From 2ae07a4679b8e5ba4d06eb1db2e8a39791bab34e Mon Sep 17 00:00:00 2001 From: Sergiusz Bazanski Date: Tue, 17 Mar 2020 00:00:50 +0100 Subject: [PATCH] bump winit, vulkano, ... --- engine/src/render/mod.rs | 25 +- engine/src/render/vulkan/data.rs | 3 +- engine/src/render/vulkan/mod.rs | 17 +- engine/src/render/vulkan/pipeline.rs | 5 +- engine/src/render/vulkan/swapchain_binding.rs | 50 +- third_party/cargo/BUILD | 6 +- third_party/cargo/Cargo.lock | 571 +- third_party/cargo/Cargo.toml | 12 +- .../arrayvec-0.4.12/.cargo-checksum.json | 1 - .../cargo/vendor/arrayvec-0.4.12/Cargo.toml | 62 - .../cargo/vendor/arrayvec-0.4.12/README.rst | 224 - .../arrayvec-0.4.12/benches/arraystring.rs | 90 - .../vendor/arrayvec-0.4.12/benches/extend.rs | 43 - .../cargo/vendor/arrayvec-0.4.12/build.rs | 90 - .../cargo/vendor/arrayvec-0.4.12/custom.css | 25 - .../cargo/vendor/arrayvec-0.4.12/src/array.rs | 137 - .../arrayvec-0.4.12/src/array_string.rs | 516 - .../cargo/vendor/arrayvec-0.4.12/src/char.rs | 54 - .../vendor/arrayvec-0.4.12/src/errors.rs | 53 - .../cargo/vendor/arrayvec-0.4.12/src/lib.rs | 1084 -- .../arrayvec-0.4.12/src/maybe_uninit.rs | 46 - .../src/maybe_uninit_nodrop.rs | 41 - .../src/maybe_uninit_stable.rs | 40 - .../cargo/vendor/arrayvec-0.4.12/src/range.rs | 42 - .../vendor/arrayvec-0.4.12/tests/serde.rs | 79 - .../vendor/arrayvec-0.4.12/tests/tests.rs | 517 - .../backtrace-0.3.45/.cargo-checksum.json | 1 - .../cargo/vendor/backtrace-0.3.45/BUILD | 61 - .../cargo/vendor/backtrace-0.3.45/Cargo.lock | 314 - .../cargo/vendor/backtrace-0.3.45/Cargo.toml | 132 - .../cargo/vendor/backtrace-0.3.45/README.md | 81 - .../backtrace-0.3.45/benches/benchmarks.rs | 94 - .../vendor/backtrace-0.3.45/ci/android-ndk.sh | 23 - .../vendor/backtrace-0.3.45/ci/android-sdk.sh | 74 - .../docker/aarch64-linux-android/Dockerfile | 18 - .../aarch64-unknown-linux-gnu/Dockerfile | 11 - .../docker/arm-linux-androideabi/Dockerfile | 37 - .../arm-unknown-linux-gnueabihf/Dockerfile | 10 - .../docker/armv7-linux-androideabi/Dockerfile | 18 - .../armv7-unknown-linux-gnueabihf/Dockerfile | 10 - .../docker/i586-unknown-linux-gnu/Dockerfile | 5 - .../ci/docker/i686-linux-android/Dockerfile | 18 - .../docker/i686-unknown-linux-gnu/Dockerfile | 5 - .../powerpc64-unknown-linux-gnu/Dockerfile | 16 - .../ci/docker/x86_64-linux-android/Dockerfile | 18 - .../docker/x86_64-pc-windows-gnu/Dockerfile | 10 - .../x86_64-unknown-linux-gnu/Dockerfile | 5 - .../x86_64-unknown-linux-musl/Dockerfile | 6 - .../vendor/backtrace-0.3.45/ci/run-docker.sh | 32 - .../cargo/vendor/backtrace-0.3.45/ci/run.sh | 5 - .../backtrace-0.3.45/ci/runtest-android.rs | 50 - .../backtrace-0.3.45/examples/backtrace.rs | 7 - .../vendor/backtrace-0.3.45/examples/raw.rs | 54 - .../backtrace-0.3.45/src/backtrace/dbghelp.rs | 233 - .../src/backtrace/libunwind.rs | 231 - .../backtrace-0.3.45/src/backtrace/mod.rs | 152 - .../backtrace-0.3.45/src/backtrace/noop.rs | 20 - .../src/backtrace/unix_backtrace.rs | 61 - .../vendor/backtrace-0.3.45/src/capture.rs | 479 - .../vendor/backtrace-0.3.45/src/dbghelp.rs | 370 - .../cargo/vendor/backtrace-0.3.45/src/lib.rs | 159 - .../vendor/backtrace-0.3.45/src/print.rs | 267 - .../backtrace-0.3.45/src/print/fuchsia.rs | 432 - .../src/symbolize/coresymbolication.rs | 277 - .../backtrace-0.3.45/src/symbolize/dbghelp.rs | 226 - .../backtrace-0.3.45/src/symbolize/dladdr.rs | 112 - .../src/symbolize/dladdr_resolve.rs | 50 - .../backtrace-0.3.45/src/symbolize/gimli.rs | 676 - .../src/symbolize/libbacktrace.rs | 489 - .../backtrace-0.3.45/src/symbolize/mod.rs | 514 - .../backtrace-0.3.45/src/symbolize/noop.rs | 37 - .../vendor/backtrace-0.3.45/src/types.rs | 83 - .../vendor/backtrace-0.3.45/src/windows.rs | 637 - .../tests/accuracy/auxiliary.rs | 16 - .../backtrace-0.3.45/tests/accuracy/main.rs | 92 - .../tests/concurrent-panics.rs | 72 - .../backtrace-0.3.45/tests/long_fn_name.rs | 50 - .../tests/skip_inner_frames.rs | 49 - .../vendor/backtrace-0.3.45/tests/smoke.rs | 250 - .../backtrace-sys-0.1.34/.cargo-checksum.json | 1 - .../vendor/backtrace-sys-0.1.34/Cargo.toml | 41 - .../vendor/backtrace-sys-0.1.34/build.rs | 166 - .../backtrace-sys-0.1.34/src/android-api.c | 4 - .../vendor/backtrace-sys-0.1.34/src/lib.rs | 58 - .../src/libbacktrace/LICENSE | 29 - .../src/libbacktrace/Makefile.am | 206 - .../src/libbacktrace/Makefile.in | 1021 -- .../libbacktrace/Mark.Twain-Tom.Sawyer.txt | 8465 --------- .../src/libbacktrace/README.md | 33 - .../src/libbacktrace/acinclude.m4 | 72 - .../src/libbacktrace/aclocal.m4 | 767 - .../src/libbacktrace/alloc.c | 156 - .../src/libbacktrace/atomic.c | 113 - .../src/libbacktrace/backtrace-supported.h.in | 66 - .../src/libbacktrace/backtrace.c | 129 - .../src/libbacktrace/backtrace.h | 182 - .../src/libbacktrace/btest.c | 500 - .../src/libbacktrace/config.guess | 1530 -- .../src/libbacktrace/config.h.in | 149 - .../src/libbacktrace/config.sub | 1794 -- .../src/libbacktrace/config/libtool.m4 | 7309 -------- .../src/libbacktrace/config/ltoptions.m4 | 368 - .../src/libbacktrace/config/ltsugar.m4 | 123 - .../src/libbacktrace/config/ltversion.m4 | 23 - .../src/libbacktrace/config/lt~obsolete.m4 | 92 - .../src/libbacktrace/configure | 14361 ---------------- .../src/libbacktrace/configure.ac | 512 - .../src/libbacktrace/dwarf.c | 3126 ---- .../src/libbacktrace/edtest.c | 121 - .../src/libbacktrace/edtest2.c | 43 - .../src/libbacktrace/elf.c | 3340 ---- .../src/libbacktrace/fileline.c | 201 - .../src/libbacktrace/filenames.h | 49 - .../src/libbacktrace/filetype.awk | 11 - .../src/libbacktrace/install-sh | 527 - .../src/libbacktrace/internal.h | 304 - .../src/libbacktrace/ltmain.sh | 7874 --------- .../src/libbacktrace/macho.c | 1418 -- .../src/libbacktrace/missing | 331 - .../src/libbacktrace/mmap.c | 325 - .../src/libbacktrace/mmapio.c | 100 - .../src/libbacktrace/move-if-change | 83 - .../src/libbacktrace/nounwind.c | 66 - .../src/libbacktrace/pecoff.c | 943 - .../src/libbacktrace/posix.c | 100 - .../src/libbacktrace/print.c | 92 - .../src/libbacktrace/read.c | 96 - .../src/libbacktrace/simple.c | 108 - .../src/libbacktrace/sort.c | 108 - .../src/libbacktrace/state.c | 72 - .../src/libbacktrace/stest.c | 137 - .../src/libbacktrace/testlib.c | 234 - .../src/libbacktrace/testlib.h | 110 - .../src/libbacktrace/ttest.c | 161 - .../src/libbacktrace/unknown.c | 65 - .../src/libbacktrace/xcoff.c | 1642 -- .../src/libbacktrace/ztest.c | 537 - .../vendor/calloop-0.4.4/.cargo-checksum.json | 1 + third_party/cargo/vendor/calloop-0.4.4/BUILD | 46 + .../cargo/vendor/calloop-0.4.4/CHANGELOG.md | 69 + .../cargo/vendor/calloop-0.4.4/Cargo.toml | 40 + .../LICENSE-MIT => calloop-0.4.4/LICENSE.txt} | 3 +- .../cargo/vendor/calloop-0.4.4/README.md | 86 + .../cargo/vendor/calloop-0.4.4/README.tpl | 9 + .../cargo/vendor/calloop-0.4.4/doc_index.html | 6 + .../cargo/vendor/calloop-0.4.4/src/lib.rs | 92 + .../cargo/vendor/calloop-0.4.4/src/list.rs | 61 + .../vendor/calloop-0.4.4/src/loop_logic.rs | 335 + .../calloop-0.4.4/src/sources/channel.rs | 183 + .../calloop-0.4.4/src/sources/generic.rs | 301 + .../vendor/calloop-0.4.4/src/sources/mod.rs | 123 + .../calloop-0.4.4/src/sources/signals.rs | 217 + .../vendor/calloop-0.4.4/src/sources/timer.rs | 311 + .../vendor/calloop-0.4.4/tests/signals.rs | 134 + .../vendor/cocoa-0.18.5/.cargo-checksum.json | 1 - .../vendor/cocoa-0.19.1/.cargo-checksum.json | 1 + .../{cocoa-0.18.5 => cocoa-0.19.1}/BUILD | 3 +- .../{cocoa-0.18.5 => cocoa-0.19.1}/COPYRIGHT | 0 .../cargo/vendor/cocoa-0.19.1/Cargo.lock | 95 + .../{cocoa-0.18.5 => cocoa-0.19.1}/Cargo.toml | 4 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../{cocoa-0.18.5 => cocoa-0.19.1}/README.md | 2 +- .../vendor/cocoa-0.19.1/examples/color.rs | 120 + .../examples/fullscreen.rs | 2 +- .../examples/hello_world.rs | 0 .../examples/tab_view.rs | 0 .../src/appkit.rs | 344 +- .../src/base.rs | 0 .../src/foundation.rs | 405 +- .../{cocoa-0.18.5 => cocoa-0.19.1}/src/lib.rs | 2 + .../cargo/vendor/cocoa-0.19.1/src/macros.rs | 79 + .../src/quartzcore.rs | 0 .../tests/foundation.rs | 34 +- .../vendor/cocoa-0.20.0/.cargo-checksum.json | 1 + .../BUILD | 21 +- .../cargo/vendor/cocoa-0.20.0/COPYRIGHT | 5 + .../cargo/vendor/cocoa-0.20.0/Cargo.lock | 95 + .../Cargo.toml | 45 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 2 +- .../cargo/vendor/cocoa-0.20.0/README.md | 6 + .../vendor/cocoa-0.20.0/examples/color.rs | 120 + .../cocoa-0.20.0/examples/fullscreen.rs | 97 + .../cocoa-0.20.0/examples/hello_world.rs | 53 + .../vendor/cocoa-0.20.0/examples/tab_view.rs | 87 + .../cargo/vendor/cocoa-0.20.0/src/appkit.rs | 4186 +++++ .../cargo/vendor/cocoa-0.20.0/src/base.rs | 28 + .../vendor/cocoa-0.20.0/src/foundation.rs | 1318 ++ .../cargo/vendor/cocoa-0.20.0/src/lib.rs | 32 + .../cargo/vendor/cocoa-0.20.0/src/macros.rs | 79 + .../vendor/cocoa-0.20.0/src/quartzcore.rs | 1859 ++ .../vendor/cocoa-0.20.0/tests/foundation.rs | 195 + .../.cargo-checksum.json | 1 + .../cargo/vendor/core-foundation-0.7.0/BUILD | 45 + .../vendor/core-foundation-0.7.0/Cargo.toml | 41 + .../LICENSE-APACHE | 0 .../vendor/core-foundation-0.7.0/LICENSE-MIT | 25 + .../vendor/core-foundation-0.7.0/src/array.rs | 286 + .../src/attributed_string.rs | 85 + .../vendor/core-foundation-0.7.0/src/base.rs | 450 + .../core-foundation-0.7.0/src/boolean.rs | 70 + .../core-foundation-0.7.0/src/bundle.rs | 152 + .../core-foundation-0.7.0/src/characterset.rs | 21 + .../vendor/core-foundation-0.7.0/src/data.rs | 63 + .../vendor/core-foundation-0.7.0/src/date.rs | 130 + .../core-foundation-0.7.0/src/dictionary.rs | 409 + .../vendor/core-foundation-0.7.0/src/error.rs | 71 + .../src/filedescriptor.rs | 210 + .../vendor/core-foundation-0.7.0/src/lib.rs | 233 + .../core-foundation-0.7.0/src/number.rs | 120 + .../core-foundation-0.7.0/src/propertylist.rs | 325 + .../core-foundation-0.7.0/src/runloop.rs | 198 + .../vendor/core-foundation-0.7.0/src/set.rs | 44 + .../core-foundation-0.7.0/src/string.rs | 150 + .../core-foundation-0.7.0/src/timezone.rs | 95 + .../vendor/core-foundation-0.7.0/src/url.rs | 156 + .../vendor/core-foundation-0.7.0/src/uuid.rs | 118 + .../tests/use_macro_outside_crate.rs | 28 + .../.cargo-checksum.json | 1 + .../BUILD | 3 +- .../core-foundation-sys-0.7.0/Cargo.toml | 27 + .../LICENSE-APACHE | 0 .../core-foundation-sys-0.7.0/LICENSE-MIT | 25 + .../vendor/core-foundation-sys-0.7.0/build.rs | 14 + .../core-foundation-sys-0.7.0/src/array.rs | 55 + .../src/attributed_string.rs | 56 + .../core-foundation-sys-0.7.0/src/base.rs | 154 + .../core-foundation-sys-0.7.0/src/bundle.rs | 37 + .../src/characterset.rs | 58 + .../core-foundation-sys-0.7.0/src/data.rs | 32 + .../core-foundation-sys-0.7.0/src/date.rs | 34 + .../src/dictionary.rs | 91 + .../core-foundation-sys-0.7.0/src/error.rs | 32 + .../src/filedescriptor.rs | 58 + .../core-foundation-sys-0.7.0/src/lib.rs | 31 + .../src/messageport.rs | 79 + .../core-foundation-sys-0.7.0/src/number.rs | 60 + .../src/propertylist.rs | 46 + .../core-foundation-sys-0.7.0/src/runloop.rs | 164 + .../core-foundation-sys-0.7.0/src/set.rs | 58 + .../core-foundation-sys-0.7.0/src/string.rs | 319 + .../core-foundation-sys-0.7.0/src/timezone.rs | 27 + .../core-foundation-sys-0.7.0/src/url.rs | 169 + .../core-foundation-sys-0.7.0/src/uuid.rs | 49 + .../core-graphics-0.19.0/.cargo-checksum.json | 1 + .../BUILD | 13 +- .../vendor/core-graphics-0.19.0/COPYRIGHT | 5 + .../vendor/core-graphics-0.19.0/Cargo.toml | 36 + .../LICENSE-APACHE | 0 .../vendor/core-graphics-0.19.0/LICENSE-MIT | 25 + .../vendor/core-graphics-0.19.0/README.md | 3 + .../vendor/core-graphics-0.19.0/src/base.rs | 59 + .../vendor/core-graphics-0.19.0/src/color.rs | 35 + .../core-graphics-0.19.0/src/color_space.rs | 69 + .../core-graphics-0.19.0/src/context.rs | 685 + .../core-graphics-0.19.0/src/data_provider.rs | 125 + .../core-graphics-0.19.0/src/display.rs | 718 + .../vendor/core-graphics-0.19.0/src/event.rs | 669 + .../core-graphics-0.19.0/src/event_source.rs | 48 + .../vendor/core-graphics-0.19.0/src/font.rs | 156 + .../core-graphics-0.19.0/src/geometry.rs | 216 + .../vendor/core-graphics-0.19.0/src/image.rs | 165 + .../vendor/core-graphics-0.19.0/src/lib.rs | 41 + .../vendor/core-graphics-0.19.0/src/path.rs | 129 + .../core-graphics-0.19.0/src/private.rs | 116 + .../vendor/core-graphics-0.19.0/src/sys.rs | 39 + .../vendor/core-graphics-0.19.0/src/window.rs | 149 + .../core-video-sys-0.1.3/.cargo-checksum.json | 1 + .../BUILD | 23 +- .../vendor/core-video-sys-0.1.3/Cargo.toml | 51 + .../LICENSE | 6 +- .../vendor/core-video-sys-0.1.3/build.rs | 6 + .../vendor/core-video-sys-0.1.3/src/base.rs | 83 + .../vendor/core-video-sys-0.1.3/src/buffer.rs | 48 + .../core-video-sys-0.1.3/src/display_link.rs | 16 + .../core-video-sys-0.1.3/src/host_time.rs | 28 + .../core-video-sys-0.1.3/src/image_buffer.rs | 3 + .../vendor/core-video-sys-0.1.3/src/lib.rs | 91 + .../core-video-sys-0.1.3/src/metal_texture.rs | 27 + .../src/metal_texture_cache.rs | 42 + .../src/open_gl_es_texture.rs | 26 + .../src/open_gl_es_texture_cache.rs | 42 + .../core-video-sys-0.1.3/src/opengl_buffer.rs | 42 + .../src/opengl_buffer_pool.rs | 32 + .../src/opengl_texture.rs | 26 + .../src/opengl_texture_cache.rs | 42 + .../core-video-sys-0.1.3/src/pixel_buffer.rs | 219 + .../src/pixel_buffer_io_surface.rs | 33 + .../src/pixel_buffer_pool.rs | 46 + .../src/pixel_format_description.rs | 121 + .../core-video-sys-0.1.3/src/return_.rs | 32 + .../crossbeam-0.5.0/.cargo-checksum.json | 1 - .../cargo/vendor/crossbeam-0.5.0/README.md | 69 - .../vendor/crossbeam-0.5.0/src/arc_cell.rs | 109 - .../vendor/crossbeam-0.5.0/src/atomic_cell.rs | 904 - .../cargo/vendor/crossbeam-0.5.0/src/lib.rs | 131 - .../vendor/crossbeam-0.5.0/src/ms_queue.rs | 557 - .../vendor/crossbeam-0.5.0/src/seg_queue.rs | 313 - .../crossbeam-0.5.0/src/sharded_lock.rs | 217 - .../crossbeam-0.5.0/src/treiber_stack.rs | 140 - .../vendor/crossbeam-0.5.0/src/wait_group.rs | 144 - .../crossbeam-0.5.0/tests/atomic_cell.rs | 208 - .../crossbeam-0.5.0/tests/wait_group.rs | 66 - .../crossbeam-0.7.3/.cargo-checksum.json | 1 + .../BUILD | 19 +- .../CHANGELOG.md | 32 + .../Cargo.toml | 40 +- .../LICENSE-APACHE | 2 +- .../LICENSE-MIT | 0 .../cargo/vendor/crossbeam-0.7.3/README.md | 162 + .../cargo/vendor/crossbeam-0.7.3/src/lib.rs | 109 + .../tests/subcrates.rs | 18 +- .../.cargo-checksum.json | 1 - .../.cargo-checksum.json | 1 + .../BUILD | 5 +- .../CHANGELOG.md | 14 + .../vendor/crossbeam-channel-0.4.2/Cargo.lock | 264 + .../Cargo.toml | 7 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../LICENSE-THIRD-PARTY | 0 .../README.md | 8 +- .../benches/crossbeam.rs | 0 .../examples/fibonacci.rs | 0 .../examples/matching.rs | 0 .../examples/stopwatch.rs | 0 .../src/channel.rs | 0 .../src/context.rs | 0 .../src/counter.rs | 0 .../src/err.rs | 16 +- .../src/flavors/after.rs | 0 .../src/flavors/array.rs | 15 +- .../src/flavors/list.rs | 21 +- .../src/flavors/mod.rs | 0 .../src/flavors/never.rs | 0 .../src/flavors/tick.rs | 42 +- .../src/flavors/zero.rs | 0 .../src/lib.rs | 1 + .../src/select.rs | 30 +- .../src/select_macro.rs | 10 +- .../src/utils.rs | 0 .../src/waker.rs | 0 .../tests/after.rs | 0 .../tests/array.rs | 2 +- .../tests/golang.rs | 2 +- .../tests/iter.rs | 0 .../tests/list.rs | 2 +- .../tests/mpsc.rs | 0 .../tests/never.rs | 0 .../tests/ready.rs | 2 +- .../tests/same_channel.rs | 0 .../tests/select.rs | 2 +- .../tests/select_macro.rs | 2 +- .../tests/thread_locals.rs | 0 .../tests/tick.rs | 0 .../tests/zero.rs | 2 +- .../.cargo-checksum.json | 1 - .../vendor/crossbeam-deque-0.6.3/src/lib.rs | 879 - .../crossbeam-deque-0.6.3/tests/fifo.rs | 371 - .../crossbeam-deque-0.6.3/tests/lifo.rs | 371 - .../.cargo-checksum.json | 1 + .../BUILD | 9 +- .../CHANGELOG.md | 24 + .../Cargo.toml | 13 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../README.md | 11 +- .../vendor/crossbeam-deque-0.7.3/src/lib.rs | 2016 +++ .../crossbeam-deque-0.7.3/tests/fifo.rs | 342 + .../crossbeam-deque-0.7.3/tests/injector.rs | 353 + .../crossbeam-deque-0.7.3/tests/lifo.rs | 342 + .../crossbeam-deque-0.7.3/tests/steal.rs | 214 + .../.cargo-checksum.json | 1 - .../cargo/vendor/crossbeam-epoch-0.6.1/BUILD | 55 - .../vendor/crossbeam-epoch-0.6.1/CHANGELOG.md | 66 - .../vendor/crossbeam-epoch-0.6.1/Cargo.toml | 53 - .../vendor/crossbeam-epoch-0.6.1/README.md | 39 - .../crossbeam-epoch-0.6.1/benches/defer.rs | 69 - .../crossbeam-epoch-0.6.1/benches/flush.rs | 51 - .../crossbeam-epoch-0.6.1/benches/pin.rs | 31 - .../examples/sanitize.rs | 68 - .../crossbeam-epoch-0.6.1/src/atomic.rs | 1124 -- .../crossbeam-epoch-0.6.1/src/collector.rs | 433 - .../crossbeam-epoch-0.6.1/src/deferred.rs | 134 - .../vendor/crossbeam-epoch-0.6.1/src/guard.rs | 547 - .../crossbeam-epoch-0.6.1/src/internal.rs | 546 - .../vendor/crossbeam-epoch-0.6.1/src/lib.rs | 106 - .../crossbeam-epoch-0.6.1/src/sync/list.rs | 477 - .../crossbeam-epoch-0.6.1/src/sync/queue.rs | 434 - .../.cargo-checksum.json | 1 - .../crossbeam-epoch-0.7.2/src/default.rs | 75 - .../vendor/crossbeam-epoch-0.7.2/src/epoch.rs | 114 - .../crossbeam-epoch-0.7.2/src/sync/mod.rs | 4 - .../.cargo-checksum.json | 1 + .../BUILD | 7 +- .../CHANGELOG.md | 19 + .../vendor/crossbeam-epoch-0.8.2/Cargo.lock | 261 + .../Cargo.toml | 15 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 4 +- .../README.md | 8 +- .../benches/defer.rs | 0 .../benches/flush.rs | 0 .../benches/pin.rs | 0 .../vendor/crossbeam-epoch-0.8.2/build.rs | 8 + .../examples/sanitize.rs | 0 .../examples/treiber_stack.rs | 0 .../src/atomic.rs | 4 +- .../src/collector.rs | 0 .../src/default.rs | 3 +- .../src/deferred.rs | 14 +- .../src/epoch.rs | 0 .../src/guard.rs | 2 + .../src/internal.rs | 125 +- .../src/lib.rs | 11 +- .../src/sync/list.rs | 39 +- .../src/sync/mod.rs | 0 .../src/sync/queue.rs | 33 +- .../.cargo-checksum.json | 1 + .../cargo/vendor/crossbeam-queue-0.2.1/BUILD | 49 + .../vendor/crossbeam-queue-0.2.1/CHANGELOG.md | 20 + .../vendor/crossbeam-queue-0.2.1/Cargo.toml | 37 + .../LICENSE-APACHE | 0 .../LICENSE-MIT | 4 +- .../crossbeam-queue-0.2.1/LICENSE-THIRD-PARTY | 31 + .../vendor/crossbeam-queue-0.2.1/README.md | 67 + .../crossbeam-queue-0.2.1/src/array_queue.rs | 433 + .../vendor/crossbeam-queue-0.2.1/src/err.rs | 47 + .../vendor/crossbeam-queue-0.2.1/src/lib.rs | 40 + .../crossbeam-queue-0.2.1/src/seg_queue.rs | 483 + .../tests/array_queue.rs | 254 + .../crossbeam-queue-0.2.1/tests/seg_queue.rs | 167 + .../.cargo-checksum.json | 1 - .../crossbeam-utils-0.6.6/src/atomic/mod.rs | 7 - .../.cargo-checksum.json | 1 + .../BUILD | 3 +- .../CHANGELOG.md | 18 +- .../Cargo.toml | 4 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 4 +- .../README.md | 8 +- .../benches/atomic_cell.rs | 0 .../vendor/crossbeam-utils-0.7.2/build.rs | 14 + .../src/atomic/atomic_cell.rs | 182 +- .../src/atomic/consume.rs | 0 .../crossbeam-utils-0.7.2/src/atomic/mod.rs | 25 + .../src/atomic/seq_lock.rs | 88 + .../src/atomic/seq_lock_wide.rs | 134 + .../src/backoff.rs | 0 .../src/cache_padded.rs | 0 .../src/lib.rs | 5 +- .../src/sync/mod.rs | 2 +- .../src/sync/parker.rs | 16 +- .../src/sync/sharded_lock.rs | 32 +- .../src/sync/wait_group.rs | 4 +- .../src/thread.rs | 4 +- .../tests/atomic_cell.rs | 26 +- .../tests/cache_padded.rs | 0 .../tests/parker.rs | 0 .../tests/sharded_lock.rs | 0 .../tests/thread.rs | 4 +- .../tests/wait_group.rs | 0 .../dispatch-0.2.0/.cargo-checksum.json | 1 + third_party/cargo/vendor/dispatch-0.2.0/BUILD | 43 + .../cargo/vendor/dispatch-0.2.0/Cargo.lock | 6 + .../Cargo.toml | 18 +- .../cargo/vendor/dispatch-0.2.0/README.md | 44 + .../vendor/dispatch-0.2.0/examples/main.rs | 51 + .../cargo/vendor/dispatch-0.2.0/src/ffi.rs | 173 + .../cargo/vendor/dispatch-0.2.0/src/group.rs | 180 + .../cargo/vendor/dispatch-0.2.0/src/lib.rs | 133 + .../cargo/vendor/dispatch-0.2.0/src/once.rs | 60 + .../cargo/vendor/dispatch-0.2.0/src/queue.rs | 506 + .../cargo/vendor/dispatch-0.2.0/src/sem.rs | 138 + .../fuchsia-zircon-0.3.3/.cargo-checksum.json | 1 + .../cargo/vendor/fuchsia-zircon-0.3.3/BUILD | 44 + .../vendor/fuchsia-zircon-0.3.3/BUILD.gn | 14 + .../Cargo.toml | 20 +- .../cargo/vendor/fuchsia-zircon-0.3.3/LICENSE | 27 + .../vendor/fuchsia-zircon-0.3.3/README.md | 12 + .../fuchsia-zircon-0.3.3/examples/BUILD.gn | 17 + .../fuchsia-zircon-0.3.3/src/channel.rs | 418 + .../vendor/fuchsia-zircon-0.3.3/src/cprng.rs | 68 + .../vendor/fuchsia-zircon-0.3.3/src/event.rs | 32 + .../fuchsia-zircon-0.3.3/src/eventpair.rs | 65 + .../vendor/fuchsia-zircon-0.3.3/src/fifo.rs | 98 + .../vendor/fuchsia-zircon-0.3.3/src/handle.rs | 243 + .../vendor/fuchsia-zircon-0.3.3/src/job.rs | 14 + .../vendor/fuchsia-zircon-0.3.3/src/lib.rs | 365 + .../vendor/fuchsia-zircon-0.3.3/src/port.rs | 344 + .../fuchsia-zircon-0.3.3/src/process.rs | 14 + .../vendor/fuchsia-zircon-0.3.3/src/rights.rs | 28 + .../fuchsia-zircon-0.3.3/src/signals.rs | 105 + .../vendor/fuchsia-zircon-0.3.3/src/socket.rs | 126 + .../vendor/fuchsia-zircon-0.3.3/src/status.rs | 162 + .../vendor/fuchsia-zircon-0.3.3/src/thread.rs | 14 + .../vendor/fuchsia-zircon-0.3.3/src/time.rs | 346 + .../vendor/fuchsia-zircon-0.3.3/src/vmar.rs | 18 + .../vendor/fuchsia-zircon-0.3.3/src/vmo.rs | 256 + .../fuchsia-zircon-0.3.3/tools/gen_status.py | 49 + .../.cargo-checksum.json | 1 + .../BUILD | 6 +- .../vendor/fuchsia-zircon-sys-0.3.3/BUILD.gn | 9 + .../fuchsia-zircon-sys-0.3.3/Cargo.toml | 19 + .../examples/hello.rs | 14 + .../src/definitions.rs | 903 + .../fuchsia-zircon-sys-0.3.3/src/lib.rs | 474 + .../vendor/instant-0.1.2/.cargo-checksum.json | 1 + .../cargo/vendor/instant-0.1.2/AUTHORS | 2 + third_party/cargo/vendor/instant-0.1.2/BUILD | 44 + .../cargo/vendor/instant-0.1.2/Cargo.toml | 58 + .../cargo/vendor/instant-0.1.2/LICENSE | 27 + .../cargo/vendor/instant-0.1.2/README.md | 101 + .../cargo/vendor/instant-0.1.2/src/lib.rs | 42 + .../cargo/vendor/instant-0.1.2/src/native.rs | 7 + .../cargo/vendor/instant-0.1.2/src/wasm.rs | 103 + .../cargo/vendor/instant-0.1.2/tests/wasm.rs | 21 + .../vendor/iovec-0.1.4/.cargo-checksum.json | 1 + .../{num_cpus-1.12.0 => iovec-0.1.4}/BUILD | 5 +- .../cargo/vendor/iovec-0.1.4/CHANGELOG.md | 19 + .../Cargo.toml | 29 +- .../LICENSE-APACHE | 2 +- .../LICENSE-MIT | 2 + .../cargo/vendor/iovec-0.1.4/README.md | 35 + .../cargo/vendor/iovec-0.1.4/appveyor.yml | 16 + .../cargo/vendor/iovec-0.1.4/src/lib.rs | 161 + .../cargo/vendor/iovec-0.1.4/src/sys/mod.rs | 26 + .../cargo/vendor/iovec-0.1.4/src/sys/unix.rs | 52 + .../vendor/iovec-0.1.4/src/sys/unknown.rs | 57 + .../vendor/iovec-0.1.4/src/sys/windows.rs | 68 + .../cargo/vendor/iovec-0.1.4/src/unix.rs | 68 + .../cargo/vendor/iovec-0.1.4/src/windows.rs | 0 .../kernel32-sys-0.2.2/.cargo-checksum.json | 1 + .../BUILD | 11 +- .../vendor/kernel32-sys-0.2.2/Cargo.toml | 17 + .../cargo/vendor/kernel32-sys-0.2.2/README.md | 13 + .../cargo/vendor/kernel32-sys-0.2.2/build.rs | 6 + .../vendor/kernel32-sys-0.2.2/src/lib.rs | 2754 +++ .../lazycell-1.2.1/.cargo-checksum.json | 1 + .../{nodrop-0.1.14 => lazycell-1.2.1}/BUILD | 4 +- .../cargo/vendor/lazycell-1.2.1/CHANGELOG.md | 178 + .../Cargo.toml | 23 +- .../LICENSE-APACHE | 0 .../cargo/vendor/lazycell-1.2.1/LICENSE-MIT | 26 + .../cargo/vendor/lazycell-1.2.1/README.md | 72 + .../cargo/vendor/lazycell-1.2.1/src/lib.rs | 649 + .../lock_api-0.1.5/.cargo-checksum.json | 1 - .../lock_api-0.3.3/.cargo-checksum.json | 1 + third_party/cargo/vendor/lock_api-0.3.3/BUILD | 43 + .../Cargo.toml | 12 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../src/lib.rs | 14 +- .../src/mutex.rs | 136 +- .../src/remutex.rs | 180 +- .../src/rwlock.rs | 272 +- .../memoffset-0.2.1/.cargo-checksum.json | 1 - .../cargo/vendor/memoffset-0.2.1/README.md | 47 - .../cargo/vendor/memoffset-0.2.1/src/lib.rs | 70 - .../vendor/memoffset-0.2.1/src/offset_of.rs | 119 - .../vendor/memoffset-0.2.1/src/span_of.rs | 274 - .../vendor/metal-0.13.1/.cargo-checksum.json | 1 - .../vendor/metal-0.13.1/src/constants.rs | 137 - .../vendor/metal-0.13.1/src/pipeline/mod.rs | 14 - .../vendor/metal-0.17.1/.cargo-checksum.json | 1 + .../{metal-0.13.1 => metal-0.17.1}/BUILD | 9 +- .../cargo/vendor/metal-0.17.1/Cargo.lock | 756 + .../{metal-0.13.1 => metal-0.17.1}/Cargo.toml | 22 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../{metal-0.13.1 => metal-0.17.1}/README.md | 1 + .../{metal-0.13.1 => metal-0.17.1}/bors.toml | 0 .../examples/argument-buffer/main.rs | 12 +- .../examples/bind/main.rs | 13 +- .../examples/caps/main.rs | 14 +- .../compute/compute-argument-buffer.metal | 0 .../compute/compute-argument-buffer.rs | 36 +- .../examples/compute/default.metallib | Bin .../examples/compute/embedded-lib.rs | 9 +- .../examples/compute/main.rs | 39 +- .../examples/compute/shaders.metal | 0 .../examples/library/main.rs | 4 +- .../examples/reflection/main.rs | 32 +- .../examples/window/default.metallib | Bin .../examples/window/main.rs | 105 +- .../examples/window/shaders.metal | 0 .../src/argument.rs | 149 +- .../src/buffer.rs | 36 +- .../src/capturemanager.rs | 24 +- .../src/commandbuffer.rs | 73 +- .../src/commandqueue.rs | 22 +- .../vendor/metal-0.17.1/src/constants.rs | 137 + .../src/depthstencil.rs | 81 +- .../src/device.rs | 508 +- .../src/drawable.rs | 5 +- .../src/encoder.rs | 359 +- .../src/heap.rs | 50 +- .../{metal-0.13.1 => metal-0.17.1}/src/lib.rs | 239 +- .../src/library.rs | 112 +- .../src/pipeline/compute.rs | 205 +- .../vendor/metal-0.17.1/src/pipeline/mod.rs | 50 + .../src/pipeline/render.rs | 230 +- .../src/renderpass.rs | 188 +- .../src/resource.rs | 23 +- .../src/sampler.rs | 63 +- .../src/texture.rs | 218 +- .../src/types.rs | 14 +- .../src/vertexdescriptor.rs | 75 +- .../vendor/mio-0.6.21/.cargo-checksum.json | 1 + third_party/cargo/vendor/mio-0.6.21/BUILD | 52 + .../cargo/vendor/mio-0.6.21/CHANGELOG.md | 208 + .../cargo/vendor/mio-0.6.21/Cargo.toml | 71 + third_party/cargo/vendor/mio-0.6.21/LICENSE | 19 + third_party/cargo/vendor/mio-0.6.21/README.md | 90 + .../vendor/mio-0.6.21/azure-pipelines.yml | 50 + .../vendor/mio-0.6.21/benches/bench_poll.rs | 53 + .../mio-0.6.21/ci/azure-cross-compile.yml | 56 + .../mio-0.6.21/ci/azure-deploy-docs.yml | 39 + .../mio-0.6.21/ci/azure-install-rust.yml | 32 + .../mio-0.6.21/ci/azure-test-stable.yml | 45 + .../cargo/vendor/mio-0.6.21/src/channel.rs | 390 + .../mio-0.6.21/src/deprecated/event_loop.rs | 346 + .../mio-0.6.21/src/deprecated/handler.rs | 37 + .../vendor/mio-0.6.21/src/deprecated/io.rs | 28 + .../vendor/mio-0.6.21/src/deprecated/mod.rs | 36 + .../mio-0.6.21/src/deprecated/notify.rs | 63 + .../vendor/mio-0.6.21/src/deprecated/unix.rs | 420 + .../cargo/vendor/mio-0.6.21/src/event_imp.rs | 1164 ++ third_party/cargo/vendor/mio-0.6.21/src/io.rs | 35 + .../cargo/vendor/mio-0.6.21/src/lazycell.rs | 554 + .../cargo/vendor/mio-0.6.21/src/lib.rs | 311 + .../cargo/vendor/mio-0.6.21/src/net/mod.rs | 14 + .../cargo/vendor/mio-0.6.21/src/net/tcp.rs | 737 + .../cargo/vendor/mio-0.6.21/src/net/udp.rs | 645 + .../cargo/vendor/mio-0.6.21/src/poll.rs | 2783 +++ .../mio-0.6.21/src/sys/fuchsia/awakener.rs | 73 + .../mio-0.6.21/src/sys/fuchsia/eventedfd.rs | 263 + .../mio-0.6.21/src/sys/fuchsia/handles.rs | 78 + .../vendor/mio-0.6.21/src/sys/fuchsia/mod.rs | 177 + .../vendor/mio-0.6.21/src/sys/fuchsia/net.rs | 444 + .../mio-0.6.21/src/sys/fuchsia/ready.rs | 181 + .../mio-0.6.21/src/sys/fuchsia/selector.rs | 353 + .../cargo/vendor/mio-0.6.21/src/sys/mod.rs | 56 + .../mio-0.6.21/src/sys/unix/awakener.rs | 74 + .../vendor/mio-0.6.21/src/sys/unix/dlsym.rs | 47 + .../vendor/mio-0.6.21/src/sys/unix/epoll.rs | 260 + .../mio-0.6.21/src/sys/unix/eventedfd.rs | 107 + .../vendor/mio-0.6.21/src/sys/unix/io.rs | 107 + .../vendor/mio-0.6.21/src/sys/unix/kqueue.rs | 360 + .../vendor/mio-0.6.21/src/sys/unix/mod.rs | 95 + .../vendor/mio-0.6.21/src/sys/unix/ready.rs | 499 + .../vendor/mio-0.6.21/src/sys/unix/tcp.rs | 286 + .../vendor/mio-0.6.21/src/sys/unix/udp.rs | 181 + .../vendor/mio-0.6.21/src/sys/unix/uds.rs | 262 + .../vendor/mio-0.6.21/src/sys/unix/uio.rs | 44 + .../mio-0.6.21/src/sys/windows/awakener.rs | 66 + .../mio-0.6.21/src/sys/windows/buffer_pool.rs | 20 + .../src/sys/windows/from_raw_arc.rs | 116 + .../vendor/mio-0.6.21/src/sys/windows/mod.rs | 187 + .../mio-0.6.21/src/sys/windows/selector.rs | 534 + .../vendor/mio-0.6.21/src/sys/windows/tcp.rs | 851 + .../vendor/mio-0.6.21/src/sys/windows/udp.rs | 413 + .../cargo/vendor/mio-0.6.21/src/timer.rs | 516 + .../cargo/vendor/mio-0.6.21/src/token.rs | 153 + .../cargo/vendor/mio-0.6.21/src/udp.rs | 326 + .../cargo/vendor/mio-0.6.21/test/benchmark.rs | 80 + .../cargo/vendor/mio-0.6.21/test/mod.rs | 214 + .../vendor/mio-0.6.21/test/test_battery.rs | 269 + .../mio-0.6.21/test/test_broken_pipe.rs | 28 + .../mio-0.6.21/test/test_close_on_drop.rs | 119 + .../mio-0.6.21/test/test_custom_evented.rs | 394 + .../mio-0.6.21/test/test_double_register.rs | 17 + .../mio-0.6.21/test/test_echo_server.rs | 303 + .../mio-0.6.21/test/test_fuchsia_handles.rs | 30 + .../mio-0.6.21/test/test_local_addr_ready.rs | 67 + .../vendor/mio-0.6.21/test/test_multicast.rs | 107 + .../vendor/mio-0.6.21/test/test_notify.rs | 192 + .../vendor/mio-0.6.21/test/test_oneshot.rs | 64 + .../cargo/vendor/mio-0.6.21/test/test_poll.rs | 18 + .../mio-0.6.21/test/test_poll_channel.rs | 285 + .../test/test_register_deregister.rs | 123 + .../test_register_multiple_event_loops.rs | 63 + .../test/test_reregister_without_poll.rs | 28 + .../vendor/mio-0.6.21/test/test_smoke.rs | 23 + .../mio-0.6.21/test/test_subprocess_pipe.rs | 249 + .../cargo/vendor/mio-0.6.21/test/test_tcp.rs | 660 + .../vendor/mio-0.6.21/test/test_tcp_level.rs | 142 + .../mio-0.6.21/test/test_tcp_shutdown.rs | 248 + .../cargo/vendor/mio-0.6.21/test/test_tick.rs | 64 + .../vendor/mio-0.6.21/test/test_udp_level.rs | 52 + .../vendor/mio-0.6.21/test/test_udp_socket.rs | 252 + .../mio-0.6.21/test/test_uds_shutdown.rs | 300 + .../mio-0.6.21/test/test_unix_echo_server.rs | 292 + .../mio-0.6.21/test/test_unix_pass_fd.rs | 306 + .../mio-0.6.21/test/test_write_then_drop.rs | 123 + .../mio-extras-2.0.6/.cargo-checksum.json | 1 + .../BUILD | 16 +- .../vendor/mio-extras-2.0.6/CHANGELOG.md | 37 + .../cargo/vendor/mio-extras-2.0.6/Cargo.toml | 40 + .../LICENSE-APACHE | 2 +- .../LICENSE-MIT | 2 +- .../cargo/vendor/mio-extras-2.0.6/README.md | 30 + .../vendor/mio-extras-2.0.6/src/channel.rs | 431 + .../cargo/vendor/mio-extras-2.0.6/src/lib.rs | 33 + .../vendor/mio-extras-2.0.6/src/timer.rs | 751 + .../cargo/vendor/mio-extras-2.0.6/test/mod.rs | 45 + .../test/test_poll_channel.rs | 362 + .../mio-extras-2.0.6/test/test_timer.rs | 308 + .../vendor/miow-0.2.1/.cargo-checksum.json | 1 + third_party/cargo/vendor/miow-0.2.1/BUILD | 46 + .../cargo/vendor/miow-0.2.1/Cargo.toml | 23 + .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 third_party/cargo/vendor/miow-0.2.1/README.md | 22 + .../cargo/vendor/miow-0.2.1/appveyor.yml | 20 + .../cargo/vendor/miow-0.2.1/src/handle.rs | 93 + .../cargo/vendor/miow-0.2.1/src/iocp.rs | 313 + .../cargo/vendor/miow-0.2.1/src/lib.rs | 57 + .../cargo/vendor/miow-0.2.1/src/net.rs | 1183 ++ .../cargo/vendor/miow-0.2.1/src/overlapped.rs | 66 + .../cargo/vendor/miow-0.2.1/src/pipe.rs | 611 + .../vendor/net2-0.2.33/.cargo-checksum.json | 1 + .../BUILD | 9 +- .../cargo/vendor/net2-0.2.33/Cargo.toml | 34 + .../LICENSE-APACHE | 0 .../{rand-0.5.6 => net2-0.2.33}/LICENSE-MIT | 0 .../cargo/vendor/net2-0.2.33/README.md | 35 + .../cargo/vendor/net2-0.2.33/appveyor.yml | 17 + .../cargo/vendor/net2-0.2.33/src/ext.rs | 1501 ++ .../cargo/vendor/net2-0.2.33/src/lib.rs | 122 + .../cargo/vendor/net2-0.2.33/src/socket.rs | 144 + .../vendor/net2-0.2.33/src/sys/redox/impls.rs | 43 + .../vendor/net2-0.2.33/src/sys/redox/mod.rs | 81 + .../vendor/net2-0.2.33/src/sys/unix/impls.rs | 44 + .../vendor/net2-0.2.33/src/sys/unix/mod.rs | 104 + .../net2-0.2.33/src/sys/windows/impls.rs | 44 + .../vendor/net2-0.2.33/src/sys/windows/mod.rs | 124 + .../cargo/vendor/net2-0.2.33/src/tcp.rs | 161 + .../cargo/vendor/net2-0.2.33/src/udp.rs | 89 + .../cargo/vendor/net2-0.2.33/src/unix.rs | 57 + .../cargo/vendor/net2-0.2.33/src/utils.rs | 51 + .../cargo/vendor/net2-0.2.33/tests/all.rs | 45 + .../vendor/nodrop-0.1.14/.cargo-checksum.json | 1 - .../cargo/vendor/nodrop-0.1.14/Cargo.toml | 36 - .../cargo/vendor/nodrop-0.1.14/LICENSE-MIT | 25 - .../cargo/vendor/nodrop-0.1.14/README.rst | 71 - .../cargo/vendor/nodrop-0.1.14/src/lib.rs | 189 - .../num_cpus-1.12.0/.cargo-checksum.json | 1 - .../cargo/vendor/num_cpus-1.12.0/CHANGELOG.md | 125 - .../vendor/num_cpus-1.12.0/CONTRIBUTING.md | 16 - .../cargo/vendor/num_cpus-1.12.0/README.md | 28 - .../vendor/num_cpus-1.12.0/examples/values.rs | 6 - .../cargo/vendor/num_cpus-1.12.0/src/lib.rs | 526 - .../.cargo-checksum.json | 1 - .../vendor/objc-foundation-0.1.1/Cargo.toml | 17 - .../examples/custom_class.rs | 77 - .../objc-foundation-0.1.1/examples/example.rs | 38 - .../vendor/objc-foundation-0.1.1/src/array.rs | 441 - .../vendor/objc-foundation-0.1.1/src/data.rs | 200 - .../objc-foundation-0.1.1/src/dictionary.rs | 230 - .../objc-foundation-0.1.1/src/enumerator.rs | 166 - .../vendor/objc-foundation-0.1.1/src/lib.rs | 33 - .../objc-foundation-0.1.1/src/macros.rs | 55 - .../objc-foundation-0.1.1/src/object.rs | 91 - .../objc-foundation-0.1.1/src/string.rs | 98 - .../vendor/objc-foundation-0.1.1/src/value.rs | 78 - .../vendor/objc_id-0.1.1/.cargo-checksum.json | 1 - .../cargo/vendor/objc_id-0.1.1/README.md | 34 - .../cargo/vendor/objc_id-0.1.1/src/id.rs | 217 - .../cargo/vendor/objc_id-0.1.1/src/lib.rs | 47 - .../owning_ref-0.4.1/.cargo-checksum.json | 1 - .../vendor/owning_ref-0.4.1/CHANGELOG.md | 8 - .../cargo/vendor/owning_ref-0.4.1/README.md | 64 - .../cargo/vendor/owning_ref-0.4.1/src/lib.rs | 2016 --- .../parking_lot-0.10.0/.cargo-checksum.json | 1 + .../BUILD | 9 +- .../vendor/parking_lot-0.10.0/CHANGELOG.md | 104 + .../Cargo.toml | 20 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../README.md | 16 +- .../vendor/parking_lot-0.10.0/appveyor.yml | 59 + .../src/condvar.rs | 433 +- .../src/deadlock.rs | 18 +- .../vendor/parking_lot-0.10.0/src/elision.rs | 116 + .../src/lib.rs | 23 +- .../src/mutex.rs | 35 +- .../src/once.rs | 82 +- .../src/raw_mutex.rs | 168 +- .../parking_lot-0.10.0/src/raw_rwlock.rs | 1137 ++ .../src/remutex.rs | 50 +- .../src/rwlock.rs | 46 +- .../src/util.rs | 12 +- .../parking_lot-0.6.4/.cargo-checksum.json | 1 - .../vendor/parking_lot-0.6.4/CHANGELOG.md | 48 - .../cargo/vendor/parking_lot-0.6.4/Cargo.toml | 35 - .../cargo/vendor/parking_lot-0.6.4/README.md | 138 - .../vendor/parking_lot-0.6.4/appveyor.yml | 29 - .../vendor/parking_lot-0.6.4/src/condvar.rs | 533 - .../vendor/parking_lot-0.6.4/src/deadlock.rs | 218 - .../vendor/parking_lot-0.6.4/src/elision.rs | 169 - .../vendor/parking_lot-0.6.4/src/mutex.rs | 298 - .../vendor/parking_lot-0.6.4/src/once.rs | 488 - .../vendor/parking_lot-0.6.4/src/raw_mutex.rs | 312 - .../parking_lot-0.6.4/src/raw_rwlock.rs | 1402 -- .../vendor/parking_lot-0.6.4/src/remutex.rs | 126 - .../vendor/parking_lot-0.6.4/src/rwlock.rs | 564 - .../vendor/parking_lot-0.6.4/src/util.rs | 32 - .../parking_lot-0.7.1/.cargo-checksum.json | 1 - .../cargo/vendor/parking_lot-0.7.1/BUILD | 46 - .../vendor/parking_lot-0.7.1/CHANGELOG.md | 59 - .../vendor/parking_lot-0.7.1/appveyor.yml | 29 - .../vendor/parking_lot-0.7.1/src/elision.rs | 177 - .../cargo/vendor/parking_lot-0.7.1/src/lib.rs | 45 - .../parking_lot-0.7.1/src/raw_rwlock.rs | 1403 -- .../vendor/parking_lot-0.7.1/src/util.rs | 44 - .../.cargo-checksum.json | 1 - .../vendor/parking_lot_core-0.3.1/LICENSE-MIT | 25 - .../vendor/parking_lot_core-0.3.1/build.rs | 8 - .../parking_lot_core-0.3.1/src/parking_lot.rs | 1391 -- .../parking_lot_core-0.3.1/src/spinwait.rs | 125 - .../src/thread_parker/generic.rs | 98 - .../src/thread_parker/linux.rs | 137 - .../src/thread_parker/windows/keyed_event.rs | 197 - .../src/thread_parker/windows/waitaddress.rs | 134 - .../.cargo-checksum.json | 1 - .../vendor/parking_lot_core-0.4.0/Cargo.toml | 49 - .../vendor/parking_lot_core-0.4.0/LICENSE-MIT | 25 - .../vendor/parking_lot_core-0.4.0/build.rs | 8 - .../vendor/parking_lot_core-0.4.0/src/lib.rs | 84 - .../src/thread_parker/generic.rs | 98 - .../src/thread_parker/unix.rs | 242 - .../src/thread_parker/windows/mod.rs | 136 - .../src/thread_parker/windows/waitaddress.rs | 134 - .../parking_lot_core-0.4.0/src/word_lock.rs | 279 - .../.cargo-checksum.json | 1 + .../BUILD | 9 +- .../Cargo.toml | 21 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../src/lib.rs | 59 +- .../src/parking_lot.rs | 1006 +- .../src/spinwait.rs | 61 +- .../src/thread_parker/cloudabi.rs | 304 + .../src/thread_parker/generic.rs | 77 + .../src/thread_parker/linux.rs | 136 +- .../src/thread_parker/mod.rs | 88 + .../src/thread_parker/redox.rs | 138 + .../src/thread_parker/sgx.rs | 94 + .../src/thread_parker/unix.rs | 134 +- .../src/thread_parker/wasm.rs | 53 + .../src/thread_parker/wasm_atomic.rs | 96 + .../src/thread_parker/windows/keyed_event.rs | 131 +- .../src/thread_parker/windows/mod.rs | 88 +- .../src/thread_parker/windows/waitaddress.rs | 149 + .../src/util.rs | 5 +- .../src/word_lock.rs | 193 +- .../.cargo-checksum.json | 1 - .../vendor/percent-encoding-1.0.1/lib.rs | 442 - .../.cargo-checksum.json | 1 + .../BUILD | 2 +- .../Cargo.toml | 5 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../vendor/percent-encoding-2.1.0/lib.rs | 442 + .../vendor/rand-0.5.6/.cargo-checksum.json | 1 - third_party/cargo/vendor/rand-0.5.6/BUILD | 57 - .../cargo/vendor/rand-0.5.6/CHANGELOG.md | 422 - .../cargo/vendor/rand-0.5.6/CONTRIBUTING.md | 93 - .../cargo/vendor/rand-0.5.6/Cargo.toml | 72 - .../cargo/vendor/rand-0.5.6/LICENSE-APACHE | 201 - third_party/cargo/vendor/rand-0.5.6/README.md | 143 - .../cargo/vendor/rand-0.5.6/UPDATING.md | 260 - .../cargo/vendor/rand-0.5.6/appveyor.yml | 39 - .../rand-0.5.6/benches/distributions.rs | 161 - .../vendor/rand-0.5.6/benches/generators.rs | 176 - .../cargo/vendor/rand-0.5.6/benches/misc.rs | 194 - .../vendor/rand-0.5.6/examples/monte-carlo.rs | 52 - .../vendor/rand-0.5.6/examples/monty-hall.rs | 117 - .../rand-0.5.6/src/distributions/bernoulli.rs | 120 - .../rand-0.5.6/src/distributions/binomial.rs | 178 - .../rand-0.5.6/src/distributions/cauchy.rs | 116 - .../src/distributions/exponential.rs | 122 - .../rand-0.5.6/src/distributions/float.rs | 206 - .../rand-0.5.6/src/distributions/gamma.rs | 360 - .../rand-0.5.6/src/distributions/integer.rs | 113 - .../rand-0.5.6/src/distributions/log_gamma.rs | 51 - .../rand-0.5.6/src/distributions/mod.rs | 784 - .../rand-0.5.6/src/distributions/normal.rs | 192 - .../rand-0.5.6/src/distributions/other.rs | 215 - .../rand-0.5.6/src/distributions/pareto.rs | 76 - .../rand-0.5.6/src/distributions/poisson.rs | 158 - .../rand-0.5.6/src/distributions/uniform.rs | 856 - .../src/distributions/ziggurat_tables.rs | 280 - .../cargo/vendor/rand-0.5.6/src/lib.rs | 1238 -- .../cargo/vendor/rand-0.5.6/src/prelude.rs | 28 - .../vendor/rand-0.5.6/src/prng/chacha.rs | 477 - .../cargo/vendor/rand-0.5.6/src/prng/hc128.rs | 464 - .../cargo/vendor/rand-0.5.6/src/prng/isaac.rs | 494 - .../vendor/rand-0.5.6/src/prng/isaac64.rs | 491 - .../vendor/rand-0.5.6/src/prng/isaac_array.rs | 137 - .../cargo/vendor/rand-0.5.6/src/prng/mod.rs | 330 - .../vendor/rand-0.5.6/src/prng/xorshift.rs | 225 - .../vendor/rand-0.5.6/src/rngs/adapter/mod.rs | 17 - .../rand-0.5.6/src/rngs/adapter/read.rs | 137 - .../rand-0.5.6/src/rngs/adapter/reseeding.rs | 260 - .../vendor/rand-0.5.6/src/rngs/entropy.rs | 296 - .../vendor/rand-0.5.6/src/rngs/jitter.rs | 887 - .../cargo/vendor/rand-0.5.6/src/rngs/mock.rs | 61 - .../cargo/vendor/rand-0.5.6/src/rngs/mod.rs | 218 - .../cargo/vendor/rand-0.5.6/src/rngs/os.rs | 1171 -- .../cargo/vendor/rand-0.5.6/src/rngs/small.rs | 101 - .../cargo/vendor/rand-0.5.6/src/rngs/std.rs | 83 - .../vendor/rand-0.5.6/src/rngs/thread.rs | 141 - .../cargo/vendor/rand-0.5.6/src/seq.rs | 334 - .../cargo/vendor/rand-0.5.6/tests/bool.rs | 23 - .../vendor/rand-0.5.6/utils/ci/install.sh | 49 - .../vendor/rand-0.5.6/utils/ci/script.sh | 29 - .../rand-0.5.6/utils/ziggurat_tables.py | 127 - .../cargo/vendor/rand_core-0.3.1/BUILD | 2 - .../.cargo-checksum.json | 1 + .../vendor/raw-window-handle-0.3.3/BUILD | 43 + .../raw-window-handle-0.3.3/CHANGELOG.md | 39 + .../vendor/raw-window-handle-0.3.3/Cargo.toml | 36 + .../LICENSE | 4 +- .../vendor/raw-window-handle-0.3.3/README.md | 7 + .../appveyor.yml | 2 - .../raw-window-handle-0.3.3/rustfmt.toml | 1 + .../raw-window-handle-0.3.3/src/android.rs | 31 + .../vendor/raw-window-handle-0.3.3/src/ios.rs | 34 + .../vendor/raw-window-handle-0.3.3/src/lib.rs | 194 + .../raw-window-handle-0.3.3/src/macos.rs | 33 + .../raw-window-handle-0.3.3/src/unix.rs | 98 + .../vendor/raw-window-handle-0.3.3/src/web.rs | 33 + .../raw-window-handle-0.3.3/src/windows.rs | 34 + .../redox_syscall-0.1.56/.cargo-checksum.json | 1 + .../cargo/vendor/redox_syscall-0.1.56/BUILD | 46 + .../vendor/redox_syscall-0.1.56/Cargo.toml | 23 + .../cargo/vendor/redox_syscall-0.1.56/LICENSE | 22 + .../vendor/redox_syscall-0.1.56/README.md | 6 + .../redox_syscall-0.1.56/src/arch/aarch64.rs | 77 + .../redox_syscall-0.1.56/src/arch/arm.rs | 73 + .../redox_syscall-0.1.56/src/arch/nonredox.rs | 31 + .../redox_syscall-0.1.56/src/arch/x86.rs | 73 + .../redox_syscall-0.1.56/src/arch/x86_64.rs | 74 + .../vendor/redox_syscall-0.1.56/src/call.rs | 393 + .../vendor/redox_syscall-0.1.56/src/data.rs | 309 + .../vendor/redox_syscall-0.1.56/src/error.rs | 311 + .../vendor/redox_syscall-0.1.56/src/flag.rs | 169 + .../vendor/redox_syscall-0.1.56/src/io/dma.rs | 76 + .../vendor/redox_syscall-0.1.56/src/io/io.rs | 67 + .../redox_syscall-0.1.56/src/io/mmio.rs | 31 + .../vendor/redox_syscall-0.1.56/src/io/mod.rs | 11 + .../vendor/redox_syscall-0.1.56/src/io/pio.rs | 89 + .../vendor/redox_syscall-0.1.56/src/lib.rs | 59 + .../vendor/redox_syscall-0.1.56/src/number.rs | 76 + .../src/scheme/generate.sh | 20 + .../redox_syscall-0.1.56/src/scheme/mod.rs | 9 + .../redox_syscall-0.1.56/src/scheme/scheme.rs | 167 + .../src/scheme/scheme_block.rs | 167 + .../src/scheme/scheme_block_mut.rs | 167 + .../src/scheme/scheme_mut.rs | 167 + .../vendor/redox_syscall-0.1.56/src/tests.rs | 129 + .../.cargo-checksum.json | 1 - .../vendor/rustc-demangle-0.1.16/README.md | 24 - .../rustc-demangle-0.1.16/src/legacy.rs | 379 - .../vendor/rustc-demangle-0.1.16/src/lib.rs | 373 - .../vendor/rustc-demangle-0.1.16/src/v0.rs | 1084 -- .../rustc_version-0.2.3/.cargo-checksum.json | 1 - .../cargo/vendor/rustc_version-0.2.3/BUILD | 43 - .../vendor/rustc_version-0.2.3/Cargo.toml | 26 - .../vendor/rustc_version-0.2.3/LICENSE-APACHE | 201 - .../vendor/rustc_version-0.2.3/LICENSE-MIT | 25 - .../vendor/rustc_version-0.2.3/README.md | 75 - .../vendor/rustc_version-0.2.3/src/errors.rs | 79 - .../vendor/rustc_version-0.2.3/src/lib.rs | 347 - .../scopeguard-0.3.3/.cargo-checksum.json | 1 - .../cargo/vendor/scopeguard-0.3.3/Cargo.toml | 28 - .../cargo/vendor/scopeguard-0.3.3/LICENSE-MIT | 25 - .../cargo/vendor/scopeguard-0.3.3/README.rst | 81 - .../scopeguard-0.3.3/examples/readme.rs | 27 - .../cargo/vendor/scopeguard-0.3.3/src/lib.rs | 409 - .../vendor/semver-0.9.0/.cargo-checksum.json | 1 - third_party/cargo/vendor/semver-0.9.0/BUILD | 47 - .../cargo/vendor/semver-0.9.0/Cargo.toml | 45 - .../cargo/vendor/semver-0.9.0/LICENSE-MIT | 25 - .../cargo/vendor/semver-0.9.0/README.md | 103 - .../cargo/vendor/semver-0.9.0/src/lib.rs | 182 - .../cargo/vendor/semver-0.9.0/src/version.rs | 759 - .../vendor/semver-0.9.0/src/version_req.rs | 895 - .../vendor/semver-0.9.0/tests/deprecation.rs | 22 - .../vendor/semver-0.9.0/tests/regression.rs | 25 - .../cargo/vendor/semver-0.9.0/tests/serde.rs | 90 - .../semver-parser-0.7.0/.cargo-checksum.json | 1 - .../vendor/semver-parser-0.7.0/Cargo.toml | 11 - .../vendor/semver-parser-0.7.0/LICENSE-APACHE | 201 - .../vendor/semver-parser-0.7.0/src/common.rs | 66 - .../vendor/semver-parser-0.7.0/src/lib.rs | 8 - .../vendor/semver-parser-0.7.0/src/range.rs | 696 - .../semver-parser-0.7.0/src/recognize.rs | 154 - .../vendor/semver-parser-0.7.0/src/version.rs | 365 - .../vendor/slab-0.4.2/.cargo-checksum.json | 1 + .../BUILD | 7 +- .../cargo/vendor/slab-0.4.2/CHANGELOG.md | 8 + .../{objc_id-0.1.1 => slab-0.4.2}/Cargo.toml | 19 +- .../LICENSE-MIT => slab-0.4.2/LICENSE} | 2 +- third_party/cargo/vendor/slab-0.4.2/README.md | 48 + .../cargo/vendor/slab-0.4.2/src/lib.rs | 977 ++ .../cargo/vendor/slab-0.4.2/tests/slab.rs | 301 + .../smallvec-0.6.13/.cargo-checksum.json | 1 - .../vendor/smallvec-0.6.13/LICENSE-APACHE | 201 - .../cargo/vendor/smallvec-0.6.13/README.md | 8 - .../smallvec-1.2.0/.cargo-checksum.json | 1 + .../{smallvec-0.6.13 => smallvec-1.2.0}/BUILD | 7 +- .../Cargo.toml | 11 +- .../LICENSE-APACHE | 0 .../LICENSE-MIT | 0 .../cargo/vendor/smallvec-1.2.0/README.md | 26 + .../benches/bench.rs | 0 .../lib.rs | 799 +- .../scripts/run_miri.sh | 6 +- .../specialization.rs | 7 +- .../.cargo-checksum.json | 1 - .../.cargo-checksum.json | 1 + .../BUILD | 8 +- .../CHANGELOG.md | 60 +- .../CONTRIBUTING.md | 0 .../smithay-client-toolkit-0.6.6/Cargo.lock | 644 + .../Cargo.toml | 17 +- .../LICENSE.txt | 0 .../README.md | 0 .../doc_index.html | 0 .../examples/compositor_info.rs | 0 .../examples/image_viewer.rs | 26 +- .../examples/kbd_input.rs | 11 +- .../examples/pointer_input.rs | 11 +- .../examples/selection.rs | 30 +- .../examples/themed_frame.rs | 229 + .../src/data_device/data_device.rs | 69 +- .../src/data_device/data_offer.rs | 9 +- .../src/data_device/data_source.rs | 47 +- .../src/data_device/mod.rs | 0 .../src/env.rs | 107 +- .../src/keyboard/ffi.rs | 0 .../src/keyboard/keysyms.rs | 0 .../src/keyboard/mod.rs | 573 +- .../src/lib.rs | 2 - .../src/output.rs | 47 +- .../src/pointer/mod.rs | 88 +- .../src/pointer/theme.rs | 180 +- .../src/shell/mod.rs | 11 +- .../src/shell/wl.rs | 24 +- .../src/shell/xdg.rs | 60 +- .../src/shell/zxdg.rs | 57 +- .../src/surface.rs | 54 +- .../src/utils/mempool.rs | 21 +- .../src/utils/mod.rs | 0 .../src/window/basic_frame.rs | 64 +- .../src/window/concept_frame.rs | 479 +- .../src/window/mod.rs | 134 +- .../travis_install_wayland.sh | 0 .../update_keysyms.sh | 0 .../.cargo-checksum.json | 1 - .../stable_deref_trait-1.1.1/LICENSE-APACHE | 201 - .../stable_deref_trait-1.1.1/LICENSE-MIT | 25 - .../vendor/stable_deref_trait-1.1.1/README.md | 23 - .../stable_deref_trait-1.1.1/src/lib.rs | 201 - .../vendor/vk-sys-0.4.0/.cargo-checksum.json | 1 - .../vendor/vk-sys-0.5.1/.cargo-checksum.json | 1 + .../{vk-sys-0.4.0 => vk-sys-0.5.1}/BUILD | 2 +- .../{vk-sys-0.4.0 => vk-sys-0.5.1}/Cargo.toml | 4 +- .../{vk-sys-0.4.0 => vk-sys-0.5.1}/src/lib.rs | 224 +- .../vulkano-0.11.1/.cargo-checksum.json | 1 - .../vulkano-0.18.0/.cargo-checksum.json | 1 + .../{vulkano-0.11.1 => vulkano-0.18.0}/BUILD | 8 +- .../Cargo.toml | 18 +- .../build.rs | 0 .../src/alloc.rs | 0 .../src/buffer/cpu_access.rs | 70 +- .../src/buffer/cpu_pool.rs | 56 +- .../src/buffer/device_local.rs | 29 +- .../src/buffer/immutable.rs | 55 +- .../src/buffer/mod.rs | 0 .../src/buffer/slice.rs | 34 +- .../src/buffer/sys.rs | 55 +- .../src/buffer/traits.rs | 29 +- .../src/buffer/usage.rs | 2 +- .../src/buffer/view.rs | 18 +- .../src/command_buffer/auto.rs | 46 +- .../src/command_buffer/mod.rs | 9 +- .../src/command_buffer/pool/mod.rs | 0 .../src/command_buffer/pool/standard.rs | 12 +- .../src/command_buffer/pool/sys.rs | 12 +- .../src/command_buffer/state_cacher.rs | 17 +- .../src/command_buffer/submit/bind_sparse.rs | 2 +- .../src/command_buffer/submit/mod.rs | 0 .../command_buffer/submit/queue_present.rs | 8 +- .../src/command_buffer/submit/queue_submit.rs | 2 +- .../command_buffer/submit/semaphores_wait.rs | 6 +- .../src/command_buffer/synced/base.rs | 218 +- .../src/command_buffer/synced/commands.rs | 249 +- .../src/command_buffer/synced/mod.rs | 0 .../src/command_buffer/synced/tests.rs | 2 +- .../src/command_buffer/sys.rs | 87 +- .../src/command_buffer/traits.rs | 18 +- .../src/command_buffer/validity/blit_image.rs | 0 .../validity/clear_color_image.rs | 0 .../command_buffer/validity/copy_buffer.rs | 0 .../src/command_buffer/validity/copy_image.rs | 0 .../validity/copy_image_buffer.rs | 39 +- .../validity/descriptor_sets.rs | 2 +- .../src/command_buffer/validity/dispatch.rs | 0 .../command_buffer/validity/dynamic_state.rs | 63 +- .../command_buffer/validity/fill_buffer.rs | 4 +- .../command_buffer/validity/index_buffer.rs | 4 +- .../src/command_buffer/validity/mod.rs | 0 .../command_buffer/validity/push_constants.rs | 0 .../command_buffer/validity/update_buffer.rs | 7 +- .../command_buffer/validity/vertex_buffers.rs | 2 +- .../src/descriptor/descriptor.rs | 67 +- .../descriptor/descriptor_set/collection.rs | 10 +- .../descriptor_set/fixed_size_pool.rs | 162 +- .../src/descriptor/descriptor_set/mod.rs | 33 +- .../descriptor/descriptor_set/persistent.rs | 194 +- .../src/descriptor/descriptor_set/std_pool.rs | 0 .../src/descriptor/descriptor_set/sys.rs | 10 +- .../descriptor_set/unsafe_layout.rs | 28 +- .../src/descriptor/mod.rs | 2 +- .../src/descriptor/pipeline_layout/empty.rs | 0 .../pipeline_layout/limits_check.rs | 0 .../src/descriptor/pipeline_layout/mod.rs | 0 .../pipeline_layout/runtime_desc.rs | 0 .../src/descriptor/pipeline_layout/sys.rs | 12 +- .../src/descriptor/pipeline_layout/traits.rs | 2 +- .../src/descriptor/pipeline_layout/tweaks.rs | 0 .../src/descriptor/pipeline_layout/union.rs | 0 .../src/device/extensions.rs | 26 +- .../src/device/mod.rs | 70 +- .../src/extensions.rs | 19 +- .../src/features.rs | 0 .../src/format.rs | 388 +- .../src/framebuffer/attachments_list.rs | 12 +- .../src/framebuffer/compat_atch.rs | 0 .../src/framebuffer/desc.rs | 0 .../src/framebuffer/empty.rs | 4 +- .../src/framebuffer/framebuffer.rs | 18 +- .../src/framebuffer/macros.rs | 14 +- .../src/framebuffer/mod.rs | 0 .../src/framebuffer/sys.rs | 19 +- .../src/framebuffer/traits.rs | 8 +- .../src/image/attachment.rs | 40 +- .../src/image/immutable.rs | 57 +- .../src/image/layout.rs | 0 .../src/image/mod.rs | 64 +- .../src/image/storage.rs | 33 +- .../src/image/swapchain.rs | 52 +- .../src/image/sys.rs | 105 +- .../src/image/traits.rs | 109 +- .../src/image/usage.rs | 0 .../src/instance/debug.rs | 218 +- .../src/instance/extensions.rs | 23 +- .../src/instance/instance.rs | 105 +- .../src/instance/layers.rs | 2 +- .../src/instance/limits.rs | 0 .../src/instance/loader.rs | 6 +- .../src/instance/mod.rs | 0 .../src/lib.rs | 6 +- .../src/memory/device_memory.rs | 18 +- .../src/memory/mod.rs | 0 .../src/memory/pool/host_visible.rs | 0 .../src/memory/pool/mod.rs | 0 .../src/memory/pool/non_host_visible.rs | 0 .../src/memory/pool/pool.rs | 0 .../src/pipeline/blend.rs | 0 .../src/pipeline/cache.rs | 10 +- .../src/pipeline/compute_pipeline.rs | 21 +- .../src/pipeline/depth_stencil.rs | 16 + .../src/pipeline/graphics_pipeline/builder.rs | 18 +- .../graphics_pipeline/creation_error.rs | 2 +- .../src/pipeline/graphics_pipeline/mod.rs | 61 +- .../src/pipeline/graphics_pipeline/tests.rs | 0 .../src/pipeline/input_assembly.rs | 0 .../src/pipeline/mod.rs | 0 .../src/pipeline/multisample.rs | 0 .../src/pipeline/raster.rs | 0 .../src/pipeline/shader.rs | 9 +- .../src/pipeline/vertex/bufferless.rs | 4 +- .../src/pipeline/vertex/definition.rs | 6 +- .../src/pipeline/vertex/impl_vertex.rs | 32 +- .../src/pipeline/vertex/instance_buffer.rs | 8 +- .../src/pipeline/vertex/mod.rs | 0 .../src/pipeline/vertex/one_one.rs | 8 +- .../src/pipeline/vertex/single.rs | 8 +- .../src/pipeline/vertex/two.rs | 8 +- .../src/pipeline/vertex/vertex.rs | 0 .../src/pipeline/viewport.rs | 0 .../src/query/mod.rs | 12 +- .../src/sampler.rs | 18 +- .../src/swapchain/capabilities.rs | 0 .../src/swapchain/display.rs | 8 +- .../src/swapchain/mod.rs | 26 +- .../src/swapchain/present_region.rs | 0 .../src/swapchain/surface.rs | 74 +- .../src/swapchain/swapchain.rs | 425 +- .../src/sync/event.rs | 10 +- .../src/sync/fence.rs | 12 +- .../src/sync/future/fence_signal.rs | 8 +- .../src/sync/future/join.rs | 23 +- .../src/sync/future/mod.rs | 16 +- .../src/sync/future/now.rs | 4 +- .../src/sync/future/semaphore_signal.rs | 6 +- .../src/sync/mod.rs | 9 +- .../src/sync/pipeline.rs | 0 .../src/sync/semaphore.rs | 10 +- .../src/tests.rs | 0 .../src/version.rs | 0 .../vulkano-win-0.11.1/.cargo-checksum.json | 1 - .../vulkano-win-0.18.0/.cargo-checksum.json | 1 + .../BUILD | 8 +- .../Cargo.toml | 15 +- .../src/lib.rs | 76 +- .../.cargo-checksum.json | 1 - .../vendor/wayland-client-0.21.13/build.rs | 20 - .../examples/dynamic_globals.rs | 109 - .../.cargo-checksum.json | 1 + .../BUILD | 24 +- .../vendor/wayland-client-0.23.6/Cargo.lock | 429 + .../Cargo.toml | 14 +- .../vendor/wayland-client-0.23.6/build.rs | 20 + .../examples/dynamic_globals.rs | 118 + .../examples/list_globals.rs | 0 .../examples/simple_window.rs | 125 +- .../src/cursor.rs | 77 +- .../src/display.rs | 74 +- .../src/egl.rs | 7 +- .../src/event_queue.rs | 88 +- .../src/globals.rs | 183 +- .../src/lib.rs | 142 +- .../src/native_lib/display.rs | 38 +- .../src/native_lib/event_queue.rs | 1 - .../src/native_lib/mod.rs | 0 .../src/native_lib/proxy.rs | 105 +- .../src/proxy.rs | 320 +- .../src/rust_imp/connection.rs | 61 +- .../src/rust_imp/display.rs | 32 +- .../src/rust_imp/mod.rs | 46 +- .../src/rust_imp/proxy.rs | 43 +- .../src/rust_imp/queues.rs | 52 +- .../vendor/wayland-client-0.23.6/src/sinks.rs | 165 + .../wayland.xml | 263 +- .../.cargo-checksum.json | 1 - .../.cargo-checksum.json | 1 + .../BUILD | 6 +- .../vendor/wayland-commons-0.23.6/Cargo.lock | 60 + .../Cargo.toml | 10 +- .../examples/manual_global_list.rs | 0 .../src/lib.rs | 39 +- .../src/map.rs | 33 +- .../wayland-commons-0.23.6/src/sinks.rs | 67 + .../src/socket.rs | 10 +- .../src/utils.rs | 86 +- .../src/wire.rs | 14 +- .../.cargo-checksum.json | 1 - .../vendor/wayland-protocols-0.21.13/build.rs | 126 - .../src/protocol_macro.rs | 112 - .../.cargo-checksum.json | 1 + .../BUILD | 20 +- .../Cargo.toml | 19 +- .../vendor/wayland-protocols-0.23.6/build.rs | 150 + .../misc/gtk-primary-selection.xml | 225 + .../protocols/COPYING | 0 .../protocols/Makefile.am | 0 .../protocols/README | 0 .../protocols/autogen.sh | 0 .../protocols/configure.ac | 0 .../protocols/m4/compat.m4 | 0 .../protocols/stable/presentation-time/README | 0 .../presentation-time/presentation-time.xml | 0 .../protocols/stable/viewporter/README | 0 .../stable/viewporter/viewporter.xml | 0 .../protocols/stable/xdg-shell/README | 0 .../protocols/stable/xdg-shell/xdg-shell.xml | 0 .../protocols/tests/scan.sh | 0 .../unstable/fullscreen-shell/README | 0 .../fullscreen-shell-unstable-v1.xml | 0 .../protocols/unstable/idle-inhibit/README | 0 .../idle-inhibit/idle-inhibit-unstable-v1.xml | 0 .../protocols/unstable/input-method/README | 0 .../input-method/input-method-unstable-v1.xml | 0 .../unstable/input-timestamps/README | 0 .../input-timestamps-unstable-v1.xml | 0 .../keyboard-shortcuts-inhibit/README | 0 ...keyboard-shortcuts-inhibit-unstable-v1.xml | 0 .../protocols/unstable/linux-dmabuf/README | 0 .../linux-dmabuf/linux-dmabuf-unstable-v1.xml | 0 .../linux-explicit-synchronization/README | 0 ...x-explicit-synchronization-unstable-v1.xml | 0 .../unstable/pointer-constraints/README | 0 .../pointer-constraints-unstable-v1.xml | 0 .../unstable/pointer-gestures/README | 0 .../pointer-gestures-unstable-v1.xml | 0 .../unstable/primary-selection/README | 0 .../primary-selection-unstable-v1.xml | 0 .../unstable/relative-pointer/README | 0 .../relative-pointer-unstable-v1.xml | 0 .../protocols/unstable/tablet/README | 0 .../unstable/tablet/tablet-unstable-v1.xml | 0 .../unstable/tablet/tablet-unstable-v2.xml | 0 .../protocols/unstable/text-input/README | 0 .../text-input/text-input-unstable-v1.xml | 0 .../text-input/text-input-unstable-v3.xml | 0 .../protocols/unstable/xdg-decoration/README | 0 .../xdg-decoration-unstable-v1.xml | 0 .../protocols/unstable/xdg-foreign/README | 0 .../xdg-foreign/xdg-foreign-unstable-v1.xml | 0 .../xdg-foreign/xdg-foreign-unstable-v2.xml | 0 .../protocols/unstable/xdg-output/README | 0 .../xdg-output/xdg-output-unstable-v1.xml | 0 .../protocols/unstable/xdg-shell/README | 0 .../xdg-shell/xdg-shell-unstable-v5.xml | 0 .../xdg-shell/xdg-shell-unstable-v6.xml | 0 .../unstable/xwayland-keyboard-grab/README | 0 .../xwayland-keyboard-grab-unstable-v1.xml | 0 .../wayland-protocols-uninstalled.pc.in | 0 .../protocols/wayland-protocols.pc.in | 0 .../src/lib.rs | 5 +- .../wayland-protocols-0.23.6/src/misc.rs | 64 + .../src/protocol_macro.rs | 60 + .../src/stable.rs | 16 +- .../src/unstable.rs | 8 +- .../src/wlr.rs | 0 .../wlr-protocols/Makefile | 0 .../wlr-protocols/check.sh | 0 .../unstable/wlr-data-control-unstable-v1.xml | 80 +- .../wlr-export-dmabuf-unstable-v1.xml | 0 ...oreign-toplevel-management-unstable-v1.xml | 0 .../wlr-gamma-control-unstable-v1.xml | 0 .../wlr-input-inhibitor-unstable-v1.xml | 0 .../unstable/wlr-layer-shell-unstable-v1.xml | 0 .../unstable/wlr-screencopy-unstable-v1.xml | 0 .../wlr-protocols/wlr-protocols.pc.in | 0 .../.cargo-checksum.json | 1 - .../src/rust_code_gen.rs | 114 - .../.cargo-checksum.json | 1 + .../BUILD | 2 +- .../Cargo.toml | 4 +- .../src/c_code_gen.rs | 122 +- .../src/c_interface_gen.rs | 88 +- .../src/common_gen.rs | 380 +- .../src/lib.rs | 165 +- .../src/parse.rs | 23 +- .../src/protocol.rs | 14 +- .../src/side.rs | 4 +- .../src/util.rs | 19 +- .../wayland-sys-0.21.13/.cargo-checksum.json | 1 - .../wayland-sys-0.23.6/.cargo-checksum.json | 1 + .../BUILD | 3 +- .../Cargo.toml | 13 +- .../src/client.rs | 9 +- .../src/common.rs | 2 +- .../src/cursor.rs | 0 .../src/egl.rs | 0 .../src/lib.rs | 22 +- .../src/server.rs | 16 +- .../vendor/winapi-0.2.8/.cargo-checksum.json | 1 + .../{memoffset-0.2.1 => winapi-0.2.8}/BUILD | 4 +- .../cargo/vendor/winapi-0.2.8/Cargo.toml | 61 + .../cargo/vendor/winapi-0.2.8/LICENSE.md | 21 + .../vendor/winapi-0.2.8/src/activation.rs | 5 + .../vendor/winapi-0.2.8/src/audioclient.rs | 71 + .../winapi-0.2.8/src/audiosessiontypes.rs | 11 + .../cargo/vendor/winapi-0.2.8/src/basetsd.rs | 99 + .../cargo/vendor/winapi-0.2.8/src/bcrypt.rs | 356 + .../cargo/vendor/winapi-0.2.8/src/cfg.rs | 134 + .../cargo/vendor/winapi-0.2.8/src/cfgmgr32.rs | 758 + .../vendor/winapi-0.2.8/src/combaseapi.rs | 17 + .../cargo/vendor/winapi-0.2.8/src/commctrl.rs | 3578 ++++ .../cargo/vendor/winapi-0.2.8/src/commdlg.rs | 583 + .../cargo/vendor/winapi-0.2.8/src/corsym.rs | 79 + .../cargo/vendor/winapi-0.2.8/src/d2d1.rs | 734 + .../vendor/winapi-0.2.8/src/d2dbasetypes.rs | 61 + .../vendor/winapi-0.2.8/src/d3d10shader.rs | 110 + .../cargo/vendor/winapi-0.2.8/src/d3d11.rs | 2665 +++ .../vendor/winapi-0.2.8/src/d3d11shader.rs | 320 + .../cargo/vendor/winapi-0.2.8/src/d3d12.rs | 2324 +++ .../vendor/winapi-0.2.8/src/d3d12sdklayers.rs | 1063 ++ .../vendor/winapi-0.2.8/src/d3d12shader.rs | 320 + .../cargo/vendor/winapi-0.2.8/src/d3d9.rs | 713 + .../cargo/vendor/winapi-0.2.8/src/d3d9caps.rs | 349 + .../vendor/winapi-0.2.8/src/d3d9types.rs | 1397 ++ .../vendor/winapi-0.2.8/src/d3dcommon.rs | 753 + .../vendor/winapi-0.2.8/src/d3dcompiler.rs | 74 + .../cargo/vendor/winapi-0.2.8/src/dbghelp.rs | 340 + .../cargo/vendor/winapi-0.2.8/src/dcommon.rs | 18 + .../vendor/winapi-0.2.8/src/devpropdef.rs | 71 + .../cargo/vendor/winapi-0.2.8/src/docobj.rs | 22 + .../cargo/vendor/winapi-0.2.8/src/dpapi.rs | 11 + .../cargo/vendor/winapi-0.2.8/src/dsgetdc.rs | 113 + .../cargo/vendor/winapi-0.2.8/src/dsound.rs | 132 + .../cargo/vendor/winapi-0.2.8/src/dsrole.rs | 50 + .../cargo/vendor/winapi-0.2.8/src/dwmapi.rs | 9 + .../cargo/vendor/winapi-0.2.8/src/dwrite.rs | 1038 ++ .../cargo/vendor/winapi-0.2.8/src/dxgi.rs | 240 + .../cargo/vendor/winapi-0.2.8/src/dxgi1_2.rs | 288 + .../cargo/vendor/winapi-0.2.8/src/dxgi1_3.rs | 131 + .../cargo/vendor/winapi-0.2.8/src/dxgi1_4.rs | 82 + .../vendor/winapi-0.2.8/src/dxgiformat.rs | 124 + .../cargo/vendor/winapi-0.2.8/src/dxgitype.rs | 86 + .../vendor/winapi-0.2.8/src/errhandlingapi.rs | 7 + .../cargo/vendor/winapi-0.2.8/src/excpt.rs | 14 + .../cargo/vendor/winapi-0.2.8/src/fileapi.rs | 152 + .../cargo/vendor/winapi-0.2.8/src/gl.rs | 35 + .../cargo/vendor/winapi-0.2.8/src/guiddef.rs | 20 + .../cargo/vendor/winapi-0.2.8/src/heapapi.rs | 12 + .../cargo/vendor/winapi-0.2.8/src/hidclass.rs | 56 + .../cargo/vendor/winapi-0.2.8/src/hidpi.rs | 182 + .../cargo/vendor/winapi-0.2.8/src/hidsdi.rs | 15 + .../cargo/vendor/winapi-0.2.8/src/hidusage.rs | 270 + .../cargo/vendor/winapi-0.2.8/src/hstring.rs | 16 + .../cargo/vendor/winapi-0.2.8/src/http.rs | 828 + .../cargo/vendor/winapi-0.2.8/src/imm.rs | 3 + .../cargo/vendor/winapi-0.2.8/src/inaddr.rs | 22 + .../vendor/winapi-0.2.8/src/inspectable.rs | 15 + .../cargo/vendor/winapi-0.2.8/src/ksmedia.rs | 18 + .../cargo/vendor/winapi-0.2.8/src/lib.rs | 368 + .../vendor/winapi-0.2.8/src/libloaderapi.rs | 23 + .../cargo/vendor/winapi-0.2.8/src/lmaccess.rs | 853 + .../cargo/vendor/winapi-0.2.8/src/lmcons.rs | 55 + .../cargo/vendor/winapi-0.2.8/src/lmdfs.rs | 311 + .../cargo/vendor/winapi-0.2.8/src/lmerrlog.rs | 263 + .../cargo/vendor/winapi-0.2.8/src/lmjoin.rs | 80 + .../vendor/winapi-0.2.8/src/lsalookup.rs | 69 + .../cargo/vendor/winapi-0.2.8/src/macros.rs | 270 + .../vendor/winapi-0.2.8/src/memoryapi.rs | 19 + .../vendor/winapi-0.2.8/src/minschannel.rs | 56 + .../vendor/winapi-0.2.8/src/minwinbase.rs | 253 + .../vendor/winapi-0.2.8/src/minwindef.rs | 89 + .../vendor/winapi-0.2.8/src/mmdeviceapi.rs | 63 + .../cargo/vendor/winapi-0.2.8/src/mmreg.rs | 304 + .../cargo/vendor/winapi-0.2.8/src/mmsystem.rs | 259 + .../cargo/vendor/winapi-0.2.8/src/mscat.rs | 28 + .../cargo/vendor/winapi-0.2.8/src/mssip.rs | 103 + .../cargo/vendor/winapi-0.2.8/src/nb30.rs | 200 + .../cargo/vendor/winapi-0.2.8/src/ncrypt.rs | 9 + .../cargo/vendor/winapi-0.2.8/src/ntdef.rs | 7 + .../cargo/vendor/winapi-0.2.8/src/ntsecapi.rs | 1589 ++ .../cargo/vendor/winapi-0.2.8/src/ntstatus.rs | 2474 +++ .../cargo/vendor/winapi-0.2.8/src/oaidl.rs | 590 + .../cargo/vendor/winapi-0.2.8/src/objbase.rs | 5 + .../cargo/vendor/winapi-0.2.8/src/objidl.rs | 100 + .../vendor/winapi-0.2.8/src/objidlbase.rs | 93 + .../cargo/vendor/winapi-0.2.8/src/olectl.rs | 10 + .../cargo/vendor/winapi-0.2.8/src/pdh.rs | 52 + .../vendor/winapi-0.2.8/src/playsoundapi.rs | 19 + .../winapi-0.2.8/src/processsnapshot.rs | 58 + .../winapi-0.2.8/src/processthreadsapi.rs | 62 + .../cargo/vendor/winapi-0.2.8/src/propidl.rs | 10 + .../cargo/vendor/winapi-0.2.8/src/propsys.rs | 4 + .../cargo/vendor/winapi-0.2.8/src/prsht.rs | 262 + .../cargo/vendor/winapi-0.2.8/src/psapi.rs | 166 + .../cargo/vendor/winapi-0.2.8/src/qos.rs | 16 + .../cargo/vendor/winapi-0.2.8/src/reason.rs | 63 + .../winapi-0.2.8/src/restrictederrorinfo.rs | 9 + .../cargo/vendor/winapi-0.2.8/src/roapi.rs | 13 + .../vendor/winapi-0.2.8/src/roerrorapi.rs | 11 + .../cargo/vendor/winapi-0.2.8/src/rpc.rs | 5 + .../cargo/vendor/winapi-0.2.8/src/rpcdce.rs | 535 + .../cargo/vendor/winapi-0.2.8/src/sapi.rs | 2431 +++ .../cargo/vendor/winapi-0.2.8/src/schannel.rs | 333 + .../cargo/vendor/winapi-0.2.8/src/servprov.rs | 11 + .../cargo/vendor/winapi-0.2.8/src/setupapi.rs | 1301 ++ .../cargo/vendor/winapi-0.2.8/src/shellapi.rs | 62 + .../winapi-0.2.8/src/shellscalingapi.rs | 19 + .../cargo/vendor/winapi-0.2.8/src/shlguid.rs | 2 + .../cargo/vendor/winapi-0.2.8/src/shlobj.rs | 94 + .../cargo/vendor/winapi-0.2.8/src/shobjidl.rs | 652 + .../cargo/vendor/winapi-0.2.8/src/shtypes.rs | 40 + .../cargo/vendor/winapi-0.2.8/src/spapidef.rs | 48 + .../cargo/vendor/winapi-0.2.8/src/sql.rs | 179 + .../cargo/vendor/winapi-0.2.8/src/sqltypes.rs | 130 + .../cargo/vendor/winapi-0.2.8/src/sspi.rs | 657 + .../cargo/vendor/winapi-0.2.8/src/strmif.rs | 4 + .../cargo/vendor/winapi-0.2.8/src/subauth.rs | 198 + .../cargo/vendor/winapi-0.2.8/src/synchapi.rs | 14 + .../vendor/winapi-0.2.8/src/sysinfoapi.rs | 46 + .../vendor/winapi-0.2.8/src/threadpoolapi.rs | 7 + .../vendor/winapi-0.2.8/src/timezoneapi.rs | 27 + .../cargo/vendor/winapi-0.2.8/src/tlhelp32.rs | 104 + .../vendor/winapi-0.2.8/src/unknwnbase.rs | 29 + .../cargo/vendor/winapi-0.2.8/src/urlhist.rs | 56 + .../cargo/vendor/winapi-0.2.8/src/urlmon.rs | 6 + .../cargo/vendor/winapi-0.2.8/src/usb.rs | 18 + .../cargo/vendor/winapi-0.2.8/src/usbspec.rs | 41 + .../cargo/vendor/winapi-0.2.8/src/usp10.rs | 201 + .../cargo/vendor/winapi-0.2.8/src/vadefs.rs | 7 + .../cargo/vendor/winapi-0.2.8/src/vsbackup.rs | 303 + .../cargo/vendor/winapi-0.2.8/src/vss.rs | 256 + .../cargo/vendor/winapi-0.2.8/src/vsserror.rs | 85 + .../cargo/vendor/winapi-0.2.8/src/vswriter.rs | 241 + .../cargo/vendor/winapi-0.2.8/src/werapi.rs | 8 + .../cargo/vendor/winapi-0.2.8/src/winbase.rs | 552 + .../cargo/vendor/winapi-0.2.8/src/wincon.rs | 198 + .../cargo/vendor/winapi-0.2.8/src/wincred.rs | 209 + .../cargo/vendor/winapi-0.2.8/src/wincrypt.rs | 2206 +++ .../cargo/vendor/winapi-0.2.8/src/windef.rs | 57 + .../vendor/winapi-0.2.8/src/windowscodecs.rs | 363 + .../cargo/vendor/winapi-0.2.8/src/windowsx.rs | 22 + .../cargo/vendor/winapi-0.2.8/src/winerror.rs | 6065 +++++++ .../cargo/vendor/winapi-0.2.8/src/winevt.rs | 40 + .../cargo/vendor/winapi-0.2.8/src/wingdi.rs | 1238 ++ .../cargo/vendor/winapi-0.2.8/src/winhttp.rs | 441 + .../cargo/vendor/winapi-0.2.8/src/winioctl.rs | 754 + .../cargo/vendor/winapi-0.2.8/src/winnetwk.rs | 275 + .../cargo/vendor/winapi-0.2.8/src/winnls.rs | 164 + .../cargo/vendor/winapi-0.2.8/src/winnt.rs | 2368 +++ .../cargo/vendor/winapi-0.2.8/src/winreg.rs | 41 + .../cargo/vendor/winapi-0.2.8/src/winscard.rs | 269 + .../cargo/vendor/winapi-0.2.8/src/winsmcrd.rs | 157 + .../cargo/vendor/winapi-0.2.8/src/winsock2.rs | 429 + .../cargo/vendor/winapi-0.2.8/src/winspool.rs | 29 + .../vendor/winapi-0.2.8/src/winstring.rs | 3 + .../cargo/vendor/winapi-0.2.8/src/winsvc.rs | 200 + .../cargo/vendor/winapi-0.2.8/src/winusb.rs | 33 + .../cargo/vendor/winapi-0.2.8/src/winusbio.rs | 18 + .../cargo/vendor/winapi-0.2.8/src/winuser.rs | 2334 +++ .../cargo/vendor/winapi-0.2.8/src/ws2def.rs | 279 + .../cargo/vendor/winapi-0.2.8/src/ws2ipdef.rs | 42 + .../cargo/vendor/winapi-0.2.8/src/ws2spi.rs | 57 + .../cargo/vendor/winapi-0.2.8/src/ws2tcpip.rs | 27 + .../cargo/vendor/winapi-0.2.8/src/wtypes.rs | 75 + .../vendor/winapi-0.2.8/src/wtypesbase.rs | 37 + .../cargo/vendor/winapi-0.2.8/src/xinput.rs | 118 + third_party/cargo/vendor/winapi-0.3.8/BUILD | 5 + .../winapi-build-0.1.1/.cargo-checksum.json | 1 + .../BUILD | 7 +- .../vendor/winapi-build-0.1.1/Cargo.toml | 11 + .../vendor/winapi-build-0.1.1/src/lib.rs | 14 + .../vendor/winit-0.18.1/.cargo-checksum.json | 1 - .../cargo/vendor/winit-0.18.1/CONTRIBUTING.md | 70 - .../cargo/vendor/winit-0.18.1/README.md | 62 - .../vendor/winit-0.18.1/examples/cursor.rs | 32 - .../winit-0.18.1/examples/cursor_grab.rs | 38 - .../winit-0.18.1/examples/fullscreen.rs | 121 - .../winit-0.18.1/examples/handling_close.rs | 74 - .../winit-0.18.1/examples/min_max_size.rs | 23 - .../winit-0.18.1/examples/monitor_list.rs | 7 - .../winit-0.18.1/examples/multiwindow.rs | 33 - .../vendor/winit-0.18.1/examples/proxy.rs | 29 - .../vendor/winit-0.18.1/examples/resizable.rs | 38 - .../winit-0.18.1/examples/transparent.rs | 20 - .../vendor/winit-0.18.1/examples/window.rs | 22 - .../winit-0.18.1/examples/window_icon.rs | 94 - .../cargo/vendor/winit-0.18.1/src/dpi.rs | 331 - .../cargo/vendor/winit-0.18.1/src/events.rs | 480 - .../cargo/vendor/winit-0.18.1/src/icon.rs | 170 - .../cargo/vendor/winit-0.18.1/src/lib.rs | 539 - .../vendor/winit-0.18.1/src/os/android.rs | 38 - .../cargo/vendor/winit-0.18.1/src/os/ios.rs | 59 - .../cargo/vendor/winit-0.18.1/src/os/unix.rs | 306 - .../vendor/winit-0.18.1/src/os/windows.rs | 117 - .../winit-0.18.1/src/platform/android/ffi.rs | 108 - .../src/platform/emscripten/ffi.rs | 314 - .../src/platform/emscripten/mod.rs | 1135 -- .../winit-0.18.1/src/platform/ios/ffi.rs | 110 - .../winit-0.18.1/src/platform/ios/mod.rs | 702 - .../winit-0.18.1/src/platform/linux/dlopen.rs | 15 - .../winit-0.18.1/src/platform/linux/mod.rs | 542 - .../src/platform/linux/wayland/event_loop.rs | 534 - .../src/platform/linux/wayland/pointer.rs | 189 - .../src/platform/linux/wayland/touch.rs | 97 - .../src/platform/linux/wayland/window.rs | 383 - .../src/platform/linux/x11/events.rs | 1008 -- .../src/platform/linux/x11/ffi.rs | 8 - .../src/platform/linux/x11/monitor.rs | 269 - .../src/platform/linux/x11/util/client_msg.rs | 95 - .../src/platform/linux/x11/util/input.rs | 159 - .../src/platform/linux/x11/util/randr.rs | 111 - .../src/platform/linux/x11/window.rs | 1213 -- .../src/platform/macos/events_loop.rs | 742 - .../winit-0.18.1/src/platform/macos/ffi.rs | 107 - .../winit-0.18.1/src/platform/macos/mod.rs | 51 - .../src/platform/macos/monitor.rs | 147 - .../src/platform/macos/util/cursor.rs | 149 - .../src/platform/macos/util/into_option.rs | 14 - .../src/platform/macos/util/mod.rs | 63 - .../winit-0.18.1/src/platform/macos/view.rs | 648 - .../winit-0.18.1/src/platform/macos/window.rs | 1362 -- .../vendor/winit-0.18.1/src/platform/mod.rs | 26 - .../winit-0.18.1/src/platform/windows/dpi.rs | 189 - .../src/platform/windows/events_loop.rs | 1299 -- .../winit-0.18.1/src/platform/windows/icon.rs | 114 - .../src/platform/windows/monitor.rs | 173 - .../winit-0.18.1/src/platform/windows/util.rs | 117 - .../src/platform/windows/window.rs | 1167 -- .../cargo/vendor/winit-0.18.1/src/window.rs | 494 - .../vendor/winit-0.18.1/tests/send_objects.rs | 23 - .../winit-0.18.1/tests/serde_objects.rs | 39 - .../vendor/winit-0.18.1/tests/sync_object.rs | 9 - .../vendor/winit-0.22.0/.cargo-checksum.json | 1 + .../{winit-0.18.1 => winit-0.22.0}/BUILD | 29 +- .../CHANGELOG.md | 267 +- .../cargo/vendor/winit-0.22.0/CONTRIBUTING.md | 42 + .../cargo/vendor/winit-0.22.0/Cargo.lock | 1368 ++ .../{winit-0.18.1 => winit-0.22.0}/Cargo.toml | 81 +- .../cargo/vendor/winit-0.22.0/FEATURES.md | 237 + .../vendor/winit-0.22.0/HALL_OF_CHAMPIONS.md | 14 + .../{winit-0.18.1 => winit-0.22.0}/LICENSE | 0 .../cargo/vendor/winit-0.22.0/README.md | 79 + .../winit-0.22.0/examples/control_flow.rs | 119 + .../vendor/winit-0.22.0/examples/cursor.rs | 88 + .../winit-0.22.0/examples/cursor_grab.rs | 55 + .../winit-0.22.0/examples/custom_events.rs | 52 + .../winit-0.22.0/examples/fullscreen.rs | 117 + .../winit-0.22.0/examples/handling_close.rs | 83 + .../examples/icon.png | Bin .../winit-0.22.0/examples/min_max_size.rs | 29 + .../vendor/winit-0.22.0/examples/minimize.rs | 40 + .../winit-0.22.0/examples/monitor_list.rs | 10 + .../winit-0.22.0/examples/multithreaded.rs | 185 + .../winit-0.22.0/examples/multiwindow.rs | 51 + .../winit-0.22.0/examples/request_redraw.rs | 38 + .../examples/request_redraw_threaded.rs | 39 + .../vendor/winit-0.22.0/examples/resizable.rs | 45 + .../vendor/winit-0.22.0/examples/timer.rs | 38 + .../winit-0.22.0/examples/transparent.rs | 31 + .../winit-0.22.0/examples/video_modes.rs | 13 + .../cargo/vendor/winit-0.22.0/examples/web.rs | 74 + .../vendor/winit-0.22.0/examples/window.rs | 32 + .../winit-0.22.0/examples/window_debug.rs | 117 + .../winit-0.22.0/examples/window_icon.rs | 56 + .../examples/window_run_return.rs | 61 + .../cargo/vendor/winit-0.22.0/rustfmt.toml | 3 + .../cargo/vendor/winit-0.22.0/src/dpi.rs | 501 + .../cargo/vendor/winit-0.22.0/src/error.rs | 82 + .../cargo/vendor/winit-0.22.0/src/event.rs | 945 + .../vendor/winit-0.22.0/src/event_loop.rs | 224 + .../cargo/vendor/winit-0.22.0/src/icon.rs | 135 + .../cargo/vendor/winit-0.22.0/src/lib.rs | 150 + .../cargo/vendor/winit-0.22.0/src/monitor.rs | 174 + .../winit-0.22.0/src/platform/android.rs | 33 + .../winit-0.22.0/src/platform/desktop.rs | 53 + .../vendor/winit-0.22.0/src/platform/ios.rs | 317 + .../os => winit-0.22.0/src/platform}/macos.rs | 113 +- .../os => winit-0.22.0/src/platform}/mod.rs | 12 +- .../vendor/winit-0.22.0/src/platform/unix.rs | 489 + .../vendor/winit-0.22.0/src/platform/web.rs | 59 + .../winit-0.22.0/src/platform/windows.rs | 213 + .../src/platform_impl/android/ffi.rs | 122 + .../src/platform_impl}/android/mod.rs | 252 +- .../src/platform_impl/ios/app_state.rs | 1046 ++ .../src/platform_impl/ios/event_loop.rs | 338 + .../winit-0.22.0/src/platform_impl/ios/ffi.rs | 390 + .../winit-0.22.0/src/platform_impl/ios/mod.rs | 113 + .../src/platform_impl/ios/monitor.rs | 299 + .../src/platform_impl/ios/view.rs | 599 + .../src/platform_impl/ios/window.rs | 638 + .../src/platform_impl/linux/mod.rs | 731 + .../platform_impl/linux/wayland/event_loop.rs | 1131 ++ .../platform_impl}/linux/wayland/keyboard.rs | 280 +- .../src/platform_impl}/linux/wayland/mod.rs | 15 +- .../platform_impl/linux/wayland/pointer.rs | 289 + .../src/platform_impl/linux/wayland/touch.rs | 132 + .../src/platform_impl/linux/wayland/window.rs | 555 + .../src/platform_impl}/linux/x11/dnd.rs | 58 +- .../linux/x11/event_processor.rs} | 1411 +- .../src/platform_impl/linux/x11/events.rs | 1008 ++ .../src/platform_impl/linux/x11/ffi.rs | 4 + .../platform_impl}/linux/x11/ime/callbacks.rs | 34 +- .../platform_impl}/linux/x11/ime/context.rs | 15 +- .../src/platform_impl}/linux/x11/ime/inner.rs | 13 +- .../linux/x11/ime/input_method.rs | 43 +- .../src/platform_impl}/linux/x11/ime/mod.rs | 46 +- .../src/platform_impl/linux/x11/mod.rs | 712 + .../src/platform_impl/linux/x11/monitor.rs | 314 + .../src/platform_impl}/linux/x11/util/atom.rs | 20 +- .../linux/x11/util/client_msg.rs | 46 + .../platform_impl/linux/x11/util/cursor.rs | 129 + .../platform_impl}/linux/x11/util/format.rs | 41 +- .../platform_impl}/linux/x11/util/geometry.rs | 154 +- .../src/platform_impl}/linux/x11/util/hint.rs | 218 +- .../src/platform_impl}/linux/x11/util/icon.rs | 15 +- .../src/platform_impl/linux/x11/util/input.rs | 190 + .../src/platform_impl/linux/x11/util/keys.rs | 92 + .../platform_impl}/linux/x11/util/memory.rs | 11 +- .../src/platform_impl}/linux/x11/util/mod.rs | 39 +- .../platform_impl/linux/x11/util/modifiers.rs | 187 + .../src/platform_impl/linux/x11/util/randr.rs | 220 + .../linux/x11/util/window_property.rs | 20 +- .../src/platform_impl}/linux/x11/util/wm.rs | 42 +- .../src/platform_impl/linux/x11/window.rs | 1328 ++ .../src/platform_impl}/linux/x11/xdisplay.rs | 54 +- .../platform_impl/macos/activation_hack.rs | 208 + .../src/platform_impl/macos/app.rs | 145 + .../src/platform_impl/macos/app_delegate.rs | 81 + .../src/platform_impl/macos/app_state.rs | 373 + .../src/platform_impl/macos/event.rs | 304 + .../src/platform_impl/macos/event_loop.rs | 158 + .../src/platform_impl/macos/ffi.rs | 209 + .../src/platform_impl/macos/mod.rs | 83 + .../src/platform_impl/macos/monitor.rs | 322 + .../src/platform_impl/macos/observer.rs | 242 + .../src/platform_impl/macos/util/async.rs | 216 + .../src/platform_impl/macos/util/cursor.rs | 164 + .../src/platform_impl/macos/util/mod.rs | 142 + .../src/platform_impl/macos/view.rs | 1060 ++ .../src/platform_impl/macos/window.rs | 1152 ++ .../platform_impl/macos/window_delegate.rs | 572 + .../winit-0.22.0/src/platform_impl/mod.rs | 40 + .../src/platform_impl/web/device.rs | 8 + .../src/platform_impl/web/error.rs | 10 + .../src/platform_impl/web/event_loop/mod.rs | 68 + .../src/platform_impl/web/event_loop/proxy.rs | 26 + .../platform_impl/web/event_loop/runner.rs | 295 + .../src/platform_impl/web/event_loop/state.rs | 40 + .../web/event_loop/window_target.rs | 216 + .../winit-0.22.0/src/platform_impl/web/mod.rs | 48 + .../src/platform_impl/web/monitor.rs | 51 + .../src/platform_impl/web/stdweb/canvas.rs | 301 + .../src/platform_impl/web/stdweb/event.rs | 229 + .../src/platform_impl/web/stdweb/mod.rs | 86 + .../src/platform_impl/web/stdweb/timeout.rs | 25 + .../src/platform_impl/web/web_sys/canvas.rs | 333 + .../src/platform_impl/web/web_sys/event.rs | 227 + .../src/platform_impl/web/web_sys/mod.rs | 106 + .../src/platform_impl/web/web_sys/timeout.rs | 40 + .../src/platform_impl/web/window.rs | 287 + .../src/platform_impl/windows/dark_mode.rs | 210 + .../src/platform_impl/windows/dpi.rs | 116 + .../platform_impl}/windows/drop_handler.rs | 107 +- .../src/platform_impl}/windows/event.rs | 262 +- .../src/platform_impl/windows/event_loop.rs | 1945 +++ .../windows/event_loop/runner.rs | 475 + .../src/platform_impl/windows/icon.rs | 169 + .../src/platform_impl}/windows/mod.rs | 36 +- .../src/platform_impl/windows/monitor.rs | 249 + .../src/platform_impl}/windows/raw_input.rs | 144 +- .../src/platform_impl/windows/util.rs | 298 + .../src/platform_impl/windows/window.rs | 897 + .../src/platform_impl/windows/window_state.rs | 368 + .../cargo/vendor/winit-0.22.0/src/window.rs | 870 + .../vendor/winit-0.22.0/tests/send_objects.rs | 27 + .../winit-0.22.0/tests/serde_objects.rs | 39 + .../vendor/winit-0.22.0/tests/sync_object.rs | 9 + .../ws2_32-sys-0.2.1/.cargo-checksum.json | 1 + .../BUILD | 15 +- .../cargo/vendor/ws2_32-sys-0.2.1/Cargo.toml | 17 + .../cargo/vendor/ws2_32-sys-0.2.1/README.md | 13 + .../cargo/vendor/ws2_32-sys-0.2.1/build.rs | 6 + .../cargo/vendor/ws2_32-sys-0.2.1/src/lib.rs | 483 + third_party/cargo/vendor/x11-dl-2.18.5/BUILD | 39 +- 1751 files changed, 178073 insertions(+), 142552 deletions(-) delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/Cargo.toml delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/README.rst delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/benches/arraystring.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/benches/extend.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/build.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/custom.css delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/array.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/array_string.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/char.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/errors.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/lib.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_nodrop.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_stable.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/src/range.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/tests/serde.rs delete mode 100644 third_party/cargo/vendor/arrayvec-0.4.12/tests/tests.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/BUILD delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/Cargo.lock delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/Cargo.toml delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/README.md delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/benches/benchmarks.rs delete mode 100755 third_party/cargo/vendor/backtrace-0.3.45/ci/android-ndk.sh delete mode 100755 third_party/cargo/vendor/backtrace-0.3.45/ci/android-sdk.sh delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-linux-android/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-unknown-linux-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-linux-androideabi/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-linux-androideabi/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i586-unknown-linux-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-linux-android/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-unknown-linux-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-linux-android/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-pc-windows-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-gnu/Dockerfile delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-musl/Dockerfile delete mode 100755 third_party/cargo/vendor/backtrace-0.3.45/ci/run-docker.sh delete mode 100755 third_party/cargo/vendor/backtrace-0.3.45/ci/run.sh delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/ci/runtest-android.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/examples/backtrace.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/examples/raw.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/dbghelp.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/libunwind.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/mod.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/noop.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/unix_backtrace.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/capture.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/dbghelp.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/lib.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/print.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/print/fuchsia.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/coresymbolication.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dbghelp.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr_resolve.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/gimli.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/libbacktrace.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/mod.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/noop.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/types.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/src/windows.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/auxiliary.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/main.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/concurrent-panics.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/long_fn_name.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/skip_inner_frames.rs delete mode 100644 third_party/cargo/vendor/backtrace-0.3.45/tests/smoke.rs delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/Cargo.toml delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/build.rs delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/android-api.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/lib.rs delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/LICENSE delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.am delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.in delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Mark.Twain-Tom.Sawyer.txt delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/README.md delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/acinclude.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/aclocal.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/alloc.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/atomic.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace-supported.h.in delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.h delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/btest.c delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.guess delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.h.in delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.sub delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/libtool.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltoptions.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltsugar.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltversion.m4 delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/lt~obsolete.m4 delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure.ac delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/dwarf.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest2.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/elf.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/fileline.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filenames.h delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filetype.awk delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/install-sh delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/internal.h delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ltmain.sh delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/macho.c delete mode 100755 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/missing delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmap.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmapio.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/move-if-change delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/nounwind.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/pecoff.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/posix.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/print.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/read.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/simple.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/sort.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/state.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/stest.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.h delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ttest.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/unknown.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/xcoff.c delete mode 100644 third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ztest.c create mode 100644 third_party/cargo/vendor/calloop-0.4.4/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/calloop-0.4.4/BUILD create mode 100644 third_party/cargo/vendor/calloop-0.4.4/CHANGELOG.md create mode 100644 third_party/cargo/vendor/calloop-0.4.4/Cargo.toml rename third_party/cargo/vendor/{num_cpus-1.12.0/LICENSE-MIT => calloop-0.4.4/LICENSE.txt} (96%) create mode 100644 third_party/cargo/vendor/calloop-0.4.4/README.md create mode 100644 third_party/cargo/vendor/calloop-0.4.4/README.tpl create mode 100644 third_party/cargo/vendor/calloop-0.4.4/doc_index.html create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/lib.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/list.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/loop_logic.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/sources/channel.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/sources/generic.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/sources/mod.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/sources/signals.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/src/sources/timer.rs create mode 100644 third_party/cargo/vendor/calloop-0.4.4/tests/signals.rs delete mode 100644 third_party/cargo/vendor/cocoa-0.18.5/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/cocoa-0.19.1/.cargo-checksum.json rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/BUILD (94%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/COPYRIGHT (100%) create mode 100644 third_party/cargo/vendor/cocoa-0.19.1/Cargo.lock rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/Cargo.toml (94%) rename third_party/cargo/vendor/{arrayvec-0.4.12 => cocoa-0.19.1}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/README.md (68%) create mode 100644 third_party/cargo/vendor/cocoa-0.19.1/examples/color.rs rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/examples/fullscreen.rs (97%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/examples/hello_world.rs (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/examples/tab_view.rs (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/src/appkit.rs (91%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/src/base.rs (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/src/foundation.rs (61%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/src/lib.rs (97%) create mode 100644 third_party/cargo/vendor/cocoa-0.19.1/src/macros.rs rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/src/quartzcore.rs (100%) rename third_party/cargo/vendor/{cocoa-0.18.5 => cocoa-0.19.1}/tests/foundation.rs (85%) create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/.cargo-checksum.json rename third_party/cargo/vendor/{objc-foundation-0.1.1 => cocoa-0.20.0}/BUILD (51%) create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/COPYRIGHT create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/Cargo.lock rename third_party/cargo/vendor/{num_cpus-1.12.0 => cocoa-0.20.0}/Cargo.toml (50%) rename third_party/cargo/vendor/{backtrace-0.3.45 => cocoa-0.20.0}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{semver-parser-0.7.0 => cocoa-0.20.0}/LICENSE-MIT (95%) create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/README.md create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/examples/color.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/examples/fullscreen.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/examples/hello_world.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/examples/tab_view.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/appkit.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/base.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/foundation.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/lib.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/macros.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/src/quartzcore.rs create mode 100644 third_party/cargo/vendor/cocoa-0.20.0/tests/foundation.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/BUILD create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/Cargo.toml rename third_party/cargo/vendor/{backtrace-sys-0.1.34 => core-foundation-0.7.0}/LICENSE-APACHE (100%) create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-MIT create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/array.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/attributed_string.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/base.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/boolean.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/bundle.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/characterset.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/data.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/date.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/dictionary.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/error.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/filedescriptor.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/lib.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/number.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/propertylist.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/runloop.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/set.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/string.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/timezone.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/url.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/src/uuid.rs create mode 100644 third_party/cargo/vendor/core-foundation-0.7.0/tests/use_macro_outside_crate.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/.cargo-checksum.json rename third_party/cargo/vendor/{semver-parser-0.7.0 => core-foundation-sys-0.7.0}/BUILD (87%) create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/Cargo.toml rename third_party/cargo/vendor/{cocoa-0.18.5 => core-foundation-sys-0.7.0}/LICENSE-APACHE (100%) create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-MIT create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/build.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/array.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/attributed_string.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/base.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/bundle.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/characterset.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/data.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/date.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/dictionary.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/error.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/filedescriptor.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/lib.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/messageport.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/number.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/propertylist.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/runloop.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/set.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/string.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/timezone.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/url.rs create mode 100644 third_party/cargo/vendor/core-foundation-sys-0.7.0/src/uuid.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/.cargo-checksum.json rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => core-graphics-0.19.0}/BUILD (70%) create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/COPYRIGHT create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/Cargo.toml rename third_party/cargo/vendor/{crossbeam-0.5.0 => core-graphics-0.19.0}/LICENSE-APACHE (100%) create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-MIT create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/README.md create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/base.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/color.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/color_space.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/context.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/data_provider.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/display.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/event.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/event_source.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/font.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/geometry.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/image.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/lib.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/path.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/private.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/sys.rs create mode 100644 third_party/cargo/vendor/core-graphics-0.19.0/src/window.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/.cargo-checksum.json rename third_party/cargo/vendor/{arrayvec-0.4.12 => core-video-sys-0.1.3}/BUILD (60%) create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/Cargo.toml rename third_party/cargo/vendor/{memoffset-0.2.1 => core-video-sys-0.1.3}/LICENSE (95%) create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/build.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/base.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/buffer.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/display_link.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/host_time.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/image_buffer.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/lib.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture_cache.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture_cache.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer_pool.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture_cache.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_io_surface.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_pool.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_format_description.rs create mode 100644 third_party/cargo/vendor/core-video-sys-0.1.3/src/return_.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/README.md delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/arc_cell.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/atomic_cell.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/lib.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/ms_queue.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/seg_queue.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/sharded_lock.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/treiber_stack.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/src/wait_group.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/tests/atomic_cell.rs delete mode 100644 third_party/cargo/vendor/crossbeam-0.5.0/tests/wait_group.rs create mode 100644 third_party/cargo/vendor/crossbeam-0.7.3/.cargo-checksum.json rename third_party/cargo/vendor/{crossbeam-0.5.0 => crossbeam-0.7.3}/BUILD (61%) rename third_party/cargo/vendor/{crossbeam-0.5.0 => crossbeam-0.7.3}/CHANGELOG.md (70%) rename third_party/cargo/vendor/{crossbeam-0.5.0 => crossbeam-0.7.3}/Cargo.toml (70%) rename third_party/cargo/vendor/{scopeguard-0.3.3 => crossbeam-0.7.3}/LICENSE-APACHE (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-0.7.3}/LICENSE-MIT (100%) create mode 100644 third_party/cargo/vendor/crossbeam-0.7.3/README.md create mode 100644 third_party/cargo/vendor/crossbeam-0.7.3/src/lib.rs rename third_party/cargo/vendor/{crossbeam-0.5.0 => crossbeam-0.7.3}/tests/subcrates.rs (66%) delete mode 100644 third_party/cargo/vendor/crossbeam-channel-0.3.9/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/crossbeam-channel-0.4.2/.cargo-checksum.json rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/BUILD (92%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/CHANGELOG.md (93%) create mode 100644 third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.lock rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/Cargo.toml (93%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-channel-0.4.2}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/LICENSE-THIRD-PARTY (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/README.md (94%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/benches/crossbeam.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/examples/fibonacci.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/examples/matching.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/examples/stopwatch.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/channel.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/context.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/counter.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/err.rs (96%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/after.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/array.rs (98%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/list.rs (96%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/mod.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/never.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/tick.rs (79%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/flavors/zero.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/lib.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/select.rs (97%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/select_macro.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/utils.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/src/waker.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/after.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/array.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/golang.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/iter.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/list.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/mpsc.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/never.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/ready.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/same_channel.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/select.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/select_macro.rs (99%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/thread_locals.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/tick.rs (100%) rename third_party/cargo/vendor/{crossbeam-channel-0.3.9 => crossbeam-channel-0.4.2}/tests/zero.rs (99%) delete mode 100644 third_party/cargo/vendor/crossbeam-deque-0.6.3/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/crossbeam-deque-0.6.3/src/lib.rs delete mode 100644 third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/fifo.rs delete mode 100644 third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/lifo.rs create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/.cargo-checksum.json rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => crossbeam-deque-0.7.3}/BUILD (72%) rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => crossbeam-deque-0.7.3}/CHANGELOG.md (68%) rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => crossbeam-deque-0.7.3}/Cargo.toml (82%) rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => crossbeam-deque-0.7.3}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-deque-0.7.3}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => crossbeam-deque-0.7.3}/README.md (80%) create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/src/lib.rs create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/fifo.rs create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/injector.rs create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/lifo.rs create mode 100644 third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/steal.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/BUILD delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/Cargo.toml delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/README.md delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/defer.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/flush.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/pin.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/examples/sanitize.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/atomic.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/collector.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/deferred.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/guard.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/internal.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/list.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/queue.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.7.2/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/default.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/epoch.rs delete mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/mod.rs create mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.8.2/.cargo-checksum.json rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/BUILD (85%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/CHANGELOG.md (77%) create mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.lock rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/Cargo.toml (89%) rename third_party/cargo/vendor/{crossbeam-epoch-0.6.1 => crossbeam-epoch-0.8.2}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{crossbeam-0.5.0 => crossbeam-epoch-0.8.2}/LICENSE-MIT (93%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/README.md (89%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/benches/defer.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/benches/flush.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/benches/pin.rs (100%) create mode 100644 third_party/cargo/vendor/crossbeam-epoch-0.8.2/build.rs rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/examples/sanitize.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/examples/treiber_stack.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/atomic.rs (99%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/collector.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.6.1 => crossbeam-epoch-0.8.2}/src/default.rs (98%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/deferred.rs (89%) rename third_party/cargo/vendor/{crossbeam-epoch-0.6.1 => crossbeam-epoch-0.8.2}/src/epoch.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/guard.rs (99%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/internal.rs (81%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/lib.rs (94%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/sync/list.rs (92%) rename third_party/cargo/vendor/{crossbeam-epoch-0.6.1 => crossbeam-epoch-0.8.2}/src/sync/mod.rs (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-epoch-0.8.2}/src/sync/queue.rs (90%) create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/BUILD create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/CHANGELOG.md create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/Cargo.toml rename third_party/cargo/vendor/{crossbeam-epoch-0.7.2 => crossbeam-queue-0.2.1}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{metal-0.13.1 => crossbeam-queue-0.2.1}/LICENSE-MIT (93%) create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-THIRD-PARTY create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/README.md create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/src/array_queue.rs create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/src/err.rs create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/src/lib.rs create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/src/seg_queue.rs create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/array_queue.rs create mode 100644 third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/seg_queue.rs delete mode 100644 third_party/cargo/vendor/crossbeam-utils-0.6.6/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/mod.rs create mode 100644 third_party/cargo/vendor/crossbeam-utils-0.7.2/.cargo-checksum.json rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/BUILD (93%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/CHANGELOG.md (83%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/Cargo.toml (95%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{arrayvec-0.4.12 => crossbeam-utils-0.7.2}/LICENSE-MIT (93%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/README.md (93%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/benches/atomic_cell.rs (100%) create mode 100644 third_party/cargo/vendor/crossbeam-utils-0.7.2/build.rs rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/atomic/atomic_cell.rs (85%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/atomic/consume.rs (100%) create mode 100644 third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/mod.rs create mode 100644 third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock.rs create mode 100644 third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock_wide.rs rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/backoff.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/cache_padded.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/lib.rs (94%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/sync/mod.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/sync/parker.rs (96%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/sync/sharded_lock.rs (96%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/sync/wait_group.rs (97%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/src/thread.rs (98%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/atomic_cell.rs (89%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/cache_padded.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/parker.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/sharded_lock.rs (100%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/thread.rs (97%) rename third_party/cargo/vendor/{crossbeam-utils-0.6.6 => crossbeam-utils-0.7.2}/tests/wait_group.rs (100%) create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/BUILD create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/Cargo.lock rename third_party/cargo/vendor/{owning_ref-0.4.1 => dispatch-0.2.0}/Cargo.toml (57%) create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/README.md create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/examples/main.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/ffi.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/group.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/lib.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/once.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/queue.rs create mode 100644 third_party/cargo/vendor/dispatch-0.2.0/src/sem.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD.gn rename third_party/cargo/vendor/{memoffset-0.2.1 => fuchsia-zircon-0.3.3}/Cargo.toml (61%) create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/LICENSE create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/README.md create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/examples/BUILD.gn create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/channel.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/cprng.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/event.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/eventpair.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/fifo.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/handle.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/job.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/lib.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/port.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/process.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/rights.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/signals.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/socket.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/status.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/thread.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/time.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/vmar.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/vmo.rs create mode 100755 third_party/cargo/vendor/fuchsia-zircon-0.3.3/tools/gen_status.py create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/.cargo-checksum.json rename third_party/cargo/vendor/{scopeguard-0.3.3 => fuchsia-zircon-sys-0.3.3}/BUILD (85%) create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/BUILD.gn create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/Cargo.toml create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/examples/hello.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/src/definitions.rs create mode 100644 third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3/src/lib.rs create mode 100644 third_party/cargo/vendor/instant-0.1.2/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/instant-0.1.2/AUTHORS create mode 100644 third_party/cargo/vendor/instant-0.1.2/BUILD create mode 100644 third_party/cargo/vendor/instant-0.1.2/Cargo.toml create mode 100644 third_party/cargo/vendor/instant-0.1.2/LICENSE create mode 100644 third_party/cargo/vendor/instant-0.1.2/README.md create mode 100644 third_party/cargo/vendor/instant-0.1.2/src/lib.rs create mode 100644 third_party/cargo/vendor/instant-0.1.2/src/native.rs create mode 100644 third_party/cargo/vendor/instant-0.1.2/src/wasm.rs create mode 100644 third_party/cargo/vendor/instant-0.1.2/tests/wasm.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/.cargo-checksum.json rename third_party/cargo/vendor/{num_cpus-1.12.0 => iovec-0.1.4}/BUILD (88%) create mode 100644 third_party/cargo/vendor/iovec-0.1.4/CHANGELOG.md rename third_party/cargo/vendor/{rustc-demangle-0.1.16 => iovec-0.1.4}/Cargo.toml (52%) rename third_party/cargo/vendor/{semver-0.9.0 => iovec-0.1.4}/LICENSE-APACHE (99%) rename third_party/cargo/vendor/{crossbeam-deque-0.6.3 => iovec-0.1.4}/LICENSE-MIT (96%) create mode 100644 third_party/cargo/vendor/iovec-0.1.4/README.md create mode 100644 third_party/cargo/vendor/iovec-0.1.4/appveyor.yml create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/lib.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/sys/mod.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/sys/unix.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/sys/unknown.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/sys/windows.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/unix.rs create mode 100644 third_party/cargo/vendor/iovec-0.1.4/src/windows.rs create mode 100644 third_party/cargo/vendor/kernel32-sys-0.2.2/.cargo-checksum.json rename third_party/cargo/vendor/{owning_ref-0.4.1 => kernel32-sys-0.2.2}/BUILD (74%) create mode 100644 third_party/cargo/vendor/kernel32-sys-0.2.2/Cargo.toml create mode 100644 third_party/cargo/vendor/kernel32-sys-0.2.2/README.md create mode 100644 third_party/cargo/vendor/kernel32-sys-0.2.2/build.rs create mode 100644 third_party/cargo/vendor/kernel32-sys-0.2.2/src/lib.rs create mode 100644 third_party/cargo/vendor/lazycell-1.2.1/.cargo-checksum.json rename third_party/cargo/vendor/{nodrop-0.1.14 => lazycell-1.2.1}/BUILD (93%) create mode 100644 third_party/cargo/vendor/lazycell-1.2.1/CHANGELOG.md rename third_party/cargo/vendor/{stable_deref_trait-1.1.1 => lazycell-1.2.1}/Cargo.toml (51%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lazycell-1.2.1}/LICENSE-APACHE (100%) create mode 100644 third_party/cargo/vendor/lazycell-1.2.1/LICENSE-MIT create mode 100644 third_party/cargo/vendor/lazycell-1.2.1/README.md create mode 100644 third_party/cargo/vendor/lazycell-1.2.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/lock_api-0.1.5/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/lock_api-0.3.3/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/lock_api-0.3.3/BUILD rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/Cargo.toml (84%) rename third_party/cargo/vendor/{metal-0.13.1 => lock_api-0.3.3}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/src/lib.rs (93%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/src/mutex.rs (82%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/src/remutex.rs (81%) rename third_party/cargo/vendor/{lock_api-0.1.5 => lock_api-0.3.3}/src/rwlock.rs (87%) delete mode 100644 third_party/cargo/vendor/memoffset-0.2.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/memoffset-0.2.1/README.md delete mode 100644 third_party/cargo/vendor/memoffset-0.2.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/memoffset-0.2.1/src/offset_of.rs delete mode 100644 third_party/cargo/vendor/memoffset-0.2.1/src/span_of.rs delete mode 100644 third_party/cargo/vendor/metal-0.13.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/metal-0.13.1/src/constants.rs delete mode 100644 third_party/cargo/vendor/metal-0.13.1/src/pipeline/mod.rs create mode 100644 third_party/cargo/vendor/metal-0.17.1/.cargo-checksum.json rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/BUILD (85%) create mode 100644 third_party/cargo/vendor/metal-0.17.1/Cargo.lock rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/Cargo.toml (86%) rename third_party/cargo/vendor/{nodrop-0.1.14 => metal-0.17.1}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{crossbeam-epoch-0.6.1 => metal-0.17.1}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/README.md (86%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/bors.toml (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/argument-buffer/main.rs (85%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/bind/main.rs (83%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/caps/main.rs (72%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/compute-argument-buffer.metal (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/compute-argument-buffer.rs (79%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/default.metallib (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/embedded-lib.rs (84%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/main.rs (75%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/compute/shaders.metal (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/library/main.rs (88%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/reflection/main.rs (75%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/window/default.metallib (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/window/main.rs (65%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/examples/window/shaders.metal (100%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/argument.rs (66%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/buffer.rs (56%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/capturemanager.rs (81%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/commandbuffer.rs (54%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/commandqueue.rs (65%) create mode 100644 third_party/cargo/vendor/metal-0.17.1/src/constants.rs rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/depthstencil.rs (67%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/device.rs (77%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/drawable.rs (88%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/encoder.rs (72%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/heap.rs (72%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/lib.rs (69%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/library.rs (63%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/pipeline/compute.rs (63%) create mode 100644 third_party/cargo/vendor/metal-0.17.1/src/pipeline/mod.rs rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/pipeline/render.rs (66%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/renderpass.rs (63%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/resource.rs (85%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/sampler.rs (67%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/texture.rs (58%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/types.rs (77%) rename third_party/cargo/vendor/{metal-0.13.1 => metal-0.17.1}/src/vertexdescriptor.rs (79%) create mode 100644 third_party/cargo/vendor/mio-0.6.21/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/mio-0.6.21/BUILD create mode 100644 third_party/cargo/vendor/mio-0.6.21/CHANGELOG.md create mode 100644 third_party/cargo/vendor/mio-0.6.21/Cargo.toml create mode 100644 third_party/cargo/vendor/mio-0.6.21/LICENSE create mode 100644 third_party/cargo/vendor/mio-0.6.21/README.md create mode 100644 third_party/cargo/vendor/mio-0.6.21/azure-pipelines.yml create mode 100644 third_party/cargo/vendor/mio-0.6.21/benches/bench_poll.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/ci/azure-cross-compile.yml create mode 100644 third_party/cargo/vendor/mio-0.6.21/ci/azure-deploy-docs.yml create mode 100644 third_party/cargo/vendor/mio-0.6.21/ci/azure-install-rust.yml create mode 100644 third_party/cargo/vendor/mio-0.6.21/ci/azure-test-stable.yml create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/channel.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/event_loop.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/handler.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/io.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/notify.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/deprecated/unix.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/event_imp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/io.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/lazycell.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/lib.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/net/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/net/tcp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/net/udp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/poll.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/awakener.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/eventedfd.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/handles.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/net.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/ready.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/selector.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/awakener.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/dlsym.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/epoll.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/eventedfd.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/io.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/kqueue.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/ready.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/tcp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/udp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uds.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uio.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/awakener.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/buffer_pool.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/from_raw_arc.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/selector.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/tcp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/sys/windows/udp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/timer.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/token.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/src/udp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/benchmark.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/mod.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_battery.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_broken_pipe.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_close_on_drop.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_custom_evented.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_double_register.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_echo_server.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_fuchsia_handles.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_local_addr_ready.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_multicast.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_notify.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_oneshot.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_poll.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_poll_channel.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_register_deregister.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_register_multiple_event_loops.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_reregister_without_poll.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_smoke.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_subprocess_pipe.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_tcp.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_tcp_level.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_tcp_shutdown.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_tick.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_udp_level.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_udp_socket.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_uds_shutdown.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_unix_echo_server.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_unix_pass_fd.rs create mode 100644 third_party/cargo/vendor/mio-0.6.21/test/test_write_then_drop.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/.cargo-checksum.json rename third_party/cargo/vendor/{lock_api-0.1.5 => mio-extras-2.0.6}/BUILD (63%) create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/CHANGELOG.md create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/Cargo.toml rename third_party/cargo/vendor/{rustc-demangle-0.1.16 => mio-extras-2.0.6}/LICENSE-APACHE (99%) rename third_party/cargo/vendor/{backtrace-sys-0.1.34 => mio-extras-2.0.6}/LICENSE-MIT (96%) create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/README.md create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/src/channel.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/src/lib.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/src/timer.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/test/mod.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/test/test_poll_channel.rs create mode 100644 third_party/cargo/vendor/mio-extras-2.0.6/test/test_timer.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/miow-0.2.1/BUILD create mode 100644 third_party/cargo/vendor/miow-0.2.1/Cargo.toml rename third_party/cargo/vendor/{num_cpus-1.12.0 => miow-0.2.1}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{backtrace-0.3.45 => miow-0.2.1}/LICENSE-MIT (100%) create mode 100644 third_party/cargo/vendor/miow-0.2.1/README.md create mode 100644 third_party/cargo/vendor/miow-0.2.1/appveyor.yml create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/handle.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/iocp.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/lib.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/net.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/overlapped.rs create mode 100644 third_party/cargo/vendor/miow-0.2.1/src/pipe.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/.cargo-checksum.json rename third_party/cargo/vendor/{stable_deref_trait-1.1.1 => net2-0.2.33}/BUILD (76%) create mode 100644 third_party/cargo/vendor/net2-0.2.33/Cargo.toml rename third_party/cargo/vendor/{parking_lot-0.6.4 => net2-0.2.33}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{rand-0.5.6 => net2-0.2.33}/LICENSE-MIT (100%) create mode 100644 third_party/cargo/vendor/net2-0.2.33/README.md create mode 100644 third_party/cargo/vendor/net2-0.2.33/appveyor.yml create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/ext.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/lib.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/socket.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/redox/impls.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/redox/mod.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/unix/impls.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/unix/mod.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/windows/impls.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/sys/windows/mod.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/tcp.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/udp.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/unix.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/src/utils.rs create mode 100644 third_party/cargo/vendor/net2-0.2.33/tests/all.rs delete mode 100644 third_party/cargo/vendor/nodrop-0.1.14/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/nodrop-0.1.14/Cargo.toml delete mode 100644 third_party/cargo/vendor/nodrop-0.1.14/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/nodrop-0.1.14/README.rst delete mode 100644 third_party/cargo/vendor/nodrop-0.1.14/src/lib.rs delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/CONTRIBUTING.md delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/README.md delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/examples/values.rs delete mode 100644 third_party/cargo/vendor/num_cpus-1.12.0/src/lib.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/Cargo.toml delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/examples/custom_class.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/examples/example.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/array.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/data.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/dictionary.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/enumerator.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/macros.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/object.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/string.rs delete mode 100644 third_party/cargo/vendor/objc-foundation-0.1.1/src/value.rs delete mode 100644 third_party/cargo/vendor/objc_id-0.1.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/objc_id-0.1.1/README.md delete mode 100644 third_party/cargo/vendor/objc_id-0.1.1/src/id.rs delete mode 100644 third_party/cargo/vendor/objc_id-0.1.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/owning_ref-0.4.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/owning_ref-0.4.1/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/owning_ref-0.4.1/README.md delete mode 100644 third_party/cargo/vendor/owning_ref-0.4.1/src/lib.rs create mode 100644 third_party/cargo/vendor/parking_lot-0.10.0/.cargo-checksum.json rename third_party/cargo/vendor/{parking_lot-0.6.4 => parking_lot-0.10.0}/BUILD (79%) create mode 100644 third_party/cargo/vendor/parking_lot-0.10.0/CHANGELOG.md rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/Cargo.toml (80%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{parking_lot-0.6.4 => parking_lot-0.10.0}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/README.md (90%) create mode 100644 third_party/cargo/vendor/parking_lot-0.10.0/appveyor.yml rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/condvar.rs (62%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/deadlock.rs (90%) create mode 100644 third_party/cargo/vendor/parking_lot-0.10.0/src/elision.rs rename third_party/cargo/vendor/{parking_lot-0.6.4 => parking_lot-0.10.0}/src/lib.rs (66%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/mutex.rs (92%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/once.rs (88%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/raw_mutex.rs (58%) create mode 100644 third_party/cargo/vendor/parking_lot-0.10.0/src/raw_rwlock.rs rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/remutex.rs (76%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot-0.10.0}/src/rwlock.rs (94%) rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => parking_lot-0.10.0}/src/util.rs (75%) delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/Cargo.toml delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/README.md delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/appveyor.yml delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/condvar.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/deadlock.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/elision.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/mutex.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/once.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/raw_mutex.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/raw_rwlock.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/remutex.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/rwlock.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.6.4/src/util.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/BUILD delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/appveyor.yml delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/src/elision.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/src/raw_rwlock.rs delete mode 100644 third_party/cargo/vendor/parking_lot-0.7.1/src/util.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/build.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/parking_lot.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/spinwait.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/generic.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/linux.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/keyed_event.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/waitaddress.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/Cargo.toml delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/build.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/lib.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/generic.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/unix.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/mod.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/waitaddress.rs delete mode 100644 third_party/cargo/vendor/parking_lot_core-0.4.0/src/word_lock.rs create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/.cargo-checksum.json rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/BUILD (76%) rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/Cargo.toml (80%) rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{parking_lot-0.7.1 => parking_lot_core-0.7.0}/LICENSE-MIT (100%) rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/src/lib.rs (66%) rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => parking_lot_core-0.7.0}/src/parking_lot.rs (58%) rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => parking_lot_core-0.7.0}/src/spinwait.rs (54%) create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/cloudabi.rs create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/generic.rs rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => parking_lot_core-0.7.0}/src/thread_parker/linux.rs (50%) create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/mod.rs create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/redox.rs create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/sgx.rs rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/src/thread_parker/unix.rs (71%) create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm.rs create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm_atomic.rs rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => parking_lot_core-0.7.0}/src/thread_parker/windows/keyed_event.rs (64%) rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/src/thread_parker/windows/mod.rs (63%) create mode 100644 third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/waitaddress.rs rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/src/util.rs (86%) rename third_party/cargo/vendor/{parking_lot_core-0.3.1 => parking_lot_core-0.7.0}/src/word_lock.rs (61%) delete mode 100644 third_party/cargo/vendor/percent-encoding-1.0.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/percent-encoding-1.0.1/lib.rs create mode 100644 third_party/cargo/vendor/percent-encoding-2.1.0/.cargo-checksum.json rename third_party/cargo/vendor/{percent-encoding-1.0.1 => percent-encoding-2.1.0}/BUILD (97%) rename third_party/cargo/vendor/{percent-encoding-1.0.1 => percent-encoding-2.1.0}/Cargo.toml (90%) rename third_party/cargo/vendor/{parking_lot_core-0.4.0 => percent-encoding-2.1.0}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{percent-encoding-1.0.1 => percent-encoding-2.1.0}/LICENSE-MIT (100%) create mode 100644 third_party/cargo/vendor/percent-encoding-2.1.0/lib.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/rand-0.5.6/BUILD delete mode 100644 third_party/cargo/vendor/rand-0.5.6/CHANGELOG.md delete mode 100644 third_party/cargo/vendor/rand-0.5.6/CONTRIBUTING.md delete mode 100644 third_party/cargo/vendor/rand-0.5.6/Cargo.toml delete mode 100644 third_party/cargo/vendor/rand-0.5.6/LICENSE-APACHE delete mode 100644 third_party/cargo/vendor/rand-0.5.6/README.md delete mode 100644 third_party/cargo/vendor/rand-0.5.6/UPDATING.md delete mode 100644 third_party/cargo/vendor/rand-0.5.6/appveyor.yml delete mode 100644 third_party/cargo/vendor/rand-0.5.6/benches/distributions.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/benches/generators.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/benches/misc.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/examples/monte-carlo.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/examples/monty-hall.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/bernoulli.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/binomial.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/cauchy.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/exponential.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/float.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/gamma.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/integer.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/log_gamma.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/mod.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/normal.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/other.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/pareto.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/poisson.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/uniform.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/distributions/ziggurat_tables.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/lib.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prelude.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/chacha.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/hc128.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/isaac.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/isaac64.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/isaac_array.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/mod.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/prng/xorshift.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/mod.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/read.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/reseeding.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/entropy.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/jitter.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/mock.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/mod.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/os.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/small.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/std.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/rngs/thread.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/src/seq.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/tests/bool.rs delete mode 100644 third_party/cargo/vendor/rand-0.5.6/utils/ci/install.sh delete mode 100644 third_party/cargo/vendor/rand-0.5.6/utils/ci/script.sh delete mode 100755 third_party/cargo/vendor/rand-0.5.6/utils/ziggurat_tables.py create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/BUILD create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/CHANGELOG.md create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/Cargo.toml rename third_party/cargo/vendor/{owning_ref-0.4.1 => raw-window-handle-0.3.3}/LICENSE (94%) create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/README.md rename third_party/cargo/vendor/{winit-0.18.1 => raw-window-handle-0.3.3}/appveyor.yml (85%) create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/rustfmt.toml create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/android.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/ios.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/lib.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/macos.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/unix.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/web.rs create mode 100644 third_party/cargo/vendor/raw-window-handle-0.3.3/src/windows.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/BUILD create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/Cargo.toml create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/LICENSE create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/README.md create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/aarch64.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/arm.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/nonredox.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86_64.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/call.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/data.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/error.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/flag.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/io/dma.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/io/io.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mmio.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mod.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/io/pio.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/lib.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/number.rs create mode 100755 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/generate.sh create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/mod.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block_mut.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_mut.rs create mode 100644 third_party/cargo/vendor/redox_syscall-0.1.56/src/tests.rs delete mode 100644 third_party/cargo/vendor/rustc-demangle-0.1.16/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/rustc-demangle-0.1.16/README.md delete mode 100644 third_party/cargo/vendor/rustc-demangle-0.1.16/src/legacy.rs delete mode 100644 third_party/cargo/vendor/rustc-demangle-0.1.16/src/lib.rs delete mode 100644 third_party/cargo/vendor/rustc-demangle-0.1.16/src/v0.rs delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/BUILD delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/Cargo.toml delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-APACHE delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/README.md delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/src/errors.rs delete mode 100644 third_party/cargo/vendor/rustc_version-0.2.3/src/lib.rs delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/Cargo.toml delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/README.rst delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/examples/readme.rs delete mode 100644 third_party/cargo/vendor/scopeguard-0.3.3/src/lib.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/semver-0.9.0/BUILD delete mode 100644 third_party/cargo/vendor/semver-0.9.0/Cargo.toml delete mode 100644 third_party/cargo/vendor/semver-0.9.0/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/semver-0.9.0/README.md delete mode 100644 third_party/cargo/vendor/semver-0.9.0/src/lib.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/src/version.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/src/version_req.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/tests/deprecation.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/tests/regression.rs delete mode 100644 third_party/cargo/vendor/semver-0.9.0/tests/serde.rs delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/Cargo.toml delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-APACHE delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/src/common.rs delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/src/lib.rs delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/src/range.rs delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/src/recognize.rs delete mode 100644 third_party/cargo/vendor/semver-parser-0.7.0/src/version.rs create mode 100644 third_party/cargo/vendor/slab-0.4.2/.cargo-checksum.json rename third_party/cargo/vendor/{rustc-demangle-0.1.16 => slab-0.4.2}/BUILD (85%) create mode 100644 third_party/cargo/vendor/slab-0.4.2/CHANGELOG.md rename third_party/cargo/vendor/{objc_id-0.1.1 => slab-0.4.2}/Cargo.toml (60%) rename third_party/cargo/vendor/{rustc-demangle-0.1.16/LICENSE-MIT => slab-0.4.2/LICENSE} (96%) create mode 100644 third_party/cargo/vendor/slab-0.4.2/README.md create mode 100644 third_party/cargo/vendor/slab-0.4.2/src/lib.rs create mode 100644 third_party/cargo/vendor/slab-0.4.2/tests/slab.rs delete mode 100644 third_party/cargo/vendor/smallvec-0.6.13/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/smallvec-0.6.13/LICENSE-APACHE delete mode 100644 third_party/cargo/vendor/smallvec-0.6.13/README.md create mode 100644 third_party/cargo/vendor/smallvec-1.2.0/.cargo-checksum.json rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/BUILD (83%) rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/Cargo.toml (88%) rename third_party/cargo/vendor/{percent-encoding-1.0.1 => smallvec-1.2.0}/LICENSE-APACHE (100%) rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/LICENSE-MIT (100%) create mode 100644 third_party/cargo/vendor/smallvec-1.2.0/README.md rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/benches/bench.rs (100%) rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/lib.rs (78%) rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/scripts/run_miri.sh (69%) rename third_party/cargo/vendor/{smallvec-0.6.13 => smallvec-1.2.0}/specialization.rs (78%) delete mode 100644 third_party/cargo/vendor/smithay-client-toolkit-0.4.6/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/smithay-client-toolkit-0.6.6/.cargo-checksum.json rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/BUILD (84%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/CHANGELOG.md (70%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/CONTRIBUTING.md (100%) create mode 100644 third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.lock rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/Cargo.toml (86%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/LICENSE.txt (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/README.md (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/doc_index.html (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/examples/compositor_info.rs (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/examples/image_viewer.rs (94%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/examples/kbd_input.rs (92%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/examples/pointer_input.rs (94%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/examples/selection.rs (93%) create mode 100644 third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/themed_frame.rs rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/data_device/data_device.rs (76%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/data_device/data_offer.rs (95%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/data_device/data_source.rs (76%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/data_device/mod.rs (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/env.rs (72%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/keyboard/ffi.rs (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/keyboard/keysyms.rs (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/keyboard/mod.rs (62%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/lib.rs (93%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/output.rs (86%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/pointer/mod.rs (66%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/pointer/theme.rs (57%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/shell/mod.rs (90%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/shell/wl.rs (80%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/shell/xdg.rs (67%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/shell/zxdg.rs (69%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/surface.rs (65%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/utils/mempool.rs (93%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/utils/mod.rs (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/window/basic_frame.rs (94%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/window/concept_frame.rs (65%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/src/window/mod.rs (83%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/travis_install_wayland.sh (100%) rename third_party/cargo/vendor/{smithay-client-toolkit-0.4.6 => smithay-client-toolkit-0.6.6}/update_keysyms.sh (100%) delete mode 100644 third_party/cargo/vendor/stable_deref_trait-1.1.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-APACHE delete mode 100644 third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-MIT delete mode 100644 third_party/cargo/vendor/stable_deref_trait-1.1.1/README.md delete mode 100644 third_party/cargo/vendor/stable_deref_trait-1.1.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/vk-sys-0.4.0/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/vk-sys-0.5.1/.cargo-checksum.json rename third_party/cargo/vendor/{vk-sys-0.4.0 => vk-sys-0.5.1}/BUILD (96%) rename third_party/cargo/vendor/{vk-sys-0.4.0 => vk-sys-0.5.1}/Cargo.toml (93%) rename third_party/cargo/vendor/{vk-sys-0.4.0 => vk-sys-0.5.1}/src/lib.rs (94%) delete mode 100644 third_party/cargo/vendor/vulkano-0.11.1/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/vulkano-0.18.0/.cargo-checksum.json rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/BUILD (83%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/Cargo.toml (86%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/build.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/alloc.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/cpu_access.rs (89%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/cpu_pool.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/device_local.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/immutable.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/slice.rs (90%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/sys.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/traits.rs (90%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/usage.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/buffer/view.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/auto.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/mod.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/pool/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/pool/standard.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/pool/sys.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/state_cacher.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/submit/bind_sparse.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/submit/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/submit/queue_present.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/submit/queue_submit.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/submit/semaphores_wait.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/synced/base.rs (87%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/synced/commands.rs (90%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/synced/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/synced/tests.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/sys.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/traits.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/blit_image.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/clear_color_image.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/copy_buffer.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/copy_image.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/copy_image_buffer.rs (77%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/descriptor_sets.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/dispatch.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/dynamic_state.rs (69%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/fill_buffer.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/index_buffer.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/push_constants.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/update_buffer.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/command_buffer/validity/vertex_buffers.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/collection.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/fixed_size_pool.rs (77%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/mod.rs (86%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/persistent.rs (87%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/std_pool.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/sys.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/descriptor_set/unsafe_layout.rs (87%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/mod.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/empty.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/limits_check.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/runtime_desc.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/sys.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/traits.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/tweaks.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/descriptor/pipeline_layout/union.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/device/extensions.rs (85%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/device/mod.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/extensions.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/features.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/format.rs (56%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/attachments_list.rs (77%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/compat_atch.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/desc.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/empty.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/framebuffer.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/macros.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/sys.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/framebuffer/traits.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/attachment.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/immutable.rs (91%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/layout.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/mod.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/storage.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/swapchain.rs (80%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/sys.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/traits.rs (83%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/image/usage.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/debug.rs (53%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/extensions.rs (90%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/instance.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/layers.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/limits.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/loader.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/instance/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/lib.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/device_memory.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/pool/host_visible.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/pool/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/pool/non_host_visible.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/memory/pool/pool.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/blend.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/cache.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/compute_pipeline.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/depth_stencil.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/graphics_pipeline/builder.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/graphics_pipeline/creation_error.rs (99%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/graphics_pipeline/mod.rs (88%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/graphics_pipeline/tests.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/input_assembly.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/multisample.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/raster.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/shader.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/bufferless.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/definition.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/impl_vertex.rs (86%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/instance_buffer.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/mod.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/one_one.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/single.rs (91%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/two.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/vertex/vertex.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/pipeline/viewport.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/query/mod.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sampler.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/capabilities.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/display.rs (97%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/mod.rs (94%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/present_region.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/surface.rs (93%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/swapchain/swapchain.rs (72%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/event.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/fence.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/future/fence_signal.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/future/join.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/future/mod.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/future/now.rs (92%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/future/semaphore_signal.rs (96%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/mod.rs (98%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/pipeline.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/sync/semaphore.rs (95%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/tests.rs (100%) rename third_party/cargo/vendor/{vulkano-0.11.1 => vulkano-0.18.0}/src/version.rs (100%) delete mode 100644 third_party/cargo/vendor/vulkano-win-0.11.1/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/vulkano-win-0.18.0/.cargo-checksum.json rename third_party/cargo/vendor/{vulkano-win-0.11.1 => vulkano-win-0.18.0}/BUILD (81%) rename third_party/cargo/vendor/{vulkano-win-0.11.1 => vulkano-win-0.18.0}/Cargo.toml (86%) rename third_party/cargo/vendor/{vulkano-win-0.11.1 => vulkano-win-0.18.0}/src/lib.rs (74%) delete mode 100644 third_party/cargo/vendor/wayland-client-0.21.13/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/wayland-client-0.21.13/build.rs delete mode 100644 third_party/cargo/vendor/wayland-client-0.21.13/examples/dynamic_globals.rs create mode 100644 third_party/cargo/vendor/wayland-client-0.23.6/.cargo-checksum.json rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/BUILD (82%) create mode 100644 third_party/cargo/vendor/wayland-client-0.23.6/Cargo.lock rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/Cargo.toml (87%) create mode 100644 third_party/cargo/vendor/wayland-client-0.23.6/build.rs create mode 100644 third_party/cargo/vendor/wayland-client-0.23.6/examples/dynamic_globals.rs rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/examples/list_globals.rs (100%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/examples/simple_window.rs (56%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/cursor.rs (72%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/display.rs (73%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/egl.rs (93%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/event_queue.rs (54%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/globals.rs (65%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/lib.rs (67%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/native_lib/display.rs (67%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/native_lib/event_queue.rs (99%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/native_lib/mod.rs (100%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/native_lib/proxy.rs (78%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/proxy.rs (51%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/rust_imp/connection.rs (73%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/rust_imp/display.rs (75%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/rust_imp/mod.rs (77%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/rust_imp/proxy.rs (90%) rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/src/rust_imp/queues.rs (79%) create mode 100644 third_party/cargo/vendor/wayland-client-0.23.6/src/sinks.rs rename third_party/cargo/vendor/{wayland-client-0.21.13 => wayland-client-0.23.6}/wayland.xml (93%) delete mode 100644 third_party/cargo/vendor/wayland-commons-0.21.13/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/wayland-commons-0.23.6/.cargo-checksum.json rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/BUILD (86%) create mode 100644 third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.lock rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/Cargo.toml (87%) rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/examples/manual_global_list.rs (100%) rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/src/lib.rs (85%) rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/src/map.rs (92%) create mode 100644 third_party/cargo/vendor/wayland-commons-0.23.6/src/sinks.rs rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/src/socket.rs (98%) rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/src/utils.rs (73%) rename third_party/cargo/vendor/{wayland-commons-0.21.13 => wayland-commons-0.23.6}/src/wire.rs (97%) delete mode 100644 third_party/cargo/vendor/wayland-protocols-0.21.13/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/wayland-protocols-0.21.13/build.rs delete mode 100644 third_party/cargo/vendor/wayland-protocols-0.21.13/src/protocol_macro.rs create mode 100644 third_party/cargo/vendor/wayland-protocols-0.23.6/.cargo-checksum.json rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/BUILD (79%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/Cargo.toml (77%) create mode 100644 third_party/cargo/vendor/wayland-protocols-0.23.6/build.rs create mode 100644 third_party/cargo/vendor/wayland-protocols-0.23.6/misc/gtk-primary-selection.xml rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/COPYING (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/Makefile.am (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/autogen.sh (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/configure.ac (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/m4/compat.m4 (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/presentation-time/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/presentation-time/presentation-time.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/viewporter/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/viewporter/viewporter.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/xdg-shell/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/stable/xdg-shell/xdg-shell.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/tests/scan.sh (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/fullscreen-shell/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/idle-inhibit/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/input-method/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/input-method/input-method-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/input-timestamps/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/keyboard-shortcuts-inhibit/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/linux-dmabuf/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/linux-explicit-synchronization/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/pointer-constraints/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/pointer-gestures/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/primary-selection/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/primary-selection/primary-selection-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/relative-pointer/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/tablet/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/tablet/tablet-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/tablet/tablet-unstable-v2.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/text-input/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/text-input/text-input-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/text-input/text-input-unstable-v3.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-decoration/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-foreign/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-output/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-output/xdg-output-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-shell/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xwayland-keyboard-grab/README (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/wayland-protocols-uninstalled.pc.in (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/protocols/wayland-protocols.pc.in (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/src/lib.rs (94%) create mode 100644 third_party/cargo/vendor/wayland-protocols-0.23.6/src/misc.rs create mode 100644 third_party/cargo/vendor/wayland-protocols-0.23.6/src/protocol_macro.rs rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/src/stable.rs (65%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/src/unstable.rs (98%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/src/wlr.rs (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/Makefile (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/check.sh (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml (73%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml (100%) rename third_party/cargo/vendor/{wayland-protocols-0.21.13 => wayland-protocols-0.23.6}/wlr-protocols/wlr-protocols.pc.in (100%) delete mode 100644 third_party/cargo/vendor/wayland-scanner-0.21.13/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/wayland-scanner-0.21.13/src/rust_code_gen.rs create mode 100644 third_party/cargo/vendor/wayland-scanner-0.23.6/.cargo-checksum.json rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/BUILD (97%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/Cargo.toml (95%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/c_code_gen.rs (83%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/c_interface_gen.rs (66%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/common_gen.rs (68%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/lib.rs (51%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/parse.rs (92%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/protocol.rs (94%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/side.rs (87%) rename third_party/cargo/vendor/{wayland-scanner-0.21.13 => wayland-scanner-0.23.6}/src/util.rs (84%) delete mode 100644 third_party/cargo/vendor/wayland-sys-0.21.13/.cargo-checksum.json create mode 100644 third_party/cargo/vendor/wayland-sys-0.23.6/.cargo-checksum.json rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/BUILD (95%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/Cargo.toml (88%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/client.rs (95%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/common.rs (98%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/cursor.rs (100%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/egl.rs (100%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/lib.rs (78%) rename third_party/cargo/vendor/{wayland-sys-0.21.13 => wayland-sys-0.23.6}/src/server.rs (96%) create mode 100644 third_party/cargo/vendor/winapi-0.2.8/.cargo-checksum.json rename third_party/cargo/vendor/{memoffset-0.2.1 => winapi-0.2.8}/BUILD (93%) create mode 100644 third_party/cargo/vendor/winapi-0.2.8/Cargo.toml create mode 100644 third_party/cargo/vendor/winapi-0.2.8/LICENSE.md create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/activation.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/audioclient.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/audiosessiontypes.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/basetsd.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/bcrypt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/cfg.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/cfgmgr32.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/combaseapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/commctrl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/commdlg.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/corsym.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d2d1.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d2dbasetypes.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d10shader.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d11.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d11shader.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d12.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d12sdklayers.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d12shader.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d9.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d9caps.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3d9types.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3dcommon.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/d3dcompiler.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dbghelp.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dcommon.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/devpropdef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/docobj.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dpapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dsgetdc.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dsound.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dsrole.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dwmapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dwrite.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_2.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_3.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_4.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgiformat.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/dxgitype.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/errhandlingapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/excpt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/fileapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/gl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/guiddef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/heapapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/hidclass.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/hidpi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/hidsdi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/hidusage.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/hstring.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/http.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/imm.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/inaddr.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/inspectable.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ksmedia.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lib.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/libloaderapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lmaccess.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lmcons.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lmdfs.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lmerrlog.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lmjoin.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/lsalookup.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/macros.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/memoryapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/minschannel.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/minwinbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/minwindef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/mmdeviceapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/mmreg.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/mmsystem.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/mscat.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/mssip.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/nb30.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ncrypt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ntdef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ntsecapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ntstatus.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/oaidl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/objbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/objidl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/objidlbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/olectl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/pdh.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/playsoundapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/processsnapshot.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/processthreadsapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/propidl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/propsys.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/prsht.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/psapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/qos.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/reason.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/restrictederrorinfo.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/roapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/roerrorapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/rpc.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/rpcdce.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/sapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/schannel.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/servprov.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/setupapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shellapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shellscalingapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shlguid.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shlobj.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shobjidl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/shtypes.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/spapidef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/sql.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/sqltypes.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/sspi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/strmif.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/subauth.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/synchapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/sysinfoapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/threadpoolapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/timezoneapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/tlhelp32.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/unknwnbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/urlhist.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/urlmon.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/usb.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/usbspec.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/usp10.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/vadefs.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/vsbackup.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/vss.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/vsserror.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/vswriter.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/werapi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wincon.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wincred.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wincrypt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/windef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/windowscodecs.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/windowsx.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winerror.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winevt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wingdi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winhttp.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winioctl.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winnetwk.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winnls.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winnt.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winreg.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winscard.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winsmcrd.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winsock2.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winspool.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winstring.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winsvc.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winusb.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winusbio.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/winuser.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ws2def.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ws2ipdef.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ws2spi.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/ws2tcpip.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wtypes.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/wtypesbase.rs create mode 100644 third_party/cargo/vendor/winapi-0.2.8/src/xinput.rs create mode 100644 third_party/cargo/vendor/winapi-build-0.1.1/.cargo-checksum.json rename third_party/cargo/vendor/{objc_id-0.1.1 => winapi-build-0.1.1}/BUILD (90%) create mode 100644 third_party/cargo/vendor/winapi-build-0.1.1/Cargo.toml create mode 100644 third_party/cargo/vendor/winapi-build-0.1.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/.cargo-checksum.json delete mode 100644 third_party/cargo/vendor/winit-0.18.1/CONTRIBUTING.md delete mode 100644 third_party/cargo/vendor/winit-0.18.1/README.md delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/cursor.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/cursor_grab.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/fullscreen.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/handling_close.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/min_max_size.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/monitor_list.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/multiwindow.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/proxy.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/resizable.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/transparent.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/examples/window_icon.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/dpi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/events.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/icon.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/lib.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/os/android.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/os/ios.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/os/unix.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/os/windows.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/android/ffi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/ffi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/ios/ffi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/ios/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/dlopen.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/event_loop.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/pointer.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/touch.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/events.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ffi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/monitor.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/client_msg.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/input.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/randr.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/events_loop.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/ffi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/monitor.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/cursor.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/into_option.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/view.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/macos/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/mod.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/dpi.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/events_loop.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/icon.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/monitor.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/util.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/platform/windows/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/src/window.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/tests/send_objects.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/tests/serde_objects.rs delete mode 100644 third_party/cargo/vendor/winit-0.18.1/tests/sync_object.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/.cargo-checksum.json rename third_party/cargo/vendor/{winit-0.18.1 => winit-0.22.0}/BUILD (58%) rename third_party/cargo/vendor/{winit-0.18.1 => winit-0.22.0}/CHANGELOG.md (56%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/CONTRIBUTING.md create mode 100644 third_party/cargo/vendor/winit-0.22.0/Cargo.lock rename third_party/cargo/vendor/{winit-0.18.1 => winit-0.22.0}/Cargo.toml (50%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/FEATURES.md create mode 100644 third_party/cargo/vendor/winit-0.22.0/HALL_OF_CHAMPIONS.md rename third_party/cargo/vendor/{winit-0.18.1 => winit-0.22.0}/LICENSE (100%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/README.md create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/control_flow.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/cursor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/cursor_grab.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/custom_events.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/fullscreen.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/handling_close.rs rename third_party/cargo/vendor/{winit-0.18.1 => winit-0.22.0}/examples/icon.png (100%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/min_max_size.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/minimize.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/monitor_list.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/multithreaded.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/multiwindow.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/request_redraw.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/request_redraw_threaded.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/resizable.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/timer.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/transparent.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/video_modes.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/web.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/window_debug.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/window_icon.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/examples/window_run_return.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/rustfmt.toml create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/dpi.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/error.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/event.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/event_loop.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/icon.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/lib.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/monitor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/android.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/desktop.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/ios.rs rename third_party/cargo/vendor/{winit-0.18.1/src/os => winit-0.22.0/src/platform}/macos.rs (62%) rename third_party/cargo/vendor/{winit-0.18.1/src/os => winit-0.22.0/src/platform}/mod.rs (61%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/unix.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/web.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform/windows.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/ffi.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/android/mod.rs (55%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/app_state.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/event_loop.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/ffi.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/monitor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/view.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/event_loop.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/wayland/keyboard.rs (60%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/wayland/mod.rs (65%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/pointer.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/touch.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/window.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/dnd.rs (87%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform/linux/x11/mod.rs => winit-0.22.0/src/platform_impl/linux/x11/event_processor.rs} (51%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/events.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ffi.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/ime/callbacks.rs (89%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/ime/context.rs (94%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/ime/inner.rs (87%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/ime/input_method.rs (91%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/ime/mod.rs (85%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/monitor.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/atom.rs (83%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/client_msg.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/cursor.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/format.rs (53%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/geometry.rs (75%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/hint.rs (53%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/icon.rs (63%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/input.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/keys.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/memory.rs (82%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/mod.rs (81%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/modifiers.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/randr.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/window_property.rs (89%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/util/wm.rs (79%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/window.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/linux/x11/xdisplay.rs (72%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/activation_hack.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_delegate.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_state.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event_loop.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/ffi.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/monitor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/observer.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/async.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/cursor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/view.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window_delegate.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/device.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/error.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/proxy.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/runner.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/state.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/window_target.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/monitor.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/canvas.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/event.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/timeout.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/canvas.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/event.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/mod.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/timeout.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dark_mode.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dpi.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/windows/drop_handler.rs (68%) rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/windows/event.rs (60%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop/runner.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/icon.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/windows/mod.rs (67%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/monitor.rs rename third_party/cargo/vendor/{winit-0.18.1/src/platform => winit-0.22.0/src/platform_impl}/windows/raw_input.rs (65%) create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/util.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window_state.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/src/window.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/tests/send_objects.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/tests/serde_objects.rs create mode 100644 third_party/cargo/vendor/winit-0.22.0/tests/sync_object.rs create mode 100644 third_party/cargo/vendor/ws2_32-sys-0.2.1/.cargo-checksum.json rename third_party/cargo/vendor/{backtrace-sys-0.1.34 => ws2_32-sys-0.2.1}/BUILD (81%) create mode 100644 third_party/cargo/vendor/ws2_32-sys-0.2.1/Cargo.toml create mode 100644 third_party/cargo/vendor/ws2_32-sys-0.2.1/README.md create mode 100644 third_party/cargo/vendor/ws2_32-sys-0.2.1/build.rs create mode 100644 third_party/cargo/vendor/ws2_32-sys-0.2.1/src/lib.rs diff --git a/engine/src/render/mod.rs b/engine/src/render/mod.rs index 9ba72f1..5e87a7a 100644 --- a/engine/src/render/mod.rs +++ b/engine/src/render/mod.rs @@ -4,11 +4,12 @@ use cgmath as cgm; use winit::{ dpi::LogicalSize, - Window, - WindowEvent, - WindowBuilder, - EventsLoop, - Event, + window::Window, + window::WindowBuilder, + event_loop::EventLoop, + event::Event, + event::WindowEvent, + platform::desktop::EventLoopExtDesktop, }; use vulkano_win::VkSurfaceBuild; use vulkano::instance as vi; @@ -21,8 +22,8 @@ const WIDTH: u32 = 800; const HEIGHT: u32 = 600; pub struct Renderer { - instance: vulkan::Instance, - events_loop: EventsLoop, + instance: vulkan::Instance, + events_loop: EventLoop<()>, } impl Renderer { @@ -37,11 +38,11 @@ impl Renderer { } } - fn init_window(instance: Arc) -> (EventsLoop, Arc>) { - let events_loop = EventsLoop::new(); + fn init_window(instance: Arc) -> (EventLoop<()>, Arc>) { + let events_loop = EventLoop::new(); let surface = WindowBuilder::new() .with_title("abrasion") - .with_dimensions(LogicalSize::new(f64::from(WIDTH), f64::from(HEIGHT))) + .with_inner_size(LogicalSize::new(f64::from(WIDTH), f64::from(HEIGHT))) .build_vk_surface(&events_loop, instance.clone()) .expect("could not create surface"); (events_loop, surface) @@ -53,10 +54,12 @@ impl Renderer { pub fn poll_close(&mut self) -> bool { let mut close = false; - self.events_loop.poll_events(|ev| { + // TODO(q3k): migrate to EventLoop::run + self.events_loop.run_return(|ev, _, control_flow| { if let Event::WindowEvent { event: WindowEvent::CloseRequested, .. } = ev { close = true; } + *control_flow = winit::event_loop::ControlFlow::Exit; }); return close; } diff --git a/engine/src/render/vulkan/data.rs b/engine/src/render/vulkan/data.rs index 484c560..8053dab 100644 --- a/engine/src/render/vulkan/data.rs +++ b/engine/src/render/vulkan/data.rs @@ -1,6 +1,6 @@ use cgmath as cgm; -#[derive(Copy, Clone)] +#[derive(Default, Copy, Clone)] pub struct Vertex { pos: [f32; 3], color: [f32; 3], @@ -15,6 +15,7 @@ impl Vertex { } vulkano::impl_vertex!(Vertex, pos, color); +#[derive(Default, Copy, Clone)] pub struct Instance { model: [f32; 16], } diff --git a/engine/src/render/vulkan/mod.rs b/engine/src/render/vulkan/mod.rs index f93acf5..a9853dd 100644 --- a/engine/src/render/vulkan/mod.rs +++ b/engine/src/render/vulkan/mod.rs @@ -25,7 +25,7 @@ const VERSION: vi::Version = vi::Version { major: 1, minor: 0, patch: 0}; fn required_instance_extensions() -> vi::InstanceExtensions { let mut exts = vulkano_win::required_extensions(); - exts.ext_debug_report = true; + exts.ext_debug_utils = true; exts } @@ -242,7 +242,8 @@ impl Instance { } let chain = self.swapchain_binding().chain.clone(); - let (image_index, acquire_future) = match vs::acquire_next_image(chain.clone(), None) { + // TODO(q3k): check the 'suboptimal' (second) bool + let (image_index, _, acquire_future) = match vs::acquire_next_image(chain.clone(), None) { Ok(r) => r, Err(vs::AcquireError::OutOfDate) => { self.armed = false; @@ -286,14 +287,12 @@ impl Instance { } fn init_debug_callback(instance: &Arc) -> vi::debug::DebugCallback { - let mt = vi::debug::MessageTypes { - error: true, - warning: true, - performance_warning: true, - information: true, - debug: true, + let mt = vi::debug::MessageType { + general: true, + validation: true, + performance: true, }; - vi::debug::DebugCallback::new(&instance, mt, |msg| { + vi::debug::DebugCallback::new(&instance, vi::debug::MessageSeverity::errors_and_warnings(), mt, |msg| { log::debug!("validation layer: {:?}", msg.description); }).expect("could not create debug callback") } diff --git a/engine/src/render/vulkan/pipeline.rs b/engine/src/render/vulkan/pipeline.rs index 8da661f..e583726 100644 --- a/engine/src/render/vulkan/pipeline.rs +++ b/engine/src/render/vulkan/pipeline.rs @@ -25,7 +25,7 @@ pub trait Pipeline { pub struct Forward { pipeline: Arc, - descriptor_set_pool: vdd::FixedSizeDescriptorSetsPool>, + descriptor_set_pool: vdd::FixedSizeDescriptorSetsPool, } impl Forward { @@ -122,7 +122,8 @@ impl Forward { .unwrap()) as Arc; - let descriptor_set_pool = vdd::FixedSizeDescriptorSetsPool::new(pipeline.clone(), 0); + let layout = pipeline.descriptor_set_layout(0).unwrap(); + let descriptor_set_pool = vdd::FixedSizeDescriptorSetsPool::new(layout.clone()); Forward { pipeline, diff --git a/engine/src/render/vulkan/swapchain_binding.rs b/engine/src/render/vulkan/swapchain_binding.rs index 84423bf..5aaa8a4 100644 --- a/engine/src/render/vulkan/swapchain_binding.rs +++ b/engine/src/render/vulkan/swapchain_binding.rs @@ -49,21 +49,41 @@ impl SwapchainBinding { Some(p) => Some(p.chain.clone()), }; - let (chain, images) = vs::Swapchain::new( - surface_binding.device.clone(), - surface_binding.surface.clone(), - image_count, - surface_format.0, - extent, - 1, - image_usage, - sharing, - capabilities.current_transform, - vs::CompositeAlpha::Opaque, - present_mode, - true, - prev.as_ref(), - ).expect("could not create swap chain"); + let (chain, images) = match prev.as_ref() { + None => vs::Swapchain::new( + surface_binding.device.clone(), + surface_binding.surface.clone(), + image_count, + surface_format.0, + extent, + 1, + image_usage, + sharing, + capabilities.current_transform, + vs::CompositeAlpha::Opaque, + present_mode, + vs::FullscreenExclusive::Default, + true, + vs::ColorSpace::SrgbNonLinear, + ), + Some(p) => vs::Swapchain::with_old_swapchain( + surface_binding.device.clone(), + surface_binding.surface.clone(), + image_count, + surface_format.0, + extent, + 1, + image_usage, + sharing, + capabilities.current_transform, + vs::CompositeAlpha::Opaque, + present_mode, + vs::FullscreenExclusive::Default, + true, + vs::ColorSpace::SrgbNonLinear, + p.clone(), + ), + }.expect("could not create swap chain"); log::info!("Swap chain: present mode {:?}, {} images", present_mode, images.len()); diff --git a/third_party/cargo/BUILD b/third_party/cargo/BUILD index 278ea71..48565aa 100644 --- a/third_party/cargo/BUILD +++ b/third_party/cargo/BUILD @@ -26,13 +26,13 @@ alias( ) alias( name = "vulkano", - actual = "//third_party/cargo/vendor/vulkano-0.11.1:vulkano", + actual = "//third_party/cargo/vendor/vulkano-0.18.0:vulkano", ) alias( name = "vulkano_win", - actual = "//third_party/cargo/vendor/vulkano-win-0.11.1:vulkano_win", + actual = "//third_party/cargo/vendor/vulkano-win-0.18.0:vulkano_win", ) alias( name = "winit", - actual = "//third_party/cargo/vendor/winit-0.18.1:winit", + actual = "//third_party/cargo/vendor/winit-0.22.0:winit", ) diff --git a/third_party/cargo/Cargo.lock b/third_party/cargo/Cargo.lock index 50165a9..6af31fb 100644 --- a/third_party/cargo/Cargo.lock +++ b/third_party/cargo/Cargo.lock @@ -38,15 +38,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "arrayvec" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9" -dependencies = [ - "nodrop", -] - [[package]] name = "arrayvec" version = "0.5.1" @@ -61,7 +52,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi", "libc", - "winapi", + "winapi 0.3.8", ] [[package]] @@ -76,28 +67,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" -[[package]] -name = "backtrace" -version = "0.3.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad235dabf00f36301792cfe82499880ba54c6486be094d1047b02bacb67c14e8" -dependencies = [ - "backtrace-sys", - "cfg-if", - "libc", - "rustc-demangle", -] - -[[package]] -name = "backtrace-sys" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca797db0057bae1a7aa2eef3283a874695455cecf08a43bfb8507ee0ebc1ed69" -dependencies = [ - "cc", - "libc", -] - [[package]] name = "bitflags" version = "1.2.1" @@ -116,6 +85,17 @@ version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" +[[package]] +name = "calloop" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa2097be53a00de9e8fc349fea6d76221f398f5c4fa550d420669906962d160" +dependencies = [ + "mio", + "mio-extras", + "nix", +] + [[package]] name = "cc" version = "1.0.50" @@ -136,7 +116,7 @@ checksum = "283944cdecc44bf0b8dd010ec9af888d3b4f142844fdbe026c20ef68148d6fe7" dependencies = [ "approx", "num-traits", - "rand 0.6.5", + "rand", ] [[package]] @@ -159,14 +139,29 @@ dependencies = [ [[package]] name = "cocoa" -version = "0.18.5" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706996401131526e36b3b49f0c4d912639ce110996f3ca144d78946727bce54" +checksum = "f29f7768b2d1be17b96158e3285951d366b40211320fb30826a76cb7a0da6400" dependencies = [ "bitflags", "block", - "core-foundation", - "core-graphics", + "core-foundation 0.6.4", + "core-graphics 0.17.3", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a4736c86d51bd878b474400d9ec888156f4037015f5d09794fab9f26eab1ad4" +dependencies = [ + "bitflags", + "block", + "core-foundation 0.7.0", + "core-graphics 0.19.0", "foreign-types", "libc", "objc", @@ -191,7 +186,17 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" dependencies = [ - "core-foundation-sys", + "core-foundation-sys 0.6.2", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" +dependencies = [ + "core-foundation-sys 0.7.0", "libc", ] @@ -201,6 +206,12 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" +[[package]] +name = "core-foundation-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" + [[package]] name = "core-graphics" version = "0.17.3" @@ -208,84 +219,113 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56790968ab1c8a1202a102e6de05fc6e1ec87da99e4e93e9a7d13efbfc1e95a9" dependencies = [ "bitflags", - "core-foundation", + "core-foundation 0.6.4", "foreign-types", "libc", ] [[package]] -name = "crossbeam" -version = "0.5.0" +name = "core-graphics" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c92ff2d7a202d592f5a412d75cf421495c913817781c1cb383bf12a77e185f" +checksum = "59e78b2e0aaf43f08e7ae0d6bc96895ef72ff0921c7d4ff4762201b2dba376dd" +dependencies = [ + "bitflags", + "core-foundation 0.7.0", + "foreign-types", + "libc", +] + +[[package]] +name = "core-video-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc065219542086f72d1e9f7aadbbab0989e980263695d129d502082d063a9d0" +dependencies = [ + "cfg-if", + "core-foundation-sys 0.6.2", + "core-graphics 0.17.3", + "libc", + "objc", +] + +[[package]] +name = "crossbeam" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" dependencies = [ "cfg-if", "crossbeam-channel", "crossbeam-deque", - "crossbeam-epoch 0.6.1", + "crossbeam-epoch", + "crossbeam-queue", "crossbeam-utils", - "lazy_static", - "num_cpus", - "parking_lot 0.6.4", ] [[package]] name = "crossbeam-channel" -version = "0.3.9" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ec7fcd21571dc78f96cc96243cab8d8f035247c3efd16c687be154c3fa9efa" +checksum = "cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061" dependencies = [ "crossbeam-utils", + "maybe-uninit", ] [[package]] name = "crossbeam-deque" -version = "0.6.3" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05e44b8cf3e1a625844d1750e1f7820da46044ff6d28f4d43e455ba3e5bb2c13" +checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" dependencies = [ - "crossbeam-epoch 0.7.2", + "crossbeam-epoch", "crossbeam-utils", + "maybe-uninit", ] [[package]] name = "crossbeam-epoch" -version = "0.6.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2449aaa4ec7ef96e5fb24db16024b935df718e9ae1cec0a1e68feeca2efca7b8" +checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ - "arrayvec 0.4.12", + "autocfg 1.0.0", "cfg-if", "crossbeam-utils", "lazy_static", - "memoffset 0.2.1", - "scopeguard 0.3.3", + "maybe-uninit", + "memoffset", + "scopeguard", ] [[package]] -name = "crossbeam-epoch" -version = "0.7.2" +name = "crossbeam-queue" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fedcd6772e37f3da2a9af9bf12ebe046c0dfe657992377b4df982a2b54cd37a9" +checksum = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" dependencies = [ - "arrayvec 0.4.12", "cfg-if", "crossbeam-utils", - "lazy_static", - "memoffset 0.5.4", - "scopeguard 1.1.0", ] [[package]] name = "crossbeam-utils" -version = "0.6.6" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" dependencies = [ + "autocfg 1.0.0", "cfg-if", "lazy_static", ] +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + [[package]] name = "dlib" version = "0.4.1" @@ -341,6 +381,22 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +dependencies = [ + "bitflags", + "fuchsia-zircon-sys", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" + [[package]] name = "half" version = "1.5.0" @@ -365,12 +421,43 @@ dependencies = [ "quick-error", ] +[[package]] +name = "instant" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c346c299e3fe8ef94dc10c2c0253d858a69aac1245157a3bf4125915d528caf" + +[[package]] +name = "iovec" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +dependencies = [ + "libc", +] + +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +[[package]] +name = "lazycell" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" + [[package]] name = "libc" version = "0.2.67" @@ -384,7 +471,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2b111a074963af1d37a139918ac6d49ad1d0d5e47f72fd55388619691a7d753" dependencies = [ "cc", - "winapi", + "winapi 0.3.8", ] [[package]] @@ -398,12 +485,11 @@ dependencies = [ [[package]] name = "lock_api" -version = "0.1.5" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c" +checksum = "79b2de95ecb4691949fea4716ca53cdbcfccb2c612e19644a8bad05edcf9f47b" dependencies = [ - "owning_ref", - "scopeguard 0.3.3", + "scopeguard", ] [[package]] @@ -443,15 +529,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" dependencies = [ "libc", - "winapi", + "winapi 0.3.8", ] -[[package]] -name = "memoffset" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3" - [[package]] name = "memoffset" version = "0.5.4" @@ -463,20 +543,71 @@ dependencies = [ [[package]] name = "metal" -version = "0.13.1" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7de9c2b83c946ab01c9942928388f911d93486b97636d9927541345905fea65d" +checksum = "f83c7dcc2038e12f68493fa3de44235df27b2497178e257185b4b5b5d028a1e4" dependencies = [ "bitflags", "block", - "cocoa", - "core-graphics", + "cocoa 0.19.1", + "core-graphics 0.17.3", "foreign-types", - "libc", "log", "objc", - "objc-foundation", - "objc_id", +] + +[[package]] +name = "mio" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302dec22bcf6bae6dfb69c647187f4b4d0fb6f535521f7bc022430ce8e12008f" +dependencies = [ + "cfg-if", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", +] + +[[package]] +name = "mio-extras" +version = "2.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" +dependencies = [ + "lazycell", + "log", + "mio", + "slab", +] + +[[package]] +name = "miow" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" +dependencies = [ + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", +] + +[[package]] +name = "net2" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" +dependencies = [ + "cfg-if", + "libc", + "winapi 0.3.8", ] [[package]] @@ -492,12 +623,6 @@ dependencies = [ "void", ] -[[package]] -name = "nodrop" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" - [[package]] name = "num-traits" version = "0.2.11" @@ -507,16 +632,6 @@ dependencies = [ "autocfg 1.0.0", ] -[[package]] -name = "num_cpus" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" -dependencies = [ - "hermit-abi", - "libc", -] - [[package]] name = "objc" version = "0.2.7" @@ -527,17 +642,6 @@ dependencies = [ "objc_exception", ] -[[package]] -name = "objc-foundation" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" -dependencies = [ - "block", - "objc", - "objc_id", -] - [[package]] name = "objc_exception" version = "0.1.2" @@ -547,15 +651,6 @@ dependencies = [ "cc", ] -[[package]] -name = "objc_id" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" -dependencies = [ - "objc", -] - [[package]] name = "openvr" version = "0.6.0" @@ -584,66 +679,35 @@ dependencies = [ "num-traits", ] -[[package]] -name = "owning_ref" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ff55baddef9e4ad00f88b6c743a2a8062d4c6ade126c2a528644b8e444d52ce" -dependencies = [ - "stable_deref_trait", -] - [[package]] name = "parking_lot" -version = "0.6.4" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0802bff09003b291ba756dc7e79313e51cc31667e94afbe847def490424cde5" +checksum = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc" dependencies = [ "lock_api", - "parking_lot_core 0.3.1", -] - -[[package]] -name = "parking_lot" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" -dependencies = [ - "lock_api", - "parking_lot_core 0.4.0", + "parking_lot_core", ] [[package]] name = "parking_lot_core" -version = "0.3.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad7f7e6ebdc79edff6fdcb87a55b620174f7a989e3eb31b65231f4af57f00b8c" +checksum = "7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1" dependencies = [ + "cfg-if", + "cloudabi", "libc", - "rand 0.5.6", - "rustc_version", + "redox_syscall", "smallvec", - "winapi", -] - -[[package]] -name = "parking_lot_core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" -dependencies = [ - "libc", - "rand 0.6.5", - "rustc_version", - "smallvec", - "winapi", + "winapi 0.3.8", ] [[package]] name = "percent-encoding" -version = "1.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" [[package]] name = "pkg-config" @@ -675,19 +739,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "rand" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9" -dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "winapi", -] - [[package]] name = "rand" version = "0.6.5" @@ -704,7 +755,7 @@ dependencies = [ "rand_os", "rand_pcg", "rand_xorshift", - "winapi", + "winapi 0.3.8", ] [[package]] @@ -758,7 +809,7 @@ checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" dependencies = [ "libc", "rand_core 0.4.2", - "winapi", + "winapi 0.3.8", ] [[package]] @@ -772,7 +823,7 @@ dependencies = [ "libc", "rand_core 0.4.2", "rdrand", - "winapi", + "winapi 0.3.8", ] [[package]] @@ -794,6 +845,15 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "raw-window-handle" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a441a7a6c80ad6473bd4b74ec1c9a4c951794285bf941c2126f607c72e48211" +dependencies = [ + "libc", +] + [[package]] name = "rdrand" version = "0.4.0" @@ -803,6 +863,12 @@ dependencies = [ "rand_core 0.3.1", ] +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" + [[package]] name = "regex" version = "1.3.5" @@ -821,21 +887,6 @@ version = "0.6.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae" -[[package]] -name = "rustc-demangle" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver", -] - [[package]] name = "rusttype" version = "0.7.9" @@ -852,7 +903,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14a911032fb5791ccbeec9f28fdcb9bf0983b81f227bafdfd227c658d0731c8a" dependencies = [ "approx", - "arrayvec 0.5.1", + "arrayvec", "ordered-float", "stb_truetype", ] @@ -866,33 +917,12 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scopeguard" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27" - [[package]] name = "scopeguard" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "shared_library" version = "0.1.9" @@ -904,19 +934,22 @@ dependencies = [ ] [[package]] -name = "smallvec" -version = "0.6.13" +name = "slab" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7b0758c52e15a8b5e3691eae6cc559f08eee9406e548a4477ba4e67770a82b6" -dependencies = [ - "maybe-uninit", -] +checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" + +[[package]] +name = "smallvec" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" [[package]] name = "smithay-client-toolkit" -version = "0.4.6" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ccb8c57049b2a34d2cc2b203fa785020ba0129d31920ef0d317430adaf748fa" +checksum = "421c8dc7acf5cb205b88160f8b4cc2c5cfabe210e43b2f80f009f4c1ef910f1d" dependencies = [ "andrew", "bitflags", @@ -925,16 +958,9 @@ dependencies = [ "memmap", "nix", "wayland-client", - "wayland-commons", "wayland-protocols", ] -[[package]] -name = "stable_deref_trait" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" - [[package]] name = "stb_truetype" version = "0.3.1" @@ -970,9 +996,9 @@ checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" [[package]] name = "vk-sys" -version = "0.4.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36f5fd4a7d6d5d19808610583131c0aed271556527cad4cb71c436831a28e059" +checksum = "c24c107c0402856ad434d2dc0f3dbdc68c9e170e8bab0f27aa82a282d234d57c" [[package]] name = "void" @@ -982,9 +1008,9 @@ checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" [[package]] name = "vulkano" -version = "0.11.1" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "715b3528d50119f2b7088479a79ff9d95416a6613d18c853d87ad98185ca43d1" +checksum = "1eb8a191577df4f71d70c31e5b69c56be2f3e88a87cbd6ad6e40ae06b38dc542" dependencies = [ "crossbeam", "fnv", @@ -997,11 +1023,11 @@ dependencies = [ [[package]] name = "vulkano-win" -version = "0.11.1" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07fffe247f37c8b051e8210ecfb6fe9a13bbb69e05ea61aceb1def5f709320ae" +checksum = "bc7e4c74bbf33d0c6b9f7e98f47068c62dc65d6a0721c0cb4b05fe4776c9af80" dependencies = [ - "cocoa", + "cocoa 0.20.0", "metal", "objc", "vulkano", @@ -1015,19 +1041,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" dependencies = [ "same-file", - "winapi", + "winapi 0.3.8", "winapi-util", ] [[package]] name = "wayland-client" -version = "0.21.13" +version = "0.23.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49963e5f9eeaf637bfcd1b9f0701c99fd5cd05225eb51035550d4272806f2713" +checksum = "af1080ebe0efabcf12aef2132152f616038f2d7dcbbccf7b2d8c5270fe14bcda" dependencies = [ "bitflags", + "calloop", "downcast-rs", "libc", + "mio", "nix", "wayland-commons", "wayland-scanner", @@ -1036,9 +1064,9 @@ dependencies = [ [[package]] name = "wayland-commons" -version = "0.21.13" +version = "0.23.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c08896768b667e1df195d88a62a53a2d1351a1ed96188be79c196b35bb32ec" +checksum = "bb66b0d1a27c39bbce712b6372131c6e25149f03ffb0cd017cf8f7de8d66dbdb" dependencies = [ "nix", "wayland-sys", @@ -1046,22 +1074,21 @@ dependencies = [ [[package]] name = "wayland-protocols" -version = "0.21.13" +version = "0.23.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4afde2ea2a428eee6d7d2c8584fdbe8b82eee8b6c353e129a434cd6e07f42145" +checksum = "6cc286643656742777d55dc8e70d144fa4699e426ca8e9d4ef454f4bf15ffcf9" dependencies = [ "bitflags", "wayland-client", "wayland-commons", "wayland-scanner", - "wayland-sys", ] [[package]] name = "wayland-scanner" -version = "0.21.13" +version = "0.23.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf3828c568714507315ee425a9529edc4a4aa9901409e373e9e0027e7622b79e" +checksum = "93b02247366f395b9258054f964fe293ddd019c3237afba9be2ccbe9e1651c3d" dependencies = [ "proc-macro2", "quote", @@ -1070,14 +1097,20 @@ dependencies = [ [[package]] name = "wayland-sys" -version = "0.21.13" +version = "0.23.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520ab0fd578017a0ee2206623ba9ef4afe5e8f23ca7b42f6acfba2f4e66b1628" +checksum = "d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4" dependencies = [ "dlib", "lazy_static", ] +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + [[package]] name = "winapi" version = "0.3.8" @@ -1088,6 +1121,12 @@ dependencies = [ "winapi-x86_64-pc-windows-gnu", ] +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" + [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" @@ -1100,7 +1139,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" dependencies = [ - "winapi", + "winapi 0.3.8", ] [[package]] @@ -1111,27 +1150,43 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "winit" -version = "0.18.1" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c57c15bd4c0ef18dff33e263e452abe32d00e2e05771cacaa410a14cc1c0776" +checksum = "02e9092b71b48ad6a0d98835a786308d10760cc09369d02e4a166608327f1f26" dependencies = [ "android_glue", - "backtrace", - "cocoa", - "core-foundation", - "core-graphics", + "bitflags", + "cocoa 0.19.1", + "core-foundation 0.6.4", + "core-graphics 0.17.3", + "core-video-sys", + "dispatch", + "instant", "lazy_static", "libc", "log", + "mio", + "mio-extras", "objc", - "parking_lot 0.7.1", + "parking_lot", "percent-encoding", + "raw-window-handle", "smithay-client-toolkit", "wayland-client", - "winapi", + "winapi 0.3.8", "x11-dl", ] +[[package]] +name = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + [[package]] name = "x11-dl" version = "2.18.5" diff --git a/third_party/cargo/Cargo.toml b/third_party/cargo/Cargo.toml index 38442a7..b00f80e 100644 --- a/third_party/cargo/Cargo.toml +++ b/third_party/cargo/Cargo.toml @@ -9,9 +9,9 @@ path = "fake_lib.rs" [dependencies] env_logger = "0.6.1" log = "0.4.6" -vulkano = "0.11.1" -vulkano-win = "0.11.1" -winit = "0.18.0" +vulkano = "0.18.0" +vulkano-win = "0.18.0" +winit = "0.22.0" cgmath = "0.17.0" openvr = "0.6.0" @@ -23,13 +23,13 @@ target = "x86_64-unknown-linux-gnu" skipped_deps = ['rusttype-0.7.9'] additional_deps = ['//third_party/cargo/vendor/rusttype-0.8.2:rusttype'] -[raze.crates.x11-dl.'2.18.4'] +[raze.crates.x11-dl.'2.18.5'] gen_buildrs = true -[raze.crates.wayland-client.'0.21.13'] +[raze.crates.wayland-client.'0.23.6'] gen_buildrs = true -[raze.crates.wayland-protocols.'0.21.13'] +[raze.crates.wayland-protocols.'0.23.6'] gen_buildrs = true [raze.crates.log.'0.4.8'] diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/.cargo-checksum.json b/third_party/cargo/vendor/arrayvec-0.4.12/.cargo-checksum.json deleted file mode 100644 index bc4b933..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"adb58f911fb48a1a3828bda514c2da5ce5650e8e98eb7217f014b1720fe11d38","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0245ee104228a100ce5fceecf43e25faae450494d9173f43fd94c27d69fdac13","README.rst":"a3cff166a7b622233cd9ccfbe472f910267629f4b41e387ad8573fc06eac37d6","benches/arraystring.rs":"f12b890977117ebde4ca42bcd6b91f2a6a087f2b235aaca6d15e30d125ae9f67","benches/extend.rs":"8c8f78df7e90b62c7e160cf5ea6c61b90bc4035a9704b6a179a1e01d8fafe2e9","build.rs":"fc29930f06cb4dde58f43d2f30b28c366ca3bafcd7e44b41a1c250d60fa900fb","custom.css":"e6f2cd299392337b4e2959c52f422e5b7be11920ea98d10db44d10ddef5ed47c","src/array.rs":"67fb063ee515bfd4968ede219dff81091a5935ef93529ebd1bb2a716ea3ed3d3","src/array_string.rs":"8a1a4cfc1699e2373815e57dc676a87a30629f91a9e861c866ccc6cb1381eadf","src/char.rs":"64a08f6a743b67bf2c96483f91c2fdaea79f6e91df5cd752f770b16a6b1d5b1e","src/errors.rs":"dde99bffaddfd45396aab7e07642cc018ef5435fe60c4f26a2c05a36555be18c","src/lib.rs":"34167f35d9a5b887e6fb424500bb64764d68d029d0e374827886b05ad4d26bca","src/maybe_uninit.rs":"7cca39ffe0f122716baaa174b433ff5fe9c93560f8e54fc077a0083500eaa1dd","src/maybe_uninit_nodrop.rs":"7fb2e24bf815dd6e1d104056fa9be4a11de7e0f0e5474742af186c580a6b47cc","src/maybe_uninit_stable.rs":"3f7daba622cf5df86992b451b46636a491c9611292f59969eb6890a10a00476d","src/range.rs":"65744ab7def208a1ab155ea2448fe9ea7fc14f33211361b1041f540125b32efd","tests/serde.rs":"ef3986a82656b09f3fbb14358e767051ffabe09592c61e69ea695cb88760e8ba","tests/tests.rs":"8066a4aca7b40356525ed87f7658773e610ef4fce3522b0cc0f301384d880f00"},"package":"cd9fd44efafa8690358b7408d253adf110036b88f55672a933f01d616ad9b1b9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/Cargo.toml b/third_party/cargo/vendor/arrayvec-0.4.12/Cargo.toml deleted file mode 100644 index f67c3c3..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/Cargo.toml +++ /dev/null @@ -1,62 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "arrayvec" -version = "0.4.12" -authors = ["bluss"] -description = "A vector with fixed capacity, backed by an array (it can be stored on the stack too). Implements fixed capacity ArrayVec and ArrayString." -documentation = "https://docs.rs/arrayvec/" -keywords = ["stack", "vector", "array", "data-structure", "no_std"] -categories = ["data-structures", "no-std"] -license = "MIT/Apache-2.0" -repository = "https://github.com/bluss/arrayvec" -[package.metadata.docs.rs] -features = ["serde-1"] - -[package.metadata.release] -no-dev-version = true -tag-name = "{{version}}" - -[[bench]] -name = "extend" -harness = false - -[[bench]] -name = "arraystring" -harness = false -[dependencies.nodrop] -version = "0.1.12" -default-features = false - -[dependencies.serde] -version = "1.0" -optional = true -default-features = false -[dev-dependencies.bencher] -version = "0.1.4" - -[dev-dependencies.matches] -version = "0.1" - -[dev-dependencies.serde_test] -version = "1.0" - -[build-dependencies] - -[features] -array-sizes-129-255 = [] -array-sizes-33-128 = [] -default = ["std"] -serde-1 = ["serde"] -std = [] -use_union = [] diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/README.rst b/third_party/cargo/vendor/arrayvec-0.4.12/README.rst deleted file mode 100644 index d20556a..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/README.rst +++ /dev/null @@ -1,224 +0,0 @@ - -arrayvec -======== - -A vector with fixed capacity. - -Please read the `API documentation here`__ - -__ https://docs.rs/arrayvec - -|build_status|_ |crates|_ |crates2|_ - -.. |build_status| image:: https://travis-ci.org/bluss/arrayvec.svg -.. _build_status: https://travis-ci.org/bluss/arrayvec - -.. |crates| image:: http://meritbadge.herokuapp.com/arrayvec -.. _crates: https://crates.io/crates/arrayvec - -.. |crates2| image:: http://meritbadge.herokuapp.com/nodrop -.. _crates2: https://crates.io/crates/nodrop - -Recent Changes (arrayvec) -------------------------- - -- 0.4.12 - - - Use raw pointers instead of ``get_unchecked_mut`` where the target may be - uninitialized a everywhere relevant in the ArrayVec implementation. - -- 0.4.11 - - - In Rust 1.36 or later, use newly stable MaybeUninit. This extends the - soundness work introduced in 0.4.9, we are finally able to use this in - stable. We use feature detection (build script) to enable this at build - time. - -- 0.4.10 - - - Use ``repr(C)`` in the ``union`` version that was introduced in 0.4.9, to - allay some soundness concerns. - -- 0.4.9 - - - Use ``union`` in the implementation on when this is detected to be supported - (nightly only for now). This is a better solution for treating uninitialized - regions correctly, and we'll use it in stable Rust as soon as we are able. - When this is enabled, the ``ArrayVec`` has no space overhead in its memory - layout, although the size of the vec should not be relied upon. (See `#114`_) - - ``ArrayString`` updated to not use uninitialized memory, it instead zeros its - backing array. This will be refined in the next version, since we - need to make changes to the user visible API. - - The ``use_union`` feature now does nothing (like its documentation foretold). - -.. _`#114`: https://github.com/bluss/arrayvec/pull/114 - -- 0.4.8 - - - Implement Clone and Debug for ``IntoIter`` by @clarcharr - - Add more array sizes under crate features. These cover all in the range - up to 128 and 129 to 255 respectively (we have a few of those by default): - - - ``array-size-33-128`` - - ``array-size-129-255`` - -- 0.4.7 - - - Fix future compat warning about raw pointer casts - - Use ``drop_in_place`` when dropping the arrayvec by-value iterator - - Decrease mininum Rust version (see docs) by @jeehoonkang - -- 0.3.25 - - - Fix future compat warning about raw pointer casts - -- 0.4.6 - - - Fix compilation on 16-bit targets. This means, the 65536 array size is not - included on these targets. - -- 0.3.24 - - - Fix compilation on 16-bit targets. This means, the 65536 array size is not - included on these targets. - - Fix license files so that they are both included (was fixed in 0.4 before) - -- 0.4.5 - - - Add methods to ``ArrayString`` by @DenialAdams: - - - ``.pop() -> Option`` - - ``.truncate(new_len)`` - - ``.remove(index) -> char`` - - - Remove dependency on crate odds - - Document debug assertions in unsafe methods better - -- 0.4.4 - - - Add method ``ArrayVec::truncate()`` by @niklasf - -- 0.4.3 - - - Improve performance for ``ArrayVec::extend`` with a lower level - implementation (#74) - - Small cleanup in dependencies (use no std for crates where we don't need more) - -- 0.4.2 - - - Add constructor method ``new`` to ``CapacityError``. - -- 0.4.1 - - - Add ``Default`` impl to ``ArrayString`` by @tbu- - -- 0.4.0 - - - Reformed signatures and error handling by @bluss and @tbu-: - - - ``ArrayVec``'s ``push, insert, remove, swap_remove`` now match ``Vec``'s - corresponding signature and panic on capacity errors where applicable. - - Add fallible methods ``try_push, insert`` and checked methods - ``pop_at, swap_pop``. - - Similar changes to ``ArrayString``'s push methods. - - - Use a local version of the ``RangeArgument`` trait - - Add array sizes 50, 150, 200 by @daboross - - Support serde 1.0 by @daboross - - New method ``.push_unchecked()`` by @niklasf - - ``ArrayString`` implements ``PartialOrd, Ord`` by @tbu- - - Require Rust 1.14 - - crate feature ``use_generic_array`` was dropped. - -- 0.3.23 - - - Implement ``PartialOrd, Ord`` as well as ``PartialOrd`` for - ``ArrayString``. - -- 0.3.22 - - - Implement ``Array`` for the 65536 size - -- 0.3.21 - - - Use ``encode_utf8`` from crate odds - - Add constructor ``ArrayString::from_byte_string`` - -- 0.3.20 - - - Simplify and speed up ``ArrayString``’s ``.push(char)``- - -- 0.3.19 - - - Add new crate feature ``use_generic_array`` which allows using their - ``GenericArray`` just like a regular fixed size array for the storage - of an ``ArrayVec``. - -- 0.3.18 - - - Fix bounds check in ``ArrayVec::insert``! - It would be buggy if ``self.len() < index < self.capacity()``. Take note of - the push out behavior specified in the docs. - -- 0.3.17 - - - Added crate feature ``use_union`` which forwards to the nodrop crate feature - - Added methods ``.is_full()`` to ``ArrayVec`` and ``ArrayString``. - -- 0.3.16 - - - Added method ``.retain()`` to ``ArrayVec``. - - Added methods ``.as_slice(), .as_mut_slice()`` to ``ArrayVec`` and ``.as_str()`` - to ``ArrayString``. - -- 0.3.15 - - - Add feature std, which you can opt out of to use ``no_std`` (requires Rust 1.6 - to opt out). - - Implement ``Clone::clone_from`` for ArrayVec and ArrayString - -- 0.3.14 - - - Add ``ArrayString::from(&str)`` - -- 0.3.13 - - - Added ``DerefMut`` impl for ``ArrayString``. - - Added method ``.simplify()`` to drop the element for ``CapacityError``. - - Added method ``.dispose()`` to ``ArrayVec`` - -- 0.3.12 - - - Added ArrayString, a fixed capacity analogy of String - -- 0.3.11 - - - Added trait impls Default, PartialOrd, Ord, Write for ArrayVec - -- 0.3.10 - - - Go back to using external NoDrop, fixing a panic safety bug (issue #3) - -- 0.3.8 - - - Inline the non-dropping logic to remove one drop flag in the - ArrayVec representation. - -- 0.3.7 - - - Added method .into_inner() - - Added unsafe method .set_len() - - -License -======= - -Dual-licensed to be compatible with the Rust project. - -Licensed under the Apache License, Version 2.0 -http://www.apache.org/licenses/LICENSE-2.0 or the MIT license -http://opensource.org/licenses/MIT, at your -option. This file may not be copied, modified, or distributed -except according to those terms. - - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/benches/arraystring.rs b/third_party/cargo/vendor/arrayvec-0.4.12/benches/arraystring.rs deleted file mode 100644 index 9cff587..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/benches/arraystring.rs +++ /dev/null @@ -1,90 +0,0 @@ - -extern crate arrayvec; -#[macro_use] extern crate bencher; - -use arrayvec::ArrayString; - -use bencher::Bencher; - -fn try_push_c(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - b.iter(|| { - v.clear(); - while v.try_push('c').is_ok() { - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -fn try_push_alpha(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - b.iter(|| { - v.clear(); - while v.try_push('α').is_ok() { - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -// Yes, pushing a string char-by-char is slow. Use .push_str. -fn try_push_string(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - let input = "abcαβγ“”"; - b.iter(|| { - v.clear(); - for ch in input.chars().cycle() { - if !v.try_push(ch).is_ok() { - break; - } - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -fn push_c(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - b.iter(|| { - v.clear(); - while !v.is_full() { - v.push('c'); - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -fn push_alpha(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - b.iter(|| { - v.clear(); - while !v.is_full() { - v.push('α'); - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -fn push_string(b: &mut Bencher) { - let mut v = ArrayString::<[u8; 512]>::new(); - let input = "abcαβγ“”"; - b.iter(|| { - v.clear(); - for ch in input.chars().cycle() { - if !v.is_full() { - v.push(ch); - } else { - break; - } - } - v.len() - }); - b.bytes = v.capacity() as u64; -} - -benchmark_group!(benches, try_push_c, try_push_alpha, try_push_string, push_c, - push_alpha, push_string); -benchmark_main!(benches); diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/benches/extend.rs b/third_party/cargo/vendor/arrayvec-0.4.12/benches/extend.rs deleted file mode 100644 index d380a7e..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/benches/extend.rs +++ /dev/null @@ -1,43 +0,0 @@ - -extern crate arrayvec; -#[macro_use] extern crate bencher; - -use arrayvec::ArrayVec; - -use bencher::Bencher; - -fn extend_with_constant(b: &mut Bencher) { - let mut v = ArrayVec::<[u8; 512]>::new(); - let cap = v.capacity(); - b.iter(|| { - v.clear(); - v.extend((0..cap).map(|_| 1)); - v[0] - }); - b.bytes = v.capacity() as u64; -} - -fn extend_with_range(b: &mut Bencher) { - let mut v = ArrayVec::<[u8; 512]>::new(); - let cap = v.capacity(); - b.iter(|| { - v.clear(); - v.extend((0..cap).map(|x| x as _)); - v[0] - }); - b.bytes = v.capacity() as u64; -} - -fn extend_with_slice(b: &mut Bencher) { - let mut v = ArrayVec::<[u8; 512]>::new(); - let data = [1; 512]; - b.iter(|| { - v.clear(); - v.extend(data.iter().cloned()); - v[0] - }); - b.bytes = v.capacity() as u64; -} - -benchmark_group!(benches, extend_with_constant, extend_with_range, extend_with_slice); -benchmark_main!(benches); diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/build.rs b/third_party/cargo/vendor/arrayvec-0.4.12/build.rs deleted file mode 100644 index a91c5f4..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/build.rs +++ /dev/null @@ -1,90 +0,0 @@ - -use std::env; -use std::io::Write; -use std::process::{Command, Stdio}; - -fn main() { - // we need to output *some* file to opt out of the default - println!("cargo:rerun-if-changed=build.rs"); - - detect_maybe_uninit(); -} - -fn detect_maybe_uninit() { - let has_stable_maybe_uninit = probe(&stable_maybe_uninit()); - if has_stable_maybe_uninit { - println!("cargo:rustc-cfg=has_stable_maybe_uninit"); - return; - } - let has_unstable_union_with_md = probe(&maybe_uninit_code(true)); - if has_unstable_union_with_md { - println!("cargo:rustc-cfg=has_manually_drop_in_union"); - println!("cargo:rustc-cfg=has_union_feature"); - } -} - -// To guard against changes in this currently unstable feature, use -// a detection tests instead of a Rustc version and/or date test. -fn stable_maybe_uninit() -> String { - let code = " - #![allow(warnings)] - use std::mem::MaybeUninit; - - fn main() { } - "; - code.to_string() -} - -// To guard against changes in this currently unstable feature, use -// a detection tests instead of a Rustc version and/or date test. -fn maybe_uninit_code(use_feature: bool) -> String { - let feature = if use_feature { "#![feature(untagged_unions)]" } else { "" }; - - let code = " - #![allow(warnings)] - use std::mem::ManuallyDrop; - - #[derive(Copy)] - pub union MaybeUninit { - empty: (), - value: ManuallyDrop, - } - - impl Clone for MaybeUninit where T: Copy - { - fn clone(&self) -> Self { *self } - } - - fn main() { - let value1 = MaybeUninit::<[i32; 3]> { empty: () }; - let value2 = MaybeUninit { value: ManuallyDrop::new([1, 2, 3]) }; - } - "; - - - [feature, code].concat() -} - -/// Test if a code snippet can be compiled -fn probe(code: &str) -> bool { - let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); - let out_dir = env::var_os("OUT_DIR").expect("environment variable OUT_DIR"); - - let mut child = Command::new(rustc) - .arg("--out-dir") - .arg(out_dir) - .arg("--emit=obj") - .arg("-") - .stdin(Stdio::piped()) - .spawn() - .expect("rustc probe"); - - child - .stdin - .as_mut() - .expect("rustc stdin") - .write_all(code.as_bytes()) - .expect("write rustc stdin"); - - child.wait().expect("rustc probe").success() -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/custom.css b/third_party/cargo/vendor/arrayvec-0.4.12/custom.css deleted file mode 100644 index 8e0b705..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/custom.css +++ /dev/null @@ -1,25 +0,0 @@ - -.docblock pre.rust { background: #eeeeff; } -pre.trait, pre.fn, pre.struct, pre.enum, pre.typedef { background: #fcfefc; } - -/* Small “example” label for doc examples */ -.docblock pre.rust::before { - content: "example"; - float: right; - font-style: italic; - font-size: 0.8em; - margin-top: -10px; - margin-right: -5px; -} - - -/* Fixup where display in trait listing */ -pre.trait .where::before { -content: '\a '; -} - -.docblock code { - background-color: inherit; - font-weight: bold; - padding: 0 0.1em; -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/array.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/array.rs deleted file mode 100644 index 4f099a6..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/array.rs +++ /dev/null @@ -1,137 +0,0 @@ - -/// Trait for fixed size arrays. -/// -/// This trait is implemented for some specific array sizes, see -/// the implementor list below. At the current state of Rust we can't -/// make this fully general for every array size. -/// -/// The following crate features add more array sizes (and they are not -/// enabled by default due to their impact on compliation speed). -/// -/// - `array-sizes-33-128`: All sizes 33 to 128 are implemented -/// (a few in this range are included by default). -/// - `array-sizes-129-255`: All sizes 129 to 255 are implemented -/// (a few in this range are included by default). -pub unsafe trait Array { - /// The array’s element type - type Item; - #[doc(hidden)] - /// The smallest index type that indexes the array. - type Index: Index; - #[doc(hidden)] - fn as_ptr(&self) -> *const Self::Item; - #[doc(hidden)] - fn as_mut_ptr(&mut self) -> *mut Self::Item; - #[doc(hidden)] - fn capacity() -> usize; -} - -pub trait Index : PartialEq + Copy { - fn to_usize(self) -> usize; - fn from(usize) -> Self; -} - -use std::slice::{from_raw_parts}; - -pub trait ArrayExt : Array { - #[inline(always)] - fn as_slice(&self) -> &[Self::Item] { - unsafe { - from_raw_parts(self.as_ptr(), Self::capacity()) - } - } -} - -impl ArrayExt for A where A: Array { } - -impl Index for u8 { - #[inline(always)] - fn to_usize(self) -> usize { self as usize } - #[inline(always)] - fn from(ix: usize) -> Self { ix as u8 } -} - -impl Index for u16 { - #[inline(always)] - fn to_usize(self) -> usize { self as usize } - #[inline(always)] - fn from(ix: usize) -> Self { ix as u16 } -} - -impl Index for u32 { - #[inline(always)] - fn to_usize(self) -> usize { self as usize } - #[inline(always)] - fn from(ix: usize) -> Self { ix as u32 } -} - -impl Index for usize { - #[inline(always)] - fn to_usize(self) -> usize { self } - #[inline(always)] - fn from(ix: usize) -> Self { ix } -} - -macro_rules! fix_array_impl { - ($index_type:ty, $len:expr ) => ( - unsafe impl Array for [T; $len] { - type Item = T; - type Index = $index_type; - #[doc(hidden)] - #[inline(always)] - fn as_ptr(&self) -> *const T { self as *const _ as *const _ } - #[doc(hidden)] - #[inline(always)] - fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _} - #[doc(hidden)] - #[inline(always)] - fn capacity() -> usize { $len } - } - ) -} - -macro_rules! fix_array_impl_recursive { - ($index_type:ty, ) => (); - ($index_type:ty, $($len:expr,)*) => ( - $(fix_array_impl!($index_type, $len);)* - ); -} - -fix_array_impl_recursive!(u8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 28, 29, 30, 31, ); - -#[cfg(not(feature="array-sizes-33-128"))] -fix_array_impl_recursive!(u8, 32, 40, 48, 50, 56, 64, 72, 96, 100, 128, ); - -#[cfg(feature="array-sizes-33-128")] -fix_array_impl_recursive!(u8, -32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, -72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, -92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, -109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, -125, 126, 127, 128, -); - -#[cfg(not(feature="array-sizes-129-255"))] -fix_array_impl_recursive!(u8, 160, 192, 200, 224,); - -#[cfg(feature="array-sizes-129-255")] -fix_array_impl_recursive!(u8, -129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, -141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, -157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, -173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, -189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, -205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, -221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, -237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, -253, 254, 255, -); - -fix_array_impl_recursive!(u16, 256, 384, 512, 768, 1024, 2048, 4096, 8192, 16384, 32768,); -// This array size doesn't exist on 16-bit -#[cfg(any(target_pointer_width="32", target_pointer_width="64"))] -fix_array_impl_recursive!(u32, 1 << 16,); - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/array_string.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/array_string.rs deleted file mode 100644 index 6cd1c65..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/array_string.rs +++ /dev/null @@ -1,516 +0,0 @@ -use std::borrow::Borrow; -use std::cmp; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::mem; -use std::ptr; -use std::ops::{Deref, DerefMut}; -use std::str; -use std::str::Utf8Error; -use std::slice; - -use array::{Array, ArrayExt}; -use array::Index; -use CapacityError; -use char::encode_utf8; - -#[cfg(feature="serde-1")] -use serde::{Serialize, Deserialize, Serializer, Deserializer}; - -/// A string with a fixed capacity. -/// -/// The `ArrayString` is a string backed by a fixed size array. It keeps track -/// of its length. -/// -/// The string is a contiguous value that you can store directly on the stack -/// if needed. -#[derive(Copy)] -pub struct ArrayString> { - // FIXME: Use Copyable union for xs when we can - xs: A, - len: A::Index, -} - -impl> Default for ArrayString { - /// Return an empty `ArrayString` - fn default() -> ArrayString { - ArrayString::new() - } -} - -impl> ArrayString { - /// Create a new empty `ArrayString`. - /// - /// Capacity is inferred from the type parameter. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 16]>::new(); - /// string.push_str("foo"); - /// assert_eq!(&string[..], "foo"); - /// assert_eq!(string.capacity(), 16); - /// ``` - pub fn new() -> ArrayString { - unsafe { - ArrayString { - // FIXME: Use Copyable union for xs when we can - xs: mem::zeroed(), - len: Index::from(0), - } - } - } - - /// Create a new `ArrayString` from a `str`. - /// - /// Capacity is inferred from the type parameter. - /// - /// **Errors** if the backing array is not large enough to fit the string. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 3]>::from("foo").unwrap(); - /// assert_eq!(&string[..], "foo"); - /// assert_eq!(string.len(), 3); - /// assert_eq!(string.capacity(), 3); - /// ``` - pub fn from(s: &str) -> Result> { - let mut arraystr = Self::new(); - arraystr.try_push_str(s)?; - Ok(arraystr) - } - - /// Create a new `ArrayString` from a byte string literal. - /// - /// **Errors** if the byte string literal is not valid UTF-8. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let string = ArrayString::from_byte_string(b"hello world").unwrap(); - /// ``` - pub fn from_byte_string(b: &A) -> Result { - let mut arraystr = Self::new(); - let s = try!(str::from_utf8(b.as_slice())); - let _result = arraystr.try_push_str(s); - debug_assert!(_result.is_ok()); - Ok(arraystr) - } - - /// Return the capacity of the `ArrayString`. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let string = ArrayString::<[_; 3]>::new(); - /// assert_eq!(string.capacity(), 3); - /// ``` - #[inline] - pub fn capacity(&self) -> usize { A::capacity() } - - /// Return if the `ArrayString` is completely filled. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 1]>::new(); - /// assert!(!string.is_full()); - /// string.push_str("A"); - /// assert!(string.is_full()); - /// ``` - pub fn is_full(&self) -> bool { self.len() == self.capacity() } - - /// Adds the given char to the end of the string. - /// - /// ***Panics*** if the backing array is not large enough to fit the additional char. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 2]>::new(); - /// - /// string.push('a'); - /// string.push('b'); - /// - /// assert_eq!(&string[..], "ab"); - /// ``` - pub fn push(&mut self, c: char) { - self.try_push(c).unwrap(); - } - - /// Adds the given char to the end of the string. - /// - /// Returns `Ok` if the push succeeds. - /// - /// **Errors** if the backing array is not large enough to fit the additional char. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 2]>::new(); - /// - /// string.try_push('a').unwrap(); - /// string.try_push('b').unwrap(); - /// let overflow = string.try_push('c'); - /// - /// assert_eq!(&string[..], "ab"); - /// assert_eq!(overflow.unwrap_err().element(), 'c'); - /// ``` - pub fn try_push(&mut self, c: char) -> Result<(), CapacityError> { - let len = self.len(); - unsafe { - match encode_utf8(c, &mut self.raw_mut_bytes()[len..]) { - Ok(n) => { - self.set_len(len + n); - Ok(()) - } - Err(_) => Err(CapacityError::new(c)), - } - } - } - - /// Adds the given string slice to the end of the string. - /// - /// ***Panics*** if the backing array is not large enough to fit the string. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 2]>::new(); - /// - /// string.push_str("a"); - /// string.push_str("d"); - /// - /// assert_eq!(&string[..], "ad"); - /// ``` - pub fn push_str(&mut self, s: &str) { - self.try_push_str(s).unwrap() - } - - /// Adds the given string slice to the end of the string. - /// - /// Returns `Ok` if the push succeeds. - /// - /// **Errors** if the backing array is not large enough to fit the string. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 2]>::new(); - /// - /// string.try_push_str("a").unwrap(); - /// let overflow1 = string.try_push_str("bc"); - /// string.try_push_str("d").unwrap(); - /// let overflow2 = string.try_push_str("ef"); - /// - /// assert_eq!(&string[..], "ad"); - /// assert_eq!(overflow1.unwrap_err().element(), "bc"); - /// assert_eq!(overflow2.unwrap_err().element(), "ef"); - /// ``` - pub fn try_push_str<'a>(&mut self, s: &'a str) -> Result<(), CapacityError<&'a str>> { - if s.len() > self.capacity() - self.len() { - return Err(CapacityError::new(s)); - } - unsafe { - let dst = self.xs.as_mut_ptr().offset(self.len() as isize); - let src = s.as_ptr(); - ptr::copy_nonoverlapping(src, dst, s.len()); - let newl = self.len() + s.len(); - self.set_len(newl); - } - Ok(()) - } - - /// Removes the last character from the string and returns it. - /// - /// Returns `None` if this `ArrayString` is empty. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut s = ArrayString::<[_; 3]>::from("foo").unwrap(); - /// - /// assert_eq!(s.pop(), Some('o')); - /// assert_eq!(s.pop(), Some('o')); - /// assert_eq!(s.pop(), Some('f')); - /// - /// assert_eq!(s.pop(), None); - /// ``` - #[inline] - pub fn pop(&mut self) -> Option { - let ch = match self.chars().rev().next() { - Some(ch) => ch, - None => return None, - }; - let new_len = self.len() - ch.len_utf8(); - unsafe { - self.set_len(new_len); - } - Some(ch) - } - - /// Shortens this `ArrayString` to the specified length. - /// - /// If `new_len` is greater than the string’s current length, this has no - /// effect. - /// - /// ***Panics*** if `new_len` does not lie on a `char` boundary. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut string = ArrayString::<[_; 6]>::from("foobar").unwrap(); - /// string.truncate(3); - /// assert_eq!(&string[..], "foo"); - /// string.truncate(4); - /// assert_eq!(&string[..], "foo"); - /// ``` - #[inline] - pub fn truncate(&mut self, new_len: usize) { - if new_len <= self.len() { - assert!(self.is_char_boundary(new_len)); - unsafe { - // In libstd truncate is called on the underlying vector, - // which in turns drops each element. - // As we know we don't have to worry about Drop, - // we can just set the length (a la clear.) - self.set_len(new_len); - } - } - } - - /// Removes a `char` from this `ArrayString` at a byte position and returns it. - /// - /// This is an `O(n)` operation, as it requires copying every element in the - /// array. - /// - /// ***Panics*** if `idx` is larger than or equal to the `ArrayString`’s length, - /// or if it does not lie on a `char` boundary. - /// - /// ``` - /// use arrayvec::ArrayString; - /// - /// let mut s = ArrayString::<[_; 3]>::from("foo").unwrap(); - /// - /// assert_eq!(s.remove(0), 'f'); - /// assert_eq!(s.remove(1), 'o'); - /// assert_eq!(s.remove(0), 'o'); - /// ``` - #[inline] - pub fn remove(&mut self, idx: usize) -> char { - let ch = match self[idx..].chars().next() { - Some(ch) => ch, - None => panic!("cannot remove a char from the end of a string"), - }; - - let next = idx + ch.len_utf8(); - let len = self.len(); - unsafe { - ptr::copy(self.xs.as_ptr().offset(next as isize), - self.xs.as_mut_ptr().offset(idx as isize), - len - next); - self.set_len(len - (next - idx)); - } - ch - } - - /// Make the string empty. - pub fn clear(&mut self) { - unsafe { - self.set_len(0); - } - } - - /// Set the strings’s length. - /// - /// This function is `unsafe` because it changes the notion of the - /// number of “valid” bytes in the string. Use with care. - /// - /// This method uses *debug assertions* to check the validity of `length` - /// and may use other debug assertions. - #[inline] - pub unsafe fn set_len(&mut self, length: usize) { - debug_assert!(length <= self.capacity()); - self.len = Index::from(length); - } - - /// Return a string slice of the whole `ArrayString`. - pub fn as_str(&self) -> &str { - self - } - - /// Return a mutable slice of the whole string’s buffer - unsafe fn raw_mut_bytes(&mut self) -> &mut [u8] { - slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.capacity()) - } -} - -impl> Deref for ArrayString { - type Target = str; - #[inline] - fn deref(&self) -> &str { - unsafe { - let sl = slice::from_raw_parts(self.xs.as_ptr(), self.len.to_usize()); - str::from_utf8_unchecked(sl) - } - } -} - -impl> DerefMut for ArrayString { - #[inline] - fn deref_mut(&mut self) -> &mut str { - unsafe { - let sl = slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.len.to_usize()); - // FIXME: Nothing but transmute to do this right now - mem::transmute(sl) - } - } -} - -impl> PartialEq for ArrayString { - fn eq(&self, rhs: &Self) -> bool { - **self == **rhs - } -} - -impl> PartialEq for ArrayString { - fn eq(&self, rhs: &str) -> bool { - &**self == rhs - } -} - -impl> PartialEq> for str { - fn eq(&self, rhs: &ArrayString) -> bool { - self == &**rhs - } -} - -impl> Eq for ArrayString { } - -impl> Hash for ArrayString { - fn hash(&self, h: &mut H) { - (**self).hash(h) - } -} - -impl> Borrow for ArrayString { - fn borrow(&self) -> &str { self } -} - -impl> AsRef for ArrayString { - fn as_ref(&self) -> &str { self } -} - -impl> fmt::Debug for ArrayString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } -} - -impl> fmt::Display for ArrayString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } -} - -/// `Write` appends written data to the end of the string. -impl> fmt::Write for ArrayString { - fn write_char(&mut self, c: char) -> fmt::Result { - self.try_push(c).map_err(|_| fmt::Error) - } - - fn write_str(&mut self, s: &str) -> fmt::Result { - self.try_push_str(s).map_err(|_| fmt::Error) - } -} - -impl + Copy> Clone for ArrayString { - fn clone(&self) -> ArrayString { - *self - } - fn clone_from(&mut self, rhs: &Self) { - // guaranteed to fit due to types matching. - self.clear(); - self.try_push_str(rhs).ok(); - } -} - -impl> PartialOrd for ArrayString { - fn partial_cmp(&self, rhs: &Self) -> Option { - (**self).partial_cmp(&**rhs) - } - fn lt(&self, rhs: &Self) -> bool { **self < **rhs } - fn le(&self, rhs: &Self) -> bool { **self <= **rhs } - fn gt(&self, rhs: &Self) -> bool { **self > **rhs } - fn ge(&self, rhs: &Self) -> bool { **self >= **rhs } -} - -impl> PartialOrd for ArrayString { - fn partial_cmp(&self, rhs: &str) -> Option { - (**self).partial_cmp(rhs) - } - fn lt(&self, rhs: &str) -> bool { &**self < rhs } - fn le(&self, rhs: &str) -> bool { &**self <= rhs } - fn gt(&self, rhs: &str) -> bool { &**self > rhs } - fn ge(&self, rhs: &str) -> bool { &**self >= rhs } -} - -impl> PartialOrd> for str { - fn partial_cmp(&self, rhs: &ArrayString) -> Option { - self.partial_cmp(&**rhs) - } - fn lt(&self, rhs: &ArrayString) -> bool { self < &**rhs } - fn le(&self, rhs: &ArrayString) -> bool { self <= &**rhs } - fn gt(&self, rhs: &ArrayString) -> bool { self > &**rhs } - fn ge(&self, rhs: &ArrayString) -> bool { self >= &**rhs } -} - -impl> Ord for ArrayString { - fn cmp(&self, rhs: &Self) -> cmp::Ordering { - (**self).cmp(&**rhs) - } -} - -#[cfg(feature="serde-1")] -/// Requires crate feature `"serde-1"` -impl> Serialize for ArrayString { - fn serialize(&self, serializer: S) -> Result - where S: Serializer - { - serializer.serialize_str(&*self) - } -} - -#[cfg(feature="serde-1")] -/// Requires crate feature `"serde-1"` -impl<'de, A: Array> Deserialize<'de> for ArrayString { - fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> - { - use serde::de::{self, Visitor}; - use std::marker::PhantomData; - - struct ArrayStringVisitor>(PhantomData); - - impl<'de, A: Array> Visitor<'de> for ArrayStringVisitor { - type Value = ArrayString; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "a string no more than {} bytes long", A::capacity()) - } - - fn visit_str(self, v: &str) -> Result - where E: de::Error, - { - ArrayString::from(v).map_err(|_| E::invalid_length(v.len(), &self)) - } - - fn visit_bytes(self, v: &[u8]) -> Result - where E: de::Error, - { - let s = try!(str::from_utf8(v).map_err(|_| E::invalid_value(de::Unexpected::Bytes(v), &self))); - - ArrayString::from(s).map_err(|_| E::invalid_length(s.len(), &self)) - } - } - - deserializer.deserialize_str(ArrayStringVisitor::(PhantomData)) - } -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/char.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/char.rs deleted file mode 100644 index 8191dfb..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/char.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2012-2016 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -// -// Original authors: alexchrichton, bluss - -// UTF-8 ranges and tags for encoding characters -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; - -/// Placeholder -pub struct EncodeUtf8Error; - -/// Encode a char into buf using UTF-8. -/// -/// On success, return the byte length of the encoding (1, 2, 3 or 4).
-/// On error, return `EncodeUtf8Error` if the buffer was too short for the char. -#[inline] -pub fn encode_utf8(ch: char, buf: &mut [u8]) -> Result -{ - let code = ch as u32; - if code < MAX_ONE_B && buf.len() >= 1 { - buf[0] = code as u8; - return Ok(1); - } else if code < MAX_TWO_B && buf.len() >= 2 { - buf[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; - buf[1] = (code & 0x3F) as u8 | TAG_CONT; - return Ok(2); - } else if code < MAX_THREE_B && buf.len() >= 3 { - buf[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; - buf[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; - buf[2] = (code & 0x3F) as u8 | TAG_CONT; - return Ok(3); - } else if buf.len() >= 4 { - 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; - return Ok(4); - }; - Err(EncodeUtf8Error) -} - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/errors.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/errors.rs deleted file mode 100644 index 5bea980..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/errors.rs +++ /dev/null @@ -1,53 +0,0 @@ -use std::fmt; -#[cfg(feature="std")] -use std::any::Any; -#[cfg(feature="std")] -use std::error::Error; - -/// Error value indicating insufficient capacity -#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] -pub struct CapacityError { - element: T, -} - -impl CapacityError { - /// Create a new `CapacityError` from `element`. - pub fn new(element: T) -> CapacityError { - CapacityError { - element: element, - } - } - - /// Extract the overflowing element - pub fn element(self) -> T { - self.element - } - - /// Convert into a `CapacityError` that does not carry an element. - pub fn simplify(self) -> CapacityError { - CapacityError { element: () } - } -} - -const CAPERROR: &'static str = "insufficient capacity"; - -#[cfg(feature="std")] -/// Requires `features="std"`. -impl Error for CapacityError { - fn description(&self) -> &str { - CAPERROR - } -} - -impl fmt::Display for CapacityError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", CAPERROR) - } -} - -impl fmt::Debug for CapacityError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}: {}", "CapacityError", CAPERROR) - } -} - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/lib.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/lib.rs deleted file mode 100644 index efd5ebd..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/lib.rs +++ /dev/null @@ -1,1084 +0,0 @@ -//! **arrayvec** provides the types `ArrayVec` and `ArrayString`: -//! array-backed vector and string types, which store their contents inline. -//! -//! The arrayvec package has the following cargo features: -//! -//! - `std` -//! - Optional, enabled by default -//! - Use libstd; disable to use `no_std` instead. -//! -//! - `serde-1` -//! - Optional -//! - Enable serialization for ArrayVec and ArrayString using serde 1.0 -//! - `array-sizes-33-128`, `array-sizes-129-255` -//! - Optional -//! - Enable more array sizes (see [Array] for more information) -//! -//! ## Rust Version -//! -//! This version of arrayvec requires Rust 1.13 or later. -//! -#![doc(html_root_url="https://docs.rs/arrayvec/0.4/")] -#![cfg_attr(not(feature="std"), no_std)] -#![cfg_attr(has_union_feature, feature(untagged_unions))] - -#[cfg(feature="serde-1")] -extern crate serde; - -#[cfg(not(feature="std"))] -extern crate core as std; - -#[cfg(not(has_manually_drop_in_union))] -extern crate nodrop; - -use std::cmp; -use std::iter; -use std::mem; -use std::ptr; -use std::ops::{ - Deref, - DerefMut, -}; -use std::slice; - -// extra traits -use std::borrow::{Borrow, BorrowMut}; -use std::hash::{Hash, Hasher}; -use std::fmt; - -#[cfg(feature="std")] -use std::io; - - -#[cfg(has_stable_maybe_uninit)] -#[path="maybe_uninit_stable.rs"] -mod maybe_uninit; -#[cfg(all(not(has_stable_maybe_uninit), has_manually_drop_in_union))] -mod maybe_uninit; -#[cfg(all(not(has_stable_maybe_uninit), not(has_manually_drop_in_union)))] -#[path="maybe_uninit_nodrop.rs"] -mod maybe_uninit; - -use maybe_uninit::MaybeUninit; - -#[cfg(feature="serde-1")] -use serde::{Serialize, Deserialize, Serializer, Deserializer}; - -mod array; -mod array_string; -mod char; -mod range; -mod errors; - -pub use array::Array; -pub use range::RangeArgument; -use array::Index; -pub use array_string::ArrayString; -pub use errors::CapacityError; - - -/// A vector with a fixed capacity. -/// -/// The `ArrayVec` is a vector backed by a fixed size array. It keeps track of -/// the number of initialized elements. -/// -/// The vector is a contiguous value that you can store directly on the stack -/// if needed. -/// -/// It offers a simple API but also dereferences to a slice, so -/// that the full slice API is available. -/// -/// ArrayVec can be converted into a by value iterator. -pub struct ArrayVec { - xs: MaybeUninit
, - len: A::Index, -} - -impl Drop for ArrayVec { - fn drop(&mut self) { - self.clear(); - - // NoDrop inhibits array's drop - // panic safety: NoDrop::drop will trigger on panic, so the inner - // array will not drop even after panic. - } -} - -macro_rules! panic_oob { - ($method_name:expr, $index:expr, $len:expr) => { - panic!(concat!("ArrayVec::", $method_name, ": index {} is out of bounds in vector of length {}"), - $index, $len) - } -} - -impl ArrayVec { - /// Create a new empty `ArrayVec`. - /// - /// Capacity is inferred from the type parameter. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 16]>::new(); - /// array.push(1); - /// array.push(2); - /// assert_eq!(&array[..], &[1, 2]); - /// assert_eq!(array.capacity(), 16); - /// ``` - pub fn new() -> ArrayVec { - unsafe { - ArrayVec { xs: MaybeUninit::uninitialized(), len: Index::from(0) } - } - } - - /// Return the number of elements in the `ArrayVec`. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3]); - /// array.pop(); - /// assert_eq!(array.len(), 2); - /// ``` - #[inline] - pub fn len(&self) -> usize { self.len.to_usize() } - - /// Return the capacity of the `ArrayVec`. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let array = ArrayVec::from([1, 2, 3]); - /// assert_eq!(array.capacity(), 3); - /// ``` - #[inline] - pub fn capacity(&self) -> usize { A::capacity() } - - /// Return if the `ArrayVec` is completely filled. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 1]>::new(); - /// assert!(!array.is_full()); - /// array.push(1); - /// assert!(array.is_full()); - /// ``` - pub fn is_full(&self) -> bool { self.len() == self.capacity() } - - /// Push `element` to the end of the vector. - /// - /// ***Panics*** if the vector is already full. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// array.push(1); - /// array.push(2); - /// - /// assert_eq!(&array[..], &[1, 2]); - /// ``` - pub fn push(&mut self, element: A::Item) { - self.try_push(element).unwrap() - } - - /// Push `element` to the end of the vector. - /// - /// Return `Ok` if the push succeeds, or return an error if the vector - /// is already full. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// let push1 = array.try_push(1); - /// let push2 = array.try_push(2); - /// - /// assert!(push1.is_ok()); - /// assert!(push2.is_ok()); - /// - /// assert_eq!(&array[..], &[1, 2]); - /// - /// let overflow = array.try_push(3); - /// - /// assert!(overflow.is_err()); - /// ``` - pub fn try_push(&mut self, element: A::Item) -> Result<(), CapacityError> { - if self.len() < A::capacity() { - unsafe { - self.push_unchecked(element); - } - Ok(()) - } else { - Err(CapacityError::new(element)) - } - } - - - /// Push `element` to the end of the vector without checking the capacity. - /// - /// It is up to the caller to ensure the capacity of the vector is - /// sufficiently large. - /// - /// This method uses *debug assertions* to check that the arrayvec is not full. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// if array.len() + 2 <= array.capacity() { - /// unsafe { - /// array.push_unchecked(1); - /// array.push_unchecked(2); - /// } - /// } - /// - /// assert_eq!(&array[..], &[1, 2]); - /// ``` - #[inline] - pub unsafe fn push_unchecked(&mut self, element: A::Item) { - let len = self.len(); - debug_assert!(len < A::capacity()); - ptr::write(self.get_unchecked_ptr(len), element); - self.set_len(len + 1); - } - - /// Get pointer to where element at `index` would be - unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut A::Item { - self.xs.ptr_mut().offset(index as isize) - } - - /// Insert `element` at position `index`. - /// - /// Shift up all elements after `index`. - /// - /// It is an error if the index is greater than the length or if the - /// arrayvec is full. - /// - /// ***Panics*** if the array is full or the `index` is out of bounds. See - /// `try_insert` for fallible version. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// array.insert(0, "x"); - /// array.insert(0, "y"); - /// assert_eq!(&array[..], &["y", "x"]); - /// - /// ``` - pub fn insert(&mut self, index: usize, element: A::Item) { - self.try_insert(index, element).unwrap() - } - - /// Insert `element` at position `index`. - /// - /// Shift up all elements after `index`; the `index` must be less than - /// or equal to the length. - /// - /// Returns an error if vector is already at full capacity. - /// - /// ***Panics*** `index` is out of bounds. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// assert!(array.try_insert(0, "x").is_ok()); - /// assert!(array.try_insert(0, "y").is_ok()); - /// assert!(array.try_insert(0, "z").is_err()); - /// assert_eq!(&array[..], &["y", "x"]); - /// - /// ``` - pub fn try_insert(&mut self, index: usize, element: A::Item) -> Result<(), CapacityError> { - if index > self.len() { - panic_oob!("try_insert", index, self.len()) - } - if self.len() == self.capacity() { - return Err(CapacityError::new(element)); - } - let len = self.len(); - - // follows is just like Vec - unsafe { // infallible - // The spot to put the new value - { - let p: *mut _ = self.get_unchecked_ptr(index); - // Shift everything over to make space. (Duplicating the - // `index`th element into two consecutive places.) - ptr::copy(p, p.offset(1), len - index); - // Write it in, overwriting the first copy of the `index`th - // element. - ptr::write(p, element); - } - self.set_len(len + 1); - } - Ok(()) - } - - /// Remove the last element in the vector and return it. - /// - /// Return `Some(` *element* `)` if the vector is non-empty, else `None`. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::<[_; 2]>::new(); - /// - /// array.push(1); - /// - /// assert_eq!(array.pop(), Some(1)); - /// assert_eq!(array.pop(), None); - /// ``` - pub fn pop(&mut self) -> Option { - if self.len() == 0 { - return None - } - unsafe { - let new_len = self.len() - 1; - self.set_len(new_len); - Some(ptr::read(self.get_unchecked_ptr(new_len))) - } - } - - /// Remove the element at `index` and swap the last element into its place. - /// - /// This operation is O(1). - /// - /// Return the *element* if the index is in bounds, else panic. - /// - /// ***Panics*** if the `index` is out of bounds. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3]); - /// - /// assert_eq!(array.swap_remove(0), 1); - /// assert_eq!(&array[..], &[3, 2]); - /// - /// assert_eq!(array.swap_remove(1), 2); - /// assert_eq!(&array[..], &[3]); - /// ``` - pub fn swap_remove(&mut self, index: usize) -> A::Item { - self.swap_pop(index) - .unwrap_or_else(|| { - panic_oob!("swap_remove", index, self.len()) - }) - } - - /// Remove the element at `index` and swap the last element into its place. - /// - /// This is a checked version of `.swap_remove`. - /// This operation is O(1). - /// - /// Return `Some(` *element* `)` if the index is in bounds, else `None`. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3]); - /// - /// assert_eq!(array.swap_pop(0), Some(1)); - /// assert_eq!(&array[..], &[3, 2]); - /// - /// assert_eq!(array.swap_pop(10), None); - /// ``` - pub fn swap_pop(&mut self, index: usize) -> Option { - let len = self.len(); - if index >= len { - return None; - } - self.swap(index, len - 1); - self.pop() - } - - /// Remove the element at `index` and shift down the following elements. - /// - /// The `index` must be strictly less than the length of the vector. - /// - /// ***Panics*** if the `index` is out of bounds. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3]); - /// - /// let removed_elt = array.remove(0); - /// assert_eq!(removed_elt, 1); - /// assert_eq!(&array[..], &[2, 3]); - /// ``` - pub fn remove(&mut self, index: usize) -> A::Item { - self.pop_at(index) - .unwrap_or_else(|| { - panic_oob!("remove", index, self.len()) - }) - } - - /// Remove the element at `index` and shift down the following elements. - /// - /// This is a checked version of `.remove(index)`. Returns `None` if there - /// is no element at `index`. Otherwise, return the element inside `Some`. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3]); - /// - /// assert!(array.pop_at(0).is_some()); - /// assert_eq!(&array[..], &[2, 3]); - /// - /// assert!(array.pop_at(2).is_none()); - /// assert!(array.pop_at(10).is_none()); - /// ``` - pub fn pop_at(&mut self, index: usize) -> Option { - if index >= self.len() { - None - } else { - self.drain(index..index + 1).next() - } - } - - /// Shortens the vector, keeping the first `len` elements and dropping - /// the rest. - /// - /// If `len` is greater than the vector’s current length this has no - /// effect. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3, 4, 5]); - /// array.truncate(3); - /// assert_eq!(&array[..], &[1, 2, 3]); - /// array.truncate(4); - /// assert_eq!(&array[..], &[1, 2, 3]); - /// ``` - pub fn truncate(&mut self, len: usize) { - while self.len() > len { self.pop(); } - } - - /// Remove all elements in the vector. - pub fn clear(&mut self) { - while let Some(_) = self.pop() { } - } - - /// Retains only the elements specified by the predicate. - /// - /// In other words, remove all elements `e` such that `f(&mut e)` returns false. - /// This method operates in place and preserves the order of the retained - /// elements. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut array = ArrayVec::from([1, 2, 3, 4]); - /// array.retain(|x| *x & 1 != 0 ); - /// assert_eq!(&array[..], &[1, 3]); - /// ``` - pub fn retain(&mut self, mut f: F) - where F: FnMut(&mut A::Item) -> bool - { - let len = self.len(); - let mut del = 0; - { - let v = &mut **self; - - for i in 0..len { - if !f(&mut v[i]) { - del += 1; - } else if del > 0 { - v.swap(i - del, i); - } - } - } - if del > 0 { - self.drain(len - del..); - } - } - - /// Set the vector’s length without dropping or moving out elements - /// - /// This method is `unsafe` because it changes the notion of the - /// number of “valid” elements in the vector. Use with care. - /// - /// This method uses *debug assertions* to check that check that `length` is - /// not greater than the capacity. - #[inline] - pub unsafe fn set_len(&mut self, length: usize) { - debug_assert!(length <= self.capacity()); - self.len = Index::from(length); - } - - /// Create a draining iterator that removes the specified range in the vector - /// and yields the removed items from start to end. The element range is - /// removed even if the iterator is not consumed until the end. - /// - /// Note: It is unspecified how many elements are removed from the vector, - /// if the `Drain` value is leaked. - /// - /// **Panics** if the starting point is greater than the end point or if - /// the end point is greater than the length of the vector. - /// - /// ``` - /// use arrayvec::ArrayVec; - /// - /// let mut v = ArrayVec::from([1, 2, 3]); - /// let u: ArrayVec<[_; 3]> = v.drain(0..2).collect(); - /// assert_eq!(&v[..], &[3]); - /// assert_eq!(&u[..], &[1, 2]); - /// ``` - pub fn drain(&mut self, range: R) -> Drain { - // Memory safety - // - // When the Drain is first created, it shortens the length of - // the source vector to make sure no uninitalized or moved-from elements - // are accessible at all if the Drain's destructor never gets to run. - // - // Drain will ptr::read out the values to remove. - // When finished, remaining tail of the vec is copied back to cover - // the hole, and the vector length is restored to the new length. - // - let len = self.len(); - let start = range.start().unwrap_or(0); - let end = range.end().unwrap_or(len); - // bounds check happens here - let range_slice: *const _ = &self[start..end]; - - unsafe { - // set self.vec length's to start, to be safe in case Drain is leaked - self.set_len(start); - Drain { - tail_start: end, - tail_len: len - end, - iter: (*range_slice).iter(), - vec: self as *mut _, - } - } - } - - /// Return the inner fixed size array, if it is full to its capacity. - /// - /// Return an `Ok` value with the array if length equals capacity, - /// return an `Err` with self otherwise. - /// - /// `Note:` This function may incur unproportionally large overhead - /// to move the array out, its performance is not optimal. - pub fn into_inner(self) -> Result { - if self.len() < self.capacity() { - Err(self) - } else { - unsafe { - let array = ptr::read(self.xs.ptr() as *const A); - mem::forget(self); - Ok(array) - } - } - } - - /// Dispose of `self` without the overwriting that is needed in Drop. - pub fn dispose(mut self) { - self.clear(); - mem::forget(self); - } - - /// Return a slice containing all elements of the vector. - pub fn as_slice(&self) -> &[A::Item] { - self - } - - /// Return a mutable slice containing all elements of the vector. - pub fn as_mut_slice(&mut self) -> &mut [A::Item] { - self - } -} - -impl Deref for ArrayVec { - type Target = [A::Item]; - #[inline] - fn deref(&self) -> &[A::Item] { - unsafe { - slice::from_raw_parts(self.xs.ptr(), self.len()) - } - } -} - -impl DerefMut for ArrayVec { - #[inline] - fn deref_mut(&mut self) -> &mut [A::Item] { - let len = self.len(); - unsafe { - slice::from_raw_parts_mut(self.xs.ptr_mut(), len) - } - } -} - -/// Create an `ArrayVec` from an array. -/// -/// ``` -/// use arrayvec::ArrayVec; -/// -/// let mut array = ArrayVec::from([1, 2, 3]); -/// assert_eq!(array.len(), 3); -/// assert_eq!(array.capacity(), 3); -/// ``` -impl From for ArrayVec { - fn from(array: A) -> Self { - ArrayVec { xs: MaybeUninit::from(array), len: Index::from(A::capacity()) } - } -} - - -/// Iterate the `ArrayVec` with references to each element. -/// -/// ``` -/// use arrayvec::ArrayVec; -/// -/// let array = ArrayVec::from([1, 2, 3]); -/// -/// for elt in &array { -/// // ... -/// } -/// ``` -impl<'a, A: Array> IntoIterator for &'a ArrayVec { - type Item = &'a A::Item; - type IntoIter = slice::Iter<'a, A::Item>; - fn into_iter(self) -> Self::IntoIter { self.iter() } -} - -/// Iterate the `ArrayVec` with mutable references to each element. -/// -/// ``` -/// use arrayvec::ArrayVec; -/// -/// let mut array = ArrayVec::from([1, 2, 3]); -/// -/// for elt in &mut array { -/// // ... -/// } -/// ``` -impl<'a, A: Array> IntoIterator for &'a mut ArrayVec { - type Item = &'a mut A::Item; - type IntoIter = slice::IterMut<'a, A::Item>; - fn into_iter(self) -> Self::IntoIter { self.iter_mut() } -} - -/// Iterate the `ArrayVec` with each element by value. -/// -/// The vector is consumed by this operation. -/// -/// ``` -/// use arrayvec::ArrayVec; -/// -/// for elt in ArrayVec::from([1, 2, 3]) { -/// // ... -/// } -/// ``` -impl IntoIterator for ArrayVec { - type Item = A::Item; - type IntoIter = IntoIter; - fn into_iter(self) -> IntoIter { - IntoIter { index: Index::from(0), v: self, } - } -} - - -/// By-value iterator for `ArrayVec`. -pub struct IntoIter { - index: A::Index, - v: ArrayVec, -} - -impl Iterator for IntoIter { - type Item = A::Item; - - #[inline] - fn next(&mut self) -> Option { - if self.index == self.v.len { - None - } else { - unsafe { - let index = self.index.to_usize(); - self.index = Index::from(index + 1); - Some(ptr::read(self.v.get_unchecked_ptr(index))) - } - } - } - - fn size_hint(&self) -> (usize, Option) { - let len = self.v.len() - self.index.to_usize(); - (len, Some(len)) - } -} - -impl DoubleEndedIterator for IntoIter { - #[inline] - fn next_back(&mut self) -> Option { - if self.index == self.v.len { - None - } else { - unsafe { - let new_len = self.v.len() - 1; - self.v.set_len(new_len); - Some(ptr::read(self.v.get_unchecked_ptr(new_len))) - } - } - } -} - -impl ExactSizeIterator for IntoIter { } - -impl Drop for IntoIter { - fn drop(&mut self) { - // panic safety: Set length to 0 before dropping elements. - let index = self.index.to_usize(); - let len = self.v.len(); - unsafe { - self.v.set_len(0); - let elements = slice::from_raw_parts_mut( - self.v.get_unchecked_ptr(index), - len - index); - ptr::drop_in_place(elements); - } - } -} - -impl Clone for IntoIter -where - A::Item: Clone, -{ - fn clone(&self) -> IntoIter { - self.v[self.index.to_usize()..] - .iter() - .cloned() - .collect::>() - .into_iter() - } -} - -impl fmt::Debug for IntoIter -where - A::Item: fmt::Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_list() - .entries(&self.v[self.index.to_usize()..]) - .finish() - } -} - -/// A draining iterator for `ArrayVec`. -pub struct Drain<'a, A> - where A: Array, - A::Item: 'a, -{ - /// Index of tail to preserve - tail_start: usize, - /// Length of tail - tail_len: usize, - /// Current remaining range to remove - iter: slice::Iter<'a, A::Item>, - vec: *mut ArrayVec, -} - -unsafe impl<'a, A: Array + Sync> Sync for Drain<'a, A> {} -unsafe impl<'a, A: Array + Send> Send for Drain<'a, A> {} - -impl<'a, A: Array> Iterator for Drain<'a, A> - where A::Item: 'a, -{ - type Item = A::Item; - - #[inline] - fn next(&mut self) -> Option { - self.iter.next().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } -} - -impl<'a, A: Array> DoubleEndedIterator for Drain<'a, A> - where A::Item: 'a, -{ - #[inline] - fn next_back(&mut self) -> Option { - self.iter.next_back().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) - } -} - -impl<'a, A: Array> ExactSizeIterator for Drain<'a, A> where A::Item: 'a {} - -impl<'a, A: Array> Drop for Drain<'a, A> - where A::Item: 'a -{ - fn drop(&mut self) { - // len is currently 0 so panicking while dropping will not cause a double drop. - - // exhaust self first - while let Some(_) = self.next() { } - - if self.tail_len > 0 { - unsafe { - let source_vec = &mut *self.vec; - // memmove back untouched tail, update to new length - let start = source_vec.len(); - let tail = self.tail_start; - let src = source_vec.as_ptr().offset(tail as isize); - let dst = source_vec.as_mut_ptr().offset(start as isize); - ptr::copy(src, dst, self.tail_len); - source_vec.set_len(start + self.tail_len); - } - } - } -} - -struct ScopeExitGuard - where F: FnMut(&Data, &mut T) -{ - value: T, - data: Data, - f: F, -} - -impl Drop for ScopeExitGuard - where F: FnMut(&Data, &mut T) -{ - fn drop(&mut self) { - (self.f)(&self.data, &mut self.value) - } -} - - - -/// Extend the `ArrayVec` with an iterator. -/// -/// Does not extract more items than there is space for. No error -/// occurs if there are more iterator elements. -impl Extend for ArrayVec { - fn extend>(&mut self, iter: T) { - let take = self.capacity() - self.len(); - unsafe { - let len = self.len(); - let mut ptr = self.as_mut_ptr().offset(len as isize); - // Keep the length in a separate variable, write it back on scope - // exit. To help the compiler with alias analysis and stuff. - // We update the length to handle panic in the iteration of the - // user's iterator, without dropping any elements on the floor. - let mut guard = ScopeExitGuard { - value: self, - data: len, - f: |&len, self_| { - self_.set_len(len) - } - }; - for elt in iter.into_iter().take(take) { - ptr::write(ptr, elt); - ptr = ptr.offset(1); - guard.data += 1; - } - } - } -} - -/// Create an `ArrayVec` from an iterator. -/// -/// Does not extract more items than there is space for. No error -/// occurs if there are more iterator elements. -impl iter::FromIterator for ArrayVec { - fn from_iter>(iter: T) -> Self { - let mut array = ArrayVec::new(); - array.extend(iter); - array - } -} - -impl Clone for ArrayVec - where A::Item: Clone -{ - fn clone(&self) -> Self { - self.iter().cloned().collect() - } - - fn clone_from(&mut self, rhs: &Self) { - // recursive case for the common prefix - let prefix = cmp::min(self.len(), rhs.len()); - self[..prefix].clone_from_slice(&rhs[..prefix]); - - if prefix < self.len() { - // rhs was shorter - for _ in 0..self.len() - prefix { - self.pop(); - } - } else { - let rhs_elems = rhs[self.len()..].iter().cloned(); - self.extend(rhs_elems); - } - } -} - -impl Hash for ArrayVec - where A::Item: Hash -{ - fn hash(&self, state: &mut H) { - Hash::hash(&**self, state) - } -} - -impl PartialEq for ArrayVec - where A::Item: PartialEq -{ - fn eq(&self, other: &Self) -> bool { - **self == **other - } -} - -impl PartialEq<[A::Item]> for ArrayVec - where A::Item: PartialEq -{ - fn eq(&self, other: &[A::Item]) -> bool { - **self == *other - } -} - -impl Eq for ArrayVec where A::Item: Eq { } - -impl Borrow<[A::Item]> for ArrayVec { - fn borrow(&self) -> &[A::Item] { self } -} - -impl BorrowMut<[A::Item]> for ArrayVec { - fn borrow_mut(&mut self) -> &mut [A::Item] { self } -} - -impl AsRef<[A::Item]> for ArrayVec { - fn as_ref(&self) -> &[A::Item] { self } -} - -impl AsMut<[A::Item]> for ArrayVec { - fn as_mut(&mut self) -> &mut [A::Item] { self } -} - -impl fmt::Debug for ArrayVec where A::Item: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } -} - -impl Default for ArrayVec { - /// Return an empty array - fn default() -> ArrayVec { - ArrayVec::new() - } -} - -impl PartialOrd for ArrayVec where A::Item: PartialOrd { - #[inline] - fn partial_cmp(&self, other: &ArrayVec) -> Option { - (**self).partial_cmp(other) - } - - #[inline] - fn lt(&self, other: &Self) -> bool { - (**self).lt(other) - } - - #[inline] - fn le(&self, other: &Self) -> bool { - (**self).le(other) - } - - #[inline] - fn ge(&self, other: &Self) -> bool { - (**self).ge(other) - } - - #[inline] - fn gt(&self, other: &Self) -> bool { - (**self).gt(other) - } -} - -impl Ord for ArrayVec where A::Item: Ord { - fn cmp(&self, other: &ArrayVec) -> cmp::Ordering { - (**self).cmp(other) - } -} - -#[cfg(feature="std")] -/// `Write` appends written data to the end of the vector. -/// -/// Requires `features="std"`. -impl> io::Write for ArrayVec { - fn write(&mut self, data: &[u8]) -> io::Result { - unsafe { - let len = self.len(); - let write_len = cmp::min(A::capacity() - len, data.len()); - ptr::copy_nonoverlapping(data.as_ptr(), self.get_unchecked_ptr(len), write_len); - self.set_len(len + write_len); - Ok(write_len) - } - } - fn flush(&mut self) -> io::Result<()> { Ok(()) } -} - -#[cfg(feature="serde-1")] -/// Requires crate feature `"serde-1"` -impl> Serialize for ArrayVec { - fn serialize(&self, serializer: S) -> Result - where S: Serializer - { - serializer.collect_seq(self) - } -} - -#[cfg(feature="serde-1")] -/// Requires crate feature `"serde-1"` -impl<'de, T: Deserialize<'de>, A: Array> Deserialize<'de> for ArrayVec { - fn deserialize(deserializer: D) -> Result - where D: Deserializer<'de> - { - use serde::de::{Visitor, SeqAccess, Error}; - use std::marker::PhantomData; - - struct ArrayVecVisitor<'de, T: Deserialize<'de>, A: Array>(PhantomData<(&'de (), T, A)>); - - impl<'de, T: Deserialize<'de>, A: Array> Visitor<'de> for ArrayVecVisitor<'de, T, A> { - type Value = ArrayVec; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "an array with no more than {} items", A::capacity()) - } - - fn visit_seq(self, mut seq: SA) -> Result - where SA: SeqAccess<'de>, - { - let mut values = ArrayVec::::new(); - - while let Some(value) = try!(seq.next_element()) { - if let Err(_) = values.try_push(value) { - return Err(SA::Error::invalid_length(A::capacity() + 1, &self)); - } - } - - Ok(values) - } - } - - deserializer.deserialize_seq(ArrayVecVisitor::(PhantomData)) - } -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit.rs deleted file mode 100644 index 9ed1f6a..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit.rs +++ /dev/null @@ -1,46 +0,0 @@ - - -use array::Array; -use std::mem::ManuallyDrop; - -/// A combination of ManuallyDrop and “maybe uninitialized”; -/// this wraps a value that can be wholly or partially uninitialized; -/// it also has no drop regardless of the type of T. -#[repr(C)] // for cast from self ptr to value -pub union MaybeUninit { - empty: (), - value: ManuallyDrop, -} -// Why we don't use std's MaybeUninit on nightly? See the ptr method - -impl MaybeUninit { - /// Create a new MaybeUninit with uninitialized interior - pub unsafe fn uninitialized() -> Self { - MaybeUninit { empty: () } - } - - /// Create a new MaybeUninit from the value `v`. - pub fn from(v: T) -> Self { - MaybeUninit { value: ManuallyDrop::new(v) } - } - - // Raw pointer casts written so that we don't reference or access the - // uninitialized interior value - - /// Return a raw pointer to the start of the interior array - pub fn ptr(&self) -> *const T::Item - where T: Array - { - // std MaybeUninit creates a &self.value reference here which is - // not guaranteed to be sound in our case - we will partially - // initialize the value, not always wholly. - self as *const _ as *const T::Item - } - - /// Return a mut raw pointer to the start of the interior array - pub fn ptr_mut(&mut self) -> *mut T::Item - where T: Array - { - self as *mut _ as *mut T::Item - } -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_nodrop.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_nodrop.rs deleted file mode 100644 index 8213b97..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_nodrop.rs +++ /dev/null @@ -1,41 +0,0 @@ - -use array::Array; -use nodrop::NoDrop; -use std::mem::uninitialized; - -/// A combination of NoDrop and “maybe uninitialized”; -/// this wraps a value that can be wholly or partially uninitialized. -/// -/// NOTE: This is known to not be a good solution, but it's the one we have kept -/// working on stable Rust. Stable improvements are encouraged, in any form, -/// but of course we are waiting for a real, stable, MaybeUninit. -pub struct MaybeUninit(NoDrop); -// why don't we use ManuallyDrop here: It doesn't inhibit -// enum layout optimizations that depend on T, and we support older Rust. - -impl MaybeUninit { - /// Create a new MaybeUninit with uninitialized interior - pub unsafe fn uninitialized() -> Self { - Self::from(uninitialized()) - } - - /// Create a new MaybeUninit from the value `v`. - pub fn from(v: T) -> Self { - MaybeUninit(NoDrop::new(v)) - } - - /// Return a raw pointer to the start of the interior array - pub fn ptr(&self) -> *const T::Item - where T: Array - { - &*self.0 as *const T as *const _ - } - - /// Return a mut raw pointer to the start of the interior array - pub fn ptr_mut(&mut self) -> *mut T::Item - where T: Array - { - &mut *self.0 as *mut T as *mut _ - } -} - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_stable.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_stable.rs deleted file mode 100644 index cb631a9..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/maybe_uninit_stable.rs +++ /dev/null @@ -1,40 +0,0 @@ - - -use array::Array; -use std::mem::MaybeUninit as StdMaybeUninit; - -pub struct MaybeUninit { - inner: StdMaybeUninit, -} - -impl MaybeUninit { - /// Create a new MaybeUninit with uninitialized interior - pub unsafe fn uninitialized() -> Self { - MaybeUninit { inner: StdMaybeUninit::uninit() } - } - - /// Create a new MaybeUninit from the value `v`. - pub fn from(v: T) -> Self { - MaybeUninit { inner: StdMaybeUninit::new(v) } - } - - // Raw pointer casts written so that we don't reference or access the - // uninitialized interior value - - /// Return a raw pointer to the start of the interior array - pub fn ptr(&self) -> *const T::Item - where T: Array - { - // std MaybeUninit creates a &self.value reference here which is - // not guaranteed to be sound in our case - we will partially - // initialize the value, not always wholly. - self.inner.as_ptr() as *const T::Item - } - - /// Return a mut raw pointer to the start of the interior array - pub fn ptr_mut(&mut self) -> *mut T::Item - where T: Array - { - self.inner.as_mut_ptr() as *mut T::Item - } -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/src/range.rs b/third_party/cargo/vendor/arrayvec-0.4.12/src/range.rs deleted file mode 100644 index f90f5af..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/src/range.rs +++ /dev/null @@ -1,42 +0,0 @@ - -use std::ops::{ - RangeFull, - RangeFrom, - RangeTo, - Range, -}; - -/// `RangeArgument` is implemented by Rust's built-in range types, produced -/// by range syntax like `..`, `a..`, `..b` or `c..d`. -/// -/// Note: This is arrayvec's provisional trait, waiting for stable Rust to -/// provide an equivalent. -pub trait RangeArgument { - #[inline] - /// Start index (inclusive) - fn start(&self) -> Option { None } - #[inline] - /// End index (exclusive) - fn end(&self) -> Option { None } -} - - -impl RangeArgument for RangeFull {} - -impl RangeArgument for RangeFrom { - #[inline] - fn start(&self) -> Option { Some(self.start) } -} - -impl RangeArgument for RangeTo { - #[inline] - fn end(&self) -> Option { Some(self.end) } -} - -impl RangeArgument for Range { - #[inline] - fn start(&self) -> Option { Some(self.start) } - #[inline] - fn end(&self) -> Option { Some(self.end) } -} - diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/tests/serde.rs b/third_party/cargo/vendor/arrayvec-0.4.12/tests/serde.rs deleted file mode 100644 index 62acf25..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/tests/serde.rs +++ /dev/null @@ -1,79 +0,0 @@ -#![cfg(feature = "serde-1")] -extern crate arrayvec; -extern crate serde_test; - -mod array_vec { - use arrayvec::ArrayVec; - - use serde_test::{Token, assert_tokens, assert_de_tokens_error}; - - #[test] - fn test_ser_de_empty() { - let vec = ArrayVec::<[u32; 0]>::new(); - - assert_tokens(&vec, &[ - Token::Seq { len: Some(0) }, - Token::SeqEnd, - ]); - } - - - #[test] - fn test_ser_de() { - let mut vec = ArrayVec::<[u32; 3]>::new(); - vec.push(20); - vec.push(55); - vec.push(123); - - assert_tokens(&vec, &[ - Token::Seq { len: Some(3) }, - Token::U32(20), - Token::U32(55), - Token::U32(123), - Token::SeqEnd, - ]); - } - - #[test] - fn test_de_too_large() { - assert_de_tokens_error::>(&[ - Token::Seq { len: Some(3) }, - Token::U32(13), - Token::U32(42), - Token::U32(68), - ], "invalid length 3, expected an array with no more than 2 items"); - } -} - -mod array_string { - use arrayvec::ArrayString; - - use serde_test::{Token, assert_tokens, assert_de_tokens_error}; - - #[test] - fn test_ser_de_empty() { - let string = ArrayString::<[u8; 0]>::new(); - - assert_tokens(&string, &[ - Token::Str(""), - ]); - } - - - #[test] - fn test_ser_de() { - let string = ArrayString::<[u8; 9]>::from("1234 abcd") - .expect("expected exact specified capacity to be enough"); - - assert_tokens(&string, &[ - Token::Str("1234 abcd"), - ]); - } - - #[test] - fn test_de_too_large() { - assert_de_tokens_error::>(&[ - Token::Str("afd") - ], "invalid length 3, expected a string no more than 2 bytes long"); - } -} diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/tests/tests.rs b/third_party/cargo/vendor/arrayvec-0.4.12/tests/tests.rs deleted file mode 100644 index b8dbadb..0000000 --- a/third_party/cargo/vendor/arrayvec-0.4.12/tests/tests.rs +++ /dev/null @@ -1,517 +0,0 @@ -extern crate arrayvec; -#[macro_use] extern crate matches; - -use arrayvec::ArrayVec; -use arrayvec::ArrayString; -use std::mem; -use arrayvec::CapacityError; - -use std::collections::HashMap; - - -#[test] -fn test_simple() { - use std::ops::Add; - - let mut vec: ArrayVec<[Vec; 3]> = ArrayVec::new(); - - vec.push(vec![1, 2, 3, 4]); - vec.push(vec![10]); - vec.push(vec![-1, 13, -2]); - - for elt in &vec { - assert_eq!(elt.iter().fold(0, Add::add), 10); - } - - let sum_len = vec.into_iter().map(|x| x.len()).fold(0, Add::add); - assert_eq!(sum_len, 8); -} - -#[test] -fn test_u16_index() { - const N: usize = 4096; - let mut vec: ArrayVec<[_; N]> = ArrayVec::new(); - for _ in 0..N { - assert!(vec.try_push(1u8).is_ok()); - } - assert!(vec.try_push(0).is_err()); - assert_eq!(vec.len(), N); -} - -#[test] -fn test_iter() { - let mut iter = ArrayVec::from([1, 2, 3]).into_iter(); - assert_eq!(iter.size_hint(), (3, Some(3))); - assert_eq!(iter.next_back(), Some(3)); - assert_eq!(iter.next(), Some(1)); - assert_eq!(iter.next_back(), Some(2)); - assert_eq!(iter.size_hint(), (0, Some(0))); - assert_eq!(iter.next_back(), None); -} - -#[test] -fn test_drop() { - use std::cell::Cell; - - let flag = &Cell::new(0); - - #[derive(Clone)] - struct Bump<'a>(&'a Cell); - - impl<'a> Drop for Bump<'a> { - fn drop(&mut self) { - let n = self.0.get(); - self.0.set(n + 1); - } - } - - { - let mut array = ArrayVec::<[Bump; 128]>::new(); - array.push(Bump(flag)); - array.push(Bump(flag)); - } - assert_eq!(flag.get(), 2); - - // test something with the nullable pointer optimization - flag.set(0); - - { - let mut array = ArrayVec::<[_; 3]>::new(); - array.push(vec![Bump(flag)]); - array.push(vec![Bump(flag), Bump(flag)]); - array.push(vec![]); - let push4 = array.try_push(vec![Bump(flag)]); - assert_eq!(flag.get(), 0); - drop(push4); - assert_eq!(flag.get(), 1); - drop(array.pop()); - assert_eq!(flag.get(), 1); - drop(array.pop()); - assert_eq!(flag.get(), 3); - } - - assert_eq!(flag.get(), 4); - - // test into_inner - flag.set(0); - { - let mut array = ArrayVec::<[_; 3]>::new(); - array.push(Bump(flag)); - array.push(Bump(flag)); - array.push(Bump(flag)); - let inner = array.into_inner(); - assert!(inner.is_ok()); - assert_eq!(flag.get(), 0); - drop(inner); - assert_eq!(flag.get(), 3); - } - - // test cloning into_iter - flag.set(0); - { - let mut array = ArrayVec::<[_; 3]>::new(); - array.push(Bump(flag)); - array.push(Bump(flag)); - array.push(Bump(flag)); - let mut iter = array.into_iter(); - assert_eq!(flag.get(), 0); - iter.next(); - assert_eq!(flag.get(), 1); - let clone = iter.clone(); - assert_eq!(flag.get(), 1); - drop(clone); - assert_eq!(flag.get(), 3); - drop(iter); - assert_eq!(flag.get(), 5); - } -} - -#[test] -fn test_extend() { - let mut range = 0..10; - - let mut array: ArrayVec<[_; 5]> = range.by_ref().collect(); - assert_eq!(&array[..], &[0, 1, 2, 3, 4]); - assert_eq!(range.next(), Some(5)); - - array.extend(range.by_ref()); - assert_eq!(range.next(), Some(6)); - - let mut array: ArrayVec<[_; 10]> = (0..3).collect(); - assert_eq!(&array[..], &[0, 1, 2]); - array.extend(3..5); - assert_eq!(&array[..], &[0, 1, 2, 3, 4]); -} - -#[test] -fn test_is_send_sync() { - let data = ArrayVec::<[Vec; 5]>::new(); - &data as &Send; - &data as &Sync; -} - -#[test] -fn test_compact_size() { - // Future rust will kill these drop flags! - // 4 elements size + 1 len + 1 enum tag + [1 drop flag] - type ByteArray = ArrayVec<[u8; 4]>; - println!("{}", mem::size_of::()); - assert!(mem::size_of::() <= 8); - - // 12 element size + 1 enum tag + 3 padding + 1 len + 1 drop flag + 2 padding - type QuadArray = ArrayVec<[u32; 3]>; - println!("{}", mem::size_of::()); - assert!(mem::size_of::() <= 24); -} - -#[test] -fn test_still_works_with_option_arrayvec() { - type RefArray = ArrayVec<[&'static i32; 2]>; - let array = Some(RefArray::new()); - assert!(array.is_some()); - println!("{:?}", array); -} - -#[test] -fn test_drain() { - let mut v = ArrayVec::from([0; 8]); - v.pop(); - v.drain(0..7); - assert_eq!(&v[..], &[]); - - v.extend(0..); - v.drain(1..4); - assert_eq!(&v[..], &[0, 4, 5, 6, 7]); - let u: ArrayVec<[_; 3]> = v.drain(1..4).rev().collect(); - assert_eq!(&u[..], &[6, 5, 4]); - assert_eq!(&v[..], &[0, 7]); - v.drain(..); - assert_eq!(&v[..], &[]); -} - -#[test] -fn test_retain() { - let mut v = ArrayVec::from([0; 8]); - for (i, elt) in v.iter_mut().enumerate() { - *elt = i; - } - v.retain(|_| true); - assert_eq!(&v[..], &[0, 1, 2, 3, 4, 5, 6, 7]); - v.retain(|elt| { - *elt /= 2; - *elt % 2 == 0 - }); - assert_eq!(&v[..], &[0, 0, 2, 2]); - v.retain(|_| false); - assert_eq!(&v[..], &[]); -} - -#[test] -#[should_panic] -fn test_drain_oob() { - let mut v = ArrayVec::from([0; 8]); - v.pop(); - v.drain(0..8); -} - -#[test] -#[should_panic] -fn test_drop_panic() { - struct DropPanic; - - impl Drop for DropPanic { - fn drop(&mut self) { - panic!("drop"); - } - } - - let mut array = ArrayVec::<[DropPanic; 1]>::new(); - array.push(DropPanic); -} - -#[test] -#[should_panic] -fn test_drop_panic_into_iter() { - struct DropPanic; - - impl Drop for DropPanic { - fn drop(&mut self) { - panic!("drop"); - } - } - - let mut array = ArrayVec::<[DropPanic; 1]>::new(); - array.push(DropPanic); - array.into_iter(); -} - -#[test] -fn test_insert() { - let mut v = ArrayVec::from([]); - assert_matches!(v.try_push(1), Err(_)); - - let mut v = ArrayVec::<[_; 3]>::new(); - v.insert(0, 0); - v.insert(1, 1); - //let ret1 = v.try_insert(3, 3); - //assert_matches!(ret1, Err(InsertError::OutOfBounds(_))); - assert_eq!(&v[..], &[0, 1]); - v.insert(2, 2); - assert_eq!(&v[..], &[0, 1, 2]); - - let ret2 = v.try_insert(1, 9); - assert_eq!(&v[..], &[0, 1, 2]); - assert_matches!(ret2, Err(_)); - - let mut v = ArrayVec::from([2]); - assert_matches!(v.try_insert(0, 1), Err(CapacityError { .. })); - assert_matches!(v.try_insert(1, 1), Err(CapacityError { .. })); - //assert_matches!(v.try_insert(2, 1), Err(CapacityError { .. })); -} - -#[test] -fn test_into_inner_1() { - let mut v = ArrayVec::from([1, 2]); - v.pop(); - let u = v.clone(); - assert_eq!(v.into_inner(), Err(u)); -} - -#[test] -fn test_into_inner_2() { - let mut v = ArrayVec::<[String; 4]>::new(); - v.push("a".into()); - v.push("b".into()); - v.push("c".into()); - v.push("d".into()); - assert_eq!(v.into_inner().unwrap(), ["a", "b", "c", "d"]); -} - -#[test] -fn test_into_inner_3_() { - let mut v = ArrayVec::<[i32; 4]>::new(); - v.extend(1..); - assert_eq!(v.into_inner().unwrap(), [1, 2, 3, 4]); -} - -#[test] -fn test_write() { - use std::io::Write; - let mut v = ArrayVec::<[_; 8]>::new(); - write!(&mut v, "\x01\x02\x03").unwrap(); - assert_eq!(&v[..], &[1, 2, 3]); - let r = v.write(&[9; 16]).unwrap(); - assert_eq!(r, 5); - assert_eq!(&v[..], &[1, 2, 3, 9, 9, 9, 9, 9]); -} - -#[test] -fn array_clone_from() { - let mut v = ArrayVec::<[_; 4]>::new(); - v.push(vec![1, 2]); - v.push(vec![3, 4, 5]); - v.push(vec![6]); - let reference = v.to_vec(); - let mut u = ArrayVec::<[_; 4]>::new(); - u.clone_from(&v); - assert_eq!(&u, &reference[..]); - - let mut t = ArrayVec::<[_; 4]>::new(); - t.push(vec![97]); - t.push(vec![]); - t.push(vec![5, 6, 2]); - t.push(vec![2]); - t.clone_from(&v); - assert_eq!(&t, &reference[..]); - t.clear(); - t.clone_from(&v); - assert_eq!(&t, &reference[..]); -} - -#[test] -fn test_string() { - use std::error::Error; - - let text = "hello world"; - let mut s = ArrayString::<[_; 16]>::new(); - s.try_push_str(text).unwrap(); - assert_eq!(&s, text); - assert_eq!(text, &s); - - // Make sure Hash / Eq / Borrow match up so we can use HashMap - let mut map = HashMap::new(); - map.insert(s, 1); - assert_eq!(map[text], 1); - - let mut t = ArrayString::<[_; 2]>::new(); - assert!(t.try_push_str(text).is_err()); - assert_eq!(&t, ""); - - t.push_str("ab"); - // DerefMut - let tmut: &mut str = &mut t; - assert_eq!(tmut, "ab"); - - // Test Error trait / try - let t = || -> Result<(), Box> { - let mut t = ArrayString::<[_; 2]>::new(); - try!(t.try_push_str(text)); - Ok(()) - }(); - assert!(t.is_err()); -} - -#[test] -fn test_string_from() { - let text = "hello world"; - // Test `from` constructor - let u = ArrayString::<[_; 11]>::from(text).unwrap(); - assert_eq!(&u, text); - assert_eq!(u.len(), text.len()); -} - -#[test] -fn test_string_from_bytes() { - let text = "hello world"; - let u = ArrayString::from_byte_string(b"hello world").unwrap(); - assert_eq!(&u, text); - assert_eq!(u.len(), text.len()); -} - -#[test] -fn test_string_clone() { - let text = "hi"; - let mut s = ArrayString::<[_; 4]>::new(); - s.push_str("abcd"); - let t = ArrayString::<[_; 4]>::from(text).unwrap(); - s.clone_from(&t); - assert_eq!(&t, &s); -} - -#[test] -fn test_string_push() { - let text = "abcαβγ"; - let mut s = ArrayString::<[_; 8]>::new(); - for c in text.chars() { - if let Err(_) = s.try_push(c) { - break; - } - } - assert_eq!("abcαβ", &s[..]); - s.push('x'); - assert_eq!("abcαβx", &s[..]); - assert!(s.try_push('x').is_err()); -} - - -#[test] -fn test_insert_at_length() { - let mut v = ArrayVec::<[_; 8]>::new(); - let result1 = v.try_insert(0, "a"); - let result2 = v.try_insert(1, "b"); - assert!(result1.is_ok() && result2.is_ok()); - assert_eq!(&v[..], &["a", "b"]); -} - -#[should_panic] -#[test] -fn test_insert_out_of_bounds() { - let mut v = ArrayVec::<[_; 8]>::new(); - let _ = v.try_insert(1, "test"); -} - -/* - * insert that pushes out the last - let mut u = ArrayVec::from([1, 2, 3, 4]); - let ret = u.try_insert(3, 99); - assert_eq!(&u[..], &[1, 2, 3, 99]); - assert_matches!(ret, Err(_)); - let ret = u.try_insert(4, 77); - assert_eq!(&u[..], &[1, 2, 3, 99]); - assert_matches!(ret, Err(_)); -*/ - -#[test] -fn test_drop_in_insert() { - use std::cell::Cell; - - let flag = &Cell::new(0); - - struct Bump<'a>(&'a Cell); - - impl<'a> Drop for Bump<'a> { - fn drop(&mut self) { - let n = self.0.get(); - self.0.set(n + 1); - } - } - - flag.set(0); - - { - let mut array = ArrayVec::<[_; 2]>::new(); - array.push(Bump(flag)); - array.insert(0, Bump(flag)); - assert_eq!(flag.get(), 0); - let ret = array.try_insert(1, Bump(flag)); - assert_eq!(flag.get(), 0); - assert_matches!(ret, Err(_)); - drop(ret); - assert_eq!(flag.get(), 1); - } - assert_eq!(flag.get(), 3); -} - -#[test] -fn test_pop_at() { - let mut v = ArrayVec::<[String; 4]>::new(); - let s = String::from; - v.push(s("a")); - v.push(s("b")); - v.push(s("c")); - v.push(s("d")); - - assert_eq!(v.pop_at(4), None); - assert_eq!(v.pop_at(1), Some(s("b"))); - assert_eq!(v.pop_at(1), Some(s("c"))); - assert_eq!(v.pop_at(2), None); - assert_eq!(&v[..], &["a", "d"]); -} - -#[test] -fn test_sizes() { - let v = ArrayVec::from([0u8; 1 << 16]); - assert_eq!(vec![0u8; v.len()], &v[..]); -} - -#[test] -fn test_default() { - use std::net; - let s: ArrayString<[u8; 4]> = Default::default(); - // Something without `Default` implementation. - let v: ArrayVec<[net::TcpStream; 4]> = Default::default(); - assert_eq!(s.len(), 0); - assert_eq!(v.len(), 0); -} - -#[cfg(feature="array-sizes-33-128")] -#[test] -fn test_sizes_33_128() { - ArrayVec::from([0u8; 52]); - ArrayVec::from([0u8; 127]); -} - -#[cfg(feature="array-sizes-129-255")] -#[test] -fn test_sizes_129_255() { - ArrayVec::from([0u8; 237]); - ArrayVec::from([0u8; 255]); -} - - -#[test] -fn test_newish_stable_uses_maybe_uninit() { - if option_env!("ARRAYVECTEST_ENSURE_MAYBEUNINIT").map(|s| !s.is_empty()).unwrap_or(false) { - assert!(cfg!(has_stable_maybe_uninit)); - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/.cargo-checksum.json b/third_party/cargo/vendor/backtrace-0.3.45/.cargo-checksum.json deleted file mode 100644 index 298954c..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.lock":"11a048ab04993f1005160db171e0638db4235147bd79c05551f77b2cf8ec03e8","Cargo.toml":"d5efaaa4bd12f2edf680d1ce97869770c85a7da5ca39539f27f31b8b3f559113","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"5038903e047ac0287b2a16218109171c99a8b67242bdeaff52db51bd60b68fb0","benches/benchmarks.rs":"ce5763576fa8aeb722d3b8bcdb294d8a31e80e3c5272da25525fdcc392ccc6cc","ci/android-ndk.sh":"89fafa41d08ff477f949bfc163d04d1eb34fdee370f7a695cfba4ef34c164a55","ci/android-sdk.sh":"3269ef90675e8d4c2031e542cd3a55d9e060b2a094105cde982b282185936dda","ci/docker/aarch64-linux-android/Dockerfile":"cb5c55f17fcb0d65713086b8796de070657440cbcb6c2eded34b61b957b7bce8","ci/docker/aarch64-unknown-linux-gnu/Dockerfile":"97fa8f20c6899ee36b47371d485b64a2e96b626a2746b5f434c01eae9168b2a1","ci/docker/arm-linux-androideabi/Dockerfile":"3fe712b0927fd8fb05c1f733f0bf0d8a139bfc5a0108ba5515bd6b499976f1ab","ci/docker/arm-unknown-linux-gnueabihf/Dockerfile":"41133d712ef13f05e67796857db86476b3ed9c6355d5eb56115575b06d739e04","ci/docker/armv7-linux-androideabi/Dockerfile":"10783c6d22e727c38b2483ed5d941aeb8f1099025e263183f1598c604924ffa6","ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile":"2a216244baad705491f249278083994bf68744a2759f51e768b2f92e0da7c360","ci/docker/i586-unknown-linux-gnu/Dockerfile":"ef898c914590d721488ca11e62f3d7c26852346e1612deb0f3e12ab011187109","ci/docker/i686-linux-android/Dockerfile":"1a2119c2119a2213cf22a825166cd7bb75386fa057c7fabb2f572fc1e65f1870","ci/docker/i686-unknown-linux-gnu/Dockerfile":"ef898c914590d721488ca11e62f3d7c26852346e1612deb0f3e12ab011187109","ci/docker/powerpc64-unknown-linux-gnu/Dockerfile":"7cd511302c4624f0ee3944a6f5e4f5f25bb727ba2623d1e6b8f288a4d8cec30c","ci/docker/x86_64-linux-android/Dockerfile":"37f0bdcfed3d9382e09056e1f32351cbf6a901810d58060a4384a42303f2f7a3","ci/docker/x86_64-pc-windows-gnu/Dockerfile":"cbde261d7bcea43059e341363d57a00a83d9ebe4501aca2c1c6ba834e0ea9eb9","ci/docker/x86_64-unknown-linux-gnu/Dockerfile":"e1c202a6831b17e017b4737e80d5b992905895b086bbc06285fc9c337cadbc23","ci/docker/x86_64-unknown-linux-musl/Dockerfile":"2efbba08cc8fff8d2431dde92517df7d122dc754c778820c668f1ac29a885290","ci/run-docker.sh":"c4efad39c65a38c89e90d61a9ef15136903dd4cf01a6ae8079aa005b882d751e","ci/run.sh":"30a3807c195cd86d8b8884e1228cd061aa112b26c54277beebf5108777a36fe9","ci/runtest-android.rs":"be2e49bb296b92a8e3643a6c0a70917fe7b130fa43b71a29c4e7514f45c00e7e","examples/backtrace.rs":"fd6e1cc6c3378ec7d41cd03b2bef187051298dceb01147e71f207dbb8a0c4867","examples/raw.rs":"81fb66bd0f71010f9a954f667d92bf792cfd1ac90fa3a09c362767d866dc8374","src/backtrace/dbghelp.rs":"d5f56dc97d1e7cf2bed05ac6e922ca5be96aaab2f1098601343affd22241fa38","src/backtrace/libunwind.rs":"d006cdb883919d9dd138132216c83398987016264f67c714d07abdbf3383362a","src/backtrace/mod.rs":"8d9c7f5ab5cacc00b766d811fb6a38c57c78b42894c2499cd02ec802bb593b4c","src/backtrace/noop.rs":"9d9a93a890cef988b691232d9d1e7d114768ada58e9591345826135cb380f01a","src/backtrace/unix_backtrace.rs":"293c6ac31e9eb8e32dc7d219f4cf5dbeb9b66bdc42dcc949d1de63233dea2666","src/capture.rs":"c7c9f0a55312c9687d43118b69d4416d9c8eac1f7eaeb542807bc5e23bc18ce0","src/dbghelp.rs":"c33788eeef29bb78a1cdd7cf7f3e034b82d3686ba87d76a920692db19b26212b","src/lib.rs":"881e140db1f7e19bf3eb139881f102801aa9c06344282417b9b1e2c67534466a","src/print.rs":"2e7dbe0aaadb8c7457065773cf4210e863704e80aea12d3d2df163a0a259a258","src/print/fuchsia.rs":"4620968941adda90cec97d3cdfe06937327cdee5882f1b98bc933efaac68ef7a","src/symbolize/coresymbolication.rs":"f5442333d8c58188fe3c7749783336bd2e096ed9940d77c19ce4295dd592fb0b","src/symbolize/dbghelp.rs":"649d5ff1656e8fd84ab1088bb48054f6ea7cd0c50a09af09f72d562c17e52b6b","src/symbolize/dladdr.rs":"4b420b07f345f7c4e545c43f68d1b2d1f419a9228712097f35eae875b182b349","src/symbolize/dladdr_resolve.rs":"ec3bc5c8462cce48e97136e4867dd08a5f1b0c133e45d511745c1c3197e78405","src/symbolize/gimli.rs":"a4f68868d7e2d44e85549882fe7cfeffe4b31dcd263314dbadc467f2c0c843c0","src/symbolize/libbacktrace.rs":"d3f18a85fd13c32f949226e2d5cde3c40f60d73d32c46e91bf670cb202cf5f3b","src/symbolize/mod.rs":"4c2bb3a4b39f6c7773a2fb5ea206a109336ca7e60303d86948019624c51beed9","src/symbolize/noop.rs":"a8581b117e1065236c12f0a4a4c49f4c1929c4e6a3283f2253bb1fd0c77e4f7a","src/types.rs":"85dac420ee8791281f4cdec78e86be056c84ffecc0e5e5821d91862fc0e23444","src/windows.rs":"4a025bd064d22134185441859ab5337e31a33d39af212801fd7ada374595fd41","tests/accuracy/auxiliary.rs":"8bcf4a3a15ebed82f878c440910a07866efbc5eacea8b74f482dae297c779226","tests/accuracy/main.rs":"db2870e7fa51df01a5176e59bd87d205d83cad1599f374f273e11baf5efd41bb","tests/concurrent-panics.rs":"7c37df054c57c0c6694265bcaa596c1418a90cce65a569699e1b0c56bcd4bdfa","tests/long_fn_name.rs":"ca2480a72e8d2c02c678f047c202cdec7efafeb2fb32d94a327c669b7c81807a","tests/skip_inner_frames.rs":"b5c9137723c8648da46396c4c631e4b7d9933cac33397ae3da588a4692322212","tests/smoke.rs":"0330093fa76bd83851f2b8efb37330ce1c1c48d2be99313074d9c727491377f7"},"package":"ad235dabf00f36301792cfe82499880ba54c6486be094d1047b02bacb67c14e8"} \ No newline at end of file diff --git a/third_party/cargo/vendor/backtrace-0.3.45/BUILD b/third_party/cargo/vendor/backtrace-0.3.45/BUILD deleted file mode 100644 index da0723b..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/BUILD +++ /dev/null @@ -1,61 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "MIT,Apache-2.0" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - -# Unsupported target "accuracy" with type "test" omitted -# Unsupported target "backtrace" with type "example" omitted - -rust_library( - name = "backtrace", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2018", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/backtrace-sys-0.1.34:backtrace_sys", - "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", - "//third_party/cargo/vendor/libc-0.2.67:libc", - "//third_party/cargo/vendor/rustc-demangle-0.1.16:rustc_demangle", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.3.45", - crate_features = [ - "backtrace-sys", - "dbghelp", - "default", - "dladdr", - "libbacktrace", - "libunwind", - "std", - ], -) - -# Unsupported target "benchmarks" with type "bench" omitted -# Unsupported target "concurrent-panics" with type "test" omitted -# Unsupported target "long_fn_name" with type "test" omitted -# Unsupported target "raw" with type "example" omitted -# Unsupported target "skip_inner_frames" with type "test" omitted -# Unsupported target "smoke" with type "test" omitted diff --git a/third_party/cargo/vendor/backtrace-0.3.45/Cargo.lock b/third_party/cargo/vendor/backtrace-0.3.45/Cargo.lock deleted file mode 100644 index 5afcf92..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/Cargo.lock +++ /dev/null @@ -1,314 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -[[package]] -name = "addr2line" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "fallible-iterator 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gimli 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)", - "lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "arrayvec" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "backtrace" -version = "0.3.45" -dependencies = [ - "addr2line 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "backtrace-sys 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)", - "cpp_demangle 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", - "findshlibs 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "goblin 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", - "memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "backtrace-sys" -version = "0.1.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "byteorder" -version = "1.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cc" -version = "1.0.50" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "compiler_builtins 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "compiler_builtins" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "cpp_demangle" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "fallible-iterator" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "findshlibs" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "gimli" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", - "fallible-iterator 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "goblin" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", - "plain 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "scroll 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "lazycell" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "libc" -version = "0.2.67" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "log" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "memmap" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "plain" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "proc-macro2" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "quote" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "compiler_builtins 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)", - "rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "rustc-serialize" -version = "0.3.24" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "rustc-std-workspace-core" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "scroll" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "scroll_derive 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "scroll_derive" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.16 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "serde" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "serde_derive" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.16 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "smallvec" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "stable_deref_trait" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "syn" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unicode-xid" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "winapi" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[metadata] -"checksum addr2line 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1c4e698660ed2d0f625c39bb877332b4269668720e330e2aa3d67bb1187a656a" -"checksum arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" -"checksum backtrace-sys 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)" = "e17b52e737c40a7d75abca20b29a19a0eb7ba9fc72c5a72dd282a0a3c2c0dc35" -"checksum byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" -"checksum cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)" = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" -"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" -"checksum compiler_builtins 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)" = "036b035e9ebcd705affece16319223d19f229e2358be6e3b7b094e57193312e6" -"checksum cpp_demangle 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "4115af6f575a7bc82c613e9e0ed7cc36a5e4fc3a8b54920dc0c820823a31a0d6" -"checksum fallible-iterator 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" -"checksum findshlibs 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1260d61e4fe2a6ab845ffdc426a0bd68ffb240b91cf0ec5a8d1170cec535bd8" -"checksum gimli 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)" = "81dd6190aad0f05ddbbf3245c54ed14ca4aa6dd32f22312b70d8f168c3e3e633" -"checksum glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" -"checksum goblin 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0259546d6aed5dd1f4efc3ae663cae62912ceb927c0e96ae1fc8a22ab1516763" -"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" -"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" -"checksum libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)" = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" -"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" -"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" -"checksum plain 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" -"checksum proc-macro2 1.0.9 (registry+https://github.com/rust-lang/crates.io-index)" = "6c09721c6781493a2a492a96b5a5bf19b65917fe6728884e7c44dd0c60ca3435" -"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" -"checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" -"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" -"checksum rustc-std-workspace-core 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1956f5517128a2b6f23ab2dadf1a976f4f5b27962e7724c2bf3d45e539ec098c" -"checksum scroll 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "abb2332cb595d33f7edd5700f4cbf94892e680c7f0ae56adab58a35190b66cb1" -"checksum scroll_derive 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8584eea9b9ff42825b46faf46a8c24d2cff13ec152fa2a50df788b87c07ee28" -"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" -"checksum serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" -"checksum smallvec 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" -"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" -"checksum syn 1.0.16 (registry+https://github.com/rust-lang/crates.io-index)" = "123bd9499cfb380418d509322d7a6d52e5315f064fe4b3ad18a53d6b92c07859" -"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" -"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" -"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/third_party/cargo/vendor/backtrace-0.3.45/Cargo.toml b/third_party/cargo/vendor/backtrace-0.3.45/Cargo.toml deleted file mode 100644 index 80c8446..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/Cargo.toml +++ /dev/null @@ -1,132 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -edition = "2018" -name = "backtrace" -version = "0.3.45" -authors = ["The Rust Project Developers"] -autoexamples = true -autotests = true -description = "A library to acquire a stack trace (backtrace) at runtime in a Rust program.\n" -homepage = "https://github.com/rust-lang/backtrace-rs" -documentation = "https://docs.rs/backtrace" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/backtrace-rs" - -[[example]] -name = "backtrace" -required-features = ["std"] - -[[example]] -name = "raw" -required-features = ["std"] - -[[test]] -name = "skip_inner_frames" -required-features = ["std"] - -[[test]] -name = "long_fn_name" -required-features = ["std"] - -[[test]] -name = "smoke" -required-features = ["std"] -edition = "2018" - -[[test]] -name = "accuracy" -required-features = ["std", "dbghelp", "libbacktrace", "libunwind"] -edition = "2018" - -[[test]] -name = "concurrent-panics" -harness = false -required-features = ["std"] -[dependencies.addr2line] -version = "0.11.0" -features = ["std"] -optional = true -default-features = false - -[dependencies.backtrace-sys] -version = "0.1.33" -optional = true -default_features = false - -[dependencies.cfg-if] -version = "0.1.10" - -[dependencies.compiler_builtins] -version = "0.1.2" -optional = true - -[dependencies.core] -version = "1.0.0" -optional = true -package = "rustc-std-workspace-core" - -[dependencies.cpp_demangle] -version = "0.2.3" -optional = true -default-features = false - -[dependencies.findshlibs] -version = "0.5.0" -optional = true - -[dependencies.goblin] -version = "0.2" -features = ["elf32", "elf64", "mach32", "mach64", "pe32", "pe64", "std"] -optional = true -default-features = false - -[dependencies.libc] -version = "0.2.45" -default-features = false - -[dependencies.memmap] -version = "0.7.0" -optional = true - -[dependencies.rustc-demangle] -version = "0.1.4" - -[dependencies.rustc-serialize] -version = "0.3" -optional = true - -[dependencies.serde] -version = "1.0" -features = ["derive"] -optional = true - -[features] -coresymbolication = [] -dbghelp = [] -default = ["std", "libunwind", "libbacktrace", "dladdr", "dbghelp"] -dladdr = [] -gimli-symbolize = ["addr2line", "findshlibs", "memmap", "goblin"] -kernel32 = [] -libbacktrace = ["backtrace-sys/backtrace-sys"] -libunwind = [] -rustc-dep-of-std = ["backtrace-sys/rustc-dep-of-std", "cfg-if/rustc-dep-of-std", "core", "compiler_builtins", "libc/rustc-dep-of-std", "rustc-demangle/rustc-dep-of-std"] -serialize-rustc = ["rustc-serialize"] -serialize-serde = ["serde"] -std = [] -unix-backtrace = [] -verify-winapi = ["winapi/dbghelp", "winapi/handleapi", "winapi/libloaderapi", "winapi/minwindef", "winapi/processthreadsapi", "winapi/synchapi", "winapi/winbase", "winapi/winnt"] -[target."cfg(windows)".dependencies.winapi] -version = "0.3.3" -optional = true diff --git a/third_party/cargo/vendor/backtrace-0.3.45/README.md b/third_party/cargo/vendor/backtrace-0.3.45/README.md deleted file mode 100644 index 9713f0c..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# backtrace-rs - -[Documentation](https://docs.rs/backtrace) - -A library for acquiring backtraces at runtime for Rust. This library aims to -enhance the support of the standard library by providing a programmatic -interface to work with, but it also supports simply easily printing the current -backtrace like libstd's panics. - -## Install - -```toml -[dependencies] -backtrace = "0.3" -``` - -Note that this crate requires `cc` and `ar` to be present on Unix systems when -`libbacktrace` is used (which is the default). For configuring C compilers see -the [`cc` crate documentation](https://github.com/alexcrichton/cc-rs). - -## Usage - -To simply capture a backtrace and defer dealing with it until a later time, -you can use the top-level `Backtrace` type. - -```rust -extern crate backtrace; - -use backtrace::Backtrace; - -fn main() { - let bt = Backtrace::new(); - - // do_some_work(); - - println!("{:?}", bt); -} -``` - -If, however, you'd like more raw access to the actual tracing functionality, you -can use the `trace` and `resolve` functions directly. - -```rust -extern crate backtrace; - -fn main() { - backtrace::trace(|frame| { - let ip = frame.ip(); - let symbol_address = frame.symbol_address(); - - // Resolve this instruction pointer to a symbol name - backtrace::resolve_frame(frame, |symbol| { - if let Some(name) = symbol.name() { - // ... - } - if let Some(filename) = symbol.filename() { - // ... - } - }); - - true // keep going to the next frame - }); -} -``` - -# License - -This project 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 backtrace-rs by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff --git a/third_party/cargo/vendor/backtrace-0.3.45/benches/benchmarks.rs b/third_party/cargo/vendor/backtrace-0.3.45/benches/benchmarks.rs deleted file mode 100644 index ad55788..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/benches/benchmarks.rs +++ /dev/null @@ -1,94 +0,0 @@ -#![feature(test)] - -extern crate test; - -extern crate backtrace; - -#[cfg(feature = "std")] -use backtrace::Backtrace; - -#[bench] -#[cfg(feature = "std")] -fn trace(b: &mut test::Bencher) { - #[inline(never)] - fn the_function() { - backtrace::trace(|frame| { - let ip = frame.ip(); - test::black_box(ip); - true - }); - } - b.iter(the_function); -} - -#[bench] -#[cfg(feature = "std")] -fn trace_and_resolve_callback(b: &mut test::Bencher) { - #[inline(never)] - fn the_function() { - backtrace::trace(|frame| { - backtrace::resolve(frame.ip(), |symbol| { - let addr = symbol.addr(); - test::black_box(addr); - }); - true - }); - } - b.iter(the_function); -} - -#[bench] -#[cfg(feature = "std")] -fn trace_and_resolve_separate(b: &mut test::Bencher) { - #[inline(never)] - fn the_function(frames: &mut Vec<*mut std::ffi::c_void>) { - backtrace::trace(|frame| { - frames.push(frame.ip()); - true - }); - frames.iter().for_each(|frame_ip| { - backtrace::resolve(*frame_ip, |symbol| { - test::black_box(symbol); - }); - }); - } - let mut frames = Vec::with_capacity(1024); - b.iter(|| { - the_function(&mut frames); - frames.clear(); - }); -} - -#[bench] -#[cfg(feature = "std")] -fn new_unresolved(b: &mut test::Bencher) { - #[inline(never)] - fn the_function() { - let bt = Backtrace::new_unresolved(); - test::black_box(bt); - } - b.iter(the_function); -} - -#[bench] -#[cfg(feature = "std")] -fn new(b: &mut test::Bencher) { - #[inline(never)] - fn the_function() { - let bt = Backtrace::new(); - test::black_box(bt); - } - b.iter(the_function); -} - -#[bench] -#[cfg(feature = "std")] -fn new_unresolved_and_resolve_separate(b: &mut test::Bencher) { - #[inline(never)] - fn the_function() { - let mut bt = Backtrace::new_unresolved(); - bt.resolve(); - test::black_box(bt); - } - b.iter(the_function); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/android-ndk.sh b/third_party/cargo/vendor/backtrace-0.3.45/ci/android-ndk.sh deleted file mode 100755 index b5df62b..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/android-ndk.sh +++ /dev/null @@ -1,23 +0,0 @@ -set -ex - -ANDROID_ARCH=$1 -ANDROID_SDK_VERSION=4333796 - -mkdir /tmp/android -cd /tmp/android - -curl -o android-sdk.zip \ - "https://dl.google.com/android/repository/sdk-tools-linux-${ANDROID_SDK_VERSION}.zip" -unzip -q android-sdk.zip - -yes | ./tools/bin/sdkmanager --licenses > /dev/null -./tools/bin/sdkmanager ndk-bundle > /dev/null - -./ndk-bundle/build/tools/make_standalone_toolchain.py \ - --arch $ANDROID_ARCH \ - --stl=libc++ \ - --api 21 \ - --install-dir /android-toolchain - -cd /tmp -rm -rf android diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/android-sdk.sh b/third_party/cargo/vendor/backtrace-0.3.45/ci/android-sdk.sh deleted file mode 100755 index aee133e..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/android-sdk.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/usr/bin/env sh -# Copyright 2016 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 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -# Prep the SDK and emulator -# -# Note that the update process requires that we accept a bunch of licenses, and -# we can't just pipe `yes` into it for some reason, so we take the same strategy -# located in https://github.com/appunite/docker by just wrapping it in a script -# which apparently magically accepts the licenses. - -SDK=4333796 -mkdir sdk -curl --retry 20 https://dl.google.com/android/repository/sdk-tools-linux-${SDK}.zip -O -unzip -q -d sdk sdk-tools-linux-${SDK}.zip - -case "$1" in - arm | armv7) - api=24 - image="system-images;android-${api};google_apis;armeabi-v7a" - ;; - aarch64) - api=24 - image="system-images;android-${api};google_apis;arm64-v8a" - ;; - i686) - api=28 - image="system-images;android-${api};default;x86" - ;; - x86_64) - api=28 - image="system-images;android-${api};default;x86_64" - ;; - *) - echo "invalid arch: $1" - exit 1 - ;; -esac; - -# Try to fix warning about missing file. -# See https://askubuntu.com/a/1078784 -mkdir -p /root/.android/ -echo '### User Sources for Android SDK Manager' >> /root/.android/repositories.cfg -echo '#Fri Nov 03 10:11:27 CET 2017 count=0' >> /root/.android/repositories.cfg - -# Print all available packages -# yes | ./sdk/tools/bin/sdkmanager --list --verbose - -# --no_https avoids -# javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found -# -# | grep -v = || true removes the progress bar output from the sdkmanager -# which produces an insane amount of output. -yes | ./sdk/tools/bin/sdkmanager --licenses --no_https | grep -v = || true -yes | ./sdk/tools/bin/sdkmanager --no_https \ - "emulator" \ - "platform-tools" \ - "platforms;android-${api}" \ - "${image}" | grep -v = || true - -echo "no" | - ./sdk/tools/bin/avdmanager create avd \ - --name "${1}" \ - --package "${image}" | grep -v = || true - diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-linux-android/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-linux-android/Dockerfile deleted file mode 100644 index 81c8208..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-linux-android/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - ca-certificates \ - unzip \ - openjdk-8-jre \ - python \ - gcc \ - libc6-dev - -COPY android-ndk.sh / -RUN /android-ndk.sh arm64 -ENV PATH=$PATH:/android-toolchain/bin - -# TODO: run tests in an emulator eventually -ENV CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=aarch64-linux-android-gcc \ - CARGO_TARGET_AARCH64_LINUX_ANDROID_RUNNER=echo diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-unknown-linux-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-unknown-linux-gnu/Dockerfile deleted file mode 100644 index d691aa4..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/aarch64-unknown-linux-gnu/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - ca-certificates \ - libc6-dev \ - gcc-aarch64-linux-gnu \ - libc6-dev-arm64-cross \ - qemu-user - -ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \ - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER="qemu-aarch64 -L /usr/aarch64-linux-gnu" diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-linux-androideabi/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-linux-androideabi/Dockerfile deleted file mode 100644 index 7cfdae6..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-linux-androideabi/Dockerfile +++ /dev/null @@ -1,37 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - ca-certificates \ - unzip \ - openjdk-8-jre \ - python \ - gcc \ - libc6-dev - -COPY android-ndk.sh / -RUN /android-ndk.sh arm -WORKDIR /android -COPY android-sdk.sh /android/sdk.sh -RUN ./sdk.sh arm -RUN mv /root/.android /tmp -RUN chmod 777 -R /tmp/.android -RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* -ENV PATH=$PATH:/android-toolchain/bin:/android/sdk/platform-tools - -# TODO: run tests in an emulator eventually -ENV CARGO_TARGET_ARM_LINUX_ANDROIDEABI_LINKER=arm-linux-androideabi-gcc \ - CARGO_TARGET_ARM_LINUX_ANDROIDEABI_RUNNER=/tmp/runtest \ - HOME=/tmp - -ADD runtest-android.rs /tmp/runtest.rs -ENTRYPOINT [ \ - "bash", \ - "-c", \ - # set SHELL so android can detect a 64bits system, see - # http://stackoverflow.com/a/41789144 - "SHELL=/bin/dash /android/sdk/emulator/emulator @arm -no-window & \ - /rust/bin/rustc /tmp/runtest.rs -o /tmp/runtest && \ - exec \"$@\"", \ - "--" \ -] diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile deleted file mode 100644 index 32095e9..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - ca-certificates \ - libc6-dev \ - gcc-arm-linux-gnueabihf \ - libc6-dev-armhf-cross \ - qemu-user -ENV CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \ - CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_RUNNER="qemu-arm -L /usr/arm-linux-gnueabihf" diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-linux-androideabi/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-linux-androideabi/Dockerfile deleted file mode 100644 index c738716..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-linux-androideabi/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - ca-certificates \ - unzip \ - openjdk-8-jre \ - python \ - gcc \ - libc6-dev - -COPY android-ndk.sh / -RUN /android-ndk.sh arm -ENV PATH=$PATH:/android-toolchain/bin - -# TODO: run tests in an emulator eventually -ENV CARGO_TARGET_ARMV7_LINUX_ANDROIDEABI_LINKER=arm-linux-androideabi-gcc \ - CARGO_TARGET_ARMV7_LINUX_ANDROIDEABI_RUNNER=echo diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile deleted file mode 100644 index a55fb27..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/armv7-unknown-linux-gnueabihf/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - ca-certificates \ - libc6-dev \ - gcc-arm-linux-gnueabihf \ - libc6-dev-armhf-cross \ - qemu-user -ENV CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \ - CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_RUNNER="qemu-arm -L /usr/arm-linux-gnueabihf" diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i586-unknown-linux-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i586-unknown-linux-gnu/Dockerfile deleted file mode 100644 index d222092..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i586-unknown-linux-gnu/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc-multilib \ - libc6-dev \ - ca-certificates diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-linux-android/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-linux-android/Dockerfile deleted file mode 100644 index ef4752c..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-linux-android/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - ca-certificates \ - unzip \ - openjdk-8-jre \ - python \ - gcc \ - libc6-dev - -COPY android-ndk.sh / -RUN /android-ndk.sh x86 -ENV PATH=$PATH:/android-toolchain/bin - -# TODO: run tests in an emulator eventually -ENV CARGO_TARGET_I686_LINUX_ANDROID_LINKER=i686-linux-android-gcc \ - CARGO_TARGET_I686_LINUX_ANDROID_RUNNER=echo diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-unknown-linux-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-unknown-linux-gnu/Dockerfile deleted file mode 100644 index d222092..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/i686-unknown-linux-gnu/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc-multilib \ - libc6-dev \ - ca-certificates diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile deleted file mode 100644 index b4f5d8a..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - ca-certificates \ - libc6-dev \ - gcc-powerpc64-linux-gnu \ - libc6-dev-ppc64-cross \ - qemu-user \ - qemu-system-ppc - -ENV CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_LINKER=powerpc64-linux-gnu-gcc \ - # TODO: should actually run these tests - #CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc64 -L /usr/powerpc64-linux-gnu" \ - CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_RUNNER=echo \ - CC=powerpc64-linux-gnu-gcc diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-linux-android/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-linux-android/Dockerfile deleted file mode 100644 index 7fea8a1..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-linux-android/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM ubuntu:18.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - ca-certificates \ - unzip \ - openjdk-8-jre \ - python \ - gcc \ - libc6-dev - -COPY android-ndk.sh / -RUN /android-ndk.sh x86_64 -ENV PATH=$PATH:/android-toolchain/bin - -# TODO: run tests in an emulator eventually -ENV CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER=x86_64-linux-android-gcc \ - CARGO_TARGET_X86_64_LINUX_ANDROID_RUNNER=echo diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-pc-windows-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-pc-windows-gnu/Dockerfile deleted file mode 100644 index 7a8fbf4..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-pc-windows-gnu/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - libc6-dev \ - ca-certificates \ - gcc-mingw-w64-x86-64 - -# No need to run tests, we're just testing that it compiles -ENV CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=echo \ - CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=x86_64-w64-mingw32-gcc diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-gnu/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-gnu/Dockerfile deleted file mode 100644 index 864d72e..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-gnu/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - libc6-dev \ - ca-certificates diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-musl/Dockerfile b/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-musl/Dockerfile deleted file mode 100644 index 6984dc2..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/docker/x86_64-unknown-linux-musl/Dockerfile +++ /dev/null @@ -1,6 +0,0 @@ -FROM ubuntu:18.04 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc \ - libc6-dev \ - ca-certificates \ - musl-tools diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/run-docker.sh b/third_party/cargo/vendor/backtrace-0.3.45/ci/run-docker.sh deleted file mode 100755 index 5a9934b..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/run-docker.sh +++ /dev/null @@ -1,32 +0,0 @@ -# Small script to run tests for a target (or all targets) inside all the -# respective docker images. - -set -ex - -run() { - docker build -t backtrace -f ci/docker/$1/Dockerfile ci - mkdir -p target - docker run \ - --user `id -u`:`id -g` \ - --rm \ - --init \ - --volume $(dirname $(dirname `which cargo`)):/cargo \ - --env CARGO_HOME=/cargo \ - --volume `rustc --print sysroot`:/rust:ro \ - --env TARGET=$1 \ - --volume `pwd`:/checkout:ro \ - --volume `pwd`/target:/checkout/target \ - --workdir /checkout \ - --privileged \ - backtrace \ - bash \ - -c 'PATH=$PATH:/rust/bin exec ci/run.sh' -} - -if [ -z "$1" ]; then - for d in `ls ci/docker/`; do - run $d - done -else - run $1 -fi diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/run.sh b/third_party/cargo/vendor/backtrace-0.3.45/ci/run.sh deleted file mode 100755 index 5cc1515..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/run.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -set -ex - -cargo test --target $TARGET diff --git a/third_party/cargo/vendor/backtrace-0.3.45/ci/runtest-android.rs b/third_party/cargo/vendor/backtrace-0.3.45/ci/runtest-android.rs deleted file mode 100644 index dc70121..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/ci/runtest-android.rs +++ /dev/null @@ -1,50 +0,0 @@ -use std::env; -use std::process::Command; -use std::path::{Path, PathBuf}; - -fn main() { - let args = env::args_os() - .skip(1) - .filter(|arg| arg != "--quiet") - .collect::>(); - assert_eq!(args.len(), 1); - let test = PathBuf::from(&args[0]); - let dst = Path::new("/data/local/tmp").join(test.file_name().unwrap()); - - println!("waiting for device to come online..."); - let status = Command::new("adb") - .arg("wait-for-device") - .status() - .expect("failed to run: adb wait-for-device"); - assert!(status.success()); - - println!("pushing executable..."); - let status = Command::new("adb") - .arg("push") - .arg(&test) - .arg(&dst) - .status() - .expect("failed to run: adb pushr"); - assert!(status.success()); - - println!("executing tests..."); - let output = Command::new("adb") - .arg("shell") - .arg(&dst) - .output() - .expect("failed to run: adb shell"); - assert!(status.success()); - - println!("status: {}\nstdout ---\n{}\nstderr ---\n{}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr)); - - let stdout = String::from_utf8_lossy(&output.stdout); - stdout.lines().find(|l| - (l.starts_with("PASSED ") && l.contains(" tests")) || - l.starts_with("test result: ok") - ).unwrap_or_else(|| { - panic!("failed to find successful test run"); - }); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/examples/backtrace.rs b/third_party/cargo/vendor/backtrace-0.3.45/examples/backtrace.rs deleted file mode 100644 index 7f9042e..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/examples/backtrace.rs +++ /dev/null @@ -1,7 +0,0 @@ -extern crate backtrace; - -use backtrace::Backtrace; - -fn main() { - println!("{:?}", Backtrace::new()); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/examples/raw.rs b/third_party/cargo/vendor/backtrace-0.3.45/examples/raw.rs deleted file mode 100644 index b43cab8..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/examples/raw.rs +++ /dev/null @@ -1,54 +0,0 @@ -extern crate backtrace; - -fn main() { - foo(); -} - -fn foo() { - bar() -} -fn bar() { - baz() -} -fn baz() { - print() -} - -#[cfg(target_pointer_width = "32")] -const HEX_WIDTH: usize = 10; -#[cfg(target_pointer_width = "64")] -const HEX_WIDTH: usize = 20; - -fn print() { - let mut cnt = 0; - backtrace::trace(|frame| { - let ip = frame.ip(); - print!("frame #{:<2} - {:#02$x}", cnt, ip as usize, HEX_WIDTH); - cnt += 1; - - let mut resolved = false; - backtrace::resolve(frame.ip(), |symbol| { - if !resolved { - resolved = true; - } else { - print!("{}", vec![" "; 7 + 2 + 3 + HEX_WIDTH].join("")); - } - - if let Some(name) = symbol.name() { - print!(" - {}", name); - } else { - print!(" - "); - } - if let Some(file) = symbol.filename() { - if let Some(l) = symbol.lineno() { - print!("\n{:13}{:4$}@ {}:{}", "", "", file.display(), l, HEX_WIDTH); - } - } - println!(""); - }); - if !resolved { - println!(" - "); - } - true // keep going - }); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/dbghelp.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/dbghelp.rs deleted file mode 100644 index 40de143..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/dbghelp.rs +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Backtrace strategy for MSVC platforms. -//! -//! This module contains the ability to generate a backtrace on MSVC using one -//! of two possible methods. The `StackWalkEx` function is primarily used if -//! possible, but not all systems have that. Failing that the `StackWalk64` -//! function is used instead. Note that `StackWalkEx` is favored because it -//! handles debuginfo internally and returns inline frame information. -//! -//! Note that all dbghelp support is loaded dynamically, see `src/dbghelp.rs` -//! for more information about that. - -#![allow(bad_style)] - -use crate::dbghelp; -use crate::windows::*; -use core::ffi::c_void; -use core::mem; - -#[derive(Clone, Copy)] -pub enum Frame { - New(STACKFRAME_EX), - Old(STACKFRAME64), -} - -// we're just sending around raw pointers and reading them, never interpreting -// them so this should be safe to both send and share across threads. -unsafe impl Send for Frame {} -unsafe impl Sync for Frame {} - -impl Frame { - pub fn ip(&self) -> *mut c_void { - self.addr_pc().Offset as *mut _ - } - - pub fn symbol_address(&self) -> *mut c_void { - self.ip() - } - - fn addr_pc(&self) -> &ADDRESS64 { - match self { - Frame::New(new) => &new.AddrPC, - Frame::Old(old) => &old.AddrPC, - } - } - - fn addr_pc_mut(&mut self) -> &mut ADDRESS64 { - match self { - Frame::New(new) => &mut new.AddrPC, - Frame::Old(old) => &mut old.AddrPC, - } - } - - fn addr_frame_mut(&mut self) -> &mut ADDRESS64 { - match self { - Frame::New(new) => &mut new.AddrFrame, - Frame::Old(old) => &mut old.AddrFrame, - } - } - - fn addr_stack_mut(&mut self) -> &mut ADDRESS64 { - match self { - Frame::New(new) => &mut new.AddrStack, - Frame::Old(old) => &mut old.AddrStack, - } - } -} - -#[repr(C, align(16))] // required by `CONTEXT`, is a FIXME in winapi right now -struct MyContext(CONTEXT); - -#[inline(always)] -pub unsafe fn trace(cb: &mut FnMut(&super::Frame) -> bool) { - // Allocate necessary structures for doing the stack walk - let process = GetCurrentProcess(); - let thread = GetCurrentThread(); - - let mut context = mem::zeroed::(); - RtlCaptureContext(&mut context.0); - - // Ensure this process's symbols are initialized - let dbghelp = match dbghelp::init() { - Ok(dbghelp) => dbghelp, - Err(()) => return, // oh well... - }; - - // On x86_64 and ARM64 we opt to not use the default `Sym*` functions from - // dbghelp for getting the function table and module base. Instead we use - // the `RtlLookupFunctionEntry` function in kernel32 which will account for - // JIT compiler frames as well. These should be equivalent, but using - // `Rtl*` allows us to backtrace through JIT frames. - // - // Note that `RtlLookupFunctionEntry` only works for in-process backtraces, - // but that's all we support anyway, so it all lines up well. - cfg_if::cfg_if! { - if #[cfg(target_pointer_width = "64")] { - use core::ptr; - - unsafe extern "system" fn function_table_access(_process: HANDLE, addr: DWORD64) -> PVOID { - let mut base = 0; - RtlLookupFunctionEntry(addr, &mut base, ptr::null_mut()).cast() - } - - unsafe extern "system" fn get_module_base(_process: HANDLE, addr: DWORD64) -> DWORD64 { - let mut base = 0; - RtlLookupFunctionEntry(addr, &mut base, ptr::null_mut()); - base - } - } else { - let function_table_access = dbghelp.SymFunctionTableAccess64(); - let get_module_base = dbghelp.SymGetModuleBase64(); - } - } - - // Attempt to use `StackWalkEx` if we can, but fall back to `StackWalk64` - // since it's in theory supported on more systems. - match (*dbghelp.dbghelp()).StackWalkEx() { - Some(StackWalkEx) => { - let mut frame = super::Frame { - inner: Frame::New(mem::zeroed()), - }; - let image = init_frame(&mut frame.inner, &context.0); - let frame_ptr = match &mut frame.inner { - Frame::New(ptr) => ptr as *mut STACKFRAME_EX, - _ => unreachable!(), - }; - - while StackWalkEx( - image as DWORD, - process, - thread, - frame_ptr, - &mut context.0 as *mut CONTEXT as *mut _, - None, - Some(function_table_access), - Some(get_module_base), - None, - 0, - ) == TRUE - { - if !cb(&frame) { - break; - } - } - } - None => { - let mut frame = super::Frame { - inner: Frame::Old(mem::zeroed()), - }; - let image = init_frame(&mut frame.inner, &context.0); - let frame_ptr = match &mut frame.inner { - Frame::Old(ptr) => ptr as *mut STACKFRAME64, - _ => unreachable!(), - }; - - while dbghelp.StackWalk64()( - image as DWORD, - process, - thread, - frame_ptr, - &mut context.0 as *mut CONTEXT as *mut _, - None, - Some(function_table_access), - Some(get_module_base), - None, - ) == TRUE - { - if !cb(&frame) { - break; - } - } - } - } -} - -#[cfg(target_arch = "x86_64")] -fn init_frame(frame: &mut Frame, ctx: &CONTEXT) -> WORD { - frame.addr_pc_mut().Offset = ctx.Rip as u64; - frame.addr_pc_mut().Mode = AddrModeFlat; - frame.addr_stack_mut().Offset = ctx.Rsp as u64; - frame.addr_stack_mut().Mode = AddrModeFlat; - frame.addr_frame_mut().Offset = ctx.Rbp as u64; - frame.addr_frame_mut().Mode = AddrModeFlat; - - IMAGE_FILE_MACHINE_AMD64 -} - -#[cfg(target_arch = "x86")] -fn init_frame(frame: &mut Frame, ctx: &CONTEXT) -> WORD { - frame.addr_pc_mut().Offset = ctx.Eip as u64; - frame.addr_pc_mut().Mode = AddrModeFlat; - frame.addr_stack_mut().Offset = ctx.Esp as u64; - frame.addr_stack_mut().Mode = AddrModeFlat; - frame.addr_frame_mut().Offset = ctx.Ebp as u64; - frame.addr_frame_mut().Mode = AddrModeFlat; - - IMAGE_FILE_MACHINE_I386 -} - -#[cfg(target_arch = "aarch64")] -fn init_frame(frame: &mut Frame, ctx: &CONTEXT) -> WORD { - frame.addr_pc_mut().Offset = ctx.Pc as u64; - frame.addr_pc_mut().Mode = AddrModeFlat; - frame.addr_stack_mut().Offset = ctx.Sp as u64; - frame.addr_stack_mut().Mode = AddrModeFlat; - unsafe { - frame.addr_frame_mut().Offset = ctx.u.s().Fp as u64; - } - frame.addr_frame_mut().Mode = AddrModeFlat; - IMAGE_FILE_MACHINE_ARM64 -} - -#[cfg(target_arch = "arm")] -fn init_frame(frame: &mut Frame, ctx: &CONTEXT) -> WORD { - frame.addr_pc_mut().Offset = ctx.Pc as u64; - frame.addr_pc_mut().Mode = AddrModeFlat; - frame.addr_stack_mut().Offset = ctx.Sp as u64; - frame.addr_stack_mut().Mode = AddrModeFlat; - unsafe { - frame.addr_frame_mut().Offset = ctx.R11 as u64; - } - frame.addr_frame_mut().Mode = AddrModeFlat; - IMAGE_FILE_MACHINE_ARMNT -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/libunwind.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/libunwind.rs deleted file mode 100644 index 21af00c..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/libunwind.rs +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Backtrace support using libunwind/gcc_s/etc APIs. -//! -//! This module contains the ability to unwind the stack using libunwind-style -//! APIs. Note that there's a whole bunch of implementations of the -//! libunwind-like API, and this is just trying to be compatible with most of -//! them all at once instead of being picky. -//! -//! The libunwind API is powered by `_Unwind_Backtrace` and is in practice very -//! reliable at generating a backtrace. It's not entirely clear how it does it -//! (frame pointers? eh_frame info? both?) but it seems to work! -//! -//! Most of the complexity of this module is handling the various platform -//! differences across libunwind implementations. Otherwise this is a pretty -//! straightforward Rust binding to the libunwind APIs. -//! -//! This is the default unwinding API for all non-Windows platforms currently. - -use core::ffi::c_void; - -pub enum Frame { - Raw(*mut uw::_Unwind_Context), - Cloned { - ip: *mut c_void, - symbol_address: *mut c_void, - }, -} - -// With a raw libunwind pointer it should only ever be access in a readonly -// threadsafe fashion, so it's `Sync`. When sending to other threads via `Clone` -// we always switch to a version which doesn't retain interior pointers, so we -// should be `Send` as well. -unsafe impl Send for Frame {} -unsafe impl Sync for Frame {} - -impl Frame { - pub fn ip(&self) -> *mut c_void { - let ctx = match *self { - Frame::Raw(ctx) => ctx, - Frame::Cloned { ip, .. } => return ip, - }; - unsafe { uw::_Unwind_GetIP(ctx) as *mut c_void } - } - - pub fn symbol_address(&self) -> *mut c_void { - if let Frame::Cloned { symbol_address, .. } = *self { - return symbol_address; - } - - // It seems that on OSX `_Unwind_FindEnclosingFunction` returns a - // pointer to... something that's unclear. It's definitely not always - // the enclosing function for whatever reason. It's not entirely clear - // to me what's going on here, so pessimize this for now and just always - // return the ip. - // - // Note the `skip_inner_frames.rs` test is skipped on OSX due to this - // clause, and if this is fixed that test in theory can be run on OSX! - if cfg!(target_os = "macos") || cfg!(target_os = "ios") { - self.ip() - } else { - unsafe { uw::_Unwind_FindEnclosingFunction(self.ip()) } - } - } -} - -impl Clone for Frame { - fn clone(&self) -> Frame { - Frame::Cloned { - ip: self.ip(), - symbol_address: self.symbol_address(), - } - } -} - -#[inline(always)] -pub unsafe fn trace(mut cb: &mut FnMut(&super::Frame) -> bool) { - uw::_Unwind_Backtrace(trace_fn, &mut cb as *mut _ as *mut _); - - extern "C" fn trace_fn( - ctx: *mut uw::_Unwind_Context, - arg: *mut c_void, - ) -> uw::_Unwind_Reason_Code { - let cb = unsafe { &mut *(arg as *mut &mut FnMut(&super::Frame) -> bool) }; - let cx = super::Frame { - inner: Frame::Raw(ctx), - }; - - let mut bomb = crate::Bomb { enabled: true }; - let keep_going = cb(&cx); - bomb.enabled = false; - - if keep_going { - uw::_URC_NO_REASON - } else { - uw::_URC_FAILURE - } - } -} - -/// Unwind library interface used for backtraces -/// -/// Note that dead code is allowed as here are just bindings -/// iOS doesn't use all of them it but adding more -/// platform-specific configs pollutes the code too much -#[allow(non_camel_case_types)] -#[allow(non_snake_case)] -#[allow(dead_code)] -mod uw { - pub use self::_Unwind_Reason_Code::*; - - use core::ffi::c_void; - - #[repr(C)] - pub enum _Unwind_Reason_Code { - _URC_NO_REASON = 0, - _URC_FOREIGN_EXCEPTION_CAUGHT = 1, - _URC_FATAL_PHASE2_ERROR = 2, - _URC_FATAL_PHASE1_ERROR = 3, - _URC_NORMAL_STOP = 4, - _URC_END_OF_STACK = 5, - _URC_HANDLER_FOUND = 6, - _URC_INSTALL_CONTEXT = 7, - _URC_CONTINUE_UNWIND = 8, - _URC_FAILURE = 9, // used only by ARM EABI - } - - pub enum _Unwind_Context {} - - pub type _Unwind_Trace_Fn = - extern "C" fn(ctx: *mut _Unwind_Context, arg: *mut c_void) -> _Unwind_Reason_Code; - - extern "C" { - // No native _Unwind_Backtrace on iOS - #[cfg(not(all(target_os = "ios", target_arch = "arm")))] - pub fn _Unwind_Backtrace( - trace: _Unwind_Trace_Fn, - trace_argument: *mut c_void, - ) -> _Unwind_Reason_Code; - - // available since GCC 4.2.0, should be fine for our purpose - #[cfg(all( - not(all(target_os = "android", target_arch = "arm")), - not(all(target_os = "freebsd", target_arch = "arm")), - not(all(target_os = "linux", target_arch = "arm")) - ))] - pub fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t; - - #[cfg(all( - not(target_os = "android"), - not(all(target_os = "freebsd", target_arch = "arm")), - not(all(target_os = "linux", target_arch = "arm")) - ))] - pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void; - } - - // On android, the function _Unwind_GetIP is a macro, and this is the - // expansion of the macro. This is all copy/pasted directly from the - // header file with the definition of _Unwind_GetIP. - #[cfg(any( - all(target_os = "android", target_arch = "arm"), - all(target_os = "freebsd", target_arch = "arm"), - all(target_os = "linux", target_arch = "arm") - ))] - pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { - #[repr(C)] - enum _Unwind_VRS_Result { - _UVRSR_OK = 0, - _UVRSR_NOT_IMPLEMENTED = 1, - _UVRSR_FAILED = 2, - } - #[repr(C)] - enum _Unwind_VRS_RegClass { - _UVRSC_CORE = 0, - _UVRSC_VFP = 1, - _UVRSC_FPA = 2, - _UVRSC_WMMXD = 3, - _UVRSC_WMMXC = 4, - } - #[repr(C)] - enum _Unwind_VRS_DataRepresentation { - _UVRSD_UINT32 = 0, - _UVRSD_VFPX = 1, - _UVRSD_FPAX = 2, - _UVRSD_UINT64 = 3, - _UVRSD_FLOAT = 4, - _UVRSD_DOUBLE = 5, - } - - type _Unwind_Word = libc::c_uint; - extern "C" { - fn _Unwind_VRS_Get( - ctx: *mut _Unwind_Context, - klass: _Unwind_VRS_RegClass, - word: _Unwind_Word, - repr: _Unwind_VRS_DataRepresentation, - data: *mut c_void, - ) -> _Unwind_VRS_Result; - } - - let mut val: _Unwind_Word = 0; - let ptr = &mut val as *mut _Unwind_Word; - let _ = _Unwind_VRS_Get( - ctx, - _Unwind_VRS_RegClass::_UVRSC_CORE, - 15, - _Unwind_VRS_DataRepresentation::_UVRSD_UINT32, - ptr as *mut c_void, - ); - (val & !1) as libc::uintptr_t - } - - // This function also doesn't exist on Android or ARM/Linux, so make it - // a no-op - #[cfg(any( - target_os = "android", - all(target_os = "freebsd", target_arch = "arm"), - all(target_os = "linux", target_arch = "arm") - ))] - pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) -> *mut c_void { - pc - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/mod.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/mod.rs deleted file mode 100644 index 204974e..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/mod.rs +++ /dev/null @@ -1,152 +0,0 @@ -use core::ffi::c_void; -use core::fmt; - -/// Inspects the current call-stack, passing all active frames into the closure -/// provided to calculate a stack trace. -/// -/// This function is the workhorse of this library in calculating the stack -/// traces for a program. The given closure `cb` is yielded instances of a -/// `Frame` which represent information about that call frame on the stack. The -/// closure is yielded frames in a top-down fashion (most recently called -/// functions first). -/// -/// The closure's return value is an indication of whether the backtrace should -/// continue. A return value of `false` will terminate the backtrace and return -/// immediately. -/// -/// Once a `Frame` is acquired you will likely want to call `backtrace::resolve` -/// to convert the `ip` (instruction pointer) or symbol address to a `Symbol` -/// through which the name and/or filename/line number can be learned. -/// -/// Note that this is a relatively low-level function and if you'd like to, for -/// example, capture a backtrace to be inspected later, then the `Backtrace` -/// type may be more appropriate. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -/// -/// # Panics -/// -/// This function strives to never panic, but if the `cb` provided panics then -/// some platforms will force a double panic to abort the process. Some -/// platforms use a C library which internally uses callbacks which cannot be -/// unwound through, so panicking from `cb` may trigger a process abort. -/// -/// # Example -/// -/// ``` -/// extern crate backtrace; -/// -/// fn main() { -/// backtrace::trace(|frame| { -/// // ... -/// -/// true // continue the backtrace -/// }); -/// } -/// ``` -#[cfg(feature = "std")] -pub fn trace bool>(cb: F) { - let _guard = crate::lock::lock(); - unsafe { trace_unsynchronized(cb) } -} - -/// Same as `trace`, only unsafe as it's unsynchronized. -/// -/// This function does not have synchronization guarentees but is available -/// when the `std` feature of this crate isn't compiled in. See the `trace` -/// function for more documentation and examples. -/// -/// # Panics -/// -/// See information on `trace` for caveats on `cb` panicking. -pub unsafe fn trace_unsynchronized bool>(mut cb: F) { - trace_imp(&mut cb) -} - -/// A trait representing one frame of a backtrace, yielded to the `trace` -/// function of this crate. -/// -/// The tracing function's closure will be yielded frames, and the frame is -/// virtually dispatched as the underlying implementation is not always known -/// until runtime. -#[derive(Clone)] -pub struct Frame { - pub(crate) inner: FrameImp, -} - -impl Frame { - /// Returns the current instruction pointer of this frame. - /// - /// This is normally the next instruction to execute in the frame, but not - /// all implementations list this with 100% accuracy (but it's generally - /// pretty close). - /// - /// It is recommended to pass this value to `backtrace::resolve` to turn it - /// into a symbol name. - pub fn ip(&self) -> *mut c_void { - self.inner.ip() - } - - /// Returns the starting symbol address of the frame of this function. - /// - /// This will attempt to rewind the instruction pointer returned by `ip` to - /// the start of the function, returning that value. In some cases, however, - /// backends will just return `ip` from this function. - /// - /// The returned value can sometimes be used if `backtrace::resolve` failed - /// on the `ip` given above. - pub fn symbol_address(&self) -> *mut c_void { - self.inner.symbol_address() - } -} - -impl fmt::Debug for Frame { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Frame") - .field("ip", &self.ip()) - .field("symbol_address", &self.symbol_address()) - .finish() - } -} - -cfg_if::cfg_if! { - if #[cfg( - any( - all( - unix, - not(target_os = "emscripten"), - not(all(target_os = "ios", target_arch = "arm")), - feature = "libunwind", - ), - all( - target_env = "sgx", - target_vendor = "fortanix", - ), - ) - )] { - mod libunwind; - use self::libunwind::trace as trace_imp; - pub(crate) use self::libunwind::Frame as FrameImp; - } else if #[cfg( - all( - unix, - not(target_os = "emscripten"), - feature = "unix-backtrace", - ) - )] { - mod unix_backtrace; - use self::unix_backtrace::trace as trace_imp; - pub(crate) use self::unix_backtrace::Frame as FrameImp; - } else if #[cfg(all(windows, feature = "dbghelp", not(target_vendor = "uwp")))] { - mod dbghelp; - use self::dbghelp::trace as trace_imp; - pub(crate) use self::dbghelp::Frame as FrameImp; - } else { - mod noop; - use self::noop::trace as trace_imp; - pub(crate) use self::noop::Frame as FrameImp; - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/noop.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/noop.rs deleted file mode 100644 index bc2eb0d..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/noop.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! Empty implementation of unwinding used when no other implementation is -//! appropriate. - -use core::ffi::c_void; - -#[inline(always)] -pub fn trace(_cb: &mut FnMut(&super::Frame) -> bool) {} - -#[derive(Clone)] -pub struct Frame; - -impl Frame { - pub fn ip(&self) -> *mut c_void { - 0 as *mut _ - } - - pub fn symbol_address(&self) -> *mut c_void { - 0 as *mut _ - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/unix_backtrace.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/unix_backtrace.rs deleted file mode 100644 index 7e3375a..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/backtrace/unix_backtrace.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Unwinding through the `backtrace` function provided in Unix. -//! -//! This is an alternative unwinding strategy for Unix platforms which don't -//! have support for libunwind but do have support for `backtrace`. Currently -//! there's not a whole lot of those though. This module is a relatively -//! straightforward binding of the `backtrace` API to the `Frame` API that we'd -//! like to have. - -use core::ffi::c_void; -use core::mem; -use libc::c_int; - -#[derive(Clone)] -pub struct Frame { - addr: usize, -} - -impl Frame { - pub fn ip(&self) -> *mut c_void { - self.addr as *mut c_void - } - pub fn symbol_address(&self) -> *mut c_void { - self.ip() - } -} - -extern "C" { - fn backtrace(buf: *mut *mut c_void, sz: c_int) -> c_int; -} - -#[inline(always)] -pub unsafe fn trace(cb: &mut FnMut(&super::Frame) -> bool) { - const SIZE: usize = 100; - - let mut buf: [*mut c_void; SIZE]; - let cnt; - - buf = mem::zeroed(); - cnt = backtrace(buf.as_mut_ptr(), SIZE as c_int); - - for addr in buf[..cnt as usize].iter() { - let cx = super::Frame { - inner: Frame { - addr: *addr as usize, - }, - }; - if !cb(&cx) { - return; - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/capture.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/capture.rs deleted file mode 100644 index 7b37bd1..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/capture.rs +++ /dev/null @@ -1,479 +0,0 @@ -use crate::PrintFmt; -use crate::{resolve, resolve_frame, trace, BacktraceFmt, Symbol, SymbolName}; -use std::ffi::c_void; -use std::fmt; -use std::path::{Path, PathBuf}; -use std::prelude::v1::*; - -#[cfg(feature = "serde")] -use serde::{Deserialize, Serialize}; - -/// Representation of an owned and self-contained backtrace. -/// -/// This structure can be used to capture a backtrace at various points in a -/// program and later used to inspect what the backtrace was at that time. -/// -/// `Backtrace` supports pretty-printing of backtraces through its `Debug` -/// implementation. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -#[derive(Clone)] -#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] -#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] -pub struct Backtrace { - // Frames here are listed from top-to-bottom of the stack - frames: Vec, - // The index we believe is the actual start of the backtrace, omitting - // frames like `Backtrace::new` and `backtrace::trace`. - actual_start_index: usize, -} - -fn _assert_send_sync() { - fn _assert() {} - _assert::(); -} - -/// Captured version of a frame in a backtrace. -/// -/// This type is returned as a list from `Backtrace::frames` and represents one -/// stack frame in a captured backtrace. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -#[derive(Clone)] -pub struct BacktraceFrame { - frame: Frame, - symbols: Option>, -} - -#[derive(Clone)] -enum Frame { - Raw(crate::Frame), - #[allow(dead_code)] - Deserialized { - ip: usize, - symbol_address: usize, - }, -} - -impl Frame { - fn ip(&self) -> *mut c_void { - match *self { - Frame::Raw(ref f) => f.ip(), - Frame::Deserialized { ip, .. } => ip as *mut c_void, - } - } - - fn symbol_address(&self) -> *mut c_void { - match *self { - Frame::Raw(ref f) => f.symbol_address(), - Frame::Deserialized { symbol_address, .. } => symbol_address as *mut c_void, - } - } -} - -/// Captured version of a symbol in a backtrace. -/// -/// This type is returned as a list from `BacktraceFrame::symbols` and -/// represents the metadata for a symbol in a backtrace. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -#[derive(Clone)] -#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] -#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))] -pub struct BacktraceSymbol { - name: Option>, - addr: Option, - filename: Option, - lineno: Option, -} - -impl Backtrace { - /// Captures a backtrace at the callsite of this function, returning an - /// owned representation. - /// - /// This function is useful for representing a backtrace as an object in - /// Rust. This returned value can be sent across threads and printed - /// elsewhere, and the purpose of this value is to be entirely self - /// contained. - /// - /// Note that on some platforms acquiring a full backtrace and resolving it - /// can be extremely expensive. If the cost is too much for your application - /// it's recommended to instead use `Backtrace::new_unresolved()` which - /// avoids the symbol resolution step (which typically takes the longest) - /// and allows deferring that to a later date. - /// - /// # Examples - /// - /// ``` - /// use backtrace::Backtrace; - /// - /// let current_backtrace = Backtrace::new(); - /// ``` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - #[inline(never)] // want to make sure there's a frame here to remove - pub fn new() -> Backtrace { - let mut bt = Self::create(Self::new as usize); - bt.resolve(); - bt - } - - /// Similar to `new` except that this does not resolve any symbols, this - /// simply captures the backtrace as a list of addresses. - /// - /// At a later time the `resolve` function can be called to resolve this - /// backtrace's symbols into readable names. This function exists because - /// the resolution process can sometimes take a significant amount of time - /// whereas any one backtrace may only be rarely printed. - /// - /// # Examples - /// - /// ``` - /// use backtrace::Backtrace; - /// - /// let mut current_backtrace = Backtrace::new_unresolved(); - /// println!("{:?}", current_backtrace); // no symbol names - /// current_backtrace.resolve(); - /// println!("{:?}", current_backtrace); // symbol names now present - /// ``` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - #[inline(never)] // want to make sure there's a frame here to remove - pub fn new_unresolved() -> Backtrace { - Self::create(Self::new_unresolved as usize) - } - - fn create(ip: usize) -> Backtrace { - let mut frames = Vec::new(); - let mut actual_start_index = None; - trace(|frame| { - frames.push(BacktraceFrame { - frame: Frame::Raw(frame.clone()), - symbols: None, - }); - - if frame.symbol_address() as usize == ip && actual_start_index.is_none() { - actual_start_index = Some(frames.len()); - } - true - }); - - Backtrace { - frames, - actual_start_index: actual_start_index.unwrap_or(0), - } - } - - /// Returns the frames from when this backtrace was captured. - /// - /// The first entry of this slice is likely the function `Backtrace::new`, - /// and the last frame is likely something about how this thread or the main - /// function started. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn frames(&self) -> &[BacktraceFrame] { - &self.frames[self.actual_start_index..] - } - - /// If this backtrace was created from `new_unresolved` then this function - /// will resolve all addresses in the backtrace to their symbolic names. - /// - /// If this backtrace has been previously resolved or was created through - /// `new`, this function does nothing. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn resolve(&mut self) { - for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) { - let mut symbols = Vec::new(); - { - let sym = |symbol: &Symbol| { - symbols.push(BacktraceSymbol { - name: symbol.name().map(|m| m.as_bytes().to_vec()), - addr: symbol.addr().map(|a| a as usize), - filename: symbol.filename().map(|m| m.to_owned()), - lineno: symbol.lineno(), - }); - }; - match frame.frame { - Frame::Raw(ref f) => resolve_frame(f, sym), - Frame::Deserialized { ip, .. } => { - resolve(ip as *mut c_void, sym); - } - } - } - frame.symbols = Some(symbols); - } - } -} - -impl From> for Backtrace { - fn from(frames: Vec) -> Self { - Backtrace { - frames, - actual_start_index: 0, - } - } -} - -impl Into> for Backtrace { - fn into(self) -> Vec { - self.frames - } -} - -impl BacktraceFrame { - /// Same as `Frame::ip` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn ip(&self) -> *mut c_void { - self.frame.ip() as *mut c_void - } - - /// Same as `Frame::symbol_address` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn symbol_address(&self) -> *mut c_void { - self.frame.symbol_address() as *mut c_void - } - - /// Returns the list of symbols that this frame corresponds to. - /// - /// Normally there is only one symbol per frame, but sometimes if a number - /// of functions are inlined into one frame then multiple symbols will be - /// returned. The first symbol listed is the "innermost function", whereas - /// the last symbol is the outermost (last caller). - /// - /// Note that if this frame came from an unresolved backtrace then this will - /// return an empty list. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn symbols(&self) -> &[BacktraceSymbol] { - self.symbols.as_ref().map(|s| &s[..]).unwrap_or(&[]) - } -} - -impl BacktraceSymbol { - /// Same as `Symbol::name` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn name(&self) -> Option { - self.name.as_ref().map(|s| SymbolName::new(s)) - } - - /// Same as `Symbol::addr` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn addr(&self) -> Option<*mut c_void> { - self.addr.map(|s| s as *mut c_void) - } - - /// Same as `Symbol::filename` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn filename(&self) -> Option<&Path> { - self.filename.as_ref().map(|p| &**p) - } - - /// Same as `Symbol::lineno` - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn lineno(&self) -> Option { - self.lineno - } -} - -impl fmt::Debug for Backtrace { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let full = fmt.alternate(); - let (frames, style) = if full { - (&self.frames[..], PrintFmt::Full) - } else { - (&self.frames[self.actual_start_index..], PrintFmt::Short) - }; - - // When printing paths we try to strip the cwd if it exists, otherwise - // we just print the path as-is. Note that we also only do this for the - // short format, because if it's full we presumably want to print - // everything. - let cwd = std::env::current_dir(); - let mut print_path = move |fmt: &mut fmt::Formatter, path: crate::BytesOrWideString| { - let path = path.into_path_buf(); - if !full { - if let Ok(cwd) = &cwd { - if let Ok(suffix) = path.strip_prefix(cwd) { - return fmt::Display::fmt(&suffix.display(), fmt); - } - } - } - fmt::Display::fmt(&path.display(), fmt) - }; - - let mut f = BacktraceFmt::new(fmt, style, &mut print_path); - f.add_context()?; - for frame in frames { - f.frame().backtrace_frame(frame)?; - } - f.finish()?; - Ok(()) - } -} - -impl Default for Backtrace { - fn default() -> Backtrace { - Backtrace::new() - } -} - -impl fmt::Debug for BacktraceFrame { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("BacktraceFrame") - .field("ip", &self.ip()) - .field("symbol_address", &self.symbol_address()) - .finish() - } -} - -impl fmt::Debug for BacktraceSymbol { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("BacktraceSymbol") - .field("name", &self.name()) - .field("addr", &self.addr()) - .field("filename", &self.filename()) - .field("lineno", &self.lineno()) - .finish() - } -} - -#[cfg(feature = "serialize-rustc")] -mod rustc_serialize_impls { - use super::*; - use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; - - #[derive(RustcEncodable, RustcDecodable)] - struct SerializedFrame { - ip: usize, - symbol_address: usize, - symbols: Option>, - } - - impl Decodable for BacktraceFrame { - fn decode(d: &mut D) -> Result - where - D: Decoder, - { - let frame: SerializedFrame = SerializedFrame::decode(d)?; - Ok(BacktraceFrame { - frame: Frame::Deserialized { - ip: frame.ip, - symbol_address: frame.symbol_address, - }, - symbols: frame.symbols, - }) - } - } - - impl Encodable for BacktraceFrame { - fn encode(&self, e: &mut E) -> Result<(), E::Error> - where - E: Encoder, - { - let BacktraceFrame { frame, symbols } = self; - SerializedFrame { - ip: frame.ip() as usize, - symbol_address: frame.symbol_address() as usize, - symbols: symbols.clone(), - } - .encode(e) - } - } -} - -#[cfg(feature = "serde")] -mod serde_impls { - extern crate serde; - - use self::serde::de::Deserializer; - use self::serde::ser::Serializer; - use self::serde::{Deserialize, Serialize}; - use super::*; - - #[derive(Serialize, Deserialize)] - struct SerializedFrame { - ip: usize, - symbol_address: usize, - symbols: Option>, - } - - impl Serialize for BacktraceFrame { - fn serialize(&self, s: S) -> Result - where - S: Serializer, - { - let BacktraceFrame { frame, symbols } = self; - SerializedFrame { - ip: frame.ip() as usize, - symbol_address: frame.symbol_address() as usize, - symbols: symbols.clone(), - } - .serialize(s) - } - } - - impl<'a> Deserialize<'a> for BacktraceFrame { - fn deserialize(d: D) -> Result - where - D: Deserializer<'a>, - { - let frame: SerializedFrame = SerializedFrame::deserialize(d)?; - Ok(BacktraceFrame { - frame: Frame::Deserialized { - ip: frame.ip, - symbol_address: frame.symbol_address, - }, - symbols: frame.symbols, - }) - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/dbghelp.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/dbghelp.rs deleted file mode 100644 index 05ffef2..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/dbghelp.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! A module to assist in managing dbghelp bindings on Windows -//! -//! Backtraces on Windows (at least for MSVC) are largely powered through -//! `dbghelp.dll` and the various functions that it contains. These functions -//! are currently loaded *dynamically* rather than linking to `dbghelp.dll` -//! statically. This is currently done by the standard library (and is in theory -//! required there), but is an effort to help reduce the static dll dependencies -//! of a library since backtraces are typically pretty optional. That being -//! said, `dbghelp.dll` almost always successfully loads on Windows. -//! -//! Note though that since we're loading all this support dynamically we can't -//! actually use the raw definitions in `winapi`, but rather we need to define -//! the function pointer types ourselves and use that. We don't really want to -//! be in the business of duplicating winapi, so we have a Cargo feature -//! `verify-winapi` which asserts that all bindings match those in winapi and -//! this feature is enabled on CI. -//! -//! Finally, you'll note here that the dll for `dbghelp.dll` is never unloaded, -//! and that's currently intentional. The thinking is that we can globally cache -//! it and use it between calls to the API, avoiding expensive loads/unloads. If -//! this is a problem for leak detectors or something like that we can cross the -//! bridge when we get there. - -#![allow(non_snake_case)] - -use crate::windows::*; -use core::mem; -use core::ptr; - -// Work around `SymGetOptions` and `SymSetOptions` not being present in winapi -// itself. Otherwise this is only used when we're double-checking types against -// winapi. -#[cfg(feature = "verify-winapi")] -mod dbghelp { - use crate::windows::*; - pub use winapi::um::dbghelp::{ - StackWalk64, SymCleanup, SymFromAddrW, SymFunctionTableAccess64, SymGetLineFromAddrW64, - SymGetModuleBase64, SymInitializeW, - }; - - extern "system" { - // Not defined in winapi yet - pub fn SymGetOptions() -> u32; - pub fn SymSetOptions(_: u32); - - // This is defined in winapi, but it's incorrect (FIXME winapi-rs#768) - pub fn StackWalkEx( - MachineType: DWORD, - hProcess: HANDLE, - hThread: HANDLE, - StackFrame: LPSTACKFRAME_EX, - ContextRecord: PVOID, - ReadMemoryRoutine: PREAD_PROCESS_MEMORY_ROUTINE64, - FunctionTableAccessRoutine: PFUNCTION_TABLE_ACCESS_ROUTINE64, - GetModuleBaseRoutine: PGET_MODULE_BASE_ROUTINE64, - TranslateAddress: PTRANSLATE_ADDRESS_ROUTINE64, - Flags: DWORD, - ) -> BOOL; - - // Not defined in winapi yet - pub fn SymFromInlineContextW( - hProcess: HANDLE, - Address: DWORD64, - InlineContext: ULONG, - Displacement: PDWORD64, - Symbol: PSYMBOL_INFOW, - ) -> BOOL; - pub fn SymGetLineFromInlineContextW( - hProcess: HANDLE, - dwAddr: DWORD64, - InlineContext: ULONG, - qwModuleBaseAddress: DWORD64, - pdwDisplacement: PDWORD, - Line: PIMAGEHLP_LINEW64, - ) -> BOOL; - } - - pub fn assert_equal_types(a: T, _b: T) -> T { - a - } -} - -// This macro is used to define a `Dbghelp` structure which internally contains -// all the function pointers that we might load. -macro_rules! dbghelp { - (extern "system" { - $(fn $name:ident($($arg:ident: $argty:ty),*) -> $ret: ty;)* - }) => ( - pub struct Dbghelp { - /// The loaded DLL for `dbghelp.dll` - dll: HMODULE, - - // Each function pointer for each function we might use - $($name: usize,)* - } - - static mut DBGHELP: Dbghelp = Dbghelp { - // Initially we haven't loaded the DLL - dll: 0 as *mut _, - // Initiall all functions are set to zero to say they need to be - // dynamically loaded. - $($name: 0,)* - }; - - // Convenience typedef for each function type. - $(pub type $name = unsafe extern "system" fn($($argty),*) -> $ret;)* - - impl Dbghelp { - /// Attempts to open `dbghelp.dll`. Returns success if it works or - /// error if `LoadLibraryW` fails. - /// - /// Panics if library is already loaded. - fn ensure_open(&mut self) -> Result<(), ()> { - if !self.dll.is_null() { - return Ok(()) - } - let lib = b"dbghelp.dll\0"; - unsafe { - self.dll = LoadLibraryA(lib.as_ptr() as *const i8); - if self.dll.is_null() { - Err(()) - } else { - Ok(()) - } - } - } - - // Function for each method we'd like to use. When called it will - // either read the cached function pointer or load it and return the - // loaded value. Loads are asserted to succeed. - $(pub fn $name(&mut self) -> Option<$name> { - unsafe { - if self.$name == 0 { - let name = concat!(stringify!($name), "\0"); - self.$name = self.symbol(name.as_bytes())?; - } - let ret = mem::transmute::(self.$name); - #[cfg(feature = "verify-winapi")] - dbghelp::assert_equal_types(ret, dbghelp::$name); - Some(ret) - } - })* - - fn symbol(&self, symbol: &[u8]) -> Option { - unsafe { - match GetProcAddress(self.dll, symbol.as_ptr() as *const _) as usize { - 0 => None, - n => Some(n), - } - } - } - } - - // Convenience proxy to use the cleanup locks to reference dbghelp - // functions. - #[allow(dead_code)] - impl Init { - $(pub fn $name(&self) -> $name { - unsafe { - DBGHELP.$name().unwrap() - } - })* - - pub fn dbghelp(&self) -> *mut Dbghelp { - unsafe { - &mut DBGHELP - } - } - } - ) - -} - -const SYMOPT_DEFERRED_LOADS: DWORD = 0x00000004; - -dbghelp! { - extern "system" { - fn SymGetOptions() -> DWORD; - fn SymSetOptions(options: DWORD) -> (); - fn SymInitializeW( - handle: HANDLE, - path: PCWSTR, - invade: BOOL - ) -> BOOL; - fn SymCleanup(handle: HANDLE) -> BOOL; - fn StackWalk64( - MachineType: DWORD, - hProcess: HANDLE, - hThread: HANDLE, - StackFrame: LPSTACKFRAME64, - ContextRecord: PVOID, - ReadMemoryRoutine: PREAD_PROCESS_MEMORY_ROUTINE64, - FunctionTableAccessRoutine: PFUNCTION_TABLE_ACCESS_ROUTINE64, - GetModuleBaseRoutine: PGET_MODULE_BASE_ROUTINE64, - TranslateAddress: PTRANSLATE_ADDRESS_ROUTINE64 - ) -> BOOL; - fn SymFunctionTableAccess64( - hProcess: HANDLE, - AddrBase: DWORD64 - ) -> PVOID; - fn SymGetModuleBase64( - hProcess: HANDLE, - AddrBase: DWORD64 - ) -> DWORD64; - fn SymFromAddrW( - hProcess: HANDLE, - Address: DWORD64, - Displacement: PDWORD64, - Symbol: PSYMBOL_INFOW - ) -> BOOL; - fn SymGetLineFromAddrW64( - hProcess: HANDLE, - dwAddr: DWORD64, - pdwDisplacement: PDWORD, - Line: PIMAGEHLP_LINEW64 - ) -> BOOL; - fn StackWalkEx( - MachineType: DWORD, - hProcess: HANDLE, - hThread: HANDLE, - StackFrame: LPSTACKFRAME_EX, - ContextRecord: PVOID, - ReadMemoryRoutine: PREAD_PROCESS_MEMORY_ROUTINE64, - FunctionTableAccessRoutine: PFUNCTION_TABLE_ACCESS_ROUTINE64, - GetModuleBaseRoutine: PGET_MODULE_BASE_ROUTINE64, - TranslateAddress: PTRANSLATE_ADDRESS_ROUTINE64, - Flags: DWORD - ) -> BOOL; - fn SymFromInlineContextW( - hProcess: HANDLE, - Address: DWORD64, - InlineContext: ULONG, - Displacement: PDWORD64, - Symbol: PSYMBOL_INFOW - ) -> BOOL; - fn SymGetLineFromInlineContextW( - hProcess: HANDLE, - dwAddr: DWORD64, - InlineContext: ULONG, - qwModuleBaseAddress: DWORD64, - pdwDisplacement: PDWORD, - Line: PIMAGEHLP_LINEW64 - ) -> BOOL; - } -} - -pub struct Init { - lock: HANDLE, -} - -/// Initialize all support necessary to access `dbghelp` API functions from this -/// crate. -/// -/// Note that this function is **safe**, it internally has its own -/// synchronization. Also note that it is safe to call this function multiple -/// times recursively. -#[cfg(all(windows, feature = "dbghelp"))] -pub fn init() -> Result { - use core::sync::atomic::{AtomicUsize, Ordering::SeqCst}; - - unsafe { - // First thing we need to do is to synchronize this function. This can - // be called concurrently from other threads or recursively within one - // thread. Note that it's trickier than that though because what we're - // using here, `dbghelp`, *also* needs to be synchronized with all other - // callers to `dbghelp` in this process. - // - // Typically there aren't really that many calls to `dbghelp` within the - // same process and we can probably safely assume that we're the only - // ones accessing it. There is, however, one primary other user we have - // to worry about which is ironically ourselves, but in the standard - // library. The Rust standard library depends on this crate for - // backtrace support, and this crate also exists on crates.io. This - // means that if the standard library is printing a panic backtrace it - // may race with this crate coming from crates.io, causing segfaults. - // - // To help solve this synchronization problem we employ a - // Windows-specific trick here (it is, after all, a Windows-specific - // restriction about synchronization). We create a *session-local* named - // mutex to protect this call. The intention here is that the standard - // library and this crate don't have to share Rust-level APIs to - // synchronize here but can instead work behind the scenes to make sure - // they're synchronizing with one another. That way when this function - // is called through the standard library or through crates.io we can be - // sure that the same mutex is being acquired. - // - // So all of that is to say that the first thing we do here is we - // atomically create a `HANDLE` which is a named mutex on Windows. We - // synchronize a bit with other threads sharing this function - // specifically and ensure that only one handle is created per instance - // of this function. Note that the handle is never closed once it's - // stored in the global. - // - // After we've actually go the lock we simply acquire it, and our `Init` - // handle we hand out will be responsible for dropping it eventually. - static LOCK: AtomicUsize = AtomicUsize::new(0); - let mut lock = LOCK.load(SeqCst); - if lock == 0 { - lock = CreateMutexA( - ptr::null_mut(), - 0, - "Local\\RustBacktraceMutex\0".as_ptr() as _, - ) as usize; - if lock == 0 { - return Err(()); - } - if let Err(other) = LOCK.compare_exchange(0, lock, SeqCst, SeqCst) { - debug_assert!(other != 0); - CloseHandle(lock as HANDLE); - lock = other; - } - } - debug_assert!(lock != 0); - let lock = lock as HANDLE; - let r = WaitForSingleObjectEx(lock, INFINITE, FALSE); - debug_assert_eq!(r, 0); - let ret = Init { lock }; - - // Ok, phew! Now that we're all safely synchronized, let's actually - // start processing everything. First up we need to ensure that - // `dbghelp.dll` is actually loaded in this process. We do this - // dynamically to avoid a static dependency. This has historically been - // done to work around weird linking issues and is intended at making - // binaries a bit more portable since this is largely just a debugging - // utility. - // - // Once we've opened `dbghelp.dll` we need to call some initialization - // functions in it, and that's detailed more below. We only do this - // once, though, so we've got a global boolean indicating whether we're - // done yet or not. - DBGHELP.ensure_open()?; - - static mut INITIALIZED: bool = false; - if INITIALIZED { - return Ok(ret); - } - - let orig = DBGHELP.SymGetOptions().unwrap()(); - - // Ensure that the `SYMOPT_DEFERRED_LOADS` flag is set, because - // according to MSVC's own docs about this: "This is the fastest, most - // efficient way to use the symbol handler.", so let's do that! - DBGHELP.SymSetOptions().unwrap()(orig | SYMOPT_DEFERRED_LOADS); - - // Actually initialize symbols with MSVC. Note that this can fail, but we - // ignore it. There's not a ton of prior art for this per se, but LLVM - // internally seems to ignore the return value here and one of the - // sanitizer libraries in LLVM prints a scary warning if this fails but - // basically ignores it in the long run. - // - // One case this comes up a lot for Rust is that the standard library and - // this crate on crates.io both want to compete for `SymInitializeW`. The - // standard library historically wanted to initialize then cleanup most of - // the time, but now that it's using this crate it means that someone will - // get to initialization first and the other will pick up that - // initialization. - DBGHELP.SymInitializeW().unwrap()(GetCurrentProcess(), ptr::null_mut(), TRUE); - INITIALIZED = true; - Ok(ret) - } -} - -impl Drop for Init { - fn drop(&mut self) { - unsafe { - let r = ReleaseMutex(self.lock); - debug_assert!(r != 0); - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/lib.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/lib.rs deleted file mode 100644 index 69a283e..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/lib.rs +++ /dev/null @@ -1,159 +0,0 @@ -//! A library for acquiring a backtrace at runtime -//! -//! This library is meant to supplement the `RUST_BACKTRACE=1` support of the -//! standard library by allowing an acquisition of a backtrace at runtime -//! programmatically. The backtraces generated by this library do not need to be -//! parsed, for example, and expose the functionality of multiple backend -//! implementations. -//! -//! # Implementation -//! -//! This library makes use of a number of strategies for actually acquiring a -//! backtrace. For example unix uses libgcc's libunwind bindings by default to -//! acquire a backtrace, but coresymbolication or dladdr is used on OSX to -//! acquire symbol names while linux uses gcc's libbacktrace. -//! -//! When using the default feature set of this library the "most reasonable" set -//! of defaults is chosen for the current platform, but the features activated -//! can also be controlled at a finer granularity. -//! -//! # API Principles -//! -//! This library attempts to be as flexible as possible to accommodate different -//! backend implementations of acquiring a backtrace. Consequently the currently -//! exported functions are closure-based as opposed to the likely expected -//! iterator-based versions. This is done due to limitations of the underlying -//! APIs used from the system. -//! -//! # Usage -//! -//! First, add this to your Cargo.toml -//! -//! ```toml -//! [dependencies] -//! backtrace = "0.3" -//! ``` -//! -//! Next: -//! -//! ``` -//! extern crate backtrace; -//! -//! fn main() { -//! # // Unsafe here so test passes on no_std. -//! # #[cfg(feature = "std")] { -//! backtrace::trace(|frame| { -//! let ip = frame.ip(); -//! let symbol_address = frame.symbol_address(); -//! -//! // Resolve this instruction pointer to a symbol name -//! backtrace::resolve_frame(frame, |symbol| { -//! if let Some(name) = symbol.name() { -//! // ... -//! } -//! if let Some(filename) = symbol.filename() { -//! // ... -//! } -//! }); -//! -//! true // keep going to the next frame -//! }); -//! } -//! # } -//! ``` - -#![doc(html_root_url = "https://docs.rs/backtrace")] -#![deny(missing_docs)] -#![no_std] -#![cfg_attr( - all(feature = "std", target_env = "sgx", target_vendor = "fortanix"), - feature(sgx_platform) -)] -#![allow(bare_trait_objects)] // TODO: remove when updating to 2018 edition -#![allow(rust_2018_idioms)] // TODO: remove when updating to 2018 edition - -#[cfg(feature = "std")] -#[macro_use] -extern crate std; - -pub use crate::backtrace::{trace_unsynchronized, Frame}; -mod backtrace; - -pub use crate::symbolize::resolve_frame_unsynchronized; -pub use crate::symbolize::{resolve_unsynchronized, Symbol, SymbolName}; -mod symbolize; - -pub use crate::types::BytesOrWideString; -mod types; - -#[cfg(feature = "std")] -pub use crate::symbolize::clear_symbol_cache; - -mod print; -pub use print::{BacktraceFmt, BacktraceFrameFmt, PrintFmt}; - -cfg_if::cfg_if! { - if #[cfg(feature = "std")] { - pub use crate::backtrace::trace; - pub use crate::symbolize::{resolve, resolve_frame}; - pub use crate::capture::{Backtrace, BacktraceFrame, BacktraceSymbol}; - mod capture; - } -} - -#[allow(dead_code)] -struct Bomb { - enabled: bool, -} - -#[allow(dead_code)] -impl Drop for Bomb { - fn drop(&mut self) { - if self.enabled { - panic!("cannot panic during the backtrace function"); - } - } -} - -#[allow(dead_code)] -#[cfg(feature = "std")] -mod lock { - use std::boxed::Box; - use std::cell::Cell; - use std::sync::{Mutex, MutexGuard, Once}; - - pub struct LockGuard(Option>); - - static mut LOCK: *mut Mutex<()> = 0 as *mut _; - static INIT: Once = Once::new(); - thread_local!(static LOCK_HELD: Cell = Cell::new(false)); - - impl Drop for LockGuard { - fn drop(&mut self) { - if self.0.is_some() { - LOCK_HELD.with(|slot| { - assert!(slot.get()); - slot.set(false); - }); - } - } - } - - pub fn lock() -> LockGuard { - if LOCK_HELD.with(|l| l.get()) { - return LockGuard(None); - } - LOCK_HELD.with(|s| s.set(true)); - unsafe { - INIT.call_once(|| { - LOCK = Box::into_raw(Box::new(Mutex::new(()))); - }); - LockGuard(Some((*LOCK).lock().unwrap())) - } - } -} - -#[cfg(all(windows, feature = "dbghelp", not(target_vendor = "uwp")))] -mod dbghelp; -#[cfg(windows)] -mod windows; diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/print.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/print.rs deleted file mode 100644 index bee6717..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/print.rs +++ /dev/null @@ -1,267 +0,0 @@ -use crate::BytesOrWideString; -use core::ffi::c_void; -use core::fmt; - -const HEX_WIDTH: usize = 2 + 2 * core::mem::size_of::(); - -#[cfg(target_os = "fuchsia")] -mod fuchsia; - -/// A formatter for backtraces. -/// -/// This type can be used to print a backtrace regardless of where the backtrace -/// itself comes from. If you have a `Backtrace` type then its `Debug` -/// implementation already uses this printing format. -pub struct BacktraceFmt<'a, 'b> { - fmt: &'a mut fmt::Formatter<'b>, - frame_index: usize, - format: PrintFmt, - print_path: &'a mut (FnMut(&mut fmt::Formatter, BytesOrWideString) -> fmt::Result + 'b), -} - -/// The styles of printing that we can print -#[derive(Copy, Clone, Eq, PartialEq)] -pub enum PrintFmt { - /// Prints a terser backtrace which ideally only contains relevant information - Short, - /// Prints a backtrace that contains all possible information - Full, - #[doc(hidden)] - __Nonexhaustive, -} - -impl<'a, 'b> BacktraceFmt<'a, 'b> { - /// Create a new `BacktraceFmt` which will write output to the provided - /// `fmt`. - /// - /// The `format` argument will control the style in which the backtrace is - /// printed, and the `print_path` argument will be used to print the - /// `BytesOrWideString` instances of filenames. This type itself doesn't do - /// any printing of filenames, but this callback is required to do so. - pub fn new( - fmt: &'a mut fmt::Formatter<'b>, - format: PrintFmt, - print_path: &'a mut (FnMut(&mut fmt::Formatter, BytesOrWideString) -> fmt::Result + 'b), - ) -> Self { - BacktraceFmt { - fmt, - frame_index: 0, - format, - print_path, - } - } - - /// Prints a preamble for the backtrace about to be printed. - /// - /// This is required on some platforms for backtraces to be fully - /// sumbolicated later, and otherwise this should just be the first method - /// you call after creating a `BacktraceFmt`. - pub fn add_context(&mut self) -> fmt::Result { - #[cfg(target_os = "fuchsia")] - fuchsia::print_dso_context(self.fmt)?; - Ok(()) - } - - /// Adds a frame to the backtrace output. - /// - /// This commit returns an RAII instance of a `BacktraceFrameFmt` which can be used - /// to actually print a frame, and on destruction it will increment the - /// frame counter. - pub fn frame(&mut self) -> BacktraceFrameFmt<'_, 'a, 'b> { - BacktraceFrameFmt { - fmt: self, - symbol_index: 0, - } - } - - /// Completes the backtrace output. - /// - /// This is currently a no-op but is added for future compatibility with - /// backtrace formats. - pub fn finish(&mut self) -> fmt::Result { - // Currently a no-op-- including this hook to allow for future additions. - Ok(()) - } -} - -/// A formatter for just one frame of a backtrace. -/// -/// This type is created by the `BacktraceFmt::frame` function. -pub struct BacktraceFrameFmt<'fmt, 'a, 'b> { - fmt: &'fmt mut BacktraceFmt<'a, 'b>, - symbol_index: usize, -} - -impl BacktraceFrameFmt<'_, '_, '_> { - /// Prints a `BacktraceFrame` with this frame formatter. - /// - /// This will recusrively print all `BacktraceSymbol` instances within the - /// `BacktraceFrame`. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - #[cfg(feature = "std")] - pub fn backtrace_frame(&mut self, frame: &crate::BacktraceFrame) -> fmt::Result { - let symbols = frame.symbols(); - for symbol in symbols { - self.backtrace_symbol(frame, symbol)?; - } - if symbols.is_empty() { - self.print_raw(frame.ip(), None, None, None)?; - } - Ok(()) - } - - /// Prints a `BacktraceSymbol` within a `BacktraceFrame`. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - #[cfg(feature = "std")] - pub fn backtrace_symbol( - &mut self, - frame: &crate::BacktraceFrame, - symbol: &crate::BacktraceSymbol, - ) -> fmt::Result { - self.print_raw( - frame.ip(), - symbol.name(), - // TODO: this isn't great that we don't end up printing anything - // with non-utf8 filenames. Thankfully almost everything is utf8 so - // this shouldn't be too too bad. - symbol - .filename() - .and_then(|p| Some(BytesOrWideString::Bytes(p.to_str()?.as_bytes()))), - symbol.lineno(), - )?; - Ok(()) - } - - /// Prints a raw traced `Frame` and `Symbol`, typically from within the raw - /// callbacks of this crate. - pub fn symbol(&mut self, frame: &crate::Frame, symbol: &crate::Symbol) -> fmt::Result { - self.print_raw( - frame.ip(), - symbol.name(), - symbol.filename_raw(), - symbol.lineno(), - )?; - Ok(()) - } - - /// Adds a raw frame to the backtrace output. - /// - /// This method, unlike the previous, takes the raw arguments in case - /// they're being source from different locations. Note that this may be - /// called multiple times for one frame. - pub fn print_raw( - &mut self, - frame_ip: *mut c_void, - symbol_name: Option, - filename: Option, - lineno: Option, - ) -> fmt::Result { - // Fuchsia is unable to symbolize within a process so it has a special - // format which can be used to symbolize later. Print that instead of - // printing addresses in our own format here. - if cfg!(target_os = "fuchsia") { - self.print_raw_fuchsia(frame_ip)?; - } else { - self.print_raw_generic(frame_ip, symbol_name, filename, lineno)?; - } - self.symbol_index += 1; - Ok(()) - } - - #[allow(unused_mut)] - fn print_raw_generic( - &mut self, - mut frame_ip: *mut c_void, - symbol_name: Option, - filename: Option, - lineno: Option, - ) -> fmt::Result { - // No need to print "null" frames, it basically just means that the - // system backtrace was a bit eager to trace back super far. - if let PrintFmt::Short = self.fmt.format { - if frame_ip.is_null() { - return Ok(()); - } - } - - // To reduce TCB size in Sgx enclave, we do not want to implement symbol - // resolution functionality. Rather, we can print the offset of the - // address here, which could be later mapped to correct function. - #[cfg(all(feature = "std", target_env = "sgx", target_vendor = "fortanix"))] - { - let image_base = std::os::fortanix_sgx::mem::image_base(); - frame_ip = usize::wrapping_sub(frame_ip as usize, image_base as _) as _; - } - - // Print the index of the frame as well as the optional instruction - // pointer of the frame. If we're beyond the first symbol of this frame - // though we just print appropriate whitespace. - if self.symbol_index == 0 { - write!(self.fmt.fmt, "{:4}: ", self.fmt.frame_index)?; - if let PrintFmt::Full = self.fmt.format { - write!(self.fmt.fmt, "{:1$?} - ", frame_ip, HEX_WIDTH)?; - } - } else { - write!(self.fmt.fmt, " ")?; - if let PrintFmt::Full = self.fmt.format { - write!(self.fmt.fmt, "{:1$}", "", HEX_WIDTH + 3)?; - } - } - - // Next up write out the symbol name, using the alternate formatting for - // more information if we're a full backtrace. Here we also handle - // symbols which don't have a name, - match (symbol_name, &self.fmt.format) { - (Some(name), PrintFmt::Short) => write!(self.fmt.fmt, "{:#}", name)?, - (Some(name), PrintFmt::Full) => write!(self.fmt.fmt, "{}", name)?, - (None, _) | (_, PrintFmt::__Nonexhaustive) => write!(self.fmt.fmt, "")?, - } - self.fmt.fmt.write_str("\n")?; - - // And last up, print out the filename/line number if they're available. - if let (Some(file), Some(line)) = (filename, lineno) { - self.print_fileline(file, line)?; - } - - Ok(()) - } - - fn print_fileline(&mut self, file: BytesOrWideString, line: u32) -> fmt::Result { - // Filename/line are printed on lines under the symbol name, so print - // some appropriate whitespace to sort of right-align ourselves. - if let PrintFmt::Full = self.fmt.format { - write!(self.fmt.fmt, "{:1$}", "", HEX_WIDTH)?; - } - write!(self.fmt.fmt, " at ")?; - - // Delegate to our internal callback to print the filename and then - // print out the line number. - (self.fmt.print_path)(self.fmt.fmt, file)?; - write!(self.fmt.fmt, ":{}\n", line)?; - Ok(()) - } - - fn print_raw_fuchsia(&mut self, frame_ip: *mut c_void) -> fmt::Result { - // We only care about the first symbol of a frame - if self.symbol_index == 0 { - self.fmt.fmt.write_str("{{{bt:")?; - write!(self.fmt.fmt, "{}:{:?}", self.fmt.frame_index, frame_ip)?; - self.fmt.fmt.write_str("}}}\n")?; - } - Ok(()) - } -} - -impl Drop for BacktraceFrameFmt<'_, '_, '_> { - fn drop(&mut self) { - self.fmt.frame_index += 1; - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/print/fuchsia.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/print/fuchsia.rs deleted file mode 100644 index 787954a..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/print/fuchsia.rs +++ /dev/null @@ -1,432 +0,0 @@ -use core::fmt::{self, Write}; -use core::mem::{size_of, transmute}; -use core::slice::from_raw_parts; -use libc::c_char; - -extern "C" { - // dl_iterate_phdr takes a callback that will receive a dl_phdr_info pointer - // for every DSO that has been linked into the process. dl_iterate_phdr also - // ensures that the dynamic linker is locked from start to finish of the - // iteration. If the callback returns a non-zero value the iteration is - // terminated early. 'data' will be passed as the third argument to the - // callback on each call. 'size' gives the size of the dl_phdr_info. - #[allow(improper_ctypes)] - fn dl_iterate_phdr( - f: extern "C" fn(info: &dl_phdr_info, size: usize, data: &mut DsoPrinter) -> i32, - data: &mut DsoPrinter, - ) -> i32; -} - -// We need to parse out the build ID and some basic program header data -// which means that we need a bit of stuff from the ELF spec as well. - -const PT_LOAD: u32 = 1; -const PT_NOTE: u32 = 4; - -// Now we have to replicate, bit for bit, the structure of the dl_phdr_info -// type used by fuchsia's current dynamic linker. Chromium also has this ABI -// boundary as well as crashpad. Eventully we'd like to move these cases to -// use elf-search but we'd need to provide that in the SDK and that has not -// yet been done. Thus we (and they) are stuck having to use this method -// which incurs a tight coupling with the fuchsia libc. - -#[allow(non_camel_case_types)] -#[repr(C)] -struct dl_phdr_info { - addr: *const u8, - name: *const c_char, - phdr: *const Elf_Phdr, - phnum: u16, - adds: u64, - subs: u64, - tls_modid: usize, - tls_data: *const u8, -} - -impl dl_phdr_info { - fn program_headers(&self) -> PhdrIter<'_> { - PhdrIter { - phdrs: self.phdr_slice(), - base: self.addr, - } - } - // We have no way of knowing of checking if e_phoff and e_phnum are valid. - // libc should ensure this for us however so it's safe to form a slice here. - fn phdr_slice(&self) -> &[Elf_Phdr] { - unsafe { from_raw_parts(self.phdr, self.phnum as usize) } - } -} - -struct PhdrIter<'a> { - phdrs: &'a [Elf_Phdr], - base: *const u8, -} - -impl<'a> Iterator for PhdrIter<'a> { - type Item = Phdr<'a>; - fn next(&mut self) -> Option { - self.phdrs.split_first().map(|(phdr, new_phdrs)| { - self.phdrs = new_phdrs; - Phdr { - phdr, - base: self.base, - } - }) - } -} - -// Elf_Phdr represents a 64-bit ELF program header in the endianness of the target -// architecture. -#[allow(non_camel_case_types)] -#[derive(Clone, Debug)] -#[repr(C)] -struct Elf_Phdr { - p_type: u32, - p_flags: u32, - p_offset: u64, - p_vaddr: u64, - p_paddr: u64, - p_filesz: u64, - p_memsz: u64, - p_align: u64, -} - -// Phdr represents a valid ELF program header and its contents. -struct Phdr<'a> { - phdr: &'a Elf_Phdr, - base: *const u8, -} - -impl<'a> Phdr<'a> { - // We have no way of checking if p_addr or p_memsz are valid. Fuchsia's libc - // parses the notes first however so by virtue of being here these headers - // must be valid. NoteIter does not require the underlying data to be valid - // but it does require the bounds to be valid. We trust that libc has ensured - // that this is the case for us here. - fn notes(&self) -> NoteIter<'a> { - unsafe { - NoteIter::new( - self.base.add(self.phdr.p_offset as usize), - self.phdr.p_memsz as usize, - ) - } - } -} - -// The note type for build IDs. -const NT_GNU_BUILD_ID: u32 = 3; - -// Elf_Nhdr represents an ELF note header in the endianness of the target. -#[allow(non_camel_case_types)] -#[repr(C)] -struct Elf_Nhdr { - n_namesz: u32, - n_descsz: u32, - n_type: u32, -} - -// Note represents an ELF note (header + contents). The name is left as a u8 -// slice because it is not always null terminated and rust makes it easy enough -// to check that the bytes match eitherway. -struct Note<'a> { - name: &'a [u8], - desc: &'a [u8], - tipe: u32, -} - -// NoteIter lets you safely iterate over a note segment. It terminates as soon -// as an error occurs or there are no more notes. If you iterate over invalid -// data it will function as though no notes were found. -struct NoteIter<'a> { - base: &'a [u8], - error: bool, -} - -impl<'a> NoteIter<'a> { - // It is an invariant of function that the pointer and size given denote a - // valid range of bytes that can all be read. The contents of these bytes - // can be anything but the range must be valid for this to be safe. - unsafe fn new(base: *const u8, size: usize) -> Self { - NoteIter { - base: from_raw_parts(base, size), - error: false, - } - } -} - -// align_to aligns 'x' to 'to'-byte alignment assuming 'to' is a power of 2. -// This follows a standard pattern in C/C++ ELF parsing code where -// (x + to - 1) & -to is used. Rust does not let you negate usize so I use -// 2's-complement conversion to recreate that. -fn align_to(x: usize, to: usize) -> usize { - (x + to - 1) & (!to + 1) -} - -// take_bytes_align4 consumes num bytes from the slice (if present) and -// additionally ensures that the final slice is properlly aligned. If an -// either the number of bytes requested is too large or the slice can't be -// realigned afterwards due to not enough remaining bytes existing, None is -// returned and the slice is not modified. -fn take_bytes_align4<'a>(num: usize, bytes: &mut &'a [u8]) -> Option<&'a [u8]> { - if bytes.len() < align_to(num, 4) { - return None; - } - let (out, bytes_new) = bytes.split_at(num); - *bytes = &bytes_new[align_to(num, 4) - num..]; - Some(out) -} - -// This function has no real invariants the caller must uphold other than -// perhaps that 'bytes' should be aligned for performance (and on some -// architectures correctness). The values in the Elf_Nhdr fields might -// be nonsense but this function ensures no such thing. -fn take_nhdr<'a>(bytes: &mut &'a [u8]) -> Option<&'a Elf_Nhdr> { - if size_of::() > bytes.len() { - return None; - } - // This is safe as long as there is enough space and we just confirmed that - // in the if statement above so this should not be unsafe. - let out = unsafe { transmute::<*const u8, &'a Elf_Nhdr>(bytes.as_ptr()) }; - // Note that sice_of::() is always 4-byte aligned. - *bytes = &bytes[size_of::()..]; - Some(out) -} - -impl<'a> Iterator for NoteIter<'a> { - type Item = Note<'a>; - fn next(&mut self) -> Option { - // Check if we've reached the end. - if self.base.len() == 0 || self.error { - return None; - } - // We transmute out an nhdr but we carefully consider the resulting - // struct. We don't trust the namesz or descsz and we make no unsafe - // decisions based on the type. So even if we get out complete garbage - // we should still be safe. - let nhdr = take_nhdr(&mut self.base)?; - let name = take_bytes_align4(nhdr.n_namesz as usize, &mut self.base)?; - let desc = take_bytes_align4(nhdr.n_descsz as usize, &mut self.base)?; - Some(Note { - name: name, - desc: desc, - tipe: nhdr.n_type, - }) - } -} - -struct Perm(u32); - -/// Indicates that a segment is executable. -const PERM_X: u32 = 0b00000001; -/// Indicates that a segment is writable. -const PERM_W: u32 = 0b00000010; -/// Indicates that a segment is readable. -const PERM_R: u32 = 0b00000100; - -impl core::fmt::Display for Perm { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let v = self.0; - if v & PERM_R != 0 { - f.write_char('r')? - } - if v & PERM_W != 0 { - f.write_char('w')? - } - if v & PERM_X != 0 { - f.write_char('x')? - } - Ok(()) - } -} - -/// Represents an ELF segment at runtime. -struct Segment { - /// Gives the runtime virtual address of this segment's contents. - addr: usize, - /// Gives the memory size of this segment's contents. - size: usize, - /// Gives the module virtual address of this segment with the ELF file. - mod_rel_addr: usize, - /// Gives the permissions found in the ELF file. These permissions are not - /// necessarily the permissions present at runtime however. - flags: Perm, -} - -/// Lets one iterate over Segments from a DSO. -struct SegmentIter<'a> { - phdrs: &'a [Elf_Phdr], - base: usize, -} - -impl Iterator for SegmentIter<'_> { - type Item = Segment; - - fn next(&mut self) -> Option { - self.phdrs.split_first().and_then(|(phdr, new_phdrs)| { - self.phdrs = new_phdrs; - if phdr.p_type != PT_LOAD { - self.next() - } else { - Some(Segment { - addr: phdr.p_vaddr as usize + self.base, - size: phdr.p_memsz as usize, - mod_rel_addr: phdr.p_vaddr as usize, - flags: Perm(phdr.p_flags), - }) - } - }) - } -} - -/// Represents an ELF DSO (Dynamic Shared Object). This type references -/// the data stored in the actual DSO rather than making its own copy. -struct Dso<'a> { - /// The dynamic linker always gives us a name, even if the name is empty. - /// In the case of the main executable this name will be empty. In the case - /// of a shared object it will be the soname (see DT_SONAME). - name: &'a str, - /// On Fuchsia virtually all binaries have build IDs but this is not a strict - /// requierment. There's no way to match up DSO information with a real ELF - /// file afterwards if there is no build_id so we require that every DSO - /// have one here. DSO's without a build_id are ignored. - build_id: &'a [u8], - - base: usize, - phdrs: &'a [Elf_Phdr], -} - -impl Dso<'_> { - /// Returns an iterator over Segments in this DSO. - fn segments(&self) -> SegmentIter<'_> { - SegmentIter { - phdrs: self.phdrs.as_ref(), - base: self.base, - } - } -} - -struct HexSlice<'a> { - bytes: &'a [u8], -} - -impl fmt::Display for HexSlice<'_> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - for byte in self.bytes { - write!(f, "{:02x}", byte)?; - } - Ok(()) - } -} - -fn get_build_id<'a>(info: &'a dl_phdr_info) -> Option<&'a [u8]> { - for phdr in info.program_headers() { - if phdr.phdr.p_type == PT_NOTE { - for note in phdr.notes() { - if note.tipe == NT_GNU_BUILD_ID && (note.name == b"GNU\0" || note.name == b"GNU") { - return Some(note.desc); - } - } - } - } - None -} - -/// These errors encode issues that arise while parsing information about -/// each DSO. -enum Error { - /// NameError means that an error occurred while converting a C style string - /// into a rust string. - NameError(core::str::Utf8Error), - /// BuildIDError means that we didn't find a build ID. This could either be - /// because the DSO had no build ID or because the segment containing the - /// build ID was malformed. - BuildIDError, -} - -/// Calls either 'dso' or 'error' for each DSO linked into the process by the -/// dynamic linker. -/// -/// # Arguments -/// -/// * `visitor` - A DsoPrinter that will have one of eats methods called foreach DSO. -fn for_each_dso(mut visitor: &mut DsoPrinter) { - extern "C" fn callback(info: &dl_phdr_info, _size: usize, visitor: &mut DsoPrinter) -> i32 { - // dl_iterate_phdr ensures that info.name will point to a valid - // location. - let name_len = unsafe { libc::strlen(info.name) }; - let name_slice: &[u8] = - unsafe { core::slice::from_raw_parts(info.name as *const u8, name_len) }; - let name = match core::str::from_utf8(name_slice) { - Ok(name) => name, - Err(err) => { - return visitor.error(Error::NameError(err)) as i32; - } - }; - let build_id = match get_build_id(info) { - Some(build_id) => build_id, - None => { - return visitor.error(Error::BuildIDError) as i32; - } - }; - visitor.dso(Dso { - name: name, - build_id: build_id, - phdrs: info.phdr_slice(), - base: info.addr as usize, - }) as i32 - } - unsafe { dl_iterate_phdr(callback, &mut visitor) }; -} - -struct DsoPrinter<'a, 'b> { - writer: &'a mut core::fmt::Formatter<'b>, - module_count: usize, - error: core::fmt::Result, -} - -impl DsoPrinter<'_, '_> { - fn dso(&mut self, dso: Dso<'_>) -> bool { - let mut write = || { - write!( - self.writer, - "{{{{{{module:{:#x}:{}:elf:{}}}}}}}\n", - self.module_count, - dso.name, - HexSlice { - bytes: dso.build_id.as_ref() - } - )?; - for seg in dso.segments() { - write!( - self.writer, - "{{{{{{mmap:{:#x}:{:#x}:load:{:#x}:{}:{:#x}}}}}}}\n", - seg.addr, seg.size, self.module_count, seg.flags, seg.mod_rel_addr - )?; - } - self.module_count += 1; - Ok(()) - }; - match write() { - Ok(()) => false, - Err(err) => { - self.error = Err(err); - true - } - } - } - fn error(&mut self, _error: Error) -> bool { - false - } -} - -/// This function prints the Fuchsia symbolizer markup for all information contained in a DSO. -pub fn print_dso_context(out: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - out.write_str("{{{reset}}}\n")?; - let mut visitor = DsoPrinter { - writer: out, - module_count: 0, - error: Ok(()), - }; - for_each_dso(&mut visitor); - visitor.error -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/coresymbolication.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/coresymbolication.rs deleted file mode 100644 index 24dc11a..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/coresymbolication.rs +++ /dev/null @@ -1,277 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Symbolication strategy that's OSX-specific and uses the `CoreSymbolication` -//! framework, if possible. -//! -//! This strategy uses internal private APIs that are somewhat undocumented but -//! seem to be widely used on OSX. This is the default symbolication strategy -//! for OSX, but is turned off in release builds for iOS due to reports of apps -//! being rejected due to using these APIs. -//! -//! This would probably be good to get official one day and not using private -//! APIs, but for now it should largely suffice. -//! -//! Note that this module will dynamically load `CoreSymbolication` and its APIs -//! through dlopen/dlsym, and if the loading fails this falls back to `dladdr` -//! as a symbolication strategy. - -#![allow(bad_style)] - -use crate::symbolize::dladdr; -use crate::symbolize::ResolveWhat; -use crate::types::BytesOrWideString; -use crate::SymbolName; -use core::ffi::c_void; -use core::mem; -use core::ptr; -use core::slice; -use libc::{c_char, c_int}; - -#[repr(C)] -#[derive(Copy, Clone, PartialEq)] -pub struct CSTypeRef { - cpp_data: *const c_void, - cpp_obj: *const c_void, -} - -const CS_NOW: u64 = 0x80000000; -const CSREF_NULL: CSTypeRef = CSTypeRef { - cpp_data: 0 as *const c_void, - cpp_obj: 0 as *const c_void, -}; - -pub enum Symbol<'a> { - Core { - path: *const c_char, - lineno: u32, - name: *const c_char, - addr: *mut c_void, - }, - Dladdr(dladdr::Symbol<'a>), -} - -impl Symbol<'_> { - pub fn name(&self) -> Option { - let name = match *self { - Symbol::Core { name, .. } => name, - Symbol::Dladdr(ref info) => return info.name(), - }; - if name.is_null() { - None - } else { - Some(SymbolName::new(unsafe { - let len = libc::strlen(name); - slice::from_raw_parts(name as *const u8, len) - })) - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - match *self { - Symbol::Core { addr, .. } => Some(addr), - Symbol::Dladdr(ref info) => info.addr(), - } - } - - fn filename_bytes(&self) -> Option<&[u8]> { - match *self { - Symbol::Core { path, .. } => { - if path.is_null() { - None - } else { - Some(unsafe { - let len = libc::strlen(path); - slice::from_raw_parts(path as *const u8, len) - }) - } - } - Symbol::Dladdr(_) => None, - } - } - - pub fn filename_raw(&self) -> Option { - self.filename_bytes().map(BytesOrWideString::Bytes) - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - use std::ffi::OsStr; - use std::os::unix::prelude::*; - use std::path::Path; - - self.filename_bytes().map(OsStr::from_bytes).map(Path::new) - } - - pub fn lineno(&self) -> Option { - match *self { - Symbol::Core { lineno: 0, .. } => None, - Symbol::Core { lineno, .. } => Some(lineno), - Symbol::Dladdr(_) => None, - } - } -} - -macro_rules! coresymbolication { - (#[load_path = $path:tt] extern "C" { - $(fn $name:ident($($arg:ident: $argty:ty),*) -> $ret: ty;)* - }) => ( - pub struct CoreSymbolication { - // The loaded dynamic library - dll: *mut c_void, - - // Each function pointer for each function we might use - $($name: usize,)* - } - - static mut CORESYMBOLICATION: CoreSymbolication = CoreSymbolication { - // Initially we haven't loaded the dynamic library - dll: 0 as *mut _, - // Initiall all functions are set to zero to say they need to be - // dynamically loaded. - $($name: 0,)* - }; - - // Convenience typedef for each function type. - $(pub type $name = unsafe extern "C" fn($($argty),*) -> $ret;)* - - impl CoreSymbolication { - /// Attempts to open `dbghelp.dll`. Returns `true` if it works or - /// `false` if `dlopen` fails. - fn open(&mut self) -> bool { - if !self.dll.is_null() { - return true; - } - let lib = concat!($path, "\0").as_bytes(); - unsafe { - self.dll = libc::dlopen(lib.as_ptr() as *const _, libc::RTLD_LAZY); - !self.dll.is_null() - } - } - - // Function for each method we'd like to use. When called it will - // either read the cached function pointer or load it and return the - // loaded value. Loads are asserted to succeed. - $(pub fn $name(&mut self) -> $name { - unsafe { - if self.$name == 0 { - let name = concat!(stringify!($name), "\0"); - self.$name = self.symbol(name.as_bytes()) - .expect(concat!("symbol ", stringify!($name), " is missing")); - } - mem::transmute::(self.$name) - } - })* - - fn symbol(&self, symbol: &[u8]) -> Option { - unsafe { - match libc::dlsym(self.dll, symbol.as_ptr() as *const _) as usize { - 0 => None, - n => Some(n), - } - } - } - } - ) -} - -coresymbolication! { - #[load_path = "/System/Library/PrivateFrameworks/CoreSymbolication.framework\ - /Versions/A/CoreSymbolication"] - extern "C" { - fn CSSymbolicatorCreateWithPid(pid: c_int) -> CSTypeRef; - fn CSRelease(rf: CSTypeRef) -> (); - fn CSSymbolicatorGetSymbolWithAddressAtTime( - cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; - fn CSSymbolicatorGetSourceInfoWithAddressAtTime( - cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; - fn CSSourceInfoGetLineNumber(info: CSTypeRef) -> c_int; - fn CSSourceInfoGetPath(info: CSTypeRef) -> *const c_char; - fn CSSourceInfoGetSymbol(info: CSTypeRef) -> CSTypeRef; - fn CSSymbolGetMangledName(sym: CSTypeRef) -> *const c_char; - fn CSSymbolGetSymbolOwner(sym: CSTypeRef) -> CSTypeRef; - fn CSSymbolOwnerGetBaseAddress(symowner: CSTypeRef) -> *mut c_void; - } -} - -unsafe fn try_resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) -> bool { - // Note that this is externally synchronized so there's no need for - // synchronization here, making this `static mut` safer. - let lib = &mut CORESYMBOLICATION; - if !lib.open() { - return false; - } - - let cs = lib.CSSymbolicatorCreateWithPid()(libc::getpid()); - if cs == CSREF_NULL { - return false; - } - let _dtor = OwnedCSTypeRef { - ptr: cs, - CSRelease: lib.CSRelease(), - }; - - let info = lib.CSSymbolicatorGetSourceInfoWithAddressAtTime()(cs, addr, CS_NOW); - let sym = if info == CSREF_NULL { - lib.CSSymbolicatorGetSymbolWithAddressAtTime()(cs, addr, CS_NOW) - } else { - lib.CSSourceInfoGetSymbol()(info) - }; - if sym == CSREF_NULL { - return false; - } - let owner = lib.CSSymbolGetSymbolOwner()(sym); - if owner == CSREF_NULL { - return false; - } - - cb(&super::Symbol { - inner: Symbol::Core { - path: if info != CSREF_NULL { - lib.CSSourceInfoGetPath()(info) - } else { - ptr::null() - }, - lineno: if info != CSREF_NULL { - lib.CSSourceInfoGetLineNumber()(info) as u32 - } else { - 0 - }, - name: lib.CSSymbolGetMangledName()(sym), - addr: lib.CSSymbolOwnerGetBaseAddress()(owner), - }, - }); - true -} - -struct OwnedCSTypeRef { - ptr: CSTypeRef, - CSRelease: unsafe extern "C" fn(CSTypeRef), -} - -impl Drop for OwnedCSTypeRef { - fn drop(&mut self) { - unsafe { - (self.CSRelease)(self.ptr); - } - } -} - -pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { - let addr = what.address_or_ip(); - if try_resolve(addr, cb) { - return; - } - dladdr::resolve(addr, &mut |sym| { - cb(&super::Symbol { - inner: Symbol::Dladdr(sym), - }) - }) -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dbghelp.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dbghelp.rs deleted file mode 100644 index 7afcee7..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dbghelp.rs +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Symbolication strategy using `dbghelp.dll` on Windows, only used for MSVC -//! -//! This symbolication strategy, like with backtraces, uses dynamically loaded -//! information from `dbghelp.dll`. (see `src/dbghelp.rs` for info about why -//! it's dynamically loaded). -//! -//! This API selects its resolution strategy based on the frame provided or the -//! information we have at hand. If a frame from `StackWalkEx` is given to us -//! then we use similar APIs to generate correct information about inlined -//! functions. Otherwise if all we have is an address or an older stack frame -//! from `StackWalk64` we use the older APIs for symbolication. -//! -//! There's a good deal of support in this module, but a good chunk of it is -//! converting back and forth between Windows types and Rust types. For example -//! symbols come to us as wide strings which we then convert to utf-8 strings if -//! we can. - -#![allow(bad_style)] - -use crate::backtrace::FrameImp as Frame; -use crate::dbghelp; -use crate::symbolize::ResolveWhat; -use crate::types::BytesOrWideString; -use crate::windows::*; -use crate::SymbolName; -use core::char; -use core::ffi::c_void; -use core::marker; -use core::mem; -use core::slice; - -// Store an OsString on std so we can provide the symbol name and filename. -pub struct Symbol<'a> { - name: *const [u8], - addr: *mut c_void, - line: Option, - filename: Option<*const [u16]>, - #[cfg(feature = "std")] - _filename_cache: Option<::std::ffi::OsString>, - #[cfg(not(feature = "std"))] - _filename_cache: (), - _marker: marker::PhantomData<&'a i32>, -} - -impl Symbol<'_> { - pub fn name(&self) -> Option { - Some(SymbolName::new(unsafe { &*self.name })) - } - - pub fn addr(&self) -> Option<*mut c_void> { - Some(self.addr as *mut _) - } - - pub fn filename_raw(&self) -> Option { - self.filename - .map(|slice| unsafe { BytesOrWideString::Wide(&*slice) }) - } - - pub fn lineno(&self) -> Option { - self.line - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - use std::path::Path; - - self._filename_cache.as_ref().map(Path::new) - } -} - -#[repr(C, align(8))] -struct Aligned8(T); - -pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { - // Ensure this process's symbols are initialized - let dbghelp = match dbghelp::init() { - Ok(dbghelp) => dbghelp, - Err(()) => return, // oh well... - }; - - match what { - ResolveWhat::Address(_) => resolve_without_inline(&dbghelp, what.address_or_ip(), cb), - ResolveWhat::Frame(frame) => match &frame.inner { - Frame::New(frame) => resolve_with_inline(&dbghelp, frame, cb), - Frame::Old(_) => resolve_without_inline(&dbghelp, frame.ip(), cb), - }, - } -} - -unsafe fn resolve_with_inline( - dbghelp: &dbghelp::Init, - frame: &STACKFRAME_EX, - cb: &mut FnMut(&super::Symbol), -) { - do_resolve( - |info| { - dbghelp.SymFromInlineContextW()( - GetCurrentProcess(), - super::adjust_ip(frame.AddrPC.Offset as *mut _) as u64, - frame.InlineFrameContext, - &mut 0, - info, - ) - }, - |line| { - dbghelp.SymGetLineFromInlineContextW()( - GetCurrentProcess(), - super::adjust_ip(frame.AddrPC.Offset as *mut _) as u64, - frame.InlineFrameContext, - 0, - &mut 0, - line, - ) - }, - cb, - ) -} - -unsafe fn resolve_without_inline( - dbghelp: &dbghelp::Init, - addr: *mut c_void, - cb: &mut FnMut(&super::Symbol), -) { - do_resolve( - |info| dbghelp.SymFromAddrW()(GetCurrentProcess(), addr as DWORD64, &mut 0, info), - |line| dbghelp.SymGetLineFromAddrW64()(GetCurrentProcess(), addr as DWORD64, &mut 0, line), - cb, - ) -} - -unsafe fn do_resolve( - sym_from_addr: impl FnOnce(*mut SYMBOL_INFOW) -> BOOL, - get_line_from_addr: impl FnOnce(&mut IMAGEHLP_LINEW64) -> BOOL, - cb: &mut FnMut(&super::Symbol), -) { - const SIZE: usize = 2 * MAX_SYM_NAME + mem::size_of::(); - let mut data = Aligned8([0u8; SIZE]); - let data = &mut data.0; - let info = &mut *(data.as_mut_ptr() as *mut SYMBOL_INFOW); - info.MaxNameLen = MAX_SYM_NAME as ULONG; - // the struct size in C. the value is different to - // `size_of::() - MAX_SYM_NAME + 1` (== 81) - // due to struct alignment. - info.SizeOfStruct = 88; - - if sym_from_addr(info) != TRUE { - return; - } - - // If the symbol name is greater than MaxNameLen, SymFromAddrW will - // give a buffer of (MaxNameLen - 1) characters and set NameLen to - // the real value. - let name_len = ::core::cmp::min(info.NameLen as usize, info.MaxNameLen as usize - 1); - let name_ptr = info.Name.as_ptr() as *const u16; - let name = slice::from_raw_parts(name_ptr, name_len); - - // Reencode the utf-16 symbol to utf-8 so we can use `SymbolName::new` like - // all other platforms - let mut name_len = 0; - let mut name_buffer = [0; 256]; - { - let mut remaining = &mut name_buffer[..]; - for c in char::decode_utf16(name.iter().cloned()) { - let c = c.unwrap_or(char::REPLACEMENT_CHARACTER); - let len = c.len_utf8(); - if len < remaining.len() { - c.encode_utf8(remaining); - let tmp = remaining; - remaining = &mut tmp[len..]; - name_len += len; - } else { - break; - } - } - } - let name = &name_buffer[..name_len] as *const [u8]; - - let mut line = mem::zeroed::(); - line.SizeOfStruct = mem::size_of::() as DWORD; - - let mut filename = None; - let mut lineno = None; - if get_line_from_addr(&mut line) == TRUE { - lineno = Some(line.LineNumber as u32); - - let base = line.FileName; - let mut len = 0; - while *base.offset(len) != 0 { - len += 1; - } - - let len = len as usize; - - filename = Some(slice::from_raw_parts(base, len) as *const [u16]); - } - - cb(&super::Symbol { - inner: Symbol { - name, - addr: info.Address as *mut _, - line: lineno, - filename, - _filename_cache: cache(filename), - _marker: marker::PhantomData, - }, - }) -} - -#[cfg(feature = "std")] -unsafe fn cache(filename: Option<*const [u16]>) -> Option<::std::ffi::OsString> { - use std::os::windows::ffi::OsStringExt; - filename.map(|f| ::std::ffi::OsString::from_wide(&*f)) -} - -#[cfg(not(feature = "std"))] -unsafe fn cache(_filename: Option<*const [u16]>) {} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr.rs deleted file mode 100644 index 9509e99..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr.rs +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Common support for resolving with `dladdr`, often used as a fallback if -//! other strategies don't work. - -#![allow(dead_code)] - -cfg_if::cfg_if! { - if #[cfg(all(unix, not(target_os = "emscripten"), feature = "dladdr"))] { - use core::ffi::c_void; - use core::marker; - use core::{mem, slice}; - use crate::SymbolName; - use crate::types::BytesOrWideString; - use libc::{self, Dl_info}; - - pub struct Symbol<'a> { - inner: Dl_info, - _marker: marker::PhantomData<&'a i32>, - } - - impl Symbol<'_> { - pub fn name(&self) -> Option { - if self.inner.dli_sname.is_null() { - None - } else { - let ptr = self.inner.dli_sname as *const u8; - unsafe { - let len = libc::strlen(self.inner.dli_sname); - Some(SymbolName::new(slice::from_raw_parts(ptr, len))) - } - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - Some(self.inner.dli_saddr as *mut _) - } - - pub fn filename_raw(&self) -> Option { - None - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - None - } - - pub fn lineno(&self) -> Option { - None - } - } - - pub unsafe fn resolve(addr: *mut c_void, cb: &mut FnMut(Symbol<'static>)) { - let mut info = Symbol { - inner: mem::zeroed(), - _marker: marker::PhantomData, - }; - // Skip null addresses to avoid calling into libc and having it do - // things with the dynamic symbol table for no reason. - if !addr.is_null() && libc::dladdr(addr as *mut _, &mut info.inner) != 0 { - cb(info) - } - } - } else { - use core::ffi::c_void; - use core::marker; - use crate::symbolize::SymbolName; - use crate::types::BytesOrWideString; - - pub struct Symbol<'a> { - a: Void, - _b: marker::PhantomData<&'a i32>, - } - - enum Void {} - - impl Symbol<'_> { - pub fn name(&self) -> Option { - match self.a {} - } - - pub fn addr(&self) -> Option<*mut c_void> { - match self.a {} - } - - pub fn filename_raw(&self) -> Option { - match self.a {} - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - match self.a {} - } - - pub fn lineno(&self) -> Option { - match self.a {} - } - } - - pub unsafe fn resolve(addr: *mut c_void, cb: &mut FnMut(Symbol<'static>)) { - drop((addr, cb)); - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr_resolve.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr_resolve.rs deleted file mode 100644 index 7790703..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/dladdr_resolve.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Symbolication strategy using `dladdr` -//! -//! The `dladdr` API is available on most Unix implementations but it's quite -//! basic, not handling inline frame information at all. Since it's so prevalent -//! though we have an option to use it! - -use crate::symbolize::{dladdr, ResolveWhat, SymbolName}; -use crate::types::BytesOrWideString; -use core::ffi::c_void; - -pub struct Symbol<'a>(dladdr::Symbol<'a>); - -impl Symbol<'_> { - pub fn name(&self) -> Option { - self.0.name() - } - - pub fn addr(&self) -> Option<*mut c_void> { - self.0.addr() - } - - pub fn filename_raw(&self) -> Option { - self.0.filename_raw() - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - self.0.filename() - } - - pub fn lineno(&self) -> Option { - self.0.lineno() - } -} - -pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { - dladdr::resolve(what.address_or_ip(), &mut |sym| { - cb(&super::Symbol { inner: Symbol(sym) }) - }); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/gimli.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/gimli.rs deleted file mode 100644 index 03124a3..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/gimli.rs +++ /dev/null @@ -1,676 +0,0 @@ -//! Support for symbolication using the `gimli` crate on crates.io -//! -//! This implementation is largely a work in progress and is off by default for -//! all platforms, but it's hoped to be developed over time! Long-term this is -//! intended to wholesale replace the `libbacktrace.rs` implementation. - -use self::gimli::read::EndianSlice; -use self::gimli::LittleEndian as Endian; -use crate::symbolize::dladdr; -use crate::symbolize::ResolveWhat; -use crate::types::BytesOrWideString; -use crate::SymbolName; -use addr2line::gimli; -use core::mem; -use core::u32; -use findshlibs::{self, Segment, SharedLibrary}; -use libc::c_void; -use memmap::Mmap; -use std::env; -use std::ffi::OsString; -use std::fs::File; -use std::path::Path; -use std::prelude::v1::*; - -const MAPPINGS_CACHE_SIZE: usize = 4; - -struct Context<'a> { - dwarf: addr2line::Context>, - object: Object<'a>, -} - -struct Mapping { - // 'static lifetime is a lie to hack around lack of support for self-referential structs. - cx: Context<'static>, - _map: Mmap, -} - -fn cx<'data>(object: Object<'data>) -> Option> { - fn load_section<'data, S>(obj: &Object<'data>) -> S - where - S: gimli::Section>, - { - let data = obj.section(S::section_name()).unwrap_or(&[]); - S::from(EndianSlice::new(data, Endian)) - } - - let dwarf = addr2line::Context::from_sections( - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - load_section(&object), - gimli::EndianSlice::new(&[], Endian), - ) - .ok()?; - Some(Context { dwarf, object }) -} - -fn assert_lifetimes<'a>(_: &'a Mmap, _: &Context<'a>) {} - -macro_rules! mk { - (Mapping { $map:expr, $inner:expr }) => {{ - assert_lifetimes(&$map, &$inner); - Mapping { - // Convert to 'static lifetimes since the symbols should - // only borrow `map` and we're preserving `map` below. - cx: unsafe { mem::transmute::, Context<'static>>($inner) }, - _map: $map, - } - }}; -} - -fn mmap(path: &Path) -> Option { - let file = File::open(path).ok()?; - // TODO: not completely safe, see https://github.com/danburkert/memmap-rs/issues/25 - unsafe { Mmap::map(&file).ok() } -} - -cfg_if::cfg_if! { - if #[cfg(windows)] { - use goblin::pe::{self, PE}; - use goblin::strtab::Strtab; - use std::cmp; - use std::convert::TryFrom; - - struct Object<'a> { - pe: PE<'a>, - data: &'a [u8], - symbols: Vec<(usize, pe::symbol::Symbol)>, - strtab: Strtab<'a>, - } - - impl<'a> Object<'a> { - fn parse(data: &'a [u8]) -> Option> { - let pe = PE::parse(data).ok()?; - let syms = pe.header.coff_header.symbols(data).ok()?; - let strtab = pe.header.coff_header.strings(data).ok()?; - - // Collect all the symbols into a local vector which is sorted - // by address and contains enough data to learn about the symbol - // name. Note that we only look at function symbols and also - // note that the sections are 1-indexed because the zero section - // is special (apparently). - let mut symbols = Vec::new(); - for (_, _, sym) in syms.iter() { - if sym.derived_type() != pe::symbol::IMAGE_SYM_DTYPE_FUNCTION - || sym.section_number == 0 - { - continue; - } - let addr = usize::try_from(sym.value).ok()?; - let section = pe.sections.get(usize::try_from(sym.section_number).ok()? - 1)?; - let va = usize::try_from(section.virtual_address).ok()?; - symbols.push((addr + va + pe.image_base, sym)); - } - symbols.sort_unstable_by_key(|x| x.0); - Some(Object { pe, data, symbols, strtab }) - } - - fn section(&self, name: &str) -> Option<&'a [u8]> { - let section = self.pe - .sections - .iter() - .find(|section| section.name().ok() == Some(name)); - section - .and_then(|section| { - let offset = section.pointer_to_raw_data as usize; - let size = cmp::min(section.virtual_size, section.size_of_raw_data) as usize; - self.data.get(offset..).and_then(|data| data.get(..size)) - }) - } - - fn search_symtab<'b>(&'b self, addr: u64) -> Option<&'b [u8]> { - // Note that unlike other formats COFF doesn't embed the size of - // each symbol. As a last ditch effort search for the *closest* - // symbol to a particular address and return that one. This gets - // really wonky once symbols start getting removed because the - // symbols returned here can be totally incorrect, but we have - // no idea of knowing how to detect that. - let addr = usize::try_from(addr).ok()?; - let i = match self.symbols.binary_search_by_key(&addr, |p| p.0) { - Ok(i) => i, - // typically `addr` isn't in the array, but `i` is where - // we'd insert it, so the previous position must be the - // greatest less than `addr` - Err(i) => i.checked_sub(1)?, - }; - Some(self.symbols[i].1.name(&self.strtab).ok()?.as_bytes()) - } - } - } else if #[cfg(target_os = "macos")] { - use goblin::mach::MachO; - - struct Object<'a> { - macho: MachO<'a>, - dwarf: Option, - syms: Vec<(&'a str, u64)>, - } - - impl<'a> Object<'a> { - fn parse(macho: MachO<'a>) -> Option> { - if !macho.little_endian { - return None; - } - let dwarf = macho - .segments - .iter() - .enumerate() - .find(|(_, segment)| segment.name().ok() == Some("__DWARF")) - .map(|p| p.0); - let mut syms = Vec::new(); - if let Some(s) = &macho.symbols { - syms = s.iter() - .filter_map(|e| e.ok()) - .filter(|(name, nlist)| name.len() > 0 && !nlist.is_undefined()) - .map(|(name, nlist)| (name, nlist.n_value)) - .collect(); - } - syms.sort_unstable_by_key(|(_, addr)| *addr); - Some(Object { macho, dwarf, syms }) - } - - fn section(&self, name: &str) -> Option<&'a [u8]> { - let dwarf = self.dwarf?; - let dwarf = &self.macho.segments[dwarf]; - dwarf - .into_iter() - .filter_map(|s| s.ok()) - .find(|(section, _data)| { - let section_name = match section.name() { - Ok(s) => s, - Err(_) => return false, - }; - §ion_name[..] == name || { - section_name.starts_with("__") - && name.starts_with(".") - && §ion_name[2..] == &name[1..] - } - }) - .map(|p| p.1) - } - - fn search_symtab<'b>(&'b self, addr: u64) -> Option<&'b [u8]> { - let i = match self.syms.binary_search_by_key(&addr, |(_, addr)| *addr) { - Ok(i) => i, - Err(i) => i.checked_sub(1)?, - }; - let (sym, _addr) = self.syms.get(i)?; - Some(sym.as_bytes()) - } - } - } else { - use goblin::elf::Elf; - - struct Object<'a> { - elf: Elf<'a>, - data: &'a [u8], - // List of pre-parsed and sorted symbols by base address. The - // boolean indicates whether it comes from the dynamic symbol table - // or the normal symbol table, affecting where it's symbolicated. - syms: Vec<(goblin::elf::Sym, bool)>, - } - - impl<'a> Object<'a> { - fn parse(data: &'a [u8]) -> Option> { - let elf = Elf::parse(data).ok()?; - if !elf.little_endian { - return None; - } - let mut syms = elf - .syms - .iter() - .map(|s| (s, false)) - .chain(elf.dynsyms.iter().map(|s| (s, true))) - // Only look at function/object symbols. This mirrors what - // libbacktrace does and in general we're only symbolicating - // function addresses in theory. Object symbols correspond - // to data, and maybe someone's crazy enough to have a - // function go into static data? - .filter(|(s, _)| { - s.is_function() || s.st_type() == goblin::elf::sym::STT_OBJECT - }) - // skip anything that's in an undefined section header, - // since it means it's an imported function and we're only - // symbolicating with locally defined functions. - .filter(|(s, _)| { - s.st_shndx != goblin::elf::section_header::SHN_UNDEF as usize - }) - .collect::>(); - syms.sort_unstable_by_key(|s| s.0.st_value); - Some(Object { - syms, - elf, - data, - }) - } - - fn section(&self, name: &str) -> Option<&'a [u8]> { - let section = self.elf.section_headers.iter().find(|section| { - match self.elf.shdr_strtab.get(section.sh_name) { - Some(Ok(section_name)) => section_name == name, - _ => false, - } - }); - section - .and_then(|section| { - self.data.get(section.sh_offset as usize..) - .and_then(|data| data.get(..section.sh_size as usize)) - }) - } - - fn search_symtab<'b>(&'b self, addr: u64) -> Option<&'b [u8]> { - // Same sort of binary search as Windows above - let i = match self.syms.binary_search_by_key(&addr, |s| s.0.st_value) { - Ok(i) => i, - Err(i) => i.checked_sub(1)?, - }; - let (sym, dynamic) = self.syms.get(i)?; - if sym.st_value <= addr && addr <= sym.st_value + sym.st_size { - let strtab = if *dynamic { - &self.elf.dynstrtab - } else { - &self.elf.strtab - }; - Some(strtab.get(sym.st_name)?.ok()?.as_bytes()) - } else { - None - } - } - } - } -} - -impl Mapping { - #[cfg(not(target_os = "macos"))] - fn new(path: &Path) -> Option { - let map = mmap(path)?; - let cx = cx(Object::parse(&map)?)?; - Some(mk!(Mapping { map, cx })) - } - - // The loading path for OSX is is so different we just have a completely - // different implementation of the function here. On OSX we need to go - // probing the filesystem for a bunch of files. - #[cfg(target_os = "macos")] - fn new(path: &Path) -> Option { - // First up we need to load the unique UUID which is stored in the macho - // header of the file we're reading, specified at `path`. - let map = mmap(path)?; - let macho = MachO::parse(&map, 0).ok()?; - let uuid = find_uuid(&macho)?; - - // Next we need to look for a `*.dSYM` file. For now we just probe the - // containing directory and look around for something that matches - // `*.dSYM`. Once it's found we root through the dwarf resources that it - // contains and try to find a macho file which has a matching UUID as - // the one of our own file. If we find a match that's the dwarf file we - // want to return. - let parent = path.parent()?; - for entry in parent.read_dir().ok()? { - let entry = entry.ok()?; - let filename = match entry.file_name().into_string() { - Ok(name) => name, - Err(_) => continue, - }; - if !filename.ends_with(".dSYM") { - continue; - } - let candidates = entry.path().join("Contents/Resources/DWARF"); - if let Some(mapping) = load_dsym(&candidates, &uuid) { - return Some(mapping); - } - } - - // Looks like nothing matched our UUID, so let's at least return our own - // file. This should have the symbol table for at least some - // symbolication purposes. - let inner = cx(Object::parse(macho)?)?; - return Some(mk!(Mapping { map, inner })); - - fn load_dsym(dir: &Path, uuid: &[u8; 16]) -> Option { - for entry in dir.read_dir().ok()? { - let entry = entry.ok()?; - let map = mmap(&entry.path())?; - let macho = MachO::parse(&map, 0).ok()?; - let entry_uuid = find_uuid(&macho)?; - if entry_uuid != uuid { - continue; - } - if let Some(cx) = Object::parse(macho).and_then(cx) { - return Some(mk!(Mapping { map, cx })); - } - } - - None - } - - fn find_uuid<'a>(object: &'a MachO) -> Option<&'a [u8; 16]> { - use goblin::mach::load_command::CommandVariant; - - object - .load_commands - .iter() - .filter_map(|cmd| match &cmd.command { - CommandVariant::Uuid(u) => Some(&u.uuid), - _ => None, - }) - .next() - } - } -} - -#[derive(Default)] -struct Cache { - /// All known shared libraries that have been loaded. - libraries: Vec, - - /// Mappings cache where we retain parsed dwarf information. - /// - /// This list has a fixed capacity for its entire liftime which never - /// increases. The `usize` element of each pair is an index into `libraries` - /// above where `usize::max_value()` represents the current executable. The - /// `Mapping` is corresponding parsed dwarf information. - /// - /// Note that this is basically an LRU cache and we'll be shifting things - /// around in here as we symbolize addresses. - mappings: Vec<(usize, Mapping)>, -} - -struct Library { - name: OsString, - segments: Vec, - bias: findshlibs::Bias, -} - -struct LibrarySegment { - len: usize, - stated_virtual_memory_address: findshlibs::Svma, -} - -// unsafe because this is required to be externally synchronized -pub unsafe fn clear_symbol_cache() { - Cache::with_global(|cache| cache.mappings.clear()); -} - -impl Cache { - fn new() -> Cache { - let mut libraries = Vec::new(); - // Iterate over all loaded shared libraries and cache information we - // learn about them. This way we only load information here once instead - // of once per symbol. - findshlibs::TargetSharedLibrary::each(|so| { - use findshlibs::IterationControl::*; - libraries.push(Library { - name: so.name().to_owned(), - segments: so - .segments() - .map(|s| LibrarySegment { - len: s.len(), - stated_virtual_memory_address: s.stated_virtual_memory_address(), - }) - .collect(), - bias: so.virtual_memory_bias(), - }); - Continue - }); - - Cache { - mappings: Vec::with_capacity(MAPPINGS_CACHE_SIZE), - libraries, - } - } - - // unsafe because this is required to be externally synchronized - unsafe fn with_global(f: impl FnOnce(&mut Self)) { - // A very small, very simple LRU cache for debug info mappings. - // - // The hit rate should be very high, since the typical stack doesn't cross - // between many shared libraries. - // - // The `addr2line::Context` structures are pretty expensive to create. Its - // cost is expected to be amortized by subsequent `locate` queries, which - // leverage the structures built when constructing `addr2line::Context`s to - // get nice speedups. If we didn't have this cache, that amortization would - // never happen, and symbolicating backtraces would be ssssllllooooowwww. - static mut MAPPINGS_CACHE: Option = None; - - f(MAPPINGS_CACHE.get_or_insert_with(|| Cache::new())) - } - - fn avma_to_svma(&self, addr: *const u8) -> Option<(usize, findshlibs::Svma)> { - // Note that for now `findshlibs` is unimplemented on Windows, so we - // just unhelpfully assume that the address is an SVMA. Surprisingly it - // seems to at least somewhat work on Wine on Linux though... - // - // This probably means ASLR on Windows is busted. - if cfg!(windows) { - let addr = findshlibs::Svma(addr); - return Some((usize::max_value(), addr)); - } - - self.libraries - .iter() - .enumerate() - .filter_map(|(i, lib)| { - // First up, test if this `lib` has any segment containing the - // `addr` (handling relocation). If this check passes then we - // can continue below and actually translate the address. - // - // Note that this is an inlining of `contains_avma` in the - // `findshlibs` crate here. - if !lib.segments.iter().any(|s| { - let svma = s.stated_virtual_memory_address; - let start = unsafe { svma.0.offset(lib.bias.0) as usize }; - let end = start + s.len; - let address = addr as usize; - start <= address && address < end - }) { - return None; - } - - // Now that we know `lib` contains `addr`, do the equiavlent of - // `avma_to_svma` in the `findshlibs` crate. - let reverse_bias = -lib.bias.0; - let svma = findshlibs::Svma(unsafe { addr.offset(reverse_bias) }); - Some((i, svma)) - }) - .next() - } - - fn mapping_for_lib<'a>(&'a mut self, lib: usize) -> Option<&'a Context<'a>> { - let idx = self.mappings.iter().position(|(idx, _)| *idx == lib); - - // Invariant: after this conditional completes without early returning - // from an error, the cache entry for this path is at index 0. - - if let Some(idx) = idx { - // When the mapping is already in the cache, move it to the front. - if idx != 0 { - let entry = self.mappings.remove(idx); - self.mappings.insert(0, entry); - } - } else { - // When the mapping is not in the cache, create a new mapping, - // insert it into the front of the cache, and evict the oldest cache - // entry if necessary. - let storage; - let path = match self.libraries.get(lib) { - Some(lib) => &lib.name, - None => { - storage = env::current_exe().ok()?.into(); - &storage - } - }; - let mapping = Mapping::new(path.as_ref())?; - - if self.mappings.len() == MAPPINGS_CACHE_SIZE { - self.mappings.pop(); - } - - self.mappings.insert(0, (lib, mapping)); - } - - let cx: &'a Context<'static> = &self.mappings[0].1.cx; - // don't leak the `'static` lifetime, make sure it's scoped to just - // ourselves - Some(unsafe { mem::transmute::<&'a Context<'static>, &'a Context<'a>>(cx) }) - } -} - -pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { - let addr = what.address_or_ip(); - let mut cb = DladdrFallback { - cb, - addr, - called: false, - }; - - Cache::with_global(|cache| { - let (lib, addr) = match cache.avma_to_svma(addr as *const u8) { - Some(pair) => pair, - None => return, - }; - - // Finally, get a cached mapping or create a new mapping for this file, and - // evaluate the DWARF info to find the file/line/name for this address. - let cx = match cache.mapping_for_lib(lib) { - Some(cx) => cx, - None => return, - }; - if let Ok(mut frames) = cx.dwarf.find_frames(addr.0 as u64) { - while let Ok(Some(frame)) = frames.next() { - cb.call(Symbol::Frame { - addr: addr.0 as *mut c_void, - location: frame.location, - name: frame.function.map(|f| f.name.slice()), - }); - } - } - - if !cb.called { - if let Some(name) = cx.object.search_symtab(addr.0 as u64) { - cb.call(Symbol::Symtab { - addr: addr.0 as *mut c_void, - name, - }); - } - } - }); - - drop(cb); -} - -struct DladdrFallback<'a, 'b> { - addr: *mut c_void, - called: bool, - cb: &'a mut (FnMut(&super::Symbol) + 'b), -} - -impl DladdrFallback<'_, '_> { - fn call(&mut self, sym: Symbol) { - self.called = true; - - // Extend the lifetime of `sym` to `'static` since we are unfortunately - // required to here, but it's ony ever going out as a reference so no - // reference to it should be persisted beyond this frame anyway. - let sym = unsafe { mem::transmute::>(sym) }; - (self.cb)(&super::Symbol { inner: sym }); - } -} - -impl Drop for DladdrFallback<'_, '_> { - fn drop(&mut self) { - if self.called { - return; - } - unsafe { - dladdr::resolve(self.addr, &mut |sym| { - (self.cb)(&super::Symbol { - inner: Symbol::Dladdr(sym), - }) - }); - } - } -} - -pub enum Symbol<'a> { - /// We were able to locate frame information for this symbol, and - /// `addr2line`'s frame internally has all the nitty gritty details. - Frame { - addr: *mut c_void, - location: Option>, - name: Option<&'a [u8]>, - }, - /// Couldn't find debug information, but we found it in the symbol table of - /// the elf executable. - Symtab { addr: *mut c_void, name: &'a [u8] }, - /// We weren't able to find anything in the original file, so we had to fall - /// back to using `dladdr` which had a hit. - Dladdr(dladdr::Symbol<'a>), -} - -impl Symbol<'_> { - pub fn name(&self) -> Option { - match self { - Symbol::Dladdr(s) => s.name(), - Symbol::Frame { name, .. } => { - let name = name.as_ref()?; - Some(SymbolName::new(name)) - } - Symbol::Symtab { name, .. } => Some(SymbolName::new(name)), - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - match self { - Symbol::Dladdr(s) => s.addr(), - Symbol::Frame { addr, .. } => Some(*addr), - Symbol::Symtab { .. } => None, - } - } - - pub fn filename_raw(&self) -> Option { - match self { - Symbol::Dladdr(s) => return s.filename_raw(), - Symbol::Frame { location, .. } => { - let file = location.as_ref()?.file?; - Some(BytesOrWideString::Bytes(file.as_bytes())) - } - Symbol::Symtab { .. } => None, - } - } - - pub fn filename(&self) -> Option<&Path> { - match self { - Symbol::Dladdr(s) => return s.filename(), - Symbol::Frame { location, .. } => { - let file = location.as_ref()?.file?; - Some(Path::new(file)) - } - Symbol::Symtab { .. } => None, - } - } - - pub fn lineno(&self) -> Option { - match self { - Symbol::Dladdr(s) => return s.lineno(), - Symbol::Frame { location, .. } => location.as_ref()?.line, - Symbol::Symtab { .. } => None, - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/libbacktrace.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/libbacktrace.rs deleted file mode 100644 index 4318789..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/libbacktrace.rs +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright 2014-2015 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Symbolication strategy using the DWARF-parsing code in libbacktrace. -//! -//! The libbacktrace C library, typically distributed with gcc, supports not -//! only generating a backtrace (which we don't actually use) but also -//! symbolicating the backtrace and handling dwarf debug information about -//! things like inlined frames and whatnot. -//! -//! This is relatively complicated due to lots of various concerns here, but the -//! basic idea is: -//! -//! * First we call `backtrace_syminfo`. This gets symbol information from the -//! dynamic symbol table if we can. -//! * Next we call `backtrace_pcinfo`. This will parse debuginfo tables if -//! they're available and allow us to recover information about inline frames, -//! filenames, line numbers, etc. -//! -//! There's lots of trickery about getting the dwarf tables into libbacktrace, -//! but hopefully it's not the end of the world and is clear enough when reading -//! below. -//! -//! This is the default symbolication strategy for non-MSVC and non-OSX -//! platforms. In libstd though this is the default strategy for OSX. - -#![allow(bad_style)] - -extern crate backtrace_sys as bt; - -use core::{ptr, slice}; -use libc::{self, c_char, c_int, c_void, uintptr_t}; - -use crate::symbolize::dladdr; -use crate::symbolize::{ResolveWhat, SymbolName}; -use crate::types::BytesOrWideString; - -pub enum Symbol<'a> { - Syminfo { - pc: uintptr_t, - symname: *const c_char, - }, - Pcinfo { - pc: uintptr_t, - filename: *const c_char, - lineno: c_int, - function: *const c_char, - symname: *const c_char, - }, - Dladdr(dladdr::Symbol<'a>), -} - -impl Symbol<'_> { - pub fn name(&self) -> Option { - let symbol = |ptr: *const c_char| unsafe { - if ptr.is_null() { - None - } else { - let len = libc::strlen(ptr); - Some(SymbolName::new(slice::from_raw_parts( - ptr as *const u8, - len, - ))) - } - }; - match *self { - Symbol::Syminfo { symname, .. } => symbol(symname), - Symbol::Pcinfo { - function, symname, .. - } => { - // If possible prefer the `function` name which comes from - // debuginfo and can typically be more accurate for inline - // frames for example. If that's not present though fall back to - // the symbol table name specified in `symname`. - // - // Note that sometimes `function` can feel somewhat less - // accurate, for example being listed as `try` - // isntead of `std::panicking::try::do_call`. It's not really - // clear why, but overall the `function` name seems more accurate. - if let Some(sym) = symbol(function) { - return Some(sym); - } - symbol(symname) - } - Symbol::Dladdr(ref s) => s.name(), - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - let pc = match *self { - Symbol::Syminfo { pc, .. } => pc, - Symbol::Pcinfo { pc, .. } => pc, - Symbol::Dladdr(ref s) => return s.addr(), - }; - if pc == 0 { - None - } else { - Some(pc as *mut _) - } - } - - fn filename_bytes(&self) -> Option<&[u8]> { - match *self { - Symbol::Syminfo { .. } => None, - Symbol::Pcinfo { filename, .. } => { - let ptr = filename as *const u8; - unsafe { - let len = libc::strlen(filename); - Some(slice::from_raw_parts(ptr, len)) - } - } - Symbol::Dladdr(_) => None, - } - } - - pub fn filename_raw(&self) -> Option { - self.filename_bytes().map(BytesOrWideString::Bytes) - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - use std::path::Path; - - #[cfg(unix)] - fn bytes2path(bytes: &[u8]) -> Option<&Path> { - use std::ffi::OsStr; - use std::os::unix::prelude::*; - Some(Path::new(OsStr::from_bytes(bytes))) - } - - #[cfg(windows)] - fn bytes2path(bytes: &[u8]) -> Option<&Path> { - use std::str; - str::from_utf8(bytes).ok().map(Path::new) - } - - self.filename_bytes().and_then(bytes2path) - } - - pub fn lineno(&self) -> Option { - match *self { - Symbol::Syminfo { .. } => None, - Symbol::Pcinfo { lineno, .. } => Some(lineno as u32), - Symbol::Dladdr(ref s) => s.lineno(), - } - } -} - -extern "C" fn error_cb(_data: *mut c_void, _msg: *const c_char, _errnum: c_int) { - // do nothing for now -} - -/// Type of the `data` pointer passed into `syminfo_cb` -struct SyminfoState<'a> { - cb: &'a mut (FnMut(&super::Symbol) + 'a), - pc: usize, -} - -extern "C" fn syminfo_cb( - data: *mut c_void, - pc: uintptr_t, - symname: *const c_char, - _symval: uintptr_t, - _symsize: uintptr_t, -) { - let mut bomb = crate::Bomb { enabled: true }; - - // Once this callback is invoked from `backtrace_syminfo` when we start - // resolving we go further to call `backtrace_pcinfo`. The - // `backtrace_pcinfo` function will consult debug information and attemp tto - // do things like recover file/line information as well as inlined frames. - // Note though that `backtrace_pcinfo` can fail or not do much if there's - // not debug info, so if that happens we're sure to call the callback with - // at least one symbol from the `syminfo_cb`. - unsafe { - let syminfo_state = &mut *(data as *mut SyminfoState); - let mut pcinfo_state = PcinfoState { - symname, - called: false, - cb: syminfo_state.cb, - }; - bt::backtrace_pcinfo( - init_state(), - syminfo_state.pc as uintptr_t, - pcinfo_cb, - error_cb, - &mut pcinfo_state as *mut _ as *mut _, - ); - if !pcinfo_state.called { - (pcinfo_state.cb)(&super::Symbol { - inner: Symbol::Syminfo { - pc: pc, - symname: symname, - }, - }); - } - } - - bomb.enabled = false; -} - -/// Type of the `data` pointer passed into `pcinfo_cb` -struct PcinfoState<'a> { - cb: &'a mut (FnMut(&super::Symbol) + 'a), - symname: *const c_char, - called: bool, -} - -extern "C" fn pcinfo_cb( - data: *mut c_void, - pc: uintptr_t, - filename: *const c_char, - lineno: c_int, - function: *const c_char, -) -> c_int { - if filename.is_null() || function.is_null() { - return -1; - } - let mut bomb = crate::Bomb { enabled: true }; - - unsafe { - let state = &mut *(data as *mut PcinfoState); - state.called = true; - (state.cb)(&super::Symbol { - inner: Symbol::Pcinfo { - pc: pc, - filename: filename, - lineno: lineno, - symname: state.symname, - function, - }, - }); - } - - bomb.enabled = false; - return 0; -} - -// The libbacktrace API supports creating a state, but it does not -// support destroying a state. I personally take this to mean that a -// state is meant to be created and then live forever. -// -// I would love to register an at_exit() handler which cleans up this -// state, but libbacktrace provides no way to do so. -// -// With these constraints, this function has a statically cached state -// that is calculated the first time this is requested. Remember that -// backtracing all happens serially (one global lock). -// -// Note the lack of synchronization here is due to the requirement that -// `resolve` is externally synchronized. -unsafe fn init_state() -> *mut bt::backtrace_state { - static mut STATE: *mut bt::backtrace_state = 0 as *mut _; - - if !STATE.is_null() { - return STATE; - } - - STATE = bt::backtrace_create_state( - load_filename(), - // Don't exercise threadsafe capabilities of libbacktrace since - // we're always calling it in a synchronized fashion. - 0, - error_cb, - ptr::null_mut(), // no extra data - ); - - return STATE; - - // Note that for libbacktrace to operate at all it needs to find the DWARF - // debug info for the current executable. It typically does that via a - // number of mechanisms including, but not limited to: - // - // * /proc/self/exe on supported platforms - // * The filename passed in explicitly when creating state - // - // The libbacktrace library is a big wad of C code. This naturally means - // it's got memory safety vulnerabilities, especially when handling - // malformed debuginfo. Libstd has run into plenty of these historically. - // - // If /proc/self/exe is used then we can typically ignore these as we - // assume that libbacktrace is "mostly correct" and otherwise doesn't do - // weird things with "attempted to be correct" dwarf debug info. - // - // If we pass in a filename, however, then it's possible on some platforms - // (like BSDs) where a malicious actor can cause an arbitrary file to be - // placed at that location. This means that if we tell libbacktrace about a - // filename it may be using an arbitrary file, possibly causing segfaults. - // If we don't tell libbacktrace anything though then it won't do anything - // on platforms that don't support paths like /proc/self/exe! - // - // Given all that we try as hard as possible to *not* pass in a filename, - // but we must on platforms that don't support /proc/self/exe at all. - cfg_if::cfg_if! { - if #[cfg(any(target_os = "macos", target_os = "ios"))] { - // Note that ideally we'd use `std::env::current_exe`, but we can't - // require `std` here. - // - // Use `_NSGetExecutablePath` to load the current executable path - // into a static area (which if it's too small just give up). - // - // Note that we're seriously trusting libbacktrace here to not die - // on corrupt executables, but it surely does... - unsafe fn load_filename() -> *const libc::c_char { - const N: usize = 256; - static mut BUF: [u8; N] = [0; N]; - extern { - fn _NSGetExecutablePath( - buf: *mut libc::c_char, - bufsize: *mut u32, - ) -> libc::c_int; - } - let mut sz: u32 = BUF.len() as u32; - let ptr = BUF.as_mut_ptr() as *mut libc::c_char; - if _NSGetExecutablePath(ptr, &mut sz) == 0 { - ptr - } else { - ptr::null() - } - } - } else if #[cfg(windows)] { - use crate::windows::*; - - // Windows has a mode of opening files where after it's opened it - // can't be deleted. That's in general what we want here because we - // want to ensure that our executable isn't changing out from under - // us after we hand it off to libbacktrace, hopefully mitigating the - // ability to pass in arbitrary data into libbacktrace (which may be - // mishandled). - // - // Given that we do a bit of a dance here to attempt to get a sort - // of lock on our own image: - // - // * Get a handle to the current process, load its filename. - // * Open a file to that filename with the right flags. - // * Reload the current process's filename, making sure it's the same - // - // If that all passes we in theory have indeed opened our process's - // file and we're guaranteed it won't change. FWIW a bunch of this - // is copied from libstd historically, so this is my best - // interpretation of what was happening. - unsafe fn load_filename() -> *const libc::c_char { - load_filename_opt().unwrap_or(ptr::null()) - } - - unsafe fn load_filename_opt() -> Result<*const libc::c_char, ()> { - const N: usize = 256; - // This lives in static memory so we can return it.. - static mut BUF: [i8; N] = [0; N]; - // ... and this lives on the stack since it's temporary - let mut stack_buf = [0; N]; - let name1 = query_full_name(&mut BUF)?; - - let handle = CreateFileA( - name1.as_ptr(), - GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, - ptr::null_mut(), - OPEN_EXISTING, - 0, - ptr::null_mut(), - ); - if handle.is_null() { - return Err(()); - } - - let name2 = query_full_name(&mut stack_buf)?; - if name1 != name2 { - CloseHandle(handle); - return Err(()) - } - // intentionally leak `handle` here because having that open - // should preserve our lock on this file name. - Ok(name1.as_ptr()) - } - - unsafe fn query_full_name(buf: &mut [i8]) -> Result<&[i8], ()> { - let dll = GetModuleHandleA(b"kernel32.dll\0".as_ptr() as *const i8); - if dll.is_null() { - return Err(()) - } - let ptrQueryFullProcessImageNameA = - GetProcAddress(dll, b"QueryFullProcessImageNameA\0".as_ptr() as *const _) as usize; - if ptrQueryFullProcessImageNameA == 0 - { - return Err(()); - } - use core::mem; - let p1 = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId()); - let mut len = buf.len() as u32; - let pfnQueryFullProcessImageNameA : extern "system" fn( - hProcess: HANDLE, - dwFlags: DWORD, - lpExeName: LPSTR, - lpdwSize: PDWORD, - ) -> BOOL = mem::transmute(ptrQueryFullProcessImageNameA); - - let rc = pfnQueryFullProcessImageNameA(p1, 0, buf.as_mut_ptr(), &mut len); - CloseHandle(p1); - - // We want to return a slice that is nul-terminated, so if - // everything was filled in and it equals the total length - // then equate that to failure. - // - // Otherwise when returning success make sure the nul byte is - // included in the slice. - if rc == 0 || len == buf.len() as u32 { - Err(()) - } else { - assert_eq!(buf[len as usize], 0); - Ok(&buf[..(len + 1) as usize]) - } - } - } else if #[cfg(target_os = "vxworks")] { - unsafe fn load_filename() -> *const libc::c_char { - use libc; - use core::mem; - - const N: usize = libc::VX_RTP_NAME_LENGTH as usize + 1; - static mut BUF: [libc::c_char; N] = [0; N]; - - let mut rtp_desc : libc::RTP_DESC = mem::zeroed(); - if (libc::rtpInfoGet(0, &mut rtp_desc as *mut libc::RTP_DESC) == 0) { - BUF.copy_from_slice(&rtp_desc.pathName); - BUF.as_ptr() - } else { - ptr::null() - } - } - } else { - unsafe fn load_filename() -> *const libc::c_char { - ptr::null() - } - } - } -} - -pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { - let symaddr = what.address_or_ip() as usize; - - // backtrace errors are currently swept under the rug - let state = init_state(); - if state.is_null() { - return dladdr_fallback(what.address_or_ip(), cb); - } - - // Call the `backtrace_syminfo` API first. This is (from reading the code) - // guaranteed to call `syminfo_cb` exactly once (or fail with an error - // presumably). We then handle more within the `syminfo_cb`. - // - // Note that we do this since `syminfo` will consult the symbol table, - // finding symbol names even if there's no debug information in the binary. - let mut called = false; - { - let mut syminfo_state = SyminfoState { - pc: symaddr, - cb: &mut |sym| { - called = true; - cb(sym); - }, - }; - bt::backtrace_syminfo( - state, - symaddr as uintptr_t, - syminfo_cb, - error_cb, - &mut syminfo_state as *mut _ as *mut _, - ); - } - - if !called { - dladdr_fallback(what.address_or_ip(), cb); - } -} - -unsafe fn dladdr_fallback(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { - dladdr::resolve(addr, &mut |sym| { - cb(&super::Symbol { - inner: Symbol::Dladdr(sym), - }) - }); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/mod.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/mod.rs deleted file mode 100644 index 36d5876..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/mod.rs +++ /dev/null @@ -1,514 +0,0 @@ -use core::{fmt, str}; - -cfg_if::cfg_if! { - if #[cfg(feature = "std")] { - use std::path::Path; - use std::prelude::v1::*; - } -} - -use crate::backtrace::Frame; -use crate::types::BytesOrWideString; -use core::ffi::c_void; -use rustc_demangle::{try_demangle, Demangle}; - -/// Resolve an address to a symbol, passing the symbol to the specified -/// closure. -/// -/// This function will look up the given address in areas such as the local -/// symbol table, dynamic symbol table, or DWARF debug info (depending on the -/// activated implementation) to find symbols to yield. -/// -/// The closure may not be called if resolution could not be performed, and it -/// also may be called more than once in the case of inlined functions. -/// -/// Symbols yielded represent the execution at the specified `addr`, returning -/// file/line pairs for that address (if available). -/// -/// Note that if you have a `Frame` then it's recommended to use the -/// `resolve_frame` function instead of this one. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -/// -/// # Panics -/// -/// This function strives to never panic, but if the `cb` provided panics then -/// some platforms will force a double panic to abort the process. Some -/// platforms use a C library which internally uses callbacks which cannot be -/// unwound through, so panicking from `cb` may trigger a process abort. -/// -/// # Example -/// -/// ``` -/// extern crate backtrace; -/// -/// fn main() { -/// backtrace::trace(|frame| { -/// let ip = frame.ip(); -/// -/// backtrace::resolve(ip, |symbol| { -/// // ... -/// }); -/// -/// false // only look at the top frame -/// }); -/// } -/// ``` -#[cfg(feature = "std")] -pub fn resolve(addr: *mut c_void, cb: F) { - let _guard = crate::lock::lock(); - unsafe { resolve_unsynchronized(addr, cb) } -} - -/// Resolve a previously capture frame to a symbol, passing the symbol to the -/// specified closure. -/// -/// This functin performs the same function as `resolve` except that it takes a -/// `Frame` as an argument instead of an address. This can allow some platform -/// implementations of backtracing to provide more accurate symbol information -/// or information about inline frames for example. It's recommended to use this -/// if you can. -/// -/// # Required features -/// -/// This function requires the `std` feature of the `backtrace` crate to be -/// enabled, and the `std` feature is enabled by default. -/// -/// # Panics -/// -/// This function strives to never panic, but if the `cb` provided panics then -/// some platforms will force a double panic to abort the process. Some -/// platforms use a C library which internally uses callbacks which cannot be -/// unwound through, so panicking from `cb` may trigger a process abort. -/// -/// # Example -/// -/// ``` -/// extern crate backtrace; -/// -/// fn main() { -/// backtrace::trace(|frame| { -/// backtrace::resolve_frame(frame, |symbol| { -/// // ... -/// }); -/// -/// false // only look at the top frame -/// }); -/// } -/// ``` -#[cfg(feature = "std")] -pub fn resolve_frame(frame: &Frame, cb: F) { - let _guard = crate::lock::lock(); - unsafe { resolve_frame_unsynchronized(frame, cb) } -} - -pub enum ResolveWhat<'a> { - Address(*mut c_void), - Frame(&'a Frame), -} - -impl<'a> ResolveWhat<'a> { - #[allow(dead_code)] - fn address_or_ip(&self) -> *mut c_void { - match self { - ResolveWhat::Address(a) => adjust_ip(*a), - ResolveWhat::Frame(f) => adjust_ip(f.ip()), - } - } -} - -// IP values from stack frames are typically (always?) the instruction -// *after* the call that's the actual stack trace. Symbolizing this on -// causes the filename/line number to be one ahead and perhaps into -// the void if it's near the end of the function. -// -// This appears to basically always be the case on all platforms, so we always -// subtract one from a resolved ip to resolve it to the previous call -// instruction instead of the instruction being returned to. -// -// Ideally we would not do this. Ideally we would require callers of the -// `resolve` APIs here to manually do the -1 and account that they want location -// information for the *previous* instruction, not the current. Ideally we'd -// also expose on `Frame` if we are indeed the address of the next instruction -// or the current. -// -// For now though this is a pretty niche concern so we just internally always -// subtract one. Consumers should keep working and getting pretty good results, -// so we should be good enough. -fn adjust_ip(a: *mut c_void) -> *mut c_void { - if a.is_null() { - a - } else { - (a as usize - 1) as *mut c_void - } -} - -/// Same as `resolve`, only unsafe as it's unsynchronized. -/// -/// This function does not have synchronization guarentees but is available when -/// the `std` feature of this crate isn't compiled in. See the `resolve` -/// function for more documentation and examples. -/// -/// # Panics -/// -/// See information on `resolve` for caveats on `cb` panicking. -pub unsafe fn resolve_unsynchronized(addr: *mut c_void, mut cb: F) -where - F: FnMut(&Symbol), -{ - resolve_imp(ResolveWhat::Address(addr), &mut cb) -} - -/// Same as `resolve_frame`, only unsafe as it's unsynchronized. -/// -/// This function does not have synchronization guarentees but is available -/// when the `std` feature of this crate isn't compiled in. See the -/// `resolve_frame` function for more documentation and examples. -/// -/// # Panics -/// -/// See information on `resolve_frame` for caveats on `cb` panicking. -pub unsafe fn resolve_frame_unsynchronized(frame: &Frame, mut cb: F) -where - F: FnMut(&Symbol), -{ - resolve_imp(ResolveWhat::Frame(frame), &mut cb) -} - -/// A trait representing the resolution of a symbol in a file. -/// -/// This trait is yielded as a trait object to the closure given to the -/// `backtrace::resolve` function, and it is virtually dispatched as it's -/// unknown which implementation is behind it. -/// -/// A symbol can give contextual information about a function, for example the -/// name, filename, line number, precise address, etc. Not all information is -/// always available in a symbol, however, so all methods return an `Option`. -pub struct Symbol { - // TODO: this lifetime bound needs to be persisted eventually to `Symbol`, - // but that's currently a breaking change. For now this is safe since - // `Symbol` is only ever handed out by reference and can't be cloned. - inner: SymbolImp<'static>, -} - -impl Symbol { - /// Returns the name of this function. - /// - /// The returned structure can be used to query various properties about the - /// symbol name: - /// - /// * The `Display` implementation will print out the demangled symbol. - /// * The raw `str` value of the symbol can be accessed (if it's valid - /// utf-8). - /// * The raw bytes for the symbol name can be accessed. - pub fn name(&self) -> Option { - self.inner.name() - } - - /// Returns the starting address of this function. - pub fn addr(&self) -> Option<*mut c_void> { - self.inner.addr().map(|p| p as *mut _) - } - - /// Returns the raw filename as a slice. This is mainly useful for `no_std` - /// environments. - pub fn filename_raw(&self) -> Option { - self.inner.filename_raw() - } - - /// Returns the line number for where this symbol is currently executing. - /// - /// This return value is typically `Some` if `filename` returns `Some`, and - /// is consequently subject to similar caveats. - pub fn lineno(&self) -> Option { - self.inner.lineno() - } - - /// Returns the file name where this function was defined. - /// - /// This is currently only available when libbacktrace is being used (e.g. - /// unix platforms other than OSX) and when a binary is compiled with - /// debuginfo. If neither of these conditions is met then this will likely - /// return `None`. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - #[cfg(feature = "std")] - #[allow(unreachable_code)] - pub fn filename(&self) -> Option<&Path> { - self.inner.filename() - } -} - -impl fmt::Debug for Symbol { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut d = f.debug_struct("Symbol"); - if let Some(name) = self.name() { - d.field("name", &name); - } - if let Some(addr) = self.addr() { - d.field("addr", &addr); - } - - #[cfg(feature = "std")] - { - if let Some(filename) = self.filename() { - d.field("filename", &filename); - } - } - - if let Some(lineno) = self.lineno() { - d.field("lineno", &lineno); - } - d.finish() - } -} - -cfg_if::cfg_if! { - if #[cfg(feature = "cpp_demangle")] { - // Maybe a parsed C++ symbol, if parsing the mangled symbol as Rust - // failed. - struct OptionCppSymbol<'a>(Option<::cpp_demangle::BorrowedSymbol<'a>>); - - impl<'a> OptionCppSymbol<'a> { - fn parse(input: &'a [u8]) -> OptionCppSymbol<'a> { - OptionCppSymbol(::cpp_demangle::BorrowedSymbol::new(input).ok()) - } - - fn none() -> OptionCppSymbol<'a> { - OptionCppSymbol(None) - } - } - } else { - use core::marker::PhantomData; - - // Make sure to keep this zero-sized, so that the `cpp_demangle` feature - // has no cost when disabled. - struct OptionCppSymbol<'a>(PhantomData<&'a ()>); - - impl<'a> OptionCppSymbol<'a> { - fn parse(_: &'a [u8]) -> OptionCppSymbol<'a> { - OptionCppSymbol(PhantomData) - } - - fn none() -> OptionCppSymbol<'a> { - OptionCppSymbol(PhantomData) - } - } - } -} - -/// A wrapper around a symbol name to provide ergonomic accessors to the -/// demangled name, the raw bytes, the raw string, etc. -// Allow dead code for when the `cpp_demangle` feature is not enabled. -#[allow(dead_code)] -pub struct SymbolName<'a> { - bytes: &'a [u8], - demangled: Option>, - cpp_demangled: OptionCppSymbol<'a>, -} - -impl<'a> SymbolName<'a> { - /// Creates a new symbol name from the raw underlying bytes. - pub fn new(bytes: &'a [u8]) -> SymbolName<'a> { - let str_bytes = str::from_utf8(bytes).ok(); - let demangled = str_bytes.and_then(|s| try_demangle(s).ok()); - - let cpp = if demangled.is_none() { - OptionCppSymbol::parse(bytes) - } else { - OptionCppSymbol::none() - }; - - SymbolName { - bytes: bytes, - demangled: demangled, - cpp_demangled: cpp, - } - } - - /// Returns the raw (mangled) symbol name as a `str` if the symbol is valid utf-8. - /// - /// Use the `Display` implementation if you want the demangled version. - pub fn as_str(&self) -> Option<&'a str> { - self.demangled - .as_ref() - .map(|s| s.as_str()) - .or_else(|| str::from_utf8(self.bytes).ok()) - } - - /// Returns the raw symbol name as a list of bytes - pub fn as_bytes(&self) -> &'a [u8] { - self.bytes - } -} - -fn format_symbol_name( - fmt: fn(&str, &mut fmt::Formatter) -> fmt::Result, - mut bytes: &[u8], - f: &mut fmt::Formatter, -) -> fmt::Result { - while bytes.len() > 0 { - match str::from_utf8(bytes) { - Ok(name) => { - fmt(name, f)?; - break; - } - Err(err) => { - fmt("\u{FFFD}", f)?; - - match err.error_len() { - Some(len) => bytes = &bytes[err.valid_up_to() + len..], - None => break, - } - } - } - } - Ok(()) -} - -cfg_if::cfg_if! { - if #[cfg(feature = "cpp_demangle")] { - impl<'a> fmt::Display for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else if let Some(ref cpp) = self.cpp_demangled.0 { - cpp.fmt(f) - } else { - format_symbol_name(fmt::Display::fmt, self.bytes, f) - } - } - } - } else { - impl<'a> fmt::Display for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else { - format_symbol_name(fmt::Display::fmt, self.bytes, f) - } - } - } - } -} - -cfg_if::cfg_if! { - if #[cfg(all(feature = "std", feature = "cpp_demangle"))] { - impl<'a> fmt::Debug for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Write; - - if let Some(ref s) = self.demangled { - return s.fmt(f) - } - - // This may to print if the demangled symbol isn't actually - // valid, so handle the error here gracefully by not propagating - // it outwards. - if let Some(ref cpp) = self.cpp_demangled.0 { - let mut s = String::new(); - if write!(s, "{}", cpp).is_ok() { - return s.fmt(f) - } - } - - format_symbol_name(fmt::Debug::fmt, self.bytes, f) - } - } - } else { - impl<'a> fmt::Debug for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else { - format_symbol_name(fmt::Debug::fmt, self.bytes, f) - } - } - } - } -} - -/// Attempt to reclaim that cached memory used to symbolicate addresses. -/// -/// This method will attempt to release any global data structures that have -/// otherwise been cached globally or in the thread which typically represent -/// parsed DWARF information or similar. -/// -/// # Caveats -/// -/// While this function is always available it doesn't actually do anything on -/// most implementations. Libraries like dbghelp or libbacktrace do not provide -/// facilities to deallocate state and manage the allocated memory. For now the -/// `gimli-symbolize` feature of this crate is the only feature where this -/// function has any effect. -#[cfg(feature = "std")] -pub fn clear_symbol_cache() { - let _guard = crate::lock::lock(); - unsafe { - clear_symbol_cache_imp(); - } -} - -mod dladdr; - -cfg_if::cfg_if! { - if #[cfg(all(windows, target_env = "msvc", feature = "dbghelp", not(target_vendor = "uwp")))] { - mod dbghelp; - use self::dbghelp::resolve as resolve_imp; - use self::dbghelp::Symbol as SymbolImp; - unsafe fn clear_symbol_cache_imp() {} - } else if #[cfg(all( - feature = "std", - feature = "gimli-symbolize", - any( - target_os = "linux", - target_os = "macos", - windows, - ), - ))] { - mod gimli; - use self::gimli::resolve as resolve_imp; - use self::gimli::Symbol as SymbolImp; - use self::gimli::clear_symbol_cache as clear_symbol_cache_imp; - // Note that we only enable coresymbolication on iOS when debug assertions - // are enabled because it's helpful in debug mode but it looks like apps get - // rejected from the app store if they use this API, see #92 for more info - } else if #[cfg(all(feature = "coresymbolication", - any(target_os = "macos", - all(target_os = "ios", debug_assertions))))] { - mod coresymbolication; - use self::coresymbolication::resolve as resolve_imp; - use self::coresymbolication::Symbol as SymbolImp; - unsafe fn clear_symbol_cache_imp() {} - } else if #[cfg(all(feature = "libbacktrace", - any(unix, all(windows, not(target_vendor = "uwp"), target_env = "gnu")), - not(target_os = "fuchsia"), - not(target_os = "emscripten"), - not(target_env = "uclibc")))] { - mod libbacktrace; - use self::libbacktrace::resolve as resolve_imp; - use self::libbacktrace::Symbol as SymbolImp; - unsafe fn clear_symbol_cache_imp() {} - } else if #[cfg(all(unix, - not(target_os = "emscripten"), - not(target_os = "fuchsia"), - not(target_env = "uclibc"), - feature = "dladdr"))] { - mod dladdr_resolve; - use self::dladdr_resolve::resolve as resolve_imp; - use self::dladdr_resolve::Symbol as SymbolImp; - unsafe fn clear_symbol_cache_imp() {} - } else { - mod noop; - use self::noop::resolve as resolve_imp; - use self::noop::Symbol as SymbolImp; - #[allow(unused)] - unsafe fn clear_symbol_cache_imp() {} - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/noop.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/noop.rs deleted file mode 100644 index 5c115d5..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/symbolize/noop.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! Empty symbolication strategy used to compile for platforms that have no -//! support. - -use crate::symbolize::ResolveWhat; -use crate::types::BytesOrWideString; -use crate::SymbolName; -use core::ffi::c_void; -use core::marker; - -pub unsafe fn resolve(_addr: ResolveWhat, _cb: &mut FnMut(&super::Symbol)) {} - -pub struct Symbol<'a> { - _marker: marker::PhantomData<&'a i32>, -} - -impl Symbol<'_> { - pub fn name(&self) -> Option { - None - } - - pub fn addr(&self) -> Option<*mut c_void> { - None - } - - pub fn filename_raw(&self) -> Option { - None - } - - #[cfg(feature = "std")] - pub fn filename(&self) -> Option<&::std::path::Path> { - None - } - - pub fn lineno(&self) -> Option { - None - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/types.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/types.rs deleted file mode 100644 index f7bcb17..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/types.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! Platform dependent types. - -cfg_if::cfg_if! { - if #[cfg(feature = "std")] { - use std::borrow::Cow; - use std::fmt; - use std::path::PathBuf; - use std::prelude::v1::*; - use std::str; - } -} - -/// A platform independent representation of a string. When working with `std` -/// enabled it is recommended to the convenience methods for providing -/// conversions to `std` types. -#[derive(Debug)] -pub enum BytesOrWideString<'a> { - /// A slice, typically provided on Unix platforms. - Bytes(&'a [u8]), - /// Wide strings typically from Windows. - Wide(&'a [u16]), -} - -#[cfg(feature = "std")] -impl<'a> BytesOrWideString<'a> { - /// Lossy converts to a `Cow`, will allocate if `Bytes` is not valid - /// UTF-8 or if `BytesOrWideString` is `Wide`. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn to_str_lossy(&self) -> Cow<'a, str> { - use self::BytesOrWideString::*; - - match self { - &Bytes(slice) => String::from_utf8_lossy(slice), - &Wide(wide) => Cow::Owned(String::from_utf16_lossy(wide)), - } - } - - /// Provides a `Path` representation of `BytesOrWideString`. - /// - /// # Required features - /// - /// This function requires the `std` feature of the `backtrace` crate to be - /// enabled, and the `std` feature is enabled by default. - pub fn into_path_buf(self) -> PathBuf { - #[cfg(unix)] - { - use std::ffi::OsStr; - use std::os::unix::ffi::OsStrExt; - - if let BytesOrWideString::Bytes(slice) = self { - return PathBuf::from(OsStr::from_bytes(slice)); - } - } - - #[cfg(windows)] - { - use std::ffi::OsString; - use std::os::windows::ffi::OsStringExt; - - if let BytesOrWideString::Wide(slice) = self { - return PathBuf::from(OsString::from_wide(slice)); - } - } - - if let BytesOrWideString::Bytes(b) = self { - if let Ok(s) = str::from_utf8(b) { - return PathBuf::from(s); - } - } - unreachable!() - } -} - -#[cfg(feature = "std")] -impl<'a> fmt::Display for BytesOrWideString<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.to_str_lossy().fmt(f) - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/src/windows.rs b/third_party/cargo/vendor/backtrace-0.3.45/src/windows.rs deleted file mode 100644 index 9672af0..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/src/windows.rs +++ /dev/null @@ -1,637 +0,0 @@ -//! A module to define the FFI definitions we use on Windows for `dbghelp.dll` -//! -//! This module uses a custom macro, `ffi!`, to wrap all definitions to -//! automatically generate tests to assert that our definitions here are the -//! same as `winapi`. -//! -//! This module largely exists to integrate into libstd itself where winapi is -//! not currently available. - -#![allow(bad_style, dead_code)] - -cfg_if::cfg_if! { - if #[cfg(feature = "verify-winapi")] { - pub use self::winapi::c_void; - pub use self::winapi::HINSTANCE; - pub use self::winapi::FARPROC; - pub use self::winapi::LPSECURITY_ATTRIBUTES; - #[cfg(target_pointer_width = "64")] - pub use self::winapi::PUNWIND_HISTORY_TABLE; - #[cfg(target_pointer_width = "64")] - pub use self::winapi::PRUNTIME_FUNCTION; - - mod winapi { - pub use winapi::ctypes::*; - pub use winapi::shared::basetsd::*; - pub use winapi::shared::minwindef::*; - pub use winapi::um::dbghelp::*; - pub use winapi::um::handleapi::*; - pub use winapi::um::libloaderapi::*; - pub use winapi::um::processthreadsapi::*; - pub use winapi::um::winbase::*; - pub use winapi::um::winnt::*; - pub use winapi::um::fileapi::*; - pub use winapi::um::minwinbase::*; - pub use winapi::um::synchapi::*; - } - } else { - pub use core::ffi::c_void; - pub type HINSTANCE = *mut c_void; - pub type FARPROC = *mut c_void; - pub type LPSECURITY_ATTRIBUTES = *mut c_void; - #[cfg(target_pointer_width = "64")] - pub type PRUNTIME_FUNCTION = *mut c_void; - #[cfg(target_pointer_width = "64")] - pub type PUNWIND_HISTORY_TABLE = *mut c_void; - } -} - -macro_rules! ffi { - () => (); - - (#[repr($($r:tt)*)] pub struct $name:ident { $(pub $field:ident: $ty:ty,)* } $($rest:tt)*) => ( - #[repr($($r)*)] - #[cfg(not(feature = "verify-winapi"))] - #[derive(Copy, Clone)] - pub struct $name { - $(pub $field: $ty,)* - } - - #[cfg(feature = "verify-winapi")] - pub use self::winapi::$name; - - #[test] - #[cfg(feature = "verify-winapi")] - fn $name() { - use core::mem; - - #[repr($($r)*)] - pub struct $name { - $(pub $field: $ty,)* - } - - assert_eq!( - mem::size_of::<$name>(), - mem::size_of::(), - concat!("size of ", stringify!($name), " is wrong"), - ); - assert_eq!( - mem::align_of::<$name>(), - mem::align_of::(), - concat!("align of ", stringify!($name), " is wrong"), - ); - - type Winapi = winapi::$name; - - fn assert_same(_: T, _: T) {} - - unsafe { - let a = &*(mem::align_of::<$name>() as *const $name); - let b = &*(mem::align_of::() as *const Winapi); - - $( - ffi!(@test_fields a b $field $ty); - )* - } - } - - ffi!($($rest)*); - ); - - // Handling verification against unions in winapi requires some special care - (@test_fields $a:ident $b:ident FltSave $ty:ty) => ( - // Skip this field on x86_64 `CONTEXT` since it's a union and a bit funny - ); - (@test_fields $a:ident $b:ident D $ty:ty) => ({ - let a = &$a.D; - let b = $b.D(); - assert_same(a, b); - assert_eq!(a as *const $ty, b as *const $ty, "misplaced field D"); - }); - (@test_fields $a:ident $b:ident s $ty:ty) => ({ - let a = &$a.s; - let b = $b.s(); - assert_same(a, b); - assert_eq!(a as *const $ty, b as *const $ty, "misplaced field s"); - }); - - // Otherwise test all fields normally. - (@test_fields $a:ident $b:ident $field:ident $ty:ty) => ({ - let a = &$a.$field; - let b = &$b.$field; - assert_same(a, b); - assert_eq!(a as *const $ty, b as *const $ty, - concat!("misplaced field ", stringify!($field))); - }); - - (pub type $name:ident = $ty:ty; $($rest:tt)*) => ( - pub type $name = $ty; - - #[cfg(feature = "verify-winapi")] - #[allow(dead_code)] - const $name: () = { - fn _foo() { - trait SameType {} - impl SameType for (T, T) {} - fn assert_same() {} - - assert_same::<($name, winapi::$name)>(); - } - }; - - ffi!($($rest)*); - ); - - (pub const $name:ident: $ty:ty = $val:expr; $($rest:tt)*) => ( - pub const $name: $ty = $val; - - #[cfg(feature = "verify-winapi")] - #[allow(unused_imports)] - mod $name { - use super::*; - #[test] - fn assert_valid() { - let x: $ty = winapi::$name; - assert_eq!(x, $val); - } - } - - - ffi!($($rest)*); - ); - - (extern "system" { $(pub fn $name:ident($($args:tt)*) -> $ret:ty;)* } $($rest:tt)*) => ( - extern "system" { - $(pub fn $name($($args)*) -> $ret;)* - } - - $( - #[cfg(feature = "verify-winapi")] - mod $name { - #[test] - fn assert_same() { - use super::*; - - assert_eq!($name as usize, winapi::$name as usize); - let mut x: unsafe extern "system" fn($($args)*) -> $ret; - x = $name; - drop(x); - x = winapi::$name; - drop(x); - } - } - )* - - ffi!($($rest)*); - ); - - (impl $name:ident { $($i:tt)* } $($rest:tt)*) => ( - #[cfg(not(feature = "verify-winapi"))] - impl $name { - $($i)* - } - - ffi!($($rest)*); - ); -} - -ffi! { - #[repr(C)] - pub struct STACKFRAME64 { - pub AddrPC: ADDRESS64, - pub AddrReturn: ADDRESS64, - pub AddrFrame: ADDRESS64, - pub AddrStack: ADDRESS64, - pub AddrBStore: ADDRESS64, - pub FuncTableEntry: PVOID, - pub Params: [DWORD64; 4], - pub Far: BOOL, - pub Virtual: BOOL, - pub Reserved: [DWORD64; 3], - pub KdHelp: KDHELP64, - } - - pub type LPSTACKFRAME64 = *mut STACKFRAME64; - - #[repr(C)] - pub struct STACKFRAME_EX { - pub AddrPC: ADDRESS64, - pub AddrReturn: ADDRESS64, - pub AddrFrame: ADDRESS64, - pub AddrStack: ADDRESS64, - pub AddrBStore: ADDRESS64, - pub FuncTableEntry: PVOID, - pub Params: [DWORD64; 4], - pub Far: BOOL, - pub Virtual: BOOL, - pub Reserved: [DWORD64; 3], - pub KdHelp: KDHELP64, - pub StackFrameSize: DWORD, - pub InlineFrameContext: DWORD, - } - - pub type LPSTACKFRAME_EX = *mut STACKFRAME_EX; - - #[repr(C)] - pub struct IMAGEHLP_LINEW64 { - pub SizeOfStruct: DWORD, - pub Key: PVOID, - pub LineNumber: DWORD, - pub FileName: PWSTR, - pub Address: DWORD64, - } - - pub type PIMAGEHLP_LINEW64 = *mut IMAGEHLP_LINEW64; - - #[repr(C)] - pub struct SYMBOL_INFOW { - pub SizeOfStruct: ULONG, - pub TypeIndex: ULONG, - pub Reserved: [ULONG64; 2], - pub Index: ULONG, - pub Size: ULONG, - pub ModBase: ULONG64, - pub Flags: ULONG, - pub Value: ULONG64, - pub Address: ULONG64, - pub Register: ULONG, - pub Scope: ULONG, - pub Tag: ULONG, - pub NameLen: ULONG, - pub MaxNameLen: ULONG, - pub Name: [WCHAR; 1], - } - - pub type PSYMBOL_INFOW = *mut SYMBOL_INFOW; - - pub type PTRANSLATE_ADDRESS_ROUTINE64 = Option< - unsafe extern "system" fn(hProcess: HANDLE, hThread: HANDLE, lpaddr: LPADDRESS64) -> DWORD64, - >; - pub type PGET_MODULE_BASE_ROUTINE64 = - Option DWORD64>; - pub type PFUNCTION_TABLE_ACCESS_ROUTINE64 = - Option PVOID>; - pub type PREAD_PROCESS_MEMORY_ROUTINE64 = Option< - unsafe extern "system" fn( - hProcess: HANDLE, - qwBaseAddress: DWORD64, - lpBuffer: PVOID, - nSize: DWORD, - lpNumberOfBytesRead: LPDWORD, - ) -> BOOL, - >; - - #[repr(C)] - pub struct ADDRESS64 { - pub Offset: DWORD64, - pub Segment: WORD, - pub Mode: ADDRESS_MODE, - } - - pub type LPADDRESS64 = *mut ADDRESS64; - - pub type ADDRESS_MODE = u32; - - #[repr(C)] - pub struct KDHELP64 { - pub Thread: DWORD64, - pub ThCallbackStack: DWORD, - pub ThCallbackBStore: DWORD, - pub NextCallback: DWORD, - pub FramePointer: DWORD, - pub KiCallUserMode: DWORD64, - pub KeUserCallbackDispatcher: DWORD64, - pub SystemRangeStart: DWORD64, - pub KiUserExceptionDispatcher: DWORD64, - pub StackBase: DWORD64, - pub StackLimit: DWORD64, - pub BuildVersion: DWORD, - pub Reserved0: DWORD, - pub Reserved1: [DWORD64; 4], - } - - pub const MAX_SYM_NAME: usize = 2000; - pub const AddrModeFlat: ADDRESS_MODE = 3; - pub const TRUE: BOOL = 1; - pub const FALSE: BOOL = 0; - pub const PROCESS_QUERY_INFORMATION: DWORD = 0x400; - pub const IMAGE_FILE_MACHINE_ARM64: u16 = 43620; - pub const IMAGE_FILE_MACHINE_AMD64: u16 = 34404; - pub const IMAGE_FILE_MACHINE_I386: u16 = 332; - pub const IMAGE_FILE_MACHINE_ARMNT: u16 = 452; - pub const FILE_SHARE_READ: DWORD = 0x1; - pub const FILE_SHARE_WRITE: DWORD = 0x2; - pub const OPEN_EXISTING: DWORD = 0x3; - pub const GENERIC_READ: DWORD = 0x80000000; - pub const INFINITE: DWORD = !0; - - pub type DWORD = u32; - pub type PDWORD = *mut u32; - pub type BOOL = i32; - pub type DWORD64 = u64; - pub type PDWORD64 = *mut u64; - pub type HANDLE = *mut c_void; - pub type PVOID = HANDLE; - pub type PCWSTR = *const u16; - pub type LPSTR = *mut i8; - pub type LPCSTR = *const i8; - pub type PWSTR = *mut u16; - pub type WORD = u16; - pub type ULONG = u32; - pub type ULONG64 = u64; - pub type WCHAR = u16; - pub type PCONTEXT = *mut CONTEXT; - pub type LPDWORD = *mut DWORD; - pub type DWORDLONG = u64; - pub type HMODULE = HINSTANCE; - - extern "system" { - pub fn GetCurrentProcess() -> HANDLE; - pub fn GetCurrentThread() -> HANDLE; - pub fn RtlCaptureContext(ContextRecord: PCONTEXT) -> (); - pub fn LoadLibraryA(a: *const i8) -> HMODULE; - pub fn GetProcAddress(h: HMODULE, name: *const i8) -> FARPROC; - pub fn GetModuleHandleA(name: *const i8) -> HMODULE; - pub fn OpenProcess( - dwDesiredAccess: DWORD, - bInheitHandle: BOOL, - dwProcessId: DWORD, - ) -> HANDLE; - pub fn GetCurrentProcessId() -> DWORD; - pub fn CloseHandle(h: HANDLE) -> BOOL; - pub fn CreateFileA( - lpFileName: LPCSTR, - dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, - dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE, - ) -> HANDLE; - pub fn CreateMutexA( - attrs: LPSECURITY_ATTRIBUTES, - initial: BOOL, - name: LPCSTR, - ) -> HANDLE; - pub fn ReleaseMutex(hMutex: HANDLE) -> BOOL; - pub fn WaitForSingleObjectEx( - hHandle: HANDLE, - dwMilliseconds: DWORD, - bAlertable: BOOL, - ) -> DWORD; - } -} - -#[cfg(target_pointer_width = "64")] -ffi! { - extern "system" { - pub fn RtlLookupFunctionEntry( - ControlPc: DWORD64, - ImageBase: PDWORD64, - HistoryTable: PUNWIND_HISTORY_TABLE, - ) -> PRUNTIME_FUNCTION; - } -} - -#[cfg(target_arch = "aarch64")] -ffi! { - #[repr(C, align(16))] - pub struct CONTEXT { - pub ContextFlags: DWORD, - pub Cpsr: DWORD, - pub u: CONTEXT_u, - pub Sp: u64, - pub Pc: u64, - pub V: [ARM64_NT_NEON128; 32], - pub Fpcr: DWORD, - pub Fpsr: DWORD, - pub Bcr: [DWORD; ARM64_MAX_BREAKPOINTS], - pub Bvr: [DWORD64; ARM64_MAX_BREAKPOINTS], - pub Wcr: [DWORD; ARM64_MAX_WATCHPOINTS], - pub Wvr: [DWORD64; ARM64_MAX_WATCHPOINTS], - } - - #[repr(C)] - pub struct CONTEXT_u { - pub s: CONTEXT_u_s, - } - - impl CONTEXT_u { - pub unsafe fn s(&self) -> &CONTEXT_u_s { - &self.s - } - } - - #[repr(C)] - pub struct CONTEXT_u_s { - pub X0: u64, - pub X1: u64, - pub X2: u64, - pub X3: u64, - pub X4: u64, - pub X5: u64, - pub X6: u64, - pub X7: u64, - pub X8: u64, - pub X9: u64, - pub X10: u64, - pub X11: u64, - pub X12: u64, - pub X13: u64, - pub X14: u64, - pub X15: u64, - pub X16: u64, - pub X17: u64, - pub X18: u64, - pub X19: u64, - pub X20: u64, - pub X21: u64, - pub X22: u64, - pub X23: u64, - pub X24: u64, - pub X25: u64, - pub X26: u64, - pub X27: u64, - pub X28: u64, - pub Fp: u64, - pub Lr: u64, - } - - pub const ARM64_MAX_BREAKPOINTS: usize = 8; - pub const ARM64_MAX_WATCHPOINTS: usize = 2; - - #[repr(C)] - pub struct ARM64_NT_NEON128 { - pub D: [f64; 2], - } -} - -#[cfg(target_arch = "x86")] -ffi! { - #[repr(C)] - pub struct CONTEXT { - pub ContextFlags: DWORD, - pub Dr0: DWORD, - pub Dr1: DWORD, - pub Dr2: DWORD, - pub Dr3: DWORD, - pub Dr6: DWORD, - pub Dr7: DWORD, - pub FloatSave: FLOATING_SAVE_AREA, - pub SegGs: DWORD, - pub SegFs: DWORD, - pub SegEs: DWORD, - pub SegDs: DWORD, - pub Edi: DWORD, - pub Esi: DWORD, - pub Ebx: DWORD, - pub Edx: DWORD, - pub Ecx: DWORD, - pub Eax: DWORD, - pub Ebp: DWORD, - pub Eip: DWORD, - pub SegCs: DWORD, - pub EFlags: DWORD, - pub Esp: DWORD, - pub SegSs: DWORD, - pub ExtendedRegisters: [u8; 512], - } - - #[repr(C)] - pub struct FLOATING_SAVE_AREA { - pub ControlWord: DWORD, - pub StatusWord: DWORD, - pub TagWord: DWORD, - pub ErrorOffset: DWORD, - pub ErrorSelector: DWORD, - pub DataOffset: DWORD, - pub DataSelector: DWORD, - pub RegisterArea: [u8; 80], - pub Spare0: DWORD, - } -} - -#[cfg(target_arch = "x86_64")] -ffi! { - #[repr(C, align(8))] - pub struct CONTEXT { - pub P1Home: DWORDLONG, - pub P2Home: DWORDLONG, - pub P3Home: DWORDLONG, - pub P4Home: DWORDLONG, - pub P5Home: DWORDLONG, - pub P6Home: DWORDLONG, - - pub ContextFlags: DWORD, - pub MxCsr: DWORD, - - pub SegCs: WORD, - pub SegDs: WORD, - pub SegEs: WORD, - pub SegFs: WORD, - pub SegGs: WORD, - pub SegSs: WORD, - pub EFlags: DWORD, - - pub Dr0: DWORDLONG, - pub Dr1: DWORDLONG, - pub Dr2: DWORDLONG, - pub Dr3: DWORDLONG, - pub Dr6: DWORDLONG, - pub Dr7: DWORDLONG, - - pub Rax: DWORDLONG, - pub Rcx: DWORDLONG, - pub Rdx: DWORDLONG, - pub Rbx: DWORDLONG, - pub Rsp: DWORDLONG, - pub Rbp: DWORDLONG, - pub Rsi: DWORDLONG, - pub Rdi: DWORDLONG, - pub R8: DWORDLONG, - pub R9: DWORDLONG, - pub R10: DWORDLONG, - pub R11: DWORDLONG, - pub R12: DWORDLONG, - pub R13: DWORDLONG, - pub R14: DWORDLONG, - pub R15: DWORDLONG, - - pub Rip: DWORDLONG, - - pub FltSave: FLOATING_SAVE_AREA, - - pub VectorRegister: [M128A; 26], - pub VectorControl: DWORDLONG, - - pub DebugControl: DWORDLONG, - pub LastBranchToRip: DWORDLONG, - pub LastBranchFromRip: DWORDLONG, - pub LastExceptionToRip: DWORDLONG, - pub LastExceptionFromRip: DWORDLONG, - } - - #[repr(C)] - pub struct M128A { - pub Low: u64, - pub High: i64, - } -} - -#[repr(C)] -#[cfg(target_arch = "x86_64")] -#[derive(Copy, Clone)] -pub struct FLOATING_SAVE_AREA { - _Dummy: [u8; 512], -} - -#[cfg(target_arch = "arm")] -ffi! { - // #[repr(C)] - // pub struct NEON128 { - // pub Low: ULONG64, - // pub High: LONG64, - // } - - // pub type PNEON128 = *mut NEON128; - - #[repr(C)] - pub struct CONTEXT_u { - // pub Q: [NEON128; 16], - pub D: [ULONG64; 32], - // pub S: [DWORD; 32], - } - - pub const ARM_MAX_BREAKPOINTS: usize = 8; - pub const ARM_MAX_WATCHPOINTS: usize = 1; - - #[repr(C)] - pub struct CONTEXT { - pub ContextFlags: DWORD, - pub R0: DWORD, - pub R1: DWORD, - pub R2: DWORD, - pub R3: DWORD, - pub R4: DWORD, - pub R5: DWORD, - pub R6: DWORD, - pub R7: DWORD, - pub R8: DWORD, - pub R9: DWORD, - pub R10: DWORD, - pub R11: DWORD, - pub R12: DWORD, - pub Sp: DWORD, - pub Lr: DWORD, - pub Pc: DWORD, - pub Cpsr: DWORD, - pub Fpsrc: DWORD, - pub Padding: DWORD, - pub u: CONTEXT_u, - pub Bvr: [DWORD; ARM_MAX_BREAKPOINTS], - pub Bcr: [DWORD; ARM_MAX_BREAKPOINTS], - pub Wvr: [DWORD; ARM_MAX_WATCHPOINTS], - pub Wcr: [DWORD; ARM_MAX_WATCHPOINTS], - pub Padding2: [DWORD; 2], - } -} // IFDEF(arm) diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/auxiliary.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/auxiliary.rs deleted file mode 100644 index 7d04570..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/auxiliary.rs +++ /dev/null @@ -1,16 +0,0 @@ -#[inline(never)] -pub fn callback(f: F) -where - F: FnOnce((&'static str, u32)), -{ - f((file!(), line!())) -} - -#[inline(always)] -#[cfg_attr(feature = "coresymbolication", inline(never))] -pub fn callback_inlined(f: F) -where - F: FnOnce((&'static str, u32)), -{ - f((file!(), line!())) -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/main.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/main.rs deleted file mode 100644 index 7c484a2..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/accuracy/main.rs +++ /dev/null @@ -1,92 +0,0 @@ -mod auxiliary; - -macro_rules! pos { - () => { - (file!(), line!()) - }; -} - -macro_rules! check { - ($($pos:expr),*) => ({ - verify(&[$($pos,)* pos!()]); - }) -} - -type Pos = (&'static str, u32); - -#[test] -fn doit() { - outer(pos!()); -} - -#[inline(never)] -fn outer(main_pos: Pos) { - inner(main_pos, pos!()); - inner_inlined(main_pos, pos!()); -} - -#[inline(never)] -#[rustfmt::skip] -fn inner(main_pos: Pos, outer_pos: Pos) { - check!(main_pos, outer_pos); - check!(main_pos, outer_pos); - let inner_pos = pos!(); auxiliary::callback(|aux_pos| { - check!(main_pos, outer_pos, inner_pos, aux_pos); - }); - let inner_pos = pos!(); auxiliary::callback_inlined(|aux_pos| { - check!(main_pos, outer_pos, inner_pos, aux_pos); - }); -} - -#[inline(always)] -#[cfg_attr(feature = "coresymbolication", inline(never))] -#[rustfmt::skip] -fn inner_inlined(main_pos: Pos, outer_pos: Pos) { - check!(main_pos, outer_pos); - check!(main_pos, outer_pos); - - #[inline(always)] - #[cfg_attr(feature = "coresymbolication", inline(never))] - fn inner_further_inlined(main_pos: Pos, outer_pos: Pos, inner_pos: Pos) { - check!(main_pos, outer_pos, inner_pos); - } - inner_further_inlined(main_pos, outer_pos, pos!()); - - let inner_pos = pos!(); auxiliary::callback(|aux_pos| { - check!(main_pos, outer_pos, inner_pos, aux_pos); - }); - let inner_pos = pos!(); auxiliary::callback_inlined(|aux_pos| { - check!(main_pos, outer_pos, inner_pos, aux_pos); - }); - - // this tests a distinction between two independent calls to the inlined function. - // (un)fortunately, LLVM somehow merges two consecutive such calls into one node. - inner_further_inlined(main_pos, outer_pos, pos!()); -} - -fn verify(filelines: &[Pos]) { - let trace = backtrace::Backtrace::new(); - println!("-----------------------------------"); - println!("looking for:"); - for (file, line) in filelines.iter().rev() { - println!("\t{}:{}", file, line); - } - println!("found:\n{:?}", trace); - let mut symbols = trace.frames().iter().flat_map(|frame| frame.symbols()); - let mut iter = filelines.iter().rev(); - while let Some((file, line)) = iter.next() { - loop { - let sym = match symbols.next() { - Some(sym) => sym, - None => panic!("failed to find {}:{}", file, line), - }; - if let Some(filename) = sym.filename() { - if let Some(lineno) = sym.lineno() { - if filename.ends_with(file) && lineno == *line { - break; - } - } - } - } - } -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/concurrent-panics.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/concurrent-panics.rs deleted file mode 100644 index ac1d61d..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/concurrent-panics.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::env; -use std::panic; -use std::process::Command; -use std::sync::atomic::{AtomicBool, Ordering::SeqCst}; -use std::sync::Arc; -use std::thread; - -const PANICS: usize = 100; -const THREADS: usize = 8; -const VAR: &str = "__THE_TEST_YOU_ARE_LUKE"; - -fn main() { - // These run in docker containers on CI where they can't re-exec the test, - // so just skip these for CI. No other reason this can't run on those - // platforms though. - if cfg!(unix) && (cfg!(target_arch = "arm") || cfg!(target_arch = "aarch64")) { - println!("test result: ok"); - return; - } - - if env::var(VAR).is_err() { - parent(); - } else { - child(); - } -} - -fn parent() { - let me = env::current_exe().unwrap(); - let result = Command::new(&me) - .env("RUST_BACKTRACE", "1") - .env(VAR, "1") - .output() - .unwrap(); - if result.status.success() { - println!("test result: ok"); - return; - } - println!("stdout:\n{}", String::from_utf8_lossy(&result.stdout)); - println!("stderr:\n{}", String::from_utf8_lossy(&result.stderr)); - println!("code: {}", result.status); - panic!(); -} - -fn child() { - let done = Arc::new(AtomicBool::new(false)); - let done2 = done.clone(); - let a = thread::spawn(move || { - while !done2.load(SeqCst) { - format!("{:?}", backtrace::Backtrace::new()); - } - }); - - let threads = (0..THREADS) - .map(|_| { - thread::spawn(|| { - for _ in 0..PANICS { - assert!(panic::catch_unwind(|| { - panic!(); - }) - .is_err()); - } - }) - }) - .collect::>(); - for thread in threads { - thread.join().unwrap(); - } - - done.store(true, SeqCst); - a.join().unwrap(); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/long_fn_name.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/long_fn_name.rs deleted file mode 100644 index a565734..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/long_fn_name.rs +++ /dev/null @@ -1,50 +0,0 @@ -extern crate backtrace; - -use backtrace::Backtrace; - -// 50-character module name -mod _234567890_234567890_234567890_234567890_234567890 { - // 50-character struct name - #[allow(non_camel_case_types)] - pub struct _234567890_234567890_234567890_234567890_234567890(T); - impl _234567890_234567890_234567890_234567890_234567890 { - #[allow(dead_code)] - pub fn new() -> crate::Backtrace { - crate::Backtrace::new() - } - } -} - -// Long function names must be truncated to (MAX_SYM_NAME - 1) characters. -// Only run this test for msvc, since gnu prints "" for all frames. -#[test] -#[cfg(all(windows, feature = "dbghelp", target_env = "msvc"))] -fn test_long_fn_name() { - use _234567890_234567890_234567890_234567890_234567890::_234567890_234567890_234567890_234567890_234567890 as S; - - // 10 repetitions of struct name, so fully qualified function name is - // atleast 10 * (50 + 50) * 2 = 2000 characters long. - // It's actually longer since it also includes `::`, `<>` and the - // name of the current module - let bt = S::>>>>>>>>>::new(); - println!("{:?}", bt); - - let mut found_long_name_frame = false; - - for frame in bt.frames() { - let symbols = frame.symbols(); - if symbols.is_empty() { - continue; - } - - if let Some(function_name) = symbols[0].name() { - let function_name = function_name.as_str().unwrap(); - if function_name.contains("::_234567890_234567890_234567890_234567890_234567890") { - found_long_name_frame = true; - assert!(function_name.len() > 200); - } - } - } - - assert!(found_long_name_frame); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/skip_inner_frames.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/skip_inner_frames.rs deleted file mode 100644 index f5043ee..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/skip_inner_frames.rs +++ /dev/null @@ -1,49 +0,0 @@ -extern crate backtrace; - -use backtrace::Backtrace; - -// This test only works on platforms which have a working `symbol_address` -// function for frames which reports the starting address of a symbol. As a -// result it's only enabled on a few platforms. -const ENABLED: bool = cfg!(all( - // Windows hasn't really been tested, and OSX doesn't support actually - // finding an enclosing frame, so disable this - target_os = "linux", - // This is the only method currently that supports accurate enough - // backtraces for this test to work. - feature = "libunwind", - // On ARM finding the enclosing function is simply returning the ip itself. - not(target_arch = "arm"), -)); - -#[test] -fn backtrace_new_unresolved_should_start_with_call_site_trace() { - if !ENABLED { - return; - } - let mut b = Backtrace::new_unresolved(); - b.resolve(); - println!("{:?}", b); - - assert!(!b.frames().is_empty()); - - let this_ip = backtrace_new_unresolved_should_start_with_call_site_trace as usize; - println!("this_ip: {:?}", this_ip as *const usize); - let frame_ip = b.frames().first().unwrap().symbol_address() as usize; - assert_eq!(this_ip, frame_ip); -} - -#[test] -fn backtrace_new_should_start_with_call_site_trace() { - if !ENABLED { - return; - } - let b = Backtrace::new(); - println!("{:?}", b); - - assert!(!b.frames().is_empty()); - - let this_ip = backtrace_new_should_start_with_call_site_trace as usize; - let frame_ip = b.frames().first().unwrap().symbol_address() as usize; - assert_eq!(this_ip, frame_ip); -} diff --git a/third_party/cargo/vendor/backtrace-0.3.45/tests/smoke.rs b/third_party/cargo/vendor/backtrace-0.3.45/tests/smoke.rs deleted file mode 100644 index 7f90d29..0000000 --- a/third_party/cargo/vendor/backtrace-0.3.45/tests/smoke.rs +++ /dev/null @@ -1,250 +0,0 @@ -extern crate backtrace; - -use backtrace::Frame; -use std::thread; - -static LIBUNWIND: bool = cfg!(all(unix, feature = "libunwind")); -static UNIX_BACKTRACE: bool = cfg!(all(unix, feature = "unix-backtrace")); -static LIBBACKTRACE: bool = cfg!(feature = "libbacktrace") && !cfg!(target_os = "fuchsia"); -static CORESYMBOLICATION: bool = cfg!(all( - any(target_os = "macos", target_os = "ios"), - feature = "coresymbolication" -)); -static DLADDR: bool = cfg!(all(unix, feature = "dladdr")) && !cfg!(target_os = "fuchsia"); -static DBGHELP: bool = cfg!(all(windows, feature = "dbghelp")); -static MSVC: bool = cfg!(target_env = "msvc"); -static GIMLI_SYMBOLIZE: bool = cfg!(all(feature = "gimli-symbolize", unix, target_os = "linux")); - -#[test] -// FIXME: shouldn't ignore this test on i686-msvc, unsure why it's failing -#[cfg_attr(all(target_arch = "x86", target_env = "msvc"), ignore)] -#[rustfmt::skip] // we care about line numbers here -fn smoke_test_frames() { - frame_1(line!()); - #[inline(never)] fn frame_1(start_line: u32) { frame_2(start_line) } - #[inline(never)] fn frame_2(start_line: u32) { frame_3(start_line) } - #[inline(never)] fn frame_3(start_line: u32) { frame_4(start_line) } - #[inline(never)] fn frame_4(start_line: u32) { - let mut v = Vec::new(); - backtrace::trace(|cx| { - v.push(cx.clone()); - true - }); - - if v.len() < 5 { - assert!(!LIBUNWIND); - assert!(!UNIX_BACKTRACE); - assert!(!DBGHELP); - return; - } - - // Various platforms have various bits of weirdness about their - // backtraces. To find a good starting spot let's search through the - // frames - let target = frame_4 as usize; - let offset = v - .iter() - .map(|frame| frame.symbol_address() as usize) - .enumerate() - .filter_map(|(i, sym)| { - if sym >= target { - Some((sym, i)) - } else { - None - } - }) - .min() - .unwrap() - .1; - let mut frames = v[offset..].iter(); - - assert_frame( - frames.next().unwrap(), - frame_4 as usize, - "frame_4", - "tests/smoke.rs", - start_line + 6, - ); - assert_frame( - frames.next().unwrap(), - frame_3 as usize, - "frame_3", - "tests/smoke.rs", - start_line + 3, - ); - assert_frame( - frames.next().unwrap(), - frame_2 as usize, - "frame_2", - "tests/smoke.rs", - start_line + 2, - ); - assert_frame( - frames.next().unwrap(), - frame_1 as usize, - "frame_1", - "tests/smoke.rs", - start_line + 1, - ); - assert_frame( - frames.next().unwrap(), - smoke_test_frames as usize, - "smoke_test_frames", - "", - 0, - ); - } - - fn assert_frame( - frame: &Frame, - actual_fn_pointer: usize, - expected_name: &str, - expected_file: &str, - expected_line: u32, - ) { - backtrace::resolve_frame(frame, |sym| { - print!("symbol ip:{:?} address:{:?} ", frame.ip(), frame.symbol_address()); - if let Some(name) = sym.name() { - print!("name:{} ", name); - } - if let Some(file) = sym.filename() { - print!("file:{} ", file.display()); - } - if let Some(lineno) = sym.lineno() { - print!("lineno:{} ", lineno); - } - println!(); - }); - - let ip = frame.ip() as usize; - let sym = frame.symbol_address() as usize; - assert!(ip >= sym); - assert!( - sym >= actual_fn_pointer, - "{:?} < {:?} ({} {}:{})", - sym as *const usize, - actual_fn_pointer as *const usize, - expected_name, - expected_file, - expected_line, - ); - - // windows dbghelp is *quite* liberal (and wrong) in many of its reports - // right now... - // - // This assertion can also fail for release builds, so skip it there - if !DBGHELP && cfg!(debug_assertions) { - assert!(sym - actual_fn_pointer < 1024); - } - - let mut resolved = 0; - let can_resolve = DLADDR || LIBBACKTRACE || CORESYMBOLICATION || DBGHELP || GIMLI_SYMBOLIZE; - - let mut name = None; - let mut addr = None; - let mut line = None; - let mut file = None; - backtrace::resolve_frame(frame, |sym| { - resolved += 1; - name = sym.name().map(|v| v.to_string()); - addr = sym.addr(); - line = sym.lineno(); - file = sym.filename().map(|v| v.to_path_buf()); - }); - - // dbghelp doesn't always resolve symbols right now - match resolved { - 0 => return assert!(!can_resolve || DBGHELP), - _ => {} - } - - // * linux dladdr doesn't work (only consults local symbol table) - // * windows dbghelp isn't great for GNU - if can_resolve && !(cfg!(target_os = "linux") && DLADDR) && !(DBGHELP && !MSVC) { - let name = name.expect("didn't find a name"); - - // in release mode names get weird as functions can get merged - // together with `mergefunc`, so only assert this in debug mode - if cfg!(debug_assertions) { - assert!( - name.contains(expected_name), - "didn't find `{}` in `{}`", - expected_name, - name - ); - } - } - - if can_resolve { - addr.expect("didn't find a symbol"); - } - - if (LIBBACKTRACE || CORESYMBOLICATION || (DBGHELP && MSVC)) && cfg!(debug_assertions) { - let line = line.expect("didn't find a line number"); - let file = file.expect("didn't find a line number"); - if !expected_file.is_empty() { - assert!( - file.ends_with(expected_file), - "{:?} didn't end with {:?}", - file, - expected_file - ); - } - if expected_line != 0 { - assert!( - line == expected_line, - "bad line number on frame for `{}`: {} != {}", - expected_name, - line, - expected_line - ); - } - } - } -} - -#[test] -fn many_threads() { - let threads = (0..16) - .map(|_| { - thread::spawn(|| { - for _ in 0..16 { - backtrace::trace(|frame| { - backtrace::resolve(frame.ip(), |symbol| { - let _s = symbol.name().map(|s| s.to_string()); - }); - true - }); - } - }) - }) - .collect::>(); - - for t in threads { - t.join().unwrap() - } -} - -#[test] -#[cfg(feature = "rustc-serialize")] -fn is_rustc_serialize() { - extern crate rustc_serialize; - - fn is_encode() {} - fn is_decode() {} - - is_encode::(); - is_decode::(); -} - -#[test] -#[cfg(feature = "serde")] -fn is_serde() { - extern crate serde; - - fn is_serialize() {} - fn is_deserialize() {} - - is_serialize::(); - is_deserialize::(); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/.cargo-checksum.json b/third_party/cargo/vendor/backtrace-sys-0.1.34/.cargo-checksum.json deleted file mode 100644 index 1a277a2..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"8b0ab1ad7e82e263ac9eb6d6e052273a5bec43632c87ff3aaeaa281bf8d4aae7","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","build.rs":"c841c48828f1a8a243cb022863ebcab47f4a21c521b5a2566559ee2882e00e1a","src/android-api.c":"b75f16de578451464f49b83dc817b76aa9a0be0d86ea71d1659cc78f99e94fbd","src/lib.rs":"ccd15703f469cb10d620a30a1accd8834e8012abab5b626f925777275d6d2b02","src/libbacktrace/LICENSE":"ef8a9b3247488f8901ca60de9b17b745d7bd67e5ec1e622f80d62364572200d8","src/libbacktrace/Makefile.am":"5353e0ce3a4732b42ccf031c474f7234336992cb23ba76cbfda3aa5262e69988","src/libbacktrace/Makefile.in":"1802d55fa8ef616a407c69311b3fa4e579093d124a215c834149ab1c50b4f3ad","src/libbacktrace/Mark.Twain-Tom.Sawyer.txt":"461eb7cb2d57d293fc680c836464c9125e4382be3596f7d415093ae9db8fcb0e","src/libbacktrace/README.md":"3b27ca2f7ddaf464ad81366a278ed4d34ad513de3766b330a51464828fa3131f","src/libbacktrace/acinclude.m4":"7f1d64805039b0e41d4c4106265618a6f8921d3cf091d64ab31fa7b900dc892f","src/libbacktrace/aclocal.m4":"4899cfe70722ba1de2b42b4e9965c1db1b173b5d6d4522cdc785becd5a5c212c","src/libbacktrace/alloc.c":"33891bbaf755c050058f8fd7dd3708e6062ef65245a0717216af45b78bab0fd0","src/libbacktrace/atomic.c":"82fd23c7ee7154d1ce4fc823637ede9cfa0e469f4073f38fff4dd9081070f1aa","src/libbacktrace/backtrace-supported.h.in":"42277f3c383386b6cfa3d3d889336e92303fac0ae1a9fb8a6a56737245dfb8f3","src/libbacktrace/backtrace.c":"837ea7b781a737d1ed37e4d03c463bcbe1432b2dc3b79b37344b21013cdfcca4","src/libbacktrace/backtrace.h":"9f035b3830c1c6000259c8ecf0bf53144f7c2e6064dfc95975b89f7f612ebf0e","src/libbacktrace/btest.c":"41c774496d58177e408b1dc33d6a792d0940634885978eed73fb192f732cafc5","src/libbacktrace/config.guess":"9be3de218833c076786b919dc34aab691611f4cd73316e7705f2673e2c41921b","src/libbacktrace/config.h.in":"b5002d9f96f6a26f54317f9d23a5ffff71fa3ee520fd8993810891d43b9a9bf7","src/libbacktrace/config.sub":"c8e70ab53f04d2f2b0280aa0e8a5432e90a902bfa2af7b0854168eb1fb3a84c0","src/libbacktrace/config/libtool.m4":"644ce34d5e9fcc544f3ef5c707f4cb29add798bbfc24e29932b55fb251e50353","src/libbacktrace/config/ltoptions.m4":"9d294950c4d97e2c891d472933113f397d410ef2a8ed875d714f81761626bbd8","src/libbacktrace/config/ltsugar.m4":"2c6618a04aa6389a2a528cde2e69ed5de55acc6c50892b486ea3e56e4e5b2c3b","src/libbacktrace/config/ltversion.m4":"8d129a46367fadad9f202dac50e708696d4d628313d01745127388e9c736e996","src/libbacktrace/config/lt~obsolete.m4":"c6c668594337aafef7d59f585bce7010436153815fe341461d81301a2235b959","src/libbacktrace/configure":"59763fc255248b54fba5d0761d61093a73d51fa4cb400b0df1b5f339b9c2f48a","src/libbacktrace/configure.ac":"b9292548330eb4d2cb014e9d9e6cd4df656aed982917365896a8f2534e9732e5","src/libbacktrace/dwarf.c":"c2103af5f94dd135e5df2a98dfc28ef2cbe0f3d56783d21e1487b9f314bfcbbc","src/libbacktrace/edtest.c":"947b9878ae45f6ba95d3b949bb080e9feed4ffdb27536cf5602b81ce79556ccf","src/libbacktrace/edtest2.c":"964bb0bb510a19013fb1cb56552929ed15cf55787eba4369d5820b74be07d249","src/libbacktrace/elf.c":"fe3e10d33c0c0965f016381302128ce82d664071095ad5077932377e3a789679","src/libbacktrace/fileline.c":"7b3b92044648f45becc498d4ed41ddc8ec08f0d11f6491cc05cfccd8a4d7627a","src/libbacktrace/filenames.h":"2c23cde7dd12dd9e0343cb37b5066036112deca703b61178f07c01f3e01398c9","src/libbacktrace/filetype.awk":"aa38776487a77dc13c93efa2a861204b384c3c4333501ed9bdb4ccbde2a784c0","src/libbacktrace/install-sh":"e7064b5e01a8d173409749c337966698fa04661cde1e3ef1a93be250eec0d2c3","src/libbacktrace/internal.h":"88c63ad6acc7e68330df3028675be4d4e3374bd787255fe22dd3febbbbc438b6","src/libbacktrace/ltmain.sh":"873bdcbc8690bd90c0f3632aac40027e880fd95ea45fb5a02ed901fea4afa4fe","src/libbacktrace/macho.c":"9a8864901eede4c34305b05bb6e815b25b76f04b59caf74381ca9dfbe8f1a8c4","src/libbacktrace/missing":"300bea3fb273b763eca2e4bb1576c663605d9b49de385fd375f82be8d912f506","src/libbacktrace/mmap.c":"5be917f3e9eba1fe49eb1bb391e28609e8377b4ce4593cace6012bf17434a33c","src/libbacktrace/mmapio.c":"be5719c4f92e70045fe6014a0493a5b4adc165ecde42c20130ea6e9da1ce978f","src/libbacktrace/move-if-change":"689762b92d23003926ba729acf98b9a109abf46de0698c09ddfa0d20490d8af5","src/libbacktrace/nounwind.c":"5eee9cc7298b7d0d2aea68eef62175541f34f88acf17736e0612056c5bb7318d","src/libbacktrace/pecoff.c":"bb536ae71a1a1c4dad5508d26032e7e81860df6d8ddfc8d696378ebefbc513b1","src/libbacktrace/posix.c":"f5e0ff701a1a1e29a25462ea49f174b049dafc6c25e040ee0eb77dd189353277","src/libbacktrace/print.c":"2d446406c8e2d9a1258d46d119be1c563bd86b6a4039cbf773b6de09c541390d","src/libbacktrace/read.c":"d0d4007f681f265a6c31e27ded45f4007502c90464eefdb4e80b69e4ae2ede28","src/libbacktrace/simple.c":"b0f767d3740195015aeadaa67e84bf6eb255a730f258485ca86bdbe02b066eca","src/libbacktrace/sort.c":"a82f911fc826a353ea5616379748dfa318ad4e57e20791af7ead853f7e73583d","src/libbacktrace/state.c":"a45abbe4077a47d17fb9687057c40828e633df12d21b8ed40b71a78d86918100","src/libbacktrace/stest.c":"7443fe435f1ee5ce49a3e634faf81a4137d66a057577fe88a211cfa819ddb2e2","src/libbacktrace/testlib.c":"a7e096e895b36db7f997a6673ce48f92a032046876511e813a8a52de6079b29a","src/libbacktrace/testlib.h":"02e02404dc89dd4f3dd82635f794a927541dd78d490d777bedf8a5424e5033fc","src/libbacktrace/ttest.c":"380f3b2be164bd6770768181fa05f1778cee8f0322434896d19724ae7cd105df","src/libbacktrace/unknown.c":"d2d148ea045dcad96ba1c5528b7036b000eeb8439ae397bca01deb0d8b287972","src/libbacktrace/xcoff.c":"e70ed97743306f71ea6132a058d68f1bb7be1380a2d38725b5dc877f5e07905d","src/libbacktrace/ztest.c":"7ad8277664e596aecb6af25818b7671e199ef6002ec2c38d9288179c5cad2082"},"package":"ca797db0057bae1a7aa2eef3283a874695455cecf08a43bfb8507ee0ebc1ed69"} \ No newline at end of file diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/Cargo.toml b/third_party/cargo/vendor/backtrace-sys-0.1.34/Cargo.toml deleted file mode 100644 index dbd49b9..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/Cargo.toml +++ /dev/null @@ -1,41 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "backtrace-sys" -version = "0.1.34" -authors = ["Alex Crichton "] -build = "build.rs" -description = "Bindings to the libbacktrace gcc library\n" -homepage = "https://github.com/alexcrichton/backtrace-rs" -documentation = "http://alexcrichton.com/backtrace-rs" -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/backtrace-rs" -[dependencies.compiler_builtins] -version = "0.1.2" -optional = true - -[dependencies.core] -version = "1.0.0" -optional = true -package = "rustc-std-workspace-core" - -[dependencies.libc] -version = "0.2" -default-features = false -[build-dependencies.cc] -version = "1.0.37" - -[features] -backtrace-sys = [] -default = ["backtrace-sys"] -rustc-dep-of-std = ["core", "compiler_builtins"] diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/build.rs b/third_party/cargo/vendor/backtrace-sys-0.1.34/build.rs deleted file mode 100644 index e963113..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/build.rs +++ /dev/null @@ -1,166 +0,0 @@ -extern crate cc; - -use std::env; -use std::fs::File; -use std::path::PathBuf; - -fn main() { - let target = env::var("TARGET").unwrap(); - - if !cfg!(feature = "backtrace-sys") || // without this feature, this crate does nothing - target.contains("msvc") || // libbacktrace isn't used on MSVC windows - target.contains("emscripten") || // no way this will ever compile for emscripten - target.contains("cloudabi") || - target.contains("hermit") || - target.contains("wasm32") || - target.contains("fuchsia") || - target.contains("uclibc") - { - println!("cargo:rustc-cfg=empty"); - return; - } - - let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap()); - - let mut build = cc::Build::new(); - build - .include("src/libbacktrace") - .include(&out_dir) - .warnings(false) - .file("src/libbacktrace/alloc.c") - .file("src/libbacktrace/dwarf.c") - .file("src/libbacktrace/fileline.c") - .file("src/libbacktrace/posix.c") - .file("src/libbacktrace/sort.c") - .file("src/libbacktrace/state.c"); - - // `mmap` does not exist on Windows, so we use - // the less efficient `read`-based code. - // Using `mmap` on macOS causes weird isseus - see - // https://github.com/rust-lang/rust/pull/45866 - if target.contains("windows") || target.contains("darwin") { - build.file("src/libbacktrace/read.c"); - } else { - build.file("src/libbacktrace/mmapio.c"); - } - - // No need to have any symbols reexported form shared objects - build.flag("-fvisibility=hidden"); - - if target.contains("darwin") { - build.file("src/libbacktrace/macho.c"); - } else if target.contains("windows") { - build.file("src/libbacktrace/pecoff.c"); - } else { - build.file("src/libbacktrace/elf.c"); - - let pointer_width = env::var("CARGO_CFG_TARGET_POINTER_WIDTH").unwrap(); - if pointer_width == "64" { - build.define("BACKTRACE_ELF_SIZE", "64"); - } else { - build.define("BACKTRACE_ELF_SIZE", "32"); - } - } - - File::create(out_dir.join("backtrace-supported.h")).unwrap(); - build.define("BACKTRACE_SUPPORTED", "1"); - build.define("BACKTRACE_USES_MALLOC", "1"); - build.define("BACKTRACE_SUPPORTS_THREADS", "0"); - build.define("BACKTRACE_SUPPORTS_DATA", "0"); - - File::create(out_dir.join("config.h")).unwrap(); - if target.contains("android") { - maybe_enable_dl_iterate_phdr_android(&mut build); - } else if !target.contains("apple-ios") - && !target.contains("solaris") - && !target.contains("redox") - && !target.contains("haiku") - && !target.contains("vxworks") - { - build.define("HAVE_DL_ITERATE_PHDR", "1"); - } - build.define("_GNU_SOURCE", "1"); - build.define("_LARGE_FILES", "1"); - - // When we're built as part of the Rust compiler, this is used to enable - // debug information in libbacktrace itself. - let any_debug = env::var("RUSTC_DEBUGINFO").unwrap_or_default() == "true" - || env::var("RUSTC_DEBUGINFO_LINES").unwrap_or_default() == "true"; - build.debug(any_debug); - - let syms = [ - "backtrace_full", - "backtrace_dwarf_add", - "backtrace_initialize", - "backtrace_pcinfo", - "backtrace_syminfo", - "backtrace_get_view", - "backtrace_release_view", - "backtrace_alloc", - "backtrace_free", - "backtrace_vector_finish", - "backtrace_vector_grow", - "backtrace_vector_release", - "backtrace_close", - "backtrace_open", - "backtrace_print", - "backtrace_simple", - "backtrace_qsort", - "backtrace_create_state", - "backtrace_uncompress_zdebug", - // These should be `static` in C, but they aren't... - "macho_get_view", - "macho_symbol_type_relevant", - "macho_get_commands", - "macho_try_dsym", - "macho_try_dwarf", - "macho_get_addr_range", - "macho_get_uuid", - "macho_add", - "macho_add_symtab", - "macho_file_to_host_u64", - "macho_file_to_host_u32", - "macho_file_to_host_u16", - ]; - let prefix = if cfg!(feature = "rustc-dep-of-std") { - println!("cargo:rustc-cfg=rdos"); - "__rdos_" - } else { - println!("cargo:rustc-cfg=rbt"); - "__rbt_" - }; - for sym in syms.iter() { - build.define(sym, &format!("{}{}", prefix, sym)[..]); - } - - build.compile("backtrace"); -} - -// The `dl_iterate_phdr` API was added in Android API 21+ (according to #227), -// so if we can dynamically detect an appropriately configured C compiler for -// that then let's enable the `dl_iterate_phdr` API, otherwise Android just -// won't have any information. -fn maybe_enable_dl_iterate_phdr_android(build: &mut cc::Build) { - let expansion = cc::Build::new().file("src/android-api.c").expand(); - let expansion = match std::str::from_utf8(&expansion) { - Ok(s) => s, - Err(_) => return, - }; - println!("expanded android version detection:\n{}", expansion); - let marker = "APIVERSION"; - let i = match expansion.find(marker) { - Some(i) => i, - None => return, - }; - let version = match expansion[i + marker.len() + 1..].split_whitespace().next() { - Some(s) => s, - None => return, - }; - let version = match version.parse::() { - Ok(n) => n, - Err(_) => return, - }; - if version >= 21 { - build.define("HAVE_DL_ITERATE_PHDR", "1"); - } -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/android-api.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/android-api.c deleted file mode 100644 index 1bfeadf..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/android-api.c +++ /dev/null @@ -1,4 +0,0 @@ -// Used from the build script to detect the value of the `__ANDROID_API__` -// builtin #define - -APIVERSION __ANDROID_API__ diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/lib.rs b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/lib.rs deleted file mode 100644 index 98a54c3..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/lib.rs +++ /dev/null @@ -1,58 +0,0 @@ -#![allow(bad_style)] -#![no_std] - -extern crate libc; - -#[cfg(not(empty))] -pub use self::bindings::*; -#[cfg(not(empty))] -mod bindings { - use libc::{c_char, c_int, c_void, uintptr_t}; - - pub type backtrace_syminfo_callback = extern "C" fn( - data: *mut c_void, - pc: uintptr_t, - symname: *const c_char, - symval: uintptr_t, - symsize: uintptr_t, - ); - pub type backtrace_full_callback = extern "C" fn( - data: *mut c_void, - pc: uintptr_t, - filename: *const c_char, - lineno: c_int, - function: *const c_char, - ) -> c_int; - pub type backtrace_error_callback = - extern "C" fn(data: *mut c_void, msg: *const c_char, errnum: c_int); - pub enum backtrace_state {} - - extern "C" { - #[cfg_attr(rdos, link_name = "__rdos_backtrace_create_state")] - #[cfg_attr(rbt, link_name = "__rbt_backtrace_create_state")] - pub fn backtrace_create_state( - filename: *const c_char, - threaded: c_int, - error: backtrace_error_callback, - data: *mut c_void, - ) -> *mut backtrace_state; - #[cfg_attr(rdos, link_name = "__rdos_backtrace_syminfo")] - #[cfg_attr(rbt, link_name = "__rbt_backtrace_syminfo")] - pub fn backtrace_syminfo( - state: *mut backtrace_state, - addr: uintptr_t, - cb: backtrace_syminfo_callback, - error: backtrace_error_callback, - data: *mut c_void, - ) -> c_int; - #[cfg_attr(rdos, link_name = "__rdos_backtrace_pcinfo")] - #[cfg_attr(rbt, link_name = "__rbt_backtrace_pcinfo")] - pub fn backtrace_pcinfo( - state: *mut backtrace_state, - addr: uintptr_t, - cb: backtrace_full_callback, - error: backtrace_error_callback, - data: *mut c_void, - ) -> c_int; - } -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/LICENSE b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/LICENSE deleted file mode 100644 index 097d277..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -# Copyright (C) 2012-2016 Free Software Foundation, Inc. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# (1) Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. - -# (2) 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. - -# (3) The name of the author may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.am b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.am deleted file mode 100644 index 56a3d1b..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.am +++ /dev/null @@ -1,206 +0,0 @@ -# Makefile.am -- Backtrace Makefile. -# Copyright (C) 2012-2018 Free Software Foundation, Inc. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# (1) Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. - -# (2) 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. - -# (3) The name of the author may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. - -ACLOCAL_AMFLAGS = -I config - -AM_CFLAGS = $(EXTRA_FLAGS) $(WARN_FLAGS) $(PIC_FLAG) - -include_HEADERS = backtrace.h backtrace-supported.h - -lib_LTLIBRARIES = libbacktrace.la - -libbacktrace_la_SOURCES = \ - backtrace.h \ - atomic.c \ - dwarf.c \ - fileline.c \ - internal.h \ - posix.c \ - print.c \ - sort.c \ - state.c - -BACKTRACE_FILES = \ - backtrace.c \ - simple.c \ - nounwind.c - -FORMAT_FILES = \ - elf.c \ - pecoff.c \ - unknown.c \ - xcoff.c - -VIEW_FILES = \ - read.c \ - mmapio.c - -ALLOC_FILES = \ - alloc.c \ - mmap.c - -EXTRA_libbacktrace_la_SOURCES = \ - $(BACKTRACE_FILES) \ - $(FORMAT_FILES) \ - $(VIEW_FILES) \ - $(ALLOC_FILES) - -libbacktrace_la_LIBADD = \ - $(BACKTRACE_FILE) \ - $(FORMAT_FILE) \ - $(VIEW_FILE) \ - $(ALLOC_FILE) - -libbacktrace_la_DEPENDENCIES = $(libbacktrace_la_LIBADD) - -# Testsuite. - -check_PROGRAMS = -CLEANFILES = - -TESTS = $(check_PROGRAMS) - -if NATIVE - -btest_SOURCES = btest.c testlib.c -btest_CFLAGS = $(AM_CFLAGS) -g -O -btest_LDADD = libbacktrace.la - -check_PROGRAMS += btest - -btest_static_SOURCES = btest.c testlib.c -btest_static_CFLAGS = $(AM_CFLAGS) -g -O -btest_static_LDADD = libbacktrace.la -btest_static_LDFLAGS = -static-libtool-libs - -check_PROGRAMS += btest_static - -stest_SOURCES = stest.c -stest_LDADD = libbacktrace.la - -check_PROGRAMS += stest - -ztest_SOURCES = ztest.c testlib.c -ztest_CFLAGS = -DSRCDIR=\"$(srcdir)\" -ztest_LDADD = libbacktrace.la - -if HAVE_ZLIB -ztest_LDADD += -lz -endif -ztest_LDADD += $(CLOCK_GETTIME_LINK) - -check_PROGRAMS += ztest - -edtest_SOURCES = edtest.c edtest2_build.c testlib.c -edtest_LDADD = libbacktrace.la - -check_PROGRAMS += edtest - -edtest2_build.c: gen_edtest2_build; @true -gen_edtest2_build: $(srcdir)/edtest2.c - cat $(srcdir)/edtest2.c > tmp-edtest2_build.c - $(SHELL) $(srcdir)/move-if-change tmp-edtest2_build.c edtest2_build.c - echo timestamp > $@ - -CLEANFILES += edtest2_build.c gen_edtest2_build - -if HAVE_PTHREAD - -check_PROGRAMS += ttest - -ttest_SOURCES = ttest.c testlib.c -ttest_CFLAGS = $(AM_CFLAGS) -pthread -ttest_LDADD = libbacktrace.la - -endif HAVE_PTHREAD - -if HAVE_OBJCOPY_DEBUGLINK - -TESTS += dtest - -dtest: btest_static - $(OBJCOPY) --only-keep-debug btest_static btest.debug - $(OBJCOPY) --strip-debug --add-gnu-debuglink=btest.debug btest_static dtest - -CLEANFILES += dtest btest.debug - -endif HAVE_OBJCOPY_DEBUGLINK - -if HAVE_COMPRESSED_DEBUG - -ctestg_SOURCES = btest.c testlib.c -ctestg_CFLAGS = $(AM_CFLAGS) -g -ctestg_LDFLAGS = -Wl,--compress-debug-sections=zlib-gnu -ctestg_LDADD = libbacktrace.la - -ctesta_SOURCES = btest.c testlib.c -ctesta_CFLAGS = $(AM_CFLAGS) -g -ctesta_LDFLAGS = -Wl,--compress-debug-sections=zlib-gabi -ctesta_LDADD = libbacktrace.la - -check_PROGRAMS += ctestg ctesta - -endif - -endif NATIVE - -# We can't use automake's automatic dependency tracking, because it -# breaks when using bootstrap-lean. Automatic dependency tracking -# with GCC bootstrap will cause some of the objects to depend on -# header files in prev-gcc/include, e.g., stddef.h and stdarg.h. When -# using bootstrap-lean, prev-gcc is removed after each stage. When -# running "make install", those header files will be gone, causing the -# library to be rebuilt at install time. That may not succeed. - -# These manual dependencies do not include dependencies on unwind.h, -# even though that is part of GCC, because where to find it depends on -# whether we are being built as a host library or a target library. - -alloc.lo: config.h backtrace.h internal.h -backtrace.lo: config.h backtrace.h internal.h -btest.lo: backtrace.h backtrace-supported.h filenames.h -dwarf.lo: config.h filenames.h backtrace.h internal.h -elf.lo: config.h backtrace.h internal.h -fileline.lo: config.h backtrace.h internal.h -mmap.lo: config.h backtrace.h internal.h -mmapio.lo: config.h backtrace.h internal.h -nounwind.lo: config.h internal.h -pecoff.lo: config.h backtrace.h internal.h -posix.lo: config.h backtrace.h internal.h -print.lo: config.h backtrace.h internal.h -read.lo: config.h backtrace.h internal.h -simple.lo: config.h backtrace.h internal.h -sort.lo: config.h backtrace.h internal.h -stest.lo: config.h backtrace.h internal.h -state.lo: config.h backtrace.h backtrace-supported.h internal.h -unknown.lo: config.h backtrace.h internal.h -xcoff.lo: config.h backtrace.h internal.h - diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.in b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.in deleted file mode 100644 index 498f7fb..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Makefile.in +++ /dev/null @@ -1,1021 +0,0 @@ -# Makefile.in generated by automake 1.11.6 from Makefile.am. -# @configure_input@ - -# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, -# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software -# Foundation, Inc. -# This Makefile.in is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -@SET_MAKE@ - -# Makefile.am -- Backtrace Makefile. -# Copyright (C) 2012-2018 Free Software Foundation, Inc. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# (1) Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. - -# (2) 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. - -# (3) The name of the author may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. - - -VPATH = @srcdir@ -am__make_dryrun = \ - { \ - am__dry=no; \ - case $$MAKEFLAGS in \ - *\\[\ \ ]*) \ - echo 'am--echo: ; @echo "AM" OK' | $(MAKE) -f - 2>/dev/null \ - | grep '^AM OK$$' >/dev/null || am__dry=yes;; \ - *) \ - for am__flg in $$MAKEFLAGS; do \ - case $$am__flg in \ - *=*|--*) ;; \ - *n*) am__dry=yes; break;; \ - esac; \ - done;; \ - esac; \ - test $$am__dry = yes; \ - } -pkgdatadir = $(datadir)/@PACKAGE@ -pkgincludedir = $(includedir)/@PACKAGE@ -pkglibdir = $(libdir)/@PACKAGE@ -pkglibexecdir = $(libexecdir)/@PACKAGE@ -am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd -install_sh_DATA = $(install_sh) -c -m 644 -install_sh_PROGRAM = $(install_sh) -c -install_sh_SCRIPT = $(install_sh) -c -INSTALL_HEADER = $(INSTALL_DATA) -transform = $(program_transform_name) -NORMAL_INSTALL = : -PRE_INSTALL = : -POST_INSTALL = : -NORMAL_UNINSTALL = : -PRE_UNINSTALL = : -POST_UNINSTALL = : -build_triplet = @build@ -host_triplet = @host@ -target_triplet = @target@ -check_PROGRAMS = $(am__EXEEXT_1) $(am__EXEEXT_2) $(am__EXEEXT_3) -@NATIVE_TRUE@am__append_1 = btest btest_static stest ztest edtest -@HAVE_ZLIB_TRUE@@NATIVE_TRUE@am__append_2 = -lz -@NATIVE_TRUE@am__append_3 = edtest2_build.c gen_edtest2_build -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@am__append_4 = ttest -@HAVE_OBJCOPY_DEBUGLINK_TRUE@@NATIVE_TRUE@am__append_5 = dtest -@HAVE_OBJCOPY_DEBUGLINK_TRUE@@NATIVE_TRUE@am__append_6 = dtest btest.debug -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@am__append_7 = ctestg ctesta -subdir = . -DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ - $(top_srcdir)/configure $(am__configure_deps) \ - $(srcdir)/config.h.in $(srcdir)/backtrace-supported.h.in \ - $(include_HEADERS) -ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 -am__aclocal_m4_deps = $(top_srcdir)/config/libtool.m4 \ - $(top_srcdir)/config/ltoptions.m4 \ - $(top_srcdir)/config/ltsugar.m4 \ - $(top_srcdir)/config/ltversion.m4 \ - $(top_srcdir)/config/lt~obsolete.m4 $(top_srcdir)/acinclude.m4 \ - $(top_srcdir)/configure.ac -am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ - $(ACLOCAL_M4) -am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ - configure.lineno config.status.lineno -mkinstalldirs = $(install_sh) -d -CONFIG_HEADER = config.h -CONFIG_CLEAN_FILES = backtrace-supported.h -CONFIG_CLEAN_VPATH_FILES = -am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; -am__vpath_adj = case $$p in \ - $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ - *) f=$$p;; \ - esac; -am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; -am__install_max = 40 -am__nobase_strip_setup = \ - srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` -am__nobase_strip = \ - for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" -am__nobase_list = $(am__nobase_strip_setup); \ - for p in $$list; do echo "$$p $$p"; done | \ - sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ - $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ - if (++n[$$2] == $(am__install_max)) \ - { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ - END { for (dir in files) print dir, files[dir] }' -am__base_list = \ - sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ - sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' -am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ - } -am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" -LTLIBRARIES = $(lib_LTLIBRARIES) -am__DEPENDENCIES_1 = -am_libbacktrace_la_OBJECTS = atomic.lo dwarf.lo fileline.lo posix.lo \ - print.lo sort.lo state.lo -libbacktrace_la_OBJECTS = $(am_libbacktrace_la_OBJECTS) -@NATIVE_TRUE@am__EXEEXT_1 = btest$(EXEEXT) btest_static$(EXEEXT) \ -@NATIVE_TRUE@ stest$(EXEEXT) ztest$(EXEEXT) edtest$(EXEEXT) -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@am__EXEEXT_2 = ttest$(EXEEXT) -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@am__EXEEXT_3 = \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ ctestg$(EXEEXT) \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ ctesta$(EXEEXT) -@NATIVE_TRUE@am_btest_OBJECTS = btest-btest.$(OBJEXT) \ -@NATIVE_TRUE@ btest-testlib.$(OBJEXT) -btest_OBJECTS = $(am_btest_OBJECTS) -@NATIVE_TRUE@btest_DEPENDENCIES = libbacktrace.la -btest_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(btest_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ - $(LDFLAGS) -o $@ -@NATIVE_TRUE@am_btest_static_OBJECTS = btest_static-btest.$(OBJEXT) \ -@NATIVE_TRUE@ btest_static-testlib.$(OBJEXT) -btest_static_OBJECTS = $(am_btest_static_OBJECTS) -@NATIVE_TRUE@btest_static_DEPENDENCIES = libbacktrace.la -btest_static_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ - $(LIBTOOLFLAGS) --mode=link $(CCLD) $(btest_static_CFLAGS) \ - $(CFLAGS) $(btest_static_LDFLAGS) $(LDFLAGS) -o $@ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@am_ctesta_OBJECTS = ctesta-btest.$(OBJEXT) \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ ctesta-testlib.$(OBJEXT) -ctesta_OBJECTS = $(am_ctesta_OBJECTS) -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctesta_DEPENDENCIES = \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ libbacktrace.la -ctesta_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(ctesta_CFLAGS) $(CFLAGS) \ - $(ctesta_LDFLAGS) $(LDFLAGS) -o $@ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@am_ctestg_OBJECTS = ctestg-btest.$(OBJEXT) \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ ctestg-testlib.$(OBJEXT) -ctestg_OBJECTS = $(am_ctestg_OBJECTS) -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctestg_DEPENDENCIES = \ -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ libbacktrace.la -ctestg_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(ctestg_CFLAGS) $(CFLAGS) \ - $(ctestg_LDFLAGS) $(LDFLAGS) -o $@ -@NATIVE_TRUE@am_edtest_OBJECTS = edtest.$(OBJEXT) \ -@NATIVE_TRUE@ edtest2_build.$(OBJEXT) testlib.$(OBJEXT) -edtest_OBJECTS = $(am_edtest_OBJECTS) -@NATIVE_TRUE@edtest_DEPENDENCIES = libbacktrace.la -@NATIVE_TRUE@am_stest_OBJECTS = stest.$(OBJEXT) -stest_OBJECTS = $(am_stest_OBJECTS) -@NATIVE_TRUE@stest_DEPENDENCIES = libbacktrace.la -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@am_ttest_OBJECTS = \ -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ ttest-ttest.$(OBJEXT) \ -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ ttest-testlib.$(OBJEXT) -ttest_OBJECTS = $(am_ttest_OBJECTS) -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ttest_DEPENDENCIES = libbacktrace.la -ttest_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(ttest_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ - $(LDFLAGS) -o $@ -@NATIVE_TRUE@am_ztest_OBJECTS = ztest-ztest.$(OBJEXT) \ -@NATIVE_TRUE@ ztest-testlib.$(OBJEXT) -ztest_OBJECTS = $(am_ztest_OBJECTS) -@NATIVE_TRUE@ztest_DEPENDENCIES = libbacktrace.la \ -@NATIVE_TRUE@ $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) -ztest_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(ztest_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ - $(LDFLAGS) -o $@ -DEFAULT_INCLUDES = -I.@am__isrc@ -depcomp = -am__depfiles_maybe = -COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ - $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ - $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -CCLD = $(CC) -LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ - --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ - $(LDFLAGS) -o $@ -SOURCES = $(libbacktrace_la_SOURCES) $(EXTRA_libbacktrace_la_SOURCES) \ - $(btest_SOURCES) $(btest_static_SOURCES) $(ctesta_SOURCES) \ - $(ctestg_SOURCES) $(edtest_SOURCES) $(stest_SOURCES) \ - $(ttest_SOURCES) $(ztest_SOURCES) -MULTISRCTOP = -MULTIBUILDTOP = -MULTIDIRS = -MULTISUBDIR = -MULTIDO = true -MULTICLEAN = true -am__can_run_installinfo = \ - case $$AM_UPDATE_INFO_DIR in \ - n|no|NO) false;; \ - *) (install-info --version) >/dev/null 2>&1;; \ - esac -HEADERS = $(include_HEADERS) -ETAGS = etags -CTAGS = ctags -am__tty_colors = \ -red=; grn=; lgn=; blu=; std= -ACLOCAL = @ACLOCAL@ -ALLOC_FILE = @ALLOC_FILE@ -AMTAR = @AMTAR@ -AR = @AR@ -AUTOCONF = @AUTOCONF@ -AUTOHEADER = @AUTOHEADER@ -AUTOMAKE = @AUTOMAKE@ -AWK = @AWK@ -BACKTRACE_FILE = @BACKTRACE_FILE@ -BACKTRACE_SUPPORTED = @BACKTRACE_SUPPORTED@ -BACKTRACE_SUPPORTS_DATA = @BACKTRACE_SUPPORTS_DATA@ -BACKTRACE_SUPPORTS_THREADS = @BACKTRACE_SUPPORTS_THREADS@ -BACKTRACE_USES_MALLOC = @BACKTRACE_USES_MALLOC@ -CC = @CC@ -CFLAGS = @CFLAGS@ -CLOCK_GETTIME_LINK = @CLOCK_GETTIME_LINK@ -CPP = @CPP@ -CPPFLAGS = @CPPFLAGS@ -CYGPATH_W = @CYGPATH_W@ -DEFS = @DEFS@ -DSYMUTIL = @DSYMUTIL@ -DUMPBIN = @DUMPBIN@ -ECHO_C = @ECHO_C@ -ECHO_N = @ECHO_N@ -ECHO_T = @ECHO_T@ -EGREP = @EGREP@ -EXEEXT = @EXEEXT@ -EXTRA_FLAGS = @EXTRA_FLAGS@ -FGREP = @FGREP@ -FORMAT_FILE = @FORMAT_FILE@ -GREP = @GREP@ -INSTALL = @INSTALL@ -INSTALL_DATA = @INSTALL_DATA@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ -INSTALL_SCRIPT = @INSTALL_SCRIPT@ -INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ -LD = @LD@ -LDFLAGS = @LDFLAGS@ -LIBOBJS = @LIBOBJS@ -LIBS = @LIBS@ -LIBTOOL = @LIBTOOL@ -LIPO = @LIPO@ -LN_S = @LN_S@ -LTLIBOBJS = @LTLIBOBJS@ -MAINT = @MAINT@ -MAKEINFO = @MAKEINFO@ -MKDIR_P = @MKDIR_P@ -NM = @NM@ -NMEDIT = @NMEDIT@ -OBJCOPY = @OBJCOPY@ -OBJEXT = @OBJEXT@ -OTOOL = @OTOOL@ -OTOOL64 = @OTOOL64@ -PACKAGE = @PACKAGE@ -PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ -PACKAGE_NAME = @PACKAGE_NAME@ -PACKAGE_STRING = @PACKAGE_STRING@ -PACKAGE_TARNAME = @PACKAGE_TARNAME@ -PACKAGE_URL = @PACKAGE_URL@ -PACKAGE_VERSION = @PACKAGE_VERSION@ -PATH_SEPARATOR = @PATH_SEPARATOR@ -PIC_FLAG = @PIC_FLAG@ -PTHREAD_CFLAGS = @PTHREAD_CFLAGS@ -RANLIB = @RANLIB@ -SED = @SED@ -SET_MAKE = @SET_MAKE@ -SHELL = @SHELL@ -STRIP = @STRIP@ -VERSION = @VERSION@ -VIEW_FILE = @VIEW_FILE@ -WARN_FLAGS = @WARN_FLAGS@ -abs_builddir = @abs_builddir@ -abs_srcdir = @abs_srcdir@ -abs_top_builddir = @abs_top_builddir@ -abs_top_srcdir = @abs_top_srcdir@ -ac_ct_CC = @ac_ct_CC@ -ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ -am__leading_dot = @am__leading_dot@ -am__tar = @am__tar@ -am__untar = @am__untar@ -bindir = @bindir@ -build = @build@ -build_alias = @build_alias@ -build_cpu = @build_cpu@ -build_os = @build_os@ -build_vendor = @build_vendor@ -builddir = @builddir@ -datadir = @datadir@ -datarootdir = @datarootdir@ -docdir = @docdir@ -dvidir = @dvidir@ -exec_prefix = @exec_prefix@ -host = @host@ -host_alias = @host_alias@ -host_cpu = @host_cpu@ -host_os = @host_os@ -host_vendor = @host_vendor@ -htmldir = @htmldir@ -includedir = @includedir@ -infodir = @infodir@ -install_sh = @install_sh@ -libdir = @libdir@ -libexecdir = @libexecdir@ -libtool_VERSION = @libtool_VERSION@ -localedir = @localedir@ -localstatedir = @localstatedir@ -lt_ECHO = @lt_ECHO@ -mandir = @mandir@ -mkdir_p = @mkdir_p@ -multi_basedir = @multi_basedir@ -oldincludedir = @oldincludedir@ -pdfdir = @pdfdir@ -prefix = @prefix@ -program_transform_name = @program_transform_name@ -psdir = @psdir@ -sbindir = @sbindir@ -sharedstatedir = @sharedstatedir@ -srcdir = @srcdir@ -sysconfdir = @sysconfdir@ -target = @target@ -target_alias = @target_alias@ -target_cpu = @target_cpu@ -target_os = @target_os@ -target_vendor = @target_vendor@ -top_build_prefix = @top_build_prefix@ -top_builddir = @top_builddir@ -top_srcdir = @top_srcdir@ -ACLOCAL_AMFLAGS = -I config -AM_CFLAGS = $(EXTRA_FLAGS) $(WARN_FLAGS) $(PIC_FLAG) -include_HEADERS = backtrace.h backtrace-supported.h -lib_LTLIBRARIES = libbacktrace.la -libbacktrace_la_SOURCES = \ - backtrace.h \ - atomic.c \ - dwarf.c \ - fileline.c \ - internal.h \ - posix.c \ - print.c \ - sort.c \ - state.c - -BACKTRACE_FILES = \ - backtrace.c \ - simple.c \ - nounwind.c - -FORMAT_FILES = \ - elf.c \ - pecoff.c \ - unknown.c \ - xcoff.c - -VIEW_FILES = \ - read.c \ - mmapio.c - -ALLOC_FILES = \ - alloc.c \ - mmap.c - -EXTRA_libbacktrace_la_SOURCES = \ - $(BACKTRACE_FILES) \ - $(FORMAT_FILES) \ - $(VIEW_FILES) \ - $(ALLOC_FILES) - -libbacktrace_la_LIBADD = \ - $(BACKTRACE_FILE) \ - $(FORMAT_FILE) \ - $(VIEW_FILE) \ - $(ALLOC_FILE) - -libbacktrace_la_DEPENDENCIES = $(libbacktrace_la_LIBADD) -CLEANFILES = $(am__append_3) $(am__append_6) -TESTS = $(check_PROGRAMS) $(am__append_5) -@NATIVE_TRUE@btest_SOURCES = btest.c testlib.c -@NATIVE_TRUE@btest_CFLAGS = $(AM_CFLAGS) -g -O -@NATIVE_TRUE@btest_LDADD = libbacktrace.la -@NATIVE_TRUE@btest_static_SOURCES = btest.c testlib.c -@NATIVE_TRUE@btest_static_CFLAGS = $(AM_CFLAGS) -g -O -@NATIVE_TRUE@btest_static_LDADD = libbacktrace.la -@NATIVE_TRUE@btest_static_LDFLAGS = -static-libtool-libs -@NATIVE_TRUE@stest_SOURCES = stest.c -@NATIVE_TRUE@stest_LDADD = libbacktrace.la -@NATIVE_TRUE@ztest_SOURCES = ztest.c testlib.c -@NATIVE_TRUE@ztest_CFLAGS = -DSRCDIR=\"$(srcdir)\" -@NATIVE_TRUE@ztest_LDADD = libbacktrace.la $(am__append_2) \ -@NATIVE_TRUE@ $(CLOCK_GETTIME_LINK) -@NATIVE_TRUE@edtest_SOURCES = edtest.c edtest2_build.c testlib.c -@NATIVE_TRUE@edtest_LDADD = libbacktrace.la -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ttest_SOURCES = ttest.c testlib.c -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ttest_CFLAGS = $(AM_CFLAGS) -pthread -@HAVE_PTHREAD_TRUE@@NATIVE_TRUE@ttest_LDADD = libbacktrace.la -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctestg_SOURCES = btest.c testlib.c -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctestg_CFLAGS = $(AM_CFLAGS) -g -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctestg_LDFLAGS = -Wl,--compress-debug-sections=zlib-gnu -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctestg_LDADD = libbacktrace.la -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctesta_SOURCES = btest.c testlib.c -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctesta_CFLAGS = $(AM_CFLAGS) -g -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctesta_LDFLAGS = -Wl,--compress-debug-sections=zlib-gabi -@HAVE_COMPRESSED_DEBUG_TRUE@@NATIVE_TRUE@ctesta_LDADD = libbacktrace.la -all: config.h - $(MAKE) $(AM_MAKEFLAGS) all-am - -.SUFFIXES: -.SUFFIXES: .c .lo .o .obj -am--refresh: Makefile - @: -$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) - @for dep in $?; do \ - case '$(am__configure_deps)' in \ - *$$dep*) \ - echo ' cd $(srcdir) && $(AUTOMAKE) --foreign --ignore-deps'; \ - $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign --ignore-deps \ - && exit 0; \ - exit 1;; \ - esac; \ - done; \ - echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign --ignore-deps Makefile'; \ - $(am__cd) $(top_srcdir) && \ - $(AUTOMAKE) --foreign --ignore-deps Makefile -.PRECIOUS: Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status - @case '$?' in \ - *config.status*) \ - echo ' $(SHELL) ./config.status'; \ - $(SHELL) ./config.status;; \ - *) \ - echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ - cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ - esac; - -$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) - $(SHELL) ./config.status --recheck - -$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) - $(am__cd) $(srcdir) && $(AUTOCONF) -$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) - $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) -$(am__aclocal_m4_deps): - -config.h: stamp-h1 - @if test ! -f $@; then rm -f stamp-h1; else :; fi - @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) stamp-h1; else :; fi - -stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status - @rm -f stamp-h1 - cd $(top_builddir) && $(SHELL) ./config.status config.h -$(srcdir)/config.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) - ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) - rm -f stamp-h1 - touch $@ - -distclean-hdr: - -rm -f config.h stamp-h1 -backtrace-supported.h: $(top_builddir)/config.status $(srcdir)/backtrace-supported.h.in - cd $(top_builddir) && $(SHELL) ./config.status $@ -install-libLTLIBRARIES: $(lib_LTLIBRARIES) - @$(NORMAL_INSTALL) - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - list2=; for p in $$list; do \ - if test -f $$p; then \ - list2="$$list2 $$p"; \ - else :; fi; \ - done; \ - test -z "$$list2" || { \ - echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ - $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ - } - -uninstall-libLTLIBRARIES: - @$(NORMAL_UNINSTALL) - @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ - for p in $$list; do \ - $(am__strip_dir) \ - echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ - $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ - done - -clean-libLTLIBRARIES: - -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) - @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ - dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ - test "$$dir" != "$$p" || dir=.; \ - echo "rm -f \"$${dir}/so_locations\""; \ - rm -f "$${dir}/so_locations"; \ - done -libbacktrace.la: $(libbacktrace_la_OBJECTS) $(libbacktrace_la_DEPENDENCIES) $(EXTRA_libbacktrace_la_DEPENDENCIES) - $(LINK) -rpath $(libdir) $(libbacktrace_la_OBJECTS) $(libbacktrace_la_LIBADD) $(LIBS) - -clean-checkPROGRAMS: - @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ - echo " rm -f" $$list; \ - rm -f $$list || exit $$?; \ - test -n "$(EXEEXT)" || exit 0; \ - list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ - echo " rm -f" $$list; \ - rm -f $$list -btest$(EXEEXT): $(btest_OBJECTS) $(btest_DEPENDENCIES) $(EXTRA_btest_DEPENDENCIES) - @rm -f btest$(EXEEXT) - $(btest_LINK) $(btest_OBJECTS) $(btest_LDADD) $(LIBS) -btest_static$(EXEEXT): $(btest_static_OBJECTS) $(btest_static_DEPENDENCIES) $(EXTRA_btest_static_DEPENDENCIES) - @rm -f btest_static$(EXEEXT) - $(btest_static_LINK) $(btest_static_OBJECTS) $(btest_static_LDADD) $(LIBS) -ctesta$(EXEEXT): $(ctesta_OBJECTS) $(ctesta_DEPENDENCIES) $(EXTRA_ctesta_DEPENDENCIES) - @rm -f ctesta$(EXEEXT) - $(ctesta_LINK) $(ctesta_OBJECTS) $(ctesta_LDADD) $(LIBS) -ctestg$(EXEEXT): $(ctestg_OBJECTS) $(ctestg_DEPENDENCIES) $(EXTRA_ctestg_DEPENDENCIES) - @rm -f ctestg$(EXEEXT) - $(ctestg_LINK) $(ctestg_OBJECTS) $(ctestg_LDADD) $(LIBS) -edtest$(EXEEXT): $(edtest_OBJECTS) $(edtest_DEPENDENCIES) $(EXTRA_edtest_DEPENDENCIES) - @rm -f edtest$(EXEEXT) - $(LINK) $(edtest_OBJECTS) $(edtest_LDADD) $(LIBS) -stest$(EXEEXT): $(stest_OBJECTS) $(stest_DEPENDENCIES) $(EXTRA_stest_DEPENDENCIES) - @rm -f stest$(EXEEXT) - $(LINK) $(stest_OBJECTS) $(stest_LDADD) $(LIBS) -ttest$(EXEEXT): $(ttest_OBJECTS) $(ttest_DEPENDENCIES) $(EXTRA_ttest_DEPENDENCIES) - @rm -f ttest$(EXEEXT) - $(ttest_LINK) $(ttest_OBJECTS) $(ttest_LDADD) $(LIBS) -ztest$(EXEEXT): $(ztest_OBJECTS) $(ztest_DEPENDENCIES) $(EXTRA_ztest_DEPENDENCIES) - @rm -f ztest$(EXEEXT) - $(ztest_LINK) $(ztest_OBJECTS) $(ztest_LDADD) $(LIBS) - -mostlyclean-compile: - -rm -f *.$(OBJEXT) - -distclean-compile: - -rm -f *.tab.c - -.c.o: - $(COMPILE) -c $< - -.c.obj: - $(COMPILE) -c `$(CYGPATH_W) '$<'` - -.c.lo: - $(LTCOMPILE) -c -o $@ $< - -btest-btest.o: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_CFLAGS) $(CFLAGS) -c -o btest-btest.o `test -f 'btest.c' || echo '$(srcdir)/'`btest.c - -btest-btest.obj: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_CFLAGS) $(CFLAGS) -c -o btest-btest.obj `if test -f 'btest.c'; then $(CYGPATH_W) 'btest.c'; else $(CYGPATH_W) '$(srcdir)/btest.c'; fi` - -btest-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_CFLAGS) $(CFLAGS) -c -o btest-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -btest-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_CFLAGS) $(CFLAGS) -c -o btest-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -btest_static-btest.o: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_static_CFLAGS) $(CFLAGS) -c -o btest_static-btest.o `test -f 'btest.c' || echo '$(srcdir)/'`btest.c - -btest_static-btest.obj: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_static_CFLAGS) $(CFLAGS) -c -o btest_static-btest.obj `if test -f 'btest.c'; then $(CYGPATH_W) 'btest.c'; else $(CYGPATH_W) '$(srcdir)/btest.c'; fi` - -btest_static-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_static_CFLAGS) $(CFLAGS) -c -o btest_static-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -btest_static-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(btest_static_CFLAGS) $(CFLAGS) -c -o btest_static-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -ctesta-btest.o: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctesta_CFLAGS) $(CFLAGS) -c -o ctesta-btest.o `test -f 'btest.c' || echo '$(srcdir)/'`btest.c - -ctesta-btest.obj: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctesta_CFLAGS) $(CFLAGS) -c -o ctesta-btest.obj `if test -f 'btest.c'; then $(CYGPATH_W) 'btest.c'; else $(CYGPATH_W) '$(srcdir)/btest.c'; fi` - -ctesta-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctesta_CFLAGS) $(CFLAGS) -c -o ctesta-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -ctesta-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctesta_CFLAGS) $(CFLAGS) -c -o ctesta-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -ctestg-btest.o: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctestg_CFLAGS) $(CFLAGS) -c -o ctestg-btest.o `test -f 'btest.c' || echo '$(srcdir)/'`btest.c - -ctestg-btest.obj: btest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctestg_CFLAGS) $(CFLAGS) -c -o ctestg-btest.obj `if test -f 'btest.c'; then $(CYGPATH_W) 'btest.c'; else $(CYGPATH_W) '$(srcdir)/btest.c'; fi` - -ctestg-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctestg_CFLAGS) $(CFLAGS) -c -o ctestg-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -ctestg-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ctestg_CFLAGS) $(CFLAGS) -c -o ctestg-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -ttest-ttest.o: ttest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ttest_CFLAGS) $(CFLAGS) -c -o ttest-ttest.o `test -f 'ttest.c' || echo '$(srcdir)/'`ttest.c - -ttest-ttest.obj: ttest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ttest_CFLAGS) $(CFLAGS) -c -o ttest-ttest.obj `if test -f 'ttest.c'; then $(CYGPATH_W) 'ttest.c'; else $(CYGPATH_W) '$(srcdir)/ttest.c'; fi` - -ttest-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ttest_CFLAGS) $(CFLAGS) -c -o ttest-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -ttest-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ttest_CFLAGS) $(CFLAGS) -c -o ttest-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -ztest-ztest.o: ztest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ztest_CFLAGS) $(CFLAGS) -c -o ztest-ztest.o `test -f 'ztest.c' || echo '$(srcdir)/'`ztest.c - -ztest-ztest.obj: ztest.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ztest_CFLAGS) $(CFLAGS) -c -o ztest-ztest.obj `if test -f 'ztest.c'; then $(CYGPATH_W) 'ztest.c'; else $(CYGPATH_W) '$(srcdir)/ztest.c'; fi` - -ztest-testlib.o: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ztest_CFLAGS) $(CFLAGS) -c -o ztest-testlib.o `test -f 'testlib.c' || echo '$(srcdir)/'`testlib.c - -ztest-testlib.obj: testlib.c - $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(ztest_CFLAGS) $(CFLAGS) -c -o ztest-testlib.obj `if test -f 'testlib.c'; then $(CYGPATH_W) 'testlib.c'; else $(CYGPATH_W) '$(srcdir)/testlib.c'; fi` - -mostlyclean-libtool: - -rm -f *.lo - -clean-libtool: - -rm -rf .libs _libs - -distclean-libtool: - -rm -f libtool config.lt - -# GNU Make needs to see an explicit $(MAKE) variable in the command it -# runs to enable its job server during parallel builds. Hence the -# comments below. -all-multi: - $(MULTIDO) $(AM_MAKEFLAGS) DO=all multi-do # $(MAKE) -install-multi: - $(MULTIDO) $(AM_MAKEFLAGS) DO=install multi-do # $(MAKE) - -mostlyclean-multi: - $(MULTICLEAN) $(AM_MAKEFLAGS) DO=mostlyclean multi-clean # $(MAKE) -clean-multi: - $(MULTICLEAN) $(AM_MAKEFLAGS) DO=clean multi-clean # $(MAKE) -distclean-multi: - $(MULTICLEAN) $(AM_MAKEFLAGS) DO=distclean multi-clean # $(MAKE) -maintainer-clean-multi: - $(MULTICLEAN) $(AM_MAKEFLAGS) DO=maintainer-clean multi-clean # $(MAKE) -install-includeHEADERS: $(include_HEADERS) - @$(NORMAL_INSTALL) - @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ - if test -n "$$list"; then \ - echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ - $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ - fi; \ - for p in $$list; do \ - if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ - echo "$$d$$p"; \ - done | $(am__base_list) | \ - while read files; do \ - echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ - $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ - done - -uninstall-includeHEADERS: - @$(NORMAL_UNINSTALL) - @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ - files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ - dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) - -ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) - list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - mkid -fID $$unique -tags: TAGS - -TAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - set x; \ - here=`pwd`; \ - list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - shift; \ - if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ - test -n "$$unique" || unique=$$empty_fix; \ - if test $$# -gt 0; then \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - "$$@" $$unique; \ - else \ - $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ - $$unique; \ - fi; \ - fi -ctags: CTAGS -CTAGS: $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \ - $(TAGS_FILES) $(LISP) - list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \ - unique=`for i in $$list; do \ - if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ - done | \ - $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ - END { if (nonempty) { for (i in files) print i; }; }'`; \ - test -z "$(CTAGS_ARGS)$$unique" \ - || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ - $$unique - -GTAGS: - here=`$(am__cd) $(top_builddir) && pwd` \ - && $(am__cd) $(top_srcdir) \ - && gtags -i $(GTAGS_ARGS) "$$here" - -distclean-tags: - -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags - -check-TESTS: $(TESTS) - @failed=0; all=0; xfail=0; xpass=0; skip=0; \ - srcdir=$(srcdir); export srcdir; \ - list=' $(TESTS) '; \ - $(am__tty_colors); \ - if test -n "$$list"; then \ - for tst in $$list; do \ - if test -f ./$$tst; then dir=./; \ - elif test -f $$tst; then dir=; \ - else dir="$(srcdir)/"; fi; \ - if $(TESTS_ENVIRONMENT) $${dir}$$tst; then \ - all=`expr $$all + 1`; \ - case " $(XFAIL_TESTS) " in \ - *[\ \ ]$$tst[\ \ ]*) \ - xpass=`expr $$xpass + 1`; \ - failed=`expr $$failed + 1`; \ - col=$$red; res=XPASS; \ - ;; \ - *) \ - col=$$grn; res=PASS; \ - ;; \ - esac; \ - elif test $$? -ne 77; then \ - all=`expr $$all + 1`; \ - case " $(XFAIL_TESTS) " in \ - *[\ \ ]$$tst[\ \ ]*) \ - xfail=`expr $$xfail + 1`; \ - col=$$lgn; res=XFAIL; \ - ;; \ - *) \ - failed=`expr $$failed + 1`; \ - col=$$red; res=FAIL; \ - ;; \ - esac; \ - else \ - skip=`expr $$skip + 1`; \ - col=$$blu; res=SKIP; \ - fi; \ - echo "$${col}$$res$${std}: $$tst"; \ - done; \ - if test "$$all" -eq 1; then \ - tests="test"; \ - All=""; \ - else \ - tests="tests"; \ - All="All "; \ - fi; \ - if test "$$failed" -eq 0; then \ - if test "$$xfail" -eq 0; then \ - banner="$$All$$all $$tests passed"; \ - else \ - if test "$$xfail" -eq 1; then failures=failure; else failures=failures; fi; \ - banner="$$All$$all $$tests behaved as expected ($$xfail expected $$failures)"; \ - fi; \ - else \ - if test "$$xpass" -eq 0; then \ - banner="$$failed of $$all $$tests failed"; \ - else \ - if test "$$xpass" -eq 1; then passes=pass; else passes=passes; fi; \ - banner="$$failed of $$all $$tests did not behave as expected ($$xpass unexpected $$passes)"; \ - fi; \ - fi; \ - dashes="$$banner"; \ - skipped=""; \ - if test "$$skip" -ne 0; then \ - if test "$$skip" -eq 1; then \ - skipped="($$skip test was not run)"; \ - else \ - skipped="($$skip tests were not run)"; \ - fi; \ - test `echo "$$skipped" | wc -c` -le `echo "$$banner" | wc -c` || \ - dashes="$$skipped"; \ - fi; \ - report=""; \ - if test "$$failed" -ne 0 && test -n "$(PACKAGE_BUGREPORT)"; then \ - report="Please report to $(PACKAGE_BUGREPORT)"; \ - test `echo "$$report" | wc -c` -le `echo "$$banner" | wc -c` || \ - dashes="$$report"; \ - fi; \ - dashes=`echo "$$dashes" | sed s/./=/g`; \ - if test "$$failed" -eq 0; then \ - col="$$grn"; \ - else \ - col="$$red"; \ - fi; \ - echo "$${col}$$dashes$${std}"; \ - echo "$${col}$$banner$${std}"; \ - test -z "$$skipped" || echo "$${col}$$skipped$${std}"; \ - test -z "$$report" || echo "$${col}$$report$${std}"; \ - echo "$${col}$$dashes$${std}"; \ - test "$$failed" -eq 0; \ - else :; fi -check-am: all-am - $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) - $(MAKE) $(AM_MAKEFLAGS) check-TESTS -check: check-am -all-am: Makefile $(LTLIBRARIES) all-multi $(HEADERS) config.h -installdirs: - for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ - test -z "$$dir" || $(MKDIR_P) "$$dir"; \ - done -install: install-am -install-exec: install-exec-am -install-data: install-data-am -uninstall: uninstall-am - -install-am: all-am - @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am - -installcheck: installcheck-am -install-strip: - if test -z '$(STRIP)'; then \ - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - install; \ - else \ - $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ - install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ - "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ - fi -mostlyclean-generic: - -clean-generic: - -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) - -distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -maintainer-clean-generic: - @echo "This command is intended for maintainers to use" - @echo "it deletes files that may require special tools to rebuild." -clean: clean-am clean-multi - -clean-am: clean-checkPROGRAMS clean-generic clean-libLTLIBRARIES \ - clean-libtool mostlyclean-am - -distclean: distclean-am distclean-multi - -rm -f $(am__CONFIG_DISTCLEAN_FILES) - -rm -f Makefile -distclean-am: clean-am distclean-compile distclean-generic \ - distclean-hdr distclean-libtool distclean-tags - -dvi: dvi-am - -dvi-am: - -html: html-am - -html-am: - -info: info-am - -info-am: - -install-data-am: install-includeHEADERS - -install-dvi: install-dvi-am - -install-dvi-am: - -install-exec-am: install-libLTLIBRARIES install-multi - -install-html: install-html-am - -install-html-am: - -install-info: install-info-am - -install-info-am: - -install-man: - -install-pdf: install-pdf-am - -install-pdf-am: - -install-ps: install-ps-am - -install-ps-am: - -installcheck-am: - -maintainer-clean: maintainer-clean-am maintainer-clean-multi - -rm -f $(am__CONFIG_DISTCLEAN_FILES) - -rm -rf $(top_srcdir)/autom4te.cache - -rm -f Makefile -maintainer-clean-am: distclean-am maintainer-clean-generic - -mostlyclean: mostlyclean-am mostlyclean-multi - -mostlyclean-am: mostlyclean-compile mostlyclean-generic \ - mostlyclean-libtool - -pdf: pdf-am - -pdf-am: - -ps: ps-am - -ps-am: - -uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES - -.MAKE: all all-multi check-am clean-multi distclean-multi install-am \ - install-multi install-strip maintainer-clean-multi \ - mostlyclean-multi - -.PHONY: CTAGS GTAGS all all-am all-multi am--refresh check check-TESTS \ - check-am clean clean-checkPROGRAMS clean-generic \ - clean-libLTLIBRARIES clean-libtool clean-multi ctags distclean \ - distclean-compile distclean-generic distclean-hdr \ - distclean-libtool distclean-multi distclean-tags dvi dvi-am \ - html html-am info info-am install install-am install-data \ - install-data-am install-dvi install-dvi-am install-exec \ - install-exec-am install-html install-html-am \ - install-includeHEADERS install-info install-info-am \ - install-libLTLIBRARIES install-man install-multi install-pdf \ - install-pdf-am install-ps install-ps-am install-strip \ - installcheck installcheck-am installdirs maintainer-clean \ - maintainer-clean-generic maintainer-clean-multi mostlyclean \ - mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ - mostlyclean-multi pdf pdf-am ps ps-am tags uninstall \ - uninstall-am uninstall-includeHEADERS uninstall-libLTLIBRARIES - - -@NATIVE_TRUE@edtest2_build.c: gen_edtest2_build; @true -@NATIVE_TRUE@gen_edtest2_build: $(srcdir)/edtest2.c -@NATIVE_TRUE@ cat $(srcdir)/edtest2.c > tmp-edtest2_build.c -@NATIVE_TRUE@ $(SHELL) $(srcdir)/move-if-change tmp-edtest2_build.c edtest2_build.c -@NATIVE_TRUE@ echo timestamp > $@ - -@HAVE_OBJCOPY_DEBUGLINK_TRUE@@NATIVE_TRUE@dtest: btest_static -@HAVE_OBJCOPY_DEBUGLINK_TRUE@@NATIVE_TRUE@ $(OBJCOPY) --only-keep-debug btest_static btest.debug -@HAVE_OBJCOPY_DEBUGLINK_TRUE@@NATIVE_TRUE@ $(OBJCOPY) --strip-debug --add-gnu-debuglink=btest.debug btest_static dtest - -# We can't use automake's automatic dependency tracking, because it -# breaks when using bootstrap-lean. Automatic dependency tracking -# with GCC bootstrap will cause some of the objects to depend on -# header files in prev-gcc/include, e.g., stddef.h and stdarg.h. When -# using bootstrap-lean, prev-gcc is removed after each stage. When -# running "make install", those header files will be gone, causing the -# library to be rebuilt at install time. That may not succeed. - -# These manual dependencies do not include dependencies on unwind.h, -# even though that is part of GCC, because where to find it depends on -# whether we are being built as a host library or a target library. - -alloc.lo: config.h backtrace.h internal.h -backtrace.lo: config.h backtrace.h internal.h -btest.lo: backtrace.h backtrace-supported.h filenames.h -dwarf.lo: config.h filenames.h backtrace.h internal.h -elf.lo: config.h backtrace.h internal.h -fileline.lo: config.h backtrace.h internal.h -mmap.lo: config.h backtrace.h internal.h -mmapio.lo: config.h backtrace.h internal.h -nounwind.lo: config.h internal.h -pecoff.lo: config.h backtrace.h internal.h -posix.lo: config.h backtrace.h internal.h -print.lo: config.h backtrace.h internal.h -read.lo: config.h backtrace.h internal.h -simple.lo: config.h backtrace.h internal.h -sort.lo: config.h backtrace.h internal.h -stest.lo: config.h backtrace.h internal.h -state.lo: config.h backtrace.h backtrace-supported.h internal.h -unknown.lo: config.h backtrace.h internal.h -xcoff.lo: config.h backtrace.h internal.h - -# Tell versions [3.59,3.63) of GNU make to not export all variables. -# Otherwise a system limit (for SysV at least) may be exceeded. -.NOEXPORT: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Mark.Twain-Tom.Sawyer.txt b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Mark.Twain-Tom.Sawyer.txt deleted file mode 100644 index c9106fd..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/Mark.Twain-Tom.Sawyer.txt +++ /dev/null @@ -1,8465 +0,0 @@ -Produced by David Widger. The previous edition was updated by Jose -Menendez. - - - - - - THE ADVENTURES OF TOM SAWYER - BY - MARK TWAIN - (Samuel Langhorne Clemens) - - - - - P R E F A C E - -MOST of the adventures recorded in this book really occurred; one or -two were experiences of my own, the rest those of boys who were -schoolmates of mine. Huck Finn is drawn from life; Tom Sawyer also, but -not from an individual--he is a combination of the characteristics of -three boys whom I knew, and therefore belongs to the composite order of -architecture. - -The odd superstitions touched upon were all prevalent among children -and slaves in the West at the period of this story--that is to say, -thirty or forty years ago. - -Although my book is intended mainly for the entertainment of boys and -girls, I hope it will not be shunned by men and women on that account, -for part of my plan has been to try to pleasantly remind adults of what -they once were themselves, and of how they felt and thought and talked, -and what queer enterprises they sometimes engaged in. - - THE AUTHOR. - -HARTFORD, 1876. - - - - T O M S A W Y E R - - - -CHAPTER I - -"TOM!" - -No answer. - -"TOM!" - -No answer. - -"What's gone with that boy, I wonder? You TOM!" - -No answer. - -The old lady pulled her spectacles down and looked over them about the -room; then she put them up and looked out under them. She seldom or -never looked THROUGH them for so small a thing as a boy; they were her -state pair, the pride of her heart, and were built for "style," not -service--she could have seen through a pair of stove-lids just as well. -She looked perplexed for a moment, and then said, not fiercely, but -still loud enough for the furniture to hear: - -"Well, I lay if I get hold of you I'll--" - -She did not finish, for by this time she was bending down and punching -under the bed with the broom, and so she needed breath to punctuate the -punches with. She resurrected nothing but the cat. - -"I never did see the beat of that boy!" - -She went to the open door and stood in it and looked out among the -tomato vines and "jimpson" weeds that constituted the garden. No Tom. -So she lifted up her voice at an angle calculated for distance and -shouted: - -"Y-o-u-u TOM!" - -There was a slight noise behind her and she turned just in time to -seize a small boy by the slack of his roundabout and arrest his flight. - -"There! I might 'a' thought of that closet. What you been doing in -there?" - -"Nothing." - -"Nothing! Look at your hands. And look at your mouth. What IS that -truck?" - -"I don't know, aunt." - -"Well, I know. It's jam--that's what it is. Forty times I've said if -you didn't let that jam alone I'd skin you. Hand me that switch." - -The switch hovered in the air--the peril was desperate-- - -"My! Look behind you, aunt!" - -The old lady whirled round, and snatched her skirts out of danger. The -lad fled on the instant, scrambled up the high board-fence, and -disappeared over it. - -His aunt Polly stood surprised a moment, and then broke into a gentle -laugh. - -"Hang the boy, can't I never learn anything? Ain't he played me tricks -enough like that for me to be looking out for him by this time? But old -fools is the biggest fools there is. Can't learn an old dog new tricks, -as the saying is. But my goodness, he never plays them alike, two days, -and how is a body to know what's coming? He 'pears to know just how -long he can torment me before I get my dander up, and he knows if he -can make out to put me off for a minute or make me laugh, it's all down -again and I can't hit him a lick. I ain't doing my duty by that boy, -and that's the Lord's truth, goodness knows. Spare the rod and spile -the child, as the Good Book says. I'm a laying up sin and suffering for -us both, I know. He's full of the Old Scratch, but laws-a-me! he's my -own dead sister's boy, poor thing, and I ain't got the heart to lash -him, somehow. Every time I let him off, my conscience does hurt me so, -and every time I hit him my old heart most breaks. Well-a-well, man -that is born of woman is of few days and full of trouble, as the -Scripture says, and I reckon it's so. He'll play hookey this evening, * -and [* Southwestern for "afternoon"] I'll just be obleeged to make him -work, to-morrow, to punish him. It's mighty hard to make him work -Saturdays, when all the boys is having holiday, but he hates work more -than he hates anything else, and I've GOT to do some of my duty by him, -or I'll be the ruination of the child." - -Tom did play hookey, and he had a very good time. He got back home -barely in season to help Jim, the small colored boy, saw next-day's -wood and split the kindlings before supper--at least he was there in -time to tell his adventures to Jim while Jim did three-fourths of the -work. Tom's younger brother (or rather half-brother) Sid was already -through with his part of the work (picking up chips), for he was a -quiet boy, and had no adventurous, troublesome ways. - -While Tom was eating his supper, and stealing sugar as opportunity -offered, Aunt Polly asked him questions that were full of guile, and -very deep--for she wanted to trap him into damaging revealments. Like -many other simple-hearted souls, it was her pet vanity to believe she -was endowed with a talent for dark and mysterious diplomacy, and she -loved to contemplate her most transparent devices as marvels of low -cunning. Said she: - -"Tom, it was middling warm in school, warn't it?" - -"Yes'm." - -"Powerful warm, warn't it?" - -"Yes'm." - -"Didn't you want to go in a-swimming, Tom?" - -A bit of a scare shot through Tom--a touch of uncomfortable suspicion. -He searched Aunt Polly's face, but it told him nothing. So he said: - -"No'm--well, not very much." - -The old lady reached out her hand and felt Tom's shirt, and said: - -"But you ain't too warm now, though." And it flattered her to reflect -that she had discovered that the shirt was dry without anybody knowing -that that was what she had in her mind. But in spite of her, Tom knew -where the wind lay, now. So he forestalled what might be the next move: - -"Some of us pumped on our heads--mine's damp yet. See?" - -Aunt Polly was vexed to think she had overlooked that bit of -circumstantial evidence, and missed a trick. Then she had a new -inspiration: - -"Tom, you didn't have to undo your shirt collar where I sewed it, to -pump on your head, did you? Unbutton your jacket!" - -The trouble vanished out of Tom's face. He opened his jacket. His -shirt collar was securely sewed. - -"Bother! Well, go 'long with you. I'd made sure you'd played hookey -and been a-swimming. But I forgive ye, Tom. I reckon you're a kind of a -singed cat, as the saying is--better'n you look. THIS time." - -She was half sorry her sagacity had miscarried, and half glad that Tom -had stumbled into obedient conduct for once. - -But Sidney said: - -"Well, now, if I didn't think you sewed his collar with white thread, -but it's black." - -"Why, I did sew it with white! Tom!" - -But Tom did not wait for the rest. As he went out at the door he said: - -"Siddy, I'll lick you for that." - -In a safe place Tom examined two large needles which were thrust into -the lapels of his jacket, and had thread bound about them--one needle -carried white thread and the other black. He said: - -"She'd never noticed if it hadn't been for Sid. Confound it! sometimes -she sews it with white, and sometimes she sews it with black. I wish to -geeminy she'd stick to one or t'other--I can't keep the run of 'em. But -I bet you I'll lam Sid for that. I'll learn him!" - -He was not the Model Boy of the village. He knew the model boy very -well though--and loathed him. - -Within two minutes, or even less, he had forgotten all his troubles. -Not because his troubles were one whit less heavy and bitter to him -than a man's are to a man, but because a new and powerful interest bore -them down and drove them out of his mind for the time--just as men's -misfortunes are forgotten in the excitement of new enterprises. This -new interest was a valued novelty in whistling, which he had just -acquired from a negro, and he was suffering to practise it undisturbed. -It consisted in a peculiar bird-like turn, a sort of liquid warble, -produced by touching the tongue to the roof of the mouth at short -intervals in the midst of the music--the reader probably remembers how -to do it, if he has ever been a boy. Diligence and attention soon gave -him the knack of it, and he strode down the street with his mouth full -of harmony and his soul full of gratitude. He felt much as an -astronomer feels who has discovered a new planet--no doubt, as far as -strong, deep, unalloyed pleasure is concerned, the advantage was with -the boy, not the astronomer. - -The summer evenings were long. It was not dark, yet. Presently Tom -checked his whistle. A stranger was before him--a boy a shade larger -than himself. A new-comer of any age or either sex was an impressive -curiosity in the poor little shabby village of St. Petersburg. This boy -was well dressed, too--well dressed on a week-day. This was simply -astounding. His cap was a dainty thing, his close-buttoned blue cloth -roundabout was new and natty, and so were his pantaloons. He had shoes -on--and it was only Friday. He even wore a necktie, a bright bit of -ribbon. He had a citified air about him that ate into Tom's vitals. The -more Tom stared at the splendid marvel, the higher he turned up his -nose at his finery and the shabbier and shabbier his own outfit seemed -to him to grow. Neither boy spoke. If one moved, the other moved--but -only sidewise, in a circle; they kept face to face and eye to eye all -the time. Finally Tom said: - -"I can lick you!" - -"I'd like to see you try it." - -"Well, I can do it." - -"No you can't, either." - -"Yes I can." - -"No you can't." - -"I can." - -"You can't." - -"Can!" - -"Can't!" - -An uncomfortable pause. Then Tom said: - -"What's your name?" - -"'Tisn't any of your business, maybe." - -"Well I 'low I'll MAKE it my business." - -"Well why don't you?" - -"If you say much, I will." - -"Much--much--MUCH. There now." - -"Oh, you think you're mighty smart, DON'T you? I could lick you with -one hand tied behind me, if I wanted to." - -"Well why don't you DO it? You SAY you can do it." - -"Well I WILL, if you fool with me." - -"Oh yes--I've seen whole families in the same fix." - -"Smarty! You think you're SOME, now, DON'T you? Oh, what a hat!" - -"You can lump that hat if you don't like it. I dare you to knock it -off--and anybody that'll take a dare will suck eggs." - -"You're a liar!" - -"You're another." - -"You're a fighting liar and dasn't take it up." - -"Aw--take a walk!" - -"Say--if you give me much more of your sass I'll take and bounce a -rock off'n your head." - -"Oh, of COURSE you will." - -"Well I WILL." - -"Well why don't you DO it then? What do you keep SAYING you will for? -Why don't you DO it? It's because you're afraid." - -"I AIN'T afraid." - -"You are." - -"I ain't." - -"You are." - -Another pause, and more eying and sidling around each other. Presently -they were shoulder to shoulder. Tom said: - -"Get away from here!" - -"Go away yourself!" - -"I won't." - -"I won't either." - -So they stood, each with a foot placed at an angle as a brace, and -both shoving with might and main, and glowering at each other with -hate. But neither could get an advantage. After struggling till both -were hot and flushed, each relaxed his strain with watchful caution, -and Tom said: - -"You're a coward and a pup. I'll tell my big brother on you, and he -can thrash you with his little finger, and I'll make him do it, too." - -"What do I care for your big brother? I've got a brother that's bigger -than he is--and what's more, he can throw him over that fence, too." -[Both brothers were imaginary.] - -"That's a lie." - -"YOUR saying so don't make it so." - -Tom drew a line in the dust with his big toe, and said: - -"I dare you to step over that, and I'll lick you till you can't stand -up. Anybody that'll take a dare will steal sheep." - -The new boy stepped over promptly, and said: - -"Now you said you'd do it, now let's see you do it." - -"Don't you crowd me now; you better look out." - -"Well, you SAID you'd do it--why don't you do it?" - -"By jingo! for two cents I WILL do it." - -The new boy took two broad coppers out of his pocket and held them out -with derision. Tom struck them to the ground. In an instant both boys -were rolling and tumbling in the dirt, gripped together like cats; and -for the space of a minute they tugged and tore at each other's hair and -clothes, punched and scratched each other's nose, and covered -themselves with dust and glory. Presently the confusion took form, and -through the fog of battle Tom appeared, seated astride the new boy, and -pounding him with his fists. "Holler 'nuff!" said he. - -The boy only struggled to free himself. He was crying--mainly from rage. - -"Holler 'nuff!"--and the pounding went on. - -At last the stranger got out a smothered "'Nuff!" and Tom let him up -and said: - -"Now that'll learn you. Better look out who you're fooling with next -time." - -The new boy went off brushing the dust from his clothes, sobbing, -snuffling, and occasionally looking back and shaking his head and -threatening what he would do to Tom the "next time he caught him out." -To which Tom responded with jeers, and started off in high feather, and -as soon as his back was turned the new boy snatched up a stone, threw -it and hit him between the shoulders and then turned tail and ran like -an antelope. Tom chased the traitor home, and thus found out where he -lived. He then held a position at the gate for some time, daring the -enemy to come outside, but the enemy only made faces at him through the -window and declined. At last the enemy's mother appeared, and called -Tom a bad, vicious, vulgar child, and ordered him away. So he went -away; but he said he "'lowed" to "lay" for that boy. - -He got home pretty late that night, and when he climbed cautiously in -at the window, he uncovered an ambuscade, in the person of his aunt; -and when she saw the state his clothes were in her resolution to turn -his Saturday holiday into captivity at hard labor became adamantine in -its firmness. - - - -CHAPTER II - -SATURDAY morning was come, and all the summer world was bright and -fresh, and brimming with life. There was a song in every heart; and if -the heart was young the music issued at the lips. There was cheer in -every face and a spring in every step. The locust-trees were in bloom -and the fragrance of the blossoms filled the air. Cardiff Hill, beyond -the village and above it, was green with vegetation and it lay just far -enough away to seem a Delectable Land, dreamy, reposeful, and inviting. - -Tom appeared on the sidewalk with a bucket of whitewash and a -long-handled brush. He surveyed the fence, and all gladness left him and -a deep melancholy settled down upon his spirit. Thirty yards of board -fence nine feet high. Life to him seemed hollow, and existence but a -burden. Sighing, he dipped his brush and passed it along the topmost -plank; repeated the operation; did it again; compared the insignificant -whitewashed streak with the far-reaching continent of unwhitewashed -fence, and sat down on a tree-box discouraged. Jim came skipping out at -the gate with a tin pail, and singing Buffalo Gals. Bringing water from -the town pump had always been hateful work in Tom's eyes, before, but -now it did not strike him so. He remembered that there was company at -the pump. White, mulatto, and negro boys and girls were always there -waiting their turns, resting, trading playthings, quarrelling, -fighting, skylarking. And he remembered that although the pump was only -a hundred and fifty yards off, Jim never got back with a bucket of -water under an hour--and even then somebody generally had to go after -him. Tom said: - -"Say, Jim, I'll fetch the water if you'll whitewash some." - -Jim shook his head and said: - -"Can't, Mars Tom. Ole missis, she tole me I got to go an' git dis -water an' not stop foolin' roun' wid anybody. She say she spec' Mars -Tom gwine to ax me to whitewash, an' so she tole me go 'long an' 'tend -to my own business--she 'lowed SHE'D 'tend to de whitewashin'." - -"Oh, never you mind what she said, Jim. That's the way she always -talks. Gimme the bucket--I won't be gone only a a minute. SHE won't -ever know." - -"Oh, I dasn't, Mars Tom. Ole missis she'd take an' tar de head off'n -me. 'Deed she would." - -"SHE! She never licks anybody--whacks 'em over the head with her -thimble--and who cares for that, I'd like to know. She talks awful, but -talk don't hurt--anyways it don't if she don't cry. Jim, I'll give you -a marvel. I'll give you a white alley!" - -Jim began to waver. - -"White alley, Jim! And it's a bully taw." - -"My! Dat's a mighty gay marvel, I tell you! But Mars Tom I's powerful -'fraid ole missis--" - -"And besides, if you will I'll show you my sore toe." - -Jim was only human--this attraction was too much for him. He put down -his pail, took the white alley, and bent over the toe with absorbing -interest while the bandage was being unwound. In another moment he was -flying down the street with his pail and a tingling rear, Tom was -whitewashing with vigor, and Aunt Polly was retiring from the field -with a slipper in her hand and triumph in her eye. - -But Tom's energy did not last. He began to think of the fun he had -planned for this day, and his sorrows multiplied. Soon the free boys -would come tripping along on all sorts of delicious expeditions, and -they would make a world of fun of him for having to work--the very -thought of it burnt him like fire. He got out his worldly wealth and -examined it--bits of toys, marbles, and trash; enough to buy an -exchange of WORK, maybe, but not half enough to buy so much as half an -hour of pure freedom. So he returned his straitened means to his -pocket, and gave up the idea of trying to buy the boys. At this dark -and hopeless moment an inspiration burst upon him! Nothing less than a -great, magnificent inspiration. - -He took up his brush and went tranquilly to work. Ben Rogers hove in -sight presently--the very boy, of all boys, whose ridicule he had been -dreading. Ben's gait was the hop-skip-and-jump--proof enough that his -heart was light and his anticipations high. He was eating an apple, and -giving a long, melodious whoop, at intervals, followed by a deep-toned -ding-dong-dong, ding-dong-dong, for he was personating a steamboat. As -he drew near, he slackened speed, took the middle of the street, leaned -far over to starboard and rounded to ponderously and with laborious -pomp and circumstance--for he was personating the Big Missouri, and -considered himself to be drawing nine feet of water. He was boat and -captain and engine-bells combined, so he had to imagine himself -standing on his own hurricane-deck giving the orders and executing them: - -"Stop her, sir! Ting-a-ling-ling!" The headway ran almost out, and he -drew up slowly toward the sidewalk. - -"Ship up to back! Ting-a-ling-ling!" His arms straightened and -stiffened down his sides. - -"Set her back on the stabboard! Ting-a-ling-ling! Chow! ch-chow-wow! -Chow!" His right hand, meantime, describing stately circles--for it was -representing a forty-foot wheel. - -"Let her go back on the labboard! Ting-a-lingling! Chow-ch-chow-chow!" -The left hand began to describe circles. - -"Stop the stabboard! Ting-a-ling-ling! Stop the labboard! Come ahead -on the stabboard! Stop her! Let your outside turn over slow! -Ting-a-ling-ling! Chow-ow-ow! Get out that head-line! LIVELY now! -Come--out with your spring-line--what're you about there! Take a turn -round that stump with the bight of it! Stand by that stage, now--let her -go! Done with the engines, sir! Ting-a-ling-ling! SH'T! S'H'T! SH'T!" -(trying the gauge-cocks). - -Tom went on whitewashing--paid no attention to the steamboat. Ben -stared a moment and then said: "Hi-YI! YOU'RE up a stump, ain't you!" - -No answer. Tom surveyed his last touch with the eye of an artist, then -he gave his brush another gentle sweep and surveyed the result, as -before. Ben ranged up alongside of him. Tom's mouth watered for the -apple, but he stuck to his work. Ben said: - -"Hello, old chap, you got to work, hey?" - -Tom wheeled suddenly and said: - -"Why, it's you, Ben! I warn't noticing." - -"Say--I'm going in a-swimming, I am. Don't you wish you could? But of -course you'd druther WORK--wouldn't you? Course you would!" - -Tom contemplated the boy a bit, and said: - -"What do you call work?" - -"Why, ain't THAT work?" - -Tom resumed his whitewashing, and answered carelessly: - -"Well, maybe it is, and maybe it ain't. All I know, is, it suits Tom -Sawyer." - -"Oh come, now, you don't mean to let on that you LIKE it?" - -The brush continued to move. - -"Like it? Well, I don't see why I oughtn't to like it. Does a boy get -a chance to whitewash a fence every day?" - -That put the thing in a new light. Ben stopped nibbling his apple. Tom -swept his brush daintily back and forth--stepped back to note the -effect--added a touch here and there--criticised the effect again--Ben -watching every move and getting more and more interested, more and more -absorbed. Presently he said: - -"Say, Tom, let ME whitewash a little." - -Tom considered, was about to consent; but he altered his mind: - -"No--no--I reckon it wouldn't hardly do, Ben. You see, Aunt Polly's -awful particular about this fence--right here on the street, you know ---but if it was the back fence I wouldn't mind and SHE wouldn't. Yes, -she's awful particular about this fence; it's got to be done very -careful; I reckon there ain't one boy in a thousand, maybe two -thousand, that can do it the way it's got to be done." - -"No--is that so? Oh come, now--lemme just try. Only just a little--I'd -let YOU, if you was me, Tom." - -"Ben, I'd like to, honest injun; but Aunt Polly--well, Jim wanted to -do it, but she wouldn't let him; Sid wanted to do it, and she wouldn't -let Sid. Now don't you see how I'm fixed? If you was to tackle this -fence and anything was to happen to it--" - -"Oh, shucks, I'll be just as careful. Now lemme try. Say--I'll give -you the core of my apple." - -"Well, here--No, Ben, now don't. I'm afeard--" - -"I'll give you ALL of it!" - -Tom gave up the brush with reluctance in his face, but alacrity in his -heart. And while the late steamer Big Missouri worked and sweated in -the sun, the retired artist sat on a barrel in the shade close by, -dangled his legs, munched his apple, and planned the slaughter of more -innocents. There was no lack of material; boys happened along every -little while; they came to jeer, but remained to whitewash. By the time -Ben was fagged out, Tom had traded the next chance to Billy Fisher for -a kite, in good repair; and when he played out, Johnny Miller bought in -for a dead rat and a string to swing it with--and so on, and so on, -hour after hour. And when the middle of the afternoon came, from being -a poor poverty-stricken boy in the morning, Tom was literally rolling -in wealth. He had besides the things before mentioned, twelve marbles, -part of a jews-harp, a piece of blue bottle-glass to look through, a -spool cannon, a key that wouldn't unlock anything, a fragment of chalk, -a glass stopper of a decanter, a tin soldier, a couple of tadpoles, six -fire-crackers, a kitten with only one eye, a brass doorknob, a -dog-collar--but no dog--the handle of a knife, four pieces of -orange-peel, and a dilapidated old window sash. - -He had had a nice, good, idle time all the while--plenty of company ---and the fence had three coats of whitewash on it! If he hadn't run out -of whitewash he would have bankrupted every boy in the village. - -Tom said to himself that it was not such a hollow world, after all. He -had discovered a great law of human action, without knowing it--namely, -that in order to make a man or a boy covet a thing, it is only -necessary to make the thing difficult to attain. If he had been a great -and wise philosopher, like the writer of this book, he would now have -comprehended that Work consists of whatever a body is OBLIGED to do, -and that Play consists of whatever a body is not obliged to do. And -this would help him to understand why constructing artificial flowers -or performing on a tread-mill is work, while rolling ten-pins or -climbing Mont Blanc is only amusement. There are wealthy gentlemen in -England who drive four-horse passenger-coaches twenty or thirty miles -on a daily line, in the summer, because the privilege costs them -considerable money; but if they were offered wages for the service, -that would turn it into work and then they would resign. - -The boy mused awhile over the substantial change which had taken place -in his worldly circumstances, and then wended toward headquarters to -report. - - - -CHAPTER III - -TOM presented himself before Aunt Polly, who was sitting by an open -window in a pleasant rearward apartment, which was bedroom, -breakfast-room, dining-room, and library, combined. The balmy summer -air, the restful quiet, the odor of the flowers, and the drowsing murmur -of the bees had had their effect, and she was nodding over her knitting ---for she had no company but the cat, and it was asleep in her lap. Her -spectacles were propped up on her gray head for safety. She had thought -that of course Tom had deserted long ago, and she wondered at seeing him -place himself in her power again in this intrepid way. He said: "Mayn't -I go and play now, aunt?" - -"What, a'ready? How much have you done?" - -"It's all done, aunt." - -"Tom, don't lie to me--I can't bear it." - -"I ain't, aunt; it IS all done." - -Aunt Polly placed small trust in such evidence. She went out to see -for herself; and she would have been content to find twenty per cent. -of Tom's statement true. When she found the entire fence whitewashed, -and not only whitewashed but elaborately coated and recoated, and even -a streak added to the ground, her astonishment was almost unspeakable. -She said: - -"Well, I never! There's no getting round it, you can work when you're -a mind to, Tom." And then she diluted the compliment by adding, "But -it's powerful seldom you're a mind to, I'm bound to say. Well, go 'long -and play; but mind you get back some time in a week, or I'll tan you." - -She was so overcome by the splendor of his achievement that she took -him into the closet and selected a choice apple and delivered it to -him, along with an improving lecture upon the added value and flavor a -treat took to itself when it came without sin through virtuous effort. -And while she closed with a happy Scriptural flourish, he "hooked" a -doughnut. - -Then he skipped out, and saw Sid just starting up the outside stairway -that led to the back rooms on the second floor. Clods were handy and -the air was full of them in a twinkling. They raged around Sid like a -hail-storm; and before Aunt Polly could collect her surprised faculties -and sally to the rescue, six or seven clods had taken personal effect, -and Tom was over the fence and gone. There was a gate, but as a general -thing he was too crowded for time to make use of it. His soul was at -peace, now that he had settled with Sid for calling attention to his -black thread and getting him into trouble. - -Tom skirted the block, and came round into a muddy alley that led by -the back of his aunt's cow-stable. He presently got safely beyond the -reach of capture and punishment, and hastened toward the public square -of the village, where two "military" companies of boys had met for -conflict, according to previous appointment. Tom was General of one of -these armies, Joe Harper (a bosom friend) General of the other. These -two great commanders did not condescend to fight in person--that being -better suited to the still smaller fry--but sat together on an eminence -and conducted the field operations by orders delivered through -aides-de-camp. Tom's army won a great victory, after a long and -hard-fought battle. Then the dead were counted, prisoners exchanged, -the terms of the next disagreement agreed upon, and the day for the -necessary battle appointed; after which the armies fell into line and -marched away, and Tom turned homeward alone. - -As he was passing by the house where Jeff Thatcher lived, he saw a new -girl in the garden--a lovely little blue-eyed creature with yellow hair -plaited into two long-tails, white summer frock and embroidered -pantalettes. The fresh-crowned hero fell without firing a shot. A -certain Amy Lawrence vanished out of his heart and left not even a -memory of herself behind. He had thought he loved her to distraction; -he had regarded his passion as adoration; and behold it was only a poor -little evanescent partiality. He had been months winning her; she had -confessed hardly a week ago; he had been the happiest and the proudest -boy in the world only seven short days, and here in one instant of time -she had gone out of his heart like a casual stranger whose visit is -done. - -He worshipped this new angel with furtive eye, till he saw that she -had discovered him; then he pretended he did not know she was present, -and began to "show off" in all sorts of absurd boyish ways, in order to -win her admiration. He kept up this grotesque foolishness for some -time; but by-and-by, while he was in the midst of some dangerous -gymnastic performances, he glanced aside and saw that the little girl -was wending her way toward the house. Tom came up to the fence and -leaned on it, grieving, and hoping she would tarry yet awhile longer. -She halted a moment on the steps and then moved toward the door. Tom -heaved a great sigh as she put her foot on the threshold. But his face -lit up, right away, for she tossed a pansy over the fence a moment -before she disappeared. - -The boy ran around and stopped within a foot or two of the flower, and -then shaded his eyes with his hand and began to look down street as if -he had discovered something of interest going on in that direction. -Presently he picked up a straw and began trying to balance it on his -nose, with his head tilted far back; and as he moved from side to side, -in his efforts, he edged nearer and nearer toward the pansy; finally -his bare foot rested upon it, his pliant toes closed upon it, and he -hopped away with the treasure and disappeared round the corner. But -only for a minute--only while he could button the flower inside his -jacket, next his heart--or next his stomach, possibly, for he was not -much posted in anatomy, and not hypercritical, anyway. - -He returned, now, and hung about the fence till nightfall, "showing -off," as before; but the girl never exhibited herself again, though Tom -comforted himself a little with the hope that she had been near some -window, meantime, and been aware of his attentions. Finally he strode -home reluctantly, with his poor head full of visions. - -All through supper his spirits were so high that his aunt wondered -"what had got into the child." He took a good scolding about clodding -Sid, and did not seem to mind it in the least. He tried to steal sugar -under his aunt's very nose, and got his knuckles rapped for it. He said: - -"Aunt, you don't whack Sid when he takes it." - -"Well, Sid don't torment a body the way you do. You'd be always into -that sugar if I warn't watching you." - -Presently she stepped into the kitchen, and Sid, happy in his -immunity, reached for the sugar-bowl--a sort of glorying over Tom which -was wellnigh unbearable. But Sid's fingers slipped and the bowl dropped -and broke. Tom was in ecstasies. In such ecstasies that he even -controlled his tongue and was silent. He said to himself that he would -not speak a word, even when his aunt came in, but would sit perfectly -still till she asked who did the mischief; and then he would tell, and -there would be nothing so good in the world as to see that pet model -"catch it." He was so brimful of exultation that he could hardly hold -himself when the old lady came back and stood above the wreck -discharging lightnings of wrath from over her spectacles. He said to -himself, "Now it's coming!" And the next instant he was sprawling on -the floor! The potent palm was uplifted to strike again when Tom cried -out: - -"Hold on, now, what 'er you belting ME for?--Sid broke it!" - -Aunt Polly paused, perplexed, and Tom looked for healing pity. But -when she got her tongue again, she only said: - -"Umf! Well, you didn't get a lick amiss, I reckon. You been into some -other audacious mischief when I wasn't around, like enough." - -Then her conscience reproached her, and she yearned to say something -kind and loving; but she judged that this would be construed into a -confession that she had been in the wrong, and discipline forbade that. -So she kept silence, and went about her affairs with a troubled heart. -Tom sulked in a corner and exalted his woes. He knew that in her heart -his aunt was on her knees to him, and he was morosely gratified by the -consciousness of it. He would hang out no signals, he would take notice -of none. He knew that a yearning glance fell upon him, now and then, -through a film of tears, but he refused recognition of it. He pictured -himself lying sick unto death and his aunt bending over him beseeching -one little forgiving word, but he would turn his face to the wall, and -die with that word unsaid. Ah, how would she feel then? And he pictured -himself brought home from the river, dead, with his curls all wet, and -his sore heart at rest. How she would throw herself upon him, and how -her tears would fall like rain, and her lips pray God to give her back -her boy and she would never, never abuse him any more! But he would lie -there cold and white and make no sign--a poor little sufferer, whose -griefs were at an end. He so worked upon his feelings with the pathos -of these dreams, that he had to keep swallowing, he was so like to -choke; and his eyes swam in a blur of water, which overflowed when he -winked, and ran down and trickled from the end of his nose. And such a -luxury to him was this petting of his sorrows, that he could not bear -to have any worldly cheeriness or any grating delight intrude upon it; -it was too sacred for such contact; and so, presently, when his cousin -Mary danced in, all alive with the joy of seeing home again after an -age-long visit of one week to the country, he got up and moved in -clouds and darkness out at one door as she brought song and sunshine in -at the other. - -He wandered far from the accustomed haunts of boys, and sought -desolate places that were in harmony with his spirit. A log raft in the -river invited him, and he seated himself on its outer edge and -contemplated the dreary vastness of the stream, wishing, the while, -that he could only be drowned, all at once and unconsciously, without -undergoing the uncomfortable routine devised by nature. Then he thought -of his flower. He got it out, rumpled and wilted, and it mightily -increased his dismal felicity. He wondered if she would pity him if she -knew? Would she cry, and wish that she had a right to put her arms -around his neck and comfort him? Or would she turn coldly away like all -the hollow world? This picture brought such an agony of pleasurable -suffering that he worked it over and over again in his mind and set it -up in new and varied lights, till he wore it threadbare. At last he -rose up sighing and departed in the darkness. - -About half-past nine or ten o'clock he came along the deserted street -to where the Adored Unknown lived; he paused a moment; no sound fell -upon his listening ear; a candle was casting a dull glow upon the -curtain of a second-story window. Was the sacred presence there? He -climbed the fence, threaded his stealthy way through the plants, till -he stood under that window; he looked up at it long, and with emotion; -then he laid him down on the ground under it, disposing himself upon -his back, with his hands clasped upon his breast and holding his poor -wilted flower. And thus he would die--out in the cold world, with no -shelter over his homeless head, no friendly hand to wipe the -death-damps from his brow, no loving face to bend pityingly over him -when the great agony came. And thus SHE would see him when she looked -out upon the glad morning, and oh! would she drop one little tear upon -his poor, lifeless form, would she heave one little sigh to see a bright -young life so rudely blighted, so untimely cut down? - -The window went up, a maid-servant's discordant voice profaned the -holy calm, and a deluge of water drenched the prone martyr's remains! - -The strangling hero sprang up with a relieving snort. There was a whiz -as of a missile in the air, mingled with the murmur of a curse, a sound -as of shivering glass followed, and a small, vague form went over the -fence and shot away in the gloom. - -Not long after, as Tom, all undressed for bed, was surveying his -drenched garments by the light of a tallow dip, Sid woke up; but if he -had any dim idea of making any "references to allusions," he thought -better of it and held his peace, for there was danger in Tom's eye. - -Tom turned in without the added vexation of prayers, and Sid made -mental note of the omission. - - - -CHAPTER IV - -THE sun rose upon a tranquil world, and beamed down upon the peaceful -village like a benediction. Breakfast over, Aunt Polly had family -worship: it began with a prayer built from the ground up of solid -courses of Scriptural quotations, welded together with a thin mortar of -originality; and from the summit of this she delivered a grim chapter -of the Mosaic Law, as from Sinai. - -Then Tom girded up his loins, so to speak, and went to work to "get -his verses." Sid had learned his lesson days before. Tom bent all his -energies to the memorizing of five verses, and he chose part of the -Sermon on the Mount, because he could find no verses that were shorter. -At the end of half an hour Tom had a vague general idea of his lesson, -but no more, for his mind was traversing the whole field of human -thought, and his hands were busy with distracting recreations. Mary -took his book to hear him recite, and he tried to find his way through -the fog: - -"Blessed are the--a--a--" - -"Poor"-- - -"Yes--poor; blessed are the poor--a--a--" - -"In spirit--" - -"In spirit; blessed are the poor in spirit, for they--they--" - -"THEIRS--" - -"For THEIRS. Blessed are the poor in spirit, for theirs is the kingdom -of heaven. Blessed are they that mourn, for they--they--" - -"Sh--" - -"For they--a--" - -"S, H, A--" - -"For they S, H--Oh, I don't know what it is!" - -"SHALL!" - -"Oh, SHALL! for they shall--for they shall--a--a--shall mourn--a--a-- -blessed are they that shall--they that--a--they that shall mourn, for -they shall--a--shall WHAT? Why don't you tell me, Mary?--what do you -want to be so mean for?" - -"Oh, Tom, you poor thick-headed thing, I'm not teasing you. I wouldn't -do that. You must go and learn it again. Don't you be discouraged, Tom, -you'll manage it--and if you do, I'll give you something ever so nice. -There, now, that's a good boy." - -"All right! What is it, Mary, tell me what it is." - -"Never you mind, Tom. You know if I say it's nice, it is nice." - -"You bet you that's so, Mary. All right, I'll tackle it again." - -And he did "tackle it again"--and under the double pressure of -curiosity and prospective gain he did it with such spirit that he -accomplished a shining success. Mary gave him a brand-new "Barlow" -knife worth twelve and a half cents; and the convulsion of delight that -swept his system shook him to his foundations. True, the knife would -not cut anything, but it was a "sure-enough" Barlow, and there was -inconceivable grandeur in that--though where the Western boys ever got -the idea that such a weapon could possibly be counterfeited to its -injury is an imposing mystery and will always remain so, perhaps. Tom -contrived to scarify the cupboard with it, and was arranging to begin -on the bureau, when he was called off to dress for Sunday-school. - -Mary gave him a tin basin of water and a piece of soap, and he went -outside the door and set the basin on a little bench there; then he -dipped the soap in the water and laid it down; turned up his sleeves; -poured out the water on the ground, gently, and then entered the -kitchen and began to wipe his face diligently on the towel behind the -door. But Mary removed the towel and said: - -"Now ain't you ashamed, Tom. You mustn't be so bad. Water won't hurt -you." - -Tom was a trifle disconcerted. The basin was refilled, and this time -he stood over it a little while, gathering resolution; took in a big -breath and began. When he entered the kitchen presently, with both eyes -shut and groping for the towel with his hands, an honorable testimony -of suds and water was dripping from his face. But when he emerged from -the towel, he was not yet satisfactory, for the clean territory stopped -short at his chin and his jaws, like a mask; below and beyond this line -there was a dark expanse of unirrigated soil that spread downward in -front and backward around his neck. Mary took him in hand, and when she -was done with him he was a man and a brother, without distinction of -color, and his saturated hair was neatly brushed, and its short curls -wrought into a dainty and symmetrical general effect. [He privately -smoothed out the curls, with labor and difficulty, and plastered his -hair close down to his head; for he held curls to be effeminate, and -his own filled his life with bitterness.] Then Mary got out a suit of -his clothing that had been used only on Sundays during two years--they -were simply called his "other clothes"--and so by that we know the -size of his wardrobe. The girl "put him to rights" after he had dressed -himself; she buttoned his neat roundabout up to his chin, turned his -vast shirt collar down over his shoulders, brushed him off and crowned -him with his speckled straw hat. He now looked exceedingly improved and -uncomfortable. He was fully as uncomfortable as he looked; for there -was a restraint about whole clothes and cleanliness that galled him. He -hoped that Mary would forget his shoes, but the hope was blighted; she -coated them thoroughly with tallow, as was the custom, and brought them -out. He lost his temper and said he was always being made to do -everything he didn't want to do. But Mary said, persuasively: - -"Please, Tom--that's a good boy." - -So he got into the shoes snarling. Mary was soon ready, and the three -children set out for Sunday-school--a place that Tom hated with his -whole heart; but Sid and Mary were fond of it. - -Sabbath-school hours were from nine to half-past ten; and then church -service. Two of the children always remained for the sermon -voluntarily, and the other always remained too--for stronger reasons. -The church's high-backed, uncushioned pews would seat about three -hundred persons; the edifice was but a small, plain affair, with a sort -of pine board tree-box on top of it for a steeple. At the door Tom -dropped back a step and accosted a Sunday-dressed comrade: - -"Say, Billy, got a yaller ticket?" - -"Yes." - -"What'll you take for her?" - -"What'll you give?" - -"Piece of lickrish and a fish-hook." - -"Less see 'em." - -Tom exhibited. They were satisfactory, and the property changed hands. -Then Tom traded a couple of white alleys for three red tickets, and -some small trifle or other for a couple of blue ones. He waylaid other -boys as they came, and went on buying tickets of various colors ten or -fifteen minutes longer. He entered the church, now, with a swarm of -clean and noisy boys and girls, proceeded to his seat and started a -quarrel with the first boy that came handy. The teacher, a grave, -elderly man, interfered; then turned his back a moment and Tom pulled a -boy's hair in the next bench, and was absorbed in his book when the boy -turned around; stuck a pin in another boy, presently, in order to hear -him say "Ouch!" and got a new reprimand from his teacher. Tom's whole -class were of a pattern--restless, noisy, and troublesome. When they -came to recite their lessons, not one of them knew his verses -perfectly, but had to be prompted all along. However, they worried -through, and each got his reward--in small blue tickets, each with a -passage of Scripture on it; each blue ticket was pay for two verses of -the recitation. Ten blue tickets equalled a red one, and could be -exchanged for it; ten red tickets equalled a yellow one; for ten yellow -tickets the superintendent gave a very plainly bound Bible (worth forty -cents in those easy times) to the pupil. How many of my readers would -have the industry and application to memorize two thousand verses, even -for a Dore Bible? And yet Mary had acquired two Bibles in this way--it -was the patient work of two years--and a boy of German parentage had -won four or five. He once recited three thousand verses without -stopping; but the strain upon his mental faculties was too great, and -he was little better than an idiot from that day forth--a grievous -misfortune for the school, for on great occasions, before company, the -superintendent (as Tom expressed it) had always made this boy come out -and "spread himself." Only the older pupils managed to keep their -tickets and stick to their tedious work long enough to get a Bible, and -so the delivery of one of these prizes was a rare and noteworthy -circumstance; the successful pupil was so great and conspicuous for -that day that on the spot every scholar's heart was fired with a fresh -ambition that often lasted a couple of weeks. It is possible that Tom's -mental stomach had never really hungered for one of those prizes, but -unquestionably his entire being had for many a day longed for the glory -and the eclat that came with it. - -In due course the superintendent stood up in front of the pulpit, with -a closed hymn-book in his hand and his forefinger inserted between its -leaves, and commanded attention. When a Sunday-school superintendent -makes his customary little speech, a hymn-book in the hand is as -necessary as is the inevitable sheet of music in the hand of a singer -who stands forward on the platform and sings a solo at a concert ---though why, is a mystery: for neither the hymn-book nor the sheet of -music is ever referred to by the sufferer. This superintendent was a -slim creature of thirty-five, with a sandy goatee and short sandy hair; -he wore a stiff standing-collar whose upper edge almost reached his -ears and whose sharp points curved forward abreast the corners of his -mouth--a fence that compelled a straight lookout ahead, and a turning -of the whole body when a side view was required; his chin was propped -on a spreading cravat which was as broad and as long as a bank-note, -and had fringed ends; his boot toes were turned sharply up, in the -fashion of the day, like sleigh-runners--an effect patiently and -laboriously produced by the young men by sitting with their toes -pressed against a wall for hours together. Mr. Walters was very earnest -of mien, and very sincere and honest at heart; and he held sacred -things and places in such reverence, and so separated them from worldly -matters, that unconsciously to himself his Sunday-school voice had -acquired a peculiar intonation which was wholly absent on week-days. He -began after this fashion: - -"Now, children, I want you all to sit up just as straight and pretty -as you can and give me all your attention for a minute or two. There ---that is it. That is the way good little boys and girls should do. I see -one little girl who is looking out of the window--I am afraid she -thinks I am out there somewhere--perhaps up in one of the trees making -a speech to the little birds. [Applausive titter.] I want to tell you -how good it makes me feel to see so many bright, clean little faces -assembled in a place like this, learning to do right and be good." And -so forth and so on. It is not necessary to set down the rest of the -oration. It was of a pattern which does not vary, and so it is familiar -to us all. - -The latter third of the speech was marred by the resumption of fights -and other recreations among certain of the bad boys, and by fidgetings -and whisperings that extended far and wide, washing even to the bases -of isolated and incorruptible rocks like Sid and Mary. But now every -sound ceased suddenly, with the subsidence of Mr. Walters' voice, and -the conclusion of the speech was received with a burst of silent -gratitude. - -A good part of the whispering had been occasioned by an event which -was more or less rare--the entrance of visitors: lawyer Thatcher, -accompanied by a very feeble and aged man; a fine, portly, middle-aged -gentleman with iron-gray hair; and a dignified lady who was doubtless -the latter's wife. The lady was leading a child. Tom had been restless -and full of chafings and repinings; conscience-smitten, too--he could -not meet Amy Lawrence's eye, he could not brook her loving gaze. But -when he saw this small new-comer his soul was all ablaze with bliss in -a moment. The next moment he was "showing off" with all his might ---cuffing boys, pulling hair, making faces--in a word, using every art -that seemed likely to fascinate a girl and win her applause. His -exaltation had but one alloy--the memory of his humiliation in this -angel's garden--and that record in sand was fast washing out, under -the waves of happiness that were sweeping over it now. - -The visitors were given the highest seat of honor, and as soon as Mr. -Walters' speech was finished, he introduced them to the school. The -middle-aged man turned out to be a prodigious personage--no less a one -than the county judge--altogether the most august creation these -children had ever looked upon--and they wondered what kind of material -he was made of--and they half wanted to hear him roar, and were half -afraid he might, too. He was from Constantinople, twelve miles away--so -he had travelled, and seen the world--these very eyes had looked upon -the county court-house--which was said to have a tin roof. The awe -which these reflections inspired was attested by the impressive silence -and the ranks of staring eyes. This was the great Judge Thatcher, -brother of their own lawyer. Jeff Thatcher immediately went forward, to -be familiar with the great man and be envied by the school. It would -have been music to his soul to hear the whisperings: - -"Look at him, Jim! He's a going up there. Say--look! he's a going to -shake hands with him--he IS shaking hands with him! By jings, don't you -wish you was Jeff?" - -Mr. Walters fell to "showing off," with all sorts of official -bustlings and activities, giving orders, delivering judgments, -discharging directions here, there, everywhere that he could find a -target. The librarian "showed off"--running hither and thither with his -arms full of books and making a deal of the splutter and fuss that -insect authority delights in. The young lady teachers "showed off" ---bending sweetly over pupils that were lately being boxed, lifting -pretty warning fingers at bad little boys and patting good ones -lovingly. The young gentlemen teachers "showed off" with small -scoldings and other little displays of authority and fine attention to -discipline--and most of the teachers, of both sexes, found business up -at the library, by the pulpit; and it was business that frequently had -to be done over again two or three times (with much seeming vexation). -The little girls "showed off" in various ways, and the little boys -"showed off" with such diligence that the air was thick with paper wads -and the murmur of scufflings. And above it all the great man sat and -beamed a majestic judicial smile upon all the house, and warmed himself -in the sun of his own grandeur--for he was "showing off," too. - -There was only one thing wanting to make Mr. Walters' ecstasy -complete, and that was a chance to deliver a Bible-prize and exhibit a -prodigy. Several pupils had a few yellow tickets, but none had enough ---he had been around among the star pupils inquiring. He would have given -worlds, now, to have that German lad back again with a sound mind. - -And now at this moment, when hope was dead, Tom Sawyer came forward -with nine yellow tickets, nine red tickets, and ten blue ones, and -demanded a Bible. This was a thunderbolt out of a clear sky. Walters -was not expecting an application from this source for the next ten -years. But there was no getting around it--here were the certified -checks, and they were good for their face. Tom was therefore elevated -to a place with the Judge and the other elect, and the great news was -announced from headquarters. It was the most stunning surprise of the -decade, and so profound was the sensation that it lifted the new hero -up to the judicial one's altitude, and the school had two marvels to -gaze upon in place of one. The boys were all eaten up with envy--but -those that suffered the bitterest pangs were those who perceived too -late that they themselves had contributed to this hated splendor by -trading tickets to Tom for the wealth he had amassed in selling -whitewashing privileges. These despised themselves, as being the dupes -of a wily fraud, a guileful snake in the grass. - -The prize was delivered to Tom with as much effusion as the -superintendent could pump up under the circumstances; but it lacked -somewhat of the true gush, for the poor fellow's instinct taught him -that there was a mystery here that could not well bear the light, -perhaps; it was simply preposterous that this boy had warehoused two -thousand sheaves of Scriptural wisdom on his premises--a dozen would -strain his capacity, without a doubt. - -Amy Lawrence was proud and glad, and she tried to make Tom see it in -her face--but he wouldn't look. She wondered; then she was just a grain -troubled; next a dim suspicion came and went--came again; she watched; -a furtive glance told her worlds--and then her heart broke, and she was -jealous, and angry, and the tears came and she hated everybody. Tom -most of all (she thought). - -Tom was introduced to the Judge; but his tongue was tied, his breath -would hardly come, his heart quaked--partly because of the awful -greatness of the man, but mainly because he was her parent. He would -have liked to fall down and worship him, if it were in the dark. The -Judge put his hand on Tom's head and called him a fine little man, and -asked him what his name was. The boy stammered, gasped, and got it out: - -"Tom." - -"Oh, no, not Tom--it is--" - -"Thomas." - -"Ah, that's it. I thought there was more to it, maybe. That's very -well. But you've another one I daresay, and you'll tell it to me, won't -you?" - -"Tell the gentleman your other name, Thomas," said Walters, "and say -sir. You mustn't forget your manners." - -"Thomas Sawyer--sir." - -"That's it! That's a good boy. Fine boy. Fine, manly little fellow. -Two thousand verses is a great many--very, very great many. And you -never can be sorry for the trouble you took to learn them; for -knowledge is worth more than anything there is in the world; it's what -makes great men and good men; you'll be a great man and a good man -yourself, some day, Thomas, and then you'll look back and say, It's all -owing to the precious Sunday-school privileges of my boyhood--it's all -owing to my dear teachers that taught me to learn--it's all owing to -the good superintendent, who encouraged me, and watched over me, and -gave me a beautiful Bible--a splendid elegant Bible--to keep and have -it all for my own, always--it's all owing to right bringing up! That is -what you will say, Thomas--and you wouldn't take any money for those -two thousand verses--no indeed you wouldn't. And now you wouldn't mind -telling me and this lady some of the things you've learned--no, I know -you wouldn't--for we are proud of little boys that learn. Now, no -doubt you know the names of all the twelve disciples. Won't you tell us -the names of the first two that were appointed?" - -Tom was tugging at a button-hole and looking sheepish. He blushed, -now, and his eyes fell. Mr. Walters' heart sank within him. He said to -himself, it is not possible that the boy can answer the simplest -question--why DID the Judge ask him? Yet he felt obliged to speak up -and say: - -"Answer the gentleman, Thomas--don't be afraid." - -Tom still hung fire. - -"Now I know you'll tell me," said the lady. "The names of the first -two disciples were--" - -"DAVID AND GOLIAH!" - -Let us draw the curtain of charity over the rest of the scene. - - - -CHAPTER V - -ABOUT half-past ten the cracked bell of the small church began to -ring, and presently the people began to gather for the morning sermon. -The Sunday-school children distributed themselves about the house and -occupied pews with their parents, so as to be under supervision. Aunt -Polly came, and Tom and Sid and Mary sat with her--Tom being placed -next the aisle, in order that he might be as far away from the open -window and the seductive outside summer scenes as possible. The crowd -filed up the aisles: the aged and needy postmaster, who had seen better -days; the mayor and his wife--for they had a mayor there, among other -unnecessaries; the justice of the peace; the widow Douglass, fair, -smart, and forty, a generous, good-hearted soul and well-to-do, her -hill mansion the only palace in the town, and the most hospitable and -much the most lavish in the matter of festivities that St. Petersburg -could boast; the bent and venerable Major and Mrs. Ward; lawyer -Riverson, the new notable from a distance; next the belle of the -village, followed by a troop of lawn-clad and ribbon-decked young -heart-breakers; then all the young clerks in town in a body--for they -had stood in the vestibule sucking their cane-heads, a circling wall of -oiled and simpering admirers, till the last girl had run their gantlet; -and last of all came the Model Boy, Willie Mufferson, taking as heedful -care of his mother as if she were cut glass. He always brought his -mother to church, and was the pride of all the matrons. The boys all -hated him, he was so good. And besides, he had been "thrown up to them" -so much. His white handkerchief was hanging out of his pocket behind, as -usual on Sundays--accidentally. Tom had no handkerchief, and he looked -upon boys who had as snobs. - -The congregation being fully assembled, now, the bell rang once more, -to warn laggards and stragglers, and then a solemn hush fell upon the -church which was only broken by the tittering and whispering of the -choir in the gallery. The choir always tittered and whispered all -through service. There was once a church choir that was not ill-bred, -but I have forgotten where it was, now. It was a great many years ago, -and I can scarcely remember anything about it, but I think it was in -some foreign country. - -The minister gave out the hymn, and read it through with a relish, in -a peculiar style which was much admired in that part of the country. -His voice began on a medium key and climbed steadily up till it reached -a certain point, where it bore with strong emphasis upon the topmost -word and then plunged down as if from a spring-board: - - Shall I be car-ri-ed toe the skies, on flow'ry BEDS of ease, - - Whilst others fight to win the prize, and sail thro' BLOODY seas? - -He was regarded as a wonderful reader. At church "sociables" he was -always called upon to read poetry; and when he was through, the ladies -would lift up their hands and let them fall helplessly in their laps, -and "wall" their eyes, and shake their heads, as much as to say, "Words -cannot express it; it is too beautiful, TOO beautiful for this mortal -earth." - -After the hymn had been sung, the Rev. Mr. Sprague turned himself into -a bulletin-board, and read off "notices" of meetings and societies and -things till it seemed that the list would stretch out to the crack of -doom--a queer custom which is still kept up in America, even in cities, -away here in this age of abundant newspapers. Often, the less there is -to justify a traditional custom, the harder it is to get rid of it. - -And now the minister prayed. A good, generous prayer it was, and went -into details: it pleaded for the church, and the little children of the -church; for the other churches of the village; for the village itself; -for the county; for the State; for the State officers; for the United -States; for the churches of the United States; for Congress; for the -President; for the officers of the Government; for poor sailors, tossed -by stormy seas; for the oppressed millions groaning under the heel of -European monarchies and Oriental despotisms; for such as have the light -and the good tidings, and yet have not eyes to see nor ears to hear -withal; for the heathen in the far islands of the sea; and closed with -a supplication that the words he was about to speak might find grace -and favor, and be as seed sown in fertile ground, yielding in time a -grateful harvest of good. Amen. - -There was a rustling of dresses, and the standing congregation sat -down. The boy whose history this book relates did not enjoy the prayer, -he only endured it--if he even did that much. He was restive all -through it; he kept tally of the details of the prayer, unconsciously ---for he was not listening, but he knew the ground of old, and the -clergyman's regular route over it--and when a little trifle of new -matter was interlarded, his ear detected it and his whole nature -resented it; he considered additions unfair, and scoundrelly. In the -midst of the prayer a fly had lit on the back of the pew in front of -him and tortured his spirit by calmly rubbing its hands together, -embracing its head with its arms, and polishing it so vigorously that -it seemed to almost part company with the body, and the slender thread -of a neck was exposed to view; scraping its wings with its hind legs -and smoothing them to its body as if they had been coat-tails; going -through its whole toilet as tranquilly as if it knew it was perfectly -safe. As indeed it was; for as sorely as Tom's hands itched to grab for -it they did not dare--he believed his soul would be instantly destroyed -if he did such a thing while the prayer was going on. But with the -closing sentence his hand began to curve and steal forward; and the -instant the "Amen" was out the fly was a prisoner of war. His aunt -detected the act and made him let it go. - -The minister gave out his text and droned along monotonously through -an argument that was so prosy that many a head by and by began to nod ---and yet it was an argument that dealt in limitless fire and brimstone -and thinned the predestined elect down to a company so small as to be -hardly worth the saving. Tom counted the pages of the sermon; after -church he always knew how many pages there had been, but he seldom knew -anything else about the discourse. However, this time he was really -interested for a little while. The minister made a grand and moving -picture of the assembling together of the world's hosts at the -millennium when the lion and the lamb should lie down together and a -little child should lead them. But the pathos, the lesson, the moral of -the great spectacle were lost upon the boy; he only thought of the -conspicuousness of the principal character before the on-looking -nations; his face lit with the thought, and he said to himself that he -wished he could be that child, if it was a tame lion. - -Now he lapsed into suffering again, as the dry argument was resumed. -Presently he bethought him of a treasure he had and got it out. It was -a large black beetle with formidable jaws--a "pinchbug," he called it. -It was in a percussion-cap box. The first thing the beetle did was to -take him by the finger. A natural fillip followed, the beetle went -floundering into the aisle and lit on its back, and the hurt finger -went into the boy's mouth. The beetle lay there working its helpless -legs, unable to turn over. Tom eyed it, and longed for it; but it was -safe out of his reach. Other people uninterested in the sermon found -relief in the beetle, and they eyed it too. Presently a vagrant poodle -dog came idling along, sad at heart, lazy with the summer softness and -the quiet, weary of captivity, sighing for change. He spied the beetle; -the drooping tail lifted and wagged. He surveyed the prize; walked -around it; smelt at it from a safe distance; walked around it again; -grew bolder, and took a closer smell; then lifted his lip and made a -gingerly snatch at it, just missing it; made another, and another; -began to enjoy the diversion; subsided to his stomach with the beetle -between his paws, and continued his experiments; grew weary at last, -and then indifferent and absent-minded. His head nodded, and little by -little his chin descended and touched the enemy, who seized it. There -was a sharp yelp, a flirt of the poodle's head, and the beetle fell a -couple of yards away, and lit on its back once more. The neighboring -spectators shook with a gentle inward joy, several faces went behind -fans and handkerchiefs, and Tom was entirely happy. The dog looked -foolish, and probably felt so; but there was resentment in his heart, -too, and a craving for revenge. So he went to the beetle and began a -wary attack on it again; jumping at it from every point of a circle, -lighting with his fore-paws within an inch of the creature, making even -closer snatches at it with his teeth, and jerking his head till his -ears flapped again. But he grew tired once more, after a while; tried -to amuse himself with a fly but found no relief; followed an ant -around, with his nose close to the floor, and quickly wearied of that; -yawned, sighed, forgot the beetle entirely, and sat down on it. Then -there was a wild yelp of agony and the poodle went sailing up the -aisle; the yelps continued, and so did the dog; he crossed the house in -front of the altar; he flew down the other aisle; he crossed before the -doors; he clamored up the home-stretch; his anguish grew with his -progress, till presently he was but a woolly comet moving in its orbit -with the gleam and the speed of light. At last the frantic sufferer -sheered from its course, and sprang into its master's lap; he flung it -out of the window, and the voice of distress quickly thinned away and -died in the distance. - -By this time the whole church was red-faced and suffocating with -suppressed laughter, and the sermon had come to a dead standstill. The -discourse was resumed presently, but it went lame and halting, all -possibility of impressiveness being at an end; for even the gravest -sentiments were constantly being received with a smothered burst of -unholy mirth, under cover of some remote pew-back, as if the poor -parson had said a rarely facetious thing. It was a genuine relief to -the whole congregation when the ordeal was over and the benediction -pronounced. - -Tom Sawyer went home quite cheerful, thinking to himself that there -was some satisfaction about divine service when there was a bit of -variety in it. He had but one marring thought; he was willing that the -dog should play with his pinchbug, but he did not think it was upright -in him to carry it off. - - - -CHAPTER VI - -MONDAY morning found Tom Sawyer miserable. Monday morning always found -him so--because it began another week's slow suffering in school. He -generally began that day with wishing he had had no intervening -holiday, it made the going into captivity and fetters again so much -more odious. - -Tom lay thinking. Presently it occurred to him that he wished he was -sick; then he could stay home from school. Here was a vague -possibility. He canvassed his system. No ailment was found, and he -investigated again. This time he thought he could detect colicky -symptoms, and he began to encourage them with considerable hope. But -they soon grew feeble, and presently died wholly away. He reflected -further. Suddenly he discovered something. One of his upper front teeth -was loose. This was lucky; he was about to begin to groan, as a -"starter," as he called it, when it occurred to him that if he came -into court with that argument, his aunt would pull it out, and that -would hurt. So he thought he would hold the tooth in reserve for the -present, and seek further. Nothing offered for some little time, and -then he remembered hearing the doctor tell about a certain thing that -laid up a patient for two or three weeks and threatened to make him -lose a finger. So the boy eagerly drew his sore toe from under the -sheet and held it up for inspection. But now he did not know the -necessary symptoms. However, it seemed well worth while to chance it, -so he fell to groaning with considerable spirit. - -But Sid slept on unconscious. - -Tom groaned louder, and fancied that he began to feel pain in the toe. - -No result from Sid. - -Tom was panting with his exertions by this time. He took a rest and -then swelled himself up and fetched a succession of admirable groans. - -Sid snored on. - -Tom was aggravated. He said, "Sid, Sid!" and shook him. This course -worked well, and Tom began to groan again. Sid yawned, stretched, then -brought himself up on his elbow with a snort, and began to stare at -Tom. Tom went on groaning. Sid said: - -"Tom! Say, Tom!" [No response.] "Here, Tom! TOM! What is the matter, -Tom?" And he shook him and looked in his face anxiously. - -Tom moaned out: - -"Oh, don't, Sid. Don't joggle me." - -"Why, what's the matter, Tom? I must call auntie." - -"No--never mind. It'll be over by and by, maybe. Don't call anybody." - -"But I must! DON'T groan so, Tom, it's awful. How long you been this -way?" - -"Hours. Ouch! Oh, don't stir so, Sid, you'll kill me." - -"Tom, why didn't you wake me sooner? Oh, Tom, DON'T! It makes my -flesh crawl to hear you. Tom, what is the matter?" - -"I forgive you everything, Sid. [Groan.] Everything you've ever done -to me. When I'm gone--" - -"Oh, Tom, you ain't dying, are you? Don't, Tom--oh, don't. Maybe--" - -"I forgive everybody, Sid. [Groan.] Tell 'em so, Sid. And Sid, you -give my window-sash and my cat with one eye to that new girl that's -come to town, and tell her--" - -But Sid had snatched his clothes and gone. Tom was suffering in -reality, now, so handsomely was his imagination working, and so his -groans had gathered quite a genuine tone. - -Sid flew down-stairs and said: - -"Oh, Aunt Polly, come! Tom's dying!" - -"Dying!" - -"Yes'm. Don't wait--come quick!" - -"Rubbage! I don't believe it!" - -But she fled up-stairs, nevertheless, with Sid and Mary at her heels. -And her face grew white, too, and her lip trembled. When she reached -the bedside she gasped out: - -"You, Tom! Tom, what's the matter with you?" - -"Oh, auntie, I'm--" - -"What's the matter with you--what is the matter with you, child?" - -"Oh, auntie, my sore toe's mortified!" - -The old lady sank down into a chair and laughed a little, then cried a -little, then did both together. This restored her and she said: - -"Tom, what a turn you did give me. Now you shut up that nonsense and -climb out of this." - -The groans ceased and the pain vanished from the toe. The boy felt a -little foolish, and he said: - -"Aunt Polly, it SEEMED mortified, and it hurt so I never minded my -tooth at all." - -"Your tooth, indeed! What's the matter with your tooth?" - -"One of them's loose, and it aches perfectly awful." - -"There, there, now, don't begin that groaning again. Open your mouth. -Well--your tooth IS loose, but you're not going to die about that. -Mary, get me a silk thread, and a chunk of fire out of the kitchen." - -Tom said: - -"Oh, please, auntie, don't pull it out. It don't hurt any more. I wish -I may never stir if it does. Please don't, auntie. I don't want to stay -home from school." - -"Oh, you don't, don't you? So all this row was because you thought -you'd get to stay home from school and go a-fishing? Tom, Tom, I love -you so, and you seem to try every way you can to break my old heart -with your outrageousness." By this time the dental instruments were -ready. The old lady made one end of the silk thread fast to Tom's tooth -with a loop and tied the other to the bedpost. Then she seized the -chunk of fire and suddenly thrust it almost into the boy's face. The -tooth hung dangling by the bedpost, now. - -But all trials bring their compensations. As Tom wended to school -after breakfast, he was the envy of every boy he met because the gap in -his upper row of teeth enabled him to expectorate in a new and -admirable way. He gathered quite a following of lads interested in the -exhibition; and one that had cut his finger and had been a centre of -fascination and homage up to this time, now found himself suddenly -without an adherent, and shorn of his glory. His heart was heavy, and -he said with a disdain which he did not feel that it wasn't anything to -spit like Tom Sawyer; but another boy said, "Sour grapes!" and he -wandered away a dismantled hero. - -Shortly Tom came upon the juvenile pariah of the village, Huckleberry -Finn, son of the town drunkard. Huckleberry was cordially hated and -dreaded by all the mothers of the town, because he was idle and lawless -and vulgar and bad--and because all their children admired him so, and -delighted in his forbidden society, and wished they dared to be like -him. Tom was like the rest of the respectable boys, in that he envied -Huckleberry his gaudy outcast condition, and was under strict orders -not to play with him. So he played with him every time he got a chance. -Huckleberry was always dressed in the cast-off clothes of full-grown -men, and they were in perennial bloom and fluttering with rags. His hat -was a vast ruin with a wide crescent lopped out of its brim; his coat, -when he wore one, hung nearly to his heels and had the rearward buttons -far down the back; but one suspender supported his trousers; the seat -of the trousers bagged low and contained nothing, the fringed legs -dragged in the dirt when not rolled up. - -Huckleberry came and went, at his own free will. He slept on doorsteps -in fine weather and in empty hogsheads in wet; he did not have to go to -school or to church, or call any being master or obey anybody; he could -go fishing or swimming when and where he chose, and stay as long as it -suited him; nobody forbade him to fight; he could sit up as late as he -pleased; he was always the first boy that went barefoot in the spring -and the last to resume leather in the fall; he never had to wash, nor -put on clean clothes; he could swear wonderfully. In a word, everything -that goes to make life precious that boy had. So thought every -harassed, hampered, respectable boy in St. Petersburg. - -Tom hailed the romantic outcast: - -"Hello, Huckleberry!" - -"Hello yourself, and see how you like it." - -"What's that you got?" - -"Dead cat." - -"Lemme see him, Huck. My, he's pretty stiff. Where'd you get him?" - -"Bought him off'n a boy." - -"What did you give?" - -"I give a blue ticket and a bladder that I got at the slaughter-house." - -"Where'd you get the blue ticket?" - -"Bought it off'n Ben Rogers two weeks ago for a hoop-stick." - -"Say--what is dead cats good for, Huck?" - -"Good for? Cure warts with." - -"No! Is that so? I know something that's better." - -"I bet you don't. What is it?" - -"Why, spunk-water." - -"Spunk-water! I wouldn't give a dern for spunk-water." - -"You wouldn't, wouldn't you? D'you ever try it?" - -"No, I hain't. But Bob Tanner did." - -"Who told you so!" - -"Why, he told Jeff Thatcher, and Jeff told Johnny Baker, and Johnny -told Jim Hollis, and Jim told Ben Rogers, and Ben told a nigger, and -the nigger told me. There now!" - -"Well, what of it? They'll all lie. Leastways all but the nigger. I -don't know HIM. But I never see a nigger that WOULDN'T lie. Shucks! Now -you tell me how Bob Tanner done it, Huck." - -"Why, he took and dipped his hand in a rotten stump where the -rain-water was." - -"In the daytime?" - -"Certainly." - -"With his face to the stump?" - -"Yes. Least I reckon so." - -"Did he say anything?" - -"I don't reckon he did. I don't know." - -"Aha! Talk about trying to cure warts with spunk-water such a blame -fool way as that! Why, that ain't a-going to do any good. You got to go -all by yourself, to the middle of the woods, where you know there's a -spunk-water stump, and just as it's midnight you back up against the -stump and jam your hand in and say: - - 'Barley-corn, barley-corn, injun-meal shorts, - Spunk-water, spunk-water, swaller these warts,' - -and then walk away quick, eleven steps, with your eyes shut, and then -turn around three times and walk home without speaking to anybody. -Because if you speak the charm's busted." - -"Well, that sounds like a good way; but that ain't the way Bob Tanner -done." - -"No, sir, you can bet he didn't, becuz he's the wartiest boy in this -town; and he wouldn't have a wart on him if he'd knowed how to work -spunk-water. I've took off thousands of warts off of my hands that way, -Huck. I play with frogs so much that I've always got considerable many -warts. Sometimes I take 'em off with a bean." - -"Yes, bean's good. I've done that." - -"Have you? What's your way?" - -"You take and split the bean, and cut the wart so as to get some -blood, and then you put the blood on one piece of the bean and take and -dig a hole and bury it 'bout midnight at the crossroads in the dark of -the moon, and then you burn up the rest of the bean. You see that piece -that's got the blood on it will keep drawing and drawing, trying to -fetch the other piece to it, and so that helps the blood to draw the -wart, and pretty soon off she comes." - -"Yes, that's it, Huck--that's it; though when you're burying it if you -say 'Down bean; off wart; come no more to bother me!' it's better. -That's the way Joe Harper does, and he's been nearly to Coonville and -most everywheres. But say--how do you cure 'em with dead cats?" - -"Why, you take your cat and go and get in the graveyard 'long about -midnight when somebody that was wicked has been buried; and when it's -midnight a devil will come, or maybe two or three, but you can't see -'em, you can only hear something like the wind, or maybe hear 'em talk; -and when they're taking that feller away, you heave your cat after 'em -and say, 'Devil follow corpse, cat follow devil, warts follow cat, I'm -done with ye!' That'll fetch ANY wart." - -"Sounds right. D'you ever try it, Huck?" - -"No, but old Mother Hopkins told me." - -"Well, I reckon it's so, then. Becuz they say she's a witch." - -"Say! Why, Tom, I KNOW she is. She witched pap. Pap says so his own -self. He come along one day, and he see she was a-witching him, so he -took up a rock, and if she hadn't dodged, he'd a got her. Well, that -very night he rolled off'n a shed wher' he was a layin drunk, and broke -his arm." - -"Why, that's awful. How did he know she was a-witching him?" - -"Lord, pap can tell, easy. Pap says when they keep looking at you -right stiddy, they're a-witching you. Specially if they mumble. Becuz -when they mumble they're saying the Lord's Prayer backards." - -"Say, Hucky, when you going to try the cat?" - -"To-night. I reckon they'll come after old Hoss Williams to-night." - -"But they buried him Saturday. Didn't they get him Saturday night?" - -"Why, how you talk! How could their charms work till midnight?--and -THEN it's Sunday. Devils don't slosh around much of a Sunday, I don't -reckon." - -"I never thought of that. That's so. Lemme go with you?" - -"Of course--if you ain't afeard." - -"Afeard! 'Tain't likely. Will you meow?" - -"Yes--and you meow back, if you get a chance. Last time, you kep' me -a-meowing around till old Hays went to throwing rocks at me and says -'Dern that cat!' and so I hove a brick through his window--but don't -you tell." - -"I won't. I couldn't meow that night, becuz auntie was watching me, -but I'll meow this time. Say--what's that?" - -"Nothing but a tick." - -"Where'd you get him?" - -"Out in the woods." - -"What'll you take for him?" - -"I don't know. I don't want to sell him." - -"All right. It's a mighty small tick, anyway." - -"Oh, anybody can run a tick down that don't belong to them. I'm -satisfied with it. It's a good enough tick for me." - -"Sho, there's ticks a plenty. I could have a thousand of 'em if I -wanted to." - -"Well, why don't you? Becuz you know mighty well you can't. This is a -pretty early tick, I reckon. It's the first one I've seen this year." - -"Say, Huck--I'll give you my tooth for him." - -"Less see it." - -Tom got out a bit of paper and carefully unrolled it. Huckleberry -viewed it wistfully. The temptation was very strong. At last he said: - -"Is it genuwyne?" - -Tom lifted his lip and showed the vacancy. - -"Well, all right," said Huckleberry, "it's a trade." - -Tom enclosed the tick in the percussion-cap box that had lately been -the pinchbug's prison, and the boys separated, each feeling wealthier -than before. - -When Tom reached the little isolated frame schoolhouse, he strode in -briskly, with the manner of one who had come with all honest speed. -He hung his hat on a peg and flung himself into his seat with -business-like alacrity. The master, throned on high in his great -splint-bottom arm-chair, was dozing, lulled by the drowsy hum of study. -The interruption roused him. - -"Thomas Sawyer!" - -Tom knew that when his name was pronounced in full, it meant trouble. - -"Sir!" - -"Come up here. Now, sir, why are you late again, as usual?" - -Tom was about to take refuge in a lie, when he saw two long tails of -yellow hair hanging down a back that he recognized by the electric -sympathy of love; and by that form was THE ONLY VACANT PLACE on the -girls' side of the schoolhouse. He instantly said: - -"I STOPPED TO TALK WITH HUCKLEBERRY FINN!" - -The master's pulse stood still, and he stared helplessly. The buzz of -study ceased. The pupils wondered if this foolhardy boy had lost his -mind. The master said: - -"You--you did what?" - -"Stopped to talk with Huckleberry Finn." - -There was no mistaking the words. - -"Thomas Sawyer, this is the most astounding confession I have ever -listened to. No mere ferule will answer for this offence. Take off your -jacket." - -The master's arm performed until it was tired and the stock of -switches notably diminished. Then the order followed: - -"Now, sir, go and sit with the girls! And let this be a warning to you." - -The titter that rippled around the room appeared to abash the boy, but -in reality that result was caused rather more by his worshipful awe of -his unknown idol and the dread pleasure that lay in his high good -fortune. He sat down upon the end of the pine bench and the girl -hitched herself away from him with a toss of her head. Nudges and winks -and whispers traversed the room, but Tom sat still, with his arms upon -the long, low desk before him, and seemed to study his book. - -By and by attention ceased from him, and the accustomed school murmur -rose upon the dull air once more. Presently the boy began to steal -furtive glances at the girl. She observed it, "made a mouth" at him and -gave him the back of her head for the space of a minute. When she -cautiously faced around again, a peach lay before her. She thrust it -away. Tom gently put it back. She thrust it away again, but with less -animosity. Tom patiently returned it to its place. Then she let it -remain. Tom scrawled on his slate, "Please take it--I got more." The -girl glanced at the words, but made no sign. Now the boy began to draw -something on the slate, hiding his work with his left hand. For a time -the girl refused to notice; but her human curiosity presently began to -manifest itself by hardly perceptible signs. The boy worked on, -apparently unconscious. The girl made a sort of noncommittal attempt to -see, but the boy did not betray that he was aware of it. At last she -gave in and hesitatingly whispered: - -"Let me see it." - -Tom partly uncovered a dismal caricature of a house with two gable -ends to it and a corkscrew of smoke issuing from the chimney. Then the -girl's interest began to fasten itself upon the work and she forgot -everything else. When it was finished, she gazed a moment, then -whispered: - -"It's nice--make a man." - -The artist erected a man in the front yard, that resembled a derrick. -He could have stepped over the house; but the girl was not -hypercritical; she was satisfied with the monster, and whispered: - -"It's a beautiful man--now make me coming along." - -Tom drew an hour-glass with a full moon and straw limbs to it and -armed the spreading fingers with a portentous fan. The girl said: - -"It's ever so nice--I wish I could draw." - -"It's easy," whispered Tom, "I'll learn you." - -"Oh, will you? When?" - -"At noon. Do you go home to dinner?" - -"I'll stay if you will." - -"Good--that's a whack. What's your name?" - -"Becky Thatcher. What's yours? Oh, I know. It's Thomas Sawyer." - -"That's the name they lick me by. I'm Tom when I'm good. You call me -Tom, will you?" - -"Yes." - -Now Tom began to scrawl something on the slate, hiding the words from -the girl. But she was not backward this time. She begged to see. Tom -said: - -"Oh, it ain't anything." - -"Yes it is." - -"No it ain't. You don't want to see." - -"Yes I do, indeed I do. Please let me." - -"You'll tell." - -"No I won't--deed and deed and double deed won't." - -"You won't tell anybody at all? Ever, as long as you live?" - -"No, I won't ever tell ANYbody. Now let me." - -"Oh, YOU don't want to see!" - -"Now that you treat me so, I WILL see." And she put her small hand -upon his and a little scuffle ensued, Tom pretending to resist in -earnest but letting his hand slip by degrees till these words were -revealed: "I LOVE YOU." - -"Oh, you bad thing!" And she hit his hand a smart rap, but reddened -and looked pleased, nevertheless. - -Just at this juncture the boy felt a slow, fateful grip closing on his -ear, and a steady lifting impulse. In that wise he was borne across the -house and deposited in his own seat, under a peppering fire of giggles -from the whole school. Then the master stood over him during a few -awful moments, and finally moved away to his throne without saying a -word. But although Tom's ear tingled, his heart was jubilant. - -As the school quieted down Tom made an honest effort to study, but the -turmoil within him was too great. In turn he took his place in the -reading class and made a botch of it; then in the geography class and -turned lakes into mountains, mountains into rivers, and rivers into -continents, till chaos was come again; then in the spelling class, and -got "turned down," by a succession of mere baby words, till he brought -up at the foot and yielded up the pewter medal which he had worn with -ostentation for months. - - - -CHAPTER VII - -THE harder Tom tried to fasten his mind on his book, the more his -ideas wandered. So at last, with a sigh and a yawn, he gave it up. It -seemed to him that the noon recess would never come. The air was -utterly dead. There was not a breath stirring. It was the sleepiest of -sleepy days. The drowsing murmur of the five and twenty studying -scholars soothed the soul like the spell that is in the murmur of bees. -Away off in the flaming sunshine, Cardiff Hill lifted its soft green -sides through a shimmering veil of heat, tinted with the purple of -distance; a few birds floated on lazy wing high in the air; no other -living thing was visible but some cows, and they were asleep. Tom's -heart ached to be free, or else to have something of interest to do to -pass the dreary time. His hand wandered into his pocket and his face -lit up with a glow of gratitude that was prayer, though he did not know -it. Then furtively the percussion-cap box came out. He released the -tick and put him on the long flat desk. The creature probably glowed -with a gratitude that amounted to prayer, too, at this moment, but it -was premature: for when he started thankfully to travel off, Tom turned -him aside with a pin and made him take a new direction. - -Tom's bosom friend sat next him, suffering just as Tom had been, and -now he was deeply and gratefully interested in this entertainment in an -instant. This bosom friend was Joe Harper. The two boys were sworn -friends all the week, and embattled enemies on Saturdays. Joe took a -pin out of his lapel and began to assist in exercising the prisoner. -The sport grew in interest momently. Soon Tom said that they were -interfering with each other, and neither getting the fullest benefit of -the tick. So he put Joe's slate on the desk and drew a line down the -middle of it from top to bottom. - -"Now," said he, "as long as he is on your side you can stir him up and -I'll let him alone; but if you let him get away and get on my side, -you're to leave him alone as long as I can keep him from crossing over." - -"All right, go ahead; start him up." - -The tick escaped from Tom, presently, and crossed the equator. Joe -harassed him awhile, and then he got away and crossed back again. This -change of base occurred often. While one boy was worrying the tick with -absorbing interest, the other would look on with interest as strong, -the two heads bowed together over the slate, and the two souls dead to -all things else. At last luck seemed to settle and abide with Joe. The -tick tried this, that, and the other course, and got as excited and as -anxious as the boys themselves, but time and again just as he would -have victory in his very grasp, so to speak, and Tom's fingers would be -twitching to begin, Joe's pin would deftly head him off, and keep -possession. At last Tom could stand it no longer. The temptation was -too strong. So he reached out and lent a hand with his pin. Joe was -angry in a moment. Said he: - -"Tom, you let him alone." - -"I only just want to stir him up a little, Joe." - -"No, sir, it ain't fair; you just let him alone." - -"Blame it, I ain't going to stir him much." - -"Let him alone, I tell you." - -"I won't!" - -"You shall--he's on my side of the line." - -"Look here, Joe Harper, whose is that tick?" - -"I don't care whose tick he is--he's on my side of the line, and you -sha'n't touch him." - -"Well, I'll just bet I will, though. He's my tick and I'll do what I -blame please with him, or die!" - -A tremendous whack came down on Tom's shoulders, and its duplicate on -Joe's; and for the space of two minutes the dust continued to fly from -the two jackets and the whole school to enjoy it. The boys had been too -absorbed to notice the hush that had stolen upon the school awhile -before when the master came tiptoeing down the room and stood over -them. He had contemplated a good part of the performance before he -contributed his bit of variety to it. - -When school broke up at noon, Tom flew to Becky Thatcher, and -whispered in her ear: - -"Put on your bonnet and let on you're going home; and when you get to -the corner, give the rest of 'em the slip, and turn down through the -lane and come back. I'll go the other way and come it over 'em the same -way." - -So the one went off with one group of scholars, and the other with -another. In a little while the two met at the bottom of the lane, and -when they reached the school they had it all to themselves. Then they -sat together, with a slate before them, and Tom gave Becky the pencil -and held her hand in his, guiding it, and so created another surprising -house. When the interest in art began to wane, the two fell to talking. -Tom was swimming in bliss. He said: - -"Do you love rats?" - -"No! I hate them!" - -"Well, I do, too--LIVE ones. But I mean dead ones, to swing round your -head with a string." - -"No, I don't care for rats much, anyway. What I like is chewing-gum." - -"Oh, I should say so! I wish I had some now." - -"Do you? I've got some. I'll let you chew it awhile, but you must give -it back to me." - -That was agreeable, so they chewed it turn about, and dangled their -legs against the bench in excess of contentment. - -"Was you ever at a circus?" said Tom. - -"Yes, and my pa's going to take me again some time, if I'm good." - -"I been to the circus three or four times--lots of times. Church ain't -shucks to a circus. There's things going on at a circus all the time. -I'm going to be a clown in a circus when I grow up." - -"Oh, are you! That will be nice. They're so lovely, all spotted up." - -"Yes, that's so. And they get slathers of money--most a dollar a day, -Ben Rogers says. Say, Becky, was you ever engaged?" - -"What's that?" - -"Why, engaged to be married." - -"No." - -"Would you like to?" - -"I reckon so. I don't know. What is it like?" - -"Like? Why it ain't like anything. You only just tell a boy you won't -ever have anybody but him, ever ever ever, and then you kiss and that's -all. Anybody can do it." - -"Kiss? What do you kiss for?" - -"Why, that, you know, is to--well, they always do that." - -"Everybody?" - -"Why, yes, everybody that's in love with each other. Do you remember -what I wrote on the slate?" - -"Ye--yes." - -"What was it?" - -"I sha'n't tell you." - -"Shall I tell YOU?" - -"Ye--yes--but some other time." - -"No, now." - -"No, not now--to-morrow." - -"Oh, no, NOW. Please, Becky--I'll whisper it, I'll whisper it ever so -easy." - -Becky hesitating, Tom took silence for consent, and passed his arm -about her waist and whispered the tale ever so softly, with his mouth -close to her ear. And then he added: - -"Now you whisper it to me--just the same." - -She resisted, for a while, and then said: - -"You turn your face away so you can't see, and then I will. But you -mustn't ever tell anybody--WILL you, Tom? Now you won't, WILL you?" - -"No, indeed, indeed I won't. Now, Becky." - -He turned his face away. She bent timidly around till her breath -stirred his curls and whispered, "I--love--you!" - -Then she sprang away and ran around and around the desks and benches, -with Tom after her, and took refuge in a corner at last, with her -little white apron to her face. Tom clasped her about her neck and -pleaded: - -"Now, Becky, it's all done--all over but the kiss. Don't you be afraid -of that--it ain't anything at all. Please, Becky." And he tugged at her -apron and the hands. - -By and by she gave up, and let her hands drop; her face, all glowing -with the struggle, came up and submitted. Tom kissed the red lips and -said: - -"Now it's all done, Becky. And always after this, you know, you ain't -ever to love anybody but me, and you ain't ever to marry anybody but -me, ever never and forever. Will you?" - -"No, I'll never love anybody but you, Tom, and I'll never marry -anybody but you--and you ain't to ever marry anybody but me, either." - -"Certainly. Of course. That's PART of it. And always coming to school -or when we're going home, you're to walk with me, when there ain't -anybody looking--and you choose me and I choose you at parties, because -that's the way you do when you're engaged." - -"It's so nice. I never heard of it before." - -"Oh, it's ever so gay! Why, me and Amy Lawrence--" - -The big eyes told Tom his blunder and he stopped, confused. - -"Oh, Tom! Then I ain't the first you've ever been engaged to!" - -The child began to cry. Tom said: - -"Oh, don't cry, Becky, I don't care for her any more." - -"Yes, you do, Tom--you know you do." - -Tom tried to put his arm about her neck, but she pushed him away and -turned her face to the wall, and went on crying. Tom tried again, with -soothing words in his mouth, and was repulsed again. Then his pride was -up, and he strode away and went outside. He stood about, restless and -uneasy, for a while, glancing at the door, every now and then, hoping -she would repent and come to find him. But she did not. Then he began -to feel badly and fear that he was in the wrong. It was a hard struggle -with him to make new advances, now, but he nerved himself to it and -entered. She was still standing back there in the corner, sobbing, with -her face to the wall. Tom's heart smote him. He went to her and stood a -moment, not knowing exactly how to proceed. Then he said hesitatingly: - -"Becky, I--I don't care for anybody but you." - -No reply--but sobs. - -"Becky"--pleadingly. "Becky, won't you say something?" - -More sobs. - -Tom got out his chiefest jewel, a brass knob from the top of an -andiron, and passed it around her so that she could see it, and said: - -"Please, Becky, won't you take it?" - -She struck it to the floor. Then Tom marched out of the house and over -the hills and far away, to return to school no more that day. Presently -Becky began to suspect. She ran to the door; he was not in sight; she -flew around to the play-yard; he was not there. Then she called: - -"Tom! Come back, Tom!" - -She listened intently, but there was no answer. She had no companions -but silence and loneliness. So she sat down to cry again and upbraid -herself; and by this time the scholars began to gather again, and she -had to hide her griefs and still her broken heart and take up the cross -of a long, dreary, aching afternoon, with none among the strangers -about her to exchange sorrows with. - - - -CHAPTER VIII - -TOM dodged hither and thither through lanes until he was well out of -the track of returning scholars, and then fell into a moody jog. He -crossed a small "branch" two or three times, because of a prevailing -juvenile superstition that to cross water baffled pursuit. Half an hour -later he was disappearing behind the Douglas mansion on the summit of -Cardiff Hill, and the schoolhouse was hardly distinguishable away off -in the valley behind him. He entered a dense wood, picked his pathless -way to the centre of it, and sat down on a mossy spot under a spreading -oak. There was not even a zephyr stirring; the dead noonday heat had -even stilled the songs of the birds; nature lay in a trance that was -broken by no sound but the occasional far-off hammering of a -woodpecker, and this seemed to render the pervading silence and sense -of loneliness the more profound. The boy's soul was steeped in -melancholy; his feelings were in happy accord with his surroundings. He -sat long with his elbows on his knees and his chin in his hands, -meditating. It seemed to him that life was but a trouble, at best, and -he more than half envied Jimmy Hodges, so lately released; it must be -very peaceful, he thought, to lie and slumber and dream forever and -ever, with the wind whispering through the trees and caressing the -grass and the flowers over the grave, and nothing to bother and grieve -about, ever any more. If he only had a clean Sunday-school record he -could be willing to go, and be done with it all. Now as to this girl. -What had he done? Nothing. He had meant the best in the world, and been -treated like a dog--like a very dog. She would be sorry some day--maybe -when it was too late. Ah, if he could only die TEMPORARILY! - -But the elastic heart of youth cannot be compressed into one -constrained shape long at a time. Tom presently began to drift -insensibly back into the concerns of this life again. What if he turned -his back, now, and disappeared mysteriously? What if he went away--ever -so far away, into unknown countries beyond the seas--and never came -back any more! How would she feel then! The idea of being a clown -recurred to him now, only to fill him with disgust. For frivolity and -jokes and spotted tights were an offense, when they intruded themselves -upon a spirit that was exalted into the vague august realm of the -romantic. No, he would be a soldier, and return after long years, all -war-worn and illustrious. No--better still, he would join the Indians, -and hunt buffaloes and go on the warpath in the mountain ranges and the -trackless great plains of the Far West, and away in the future come -back a great chief, bristling with feathers, hideous with paint, and -prance into Sunday-school, some drowsy summer morning, with a -bloodcurdling war-whoop, and sear the eyeballs of all his companions -with unappeasable envy. But no, there was something gaudier even than -this. He would be a pirate! That was it! NOW his future lay plain -before him, and glowing with unimaginable splendor. How his name would -fill the world, and make people shudder! How gloriously he would go -plowing the dancing seas, in his long, low, black-hulled racer, the -Spirit of the Storm, with his grisly flag flying at the fore! And at -the zenith of his fame, how he would suddenly appear at the old village -and stalk into church, brown and weather-beaten, in his black velvet -doublet and trunks, his great jack-boots, his crimson sash, his belt -bristling with horse-pistols, his crime-rusted cutlass at his side, his -slouch hat with waving plumes, his black flag unfurled, with the skull -and crossbones on it, and hear with swelling ecstasy the whisperings, -"It's Tom Sawyer the Pirate!--the Black Avenger of the Spanish Main!" - -Yes, it was settled; his career was determined. He would run away from -home and enter upon it. He would start the very next morning. Therefore -he must now begin to get ready. He would collect his resources -together. He went to a rotten log near at hand and began to dig under -one end of it with his Barlow knife. He soon struck wood that sounded -hollow. He put his hand there and uttered this incantation impressively: - -"What hasn't come here, come! What's here, stay here!" - -Then he scraped away the dirt, and exposed a pine shingle. He took it -up and disclosed a shapely little treasure-house whose bottom and sides -were of shingles. In it lay a marble. Tom's astonishment was boundless! -He scratched his head with a perplexed air, and said: - -"Well, that beats anything!" - -Then he tossed the marble away pettishly, and stood cogitating. The -truth was, that a superstition of his had failed, here, which he and -all his comrades had always looked upon as infallible. If you buried a -marble with certain necessary incantations, and left it alone a -fortnight, and then opened the place with the incantation he had just -used, you would find that all the marbles you had ever lost had -gathered themselves together there, meantime, no matter how widely they -had been separated. But now, this thing had actually and unquestionably -failed. Tom's whole structure of faith was shaken to its foundations. -He had many a time heard of this thing succeeding but never of its -failing before. It did not occur to him that he had tried it several -times before, himself, but could never find the hiding-places -afterward. He puzzled over the matter some time, and finally decided -that some witch had interfered and broken the charm. He thought he -would satisfy himself on that point; so he searched around till he -found a small sandy spot with a little funnel-shaped depression in it. -He laid himself down and put his mouth close to this depression and -called-- - -"Doodle-bug, doodle-bug, tell me what I want to know! Doodle-bug, -doodle-bug, tell me what I want to know!" - -The sand began to work, and presently a small black bug appeared for a -second and then darted under again in a fright. - -"He dasn't tell! So it WAS a witch that done it. I just knowed it." - -He well knew the futility of trying to contend against witches, so he -gave up discouraged. But it occurred to him that he might as well have -the marble he had just thrown away, and therefore he went and made a -patient search for it. But he could not find it. Now he went back to -his treasure-house and carefully placed himself just as he had been -standing when he tossed the marble away; then he took another marble -from his pocket and tossed it in the same way, saying: - -"Brother, go find your brother!" - -He watched where it stopped, and went there and looked. But it must -have fallen short or gone too far; so he tried twice more. The last -repetition was successful. The two marbles lay within a foot of each -other. - -Just here the blast of a toy tin trumpet came faintly down the green -aisles of the forest. Tom flung off his jacket and trousers, turned a -suspender into a belt, raked away some brush behind the rotten log, -disclosing a rude bow and arrow, a lath sword and a tin trumpet, and in -a moment had seized these things and bounded away, barelegged, with -fluttering shirt. He presently halted under a great elm, blew an -answering blast, and then began to tiptoe and look warily out, this way -and that. He said cautiously--to an imaginary company: - -"Hold, my merry men! Keep hid till I blow." - -Now appeared Joe Harper, as airily clad and elaborately armed as Tom. -Tom called: - -"Hold! Who comes here into Sherwood Forest without my pass?" - -"Guy of Guisborne wants no man's pass. Who art thou that--that--" - -"Dares to hold such language," said Tom, prompting--for they talked -"by the book," from memory. - -"Who art thou that dares to hold such language?" - -"I, indeed! I am Robin Hood, as thy caitiff carcase soon shall know." - -"Then art thou indeed that famous outlaw? Right gladly will I dispute -with thee the passes of the merry wood. Have at thee!" - -They took their lath swords, dumped their other traps on the ground, -struck a fencing attitude, foot to foot, and began a grave, careful -combat, "two up and two down." Presently Tom said: - -"Now, if you've got the hang, go it lively!" - -So they "went it lively," panting and perspiring with the work. By and -by Tom shouted: - -"Fall! fall! Why don't you fall?" - -"I sha'n't! Why don't you fall yourself? You're getting the worst of -it." - -"Why, that ain't anything. I can't fall; that ain't the way it is in -the book. The book says, 'Then with one back-handed stroke he slew poor -Guy of Guisborne.' You're to turn around and let me hit you in the -back." - -There was no getting around the authorities, so Joe turned, received -the whack and fell. - -"Now," said Joe, getting up, "you got to let me kill YOU. That's fair." - -"Why, I can't do that, it ain't in the book." - -"Well, it's blamed mean--that's all." - -"Well, say, Joe, you can be Friar Tuck or Much the miller's son, and -lam me with a quarter-staff; or I'll be the Sheriff of Nottingham and -you be Robin Hood a little while and kill me." - -This was satisfactory, and so these adventures were carried out. Then -Tom became Robin Hood again, and was allowed by the treacherous nun to -bleed his strength away through his neglected wound. And at last Joe, -representing a whole tribe of weeping outlaws, dragged him sadly forth, -gave his bow into his feeble hands, and Tom said, "Where this arrow -falls, there bury poor Robin Hood under the greenwood tree." Then he -shot the arrow and fell back and would have died, but he lit on a -nettle and sprang up too gaily for a corpse. - -The boys dressed themselves, hid their accoutrements, and went off -grieving that there were no outlaws any more, and wondering what modern -civilization could claim to have done to compensate for their loss. -They said they would rather be outlaws a year in Sherwood Forest than -President of the United States forever. - - - -CHAPTER IX - -AT half-past nine, that night, Tom and Sid were sent to bed, as usual. -They said their prayers, and Sid was soon asleep. Tom lay awake and -waited, in restless impatience. When it seemed to him that it must be -nearly daylight, he heard the clock strike ten! This was despair. He -would have tossed and fidgeted, as his nerves demanded, but he was -afraid he might wake Sid. So he lay still, and stared up into the dark. -Everything was dismally still. By and by, out of the stillness, little, -scarcely perceptible noises began to emphasize themselves. The ticking -of the clock began to bring itself into notice. Old beams began to -crack mysteriously. The stairs creaked faintly. Evidently spirits were -abroad. A measured, muffled snore issued from Aunt Polly's chamber. And -now the tiresome chirping of a cricket that no human ingenuity could -locate, began. Next the ghastly ticking of a deathwatch in the wall at -the bed's head made Tom shudder--it meant that somebody's days were -numbered. Then the howl of a far-off dog rose on the night air, and was -answered by a fainter howl from a remoter distance. Tom was in an -agony. At last he was satisfied that time had ceased and eternity -begun; he began to doze, in spite of himself; the clock chimed eleven, -but he did not hear it. And then there came, mingling with his -half-formed dreams, a most melancholy caterwauling. The raising of a -neighboring window disturbed him. A cry of "Scat! you devil!" and the -crash of an empty bottle against the back of his aunt's woodshed -brought him wide awake, and a single minute later he was dressed and -out of the window and creeping along the roof of the "ell" on all -fours. He "meow'd" with caution once or twice, as he went; then jumped -to the roof of the woodshed and thence to the ground. Huckleberry Finn -was there, with his dead cat. The boys moved off and disappeared in the -gloom. At the end of half an hour they were wading through the tall -grass of the graveyard. - -It was a graveyard of the old-fashioned Western kind. It was on a -hill, about a mile and a half from the village. It had a crazy board -fence around it, which leaned inward in places, and outward the rest of -the time, but stood upright nowhere. Grass and weeds grew rank over the -whole cemetery. All the old graves were sunken in, there was not a -tombstone on the place; round-topped, worm-eaten boards staggered over -the graves, leaning for support and finding none. "Sacred to the memory -of" So-and-So had been painted on them once, but it could no longer -have been read, on the most of them, now, even if there had been light. - -A faint wind moaned through the trees, and Tom feared it might be the -spirits of the dead, complaining at being disturbed. The boys talked -little, and only under their breath, for the time and the place and the -pervading solemnity and silence oppressed their spirits. They found the -sharp new heap they were seeking, and ensconced themselves within the -protection of three great elms that grew in a bunch within a few feet -of the grave. - -Then they waited in silence for what seemed a long time. The hooting -of a distant owl was all the sound that troubled the dead stillness. -Tom's reflections grew oppressive. He must force some talk. So he said -in a whisper: - -"Hucky, do you believe the dead people like it for us to be here?" - -Huckleberry whispered: - -"I wisht I knowed. It's awful solemn like, AIN'T it?" - -"I bet it is." - -There was a considerable pause, while the boys canvassed this matter -inwardly. Then Tom whispered: - -"Say, Hucky--do you reckon Hoss Williams hears us talking?" - -"O' course he does. Least his sperrit does." - -Tom, after a pause: - -"I wish I'd said Mister Williams. But I never meant any harm. -Everybody calls him Hoss." - -"A body can't be too partic'lar how they talk 'bout these-yer dead -people, Tom." - -This was a damper, and conversation died again. - -Presently Tom seized his comrade's arm and said: - -"Sh!" - -"What is it, Tom?" And the two clung together with beating hearts. - -"Sh! There 'tis again! Didn't you hear it?" - -"I--" - -"There! Now you hear it." - -"Lord, Tom, they're coming! They're coming, sure. What'll we do?" - -"I dono. Think they'll see us?" - -"Oh, Tom, they can see in the dark, same as cats. I wisht I hadn't -come." - -"Oh, don't be afeard. I don't believe they'll bother us. We ain't -doing any harm. If we keep perfectly still, maybe they won't notice us -at all." - -"I'll try to, Tom, but, Lord, I'm all of a shiver." - -"Listen!" - -The boys bent their heads together and scarcely breathed. A muffled -sound of voices floated up from the far end of the graveyard. - -"Look! See there!" whispered Tom. "What is it?" - -"It's devil-fire. Oh, Tom, this is awful." - -Some vague figures approached through the gloom, swinging an -old-fashioned tin lantern that freckled the ground with innumerable -little spangles of light. Presently Huckleberry whispered with a -shudder: - -"It's the devils sure enough. Three of 'em! Lordy, Tom, we're goners! -Can you pray?" - -"I'll try, but don't you be afeard. They ain't going to hurt us. 'Now -I lay me down to sleep, I--'" - -"Sh!" - -"What is it, Huck?" - -"They're HUMANS! One of 'em is, anyway. One of 'em's old Muff Potter's -voice." - -"No--'tain't so, is it?" - -"I bet I know it. Don't you stir nor budge. He ain't sharp enough to -notice us. Drunk, the same as usual, likely--blamed old rip!" - -"All right, I'll keep still. Now they're stuck. Can't find it. Here -they come again. Now they're hot. Cold again. Hot again. Red hot! -They're p'inted right, this time. Say, Huck, I know another o' them -voices; it's Injun Joe." - -"That's so--that murderin' half-breed! I'd druther they was devils a -dern sight. What kin they be up to?" - -The whisper died wholly out, now, for the three men had reached the -grave and stood within a few feet of the boys' hiding-place. - -"Here it is," said the third voice; and the owner of it held the -lantern up and revealed the face of young Doctor Robinson. - -Potter and Injun Joe were carrying a handbarrow with a rope and a -couple of shovels on it. They cast down their load and began to open -the grave. The doctor put the lantern at the head of the grave and came -and sat down with his back against one of the elm trees. He was so -close the boys could have touched him. - -"Hurry, men!" he said, in a low voice; "the moon might come out at any -moment." - -They growled a response and went on digging. For some time there was -no noise but the grating sound of the spades discharging their freight -of mould and gravel. It was very monotonous. Finally a spade struck -upon the coffin with a dull woody accent, and within another minute or -two the men had hoisted it out on the ground. They pried off the lid -with their shovels, got out the body and dumped it rudely on the -ground. The moon drifted from behind the clouds and exposed the pallid -face. The barrow was got ready and the corpse placed on it, covered -with a blanket, and bound to its place with the rope. Potter took out a -large spring-knife and cut off the dangling end of the rope and then -said: - -"Now the cussed thing's ready, Sawbones, and you'll just out with -another five, or here she stays." - -"That's the talk!" said Injun Joe. - -"Look here, what does this mean?" said the doctor. "You required your -pay in advance, and I've paid you." - -"Yes, and you done more than that," said Injun Joe, approaching the -doctor, who was now standing. "Five years ago you drove me away from -your father's kitchen one night, when I come to ask for something to -eat, and you said I warn't there for any good; and when I swore I'd get -even with you if it took a hundred years, your father had me jailed for -a vagrant. Did you think I'd forget? The Injun blood ain't in me for -nothing. And now I've GOT you, and you got to SETTLE, you know!" - -He was threatening the doctor, with his fist in his face, by this -time. The doctor struck out suddenly and stretched the ruffian on the -ground. Potter dropped his knife, and exclaimed: - -"Here, now, don't you hit my pard!" and the next moment he had -grappled with the doctor and the two were struggling with might and -main, trampling the grass and tearing the ground with their heels. -Injun Joe sprang to his feet, his eyes flaming with passion, snatched -up Potter's knife, and went creeping, catlike and stooping, round and -round about the combatants, seeking an opportunity. All at once the -doctor flung himself free, seized the heavy headboard of Williams' -grave and felled Potter to the earth with it--and in the same instant -the half-breed saw his chance and drove the knife to the hilt in the -young man's breast. He reeled and fell partly upon Potter, flooding him -with his blood, and in the same moment the clouds blotted out the -dreadful spectacle and the two frightened boys went speeding away in -the dark. - -Presently, when the moon emerged again, Injun Joe was standing over -the two forms, contemplating them. The doctor murmured inarticulately, -gave a long gasp or two and was still. The half-breed muttered: - -"THAT score is settled--damn you." - -Then he robbed the body. After which he put the fatal knife in -Potter's open right hand, and sat down on the dismantled coffin. Three ---four--five minutes passed, and then Potter began to stir and moan. His -hand closed upon the knife; he raised it, glanced at it, and let it -fall, with a shudder. Then he sat up, pushing the body from him, and -gazed at it, and then around him, confusedly. His eyes met Joe's. - -"Lord, how is this, Joe?" he said. - -"It's a dirty business," said Joe, without moving. - -"What did you do it for?" - -"I! I never done it!" - -"Look here! That kind of talk won't wash." - -Potter trembled and grew white. - -"I thought I'd got sober. I'd no business to drink to-night. But it's -in my head yet--worse'n when we started here. I'm all in a muddle; -can't recollect anything of it, hardly. Tell me, Joe--HONEST, now, old -feller--did I do it? Joe, I never meant to--'pon my soul and honor, I -never meant to, Joe. Tell me how it was, Joe. Oh, it's awful--and him -so young and promising." - -"Why, you two was scuffling, and he fetched you one with the headboard -and you fell flat; and then up you come, all reeling and staggering -like, and snatched the knife and jammed it into him, just as he fetched -you another awful clip--and here you've laid, as dead as a wedge til -now." - -"Oh, I didn't know what I was a-doing. I wish I may die this minute if -I did. It was all on account of the whiskey and the excitement, I -reckon. I never used a weepon in my life before, Joe. I've fought, but -never with weepons. They'll all say that. Joe, don't tell! Say you -won't tell, Joe--that's a good feller. I always liked you, Joe, and -stood up for you, too. Don't you remember? You WON'T tell, WILL you, -Joe?" And the poor creature dropped on his knees before the stolid -murderer, and clasped his appealing hands. - -"No, you've always been fair and square with me, Muff Potter, and I -won't go back on you. There, now, that's as fair as a man can say." - -"Oh, Joe, you're an angel. I'll bless you for this the longest day I -live." And Potter began to cry. - -"Come, now, that's enough of that. This ain't any time for blubbering. -You be off yonder way and I'll go this. Move, now, and don't leave any -tracks behind you." - -Potter started on a trot that quickly increased to a run. The -half-breed stood looking after him. He muttered: - -"If he's as much stunned with the lick and fuddled with the rum as he -had the look of being, he won't think of the knife till he's gone so -far he'll be afraid to come back after it to such a place by himself ---chicken-heart!" - -Two or three minutes later the murdered man, the blanketed corpse, the -lidless coffin, and the open grave were under no inspection but the -moon's. The stillness was complete again, too. - - - -CHAPTER X - -THE two boys flew on and on, toward the village, speechless with -horror. They glanced backward over their shoulders from time to time, -apprehensively, as if they feared they might be followed. Every stump -that started up in their path seemed a man and an enemy, and made them -catch their breath; and as they sped by some outlying cottages that lay -near the village, the barking of the aroused watch-dogs seemed to give -wings to their feet. - -"If we can only get to the old tannery before we break down!" -whispered Tom, in short catches between breaths. "I can't stand it much -longer." - -Huckleberry's hard pantings were his only reply, and the boys fixed -their eyes on the goal of their hopes and bent to their work to win it. -They gained steadily on it, and at last, breast to breast, they burst -through the open door and fell grateful and exhausted in the sheltering -shadows beyond. By and by their pulses slowed down, and Tom whispered: - -"Huckleberry, what do you reckon'll come of this?" - -"If Doctor Robinson dies, I reckon hanging'll come of it." - -"Do you though?" - -"Why, I KNOW it, Tom." - -Tom thought a while, then he said: - -"Who'll tell? We?" - -"What are you talking about? S'pose something happened and Injun Joe -DIDN'T hang? Why, he'd kill us some time or other, just as dead sure as -we're a laying here." - -"That's just what I was thinking to myself, Huck." - -"If anybody tells, let Muff Potter do it, if he's fool enough. He's -generally drunk enough." - -Tom said nothing--went on thinking. Presently he whispered: - -"Huck, Muff Potter don't know it. How can he tell?" - -"What's the reason he don't know it?" - -"Because he'd just got that whack when Injun Joe done it. D'you reckon -he could see anything? D'you reckon he knowed anything?" - -"By hokey, that's so, Tom!" - -"And besides, look-a-here--maybe that whack done for HIM!" - -"No, 'taint likely, Tom. He had liquor in him; I could see that; and -besides, he always has. Well, when pap's full, you might take and belt -him over the head with a church and you couldn't phase him. He says so, -his own self. So it's the same with Muff Potter, of course. But if a -man was dead sober, I reckon maybe that whack might fetch him; I dono." - -After another reflective silence, Tom said: - -"Hucky, you sure you can keep mum?" - -"Tom, we GOT to keep mum. You know that. That Injun devil wouldn't -make any more of drownding us than a couple of cats, if we was to -squeak 'bout this and they didn't hang him. Now, look-a-here, Tom, less -take and swear to one another--that's what we got to do--swear to keep -mum." - -"I'm agreed. It's the best thing. Would you just hold hands and swear -that we--" - -"Oh no, that wouldn't do for this. That's good enough for little -rubbishy common things--specially with gals, cuz THEY go back on you -anyway, and blab if they get in a huff--but there orter be writing -'bout a big thing like this. And blood." - -Tom's whole being applauded this idea. It was deep, and dark, and -awful; the hour, the circumstances, the surroundings, were in keeping -with it. He picked up a clean pine shingle that lay in the moonlight, -took a little fragment of "red keel" out of his pocket, got the moon on -his work, and painfully scrawled these lines, emphasizing each slow -down-stroke by clamping his tongue between his teeth, and letting up -the pressure on the up-strokes. [See next page.] - - "Huck Finn and - Tom Sawyer swears - they will keep mum - about This and They - wish They may Drop - down dead in Their - Tracks if They ever - Tell and Rot." - -Huckleberry was filled with admiration of Tom's facility in writing, -and the sublimity of his language. He at once took a pin from his lapel -and was going to prick his flesh, but Tom said: - -"Hold on! Don't do that. A pin's brass. It might have verdigrease on -it." - -"What's verdigrease?" - -"It's p'ison. That's what it is. You just swaller some of it once ---you'll see." - -So Tom unwound the thread from one of his needles, and each boy -pricked the ball of his thumb and squeezed out a drop of blood. In -time, after many squeezes, Tom managed to sign his initials, using the -ball of his little finger for a pen. Then he showed Huckleberry how to -make an H and an F, and the oath was complete. They buried the shingle -close to the wall, with some dismal ceremonies and incantations, and -the fetters that bound their tongues were considered to be locked and -the key thrown away. - -A figure crept stealthily through a break in the other end of the -ruined building, now, but they did not notice it. - -"Tom," whispered Huckleberry, "does this keep us from EVER telling ---ALWAYS?" - -"Of course it does. It don't make any difference WHAT happens, we got -to keep mum. We'd drop down dead--don't YOU know that?" - -"Yes, I reckon that's so." - -They continued to whisper for some little time. Presently a dog set up -a long, lugubrious howl just outside--within ten feet of them. The boys -clasped each other suddenly, in an agony of fright. - -"Which of us does he mean?" gasped Huckleberry. - -"I dono--peep through the crack. Quick!" - -"No, YOU, Tom!" - -"I can't--I can't DO it, Huck!" - -"Please, Tom. There 'tis again!" - -"Oh, lordy, I'm thankful!" whispered Tom. "I know his voice. It's Bull -Harbison." * - -[* If Mr. Harbison owned a slave named Bull, Tom would have spoken of -him as "Harbison's Bull," but a son or a dog of that name was "Bull -Harbison."] - -"Oh, that's good--I tell you, Tom, I was most scared to death; I'd a -bet anything it was a STRAY dog." - -The dog howled again. The boys' hearts sank once more. - -"Oh, my! that ain't no Bull Harbison!" whispered Huckleberry. "DO, Tom!" - -Tom, quaking with fear, yielded, and put his eye to the crack. His -whisper was hardly audible when he said: - -"Oh, Huck, IT S A STRAY DOG!" - -"Quick, Tom, quick! Who does he mean?" - -"Huck, he must mean us both--we're right together." - -"Oh, Tom, I reckon we're goners. I reckon there ain't no mistake 'bout -where I'LL go to. I been so wicked." - -"Dad fetch it! This comes of playing hookey and doing everything a -feller's told NOT to do. I might a been good, like Sid, if I'd a tried ---but no, I wouldn't, of course. But if ever I get off this time, I lay -I'll just WALLER in Sunday-schools!" And Tom began to snuffle a little. - -"YOU bad!" and Huckleberry began to snuffle too. "Consound it, Tom -Sawyer, you're just old pie, 'longside o' what I am. Oh, LORDY, lordy, -lordy, I wisht I only had half your chance." - -Tom choked off and whispered: - -"Look, Hucky, look! He's got his BACK to us!" - -Hucky looked, with joy in his heart. - -"Well, he has, by jingoes! Did he before?" - -"Yes, he did. But I, like a fool, never thought. Oh, this is bully, -you know. NOW who can he mean?" - -The howling stopped. Tom pricked up his ears. - -"Sh! What's that?" he whispered. - -"Sounds like--like hogs grunting. No--it's somebody snoring, Tom." - -"That IS it! Where 'bouts is it, Huck?" - -"I bleeve it's down at 'tother end. Sounds so, anyway. Pap used to -sleep there, sometimes, 'long with the hogs, but laws bless you, he -just lifts things when HE snores. Besides, I reckon he ain't ever -coming back to this town any more." - -The spirit of adventure rose in the boys' souls once more. - -"Hucky, do you das't to go if I lead?" - -"I don't like to, much. Tom, s'pose it's Injun Joe!" - -Tom quailed. But presently the temptation rose up strong again and the -boys agreed to try, with the understanding that they would take to -their heels if the snoring stopped. So they went tiptoeing stealthily -down, the one behind the other. When they had got to within five steps -of the snorer, Tom stepped on a stick, and it broke with a sharp snap. -The man moaned, writhed a little, and his face came into the moonlight. -It was Muff Potter. The boys' hearts had stood still, and their hopes -too, when the man moved, but their fears passed away now. They tiptoed -out, through the broken weather-boarding, and stopped at a little -distance to exchange a parting word. That long, lugubrious howl rose on -the night air again! They turned and saw the strange dog standing -within a few feet of where Potter was lying, and FACING Potter, with -his nose pointing heavenward. - -"Oh, geeminy, it's HIM!" exclaimed both boys, in a breath. - -"Say, Tom--they say a stray dog come howling around Johnny Miller's -house, 'bout midnight, as much as two weeks ago; and a whippoorwill -come in and lit on the banisters and sung, the very same evening; and -there ain't anybody dead there yet." - -"Well, I know that. And suppose there ain't. Didn't Gracie Miller fall -in the kitchen fire and burn herself terrible the very next Saturday?" - -"Yes, but she ain't DEAD. And what's more, she's getting better, too." - -"All right, you wait and see. She's a goner, just as dead sure as Muff -Potter's a goner. That's what the niggers say, and they know all about -these kind of things, Huck." - -Then they separated, cogitating. When Tom crept in at his bedroom -window the night was almost spent. He undressed with excessive caution, -and fell asleep congratulating himself that nobody knew of his -escapade. He was not aware that the gently-snoring Sid was awake, and -had been so for an hour. - -When Tom awoke, Sid was dressed and gone. There was a late look in the -light, a late sense in the atmosphere. He was startled. Why had he not -been called--persecuted till he was up, as usual? The thought filled -him with bodings. Within five minutes he was dressed and down-stairs, -feeling sore and drowsy. The family were still at table, but they had -finished breakfast. There was no voice of rebuke; but there were -averted eyes; there was a silence and an air of solemnity that struck a -chill to the culprit's heart. He sat down and tried to seem gay, but it -was up-hill work; it roused no smile, no response, and he lapsed into -silence and let his heart sink down to the depths. - -After breakfast his aunt took him aside, and Tom almost brightened in -the hope that he was going to be flogged; but it was not so. His aunt -wept over him and asked him how he could go and break her old heart so; -and finally told him to go on, and ruin himself and bring her gray -hairs with sorrow to the grave, for it was no use for her to try any -more. This was worse than a thousand whippings, and Tom's heart was -sorer now than his body. He cried, he pleaded for forgiveness, promised -to reform over and over again, and then received his dismissal, feeling -that he had won but an imperfect forgiveness and established but a -feeble confidence. - -He left the presence too miserable to even feel revengeful toward Sid; -and so the latter's prompt retreat through the back gate was -unnecessary. He moped to school gloomy and sad, and took his flogging, -along with Joe Harper, for playing hookey the day before, with the air -of one whose heart was busy with heavier woes and wholly dead to -trifles. Then he betook himself to his seat, rested his elbows on his -desk and his jaws in his hands, and stared at the wall with the stony -stare of suffering that has reached the limit and can no further go. -His elbow was pressing against some hard substance. After a long time -he slowly and sadly changed his position, and took up this object with -a sigh. It was in a paper. He unrolled it. A long, lingering, colossal -sigh followed, and his heart broke. It was his brass andiron knob! - -This final feather broke the camel's back. - - - -CHAPTER XI - -CLOSE upon the hour of noon the whole village was suddenly electrified -with the ghastly news. No need of the as yet undreamed-of telegraph; -the tale flew from man to man, from group to group, from house to -house, with little less than telegraphic speed. Of course the -schoolmaster gave holiday for that afternoon; the town would have -thought strangely of him if he had not. - -A gory knife had been found close to the murdered man, and it had been -recognized by somebody as belonging to Muff Potter--so the story ran. -And it was said that a belated citizen had come upon Potter washing -himself in the "branch" about one or two o'clock in the morning, and -that Potter had at once sneaked off--suspicious circumstances, -especially the washing which was not a habit with Potter. It was also -said that the town had been ransacked for this "murderer" (the public -are not slow in the matter of sifting evidence and arriving at a -verdict), but that he could not be found. Horsemen had departed down -all the roads in every direction, and the Sheriff "was confident" that -he would be captured before night. - -All the town was drifting toward the graveyard. Tom's heartbreak -vanished and he joined the procession, not because he would not a -thousand times rather go anywhere else, but because an awful, -unaccountable fascination drew him on. Arrived at the dreadful place, -he wormed his small body through the crowd and saw the dismal -spectacle. It seemed to him an age since he was there before. Somebody -pinched his arm. He turned, and his eyes met Huckleberry's. Then both -looked elsewhere at once, and wondered if anybody had noticed anything -in their mutual glance. But everybody was talking, and intent upon the -grisly spectacle before them. - -"Poor fellow!" "Poor young fellow!" "This ought to be a lesson to -grave robbers!" "Muff Potter'll hang for this if they catch him!" This -was the drift of remark; and the minister said, "It was a judgment; His -hand is here." - -Now Tom shivered from head to heel; for his eye fell upon the stolid -face of Injun Joe. At this moment the crowd began to sway and struggle, -and voices shouted, "It's him! it's him! he's coming himself!" - -"Who? Who?" from twenty voices. - -"Muff Potter!" - -"Hallo, he's stopped!--Look out, he's turning! Don't let him get away!" - -People in the branches of the trees over Tom's head said he wasn't -trying to get away--he only looked doubtful and perplexed. - -"Infernal impudence!" said a bystander; "wanted to come and take a -quiet look at his work, I reckon--didn't expect any company." - -The crowd fell apart, now, and the Sheriff came through, -ostentatiously leading Potter by the arm. The poor fellow's face was -haggard, and his eyes showed the fear that was upon him. When he stood -before the murdered man, he shook as with a palsy, and he put his face -in his hands and burst into tears. - -"I didn't do it, friends," he sobbed; "'pon my word and honor I never -done it." - -"Who's accused you?" shouted a voice. - -This shot seemed to carry home. Potter lifted his face and looked -around him with a pathetic hopelessness in his eyes. He saw Injun Joe, -and exclaimed: - -"Oh, Injun Joe, you promised me you'd never--" - -"Is that your knife?" and it was thrust before him by the Sheriff. - -Potter would have fallen if they had not caught him and eased him to -the ground. Then he said: - -"Something told me 't if I didn't come back and get--" He shuddered; -then waved his nerveless hand with a vanquished gesture and said, "Tell -'em, Joe, tell 'em--it ain't any use any more." - -Then Huckleberry and Tom stood dumb and staring, and heard the -stony-hearted liar reel off his serene statement, they expecting every -moment that the clear sky would deliver God's lightnings upon his head, -and wondering to see how long the stroke was delayed. And when he had -finished and still stood alive and whole, their wavering impulse to -break their oath and save the poor betrayed prisoner's life faded and -vanished away, for plainly this miscreant had sold himself to Satan and -it would be fatal to meddle with the property of such a power as that. - -"Why didn't you leave? What did you want to come here for?" somebody -said. - -"I couldn't help it--I couldn't help it," Potter moaned. "I wanted to -run away, but I couldn't seem to come anywhere but here." And he fell -to sobbing again. - -Injun Joe repeated his statement, just as calmly, a few minutes -afterward on the inquest, under oath; and the boys, seeing that the -lightnings were still withheld, were confirmed in their belief that Joe -had sold himself to the devil. He was now become, to them, the most -balefully interesting object they had ever looked upon, and they could -not take their fascinated eyes from his face. - -They inwardly resolved to watch him nights, when opportunity should -offer, in the hope of getting a glimpse of his dread master. - -Injun Joe helped to raise the body of the murdered man and put it in a -wagon for removal; and it was whispered through the shuddering crowd -that the wound bled a little! The boys thought that this happy -circumstance would turn suspicion in the right direction; but they were -disappointed, for more than one villager remarked: - -"It was within three feet of Muff Potter when it done it." - -Tom's fearful secret and gnawing conscience disturbed his sleep for as -much as a week after this; and at breakfast one morning Sid said: - -"Tom, you pitch around and talk in your sleep so much that you keep me -awake half the time." - -Tom blanched and dropped his eyes. - -"It's a bad sign," said Aunt Polly, gravely. "What you got on your -mind, Tom?" - -"Nothing. Nothing 't I know of." But the boy's hand shook so that he -spilled his coffee. - -"And you do talk such stuff," Sid said. "Last night you said, 'It's -blood, it's blood, that's what it is!' You said that over and over. And -you said, 'Don't torment me so--I'll tell!' Tell WHAT? What is it -you'll tell?" - -Everything was swimming before Tom. There is no telling what might -have happened, now, but luckily the concern passed out of Aunt Polly's -face and she came to Tom's relief without knowing it. She said: - -"Sho! It's that dreadful murder. I dream about it most every night -myself. Sometimes I dream it's me that done it." - -Mary said she had been affected much the same way. Sid seemed -satisfied. Tom got out of the presence as quick as he plausibly could, -and after that he complained of toothache for a week, and tied up his -jaws every night. He never knew that Sid lay nightly watching, and -frequently slipped the bandage free and then leaned on his elbow -listening a good while at a time, and afterward slipped the bandage -back to its place again. Tom's distress of mind wore off gradually and -the toothache grew irksome and was discarded. If Sid really managed to -make anything out of Tom's disjointed mutterings, he kept it to himself. - -It seemed to Tom that his schoolmates never would get done holding -inquests on dead cats, and thus keeping his trouble present to his -mind. Sid noticed that Tom never was coroner at one of these inquiries, -though it had been his habit to take the lead in all new enterprises; -he noticed, too, that Tom never acted as a witness--and that was -strange; and Sid did not overlook the fact that Tom even showed a -marked aversion to these inquests, and always avoided them when he -could. Sid marvelled, but said nothing. However, even inquests went out -of vogue at last, and ceased to torture Tom's conscience. - -Every day or two, during this time of sorrow, Tom watched his -opportunity and went to the little grated jail-window and smuggled such -small comforts through to the "murderer" as he could get hold of. The -jail was a trifling little brick den that stood in a marsh at the edge -of the village, and no guards were afforded for it; indeed, it was -seldom occupied. These offerings greatly helped to ease Tom's -conscience. - -The villagers had a strong desire to tar-and-feather Injun Joe and -ride him on a rail, for body-snatching, but so formidable was his -character that nobody could be found who was willing to take the lead -in the matter, so it was dropped. He had been careful to begin both of -his inquest-statements with the fight, without confessing the -grave-robbery that preceded it; therefore it was deemed wisest not -to try the case in the courts at present. - - - -CHAPTER XII - -ONE of the reasons why Tom's mind had drifted away from its secret -troubles was, that it had found a new and weighty matter to interest -itself about. Becky Thatcher had stopped coming to school. Tom had -struggled with his pride a few days, and tried to "whistle her down the -wind," but failed. He began to find himself hanging around her father's -house, nights, and feeling very miserable. She was ill. What if she -should die! There was distraction in the thought. He no longer took an -interest in war, nor even in piracy. The charm of life was gone; there -was nothing but dreariness left. He put his hoop away, and his bat; -there was no joy in them any more. His aunt was concerned. She began to -try all manner of remedies on him. She was one of those people who are -infatuated with patent medicines and all new-fangled methods of -producing health or mending it. She was an inveterate experimenter in -these things. When something fresh in this line came out she was in a -fever, right away, to try it; not on herself, for she was never ailing, -but on anybody else that came handy. She was a subscriber for all the -"Health" periodicals and phrenological frauds; and the solemn ignorance -they were inflated with was breath to her nostrils. All the "rot" they -contained about ventilation, and how to go to bed, and how to get up, -and what to eat, and what to drink, and how much exercise to take, and -what frame of mind to keep one's self in, and what sort of clothing to -wear, was all gospel to her, and she never observed that her -health-journals of the current month customarily upset everything they -had recommended the month before. She was as simple-hearted and honest -as the day was long, and so she was an easy victim. She gathered -together her quack periodicals and her quack medicines, and thus armed -with death, went about on her pale horse, metaphorically speaking, with -"hell following after." But she never suspected that she was not an -angel of healing and the balm of Gilead in disguise, to the suffering -neighbors. - -The water treatment was new, now, and Tom's low condition was a -windfall to her. She had him out at daylight every morning, stood him -up in the woodshed and drowned him with a deluge of cold water; then -she scrubbed him down with a towel like a file, and so brought him to; -then she rolled him up in a wet sheet and put him away under blankets -till she sweated his soul clean and "the yellow stains of it came -through his pores"--as Tom said. - -Yet notwithstanding all this, the boy grew more and more melancholy -and pale and dejected. She added hot baths, sitz baths, shower baths, -and plunges. The boy remained as dismal as a hearse. She began to -assist the water with a slim oatmeal diet and blister-plasters. She -calculated his capacity as she would a jug's, and filled him up every -day with quack cure-alls. - -Tom had become indifferent to persecution by this time. This phase -filled the old lady's heart with consternation. This indifference must -be broken up at any cost. Now she heard of Pain-killer for the first -time. She ordered a lot at once. She tasted it and was filled with -gratitude. It was simply fire in a liquid form. She dropped the water -treatment and everything else, and pinned her faith to Pain-killer. She -gave Tom a teaspoonful and watched with the deepest anxiety for the -result. Her troubles were instantly at rest, her soul at peace again; -for the "indifference" was broken up. The boy could not have shown a -wilder, heartier interest, if she had built a fire under him. - -Tom felt that it was time to wake up; this sort of life might be -romantic enough, in his blighted condition, but it was getting to have -too little sentiment and too much distracting variety about it. So he -thought over various plans for relief, and finally hit pon that of -professing to be fond of Pain-killer. He asked for it so often that he -became a nuisance, and his aunt ended by telling him to help himself -and quit bothering her. If it had been Sid, she would have had no -misgivings to alloy her delight; but since it was Tom, she watched the -bottle clandestinely. She found that the medicine did really diminish, -but it did not occur to her that the boy was mending the health of a -crack in the sitting-room floor with it. - -One day Tom was in the act of dosing the crack when his aunt's yellow -cat came along, purring, eying the teaspoon avariciously, and begging -for a taste. Tom said: - -"Don't ask for it unless you want it, Peter." - -But Peter signified that he did want it. - -"You better make sure." - -Peter was sure. - -"Now you've asked for it, and I'll give it to you, because there ain't -anything mean about me; but if you find you don't like it, you mustn't -blame anybody but your own self." - -Peter was agreeable. So Tom pried his mouth open and poured down the -Pain-killer. Peter sprang a couple of yards in the air, and then -delivered a war-whoop and set off round and round the room, banging -against furniture, upsetting flower-pots, and making general havoc. -Next he rose on his hind feet and pranced around, in a frenzy of -enjoyment, with his head over his shoulder and his voice proclaiming -his unappeasable happiness. Then he went tearing around the house again -spreading chaos and destruction in his path. Aunt Polly entered in time -to see him throw a few double summersets, deliver a final mighty -hurrah, and sail through the open window, carrying the rest of the -flower-pots with him. The old lady stood petrified with astonishment, -peering over her glasses; Tom lay on the floor expiring with laughter. - -"Tom, what on earth ails that cat?" - -"I don't know, aunt," gasped the boy. - -"Why, I never see anything like it. What did make him act so?" - -"Deed I don't know, Aunt Polly; cats always act so when they're having -a good time." - -"They do, do they?" There was something in the tone that made Tom -apprehensive. - -"Yes'm. That is, I believe they do." - -"You DO?" - -"Yes'm." - -The old lady was bending down, Tom watching, with interest emphasized -by anxiety. Too late he divined her "drift." The handle of the telltale -teaspoon was visible under the bed-valance. Aunt Polly took it, held it -up. Tom winced, and dropped his eyes. Aunt Polly raised him by the -usual handle--his ear--and cracked his head soundly with her thimble. - -"Now, sir, what did you want to treat that poor dumb beast so, for?" - -"I done it out of pity for him--because he hadn't any aunt." - -"Hadn't any aunt!--you numskull. What has that got to do with it?" - -"Heaps. Because if he'd had one she'd a burnt him out herself! She'd a -roasted his bowels out of him 'thout any more feeling than if he was a -human!" - -Aunt Polly felt a sudden pang of remorse. This was putting the thing -in a new light; what was cruelty to a cat MIGHT be cruelty to a boy, -too. She began to soften; she felt sorry. Her eyes watered a little, -and she put her hand on Tom's head and said gently: - -"I was meaning for the best, Tom. And, Tom, it DID do you good." - -Tom looked up in her face with just a perceptible twinkle peeping -through his gravity. - -"I know you was meaning for the best, aunty, and so was I with Peter. -It done HIM good, too. I never see him get around so since--" - -"Oh, go 'long with you, Tom, before you aggravate me again. And you -try and see if you can't be a good boy, for once, and you needn't take -any more medicine." - -Tom reached school ahead of time. It was noticed that this strange -thing had been occurring every day latterly. And now, as usual of late, -he hung about the gate of the schoolyard instead of playing with his -comrades. He was sick, he said, and he looked it. He tried to seem to -be looking everywhere but whither he really was looking--down the road. -Presently Jeff Thatcher hove in sight, and Tom's face lighted; he gazed -a moment, and then turned sorrowfully away. When Jeff arrived, Tom -accosted him; and "led up" warily to opportunities for remark about -Becky, but the giddy lad never could see the bait. Tom watched and -watched, hoping whenever a frisking frock came in sight, and hating the -owner of it as soon as he saw she was not the right one. At last frocks -ceased to appear, and he dropped hopelessly into the dumps; he entered -the empty schoolhouse and sat down to suffer. Then one more frock -passed in at the gate, and Tom's heart gave a great bound. The next -instant he was out, and "going on" like an Indian; yelling, laughing, -chasing boys, jumping over the fence at risk of life and limb, throwing -handsprings, standing on his head--doing all the heroic things he could -conceive of, and keeping a furtive eye out, all the while, to see if -Becky Thatcher was noticing. But she seemed to be unconscious of it -all; she never looked. Could it be possible that she was not aware that -he was there? He carried his exploits to her immediate vicinity; came -war-whooping around, snatched a boy's cap, hurled it to the roof of the -schoolhouse, broke through a group of boys, tumbling them in every -direction, and fell sprawling, himself, under Becky's nose, almost -upsetting her--and she turned, with her nose in the air, and he heard -her say: "Mf! some people think they're mighty smart--always showing -off!" - -Tom's cheeks burned. He gathered himself up and sneaked off, crushed -and crestfallen. - - - -CHAPTER XIII - -TOM'S mind was made up now. He was gloomy and desperate. He was a -forsaken, friendless boy, he said; nobody loved him; when they found -out what they had driven him to, perhaps they would be sorry; he had -tried to do right and get along, but they would not let him; since -nothing would do them but to be rid of him, let it be so; and let them -blame HIM for the consequences--why shouldn't they? What right had the -friendless to complain? Yes, they had forced him to it at last: he -would lead a life of crime. There was no choice. - -By this time he was far down Meadow Lane, and the bell for school to -"take up" tinkled faintly upon his ear. He sobbed, now, to think he -should never, never hear that old familiar sound any more--it was very -hard, but it was forced on him; since he was driven out into the cold -world, he must submit--but he forgave them. Then the sobs came thick -and fast. - -Just at this point he met his soul's sworn comrade, Joe Harper ---hard-eyed, and with evidently a great and dismal purpose in his heart. -Plainly here were "two souls with but a single thought." Tom, wiping -his eyes with his sleeve, began to blubber out something about a -resolution to escape from hard usage and lack of sympathy at home by -roaming abroad into the great world never to return; and ended by -hoping that Joe would not forget him. - -But it transpired that this was a request which Joe had just been -going to make of Tom, and had come to hunt him up for that purpose. His -mother had whipped him for drinking some cream which he had never -tasted and knew nothing about; it was plain that she was tired of him -and wished him to go; if she felt that way, there was nothing for him -to do but succumb; he hoped she would be happy, and never regret having -driven her poor boy out into the unfeeling world to suffer and die. - -As the two boys walked sorrowing along, they made a new compact to -stand by each other and be brothers and never separate till death -relieved them of their troubles. Then they began to lay their plans. -Joe was for being a hermit, and living on crusts in a remote cave, and -dying, some time, of cold and want and grief; but after listening to -Tom, he conceded that there were some conspicuous advantages about a -life of crime, and so he consented to be a pirate. - -Three miles below St. Petersburg, at a point where the Mississippi -River was a trifle over a mile wide, there was a long, narrow, wooded -island, with a shallow bar at the head of it, and this offered well as -a rendezvous. It was not inhabited; it lay far over toward the further -shore, abreast a dense and almost wholly unpeopled forest. So Jackson's -Island was chosen. Who were to be the subjects of their piracies was a -matter that did not occur to them. Then they hunted up Huckleberry -Finn, and he joined them promptly, for all careers were one to him; he -was indifferent. They presently separated to meet at a lonely spot on -the river-bank two miles above the village at the favorite hour--which -was midnight. There was a small log raft there which they meant to -capture. Each would bring hooks and lines, and such provision as he -could steal in the most dark and mysterious way--as became outlaws. And -before the afternoon was done, they had all managed to enjoy the sweet -glory of spreading the fact that pretty soon the town would "hear -something." All who got this vague hint were cautioned to "be mum and -wait." - -About midnight Tom arrived with a boiled ham and a few trifles, -and stopped in a dense undergrowth on a small bluff overlooking the -meeting-place. It was starlight, and very still. The mighty river lay -like an ocean at rest. Tom listened a moment, but no sound disturbed the -quiet. Then he gave a low, distinct whistle. It was answered from under -the bluff. Tom whistled twice more; these signals were answered in the -same way. Then a guarded voice said: - -"Who goes there?" - -"Tom Sawyer, the Black Avenger of the Spanish Main. Name your names." - -"Huck Finn the Red-Handed, and Joe Harper the Terror of the Seas." Tom -had furnished these titles, from his favorite literature. - -"'Tis well. Give the countersign." - -Two hoarse whispers delivered the same awful word simultaneously to -the brooding night: - -"BLOOD!" - -Then Tom tumbled his ham over the bluff and let himself down after it, -tearing both skin and clothes to some extent in the effort. There was -an easy, comfortable path along the shore under the bluff, but it -lacked the advantages of difficulty and danger so valued by a pirate. - -The Terror of the Seas had brought a side of bacon, and had about worn -himself out with getting it there. Finn the Red-Handed had stolen a -skillet and a quantity of half-cured leaf tobacco, and had also brought -a few corn-cobs to make pipes with. But none of the pirates smoked or -"chewed" but himself. The Black Avenger of the Spanish Main said it -would never do to start without some fire. That was a wise thought; -matches were hardly known there in that day. They saw a fire -smouldering upon a great raft a hundred yards above, and they went -stealthily thither and helped themselves to a chunk. They made an -imposing adventure of it, saying, "Hist!" every now and then, and -suddenly halting with finger on lip; moving with hands on imaginary -dagger-hilts; and giving orders in dismal whispers that if "the foe" -stirred, to "let him have it to the hilt," because "dead men tell no -tales." They knew well enough that the raftsmen were all down at the -village laying in stores or having a spree, but still that was no -excuse for their conducting this thing in an unpiratical way. - -They shoved off, presently, Tom in command, Huck at the after oar and -Joe at the forward. Tom stood amidships, gloomy-browed, and with folded -arms, and gave his orders in a low, stern whisper: - -"Luff, and bring her to the wind!" - -"Aye-aye, sir!" - -"Steady, steady-y-y-y!" - -"Steady it is, sir!" - -"Let her go off a point!" - -"Point it is, sir!" - -As the boys steadily and monotonously drove the raft toward mid-stream -it was no doubt understood that these orders were given only for -"style," and were not intended to mean anything in particular. - -"What sail's she carrying?" - -"Courses, tops'ls, and flying-jib, sir." - -"Send the r'yals up! Lay out aloft, there, half a dozen of ye ---foretopmaststuns'l! Lively, now!" - -"Aye-aye, sir!" - -"Shake out that maintogalans'l! Sheets and braces! NOW my hearties!" - -"Aye-aye, sir!" - -"Hellum-a-lee--hard a port! Stand by to meet her when she comes! Port, -port! NOW, men! With a will! Stead-y-y-y!" - -"Steady it is, sir!" - -The raft drew beyond the middle of the river; the boys pointed her -head right, and then lay on their oars. The river was not high, so -there was not more than a two or three mile current. Hardly a word was -said during the next three-quarters of an hour. Now the raft was -passing before the distant town. Two or three glimmering lights showed -where it lay, peacefully sleeping, beyond the vague vast sweep of -star-gemmed water, unconscious of the tremendous event that was happening. -The Black Avenger stood still with folded arms, "looking his last" upon -the scene of his former joys and his later sufferings, and wishing -"she" could see him now, abroad on the wild sea, facing peril and death -with dauntless heart, going to his doom with a grim smile on his lips. -It was but a small strain on his imagination to remove Jackson's Island -beyond eyeshot of the village, and so he "looked his last" with a -broken and satisfied heart. The other pirates were looking their last, -too; and they all looked so long that they came near letting the -current drift them out of the range of the island. But they discovered -the danger in time, and made shift to avert it. About two o'clock in -the morning the raft grounded on the bar two hundred yards above the -head of the island, and they waded back and forth until they had landed -their freight. Part of the little raft's belongings consisted of an old -sail, and this they spread over a nook in the bushes for a tent to -shelter their provisions; but they themselves would sleep in the open -air in good weather, as became outlaws. - -They built a fire against the side of a great log twenty or thirty -steps within the sombre depths of the forest, and then cooked some -bacon in the frying-pan for supper, and used up half of the corn "pone" -stock they had brought. It seemed glorious sport to be feasting in that -wild, free way in the virgin forest of an unexplored and uninhabited -island, far from the haunts of men, and they said they never would -return to civilization. The climbing fire lit up their faces and threw -its ruddy glare upon the pillared tree-trunks of their forest temple, -and upon the varnished foliage and festooning vines. - -When the last crisp slice of bacon was gone, and the last allowance of -corn pone devoured, the boys stretched themselves out on the grass, -filled with contentment. They could have found a cooler place, but they -would not deny themselves such a romantic feature as the roasting -camp-fire. - -"AIN'T it gay?" said Joe. - -"It's NUTS!" said Tom. "What would the boys say if they could see us?" - -"Say? Well, they'd just die to be here--hey, Hucky!" - -"I reckon so," said Huckleberry; "anyways, I'm suited. I don't want -nothing better'n this. I don't ever get enough to eat, gen'ally--and -here they can't come and pick at a feller and bullyrag him so." - -"It's just the life for me," said Tom. "You don't have to get up, -mornings, and you don't have to go to school, and wash, and all that -blame foolishness. You see a pirate don't have to do ANYTHING, Joe, -when he's ashore, but a hermit HE has to be praying considerable, and -then he don't have any fun, anyway, all by himself that way." - -"Oh yes, that's so," said Joe, "but I hadn't thought much about it, -you know. I'd a good deal rather be a pirate, now that I've tried it." - -"You see," said Tom, "people don't go much on hermits, nowadays, like -they used to in old times, but a pirate's always respected. And a -hermit's got to sleep on the hardest place he can find, and put -sackcloth and ashes on his head, and stand out in the rain, and--" - -"What does he put sackcloth and ashes on his head for?" inquired Huck. - -"I dono. But they've GOT to do it. Hermits always do. You'd have to do -that if you was a hermit." - -"Dern'd if I would," said Huck. - -"Well, what would you do?" - -"I dono. But I wouldn't do that." - -"Why, Huck, you'd HAVE to. How'd you get around it?" - -"Why, I just wouldn't stand it. I'd run away." - -"Run away! Well, you WOULD be a nice old slouch of a hermit. You'd be -a disgrace." - -The Red-Handed made no response, being better employed. He had -finished gouging out a cob, and now he fitted a weed stem to it, loaded -it with tobacco, and was pressing a coal to the charge and blowing a -cloud of fragrant smoke--he was in the full bloom of luxurious -contentment. The other pirates envied him this majestic vice, and -secretly resolved to acquire it shortly. Presently Huck said: - -"What does pirates have to do?" - -Tom said: - -"Oh, they have just a bully time--take ships and burn them, and get -the money and bury it in awful places in their island where there's -ghosts and things to watch it, and kill everybody in the ships--make -'em walk a plank." - -"And they carry the women to the island," said Joe; "they don't kill -the women." - -"No," assented Tom, "they don't kill the women--they're too noble. And -the women's always beautiful, too. - -"And don't they wear the bulliest clothes! Oh no! All gold and silver -and di'monds," said Joe, with enthusiasm. - -"Who?" said Huck. - -"Why, the pirates." - -Huck scanned his own clothing forlornly. - -"I reckon I ain't dressed fitten for a pirate," said he, with a -regretful pathos in his voice; "but I ain't got none but these." - -But the other boys told him the fine clothes would come fast enough, -after they should have begun their adventures. They made him understand -that his poor rags would do to begin with, though it was customary for -wealthy pirates to start with a proper wardrobe. - -Gradually their talk died out and drowsiness began to steal upon the -eyelids of the little waifs. The pipe dropped from the fingers of the -Red-Handed, and he slept the sleep of the conscience-free and the -weary. The Terror of the Seas and the Black Avenger of the Spanish Main -had more difficulty in getting to sleep. They said their prayers -inwardly, and lying down, since there was nobody there with authority -to make them kneel and recite aloud; in truth, they had a mind not to -say them at all, but they were afraid to proceed to such lengths as -that, lest they might call down a sudden and special thunderbolt from -heaven. Then at once they reached and hovered upon the imminent verge -of sleep--but an intruder came, now, that would not "down." It was -conscience. They began to feel a vague fear that they had been doing -wrong to run away; and next they thought of the stolen meat, and then -the real torture came. They tried to argue it away by reminding -conscience that they had purloined sweetmeats and apples scores of -times; but conscience was not to be appeased by such thin -plausibilities; it seemed to them, in the end, that there was no -getting around the stubborn fact that taking sweetmeats was only -"hooking," while taking bacon and hams and such valuables was plain -simple stealing--and there was a command against that in the Bible. So -they inwardly resolved that so long as they remained in the business, -their piracies should not again be sullied with the crime of stealing. -Then conscience granted a truce, and these curiously inconsistent -pirates fell peacefully to sleep. - - - -CHAPTER XIV - -WHEN Tom awoke in the morning, he wondered where he was. He sat up and -rubbed his eyes and looked around. Then he comprehended. It was the -cool gray dawn, and there was a delicious sense of repose and peace in -the deep pervading calm and silence of the woods. Not a leaf stirred; -not a sound obtruded upon great Nature's meditation. Beaded dewdrops -stood upon the leaves and grasses. A white layer of ashes covered the -fire, and a thin blue breath of smoke rose straight into the air. Joe -and Huck still slept. - -Now, far away in the woods a bird called; another answered; presently -the hammering of a woodpecker was heard. Gradually the cool dim gray of -the morning whitened, and as gradually sounds multiplied and life -manifested itself. The marvel of Nature shaking off sleep and going to -work unfolded itself to the musing boy. A little green worm came -crawling over a dewy leaf, lifting two-thirds of his body into the air -from time to time and "sniffing around," then proceeding again--for he -was measuring, Tom said; and when the worm approached him, of its own -accord, he sat as still as a stone, with his hopes rising and falling, -by turns, as the creature still came toward him or seemed inclined to -go elsewhere; and when at last it considered a painful moment with its -curved body in the air and then came decisively down upon Tom's leg and -began a journey over him, his whole heart was glad--for that meant that -he was going to have a new suit of clothes--without the shadow of a -doubt a gaudy piratical uniform. Now a procession of ants appeared, -from nowhere in particular, and went about their labors; one struggled -manfully by with a dead spider five times as big as itself in its arms, -and lugged it straight up a tree-trunk. A brown spotted lady-bug -climbed the dizzy height of a grass blade, and Tom bent down close to -it and said, "Lady-bug, lady-bug, fly away home, your house is on fire, -your children's alone," and she took wing and went off to see about it ---which did not surprise the boy, for he knew of old that this insect was -credulous about conflagrations, and he had practised upon its -simplicity more than once. A tumblebug came next, heaving sturdily at -its ball, and Tom touched the creature, to see it shut its legs against -its body and pretend to be dead. The birds were fairly rioting by this -time. A catbird, the Northern mocker, lit in a tree over Tom's head, -and trilled out her imitations of her neighbors in a rapture of -enjoyment; then a shrill jay swept down, a flash of blue flame, and -stopped on a twig almost within the boy's reach, cocked his head to one -side and eyed the strangers with a consuming curiosity; a gray squirrel -and a big fellow of the "fox" kind came skurrying along, sitting up at -intervals to inspect and chatter at the boys, for the wild things had -probably never seen a human being before and scarcely knew whether to -be afraid or not. All Nature was wide awake and stirring, now; long -lances of sunlight pierced down through the dense foliage far and near, -and a few butterflies came fluttering upon the scene. - -Tom stirred up the other pirates and they all clattered away with a -shout, and in a minute or two were stripped and chasing after and -tumbling over each other in the shallow limpid water of the white -sandbar. They felt no longing for the little village sleeping in the -distance beyond the majestic waste of water. A vagrant current or a -slight rise in the river had carried off their raft, but this only -gratified them, since its going was something like burning the bridge -between them and civilization. - -They came back to camp wonderfully refreshed, glad-hearted, and -ravenous; and they soon had the camp-fire blazing up again. Huck found -a spring of clear cold water close by, and the boys made cups of broad -oak or hickory leaves, and felt that water, sweetened with such a -wildwood charm as that, would be a good enough substitute for coffee. -While Joe was slicing bacon for breakfast, Tom and Huck asked him to -hold on a minute; they stepped to a promising nook in the river-bank -and threw in their lines; almost immediately they had reward. Joe had -not had time to get impatient before they were back again with some -handsome bass, a couple of sun-perch and a small catfish--provisions -enough for quite a family. They fried the fish with the bacon, and were -astonished; for no fish had ever seemed so delicious before. They did -not know that the quicker a fresh-water fish is on the fire after he is -caught the better he is; and they reflected little upon what a sauce -open-air sleeping, open-air exercise, bathing, and a large ingredient -of hunger make, too. - -They lay around in the shade, after breakfast, while Huck had a smoke, -and then went off through the woods on an exploring expedition. They -tramped gayly along, over decaying logs, through tangled underbrush, -among solemn monarchs of the forest, hung from their crowns to the -ground with a drooping regalia of grape-vines. Now and then they came -upon snug nooks carpeted with grass and jeweled with flowers. - -They found plenty of things to be delighted with, but nothing to be -astonished at. They discovered that the island was about three miles -long and a quarter of a mile wide, and that the shore it lay closest to -was only separated from it by a narrow channel hardly two hundred yards -wide. They took a swim about every hour, so it was close upon the -middle of the afternoon when they got back to camp. They were too -hungry to stop to fish, but they fared sumptuously upon cold ham, and -then threw themselves down in the shade to talk. But the talk soon -began to drag, and then died. The stillness, the solemnity that brooded -in the woods, and the sense of loneliness, began to tell upon the -spirits of the boys. They fell to thinking. A sort of undefined longing -crept upon them. This took dim shape, presently--it was budding -homesickness. Even Finn the Red-Handed was dreaming of his doorsteps -and empty hogsheads. But they were all ashamed of their weakness, and -none was brave enough to speak his thought. - -For some time, now, the boys had been dully conscious of a peculiar -sound in the distance, just as one sometimes is of the ticking of a -clock which he takes no distinct note of. But now this mysterious sound -became more pronounced, and forced a recognition. The boys started, -glanced at each other, and then each assumed a listening attitude. -There was a long silence, profound and unbroken; then a deep, sullen -boom came floating down out of the distance. - -"What is it!" exclaimed Joe, under his breath. - -"I wonder," said Tom in a whisper. - -"'Tain't thunder," said Huckleberry, in an awed tone, "becuz thunder--" - -"Hark!" said Tom. "Listen--don't talk." - -They waited a time that seemed an age, and then the same muffled boom -troubled the solemn hush. - -"Let's go and see." - -They sprang to their feet and hurried to the shore toward the town. -They parted the bushes on the bank and peered out over the water. The -little steam ferryboat was about a mile below the village, drifting -with the current. Her broad deck seemed crowded with people. There were -a great many skiffs rowing about or floating with the stream in the -neighborhood of the ferryboat, but the boys could not determine what -the men in them were doing. Presently a great jet of white smoke burst -from the ferryboat's side, and as it expanded and rose in a lazy cloud, -that same dull throb of sound was borne to the listeners again. - -"I know now!" exclaimed Tom; "somebody's drownded!" - -"That's it!" said Huck; "they done that last summer, when Bill Turner -got drownded; they shoot a cannon over the water, and that makes him -come up to the top. Yes, and they take loaves of bread and put -quicksilver in 'em and set 'em afloat, and wherever there's anybody -that's drownded, they'll float right there and stop." - -"Yes, I've heard about that," said Joe. "I wonder what makes the bread -do that." - -"Oh, it ain't the bread, so much," said Tom; "I reckon it's mostly -what they SAY over it before they start it out." - -"But they don't say anything over it," said Huck. "I've seen 'em and -they don't." - -"Well, that's funny," said Tom. "But maybe they say it to themselves. -Of COURSE they do. Anybody might know that." - -The other boys agreed that there was reason in what Tom said, because -an ignorant lump of bread, uninstructed by an incantation, could not be -expected to act very intelligently when set upon an errand of such -gravity. - -"By jings, I wish I was over there, now," said Joe. - -"I do too" said Huck "I'd give heaps to know who it is." - -The boys still listened and watched. Presently a revealing thought -flashed through Tom's mind, and he exclaimed: - -"Boys, I know who's drownded--it's us!" - -They felt like heroes in an instant. Here was a gorgeous triumph; they -were missed; they were mourned; hearts were breaking on their account; -tears were being shed; accusing memories of unkindness to these poor -lost lads were rising up, and unavailing regrets and remorse were being -indulged; and best of all, the departed were the talk of the whole -town, and the envy of all the boys, as far as this dazzling notoriety -was concerned. This was fine. It was worth while to be a pirate, after -all. - -As twilight drew on, the ferryboat went back to her accustomed -business and the skiffs disappeared. The pirates returned to camp. They -were jubilant with vanity over their new grandeur and the illustrious -trouble they were making. They caught fish, cooked supper and ate it, -and then fell to guessing at what the village was thinking and saying -about them; and the pictures they drew of the public distress on their -account were gratifying to look upon--from their point of view. But -when the shadows of night closed them in, they gradually ceased to -talk, and sat gazing into the fire, with their minds evidently -wandering elsewhere. The excitement was gone, now, and Tom and Joe -could not keep back thoughts of certain persons at home who were not -enjoying this fine frolic as much as they were. Misgivings came; they -grew troubled and unhappy; a sigh or two escaped, unawares. By and by -Joe timidly ventured upon a roundabout "feeler" as to how the others -might look upon a return to civilization--not right now, but-- - -Tom withered him with derision! Huck, being uncommitted as yet, joined -in with Tom, and the waverer quickly "explained," and was glad to get -out of the scrape with as little taint of chicken-hearted homesickness -clinging to his garments as he could. Mutiny was effectually laid to -rest for the moment. - -As the night deepened, Huck began to nod, and presently to snore. Joe -followed next. Tom lay upon his elbow motionless, for some time, -watching the two intently. At last he got up cautiously, on his knees, -and went searching among the grass and the flickering reflections flung -by the camp-fire. He picked up and inspected several large -semi-cylinders of the thin white bark of a sycamore, and finally chose -two which seemed to suit him. Then he knelt by the fire and painfully -wrote something upon each of these with his "red keel"; one he rolled up -and put in his jacket pocket, and the other he put in Joe's hat and -removed it to a little distance from the owner. And he also put into the -hat certain schoolboy treasures of almost inestimable value--among them -a lump of chalk, an India-rubber ball, three fishhooks, and one of that -kind of marbles known as a "sure 'nough crystal." Then he tiptoed his -way cautiously among the trees till he felt that he was out of hearing, -and straightway broke into a keen run in the direction of the sandbar. - - - -CHAPTER XV - -A FEW minutes later Tom was in the shoal water of the bar, wading -toward the Illinois shore. Before the depth reached his middle he was -half-way over; the current would permit no more wading, now, so he -struck out confidently to swim the remaining hundred yards. He swam -quartering upstream, but still was swept downward rather faster than he -had expected. However, he reached the shore finally, and drifted along -till he found a low place and drew himself out. He put his hand on his -jacket pocket, found his piece of bark safe, and then struck through -the woods, following the shore, with streaming garments. Shortly before -ten o'clock he came out into an open place opposite the village, and -saw the ferryboat lying in the shadow of the trees and the high bank. -Everything was quiet under the blinking stars. He crept down the bank, -watching with all his eyes, slipped into the water, swam three or four -strokes and climbed into the skiff that did "yawl" duty at the boat's -stern. He laid himself down under the thwarts and waited, panting. - -Presently the cracked bell tapped and a voice gave the order to "cast -off." A minute or two later the skiff's head was standing high up, -against the boat's swell, and the voyage was begun. Tom felt happy in -his success, for he knew it was the boat's last trip for the night. At -the end of a long twelve or fifteen minutes the wheels stopped, and Tom -slipped overboard and swam ashore in the dusk, landing fifty yards -downstream, out of danger of possible stragglers. - -He flew along unfrequented alleys, and shortly found himself at his -aunt's back fence. He climbed over, approached the "ell," and looked in -at the sitting-room window, for a light was burning there. There sat -Aunt Polly, Sid, Mary, and Joe Harper's mother, grouped together, -talking. They were by the bed, and the bed was between them and the -door. Tom went to the door and began to softly lift the latch; then he -pressed gently and the door yielded a crack; he continued pushing -cautiously, and quaking every time it creaked, till he judged he might -squeeze through on his knees; so he put his head through and began, -warily. - -"What makes the candle blow so?" said Aunt Polly. Tom hurried up. -"Why, that door's open, I believe. Why, of course it is. No end of -strange things now. Go 'long and shut it, Sid." - -Tom disappeared under the bed just in time. He lay and "breathed" -himself for a time, and then crept to where he could almost touch his -aunt's foot. - -"But as I was saying," said Aunt Polly, "he warn't BAD, so to say ---only mischEEvous. Only just giddy, and harum-scarum, you know. He -warn't any more responsible than a colt. HE never meant any harm, and -he was the best-hearted boy that ever was"--and she began to cry. - -"It was just so with my Joe--always full of his devilment, and up to -every kind of mischief, but he was just as unselfish and kind as he -could be--and laws bless me, to think I went and whipped him for taking -that cream, never once recollecting that I throwed it out myself -because it was sour, and I never to see him again in this world, never, -never, never, poor abused boy!" And Mrs. Harper sobbed as if her heart -would break. - -"I hope Tom's better off where he is," said Sid, "but if he'd been -better in some ways--" - -"SID!" Tom felt the glare of the old lady's eye, though he could not -see it. "Not a word against my Tom, now that he's gone! God'll take -care of HIM--never you trouble YOURself, sir! Oh, Mrs. Harper, I don't -know how to give him up! I don't know how to give him up! He was such a -comfort to me, although he tormented my old heart out of me, 'most." - -"The Lord giveth and the Lord hath taken away--Blessed be the name of -the Lord! But it's so hard--Oh, it's so hard! Only last Saturday my -Joe busted a firecracker right under my nose and I knocked him -sprawling. Little did I know then, how soon--Oh, if it was to do over -again I'd hug him and bless him for it." - -"Yes, yes, yes, I know just how you feel, Mrs. Harper, I know just -exactly how you feel. No longer ago than yesterday noon, my Tom took -and filled the cat full of Pain-killer, and I did think the cretur -would tear the house down. And God forgive me, I cracked Tom's head -with my thimble, poor boy, poor dead boy. But he's out of all his -troubles now. And the last words I ever heard him say was to reproach--" - -But this memory was too much for the old lady, and she broke entirely -down. Tom was snuffling, now, himself--and more in pity of himself than -anybody else. He could hear Mary crying, and putting in a kindly word -for him from time to time. He began to have a nobler opinion of himself -than ever before. Still, he was sufficiently touched by his aunt's -grief to long to rush out from under the bed and overwhelm her with -joy--and the theatrical gorgeousness of the thing appealed strongly to -his nature, too, but he resisted and lay still. - -He went on listening, and gathered by odds and ends that it was -conjectured at first that the boys had got drowned while taking a swim; -then the small raft had been missed; next, certain boys said the -missing lads had promised that the village should "hear something" -soon; the wise-heads had "put this and that together" and decided that -the lads had gone off on that raft and would turn up at the next town -below, presently; but toward noon the raft had been found, lodged -against the Missouri shore some five or six miles below the village ---and then hope perished; they must be drowned, else hunger would have -driven them home by nightfall if not sooner. It was believed that the -search for the bodies had been a fruitless effort merely because the -drowning must have occurred in mid-channel, since the boys, being good -swimmers, would otherwise have escaped to shore. This was Wednesday -night. If the bodies continued missing until Sunday, all hope would be -given over, and the funerals would be preached on that morning. Tom -shuddered. - -Mrs. Harper gave a sobbing good-night and turned to go. Then with a -mutual impulse the two bereaved women flung themselves into each -other's arms and had a good, consoling cry, and then parted. Aunt Polly -was tender far beyond her wont, in her good-night to Sid and Mary. Sid -snuffled a bit and Mary went off crying with all her heart. - -Aunt Polly knelt down and prayed for Tom so touchingly, so -appealingly, and with such measureless love in her words and her old -trembling voice, that he was weltering in tears again, long before she -was through. - -He had to keep still long after she went to bed, for she kept making -broken-hearted ejaculations from time to time, tossing unrestfully, and -turning over. But at last she was still, only moaning a little in her -sleep. Now the boy stole out, rose gradually by the bedside, shaded the -candle-light with his hand, and stood regarding her. His heart was full -of pity for her. He took out his sycamore scroll and placed it by the -candle. But something occurred to him, and he lingered considering. His -face lighted with a happy solution of his thought; he put the bark -hastily in his pocket. Then he bent over and kissed the faded lips, and -straightway made his stealthy exit, latching the door behind him. - -He threaded his way back to the ferry landing, found nobody at large -there, and walked boldly on board the boat, for he knew she was -tenantless except that there was a watchman, who always turned in and -slept like a graven image. He untied the skiff at the stern, slipped -into it, and was soon rowing cautiously upstream. When he had pulled a -mile above the village, he started quartering across and bent himself -stoutly to his work. He hit the landing on the other side neatly, for -this was a familiar bit of work to him. He was moved to capture the -skiff, arguing that it might be considered a ship and therefore -legitimate prey for a pirate, but he knew a thorough search would be -made for it and that might end in revelations. So he stepped ashore and -entered the woods. - -He sat down and took a long rest, torturing himself meanwhile to keep -awake, and then started warily down the home-stretch. The night was far -spent. It was broad daylight before he found himself fairly abreast the -island bar. He rested again until the sun was well up and gilding the -great river with its splendor, and then he plunged into the stream. A -little later he paused, dripping, upon the threshold of the camp, and -heard Joe say: - -"No, Tom's true-blue, Huck, and he'll come back. He won't desert. He -knows that would be a disgrace to a pirate, and Tom's too proud for -that sort of thing. He's up to something or other. Now I wonder what?" - -"Well, the things is ours, anyway, ain't they?" - -"Pretty near, but not yet, Huck. The writing says they are if he ain't -back here to breakfast." - -"Which he is!" exclaimed Tom, with fine dramatic effect, stepping -grandly into camp. - -A sumptuous breakfast of bacon and fish was shortly provided, and as -the boys set to work upon it, Tom recounted (and adorned) his -adventures. They were a vain and boastful company of heroes when the -tale was done. Then Tom hid himself away in a shady nook to sleep till -noon, and the other pirates got ready to fish and explore. - - - -CHAPTER XVI - -AFTER dinner all the gang turned out to hunt for turtle eggs on the -bar. They went about poking sticks into the sand, and when they found a -soft place they went down on their knees and dug with their hands. -Sometimes they would take fifty or sixty eggs out of one hole. They -were perfectly round white things a trifle smaller than an English -walnut. They had a famous fried-egg feast that night, and another on -Friday morning. - -After breakfast they went whooping and prancing out on the bar, and -chased each other round and round, shedding clothes as they went, until -they were naked, and then continued the frolic far away up the shoal -water of the bar, against the stiff current, which latter tripped their -legs from under them from time to time and greatly increased the fun. -And now and then they stooped in a group and splashed water in each -other's faces with their palms, gradually approaching each other, with -averted faces to avoid the strangling sprays, and finally gripping and -struggling till the best man ducked his neighbor, and then they all -went under in a tangle of white legs and arms and came up blowing, -sputtering, laughing, and gasping for breath at one and the same time. - -When they were well exhausted, they would run out and sprawl on the -dry, hot sand, and lie there and cover themselves up with it, and by -and by break for the water again and go through the original -performance once more. Finally it occurred to them that their naked -skin represented flesh-colored "tights" very fairly; so they drew a -ring in the sand and had a circus--with three clowns in it, for none -would yield this proudest post to his neighbor. - -Next they got their marbles and played "knucks" and "ring-taw" and -"keeps" till that amusement grew stale. Then Joe and Huck had another -swim, but Tom would not venture, because he found that in kicking off -his trousers he had kicked his string of rattlesnake rattles off his -ankle, and he wondered how he had escaped cramp so long without the -protection of this mysterious charm. He did not venture again until he -had found it, and by that time the other boys were tired and ready to -rest. They gradually wandered apart, dropped into the "dumps," and fell -to gazing longingly across the wide river to where the village lay -drowsing in the sun. Tom found himself writing "BECKY" in the sand with -his big toe; he scratched it out, and was angry with himself for his -weakness. But he wrote it again, nevertheless; he could not help it. He -erased it once more and then took himself out of temptation by driving -the other boys together and joining them. - -But Joe's spirits had gone down almost beyond resurrection. He was so -homesick that he could hardly endure the misery of it. The tears lay -very near the surface. Huck was melancholy, too. Tom was downhearted, -but tried hard not to show it. He had a secret which he was not ready -to tell, yet, but if this mutinous depression was not broken up soon, -he would have to bring it out. He said, with a great show of -cheerfulness: - -"I bet there's been pirates on this island before, boys. We'll explore -it again. They've hid treasures here somewhere. How'd you feel to light -on a rotten chest full of gold and silver--hey?" - -But it roused only faint enthusiasm, which faded out, with no reply. -Tom tried one or two other seductions; but they failed, too. It was -discouraging work. Joe sat poking up the sand with a stick and looking -very gloomy. Finally he said: - -"Oh, boys, let's give it up. I want to go home. It's so lonesome." - -"Oh no, Joe, you'll feel better by and by," said Tom. "Just think of -the fishing that's here." - -"I don't care for fishing. I want to go home." - -"But, Joe, there ain't such another swimming-place anywhere." - -"Swimming's no good. I don't seem to care for it, somehow, when there -ain't anybody to say I sha'n't go in. I mean to go home." - -"Oh, shucks! Baby! You want to see your mother, I reckon." - -"Yes, I DO want to see my mother--and you would, too, if you had one. -I ain't any more baby than you are." And Joe snuffled a little. - -"Well, we'll let the cry-baby go home to his mother, won't we, Huck? -Poor thing--does it want to see its mother? And so it shall. You like -it here, don't you, Huck? We'll stay, won't we?" - -Huck said, "Y-e-s"--without any heart in it. - -"I'll never speak to you again as long as I live," said Joe, rising. -"There now!" And he moved moodily away and began to dress himself. - -"Who cares!" said Tom. "Nobody wants you to. Go 'long home and get -laughed at. Oh, you're a nice pirate. Huck and me ain't cry-babies. -We'll stay, won't we, Huck? Let him go if he wants to. I reckon we can -get along without him, per'aps." - -But Tom was uneasy, nevertheless, and was alarmed to see Joe go -sullenly on with his dressing. And then it was discomforting to see -Huck eying Joe's preparations so wistfully, and keeping up such an -ominous silence. Presently, without a parting word, Joe began to wade -off toward the Illinois shore. Tom's heart began to sink. He glanced at -Huck. Huck could not bear the look, and dropped his eyes. Then he said: - -"I want to go, too, Tom. It was getting so lonesome anyway, and now -it'll be worse. Let's us go, too, Tom." - -"I won't! You can all go, if you want to. I mean to stay." - -"Tom, I better go." - -"Well, go 'long--who's hendering you." - -Huck began to pick up his scattered clothes. He said: - -"Tom, I wisht you'd come, too. Now you think it over. We'll wait for -you when we get to shore." - -"Well, you'll wait a blame long time, that's all." - -Huck started sorrowfully away, and Tom stood looking after him, with a -strong desire tugging at his heart to yield his pride and go along too. -He hoped the boys would stop, but they still waded slowly on. It -suddenly dawned on Tom that it was become very lonely and still. He -made one final struggle with his pride, and then darted after his -comrades, yelling: - -"Wait! Wait! I want to tell you something!" - -They presently stopped and turned around. When he got to where they -were, he began unfolding his secret, and they listened moodily till at -last they saw the "point" he was driving at, and then they set up a -war-whoop of applause and said it was "splendid!" and said if he had -told them at first, they wouldn't have started away. He made a plausible -excuse; but his real reason had been the fear that not even the secret -would keep them with him any very great length of time, and so he had -meant to hold it in reserve as a last seduction. - -The lads came gayly back and went at their sports again with a will, -chattering all the time about Tom's stupendous plan and admiring the -genius of it. After a dainty egg and fish dinner, Tom said he wanted to -learn to smoke, now. Joe caught at the idea and said he would like to -try, too. So Huck made pipes and filled them. These novices had never -smoked anything before but cigars made of grape-vine, and they "bit" -the tongue, and were not considered manly anyway. - -Now they stretched themselves out on their elbows and began to puff, -charily, and with slender confidence. The smoke had an unpleasant -taste, and they gagged a little, but Tom said: - -"Why, it's just as easy! If I'd a knowed this was all, I'd a learnt -long ago." - -"So would I," said Joe. "It's just nothing." - -"Why, many a time I've looked at people smoking, and thought well I -wish I could do that; but I never thought I could," said Tom. - -"That's just the way with me, hain't it, Huck? You've heard me talk -just that way--haven't you, Huck? I'll leave it to Huck if I haven't." - -"Yes--heaps of times," said Huck. - -"Well, I have too," said Tom; "oh, hundreds of times. Once down by the -slaughter-house. Don't you remember, Huck? Bob Tanner was there, and -Johnny Miller, and Jeff Thatcher, when I said it. Don't you remember, -Huck, 'bout me saying that?" - -"Yes, that's so," said Huck. "That was the day after I lost a white -alley. No, 'twas the day before." - -"There--I told you so," said Tom. "Huck recollects it." - -"I bleeve I could smoke this pipe all day," said Joe. "I don't feel -sick." - -"Neither do I," said Tom. "I could smoke it all day. But I bet you -Jeff Thatcher couldn't." - -"Jeff Thatcher! Why, he'd keel over just with two draws. Just let him -try it once. HE'D see!" - -"I bet he would. And Johnny Miller--I wish could see Johnny Miller -tackle it once." - -"Oh, don't I!" said Joe. "Why, I bet you Johnny Miller couldn't any -more do this than nothing. Just one little snifter would fetch HIM." - -"'Deed it would, Joe. Say--I wish the boys could see us now." - -"So do I." - -"Say--boys, don't say anything about it, and some time when they're -around, I'll come up to you and say, 'Joe, got a pipe? I want a smoke.' -And you'll say, kind of careless like, as if it warn't anything, you'll -say, 'Yes, I got my OLD pipe, and another one, but my tobacker ain't -very good.' And I'll say, 'Oh, that's all right, if it's STRONG -enough.' And then you'll out with the pipes, and we'll light up just as -ca'm, and then just see 'em look!" - -"By jings, that'll be gay, Tom! I wish it was NOW!" - -"So do I! And when we tell 'em we learned when we was off pirating, -won't they wish they'd been along?" - -"Oh, I reckon not! I'll just BET they will!" - -So the talk ran on. But presently it began to flag a trifle, and grow -disjointed. The silences widened; the expectoration marvellously -increased. Every pore inside the boys' cheeks became a spouting -fountain; they could scarcely bail out the cellars under their tongues -fast enough to prevent an inundation; little overflowings down their -throats occurred in spite of all they could do, and sudden retchings -followed every time. Both boys were looking very pale and miserable, -now. Joe's pipe dropped from his nerveless fingers. Tom's followed. -Both fountains were going furiously and both pumps bailing with might -and main. Joe said feebly: - -"I've lost my knife. I reckon I better go and find it." - -Tom said, with quivering lips and halting utterance: - -"I'll help you. You go over that way and I'll hunt around by the -spring. No, you needn't come, Huck--we can find it." - -So Huck sat down again, and waited an hour. Then he found it lonesome, -and went to find his comrades. They were wide apart in the woods, both -very pale, both fast asleep. But something informed him that if they -had had any trouble they had got rid of it. - -They were not talkative at supper that night. They had a humble look, -and when Huck prepared his pipe after the meal and was going to prepare -theirs, they said no, they were not feeling very well--something they -ate at dinner had disagreed with them. - -About midnight Joe awoke, and called the boys. There was a brooding -oppressiveness in the air that seemed to bode something. The boys -huddled themselves together and sought the friendly companionship of -the fire, though the dull dead heat of the breathless atmosphere was -stifling. They sat still, intent and waiting. The solemn hush -continued. Beyond the light of the fire everything was swallowed up in -the blackness of darkness. Presently there came a quivering glow that -vaguely revealed the foliage for a moment and then vanished. By and by -another came, a little stronger. Then another. Then a faint moan came -sighing through the branches of the forest and the boys felt a fleeting -breath upon their cheeks, and shuddered with the fancy that the Spirit -of the Night had gone by. There was a pause. Now a weird flash turned -night into day and showed every little grass-blade, separate and -distinct, that grew about their feet. And it showed three white, -startled faces, too. A deep peal of thunder went rolling and tumbling -down the heavens and lost itself in sullen rumblings in the distance. A -sweep of chilly air passed by, rustling all the leaves and snowing the -flaky ashes broadcast about the fire. Another fierce glare lit up the -forest and an instant crash followed that seemed to rend the tree-tops -right over the boys' heads. They clung together in terror, in the thick -gloom that followed. A few big rain-drops fell pattering upon the -leaves. - -"Quick! boys, go for the tent!" exclaimed Tom. - -They sprang away, stumbling over roots and among vines in the dark, no -two plunging in the same direction. A furious blast roared through the -trees, making everything sing as it went. One blinding flash after -another came, and peal on peal of deafening thunder. And now a -drenching rain poured down and the rising hurricane drove it in sheets -along the ground. The boys cried out to each other, but the roaring -wind and the booming thunder-blasts drowned their voices utterly. -However, one by one they straggled in at last and took shelter under -the tent, cold, scared, and streaming with water; but to have company -in misery seemed something to be grateful for. They could not talk, the -old sail flapped so furiously, even if the other noises would have -allowed them. The tempest rose higher and higher, and presently the -sail tore loose from its fastenings and went winging away on the blast. -The boys seized each others' hands and fled, with many tumblings and -bruises, to the shelter of a great oak that stood upon the river-bank. -Now the battle was at its highest. Under the ceaseless conflagration of -lightning that flamed in the skies, everything below stood out in -clean-cut and shadowless distinctness: the bending trees, the billowy -river, white with foam, the driving spray of spume-flakes, the dim -outlines of the high bluffs on the other side, glimpsed through the -drifting cloud-rack and the slanting veil of rain. Every little while -some giant tree yielded the fight and fell crashing through the younger -growth; and the unflagging thunder-peals came now in ear-splitting -explosive bursts, keen and sharp, and unspeakably appalling. The storm -culminated in one matchless effort that seemed likely to tear the island -to pieces, burn it up, drown it to the tree-tops, blow it away, and -deafen every creature in it, all at one and the same moment. It was a -wild night for homeless young heads to be out in. - -But at last the battle was done, and the forces retired with weaker -and weaker threatenings and grumblings, and peace resumed her sway. The -boys went back to camp, a good deal awed; but they found there was -still something to be thankful for, because the great sycamore, the -shelter of their beds, was a ruin, now, blasted by the lightnings, and -they were not under it when the catastrophe happened. - -Everything in camp was drenched, the camp-fire as well; for they were -but heedless lads, like their generation, and had made no provision -against rain. Here was matter for dismay, for they were soaked through -and chilled. They were eloquent in their distress; but they presently -discovered that the fire had eaten so far up under the great log it had -been built against (where it curved upward and separated itself from -the ground), that a handbreadth or so of it had escaped wetting; so -they patiently wrought until, with shreds and bark gathered from the -under sides of sheltered logs, they coaxed the fire to burn again. Then -they piled on great dead boughs till they had a roaring furnace, and -were glad-hearted once more. They dried their boiled ham and had a -feast, and after that they sat by the fire and expanded and glorified -their midnight adventure until morning, for there was not a dry spot to -sleep on, anywhere around. - -As the sun began to steal in upon the boys, drowsiness came over them, -and they went out on the sandbar and lay down to sleep. They got -scorched out by and by, and drearily set about getting breakfast. After -the meal they felt rusty, and stiff-jointed, and a little homesick once -more. Tom saw the signs, and fell to cheering up the pirates as well as -he could. But they cared nothing for marbles, or circus, or swimming, -or anything. He reminded them of the imposing secret, and raised a ray -of cheer. While it lasted, he got them interested in a new device. This -was to knock off being pirates, for a while, and be Indians for a -change. They were attracted by this idea; so it was not long before -they were stripped, and striped from head to heel with black mud, like -so many zebras--all of them chiefs, of course--and then they went -tearing through the woods to attack an English settlement. - -By and by they separated into three hostile tribes, and darted upon -each other from ambush with dreadful war-whoops, and killed and scalped -each other by thousands. It was a gory day. Consequently it was an -extremely satisfactory one. - -They assembled in camp toward supper-time, hungry and happy; but now a -difficulty arose--hostile Indians could not break the bread of -hospitality together without first making peace, and this was a simple -impossibility without smoking a pipe of peace. There was no other -process that ever they had heard of. Two of the savages almost wished -they had remained pirates. However, there was no other way; so with -such show of cheerfulness as they could muster they called for the pipe -and took their whiff as it passed, in due form. - -And behold, they were glad they had gone into savagery, for they had -gained something; they found that they could now smoke a little without -having to go and hunt for a lost knife; they did not get sick enough to -be seriously uncomfortable. They were not likely to fool away this high -promise for lack of effort. No, they practised cautiously, after -supper, with right fair success, and so they spent a jubilant evening. -They were prouder and happier in their new acquirement than they would -have been in the scalping and skinning of the Six Nations. We will -leave them to smoke and chatter and brag, since we have no further use -for them at present. - - - -CHAPTER XVII - -BUT there was no hilarity in the little town that same tranquil -Saturday afternoon. The Harpers, and Aunt Polly's family, were being -put into mourning, with great grief and many tears. An unusual quiet -possessed the village, although it was ordinarily quiet enough, in all -conscience. The villagers conducted their concerns with an absent air, -and talked little; but they sighed often. The Saturday holiday seemed a -burden to the children. They had no heart in their sports, and -gradually gave them up. - -In the afternoon Becky Thatcher found herself moping about the -deserted schoolhouse yard, and feeling very melancholy. But she found -nothing there to comfort her. She soliloquized: - -"Oh, if I only had a brass andiron-knob again! But I haven't got -anything now to remember him by." And she choked back a little sob. - -Presently she stopped, and said to herself: - -"It was right here. Oh, if it was to do over again, I wouldn't say -that--I wouldn't say it for the whole world. But he's gone now; I'll -never, never, never see him any more." - -This thought broke her down, and she wandered away, with tears rolling -down her cheeks. Then quite a group of boys and girls--playmates of -Tom's and Joe's--came by, and stood looking over the paling fence and -talking in reverent tones of how Tom did so-and-so the last time they -saw him, and how Joe said this and that small trifle (pregnant with -awful prophecy, as they could easily see now!)--and each speaker -pointed out the exact spot where the lost lads stood at the time, and -then added something like "and I was a-standing just so--just as I am -now, and as if you was him--I was as close as that--and he smiled, just -this way--and then something seemed to go all over me, like--awful, you -know--and I never thought what it meant, of course, but I can see now!" - -Then there was a dispute about who saw the dead boys last in life, and -many claimed that dismal distinction, and offered evidences, more or -less tampered with by the witness; and when it was ultimately decided -who DID see the departed last, and exchanged the last words with them, -the lucky parties took upon themselves a sort of sacred importance, and -were gaped at and envied by all the rest. One poor chap, who had no -other grandeur to offer, said with tolerably manifest pride in the -remembrance: - -"Well, Tom Sawyer he licked me once." - -But that bid for glory was a failure. Most of the boys could say that, -and so that cheapened the distinction too much. The group loitered -away, still recalling memories of the lost heroes, in awed voices. - -When the Sunday-school hour was finished, the next morning, the bell -began to toll, instead of ringing in the usual way. It was a very still -Sabbath, and the mournful sound seemed in keeping with the musing hush -that lay upon nature. The villagers began to gather, loitering a moment -in the vestibule to converse in whispers about the sad event. But there -was no whispering in the house; only the funereal rustling of dresses -as the women gathered to their seats disturbed the silence there. None -could remember when the little church had been so full before. There -was finally a waiting pause, an expectant dumbness, and then Aunt Polly -entered, followed by Sid and Mary, and they by the Harper family, all -in deep black, and the whole congregation, the old minister as well, -rose reverently and stood until the mourners were seated in the front -pew. There was another communing silence, broken at intervals by -muffled sobs, and then the minister spread his hands abroad and prayed. -A moving hymn was sung, and the text followed: "I am the Resurrection -and the Life." - -As the service proceeded, the clergyman drew such pictures of the -graces, the winning ways, and the rare promise of the lost lads that -every soul there, thinking he recognized these pictures, felt a pang in -remembering that he had persistently blinded himself to them always -before, and had as persistently seen only faults and flaws in the poor -boys. The minister related many a touching incident in the lives of the -departed, too, which illustrated their sweet, generous natures, and the -people could easily see, now, how noble and beautiful those episodes -were, and remembered with grief that at the time they occurred they had -seemed rank rascalities, well deserving of the cowhide. The -congregation became more and more moved, as the pathetic tale went on, -till at last the whole company broke down and joined the weeping -mourners in a chorus of anguished sobs, the preacher himself giving way -to his feelings, and crying in the pulpit. - -There was a rustle in the gallery, which nobody noticed; a moment -later the church door creaked; the minister raised his streaming eyes -above his handkerchief, and stood transfixed! First one and then -another pair of eyes followed the minister's, and then almost with one -impulse the congregation rose and stared while the three dead boys came -marching up the aisle, Tom in the lead, Joe next, and Huck, a ruin of -drooping rags, sneaking sheepishly in the rear! They had been hid in -the unused gallery listening to their own funeral sermon! - -Aunt Polly, Mary, and the Harpers threw themselves upon their restored -ones, smothered them with kisses and poured out thanksgivings, while -poor Huck stood abashed and uncomfortable, not knowing exactly what to -do or where to hide from so many unwelcoming eyes. He wavered, and -started to slink away, but Tom seized him and said: - -"Aunt Polly, it ain't fair. Somebody's got to be glad to see Huck." - -"And so they shall. I'm glad to see him, poor motherless thing!" And -the loving attentions Aunt Polly lavished upon him were the one thing -capable of making him more uncomfortable than he was before. - -Suddenly the minister shouted at the top of his voice: "Praise God -from whom all blessings flow--SING!--and put your hearts in it!" - -And they did. Old Hundred swelled up with a triumphant burst, and -while it shook the rafters Tom Sawyer the Pirate looked around upon the -envying juveniles about him and confessed in his heart that this was -the proudest moment of his life. - -As the "sold" congregation trooped out they said they would almost be -willing to be made ridiculous again to hear Old Hundred sung like that -once more. - -Tom got more cuffs and kisses that day--according to Aunt Polly's -varying moods--than he had earned before in a year; and he hardly knew -which expressed the most gratefulness to God and affection for himself. - - - -CHAPTER XVIII - -THAT was Tom's great secret--the scheme to return home with his -brother pirates and attend their own funerals. They had paddled over to -the Missouri shore on a log, at dusk on Saturday, landing five or six -miles below the village; they had slept in the woods at the edge of the -town till nearly daylight, and had then crept through back lanes and -alleys and finished their sleep in the gallery of the church among a -chaos of invalided benches. - -At breakfast, Monday morning, Aunt Polly and Mary were very loving to -Tom, and very attentive to his wants. There was an unusual amount of -talk. In the course of it Aunt Polly said: - -"Well, I don't say it wasn't a fine joke, Tom, to keep everybody -suffering 'most a week so you boys had a good time, but it is a pity -you could be so hard-hearted as to let me suffer so. If you could come -over on a log to go to your funeral, you could have come over and give -me a hint some way that you warn't dead, but only run off." - -"Yes, you could have done that, Tom," said Mary; "and I believe you -would if you had thought of it." - -"Would you, Tom?" said Aunt Polly, her face lighting wistfully. "Say, -now, would you, if you'd thought of it?" - -"I--well, I don't know. 'Twould 'a' spoiled everything." - -"Tom, I hoped you loved me that much," said Aunt Polly, with a grieved -tone that discomforted the boy. "It would have been something if you'd -cared enough to THINK of it, even if you didn't DO it." - -"Now, auntie, that ain't any harm," pleaded Mary; "it's only Tom's -giddy way--he is always in such a rush that he never thinks of -anything." - -"More's the pity. Sid would have thought. And Sid would have come and -DONE it, too. Tom, you'll look back, some day, when it's too late, and -wish you'd cared a little more for me when it would have cost you so -little." - -"Now, auntie, you know I do care for you," said Tom. - -"I'd know it better if you acted more like it." - -"I wish now I'd thought," said Tom, with a repentant tone; "but I -dreamt about you, anyway. That's something, ain't it?" - -"It ain't much--a cat does that much--but it's better than nothing. -What did you dream?" - -"Why, Wednesday night I dreamt that you was sitting over there by the -bed, and Sid was sitting by the woodbox, and Mary next to him." - -"Well, so we did. So we always do. I'm glad your dreams could take -even that much trouble about us." - -"And I dreamt that Joe Harper's mother was here." - -"Why, she was here! Did you dream any more?" - -"Oh, lots. But it's so dim, now." - -"Well, try to recollect--can't you?" - -"Somehow it seems to me that the wind--the wind blowed the--the--" - -"Try harder, Tom! The wind did blow something. Come!" - -Tom pressed his fingers on his forehead an anxious minute, and then -said: - -"I've got it now! I've got it now! It blowed the candle!" - -"Mercy on us! Go on, Tom--go on!" - -"And it seems to me that you said, 'Why, I believe that that door--'" - -"Go ON, Tom!" - -"Just let me study a moment--just a moment. Oh, yes--you said you -believed the door was open." - -"As I'm sitting here, I did! Didn't I, Mary! Go on!" - -"And then--and then--well I won't be certain, but it seems like as if -you made Sid go and--and--" - -"Well? Well? What did I make him do, Tom? What did I make him do?" - -"You made him--you--Oh, you made him shut it." - -"Well, for the land's sake! I never heard the beat of that in all my -days! Don't tell ME there ain't anything in dreams, any more. Sereny -Harper shall know of this before I'm an hour older. I'd like to see her -get around THIS with her rubbage 'bout superstition. Go on, Tom!" - -"Oh, it's all getting just as bright as day, now. Next you said I -warn't BAD, only mischeevous and harum-scarum, and not any more -responsible than--than--I think it was a colt, or something." - -"And so it was! Well, goodness gracious! Go on, Tom!" - -"And then you began to cry." - -"So I did. So I did. Not the first time, neither. And then--" - -"Then Mrs. Harper she began to cry, and said Joe was just the same, -and she wished she hadn't whipped him for taking cream when she'd -throwed it out her own self--" - -"Tom! The sperrit was upon you! You was a prophesying--that's what you -was doing! Land alive, go on, Tom!" - -"Then Sid he said--he said--" - -"I don't think I said anything," said Sid. - -"Yes you did, Sid," said Mary. - -"Shut your heads and let Tom go on! What did he say, Tom?" - -"He said--I THINK he said he hoped I was better off where I was gone -to, but if I'd been better sometimes--" - -"THERE, d'you hear that! It was his very words!" - -"And you shut him up sharp." - -"I lay I did! There must 'a' been an angel there. There WAS an angel -there, somewheres!" - -"And Mrs. Harper told about Joe scaring her with a firecracker, and -you told about Peter and the Painkiller--" - -"Just as true as I live!" - -"And then there was a whole lot of talk 'bout dragging the river for -us, and 'bout having the funeral Sunday, and then you and old Miss -Harper hugged and cried, and she went." - -"It happened just so! It happened just so, as sure as I'm a-sitting in -these very tracks. Tom, you couldn't told it more like if you'd 'a' -seen it! And then what? Go on, Tom!" - -"Then I thought you prayed for me--and I could see you and hear every -word you said. And you went to bed, and I was so sorry that I took and -wrote on a piece of sycamore bark, 'We ain't dead--we are only off -being pirates,' and put it on the table by the candle; and then you -looked so good, laying there asleep, that I thought I went and leaned -over and kissed you on the lips." - -"Did you, Tom, DID you! I just forgive you everything for that!" And -she seized the boy in a crushing embrace that made him feel like the -guiltiest of villains. - -"It was very kind, even though it was only a--dream," Sid soliloquized -just audibly. - -"Shut up, Sid! A body does just the same in a dream as he'd do if he -was awake. Here's a big Milum apple I've been saving for you, Tom, if -you was ever found again--now go 'long to school. I'm thankful to the -good God and Father of us all I've got you back, that's long-suffering -and merciful to them that believe on Him and keep His word, though -goodness knows I'm unworthy of it, but if only the worthy ones got His -blessings and had His hand to help them over the rough places, there's -few enough would smile here or ever enter into His rest when the long -night comes. Go 'long Sid, Mary, Tom--take yourselves off--you've -hendered me long enough." - -The children left for school, and the old lady to call on Mrs. Harper -and vanquish her realism with Tom's marvellous dream. Sid had better -judgment than to utter the thought that was in his mind as he left the -house. It was this: "Pretty thin--as long a dream as that, without any -mistakes in it!" - -What a hero Tom was become, now! He did not go skipping and prancing, -but moved with a dignified swagger as became a pirate who felt that the -public eye was on him. And indeed it was; he tried not to seem to see -the looks or hear the remarks as he passed along, but they were food -and drink to him. Smaller boys than himself flocked at his heels, as -proud to be seen with him, and tolerated by him, as if he had been the -drummer at the head of a procession or the elephant leading a menagerie -into town. Boys of his own size pretended not to know he had been away -at all; but they were consuming with envy, nevertheless. They would -have given anything to have that swarthy suntanned skin of his, and his -glittering notoriety; and Tom would not have parted with either for a -circus. - -At school the children made so much of him and of Joe, and delivered -such eloquent admiration from their eyes, that the two heroes were not -long in becoming insufferably "stuck-up." They began to tell their -adventures to hungry listeners--but they only began; it was not a thing -likely to have an end, with imaginations like theirs to furnish -material. And finally, when they got out their pipes and went serenely -puffing around, the very summit of glory was reached. - -Tom decided that he could be independent of Becky Thatcher now. Glory -was sufficient. He would live for glory. Now that he was distinguished, -maybe she would be wanting to "make up." Well, let her--she should see -that he could be as indifferent as some other people. Presently she -arrived. Tom pretended not to see her. He moved away and joined a group -of boys and girls and began to talk. Soon he observed that she was -tripping gayly back and forth with flushed face and dancing eyes, -pretending to be busy chasing schoolmates, and screaming with laughter -when she made a capture; but he noticed that she always made her -captures in his vicinity, and that she seemed to cast a conscious eye -in his direction at such times, too. It gratified all the vicious -vanity that was in him; and so, instead of winning him, it only "set -him up" the more and made him the more diligent to avoid betraying that -he knew she was about. Presently she gave over skylarking, and moved -irresolutely about, sighing once or twice and glancing furtively and -wistfully toward Tom. Then she observed that now Tom was talking more -particularly to Amy Lawrence than to any one else. She felt a sharp -pang and grew disturbed and uneasy at once. She tried to go away, but -her feet were treacherous, and carried her to the group instead. She -said to a girl almost at Tom's elbow--with sham vivacity: - -"Why, Mary Austin! you bad girl, why didn't you come to Sunday-school?" - -"I did come--didn't you see me?" - -"Why, no! Did you? Where did you sit?" - -"I was in Miss Peters' class, where I always go. I saw YOU." - -"Did you? Why, it's funny I didn't see you. I wanted to tell you about -the picnic." - -"Oh, that's jolly. Who's going to give it?" - -"My ma's going to let me have one." - -"Oh, goody; I hope she'll let ME come." - -"Well, she will. The picnic's for me. She'll let anybody come that I -want, and I want you." - -"That's ever so nice. When is it going to be?" - -"By and by. Maybe about vacation." - -"Oh, won't it be fun! You going to have all the girls and boys?" - -"Yes, every one that's friends to me--or wants to be"; and she glanced -ever so furtively at Tom, but he talked right along to Amy Lawrence -about the terrible storm on the island, and how the lightning tore the -great sycamore tree "all to flinders" while he was "standing within -three feet of it." - -"Oh, may I come?" said Grace Miller. - -"Yes." - -"And me?" said Sally Rogers. - -"Yes." - -"And me, too?" said Susy Harper. "And Joe?" - -"Yes." - -And so on, with clapping of joyful hands till all the group had begged -for invitations but Tom and Amy. Then Tom turned coolly away, still -talking, and took Amy with him. Becky's lips trembled and the tears -came to her eyes; she hid these signs with a forced gayety and went on -chattering, but the life had gone out of the picnic, now, and out of -everything else; she got away as soon as she could and hid herself and -had what her sex call "a good cry." Then she sat moody, with wounded -pride, till the bell rang. She roused up, now, with a vindictive cast -in her eye, and gave her plaited tails a shake and said she knew what -SHE'D do. - -At recess Tom continued his flirtation with Amy with jubilant -self-satisfaction. And he kept drifting about to find Becky and lacerate -her with the performance. At last he spied her, but there was a sudden -falling of his mercury. She was sitting cosily on a little bench behind -the schoolhouse looking at a picture-book with Alfred Temple--and so -absorbed were they, and their heads so close together over the book, -that they did not seem to be conscious of anything in the world besides. -Jealousy ran red-hot through Tom's veins. He began to hate himself for -throwing away the chance Becky had offered for a reconciliation. He -called himself a fool, and all the hard names he could think of. He -wanted to cry with vexation. Amy chatted happily along, as they walked, -for her heart was singing, but Tom's tongue had lost its function. He -did not hear what Amy was saying, and whenever she paused expectantly he -could only stammer an awkward assent, which was as often misplaced as -otherwise. He kept drifting to the rear of the schoolhouse, again and -again, to sear his eyeballs with the hateful spectacle there. He could -not help it. And it maddened him to see, as he thought he saw, that -Becky Thatcher never once suspected that he was even in the land of the -living. But she did see, nevertheless; and she knew she was winning her -fight, too, and was glad to see him suffer as she had suffered. - -Amy's happy prattle became intolerable. Tom hinted at things he had to -attend to; things that must be done; and time was fleeting. But in -vain--the girl chirped on. Tom thought, "Oh, hang her, ain't I ever -going to get rid of her?" At last he must be attending to those -things--and she said artlessly that she would be "around" when school -let out. And he hastened away, hating her for it. - -"Any other boy!" Tom thought, grating his teeth. "Any boy in the whole -town but that Saint Louis smarty that thinks he dresses so fine and is -aristocracy! Oh, all right, I licked you the first day you ever saw -this town, mister, and I'll lick you again! You just wait till I catch -you out! I'll just take and--" - -And he went through the motions of thrashing an imaginary boy ---pummelling the air, and kicking and gouging. "Oh, you do, do you? You -holler 'nough, do you? Now, then, let that learn you!" And so the -imaginary flogging was finished to his satisfaction. - -Tom fled home at noon. His conscience could not endure any more of -Amy's grateful happiness, and his jealousy could bear no more of the -other distress. Becky resumed her picture inspections with Alfred, but -as the minutes dragged along and no Tom came to suffer, her triumph -began to cloud and she lost interest; gravity and absent-mindedness -followed, and then melancholy; two or three times she pricked up her -ear at a footstep, but it was a false hope; no Tom came. At last she -grew entirely miserable and wished she hadn't carried it so far. When -poor Alfred, seeing that he was losing her, he did not know how, kept -exclaiming: "Oh, here's a jolly one! look at this!" she lost patience -at last, and said, "Oh, don't bother me! I don't care for them!" and -burst into tears, and got up and walked away. - -Alfred dropped alongside and was going to try to comfort her, but she -said: - -"Go away and leave me alone, can't you! I hate you!" - -So the boy halted, wondering what he could have done--for she had said -she would look at pictures all through the nooning--and she walked on, -crying. Then Alfred went musing into the deserted schoolhouse. He was -humiliated and angry. He easily guessed his way to the truth--the girl -had simply made a convenience of him to vent her spite upon Tom Sawyer. -He was far from hating Tom the less when this thought occurred to him. -He wished there was some way to get that boy into trouble without much -risk to himself. Tom's spelling-book fell under his eye. Here was his -opportunity. He gratefully opened to the lesson for the afternoon and -poured ink upon the page. - -Becky, glancing in at a window behind him at the moment, saw the act, -and moved on, without discovering herself. She started homeward, now, -intending to find Tom and tell him; Tom would be thankful and their -troubles would be healed. Before she was half way home, however, she -had changed her mind. The thought of Tom's treatment of her when she -was talking about her picnic came scorching back and filled her with -shame. She resolved to let him get whipped on the damaged -spelling-book's account, and to hate him forever, into the bargain. - - - -CHAPTER XIX - -TOM arrived at home in a dreary mood, and the first thing his aunt -said to him showed him that he had brought his sorrows to an -unpromising market: - -"Tom, I've a notion to skin you alive!" - -"Auntie, what have I done?" - -"Well, you've done enough. Here I go over to Sereny Harper, like an -old softy, expecting I'm going to make her believe all that rubbage -about that dream, when lo and behold you she'd found out from Joe that -you was over here and heard all the talk we had that night. Tom, I -don't know what is to become of a boy that will act like that. It makes -me feel so bad to think you could let me go to Sereny Harper and make -such a fool of myself and never say a word." - -This was a new aspect of the thing. His smartness of the morning had -seemed to Tom a good joke before, and very ingenious. It merely looked -mean and shabby now. He hung his head and could not think of anything -to say for a moment. Then he said: - -"Auntie, I wish I hadn't done it--but I didn't think." - -"Oh, child, you never think. You never think of anything but your own -selfishness. You could think to come all the way over here from -Jackson's Island in the night to laugh at our troubles, and you could -think to fool me with a lie about a dream; but you couldn't ever think -to pity us and save us from sorrow." - -"Auntie, I know now it was mean, but I didn't mean to be mean. I -didn't, honest. And besides, I didn't come over here to laugh at you -that night." - -"What did you come for, then?" - -"It was to tell you not to be uneasy about us, because we hadn't got -drownded." - -"Tom, Tom, I would be the thankfullest soul in this world if I could -believe you ever had as good a thought as that, but you know you never -did--and I know it, Tom." - -"Indeed and 'deed I did, auntie--I wish I may never stir if I didn't." - -"Oh, Tom, don't lie--don't do it. It only makes things a hundred times -worse." - -"It ain't a lie, auntie; it's the truth. I wanted to keep you from -grieving--that was all that made me come." - -"I'd give the whole world to believe that--it would cover up a power -of sins, Tom. I'd 'most be glad you'd run off and acted so bad. But it -ain't reasonable; because, why didn't you tell me, child?" - -"Why, you see, when you got to talking about the funeral, I just got -all full of the idea of our coming and hiding in the church, and I -couldn't somehow bear to spoil it. So I just put the bark back in my -pocket and kept mum." - -"What bark?" - -"The bark I had wrote on to tell you we'd gone pirating. I wish, now, -you'd waked up when I kissed you--I do, honest." - -The hard lines in his aunt's face relaxed and a sudden tenderness -dawned in her eyes. - -"DID you kiss me, Tom?" - -"Why, yes, I did." - -"Are you sure you did, Tom?" - -"Why, yes, I did, auntie--certain sure." - -"What did you kiss me for, Tom?" - -"Because I loved you so, and you laid there moaning and I was so sorry." - -The words sounded like truth. The old lady could not hide a tremor in -her voice when she said: - -"Kiss me again, Tom!--and be off with you to school, now, and don't -bother me any more." - -The moment he was gone, she ran to a closet and got out the ruin of a -jacket which Tom had gone pirating in. Then she stopped, with it in her -hand, and said to herself: - -"No, I don't dare. Poor boy, I reckon he's lied about it--but it's a -blessed, blessed lie, there's such a comfort come from it. I hope the -Lord--I KNOW the Lord will forgive him, because it was such -goodheartedness in him to tell it. But I don't want to find out it's a -lie. I won't look." - -She put the jacket away, and stood by musing a minute. Twice she put -out her hand to take the garment again, and twice she refrained. Once -more she ventured, and this time she fortified herself with the -thought: "It's a good lie--it's a good lie--I won't let it grieve me." -So she sought the jacket pocket. A moment later she was reading Tom's -piece of bark through flowing tears and saying: "I could forgive the -boy, now, if he'd committed a million sins!" - - - -CHAPTER XX - -THERE was something about Aunt Polly's manner, when she kissed Tom, -that swept away his low spirits and made him lighthearted and happy -again. He started to school and had the luck of coming upon Becky -Thatcher at the head of Meadow Lane. His mood always determined his -manner. Without a moment's hesitation he ran to her and said: - -"I acted mighty mean to-day, Becky, and I'm so sorry. I won't ever, -ever do that way again, as long as ever I live--please make up, won't -you?" - -The girl stopped and looked him scornfully in the face: - -"I'll thank you to keep yourself TO yourself, Mr. Thomas Sawyer. I'll -never speak to you again." - -She tossed her head and passed on. Tom was so stunned that he had not -even presence of mind enough to say "Who cares, Miss Smarty?" until the -right time to say it had gone by. So he said nothing. But he was in a -fine rage, nevertheless. He moped into the schoolyard wishing she were -a boy, and imagining how he would trounce her if she were. He presently -encountered her and delivered a stinging remark as he passed. She -hurled one in return, and the angry breach was complete. It seemed to -Becky, in her hot resentment, that she could hardly wait for school to -"take in," she was so impatient to see Tom flogged for the injured -spelling-book. If she had had any lingering notion of exposing Alfred -Temple, Tom's offensive fling had driven it entirely away. - -Poor girl, she did not know how fast she was nearing trouble herself. -The master, Mr. Dobbins, had reached middle age with an unsatisfied -ambition. The darling of his desires was, to be a doctor, but poverty -had decreed that he should be nothing higher than a village -schoolmaster. Every day he took a mysterious book out of his desk and -absorbed himself in it at times when no classes were reciting. He kept -that book under lock and key. There was not an urchin in school but was -perishing to have a glimpse of it, but the chance never came. Every boy -and girl had a theory about the nature of that book; but no two -theories were alike, and there was no way of getting at the facts in -the case. Now, as Becky was passing by the desk, which stood near the -door, she noticed that the key was in the lock! It was a precious -moment. She glanced around; found herself alone, and the next instant -she had the book in her hands. The title-page--Professor Somebody's -ANATOMY--carried no information to her mind; so she began to turn the -leaves. She came at once upon a handsomely engraved and colored -frontispiece--a human figure, stark naked. At that moment a shadow fell -on the page and Tom Sawyer stepped in at the door and caught a glimpse -of the picture. Becky snatched at the book to close it, and had the -hard luck to tear the pictured page half down the middle. She thrust -the volume into the desk, turned the key, and burst out crying with -shame and vexation. - -"Tom Sawyer, you are just as mean as you can be, to sneak up on a -person and look at what they're looking at." - -"How could I know you was looking at anything?" - -"You ought to be ashamed of yourself, Tom Sawyer; you know you're -going to tell on me, and oh, what shall I do, what shall I do! I'll be -whipped, and I never was whipped in school." - -Then she stamped her little foot and said: - -"BE so mean if you want to! I know something that's going to happen. -You just wait and you'll see! Hateful, hateful, hateful!"--and she -flung out of the house with a new explosion of crying. - -Tom stood still, rather flustered by this onslaught. Presently he said -to himself: - -"What a curious kind of a fool a girl is! Never been licked in school! -Shucks! What's a licking! That's just like a girl--they're so -thin-skinned and chicken-hearted. Well, of course I ain't going to tell -old Dobbins on this little fool, because there's other ways of getting -even on her, that ain't so mean; but what of it? Old Dobbins will ask -who it was tore his book. Nobody'll answer. Then he'll do just the way -he always does--ask first one and then t'other, and when he comes to the -right girl he'll know it, without any telling. Girls' faces always tell -on them. They ain't got any backbone. She'll get licked. Well, it's a -kind of a tight place for Becky Thatcher, because there ain't any way -out of it." Tom conned the thing a moment longer, and then added: "All -right, though; she'd like to see me in just such a fix--let her sweat it -out!" - -Tom joined the mob of skylarking scholars outside. In a few moments -the master arrived and school "took in." Tom did not feel a strong -interest in his studies. Every time he stole a glance at the girls' -side of the room Becky's face troubled him. Considering all things, he -did not want to pity her, and yet it was all he could do to help it. He -could get up no exultation that was really worthy the name. Presently -the spelling-book discovery was made, and Tom's mind was entirely full -of his own matters for a while after that. Becky roused up from her -lethargy of distress and showed good interest in the proceedings. She -did not expect that Tom could get out of his trouble by denying that he -spilt the ink on the book himself; and she was right. The denial only -seemed to make the thing worse for Tom. Becky supposed she would be -glad of that, and she tried to believe she was glad of it, but she -found she was not certain. When the worst came to the worst, she had an -impulse to get up and tell on Alfred Temple, but she made an effort and -forced herself to keep still--because, said she to herself, "he'll tell -about me tearing the picture sure. I wouldn't say a word, not to save -his life!" - -Tom took his whipping and went back to his seat not at all -broken-hearted, for he thought it was possible that he had unknowingly -upset the ink on the spelling-book himself, in some skylarking bout--he -had denied it for form's sake and because it was custom, and had stuck -to the denial from principle. - -A whole hour drifted by, the master sat nodding in his throne, the air -was drowsy with the hum of study. By and by, Mr. Dobbins straightened -himself up, yawned, then unlocked his desk, and reached for his book, -but seemed undecided whether to take it out or leave it. Most of the -pupils glanced up languidly, but there were two among them that watched -his movements with intent eyes. Mr. Dobbins fingered his book absently -for a while, then took it out and settled himself in his chair to read! -Tom shot a glance at Becky. He had seen a hunted and helpless rabbit -look as she did, with a gun levelled at its head. Instantly he forgot -his quarrel with her. Quick--something must be done! done in a flash, -too! But the very imminence of the emergency paralyzed his invention. -Good!--he had an inspiration! He would run and snatch the book, spring -through the door and fly. But his resolution shook for one little -instant, and the chance was lost--the master opened the volume. If Tom -only had the wasted opportunity back again! Too late. There was no help -for Becky now, he said. The next moment the master faced the school. -Every eye sank under his gaze. There was that in it which smote even -the innocent with fear. There was silence while one might count ten ---the master was gathering his wrath. Then he spoke: "Who tore this book?" - -There was not a sound. One could have heard a pin drop. The stillness -continued; the master searched face after face for signs of guilt. - -"Benjamin Rogers, did you tear this book?" - -A denial. Another pause. - -"Joseph Harper, did you?" - -Another denial. Tom's uneasiness grew more and more intense under the -slow torture of these proceedings. The master scanned the ranks of -boys--considered a while, then turned to the girls: - -"Amy Lawrence?" - -A shake of the head. - -"Gracie Miller?" - -The same sign. - -"Susan Harper, did you do this?" - -Another negative. The next girl was Becky Thatcher. Tom was trembling -from head to foot with excitement and a sense of the hopelessness of -the situation. - -"Rebecca Thatcher" [Tom glanced at her face--it was white with terror] ---"did you tear--no, look me in the face" [her hands rose in appeal] ---"did you tear this book?" - -A thought shot like lightning through Tom's brain. He sprang to his -feet and shouted--"I done it!" - -The school stared in perplexity at this incredible folly. Tom stood a -moment, to gather his dismembered faculties; and when he stepped -forward to go to his punishment the surprise, the gratitude, the -adoration that shone upon him out of poor Becky's eyes seemed pay -enough for a hundred floggings. Inspired by the splendor of his own -act, he took without an outcry the most merciless flaying that even Mr. -Dobbins had ever administered; and also received with indifference the -added cruelty of a command to remain two hours after school should be -dismissed--for he knew who would wait for him outside till his -captivity was done, and not count the tedious time as loss, either. - -Tom went to bed that night planning vengeance against Alfred Temple; -for with shame and repentance Becky had told him all, not forgetting -her own treachery; but even the longing for vengeance had to give way, -soon, to pleasanter musings, and he fell asleep at last with Becky's -latest words lingering dreamily in his ear-- - -"Tom, how COULD you be so noble!" - - - -CHAPTER XXI - -VACATION was approaching. The schoolmaster, always severe, grew -severer and more exacting than ever, for he wanted the school to make a -good showing on "Examination" day. His rod and his ferule were seldom -idle now--at least among the smaller pupils. Only the biggest boys, and -young ladies of eighteen and twenty, escaped lashing. Mr. Dobbins' -lashings were very vigorous ones, too; for although he carried, under -his wig, a perfectly bald and shiny head, he had only reached middle -age, and there was no sign of feebleness in his muscle. As the great -day approached, all the tyranny that was in him came to the surface; he -seemed to take a vindictive pleasure in punishing the least -shortcomings. The consequence was, that the smaller boys spent their -days in terror and suffering and their nights in plotting revenge. They -threw away no opportunity to do the master a mischief. But he kept -ahead all the time. The retribution that followed every vengeful -success was so sweeping and majestic that the boys always retired from -the field badly worsted. At last they conspired together and hit upon a -plan that promised a dazzling victory. They swore in the sign-painter's -boy, told him the scheme, and asked his help. He had his own reasons -for being delighted, for the master boarded in his father's family and -had given the boy ample cause to hate him. The master's wife would go -on a visit to the country in a few days, and there would be nothing to -interfere with the plan; the master always prepared himself for great -occasions by getting pretty well fuddled, and the sign-painter's boy -said that when the dominie had reached the proper condition on -Examination Evening he would "manage the thing" while he napped in his -chair; then he would have him awakened at the right time and hurried -away to school. - -In the fulness of time the interesting occasion arrived. At eight in -the evening the schoolhouse was brilliantly lighted, and adorned with -wreaths and festoons of foliage and flowers. The master sat throned in -his great chair upon a raised platform, with his blackboard behind him. -He was looking tolerably mellow. Three rows of benches on each side and -six rows in front of him were occupied by the dignitaries of the town -and by the parents of the pupils. To his left, back of the rows of -citizens, was a spacious temporary platform upon which were seated the -scholars who were to take part in the exercises of the evening; rows of -small boys, washed and dressed to an intolerable state of discomfort; -rows of gawky big boys; snowbanks of girls and young ladies clad in -lawn and muslin and conspicuously conscious of their bare arms, their -grandmothers' ancient trinkets, their bits of pink and blue ribbon and -the flowers in their hair. All the rest of the house was filled with -non-participating scholars. - -The exercises began. A very little boy stood up and sheepishly -recited, "You'd scarce expect one of my age to speak in public on the -stage," etc.--accompanying himself with the painfully exact and -spasmodic gestures which a machine might have used--supposing the -machine to be a trifle out of order. But he got through safely, though -cruelly scared, and got a fine round of applause when he made his -manufactured bow and retired. - -A little shamefaced girl lisped, "Mary had a little lamb," etc., -performed a compassion-inspiring curtsy, got her meed of applause, and -sat down flushed and happy. - -Tom Sawyer stepped forward with conceited confidence and soared into -the unquenchable and indestructible "Give me liberty or give me death" -speech, with fine fury and frantic gesticulation, and broke down in the -middle of it. A ghastly stage-fright seized him, his legs quaked under -him and he was like to choke. True, he had the manifest sympathy of the -house but he had the house's silence, too, which was even worse than -its sympathy. The master frowned, and this completed the disaster. Tom -struggled awhile and then retired, utterly defeated. There was a weak -attempt at applause, but it died early. - -"The Boy Stood on the Burning Deck" followed; also "The Assyrian Came -Down," and other declamatory gems. Then there were reading exercises, -and a spelling fight. The meagre Latin class recited with honor. The -prime feature of the evening was in order, now--original "compositions" -by the young ladies. Each in her turn stepped forward to the edge of -the platform, cleared her throat, held up her manuscript (tied with -dainty ribbon), and proceeded to read, with labored attention to -"expression" and punctuation. The themes were the same that had been -illuminated upon similar occasions by their mothers before them, their -grandmothers, and doubtless all their ancestors in the female line -clear back to the Crusades. "Friendship" was one; "Memories of Other -Days"; "Religion in History"; "Dream Land"; "The Advantages of -Culture"; "Forms of Political Government Compared and Contrasted"; -"Melancholy"; "Filial Love"; "Heart Longings," etc., etc. - -A prevalent feature in these compositions was a nursed and petted -melancholy; another was a wasteful and opulent gush of "fine language"; -another was a tendency to lug in by the ears particularly prized words -and phrases until they were worn entirely out; and a peculiarity that -conspicuously marked and marred them was the inveterate and intolerable -sermon that wagged its crippled tail at the end of each and every one -of them. No matter what the subject might be, a brain-racking effort -was made to squirm it into some aspect or other that the moral and -religious mind could contemplate with edification. The glaring -insincerity of these sermons was not sufficient to compass the -banishment of the fashion from the schools, and it is not sufficient -to-day; it never will be sufficient while the world stands, perhaps. -There is no school in all our land where the young ladies do not feel -obliged to close their compositions with a sermon; and you will find -that the sermon of the most frivolous and the least religious girl in -the school is always the longest and the most relentlessly pious. But -enough of this. Homely truth is unpalatable. - -Let us return to the "Examination." The first composition that was -read was one entitled "Is this, then, Life?" Perhaps the reader can -endure an extract from it: - - "In the common walks of life, with what delightful - emotions does the youthful mind look forward to some - anticipated scene of festivity! Imagination is busy - sketching rose-tinted pictures of joy. In fancy, the - voluptuous votary of fashion sees herself amid the - festive throng, 'the observed of all observers.' Her - graceful form, arrayed in snowy robes, is whirling - through the mazes of the joyous dance; her eye is - brightest, her step is lightest in the gay assembly. - - "In such delicious fancies time quickly glides by, - and the welcome hour arrives for her entrance into - the Elysian world, of which she has had such bright - dreams. How fairy-like does everything appear to - her enchanted vision! Each new scene is more charming - than the last. But after a while she finds that - beneath this goodly exterior, all is vanity, the - flattery which once charmed her soul, now grates - harshly upon her ear; the ball-room has lost its - charms; and with wasted health and imbittered heart, - she turns away with the conviction that earthly - pleasures cannot satisfy the longings of the soul!" - -And so forth and so on. There was a buzz of gratification from time to -time during the reading, accompanied by whispered ejaculations of "How -sweet!" "How eloquent!" "So true!" etc., and after the thing had closed -with a peculiarly afflicting sermon the applause was enthusiastic. - -Then arose a slim, melancholy girl, whose face had the "interesting" -paleness that comes of pills and indigestion, and read a "poem." Two -stanzas of it will do: - - "A MISSOURI MAIDEN'S FAREWELL TO ALABAMA - - "Alabama, good-bye! I love thee well! - But yet for a while do I leave thee now! - Sad, yes, sad thoughts of thee my heart doth swell, - And burning recollections throng my brow! - For I have wandered through thy flowery woods; - Have roamed and read near Tallapoosa's stream; - Have listened to Tallassee's warring floods, - And wooed on Coosa's side Aurora's beam. - - "Yet shame I not to bear an o'er-full heart, - Nor blush to turn behind my tearful eyes; - 'Tis from no stranger land I now must part, - 'Tis to no strangers left I yield these sighs. - Welcome and home were mine within this State, - Whose vales I leave--whose spires fade fast from me - And cold must be mine eyes, and heart, and tete, - When, dear Alabama! they turn cold on thee!" - -There were very few there who knew what "tete" meant, but the poem was -very satisfactory, nevertheless. - -Next appeared a dark-complexioned, black-eyed, black-haired young -lady, who paused an impressive moment, assumed a tragic expression, and -began to read in a measured, solemn tone: - - "A VISION - - "Dark and tempestuous was night. Around the - throne on high not a single star quivered; but - the deep intonations of the heavy thunder - constantly vibrated upon the ear; whilst the - terrific lightning revelled in angry mood - through the cloudy chambers of heaven, seeming - to scorn the power exerted over its terror by - the illustrious Franklin! Even the boisterous - winds unanimously came forth from their mystic - homes, and blustered about as if to enhance by - their aid the wildness of the scene. - - "At such a time, so dark, so dreary, for human - sympathy my very spirit sighed; but instead thereof, - - "'My dearest friend, my counsellor, my comforter - and guide--My joy in grief, my second bliss - in joy,' came to my side. She moved like one of - those bright beings pictured in the sunny walks - of fancy's Eden by the romantic and young, a - queen of beauty unadorned save by her own - transcendent loveliness. So soft was her step, it - failed to make even a sound, and but for the - magical thrill imparted by her genial touch, as - other unobtrusive beauties, she would have glided - away un-perceived--unsought. A strange sadness - rested upon her features, like icy tears upon - the robe of December, as she pointed to the - contending elements without, and bade me contemplate - the two beings presented." - -This nightmare occupied some ten pages of manuscript and wound up with -a sermon so destructive of all hope to non-Presbyterians that it took -the first prize. This composition was considered to be the very finest -effort of the evening. The mayor of the village, in delivering the -prize to the author of it, made a warm speech in which he said that it -was by far the most "eloquent" thing he had ever listened to, and that -Daniel Webster himself might well be proud of it. - -It may be remarked, in passing, that the number of compositions in -which the word "beauteous" was over-fondled, and human experience -referred to as "life's page," was up to the usual average. - -Now the master, mellow almost to the verge of geniality, put his chair -aside, turned his back to the audience, and began to draw a map of -America on the blackboard, to exercise the geography class upon. But he -made a sad business of it with his unsteady hand, and a smothered -titter rippled over the house. He knew what the matter was, and set -himself to right it. He sponged out lines and remade them; but he only -distorted them more than ever, and the tittering was more pronounced. -He threw his entire attention upon his work, now, as if determined not -to be put down by the mirth. He felt that all eyes were fastened upon -him; he imagined he was succeeding, and yet the tittering continued; it -even manifestly increased. And well it might. There was a garret above, -pierced with a scuttle over his head; and down through this scuttle -came a cat, suspended around the haunches by a string; she had a rag -tied about her head and jaws to keep her from mewing; as she slowly -descended she curved upward and clawed at the string, she swung -downward and clawed at the intangible air. The tittering rose higher -and higher--the cat was within six inches of the absorbed teacher's -head--down, down, a little lower, and she grabbed his wig with her -desperate claws, clung to it, and was snatched up into the garret in an -instant with her trophy still in her possession! And how the light did -blaze abroad from the master's bald pate--for the sign-painter's boy -had GILDED it! - -That broke up the meeting. The boys were avenged. Vacation had come. - - NOTE:--The pretended "compositions" quoted in - this chapter are taken without alteration from a - volume entitled "Prose and Poetry, by a Western - Lady"--but they are exactly and precisely after - the schoolgirl pattern, and hence are much - happier than any mere imitations could be. - - - -CHAPTER XXII - -TOM joined the new order of Cadets of Temperance, being attracted by -the showy character of their "regalia." He promised to abstain from -smoking, chewing, and profanity as long as he remained a member. Now he -found out a new thing--namely, that to promise not to do a thing is the -surest way in the world to make a body want to go and do that very -thing. Tom soon found himself tormented with a desire to drink and -swear; the desire grew to be so intense that nothing but the hope of a -chance to display himself in his red sash kept him from withdrawing -from the order. Fourth of July was coming; but he soon gave that up ---gave it up before he had worn his shackles over forty-eight hours--and -fixed his hopes upon old Judge Frazer, justice of the peace, who was -apparently on his deathbed and would have a big public funeral, since -he was so high an official. During three days Tom was deeply concerned -about the Judge's condition and hungry for news of it. Sometimes his -hopes ran high--so high that he would venture to get out his regalia -and practise before the looking-glass. But the Judge had a most -discouraging way of fluctuating. At last he was pronounced upon the -mend--and then convalescent. Tom was disgusted; and felt a sense of -injury, too. He handed in his resignation at once--and that night the -Judge suffered a relapse and died. Tom resolved that he would never -trust a man like that again. - -The funeral was a fine thing. The Cadets paraded in a style calculated -to kill the late member with envy. Tom was a free boy again, however ---there was something in that. He could drink and swear, now--but found -to his surprise that he did not want to. The simple fact that he could, -took the desire away, and the charm of it. - -Tom presently wondered to find that his coveted vacation was beginning -to hang a little heavily on his hands. - -He attempted a diary--but nothing happened during three days, and so -he abandoned it. - -The first of all the negro minstrel shows came to town, and made a -sensation. Tom and Joe Harper got up a band of performers and were -happy for two days. - -Even the Glorious Fourth was in some sense a failure, for it rained -hard, there was no procession in consequence, and the greatest man in -the world (as Tom supposed), Mr. Benton, an actual United States -Senator, proved an overwhelming disappointment--for he was not -twenty-five feet high, nor even anywhere in the neighborhood of it. - -A circus came. The boys played circus for three days afterward in -tents made of rag carpeting--admission, three pins for boys, two for -girls--and then circusing was abandoned. - -A phrenologist and a mesmerizer came--and went again and left the -village duller and drearier than ever. - -There were some boys-and-girls' parties, but they were so few and so -delightful that they only made the aching voids between ache the harder. - -Becky Thatcher was gone to her Constantinople home to stay with her -parents during vacation--so there was no bright side to life anywhere. - -The dreadful secret of the murder was a chronic misery. It was a very -cancer for permanency and pain. - -Then came the measles. - -During two long weeks Tom lay a prisoner, dead to the world and its -happenings. He was very ill, he was interested in nothing. When he got -upon his feet at last and moved feebly down-town, a melancholy change -had come over everything and every creature. There had been a -"revival," and everybody had "got religion," not only the adults, but -even the boys and girls. Tom went about, hoping against hope for the -sight of one blessed sinful face, but disappointment crossed him -everywhere. He found Joe Harper studying a Testament, and turned sadly -away from the depressing spectacle. He sought Ben Rogers, and found him -visiting the poor with a basket of tracts. He hunted up Jim Hollis, who -called his attention to the precious blessing of his late measles as a -warning. Every boy he encountered added another ton to his depression; -and when, in desperation, he flew for refuge at last to the bosom of -Huckleberry Finn and was received with a Scriptural quotation, his -heart broke and he crept home and to bed realizing that he alone of all -the town was lost, forever and forever. - -And that night there came on a terrific storm, with driving rain, -awful claps of thunder and blinding sheets of lightning. He covered his -head with the bedclothes and waited in a horror of suspense for his -doom; for he had not the shadow of a doubt that all this hubbub was -about him. He believed he had taxed the forbearance of the powers above -to the extremity of endurance and that this was the result. It might -have seemed to him a waste of pomp and ammunition to kill a bug with a -battery of artillery, but there seemed nothing incongruous about the -getting up such an expensive thunderstorm as this to knock the turf -from under an insect like himself. - -By and by the tempest spent itself and died without accomplishing its -object. The boy's first impulse was to be grateful, and reform. His -second was to wait--for there might not be any more storms. - -The next day the doctors were back; Tom had relapsed. The three weeks -he spent on his back this time seemed an entire age. When he got abroad -at last he was hardly grateful that he had been spared, remembering how -lonely was his estate, how companionless and forlorn he was. He drifted -listlessly down the street and found Jim Hollis acting as judge in a -juvenile court that was trying a cat for murder, in the presence of her -victim, a bird. He found Joe Harper and Huck Finn up an alley eating a -stolen melon. Poor lads! they--like Tom--had suffered a relapse. - - - -CHAPTER XXIII - -AT last the sleepy atmosphere was stirred--and vigorously: the murder -trial came on in the court. It became the absorbing topic of village -talk immediately. Tom could not get away from it. Every reference to -the murder sent a shudder to his heart, for his troubled conscience and -fears almost persuaded him that these remarks were put forth in his -hearing as "feelers"; he did not see how he could be suspected of -knowing anything about the murder, but still he could not be -comfortable in the midst of this gossip. It kept him in a cold shiver -all the time. He took Huck to a lonely place to have a talk with him. -It would be some relief to unseal his tongue for a little while; to -divide his burden of distress with another sufferer. Moreover, he -wanted to assure himself that Huck had remained discreet. - -"Huck, have you ever told anybody about--that?" - -"'Bout what?" - -"You know what." - -"Oh--'course I haven't." - -"Never a word?" - -"Never a solitary word, so help me. What makes you ask?" - -"Well, I was afeard." - -"Why, Tom Sawyer, we wouldn't be alive two days if that got found out. -YOU know that." - -Tom felt more comfortable. After a pause: - -"Huck, they couldn't anybody get you to tell, could they?" - -"Get me to tell? Why, if I wanted that half-breed devil to drownd me -they could get me to tell. They ain't no different way." - -"Well, that's all right, then. I reckon we're safe as long as we keep -mum. But let's swear again, anyway. It's more surer." - -"I'm agreed." - -So they swore again with dread solemnities. - -"What is the talk around, Huck? I've heard a power of it." - -"Talk? Well, it's just Muff Potter, Muff Potter, Muff Potter all the -time. It keeps me in a sweat, constant, so's I want to hide som'ers." - -"That's just the same way they go on round me. I reckon he's a goner. -Don't you feel sorry for him, sometimes?" - -"Most always--most always. He ain't no account; but then he hain't -ever done anything to hurt anybody. Just fishes a little, to get money -to get drunk on--and loafs around considerable; but lord, we all do -that--leastways most of us--preachers and such like. But he's kind of -good--he give me half a fish, once, when there warn't enough for two; -and lots of times he's kind of stood by me when I was out of luck." - -"Well, he's mended kites for me, Huck, and knitted hooks on to my -line. I wish we could get him out of there." - -"My! we couldn't get him out, Tom. And besides, 'twouldn't do any -good; they'd ketch him again." - -"Yes--so they would. But I hate to hear 'em abuse him so like the -dickens when he never done--that." - -"I do too, Tom. Lord, I hear 'em say he's the bloodiest looking -villain in this country, and they wonder he wasn't ever hung before." - -"Yes, they talk like that, all the time. I've heard 'em say that if he -was to get free they'd lynch him." - -"And they'd do it, too." - -The boys had a long talk, but it brought them little comfort. As the -twilight drew on, they found themselves hanging about the neighborhood -of the little isolated jail, perhaps with an undefined hope that -something would happen that might clear away their difficulties. But -nothing happened; there seemed to be no angels or fairies interested in -this luckless captive. - -The boys did as they had often done before--went to the cell grating -and gave Potter some tobacco and matches. He was on the ground floor -and there were no guards. - -His gratitude for their gifts had always smote their consciences -before--it cut deeper than ever, this time. They felt cowardly and -treacherous to the last degree when Potter said: - -"You've been mighty good to me, boys--better'n anybody else in this -town. And I don't forget it, I don't. Often I says to myself, says I, -'I used to mend all the boys' kites and things, and show 'em where the -good fishin' places was, and befriend 'em what I could, and now they've -all forgot old Muff when he's in trouble; but Tom don't, and Huck -don't--THEY don't forget him, says I, 'and I don't forget them.' Well, -boys, I done an awful thing--drunk and crazy at the time--that's the -only way I account for it--and now I got to swing for it, and it's -right. Right, and BEST, too, I reckon--hope so, anyway. Well, we won't -talk about that. I don't want to make YOU feel bad; you've befriended -me. But what I want to say, is, don't YOU ever get drunk--then you won't -ever get here. Stand a litter furder west--so--that's it; it's a prime -comfort to see faces that's friendly when a body's in such a muck of -trouble, and there don't none come here but yourn. Good friendly -faces--good friendly faces. Git up on one another's backs and let me -touch 'em. That's it. Shake hands--yourn'll come through the bars, but -mine's too big. Little hands, and weak--but they've helped Muff Potter -a power, and they'd help him more if they could." - -Tom went home miserable, and his dreams that night were full of -horrors. The next day and the day after, he hung about the court-room, -drawn by an almost irresistible impulse to go in, but forcing himself -to stay out. Huck was having the same experience. They studiously -avoided each other. Each wandered away, from time to time, but the same -dismal fascination always brought them back presently. Tom kept his -ears open when idlers sauntered out of the court-room, but invariably -heard distressing news--the toils were closing more and more -relentlessly around poor Potter. At the end of the second day the -village talk was to the effect that Injun Joe's evidence stood firm and -unshaken, and that there was not the slightest question as to what the -jury's verdict would be. - -Tom was out late, that night, and came to bed through the window. He -was in a tremendous state of excitement. It was hours before he got to -sleep. All the village flocked to the court-house the next morning, for -this was to be the great day. Both sexes were about equally represented -in the packed audience. After a long wait the jury filed in and took -their places; shortly afterward, Potter, pale and haggard, timid and -hopeless, was brought in, with chains upon him, and seated where all -the curious eyes could stare at him; no less conspicuous was Injun Joe, -stolid as ever. There was another pause, and then the judge arrived and -the sheriff proclaimed the opening of the court. The usual whisperings -among the lawyers and gathering together of papers followed. These -details and accompanying delays worked up an atmosphere of preparation -that was as impressive as it was fascinating. - -Now a witness was called who testified that he found Muff Potter -washing in the brook, at an early hour of the morning that the murder -was discovered, and that he immediately sneaked away. After some -further questioning, counsel for the prosecution said: - -"Take the witness." - -The prisoner raised his eyes for a moment, but dropped them again when -his own counsel said: - -"I have no questions to ask him." - -The next witness proved the finding of the knife near the corpse. -Counsel for the prosecution said: - -"Take the witness." - -"I have no questions to ask him," Potter's lawyer replied. - -A third witness swore he had often seen the knife in Potter's -possession. - -"Take the witness." - -Counsel for Potter declined to question him. The faces of the audience -began to betray annoyance. Did this attorney mean to throw away his -client's life without an effort? - -Several witnesses deposed concerning Potter's guilty behavior when -brought to the scene of the murder. They were allowed to leave the -stand without being cross-questioned. - -Every detail of the damaging circumstances that occurred in the -graveyard upon that morning which all present remembered so well was -brought out by credible witnesses, but none of them were cross-examined -by Potter's lawyer. The perplexity and dissatisfaction of the house -expressed itself in murmurs and provoked a reproof from the bench. -Counsel for the prosecution now said: - -"By the oaths of citizens whose simple word is above suspicion, we -have fastened this awful crime, beyond all possibility of question, -upon the unhappy prisoner at the bar. We rest our case here." - -A groan escaped from poor Potter, and he put his face in his hands and -rocked his body softly to and fro, while a painful silence reigned in -the court-room. Many men were moved, and many women's compassion -testified itself in tears. Counsel for the defence rose and said: - -"Your honor, in our remarks at the opening of this trial, we -foreshadowed our purpose to prove that our client did this fearful deed -while under the influence of a blind and irresponsible delirium -produced by drink. We have changed our mind. We shall not offer that -plea." [Then to the clerk:] "Call Thomas Sawyer!" - -A puzzled amazement awoke in every face in the house, not even -excepting Potter's. Every eye fastened itself with wondering interest -upon Tom as he rose and took his place upon the stand. The boy looked -wild enough, for he was badly scared. The oath was administered. - -"Thomas Sawyer, where were you on the seventeenth of June, about the -hour of midnight?" - -Tom glanced at Injun Joe's iron face and his tongue failed him. The -audience listened breathless, but the words refused to come. After a -few moments, however, the boy got a little of his strength back, and -managed to put enough of it into his voice to make part of the house -hear: - -"In the graveyard!" - -"A little bit louder, please. Don't be afraid. You were--" - -"In the graveyard." - -A contemptuous smile flitted across Injun Joe's face. - -"Were you anywhere near Horse Williams' grave?" - -"Yes, sir." - -"Speak up--just a trifle louder. How near were you?" - -"Near as I am to you." - -"Were you hidden, or not?" - -"I was hid." - -"Where?" - -"Behind the elms that's on the edge of the grave." - -Injun Joe gave a barely perceptible start. - -"Any one with you?" - -"Yes, sir. I went there with--" - -"Wait--wait a moment. Never mind mentioning your companion's name. We -will produce him at the proper time. Did you carry anything there with -you." - -Tom hesitated and looked confused. - -"Speak out, my boy--don't be diffident. The truth is always -respectable. What did you take there?" - -"Only a--a--dead cat." - -There was a ripple of mirth, which the court checked. - -"We will produce the skeleton of that cat. Now, my boy, tell us -everything that occurred--tell it in your own way--don't skip anything, -and don't be afraid." - -Tom began--hesitatingly at first, but as he warmed to his subject his -words flowed more and more easily; in a little while every sound ceased -but his own voice; every eye fixed itself upon him; with parted lips -and bated breath the audience hung upon his words, taking no note of -time, rapt in the ghastly fascinations of the tale. The strain upon -pent emotion reached its climax when the boy said: - -"--and as the doctor fetched the board around and Muff Potter fell, -Injun Joe jumped with the knife and--" - -Crash! Quick as lightning the half-breed sprang for a window, tore his -way through all opposers, and was gone! - - - -CHAPTER XXIV - -TOM was a glittering hero once more--the pet of the old, the envy of -the young. His name even went into immortal print, for the village -paper magnified him. There were some that believed he would be -President, yet, if he escaped hanging. - -As usual, the fickle, unreasoning world took Muff Potter to its bosom -and fondled him as lavishly as it had abused him before. But that sort -of conduct is to the world's credit; therefore it is not well to find -fault with it. - -Tom's days were days of splendor and exultation to him, but his nights -were seasons of horror. Injun Joe infested all his dreams, and always -with doom in his eye. Hardly any temptation could persuade the boy to -stir abroad after nightfall. Poor Huck was in the same state of -wretchedness and terror, for Tom had told the whole story to the lawyer -the night before the great day of the trial, and Huck was sore afraid -that his share in the business might leak out, yet, notwithstanding -Injun Joe's flight had saved him the suffering of testifying in court. -The poor fellow had got the attorney to promise secrecy, but what of -that? Since Tom's harassed conscience had managed to drive him to the -lawyer's house by night and wring a dread tale from lips that had been -sealed with the dismalest and most formidable of oaths, Huck's -confidence in the human race was well-nigh obliterated. - -Daily Muff Potter's gratitude made Tom glad he had spoken; but nightly -he wished he had sealed up his tongue. - -Half the time Tom was afraid Injun Joe would never be captured; the -other half he was afraid he would be. He felt sure he never could draw -a safe breath again until that man was dead and he had seen the corpse. - -Rewards had been offered, the country had been scoured, but no Injun -Joe was found. One of those omniscient and awe-inspiring marvels, a -detective, came up from St. Louis, moused around, shook his head, -looked wise, and made that sort of astounding success which members of -that craft usually achieve. That is to say, he "found a clew." But you -can't hang a "clew" for murder, and so after that detective had got -through and gone home, Tom felt just as insecure as he was before. - -The slow days drifted on, and each left behind it a slightly lightened -weight of apprehension. - - - -CHAPTER XXV - -THERE comes a time in every rightly-constructed boy's life when he has -a raging desire to go somewhere and dig for hidden treasure. This -desire suddenly came upon Tom one day. He sallied out to find Joe -Harper, but failed of success. Next he sought Ben Rogers; he had gone -fishing. Presently he stumbled upon Huck Finn the Red-Handed. Huck -would answer. Tom took him to a private place and opened the matter to -him confidentially. Huck was willing. Huck was always willing to take a -hand in any enterprise that offered entertainment and required no -capital, for he had a troublesome superabundance of that sort of time -which is not money. "Where'll we dig?" said Huck. - -"Oh, most anywhere." - -"Why, is it hid all around?" - -"No, indeed it ain't. It's hid in mighty particular places, Huck ---sometimes on islands, sometimes in rotten chests under the end of a -limb of an old dead tree, just where the shadow falls at midnight; but -mostly under the floor in ha'nted houses." - -"Who hides it?" - -"Why, robbers, of course--who'd you reckon? Sunday-school -sup'rintendents?" - -"I don't know. If 'twas mine I wouldn't hide it; I'd spend it and have -a good time." - -"So would I. But robbers don't do that way. They always hide it and -leave it there." - -"Don't they come after it any more?" - -"No, they think they will, but they generally forget the marks, or -else they die. Anyway, it lays there a long time and gets rusty; and by -and by somebody finds an old yellow paper that tells how to find the -marks--a paper that's got to be ciphered over about a week because it's -mostly signs and hy'roglyphics." - -"Hyro--which?" - -"Hy'roglyphics--pictures and things, you know, that don't seem to mean -anything." - -"Have you got one of them papers, Tom?" - -"No." - -"Well then, how you going to find the marks?" - -"I don't want any marks. They always bury it under a ha'nted house or -on an island, or under a dead tree that's got one limb sticking out. -Well, we've tried Jackson's Island a little, and we can try it again -some time; and there's the old ha'nted house up the Still-House branch, -and there's lots of dead-limb trees--dead loads of 'em." - -"Is it under all of them?" - -"How you talk! No!" - -"Then how you going to know which one to go for?" - -"Go for all of 'em!" - -"Why, Tom, it'll take all summer." - -"Well, what of that? Suppose you find a brass pot with a hundred -dollars in it, all rusty and gray, or rotten chest full of di'monds. -How's that?" - -Huck's eyes glowed. - -"That's bully. Plenty bully enough for me. Just you gimme the hundred -dollars and I don't want no di'monds." - -"All right. But I bet you I ain't going to throw off on di'monds. Some -of 'em's worth twenty dollars apiece--there ain't any, hardly, but's -worth six bits or a dollar." - -"No! Is that so?" - -"Cert'nly--anybody'll tell you so. Hain't you ever seen one, Huck?" - -"Not as I remember." - -"Oh, kings have slathers of them." - -"Well, I don' know no kings, Tom." - -"I reckon you don't. But if you was to go to Europe you'd see a raft -of 'em hopping around." - -"Do they hop?" - -"Hop?--your granny! No!" - -"Well, what did you say they did, for?" - -"Shucks, I only meant you'd SEE 'em--not hopping, of course--what do -they want to hop for?--but I mean you'd just see 'em--scattered around, -you know, in a kind of a general way. Like that old humpbacked Richard." - -"Richard? What's his other name?" - -"He didn't have any other name. Kings don't have any but a given name." - -"No?" - -"But they don't." - -"Well, if they like it, Tom, all right; but I don't want to be a king -and have only just a given name, like a nigger. But say--where you -going to dig first?" - -"Well, I don't know. S'pose we tackle that old dead-limb tree on the -hill t'other side of Still-House branch?" - -"I'm agreed." - -So they got a crippled pick and a shovel, and set out on their -three-mile tramp. They arrived hot and panting, and threw themselves -down in the shade of a neighboring elm to rest and have a smoke. - -"I like this," said Tom. - -"So do I." - -"Say, Huck, if we find a treasure here, what you going to do with your -share?" - -"Well, I'll have pie and a glass of soda every day, and I'll go to -every circus that comes along. I bet I'll have a gay time." - -"Well, ain't you going to save any of it?" - -"Save it? What for?" - -"Why, so as to have something to live on, by and by." - -"Oh, that ain't any use. Pap would come back to thish-yer town some -day and get his claws on it if I didn't hurry up, and I tell you he'd -clean it out pretty quick. What you going to do with yourn, Tom?" - -"I'm going to buy a new drum, and a sure-'nough sword, and a red -necktie and a bull pup, and get married." - -"Married!" - -"That's it." - -"Tom, you--why, you ain't in your right mind." - -"Wait--you'll see." - -"Well, that's the foolishest thing you could do. Look at pap and my -mother. Fight! Why, they used to fight all the time. I remember, mighty -well." - -"That ain't anything. The girl I'm going to marry won't fight." - -"Tom, I reckon they're all alike. They'll all comb a body. Now you -better think 'bout this awhile. I tell you you better. What's the name -of the gal?" - -"It ain't a gal at all--it's a girl." - -"It's all the same, I reckon; some says gal, some says girl--both's -right, like enough. Anyway, what's her name, Tom?" - -"I'll tell you some time--not now." - -"All right--that'll do. Only if you get married I'll be more lonesomer -than ever." - -"No you won't. You'll come and live with me. Now stir out of this and -we'll go to digging." - -They worked and sweated for half an hour. No result. They toiled -another half-hour. Still no result. Huck said: - -"Do they always bury it as deep as this?" - -"Sometimes--not always. Not generally. I reckon we haven't got the -right place." - -So they chose a new spot and began again. The labor dragged a little, -but still they made progress. They pegged away in silence for some -time. Finally Huck leaned on his shovel, swabbed the beaded drops from -his brow with his sleeve, and said: - -"Where you going to dig next, after we get this one?" - -"I reckon maybe we'll tackle the old tree that's over yonder on -Cardiff Hill back of the widow's." - -"I reckon that'll be a good one. But won't the widow take it away from -us, Tom? It's on her land." - -"SHE take it away! Maybe she'd like to try it once. Whoever finds one -of these hid treasures, it belongs to him. It don't make any difference -whose land it's on." - -That was satisfactory. The work went on. By and by Huck said: - -"Blame it, we must be in the wrong place again. What do you think?" - -"It is mighty curious, Huck. I don't understand it. Sometimes witches -interfere. I reckon maybe that's what's the trouble now." - -"Shucks! Witches ain't got no power in the daytime." - -"Well, that's so. I didn't think of that. Oh, I know what the matter -is! What a blamed lot of fools we are! You got to find out where the -shadow of the limb falls at midnight, and that's where you dig!" - -"Then consound it, we've fooled away all this work for nothing. Now -hang it all, we got to come back in the night. It's an awful long way. -Can you get out?" - -"I bet I will. We've got to do it to-night, too, because if somebody -sees these holes they'll know in a minute what's here and they'll go -for it." - -"Well, I'll come around and maow to-night." - -"All right. Let's hide the tools in the bushes." - -The boys were there that night, about the appointed time. They sat in -the shadow waiting. It was a lonely place, and an hour made solemn by -old traditions. Spirits whispered in the rustling leaves, ghosts lurked -in the murky nooks, the deep baying of a hound floated up out of the -distance, an owl answered with his sepulchral note. The boys were -subdued by these solemnities, and talked little. By and by they judged -that twelve had come; they marked where the shadow fell, and began to -dig. Their hopes commenced to rise. Their interest grew stronger, and -their industry kept pace with it. The hole deepened and still deepened, -but every time their hearts jumped to hear the pick strike upon -something, they only suffered a new disappointment. It was only a stone -or a chunk. At last Tom said: - -"It ain't any use, Huck, we're wrong again." - -"Well, but we CAN'T be wrong. We spotted the shadder to a dot." - -"I know it, but then there's another thing." - -"What's that?". - -"Why, we only guessed at the time. Like enough it was too late or too -early." - -Huck dropped his shovel. - -"That's it," said he. "That's the very trouble. We got to give this -one up. We can't ever tell the right time, and besides this kind of -thing's too awful, here this time of night with witches and ghosts -a-fluttering around so. I feel as if something's behind me all the time; -and I'm afeard to turn around, becuz maybe there's others in front -a-waiting for a chance. I been creeping all over, ever since I got here." - -"Well, I've been pretty much so, too, Huck. They most always put in a -dead man when they bury a treasure under a tree, to look out for it." - -"Lordy!" - -"Yes, they do. I've always heard that." - -"Tom, I don't like to fool around much where there's dead people. A -body's bound to get into trouble with 'em, sure." - -"I don't like to stir 'em up, either. S'pose this one here was to -stick his skull out and say something!" - -"Don't Tom! It's awful." - -"Well, it just is. Huck, I don't feel comfortable a bit." - -"Say, Tom, let's give this place up, and try somewheres else." - -"All right, I reckon we better." - -"What'll it be?" - -Tom considered awhile; and then said: - -"The ha'nted house. That's it!" - -"Blame it, I don't like ha'nted houses, Tom. Why, they're a dern sight -worse'n dead people. Dead people might talk, maybe, but they don't come -sliding around in a shroud, when you ain't noticing, and peep over your -shoulder all of a sudden and grit their teeth, the way a ghost does. I -couldn't stand such a thing as that, Tom--nobody could." - -"Yes, but, Huck, ghosts don't travel around only at night. They won't -hender us from digging there in the daytime." - -"Well, that's so. But you know mighty well people don't go about that -ha'nted house in the day nor the night." - -"Well, that's mostly because they don't like to go where a man's been -murdered, anyway--but nothing's ever been seen around that house except -in the night--just some blue lights slipping by the windows--no regular -ghosts." - -"Well, where you see one of them blue lights flickering around, Tom, -you can bet there's a ghost mighty close behind it. It stands to -reason. Becuz you know that they don't anybody but ghosts use 'em." - -"Yes, that's so. But anyway they don't come around in the daytime, so -what's the use of our being afeard?" - -"Well, all right. We'll tackle the ha'nted house if you say so--but I -reckon it's taking chances." - -They had started down the hill by this time. There in the middle of -the moonlit valley below them stood the "ha'nted" house, utterly -isolated, its fences gone long ago, rank weeds smothering the very -doorsteps, the chimney crumbled to ruin, the window-sashes vacant, a -corner of the roof caved in. The boys gazed awhile, half expecting to -see a blue light flit past a window; then talking in a low tone, as -befitted the time and the circumstances, they struck far off to the -right, to give the haunted house a wide berth, and took their way -homeward through the woods that adorned the rearward side of Cardiff -Hill. - - - -CHAPTER XXVI - -ABOUT noon the next day the boys arrived at the dead tree; they had -come for their tools. Tom was impatient to go to the haunted house; -Huck was measurably so, also--but suddenly said: - -"Lookyhere, Tom, do you know what day it is?" - -Tom mentally ran over the days of the week, and then quickly lifted -his eyes with a startled look in them-- - -"My! I never once thought of it, Huck!" - -"Well, I didn't neither, but all at once it popped onto me that it was -Friday." - -"Blame it, a body can't be too careful, Huck. We might 'a' got into an -awful scrape, tackling such a thing on a Friday." - -"MIGHT! Better say we WOULD! There's some lucky days, maybe, but -Friday ain't." - -"Any fool knows that. I don't reckon YOU was the first that found it -out, Huck." - -"Well, I never said I was, did I? And Friday ain't all, neither. I had -a rotten bad dream last night--dreampt about rats." - -"No! Sure sign of trouble. Did they fight?" - -"No." - -"Well, that's good, Huck. When they don't fight it's only a sign that -there's trouble around, you know. All we got to do is to look mighty -sharp and keep out of it. We'll drop this thing for to-day, and play. -Do you know Robin Hood, Huck?" - -"No. Who's Robin Hood?" - -"Why, he was one of the greatest men that was ever in England--and the -best. He was a robber." - -"Cracky, I wisht I was. Who did he rob?" - -"Only sheriffs and bishops and rich people and kings, and such like. -But he never bothered the poor. He loved 'em. He always divided up with -'em perfectly square." - -"Well, he must 'a' been a brick." - -"I bet you he was, Huck. Oh, he was the noblest man that ever was. -They ain't any such men now, I can tell you. He could lick any man in -England, with one hand tied behind him; and he could take his yew bow -and plug a ten-cent piece every time, a mile and a half." - -"What's a YEW bow?" - -"I don't know. It's some kind of a bow, of course. And if he hit that -dime only on the edge he would set down and cry--and curse. But we'll -play Robin Hood--it's nobby fun. I'll learn you." - -"I'm agreed." - -So they played Robin Hood all the afternoon, now and then casting a -yearning eye down upon the haunted house and passing a remark about the -morrow's prospects and possibilities there. As the sun began to sink -into the west they took their way homeward athwart the long shadows of -the trees and soon were buried from sight in the forests of Cardiff -Hill. - -On Saturday, shortly after noon, the boys were at the dead tree again. -They had a smoke and a chat in the shade, and then dug a little in -their last hole, not with great hope, but merely because Tom said there -were so many cases where people had given up a treasure after getting -down within six inches of it, and then somebody else had come along and -turned it up with a single thrust of a shovel. The thing failed this -time, however, so the boys shouldered their tools and went away feeling -that they had not trifled with fortune, but had fulfilled all the -requirements that belong to the business of treasure-hunting. - -When they reached the haunted house there was something so weird and -grisly about the dead silence that reigned there under the baking sun, -and something so depressing about the loneliness and desolation of the -place, that they were afraid, for a moment, to venture in. Then they -crept to the door and took a trembling peep. They saw a weed-grown, -floorless room, unplastered, an ancient fireplace, vacant windows, a -ruinous staircase; and here, there, and everywhere hung ragged and -abandoned cobwebs. They presently entered, softly, with quickened -pulses, talking in whispers, ears alert to catch the slightest sound, -and muscles tense and ready for instant retreat. - -In a little while familiarity modified their fears and they gave the -place a critical and interested examination, rather admiring their own -boldness, and wondering at it, too. Next they wanted to look up-stairs. -This was something like cutting off retreat, but they got to daring -each other, and of course there could be but one result--they threw -their tools into a corner and made the ascent. Up there were the same -signs of decay. In one corner they found a closet that promised -mystery, but the promise was a fraud--there was nothing in it. Their -courage was up now and well in hand. They were about to go down and -begin work when-- - -"Sh!" said Tom. - -"What is it?" whispered Huck, blanching with fright. - -"Sh!... There!... Hear it?" - -"Yes!... Oh, my! Let's run!" - -"Keep still! Don't you budge! They're coming right toward the door." - -The boys stretched themselves upon the floor with their eyes to -knot-holes in the planking, and lay waiting, in a misery of fear. - -"They've stopped.... No--coming.... Here they are. Don't whisper -another word, Huck. My goodness, I wish I was out of this!" - -Two men entered. Each boy said to himself: "There's the old deaf and -dumb Spaniard that's been about town once or twice lately--never saw -t'other man before." - -"T'other" was a ragged, unkempt creature, with nothing very pleasant -in his face. The Spaniard was wrapped in a serape; he had bushy white -whiskers; long white hair flowed from under his sombrero, and he wore -green goggles. When they came in, "t'other" was talking in a low voice; -they sat down on the ground, facing the door, with their backs to the -wall, and the speaker continued his remarks. His manner became less -guarded and his words more distinct as he proceeded: - -"No," said he, "I've thought it all over, and I don't like it. It's -dangerous." - -"Dangerous!" grunted the "deaf and dumb" Spaniard--to the vast -surprise of the boys. "Milksop!" - -This voice made the boys gasp and quake. It was Injun Joe's! There was -silence for some time. Then Joe said: - -"What's any more dangerous than that job up yonder--but nothing's come -of it." - -"That's different. Away up the river so, and not another house about. -'Twon't ever be known that we tried, anyway, long as we didn't succeed." - -"Well, what's more dangerous than coming here in the daytime!--anybody -would suspicion us that saw us." - -"I know that. But there warn't any other place as handy after that -fool of a job. I want to quit this shanty. I wanted to yesterday, only -it warn't any use trying to stir out of here, with those infernal boys -playing over there on the hill right in full view." - -"Those infernal boys" quaked again under the inspiration of this -remark, and thought how lucky it was that they had remembered it was -Friday and concluded to wait a day. They wished in their hearts they -had waited a year. - -The two men got out some food and made a luncheon. After a long and -thoughtful silence, Injun Joe said: - -"Look here, lad--you go back up the river where you belong. Wait there -till you hear from me. I'll take the chances on dropping into this town -just once more, for a look. We'll do that 'dangerous' job after I've -spied around a little and think things look well for it. Then for -Texas! We'll leg it together!" - -This was satisfactory. Both men presently fell to yawning, and Injun -Joe said: - -"I'm dead for sleep! It's your turn to watch." - -He curled down in the weeds and soon began to snore. His comrade -stirred him once or twice and he became quiet. Presently the watcher -began to nod; his head drooped lower and lower, both men began to snore -now. - -The boys drew a long, grateful breath. Tom whispered: - -"Now's our chance--come!" - -Huck said: - -"I can't--I'd die if they was to wake." - -Tom urged--Huck held back. At last Tom rose slowly and softly, and -started alone. But the first step he made wrung such a hideous creak -from the crazy floor that he sank down almost dead with fright. He -never made a second attempt. The boys lay there counting the dragging -moments till it seemed to them that time must be done and eternity -growing gray; and then they were grateful to note that at last the sun -was setting. - -Now one snore ceased. Injun Joe sat up, stared around--smiled grimly -upon his comrade, whose head was drooping upon his knees--stirred him -up with his foot and said: - -"Here! YOU'RE a watchman, ain't you! All right, though--nothing's -happened." - -"My! have I been asleep?" - -"Oh, partly, partly. Nearly time for us to be moving, pard. What'll we -do with what little swag we've got left?" - -"I don't know--leave it here as we've always done, I reckon. No use to -take it away till we start south. Six hundred and fifty in silver's -something to carry." - -"Well--all right--it won't matter to come here once more." - -"No--but I'd say come in the night as we used to do--it's better." - -"Yes: but look here; it may be a good while before I get the right -chance at that job; accidents might happen; 'tain't in such a very good -place; we'll just regularly bury it--and bury it deep." - -"Good idea," said the comrade, who walked across the room, knelt down, -raised one of the rearward hearth-stones and took out a bag that -jingled pleasantly. He subtracted from it twenty or thirty dollars for -himself and as much for Injun Joe, and passed the bag to the latter, -who was on his knees in the corner, now, digging with his bowie-knife. - -The boys forgot all their fears, all their miseries in an instant. -With gloating eyes they watched every movement. Luck!--the splendor of -it was beyond all imagination! Six hundred dollars was money enough to -make half a dozen boys rich! Here was treasure-hunting under the -happiest auspices--there would not be any bothersome uncertainty as to -where to dig. They nudged each other every moment--eloquent nudges and -easily understood, for they simply meant--"Oh, but ain't you glad NOW -we're here!" - -Joe's knife struck upon something. - -"Hello!" said he. - -"What is it?" said his comrade. - -"Half-rotten plank--no, it's a box, I believe. Here--bear a hand and -we'll see what it's here for. Never mind, I've broke a hole." - -He reached his hand in and drew it out-- - -"Man, it's money!" - -The two men examined the handful of coins. They were gold. The boys -above were as excited as themselves, and as delighted. - -Joe's comrade said: - -"We'll make quick work of this. There's an old rusty pick over amongst -the weeds in the corner the other side of the fireplace--I saw it a -minute ago." - -He ran and brought the boys' pick and shovel. Injun Joe took the pick, -looked it over critically, shook his head, muttered something to -himself, and then began to use it. The box was soon unearthed. It was -not very large; it was iron bound and had been very strong before the -slow years had injured it. The men contemplated the treasure awhile in -blissful silence. - -"Pard, there's thousands of dollars here," said Injun Joe. - -"'Twas always said that Murrel's gang used to be around here one -summer," the stranger observed. - -"I know it," said Injun Joe; "and this looks like it, I should say." - -"Now you won't need to do that job." - -The half-breed frowned. Said he: - -"You don't know me. Least you don't know all about that thing. 'Tain't -robbery altogether--it's REVENGE!" and a wicked light flamed in his -eyes. "I'll need your help in it. When it's finished--then Texas. Go -home to your Nance and your kids, and stand by till you hear from me." - -"Well--if you say so; what'll we do with this--bury it again?" - -"Yes. [Ravishing delight overhead.] NO! by the great Sachem, no! -[Profound distress overhead.] I'd nearly forgot. That pick had fresh -earth on it! [The boys were sick with terror in a moment.] What -business has a pick and a shovel here? What business with fresh earth -on them? Who brought them here--and where are they gone? Have you heard -anybody?--seen anybody? What! bury it again and leave them to come and -see the ground disturbed? Not exactly--not exactly. We'll take it to my -den." - -"Why, of course! Might have thought of that before. You mean Number -One?" - -"No--Number Two--under the cross. The other place is bad--too common." - -"All right. It's nearly dark enough to start." - -Injun Joe got up and went about from window to window cautiously -peeping out. Presently he said: - -"Who could have brought those tools here? Do you reckon they can be -up-stairs?" - -The boys' breath forsook them. Injun Joe put his hand on his knife, -halted a moment, undecided, and then turned toward the stairway. The -boys thought of the closet, but their strength was gone. The steps came -creaking up the stairs--the intolerable distress of the situation woke -the stricken resolution of the lads--they were about to spring for the -closet, when there was a crash of rotten timbers and Injun Joe landed -on the ground amid the debris of the ruined stairway. He gathered -himself up cursing, and his comrade said: - -"Now what's the use of all that? If it's anybody, and they're up -there, let them STAY there--who cares? If they want to jump down, now, -and get into trouble, who objects? It will be dark in fifteen minutes ---and then let them follow us if they want to. I'm willing. In my -opinion, whoever hove those things in here caught a sight of us and -took us for ghosts or devils or something. I'll bet they're running -yet." - -Joe grumbled awhile; then he agreed with his friend that what daylight -was left ought to be economized in getting things ready for leaving. -Shortly afterward they slipped out of the house in the deepening -twilight, and moved toward the river with their precious box. - -Tom and Huck rose up, weak but vastly relieved, and stared after them -through the chinks between the logs of the house. Follow? Not they. -They were content to reach ground again without broken necks, and take -the townward track over the hill. They did not talk much. They were too -much absorbed in hating themselves--hating the ill luck that made them -take the spade and the pick there. But for that, Injun Joe never would -have suspected. He would have hidden the silver with the gold to wait -there till his "revenge" was satisfied, and then he would have had the -misfortune to find that money turn up missing. Bitter, bitter luck that -the tools were ever brought there! - -They resolved to keep a lookout for that Spaniard when he should come -to town spying out for chances to do his revengeful job, and follow him -to "Number Two," wherever that might be. Then a ghastly thought -occurred to Tom. - -"Revenge? What if he means US, Huck!" - -"Oh, don't!" said Huck, nearly fainting. - -They talked it all over, and as they entered town they agreed to -believe that he might possibly mean somebody else--at least that he -might at least mean nobody but Tom, since only Tom had testified. - -Very, very small comfort it was to Tom to be alone in danger! Company -would be a palpable improvement, he thought. - - - -CHAPTER XXVII - -THE adventure of the day mightily tormented Tom's dreams that night. -Four times he had his hands on that rich treasure and four times it -wasted to nothingness in his fingers as sleep forsook him and -wakefulness brought back the hard reality of his misfortune. As he lay -in the early morning recalling the incidents of his great adventure, he -noticed that they seemed curiously subdued and far away--somewhat as if -they had happened in another world, or in a time long gone by. Then it -occurred to him that the great adventure itself must be a dream! There -was one very strong argument in favor of this idea--namely, that the -quantity of coin he had seen was too vast to be real. He had never seen -as much as fifty dollars in one mass before, and he was like all boys -of his age and station in life, in that he imagined that all references -to "hundreds" and "thousands" were mere fanciful forms of speech, and -that no such sums really existed in the world. He never had supposed -for a moment that so large a sum as a hundred dollars was to be found -in actual money in any one's possession. If his notions of hidden -treasure had been analyzed, they would have been found to consist of a -handful of real dimes and a bushel of vague, splendid, ungraspable -dollars. - -But the incidents of his adventure grew sensibly sharper and clearer -under the attrition of thinking them over, and so he presently found -himself leaning to the impression that the thing might not have been a -dream, after all. This uncertainty must be swept away. He would snatch -a hurried breakfast and go and find Huck. Huck was sitting on the -gunwale of a flatboat, listlessly dangling his feet in the water and -looking very melancholy. Tom concluded to let Huck lead up to the -subject. If he did not do it, then the adventure would be proved to -have been only a dream. - -"Hello, Huck!" - -"Hello, yourself." - -Silence, for a minute. - -"Tom, if we'd 'a' left the blame tools at the dead tree, we'd 'a' got -the money. Oh, ain't it awful!" - -"'Tain't a dream, then, 'tain't a dream! Somehow I most wish it was. -Dog'd if I don't, Huck." - -"What ain't a dream?" - -"Oh, that thing yesterday. I been half thinking it was." - -"Dream! If them stairs hadn't broke down you'd 'a' seen how much dream -it was! I've had dreams enough all night--with that patch-eyed Spanish -devil going for me all through 'em--rot him!" - -"No, not rot him. FIND him! Track the money!" - -"Tom, we'll never find him. A feller don't have only one chance for -such a pile--and that one's lost. I'd feel mighty shaky if I was to see -him, anyway." - -"Well, so'd I; but I'd like to see him, anyway--and track him out--to -his Number Two." - -"Number Two--yes, that's it. I been thinking 'bout that. But I can't -make nothing out of it. What do you reckon it is?" - -"I dono. It's too deep. Say, Huck--maybe it's the number of a house!" - -"Goody!... No, Tom, that ain't it. If it is, it ain't in this -one-horse town. They ain't no numbers here." - -"Well, that's so. Lemme think a minute. Here--it's the number of a -room--in a tavern, you know!" - -"Oh, that's the trick! They ain't only two taverns. We can find out -quick." - -"You stay here, Huck, till I come." - -Tom was off at once. He did not care to have Huck's company in public -places. He was gone half an hour. He found that in the best tavern, No. -2 had long been occupied by a young lawyer, and was still so occupied. -In the less ostentatious house, No. 2 was a mystery. The -tavern-keeper's young son said it was kept locked all the time, and he -never saw anybody go into it or come out of it except at night; he did -not know any particular reason for this state of things; had had some -little curiosity, but it was rather feeble; had made the most of the -mystery by entertaining himself with the idea that that room was -"ha'nted"; had noticed that there was a light in there the night before. - -"That's what I've found out, Huck. I reckon that's the very No. 2 -we're after." - -"I reckon it is, Tom. Now what you going to do?" - -"Lemme think." - -Tom thought a long time. Then he said: - -"I'll tell you. The back door of that No. 2 is the door that comes out -into that little close alley between the tavern and the old rattle trap -of a brick store. Now you get hold of all the door-keys you can find, -and I'll nip all of auntie's, and the first dark night we'll go there -and try 'em. And mind you, keep a lookout for Injun Joe, because he -said he was going to drop into town and spy around once more for a -chance to get his revenge. If you see him, you just follow him; and if -he don't go to that No. 2, that ain't the place." - -"Lordy, I don't want to foller him by myself!" - -"Why, it'll be night, sure. He mightn't ever see you--and if he did, -maybe he'd never think anything." - -"Well, if it's pretty dark I reckon I'll track him. I dono--I dono. -I'll try." - -"You bet I'll follow him, if it's dark, Huck. Why, he might 'a' found -out he couldn't get his revenge, and be going right after that money." - -"It's so, Tom, it's so. I'll foller him; I will, by jingoes!" - -"Now you're TALKING! Don't you ever weaken, Huck, and I won't." - - - -CHAPTER XXVIII - -THAT night Tom and Huck were ready for their adventure. They hung -about the neighborhood of the tavern until after nine, one watching the -alley at a distance and the other the tavern door. Nobody entered the -alley or left it; nobody resembling the Spaniard entered or left the -tavern door. The night promised to be a fair one; so Tom went home with -the understanding that if a considerable degree of darkness came on, -Huck was to come and "maow," whereupon he would slip out and try the -keys. But the night remained clear, and Huck closed his watch and -retired to bed in an empty sugar hogshead about twelve. - -Tuesday the boys had the same ill luck. Also Wednesday. But Thursday -night promised better. Tom slipped out in good season with his aunt's -old tin lantern, and a large towel to blindfold it with. He hid the -lantern in Huck's sugar hogshead and the watch began. An hour before -midnight the tavern closed up and its lights (the only ones -thereabouts) were put out. No Spaniard had been seen. Nobody had -entered or left the alley. Everything was auspicious. The blackness of -darkness reigned, the perfect stillness was interrupted only by -occasional mutterings of distant thunder. - -Tom got his lantern, lit it in the hogshead, wrapped it closely in the -towel, and the two adventurers crept in the gloom toward the tavern. -Huck stood sentry and Tom felt his way into the alley. Then there was a -season of waiting anxiety that weighed upon Huck's spirits like a -mountain. He began to wish he could see a flash from the lantern--it -would frighten him, but it would at least tell him that Tom was alive -yet. It seemed hours since Tom had disappeared. Surely he must have -fainted; maybe he was dead; maybe his heart had burst under terror and -excitement. In his uneasiness Huck found himself drawing closer and -closer to the alley; fearing all sorts of dreadful things, and -momentarily expecting some catastrophe to happen that would take away -his breath. There was not much to take away, for he seemed only able to -inhale it by thimblefuls, and his heart would soon wear itself out, the -way it was beating. Suddenly there was a flash of light and Tom came -tearing by him: "Run!" said he; "run, for your life!" - -He needn't have repeated it; once was enough; Huck was making thirty -or forty miles an hour before the repetition was uttered. The boys -never stopped till they reached the shed of a deserted slaughter-house -at the lower end of the village. Just as they got within its shelter -the storm burst and the rain poured down. As soon as Tom got his breath -he said: - -"Huck, it was awful! I tried two of the keys, just as soft as I could; -but they seemed to make such a power of racket that I couldn't hardly -get my breath I was so scared. They wouldn't turn in the lock, either. -Well, without noticing what I was doing, I took hold of the knob, and -open comes the door! It warn't locked! I hopped in, and shook off the -towel, and, GREAT CAESAR'S GHOST!" - -"What!--what'd you see, Tom?" - -"Huck, I most stepped onto Injun Joe's hand!" - -"No!" - -"Yes! He was lying there, sound asleep on the floor, with his old -patch on his eye and his arms spread out." - -"Lordy, what did you do? Did he wake up?" - -"No, never budged. Drunk, I reckon. I just grabbed that towel and -started!" - -"I'd never 'a' thought of the towel, I bet!" - -"Well, I would. My aunt would make me mighty sick if I lost it." - -"Say, Tom, did you see that box?" - -"Huck, I didn't wait to look around. I didn't see the box, I didn't -see the cross. I didn't see anything but a bottle and a tin cup on the -floor by Injun Joe; yes, I saw two barrels and lots more bottles in the -room. Don't you see, now, what's the matter with that ha'nted room?" - -"How?" - -"Why, it's ha'nted with whiskey! Maybe ALL the Temperance Taverns have -got a ha'nted room, hey, Huck?" - -"Well, I reckon maybe that's so. Who'd 'a' thought such a thing? But -say, Tom, now's a mighty good time to get that box, if Injun Joe's -drunk." - -"It is, that! You try it!" - -Huck shuddered. - -"Well, no--I reckon not." - -"And I reckon not, Huck. Only one bottle alongside of Injun Joe ain't -enough. If there'd been three, he'd be drunk enough and I'd do it." - -There was a long pause for reflection, and then Tom said: - -"Lookyhere, Huck, less not try that thing any more till we know Injun -Joe's not in there. It's too scary. Now, if we watch every night, we'll -be dead sure to see him go out, some time or other, and then we'll -snatch that box quicker'n lightning." - -"Well, I'm agreed. I'll watch the whole night long, and I'll do it -every night, too, if you'll do the other part of the job." - -"All right, I will. All you got to do is to trot up Hooper Street a -block and maow--and if I'm asleep, you throw some gravel at the window -and that'll fetch me." - -"Agreed, and good as wheat!" - -"Now, Huck, the storm's over, and I'll go home. It'll begin to be -daylight in a couple of hours. You go back and watch that long, will -you?" - -"I said I would, Tom, and I will. I'll ha'nt that tavern every night -for a year! I'll sleep all day and I'll stand watch all night." - -"That's all right. Now, where you going to sleep?" - -"In Ben Rogers' hayloft. He lets me, and so does his pap's nigger man, -Uncle Jake. I tote water for Uncle Jake whenever he wants me to, and -any time I ask him he gives me a little something to eat if he can -spare it. That's a mighty good nigger, Tom. He likes me, becuz I don't -ever act as if I was above him. Sometime I've set right down and eat -WITH him. But you needn't tell that. A body's got to do things when -he's awful hungry he wouldn't want to do as a steady thing." - -"Well, if I don't want you in the daytime, I'll let you sleep. I won't -come bothering around. Any time you see something's up, in the night, -just skip right around and maow." - - - -CHAPTER XXIX - -THE first thing Tom heard on Friday morning was a glad piece of news ---Judge Thatcher's family had come back to town the night before. Both -Injun Joe and the treasure sunk into secondary importance for a moment, -and Becky took the chief place in the boy's interest. He saw her and -they had an exhausting good time playing "hi-spy" and "gully-keeper" -with a crowd of their school-mates. The day was completed and crowned -in a peculiarly satisfactory way: Becky teased her mother to appoint -the next day for the long-promised and long-delayed picnic, and she -consented. The child's delight was boundless; and Tom's not more -moderate. The invitations were sent out before sunset, and straightway -the young folks of the village were thrown into a fever of preparation -and pleasurable anticipation. Tom's excitement enabled him to keep -awake until a pretty late hour, and he had good hopes of hearing Huck's -"maow," and of having his treasure to astonish Becky and the picnickers -with, next day; but he was disappointed. No signal came that night. - -Morning came, eventually, and by ten or eleven o'clock a giddy and -rollicking company were gathered at Judge Thatcher's, and everything -was ready for a start. It was not the custom for elderly people to mar -the picnics with their presence. The children were considered safe -enough under the wings of a few young ladies of eighteen and a few -young gentlemen of twenty-three or thereabouts. The old steam ferryboat -was chartered for the occasion; presently the gay throng filed up the -main street laden with provision-baskets. Sid was sick and had to miss -the fun; Mary remained at home to entertain him. The last thing Mrs. -Thatcher said to Becky, was: - -"You'll not get back till late. Perhaps you'd better stay all night -with some of the girls that live near the ferry-landing, child." - -"Then I'll stay with Susy Harper, mamma." - -"Very well. And mind and behave yourself and don't be any trouble." - -Presently, as they tripped along, Tom said to Becky: - -"Say--I'll tell you what we'll do. 'Stead of going to Joe Harper's -we'll climb right up the hill and stop at the Widow Douglas'. She'll -have ice-cream! She has it most every day--dead loads of it. And she'll -be awful glad to have us." - -"Oh, that will be fun!" - -Then Becky reflected a moment and said: - -"But what will mamma say?" - -"How'll she ever know?" - -The girl turned the idea over in her mind, and said reluctantly: - -"I reckon it's wrong--but--" - -"But shucks! Your mother won't know, and so what's the harm? All she -wants is that you'll be safe; and I bet you she'd 'a' said go there if -she'd 'a' thought of it. I know she would!" - -The Widow Douglas' splendid hospitality was a tempting bait. It and -Tom's persuasions presently carried the day. So it was decided to say -nothing anybody about the night's programme. Presently it occurred to -Tom that maybe Huck might come this very night and give the signal. The -thought took a deal of the spirit out of his anticipations. Still he -could not bear to give up the fun at Widow Douglas'. And why should he -give it up, he reasoned--the signal did not come the night before, so -why should it be any more likely to come to-night? The sure fun of the -evening outweighed the uncertain treasure; and, boy-like, he determined -to yield to the stronger inclination and not allow himself to think of -the box of money another time that day. - -Three miles below town the ferryboat stopped at the mouth of a woody -hollow and tied up. The crowd swarmed ashore and soon the forest -distances and craggy heights echoed far and near with shoutings and -laughter. All the different ways of getting hot and tired were gone -through with, and by-and-by the rovers straggled back to camp fortified -with responsible appetites, and then the destruction of the good things -began. After the feast there was a refreshing season of rest and chat -in the shade of spreading oaks. By-and-by somebody shouted: - -"Who's ready for the cave?" - -Everybody was. Bundles of candles were procured, and straightway there -was a general scamper up the hill. The mouth of the cave was up the -hillside--an opening shaped like a letter A. Its massive oaken door -stood unbarred. Within was a small chamber, chilly as an ice-house, and -walled by Nature with solid limestone that was dewy with a cold sweat. -It was romantic and mysterious to stand here in the deep gloom and look -out upon the green valley shining in the sun. But the impressiveness of -the situation quickly wore off, and the romping began again. The moment -a candle was lighted there was a general rush upon the owner of it; a -struggle and a gallant defence followed, but the candle was soon -knocked down or blown out, and then there was a glad clamor of laughter -and a new chase. But all things have an end. By-and-by the procession -went filing down the steep descent of the main avenue, the flickering -rank of lights dimly revealing the lofty walls of rock almost to their -point of junction sixty feet overhead. This main avenue was not more -than eight or ten feet wide. Every few steps other lofty and still -narrower crevices branched from it on either hand--for McDougal's cave -was but a vast labyrinth of crooked aisles that ran into each other and -out again and led nowhere. It was said that one might wander days and -nights together through its intricate tangle of rifts and chasms, and -never find the end of the cave; and that he might go down, and down, -and still down, into the earth, and it was just the same--labyrinth -under labyrinth, and no end to any of them. No man "knew" the cave. -That was an impossible thing. Most of the young men knew a portion of -it, and it was not customary to venture much beyond this known portion. -Tom Sawyer knew as much of the cave as any one. - -The procession moved along the main avenue some three-quarters of a -mile, and then groups and couples began to slip aside into branch -avenues, fly along the dismal corridors, and take each other by -surprise at points where the corridors joined again. Parties were able -to elude each other for the space of half an hour without going beyond -the "known" ground. - -By-and-by, one group after another came straggling back to the mouth -of the cave, panting, hilarious, smeared from head to foot with tallow -drippings, daubed with clay, and entirely delighted with the success of -the day. Then they were astonished to find that they had been taking no -note of time and that night was about at hand. The clanging bell had -been calling for half an hour. However, this sort of close to the day's -adventures was romantic and therefore satisfactory. When the ferryboat -with her wild freight pushed into the stream, nobody cared sixpence for -the wasted time but the captain of the craft. - -Huck was already upon his watch when the ferryboat's lights went -glinting past the wharf. He heard no noise on board, for the young -people were as subdued and still as people usually are who are nearly -tired to death. He wondered what boat it was, and why she did not stop -at the wharf--and then he dropped her out of his mind and put his -attention upon his business. The night was growing cloudy and dark. Ten -o'clock came, and the noise of vehicles ceased, scattered lights began -to wink out, all straggling foot-passengers disappeared, the village -betook itself to its slumbers and left the small watcher alone with the -silence and the ghosts. Eleven o'clock came, and the tavern lights were -put out; darkness everywhere, now. Huck waited what seemed a weary long -time, but nothing happened. His faith was weakening. Was there any use? -Was there really any use? Why not give it up and turn in? - -A noise fell upon his ear. He was all attention in an instant. The -alley door closed softly. He sprang to the corner of the brick store. -The next moment two men brushed by him, and one seemed to have -something under his arm. It must be that box! So they were going to -remove the treasure. Why call Tom now? It would be absurd--the men -would get away with the box and never be found again. No, he would -stick to their wake and follow them; he would trust to the darkness for -security from discovery. So communing with himself, Huck stepped out -and glided along behind the men, cat-like, with bare feet, allowing -them to keep just far enough ahead not to be invisible. - -They moved up the river street three blocks, then turned to the left -up a cross-street. They went straight ahead, then, until they came to -the path that led up Cardiff Hill; this they took. They passed by the -old Welshman's house, half-way up the hill, without hesitating, and -still climbed upward. Good, thought Huck, they will bury it in the old -quarry. But they never stopped at the quarry. They passed on, up the -summit. They plunged into the narrow path between the tall sumach -bushes, and were at once hidden in the gloom. Huck closed up and -shortened his distance, now, for they would never be able to see him. -He trotted along awhile; then slackened his pace, fearing he was -gaining too fast; moved on a piece, then stopped altogether; listened; -no sound; none, save that he seemed to hear the beating of his own -heart. The hooting of an owl came over the hill--ominous sound! But no -footsteps. Heavens, was everything lost! He was about to spring with -winged feet, when a man cleared his throat not four feet from him! -Huck's heart shot into his throat, but he swallowed it again; and then -he stood there shaking as if a dozen agues had taken charge of him at -once, and so weak that he thought he must surely fall to the ground. He -knew where he was. He knew he was within five steps of the stile -leading into Widow Douglas' grounds. Very well, he thought, let them -bury it there; it won't be hard to find. - -Now there was a voice--a very low voice--Injun Joe's: - -"Damn her, maybe she's got company--there's lights, late as it is." - -"I can't see any." - -This was that stranger's voice--the stranger of the haunted house. A -deadly chill went to Huck's heart--this, then, was the "revenge" job! -His thought was, to fly. Then he remembered that the Widow Douglas had -been kind to him more than once, and maybe these men were going to -murder her. He wished he dared venture to warn her; but he knew he -didn't dare--they might come and catch him. He thought all this and -more in the moment that elapsed between the stranger's remark and Injun -Joe's next--which was-- - -"Because the bush is in your way. Now--this way--now you see, don't -you?" - -"Yes. Well, there IS company there, I reckon. Better give it up." - -"Give it up, and I just leaving this country forever! Give it up and -maybe never have another chance. I tell you again, as I've told you -before, I don't care for her swag--you may have it. But her husband was -rough on me--many times he was rough on me--and mainly he was the -justice of the peace that jugged me for a vagrant. And that ain't all. -It ain't a millionth part of it! He had me HORSEWHIPPED!--horsewhipped -in front of the jail, like a nigger!--with all the town looking on! -HORSEWHIPPED!--do you understand? He took advantage of me and died. But -I'll take it out of HER." - -"Oh, don't kill her! Don't do that!" - -"Kill? Who said anything about killing? I would kill HIM if he was -here; but not her. When you want to get revenge on a woman you don't -kill her--bosh! you go for her looks. You slit her nostrils--you notch -her ears like a sow!" - -"By God, that's--" - -"Keep your opinion to yourself! It will be safest for you. I'll tie -her to the bed. If she bleeds to death, is that my fault? I'll not cry, -if she does. My friend, you'll help me in this thing--for MY sake ---that's why you're here--I mightn't be able alone. If you flinch, I'll -kill you. Do you understand that? And if I have to kill you, I'll kill -her--and then I reckon nobody'll ever know much about who done this -business." - -"Well, if it's got to be done, let's get at it. The quicker the -better--I'm all in a shiver." - -"Do it NOW? And company there? Look here--I'll get suspicious of you, -first thing you know. No--we'll wait till the lights are out--there's -no hurry." - -Huck felt that a silence was going to ensue--a thing still more awful -than any amount of murderous talk; so he held his breath and stepped -gingerly back; planted his foot carefully and firmly, after balancing, -one-legged, in a precarious way and almost toppling over, first on one -side and then on the other. He took another step back, with the same -elaboration and the same risks; then another and another, and--a twig -snapped under his foot! His breath stopped and he listened. There was -no sound--the stillness was perfect. His gratitude was measureless. Now -he turned in his tracks, between the walls of sumach bushes--turned -himself as carefully as if he were a ship--and then stepped quickly but -cautiously along. When he emerged at the quarry he felt secure, and so -he picked up his nimble heels and flew. Down, down he sped, till he -reached the Welshman's. He banged at the door, and presently the heads -of the old man and his two stalwart sons were thrust from windows. - -"What's the row there? Who's banging? What do you want?" - -"Let me in--quick! I'll tell everything." - -"Why, who are you?" - -"Huckleberry Finn--quick, let me in!" - -"Huckleberry Finn, indeed! It ain't a name to open many doors, I -judge! But let him in, lads, and let's see what's the trouble." - -"Please don't ever tell I told you," were Huck's first words when he -got in. "Please don't--I'd be killed, sure--but the widow's been good -friends to me sometimes, and I want to tell--I WILL tell if you'll -promise you won't ever say it was me." - -"By George, he HAS got something to tell, or he wouldn't act so!" -exclaimed the old man; "out with it and nobody here'll ever tell, lad." - -Three minutes later the old man and his sons, well armed, were up the -hill, and just entering the sumach path on tiptoe, their weapons in -their hands. Huck accompanied them no further. He hid behind a great -bowlder and fell to listening. There was a lagging, anxious silence, -and then all of a sudden there was an explosion of firearms and a cry. - -Huck waited for no particulars. He sprang away and sped down the hill -as fast as his legs could carry him. - - - -CHAPTER XXX - -AS the earliest suspicion of dawn appeared on Sunday morning, Huck -came groping up the hill and rapped gently at the old Welshman's door. -The inmates were asleep, but it was a sleep that was set on a -hair-trigger, on account of the exciting episode of the night. A call -came from a window: - -"Who's there!" - -Huck's scared voice answered in a low tone: - -"Please let me in! It's only Huck Finn!" - -"It's a name that can open this door night or day, lad!--and welcome!" - -These were strange words to the vagabond boy's ears, and the -pleasantest he had ever heard. He could not recollect that the closing -word had ever been applied in his case before. The door was quickly -unlocked, and he entered. Huck was given a seat and the old man and his -brace of tall sons speedily dressed themselves. - -"Now, my boy, I hope you're good and hungry, because breakfast will be -ready as soon as the sun's up, and we'll have a piping hot one, too ---make yourself easy about that! I and the boys hoped you'd turn up and -stop here last night." - -"I was awful scared," said Huck, "and I run. I took out when the -pistols went off, and I didn't stop for three mile. I've come now becuz -I wanted to know about it, you know; and I come before daylight becuz I -didn't want to run across them devils, even if they was dead." - -"Well, poor chap, you do look as if you'd had a hard night of it--but -there's a bed here for you when you've had your breakfast. No, they -ain't dead, lad--we are sorry enough for that. You see we knew right -where to put our hands on them, by your description; so we crept along -on tiptoe till we got within fifteen feet of them--dark as a cellar -that sumach path was--and just then I found I was going to sneeze. It -was the meanest kind of luck! I tried to keep it back, but no use ---'twas bound to come, and it did come! I was in the lead with my pistol -raised, and when the sneeze started those scoundrels a-rustling to get -out of the path, I sung out, 'Fire boys!' and blazed away at the place -where the rustling was. So did the boys. But they were off in a jiffy, -those villains, and we after them, down through the woods. I judge we -never touched them. They fired a shot apiece as they started, but their -bullets whizzed by and didn't do us any harm. As soon as we lost the -sound of their feet we quit chasing, and went down and stirred up the -constables. They got a posse together, and went off to guard the river -bank, and as soon as it is light the sheriff and a gang are going to -beat up the woods. My boys will be with them presently. I wish we had -some sort of description of those rascals--'twould help a good deal. -But you couldn't see what they were like, in the dark, lad, I suppose?" - -"Oh yes; I saw them down-town and follered them." - -"Splendid! Describe them--describe them, my boy!" - -"One's the old deaf and dumb Spaniard that's ben around here once or -twice, and t'other's a mean-looking, ragged--" - -"That's enough, lad, we know the men! Happened on them in the woods -back of the widow's one day, and they slunk away. Off with you, boys, -and tell the sheriff--get your breakfast to-morrow morning!" - -The Welshman's sons departed at once. As they were leaving the room -Huck sprang up and exclaimed: - -"Oh, please don't tell ANYbody it was me that blowed on them! Oh, -please!" - -"All right if you say it, Huck, but you ought to have the credit of -what you did." - -"Oh no, no! Please don't tell!" - -When the young men were gone, the old Welshman said: - -"They won't tell--and I won't. But why don't you want it known?" - -Huck would not explain, further than to say that he already knew too -much about one of those men and would not have the man know that he -knew anything against him for the whole world--he would be killed for -knowing it, sure. - -The old man promised secrecy once more, and said: - -"How did you come to follow these fellows, lad? Were they looking -suspicious?" - -Huck was silent while he framed a duly cautious reply. Then he said: - -"Well, you see, I'm a kind of a hard lot,--least everybody says so, -and I don't see nothing agin it--and sometimes I can't sleep much, on -account of thinking about it and sort of trying to strike out a new way -of doing. That was the way of it last night. I couldn't sleep, and so I -come along up-street 'bout midnight, a-turning it all over, and when I -got to that old shackly brick store by the Temperance Tavern, I backed -up agin the wall to have another think. Well, just then along comes -these two chaps slipping along close by me, with something under their -arm, and I reckoned they'd stole it. One was a-smoking, and t'other one -wanted a light; so they stopped right before me and the cigars lit up -their faces and I see that the big one was the deaf and dumb Spaniard, -by his white whiskers and the patch on his eye, and t'other one was a -rusty, ragged-looking devil." - -"Could you see the rags by the light of the cigars?" - -This staggered Huck for a moment. Then he said: - -"Well, I don't know--but somehow it seems as if I did." - -"Then they went on, and you--" - -"Follered 'em--yes. That was it. I wanted to see what was up--they -sneaked along so. I dogged 'em to the widder's stile, and stood in the -dark and heard the ragged one beg for the widder, and the Spaniard -swear he'd spile her looks just as I told you and your two--" - -"What! The DEAF AND DUMB man said all that!" - -Huck had made another terrible mistake! He was trying his best to keep -the old man from getting the faintest hint of who the Spaniard might -be, and yet his tongue seemed determined to get him into trouble in -spite of all he could do. He made several efforts to creep out of his -scrape, but the old man's eye was upon him and he made blunder after -blunder. Presently the Welshman said: - -"My boy, don't be afraid of me. I wouldn't hurt a hair of your head -for all the world. No--I'd protect you--I'd protect you. This Spaniard -is not deaf and dumb; you've let that slip without intending it; you -can't cover that up now. You know something about that Spaniard that -you want to keep dark. Now trust me--tell me what it is, and trust me ---I won't betray you." - -Huck looked into the old man's honest eyes a moment, then bent over -and whispered in his ear: - -"'Tain't a Spaniard--it's Injun Joe!" - -The Welshman almost jumped out of his chair. In a moment he said: - -"It's all plain enough, now. When you talked about notching ears and -slitting noses I judged that that was your own embellishment, because -white men don't take that sort of revenge. But an Injun! That's a -different matter altogether." - -During breakfast the talk went on, and in the course of it the old man -said that the last thing which he and his sons had done, before going -to bed, was to get a lantern and examine the stile and its vicinity for -marks of blood. They found none, but captured a bulky bundle of-- - -"Of WHAT?" - -If the words had been lightning they could not have leaped with a more -stunning suddenness from Huck's blanched lips. His eyes were staring -wide, now, and his breath suspended--waiting for the answer. The -Welshman started--stared in return--three seconds--five seconds--ten ---then replied: - -"Of burglar's tools. Why, what's the MATTER with you?" - -Huck sank back, panting gently, but deeply, unutterably grateful. The -Welshman eyed him gravely, curiously--and presently said: - -"Yes, burglar's tools. That appears to relieve you a good deal. But -what did give you that turn? What were YOU expecting we'd found?" - -Huck was in a close place--the inquiring eye was upon him--he would -have given anything for material for a plausible answer--nothing -suggested itself--the inquiring eye was boring deeper and deeper--a -senseless reply offered--there was no time to weigh it, so at a venture -he uttered it--feebly: - -"Sunday-school books, maybe." - -Poor Huck was too distressed to smile, but the old man laughed loud -and joyously, shook up the details of his anatomy from head to foot, -and ended by saying that such a laugh was money in a-man's pocket, -because it cut down the doctor's bill like everything. Then he added: - -"Poor old chap, you're white and jaded--you ain't well a bit--no -wonder you're a little flighty and off your balance. But you'll come -out of it. Rest and sleep will fetch you out all right, I hope." - -Huck was irritated to think he had been such a goose and betrayed such -a suspicious excitement, for he had dropped the idea that the parcel -brought from the tavern was the treasure, as soon as he had heard the -talk at the widow's stile. He had only thought it was not the treasure, -however--he had not known that it wasn't--and so the suggestion of a -captured bundle was too much for his self-possession. But on the whole -he felt glad the little episode had happened, for now he knew beyond -all question that that bundle was not THE bundle, and so his mind was -at rest and exceedingly comfortable. In fact, everything seemed to be -drifting just in the right direction, now; the treasure must be still -in No. 2, the men would be captured and jailed that day, and he and Tom -could seize the gold that night without any trouble or any fear of -interruption. - -Just as breakfast was completed there was a knock at the door. Huck -jumped for a hiding-place, for he had no mind to be connected even -remotely with the late event. The Welshman admitted several ladies and -gentlemen, among them the Widow Douglas, and noticed that groups of -citizens were climbing up the hill--to stare at the stile. So the news -had spread. The Welshman had to tell the story of the night to the -visitors. The widow's gratitude for her preservation was outspoken. - -"Don't say a word about it, madam. There's another that you're more -beholden to than you are to me and my boys, maybe, but he don't allow -me to tell his name. We wouldn't have been there but for him." - -Of course this excited a curiosity so vast that it almost belittled -the main matter--but the Welshman allowed it to eat into the vitals of -his visitors, and through them be transmitted to the whole town, for he -refused to part with his secret. When all else had been learned, the -widow said: - -"I went to sleep reading in bed and slept straight through all that -noise. Why didn't you come and wake me?" - -"We judged it warn't worth while. Those fellows warn't likely to come -again--they hadn't any tools left to work with, and what was the use of -waking you up and scaring you to death? My three negro men stood guard -at your house all the rest of the night. They've just come back." - -More visitors came, and the story had to be told and retold for a -couple of hours more. - -There was no Sabbath-school during day-school vacation, but everybody -was early at church. The stirring event was well canvassed. News came -that not a sign of the two villains had been yet discovered. When the -sermon was finished, Judge Thatcher's wife dropped alongside of Mrs. -Harper as she moved down the aisle with the crowd and said: - -"Is my Becky going to sleep all day? I just expected she would be -tired to death." - -"Your Becky?" - -"Yes," with a startled look--"didn't she stay with you last night?" - -"Why, no." - -Mrs. Thatcher turned pale, and sank into a pew, just as Aunt Polly, -talking briskly with a friend, passed by. Aunt Polly said: - -"Good-morning, Mrs. Thatcher. Good-morning, Mrs. Harper. I've got a -boy that's turned up missing. I reckon my Tom stayed at your house last -night--one of you. And now he's afraid to come to church. I've got to -settle with him." - -Mrs. Thatcher shook her head feebly and turned paler than ever. - -"He didn't stay with us," said Mrs. Harper, beginning to look uneasy. -A marked anxiety came into Aunt Polly's face. - -"Joe Harper, have you seen my Tom this morning?" - -"No'm." - -"When did you see him last?" - -Joe tried to remember, but was not sure he could say. The people had -stopped moving out of church. Whispers passed along, and a boding -uneasiness took possession of every countenance. Children were -anxiously questioned, and young teachers. They all said they had not -noticed whether Tom and Becky were on board the ferryboat on the -homeward trip; it was dark; no one thought of inquiring if any one was -missing. One young man finally blurted out his fear that they were -still in the cave! Mrs. Thatcher swooned away. Aunt Polly fell to -crying and wringing her hands. - -The alarm swept from lip to lip, from group to group, from street to -street, and within five minutes the bells were wildly clanging and the -whole town was up! The Cardiff Hill episode sank into instant -insignificance, the burglars were forgotten, horses were saddled, -skiffs were manned, the ferryboat ordered out, and before the horror -was half an hour old, two hundred men were pouring down highroad and -river toward the cave. - -All the long afternoon the village seemed empty and dead. Many women -visited Aunt Polly and Mrs. Thatcher and tried to comfort them. They -cried with them, too, and that was still better than words. All the -tedious night the town waited for news; but when the morning dawned at -last, all the word that came was, "Send more candles--and send food." -Mrs. Thatcher was almost crazed; and Aunt Polly, also. Judge Thatcher -sent messages of hope and encouragement from the cave, but they -conveyed no real cheer. - -The old Welshman came home toward daylight, spattered with -candle-grease, smeared with clay, and almost worn out. He found Huck -still in the bed that had been provided for him, and delirious with -fever. The physicians were all at the cave, so the Widow Douglas came -and took charge of the patient. She said she would do her best by him, -because, whether he was good, bad, or indifferent, he was the Lord's, -and nothing that was the Lord's was a thing to be neglected. The -Welshman said Huck had good spots in him, and the widow said: - -"You can depend on it. That's the Lord's mark. He don't leave it off. -He never does. Puts it somewhere on every creature that comes from his -hands." - -Early in the forenoon parties of jaded men began to straggle into the -village, but the strongest of the citizens continued searching. All the -news that could be gained was that remotenesses of the cavern were -being ransacked that had never been visited before; that every corner -and crevice was going to be thoroughly searched; that wherever one -wandered through the maze of passages, lights were to be seen flitting -hither and thither in the distance, and shoutings and pistol-shots sent -their hollow reverberations to the ear down the sombre aisles. In one -place, far from the section usually traversed by tourists, the names -"BECKY & TOM" had been found traced upon the rocky wall with -candle-smoke, and near at hand a grease-soiled bit of ribbon. Mrs. -Thatcher recognized the ribbon and cried over it. She said it was the -last relic she should ever have of her child; and that no other memorial -of her could ever be so precious, because this one parted latest from -the living body before the awful death came. Some said that now and -then, in the cave, a far-away speck of light would glimmer, and then a -glorious shout would burst forth and a score of men go trooping down the -echoing aisle--and then a sickening disappointment always followed; the -children were not there; it was only a searcher's light. - -Three dreadful days and nights dragged their tedious hours along, and -the village sank into a hopeless stupor. No one had heart for anything. -The accidental discovery, just made, that the proprietor of the -Temperance Tavern kept liquor on his premises, scarcely fluttered the -public pulse, tremendous as the fact was. In a lucid interval, Huck -feebly led up to the subject of taverns, and finally asked--dimly -dreading the worst--if anything had been discovered at the Temperance -Tavern since he had been ill. - -"Yes," said the widow. - -Huck started up in bed, wild-eyed: - -"What? What was it?" - -"Liquor!--and the place has been shut up. Lie down, child--what a turn -you did give me!" - -"Only tell me just one thing--only just one--please! Was it Tom Sawyer -that found it?" - -The widow burst into tears. "Hush, hush, child, hush! I've told you -before, you must NOT talk. You are very, very sick!" - -Then nothing but liquor had been found; there would have been a great -powwow if it had been the gold. So the treasure was gone forever--gone -forever! But what could she be crying about? Curious that she should -cry. - -These thoughts worked their dim way through Huck's mind, and under the -weariness they gave him he fell asleep. The widow said to herself: - -"There--he's asleep, poor wreck. Tom Sawyer find it! Pity but somebody -could find Tom Sawyer! Ah, there ain't many left, now, that's got hope -enough, or strength enough, either, to go on searching." - - - -CHAPTER XXXI - -NOW to return to Tom and Becky's share in the picnic. They tripped -along the murky aisles with the rest of the company, visiting the -familiar wonders of the cave--wonders dubbed with rather -over-descriptive names, such as "The Drawing-Room," "The Cathedral," -"Aladdin's Palace," and so on. Presently the hide-and-seek frolicking -began, and Tom and Becky engaged in it with zeal until the exertion -began to grow a trifle wearisome; then they wandered down a sinuous -avenue holding their candles aloft and reading the tangled web-work of -names, dates, post-office addresses, and mottoes with which the rocky -walls had been frescoed (in candle-smoke). Still drifting along and -talking, they scarcely noticed that they were now in a part of the cave -whose walls were not frescoed. They smoked their own names under an -overhanging shelf and moved on. Presently they came to a place where a -little stream of water, trickling over a ledge and carrying a limestone -sediment with it, had, in the slow-dragging ages, formed a laced and -ruffled Niagara in gleaming and imperishable stone. Tom squeezed his -small body behind it in order to illuminate it for Becky's -gratification. He found that it curtained a sort of steep natural -stairway which was enclosed between narrow walls, and at once the -ambition to be a discoverer seized him. Becky responded to his call, -and they made a smoke-mark for future guidance, and started upon their -quest. They wound this way and that, far down into the secret depths of -the cave, made another mark, and branched off in search of novelties to -tell the upper world about. In one place they found a spacious cavern, -from whose ceiling depended a multitude of shining stalactites of the -length and circumference of a man's leg; they walked all about it, -wondering and admiring, and presently left it by one of the numerous -passages that opened into it. This shortly brought them to a bewitching -spring, whose basin was incrusted with a frostwork of glittering -crystals; it was in the midst of a cavern whose walls were supported by -many fantastic pillars which had been formed by the joining of great -stalactites and stalagmites together, the result of the ceaseless -water-drip of centuries. Under the roof vast knots of bats had packed -themselves together, thousands in a bunch; the lights disturbed the -creatures and they came flocking down by hundreds, squeaking and -darting furiously at the candles. Tom knew their ways and the danger of -this sort of conduct. He seized Becky's hand and hurried her into the -first corridor that offered; and none too soon, for a bat struck -Becky's light out with its wing while she was passing out of the -cavern. The bats chased the children a good distance; but the fugitives -plunged into every new passage that offered, and at last got rid of the -perilous things. Tom found a subterranean lake, shortly, which -stretched its dim length away until its shape was lost in the shadows. -He wanted to explore its borders, but concluded that it would be best -to sit down and rest awhile, first. Now, for the first time, the deep -stillness of the place laid a clammy hand upon the spirits of the -children. Becky said: - -"Why, I didn't notice, but it seems ever so long since I heard any of -the others." - -"Come to think, Becky, we are away down below them--and I don't know -how far away north, or south, or east, or whichever it is. We couldn't -hear them here." - -Becky grew apprehensive. - -"I wonder how long we've been down here, Tom? We better start back." - -"Yes, I reckon we better. P'raps we better." - -"Can you find the way, Tom? It's all a mixed-up crookedness to me." - -"I reckon I could find it--but then the bats. If they put our candles -out it will be an awful fix. Let's try some other way, so as not to go -through there." - -"Well. But I hope we won't get lost. It would be so awful!" and the -girl shuddered at the thought of the dreadful possibilities. - -They started through a corridor, and traversed it in silence a long -way, glancing at each new opening, to see if there was anything -familiar about the look of it; but they were all strange. Every time -Tom made an examination, Becky would watch his face for an encouraging -sign, and he would say cheerily: - -"Oh, it's all right. This ain't the one, but we'll come to it right -away!" - -But he felt less and less hopeful with each failure, and presently -began to turn off into diverging avenues at sheer random, in desperate -hope of finding the one that was wanted. He still said it was "all -right," but there was such a leaden dread at his heart that the words -had lost their ring and sounded just as if he had said, "All is lost!" -Becky clung to his side in an anguish of fear, and tried hard to keep -back the tears, but they would come. At last she said: - -"Oh, Tom, never mind the bats, let's go back that way! We seem to get -worse and worse off all the time." - -"Listen!" said he. - -Profound silence; silence so deep that even their breathings were -conspicuous in the hush. Tom shouted. The call went echoing down the -empty aisles and died out in the distance in a faint sound that -resembled a ripple of mocking laughter. - -"Oh, don't do it again, Tom, it is too horrid," said Becky. - -"It is horrid, but I better, Becky; they might hear us, you know," and -he shouted again. - -The "might" was even a chillier horror than the ghostly laughter, it -so confessed a perishing hope. The children stood still and listened; -but there was no result. Tom turned upon the back track at once, and -hurried his steps. It was but a little while before a certain -indecision in his manner revealed another fearful fact to Becky--he -could not find his way back! - -"Oh, Tom, you didn't make any marks!" - -"Becky, I was such a fool! Such a fool! I never thought we might want -to come back! No--I can't find the way. It's all mixed up." - -"Tom, Tom, we're lost! we're lost! We never can get out of this awful -place! Oh, why DID we ever leave the others!" - -She sank to the ground and burst into such a frenzy of crying that Tom -was appalled with the idea that she might die, or lose her reason. He -sat down by her and put his arms around her; she buried her face in his -bosom, she clung to him, she poured out her terrors, her unavailing -regrets, and the far echoes turned them all to jeering laughter. Tom -begged her to pluck up hope again, and she said she could not. He fell -to blaming and abusing himself for getting her into this miserable -situation; this had a better effect. She said she would try to hope -again, she would get up and follow wherever he might lead if only he -would not talk like that any more. For he was no more to blame than -she, she said. - -So they moved on again--aimlessly--simply at random--all they could do -was to move, keep moving. For a little while, hope made a show of -reviving--not with any reason to back it, but only because it is its -nature to revive when the spring has not been taken out of it by age -and familiarity with failure. - -By-and-by Tom took Becky's candle and blew it out. This economy meant -so much! Words were not needed. Becky understood, and her hope died -again. She knew that Tom had a whole candle and three or four pieces in -his pockets--yet he must economize. - -By-and-by, fatigue began to assert its claims; the children tried to -pay attention, for it was dreadful to think of sitting down when time -was grown to be so precious, moving, in some direction, in any -direction, was at least progress and might bear fruit; but to sit down -was to invite death and shorten its pursuit. - -At last Becky's frail limbs refused to carry her farther. She sat -down. Tom rested with her, and they talked of home, and the friends -there, and the comfortable beds and, above all, the light! Becky cried, -and Tom tried to think of some way of comforting her, but all his -encouragements were grown threadbare with use, and sounded like -sarcasms. Fatigue bore so heavily upon Becky that she drowsed off to -sleep. Tom was grateful. He sat looking into her drawn face and saw it -grow smooth and natural under the influence of pleasant dreams; and -by-and-by a smile dawned and rested there. The peaceful face reflected -somewhat of peace and healing into his own spirit, and his thoughts -wandered away to bygone times and dreamy memories. While he was deep in -his musings, Becky woke up with a breezy little laugh--but it was -stricken dead upon her lips, and a groan followed it. - -"Oh, how COULD I sleep! I wish I never, never had waked! No! No, I -don't, Tom! Don't look so! I won't say it again." - -"I'm glad you've slept, Becky; you'll feel rested, now, and we'll find -the way out." - -"We can try, Tom; but I've seen such a beautiful country in my dream. -I reckon we are going there." - -"Maybe not, maybe not. Cheer up, Becky, and let's go on trying." - -They rose up and wandered along, hand in hand and hopeless. They tried -to estimate how long they had been in the cave, but all they knew was -that it seemed days and weeks, and yet it was plain that this could not -be, for their candles were not gone yet. A long time after this--they -could not tell how long--Tom said they must go softly and listen for -dripping water--they must find a spring. They found one presently, and -Tom said it was time to rest again. Both were cruelly tired, yet Becky -said she thought she could go a little farther. She was surprised to -hear Tom dissent. She could not understand it. They sat down, and Tom -fastened his candle to the wall in front of them with some clay. -Thought was soon busy; nothing was said for some time. Then Becky broke -the silence: - -"Tom, I am so hungry!" - -Tom took something out of his pocket. - -"Do you remember this?" said he. - -Becky almost smiled. - -"It's our wedding-cake, Tom." - -"Yes--I wish it was as big as a barrel, for it's all we've got." - -"I saved it from the picnic for us to dream on, Tom, the way grown-up -people do with wedding-cake--but it'll be our--" - -She dropped the sentence where it was. Tom divided the cake and Becky -ate with good appetite, while Tom nibbled at his moiety. There was -abundance of cold water to finish the feast with. By-and-by Becky -suggested that they move on again. Tom was silent a moment. Then he -said: - -"Becky, can you bear it if I tell you something?" - -Becky's face paled, but she thought she could. - -"Well, then, Becky, we must stay here, where there's water to drink. -That little piece is our last candle!" - -Becky gave loose to tears and wailings. Tom did what he could to -comfort her, but with little effect. At length Becky said: - -"Tom!" - -"Well, Becky?" - -"They'll miss us and hunt for us!" - -"Yes, they will! Certainly they will!" - -"Maybe they're hunting for us now, Tom." - -"Why, I reckon maybe they are. I hope they are." - -"When would they miss us, Tom?" - -"When they get back to the boat, I reckon." - -"Tom, it might be dark then--would they notice we hadn't come?" - -"I don't know. But anyway, your mother would miss you as soon as they -got home." - -A frightened look in Becky's face brought Tom to his senses and he saw -that he had made a blunder. Becky was not to have gone home that night! -The children became silent and thoughtful. In a moment a new burst of -grief from Becky showed Tom that the thing in his mind had struck hers -also--that the Sabbath morning might be half spent before Mrs. Thatcher -discovered that Becky was not at Mrs. Harper's. - -The children fastened their eyes upon their bit of candle and watched -it melt slowly and pitilessly away; saw the half inch of wick stand -alone at last; saw the feeble flame rise and fall, climb the thin -column of smoke, linger at its top a moment, and then--the horror of -utter darkness reigned! - -How long afterward it was that Becky came to a slow consciousness that -she was crying in Tom's arms, neither could tell. All that they knew -was, that after what seemed a mighty stretch of time, both awoke out of -a dead stupor of sleep and resumed their miseries once more. Tom said -it might be Sunday, now--maybe Monday. He tried to get Becky to talk, -but her sorrows were too oppressive, all her hopes were gone. Tom said -that they must have been missed long ago, and no doubt the search was -going on. He would shout and maybe some one would come. He tried it; -but in the darkness the distant echoes sounded so hideously that he -tried it no more. - -The hours wasted away, and hunger came to torment the captives again. -A portion of Tom's half of the cake was left; they divided and ate it. -But they seemed hungrier than before. The poor morsel of food only -whetted desire. - -By-and-by Tom said: - -"SH! Did you hear that?" - -Both held their breath and listened. There was a sound like the -faintest, far-off shout. Instantly Tom answered it, and leading Becky -by the hand, started groping down the corridor in its direction. -Presently he listened again; again the sound was heard, and apparently -a little nearer. - -"It's them!" said Tom; "they're coming! Come along, Becky--we're all -right now!" - -The joy of the prisoners was almost overwhelming. Their speed was -slow, however, because pitfalls were somewhat common, and had to be -guarded against. They shortly came to one and had to stop. It might be -three feet deep, it might be a hundred--there was no passing it at any -rate. Tom got down on his breast and reached as far down as he could. -No bottom. They must stay there and wait until the searchers came. They -listened; evidently the distant shoutings were growing more distant! a -moment or two more and they had gone altogether. The heart-sinking -misery of it! Tom whooped until he was hoarse, but it was of no use. He -talked hopefully to Becky; but an age of anxious waiting passed and no -sounds came again. - -The children groped their way back to the spring. The weary time -dragged on; they slept again, and awoke famished and woe-stricken. Tom -believed it must be Tuesday by this time. - -Now an idea struck him. There were some side passages near at hand. It -would be better to explore some of these than bear the weight of the -heavy time in idleness. He took a kite-line from his pocket, tied it to -a projection, and he and Becky started, Tom in the lead, unwinding the -line as he groped along. At the end of twenty steps the corridor ended -in a "jumping-off place." Tom got down on his knees and felt below, and -then as far around the corner as he could reach with his hands -conveniently; he made an effort to stretch yet a little farther to the -right, and at that moment, not twenty yards away, a human hand, holding -a candle, appeared from behind a rock! Tom lifted up a glorious shout, -and instantly that hand was followed by the body it belonged to--Injun -Joe's! Tom was paralyzed; he could not move. He was vastly gratified -the next moment, to see the "Spaniard" take to his heels and get -himself out of sight. Tom wondered that Joe had not recognized his -voice and come over and killed him for testifying in court. But the -echoes must have disguised the voice. Without doubt, that was it, he -reasoned. Tom's fright weakened every muscle in his body. He said to -himself that if he had strength enough to get back to the spring he -would stay there, and nothing should tempt him to run the risk of -meeting Injun Joe again. He was careful to keep from Becky what it was -he had seen. He told her he had only shouted "for luck." - -But hunger and wretchedness rise superior to fears in the long run. -Another tedious wait at the spring and another long sleep brought -changes. The children awoke tortured with a raging hunger. Tom believed -that it must be Wednesday or Thursday or even Friday or Saturday, now, -and that the search had been given over. He proposed to explore another -passage. He felt willing to risk Injun Joe and all other terrors. But -Becky was very weak. She had sunk into a dreary apathy and would not be -roused. She said she would wait, now, where she was, and die--it would -not be long. She told Tom to go with the kite-line and explore if he -chose; but she implored him to come back every little while and speak -to her; and she made him promise that when the awful time came, he -would stay by her and hold her hand until all was over. - -Tom kissed her, with a choking sensation in his throat, and made a -show of being confident of finding the searchers or an escape from the -cave; then he took the kite-line in his hand and went groping down one -of the passages on his hands and knees, distressed with hunger and sick -with bodings of coming doom. - - - -CHAPTER XXXII - -TUESDAY afternoon came, and waned to the twilight. The village of St. -Petersburg still mourned. The lost children had not been found. Public -prayers had been offered up for them, and many and many a private -prayer that had the petitioner's whole heart in it; but still no good -news came from the cave. The majority of the searchers had given up the -quest and gone back to their daily avocations, saying that it was plain -the children could never be found. Mrs. Thatcher was very ill, and a -great part of the time delirious. People said it was heartbreaking to -hear her call her child, and raise her head and listen a whole minute -at a time, then lay it wearily down again with a moan. Aunt Polly had -drooped into a settled melancholy, and her gray hair had grown almost -white. The village went to its rest on Tuesday night, sad and forlorn. - -Away in the middle of the night a wild peal burst from the village -bells, and in a moment the streets were swarming with frantic half-clad -people, who shouted, "Turn out! turn out! they're found! they're -found!" Tin pans and horns were added to the din, the population massed -itself and moved toward the river, met the children coming in an open -carriage drawn by shouting citizens, thronged around it, joined its -homeward march, and swept magnificently up the main street roaring -huzzah after huzzah! - -The village was illuminated; nobody went to bed again; it was the -greatest night the little town had ever seen. During the first half-hour -a procession of villagers filed through Judge Thatcher's house, seized -the saved ones and kissed them, squeezed Mrs. Thatcher's hand, tried to -speak but couldn't--and drifted out raining tears all over the place. - -Aunt Polly's happiness was complete, and Mrs. Thatcher's nearly so. It -would be complete, however, as soon as the messenger dispatched with -the great news to the cave should get the word to her husband. Tom lay -upon a sofa with an eager auditory about him and told the history of -the wonderful adventure, putting in many striking additions to adorn it -withal; and closed with a description of how he left Becky and went on -an exploring expedition; how he followed two avenues as far as his -kite-line would reach; how he followed a third to the fullest stretch of -the kite-line, and was about to turn back when he glimpsed a far-off -speck that looked like daylight; dropped the line and groped toward it, -pushed his head and shoulders through a small hole, and saw the broad -Mississippi rolling by! And if it had only happened to be night he would -not have seen that speck of daylight and would not have explored that -passage any more! He told how he went back for Becky and broke the good -news and she told him not to fret her with such stuff, for she was -tired, and knew she was going to die, and wanted to. He described how he -labored with her and convinced her; and how she almost died for joy when -she had groped to where she actually saw the blue speck of daylight; how -he pushed his way out at the hole and then helped her out; how they sat -there and cried for gladness; how some men came along in a skiff and Tom -hailed them and told them their situation and their famished condition; -how the men didn't believe the wild tale at first, "because," said they, -"you are five miles down the river below the valley the cave is in" ---then took them aboard, rowed to a house, gave them supper, made them -rest till two or three hours after dark and then brought them home. - -Before day-dawn, Judge Thatcher and the handful of searchers with him -were tracked out, in the cave, by the twine clews they had strung -behind them, and informed of the great news. - -Three days and nights of toil and hunger in the cave were not to be -shaken off at once, as Tom and Becky soon discovered. They were -bedridden all of Wednesday and Thursday, and seemed to grow more and -more tired and worn, all the time. Tom got about, a little, on -Thursday, was down-town Friday, and nearly as whole as ever Saturday; -but Becky did not leave her room until Sunday, and then she looked as -if she had passed through a wasting illness. - -Tom learned of Huck's sickness and went to see him on Friday, but -could not be admitted to the bedroom; neither could he on Saturday or -Sunday. He was admitted daily after that, but was warned to keep still -about his adventure and introduce no exciting topic. The Widow Douglas -stayed by to see that he obeyed. At home Tom learned of the Cardiff -Hill event; also that the "ragged man's" body had eventually been found -in the river near the ferry-landing; he had been drowned while trying -to escape, perhaps. - -About a fortnight after Tom's rescue from the cave, he started off to -visit Huck, who had grown plenty strong enough, now, to hear exciting -talk, and Tom had some that would interest him, he thought. Judge -Thatcher's house was on Tom's way, and he stopped to see Becky. The -Judge and some friends set Tom to talking, and some one asked him -ironically if he wouldn't like to go to the cave again. Tom said he -thought he wouldn't mind it. The Judge said: - -"Well, there are others just like you, Tom, I've not the least doubt. -But we have taken care of that. Nobody will get lost in that cave any -more." - -"Why?" - -"Because I had its big door sheathed with boiler iron two weeks ago, -and triple-locked--and I've got the keys." - -Tom turned as white as a sheet. - -"What's the matter, boy! Here, run, somebody! Fetch a glass of water!" - -The water was brought and thrown into Tom's face. - -"Ah, now you're all right. What was the matter with you, Tom?" - -"Oh, Judge, Injun Joe's in the cave!" - - - -CHAPTER XXXIII - -WITHIN a few minutes the news had spread, and a dozen skiff-loads of -men were on their way to McDougal's cave, and the ferryboat, well -filled with passengers, soon followed. Tom Sawyer was in the skiff that -bore Judge Thatcher. - -When the cave door was unlocked, a sorrowful sight presented itself in -the dim twilight of the place. Injun Joe lay stretched upon the ground, -dead, with his face close to the crack of the door, as if his longing -eyes had been fixed, to the latest moment, upon the light and the cheer -of the free world outside. Tom was touched, for he knew by his own -experience how this wretch had suffered. His pity was moved, but -nevertheless he felt an abounding sense of relief and security, now, -which revealed to him in a degree which he had not fully appreciated -before how vast a weight of dread had been lying upon him since the day -he lifted his voice against this bloody-minded outcast. - -Injun Joe's bowie-knife lay close by, its blade broken in two. The -great foundation-beam of the door had been chipped and hacked through, -with tedious labor; useless labor, too, it was, for the native rock -formed a sill outside it, and upon that stubborn material the knife had -wrought no effect; the only damage done was to the knife itself. But if -there had been no stony obstruction there the labor would have been -useless still, for if the beam had been wholly cut away Injun Joe could -not have squeezed his body under the door, and he knew it. So he had -only hacked that place in order to be doing something--in order to pass -the weary time--in order to employ his tortured faculties. Ordinarily -one could find half a dozen bits of candle stuck around in the crevices -of this vestibule, left there by tourists; but there were none now. The -prisoner had searched them out and eaten them. He had also contrived to -catch a few bats, and these, also, he had eaten, leaving only their -claws. The poor unfortunate had starved to death. In one place, near at -hand, a stalagmite had been slowly growing up from the ground for ages, -builded by the water-drip from a stalactite overhead. The captive had -broken off the stalagmite, and upon the stump had placed a stone, -wherein he had scooped a shallow hollow to catch the precious drop -that fell once in every three minutes with the dreary regularity of a -clock-tick--a dessertspoonful once in four and twenty hours. That drop -was falling when the Pyramids were new; when Troy fell; when the -foundations of Rome were laid; when Christ was crucified; when the -Conqueror created the British empire; when Columbus sailed; when the -massacre at Lexington was "news." It is falling now; it will still be -falling when all these things shall have sunk down the afternoon of -history, and the twilight of tradition, and been swallowed up in the -thick night of oblivion. Has everything a purpose and a mission? Did -this drop fall patiently during five thousand years to be ready for -this flitting human insect's need? and has it another important object -to accomplish ten thousand years to come? No matter. It is many and -many a year since the hapless half-breed scooped out the stone to catch -the priceless drops, but to this day the tourist stares longest at that -pathetic stone and that slow-dropping water when he comes to see the -wonders of McDougal's cave. Injun Joe's cup stands first in the list of -the cavern's marvels; even "Aladdin's Palace" cannot rival it. - -Injun Joe was buried near the mouth of the cave; and people flocked -there in boats and wagons from the towns and from all the farms and -hamlets for seven miles around; they brought their children, and all -sorts of provisions, and confessed that they had had almost as -satisfactory a time at the funeral as they could have had at the -hanging. - -This funeral stopped the further growth of one thing--the petition to -the governor for Injun Joe's pardon. The petition had been largely -signed; many tearful and eloquent meetings had been held, and a -committee of sappy women been appointed to go in deep mourning and wail -around the governor, and implore him to be a merciful ass and trample -his duty under foot. Injun Joe was believed to have killed five -citizens of the village, but what of that? If he had been Satan himself -there would have been plenty of weaklings ready to scribble their names -to a pardon-petition, and drip a tear on it from their permanently -impaired and leaky water-works. - -The morning after the funeral Tom took Huck to a private place to have -an important talk. Huck had learned all about Tom's adventure from the -Welshman and the Widow Douglas, by this time, but Tom said he reckoned -there was one thing they had not told him; that thing was what he -wanted to talk about now. Huck's face saddened. He said: - -"I know what it is. You got into No. 2 and never found anything but -whiskey. Nobody told me it was you; but I just knowed it must 'a' ben -you, soon as I heard 'bout that whiskey business; and I knowed you -hadn't got the money becuz you'd 'a' got at me some way or other and -told me even if you was mum to everybody else. Tom, something's always -told me we'd never get holt of that swag." - -"Why, Huck, I never told on that tavern-keeper. YOU know his tavern -was all right the Saturday I went to the picnic. Don't you remember you -was to watch there that night?" - -"Oh yes! Why, it seems 'bout a year ago. It was that very night that I -follered Injun Joe to the widder's." - -"YOU followed him?" - -"Yes--but you keep mum. I reckon Injun Joe's left friends behind him, -and I don't want 'em souring on me and doing me mean tricks. If it -hadn't ben for me he'd be down in Texas now, all right." - -Then Huck told his entire adventure in confidence to Tom, who had only -heard of the Welshman's part of it before. - -"Well," said Huck, presently, coming back to the main question, -"whoever nipped the whiskey in No. 2, nipped the money, too, I reckon ---anyways it's a goner for us, Tom." - -"Huck, that money wasn't ever in No. 2!" - -"What!" Huck searched his comrade's face keenly. "Tom, have you got on -the track of that money again?" - -"Huck, it's in the cave!" - -Huck's eyes blazed. - -"Say it again, Tom." - -"The money's in the cave!" - -"Tom--honest injun, now--is it fun, or earnest?" - -"Earnest, Huck--just as earnest as ever I was in my life. Will you go -in there with me and help get it out?" - -"I bet I will! I will if it's where we can blaze our way to it and not -get lost." - -"Huck, we can do that without the least little bit of trouble in the -world." - -"Good as wheat! What makes you think the money's--" - -"Huck, you just wait till we get in there. If we don't find it I'll -agree to give you my drum and every thing I've got in the world. I -will, by jings." - -"All right--it's a whiz. When do you say?" - -"Right now, if you say it. Are you strong enough?" - -"Is it far in the cave? I ben on my pins a little, three or four days, -now, but I can't walk more'n a mile, Tom--least I don't think I could." - -"It's about five mile into there the way anybody but me would go, -Huck, but there's a mighty short cut that they don't anybody but me -know about. Huck, I'll take you right to it in a skiff. I'll float the -skiff down there, and I'll pull it back again all by myself. You -needn't ever turn your hand over." - -"Less start right off, Tom." - -"All right. We want some bread and meat, and our pipes, and a little -bag or two, and two or three kite-strings, and some of these -new-fangled things they call lucifer matches. I tell you, many's -the time I wished I had some when I was in there before." - -A trifle after noon the boys borrowed a small skiff from a citizen who -was absent, and got under way at once. When they were several miles -below "Cave Hollow," Tom said: - -"Now you see this bluff here looks all alike all the way down from the -cave hollow--no houses, no wood-yards, bushes all alike. But do you see -that white place up yonder where there's been a landslide? Well, that's -one of my marks. We'll get ashore, now." - -They landed. - -"Now, Huck, where we're a-standing you could touch that hole I got out -of with a fishing-pole. See if you can find it." - -Huck searched all the place about, and found nothing. Tom proudly -marched into a thick clump of sumach bushes and said: - -"Here you are! Look at it, Huck; it's the snuggest hole in this -country. You just keep mum about it. All along I've been wanting to be -a robber, but I knew I'd got to have a thing like this, and where to -run across it was the bother. We've got it now, and we'll keep it -quiet, only we'll let Joe Harper and Ben Rogers in--because of course -there's got to be a Gang, or else there wouldn't be any style about it. -Tom Sawyer's Gang--it sounds splendid, don't it, Huck?" - -"Well, it just does, Tom. And who'll we rob?" - -"Oh, most anybody. Waylay people--that's mostly the way." - -"And kill them?" - -"No, not always. Hive them in the cave till they raise a ransom." - -"What's a ransom?" - -"Money. You make them raise all they can, off'n their friends; and -after you've kept them a year, if it ain't raised then you kill them. -That's the general way. Only you don't kill the women. You shut up the -women, but you don't kill them. They're always beautiful and rich, and -awfully scared. You take their watches and things, but you always take -your hat off and talk polite. They ain't anybody as polite as robbers ---you'll see that in any book. Well, the women get to loving you, and -after they've been in the cave a week or two weeks they stop crying and -after that you couldn't get them to leave. If you drove them out they'd -turn right around and come back. It's so in all the books." - -"Why, it's real bully, Tom. I believe it's better'n to be a pirate." - -"Yes, it's better in some ways, because it's close to home and -circuses and all that." - -By this time everything was ready and the boys entered the hole, Tom -in the lead. They toiled their way to the farther end of the tunnel, -then made their spliced kite-strings fast and moved on. A few steps -brought them to the spring, and Tom felt a shudder quiver all through -him. He showed Huck the fragment of candle-wick perched on a lump of -clay against the wall, and described how he and Becky had watched the -flame struggle and expire. - -The boys began to quiet down to whispers, now, for the stillness and -gloom of the place oppressed their spirits. They went on, and presently -entered and followed Tom's other corridor until they reached the -"jumping-off place." The candles revealed the fact that it was not -really a precipice, but only a steep clay hill twenty or thirty feet -high. Tom whispered: - -"Now I'll show you something, Huck." - -He held his candle aloft and said: - -"Look as far around the corner as you can. Do you see that? There--on -the big rock over yonder--done with candle-smoke." - -"Tom, it's a CROSS!" - -"NOW where's your Number Two? 'UNDER THE CROSS,' hey? Right yonder's -where I saw Injun Joe poke up his candle, Huck!" - -Huck stared at the mystic sign awhile, and then said with a shaky voice: - -"Tom, less git out of here!" - -"What! and leave the treasure?" - -"Yes--leave it. Injun Joe's ghost is round about there, certain." - -"No it ain't, Huck, no it ain't. It would ha'nt the place where he -died--away out at the mouth of the cave--five mile from here." - -"No, Tom, it wouldn't. It would hang round the money. I know the ways -of ghosts, and so do you." - -Tom began to fear that Huck was right. Misgivings gathered in his -mind. But presently an idea occurred to him-- - -"Lookyhere, Huck, what fools we're making of ourselves! Injun Joe's -ghost ain't a going to come around where there's a cross!" - -The point was well taken. It had its effect. - -"Tom, I didn't think of that. But that's so. It's luck for us, that -cross is. I reckon we'll climb down there and have a hunt for that box." - -Tom went first, cutting rude steps in the clay hill as he descended. -Huck followed. Four avenues opened out of the small cavern which the -great rock stood in. The boys examined three of them with no result. -They found a small recess in the one nearest the base of the rock, with -a pallet of blankets spread down in it; also an old suspender, some -bacon rind, and the well-gnawed bones of two or three fowls. But there -was no money-box. The lads searched and researched this place, but in -vain. Tom said: - -"He said UNDER the cross. Well, this comes nearest to being under the -cross. It can't be under the rock itself, because that sets solid on -the ground." - -They searched everywhere once more, and then sat down discouraged. -Huck could suggest nothing. By-and-by Tom said: - -"Lookyhere, Huck, there's footprints and some candle-grease on the -clay about one side of this rock, but not on the other sides. Now, -what's that for? I bet you the money IS under the rock. I'm going to -dig in the clay." - -"That ain't no bad notion, Tom!" said Huck with animation. - -Tom's "real Barlow" was out at once, and he had not dug four inches -before he struck wood. - -"Hey, Huck!--you hear that?" - -Huck began to dig and scratch now. Some boards were soon uncovered and -removed. They had concealed a natural chasm which led under the rock. -Tom got into this and held his candle as far under the rock as he -could, but said he could not see to the end of the rift. He proposed to -explore. He stooped and passed under; the narrow way descended -gradually. He followed its winding course, first to the right, then to -the left, Huck at his heels. Tom turned a short curve, by-and-by, and -exclaimed: - -"My goodness, Huck, lookyhere!" - -It was the treasure-box, sure enough, occupying a snug little cavern, -along with an empty powder-keg, a couple of guns in leather cases, two -or three pairs of old moccasins, a leather belt, and some other rubbish -well soaked with the water-drip. - -"Got it at last!" said Huck, ploughing among the tarnished coins with -his hand. "My, but we're rich, Tom!" - -"Huck, I always reckoned we'd get it. It's just too good to believe, -but we HAVE got it, sure! Say--let's not fool around here. Let's snake -it out. Lemme see if I can lift the box." - -It weighed about fifty pounds. Tom could lift it, after an awkward -fashion, but could not carry it conveniently. - -"I thought so," he said; "THEY carried it like it was heavy, that day -at the ha'nted house. I noticed that. I reckon I was right to think of -fetching the little bags along." - -The money was soon in the bags and the boys took it up to the cross -rock. - -"Now less fetch the guns and things," said Huck. - -"No, Huck--leave them there. They're just the tricks to have when we -go to robbing. We'll keep them there all the time, and we'll hold our -orgies there, too. It's an awful snug place for orgies." - -"What orgies?" - -"I dono. But robbers always have orgies, and of course we've got to -have them, too. Come along, Huck, we've been in here a long time. It's -getting late, I reckon. I'm hungry, too. We'll eat and smoke when we -get to the skiff." - -They presently emerged into the clump of sumach bushes, looked warily -out, found the coast clear, and were soon lunching and smoking in the -skiff. As the sun dipped toward the horizon they pushed out and got -under way. Tom skimmed up the shore through the long twilight, chatting -cheerily with Huck, and landed shortly after dark. - -"Now, Huck," said Tom, "we'll hide the money in the loft of the -widow's woodshed, and I'll come up in the morning and we'll count it -and divide, and then we'll hunt up a place out in the woods for it -where it will be safe. Just you lay quiet here and watch the stuff till -I run and hook Benny Taylor's little wagon; I won't be gone a minute." - -He disappeared, and presently returned with the wagon, put the two -small sacks into it, threw some old rags on top of them, and started -off, dragging his cargo behind him. When the boys reached the -Welshman's house, they stopped to rest. Just as they were about to move -on, the Welshman stepped out and said: - -"Hallo, who's that?" - -"Huck and Tom Sawyer." - -"Good! Come along with me, boys, you are keeping everybody waiting. -Here--hurry up, trot ahead--I'll haul the wagon for you. Why, it's not -as light as it might be. Got bricks in it?--or old metal?" - -"Old metal," said Tom. - -"I judged so; the boys in this town will take more trouble and fool -away more time hunting up six bits' worth of old iron to sell to the -foundry than they would to make twice the money at regular work. But -that's human nature--hurry along, hurry along!" - -The boys wanted to know what the hurry was about. - -"Never mind; you'll see, when we get to the Widow Douglas'." - -Huck said with some apprehension--for he was long used to being -falsely accused: - -"Mr. Jones, we haven't been doing nothing." - -The Welshman laughed. - -"Well, I don't know, Huck, my boy. I don't know about that. Ain't you -and the widow good friends?" - -"Yes. Well, she's ben good friends to me, anyway." - -"All right, then. What do you want to be afraid for?" - -This question was not entirely answered in Huck's slow mind before he -found himself pushed, along with Tom, into Mrs. Douglas' drawing-room. -Mr. Jones left the wagon near the door and followed. - -The place was grandly lighted, and everybody that was of any -consequence in the village was there. The Thatchers were there, the -Harpers, the Rogerses, Aunt Polly, Sid, Mary, the minister, the editor, -and a great many more, and all dressed in their best. The widow -received the boys as heartily as any one could well receive two such -looking beings. They were covered with clay and candle-grease. Aunt -Polly blushed crimson with humiliation, and frowned and shook her head -at Tom. Nobody suffered half as much as the two boys did, however. Mr. -Jones said: - -"Tom wasn't at home, yet, so I gave him up; but I stumbled on him and -Huck right at my door, and so I just brought them along in a hurry." - -"And you did just right," said the widow. "Come with me, boys." - -She took them to a bedchamber and said: - -"Now wash and dress yourselves. Here are two new suits of clothes ---shirts, socks, everything complete. They're Huck's--no, no thanks, -Huck--Mr. Jones bought one and I the other. But they'll fit both of you. -Get into them. We'll wait--come down when you are slicked up enough." - -Then she left. - - - -CHAPTER XXXIV - -HUCK said: "Tom, we can slope, if we can find a rope. The window ain't -high from the ground." - -"Shucks! what do you want to slope for?" - -"Well, I ain't used to that kind of a crowd. I can't stand it. I ain't -going down there, Tom." - -"Oh, bother! It ain't anything. I don't mind it a bit. I'll take care -of you." - -Sid appeared. - -"Tom," said he, "auntie has been waiting for you all the afternoon. -Mary got your Sunday clothes ready, and everybody's been fretting about -you. Say--ain't this grease and clay, on your clothes?" - -"Now, Mr. Siddy, you jist 'tend to your own business. What's all this -blow-out about, anyway?" - -"It's one of the widow's parties that she's always having. This time -it's for the Welshman and his sons, on account of that scrape they -helped her out of the other night. And say--I can tell you something, -if you want to know." - -"Well, what?" - -"Why, old Mr. Jones is going to try to spring something on the people -here to-night, but I overheard him tell auntie to-day about it, as a -secret, but I reckon it's not much of a secret now. Everybody knows ---the widow, too, for all she tries to let on she don't. Mr. Jones was -bound Huck should be here--couldn't get along with his grand secret -without Huck, you know!" - -"Secret about what, Sid?" - -"About Huck tracking the robbers to the widow's. I reckon Mr. Jones -was going to make a grand time over his surprise, but I bet you it will -drop pretty flat." - -Sid chuckled in a very contented and satisfied way. - -"Sid, was it you that told?" - -"Oh, never mind who it was. SOMEBODY told--that's enough." - -"Sid, there's only one person in this town mean enough to do that, and -that's you. If you had been in Huck's place you'd 'a' sneaked down the -hill and never told anybody on the robbers. You can't do any but mean -things, and you can't bear to see anybody praised for doing good ones. -There--no thanks, as the widow says"--and Tom cuffed Sid's ears and -helped him to the door with several kicks. "Now go and tell auntie if -you dare--and to-morrow you'll catch it!" - -Some minutes later the widow's guests were at the supper-table, and a -dozen children were propped up at little side-tables in the same room, -after the fashion of that country and that day. At the proper time Mr. -Jones made his little speech, in which he thanked the widow for the -honor she was doing himself and his sons, but said that there was -another person whose modesty-- - -And so forth and so on. He sprung his secret about Huck's share in the -adventure in the finest dramatic manner he was master of, but the -surprise it occasioned was largely counterfeit and not as clamorous and -effusive as it might have been under happier circumstances. However, -the widow made a pretty fair show of astonishment, and heaped so many -compliments and so much gratitude upon Huck that he almost forgot the -nearly intolerable discomfort of his new clothes in the entirely -intolerable discomfort of being set up as a target for everybody's gaze -and everybody's laudations. - -The widow said she meant to give Huck a home under her roof and have -him educated; and that when she could spare the money she would start -him in business in a modest way. Tom's chance was come. He said: - -"Huck don't need it. Huck's rich." - -Nothing but a heavy strain upon the good manners of the company kept -back the due and proper complimentary laugh at this pleasant joke. But -the silence was a little awkward. Tom broke it: - -"Huck's got money. Maybe you don't believe it, but he's got lots of -it. Oh, you needn't smile--I reckon I can show you. You just wait a -minute." - -Tom ran out of doors. The company looked at each other with a -perplexed interest--and inquiringly at Huck, who was tongue-tied. - -"Sid, what ails Tom?" said Aunt Polly. "He--well, there ain't ever any -making of that boy out. I never--" - -Tom entered, struggling with the weight of his sacks, and Aunt Polly -did not finish her sentence. Tom poured the mass of yellow coin upon -the table and said: - -"There--what did I tell you? Half of it's Huck's and half of it's mine!" - -The spectacle took the general breath away. All gazed, nobody spoke -for a moment. Then there was a unanimous call for an explanation. Tom -said he could furnish it, and he did. The tale was long, but brimful of -interest. There was scarcely an interruption from any one to break the -charm of its flow. When he had finished, Mr. Jones said: - -"I thought I had fixed up a little surprise for this occasion, but it -don't amount to anything now. This one makes it sing mighty small, I'm -willing to allow." - -The money was counted. The sum amounted to a little over twelve -thousand dollars. It was more than any one present had ever seen at one -time before, though several persons were there who were worth -considerably more than that in property. - - - -CHAPTER XXXV - -THE reader may rest satisfied that Tom's and Huck's windfall made a -mighty stir in the poor little village of St. Petersburg. So vast a -sum, all in actual cash, seemed next to incredible. It was talked -about, gloated over, glorified, until the reason of many of the -citizens tottered under the strain of the unhealthy excitement. Every -"haunted" house in St. Petersburg and the neighboring villages was -dissected, plank by plank, and its foundations dug up and ransacked for -hidden treasure--and not by boys, but men--pretty grave, unromantic -men, too, some of them. Wherever Tom and Huck appeared they were -courted, admired, stared at. The boys were not able to remember that -their remarks had possessed weight before; but now their sayings were -treasured and repeated; everything they did seemed somehow to be -regarded as remarkable; they had evidently lost the power of doing and -saying commonplace things; moreover, their past history was raked up -and discovered to bear marks of conspicuous originality. The village -paper published biographical sketches of the boys. - -The Widow Douglas put Huck's money out at six per cent., and Judge -Thatcher did the same with Tom's at Aunt Polly's request. Each lad had -an income, now, that was simply prodigious--a dollar for every week-day -in the year and half of the Sundays. It was just what the minister got ---no, it was what he was promised--he generally couldn't collect it. A -dollar and a quarter a week would board, lodge, and school a boy in -those old simple days--and clothe him and wash him, too, for that -matter. - -Judge Thatcher had conceived a great opinion of Tom. He said that no -commonplace boy would ever have got his daughter out of the cave. When -Becky told her father, in strict confidence, how Tom had taken her -whipping at school, the Judge was visibly moved; and when she pleaded -grace for the mighty lie which Tom had told in order to shift that -whipping from her shoulders to his own, the Judge said with a fine -outburst that it was a noble, a generous, a magnanimous lie--a lie that -was worthy to hold up its head and march down through history breast to -breast with George Washington's lauded Truth about the hatchet! Becky -thought her father had never looked so tall and so superb as when he -walked the floor and stamped his foot and said that. She went straight -off and told Tom about it. - -Judge Thatcher hoped to see Tom a great lawyer or a great soldier some -day. He said he meant to look to it that Tom should be admitted to the -National Military Academy and afterward trained in the best law school -in the country, in order that he might be ready for either career or -both. - -Huck Finn's wealth and the fact that he was now under the Widow -Douglas' protection introduced him into society--no, dragged him into -it, hurled him into it--and his sufferings were almost more than he -could bear. The widow's servants kept him clean and neat, combed and -brushed, and they bedded him nightly in unsympathetic sheets that had -not one little spot or stain which he could press to his heart and know -for a friend. He had to eat with a knife and fork; he had to use -napkin, cup, and plate; he had to learn his book, he had to go to -church; he had to talk so properly that speech was become insipid in -his mouth; whithersoever he turned, the bars and shackles of -civilization shut him in and bound him hand and foot. - -He bravely bore his miseries three weeks, and then one day turned up -missing. For forty-eight hours the widow hunted for him everywhere in -great distress. The public were profoundly concerned; they searched -high and low, they dragged the river for his body. Early the third -morning Tom Sawyer wisely went poking among some old empty hogsheads -down behind the abandoned slaughter-house, and in one of them he found -the refugee. Huck had slept there; he had just breakfasted upon some -stolen odds and ends of food, and was lying off, now, in comfort, with -his pipe. He was unkempt, uncombed, and clad in the same old ruin of -rags that had made him picturesque in the days when he was free and -happy. Tom routed him out, told him the trouble he had been causing, -and urged him to go home. Huck's face lost its tranquil content, and -took a melancholy cast. He said: - -"Don't talk about it, Tom. I've tried it, and it don't work; it don't -work, Tom. It ain't for me; I ain't used to it. The widder's good to -me, and friendly; but I can't stand them ways. She makes me get up just -at the same time every morning; she makes me wash, they comb me all to -thunder; she won't let me sleep in the woodshed; I got to wear them -blamed clothes that just smothers me, Tom; they don't seem to any air -git through 'em, somehow; and they're so rotten nice that I can't set -down, nor lay down, nor roll around anywher's; I hain't slid on a -cellar-door for--well, it 'pears to be years; I got to go to church and -sweat and sweat--I hate them ornery sermons! I can't ketch a fly in -there, I can't chaw. I got to wear shoes all Sunday. The widder eats by -a bell; she goes to bed by a bell; she gits up by a bell--everything's -so awful reg'lar a body can't stand it." - -"Well, everybody does that way, Huck." - -"Tom, it don't make no difference. I ain't everybody, and I can't -STAND it. It's awful to be tied up so. And grub comes too easy--I don't -take no interest in vittles, that way. I got to ask to go a-fishing; I -got to ask to go in a-swimming--dern'd if I hain't got to ask to do -everything. Well, I'd got to talk so nice it wasn't no comfort--I'd got -to go up in the attic and rip out awhile, every day, to git a taste in -my mouth, or I'd a died, Tom. The widder wouldn't let me smoke; she -wouldn't let me yell, she wouldn't let me gape, nor stretch, nor -scratch, before folks--" [Then with a spasm of special irritation and -injury]--"And dad fetch it, she prayed all the time! I never see such a -woman! I HAD to shove, Tom--I just had to. And besides, that school's -going to open, and I'd a had to go to it--well, I wouldn't stand THAT, -Tom. Looky here, Tom, being rich ain't what it's cracked up to be. It's -just worry and worry, and sweat and sweat, and a-wishing you was dead -all the time. Now these clothes suits me, and this bar'l suits me, and -I ain't ever going to shake 'em any more. Tom, I wouldn't ever got into -all this trouble if it hadn't 'a' ben for that money; now you just take -my sheer of it along with your'n, and gimme a ten-center sometimes--not -many times, becuz I don't give a dern for a thing 'thout it's tollable -hard to git--and you go and beg off for me with the widder." - -"Oh, Huck, you know I can't do that. 'Tain't fair; and besides if -you'll try this thing just a while longer you'll come to like it." - -"Like it! Yes--the way I'd like a hot stove if I was to set on it long -enough. No, Tom, I won't be rich, and I won't live in them cussed -smothery houses. I like the woods, and the river, and hogsheads, and -I'll stick to 'em, too. Blame it all! just as we'd got guns, and a -cave, and all just fixed to rob, here this dern foolishness has got to -come up and spile it all!" - -Tom saw his opportunity-- - -"Lookyhere, Huck, being rich ain't going to keep me back from turning -robber." - -"No! Oh, good-licks; are you in real dead-wood earnest, Tom?" - -"Just as dead earnest as I'm sitting here. But Huck, we can't let you -into the gang if you ain't respectable, you know." - -Huck's joy was quenched. - -"Can't let me in, Tom? Didn't you let me go for a pirate?" - -"Yes, but that's different. A robber is more high-toned than what a -pirate is--as a general thing. In most countries they're awful high up -in the nobility--dukes and such." - -"Now, Tom, hain't you always ben friendly to me? You wouldn't shet me -out, would you, Tom? You wouldn't do that, now, WOULD you, Tom?" - -"Huck, I wouldn't want to, and I DON'T want to--but what would people -say? Why, they'd say, 'Mph! Tom Sawyer's Gang! pretty low characters in -it!' They'd mean you, Huck. You wouldn't like that, and I wouldn't." - -Huck was silent for some time, engaged in a mental struggle. Finally -he said: - -"Well, I'll go back to the widder for a month and tackle it and see if -I can come to stand it, if you'll let me b'long to the gang, Tom." - -"All right, Huck, it's a whiz! Come along, old chap, and I'll ask the -widow to let up on you a little, Huck." - -"Will you, Tom--now will you? That's good. If she'll let up on some of -the roughest things, I'll smoke private and cuss private, and crowd -through or bust. When you going to start the gang and turn robbers?" - -"Oh, right off. We'll get the boys together and have the initiation -to-night, maybe." - -"Have the which?" - -"Have the initiation." - -"What's that?" - -"It's to swear to stand by one another, and never tell the gang's -secrets, even if you're chopped all to flinders, and kill anybody and -all his family that hurts one of the gang." - -"That's gay--that's mighty gay, Tom, I tell you." - -"Well, I bet it is. And all that swearing's got to be done at -midnight, in the lonesomest, awfulest place you can find--a ha'nted -house is the best, but they're all ripped up now." - -"Well, midnight's good, anyway, Tom." - -"Yes, so it is. And you've got to swear on a coffin, and sign it with -blood." - -"Now, that's something LIKE! Why, it's a million times bullier than -pirating. I'll stick to the widder till I rot, Tom; and if I git to be -a reg'lar ripper of a robber, and everybody talking 'bout it, I reckon -she'll be proud she snaked me in out of the wet." - - - -CONCLUSION - -SO endeth this chronicle. It being strictly a history of a BOY, it -must stop here; the story could not go much further without becoming -the history of a MAN. When one writes a novel about grown people, he -knows exactly where to stop--that is, with a marriage; but when he -writes of juveniles, he must stop where he best can. - -Most of the characters that perform in this book still live, and are -prosperous and happy. Some day it may seem worth while to take up the -story of the younger ones again and see what sort of men and women they -turned out to be; therefore it will be wisest not to reveal any of that -part of their lives at present. diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/README.md b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/README.md deleted file mode 100644 index da6d966..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# libbacktrace -A C library that may be linked into a C/C++ program to produce symbolic backtraces - -Initially written by Ian Lance Taylor . - -This is version 1.0. -It is likely that this will always be version 1.0. - -The libbacktrace library may be linked into a program or library and -used to produce symbolic backtraces. -Sample uses would be to print a detailed backtrace when an error -occurs or to gather detailed profiling information. - -The libbacktrace library is provided under a BSD license. -See the source files for the exact license text. - -The public functions are declared and documented in the header file -backtrace.h, which should be #include'd by a user of the library. - -Building libbacktrace will generate a file backtrace-supported.h, -which a user of the library may use to determine whether backtraces -will work. -See the source file backtrace-supported.h.in for the macros that it -defines. - -As of January 2018, libbacktrace only supports ELF, PE/COFF, and XCOFF -executables with DWARF debugging information. -The library is written to make it straightforward to add support for -other object file and debugging formats. - -The library relies on the C++ unwind API defined at -https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html -This API is provided by GCC. diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/acinclude.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/acinclude.m4 deleted file mode 100644 index daa73af..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/acinclude.m4 +++ /dev/null @@ -1,72 +0,0 @@ -dnl -dnl Check whether _Unwind_GetIPInfo is available without doing a link -dnl test so we can use this with libstdc++-v3 and libjava. Need to -dnl use $target to set defaults because automatic checking is not possible -dnl without a link test (and maybe even with a link test). -dnl - -AC_DEFUN([GCC_CHECK_UNWIND_GETIPINFO], [ - AC_ARG_WITH(system-libunwind, - [ --with-system-libunwind use installed libunwind]) - # If system-libunwind was not specifically set, pick a default setting. - if test x$with_system_libunwind = x; then - case ${target} in - ia64-*-hpux*) with_system_libunwind=yes ;; - *) with_system_libunwind=no ;; - esac - fi - # Based on system-libunwind and target, do we have ipinfo? - if test x$with_system_libunwind = xyes; then - case ${target} in - ia64-*-*) have_unwind_getipinfo=no ;; - *) have_unwind_getipinfo=yes ;; - esac - else - # Darwin before version 9 does not have _Unwind_GetIPInfo. - changequote(,) - case ${target} in - *-*-darwin[3-8]|*-*-darwin[3-8].*) have_unwind_getipinfo=no ;; - *) have_unwind_getipinfo=yes ;; - esac - changequote([,]) - fi - - if test x$have_unwind_getipinfo = xyes; then - AC_DEFINE(HAVE_GETIPINFO, 1, [Define if _Unwind_GetIPInfo is available.]) - fi -]) - -# ACX_PROG_CC_WARNING_OPTS(WARNINGS, [VARIABLE = WARN_CFLAGS]) -# Sets @VARIABLE@ to the subset of the given options which the -# compiler accepts. -AC_DEFUN([ACX_PROG_CC_WARNING_OPTS], -[AC_REQUIRE([AC_PROG_CC])dnl -AC_LANG_PUSH(C) -m4_pushdef([acx_Var], [m4_default([$2], [WARN_CFLAGS])])dnl -AC_SUBST(acx_Var)dnl -m4_expand_once([acx_Var= -],m4_quote(acx_Var=))dnl -save_CFLAGS="$CFLAGS" -for real_option in $1; do - # Do the check with the no- prefix removed since gcc silently - # accepts any -Wno-* option on purpose - case $real_option in - -Wno-*) option=-W`expr x$real_option : 'x-Wno-\(.*\)'` ;; - *) option=$real_option ;; - esac - AS_VAR_PUSHDEF([acx_Woption], [acx_cv_prog_cc_warning_$option]) - AC_CACHE_CHECK([whether $CC supports $option], acx_Woption, - [CFLAGS="$option" - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])], - [AS_VAR_SET(acx_Woption, yes)], - [AS_VAR_SET(acx_Woption, no)]) - ]) - AS_IF([test AS_VAR_GET(acx_Woption) = yes], - [acx_Var="$acx_Var${acx_Var:+ }$real_option"]) - AS_VAR_POPDEF([acx_Woption])dnl -done -CFLAGS="$save_CFLAGS" -m4_popdef([acx_Var])dnl -AC_LANG_POP(C) -])# ACX_PROG_CC_WARNING_OPTS - diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/aclocal.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/aclocal.m4 deleted file mode 100644 index 32a1811..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/aclocal.m4 +++ /dev/null @@ -1,767 +0,0 @@ -# generated automatically by aclocal 1.11.6 -*- Autoconf -*- - -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, -# 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, -# Inc. -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY, to the extent permitted by law; without -# even the implied warranty of MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. - -m4_ifndef([AC_AUTOCONF_VERSION], - [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl -m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.64],, -[m4_warning([this file was generated for autoconf 2.64. -You have another version of autoconf. It may work, but is not guaranteed to. -If you have problems, you may need to regenerate the build system entirely. -To do so, use the procedure documented by the package, typically `autoreconf'.])]) - -# Copyright (C) 2002, 2003, 2005, 2006, 2007, 2008, 2011 Free Software -# Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 1 - -# AM_AUTOMAKE_VERSION(VERSION) -# ---------------------------- -# Automake X.Y traces this macro to ensure aclocal.m4 has been -# generated from the m4 files accompanying Automake X.Y. -# (This private macro should not be called outside this file.) -AC_DEFUN([AM_AUTOMAKE_VERSION], -[am__api_version='1.11' -dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to -dnl require some minimum version. Point them to the right macro. -m4_if([$1], [1.11.6], [], - [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl -]) - -# _AM_AUTOCONF_VERSION(VERSION) -# ----------------------------- -# aclocal traces this macro to find the Autoconf version. -# This is a private macro too. Using m4_define simplifies -# the logic in aclocal, which can simply ignore this definition. -m4_define([_AM_AUTOCONF_VERSION], []) - -# AM_SET_CURRENT_AUTOMAKE_VERSION -# ------------------------------- -# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. -# This function is AC_REQUIREd by AM_INIT_AUTOMAKE. -AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], -[AM_AUTOMAKE_VERSION([1.11.6])dnl -m4_ifndef([AC_AUTOCONF_VERSION], - [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl -_AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) - -# AM_AUX_DIR_EXPAND -*- Autoconf -*- - -# Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 1 - -# For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets -# $ac_aux_dir to `$srcdir/foo'. In other projects, it is set to -# `$srcdir', `$srcdir/..', or `$srcdir/../..'. -# -# Of course, Automake must honor this variable whenever it calls a -# tool from the auxiliary directory. The problem is that $srcdir (and -# therefore $ac_aux_dir as well) can be either absolute or relative, -# depending on how configure is run. This is pretty annoying, since -# it makes $ac_aux_dir quite unusable in subdirectories: in the top -# source directory, any form will work fine, but in subdirectories a -# relative path needs to be adjusted first. -# -# $ac_aux_dir/missing -# fails when called from a subdirectory if $ac_aux_dir is relative -# $top_srcdir/$ac_aux_dir/missing -# fails if $ac_aux_dir is absolute, -# fails when called from a subdirectory in a VPATH build with -# a relative $ac_aux_dir -# -# The reason of the latter failure is that $top_srcdir and $ac_aux_dir -# are both prefixed by $srcdir. In an in-source build this is usually -# harmless because $srcdir is `.', but things will broke when you -# start a VPATH build or use an absolute $srcdir. -# -# So we could use something similar to $top_srcdir/$ac_aux_dir/missing, -# iff we strip the leading $srcdir from $ac_aux_dir. That would be: -# am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` -# and then we would define $MISSING as -# MISSING="\${SHELL} $am_aux_dir/missing" -# This will work as long as MISSING is not called from configure, because -# unfortunately $(top_srcdir) has no meaning in configure. -# However there are other variables, like CC, which are often used in -# configure, and could therefore not use this "fixed" $ac_aux_dir. -# -# Another solution, used here, is to always expand $ac_aux_dir to an -# absolute PATH. The drawback is that using absolute paths prevent a -# configured tree to be moved without reconfiguration. - -AC_DEFUN([AM_AUX_DIR_EXPAND], -[dnl Rely on autoconf to set up CDPATH properly. -AC_PREREQ([2.50])dnl -# expand $ac_aux_dir to an absolute path -am_aux_dir=`cd $ac_aux_dir && pwd` -]) - -# AM_CONDITIONAL -*- Autoconf -*- - -# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006, 2008 -# Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 9 - -# AM_CONDITIONAL(NAME, SHELL-CONDITION) -# ------------------------------------- -# Define a conditional. -AC_DEFUN([AM_CONDITIONAL], -[AC_PREREQ(2.52)dnl - ifelse([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], - [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl -AC_SUBST([$1_TRUE])dnl -AC_SUBST([$1_FALSE])dnl -_AM_SUBST_NOTMAKE([$1_TRUE])dnl -_AM_SUBST_NOTMAKE([$1_FALSE])dnl -m4_define([_AM_COND_VALUE_$1], [$2])dnl -if $2; then - $1_TRUE= - $1_FALSE='#' -else - $1_TRUE='#' - $1_FALSE= -fi -AC_CONFIG_COMMANDS_PRE( -[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then - AC_MSG_ERROR([[conditional "$1" was never defined. -Usually this means the macro was only invoked conditionally.]]) -fi])]) - -# Do all the work for Automake. -*- Autoconf -*- - -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, -# 2005, 2006, 2008, 2009 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 16 - -# This macro actually does too much. Some checks are only needed if -# your package does certain things. But this isn't really a big deal. - -# AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) -# AM_INIT_AUTOMAKE([OPTIONS]) -# ----------------------------------------------- -# The call with PACKAGE and VERSION arguments is the old style -# call (pre autoconf-2.50), which is being phased out. PACKAGE -# and VERSION should now be passed to AC_INIT and removed from -# the call to AM_INIT_AUTOMAKE. -# We support both call styles for the transition. After -# the next Automake release, Autoconf can make the AC_INIT -# arguments mandatory, and then we can depend on a new Autoconf -# release and drop the old call support. -AC_DEFUN([AM_INIT_AUTOMAKE], -[AC_PREREQ([2.62])dnl -dnl Autoconf wants to disallow AM_ names. We explicitly allow -dnl the ones we care about. -m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl -AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl -AC_REQUIRE([AC_PROG_INSTALL])dnl -if test "`cd $srcdir && pwd`" != "`pwd`"; then - # Use -I$(srcdir) only when $(srcdir) != ., so that make's output - # is not polluted with repeated "-I." - AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl - # test to see if srcdir already configured - if test -f $srcdir/config.status; then - AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) - fi -fi - -# test whether we have cygpath -if test -z "$CYGPATH_W"; then - if (cygpath --version) >/dev/null 2>/dev/null; then - CYGPATH_W='cygpath -w' - else - CYGPATH_W=echo - fi -fi -AC_SUBST([CYGPATH_W]) - -# Define the identity of the package. -dnl Distinguish between old-style and new-style calls. -m4_ifval([$2], -[m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl - AC_SUBST([PACKAGE], [$1])dnl - AC_SUBST([VERSION], [$2])], -[_AM_SET_OPTIONS([$1])dnl -dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. -m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,, - [m4_fatal([AC_INIT should be called with package and version arguments])])dnl - AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl - AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl - -_AM_IF_OPTION([no-define],, -[AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of package]) - AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version number of package])])dnl - -# Some tools Automake needs. -AC_REQUIRE([AM_SANITY_CHECK])dnl -AC_REQUIRE([AC_ARG_PROGRAM])dnl -AM_MISSING_PROG(ACLOCAL, aclocal-${am__api_version}) -AM_MISSING_PROG(AUTOCONF, autoconf) -AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version}) -AM_MISSING_PROG(AUTOHEADER, autoheader) -AM_MISSING_PROG(MAKEINFO, makeinfo) -AC_REQUIRE([AM_PROG_INSTALL_SH])dnl -AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl -AC_REQUIRE([AM_PROG_MKDIR_P])dnl -# We need awk for the "check" target. The system "awk" is bad on -# some platforms. -AC_REQUIRE([AC_PROG_AWK])dnl -AC_REQUIRE([AC_PROG_MAKE_SET])dnl -AC_REQUIRE([AM_SET_LEADING_DOT])dnl -_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], - [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], - [_AM_PROG_TAR([v7])])]) -_AM_IF_OPTION([no-dependencies],, -[AC_PROVIDE_IFELSE([AC_PROG_CC], - [_AM_DEPENDENCIES(CC)], - [define([AC_PROG_CC], - defn([AC_PROG_CC])[_AM_DEPENDENCIES(CC)])])dnl -AC_PROVIDE_IFELSE([AC_PROG_CXX], - [_AM_DEPENDENCIES(CXX)], - [define([AC_PROG_CXX], - defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl -AC_PROVIDE_IFELSE([AC_PROG_OBJC], - [_AM_DEPENDENCIES(OBJC)], - [define([AC_PROG_OBJC], - defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl -]) -_AM_IF_OPTION([silent-rules], [AC_REQUIRE([AM_SILENT_RULES])])dnl -dnl The `parallel-tests' driver may need to know about EXEEXT, so add the -dnl `am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This macro -dnl is hooked onto _AC_COMPILER_EXEEXT early, see below. -AC_CONFIG_COMMANDS_PRE(dnl -[m4_provide_if([_AM_COMPILER_EXEEXT], - [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl -]) - -dnl Hook into `_AC_COMPILER_EXEEXT' early to learn its expansion. Do not -dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further -dnl mangled by Autoconf and run in a shell conditional statement. -m4_define([_AC_COMPILER_EXEEXT], -m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) - - -# When config.status generates a header, we must update the stamp-h file. -# This file resides in the same directory as the config header -# that is generated. The stamp files are numbered to have different names. - -# Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the -# loop where config.status creates the headers, so we can generate -# our stamp files there. -AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], -[# Compute $1's index in $config_headers. -_am_arg=$1 -_am_stamp_count=1 -for _am_header in $config_headers :; do - case $_am_header in - $_am_arg | $_am_arg:* ) - break ;; - * ) - _am_stamp_count=`expr $_am_stamp_count + 1` ;; - esac -done -echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) - -# Copyright (C) 2001, 2003, 2005, 2008, 2011 Free Software Foundation, -# Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 1 - -# AM_PROG_INSTALL_SH -# ------------------ -# Define $install_sh. -AC_DEFUN([AM_PROG_INSTALL_SH], -[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl -if test x"${install_sh}" != xset; then - case $am_aux_dir in - *\ * | *\ *) - install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; - *) - install_sh="\${SHELL} $am_aux_dir/install-sh" - esac -fi -AC_SUBST(install_sh)]) - -# Copyright (C) 2003, 2005 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 2 - -# Check whether the underlying file-system supports filenames -# with a leading dot. For instance MS-DOS doesn't. -AC_DEFUN([AM_SET_LEADING_DOT], -[rm -rf .tst 2>/dev/null -mkdir .tst 2>/dev/null -if test -d .tst; then - am__leading_dot=. -else - am__leading_dot=_ -fi -rmdir .tst 2>/dev/null -AC_SUBST([am__leading_dot])]) - -# Add --enable-maintainer-mode option to configure. -*- Autoconf -*- -# From Jim Meyering - -# Copyright (C) 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008, -# 2011 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 5 - -# AM_MAINTAINER_MODE([DEFAULT-MODE]) -# ---------------------------------- -# Control maintainer-specific portions of Makefiles. -# Default is to disable them, unless `enable' is passed literally. -# For symmetry, `disable' may be passed as well. Anyway, the user -# can override the default with the --enable/--disable switch. -AC_DEFUN([AM_MAINTAINER_MODE], -[m4_case(m4_default([$1], [disable]), - [enable], [m4_define([am_maintainer_other], [disable])], - [disable], [m4_define([am_maintainer_other], [enable])], - [m4_define([am_maintainer_other], [enable]) - m4_warn([syntax], [unexpected argument to AM@&t@_MAINTAINER_MODE: $1])]) -AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) - dnl maintainer-mode's default is 'disable' unless 'enable' is passed - AC_ARG_ENABLE([maintainer-mode], -[ --][am_maintainer_other][-maintainer-mode am_maintainer_other make rules and dependencies not useful - (and sometimes confusing) to the casual installer], - [USE_MAINTAINER_MODE=$enableval], - [USE_MAINTAINER_MODE=]m4_if(am_maintainer_other, [enable], [no], [yes])) - AC_MSG_RESULT([$USE_MAINTAINER_MODE]) - AM_CONDITIONAL([MAINTAINER_MODE], [test $USE_MAINTAINER_MODE = yes]) - MAINT=$MAINTAINER_MODE_TRUE - AC_SUBST([MAINT])dnl -] -) - -AU_DEFUN([jm_MAINTAINER_MODE], [AM_MAINTAINER_MODE]) - -# Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- - -# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005, 2008 -# Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 6 - -# AM_MISSING_PROG(NAME, PROGRAM) -# ------------------------------ -AC_DEFUN([AM_MISSING_PROG], -[AC_REQUIRE([AM_MISSING_HAS_RUN]) -$1=${$1-"${am_missing_run}$2"} -AC_SUBST($1)]) - - -# AM_MISSING_HAS_RUN -# ------------------ -# Define MISSING if not defined so far and test if it supports --run. -# If it does, set am_missing_run to use it, otherwise, to nothing. -AC_DEFUN([AM_MISSING_HAS_RUN], -[AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl -AC_REQUIRE_AUX_FILE([missing])dnl -if test x"${MISSING+set}" != xset; then - case $am_aux_dir in - *\ * | *\ *) - MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; - *) - MISSING="\${SHELL} $am_aux_dir/missing" ;; - esac -fi -# Use eval to expand $SHELL -if eval "$MISSING --run true"; then - am_missing_run="$MISSING --run " -else - am_missing_run= - AC_MSG_WARN([`missing' script is too old or missing]) -fi -]) - -# Copyright (C) 2003, 2004, 2005, 2006, 2011 Free Software Foundation, -# Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 1 - -# AM_PROG_MKDIR_P -# --------------- -# Check for `mkdir -p'. -AC_DEFUN([AM_PROG_MKDIR_P], -[AC_PREREQ([2.60])dnl -AC_REQUIRE([AC_PROG_MKDIR_P])dnl -dnl Automake 1.8 to 1.9.6 used to define mkdir_p. We now use MKDIR_P, -dnl while keeping a definition of mkdir_p for backward compatibility. -dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile. -dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of -dnl Makefile.ins that do not define MKDIR_P, so we do our own -dnl adjustment using top_builddir (which is defined more often than -dnl MKDIR_P). -AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl -case $mkdir_p in - [[\\/$]]* | ?:[[\\/]]*) ;; - */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; -esac -]) - -# Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2012 -# Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 6 - -# AM_ENABLE_MULTILIB([MAKEFILE], [REL-TO-TOP-SRCDIR]) -# --------------------------------------------------- -# Add --enable-multilib to configure. -AC_DEFUN([AM_ENABLE_MULTILIB], -[m4_warn([obsolete], [$0 will be removed from Automake core soon. -Files implementing the "multilib" feature are (and will remain) available -to the 'contrib/' directory in the Automake distribution.])]dnl -[# Default to --enable-multilib -AC_ARG_ENABLE(multilib, -[ --enable-multilib build many library versions (default)], -[case "$enableval" in - yes) multilib=yes ;; - no) multilib=no ;; - *) AC_MSG_ERROR([bad value $enableval for multilib option]) ;; - esac], - [multilib=yes]) - -# We may get other options which we leave undocumented: -# --with-target-subdir, --with-multisrctop, --with-multisubdir -# See config-ml.in if you want the gory details. - -if test "$srcdir" = "."; then - if test "$with_target_subdir" != "."; then - multi_basedir="$srcdir/$with_multisrctop../$2" - else - multi_basedir="$srcdir/$with_multisrctop$2" - fi -else - multi_basedir="$srcdir/$2" -fi -AC_SUBST(multi_basedir) - -# Even if the default multilib is not a cross compilation, -# it may be that some of the other multilibs are. -if test $cross_compiling = no && test $multilib = yes \ - && test "x${with_multisubdir}" != x ; then - cross_compiling=maybe -fi - -AC_OUTPUT_COMMANDS([ -# Only add multilib support code if we just rebuilt the top-level -# Makefile. -case " $CONFIG_FILES " in - *" ]m4_default([$1],Makefile)[ "*) - ac_file=]m4_default([$1],Makefile)[ . ${multi_basedir}/config-ml.in - ;; -esac], - [ -srcdir="$srcdir" -host="$host" -target="$target" -with_multisubdir="$with_multisubdir" -with_multisrctop="$with_multisrctop" -with_target_subdir="$with_target_subdir" -ac_configure_args="${multilib_arg} ${ac_configure_args}" -multi_basedir="$multi_basedir" -CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} -CC="$CC"])])dnl - -# Helper functions for option handling. -*- Autoconf -*- - -# Copyright (C) 2001, 2002, 2003, 2005, 2008, 2010 Free Software -# Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 5 - -# _AM_MANGLE_OPTION(NAME) -# ----------------------- -AC_DEFUN([_AM_MANGLE_OPTION], -[[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) - -# _AM_SET_OPTION(NAME) -# -------------------- -# Set option NAME. Presently that only means defining a flag for this option. -AC_DEFUN([_AM_SET_OPTION], -[m4_define(_AM_MANGLE_OPTION([$1]), 1)]) - -# _AM_SET_OPTIONS(OPTIONS) -# ------------------------ -# OPTIONS is a space-separated list of Automake options. -AC_DEFUN([_AM_SET_OPTIONS], -[m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) - -# _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) -# ------------------------------------------- -# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. -AC_DEFUN([_AM_IF_OPTION], -[m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) - -# Check to make sure that the build environment is sane. -*- Autoconf -*- - -# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005, 2008 -# Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 5 - -# AM_SANITY_CHECK -# --------------- -AC_DEFUN([AM_SANITY_CHECK], -[AC_MSG_CHECKING([whether build environment is sane]) -# Just in case -sleep 1 -echo timestamp > conftest.file -# Reject unsafe characters in $srcdir or the absolute working directory -# name. Accept space and tab only in the latter. -am_lf=' -' -case `pwd` in - *[[\\\"\#\$\&\'\`$am_lf]]*) - AC_MSG_ERROR([unsafe absolute working directory name]);; -esac -case $srcdir in - *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) - AC_MSG_ERROR([unsafe srcdir value: `$srcdir']);; -esac - -# Do `set' in a subshell so we don't clobber the current shell's -# arguments. Must try -L first in case configure is actually a -# symlink; some systems play weird games with the mod time of symlinks -# (eg FreeBSD returns the mod time of the symlink's containing -# directory). -if ( - set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` - if test "$[*]" = "X"; then - # -L didn't work. - set X `ls -t "$srcdir/configure" conftest.file` - fi - rm -f conftest.file - if test "$[*]" != "X $srcdir/configure conftest.file" \ - && test "$[*]" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken -alias in your environment]) - fi - - test "$[2]" = conftest.file - ) -then - # Ok. - : -else - AC_MSG_ERROR([newly created file is older than distributed files! -Check your system clock]) -fi -AC_MSG_RESULT(yes)]) - -# Copyright (C) 2001, 2003, 2005, 2011 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 1 - -# AM_PROG_INSTALL_STRIP -# --------------------- -# One issue with vendor `install' (even GNU) is that you can't -# specify the program used to strip binaries. This is especially -# annoying in cross-compiling environments, where the build's strip -# is unlikely to handle the host's binaries. -# Fortunately install-sh will honor a STRIPPROG variable, so we -# always use install-sh in `make install-strip', and initialize -# STRIPPROG with the value of the STRIP variable (set by the user). -AC_DEFUN([AM_PROG_INSTALL_STRIP], -[AC_REQUIRE([AM_PROG_INSTALL_SH])dnl -# Installed binaries are usually stripped using `strip' when the user -# run `make install-strip'. However `strip' might not be the right -# tool to use in cross-compilation environments, therefore Automake -# will honor the `STRIP' environment variable to overrule this program. -dnl Don't test for $cross_compiling = yes, because it might be `maybe'. -if test "$cross_compiling" != no; then - AC_CHECK_TOOL([STRIP], [strip], :) -fi -INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" -AC_SUBST([INSTALL_STRIP_PROGRAM])]) - -# Copyright (C) 2006, 2008, 2010 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 3 - -# _AM_SUBST_NOTMAKE(VARIABLE) -# --------------------------- -# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. -# This macro is traced by Automake. -AC_DEFUN([_AM_SUBST_NOTMAKE]) - -# AM_SUBST_NOTMAKE(VARIABLE) -# -------------------------- -# Public sister of _AM_SUBST_NOTMAKE. -AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) - -# Check how to create a tarball. -*- Autoconf -*- - -# Copyright (C) 2004, 2005, 2012 Free Software Foundation, Inc. -# -# This file is free software; the Free Software Foundation -# gives unlimited permission to copy and/or distribute it, -# with or without modifications, as long as this notice is preserved. - -# serial 2 - -# _AM_PROG_TAR(FORMAT) -# -------------------- -# Check how to create a tarball in format FORMAT. -# FORMAT should be one of `v7', `ustar', or `pax'. -# -# Substitute a variable $(am__tar) that is a command -# writing to stdout a FORMAT-tarball containing the directory -# $tardir. -# tardir=directory && $(am__tar) > result.tar -# -# Substitute a variable $(am__untar) that extract such -# a tarball read from stdin. -# $(am__untar) < result.tar -AC_DEFUN([_AM_PROG_TAR], -[# Always define AMTAR for backward compatibility. Yes, it's still used -# in the wild :-( We should find a proper way to deprecate it ... -AC_SUBST([AMTAR], ['$${TAR-tar}']) -m4_if([$1], [v7], - [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], - [m4_case([$1], [ustar],, [pax],, - [m4_fatal([Unknown tar format])]) -AC_MSG_CHECKING([how to create a $1 tar archive]) -# Loop over all known methods to create a tar archive until one works. -_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' -_am_tools=${am_cv_prog_tar_$1-$_am_tools} -# Do not fold the above two line into one, because Tru64 sh and -# Solaris sh will not grok spaces in the rhs of `-'. -for _am_tool in $_am_tools -do - case $_am_tool in - gnutar) - for _am_tar in tar gnutar gtar; - do - AM_RUN_LOG([$_am_tar --version]) && break - done - am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' - am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' - am__untar="$_am_tar -xf -" - ;; - plaintar) - # Must skip GNU tar: if it does not support --format= it doesn't create - # ustar tarball either. - (tar --version) >/dev/null 2>&1 && continue - am__tar='tar chf - "$$tardir"' - am__tar_='tar chf - "$tardir"' - am__untar='tar xf -' - ;; - pax) - am__tar='pax -L -x $1 -w "$$tardir"' - am__tar_='pax -L -x $1 -w "$tardir"' - am__untar='pax -r' - ;; - cpio) - am__tar='find "$$tardir" -print | cpio -o -H $1 -L' - am__tar_='find "$tardir" -print | cpio -o -H $1 -L' - am__untar='cpio -i -H $1 -d' - ;; - none) - am__tar=false - am__tar_=false - am__untar=false - ;; - esac - - # If the value was cached, stop now. We just wanted to have am__tar - # and am__untar set. - test -n "${am_cv_prog_tar_$1}" && break - - # tar/untar a dummy directory, and stop if the command works - rm -rf conftest.dir - mkdir conftest.dir - echo GrepMe > conftest.dir/file - AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) - rm -rf conftest.dir - if test -s conftest.tar; then - AM_RUN_LOG([$am__untar /dev/null 2>&1 && break - fi -done -rm -rf conftest.dir - -AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) -AC_MSG_RESULT([$am_cv_prog_tar_$1])]) -AC_SUBST([am__tar]) -AC_SUBST([am__untar]) -]) # _AM_PROG_TAR - -m4_include([config/libtool.m4]) -m4_include([config/ltoptions.m4]) -m4_include([config/ltsugar.m4]) -m4_include([config/ltversion.m4]) -m4_include([config/lt~obsolete.m4]) -m4_include([acinclude.m4]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/alloc.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/alloc.c deleted file mode 100644 index 7070afb..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/alloc.c +++ /dev/null @@ -1,156 +0,0 @@ -/* alloc.c -- Memory allocation without mmap. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* Allocation routines to use on systems that do not support anonymous - mmap. This implementation just uses malloc, which means that the - backtrace functions may not be safely invoked from a signal - handler. */ - -/* Allocate memory like malloc. If ERROR_CALLBACK is NULL, don't - report an error. */ - -void * -backtrace_alloc (struct backtrace_state *state ATTRIBUTE_UNUSED, - size_t size, backtrace_error_callback error_callback, - void *data) -{ - void *ret; - - ret = malloc (size); - if (ret == NULL) - { - if (error_callback) - error_callback (data, "malloc", errno); - } - return ret; -} - -/* Free memory. */ - -void -backtrace_free (struct backtrace_state *state ATTRIBUTE_UNUSED, - void *p, size_t size ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data ATTRIBUTE_UNUSED) -{ - free (p); -} - -/* Grow VEC by SIZE bytes. */ - -void * -backtrace_vector_grow (struct backtrace_state *state ATTRIBUTE_UNUSED, - size_t size, backtrace_error_callback error_callback, - void *data, struct backtrace_vector *vec) -{ - void *ret; - - if (size > vec->alc) - { - size_t alc; - void *base; - - if (vec->size == 0) - alc = 32 * size; - else if (vec->size >= 4096) - alc = vec->size + 4096; - else - alc = 2 * vec->size; - - if (alc < vec->size + size) - alc = vec->size + size; - - base = realloc (vec->base, alc); - if (base == NULL) - { - error_callback (data, "realloc", errno); - return NULL; - } - - vec->base = base; - vec->alc = alc - vec->size; - } - - ret = (char *) vec->base + vec->size; - vec->size += size; - vec->alc -= size; - return ret; -} - -/* Finish the current allocation on VEC. */ - -void * -backtrace_vector_finish (struct backtrace_state *state, - struct backtrace_vector *vec, - backtrace_error_callback error_callback, - void *data) -{ - void *ret; - - /* With this allocator we call realloc in backtrace_vector_grow, - which means we can't easily reuse the memory here. So just - release it. */ - if (!backtrace_vector_release (state, vec, error_callback, data)) - return NULL; - ret = vec->base; - vec->base = NULL; - vec->size = 0; - vec->alc = 0; - return ret; -} - -/* Release any extra space allocated for VEC. */ - -int -backtrace_vector_release (struct backtrace_state *state ATTRIBUTE_UNUSED, - struct backtrace_vector *vec, - backtrace_error_callback error_callback, - void *data) -{ - vec->base = realloc (vec->base, vec->size); - if (vec->base == NULL) - { - error_callback (data, "realloc", errno); - return 0; - } - vec->alc = 0; - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/atomic.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/atomic.c deleted file mode 100644 index 5ab1600..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/atomic.c +++ /dev/null @@ -1,113 +0,0 @@ -/* atomic.c -- Support for atomic functions if not present. - Copyright (C) 2013-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include - -#include "backtrace.h" -#include "backtrace-supported.h" -#include "internal.h" - -/* This file holds implementations of the atomic functions that are - used if the host compiler has the sync functions but not the atomic - functions, as is true of versions of GCC before 4.7. */ - -#if !defined (HAVE_ATOMIC_FUNCTIONS) && defined (HAVE_SYNC_FUNCTIONS) - -/* Do an atomic load of a pointer. */ - -void * -backtrace_atomic_load_pointer (void *arg) -{ - void **pp; - void *p; - - pp = (void **) arg; - p = *pp; - while (!__sync_bool_compare_and_swap (pp, p, p)) - p = *pp; - return p; -} - -/* Do an atomic load of an int. */ - -int -backtrace_atomic_load_int (int *p) -{ - int i; - - i = *p; - while (!__sync_bool_compare_and_swap (p, i, i)) - i = *p; - return i; -} - -/* Do an atomic store of a pointer. */ - -void -backtrace_atomic_store_pointer (void *arg, void *p) -{ - void **pp; - void *old; - - pp = (void **) arg; - old = *pp; - while (!__sync_bool_compare_and_swap (pp, old, p)) - old = *pp; -} - -/* Do an atomic store of a size_t value. */ - -void -backtrace_atomic_store_size_t (size_t *p, size_t v) -{ - size_t old; - - old = *p; - while (!__sync_bool_compare_and_swap (p, old, v)) - old = *p; -} - -/* Do an atomic store of a int value. */ - -void -backtrace_atomic_store_int (int *p, int v) -{ - size_t old; - - old = *p; - while (!__sync_bool_compare_and_swap (p, old, v)) - old = *p; -} - -#endif diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace-supported.h.in b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace-supported.h.in deleted file mode 100644 index c2d03d2..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace-supported.h.in +++ /dev/null @@ -1,66 +0,0 @@ -/* backtrace-supported.h.in -- Whether stack backtrace is supported. - Copyright (C) 2012-2016 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -/* The file backtrace-supported.h.in is used by configure to generate - the file backtrace-supported.h. The file backtrace-supported.h may - be #include'd to see whether the backtrace library will be able to - get a backtrace and produce symbolic information. */ - - -/* BACKTRACE_SUPPORTED will be #define'd as 1 if the backtrace library - should work, 0 if it will not. Libraries may #include this to make - other arrangements. */ - -#define BACKTRACE_SUPPORTED @BACKTRACE_SUPPORTED@ - -/* BACKTRACE_USES_MALLOC will be #define'd as 1 if the backtrace - library will call malloc as it works, 0 if it will call mmap - instead. This may be used to determine whether it is safe to call - the backtrace functions from a signal handler. In general this - only applies to calls like backtrace and backtrace_pcinfo. It does - not apply to backtrace_simple, which never calls malloc. It does - not apply to backtrace_print, which always calls fprintf and - therefore malloc. */ - -#define BACKTRACE_USES_MALLOC @BACKTRACE_USES_MALLOC@ - -/* BACKTRACE_SUPPORTS_THREADS will be #define'd as 1 if the backtrace - library is configured with threading support, 0 if not. If this is - 0, the threaded parameter to backtrace_create_state must be passed - as 0. */ - -#define BACKTRACE_SUPPORTS_THREADS @BACKTRACE_SUPPORTS_THREADS@ - -/* BACKTRACE_SUPPORTS_DATA will be #defined'd as 1 if the backtrace_syminfo - will work for variables. It will always work for functions. */ - -#define BACKTRACE_SUPPORTS_DATA @BACKTRACE_SUPPORTS_DATA@ diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.c deleted file mode 100644 index f8e3dc5..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.c +++ /dev/null @@ -1,129 +0,0 @@ -/* backtrace.c -- Entry point for stack backtrace library. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include - -#include "unwind.h" -#include "backtrace.h" -#include "internal.h" - -/* The main backtrace_full routine. */ - -/* Data passed through _Unwind_Backtrace. */ - -struct backtrace_data -{ - /* Number of frames to skip. */ - int skip; - /* Library state. */ - struct backtrace_state *state; - /* Callback routine. */ - backtrace_full_callback callback; - /* Error callback routine. */ - backtrace_error_callback error_callback; - /* Data to pass to callback routines. */ - void *data; - /* Value to return from backtrace_full. */ - int ret; - /* Whether there is any memory available. */ - int can_alloc; -}; - -/* Unwind library callback routine. This is passed to - _Unwind_Backtrace. */ - -static _Unwind_Reason_Code -unwind (struct _Unwind_Context *context, void *vdata) -{ - struct backtrace_data *bdata = (struct backtrace_data *) vdata; - uintptr_t pc; - int ip_before_insn = 0; - -#ifdef HAVE_GETIPINFO - pc = _Unwind_GetIPInfo (context, &ip_before_insn); -#else - pc = _Unwind_GetIP (context); -#endif - - if (bdata->skip > 0) - { - --bdata->skip; - return _URC_NO_REASON; - } - - if (!ip_before_insn) - --pc; - - if (!bdata->can_alloc) - bdata->ret = bdata->callback (bdata->data, pc, NULL, 0, NULL); - else - bdata->ret = backtrace_pcinfo (bdata->state, pc, bdata->callback, - bdata->error_callback, bdata->data); - if (bdata->ret != 0) - return _URC_END_OF_STACK; - - return _URC_NO_REASON; -} - -/* Get a stack backtrace. */ - -int -backtrace_full (struct backtrace_state *state, int skip, - backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data) -{ - struct backtrace_data bdata; - void *p; - - bdata.skip = skip + 1; - bdata.state = state; - bdata.callback = callback; - bdata.error_callback = error_callback; - bdata.data = data; - bdata.ret = 0; - - /* If we can't allocate any memory at all, don't try to produce - file/line information. */ - p = backtrace_alloc (state, 4096, NULL, NULL); - if (p == NULL) - bdata.can_alloc = 0; - else - { - backtrace_free (state, p, 4096, NULL, NULL); - bdata.can_alloc = 1; - } - - _Unwind_Backtrace (unwind, &bdata); - return bdata.ret; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.h b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.h deleted file mode 100644 index 17b1019..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/backtrace.h +++ /dev/null @@ -1,182 +0,0 @@ -/* backtrace.h -- Public header file for stack backtrace library. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#ifndef BACKTRACE_H -#define BACKTRACE_H - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* The backtrace state. This struct is intentionally not defined in - the public interface. */ - -struct backtrace_state; - -/* The type of the error callback argument to backtrace functions. - This function, if not NULL, will be called for certain error cases. - The DATA argument is passed to the function that calls this one. - The MSG argument is an error message. The ERRNUM argument, if - greater than 0, holds an errno value. The MSG buffer may become - invalid after this function returns. - - As a special case, the ERRNUM argument will be passed as -1 if no - debug info can be found for the executable, but the function - requires debug info (e.g., backtrace_full, backtrace_pcinfo). The - MSG in this case will be something along the lines of "no debug - info". Similarly, ERRNUM will be passed as -1 if there is no - symbol table, but the function requires a symbol table (e.g., - backtrace_syminfo). This may be used as a signal that some other - approach should be tried. */ - -typedef void (*backtrace_error_callback) (void *data, const char *msg, - int errnum); - -/* Create state information for the backtrace routines. This must be - called before any of the other routines, and its return value must - be passed to all of the other routines. FILENAME is the path name - of the executable file; if it is NULL the library will try - system-specific path names. If not NULL, FILENAME must point to a - permanent buffer. If THREADED is non-zero the state may be - accessed by multiple threads simultaneously, and the library will - use appropriate atomic operations. If THREADED is zero the state - may only be accessed by one thread at a time. This returns a state - pointer on success, NULL on error. If an error occurs, this will - call the ERROR_CALLBACK routine. */ - -extern struct backtrace_state *backtrace_create_state ( - const char *filename, int threaded, - backtrace_error_callback error_callback, void *data); - -/* The type of the callback argument to the backtrace_full function. - DATA is the argument passed to backtrace_full. PC is the program - counter. FILENAME is the name of the file containing PC, or NULL - if not available. LINENO is the line number in FILENAME containing - PC, or 0 if not available. FUNCTION is the name of the function - containing PC, or NULL if not available. This should return 0 to - continuing tracing. The FILENAME and FUNCTION buffers may become - invalid after this function returns. */ - -typedef int (*backtrace_full_callback) (void *data, uintptr_t pc, - const char *filename, int lineno, - const char *function); - -/* Get a full stack backtrace. SKIP is the number of frames to skip; - passing 0 will start the trace with the function calling - backtrace_full. DATA is passed to the callback routine. If any - call to CALLBACK returns a non-zero value, the stack backtrace - stops, and backtrace returns that value; this may be used to limit - the number of stack frames desired. If all calls to CALLBACK - return 0, backtrace returns 0. The backtrace_full function will - make at least one call to either CALLBACK or ERROR_CALLBACK. This - function requires debug info for the executable. */ - -extern int backtrace_full (struct backtrace_state *state, int skip, - backtrace_full_callback callback, - backtrace_error_callback error_callback, - void *data); - -/* The type of the callback argument to the backtrace_simple function. - DATA is the argument passed to simple_backtrace. PC is the program - counter. This should return 0 to continue tracing. */ - -typedef int (*backtrace_simple_callback) (void *data, uintptr_t pc); - -/* Get a simple backtrace. SKIP is the number of frames to skip, as - in backtrace. DATA is passed to the callback routine. If any call - to CALLBACK returns a non-zero value, the stack backtrace stops, - and backtrace_simple returns that value. Otherwise - backtrace_simple returns 0. The backtrace_simple function will - make at least one call to either CALLBACK or ERROR_CALLBACK. This - function does not require any debug info for the executable. */ - -extern int backtrace_simple (struct backtrace_state *state, int skip, - backtrace_simple_callback callback, - backtrace_error_callback error_callback, - void *data); - -/* Print the current backtrace in a user readable format to a FILE. - SKIP is the number of frames to skip, as in backtrace_full. Any - error messages are printed to stderr. This function requires debug - info for the executable. */ - -extern void backtrace_print (struct backtrace_state *state, int skip, FILE *); - -/* Given PC, a program counter in the current program, call the - callback function with filename, line number, and function name - information. This will normally call the callback function exactly - once. However, if the PC happens to describe an inlined call, and - the debugging information contains the necessary information, then - this may call the callback function multiple times. This will make - at least one call to either CALLBACK or ERROR_CALLBACK. This - returns the first non-zero value returned by CALLBACK, or 0. */ - -extern int backtrace_pcinfo (struct backtrace_state *state, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback, - void *data); - -/* The type of the callback argument to backtrace_syminfo. DATA and - PC are the arguments passed to backtrace_syminfo. SYMNAME is the - name of the symbol for the corresponding code. SYMVAL is the - value and SYMSIZE is the size of the symbol. SYMNAME will be NULL - if no error occurred but the symbol could not be found. */ - -typedef void (*backtrace_syminfo_callback) (void *data, uintptr_t pc, - const char *symname, - uintptr_t symval, - uintptr_t symsize); - -/* Given ADDR, an address or program counter in the current program, - call the callback information with the symbol name and value - describing the function or variable in which ADDR may be found. - This will call either CALLBACK or ERROR_CALLBACK exactly once. - This returns 1 on success, 0 on failure. This function requires - the symbol table but does not require the debug info. Note that if - the symbol table is present but ADDR could not be found in the - table, CALLBACK will be called with a NULL SYMNAME argument. - Returns 1 on success, 0 on error. */ - -extern int backtrace_syminfo (struct backtrace_state *state, uintptr_t addr, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback, - void *data); - -#ifdef __cplusplus -} /* End extern "C". */ -#endif - -#endif diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/btest.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/btest.c deleted file mode 100644 index 1348d54..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/btest.c +++ /dev/null @@ -1,500 +0,0 @@ -/* btest.c -- Test for libbacktrace library - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -/* This program tests the externally visible interfaces of the - libbacktrace library. */ - -#include -#include -#include -#include -#include - -#include "filenames.h" - -#include "backtrace.h" -#include "backtrace-supported.h" - -#include "testlib.h" - -/* Test the backtrace function with non-inlined functions. */ - -static int test1 (void) __attribute__ ((noinline, unused)); -static int f2 (int) __attribute__ ((noinline)); -static int f3 (int, int) __attribute__ ((noinline)); - -static int -test1 (void) -{ - /* Returning a value here and elsewhere avoids a tailcall which - would mess up the backtrace. */ - return f2 (__LINE__) + 1; -} - -static int -f2 (int f1line) -{ - return f3 (f1line, __LINE__) + 2; -} - -static int -f3 (int f1line, int f2line) -{ - struct info all[20]; - struct bdata data; - int f3line; - int i; - - data.all = &all[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_full (state, 0, callback_one, error_callback_one, &data); - - if (i != 0) - { - fprintf (stderr, "test1: unexpected return value %d\n", i); - data.failed = 1; - } - - if (data.index < 3) - { - fprintf (stderr, - "test1: not enough frames; got %zu, expected at least 3\n", - data.index); - data.failed = 1; - } - - check ("test1", 0, all, f3line, "f3", "btest.c", &data.failed); - check ("test1", 1, all, f2line, "f2", "btest.c", &data.failed); - check ("test1", 2, all, f1line, "test1", "btest.c", &data.failed); - - printf ("%s: backtrace_full noinline\n", data.failed ? "FAIL" : "PASS"); - - if (data.failed) - ++failures; - - return failures; -} - -/* Test the backtrace function with inlined functions. */ - -static inline int test2 (void) __attribute__ ((always_inline, unused)); -static inline int f12 (int) __attribute__ ((always_inline)); -static inline int f13 (int, int) __attribute__ ((always_inline)); - -static inline int -test2 (void) -{ - return f12 (__LINE__) + 1; -} - -static inline int -f12 (int f1line) -{ - return f13 (f1line, __LINE__) + 2; -} - -static inline int -f13 (int f1line, int f2line) -{ - struct info all[20]; - struct bdata data; - int f3line; - int i; - - data.all = &all[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_full (state, 0, callback_one, error_callback_one, &data); - - if (i != 0) - { - fprintf (stderr, "test2: unexpected return value %d\n", i); - data.failed = 1; - } - - check ("test2", 0, all, f3line, "f13", "btest.c", &data.failed); - check ("test2", 1, all, f2line, "f12", "btest.c", &data.failed); - check ("test2", 2, all, f1line, "test2", "btest.c", &data.failed); - - printf ("%s: backtrace_full inline\n", data.failed ? "FAIL" : "PASS"); - - if (data.failed) - ++failures; - - return failures; -} - -/* Test the backtrace_simple function with non-inlined functions. */ - -static int test3 (void) __attribute__ ((noinline, unused)); -static int f22 (int) __attribute__ ((noinline)); -static int f23 (int, int) __attribute__ ((noinline)); - -static int -test3 (void) -{ - return f22 (__LINE__) + 1; -} - -static int -f22 (int f1line) -{ - return f23 (f1line, __LINE__) + 2; -} - -static int -f23 (int f1line, int f2line) -{ - uintptr_t addrs[20]; - struct sdata data; - int f3line; - int i; - - data.addrs = &addrs[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_simple (state, 0, callback_two, error_callback_two, &data); - - if (i != 0) - { - fprintf (stderr, "test3: unexpected return value %d\n", i); - data.failed = 1; - } - - if (!data.failed) - { - struct info all[20]; - struct bdata bdata; - int j; - - bdata.all = &all[0]; - bdata.index = 0; - bdata.max = 20; - bdata.failed = 0; - - for (j = 0; j < 3; ++j) - { - i = backtrace_pcinfo (state, addrs[j], callback_one, - error_callback_one, &bdata); - if (i != 0) - { - fprintf (stderr, - ("test3: unexpected return value " - "from backtrace_pcinfo %d\n"), - i); - bdata.failed = 1; - } - if (!bdata.failed && bdata.index != (size_t) (j + 1)) - { - fprintf (stderr, - ("wrong number of calls from backtrace_pcinfo " - "got %u expected %d\n"), - (unsigned int) bdata.index, j + 1); - bdata.failed = 1; - } - } - - check ("test3", 0, all, f3line, "f23", "btest.c", &bdata.failed); - check ("test3", 1, all, f2line, "f22", "btest.c", &bdata.failed); - check ("test3", 2, all, f1line, "test3", "btest.c", &bdata.failed); - - if (bdata.failed) - data.failed = 1; - - for (j = 0; j < 3; ++j) - { - struct symdata symdata; - - symdata.name = NULL; - symdata.val = 0; - symdata.size = 0; - symdata.failed = 0; - - i = backtrace_syminfo (state, addrs[j], callback_three, - error_callback_three, &symdata); - if (i == 0) - { - fprintf (stderr, - ("test3: [%d]: unexpected return value " - "from backtrace_syminfo %d\n"), - j, i); - symdata.failed = 1; - } - - if (!symdata.failed) - { - const char *expected; - - switch (j) - { - case 0: - expected = "f23"; - break; - case 1: - expected = "f22"; - break; - case 2: - expected = "test3"; - break; - default: - assert (0); - } - - if (symdata.name == NULL) - { - fprintf (stderr, "test3: [%d]: NULL syminfo name\n", j); - symdata.failed = 1; - } - /* Use strncmp, not strcmp, because GCC might create a - clone. */ - else if (strncmp (symdata.name, expected, strlen (expected)) - != 0) - { - fprintf (stderr, - ("test3: [%d]: unexpected syminfo name " - "got %s expected %s\n"), - j, symdata.name, expected); - symdata.failed = 1; - } - } - - if (symdata.failed) - data.failed = 1; - } - } - - printf ("%s: backtrace_simple noinline\n", data.failed ? "FAIL" : "PASS"); - - if (data.failed) - ++failures; - - return failures; -} - -/* Test the backtrace_simple function with inlined functions. */ - -static inline int test4 (void) __attribute__ ((always_inline, unused)); -static inline int f32 (int) __attribute__ ((always_inline)); -static inline int f33 (int, int) __attribute__ ((always_inline)); - -static inline int -test4 (void) -{ - return f32 (__LINE__) + 1; -} - -static inline int -f32 (int f1line) -{ - return f33 (f1line, __LINE__) + 2; -} - -static inline int -f33 (int f1line, int f2line) -{ - uintptr_t addrs[20]; - struct sdata data; - int f3line; - int i; - - data.addrs = &addrs[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_simple (state, 0, callback_two, error_callback_two, &data); - - if (i != 0) - { - fprintf (stderr, "test3: unexpected return value %d\n", i); - data.failed = 1; - } - - if (!data.failed) - { - struct info all[20]; - struct bdata bdata; - - bdata.all = &all[0]; - bdata.index = 0; - bdata.max = 20; - bdata.failed = 0; - - i = backtrace_pcinfo (state, addrs[0], callback_one, error_callback_one, - &bdata); - if (i != 0) - { - fprintf (stderr, - ("test4: unexpected return value " - "from backtrace_pcinfo %d\n"), - i); - bdata.failed = 1; - } - - check ("test4", 0, all, f3line, "f33", "btest.c", &bdata.failed); - check ("test4", 1, all, f2line, "f32", "btest.c", &bdata.failed); - check ("test4", 2, all, f1line, "test4", "btest.c", &bdata.failed); - - if (bdata.failed) - data.failed = 1; - } - - printf ("%s: backtrace_simple inline\n", data.failed ? "FAIL" : "PASS"); - - if (data.failed) - ++failures; - - return failures; -} - -static int test5 (void) __attribute__ ((unused)); - -int global = 1; - -static int -test5 (void) -{ - struct symdata symdata; - int i; - uintptr_t addr = (uintptr_t) &global; - - if (sizeof (global) > 1) - addr += 1; - - symdata.name = NULL; - symdata.val = 0; - symdata.size = 0; - symdata.failed = 0; - - i = backtrace_syminfo (state, addr, callback_three, - error_callback_three, &symdata); - if (i == 0) - { - fprintf (stderr, - "test5: unexpected return value from backtrace_syminfo %d\n", - i); - symdata.failed = 1; - } - - if (!symdata.failed) - { - if (symdata.name == NULL) - { - fprintf (stderr, "test5: NULL syminfo name\n"); - symdata.failed = 1; - } - else if (strcmp (symdata.name, "global") != 0) - { - fprintf (stderr, - "test5: unexpected syminfo name got %s expected %s\n", - symdata.name, "global"); - symdata.failed = 1; - } - else if (symdata.val != (uintptr_t) &global) - { - fprintf (stderr, - "test5: unexpected syminfo value got %lx expected %lx\n", - (unsigned long) symdata.val, - (unsigned long) (uintptr_t) &global); - symdata.failed = 1; - } - else if (symdata.size != sizeof (global)) - { - fprintf (stderr, - "test5: unexpected syminfo size got %lx expected %lx\n", - (unsigned long) symdata.size, - (unsigned long) sizeof (global)); - symdata.failed = 1; - } - } - - printf ("%s: backtrace_syminfo variable\n", - symdata.failed ? "FAIL" : "PASS"); - - if (symdata.failed) - ++failures; - - return failures; -} - -/* Check that are no files left open. */ - -static void -check_open_files (void) -{ - int i; - - for (i = 3; i < 10; i++) - { - if (close (i) == 0) - { - fprintf (stderr, - "ERROR: descriptor %d still open after tests complete\n", - i); - ++failures; - } - } -} - -/* Run all the tests. */ - -int -main (int argc ATTRIBUTE_UNUSED, char **argv) -{ - state = backtrace_create_state (argv[0], BACKTRACE_SUPPORTS_THREADS, - error_callback_create, NULL); - -#if BACKTRACE_SUPPORTED - test1 (); - test2 (); - test3 (); - test4 (); -#if BACKTRACE_SUPPORTS_DATA - test5 (); -#endif -#endif - - check_open_files (); - - exit (failures ? EXIT_FAILURE : EXIT_SUCCESS); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.guess b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.guess deleted file mode 100755 index d622a44..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.guess +++ /dev/null @@ -1,1530 +0,0 @@ -#! /bin/sh -# Attempt to guess a canonical system name. -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, -# 2011, 2012 Free Software Foundation, Inc. - -timestamp='2012-02-10' - -# This file is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, see . -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - - -# Originally written by Per Bothner. Please send patches (context -# diff format) to and include a ChangeLog -# entry. -# -# This script attempts to guess a canonical system name similar to -# config.sub. If it succeeds, it prints the system name on stdout, and -# exits with 0. Otherwise, it exits with 1. -# -# You can get the latest version of this script from: -# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD - -me=`echo "$0" | sed -e 's,.*/,,'` - -usage="\ -Usage: $0 [OPTION] - -Output the configuration name of the system \`$me' is run on. - -Operation modes: - -h, --help print this help, then exit - -t, --time-stamp print date of last modification, then exit - -v, --version print version number, then exit - -Report bugs and patches to ." - -version="\ -GNU config.guess ($timestamp) - -Originally written by Per Bothner. -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, -2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 -Free Software Foundation, Inc. - -This is free software; see the source for copying conditions. There is NO -warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - -help=" -Try \`$me --help' for more information." - -# Parse command line -while test $# -gt 0 ; do - case $1 in - --time-stamp | --time* | -t ) - echo "$timestamp" ; exit ;; - --version | -v ) - echo "$version" ; exit ;; - --help | --h* | -h ) - echo "$usage"; exit ;; - -- ) # Stop option processing - shift; break ;; - - ) # Use stdin as input. - break ;; - -* ) - echo "$me: invalid option $1$help" >&2 - exit 1 ;; - * ) - break ;; - esac -done - -if test $# != 0; then - echo "$me: too many arguments$help" >&2 - exit 1 -fi - -trap 'exit 1' 1 2 15 - -# CC_FOR_BUILD -- compiler used by this script. Note that the use of a -# compiler to aid in system detection is discouraged as it requires -# temporary files to be created and, as you can see below, it is a -# headache to deal with in a portable fashion. - -# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still -# use `HOST_CC' if defined, but it is deprecated. - -# Portable tmp directory creation inspired by the Autoconf team. - -set_cc_for_build=' -trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; -trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; -: ${TMPDIR=/tmp} ; - { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || - { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || - { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || - { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; -dummy=$tmp/dummy ; -tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; -case $CC_FOR_BUILD,$HOST_CC,$CC in - ,,) echo "int x;" > $dummy.c ; - for c in cc gcc c89 c99 ; do - if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then - CC_FOR_BUILD="$c"; break ; - fi ; - done ; - if test x"$CC_FOR_BUILD" = x ; then - CC_FOR_BUILD=no_compiler_found ; - fi - ;; - ,,*) CC_FOR_BUILD=$CC ;; - ,*,*) CC_FOR_BUILD=$HOST_CC ;; -esac ; set_cc_for_build= ;' - -# This is needed to find uname on a Pyramid OSx when run in the BSD universe. -# (ghazi@noc.rutgers.edu 1994-08-24) -if (test -f /.attbin/uname) >/dev/null 2>&1 ; then - PATH=$PATH:/.attbin ; export PATH -fi - -UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown -UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown -UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown -UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown - -# Note: order is significant - the case branches are not exclusive. - -case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in - *:NetBSD:*:*) - # NetBSD (nbsd) targets should (where applicable) match one or - # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, - # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently - # switched to ELF, *-*-netbsd* would select the old - # object file format. This provides both forward - # compatibility and a consistent mechanism for selecting the - # object file format. - # - # Note: NetBSD doesn't particularly care about the vendor - # portion of the name. We always set it to "unknown". - sysctl="sysctl -n hw.machine_arch" - UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ - /usr/sbin/$sysctl 2>/dev/null || echo unknown)` - case "${UNAME_MACHINE_ARCH}" in - armeb) machine=armeb-unknown ;; - arm*) machine=arm-unknown ;; - sh3el) machine=shl-unknown ;; - sh3eb) machine=sh-unknown ;; - sh5el) machine=sh5le-unknown ;; - *) machine=${UNAME_MACHINE_ARCH}-unknown ;; - esac - # The Operating System including object format, if it has switched - # to ELF recently, or will in the future. - case "${UNAME_MACHINE_ARCH}" in - arm*|i386|m68k|ns32k|sh3*|sparc|vax) - eval $set_cc_for_build - if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ - | grep -q __ELF__ - then - # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). - # Return netbsd for either. FIX? - os=netbsd - else - os=netbsdelf - fi - ;; - *) - os=netbsd - ;; - esac - # The OS release - # Debian GNU/NetBSD machines have a different userland, and - # thus, need a distinct triplet. However, they do not need - # kernel version information, so it can be replaced with a - # suitable tag, in the style of linux-gnu. - case "${UNAME_VERSION}" in - Debian*) - release='-gnu' - ;; - *) - release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` - ;; - esac - # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: - # contains redundant information, the shorter form: - # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. - echo "${machine}-${os}${release}" - exit ;; - *:OpenBSD:*:*) - UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` - echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} - exit ;; - *:ekkoBSD:*:*) - echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} - exit ;; - *:SolidBSD:*:*) - echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} - exit ;; - macppc:MirBSD:*:*) - echo powerpc-unknown-mirbsd${UNAME_RELEASE} - exit ;; - *:MirBSD:*:*) - echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} - exit ;; - alpha:OSF1:*:*) - case $UNAME_RELEASE in - *4.0) - UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` - ;; - *5.*) - UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` - ;; - esac - # According to Compaq, /usr/sbin/psrinfo has been available on - # OSF/1 and Tru64 systems produced since 1995. I hope that - # covers most systems running today. This code pipes the CPU - # types through head -n 1, so we only detect the type of CPU 0. - ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` - case "$ALPHA_CPU_TYPE" in - "EV4 (21064)") - UNAME_MACHINE="alpha" ;; - "EV4.5 (21064)") - UNAME_MACHINE="alpha" ;; - "LCA4 (21066/21068)") - UNAME_MACHINE="alpha" ;; - "EV5 (21164)") - UNAME_MACHINE="alphaev5" ;; - "EV5.6 (21164A)") - UNAME_MACHINE="alphaev56" ;; - "EV5.6 (21164PC)") - UNAME_MACHINE="alphapca56" ;; - "EV5.7 (21164PC)") - UNAME_MACHINE="alphapca57" ;; - "EV6 (21264)") - UNAME_MACHINE="alphaev6" ;; - "EV6.7 (21264A)") - UNAME_MACHINE="alphaev67" ;; - "EV6.8CB (21264C)") - UNAME_MACHINE="alphaev68" ;; - "EV6.8AL (21264B)") - UNAME_MACHINE="alphaev68" ;; - "EV6.8CX (21264D)") - UNAME_MACHINE="alphaev68" ;; - "EV6.9A (21264/EV69A)") - UNAME_MACHINE="alphaev69" ;; - "EV7 (21364)") - UNAME_MACHINE="alphaev7" ;; - "EV7.9 (21364A)") - UNAME_MACHINE="alphaev79" ;; - esac - # A Pn.n version is a patched version. - # A Vn.n version is a released version. - # A Tn.n version is a released field test version. - # A Xn.n version is an unreleased experimental baselevel. - # 1.2 uses "1.2" for uname -r. - echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - # Reset EXIT trap before exiting to avoid spurious non-zero exit code. - exitcode=$? - trap '' 0 - exit $exitcode ;; - Alpha\ *:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # Should we change UNAME_MACHINE based on the output of uname instead - # of the specific Alpha model? - echo alpha-pc-interix - exit ;; - 21064:Windows_NT:50:3) - echo alpha-dec-winnt3.5 - exit ;; - Amiga*:UNIX_System_V:4.0:*) - echo m68k-unknown-sysv4 - exit ;; - *:[Aa]miga[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-amigaos - exit ;; - *:[Mm]orph[Oo][Ss]:*:*) - echo ${UNAME_MACHINE}-unknown-morphos - exit ;; - *:OS/390:*:*) - echo i370-ibm-openedition - exit ;; - *:z/VM:*:*) - echo s390-ibm-zvmoe - exit ;; - *:OS400:*:*) - echo powerpc-ibm-os400 - exit ;; - arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) - echo arm-acorn-riscix${UNAME_RELEASE} - exit ;; - arm:riscos:*:*|arm:RISCOS:*:*) - echo arm-unknown-riscos - exit ;; - SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) - echo hppa1.1-hitachi-hiuxmpp - exit ;; - Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) - # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. - if test "`(/bin/universe) 2>/dev/null`" = att ; then - echo pyramid-pyramid-sysv3 - else - echo pyramid-pyramid-bsd - fi - exit ;; - NILE*:*:*:dcosx) - echo pyramid-pyramid-svr4 - exit ;; - DRS?6000:unix:4.0:6*) - echo sparc-icl-nx6 - exit ;; - DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) - case `/usr/bin/uname -p` in - sparc) echo sparc-icl-nx7; exit ;; - esac ;; - s390x:SunOS:*:*) - echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4H:SunOS:5.*:*) - echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) - echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) - echo i386-pc-auroraux${UNAME_RELEASE} - exit ;; - i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) - eval $set_cc_for_build - SUN_ARCH="i386" - # If there is a compiler, see if it is configured for 64-bit objects. - # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. - # This test works for both compilers. - if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then - if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ - (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ - grep IS_64BIT_ARCH >/dev/null - then - SUN_ARCH="x86_64" - fi - fi - echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:6*:*) - # According to config.sub, this is the proper way to canonicalize - # SunOS6. Hard to guess exactly what SunOS6 will be like, but - # it's likely to be more like Solaris than SunOS4. - echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - sun4*:SunOS:*:*) - case "`/usr/bin/arch -k`" in - Series*|S4*) - UNAME_RELEASE=`uname -v` - ;; - esac - # Japanese Language versions have a version number like `4.1.3-JL'. - echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` - exit ;; - sun3*:SunOS:*:*) - echo m68k-sun-sunos${UNAME_RELEASE} - exit ;; - sun*:*:4.2BSD:*) - UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` - test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 - case "`/bin/arch`" in - sun3) - echo m68k-sun-sunos${UNAME_RELEASE} - ;; - sun4) - echo sparc-sun-sunos${UNAME_RELEASE} - ;; - esac - exit ;; - aushp:SunOS:*:*) - echo sparc-auspex-sunos${UNAME_RELEASE} - exit ;; - # The situation for MiNT is a little confusing. The machine name - # can be virtually everything (everything which is not - # "atarist" or "atariste" at least should have a processor - # > m68000). The system name ranges from "MiNT" over "FreeMiNT" - # to the lowercase version "mint" (or "freemint"). Finally - # the system name "TOS" denotes a system which is actually not - # MiNT. But MiNT is downward compatible to TOS, so this should - # be no problem. - atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) - echo m68k-atari-mint${UNAME_RELEASE} - exit ;; - milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) - echo m68k-milan-mint${UNAME_RELEASE} - exit ;; - hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) - echo m68k-hades-mint${UNAME_RELEASE} - exit ;; - *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) - echo m68k-unknown-mint${UNAME_RELEASE} - exit ;; - m68k:machten:*:*) - echo m68k-apple-machten${UNAME_RELEASE} - exit ;; - powerpc:machten:*:*) - echo powerpc-apple-machten${UNAME_RELEASE} - exit ;; - RISC*:Mach:*:*) - echo mips-dec-mach_bsd4.3 - exit ;; - RISC*:ULTRIX:*:*) - echo mips-dec-ultrix${UNAME_RELEASE} - exit ;; - VAX*:ULTRIX*:*:*) - echo vax-dec-ultrix${UNAME_RELEASE} - exit ;; - 2020:CLIX:*:* | 2430:CLIX:*:*) - echo clipper-intergraph-clix${UNAME_RELEASE} - exit ;; - mips:*:*:UMIPS | mips:*:*:RISCos) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c -#ifdef __cplusplus -#include /* for printf() prototype */ - int main (int argc, char *argv[]) { -#else - int main (argc, argv) int argc; char *argv[]; { -#endif - #if defined (host_mips) && defined (MIPSEB) - #if defined (SYSTYPE_SYSV) - printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); - #endif - #if defined (SYSTYPE_SVR4) - printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); - #endif - #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) - printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); - #endif - #endif - exit (-1); - } -EOF - $CC_FOR_BUILD -o $dummy $dummy.c && - dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && - SYSTEM_NAME=`$dummy $dummyarg` && - { echo "$SYSTEM_NAME"; exit; } - echo mips-mips-riscos${UNAME_RELEASE} - exit ;; - Motorola:PowerMAX_OS:*:*) - echo powerpc-motorola-powermax - exit ;; - Motorola:*:4.3:PL8-*) - echo powerpc-harris-powermax - exit ;; - Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) - echo powerpc-harris-powermax - exit ;; - Night_Hawk:Power_UNIX:*:*) - echo powerpc-harris-powerunix - exit ;; - m88k:CX/UX:7*:*) - echo m88k-harris-cxux7 - exit ;; - m88k:*:4*:R4*) - echo m88k-motorola-sysv4 - exit ;; - m88k:*:3*:R3*) - echo m88k-motorola-sysv3 - exit ;; - AViiON:dgux:*:*) - # DG/UX returns AViiON for all architectures - UNAME_PROCESSOR=`/usr/bin/uname -p` - if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] - then - if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ - [ ${TARGET_BINARY_INTERFACE}x = x ] - then - echo m88k-dg-dgux${UNAME_RELEASE} - else - echo m88k-dg-dguxbcs${UNAME_RELEASE} - fi - else - echo i586-dg-dgux${UNAME_RELEASE} - fi - exit ;; - M88*:DolphinOS:*:*) # DolphinOS (SVR3) - echo m88k-dolphin-sysv3 - exit ;; - M88*:*:R3*:*) - # Delta 88k system running SVR3 - echo m88k-motorola-sysv3 - exit ;; - XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) - echo m88k-tektronix-sysv3 - exit ;; - Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) - echo m68k-tektronix-bsd - exit ;; - *:IRIX*:*:*) - echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` - exit ;; - ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. - echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id - exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' - i*86:AIX:*:*) - echo i386-ibm-aix - exit ;; - ia64:AIX:*:*) - if [ -x /usr/bin/oslevel ] ; then - IBM_REV=`/usr/bin/oslevel` - else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} - fi - echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} - exit ;; - *:AIX:2:3) - if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #include - - main() - { - if (!__power_pc()) - exit(1); - puts("powerpc-ibm-aix3.2.5"); - exit(0); - } -EOF - if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` - then - echo "$SYSTEM_NAME" - else - echo rs6000-ibm-aix3.2.5 - fi - elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then - echo rs6000-ibm-aix3.2.4 - else - echo rs6000-ibm-aix3.2 - fi - exit ;; - *:AIX:*:[4567]) - IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` - if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then - IBM_ARCH=rs6000 - else - IBM_ARCH=powerpc - fi - if [ -x /usr/bin/oslevel ] ; then - IBM_REV=`/usr/bin/oslevel` - else - IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} - fi - echo ${IBM_ARCH}-ibm-aix${IBM_REV} - exit ;; - *:AIX:*:*) - echo rs6000-ibm-aix - exit ;; - ibmrt:4.4BSD:*|romp-ibm:BSD:*) - echo romp-ibm-bsd4.4 - exit ;; - ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and - echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to - exit ;; # report: romp-ibm BSD 4.3 - *:BOSX:*:*) - echo rs6000-bull-bosx - exit ;; - DPX/2?00:B.O.S.:*:*) - echo m68k-bull-sysv3 - exit ;; - 9000/[34]??:4.3bsd:1.*:*) - echo m68k-hp-bsd - exit ;; - hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) - echo m68k-hp-bsd4.4 - exit ;; - 9000/[34678]??:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - case "${UNAME_MACHINE}" in - 9000/31? ) HP_ARCH=m68000 ;; - 9000/[34]?? ) HP_ARCH=m68k ;; - 9000/[678][0-9][0-9]) - if [ -x /usr/bin/getconf ]; then - sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` - sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` - case "${sc_cpu_version}" in - 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 - 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 - 532) # CPU_PA_RISC2_0 - case "${sc_kernel_bits}" in - 32) HP_ARCH="hppa2.0n" ;; - 64) HP_ARCH="hppa2.0w" ;; - '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 - esac ;; - esac - fi - if [ "${HP_ARCH}" = "" ]; then - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - - #define _HPUX_SOURCE - #include - #include - - int main () - { - #if defined(_SC_KERNEL_BITS) - long bits = sysconf(_SC_KERNEL_BITS); - #endif - long cpu = sysconf (_SC_CPU_VERSION); - - switch (cpu) - { - case CPU_PA_RISC1_0: puts ("hppa1.0"); break; - case CPU_PA_RISC1_1: puts ("hppa1.1"); break; - case CPU_PA_RISC2_0: - #if defined(_SC_KERNEL_BITS) - switch (bits) - { - case 64: puts ("hppa2.0w"); break; - case 32: puts ("hppa2.0n"); break; - default: puts ("hppa2.0"); break; - } break; - #else /* !defined(_SC_KERNEL_BITS) */ - puts ("hppa2.0"); break; - #endif - default: puts ("hppa1.0"); break; - } - exit (0); - } -EOF - (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` - test -z "$HP_ARCH" && HP_ARCH=hppa - fi ;; - esac - if [ ${HP_ARCH} = "hppa2.0w" ] - then - eval $set_cc_for_build - - # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating - # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler - # generating 64-bit code. GNU and HP use different nomenclature: - # - # $ CC_FOR_BUILD=cc ./config.guess - # => hppa2.0w-hp-hpux11.23 - # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess - # => hppa64-hp-hpux11.23 - - if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | - grep -q __LP64__ - then - HP_ARCH="hppa2.0w" - else - HP_ARCH="hppa64" - fi - fi - echo ${HP_ARCH}-hp-hpux${HPUX_REV} - exit ;; - ia64:HP-UX:*:*) - HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` - echo ia64-hp-hpux${HPUX_REV} - exit ;; - 3050*:HI-UX:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #include - int - main () - { - long cpu = sysconf (_SC_CPU_VERSION); - /* The order matters, because CPU_IS_HP_MC68K erroneously returns - true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct - results, however. */ - if (CPU_IS_PA_RISC (cpu)) - { - switch (cpu) - { - case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; - case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; - case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; - default: puts ("hppa-hitachi-hiuxwe2"); break; - } - } - else if (CPU_IS_HP_MC68K (cpu)) - puts ("m68k-hitachi-hiuxwe2"); - else puts ("unknown-hitachi-hiuxwe2"); - exit (0); - } -EOF - $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && - { echo "$SYSTEM_NAME"; exit; } - echo unknown-hitachi-hiuxwe2 - exit ;; - 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) - echo hppa1.1-hp-bsd - exit ;; - 9000/8??:4.3bsd:*:*) - echo hppa1.0-hp-bsd - exit ;; - *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) - echo hppa1.0-hp-mpeix - exit ;; - hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) - echo hppa1.1-hp-osf - exit ;; - hp8??:OSF1:*:*) - echo hppa1.0-hp-osf - exit ;; - i*86:OSF1:*:*) - if [ -x /usr/sbin/sysversion ] ; then - echo ${UNAME_MACHINE}-unknown-osf1mk - else - echo ${UNAME_MACHINE}-unknown-osf1 - fi - exit ;; - parisc*:Lites*:*:*) - echo hppa1.1-hp-lites - exit ;; - C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) - echo c1-convex-bsd - exit ;; - C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) - if getsysinfo -f scalar_acc - then echo c32-convex-bsd - else echo c2-convex-bsd - fi - exit ;; - C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) - echo c34-convex-bsd - exit ;; - C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) - echo c38-convex-bsd - exit ;; - C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) - echo c4-convex-bsd - exit ;; - CRAY*Y-MP:*:*:*) - echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*[A-Z]90:*:*:*) - echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ - | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ - -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ - -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*TS:*:*:*) - echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*T3E:*:*:*) - echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - CRAY*SV1:*:*:*) - echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - *:UNICOS/mp:*:*) - echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' - exit ;; - F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) - FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` - echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; - 5000:UNIX_System_V:4.*:*) - FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` - FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` - echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" - exit ;; - i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) - echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} - exit ;; - sparc*:BSD/OS:*:*) - echo sparc-unknown-bsdi${UNAME_RELEASE} - exit ;; - *:BSD/OS:*:*) - echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} - exit ;; - *:FreeBSD:*:*) - UNAME_PROCESSOR=`/usr/bin/uname -p` - case ${UNAME_PROCESSOR} in - amd64) - echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - *) - echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; - esac - exit ;; - i*:CYGWIN*:*) - echo ${UNAME_MACHINE}-pc-cygwin - exit ;; - *:MINGW*:*) - echo ${UNAME_MACHINE}-pc-mingw32 - exit ;; - i*:MSYS*:*) - echo ${UNAME_MACHINE}-pc-msys - exit ;; - i*:windows32*:*) - # uname -m includes "-pc" on this system. - echo ${UNAME_MACHINE}-mingw32 - exit ;; - i*:PW*:*) - echo ${UNAME_MACHINE}-pc-pw32 - exit ;; - *:Interix*:*) - case ${UNAME_MACHINE} in - x86) - echo i586-pc-interix${UNAME_RELEASE} - exit ;; - authenticamd | genuineintel | EM64T) - echo x86_64-unknown-interix${UNAME_RELEASE} - exit ;; - IA64) - echo ia64-unknown-interix${UNAME_RELEASE} - exit ;; - esac ;; - [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) - echo i${UNAME_MACHINE}-pc-mks - exit ;; - 8664:Windows_NT:*) - echo x86_64-pc-mks - exit ;; - i*:Windows_NT*:* | Pentium*:Windows_NT*:*) - # How do we know it's Interix rather than the generic POSIX subsystem? - # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we - # UNAME_MACHINE based on the output of uname instead of i386? - echo i586-pc-interix - exit ;; - i*:UWIN*:*) - echo ${UNAME_MACHINE}-pc-uwin - exit ;; - amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) - echo x86_64-unknown-cygwin - exit ;; - p*:CYGWIN*:*) - echo powerpcle-unknown-cygwin - exit ;; - prep*:SunOS:5.*:*) - echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` - exit ;; - *:GNU:*:*) - # the GNU system - echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` - exit ;; - *:GNU/*:*:*) - # other systems with GNU libc and userland - echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu - exit ;; - i*86:Minix:*:*) - echo ${UNAME_MACHINE}-pc-minix - exit ;; - aarch64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - aarch64_be:Linux:*:*) - UNAME_MACHINE=aarch64_be - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - alpha:Linux:*:*) - case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in - EV5) UNAME_MACHINE=alphaev5 ;; - EV56) UNAME_MACHINE=alphaev56 ;; - PCA56) UNAME_MACHINE=alphapca56 ;; - PCA57) UNAME_MACHINE=alphapca56 ;; - EV6) UNAME_MACHINE=alphaev6 ;; - EV67) UNAME_MACHINE=alphaev67 ;; - EV68*) UNAME_MACHINE=alphaev68 ;; - esac - objdump --private-headers /bin/sh | grep -q ld.so.1 - if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi - echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} - exit ;; - arm*:Linux:*:*) - eval $set_cc_for_build - if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ - | grep -q __ARM_EABI__ - then - echo ${UNAME_MACHINE}-unknown-linux-gnu - else - if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ - | grep -q __ARM_PCS_VFP - then - echo ${UNAME_MACHINE}-unknown-linux-gnueabi - else - echo ${UNAME_MACHINE}-unknown-linux-gnueabihf - fi - fi - exit ;; - avr32*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - cris:Linux:*:*) - echo ${UNAME_MACHINE}-axis-linux-gnu - exit ;; - crisv32:Linux:*:*) - echo ${UNAME_MACHINE}-axis-linux-gnu - exit ;; - frv:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - hexagon:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - i*86:Linux:*:*) - LIBC=gnu - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #ifdef __dietlibc__ - LIBC=dietlibc - #endif -EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` - echo "${UNAME_MACHINE}-pc-linux-${LIBC}" - exit ;; - ia64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - m32r*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - m68*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - mips:Linux:*:* | mips64:Linux:*:*) - eval $set_cc_for_build - sed 's/^ //' << EOF >$dummy.c - #undef CPU - #undef ${UNAME_MACHINE} - #undef ${UNAME_MACHINE}el - #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) - CPU=${UNAME_MACHINE}el - #else - #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) - CPU=${UNAME_MACHINE} - #else - CPU= - #endif - #endif -EOF - eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` - test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } - ;; - or32:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - padre:Linux:*:*) - echo sparc-unknown-linux-gnu - exit ;; - parisc64:Linux:*:* | hppa64:Linux:*:*) - echo hppa64-unknown-linux-gnu - exit ;; - parisc:Linux:*:* | hppa:Linux:*:*) - # Look for CPU level - case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in - PA7*) echo hppa1.1-unknown-linux-gnu ;; - PA8*) echo hppa2.0-unknown-linux-gnu ;; - *) echo hppa-unknown-linux-gnu ;; - esac - exit ;; - ppc64:Linux:*:*) - echo powerpc64-unknown-linux-gnu - exit ;; - ppc:Linux:*:*) - echo powerpc-unknown-linux-gnu - exit ;; - s390:Linux:*:* | s390x:Linux:*:*) - echo ${UNAME_MACHINE}-ibm-linux - exit ;; - sh64*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - sh*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - sparc:Linux:*:* | sparc64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - tile*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - vax:Linux:*:*) - echo ${UNAME_MACHINE}-dec-linux-gnu - exit ;; - x86_64:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - xtensa*:Linux:*:*) - echo ${UNAME_MACHINE}-unknown-linux-gnu - exit ;; - i*86:DYNIX/ptx:4*:*) - # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. - # earlier versions are messed up and put the nodename in both - # sysname and nodename. - echo i386-sequent-sysv4 - exit ;; - i*86:UNIX_SV:4.2MP:2.*) - # Unixware is an offshoot of SVR4, but it has its own version - # number series starting with 2... - # I am not positive that other SVR4 systems won't match this, - # I just have to hope. -- rms. - # Use sysv4.2uw... so that sysv4* matches it. - echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} - exit ;; - i*86:OS/2:*:*) - # If we were able to find `uname', then EMX Unix compatibility - # is probably installed. - echo ${UNAME_MACHINE}-pc-os2-emx - exit ;; - i*86:XTS-300:*:STOP) - echo ${UNAME_MACHINE}-unknown-stop - exit ;; - i*86:atheos:*:*) - echo ${UNAME_MACHINE}-unknown-atheos - exit ;; - i*86:syllable:*:*) - echo ${UNAME_MACHINE}-pc-syllable - exit ;; - i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) - echo i386-unknown-lynxos${UNAME_RELEASE} - exit ;; - i*86:*DOS:*:*) - echo ${UNAME_MACHINE}-pc-msdosdjgpp - exit ;; - i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) - UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` - if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then - echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} - else - echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} - fi - exit ;; - i*86:*:5:[678]*) - # UnixWare 7.x, OpenUNIX and OpenServer 6. - case `/bin/uname -X | grep "^Machine"` in - *486*) UNAME_MACHINE=i486 ;; - *Pentium) UNAME_MACHINE=i586 ;; - *Pent*|*Celeron) UNAME_MACHINE=i686 ;; - esac - echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} - exit ;; - i*86:*:3.2:*) - if test -f /usr/options/cb.name; then - UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then - UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` - (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 - (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ - && UNAME_MACHINE=i586 - (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ - && UNAME_MACHINE=i686 - (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ - && UNAME_MACHINE=i686 - echo ${UNAME_MACHINE}-pc-sco$UNAME_REL - else - echo ${UNAME_MACHINE}-pc-sysv32 - fi - exit ;; - pc:*:*:*) - # Left here for compatibility: - # uname -m prints for DJGPP always 'pc', but it prints nothing about - # the processor, so we play safe by assuming i586. - # Note: whatever this is, it MUST be the same as what config.sub - # prints for the "djgpp" host, or else GDB configury will decide that - # this is a cross-build. - echo i586-pc-msdosdjgpp - exit ;; - Intel:Mach:3*:*) - echo i386-pc-mach3 - exit ;; - paragon:*:*:*) - echo i860-intel-osf1 - exit ;; - i860:*:4.*:*) # i860-SVR4 - if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then - echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 - else # Add other i860-SVR4 vendors below as they are discovered. - echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 - fi - exit ;; - mini*:CTIX:SYS*5:*) - # "miniframe" - echo m68010-convergent-sysv - exit ;; - mc68k:UNIX:SYSTEM5:3.51m) - echo m68k-convergent-sysv - exit ;; - M680?0:D-NIX:5.3:*) - echo m68k-diab-dnix - exit ;; - M68*:*:R3V[5678]*:*) - test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; - 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) - OS_REL='' - test -r /etc/.relid \ - && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4.3${OS_REL}; exit; } - /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; - 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4; exit; } ;; - NCR*:*:4.2:* | MPRAS*:*:4.2:*) - OS_REL='.3' - test -r /etc/.relid \ - && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` - /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ - && { echo i486-ncr-sysv4.3${OS_REL}; exit; } - /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } - /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ - && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; - m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) - echo m68k-unknown-lynxos${UNAME_RELEASE} - exit ;; - mc68030:UNIX_System_V:4.*:*) - echo m68k-atari-sysv4 - exit ;; - TSUNAMI:LynxOS:2.*:*) - echo sparc-unknown-lynxos${UNAME_RELEASE} - exit ;; - rs6000:LynxOS:2.*:*) - echo rs6000-unknown-lynxos${UNAME_RELEASE} - exit ;; - PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) - echo powerpc-unknown-lynxos${UNAME_RELEASE} - exit ;; - SM[BE]S:UNIX_SV:*:*) - echo mips-dde-sysv${UNAME_RELEASE} - exit ;; - RM*:ReliantUNIX-*:*:*) - echo mips-sni-sysv4 - exit ;; - RM*:SINIX-*:*:*) - echo mips-sni-sysv4 - exit ;; - *:SINIX-*:*:*) - if uname -p 2>/dev/null >/dev/null ; then - UNAME_MACHINE=`(uname -p) 2>/dev/null` - echo ${UNAME_MACHINE}-sni-sysv4 - else - echo ns32k-sni-sysv - fi - exit ;; - PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort - # says - echo i586-unisys-sysv4 - exit ;; - *:UNIX_System_V:4*:FTX*) - # From Gerald Hewes . - # How about differentiating between stratus architectures? -djm - echo hppa1.1-stratus-sysv4 - exit ;; - *:*:*:FTX*) - # From seanf@swdc.stratus.com. - echo i860-stratus-sysv4 - exit ;; - i*86:VOS:*:*) - # From Paul.Green@stratus.com. - echo ${UNAME_MACHINE}-stratus-vos - exit ;; - *:VOS:*:*) - # From Paul.Green@stratus.com. - echo hppa1.1-stratus-vos - exit ;; - mc68*:A/UX:*:*) - echo m68k-apple-aux${UNAME_RELEASE} - exit ;; - news*:NEWS-OS:6*:*) - echo mips-sony-newsos6 - exit ;; - R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) - if [ -d /usr/nec ]; then - echo mips-nec-sysv${UNAME_RELEASE} - else - echo mips-unknown-sysv${UNAME_RELEASE} - fi - exit ;; - BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. - echo powerpc-be-beos - exit ;; - BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. - echo powerpc-apple-beos - exit ;; - BePC:BeOS:*:*) # BeOS running on Intel PC compatible. - echo i586-pc-beos - exit ;; - BePC:Haiku:*:*) # Haiku running on Intel PC compatible. - echo i586-pc-haiku - exit ;; - SX-4:SUPER-UX:*:*) - echo sx4-nec-superux${UNAME_RELEASE} - exit ;; - SX-5:SUPER-UX:*:*) - echo sx5-nec-superux${UNAME_RELEASE} - exit ;; - SX-6:SUPER-UX:*:*) - echo sx6-nec-superux${UNAME_RELEASE} - exit ;; - SX-7:SUPER-UX:*:*) - echo sx7-nec-superux${UNAME_RELEASE} - exit ;; - SX-8:SUPER-UX:*:*) - echo sx8-nec-superux${UNAME_RELEASE} - exit ;; - SX-8R:SUPER-UX:*:*) - echo sx8r-nec-superux${UNAME_RELEASE} - exit ;; - Power*:Rhapsody:*:*) - echo powerpc-apple-rhapsody${UNAME_RELEASE} - exit ;; - *:Rhapsody:*:*) - echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} - exit ;; - *:Darwin:*:*) - UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown - case $UNAME_PROCESSOR in - i386) - eval $set_cc_for_build - if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then - if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ - (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ - grep IS_64BIT_ARCH >/dev/null - then - UNAME_PROCESSOR="x86_64" - fi - fi ;; - unknown) UNAME_PROCESSOR=powerpc ;; - esac - echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} - exit ;; - *:procnto*:*:* | *:QNX:[0123456789]*:*) - UNAME_PROCESSOR=`uname -p` - if test "$UNAME_PROCESSOR" = "x86"; then - UNAME_PROCESSOR=i386 - UNAME_MACHINE=pc - fi - echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} - exit ;; - *:QNX:*:4*) - echo i386-pc-qnx - exit ;; - NEO-?:NONSTOP_KERNEL:*:*) - echo neo-tandem-nsk${UNAME_RELEASE} - exit ;; - NSE-?:NONSTOP_KERNEL:*:*) - echo nse-tandem-nsk${UNAME_RELEASE} - exit ;; - NSR-?:NONSTOP_KERNEL:*:*) - echo nsr-tandem-nsk${UNAME_RELEASE} - exit ;; - *:NonStop-UX:*:*) - echo mips-compaq-nonstopux - exit ;; - BS2000:POSIX*:*:*) - echo bs2000-siemens-sysv - exit ;; - DS/*:UNIX_System_V:*:*) - echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} - exit ;; - *:Plan9:*:*) - # "uname -m" is not consistent, so use $cputype instead. 386 - # is converted to i386 for consistency with other x86 - # operating systems. - if test "$cputype" = "386"; then - UNAME_MACHINE=i386 - else - UNAME_MACHINE="$cputype" - fi - echo ${UNAME_MACHINE}-unknown-plan9 - exit ;; - *:TOPS-10:*:*) - echo pdp10-unknown-tops10 - exit ;; - *:TENEX:*:*) - echo pdp10-unknown-tenex - exit ;; - KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) - echo pdp10-dec-tops20 - exit ;; - XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) - echo pdp10-xkl-tops20 - exit ;; - *:TOPS-20:*:*) - echo pdp10-unknown-tops20 - exit ;; - *:ITS:*:*) - echo pdp10-unknown-its - exit ;; - SEI:*:*:SEIUX) - echo mips-sei-seiux${UNAME_RELEASE} - exit ;; - *:DragonFly:*:*) - echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` - exit ;; - *:*VMS:*:*) - UNAME_MACHINE=`(uname -p) 2>/dev/null` - case "${UNAME_MACHINE}" in - A*) echo alpha-dec-vms ; exit ;; - I*) echo ia64-dec-vms ; exit ;; - V*) echo vax-dec-vms ; exit ;; - esac ;; - *:XENIX:*:SysV) - echo i386-pc-xenix - exit ;; - i*86:skyos:*:*) - echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' - exit ;; - i*86:rdos:*:*) - echo ${UNAME_MACHINE}-pc-rdos - exit ;; - i*86:AROS:*:*) - echo ${UNAME_MACHINE}-pc-aros - exit ;; - x86_64:VMkernel:*:*) - echo ${UNAME_MACHINE}-unknown-esx - exit ;; -esac - -#echo '(No uname command or uname output not recognized.)' 1>&2 -#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 - -eval $set_cc_for_build -cat >$dummy.c < -# include -#endif -main () -{ -#if defined (sony) -#if defined (MIPSEB) - /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, - I don't know.... */ - printf ("mips-sony-bsd\n"); exit (0); -#else -#include - printf ("m68k-sony-newsos%s\n", -#ifdef NEWSOS4 - "4" -#else - "" -#endif - ); exit (0); -#endif -#endif - -#if defined (__arm) && defined (__acorn) && defined (__unix) - printf ("arm-acorn-riscix\n"); exit (0); -#endif - -#if defined (hp300) && !defined (hpux) - printf ("m68k-hp-bsd\n"); exit (0); -#endif - -#if defined (NeXT) -#if !defined (__ARCHITECTURE__) -#define __ARCHITECTURE__ "m68k" -#endif - int version; - version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; - if (version < 4) - printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); - else - printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); - exit (0); -#endif - -#if defined (MULTIMAX) || defined (n16) -#if defined (UMAXV) - printf ("ns32k-encore-sysv\n"); exit (0); -#else -#if defined (CMU) - printf ("ns32k-encore-mach\n"); exit (0); -#else - printf ("ns32k-encore-bsd\n"); exit (0); -#endif -#endif -#endif - -#if defined (__386BSD__) - printf ("i386-pc-bsd\n"); exit (0); -#endif - -#if defined (sequent) -#if defined (i386) - printf ("i386-sequent-dynix\n"); exit (0); -#endif -#if defined (ns32000) - printf ("ns32k-sequent-dynix\n"); exit (0); -#endif -#endif - -#if defined (_SEQUENT_) - struct utsname un; - - uname(&un); - - if (strncmp(un.version, "V2", 2) == 0) { - printf ("i386-sequent-ptx2\n"); exit (0); - } - if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ - printf ("i386-sequent-ptx1\n"); exit (0); - } - printf ("i386-sequent-ptx\n"); exit (0); - -#endif - -#if defined (vax) -# if !defined (ultrix) -# include -# if defined (BSD) -# if BSD == 43 - printf ("vax-dec-bsd4.3\n"); exit (0); -# else -# if BSD == 199006 - printf ("vax-dec-bsd4.3reno\n"); exit (0); -# else - printf ("vax-dec-bsd\n"); exit (0); -# endif -# endif -# else - printf ("vax-dec-bsd\n"); exit (0); -# endif -# else - printf ("vax-dec-ultrix\n"); exit (0); -# endif -#endif - -#if defined (alliant) && defined (i860) - printf ("i860-alliant-bsd\n"); exit (0); -#endif - - exit (1); -} -EOF - -$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && - { echo "$SYSTEM_NAME"; exit; } - -# Apollos put the system type in the environment. - -test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } - -# Convex versions that predate uname can use getsysinfo(1) - -if [ -x /usr/convex/getsysinfo ] -then - case `getsysinfo -f cpu_type` in - c1*) - echo c1-convex-bsd - exit ;; - c2*) - if getsysinfo -f scalar_acc - then echo c32-convex-bsd - else echo c2-convex-bsd - fi - exit ;; - c34*) - echo c34-convex-bsd - exit ;; - c38*) - echo c38-convex-bsd - exit ;; - c4*) - echo c4-convex-bsd - exit ;; - esac -fi - -cat >&2 < in order to provide the needed -information to handle your system. - -config.guess timestamp = $timestamp - -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` - -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null` - -hostinfo = `(hostinfo) 2>/dev/null` -/bin/universe = `(/bin/universe) 2>/dev/null` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` -/bin/arch = `(/bin/arch) 2>/dev/null` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` - -UNAME_MACHINE = ${UNAME_MACHINE} -UNAME_RELEASE = ${UNAME_RELEASE} -UNAME_SYSTEM = ${UNAME_SYSTEM} -UNAME_VERSION = ${UNAME_VERSION} -EOF - -exit 1 - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "timestamp='" -# time-stamp-format: "%:y-%02m-%02d" -# time-stamp-end: "'" -# End: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.h.in b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.h.in deleted file mode 100644 index 76baa09..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.h.in +++ /dev/null @@ -1,149 +0,0 @@ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* ELF size: 32 or 64 */ -#undef BACKTRACE_ELF_SIZE - -/* XCOFF size: 32 or 64 */ -#undef BACKTRACE_XCOFF_SIZE - -/* Define to 1 if you have the __atomic functions */ -#undef HAVE_ATOMIC_FUNCTIONS - -/* Define to 1 if you have the `clock_gettime' function. */ -#undef HAVE_CLOCK_GETTIME - -/* Define to 1 if you have the declaration of `strnlen', and to 0 if you - don't. */ -#undef HAVE_DECL_STRNLEN - -/* Define to 1 if you have the header file. */ -#undef HAVE_DLFCN_H - -/* Define if dl_iterate_phdr is available. */ -#undef HAVE_DL_ITERATE_PHDR - -/* Define to 1 if you have the fcntl function */ -#undef HAVE_FCNTL - -/* Define if getexecname is available. */ -#undef HAVE_GETEXECNAME - -/* Define if _Unwind_GetIPInfo is available. */ -#undef HAVE_GETIPINFO - -/* Define to 1 if you have the header file. */ -#undef HAVE_INTTYPES_H - -/* Define to 1 if you have the `z' library (-lz). */ -#undef HAVE_LIBZ - -/* Define to 1 if you have the header file. */ -#undef HAVE_LINK_H - -/* Define if AIX loadquery is available. */ -#undef HAVE_LOADQUERY - -/* Define to 1 if you have the `lstat' function. */ -#undef HAVE_LSTAT - -/* Define to 1 if you have the header file. */ -#undef HAVE_MEMORY_H - -/* Define to 1 if you have the `readlink' function. */ -#undef HAVE_READLINK - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDINT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDLIB_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRING_H - -/* Define to 1 if you have the __sync functions */ -#undef HAVE_SYNC_FUNCTIONS - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_LDR_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_MMAN_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_UNISTD_H - -/* Define if -lz is available. */ -#undef HAVE_ZLIB - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#undef LT_OBJDIR - -/* Define to the address where bug reports for this package should be sent. */ -#undef PACKAGE_BUGREPORT - -/* Define to the full name of this package. */ -#undef PACKAGE_NAME - -/* Define to the full name and version of this package. */ -#undef PACKAGE_STRING - -/* Define to the one symbol short name of this package. */ -#undef PACKAGE_TARNAME - -/* Define to the home page for this package. */ -#undef PACKAGE_URL - -/* Define to the version of this package. */ -#undef PACKAGE_VERSION - -/* Define to 1 if you have the ANSI C header files. */ -#undef STDC_HEADERS - -/* Enable extensions on AIX 3, Interix. */ -#ifndef _ALL_SOURCE -# undef _ALL_SOURCE -#endif -/* Enable GNU extensions on systems that have them. */ -#ifndef _GNU_SOURCE -# undef _GNU_SOURCE -#endif -/* Enable threading extensions on Solaris. */ -#ifndef _POSIX_PTHREAD_SEMANTICS -# undef _POSIX_PTHREAD_SEMANTICS -#endif -/* Enable extensions on HP NonStop. */ -#ifndef _TANDEM_SOURCE -# undef _TANDEM_SOURCE -#endif -/* Enable general extensions on Solaris. */ -#ifndef __EXTENSIONS__ -# undef __EXTENSIONS__ -#endif - - -/* Number of bits in a file offset, on hosts where this is settable. */ -#undef _FILE_OFFSET_BITS - -/* Define for large files, on AIX-style hosts. */ -#undef _LARGE_FILES - -/* Define to 1 if on MINIX. */ -#undef _MINIX - -/* Define to 2 if the system does not provide POSIX.1 features except with - this defined. */ -#undef _POSIX_1_SOURCE - -/* Define to 1 if you need to in order for `stat' and other things to work. */ -#undef _POSIX_SOURCE diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.sub b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.sub deleted file mode 100755 index 63634d9..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config.sub +++ /dev/null @@ -1,1794 +0,0 @@ -#! /bin/sh -# Configuration validation subroutine script. -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, -# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, -# 2011, 2012 Free Software Foundation, Inc. - -timestamp='2012-02-10' - -# This file is (in principle) common to ALL GNU software. -# The presence of a machine in this file suggests that SOME GNU software -# can handle that machine. It does not imply ALL GNU software can. -# -# This file is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, see . -# -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - - -# Please send patches to . Submit a context -# diff and a properly formatted GNU ChangeLog entry. -# -# Configuration subroutine to validate and canonicalize a configuration type. -# Supply the specified configuration type as an argument. -# If it is invalid, we print an error message on stderr and exit with code 1. -# Otherwise, we print the canonical config type on stdout and succeed. - -# You can get the latest version of this script from: -# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD - -# This file is supposed to be the same for all GNU packages -# and recognize all the CPU types, system types and aliases -# that are meaningful with *any* GNU software. -# Each package is responsible for reporting which valid configurations -# it does not support. The user should be able to distinguish -# a failure to support a valid configuration from a meaningless -# configuration. - -# The goal of this file is to map all the various variations of a given -# machine specification into a single specification in the form: -# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM -# or in some cases, the newer four-part form: -# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM -# It is wrong to echo any other type of specification. - -me=`echo "$0" | sed -e 's,.*/,,'` - -usage="\ -Usage: $0 [OPTION] CPU-MFR-OPSYS - $0 [OPTION] ALIAS - -Canonicalize a configuration name. - -Operation modes: - -h, --help print this help, then exit - -t, --time-stamp print date of last modification, then exit - -v, --version print version number, then exit - -Report bugs and patches to ." - -version="\ -GNU config.sub ($timestamp) - -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, -2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 -Free Software Foundation, Inc. - -This is free software; see the source for copying conditions. There is NO -warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." - -help=" -Try \`$me --help' for more information." - -# Parse command line -while test $# -gt 0 ; do - case $1 in - --time-stamp | --time* | -t ) - echo "$timestamp" ; exit ;; - --version | -v ) - echo "$version" ; exit ;; - --help | --h* | -h ) - echo "$usage"; exit ;; - -- ) # Stop option processing - shift; break ;; - - ) # Use stdin as input. - break ;; - -* ) - echo "$me: invalid option $1$help" - exit 1 ;; - - *local*) - # First pass through any local machine types. - echo $1 - exit ;; - - * ) - break ;; - esac -done - -case $# in - 0) echo "$me: missing argument$help" >&2 - exit 1;; - 1) ;; - *) echo "$me: too many arguments$help" >&2 - exit 1;; -esac - -# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). -# Here we must recognize all the valid KERNEL-OS combinations. -maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` -case $maybe_os in - nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ - linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ - knetbsd*-gnu* | netbsd*-gnu* | \ - kopensolaris*-gnu* | \ - storm-chaos* | os2-emx* | rtmk-nova*) - os=-$maybe_os - basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` - ;; - android-linux) - os=-linux-android - basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown - ;; - *) - basic_machine=`echo $1 | sed 's/-[^-]*$//'` - if [ $basic_machine != $1 ] - then os=`echo $1 | sed 's/.*-/-/'` - else os=; fi - ;; -esac - -### Let's recognize common machines as not being operating systems so -### that things like config.sub decstation-3100 work. We also -### recognize some manufacturers as not being operating systems, so we -### can provide default operating systems below. -case $os in - -sun*os*) - # Prevent following clause from handling this invalid input. - ;; - -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ - -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ - -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ - -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ - -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ - -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ - -apple | -axis | -knuth | -cray | -microblaze) - os= - basic_machine=$1 - ;; - -bluegene*) - os=-cnk - ;; - -sim | -cisco | -oki | -wec | -winbond) - os= - basic_machine=$1 - ;; - -scout) - ;; - -wrs) - os=-vxworks - basic_machine=$1 - ;; - -chorusos*) - os=-chorusos - basic_machine=$1 - ;; - -chorusrdb) - os=-chorusrdb - basic_machine=$1 - ;; - -hiux*) - os=-hiuxwe2 - ;; - -sco6) - os=-sco5v6 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco5) - os=-sco3.2v5 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco4) - os=-sco3.2v4 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco3.2.[4-9]*) - os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco3.2v[4-9]*) - # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco5v6*) - # Don't forget version if it is 3.2v4 or newer. - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -sco*) - os=-sco3.2v2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -udk*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -isc) - os=-isc2.2 - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -clix*) - basic_machine=clipper-intergraph - ;; - -isc*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` - ;; - -lynx*) - os=-lynxos - ;; - -ptx*) - basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` - ;; - -windowsnt*) - os=`echo $os | sed -e 's/windowsnt/winnt/'` - ;; - -psos*) - os=-psos - ;; - -mint | -mint[0-9]*) - basic_machine=m68k-atari - os=-mint - ;; -esac - -# Decode aliases for certain CPU-COMPANY combinations. -case $basic_machine in - # Recognize the basic CPU types without company name. - # Some are omitted here because they have special meanings below. - 1750a | 580 \ - | a29k \ - | aarch64 | aarch64_be \ - | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ - | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ - | am33_2.0 \ - | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ - | be32 | be64 \ - | bfin \ - | c4x | clipper \ - | d10v | d30v | dlx | dsp16xx \ - | epiphany \ - | fido | fr30 | frv \ - | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ - | hexagon \ - | i370 | i860 | i960 | ia16 | ia64 \ - | ip2k | iq2000 \ - | le32 | le64 \ - | lm32 \ - | m32c | m32r | m32rle | m68000 | m68k | m88k \ - | maxq | mb | microblaze | mcore | mep | metag \ - | mips | mipsbe | mipseb | mipsel | mipsle \ - | mips16 \ - | mips64 | mips64el \ - | mips64octeon | mips64octeonel \ - | mips64orion | mips64orionel \ - | mips64r5900 | mips64r5900el \ - | mips64vr | mips64vrel \ - | mips64vr4100 | mips64vr4100el \ - | mips64vr4300 | mips64vr4300el \ - | mips64vr5000 | mips64vr5000el \ - | mips64vr5900 | mips64vr5900el \ - | mipsisa32 | mipsisa32el \ - | mipsisa32r2 | mipsisa32r2el \ - | mipsisa64 | mipsisa64el \ - | mipsisa64r2 | mipsisa64r2el \ - | mipsisa64sb1 | mipsisa64sb1el \ - | mipsisa64sr71k | mipsisa64sr71kel \ - | mipstx39 | mipstx39el \ - | mn10200 | mn10300 \ - | moxie \ - | mt \ - | msp430 \ - | nds32 | nds32le | nds32be \ - | nios | nios2 \ - | ns16k | ns32k \ - | open8 \ - | or32 \ - | pdp10 | pdp11 | pj | pjl \ - | powerpc | powerpc64 | powerpc64le | powerpcle \ - | pru \ - | pyramid \ - | rl78 | rx \ - | score \ - | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ - | sh64 | sh64le \ - | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ - | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ - | spu \ - | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ - | ubicom32 \ - | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ - | we32k \ - | x86 | xc16x | xstormy16 | xtensa \ - | z8k | z80) - basic_machine=$basic_machine-unknown - ;; - c54x) - basic_machine=tic54x-unknown - ;; - c55x) - basic_machine=tic55x-unknown - ;; - c6x) - basic_machine=tic6x-unknown - ;; - m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) - basic_machine=$basic_machine-unknown - os=-none - ;; - m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) - ;; - ms1) - basic_machine=mt-unknown - ;; - - strongarm | thumb | xscale) - basic_machine=arm-unknown - ;; - xgate) - basic_machine=$basic_machine-unknown - os=-none - ;; - xscaleeb) - basic_machine=armeb-unknown - ;; - - xscaleel) - basic_machine=armel-unknown - ;; - - # We use `pc' rather than `unknown' - # because (1) that's what they normally are, and - # (2) the word "unknown" tends to confuse beginning users. - i*86 | x86_64) - basic_machine=$basic_machine-pc - ;; - # Object if more than one company name word. - *-*-*) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 - exit 1 - ;; - # Recognize the basic CPU types with company name. - 580-* \ - | a29k-* \ - | aarch64-* | aarch64_be-* \ - | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ - | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ - | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ - | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ - | avr-* | avr32-* \ - | be32-* | be64-* \ - | bfin-* | bs2000-* \ - | c[123]* | c30-* | [cjt]90-* | c4x-* \ - | clipper-* | craynv-* | cydra-* \ - | d10v-* | d30v-* | dlx-* \ - | elxsi-* \ - | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ - | h8300-* | h8500-* \ - | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ - | hexagon-* \ - | i*86-* | i860-* | i960-* | ia16-* | ia64-* \ - | ip2k-* | iq2000-* \ - | le32-* | le64-* \ - | lm32-* \ - | m32c-* | m32r-* | m32rle-* \ - | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ - | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \ - | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ - | mips16-* \ - | mips64-* | mips64el-* \ - | mips64octeon-* | mips64octeonel-* \ - | mips64orion-* | mips64orionel-* \ - | mips64r5900-* | mips64r5900el-* \ - | mips64vr-* | mips64vrel-* \ - | mips64vr4100-* | mips64vr4100el-* \ - | mips64vr4300-* | mips64vr4300el-* \ - | mips64vr5000-* | mips64vr5000el-* \ - | mips64vr5900-* | mips64vr5900el-* \ - | mipsisa32-* | mipsisa32el-* \ - | mipsisa32r2-* | mipsisa32r2el-* \ - | mipsisa64-* | mipsisa64el-* \ - | mipsisa64r2-* | mipsisa64r2el-* \ - | mipsisa64sb1-* | mipsisa64sb1el-* \ - | mipsisa64sr71k-* | mipsisa64sr71kel-* \ - | mipstx39-* | mipstx39el-* \ - | mmix-* \ - | mt-* \ - | msp430-* \ - | nds32-* | nds32le-* | nds32be-* \ - | nios-* | nios2-* \ - | none-* | np1-* | ns16k-* | ns32k-* \ - | open8-* \ - | orion-* \ - | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ - | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ - | pru-* \ - | pyramid-* \ - | rl78-* | romp-* | rs6000-* | rx-* \ - | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ - | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ - | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ - | sparclite-* \ - | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ - | tahoe-* \ - | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ - | tile*-* \ - | tron-* \ - | ubicom32-* \ - | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ - | vax-* \ - | we32k-* \ - | x86-* | x86_64-* | xc16x-* | xps100-* \ - | xstormy16-* | xtensa*-* \ - | ymp-* \ - | z8k-* | z80-*) - ;; - # Recognize the basic CPU types without company name, with glob match. - xtensa*) - basic_machine=$basic_machine-unknown - ;; - # Recognize the various machine names and aliases which stand - # for a CPU type and a company and sometimes even an OS. - 386bsd) - basic_machine=i386-unknown - os=-bsd - ;; - 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) - basic_machine=m68000-att - ;; - 3b*) - basic_machine=we32k-att - ;; - a29khif) - basic_machine=a29k-amd - os=-udi - ;; - abacus) - basic_machine=abacus-unknown - ;; - adobe68k) - basic_machine=m68010-adobe - os=-scout - ;; - alliant | fx80) - basic_machine=fx80-alliant - ;; - altos | altos3068) - basic_machine=m68k-altos - ;; - am29k) - basic_machine=a29k-none - os=-bsd - ;; - amd64) - basic_machine=x86_64-pc - ;; - amd64-*) - basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - amdahl) - basic_machine=580-amdahl - os=-sysv - ;; - amiga | amiga-*) - basic_machine=m68k-unknown - ;; - amigaos | amigados) - basic_machine=m68k-unknown - os=-amigaos - ;; - amigaunix | amix) - basic_machine=m68k-unknown - os=-sysv4 - ;; - apollo68) - basic_machine=m68k-apollo - os=-sysv - ;; - apollo68bsd) - basic_machine=m68k-apollo - os=-bsd - ;; - aros) - basic_machine=i386-pc - os=-aros - ;; - aux) - basic_machine=m68k-apple - os=-aux - ;; - balance) - basic_machine=ns32k-sequent - os=-dynix - ;; - blackfin) - basic_machine=bfin-unknown - os=-linux - ;; - blackfin-*) - basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` - os=-linux - ;; - bluegene*) - basic_machine=powerpc-ibm - os=-cnk - ;; - c54x-*) - basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - c55x-*) - basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - c6x-*) - basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - c90) - basic_machine=c90-cray - os=-unicos - ;; - cegcc) - basic_machine=arm-unknown - os=-cegcc - ;; - convex-c1) - basic_machine=c1-convex - os=-bsd - ;; - convex-c2) - basic_machine=c2-convex - os=-bsd - ;; - convex-c32) - basic_machine=c32-convex - os=-bsd - ;; - convex-c34) - basic_machine=c34-convex - os=-bsd - ;; - convex-c38) - basic_machine=c38-convex - os=-bsd - ;; - cray | j90) - basic_machine=j90-cray - os=-unicos - ;; - craynv) - basic_machine=craynv-cray - os=-unicosmp - ;; - cr16 | cr16-*) - basic_machine=cr16-unknown - os=-elf - ;; - crds | unos) - basic_machine=m68k-crds - ;; - crisv32 | crisv32-* | etraxfs*) - basic_machine=crisv32-axis - ;; - cris | cris-* | etrax*) - basic_machine=cris-axis - ;; - crx) - basic_machine=crx-unknown - os=-elf - ;; - da30 | da30-*) - basic_machine=m68k-da30 - ;; - decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) - basic_machine=mips-dec - ;; - decsystem10* | dec10*) - basic_machine=pdp10-dec - os=-tops10 - ;; - decsystem20* | dec20*) - basic_machine=pdp10-dec - os=-tops20 - ;; - delta | 3300 | motorola-3300 | motorola-delta \ - | 3300-motorola | delta-motorola) - basic_machine=m68k-motorola - ;; - delta88) - basic_machine=m88k-motorola - os=-sysv3 - ;; - dicos) - basic_machine=i686-pc - os=-dicos - ;; - djgpp) - basic_machine=i586-pc - os=-msdosdjgpp - ;; - dpx20 | dpx20-*) - basic_machine=rs6000-bull - os=-bosx - ;; - dpx2* | dpx2*-bull) - basic_machine=m68k-bull - os=-sysv3 - ;; - e500v[12]) - basic_machine=powerpc-unknown - os=$os"spe" - ;; - e500v[12]-*) - basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` - os=$os"spe" - ;; - ebmon29k) - basic_machine=a29k-amd - os=-ebmon - ;; - elxsi) - basic_machine=elxsi-elxsi - os=-bsd - ;; - encore | umax | mmax) - basic_machine=ns32k-encore - ;; - es1800 | OSE68k | ose68k | ose | OSE) - basic_machine=m68k-ericsson - os=-ose - ;; - fx2800) - basic_machine=i860-alliant - ;; - genix) - basic_machine=ns32k-ns - ;; - gmicro) - basic_machine=tron-gmicro - os=-sysv - ;; - go32) - basic_machine=i386-pc - os=-go32 - ;; - h3050r* | hiux*) - basic_machine=hppa1.1-hitachi - os=-hiuxwe2 - ;; - h8300hms) - basic_machine=h8300-hitachi - os=-hms - ;; - h8300xray) - basic_machine=h8300-hitachi - os=-xray - ;; - h8500hms) - basic_machine=h8500-hitachi - os=-hms - ;; - harris) - basic_machine=m88k-harris - os=-sysv3 - ;; - hp300-*) - basic_machine=m68k-hp - ;; - hp300bsd) - basic_machine=m68k-hp - os=-bsd - ;; - hp300hpux) - basic_machine=m68k-hp - os=-hpux - ;; - hp3k9[0-9][0-9] | hp9[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hp9k2[0-9][0-9] | hp9k31[0-9]) - basic_machine=m68000-hp - ;; - hp9k3[2-9][0-9]) - basic_machine=m68k-hp - ;; - hp9k6[0-9][0-9] | hp6[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hp9k7[0-79][0-9] | hp7[0-79][0-9]) - basic_machine=hppa1.1-hp - ;; - hp9k78[0-9] | hp78[0-9]) - # FIXME: really hppa2.0-hp - basic_machine=hppa1.1-hp - ;; - hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) - # FIXME: really hppa2.0-hp - basic_machine=hppa1.1-hp - ;; - hp9k8[0-9][13679] | hp8[0-9][13679]) - basic_machine=hppa1.1-hp - ;; - hp9k8[0-9][0-9] | hp8[0-9][0-9]) - basic_machine=hppa1.0-hp - ;; - hppa-next) - os=-nextstep3 - ;; - hppaosf) - basic_machine=hppa1.1-hp - os=-osf - ;; - hppro) - basic_machine=hppa1.1-hp - os=-proelf - ;; - i370-ibm* | ibm*) - basic_machine=i370-ibm - ;; - i*86v32) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv32 - ;; - i*86v4*) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv4 - ;; - i*86v) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-sysv - ;; - i*86sol2) - basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` - os=-solaris2 - ;; - i386mach) - basic_machine=i386-mach - os=-mach - ;; - i386-vsta | vsta) - basic_machine=i386-unknown - os=-vsta - ;; - iris | iris4d) - basic_machine=mips-sgi - case $os in - -irix*) - ;; - *) - os=-irix4 - ;; - esac - ;; - isi68 | isi) - basic_machine=m68k-isi - os=-sysv - ;; - m68knommu) - basic_machine=m68k-unknown - os=-linux - ;; - m68knommu-*) - basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` - os=-linux - ;; - m88k-omron*) - basic_machine=m88k-omron - ;; - magnum | m3230) - basic_machine=mips-mips - os=-sysv - ;; - merlin) - basic_machine=ns32k-utek - os=-sysv - ;; - microblaze) - basic_machine=microblaze-xilinx - ;; - mingw32) - basic_machine=i386-pc - os=-mingw32 - ;; - mingw32ce) - basic_machine=arm-unknown - os=-mingw32ce - ;; - miniframe) - basic_machine=m68000-convergent - ;; - *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) - basic_machine=m68k-atari - os=-mint - ;; - mips3*-*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` - ;; - mips3*) - basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown - ;; - monitor) - basic_machine=m68k-rom68k - os=-coff - ;; - morphos) - basic_machine=powerpc-unknown - os=-morphos - ;; - msdos) - basic_machine=i386-pc - os=-msdos - ;; - ms1-*) - basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` - ;; - msys) - basic_machine=i386-pc - os=-msys - ;; - mvs) - basic_machine=i370-ibm - os=-mvs - ;; - nacl) - basic_machine=le32-unknown - os=-nacl - ;; - ncr3000) - basic_machine=i486-ncr - os=-sysv4 - ;; - netbsd386) - basic_machine=i386-unknown - os=-netbsd - ;; - netwinder) - basic_machine=armv4l-rebel - os=-linux - ;; - news | news700 | news800 | news900) - basic_machine=m68k-sony - os=-newsos - ;; - news1000) - basic_machine=m68030-sony - os=-newsos - ;; - news-3600 | risc-news) - basic_machine=mips-sony - os=-newsos - ;; - necv70) - basic_machine=v70-nec - os=-sysv - ;; - next | m*-next ) - basic_machine=m68k-next - case $os in - -nextstep* ) - ;; - -ns2*) - os=-nextstep2 - ;; - *) - os=-nextstep3 - ;; - esac - ;; - nh3000) - basic_machine=m68k-harris - os=-cxux - ;; - nh[45]000) - basic_machine=m88k-harris - os=-cxux - ;; - nindy960) - basic_machine=i960-intel - os=-nindy - ;; - mon960) - basic_machine=i960-intel - os=-mon960 - ;; - nonstopux) - basic_machine=mips-compaq - os=-nonstopux - ;; - np1) - basic_machine=np1-gould - ;; - neo-tandem) - basic_machine=neo-tandem - ;; - nse-tandem) - basic_machine=nse-tandem - ;; - nsr-tandem) - basic_machine=nsr-tandem - ;; - nsx-tandem) - basic_machine=nsx-tandem - ;; - op50n-* | op60c-*) - basic_machine=hppa1.1-oki - os=-proelf - ;; - openrisc | openrisc-*) - basic_machine=or32-unknown - ;; - os400) - basic_machine=powerpc-ibm - os=-os400 - ;; - OSE68000 | ose68000) - basic_machine=m68000-ericsson - os=-ose - ;; - os68k) - basic_machine=m68k-none - os=-os68k - ;; - pa-hitachi) - basic_machine=hppa1.1-hitachi - os=-hiuxwe2 - ;; - paragon) - basic_machine=i860-intel - os=-osf - ;; - parisc) - basic_machine=hppa-unknown - os=-linux - ;; - parisc-*) - basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` - os=-linux - ;; - pbd) - basic_machine=sparc-tti - ;; - pbb) - basic_machine=m68k-tti - ;; - pc532 | pc532-*) - basic_machine=ns32k-pc532 - ;; - pc98) - basic_machine=i386-pc - ;; - pc98-*) - basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentium | p5 | k5 | k6 | nexgen | viac3) - basic_machine=i586-pc - ;; - pentiumpro | p6 | 6x86 | athlon | athlon_*) - basic_machine=i686-pc - ;; - pentiumii | pentium2 | pentiumiii | pentium3) - basic_machine=i686-pc - ;; - pentium4) - basic_machine=i786-pc - ;; - pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) - basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentiumpro-* | p6-* | 6x86-* | athlon-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) - basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pentium4-*) - basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - pn) - basic_machine=pn-gould - ;; - power) basic_machine=power-ibm - ;; - ppc | ppcbe) basic_machine=powerpc-unknown - ;; - ppc-* | ppcbe-*) - basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppcle | powerpclittle) - basic_machine=powerpcle-unknown - ;; - ppcle-* | powerpclittle-*) - basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppc64) basic_machine=powerpc64-unknown - ;; - ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ppc64le | powerpc64little) - basic_machine=powerpc64le-unknown - ;; - ppc64le-* | powerpc64little-*) - basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - ps2) - basic_machine=i386-ibm - ;; - pw32) - basic_machine=i586-unknown - os=-pw32 - ;; - rdos) - basic_machine=i386-pc - os=-rdos - ;; - rom68k) - basic_machine=m68k-rom68k - os=-coff - ;; - rm[46]00) - basic_machine=mips-siemens - ;; - rtpc | rtpc-*) - basic_machine=romp-ibm - ;; - s390 | s390-*) - basic_machine=s390-ibm - ;; - s390x | s390x-*) - basic_machine=s390x-ibm - ;; - sa29200) - basic_machine=a29k-amd - os=-udi - ;; - sb1) - basic_machine=mipsisa64sb1-unknown - ;; - sb1el) - basic_machine=mipsisa64sb1el-unknown - ;; - sde) - basic_machine=mipsisa32-sde - os=-elf - ;; - sei) - basic_machine=mips-sei - os=-seiux - ;; - sequent) - basic_machine=i386-sequent - ;; - sh) - basic_machine=sh-hitachi - os=-hms - ;; - sh5el) - basic_machine=sh5le-unknown - ;; - sh64) - basic_machine=sh64-unknown - ;; - sparclite-wrs | simso-wrs) - basic_machine=sparclite-wrs - os=-vxworks - ;; - sps7) - basic_machine=m68k-bull - os=-sysv2 - ;; - spur) - basic_machine=spur-unknown - ;; - st2000) - basic_machine=m68k-tandem - ;; - stratus) - basic_machine=i860-stratus - os=-sysv4 - ;; - strongarm-* | thumb-*) - basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` - ;; - sun2) - basic_machine=m68000-sun - ;; - sun2os3) - basic_machine=m68000-sun - os=-sunos3 - ;; - sun2os4) - basic_machine=m68000-sun - os=-sunos4 - ;; - sun3os3) - basic_machine=m68k-sun - os=-sunos3 - ;; - sun3os4) - basic_machine=m68k-sun - os=-sunos4 - ;; - sun4os3) - basic_machine=sparc-sun - os=-sunos3 - ;; - sun4os4) - basic_machine=sparc-sun - os=-sunos4 - ;; - sun4sol2) - basic_machine=sparc-sun - os=-solaris2 - ;; - sun3 | sun3-*) - basic_machine=m68k-sun - ;; - sun4) - basic_machine=sparc-sun - ;; - sun386 | sun386i | roadrunner) - basic_machine=i386-sun - ;; - sv1) - basic_machine=sv1-cray - os=-unicos - ;; - symmetry) - basic_machine=i386-sequent - os=-dynix - ;; - t3e) - basic_machine=alphaev5-cray - os=-unicos - ;; - t90) - basic_machine=t90-cray - os=-unicos - ;; - tile*) - basic_machine=$basic_machine-unknown - os=-linux-gnu - ;; - tx39) - basic_machine=mipstx39-unknown - ;; - tx39el) - basic_machine=mipstx39el-unknown - ;; - toad1) - basic_machine=pdp10-xkl - os=-tops20 - ;; - tower | tower-32) - basic_machine=m68k-ncr - ;; - tpf) - basic_machine=s390x-ibm - os=-tpf - ;; - udi29k) - basic_machine=a29k-amd - os=-udi - ;; - ultra3) - basic_machine=a29k-nyu - os=-sym1 - ;; - v810 | necv810) - basic_machine=v810-nec - os=-none - ;; - vaxv) - basic_machine=vax-dec - os=-sysv - ;; - vms) - basic_machine=vax-dec - os=-vms - ;; - vpp*|vx|vx-*) - basic_machine=f301-fujitsu - ;; - vxworks960) - basic_machine=i960-wrs - os=-vxworks - ;; - vxworks68) - basic_machine=m68k-wrs - os=-vxworks - ;; - vxworks29k) - basic_machine=a29k-wrs - os=-vxworks - ;; - wasm32) - basic_machine=wasm32-unknown - ;; - w65*) - basic_machine=w65-wdc - os=-none - ;; - w89k-*) - basic_machine=hppa1.1-winbond - os=-proelf - ;; - xbox) - basic_machine=i686-pc - os=-mingw32 - ;; - xps | xps100) - basic_machine=xps100-honeywell - ;; - xscale-* | xscalee[bl]-*) - basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` - ;; - ymp) - basic_machine=ymp-cray - os=-unicos - ;; - z8k-*-coff) - basic_machine=z8k-unknown - os=-sim - ;; - z80-*-coff) - basic_machine=z80-unknown - os=-sim - ;; - none) - basic_machine=none-none - os=-none - ;; - -# Here we handle the default manufacturer of certain CPU types. It is in -# some cases the only manufacturer, in others, it is the most popular. - w89k) - basic_machine=hppa1.1-winbond - ;; - op50n) - basic_machine=hppa1.1-oki - ;; - op60c) - basic_machine=hppa1.1-oki - ;; - romp) - basic_machine=romp-ibm - ;; - mmix) - basic_machine=mmix-knuth - ;; - rs6000) - basic_machine=rs6000-ibm - ;; - vax) - basic_machine=vax-dec - ;; - pdp10) - # there are many clones, so DEC is not a safe bet - basic_machine=pdp10-unknown - ;; - pdp11) - basic_machine=pdp11-dec - ;; - we32k) - basic_machine=we32k-att - ;; - sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) - basic_machine=sh-unknown - ;; - sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) - basic_machine=sparc-sun - ;; - cydra) - basic_machine=cydra-cydrome - ;; - orion) - basic_machine=orion-highlevel - ;; - orion105) - basic_machine=clipper-highlevel - ;; - mac | mpw | mac-mpw) - basic_machine=m68k-apple - ;; - pmac | pmac-mpw) - basic_machine=powerpc-apple - ;; - *-unknown) - # Make sure to match an already-canonicalized machine name. - ;; - *) - echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 - exit 1 - ;; -esac - -# Here we canonicalize certain aliases for manufacturers. -case $basic_machine in - *-digital*) - basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` - ;; - *-commodore*) - basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` - ;; - *) - ;; -esac - -# Decode manufacturer-specific aliases for certain operating systems. - -if [ x"$os" != x"" ] -then -case $os in - # First match some system type aliases - # that might get confused with valid system types. - # -solaris* is a basic system type, with this one exception. - -auroraux) - os=-auroraux - ;; - -solaris1 | -solaris1.*) - os=`echo $os | sed -e 's|solaris1|sunos4|'` - ;; - -solaris) - os=-solaris2 - ;; - -svr4*) - os=-sysv4 - ;; - -unixware*) - os=-sysv4.2uw - ;; - -gnu/linux*) - os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` - ;; - # First accept the basic system types. - # The portable systems comes first. - # Each alternative MUST END IN A *, to match a version number. - # -sysv* is not here because it comes later, after sysvr4. - -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ - | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ - | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ - | -sym* | -kopensolaris* \ - | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ - | -aos* | -aros* \ - | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ - | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ - | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ - | -openbsd* | -solidbsd* \ - | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ - | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ - | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ - | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ - | -chorusos* | -chorusrdb* | -cegcc* \ - | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ - | -mingw32* | -linux-gnu* | -linux-android* \ - | -linux-newlib* | -linux-uclibc* \ - | -uxpv* | -beos* | -mpeix* | -udk* \ - | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ - | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ - | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ - | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ - | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ - | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ - | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) - # Remember, each alternative MUST END IN *, to match a version number. - ;; - -qnx*) - case $basic_machine in - x86-* | i*86-*) - ;; - *) - os=-nto$os - ;; - esac - ;; - -nto-qnx*) - ;; - -nto*) - os=`echo $os | sed -e 's|nto|nto-qnx|'` - ;; - -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ - | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ - | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) - ;; - -mac*) - os=`echo $os | sed -e 's|mac|macos|'` - ;; - -linux-dietlibc) - os=-linux-dietlibc - ;; - -linux*) - os=`echo $os | sed -e 's|linux|linux-gnu|'` - ;; - -sunos5*) - os=`echo $os | sed -e 's|sunos5|solaris2|'` - ;; - -sunos6*) - os=`echo $os | sed -e 's|sunos6|solaris3|'` - ;; - -opened*) - os=-openedition - ;; - -os400*) - os=-os400 - ;; - -wince*) - os=-wince - ;; - -osfrose*) - os=-osfrose - ;; - -osf*) - os=-osf - ;; - -utek*) - os=-bsd - ;; - -dynix*) - os=-bsd - ;; - -acis*) - os=-aos - ;; - -atheos*) - os=-atheos - ;; - -syllable*) - os=-syllable - ;; - -386bsd) - os=-bsd - ;; - -ctix* | -uts*) - os=-sysv - ;; - -nova*) - os=-rtmk-nova - ;; - -ns2 ) - os=-nextstep2 - ;; - -nsk*) - os=-nsk - ;; - # Preserve the version number of sinix5. - -sinix5.*) - os=`echo $os | sed -e 's|sinix|sysv|'` - ;; - -sinix*) - os=-sysv4 - ;; - -tpf*) - os=-tpf - ;; - -triton*) - os=-sysv3 - ;; - -oss*) - os=-sysv3 - ;; - -svr4) - os=-sysv4 - ;; - -svr3) - os=-sysv3 - ;; - -sysvr4) - os=-sysv4 - ;; - # This must come after -sysvr4. - -sysv*) - ;; - -ose*) - os=-ose - ;; - -es1800*) - os=-ose - ;; - -xenix) - os=-xenix - ;; - -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) - os=-mint - ;; - -aros*) - os=-aros - ;; - -kaos*) - os=-kaos - ;; - -zvmoe) - os=-zvmoe - ;; - -dicos*) - os=-dicos - ;; - -nacl*) - ;; - -ios) - ;; - -none) - ;; - *) - # Get rid of the `-' at the beginning of $os. - os=`echo $os | sed 's/[^-]*-//'` - echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 - exit 1 - ;; -esac -else - -# Here we handle the default operating systems that come with various machines. -# The value should be what the vendor currently ships out the door with their -# machine or put another way, the most popular os provided with the machine. - -# Note that if you're going to try to match "-MANUFACTURER" here (say, -# "-sun"), then you have to tell the case statement up towards the top -# that MANUFACTURER isn't an operating system. Otherwise, code above -# will signal an error saying that MANUFACTURER isn't an operating -# system, and we'll never get to this point. - -case $basic_machine in - score-*) - os=-elf - ;; - spu-*) - os=-elf - ;; - *-acorn) - os=-riscix1.2 - ;; - arm*-rebel) - os=-linux - ;; - arm*-semi) - os=-aout - ;; - c4x-* | tic4x-*) - os=-coff - ;; - tic54x-*) - os=-coff - ;; - tic55x-*) - os=-coff - ;; - tic6x-*) - os=-coff - ;; - # This must come before the *-dec entry. - pdp10-*) - os=-tops20 - ;; - pdp11-*) - os=-none - ;; - *-dec | vax-*) - os=-ultrix4.2 - ;; - m68*-apollo) - os=-domain - ;; - i386-sun) - os=-sunos4.0.2 - ;; - m68000-sun) - os=-sunos3 - ;; - m68*-cisco) - os=-aout - ;; - mep-*) - os=-elf - ;; - mips*-cisco) - os=-elf - ;; - mips*-*) - os=-elf - ;; - or32-*) - os=-coff - ;; - *-tti) # must be before sparc entry or we get the wrong os. - os=-sysv3 - ;; - sparc-* | *-sun) - os=-sunos4.1.1 - ;; - pru-*) - os=-elf - ;; - *-be) - os=-beos - ;; - *-haiku) - os=-haiku - ;; - *-ibm) - os=-aix - ;; - *-knuth) - os=-mmixware - ;; - *-wec) - os=-proelf - ;; - *-winbond) - os=-proelf - ;; - *-oki) - os=-proelf - ;; - *-hp) - os=-hpux - ;; - *-hitachi) - os=-hiux - ;; - i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) - os=-sysv - ;; - *-cbm) - os=-amigaos - ;; - *-dg) - os=-dgux - ;; - *-dolphin) - os=-sysv3 - ;; - m68k-ccur) - os=-rtu - ;; - m88k-omron*) - os=-luna - ;; - *-next ) - os=-nextstep - ;; - *-sequent) - os=-ptx - ;; - *-crds) - os=-unos - ;; - *-ns) - os=-genix - ;; - i370-*) - os=-mvs - ;; - *-next) - os=-nextstep3 - ;; - *-gould) - os=-sysv - ;; - *-highlevel) - os=-bsd - ;; - *-encore) - os=-bsd - ;; - *-sgi) - os=-irix - ;; - *-siemens) - os=-sysv4 - ;; - *-masscomp) - os=-rtu - ;; - f30[01]-fujitsu | f700-fujitsu) - os=-uxpv - ;; - *-rom68k) - os=-coff - ;; - *-*bug) - os=-coff - ;; - *-apple) - os=-macos - ;; - *-atari*) - os=-mint - ;; - *) - os=-none - ;; -esac -fi - -# Here we handle the case where we know the os, and the CPU type, but not the -# manufacturer. We pick the logical manufacturer. -vendor=unknown -case $basic_machine in - *-unknown) - case $os in - -riscix*) - vendor=acorn - ;; - -sunos*) - vendor=sun - ;; - -cnk*|-aix*) - vendor=ibm - ;; - -beos*) - vendor=be - ;; - -hpux*) - vendor=hp - ;; - -mpeix*) - vendor=hp - ;; - -hiux*) - vendor=hitachi - ;; - -unos*) - vendor=crds - ;; - -dgux*) - vendor=dg - ;; - -luna*) - vendor=omron - ;; - -genix*) - vendor=ns - ;; - -mvs* | -opened*) - vendor=ibm - ;; - -os400*) - vendor=ibm - ;; - -ptx*) - vendor=sequent - ;; - -tpf*) - vendor=ibm - ;; - -vxsim* | -vxworks* | -windiss*) - vendor=wrs - ;; - -aux*) - vendor=apple - ;; - -hms*) - vendor=hitachi - ;; - -mpw* | -macos*) - vendor=apple - ;; - -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) - vendor=atari - ;; - -vos*) - vendor=stratus - ;; - esac - basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` - ;; -esac - -echo $basic_machine$os -exit - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "timestamp='" -# time-stamp-format: "%:y-%02m-%02d" -# time-stamp-end: "'" -# End: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/libtool.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/libtool.m4 deleted file mode 100644 index 4ceb7f1..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/libtool.m4 +++ /dev/null @@ -1,7309 +0,0 @@ -# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- -# -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, -# 2006, 2007, 2008 Free Software Foundation, Inc. -# Written by Gordon Matzigkeit, 1996 -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -m4_define([_LT_COPYING], [dnl -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, -# 2006, 2007, 2008 Free Software Foundation, Inc. -# Written by Gordon Matzigkeit, 1996 -# -# This file is part of GNU Libtool. -# -# GNU Libtool is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as -# published by the Free Software Foundation; either version 2 of -# the License, or (at your option) any later version. -# -# As a special exception to the GNU General Public License, -# if you distribute this file as part of a program or library that -# is built using GNU Libtool, you may include this file under the -# same distribution terms that you use for the rest of that program. -# -# GNU Libtool is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with GNU Libtool; see the file COPYING. If not, a copy -# can be downloaded from http://www.gnu.org/licenses/gpl.html, or -# obtained by writing to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -]) - -# serial 56 LT_INIT - - -# LT_PREREQ(VERSION) -# ------------------ -# Complain and exit if this libtool version is less that VERSION. -m4_defun([LT_PREREQ], -[m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, - [m4_default([$3], - [m4_fatal([Libtool version $1 or higher is required], - 63)])], - [$2])]) - - -# _LT_CHECK_BUILDDIR -# ------------------ -# Complain if the absolute build directory name contains unusual characters -m4_defun([_LT_CHECK_BUILDDIR], -[case `pwd` in - *\ * | *\ *) - AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; -esac -]) - - -# LT_INIT([OPTIONS]) -# ------------------ -AC_DEFUN([LT_INIT], -[AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT -AC_BEFORE([$0], [LT_LANG])dnl -AC_BEFORE([$0], [LT_OUTPUT])dnl -AC_BEFORE([$0], [LTDL_INIT])dnl -m4_require([_LT_CHECK_BUILDDIR])dnl - -dnl Autoconf doesn't catch unexpanded LT_ macros by default: -m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl -m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl -dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 -dnl unless we require an AC_DEFUNed macro: -AC_REQUIRE([LTOPTIONS_VERSION])dnl -AC_REQUIRE([LTSUGAR_VERSION])dnl -AC_REQUIRE([LTVERSION_VERSION])dnl -AC_REQUIRE([LTOBSOLETE_VERSION])dnl -m4_require([_LT_PROG_LTMAIN])dnl - -dnl Parse OPTIONS -_LT_SET_OPTIONS([$0], [$1]) - -# This can be used to rebuild libtool when needed -LIBTOOL_DEPS="$ltmain" - -# Always use our own libtool. -LIBTOOL='$(SHELL) $(top_builddir)/libtool' -AC_SUBST(LIBTOOL)dnl - -_LT_SETUP - -# Only expand once: -m4_define([LT_INIT]) -])# LT_INIT - -# Old names: -AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) -AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_PROG_LIBTOOL], []) -dnl AC_DEFUN([AM_PROG_LIBTOOL], []) - - -# _LT_CC_BASENAME(CC) -# ------------------- -# Calculate cc_basename. Skip known compiler wrappers and cross-prefix. -m4_defun([_LT_CC_BASENAME], -[for cc_temp in $1""; do - case $cc_temp in - compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; - distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; - \-*) ;; - *) break;; - esac -done -cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` -]) - - -# _LT_FILEUTILS_DEFAULTS -# ---------------------- -# It is okay to use these file commands and assume they have been set -# sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. -m4_defun([_LT_FILEUTILS_DEFAULTS], -[: ${CP="cp -f"} -: ${MV="mv -f"} -: ${RM="rm -f"} -])# _LT_FILEUTILS_DEFAULTS - - -# _LT_SETUP -# --------- -m4_defun([_LT_SETUP], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -AC_REQUIRE([AC_CANONICAL_BUILD])dnl -_LT_DECL([], [host_alias], [0], [The host system])dnl -_LT_DECL([], [host], [0])dnl -_LT_DECL([], [host_os], [0])dnl -dnl -_LT_DECL([], [build_alias], [0], [The build system])dnl -_LT_DECL([], [build], [0])dnl -_LT_DECL([], [build_os], [0])dnl -dnl -AC_REQUIRE([AC_PROG_CC])dnl -AC_REQUIRE([LT_PATH_LD])dnl -AC_REQUIRE([LT_PATH_NM])dnl -dnl -AC_REQUIRE([AC_PROG_LN_S])dnl -test -z "$LN_S" && LN_S="ln -s" -_LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl -dnl -AC_REQUIRE([LT_CMD_MAX_LEN])dnl -_LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl -_LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl -dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_CHECK_SHELL_FEATURES])dnl -m4_require([_LT_CMD_RELOAD])dnl -m4_require([_LT_CHECK_MAGIC_METHOD])dnl -m4_require([_LT_CMD_OLD_ARCHIVE])dnl -m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl - -_LT_CONFIG_LIBTOOL_INIT([ -# See if we are running on zsh, and set the options which allow our -# commands through without removal of \ escapes INIT. -if test -n "\${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi -]) -if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi - -_LT_CHECK_OBJDIR - -m4_require([_LT_TAG_COMPILER])dnl -_LT_PROG_ECHO_BACKSLASH - -case $host_os in -aix3*) - # AIX sometimes has problems with the GCC collect2 program. For some - # reason, if we set the COLLECT_NAMES environment variable, the problems - # vanish in a puff of smoke. - if test "X${COLLECT_NAMES+set}" != Xset; then - COLLECT_NAMES= - export COLLECT_NAMES - fi - ;; -esac - -# Sed substitution that helps us do robust quoting. It backslashifies -# metacharacters that are still active within double-quoted strings. -sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' - -# Same as above, but do not quote variable references. -double_quote_subst='s/\([["`\\]]\)/\\\1/g' - -# Sed substitution to delay expansion of an escaped shell variable in a -# double_quote_subst'ed string. -delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' - -# Sed substitution to delay expansion of an escaped single quote. -delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' - -# Sed substitution to avoid accidental globbing in evaled expressions -no_glob_subst='s/\*/\\\*/g' - -# Global variables: -ofile=libtool -can_build_shared=yes - -# All known linkers require a `.a' archive for static linking (except MSVC, -# which needs '.lib'). -libext=a - -with_gnu_ld="$lt_cv_prog_gnu_ld" - -old_CC="$CC" -old_CFLAGS="$CFLAGS" - -# Set sane defaults for various variables -test -z "$CC" && CC=cc -test -z "$LTCC" && LTCC=$CC -test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS -test -z "$LD" && LD=ld -test -z "$ac_objext" && ac_objext=o - -_LT_CC_BASENAME([$compiler]) - -# Only perform the check for file, if the check method requires it -test -z "$MAGIC_CMD" && MAGIC_CMD=file -case $deplibs_check_method in -file_magic*) - if test "$file_magic_cmd" = '$MAGIC_CMD'; then - _LT_PATH_MAGIC - fi - ;; -esac - -# Use C for the default configuration in the libtool script -LT_SUPPORTED_TAG([CC]) -_LT_LANG_C_CONFIG -_LT_LANG_DEFAULT_CONFIG -_LT_CONFIG_COMMANDS -])# _LT_SETUP - - -# _LT_PROG_LTMAIN -# --------------- -# Note that this code is called both from `configure', and `config.status' -# now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, -# `config.status' has no value for ac_aux_dir unless we are using Automake, -# so we pass a copy along to make sure it has a sensible value anyway. -m4_defun([_LT_PROG_LTMAIN], -[m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl -_LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) -ltmain="$ac_aux_dir/ltmain.sh" -])# _LT_PROG_LTMAIN - - -## ------------------------------------- ## -## Accumulate code for creating libtool. ## -## ------------------------------------- ## - -# So that we can recreate a full libtool script including additional -# tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS -# in macros and then make a single call at the end using the `libtool' -# label. - - -# _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) -# ---------------------------------------- -# Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. -m4_define([_LT_CONFIG_LIBTOOL_INIT], -[m4_ifval([$1], - [m4_append([_LT_OUTPUT_LIBTOOL_INIT], - [$1 -])])]) - -# Initialize. -m4_define([_LT_OUTPUT_LIBTOOL_INIT]) - - -# _LT_CONFIG_LIBTOOL([COMMANDS]) -# ------------------------------ -# Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. -m4_define([_LT_CONFIG_LIBTOOL], -[m4_ifval([$1], - [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], - [$1 -])])]) - -# Initialize. -m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) - - -# _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) -# ----------------------------------------------------- -m4_defun([_LT_CONFIG_SAVE_COMMANDS], -[_LT_CONFIG_LIBTOOL([$1]) -_LT_CONFIG_LIBTOOL_INIT([$2]) -]) - - -# _LT_FORMAT_COMMENT([COMMENT]) -# ----------------------------- -# Add leading comment marks to the start of each line, and a trailing -# full-stop to the whole comment if one is not present already. -m4_define([_LT_FORMAT_COMMENT], -[m4_ifval([$1], [ -m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], - [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) -)]) - - - -## ------------------------ ## -## FIXME: Eliminate VARNAME ## -## ------------------------ ## - - -# _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) -# ------------------------------------------------------------------- -# CONFIGNAME is the name given to the value in the libtool script. -# VARNAME is the (base) name used in the configure script. -# VALUE may be 0, 1 or 2 for a computed quote escaped value based on -# VARNAME. Any other value will be used directly. -m4_define([_LT_DECL], -[lt_if_append_uniq([lt_decl_varnames], [$2], [, ], - [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], - [m4_ifval([$1], [$1], [$2])]) - lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) - m4_ifval([$4], - [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) - lt_dict_add_subkey([lt_decl_dict], [$2], - [tagged?], [m4_ifval([$5], [yes], [no])])]) -]) - - -# _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) -# -------------------------------------------------------- -m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) - - -# lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) -# ------------------------------------------------ -m4_define([lt_decl_tag_varnames], -[_lt_decl_filter([tagged?], [yes], $@)]) - - -# _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) -# --------------------------------------------------------- -m4_define([_lt_decl_filter], -[m4_case([$#], - [0], [m4_fatal([$0: too few arguments: $#])], - [1], [m4_fatal([$0: too few arguments: $#: $1])], - [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], - [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], - [lt_dict_filter([lt_decl_dict], $@)])[]dnl -]) - - -# lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) -# -------------------------------------------------- -m4_define([lt_decl_quote_varnames], -[_lt_decl_filter([value], [1], $@)]) - - -# lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) -# --------------------------------------------------- -m4_define([lt_decl_dquote_varnames], -[_lt_decl_filter([value], [2], $@)]) - - -# lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) -# --------------------------------------------------- -m4_define([lt_decl_varnames_tagged], -[_$0(m4_quote(m4_default([$1], [[, ]])), - m4_quote(m4_if([$2], [], - m4_quote(lt_decl_tag_varnames), - m4_quote(m4_shift($@)))), - m4_split(m4_normalize(m4_quote(_LT_TAGS))))]) -m4_define([_lt_decl_varnames_tagged], [lt_combine([$1], [$2], [_], $3)]) - - -# lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) -# ------------------------------------------------ -m4_define([lt_decl_all_varnames], -[_$0(m4_quote(m4_default([$1], [[, ]])), - m4_if([$2], [], - m4_quote(lt_decl_varnames), - m4_quote(m4_shift($@))))[]dnl -]) -m4_define([_lt_decl_all_varnames], -[lt_join($@, lt_decl_varnames_tagged([$1], - lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl -]) - - -# _LT_CONFIG_STATUS_DECLARE([VARNAME]) -# ------------------------------------ -# Quote a variable value, and forward it to `config.status' so that its -# declaration there will have the same value as in `configure'. VARNAME -# must have a single quote delimited value for this to work. -m4_define([_LT_CONFIG_STATUS_DECLARE], -[$1='`$ECHO "X$][$1" | $Xsed -e "$delay_single_quote_subst"`']) - - -# _LT_CONFIG_STATUS_DECLARATIONS -# ------------------------------ -# We delimit libtool config variables with single quotes, so when -# we write them to config.status, we have to be sure to quote all -# embedded single quotes properly. In configure, this macro expands -# each variable declared with _LT_DECL (and _LT_TAGDECL) into: -# -# ='`$ECHO "X$" | $Xsed -e "$delay_single_quote_subst"`' -m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], -[m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), - [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) - - -# _LT_LIBTOOL_TAGS -# ---------------- -# Output comment and list of tags supported by the script -m4_defun([_LT_LIBTOOL_TAGS], -[_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl -available_tags="_LT_TAGS"dnl -]) - - -# _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) -# ----------------------------------- -# Extract the dictionary values for VARNAME (optionally with TAG) and -# expand to a commented shell variable setting: -# -# # Some comment about what VAR is for. -# visible_name=$lt_internal_name -m4_define([_LT_LIBTOOL_DECLARE], -[_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], - [description])))[]dnl -m4_pushdef([_libtool_name], - m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl -m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), - [0], [_libtool_name=[$]$1], - [1], [_libtool_name=$lt_[]$1], - [2], [_libtool_name=$lt_[]$1], - [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl -m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl -]) - - -# _LT_LIBTOOL_CONFIG_VARS -# ----------------------- -# Produce commented declarations of non-tagged libtool config variables -# suitable for insertion in the LIBTOOL CONFIG section of the `libtool' -# script. Tagged libtool config variables (even for the LIBTOOL CONFIG -# section) are produced by _LT_LIBTOOL_TAG_VARS. -m4_defun([_LT_LIBTOOL_CONFIG_VARS], -[m4_foreach([_lt_var], - m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), - [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) - - -# _LT_LIBTOOL_TAG_VARS(TAG) -# ------------------------- -m4_define([_LT_LIBTOOL_TAG_VARS], -[m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), - [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) - - -# _LT_TAGVAR(VARNAME, [TAGNAME]) -# ------------------------------ -m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) - - -# _LT_CONFIG_COMMANDS -# ------------------- -# Send accumulated output to $CONFIG_STATUS. Thanks to the lists of -# variables for single and double quote escaping we saved from calls -# to _LT_DECL, we can put quote escaped variables declarations -# into `config.status', and then the shell code to quote escape them in -# for loops in `config.status'. Finally, any additional code accumulated -# from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. -m4_defun([_LT_CONFIG_COMMANDS], -[AC_PROVIDE_IFELSE([LT_OUTPUT], - dnl If the libtool generation code has been placed in $CONFIG_LT, - dnl instead of duplicating it all over again into config.status, - dnl then we will have config.status run $CONFIG_LT later, so it - dnl needs to know what name is stored there: - [AC_CONFIG_COMMANDS([libtool], - [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], - dnl If the libtool generation code is destined for config.status, - dnl expand the accumulated commands and init code now: - [AC_CONFIG_COMMANDS([libtool], - [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) -])#_LT_CONFIG_COMMANDS - - -# Initialize. -m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], -[ - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -sed_quote_subst='$sed_quote_subst' -double_quote_subst='$double_quote_subst' -delay_variable_subst='$delay_variable_subst' -_LT_CONFIG_STATUS_DECLARATIONS -LTCC='$LTCC' -LTCFLAGS='$LTCFLAGS' -compiler='$compiler_DEFAULT' - -# Quote evaled strings. -for var in lt_decl_all_varnames([[ \ -]], lt_decl_quote_varnames); do - case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in - *[[\\\\\\\`\\"\\\$]]*) - eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" - ;; - *) - eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" - ;; - esac -done - -# Double-quote double-evaled strings. -for var in lt_decl_all_varnames([[ \ -]], lt_decl_dquote_varnames); do - case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in - *[[\\\\\\\`\\"\\\$]]*) - eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" - ;; - *) - eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" - ;; - esac -done - -# Fix-up fallback echo if it was mangled by the above quoting rules. -case \$lt_ECHO in -*'\\\[$]0 --fallback-echo"')dnl " - lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\[$]0 --fallback-echo"\[$]/\[$]0 --fallback-echo"/'\` - ;; -esac - -_LT_OUTPUT_LIBTOOL_INIT -]) - - -# LT_OUTPUT -# --------- -# This macro allows early generation of the libtool script (before -# AC_OUTPUT is called), incase it is used in configure for compilation -# tests. -AC_DEFUN([LT_OUTPUT], -[: ${CONFIG_LT=./config.lt} -AC_MSG_NOTICE([creating $CONFIG_LT]) -cat >"$CONFIG_LT" <<_LTEOF -#! $SHELL -# Generated by $as_me. -# Run this file to recreate a libtool stub with the current configuration. - -lt_cl_silent=false -SHELL=\${CONFIG_SHELL-$SHELL} -_LTEOF - -cat >>"$CONFIG_LT" <<\_LTEOF -AS_SHELL_SANITIZE -_AS_PREPARE - -exec AS_MESSAGE_FD>&1 -exec AS_MESSAGE_LOG_FD>>config.log -{ - echo - AS_BOX([Running $as_me.]) -} >&AS_MESSAGE_LOG_FD - -lt_cl_help="\ -\`$as_me' creates a local libtool stub from the current configuration, -for use in further configure time tests before the real libtool is -generated. - -Usage: $[0] [[OPTIONS]] - - -h, --help print this help, then exit - -V, --version print version number, then exit - -q, --quiet do not print progress messages - -d, --debug don't remove temporary files - -Report bugs to ." - -lt_cl_version="\ -m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl -m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) -configured by $[0], generated by m4_PACKAGE_STRING. - -Copyright (C) 2008 Free Software Foundation, Inc. -This config.lt script is free software; the Free Software Foundation -gives unlimited permision to copy, distribute and modify it." - -while test $[#] != 0 -do - case $[1] in - --version | --v* | -V ) - echo "$lt_cl_version"; exit 0 ;; - --help | --h* | -h ) - echo "$lt_cl_help"; exit 0 ;; - --debug | --d* | -d ) - debug=: ;; - --quiet | --q* | --silent | --s* | -q ) - lt_cl_silent=: ;; - - -*) AC_MSG_ERROR([unrecognized option: $[1] -Try \`$[0] --help' for more information.]) ;; - - *) AC_MSG_ERROR([unrecognized argument: $[1] -Try \`$[0] --help' for more information.]) ;; - esac - shift -done - -if $lt_cl_silent; then - exec AS_MESSAGE_FD>/dev/null -fi -_LTEOF - -cat >>"$CONFIG_LT" <<_LTEOF -_LT_OUTPUT_LIBTOOL_COMMANDS_INIT -_LTEOF - -cat >>"$CONFIG_LT" <<\_LTEOF -AC_MSG_NOTICE([creating $ofile]) -_LT_OUTPUT_LIBTOOL_COMMANDS -AS_EXIT(0) -_LTEOF -chmod +x "$CONFIG_LT" - -# configure is writing to config.log, but config.lt does its own redirection, -# appending to config.log, which fails on DOS, as config.log is still kept -# open by configure. Here we exec the FD to /dev/null, effectively closing -# config.log, so it can be properly (re)opened and appended to by config.lt. -if test "$no_create" != yes; then - lt_cl_success=: - test "$silent" = yes && - lt_config_lt_args="$lt_config_lt_args --quiet" - exec AS_MESSAGE_LOG_FD>/dev/null - $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false - exec AS_MESSAGE_LOG_FD>>config.log - $lt_cl_success || AS_EXIT(1) -fi -])# LT_OUTPUT - - -# _LT_CONFIG(TAG) -# --------------- -# If TAG is the built-in tag, create an initial libtool script with a -# default configuration from the untagged config vars. Otherwise add code -# to config.status for appending the configuration named by TAG from the -# matching tagged config vars. -m4_defun([_LT_CONFIG], -[m4_require([_LT_FILEUTILS_DEFAULTS])dnl -_LT_CONFIG_SAVE_COMMANDS([ - m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl - m4_if(_LT_TAG, [C], [ - # See if we are running on zsh, and set the options which allow our - # commands through without removal of \ escapes. - if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST - fi - - cfgfile="${ofile}T" - trap "$RM \"$cfgfile\"; exit 1" 1 2 15 - $RM "$cfgfile" - - cat <<_LT_EOF >> "$cfgfile" -#! $SHELL - -# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. -# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION -# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: -# NOTE: Changes made to this file will be lost: look at ltmain.sh. -# -_LT_COPYING -_LT_LIBTOOL_TAGS - -# ### BEGIN LIBTOOL CONFIG -_LT_LIBTOOL_CONFIG_VARS -_LT_LIBTOOL_TAG_VARS -# ### END LIBTOOL CONFIG - -_LT_EOF - - case $host_os in - aix3*) - cat <<\_LT_EOF >> "$cfgfile" -# AIX sometimes has problems with the GCC collect2 program. For some -# reason, if we set the COLLECT_NAMES environment variable, the problems -# vanish in a puff of smoke. -if test "X${COLLECT_NAMES+set}" != Xset; then - COLLECT_NAMES= - export COLLECT_NAMES -fi -_LT_EOF - ;; - esac - - _LT_PROG_LTMAIN - - # We use sed instead of cat because bash on DJGPP gets confused if - # if finds mixed CR/LF and LF-only lines. Since sed operates in - # text mode, it properly converts lines to CR/LF. This bash problem - # is reportedly fixed, but why not run on old versions too? - sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \ - || (rm -f "$cfgfile"; exit 1) - - _LT_PROG_XSI_SHELLFNS - - sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \ - || (rm -f "$cfgfile"; exit 1) - - mv -f "$cfgfile" "$ofile" || - (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") - chmod +x "$ofile" -], -[cat <<_LT_EOF >> "$ofile" - -dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded -dnl in a comment (ie after a #). -# ### BEGIN LIBTOOL TAG CONFIG: $1 -_LT_LIBTOOL_TAG_VARS(_LT_TAG) -# ### END LIBTOOL TAG CONFIG: $1 -_LT_EOF -])dnl /m4_if -], -[m4_if([$1], [], [ - PACKAGE='$PACKAGE' - VERSION='$VERSION' - TIMESTAMP='$TIMESTAMP' - RM='$RM' - ofile='$ofile'], []) -])dnl /_LT_CONFIG_SAVE_COMMANDS -])# _LT_CONFIG - - -# LT_SUPPORTED_TAG(TAG) -# --------------------- -# Trace this macro to discover what tags are supported by the libtool -# --tag option, using: -# autoconf --trace 'LT_SUPPORTED_TAG:$1' -AC_DEFUN([LT_SUPPORTED_TAG], []) - - -# C support is built-in for now -m4_define([_LT_LANG_C_enabled], []) -m4_define([_LT_TAGS], []) - - -# LT_LANG(LANG) -# ------------- -# Enable libtool support for the given language if not already enabled. -AC_DEFUN([LT_LANG], -[AC_BEFORE([$0], [LT_OUTPUT])dnl -m4_case([$1], - [C], [_LT_LANG(C)], - [C++], [_LT_LANG(CXX)], - [Java], [_LT_LANG(GCJ)], - [Fortran 77], [_LT_LANG(F77)], - [Fortran], [_LT_LANG(FC)], - [Windows Resource], [_LT_LANG(RC)], - [m4_ifdef([_LT_LANG_]$1[_CONFIG], - [_LT_LANG($1)], - [m4_fatal([$0: unsupported language: "$1"])])])dnl -])# LT_LANG - - -# _LT_LANG(LANGNAME) -# ------------------ -m4_defun([_LT_LANG], -[m4_ifdef([_LT_LANG_]$1[_enabled], [], - [LT_SUPPORTED_TAG([$1])dnl - m4_append([_LT_TAGS], [$1 ])dnl - m4_define([_LT_LANG_]$1[_enabled], [])dnl - _LT_LANG_$1_CONFIG($1)])dnl -])# _LT_LANG - - -# _LT_LANG_DEFAULT_CONFIG -# ----------------------- -m4_defun([_LT_LANG_DEFAULT_CONFIG], -[AC_PROVIDE_IFELSE([AC_PROG_CXX], - [LT_LANG(CXX)], - [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) - -AC_PROVIDE_IFELSE([AC_PROG_F77], - [LT_LANG(F77)], - [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) - -AC_PROVIDE_IFELSE([AC_PROG_FC], - [LT_LANG(FC)], - [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) - -dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal -dnl pulling things in needlessly. -AC_PROVIDE_IFELSE([AC_PROG_GCJ], - [LT_LANG(GCJ)], - [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], - [LT_LANG(GCJ)], - [AC_PROVIDE_IFELSE([LT_PROG_GCJ], - [LT_LANG(GCJ)], - [m4_ifdef([AC_PROG_GCJ], - [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) - m4_ifdef([A][M_PROG_GCJ], - [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) - m4_ifdef([LT_PROG_GCJ], - [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) - -AC_PROVIDE_IFELSE([LT_PROG_RC], - [LT_LANG(RC)], - [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) -])# _LT_LANG_DEFAULT_CONFIG - -# Obsolete macros: -AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) -AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) -AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) -AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_CXX], []) -dnl AC_DEFUN([AC_LIBTOOL_F77], []) -dnl AC_DEFUN([AC_LIBTOOL_FC], []) -dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) - - -# _LT_TAG_COMPILER -# ---------------- -m4_defun([_LT_TAG_COMPILER], -[AC_REQUIRE([AC_PROG_CC])dnl - -_LT_DECL([LTCC], [CC], [1], [A C compiler])dnl -_LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl -_LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl -_LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl - -# If no C compiler was specified, use CC. -LTCC=${LTCC-"$CC"} - -# If no C compiler flags were specified, use CFLAGS. -LTCFLAGS=${LTCFLAGS-"$CFLAGS"} - -# Allow CC to be a program name with arguments. -compiler=$CC -])# _LT_TAG_COMPILER - - -# _LT_COMPILER_BOILERPLATE -# ------------------------ -# Check for compiler boilerplate output or warnings with -# the simple compiler test code. -m4_defun([_LT_COMPILER_BOILERPLATE], -[m4_require([_LT_DECL_SED])dnl -ac_outfile=conftest.$ac_objext -echo "$lt_simple_compile_test_code" >conftest.$ac_ext -eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err -_lt_compiler_boilerplate=`cat conftest.err` -$RM conftest* -])# _LT_COMPILER_BOILERPLATE - - -# _LT_LINKER_BOILERPLATE -# ---------------------- -# Check for linker boilerplate output or warnings with -# the simple link test code. -m4_defun([_LT_LINKER_BOILERPLATE], -[m4_require([_LT_DECL_SED])dnl -ac_outfile=conftest.$ac_objext -echo "$lt_simple_link_test_code" >conftest.$ac_ext -eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err -_lt_linker_boilerplate=`cat conftest.err` -$RM -r conftest* -])# _LT_LINKER_BOILERPLATE - -# _LT_REQUIRED_DARWIN_CHECKS -# ------------------------- -m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ - case $host_os in - rhapsody* | darwin*) - AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) - AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) - AC_CHECK_TOOL([LIPO], [lipo], [:]) - AC_CHECK_TOOL([OTOOL], [otool], [:]) - AC_CHECK_TOOL([OTOOL64], [otool64], [:]) - _LT_DECL([], [DSYMUTIL], [1], - [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) - _LT_DECL([], [NMEDIT], [1], - [Tool to change global to local symbols on Mac OS X]) - _LT_DECL([], [LIPO], [1], - [Tool to manipulate fat objects and archives on Mac OS X]) - _LT_DECL([], [OTOOL], [1], - [ldd/readelf like tool for Mach-O binaries on Mac OS X]) - _LT_DECL([], [OTOOL64], [1], - [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) - - AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], - [lt_cv_apple_cc_single_mod=no - if test -z "${LT_MULTI_MODULE}"; then - # By default we will add the -single_module flag. You can override - # by either setting the environment variable LT_MULTI_MODULE - # non-empty at configure time, or by adding -multi_module to the - # link flags. - rm -rf libconftest.dylib* - echo "int foo(void){return 1;}" > conftest.c - echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ --dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD - $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ - -dynamiclib -Wl,-single_module conftest.c 2>conftest.err - _lt_result=$? - if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then - lt_cv_apple_cc_single_mod=yes - else - cat conftest.err >&AS_MESSAGE_LOG_FD - fi - rm -rf libconftest.dylib* - rm -f conftest.* - fi]) - AC_CACHE_CHECK([for -exported_symbols_list linker flag], - [lt_cv_ld_exported_symbols_list], - [lt_cv_ld_exported_symbols_list=no - save_LDFLAGS=$LDFLAGS - echo "_main" > conftest.sym - LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" - AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], - [lt_cv_ld_exported_symbols_list=yes], - [lt_cv_ld_exported_symbols_list=no]) - LDFLAGS="$save_LDFLAGS" - ]) - case $host_os in - rhapsody* | darwin1.[[012]]) - _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; - darwin1.*) - _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; - darwin*) # darwin 5.x on - # if running on 10.5 or later, the deployment target defaults - # to the OS version, if on x86, and 10.4, the deployment - # target defaults to 10.4. Don't you love it? - case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in - 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) - _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; - 10.[[012]]*) - _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; - 10.*) - _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; - esac - ;; - esac - if test "$lt_cv_apple_cc_single_mod" = "yes"; then - _lt_dar_single_mod='$single_module' - fi - if test "$lt_cv_ld_exported_symbols_list" = "yes"; then - _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' - else - _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' - fi - if test "$DSYMUTIL" != ":"; then - _lt_dsymutil='~$DSYMUTIL $lib || :' - else - _lt_dsymutil= - fi - ;; - esac -]) - - -# _LT_DARWIN_LINKER_FEATURES -# -------------------------- -# Checks for linker and compiler features on darwin -m4_defun([_LT_DARWIN_LINKER_FEATURES], -[ - m4_require([_LT_REQUIRED_DARWIN_CHECKS]) - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_automatic, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported - _LT_TAGVAR(whole_archive_flag_spec, $1)='' - _LT_TAGVAR(link_all_deplibs, $1)=yes - _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" - if test "$GCC" = "yes"; then - output_verbose_link_cmd=echo - _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" - _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" - _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" - _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" - m4_if([$1], [CXX], -[ if test "$lt_cv_apple_cc_single_mod" != "yes"; then - _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" - _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" - fi -],[]) - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi -]) - -# _LT_SYS_MODULE_PATH_AIX -# ----------------------- -# Links a minimal program and checks the executable -# for the system default hardcoded library path. In most cases, -# this is /usr/lib:/lib, but when the MPI compilers are used -# the location of the communication and MPI libs are included too. -# If we don't find anything, use the default library path according -# to the aix ld manual. -m4_defun([_LT_SYS_MODULE_PATH_AIX], -[m4_require([_LT_DECL_SED])dnl -AC_LINK_IFELSE(AC_LANG_PROGRAM,[ -lt_aix_libpath_sed=' - /Import File Strings/,/^$/ { - /^0/ { - s/^0 *\(.*\)$/\1/ - p - } - }' -aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -# Check for a 64-bit object if we didn't find anything. -if test -z "$aix_libpath"; then - aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -fi],[]) -if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi -])# _LT_SYS_MODULE_PATH_AIX - - -# _LT_SHELL_INIT(ARG) -# ------------------- -m4_define([_LT_SHELL_INIT], -[ifdef([AC_DIVERSION_NOTICE], - [AC_DIVERT_PUSH(AC_DIVERSION_NOTICE)], - [AC_DIVERT_PUSH(NOTICE)]) -$1 -AC_DIVERT_POP -])# _LT_SHELL_INIT - - -# _LT_PROG_ECHO_BACKSLASH -# ----------------------- -# Add some code to the start of the generated configure script which -# will find an echo command which doesn't interpret backslashes. -m4_defun([_LT_PROG_ECHO_BACKSLASH], -[_LT_SHELL_INIT([ -# Check that we are running under the correct shell. -SHELL=${CONFIG_SHELL-/bin/sh} - -case X$lt_ECHO in -X*--fallback-echo) - # Remove one level of quotation (which was required for Make). - ECHO=`echo "$lt_ECHO" | sed 's,\\\\\[$]\\[$]0,'[$]0','` - ;; -esac - -ECHO=${lt_ECHO-echo} -if test "X[$]1" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift -elif test "X[$]1" = X--fallback-echo; then - # Avoid inline document here, it may be left over - : -elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then - # Yippee, $ECHO works! - : -else - # Restart under the correct shell. - exec $SHELL "[$]0" --no-reexec ${1+"[$]@"} -fi - -if test "X[$]1" = X--fallback-echo; then - # used as fallback echo - shift - cat <<_LT_EOF -[$]* -_LT_EOF - exit 0 -fi - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -if test -z "$lt_ECHO"; then - if test "X${echo_test_string+set}" != Xset; then - # find a string as large as possible, as long as the shell can cope with it - for cmd in 'sed 50q "[$]0"' 'sed 20q "[$]0"' 'sed 10q "[$]0"' 'sed 2q "[$]0"' 'echo test'; do - # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... - if { echo_test_string=`eval $cmd`; } 2>/dev/null && - { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null - then - break - fi - done - fi - - if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - : - else - # The Solaris, AIX, and Digital Unix default echo programs unquote - # backslashes. This makes it impossible to quote backslashes using - # echo "$something" | sed 's/\\/\\\\/g' - # - # So, first we look for a working echo in the user's PATH. - - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for dir in $PATH /usr/ucb; do - IFS="$lt_save_ifs" - if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && - test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && - echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - ECHO="$dir/echo" - break - fi - done - IFS="$lt_save_ifs" - - if test "X$ECHO" = Xecho; then - # We didn't find a better echo, so look for alternatives. - if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - # This shell has a builtin print -r that does the trick. - ECHO='print -r' - elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } && - test "X$CONFIG_SHELL" != X/bin/ksh; then - # If we have ksh, try running configure again with it. - ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} - export ORIGINAL_CONFIG_SHELL - CONFIG_SHELL=/bin/ksh - export CONFIG_SHELL - exec $CONFIG_SHELL "[$]0" --no-reexec ${1+"[$]@"} - else - # Try using printf. - ECHO='printf %s\n' - if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - # Cool, printf works - : - elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && - test "X$echo_testing_string" = 'X\t' && - echo_testing_string=`($ORIGINAL_CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL - export CONFIG_SHELL - SHELL="$CONFIG_SHELL" - export SHELL - ECHO="$CONFIG_SHELL [$]0 --fallback-echo" - elif echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo '\t') 2>/dev/null` && - test "X$echo_testing_string" = 'X\t' && - echo_testing_string=`($CONFIG_SHELL "[$]0" --fallback-echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - ECHO="$CONFIG_SHELL [$]0 --fallback-echo" - else - # maybe with a smaller string... - prev=: - - for cmd in 'echo test' 'sed 2q "[$]0"' 'sed 10q "[$]0"' 'sed 20q "[$]0"' 'sed 50q "[$]0"'; do - if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null - then - break - fi - prev="$cmd" - done - - if test "$prev" != 'sed 50q "[$]0"'; then - echo_test_string=`eval $prev` - export echo_test_string - exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "[$]0" ${1+"[$]@"} - else - # Oops. We lost completely, so just stick with echo. - ECHO=echo - fi - fi - fi - fi - fi -fi - -# Copy echo and quote the copy suitably for passing to libtool from -# the Makefile, instead of quoting the original, which is used later. -lt_ECHO=$ECHO -if test "X$lt_ECHO" = "X$CONFIG_SHELL [$]0 --fallback-echo"; then - lt_ECHO="$CONFIG_SHELL \\\$\[$]0 --fallback-echo" -fi - -AC_SUBST(lt_ECHO) -]) -_LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) -_LT_DECL([], [ECHO], [1], - [An echo program that does not interpret backslashes]) -])# _LT_PROG_ECHO_BACKSLASH - - -# _LT_ENABLE_LOCK -# --------------- -m4_defun([_LT_ENABLE_LOCK], -[AC_ARG_ENABLE([libtool-lock], - [AS_HELP_STRING([--disable-libtool-lock], - [avoid locking (might break parallel builds)])]) -test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes - -# Some flags need to be propagated to the compiler or linker for good -# libtool support. -case $host in -ia64-*-hpux*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if AC_TRY_EVAL(ac_compile); then - case `/usr/bin/file conftest.$ac_objext` in - *ELF-32*) - HPUX_IA64_MODE="32" - ;; - *ELF-64*) - HPUX_IA64_MODE="64" - ;; - esac - fi - rm -rf conftest* - ;; -*-*-irix6*) - # Find out which ABI we are using. - echo '[#]line __oline__ "configure"' > conftest.$ac_ext - if AC_TRY_EVAL(ac_compile); then - if test "$lt_cv_prog_gnu_ld" = yes; then - case `/usr/bin/file conftest.$ac_objext` in - *32-bit*) - LD="${LD-ld} -melf32bsmip" - ;; - *N32*) - LD="${LD-ld} -melf32bmipn32" - ;; - *64-bit*) - LD="${LD-ld} -melf64bmip" - ;; - esac - else - case `/usr/bin/file conftest.$ac_objext` in - *32-bit*) - LD="${LD-ld} -32" - ;; - *N32*) - LD="${LD-ld} -n32" - ;; - *64-bit*) - LD="${LD-ld} -64" - ;; - esac - fi - fi - rm -rf conftest* - ;; - -x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ -s390*-*linux*|s390*-*tpf*|sparc*-*linux*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if AC_TRY_EVAL(ac_compile); then - case `/usr/bin/file conftest.o` in - *32-bit*) - case $host in - x86_64-*kfreebsd*-gnu) - LD="${LD-ld} -m elf_i386_fbsd" - ;; - x86_64-*linux*) - LD="${LD-ld} -m elf_i386" - ;; - ppc64-*linux*|powerpc64-*linux*) - LD="${LD-ld} -m elf32ppclinux" - ;; - s390x-*linux*) - LD="${LD-ld} -m elf_s390" - ;; - sparc64-*linux*) - LD="${LD-ld} -m elf32_sparc" - ;; - esac - ;; - *64-bit*) - case $host in - x86_64-*kfreebsd*-gnu) - LD="${LD-ld} -m elf_x86_64_fbsd" - ;; - x86_64-*linux*) - LD="${LD-ld} -m elf_x86_64" - ;; - ppc*-*linux*|powerpc*-*linux*) - LD="${LD-ld} -m elf64ppc" - ;; - s390*-*linux*|s390*-*tpf*) - LD="${LD-ld} -m elf64_s390" - ;; - sparc*-*linux*) - LD="${LD-ld} -m elf64_sparc" - ;; - esac - ;; - esac - fi - rm -rf conftest* - ;; - -*-*-sco3.2v5*) - # On SCO OpenServer 5, we need -belf to get full-featured binaries. - SAVE_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS -belf" - AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, - [AC_LANG_PUSH(C) - AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) - AC_LANG_POP]) - if test x"$lt_cv_cc_needs_belf" != x"yes"; then - # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf - CFLAGS="$SAVE_CFLAGS" - fi - ;; -sparc*-*solaris*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if AC_TRY_EVAL(ac_compile); then - case `/usr/bin/file conftest.o` in - *64-bit*) - case $lt_cv_prog_gnu_ld in - yes*) LD="${LD-ld} -m elf64_sparc" ;; - *) - if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then - LD="${LD-ld} -64" - fi - ;; - esac - ;; - esac - fi - rm -rf conftest* - ;; -esac - -need_locks="$enable_libtool_lock" -])# _LT_ENABLE_LOCK - - -# _LT_CMD_OLD_ARCHIVE -# ------------------- -m4_defun([_LT_CMD_OLD_ARCHIVE], -[AC_CHECK_TOOL(AR, ar, false) -test -z "$AR" && AR=ar -test -z "$AR_FLAGS" && AR_FLAGS=cru -_LT_DECL([], [AR], [1], [The archiver]) -_LT_DECL([], [AR_FLAGS], [1]) - -AC_CHECK_TOOL(STRIP, strip, :) -test -z "$STRIP" && STRIP=: -_LT_DECL([], [STRIP], [1], [A symbol stripping program]) - -AC_CHECK_TOOL(RANLIB, ranlib, :) -test -z "$RANLIB" && RANLIB=: -_LT_DECL([], [RANLIB], [1], - [Commands used to install an old-style archive]) - -# Determine commands to create old-style static archives. -old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' -old_postinstall_cmds='chmod 644 $oldlib' -old_postuninstall_cmds= - -if test -n "$RANLIB"; then - case $host_os in - openbsd*) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" - ;; - *) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" - ;; - esac - old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" -fi -_LT_DECL([], [old_postinstall_cmds], [2]) -_LT_DECL([], [old_postuninstall_cmds], [2]) -_LT_TAGDECL([], [old_archive_cmds], [2], - [Commands used to build an old-style archive]) -])# _LT_CMD_OLD_ARCHIVE - - -# _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, -# [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) -# ---------------------------------------------------------------- -# Check whether the given compiler option works -AC_DEFUN([_LT_COMPILER_OPTION], -[m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_DECL_SED])dnl -AC_CACHE_CHECK([$1], [$2], - [$2=no - m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - lt_compiler_flag="$3" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - # The option is referenced via a variable to avoid confusing sed. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) - (eval "$lt_compile" 2>conftest.err) - ac_status=$? - cat conftest.err >&AS_MESSAGE_LOG_FD - echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD - if (exit $ac_status) && test -s "$ac_outfile"; then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings other than the usual output. - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp - $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 - if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then - $2=yes - fi - fi - $RM conftest* -]) - -if test x"[$]$2" = xyes; then - m4_if([$5], , :, [$5]) -else - m4_if([$6], , :, [$6]) -fi -])# _LT_COMPILER_OPTION - -# Old name: -AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) - - -# _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, -# [ACTION-SUCCESS], [ACTION-FAILURE]) -# ---------------------------------------------------- -# Check whether the given linker option works -AC_DEFUN([_LT_LINKER_OPTION], -[m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_DECL_SED])dnl -AC_CACHE_CHECK([$1], [$2], - [$2=no - save_LDFLAGS="$LDFLAGS" - LDFLAGS="$LDFLAGS $3" - echo "$lt_simple_link_test_code" > conftest.$ac_ext - if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then - # The linker can only warn and ignore the option if not recognized - # So say no if there are warnings - if test -s conftest.err; then - # Append any errors to the config.log. - cat conftest.err 1>&AS_MESSAGE_LOG_FD - $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp - $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 - if diff conftest.exp conftest.er2 >/dev/null; then - $2=yes - fi - else - $2=yes - fi - fi - $RM -r conftest* - LDFLAGS="$save_LDFLAGS" -]) - -if test x"[$]$2" = xyes; then - m4_if([$4], , :, [$4]) -else - m4_if([$5], , :, [$5]) -fi -])# _LT_LINKER_OPTION - -# Old name: -AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) - - -# LT_CMD_MAX_LEN -#--------------- -AC_DEFUN([LT_CMD_MAX_LEN], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -# find the maximum length of command line arguments -AC_MSG_CHECKING([the maximum length of command line arguments]) -AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl - i=0 - teststring="ABCD" - - case $build_os in - msdosdjgpp*) - # On DJGPP, this test can blow up pretty badly due to problems in libc - # (any single argument exceeding 2000 bytes causes a buffer overrun - # during glob expansion). Even if it were fixed, the result of this - # check would be larger than it should be. - lt_cv_sys_max_cmd_len=12288; # 12K is about right - ;; - - gnu*) - # Under GNU Hurd, this test is not required because there is - # no limit to the length of command line arguments. - # Libtool will interpret -1 as no limit whatsoever - lt_cv_sys_max_cmd_len=-1; - ;; - - cygwin* | mingw*) - # On Win9x/ME, this test blows up -- it succeeds, but takes - # about 5 minutes as the teststring grows exponentially. - # Worse, since 9x/ME are not pre-emptively multitasking, - # you end up with a "frozen" computer, even though with patience - # the test eventually succeeds (with a max line length of 256k). - # Instead, let's just punt: use the minimum linelength reported by - # all of the supported platforms: 8192 (on NT/2K/XP). - lt_cv_sys_max_cmd_len=8192; - ;; - - amigaos*) - # On AmigaOS with pdksh, this test takes hours, literally. - # So we just punt and use a minimum line length of 8192. - lt_cv_sys_max_cmd_len=8192; - ;; - - netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) - # This has been around since 386BSD, at least. Likely further. - if test -x /sbin/sysctl; then - lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` - elif test -x /usr/sbin/sysctl; then - lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` - else - lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs - fi - # And add a safety zone - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` - ;; - - interix*) - # We know the value 262144 and hardcode it with a safety zone (like BSD) - lt_cv_sys_max_cmd_len=196608 - ;; - - osf*) - # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure - # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not - # nice to cause kernel panics so lets avoid the loop below. - # First set a reasonable default. - lt_cv_sys_max_cmd_len=16384 - # - if test -x /sbin/sysconfig; then - case `/sbin/sysconfig -q proc exec_disable_arg_limit` in - *1*) lt_cv_sys_max_cmd_len=-1 ;; - esac - fi - ;; - sco3.2v5*) - lt_cv_sys_max_cmd_len=102400 - ;; - sysv5* | sco5v6* | sysv4.2uw2*) - kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` - if test -n "$kargmax"; then - lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` - else - lt_cv_sys_max_cmd_len=32768 - fi - ;; - *) - lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` - if test -n "$lt_cv_sys_max_cmd_len"; then - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` - else - # Make teststring a little bigger before we do anything with it. - # a 1K string should be a reasonable start. - for i in 1 2 3 4 5 6 7 8 ; do - teststring=$teststring$teststring - done - SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} - # If test is not a shell built-in, we'll probably end up computing a - # maximum length that is only half of the actual maximum length, but - # we can't tell. - while { test "X"`$SHELL [$]0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \ - = "XX$teststring$teststring"; } >/dev/null 2>&1 && - test $i != 17 # 1/2 MB should be enough - do - i=`expr $i + 1` - teststring=$teststring$teststring - done - # Only check the string length outside the loop. - lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` - teststring= - # Add a significant safety factor because C++ compilers can tack on - # massive amounts of additional arguments before passing them to the - # linker. It appears as though 1/2 is a usable value. - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` - fi - ;; - esac -]) -if test -n $lt_cv_sys_max_cmd_len ; then - AC_MSG_RESULT($lt_cv_sys_max_cmd_len) -else - AC_MSG_RESULT(none) -fi -max_cmd_len=$lt_cv_sys_max_cmd_len -_LT_DECL([], [max_cmd_len], [0], - [What is the maximum length of a command?]) -])# LT_CMD_MAX_LEN - -# Old name: -AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) - - -# _LT_HEADER_DLFCN -# ---------------- -m4_defun([_LT_HEADER_DLFCN], -[AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl -])# _LT_HEADER_DLFCN - - -# _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, -# ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) -# ---------------------------------------------------------------- -m4_defun([_LT_TRY_DLOPEN_SELF], -[m4_require([_LT_HEADER_DLFCN])dnl -if test "$cross_compiling" = yes; then : - [$4] -else - lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 - lt_status=$lt_dlunknown - cat > conftest.$ac_ext <<_LT_EOF -[#line __oline__ "configure" -#include "confdefs.h" - -#if HAVE_DLFCN_H -#include -#endif - -#include - -#ifdef RTLD_GLOBAL -# define LT_DLGLOBAL RTLD_GLOBAL -#else -# ifdef DL_GLOBAL -# define LT_DLGLOBAL DL_GLOBAL -# else -# define LT_DLGLOBAL 0 -# endif -#endif - -/* We may have to define LT_DLLAZY_OR_NOW in the command line if we - find out it does not work in some platform. */ -#ifndef LT_DLLAZY_OR_NOW -# ifdef RTLD_LAZY -# define LT_DLLAZY_OR_NOW RTLD_LAZY -# else -# ifdef DL_LAZY -# define LT_DLLAZY_OR_NOW DL_LAZY -# else -# ifdef RTLD_NOW -# define LT_DLLAZY_OR_NOW RTLD_NOW -# else -# ifdef DL_NOW -# define LT_DLLAZY_OR_NOW DL_NOW -# else -# define LT_DLLAZY_OR_NOW 0 -# endif -# endif -# endif -# endif -#endif - -#ifdef __cplusplus -extern "C" void exit (int); -#endif - -void fnord() { int i=42;} -int main () -{ - void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); - int status = $lt_dlunknown; - - if (self) - { - if (dlsym (self,"fnord")) status = $lt_dlno_uscore; - else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; - /* dlclose (self); */ - } - else - puts (dlerror ()); - - exit (status); -}] -_LT_EOF - if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then - (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null - lt_status=$? - case x$lt_status in - x$lt_dlno_uscore) $1 ;; - x$lt_dlneed_uscore) $2 ;; - x$lt_dlunknown|x*) $3 ;; - esac - else : - # compilation failed - $3 - fi -fi -rm -fr conftest* -])# _LT_TRY_DLOPEN_SELF - - -# LT_SYS_DLOPEN_SELF -# ------------------ -AC_DEFUN([LT_SYS_DLOPEN_SELF], -[m4_require([_LT_HEADER_DLFCN])dnl -if test "x$enable_dlopen" != xyes; then - enable_dlopen=unknown - enable_dlopen_self=unknown - enable_dlopen_self_static=unknown -else - lt_cv_dlopen=no - lt_cv_dlopen_libs= - - case $host_os in - beos*) - lt_cv_dlopen="load_add_on" - lt_cv_dlopen_libs= - lt_cv_dlopen_self=yes - ;; - - mingw* | pw32*) - lt_cv_dlopen="LoadLibrary" - lt_cv_dlopen_libs= - ;; - - cygwin*) - lt_cv_dlopen="dlopen" - lt_cv_dlopen_libs= - ;; - - darwin*) - # if libdl is installed we need to link against it - AC_CHECK_LIB([dl], [dlopen], - [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ - lt_cv_dlopen="dyld" - lt_cv_dlopen_libs= - lt_cv_dlopen_self=yes - ]) - ;; - - *) - AC_CHECK_FUNC([shl_load], - [lt_cv_dlopen="shl_load"], - [AC_CHECK_LIB([dld], [shl_load], - [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], - [AC_CHECK_FUNC([dlopen], - [lt_cv_dlopen="dlopen"], - [AC_CHECK_LIB([dl], [dlopen], - [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], - [AC_CHECK_LIB([svld], [dlopen], - [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], - [AC_CHECK_LIB([dld], [dld_link], - [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) - ]) - ]) - ]) - ]) - ]) - ;; - esac - - if test "x$lt_cv_dlopen" != xno; then - enable_dlopen=yes - else - enable_dlopen=no - fi - - case $lt_cv_dlopen in - dlopen) - save_CPPFLAGS="$CPPFLAGS" - test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" - - save_LDFLAGS="$LDFLAGS" - wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" - - save_LIBS="$LIBS" - LIBS="$lt_cv_dlopen_libs $LIBS" - - AC_CACHE_CHECK([whether a program can dlopen itself], - lt_cv_dlopen_self, [dnl - _LT_TRY_DLOPEN_SELF( - lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, - lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) - ]) - - if test "x$lt_cv_dlopen_self" = xyes; then - wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" - AC_CACHE_CHECK([whether a statically linked program can dlopen itself], - lt_cv_dlopen_self_static, [dnl - _LT_TRY_DLOPEN_SELF( - lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, - lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) - ]) - fi - - CPPFLAGS="$save_CPPFLAGS" - LDFLAGS="$save_LDFLAGS" - LIBS="$save_LIBS" - ;; - esac - - case $lt_cv_dlopen_self in - yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; - *) enable_dlopen_self=unknown ;; - esac - - case $lt_cv_dlopen_self_static in - yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; - *) enable_dlopen_self_static=unknown ;; - esac -fi -_LT_DECL([dlopen_support], [enable_dlopen], [0], - [Whether dlopen is supported]) -_LT_DECL([dlopen_self], [enable_dlopen_self], [0], - [Whether dlopen of programs is supported]) -_LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], - [Whether dlopen of statically linked programs is supported]) -])# LT_SYS_DLOPEN_SELF - -# Old name: -AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) - - -# _LT_COMPILER_C_O([TAGNAME]) -# --------------------------- -# Check to see if options -c and -o are simultaneously supported by compiler. -# This macro does not hard code the compiler like AC_PROG_CC_C_O. -m4_defun([_LT_COMPILER_C_O], -[m4_require([_LT_DECL_SED])dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_TAG_COMPILER])dnl -AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], - [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], - [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no - $RM -r conftest 2>/dev/null - mkdir conftest - cd conftest - mkdir out - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - - lt_compiler_flag="-o out/conftest2.$ac_objext" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:__oline__: $lt_compile\"" >&AS_MESSAGE_LOG_FD) - (eval "$lt_compile" 2>out/conftest.err) - ac_status=$? - cat out/conftest.err >&AS_MESSAGE_LOG_FD - echo "$as_me:__oline__: \$? = $ac_status" >&AS_MESSAGE_LOG_FD - if (exit $ac_status) && test -s out/conftest2.$ac_objext - then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp - $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 - if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then - _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes - fi - fi - chmod u+w . 2>&AS_MESSAGE_LOG_FD - $RM conftest* - # SGI C++ compiler will create directory out/ii_files/ for - # template instantiation - test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files - $RM out/* && rmdir out - cd .. - $RM -r conftest - $RM conftest* -]) -_LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], - [Does compiler simultaneously support -c and -o options?]) -])# _LT_COMPILER_C_O - - -# _LT_COMPILER_FILE_LOCKS([TAGNAME]) -# ---------------------------------- -# Check to see if we can do hard links to lock some files if needed -m4_defun([_LT_COMPILER_FILE_LOCKS], -[m4_require([_LT_ENABLE_LOCK])dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -_LT_COMPILER_C_O([$1]) - -hard_links="nottested" -if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then - # do not overwrite the value of need_locks provided by the user - AC_MSG_CHECKING([if we can lock with hard links]) - hard_links=yes - $RM conftest* - ln conftest.a conftest.b 2>/dev/null && hard_links=no - touch conftest.a - ln conftest.a conftest.b 2>&5 || hard_links=no - ln conftest.a conftest.b 2>/dev/null && hard_links=no - AC_MSG_RESULT([$hard_links]) - if test "$hard_links" = no; then - AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) - need_locks=warn - fi -else - need_locks=no -fi -_LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) -])# _LT_COMPILER_FILE_LOCKS - - -# _LT_CHECK_OBJDIR -# ---------------- -m4_defun([_LT_CHECK_OBJDIR], -[AC_CACHE_CHECK([for objdir], [lt_cv_objdir], -[rm -f .libs 2>/dev/null -mkdir .libs 2>/dev/null -if test -d .libs; then - lt_cv_objdir=.libs -else - # MS-DOS does not allow filenames that begin with a dot. - lt_cv_objdir=_libs -fi -rmdir .libs 2>/dev/null]) -objdir=$lt_cv_objdir -_LT_DECL([], [objdir], [0], - [The name of the directory that contains temporary libtool files])dnl -m4_pattern_allow([LT_OBJDIR])dnl -AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", - [Define to the sub-directory in which libtool stores uninstalled libraries.]) -])# _LT_CHECK_OBJDIR - - -# _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) -# -------------------------------------- -# Check hardcoding attributes. -m4_defun([_LT_LINKER_HARDCODE_LIBPATH], -[AC_MSG_CHECKING([how to hardcode library paths into programs]) -_LT_TAGVAR(hardcode_action, $1)= -if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || - test -n "$_LT_TAGVAR(runpath_var, $1)" || - test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then - - # We can hardcode non-existent directories. - if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && - # If the only mechanism to avoid hardcoding is shlibpath_var, we - # have to relink, otherwise we might link with an installed library - # when we should be linking with a yet-to-be-installed one - ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && - test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then - # Linking always hardcodes the temporary library directory. - _LT_TAGVAR(hardcode_action, $1)=relink - else - # We can link without hardcoding, and we can hardcode nonexisting dirs. - _LT_TAGVAR(hardcode_action, $1)=immediate - fi -else - # We cannot hardcode anything, or else we can only hardcode existing - # directories. - _LT_TAGVAR(hardcode_action, $1)=unsupported -fi -AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) - -if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || - test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then - # Fast installation is not supported - enable_fast_install=no -elif test "$shlibpath_overrides_runpath" = yes || - test "$enable_shared" = no; then - # Fast installation is not necessary - enable_fast_install=needless -fi -_LT_TAGDECL([], [hardcode_action], [0], - [How to hardcode a shared library path into an executable]) -])# _LT_LINKER_HARDCODE_LIBPATH - - -# _LT_CMD_STRIPLIB -# ---------------- -m4_defun([_LT_CMD_STRIPLIB], -[m4_require([_LT_DECL_EGREP]) -striplib= -old_striplib= -AC_MSG_CHECKING([whether stripping libraries is possible]) -if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then - test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" - test -z "$striplib" && striplib="$STRIP --strip-unneeded" - AC_MSG_RESULT([yes]) -else -# FIXME - insert some real tests, host_os isn't really good enough - case $host_os in - darwin*) - if test -n "$STRIP" ; then - striplib="$STRIP -x" - old_striplib="$STRIP -S" - AC_MSG_RESULT([yes]) - else - AC_MSG_RESULT([no]) - fi - ;; - *) - AC_MSG_RESULT([no]) - ;; - esac -fi -_LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) -_LT_DECL([], [striplib], [1]) -])# _LT_CMD_STRIPLIB - - -# _LT_SYS_DYNAMIC_LINKER([TAG]) -# ----------------------------- -# PORTME Fill in your ld.so characteristics -m4_defun([_LT_SYS_DYNAMIC_LINKER], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -m4_require([_LT_DECL_EGREP])dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_DECL_SED])dnl -AC_MSG_CHECKING([dynamic linker characteristics]) -m4_if([$1], - [], [ -if test "$GCC" = yes; then - case $host_os in - darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; - *) lt_awk_arg="/^libraries:/" ;; - esac - lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` - if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then - # if the path contains ";" then we assume it to be the separator - # otherwise default to the standard path separator (i.e. ":") - it is - # assumed that no part of a normal pathname contains ";" but that should - # okay in the real world where ";" in dirpaths is itself problematic. - lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'` - else - lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` - fi - # Ok, now we have the path, separated by spaces, we can step through it - # and add multilib dir if necessary. - lt_tmp_lt_search_path_spec= - lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` - for lt_sys_path in $lt_search_path_spec; do - if test -d "$lt_sys_path/$lt_multi_os_dir"; then - lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" - else - test -d "$lt_sys_path" && \ - lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" - fi - done - lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk ' -BEGIN {RS=" "; FS="/|\n";} { - lt_foo=""; - lt_count=0; - for (lt_i = NF; lt_i > 0; lt_i--) { - if ($lt_i != "" && $lt_i != ".") { - if ($lt_i == "..") { - lt_count++; - } else { - if (lt_count == 0) { - lt_foo="/" $lt_i lt_foo; - } else { - lt_count--; - } - } - } - } - if (lt_foo != "") { lt_freq[[lt_foo]]++; } - if (lt_freq[[lt_foo]] == 1) { print lt_foo; } -}'` - sys_lib_search_path_spec=`$ECHO $lt_search_path_spec` -else - sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" -fi]) -library_names_spec= -libname_spec='lib$name' -soname_spec= -shrext_cmds=".so" -postinstall_cmds= -postuninstall_cmds= -finish_cmds= -finish_eval= -shlibpath_var= -shlibpath_overrides_runpath=unknown -version_type=none -dynamic_linker="$host_os ld.so" -sys_lib_dlsearch_path_spec="/lib /usr/lib" -need_lib_prefix=unknown -hardcode_into_libs=no - -# when you set need_version to no, make sure it does not cause -set_version -# flags to be left without arguments -need_version=unknown - -case $host_os in -aix3*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' - shlibpath_var=LIBPATH - - # AIX 3 has no versioning support, so we append a major version to the name. - soname_spec='${libname}${release}${shared_ext}$major' - ;; - -aix[[4-9]]*) - version_type=linux - need_lib_prefix=no - need_version=no - hardcode_into_libs=yes - if test "$host_cpu" = ia64; then - # AIX 5 supports IA64 - library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - else - # With GCC up to 2.95.x, collect2 would create an import file - # for dependence libraries. The import file would start with - # the line `#! .'. This would cause the generated library to - # depend on `.', always an invalid library. This was fixed in - # development snapshots of GCC prior to 3.0. - case $host_os in - aix4 | aix4.[[01]] | aix4.[[01]].*) - if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' - echo ' yes ' - echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then - : - else - can_build_shared=no - fi - ;; - esac - # AIX (on Power*) has no versioning support, so currently we can not hardcode correct - # soname into executable. Probably we can add versioning support to - # collect2, so additional links can be useful in future. - if test "$aix_use_runtimelinking" = yes; then - # If using run time linking (on AIX 4.2 or later) use lib.so - # instead of lib.a to let people know that these are not - # typical AIX shared libraries. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - else - # We preserve .a as extension for shared libraries through AIX4.2 - # and later when we are not doing run time linking. - library_names_spec='${libname}${release}.a $libname.a' - soname_spec='${libname}${release}${shared_ext}$major' - fi - shlibpath_var=LIBPATH - fi - ;; - -amigaos*) - case $host_cpu in - powerpc) - # Since July 2007 AmigaOS4 officially supports .so libraries. - # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - ;; - m68k) - library_names_spec='$libname.ixlibrary $libname.a' - # Create ${libname}_ixlibrary.a entries in /sys/libs. - finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' - ;; - esac - ;; - -beos*) - library_names_spec='${libname}${shared_ext}' - dynamic_linker="$host_os ld.so" - shlibpath_var=LIBRARY_PATH - ;; - -bsdi[[45]]*) - version_type=linux - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' - shlibpath_var=LD_LIBRARY_PATH - sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" - sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" - # the default ld.so.conf also contains /usr/contrib/lib and - # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow - # libtool to hard-code these into programs - ;; - -cygwin* | mingw* | pw32*) - version_type=windows - shrext_cmds=".dll" - need_version=no - need_lib_prefix=no - - case $GCC,$host_os in - yes,cygwin* | yes,mingw* | yes,pw32*) - library_names_spec='$libname.dll.a' - # DLL is installed to $(libdir)/../bin by postinstall_cmds - postinstall_cmds='base_file=`basename \${file}`~ - dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ - dldir=$destdir/`dirname \$dlpath`~ - test -d \$dldir || mkdir -p \$dldir~ - $install_prog $dir/$dlname \$dldir/$dlname~ - chmod a+x \$dldir/$dlname~ - if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then - eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; - fi' - postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ - dlpath=$dir/\$dldll~ - $RM \$dlpath' - shlibpath_overrides_runpath=yes - - case $host_os in - cygwin*) - # Cygwin DLLs use 'cyg' prefix rather than 'lib' - soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' - sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" - ;; - mingw*) - # MinGW DLLs use traditional 'lib' prefix - soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' - sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` - if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then - # It is most probably a Windows format PATH printed by - # mingw gcc, but we are running on Cygwin. Gcc prints its search - # path with ; separators, and with drive letters. We can handle the - # drive letters (cygwin fileutils understands them), so leave them, - # especially as we might pass files found there to a mingw objdump, - # which wouldn't understand a cygwinified path. Ahh. - sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` - else - sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` - fi - ;; - pw32*) - # pw32 DLLs use 'pw' prefix rather than 'lib' - library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' - ;; - esac - ;; - - *) - library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' - ;; - esac - dynamic_linker='Win32 ld.exe' - # FIXME: first we should search . and the directory the executable is in - shlibpath_var=PATH - ;; - -darwin* | rhapsody*) - dynamic_linker="$host_os dyld" - version_type=darwin - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' - soname_spec='${libname}${release}${major}$shared_ext' - shlibpath_overrides_runpath=yes - shlibpath_var=DYLD_LIBRARY_PATH - shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' -m4_if([$1], [],[ - sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) - sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' - ;; - -dgux*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - ;; - -freebsd1*) - dynamic_linker=no - ;; - -freebsd* | dragonfly*) - # DragonFly does not have aout. When/if they implement a new - # versioning mechanism, adjust this. - if test -x /usr/bin/objformat; then - objformat=`/usr/bin/objformat` - else - case $host_os in - freebsd[[123]]*) objformat=aout ;; - *) objformat=elf ;; - esac - fi - version_type=freebsd-$objformat - case $version_type in - freebsd-elf*) - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' - need_version=no - need_lib_prefix=no - ;; - freebsd-*) - library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' - need_version=yes - ;; - esac - shlibpath_var=LD_LIBRARY_PATH - case $host_os in - freebsd2*) - shlibpath_overrides_runpath=yes - ;; - freebsd3.[[01]]* | freebsdelf3.[[01]]*) - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ - freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - *) # from 4.6 on, and DragonFly - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - esac - ;; - -gnu*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - hardcode_into_libs=yes - ;; - -hpux9* | hpux10* | hpux11*) - # Give a soname corresponding to the major version so that dld.sl refuses to - # link against other versions. - version_type=sunos - need_lib_prefix=no - need_version=no - case $host_cpu in - ia64*) - shrext_cmds='.so' - hardcode_into_libs=yes - dynamic_linker="$host_os dld.so" - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - if test "X$HPUX_IA64_MODE" = X32; then - sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" - else - sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" - fi - sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec - ;; - hppa*64*) - shrext_cmds='.sl' - hardcode_into_libs=yes - dynamic_linker="$host_os dld.sl" - shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH - shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" - sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec - ;; - *) - shrext_cmds='.sl' - dynamic_linker="$host_os dld.sl" - shlibpath_var=SHLIB_PATH - shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - ;; - esac - # HP-UX runs *really* slowly unless shared libraries are mode 555. - postinstall_cmds='chmod 555 $lib' - ;; - -interix[[3-9]]*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - -irix5* | irix6* | nonstopux*) - case $host_os in - nonstopux*) version_type=nonstopux ;; - *) - if test "$lt_cv_prog_gnu_ld" = yes; then - version_type=linux - else - version_type=irix - fi ;; - esac - need_lib_prefix=no - need_version=no - soname_spec='${libname}${release}${shared_ext}$major' - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' - case $host_os in - irix5* | nonstopux*) - libsuff= shlibsuff= - ;; - *) - case $LD in # libtool.m4 will add one of these switches to LD - *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") - libsuff= shlibsuff= libmagic=32-bit;; - *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") - libsuff=32 shlibsuff=N32 libmagic=N32;; - *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") - libsuff=64 shlibsuff=64 libmagic=64-bit;; - *) libsuff= shlibsuff= libmagic=never-match;; - esac - ;; - esac - shlibpath_var=LD_LIBRARY${shlibsuff}_PATH - shlibpath_overrides_runpath=no - sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" - sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" - hardcode_into_libs=yes - ;; - -# No shared lib support for Linux oldld, aout, or coff. -linux*oldld* | linux*aout* | linux*coff*) - dynamic_linker=no - ;; - -# This must be Linux ELF. -linux* | k*bsd*-gnu) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - # Some binutils ld are patched to set DT_RUNPATH - save_LDFLAGS=$LDFLAGS - save_libdir=$libdir - eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ - LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" - AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], - [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], - [shlibpath_overrides_runpath=yes])]) - LDFLAGS=$save_LDFLAGS - libdir=$save_libdir - - # This implies no fast_install, which is unacceptable. - # Some rework will be needed to allow for fast_install - # before this can be enabled. - hardcode_into_libs=yes - - # Append ld.so.conf contents to the search path - if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" - fi - - # We used to test for /lib/ld.so.1 and disable shared libraries on - # powerpc, because MkLinux only supported shared libraries with the - # GNU dynamic linker. Since this was broken with cross compilers, - # most powerpc-linux boxes support dynamic linking these days and - # people can always --disable-shared, the test was removed, and we - # assume the GNU/Linux dynamic linker is in use. - dynamic_linker='GNU/Linux ld.so' - ;; - -netbsd*) - version_type=sunos - need_lib_prefix=no - need_version=no - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' - dynamic_linker='NetBSD (a.out) ld.so' - else - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - dynamic_linker='NetBSD ld.elf_so' - fi - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - -newsos6) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - ;; - -*nto* | *qnx*) - version_type=qnx - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - dynamic_linker='ldqnx.so' - ;; - -openbsd*) - version_type=sunos - sys_lib_dlsearch_path_spec="/usr/lib" - need_lib_prefix=no - # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. - case $host_os in - openbsd3.3 | openbsd3.3.*) need_version=yes ;; - *) need_version=no ;; - esac - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' - shlibpath_var=LD_LIBRARY_PATH - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - case $host_os in - openbsd2.[[89]] | openbsd2.[[89]].*) - shlibpath_overrides_runpath=no - ;; - *) - shlibpath_overrides_runpath=yes - ;; - esac - else - shlibpath_overrides_runpath=yes - fi - ;; - -os2*) - libname_spec='$name' - shrext_cmds=".dll" - need_lib_prefix=no - library_names_spec='$libname${shared_ext} $libname.a' - dynamic_linker='OS/2 ld.exe' - shlibpath_var=LIBPATH - ;; - -osf3* | osf4* | osf5*) - version_type=osf - need_lib_prefix=no - need_version=no - soname_spec='${libname}${release}${shared_ext}$major' - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" - sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" - ;; - -rdos*) - dynamic_linker=no - ;; - -solaris*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - # ldd complains unless libraries are executable - postinstall_cmds='chmod +x $lib' - ;; - -sunos4*) - version_type=sunos - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - if test "$with_gnu_ld" = yes; then - need_lib_prefix=no - fi - need_version=yes - ;; - -sysv4 | sysv4.3*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - case $host_vendor in - sni) - shlibpath_overrides_runpath=no - need_lib_prefix=no - runpath_var=LD_RUN_PATH - ;; - siemens) - need_lib_prefix=no - ;; - motorola) - need_lib_prefix=no - need_version=no - shlibpath_overrides_runpath=no - sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' - ;; - esac - ;; - -sysv4*MP*) - if test -d /usr/nec ;then - version_type=linux - library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' - soname_spec='$libname${shared_ext}.$major' - shlibpath_var=LD_LIBRARY_PATH - fi - ;; - -sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) - version_type=freebsd-elf - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - if test "$with_gnu_ld" = yes; then - sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' - else - sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' - case $host_os in - sco3.2v5*) - sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" - ;; - esac - fi - sys_lib_dlsearch_path_spec='/usr/lib' - ;; - -tpf*) - # TPF is a cross-target only. Preferred cross-host = GNU/Linux. - version_type=linux - need_lib_prefix=no - need_version=no - library_name_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - -uts4*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - ;; - -*) - dynamic_linker=no - ;; -esac -AC_MSG_RESULT([$dynamic_linker]) -test "$dynamic_linker" = no && can_build_shared=no - -variables_saved_for_relink="PATH $shlibpath_var $runpath_var" -if test "$GCC" = yes; then - variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" -fi - -if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then - sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" -fi -if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then - sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" -fi - -_LT_DECL([], [variables_saved_for_relink], [1], - [Variables whose values should be saved in libtool wrapper scripts and - restored at link time]) -_LT_DECL([], [need_lib_prefix], [0], - [Do we need the "lib" prefix for modules?]) -_LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) -_LT_DECL([], [version_type], [0], [Library versioning type]) -_LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) -_LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) -_LT_DECL([], [shlibpath_overrides_runpath], [0], - [Is shlibpath searched before the hard-coded library search path?]) -_LT_DECL([], [libname_spec], [1], [Format of library name prefix]) -_LT_DECL([], [library_names_spec], [1], - [[List of archive names. First name is the real one, the rest are links. - The last name is the one that the linker finds with -lNAME]]) -_LT_DECL([], [soname_spec], [1], - [[The coded name of the library, if different from the real name]]) -_LT_DECL([], [postinstall_cmds], [2], - [Command to use after installation of a shared archive]) -_LT_DECL([], [postuninstall_cmds], [2], - [Command to use after uninstallation of a shared archive]) -_LT_DECL([], [finish_cmds], [2], - [Commands used to finish a libtool library installation in a directory]) -_LT_DECL([], [finish_eval], [1], - [[As "finish_cmds", except a single script fragment to be evaled but - not shown]]) -_LT_DECL([], [hardcode_into_libs], [0], - [Whether we should hardcode library paths into libraries]) -_LT_DECL([], [sys_lib_search_path_spec], [2], - [Compile-time system search path for libraries]) -_LT_DECL([], [sys_lib_dlsearch_path_spec], [2], - [Run-time system search path for libraries]) -])# _LT_SYS_DYNAMIC_LINKER - - -# _LT_PATH_TOOL_PREFIX(TOOL) -# -------------------------- -# find a file program which can recognize shared library -AC_DEFUN([_LT_PATH_TOOL_PREFIX], -[m4_require([_LT_DECL_EGREP])dnl -AC_MSG_CHECKING([for $1]) -AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, -[case $MAGIC_CMD in -[[\\/*] | ?:[\\/]*]) - lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. - ;; -*) - lt_save_MAGIC_CMD="$MAGIC_CMD" - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR -dnl $ac_dummy forces splitting on constant user-supplied paths. -dnl POSIX.2 word splitting is done only on the output of word expansions, -dnl not every word. This closes a longstanding sh security hole. - ac_dummy="m4_if([$2], , $PATH, [$2])" - for ac_dir in $ac_dummy; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/$1; then - lt_cv_path_MAGIC_CMD="$ac_dir/$1" - if test -n "$file_magic_test_file"; then - case $deplibs_check_method in - "file_magic "*) - file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` - MAGIC_CMD="$lt_cv_path_MAGIC_CMD" - if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | - $EGREP "$file_magic_regex" > /dev/null; then - : - else - cat <<_LT_EOF 1>&2 - -*** Warning: the command libtool uses to detect shared libraries, -*** $file_magic_cmd, produces output that libtool cannot recognize. -*** The result is that libtool may fail to recognize shared libraries -*** as such. This will affect the creation of libtool libraries that -*** depend on shared libraries, but programs linked with such libtool -*** libraries will work regardless of this problem. Nevertheless, you -*** may want to report the problem to your system manager and/or to -*** bug-libtool@gnu.org - -_LT_EOF - fi ;; - esac - fi - break - fi - done - IFS="$lt_save_ifs" - MAGIC_CMD="$lt_save_MAGIC_CMD" - ;; -esac]) -MAGIC_CMD="$lt_cv_path_MAGIC_CMD" -if test -n "$MAGIC_CMD"; then - AC_MSG_RESULT($MAGIC_CMD) -else - AC_MSG_RESULT(no) -fi -_LT_DECL([], [MAGIC_CMD], [0], - [Used to examine libraries when file_magic_cmd begins with "file"])dnl -])# _LT_PATH_TOOL_PREFIX - -# Old name: -AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) - - -# _LT_PATH_MAGIC -# -------------- -# find a file program which can recognize a shared library -m4_defun([_LT_PATH_MAGIC], -[_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) -if test -z "$lt_cv_path_MAGIC_CMD"; then - if test -n "$ac_tool_prefix"; then - _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) - else - MAGIC_CMD=: - fi -fi -])# _LT_PATH_MAGIC - - -# LT_PATH_LD -# ---------- -# find the pathname to the GNU or non-GNU linker -AC_DEFUN([LT_PATH_LD], -[AC_REQUIRE([AC_PROG_CC])dnl -AC_REQUIRE([AC_CANONICAL_HOST])dnl -AC_REQUIRE([AC_CANONICAL_BUILD])dnl -m4_require([_LT_DECL_SED])dnl -m4_require([_LT_DECL_EGREP])dnl - -AC_ARG_WITH([gnu-ld], - [AS_HELP_STRING([--with-gnu-ld], - [assume the C compiler uses GNU ld @<:@default=no@:>@])], - [test "$withval" = no || with_gnu_ld=yes], - [with_gnu_ld=no])dnl - -ac_prog=ld -if test "$GCC" = yes; then - # Check if gcc -print-prog-name=ld gives a path. - AC_MSG_CHECKING([for ld used by $CC]) - case $host in - *-*-mingw*) - # gcc leaves a trailing carriage return which upsets mingw - ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; - *) - ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; - esac - case $ac_prog in - # Accept absolute paths. - [[\\/]]* | ?:[[\\/]]*) - re_direlt='/[[^/]][[^/]]*/\.\./' - # Canonicalize the pathname of ld - ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` - while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do - ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` - done - test -z "$LD" && LD="$ac_prog" - ;; - "") - # If it fails, then pretend we aren't using GCC. - ac_prog=ld - ;; - *) - # If it is relative, then search for the first ld in PATH. - with_gnu_ld=unknown - ;; - esac -elif test "$with_gnu_ld" = yes; then - AC_MSG_CHECKING([for GNU ld]) -else - AC_MSG_CHECKING([for non-GNU ld]) -fi -AC_CACHE_VAL(lt_cv_path_LD, -[if test -z "$LD"; then - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for ac_dir in $PATH; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then - lt_cv_path_LD="$ac_dir/$ac_prog" - # Check to see if the program is GNU ld. I'd rather use --version, - # but apparently some variants of GNU ld only accept -v. - # Break only if it was the GNU/non-GNU ld that we prefer. - case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then - lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' - lt_cv_file_magic_cmd='func_win32_libid' - else - lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' - lt_cv_file_magic_cmd='$OBJDUMP -f' - fi - ;; - -darwin* | rhapsody*) - lt_cv_deplibs_check_method=pass_all - ;; - -freebsd* | dragonfly*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then - case $host_cpu in - i*86 ) - # Not sure whether the presence of OpenBSD here was a mistake. - # Let's accept both of them until this is cleared up. - lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' - lt_cv_file_magic_cmd=/usr/bin/file - lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` - ;; - esac - else - lt_cv_deplibs_check_method=pass_all - fi - ;; - -gnu*) - lt_cv_deplibs_check_method=pass_all - ;; - -hpux10.20* | hpux11*) - lt_cv_file_magic_cmd=/usr/bin/file - case $host_cpu in - ia64*) - lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' - lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so - ;; - hppa*64*) - [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]'] - lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl - ;; - *) - lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]].[[0-9]]) shared library' - lt_cv_file_magic_test_file=/usr/lib/libc.sl - ;; - esac - ;; - -interix[[3-9]]*) - # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here - lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' - ;; - -irix5* | irix6* | nonstopux*) - case $LD in - *-32|*"-32 ") libmagic=32-bit;; - *-n32|*"-n32 ") libmagic=N32;; - *-64|*"-64 ") libmagic=64-bit;; - *) libmagic=never-match;; - esac - lt_cv_deplibs_check_method=pass_all - ;; - -# This must be Linux ELF. -linux* | k*bsd*-gnu) - lt_cv_deplibs_check_method=pass_all - ;; - -netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then - lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' - else - lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' - fi - ;; - -newos6*) - lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' - lt_cv_file_magic_cmd=/usr/bin/file - lt_cv_file_magic_test_file=/usr/lib/libnls.so - ;; - -*nto* | *qnx*) - lt_cv_deplibs_check_method=pass_all - ;; - -openbsd*) - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' - else - lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' - fi - ;; - -osf3* | osf4* | osf5*) - lt_cv_deplibs_check_method=pass_all - ;; - -rdos*) - lt_cv_deplibs_check_method=pass_all - ;; - -solaris*) - lt_cv_deplibs_check_method=pass_all - ;; - -sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) - lt_cv_deplibs_check_method=pass_all - ;; - -sysv4 | sysv4.3*) - case $host_vendor in - motorola) - lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' - lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` - ;; - ncr) - lt_cv_deplibs_check_method=pass_all - ;; - sequent) - lt_cv_file_magic_cmd='/bin/file' - lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' - ;; - sni) - lt_cv_file_magic_cmd='/bin/file' - lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" - lt_cv_file_magic_test_file=/lib/libc.so - ;; - siemens) - lt_cv_deplibs_check_method=pass_all - ;; - pc) - lt_cv_deplibs_check_method=pass_all - ;; - esac - ;; - -tpf*) - lt_cv_deplibs_check_method=pass_all - ;; -esac -]) -file_magic_cmd=$lt_cv_file_magic_cmd -deplibs_check_method=$lt_cv_deplibs_check_method -test -z "$deplibs_check_method" && deplibs_check_method=unknown - -_LT_DECL([], [deplibs_check_method], [1], - [Method to check whether dependent libraries are shared objects]) -_LT_DECL([], [file_magic_cmd], [1], - [Command to use when deplibs_check_method == "file_magic"]) -])# _LT_CHECK_MAGIC_METHOD - - -# LT_PATH_NM -# ---------- -# find the pathname to a BSD- or MS-compatible name lister -AC_DEFUN([LT_PATH_NM], -[AC_REQUIRE([AC_PROG_CC])dnl -AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, -[if test -n "$NM"; then - # Let the user override the test. - lt_cv_path_NM="$NM" -else - lt_nm_to_check="${ac_tool_prefix}nm" - if test -n "$ac_tool_prefix" && test "$build" = "$host"; then - lt_nm_to_check="$lt_nm_to_check nm" - fi - for lt_tmp_nm in $lt_nm_to_check; do - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - tmp_nm="$ac_dir/$lt_tmp_nm" - if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then - # Check to see if the nm accepts a BSD-compat flag. - # Adding the `sed 1q' prevents false positives on HP-UX, which says: - # nm: unknown option "B" ignored - # Tru64's nm complains that /dev/null is an invalid object file - case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in - */dev/null* | *'Invalid file or object type'*) - lt_cv_path_NM="$tmp_nm -B" - break - ;; - *) - case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in - */dev/null*) - lt_cv_path_NM="$tmp_nm -p" - break - ;; - *) - lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but - continue # so that we can try to find one that supports BSD flags - ;; - esac - ;; - esac - fi - done - IFS="$lt_save_ifs" - done - : ${lt_cv_path_NM=no} -fi]) -if test "$lt_cv_path_NM" != "no"; then - NM="$lt_cv_path_NM" -else - # Didn't find any BSD compatible name lister, look for dumpbin. - AC_CHECK_TOOLS(DUMPBIN, ["dumpbin -symbols" "link -dump -symbols"], :) - AC_SUBST([DUMPBIN]) - if test "$DUMPBIN" != ":"; then - NM="$DUMPBIN" - fi -fi -test -z "$NM" && NM=nm -AC_SUBST([NM]) -_LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl - -AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], - [lt_cv_nm_interface="BSD nm" - echo "int some_variable = 0;" > conftest.$ac_ext - (eval echo "\"\$as_me:__oline__: $ac_compile\"" >&AS_MESSAGE_LOG_FD) - (eval "$ac_compile" 2>conftest.err) - cat conftest.err >&AS_MESSAGE_LOG_FD - (eval echo "\"\$as_me:__oline__: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) - (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) - cat conftest.err >&AS_MESSAGE_LOG_FD - (eval echo "\"\$as_me:__oline__: output\"" >&AS_MESSAGE_LOG_FD) - cat conftest.out >&AS_MESSAGE_LOG_FD - if $GREP 'External.*some_variable' conftest.out > /dev/null; then - lt_cv_nm_interface="MS dumpbin" - fi - rm -f conftest*]) -])# LT_PATH_NM - -# Old names: -AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) -AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AM_PROG_NM], []) -dnl AC_DEFUN([AC_PROG_NM], []) - - -# LT_LIB_M -# -------- -# check for math library -AC_DEFUN([LT_LIB_M], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -LIBM= -case $host in -*-*-beos* | *-*-cygwin* | *-*-pw32* | *-*-darwin*) - # These system don't have libm, or don't need it - ;; -*-ncr-sysv4.3*) - AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") - AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") - ;; -*) - AC_CHECK_LIB(m, cos, LIBM="-lm") - ;; -esac -AC_SUBST([LIBM]) -])# LT_LIB_M - -# Old name: -AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_CHECK_LIBM], []) - - -# _LT_COMPILER_NO_RTTI([TAGNAME]) -# ------------------------------- -m4_defun([_LT_COMPILER_NO_RTTI], -[m4_require([_LT_TAG_COMPILER])dnl - -_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= - -if test "$GCC" = yes; then - _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' - - _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], - lt_cv_prog_compiler_rtti_exceptions, - [-fno-rtti -fno-exceptions], [], - [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) -fi -_LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], - [Compiler flag to turn off builtin functions]) -])# _LT_COMPILER_NO_RTTI - - -# _LT_CMD_GLOBAL_SYMBOLS -# ---------------------- -m4_defun([_LT_CMD_GLOBAL_SYMBOLS], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -AC_REQUIRE([AC_PROG_CC])dnl -AC_REQUIRE([LT_PATH_NM])dnl -AC_REQUIRE([LT_PATH_LD])dnl -m4_require([_LT_DECL_SED])dnl -m4_require([_LT_DECL_EGREP])dnl -m4_require([_LT_TAG_COMPILER])dnl - -# Check for command to grab the raw symbol name followed by C symbol from nm. -AC_MSG_CHECKING([command to parse $NM output from $compiler object]) -AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], -[ -# These are sane defaults that work on at least a few old systems. -# [They come from Ultrix. What could be older than Ultrix?!! ;)] - -# Character class describing NM global symbol codes. -symcode='[[BCDEGRST]]' - -# Regexp to match symbols that can be accessed directly from C. -sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' - -# Define system-specific variables. -case $host_os in -aix*) - symcode='[[BCDT]]' - ;; -cygwin* | mingw* | pw32*) - symcode='[[ABCDGISTW]]' - ;; -hpux*) - if test "$host_cpu" = ia64; then - symcode='[[ABCDEGRST]]' - fi - ;; -irix* | nonstopux*) - symcode='[[BCDEGRST]]' - ;; -osf*) - symcode='[[BCDEGQRST]]' - ;; -solaris*) - symcode='[[BDRT]]' - ;; -sco3.2v5*) - symcode='[[DT]]' - ;; -sysv4.2uw2*) - symcode='[[DT]]' - ;; -sysv5* | sco5v6* | unixware* | OpenUNIX*) - symcode='[[ABDT]]' - ;; -sysv4) - symcode='[[DFNSTU]]' - ;; -esac - -# If we're using GNU nm, then use its standard symbol codes. -case `$NM -V 2>&1` in -*GNU* | *'with BFD'*) - symcode='[[ABCDGIRSTW]]' ;; -esac - -# Transform an extracted symbol line into a proper C declaration. -# Some systems (esp. on ia64) link data and code symbols differently, -# so use this general approach. -lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" - -# Transform an extracted symbol line into symbol name and symbol address -lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" -lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" - -# Handle CRLF in mingw tool chain -opt_cr= -case $build_os in -mingw*) - opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp - ;; -esac - -# Try without a prefix underscore, then with it. -for ac_symprfx in "" "_"; do - - # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. - symxfrm="\\1 $ac_symprfx\\2 \\2" - - # Write the raw and C identifiers. - if test "$lt_cv_nm_interface" = "MS dumpbin"; then - # Fake it for dumpbin and say T for any non-static function - # and D for any global variable. - # Also find C++ and __fastcall symbols from MSVC++, - # which start with @ or ?. - lt_cv_sys_global_symbol_pipe="$AWK ['"\ -" {last_section=section; section=\$ 3};"\ -" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ -" \$ 0!~/External *\|/{next};"\ -" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ -" {if(hide[section]) next};"\ -" {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ -" {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ -" s[1]~/^[@?]/{print s[1], s[1]; next};"\ -" s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ -" ' prfx=^$ac_symprfx]" - else - lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" - fi - - # Check to see that the pipe works correctly. - pipe_works=no - - rm -f conftest* - cat > conftest.$ac_ext <<_LT_EOF -#ifdef __cplusplus -extern "C" { -#endif -char nm_test_var; -void nm_test_func(void); -void nm_test_func(void){} -#ifdef __cplusplus -} -#endif -int main(){nm_test_var='a';nm_test_func();return(0);} -_LT_EOF - - if AC_TRY_EVAL(ac_compile); then - # Now try to grab the symbols. - nlist=conftest.nm - if AC_TRY_EVAL(NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) && test -s "$nlist"; then - # Try sorting and uniquifying the output. - if sort "$nlist" | uniq > "$nlist"T; then - mv -f "$nlist"T "$nlist" - else - rm -f "$nlist"T - fi - - # Make sure that we snagged all the symbols we need. - if $GREP ' nm_test_var$' "$nlist" >/dev/null; then - if $GREP ' nm_test_func$' "$nlist" >/dev/null; then - cat <<_LT_EOF > conftest.$ac_ext -#ifdef __cplusplus -extern "C" { -#endif - -_LT_EOF - # Now generate the symbol file. - eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' - - cat <<_LT_EOF >> conftest.$ac_ext - -/* The mapping between symbol names and symbols. */ -const struct { - const char *name; - void *address; -} -lt__PROGRAM__LTX_preloaded_symbols[[]] = -{ - { "@PROGRAM@", (void *) 0 }, -_LT_EOF - $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext - cat <<\_LT_EOF >> conftest.$ac_ext - {0, (void *) 0} -}; - -/* This works around a problem in FreeBSD linker */ -#ifdef FREEBSD_WORKAROUND -static const void *lt_preloaded_setup() { - return lt__PROGRAM__LTX_preloaded_symbols; -} -#endif - -#ifdef __cplusplus -} -#endif -_LT_EOF - # Now try linking the two files. - mv conftest.$ac_objext conftstm.$ac_objext - lt_save_LIBS="$LIBS" - lt_save_CFLAGS="$CFLAGS" - LIBS="conftstm.$ac_objext" - CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" - if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then - pipe_works=yes - fi - LIBS="$lt_save_LIBS" - CFLAGS="$lt_save_CFLAGS" - else - echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD - fi - else - echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD - fi - else - echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD - fi - else - echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD - cat conftest.$ac_ext >&5 - fi - rm -rf conftest* conftst* - - # Do not use the global_symbol_pipe unless it works. - if test "$pipe_works" = yes; then - break - else - lt_cv_sys_global_symbol_pipe= - fi -done -]) -if test -z "$lt_cv_sys_global_symbol_pipe"; then - lt_cv_sys_global_symbol_to_cdecl= -fi -if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then - AC_MSG_RESULT(failed) -else - AC_MSG_RESULT(ok) -fi - -_LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], - [Take the output of nm and produce a listing of raw symbols and C names]) -_LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], - [Transform the output of nm in a proper C declaration]) -_LT_DECL([global_symbol_to_c_name_address], - [lt_cv_sys_global_symbol_to_c_name_address], [1], - [Transform the output of nm in a C name address pair]) -_LT_DECL([global_symbol_to_c_name_address_lib_prefix], - [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], - [Transform the output of nm in a C name address pair when lib prefix is needed]) -]) # _LT_CMD_GLOBAL_SYMBOLS - - -# _LT_COMPILER_PIC([TAGNAME]) -# --------------------------- -m4_defun([_LT_COMPILER_PIC], -[m4_require([_LT_TAG_COMPILER])dnl -_LT_TAGVAR(lt_prog_compiler_wl, $1)= -_LT_TAGVAR(lt_prog_compiler_pic, $1)= -_LT_TAGVAR(lt_prog_compiler_static, $1)= - -AC_MSG_CHECKING([for $compiler option to produce PIC]) -m4_if([$1], [CXX], [ - # C++ specific cases for pic, static, wl, etc. - if test "$GXX" = yes; then - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' - - case $host_os in - aix*) - # All AIX code is PIC. - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - m68k) - # FIXME: we need at least 68020 code to build shared libraries, but - # adding the `-m68020' flag to GCC prevents building anything better, - # like `-m68040'. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' - ;; - esac - ;; - - beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) - # PIC is the default for these OSes. - ;; - mingw* | cygwin* | os2* | pw32*) - # This hack is so that the source file can tell whether it is being - # built for inclusion in a dll (and should export symbols for example). - # Although the cygwin gcc ignores -fPIC, still need this for old-style - # (--disable-auto-import) libraries - m4_if([$1], [GCJ], [], - [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) - ;; - darwin* | rhapsody*) - # PIC is the default on this platform - # Common symbols not allowed in MH_DYLIB files - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' - ;; - *djgpp*) - # DJGPP does not support shared libraries at all - _LT_TAGVAR(lt_prog_compiler_pic, $1)= - ;; - interix[[3-9]]*) - # Interix 3.x gcc -fpic/-fPIC options generate broken code. - # Instead, we relocate shared libraries at runtime. - ;; - sysv4*MP*) - if test -d /usr/nec; then - _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic - fi - ;; - hpux*) - # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but - # not for PA HP-UX. - case $host_cpu in - hppa*64*|ia64*) - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - esac - ;; - *qnx* | *nto*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - esac - else - case $host_os in - aix[[4-9]]*) - # All AIX code is PIC. - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - else - _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' - fi - ;; - chorus*) - case $cc_basename in - cxch68*) - # Green Hills C++ Compiler - # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" - ;; - esac - ;; - dgux*) - case $cc_basename in - ec++*) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - ;; - ghcx*) - # Green Hills C++ Compiler - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' - ;; - *) - ;; - esac - ;; - freebsd* | dragonfly*) - # FreeBSD uses GNU C++ - ;; - hpux9* | hpux10* | hpux11*) - case $cc_basename in - CC*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' - if test "$host_cpu" != ia64; then - _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' - fi - ;; - aCC*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' - case $host_cpu in - hppa*64*|ia64*) - # +Z the default - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' - ;; - esac - ;; - *) - ;; - esac - ;; - interix*) - # This is c89, which is MS Visual C++ (no shared libs) - # Anyone wants to do a port? - ;; - irix5* | irix6* | nonstopux*) - case $cc_basename in - CC*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - # CC pic flag -KPIC is the default. - ;; - *) - ;; - esac - ;; - linux* | k*bsd*-gnu) - case $cc_basename in - KCC*) - # KAI C++ Compiler - _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - icpc* | ecpc* ) - # Intel C++ - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' - ;; - pgCC* | pgcpp*) - # Portland Group C++ compiler - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - cxx*) - # Compaq C++ - # Make sure the PIC flag is empty. It appears that all Alpha - # Linux and Compaq Tru64 Unix objects are PIC. - _LT_TAGVAR(lt_prog_compiler_pic, $1)= - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - xlc* | xlC*) - # IBM XL 8.0 on PPC - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' - ;; - *) - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) - # Sun C++ 5.9 - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' - ;; - esac - ;; - esac - ;; - lynxos*) - ;; - m88k*) - ;; - mvs*) - case $cc_basename in - cxx*) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' - ;; - *) - ;; - esac - ;; - netbsd*) - ;; - *qnx* | *nto*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' - ;; - osf3* | osf4* | osf5*) - case $cc_basename in - KCC*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' - ;; - RCC*) - # Rational C++ 2.4.1 - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' - ;; - cxx*) - # Digital/Compaq C++ - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - # Make sure the PIC flag is empty. It appears that all Alpha - # Linux and Compaq Tru64 Unix objects are PIC. - _LT_TAGVAR(lt_prog_compiler_pic, $1)= - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - *) - ;; - esac - ;; - psos*) - ;; - solaris*) - case $cc_basename in - CC*) - # Sun C++ 4.2, 5.x and Centerline C++ - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' - ;; - gcx*) - # Green Hills C++ Compiler - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' - ;; - *) - ;; - esac - ;; - sunos4*) - case $cc_basename in - CC*) - # Sun C++ 4.x - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - lcc*) - # Lucid - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' - ;; - *) - ;; - esac - ;; - sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) - case $cc_basename in - CC*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - esac - ;; - tandem*) - case $cc_basename in - NCC*) - # NonStop-UX NCC 3.20 - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - ;; - *) - ;; - esac - ;; - vxworks*) - ;; - *) - _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no - ;; - esac - fi -], -[ - if test "$GCC" = yes; then - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' - - case $host_os in - aix*) - # All AIX code is PIC. - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - m68k) - # FIXME: we need at least 68020 code to build shared libraries, but - # adding the `-m68020' flag to GCC prevents building anything better, - # like `-m68040'. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' - ;; - esac - ;; - - beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) - # PIC is the default for these OSes. - ;; - - mingw* | cygwin* | pw32* | os2*) - # This hack is so that the source file can tell whether it is being - # built for inclusion in a dll (and should export symbols for example). - # Although the cygwin gcc ignores -fPIC, still need this for old-style - # (--disable-auto-import) libraries - m4_if([$1], [GCJ], [], - [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) - ;; - - darwin* | rhapsody*) - # PIC is the default on this platform - # Common symbols not allowed in MH_DYLIB files - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' - ;; - - hpux*) - # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but - # not for PA HP-UX. - case $host_cpu in - hppa*64*|ia64*) - # +Z the default - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - esac - ;; - - interix[[3-9]]*) - # Interix 3.x gcc -fpic/-fPIC options generate broken code. - # Instead, we relocate shared libraries at runtime. - ;; - - msdosdjgpp*) - # Just because we use GCC doesn't mean we suddenly get shared libraries - # on systems that don't support them. - _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no - enable_shared=no - ;; - - *nto* | *qnx*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' - ;; - - sysv4*MP*) - if test -d /usr/nec; then - _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic - fi - ;; - - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' - ;; - esac - else - # PORTME Check for flag to pass linker flags through the system compiler. - case $host_os in - aix*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - else - _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' - fi - ;; - - mingw* | cygwin* | pw32* | os2*) - # This hack is so that the source file can tell whether it is being - # built for inclusion in a dll (and should export symbols for example). - m4_if([$1], [GCJ], [], - [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) - ;; - - hpux9* | hpux10* | hpux11*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but - # not for PA HP-UX. - case $host_cpu in - hppa*64*|ia64*) - # +Z the default - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' - ;; - esac - # Is there a better lt_prog_compiler_static that works with the bundled CC? - _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' - ;; - - irix5* | irix6* | nonstopux*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - # PIC (with -KPIC) is the default. - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - - linux* | k*bsd*-gnu) - case $cc_basename in - icc* | ecc* | ifort*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' - ;; - pgcc* | pgf77* | pgf90* | pgf95*) - # Portland Group compilers (*not* the Pentium gcc compiler, - # which looks to be a dead project) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - ccc*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - # All Alpha code is PIC. - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - xl*) - # IBM XL C 8.0/Fortran 10.1 on PPC - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' - ;; - *) - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) - # Sun C 5.9 - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - ;; - *Sun\ F*) - # Sun Fortran 8.3 passes all unrecognized flags to the linker - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - _LT_TAGVAR(lt_prog_compiler_wl, $1)='' - ;; - esac - ;; - esac - ;; - - newsos6) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - - *nto* | *qnx*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' - ;; - - osf3* | osf4* | osf5*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - # All OSF/1 code is PIC. - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - - rdos*) - _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' - ;; - - solaris*) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - case $cc_basename in - f77* | f90* | f95*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; - *) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; - esac - ;; - - sunos4*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - - sysv4 | sysv4.2uw2* | sysv4.3*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - - sysv4*MP*) - if test -d /usr/nec ;then - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - fi - ;; - - sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - - unicos*) - _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' - _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no - ;; - - uts4*) - _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' - _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' - ;; - - *) - _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no - ;; - esac - fi -]) -case $host_os in - # For platforms which do not support PIC, -DPIC is meaningless: - *djgpp*) - _LT_TAGVAR(lt_prog_compiler_pic, $1)= - ;; - *) - _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" - ;; -esac -AC_MSG_RESULT([$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) -_LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], - [How to pass a linker flag through the compiler]) - -# -# Check to make sure the PIC flag actually works. -# -if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then - _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], - [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], - [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], - [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in - "" | " "*) ;; - *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; - esac], - [_LT_TAGVAR(lt_prog_compiler_pic, $1)= - _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) -fi -_LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], - [Additional compiler flags for building library objects]) - -# -# Check to make sure the static flag actually works. -# -wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" -_LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], - _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), - $lt_tmp_static_flag, - [], - [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) -_LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], - [Compiler flag to prevent dynamic linking]) -])# _LT_COMPILER_PIC - - -# _LT_LINKER_SHLIBS([TAGNAME]) -# ---------------------------- -# See if the linker supports building shared libraries. -m4_defun([_LT_LINKER_SHLIBS], -[AC_REQUIRE([LT_PATH_LD])dnl -AC_REQUIRE([LT_PATH_NM])dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_DECL_EGREP])dnl -m4_require([_LT_DECL_SED])dnl -m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl -m4_require([_LT_TAG_COMPILER])dnl -AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) -m4_if([$1], [CXX], [ - _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' - case $host_os in - aix[[4-9]]*) - # If we're using GNU nm, then we don't want the "-C" option. - # -C means demangle to AIX nm, but means don't demangle with GNU nm - if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then - _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - else - _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - fi - ;; - pw32*) - _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" - ;; - cygwin* | mingw*) - _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;/^.*[[ ]]__nm__/s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' - ;; - *) - _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' - ;; - esac - _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] -], [ - runpath_var= - _LT_TAGVAR(allow_undefined_flag, $1)= - _LT_TAGVAR(always_export_symbols, $1)=no - _LT_TAGVAR(archive_cmds, $1)= - _LT_TAGVAR(archive_expsym_cmds, $1)= - _LT_TAGVAR(compiler_needs_object, $1)=no - _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no - _LT_TAGVAR(export_dynamic_flag_spec, $1)= - _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' - _LT_TAGVAR(hardcode_automatic, $1)=no - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_direct_absolute, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= - _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= - _LT_TAGVAR(hardcode_libdir_separator, $1)= - _LT_TAGVAR(hardcode_minus_L, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported - _LT_TAGVAR(inherit_rpath, $1)=no - _LT_TAGVAR(link_all_deplibs, $1)=unknown - _LT_TAGVAR(module_cmds, $1)= - _LT_TAGVAR(module_expsym_cmds, $1)= - _LT_TAGVAR(old_archive_from_new_cmds, $1)= - _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= - _LT_TAGVAR(thread_safe_flag_spec, $1)= - _LT_TAGVAR(whole_archive_flag_spec, $1)= - # include_expsyms should be a list of space-separated symbols to be *always* - # included in the symbol list - _LT_TAGVAR(include_expsyms, $1)= - # exclude_expsyms can be an extended regexp of symbols to exclude - # it will be wrapped by ` (' and `)$', so one must not match beginning or - # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', - # as well as any symbol that contains `d'. - _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] - # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out - # platforms (ab)use it in PIC code, but their linkers get confused if - # the symbol is explicitly referenced. Since portable code cannot - # rely on this symbol name, it's probably fine to never include it in - # preloaded symbol tables. - # Exclude shared library initialization/finalization symbols. -dnl Note also adjust exclude_expsyms for C++ above. - extract_expsyms_cmds= - - case $host_os in - cygwin* | mingw* | pw32*) - # FIXME: the MSVC++ port hasn't been tested in a loooong time - # When not using gcc, we currently assume that we are using - # Microsoft Visual C++. - if test "$GCC" != yes; then - with_gnu_ld=no - fi - ;; - interix*) - # we just hope/assume this is gcc and not c89 (= MSVC++) - with_gnu_ld=yes - ;; - openbsd*) - with_gnu_ld=no - ;; - esac - - _LT_TAGVAR(ld_shlibs, $1)=yes - if test "$with_gnu_ld" = yes; then - # If archive_cmds runs LD, not CC, wlarc should be empty - wlarc='${wl}' - - # Set some defaults for GNU ld with shared library support. These - # are reset later if shared libraries are not supported. Putting them - # here allows them to be overridden if necessary. - runpath_var=LD_RUN_PATH - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - # ancient GNU ld didn't support --whole-archive et. al. - if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then - _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' - else - _LT_TAGVAR(whole_archive_flag_spec, $1)= - fi - supports_anon_versioning=no - case `$LD -v 2>&1` in - *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 - *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... - *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... - *\ 2.11.*) ;; # other 2.11 versions - *) supports_anon_versioning=yes ;; - esac - - # See if GNU ld supports shared libraries. - case $host_os in - aix[[3-9]]*) - # On AIX/PPC, the GNU linker is very broken - if test "$host_cpu" != ia64; then - _LT_TAGVAR(ld_shlibs, $1)=no - cat <<_LT_EOF 1>&2 - -*** Warning: the GNU linker, at least up to release 2.9.1, is reported -*** to be unable to reliably create shared libraries on AIX. -*** Therefore, libtool is disabling shared libraries support. If you -*** really care for shared libraries, you may want to modify your PATH -*** so that a non-GNU linker is found, and then restart. - -_LT_EOF - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='' - ;; - m68k) - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_minus_L, $1)=yes - ;; - esac - ;; - - beos*) - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - # Joseph Beckenbach says some releases of gcc - # support --undefined. This deserves some investigation. FIXME - _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - cygwin* | mingw* | pw32*) - # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, - # as there is no search path for DLLs. - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - _LT_TAGVAR(always_export_symbols, $1)=no - _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes - _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' - - if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - # If the export-symbols file already is a .def file (1st line - # is EXPORTS), use it as is; otherwise, prepend... - _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then - cp $export_symbols $output_objdir/$soname.def; - else - echo EXPORTS > $output_objdir/$soname.def; - cat $export_symbols >> $output_objdir/$soname.def; - fi~ - $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - interix[[3-9]]*) - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. - # Instead, shared libraries are loaded at an image base (0x10000000 by - # default) and relocated if they conflict, which is a slow very memory - # consuming and fragmenting process. To avoid this, we pick a random, - # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link - # time. Moving up from 0x10000000 also allows more sbrk(2) space. - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - ;; - - gnu* | linux* | tpf* | k*bsd*-gnu) - tmp_diet=no - if test "$host_os" = linux-dietlibc; then - case $cc_basename in - diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) - esac - fi - if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ - && test "$tmp_diet" = no - then - tmp_addflag= - tmp_sharedflag='-shared' - case $cc_basename,$host_cpu in - pgcc*) # Portland Group C compiler - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - tmp_addflag=' $pic_flag' - ;; - pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - tmp_addflag=' $pic_flag -Mnomain' ;; - ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 - tmp_addflag=' -i_dynamic' ;; - efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 - tmp_addflag=' -i_dynamic -nofor_main' ;; - ifc* | ifort*) # Intel Fortran compiler - tmp_addflag=' -nofor_main' ;; - xl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) - tmp_sharedflag='-qmkshrobj' - tmp_addflag= ;; - esac - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) # Sun C 5.9 - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - _LT_TAGVAR(compiler_needs_object, $1)=yes - tmp_sharedflag='-G' ;; - *Sun\ F*) # Sun Fortran 8.3 - tmp_sharedflag='-G' ;; - esac - _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - - if test "x$supports_anon_versioning" = xyes; then - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ - cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ - echo "local: *; };" >> $output_objdir/$libname.ver~ - $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' - fi - - case $cc_basename in - xlf*) - # IBM XL Fortran 10.1 on PPC cannot create shared libs itself - _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= - _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='-rpath $libdir' - _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib' - if test "x$supports_anon_versioning" = xyes; then - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ - cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ - echo "local: *; };" >> $output_objdir/$libname.ver~ - $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' - fi - ;; - esac - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' - wlarc= - else - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - fi - ;; - - solaris*) - if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then - _LT_TAGVAR(ld_shlibs, $1)=no - cat <<_LT_EOF 1>&2 - -*** Warning: The releases 2.8.* of the GNU linker cannot reliably -*** create shared libraries on Solaris systems. Therefore, libtool -*** is disabling shared libraries support. We urge you to upgrade GNU -*** binutils to release 2.9.1 or newer. Another option is to modify -*** your PATH or compiler configuration so that the native linker is -*** used, and then restart. - -_LT_EOF - elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) - case `$LD -v 2>&1` in - *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) - _LT_TAGVAR(ld_shlibs, $1)=no - cat <<_LT_EOF 1>&2 - -*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not -*** reliably create shared libraries on SCO systems. Therefore, libtool -*** is disabling shared libraries support. We urge you to upgrade GNU -*** binutils to release 2.16.91.0.3 or newer. Another option is to modify -*** your PATH or compiler configuration so that the native linker is -*** used, and then restart. - -_LT_EOF - ;; - *) - # For security reasons, it is highly recommended that you always - # use absolute paths for naming shared libraries, and exclude the - # DT_RUNPATH tag from executables and libraries. But doing so - # requires that you compile everything twice, which is a pain. - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - esac - ;; - - sunos4*) - _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' - wlarc= - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - *) - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - esac - - if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then - runpath_var= - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= - _LT_TAGVAR(export_dynamic_flag_spec, $1)= - _LT_TAGVAR(whole_archive_flag_spec, $1)= - fi - else - # PORTME fill in a description of your system's linker (not GNU ld) - case $host_os in - aix3*) - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - _LT_TAGVAR(always_export_symbols, $1)=yes - _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' - # Note: this linker hardcodes the directories in LIBPATH if there - # are no directories specified by -L. - _LT_TAGVAR(hardcode_minus_L, $1)=yes - if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then - # Neither direct hardcoding nor static linking is supported with a - # broken collect2. - _LT_TAGVAR(hardcode_direct, $1)=unsupported - fi - ;; - - aix[[4-9]]*) - if test "$host_cpu" = ia64; then - # On IA64, the linker does run time linking by default, so we don't - # have to do anything special. - aix_use_runtimelinking=no - exp_sym_flag='-Bexport' - no_entry_flag="" - else - # If we're using GNU nm, then we don't want the "-C" option. - # -C means demangle to AIX nm, but means don't demangle with GNU nm - if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then - _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - else - _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - fi - aix_use_runtimelinking=no - - # Test if we are trying to use run time linking or normal - # AIX style linking. If -brtl is somewhere in LDFLAGS, we - # need to do runtime linking. - case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) - for ld_flag in $LDFLAGS; do - if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then - aix_use_runtimelinking=yes - break - fi - done - ;; - esac - - exp_sym_flag='-bexport' - no_entry_flag='-bnoentry' - fi - - # When large executables or shared objects are built, AIX ld can - # have problems creating the table of contents. If linking a library - # or program results in "error TOC overflow" add -mminimal-toc to - # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not - # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. - - _LT_TAGVAR(archive_cmds, $1)='' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(hardcode_libdir_separator, $1)=':' - _LT_TAGVAR(link_all_deplibs, $1)=yes - _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' - - if test "$GCC" = yes; then - case $host_os in aix4.[[012]]|aix4.[[012]].*) - # We only want to do this on AIX 4.2 and lower, the check - # below for broken collect2 doesn't work under 4.3+ - collect2name=`${CC} -print-prog-name=collect2` - if test -f "$collect2name" && - strings "$collect2name" | $GREP resolve_lib_name >/dev/null - then - # We have reworked collect2 - : - else - # We have old collect2 - _LT_TAGVAR(hardcode_direct, $1)=unsupported - # It fails to find uninstalled libraries when the uninstalled - # path is not listed in the libpath. Setting hardcode_minus_L - # to unsupported forces relinking - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)= - fi - ;; - esac - shared_flag='-shared' - if test "$aix_use_runtimelinking" = yes; then - shared_flag="$shared_flag "'${wl}-G' - fi - else - # not using gcc - if test "$host_cpu" = ia64; then - # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release - # chokes on -Wl,-G. The following line is correct: - shared_flag='-G' - else - if test "$aix_use_runtimelinking" = yes; then - shared_flag='${wl}-G' - else - shared_flag='${wl}-bM:SRE' - fi - fi - fi - - # It seems that -bexpall does not export symbols beginning with - # underscore (_), so it is better to generate a list of symbols to export. - _LT_TAGVAR(always_export_symbols, $1)=yes - if test "$aix_use_runtimelinking" = yes; then - # Warning - without using the other runtime loading flags (-brtl), - # -berok will link without error, but may produce a broken library. - _LT_TAGVAR(allow_undefined_flag, $1)='-berok' - # Determine the default libpath from the value encoded in an - # empty executable. - _LT_SYS_MODULE_PATH_AIX - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" - else - if test "$host_cpu" = ia64; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' - _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" - _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" - else - # Determine the default libpath from the value encoded in an - # empty executable. - _LT_SYS_MODULE_PATH_AIX - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" - # Warning - without using the other run time loading flags, - # -berok will link without error, but may produce a broken library. - _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' - # Exported symbols can be pulled into shared objects from archives - _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' - _LT_TAGVAR(archive_cmds_need_lc, $1)=yes - # This is similar to how AIX traditionally builds its shared libraries. - _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' - fi - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='' - ;; - m68k) - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_minus_L, $1)=yes - ;; - esac - ;; - - bsdi[[45]]*) - _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic - ;; - - cygwin* | mingw* | pw32*) - # When not using gcc, we currently assume that we are using - # Microsoft Visual C++. - # hardcode_libdir_flag_spec is actually meaningless, as there is - # no search path for DLLs. - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - # Tell ltmain to make .lib files, not .a files. - libext=lib - # Tell ltmain to make .dll files, not .so files. - shrext_cmds=".dll" - # FIXME: Setting linknames here is a bad hack. - _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames=' - # The linker will automatically build a .lib file if we build a DLL. - _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' - # FIXME: Should let the user specify the lib program. - _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' - _LT_TAGVAR(fix_srcfile_path, $1)='`cygpath -w "$srcfile"`' - _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes - ;; - - darwin* | rhapsody*) - _LT_DARWIN_LINKER_FEATURES($1) - ;; - - dgux*) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - freebsd1*) - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor - # support. Future versions do this automatically, but an explicit c++rt0.o - # does not break anything, and helps significantly (at the cost of a little - # extra space). - freebsd2.2*) - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - # Unfortunately, older versions of FreeBSD 2 do not have this feature. - freebsd2*) - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - # FreeBSD 3 and greater uses gcc -shared to do shared libraries. - freebsd* | dragonfly*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - hpux9*) - if test "$GCC" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - else - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - fi - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(hardcode_direct, $1)=yes - - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - ;; - - hpux10*) - if test "$GCC" = yes -a "$with_gnu_ld" = no; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - else - _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' - fi - if test "$with_gnu_ld" = no; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)='+b $libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - _LT_TAGVAR(hardcode_minus_L, $1)=yes - fi - ;; - - hpux11*) - if test "$GCC" = yes -a "$with_gnu_ld" = no; then - case $host_cpu in - hppa*64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - ia64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - else - case $host_cpu in - hppa*64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - ia64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - fi - if test "$with_gnu_ld" = no; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - case $host_cpu in - hppa*64*|ia64*) - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - *) - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - _LT_TAGVAR(hardcode_minus_L, $1)=yes - ;; - esac - fi - ;; - - irix5* | irix6* | nonstopux*) - if test "$GCC" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - # Try to use the -exported_symbol ld option, if it does not - # work, assume that -exports_file does not work either and - # implicitly export all symbols. - save_LDFLAGS="$LDFLAGS" - LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" - AC_LINK_IFELSE(int foo(void) {}, - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' - ) - LDFLAGS="$save_LDFLAGS" - else - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' - fi - _LT_TAGVAR(archive_cmds_need_lc, $1)='no' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(inherit_rpath, $1)=yes - _LT_TAGVAR(link_all_deplibs, $1)=yes - ;; - - netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out - else - _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF - fi - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - newsos6) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - *nto* | *qnx*) - ;; - - openbsd*) - if test -f /usr/libexec/ld.so; then - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - else - case $host_os in - openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - ;; - esac - fi - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - os2*) - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' - _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' - ;; - - osf3*) - if test "$GCC" = yes; then - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - else - _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - fi - _LT_TAGVAR(archive_cmds_need_lc, $1)='no' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - ;; - - osf4* | osf5*) # as osf3* with the addition of -msym flag - if test "$GCC" = yes; then - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - else - _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ - $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' - - # Both c and cxx compiler support -rpath directly - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' - fi - _LT_TAGVAR(archive_cmds_need_lc, $1)='no' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - ;; - - solaris*) - _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' - if test "$GCC" = yes; then - wlarc='${wl}' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' - else - case `$CC -V 2>&1` in - *"Compilers 5.0"*) - wlarc='' - _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' - ;; - *) - wlarc='${wl}' - _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' - ;; - esac - fi - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - case $host_os in - solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; - *) - # The compiler driver will combine and reorder linker options, - # but understands `-z linker_flag'. GCC discards it without `$wl', - # but is careful enough not to reorder. - # Supported since Solaris 2.6 (maybe 2.5.1?) - if test "$GCC" = yes; then - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' - else - _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' - fi - ;; - esac - _LT_TAGVAR(link_all_deplibs, $1)=yes - ;; - - sunos4*) - if test "x$host_vendor" = xsequent; then - # Use $CC to link under sequent, because it throws in some extra .o - # files that make .init and .fini sections work. - _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' - else - _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' - fi - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - sysv4) - case $host_vendor in - sni) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? - ;; - siemens) - ## LD is ld it makes a PLAMLIB - ## CC just makes a GrossModule. - _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' - _LT_TAGVAR(hardcode_direct, $1)=no - ;; - motorola) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie - ;; - esac - runpath_var='LD_RUN_PATH' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - sysv4.3*) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' - ;; - - sysv4*MP*) - if test -d /usr/nec; then - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - runpath_var=LD_RUN_PATH - hardcode_runpath_var=yes - _LT_TAGVAR(ld_shlibs, $1)=yes - fi - ;; - - sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) - _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - runpath_var='LD_RUN_PATH' - - if test "$GCC" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - else - _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - fi - ;; - - sysv5* | sco3.2v5* | sco5v6*) - # Note: We can NOT use -z defs as we might desire, because we do not - # link with -lc, and that would cause any symbols used from libc to - # always be unresolved, which means just about no library would - # ever link correctly. If we're not using GNU ld we use -z text - # though, which does catch some bad symbols but isn't as heavy-handed - # as -z defs. - _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' - _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=':' - _LT_TAGVAR(link_all_deplibs, $1)=yes - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' - runpath_var='LD_RUN_PATH' - - if test "$GCC" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - else - _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - fi - ;; - - uts4*) - _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - - *) - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - - if test x$host_vendor = xsni; then - case $host in - sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' - ;; - esac - fi - fi -]) -AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) -test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no - -_LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld - -_LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl -_LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl -_LT_DECL([], [extract_expsyms_cmds], [2], - [The commands to extract the exported symbol list from a shared archive]) - -# -# Do we need to explicitly link libc? -# -case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in -x|xyes) - # Assume -lc should be added - _LT_TAGVAR(archive_cmds_need_lc, $1)=yes - - if test "$enable_shared" = yes && test "$GCC" = yes; then - case $_LT_TAGVAR(archive_cmds, $1) in - *'~'*) - # FIXME: we may have to deal with multi-command sequences. - ;; - '$CC '*) - # Test whether the compiler implicitly links with -lc since on some - # systems, -lgcc has to come before -lc. If gcc already passes -lc - # to ld, don't add -lc before -lgcc. - AC_MSG_CHECKING([whether -lc should be explicitly linked in]) - $RM conftest* - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - - if AC_TRY_EVAL(ac_compile) 2>conftest.err; then - soname=conftest - lib=conftest - libobjs=conftest.$ac_objext - deplibs= - wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) - pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) - compiler_flags=-v - linker_flags=-v - verstring= - output_objdir=. - libname=conftest - lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) - _LT_TAGVAR(allow_undefined_flag, $1)= - if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) - then - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - else - _LT_TAGVAR(archive_cmds_need_lc, $1)=yes - fi - _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag - else - cat conftest.err 1>&5 - fi - $RM conftest* - AC_MSG_RESULT([$_LT_TAGVAR(archive_cmds_need_lc, $1)]) - ;; - esac - fi - ;; -esac - -_LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], - [Whether or not to add -lc for building shared libraries]) -_LT_TAGDECL([allow_libtool_libs_with_static_runtimes], - [enable_shared_with_static_runtimes], [0], - [Whether or not to disallow shared libs when runtime libs are static]) -_LT_TAGDECL([], [export_dynamic_flag_spec], [1], - [Compiler flag to allow reflexive dlopens]) -_LT_TAGDECL([], [whole_archive_flag_spec], [1], - [Compiler flag to generate shared objects directly from archives]) -_LT_TAGDECL([], [compiler_needs_object], [1], - [Whether the compiler copes with passing no objects directly]) -_LT_TAGDECL([], [old_archive_from_new_cmds], [2], - [Create an old-style archive from a shared archive]) -_LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], - [Create a temporary old-style archive to link instead of a shared archive]) -_LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) -_LT_TAGDECL([], [archive_expsym_cmds], [2]) -_LT_TAGDECL([], [module_cmds], [2], - [Commands used to build a loadable module if different from building - a shared archive.]) -_LT_TAGDECL([], [module_expsym_cmds], [2]) -_LT_TAGDECL([], [with_gnu_ld], [1], - [Whether we are building with GNU ld or not]) -_LT_TAGDECL([], [allow_undefined_flag], [1], - [Flag that allows shared libraries with undefined symbols to be built]) -_LT_TAGDECL([], [no_undefined_flag], [1], - [Flag that enforces no undefined symbols]) -_LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], - [Flag to hardcode $libdir into a binary during linking. - This must work even if $libdir does not exist]) -_LT_TAGDECL([], [hardcode_libdir_flag_spec_ld], [1], - [[If ld is used when linking, flag to hardcode $libdir into a binary - during linking. This must work even if $libdir does not exist]]) -_LT_TAGDECL([], [hardcode_libdir_separator], [1], - [Whether we need a single "-rpath" flag with a separated argument]) -_LT_TAGDECL([], [hardcode_direct], [0], - [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes - DIR into the resulting binary]) -_LT_TAGDECL([], [hardcode_direct_absolute], [0], - [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes - DIR into the resulting binary and the resulting library dependency is - "absolute", i.e impossible to change by setting ${shlibpath_var} if the - library is relocated]) -_LT_TAGDECL([], [hardcode_minus_L], [0], - [Set to "yes" if using the -LDIR flag during linking hardcodes DIR - into the resulting binary]) -_LT_TAGDECL([], [hardcode_shlibpath_var], [0], - [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR - into the resulting binary]) -_LT_TAGDECL([], [hardcode_automatic], [0], - [Set to "yes" if building a shared library automatically hardcodes DIR - into the library and all subsequent libraries and executables linked - against it]) -_LT_TAGDECL([], [inherit_rpath], [0], - [Set to yes if linker adds runtime paths of dependent libraries - to runtime path list]) -_LT_TAGDECL([], [link_all_deplibs], [0], - [Whether libtool must link a program against all its dependency libraries]) -_LT_TAGDECL([], [fix_srcfile_path], [1], - [Fix the shell variable $srcfile for the compiler]) -_LT_TAGDECL([], [always_export_symbols], [0], - [Set to "yes" if exported symbols are required]) -_LT_TAGDECL([], [export_symbols_cmds], [2], - [The commands to list exported symbols]) -_LT_TAGDECL([], [exclude_expsyms], [1], - [Symbols that should not be listed in the preloaded symbols]) -_LT_TAGDECL([], [include_expsyms], [1], - [Symbols that must always be exported]) -_LT_TAGDECL([], [prelink_cmds], [2], - [Commands necessary for linking programs (against libraries) with templates]) -_LT_TAGDECL([], [file_list_spec], [1], - [Specify filename containing input files]) -dnl FIXME: Not yet implemented -dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], -dnl [Compiler flag to generate thread safe objects]) -])# _LT_LINKER_SHLIBS - - -# _LT_LANG_C_CONFIG([TAG]) -# ------------------------ -# Ensure that the configuration variables for a C compiler are suitably -# defined. These variables are subsequently used by _LT_CONFIG to write -# the compiler configuration to `libtool'. -m4_defun([_LT_LANG_C_CONFIG], -[m4_require([_LT_DECL_EGREP])dnl -lt_save_CC="$CC" -AC_LANG_PUSH(C) - -# Source file extension for C test sources. -ac_ext=c - -# Object file extension for compiled C test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# Code to be used in simple compile tests -lt_simple_compile_test_code="int some_variable = 0;" - -# Code to be used in simple link tests -lt_simple_link_test_code='int main(){return(0);}' - -_LT_TAG_COMPILER -# Save the default compiler, since it gets overwritten when the other -# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. -compiler_DEFAULT=$CC - -# save warnings/boilerplate of simple test code -_LT_COMPILER_BOILERPLATE -_LT_LINKER_BOILERPLATE - -## CAVEAT EMPTOR: -## There is no encapsulation within the following macros, do not change -## the running order or otherwise move them around unless you know exactly -## what you are doing... -if test -n "$compiler"; then - _LT_COMPILER_NO_RTTI($1) - _LT_COMPILER_PIC($1) - _LT_COMPILER_C_O($1) - _LT_COMPILER_FILE_LOCKS($1) - _LT_LINKER_SHLIBS($1) - _LT_SYS_DYNAMIC_LINKER($1) - _LT_LINKER_HARDCODE_LIBPATH($1) - LT_SYS_DLOPEN_SELF - _LT_CMD_STRIPLIB - - # Report which library types will actually be built - AC_MSG_CHECKING([if libtool supports shared libraries]) - AC_MSG_RESULT([$can_build_shared]) - - AC_MSG_CHECKING([whether to build shared libraries]) - test "$can_build_shared" = "no" && enable_shared=no - - # On AIX, shared libraries and static libraries use the same namespace, and - # are all built from PIC. - case $host_os in - aix3*) - test "$enable_shared" = yes && enable_static=no - if test -n "$RANLIB"; then - archive_cmds="$archive_cmds~\$RANLIB \$lib" - postinstall_cmds='$RANLIB $lib' - fi - ;; - - aix[[4-9]]*) - if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then - test "$enable_shared" = yes && enable_static=no - fi - ;; - esac - AC_MSG_RESULT([$enable_shared]) - - AC_MSG_CHECKING([whether to build static libraries]) - # Make sure either enable_shared or enable_static is yes. - test "$enable_shared" = yes || enable_static=yes - AC_MSG_RESULT([$enable_static]) - - _LT_CONFIG($1) -fi -AC_LANG_POP -CC="$lt_save_CC" -])# _LT_LANG_C_CONFIG - - -# _LT_PROG_CXX -# ------------ -# Since AC_PROG_CXX is broken, in that it returns g++ if there is no c++ -# compiler, we have our own version here. -m4_defun([_LT_PROG_CXX], -[ -pushdef([AC_MSG_ERROR], [_lt_caught_CXX_error=yes]) -AC_PROG_CXX -if test -n "$CXX" && ( test "X$CXX" != "Xno" && - ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || - (test "X$CXX" != "Xg++"))) ; then - AC_PROG_CXXCPP -else - _lt_caught_CXX_error=yes -fi -popdef([AC_MSG_ERROR]) -])# _LT_PROG_CXX - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([_LT_PROG_CXX], []) - - -# _LT_LANG_CXX_CONFIG([TAG]) -# -------------------------- -# Ensure that the configuration variables for a C++ compiler are suitably -# defined. These variables are subsequently used by _LT_CONFIG to write -# the compiler configuration to `libtool'. -m4_defun([_LT_LANG_CXX_CONFIG], -[AC_REQUIRE([_LT_PROG_CXX])dnl -m4_require([_LT_FILEUTILS_DEFAULTS])dnl -m4_require([_LT_DECL_EGREP])dnl - -AC_LANG_PUSH(C++) -_LT_TAGVAR(archive_cmds_need_lc, $1)=no -_LT_TAGVAR(allow_undefined_flag, $1)= -_LT_TAGVAR(always_export_symbols, $1)=no -_LT_TAGVAR(archive_expsym_cmds, $1)= -_LT_TAGVAR(compiler_needs_object, $1)=no -_LT_TAGVAR(export_dynamic_flag_spec, $1)= -_LT_TAGVAR(hardcode_direct, $1)=no -_LT_TAGVAR(hardcode_direct_absolute, $1)=no -_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= -_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= -_LT_TAGVAR(hardcode_libdir_separator, $1)= -_LT_TAGVAR(hardcode_minus_L, $1)=no -_LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported -_LT_TAGVAR(hardcode_automatic, $1)=no -_LT_TAGVAR(inherit_rpath, $1)=no -_LT_TAGVAR(module_cmds, $1)= -_LT_TAGVAR(module_expsym_cmds, $1)= -_LT_TAGVAR(link_all_deplibs, $1)=unknown -_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds -_LT_TAGVAR(no_undefined_flag, $1)= -_LT_TAGVAR(whole_archive_flag_spec, $1)= -_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no - -# Source file extension for C++ test sources. -ac_ext=cpp - -# Object file extension for compiled C++ test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# No sense in running all these tests if we already determined that -# the CXX compiler isn't working. Some variables (like enable_shared) -# are currently assumed to apply to all compilers on this platform, -# and will be corrupted by setting them based on a non-working compiler. -if test "$_lt_caught_CXX_error" != yes; then - # Code to be used in simple compile tests - lt_simple_compile_test_code="int some_variable = 0;" - - # Code to be used in simple link tests - lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' - - # ltmain only uses $CC for tagged configurations so make sure $CC is set. - _LT_TAG_COMPILER - - # save warnings/boilerplate of simple test code - _LT_COMPILER_BOILERPLATE - _LT_LINKER_BOILERPLATE - - # Allow CC to be a program name with arguments. - lt_save_CC=$CC - lt_save_LD=$LD - lt_save_GCC=$GCC - GCC=$GXX - lt_save_with_gnu_ld=$with_gnu_ld - lt_save_path_LD=$lt_cv_path_LD - if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then - lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx - else - $as_unset lt_cv_prog_gnu_ld - fi - if test -n "${lt_cv_path_LDCXX+set}"; then - lt_cv_path_LD=$lt_cv_path_LDCXX - else - $as_unset lt_cv_path_LD - fi - test -z "${LDCXX+set}" || LD=$LDCXX - CC=${CXX-"c++"} - compiler=$CC - _LT_TAGVAR(compiler, $1)=$CC - _LT_CC_BASENAME([$compiler]) - - if test -n "$compiler"; then - # We don't want -fno-exception when compiling C++ code, so set the - # no_builtin_flag separately - if test "$GXX" = yes; then - _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' - else - _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= - fi - - if test "$GXX" = yes; then - # Set up default GNU C++ configuration - - LT_PATH_LD - - # Check if GNU C++ uses GNU ld as the underlying linker, since the - # archiving commands below assume that GNU ld is being used. - if test "$with_gnu_ld" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - - # If archive_cmds runs LD, not CC, wlarc should be empty - # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to - # investigate it a little bit more. (MM) - wlarc='${wl}' - - # ancient GNU ld didn't support --whole-archive et. al. - if eval "`$CC -print-prog-name=ld` --help 2>&1" | - $GREP 'no-whole-archive' > /dev/null; then - _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' - else - _LT_TAGVAR(whole_archive_flag_spec, $1)= - fi - else - with_gnu_ld=no - wlarc= - - # A generic and very simple default shared library creation - # command for GNU C++ for the case where it uses the native - # linker, instead of GNU ld. If possible, this setting should - # overridden to take advantage of the native linker features on - # the platform it is being used on. - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' - fi - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' - - else - GXX=no - with_gnu_ld=no - wlarc= - fi - - # PORTME: fill in a description of your system's C++ link characteristics - AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) - _LT_TAGVAR(ld_shlibs, $1)=yes - case $host_os in - aix3*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - aix[[4-9]]*) - if test "$host_cpu" = ia64; then - # On IA64, the linker does run time linking by default, so we don't - # have to do anything special. - aix_use_runtimelinking=no - exp_sym_flag='-Bexport' - no_entry_flag="" - else - aix_use_runtimelinking=no - - # Test if we are trying to use run time linking or normal - # AIX style linking. If -brtl is somewhere in LDFLAGS, we - # need to do runtime linking. - case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) - for ld_flag in $LDFLAGS; do - case $ld_flag in - *-brtl*) - aix_use_runtimelinking=yes - break - ;; - esac - done - ;; - esac - - exp_sym_flag='-bexport' - no_entry_flag='-bnoentry' - fi - - # When large executables or shared objects are built, AIX ld can - # have problems creating the table of contents. If linking a library - # or program results in "error TOC overflow" add -mminimal-toc to - # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not - # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. - - _LT_TAGVAR(archive_cmds, $1)='' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(hardcode_libdir_separator, $1)=':' - _LT_TAGVAR(link_all_deplibs, $1)=yes - _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' - - if test "$GXX" = yes; then - case $host_os in aix4.[[012]]|aix4.[[012]].*) - # We only want to do this on AIX 4.2 and lower, the check - # below for broken collect2 doesn't work under 4.3+ - collect2name=`${CC} -print-prog-name=collect2` - if test -f "$collect2name" && - strings "$collect2name" | $GREP resolve_lib_name >/dev/null - then - # We have reworked collect2 - : - else - # We have old collect2 - _LT_TAGVAR(hardcode_direct, $1)=unsupported - # It fails to find uninstalled libraries when the uninstalled - # path is not listed in the libpath. Setting hardcode_minus_L - # to unsupported forces relinking - _LT_TAGVAR(hardcode_minus_L, $1)=yes - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)= - fi - esac - shared_flag='-shared' - if test "$aix_use_runtimelinking" = yes; then - shared_flag="$shared_flag "'${wl}-G' - fi - else - # not using gcc - if test "$host_cpu" = ia64; then - # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release - # chokes on -Wl,-G. The following line is correct: - shared_flag='-G' - else - if test "$aix_use_runtimelinking" = yes; then - shared_flag='${wl}-G' - else - shared_flag='${wl}-bM:SRE' - fi - fi - fi - - # It seems that -bexpall does not export symbols beginning with - # underscore (_), so it is better to generate a list of symbols to - # export. - _LT_TAGVAR(always_export_symbols, $1)=yes - if test "$aix_use_runtimelinking" = yes; then - # Warning - without using the other runtime loading flags (-brtl), - # -berok will link without error, but may produce a broken library. - _LT_TAGVAR(allow_undefined_flag, $1)='-berok' - # Determine the default libpath from the value encoded in an empty - # executable. - _LT_SYS_MODULE_PATH_AIX - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" - - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" - else - if test "$host_cpu" = ia64; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' - _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" - _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" - else - # Determine the default libpath from the value encoded in an - # empty executable. - _LT_SYS_MODULE_PATH_AIX - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" - # Warning - without using the other run time loading flags, - # -berok will link without error, but may produce a broken library. - _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' - # Exported symbols can be pulled into shared objects from archives - _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' - _LT_TAGVAR(archive_cmds_need_lc, $1)=yes - # This is similar to how AIX traditionally builds its shared - # libraries. - _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' - fi - fi - ;; - - beos*) - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - # Joseph Beckenbach says some releases of gcc - # support --undefined. This deserves some investigation. FIXME - _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - chorus*) - case $cc_basename in - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - ;; - - cygwin* | mingw* | pw32*) - # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, - # as there is no search path for DLLs. - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' - _LT_TAGVAR(allow_undefined_flag, $1)=unsupported - _LT_TAGVAR(always_export_symbols, $1)=no - _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes - - if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - # If the export-symbols file already is a .def file (1st line - # is EXPORTS), use it as is; otherwise, prepend... - _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then - cp $export_symbols $output_objdir/$soname.def; - else - echo EXPORTS > $output_objdir/$soname.def; - cat $export_symbols >> $output_objdir/$soname.def; - fi~ - $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - darwin* | rhapsody*) - _LT_DARWIN_LINKER_FEATURES($1) - ;; - - dgux*) - case $cc_basename in - ec++*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - ghcx*) - # Green Hills C++ Compiler - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - ;; - - freebsd[[12]]*) - # C++ shared libraries reported to be fairly broken before - # switch to ELF - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - freebsd-elf*) - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - ;; - - freebsd* | dragonfly*) - # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF - # conventions - _LT_TAGVAR(ld_shlibs, $1)=yes - ;; - - gnu*) - ;; - - hpux9*) - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, - # but as the default - # location of the library. - - case $cc_basename in - CC*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - aCC*) - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - # - # There doesn't appear to be a way to prevent this compiler from - # explicitly linking system object files so we need to strip them - # from the output so that they don't get included in the library - # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' - ;; - *) - if test "$GXX" = yes; then - _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - else - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - esac - ;; - - hpux10*|hpux11*) - if test $with_gnu_ld = no; then - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - case $host_cpu in - hppa*64*|ia64*) - ;; - *) - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - ;; - esac - fi - case $host_cpu in - hppa*64*|ia64*) - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - ;; - *) - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, - # but as the default - # location of the library. - ;; - esac - - case $cc_basename in - CC*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - aCC*) - case $host_cpu in - hppa*64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - ia64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - esac - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - # - # There doesn't appear to be a way to prevent this compiler from - # explicitly linking system object files so we need to strip them - # from the output so that they don't get included in the library - # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' - ;; - *) - if test "$GXX" = yes; then - if test $with_gnu_ld = no; then - case $host_cpu in - hppa*64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - ia64*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - ;; - esac - fi - else - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - esac - ;; - - interix[[3-9]]*) - _LT_TAGVAR(hardcode_direct, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. - # Instead, shared libraries are loaded at an image base (0x10000000 by - # default) and relocated if they conflict, which is a slow very memory - # consuming and fragmenting process. To avoid this, we pick a random, - # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link - # time. Moving up from 0x10000000 also allows more sbrk(2) space. - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - ;; - irix5* | irix6*) - case $cc_basename in - CC*) - # SGI C++ - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - - # Archives containing C++ object files must be created using - # "CC -ar", where "CC" is the IRIX C++ compiler. This is - # necessary to make sure instantiated templates are included - # in the archive. - _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' - ;; - *) - if test "$GXX" = yes; then - if test "$with_gnu_ld" = no; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - else - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` -o $lib' - fi - fi - _LT_TAGVAR(link_all_deplibs, $1)=yes - ;; - esac - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - _LT_TAGVAR(inherit_rpath, $1)=yes - ;; - - linux* | k*bsd*-gnu) - case $cc_basename in - KCC*) - # Kuck and Associates, Inc. (KAI) C++ Compiler - - # KCC will only create a shared library if the output file - # ends with ".so" (or ".sl" for HP-UX), so rename the library - # to its proper name (with version) after linking. - _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - # - # There doesn't appear to be a way to prevent this compiler from - # explicitly linking system object files so we need to strip them - # from the output so that they don't get included in the library - # dependencies. - output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - - # Archives containing C++ object files must be created using - # "CC -Bstatic", where "CC" is the KAI C++ compiler. - _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' - ;; - icpc* | ecpc* ) - # Intel C++ - with_gnu_ld=yes - # version 8.0 and above of icpc choke on multiply defined symbols - # if we add $predep_objects and $postdep_objects, however 7.1 and - # earlier do not add the objects themselves. - case `$CC -V 2>&1` in - *"Version 7."*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - ;; - *) # Version 8.0 or newer - tmp_idyn= - case $host_cpu in - ia64*) tmp_idyn=' -i_dynamic';; - esac - _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - ;; - esac - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' - ;; - pgCC* | pgcpp*) - # Portland Group C++ compiler - case `$CC -V` in - *pgCC\ [[1-5]]* | *pgcpp\ [[1-5]]*) - _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ - rm -rf $tpldir~ - $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ - compile_command="$compile_command `find $tpldir -name \*.o | $NL2SP`"' - _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ - rm -rf $tpldir~ - $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ - $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | $NL2SP`~ - $RANLIB $oldlib' - _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ - rm -rf $tpldir~ - $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ - $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ - rm -rf $tpldir~ - $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ - $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' - ;; - *) # Version 6 will use weak symbols - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' - ;; - esac - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - ;; - cxx*) - # Compaq C++ - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' - - runpath_var=LD_RUN_PATH - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - # - # There doesn't appear to be a way to prevent this compiler from - # explicitly linking system object files so we need to strip them - # from the output so that they don't get included in the library - # dependencies. - output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' - ;; - xl*) - # IBM XL 8.0 on PPC, with GNU ld - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' - _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - if test "x$supports_anon_versioning" = xyes; then - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ - cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ - echo "local: *; };" >> $output_objdir/$libname.ver~ - $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' - fi - ;; - *) - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) - # Sun C++ 5.9 - _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' - _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - _LT_TAGVAR(compiler_needs_object, $1)=yes - - # Not sure whether something based on - # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 - # would be better. - output_verbose_link_cmd='echo' - - # Archives containing C++ object files must be created using - # "CC -xar", where "CC" is the Sun C++ compiler. This is - # necessary to make sure instantiated templates are included - # in the archive. - _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' - ;; - esac - ;; - esac - ;; - - lynxos*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - m88k*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - mvs*) - case $cc_basename in - cxx*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - ;; - - netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' - wlarc= - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - fi - # Workaround some broken pre-1.5 toolchains - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' - ;; - - *nto* | *qnx*) - _LT_TAGVAR(ld_shlibs, $1)=yes - ;; - - openbsd2*) - # C++ shared libraries are fairly broken - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - openbsd*) - if test -f /usr/libexec/ld.so; then - _LT_TAGVAR(hardcode_direct, $1)=yes - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_direct_absolute, $1)=yes - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' - _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' - fi - output_verbose_link_cmd=echo - else - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - - osf3* | osf4* | osf5*) - case $cc_basename in - KCC*) - # Kuck and Associates, Inc. (KAI) C++ Compiler - - # KCC will only create a shared library if the output file - # ends with ".so" (or ".sl" for HP-UX), so rename the library - # to its proper name (with version) after linking. - _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - # Archives containing C++ object files must be created using - # the KAI C++ compiler. - case $host in - osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; - *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; - esac - ;; - RCC*) - # Rational C++ 2.4.1 - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - cxx*) - case $host in - osf3*) - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && $ECHO "X${wl}-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - ;; - *) - _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' - _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ - echo "-hidden">> $lib.exp~ - $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~ - $RM $lib.exp' - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' - ;; - esac - - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - # - # There doesn't appear to be a way to prevent this compiler from - # explicitly linking system object files so we need to strip them - # from the output so that they don't get included in the library - # dependencies. - output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`$ECHO "X$templist" | $Xsed -e "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; $ECHO "X$list" | $Xsed' - ;; - *) - if test "$GXX" = yes && test "$with_gnu_ld" = no; then - _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' - case $host in - osf3*) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - ;; - esac - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=: - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' - - else - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - fi - ;; - esac - ;; - - psos*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - sunos4*) - case $cc_basename in - CC*) - # Sun C++ 4.x - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - lcc*) - # Lucid - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - ;; - - solaris*) - case $cc_basename in - CC*) - # Sun C++ 4.2, 5.x and Centerline C++ - _LT_TAGVAR(archive_cmds_need_lc,$1)=yes - _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' - _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - case $host_os in - solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; - *) - # The compiler driver will combine and reorder linker options, - # but understands `-z linker_flag'. - # Supported since Solaris 2.6 (maybe 2.5.1?) - _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' - ;; - esac - _LT_TAGVAR(link_all_deplibs, $1)=yes - - output_verbose_link_cmd='echo' - - # Archives containing C++ object files must be created using - # "CC -xar", where "CC" is the Sun C++ compiler. This is - # necessary to make sure instantiated templates are included - # in the archive. - _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' - ;; - gcx*) - # Green Hills C++ Compiler - _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' - - # The C++ compiler must be used to create the archive. - _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' - ;; - *) - # GNU C++ compiler with Solaris linker - if test "$GXX" = yes && test "$with_gnu_ld" = no; then - _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' - if $CC --version | $GREP -v '^2\.7' > /dev/null; then - _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -shared -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' - else - # g++ 2.7 appears to require `-G' NOT `-shared' on this - # platform. - _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' - _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' - - # Commands to make compiler produce verbose output that lists - # what "hidden" libraries, object files and flags are used when - # linking a shared library. - output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP "\-L"' - fi - - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' - case $host_os in - solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; - *) - _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' - ;; - esac - fi - ;; - esac - ;; - - sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) - _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - runpath_var='LD_RUN_PATH' - - case $cc_basename in - CC*) - _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - ;; - - sysv5* | sco3.2v5* | sco5v6*) - # Note: We can NOT use -z defs as we might desire, because we do not - # link with -lc, and that would cause any symbols used from libc to - # always be unresolved, which means just about no library would - # ever link correctly. If we're not using GNU ld we use -z text - # though, which does catch some bad symbols but isn't as heavy-handed - # as -z defs. - _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' - _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' - _LT_TAGVAR(archive_cmds_need_lc, $1)=no - _LT_TAGVAR(hardcode_shlibpath_var, $1)=no - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' - _LT_TAGVAR(hardcode_libdir_separator, $1)=':' - _LT_TAGVAR(link_all_deplibs, $1)=yes - _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' - runpath_var='LD_RUN_PATH' - - case $cc_basename in - CC*) - _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - ;; - - tandem*) - case $cc_basename in - NCC*) - # NonStop-UX NCC 3.20 - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - ;; - - vxworks*) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - - *) - # FIXME: insert proper C++ library support - _LT_TAGVAR(ld_shlibs, $1)=no - ;; - esac - - AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) - test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no - - _LT_TAGVAR(GCC, $1)="$GXX" - _LT_TAGVAR(LD, $1)="$LD" - - ## CAVEAT EMPTOR: - ## There is no encapsulation within the following macros, do not change - ## the running order or otherwise move them around unless you know exactly - ## what you are doing... - _LT_SYS_HIDDEN_LIBDEPS($1) - _LT_COMPILER_PIC($1) - _LT_COMPILER_C_O($1) - _LT_COMPILER_FILE_LOCKS($1) - _LT_LINKER_SHLIBS($1) - _LT_SYS_DYNAMIC_LINKER($1) - _LT_LINKER_HARDCODE_LIBPATH($1) - - _LT_CONFIG($1) - fi # test -n "$compiler" - - CC=$lt_save_CC - LDCXX=$LD - LD=$lt_save_LD - GCC=$lt_save_GCC - with_gnu_ld=$lt_save_with_gnu_ld - lt_cv_path_LDCXX=$lt_cv_path_LD - lt_cv_path_LD=$lt_save_path_LD - lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld - lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld -fi # test "$_lt_caught_CXX_error" != yes - -AC_LANG_POP -])# _LT_LANG_CXX_CONFIG - - -# _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) -# --------------------------------- -# Figure out "hidden" library dependencies from verbose -# compiler output when linking a shared library. -# Parse the compiler output and extract the necessary -# objects, libraries and library flags. -m4_defun([_LT_SYS_HIDDEN_LIBDEPS], -[m4_require([_LT_FILEUTILS_DEFAULTS])dnl -# Dependencies to place before and after the object being linked: -_LT_TAGVAR(predep_objects, $1)= -_LT_TAGVAR(postdep_objects, $1)= -_LT_TAGVAR(predeps, $1)= -_LT_TAGVAR(postdeps, $1)= -_LT_TAGVAR(compiler_lib_search_path, $1)= - -dnl we can't use the lt_simple_compile_test_code here, -dnl because it contains code intended for an executable, -dnl not a library. It's possible we should let each -dnl tag define a new lt_????_link_test_code variable, -dnl but it's only used here... -m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF -int a; -void foo (void) { a = 0; } -_LT_EOF -], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF -class Foo -{ -public: - Foo (void) { a = 0; } -private: - int a; -}; -_LT_EOF -], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF - subroutine foo - implicit none - integer*4 a - a=0 - return - end -_LT_EOF -], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF - subroutine foo - implicit none - integer a - a=0 - return - end -_LT_EOF -], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF -public class foo { - private int a; - public void bar (void) { - a = 0; - } -}; -_LT_EOF -]) -dnl Parse the compiler output and extract the necessary -dnl objects, libraries and library flags. -if AC_TRY_EVAL(ac_compile); then - # Parse the compiler output and extract the necessary - # objects, libraries and library flags. - - # Sentinel used to keep track of whether or not we are before - # the conftest object file. - pre_test_object_deps_done=no - - for p in `eval "$output_verbose_link_cmd"`; do - case $p in - - -L* | -R* | -l*) - # Some compilers place space between "-{L,R}" and the path. - # Remove the space. - if test $p = "-L" || - test $p = "-R"; then - prev=$p - continue - else - prev= - fi - - if test "$pre_test_object_deps_done" = no; then - case $p in - -L* | -R*) - # Internal compiler library paths should come after those - # provided the user. The postdeps already come after the - # user supplied libs so there is no need to process them. - if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then - _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" - else - _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" - fi - ;; - # The "-l" case would never come before the object being - # linked, so don't bother handling this case. - esac - else - if test -z "$_LT_TAGVAR(postdeps, $1)"; then - _LT_TAGVAR(postdeps, $1)="${prev}${p}" - else - _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" - fi - fi - ;; - - *.$objext) - # This assumes that the test object file only shows up - # once in the compiler output. - if test "$p" = "conftest.$objext"; then - pre_test_object_deps_done=yes - continue - fi - - if test "$pre_test_object_deps_done" = no; then - if test -z "$_LT_TAGVAR(predep_objects, $1)"; then - _LT_TAGVAR(predep_objects, $1)="$p" - else - _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" - fi - else - if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then - _LT_TAGVAR(postdep_objects, $1)="$p" - else - _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" - fi - fi - ;; - - *) ;; # Ignore the rest. - - esac - done - - # Clean up. - rm -f a.out a.exe -else - echo "libtool.m4: error: problem compiling $1 test program" -fi - -$RM -f confest.$objext - -# PORTME: override above test on systems where it is broken -m4_if([$1], [CXX], -[case $host_os in -interix[[3-9]]*) - # Interix 3.5 installs completely hosed .la files for C++, so rather than - # hack all around it, let's just trust "g++" to DTRT. - _LT_TAGVAR(predep_objects,$1)= - _LT_TAGVAR(postdep_objects,$1)= - _LT_TAGVAR(postdeps,$1)= - ;; - -linux*) - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) - # Sun C++ 5.9 - - # The more standards-conforming stlport4 library is - # incompatible with the Cstd library. Avoid specifying - # it if it's in CXXFLAGS. Ignore libCrun as - # -library=stlport4 depends on it. - case " $CXX $CXXFLAGS " in - *" -library=stlport4 "*) - solaris_use_stlport4=yes - ;; - esac - - if test "$solaris_use_stlport4" != yes; then - _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' - fi - ;; - esac - ;; - -solaris*) - case $cc_basename in - CC*) - # The more standards-conforming stlport4 library is - # incompatible with the Cstd library. Avoid specifying - # it if it's in CXXFLAGS. Ignore libCrun as - # -library=stlport4 depends on it. - case " $CXX $CXXFLAGS " in - *" -library=stlport4 "*) - solaris_use_stlport4=yes - ;; - esac - - # Adding this requires a known-good setup of shared libraries for - # Sun compiler versions before 5.6, else PIC objects from an old - # archive will be linked into the output, leading to subtle bugs. - if test "$solaris_use_stlport4" != yes; then - _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' - fi - ;; - esac - ;; -esac -]) - -case " $_LT_TAGVAR(postdeps, $1) " in -*" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; -esac - _LT_TAGVAR(compiler_lib_search_dirs, $1)= -if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then - _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` -fi -_LT_TAGDECL([], [compiler_lib_search_dirs], [1], - [The directories searched by this compiler when creating a shared library]) -_LT_TAGDECL([], [predep_objects], [1], - [Dependencies to place before and after the objects being linked to - create a shared library]) -_LT_TAGDECL([], [postdep_objects], [1]) -_LT_TAGDECL([], [predeps], [1]) -_LT_TAGDECL([], [postdeps], [1]) -_LT_TAGDECL([], [compiler_lib_search_path], [1], - [The library search path used internally by the compiler when linking - a shared library]) -])# _LT_SYS_HIDDEN_LIBDEPS - - -# _LT_PROG_F77 -# ------------ -# Since AC_PROG_F77 is broken, in that it returns the empty string -# if there is no fortran compiler, we have our own version here. -m4_defun([_LT_PROG_F77], -[ -pushdef([AC_MSG_ERROR], [_lt_disable_F77=yes]) -AC_PROG_F77 -if test -z "$F77" || test "X$F77" = "Xno"; then - _lt_disable_F77=yes -fi -popdef([AC_MSG_ERROR]) -])# _LT_PROG_F77 - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([_LT_PROG_F77], []) - - -# _LT_LANG_F77_CONFIG([TAG]) -# -------------------------- -# Ensure that the configuration variables for a Fortran 77 compiler are -# suitably defined. These variables are subsequently used by _LT_CONFIG -# to write the compiler configuration to `libtool'. -m4_defun([_LT_LANG_F77_CONFIG], -[AC_REQUIRE([_LT_PROG_F77])dnl -AC_LANG_PUSH(Fortran 77) - -_LT_TAGVAR(archive_cmds_need_lc, $1)=no -_LT_TAGVAR(allow_undefined_flag, $1)= -_LT_TAGVAR(always_export_symbols, $1)=no -_LT_TAGVAR(archive_expsym_cmds, $1)= -_LT_TAGVAR(export_dynamic_flag_spec, $1)= -_LT_TAGVAR(hardcode_direct, $1)=no -_LT_TAGVAR(hardcode_direct_absolute, $1)=no -_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= -_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= -_LT_TAGVAR(hardcode_libdir_separator, $1)= -_LT_TAGVAR(hardcode_minus_L, $1)=no -_LT_TAGVAR(hardcode_automatic, $1)=no -_LT_TAGVAR(inherit_rpath, $1)=no -_LT_TAGVAR(module_cmds, $1)= -_LT_TAGVAR(module_expsym_cmds, $1)= -_LT_TAGVAR(link_all_deplibs, $1)=unknown -_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds -_LT_TAGVAR(no_undefined_flag, $1)= -_LT_TAGVAR(whole_archive_flag_spec, $1)= -_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no - -# Source file extension for f77 test sources. -ac_ext=f - -# Object file extension for compiled f77 test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# No sense in running all these tests if we already determined that -# the F77 compiler isn't working. Some variables (like enable_shared) -# are currently assumed to apply to all compilers on this platform, -# and will be corrupted by setting them based on a non-working compiler. -if test "$_lt_disable_F77" != yes; then - # Code to be used in simple compile tests - lt_simple_compile_test_code="\ - subroutine t - return - end -" - - # Code to be used in simple link tests - lt_simple_link_test_code="\ - program t - end -" - - # ltmain only uses $CC for tagged configurations so make sure $CC is set. - _LT_TAG_COMPILER - - # save warnings/boilerplate of simple test code - _LT_COMPILER_BOILERPLATE - _LT_LINKER_BOILERPLATE - - # Allow CC to be a program name with arguments. - lt_save_CC="$CC" - lt_save_GCC=$GCC - CC=${F77-"f77"} - compiler=$CC - _LT_TAGVAR(compiler, $1)=$CC - _LT_CC_BASENAME([$compiler]) - GCC=$G77 - if test -n "$compiler"; then - AC_MSG_CHECKING([if libtool supports shared libraries]) - AC_MSG_RESULT([$can_build_shared]) - - AC_MSG_CHECKING([whether to build shared libraries]) - test "$can_build_shared" = "no" && enable_shared=no - - # On AIX, shared libraries and static libraries use the same namespace, and - # are all built from PIC. - case $host_os in - aix3*) - test "$enable_shared" = yes && enable_static=no - if test -n "$RANLIB"; then - archive_cmds="$archive_cmds~\$RANLIB \$lib" - postinstall_cmds='$RANLIB $lib' - fi - ;; - aix[[4-9]]*) - if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then - test "$enable_shared" = yes && enable_static=no - fi - ;; - esac - AC_MSG_RESULT([$enable_shared]) - - AC_MSG_CHECKING([whether to build static libraries]) - # Make sure either enable_shared or enable_static is yes. - test "$enable_shared" = yes || enable_static=yes - AC_MSG_RESULT([$enable_static]) - - _LT_TAGVAR(GCC, $1)="$G77" - _LT_TAGVAR(LD, $1)="$LD" - - ## CAVEAT EMPTOR: - ## There is no encapsulation within the following macros, do not change - ## the running order or otherwise move them around unless you know exactly - ## what you are doing... - _LT_COMPILER_PIC($1) - _LT_COMPILER_C_O($1) - _LT_COMPILER_FILE_LOCKS($1) - _LT_LINKER_SHLIBS($1) - _LT_SYS_DYNAMIC_LINKER($1) - _LT_LINKER_HARDCODE_LIBPATH($1) - - _LT_CONFIG($1) - fi # test -n "$compiler" - - GCC=$lt_save_GCC - CC="$lt_save_CC" -fi # test "$_lt_disable_F77" != yes - -AC_LANG_POP -])# _LT_LANG_F77_CONFIG - - -# _LT_PROG_FC -# ----------- -# Since AC_PROG_FC is broken, in that it returns the empty string -# if there is no fortran compiler, we have our own version here. -m4_defun([_LT_PROG_FC], -[ -pushdef([AC_MSG_ERROR], [_lt_disable_FC=yes]) -AC_PROG_FC -if test -z "$FC" || test "X$FC" = "Xno"; then - _lt_disable_FC=yes -fi -popdef([AC_MSG_ERROR]) -])# _LT_PROG_FC - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([_LT_PROG_FC], []) - - -# _LT_LANG_FC_CONFIG([TAG]) -# ------------------------- -# Ensure that the configuration variables for a Fortran compiler are -# suitably defined. These variables are subsequently used by _LT_CONFIG -# to write the compiler configuration to `libtool'. -m4_defun([_LT_LANG_FC_CONFIG], -[AC_REQUIRE([_LT_PROG_FC])dnl -AC_LANG_PUSH(Fortran) - -_LT_TAGVAR(archive_cmds_need_lc, $1)=no -_LT_TAGVAR(allow_undefined_flag, $1)= -_LT_TAGVAR(always_export_symbols, $1)=no -_LT_TAGVAR(archive_expsym_cmds, $1)= -_LT_TAGVAR(export_dynamic_flag_spec, $1)= -_LT_TAGVAR(hardcode_direct, $1)=no -_LT_TAGVAR(hardcode_direct_absolute, $1)=no -_LT_TAGVAR(hardcode_libdir_flag_spec, $1)= -_LT_TAGVAR(hardcode_libdir_flag_spec_ld, $1)= -_LT_TAGVAR(hardcode_libdir_separator, $1)= -_LT_TAGVAR(hardcode_minus_L, $1)=no -_LT_TAGVAR(hardcode_automatic, $1)=no -_LT_TAGVAR(inherit_rpath, $1)=no -_LT_TAGVAR(module_cmds, $1)= -_LT_TAGVAR(module_expsym_cmds, $1)= -_LT_TAGVAR(link_all_deplibs, $1)=unknown -_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds -_LT_TAGVAR(no_undefined_flag, $1)= -_LT_TAGVAR(whole_archive_flag_spec, $1)= -_LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no - -# Source file extension for fc test sources. -ac_ext=${ac_fc_srcext-f} - -# Object file extension for compiled fc test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# No sense in running all these tests if we already determined that -# the FC compiler isn't working. Some variables (like enable_shared) -# are currently assumed to apply to all compilers on this platform, -# and will be corrupted by setting them based on a non-working compiler. -if test "$_lt_disable_FC" != yes; then - # Code to be used in simple compile tests - lt_simple_compile_test_code="\ - subroutine t - return - end -" - - # Code to be used in simple link tests - lt_simple_link_test_code="\ - program t - end -" - - # ltmain only uses $CC for tagged configurations so make sure $CC is set. - _LT_TAG_COMPILER - - # save warnings/boilerplate of simple test code - _LT_COMPILER_BOILERPLATE - _LT_LINKER_BOILERPLATE - - # Allow CC to be a program name with arguments. - lt_save_CC="$CC" - lt_save_GCC=$GCC - CC=${FC-"f95"} - compiler=$CC - GCC=$ac_cv_fc_compiler_gnu - - _LT_TAGVAR(compiler, $1)=$CC - _LT_CC_BASENAME([$compiler]) - - if test -n "$compiler"; then - AC_MSG_CHECKING([if libtool supports shared libraries]) - AC_MSG_RESULT([$can_build_shared]) - - AC_MSG_CHECKING([whether to build shared libraries]) - test "$can_build_shared" = "no" && enable_shared=no - - # On AIX, shared libraries and static libraries use the same namespace, and - # are all built from PIC. - case $host_os in - aix3*) - test "$enable_shared" = yes && enable_static=no - if test -n "$RANLIB"; then - archive_cmds="$archive_cmds~\$RANLIB \$lib" - postinstall_cmds='$RANLIB $lib' - fi - ;; - aix[[4-9]]*) - if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then - test "$enable_shared" = yes && enable_static=no - fi - ;; - esac - AC_MSG_RESULT([$enable_shared]) - - AC_MSG_CHECKING([whether to build static libraries]) - # Make sure either enable_shared or enable_static is yes. - test "$enable_shared" = yes || enable_static=yes - AC_MSG_RESULT([$enable_static]) - - _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" - _LT_TAGVAR(LD, $1)="$LD" - - ## CAVEAT EMPTOR: - ## There is no encapsulation within the following macros, do not change - ## the running order or otherwise move them around unless you know exactly - ## what you are doing... - _LT_SYS_HIDDEN_LIBDEPS($1) - _LT_COMPILER_PIC($1) - _LT_COMPILER_C_O($1) - _LT_COMPILER_FILE_LOCKS($1) - _LT_LINKER_SHLIBS($1) - _LT_SYS_DYNAMIC_LINKER($1) - _LT_LINKER_HARDCODE_LIBPATH($1) - - _LT_CONFIG($1) - fi # test -n "$compiler" - - GCC=$lt_save_GCC - CC="$lt_save_CC" -fi # test "$_lt_disable_FC" != yes - -AC_LANG_POP -])# _LT_LANG_FC_CONFIG - - -# _LT_LANG_GCJ_CONFIG([TAG]) -# -------------------------- -# Ensure that the configuration variables for the GNU Java Compiler compiler -# are suitably defined. These variables are subsequently used by _LT_CONFIG -# to write the compiler configuration to `libtool'. -m4_defun([_LT_LANG_GCJ_CONFIG], -[AC_REQUIRE([LT_PROG_GCJ])dnl -AC_LANG_SAVE - -# Source file extension for Java test sources. -ac_ext=java - -# Object file extension for compiled Java test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# Code to be used in simple compile tests -lt_simple_compile_test_code="class foo {}" - -# Code to be used in simple link tests -lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' - -# ltmain only uses $CC for tagged configurations so make sure $CC is set. -_LT_TAG_COMPILER - -# save warnings/boilerplate of simple test code -_LT_COMPILER_BOILERPLATE -_LT_LINKER_BOILERPLATE - -# Allow CC to be a program name with arguments. -lt_save_CC="$CC" -lt_save_GCC=$GCC -GCC=yes -CC=${GCJ-"gcj"} -compiler=$CC -_LT_TAGVAR(compiler, $1)=$CC -_LT_TAGVAR(LD, $1)="$LD" -_LT_CC_BASENAME([$compiler]) - -# GCJ did not exist at the time GCC didn't implicitly link libc in. -_LT_TAGVAR(archive_cmds_need_lc, $1)=no - -_LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds - -## CAVEAT EMPTOR: -## There is no encapsulation within the following macros, do not change -## the running order or otherwise move them around unless you know exactly -## what you are doing... -if test -n "$compiler"; then - _LT_COMPILER_NO_RTTI($1) - _LT_COMPILER_PIC($1) - _LT_COMPILER_C_O($1) - _LT_COMPILER_FILE_LOCKS($1) - _LT_LINKER_SHLIBS($1) - _LT_LINKER_HARDCODE_LIBPATH($1) - - _LT_CONFIG($1) -fi - -AC_LANG_RESTORE - -GCC=$lt_save_GCC -CC="$lt_save_CC" -])# _LT_LANG_GCJ_CONFIG - - -# _LT_LANG_RC_CONFIG([TAG]) -# ------------------------- -# Ensure that the configuration variables for the Windows resource compiler -# are suitably defined. These variables are subsequently used by _LT_CONFIG -# to write the compiler configuration to `libtool'. -m4_defun([_LT_LANG_RC_CONFIG], -[AC_REQUIRE([LT_PROG_RC])dnl -AC_LANG_SAVE - -# Source file extension for RC test sources. -ac_ext=rc - -# Object file extension for compiled RC test sources. -objext=o -_LT_TAGVAR(objext, $1)=$objext - -# Code to be used in simple compile tests -lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' - -# Code to be used in simple link tests -lt_simple_link_test_code="$lt_simple_compile_test_code" - -# ltmain only uses $CC for tagged configurations so make sure $CC is set. -_LT_TAG_COMPILER - -# save warnings/boilerplate of simple test code -_LT_COMPILER_BOILERPLATE -_LT_LINKER_BOILERPLATE - -# Allow CC to be a program name with arguments. -lt_save_CC="$CC" -lt_save_GCC=$GCC -GCC= -CC=${RC-"windres"} -compiler=$CC -_LT_TAGVAR(compiler, $1)=$CC -_LT_CC_BASENAME([$compiler]) -_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes - -if test -n "$compiler"; then - : - _LT_CONFIG($1) -fi - -GCC=$lt_save_GCC -AC_LANG_RESTORE -CC="$lt_save_CC" -])# _LT_LANG_RC_CONFIG - - -# LT_PROG_GCJ -# ----------- -AC_DEFUN([LT_PROG_GCJ], -[m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], - [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], - [AC_CHECK_TOOL(GCJ, gcj,) - test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" - AC_SUBST(GCJFLAGS)])])[]dnl -]) - -# Old name: -AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([LT_AC_PROG_GCJ], []) - - -# LT_PROG_RC -# ---------- -AC_DEFUN([LT_PROG_RC], -[AC_CHECK_TOOL(RC, windres,) -]) - -# Old name: -AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([LT_AC_PROG_RC], []) - - -# _LT_DECL_EGREP -# -------------- -# If we don't have a new enough Autoconf to choose the best grep -# available, choose the one first in the user's PATH. -m4_defun([_LT_DECL_EGREP], -[AC_REQUIRE([AC_PROG_EGREP])dnl -AC_REQUIRE([AC_PROG_FGREP])dnl -test -z "$GREP" && GREP=grep -_LT_DECL([], [GREP], [1], [A grep program that handles long lines]) -_LT_DECL([], [EGREP], [1], [An ERE matcher]) -_LT_DECL([], [FGREP], [1], [A literal string matcher]) -dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too -AC_SUBST([GREP]) -]) - - -# _LT_DECL_SED -# ------------ -# Check for a fully-functional sed program, that truncates -# as few characters as possible. Prefer GNU sed if found. -m4_defun([_LT_DECL_SED], -[AC_PROG_SED -test -z "$SED" && SED=sed -Xsed="$SED -e 1s/^X//" -_LT_DECL([], [SED], [1], [A sed program that does not truncate output]) -_LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], - [Sed that helps us avoid accidentally triggering echo(1) options like -n]) -])# _LT_DECL_SED - -m4_ifndef([AC_PROG_SED], [ -############################################################ -# NOTE: This macro has been submitted for inclusion into # -# GNU Autoconf as AC_PROG_SED. When it is available in # -# a released version of Autoconf we should remove this # -# macro and use it instead. # -############################################################ - -m4_defun([AC_PROG_SED], -[AC_MSG_CHECKING([for a sed that does not truncate output]) -AC_CACHE_VAL(lt_cv_path_SED, -[# Loop through the user's path and test for sed and gsed. -# Then use that list of sed's as ones to test for truncation. -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for lt_ac_prog in sed gsed; do - for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then - lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" - fi - done - done -done -IFS=$as_save_IFS -lt_ac_max=0 -lt_ac_count=0 -# Add /usr/xpg4/bin/sed as it is typically found on Solaris -# along with /bin/sed that truncates output. -for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do - test ! -f $lt_ac_sed && continue - cat /dev/null > conftest.in - lt_ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >conftest.in - # Check for GNU sed and select it if it is found. - if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then - lt_cv_path_SED=$lt_ac_sed - break - fi - while true; do - cat conftest.in conftest.in >conftest.tmp - mv conftest.tmp conftest.in - cp conftest.in conftest.nl - echo >>conftest.nl - $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break - cmp -s conftest.out conftest.nl || break - # 10000 chars as input seems more than enough - test $lt_ac_count -gt 10 && break - lt_ac_count=`expr $lt_ac_count + 1` - if test $lt_ac_count -gt $lt_ac_max; then - lt_ac_max=$lt_ac_count - lt_cv_path_SED=$lt_ac_sed - fi - done -done -]) -SED=$lt_cv_path_SED -AC_SUBST([SED]) -AC_MSG_RESULT([$SED]) -])#AC_PROG_SED -])#m4_ifndef - -# Old name: -AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([LT_AC_PROG_SED], []) - - -# _LT_CHECK_SHELL_FEATURES -# ------------------------ -# Find out whether the shell is Bourne or XSI compatible, -# or has some other useful features. -m4_defun([_LT_CHECK_SHELL_FEATURES], -[AC_MSG_CHECKING([whether the shell understands some XSI constructs]) -# Try some XSI features -xsi_shell=no -( _lt_dummy="a/b/c" - test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \ - = c,a/b,, \ - && eval 'test $(( 1 + 1 )) -eq 2 \ - && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ - && xsi_shell=yes -AC_MSG_RESULT([$xsi_shell]) -_LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) - -AC_MSG_CHECKING([whether the shell understands "+="]) -lt_shell_append=no -( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ - >/dev/null 2>&1 \ - && lt_shell_append=yes -AC_MSG_RESULT([$lt_shell_append]) -_LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) - -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - lt_unset=unset -else - lt_unset=false -fi -_LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl - -# test EBCDIC or ASCII -case `echo X|tr X '\101'` in - A) # ASCII based system - # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr - lt_SP2NL='tr \040 \012' - lt_NL2SP='tr \015\012 \040\040' - ;; - *) # EBCDIC based system - lt_SP2NL='tr \100 \n' - lt_NL2SP='tr \r\n \100\100' - ;; -esac -_LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl -_LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl -])# _LT_CHECK_SHELL_FEATURES - - -# _LT_PROG_XSI_SHELLFNS -# --------------------- -# Bourne and XSI compatible variants of some useful shell functions. -m4_defun([_LT_PROG_XSI_SHELLFNS], -[case $xsi_shell in - yes) - cat << \_LT_EOF >> "$cfgfile" - -# func_dirname file append nondir_replacement -# Compute the dirname of FILE. If nonempty, add APPEND to the result, -# otherwise set result to NONDIR_REPLACEMENT. -func_dirname () -{ - case ${1} in - */*) func_dirname_result="${1%/*}${2}" ;; - * ) func_dirname_result="${3}" ;; - esac -} - -# func_basename file -func_basename () -{ - func_basename_result="${1##*/}" -} - -# func_dirname_and_basename file append nondir_replacement -# perform func_basename and func_dirname in a single function -# call: -# dirname: Compute the dirname of FILE. If nonempty, -# add APPEND to the result, otherwise set result -# to NONDIR_REPLACEMENT. -# value returned in "$func_dirname_result" -# basename: Compute filename of FILE. -# value retuned in "$func_basename_result" -# Implementation must be kept synchronized with func_dirname -# and func_basename. For efficiency, we do not delegate to -# those functions but instead duplicate the functionality here. -func_dirname_and_basename () -{ - case ${1} in - */*) func_dirname_result="${1%/*}${2}" ;; - * ) func_dirname_result="${3}" ;; - esac - func_basename_result="${1##*/}" -} - -# func_stripname prefix suffix name -# strip PREFIX and SUFFIX off of NAME. -# PREFIX and SUFFIX must not contain globbing or regex special -# characters, hashes, percent signs, but SUFFIX may contain a leading -# dot (in which case that matches only a dot). -func_stripname () -{ - # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are - # positional parameters, so assign one to ordinary parameter first. - func_stripname_result=${3} - func_stripname_result=${func_stripname_result#"${1}"} - func_stripname_result=${func_stripname_result%"${2}"} -} - -# func_opt_split -func_opt_split () -{ - func_opt_split_opt=${1%%=*} - func_opt_split_arg=${1#*=} -} - -# func_lo2o object -func_lo2o () -{ - case ${1} in - *.lo) func_lo2o_result=${1%.lo}.${objext} ;; - *) func_lo2o_result=${1} ;; - esac -} - -# func_xform libobj-or-source -func_xform () -{ - func_xform_result=${1%.*}.lo -} - -# func_arith arithmetic-term... -func_arith () -{ - func_arith_result=$(( $[*] )) -} - -# func_len string -# STRING may not start with a hyphen. -func_len () -{ - func_len_result=${#1} -} - -_LT_EOF - ;; - *) # Bourne compatible functions. - cat << \_LT_EOF >> "$cfgfile" - -# func_dirname file append nondir_replacement -# Compute the dirname of FILE. If nonempty, add APPEND to the result, -# otherwise set result to NONDIR_REPLACEMENT. -func_dirname () -{ - # Extract subdirectory from the argument. - func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` - if test "X$func_dirname_result" = "X${1}"; then - func_dirname_result="${3}" - else - func_dirname_result="$func_dirname_result${2}" - fi -} - -# func_basename file -func_basename () -{ - func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` -} - -dnl func_dirname_and_basename -dnl A portable version of this function is already defined in general.m4sh -dnl so there is no need for it here. - -# func_stripname prefix suffix name -# strip PREFIX and SUFFIX off of NAME. -# PREFIX and SUFFIX must not contain globbing or regex special -# characters, hashes, percent signs, but SUFFIX may contain a leading -# dot (in which case that matches only a dot). -# func_strip_suffix prefix name -func_stripname () -{ - case ${2} in - .*) func_stripname_result=`$ECHO "X${3}" \ - | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;; - *) func_stripname_result=`$ECHO "X${3}" \ - | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;; - esac -} - -# sed scripts: -my_sed_long_opt='1s/^\(-[[^=]]*\)=.*/\1/;q' -my_sed_long_arg='1s/^-[[^=]]*=//' - -# func_opt_split -func_opt_split () -{ - func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"` - func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"` -} - -# func_lo2o object -func_lo2o () -{ - func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"` -} - -# func_xform libobj-or-source -func_xform () -{ - func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[[^.]]*$/.lo/'` -} - -# func_arith arithmetic-term... -func_arith () -{ - func_arith_result=`expr "$[@]"` -} - -# func_len string -# STRING may not start with a hyphen. -func_len () -{ - func_len_result=`expr "$[1]" : ".*" 2>/dev/null || echo $max_cmd_len` -} - -_LT_EOF -esac - -case $lt_shell_append in - yes) - cat << \_LT_EOF >> "$cfgfile" - -# func_append var value -# Append VALUE to the end of shell variable VAR. -func_append () -{ - eval "$[1]+=\$[2]" -} -_LT_EOF - ;; - *) - cat << \_LT_EOF >> "$cfgfile" - -# func_append var value -# Append VALUE to the end of shell variable VAR. -func_append () -{ - eval "$[1]=\$$[1]\$[2]" -} - -_LT_EOF - ;; - esac -]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltoptions.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltoptions.m4 deleted file mode 100644 index e970119..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltoptions.m4 +++ /dev/null @@ -1,368 +0,0 @@ -# Helper functions for option handling. -*- Autoconf -*- -# -# Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. -# Written by Gary V. Vaughan, 2004 -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# serial 6 ltoptions.m4 - -# This is to help aclocal find these macros, as it can't see m4_define. -AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) - - -# _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) -# ------------------------------------------ -m4_define([_LT_MANGLE_OPTION], -[[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) - - -# _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) -# --------------------------------------- -# Set option OPTION-NAME for macro MACRO-NAME, and if there is a -# matching handler defined, dispatch to it. Other OPTION-NAMEs are -# saved as a flag. -m4_define([_LT_SET_OPTION], -[m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl -m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), - _LT_MANGLE_DEFUN([$1], [$2]), - [m4_warning([Unknown $1 option `$2'])])[]dnl -]) - - -# _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) -# ------------------------------------------------------------ -# Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. -m4_define([_LT_IF_OPTION], -[m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) - - -# _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) -# ------------------------------------------------------- -# Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME -# are set. -m4_define([_LT_UNLESS_OPTIONS], -[m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), - [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), - [m4_define([$0_found])])])[]dnl -m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 -])[]dnl -]) - - -# _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) -# ---------------------------------------- -# OPTION-LIST is a space-separated list of Libtool options associated -# with MACRO-NAME. If any OPTION has a matching handler declared with -# LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about -# the unknown option and exit. -m4_defun([_LT_SET_OPTIONS], -[# Set options -m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), - [_LT_SET_OPTION([$1], _LT_Option)]) - -m4_if([$1],[LT_INIT],[ - dnl - dnl Simply set some default values (i.e off) if boolean options were not - dnl specified: - _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no - ]) - _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no - ]) - dnl - dnl If no reference was made to various pairs of opposing options, then - dnl we run the default mode handler for the pair. For example, if neither - dnl `shared' nor `disable-shared' was passed, we enable building of shared - dnl archives by default: - _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) - _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) - _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) - _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], - [_LT_ENABLE_FAST_INSTALL]) - ]) -])# _LT_SET_OPTIONS - - -## --------------------------------- ## -## Macros to handle LT_INIT options. ## -## --------------------------------- ## - -# _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) -# ----------------------------------------- -m4_define([_LT_MANGLE_DEFUN], -[[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) - - -# LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) -# ----------------------------------------------- -m4_define([LT_OPTION_DEFINE], -[m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl -])# LT_OPTION_DEFINE - - -# dlopen -# ------ -LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes -]) - -AU_DEFUN([AC_LIBTOOL_DLOPEN], -[_LT_SET_OPTION([LT_INIT], [dlopen]) -AC_DIAGNOSE([obsolete], -[$0: Remove this warning and the call to _LT_SET_OPTION when you -put the `dlopen' option into LT_INIT's first parameter.]) -]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) - - -# win32-dll -# --------- -# Declare package support for building win32 dll's. -LT_OPTION_DEFINE([LT_INIT], [win32-dll], -[enable_win32_dll=yes - -case $host in -*-*-cygwin* | *-*-mingw* | *-*-pw32*) - AC_CHECK_TOOL(AS, as, false) - AC_CHECK_TOOL(DLLTOOL, dlltool, false) - AC_CHECK_TOOL(OBJDUMP, objdump, false) - ;; -esac - -test -z "$AS" && AS=as -_LT_DECL([], [AS], [0], [Assembler program])dnl - -test -z "$DLLTOOL" && DLLTOOL=dlltool -_LT_DECL([], [DLLTOOL], [0], [DLL creation program])dnl - -test -z "$OBJDUMP" && OBJDUMP=objdump -_LT_DECL([], [OBJDUMP], [0], [Object dumper program])dnl -])# win32-dll - -AU_DEFUN([AC_LIBTOOL_WIN32_DLL], -[AC_REQUIRE([AC_CANONICAL_HOST])dnl -_LT_SET_OPTION([LT_INIT], [win32-dll]) -AC_DIAGNOSE([obsolete], -[$0: Remove this warning and the call to _LT_SET_OPTION when you -put the `win32-dll' option into LT_INIT's first parameter.]) -]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) - - -# _LT_ENABLE_SHARED([DEFAULT]) -# ---------------------------- -# implement the --enable-shared flag, and supports the `shared' and -# `disable-shared' LT_INIT options. -# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. -m4_define([_LT_ENABLE_SHARED], -[m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl -AC_ARG_ENABLE([shared], - [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], - [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], - [p=${PACKAGE-default} - case $enableval in - yes) enable_shared=yes ;; - no) enable_shared=no ;; - *) - enable_shared=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_shared=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac], - [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) - - _LT_DECL([build_libtool_libs], [enable_shared], [0], - [Whether or not to build shared libraries]) -])# _LT_ENABLE_SHARED - -LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) -LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) - -# Old names: -AC_DEFUN([AC_ENABLE_SHARED], -[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) -]) - -AC_DEFUN([AC_DISABLE_SHARED], -[_LT_SET_OPTION([LT_INIT], [disable-shared]) -]) - -AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) -AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AM_ENABLE_SHARED], []) -dnl AC_DEFUN([AM_DISABLE_SHARED], []) - - - -# _LT_ENABLE_STATIC([DEFAULT]) -# ---------------------------- -# implement the --enable-static flag, and support the `static' and -# `disable-static' LT_INIT options. -# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. -m4_define([_LT_ENABLE_STATIC], -[m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl -AC_ARG_ENABLE([static], - [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], - [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], - [p=${PACKAGE-default} - case $enableval in - yes) enable_static=yes ;; - no) enable_static=no ;; - *) - enable_static=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_static=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac], - [enable_static=]_LT_ENABLE_STATIC_DEFAULT) - - _LT_DECL([build_old_libs], [enable_static], [0], - [Whether or not to build static libraries]) -])# _LT_ENABLE_STATIC - -LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) -LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) - -# Old names: -AC_DEFUN([AC_ENABLE_STATIC], -[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) -]) - -AC_DEFUN([AC_DISABLE_STATIC], -[_LT_SET_OPTION([LT_INIT], [disable-static]) -]) - -AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) -AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AM_ENABLE_STATIC], []) -dnl AC_DEFUN([AM_DISABLE_STATIC], []) - - - -# _LT_ENABLE_FAST_INSTALL([DEFAULT]) -# ---------------------------------- -# implement the --enable-fast-install flag, and support the `fast-install' -# and `disable-fast-install' LT_INIT options. -# DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. -m4_define([_LT_ENABLE_FAST_INSTALL], -[m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl -AC_ARG_ENABLE([fast-install], - [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], - [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], - [p=${PACKAGE-default} - case $enableval in - yes) enable_fast_install=yes ;; - no) enable_fast_install=no ;; - *) - enable_fast_install=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_fast_install=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac], - [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) - -_LT_DECL([fast_install], [enable_fast_install], [0], - [Whether or not to optimize for fast installation])dnl -])# _LT_ENABLE_FAST_INSTALL - -LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) -LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) - -# Old names: -AU_DEFUN([AC_ENABLE_FAST_INSTALL], -[_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) -AC_DIAGNOSE([obsolete], -[$0: Remove this warning and the call to _LT_SET_OPTION when you put -the `fast-install' option into LT_INIT's first parameter.]) -]) - -AU_DEFUN([AC_DISABLE_FAST_INSTALL], -[_LT_SET_OPTION([LT_INIT], [disable-fast-install]) -AC_DIAGNOSE([obsolete], -[$0: Remove this warning and the call to _LT_SET_OPTION when you put -the `disable-fast-install' option into LT_INIT's first parameter.]) -]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) -dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) - - -# _LT_WITH_PIC([MODE]) -# -------------------- -# implement the --with-pic flag, and support the `pic-only' and `no-pic' -# LT_INIT options. -# MODE is either `yes' or `no'. If omitted, it defaults to `both'. -m4_define([_LT_WITH_PIC], -[AC_ARG_WITH([pic], - [AS_HELP_STRING([--with-pic], - [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], - [pic_mode="$withval"], - [pic_mode=default]) - -test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) - -_LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl -])# _LT_WITH_PIC - -LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) -LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) - -# Old name: -AU_DEFUN([AC_LIBTOOL_PICMODE], -[_LT_SET_OPTION([LT_INIT], [pic-only]) -AC_DIAGNOSE([obsolete], -[$0: Remove this warning and the call to _LT_SET_OPTION when you -put the `pic-only' option into LT_INIT's first parameter.]) -]) - -dnl aclocal-1.4 backwards compatibility: -dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) - -## ----------------- ## -## LTDL_INIT Options ## -## ----------------- ## - -m4_define([_LTDL_MODE], []) -LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], - [m4_define([_LTDL_MODE], [nonrecursive])]) -LT_OPTION_DEFINE([LTDL_INIT], [recursive], - [m4_define([_LTDL_MODE], [recursive])]) -LT_OPTION_DEFINE([LTDL_INIT], [subproject], - [m4_define([_LTDL_MODE], [subproject])]) - -m4_define([_LTDL_TYPE], []) -LT_OPTION_DEFINE([LTDL_INIT], [installable], - [m4_define([_LTDL_TYPE], [installable])]) -LT_OPTION_DEFINE([LTDL_INIT], [convenience], - [m4_define([_LTDL_TYPE], [convenience])]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltsugar.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltsugar.m4 deleted file mode 100644 index 0d258e0..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltsugar.m4 +++ /dev/null @@ -1,123 +0,0 @@ -# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- -# -# Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc. -# Written by Gary V. Vaughan, 2004 -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# serial 5 ltsugar.m4 - -# This is to help aclocal find these macros, as it can't see m4_define. -AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) - - -# lt_join(SEP, ARG1, [ARG2...]) -# ----------------------------- -# Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their -# associated separator. -# Needed until we can rely on m4_join from Autoconf 2.62, since all earlier -# versions in m4sugar had bugs. -m4_define([lt_join], -[m4_if([$#], [1], [], - [$#], [2], [[$2]], - [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) -m4_define([_lt_join], -[m4_if([$#$2], [2], [], - [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) - - -# lt_car(LIST) -# lt_cdr(LIST) -# ------------ -# Manipulate m4 lists. -# These macros are necessary as long as will still need to support -# Autoconf-2.59 which quotes differently. -m4_define([lt_car], [[$1]]) -m4_define([lt_cdr], -[m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], - [$#], 1, [], - [m4_dquote(m4_shift($@))])]) -m4_define([lt_unquote], $1) - - -# lt_append(MACRO-NAME, STRING, [SEPARATOR]) -# ------------------------------------------ -# Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. -# Note that neither SEPARATOR nor STRING are expanded; they are appended -# to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). -# No SEPARATOR is output if MACRO-NAME was previously undefined (different -# than defined and empty). -# -# This macro is needed until we can rely on Autoconf 2.62, since earlier -# versions of m4sugar mistakenly expanded SEPARATOR but not STRING. -m4_define([lt_append], -[m4_define([$1], - m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) - - - -# lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) -# ---------------------------------------------------------- -# Produce a SEP delimited list of all paired combinations of elements of -# PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list -# has the form PREFIXmINFIXSUFFIXn. -m4_define([lt_combine], -[m4_if([$2], [], [], - [m4_if([$4], [], [], - [lt_join(m4_quote(m4_default([$1], [[, ]])), - lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_prefix, [$2], - [m4_foreach(_Lt_suffix, lt_car([m4_shiftn(3, $@)]), - [_Lt_prefix[]$3[]_Lt_suffix ])])))))])])dnl -]) - - -# lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) -# ----------------------------------------------------------------------- -# Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited -# by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. -m4_define([lt_if_append_uniq], -[m4_ifdef([$1], - [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], - [lt_append([$1], [$2], [$3])$4], - [$5])], - [lt_append([$1], [$2], [$3])$4])]) - - -# lt_dict_add(DICT, KEY, VALUE) -# ----------------------------- -m4_define([lt_dict_add], -[m4_define([$1($2)], [$3])]) - - -# lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) -# -------------------------------------------- -m4_define([lt_dict_add_subkey], -[m4_define([$1($2:$3)], [$4])]) - - -# lt_dict_fetch(DICT, KEY, [SUBKEY]) -# ---------------------------------- -m4_define([lt_dict_fetch], -[m4_ifval([$3], - m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), - m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) - - -# lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) -# ----------------------------------------------------------------- -m4_define([lt_if_dict_fetch], -[m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], - [$5], - [$6])]) - - -# lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) -# -------------------------------------------------------------- -m4_define([lt_dict_filter], -[m4_if([$5], [], [], - [lt_join(m4_quote(m4_default([$4], [[, ]])), - lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), - [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl -]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltversion.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltversion.m4 deleted file mode 100644 index 45cb155..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/ltversion.m4 +++ /dev/null @@ -1,23 +0,0 @@ -# ltversion.m4 -- version numbers -*- Autoconf -*- -# -# Copyright (C) 2004 Free Software Foundation, Inc. -# Written by Scott James Remnant, 2004 -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# Generated from ltversion.in. - -# serial 2976 ltversion.m4 -# This file is part of GNU Libtool - -m4_define([LT_PACKAGE_VERSION], [2.2.4]) -m4_define([LT_PACKAGE_REVISION], [1.2976]) - -AC_DEFUN([LTVERSION_VERSION], -[macro_version='2.2.4' -macro_revision='1.2976' -_LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) -_LT_DECL(, macro_revision, 0) -]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/lt~obsolete.m4 b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/lt~obsolete.m4 deleted file mode 100644 index 637bb20..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/config/lt~obsolete.m4 +++ /dev/null @@ -1,92 +0,0 @@ -# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- -# -# Copyright (C) 2004, 2005, 2007 Free Software Foundation, Inc. -# Written by Scott James Remnant, 2004. -# -# This file is free software; the Free Software Foundation gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. - -# serial 4 lt~obsolete.m4 - -# These exist entirely to fool aclocal when bootstrapping libtool. -# -# In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) -# which have later been changed to m4_define as they aren't part of the -# exported API, or moved to Autoconf or Automake where they belong. -# -# The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN -# in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us -# using a macro with the same name in our local m4/libtool.m4 it'll -# pull the old libtool.m4 in (it doesn't see our shiny new m4_define -# and doesn't know about Autoconf macros at all.) -# -# So we provide this file, which has a silly filename so it's always -# included after everything else. This provides aclocal with the -# AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything -# because those macros already exist, or will be overwritten later. -# We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. -# -# Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. -# Yes, that means every name once taken will need to remain here until -# we give up compatibility with versions before 1.7, at which point -# we need to keep only those names which we still refer to. - -# This is to help aclocal find these macros, as it can't see m4_define. -AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) - -m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) -m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) -m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) -m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) -m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) -m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) -m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) -m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) -m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) -m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) -m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) -m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) -m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) -m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) -m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) -m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) -m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) -m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) -m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) -m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) -m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) -m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) -m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) -m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) -m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) -m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) -m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) -m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) -m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) -m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) -m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) -m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) -m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) -m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) -m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) -m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) -m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) -m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) -m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) -m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) -m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) -m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) -m4_ifndef([AC_LIBTOOL_RC], [AC_DEFUN([AC_LIBTOOL_RC])]) -m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) -m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) -m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) -m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) -m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) -m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) -m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) -m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) -m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure deleted file mode 100755 index b984f5f..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure +++ /dev/null @@ -1,14361 +0,0 @@ -#! /bin/sh -# Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.64 for package-unused version-unused. -# -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software -# Foundation, Inc. -# -# This configure script is free software; the Free Software Foundation -# gives unlimited permission to copy, distribute and modify it. -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -if test "x$CONFIG_SHELL" = x; then - as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which - # is contrary to our usage. Disable this feature. - alias -g '\${1+\"\$@\"}'='\"\$@\"' - setopt NO_GLOB_SUBST -else - case \`(set -o) 2>/dev/null\` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi -" - as_required="as_fn_return () { (exit \$1); } -as_fn_success () { as_fn_return 0; } -as_fn_failure () { as_fn_return 1; } -as_fn_ret_success () { return 0; } -as_fn_ret_failure () { return 1; } - -exitcode=0 -as_fn_success || { exitcode=1; echo as_fn_success failed.; } -as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } -as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } -as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } -if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : - -else - exitcode=1; echo positional parameters were not saved. -fi -test x\$exitcode = x0 || exit 1" - as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO - as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO - eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && - test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 -test \$(( 1 + 1 )) = 2 || exit 1" - if (eval "$as_required") 2>/dev/null; then : - as_have_required=yes -else - as_have_required=no -fi - if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : - -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_found=false -for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - as_found=: - case $as_dir in #( - /*) - for as_base in sh bash ksh sh5; do - # Try only shells that exist, to save several forks. - as_shell=$as_dir/$as_base - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : - CONFIG_SHELL=$as_shell as_have_required=yes - if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : - break 2 -fi -fi - done;; - esac - as_found=false -done -$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : - CONFIG_SHELL=$SHELL as_have_required=yes -fi; } -IFS=$as_save_IFS - - - if test "x$CONFIG_SHELL" != x; then : - # We cannot yet assume a decent shell, so we have to provide a - # neutralization value for shells without unset; and this also - # works around shells that cannot unset nonexistent variables. - BASH_ENV=/dev/null - ENV=/dev/null - (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - if test x$as_have_required = xno; then : - $as_echo "$0: This script requires a shell more modern than all" - $as_echo "$0: the shells that I found on your system." - if test x${ZSH_VERSION+set} = xset ; then - $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" - $as_echo "$0: be upgraded to zsh 4.3.4 or later." - else - $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, -$0: including any error possibly output before this -$0: message. Then install a modern shell, or manually run -$0: the script under such a shell if you do have one." - fi - exit 1 -fi -fi -fi -SHELL=${CONFIG_SHELL-/bin/sh} -export SHELL -# Unset more variables known to interfere with behavior of common tools. -CLICOLOR_FORCE= GREP_OPTIONS= -unset CLICOLOR_FORCE GREP_OPTIONS - -## --------------------- ## -## M4sh Shell Functions. ## -## --------------------- ## -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. -as_fn_error () -{ - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 - fi - $as_echo "$as_me: error: $1" >&2 - as_fn_exit $as_status -} # as_fn_error - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - - - as_lineno_1=$LINENO as_lineno_1a=$LINENO - as_lineno_2=$LINENO as_lineno_2a=$LINENO - eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && - test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { - # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - - -# Check that we are running under the correct shell. -SHELL=${CONFIG_SHELL-/bin/sh} - -case X$lt_ECHO in -X*--fallback-echo) - # Remove one level of quotation (which was required for Make). - ECHO=`echo "$lt_ECHO" | sed 's,\\\\\$\\$0,'$0','` - ;; -esac - -ECHO=${lt_ECHO-echo} -if test "X$1" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift -elif test "X$1" = X--fallback-echo; then - # Avoid inline document here, it may be left over - : -elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' ; then - # Yippee, $ECHO works! - : -else - # Restart under the correct shell. - exec $SHELL "$0" --no-reexec ${1+"$@"} -fi - -if test "X$1" = X--fallback-echo; then - # used as fallback echo - shift - cat <<_LT_EOF -$* -_LT_EOF - exit 0 -fi - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -if test -z "$lt_ECHO"; then - if test "X${echo_test_string+set}" != Xset; then - # find a string as large as possible, as long as the shell can cope with it - for cmd in 'sed 50q "$0"' 'sed 20q "$0"' 'sed 10q "$0"' 'sed 2q "$0"' 'echo test'; do - # expected sizes: less than 2Kb, 1Kb, 512 bytes, 16 bytes, ... - if { echo_test_string=`eval $cmd`; } 2>/dev/null && - { test "X$echo_test_string" = "X$echo_test_string"; } 2>/dev/null - then - break - fi - done - fi - - if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - : - else - # The Solaris, AIX, and Digital Unix default echo programs unquote - # backslashes. This makes it impossible to quote backslashes using - # echo "$something" | sed 's/\\/\\\\/g' - # - # So, first we look for a working echo in the user's PATH. - - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for dir in $PATH /usr/ucb; do - IFS="$lt_save_ifs" - if (test -f $dir/echo || test -f $dir/echo$ac_exeext) && - test "X`($dir/echo '\t') 2>/dev/null`" = 'X\t' && - echo_testing_string=`($dir/echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - ECHO="$dir/echo" - break - fi - done - IFS="$lt_save_ifs" - - if test "X$ECHO" = Xecho; then - # We didn't find a better echo, so look for alternatives. - if test "X`{ print -r '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ print -r "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - # This shell has a builtin print -r that does the trick. - ECHO='print -r' - elif { test -f /bin/ksh || test -f /bin/ksh$ac_exeext; } && - test "X$CONFIG_SHELL" != X/bin/ksh; then - # If we have ksh, try running configure again with it. - ORIGINAL_CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} - export ORIGINAL_CONFIG_SHELL - CONFIG_SHELL=/bin/ksh - export CONFIG_SHELL - exec $CONFIG_SHELL "$0" --no-reexec ${1+"$@"} - else - # Try using printf. - ECHO='printf %s\n' - if test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t' && - echo_testing_string=`{ $ECHO "$echo_test_string"; } 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - # Cool, printf works - : - elif echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && - test "X$echo_testing_string" = 'X\t' && - echo_testing_string=`($ORIGINAL_CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - CONFIG_SHELL=$ORIGINAL_CONFIG_SHELL - export CONFIG_SHELL - SHELL="$CONFIG_SHELL" - export SHELL - ECHO="$CONFIG_SHELL $0 --fallback-echo" - elif echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo '\t') 2>/dev/null` && - test "X$echo_testing_string" = 'X\t' && - echo_testing_string=`($CONFIG_SHELL "$0" --fallback-echo "$echo_test_string") 2>/dev/null` && - test "X$echo_testing_string" = "X$echo_test_string"; then - ECHO="$CONFIG_SHELL $0 --fallback-echo" - else - # maybe with a smaller string... - prev=: - - for cmd in 'echo test' 'sed 2q "$0"' 'sed 10q "$0"' 'sed 20q "$0"' 'sed 50q "$0"'; do - if { test "X$echo_test_string" = "X`eval $cmd`"; } 2>/dev/null - then - break - fi - prev="$cmd" - done - - if test "$prev" != 'sed 50q "$0"'; then - echo_test_string=`eval $prev` - export echo_test_string - exec ${ORIGINAL_CONFIG_SHELL-${CONFIG_SHELL-/bin/sh}} "$0" ${1+"$@"} - else - # Oops. We lost completely, so just stick with echo. - ECHO=echo - fi - fi - fi - fi - fi -fi - -# Copy echo and quote the copy suitably for passing to libtool from -# the Makefile, instead of quoting the original, which is used later. -lt_ECHO=$ECHO -if test "X$lt_ECHO" = "X$CONFIG_SHELL $0 --fallback-echo"; then - lt_ECHO="$CONFIG_SHELL \\\$\$0 --fallback-echo" -fi - - - - -exec 7<&0 &1 - -# Name of the host. -# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, -# so uname gets run too. -ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` - -# -# Initializations. -# -ac_default_prefix=/usr/local -ac_clean_files= -ac_config_libobj_dir=. -LIBOBJS= -cross_compiling=no -subdirs= -MFLAGS= -MAKEFLAGS= - -# Identity of this package. -PACKAGE_NAME='package-unused' -PACKAGE_TARNAME='libbacktrace' -PACKAGE_VERSION='version-unused' -PACKAGE_STRING='package-unused version-unused' -PACKAGE_BUGREPORT='' -PACKAGE_URL='' - -ac_unique_file="backtrace.h" -# Factoring default headers for most tests. -ac_includes_default="\ -#include -#ifdef HAVE_SYS_TYPES_H -# include -#endif -#ifdef HAVE_SYS_STAT_H -# include -#endif -#ifdef STDC_HEADERS -# include -# include -#else -# ifdef HAVE_STDLIB_H -# include -# endif -#endif -#ifdef HAVE_STRING_H -# if !defined STDC_HEADERS && defined HAVE_MEMORY_H -# include -# endif -# include -#endif -#ifdef HAVE_STRINGS_H -# include -#endif -#ifdef HAVE_INTTYPES_H -# include -#endif -#ifdef HAVE_STDINT_H -# include -#endif -#ifdef HAVE_UNISTD_H -# include -#endif" - -ac_subst_vars='am__EXEEXT_FALSE -am__EXEEXT_TRUE -LTLIBOBJS -LIBOBJS -NATIVE_FALSE -NATIVE_TRUE -HAVE_OBJCOPY_DEBUGLINK_FALSE -HAVE_OBJCOPY_DEBUGLINK_TRUE -OBJCOPY -HAVE_COMPRESSED_DEBUG_FALSE -HAVE_COMPRESSED_DEBUG_TRUE -HAVE_ZLIB_FALSE -HAVE_ZLIB_TRUE -HAVE_PTHREAD_FALSE -HAVE_PTHREAD_TRUE -PTHREAD_CFLAGS -CLOCK_GETTIME_LINK -BACKTRACE_USES_MALLOC -ALLOC_FILE -VIEW_FILE -BACKTRACE_SUPPORTS_DATA -BACKTRACE_SUPPORTED -FORMAT_FILE -BACKTRACE_SUPPORTS_THREADS -PIC_FLAG -WARN_FLAGS -EXTRA_FLAGS -BACKTRACE_FILE -OTOOL64 -OTOOL -LIPO -NMEDIT -DSYMUTIL -lt_ECHO -RANLIB -AR -LN_S -NM -ac_ct_DUMPBIN -DUMPBIN -LD -FGREP -SED -LIBTOOL -MAINT -MAINTAINER_MODE_FALSE -MAINTAINER_MODE_TRUE -am__untar -am__tar -AMTAR -am__leading_dot -SET_MAKE -AWK -mkdir_p -MKDIR_P -INSTALL_STRIP_PROGRAM -STRIP -install_sh -MAKEINFO -AUTOHEADER -AUTOMAKE -AUTOCONF -ACLOCAL -VERSION -PACKAGE -CYGPATH_W -am__isrc -INSTALL_DATA -INSTALL_SCRIPT -INSTALL_PROGRAM -libtool_VERSION -EGREP -GREP -CPP -OBJEXT -EXEEXT -ac_ct_CC -CPPFLAGS -LDFLAGS -CFLAGS -CC -target_os -target_vendor -target_cpu -target -host_os -host_vendor -host_cpu -host -build_os -build_vendor -build_cpu -build -multi_basedir -target_alias -host_alias -build_alias -LIBS -ECHO_T -ECHO_N -ECHO_C -DEFS -mandir -localedir -libdir -psdir -pdfdir -dvidir -htmldir -infodir -docdir -oldincludedir -includedir -localstatedir -sharedstatedir -sysconfdir -datadir -datarootdir -libexecdir -sbindir -bindir -program_transform_name -prefix -exec_prefix -PACKAGE_URL -PACKAGE_BUGREPORT -PACKAGE_STRING -PACKAGE_VERSION -PACKAGE_TARNAME -PACKAGE_NAME -PATH_SEPARATOR -SHELL' -ac_subst_files='' -ac_user_opts=' -enable_option_checking -enable_multilib -enable_maintainer_mode -with_target_subdir -enable_shared -enable_static -with_pic -enable_fast_install -with_gnu_ld -enable_libtool_lock -enable_largefile -with_system_libunwind -enable_host_shared -' - ac_precious_vars='build_alias -host_alias -target_alias -CC -CFLAGS -LDFLAGS -LIBS -CPPFLAGS -CPP -OBJCOPY' - - -# Initialize some variables set by options. -ac_init_help= -ac_init_version=false -ac_unrecognized_opts= -ac_unrecognized_sep= -# The variables have the same names as the options, with -# dashes changed to underlines. -cache_file=/dev/null -exec_prefix=NONE -no_create= -no_recursion= -prefix=NONE -program_prefix=NONE -program_suffix=NONE -program_transform_name=s,x,x, -silent= -site= -srcdir= -verbose= -x_includes=NONE -x_libraries=NONE - -# Installation directory options. -# These are left unexpanded so users can "make install exec_prefix=/foo" -# and all the variables that are supposed to be based on exec_prefix -# by default will actually change. -# Use braces instead of parens because sh, perl, etc. also accept them. -# (The list follows the same order as the GNU Coding Standards.) -bindir='${exec_prefix}/bin' -sbindir='${exec_prefix}/sbin' -libexecdir='${exec_prefix}/libexec' -datarootdir='${prefix}/share' -datadir='${datarootdir}' -sysconfdir='${prefix}/etc' -sharedstatedir='${prefix}/com' -localstatedir='${prefix}/var' -includedir='${prefix}/include' -oldincludedir='/usr/include' -docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' -infodir='${datarootdir}/info' -htmldir='${docdir}' -dvidir='${docdir}' -pdfdir='${docdir}' -psdir='${docdir}' -libdir='${exec_prefix}/lib' -localedir='${datarootdir}/locale' -mandir='${datarootdir}/man' - -ac_prev= -ac_dashdash= -for ac_option -do - # If the previous option needs an argument, assign it. - if test -n "$ac_prev"; then - eval $ac_prev=\$ac_option - ac_prev= - continue - fi - - case $ac_option in - *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; - *) ac_optarg=yes ;; - esac - - # Accept the important Cygnus configure options, so we can diagnose typos. - - case $ac_dashdash$ac_option in - --) - ac_dashdash=yes ;; - - -bindir | --bindir | --bindi | --bind | --bin | --bi) - ac_prev=bindir ;; - -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) - bindir=$ac_optarg ;; - - -build | --build | --buil | --bui | --bu) - ac_prev=build_alias ;; - -build=* | --build=* | --buil=* | --bui=* | --bu=*) - build_alias=$ac_optarg ;; - - -cache-file | --cache-file | --cache-fil | --cache-fi \ - | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) - ac_prev=cache_file ;; - -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ - | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) - cache_file=$ac_optarg ;; - - --config-cache | -C) - cache_file=config.cache ;; - - -datadir | --datadir | --datadi | --datad) - ac_prev=datadir ;; - -datadir=* | --datadir=* | --datadi=* | --datad=*) - datadir=$ac_optarg ;; - - -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ - | --dataroo | --dataro | --datar) - ac_prev=datarootdir ;; - -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ - | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) - datarootdir=$ac_optarg ;; - - -disable-* | --disable-*) - ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=no ;; - - -docdir | --docdir | --docdi | --doc | --do) - ac_prev=docdir ;; - -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) - docdir=$ac_optarg ;; - - -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) - ac_prev=dvidir ;; - -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) - dvidir=$ac_optarg ;; - - -enable-* | --enable-*) - ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=\$ac_optarg ;; - - -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ - | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ - | --exec | --exe | --ex) - ac_prev=exec_prefix ;; - -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ - | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ - | --exec=* | --exe=* | --ex=*) - exec_prefix=$ac_optarg ;; - - -gas | --gas | --ga | --g) - # Obsolete; use --with-gas. - with_gas=yes ;; - - -help | --help | --hel | --he | -h) - ac_init_help=long ;; - -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) - ac_init_help=recursive ;; - -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) - ac_init_help=short ;; - - -host | --host | --hos | --ho) - ac_prev=host_alias ;; - -host=* | --host=* | --hos=* | --ho=*) - host_alias=$ac_optarg ;; - - -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) - ac_prev=htmldir ;; - -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ - | --ht=*) - htmldir=$ac_optarg ;; - - -includedir | --includedir | --includedi | --included | --include \ - | --includ | --inclu | --incl | --inc) - ac_prev=includedir ;; - -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ - | --includ=* | --inclu=* | --incl=* | --inc=*) - includedir=$ac_optarg ;; - - -infodir | --infodir | --infodi | --infod | --info | --inf) - ac_prev=infodir ;; - -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) - infodir=$ac_optarg ;; - - -libdir | --libdir | --libdi | --libd) - ac_prev=libdir ;; - -libdir=* | --libdir=* | --libdi=* | --libd=*) - libdir=$ac_optarg ;; - - -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ - | --libexe | --libex | --libe) - ac_prev=libexecdir ;; - -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ - | --libexe=* | --libex=* | --libe=*) - libexecdir=$ac_optarg ;; - - -localedir | --localedir | --localedi | --localed | --locale) - ac_prev=localedir ;; - -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) - localedir=$ac_optarg ;; - - -localstatedir | --localstatedir | --localstatedi | --localstated \ - | --localstate | --localstat | --localsta | --localst | --locals) - ac_prev=localstatedir ;; - -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ - | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) - localstatedir=$ac_optarg ;; - - -mandir | --mandir | --mandi | --mand | --man | --ma | --m) - ac_prev=mandir ;; - -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) - mandir=$ac_optarg ;; - - -nfp | --nfp | --nf) - # Obsolete; use --without-fp. - with_fp=no ;; - - -no-create | --no-create | --no-creat | --no-crea | --no-cre \ - | --no-cr | --no-c | -n) - no_create=yes ;; - - -no-recursion | --no-recursion | --no-recursio | --no-recursi \ - | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) - no_recursion=yes ;; - - -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ - | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ - | --oldin | --oldi | --old | --ol | --o) - ac_prev=oldincludedir ;; - -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ - | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ - | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) - oldincludedir=$ac_optarg ;; - - -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) - ac_prev=prefix ;; - -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) - prefix=$ac_optarg ;; - - -program-prefix | --program-prefix | --program-prefi | --program-pref \ - | --program-pre | --program-pr | --program-p) - ac_prev=program_prefix ;; - -program-prefix=* | --program-prefix=* | --program-prefi=* \ - | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) - program_prefix=$ac_optarg ;; - - -program-suffix | --program-suffix | --program-suffi | --program-suff \ - | --program-suf | --program-su | --program-s) - ac_prev=program_suffix ;; - -program-suffix=* | --program-suffix=* | --program-suffi=* \ - | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) - program_suffix=$ac_optarg ;; - - -program-transform-name | --program-transform-name \ - | --program-transform-nam | --program-transform-na \ - | --program-transform-n | --program-transform- \ - | --program-transform | --program-transfor \ - | --program-transfo | --program-transf \ - | --program-trans | --program-tran \ - | --progr-tra | --program-tr | --program-t) - ac_prev=program_transform_name ;; - -program-transform-name=* | --program-transform-name=* \ - | --program-transform-nam=* | --program-transform-na=* \ - | --program-transform-n=* | --program-transform-=* \ - | --program-transform=* | --program-transfor=* \ - | --program-transfo=* | --program-transf=* \ - | --program-trans=* | --program-tran=* \ - | --progr-tra=* | --program-tr=* | --program-t=*) - program_transform_name=$ac_optarg ;; - - -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) - ac_prev=pdfdir ;; - -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) - pdfdir=$ac_optarg ;; - - -psdir | --psdir | --psdi | --psd | --ps) - ac_prev=psdir ;; - -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) - psdir=$ac_optarg ;; - - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - silent=yes ;; - - -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) - ac_prev=sbindir ;; - -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ - | --sbi=* | --sb=*) - sbindir=$ac_optarg ;; - - -sharedstatedir | --sharedstatedir | --sharedstatedi \ - | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ - | --sharedst | --shareds | --shared | --share | --shar \ - | --sha | --sh) - ac_prev=sharedstatedir ;; - -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ - | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ - | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ - | --sha=* | --sh=*) - sharedstatedir=$ac_optarg ;; - - -site | --site | --sit) - ac_prev=site ;; - -site=* | --site=* | --sit=*) - site=$ac_optarg ;; - - -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) - ac_prev=srcdir ;; - -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) - srcdir=$ac_optarg ;; - - -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ - | --syscon | --sysco | --sysc | --sys | --sy) - ac_prev=sysconfdir ;; - -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ - | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) - sysconfdir=$ac_optarg ;; - - -target | --target | --targe | --targ | --tar | --ta | --t) - ac_prev=target_alias ;; - -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) - target_alias=$ac_optarg ;; - - -v | -verbose | --verbose | --verbos | --verbo | --verb) - verbose=yes ;; - - -version | --version | --versio | --versi | --vers | -V) - ac_init_version=: ;; - - -with-* | --with-*) - ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=\$ac_optarg ;; - - -without-* | --without-*) - ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=no ;; - - --x) - # Obsolete; use --with-x. - with_x=yes ;; - - -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ - | --x-incl | --x-inc | --x-in | --x-i) - ac_prev=x_includes ;; - -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ - | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) - x_includes=$ac_optarg ;; - - -x-libraries | --x-libraries | --x-librarie | --x-librari \ - | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) - ac_prev=x_libraries ;; - -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ - | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) - x_libraries=$ac_optarg ;; - - -*) as_fn_error "unrecognized option: \`$ac_option' -Try \`$0 --help' for more information." - ;; - - *=*) - ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` - # Reject names that are not valid shell variable names. - case $ac_envvar in #( - '' | [0-9]* | *[!_$as_cr_alnum]* ) - as_fn_error "invalid variable name: \`$ac_envvar'" ;; - esac - eval $ac_envvar=\$ac_optarg - export $ac_envvar ;; - - *) - # FIXME: should be removed in autoconf 3.0. - $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 - expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 - : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} - ;; - - esac -done - -if test -n "$ac_prev"; then - ac_option=--`echo $ac_prev | sed 's/_/-/g'` - as_fn_error "missing argument to $ac_option" -fi - -if test -n "$ac_unrecognized_opts"; then - case $enable_option_checking in - no) ;; - fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; - *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; - esac -fi - -# Check all directory arguments for consistency. -for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ - datadir sysconfdir sharedstatedir localstatedir includedir \ - oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir -do - eval ac_val=\$$ac_var - # Remove trailing slashes. - case $ac_val in - */ ) - ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` - eval $ac_var=\$ac_val;; - esac - # Be sure to have absolute directory names. - case $ac_val in - [\\/$]* | ?:[\\/]* ) continue;; - NONE | '' ) case $ac_var in *prefix ) continue;; esac;; - esac - as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" -done - -# There might be people who depend on the old broken behavior: `$host' -# used to hold the argument of --host etc. -# FIXME: To remove some day. -build=$build_alias -host=$host_alias -target=$target_alias - -# FIXME: To remove some day. -if test "x$host_alias" != x; then - if test "x$build_alias" = x; then - cross_compiling=maybe - $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. - If a cross compiler is detected then cross compile mode will be used." >&2 - elif test "x$build_alias" != "x$host_alias"; then - cross_compiling=yes - fi -fi - -ac_tool_prefix= -test -n "$host_alias" && ac_tool_prefix=$host_alias- - -test "$silent" = yes && exec 6>/dev/null - - -ac_pwd=`pwd` && test -n "$ac_pwd" && -ac_ls_di=`ls -di .` && -ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - as_fn_error "working directory cannot be determined" -test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - as_fn_error "pwd does not report name of working directory" - - -# Find the source files, if location was not specified. -if test -z "$srcdir"; then - ac_srcdir_defaulted=yes - # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$as_myself" || -$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_myself" : 'X\(//\)[^/]' \| \ - X"$as_myself" : 'X\(//\)$' \| \ - X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_myself" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - srcdir=$ac_confdir - if test ! -r "$srcdir/$ac_unique_file"; then - srcdir=.. - fi -else - ac_srcdir_defaulted=no -fi -if test ! -r "$srcdir/$ac_unique_file"; then - test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" -fi -ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" -ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" - pwd)` -# When building in place, set srcdir=. -if test "$ac_abs_confdir" = "$ac_pwd"; then - srcdir=. -fi -# Remove unnecessary trailing slashes from srcdir. -# Double slashes in file names in object file debugging info -# mess up M-x gdb in Emacs. -case $srcdir in -*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; -esac -for ac_var in $ac_precious_vars; do - eval ac_env_${ac_var}_set=\${${ac_var}+set} - eval ac_env_${ac_var}_value=\$${ac_var} - eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} - eval ac_cv_env_${ac_var}_value=\$${ac_var} -done - -# -# Report the --help message. -# -if test "$ac_init_help" = "long"; then - # Omit some internal or obsolete options to make the list less imposing. - # This message is too long to be a string in the A/UX 3.1 sh. - cat <<_ACEOF -\`configure' configures package-unused version-unused to adapt to many kinds of systems. - -Usage: $0 [OPTION]... [VAR=VALUE]... - -To assign environment variables (e.g., CC, CFLAGS...), specify them as -VAR=VALUE. See below for descriptions of some of the useful variables. - -Defaults for the options are specified in brackets. - -Configuration: - -h, --help display this help and exit - --help=short display options specific to this package - --help=recursive display the short help of all the included packages - -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking...' messages - --cache-file=FILE cache test results in FILE [disabled] - -C, --config-cache alias for \`--cache-file=config.cache' - -n, --no-create do not create output files - --srcdir=DIR find the sources in DIR [configure dir or \`..'] - -Installation directories: - --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] - --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] - -By default, \`make install' will install all the files in -\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify -an installation prefix other than \`$ac_default_prefix' using \`--prefix', -for instance \`--prefix=\$HOME'. - -For better control, use the options below. - -Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/libbacktrace] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] -_ACEOF - - cat <<\_ACEOF - -Program names: - --program-prefix=PREFIX prepend PREFIX to installed program names - --program-suffix=SUFFIX append SUFFIX to installed program names - --program-transform-name=PROGRAM run sed PROGRAM on installed program names - -System types: - --build=BUILD configure for building on BUILD [guessed] - --host=HOST cross-compile to build programs to run on HOST [BUILD] - --target=TARGET configure for building compilers for TARGET [HOST] -_ACEOF -fi - -if test -n "$ac_init_help"; then - case $ac_init_help in - short | recursive ) echo "Configuration of package-unused version-unused:";; - esac - cat <<\_ACEOF - -Optional Features: - --disable-option-checking ignore unrecognized --enable/--with options - --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) - --enable-FEATURE[=ARG] include FEATURE [ARG=yes] - --enable-multilib build many library versions (default) - --enable-maintainer-mode enable make rules and dependencies not useful - (and sometimes confusing) to the casual installer - --enable-shared[=PKGS] build shared libraries [default=yes] - --enable-static[=PKGS] build static libraries [default=yes] - --enable-fast-install[=PKGS] - optimize for fast installation [default=yes] - --disable-libtool-lock avoid locking (might break parallel builds) - --disable-largefile omit support for large files - --enable-host-shared build host code as shared libraries - -Optional Packages: - --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] - --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --with-target-subdir=SUBDIR Configuring in a subdirectory for target - --with-pic try to use only PIC/non-PIC objects [default=use - both] - --with-gnu-ld assume the C compiler uses GNU ld [default=no] - --with-system-libunwind use installed libunwind - -Some influential environment variables: - CC C compiler command - CFLAGS C compiler flags - LDFLAGS linker flags, e.g. -L if you have libraries in a - nonstandard directory - LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if - you have headers in a nonstandard directory - CPP C preprocessor - OBJCOPY location of objcopy - -Use these variables to override the choices made by `configure' or to help -it to find libraries and programs with nonstandard names/locations. - -Report bugs to the package provider. -_ACEOF -ac_status=$? -fi - -if test "$ac_init_help" = "recursive"; then - # If there are subdirs, report their specific --help. - for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || - { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || - continue - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - cd "$ac_dir" || { ac_status=$?; continue; } - # Check for guested configure. - if test -f "$ac_srcdir/configure.gnu"; then - echo && - $SHELL "$ac_srcdir/configure.gnu" --help=recursive - elif test -f "$ac_srcdir/configure"; then - echo && - $SHELL "$ac_srcdir/configure" --help=recursive - else - $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 - fi || ac_status=$? - cd "$ac_pwd" || { ac_status=$?; break; } - done -fi - -test -n "$ac_init_help" && exit $ac_status -if $ac_init_version; then - cat <<\_ACEOF -package-unused configure version-unused -generated by GNU Autoconf 2.64 - -Copyright (C) 2009 Free Software Foundation, Inc. -This configure script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it. -_ACEOF - exit -fi - -## ------------------------ ## -## Autoconf initialization. ## -## ------------------------ ## - -# ac_fn_c_try_compile LINENO -# -------------------------- -# Try to compile conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext - if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_compile - -# ac_fn_c_try_cpp LINENO -# ---------------------- -# Try to preprocess conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_cpp () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_cpp - -# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists, giving a warning if it cannot be compiled using -# the include files in INCLUDES and setting the cache variable VAR -# accordingly. -ac_fn_c_check_header_mongrel () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 -$as_echo_n "checking $2 usability... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_header_compiler=yes -else - ac_header_compiler=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 -$as_echo_n "checking $2 presence... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include <$2> -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - ac_header_preproc=yes -else - ac_header_preproc=no -fi -rm -f conftest.err conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( - yes:no: ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} - ;; - no:yes:* ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} - ;; -esac - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - eval "$3=\$ac_header_compiler" -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_mongrel - -# ac_fn_c_try_run LINENO -# ---------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes -# that executables *can* be run. -ac_fn_c_try_run () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then : - ac_retval=0 -else - $as_echo "$as_me: program exited with status $ac_status" >&5 - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=$ac_status -fi - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_run - -# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists and can be compiled using the include files in -# INCLUDES, setting the cache variable VAR accordingly. -ac_fn_c_check_header_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_compile - -# ac_fn_c_try_link LINENO -# ----------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_link () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext conftest$ac_exeext - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information - # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would - # interfere with the next link command; also delete a directory that is - # left behind by Apple's compiler. We do this before executing the actions. - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - return $ac_retval - -} # ac_fn_c_try_link - -# ac_fn_c_check_func LINENO FUNC VAR -# ---------------------------------- -# Tests whether FUNC exists, setting the cache variable VAR accordingly -ac_fn_c_check_func () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -/* Define $2 to an innocuous variant, in case declares $2. - For example, HP-UX 11i declares gettimeofday. */ -#define $2 innocuous_$2 - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $2 (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $2 - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $2 (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$2 || defined __stub___$2 -choke me -#endif - -int -main () -{ -return $2 (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_func - -# ac_fn_c_check_decl LINENO SYMBOL VAR -# ------------------------------------ -# Tests whether SYMBOL is declared, setting cache variable VAR accordingly. -ac_fn_c_check_decl () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $2 is declared" >&5 -$as_echo_n "checking whether $2 is declared... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -int -main () -{ -#ifndef $2 - (void) $2; -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_decl -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. - -It was created by package-unused $as_me version-unused, which was -generated by GNU Autoconf 2.64. Invocation command line was - - $ $0 $@ - -_ACEOF -exec 5>>config.log -{ -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## - -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` - -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` - -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` - -_ASUNAME - -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - $as_echo "PATH: $as_dir" - done -IFS=$as_save_IFS - -} >&5 - -cat >&5 <<_ACEOF - - -## ----------- ## -## Core tests. ## -## ----------- ## - -_ACEOF - - -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; - 2) - as_fn_append ac_configure_args1 " '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - as_fn_append ac_configure_args " '$ac_arg'" - ;; - esac - done -done -{ ac_configure_args0=; unset ac_configure_args0;} -{ ac_configure_args1=; unset ac_configure_args1;} - -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo - - cat <<\_ASBOX -## ---------------- ## -## Cache variables. ## -## ---------------- ## -_ASBOX - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo - - cat <<\_ASBOX -## ----------------- ## -## Output variables. ## -## ----------------- ## -_ASBOX - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - - if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## -## File substitutions. ## -## ------------------- ## -_ASBOX - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi - - if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## -## confdefs.h. ## -## ----------- ## -_ASBOX - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - $as_echo "$as_me: caught signal $ac_signal" - $as_echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal -done -ac_signal=0 - -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h - -$as_echo "/* confdefs.h */" > confdefs.h - -# Predefined preprocessor variables. - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_URL "$PACKAGE_URL" -_ACEOF - - -# Let the site file select an alternate cache file if it wants to. -# Prefer an explicitly selected file to automatically selected ones. -ac_site_file1=NONE -ac_site_file2=NONE -if test -n "$CONFIG_SITE"; then - ac_site_file1=$CONFIG_SITE -elif test "x$prefix" != xNONE; then - ac_site_file1=$prefix/share/config.site - ac_site_file2=$prefix/etc/config.site -else - ac_site_file1=$ac_default_prefix/share/config.site - ac_site_file2=$ac_default_prefix/etc/config.site -fi -for ac_site_file in "$ac_site_file1" "$ac_site_file2" -do - test "x$ac_site_file" = xNONE && continue - if test -r "$ac_site_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 -$as_echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" - fi -done - -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 -$as_echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi -else - { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 -$as_echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file -fi - -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - # differences in whitespace do not lead to failure. - ac_old_val_w=`echo x $ac_old_val` - ac_new_val_w=`echo x $ac_new_val` - if test "$ac_old_val_w" != "$ac_new_val_w"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 -$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - ac_cache_corrupted=: - else - { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 -$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} - eval $ac_var=\$ac_old_val - fi - { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 -$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 -$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) as_fn_append ac_configure_args " '$ac_arg'" ;; - esac - fi -done -if $ac_cache_corrupted; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 -$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} - as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 -fi -## -------------------- ## -## Main body of script. ## -## -------------------- ## - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -ac_config_headers="$ac_config_headers config.h" - - - -# with_target_subdir is used when configured as part of a GCC tree. -if test -n "${with_target_subdir}"; then - # Default to --enable-multilib -# Check whether --enable-multilib was given. -if test "${enable_multilib+set}" = set; then : - enableval=$enable_multilib; case "$enableval" in - yes) multilib=yes ;; - no) multilib=no ;; - *) as_fn_error "bad value $enableval for multilib option" "$LINENO" 5 ;; - esac -else - multilib=yes -fi - - -# We may get other options which we leave undocumented: -# --with-target-subdir, --with-multisrctop, --with-multisubdir -# See config-ml.in if you want the gory details. - -if test "$srcdir" = "."; then - if test "$with_target_subdir" != "."; then - multi_basedir="$srcdir/$with_multisrctop../.." - else - multi_basedir="$srcdir/$with_multisrctop.." - fi -else - multi_basedir="$srcdir/.." -fi - - -# Even if the default multilib is not a cross compilation, -# it may be that some of the other multilibs are. -if test $cross_compiling = no && test $multilib = yes \ - && test "x${with_multisubdir}" != x ; then - cross_compiling=maybe -fi - -ac_config_commands="$ac_config_commands default-1" - -fi - -ac_aux_dir= -for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - for ac_t in install-sh install.sh shtool; do - if test -f "$ac_dir/$ac_t"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/$ac_t -c" - break 2 - fi - done -done -if test -z "$ac_aux_dir"; then - as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 -fi - -# These three variables are undocumented and unsupported, -# and are intended to be withdrawn in a future Autoconf release. -# They can cause serious problems if a builder's source tree is in a directory -# whose full name contains unusual characters. -ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. -ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. -ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. - - -# Make sure we can run config.sub. -$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || - as_fn_error "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 -$as_echo_n "checking build system type... " >&6; } -if test "${ac_cv_build+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_build_alias=$build_alias -test "x$ac_build_alias" = x && - ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` -test "x$ac_build_alias" = x && - as_fn_error "cannot guess build type; you must specify one" "$LINENO" 5 -ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 -$as_echo "$ac_cv_build" >&6; } -case $ac_cv_build in -*-*-*) ;; -*) as_fn_error "invalid value of canonical build" "$LINENO" 5;; -esac -build=$ac_cv_build -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_build -shift -build_cpu=$1 -build_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -build_os=$* -IFS=$ac_save_IFS -case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 -$as_echo_n "checking host system type... " >&6; } -if test "${ac_cv_host+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "x$host_alias" = x; then - ac_cv_host=$ac_cv_build -else - ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 -$as_echo "$ac_cv_host" >&6; } -case $ac_cv_host in -*-*-*) ;; -*) as_fn_error "invalid value of canonical host" "$LINENO" 5;; -esac -host=$ac_cv_host -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_host -shift -host_cpu=$1 -host_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -host_os=$* -IFS=$ac_save_IFS -case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 -$as_echo_n "checking target system type... " >&6; } -if test "${ac_cv_target+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "x$target_alias" = x; then - ac_cv_target=$ac_cv_host -else - ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 -$as_echo "$ac_cv_target" >&6; } -case $ac_cv_target in -*-*-*) ;; -*) as_fn_error "invalid value of canonical target" "$LINENO" 5;; -esac -target=$ac_cv_target -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_target -shift -target_cpu=$1 -target_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -target_os=$* -IFS=$ac_save_IFS -case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac - - -# The aliases save the names the user supplied, while $host etc. -# will get canonicalized. -test -n "$target_alias" && - test "$program_prefix$program_suffix$program_transform_name" = \ - NONENONEs,x,x, && - program_prefix=${target_alias}- - -target_alias=${target_alias-$host_alias} - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi - -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_CC" && break -done - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi - -fi - - -test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "no acceptable C compiler found in \$PATH -See \`config.log' for more details." "$LINENO" 5; } - -# Provide some information about the compiler. -$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -for ac_option in --version -v -V -qversion; do - { { ac_try="$ac_compiler $ac_option >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compiler $ac_option >&5") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - sed '10a\ -... rest of stderr output deleted ... - 10q' conftest.err >conftest.er1 - cat conftest.er1 >&5 - rm -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } -done - -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -int -main () -{ -FILE *f = fopen ("conftest.out", "w"); - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out conftest.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 -$as_echo_n "checking for C compiler default output file name... " >&6; } -ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` - -# The possible output files: -ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" - -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles - -if { { ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= - -else - ac_file='' -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 -$as_echo "$ac_file" >&6; } -if test -z "$ac_file"; then : - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ as_fn_set_status 77 -as_fn_error "C compiler cannot create executables -See \`config.log' for more details." "$LINENO" 5; }; } -fi -ac_exeext=$ac_cv_exeext - -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 -$as_echo_n "checking whether the C compiler works... " >&6; } -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." "$LINENO" 5; } - fi - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - -rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out conftest.out -ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 -$as_echo_n "checking whether we are cross compiling... " >&6; } -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 -$as_echo "$cross_compiling" >&6; } - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 -$as_echo_n "checking for suffix of executables... " >&6; } -if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." "$LINENO" 5; } -fi -rm -f conftest$ac_cv_exeext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 -$as_echo "$ac_cv_exeext" >&6; } - -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 -$as_echo_n "checking for suffix of object files... " >&6; } -if test "${ac_cv_objext+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of object files: cannot compile -See \`config.log' for more details." "$LINENO" 5; } -fi -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 -$as_echo "$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 -$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_compiler_gnu=yes -else - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 -$as_echo "$ac_cv_c_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GCC=yes -else - GCC= -fi -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 -$as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -else - CFLAGS="" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - -else - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 -$as_echo "$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 -$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_c89=$ac_arg -fi -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC - -fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 -$as_echo "none needed" >&6; } ;; - xno) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 -$as_echo "unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 -$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; -esac -if test "x$ac_cv_prog_cc_c89" != xno; then : - -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 -$as_echo_n "checking how to run the C preprocessor... " >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= -fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - break -fi - - done - ac_cv_prog_CPP=$CPP - -fi - CPP=$ac_cv_prog_CPP -else - ac_cv_prog_CPP=$CPP -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 -$as_echo "$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." "$LINENO" 5; } -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 -$as_echo_n "checking for grep that handles long lines and -e... " >&6; } -if test "${ac_cv_path_GREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -z "$GREP"; then - ac_path_GREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue -# Check for GNU ac_path_GREP and select it if it is found. - # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in -*GNU*) - ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'GREP' >> "conftest.nl" - "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_GREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_GREP="$ac_path_GREP" - ac_path_GREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_GREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_GREP"; then - as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_GREP=$GREP -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 -$as_echo "$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 -$as_echo_n "checking for egrep... " >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - if test -z "$EGREP"; then - ac_path_EGREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue -# Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_EGREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_EGREP"; then - as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_EGREP=$EGREP -fi - - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 -$as_echo "$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 -$as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_stdc=yes -else - ac_cv_header_stdc=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then : - : -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - -else - ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 -$as_echo "$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -$as_echo "#define STDC_HEADERS 1" >>confdefs.h - -fi - -# On IRIX 5.3, sys/types and inttypes.h are conflicting. -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do : - as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default -" -eval as_val=\$$as_ac_Header - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - - - ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default" -if test "x$ac_cv_header_minix_config_h" = x""yes; then : - MINIX=yes -else - MINIX= -fi - - - if test "$MINIX" = yes; then - -$as_echo "#define _POSIX_SOURCE 1" >>confdefs.h - - -$as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h - - -$as_echo "#define _MINIX 1" >>confdefs.h - - fi - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5 -$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; } -if test "${ac_cv_safe_to_define___extensions__+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -# define __EXTENSIONS__ 1 - $ac_includes_default -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_safe_to_define___extensions__=yes -else - ac_cv_safe_to_define___extensions__=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5 -$as_echo "$ac_cv_safe_to_define___extensions__" >&6; } - test $ac_cv_safe_to_define___extensions__ = yes && - $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h - - $as_echo "#define _ALL_SOURCE 1" >>confdefs.h - - $as_echo "#define _GNU_SOURCE 1" >>confdefs.h - - $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h - - $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h - - - -libtool_VERSION=1:0:0 - - -# 1.11.1: Require that version of automake. -# foreign: Don't require README, INSTALL, NEWS, etc. -# no-define: Don't define PACKAGE and VERSION. -# no-dependencies: Don't generate automatic dependencies. -# (because it breaks when using bootstrap-lean, since some of the -# headers are gone at "make install" time). -# -Wall: Issue all automake warnings. -# -Wno-portability: Don't warn about constructs supported by GNU make. -# (because GCC requires GNU make anyhow). -am__api_version='1.11' - -# Find a good install program. We prefer a C program (faster), -# so one script is as good as another. But avoid the broken or -# incompatible versions: -# SysV /etc/install, /usr/sbin/install -# SunOS /usr/etc/install -# IRIX /sbin/install -# AIX /bin/install -# AmigaOS /C/install, which installs bootblocks on floppy discs -# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag -# AFS /usr/afsws/bin/install, which mishandles nonexistent args -# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" -# OS/2's system install, which has a completely different semantic -# ./install, which can be erroneously created by make from ./install.sh. -# Reject install programs that cannot install multiple files. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 -$as_echo_n "checking for a BSD-compatible install... " >&6; } -if test -z "$INSTALL"; then -if test "${ac_cv_path_install+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - # Account for people who put trailing slashes in PATH elements. -case $as_dir/ in #(( - ./ | .// | /[cC]/* | \ - /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ - ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ - /usr/ucb/* ) ;; - *) - # OSF1 and SCO ODT 3.0 have their own names for install. - # Don't use installbsd from OSF since it installs stuff as root - # by default. - for ac_prog in ginstall scoinst install; do - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then - if test $ac_prog = install && - grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # AIX install. It has an incompatible calling convention. - : - elif test $ac_prog = install && - grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # program-specific install script used by HP pwplus--don't use. - : - else - rm -rf conftest.one conftest.two conftest.dir - echo one > conftest.one - echo two > conftest.two - mkdir conftest.dir - if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && - test -s conftest.one && test -s conftest.two && - test -s conftest.dir/conftest.one && - test -s conftest.dir/conftest.two - then - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 - fi - fi - fi - done - done - ;; -esac - - done -IFS=$as_save_IFS - -rm -rf conftest.one conftest.two conftest.dir - -fi - if test "${ac_cv_path_install+set}" = set; then - INSTALL=$ac_cv_path_install - else - # As a last resort, use the slow shell script. Don't cache a - # value for INSTALL within a source directory, because that will - # break other packages using the cache if that directory is - # removed, or if the value is a relative name. - INSTALL=$ac_install_sh - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 -$as_echo "$INSTALL" >&6; } - -# Use test -z because SunOS4 sh mishandles braces in ${var-val}. -# It thinks the first close brace ends the variable substitution. -test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' - -test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' - -test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 -$as_echo_n "checking whether build environment is sane... " >&6; } -# Just in case -sleep 1 -echo timestamp > conftest.file -# Reject unsafe characters in $srcdir or the absolute working directory -# name. Accept space and tab only in the latter. -am_lf=' -' -case `pwd` in - *[\\\"\#\$\&\'\`$am_lf]*) - as_fn_error "unsafe absolute working directory name" "$LINENO" 5;; -esac -case $srcdir in - *[\\\"\#\$\&\'\`$am_lf\ \ ]*) - as_fn_error "unsafe srcdir value: \`$srcdir'" "$LINENO" 5;; -esac - -# Do `set' in a subshell so we don't clobber the current shell's -# arguments. Must try -L first in case configure is actually a -# symlink; some systems play weird games with the mod time of symlinks -# (eg FreeBSD returns the mod time of the symlink's containing -# directory). -if ( - set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` - if test "$*" = "X"; then - # -L didn't work. - set X `ls -t "$srcdir/configure" conftest.file` - fi - rm -f conftest.file - if test "$*" != "X $srcdir/configure conftest.file" \ - && test "$*" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - as_fn_error "ls -t appears to fail. Make sure there is not a broken -alias in your environment" "$LINENO" 5 - fi - - test "$2" = conftest.file - ) -then - # Ok. - : -else - as_fn_error "newly created file is older than distributed files! -Check your system clock" "$LINENO" 5 -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -test "$program_prefix" != NONE && - program_transform_name="s&^&$program_prefix&;$program_transform_name" -# Use a double $ so make ignores it. -test "$program_suffix" != NONE && - program_transform_name="s&\$&$program_suffix&;$program_transform_name" -# Double any \ or $. -# By default was `s,x,x', remove it if useless. -ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' -program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` - -# expand $ac_aux_dir to an absolute path -am_aux_dir=`cd $ac_aux_dir && pwd` - -if test x"${MISSING+set}" != xset; then - case $am_aux_dir in - *\ * | *\ *) - MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; - *) - MISSING="\${SHELL} $am_aux_dir/missing" ;; - esac -fi -# Use eval to expand $SHELL -if eval "$MISSING --run true"; then - am_missing_run="$MISSING --run " -else - am_missing_run= - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`missing' script is too old or missing" >&5 -$as_echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;} -fi - -if test x"${install_sh}" != xset; then - case $am_aux_dir in - *\ * | *\ *) - install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; - *) - install_sh="\${SHELL} $am_aux_dir/install-sh" - esac -fi - -# Installed binaries are usually stripped using `strip' when the user -# run `make install-strip'. However `strip' might not be the right -# tool to use in cross-compilation environments, therefore Automake -# will honor the `STRIP' environment variable to overrule this program. -if test "$cross_compiling" != no; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. -set dummy ${ac_tool_prefix}strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_STRIP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$STRIP"; then - ac_cv_prog_STRIP="$STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_STRIP="${ac_tool_prefix}strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -STRIP=$ac_cv_prog_STRIP -if test -n "$STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 -$as_echo "$STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_STRIP"; then - ac_ct_STRIP=$STRIP - # Extract the first word of "strip", so it can be a program name with args. -set dummy strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_STRIP"; then - ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_STRIP="strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP -if test -n "$ac_ct_STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 -$as_echo "$ac_ct_STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_STRIP" = x; then - STRIP=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - STRIP=$ac_ct_STRIP - fi -else - STRIP="$ac_cv_prog_STRIP" -fi - -fi -INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 -$as_echo_n "checking for a thread-safe mkdir -p... " >&6; } -if test -z "$MKDIR_P"; then - if test "${ac_cv_path_mkdir+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in mkdir gmkdir; do - for ac_exec_ext in '' $ac_executable_extensions; do - { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue - case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( - 'mkdir (GNU coreutils) '* | \ - 'mkdir (coreutils) '* | \ - 'mkdir (fileutils) '4.1*) - ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext - break 3;; - esac - done - done - done -IFS=$as_save_IFS - -fi - - if test "${ac_cv_path_mkdir+set}" = set; then - MKDIR_P="$ac_cv_path_mkdir -p" - else - # As a last resort, use the slow shell script. Don't cache a - # value for MKDIR_P within a source directory, because that will - # break other packages using the cache if that directory is - # removed, or if the value is a relative name. - test -d ./--version && rmdir ./--version - MKDIR_P="$ac_install_sh -d" - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 -$as_echo "$MKDIR_P" >&6; } - -mkdir_p="$MKDIR_P" -case $mkdir_p in - [\\/$]* | ?:[\\/]*) ;; - */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;; -esac - -for ac_prog in gawk mawk nawk awk -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AWK+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$AWK"; then - ac_cv_prog_AWK="$AWK" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_AWK="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -AWK=$ac_cv_prog_AWK -if test -n "$AWK"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 -$as_echo "$AWK" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$AWK" && break -done - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 -$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } -set x ${MAKE-make} -ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` -if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - cat >conftest.make <<\_ACEOF -SHELL = /bin/sh -all: - @echo '@@@%%%=$(MAKE)=@@@%%%' -_ACEOF -# GNU make sometimes prints "make[1]: Entering...", which would confuse us. -case `${MAKE-make} -f conftest.make 2>/dev/null` in - *@@@%%%=?*=@@@%%%*) - eval ac_cv_prog_make_${ac_make}_set=yes;; - *) - eval ac_cv_prog_make_${ac_make}_set=no;; -esac -rm -f conftest.make -fi -if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - SET_MAKE= -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - SET_MAKE="MAKE=${MAKE-make}" -fi - -rm -rf .tst 2>/dev/null -mkdir .tst 2>/dev/null -if test -d .tst; then - am__leading_dot=. -else - am__leading_dot=_ -fi -rmdir .tst 2>/dev/null - -if test "`cd $srcdir && pwd`" != "`pwd`"; then - # Use -I$(srcdir) only when $(srcdir) != ., so that make's output - # is not polluted with repeated "-I." - am__isrc=' -I$(srcdir)' - # test to see if srcdir already configured - if test -f $srcdir/config.status; then - as_fn_error "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 - fi -fi - -# test whether we have cygpath -if test -z "$CYGPATH_W"; then - if (cygpath --version) >/dev/null 2>/dev/null; then - CYGPATH_W='cygpath -w' - else - CYGPATH_W=echo - fi -fi - - -# Define the identity of the package. - PACKAGE='libbacktrace' - VERSION='version-unused' - - -# Some tools Automake needs. - -ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} - - -AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} - - -AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} - - -AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} - - -MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} - -# We need awk for the "check" target. The system "awk" is bad on -# some platforms. -# Always define AMTAR for backward compatibility. Yes, it's still used -# in the wild :-( We should find a proper way to deprecate it ... -AMTAR='$${TAR-tar}' - -am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' - - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to enable maintainer-specific portions of Makefiles" >&5 -$as_echo_n "checking whether to enable maintainer-specific portions of Makefiles... " >&6; } - # Check whether --enable-maintainer-mode was given. -if test "${enable_maintainer_mode+set}" = set; then : - enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval -else - USE_MAINTAINER_MODE=no -fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >&5 -$as_echo "$USE_MAINTAINER_MODE" >&6; } - if test $USE_MAINTAINER_MODE = yes; then - MAINTAINER_MODE_TRUE= - MAINTAINER_MODE_FALSE='#' -else - MAINTAINER_MODE_TRUE='#' - MAINTAINER_MODE_FALSE= -fi - - MAINT=$MAINTAINER_MODE_TRUE - - - - -# Check whether --with-target-subdir was given. -if test "${with_target_subdir+set}" = set; then : - withval=$with_target_subdir; -fi - - -# We must force CC to /not/ be precious variables; otherwise -# the wrong, non-multilib-adjusted value will be used in multilibs. -# As a side effect, we have to subst CFLAGS ourselves. - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi - -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_CC" && break -done - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi - -fi - - -test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "no acceptable C compiler found in \$PATH -See \`config.log' for more details." "$LINENO" 5; } - -# Provide some information about the compiler. -$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -for ac_option in --version -v -V -qversion; do - { { ac_try="$ac_compiler $ac_option >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compiler $ac_option >&5") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - sed '10a\ -... rest of stderr output deleted ... - 10q' conftest.err >conftest.er1 - cat conftest.er1 >&5 - rm -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } -done - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 -$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_compiler_gnu=yes -else - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 -$as_echo "$ac_cv_c_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GCC=yes -else - GCC= -fi -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 -$as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -else - CFLAGS="" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - -else - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 -$as_echo "$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 -$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_c89=$ac_arg -fi -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC - -fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 -$as_echo "none needed" >&6; } ;; - xno) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 -$as_echo "unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 -$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; -esac -if test "x$ac_cv_prog_cc_c89" != xno; then : - -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - - - -for ac_prog in gawk mawk nawk awk -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AWK+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$AWK"; then - ac_cv_prog_AWK="$AWK" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_AWK="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -AWK=$ac_cv_prog_AWK -if test -n "$AWK"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 -$as_echo "$AWK" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$AWK" && break -done - -case "$AWK" in -"") as_fn_error "can't build without awk" "$LINENO" 5 ;; -esac - -case `pwd` in - *\ * | *\ *) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 -$as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; -esac - - - -macro_version='2.2.4' -macro_revision='1.2976' - - - - - - - - - - - - - -ltmain="$ac_aux_dir/ltmain.sh" - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 -$as_echo_n "checking for a sed that does not truncate output... " >&6; } -if test "${ac_cv_path_SED+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ - for ac_i in 1 2 3 4 5 6 7; do - ac_script="$ac_script$as_nl$ac_script" - done - echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed - { ac_script=; unset ac_script;} - if test -z "$SED"; then - ac_path_SED_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in sed gsed; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_SED" && $as_test_x "$ac_path_SED"; } || continue -# Check for GNU ac_path_SED and select it if it is found. - # Check for GNU $ac_path_SED -case `"$ac_path_SED" --version 2>&1` in -*GNU*) - ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo '' >> "conftest.nl" - "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_SED_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_SED="$ac_path_SED" - ac_path_SED_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_SED_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_SED"; then - as_fn_error "no acceptable sed could be found in \$PATH" "$LINENO" 5 - fi -else - ac_cv_path_SED=$SED -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 -$as_echo "$ac_cv_path_SED" >&6; } - SED="$ac_cv_path_SED" - rm -f conftest.sed - -test -z "$SED" && SED=sed -Xsed="$SED -e 1s/^X//" - - - - - - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 -$as_echo_n "checking for fgrep... " >&6; } -if test "${ac_cv_path_FGREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 - then ac_cv_path_FGREP="$GREP -F" - else - if test -z "$FGREP"; then - ac_path_FGREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in fgrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_FGREP" && $as_test_x "$ac_path_FGREP"; } || continue -# Check for GNU ac_path_FGREP and select it if it is found. - # Check for GNU $ac_path_FGREP -case `"$ac_path_FGREP" --version 2>&1` in -*GNU*) - ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'FGREP' >> "conftest.nl" - "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_FGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_FGREP="$ac_path_FGREP" - ac_path_FGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_FGREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_FGREP"; then - as_fn_error "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_FGREP=$FGREP -fi - - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 -$as_echo "$ac_cv_path_FGREP" >&6; } - FGREP="$ac_cv_path_FGREP" - - -test -z "$GREP" && GREP=grep - - - - - - - - - - - - - - - - - - - -# Check whether --with-gnu-ld was given. -if test "${with_gnu_ld+set}" = set; then : - withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes -else - with_gnu_ld=no -fi - -ac_prog=ld -if test "$GCC" = yes; then - # Check if gcc -print-prog-name=ld gives a path. - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 -$as_echo_n "checking for ld used by $CC... " >&6; } - case $host in - *-*-mingw*) - # gcc leaves a trailing carriage return which upsets mingw - ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; - *) - ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; - esac - case $ac_prog in - # Accept absolute paths. - [\\/]* | ?:[\\/]*) - re_direlt='/[^/][^/]*/\.\./' - # Canonicalize the pathname of ld - ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` - while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do - ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` - done - test -z "$LD" && LD="$ac_prog" - ;; - "") - # If it fails, then pretend we aren't using GCC. - ac_prog=ld - ;; - *) - # If it is relative, then search for the first ld in PATH. - with_gnu_ld=unknown - ;; - esac -elif test "$with_gnu_ld" = yes; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 -$as_echo_n "checking for GNU ld... " >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 -$as_echo_n "checking for non-GNU ld... " >&6; } -fi -if test "${lt_cv_path_LD+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -z "$LD"; then - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for ac_dir in $PATH; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then - lt_cv_path_LD="$ac_dir/$ac_prog" - # Check to see if the program is GNU ld. I'd rather use --version, - # but apparently some variants of GNU ld only accept -v. - # Break only if it was the GNU/non-GNU ld that we prefer. - case `"$lt_cv_path_LD" -v 2>&1 &5 -$as_echo "$LD" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi -test -z "$LD" && as_fn_error "no acceptable ld found in \$PATH" "$LINENO" 5 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 -$as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } -if test "${lt_cv_prog_gnu_ld+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - # I'd rather use --version here, but apparently some GNU lds only accept -v. -case `$LD -v 2>&1 &5 -$as_echo "$lt_cv_prog_gnu_ld" >&6; } -with_gnu_ld=$lt_cv_prog_gnu_ld - - - - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 -$as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } -if test "${lt_cv_path_NM+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$NM"; then - # Let the user override the test. - lt_cv_path_NM="$NM" -else - lt_nm_to_check="${ac_tool_prefix}nm" - if test -n "$ac_tool_prefix" && test "$build" = "$host"; then - lt_nm_to_check="$lt_nm_to_check nm" - fi - for lt_tmp_nm in $lt_nm_to_check; do - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - tmp_nm="$ac_dir/$lt_tmp_nm" - if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then - # Check to see if the nm accepts a BSD-compat flag. - # Adding the `sed 1q' prevents false positives on HP-UX, which says: - # nm: unknown option "B" ignored - # Tru64's nm complains that /dev/null is an invalid object file - case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in - */dev/null* | *'Invalid file or object type'*) - lt_cv_path_NM="$tmp_nm -B" - break - ;; - *) - case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in - */dev/null*) - lt_cv_path_NM="$tmp_nm -p" - break - ;; - *) - lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but - continue # so that we can try to find one that supports BSD flags - ;; - esac - ;; - esac - fi - done - IFS="$lt_save_ifs" - done - : ${lt_cv_path_NM=no} -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 -$as_echo "$lt_cv_path_NM" >&6; } -if test "$lt_cv_path_NM" != "no"; then - NM="$lt_cv_path_NM" -else - # Didn't find any BSD compatible name lister, look for dumpbin. - if test -n "$ac_tool_prefix"; then - for ac_prog in "dumpbin -symbols" "link -dump -symbols" - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_DUMPBIN+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$DUMPBIN"; then - ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -DUMPBIN=$ac_cv_prog_DUMPBIN -if test -n "$DUMPBIN"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 -$as_echo "$DUMPBIN" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$DUMPBIN" && break - done -fi -if test -z "$DUMPBIN"; then - ac_ct_DUMPBIN=$DUMPBIN - for ac_prog in "dumpbin -symbols" "link -dump -symbols" -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_DUMPBIN+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_DUMPBIN"; then - ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN -if test -n "$ac_ct_DUMPBIN"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 -$as_echo "$ac_ct_DUMPBIN" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_DUMPBIN" && break -done - - if test "x$ac_ct_DUMPBIN" = x; then - DUMPBIN=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - DUMPBIN=$ac_ct_DUMPBIN - fi -fi - - - if test "$DUMPBIN" != ":"; then - NM="$DUMPBIN" - fi -fi -test -z "$NM" && NM=nm - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 -$as_echo_n "checking the name lister ($NM) interface... " >&6; } -if test "${lt_cv_nm_interface+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_nm_interface="BSD nm" - echo "int some_variable = 0;" > conftest.$ac_ext - (eval echo "\"\$as_me:5363: $ac_compile\"" >&5) - (eval "$ac_compile" 2>conftest.err) - cat conftest.err >&5 - (eval echo "\"\$as_me:5366: $NM \\\"conftest.$ac_objext\\\"\"" >&5) - (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) - cat conftest.err >&5 - (eval echo "\"\$as_me:5369: output\"" >&5) - cat conftest.out >&5 - if $GREP 'External.*some_variable' conftest.out > /dev/null; then - lt_cv_nm_interface="MS dumpbin" - fi - rm -f conftest* -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 -$as_echo "$lt_cv_nm_interface" >&6; } - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 -$as_echo_n "checking whether ln -s works... " >&6; } -LN_S=$as_ln_s -if test "$LN_S" = "ln -s"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 -$as_echo "no, using $LN_S" >&6; } -fi - -# find the maximum length of command line arguments -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 -$as_echo_n "checking the maximum length of command line arguments... " >&6; } -if test "${lt_cv_sys_max_cmd_len+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - i=0 - teststring="ABCD" - - case $build_os in - msdosdjgpp*) - # On DJGPP, this test can blow up pretty badly due to problems in libc - # (any single argument exceeding 2000 bytes causes a buffer overrun - # during glob expansion). Even if it were fixed, the result of this - # check would be larger than it should be. - lt_cv_sys_max_cmd_len=12288; # 12K is about right - ;; - - gnu*) - # Under GNU Hurd, this test is not required because there is - # no limit to the length of command line arguments. - # Libtool will interpret -1 as no limit whatsoever - lt_cv_sys_max_cmd_len=-1; - ;; - - cygwin* | mingw*) - # On Win9x/ME, this test blows up -- it succeeds, but takes - # about 5 minutes as the teststring grows exponentially. - # Worse, since 9x/ME are not pre-emptively multitasking, - # you end up with a "frozen" computer, even though with patience - # the test eventually succeeds (with a max line length of 256k). - # Instead, let's just punt: use the minimum linelength reported by - # all of the supported platforms: 8192 (on NT/2K/XP). - lt_cv_sys_max_cmd_len=8192; - ;; - - amigaos*) - # On AmigaOS with pdksh, this test takes hours, literally. - # So we just punt and use a minimum line length of 8192. - lt_cv_sys_max_cmd_len=8192; - ;; - - netbsd* | freebsd* | openbsd* | darwin* | dragonfly* | bitrig*) - # This has been around since 386BSD, at least. Likely further. - if test -x /sbin/sysctl; then - lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` - elif test -x /usr/sbin/sysctl; then - lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` - else - lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs - fi - # And add a safety zone - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` - ;; - - interix*) - # We know the value 262144 and hardcode it with a safety zone (like BSD) - lt_cv_sys_max_cmd_len=196608 - ;; - - osf*) - # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure - # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not - # nice to cause kernel panics so lets avoid the loop below. - # First set a reasonable default. - lt_cv_sys_max_cmd_len=16384 - # - if test -x /sbin/sysconfig; then - case `/sbin/sysconfig -q proc exec_disable_arg_limit` in - *1*) lt_cv_sys_max_cmd_len=-1 ;; - esac - fi - ;; - sco3.2v5*) - lt_cv_sys_max_cmd_len=102400 - ;; - sysv5* | sco5v6* | sysv4.2uw2*) - kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` - if test -n "$kargmax"; then - lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` - else - lt_cv_sys_max_cmd_len=32768 - fi - ;; - *) - lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` - if test -n "$lt_cv_sys_max_cmd_len"; then - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` - else - # Make teststring a little bigger before we do anything with it. - # a 1K string should be a reasonable start. - for i in 1 2 3 4 5 6 7 8 ; do - teststring=$teststring$teststring - done - SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} - # If test is not a shell built-in, we'll probably end up computing a - # maximum length that is only half of the actual maximum length, but - # we can't tell. - while { test "X"`$SHELL $0 --fallback-echo "X$teststring$teststring" 2>/dev/null` \ - = "XX$teststring$teststring"; } >/dev/null 2>&1 && - test $i != 17 # 1/2 MB should be enough - do - i=`expr $i + 1` - teststring=$teststring$teststring - done - # Only check the string length outside the loop. - lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` - teststring= - # Add a significant safety factor because C++ compilers can tack on - # massive amounts of additional arguments before passing them to the - # linker. It appears as though 1/2 is a usable value. - lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` - fi - ;; - esac - -fi - -if test -n $lt_cv_sys_max_cmd_len ; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 -$as_echo "$lt_cv_sys_max_cmd_len" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 -$as_echo "none" >&6; } -fi -max_cmd_len=$lt_cv_sys_max_cmd_len - - - - - - -: ${CP="cp -f"} -: ${MV="mv -f"} -: ${RM="rm -f"} - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 -$as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } -# Try some XSI features -xsi_shell=no -( _lt_dummy="a/b/c" - test "${_lt_dummy##*/},${_lt_dummy%/*},"${_lt_dummy%"$_lt_dummy"}, \ - = c,a/b,, \ - && eval 'test $(( 1 + 1 )) -eq 2 \ - && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ - && xsi_shell=yes -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 -$as_echo "$xsi_shell" >&6; } - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 -$as_echo_n "checking whether the shell understands \"+=\"... " >&6; } -lt_shell_append=no -( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ - >/dev/null 2>&1 \ - && lt_shell_append=yes -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 -$as_echo "$lt_shell_append" >&6; } - - -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - lt_unset=unset -else - lt_unset=false -fi - - - - - -# test EBCDIC or ASCII -case `echo X|tr X '\101'` in - A) # ASCII based system - # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr - lt_SP2NL='tr \040 \012' - lt_NL2SP='tr \015\012 \040\040' - ;; - *) # EBCDIC based system - lt_SP2NL='tr \100 \n' - lt_NL2SP='tr \r\n \100\100' - ;; -esac - - - - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 -$as_echo_n "checking for $LD option to reload object files... " >&6; } -if test "${lt_cv_ld_reload_flag+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_ld_reload_flag='-r' -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 -$as_echo "$lt_cv_ld_reload_flag" >&6; } -reload_flag=$lt_cv_ld_reload_flag -case $reload_flag in -"" | " "*) ;; -*) reload_flag=" $reload_flag" ;; -esac -reload_cmds='$LD$reload_flag -o $output$reload_objs' -case $host_os in - darwin*) - if test "$GCC" = yes; then - reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' - else - reload_cmds='$LD$reload_flag -o $output$reload_objs' - fi - ;; -esac - - - - - - - - - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 -$as_echo_n "checking how to recognize dependent libraries... " >&6; } -if test "${lt_cv_deplibs_check_method+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_file_magic_cmd='$MAGIC_CMD' -lt_cv_file_magic_test_file= -lt_cv_deplibs_check_method='unknown' -# Need to set the preceding variable on all platforms that support -# interlibrary dependencies. -# 'none' -- dependencies not supported. -# `unknown' -- same as none, but documents that we really don't know. -# 'pass_all' -- all dependencies passed with no checks. -# 'test_compile' -- check by making test program. -# 'file_magic [[regex]]' -- check by looking for files in library path -# which responds to the $file_magic_cmd with a given extended regex. -# If you have `file' or equivalent on your system and you're not sure -# whether `pass_all' will *always* work, you probably want this one. - -case $host_os in -aix[4-9]*) - lt_cv_deplibs_check_method=pass_all - ;; - -beos*) - lt_cv_deplibs_check_method=pass_all - ;; - -bsdi[45]*) - lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' - lt_cv_file_magic_cmd='/usr/bin/file -L' - lt_cv_file_magic_test_file=/shlib/libc.so - ;; - -cygwin*) - # func_win32_libid is a shell function defined in ltmain.sh - lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' - lt_cv_file_magic_cmd='func_win32_libid' - ;; - -mingw* | pw32*) - # Base MSYS/MinGW do not provide the 'file' command needed by - # func_win32_libid shell function, so use a weaker test based on 'objdump', - # unless we find 'file', for example because we are cross-compiling. - if ( file / ) >/dev/null 2>&1; then - lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' - lt_cv_file_magic_cmd='func_win32_libid' - else - lt_cv_deplibs_check_method='file_magic file format pei*-i386(.*architecture: i386)?' - lt_cv_file_magic_cmd='$OBJDUMP -f' - fi - ;; - -darwin* | rhapsody*) - lt_cv_deplibs_check_method=pass_all - ;; - -freebsd* | dragonfly*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then - case $host_cpu in - i*86 ) - # Not sure whether the presence of OpenBSD here was a mistake. - # Let's accept both of them until this is cleared up. - lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' - lt_cv_file_magic_cmd=/usr/bin/file - lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` - ;; - esac - else - lt_cv_deplibs_check_method=pass_all - fi - ;; - -gnu*) - lt_cv_deplibs_check_method=pass_all - ;; - -hpux10.20* | hpux11*) - lt_cv_file_magic_cmd=/usr/bin/file - case $host_cpu in - ia64*) - lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' - lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so - ;; - hppa*64*) - lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - PA-RISC [0-9].[0-9]' - lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl - ;; - *) - lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9].[0-9]) shared library' - lt_cv_file_magic_test_file=/usr/lib/libc.sl - ;; - esac - ;; - -interix[3-9]*) - # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here - lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' - ;; - -irix5* | irix6* | nonstopux*) - case $LD in - *-32|*"-32 ") libmagic=32-bit;; - *-n32|*"-n32 ") libmagic=N32;; - *-64|*"-64 ") libmagic=64-bit;; - *) libmagic=never-match;; - esac - lt_cv_deplibs_check_method=pass_all - ;; - -# This must be Linux ELF. -linux* | k*bsd*-gnu) - lt_cv_deplibs_check_method=pass_all - ;; - -netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then - lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' - else - lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' - fi - ;; - -newos6*) - lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' - lt_cv_file_magic_cmd=/usr/bin/file - lt_cv_file_magic_test_file=/usr/lib/libnls.so - ;; - -*nto* | *qnx*) - lt_cv_deplibs_check_method=pass_all - ;; - -openbsd*) - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' - else - lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' - fi - ;; - -osf3* | osf4* | osf5*) - lt_cv_deplibs_check_method=pass_all - ;; - -rdos*) - lt_cv_deplibs_check_method=pass_all - ;; - -solaris*) - lt_cv_deplibs_check_method=pass_all - ;; - -sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) - lt_cv_deplibs_check_method=pass_all - ;; - -sysv4 | sysv4.3*) - case $host_vendor in - motorola) - lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' - lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` - ;; - ncr) - lt_cv_deplibs_check_method=pass_all - ;; - sequent) - lt_cv_file_magic_cmd='/bin/file' - lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' - ;; - sni) - lt_cv_file_magic_cmd='/bin/file' - lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" - lt_cv_file_magic_test_file=/lib/libc.so - ;; - siemens) - lt_cv_deplibs_check_method=pass_all - ;; - pc) - lt_cv_deplibs_check_method=pass_all - ;; - esac - ;; - -tpf*) - lt_cv_deplibs_check_method=pass_all - ;; -esac - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 -$as_echo "$lt_cv_deplibs_check_method" >&6; } -file_magic_cmd=$lt_cv_file_magic_cmd -deplibs_check_method=$lt_cv_deplibs_check_method -test -z "$deplibs_check_method" && deplibs_check_method=unknown - - - - - - - - - - - - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args. -set dummy ${ac_tool_prefix}ar; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AR+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$AR"; then - ac_cv_prog_AR="$AR" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_AR="${ac_tool_prefix}ar" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -AR=$ac_cv_prog_AR -if test -n "$AR"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 -$as_echo "$AR" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_AR"; then - ac_ct_AR=$AR - # Extract the first word of "ar", so it can be a program name with args. -set dummy ar; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_AR+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_AR"; then - ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_AR="ar" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_AR=$ac_cv_prog_ac_ct_AR -if test -n "$ac_ct_AR"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 -$as_echo "$ac_ct_AR" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_AR" = x; then - AR="false" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - AR=$ac_ct_AR - fi -else - AR="$ac_cv_prog_AR" -fi - -test -z "$AR" && AR=ar -test -z "$AR_FLAGS" && AR_FLAGS=cru - - - - - - - - - - - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. -set dummy ${ac_tool_prefix}strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_STRIP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$STRIP"; then - ac_cv_prog_STRIP="$STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_STRIP="${ac_tool_prefix}strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -STRIP=$ac_cv_prog_STRIP -if test -n "$STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 -$as_echo "$STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_STRIP"; then - ac_ct_STRIP=$STRIP - # Extract the first word of "strip", so it can be a program name with args. -set dummy strip; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_STRIP"; then - ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_STRIP="strip" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP -if test -n "$ac_ct_STRIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 -$as_echo "$ac_ct_STRIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_STRIP" = x; then - STRIP=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - STRIP=$ac_ct_STRIP - fi -else - STRIP="$ac_cv_prog_STRIP" -fi - -test -z "$STRIP" && STRIP=: - - - - - - -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. -set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_RANLIB+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$RANLIB"; then - ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -RANLIB=$ac_cv_prog_RANLIB -if test -n "$RANLIB"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 -$as_echo "$RANLIB" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_RANLIB"; then - ac_ct_RANLIB=$RANLIB - # Extract the first word of "ranlib", so it can be a program name with args. -set dummy ranlib; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_RANLIB"; then - ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_RANLIB="ranlib" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB -if test -n "$ac_ct_RANLIB"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 -$as_echo "$ac_ct_RANLIB" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_RANLIB" = x; then - RANLIB=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - RANLIB=$ac_ct_RANLIB - fi -else - RANLIB="$ac_cv_prog_RANLIB" -fi - -test -z "$RANLIB" && RANLIB=: - - - - - - -# Determine commands to create old-style static archives. -old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' -old_postinstall_cmds='chmod 644 $oldlib' -old_postuninstall_cmds= - -if test -n "$RANLIB"; then - case $host_os in - openbsd*) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$oldlib" - ;; - *) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$oldlib" - ;; - esac - old_archive_cmds="$old_archive_cmds~\$RANLIB \$oldlib" -fi - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -# If no C compiler was specified, use CC. -LTCC=${LTCC-"$CC"} - -# If no C compiler flags were specified, use CFLAGS. -LTCFLAGS=${LTCFLAGS-"$CFLAGS"} - -# Allow CC to be a program name with arguments. -compiler=$CC - - -# Check for command to grab the raw symbol name followed by C symbol from nm. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 -$as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } -if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - -# These are sane defaults that work on at least a few old systems. -# [They come from Ultrix. What could be older than Ultrix?!! ;)] - -# Character class describing NM global symbol codes. -symcode='[BCDEGRST]' - -# Regexp to match symbols that can be accessed directly from C. -sympat='\([_A-Za-z][_A-Za-z0-9]*\)' - -# Define system-specific variables. -case $host_os in -aix*) - symcode='[BCDT]' - ;; -cygwin* | mingw* | pw32*) - symcode='[ABCDGISTW]' - ;; -hpux*) - if test "$host_cpu" = ia64; then - symcode='[ABCDEGRST]' - fi - ;; -irix* | nonstopux*) - symcode='[BCDEGRST]' - ;; -osf*) - symcode='[BCDEGQRST]' - ;; -solaris*) - symcode='[BDRT]' - ;; -sco3.2v5*) - symcode='[DT]' - ;; -sysv4.2uw2*) - symcode='[DT]' - ;; -sysv5* | sco5v6* | unixware* | OpenUNIX*) - symcode='[ABDT]' - ;; -sysv4) - symcode='[DFNSTU]' - ;; -esac - -# If we're using GNU nm, then use its standard symbol codes. -case `$NM -V 2>&1` in -*GNU* | *'with BFD'*) - symcode='[ABCDGIRSTW]' ;; -esac - -# Transform an extracted symbol line into a proper C declaration. -# Some systems (esp. on ia64) link data and code symbols differently, -# so use this general approach. -lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" - -# Transform an extracted symbol line into symbol name and symbol address -lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" -lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\) $/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" - -# Handle CRLF in mingw tool chain -opt_cr= -case $build_os in -mingw*) - opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp - ;; -esac - -# Try without a prefix underscore, then with it. -for ac_symprfx in "" "_"; do - - # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. - symxfrm="\\1 $ac_symprfx\\2 \\2" - - # Write the raw and C identifiers. - if test "$lt_cv_nm_interface" = "MS dumpbin"; then - # Fake it for dumpbin and say T for any non-static function - # and D for any global variable. - # Also find C++ and __fastcall symbols from MSVC++, - # which start with @ or ?. - lt_cv_sys_global_symbol_pipe="$AWK '"\ -" {last_section=section; section=\$ 3};"\ -" /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ -" \$ 0!~/External *\|/{next};"\ -" / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ -" {if(hide[section]) next};"\ -" {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ -" {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ -" s[1]~/^[@?]/{print s[1], s[1]; next};"\ -" s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ -" ' prfx=^$ac_symprfx" - else - lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" - fi - - # Check to see that the pipe works correctly. - pipe_works=no - - rm -f conftest* - cat > conftest.$ac_ext <<_LT_EOF -#ifdef __cplusplus -extern "C" { -#endif -char nm_test_var; -void nm_test_func(void); -void nm_test_func(void){} -#ifdef __cplusplus -} -#endif -int main(){nm_test_var='a';nm_test_func();return(0);} -_LT_EOF - - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then - # Now try to grab the symbols. - nlist=conftest.nm - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist\""; } >&5 - (eval $NM conftest.$ac_objext \| $lt_cv_sys_global_symbol_pipe \> $nlist) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && test -s "$nlist"; then - # Try sorting and uniquifying the output. - if sort "$nlist" | uniq > "$nlist"T; then - mv -f "$nlist"T "$nlist" - else - rm -f "$nlist"T - fi - - # Make sure that we snagged all the symbols we need. - if $GREP ' nm_test_var$' "$nlist" >/dev/null; then - if $GREP ' nm_test_func$' "$nlist" >/dev/null; then - cat <<_LT_EOF > conftest.$ac_ext -#ifdef __cplusplus -extern "C" { -#endif - -_LT_EOF - # Now generate the symbol file. - eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' - - cat <<_LT_EOF >> conftest.$ac_ext - -/* The mapping between symbol names and symbols. */ -const struct { - const char *name; - void *address; -} -lt__PROGRAM__LTX_preloaded_symbols[] = -{ - { "@PROGRAM@", (void *) 0 }, -_LT_EOF - $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext - cat <<\_LT_EOF >> conftest.$ac_ext - {0, (void *) 0} -}; - -/* This works around a problem in FreeBSD linker */ -#ifdef FREEBSD_WORKAROUND -static const void *lt_preloaded_setup() { - return lt__PROGRAM__LTX_preloaded_symbols; -} -#endif - -#ifdef __cplusplus -} -#endif -_LT_EOF - # Now try linking the two files. - mv conftest.$ac_objext conftstm.$ac_objext - lt_save_LIBS="$LIBS" - lt_save_CFLAGS="$CFLAGS" - LIBS="conftstm.$ac_objext" - CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 - (eval $ac_link) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && test -s conftest${ac_exeext}; then - pipe_works=yes - fi - LIBS="$lt_save_LIBS" - CFLAGS="$lt_save_CFLAGS" - else - echo "cannot find nm_test_func in $nlist" >&5 - fi - else - echo "cannot find nm_test_var in $nlist" >&5 - fi - else - echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 - fi - else - echo "$progname: failed program was:" >&5 - cat conftest.$ac_ext >&5 - fi - rm -rf conftest* conftst* - - # Do not use the global_symbol_pipe unless it works. - if test "$pipe_works" = yes; then - break - else - lt_cv_sys_global_symbol_pipe= - fi -done - -fi - -if test -z "$lt_cv_sys_global_symbol_pipe"; then - lt_cv_sys_global_symbol_to_cdecl= -fi -if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 -$as_echo "failed" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 -$as_echo "ok" >&6; } -fi - - - - - - - - - - - - - - - - - - - - - - -# Check whether --enable-libtool-lock was given. -if test "${enable_libtool_lock+set}" = set; then : - enableval=$enable_libtool_lock; -fi - -test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes - -# Some flags need to be propagated to the compiler or linker for good -# libtool support. -case $host in -ia64-*-hpux*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then - case `/usr/bin/file conftest.$ac_objext` in - *ELF-32*) - HPUX_IA64_MODE="32" - ;; - *ELF-64*) - HPUX_IA64_MODE="64" - ;; - esac - fi - rm -rf conftest* - ;; -*-*-irix6*) - # Find out which ABI we are using. - echo '#line 6467 "configure"' > conftest.$ac_ext - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then - if test "$lt_cv_prog_gnu_ld" = yes; then - case `/usr/bin/file conftest.$ac_objext` in - *32-bit*) - LD="${LD-ld} -melf32bsmip" - ;; - *N32*) - LD="${LD-ld} -melf32bmipn32" - ;; - *64-bit*) - LD="${LD-ld} -melf64bmip" - ;; - esac - else - case `/usr/bin/file conftest.$ac_objext` in - *32-bit*) - LD="${LD-ld} -32" - ;; - *N32*) - LD="${LD-ld} -n32" - ;; - *64-bit*) - LD="${LD-ld} -64" - ;; - esac - fi - fi - rm -rf conftest* - ;; - -x86_64-*kfreebsd*-gnu|x86_64-*linux*|ppc*-*linux*|powerpc*-*linux*| \ -s390*-*linux*|s390*-*tpf*|sparc*-*linux*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then - case `/usr/bin/file conftest.o` in - *32-bit*) - case $host in - x86_64-*kfreebsd*-gnu) - LD="${LD-ld} -m elf_i386_fbsd" - ;; - x86_64-*linux*) - LD="${LD-ld} -m elf_i386" - ;; - ppc64-*linux*|powerpc64-*linux*) - LD="${LD-ld} -m elf32ppclinux" - ;; - s390x-*linux*) - LD="${LD-ld} -m elf_s390" - ;; - sparc64-*linux*) - LD="${LD-ld} -m elf32_sparc" - ;; - esac - ;; - *64-bit*) - case $host in - x86_64-*kfreebsd*-gnu) - LD="${LD-ld} -m elf_x86_64_fbsd" - ;; - x86_64-*linux*) - LD="${LD-ld} -m elf_x86_64" - ;; - ppc*-*linux*|powerpc*-*linux*) - LD="${LD-ld} -m elf64ppc" - ;; - s390*-*linux*|s390*-*tpf*) - LD="${LD-ld} -m elf64_s390" - ;; - sparc*-*linux*) - LD="${LD-ld} -m elf64_sparc" - ;; - esac - ;; - esac - fi - rm -rf conftest* - ;; - -*-*-sco3.2v5*) - # On SCO OpenServer 5, we need -belf to get full-featured binaries. - SAVE_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS -belf" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 -$as_echo_n "checking whether the C compiler needs -belf... " >&6; } -if test "${lt_cv_cc_needs_belf+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - lt_cv_cc_needs_belf=yes -else - lt_cv_cc_needs_belf=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 -$as_echo "$lt_cv_cc_needs_belf" >&6; } - if test x"$lt_cv_cc_needs_belf" != x"yes"; then - # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf - CFLAGS="$SAVE_CFLAGS" - fi - ;; -sparc*-*solaris*) - # Find out which ABI we are using. - echo 'int i;' > conftest.$ac_ext - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then - case `/usr/bin/file conftest.o` in - *64-bit*) - case $lt_cv_prog_gnu_ld in - yes*) LD="${LD-ld} -m elf64_sparc" ;; - *) - if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then - LD="${LD-ld} -64" - fi - ;; - esac - ;; - esac - fi - rm -rf conftest* - ;; -esac - -need_locks="$enable_libtool_lock" - - - case $host_os in - rhapsody* | darwin*) - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. -set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_DSYMUTIL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$DSYMUTIL"; then - ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -DSYMUTIL=$ac_cv_prog_DSYMUTIL -if test -n "$DSYMUTIL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 -$as_echo "$DSYMUTIL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_DSYMUTIL"; then - ac_ct_DSYMUTIL=$DSYMUTIL - # Extract the first word of "dsymutil", so it can be a program name with args. -set dummy dsymutil; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_DSYMUTIL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_DSYMUTIL"; then - ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL -if test -n "$ac_ct_DSYMUTIL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 -$as_echo "$ac_ct_DSYMUTIL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_DSYMUTIL" = x; then - DSYMUTIL=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - DSYMUTIL=$ac_ct_DSYMUTIL - fi -else - DSYMUTIL="$ac_cv_prog_DSYMUTIL" -fi - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. -set dummy ${ac_tool_prefix}nmedit; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_NMEDIT+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$NMEDIT"; then - ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -NMEDIT=$ac_cv_prog_NMEDIT -if test -n "$NMEDIT"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 -$as_echo "$NMEDIT" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_NMEDIT"; then - ac_ct_NMEDIT=$NMEDIT - # Extract the first word of "nmedit", so it can be a program name with args. -set dummy nmedit; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_NMEDIT+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_NMEDIT"; then - ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_NMEDIT="nmedit" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT -if test -n "$ac_ct_NMEDIT"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 -$as_echo "$ac_ct_NMEDIT" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_NMEDIT" = x; then - NMEDIT=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - NMEDIT=$ac_ct_NMEDIT - fi -else - NMEDIT="$ac_cv_prog_NMEDIT" -fi - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. -set dummy ${ac_tool_prefix}lipo; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_LIPO+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$LIPO"; then - ac_cv_prog_LIPO="$LIPO" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_LIPO="${ac_tool_prefix}lipo" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -LIPO=$ac_cv_prog_LIPO -if test -n "$LIPO"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 -$as_echo "$LIPO" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_LIPO"; then - ac_ct_LIPO=$LIPO - # Extract the first word of "lipo", so it can be a program name with args. -set dummy lipo; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_LIPO+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_LIPO"; then - ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_LIPO="lipo" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO -if test -n "$ac_ct_LIPO"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 -$as_echo "$ac_ct_LIPO" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_LIPO" = x; then - LIPO=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - LIPO=$ac_ct_LIPO - fi -else - LIPO="$ac_cv_prog_LIPO" -fi - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. -set dummy ${ac_tool_prefix}otool; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OTOOL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$OTOOL"; then - ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_OTOOL="${ac_tool_prefix}otool" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -OTOOL=$ac_cv_prog_OTOOL -if test -n "$OTOOL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 -$as_echo "$OTOOL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_OTOOL"; then - ac_ct_OTOOL=$OTOOL - # Extract the first word of "otool", so it can be a program name with args. -set dummy otool; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_OTOOL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_OTOOL"; then - ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_OTOOL="otool" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL -if test -n "$ac_ct_OTOOL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 -$as_echo "$ac_ct_OTOOL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_OTOOL" = x; then - OTOOL=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - OTOOL=$ac_ct_OTOOL - fi -else - OTOOL="$ac_cv_prog_OTOOL" -fi - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. -set dummy ${ac_tool_prefix}otool64; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OTOOL64+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$OTOOL64"; then - ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -OTOOL64=$ac_cv_prog_OTOOL64 -if test -n "$OTOOL64"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 -$as_echo "$OTOOL64" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_OTOOL64"; then - ac_ct_OTOOL64=$OTOOL64 - # Extract the first word of "otool64", so it can be a program name with args. -set dummy otool64; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_OTOOL64+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_OTOOL64"; then - ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_OTOOL64="otool64" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 -if test -n "$ac_ct_OTOOL64"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 -$as_echo "$ac_ct_OTOOL64" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_OTOOL64" = x; then - OTOOL64=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - OTOOL64=$ac_ct_OTOOL64 - fi -else - OTOOL64="$ac_cv_prog_OTOOL64" -fi - - - - - - - - - - - - - - - - - - - - - - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 -$as_echo_n "checking for -single_module linker flag... " >&6; } -if test "${lt_cv_apple_cc_single_mod+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_apple_cc_single_mod=no - if test -z "${LT_MULTI_MODULE}"; then - # By default we will add the -single_module flag. You can override - # by either setting the environment variable LT_MULTI_MODULE - # non-empty at configure time, or by adding -multi_module to the - # link flags. - rm -rf libconftest.dylib* - echo "int foo(void){return 1;}" > conftest.c - echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ --dynamiclib -Wl,-single_module conftest.c" >&5 - $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ - -dynamiclib -Wl,-single_module conftest.c 2>conftest.err - _lt_result=$? - if test -f libconftest.dylib && test ! -s conftest.err && test $_lt_result = 0; then - lt_cv_apple_cc_single_mod=yes - else - cat conftest.err >&5 - fi - rm -rf libconftest.dylib* - rm -f conftest.* - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 -$as_echo "$lt_cv_apple_cc_single_mod" >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 -$as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } -if test "${lt_cv_ld_exported_symbols_list+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_ld_exported_symbols_list=no - save_LDFLAGS=$LDFLAGS - echo "_main" > conftest.sym - LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - lt_cv_ld_exported_symbols_list=yes -else - lt_cv_ld_exported_symbols_list=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - LDFLAGS="$save_LDFLAGS" - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 -$as_echo "$lt_cv_ld_exported_symbols_list" >&6; } - case $host_os in - rhapsody* | darwin1.[012]) - _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; - darwin1.*) - _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; - darwin*) # darwin 5.x on - # if running on 10.5 or later, the deployment target defaults - # to the OS version, if on x86, and 10.4, the deployment - # target defaults to 10.4. Don't you love it? - case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in - 10.0,*86*-darwin8*|10.0,*-darwin[91]*) - _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; - 10.[012]*) - _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; - 10.*) - _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; - esac - ;; - esac - if test "$lt_cv_apple_cc_single_mod" = "yes"; then - _lt_dar_single_mod='$single_module' - fi - if test "$lt_cv_ld_exported_symbols_list" = "yes"; then - _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' - else - _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' - fi - if test "$DSYMUTIL" != ":"; then - _lt_dsymutil='~$DSYMUTIL $lib || :' - else - _lt_dsymutil= - fi - ;; - esac - -for ac_header in dlfcn.h -do : - ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default -" -if test "x$ac_cv_header_dlfcn_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_DLFCN_H 1 -_ACEOF - -fi - -done - - - -# Set options - - - - enable_dlopen=no - - - enable_win32_dll=no - - - # Check whether --enable-shared was given. -if test "${enable_shared+set}" = set; then : - enableval=$enable_shared; p=${PACKAGE-default} - case $enableval in - yes) enable_shared=yes ;; - no) enable_shared=no ;; - *) - enable_shared=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_shared=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac -else - enable_shared=yes -fi - - - - - - - - - - # Check whether --enable-static was given. -if test "${enable_static+set}" = set; then : - enableval=$enable_static; p=${PACKAGE-default} - case $enableval in - yes) enable_static=yes ;; - no) enable_static=no ;; - *) - enable_static=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_static=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac -else - enable_static=yes -fi - - - - - - - - - - -# Check whether --with-pic was given. -if test "${with_pic+set}" = set; then : - withval=$with_pic; pic_mode="$withval" -else - pic_mode=default -fi - - -test -z "$pic_mode" && pic_mode=default - - - - - - - - # Check whether --enable-fast-install was given. -if test "${enable_fast_install+set}" = set; then : - enableval=$enable_fast_install; p=${PACKAGE-default} - case $enableval in - yes) enable_fast_install=yes ;; - no) enable_fast_install=no ;; - *) - enable_fast_install=no - # Look at the argument we got. We use all the common list separators. - lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," - for pkg in $enableval; do - IFS="$lt_save_ifs" - if test "X$pkg" = "X$p"; then - enable_fast_install=yes - fi - done - IFS="$lt_save_ifs" - ;; - esac -else - enable_fast_install=yes -fi - - - - - - - - - - - -# This can be used to rebuild libtool when needed -LIBTOOL_DEPS="$ltmain" - -# Always use our own libtool. -LIBTOOL='$(SHELL) $(top_builddir)/libtool' - - - - - - - - - - - - - - - - - - - - - - - - - -test -z "$LN_S" && LN_S="ln -s" - - - - - - - - - - - - - - -if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 -$as_echo_n "checking for objdir... " >&6; } -if test "${lt_cv_objdir+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - rm -f .libs 2>/dev/null -mkdir .libs 2>/dev/null -if test -d .libs; then - lt_cv_objdir=.libs -else - # MS-DOS does not allow filenames that begin with a dot. - lt_cv_objdir=_libs -fi -rmdir .libs 2>/dev/null -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 -$as_echo "$lt_cv_objdir" >&6; } -objdir=$lt_cv_objdir - - - - - -cat >>confdefs.h <<_ACEOF -#define LT_OBJDIR "$lt_cv_objdir/" -_ACEOF - - - - - - - - - - - - - - - - - -case $host_os in -aix3*) - # AIX sometimes has problems with the GCC collect2 program. For some - # reason, if we set the COLLECT_NAMES environment variable, the problems - # vanish in a puff of smoke. - if test "X${COLLECT_NAMES+set}" != Xset; then - COLLECT_NAMES= - export COLLECT_NAMES - fi - ;; -esac - -# Sed substitution that helps us do robust quoting. It backslashifies -# metacharacters that are still active within double-quoted strings. -sed_quote_subst='s/\(["`$\\]\)/\\\1/g' - -# Same as above, but do not quote variable references. -double_quote_subst='s/\(["`\\]\)/\\\1/g' - -# Sed substitution to delay expansion of an escaped shell variable in a -# double_quote_subst'ed string. -delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' - -# Sed substitution to delay expansion of an escaped single quote. -delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' - -# Sed substitution to avoid accidental globbing in evaled expressions -no_glob_subst='s/\*/\\\*/g' - -# Global variables: -ofile=libtool -can_build_shared=yes - -# All known linkers require a `.a' archive for static linking (except MSVC, -# which needs '.lib'). -libext=a - -with_gnu_ld="$lt_cv_prog_gnu_ld" - -old_CC="$CC" -old_CFLAGS="$CFLAGS" - -# Set sane defaults for various variables -test -z "$CC" && CC=cc -test -z "$LTCC" && LTCC=$CC -test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS -test -z "$LD" && LD=ld -test -z "$ac_objext" && ac_objext=o - -for cc_temp in $compiler""; do - case $cc_temp in - compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; - distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; - \-*) ;; - *) break;; - esac -done -cc_basename=`$ECHO "X$cc_temp" | $Xsed -e 's%.*/%%' -e "s%^$host_alias-%%"` - - -# Only perform the check for file, if the check method requires it -test -z "$MAGIC_CMD" && MAGIC_CMD=file -case $deplibs_check_method in -file_magic*) - if test "$file_magic_cmd" = '$MAGIC_CMD'; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 -$as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } -if test "${lt_cv_path_MAGIC_CMD+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $MAGIC_CMD in -[\\/*] | ?:[\\/]*) - lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. - ;; -*) - lt_save_MAGIC_CMD="$MAGIC_CMD" - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" - for ac_dir in $ac_dummy; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/${ac_tool_prefix}file; then - lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" - if test -n "$file_magic_test_file"; then - case $deplibs_check_method in - "file_magic "*) - file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` - MAGIC_CMD="$lt_cv_path_MAGIC_CMD" - if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | - $EGREP "$file_magic_regex" > /dev/null; then - : - else - cat <<_LT_EOF 1>&2 - -*** Warning: the command libtool uses to detect shared libraries, -*** $file_magic_cmd, produces output that libtool cannot recognize. -*** The result is that libtool may fail to recognize shared libraries -*** as such. This will affect the creation of libtool libraries that -*** depend on shared libraries, but programs linked with such libtool -*** libraries will work regardless of this problem. Nevertheless, you -*** may want to report the problem to your system manager and/or to -*** bug-libtool@gnu.org - -_LT_EOF - fi ;; - esac - fi - break - fi - done - IFS="$lt_save_ifs" - MAGIC_CMD="$lt_save_MAGIC_CMD" - ;; -esac -fi - -MAGIC_CMD="$lt_cv_path_MAGIC_CMD" -if test -n "$MAGIC_CMD"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 -$as_echo "$MAGIC_CMD" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - - - -if test -z "$lt_cv_path_MAGIC_CMD"; then - if test -n "$ac_tool_prefix"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 -$as_echo_n "checking for file... " >&6; } -if test "${lt_cv_path_MAGIC_CMD+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $MAGIC_CMD in -[\\/*] | ?:[\\/]*) - lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. - ;; -*) - lt_save_MAGIC_CMD="$MAGIC_CMD" - lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR - ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" - for ac_dir in $ac_dummy; do - IFS="$lt_save_ifs" - test -z "$ac_dir" && ac_dir=. - if test -f $ac_dir/file; then - lt_cv_path_MAGIC_CMD="$ac_dir/file" - if test -n "$file_magic_test_file"; then - case $deplibs_check_method in - "file_magic "*) - file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` - MAGIC_CMD="$lt_cv_path_MAGIC_CMD" - if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | - $EGREP "$file_magic_regex" > /dev/null; then - : - else - cat <<_LT_EOF 1>&2 - -*** Warning: the command libtool uses to detect shared libraries, -*** $file_magic_cmd, produces output that libtool cannot recognize. -*** The result is that libtool may fail to recognize shared libraries -*** as such. This will affect the creation of libtool libraries that -*** depend on shared libraries, but programs linked with such libtool -*** libraries will work regardless of this problem. Nevertheless, you -*** may want to report the problem to your system manager and/or to -*** bug-libtool@gnu.org - -_LT_EOF - fi ;; - esac - fi - break - fi - done - IFS="$lt_save_ifs" - MAGIC_CMD="$lt_save_MAGIC_CMD" - ;; -esac -fi - -MAGIC_CMD="$lt_cv_path_MAGIC_CMD" -if test -n "$MAGIC_CMD"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 -$as_echo "$MAGIC_CMD" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - else - MAGIC_CMD=: - fi -fi - - fi - ;; -esac - -# Use C for the default configuration in the libtool script - -lt_save_CC="$CC" -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -# Source file extension for C test sources. -ac_ext=c - -# Object file extension for compiled C test sources. -objext=o -objext=$objext - -# Code to be used in simple compile tests -lt_simple_compile_test_code="int some_variable = 0;" - -# Code to be used in simple link tests -lt_simple_link_test_code='int main(){return(0);}' - - - - - - - -# If no C compiler was specified, use CC. -LTCC=${LTCC-"$CC"} - -# If no C compiler flags were specified, use CFLAGS. -LTCFLAGS=${LTCFLAGS-"$CFLAGS"} - -# Allow CC to be a program name with arguments. -compiler=$CC - -# Save the default compiler, since it gets overwritten when the other -# tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. -compiler_DEFAULT=$CC - -# save warnings/boilerplate of simple test code -ac_outfile=conftest.$ac_objext -echo "$lt_simple_compile_test_code" >conftest.$ac_ext -eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err -_lt_compiler_boilerplate=`cat conftest.err` -$RM conftest* - -ac_outfile=conftest.$ac_objext -echo "$lt_simple_link_test_code" >conftest.$ac_ext -eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err -_lt_linker_boilerplate=`cat conftest.err` -$RM -r conftest* - - -## CAVEAT EMPTOR: -## There is no encapsulation within the following macros, do not change -## the running order or otherwise move them around unless you know exactly -## what you are doing... -if test -n "$compiler"; then - -lt_prog_compiler_no_builtin_flag= - -if test "$GCC" = yes; then - lt_prog_compiler_no_builtin_flag=' -fno-builtin' - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 -$as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } -if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_prog_compiler_rtti_exceptions=no - ac_outfile=conftest.$ac_objext - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - lt_compiler_flag="-fno-rtti -fno-exceptions" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - # The option is referenced via a variable to avoid confusing sed. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:7729: $lt_compile\"" >&5) - (eval "$lt_compile" 2>conftest.err) - ac_status=$? - cat conftest.err >&5 - echo "$as_me:7733: \$? = $ac_status" >&5 - if (exit $ac_status) && test -s "$ac_outfile"; then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings other than the usual output. - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp - $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 - if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then - lt_cv_prog_compiler_rtti_exceptions=yes - fi - fi - $RM conftest* - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 -$as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } - -if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then - lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" -else - : -fi - -fi - - - - - - - lt_prog_compiler_wl= -lt_prog_compiler_pic= -lt_prog_compiler_static= - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 -$as_echo_n "checking for $compiler option to produce PIC... " >&6; } - - if test "$GCC" = yes; then - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_static='-static' - - case $host_os in - aix*) - # All AIX code is PIC. - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - lt_prog_compiler_static='-Bstatic' - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - lt_prog_compiler_pic='-fPIC' - ;; - m68k) - # FIXME: we need at least 68020 code to build shared libraries, but - # adding the `-m68020' flag to GCC prevents building anything better, - # like `-m68040'. - lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' - ;; - esac - ;; - - beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) - # PIC is the default for these OSes. - ;; - - mingw* | cygwin* | pw32* | os2*) - # This hack is so that the source file can tell whether it is being - # built for inclusion in a dll (and should export symbols for example). - # Although the cygwin gcc ignores -fPIC, still need this for old-style - # (--disable-auto-import) libraries - lt_prog_compiler_pic='-DDLL_EXPORT' - ;; - - darwin* | rhapsody*) - # PIC is the default on this platform - # Common symbols not allowed in MH_DYLIB files - lt_prog_compiler_pic='-fno-common' - ;; - - hpux*) - # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but - # not for PA HP-UX. - case $host_cpu in - hppa*64*|ia64*) - # +Z the default - ;; - *) - lt_prog_compiler_pic='-fPIC' - ;; - esac - ;; - - interix[3-9]*) - # Interix 3.x gcc -fpic/-fPIC options generate broken code. - # Instead, we relocate shared libraries at runtime. - ;; - - msdosdjgpp*) - # Just because we use GCC doesn't mean we suddenly get shared libraries - # on systems that don't support them. - lt_prog_compiler_can_build_shared=no - enable_shared=no - ;; - - *nto* | *qnx*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - lt_prog_compiler_pic='-fPIC -shared' - ;; - - sysv4*MP*) - if test -d /usr/nec; then - lt_prog_compiler_pic=-Kconform_pic - fi - ;; - - *) - lt_prog_compiler_pic='-fPIC' - ;; - esac - else - # PORTME Check for flag to pass linker flags through the system compiler. - case $host_os in - aix*) - lt_prog_compiler_wl='-Wl,' - if test "$host_cpu" = ia64; then - # AIX 5 now supports IA64 processor - lt_prog_compiler_static='-Bstatic' - else - lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' - fi - ;; - - mingw* | cygwin* | pw32* | os2*) - # This hack is so that the source file can tell whether it is being - # built for inclusion in a dll (and should export symbols for example). - lt_prog_compiler_pic='-DDLL_EXPORT' - ;; - - hpux9* | hpux10* | hpux11*) - lt_prog_compiler_wl='-Wl,' - # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but - # not for PA HP-UX. - case $host_cpu in - hppa*64*|ia64*) - # +Z the default - ;; - *) - lt_prog_compiler_pic='+Z' - ;; - esac - # Is there a better lt_prog_compiler_static that works with the bundled CC? - lt_prog_compiler_static='${wl}-a ${wl}archive' - ;; - - irix5* | irix6* | nonstopux*) - lt_prog_compiler_wl='-Wl,' - # PIC (with -KPIC) is the default. - lt_prog_compiler_static='-non_shared' - ;; - - linux* | k*bsd*-gnu) - case $cc_basename in - icc* | ecc* | ifort*) - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-static' - ;; - pgcc* | pgf77* | pgf90* | pgf95*) - # Portland Group compilers (*not* the Pentium gcc compiler, - # which looks to be a dead project) - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_pic='-fpic' - lt_prog_compiler_static='-Bstatic' - ;; - ccc*) - lt_prog_compiler_wl='-Wl,' - # All Alpha code is PIC. - lt_prog_compiler_static='-non_shared' - ;; - xl*) - # IBM XL C 8.0/Fortran 10.1 on PPC - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_pic='-qpic' - lt_prog_compiler_static='-qstaticlink' - ;; - *) - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) - # Sun C 5.9 - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - lt_prog_compiler_wl='-Wl,' - ;; - *Sun\ F*) - # Sun Fortran 8.3 passes all unrecognized flags to the linker - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - lt_prog_compiler_wl='' - ;; - esac - ;; - esac - ;; - - newsos6) - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - ;; - - *nto* | *qnx*) - # QNX uses GNU C++, but need to define -shared option too, otherwise - # it will coredump. - lt_prog_compiler_pic='-fPIC -shared' - ;; - - osf3* | osf4* | osf5*) - lt_prog_compiler_wl='-Wl,' - # All OSF/1 code is PIC. - lt_prog_compiler_static='-non_shared' - ;; - - rdos*) - lt_prog_compiler_static='-non_shared' - ;; - - solaris*) - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - case $cc_basename in - f77* | f90* | f95*) - lt_prog_compiler_wl='-Qoption ld ';; - *) - lt_prog_compiler_wl='-Wl,';; - esac - ;; - - sunos4*) - lt_prog_compiler_wl='-Qoption ld ' - lt_prog_compiler_pic='-PIC' - lt_prog_compiler_static='-Bstatic' - ;; - - sysv4 | sysv4.2uw2* | sysv4.3*) - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - ;; - - sysv4*MP*) - if test -d /usr/nec ;then - lt_prog_compiler_pic='-Kconform_pic' - lt_prog_compiler_static='-Bstatic' - fi - ;; - - sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_pic='-KPIC' - lt_prog_compiler_static='-Bstatic' - ;; - - unicos*) - lt_prog_compiler_wl='-Wl,' - lt_prog_compiler_can_build_shared=no - ;; - - uts4*) - lt_prog_compiler_pic='-pic' - lt_prog_compiler_static='-Bstatic' - ;; - - *) - lt_prog_compiler_can_build_shared=no - ;; - esac - fi - -case $host_os in - # For platforms which do not support PIC, -DPIC is meaningless: - *djgpp*) - lt_prog_compiler_pic= - ;; - *) - lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" - ;; -esac -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_prog_compiler_pic" >&5 -$as_echo "$lt_prog_compiler_pic" >&6; } - - - - - - -# -# Check to make sure the PIC flag actually works. -# -if test -n "$lt_prog_compiler_pic"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 -$as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } -if test "${lt_cv_prog_compiler_pic_works+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_prog_compiler_pic_works=no - ac_outfile=conftest.$ac_objext - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - lt_compiler_flag="$lt_prog_compiler_pic -DPIC" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - # The option is referenced via a variable to avoid confusing sed. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:8053: $lt_compile\"" >&5) - (eval "$lt_compile" 2>conftest.err) - ac_status=$? - cat conftest.err >&5 - echo "$as_me:8057: \$? = $ac_status" >&5 - if (exit $ac_status) && test -s "$ac_outfile"; then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings other than the usual output. - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp - $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 - if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then - lt_cv_prog_compiler_pic_works=yes - fi - fi - $RM conftest* - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 -$as_echo "$lt_cv_prog_compiler_pic_works" >&6; } - -if test x"$lt_cv_prog_compiler_pic_works" = xyes; then - case $lt_prog_compiler_pic in - "" | " "*) ;; - *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; - esac -else - lt_prog_compiler_pic= - lt_prog_compiler_can_build_shared=no -fi - -fi - - - - - - -# -# Check to make sure the static flag actually works. -# -wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 -$as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } -if test "${lt_cv_prog_compiler_static_works+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_prog_compiler_static_works=no - save_LDFLAGS="$LDFLAGS" - LDFLAGS="$LDFLAGS $lt_tmp_static_flag" - echo "$lt_simple_link_test_code" > conftest.$ac_ext - if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then - # The linker can only warn and ignore the option if not recognized - # So say no if there are warnings - if test -s conftest.err; then - # Append any errors to the config.log. - cat conftest.err 1>&5 - $ECHO "X$_lt_linker_boilerplate" | $Xsed -e '/^$/d' > conftest.exp - $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 - if diff conftest.exp conftest.er2 >/dev/null; then - lt_cv_prog_compiler_static_works=yes - fi - else - lt_cv_prog_compiler_static_works=yes - fi - fi - $RM -r conftest* - LDFLAGS="$save_LDFLAGS" - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 -$as_echo "$lt_cv_prog_compiler_static_works" >&6; } - -if test x"$lt_cv_prog_compiler_static_works" = xyes; then - : -else - lt_prog_compiler_static= -fi - - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 -$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } -if test "${lt_cv_prog_compiler_c_o+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_prog_compiler_c_o=no - $RM -r conftest 2>/dev/null - mkdir conftest - cd conftest - mkdir out - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - - lt_compiler_flag="-o out/conftest2.$ac_objext" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:8158: $lt_compile\"" >&5) - (eval "$lt_compile" 2>out/conftest.err) - ac_status=$? - cat out/conftest.err >&5 - echo "$as_me:8162: \$? = $ac_status" >&5 - if (exit $ac_status) && test -s out/conftest2.$ac_objext - then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp - $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 - if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then - lt_cv_prog_compiler_c_o=yes - fi - fi - chmod u+w . 2>&5 - $RM conftest* - # SGI C++ compiler will create directory out/ii_files/ for - # template instantiation - test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files - $RM out/* && rmdir out - cd .. - $RM -r conftest - $RM conftest* - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 -$as_echo "$lt_cv_prog_compiler_c_o" >&6; } - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 -$as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } -if test "${lt_cv_prog_compiler_c_o+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - lt_cv_prog_compiler_c_o=no - $RM -r conftest 2>/dev/null - mkdir conftest - cd conftest - mkdir out - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - - lt_compiler_flag="-o out/conftest2.$ac_objext" - # Insert the option either (1) after the last *FLAGS variable, or - # (2) before a word containing "conftest.", or (3) at the end. - # Note that $ac_compile itself does not contain backslashes and begins - # with a dollar sign (not a hyphen), so the echo should work correctly. - lt_compile=`echo "$ac_compile" | $SED \ - -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ - -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ - -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:8213: $lt_compile\"" >&5) - (eval "$lt_compile" 2>out/conftest.err) - ac_status=$? - cat out/conftest.err >&5 - echo "$as_me:8217: \$? = $ac_status" >&5 - if (exit $ac_status) && test -s out/conftest2.$ac_objext - then - # The compiler can only warn and ignore the option if not recognized - # So say no if there are warnings - $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp - $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 - if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then - lt_cv_prog_compiler_c_o=yes - fi - fi - chmod u+w . 2>&5 - $RM conftest* - # SGI C++ compiler will create directory out/ii_files/ for - # template instantiation - test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files - $RM out/* && rmdir out - cd .. - $RM -r conftest - $RM conftest* - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 -$as_echo "$lt_cv_prog_compiler_c_o" >&6; } - - - - -hard_links="nottested" -if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then - # do not overwrite the value of need_locks provided by the user - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 -$as_echo_n "checking if we can lock with hard links... " >&6; } - hard_links=yes - $RM conftest* - ln conftest.a conftest.b 2>/dev/null && hard_links=no - touch conftest.a - ln conftest.a conftest.b 2>&5 || hard_links=no - ln conftest.a conftest.b 2>/dev/null && hard_links=no - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 -$as_echo "$hard_links" >&6; } - if test "$hard_links" = no; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 -$as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} - need_locks=warn - fi -else - need_locks=no -fi - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 -$as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } - - runpath_var= - allow_undefined_flag= - always_export_symbols=no - archive_cmds= - archive_expsym_cmds= - compiler_needs_object=no - enable_shared_with_static_runtimes=no - export_dynamic_flag_spec= - export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' - hardcode_automatic=no - hardcode_direct=no - hardcode_direct_absolute=no - hardcode_libdir_flag_spec= - hardcode_libdir_flag_spec_ld= - hardcode_libdir_separator= - hardcode_minus_L=no - hardcode_shlibpath_var=unsupported - inherit_rpath=no - link_all_deplibs=unknown - module_cmds= - module_expsym_cmds= - old_archive_from_new_cmds= - old_archive_from_expsyms_cmds= - thread_safe_flag_spec= - whole_archive_flag_spec= - # include_expsyms should be a list of space-separated symbols to be *always* - # included in the symbol list - include_expsyms= - # exclude_expsyms can be an extended regexp of symbols to exclude - # it will be wrapped by ` (' and `)$', so one must not match beginning or - # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', - # as well as any symbol that contains `d'. - exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' - # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out - # platforms (ab)use it in PIC code, but their linkers get confused if - # the symbol is explicitly referenced. Since portable code cannot - # rely on this symbol name, it's probably fine to never include it in - # preloaded symbol tables. - # Exclude shared library initialization/finalization symbols. - extract_expsyms_cmds= - - case $host_os in - cygwin* | mingw* | pw32*) - # FIXME: the MSVC++ port hasn't been tested in a loooong time - # When not using gcc, we currently assume that we are using - # Microsoft Visual C++. - if test "$GCC" != yes; then - with_gnu_ld=no - fi - ;; - interix*) - # we just hope/assume this is gcc and not c89 (= MSVC++) - with_gnu_ld=yes - ;; - openbsd*) - with_gnu_ld=no - ;; - esac - - ld_shlibs=yes - if test "$with_gnu_ld" = yes; then - # If archive_cmds runs LD, not CC, wlarc should be empty - wlarc='${wl}' - - # Set some defaults for GNU ld with shared library support. These - # are reset later if shared libraries are not supported. Putting them - # here allows them to be overridden if necessary. - runpath_var=LD_RUN_PATH - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - export_dynamic_flag_spec='${wl}--export-dynamic' - # ancient GNU ld didn't support --whole-archive et. al. - if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then - whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' - else - whole_archive_flag_spec= - fi - supports_anon_versioning=no - case `$LD -v 2>&1` in - *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 - *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... - *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... - *\ 2.11.*) ;; # other 2.11 versions - *) supports_anon_versioning=yes ;; - esac - - # See if GNU ld supports shared libraries. - case $host_os in - aix[3-9]*) - # On AIX/PPC, the GNU linker is very broken - if test "$host_cpu" != ia64; then - ld_shlibs=no - cat <<_LT_EOF 1>&2 - -*** Warning: the GNU linker, at least up to release 2.9.1, is reported -*** to be unable to reliably create shared libraries on AIX. -*** Therefore, libtool is disabling shared libraries support. If you -*** really care for shared libraries, you may want to modify your PATH -*** so that a non-GNU linker is found, and then restart. - -_LT_EOF - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='' - ;; - m68k) - archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' - hardcode_libdir_flag_spec='-L$libdir' - hardcode_minus_L=yes - ;; - esac - ;; - - beos*) - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - allow_undefined_flag=unsupported - # Joseph Beckenbach says some releases of gcc - # support --undefined. This deserves some investigation. FIXME - archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - else - ld_shlibs=no - fi - ;; - - cygwin* | mingw* | pw32*) - # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, - # as there is no search path for DLLs. - hardcode_libdir_flag_spec='-L$libdir' - allow_undefined_flag=unsupported - always_export_symbols=no - enable_shared_with_static_runtimes=yes - export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' - - if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - # If the export-symbols file already is a .def file (1st line - # is EXPORTS), use it as is; otherwise, prepend... - archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then - cp $export_symbols $output_objdir/$soname.def; - else - echo EXPORTS > $output_objdir/$soname.def; - cat $export_symbols >> $output_objdir/$soname.def; - fi~ - $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' - else - ld_shlibs=no - fi - ;; - - interix[3-9]*) - hardcode_direct=no - hardcode_shlibpath_var=no - hardcode_libdir_flag_spec='${wl}-rpath,$libdir' - export_dynamic_flag_spec='${wl}-E' - # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. - # Instead, shared libraries are loaded at an image base (0x10000000 by - # default) and relocated if they conflict, which is a slow very memory - # consuming and fragmenting process. To avoid this, we pick a random, - # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link - # time. Moving up from 0x10000000 also allows more sbrk(2) space. - archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' - ;; - - gnu* | linux* | tpf* | k*bsd*-gnu) - tmp_diet=no - if test "$host_os" = linux-dietlibc; then - case $cc_basename in - diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) - esac - fi - if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ - && test "$tmp_diet" = no - then - tmp_addflag= - tmp_sharedflag='-shared' - case $cc_basename,$host_cpu in - pgcc*) # Portland Group C compiler - whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - tmp_addflag=' $pic_flag' - ;; - pgf77* | pgf90* | pgf95*) # Portland Group f77 and f90 compilers - whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - tmp_addflag=' $pic_flag -Mnomain' ;; - ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 - tmp_addflag=' -i_dynamic' ;; - efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 - tmp_addflag=' -i_dynamic -nofor_main' ;; - ifc* | ifort*) # Intel Fortran compiler - tmp_addflag=' -nofor_main' ;; - xl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) - tmp_sharedflag='-qmkshrobj' - tmp_addflag= ;; - esac - case `$CC -V 2>&1 | sed 5q` in - *Sun\ C*) # Sun C 5.9 - whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; $ECHO \"$new_convenience\"` ${wl}--no-whole-archive' - compiler_needs_object=yes - tmp_sharedflag='-G' ;; - *Sun\ F*) # Sun Fortran 8.3 - tmp_sharedflag='-G' ;; - esac - archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - - if test "x$supports_anon_versioning" = xyes; then - archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ - cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ - echo "local: *; };" >> $output_objdir/$libname.ver~ - $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' - fi - - case $cc_basename in - xlf*) - # IBM XL Fortran 10.1 on PPC cannot create shared libs itself - whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' - hardcode_libdir_flag_spec= - hardcode_libdir_flag_spec_ld='-rpath $libdir' - archive_cmds='$LD -shared $libobjs $deplibs $compiler_flags -soname $soname -o $lib' - if test "x$supports_anon_versioning" = xyes; then - archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ - cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ - echo "local: *; };" >> $output_objdir/$libname.ver~ - $LD -shared $libobjs $deplibs $compiler_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' - fi - ;; - esac - else - ld_shlibs=no - fi - ;; - - netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' - wlarc= - else - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - fi - ;; - - solaris*) - if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then - ld_shlibs=no - cat <<_LT_EOF 1>&2 - -*** Warning: The releases 2.8.* of the GNU linker cannot reliably -*** create shared libraries on Solaris systems. Therefore, libtool -*** is disabling shared libraries support. We urge you to upgrade GNU -*** binutils to release 2.9.1 or newer. Another option is to modify -*** your PATH or compiler configuration so that the native linker is -*** used, and then restart. - -_LT_EOF - elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - ld_shlibs=no - fi - ;; - - sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) - case `$LD -v 2>&1` in - *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) - ld_shlibs=no - cat <<_LT_EOF 1>&2 - -*** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not -*** reliably create shared libraries on SCO systems. Therefore, libtool -*** is disabling shared libraries support. We urge you to upgrade GNU -*** binutils to release 2.16.91.0.3 or newer. Another option is to modify -*** your PATH or compiler configuration so that the native linker is -*** used, and then restart. - -_LT_EOF - ;; - *) - # For security reasons, it is highly recommended that you always - # use absolute paths for naming shared libraries, and exclude the - # DT_RUNPATH tag from executables and libraries. But doing so - # requires that you compile everything twice, which is a pain. - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - ld_shlibs=no - fi - ;; - esac - ;; - - sunos4*) - archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' - wlarc= - hardcode_direct=yes - hardcode_shlibpath_var=no - ;; - - *) - if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' - else - ld_shlibs=no - fi - ;; - esac - - if test "$ld_shlibs" = no; then - runpath_var= - hardcode_libdir_flag_spec= - export_dynamic_flag_spec= - whole_archive_flag_spec= - fi - else - # PORTME fill in a description of your system's linker (not GNU ld) - case $host_os in - aix3*) - allow_undefined_flag=unsupported - always_export_symbols=yes - archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' - # Note: this linker hardcodes the directories in LIBPATH if there - # are no directories specified by -L. - hardcode_minus_L=yes - if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then - # Neither direct hardcoding nor static linking is supported with a - # broken collect2. - hardcode_direct=unsupported - fi - ;; - - aix[4-9]*) - if test "$host_cpu" = ia64; then - # On IA64, the linker does run time linking by default, so we don't - # have to do anything special. - aix_use_runtimelinking=no - exp_sym_flag='-Bexport' - no_entry_flag="" - else - # If we're using GNU nm, then we don't want the "-C" option. - # -C means demangle to AIX nm, but means don't demangle with GNU nm - if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then - export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - else - export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' - fi - aix_use_runtimelinking=no - - # Test if we are trying to use run time linking or normal - # AIX style linking. If -brtl is somewhere in LDFLAGS, we - # need to do runtime linking. - case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) - for ld_flag in $LDFLAGS; do - if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then - aix_use_runtimelinking=yes - break - fi - done - ;; - esac - - exp_sym_flag='-bexport' - no_entry_flag='-bnoentry' - fi - - # When large executables or shared objects are built, AIX ld can - # have problems creating the table of contents. If linking a library - # or program results in "error TOC overflow" add -mminimal-toc to - # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not - # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. - - archive_cmds='' - hardcode_direct=yes - hardcode_direct_absolute=yes - hardcode_libdir_separator=':' - link_all_deplibs=yes - file_list_spec='${wl}-f,' - - if test "$GCC" = yes; then - case $host_os in aix4.[012]|aix4.[012].*) - # We only want to do this on AIX 4.2 and lower, the check - # below for broken collect2 doesn't work under 4.3+ - collect2name=`${CC} -print-prog-name=collect2` - if test -f "$collect2name" && - strings "$collect2name" | $GREP resolve_lib_name >/dev/null - then - # We have reworked collect2 - : - else - # We have old collect2 - hardcode_direct=unsupported - # It fails to find uninstalled libraries when the uninstalled - # path is not listed in the libpath. Setting hardcode_minus_L - # to unsupported forces relinking - hardcode_minus_L=yes - hardcode_libdir_flag_spec='-L$libdir' - hardcode_libdir_separator= - fi - ;; - esac - shared_flag='-shared' - if test "$aix_use_runtimelinking" = yes; then - shared_flag="$shared_flag "'${wl}-G' - fi - else - # not using gcc - if test "$host_cpu" = ia64; then - # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release - # chokes on -Wl,-G. The following line is correct: - shared_flag='-G' - else - if test "$aix_use_runtimelinking" = yes; then - shared_flag='${wl}-G' - else - shared_flag='${wl}-bM:SRE' - fi - fi - fi - - # It seems that -bexpall does not export symbols beginning with - # underscore (_), so it is better to generate a list of symbols to export. - always_export_symbols=yes - if test "$aix_use_runtimelinking" = yes; then - # Warning - without using the other runtime loading flags (-brtl), - # -berok will link without error, but may produce a broken library. - allow_undefined_flag='-berok' - # Determine the default libpath from the value encoded in an - # empty executable. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - -lt_aix_libpath_sed=' - /Import File Strings/,/^$/ { - /^0/ { - s/^0 *\(.*\)$/\1/ - p - } - }' -aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -# Check for a 64-bit object if we didn't find anything. -if test -z "$aix_libpath"; then - aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -fi -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi - - hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" - archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then $ECHO "X${wl}${allow_undefined_flag}" | $Xsed; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" - else - if test "$host_cpu" = ia64; then - hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' - allow_undefined_flag="-z nodefs" - archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" - else - # Determine the default libpath from the value encoded in an - # empty executable. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - -lt_aix_libpath_sed=' - /Import File Strings/,/^$/ { - /^0/ { - s/^0 *\(.*\)$/\1/ - p - } - }' -aix_libpath=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -# Check for a 64-bit object if we didn't find anything. -if test -z "$aix_libpath"; then - aix_libpath=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` -fi -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -if test -z "$aix_libpath"; then aix_libpath="/usr/lib:/lib"; fi - - hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" - # Warning - without using the other run time loading flags, - # -berok will link without error, but may produce a broken library. - no_undefined_flag=' ${wl}-bernotok' - allow_undefined_flag=' ${wl}-berok' - # Exported symbols can be pulled into shared objects from archives - whole_archive_flag_spec='$convenience' - archive_cmds_need_lc=yes - # This is similar to how AIX traditionally builds its shared libraries. - archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' - fi - fi - ;; - - amigaos*) - case $host_cpu in - powerpc) - # see comment about AmigaOS4 .so support - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' - archive_expsym_cmds='' - ;; - m68k) - archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' - hardcode_libdir_flag_spec='-L$libdir' - hardcode_minus_L=yes - ;; - esac - ;; - - bsdi[45]*) - export_dynamic_flag_spec=-rdynamic - ;; - - cygwin* | mingw* | pw32*) - # When not using gcc, we currently assume that we are using - # Microsoft Visual C++. - # hardcode_libdir_flag_spec is actually meaningless, as there is - # no search path for DLLs. - hardcode_libdir_flag_spec=' ' - allow_undefined_flag=unsupported - # Tell ltmain to make .lib files, not .a files. - libext=lib - # Tell ltmain to make .dll files, not .so files. - shrext_cmds=".dll" - # FIXME: Setting linknames here is a bad hack. - archive_cmds='$CC -o $lib $libobjs $compiler_flags `$ECHO "X$deplibs" | $Xsed -e '\''s/ -lc$//'\''` -link -dll~linknames=' - # The linker will automatically build a .lib file if we build a DLL. - old_archive_from_new_cmds='true' - # FIXME: Should let the user specify the lib program. - old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' - fix_srcfile_path='`cygpath -w "$srcfile"`' - enable_shared_with_static_runtimes=yes - ;; - - darwin* | rhapsody*) - - - archive_cmds_need_lc=no - hardcode_direct=no - hardcode_automatic=yes - hardcode_shlibpath_var=unsupported - whole_archive_flag_spec='' - link_all_deplibs=yes - allow_undefined_flag="$_lt_dar_allow_undefined" - if test "$GCC" = "yes"; then - output_verbose_link_cmd=echo - archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" - module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" - archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" - module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" - - else - ld_shlibs=no - fi - - ;; - - dgux*) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_libdir_flag_spec='-L$libdir' - hardcode_shlibpath_var=no - ;; - - freebsd1*) - ld_shlibs=no - ;; - - # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor - # support. Future versions do this automatically, but an explicit c++rt0.o - # does not break anything, and helps significantly (at the cost of a little - # extra space). - freebsd2.2*) - archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' - hardcode_libdir_flag_spec='-R$libdir' - hardcode_direct=yes - hardcode_shlibpath_var=no - ;; - - # Unfortunately, older versions of FreeBSD 2 do not have this feature. - freebsd2*) - archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' - hardcode_direct=yes - hardcode_minus_L=yes - hardcode_shlibpath_var=no - ;; - - # FreeBSD 3 and greater uses gcc -shared to do shared libraries. - freebsd* | dragonfly* | openbsd* | bitrig*) - archive_cmds='$CC -shared -o $lib $libobjs $deplibs $compiler_flags' - hardcode_libdir_flag_spec='-R$libdir' - hardcode_direct=yes - hardcode_shlibpath_var=no - ;; - - hpux9*) - if test "$GCC" = yes; then - archive_cmds='$RM $output_objdir/$soname~$CC -shared -fPIC ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - else - archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' - fi - hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' - hardcode_libdir_separator=: - hardcode_direct=yes - - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - hardcode_minus_L=yes - export_dynamic_flag_spec='${wl}-E' - ;; - - hpux10*) - if test "$GCC" = yes -a "$with_gnu_ld" = no; then - archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - else - archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' - fi - if test "$with_gnu_ld" = no; then - hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' - hardcode_libdir_flag_spec_ld='+b $libdir' - hardcode_libdir_separator=: - hardcode_direct=yes - hardcode_direct_absolute=yes - export_dynamic_flag_spec='${wl}-E' - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - hardcode_minus_L=yes - fi - ;; - - hpux11*) - if test "$GCC" = yes -a "$with_gnu_ld" = no; then - case $host_cpu in - hppa*64*) - archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - ia64*) - archive_cmds='$CC -shared ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - archive_cmds='$CC -shared -fPIC ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - else - case $host_cpu in - hppa*64*) - archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - ;; - ia64*) - archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' - ;; - *) - archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' - ;; - esac - fi - if test "$with_gnu_ld" = no; then - hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' - hardcode_libdir_separator=: - - case $host_cpu in - hppa*64*|ia64*) - hardcode_direct=no - hardcode_shlibpath_var=no - ;; - *) - hardcode_direct=yes - hardcode_direct_absolute=yes - export_dynamic_flag_spec='${wl}-E' - - # hardcode_minus_L: Not really in the search PATH, - # but as the default location of the library. - hardcode_minus_L=yes - ;; - esac - fi - ;; - - irix5* | irix6* | nonstopux*) - if test "$GCC" = yes; then - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - # Try to use the -exported_symbol ld option, if it does not - # work, assume that -exports_file does not work either and - # implicitly export all symbols. - save_LDFLAGS="$LDFLAGS" - LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -int foo(void) {} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' - -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - LDFLAGS="$save_LDFLAGS" - else - archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' - fi - archive_cmds_need_lc='no' - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - hardcode_libdir_separator=: - inherit_rpath=yes - link_all_deplibs=yes - ;; - - netbsd*) - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out - else - archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF - fi - hardcode_libdir_flag_spec='-R$libdir' - hardcode_direct=yes - hardcode_shlibpath_var=no - ;; - - newsos6) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_direct=yes - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - hardcode_libdir_separator=: - hardcode_shlibpath_var=no - ;; - - *nto* | *qnx*) - ;; - - openbsd*) - if test -f /usr/libexec/ld.so; then - hardcode_direct=yes - hardcode_shlibpath_var=no - hardcode_direct_absolute=yes - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' - hardcode_libdir_flag_spec='${wl}-rpath,$libdir' - export_dynamic_flag_spec='${wl}-E' - else - case $host_os in - openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) - archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' - hardcode_libdir_flag_spec='-R$libdir' - ;; - *) - archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' - hardcode_libdir_flag_spec='${wl}-rpath,$libdir' - ;; - esac - fi - else - ld_shlibs=no - fi - ;; - - os2*) - hardcode_libdir_flag_spec='-L$libdir' - hardcode_minus_L=yes - allow_undefined_flag=unsupported - archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~$ECHO DATA >> $output_objdir/$libname.def~$ECHO " SINGLE NONSHARED" >> $output_objdir/$libname.def~$ECHO EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' - old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' - ;; - - osf3*) - if test "$GCC" = yes; then - allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' - archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - else - allow_undefined_flag=' -expect_unresolved \*' - archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - fi - archive_cmds_need_lc='no' - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - hardcode_libdir_separator=: - ;; - - osf4* | osf5*) # as osf3* with the addition of -msym flag - if test "$GCC" = yes; then - allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' - archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && $ECHO "X${wl}-set_version ${wl}$verstring" | $Xsed` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' - hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' - else - allow_undefined_flag=' -expect_unresolved \*' - archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib' - archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ - $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "X-set_version $verstring" | $Xsed` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' - - # Both c and cxx compiler support -rpath directly - hardcode_libdir_flag_spec='-rpath $libdir' - fi - archive_cmds_need_lc='no' - hardcode_libdir_separator=: - ;; - - solaris*) - no_undefined_flag=' -z defs' - if test "$GCC" = yes; then - wlarc='${wl}' - archive_cmds='$CC -shared ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -shared ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' - else - case `$CC -V 2>&1` in - *"Compilers 5.0"*) - wlarc='' - archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' - archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' - ;; - *) - wlarc='${wl}' - archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ - $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' - ;; - esac - fi - hardcode_libdir_flag_spec='-R$libdir' - hardcode_shlibpath_var=no - case $host_os in - solaris2.[0-5] | solaris2.[0-5].*) ;; - *) - # The compiler driver will combine and reorder linker options, - # but understands `-z linker_flag'. GCC discards it without `$wl', - # but is careful enough not to reorder. - # Supported since Solaris 2.6 (maybe 2.5.1?) - if test "$GCC" = yes; then - whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' - else - whole_archive_flag_spec='-z allextract$convenience -z defaultextract' - fi - ;; - esac - link_all_deplibs=yes - ;; - - sunos4*) - if test "x$host_vendor" = xsequent; then - # Use $CC to link under sequent, because it throws in some extra .o - # files that make .init and .fini sections work. - archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' - else - archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' - fi - hardcode_libdir_flag_spec='-L$libdir' - hardcode_direct=yes - hardcode_minus_L=yes - hardcode_shlibpath_var=no - ;; - - sysv4) - case $host_vendor in - sni) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_direct=yes # is this really true??? - ;; - siemens) - ## LD is ld it makes a PLAMLIB - ## CC just makes a GrossModule. - archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' - reload_cmds='$CC -r -o $output$reload_objs' - hardcode_direct=no - ;; - motorola) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_direct=no #Motorola manual says yes, but my tests say they lie - ;; - esac - runpath_var='LD_RUN_PATH' - hardcode_shlibpath_var=no - ;; - - sysv4.3*) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_shlibpath_var=no - export_dynamic_flag_spec='-Bexport' - ;; - - sysv4*MP*) - if test -d /usr/nec; then - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_shlibpath_var=no - runpath_var=LD_RUN_PATH - hardcode_runpath_var=yes - ld_shlibs=yes - fi - ;; - - sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) - no_undefined_flag='${wl}-z,text' - archive_cmds_need_lc=no - hardcode_shlibpath_var=no - runpath_var='LD_RUN_PATH' - - if test "$GCC" = yes; then - archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - else - archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - fi - ;; - - sysv5* | sco3.2v5* | sco5v6*) - # Note: We can NOT use -z defs as we might desire, because we do not - # link with -lc, and that would cause any symbols used from libc to - # always be unresolved, which means just about no library would - # ever link correctly. If we're not using GNU ld we use -z text - # though, which does catch some bad symbols but isn't as heavy-handed - # as -z defs. - no_undefined_flag='${wl}-z,text' - allow_undefined_flag='${wl}-z,nodefs' - archive_cmds_need_lc=no - hardcode_shlibpath_var=no - hardcode_libdir_flag_spec='${wl}-R,$libdir' - hardcode_libdir_separator=':' - link_all_deplibs=yes - export_dynamic_flag_spec='${wl}-Bexport' - runpath_var='LD_RUN_PATH' - - if test "$GCC" = yes; then - archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - else - archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' - fi - ;; - - uts4*) - archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' - hardcode_libdir_flag_spec='-L$libdir' - hardcode_shlibpath_var=no - ;; - - *) - ld_shlibs=no - ;; - esac - - if test x$host_vendor = xsni; then - case $host in - sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) - export_dynamic_flag_spec='${wl}-Blargedynsym' - ;; - esac - fi - fi - -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 -$as_echo "$ld_shlibs" >&6; } -test "$ld_shlibs" = no && can_build_shared=no - -with_gnu_ld=$with_gnu_ld - - - - - - - - - - - - - - - -# -# Do we need to explicitly link libc? -# -case "x$archive_cmds_need_lc" in -x|xyes) - # Assume -lc should be added - archive_cmds_need_lc=yes - - if test "$enable_shared" = yes && test "$GCC" = yes; then - case $archive_cmds in - *'~'*) - # FIXME: we may have to deal with multi-command sequences. - ;; - '$CC '*) - # Test whether the compiler implicitly links with -lc since on some - # systems, -lgcc has to come before -lc. If gcc already passes -lc - # to ld, don't add -lc before -lgcc. - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 -$as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } - $RM conftest* - echo "$lt_simple_compile_test_code" > conftest.$ac_ext - - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } 2>conftest.err; then - soname=conftest - lib=conftest - libobjs=conftest.$ac_objext - deplibs= - wl=$lt_prog_compiler_wl - pic_flag=$lt_prog_compiler_pic - compiler_flags=-v - linker_flags=-v - verstring= - output_objdir=. - libname=conftest - lt_save_allow_undefined_flag=$allow_undefined_flag - allow_undefined_flag= - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 - (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } - then - archive_cmds_need_lc=no - else - archive_cmds_need_lc=yes - fi - allow_undefined_flag=$lt_save_allow_undefined_flag - else - cat conftest.err 1>&5 - fi - $RM conftest* - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $archive_cmds_need_lc" >&5 -$as_echo "$archive_cmds_need_lc" >&6; } - ;; - esac - fi - ;; -esac - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 -$as_echo_n "checking dynamic linker characteristics... " >&6; } - -if test "$GCC" = yes; then - case $host_os in - darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; - *) lt_awk_arg="/^libraries:/" ;; - esac - lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e "s,=/,/,g"` - if $ECHO "$lt_search_path_spec" | $GREP ';' >/dev/null ; then - # if the path contains ";" then we assume it to be the separator - # otherwise default to the standard path separator (i.e. ":") - it is - # assumed that no part of a normal pathname contains ";" but that should - # okay in the real world where ";" in dirpaths is itself problematic. - lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e 's/;/ /g'` - else - lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` - fi - # Ok, now we have the path, separated by spaces, we can step through it - # and add multilib dir if necessary. - lt_tmp_lt_search_path_spec= - lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` - for lt_sys_path in $lt_search_path_spec; do - if test -d "$lt_sys_path/$lt_multi_os_dir"; then - lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" - else - test -d "$lt_sys_path" && \ - lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" - fi - done - lt_search_path_spec=`$ECHO $lt_tmp_lt_search_path_spec | awk ' -BEGIN {RS=" "; FS="/|\n";} { - lt_foo=""; - lt_count=0; - for (lt_i = NF; lt_i > 0; lt_i--) { - if ($lt_i != "" && $lt_i != ".") { - if ($lt_i == "..") { - lt_count++; - } else { - if (lt_count == 0) { - lt_foo="/" $lt_i lt_foo; - } else { - lt_count--; - } - } - } - } - if (lt_foo != "") { lt_freq[lt_foo]++; } - if (lt_freq[lt_foo] == 1) { print lt_foo; } -}'` - sys_lib_search_path_spec=`$ECHO $lt_search_path_spec` -else - sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" -fi -library_names_spec= -libname_spec='lib$name' -soname_spec= -shrext_cmds=".so" -postinstall_cmds= -postuninstall_cmds= -finish_cmds= -finish_eval= -shlibpath_var= -shlibpath_overrides_runpath=unknown -version_type=none -dynamic_linker="$host_os ld.so" -sys_lib_dlsearch_path_spec="/lib /usr/lib" -need_lib_prefix=unknown -hardcode_into_libs=no - -# when you set need_version to no, make sure it does not cause -set_version -# flags to be left without arguments -need_version=unknown - -case $host_os in -aix3*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' - shlibpath_var=LIBPATH - - # AIX 3 has no versioning support, so we append a major version to the name. - soname_spec='${libname}${release}${shared_ext}$major' - ;; - -aix[4-9]*) - version_type=linux - need_lib_prefix=no - need_version=no - hardcode_into_libs=yes - if test "$host_cpu" = ia64; then - # AIX 5 supports IA64 - library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - else - # With GCC up to 2.95.x, collect2 would create an import file - # for dependence libraries. The import file would start with - # the line `#! .'. This would cause the generated library to - # depend on `.', always an invalid library. This was fixed in - # development snapshots of GCC prior to 3.0. - case $host_os in - aix4 | aix4.[01] | aix4.[01].*) - if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' - echo ' yes ' - echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then - : - else - can_build_shared=no - fi - ;; - esac - # AIX (on Power*) has no versioning support, so currently we can not hardcode correct - # soname into executable. Probably we can add versioning support to - # collect2, so additional links can be useful in future. - if test "$aix_use_runtimelinking" = yes; then - # If using run time linking (on AIX 4.2 or later) use lib.so - # instead of lib.a to let people know that these are not - # typical AIX shared libraries. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - else - # We preserve .a as extension for shared libraries through AIX4.2 - # and later when we are not doing run time linking. - library_names_spec='${libname}${release}.a $libname.a' - soname_spec='${libname}${release}${shared_ext}$major' - fi - shlibpath_var=LIBPATH - fi - ;; - -amigaos*) - case $host_cpu in - powerpc) - # Since July 2007 AmigaOS4 officially supports .so libraries. - # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - ;; - m68k) - library_names_spec='$libname.ixlibrary $libname.a' - # Create ${libname}_ixlibrary.a entries in /sys/libs. - finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`$ECHO "X$lib" | $Xsed -e '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' - ;; - esac - ;; - -beos*) - library_names_spec='${libname}${shared_ext}' - dynamic_linker="$host_os ld.so" - shlibpath_var=LIBRARY_PATH - ;; - -bsdi[45]*) - version_type=linux - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' - shlibpath_var=LD_LIBRARY_PATH - sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" - sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" - # the default ld.so.conf also contains /usr/contrib/lib and - # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow - # libtool to hard-code these into programs - ;; - -cygwin* | mingw* | pw32*) - version_type=windows - shrext_cmds=".dll" - need_version=no - need_lib_prefix=no - - case $GCC,$host_os in - yes,cygwin* | yes,mingw* | yes,pw32*) - library_names_spec='$libname.dll.a' - # DLL is installed to $(libdir)/../bin by postinstall_cmds - postinstall_cmds='base_file=`basename \${file}`~ - dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ - dldir=$destdir/`dirname \$dlpath`~ - test -d \$dldir || mkdir -p \$dldir~ - $install_prog $dir/$dlname \$dldir/$dlname~ - chmod a+x \$dldir/$dlname~ - if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then - eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; - fi' - postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ - dlpath=$dir/\$dldll~ - $RM \$dlpath' - shlibpath_overrides_runpath=yes - - case $host_os in - cygwin*) - # Cygwin DLLs use 'cyg' prefix rather than 'lib' - soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' - sys_lib_search_path_spec="/usr/lib /lib/w32api /lib /usr/local/lib" - ;; - mingw*) - # MinGW DLLs use traditional 'lib' prefix - soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' - sys_lib_search_path_spec=`$CC -print-search-dirs | $GREP "^libraries:" | $SED -e "s/^libraries://" -e "s,=/,/,g"` - if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then - # It is most probably a Windows format PATH printed by - # mingw gcc, but we are running on Cygwin. Gcc prints its search - # path with ; separators, and with drive letters. We can handle the - # drive letters (cygwin fileutils understands them), so leave them, - # especially as we might pass files found there to a mingw objdump, - # which wouldn't understand a cygwinified path. Ahh. - sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` - else - sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` - fi - ;; - pw32*) - # pw32 DLLs use 'pw' prefix rather than 'lib' - library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' - ;; - esac - ;; - - *) - library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' - ;; - esac - dynamic_linker='Win32 ld.exe' - # FIXME: first we should search . and the directory the executable is in - shlibpath_var=PATH - ;; - -darwin* | rhapsody*) - dynamic_linker="$host_os dyld" - version_type=darwin - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' - soname_spec='${libname}${release}${major}$shared_ext' - shlibpath_overrides_runpath=yes - shlibpath_var=DYLD_LIBRARY_PATH - shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' - - sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" - sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' - ;; - -dgux*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - ;; - -freebsd1*) - dynamic_linker=no - ;; - -freebsd* | dragonfly*) - # DragonFly does not have aout. When/if they implement a new - # versioning mechanism, adjust this. - if test -x /usr/bin/objformat; then - objformat=`/usr/bin/objformat` - else - case $host_os in - freebsd[123]*) objformat=aout ;; - *) objformat=elf ;; - esac - fi - version_type=freebsd-$objformat - case $version_type in - freebsd-elf*) - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' - need_version=no - need_lib_prefix=no - ;; - freebsd-*) - library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' - need_version=yes - ;; - esac - shlibpath_var=LD_LIBRARY_PATH - case $host_os in - freebsd2*) - shlibpath_overrides_runpath=yes - ;; - freebsd3.[01]* | freebsdelf3.[01]*) - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ - freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - *) # from 4.6 on, and DragonFly - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - esac - ;; - -gnu*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - hardcode_into_libs=yes - ;; - -hpux9* | hpux10* | hpux11*) - # Give a soname corresponding to the major version so that dld.sl refuses to - # link against other versions. - version_type=sunos - need_lib_prefix=no - need_version=no - case $host_cpu in - ia64*) - shrext_cmds='.so' - hardcode_into_libs=yes - dynamic_linker="$host_os dld.so" - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - if test "X$HPUX_IA64_MODE" = X32; then - sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" - else - sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" - fi - sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec - ;; - hppa*64*) - shrext_cmds='.sl' - hardcode_into_libs=yes - dynamic_linker="$host_os dld.sl" - shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH - shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" - sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec - ;; - *) - shrext_cmds='.sl' - dynamic_linker="$host_os dld.sl" - shlibpath_var=SHLIB_PATH - shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - ;; - esac - # HP-UX runs *really* slowly unless shared libraries are mode 555. - postinstall_cmds='chmod 555 $lib' - ;; - -interix[3-9]*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - -irix5* | irix6* | nonstopux*) - case $host_os in - nonstopux*) version_type=nonstopux ;; - *) - if test "$lt_cv_prog_gnu_ld" = yes; then - version_type=linux - else - version_type=irix - fi ;; - esac - need_lib_prefix=no - need_version=no - soname_spec='${libname}${release}${shared_ext}$major' - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' - case $host_os in - irix5* | nonstopux*) - libsuff= shlibsuff= - ;; - *) - case $LD in # libtool.m4 will add one of these switches to LD - *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") - libsuff= shlibsuff= libmagic=32-bit;; - *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") - libsuff=32 shlibsuff=N32 libmagic=N32;; - *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") - libsuff=64 shlibsuff=64 libmagic=64-bit;; - *) libsuff= shlibsuff= libmagic=never-match;; - esac - ;; - esac - shlibpath_var=LD_LIBRARY${shlibsuff}_PATH - shlibpath_overrides_runpath=no - sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" - sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" - hardcode_into_libs=yes - ;; - -# No shared lib support for Linux oldld, aout, or coff. -linux*oldld* | linux*aout* | linux*coff*) - dynamic_linker=no - ;; - -# This must be Linux ELF. -linux* | k*bsd*-gnu) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - # Some binutils ld are patched to set DT_RUNPATH - save_LDFLAGS=$LDFLAGS - save_libdir=$libdir - eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ - LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : - shlibpath_overrides_runpath=yes -fi -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - LDFLAGS=$save_LDFLAGS - libdir=$save_libdir - - # This implies no fast_install, which is unacceptable. - # Some rework will be needed to allow for fast_install - # before this can be enabled. - hardcode_into_libs=yes - - # Append ld.so.conf contents to the search path - if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" - fi - - # We used to test for /lib/ld.so.1 and disable shared libraries on - # powerpc, because MkLinux only supported shared libraries with the - # GNU dynamic linker. Since this was broken with cross compilers, - # most powerpc-linux boxes support dynamic linking these days and - # people can always --disable-shared, the test was removed, and we - # assume the GNU/Linux dynamic linker is in use. - dynamic_linker='GNU/Linux ld.so' - ;; - -netbsd*) - version_type=sunos - need_lib_prefix=no - need_version=no - if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' - dynamic_linker='NetBSD (a.out) ld.so' - else - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - dynamic_linker='NetBSD ld.elf_so' - fi - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - ;; - -newsos6) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - ;; - -*nto* | *qnx*) - version_type=qnx - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - dynamic_linker='ldqnx.so' - ;; - -openbsd*) - version_type=sunos - sys_lib_dlsearch_path_spec="/usr/lib" - need_lib_prefix=no - # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. - case $host_os in - openbsd3.3 | openbsd3.3.*) need_version=yes ;; - *) need_version=no ;; - esac - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' - shlibpath_var=LD_LIBRARY_PATH - if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then - case $host_os in - openbsd2.[89] | openbsd2.[89].*) - shlibpath_overrides_runpath=no - ;; - *) - shlibpath_overrides_runpath=yes - ;; - esac - else - shlibpath_overrides_runpath=yes - fi - ;; - -os2*) - libname_spec='$name' - shrext_cmds=".dll" - need_lib_prefix=no - library_names_spec='$libname${shared_ext} $libname.a' - dynamic_linker='OS/2 ld.exe' - shlibpath_var=LIBPATH - ;; - -osf3* | osf4* | osf5*) - version_type=osf - need_lib_prefix=no - need_version=no - soname_spec='${libname}${release}${shared_ext}$major' - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" - sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" - ;; - -rdos*) - dynamic_linker=no - ;; - -solaris*) - version_type=linux - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - # ldd complains unless libraries are executable - postinstall_cmds='chmod +x $lib' - ;; - -sunos4*) - version_type=sunos - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' - finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - if test "$with_gnu_ld" = yes; then - need_lib_prefix=no - fi - need_version=yes - ;; - -sysv4 | sysv4.3*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - case $host_vendor in - sni) - shlibpath_overrides_runpath=no - need_lib_prefix=no - runpath_var=LD_RUN_PATH - ;; - siemens) - need_lib_prefix=no - ;; - motorola) - need_lib_prefix=no - need_version=no - shlibpath_overrides_runpath=no - sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' - ;; - esac - ;; - -sysv4*MP*) - if test -d /usr/nec ;then - version_type=linux - library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' - soname_spec='$libname${shared_ext}.$major' - shlibpath_var=LD_LIBRARY_PATH - fi - ;; - -sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) - version_type=freebsd-elf - need_lib_prefix=no - need_version=no - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - if test "$with_gnu_ld" = yes; then - sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' - else - sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' - case $host_os in - sco3.2v5*) - sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" - ;; - esac - fi - sys_lib_dlsearch_path_spec='/usr/lib' - ;; - -tpf*) - # TPF is a cross-target only. Preferred cross-host = GNU/Linux. - version_type=linux - need_lib_prefix=no - need_version=no - library_name_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; - -uts4*) - version_type=linux - library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' - soname_spec='${libname}${release}${shared_ext}$major' - shlibpath_var=LD_LIBRARY_PATH - ;; - -*) - dynamic_linker=no - ;; -esac -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 -$as_echo "$dynamic_linker" >&6; } -test "$dynamic_linker" = no && can_build_shared=no - -variables_saved_for_relink="PATH $shlibpath_var $runpath_var" -if test "$GCC" = yes; then - variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" -fi - -if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then - sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" -fi -if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then - sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" -fi - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 -$as_echo_n "checking how to hardcode library paths into programs... " >&6; } -hardcode_action= -if test -n "$hardcode_libdir_flag_spec" || - test -n "$runpath_var" || - test "X$hardcode_automatic" = "Xyes" ; then - - # We can hardcode non-existent directories. - if test "$hardcode_direct" != no && - # If the only mechanism to avoid hardcoding is shlibpath_var, we - # have to relink, otherwise we might link with an installed library - # when we should be linking with a yet-to-be-installed one - ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && - test "$hardcode_minus_L" != no; then - # Linking always hardcodes the temporary library directory. - hardcode_action=relink - else - # We can link without hardcoding, and we can hardcode nonexisting dirs. - hardcode_action=immediate - fi -else - # We cannot hardcode anything, or else we can only hardcode existing - # directories. - hardcode_action=unsupported -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 -$as_echo "$hardcode_action" >&6; } - -if test "$hardcode_action" = relink || - test "$inherit_rpath" = yes; then - # Fast installation is not supported - enable_fast_install=no -elif test "$shlibpath_overrides_runpath" = yes || - test "$enable_shared" = no; then - # Fast installation is not necessary - enable_fast_install=needless -fi - - - - - - - if test "x$enable_dlopen" != xyes; then - enable_dlopen=unknown - enable_dlopen_self=unknown - enable_dlopen_self_static=unknown -else - lt_cv_dlopen=no - lt_cv_dlopen_libs= - - case $host_os in - beos*) - lt_cv_dlopen="load_add_on" - lt_cv_dlopen_libs= - lt_cv_dlopen_self=yes - ;; - - mingw* | pw32*) - lt_cv_dlopen="LoadLibrary" - lt_cv_dlopen_libs= - ;; - - cygwin*) - lt_cv_dlopen="dlopen" - lt_cv_dlopen_libs= - ;; - - darwin*) - # if libdl is installed we need to link against it - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 -$as_echo_n "checking for dlopen in -ldl... " >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldl $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_dl_dlopen=yes -else - ac_cv_lib_dl_dlopen=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 -$as_echo "$ac_cv_lib_dl_dlopen" >&6; } -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : - lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" -else - - lt_cv_dlopen="dyld" - lt_cv_dlopen_libs= - lt_cv_dlopen_self=yes - -fi - - ;; - - *) - ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" -if test "x$ac_cv_func_shl_load" = x""yes; then : - lt_cv_dlopen="shl_load" -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 -$as_echo_n "checking for shl_load in -ldld... " >&6; } -if test "${ac_cv_lib_dld_shl_load+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldld $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char shl_load (); -int -main () -{ -return shl_load (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_dld_shl_load=yes -else - ac_cv_lib_dld_shl_load=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 -$as_echo "$ac_cv_lib_dld_shl_load" >&6; } -if test "x$ac_cv_lib_dld_shl_load" = x""yes; then : - lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" -else - ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" -if test "x$ac_cv_func_dlopen" = x""yes; then : - lt_cv_dlopen="dlopen" -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 -$as_echo_n "checking for dlopen in -ldl... " >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldl $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_dl_dlopen=yes -else - ac_cv_lib_dl_dlopen=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 -$as_echo "$ac_cv_lib_dl_dlopen" >&6; } -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : - lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 -$as_echo_n "checking for dlopen in -lsvld... " >&6; } -if test "${ac_cv_lib_svld_dlopen+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lsvld $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dlopen (); -int -main () -{ -return dlopen (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_svld_dlopen=yes -else - ac_cv_lib_svld_dlopen=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 -$as_echo "$ac_cv_lib_svld_dlopen" >&6; } -if test "x$ac_cv_lib_svld_dlopen" = x""yes; then : - lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 -$as_echo_n "checking for dld_link in -ldld... " >&6; } -if test "${ac_cv_lib_dld_dld_link+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-ldld $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char dld_link (); -int -main () -{ -return dld_link (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_dld_dld_link=yes -else - ac_cv_lib_dld_dld_link=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 -$as_echo "$ac_cv_lib_dld_dld_link" >&6; } -if test "x$ac_cv_lib_dld_dld_link" = x""yes; then : - lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" -fi - - -fi - - -fi - - -fi - - -fi - - -fi - - ;; - esac - - if test "x$lt_cv_dlopen" != xno; then - enable_dlopen=yes - else - enable_dlopen=no - fi - - case $lt_cv_dlopen in - dlopen) - save_CPPFLAGS="$CPPFLAGS" - test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" - - save_LDFLAGS="$LDFLAGS" - wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" - - save_LIBS="$LIBS" - LIBS="$lt_cv_dlopen_libs $LIBS" - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 -$as_echo_n "checking whether a program can dlopen itself... " >&6; } -if test "${lt_cv_dlopen_self+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - lt_cv_dlopen_self=cross -else - lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 - lt_status=$lt_dlunknown - cat > conftest.$ac_ext <<_LT_EOF -#line 10572 "configure" -#include "confdefs.h" - -#if HAVE_DLFCN_H -#include -#endif - -#include - -#ifdef RTLD_GLOBAL -# define LT_DLGLOBAL RTLD_GLOBAL -#else -# ifdef DL_GLOBAL -# define LT_DLGLOBAL DL_GLOBAL -# else -# define LT_DLGLOBAL 0 -# endif -#endif - -/* We may have to define LT_DLLAZY_OR_NOW in the command line if we - find out it does not work in some platform. */ -#ifndef LT_DLLAZY_OR_NOW -# ifdef RTLD_LAZY -# define LT_DLLAZY_OR_NOW RTLD_LAZY -# else -# ifdef DL_LAZY -# define LT_DLLAZY_OR_NOW DL_LAZY -# else -# ifdef RTLD_NOW -# define LT_DLLAZY_OR_NOW RTLD_NOW -# else -# ifdef DL_NOW -# define LT_DLLAZY_OR_NOW DL_NOW -# else -# define LT_DLLAZY_OR_NOW 0 -# endif -# endif -# endif -# endif -#endif - -#ifdef __cplusplus -extern "C" void exit (int); -#endif - -void fnord() { int i=42;} -int main () -{ - void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); - int status = $lt_dlunknown; - - if (self) - { - if (dlsym (self,"fnord")) status = $lt_dlno_uscore; - else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; - /* dlclose (self); */ - } - else - puts (dlerror ()); - - exit (status); -} -_LT_EOF - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 - (eval $ac_link) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then - (./conftest; exit; ) >&5 2>/dev/null - lt_status=$? - case x$lt_status in - x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; - x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; - x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; - esac - else : - # compilation failed - lt_cv_dlopen_self=no - fi -fi -rm -fr conftest* - - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 -$as_echo "$lt_cv_dlopen_self" >&6; } - - if test "x$lt_cv_dlopen_self" = xyes; then - wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 -$as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } -if test "${lt_cv_dlopen_self_static+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - lt_cv_dlopen_self_static=cross -else - lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 - lt_status=$lt_dlunknown - cat > conftest.$ac_ext <<_LT_EOF -#line 10672 "configure" -#include "confdefs.h" - -#if HAVE_DLFCN_H -#include -#endif - -#include - -#ifdef RTLD_GLOBAL -# define LT_DLGLOBAL RTLD_GLOBAL -#else -# ifdef DL_GLOBAL -# define LT_DLGLOBAL DL_GLOBAL -# else -# define LT_DLGLOBAL 0 -# endif -#endif - -/* We may have to define LT_DLLAZY_OR_NOW in the command line if we - find out it does not work in some platform. */ -#ifndef LT_DLLAZY_OR_NOW -# ifdef RTLD_LAZY -# define LT_DLLAZY_OR_NOW RTLD_LAZY -# else -# ifdef DL_LAZY -# define LT_DLLAZY_OR_NOW DL_LAZY -# else -# ifdef RTLD_NOW -# define LT_DLLAZY_OR_NOW RTLD_NOW -# else -# ifdef DL_NOW -# define LT_DLLAZY_OR_NOW DL_NOW -# else -# define LT_DLLAZY_OR_NOW 0 -# endif -# endif -# endif -# endif -#endif - -#ifdef __cplusplus -extern "C" void exit (int); -#endif - -void fnord() { int i=42;} -int main () -{ - void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); - int status = $lt_dlunknown; - - if (self) - { - if (dlsym (self,"fnord")) status = $lt_dlno_uscore; - else if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; - /* dlclose (self); */ - } - else - puts (dlerror ()); - - exit (status); -} -_LT_EOF - if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 - (eval $ac_link) 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then - (./conftest; exit; ) >&5 2>/dev/null - lt_status=$? - case x$lt_status in - x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; - x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; - x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; - esac - else : - # compilation failed - lt_cv_dlopen_self_static=no - fi -fi -rm -fr conftest* - - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 -$as_echo "$lt_cv_dlopen_self_static" >&6; } - fi - - CPPFLAGS="$save_CPPFLAGS" - LDFLAGS="$save_LDFLAGS" - LIBS="$save_LIBS" - ;; - esac - - case $lt_cv_dlopen_self in - yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; - *) enable_dlopen_self=unknown ;; - esac - - case $lt_cv_dlopen_self_static in - yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; - *) enable_dlopen_self_static=unknown ;; - esac -fi - - - - - - - - - - - - - - - - - -striplib= -old_striplib= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 -$as_echo_n "checking whether stripping libraries is possible... " >&6; } -if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then - test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" - test -z "$striplib" && striplib="$STRIP --strip-unneeded" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -else -# FIXME - insert some real tests, host_os isn't really good enough - case $host_os in - darwin*) - if test -n "$STRIP" ; then - striplib="$STRIP -x" - old_striplib="$STRIP -S" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - fi - ;; - *) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - ;; - esac -fi - - - - - - - - - - - - - # Report which library types will actually be built - { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 -$as_echo_n "checking if libtool supports shared libraries... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 -$as_echo "$can_build_shared" >&6; } - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 -$as_echo_n "checking whether to build shared libraries... " >&6; } - test "$can_build_shared" = "no" && enable_shared=no - - # On AIX, shared libraries and static libraries use the same namespace, and - # are all built from PIC. - case $host_os in - aix3*) - test "$enable_shared" = yes && enable_static=no - if test -n "$RANLIB"; then - archive_cmds="$archive_cmds~\$RANLIB \$lib" - postinstall_cmds='$RANLIB $lib' - fi - ;; - - aix[4-9]*) - if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then - test "$enable_shared" = yes && enable_static=no - fi - ;; - esac - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 -$as_echo "$enable_shared" >&6; } - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 -$as_echo_n "checking whether to build static libraries... " >&6; } - # Make sure either enable_shared or enable_static is yes. - test "$enable_shared" = yes || enable_static=yes - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 -$as_echo "$enable_static" >&6; } - - - - -fi -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -CC="$lt_save_CC" - - - - - - - - - - - - - - ac_config_commands="$ac_config_commands libtool" - - - - -# Only expand once: - - - - -# Check whether --enable-largefile was given. -if test "${enable_largefile+set}" = set; then : - enableval=$enable_largefile; -fi - -if test "$enable_largefile" != no; then - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5 -$as_echo_n "checking for special C compiler options needed for large files... " >&6; } -if test "${ac_cv_sys_largefile_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_cv_sys_largefile_CC=no - if test "$GCC" != yes; then - ac_save_CC=$CC - while :; do - # IRIX 6.2 and later do not support large files by default, - # so use the C compiler's -n32 option if that helps. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - /* Check that off_t can represent 2**63 - 1 correctly. - We can't simply define LARGE_OFF_T to be 9223372036854775807, - since some C++ compilers masquerading as C compilers - incorrectly reject 9223372036854775807. */ -#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) - int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 - && LARGE_OFF_T % 2147483647 == 1) - ? 1 : -1]; -int -main () -{ - - ; - return 0; -} -_ACEOF - if ac_fn_c_try_compile "$LINENO"; then : - break -fi -rm -f core conftest.err conftest.$ac_objext - CC="$CC -n32" - if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_sys_largefile_CC=' -n32'; break -fi -rm -f core conftest.err conftest.$ac_objext - break - done - CC=$ac_save_CC - rm -f conftest.$ac_ext - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5 -$as_echo "$ac_cv_sys_largefile_CC" >&6; } - if test "$ac_cv_sys_largefile_CC" != no; then - CC=$CC$ac_cv_sys_largefile_CC - fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5 -$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; } -if test "${ac_cv_sys_file_offset_bits+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - while :; do - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - /* Check that off_t can represent 2**63 - 1 correctly. - We can't simply define LARGE_OFF_T to be 9223372036854775807, - since some C++ compilers masquerading as C compilers - incorrectly reject 9223372036854775807. */ -#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) - int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 - && LARGE_OFF_T % 2147483647 == 1) - ? 1 : -1]; -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_sys_file_offset_bits=no; break -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#define _FILE_OFFSET_BITS 64 -#include - /* Check that off_t can represent 2**63 - 1 correctly. - We can't simply define LARGE_OFF_T to be 9223372036854775807, - since some C++ compilers masquerading as C compilers - incorrectly reject 9223372036854775807. */ -#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) - int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 - && LARGE_OFF_T % 2147483647 == 1) - ? 1 : -1]; -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_sys_file_offset_bits=64; break -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_cv_sys_file_offset_bits=unknown - break -done -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5 -$as_echo "$ac_cv_sys_file_offset_bits" >&6; } -case $ac_cv_sys_file_offset_bits in #( - no | unknown) ;; - *) -cat >>confdefs.h <<_ACEOF -#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits -_ACEOF -;; -esac -rm -rf conftest* - if test $ac_cv_sys_file_offset_bits = unknown; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5 -$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; } -if test "${ac_cv_sys_large_files+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - while :; do - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - /* Check that off_t can represent 2**63 - 1 correctly. - We can't simply define LARGE_OFF_T to be 9223372036854775807, - since some C++ compilers masquerading as C compilers - incorrectly reject 9223372036854775807. */ -#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) - int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 - && LARGE_OFF_T % 2147483647 == 1) - ? 1 : -1]; -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_sys_large_files=no; break -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#define _LARGE_FILES 1 -#include - /* Check that off_t can represent 2**63 - 1 correctly. - We can't simply define LARGE_OFF_T to be 9223372036854775807, - since some C++ compilers masquerading as C compilers - incorrectly reject 9223372036854775807. */ -#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) - int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 - && LARGE_OFF_T % 2147483647 == 1) - ? 1 : -1]; -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_sys_large_files=1; break -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_cv_sys_large_files=unknown - break -done -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5 -$as_echo "$ac_cv_sys_large_files" >&6; } -case $ac_cv_sys_large_files in #( - no | unknown) ;; - *) -cat >>confdefs.h <<_ACEOF -#define _LARGE_FILES $ac_cv_sys_large_files -_ACEOF -;; -esac -rm -rf conftest* - fi -fi - - -backtrace_supported=yes - -if test -n "${with_target_subdir}"; then - # We are compiling a GCC library. We can assume that the unwind - # library exists. - BACKTRACE_FILE="backtrace.lo simple.lo" -else - ac_fn_c_check_header_mongrel "$LINENO" "unwind.h" "ac_cv_header_unwind_h" "$ac_includes_default" -if test "x$ac_cv_header_unwind_h" = x""yes; then : - ac_fn_c_check_func "$LINENO" "_Unwind_Backtrace" "ac_cv_func__Unwind_Backtrace" -if test "x$ac_cv_func__Unwind_Backtrace" = x""yes; then : - BACKTRACE_FILE="backtrace.lo simple.lo" -else - BACKTRACE_FILE="nounwind.lo" - backtrace_supported=no -fi - -else - BACKTRACE_FILE="nounwind.lo" - backtrace_supported=no -fi - - -fi - - -EXTRA_FLAGS= -if test -n "${with_target_subdir}"; then - EXTRA_FLAGS="-funwind-tables -frandom-seed=\$@" -else - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -funwind-tables option" >&5 -$as_echo_n "checking for -funwind-tables option... " >&6; } -if test "${libbacktrace_cv_c_unwind_tables+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - CFLAGS_hold="$CFLAGS" - CFLAGS="$CFLAGS -funwind-tables" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -static int f() { return 0; } -int -main () -{ -return f(); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - libbacktrace_cv_c_unwind_tables=yes -else - libbacktrace_cv_c_unwind_tables=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS="$CFLAGS_hold" -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_c_unwind_tables" >&5 -$as_echo "$libbacktrace_cv_c_unwind_tables" >&6; } - if test "$libbacktrace_cv_c_unwind_tables" = "yes"; then - EXTRA_FLAGS=-funwind-tables - fi - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -frandom-seed=string option" >&5 -$as_echo_n "checking for -frandom-seed=string option... " >&6; } -if test "${libbacktrace_cv_c_random_seed_string+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - CFLAGS_hold="$CFLAGS" - CFLAGS="$CFLAGS -frandom-seed=conftest.lo" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -return 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - libbacktrace_cv_c_random_seed_string=yes -else - libbacktrace_cv_c_random_seed_string=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - CFLAGS="$CFLAGS_hold" -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_c_random_seed_string" >&5 -$as_echo "$libbacktrace_cv_c_random_seed_string" >&6; } - if test "$libbacktrace_cv_c_random_seed_string" = "yes"; then - EXTRA_FLAGS="$EXTRA_FLAGS -frandom-seed=\$@" - fi -fi - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -WARN_FLAGS= -save_CFLAGS="$CFLAGS" -for real_option in -W -Wall -Wwrite-strings -Wstrict-prototypes \ - -Wmissing-prototypes -Wold-style-definition \ - -Wmissing-format-attribute -Wcast-qual; do - # Do the check with the no- prefix removed since gcc silently - # accepts any -Wno-* option on purpose - case $real_option in - -Wno-*) option=-W`expr x$real_option : 'x-Wno-\(.*\)'` ;; - *) option=$real_option ;; - esac - as_acx_Woption=`$as_echo "acx_cv_prog_cc_warning_$option" | $as_tr_sh` - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC supports $option" >&5 -$as_echo_n "checking whether $CC supports $option... " >&6; } -if { as_var=$as_acx_Woption; eval "test \"\${$as_var+set}\" = set"; }; then : - $as_echo_n "(cached) " >&6 -else - CFLAGS="$option" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - eval "$as_acx_Woption=yes" -else - eval "$as_acx_Woption=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -fi -eval ac_res=\$$as_acx_Woption - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - if test `eval 'as_val=${'$as_acx_Woption'};$as_echo "$as_val"'` = yes; then : - WARN_FLAGS="$WARN_FLAGS${WARN_FLAGS:+ }$real_option" -fi - done -CFLAGS="$save_CFLAGS" -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -if test -n "${with_target_subdir}"; then - WARN_FLAGS="$WARN_FLAGS -Werror" -fi - - - -if test -n "${with_target_subdir}"; then - - -# Check whether --with-system-libunwind was given. -if test "${with_system_libunwind+set}" = set; then : - withval=$with_system_libunwind; -fi - - # If system-libunwind was not specifically set, pick a default setting. - if test x$with_system_libunwind = x; then - case ${target} in - ia64-*-hpux*) with_system_libunwind=yes ;; - *) with_system_libunwind=no ;; - esac - fi - # Based on system-libunwind and target, do we have ipinfo? - if test x$with_system_libunwind = xyes; then - case ${target} in - ia64-*-*) have_unwind_getipinfo=no ;; - *) have_unwind_getipinfo=yes ;; - esac - else - # Darwin before version 9 does not have _Unwind_GetIPInfo. - - case ${target} in - *-*-darwin[3-8]|*-*-darwin[3-8].*) have_unwind_getipinfo=no ;; - *) have_unwind_getipinfo=yes ;; - esac - - fi - - if test x$have_unwind_getipinfo = xyes; then - -$as_echo "#define HAVE_GETIPINFO 1" >>confdefs.h - - fi - -else - ac_save_CFFLAGS="$CFLAGS" - CFLAGS="$CFLAGS -Werror-implicit-function-declaration" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _Unwind_GetIPInfo" >&5 -$as_echo_n "checking for _Unwind_GetIPInfo... " >&6; } - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include "unwind.h" - struct _Unwind_Context *context; - int ip_before_insn = 0; -int -main () -{ -return _Unwind_GetIPInfo (context, &ip_before_insn); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - have_unwind_getipinfo=yes -else - have_unwind_getipinfo=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - CFLAGS="$ac_save_CFLAGS" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_unwind_getipinfo" >&5 -$as_echo "$have_unwind_getipinfo" >&6; } - if test "$have_unwind_getipinfo" = "yes"; then - -$as_echo "#define HAVE_GETIPINFO 1" >>confdefs.h - - fi -fi - -# Enable --enable-host-shared. -# Check whether --enable-host-shared was given. -if test "${enable_host_shared+set}" = set; then : - enableval=$enable_host_shared; PIC_FLAG=-fPIC -else - PIC_FLAG= -fi - - - -# Test for __sync support. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking __sync extensions" >&5 -$as_echo_n "checking __sync extensions... " >&6; } -if test "${libbacktrace_cv_sys_sync+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "${with_target_subdir}"; then - case "${host}" in - hppa*-*-hpux*) libbacktrace_cv_sys_sync=no ;; - *) libbacktrace_cv_sys_sync=yes ;; - esac - else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -int i; -int -main () -{ -__sync_bool_compare_and_swap (&i, i, i); - __sync_lock_test_and_set (&i, 1); - __sync_lock_release (&i); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - libbacktrace_cv_sys_sync=yes -else - libbacktrace_cv_sys_sync=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_sys_sync" >&5 -$as_echo "$libbacktrace_cv_sys_sync" >&6; } -BACKTRACE_SUPPORTS_THREADS=0 -if test "$libbacktrace_cv_sys_sync" = "yes"; then - BACKTRACE_SUPPORTS_THREADS=1 - -$as_echo "#define HAVE_SYNC_FUNCTIONS 1" >>confdefs.h - -fi - - -# Test for __atomic support. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking __atomic extensions" >&5 -$as_echo_n "checking __atomic extensions... " >&6; } -if test "${libbacktrace_cv_sys_atomic+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "${with_target_subdir}"; then - libbacktrace_cv_sys_atomic=yes - else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -int i; -int -main () -{ -__atomic_load_n (&i, __ATOMIC_ACQUIRE); - __atomic_store_n (&i, 1, __ATOMIC_RELEASE); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - libbacktrace_cv_sys_atomic=yes -else - libbacktrace_cv_sys_atomic=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_sys_atomic" >&5 -$as_echo "$libbacktrace_cv_sys_atomic" >&6; } -if test "$libbacktrace_cv_sys_atomic" = "yes"; then - -$as_echo "#define HAVE_ATOMIC_FUNCTIONS 1" >>confdefs.h - -fi - -# The library needs to be able to read the executable itself. Compile -# a file to determine the executable format. The awk script -# filetype.awk prints out the file type. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking output filetype" >&5 -$as_echo_n "checking output filetype... " >&6; } -if test "${libbacktrace_cv_sys_filetype+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - filetype= -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -int i; -int -main () -{ -int j; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - filetype=`${AWK} -f $srcdir/filetype.awk conftest.$ac_objext` -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "compiler failed -See \`config.log' for more details." "$LINENO" 5; } -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -libbacktrace_cv_sys_filetype=$filetype -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_sys_filetype" >&5 -$as_echo "$libbacktrace_cv_sys_filetype" >&6; } - -# Match the file type to decide what files to compile. -FORMAT_FILE= -backtrace_supports_data=yes -case "$libbacktrace_cv_sys_filetype" in -elf*) FORMAT_FILE="elf.lo" ;; -pecoff) FORMAT_FILE="pecoff.lo" - backtrace_supports_data=no - ;; -xcoff*) FORMAT_FILE="xcoff.lo" - backtrace_supports_data=no - ;; -macho*) FORMAT_FILE="macho.lo" - backtrace_supports_data=no - ;; -*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: could not determine output file type" >&5 -$as_echo "$as_me: WARNING: could not determine output file type" >&2;} - FORMAT_FILE="unknown.lo" - backtrace_supported=no - ;; -esac - - -# ELF defines. -elfsize= -case "$libbacktrace_cv_sys_filetype" in -elf32) elfsize=32 ;; -elf64) elfsize=64 ;; -*) elfsize=unused -esac - -cat >>confdefs.h <<_ACEOF -#define BACKTRACE_ELF_SIZE $elfsize -_ACEOF - - -# XCOFF defines. -xcoffsize= -case "$libbacktrace_cv_sys_filetype" in -xcoff32) xcoffsize=32 ;; -xcoff64) xcoffsize=64 ;; -*) xcoffsize=unused -esac - -cat >>confdefs.h <<_ACEOF -#define BACKTRACE_XCOFF_SIZE $xcoffsize -_ACEOF - - -BACKTRACE_SUPPORTED=0 -if test "$backtrace_supported" = "yes"; then - BACKTRACE_SUPPORTED=1 -fi - - -BACKTRACE_SUPPORTS_DATA=0 -if test "$backtrace_supports_data" = "yes"; then - BACKTRACE_SUPPORTS_DATA=1 -fi - - -for ac_header in sys/mman.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "sys/mman.h" "ac_cv_header_sys_mman_h" "$ac_includes_default" -if test "x$ac_cv_header_sys_mman_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_SYS_MMAN_H 1 -_ACEOF - -fi - -done - -if test "$ac_cv_header_sys_mman_h" = "no"; then - have_mmap=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. We - # simply assume that if we have mman.h, we have mmap. - have_mmap=yes - case "${host}" in - spu-*-*|*-*-msdosdjgpp) - # The SPU does not have mmap, but it has a sys/mman.h header file - # containing "mmap_eaddr" and the mmap flags, confusing the test. - # DJGPP also has sys/man.h, but no mmap - have_mmap=no ;; - esac - else - ac_fn_c_check_func "$LINENO" "mmap" "ac_cv_func_mmap" -if test "x$ac_cv_func_mmap" = x""yes; then : - have_mmap=yes -else - have_mmap=no -fi - - fi -fi - -case "${host_os}" in -darwin*) - have_mmap=no ;; -esac - -if test "$have_mmap" = "no"; then - VIEW_FILE=read.lo - ALLOC_FILE=alloc.lo -else - VIEW_FILE=mmapio.lo - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -#include -#if !defined(MAP_ANONYMOUS) && !defined(MAP_ANON) - #error no MAP_ANONYMOUS -#endif - -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - ALLOC_FILE=alloc.lo -else - ALLOC_FILE=alloc.lo -fi -rm -f conftest.err conftest.$ac_ext -fi - - - -BACKTRACE_USES_MALLOC=0 -if test "$ALLOC_FILE" = "alloc.lo"; then - BACKTRACE_USES_MALLOC=1 -fi - - -# Check for dl_iterate_phdr. -for ac_header in link.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "link.h" "ac_cv_header_link_h" "$ac_includes_default" -if test "x$ac_cv_header_link_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LINK_H 1 -_ACEOF - -fi - -done - -if test "$ac_cv_header_link_h" = "no"; then - have_dl_iterate_phdr=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "dl_iterate_phdr" >/dev/null 2>&1; then : - have_dl_iterate_phdr=yes -else - have_dl_iterate_phdr=no -fi -rm -f conftest* - - case "${host}" in - *-*-solaris2.10*) - # Avoid dl_iterate_phdr on Solaris 10, where it is in the - # header file but is only in -ldl. - have_dl_iterate_phdr=no ;; - esac - else - ac_fn_c_check_func "$LINENO" "dl_iterate_phdr" "ac_cv_func_dl_iterate_phdr" -if test "x$ac_cv_func_dl_iterate_phdr" = x""yes; then : - have_dl_iterate_phdr=yes -else - have_dl_iterate_phdr=no -fi - - fi -fi -if test "$have_dl_iterate_phdr" = "yes"; then - -$as_echo "#define HAVE_DL_ITERATE_PHDR 1" >>confdefs.h - -fi - -# Check for loadquery. -for ac_header in sys/ldr.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "sys/ldr.h" "ac_cv_header_sys_ldr_h" "$ac_includes_default" -if test "x$ac_cv_header_sys_ldr_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_SYS_LDR_H 1 -_ACEOF - -fi - -done - -if test "$ac_cv_header_sys_ldr_h" = "no"; then - have_loadquery=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "loadquery" >/dev/null 2>&1; then : - have_loadquery=yes -else - have_loadquery=no -fi -rm -f conftest* - - else - ac_fn_c_check_func "$LINENO" "loadquery" "ac_cv_func_loadquery" -if test "x$ac_cv_func_loadquery" = x""yes; then : - have_loadquery=yes -else - have_loadquery=no -fi - - fi -fi -if test "$have_loadquery" = "yes"; then - -$as_echo "#define HAVE_LOADQUERY 1" >>confdefs.h - -fi - -# Check for the fcntl function. -if test -n "${with_target_subdir}"; then - case "${host}" in - *-*-mingw*) have_fcntl=no ;; - spu-*-*) have_fcntl=no ;; - *) have_fcntl=yes ;; - esac -else - ac_fn_c_check_func "$LINENO" "fcntl" "ac_cv_func_fcntl" -if test "x$ac_cv_func_fcntl" = x""yes; then : - have_fcntl=yes -else - have_fcntl=no -fi - -fi -if test "$have_fcntl" = "yes"; then - -$as_echo "#define HAVE_FCNTL 1" >>confdefs.h - -fi - -ac_fn_c_check_decl "$LINENO" "strnlen" "ac_cv_have_decl_strnlen" "$ac_includes_default" -if test "x$ac_cv_have_decl_strnlen" = x""yes; then : - ac_have_decl=1 -else - ac_have_decl=0 -fi - -cat >>confdefs.h <<_ACEOF -#define HAVE_DECL_STRNLEN $ac_have_decl -_ACEOF - -for ac_func in lstat readlink -do : - as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` -ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" -eval as_val=\$$as_ac_var - if test "x$as_val" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - -# Check for getexecname function. -if test -n "${with_target_subdir}"; then - case "${host}" in - *-*-solaris2*) have_getexecname=yes ;; - *) have_getexecname=no ;; - esac -else - ac_fn_c_check_func "$LINENO" "getexecname" "ac_cv_func_getexecname" -if test "x$ac_cv_func_getexecname" = x""yes; then : - have_getexecname=yes -else - have_getexecname=no -fi - -fi -if test "$have_getexecname" = "yes"; then - -$as_echo "#define HAVE_GETEXECNAME 1" >>confdefs.h - -fi - -# Check for the clock_gettime function. -for ac_func in clock_gettime -do : - ac_fn_c_check_func "$LINENO" "clock_gettime" "ac_cv_func_clock_gettime" -if test "x$ac_cv_func_clock_gettime" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_CLOCK_GETTIME 1 -_ACEOF - -fi -done - -clock_gettime_link= -# At least for glibc, clock_gettime is in librt. But don't -# pull that in if it still doesn't give us the function we want. This -# test is copied from libgomp, and modified to not link in -lrt as -# we're using this for test timing only. -if test "$ac_cv_func_clock_gettime" = no; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in -lrt" >&5 -$as_echo_n "checking for clock_gettime in -lrt... " >&6; } -if test "${ac_cv_lib_rt_clock_gettime+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lrt $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char clock_gettime (); -int -main () -{ -return clock_gettime (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_rt_clock_gettime=yes -else - ac_cv_lib_rt_clock_gettime=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_clock_gettime" >&5 -$as_echo "$ac_cv_lib_rt_clock_gettime" >&6; } -if test "x$ac_cv_lib_rt_clock_gettime" = x""yes; then : - CLOCK_GETTIME_LINK=-lrt - -$as_echo "#define HAVE_CLOCK_GETTIME 1" >>confdefs.h - -fi - -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -pthread is supported" >&5 -$as_echo_n "checking whether -pthread is supported... " >&6; } -if test "${libgo_cv_lib_pthread+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - CFLAGS_hold=$CFLAGS -CFLAGS="$CFLAGS -pthread" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -int i; -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - libgo_cv_lib_pthread=yes -else - libgo_cv_lib_pthread=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -CFLAGS=$CFLAGS_hold -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libgo_cv_lib_pthread" >&5 -$as_echo "$libgo_cv_lib_pthread" >&6; } -PTHREAD_CFLAGS= -if test "$libgo_cv_lib_pthread" = yes; then - PTHREAD_CFLAGS=-pthread -fi - - - if test "$libgo_cv_lib_pthread" = yes; then - HAVE_PTHREAD_TRUE= - HAVE_PTHREAD_FALSE='#' -else - HAVE_PTHREAD_TRUE='#' - HAVE_PTHREAD_FALSE= -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for compress in -lz" >&5 -$as_echo_n "checking for compress in -lz... " >&6; } -if test "${ac_cv_lib_z_compress+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lz $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char compress (); -int -main () -{ -return compress (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_z_compress=yes -else - ac_cv_lib_z_compress=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_compress" >&5 -$as_echo "$ac_cv_lib_z_compress" >&6; } -if test "x$ac_cv_lib_z_compress" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_LIBZ 1 -_ACEOF - - LIBS="-lz $LIBS" - -fi - -if test $ac_cv_lib_z_compress = "yes"; then - -$as_echo "#define HAVE_ZLIB 1" >>confdefs.h - -fi - if test "$ac_cv_lib_z_compress" = yes; then - HAVE_ZLIB_TRUE= - HAVE_ZLIB_FALSE='#' -else - HAVE_ZLIB_TRUE='#' - HAVE_ZLIB_FALSE= -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether --compress-debug-sections is supported" >&5 -$as_echo_n "checking whether --compress-debug-sections is supported... " >&6; } -if test "${libgo_cv_ld_compress+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - LDFLAGS_hold=$LDFLAGS -LDFLAGS="$LDFLAGS -Wl,--compress-debug-sections=zlib-gnu" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - libgo_cv_ld_compress=yes -else - libgo_cv_ld_compress=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LDFLAGS=$LDFLAGS_hold -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libgo_cv_ld_compress" >&5 -$as_echo "$libgo_cv_ld_compress" >&6; } - if test "$libgo_cv_ld_compress" = yes; then - HAVE_COMPRESSED_DEBUG_TRUE= - HAVE_COMPRESSED_DEBUG_FALSE='#' -else - HAVE_COMPRESSED_DEBUG_TRUE='#' - HAVE_COMPRESSED_DEBUG_FALSE= -fi - - - -# Extract the first word of "objcopy", so it can be a program name with args. -set dummy objcopy; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OBJCOPY+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$OBJCOPY"; then - ac_cv_prog_OBJCOPY="$OBJCOPY" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_OBJCOPY="objcopy" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -OBJCOPY=$ac_cv_prog_OBJCOPY -if test -n "$OBJCOPY"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJCOPY" >&5 -$as_echo "$OBJCOPY" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether objcopy supports debuglink" >&5 -$as_echo_n "checking whether objcopy supports debuglink... " >&6; } -if test "${libbacktrace_cv_objcopy_debuglink+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "${with_target_subdir}"; then - libbacktrace_cv_objcopy_debuglink=no -elif ${OBJCOPY} --add-gnu-debuglink=x /bin/ls /tmp/ls$$; then - rm -f /tmp/ls$$ - libbacktrace_cv_objcopy_debuglink=yes -else - libbacktrace_cv_objcopy_debuglink=no -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_objcopy_debuglink" >&5 -$as_echo "$libbacktrace_cv_objcopy_debuglink" >&6; } - if test "$libbacktrace_cv_objcopy_debuglink" = yes; then - HAVE_OBJCOPY_DEBUGLINK_TRUE= - HAVE_OBJCOPY_DEBUGLINK_FALSE='#' -else - HAVE_OBJCOPY_DEBUGLINK_TRUE='#' - HAVE_OBJCOPY_DEBUGLINK_FALSE= -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tests can run" >&5 -$as_echo_n "checking whether tests can run... " >&6; } -if test "${libbacktrace_cv_sys_native+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - libbacktrace_cv_sys_native=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -return 0; - ; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - libbacktrace_cv_sys_native=yes -else - libbacktrace_cv_sys_native=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $libbacktrace_cv_sys_native" >&5 -$as_echo "$libbacktrace_cv_sys_native" >&6; } - if test "$libbacktrace_cv_sys_native" = "yes"; then - NATIVE_TRUE= - NATIVE_FALSE='#' -else - NATIVE_TRUE='#' - NATIVE_FALSE= -fi - - -if test "${multilib}" = "yes"; then - multilib_arg="--enable-multilib" -else - multilib_arg= -fi - -ac_config_files="$ac_config_files Makefile backtrace-supported.h" - - -# We need multilib support, but only if configuring for the target. -ac_config_commands="$ac_config_commands default" - - -cat >confcache <<\_ACEOF -# This file is a shell script that caches the results of configure -# tests run on this system so they can be shared between configure -# scripts and configure runs, see configure's option --config-cache. -# It is not useful on other systems. If it contains results you don't -# want to keep, you may remove or edit it. -# -# config.status only pays attention to the cache file if you give it -# the --recheck option to rerun configure. -# -# `ac_cv_env_foo' variables (set or unset) will be overridden when -# loading this file, other *unset* `ac_cv_foo' will be assigned the -# following values. - -_ACEOF - -# The following way of writing the cache mishandles newlines in values, -# but we know of no workaround that is simple, portable, and efficient. -# So, we kill variables containing newlines. -# Ultrix sh set writes to stderr and can't be redirected directly, -# and sets the high bit in the cache file unless we assign to the vars. -( - for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - - (set) 2>&1 | - case $as_nl`(ac_space=' '; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes: double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \. - sed -n \ - "s/'/'\\\\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" - ;; #( - *) - # `set' quotes correctly as required by POSIX, so do not add quotes. - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) | - sed ' - /^ac_cv_env_/b end - t clear - :clear - s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ - t end - s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ - :end' >>confcache -if diff "$cache_file" confcache >/dev/null 2>&1; then :; else - if test -w "$cache_file"; then - test "x$cache_file" != "x/dev/null" && - { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 -$as_echo "$as_me: updating cache $cache_file" >&6;} - cat confcache >$cache_file - else - { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 -$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} - fi -fi -rm -f confcache - -test "x$prefix" = xNONE && prefix=$ac_default_prefix -# Let make expand exec_prefix. -test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' - -DEFS=-DHAVE_CONFIG_H - -ac_libobjs= -ac_ltlibobjs= -for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue - # 1. Remove the extension, and $U if already installed. - ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`$as_echo "$ac_i" | sed "$ac_script"` - # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR - # will be set to the directory where LIBOBJS objects are built. - as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" - as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' -done -LIBOBJS=$ac_libobjs - -LTLIBOBJS=$ac_ltlibobjs - - - if test -n "$EXEEXT"; then - am__EXEEXT_TRUE= - am__EXEEXT_FALSE='#' -else - am__EXEEXT_TRUE='#' - am__EXEEXT_FALSE= -fi - -if test -z "${MAINTAINER_MODE_TRUE}" && test -z "${MAINTAINER_MODE_FALSE}"; then - as_fn_error "conditional \"MAINTAINER_MODE\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi -if test -z "${HAVE_PTHREAD_TRUE}" && test -z "${HAVE_PTHREAD_FALSE}"; then - as_fn_error "conditional \"HAVE_PTHREAD\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi -if test -z "${HAVE_ZLIB_TRUE}" && test -z "${HAVE_ZLIB_FALSE}"; then - as_fn_error "conditional \"HAVE_ZLIB\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi -if test -z "${HAVE_COMPRESSED_DEBUG_TRUE}" && test -z "${HAVE_COMPRESSED_DEBUG_FALSE}"; then - as_fn_error "conditional \"HAVE_COMPRESSED_DEBUG\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi -if test -z "${HAVE_OBJCOPY_DEBUGLINK_TRUE}" && test -z "${HAVE_OBJCOPY_DEBUGLINK_FALSE}"; then - as_fn_error "conditional \"HAVE_OBJCOPY_DEBUGLINK\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi -if test -z "${NATIVE_TRUE}" && test -z "${NATIVE_FALSE}"; then - as_fn_error "conditional \"NATIVE\" was never defined. -Usually this means the macro was only invoked conditionally." "$LINENO" 5 -fi - -: ${CONFIG_STATUS=./config.status} -ac_write_fail=0 -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 -$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} -as_write_fail=0 -cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 -#! $SHELL -# Generated by $as_me. -# Run this file to recreate the current configuration. -# Compiler output produced by configure, useful for debugging -# configure, is in config.log if it exists. - -debug=false -ac_cs_recheck=false -ac_cs_silent=false - -SHELL=\${CONFIG_SHELL-$SHELL} -export SHELL -_ASEOF -cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - - -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. -as_fn_error () -{ - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 - fi - $as_echo "$as_me: error: $1" >&2 - as_fn_exit $as_status -} # as_fn_error - - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -exec 6>&1 -## ----------------------------------- ## -## Main body of $CONFIG_STATUS script. ## -## ----------------------------------- ## -_ASEOF -test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# Save the log message, to keep $0 and so on meaningful, and to -# report actual input values of CONFIG_FILES etc. instead of their -# values after options handling. -ac_log=" -This file was extended by package-unused $as_me version-unused, which was -generated by GNU Autoconf 2.64. Invocation command line was - - CONFIG_FILES = $CONFIG_FILES - CONFIG_HEADERS = $CONFIG_HEADERS - CONFIG_LINKS = $CONFIG_LINKS - CONFIG_COMMANDS = $CONFIG_COMMANDS - $ $0 $@ - -on `(hostname || uname -n) 2>/dev/null | sed 1q` -" - -_ACEOF - -case $ac_config_files in *" -"*) set x $ac_config_files; shift; ac_config_files=$*;; -esac - -case $ac_config_headers in *" -"*) set x $ac_config_headers; shift; ac_config_headers=$*;; -esac - - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -# Files that config.status was made for. -config_files="$ac_config_files" -config_headers="$ac_config_headers" -config_commands="$ac_config_commands" - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -ac_cs_usage="\ -\`$as_me' instantiates files and other configuration actions -from templates according to the current configuration. Unless the files -and actions are specified as TAGs, all are instantiated by default. - -Usage: $0 [OPTION]... [TAG]... - - -h, --help print this help, then exit - -V, --version print version number and configuration settings, then exit - -q, --quiet, --silent - do not print progress messages - -d, --debug don't remove temporary files - --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE - -Configuration files: -$config_files - -Configuration headers: -$config_headers - -Configuration commands: -$config_commands - -Report bugs to the package provider." - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_cs_version="\\ -package-unused config.status version-unused -configured by $0, generated by GNU Autoconf 2.64, - with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" - -Copyright (C) 2009 Free Software Foundation, Inc. -This config.status script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it." - -ac_pwd='$ac_pwd' -srcdir='$srcdir' -INSTALL='$INSTALL' -MKDIR_P='$MKDIR_P' -AWK='$AWK' -test -n "\$AWK" || AWK=awk -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# The default lists apply if the user does not specify any file. -ac_need_defaults=: -while test $# != 0 -do - case $1 in - --*=*) - ac_option=`expr "X$1" : 'X\([^=]*\)='` - ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` - ac_shift=: - ;; - *) - ac_option=$1 - ac_optarg=$2 - ac_shift=shift - ;; - esac - - case $ac_option in - # Handling of the options. - -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) - ac_cs_recheck=: ;; - --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - $as_echo "$ac_cs_version"; exit ;; - --debug | --debu | --deb | --de | --d | -d ) - debug=: ;; - --file | --fil | --fi | --f ) - $ac_shift - case $ac_optarg in - *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - as_fn_append CONFIG_FILES " '$ac_optarg'" - ac_need_defaults=false;; - --header | --heade | --head | --hea ) - $ac_shift - case $ac_optarg in - *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - as_fn_append CONFIG_HEADERS " '$ac_optarg'" - ac_need_defaults=false;; - --he | --h) - # Conflict between --help and --header - as_fn_error "ambiguous option: \`$1' -Try \`$0 --help' for more information.";; - --help | --hel | -h ) - $as_echo "$ac_cs_usage"; exit ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil | --si | --s) - ac_cs_silent=: ;; - - # This is an error. - -*) as_fn_error "unrecognized option: \`$1' -Try \`$0 --help' for more information." ;; - - *) as_fn_append ac_config_targets " $1" - ac_need_defaults=false ;; - - esac - shift -done - -ac_configure_extra_args= - -if $ac_cs_silent; then - exec 6>/dev/null - ac_configure_extra_args="$ac_configure_extra_args --silent" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -if \$ac_cs_recheck; then - set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion - shift - \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 - CONFIG_SHELL='$SHELL' - export CONFIG_SHELL - exec "\$@" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -exec 5>>config.log -{ - echo - sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX -## Running $as_me. ## -_ASBOX - $as_echo "$ac_log" -} >&5 - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -# -# INIT-COMMANDS -# - -srcdir="$srcdir" -host="$host" -target="$target" -with_multisubdir="$with_multisubdir" -with_multisrctop="$with_multisrctop" -with_target_subdir="$with_target_subdir" -ac_configure_args="${multilib_arg} ${ac_configure_args}" -multi_basedir="$multi_basedir" -CONFIG_SHELL=${CONFIG_SHELL-/bin/sh} -CC="$CC" - - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -sed_quote_subst='$sed_quote_subst' -double_quote_subst='$double_quote_subst' -delay_variable_subst='$delay_variable_subst' -macro_version='`$ECHO "X$macro_version" | $Xsed -e "$delay_single_quote_subst"`' -macro_revision='`$ECHO "X$macro_revision" | $Xsed -e "$delay_single_quote_subst"`' -enable_shared='`$ECHO "X$enable_shared" | $Xsed -e "$delay_single_quote_subst"`' -enable_static='`$ECHO "X$enable_static" | $Xsed -e "$delay_single_quote_subst"`' -pic_mode='`$ECHO "X$pic_mode" | $Xsed -e "$delay_single_quote_subst"`' -enable_fast_install='`$ECHO "X$enable_fast_install" | $Xsed -e "$delay_single_quote_subst"`' -host_alias='`$ECHO "X$host_alias" | $Xsed -e "$delay_single_quote_subst"`' -host='`$ECHO "X$host" | $Xsed -e "$delay_single_quote_subst"`' -host_os='`$ECHO "X$host_os" | $Xsed -e "$delay_single_quote_subst"`' -build_alias='`$ECHO "X$build_alias" | $Xsed -e "$delay_single_quote_subst"`' -build='`$ECHO "X$build" | $Xsed -e "$delay_single_quote_subst"`' -build_os='`$ECHO "X$build_os" | $Xsed -e "$delay_single_quote_subst"`' -SED='`$ECHO "X$SED" | $Xsed -e "$delay_single_quote_subst"`' -Xsed='`$ECHO "X$Xsed" | $Xsed -e "$delay_single_quote_subst"`' -GREP='`$ECHO "X$GREP" | $Xsed -e "$delay_single_quote_subst"`' -EGREP='`$ECHO "X$EGREP" | $Xsed -e "$delay_single_quote_subst"`' -FGREP='`$ECHO "X$FGREP" | $Xsed -e "$delay_single_quote_subst"`' -LD='`$ECHO "X$LD" | $Xsed -e "$delay_single_quote_subst"`' -NM='`$ECHO "X$NM" | $Xsed -e "$delay_single_quote_subst"`' -LN_S='`$ECHO "X$LN_S" | $Xsed -e "$delay_single_quote_subst"`' -max_cmd_len='`$ECHO "X$max_cmd_len" | $Xsed -e "$delay_single_quote_subst"`' -ac_objext='`$ECHO "X$ac_objext" | $Xsed -e "$delay_single_quote_subst"`' -exeext='`$ECHO "X$exeext" | $Xsed -e "$delay_single_quote_subst"`' -lt_unset='`$ECHO "X$lt_unset" | $Xsed -e "$delay_single_quote_subst"`' -lt_SP2NL='`$ECHO "X$lt_SP2NL" | $Xsed -e "$delay_single_quote_subst"`' -lt_NL2SP='`$ECHO "X$lt_NL2SP" | $Xsed -e "$delay_single_quote_subst"`' -reload_flag='`$ECHO "X$reload_flag" | $Xsed -e "$delay_single_quote_subst"`' -reload_cmds='`$ECHO "X$reload_cmds" | $Xsed -e "$delay_single_quote_subst"`' -deplibs_check_method='`$ECHO "X$deplibs_check_method" | $Xsed -e "$delay_single_quote_subst"`' -file_magic_cmd='`$ECHO "X$file_magic_cmd" | $Xsed -e "$delay_single_quote_subst"`' -AR='`$ECHO "X$AR" | $Xsed -e "$delay_single_quote_subst"`' -AR_FLAGS='`$ECHO "X$AR_FLAGS" | $Xsed -e "$delay_single_quote_subst"`' -STRIP='`$ECHO "X$STRIP" | $Xsed -e "$delay_single_quote_subst"`' -RANLIB='`$ECHO "X$RANLIB" | $Xsed -e "$delay_single_quote_subst"`' -old_postinstall_cmds='`$ECHO "X$old_postinstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' -old_postuninstall_cmds='`$ECHO "X$old_postuninstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' -old_archive_cmds='`$ECHO "X$old_archive_cmds" | $Xsed -e "$delay_single_quote_subst"`' -CC='`$ECHO "X$CC" | $Xsed -e "$delay_single_quote_subst"`' -CFLAGS='`$ECHO "X$CFLAGS" | $Xsed -e "$delay_single_quote_subst"`' -compiler='`$ECHO "X$compiler" | $Xsed -e "$delay_single_quote_subst"`' -GCC='`$ECHO "X$GCC" | $Xsed -e "$delay_single_quote_subst"`' -lt_cv_sys_global_symbol_pipe='`$ECHO "X$lt_cv_sys_global_symbol_pipe" | $Xsed -e "$delay_single_quote_subst"`' -lt_cv_sys_global_symbol_to_cdecl='`$ECHO "X$lt_cv_sys_global_symbol_to_cdecl" | $Xsed -e "$delay_single_quote_subst"`' -lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "X$lt_cv_sys_global_symbol_to_c_name_address" | $Xsed -e "$delay_single_quote_subst"`' -lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "X$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $Xsed -e "$delay_single_quote_subst"`' -objdir='`$ECHO "X$objdir" | $Xsed -e "$delay_single_quote_subst"`' -SHELL='`$ECHO "X$SHELL" | $Xsed -e "$delay_single_quote_subst"`' -ECHO='`$ECHO "X$ECHO" | $Xsed -e "$delay_single_quote_subst"`' -MAGIC_CMD='`$ECHO "X$MAGIC_CMD" | $Xsed -e "$delay_single_quote_subst"`' -lt_prog_compiler_no_builtin_flag='`$ECHO "X$lt_prog_compiler_no_builtin_flag" | $Xsed -e "$delay_single_quote_subst"`' -lt_prog_compiler_wl='`$ECHO "X$lt_prog_compiler_wl" | $Xsed -e "$delay_single_quote_subst"`' -lt_prog_compiler_pic='`$ECHO "X$lt_prog_compiler_pic" | $Xsed -e "$delay_single_quote_subst"`' -lt_prog_compiler_static='`$ECHO "X$lt_prog_compiler_static" | $Xsed -e "$delay_single_quote_subst"`' -lt_cv_prog_compiler_c_o='`$ECHO "X$lt_cv_prog_compiler_c_o" | $Xsed -e "$delay_single_quote_subst"`' -need_locks='`$ECHO "X$need_locks" | $Xsed -e "$delay_single_quote_subst"`' -DSYMUTIL='`$ECHO "X$DSYMUTIL" | $Xsed -e "$delay_single_quote_subst"`' -NMEDIT='`$ECHO "X$NMEDIT" | $Xsed -e "$delay_single_quote_subst"`' -LIPO='`$ECHO "X$LIPO" | $Xsed -e "$delay_single_quote_subst"`' -OTOOL='`$ECHO "X$OTOOL" | $Xsed -e "$delay_single_quote_subst"`' -OTOOL64='`$ECHO "X$OTOOL64" | $Xsed -e "$delay_single_quote_subst"`' -libext='`$ECHO "X$libext" | $Xsed -e "$delay_single_quote_subst"`' -shrext_cmds='`$ECHO "X$shrext_cmds" | $Xsed -e "$delay_single_quote_subst"`' -extract_expsyms_cmds='`$ECHO "X$extract_expsyms_cmds" | $Xsed -e "$delay_single_quote_subst"`' -archive_cmds_need_lc='`$ECHO "X$archive_cmds_need_lc" | $Xsed -e "$delay_single_quote_subst"`' -enable_shared_with_static_runtimes='`$ECHO "X$enable_shared_with_static_runtimes" | $Xsed -e "$delay_single_quote_subst"`' -export_dynamic_flag_spec='`$ECHO "X$export_dynamic_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' -whole_archive_flag_spec='`$ECHO "X$whole_archive_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' -compiler_needs_object='`$ECHO "X$compiler_needs_object" | $Xsed -e "$delay_single_quote_subst"`' -old_archive_from_new_cmds='`$ECHO "X$old_archive_from_new_cmds" | $Xsed -e "$delay_single_quote_subst"`' -old_archive_from_expsyms_cmds='`$ECHO "X$old_archive_from_expsyms_cmds" | $Xsed -e "$delay_single_quote_subst"`' -archive_cmds='`$ECHO "X$archive_cmds" | $Xsed -e "$delay_single_quote_subst"`' -archive_expsym_cmds='`$ECHO "X$archive_expsym_cmds" | $Xsed -e "$delay_single_quote_subst"`' -module_cmds='`$ECHO "X$module_cmds" | $Xsed -e "$delay_single_quote_subst"`' -module_expsym_cmds='`$ECHO "X$module_expsym_cmds" | $Xsed -e "$delay_single_quote_subst"`' -with_gnu_ld='`$ECHO "X$with_gnu_ld" | $Xsed -e "$delay_single_quote_subst"`' -allow_undefined_flag='`$ECHO "X$allow_undefined_flag" | $Xsed -e "$delay_single_quote_subst"`' -no_undefined_flag='`$ECHO "X$no_undefined_flag" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_libdir_flag_spec='`$ECHO "X$hardcode_libdir_flag_spec" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_libdir_flag_spec_ld='`$ECHO "X$hardcode_libdir_flag_spec_ld" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_libdir_separator='`$ECHO "X$hardcode_libdir_separator" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_direct='`$ECHO "X$hardcode_direct" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_direct_absolute='`$ECHO "X$hardcode_direct_absolute" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_minus_L='`$ECHO "X$hardcode_minus_L" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_shlibpath_var='`$ECHO "X$hardcode_shlibpath_var" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_automatic='`$ECHO "X$hardcode_automatic" | $Xsed -e "$delay_single_quote_subst"`' -inherit_rpath='`$ECHO "X$inherit_rpath" | $Xsed -e "$delay_single_quote_subst"`' -link_all_deplibs='`$ECHO "X$link_all_deplibs" | $Xsed -e "$delay_single_quote_subst"`' -fix_srcfile_path='`$ECHO "X$fix_srcfile_path" | $Xsed -e "$delay_single_quote_subst"`' -always_export_symbols='`$ECHO "X$always_export_symbols" | $Xsed -e "$delay_single_quote_subst"`' -export_symbols_cmds='`$ECHO "X$export_symbols_cmds" | $Xsed -e "$delay_single_quote_subst"`' -exclude_expsyms='`$ECHO "X$exclude_expsyms" | $Xsed -e "$delay_single_quote_subst"`' -include_expsyms='`$ECHO "X$include_expsyms" | $Xsed -e "$delay_single_quote_subst"`' -prelink_cmds='`$ECHO "X$prelink_cmds" | $Xsed -e "$delay_single_quote_subst"`' -file_list_spec='`$ECHO "X$file_list_spec" | $Xsed -e "$delay_single_quote_subst"`' -variables_saved_for_relink='`$ECHO "X$variables_saved_for_relink" | $Xsed -e "$delay_single_quote_subst"`' -need_lib_prefix='`$ECHO "X$need_lib_prefix" | $Xsed -e "$delay_single_quote_subst"`' -need_version='`$ECHO "X$need_version" | $Xsed -e "$delay_single_quote_subst"`' -version_type='`$ECHO "X$version_type" | $Xsed -e "$delay_single_quote_subst"`' -runpath_var='`$ECHO "X$runpath_var" | $Xsed -e "$delay_single_quote_subst"`' -shlibpath_var='`$ECHO "X$shlibpath_var" | $Xsed -e "$delay_single_quote_subst"`' -shlibpath_overrides_runpath='`$ECHO "X$shlibpath_overrides_runpath" | $Xsed -e "$delay_single_quote_subst"`' -libname_spec='`$ECHO "X$libname_spec" | $Xsed -e "$delay_single_quote_subst"`' -library_names_spec='`$ECHO "X$library_names_spec" | $Xsed -e "$delay_single_quote_subst"`' -soname_spec='`$ECHO "X$soname_spec" | $Xsed -e "$delay_single_quote_subst"`' -postinstall_cmds='`$ECHO "X$postinstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' -postuninstall_cmds='`$ECHO "X$postuninstall_cmds" | $Xsed -e "$delay_single_quote_subst"`' -finish_cmds='`$ECHO "X$finish_cmds" | $Xsed -e "$delay_single_quote_subst"`' -finish_eval='`$ECHO "X$finish_eval" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_into_libs='`$ECHO "X$hardcode_into_libs" | $Xsed -e "$delay_single_quote_subst"`' -sys_lib_search_path_spec='`$ECHO "X$sys_lib_search_path_spec" | $Xsed -e "$delay_single_quote_subst"`' -sys_lib_dlsearch_path_spec='`$ECHO "X$sys_lib_dlsearch_path_spec" | $Xsed -e "$delay_single_quote_subst"`' -hardcode_action='`$ECHO "X$hardcode_action" | $Xsed -e "$delay_single_quote_subst"`' -enable_dlopen='`$ECHO "X$enable_dlopen" | $Xsed -e "$delay_single_quote_subst"`' -enable_dlopen_self='`$ECHO "X$enable_dlopen_self" | $Xsed -e "$delay_single_quote_subst"`' -enable_dlopen_self_static='`$ECHO "X$enable_dlopen_self_static" | $Xsed -e "$delay_single_quote_subst"`' -old_striplib='`$ECHO "X$old_striplib" | $Xsed -e "$delay_single_quote_subst"`' -striplib='`$ECHO "X$striplib" | $Xsed -e "$delay_single_quote_subst"`' - -LTCC='$LTCC' -LTCFLAGS='$LTCFLAGS' -compiler='$compiler_DEFAULT' - -# Quote evaled strings. -for var in SED \ -GREP \ -EGREP \ -FGREP \ -LD \ -NM \ -LN_S \ -lt_SP2NL \ -lt_NL2SP \ -reload_flag \ -deplibs_check_method \ -file_magic_cmd \ -AR \ -AR_FLAGS \ -STRIP \ -RANLIB \ -CC \ -CFLAGS \ -compiler \ -lt_cv_sys_global_symbol_pipe \ -lt_cv_sys_global_symbol_to_cdecl \ -lt_cv_sys_global_symbol_to_c_name_address \ -lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ -SHELL \ -ECHO \ -lt_prog_compiler_no_builtin_flag \ -lt_prog_compiler_wl \ -lt_prog_compiler_pic \ -lt_prog_compiler_static \ -lt_cv_prog_compiler_c_o \ -need_locks \ -DSYMUTIL \ -NMEDIT \ -LIPO \ -OTOOL \ -OTOOL64 \ -shrext_cmds \ -export_dynamic_flag_spec \ -whole_archive_flag_spec \ -compiler_needs_object \ -with_gnu_ld \ -allow_undefined_flag \ -no_undefined_flag \ -hardcode_libdir_flag_spec \ -hardcode_libdir_flag_spec_ld \ -hardcode_libdir_separator \ -fix_srcfile_path \ -exclude_expsyms \ -include_expsyms \ -file_list_spec \ -variables_saved_for_relink \ -libname_spec \ -library_names_spec \ -soname_spec \ -finish_eval \ -old_striplib \ -striplib; do - case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in - *[\\\\\\\`\\"\\\$]*) - eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" - ;; - *) - eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" - ;; - esac -done - -# Double-quote double-evaled strings. -for var in reload_cmds \ -old_postinstall_cmds \ -old_postuninstall_cmds \ -old_archive_cmds \ -extract_expsyms_cmds \ -old_archive_from_new_cmds \ -old_archive_from_expsyms_cmds \ -archive_cmds \ -archive_expsym_cmds \ -module_cmds \ -module_expsym_cmds \ -export_symbols_cmds \ -prelink_cmds \ -postinstall_cmds \ -postuninstall_cmds \ -finish_cmds \ -sys_lib_search_path_spec \ -sys_lib_dlsearch_path_spec; do - case \`eval \\\\\$ECHO "X\\\\\$\$var"\` in - *[\\\\\\\`\\"\\\$]*) - eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"X\\\$\$var\\" | \\\$Xsed -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" - ;; - *) - eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" - ;; - esac -done - -# Fix-up fallback echo if it was mangled by the above quoting rules. -case \$lt_ECHO in -*'\\\$0 --fallback-echo"') lt_ECHO=\`\$ECHO "X\$lt_ECHO" | \$Xsed -e 's/\\\\\\\\\\\\\\\$0 --fallback-echo"\$/\$0 --fallback-echo"/'\` - ;; -esac - -ac_aux_dir='$ac_aux_dir' -xsi_shell='$xsi_shell' -lt_shell_append='$lt_shell_append' - -# See if we are running on zsh, and set the options which allow our -# commands through without removal of \ escapes INIT. -if test -n "\${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST -fi - - - PACKAGE='$PACKAGE' - VERSION='$VERSION' - TIMESTAMP='$TIMESTAMP' - RM='$RM' - ofile='$ofile' - - - - -# Variables needed in config.status (file generation) which aren't already -# passed by autoconf. -SUBDIRS="$SUBDIRS" - - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 - -# Handling of arguments. -for ac_config_target in $ac_config_targets -do - case $ac_config_target in - "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; - "default-1") CONFIG_COMMANDS="$CONFIG_COMMANDS default-1" ;; - "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; - "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; - "backtrace-supported.h") CONFIG_FILES="$CONFIG_FILES backtrace-supported.h" ;; - "default") CONFIG_COMMANDS="$CONFIG_COMMANDS default" ;; - - *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; - esac -done - - -# If the user did not use the arguments to specify the items to instantiate, -# then the envvar interface is used. Set only those that are not. -# We use the long form for the default assignment because of an extremely -# bizarre bug on SunOS 4.1.3. -if $ac_need_defaults; then - test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files - test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers - test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands -fi - -# Have a temporary directory for convenience. Make it in the build tree -# simply because there is no reason against having it here, and in addition, -# creating and moving files from /tmp can sometimes cause problems. -# Hook for its removal unless debugging. -# Note that there is a small window in which the directory will not be cleaned: -# after its creation but before its name has been assigned to `$tmp'. -$debug || -{ - tmp= - trap 'exit_status=$? - { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status -' 0 - trap 'as_fn_exit 1' 1 2 13 15 -} -# Create a (secure) tmp directory for tmp files. - -{ - tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && - test -n "$tmp" && test -d "$tmp" -} || -{ - tmp=./conf$$-$RANDOM - (umask 077 && mkdir "$tmp") -} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 - -# Set up the scripts for CONFIG_FILES section. -# No need to generate them if there are no CONFIG_FILES. -# This happens for instance with `./config.status config.h'. -if test -n "$CONFIG_FILES"; then - - -ac_cr=`echo X | tr X '\015'` -# On cygwin, bash can eat \r inside `` if the user requested igncr. -# But we know of no other shell where ac_cr would be empty at this -# point, so we can use a bashism as a fallback. -if test "x$ac_cr" = x; then - eval ac_cr=\$\'\\r\' -fi -ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` -if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then - ac_cs_awk_cr='\r' -else - ac_cs_awk_cr=$ac_cr -fi - -echo 'BEGIN {' >"$tmp/subs1.awk" && -_ACEOF - - -{ - echo "cat >conf$$subs.awk <<_ACEOF" && - echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && - echo "_ACEOF" -} >conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 -ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - . ./conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - - ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` - if test $ac_delim_n = $ac_delim_num; then - break - elif $ac_last_try; then - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done -rm -f conf$$subs.sh - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -cat >>"\$tmp/subs1.awk" <<\\_ACAWK && -_ACEOF -sed -n ' -h -s/^/S["/; s/!.*/"]=/ -p -g -s/^[^!]*!// -:repl -t repl -s/'"$ac_delim"'$// -t delim -:nl -h -s/\(.\{148\}\).*/\1/ -t more1 -s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ -p -n -b repl -:more1 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t nl -:delim -h -s/\(.\{148\}\).*/\1/ -t more2 -s/["\\]/\\&/g; s/^/"/; s/$/"/ -p -b -:more2 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t delim -' >$CONFIG_STATUS || ac_write_fail=1 -rm -f conf$$subs.awk -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -_ACAWK -cat >>"\$tmp/subs1.awk" <<_ACAWK && - for (key in S) S_is_set[key] = 1 - FS = "" - -} -{ - line = $ 0 - nfields = split(line, field, "@") - substed = 0 - len = length(field[1]) - for (i = 2; i < nfields; i++) { - key = field[i] - keylen = length(key) - if (S_is_set[key]) { - value = S[key] - line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) - len += length(value) + length(field[++i]) - substed = 1 - } else - len += 1 + keylen - } - - print line -} - -_ACAWK -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then - sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" -else - cat -fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ - || as_fn_error "could not setup config files machinery" "$LINENO" 5 -_ACEOF - -# VPATH may cause trouble with some makes, so we remove $(srcdir), -# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and -# trailing colons and then remove the whole line if VPATH becomes empty -# (actually we leave an empty line to preserve line numbers). -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=/{ -s/:*\$(srcdir):*/:/ -s/:*\${srcdir}:*/:/ -s/:*@srcdir@:*/:/ -s/^\([^=]*=[ ]*\):*/\1/ -s/:*$// -s/^[^=]*=[ ]*$// -}' -fi - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -fi # test -n "$CONFIG_FILES" - -# Set up the scripts for CONFIG_HEADERS section. -# No need to generate them if there are no CONFIG_HEADERS. -# This happens for instance with `./config.status Makefile'. -if test -n "$CONFIG_HEADERS"; then -cat >"$tmp/defines.awk" <<\_ACAWK || -BEGIN { -_ACEOF - -# Transform confdefs.h into an awk script `defines.awk', embedded as -# here-document in config.status, that substitutes the proper values into -# config.h.in to produce config.h. - -# Create a delimiter string that does not exist in confdefs.h, to ease -# handling of long lines. -ac_delim='%!_!# ' -for ac_last_try in false false :; do - ac_t=`sed -n "/$ac_delim/p" confdefs.h` - if test -z "$ac_t"; then - break - elif $ac_last_try; then - as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5 - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done - -# For the awk script, D is an array of macro values keyed by name, -# likewise P contains macro parameters if any. Preserve backslash -# newline sequences. - -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -sed -n ' -s/.\{148\}/&'"$ac_delim"'/g -t rset -:rset -s/^[ ]*#[ ]*define[ ][ ]*/ / -t def -d -:def -s/\\$// -t bsnl -s/["\\]/\\&/g -s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ -D["\1"]=" \3"/p -s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p -d -:bsnl -s/["\\]/\\&/g -s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ -D["\1"]=" \3\\\\\\n"\\/p -t cont -s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p -t cont -d -:cont -n -s/.\{148\}/&'"$ac_delim"'/g -t clear -:clear -s/\\$// -t bsnlc -s/["\\]/\\&/g; s/^/"/; s/$/"/p -d -:bsnlc -s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p -b cont -' >$CONFIG_STATUS || ac_write_fail=1 - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 - for (key in D) D_is_set[key] = 1 - FS = "" -} -/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { - line = \$ 0 - split(line, arg, " ") - if (arg[1] == "#") { - defundef = arg[2] - mac1 = arg[3] - } else { - defundef = substr(arg[1], 2) - mac1 = arg[2] - } - split(mac1, mac2, "(") #) - macro = mac2[1] - prefix = substr(line, 1, index(line, defundef) - 1) - if (D_is_set[macro]) { - # Preserve the white space surrounding the "#". - print prefix "define", macro P[macro] D[macro] - next - } else { - # Replace #undef with comments. This is necessary, for example, - # in the case of _POSIX_SOURCE, which is predefined and required - # on some systems where configure will not decide to define it. - if (defundef == "undef") { - print "/*", prefix defundef, macro, "*/" - next - } - } -} -{ print } -_ACAWK -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 - as_fn_error "could not setup config headers machinery" "$LINENO" 5 -fi # test -n "$CONFIG_HEADERS" - - -eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" -shift -for ac_tag -do - case $ac_tag in - :[FHLC]) ac_mode=$ac_tag; continue;; - esac - case $ac_mode$ac_tag in - :[FHL]*:*);; - :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; - :[FH]-) ac_tag=-:-;; - :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; - esac - ac_save_IFS=$IFS - IFS=: - set x $ac_tag - IFS=$ac_save_IFS - shift - ac_file=$1 - shift - - case $ac_mode in - :L) ac_source=$1;; - :[FH]) - ac_file_inputs= - for ac_f - do - case $ac_f in - -) ac_f="$tmp/stdin";; - *) # Look for the file first in the build tree, then in the source tree - # (if the path is not absolute). The absolute path cannot be DOS-style, - # because $ac_f cannot contain `:'. - test -f "$ac_f" || - case $ac_f in - [\\/$]*) false;; - *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; - esac || - as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; - esac - case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac - as_fn_append ac_file_inputs " '$ac_f'" - done - - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - configure_input='Generated from '` - $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' - `' by configure.' - if test x"$ac_file" != x-; then - configure_input="$ac_file. $configure_input" - { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 -$as_echo "$as_me: creating $ac_file" >&6;} - fi - # Neutralize special characters interpreted by sed in replacement strings. - case $configure_input in #( - *\&* | *\|* | *\\* ) - ac_sed_conf_input=`$as_echo "$configure_input" | - sed 's/[\\\\&|]/\\\\&/g'`;; #( - *) ac_sed_conf_input=$configure_input;; - esac - - case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin" \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; - esac - ;; - esac - - ac_dir=`$as_dirname -- "$ac_file" || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - as_dir="$ac_dir"; as_fn_mkdir_p - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - - case $ac_mode in - :F) - # - # CONFIG_FILE - # - - case $INSTALL in - [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; - *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; - esac - ac_MKDIR_P=$MKDIR_P - case $MKDIR_P in - [\\/$]* | ?:[\\/]* ) ;; - */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; - esac -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# If the template does not know about datarootdir, expand it. -# FIXME: This hack should be removed a few years after 2.60. -ac_datarootdir_hack=; ac_datarootdir_seen= -ac_sed_dataroot=' -/datarootdir/ { - p - q -} -/@datadir@/p -/@docdir@/p -/@infodir@/p -/@localedir@/p -/@mandir@/p' -case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in -*datarootdir*) ac_datarootdir_seen=yes;; -*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 - ac_datarootdir_hack=' - s&@datadir@&$datadir&g - s&@docdir@&$docdir&g - s&@infodir@&$infodir&g - s&@localedir@&$localedir&g - s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; -esac -_ACEOF - -# Neutralize VPATH when `$srcdir' = `.'. -# Shell code in configure.ac might set extrasub. -# FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_sed_extra="$ac_vpsub -$extrasub -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -:t -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s|@configure_input@|$ac_sed_conf_input|;t t -s&@top_builddir@&$ac_top_builddir_sub&;t t -s&@top_build_prefix@&$ac_top_build_prefix&;t t -s&@srcdir@&$ac_srcdir&;t t -s&@abs_srcdir@&$ac_abs_srcdir&;t t -s&@top_srcdir@&$ac_top_srcdir&;t t -s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t -s&@builddir@&$ac_builddir&;t t -s&@abs_builddir@&$ac_abs_builddir&;t t -s&@abs_top_builddir@&$ac_abs_top_builddir&;t t -s&@INSTALL@&$ac_INSTALL&;t t -s&@MKDIR_P@&$ac_MKDIR_P&;t t -$ac_datarootdir_hack -" -eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - -test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && - { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && - { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&5 -$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&2;} - - rm -f "$tmp/stdin" - case $ac_file in - -) cat "$tmp/out" && rm -f "$tmp/out";; - *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; - esac \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - ;; - :H) - # - # CONFIG_HEADER - # - if test x"$ac_file" != x-; then - { - $as_echo "/* $configure_input */" \ - && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" - } >"$tmp/config.h" \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then - { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 -$as_echo "$as_me: $ac_file is unchanged" >&6;} - else - rm -f "$ac_file" - mv "$tmp/config.h" "$ac_file" \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 - fi - else - $as_echo "/* $configure_input */" \ - && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ - || as_fn_error "could not create -" "$LINENO" 5 - fi -# Compute "$ac_file"'s index in $config_headers. -_am_arg="$ac_file" -_am_stamp_count=1 -for _am_header in $config_headers :; do - case $_am_header in - $_am_arg | $_am_arg:* ) - break ;; - * ) - _am_stamp_count=`expr $_am_stamp_count + 1` ;; - esac -done -echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || -$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$_am_arg" : 'X\(//\)[^/]' \| \ - X"$_am_arg" : 'X\(//\)$' \| \ - X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$_am_arg" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'`/stamp-h$_am_stamp_count - ;; - - :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 -$as_echo "$as_me: executing $ac_file commands" >&6;} - ;; - esac - - - case $ac_file$ac_mode in - "default-1":C) -# Only add multilib support code if we just rebuilt the top-level -# Makefile. -case " $CONFIG_FILES " in - *" Makefile "*) - ac_file=Makefile . ${multi_basedir}/config-ml.in - ;; -esac ;; - "libtool":C) - - # See if we are running on zsh, and set the options which allow our - # commands through without removal of \ escapes. - if test -n "${ZSH_VERSION+set}" ; then - setopt NO_GLOB_SUBST - fi - - cfgfile="${ofile}T" - trap "$RM \"$cfgfile\"; exit 1" 1 2 15 - $RM "$cfgfile" - - cat <<_LT_EOF >> "$cfgfile" -#! $SHELL - -# `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. -# Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION -# Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: -# NOTE: Changes made to this file will be lost: look at ltmain.sh. -# -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, -# 2006, 2007, 2008 Free Software Foundation, Inc. -# Written by Gordon Matzigkeit, 1996 -# -# This file is part of GNU Libtool. -# -# GNU Libtool is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as -# published by the Free Software Foundation; either version 2 of -# the License, or (at your option) any later version. -# -# As a special exception to the GNU General Public License, -# if you distribute this file as part of a program or library that -# is built using GNU Libtool, you may include this file under the -# same distribution terms that you use for the rest of that program. -# -# GNU Libtool is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with GNU Libtool; see the file COPYING. If not, a copy -# can be downloaded from http://www.gnu.org/licenses/gpl.html, or -# obtained by writing to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - - -# The names of the tagged configurations supported by this script. -available_tags="" - -# ### BEGIN LIBTOOL CONFIG - -# Which release of libtool.m4 was used? -macro_version=$macro_version -macro_revision=$macro_revision - -# Whether or not to build shared libraries. -build_libtool_libs=$enable_shared - -# Whether or not to build static libraries. -build_old_libs=$enable_static - -# What type of objects to build. -pic_mode=$pic_mode - -# Whether or not to optimize for fast installation. -fast_install=$enable_fast_install - -# The host system. -host_alias=$host_alias -host=$host -host_os=$host_os - -# The build system. -build_alias=$build_alias -build=$build -build_os=$build_os - -# A sed program that does not truncate output. -SED=$lt_SED - -# Sed that helps us avoid accidentally triggering echo(1) options like -n. -Xsed="\$SED -e 1s/^X//" - -# A grep program that handles long lines. -GREP=$lt_GREP - -# An ERE matcher. -EGREP=$lt_EGREP - -# A literal string matcher. -FGREP=$lt_FGREP - -# A BSD- or MS-compatible name lister. -NM=$lt_NM - -# Whether we need soft or hard links. -LN_S=$lt_LN_S - -# What is the maximum length of a command? -max_cmd_len=$max_cmd_len - -# Object file suffix (normally "o"). -objext=$ac_objext - -# Executable file suffix (normally ""). -exeext=$exeext - -# whether the shell understands "unset". -lt_unset=$lt_unset - -# turn spaces into newlines. -SP2NL=$lt_lt_SP2NL - -# turn newlines into spaces. -NL2SP=$lt_lt_NL2SP - -# How to create reloadable object files. -reload_flag=$lt_reload_flag -reload_cmds=$lt_reload_cmds - -# Method to check whether dependent libraries are shared objects. -deplibs_check_method=$lt_deplibs_check_method - -# Command to use when deplibs_check_method == "file_magic". -file_magic_cmd=$lt_file_magic_cmd - -# The archiver. -AR=$lt_AR -AR_FLAGS=$lt_AR_FLAGS - -# A symbol stripping program. -STRIP=$lt_STRIP - -# Commands used to install an old-style archive. -RANLIB=$lt_RANLIB -old_postinstall_cmds=$lt_old_postinstall_cmds -old_postuninstall_cmds=$lt_old_postuninstall_cmds - -# A C compiler. -LTCC=$lt_CC - -# LTCC compiler flags. -LTCFLAGS=$lt_CFLAGS - -# Take the output of nm and produce a listing of raw symbols and C names. -global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe - -# Transform the output of nm in a proper C declaration. -global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl - -# Transform the output of nm in a C name address pair. -global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address - -# Transform the output of nm in a C name address pair when lib prefix is needed. -global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix - -# The name of the directory that contains temporary libtool files. -objdir=$objdir - -# Shell to use when invoking shell scripts. -SHELL=$lt_SHELL - -# An echo program that does not interpret backslashes. -ECHO=$lt_ECHO - -# Used to examine libraries when file_magic_cmd begins with "file". -MAGIC_CMD=$MAGIC_CMD - -# Must we lock files when doing compilation? -need_locks=$lt_need_locks - -# Tool to manipulate archived DWARF debug symbol files on Mac OS X. -DSYMUTIL=$lt_DSYMUTIL - -# Tool to change global to local symbols on Mac OS X. -NMEDIT=$lt_NMEDIT - -# Tool to manipulate fat objects and archives on Mac OS X. -LIPO=$lt_LIPO - -# ldd/readelf like tool for Mach-O binaries on Mac OS X. -OTOOL=$lt_OTOOL - -# ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. -OTOOL64=$lt_OTOOL64 - -# Old archive suffix (normally "a"). -libext=$libext - -# Shared library suffix (normally ".so"). -shrext_cmds=$lt_shrext_cmds - -# The commands to extract the exported symbol list from a shared archive. -extract_expsyms_cmds=$lt_extract_expsyms_cmds - -# Variables whose values should be saved in libtool wrapper scripts and -# restored at link time. -variables_saved_for_relink=$lt_variables_saved_for_relink - -# Do we need the "lib" prefix for modules? -need_lib_prefix=$need_lib_prefix - -# Do we need a version for libraries? -need_version=$need_version - -# Library versioning type. -version_type=$version_type - -# Shared library runtime path variable. -runpath_var=$runpath_var - -# Shared library path variable. -shlibpath_var=$shlibpath_var - -# Is shlibpath searched before the hard-coded library search path? -shlibpath_overrides_runpath=$shlibpath_overrides_runpath - -# Format of library name prefix. -libname_spec=$lt_libname_spec - -# List of archive names. First name is the real one, the rest are links. -# The last name is the one that the linker finds with -lNAME -library_names_spec=$lt_library_names_spec - -# The coded name of the library, if different from the real name. -soname_spec=$lt_soname_spec - -# Command to use after installation of a shared archive. -postinstall_cmds=$lt_postinstall_cmds - -# Command to use after uninstallation of a shared archive. -postuninstall_cmds=$lt_postuninstall_cmds - -# Commands used to finish a libtool library installation in a directory. -finish_cmds=$lt_finish_cmds - -# As "finish_cmds", except a single script fragment to be evaled but -# not shown. -finish_eval=$lt_finish_eval - -# Whether we should hardcode library paths into libraries. -hardcode_into_libs=$hardcode_into_libs - -# Compile-time system search path for libraries. -sys_lib_search_path_spec=$lt_sys_lib_search_path_spec - -# Run-time system search path for libraries. -sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec - -# Whether dlopen is supported. -dlopen_support=$enable_dlopen - -# Whether dlopen of programs is supported. -dlopen_self=$enable_dlopen_self - -# Whether dlopen of statically linked programs is supported. -dlopen_self_static=$enable_dlopen_self_static - -# Commands to strip libraries. -old_striplib=$lt_old_striplib -striplib=$lt_striplib - - -# The linker used to build libraries. -LD=$lt_LD - -# Commands used to build an old-style archive. -old_archive_cmds=$lt_old_archive_cmds - -# A language specific compiler. -CC=$lt_compiler - -# Is the compiler the GNU compiler? -with_gcc=$GCC - -# Compiler flag to turn off builtin functions. -no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag - -# How to pass a linker flag through the compiler. -wl=$lt_lt_prog_compiler_wl - -# Additional compiler flags for building library objects. -pic_flag=$lt_lt_prog_compiler_pic - -# Compiler flag to prevent dynamic linking. -link_static_flag=$lt_lt_prog_compiler_static - -# Does compiler simultaneously support -c and -o options? -compiler_c_o=$lt_lt_cv_prog_compiler_c_o - -# Whether or not to add -lc for building shared libraries. -build_libtool_need_lc=$archive_cmds_need_lc - -# Whether or not to disallow shared libs when runtime libs are static. -allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes - -# Compiler flag to allow reflexive dlopens. -export_dynamic_flag_spec=$lt_export_dynamic_flag_spec - -# Compiler flag to generate shared objects directly from archives. -whole_archive_flag_spec=$lt_whole_archive_flag_spec - -# Whether the compiler copes with passing no objects directly. -compiler_needs_object=$lt_compiler_needs_object - -# Create an old-style archive from a shared archive. -old_archive_from_new_cmds=$lt_old_archive_from_new_cmds - -# Create a temporary old-style archive to link instead of a shared archive. -old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds - -# Commands used to build a shared archive. -archive_cmds=$lt_archive_cmds -archive_expsym_cmds=$lt_archive_expsym_cmds - -# Commands used to build a loadable module if different from building -# a shared archive. -module_cmds=$lt_module_cmds -module_expsym_cmds=$lt_module_expsym_cmds - -# Whether we are building with GNU ld or not. -with_gnu_ld=$lt_with_gnu_ld - -# Flag that allows shared libraries with undefined symbols to be built. -allow_undefined_flag=$lt_allow_undefined_flag - -# Flag that enforces no undefined symbols. -no_undefined_flag=$lt_no_undefined_flag - -# Flag to hardcode \$libdir into a binary during linking. -# This must work even if \$libdir does not exist -hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec - -# If ld is used when linking, flag to hardcode \$libdir into a binary -# during linking. This must work even if \$libdir does not exist. -hardcode_libdir_flag_spec_ld=$lt_hardcode_libdir_flag_spec_ld - -# Whether we need a single "-rpath" flag with a separated argument. -hardcode_libdir_separator=$lt_hardcode_libdir_separator - -# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes -# DIR into the resulting binary. -hardcode_direct=$hardcode_direct - -# Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes -# DIR into the resulting binary and the resulting library dependency is -# "absolute",i.e impossible to change by setting \${shlibpath_var} if the -# library is relocated. -hardcode_direct_absolute=$hardcode_direct_absolute - -# Set to "yes" if using the -LDIR flag during linking hardcodes DIR -# into the resulting binary. -hardcode_minus_L=$hardcode_minus_L - -# Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR -# into the resulting binary. -hardcode_shlibpath_var=$hardcode_shlibpath_var - -# Set to "yes" if building a shared library automatically hardcodes DIR -# into the library and all subsequent libraries and executables linked -# against it. -hardcode_automatic=$hardcode_automatic - -# Set to yes if linker adds runtime paths of dependent libraries -# to runtime path list. -inherit_rpath=$inherit_rpath - -# Whether libtool must link a program against all its dependency libraries. -link_all_deplibs=$link_all_deplibs - -# Fix the shell variable \$srcfile for the compiler. -fix_srcfile_path=$lt_fix_srcfile_path - -# Set to "yes" if exported symbols are required. -always_export_symbols=$always_export_symbols - -# The commands to list exported symbols. -export_symbols_cmds=$lt_export_symbols_cmds - -# Symbols that should not be listed in the preloaded symbols. -exclude_expsyms=$lt_exclude_expsyms - -# Symbols that must always be exported. -include_expsyms=$lt_include_expsyms - -# Commands necessary for linking programs (against libraries) with templates. -prelink_cmds=$lt_prelink_cmds - -# Specify filename containing input files. -file_list_spec=$lt_file_list_spec - -# How to hardcode a shared library path into an executable. -hardcode_action=$hardcode_action - -# ### END LIBTOOL CONFIG - -_LT_EOF - - case $host_os in - aix3*) - cat <<\_LT_EOF >> "$cfgfile" -# AIX sometimes has problems with the GCC collect2 program. For some -# reason, if we set the COLLECT_NAMES environment variable, the problems -# vanish in a puff of smoke. -if test "X${COLLECT_NAMES+set}" != Xset; then - COLLECT_NAMES= - export COLLECT_NAMES -fi -_LT_EOF - ;; - esac - - -ltmain="$ac_aux_dir/ltmain.sh" - - - # We use sed instead of cat because bash on DJGPP gets confused if - # if finds mixed CR/LF and LF-only lines. Since sed operates in - # text mode, it properly converts lines to CR/LF. This bash problem - # is reportedly fixed, but why not run on old versions too? - sed '/^# Generated shell functions inserted here/q' "$ltmain" >> "$cfgfile" \ - || (rm -f "$cfgfile"; exit 1) - - case $xsi_shell in - yes) - cat << \_LT_EOF >> "$cfgfile" - -# func_dirname file append nondir_replacement -# Compute the dirname of FILE. If nonempty, add APPEND to the result, -# otherwise set result to NONDIR_REPLACEMENT. -func_dirname () -{ - case ${1} in - */*) func_dirname_result="${1%/*}${2}" ;; - * ) func_dirname_result="${3}" ;; - esac -} - -# func_basename file -func_basename () -{ - func_basename_result="${1##*/}" -} - -# func_dirname_and_basename file append nondir_replacement -# perform func_basename and func_dirname in a single function -# call: -# dirname: Compute the dirname of FILE. If nonempty, -# add APPEND to the result, otherwise set result -# to NONDIR_REPLACEMENT. -# value returned in "$func_dirname_result" -# basename: Compute filename of FILE. -# value retuned in "$func_basename_result" -# Implementation must be kept synchronized with func_dirname -# and func_basename. For efficiency, we do not delegate to -# those functions but instead duplicate the functionality here. -func_dirname_and_basename () -{ - case ${1} in - */*) func_dirname_result="${1%/*}${2}" ;; - * ) func_dirname_result="${3}" ;; - esac - func_basename_result="${1##*/}" -} - -# func_stripname prefix suffix name -# strip PREFIX and SUFFIX off of NAME. -# PREFIX and SUFFIX must not contain globbing or regex special -# characters, hashes, percent signs, but SUFFIX may contain a leading -# dot (in which case that matches only a dot). -func_stripname () -{ - # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are - # positional parameters, so assign one to ordinary parameter first. - func_stripname_result=${3} - func_stripname_result=${func_stripname_result#"${1}"} - func_stripname_result=${func_stripname_result%"${2}"} -} - -# func_opt_split -func_opt_split () -{ - func_opt_split_opt=${1%%=*} - func_opt_split_arg=${1#*=} -} - -# func_lo2o object -func_lo2o () -{ - case ${1} in - *.lo) func_lo2o_result=${1%.lo}.${objext} ;; - *) func_lo2o_result=${1} ;; - esac -} - -# func_xform libobj-or-source -func_xform () -{ - func_xform_result=${1%.*}.lo -} - -# func_arith arithmetic-term... -func_arith () -{ - func_arith_result=$(( $* )) -} - -# func_len string -# STRING may not start with a hyphen. -func_len () -{ - func_len_result=${#1} -} - -_LT_EOF - ;; - *) # Bourne compatible functions. - cat << \_LT_EOF >> "$cfgfile" - -# func_dirname file append nondir_replacement -# Compute the dirname of FILE. If nonempty, add APPEND to the result, -# otherwise set result to NONDIR_REPLACEMENT. -func_dirname () -{ - # Extract subdirectory from the argument. - func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` - if test "X$func_dirname_result" = "X${1}"; then - func_dirname_result="${3}" - else - func_dirname_result="$func_dirname_result${2}" - fi -} - -# func_basename file -func_basename () -{ - func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` -} - - -# func_stripname prefix suffix name -# strip PREFIX and SUFFIX off of NAME. -# PREFIX and SUFFIX must not contain globbing or regex special -# characters, hashes, percent signs, but SUFFIX may contain a leading -# dot (in which case that matches only a dot). -# func_strip_suffix prefix name -func_stripname () -{ - case ${2} in - .*) func_stripname_result=`$ECHO "X${3}" \ - | $Xsed -e "s%^${1}%%" -e "s%\\\\${2}\$%%"`;; - *) func_stripname_result=`$ECHO "X${3}" \ - | $Xsed -e "s%^${1}%%" -e "s%${2}\$%%"`;; - esac -} - -# sed scripts: -my_sed_long_opt='1s/^\(-[^=]*\)=.*/\1/;q' -my_sed_long_arg='1s/^-[^=]*=//' - -# func_opt_split -func_opt_split () -{ - func_opt_split_opt=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_opt"` - func_opt_split_arg=`$ECHO "X${1}" | $Xsed -e "$my_sed_long_arg"` -} - -# func_lo2o object -func_lo2o () -{ - func_lo2o_result=`$ECHO "X${1}" | $Xsed -e "$lo2o"` -} - -# func_xform libobj-or-source -func_xform () -{ - func_xform_result=`$ECHO "X${1}" | $Xsed -e 's/\.[^.]*$/.lo/'` -} - -# func_arith arithmetic-term... -func_arith () -{ - func_arith_result=`expr "$@"` -} - -# func_len string -# STRING may not start with a hyphen. -func_len () -{ - func_len_result=`expr "$1" : ".*" 2>/dev/null || echo $max_cmd_len` -} - -_LT_EOF -esac - -case $lt_shell_append in - yes) - cat << \_LT_EOF >> "$cfgfile" - -# func_append var value -# Append VALUE to the end of shell variable VAR. -func_append () -{ - eval "$1+=\$2" -} -_LT_EOF - ;; - *) - cat << \_LT_EOF >> "$cfgfile" - -# func_append var value -# Append VALUE to the end of shell variable VAR. -func_append () -{ - eval "$1=\$$1\$2" -} - -_LT_EOF - ;; - esac - - - sed -n '/^# Generated shell functions inserted here/,$p' "$ltmain" >> "$cfgfile" \ - || (rm -f "$cfgfile"; exit 1) - - mv -f "$cfgfile" "$ofile" || - (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") - chmod +x "$ofile" - - ;; - "default":C) if test -n "$CONFIG_FILES"; then - if test -n "${with_target_subdir}"; then - # Multilibs need MULTISUBDIR defined correctly in certain makefiles so - # that multilib installs will end up installed in the correct place. - # The testsuite needs it for multilib-aware ABI baseline files. - # To work around this not being passed down from config-ml.in -> - # srcdir/Makefile.am -> srcdir/{src,libsupc++,...}/Makefile.am, manually - # append it here. Only modify Makefiles that have just been created. - # - # Also, get rid of this simulated-VPATH thing that automake does. - cat > vpsed << \_EOF - s!`test -f '$<' || echo '$(srcdir)/'`!! -_EOF - for i in $SUBDIRS; do - case $CONFIG_FILES in - *${i}/Makefile*) - #echo "Adding MULTISUBDIR to $i/Makefile" - sed -f vpsed $i/Makefile > tmp - grep '^MULTISUBDIR =' Makefile >> tmp - mv tmp $i/Makefile - ;; - esac - done - rm vpsed - fi - fi - ;; - - esac -done # for ac_tag - - -as_fn_exit 0 -_ACEOF -ac_clean_files=$ac_clean_files_save - -test $ac_write_fail = 0 || - as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 - - -# configure is writing to config.log, and then calls config.status. -# config.status does its own redirection, appending to config.log. -# Unfortunately, on DOS this fails, as config.log is still kept open -# by configure, so config.status won't be able to write to it; its -# output is simply discarded. So we exec the FD to /dev/null, -# effectively closing config.log, so it can be properly (re)opened and -# appended to by config.status. When coming back to configure, we -# need to make the FD available again. -if test "$no_create" != yes; then - ac_cs_success=: - ac_config_status_args= - test "$silent" = yes && - ac_config_status_args="$ac_config_status_args --quiet" - exec 5>/dev/null - $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false - exec 5>>config.log - # Use ||, not &&, to avoid exiting from the if with $? = 1, which - # would make configure fail if this is the last instruction. - $ac_cs_success || as_fn_exit $? -fi -if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 -$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} -fi - diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure.ac b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure.ac deleted file mode 100644 index b9056cc..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/configure.ac +++ /dev/null @@ -1,512 +0,0 @@ -# configure.ac -- Backtrace configure script. -# Copyright (C) 2012-2018 Free Software Foundation, Inc. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# (1) Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. - -# (2) 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. - -# (3) The name of the author may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. - -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. - -AC_PREREQ(2.64) -AC_INIT(package-unused, version-unused,, libbacktrace) -AC_CONFIG_SRCDIR(backtrace.h) -AC_CONFIG_HEADER(config.h) -AC_CONFIG_MACRO_DIR(config) - -# with_target_subdir is used when configured as part of a GCC tree. -if test -n "${with_target_subdir}"; then - AM_ENABLE_MULTILIB(, ..) -fi - -AC_CANONICAL_SYSTEM -target_alias=${target_alias-$host_alias} - -AC_USE_SYSTEM_EXTENSIONS - -libtool_VERSION=1:0:0 -AC_SUBST(libtool_VERSION) - -# 1.11.1: Require that version of automake. -# foreign: Don't require README, INSTALL, NEWS, etc. -# no-define: Don't define PACKAGE and VERSION. -# no-dependencies: Don't generate automatic dependencies. -# (because it breaks when using bootstrap-lean, since some of the -# headers are gone at "make install" time). -# -Wall: Issue all automake warnings. -# -Wno-portability: Don't warn about constructs supported by GNU make. -# (because GCC requires GNU make anyhow). -AM_INIT_AUTOMAKE([1.11.1 foreign no-dist no-define no-dependencies -Wall -Wno-portability]) - -AM_MAINTAINER_MODE - -AC_ARG_WITH(target-subdir, -[ --with-target-subdir=SUBDIR Configuring in a subdirectory for target]) - -# We must force CC to /not/ be precious variables; otherwise -# the wrong, non-multilib-adjusted value will be used in multilibs. -# As a side effect, we have to subst CFLAGS ourselves. -m4_rename([_AC_ARG_VAR_PRECIOUS],[backtrace_PRECIOUS]) -m4_define([_AC_ARG_VAR_PRECIOUS],[]) -AC_PROG_CC -m4_rename_force([backtrace_PRECIOUS],[_AC_ARG_VAR_PRECIOUS]) - -AC_SUBST(CFLAGS) - -AC_PROG_AWK -case "$AWK" in -"") AC_MSG_ERROR([can't build without awk]) ;; -esac - -LT_INIT -AM_PROG_LIBTOOL - -AC_SYS_LARGEFILE - -backtrace_supported=yes - -if test -n "${with_target_subdir}"; then - # We are compiling a GCC library. We can assume that the unwind - # library exists. - BACKTRACE_FILE="backtrace.lo simple.lo" -else - AC_CHECK_HEADER([unwind.h], - [AC_CHECK_FUNC([_Unwind_Backtrace], - [BACKTRACE_FILE="backtrace.lo simple.lo"], - [BACKTRACE_FILE="nounwind.lo" - backtrace_supported=no])], - [BACKTRACE_FILE="nounwind.lo" - backtrace_supported=no]) -fi -AC_SUBST(BACKTRACE_FILE) - -EXTRA_FLAGS= -if test -n "${with_target_subdir}"; then - EXTRA_FLAGS="-funwind-tables -frandom-seed=\$@" -else - AC_CACHE_CHECK([for -funwind-tables option], - [libbacktrace_cv_c_unwind_tables], - [CFLAGS_hold="$CFLAGS" - CFLAGS="$CFLAGS -funwind-tables" - AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([static int f() { return 0; }], [return f();])], - [libbacktrace_cv_c_unwind_tables=yes], - [libbacktrace_cv_c_unwind_tables=no]) - CFLAGS="$CFLAGS_hold"]) - if test "$libbacktrace_cv_c_unwind_tables" = "yes"; then - EXTRA_FLAGS=-funwind-tables - fi - AC_CACHE_CHECK([for -frandom-seed=string option], - [libbacktrace_cv_c_random_seed_string], - [CFLAGS_hold="$CFLAGS" - CFLAGS="$CFLAGS -frandom-seed=conftest.lo" - AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([], [return 0;])], - [libbacktrace_cv_c_random_seed_string=yes], - [libbacktrace_cv_c_random_seed_string=no]) - CFLAGS="$CFLAGS_hold"]) - if test "$libbacktrace_cv_c_random_seed_string" = "yes"; then - EXTRA_FLAGS="$EXTRA_FLAGS -frandom-seed=\$@" - fi -fi -AC_SUBST(EXTRA_FLAGS) - -ACX_PROG_CC_WARNING_OPTS([-W -Wall -Wwrite-strings -Wstrict-prototypes \ - -Wmissing-prototypes -Wold-style-definition \ - -Wmissing-format-attribute -Wcast-qual], - [WARN_FLAGS]) - -if test -n "${with_target_subdir}"; then - WARN_FLAGS="$WARN_FLAGS -Werror" -fi - -AC_SUBST(WARN_FLAGS) - -if test -n "${with_target_subdir}"; then - GCC_CHECK_UNWIND_GETIPINFO -else - ac_save_CFFLAGS="$CFLAGS" - CFLAGS="$CFLAGS -Werror-implicit-function-declaration" - AC_MSG_CHECKING([for _Unwind_GetIPInfo]) - AC_LINK_IFELSE( - [AC_LANG_PROGRAM( - [#include "unwind.h" - struct _Unwind_Context *context; - int ip_before_insn = 0;], - [return _Unwind_GetIPInfo (context, &ip_before_insn);])], - [have_unwind_getipinfo=yes], [have_unwind_getipinfo=no]) - CFLAGS="$ac_save_CFLAGS" - AC_MSG_RESULT([$have_unwind_getipinfo]) - if test "$have_unwind_getipinfo" = "yes"; then - AC_DEFINE(HAVE_GETIPINFO, 1, [Define if _Unwind_GetIPInfo is available.]) - fi -fi - -# Enable --enable-host-shared. -AC_ARG_ENABLE(host-shared, -[AS_HELP_STRING([--enable-host-shared], - [build host code as shared libraries])], -[PIC_FLAG=-fPIC], [PIC_FLAG=]) -AC_SUBST(PIC_FLAG) - -# Test for __sync support. -AC_CACHE_CHECK([__sync extensions], -[libbacktrace_cv_sys_sync], -[if test -n "${with_target_subdir}"; then - case "${host}" in - hppa*-*-hpux*) libbacktrace_cv_sys_sync=no ;; - *) libbacktrace_cv_sys_sync=yes ;; - esac - else - AC_LINK_IFELSE( - [AC_LANG_PROGRAM([int i;], - [__sync_bool_compare_and_swap (&i, i, i); - __sync_lock_test_and_set (&i, 1); - __sync_lock_release (&i);])], - [libbacktrace_cv_sys_sync=yes], - [libbacktrace_cv_sys_sync=no]) - fi]) -BACKTRACE_SUPPORTS_THREADS=0 -if test "$libbacktrace_cv_sys_sync" = "yes"; then - BACKTRACE_SUPPORTS_THREADS=1 - AC_DEFINE([HAVE_SYNC_FUNCTIONS], 1, - [Define to 1 if you have the __sync functions]) -fi -AC_SUBST(BACKTRACE_SUPPORTS_THREADS) - -# Test for __atomic support. -AC_CACHE_CHECK([__atomic extensions], -[libbacktrace_cv_sys_atomic], -[if test -n "${with_target_subdir}"; then - libbacktrace_cv_sys_atomic=yes - else - AC_LINK_IFELSE( - [AC_LANG_PROGRAM([int i;], - [__atomic_load_n (&i, __ATOMIC_ACQUIRE); - __atomic_store_n (&i, 1, __ATOMIC_RELEASE);])], - [libbacktrace_cv_sys_atomic=yes], - [libbacktrace_cv_sys_atomic=no]) - fi]) -if test "$libbacktrace_cv_sys_atomic" = "yes"; then - AC_DEFINE([HAVE_ATOMIC_FUNCTIONS], 1, - [Define to 1 if you have the __atomic functions]) -fi - -# The library needs to be able to read the executable itself. Compile -# a file to determine the executable format. The awk script -# filetype.awk prints out the file type. -AC_CACHE_CHECK([output filetype], -[libbacktrace_cv_sys_filetype], -[filetype= -AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM([int i;], [int j;])], - [filetype=`${AWK} -f $srcdir/filetype.awk conftest.$ac_objext`], - [AC_MSG_FAILURE([compiler failed])]) -libbacktrace_cv_sys_filetype=$filetype]) - -# Match the file type to decide what files to compile. -FORMAT_FILE= -backtrace_supports_data=yes -case "$libbacktrace_cv_sys_filetype" in -elf*) FORMAT_FILE="elf.lo" ;; -pecoff) FORMAT_FILE="pecoff.lo" - backtrace_supports_data=no - ;; -xcoff*) FORMAT_FILE="xcoff.lo" - backtrace_supports_data=no - ;; -macho*) FORMAT_FILE="macho.lo" - backtrace_supports_data=no - ;; -*) AC_MSG_WARN([could not determine output file type]) - FORMAT_FILE="unknown.lo" - backtrace_supported=no - ;; -esac -AC_SUBST(FORMAT_FILE) - -# ELF defines. -elfsize= -case "$libbacktrace_cv_sys_filetype" in -elf32) elfsize=32 ;; -elf64) elfsize=64 ;; -*) elfsize=unused -esac -AC_DEFINE_UNQUOTED([BACKTRACE_ELF_SIZE], [$elfsize], [ELF size: 32 or 64]) - -# XCOFF defines. -xcoffsize= -case "$libbacktrace_cv_sys_filetype" in -xcoff32) xcoffsize=32 ;; -xcoff64) xcoffsize=64 ;; -*) xcoffsize=unused -esac -AC_DEFINE_UNQUOTED([BACKTRACE_XCOFF_SIZE], [$xcoffsize], [XCOFF size: 32 or 64]) - -BACKTRACE_SUPPORTED=0 -if test "$backtrace_supported" = "yes"; then - BACKTRACE_SUPPORTED=1 -fi -AC_SUBST(BACKTRACE_SUPPORTED) - -BACKTRACE_SUPPORTS_DATA=0 -if test "$backtrace_supports_data" = "yes"; then - BACKTRACE_SUPPORTS_DATA=1 -fi -AC_SUBST(BACKTRACE_SUPPORTS_DATA) - -AC_CHECK_HEADERS(sys/mman.h) -if test "$ac_cv_header_sys_mman_h" = "no"; then - have_mmap=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. We - # simply assume that if we have mman.h, we have mmap. - have_mmap=yes - case "${host}" in - spu-*-*|*-*-msdosdjgpp) - # The SPU does not have mmap, but it has a sys/mman.h header file - # containing "mmap_eaddr" and the mmap flags, confusing the test. - # DJGPP also has sys/man.h, but no mmap - have_mmap=no ;; - esac - else - AC_CHECK_FUNC(mmap, [have_mmap=yes], [have_mmap=no]) - fi -fi - -case "${host_os}" in -darwin*) - have_mmap=no ;; -esac - -if test "$have_mmap" = "no"; then - VIEW_FILE=read.lo - ALLOC_FILE=alloc.lo -else - VIEW_FILE=mmapio.lo - AC_PREPROC_IFELSE([ -#include -#if !defined(MAP_ANONYMOUS) && !defined(MAP_ANON) - #error no MAP_ANONYMOUS -#endif -], [ALLOC_FILE=mmap.lo], [ALLOC_FILE=alloc.lo]) -fi -AC_SUBST(VIEW_FILE) -AC_SUBST(ALLOC_FILE) - -BACKTRACE_USES_MALLOC=0 -if test "$ALLOC_FILE" = "alloc.lo"; then - BACKTRACE_USES_MALLOC=1 -fi -AC_SUBST(BACKTRACE_USES_MALLOC) - -# Check for dl_iterate_phdr. -AC_CHECK_HEADERS(link.h) -if test "$ac_cv_header_link_h" = "no"; then - have_dl_iterate_phdr=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. - AC_EGREP_HEADER([dl_iterate_phdr], [link.h], [have_dl_iterate_phdr=yes], - [have_dl_iterate_phdr=no]) - case "${host}" in - *-*-solaris2.10*) - # Avoid dl_iterate_phdr on Solaris 10, where it is in the - # header file but is only in -ldl. - have_dl_iterate_phdr=no ;; - esac - else - AC_CHECK_FUNC([dl_iterate_phdr], [have_dl_iterate_phdr=yes], - [have_dl_iterate_phdr=no]) - fi -fi -if test "$have_dl_iterate_phdr" = "yes"; then - AC_DEFINE(HAVE_DL_ITERATE_PHDR, 1, [Define if dl_iterate_phdr is available.]) -fi - -# Check for loadquery. -AC_CHECK_HEADERS(sys/ldr.h) -if test "$ac_cv_header_sys_ldr_h" = "no"; then - have_loadquery=no -else - if test -n "${with_target_subdir}"; then - # When built as a GCC target library, we can't do a link test. - AC_EGREP_HEADER([loadquery], [sys/ldr.h], [have_loadquery=yes], - [have_loadquery=no]) - else - AC_CHECK_FUNC([loadquery], [have_loadquery=yes], - [have_loadquery=no]) - fi -fi -if test "$have_loadquery" = "yes"; then - AC_DEFINE(HAVE_LOADQUERY, 1, [Define if AIX loadquery is available.]) -fi - -# Check for the fcntl function. -if test -n "${with_target_subdir}"; then - case "${host}" in - *-*-mingw*) have_fcntl=no ;; - spu-*-*) have_fcntl=no ;; - *) have_fcntl=yes ;; - esac -else - AC_CHECK_FUNC(fcntl, [have_fcntl=yes], [have_fcntl=no]) -fi -if test "$have_fcntl" = "yes"; then - AC_DEFINE([HAVE_FCNTL], 1, - [Define to 1 if you have the fcntl function]) -fi - -AC_CHECK_DECLS(strnlen) -AC_CHECK_FUNCS(lstat readlink) - -# Check for getexecname function. -if test -n "${with_target_subdir}"; then - case "${host}" in - *-*-solaris2*) have_getexecname=yes ;; - *) have_getexecname=no ;; - esac -else - AC_CHECK_FUNC(getexecname, [have_getexecname=yes], [have_getexecname=no]) -fi -if test "$have_getexecname" = "yes"; then - AC_DEFINE(HAVE_GETEXECNAME, 1, [Define if getexecname is available.]) -fi - -# Check for the clock_gettime function. -AC_CHECK_FUNCS(clock_gettime) -clock_gettime_link= -# At least for glibc, clock_gettime is in librt. But don't -# pull that in if it still doesn't give us the function we want. This -# test is copied from libgomp, and modified to not link in -lrt as -# we're using this for test timing only. -if test "$ac_cv_func_clock_gettime" = no; then - AC_CHECK_LIB(rt, clock_gettime, - [CLOCK_GETTIME_LINK=-lrt - AC_DEFINE(HAVE_CLOCK_GETTIME, 1, - [Define to 1 if you have the `clock_gettime' function.])]) -fi -AC_SUBST(CLOCK_GETTIME_LINK) - -dnl Test whether the compiler supports the -pthread option. -AC_CACHE_CHECK([whether -pthread is supported], -[libgo_cv_lib_pthread], -[CFLAGS_hold=$CFLAGS -CFLAGS="$CFLAGS -pthread" -AC_COMPILE_IFELSE([[int i;]], -[libgo_cv_lib_pthread=yes], -[libgo_cv_lib_pthread=no]) -CFLAGS=$CFLAGS_hold]) -PTHREAD_CFLAGS= -if test "$libgo_cv_lib_pthread" = yes; then - PTHREAD_CFLAGS=-pthread -fi -AC_SUBST(PTHREAD_CFLAGS) - -AM_CONDITIONAL(HAVE_PTHREAD, test "$libgo_cv_lib_pthread" = yes) - -AC_CHECK_LIB([z], [compress], []) -if test $ac_cv_lib_z_compress = "yes"; then - AC_DEFINE(HAVE_ZLIB, 1, [Define if -lz is available.]) -fi -AM_CONDITIONAL(HAVE_ZLIB, test "$ac_cv_lib_z_compress" = yes) - -dnl Test whether the linker supports the --compress_debug_sections option. -AC_CACHE_CHECK([whether --compress-debug-sections is supported], -[libgo_cv_ld_compress], -[LDFLAGS_hold=$LDFLAGS -LDFLAGS="$LDFLAGS -Wl,--compress-debug-sections=zlib-gnu" -AC_LINK_IFELSE([AC_LANG_PROGRAM(,)], -[libgo_cv_ld_compress=yes], -[libgo_cv_ld_compress=no]) -LDFLAGS=$LDFLAGS_hold]) -AM_CONDITIONAL(HAVE_COMPRESSED_DEBUG, test "$libgo_cv_ld_compress" = yes) - -AC_ARG_VAR(OBJCOPY, [location of objcopy]) -AC_CHECK_PROG(OBJCOPY, objcopy, objcopy,) -AC_CACHE_CHECK([whether objcopy supports debuglink], -[libbacktrace_cv_objcopy_debuglink], -[if test -n "${with_target_subdir}"; then - libbacktrace_cv_objcopy_debuglink=no -elif ${OBJCOPY} --add-gnu-debuglink=x /bin/ls /tmp/ls$$; then - rm -f /tmp/ls$$ - libbacktrace_cv_objcopy_debuglink=yes -else - libbacktrace_cv_objcopy_debuglink=no -fi]) -AM_CONDITIONAL(HAVE_OBJCOPY_DEBUGLINK, test "$libbacktrace_cv_objcopy_debuglink" = yes) - -AC_CACHE_CHECK([whether tests can run], - [libbacktrace_cv_sys_native], - [AC_RUN_IFELSE([AC_LANG_PROGRAM([], [return 0;])], - [libbacktrace_cv_sys_native=yes], - [libbacktrace_cv_sys_native=no], - [libbacktrace_cv_sys_native=no])]) -AM_CONDITIONAL(NATIVE, test "$libbacktrace_cv_sys_native" = "yes") - -if test "${multilib}" = "yes"; then - multilib_arg="--enable-multilib" -else - multilib_arg= -fi - -AC_CONFIG_FILES(Makefile backtrace-supported.h) - -# We need multilib support, but only if configuring for the target. -AC_CONFIG_COMMANDS([default], -[if test -n "$CONFIG_FILES"; then - if test -n "${with_target_subdir}"; then - # Multilibs need MULTISUBDIR defined correctly in certain makefiles so - # that multilib installs will end up installed in the correct place. - # The testsuite needs it for multilib-aware ABI baseline files. - # To work around this not being passed down from config-ml.in -> - # srcdir/Makefile.am -> srcdir/{src,libsupc++,...}/Makefile.am, manually - # append it here. Only modify Makefiles that have just been created. - # - # Also, get rid of this simulated-VPATH thing that automake does. - cat > vpsed << \_EOF - s!`test -f '$<' || echo '$(srcdir)/'`!! -_EOF - for i in $SUBDIRS; do - case $CONFIG_FILES in - *${i}/Makefile*) - #echo "Adding MULTISUBDIR to $i/Makefile" - sed -f vpsed $i/Makefile > tmp - grep '^MULTISUBDIR =' Makefile >> tmp - mv tmp $i/Makefile - ;; - esac - done - rm vpsed - fi - fi -], -[ -# Variables needed in config.status (file generation) which aren't already -# passed by autoconf. -SUBDIRS="$SUBDIRS" -]) - -AC_OUTPUT diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/dwarf.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/dwarf.c deleted file mode 100644 index 1bd1488..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/dwarf.c +++ /dev/null @@ -1,3126 +0,0 @@ -/* dwarf.c -- Get file/line information from DWARF for backtraces. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* DWARF constants. */ - -enum dwarf_tag { - DW_TAG_entry_point = 0x3, - DW_TAG_compile_unit = 0x11, - DW_TAG_inlined_subroutine = 0x1d, - DW_TAG_subprogram = 0x2e, -}; - -enum dwarf_form { - DW_FORM_addr = 0x1, - DW_FORM_block2 = 0x3, - DW_FORM_block4 = 0x4, - DW_FORM_data2 = 0x5, - DW_FORM_data4 = 0x6, - DW_FORM_data8 = 0x07, - DW_FORM_string = 0x08, - DW_FORM_block = 0x09, - DW_FORM_block1 = 0x0a, - DW_FORM_data1 = 0x0b, - DW_FORM_flag = 0x0c, - DW_FORM_sdata = 0x0d, - DW_FORM_strp = 0x0e, - DW_FORM_udata = 0x0f, - DW_FORM_ref_addr = 0x10, - DW_FORM_ref1 = 0x11, - DW_FORM_ref2 = 0x12, - DW_FORM_ref4 = 0x13, - DW_FORM_ref8 = 0x14, - DW_FORM_ref_udata = 0x15, - DW_FORM_indirect = 0x16, - DW_FORM_sec_offset = 0x17, - DW_FORM_exprloc = 0x18, - DW_FORM_flag_present = 0x19, - DW_FORM_ref_sig8 = 0x20, - DW_FORM_GNU_addr_index = 0x1f01, - DW_FORM_GNU_str_index = 0x1f02, - DW_FORM_GNU_ref_alt = 0x1f20, - DW_FORM_GNU_strp_alt = 0x1f21, -}; - -enum dwarf_attribute { - DW_AT_name = 0x3, - DW_AT_stmt_list = 0x10, - DW_AT_low_pc = 0x11, - DW_AT_high_pc = 0x12, - DW_AT_comp_dir = 0x1b, - DW_AT_abstract_origin = 0x31, - DW_AT_specification = 0x47, - DW_AT_ranges = 0x55, - DW_AT_call_file = 0x58, - DW_AT_call_line = 0x59, - DW_AT_linkage_name = 0x6e, - DW_AT_MIPS_linkage_name = 0x2007, -}; - -enum dwarf_line_number_op { - DW_LNS_extended_op = 0x0, - DW_LNS_copy = 0x1, - DW_LNS_advance_pc = 0x2, - DW_LNS_advance_line = 0x3, - DW_LNS_set_file = 0x4, - DW_LNS_set_column = 0x5, - DW_LNS_negate_stmt = 0x6, - DW_LNS_set_basic_block = 0x7, - DW_LNS_const_add_pc = 0x8, - DW_LNS_fixed_advance_pc = 0x9, - DW_LNS_set_prologue_end = 0xa, - DW_LNS_set_epilogue_begin = 0xb, - DW_LNS_set_isa = 0xc, -}; - -enum dwarf_extedned_line_number_op { - DW_LNE_end_sequence = 0x1, - DW_LNE_set_address = 0x2, - DW_LNE_define_file = 0x3, - DW_LNE_set_discriminator = 0x4, -}; - -#if defined(__MSDOS__) || defined(_WIN32) || defined(__OS2__) || defined (__CYGWIN__) -# define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == '\\') -#define HAS_DRIVE_SPEC(f) ((f)[0] && (f)[1] == ':') -# define IS_ABSOLUTE_PATH(f) (IS_DIR_SEPARATOR(f[0]) || HAS_DRIVE_SPEC(f)) -#else -# define IS_DIR_SEPARATOR(c) ((c) == '/') -# define IS_ABSOLUTE_PATH(f) IS_DIR_SEPARATOR(f[0]) -#endif - -#if !defined(HAVE_DECL_STRNLEN) || !HAVE_DECL_STRNLEN - -/* If strnlen is not declared, provide our own version. */ - -static size_t -xstrnlen (const char *s, size_t maxlen) -{ - size_t i; - - for (i = 0; i < maxlen; ++i) - if (s[i] == '\0') - break; - return i; -} - -#define strnlen xstrnlen - -#endif - -/* A buffer to read DWARF info. */ - -struct dwarf_buf -{ - /* Buffer name for error messages. */ - const char *name; - /* Start of the buffer. */ - const unsigned char *start; - /* Next byte to read. */ - const unsigned char *buf; - /* The number of bytes remaining. */ - size_t left; - /* Whether the data is big-endian. */ - int is_bigendian; - /* Error callback routine. */ - backtrace_error_callback error_callback; - /* Data for error_callback. */ - void *data; - /* Non-zero if we've reported an underflow error. */ - int reported_underflow; -}; - -/* A single attribute in a DWARF abbreviation. */ - -struct attr -{ - /* The attribute name. */ - enum dwarf_attribute name; - /* The attribute form. */ - enum dwarf_form form; -}; - -/* A single DWARF abbreviation. */ - -struct abbrev -{ - /* The abbrev code--the number used to refer to the abbrev. */ - uint64_t code; - /* The entry tag. */ - enum dwarf_tag tag; - /* Non-zero if this abbrev has child entries. */ - int has_children; - /* The number of attributes. */ - size_t num_attrs; - /* The attributes. */ - struct attr *attrs; -}; - -/* The DWARF abbreviations for a compilation unit. This structure - only exists while reading the compilation unit. Most DWARF readers - seem to a hash table to map abbrev ID's to abbrev entries. - However, we primarily care about GCC, and GCC simply issues ID's in - numerical order starting at 1. So we simply keep a sorted vector, - and try to just look up the code. */ - -struct abbrevs -{ - /* The number of abbrevs in the vector. */ - size_t num_abbrevs; - /* The abbrevs, sorted by the code field. */ - struct abbrev *abbrevs; -}; - -/* The different kinds of attribute values. */ - -enum attr_val_encoding -{ - /* An address. */ - ATTR_VAL_ADDRESS, - /* A unsigned integer. */ - ATTR_VAL_UINT, - /* A sigd integer. */ - ATTR_VAL_SINT, - /* A string. */ - ATTR_VAL_STRING, - /* An offset to other data in the containing unit. */ - ATTR_VAL_REF_UNIT, - /* An offset to other data within the .dwarf_info section. */ - ATTR_VAL_REF_INFO, - /* An offset to data in some other section. */ - ATTR_VAL_REF_SECTION, - /* A type signature. */ - ATTR_VAL_REF_TYPE, - /* A block of data (not represented). */ - ATTR_VAL_BLOCK, - /* An expression (not represented). */ - ATTR_VAL_EXPR, -}; - -/* An attribute value. */ - -struct attr_val -{ - /* How the value is stored in the field u. */ - enum attr_val_encoding encoding; - union - { - /* ATTR_VAL_ADDRESS, ATTR_VAL_UINT, ATTR_VAL_REF*. */ - uint64_t uint; - /* ATTR_VAL_SINT. */ - int64_t sint; - /* ATTR_VAL_STRING. */ - const char *string; - /* ATTR_VAL_BLOCK not stored. */ - } u; -}; - -/* The line number program header. */ - -struct line_header -{ - /* The version of the line number information. */ - int version; - /* The minimum instruction length. */ - unsigned int min_insn_len; - /* The maximum number of ops per instruction. */ - unsigned int max_ops_per_insn; - /* The line base for special opcodes. */ - int line_base; - /* The line range for special opcodes. */ - unsigned int line_range; - /* The opcode base--the first special opcode. */ - unsigned int opcode_base; - /* Opcode lengths, indexed by opcode - 1. */ - const unsigned char *opcode_lengths; - /* The number of directory entries. */ - size_t dirs_count; - /* The directory entries. */ - const char **dirs; - /* The number of filenames. */ - size_t filenames_count; - /* The filenames. */ - const char **filenames; -}; - -/* Map a single PC value to a file/line. We will keep a vector of - these sorted by PC value. Each file/line will be correct from the - PC up to the PC of the next entry if there is one. We allocate one - extra entry at the end so that we can use bsearch. */ - -struct line -{ - /* PC. */ - uintptr_t pc; - /* File name. Many entries in the array are expected to point to - the same file name. */ - const char *filename; - /* Line number. */ - int lineno; - /* Index of the object in the original array read from the DWARF - section, before it has been sorted. The index makes it possible - to use Quicksort and maintain stability. */ - int idx; -}; - -/* A growable vector of line number information. This is used while - reading the line numbers. */ - -struct line_vector -{ - /* Memory. This is an array of struct line. */ - struct backtrace_vector vec; - /* Number of valid mappings. */ - size_t count; -}; - -/* A function described in the debug info. */ - -struct function -{ - /* The name of the function. */ - const char *name; - /* If this is an inlined function, the filename of the call - site. */ - const char *caller_filename; - /* If this is an inlined function, the line number of the call - site. */ - int caller_lineno; - /* Map PC ranges to inlined functions. */ - struct function_addrs *function_addrs; - size_t function_addrs_count; -}; - -/* An address range for a function. This maps a PC value to a - specific function. */ - -struct function_addrs -{ - /* Range is LOW <= PC < HIGH. */ - uint64_t low; - uint64_t high; - /* Function for this address range. */ - struct function *function; -}; - -/* A growable vector of function address ranges. */ - -struct function_vector -{ - /* Memory. This is an array of struct function_addrs. */ - struct backtrace_vector vec; - /* Number of address ranges present. */ - size_t count; -}; - -/* A DWARF compilation unit. This only holds the information we need - to map a PC to a file and line. */ - -struct unit -{ - /* The first entry for this compilation unit. */ - const unsigned char *unit_data; - /* The length of the data for this compilation unit. */ - size_t unit_data_len; - /* The offset of UNIT_DATA from the start of the information for - this compilation unit. */ - size_t unit_data_offset; - /* DWARF version. */ - int version; - /* Whether unit is DWARF64. */ - int is_dwarf64; - /* Address size. */ - int addrsize; - /* Offset into line number information. */ - off_t lineoff; - /* Primary source file. */ - const char *filename; - /* Compilation command working directory. */ - const char *comp_dir; - /* Absolute file name, only set if needed. */ - const char *abs_filename; - /* The abbreviations for this unit. */ - struct abbrevs abbrevs; - - /* The fields above this point are read in during initialization and - may be accessed freely. The fields below this point are read in - as needed, and therefore require care, as different threads may - try to initialize them simultaneously. */ - - /* PC to line number mapping. This is NULL if the values have not - been read. This is (struct line *) -1 if there was an error - reading the values. */ - struct line *lines; - /* Number of entries in lines. */ - size_t lines_count; - /* PC ranges to function. */ - struct function_addrs *function_addrs; - size_t function_addrs_count; -}; - -/* An address range for a compilation unit. This maps a PC value to a - specific compilation unit. Note that we invert the representation - in DWARF: instead of listing the units and attaching a list of - ranges, we list the ranges and have each one point to the unit. - This lets us do a binary search to find the unit. */ - -struct unit_addrs -{ - /* Range is LOW <= PC < HIGH. */ - uint64_t low; - uint64_t high; - /* Compilation unit for this address range. */ - struct unit *u; -}; - -/* A growable vector of compilation unit address ranges. */ - -struct unit_addrs_vector -{ - /* Memory. This is an array of struct unit_addrs. */ - struct backtrace_vector vec; - /* Number of address ranges present. */ - size_t count; -}; - -/* The information we need to map a PC to a file and line. */ - -struct dwarf_data -{ - /* The data for the next file we know about. */ - struct dwarf_data *next; - /* The base address for this file. */ - uintptr_t base_address; - /* A sorted list of address ranges. */ - struct unit_addrs *addrs; - /* Number of address ranges in list. */ - size_t addrs_count; - /* The unparsed .debug_info section. */ - const unsigned char *dwarf_info; - size_t dwarf_info_size; - /* The unparsed .debug_line section. */ - const unsigned char *dwarf_line; - size_t dwarf_line_size; - /* The unparsed .debug_ranges section. */ - const unsigned char *dwarf_ranges; - size_t dwarf_ranges_size; - /* The unparsed .debug_str section. */ - const unsigned char *dwarf_str; - size_t dwarf_str_size; - /* Whether the data is big-endian or not. */ - int is_bigendian; - /* A vector used for function addresses. We keep this here so that - we can grow the vector as we read more functions. */ - struct function_vector fvec; -}; - -/* Report an error for a DWARF buffer. */ - -static void -dwarf_buf_error (struct dwarf_buf *buf, const char *msg) -{ - char b[200]; - - snprintf (b, sizeof b, "%s in %s at %d", - msg, buf->name, (int) (buf->buf - buf->start)); - buf->error_callback (buf->data, b, 0); -} - -/* Require at least COUNT bytes in BUF. Return 1 if all is well, 0 on - error. */ - -static int -require (struct dwarf_buf *buf, size_t count) -{ - if (buf->left >= count) - return 1; - - if (!buf->reported_underflow) - { - dwarf_buf_error (buf, "DWARF underflow"); - buf->reported_underflow = 1; - } - - return 0; -} - -/* Advance COUNT bytes in BUF. Return 1 if all is well, 0 on - error. */ - -static int -advance (struct dwarf_buf *buf, size_t count) -{ - if (!require (buf, count)) - return 0; - buf->buf += count; - buf->left -= count; - return 1; -} - -/* Read one byte from BUF and advance 1 byte. */ - -static unsigned char -read_byte (struct dwarf_buf *buf) -{ - const unsigned char *p = buf->buf; - - if (!advance (buf, 1)) - return 0; - return p[0]; -} - -/* Read a signed char from BUF and advance 1 byte. */ - -static signed char -read_sbyte (struct dwarf_buf *buf) -{ - const unsigned char *p = buf->buf; - - if (!advance (buf, 1)) - return 0; - return (*p ^ 0x80) - 0x80; -} - -/* Read a uint16 from BUF and advance 2 bytes. */ - -static uint16_t -read_uint16 (struct dwarf_buf *buf) -{ - const unsigned char *p = buf->buf; - - if (!advance (buf, 2)) - return 0; - if (buf->is_bigendian) - return ((uint16_t) p[0] << 8) | (uint16_t) p[1]; - else - return ((uint16_t) p[1] << 8) | (uint16_t) p[0]; -} - -/* Read a uint32 from BUF and advance 4 bytes. */ - -static uint32_t -read_uint32 (struct dwarf_buf *buf) -{ - const unsigned char *p = buf->buf; - - if (!advance (buf, 4)) - return 0; - if (buf->is_bigendian) - return (((uint32_t) p[0] << 24) | ((uint32_t) p[1] << 16) - | ((uint32_t) p[2] << 8) | (uint32_t) p[3]); - else - return (((uint32_t) p[3] << 24) | ((uint32_t) p[2] << 16) - | ((uint32_t) p[1] << 8) | (uint32_t) p[0]); -} - -/* Read a uint64 from BUF and advance 8 bytes. */ - -static uint64_t -read_uint64 (struct dwarf_buf *buf) -{ - const unsigned char *p = buf->buf; - - if (!advance (buf, 8)) - return 0; - if (buf->is_bigendian) - return (((uint64_t) p[0] << 56) | ((uint64_t) p[1] << 48) - | ((uint64_t) p[2] << 40) | ((uint64_t) p[3] << 32) - | ((uint64_t) p[4] << 24) | ((uint64_t) p[5] << 16) - | ((uint64_t) p[6] << 8) | (uint64_t) p[7]); - else - return (((uint64_t) p[7] << 56) | ((uint64_t) p[6] << 48) - | ((uint64_t) p[5] << 40) | ((uint64_t) p[4] << 32) - | ((uint64_t) p[3] << 24) | ((uint64_t) p[2] << 16) - | ((uint64_t) p[1] << 8) | (uint64_t) p[0]); -} - -/* Read an offset from BUF and advance the appropriate number of - bytes. */ - -static uint64_t -read_offset (struct dwarf_buf *buf, int is_dwarf64) -{ - if (is_dwarf64) - return read_uint64 (buf); - else - return read_uint32 (buf); -} - -/* Read an address from BUF and advance the appropriate number of - bytes. */ - -static uint64_t -read_address (struct dwarf_buf *buf, int addrsize) -{ - switch (addrsize) - { - case 1: - return read_byte (buf); - case 2: - return read_uint16 (buf); - case 4: - return read_uint32 (buf); - case 8: - return read_uint64 (buf); - default: - dwarf_buf_error (buf, "unrecognized address size"); - return 0; - } -} - -/* Return whether a value is the highest possible address, given the - address size. */ - -static int -is_highest_address (uint64_t address, int addrsize) -{ - switch (addrsize) - { - case 1: - return address == (unsigned char) -1; - case 2: - return address == (uint16_t) -1; - case 4: - return address == (uint32_t) -1; - case 8: - return address == (uint64_t) -1; - default: - return 0; - } -} - -/* Read an unsigned LEB128 number. */ - -static uint64_t -read_uleb128 (struct dwarf_buf *buf) -{ - uint64_t ret; - unsigned int shift; - int overflow; - unsigned char b; - - ret = 0; - shift = 0; - overflow = 0; - do - { - const unsigned char *p; - - p = buf->buf; - if (!advance (buf, 1)) - return 0; - b = *p; - if (shift < 64) - ret |= ((uint64_t) (b & 0x7f)) << shift; - else if (!overflow) - { - dwarf_buf_error (buf, "LEB128 overflows uint64_t"); - overflow = 1; - } - shift += 7; - } - while ((b & 0x80) != 0); - - return ret; -} - -/* Read a signed LEB128 number. */ - -static int64_t -read_sleb128 (struct dwarf_buf *buf) -{ - uint64_t val; - unsigned int shift; - int overflow; - unsigned char b; - - val = 0; - shift = 0; - overflow = 0; - do - { - const unsigned char *p; - - p = buf->buf; - if (!advance (buf, 1)) - return 0; - b = *p; - if (shift < 64) - val |= ((uint64_t) (b & 0x7f)) << shift; - else if (!overflow) - { - dwarf_buf_error (buf, "signed LEB128 overflows uint64_t"); - overflow = 1; - } - shift += 7; - } - while ((b & 0x80) != 0); - - if ((b & 0x40) != 0 && shift < 64) - val |= ((uint64_t) -1) << shift; - - return (int64_t) val; -} - -/* Return the length of an LEB128 number. */ - -static size_t -leb128_len (const unsigned char *p) -{ - size_t ret; - - ret = 1; - while ((*p & 0x80) != 0) - { - ++p; - ++ret; - } - return ret; -} - -/* Free an abbreviations structure. */ - -static void -free_abbrevs (struct backtrace_state *state, struct abbrevs *abbrevs, - backtrace_error_callback error_callback, void *data) -{ - size_t i; - - for (i = 0; i < abbrevs->num_abbrevs; ++i) - backtrace_free (state, abbrevs->abbrevs[i].attrs, - abbrevs->abbrevs[i].num_attrs * sizeof (struct attr), - error_callback, data); - backtrace_free (state, abbrevs->abbrevs, - abbrevs->num_abbrevs * sizeof (struct abbrev), - error_callback, data); - abbrevs->num_abbrevs = 0; - abbrevs->abbrevs = NULL; -} - -/* Read an attribute value. Returns 1 on success, 0 on failure. If - the value can be represented as a uint64_t, sets *VAL and sets - *IS_VALID to 1. We don't try to store the value of other attribute - forms, because we don't care about them. */ - -static int -read_attribute (enum dwarf_form form, struct dwarf_buf *buf, - int is_dwarf64, int version, int addrsize, - const unsigned char *dwarf_str, size_t dwarf_str_size, - struct attr_val *val) -{ - /* Avoid warnings about val.u.FIELD may be used uninitialized if - this function is inlined. The warnings aren't valid but can - occur because the different fields are set and used - conditionally. */ - memset (val, 0, sizeof *val); - - switch (form) - { - case DW_FORM_addr: - val->encoding = ATTR_VAL_ADDRESS; - val->u.uint = read_address (buf, addrsize); - return 1; - case DW_FORM_block2: - val->encoding = ATTR_VAL_BLOCK; - return advance (buf, read_uint16 (buf)); - case DW_FORM_block4: - val->encoding = ATTR_VAL_BLOCK; - return advance (buf, read_uint32 (buf)); - case DW_FORM_data2: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_uint16 (buf); - return 1; - case DW_FORM_data4: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_uint32 (buf); - return 1; - case DW_FORM_data8: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_uint64 (buf); - return 1; - case DW_FORM_string: - val->encoding = ATTR_VAL_STRING; - val->u.string = (const char *) buf->buf; - return advance (buf, strnlen ((const char *) buf->buf, buf->left) + 1); - case DW_FORM_block: - val->encoding = ATTR_VAL_BLOCK; - return advance (buf, read_uleb128 (buf)); - case DW_FORM_block1: - val->encoding = ATTR_VAL_BLOCK; - return advance (buf, read_byte (buf)); - case DW_FORM_data1: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_byte (buf); - return 1; - case DW_FORM_flag: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_byte (buf); - return 1; - case DW_FORM_sdata: - val->encoding = ATTR_VAL_SINT; - val->u.sint = read_sleb128 (buf); - return 1; - case DW_FORM_strp: - { - uint64_t offset; - - offset = read_offset (buf, is_dwarf64); - if (offset >= dwarf_str_size) - { - dwarf_buf_error (buf, "DW_FORM_strp out of range"); - return 0; - } - val->encoding = ATTR_VAL_STRING; - val->u.string = (const char *) dwarf_str + offset; - return 1; - } - case DW_FORM_udata: - val->encoding = ATTR_VAL_UINT; - val->u.uint = read_uleb128 (buf); - return 1; - case DW_FORM_ref_addr: - val->encoding = ATTR_VAL_REF_INFO; - if (version == 2) - val->u.uint = read_address (buf, addrsize); - else - val->u.uint = read_offset (buf, is_dwarf64); - return 1; - case DW_FORM_ref1: - val->encoding = ATTR_VAL_REF_UNIT; - val->u.uint = read_byte (buf); - return 1; - case DW_FORM_ref2: - val->encoding = ATTR_VAL_REF_UNIT; - val->u.uint = read_uint16 (buf); - return 1; - case DW_FORM_ref4: - val->encoding = ATTR_VAL_REF_UNIT; - val->u.uint = read_uint32 (buf); - return 1; - case DW_FORM_ref8: - val->encoding = ATTR_VAL_REF_UNIT; - val->u.uint = read_uint64 (buf); - return 1; - case DW_FORM_ref_udata: - val->encoding = ATTR_VAL_REF_UNIT; - val->u.uint = read_uleb128 (buf); - return 1; - case DW_FORM_indirect: - { - uint64_t form; - - form = read_uleb128 (buf); - return read_attribute ((enum dwarf_form) form, buf, is_dwarf64, - version, addrsize, dwarf_str, dwarf_str_size, - val); - } - case DW_FORM_sec_offset: - val->encoding = ATTR_VAL_REF_SECTION; - val->u.uint = read_offset (buf, is_dwarf64); - return 1; - case DW_FORM_exprloc: - val->encoding = ATTR_VAL_EXPR; - return advance (buf, read_uleb128 (buf)); - case DW_FORM_flag_present: - val->encoding = ATTR_VAL_UINT; - val->u.uint = 1; - return 1; - case DW_FORM_ref_sig8: - val->encoding = ATTR_VAL_REF_TYPE; - val->u.uint = read_uint64 (buf); - return 1; - case DW_FORM_GNU_addr_index: - val->encoding = ATTR_VAL_REF_SECTION; - val->u.uint = read_uleb128 (buf); - return 1; - case DW_FORM_GNU_str_index: - val->encoding = ATTR_VAL_REF_SECTION; - val->u.uint = read_uleb128 (buf); - return 1; - case DW_FORM_GNU_ref_alt: - val->encoding = ATTR_VAL_REF_SECTION; - val->u.uint = read_offset (buf, is_dwarf64); - return 1; - case DW_FORM_GNU_strp_alt: - val->encoding = ATTR_VAL_REF_SECTION; - val->u.uint = read_offset (buf, is_dwarf64); - return 1; - default: - dwarf_buf_error (buf, "unrecognized DWARF form"); - return 0; - } -} - -/* Compare function_addrs for qsort. When ranges are nested, make the - smallest one sort last. */ - -static int -function_addrs_compare (const void *v1, const void *v2) -{ - const struct function_addrs *a1 = (const struct function_addrs *) v1; - const struct function_addrs *a2 = (const struct function_addrs *) v2; - - if (a1->low < a2->low) - return -1; - if (a1->low > a2->low) - return 1; - if (a1->high < a2->high) - return 1; - if (a1->high > a2->high) - return -1; - return strcmp (a1->function->name, a2->function->name); -} - -/* Compare a PC against a function_addrs for bsearch. Note that if - there are multiple ranges containing PC, which one will be returned - is unpredictable. We compensate for that in dwarf_fileline. */ - -static int -function_addrs_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct function_addrs *entry = (const struct function_addrs *) ventry; - uintptr_t pc; - - pc = *key; - if (pc < entry->low) - return -1; - else if (pc >= entry->high) - return 1; - else - return 0; -} - -/* Add a new compilation unit address range to a vector. Returns 1 on - success, 0 on failure. */ - -static int -add_unit_addr (struct backtrace_state *state, uintptr_t base_address, - struct unit_addrs addrs, - backtrace_error_callback error_callback, void *data, - struct unit_addrs_vector *vec) -{ - struct unit_addrs *p; - - /* Add in the base address of the module here, so that we can look - up the PC directly. */ - addrs.low += base_address; - addrs.high += base_address; - - /* Try to merge with the last entry. */ - if (vec->count > 0) - { - p = (struct unit_addrs *) vec->vec.base + (vec->count - 1); - if ((addrs.low == p->high || addrs.low == p->high + 1) - && addrs.u == p->u) - { - if (addrs.high > p->high) - p->high = addrs.high; - return 1; - } - } - - p = ((struct unit_addrs *) - backtrace_vector_grow (state, sizeof (struct unit_addrs), - error_callback, data, &vec->vec)); - if (p == NULL) - return 0; - - *p = addrs; - ++vec->count; - return 1; -} - -/* Free a unit address vector. */ - -static void -free_unit_addrs_vector (struct backtrace_state *state, - struct unit_addrs_vector *vec, - backtrace_error_callback error_callback, void *data) -{ - struct unit_addrs *addrs; - size_t i; - - addrs = (struct unit_addrs *) vec->vec.base; - for (i = 0; i < vec->count; ++i) - free_abbrevs (state, &addrs[i].u->abbrevs, error_callback, data); -} - -/* Compare unit_addrs for qsort. When ranges are nested, make the - smallest one sort last. */ - -static int -unit_addrs_compare (const void *v1, const void *v2) -{ - const struct unit_addrs *a1 = (const struct unit_addrs *) v1; - const struct unit_addrs *a2 = (const struct unit_addrs *) v2; - - if (a1->low < a2->low) - return -1; - if (a1->low > a2->low) - return 1; - if (a1->high < a2->high) - return 1; - if (a1->high > a2->high) - return -1; - if (a1->u->lineoff < a2->u->lineoff) - return -1; - if (a1->u->lineoff > a2->u->lineoff) - return 1; - return 0; -} - -/* Compare a PC against a unit_addrs for bsearch. Note that if there - are multiple ranges containing PC, which one will be returned is - unpredictable. We compensate for that in dwarf_fileline. */ - -static int -unit_addrs_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct unit_addrs *entry = (const struct unit_addrs *) ventry; - uintptr_t pc; - - pc = *key; - if (pc < entry->low) - return -1; - else if (pc >= entry->high) - return 1; - else - return 0; -} - -/* Sort the line vector by PC. We want a stable sort here to maintain - the order of lines for the same PC values. Since the sequence is - being sorted in place, their addresses cannot be relied on to - maintain stability. That is the purpose of the index member. */ - -static int -line_compare (const void *v1, const void *v2) -{ - const struct line *ln1 = (const struct line *) v1; - const struct line *ln2 = (const struct line *) v2; - - if (ln1->pc < ln2->pc) - return -1; - else if (ln1->pc > ln2->pc) - return 1; - else if (ln1->idx < ln2->idx) - return -1; - else if (ln1->idx > ln2->idx) - return 1; - else - return 0; -} - -/* Find a PC in a line vector. We always allocate an extra entry at - the end of the lines vector, so that this routine can safely look - at the next entry. Note that when there are multiple mappings for - the same PC value, this will return the last one. */ - -static int -line_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct line *entry = (const struct line *) ventry; - uintptr_t pc; - - pc = *key; - if (pc < entry->pc) - return -1; - else if (pc >= (entry + 1)->pc) - return 1; - else - return 0; -} - -/* Sort the abbrevs by the abbrev code. This function is passed to - both qsort and bsearch. */ - -static int -abbrev_compare (const void *v1, const void *v2) -{ - const struct abbrev *a1 = (const struct abbrev *) v1; - const struct abbrev *a2 = (const struct abbrev *) v2; - - if (a1->code < a2->code) - return -1; - else if (a1->code > a2->code) - return 1; - else - { - /* This really shouldn't happen. It means there are two - different abbrevs with the same code, and that means we don't - know which one lookup_abbrev should return. */ - return 0; - } -} - -/* Read the abbreviation table for a compilation unit. Returns 1 on - success, 0 on failure. */ - -static int -read_abbrevs (struct backtrace_state *state, uint64_t abbrev_offset, - const unsigned char *dwarf_abbrev, size_t dwarf_abbrev_size, - int is_bigendian, backtrace_error_callback error_callback, - void *data, struct abbrevs *abbrevs) -{ - struct dwarf_buf abbrev_buf; - struct dwarf_buf count_buf; - size_t num_abbrevs; - - abbrevs->num_abbrevs = 0; - abbrevs->abbrevs = NULL; - - if (abbrev_offset >= dwarf_abbrev_size) - { - error_callback (data, "abbrev offset out of range", 0); - return 0; - } - - abbrev_buf.name = ".debug_abbrev"; - abbrev_buf.start = dwarf_abbrev; - abbrev_buf.buf = dwarf_abbrev + abbrev_offset; - abbrev_buf.left = dwarf_abbrev_size - abbrev_offset; - abbrev_buf.is_bigendian = is_bigendian; - abbrev_buf.error_callback = error_callback; - abbrev_buf.data = data; - abbrev_buf.reported_underflow = 0; - - /* Count the number of abbrevs in this list. */ - - count_buf = abbrev_buf; - num_abbrevs = 0; - while (read_uleb128 (&count_buf) != 0) - { - if (count_buf.reported_underflow) - return 0; - ++num_abbrevs; - // Skip tag. - read_uleb128 (&count_buf); - // Skip has_children. - read_byte (&count_buf); - // Skip attributes. - while (read_uleb128 (&count_buf) != 0) - read_uleb128 (&count_buf); - // Skip form of last attribute. - read_uleb128 (&count_buf); - } - - if (count_buf.reported_underflow) - return 0; - - if (num_abbrevs == 0) - return 1; - - abbrevs->num_abbrevs = num_abbrevs; - abbrevs->abbrevs = ((struct abbrev *) - backtrace_alloc (state, - num_abbrevs * sizeof (struct abbrev), - error_callback, data)); - if (abbrevs->abbrevs == NULL) - return 0; - memset (abbrevs->abbrevs, 0, num_abbrevs * sizeof (struct abbrev)); - - num_abbrevs = 0; - while (1) - { - uint64_t code; - struct abbrev a; - size_t num_attrs; - struct attr *attrs; - - if (abbrev_buf.reported_underflow) - goto fail; - - code = read_uleb128 (&abbrev_buf); - if (code == 0) - break; - - a.code = code; - a.tag = (enum dwarf_tag) read_uleb128 (&abbrev_buf); - a.has_children = read_byte (&abbrev_buf); - - count_buf = abbrev_buf; - num_attrs = 0; - while (read_uleb128 (&count_buf) != 0) - { - ++num_attrs; - read_uleb128 (&count_buf); - } - - if (num_attrs == 0) - { - attrs = NULL; - read_uleb128 (&abbrev_buf); - read_uleb128 (&abbrev_buf); - } - else - { - attrs = ((struct attr *) - backtrace_alloc (state, num_attrs * sizeof *attrs, - error_callback, data)); - if (attrs == NULL) - goto fail; - num_attrs = 0; - while (1) - { - uint64_t name; - uint64_t form; - - name = read_uleb128 (&abbrev_buf); - form = read_uleb128 (&abbrev_buf); - if (name == 0) - break; - attrs[num_attrs].name = (enum dwarf_attribute) name; - attrs[num_attrs].form = (enum dwarf_form) form; - ++num_attrs; - } - } - - a.num_attrs = num_attrs; - a.attrs = attrs; - - abbrevs->abbrevs[num_abbrevs] = a; - ++num_abbrevs; - } - - backtrace_qsort (abbrevs->abbrevs, abbrevs->num_abbrevs, - sizeof (struct abbrev), abbrev_compare); - - return 1; - - fail: - free_abbrevs (state, abbrevs, error_callback, data); - return 0; -} - -/* Return the abbrev information for an abbrev code. */ - -static const struct abbrev * -lookup_abbrev (struct abbrevs *abbrevs, uint64_t code, - backtrace_error_callback error_callback, void *data) -{ - struct abbrev key; - void *p; - - /* With GCC, where abbrevs are simply numbered in order, we should - be able to just look up the entry. */ - if (code - 1 < abbrevs->num_abbrevs - && abbrevs->abbrevs[code - 1].code == code) - return &abbrevs->abbrevs[code - 1]; - - /* Otherwise we have to search. */ - memset (&key, 0, sizeof key); - key.code = code; - p = bsearch (&key, abbrevs->abbrevs, abbrevs->num_abbrevs, - sizeof (struct abbrev), abbrev_compare); - if (p == NULL) - { - error_callback (data, "invalid abbreviation code", 0); - return NULL; - } - return (const struct abbrev *) p; -} - -/* Add non-contiguous address ranges for a compilation unit. Returns - 1 on success, 0 on failure. */ - -static int -add_unit_ranges (struct backtrace_state *state, uintptr_t base_address, - struct unit *u, uint64_t ranges, uint64_t base, - int is_bigendian, const unsigned char *dwarf_ranges, - size_t dwarf_ranges_size, - backtrace_error_callback error_callback, void *data, - struct unit_addrs_vector *addrs) -{ - struct dwarf_buf ranges_buf; - - if (ranges >= dwarf_ranges_size) - { - error_callback (data, "ranges offset out of range", 0); - return 0; - } - - ranges_buf.name = ".debug_ranges"; - ranges_buf.start = dwarf_ranges; - ranges_buf.buf = dwarf_ranges + ranges; - ranges_buf.left = dwarf_ranges_size - ranges; - ranges_buf.is_bigendian = is_bigendian; - ranges_buf.error_callback = error_callback; - ranges_buf.data = data; - ranges_buf.reported_underflow = 0; - - while (1) - { - uint64_t low; - uint64_t high; - - if (ranges_buf.reported_underflow) - return 0; - - low = read_address (&ranges_buf, u->addrsize); - high = read_address (&ranges_buf, u->addrsize); - - if (low == 0 && high == 0) - break; - - if (is_highest_address (low, u->addrsize)) - base = high; - else - { - struct unit_addrs a; - - a.low = low + base; - a.high = high + base; - a.u = u; - if (!add_unit_addr (state, base_address, a, error_callback, data, - addrs)) - return 0; - } - } - - if (ranges_buf.reported_underflow) - return 0; - - return 1; -} - -/* Find the address range covered by a compilation unit, reading from - UNIT_BUF and adding values to U. Returns 1 if all data could be - read, 0 if there is some error. */ - -static int -find_address_ranges (struct backtrace_state *state, uintptr_t base_address, - struct dwarf_buf *unit_buf, - const unsigned char *dwarf_str, size_t dwarf_str_size, - const unsigned char *dwarf_ranges, - size_t dwarf_ranges_size, - int is_bigendian, backtrace_error_callback error_callback, - void *data, struct unit *u, - struct unit_addrs_vector *addrs) -{ - while (unit_buf->left > 0) - { - uint64_t code; - const struct abbrev *abbrev; - uint64_t lowpc; - int have_lowpc; - uint64_t highpc; - int have_highpc; - int highpc_is_relative; - uint64_t ranges; - int have_ranges; - size_t i; - - code = read_uleb128 (unit_buf); - if (code == 0) - return 1; - - abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data); - if (abbrev == NULL) - return 0; - - lowpc = 0; - have_lowpc = 0; - highpc = 0; - have_highpc = 0; - highpc_is_relative = 0; - ranges = 0; - have_ranges = 0; - for (i = 0; i < abbrev->num_attrs; ++i) - { - struct attr_val val; - - if (!read_attribute (abbrev->attrs[i].form, unit_buf, - u->is_dwarf64, u->version, u->addrsize, - dwarf_str, dwarf_str_size, &val)) - return 0; - - switch (abbrev->attrs[i].name) - { - case DW_AT_low_pc: - if (val.encoding == ATTR_VAL_ADDRESS) - { - lowpc = val.u.uint; - have_lowpc = 1; - } - break; - - case DW_AT_high_pc: - if (val.encoding == ATTR_VAL_ADDRESS) - { - highpc = val.u.uint; - have_highpc = 1; - } - else if (val.encoding == ATTR_VAL_UINT) - { - highpc = val.u.uint; - have_highpc = 1; - highpc_is_relative = 1; - } - break; - - case DW_AT_ranges: - if (val.encoding == ATTR_VAL_UINT - || val.encoding == ATTR_VAL_REF_SECTION) - { - ranges = val.u.uint; - have_ranges = 1; - } - break; - - case DW_AT_stmt_list: - if (abbrev->tag == DW_TAG_compile_unit - && (val.encoding == ATTR_VAL_UINT - || val.encoding == ATTR_VAL_REF_SECTION)) - u->lineoff = val.u.uint; - break; - - case DW_AT_name: - if (abbrev->tag == DW_TAG_compile_unit - && val.encoding == ATTR_VAL_STRING) - u->filename = val.u.string; - break; - - case DW_AT_comp_dir: - if (abbrev->tag == DW_TAG_compile_unit - && val.encoding == ATTR_VAL_STRING) - u->comp_dir = val.u.string; - break; - - default: - break; - } - } - - if (abbrev->tag == DW_TAG_compile_unit - || abbrev->tag == DW_TAG_subprogram) - { - if (have_ranges) - { - if (!add_unit_ranges (state, base_address, u, ranges, lowpc, - is_bigendian, dwarf_ranges, - dwarf_ranges_size, error_callback, - data, addrs)) - return 0; - } - else if (have_lowpc && have_highpc) - { - struct unit_addrs a; - - if (highpc_is_relative) - highpc += lowpc; - a.low = lowpc; - a.high = highpc; - a.u = u; - - if (!add_unit_addr (state, base_address, a, error_callback, data, - addrs)) - return 0; - } - - /* If we found the PC range in the DW_TAG_compile_unit, we - can stop now. */ - if (abbrev->tag == DW_TAG_compile_unit - && (have_ranges || (have_lowpc && have_highpc))) - return 1; - } - - if (abbrev->has_children) - { - if (!find_address_ranges (state, base_address, unit_buf, - dwarf_str, dwarf_str_size, - dwarf_ranges, dwarf_ranges_size, - is_bigendian, error_callback, data, - u, addrs)) - return 0; - } - } - - return 1; -} - -/* Build a mapping from address ranges to the compilation units where - the line number information for that range can be found. Returns 1 - on success, 0 on failure. */ - -static int -build_address_map (struct backtrace_state *state, uintptr_t base_address, - const unsigned char *dwarf_info, size_t dwarf_info_size, - const unsigned char *dwarf_abbrev, size_t dwarf_abbrev_size, - const unsigned char *dwarf_ranges, size_t dwarf_ranges_size, - const unsigned char *dwarf_str, size_t dwarf_str_size, - int is_bigendian, backtrace_error_callback error_callback, - void *data, struct unit_addrs_vector *addrs) -{ - struct dwarf_buf info; - struct abbrevs abbrevs; - - memset (&addrs->vec, 0, sizeof addrs->vec); - addrs->count = 0; - - /* Read through the .debug_info section. FIXME: Should we use the - .debug_aranges section? gdb and addr2line don't use it, but I'm - not sure why. */ - - info.name = ".debug_info"; - info.start = dwarf_info; - info.buf = dwarf_info; - info.left = dwarf_info_size; - info.is_bigendian = is_bigendian; - info.error_callback = error_callback; - info.data = data; - info.reported_underflow = 0; - - memset (&abbrevs, 0, sizeof abbrevs); - while (info.left > 0) - { - const unsigned char *unit_data_start; - uint64_t len; - int is_dwarf64; - struct dwarf_buf unit_buf; - int version; - uint64_t abbrev_offset; - int addrsize; - struct unit *u; - - if (info.reported_underflow) - goto fail; - - unit_data_start = info.buf; - - is_dwarf64 = 0; - len = read_uint32 (&info); - if (len == 0xffffffff) - { - len = read_uint64 (&info); - is_dwarf64 = 1; - } - - unit_buf = info; - unit_buf.left = len; - - if (!advance (&info, len)) - goto fail; - - version = read_uint16 (&unit_buf); - if (version < 2 || version > 4) - { - dwarf_buf_error (&unit_buf, "unrecognized DWARF version"); - goto fail; - } - - abbrev_offset = read_offset (&unit_buf, is_dwarf64); - if (!read_abbrevs (state, abbrev_offset, dwarf_abbrev, dwarf_abbrev_size, - is_bigendian, error_callback, data, &abbrevs)) - goto fail; - - addrsize = read_byte (&unit_buf); - - u = ((struct unit *) - backtrace_alloc (state, sizeof *u, error_callback, data)); - if (u == NULL) - goto fail; - u->unit_data = unit_buf.buf; - u->unit_data_len = unit_buf.left; - u->unit_data_offset = unit_buf.buf - unit_data_start; - u->version = version; - u->is_dwarf64 = is_dwarf64; - u->addrsize = addrsize; - u->filename = NULL; - u->comp_dir = NULL; - u->abs_filename = NULL; - u->lineoff = 0; - u->abbrevs = abbrevs; - memset (&abbrevs, 0, sizeof abbrevs); - - /* The actual line number mappings will be read as needed. */ - u->lines = NULL; - u->lines_count = 0; - u->function_addrs = NULL; - u->function_addrs_count = 0; - - if (!find_address_ranges (state, base_address, &unit_buf, - dwarf_str, dwarf_str_size, - dwarf_ranges, dwarf_ranges_size, - is_bigendian, error_callback, data, - u, addrs)) - { - free_abbrevs (state, &u->abbrevs, error_callback, data); - backtrace_free (state, u, sizeof *u, error_callback, data); - goto fail; - } - - if (unit_buf.reported_underflow) - { - free_abbrevs (state, &u->abbrevs, error_callback, data); - backtrace_free (state, u, sizeof *u, error_callback, data); - goto fail; - } - } - if (info.reported_underflow) - goto fail; - - return 1; - - fail: - free_abbrevs (state, &abbrevs, error_callback, data); - free_unit_addrs_vector (state, addrs, error_callback, data); - return 0; -} - -/* Add a new mapping to the vector of line mappings that we are - building. Returns 1 on success, 0 on failure. */ - -static int -add_line (struct backtrace_state *state, struct dwarf_data *ddata, - uintptr_t pc, const char *filename, int lineno, - backtrace_error_callback error_callback, void *data, - struct line_vector *vec) -{ - struct line *ln; - - /* If we are adding the same mapping, ignore it. This can happen - when using discriminators. */ - if (vec->count > 0) - { - ln = (struct line *) vec->vec.base + (vec->count - 1); - if (pc == ln->pc && filename == ln->filename && lineno == ln->lineno) - return 1; - } - - ln = ((struct line *) - backtrace_vector_grow (state, sizeof (struct line), error_callback, - data, &vec->vec)); - if (ln == NULL) - return 0; - - /* Add in the base address here, so that we can look up the PC - directly. */ - ln->pc = pc + ddata->base_address; - - ln->filename = filename; - ln->lineno = lineno; - ln->idx = vec->count; - - ++vec->count; - - return 1; -} - -/* Free the line header information. */ - -static void -free_line_header (struct backtrace_state *state, struct line_header *hdr, - backtrace_error_callback error_callback, void *data) -{ - if (hdr->dirs_count != 0) - backtrace_free (state, hdr->dirs, hdr->dirs_count * sizeof (const char *), - error_callback, data); - backtrace_free (state, hdr->filenames, - hdr->filenames_count * sizeof (char *), - error_callback, data); -} - -/* Read the line header. Return 1 on success, 0 on failure. */ - -static int -read_line_header (struct backtrace_state *state, struct unit *u, - int is_dwarf64, struct dwarf_buf *line_buf, - struct line_header *hdr) -{ - uint64_t hdrlen; - struct dwarf_buf hdr_buf; - const unsigned char *p; - const unsigned char *pend; - size_t i; - - hdr->version = read_uint16 (line_buf); - if (hdr->version < 2 || hdr->version > 4) - { - dwarf_buf_error (line_buf, "unsupported line number version"); - return 0; - } - - hdrlen = read_offset (line_buf, is_dwarf64); - - hdr_buf = *line_buf; - hdr_buf.left = hdrlen; - - if (!advance (line_buf, hdrlen)) - return 0; - - hdr->min_insn_len = read_byte (&hdr_buf); - if (hdr->version < 4) - hdr->max_ops_per_insn = 1; - else - hdr->max_ops_per_insn = read_byte (&hdr_buf); - - /* We don't care about default_is_stmt. */ - read_byte (&hdr_buf); - - hdr->line_base = read_sbyte (&hdr_buf); - hdr->line_range = read_byte (&hdr_buf); - - hdr->opcode_base = read_byte (&hdr_buf); - hdr->opcode_lengths = hdr_buf.buf; - if (!advance (&hdr_buf, hdr->opcode_base - 1)) - return 0; - - /* Count the number of directory entries. */ - hdr->dirs_count = 0; - p = hdr_buf.buf; - pend = p + hdr_buf.left; - while (p < pend && *p != '\0') - { - p += strnlen((const char *) p, pend - p) + 1; - ++hdr->dirs_count; - } - - hdr->dirs = NULL; - if (hdr->dirs_count != 0) - { - hdr->dirs = ((const char **) - backtrace_alloc (state, - hdr->dirs_count * sizeof (const char *), - line_buf->error_callback, line_buf->data)); - if (hdr->dirs == NULL) - return 0; - } - - i = 0; - while (*hdr_buf.buf != '\0') - { - if (hdr_buf.reported_underflow) - return 0; - - hdr->dirs[i] = (const char *) hdr_buf.buf; - ++i; - if (!advance (&hdr_buf, - strnlen ((const char *) hdr_buf.buf, hdr_buf.left) + 1)) - return 0; - } - if (!advance (&hdr_buf, 1)) - return 0; - - /* Count the number of file entries. */ - hdr->filenames_count = 0; - p = hdr_buf.buf; - pend = p + hdr_buf.left; - while (p < pend && *p != '\0') - { - p += strnlen ((const char *) p, pend - p) + 1; - p += leb128_len (p); - p += leb128_len (p); - p += leb128_len (p); - ++hdr->filenames_count; - } - - hdr->filenames = ((const char **) - backtrace_alloc (state, - hdr->filenames_count * sizeof (char *), - line_buf->error_callback, - line_buf->data)); - if (hdr->filenames == NULL) - return 0; - i = 0; - while (*hdr_buf.buf != '\0') - { - const char *filename; - uint64_t dir_index; - - if (hdr_buf.reported_underflow) - return 0; - - filename = (const char *) hdr_buf.buf; - if (!advance (&hdr_buf, - strnlen ((const char *) hdr_buf.buf, hdr_buf.left) + 1)) - return 0; - dir_index = read_uleb128 (&hdr_buf); - if (IS_ABSOLUTE_PATH (filename) - || (dir_index == 0 && u->comp_dir == NULL)) - hdr->filenames[i] = filename; - else - { - const char *dir; - size_t dir_len; - size_t filename_len; - char *s; - - if (dir_index == 0) - dir = u->comp_dir; - else if (dir_index - 1 < hdr->dirs_count) - dir = hdr->dirs[dir_index - 1]; - else - { - dwarf_buf_error (line_buf, - ("invalid directory index in " - "line number program header")); - return 0; - } - dir_len = strlen (dir); - filename_len = strlen (filename); - s = ((char *) - backtrace_alloc (state, dir_len + filename_len + 2, - line_buf->error_callback, line_buf->data)); - if (s == NULL) - return 0; - memcpy (s, dir, dir_len); - /* FIXME: If we are on a DOS-based file system, and the - directory or the file name use backslashes, then we - should use a backslash here. */ - s[dir_len] = '/'; - memcpy (s + dir_len + 1, filename, filename_len + 1); - hdr->filenames[i] = s; - } - - /* Ignore the modification time and size. */ - read_uleb128 (&hdr_buf); - read_uleb128 (&hdr_buf); - - ++i; - } - - if (hdr_buf.reported_underflow) - return 0; - - return 1; -} - -/* Read the line program, adding line mappings to VEC. Return 1 on - success, 0 on failure. */ - -static int -read_line_program (struct backtrace_state *state, struct dwarf_data *ddata, - struct unit *u, const struct line_header *hdr, - struct dwarf_buf *line_buf, struct line_vector *vec) -{ - uint64_t address; - unsigned int op_index; - const char *reset_filename; - const char *filename; - int lineno; - - address = 0; - op_index = 0; - if (hdr->filenames_count > 0) - reset_filename = hdr->filenames[0]; - else - reset_filename = ""; - filename = reset_filename; - lineno = 1; - while (line_buf->left > 0) - { - unsigned int op; - - op = read_byte (line_buf); - if (op >= hdr->opcode_base) - { - unsigned int advance; - - /* Special opcode. */ - op -= hdr->opcode_base; - advance = op / hdr->line_range; - address += (hdr->min_insn_len * (op_index + advance) - / hdr->max_ops_per_insn); - op_index = (op_index + advance) % hdr->max_ops_per_insn; - lineno += hdr->line_base + (int) (op % hdr->line_range); - add_line (state, ddata, address, filename, lineno, - line_buf->error_callback, line_buf->data, vec); - } - else if (op == DW_LNS_extended_op) - { - uint64_t len; - - len = read_uleb128 (line_buf); - op = read_byte (line_buf); - switch (op) - { - case DW_LNE_end_sequence: - /* FIXME: Should we mark the high PC here? It seems - that we already have that information from the - compilation unit. */ - address = 0; - op_index = 0; - filename = reset_filename; - lineno = 1; - break; - case DW_LNE_set_address: - address = read_address (line_buf, u->addrsize); - break; - case DW_LNE_define_file: - { - const char *f; - unsigned int dir_index; - - f = (const char *) line_buf->buf; - if (!advance (line_buf, strnlen (f, line_buf->left) + 1)) - return 0; - dir_index = read_uleb128 (line_buf); - /* Ignore that time and length. */ - read_uleb128 (line_buf); - read_uleb128 (line_buf); - if (IS_ABSOLUTE_PATH (f)) - filename = f; - else - { - const char *dir; - size_t dir_len; - size_t f_len; - char *p; - - if (dir_index == 0) - dir = u->comp_dir; - else if (dir_index - 1 < hdr->dirs_count) - dir = hdr->dirs[dir_index - 1]; - else - { - dwarf_buf_error (line_buf, - ("invalid directory index " - "in line number program")); - return 0; - } - dir_len = strlen (dir); - f_len = strlen (f); - p = ((char *) - backtrace_alloc (state, dir_len + f_len + 2, - line_buf->error_callback, - line_buf->data)); - if (p == NULL) - return 0; - memcpy (p, dir, dir_len); - /* FIXME: If we are on a DOS-based file system, - and the directory or the file name use - backslashes, then we should use a backslash - here. */ - p[dir_len] = '/'; - memcpy (p + dir_len + 1, f, f_len + 1); - filename = p; - } - } - break; - case DW_LNE_set_discriminator: - /* We don't care about discriminators. */ - read_uleb128 (line_buf); - break; - default: - if (!advance (line_buf, len - 1)) - return 0; - break; - } - } - else - { - switch (op) - { - case DW_LNS_copy: - add_line (state, ddata, address, filename, lineno, - line_buf->error_callback, line_buf->data, vec); - break; - case DW_LNS_advance_pc: - { - uint64_t advance; - - advance = read_uleb128 (line_buf); - address += (hdr->min_insn_len * (op_index + advance) - / hdr->max_ops_per_insn); - op_index = (op_index + advance) % hdr->max_ops_per_insn; - } - break; - case DW_LNS_advance_line: - lineno += (int) read_sleb128 (line_buf); - break; - case DW_LNS_set_file: - { - uint64_t fileno; - - fileno = read_uleb128 (line_buf); - if (fileno == 0) - filename = ""; - else - { - if (fileno - 1 >= hdr->filenames_count) - { - dwarf_buf_error (line_buf, - ("invalid file number in " - "line number program")); - return 0; - } - filename = hdr->filenames[fileno - 1]; - } - } - break; - case DW_LNS_set_column: - read_uleb128 (line_buf); - break; - case DW_LNS_negate_stmt: - break; - case DW_LNS_set_basic_block: - break; - case DW_LNS_const_add_pc: - { - unsigned int advance; - - op = 255 - hdr->opcode_base; - advance = op / hdr->line_range; - address += (hdr->min_insn_len * (op_index + advance) - / hdr->max_ops_per_insn); - op_index = (op_index + advance) % hdr->max_ops_per_insn; - } - break; - case DW_LNS_fixed_advance_pc: - address += read_uint16 (line_buf); - op_index = 0; - break; - case DW_LNS_set_prologue_end: - break; - case DW_LNS_set_epilogue_begin: - break; - case DW_LNS_set_isa: - read_uleb128 (line_buf); - break; - default: - { - unsigned int i; - - for (i = hdr->opcode_lengths[op - 1]; i > 0; --i) - read_uleb128 (line_buf); - } - break; - } - } - } - - return 1; -} - -/* Read the line number information for a compilation unit. Returns 1 - on success, 0 on failure. */ - -static int -read_line_info (struct backtrace_state *state, struct dwarf_data *ddata, - backtrace_error_callback error_callback, void *data, - struct unit *u, struct line_header *hdr, struct line **lines, - size_t *lines_count) -{ - struct line_vector vec; - struct dwarf_buf line_buf; - uint64_t len; - int is_dwarf64; - struct line *ln; - - memset (&vec.vec, 0, sizeof vec.vec); - vec.count = 0; - - memset (hdr, 0, sizeof *hdr); - - if (u->lineoff != (off_t) (size_t) u->lineoff - || (size_t) u->lineoff >= ddata->dwarf_line_size) - { - error_callback (data, "unit line offset out of range", 0); - goto fail; - } - - line_buf.name = ".debug_line"; - line_buf.start = ddata->dwarf_line; - line_buf.buf = ddata->dwarf_line + u->lineoff; - line_buf.left = ddata->dwarf_line_size - u->lineoff; - line_buf.is_bigendian = ddata->is_bigendian; - line_buf.error_callback = error_callback; - line_buf.data = data; - line_buf.reported_underflow = 0; - - is_dwarf64 = 0; - len = read_uint32 (&line_buf); - if (len == 0xffffffff) - { - len = read_uint64 (&line_buf); - is_dwarf64 = 1; - } - line_buf.left = len; - - if (!read_line_header (state, u, is_dwarf64, &line_buf, hdr)) - goto fail; - - if (!read_line_program (state, ddata, u, hdr, &line_buf, &vec)) - goto fail; - - if (line_buf.reported_underflow) - goto fail; - - if (vec.count == 0) - { - /* This is not a failure in the sense of a generating an error, - but it is a failure in that sense that we have no useful - information. */ - goto fail; - } - - /* Allocate one extra entry at the end. */ - ln = ((struct line *) - backtrace_vector_grow (state, sizeof (struct line), error_callback, - data, &vec.vec)); - if (ln == NULL) - goto fail; - ln->pc = (uintptr_t) -1; - ln->filename = NULL; - ln->lineno = 0; - ln->idx = 0; - - if (!backtrace_vector_release (state, &vec.vec, error_callback, data)) - goto fail; - - ln = (struct line *) vec.vec.base; - backtrace_qsort (ln, vec.count, sizeof (struct line), line_compare); - - *lines = ln; - *lines_count = vec.count; - - return 1; - - fail: - vec.vec.alc += vec.vec.size; - vec.vec.size = 0; - backtrace_vector_release (state, &vec.vec, error_callback, data); - free_line_header (state, hdr, error_callback, data); - *lines = (struct line *) (uintptr_t) -1; - *lines_count = 0; - return 0; -} - -/* Read the name of a function from a DIE referenced by a - DW_AT_abstract_origin or DW_AT_specification tag. OFFSET is within - the same compilation unit. */ - -static const char * -read_referenced_name (struct dwarf_data *ddata, struct unit *u, - uint64_t offset, backtrace_error_callback error_callback, - void *data) -{ - struct dwarf_buf unit_buf; - uint64_t code; - const struct abbrev *abbrev; - const char *ret; - size_t i; - - /* OFFSET is from the start of the data for this compilation unit. - U->unit_data is the data, but it starts U->unit_data_offset bytes - from the beginning. */ - - if (offset < u->unit_data_offset - || offset - u->unit_data_offset >= u->unit_data_len) - { - error_callback (data, - "abstract origin or specification out of range", - 0); - return NULL; - } - - offset -= u->unit_data_offset; - - unit_buf.name = ".debug_info"; - unit_buf.start = ddata->dwarf_info; - unit_buf.buf = u->unit_data + offset; - unit_buf.left = u->unit_data_len - offset; - unit_buf.is_bigendian = ddata->is_bigendian; - unit_buf.error_callback = error_callback; - unit_buf.data = data; - unit_buf.reported_underflow = 0; - - code = read_uleb128 (&unit_buf); - if (code == 0) - { - dwarf_buf_error (&unit_buf, "invalid abstract origin or specification"); - return NULL; - } - - abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data); - if (abbrev == NULL) - return NULL; - - ret = NULL; - for (i = 0; i < abbrev->num_attrs; ++i) - { - struct attr_val val; - - if (!read_attribute (abbrev->attrs[i].form, &unit_buf, - u->is_dwarf64, u->version, u->addrsize, - ddata->dwarf_str, ddata->dwarf_str_size, - &val)) - return NULL; - - switch (abbrev->attrs[i].name) - { - case DW_AT_name: - /* We prefer the linkage name if get one. */ - if (val.encoding == ATTR_VAL_STRING) - ret = val.u.string; - break; - - case DW_AT_linkage_name: - case DW_AT_MIPS_linkage_name: - if (val.encoding == ATTR_VAL_STRING) - return val.u.string; - break; - - case DW_AT_specification: - if (abbrev->attrs[i].form == DW_FORM_ref_addr - || abbrev->attrs[i].form == DW_FORM_ref_sig8) - { - /* This refers to a specification defined in some other - compilation unit. We can handle this case if we - must, but it's harder. */ - break; - } - if (val.encoding == ATTR_VAL_UINT - || val.encoding == ATTR_VAL_REF_UNIT) - { - const char *name; - - name = read_referenced_name (ddata, u, val.u.uint, - error_callback, data); - if (name != NULL) - ret = name; - } - break; - - default: - break; - } - } - - return ret; -} - -/* Add a single range to U that maps to function. Returns 1 on - success, 0 on error. */ - -static int -add_function_range (struct backtrace_state *state, struct dwarf_data *ddata, - struct function *function, uint64_t lowpc, uint64_t highpc, - backtrace_error_callback error_callback, - void *data, struct function_vector *vec) -{ - struct function_addrs *p; - - /* Add in the base address here, so that we can look up the PC - directly. */ - lowpc += ddata->base_address; - highpc += ddata->base_address; - - if (vec->count > 0) - { - p = (struct function_addrs *) vec->vec.base + vec->count - 1; - if ((lowpc == p->high || lowpc == p->high + 1) - && function == p->function) - { - if (highpc > p->high) - p->high = highpc; - return 1; - } - } - - p = ((struct function_addrs *) - backtrace_vector_grow (state, sizeof (struct function_addrs), - error_callback, data, &vec->vec)); - if (p == NULL) - return 0; - - p->low = lowpc; - p->high = highpc; - p->function = function; - ++vec->count; - return 1; -} - -/* Add PC ranges to U that map to FUNCTION. Returns 1 on success, 0 - on error. */ - -static int -add_function_ranges (struct backtrace_state *state, struct dwarf_data *ddata, - struct unit *u, struct function *function, - uint64_t ranges, uint64_t base, - backtrace_error_callback error_callback, void *data, - struct function_vector *vec) -{ - struct dwarf_buf ranges_buf; - - if (ranges >= ddata->dwarf_ranges_size) - { - error_callback (data, "function ranges offset out of range", 0); - return 0; - } - - ranges_buf.name = ".debug_ranges"; - ranges_buf.start = ddata->dwarf_ranges; - ranges_buf.buf = ddata->dwarf_ranges + ranges; - ranges_buf.left = ddata->dwarf_ranges_size - ranges; - ranges_buf.is_bigendian = ddata->is_bigendian; - ranges_buf.error_callback = error_callback; - ranges_buf.data = data; - ranges_buf.reported_underflow = 0; - - while (1) - { - uint64_t low; - uint64_t high; - - if (ranges_buf.reported_underflow) - return 0; - - low = read_address (&ranges_buf, u->addrsize); - high = read_address (&ranges_buf, u->addrsize); - - if (low == 0 && high == 0) - break; - - if (is_highest_address (low, u->addrsize)) - base = high; - else - { - if (!add_function_range (state, ddata, function, low + base, - high + base, error_callback, data, vec)) - return 0; - } - } - - if (ranges_buf.reported_underflow) - return 0; - - return 1; -} - -/* Read one entry plus all its children. Add function addresses to - VEC. Returns 1 on success, 0 on error. */ - -static int -read_function_entry (struct backtrace_state *state, struct dwarf_data *ddata, - struct unit *u, uint64_t base, struct dwarf_buf *unit_buf, - const struct line_header *lhdr, - backtrace_error_callback error_callback, void *data, - struct function_vector *vec_function, - struct function_vector *vec_inlined) -{ - while (unit_buf->left > 0) - { - uint64_t code; - const struct abbrev *abbrev; - int is_function; - struct function *function; - struct function_vector *vec; - size_t i; - uint64_t lowpc; - int have_lowpc; - uint64_t highpc; - int have_highpc; - int highpc_is_relative; - uint64_t ranges; - int have_ranges; - - code = read_uleb128 (unit_buf); - if (code == 0) - return 1; - - abbrev = lookup_abbrev (&u->abbrevs, code, error_callback, data); - if (abbrev == NULL) - return 0; - - is_function = (abbrev->tag == DW_TAG_subprogram - || abbrev->tag == DW_TAG_entry_point - || abbrev->tag == DW_TAG_inlined_subroutine); - - if (abbrev->tag == DW_TAG_inlined_subroutine) - vec = vec_inlined; - else - vec = vec_function; - - function = NULL; - if (is_function) - { - function = ((struct function *) - backtrace_alloc (state, sizeof *function, - error_callback, data)); - if (function == NULL) - return 0; - memset (function, 0, sizeof *function); - } - - lowpc = 0; - have_lowpc = 0; - highpc = 0; - have_highpc = 0; - highpc_is_relative = 0; - ranges = 0; - have_ranges = 0; - for (i = 0; i < abbrev->num_attrs; ++i) - { - struct attr_val val; - - if (!read_attribute (abbrev->attrs[i].form, unit_buf, - u->is_dwarf64, u->version, u->addrsize, - ddata->dwarf_str, ddata->dwarf_str_size, - &val)) - return 0; - - /* The compile unit sets the base address for any address - ranges in the function entries. */ - if (abbrev->tag == DW_TAG_compile_unit - && abbrev->attrs[i].name == DW_AT_low_pc - && val.encoding == ATTR_VAL_ADDRESS) - base = val.u.uint; - - if (is_function) - { - switch (abbrev->attrs[i].name) - { - case DW_AT_call_file: - if (val.encoding == ATTR_VAL_UINT) - { - if (val.u.uint == 0) - function->caller_filename = ""; - else - { - if (val.u.uint - 1 >= lhdr->filenames_count) - { - dwarf_buf_error (unit_buf, - ("invalid file number in " - "DW_AT_call_file attribute")); - return 0; - } - function->caller_filename = - lhdr->filenames[val.u.uint - 1]; - } - } - break; - - case DW_AT_call_line: - if (val.encoding == ATTR_VAL_UINT) - function->caller_lineno = val.u.uint; - break; - - case DW_AT_abstract_origin: - case DW_AT_specification: - if (abbrev->attrs[i].form == DW_FORM_ref_addr - || abbrev->attrs[i].form == DW_FORM_ref_sig8) - { - /* This refers to an abstract origin defined in - some other compilation unit. We can handle - this case if we must, but it's harder. */ - break; - } - if (val.encoding == ATTR_VAL_UINT - || val.encoding == ATTR_VAL_REF_UNIT) - { - const char *name; - - name = read_referenced_name (ddata, u, val.u.uint, - error_callback, data); - if (name != NULL) - function->name = name; - } - break; - - case DW_AT_name: - if (val.encoding == ATTR_VAL_STRING) - { - /* Don't override a name we found in some other - way, as it will normally be more - useful--e.g., this name is normally not - mangled. */ - if (function->name == NULL) - function->name = val.u.string; - } - break; - - case DW_AT_linkage_name: - case DW_AT_MIPS_linkage_name: - if (val.encoding == ATTR_VAL_STRING) - function->name = val.u.string; - break; - - case DW_AT_low_pc: - if (val.encoding == ATTR_VAL_ADDRESS) - { - lowpc = val.u.uint; - have_lowpc = 1; - } - break; - - case DW_AT_high_pc: - if (val.encoding == ATTR_VAL_ADDRESS) - { - highpc = val.u.uint; - have_highpc = 1; - } - else if (val.encoding == ATTR_VAL_UINT) - { - highpc = val.u.uint; - have_highpc = 1; - highpc_is_relative = 1; - } - break; - - case DW_AT_ranges: - if (val.encoding == ATTR_VAL_UINT - || val.encoding == ATTR_VAL_REF_SECTION) - { - ranges = val.u.uint; - have_ranges = 1; - } - break; - - default: - break; - } - } - } - - /* If we couldn't find a name for the function, we have no use - for it. */ - if (is_function && function->name == NULL) - { - backtrace_free (state, function, sizeof *function, - error_callback, data); - is_function = 0; - } - - if (is_function) - { - if (have_ranges) - { - if (!add_function_ranges (state, ddata, u, function, ranges, - base, error_callback, data, vec)) - return 0; - } - else if (have_lowpc && have_highpc) - { - if (highpc_is_relative) - highpc += lowpc; - if (!add_function_range (state, ddata, function, lowpc, highpc, - error_callback, data, vec)) - return 0; - } - else - { - backtrace_free (state, function, sizeof *function, - error_callback, data); - is_function = 0; - } - } - - if (abbrev->has_children) - { - if (!is_function) - { - if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr, - error_callback, data, vec_function, - vec_inlined)) - return 0; - } - else - { - struct function_vector fvec; - - /* Gather any information for inlined functions in - FVEC. */ - - memset (&fvec, 0, sizeof fvec); - - if (!read_function_entry (state, ddata, u, base, unit_buf, lhdr, - error_callback, data, vec_function, - &fvec)) - return 0; - - if (fvec.count > 0) - { - struct function_addrs *faddrs; - - if (!backtrace_vector_release (state, &fvec.vec, - error_callback, data)) - return 0; - - faddrs = (struct function_addrs *) fvec.vec.base; - backtrace_qsort (faddrs, fvec.count, - sizeof (struct function_addrs), - function_addrs_compare); - - function->function_addrs = faddrs; - function->function_addrs_count = fvec.count; - } - } - } - } - - return 1; -} - -/* Read function name information for a compilation unit. We look - through the whole unit looking for function tags. */ - -static void -read_function_info (struct backtrace_state *state, struct dwarf_data *ddata, - const struct line_header *lhdr, - backtrace_error_callback error_callback, void *data, - struct unit *u, struct function_vector *fvec, - struct function_addrs **ret_addrs, - size_t *ret_addrs_count) -{ - struct function_vector lvec; - struct function_vector *pfvec; - struct dwarf_buf unit_buf; - struct function_addrs *addrs; - size_t addrs_count; - - /* Use FVEC if it is not NULL. Otherwise use our own vector. */ - if (fvec != NULL) - pfvec = fvec; - else - { - memset (&lvec, 0, sizeof lvec); - pfvec = &lvec; - } - - unit_buf.name = ".debug_info"; - unit_buf.start = ddata->dwarf_info; - unit_buf.buf = u->unit_data; - unit_buf.left = u->unit_data_len; - unit_buf.is_bigendian = ddata->is_bigendian; - unit_buf.error_callback = error_callback; - unit_buf.data = data; - unit_buf.reported_underflow = 0; - - while (unit_buf.left > 0) - { - if (!read_function_entry (state, ddata, u, 0, &unit_buf, lhdr, - error_callback, data, pfvec, pfvec)) - return; - } - - if (pfvec->count == 0) - return; - - addrs_count = pfvec->count; - - if (fvec == NULL) - { - if (!backtrace_vector_release (state, &lvec.vec, error_callback, data)) - return; - addrs = (struct function_addrs *) pfvec->vec.base; - } - else - { - /* Finish this list of addresses, but leave the remaining space in - the vector available for the next function unit. */ - addrs = ((struct function_addrs *) - backtrace_vector_finish (state, &fvec->vec, - error_callback, data)); - if (addrs == NULL) - return; - fvec->count = 0; - } - - backtrace_qsort (addrs, addrs_count, sizeof (struct function_addrs), - function_addrs_compare); - - *ret_addrs = addrs; - *ret_addrs_count = addrs_count; -} - -/* See if PC is inlined in FUNCTION. If it is, print out the inlined - information, and update FILENAME and LINENO for the caller. - Returns whatever CALLBACK returns, or 0 to keep going. */ - -static int -report_inlined_functions (uintptr_t pc, struct function *function, - backtrace_full_callback callback, void *data, - const char **filename, int *lineno) -{ - struct function_addrs *function_addrs; - struct function *inlined; - int ret; - - if (function->function_addrs_count == 0) - return 0; - - function_addrs = ((struct function_addrs *) - bsearch (&pc, function->function_addrs, - function->function_addrs_count, - sizeof (struct function_addrs), - function_addrs_search)); - if (function_addrs == NULL) - return 0; - - while (((size_t) (function_addrs - function->function_addrs) + 1 - < function->function_addrs_count) - && pc >= (function_addrs + 1)->low - && pc < (function_addrs + 1)->high) - ++function_addrs; - - /* We found an inlined call. */ - - inlined = function_addrs->function; - - /* Report any calls inlined into this one. */ - ret = report_inlined_functions (pc, inlined, callback, data, - filename, lineno); - if (ret != 0) - return ret; - - /* Report this inlined call. */ - ret = callback (data, pc, *filename, *lineno, inlined->name); - if (ret != 0) - return ret; - - /* Our caller will report the caller of the inlined function; tell - it the appropriate filename and line number. */ - *filename = inlined->caller_filename; - *lineno = inlined->caller_lineno; - - return 0; -} - -/* Look for a PC in the DWARF mapping for one module. On success, - call CALLBACK and return whatever it returns. On error, call - ERROR_CALLBACK and return 0. Sets *FOUND to 1 if the PC is found, - 0 if not. */ - -static int -dwarf_lookup_pc (struct backtrace_state *state, struct dwarf_data *ddata, - uintptr_t pc, backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data, - int *found) -{ - struct unit_addrs *entry; - struct unit *u; - int new_data; - struct line *lines; - struct line *ln; - struct function_addrs *function_addrs; - struct function *function; - const char *filename; - int lineno; - int ret; - - *found = 1; - - /* Find an address range that includes PC. */ - entry = bsearch (&pc, ddata->addrs, ddata->addrs_count, - sizeof (struct unit_addrs), unit_addrs_search); - - if (entry == NULL) - { - *found = 0; - return 0; - } - - /* If there are multiple ranges that contain PC, use the last one, - in order to produce predictable results. If we assume that all - ranges are properly nested, then the last range will be the - smallest one. */ - while ((size_t) (entry - ddata->addrs) + 1 < ddata->addrs_count - && pc >= (entry + 1)->low - && pc < (entry + 1)->high) - ++entry; - - /* We need the lines, lines_count, function_addrs, - function_addrs_count fields of u. If they are not set, we need - to set them. When running in threaded mode, we need to allow for - the possibility that some other thread is setting them - simultaneously. */ - - u = entry->u; - lines = u->lines; - - /* Skip units with no useful line number information by walking - backward. Useless line number information is marked by setting - lines == -1. */ - while (entry > ddata->addrs - && pc >= (entry - 1)->low - && pc < (entry - 1)->high) - { - if (state->threaded) - lines = (struct line *) backtrace_atomic_load_pointer (&u->lines); - - if (lines != (struct line *) (uintptr_t) -1) - break; - - --entry; - - u = entry->u; - lines = u->lines; - } - - if (state->threaded) - lines = backtrace_atomic_load_pointer (&u->lines); - - new_data = 0; - if (lines == NULL) - { - size_t function_addrs_count; - struct line_header lhdr; - size_t count; - - /* We have never read the line information for this unit. Read - it now. */ - - function_addrs = NULL; - function_addrs_count = 0; - if (read_line_info (state, ddata, error_callback, data, entry->u, &lhdr, - &lines, &count)) - { - struct function_vector *pfvec; - - /* If not threaded, reuse DDATA->FVEC for better memory - consumption. */ - if (state->threaded) - pfvec = NULL; - else - pfvec = &ddata->fvec; - read_function_info (state, ddata, &lhdr, error_callback, data, - entry->u, pfvec, &function_addrs, - &function_addrs_count); - free_line_header (state, &lhdr, error_callback, data); - new_data = 1; - } - - /* Atomically store the information we just read into the unit. - If another thread is simultaneously writing, it presumably - read the same information, and we don't care which one we - wind up with; we just leak the other one. We do have to - write the lines field last, so that the acquire-loads above - ensure that the other fields are set. */ - - if (!state->threaded) - { - u->lines_count = count; - u->function_addrs = function_addrs; - u->function_addrs_count = function_addrs_count; - u->lines = lines; - } - else - { - backtrace_atomic_store_size_t (&u->lines_count, count); - backtrace_atomic_store_pointer (&u->function_addrs, function_addrs); - backtrace_atomic_store_size_t (&u->function_addrs_count, - function_addrs_count); - backtrace_atomic_store_pointer (&u->lines, lines); - } - } - - /* Now all fields of U have been initialized. */ - - if (lines == (struct line *) (uintptr_t) -1) - { - /* If reading the line number information failed in some way, - try again to see if there is a better compilation unit for - this PC. */ - if (new_data) - return dwarf_lookup_pc (state, ddata, pc, callback, error_callback, - data, found); - return callback (data, pc, NULL, 0, NULL); - } - - /* Search for PC within this unit. */ - - ln = (struct line *) bsearch (&pc, lines, entry->u->lines_count, - sizeof (struct line), line_search); - if (ln == NULL) - { - /* The PC is between the low_pc and high_pc attributes of the - compilation unit, but no entry in the line table covers it. - This implies that the start of the compilation unit has no - line number information. */ - - if (entry->u->abs_filename == NULL) - { - const char *filename; - - filename = entry->u->filename; - if (filename != NULL - && !IS_ABSOLUTE_PATH (filename) - && entry->u->comp_dir != NULL) - { - size_t filename_len; - const char *dir; - size_t dir_len; - char *s; - - filename_len = strlen (filename); - dir = entry->u->comp_dir; - dir_len = strlen (dir); - s = (char *) backtrace_alloc (state, dir_len + filename_len + 2, - error_callback, data); - if (s == NULL) - { - *found = 0; - return 0; - } - memcpy (s, dir, dir_len); - /* FIXME: Should use backslash if DOS file system. */ - s[dir_len] = '/'; - memcpy (s + dir_len + 1, filename, filename_len + 1); - filename = s; - } - entry->u->abs_filename = filename; - } - - return callback (data, pc, entry->u->abs_filename, 0, NULL); - } - - /* Search for function name within this unit. */ - - if (entry->u->function_addrs_count == 0) - return callback (data, pc, ln->filename, ln->lineno, NULL); - - function_addrs = ((struct function_addrs *) - bsearch (&pc, entry->u->function_addrs, - entry->u->function_addrs_count, - sizeof (struct function_addrs), - function_addrs_search)); - if (function_addrs == NULL) - return callback (data, pc, ln->filename, ln->lineno, NULL); - - /* If there are multiple function ranges that contain PC, use the - last one, in order to produce predictable results. */ - - while (((size_t) (function_addrs - entry->u->function_addrs + 1) - < entry->u->function_addrs_count) - && pc >= (function_addrs + 1)->low - && pc < (function_addrs + 1)->high) - ++function_addrs; - - function = function_addrs->function; - - filename = ln->filename; - lineno = ln->lineno; - - ret = report_inlined_functions (pc, function, callback, data, - &filename, &lineno); - if (ret != 0) - return ret; - - return callback (data, pc, filename, lineno, function->name); -} - - -/* Return the file/line information for a PC using the DWARF mapping - we built earlier. */ - -static int -dwarf_fileline (struct backtrace_state *state, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data) -{ - struct dwarf_data *ddata; - int found; - int ret; - - if (!state->threaded) - { - for (ddata = (struct dwarf_data *) state->fileline_data; - ddata != NULL; - ddata = ddata->next) - { - ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback, - data, &found); - if (ret != 0 || found) - return ret; - } - } - else - { - struct dwarf_data **pp; - - pp = (struct dwarf_data **) (void *) &state->fileline_data; - while (1) - { - ddata = backtrace_atomic_load_pointer (pp); - if (ddata == NULL) - break; - - ret = dwarf_lookup_pc (state, ddata, pc, callback, error_callback, - data, &found); - if (ret != 0 || found) - return ret; - - pp = &ddata->next; - } - } - - /* FIXME: See if any libraries have been dlopen'ed. */ - - return callback (data, pc, NULL, 0, NULL); -} - -/* Initialize our data structures from the DWARF debug info for a - file. Return NULL on failure. */ - -static struct dwarf_data * -build_dwarf_data (struct backtrace_state *state, - uintptr_t base_address, - const unsigned char *dwarf_info, - size_t dwarf_info_size, - const unsigned char *dwarf_line, - size_t dwarf_line_size, - const unsigned char *dwarf_abbrev, - size_t dwarf_abbrev_size, - const unsigned char *dwarf_ranges, - size_t dwarf_ranges_size, - const unsigned char *dwarf_str, - size_t dwarf_str_size, - int is_bigendian, - backtrace_error_callback error_callback, - void *data) -{ - struct unit_addrs_vector addrs_vec; - struct unit_addrs *addrs; - size_t addrs_count; - struct dwarf_data *fdata; - - if (!build_address_map (state, base_address, dwarf_info, dwarf_info_size, - dwarf_abbrev, dwarf_abbrev_size, dwarf_ranges, - dwarf_ranges_size, dwarf_str, dwarf_str_size, - is_bigendian, error_callback, data, &addrs_vec)) - return NULL; - - if (!backtrace_vector_release (state, &addrs_vec.vec, error_callback, data)) - return NULL; - addrs = (struct unit_addrs *) addrs_vec.vec.base; - addrs_count = addrs_vec.count; - backtrace_qsort (addrs, addrs_count, sizeof (struct unit_addrs), - unit_addrs_compare); - - fdata = ((struct dwarf_data *) - backtrace_alloc (state, sizeof (struct dwarf_data), - error_callback, data)); - if (fdata == NULL) - return NULL; - - fdata->next = NULL; - fdata->base_address = base_address; - fdata->addrs = addrs; - fdata->addrs_count = addrs_count; - fdata->dwarf_info = dwarf_info; - fdata->dwarf_info_size = dwarf_info_size; - fdata->dwarf_line = dwarf_line; - fdata->dwarf_line_size = dwarf_line_size; - fdata->dwarf_ranges = dwarf_ranges; - fdata->dwarf_ranges_size = dwarf_ranges_size; - fdata->dwarf_str = dwarf_str; - fdata->dwarf_str_size = dwarf_str_size; - fdata->is_bigendian = is_bigendian; - memset (&fdata->fvec, 0, sizeof fdata->fvec); - - return fdata; -} - -/* Build our data structures from the DWARF sections for a module. - Set FILELINE_FN and STATE->FILELINE_DATA. Return 1 on success, 0 - on failure. */ - -int -backtrace_dwarf_add (struct backtrace_state *state, - uintptr_t base_address, - const unsigned char *dwarf_info, - size_t dwarf_info_size, - const unsigned char *dwarf_line, - size_t dwarf_line_size, - const unsigned char *dwarf_abbrev, - size_t dwarf_abbrev_size, - const unsigned char *dwarf_ranges, - size_t dwarf_ranges_size, - const unsigned char *dwarf_str, - size_t dwarf_str_size, - int is_bigendian, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn) -{ - struct dwarf_data *fdata; - - fdata = build_dwarf_data (state, base_address, dwarf_info, dwarf_info_size, - dwarf_line, dwarf_line_size, dwarf_abbrev, - dwarf_abbrev_size, dwarf_ranges, dwarf_ranges_size, - dwarf_str, dwarf_str_size, is_bigendian, - error_callback, data); - if (fdata == NULL) - return 0; - - if (!state->threaded) - { - struct dwarf_data **pp; - - for (pp = (struct dwarf_data **) (void *) &state->fileline_data; - *pp != NULL; - pp = &(*pp)->next) - ; - *pp = fdata; - } - else - { - while (1) - { - struct dwarf_data **pp; - - pp = (struct dwarf_data **) (void *) &state->fileline_data; - - while (1) - { - struct dwarf_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, fdata)) - break; - } - } - - *fileline_fn = dwarf_fileline; - - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest.c deleted file mode 100644 index 3a2cac4..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest.c +++ /dev/null @@ -1,121 +0,0 @@ -/* edtest.c -- Test for libbacktrace storage allocation stress handling - Copyright (C) 2017-2018 Free Software Foundation, Inc. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#include "backtrace.h" -#include "backtrace-supported.h" -#include "internal.h" - -#include "testlib.h" - -static int test1 (void) __attribute__ ((noinline, unused)); -static int test1 (void) __attribute__ ((noinline, unused)); -extern int f2 (int); -extern int f3 (int, int); - -static int -test1 (void) -{ - /* Returning a value here and elsewhere avoids a tailcall which - would mess up the backtrace. */ - return f2 (__LINE__) + 1; -} - -int -f3 (int f1line, int f2line) -{ - struct info all[20]; - struct bdata data; - int f3line; - int i; - - data.all = &all[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_full (state, 0, callback_one, error_callback_one, &data); - - if (i != 0) - { - fprintf (stderr, "test1: unexpected return value %d\n", i); - data.failed = 1; - } - - if (data.index < 3) - { - fprintf (stderr, - "test1: not enough frames; got %zu, expected at least 3\n", - data.index); - data.failed = 1; - } - - check ("test1", 0, all, f3line, "f3", "edtest.c", &data.failed); - check ("test1", 1, all, f2line, "f2", "edtest2_build.c", &data.failed); - check ("test1", 2, all, f1line, "test1", "edtest.c", &data.failed); - - printf ("%s: backtrace_full alloc stress\n", data.failed ? "FAIL" : "PASS"); - - if (data.failed) - ++failures; - - return failures; -} - -int -main (int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) -{ - state = backtrace_create_state (argv[0], BACKTRACE_SUPPORTS_THREADS, - error_callback_create, NULL); - - // Grab the storage allocation lock prior to doing anything interesting. - // The intent here is to insure that the backtrace_alloc code is forced - // to always call mmap() for new memory as opposed to reusing previously - // allocated memory from the free list. Doing things this way helps - // simulate what you might see in a multithreaded program in which there - // are racing calls to the allocator. - struct backtrace_state *state_internal = - (struct backtrace_state *) state; - state_internal->lock_alloc = 1; - - // Kick off the test - test1(); - - exit (failures > 0 ? EXIT_FAILURE : EXIT_SUCCESS); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest2.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest2.c deleted file mode 100644 index e0c0470..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/edtest2.c +++ /dev/null @@ -1,43 +0,0 @@ -/* edtest2.c -- Test for libbacktrace storage allocation stress handling (p2) - Copyright (C) 2017-2018 Free Software Foundation, Inc. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -/* This file intentionally written without any #include's - */ - -extern int f3(int, int); -extern int f2(int); - -int f2(int x) -{ - /* Returning a value here and elsewhere avoids a tailcall which - would mess up the backtrace. */ - return f3(x, __LINE__) + 3; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/elf.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/elf.c deleted file mode 100644 index 0fd5e6f..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/elf.c +++ /dev/null @@ -1,3340 +0,0 @@ -/* elf.c -- Get debug data from an ELF file for backtraces. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_DL_ITERATE_PHDR -#include -#endif - -#include "backtrace.h" -#include "internal.h" - -#ifndef S_ISLNK - #ifndef S_IFLNK - #define S_IFLNK 0120000 - #endif - #ifndef S_IFMT - #define S_IFMT 0170000 - #endif - #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) -#endif - -#ifndef __GNUC__ -#define __builtin_prefetch(p, r, l) -#define unlikely(x) (x) -#else -#define unlikely(x) __builtin_expect(!!(x), 0) -#endif - -#if !defined(HAVE_DECL_STRNLEN) || !HAVE_DECL_STRNLEN - -/* If strnlen is not declared, provide our own version. */ - -static size_t -xstrnlen (const char *s, size_t maxlen) -{ - size_t i; - - for (i = 0; i < maxlen; ++i) - if (s[i] == '\0') - break; - return i; -} - -#define strnlen xstrnlen - -#endif - -#ifndef HAVE_LSTAT - -/* Dummy version of lstat for systems that don't have it. */ - -static int -xlstat (const char *path ATTRIBUTE_UNUSED, struct stat *st ATTRIBUTE_UNUSED) -{ - return -1; -} - -#define lstat xlstat - -#endif - -#ifndef HAVE_READLINK - -/* Dummy version of readlink for systems that don't have it. */ - -static ssize_t -xreadlink (const char *path ATTRIBUTE_UNUSED, char *buf ATTRIBUTE_UNUSED, - size_t bufsz ATTRIBUTE_UNUSED) -{ - return -1; -} - -#define readlink xreadlink - -#endif - -#ifndef HAVE_DL_ITERATE_PHDR - -/* Dummy version of dl_iterate_phdr for systems that don't have it. */ - -#define dl_phdr_info x_dl_phdr_info -#define dl_iterate_phdr x_dl_iterate_phdr - -struct dl_phdr_info -{ - uintptr_t dlpi_addr; - const char *dlpi_name; -}; - -static int -dl_iterate_phdr (int (*callback) (struct dl_phdr_info *, - size_t, void *) ATTRIBUTE_UNUSED, - void *data ATTRIBUTE_UNUSED) -{ - return 0; -} - -#endif /* ! defined (HAVE_DL_ITERATE_PHDR) */ - -/* The configure script must tell us whether we are 32-bit or 64-bit - ELF. We could make this code test and support either possibility, - but there is no point. This code only works for the currently - running executable, which means that we know the ELF mode at - configure time. */ - -#if BACKTRACE_ELF_SIZE != 32 && BACKTRACE_ELF_SIZE != 64 -#error "Unknown BACKTRACE_ELF_SIZE" -#endif - -/* might #include which might define our constants - with slightly different values. Undefine them to be safe. */ - -#undef EI_NIDENT -#undef EI_MAG0 -#undef EI_MAG1 -#undef EI_MAG2 -#undef EI_MAG3 -#undef EI_CLASS -#undef EI_DATA -#undef EI_VERSION -#undef ELF_MAG0 -#undef ELF_MAG1 -#undef ELF_MAG2 -#undef ELF_MAG3 -#undef ELFCLASS32 -#undef ELFCLASS64 -#undef ELFDATA2LSB -#undef ELFDATA2MSB -#undef EV_CURRENT -#undef ET_DYN -#undef EM_PPC64 -#undef EF_PPC64_ABI -#undef SHN_LORESERVE -#undef SHN_XINDEX -#undef SHN_UNDEF -#undef SHT_PROGBITS -#undef SHT_SYMTAB -#undef SHT_STRTAB -#undef SHT_DYNSYM -#undef SHF_COMPRESSED -#undef STT_OBJECT -#undef STT_FUNC -#undef NT_GNU_BUILD_ID -#undef ELFCOMPRESS_ZLIB - -/* Basic types. */ - -typedef uint16_t b_elf_half; /* Elf_Half. */ -typedef uint32_t b_elf_word; /* Elf_Word. */ -typedef int32_t b_elf_sword; /* Elf_Sword. */ - -#if BACKTRACE_ELF_SIZE == 32 - -typedef uint32_t b_elf_addr; /* Elf_Addr. */ -typedef uint32_t b_elf_off; /* Elf_Off. */ - -typedef uint32_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */ - -#else - -typedef uint64_t b_elf_addr; /* Elf_Addr. */ -typedef uint64_t b_elf_off; /* Elf_Off. */ -typedef uint64_t b_elf_xword; /* Elf_Xword. */ -typedef int64_t b_elf_sxword; /* Elf_Sxword. */ - -typedef uint64_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */ - -#endif - -/* Data structures and associated constants. */ - -#define EI_NIDENT 16 - -typedef struct { - unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */ - b_elf_half e_type; /* Identifies object file type */ - b_elf_half e_machine; /* Specifies required architecture */ - b_elf_word e_version; /* Identifies object file version */ - b_elf_addr e_entry; /* Entry point virtual address */ - b_elf_off e_phoff; /* Program header table file offset */ - b_elf_off e_shoff; /* Section header table file offset */ - b_elf_word e_flags; /* Processor-specific flags */ - b_elf_half e_ehsize; /* ELF header size in bytes */ - b_elf_half e_phentsize; /* Program header table entry size */ - b_elf_half e_phnum; /* Program header table entry count */ - b_elf_half e_shentsize; /* Section header table entry size */ - b_elf_half e_shnum; /* Section header table entry count */ - b_elf_half e_shstrndx; /* Section header string table index */ -} b_elf_ehdr; /* Elf_Ehdr. */ - -#define EI_MAG0 0 -#define EI_MAG1 1 -#define EI_MAG2 2 -#define EI_MAG3 3 -#define EI_CLASS 4 -#define EI_DATA 5 -#define EI_VERSION 6 - -#define ELFMAG0 0x7f -#define ELFMAG1 'E' -#define ELFMAG2 'L' -#define ELFMAG3 'F' - -#define ELFCLASS32 1 -#define ELFCLASS64 2 - -#define ELFDATA2LSB 1 -#define ELFDATA2MSB 2 - -#define EV_CURRENT 1 - -#define ET_DYN 3 - -#define EM_PPC64 21 -#define EF_PPC64_ABI 3 - -typedef struct { - b_elf_word sh_name; /* Section name, index in string tbl */ - b_elf_word sh_type; /* Type of section */ - b_elf_wxword sh_flags; /* Miscellaneous section attributes */ - b_elf_addr sh_addr; /* Section virtual addr at execution */ - b_elf_off sh_offset; /* Section file offset */ - b_elf_wxword sh_size; /* Size of section in bytes */ - b_elf_word sh_link; /* Index of another section */ - b_elf_word sh_info; /* Additional section information */ - b_elf_wxword sh_addralign; /* Section alignment */ - b_elf_wxword sh_entsize; /* Entry size if section holds table */ -} b_elf_shdr; /* Elf_Shdr. */ - -#define SHN_UNDEF 0x0000 /* Undefined section */ -#define SHN_LORESERVE 0xFF00 /* Begin range of reserved indices */ -#define SHN_XINDEX 0xFFFF /* Section index is held elsewhere */ - -#define SHT_PROGBITS 1 -#define SHT_SYMTAB 2 -#define SHT_STRTAB 3 -#define SHT_DYNSYM 11 - -#define SHF_COMPRESSED 0x800 - -#if BACKTRACE_ELF_SIZE == 32 - -typedef struct -{ - b_elf_word st_name; /* Symbol name, index in string tbl */ - b_elf_addr st_value; /* Symbol value */ - b_elf_word st_size; /* Symbol size */ - unsigned char st_info; /* Symbol binding and type */ - unsigned char st_other; /* Visibility and other data */ - b_elf_half st_shndx; /* Symbol section index */ -} b_elf_sym; /* Elf_Sym. */ - -#else /* BACKTRACE_ELF_SIZE != 32 */ - -typedef struct -{ - b_elf_word st_name; /* Symbol name, index in string tbl */ - unsigned char st_info; /* Symbol binding and type */ - unsigned char st_other; /* Visibility and other data */ - b_elf_half st_shndx; /* Symbol section index */ - b_elf_addr st_value; /* Symbol value */ - b_elf_xword st_size; /* Symbol size */ -} b_elf_sym; /* Elf_Sym. */ - -#endif /* BACKTRACE_ELF_SIZE != 32 */ - -#define STT_OBJECT 1 -#define STT_FUNC 2 - -typedef struct -{ - uint32_t namesz; - uint32_t descsz; - uint32_t type; - char name[1]; -} b_elf_note; - -#define NT_GNU_BUILD_ID 3 - -#if BACKTRACE_ELF_SIZE == 32 - -typedef struct -{ - b_elf_word ch_type; /* Compresstion algorithm */ - b_elf_word ch_size; /* Uncompressed size */ - b_elf_word ch_addralign; /* Alignment for uncompressed data */ -} b_elf_chdr; /* Elf_Chdr */ - -#else /* BACKTRACE_ELF_SIZE != 32 */ - -typedef struct -{ - b_elf_word ch_type; /* Compression algorithm */ - b_elf_word ch_reserved; /* Reserved */ - b_elf_xword ch_size; /* Uncompressed size */ - b_elf_xword ch_addralign; /* Alignment for uncompressed data */ -} b_elf_chdr; /* Elf_Chdr */ - -#endif /* BACKTRACE_ELF_SIZE != 32 */ - -#define ELFCOMPRESS_ZLIB 1 - -/* An index of ELF sections we care about. */ - -enum debug_section -{ - DEBUG_INFO, - DEBUG_LINE, - DEBUG_ABBREV, - DEBUG_RANGES, - DEBUG_STR, - - /* The old style compressed sections. This list must correspond to - the list of normal debug sections. */ - ZDEBUG_INFO, - ZDEBUG_LINE, - ZDEBUG_ABBREV, - ZDEBUG_RANGES, - ZDEBUG_STR, - - DEBUG_MAX -}; - -/* Names of sections, indexed by enum elf_section. */ - -static const char * const debug_section_names[DEBUG_MAX] = -{ - ".debug_info", - ".debug_line", - ".debug_abbrev", - ".debug_ranges", - ".debug_str", - ".zdebug_info", - ".zdebug_line", - ".zdebug_abbrev", - ".zdebug_ranges", - ".zdebug_str" -}; - -/* Information we gather for the sections we care about. */ - -struct debug_section_info -{ - /* Section file offset. */ - off_t offset; - /* Section size. */ - size_t size; - /* Section contents, after read from file. */ - const unsigned char *data; - /* Whether the SHF_COMPRESSED flag is set for the section. */ - int compressed; -}; - -/* Information we keep for an ELF symbol. */ - -struct elf_symbol -{ - /* The name of the symbol. */ - const char *name; - /* The address of the symbol. */ - uintptr_t address; - /* The size of the symbol. */ - size_t size; -}; - -/* Information to pass to elf_syminfo. */ - -struct elf_syminfo_data -{ - /* Symbols for the next module. */ - struct elf_syminfo_data *next; - /* The ELF symbols, sorted by address. */ - struct elf_symbol *symbols; - /* The number of symbols. */ - size_t count; -}; - -/* Information about PowerPC64 ELFv1 .opd section. */ - -struct elf_ppc64_opd_data -{ - /* Address of the .opd section. */ - b_elf_addr addr; - /* Section data. */ - const char *data; - /* Size of the .opd section. */ - size_t size; - /* Corresponding section view. */ - struct backtrace_view view; -}; - -/* Compute the CRC-32 of BUF/LEN. This uses the CRC used for - .gnu_debuglink files. */ - -static uint32_t -elf_crc32 (uint32_t crc, const unsigned char *buf, size_t len) -{ - static const uint32_t crc32_table[256] = - { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d - }; - const unsigned char *end; - - crc = ~crc; - for (end = buf + len; buf < end; ++ buf) - crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8); - return ~crc; -} - -/* Return the CRC-32 of the entire file open at DESCRIPTOR. */ - -static uint32_t -elf_crc32_file (struct backtrace_state *state, int descriptor, - backtrace_error_callback error_callback, void *data) -{ - struct stat st; - struct backtrace_view file_view; - uint32_t ret; - - if (fstat (descriptor, &st) < 0) - { - error_callback (data, "fstat", errno); - return 0; - } - - if (!backtrace_get_view (state, descriptor, 0, st.st_size, error_callback, - data, &file_view)) - return 0; - - ret = elf_crc32 (0, (const unsigned char *) file_view.data, st.st_size); - - backtrace_release_view (state, &file_view, error_callback, data); - - return ret; -} - -/* A dummy callback function used when we can't find any debug info. */ - -static int -elf_nodebug (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t pc ATTRIBUTE_UNUSED, - backtrace_full_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no debug info in ELF executable", -1); - return 0; -} - -/* A dummy callback function used when we can't find a symbol - table. */ - -static void -elf_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t addr ATTRIBUTE_UNUSED, - backtrace_syminfo_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no symbol table in ELF executable", -1); -} - -/* Compare struct elf_symbol for qsort. */ - -static int -elf_symbol_compare (const void *v1, const void *v2) -{ - const struct elf_symbol *e1 = (const struct elf_symbol *) v1; - const struct elf_symbol *e2 = (const struct elf_symbol *) v2; - - if (e1->address < e2->address) - return -1; - else if (e1->address > e2->address) - return 1; - else - return 0; -} - -/* Compare an ADDR against an elf_symbol for bsearch. We allocate one - extra entry in the array so that this can look safely at the next - entry. */ - -static int -elf_symbol_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct elf_symbol *entry = (const struct elf_symbol *) ventry; - uintptr_t addr; - - addr = *key; - if (addr < entry->address) - return -1; - else if (addr >= entry->address + entry->size) - return 1; - else - return 0; -} - -/* Initialize the symbol table info for elf_syminfo. */ - -static int -elf_initialize_syminfo (struct backtrace_state *state, - uintptr_t base_address, - const unsigned char *symtab_data, size_t symtab_size, - const unsigned char *strtab, size_t strtab_size, - backtrace_error_callback error_callback, - void *data, struct elf_syminfo_data *sdata, - struct elf_ppc64_opd_data *opd) -{ - size_t sym_count; - const b_elf_sym *sym; - size_t elf_symbol_count; - size_t elf_symbol_size; - struct elf_symbol *elf_symbols; - size_t i; - unsigned int j; - - sym_count = symtab_size / sizeof (b_elf_sym); - - /* We only care about function symbols. Count them. */ - sym = (const b_elf_sym *) symtab_data; - elf_symbol_count = 0; - for (i = 0; i < sym_count; ++i, ++sym) - { - int info; - - info = sym->st_info & 0xf; - if ((info == STT_FUNC || info == STT_OBJECT) - && sym->st_shndx != SHN_UNDEF) - ++elf_symbol_count; - } - - elf_symbol_size = elf_symbol_count * sizeof (struct elf_symbol); - elf_symbols = ((struct elf_symbol *) - backtrace_alloc (state, elf_symbol_size, error_callback, - data)); - if (elf_symbols == NULL) - return 0; - - sym = (const b_elf_sym *) symtab_data; - j = 0; - for (i = 0; i < sym_count; ++i, ++sym) - { - int info; - - info = sym->st_info & 0xf; - if (info != STT_FUNC && info != STT_OBJECT) - continue; - if (sym->st_shndx == SHN_UNDEF) - continue; - if (sym->st_name >= strtab_size) - { - error_callback (data, "symbol string index out of range", 0); - backtrace_free (state, elf_symbols, elf_symbol_size, error_callback, - data); - return 0; - } - elf_symbols[j].name = (const char *) strtab + sym->st_name; - /* Special case PowerPC64 ELFv1 symbols in .opd section, if the symbol - is a function descriptor, read the actual code address from the - descriptor. */ - if (opd - && sym->st_value >= opd->addr - && sym->st_value < opd->addr + opd->size) - elf_symbols[j].address - = *(const b_elf_addr *) (opd->data + (sym->st_value - opd->addr)); - else - elf_symbols[j].address = sym->st_value; - elf_symbols[j].address += base_address; - elf_symbols[j].size = sym->st_size; - ++j; - } - - backtrace_qsort (elf_symbols, elf_symbol_count, sizeof (struct elf_symbol), - elf_symbol_compare); - - sdata->next = NULL; - sdata->symbols = elf_symbols; - sdata->count = elf_symbol_count; - - return 1; -} - -/* Add EDATA to the list in STATE. */ - -static void -elf_add_syminfo_data (struct backtrace_state *state, - struct elf_syminfo_data *edata) -{ - if (!state->threaded) - { - struct elf_syminfo_data **pp; - - for (pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data; - *pp != NULL; - pp = &(*pp)->next) - ; - *pp = edata; - } - else - { - while (1) - { - struct elf_syminfo_data **pp; - - pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data; - - while (1) - { - struct elf_syminfo_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, edata)) - break; - } - } -} - -/* Return the symbol name and value for an ADDR. */ - -static void -elf_syminfo (struct backtrace_state *state, uintptr_t addr, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data) -{ - struct elf_syminfo_data *edata; - struct elf_symbol *sym = NULL; - - if (!state->threaded) - { - for (edata = (struct elf_syminfo_data *) state->syminfo_data; - edata != NULL; - edata = edata->next) - { - sym = ((struct elf_symbol *) - bsearch (&addr, edata->symbols, edata->count, - sizeof (struct elf_symbol), elf_symbol_search)); - if (sym != NULL) - break; - } - } - else - { - struct elf_syminfo_data **pp; - - pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data; - while (1) - { - edata = backtrace_atomic_load_pointer (pp); - if (edata == NULL) - break; - - sym = ((struct elf_symbol *) - bsearch (&addr, edata->symbols, edata->count, - sizeof (struct elf_symbol), elf_symbol_search)); - if (sym != NULL) - break; - - pp = &edata->next; - } - } - - if (sym == NULL) - callback (data, addr, NULL, 0, 0); - else - callback (data, addr, sym->name, sym->address, sym->size); -} - -/* Return whether FILENAME is a symlink. */ - -static int -elf_is_symlink (const char *filename) -{ - struct stat st; - - if (lstat (filename, &st) < 0) - return 0; - return S_ISLNK (st.st_mode); -} - -/* Return the results of reading the symlink FILENAME in a buffer - allocated by backtrace_alloc. Return the length of the buffer in - *LEN. */ - -static char * -elf_readlink (struct backtrace_state *state, const char *filename, - backtrace_error_callback error_callback, void *data, - size_t *plen) -{ - size_t len; - char *buf; - - len = 128; - while (1) - { - ssize_t rl; - - buf = backtrace_alloc (state, len, error_callback, data); - if (buf == NULL) - return NULL; - rl = readlink (filename, buf, len); - if (rl < 0) - { - backtrace_free (state, buf, len, error_callback, data); - return NULL; - } - if ((size_t) rl < len - 1) - { - buf[rl] = '\0'; - *plen = len; - return buf; - } - backtrace_free (state, buf, len, error_callback, data); - len *= 2; - } -} - -/* Open a separate debug info file, using the build ID to find it. - Returns an open file descriptor, or -1. - - The GDB manual says that the only place gdb looks for a debug file - when the build ID is known is in /usr/lib/debug/.build-id. */ - -static int -elf_open_debugfile_by_buildid (struct backtrace_state *state, - const char *buildid_data, size_t buildid_size, - backtrace_error_callback error_callback, - void *data) -{ - const char * const prefix = "/usr/lib/debug/.build-id/"; - const size_t prefix_len = strlen (prefix); - const char * const suffix = ".debug"; - const size_t suffix_len = strlen (suffix); - size_t len; - char *bd_filename; - char *t; - size_t i; - int ret; - int does_not_exist; - - len = prefix_len + buildid_size * 2 + suffix_len + 2; - bd_filename = backtrace_alloc (state, len, error_callback, data); - if (bd_filename == NULL) - return -1; - - t = bd_filename; - memcpy (t, prefix, prefix_len); - t += prefix_len; - for (i = 0; i < buildid_size; i++) - { - unsigned char b; - unsigned char nib; - - b = (unsigned char) buildid_data[i]; - nib = (b & 0xf0) >> 4; - *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10; - nib = b & 0x0f; - *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10; - if (i == 0) - *t++ = '/'; - } - memcpy (t, suffix, suffix_len); - t[suffix_len] = '\0'; - - ret = backtrace_open (bd_filename, error_callback, data, &does_not_exist); - - backtrace_free (state, bd_filename, len, error_callback, data); - - /* gdb checks that the debuginfo file has the same build ID note. - That seems kind of pointless to me--why would it have the right - name but not the right build ID?--so skipping the check. */ - - return ret; -} - -/* Try to open a file whose name is PREFIX (length PREFIX_LEN) - concatenated with PREFIX2 (length PREFIX2_LEN) concatenated with - DEBUGLINK_NAME. Returns an open file descriptor, or -1. */ - -static int -elf_try_debugfile (struct backtrace_state *state, const char *prefix, - size_t prefix_len, const char *prefix2, size_t prefix2_len, - const char *debuglink_name, - backtrace_error_callback error_callback, void *data) -{ - size_t debuglink_len; - size_t try_len; - char *try; - int does_not_exist; - int ret; - - debuglink_len = strlen (debuglink_name); - try_len = prefix_len + prefix2_len + debuglink_len + 1; - try = backtrace_alloc (state, try_len, error_callback, data); - if (try == NULL) - return -1; - - memcpy (try, prefix, prefix_len); - memcpy (try + prefix_len, prefix2, prefix2_len); - memcpy (try + prefix_len + prefix2_len, debuglink_name, debuglink_len); - try[prefix_len + prefix2_len + debuglink_len] = '\0'; - - ret = backtrace_open (try, error_callback, data, &does_not_exist); - - backtrace_free (state, try, try_len, error_callback, data); - - return ret; -} - -/* Find a separate debug info file, using the debuglink section data - to find it. Returns an open file descriptor, or -1. */ - -static int -elf_find_debugfile_by_debuglink (struct backtrace_state *state, - const char *filename, - const char *debuglink_name, - backtrace_error_callback error_callback, - void *data) -{ - int ret; - char *alc; - size_t alc_len; - const char *slash; - int ddescriptor; - const char *prefix; - size_t prefix_len; - - /* Resolve symlinks in FILENAME. Since FILENAME is fairly likely to - be /proc/self/exe, symlinks are common. We don't try to resolve - the whole path name, just the base name. */ - ret = -1; - alc = NULL; - alc_len = 0; - while (elf_is_symlink (filename)) - { - char *new_buf; - size_t new_len; - - new_buf = elf_readlink (state, filename, error_callback, data, &new_len); - if (new_buf == NULL) - break; - - if (new_buf[0] == '/') - filename = new_buf; - else - { - slash = strrchr (filename, '/'); - if (slash == NULL) - filename = new_buf; - else - { - size_t clen; - char *c; - - slash++; - clen = slash - filename + strlen (new_buf) + 1; - c = backtrace_alloc (state, clen, error_callback, data); - if (c == NULL) - goto done; - - memcpy (c, filename, slash - filename); - memcpy (c + (slash - filename), new_buf, strlen (new_buf)); - c[slash - filename + strlen (new_buf)] = '\0'; - backtrace_free (state, new_buf, new_len, error_callback, data); - filename = c; - new_buf = c; - new_len = clen; - } - } - - if (alc != NULL) - backtrace_free (state, alc, alc_len, error_callback, data); - alc = new_buf; - alc_len = new_len; - } - - /* Look for DEBUGLINK_NAME in the same directory as FILENAME. */ - - slash = strrchr (filename, '/'); - if (slash == NULL) - { - prefix = ""; - prefix_len = 0; - } - else - { - slash++; - prefix = filename; - prefix_len = slash - filename; - } - - ddescriptor = elf_try_debugfile (state, prefix, prefix_len, "", 0, - debuglink_name, error_callback, data); - if (ddescriptor >= 0) - { - ret = ddescriptor; - goto done; - } - - /* Look for DEBUGLINK_NAME in a .debug subdirectory of FILENAME. */ - - ddescriptor = elf_try_debugfile (state, prefix, prefix_len, ".debug/", - strlen (".debug/"), debuglink_name, - error_callback, data); - if (ddescriptor >= 0) - { - ret = ddescriptor; - goto done; - } - - /* Look for DEBUGLINK_NAME in /usr/lib/debug. */ - - ddescriptor = elf_try_debugfile (state, "/usr/lib/debug/", - strlen ("/usr/lib/debug/"), prefix, - prefix_len, debuglink_name, - error_callback, data); - if (ddescriptor >= 0) - ret = ddescriptor; - - done: - if (alc != NULL && alc_len > 0) - backtrace_free (state, alc, alc_len, error_callback, data); - return ret; -} - -/* Open a separate debug info file, using the debuglink section data - to find it. Returns an open file descriptor, or -1. */ - -static int -elf_open_debugfile_by_debuglink (struct backtrace_state *state, - const char *filename, - const char *debuglink_name, - uint32_t debuglink_crc, - backtrace_error_callback error_callback, - void *data) -{ - int ddescriptor; - - ddescriptor = elf_find_debugfile_by_debuglink (state, filename, - debuglink_name, - error_callback, data); - if (ddescriptor < 0) - return -1; - - if (debuglink_crc != 0) - { - uint32_t got_crc; - - got_crc = elf_crc32_file (state, ddescriptor, error_callback, data); - if (got_crc != debuglink_crc) - { - backtrace_close (ddescriptor, error_callback, data); - return -1; - } - } - - return ddescriptor; -} - -/* A function useful for setting a breakpoint for an inflation failure - when this code is compiled with -g. */ - -static void -elf_zlib_failed(void) -{ -} - -/* *PVAL is the current value being read from the stream, and *PBITS - is the number of valid bits. Ensure that *PVAL holds at least 15 - bits by reading additional bits from *PPIN, up to PINEND, as - needed. Updates *PPIN, *PVAL and *PBITS. Returns 1 on success, 0 - on error. */ - -static int -elf_zlib_fetch (const unsigned char **ppin, const unsigned char *pinend, - uint64_t *pval, unsigned int *pbits) -{ - unsigned int bits; - const unsigned char *pin; - uint64_t val; - uint32_t next; - - bits = *pbits; - if (bits >= 15) - return 1; - pin = *ppin; - val = *pval; - - if (unlikely (pinend - pin < 4)) - { - elf_zlib_failed (); - return 0; - } - -#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) \ - && defined(__ORDER_BIG_ENDIAN__) \ - && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \ - || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) - /* We've ensured that PIN is aligned. */ - next = *(const uint32_t *)pin; - -#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ - next = __builtin_bswap32 (next); -#endif -#else - next = pin[0] | (pin[1] << 8) | (pin[2] << 16) | (pin[3] << 24); -#endif - - val |= (uint64_t)next << bits; - bits += 32; - pin += 4; - - /* We will need the next four bytes soon. */ - __builtin_prefetch (pin, 0, 0); - - *ppin = pin; - *pval = val; - *pbits = bits; - return 1; -} - -/* Huffman code tables, like the rest of the zlib format, are defined - by RFC 1951. We store a Huffman code table as a series of tables - stored sequentially in memory. Each entry in a table is 16 bits. - The first, main, table has 256 entries. It is followed by a set of - secondary tables of length 2 to 128 entries. The maximum length of - a code sequence in the deflate format is 15 bits, so that is all we - need. Each secondary table has an index, which is the offset of - the table in the overall memory storage. - - The deflate format says that all codes of a given bit length are - lexicographically consecutive. Perhaps we could have 130 values - that require a 15-bit code, perhaps requiring three secondary - tables of size 128. I don't know if this is actually possible, but - it suggests that the maximum size required for secondary tables is - 3 * 128 + 3 * 64 ... == 768. The zlib enough program reports 660 - as the maximum. We permit 768, since in addition to the 256 for - the primary table, with two bytes per entry, and with the two - tables we need, that gives us a page. - - A single table entry needs to store a value or (for the main table - only) the index and size of a secondary table. Values range from 0 - to 285, inclusive. Secondary table indexes, per above, range from - 0 to 510. For a value we need to store the number of bits we need - to determine that value (one value may appear multiple times in the - table), which is 1 to 8. For a secondary table we need to store - the number of bits used to index into the table, which is 1 to 7. - And of course we need 1 bit to decide whether we have a value or a - secondary table index. So each entry needs 9 bits for value/table - index, 3 bits for size, 1 bit what it is. For simplicity we use 16 - bits per entry. */ - -/* Number of entries we allocate to for one code table. We get a page - for the two code tables we need. */ - -#define HUFFMAN_TABLE_SIZE (1024) - -/* Bit masks and shifts for the values in the table. */ - -#define HUFFMAN_VALUE_MASK 0x01ff -#define HUFFMAN_BITS_SHIFT 9 -#define HUFFMAN_BITS_MASK 0x7 -#define HUFFMAN_SECONDARY_SHIFT 12 - -/* For working memory while inflating we need two code tables, we need - an array of code lengths (max value 15, so we use unsigned char), - and an array of unsigned shorts used while building a table. The - latter two arrays must be large enough to hold the maximum number - of code lengths, which RFC 1951 defines as 286 + 30. */ - -#define ZDEBUG_TABLE_SIZE \ - (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \ - + (286 + 30) * sizeof (uint16_t) \ - + (286 + 30) * sizeof (unsigned char)) - -#define ZDEBUG_TABLE_CODELEN_OFFSET \ - (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \ - + (286 + 30) * sizeof (uint16_t)) - -#define ZDEBUG_TABLE_WORK_OFFSET \ - (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t)) - -#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE - -/* Used by the main function that generates the fixed table to learn - the table size. */ -static size_t final_next_secondary; - -#endif - -/* Build a Huffman code table from an array of lengths in CODES of - length CODES_LEN. The table is stored into *TABLE. ZDEBUG_TABLE - is the same as for elf_zlib_inflate, used to find some work space. - Returns 1 on success, 0 on error. */ - -static int -elf_zlib_inflate_table (unsigned char *codes, size_t codes_len, - uint16_t *zdebug_table, uint16_t *table) -{ - uint16_t count[16]; - uint16_t start[16]; - uint16_t prev[16]; - uint16_t firstcode[7]; - uint16_t *next; - size_t i; - size_t j; - unsigned int code; - size_t next_secondary; - - /* Count the number of code of each length. Set NEXT[val] to be the - next value after VAL with the same bit length. */ - - next = (uint16_t *) (((unsigned char *) zdebug_table) - + ZDEBUG_TABLE_WORK_OFFSET); - - memset (&count[0], 0, 16 * sizeof (uint16_t)); - for (i = 0; i < codes_len; ++i) - { - if (unlikely (codes[i] >= 16)) - { - elf_zlib_failed (); - return 0; - } - - if (count[codes[i]] == 0) - { - start[codes[i]] = i; - prev[codes[i]] = i; - } - else - { - next[prev[codes[i]]] = i; - prev[codes[i]] = i; - } - - ++count[codes[i]]; - } - - /* For each length, fill in the table for the codes of that - length. */ - - memset (table, 0, HUFFMAN_TABLE_SIZE * sizeof (uint16_t)); - - /* Handle the values that do not require a secondary table. */ - - code = 0; - for (j = 1; j <= 8; ++j) - { - unsigned int jcnt; - unsigned int val; - - jcnt = count[j]; - if (jcnt == 0) - continue; - - if (unlikely (jcnt > (1U << j))) - { - elf_zlib_failed (); - return 0; - } - - /* There are JCNT values that have this length, the values - starting from START[j] continuing through NEXT[VAL]. Those - values are assigned consecutive values starting at CODE. */ - - val = start[j]; - for (i = 0; i < jcnt; ++i) - { - uint16_t tval; - size_t ind; - unsigned int incr; - - /* In the compressed bit stream, the value VAL is encoded as - J bits with the value C. */ - - if (unlikely ((val & ~HUFFMAN_VALUE_MASK) != 0)) - { - elf_zlib_failed (); - return 0; - } - - tval = val | ((j - 1) << HUFFMAN_BITS_SHIFT); - - /* The table lookup uses 8 bits. If J is less than 8, we - don't know what the other bits will be. We need to fill - in all possibilities in the table. Since the Huffman - code is unambiguous, those entries can't be used for any - other code. */ - - for (ind = code; ind < 0x100; ind += 1 << j) - { - if (unlikely (table[ind] != 0)) - { - elf_zlib_failed (); - return 0; - } - table[ind] = tval; - } - - /* Advance to the next value with this length. */ - if (i + 1 < jcnt) - val = next[val]; - - /* The Huffman codes are stored in the bitstream with the - most significant bit first, as is required to make them - unambiguous. The effect is that when we read them from - the bitstream we see the bit sequence in reverse order: - the most significant bit of the Huffman code is the least - significant bit of the value we read from the bitstream. - That means that to make our table lookups work, we need - to reverse the bits of CODE. Since reversing bits is - tedious and in general requires using a table, we instead - increment CODE in reverse order. That is, if the number - of bits we are currently using, here named J, is 3, we - count as 000, 100, 010, 110, 001, 101, 011, 111, which is - to say the numbers from 0 to 7 but with the bits - reversed. Going to more bits, aka incrementing J, - effectively just adds more zero bits as the beginning, - and as such does not change the numeric value of CODE. - - To increment CODE of length J in reverse order, find the - most significant zero bit and set it to one while - clearing all higher bits. In other words, add 1 modulo - 2^J, only reversed. */ - - incr = 1U << (j - 1); - while ((code & incr) != 0) - incr >>= 1; - if (incr == 0) - code = 0; - else - { - code &= incr - 1; - code += incr; - } - } - } - - /* Handle the values that require a secondary table. */ - - /* Set FIRSTCODE, the number at which the codes start, for each - length. */ - - for (j = 9; j < 16; j++) - { - unsigned int jcnt; - unsigned int k; - - jcnt = count[j]; - if (jcnt == 0) - continue; - - /* There are JCNT values that have this length, the values - starting from START[j]. Those values are assigned - consecutive values starting at CODE. */ - - firstcode[j - 9] = code; - - /* Reverse add JCNT to CODE modulo 2^J. */ - for (k = 0; k < j; ++k) - { - if ((jcnt & (1U << k)) != 0) - { - unsigned int m; - unsigned int bit; - - bit = 1U << (j - k - 1); - for (m = 0; m < j - k; ++m, bit >>= 1) - { - if ((code & bit) == 0) - { - code += bit; - break; - } - code &= ~bit; - } - jcnt &= ~(1U << k); - } - } - if (unlikely (jcnt != 0)) - { - elf_zlib_failed (); - return 0; - } - } - - /* For J from 9 to 15, inclusive, we store COUNT[J] consecutive - values starting at START[J] with consecutive codes starting at - FIRSTCODE[J - 9]. In the primary table we need to point to the - secondary table, and the secondary table will be indexed by J - 9 - bits. We count down from 15 so that we install the larger - secondary tables first, as the smaller ones may be embedded in - the larger ones. */ - - next_secondary = 0; /* Index of next secondary table (after primary). */ - for (j = 15; j >= 9; j--) - { - unsigned int jcnt; - unsigned int val; - size_t primary; /* Current primary index. */ - size_t secondary; /* Offset to current secondary table. */ - size_t secondary_bits; /* Bit size of current secondary table. */ - - jcnt = count[j]; - if (jcnt == 0) - continue; - - val = start[j]; - code = firstcode[j - 9]; - primary = 0x100; - secondary = 0; - secondary_bits = 0; - for (i = 0; i < jcnt; ++i) - { - uint16_t tval; - size_t ind; - unsigned int incr; - - if ((code & 0xff) != primary) - { - uint16_t tprimary; - - /* Fill in a new primary table entry. */ - - primary = code & 0xff; - - tprimary = table[primary]; - if (tprimary == 0) - { - /* Start a new secondary table. */ - - if (unlikely ((next_secondary & HUFFMAN_VALUE_MASK) - != next_secondary)) - { - elf_zlib_failed (); - return 0; - } - - secondary = next_secondary; - secondary_bits = j - 8; - next_secondary += 1 << secondary_bits; - table[primary] = (secondary - + ((j - 8) << HUFFMAN_BITS_SHIFT) - + (1U << HUFFMAN_SECONDARY_SHIFT)); - } - else - { - /* There is an existing entry. It had better be a - secondary table with enough bits. */ - if (unlikely ((tprimary & (1U << HUFFMAN_SECONDARY_SHIFT)) - == 0)) - { - elf_zlib_failed (); - return 0; - } - secondary = tprimary & HUFFMAN_VALUE_MASK; - secondary_bits = ((tprimary >> HUFFMAN_BITS_SHIFT) - & HUFFMAN_BITS_MASK); - if (unlikely (secondary_bits < j - 8)) - { - elf_zlib_failed (); - return 0; - } - } - } - - /* Fill in secondary table entries. */ - - tval = val | ((j - 8) << HUFFMAN_BITS_SHIFT); - - for (ind = code >> 8; - ind < (1U << secondary_bits); - ind += 1U << (j - 8)) - { - if (unlikely (table[secondary + 0x100 + ind] != 0)) - { - elf_zlib_failed (); - return 0; - } - table[secondary + 0x100 + ind] = tval; - } - - if (i + 1 < jcnt) - val = next[val]; - - incr = 1U << (j - 1); - while ((code & incr) != 0) - incr >>= 1; - if (incr == 0) - code = 0; - else - { - code &= incr - 1; - code += incr; - } - } - } - -#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE - final_next_secondary = next_secondary; -#endif - - return 1; -} - -#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE - -/* Used to generate the fixed Huffman table for block type 1. */ - -#include - -static uint16_t table[ZDEBUG_TABLE_SIZE]; -static unsigned char codes[288]; - -int -main () -{ - size_t i; - - for (i = 0; i <= 143; ++i) - codes[i] = 8; - for (i = 144; i <= 255; ++i) - codes[i] = 9; - for (i = 256; i <= 279; ++i) - codes[i] = 7; - for (i = 280; i <= 287; ++i) - codes[i] = 8; - if (!elf_zlib_inflate_table (&codes[0], 288, &table[0], &table[0])) - { - fprintf (stderr, "elf_zlib_inflate_table failed\n"); - exit (EXIT_FAILURE); - } - - printf ("static const uint16_t elf_zlib_default_table[%#zx] =\n", - final_next_secondary + 0x100); - printf ("{\n"); - for (i = 0; i < final_next_secondary + 0x100; i += 8) - { - size_t j; - - printf (" "); - for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j) - printf (" %#x,", table[j]); - printf ("\n"); - } - printf ("};\n"); - printf ("\n"); - - for (i = 0; i < 32; ++i) - codes[i] = 5; - if (!elf_zlib_inflate_table (&codes[0], 32, &table[0], &table[0])) - { - fprintf (stderr, "elf_zlib_inflate_table failed\n"); - exit (EXIT_FAILURE); - } - - printf ("static const uint16_t elf_zlib_default_dist_table[%#zx] =\n", - final_next_secondary + 0x100); - printf ("{\n"); - for (i = 0; i < final_next_secondary + 0x100; i += 8) - { - size_t j; - - printf (" "); - for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j) - printf (" %#x,", table[j]); - printf ("\n"); - } - printf ("};\n"); - - return 0; -} - -#endif - -/* The fixed tables generated by the #ifdef'ed out main function - above. */ - -static const uint16_t elf_zlib_default_table[0x170] = -{ - 0xd00, 0xe50, 0xe10, 0xf18, 0xd10, 0xe70, 0xe30, 0x1230, - 0xd08, 0xe60, 0xe20, 0x1210, 0xe00, 0xe80, 0xe40, 0x1250, - 0xd04, 0xe58, 0xe18, 0x1200, 0xd14, 0xe78, 0xe38, 0x1240, - 0xd0c, 0xe68, 0xe28, 0x1220, 0xe08, 0xe88, 0xe48, 0x1260, - 0xd02, 0xe54, 0xe14, 0xf1c, 0xd12, 0xe74, 0xe34, 0x1238, - 0xd0a, 0xe64, 0xe24, 0x1218, 0xe04, 0xe84, 0xe44, 0x1258, - 0xd06, 0xe5c, 0xe1c, 0x1208, 0xd16, 0xe7c, 0xe3c, 0x1248, - 0xd0e, 0xe6c, 0xe2c, 0x1228, 0xe0c, 0xe8c, 0xe4c, 0x1268, - 0xd01, 0xe52, 0xe12, 0xf1a, 0xd11, 0xe72, 0xe32, 0x1234, - 0xd09, 0xe62, 0xe22, 0x1214, 0xe02, 0xe82, 0xe42, 0x1254, - 0xd05, 0xe5a, 0xe1a, 0x1204, 0xd15, 0xe7a, 0xe3a, 0x1244, - 0xd0d, 0xe6a, 0xe2a, 0x1224, 0xe0a, 0xe8a, 0xe4a, 0x1264, - 0xd03, 0xe56, 0xe16, 0xf1e, 0xd13, 0xe76, 0xe36, 0x123c, - 0xd0b, 0xe66, 0xe26, 0x121c, 0xe06, 0xe86, 0xe46, 0x125c, - 0xd07, 0xe5e, 0xe1e, 0x120c, 0xd17, 0xe7e, 0xe3e, 0x124c, - 0xd0f, 0xe6e, 0xe2e, 0x122c, 0xe0e, 0xe8e, 0xe4e, 0x126c, - 0xd00, 0xe51, 0xe11, 0xf19, 0xd10, 0xe71, 0xe31, 0x1232, - 0xd08, 0xe61, 0xe21, 0x1212, 0xe01, 0xe81, 0xe41, 0x1252, - 0xd04, 0xe59, 0xe19, 0x1202, 0xd14, 0xe79, 0xe39, 0x1242, - 0xd0c, 0xe69, 0xe29, 0x1222, 0xe09, 0xe89, 0xe49, 0x1262, - 0xd02, 0xe55, 0xe15, 0xf1d, 0xd12, 0xe75, 0xe35, 0x123a, - 0xd0a, 0xe65, 0xe25, 0x121a, 0xe05, 0xe85, 0xe45, 0x125a, - 0xd06, 0xe5d, 0xe1d, 0x120a, 0xd16, 0xe7d, 0xe3d, 0x124a, - 0xd0e, 0xe6d, 0xe2d, 0x122a, 0xe0d, 0xe8d, 0xe4d, 0x126a, - 0xd01, 0xe53, 0xe13, 0xf1b, 0xd11, 0xe73, 0xe33, 0x1236, - 0xd09, 0xe63, 0xe23, 0x1216, 0xe03, 0xe83, 0xe43, 0x1256, - 0xd05, 0xe5b, 0xe1b, 0x1206, 0xd15, 0xe7b, 0xe3b, 0x1246, - 0xd0d, 0xe6b, 0xe2b, 0x1226, 0xe0b, 0xe8b, 0xe4b, 0x1266, - 0xd03, 0xe57, 0xe17, 0xf1f, 0xd13, 0xe77, 0xe37, 0x123e, - 0xd0b, 0xe67, 0xe27, 0x121e, 0xe07, 0xe87, 0xe47, 0x125e, - 0xd07, 0xe5f, 0xe1f, 0x120e, 0xd17, 0xe7f, 0xe3f, 0x124e, - 0xd0f, 0xe6f, 0xe2f, 0x122e, 0xe0f, 0xe8f, 0xe4f, 0x126e, - 0x290, 0x291, 0x292, 0x293, 0x294, 0x295, 0x296, 0x297, - 0x298, 0x299, 0x29a, 0x29b, 0x29c, 0x29d, 0x29e, 0x29f, - 0x2a0, 0x2a1, 0x2a2, 0x2a3, 0x2a4, 0x2a5, 0x2a6, 0x2a7, - 0x2a8, 0x2a9, 0x2aa, 0x2ab, 0x2ac, 0x2ad, 0x2ae, 0x2af, - 0x2b0, 0x2b1, 0x2b2, 0x2b3, 0x2b4, 0x2b5, 0x2b6, 0x2b7, - 0x2b8, 0x2b9, 0x2ba, 0x2bb, 0x2bc, 0x2bd, 0x2be, 0x2bf, - 0x2c0, 0x2c1, 0x2c2, 0x2c3, 0x2c4, 0x2c5, 0x2c6, 0x2c7, - 0x2c8, 0x2c9, 0x2ca, 0x2cb, 0x2cc, 0x2cd, 0x2ce, 0x2cf, - 0x2d0, 0x2d1, 0x2d2, 0x2d3, 0x2d4, 0x2d5, 0x2d6, 0x2d7, - 0x2d8, 0x2d9, 0x2da, 0x2db, 0x2dc, 0x2dd, 0x2de, 0x2df, - 0x2e0, 0x2e1, 0x2e2, 0x2e3, 0x2e4, 0x2e5, 0x2e6, 0x2e7, - 0x2e8, 0x2e9, 0x2ea, 0x2eb, 0x2ec, 0x2ed, 0x2ee, 0x2ef, - 0x2f0, 0x2f1, 0x2f2, 0x2f3, 0x2f4, 0x2f5, 0x2f6, 0x2f7, - 0x2f8, 0x2f9, 0x2fa, 0x2fb, 0x2fc, 0x2fd, 0x2fe, 0x2ff, -}; - -static const uint16_t elf_zlib_default_dist_table[0x100] = -{ - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, - 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c, - 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e, - 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d, - 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f, -}; - -/* Inflate a zlib stream from PIN/SIN to POUT/SOUT. Return 1 on - success, 0 on some error parsing the stream. */ - -static int -elf_zlib_inflate (const unsigned char *pin, size_t sin, uint16_t *zdebug_table, - unsigned char *pout, size_t sout) -{ - unsigned char *porigout; - const unsigned char *pinend; - unsigned char *poutend; - - /* We can apparently see multiple zlib streams concatenated - together, so keep going as long as there is something to read. - The last 4 bytes are the checksum. */ - porigout = pout; - pinend = pin + sin; - poutend = pout + sout; - while ((pinend - pin) > 4) - { - uint64_t val; - unsigned int bits; - int last; - - /* Read the two byte zlib header. */ - - if (unlikely ((pin[0] & 0xf) != 8)) /* 8 is zlib encoding. */ - { - /* Unknown compression method. */ - elf_zlib_failed (); - return 0; - } - if (unlikely ((pin[0] >> 4) > 7)) - { - /* Window size too large. Other than this check, we don't - care about the window size. */ - elf_zlib_failed (); - return 0; - } - if (unlikely ((pin[1] & 0x20) != 0)) - { - /* Stream expects a predefined dictionary, but we have no - dictionary. */ - elf_zlib_failed (); - return 0; - } - val = (pin[0] << 8) | pin[1]; - if (unlikely (val % 31 != 0)) - { - /* Header check failure. */ - elf_zlib_failed (); - return 0; - } - pin += 2; - - /* Align PIN to a 32-bit boundary. */ - - val = 0; - bits = 0; - while ((((uintptr_t) pin) & 3) != 0) - { - val |= (uint64_t)*pin << bits; - bits += 8; - ++pin; - } - - /* Read blocks until one is marked last. */ - - last = 0; - - while (!last) - { - unsigned int type; - const uint16_t *tlit; - const uint16_t *tdist; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - last = val & 1; - type = (val >> 1) & 3; - val >>= 3; - bits -= 3; - - if (unlikely (type == 3)) - { - /* Invalid block type. */ - elf_zlib_failed (); - return 0; - } - - if (type == 0) - { - uint16_t len; - uint16_t lenc; - - /* An uncompressed block. */ - - /* If we've read ahead more than a byte, back up. */ - while (bits > 8) - { - --pin; - bits -= 8; - } - - val = 0; - bits = 0; - if (unlikely ((pinend - pin) < 4)) - { - /* Missing length. */ - elf_zlib_failed (); - return 0; - } - len = pin[0] | (pin[1] << 8); - lenc = pin[2] | (pin[3] << 8); - pin += 4; - lenc = ~lenc; - if (unlikely (len != lenc)) - { - /* Corrupt data. */ - elf_zlib_failed (); - return 0; - } - if (unlikely (len > (unsigned int) (pinend - pin) - || len > (unsigned int) (poutend - pout))) - { - /* Not enough space in buffers. */ - elf_zlib_failed (); - return 0; - } - memcpy (pout, pin, len); - pout += len; - pin += len; - - /* Align PIN. */ - while ((((uintptr_t) pin) & 3) != 0) - { - val |= (uint64_t)*pin << bits; - bits += 8; - ++pin; - } - - /* Go around to read the next block. */ - continue; - } - - if (type == 1) - { - tlit = elf_zlib_default_table; - tdist = elf_zlib_default_dist_table; - } - else - { - unsigned int nlit; - unsigned int ndist; - unsigned int nclen; - unsigned char codebits[19]; - unsigned char *plenbase; - unsigned char *plen; - unsigned char *plenend; - - /* Read a Huffman encoding table. The various magic - numbers here are from RFC 1951. */ - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - nlit = (val & 0x1f) + 257; - val >>= 5; - ndist = (val & 0x1f) + 1; - val >>= 5; - nclen = (val & 0xf) + 4; - val >>= 4; - bits -= 14; - if (unlikely (nlit > 286 || ndist > 30)) - { - /* Values out of range. */ - elf_zlib_failed (); - return 0; - } - - /* Read and build the table used to compress the - literal, length, and distance codes. */ - - memset(&codebits[0], 0, 19); - - /* There are always at least 4 elements in the - table. */ - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - codebits[16] = val & 7; - codebits[17] = (val >> 3) & 7; - codebits[18] = (val >> 6) & 7; - codebits[0] = (val >> 9) & 7; - val >>= 12; - bits -= 12; - - if (nclen == 4) - goto codebitsdone; - - codebits[8] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 5) - goto codebitsdone; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - codebits[7] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 6) - goto codebitsdone; - - codebits[9] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 7) - goto codebitsdone; - - codebits[6] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 8) - goto codebitsdone; - - codebits[10] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 9) - goto codebitsdone; - - codebits[5] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 10) - goto codebitsdone; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - codebits[11] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 11) - goto codebitsdone; - - codebits[4] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 12) - goto codebitsdone; - - codebits[12] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 13) - goto codebitsdone; - - codebits[3] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 14) - goto codebitsdone; - - codebits[13] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 15) - goto codebitsdone; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - codebits[2] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 16) - goto codebitsdone; - - codebits[14] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 17) - goto codebitsdone; - - codebits[1] = val & 7; - val >>= 3; - bits -= 3; - - if (nclen == 18) - goto codebitsdone; - - codebits[15] = val & 7; - val >>= 3; - bits -= 3; - - codebitsdone: - - if (!elf_zlib_inflate_table (codebits, 19, zdebug_table, - zdebug_table)) - return 0; - - /* Read the compressed bit lengths of the literal, - length, and distance codes. We have allocated space - at the end of zdebug_table to hold them. */ - - plenbase = (((unsigned char *) zdebug_table) - + ZDEBUG_TABLE_CODELEN_OFFSET); - plen = plenbase; - plenend = plen + nlit + ndist; - while (plen < plenend) - { - uint16_t t; - unsigned int b; - uint16_t v; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - t = zdebug_table[val & 0xff]; - - /* The compression here uses bit lengths up to 7, so - a secondary table is never necessary. */ - if (unlikely ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) != 0)) - { - elf_zlib_failed (); - return 0; - } - - b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK; - val >>= b + 1; - bits -= b + 1; - - v = t & HUFFMAN_VALUE_MASK; - if (v < 16) - *plen++ = v; - else if (v == 16) - { - unsigned int c; - unsigned int prev; - - /* Copy previous entry 3 to 6 times. */ - - if (unlikely (plen == plenbase)) - { - elf_zlib_failed (); - return 0; - } - - /* We used up to 7 bits since the last - elf_zlib_fetch, so we have at least 8 bits - available here. */ - - c = 3 + (val & 0x3); - val >>= 2; - bits -= 2; - if (unlikely ((unsigned int) (plenend - plen) < c)) - { - elf_zlib_failed (); - return 0; - } - - prev = plen[-1]; - switch (c) - { - case 6: - *plen++ = prev; - /* fallthrough */ - case 5: - *plen++ = prev; - /* fallthrough */ - case 4: - *plen++ = prev; - } - *plen++ = prev; - *plen++ = prev; - *plen++ = prev; - } - else if (v == 17) - { - unsigned int c; - - /* Store zero 3 to 10 times. */ - - /* We used up to 7 bits since the last - elf_zlib_fetch, so we have at least 8 bits - available here. */ - - c = 3 + (val & 0x7); - val >>= 3; - bits -= 3; - if (unlikely ((unsigned int) (plenend - plen) < c)) - { - elf_zlib_failed (); - return 0; - } - - switch (c) - { - case 10: - *plen++ = 0; - /* fallthrough */ - case 9: - *plen++ = 0; - /* fallthrough */ - case 8: - *plen++ = 0; - /* fallthrough */ - case 7: - *plen++ = 0; - /* fallthrough */ - case 6: - *plen++ = 0; - /* fallthrough */ - case 5: - *plen++ = 0; - /* fallthrough */ - case 4: - *plen++ = 0; - } - *plen++ = 0; - *plen++ = 0; - *plen++ = 0; - } - else if (v == 18) - { - unsigned int c; - - /* Store zero 11 to 138 times. */ - - /* We used up to 7 bits since the last - elf_zlib_fetch, so we have at least 8 bits - available here. */ - - c = 11 + (val & 0x7f); - val >>= 7; - bits -= 7; - if (unlikely ((unsigned int) (plenend - plen) < c)) - { - elf_zlib_failed (); - return 0; - } - - memset (plen, 0, c); - plen += c; - } - else - { - elf_zlib_failed (); - return 0; - } - } - - /* Make sure that the stop code can appear. */ - - plen = plenbase; - if (unlikely (plen[256] == 0)) - { - elf_zlib_failed (); - return 0; - } - - /* Build the decompression tables. */ - - if (!elf_zlib_inflate_table (plen, nlit, zdebug_table, - zdebug_table)) - return 0; - if (!elf_zlib_inflate_table (plen + nlit, ndist, zdebug_table, - zdebug_table + HUFFMAN_TABLE_SIZE)) - return 0; - tlit = zdebug_table; - tdist = zdebug_table + HUFFMAN_TABLE_SIZE; - } - - /* Inflate values until the end of the block. This is the - main loop of the inflation code. */ - - while (1) - { - uint16_t t; - unsigned int b; - uint16_t v; - unsigned int lit; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - t = tlit[val & 0xff]; - b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK; - v = t & HUFFMAN_VALUE_MASK; - - if ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) == 0) - { - lit = v; - val >>= b + 1; - bits -= b + 1; - } - else - { - t = tlit[v + 0x100 + ((val >> 8) & ((1U << b) - 1))]; - b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK; - lit = t & HUFFMAN_VALUE_MASK; - val >>= b + 8; - bits -= b + 8; - } - - if (lit < 256) - { - if (unlikely (pout == poutend)) - { - elf_zlib_failed (); - return 0; - } - - *pout++ = lit; - - /* We will need to write the next byte soon. We ask - for high temporal locality because we will write - to the whole cache line soon. */ - __builtin_prefetch (pout, 1, 3); - } - else if (lit == 256) - { - /* The end of the block. */ - break; - } - else - { - unsigned int dist; - unsigned int len; - - /* Convert lit into a length. */ - - if (lit < 265) - len = lit - 257 + 3; - else if (lit == 285) - len = 258; - else if (unlikely (lit > 285)) - { - elf_zlib_failed (); - return 0; - } - else - { - unsigned int extra; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - /* This is an expression for the table of length - codes in RFC 1951 3.2.5. */ - lit -= 265; - extra = (lit >> 2) + 1; - len = (lit & 3) << extra; - len += 11; - len += ((1U << (extra - 1)) - 1) << 3; - len += val & ((1U << extra) - 1); - val >>= extra; - bits -= extra; - } - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - t = tdist[val & 0xff]; - b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK; - v = t & HUFFMAN_VALUE_MASK; - - if ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) == 0) - { - dist = v; - val >>= b + 1; - bits -= b + 1; - } - else - { - t = tdist[v + 0x100 + ((val >> 8) & ((1U << b) - 1))]; - b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK; - dist = t & HUFFMAN_VALUE_MASK; - val >>= b + 8; - bits -= b + 8; - } - - /* Convert dist to a distance. */ - - if (dist == 0) - { - /* A distance of 1. A common case, meaning - repeat the last character LEN times. */ - - if (unlikely (pout == porigout)) - { - elf_zlib_failed (); - return 0; - } - - if (unlikely ((unsigned int) (poutend - pout) < len)) - { - elf_zlib_failed (); - return 0; - } - - memset (pout, pout[-1], len); - pout += len; - } - else if (unlikely (dist > 29)) - { - elf_zlib_failed (); - return 0; - } - else - { - if (dist < 4) - dist = dist + 1; - else - { - unsigned int extra; - - if (!elf_zlib_fetch (&pin, pinend, &val, &bits)) - return 0; - - /* This is an expression for the table of - distance codes in RFC 1951 3.2.5. */ - dist -= 4; - extra = (dist >> 1) + 1; - dist = (dist & 1) << extra; - dist += 5; - dist += ((1U << (extra - 1)) - 1) << 2; - dist += val & ((1U << extra) - 1); - val >>= extra; - bits -= extra; - } - - /* Go back dist bytes, and copy len bytes from - there. */ - - if (unlikely ((unsigned int) (pout - porigout) < dist)) - { - elf_zlib_failed (); - return 0; - } - - if (unlikely ((unsigned int) (poutend - pout) < len)) - { - elf_zlib_failed (); - return 0; - } - - if (dist >= len) - { - memcpy (pout, pout - dist, len); - pout += len; - } - else - { - while (len > 0) - { - unsigned int copy; - - copy = len < dist ? len : dist; - memcpy (pout, pout - dist, copy); - len -= copy; - pout += copy; - } - } - } - } - } - } - } - - /* We should have filled the output buffer. */ - if (unlikely (pout != poutend)) - { - elf_zlib_failed (); - return 0; - } - - return 1; -} - -/* Verify the zlib checksum. The checksum is in the 4 bytes at - CHECKBYTES, and the uncompressed data is at UNCOMPRESSED / - UNCOMPRESSED_SIZE. Returns 1 on success, 0 on failure. */ - -static int -elf_zlib_verify_checksum (const unsigned char *checkbytes, - const unsigned char *uncompressed, - size_t uncompressed_size) -{ - unsigned int i; - unsigned int cksum; - const unsigned char *p; - uint32_t s1; - uint32_t s2; - size_t hsz; - - cksum = 0; - for (i = 0; i < 4; i++) - cksum = (cksum << 8) | checkbytes[i]; - - s1 = 1; - s2 = 0; - - /* Minimize modulo operations. */ - - p = uncompressed; - hsz = uncompressed_size; - while (hsz >= 5552) - { - for (i = 0; i < 5552; i += 16) - { - /* Manually unroll loop 16 times. */ - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - } - hsz -= 5552; - s1 %= 65521; - s2 %= 65521; - } - - while (hsz >= 16) - { - /* Manually unroll loop 16 times. */ - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - s1 = s1 + *p++; - s2 = s2 + s1; - - hsz -= 16; - } - - for (i = 0; i < hsz; ++i) - { - s1 = s1 + *p++; - s2 = s2 + s1; - } - - s1 %= 65521; - s2 %= 65521; - - if (unlikely ((s2 << 16) + s1 != cksum)) - { - elf_zlib_failed (); - return 0; - } - - return 1; -} - -/* Inflate a zlib stream from PIN/SIN to POUT/SOUT, and verify the - checksum. Return 1 on success, 0 on error. */ - -static int -elf_zlib_inflate_and_verify (const unsigned char *pin, size_t sin, - uint16_t *zdebug_table, unsigned char *pout, - size_t sout) -{ - if (!elf_zlib_inflate (pin, sin, zdebug_table, pout, sout)) - return 0; - if (!elf_zlib_verify_checksum (pin + sin - 4, pout, sout)) - return 0; - return 1; -} - -/* Uncompress the old compressed debug format, the one emitted by - --compress-debug-sections=zlib-gnu. The compressed data is in - COMPRESSED / COMPRESSED_SIZE, and the function writes to - *UNCOMPRESSED / *UNCOMPRESSED_SIZE. ZDEBUG_TABLE is work space to - hold Huffman tables. Returns 0 on error, 1 on successful - decompression or if something goes wrong. In general we try to - carry on, by returning 1, even if we can't decompress. */ - -static int -elf_uncompress_zdebug (struct backtrace_state *state, - const unsigned char *compressed, size_t compressed_size, - uint16_t *zdebug_table, - backtrace_error_callback error_callback, void *data, - unsigned char **uncompressed, size_t *uncompressed_size) -{ - size_t sz; - size_t i; - unsigned char *po; - - *uncompressed = NULL; - *uncompressed_size = 0; - - /* The format starts with the four bytes ZLIB, followed by the 8 - byte length of the uncompressed data in big-endian order, - followed by a zlib stream. */ - - if (compressed_size < 12 || memcmp (compressed, "ZLIB", 4) != 0) - return 1; - - sz = 0; - for (i = 0; i < 8; i++) - sz = (sz << 8) | compressed[i + 4]; - - if (*uncompressed != NULL && *uncompressed_size >= sz) - po = *uncompressed; - else - { - po = (unsigned char *) backtrace_alloc (state, sz, error_callback, data); - if (po == NULL) - return 0; - } - - if (!elf_zlib_inflate_and_verify (compressed + 12, compressed_size - 12, - zdebug_table, po, sz)) - return 1; - - *uncompressed = po; - *uncompressed_size = sz; - - return 1; -} - -/* Uncompress the new compressed debug format, the official standard - ELF approach emitted by --compress-debug-sections=zlib-gabi. The - compressed data is in COMPRESSED / COMPRESSED_SIZE, and the - function writes to *UNCOMPRESSED / *UNCOMPRESSED_SIZE. - ZDEBUG_TABLE is work space as for elf_uncompress_zdebug. Returns 0 - on error, 1 on successful decompression or if something goes wrong. - In general we try to carry on, by returning 1, even if we can't - decompress. */ - -static int -elf_uncompress_chdr (struct backtrace_state *state, - const unsigned char *compressed, size_t compressed_size, - uint16_t *zdebug_table, - backtrace_error_callback error_callback, void *data, - unsigned char **uncompressed, size_t *uncompressed_size) -{ - const b_elf_chdr *chdr; - unsigned char *po; - - *uncompressed = NULL; - *uncompressed_size = 0; - - /* The format starts with an ELF compression header. */ - if (compressed_size < sizeof (b_elf_chdr)) - return 1; - - chdr = (const b_elf_chdr *) compressed; - - if (chdr->ch_type != ELFCOMPRESS_ZLIB) - { - /* Unsupported compression algorithm. */ - return 1; - } - - if (*uncompressed != NULL && *uncompressed_size >= chdr->ch_size) - po = *uncompressed; - else - { - po = (unsigned char *) backtrace_alloc (state, chdr->ch_size, - error_callback, data); - if (po == NULL) - return 0; - } - - if (!elf_zlib_inflate_and_verify (compressed + sizeof (b_elf_chdr), - compressed_size - sizeof (b_elf_chdr), - zdebug_table, po, chdr->ch_size)) - return 1; - - *uncompressed = po; - *uncompressed_size = chdr->ch_size; - - return 1; -} - -/* This function is a hook for testing the zlib support. It is only - used by tests. */ - -int -backtrace_uncompress_zdebug (struct backtrace_state *state, - const unsigned char *compressed, - size_t compressed_size, - backtrace_error_callback error_callback, - void *data, unsigned char **uncompressed, - size_t *uncompressed_size) -{ - uint16_t *zdebug_table; - int ret; - - zdebug_table = ((uint16_t *) backtrace_alloc (state, ZDEBUG_TABLE_SIZE, - error_callback, data)); - if (zdebug_table == NULL) - return 0; - ret = elf_uncompress_zdebug (state, compressed, compressed_size, - zdebug_table, error_callback, data, - uncompressed, uncompressed_size); - backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE, - error_callback, data); - return ret; -} - -/* Add the backtrace data for one ELF file. Returns 1 on success, - 0 on failure (in both cases descriptor is closed) or -1 if exe - is non-zero and the ELF file is ET_DYN, which tells the caller that - elf_add will need to be called on the descriptor again after - base_address is determined. */ - -static int -elf_add (struct backtrace_state *state, const char *filename, int descriptor, - uintptr_t base_address, backtrace_error_callback error_callback, - void *data, fileline *fileline_fn, int *found_sym, int *found_dwarf, - int exe, int debuginfo) -{ - struct backtrace_view ehdr_view; - b_elf_ehdr ehdr; - off_t shoff; - unsigned int shnum; - unsigned int shstrndx; - struct backtrace_view shdrs_view; - int shdrs_view_valid; - const b_elf_shdr *shdrs; - const b_elf_shdr *shstrhdr; - size_t shstr_size; - off_t shstr_off; - struct backtrace_view names_view; - int names_view_valid; - const char *names; - unsigned int symtab_shndx; - unsigned int dynsym_shndx; - unsigned int i; - struct debug_section_info sections[DEBUG_MAX]; - struct backtrace_view symtab_view; - int symtab_view_valid; - struct backtrace_view strtab_view; - int strtab_view_valid; - struct backtrace_view buildid_view; - int buildid_view_valid; - const char *buildid_data; - uint32_t buildid_size; - struct backtrace_view debuglink_view; - int debuglink_view_valid; - const char *debuglink_name; - uint32_t debuglink_crc; - off_t min_offset; - off_t max_offset; - struct backtrace_view debug_view; - int debug_view_valid; - unsigned int using_debug_view; - uint16_t *zdebug_table; - struct elf_ppc64_opd_data opd_data, *opd; - - if (!debuginfo) - { - *found_sym = 0; - *found_dwarf = 0; - } - - shdrs_view_valid = 0; - names_view_valid = 0; - symtab_view_valid = 0; - strtab_view_valid = 0; - buildid_view_valid = 0; - buildid_data = NULL; - buildid_size = 0; - debuglink_view_valid = 0; - debuglink_name = NULL; - debuglink_crc = 0; - debug_view_valid = 0; - opd = NULL; - - if (!backtrace_get_view (state, descriptor, 0, sizeof ehdr, error_callback, - data, &ehdr_view)) - goto fail; - - memcpy (&ehdr, ehdr_view.data, sizeof ehdr); - - backtrace_release_view (state, &ehdr_view, error_callback, data); - - if (ehdr.e_ident[EI_MAG0] != ELFMAG0 - || ehdr.e_ident[EI_MAG1] != ELFMAG1 - || ehdr.e_ident[EI_MAG2] != ELFMAG2 - || ehdr.e_ident[EI_MAG3] != ELFMAG3) - { - error_callback (data, "executable file is not ELF", 0); - goto fail; - } - if (ehdr.e_ident[EI_VERSION] != EV_CURRENT) - { - error_callback (data, "executable file is unrecognized ELF version", 0); - goto fail; - } - -#if BACKTRACE_ELF_SIZE == 32 -#define BACKTRACE_ELFCLASS ELFCLASS32 -#else -#define BACKTRACE_ELFCLASS ELFCLASS64 -#endif - - if (ehdr.e_ident[EI_CLASS] != BACKTRACE_ELFCLASS) - { - error_callback (data, "executable file is unexpected ELF class", 0); - goto fail; - } - - if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB - && ehdr.e_ident[EI_DATA] != ELFDATA2MSB) - { - error_callback (data, "executable file has unknown endianness", 0); - goto fail; - } - - /* If the executable is ET_DYN, it is either a PIE, or we are running - directly a shared library with .interp. We need to wait for - dl_iterate_phdr in that case to determine the actual base_address. */ - if (exe && ehdr.e_type == ET_DYN) - return -1; - - shoff = ehdr.e_shoff; - shnum = ehdr.e_shnum; - shstrndx = ehdr.e_shstrndx; - - if ((shnum == 0 || shstrndx == SHN_XINDEX) - && shoff != 0) - { - struct backtrace_view shdr_view; - const b_elf_shdr *shdr; - - if (!backtrace_get_view (state, descriptor, shoff, sizeof shdr, - error_callback, data, &shdr_view)) - goto fail; - - shdr = (const b_elf_shdr *) shdr_view.data; - - if (shnum == 0) - shnum = shdr->sh_size; - - if (shstrndx == SHN_XINDEX) - { - shstrndx = shdr->sh_link; - - /* Versions of the GNU binutils between 2.12 and 2.18 did - not handle objects with more than SHN_LORESERVE sections - correctly. All large section indexes were offset by - 0x100. There is more information at - http://sourceware.org/bugzilla/show_bug.cgi?id-5900 . - Fortunately these object files are easy to detect, as the - GNU binutils always put the section header string table - near the end of the list of sections. Thus if the - section header string table index is larger than the - number of sections, then we know we have to subtract - 0x100 to get the real section index. */ - if (shstrndx >= shnum && shstrndx >= SHN_LORESERVE + 0x100) - shstrndx -= 0x100; - } - - backtrace_release_view (state, &shdr_view, error_callback, data); - } - - /* To translate PC to file/line when using DWARF, we need to find - the .debug_info and .debug_line sections. */ - - /* Read the section headers, skipping the first one. */ - - if (!backtrace_get_view (state, descriptor, shoff + sizeof (b_elf_shdr), - (shnum - 1) * sizeof (b_elf_shdr), - error_callback, data, &shdrs_view)) - goto fail; - shdrs_view_valid = 1; - shdrs = (const b_elf_shdr *) shdrs_view.data; - - /* Read the section names. */ - - shstrhdr = &shdrs[shstrndx - 1]; - shstr_size = shstrhdr->sh_size; - shstr_off = shstrhdr->sh_offset; - - if (!backtrace_get_view (state, descriptor, shstr_off, shstr_size, - error_callback, data, &names_view)) - goto fail; - names_view_valid = 1; - names = (const char *) names_view.data; - - symtab_shndx = 0; - dynsym_shndx = 0; - - memset (sections, 0, sizeof sections); - - /* Look for the symbol table. */ - for (i = 1; i < shnum; ++i) - { - const b_elf_shdr *shdr; - unsigned int sh_name; - const char *name; - int j; - - shdr = &shdrs[i - 1]; - - if (shdr->sh_type == SHT_SYMTAB) - symtab_shndx = i; - else if (shdr->sh_type == SHT_DYNSYM) - dynsym_shndx = i; - - sh_name = shdr->sh_name; - if (sh_name >= shstr_size) - { - error_callback (data, "ELF section name out of range", 0); - goto fail; - } - - name = names + sh_name; - - for (j = 0; j < (int) DEBUG_MAX; ++j) - { - if (strcmp (name, debug_section_names[j]) == 0) - { - sections[j].offset = shdr->sh_offset; - sections[j].size = shdr->sh_size; - sections[j].compressed = (shdr->sh_flags & SHF_COMPRESSED) != 0; - break; - } - } - - /* Read the build ID if present. This could check for any - SHT_NOTE section with the right note name and type, but gdb - looks for a specific section name. */ - if (!debuginfo - && !buildid_view_valid - && strcmp (name, ".note.gnu.build-id") == 0) - { - const b_elf_note *note; - - if (!backtrace_get_view (state, descriptor, shdr->sh_offset, - shdr->sh_size, error_callback, data, - &buildid_view)) - goto fail; - - buildid_view_valid = 1; - note = (const b_elf_note *) buildid_view.data; - if (note->type == NT_GNU_BUILD_ID - && note->namesz == 4 - && strncmp (note->name, "GNU", 4) == 0 - && shdr->sh_size < 12 + ((note->namesz + 3) & ~ 3) + note->descsz) - { - buildid_data = ¬e->name[0] + ((note->namesz + 3) & ~ 3); - buildid_size = note->descsz; - } - } - - /* Read the debuglink file if present. */ - if (!debuginfo - && !debuglink_view_valid - && strcmp (name, ".gnu_debuglink") == 0) - { - const char *debuglink_data; - size_t crc_offset; - - if (!backtrace_get_view (state, descriptor, shdr->sh_offset, - shdr->sh_size, error_callback, data, - &debuglink_view)) - goto fail; - - debuglink_view_valid = 1; - debuglink_data = (const char *) debuglink_view.data; - crc_offset = strnlen (debuglink_data, shdr->sh_size); - crc_offset = (crc_offset + 3) & ~3; - if (crc_offset + 4 <= shdr->sh_size) - { - debuglink_name = debuglink_data; - debuglink_crc = *(const uint32_t*)(debuglink_data + crc_offset); - } - } - - /* Read the .opd section on PowerPC64 ELFv1. */ - if (ehdr.e_machine == EM_PPC64 - && (ehdr.e_flags & EF_PPC64_ABI) < 2 - && shdr->sh_type == SHT_PROGBITS - && strcmp (name, ".opd") == 0) - { - if (!backtrace_get_view (state, descriptor, shdr->sh_offset, - shdr->sh_size, error_callback, data, - &opd_data.view)) - goto fail; - - opd = &opd_data; - opd->addr = shdr->sh_addr; - opd->data = (const char *) opd_data.view.data; - opd->size = shdr->sh_size; - } - } - - if (symtab_shndx == 0) - symtab_shndx = dynsym_shndx; - if (symtab_shndx != 0 && !debuginfo) - { - const b_elf_shdr *symtab_shdr; - unsigned int strtab_shndx; - const b_elf_shdr *strtab_shdr; - struct elf_syminfo_data *sdata; - - symtab_shdr = &shdrs[symtab_shndx - 1]; - strtab_shndx = symtab_shdr->sh_link; - if (strtab_shndx >= shnum) - { - error_callback (data, - "ELF symbol table strtab link out of range", 0); - goto fail; - } - strtab_shdr = &shdrs[strtab_shndx - 1]; - - if (!backtrace_get_view (state, descriptor, symtab_shdr->sh_offset, - symtab_shdr->sh_size, error_callback, data, - &symtab_view)) - goto fail; - symtab_view_valid = 1; - - if (!backtrace_get_view (state, descriptor, strtab_shdr->sh_offset, - strtab_shdr->sh_size, error_callback, data, - &strtab_view)) - goto fail; - strtab_view_valid = 1; - - sdata = ((struct elf_syminfo_data *) - backtrace_alloc (state, sizeof *sdata, error_callback, data)); - if (sdata == NULL) - goto fail; - - if (!elf_initialize_syminfo (state, base_address, - symtab_view.data, symtab_shdr->sh_size, - strtab_view.data, strtab_shdr->sh_size, - error_callback, data, sdata, opd)) - { - backtrace_free (state, sdata, sizeof *sdata, error_callback, data); - goto fail; - } - - /* We no longer need the symbol table, but we hold on to the - string table permanently. */ - backtrace_release_view (state, &symtab_view, error_callback, data); - symtab_view_valid = 0; - - *found_sym = 1; - - elf_add_syminfo_data (state, sdata); - } - - backtrace_release_view (state, &shdrs_view, error_callback, data); - shdrs_view_valid = 0; - backtrace_release_view (state, &names_view, error_callback, data); - names_view_valid = 0; - - /* If the debug info is in a separate file, read that one instead. */ - - if (buildid_data != NULL) - { - int d; - - d = elf_open_debugfile_by_buildid (state, buildid_data, buildid_size, - error_callback, data); - if (d >= 0) - { - int ret; - - backtrace_release_view (state, &buildid_view, error_callback, data); - if (debuglink_view_valid) - backtrace_release_view (state, &debuglink_view, error_callback, - data); - ret = elf_add (state, NULL, d, base_address, error_callback, data, - fileline_fn, found_sym, found_dwarf, 0, 1); - if (ret < 0) - backtrace_close (d, error_callback, data); - else - backtrace_close (descriptor, error_callback, data); - return ret; - } - } - - if (buildid_view_valid) - { - backtrace_release_view (state, &buildid_view, error_callback, data); - buildid_view_valid = 0; - } - - if (opd) - { - backtrace_release_view (state, &opd->view, error_callback, data); - opd = NULL; - } - - if (debuglink_name != NULL) - { - int d; - - d = elf_open_debugfile_by_debuglink (state, filename, debuglink_name, - debuglink_crc, error_callback, - data); - if (d >= 0) - { - int ret; - - backtrace_release_view (state, &debuglink_view, error_callback, - data); - ret = elf_add (state, NULL, d, base_address, error_callback, data, - fileline_fn, found_sym, found_dwarf, 0, 1); - if (ret < 0) - backtrace_close (d, error_callback, data); - else - backtrace_close(descriptor, error_callback, data); - return ret; - } - } - - if (debuglink_view_valid) - { - backtrace_release_view (state, &debuglink_view, error_callback, data); - debuglink_view_valid = 0; - } - - /* Read all the debug sections in a single view, since they are - probably adjacent in the file. We never release this view. */ - - min_offset = 0; - max_offset = 0; - for (i = 0; i < (int) DEBUG_MAX; ++i) - { - off_t end; - - if (sections[i].size == 0) - continue; - if (min_offset == 0 || sections[i].offset < min_offset) - min_offset = sections[i].offset; - end = sections[i].offset + sections[i].size; - if (end > max_offset) - max_offset = end; - } - if (min_offset == 0 || max_offset == 0) - { - if (!backtrace_close (descriptor, error_callback, data)) - goto fail; - return 1; - } - - if (!backtrace_get_view (state, descriptor, min_offset, - max_offset - min_offset, - error_callback, data, &debug_view)) - goto fail; - debug_view_valid = 1; - - /* We've read all we need from the executable. */ - if (!backtrace_close (descriptor, error_callback, data)) - goto fail; - descriptor = -1; - - using_debug_view = 0; - for (i = 0; i < (int) DEBUG_MAX; ++i) - { - if (sections[i].size == 0) - sections[i].data = NULL; - else - { - sections[i].data = ((const unsigned char *) debug_view.data - + (sections[i].offset - min_offset)); - if (i < ZDEBUG_INFO) - ++using_debug_view; - } - } - - /* Uncompress the old format (--compress-debug-sections=zlib-gnu). */ - - zdebug_table = NULL; - for (i = 0; i < ZDEBUG_INFO; ++i) - { - struct debug_section_info *pz; - - pz = §ions[i + ZDEBUG_INFO - DEBUG_INFO]; - if (sections[i].size == 0 && pz->size > 0) - { - unsigned char *uncompressed_data; - size_t uncompressed_size; - - if (zdebug_table == NULL) - { - zdebug_table = ((uint16_t *) - backtrace_alloc (state, ZDEBUG_TABLE_SIZE, - error_callback, data)); - if (zdebug_table == NULL) - goto fail; - } - - uncompressed_data = NULL; - uncompressed_size = 0; - if (!elf_uncompress_zdebug (state, pz->data, pz->size, zdebug_table, - error_callback, data, - &uncompressed_data, &uncompressed_size)) - goto fail; - sections[i].data = uncompressed_data; - sections[i].size = uncompressed_size; - sections[i].compressed = 0; - } - } - - /* Uncompress the official ELF format - (--compress-debug-sections=zlib-gabi). */ - for (i = 0; i < ZDEBUG_INFO; ++i) - { - unsigned char *uncompressed_data; - size_t uncompressed_size; - - if (sections[i].size == 0 || !sections[i].compressed) - continue; - - if (zdebug_table == NULL) - { - zdebug_table = ((uint16_t *) - backtrace_alloc (state, ZDEBUG_TABLE_SIZE, - error_callback, data)); - if (zdebug_table == NULL) - goto fail; - } - - uncompressed_data = NULL; - uncompressed_size = 0; - if (!elf_uncompress_chdr (state, sections[i].data, sections[i].size, - zdebug_table, error_callback, data, - &uncompressed_data, &uncompressed_size)) - goto fail; - sections[i].data = uncompressed_data; - sections[i].size = uncompressed_size; - sections[i].compressed = 0; - - --using_debug_view; - } - - if (zdebug_table != NULL) - backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE, - error_callback, data); - - if (debug_view_valid && using_debug_view == 0) - { - backtrace_release_view (state, &debug_view, error_callback, data); - debug_view_valid = 0; - } - - if (!backtrace_dwarf_add (state, base_address, - sections[DEBUG_INFO].data, - sections[DEBUG_INFO].size, - sections[DEBUG_LINE].data, - sections[DEBUG_LINE].size, - sections[DEBUG_ABBREV].data, - sections[DEBUG_ABBREV].size, - sections[DEBUG_RANGES].data, - sections[DEBUG_RANGES].size, - sections[DEBUG_STR].data, - sections[DEBUG_STR].size, - ehdr.e_ident[EI_DATA] == ELFDATA2MSB, - error_callback, data, fileline_fn)) - goto fail; - - *found_dwarf = 1; - - return 1; - - fail: - if (shdrs_view_valid) - backtrace_release_view (state, &shdrs_view, error_callback, data); - if (names_view_valid) - backtrace_release_view (state, &names_view, error_callback, data); - if (symtab_view_valid) - backtrace_release_view (state, &symtab_view, error_callback, data); - if (strtab_view_valid) - backtrace_release_view (state, &strtab_view, error_callback, data); - if (debuglink_view_valid) - backtrace_release_view (state, &debuglink_view, error_callback, data); - if (buildid_view_valid) - backtrace_release_view (state, &buildid_view, error_callback, data); - if (debug_view_valid) - backtrace_release_view (state, &debug_view, error_callback, data); - if (opd) - backtrace_release_view (state, &opd->view, error_callback, data); - if (descriptor != -1) - backtrace_close (descriptor, error_callback, data); - return 0; -} - -/* Data passed to phdr_callback. */ - -struct phdr_data -{ - struct backtrace_state *state; - backtrace_error_callback error_callback; - void *data; - fileline *fileline_fn; - int *found_sym; - int *found_dwarf; - const char *exe_filename; - int exe_descriptor; -}; - -/* Callback passed to dl_iterate_phdr. Load debug info from shared - libraries. */ - -static int -#ifdef __i386__ -__attribute__ ((__force_align_arg_pointer__)) -#endif -phdr_callback (struct dl_phdr_info *info, size_t size ATTRIBUTE_UNUSED, - void *pdata) -{ - struct phdr_data *pd = (struct phdr_data *) pdata; - const char *filename; - int descriptor; - int does_not_exist; - fileline elf_fileline_fn; - int found_dwarf; - - /* There is not much we can do if we don't have the module name, - unless executable is ET_DYN, where we expect the very first - phdr_callback to be for the PIE. */ - if (info->dlpi_name == NULL || info->dlpi_name[0] == '\0') - { - if (pd->exe_descriptor == -1) - return 0; - filename = pd->exe_filename; - descriptor = pd->exe_descriptor; - pd->exe_descriptor = -1; - } - else - { - if (pd->exe_descriptor != -1) - { - backtrace_close (pd->exe_descriptor, pd->error_callback, pd->data); - pd->exe_descriptor = -1; - } - - filename = info->dlpi_name; - descriptor = backtrace_open (info->dlpi_name, pd->error_callback, - pd->data, &does_not_exist); - if (descriptor < 0) - return 0; - } - - if (elf_add (pd->state, filename, descriptor, info->dlpi_addr, - pd->error_callback, pd->data, &elf_fileline_fn, pd->found_sym, - &found_dwarf, 0, 0)) - { - if (found_dwarf) - { - *pd->found_dwarf = 1; - *pd->fileline_fn = elf_fileline_fn; - } - } - - return 0; -} - -/* Initialize the backtrace data we need from an ELF executable. At - the ELF level, all we need to do is find the debug info - sections. */ - -int -backtrace_initialize (struct backtrace_state *state, const char *filename, - int descriptor, backtrace_error_callback error_callback, - void *data, fileline *fileline_fn) -{ - int ret; - int found_sym; - int found_dwarf; - fileline elf_fileline_fn = elf_nodebug; - struct phdr_data pd; - - ret = elf_add (state, filename, descriptor, 0, error_callback, data, - &elf_fileline_fn, &found_sym, &found_dwarf, 1, 0); - if (!ret) - return 0; - - pd.state = state; - pd.error_callback = error_callback; - pd.data = data; - pd.fileline_fn = &elf_fileline_fn; - pd.found_sym = &found_sym; - pd.found_dwarf = &found_dwarf; - pd.exe_filename = filename; - pd.exe_descriptor = ret < 0 ? descriptor : -1; - - dl_iterate_phdr (phdr_callback, (void *) &pd); - - if (!state->threaded) - { - if (found_sym) - state->syminfo_fn = elf_syminfo; - else if (state->syminfo_fn == NULL) - state->syminfo_fn = elf_nosyms; - } - else - { - if (found_sym) - backtrace_atomic_store_pointer (&state->syminfo_fn, elf_syminfo); - else - (void) __sync_bool_compare_and_swap (&state->syminfo_fn, NULL, - elf_nosyms); - } - - if (!state->threaded) - *fileline_fn = state->fileline_fn; - else - *fileline_fn = backtrace_atomic_load_pointer (&state->fileline_fn); - - if (*fileline_fn == NULL || *fileline_fn == elf_nodebug) - *fileline_fn = elf_fileline_fn; - - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/fileline.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/fileline.c deleted file mode 100644 index e567306..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/fileline.c +++ /dev/null @@ -1,201 +0,0 @@ -/* fileline.c -- Get file and line number information in a backtrace. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -#ifndef HAVE_GETEXECNAME -#define getexecname() NULL -#endif - -/* Initialize the fileline information from the executable. Returns 1 - on success, 0 on failure. */ - -static int -fileline_initialize (struct backtrace_state *state, - backtrace_error_callback error_callback, void *data) -{ - int failed; - fileline fileline_fn; - int pass; - int called_error_callback; - int descriptor; - const char *filename; - char buf[64]; - - if (!state->threaded) - failed = state->fileline_initialization_failed; - else - failed = backtrace_atomic_load_int (&state->fileline_initialization_failed); - - if (failed) - { - error_callback (data, "failed to read executable information", -1); - return 0; - } - - if (!state->threaded) - fileline_fn = state->fileline_fn; - else - fileline_fn = backtrace_atomic_load_pointer (&state->fileline_fn); - if (fileline_fn != NULL) - return 1; - - /* We have not initialized the information. Do it now. */ - - descriptor = -1; - called_error_callback = 0; - for (pass = 0; pass < 5; ++pass) - { - int does_not_exist; - - switch (pass) - { - case 0: - filename = state->filename; - break; - case 1: - filename = getexecname (); - break; - case 2: - filename = "/proc/self/exe"; - break; - case 3: - filename = "/proc/curproc/file"; - break; - case 4: - snprintf (buf, sizeof (buf), "/proc/%ld/object/a.out", - (long) getpid ()); - filename = buf; - break; - default: - abort (); - } - - if (filename == NULL) - continue; - - descriptor = backtrace_open (filename, error_callback, data, - &does_not_exist); - if (descriptor < 0 && !does_not_exist) - { - called_error_callback = 1; - break; - } - if (descriptor >= 0) - break; - } - - if (descriptor < 0) - { - if (!called_error_callback) - { - if (state->filename != NULL) - error_callback (data, state->filename, ENOENT); - else - error_callback (data, - "libbacktrace could not find executable to open", - 0); - } - failed = 1; - } - - if (!failed) - { - if (!backtrace_initialize (state, filename, descriptor, error_callback, - data, &fileline_fn)) - failed = 1; - } - - if (failed) - { - if (!state->threaded) - state->fileline_initialization_failed = 1; - else - backtrace_atomic_store_int (&state->fileline_initialization_failed, 1); - return 0; - } - - if (!state->threaded) - state->fileline_fn = fileline_fn; - else - { - backtrace_atomic_store_pointer (&state->fileline_fn, fileline_fn); - - /* Note that if two threads initialize at once, one of the data - sets may be leaked. */ - } - - return 1; -} - -/* Given a PC, find the file name, line number, and function name. */ - -int -backtrace_pcinfo (struct backtrace_state *state, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data) -{ - if (!fileline_initialize (state, error_callback, data)) - return 0; - - if (state->fileline_initialization_failed) - return 0; - - return state->fileline_fn (state, pc, callback, error_callback, data); -} - -/* Given a PC, find the symbol for it, and its value. */ - -int -backtrace_syminfo (struct backtrace_state *state, uintptr_t pc, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback, void *data) -{ - if (!fileline_initialize (state, error_callback, data)) - return 0; - - if (state->fileline_initialization_failed) - return 0; - - state->syminfo_fn (state, pc, callback, error_callback, data); - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filenames.h b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filenames.h deleted file mode 100644 index 2dcd664..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filenames.h +++ /dev/null @@ -1,49 +0,0 @@ -/* btest.c -- Filename header for libbacktrace library - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#ifndef GCC_VERSION -# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) -#endif - -#if (GCC_VERSION < 2007) -# define __attribute__(x) -#endif - -#ifndef ATTRIBUTE_UNUSED -# define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) -#endif - -#if defined(__MSDOS__) || defined(_WIN32) || defined(__OS2__) || defined (__CYGWIN__) -# define IS_DIR_SEPARATOR(c) ((c) == '/' || (c) == '\\') -#else -# define IS_DIR_SEPARATOR(c) ((c) == '/') -#endif diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filetype.awk b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filetype.awk deleted file mode 100644 index a5f6c8c..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/filetype.awk +++ /dev/null @@ -1,11 +0,0 @@ -# An awk script to determine the type of a file. -/\177ELF\001/ { if (NR == 1) { print "elf32"; exit } } -/\177ELF\002/ { if (NR == 1) { print "elf64"; exit } } -/\114\001/ { if (NR == 1) { print "pecoff"; exit } } -/\144\206/ { if (NR == 1) { print "pecoff"; exit } } -/\xFE\xED\xFA\xCE/ { if (NR == 1) { print "macho32"; exit } } -/\xCE\xFA\xED\xFE/ { if (NR == 1) { print "macho32"; exit } } -/\xFE\xED\xFA\xCF/ { if (NR == 1) { print "macho64"; exit } } -/\xCF\xFA\xED\xFE/ { if (NR == 1) { print "macho64"; exit } } -/\xCA\xFE\xBA\xBE/ { if (NR == 1) { print "macho-fat"; exit } } -/\xBE\xBA\xFE\xCA/ { if (NR == 1) { print "macho-fat"; exit } } diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/install-sh b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/install-sh deleted file mode 100755 index a9244eb..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/install-sh +++ /dev/null @@ -1,527 +0,0 @@ -#!/bin/sh -# install - install a program, script, or datafile - -scriptversion=2011-01-19.21; # UTC - -# This originates from X11R5 (mit/util/scripts/install.sh), which was -# later released in X11R6 (xc/config/util/install.sh) with the -# following copyright and license. -# -# Copyright (C) 1994 X Consortium -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- -# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -# Except as contained in this notice, the name of the X Consortium shall not -# be used in advertising or otherwise to promote the sale, use or other deal- -# ings in this Software without prior written authorization from the X Consor- -# tium. -# -# -# FSF changes to this file are in the public domain. -# -# Calling this script install-sh is preferred over install.sh, to prevent -# `make' implicit rules from creating a file called install from it -# when there is no Makefile. -# -# This script is compatible with the BSD install script, but was written -# from scratch. - -nl=' -' -IFS=" "" $nl" - -# set DOITPROG to echo to test this script - -# Don't use :- since 4.3BSD and earlier shells don't like it. -doit=${DOITPROG-} -if test -z "$doit"; then - doit_exec=exec -else - doit_exec=$doit -fi - -# Put in absolute file names if you don't have them in your path; -# or use environment vars. - -chgrpprog=${CHGRPPROG-chgrp} -chmodprog=${CHMODPROG-chmod} -chownprog=${CHOWNPROG-chown} -cmpprog=${CMPPROG-cmp} -cpprog=${CPPROG-cp} -mkdirprog=${MKDIRPROG-mkdir} -mvprog=${MVPROG-mv} -rmprog=${RMPROG-rm} -stripprog=${STRIPPROG-strip} - -posix_glob='?' -initialize_posix_glob=' - test "$posix_glob" != "?" || { - if (set -f) 2>/dev/null; then - posix_glob= - else - posix_glob=: - fi - } -' - -posix_mkdir= - -# Desired mode of installed file. -mode=0755 - -chgrpcmd= -chmodcmd=$chmodprog -chowncmd= -mvcmd=$mvprog -rmcmd="$rmprog -f" -stripcmd= - -src= -dst= -dir_arg= -dst_arg= - -copy_on_change=false -no_target_directory= - -usage="\ -Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE - or: $0 [OPTION]... SRCFILES... DIRECTORY - or: $0 [OPTION]... -t DIRECTORY SRCFILES... - or: $0 [OPTION]... -d DIRECTORIES... - -In the 1st form, copy SRCFILE to DSTFILE. -In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. -In the 4th, create DIRECTORIES. - -Options: - --help display this help and exit. - --version display version info and exit. - - -c (ignored) - -C install only if different (preserve the last data modification time) - -d create directories instead of installing files. - -g GROUP $chgrpprog installed files to GROUP. - -m MODE $chmodprog installed files to MODE. - -o USER $chownprog installed files to USER. - -s $stripprog installed files. - -t DIRECTORY install into DIRECTORY. - -T report an error if DSTFILE is a directory. - -Environment variables override the default commands: - CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG - RMPROG STRIPPROG -" - -while test $# -ne 0; do - case $1 in - -c) ;; - - -C) copy_on_change=true;; - - -d) dir_arg=true;; - - -g) chgrpcmd="$chgrpprog $2" - shift;; - - --help) echo "$usage"; exit $?;; - - -m) mode=$2 - case $mode in - *' '* | *' '* | *' -'* | *'*'* | *'?'* | *'['*) - echo "$0: invalid mode: $mode" >&2 - exit 1;; - esac - shift;; - - -o) chowncmd="$chownprog $2" - shift;; - - -s) stripcmd=$stripprog;; - - -t) dst_arg=$2 - # Protect names problematic for `test' and other utilities. - case $dst_arg in - -* | [=\(\)!]) dst_arg=./$dst_arg;; - esac - shift;; - - -T) no_target_directory=true;; - - --version) echo "$0 $scriptversion"; exit $?;; - - --) shift - break;; - - -*) echo "$0: invalid option: $1" >&2 - exit 1;; - - *) break;; - esac - shift -done - -if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then - # When -d is used, all remaining arguments are directories to create. - # When -t is used, the destination is already specified. - # Otherwise, the last argument is the destination. Remove it from $@. - for arg - do - if test -n "$dst_arg"; then - # $@ is not empty: it contains at least $arg. - set fnord "$@" "$dst_arg" - shift # fnord - fi - shift # arg - dst_arg=$arg - # Protect names problematic for `test' and other utilities. - case $dst_arg in - -* | [=\(\)!]) dst_arg=./$dst_arg;; - esac - done -fi - -if test $# -eq 0; then - if test -z "$dir_arg"; then - echo "$0: no input file specified." >&2 - exit 1 - fi - # It's OK to call `install-sh -d' without argument. - # This can happen when creating conditional directories. - exit 0 -fi - -if test -z "$dir_arg"; then - do_exit='(exit $ret); exit $ret' - trap "ret=129; $do_exit" 1 - trap "ret=130; $do_exit" 2 - trap "ret=141; $do_exit" 13 - trap "ret=143; $do_exit" 15 - - # Set umask so as not to create temps with too-generous modes. - # However, 'strip' requires both read and write access to temps. - case $mode in - # Optimize common cases. - *644) cp_umask=133;; - *755) cp_umask=22;; - - *[0-7]) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw='% 200' - fi - cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; - *) - if test -z "$stripcmd"; then - u_plus_rw= - else - u_plus_rw=,u+rw - fi - cp_umask=$mode$u_plus_rw;; - esac -fi - -for src -do - # Protect names problematic for `test' and other utilities. - case $src in - -* | [=\(\)!]) src=./$src;; - esac - - if test -n "$dir_arg"; then - dst=$src - dstdir=$dst - test -d "$dstdir" - dstdir_status=$? - else - - # Waiting for this to be detected by the "$cpprog $src $dsttmp" command - # might cause directories to be created, which would be especially bad - # if $src (and thus $dsttmp) contains '*'. - if test ! -f "$src" && test ! -d "$src"; then - echo "$0: $src does not exist." >&2 - exit 1 - fi - - if test -z "$dst_arg"; then - echo "$0: no destination specified." >&2 - exit 1 - fi - dst=$dst_arg - - # If destination is a directory, append the input filename; won't work - # if double slashes aren't ignored. - if test -d "$dst"; then - if test -n "$no_target_directory"; then - echo "$0: $dst_arg: Is a directory" >&2 - exit 1 - fi - dstdir=$dst - dst=$dstdir/`basename "$src"` - dstdir_status=0 - else - # Prefer dirname, but fall back on a substitute if dirname fails. - dstdir=` - (dirname "$dst") 2>/dev/null || - expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$dst" : 'X\(//\)[^/]' \| \ - X"$dst" : 'X\(//\)$' \| \ - X"$dst" : 'X\(/\)' \| . 2>/dev/null || - echo X"$dst" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q' - ` - - test -d "$dstdir" - dstdir_status=$? - fi - fi - - obsolete_mkdir_used=false - - if test $dstdir_status != 0; then - case $posix_mkdir in - '') - # Create intermediate dirs using mode 755 as modified by the umask. - # This is like FreeBSD 'install' as of 1997-10-28. - umask=`umask` - case $stripcmd.$umask in - # Optimize common cases. - *[2367][2367]) mkdir_umask=$umask;; - .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; - - *[0-7]) - mkdir_umask=`expr $umask + 22 \ - - $umask % 100 % 40 + $umask % 20 \ - - $umask % 10 % 4 + $umask % 2 - `;; - *) mkdir_umask=$umask,go-w;; - esac - - # With -d, create the new directory with the user-specified mode. - # Otherwise, rely on $mkdir_umask. - if test -n "$dir_arg"; then - mkdir_mode=-m$mode - else - mkdir_mode= - fi - - posix_mkdir=false - case $umask in - *[123567][0-7][0-7]) - # POSIX mkdir -p sets u+wx bits regardless of umask, which - # is incompatible with FreeBSD 'install' when (umask & 300) != 0. - ;; - *) - tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ - trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 - - if (umask $mkdir_umask && - exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 - then - if test -z "$dir_arg" || { - # Check for POSIX incompatibilities with -m. - # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or - # other-writeable bit of parent directory when it shouldn't. - # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. - ls_ld_tmpdir=`ls -ld "$tmpdir"` - case $ls_ld_tmpdir in - d????-?r-*) different_mode=700;; - d????-?--*) different_mode=755;; - *) false;; - esac && - $mkdirprog -m$different_mode -p -- "$tmpdir" && { - ls_ld_tmpdir_1=`ls -ld "$tmpdir"` - test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" - } - } - then posix_mkdir=: - fi - rmdir "$tmpdir/d" "$tmpdir" - else - # Remove any dirs left behind by ancient mkdir implementations. - rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null - fi - trap '' 0;; - esac;; - esac - - if - $posix_mkdir && ( - umask $mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" - ) - then : - else - - # The umask is ridiculous, or mkdir does not conform to POSIX, - # or it failed possibly due to a race condition. Create the - # directory the slow way, step by step, checking for races as we go. - - case $dstdir in - /*) prefix='/';; - [-=\(\)!]*) prefix='./';; - *) prefix='';; - esac - - eval "$initialize_posix_glob" - - oIFS=$IFS - IFS=/ - $posix_glob set -f - set fnord $dstdir - shift - $posix_glob set +f - IFS=$oIFS - - prefixes= - - for d - do - test X"$d" = X && continue - - prefix=$prefix$d - if test -d "$prefix"; then - prefixes= - else - if $posix_mkdir; then - (umask=$mkdir_umask && - $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break - # Don't fail if two instances are running concurrently. - test -d "$prefix" || exit 1 - else - case $prefix in - *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; - *) qprefix=$prefix;; - esac - prefixes="$prefixes '$qprefix'" - fi - fi - prefix=$prefix/ - done - - if test -n "$prefixes"; then - # Don't fail if two instances are running concurrently. - (umask $mkdir_umask && - eval "\$doit_exec \$mkdirprog $prefixes") || - test -d "$dstdir" || exit 1 - obsolete_mkdir_used=true - fi - fi - fi - - if test -n "$dir_arg"; then - { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && - { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || - test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 - else - - # Make a couple of temp file names in the proper directory. - dsttmp=$dstdir/_inst.$$_ - rmtmp=$dstdir/_rm.$$_ - - # Trap to clean up those temp files at exit. - trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 - - # Copy the file name to the temp name. - (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && - - # and set any options; do chmod last to preserve setuid bits. - # - # If any of these fail, we abort the whole thing. If we want to - # ignore errors from any of these, just make sure not to ignore - # errors from the above "$doit $cpprog $src $dsttmp" command. - # - { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && - { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && - { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && - { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && - - # If -C, don't bother to copy if it wouldn't change the file. - if $copy_on_change && - old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && - new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && - - eval "$initialize_posix_glob" && - $posix_glob set -f && - set X $old && old=:$2:$4:$5:$6 && - set X $new && new=:$2:$4:$5:$6 && - $posix_glob set +f && - - test "$old" = "$new" && - $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 - then - rm -f "$dsttmp" - else - # Rename the file to the real destination. - $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || - - # The rename failed, perhaps because mv can't rename something else - # to itself, or perhaps because mv is so ancient that it does not - # support -f. - { - # Now remove or move aside any old file at destination location. - # We try this two ways since rm can't unlink itself on some - # systems and the destination file might be busy for other - # reasons. In this case, the final cleanup might fail but the new - # file should still install successfully. - { - test ! -f "$dst" || - $doit $rmcmd -f "$dst" 2>/dev/null || - { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && - { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } - } || - { echo "$0: cannot unlink or rename $dst" >&2 - (exit 1); exit 1 - } - } && - - # Now rename the file to the real destination. - $doit $mvcmd "$dsttmp" "$dst" - } - fi || exit 1 - - trap '' 0 - fi -done - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" -# time-stamp-time-zone: "UTC" -# time-stamp-end: "; # UTC" -# End: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/internal.h b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/internal.h deleted file mode 100644 index bff8ed4..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/internal.h +++ /dev/null @@ -1,304 +0,0 @@ -/* internal.h -- Internal header file for stack backtrace library. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#ifndef BACKTRACE_INTERNAL_H -#define BACKTRACE_INTERNAL_H - -/* We assume that and "backtrace.h" have already been - included. */ - -#ifndef GCC_VERSION -# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) -#endif - -#if (GCC_VERSION < 2007) -# define __attribute__(x) -#endif - -#ifndef ATTRIBUTE_UNUSED -# define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) -#endif - -#ifndef ATTRIBUTE_MALLOC -# if (GCC_VERSION >= 2096) -# define ATTRIBUTE_MALLOC __attribute__ ((__malloc__)) -# else -# define ATTRIBUTE_MALLOC -# endif -#endif - -#ifndef HAVE_SYNC_FUNCTIONS - -/* Define out the sync functions. These should never be called if - they are not available. */ - -#define __sync_bool_compare_and_swap(A, B, C) (abort(), 1) -#define __sync_lock_test_and_set(A, B) (abort(), 0) -#define __sync_lock_release(A) abort() - -#endif /* !defined (HAVE_SYNC_FUNCTIONS) */ - -#ifdef HAVE_ATOMIC_FUNCTIONS - -/* We have the atomic builtin functions. */ - -#define backtrace_atomic_load_pointer(p) \ - __atomic_load_n ((p), __ATOMIC_ACQUIRE) -#define backtrace_atomic_load_int(p) \ - __atomic_load_n ((p), __ATOMIC_ACQUIRE) -#define backtrace_atomic_store_pointer(p, v) \ - __atomic_store_n ((p), (v), __ATOMIC_RELEASE) -#define backtrace_atomic_store_size_t(p, v) \ - __atomic_store_n ((p), (v), __ATOMIC_RELEASE) -#define backtrace_atomic_store_int(p, v) \ - __atomic_store_n ((p), (v), __ATOMIC_RELEASE) - -#else /* !defined (HAVE_ATOMIC_FUNCTIONS) */ -#ifdef HAVE_SYNC_FUNCTIONS - -/* We have the sync functions but not the atomic functions. Define - the atomic ones in terms of the sync ones. */ - -extern void *backtrace_atomic_load_pointer (void *); -extern int backtrace_atomic_load_int (int *); -extern void backtrace_atomic_store_pointer (void *, void *); -extern void backtrace_atomic_store_size_t (size_t *, size_t); -extern void backtrace_atomic_store_int (int *, int); - -#else /* !defined (HAVE_SYNC_FUNCTIONS) */ - -/* We have neither the sync nor the atomic functions. These will - never be called. */ - -#define backtrace_atomic_load_pointer(p) (abort(), (void *) NULL) -#define backtrace_atomic_load_int(p) (abort(), 0) -#define backtrace_atomic_store_pointer(p, v) abort() -#define backtrace_atomic_store_size_t(p, v) abort() -#define backtrace_atomic_store_int(p, v) abort() - -#endif /* !defined (HAVE_SYNC_FUNCTIONS) */ -#endif /* !defined (HAVE_ATOMIC_FUNCTIONS) */ - -/* The type of the function that collects file/line information. This - is like backtrace_pcinfo. */ - -typedef int (*fileline) (struct backtrace_state *state, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data); - -/* The type of the function that collects symbol information. This is - like backtrace_syminfo. */ - -typedef void (*syminfo) (struct backtrace_state *state, uintptr_t pc, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback, void *data); - -/* What the backtrace state pointer points to. */ - -struct backtrace_state -{ - /* The name of the executable. */ - const char *filename; - /* Non-zero if threaded. */ - int threaded; - /* The master lock for fileline_fn, fileline_data, syminfo_fn, - syminfo_data, fileline_initialization_failed and everything the - data pointers point to. */ - void *lock; - /* The function that returns file/line information. */ - fileline fileline_fn; - /* The data to pass to FILELINE_FN. */ - void *fileline_data; - /* The function that returns symbol information. */ - syminfo syminfo_fn; - /* The data to pass to SYMINFO_FN. */ - void *syminfo_data; - /* Whether initializing the file/line information failed. */ - int fileline_initialization_failed; - /* The lock for the freelist. */ - int lock_alloc; - /* The freelist when using mmap. */ - struct backtrace_freelist_struct *freelist; -}; - -/* Open a file for reading. Returns -1 on error. If DOES_NOT_EXIST - is not NULL, *DOES_NOT_EXIST will be set to 0 normally and set to 1 - if the file does not exist. If the file does not exist and - DOES_NOT_EXIST is not NULL, the function will return -1 and will - not call ERROR_CALLBACK. On other errors, or if DOES_NOT_EXIST is - NULL, the function will call ERROR_CALLBACK before returning. */ -extern int backtrace_open (const char *filename, - backtrace_error_callback error_callback, - void *data, - int *does_not_exist); - -/* A view of the contents of a file. This supports mmap when - available. A view will remain in memory even after backtrace_close - is called on the file descriptor from which the view was - obtained. */ - -struct backtrace_view -{ - /* The data that the caller requested. */ - const void *data; - /* The base of the view. */ - void *base; - /* The total length of the view. */ - size_t len; -}; - -/* Create a view of SIZE bytes from DESCRIPTOR at OFFSET. Store the - result in *VIEW. Returns 1 on success, 0 on error. */ -extern int backtrace_get_view (struct backtrace_state *state, int descriptor, - off_t offset, size_t size, - backtrace_error_callback error_callback, - void *data, struct backtrace_view *view); - -/* Release a view created by backtrace_get_view. */ -extern void backtrace_release_view (struct backtrace_state *state, - struct backtrace_view *view, - backtrace_error_callback error_callback, - void *data); - -/* Close a file opened by backtrace_open. Returns 1 on success, 0 on - error. */ - -extern int backtrace_close (int descriptor, - backtrace_error_callback error_callback, - void *data); - -/* Sort without using memory. */ - -extern void backtrace_qsort (void *base, size_t count, size_t size, - int (*compar) (const void *, const void *)); - -/* Allocate memory. This is like malloc. If ERROR_CALLBACK is NULL, - this does not report an error, it just returns NULL. */ - -extern void *backtrace_alloc (struct backtrace_state *state, size_t size, - backtrace_error_callback error_callback, - void *data) ATTRIBUTE_MALLOC; - -/* Free memory allocated by backtrace_alloc. If ERROR_CALLBACK is - NULL, this does not report an error. */ - -extern void backtrace_free (struct backtrace_state *state, void *mem, - size_t size, - backtrace_error_callback error_callback, - void *data); - -/* A growable vector of some struct. This is used for more efficient - allocation when we don't know the final size of some group of data - that we want to represent as an array. */ - -struct backtrace_vector -{ - /* The base of the vector. */ - void *base; - /* The number of bytes in the vector. */ - size_t size; - /* The number of bytes available at the current allocation. */ - size_t alc; -}; - -/* Grow VEC by SIZE bytes. Return a pointer to the newly allocated - bytes. Note that this may move the entire vector to a new memory - location. Returns NULL on failure. */ - -extern void *backtrace_vector_grow (struct backtrace_state *state, size_t size, - backtrace_error_callback error_callback, - void *data, - struct backtrace_vector *vec); - -/* Finish the current allocation on VEC. Prepare to start a new - allocation. The finished allocation will never be freed. Returns - a pointer to the base of the finished entries, or NULL on - failure. */ - -extern void* backtrace_vector_finish (struct backtrace_state *state, - struct backtrace_vector *vec, - backtrace_error_callback error_callback, - void *data); - -/* Release any extra space allocated for VEC. This may change - VEC->base. Returns 1 on success, 0 on failure. */ - -extern int backtrace_vector_release (struct backtrace_state *state, - struct backtrace_vector *vec, - backtrace_error_callback error_callback, - void *data); - -/* Read initial debug data from a descriptor, and set the - fileline_data, syminfo_fn, and syminfo_data fields of STATE. - Return the fileln_fn field in *FILELN_FN--this is done this way so - that the synchronization code is only implemented once. This is - called after the descriptor has first been opened. It will close - the descriptor if it is no longer needed. Returns 1 on success, 0 - on error. There will be multiple implementations of this function, - for different file formats. Each system will compile the - appropriate one. */ - -extern int backtrace_initialize (struct backtrace_state *state, - const char *filename, - int descriptor, - backtrace_error_callback error_callback, - void *data, - fileline *fileline_fn); - -/* Add file/line information for a DWARF module. */ - -extern int backtrace_dwarf_add (struct backtrace_state *state, - uintptr_t base_address, - const unsigned char* dwarf_info, - size_t dwarf_info_size, - const unsigned char *dwarf_line, - size_t dwarf_line_size, - const unsigned char *dwarf_abbrev, - size_t dwarf_abbrev_size, - const unsigned char *dwarf_ranges, - size_t dwarf_range_size, - const unsigned char *dwarf_str, - size_t dwarf_str_size, - int is_bigendian, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn); - -/* A test-only hook for elf_uncompress_zdebug. */ - -extern int backtrace_uncompress_zdebug (struct backtrace_state *, - const unsigned char *compressed, - size_t compressed_size, - backtrace_error_callback, void *data, - unsigned char **uncompressed, - size_t *uncompressed_size); - -#endif diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ltmain.sh b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ltmain.sh deleted file mode 100755 index 93793bf..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ltmain.sh +++ /dev/null @@ -1,7874 +0,0 @@ -# Generated from ltmain.m4sh. - -# ltmain.sh (GNU libtool) 2.2.4 -# Written by Gordon Matzigkeit , 1996 - -# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc. -# This is free software; see the source for copying conditions. There is NO -# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -# GNU Libtool is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# As a special exception to the GNU General Public License, -# if you distribute this file as part of a program or library that -# is built using GNU Libtool, you may include this file under the -# same distribution terms that you use for the rest of that program. -# -# GNU Libtool is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with GNU Libtool; see the file COPYING. If not, a copy -# can be downloaded from http://www.gnu.org/licenses/gpl.html, -# or obtained by writing to the Free Software Foundation, Inc., -# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -# Usage: $progname [OPTION]... [MODE-ARG]... -# -# Provide generalized library-building support services. -# -# --config show all configuration variables -# --debug enable verbose shell tracing -# -n, --dry-run display commands without modifying any files -# --features display basic configuration information and exit -# --mode=MODE use operation mode MODE -# --preserve-dup-deps don't remove duplicate dependency libraries -# --quiet, --silent don't print informational messages -# --tag=TAG use configuration variables from tag TAG -# -v, --verbose print informational messages (default) -# --version print version information -# -h, --help print short or long help message -# -# MODE must be one of the following: -# -# clean remove files from the build directory -# compile compile a source file into a libtool object -# execute automatically set library path, then run a program -# finish complete the installation of libtool libraries -# install install libraries or executables -# link create a library or an executable -# uninstall remove libraries from an installed directory -# -# MODE-ARGS vary depending on the MODE. -# Try `$progname --help --mode=MODE' for a more detailed description of MODE. -# -# When reporting a bug, please describe a test case to reproduce it and -# include the following information: -# -# host-triplet: $host -# shell: $SHELL -# compiler: $LTCC -# compiler flags: $LTCFLAGS -# linker: $LD (gnu? $with_gnu_ld) -# $progname: (GNU libtool) 2.2.4 -# automake: $automake_version -# autoconf: $autoconf_version -# -# Report bugs to . - -PROGRAM=ltmain.sh -PACKAGE=libtool -VERSION=2.2.4 -TIMESTAMP="" -package_revision=1.2976 - -# Be Bourne compatible -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac -fi -BIN_SH=xpg4; export BIN_SH # for Tru64 -DUALCASE=1; export DUALCASE # for MKS sh - -# NLS nuisances: We save the old values to restore during execute mode. -# Only set LANG and LC_ALL to C if already set. -# These must not be set unconditionally because not all systems understand -# e.g. LANG=C (notably SCO). -lt_user_locale= -lt_safe_locale= -for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES -do - eval "if test \"\${$lt_var+set}\" = set; then - save_$lt_var=\$$lt_var - $lt_var=C - export $lt_var - lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" - lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" - fi" -done - -$lt_unset CDPATH - - - - - -: ${CP="cp -f"} -: ${ECHO="echo"} -: ${EGREP="/usr/bin/grep -E"} -: ${FGREP="/usr/bin/grep -F"} -: ${GREP="/usr/bin/grep"} -: ${LN_S="ln -s"} -: ${MAKE="make"} -: ${MKDIR="mkdir"} -: ${MV="mv -f"} -: ${RM="rm -f"} -: ${SED="/opt/local/bin/gsed"} -: ${SHELL="${CONFIG_SHELL-/bin/sh}"} -: ${Xsed="$SED -e 1s/^X//"} - -# Global variables: -EXIT_SUCCESS=0 -EXIT_FAILURE=1 -EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. -EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. - -exit_status=$EXIT_SUCCESS - -# Make sure IFS has a sensible default -lt_nl=' -' -IFS=" $lt_nl" - -dirname="s,/[^/]*$,," -basename="s,^.*/,," - -# func_dirname_and_basename file append nondir_replacement -# perform func_basename and func_dirname in a single function -# call: -# dirname: Compute the dirname of FILE. If nonempty, -# add APPEND to the result, otherwise set result -# to NONDIR_REPLACEMENT. -# value returned in "$func_dirname_result" -# basename: Compute filename of FILE. -# value retuned in "$func_basename_result" -# Implementation must be kept synchronized with func_dirname -# and func_basename. For efficiency, we do not delegate to -# those functions but instead duplicate the functionality here. -func_dirname_and_basename () -{ - # Extract subdirectory from the argument. - func_dirname_result=`$ECHO "X${1}" | $Xsed -e "$dirname"` - if test "X$func_dirname_result" = "X${1}"; then - func_dirname_result="${3}" - else - func_dirname_result="$func_dirname_result${2}" - fi - func_basename_result=`$ECHO "X${1}" | $Xsed -e "$basename"` -} - -# Generated shell functions inserted here. - -# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh -# is ksh but when the shell is invoked as "sh" and the current value of -# the _XPG environment variable is not equal to 1 (one), the special -# positional parameter $0, within a function call, is the name of the -# function. -progpath="$0" - -# The name of this program: -# In the unlikely event $progname began with a '-', it would play havoc with -# func_echo (imagine progname=-n), so we prepend ./ in that case: -func_dirname_and_basename "$progpath" -progname=$func_basename_result -case $progname in - -*) progname=./$progname ;; -esac - -# Make sure we have an absolute path for reexecution: -case $progpath in - [\\/]*|[A-Za-z]:\\*) ;; - *[\\/]*) - progdir=$func_dirname_result - progdir=`cd "$progdir" && pwd` - progpath="$progdir/$progname" - ;; - *) - save_IFS="$IFS" - IFS=: - for progdir in $PATH; do - IFS="$save_IFS" - test -x "$progdir/$progname" && break - done - IFS="$save_IFS" - test -n "$progdir" || progdir=`pwd` - progpath="$progdir/$progname" - ;; -esac - -# Sed substitution that helps us do robust quoting. It backslashifies -# metacharacters that are still active within double-quoted strings. -Xsed="${SED}"' -e 1s/^X//' -sed_quote_subst='s/\([`"$\\]\)/\\\1/g' - -# Same as above, but do not quote variable references. -double_quote_subst='s/\(["`\\]\)/\\\1/g' - -# Re-`\' parameter expansions in output of double_quote_subst that were -# `\'-ed in input to the same. If an odd number of `\' preceded a '$' -# in input to double_quote_subst, that '$' was protected from expansion. -# Since each input `\' is now two `\'s, look for any number of runs of -# four `\'s followed by two `\'s and then a '$'. `\' that '$'. -bs='\\' -bs2='\\\\' -bs4='\\\\\\\\' -dollar='\$' -sed_double_backslash="\ - s/$bs4/&\\ -/g - s/^$bs2$dollar/$bs&/ - s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g - s/\n//g" - -# Standard options: -opt_dry_run=false -opt_help=false -opt_quiet=false -opt_verbose=false -opt_warning=: - -# func_echo arg... -# Echo program name prefixed message, along with the current mode -# name if it has been set yet. -func_echo () -{ - $ECHO "$progname${mode+: }$mode: $*" -} - -# func_verbose arg... -# Echo program name prefixed message in verbose mode only. -func_verbose () -{ - $opt_verbose && func_echo ${1+"$@"} - - # A bug in bash halts the script if the last line of a function - # fails when set -e is in force, so we need another command to - # work around that: - : -} - -# func_error arg... -# Echo program name prefixed message to standard error. -func_error () -{ - $ECHO "$progname${mode+: }$mode: "${1+"$@"} 1>&2 -} - -# func_warning arg... -# Echo program name prefixed warning message to standard error. -func_warning () -{ - $opt_warning && $ECHO "$progname${mode+: }$mode: warning: "${1+"$@"} 1>&2 - - # bash bug again: - : -} - -# func_fatal_error arg... -# Echo program name prefixed message to standard error, and exit. -func_fatal_error () -{ - func_error ${1+"$@"} - exit $EXIT_FAILURE -} - -# func_fatal_help arg... -# Echo program name prefixed message to standard error, followed by -# a help hint, and exit. -func_fatal_help () -{ - func_error ${1+"$@"} - func_fatal_error "$help" -} -help="Try \`$progname --help' for more information." ## default - - -# func_grep expression filename -# Check whether EXPRESSION matches any line of FILENAME, without output. -func_grep () -{ - $GREP "$1" "$2" >/dev/null 2>&1 -} - - -# func_mkdir_p directory-path -# Make sure the entire path to DIRECTORY-PATH is available. -func_mkdir_p () -{ - my_directory_path="$1" - my_dir_list= - - if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then - - # Protect directory names starting with `-' - case $my_directory_path in - -*) my_directory_path="./$my_directory_path" ;; - esac - - # While some portion of DIR does not yet exist... - while test ! -d "$my_directory_path"; do - # ...make a list in topmost first order. Use a colon delimited - # list incase some portion of path contains whitespace. - my_dir_list="$my_directory_path:$my_dir_list" - - # If the last portion added has no slash in it, the list is done - case $my_directory_path in */*) ;; *) break ;; esac - - # ...otherwise throw away the child directory and loop - my_directory_path=`$ECHO "X$my_directory_path" | $Xsed -e "$dirname"` - done - my_dir_list=`$ECHO "X$my_dir_list" | $Xsed -e 's,:*$,,'` - - save_mkdir_p_IFS="$IFS"; IFS=':' - for my_dir in $my_dir_list; do - IFS="$save_mkdir_p_IFS" - # mkdir can fail with a `File exist' error if two processes - # try to create one of the directories concurrently. Don't - # stop in that case! - $MKDIR "$my_dir" 2>/dev/null || : - done - IFS="$save_mkdir_p_IFS" - - # Bail out if we (or some other process) failed to create a directory. - test -d "$my_directory_path" || \ - func_fatal_error "Failed to create \`$1'" - fi -} - - -# func_mktempdir [string] -# Make a temporary directory that won't clash with other running -# libtool processes, and avoids race conditions if possible. If -# given, STRING is the basename for that directory. -func_mktempdir () -{ - my_template="${TMPDIR-/tmp}/${1-$progname}" - - if test "$opt_dry_run" = ":"; then - # Return a directory name, but don't create it in dry-run mode - my_tmpdir="${my_template}-$$" - else - - # If mktemp works, use that first and foremost - my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` - - if test ! -d "$my_tmpdir"; then - # Failing that, at least try and use $RANDOM to avoid a race - my_tmpdir="${my_template}-${RANDOM-0}$$" - - save_mktempdir_umask=`umask` - umask 0077 - $MKDIR "$my_tmpdir" - umask $save_mktempdir_umask - fi - - # If we're not in dry-run mode, bomb out on failure - test -d "$my_tmpdir" || \ - func_fatal_error "cannot create temporary directory \`$my_tmpdir'" - fi - - $ECHO "X$my_tmpdir" | $Xsed -} - - -# func_quote_for_eval arg -# Aesthetically quote ARG to be evaled later. -# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT -# is double-quoted, suitable for a subsequent eval, whereas -# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters -# which are still active within double quotes backslashified. -func_quote_for_eval () -{ - case $1 in - *[\\\`\"\$]*) - func_quote_for_eval_unquoted_result=`$ECHO "X$1" | $Xsed -e "$sed_quote_subst"` ;; - *) - func_quote_for_eval_unquoted_result="$1" ;; - esac - - case $func_quote_for_eval_unquoted_result in - # Double-quote args containing shell metacharacters to delay - # word splitting, command substitution and and variable - # expansion for a subsequent eval. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, so we specify it separately. - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" - ;; - *) - func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" - esac -} - - -# func_quote_for_expand arg -# Aesthetically quote ARG to be evaled later; same as above, -# but do not quote variable references. -func_quote_for_expand () -{ - case $1 in - *[\\\`\"]*) - my_arg=`$ECHO "X$1" | $Xsed \ - -e "$double_quote_subst" -e "$sed_double_backslash"` ;; - *) - my_arg="$1" ;; - esac - - case $my_arg in - # Double-quote args containing shell metacharacters to delay - # word splitting and command substitution for a subsequent eval. - # Many Bourne shells cannot handle close brackets correctly - # in scan sets, so we specify it separately. - *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") - my_arg="\"$my_arg\"" - ;; - esac - - func_quote_for_expand_result="$my_arg" -} - - -# func_show_eval cmd [fail_exp] -# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is -# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP -# is given, then evaluate it. -func_show_eval () -{ - my_cmd="$1" - my_fail_exp="${2-:}" - - ${opt_silent-false} || { - func_quote_for_expand "$my_cmd" - eval "func_echo $func_quote_for_expand_result" - } - - if ${opt_dry_run-false}; then :; else - eval "$my_cmd" - my_status=$? - if test "$my_status" -eq 0; then :; else - eval "(exit $my_status); $my_fail_exp" - fi - fi -} - - -# func_show_eval_locale cmd [fail_exp] -# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is -# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP -# is given, then evaluate it. Use the saved locale for evaluation. -func_show_eval_locale () -{ - my_cmd="$1" - my_fail_exp="${2-:}" - - ${opt_silent-false} || { - func_quote_for_expand "$my_cmd" - eval "func_echo $func_quote_for_expand_result" - } - - if ${opt_dry_run-false}; then :; else - eval "$lt_user_locale - $my_cmd" - my_status=$? - eval "$lt_safe_locale" - if test "$my_status" -eq 0; then :; else - eval "(exit $my_status); $my_fail_exp" - fi - fi -} - - - - - -# func_version -# Echo version message to standard output and exit. -func_version () -{ - $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / { - s/^# // - s/^# *$// - s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ - p - }' < "$progpath" - exit $? -} - -# func_usage -# Echo short help message to standard output and exit. -func_usage () -{ - $SED -n '/^# Usage:/,/# -h/ { - s/^# // - s/^# *$// - s/\$progname/'$progname'/ - p - }' < "$progpath" - $ECHO - $ECHO "run \`$progname --help | more' for full usage" - exit $? -} - -# func_help -# Echo long help message to standard output and exit. -func_help () -{ - $SED -n '/^# Usage:/,/# Report bugs to/ { - s/^# // - s/^# *$// - s*\$progname*'$progname'* - s*\$host*'"$host"'* - s*\$SHELL*'"$SHELL"'* - s*\$LTCC*'"$LTCC"'* - s*\$LTCFLAGS*'"$LTCFLAGS"'* - s*\$LD*'"$LD"'* - s/\$with_gnu_ld/'"$with_gnu_ld"'/ - s/\$automake_version/'"`(automake --version) 2>/dev/null |$SED 1q`"'/ - s/\$autoconf_version/'"`(autoconf --version) 2>/dev/null |$SED 1q`"'/ - p - }' < "$progpath" - exit $? -} - -# func_missing_arg argname -# Echo program name prefixed message to standard error and set global -# exit_cmd. -func_missing_arg () -{ - func_error "missing argument for $1" - exit_cmd=exit -} - -exit_cmd=: - - - - - -# Check that we have a working $ECHO. -if test "X$1" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift -elif test "X$1" = X--fallback-echo; then - # Avoid inline document here, it may be left over - : -elif test "X`{ $ECHO '\t'; } 2>/dev/null`" = 'X\t'; then - # Yippee, $ECHO works! - : -else - # Restart under the correct shell, and then maybe $ECHO will work. - exec $SHELL "$progpath" --no-reexec ${1+"$@"} -fi - -if test "X$1" = X--fallback-echo; then - # used as fallback echo - shift - cat </dev/null 2>&1; then - taglist="$taglist $tagname" - - # Evaluate the configuration. Be careful to quote the path - # and the sed script, to avoid splitting on whitespace, but - # also don't use non-portable quotes within backquotes within - # quotes we have to do it in 2 steps: - extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` - eval "$extractedcf" - else - func_error "ignoring unknown tag $tagname" - fi - ;; - esac -} - -# Parse options once, thoroughly. This comes as soon as possible in -# the script to make things like `libtool --version' happen quickly. -{ - - # Shorthand for --mode=foo, only valid as the first argument - case $1 in - clean|clea|cle|cl) - shift; set dummy --mode clean ${1+"$@"}; shift - ;; - compile|compil|compi|comp|com|co|c) - shift; set dummy --mode compile ${1+"$@"}; shift - ;; - execute|execut|execu|exec|exe|ex|e) - shift; set dummy --mode execute ${1+"$@"}; shift - ;; - finish|finis|fini|fin|fi|f) - shift; set dummy --mode finish ${1+"$@"}; shift - ;; - install|instal|insta|inst|ins|in|i) - shift; set dummy --mode install ${1+"$@"}; shift - ;; - link|lin|li|l) - shift; set dummy --mode link ${1+"$@"}; shift - ;; - uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) - shift; set dummy --mode uninstall ${1+"$@"}; shift - ;; - esac - - # Parse non-mode specific arguments: - while test "$#" -gt 0; do - opt="$1" - shift - - case $opt in - --config) func_config ;; - - --debug) preserve_args="$preserve_args $opt" - func_echo "enabling shell trace mode" - opt_debug='set -x' - $opt_debug - ;; - - -dlopen) test "$#" -eq 0 && func_missing_arg "$opt" && break - execute_dlfiles="$execute_dlfiles $1" - shift - ;; - - --dry-run | -n) opt_dry_run=: ;; - --features) func_features ;; - --finish) mode="finish" ;; - - --mode) test "$#" -eq 0 && func_missing_arg "$opt" && break - case $1 in - # Valid mode arguments: - clean) ;; - compile) ;; - execute) ;; - finish) ;; - install) ;; - link) ;; - relink) ;; - uninstall) ;; - - # Catch anything else as an error - *) func_error "invalid argument for $opt" - exit_cmd=exit - break - ;; - esac - - mode="$1" - shift - ;; - - --preserve-dup-deps) - opt_duplicate_deps=: ;; - - --quiet|--silent) preserve_args="$preserve_args $opt" - opt_silent=: - ;; - - --verbose| -v) preserve_args="$preserve_args $opt" - opt_silent=false - ;; - - --tag) test "$#" -eq 0 && func_missing_arg "$opt" && break - preserve_args="$preserve_args $opt $1" - func_enable_tag "$1" # tagname is set here - shift - ;; - - # Separate optargs to long options: - -dlopen=*|--mode=*|--tag=*) - func_opt_split "$opt" - set dummy "$func_opt_split_opt" "$func_opt_split_arg" ${1+"$@"} - shift - ;; - - -\?|-h) func_usage ;; - --help) opt_help=: ;; - --version) func_version ;; - - -*) func_fatal_help "unrecognized option \`$opt'" ;; - - *) nonopt="$opt" - break - ;; - esac - done - - - case $host in - *cygwin* | *mingw* | *pw32*) - # don't eliminate duplications in $postdeps and $predeps - opt_duplicate_compiler_generated_deps=: - ;; - *) - opt_duplicate_compiler_generated_deps=$opt_duplicate_deps - ;; - esac - - # Having warned about all mis-specified options, bail out if - # anything was wrong. - $exit_cmd $EXIT_FAILURE -} - -# func_check_version_match -# Ensure that we are using m4 macros, and libtool script from the same -# release of libtool. -func_check_version_match () -{ - if test "$package_revision" != "$macro_revision"; then - if test "$VERSION" != "$macro_version"; then - if test -z "$macro_version"; then - cat >&2 <<_LT_EOF -$progname: Version mismatch error. This is $PACKAGE $VERSION, but the -$progname: definition of this LT_INIT comes from an older release. -$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION -$progname: and run autoconf again. -_LT_EOF - else - cat >&2 <<_LT_EOF -$progname: Version mismatch error. This is $PACKAGE $VERSION, but the -$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. -$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION -$progname: and run autoconf again. -_LT_EOF - fi - else - cat >&2 <<_LT_EOF -$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, -$progname: but the definition of this LT_INIT comes from revision $macro_revision. -$progname: You should recreate aclocal.m4 with macros from revision $package_revision -$progname: of $PACKAGE $VERSION and run autoconf again. -_LT_EOF - fi - - exit $EXIT_MISMATCH - fi -} - - -## ----------- ## -## Main. ## -## ----------- ## - -$opt_help || { - # Sanity checks first: - func_check_version_match - - if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then - func_fatal_configuration "not configured to build any kind of library" - fi - - test -z "$mode" && func_fatal_error "error: you must specify a MODE." - - - # Darwin sucks - eval std_shrext=\"$shrext_cmds\" - - - # Only execute mode is allowed to have -dlopen flags. - if test -n "$execute_dlfiles" && test "$mode" != execute; then - func_error "unrecognized option \`-dlopen'" - $ECHO "$help" 1>&2 - exit $EXIT_FAILURE - fi - - # Change the help message to a mode-specific one. - generic_help="$help" - help="Try \`$progname --help --mode=$mode' for more information." -} - - -# func_lalib_p file -# True iff FILE is a libtool `.la' library or `.lo' object file. -# This function is only a basic sanity check; it will hardly flush out -# determined imposters. -func_lalib_p () -{ - $SED -e 4q "$1" 2>/dev/null \ - | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 -} - -# func_lalib_unsafe_p file -# True iff FILE is a libtool `.la' library or `.lo' object file. -# This function implements the same check as func_lalib_p without -# resorting to external programs. To this end, it redirects stdin and -# closes it afterwards, without saving the original file descriptor. -# As a safety measure, use it only where a negative result would be -# fatal anyway. Works if `file' does not exist. -func_lalib_unsafe_p () -{ - lalib_p=no - if test -r "$1" && exec 5<&0 <"$1"; then - for lalib_p_l in 1 2 3 4 - do - read lalib_p_line - case "$lalib_p_line" in - \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; - esac - done - exec 0<&5 5<&- - fi - test "$lalib_p" = yes -} - -# func_ltwrapper_script_p file -# True iff FILE is a libtool wrapper script -# This function is only a basic sanity check; it will hardly flush out -# determined imposters. -func_ltwrapper_script_p () -{ - func_lalib_p "$1" -} - -# func_ltwrapper_executable_p file -# True iff FILE is a libtool wrapper executable -# This function is only a basic sanity check; it will hardly flush out -# determined imposters. -func_ltwrapper_executable_p () -{ - func_ltwrapper_exec_suffix= - case $1 in - *.exe) ;; - *) func_ltwrapper_exec_suffix=.exe ;; - esac - $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 -} - -# func_ltwrapper_scriptname file -# Assumes file is an ltwrapper_executable -# uses $file to determine the appropriate filename for a -# temporary ltwrapper_script. -func_ltwrapper_scriptname () -{ - func_ltwrapper_scriptname_result="" - if func_ltwrapper_executable_p "$1"; then - func_dirname_and_basename "$1" "" "." - func_stripname '' '.exe' "$func_basename_result" - func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" - fi -} - -# func_ltwrapper_p file -# True iff FILE is a libtool wrapper script or wrapper executable -# This function is only a basic sanity check; it will hardly flush out -# determined imposters. -func_ltwrapper_p () -{ - func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" -} - - -# func_execute_cmds commands fail_cmd -# Execute tilde-delimited COMMANDS. -# If FAIL_CMD is given, eval that upon failure. -# FAIL_CMD may read-access the current command in variable CMD! -func_execute_cmds () -{ - $opt_debug - save_ifs=$IFS; IFS='~' - for cmd in $1; do - IFS=$save_ifs - eval cmd=\"$cmd\" - func_show_eval "$cmd" "${2-:}" - done - IFS=$save_ifs -} - - -# func_source file -# Source FILE, adding directory component if necessary. -# Note that it is not necessary on cygwin/mingw to append a dot to -# FILE even if both FILE and FILE.exe exist: automatic-append-.exe -# behavior happens only for exec(3), not for open(2)! Also, sourcing -# `FILE.' does not work on cygwin managed mounts. -func_source () -{ - $opt_debug - case $1 in - */* | *\\*) . "$1" ;; - *) . "./$1" ;; - esac -} - - -# func_infer_tag arg -# Infer tagged configuration to use if any are available and -# if one wasn't chosen via the "--tag" command line option. -# Only attempt this if the compiler in the base compile -# command doesn't match the default compiler. -# arg is usually of the form 'gcc ...' -func_infer_tag () -{ - $opt_debug - if test -n "$available_tags" && test -z "$tagname"; then - CC_quoted= - for arg in $CC; do - func_quote_for_eval "$arg" - CC_quoted="$CC_quoted $func_quote_for_eval_result" - done - case $@ in - # Blanks in the command may have been stripped by the calling shell, - # but not from the CC environment variable when configure was run. - " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) ;; - # Blanks at the start of $base_compile will cause this to fail - # if we don't check for them as well. - *) - for z in $available_tags; do - if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then - # Evaluate the configuration. - eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" - CC_quoted= - for arg in $CC; do - # Double-quote args containing other shell metacharacters. - func_quote_for_eval "$arg" - CC_quoted="$CC_quoted $func_quote_for_eval_result" - done - case "$@ " in - " $CC "* | "$CC "* | " `$ECHO $CC` "* | "`$ECHO $CC` "* | " $CC_quoted"* | "$CC_quoted "* | " `$ECHO $CC_quoted` "* | "`$ECHO $CC_quoted` "*) - # The compiler in the base compile command matches - # the one in the tagged configuration. - # Assume this is the tagged configuration we want. - tagname=$z - break - ;; - esac - fi - done - # If $tagname still isn't set, then no tagged configuration - # was found and let the user know that the "--tag" command - # line option must be used. - if test -z "$tagname"; then - func_echo "unable to infer tagged configuration" - func_fatal_error "specify a tag with \`--tag'" -# else -# func_verbose "using $tagname tagged configuration" - fi - ;; - esac - fi -} - - - -# func_write_libtool_object output_name pic_name nonpic_name -# Create a libtool object file (analogous to a ".la" file), -# but don't create it if we're doing a dry run. -func_write_libtool_object () -{ - write_libobj=${1} - if test "$build_libtool_libs" = yes; then - write_lobj=\'${2}\' - else - write_lobj=none - fi - - if test "$build_old_libs" = yes; then - write_oldobj=\'${3}\' - else - write_oldobj=none - fi - - $opt_dry_run || { - cat >${write_libobj}T <?"'"'"' &()|`$[]' \ - && func_warning "libobj name \`$libobj' may not contain shell special characters." - func_dirname_and_basename "$obj" "/" "" - objname="$func_basename_result" - xdir="$func_dirname_result" - lobj=${xdir}$objdir/$objname - - test -z "$base_compile" && \ - func_fatal_help "you must specify a compilation command" - - # Delete any leftover library objects. - if test "$build_old_libs" = yes; then - removelist="$obj $lobj $libobj ${libobj}T" - else - removelist="$lobj $libobj ${libobj}T" - fi - - # On Cygwin there's no "real" PIC flag so we must build both object types - case $host_os in - cygwin* | mingw* | pw32* | os2*) - pic_mode=default - ;; - esac - if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then - # non-PIC code in shared libraries is not supported - pic_mode=default - fi - - # Calculate the filename of the output object if compiler does - # not support -o with -c - if test "$compiler_c_o" = no; then - output_obj=`$ECHO "X$srcfile" | $Xsed -e 's%^.*/%%' -e 's%\.[^.]*$%%'`.${objext} - lockfile="$output_obj.lock" - else - output_obj= - need_locks=no - lockfile= - fi - - # Lock this critical section if it is needed - # We use this script file to make the link, it avoids creating a new file - if test "$need_locks" = yes; then - until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do - func_echo "Waiting for $lockfile to be removed" - sleep 2 - done - elif test "$need_locks" = warn; then - if test -f "$lockfile"; then - $ECHO "\ -*** ERROR, $lockfile exists and contains: -`cat $lockfile 2>/dev/null` - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $opt_dry_run || $RM $removelist - exit $EXIT_FAILURE - fi - removelist="$removelist $output_obj" - $ECHO "$srcfile" > "$lockfile" - fi - - $opt_dry_run || $RM $removelist - removelist="$removelist $lockfile" - trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 - - if test -n "$fix_srcfile_path"; then - eval srcfile=\"$fix_srcfile_path\" - fi - func_quote_for_eval "$srcfile" - qsrcfile=$func_quote_for_eval_result - - # Only build a PIC object if we are building libtool libraries. - if test "$build_libtool_libs" = yes; then - # Without this assignment, base_compile gets emptied. - fbsd_hideous_sh_bug=$base_compile - - if test "$pic_mode" != no; then - command="$base_compile $qsrcfile $pic_flag" - else - # Don't build PIC code - command="$base_compile $qsrcfile" - fi - - func_mkdir_p "$xdir$objdir" - - if test -z "$output_obj"; then - # Place PIC objects in $objdir - command="$command -o $lobj" - fi - - func_show_eval_locale "$command" \ - 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' - - if test "$need_locks" = warn && - test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then - $ECHO "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $opt_dry_run || $RM $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed, then go on to compile the next one - if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then - func_show_eval '$MV "$output_obj" "$lobj"' \ - 'error=$?; $opt_dry_run || $RM $removelist; exit $error' - fi - - # Allow error messages only from the first compilation. - if test "$suppress_opt" = yes; then - suppress_output=' >/dev/null 2>&1' - fi - fi - - # Only build a position-dependent object if we build old libraries. - if test "$build_old_libs" = yes; then - if test "$pic_mode" != yes; then - # Don't build PIC code - command="$base_compile $qsrcfile$pie_flag" - else - command="$base_compile $qsrcfile $pic_flag" - fi - if test "$compiler_c_o" = yes; then - command="$command -o $obj" - fi - - # Suppress compiler output if we already did a PIC compilation. - command="$command$suppress_output" - func_show_eval_locale "$command" \ - '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' - - if test "$need_locks" = warn && - test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then - $ECHO "\ -*** ERROR, $lockfile contains: -`cat $lockfile 2>/dev/null` - -but it should contain: -$srcfile - -This indicates that another process is trying to use the same -temporary object file, and libtool could not work around it because -your compiler does not support \`-c' and \`-o' together. If you -repeat this compilation, it may succeed, by chance, but you had better -avoid parallel builds (make -j) in this platform, or get a better -compiler." - - $opt_dry_run || $RM $removelist - exit $EXIT_FAILURE - fi - - # Just move the object if needed - if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then - func_show_eval '$MV "$output_obj" "$obj"' \ - 'error=$?; $opt_dry_run || $RM $removelist; exit $error' - fi - fi - - $opt_dry_run || { - func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" - - # Unlock the critical section if it was locked - if test "$need_locks" != no; then - removelist=$lockfile - $RM "$lockfile" - fi - } - - exit $EXIT_SUCCESS -} - -$opt_help || { -test "$mode" = compile && func_mode_compile ${1+"$@"} -} - -func_mode_help () -{ - # We need to display help for each of the modes. - case $mode in - "") - # Generic help is extracted from the usage comments - # at the start of this file. - func_help - ;; - - clean) - $ECHO \ -"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... - -Remove files from the build directory. - -RM is the name of the program to use to delete files associated with each FILE -(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed -to RM. - -If FILE is a libtool library, object or program, all the files associated -with it are deleted. Otherwise, only FILE itself is deleted using RM." - ;; - - compile) - $ECHO \ -"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE - -Compile a source file into a libtool library object. - -This mode accepts the following additional options: - - -o OUTPUT-FILE set the output file name to OUTPUT-FILE - -no-suppress do not suppress compiler output for multiple passes - -prefer-pic try to building PIC objects only - -prefer-non-pic try to building non-PIC objects only - -shared do not build a \`.o' file suitable for static linking - -static only build a \`.o' file suitable for static linking - -COMPILE-COMMAND is a command to be used in creating a \`standard' object file -from the given SOURCEFILE. - -The output file name is determined by removing the directory component from -SOURCEFILE, then substituting the C source code suffix \`.c' with the -library object suffix, \`.lo'." - ;; - - execute) - $ECHO \ -"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... - -Automatically set library path, then run a program. - -This mode accepts the following additional options: - - -dlopen FILE add the directory containing FILE to the library path - -This mode sets the library path environment variable according to \`-dlopen' -flags. - -If any of the ARGS are libtool executable wrappers, then they are translated -into their corresponding uninstalled binary, and any of their required library -directories are added to the library path. - -Then, COMMAND is executed, with ARGS as arguments." - ;; - - finish) - $ECHO \ -"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... - -Complete the installation of libtool libraries. - -Each LIBDIR is a directory that contains libtool libraries. - -The commands that this mode executes may require superuser privileges. Use -the \`--dry-run' option if you just want to see what would be executed." - ;; - - install) - $ECHO \ -"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... - -Install executables or libraries. - -INSTALL-COMMAND is the installation command. The first component should be -either the \`install' or \`cp' program. - -The following components of INSTALL-COMMAND are treated specially: - - -inst-prefix PREFIX-DIR Use PREFIX-DIR as a staging area for installation - -The rest of the components are interpreted as arguments to that command (only -BSD-compatible install options are recognized)." - ;; - - link) - $ECHO \ -"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... - -Link object files or libraries together to form another library, or to -create an executable program. - -LINK-COMMAND is a command using the C compiler that you would use to create -a program from several object files. - -The following components of LINK-COMMAND are treated specially: - - -all-static do not do any dynamic linking at all - -avoid-version do not add a version suffix if possible - -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime - -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols - -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) - -export-symbols SYMFILE - try to export only the symbols listed in SYMFILE - -export-symbols-regex REGEX - try to export only the symbols matching REGEX - -LLIBDIR search LIBDIR for required installed libraries - -lNAME OUTPUT-FILE requires the installed library libNAME - -module build a library that can dlopened - -no-fast-install disable the fast-install mode - -no-install link a not-installable executable - -no-undefined declare that a library does not refer to external symbols - -o OUTPUT-FILE create OUTPUT-FILE from the specified objects - -objectlist FILE Use a list of object files found in FILE to specify objects - -precious-files-regex REGEX - don't remove output files matching REGEX - -release RELEASE specify package release information - -rpath LIBDIR the created library will eventually be installed in LIBDIR - -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries - -shared only do dynamic linking of libtool libraries - -shrext SUFFIX override the standard shared library file extension - -static do not do any dynamic linking of uninstalled libtool libraries - -static-libtool-libs - do not do any dynamic linking of libtool libraries - -version-info CURRENT[:REVISION[:AGE]] - specify library version info [each variable defaults to 0] - -weak LIBNAME declare that the target provides the LIBNAME interface - -All other options (arguments beginning with \`-') are ignored. - -Every other argument is treated as a filename. Files ending in \`.la' are -treated as uninstalled libtool libraries, other files are standard or library -object files. - -If the OUTPUT-FILE ends in \`.la', then a libtool library is created, -only library objects (\`.lo' files) may be specified, and \`-rpath' is -required, except when creating a convenience library. - -If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created -using \`ar' and \`ranlib', or on Windows using \`lib'. - -If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file -is created, otherwise an executable program is created." - ;; - - uninstall) - $ECHO \ -"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... - -Remove libraries from an installation directory. - -RM is the name of the program to use to delete files associated with each FILE -(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed -to RM. - -If FILE is a libtool library, all the files associated with it are deleted. -Otherwise, only FILE itself is deleted using RM." - ;; - - *) - func_fatal_help "invalid operation mode \`$mode'" - ;; - esac - - $ECHO - $ECHO "Try \`$progname --help' for more information about other modes." - - exit $? -} - - # Now that we've collected a possible --mode arg, show help if necessary - $opt_help && func_mode_help - - -# func_mode_execute arg... -func_mode_execute () -{ - $opt_debug - # The first argument is the command name. - cmd="$nonopt" - test -z "$cmd" && \ - func_fatal_help "you must specify a COMMAND" - - # Handle -dlopen flags immediately. - for file in $execute_dlfiles; do - test -f "$file" \ - || func_fatal_help "\`$file' is not a file" - - dir= - case $file in - *.la) - # Check to see that this really is a libtool archive. - func_lalib_unsafe_p "$file" \ - || func_fatal_help "\`$lib' is not a valid libtool archive" - - # Read the libtool library. - dlname= - library_names= - func_source "$file" - - # Skip this library if it cannot be dlopened. - if test -z "$dlname"; then - # Warn if it was a shared library. - test -n "$library_names" && \ - func_warning "\`$file' was not linked with \`-export-dynamic'" - continue - fi - - func_dirname "$file" "" "." - dir="$func_dirname_result" - - if test -f "$dir/$objdir/$dlname"; then - dir="$dir/$objdir" - else - if test ! -f "$dir/$dlname"; then - func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" - fi - fi - ;; - - *.lo) - # Just add the directory containing the .lo file. - func_dirname "$file" "" "." - dir="$func_dirname_result" - ;; - - *) - func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" - continue - ;; - esac - - # Get the absolute pathname. - absdir=`cd "$dir" && pwd` - test -n "$absdir" && dir="$absdir" - - # Now add the directory to shlibpath_var. - if eval "test -z \"\$$shlibpath_var\""; then - eval "$shlibpath_var=\"\$dir\"" - else - eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" - fi - done - - # This variable tells wrapper scripts just to set shlibpath_var - # rather than running their programs. - libtool_execute_magic="$magic" - - # Check if any of the arguments is a wrapper script. - args= - for file - do - case $file in - -*) ;; - *) - # Do a test to see if this is really a libtool program. - if func_ltwrapper_script_p "$file"; then - func_source "$file" - # Transform arg to wrapped name. - file="$progdir/$program" - elif func_ltwrapper_executable_p "$file"; then - func_ltwrapper_scriptname "$file" - func_source "$func_ltwrapper_scriptname_result" - # Transform arg to wrapped name. - file="$progdir/$program" - fi - ;; - esac - # Quote arguments (to preserve shell metacharacters). - func_quote_for_eval "$file" - args="$args $func_quote_for_eval_result" - done - - if test "X$opt_dry_run" = Xfalse; then - if test -n "$shlibpath_var"; then - # Export the shlibpath_var. - eval "export $shlibpath_var" - fi - - # Restore saved environment variables - for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES - do - eval "if test \"\${save_$lt_var+set}\" = set; then - $lt_var=\$save_$lt_var; export $lt_var - else - $lt_unset $lt_var - fi" - done - - # Now prepare to actually exec the command. - exec_cmd="\$cmd$args" - else - # Display what would be done. - if test -n "$shlibpath_var"; then - eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" - $ECHO "export $shlibpath_var" - fi - $ECHO "$cmd$args" - exit $EXIT_SUCCESS - fi -} - -test "$mode" = execute && func_mode_execute ${1+"$@"} - - -# func_mode_finish arg... -func_mode_finish () -{ - $opt_debug - libdirs="$nonopt" - admincmds= - - if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then - for dir - do - libdirs="$libdirs $dir" - done - - for libdir in $libdirs; do - if test -n "$finish_cmds"; then - # Do each command in the finish commands. - func_execute_cmds "$finish_cmds" 'admincmds="$admincmds -'"$cmd"'"' - fi - if test -n "$finish_eval"; then - # Do the single finish_eval. - eval cmds=\"$finish_eval\" - $opt_dry_run || eval "$cmds" || admincmds="$admincmds - $cmds" - fi - done - fi - - # Exit here if they wanted silent mode. - $opt_silent && exit $EXIT_SUCCESS - - $ECHO "X----------------------------------------------------------------------" | $Xsed - $ECHO "Libraries have been installed in:" - for libdir in $libdirs; do - $ECHO " $libdir" - done - $ECHO - $ECHO "If you ever happen to want to link against installed libraries" - $ECHO "in a given directory, LIBDIR, you must either use libtool, and" - $ECHO "specify the full pathname of the library, or use the \`-LLIBDIR'" - $ECHO "flag during linking and do at least one of the following:" - if test -n "$shlibpath_var"; then - $ECHO " - add LIBDIR to the \`$shlibpath_var' environment variable" - $ECHO " during execution" - fi - if test -n "$runpath_var"; then - $ECHO " - add LIBDIR to the \`$runpath_var' environment variable" - $ECHO " during linking" - fi - if test -n "$hardcode_libdir_flag_spec"; then - libdir=LIBDIR - eval flag=\"$hardcode_libdir_flag_spec\" - - $ECHO " - use the \`$flag' linker flag" - fi - if test -n "$admincmds"; then - $ECHO " - have your system administrator run these commands:$admincmds" - fi - if test -f /etc/ld.so.conf; then - $ECHO " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" - fi - $ECHO - - $ECHO "See any operating system documentation about shared libraries for" - case $host in - solaris2.[6789]|solaris2.1[0-9]) - $ECHO "more information, such as the ld(1), crle(1) and ld.so(8) manual" - $ECHO "pages." - ;; - *) - $ECHO "more information, such as the ld(1) and ld.so(8) manual pages." - ;; - esac - $ECHO "X----------------------------------------------------------------------" | $Xsed - exit $EXIT_SUCCESS -} - -test "$mode" = finish && func_mode_finish ${1+"$@"} - - -# func_mode_install arg... -func_mode_install () -{ - $opt_debug - # There may be an optional sh(1) argument at the beginning of - # install_prog (especially on Windows NT). - if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || - # Allow the use of GNU shtool's install command. - $ECHO "X$nonopt" | $GREP shtool >/dev/null; then - # Aesthetically quote it. - func_quote_for_eval "$nonopt" - install_prog="$func_quote_for_eval_result " - arg=$1 - shift - else - install_prog= - arg=$nonopt - fi - - # The real first argument should be the name of the installation program. - # Aesthetically quote it. - func_quote_for_eval "$arg" - install_prog="$install_prog$func_quote_for_eval_result" - - # We need to accept at least all the BSD install flags. - dest= - files= - opts= - prev= - install_type= - isdir=no - stripme= - for arg - do - if test -n "$dest"; then - files="$files $dest" - dest=$arg - continue - fi - - case $arg in - -d) isdir=yes ;; - -f) - case " $install_prog " in - *[\\\ /]cp\ *) ;; - *) prev=$arg ;; - esac - ;; - -g | -m | -o) - prev=$arg - ;; - -s) - stripme=" -s" - continue - ;; - -*) - ;; - *) - # If the previous option needed an argument, then skip it. - if test -n "$prev"; then - prev= - else - dest=$arg - continue - fi - ;; - esac - - # Aesthetically quote the argument. - func_quote_for_eval "$arg" - install_prog="$install_prog $func_quote_for_eval_result" - done - - test -z "$install_prog" && \ - func_fatal_help "you must specify an install program" - - test -n "$prev" && \ - func_fatal_help "the \`$prev' option requires an argument" - - if test -z "$files"; then - if test -z "$dest"; then - func_fatal_help "no file or destination specified" - else - func_fatal_help "you must specify a destination" - fi - fi - - # Strip any trailing slash from the destination. - func_stripname '' '/' "$dest" - dest=$func_stripname_result - - # Check to see that the destination is a directory. - test -d "$dest" && isdir=yes - if test "$isdir" = yes; then - destdir="$dest" - destname= - else - func_dirname_and_basename "$dest" "" "." - destdir="$func_dirname_result" - destname="$func_basename_result" - - # Not a directory, so check to see that there is only one file specified. - set dummy $files; shift - test "$#" -gt 1 && \ - func_fatal_help "\`$dest' is not a directory" - fi - case $destdir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - for file in $files; do - case $file in - *.lo) ;; - *) - func_fatal_help "\`$destdir' must be an absolute directory name" - ;; - esac - done - ;; - esac - - # This variable tells wrapper scripts just to set variables rather - # than running their programs. - libtool_install_magic="$magic" - - staticlibs= - future_libdirs= - current_libdirs= - for file in $files; do - - # Do each installation. - case $file in - *.$libext) - # Do the static libraries later. - staticlibs="$staticlibs $file" - ;; - - *.la) - # Check to see that this really is a libtool archive. - func_lalib_unsafe_p "$file" \ - || func_fatal_help "\`$file' is not a valid libtool archive" - - library_names= - old_library= - relink_command= - func_source "$file" - - # Add the libdir to current_libdirs if it is the destination. - if test "X$destdir" = "X$libdir"; then - case "$current_libdirs " in - *" $libdir "*) ;; - *) current_libdirs="$current_libdirs $libdir" ;; - esac - else - # Note the libdir as a future libdir. - case "$future_libdirs " in - *" $libdir "*) ;; - *) future_libdirs="$future_libdirs $libdir" ;; - esac - fi - - func_dirname "$file" "/" "" - dir="$func_dirname_result" - dir="$dir$objdir" - - if test -n "$relink_command"; then - # Determine the prefix the user has applied to our future dir. - inst_prefix_dir=`$ECHO "X$destdir" | $Xsed -e "s%$libdir\$%%"` - - # Don't allow the user to place us outside of our expected - # location b/c this prevents finding dependent libraries that - # are installed to the same prefix. - # At present, this check doesn't affect windows .dll's that - # are installed into $libdir/../bin (currently, that works fine) - # but it's something to keep an eye on. - test "$inst_prefix_dir" = "$destdir" && \ - func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" - - if test -n "$inst_prefix_dir"; then - # Stick the inst_prefix_dir data into the link command. - relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` - else - relink_command=`$ECHO "X$relink_command" | $Xsed -e "s%@inst_prefix_dir@%%"` - fi - - func_warning "relinking \`$file'" - func_show_eval "$relink_command" \ - 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' - fi - - # See the names of the shared library. - set dummy $library_names; shift - if test -n "$1"; then - realname="$1" - shift - - srcname="$realname" - test -n "$relink_command" && srcname="$realname"T - - # Install the shared library and build the symlinks. - func_show_eval "$install_prog $dir/$srcname $destdir/$realname" \ - 'exit $?' - tstripme="$stripme" - case $host_os in - cygwin* | mingw* | pw32*) - case $realname in - *.dll.a) - tstripme="" - ;; - esac - ;; - esac - if test -n "$tstripme" && test -n "$striplib"; then - func_show_eval "$striplib $destdir/$realname" 'exit $?' - fi - - if test "$#" -gt 0; then - # Delete the old symlinks, and create new ones. - # Try `ln -sf' first, because the `ln' binary might depend on - # the symlink we replace! Solaris /bin/ln does not understand -f, - # so we also need to try rm && ln -s. - for linkname - do - test "$linkname" != "$realname" \ - && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" - done - fi - - # Do each command in the postinstall commands. - lib="$destdir/$realname" - func_execute_cmds "$postinstall_cmds" 'exit $?' - fi - - # Install the pseudo-library for information purposes. - func_basename "$file" - name="$func_basename_result" - instname="$dir/$name"i - func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' - - # Maybe install the static library, too. - test -n "$old_library" && staticlibs="$staticlibs $dir/$old_library" - ;; - - *.lo) - # Install (i.e. copy) a libtool object. - - # Figure out destination file name, if it wasn't already specified. - if test -n "$destname"; then - destfile="$destdir/$destname" - else - func_basename "$file" - destfile="$func_basename_result" - destfile="$destdir/$destfile" - fi - - # Deduce the name of the destination old-style object file. - case $destfile in - *.lo) - func_lo2o "$destfile" - staticdest=$func_lo2o_result - ;; - *.$objext) - staticdest="$destfile" - destfile= - ;; - *) - func_fatal_help "cannot copy a libtool object to \`$destfile'" - ;; - esac - - # Install the libtool object if requested. - test -n "$destfile" && \ - func_show_eval "$install_prog $file $destfile" 'exit $?' - - # Install the old object if enabled. - if test "$build_old_libs" = yes; then - # Deduce the name of the old-style object file. - func_lo2o "$file" - staticobj=$func_lo2o_result - func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' - fi - exit $EXIT_SUCCESS - ;; - - *) - # Figure out destination file name, if it wasn't already specified. - if test -n "$destname"; then - destfile="$destdir/$destname" - else - func_basename "$file" - destfile="$func_basename_result" - destfile="$destdir/$destfile" - fi - - # If the file is missing, and there is a .exe on the end, strip it - # because it is most likely a libtool script we actually want to - # install - stripped_ext="" - case $file in - *.exe) - if test ! -f "$file"; then - func_stripname '' '.exe' "$file" - file=$func_stripname_result - stripped_ext=".exe" - fi - ;; - esac - - # Do a test to see if this is really a libtool program. - case $host in - *cygwin*|*mingw*) - if func_ltwrapper_executable_p "$file"; then - func_ltwrapper_scriptname "$file" - wrapper=$func_ltwrapper_scriptname_result - else - func_stripname '' '.exe' "$file" - wrapper=$func_stripname_result - fi - ;; - *) - wrapper=$file - ;; - esac - if func_ltwrapper_script_p "$wrapper"; then - notinst_deplibs= - relink_command= - - func_source "$wrapper" - - # Check the variables that should have been set. - test -z "$generated_by_libtool_version" && \ - func_fatal_error "invalid libtool wrapper script \`$wrapper'" - - finalize=yes - for lib in $notinst_deplibs; do - # Check to see that each library is installed. - libdir= - if test -f "$lib"; then - func_source "$lib" - fi - libfile="$libdir/"`$ECHO "X$lib" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test - if test -n "$libdir" && test ! -f "$libfile"; then - func_warning "\`$lib' has not been installed in \`$libdir'" - finalize=no - fi - done - - relink_command= - func_source "$wrapper" - - outputname= - if test "$fast_install" = no && test -n "$relink_command"; then - $opt_dry_run || { - if test "$finalize" = yes; then - tmpdir=`func_mktempdir` - func_basename "$file$stripped_ext" - file="$func_basename_result" - outputname="$tmpdir/$file" - # Replace the output file specification. - relink_command=`$ECHO "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` - - $opt_silent || { - func_quote_for_expand "$relink_command" - eval "func_echo $func_quote_for_expand_result" - } - if eval "$relink_command"; then : - else - func_error "error: relink \`$file' with the above command before installing it" - $opt_dry_run || ${RM}r "$tmpdir" - continue - fi - file="$outputname" - else - func_warning "cannot relink \`$file'" - fi - } - else - # Install the binary that we compiled earlier. - file=`$ECHO "X$file$stripped_ext" | $Xsed -e "s%\([^/]*\)$%$objdir/\1%"` - fi - fi - - # remove .exe since cygwin /usr/bin/install will append another - # one anyway - case $install_prog,$host in - */usr/bin/install*,*cygwin*) - case $file:$destfile in - *.exe:*.exe) - # this is ok - ;; - *.exe:*) - destfile=$destfile.exe - ;; - *:*.exe) - func_stripname '' '.exe' "$destfile" - destfile=$func_stripname_result - ;; - esac - ;; - esac - func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' - $opt_dry_run || if test -n "$outputname"; then - ${RM}r "$tmpdir" - fi - ;; - esac - done - - for file in $staticlibs; do - func_basename "$file" - name="$func_basename_result" - - # Set up the ranlib parameters. - oldlib="$destdir/$name" - - func_show_eval "$install_prog \$file \$oldlib" 'exit $?' - - if test -n "$stripme" && test -n "$old_striplib"; then - func_show_eval "$old_striplib $oldlib" 'exit $?' - fi - - # Do each command in the postinstall commands. - func_execute_cmds "$old_postinstall_cmds" 'exit $?' - done - - test -n "$future_libdirs" && \ - func_warning "remember to run \`$progname --finish$future_libdirs'" - - if test -n "$current_libdirs"; then - # Maybe just do a dry run. - $opt_dry_run && current_libdirs=" -n$current_libdirs" - exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' - else - exit $EXIT_SUCCESS - fi -} - -test "$mode" = install && func_mode_install ${1+"$@"} - - -# func_generate_dlsyms outputname originator pic_p -# Extract symbols from dlprefiles and create ${outputname}S.o with -# a dlpreopen symbol table. -func_generate_dlsyms () -{ - $opt_debug - my_outputname="$1" - my_originator="$2" - my_pic_p="${3-no}" - my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` - my_dlsyms= - - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - if test -n "$NM" && test -n "$global_symbol_pipe"; then - my_dlsyms="${my_outputname}S.c" - else - func_error "not configured to extract global symbols from dlpreopened files" - fi - fi - - if test -n "$my_dlsyms"; then - case $my_dlsyms in - "") ;; - *.c) - # Discover the nlist of each of the dlfiles. - nlist="$output_objdir/${my_outputname}.nm" - - func_show_eval "$RM $nlist ${nlist}S ${nlist}T" - - # Parse the name list into a source file. - func_verbose "creating $output_objdir/$my_dlsyms" - - $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ -/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ -/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ - -#ifdef __cplusplus -extern \"C\" { -#endif - -/* External symbol declarations for the compiler. */\ -" - - if test "$dlself" = yes; then - func_verbose "generating symbol list for \`$output'" - - $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" - - # Add our own program objects to the symbol list. - progfiles=`$ECHO "X$objs$old_deplibs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - for progfile in $progfiles; do - func_verbose "extracting global C symbols from \`$progfile'" - $opt_dry_run || eval "$NM $progfile | $global_symbol_pipe >> '$nlist'" - done - - if test -n "$exclude_expsyms"; then - $opt_dry_run || { - eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' - eval '$MV "$nlist"T "$nlist"' - } - fi - - if test -n "$export_symbols_regex"; then - $opt_dry_run || { - eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' - eval '$MV "$nlist"T "$nlist"' - } - fi - - # Prepare the list of exported symbols - if test -z "$export_symbols"; then - export_symbols="$output_objdir/$outputname.exp" - $opt_dry_run || { - $RM $export_symbols - eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' - case $host in - *cygwin* | *mingw* ) - eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' - eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' - ;; - esac - } - else - $opt_dry_run || { - eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' - eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' - eval '$MV "$nlist"T "$nlist"' - case $host in - *cygwin | *mingw* ) - eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' - eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' - ;; - esac - } - fi - fi - - for dlprefile in $dlprefiles; do - func_verbose "extracting global C symbols from \`$dlprefile'" - func_basename "$dlprefile" - name="$func_basename_result" - $opt_dry_run || { - eval '$ECHO ": $name " >> "$nlist"' - eval "$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'" - } - done - - $opt_dry_run || { - # Make sure we have at least an empty file. - test -f "$nlist" || : > "$nlist" - - if test -n "$exclude_expsyms"; then - $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T - $MV "$nlist"T "$nlist" - fi - - # Try sorting and uniquifying the output. - if $GREP -v "^: " < "$nlist" | - if sort -k 3 /dev/null 2>&1; then - sort -k 3 - else - sort +2 - fi | - uniq > "$nlist"S; then - : - else - $GREP -v "^: " < "$nlist" > "$nlist"S - fi - - if test -f "$nlist"S; then - eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' - else - $ECHO '/* NONE */' >> "$output_objdir/$my_dlsyms" - fi - - $ECHO >> "$output_objdir/$my_dlsyms" "\ - -/* The mapping between symbol names and symbols. */ -typedef struct { - const char *name; - void *address; -} lt_dlsymlist; -" - case $host in - *cygwin* | *mingw* ) - $ECHO >> "$output_objdir/$my_dlsyms" "\ -/* DATA imports from DLLs on WIN32 con't be const, because - runtime relocations are performed -- see ld's documentation - on pseudo-relocs. */" - lt_dlsym_const= ;; - *osf5*) - echo >> "$output_objdir/$my_dlsyms" "\ -/* This system does not cope well with relocations in const data */" - lt_dlsym_const= ;; - *) - lt_dlsym_const=const ;; - esac - - $ECHO >> "$output_objdir/$my_dlsyms" "\ -extern $lt_dlsym_const lt_dlsymlist -lt_${my_prefix}_LTX_preloaded_symbols[]; -$lt_dlsym_const lt_dlsymlist -lt_${my_prefix}_LTX_preloaded_symbols[] = -{\ - { \"$my_originator\", (void *) 0 }," - - case $need_lib_prefix in - no) - eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" - ;; - *) - eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" - ;; - esac - $ECHO >> "$output_objdir/$my_dlsyms" "\ - {0, (void *) 0} -}; - -/* This works around a problem in FreeBSD linker */ -#ifdef FREEBSD_WORKAROUND -static const void *lt_preloaded_setup() { - return lt_${my_prefix}_LTX_preloaded_symbols; -} -#endif - -#ifdef __cplusplus -} -#endif\ -" - } # !$opt_dry_run - - pic_flag_for_symtable= - case "$compile_command " in - *" -static "*) ;; - *) - case $host in - # compiling the symbol table file with pic_flag works around - # a FreeBSD bug that causes programs to crash when -lm is - # linked before any other PIC object. But we must not use - # pic_flag when linking with -static. The problem exists in - # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. - *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) - pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; - *-*-hpux*) - pic_flag_for_symtable=" $pic_flag" ;; - *) - if test "X$my_pic_p" != Xno; then - pic_flag_for_symtable=" $pic_flag" - fi - ;; - esac - ;; - esac - symtab_cflags= - for arg in $LTCFLAGS; do - case $arg in - -pie | -fpie | -fPIE) ;; - *) symtab_cflags="$symtab_cflags $arg" ;; - esac - done - - # Now compile the dynamic symbol file. - func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' - - # Clean up the generated files. - func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' - - # Transform the symbol file into the correct name. - symfileobj="$output_objdir/${my_outputname}S.$objext" - case $host in - *cygwin* | *mingw* ) - if test -f "$output_objdir/$my_outputname.def"; then - compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` - finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` - else - compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` - finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` - fi - ;; - *) - compile_command=`$ECHO "X$compile_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` - finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$symfileobj%"` - ;; - esac - ;; - *) - func_fatal_error "unknown suffix for \`$my_dlsyms'" - ;; - esac - else - # We keep going just in case the user didn't refer to - # lt_preloaded_symbols. The linker will fail if global_symbol_pipe - # really was required. - - # Nullify the symbol file. - compile_command=`$ECHO "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` - finalize_command=`$ECHO "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` - fi -} - -# func_win32_libid arg -# return the library type of file 'arg' -# -# Need a lot of goo to handle *both* DLLs and import libs -# Has to be a shell function in order to 'eat' the argument -# that is supplied when $file_magic_command is called. -func_win32_libid () -{ - $opt_debug - win32_libid_type="unknown" - win32_fileres=`file -L $1 2>/dev/null` - case $win32_fileres in - *ar\ archive\ import\ library*) # definitely import - win32_libid_type="x86 archive import" - ;; - *ar\ archive*) # could be an import, or static - if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | - $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then - win32_nmres=`eval $NM -f posix -A $1 | - $SED -n -e ' - 1,100{ - / I /{ - s,.*,import, - p - q - } - }'` - case $win32_nmres in - import*) win32_libid_type="x86 archive import";; - *) win32_libid_type="x86 archive static";; - esac - fi - ;; - *DLL*) - win32_libid_type="x86 DLL" - ;; - *executable*) # but shell scripts are "executable" too... - case $win32_fileres in - *MS\ Windows\ PE\ Intel*) - win32_libid_type="x86 DLL" - ;; - esac - ;; - esac - $ECHO "$win32_libid_type" -} - - - -# func_extract_an_archive dir oldlib -func_extract_an_archive () -{ - $opt_debug - f_ex_an_ar_dir="$1"; shift - f_ex_an_ar_oldlib="$1" - func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" 'exit $?' - if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then - : - else - func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" - fi -} - - -# func_extract_archives gentop oldlib ... -func_extract_archives () -{ - $opt_debug - my_gentop="$1"; shift - my_oldlibs=${1+"$@"} - my_oldobjs="" - my_xlib="" - my_xabs="" - my_xdir="" - - for my_xlib in $my_oldlibs; do - # Extract the objects. - case $my_xlib in - [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; - *) my_xabs=`pwd`"/$my_xlib" ;; - esac - func_basename "$my_xlib" - my_xlib="$func_basename_result" - my_xlib_u=$my_xlib - while :; do - case " $extracted_archives " in - *" $my_xlib_u "*) - func_arith $extracted_serial + 1 - extracted_serial=$func_arith_result - my_xlib_u=lt$extracted_serial-$my_xlib ;; - *) break ;; - esac - done - extracted_archives="$extracted_archives $my_xlib_u" - my_xdir="$my_gentop/$my_xlib_u" - - func_mkdir_p "$my_xdir" - - case $host in - *-darwin*) - func_verbose "Extracting $my_xabs" - # Do not bother doing anything if just a dry run - $opt_dry_run || { - darwin_orig_dir=`pwd` - cd $my_xdir || exit $? - darwin_archive=$my_xabs - darwin_curdir=`pwd` - darwin_base_archive=`basename "$darwin_archive"` - darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` - if test -n "$darwin_arches"; then - darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` - darwin_arch= - func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" - for darwin_arch in $darwin_arches ; do - func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" - $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" - cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" - func_extract_an_archive "`pwd`" "${darwin_base_archive}" - cd "$darwin_curdir" - $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" - done # $darwin_arches - ## Okay now we've a bunch of thin objects, gotta fatten them up :) - darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` - darwin_file= - darwin_files= - for darwin_file in $darwin_filelist; do - darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP` - $LIPO -create -output "$darwin_file" $darwin_files - done # $darwin_filelist - $RM -rf unfat-$$ - cd "$darwin_orig_dir" - else - cd $darwin_orig_dir - func_extract_an_archive "$my_xdir" "$my_xabs" - fi # $darwin_arches - } # !$opt_dry_run - ;; - *) - func_extract_an_archive "$my_xdir" "$my_xabs" - ;; - esac - my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | $NL2SP` - done - - func_extract_archives_result="$my_oldobjs" -} - - - -# func_emit_wrapper arg -# -# emit a libtool wrapper script on stdout -# don't directly open a file because we may want to -# incorporate the script contents within a cygwin/mingw -# wrapper executable. Must ONLY be called from within -# func_mode_link because it depends on a number of variable -# set therein. -# -# arg is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR -# variable will take. If 'yes', then the emitted script -# will assume that the directory in which it is stored is -# the '.lib' directory. This is a cygwin/mingw-specific -# behavior. -func_emit_wrapper () -{ - func_emit_wrapper_arg1=no - if test -n "$1" ; then - func_emit_wrapper_arg1=$1 - fi - - $ECHO "\ -#! $SHELL - -# $output - temporary wrapper script for $objdir/$outputname -# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION -# -# The $output program cannot be directly executed until all the libtool -# libraries that it depends on are installed. -# -# This wrapper script should never be moved out of the build directory. -# If it is, it will not operate correctly. - -# Sed substitution that helps us do robust quoting. It backslashifies -# metacharacters that are still active within double-quoted strings. -Xsed='${SED} -e 1s/^X//' -sed_quote_subst='$sed_quote_subst' - -# Be Bourne compatible -if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which - # is contrary to our usage. Disable this feature. - alias -g '\${1+\"\$@\"}'='\"\$@\"' - setopt NO_GLOB_SUBST -else - case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac -fi -BIN_SH=xpg4; export BIN_SH # for Tru64 -DUALCASE=1; export DUALCASE # for MKS sh - -# The HP-UX ksh and POSIX shell print the target directory to stdout -# if CDPATH is set. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -relink_command=\"$relink_command\" - -# This environment variable determines our operation mode. -if test \"\$libtool_install_magic\" = \"$magic\"; then - # install mode needs the following variables: - generated_by_libtool_version='$macro_version' - notinst_deplibs='$notinst_deplibs' -else - # When we are sourced in execute mode, \$file and \$ECHO are already set. - if test \"\$libtool_execute_magic\" != \"$magic\"; then - ECHO=\"$qecho\" - file=\"\$0\" - # Make sure echo works. - if test \"X\$1\" = X--no-reexec; then - # Discard the --no-reexec flag, and continue. - shift - elif test \"X\`{ \$ECHO '\t'; } 2>/dev/null\`\" = 'X\t'; then - # Yippee, \$ECHO works! - : - else - # Restart under the correct shell, and then maybe \$ECHO will work. - exec $SHELL \"\$0\" --no-reexec \${1+\"\$@\"} - fi - fi\ -" - $ECHO "\ - - # Find the directory that this script lives in. - thisdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*$%%'\` - test \"x\$thisdir\" = \"x\$file\" && thisdir=. - - # Follow symbolic links until we get to the real thisdir. - file=\`ls -ld \"\$file\" | ${SED} -n 's/.*-> //p'\` - while test -n \"\$file\"; do - destdir=\`\$ECHO \"X\$file\" | \$Xsed -e 's%/[^/]*\$%%'\` - - # If there was a directory component, then change thisdir. - if test \"x\$destdir\" != \"x\$file\"; then - case \"\$destdir\" in - [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; - *) thisdir=\"\$thisdir/\$destdir\" ;; - esac - fi - - file=\`\$ECHO \"X\$file\" | \$Xsed -e 's%^.*/%%'\` - file=\`ls -ld \"\$thisdir/\$file\" | ${SED} -n 's/.*-> //p'\` - done - - # Usually 'no', except on cygwin/mingw when embedded into - # the cwrapper. - WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 - if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then - # special case for '.' - if test \"\$thisdir\" = \".\"; then - thisdir=\`pwd\` - fi - # remove .libs from thisdir - case \"\$thisdir\" in - *[\\\\/]$objdir ) thisdir=\`\$ECHO \"X\$thisdir\" | \$Xsed -e 's%[\\\\/][^\\\\/]*$%%'\` ;; - $objdir ) thisdir=. ;; - esac - fi - - # Try to get the absolute directory name. - absdir=\`cd \"\$thisdir\" && pwd\` - test -n \"\$absdir\" && thisdir=\"\$absdir\" -" - - if test "$fast_install" = yes; then - $ECHO "\ - program=lt-'$outputname'$exeext - progdir=\"\$thisdir/$objdir\" - - if test ! -f \"\$progdir/\$program\" || - { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ - test \"X\$file\" != \"X\$progdir/\$program\"; }; then - - file=\"\$\$-\$program\" - - if test ! -d \"\$progdir\"; then - $MKDIR \"\$progdir\" - else - $RM \"\$progdir/\$file\" - fi" - - $ECHO "\ - - # relink executable if necessary - if test -n \"\$relink_command\"; then - if relink_command_output=\`eval \$relink_command 2>&1\`; then : - else - $ECHO \"\$relink_command_output\" >&2 - $RM \"\$progdir/\$file\" - exit 1 - fi - fi - - $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || - { $RM \"\$progdir/\$program\"; - $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } - $RM \"\$progdir/\$file\" - fi" - else - $ECHO "\ - program='$outputname' - progdir=\"\$thisdir/$objdir\" -" - fi - - $ECHO "\ - - if test -f \"\$progdir/\$program\"; then" - - # Export our shlibpath_var if we have one. - if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then - $ECHO "\ - # Add our own library path to $shlibpath_var - $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" - - # Some systems cannot cope with colon-terminated $shlibpath_var - # The second colon is a workaround for a bug in BeOS R4 sed - $shlibpath_var=\`\$ECHO \"X\$$shlibpath_var\" | \$Xsed -e 's/::*\$//'\` - - export $shlibpath_var -" - fi - - # fixup the dll searchpath if we need to. - if test -n "$dllsearchpath"; then - $ECHO "\ - # Add the dll search path components to the executable PATH - PATH=$dllsearchpath:\$PATH -" - fi - - $ECHO "\ - if test \"\$libtool_execute_magic\" != \"$magic\"; then - # Run the actual program with our arguments. -" - case $host in - # Backslashes separate directories on plain windows - *-*-mingw | *-*-os2*) - $ECHO "\ - exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} -" - ;; - - *) - $ECHO "\ - exec \"\$progdir/\$program\" \${1+\"\$@\"} -" - ;; - esac - $ECHO "\ - \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 - exit 1 - fi - else - # The program doesn't exist. - \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 - \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 - $ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 - exit 1 - fi -fi\ -" -} -# end: func_emit_wrapper - -# func_emit_cwrapperexe_src -# emit the source code for a wrapper executable on stdout -# Must ONLY be called from within func_mode_link because -# it depends on a number of variable set therein. -func_emit_cwrapperexe_src () -{ - cat < -#include -#ifdef _MSC_VER -# include -# include -# include -# define setmode _setmode -#else -# include -# include -# ifdef __CYGWIN__ -# include -# endif -#endif -#include -#include -#include -#include -#include -#include -#include -#include - -#if defined(PATH_MAX) -# define LT_PATHMAX PATH_MAX -#elif defined(MAXPATHLEN) -# define LT_PATHMAX MAXPATHLEN -#else -# define LT_PATHMAX 1024 -#endif - -#ifndef S_IXOTH -# define S_IXOTH 0 -#endif -#ifndef S_IXGRP -# define S_IXGRP 0 -#endif - -#ifdef _MSC_VER -# define S_IXUSR _S_IEXEC -# define stat _stat -# ifndef _INTPTR_T_DEFINED -# define intptr_t int -# endif -#endif - -#ifndef DIR_SEPARATOR -# define DIR_SEPARATOR '/' -# define PATH_SEPARATOR ':' -#endif - -#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ - defined (__OS2__) -# define HAVE_DOS_BASED_FILE_SYSTEM -# define FOPEN_WB "wb" -# ifndef DIR_SEPARATOR_2 -# define DIR_SEPARATOR_2 '\\' -# endif -# ifndef PATH_SEPARATOR_2 -# define PATH_SEPARATOR_2 ';' -# endif -#endif - -#ifndef DIR_SEPARATOR_2 -# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) -#else /* DIR_SEPARATOR_2 */ -# define IS_DIR_SEPARATOR(ch) \ - (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) -#endif /* DIR_SEPARATOR_2 */ - -#ifndef PATH_SEPARATOR_2 -# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) -#else /* PATH_SEPARATOR_2 */ -# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) -#endif /* PATH_SEPARATOR_2 */ - -#ifdef __CYGWIN__ -# define FOPEN_WB "wb" -#endif - -#ifndef FOPEN_WB -# define FOPEN_WB "w" -#endif -#ifndef _O_BINARY -# define _O_BINARY 0 -#endif - -#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) -#define XFREE(stale) do { \ - if (stale) { free ((void *) stale); stale = 0; } \ -} while (0) - -#undef LTWRAPPER_DEBUGPRINTF -#if defined DEBUGWRAPPER -# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args -static void -ltwrapper_debugprintf (const char *fmt, ...) -{ - va_list args; - va_start (args, fmt); - (void) vfprintf (stderr, fmt, args); - va_end (args); -} -#else -# define LTWRAPPER_DEBUGPRINTF(args) -#endif - -const char *program_name = NULL; - -void *xmalloc (size_t num); -char *xstrdup (const char *string); -const char *base_name (const char *name); -char *find_executable (const char *wrapper); -char *chase_symlinks (const char *pathspec); -int make_executable (const char *path); -int check_executable (const char *path); -char *strendzap (char *str, const char *pat); -void lt_fatal (const char *message, ...); - -static const char *script_text = -EOF - - func_emit_wrapper yes | - $SED -e 's/\([\\"]\)/\\\1/g' \ - -e 's/^/ "/' -e 's/$/\\n"/' - echo ";" - - cat </dev/null || echo $SHELL` - case $lt_newargv0 in - *.exe | *.EXE) ;; - *) lt_newargv0=$lt_newargv0.exe ;; - esac - ;; - * ) lt_newargv0=$SHELL ;; - esac - fi - - cat <= 0) - && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) - return 1; - else - return 0; -} - -int -make_executable (const char *path) -{ - int rval = 0; - struct stat st; - - LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", - path ? (*path ? path : "EMPTY!") : "NULL!")); - if ((!path) || (!*path)) - return 0; - - if (stat (path, &st) >= 0) - { - rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); - } - return rval; -} - -/* Searches for the full path of the wrapper. Returns - newly allocated full path name if found, NULL otherwise - Does not chase symlinks, even on platforms that support them. -*/ -char * -find_executable (const char *wrapper) -{ - int has_slash = 0; - const char *p; - const char *p_next; - /* static buffer for getcwd */ - char tmp[LT_PATHMAX + 1]; - int tmp_len; - char *concat_name; - - LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", - wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); - - if ((wrapper == NULL) || (*wrapper == '\0')) - return NULL; - - /* Absolute path? */ -#if defined (HAVE_DOS_BASED_FILE_SYSTEM) - if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') - { - concat_name = xstrdup (wrapper); - if (check_executable (concat_name)) - return concat_name; - XFREE (concat_name); - } - else - { -#endif - if (IS_DIR_SEPARATOR (wrapper[0])) - { - concat_name = xstrdup (wrapper); - if (check_executable (concat_name)) - return concat_name; - XFREE (concat_name); - } -#if defined (HAVE_DOS_BASED_FILE_SYSTEM) - } -#endif - - for (p = wrapper; *p; p++) - if (*p == '/') - { - has_slash = 1; - break; - } - if (!has_slash) - { - /* no slashes; search PATH */ - const char *path = getenv ("PATH"); - if (path != NULL) - { - for (p = path; *p; p = p_next) - { - const char *q; - size_t p_len; - for (q = p; *q; q++) - if (IS_PATH_SEPARATOR (*q)) - break; - p_len = q - p; - p_next = (*q == '\0' ? q : q + 1); - if (p_len == 0) - { - /* empty path: current directory */ - if (getcwd (tmp, LT_PATHMAX) == NULL) - lt_fatal ("getcwd failed"); - tmp_len = strlen (tmp); - concat_name = - XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); - memcpy (concat_name, tmp, tmp_len); - concat_name[tmp_len] = '/'; - strcpy (concat_name + tmp_len + 1, wrapper); - } - else - { - concat_name = - XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); - memcpy (concat_name, p, p_len); - concat_name[p_len] = '/'; - strcpy (concat_name + p_len + 1, wrapper); - } - if (check_executable (concat_name)) - return concat_name; - XFREE (concat_name); - } - } - /* not found in PATH; assume curdir */ - } - /* Relative path | not found in path: prepend cwd */ - if (getcwd (tmp, LT_PATHMAX) == NULL) - lt_fatal ("getcwd failed"); - tmp_len = strlen (tmp); - concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); - memcpy (concat_name, tmp, tmp_len); - concat_name[tmp_len] = '/'; - strcpy (concat_name + tmp_len + 1, wrapper); - - if (check_executable (concat_name)) - return concat_name; - XFREE (concat_name); - return NULL; -} - -char * -chase_symlinks (const char *pathspec) -{ -#ifndef S_ISLNK - return xstrdup (pathspec); -#else - char buf[LT_PATHMAX]; - struct stat s; - char *tmp_pathspec = xstrdup (pathspec); - char *p; - int has_symlinks = 0; - while (strlen (tmp_pathspec) && !has_symlinks) - { - LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", - tmp_pathspec)); - if (lstat (tmp_pathspec, &s) == 0) - { - if (S_ISLNK (s.st_mode) != 0) - { - has_symlinks = 1; - break; - } - - /* search backwards for last DIR_SEPARATOR */ - p = tmp_pathspec + strlen (tmp_pathspec) - 1; - while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) - p--; - if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) - { - /* no more DIR_SEPARATORS left */ - break; - } - *p = '\0'; - } - else - { - char *errstr = strerror (errno); - lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); - } - } - XFREE (tmp_pathspec); - - if (!has_symlinks) - { - return xstrdup (pathspec); - } - - tmp_pathspec = realpath (pathspec, buf); - if (tmp_pathspec == 0) - { - lt_fatal ("Could not follow symlinks for %s", pathspec); - } - return xstrdup (tmp_pathspec); -#endif -} - -char * -strendzap (char *str, const char *pat) -{ - size_t len, patlen; - - assert (str != NULL); - assert (pat != NULL); - - len = strlen (str); - patlen = strlen (pat); - - if (patlen <= len) - { - str += len - patlen; - if (strcmp (str, pat) == 0) - *str = '\0'; - } - return str; -} - -static void -lt_error_core (int exit_status, const char *mode, - const char *message, va_list ap) -{ - fprintf (stderr, "%s: %s: ", program_name, mode); - vfprintf (stderr, message, ap); - fprintf (stderr, ".\n"); - - if (exit_status >= 0) - exit (exit_status); -} - -void -lt_fatal (const char *message, ...) -{ - va_list ap; - va_start (ap, message); - lt_error_core (EXIT_FAILURE, "FATAL", message, ap); - va_end (ap); -} -EOF -} -# end: func_emit_cwrapperexe_src - -# func_mode_link arg... -func_mode_link () -{ - $opt_debug - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - # It is impossible to link a dll without this setting, and - # we shouldn't force the makefile maintainer to figure out - # which system we are compiling for in order to pass an extra - # flag for every libtool invocation. - # allow_undefined=no - - # FIXME: Unfortunately, there are problems with the above when trying - # to make a dll which has undefined symbols, in which case not - # even a static library is built. For now, we need to specify - # -no-undefined on the libtool link line when we can be certain - # that all symbols are satisfied, otherwise we get a static library. - allow_undefined=yes - ;; - *) - allow_undefined=yes - ;; - esac - libtool_args=$nonopt - base_compile="$nonopt $@" - compile_command=$nonopt - finalize_command=$nonopt - - compile_rpath= - finalize_rpath= - compile_shlibpath= - finalize_shlibpath= - convenience= - old_convenience= - deplibs= - old_deplibs= - compiler_flags= - linker_flags= - dllsearchpath= - lib_search_path=`pwd` - inst_prefix_dir= - new_inherited_linker_flags= - - avoid_version=no - dlfiles= - dlprefiles= - dlself=no - export_dynamic=no - export_symbols= - export_symbols_regex= - generated= - libobjs= - ltlibs= - module=no - no_install=no - objs= - non_pic_objects= - precious_files_regex= - prefer_static_libs=no - preload=no - prev= - prevarg= - release= - rpath= - xrpath= - perm_rpath= - temp_rpath= - thread_safe=no - vinfo= - vinfo_number=no - weak_libs= - single_module="${wl}-single_module" - func_infer_tag $base_compile - - # We need to know -static, to get the right output filenames. - for arg - do - case $arg in - -shared) - test "$build_libtool_libs" != yes && \ - func_fatal_configuration "can not build a shared library" - build_old_libs=no - break - ;; - -all-static | -static | -static-libtool-libs) - case $arg in - -all-static) - if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then - func_warning "complete static linking is impossible in this configuration" - fi - if test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=yes - ;; - -static) - if test -z "$pic_flag" && test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=built - ;; - -static-libtool-libs) - if test -z "$pic_flag" && test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=yes - ;; - esac - build_libtool_libs=no - build_old_libs=yes - break - ;; - esac - done - - # See if our shared archives depend on static archives. - test -n "$old_archive_from_new_cmds" && build_old_libs=yes - - # Go through the arguments, transforming them on the way. - while test "$#" -gt 0; do - arg="$1" - shift - func_quote_for_eval "$arg" - qarg=$func_quote_for_eval_unquoted_result - func_append libtool_args " $func_quote_for_eval_result" - - # If the previous option needs an argument, assign it. - if test -n "$prev"; then - case $prev in - output) - func_append compile_command " @OUTPUT@" - func_append finalize_command " @OUTPUT@" - ;; - esac - - case $prev in - dlfiles|dlprefiles) - if test "$preload" = no; then - # Add the symbol object into the linking commands. - func_append compile_command " @SYMFILE@" - func_append finalize_command " @SYMFILE@" - preload=yes - fi - case $arg in - *.la | *.lo) ;; # We handle these cases below. - force) - if test "$dlself" = no; then - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - self) - if test "$prev" = dlprefiles; then - dlself=yes - elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then - dlself=yes - else - dlself=needless - export_dynamic=yes - fi - prev= - continue - ;; - *) - if test "$prev" = dlfiles; then - dlfiles="$dlfiles $arg" - else - dlprefiles="$dlprefiles $arg" - fi - prev= - continue - ;; - esac - ;; - expsyms) - export_symbols="$arg" - test -f "$arg" \ - || func_fatal_error "symbol file \`$arg' does not exist" - prev= - continue - ;; - expsyms_regex) - export_symbols_regex="$arg" - prev= - continue - ;; - framework) - case $host in - *-*-darwin*) - case "$deplibs " in - *" $qarg.ltframework "*) ;; - *) deplibs="$deplibs $qarg.ltframework" # this is fixed later - ;; - esac - ;; - esac - prev= - continue - ;; - inst_prefix) - inst_prefix_dir="$arg" - prev= - continue - ;; - objectlist) - if test -f "$arg"; then - save_arg=$arg - moreargs= - for fil in `cat "$save_arg"` - do -# moreargs="$moreargs $fil" - arg=$fil - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if func_lalib_unsafe_p "$arg"; then - pic_object= - non_pic_object= - - # Read the .lo file - func_source "$arg" - - if test -z "$pic_object" || - test -z "$non_pic_object" || - test "$pic_object" = none && - test "$non_pic_object" = none; then - func_fatal_error "cannot find name of object for \`$arg'" - fi - - # Extract subdirectory from the argument. - func_dirname "$arg" "/" "" - xdir="$func_dirname_result" - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - func_append libobjs " $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - func_append non_pic_objects " $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - func_append non_pic_objects " $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if $opt_dry_run; then - # Extract subdirectory from the argument. - func_dirname "$arg" "/" "" - xdir="$func_dirname_result" - - func_lo2o "$arg" - pic_object=$xdir$objdir/$func_lo2o_result - non_pic_object=$xdir$func_lo2o_result - func_append libobjs " $pic_object" - func_append non_pic_objects " $non_pic_object" - else - func_fatal_error "\`$arg' is not a valid libtool object" - fi - fi - done - else - func_fatal_error "link input file \`$arg' does not exist" - fi - arg=$save_arg - prev= - continue - ;; - precious_regex) - precious_files_regex="$arg" - prev= - continue - ;; - release) - release="-$arg" - prev= - continue - ;; - rpath | xrpath) - # We need an absolute path. - case $arg in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - func_fatal_error "only absolute run-paths are allowed" - ;; - esac - if test "$prev" = rpath; then - case "$rpath " in - *" $arg "*) ;; - *) rpath="$rpath $arg" ;; - esac - else - case "$xrpath " in - *" $arg "*) ;; - *) xrpath="$xrpath $arg" ;; - esac - fi - prev= - continue - ;; - shrext) - shrext_cmds="$arg" - prev= - continue - ;; - weak) - weak_libs="$weak_libs $arg" - prev= - continue - ;; - xcclinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $qarg" - prev= - func_append compile_command " $qarg" - func_append finalize_command " $qarg" - continue - ;; - xcompiler) - compiler_flags="$compiler_flags $qarg" - prev= - func_append compile_command " $qarg" - func_append finalize_command " $qarg" - continue - ;; - xlinker) - linker_flags="$linker_flags $qarg" - compiler_flags="$compiler_flags $wl$qarg" - prev= - func_append compile_command " $wl$qarg" - func_append finalize_command " $wl$qarg" - continue - ;; - *) - eval "$prev=\"\$arg\"" - prev= - continue - ;; - esac - fi # test -n "$prev" - - prevarg="$arg" - - case $arg in - -all-static) - if test -n "$link_static_flag"; then - # See comment for -static flag below, for more details. - func_append compile_command " $link_static_flag" - func_append finalize_command " $link_static_flag" - fi - continue - ;; - - -allow-undefined) - # FIXME: remove this flag sometime in the future. - func_fatal_error "\`-allow-undefined' must not be used because it is the default" - ;; - - -avoid-version) - avoid_version=yes - continue - ;; - - -dlopen) - prev=dlfiles - continue - ;; - - -dlpreopen) - prev=dlprefiles - continue - ;; - - -export-dynamic) - export_dynamic=yes - continue - ;; - - -export-symbols | -export-symbols-regex) - if test -n "$export_symbols" || test -n "$export_symbols_regex"; then - func_fatal_error "more than one -exported-symbols argument is not allowed" - fi - if test "X$arg" = "X-export-symbols"; then - prev=expsyms - else - prev=expsyms_regex - fi - continue - ;; - - -framework) - prev=framework - continue - ;; - - -inst-prefix-dir) - prev=inst_prefix - continue - ;; - - # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* - # so, if we see these flags be careful not to treat them like -L - -L[A-Z][A-Z]*:*) - case $with_gcc/$host in - no/*-*-irix* | /*-*-irix*) - func_append compile_command " $arg" - func_append finalize_command " $arg" - ;; - esac - continue - ;; - - -L*) - func_stripname '-L' '' "$arg" - dir=$func_stripname_result - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - absdir=`cd "$dir" && pwd` - test -z "$absdir" && \ - func_fatal_error "cannot determine absolute directory name of \`$dir'" - dir="$absdir" - ;; - esac - case "$deplibs " in - *" -L$dir "*) ;; - *) - deplibs="$deplibs -L$dir" - lib_search_path="$lib_search_path $dir" - ;; - esac - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - testbindir=`$ECHO "X$dir" | $Xsed -e 's*/lib$*/bin*'` - case :$dllsearchpath: in - *":$dir:"*) ;; - *) dllsearchpath="$dllsearchpath:$dir";; - esac - case :$dllsearchpath: in - *":$testbindir:"*) ;; - *) dllsearchpath="$dllsearchpath:$testbindir";; - esac - ;; - esac - continue - ;; - - -l*) - if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos*) - # These systems don't actually have a C or math library (as such) - continue - ;; - *-*-os2*) - # These systems don't actually have a C library (as such) - test "X$arg" = "X-lc" && continue - ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*) - # Do not include libc due to us having libc/libc_r. - test "X$arg" = "X-lc" && continue - ;; - *-*-rhapsody* | *-*-darwin1.[012]) - # Rhapsody C and math libraries are in the System framework - deplibs="$deplibs System.ltframework" - continue - ;; - *-*-sco3.2v5* | *-*-sco5v6*) - # Causes problems with __ctype - test "X$arg" = "X-lc" && continue - ;; - *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) - # Compiler inserts libc in the correct place for threads to work - test "X$arg" = "X-lc" && continue - ;; - esac - elif test "X$arg" = "X-lc_r"; then - case $host in - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc_r directly, use -pthread flag. - continue - ;; - esac - fi - deplibs="$deplibs $arg" - continue - ;; - - -module) - module=yes - continue - ;; - - # Tru64 UNIX uses -model [arg] to determine the layout of C++ - # classes, name mangling, and exception handling. - # Darwin uses the -arch flag to determine output architecture. - -model|-arch|-isysroot) - compiler_flags="$compiler_flags $arg" - func_append compile_command " $arg" - func_append finalize_command " $arg" - prev=xcompiler - continue - ;; - - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) - compiler_flags="$compiler_flags $arg" - func_append compile_command " $arg" - func_append finalize_command " $arg" - case "$new_inherited_linker_flags " in - *" $arg "*) ;; - * ) new_inherited_linker_flags="$new_inherited_linker_flags $arg" ;; - esac - continue - ;; - - -multi_module) - single_module="${wl}-multi_module" - continue - ;; - - -no-fast-install) - fast_install=no - continue - ;; - - -no-install) - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin*) - # The PATH hackery in wrapper scripts is required on Windows - # and Darwin in order for the loader to find any dlls it needs. - func_warning "\`-no-install' is ignored for $host" - func_warning "assuming \`-no-fast-install' instead" - fast_install=no - ;; - *) no_install=yes ;; - esac - continue - ;; - - -no-undefined) - allow_undefined=no - continue - ;; - - -objectlist) - prev=objectlist - continue - ;; - - -o) prev=output ;; - - -precious-files-regex) - prev=precious_regex - continue - ;; - - -release) - prev=release - continue - ;; - - -rpath) - prev=rpath - continue - ;; - - -R) - prev=xrpath - continue - ;; - - -R*) - func_stripname '-R' '' "$arg" - dir=$func_stripname_result - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) ;; - *) - func_fatal_error "only absolute run-paths are allowed" - ;; - esac - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - continue - ;; - - -shared) - # The effects of -shared are defined in a previous loop. - continue - ;; - - -shrext) - prev=shrext - continue - ;; - - -static | -static-libtool-libs) - # The effects of -static are defined in a previous loop. - # We used to do the same as -all-static on platforms that - # didn't have a PIC flag, but the assumption that the effects - # would be equivalent was wrong. It would break on at least - # Digital Unix and AIX. - continue - ;; - - -thread-safe) - thread_safe=yes - continue - ;; - - -version-info) - prev=vinfo - continue - ;; - - -version-number) - prev=vinfo - vinfo_number=yes - continue - ;; - - -weak) - prev=weak - continue - ;; - - -Wc,*) - func_stripname '-Wc,' '' "$arg" - args=$func_stripname_result - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - func_quote_for_eval "$flag" - arg="$arg $wl$func_quote_for_eval_result" - compiler_flags="$compiler_flags $func_quote_for_eval_result" - done - IFS="$save_ifs" - func_stripname ' ' '' "$arg" - arg=$func_stripname_result - ;; - - -Wl,*) - func_stripname '-Wl,' '' "$arg" - args=$func_stripname_result - arg= - save_ifs="$IFS"; IFS=',' - for flag in $args; do - IFS="$save_ifs" - func_quote_for_eval "$flag" - arg="$arg $wl$func_quote_for_eval_result" - compiler_flags="$compiler_flags $wl$func_quote_for_eval_result" - linker_flags="$linker_flags $func_quote_for_eval_result" - done - IFS="$save_ifs" - func_stripname ' ' '' "$arg" - arg=$func_stripname_result - ;; - - -Xcompiler) - prev=xcompiler - continue - ;; - - -Xlinker) - prev=xlinker - continue - ;; - - -XCClinker) - prev=xcclinker - continue - ;; - - # -msg_* for osf cc - -msg_*) - func_quote_for_eval "$arg" - arg="$func_quote_for_eval_result" - ;; - - # -64, -mips[0-9] enable 64-bit mode on the SGI compiler - # -r[0-9][0-9]* specifies the processor on the SGI compiler - # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler - # +DA*, +DD* enable 64-bit mode on the HP compiler - # -q* pass through compiler args for the IBM compiler - # -m*, -t[45]*, -txscale* pass through architecture-specific - # compiler args for GCC - # -F/path gives path to uninstalled frameworks, gcc on darwin - # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC - # @file GCC response files - -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ - -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*) - func_quote_for_eval "$arg" - arg="$func_quote_for_eval_result" - func_append compile_command " $arg" - func_append finalize_command " $arg" - compiler_flags="$compiler_flags $arg" - continue - ;; - - # Some other compiler flag. - -* | +*) - func_quote_for_eval "$arg" - arg="$func_quote_for_eval_result" - ;; - - *.$objext) - # A standard object. - objs="$objs $arg" - ;; - - *.lo) - # A libtool-controlled object. - - # Check to see that this really is a libtool object. - if func_lalib_unsafe_p "$arg"; then - pic_object= - non_pic_object= - - # Read the .lo file - func_source "$arg" - - if test -z "$pic_object" || - test -z "$non_pic_object" || - test "$pic_object" = none && - test "$non_pic_object" = none; then - func_fatal_error "cannot find name of object for \`$arg'" - fi - - # Extract subdirectory from the argument. - func_dirname "$arg" "/" "" - xdir="$func_dirname_result" - - if test "$pic_object" != none; then - # Prepend the subdirectory the object is found in. - pic_object="$xdir$pic_object" - - if test "$prev" = dlfiles; then - if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then - dlfiles="$dlfiles $pic_object" - prev= - continue - else - # If libtool objects are unsupported, then we need to preload. - prev=dlprefiles - fi - fi - - # CHECK ME: I think I busted this. -Ossama - if test "$prev" = dlprefiles; then - # Preload the old-style object. - dlprefiles="$dlprefiles $pic_object" - prev= - fi - - # A PIC object. - func_append libobjs " $pic_object" - arg="$pic_object" - fi - - # Non-PIC object. - if test "$non_pic_object" != none; then - # Prepend the subdirectory the object is found in. - non_pic_object="$xdir$non_pic_object" - - # A standard non-PIC object - func_append non_pic_objects " $non_pic_object" - if test -z "$pic_object" || test "$pic_object" = none ; then - arg="$non_pic_object" - fi - else - # If the PIC object exists, use it instead. - # $xdir was prepended to $pic_object above. - non_pic_object="$pic_object" - func_append non_pic_objects " $non_pic_object" - fi - else - # Only an error if not doing a dry-run. - if $opt_dry_run; then - # Extract subdirectory from the argument. - func_dirname "$arg" "/" "" - xdir="$func_dirname_result" - - func_lo2o "$arg" - pic_object=$xdir$objdir/$func_lo2o_result - non_pic_object=$xdir$func_lo2o_result - func_append libobjs " $pic_object" - func_append non_pic_objects " $non_pic_object" - else - func_fatal_error "\`$arg' is not a valid libtool object" - fi - fi - ;; - - *.$libext) - # An archive. - deplibs="$deplibs $arg" - old_deplibs="$old_deplibs $arg" - continue - ;; - - *.la) - # A libtool-controlled library. - - if test "$prev" = dlfiles; then - # This library was specified with -dlopen. - dlfiles="$dlfiles $arg" - prev= - elif test "$prev" = dlprefiles; then - # The library was specified with -dlpreopen. - dlprefiles="$dlprefiles $arg" - prev= - else - deplibs="$deplibs $arg" - fi - continue - ;; - - # Some other compiler argument. - *) - # Unknown arguments in both finalize_command and compile_command need - # to be aesthetically quoted because they are evaled later. - func_quote_for_eval "$arg" - arg="$func_quote_for_eval_result" - ;; - esac # arg - - # Now actually substitute the argument into the commands. - if test -n "$arg"; then - func_append compile_command " $arg" - func_append finalize_command " $arg" - fi - done # argument parsing loop - - test -n "$prev" && \ - func_fatal_help "the \`$prevarg' option requires an argument" - - if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then - eval arg=\"$export_dynamic_flag_spec\" - func_append compile_command " $arg" - func_append finalize_command " $arg" - fi - - oldlibs= - # calculate the name of the file, without its directory - func_basename "$output" - outputname="$func_basename_result" - libobjs_save="$libobjs" - - if test -n "$shlibpath_var"; then - # get the directories listed in $shlibpath_var - eval shlib_search_path=\`\$ECHO \"X\${$shlibpath_var}\" \| \$Xsed -e \'s/:/ /g\'\` - else - shlib_search_path= - fi - eval sys_lib_search_path=\"$sys_lib_search_path_spec\" - eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" - - func_dirname "$output" "/" "" - output_objdir="$func_dirname_result$objdir" - # Create the object directory. - func_mkdir_p "$output_objdir" - - # Determine the type of output - case $output in - "") - func_fatal_help "you must specify an output file" - ;; - *.$libext) linkmode=oldlib ;; - *.lo | *.$objext) linkmode=obj ;; - *.la) linkmode=lib ;; - *) linkmode=prog ;; # Anything else should be a program. - esac - - specialdeplibs= - - libs= - # Find all interdependent deplibs by searching for libraries - # that are linked more than once (e.g. -la -lb -la) - for deplib in $deplibs; do - if $opt_duplicate_deps ; then - case "$libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - libs="$libs $deplib" - done - - if test "$linkmode" = lib; then - libs="$predeps $libs $compiler_lib_search_path $postdeps" - - # Compute libraries that are listed more than once in $predeps - # $postdeps and mark them as special (i.e., whose duplicates are - # not to be eliminated). - pre_post_deps= - if $opt_duplicate_compiler_generated_deps; then - for pre_post_dep in $predeps $postdeps; do - case "$pre_post_deps " in - *" $pre_post_dep "*) specialdeplibs="$specialdeplibs $pre_post_deps" ;; - esac - pre_post_deps="$pre_post_deps $pre_post_dep" - done - fi - pre_post_deps= - fi - - deplibs= - newdependency_libs= - newlib_search_path= - need_relink=no # whether we're linking any uninstalled libtool libraries - notinst_deplibs= # not-installed libtool libraries - notinst_path= # paths that contain not-installed libtool libraries - - case $linkmode in - lib) - passes="conv dlpreopen link" - for file in $dlfiles $dlprefiles; do - case $file in - *.la) ;; - *) - func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" - ;; - esac - done - ;; - prog) - compile_deplibs= - finalize_deplibs= - alldeplibs=no - newdlfiles= - newdlprefiles= - passes="conv scan dlopen dlpreopen link" - ;; - *) passes="conv" - ;; - esac - - for pass in $passes; do - # The preopen pass in lib mode reverses $deplibs; put it back here - # so that -L comes before libs that need it for instance... - if test "$linkmode,$pass" = "lib,link"; then - ## FIXME: Find the place where the list is rebuilt in the wrong - ## order, and fix it there properly - tmp_deplibs= - for deplib in $deplibs; do - tmp_deplibs="$deplib $tmp_deplibs" - done - deplibs="$tmp_deplibs" - fi - - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan"; then - libs="$deplibs" - deplibs= - fi - if test "$linkmode" = prog; then - case $pass in - dlopen) libs="$dlfiles" ;; - dlpreopen) libs="$dlprefiles" ;; - link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; - esac - fi - if test "$linkmode,$pass" = "lib,dlpreopen"; then - # Collect and forward deplibs of preopened libtool libs - for lib in $dlprefiles; do - # Ignore non-libtool-libs - dependency_libs= - case $lib in - *.la) func_source "$lib" ;; - esac - - # Collect preopened libtool deplibs, except any this library - # has declared as weak libs - for deplib in $dependency_libs; do - deplib_base=`$ECHO "X$deplib" | $Xsed -e "$basename"` - case " $weak_libs " in - *" $deplib_base "*) ;; - *) deplibs="$deplibs $deplib" ;; - esac - done - done - libs="$dlprefiles" - fi - if test "$pass" = dlopen; then - # Collect dlpreopened libraries - save_deplibs="$deplibs" - deplibs= - fi - - for deplib in $libs; do - lib= - found=no - case $deplib in - -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads) - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - compiler_flags="$compiler_flags $deplib" - if test "$linkmode" = lib ; then - case "$new_inherited_linker_flags " in - *" $deplib "*) ;; - * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; - esac - fi - fi - continue - ;; - -l*) - if test "$linkmode" != lib && test "$linkmode" != prog; then - func_warning "\`-l' is ignored for archives/objects" - continue - fi - func_stripname '-l' '' "$deplib" - name=$func_stripname_result - if test "$linkmode" = lib; then - searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" - else - searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" - fi - for searchdir in $searchdirs; do - for search_ext in .la $std_shrext .so .a; do - # Search the libtool library - lib="$searchdir/lib${name}${search_ext}" - if test -f "$lib"; then - if test "$search_ext" = ".la"; then - found=yes - else - found=no - fi - break 2 - fi - done - done - if test "$found" != yes; then - # deplib doesn't seem to be a libtool library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - else # deplib is a libtool library - # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, - # We need to do some special things here, and not later. - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - case " $predeps $postdeps " in - *" $deplib "*) - if func_lalib_p "$lib"; then - library_names= - old_library= - func_source "$lib" - for l in $old_library $library_names; do - ll="$l" - done - if test "X$ll" = "X$old_library" ; then # only static version available - found=no - func_dirname "$lib" "" "." - ladir="$func_dirname_result" - lib=$ladir/$old_library - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" - fi - continue - fi - fi - ;; - *) ;; - esac - fi - fi - ;; # -l - *.ltframework) - if test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - deplibs="$deplib $deplibs" - if test "$linkmode" = lib ; then - case "$new_inherited_linker_flags " in - *" $deplib "*) ;; - * ) new_inherited_linker_flags="$new_inherited_linker_flags $deplib" ;; - esac - fi - fi - continue - ;; - -L*) - case $linkmode in - lib) - deplibs="$deplib $deplibs" - test "$pass" = conv && continue - newdependency_libs="$deplib $newdependency_libs" - func_stripname '-L' '' "$deplib" - newlib_search_path="$newlib_search_path $func_stripname_result" - ;; - prog) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - if test "$pass" = scan; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - func_stripname '-L' '' "$deplib" - newlib_search_path="$newlib_search_path $func_stripname_result" - ;; - *) - func_warning "\`-L' is ignored for archives/objects" - ;; - esac # linkmode - continue - ;; # -L - -R*) - if test "$pass" = link; then - func_stripname '-R' '' "$deplib" - dir=$func_stripname_result - # Make sure the xrpath contains only unique directories. - case "$xrpath " in - *" $dir "*) ;; - *) xrpath="$xrpath $dir" ;; - esac - fi - deplibs="$deplib $deplibs" - continue - ;; - *.la) lib="$deplib" ;; - *.$libext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - continue - fi - case $linkmode in - lib) - # Linking convenience modules into shared libraries is allowed, - # but linking other static libraries is non-portable. - case " $dlpreconveniencelibs " in - *" $deplib "*) ;; - *) - valid_a_lib=no - case $deplibs_check_method in - match_pattern*) - set dummy $deplibs_check_method; shift - match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` - if eval "\$ECHO \"X$deplib\"" 2>/dev/null | $Xsed -e 10q \ - | $EGREP "$match_pattern_regex" > /dev/null; then - valid_a_lib=yes - fi - ;; - pass_all) - valid_a_lib=yes - ;; - esac - if test "$valid_a_lib" != yes; then - $ECHO - $ECHO "*** Warning: Trying to link with static lib archive $deplib." - $ECHO "*** I have the capability to make that library automatically link in when" - $ECHO "*** you link to this library. But I can only do this if you have a" - $ECHO "*** shared version of the library, which you do not appear to have" - $ECHO "*** because the file extensions .$libext of this argument makes me believe" - $ECHO "*** that it is just a static archive that I should not use here." - else - $ECHO - $ECHO "*** Warning: Linking the shared library $output against the" - $ECHO "*** static library $deplib is not portable!" - deplibs="$deplib $deplibs" - fi - ;; - esac - continue - ;; - prog) - if test "$pass" != link; then - deplibs="$deplib $deplibs" - else - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - fi - continue - ;; - esac # linkmode - ;; # *.$libext - *.lo | *.$objext) - if test "$pass" = conv; then - deplibs="$deplib $deplibs" - elif test "$linkmode" = prog; then - if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then - # If there is no dlopen support or we're linking statically, - # we need to preload. - newdlprefiles="$newdlprefiles $deplib" - compile_deplibs="$deplib $compile_deplibs" - finalize_deplibs="$deplib $finalize_deplibs" - else - newdlfiles="$newdlfiles $deplib" - fi - fi - continue - ;; - %DEPLIBS%) - alldeplibs=yes - continue - ;; - esac # case $deplib - - if test "$found" = yes || test -f "$lib"; then : - else - func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" - fi - - # Check to see that this really is a libtool archive. - func_lalib_unsafe_p "$lib" \ - || func_fatal_error "\`$lib' is not a valid libtool archive" - - func_dirname "$lib" "" "." - ladir="$func_dirname_result" - - dlname= - dlopen= - dlpreopen= - libdir= - library_names= - old_library= - inherited_linker_flags= - # If the library was installed with an old release of libtool, - # it will not redefine variables installed, or shouldnotlink - installed=yes - shouldnotlink=no - avoidtemprpath= - - - # Read the .la file - func_source "$lib" - - # Convert "-framework foo" to "foo.ltframework" - if test -n "$inherited_linker_flags"; then - tmp_inherited_linker_flags=`$ECHO "X$inherited_linker_flags" | $Xsed -e 's/-framework \([^ $]*\)/\1.ltframework/g'` - for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do - case " $new_inherited_linker_flags " in - *" $tmp_inherited_linker_flag "*) ;; - *) new_inherited_linker_flags="$new_inherited_linker_flags $tmp_inherited_linker_flag";; - esac - done - fi - dependency_libs=`$ECHO "X $dependency_libs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - if test "$linkmode,$pass" = "lib,link" || - test "$linkmode,$pass" = "prog,scan" || - { test "$linkmode" != prog && test "$linkmode" != lib; }; then - test -n "$dlopen" && dlfiles="$dlfiles $dlopen" - test -n "$dlpreopen" && dlprefiles="$dlprefiles $dlpreopen" - fi - - if test "$pass" = conv; then - # Only check for convenience libraries - deplibs="$lib $deplibs" - if test -z "$libdir"; then - if test -z "$old_library"; then - func_fatal_error "cannot find name of link library for \`$lib'" - fi - # It is a libtool convenience library, so add in its objects. - convenience="$convenience $ladir/$objdir/$old_library" - old_convenience="$old_convenience $ladir/$objdir/$old_library" - elif test "$linkmode" != prog && test "$linkmode" != lib; then - func_fatal_error "\`$lib' is not a convenience library" - fi - tmp_libs= - for deplib in $dependency_libs; do - deplibs="$deplib $deplibs" - if $opt_duplicate_deps ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done - continue - fi # $pass = conv - - - # Get the name of the library we link against. - linklib= - for l in $old_library $library_names; do - linklib="$l" - done - if test -z "$linklib"; then - func_fatal_error "cannot find name of link library for \`$lib'" - fi - - # This library was specified with -dlopen. - if test "$pass" = dlopen; then - if test -z "$libdir"; then - func_fatal_error "cannot -dlopen a convenience library: \`$lib'" - fi - if test -z "$dlname" || - test "$dlopen_support" != yes || - test "$build_libtool_libs" = no; then - # If there is no dlname, no dlopen support or we're linking - # statically, we need to preload. We also need to preload any - # dependent libraries so libltdl's deplib preloader doesn't - # bomb out in the load deplibs phase. - dlprefiles="$dlprefiles $lib $dependency_libs" - else - newdlfiles="$newdlfiles $lib" - fi - continue - fi # $pass = dlopen - - # We need an absolute path. - case $ladir in - [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; - *) - abs_ladir=`cd "$ladir" && pwd` - if test -z "$abs_ladir"; then - func_warning "cannot determine absolute directory name of \`$ladir'" - func_warning "passing it literally to the linker, although it might fail" - abs_ladir="$ladir" - fi - ;; - esac - func_basename "$lib" - laname="$func_basename_result" - - # Find the relevant object directory and library name. - if test "X$installed" = Xyes; then - if test ! -f "$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then - func_warning "library \`$lib' was moved." - dir="$ladir" - absdir="$abs_ladir" - libdir="$abs_ladir" - else - dir="$libdir" - absdir="$libdir" - fi - test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes - else - if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then - dir="$ladir" - absdir="$abs_ladir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - else - dir="$ladir/$objdir" - absdir="$abs_ladir/$objdir" - # Remove this search path later - notinst_path="$notinst_path $abs_ladir" - fi - fi # $installed = yes - func_stripname 'lib' '.la' "$laname" - name=$func_stripname_result - - # This library was specified with -dlpreopen. - if test "$pass" = dlpreopen; then - if test -z "$libdir" && test "$linkmode" = prog; then - func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" - fi - # Prefer using a static library (so that no silly _DYNAMIC symbols - # are required to link). - if test -n "$old_library"; then - newdlprefiles="$newdlprefiles $dir/$old_library" - # Keep a list of preopened convenience libraries to check - # that they are being used correctly in the link pass. - test -z "$libdir" && \ - dlpreconveniencelibs="$dlpreconveniencelibs $dir/$old_library" - # Otherwise, use the dlname, so that lt_dlopen finds it. - elif test -n "$dlname"; then - newdlprefiles="$newdlprefiles $dir/$dlname" - else - newdlprefiles="$newdlprefiles $dir/$linklib" - fi - fi # $pass = dlpreopen - - if test -z "$libdir"; then - # Link the convenience library - if test "$linkmode" = lib; then - deplibs="$dir/$old_library $deplibs" - elif test "$linkmode,$pass" = "prog,link"; then - compile_deplibs="$dir/$old_library $compile_deplibs" - finalize_deplibs="$dir/$old_library $finalize_deplibs" - else - deplibs="$lib $deplibs" # used for prog,scan pass - fi - continue - fi - - - if test "$linkmode" = prog && test "$pass" != link; then - newlib_search_path="$newlib_search_path $ladir" - deplibs="$lib $deplibs" - - linkalldeplibs=no - if test "$link_all_deplibs" != no || test -z "$library_names" || - test "$build_libtool_libs" = no; then - linkalldeplibs=yes - fi - - tmp_libs= - for deplib in $dependency_libs; do - case $deplib in - -L*) func_stripname '-L' '' "$deplib" - newlib_search_path="$newlib_search_path $func_stripname_result" - ;; - esac - # Need to link against all dependency_libs? - if test "$linkalldeplibs" = yes; then - deplibs="$deplib $deplibs" - else - # Need to hardcode shared library paths - # or/and link against static libraries - newdependency_libs="$deplib $newdependency_libs" - fi - if $opt_duplicate_deps ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done # for deplib - continue - fi # $linkmode = prog... - - if test "$linkmode,$pass" = "prog,link"; then - if test -n "$library_names" && - { { test "$prefer_static_libs" = no || - test "$prefer_static_libs,$installed" = "built,yes"; } || - test -z "$old_library"; }; then - # We need to hardcode the library path - if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then - # Make sure the rpath contains only unique directories. - case "$temp_rpath:" in - *"$absdir:"*) ;; - *) temp_rpath="$temp_rpath$absdir:" ;; - esac - fi - - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi # $linkmode,$pass = prog,link... - - if test "$alldeplibs" = yes && - { test "$deplibs_check_method" = pass_all || - { test "$build_libtool_libs" = yes && - test -n "$library_names"; }; }; then - # We only need to search for static libraries - continue - fi - fi - - link_static=no # Whether the deplib will be linked statically - use_static_libs=$prefer_static_libs - if test "$use_static_libs" = built && test "$installed" = yes; then - use_static_libs=no - fi - if test -n "$library_names" && - { test "$use_static_libs" = no || test -z "$old_library"; }; then - case $host in - *cygwin* | *mingw*) - # No point in relinking DLLs because paths are not encoded - notinst_deplibs="$notinst_deplibs $lib" - need_relink=no - ;; - *) - if test "$installed" = no; then - notinst_deplibs="$notinst_deplibs $lib" - need_relink=yes - fi - ;; - esac - # This is a shared library - - # Warn about portability, can't link against -module's on some - # systems (darwin). Don't bleat about dlopened modules though! - dlopenmodule="" - for dlpremoduletest in $dlprefiles; do - if test "X$dlpremoduletest" = "X$lib"; then - dlopenmodule="$dlpremoduletest" - break - fi - done - if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then - $ECHO - if test "$linkmode" = prog; then - $ECHO "*** Warning: Linking the executable $output against the loadable module" - else - $ECHO "*** Warning: Linking the shared library $output against the loadable module" - fi - $ECHO "*** $linklib is not portable!" - fi - if test "$linkmode" = lib && - test "$hardcode_into_libs" = yes; then - # Hardcode the library path. - # Skip directories that are in the system default run-time - # search path. - case " $sys_lib_dlsearch_path " in - *" $absdir "*) ;; - *) - case "$compile_rpath " in - *" $absdir "*) ;; - *) compile_rpath="$compile_rpath $absdir" - esac - ;; - esac - case " $sys_lib_dlsearch_path " in - *" $libdir "*) ;; - *) - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" - esac - ;; - esac - fi - - if test -n "$old_archive_from_expsyms_cmds"; then - # figure out the soname - set dummy $library_names - shift - realname="$1" - shift - libname=`eval "\\$ECHO \"$libname_spec\""` - # use dlname if we got it. it's perfectly good, no? - if test -n "$dlname"; then - soname="$dlname" - elif test -n "$soname_spec"; then - # bleh windows - case $host in - *cygwin* | mingw*) - func_arith $current - $age - major=$func_arith_result - versuffix="-$major" - ;; - esac - eval soname=\"$soname_spec\" - else - soname="$realname" - fi - - # Make a new name for the extract_expsyms_cmds to use - soroot="$soname" - func_basename "$soroot" - soname="$func_basename_result" - func_stripname 'lib' '.dll' "$soname" - newlib=libimp-$func_stripname_result.a - - # If the library has no export list, then create one now - if test -f "$output_objdir/$soname-def"; then : - else - func_verbose "extracting exported symbol list from \`$soname'" - func_execute_cmds "$extract_expsyms_cmds" 'exit $?' - fi - - # Create $newlib - if test -f "$output_objdir/$newlib"; then :; else - func_verbose "generating import library for \`$soname'" - func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' - fi - # make sure the library variables are pointing to the new library - dir=$output_objdir - linklib=$newlib - fi # test -n "$old_archive_from_expsyms_cmds" - - if test "$linkmode" = prog || test "$mode" != relink; then - add_shlibpath= - add_dir= - add= - lib_linked=yes - case $hardcode_action in - immediate | unsupported) - if test "$hardcode_direct" = no; then - add="$dir/$linklib" - case $host in - *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; - *-*-sysv4*uw2*) add_dir="-L$dir" ;; - *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ - *-*-unixware7*) add_dir="-L$dir" ;; - *-*-darwin* ) - # if the lib is a (non-dlopened) module then we can not - # link against it, someone is ignoring the earlier warnings - if /usr/bin/file -L $add 2> /dev/null | - $GREP ": [^:]* bundle" >/dev/null ; then - if test "X$dlopenmodule" != "X$lib"; then - $ECHO "*** Warning: lib $linklib is a module, not a shared library" - if test -z "$old_library" ; then - $ECHO - $ECHO "*** And there doesn't seem to be a static archive available" - $ECHO "*** The link will probably fail, sorry" - else - add="$dir/$old_library" - fi - elif test -n "$old_library"; then - add="$dir/$old_library" - fi - fi - esac - elif test "$hardcode_minus_L" = no; then - case $host in - *-*-sunos*) add_shlibpath="$dir" ;; - esac - add_dir="-L$dir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = no; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - relink) - if test "$hardcode_direct" = yes && - test "$hardcode_direct_absolute" = no; then - add="$dir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$dir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - add_shlibpath="$dir" - add="-l$name" - else - lib_linked=no - fi - ;; - *) lib_linked=no ;; - esac - - if test "$lib_linked" != yes; then - func_fatal_configuration "unsupported hardcode properties" - fi - - if test -n "$add_shlibpath"; then - case :$compile_shlibpath: in - *":$add_shlibpath:"*) ;; - *) compile_shlibpath="$compile_shlibpath$add_shlibpath:" ;; - esac - fi - if test "$linkmode" = prog; then - test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" - test -n "$add" && compile_deplibs="$add $compile_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - if test "$hardcode_direct" != yes && - test "$hardcode_minus_L" != yes && - test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - fi - fi - fi - - if test "$linkmode" = prog || test "$mode" = relink; then - add_shlibpath= - add_dir= - add= - # Finalize command for both is simple: just hardcode it. - if test "$hardcode_direct" = yes && - test "$hardcode_direct_absolute" = no; then - add="$libdir/$linklib" - elif test "$hardcode_minus_L" = yes; then - add_dir="-L$libdir" - add="-l$name" - elif test "$hardcode_shlibpath_var" = yes; then - case :$finalize_shlibpath: in - *":$libdir:"*) ;; - *) finalize_shlibpath="$finalize_shlibpath$libdir:" ;; - esac - add="-l$name" - elif test "$hardcode_automatic" = yes; then - if test -n "$inst_prefix_dir" && - test -f "$inst_prefix_dir$libdir/$linklib" ; then - add="$inst_prefix_dir$libdir/$linklib" - else - add="$libdir/$linklib" - fi - else - # We cannot seem to hardcode it, guess we'll fake it. - add_dir="-L$libdir" - # Try looking first in the location we're being installed to. - if test -n "$inst_prefix_dir"; then - case $libdir in - [\\/]*) - add_dir="$add_dir -L$inst_prefix_dir$libdir" - ;; - esac - fi - add="-l$name" - fi - - if test "$linkmode" = prog; then - test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" - test -n "$add" && finalize_deplibs="$add $finalize_deplibs" - else - test -n "$add_dir" && deplibs="$add_dir $deplibs" - test -n "$add" && deplibs="$add $deplibs" - fi - fi - elif test "$linkmode" = prog; then - # Here we assume that one of hardcode_direct or hardcode_minus_L - # is not unsupported. This is valid on all known static and - # shared platforms. - if test "$hardcode_direct" != unsupported; then - test -n "$old_library" && linklib="$old_library" - compile_deplibs="$dir/$linklib $compile_deplibs" - finalize_deplibs="$dir/$linklib $finalize_deplibs" - else - compile_deplibs="-l$name -L$dir $compile_deplibs" - finalize_deplibs="-l$name -L$dir $finalize_deplibs" - fi - elif test "$build_libtool_libs" = yes; then - # Not a shared library - if test "$deplibs_check_method" != pass_all; then - # We're trying link a shared library against a static one - # but the system doesn't support it. - - # Just print a warning and add the library to dependency_libs so - # that the program can be linked against the static library. - $ECHO - $ECHO "*** Warning: This system can not link to static lib archive $lib." - $ECHO "*** I have the capability to make that library automatically link in when" - $ECHO "*** you link to this library. But I can only do this if you have a" - $ECHO "*** shared version of the library, which you do not appear to have." - if test "$module" = yes; then - $ECHO "*** But as you try to build a module library, libtool will still create " - $ECHO "*** a static module, that should work as long as the dlopening application" - $ECHO "*** is linked with the -dlopen flag to resolve symbols at runtime." - if test -z "$global_symbol_pipe"; then - $ECHO - $ECHO "*** However, this would only work if libtool was able to extract symbol" - $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" - $ECHO "*** not find such a program. So, this module is probably useless." - $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." - fi - if test "$build_old_libs" = no; then - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - fi - else - deplibs="$dir/$old_library $deplibs" - link_static=yes - fi - fi # link shared/static library? - - if test "$linkmode" = lib; then - if test -n "$dependency_libs" && - { test "$hardcode_into_libs" != yes || - test "$build_old_libs" = yes || - test "$link_static" = yes; }; then - # Extract -R from dependency_libs - temp_deplibs= - for libdir in $dependency_libs; do - case $libdir in - -R*) func_stripname '-R' '' "$libdir" - temp_xrpath=$func_stripname_result - case " $xrpath " in - *" $temp_xrpath "*) ;; - *) xrpath="$xrpath $temp_xrpath";; - esac;; - *) temp_deplibs="$temp_deplibs $libdir";; - esac - done - dependency_libs="$temp_deplibs" - fi - - newlib_search_path="$newlib_search_path $absdir" - # Link against this library - test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" - # ... and its dependency_libs - tmp_libs= - for deplib in $dependency_libs; do - newdependency_libs="$deplib $newdependency_libs" - if $opt_duplicate_deps ; then - case "$tmp_libs " in - *" $deplib "*) specialdeplibs="$specialdeplibs $deplib" ;; - esac - fi - tmp_libs="$tmp_libs $deplib" - done - - if test "$link_all_deplibs" != no; then - # Add the search paths of all dependency libraries - for deplib in $dependency_libs; do - case $deplib in - -L*) path="$deplib" ;; - *.la) - func_dirname "$deplib" "" "." - dir="$func_dirname_result" - # We need an absolute path. - case $dir in - [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; - *) - absdir=`cd "$dir" && pwd` - if test -z "$absdir"; then - func_warning "cannot determine absolute directory name of \`$dir'" - absdir="$dir" - fi - ;; - esac - if $GREP "^installed=no" $deplib > /dev/null; then - case $host in - *-*-darwin*) - depdepl= - eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` - if test -n "$deplibrary_names" ; then - for tmp in $deplibrary_names ; do - depdepl=$tmp - done - if test -f "$absdir/$objdir/$depdepl" ; then - depdepl="$absdir/$objdir/$depdepl" - darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` - if test -z "$darwin_install_name"; then - darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` - fi - compiler_flags="$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" - linker_flags="$linker_flags -dylib_file ${darwin_install_name}:${depdepl}" - path= - fi - fi - ;; - *) - path="-L$absdir/$objdir" - ;; - esac - else - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` - test -z "$libdir" && \ - func_fatal_error "\`$deplib' is not a valid libtool archive" - test "$absdir" != "$libdir" && \ - func_warning "\`$deplib' seems to be moved" - - path="-L$absdir" - fi - ;; - esac - case " $deplibs " in - *" $path "*) ;; - *) deplibs="$path $deplibs" ;; - esac - done - fi # link_all_deplibs != no - fi # linkmode = lib - done # for deplib in $libs - if test "$pass" = link; then - if test "$linkmode" = "prog"; then - compile_deplibs="$new_inherited_linker_flags $compile_deplibs" - finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" - else - compiler_flags="$compiler_flags "`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - fi - fi - dependency_libs="$newdependency_libs" - if test "$pass" = dlpreopen; then - # Link the dlpreopened libraries before other libraries - for deplib in $save_deplibs; do - deplibs="$deplib $deplibs" - done - fi - if test "$pass" != dlopen; then - if test "$pass" != conv; then - # Make sure lib_search_path contains only unique directories. - lib_search_path= - for dir in $newlib_search_path; do - case "$lib_search_path " in - *" $dir "*) ;; - *) lib_search_path="$lib_search_path $dir" ;; - esac - done - newlib_search_path= - fi - - if test "$linkmode,$pass" != "prog,link"; then - vars="deplibs" - else - vars="compile_deplibs finalize_deplibs" - fi - for var in $vars dependency_libs; do - # Add libraries to $var in reverse order - eval tmp_libs=\"\$$var\" - new_libs= - for deplib in $tmp_libs; do - # FIXME: Pedantically, this is the right thing to do, so - # that some nasty dependency loop isn't accidentally - # broken: - #new_libs="$deplib $new_libs" - # Pragmatically, this seems to cause very few problems in - # practice: - case $deplib in - -L*) new_libs="$deplib $new_libs" ;; - -R*) ;; - *) - # And here is the reason: when a library appears more - # than once as an explicit dependence of a library, or - # is implicitly linked in more than once by the - # compiler, it is considered special, and multiple - # occurrences thereof are not removed. Compare this - # with having the same library being listed as a - # dependency of multiple other libraries: in this case, - # we know (pedantically, we assume) the library does not - # need to be listed more than once, so we keep only the - # last copy. This is not always right, but it is rare - # enough that we require users that really mean to play - # such unportable linking tricks to link the library - # using -Wl,-lname, so that libtool does not consider it - # for duplicate removal. - case " $specialdeplibs " in - *" $deplib "*) new_libs="$deplib $new_libs" ;; - *) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$deplib $new_libs" ;; - esac - ;; - esac - ;; - esac - done - tmp_libs= - for deplib in $new_libs; do - case $deplib in - -L*) - case " $tmp_libs " in - *" $deplib "*) ;; - *) tmp_libs="$tmp_libs $deplib" ;; - esac - ;; - *) tmp_libs="$tmp_libs $deplib" ;; - esac - done - eval $var=\"$tmp_libs\" - done # for var - fi - # Last step: remove runtime libs from dependency_libs - # (they stay in deplibs) - tmp_libs= - for i in $dependency_libs ; do - case " $predeps $postdeps $compiler_lib_search_path " in - *" $i "*) - i="" - ;; - esac - if test -n "$i" ; then - tmp_libs="$tmp_libs $i" - fi - done - dependency_libs=$tmp_libs - done # for pass - if test "$linkmode" = prog; then - dlfiles="$newdlfiles" - fi - if test "$linkmode" = prog || test "$linkmode" = lib; then - dlprefiles="$newdlprefiles" - fi - - case $linkmode in - oldlib) - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - func_warning "\`-dlopen' is ignored for archives" - fi - - case " $deplibs" in - *\ -l* | *\ -L*) - func_warning "\`-l' and \`-L' are ignored for archives" ;; - esac - - test -n "$rpath" && \ - func_warning "\`-rpath' is ignored for archives" - - test -n "$xrpath" && \ - func_warning "\`-R' is ignored for archives" - - test -n "$vinfo" && \ - func_warning "\`-version-info/-version-number' is ignored for archives" - - test -n "$release" && \ - func_warning "\`-release' is ignored for archives" - - test -n "$export_symbols$export_symbols_regex" && \ - func_warning "\`-export-symbols' is ignored for archives" - - # Now set the variables for building old libraries. - build_libtool_libs=no - oldlibs="$output" - objs="$objs$old_deplibs" - ;; - - lib) - # Make sure we only generate libraries of the form `libNAME.la'. - case $outputname in - lib*) - func_stripname 'lib' '.la' "$outputname" - name=$func_stripname_result - eval shared_ext=\"$shrext_cmds\" - eval libname=\"$libname_spec\" - ;; - *) - test "$module" = no && \ - func_fatal_help "libtool library \`$output' must begin with \`lib'" - - if test "$need_lib_prefix" != no; then - # Add the "lib" prefix for modules if required - func_stripname '' '.la' "$outputname" - name=$func_stripname_result - eval shared_ext=\"$shrext_cmds\" - eval libname=\"$libname_spec\" - else - func_stripname '' '.la' "$outputname" - libname=$func_stripname_result - fi - ;; - esac - - if test -n "$objs"; then - if test "$deplibs_check_method" != pass_all; then - func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" - else - $ECHO - $ECHO "*** Warning: Linking the shared library $output against the non-libtool" - $ECHO "*** objects $objs is not portable!" - libobjs="$libobjs $objs" - fi - fi - - test "$dlself" != no && \ - func_warning "\`-dlopen self' is ignored for libtool libraries" - - set dummy $rpath - shift - test "$#" -gt 1 && \ - func_warning "ignoring multiple \`-rpath's for a libtool library" - - install_libdir="$1" - - oldlibs= - if test -z "$rpath"; then - if test "$build_libtool_libs" = yes; then - # Building a libtool convenience library. - # Some compilers have problems with a `.al' extension so - # convenience libraries should have the same extension an - # archive normally would. - oldlibs="$output_objdir/$libname.$libext $oldlibs" - build_libtool_libs=convenience - build_old_libs=yes - fi - - test -n "$vinfo" && \ - func_warning "\`-version-info/-version-number' is ignored for convenience libraries" - - test -n "$release" && \ - func_warning "\`-release' is ignored for convenience libraries" - else - - # Parse the version information argument. - save_ifs="$IFS"; IFS=':' - set dummy $vinfo 0 0 0 - shift - IFS="$save_ifs" - - test -n "$7" && \ - func_fatal_help "too many parameters to \`-version-info'" - - # convert absolute version numbers to libtool ages - # this retains compatibility with .la files and attempts - # to make the code below a bit more comprehensible - - case $vinfo_number in - yes) - number_major="$1" - number_minor="$2" - number_revision="$3" - # - # There are really only two kinds -- those that - # use the current revision as the major version - # and those that subtract age and use age as - # a minor version. But, then there is irix - # which has an extra 1 added just for fun - # - case $version_type in - darwin|linux|osf|windows|none) - func_arith $number_major + $number_minor - current=$func_arith_result - age="$number_minor" - revision="$number_revision" - ;; - freebsd-aout|freebsd-elf|sunos) - current="$number_major" - revision="$number_minor" - age="0" - ;; - irix|nonstopux) - func_arith $number_major + $number_minor - current=$func_arith_result - age="$number_minor" - revision="$number_minor" - lt_irix_increment=no - ;; - esac - ;; - no) - current="$1" - revision="$2" - age="$3" - ;; - esac - - # Check that each of the things are valid numbers. - case $current in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - func_error "CURRENT \`$current' must be a nonnegative integer" - func_fatal_error "\`$vinfo' is not valid version information" - ;; - esac - - case $revision in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - func_error "REVISION \`$revision' must be a nonnegative integer" - func_fatal_error "\`$vinfo' is not valid version information" - ;; - esac - - case $age in - 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; - *) - func_error "AGE \`$age' must be a nonnegative integer" - func_fatal_error "\`$vinfo' is not valid version information" - ;; - esac - - if test "$age" -gt "$current"; then - func_error "AGE \`$age' is greater than the current interface number \`$current'" - func_fatal_error "\`$vinfo' is not valid version information" - fi - - # Calculate the version variables. - major= - versuffix= - verstring= - case $version_type in - none) ;; - - darwin) - # Like Linux, but with the current version available in - # verstring for coding it into the library header - func_arith $current - $age - major=.$func_arith_result - versuffix="$major.$age.$revision" - # Darwin ld doesn't like 0 for these options... - func_arith $current + 1 - minor_current=$func_arith_result - xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" - verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" - ;; - - freebsd-aout) - major=".$current" - versuffix=".$current.$revision"; - ;; - - freebsd-elf) - major=".$current" - versuffix=".$current" - ;; - - irix | nonstopux) - if test "X$lt_irix_increment" = "Xno"; then - func_arith $current - $age - else - func_arith $current - $age + 1 - fi - major=$func_arith_result - - case $version_type in - nonstopux) verstring_prefix=nonstopux ;; - *) verstring_prefix=sgi ;; - esac - verstring="$verstring_prefix$major.$revision" - - # Add in all the interfaces that we are compatible with. - loop=$revision - while test "$loop" -ne 0; do - func_arith $revision - $loop - iface=$func_arith_result - func_arith $loop - 1 - loop=$func_arith_result - verstring="$verstring_prefix$major.$iface:$verstring" - done - - # Before this point, $major must not contain `.'. - major=.$major - versuffix="$major.$revision" - ;; - - linux) - func_arith $current - $age - major=.$func_arith_result - versuffix="$major.$age.$revision" - ;; - - osf) - func_arith $current - $age - major=.$func_arith_result - versuffix=".$current.$age.$revision" - verstring="$current.$age.$revision" - - # Add in all the interfaces that we are compatible with. - loop=$age - while test "$loop" -ne 0; do - func_arith $current - $loop - iface=$func_arith_result - func_arith $loop - 1 - loop=$func_arith_result - verstring="$verstring:${iface}.0" - done - - # Make executables depend on our current version. - verstring="$verstring:${current}.0" - ;; - - qnx) - major=".$current" - versuffix=".$current" - ;; - - sunos) - major=".$current" - versuffix=".$current.$revision" - ;; - - windows) - # Use '-' rather than '.', since we only want one - # extension on DOS 8.3 filesystems. - func_arith $current - $age - major=$func_arith_result - versuffix="-$major" - ;; - - *) - func_fatal_configuration "unknown library version type \`$version_type'" - ;; - esac - - # Clear the version info if we defaulted, and they specified a release. - if test -z "$vinfo" && test -n "$release"; then - major= - case $version_type in - darwin) - # we can't check for "0.0" in archive_cmds due to quoting - # problems, so we reset it completely - verstring= - ;; - *) - verstring="0.0" - ;; - esac - if test "$need_version" = no; then - versuffix= - else - versuffix=".0.0" - fi - fi - - # Remove version info from name if versioning should be avoided - if test "$avoid_version" = yes && test "$need_version" = no; then - major= - versuffix= - verstring="" - fi - - # Check to see if the archive will have undefined symbols. - if test "$allow_undefined" = yes; then - if test "$allow_undefined_flag" = unsupported; then - func_warning "undefined symbols not allowed in $host shared libraries" - build_libtool_libs=no - build_old_libs=yes - fi - else - # Don't allow undefined symbols. - allow_undefined_flag="$no_undefined_flag" - fi - - fi - - func_generate_dlsyms "$libname" "$libname" "yes" - libobjs="$libobjs $symfileobj" - test "X$libobjs" = "X " && libobjs= - - if test "$mode" != relink; then - # Remove our outputs, but don't remove object files since they - # may have been created when compiling PIC objects. - removelist= - tempremovelist=`$ECHO "$output_objdir/*"` - for p in $tempremovelist; do - case $p in - *.$objext) - ;; - $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) - if test "X$precious_files_regex" != "X"; then - if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 - then - continue - fi - fi - removelist="$removelist $p" - ;; - *) ;; - esac - done - test -n "$removelist" && \ - func_show_eval "${RM}r \$removelist" - fi - - # Now set the variables for building old libraries. - if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then - oldlibs="$oldlibs $output_objdir/$libname.$libext" - - # Transform .lo files to .o files. - oldobjs="$objs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}'$/d' -e "$lo2o" | $NL2SP` - fi - - # Eliminate all temporary directories. - #for path in $notinst_path; do - # lib_search_path=`$ECHO "X$lib_search_path " | $Xsed -e "s% $path % %g"` - # deplibs=`$ECHO "X$deplibs " | $Xsed -e "s% -L$path % %g"` - # dependency_libs=`$ECHO "X$dependency_libs " | $Xsed -e "s% -L$path % %g"` - #done - - if test -n "$xrpath"; then - # If the user specified any rpath flags, then add them. - temp_xrpath= - for libdir in $xrpath; do - temp_xrpath="$temp_xrpath -R$libdir" - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" ;; - esac - done - if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then - dependency_libs="$temp_xrpath $dependency_libs" - fi - fi - - # Make sure dlfiles contains only unique files that won't be dlpreopened - old_dlfiles="$dlfiles" - dlfiles= - for lib in $old_dlfiles; do - case " $dlprefiles $dlfiles " in - *" $lib "*) ;; - *) dlfiles="$dlfiles $lib" ;; - esac - done - - # Make sure dlprefiles contains only unique files - old_dlprefiles="$dlprefiles" - dlprefiles= - for lib in $old_dlprefiles; do - case "$dlprefiles " in - *" $lib "*) ;; - *) dlprefiles="$dlprefiles $lib" ;; - esac - done - - if test "$build_libtool_libs" = yes; then - if test -n "$rpath"; then - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos*) - # these systems don't actually have a c library (as such)! - ;; - *-*-rhapsody* | *-*-darwin1.[012]) - # Rhapsody C library is in the System framework - deplibs="$deplibs System.ltframework" - ;; - *-*-netbsd*) - # Don't link with libc until the a.out ld.so is fixed. - ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) - # Do not include libc due to us having libc/libc_r. - ;; - *-*-sco3.2v5* | *-*-sco5v6*) - # Causes problems with __ctype - ;; - *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) - # Compiler inserts libc in the correct place for threads to work - ;; - *) - # Add libc to deplibs on all other systems if necessary. - if test "$build_libtool_need_lc" = "yes"; then - deplibs="$deplibs -lc" - fi - ;; - esac - fi - - # Transform deplibs into only deplibs that can be linked in shared. - name_save=$name - libname_save=$libname - release_save=$release - versuffix_save=$versuffix - major_save=$major - # I'm not sure if I'm treating the release correctly. I think - # release should show up in the -l (ie -lgmp5) so we don't want to - # add it in twice. Is that correct? - release="" - versuffix="" - major="" - newdeplibs= - droppeddeps=no - case $deplibs_check_method in - pass_all) - # Don't check for shared/static. Everything works. - # This might be a little naive. We might want to check - # whether the library exists or not. But this is on - # osf3 & osf4 and I'm not really sure... Just - # implementing what was already the behavior. - newdeplibs=$deplibs - ;; - test_compile) - # This code stresses the "libraries are programs" paradigm to its - # limits. Maybe even breaks it. We compile a program, linking it - # against the deplibs as a proxy for the library. Then we can check - # whether they linked in statically or dynamically with ldd. - $opt_dry_run || $RM conftest.c - cat > conftest.c </dev/null` - for potent_lib in $potential_libs; do - # Follow soft links. - if ls -lLd "$potent_lib" 2>/dev/null | - $GREP " -> " >/dev/null; then - continue - fi - # The statement above tries to avoid entering an - # endless loop below, in case of cyclic links. - # We might still enter an endless loop, since a link - # loop can be closed while we follow links, - # but so what? - potlib="$potent_lib" - while test -h "$potlib" 2>/dev/null; do - potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` - case $potliblink in - [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; - *) potlib=`$ECHO "X$potlib" | $Xsed -e 's,[^/]*$,,'`"$potliblink";; - esac - done - if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | - $SED -e 10q | - $EGREP "$file_magic_regex" > /dev/null; then - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - break 2 - fi - done - done - fi - if test -n "$a_deplib" ; then - droppeddeps=yes - $ECHO - $ECHO "*** Warning: linker path does not have real file for library $a_deplib." - $ECHO "*** I have the capability to make that library automatically link in when" - $ECHO "*** you link to this library. But I can only do this if you have a" - $ECHO "*** shared version of the library, which you do not appear to have" - $ECHO "*** because I did check the linker path looking for a file starting" - if test -z "$potlib" ; then - $ECHO "*** with $libname but no candidates were found. (...for file magic test)" - else - $ECHO "*** with $libname and none of the candidates passed a file format test" - $ECHO "*** using a file magic. Last file checked: $potlib" - fi - fi - ;; - *) - # Add a -L argument. - newdeplibs="$newdeplibs $a_deplib" - ;; - esac - done # Gone through all deplibs. - ;; - match_pattern*) - set dummy $deplibs_check_method; shift - match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` - for a_deplib in $deplibs; do - case $a_deplib in - -l*) - func_stripname -l '' "$a_deplib" - name=$func_stripname_result - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - case " $predeps $postdeps " in - *" $a_deplib "*) - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - ;; - esac - fi - if test -n "$a_deplib" ; then - libname=`eval "\\$ECHO \"$libname_spec\""` - for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do - potential_libs=`ls $i/$libname[.-]* 2>/dev/null` - for potent_lib in $potential_libs; do - potlib="$potent_lib" # see symlink-check above in file_magic test - if eval "\$ECHO \"X$potent_lib\"" 2>/dev/null | $Xsed -e 10q | \ - $EGREP "$match_pattern_regex" > /dev/null; then - newdeplibs="$newdeplibs $a_deplib" - a_deplib="" - break 2 - fi - done - done - fi - if test -n "$a_deplib" ; then - droppeddeps=yes - $ECHO - $ECHO "*** Warning: linker path does not have real file for library $a_deplib." - $ECHO "*** I have the capability to make that library automatically link in when" - $ECHO "*** you link to this library. But I can only do this if you have a" - $ECHO "*** shared version of the library, which you do not appear to have" - $ECHO "*** because I did check the linker path looking for a file starting" - if test -z "$potlib" ; then - $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" - else - $ECHO "*** with $libname and none of the candidates passed a file format test" - $ECHO "*** using a regex pattern. Last file checked: $potlib" - fi - fi - ;; - *) - # Add a -L argument. - newdeplibs="$newdeplibs $a_deplib" - ;; - esac - done # Gone through all deplibs. - ;; - none | unknown | *) - newdeplibs="" - tmp_deplibs=`$ECHO "X $deplibs" | $Xsed \ - -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'` - if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then - for i in $predeps $postdeps ; do - # can't use Xsed below, because $i might contain '/' - tmp_deplibs=`$ECHO "X $tmp_deplibs" | $Xsed -e "s,$i,,"` - done - fi - if $ECHO "X $tmp_deplibs" | $Xsed -e 's/[ ]//g' | - $GREP . >/dev/null; then - $ECHO - if test "X$deplibs_check_method" = "Xnone"; then - $ECHO "*** Warning: inter-library dependencies are not supported in this platform." - else - $ECHO "*** Warning: inter-library dependencies are not known to be supported." - fi - $ECHO "*** All declared inter-library dependencies are being dropped." - droppeddeps=yes - fi - ;; - esac - versuffix=$versuffix_save - major=$major_save - release=$release_save - libname=$libname_save - name=$name_save - - case $host in - *-*-rhapsody* | *-*-darwin1.[012]) - # On Rhapsody replace the C library with the System framework - newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's/ -lc / System.ltframework /'` - ;; - esac - - if test "$droppeddeps" = yes; then - if test "$module" = yes; then - $ECHO - $ECHO "*** Warning: libtool could not satisfy all declared inter-library" - $ECHO "*** dependencies of module $libname. Therefore, libtool will create" - $ECHO "*** a static module, that should work as long as the dlopening" - $ECHO "*** application is linked with the -dlopen flag." - if test -z "$global_symbol_pipe"; then - $ECHO - $ECHO "*** However, this would only work if libtool was able to extract symbol" - $ECHO "*** lists from a program, using \`nm' or equivalent, but libtool could" - $ECHO "*** not find such a program. So, this module is probably useless." - $ECHO "*** \`nm' from GNU binutils and a full rebuild may help." - fi - if test "$build_old_libs" = no; then - oldlibs="$output_objdir/$libname.$libext" - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - else - $ECHO "*** The inter-library dependencies that have been dropped here will be" - $ECHO "*** automatically added whenever a program is linked with this library" - $ECHO "*** or is declared to -dlopen it." - - if test "$allow_undefined" = no; then - $ECHO - $ECHO "*** Since this library must not contain undefined symbols," - $ECHO "*** because either the platform does not support them or" - $ECHO "*** it was explicitly requested with -no-undefined," - $ECHO "*** libtool will only create a static version of it." - if test "$build_old_libs" = no; then - oldlibs="$output_objdir/$libname.$libext" - build_libtool_libs=module - build_old_libs=yes - else - build_libtool_libs=no - fi - fi - fi - fi - # Done checking deplibs! - deplibs=$newdeplibs - fi - # Time to change all our "foo.ltframework" stuff back to "-framework foo" - case $host in - *-*-darwin*) - newdeplibs=`$ECHO "X $newdeplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - new_inherited_linker_flags=`$ECHO "X $new_inherited_linker_flags" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - deplibs=`$ECHO "X $deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - ;; - esac - - # move library search paths that coincide with paths to not yet - # installed libraries to the beginning of the library search list - new_libs= - for path in $notinst_path; do - case " $new_libs " in - *" -L$path/$objdir "*) ;; - *) - case " $deplibs " in - *" -L$path/$objdir "*) - new_libs="$new_libs -L$path/$objdir" ;; - esac - ;; - esac - done - for deplib in $deplibs; do - case $deplib in - -L*) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$new_libs $deplib" ;; - esac - ;; - *) new_libs="$new_libs $deplib" ;; - esac - done - deplibs="$new_libs" - - # All the library-specific variables (install_libdir is set above). - library_names= - old_library= - dlname= - - # Test again, we may have decided not to build it any more - if test "$build_libtool_libs" = yes; then - if test "$hardcode_into_libs" = yes; then - # Hardcode the library paths - hardcode_libdirs= - dep_rpath= - rpath="$finalize_rpath" - test "$mode" != relink && rpath="$compile_rpath$rpath" - for libdir in $rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - dep_rpath="$dep_rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$perm_rpath " in - *" $libdir "*) ;; - *) perm_rpath="$perm_rpath $libdir" ;; - esac - fi - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - if test -n "$hardcode_libdir_flag_spec_ld"; then - eval dep_rpath=\"$hardcode_libdir_flag_spec_ld\" - else - eval dep_rpath=\"$hardcode_libdir_flag_spec\" - fi - fi - if test -n "$runpath_var" && test -n "$perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $perm_rpath; do - rpath="$rpath$dir:" - done - eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" - fi - test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" - fi - - shlibpath="$finalize_shlibpath" - test "$mode" != relink && shlibpath="$compile_shlibpath$shlibpath" - if test -n "$shlibpath"; then - eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" - fi - - # Get the real and link names of the library. - eval shared_ext=\"$shrext_cmds\" - eval library_names=\"$library_names_spec\" - set dummy $library_names - shift - realname="$1" - shift - - if test -n "$soname_spec"; then - eval soname=\"$soname_spec\" - else - soname="$realname" - fi - if test -z "$dlname"; then - dlname=$soname - fi - - lib="$output_objdir/$realname" - linknames= - for link - do - linknames="$linknames $link" - done - - # Use standard objects if they are pic - test -z "$pic_flag" && libobjs=`$ECHO "X$libobjs" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - test "X$libobjs" = "X " && libobjs= - - delfiles= - if test -n "$export_symbols" && test -n "$include_expsyms"; then - $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" - export_symbols="$output_objdir/$libname.uexp" - delfiles="$delfiles $export_symbols" - fi - - orig_export_symbols= - case $host_os in - cygwin* | mingw*) - if test -n "$export_symbols" && test -z "$export_symbols_regex"; then - # exporting using user supplied symfile - if test "x`$SED 1q $export_symbols`" != xEXPORTS; then - # and it's NOT already a .def file. Must figure out - # which of the given symbols are data symbols and tag - # them as such. So, trigger use of export_symbols_cmds. - # export_symbols gets reassigned inside the "prepare - # the list of exported symbols" if statement, so the - # include_expsyms logic still works. - orig_export_symbols="$export_symbols" - export_symbols= - always_export_symbols=yes - fi - fi - ;; - esac - - # Prepare the list of exported symbols - if test -z "$export_symbols"; then - if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then - func_verbose "generating symbol list for \`$libname.la'" - export_symbols="$output_objdir/$libname.exp" - $opt_dry_run || $RM $export_symbols - cmds=$export_symbols_cmds - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - func_len " $cmd" - len=$func_len_result - if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then - func_show_eval "$cmd" 'exit $?' - skipped_export=false - else - # The command line is too long to execute in one step. - func_verbose "using reloadable object file for export list..." - skipped_export=: - # Break out early, otherwise skipped_export may be - # set to false by a later but shorter cmd. - break - fi - done - IFS="$save_ifs" - if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then - func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' - func_show_eval '$MV "${export_symbols}T" "$export_symbols"' - fi - fi - fi - - if test -n "$export_symbols" && test -n "$include_expsyms"; then - tmp_export_symbols="$export_symbols" - test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" - $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' - fi - - if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then - # The given exports_symbols file has to be filtered, so filter it. - func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" - # FIXME: $output_objdir/$libname.filter potentially contains lots of - # 's' commands which not all seds can handle. GNU sed should be fine - # though. Also, the filter scales superlinearly with the number of - # global variables. join(1) would be nice here, but unfortunately - # isn't a blessed tool. - $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter - delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" - export_symbols=$output_objdir/$libname.def - $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols - fi - - tmp_deplibs= - for test_deplib in $deplibs; do - case " $convenience " in - *" $test_deplib "*) ;; - *) - tmp_deplibs="$tmp_deplibs $test_deplib" - ;; - esac - done - deplibs="$tmp_deplibs" - - if test -n "$convenience"; then - if test -n "$whole_archive_flag_spec" && - test "$compiler_needs_object" = yes && - test -z "$libobjs"; then - # extract the archives, so we have objects to list. - # TODO: could optimize this to just extract one archive. - whole_archive_flag_spec= - fi - if test -n "$whole_archive_flag_spec"; then - save_libobjs=$libobjs - eval libobjs=\"\$libobjs $whole_archive_flag_spec\" - test "X$libobjs" = "X " && libobjs= - else - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $convenience - libobjs="$libobjs $func_extract_archives_result" - test "X$libobjs" = "X " && libobjs= - fi - fi - - if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then - eval flag=\"$thread_safe_flag_spec\" - linker_flags="$linker_flags $flag" - fi - - # Make a backup of the uninstalled library when relinking - if test "$mode" = relink; then - $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? - fi - - # Do each of the archive commands. - if test "$module" = yes && test -n "$module_cmds" ; then - if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then - eval test_cmds=\"$module_expsym_cmds\" - cmds=$module_expsym_cmds - else - eval test_cmds=\"$module_cmds\" - cmds=$module_cmds - fi - else - if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then - eval test_cmds=\"$archive_expsym_cmds\" - cmds=$archive_expsym_cmds - else - eval test_cmds=\"$archive_cmds\" - cmds=$archive_cmds - fi - fi - - if test "X$skipped_export" != "X:" && - func_len " $test_cmds" && - len=$func_len_result && - test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then - : - else - # The command line is too long to link in one step, link piecewise - # or, if using GNU ld and skipped_export is not :, use a linker - # script. - - # Save the value of $output and $libobjs because we want to - # use them later. If we have whole_archive_flag_spec, we - # want to use save_libobjs as it was before - # whole_archive_flag_spec was expanded, because we can't - # assume the linker understands whole_archive_flag_spec. - # This may have to be revisited, in case too many - # convenience libraries get linked in and end up exceeding - # the spec. - if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then - save_libobjs=$libobjs - fi - save_output=$output - output_la=`$ECHO "X$output" | $Xsed -e "$basename"` - - # Clear the reloadable object creation command queue and - # initialize k to one. - test_cmds= - concat_cmds= - objlist= - last_robj= - k=1 - - if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then - output=${output_objdir}/${output_la}.lnkscript - func_verbose "creating GNU ld script: $output" - $ECHO 'INPUT (' > $output - for obj in $save_libobjs - do - $ECHO "$obj" >> $output - done - $ECHO ')' >> $output - delfiles="$delfiles $output" - elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then - output=${output_objdir}/${output_la}.lnk - func_verbose "creating linker input file list: $output" - : > $output - set x $save_libobjs - shift - firstobj= - if test "$compiler_needs_object" = yes; then - firstobj="$1 " - shift - fi - for obj - do - $ECHO "$obj" >> $output - done - delfiles="$delfiles $output" - output=$firstobj\"$file_list_spec$output\" - else - if test -n "$save_libobjs"; then - func_verbose "creating reloadable object files..." - output=$output_objdir/$output_la-${k}.$objext - eval test_cmds=\"$reload_cmds\" - func_len " $test_cmds" - len0=$func_len_result - len=$len0 - - # Loop over the list of objects to be linked. - for obj in $save_libobjs - do - func_len " $obj" - func_arith $len + $func_len_result - len=$func_arith_result - if test "X$objlist" = X || - test "$len" -lt "$max_cmd_len"; then - func_append objlist " $obj" - else - # The command $test_cmds is almost too long, add a - # command to the queue. - if test "$k" -eq 1 ; then - # The first file doesn't have a previous command to add. - eval concat_cmds=\"$reload_cmds $objlist $last_robj\" - else - # All subsequent reloadable object files will link in - # the last one created. - eval concat_cmds=\"\$concat_cmds~$reload_cmds $objlist $last_robj~\$RM $last_robj\" - fi - last_robj=$output_objdir/$output_la-${k}.$objext - func_arith $k + 1 - k=$func_arith_result - output=$output_objdir/$output_la-${k}.$objext - objlist=$obj - func_len " $last_robj" - func_arith $len0 + $func_len_result - len=$func_arith_result - fi - done - # Handle the remaining objects by creating one last - # reloadable object file. All subsequent reloadable object - # files will link in the last one created. - test -z "$concat_cmds" || concat_cmds=$concat_cmds~ - eval concat_cmds=\"\${concat_cmds}$reload_cmds $objlist $last_robj\" - if test -n "$last_robj"; then - eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" - fi - delfiles="$delfiles $output" - - else - output= - fi - - if ${skipped_export-false}; then - func_verbose "generating symbol list for \`$libname.la'" - export_symbols="$output_objdir/$libname.exp" - $opt_dry_run || $RM $export_symbols - libobjs=$output - # Append the command to create the export file. - test -z "$concat_cmds" || concat_cmds=$concat_cmds~ - eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" - if test -n "$last_robj"; then - eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" - fi - fi - - test -n "$save_libobjs" && - func_verbose "creating a temporary reloadable object file: $output" - - # Loop through the commands generated above and execute them. - save_ifs="$IFS"; IFS='~' - for cmd in $concat_cmds; do - IFS="$save_ifs" - $opt_silent || { - func_quote_for_expand "$cmd" - eval "func_echo $func_quote_for_expand_result" - } - $opt_dry_run || eval "$cmd" || { - lt_exit=$? - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - ( cd "$output_objdir" && \ - $RM "${realname}T" && \ - $MV "${realname}U" "$realname" ) - fi - - exit $lt_exit - } - done - IFS="$save_ifs" - - if test -n "$export_symbols_regex" && ${skipped_export-false}; then - func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' - func_show_eval '$MV "${export_symbols}T" "$export_symbols"' - fi - fi - - if ${skipped_export-false}; then - if test -n "$export_symbols" && test -n "$include_expsyms"; then - tmp_export_symbols="$export_symbols" - test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" - $opt_dry_run || eval '$ECHO "X$include_expsyms" | $Xsed | $SP2NL >> "$tmp_export_symbols"' - fi - - if test -n "$orig_export_symbols"; then - # The given exports_symbols file has to be filtered, so filter it. - func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" - # FIXME: $output_objdir/$libname.filter potentially contains lots of - # 's' commands which not all seds can handle. GNU sed should be fine - # though. Also, the filter scales superlinearly with the number of - # global variables. join(1) would be nice here, but unfortunately - # isn't a blessed tool. - $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter - delfiles="$delfiles $export_symbols $output_objdir/$libname.filter" - export_symbols=$output_objdir/$libname.def - $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols - fi - fi - - libobjs=$output - # Restore the value of output. - output=$save_output - - if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then - eval libobjs=\"\$libobjs $whole_archive_flag_spec\" - test "X$libobjs" = "X " && libobjs= - fi - # Expand the library linking commands again to reset the - # value of $libobjs for piecewise linking. - - # Do each of the archive commands. - if test "$module" = yes && test -n "$module_cmds" ; then - if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then - cmds=$module_expsym_cmds - else - cmds=$module_cmds - fi - else - if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then - cmds=$archive_expsym_cmds - else - cmds=$archive_cmds - fi - fi - fi - - if test -n "$delfiles"; then - # Append the command to remove temporary files to $cmds. - eval cmds=\"\$cmds~\$RM $delfiles\" - fi - - # Add any objects from preloaded convenience libraries - if test -n "$dlprefiles"; then - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $dlprefiles - libobjs="$libobjs $func_extract_archives_result" - test "X$libobjs" = "X " && libobjs= - fi - - save_ifs="$IFS"; IFS='~' - for cmd in $cmds; do - IFS="$save_ifs" - eval cmd=\"$cmd\" - $opt_silent || { - func_quote_for_expand "$cmd" - eval "func_echo $func_quote_for_expand_result" - } - $opt_dry_run || eval "$cmd" || { - lt_exit=$? - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - ( cd "$output_objdir" && \ - $RM "${realname}T" && \ - $MV "${realname}U" "$realname" ) - fi - - exit $lt_exit - } - done - IFS="$save_ifs" - - # Restore the uninstalled library and exit - if test "$mode" = relink; then - $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? - - if test -n "$convenience"; then - if test -z "$whole_archive_flag_spec"; then - func_show_eval '${RM}r "$gentop"' - fi - fi - - exit $EXIT_SUCCESS - fi - - # Create links to the real library. - for linkname in $linknames; do - if test "$realname" != "$linkname"; then - func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' - fi - done - - # If -module or -export-dynamic was specified, set the dlname. - if test "$module" = yes || test "$export_dynamic" = yes; then - # On all known operating systems, these are identical. - dlname="$soname" - fi - fi - ;; - - obj) - if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then - func_warning "\`-dlopen' is ignored for objects" - fi - - case " $deplibs" in - *\ -l* | *\ -L*) - func_warning "\`-l' and \`-L' are ignored for objects" ;; - esac - - test -n "$rpath" && \ - func_warning "\`-rpath' is ignored for objects" - - test -n "$xrpath" && \ - func_warning "\`-R' is ignored for objects" - - test -n "$vinfo" && \ - func_warning "\`-version-info' is ignored for objects" - - test -n "$release" && \ - func_warning "\`-release' is ignored for objects" - - case $output in - *.lo) - test -n "$objs$old_deplibs" && \ - func_fatal_error "cannot build library object \`$output' from non-libtool objects" - - libobj=$output - func_lo2o "$libobj" - obj=$func_lo2o_result - ;; - *) - libobj= - obj="$output" - ;; - esac - - # Delete the old objects. - $opt_dry_run || $RM $obj $libobj - - # Objects from convenience libraries. This assumes - # single-version convenience libraries. Whenever we create - # different ones for PIC/non-PIC, this we'll have to duplicate - # the extraction. - reload_conv_objs= - gentop= - # reload_cmds runs $LD directly, so let us get rid of - # -Wl from whole_archive_flag_spec and hope we can get by with - # turning comma into space.. - wl= - - if test -n "$convenience"; then - if test -n "$whole_archive_flag_spec"; then - eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" - reload_conv_objs=$reload_objs\ `$ECHO "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` - else - gentop="$output_objdir/${obj}x" - generated="$generated $gentop" - - func_extract_archives $gentop $convenience - reload_conv_objs="$reload_objs $func_extract_archives_result" - fi - fi - - # Create the old-style object. - reload_objs="$objs$old_deplibs "`$ECHO "X$libobjs" | $SP2NL | $Xsed -e '/\.'${libext}$'/d' -e '/\.lib$/d' -e "$lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test - - output="$obj" - func_execute_cmds "$reload_cmds" 'exit $?' - - # Exit if we aren't doing a library object file. - if test -z "$libobj"; then - if test -n "$gentop"; then - func_show_eval '${RM}r "$gentop"' - fi - - exit $EXIT_SUCCESS - fi - - if test "$build_libtool_libs" != yes; then - if test -n "$gentop"; then - func_show_eval '${RM}r "$gentop"' - fi - - # Create an invalid libtool object if no PIC, so that we don't - # accidentally link it into a program. - # $show "echo timestamp > $libobj" - # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? - exit $EXIT_SUCCESS - fi - - if test -n "$pic_flag" || test "$pic_mode" != default; then - # Only do commands if we really have different PIC objects. - reload_objs="$libobjs $reload_conv_objs" - output="$libobj" - func_execute_cmds "$reload_cmds" 'exit $?' - fi - - if test -n "$gentop"; then - func_show_eval '${RM}r "$gentop"' - fi - - exit $EXIT_SUCCESS - ;; - - prog) - case $host in - *cygwin*) func_stripname '' '.exe' "$output" - output=$func_stripname_result.exe;; - esac - test -n "$vinfo" && \ - func_warning "\`-version-info' is ignored for programs" - - test -n "$release" && \ - func_warning "\`-release' is ignored for programs" - - test "$preload" = yes \ - && test "$dlopen_support" = unknown \ - && test "$dlopen_self" = unknown \ - && test "$dlopen_self_static" = unknown && \ - func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." - - case $host in - *-*-rhapsody* | *-*-darwin1.[012]) - # On Rhapsody replace the C library is the System framework - compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` - finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's/ -lc / System.ltframework /'` - ;; - esac - - case $host in - *-*-darwin*) - # Don't allow lazy linking, it breaks C++ global constructors - # But is supposedly fixed on 10.4 or later (yay!). - if test "$tagname" = CXX ; then - case ${MACOSX_DEPLOYMENT_TARGET-10.0} in - 10.[0123]) - compile_command="$compile_command ${wl}-bind_at_load" - finalize_command="$finalize_command ${wl}-bind_at_load" - ;; - esac - fi - # Time to change all our "foo.ltframework" stuff back to "-framework foo" - compile_deplibs=`$ECHO "X $compile_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - finalize_deplibs=`$ECHO "X $finalize_deplibs" | $Xsed -e 's% \([^ $]*\).ltframework% -framework \1%g'` - ;; - esac - - - # move library search paths that coincide with paths to not yet - # installed libraries to the beginning of the library search list - new_libs= - for path in $notinst_path; do - case " $new_libs " in - *" -L$path/$objdir "*) ;; - *) - case " $compile_deplibs " in - *" -L$path/$objdir "*) - new_libs="$new_libs -L$path/$objdir" ;; - esac - ;; - esac - done - for deplib in $compile_deplibs; do - case $deplib in - -L*) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$new_libs $deplib" ;; - esac - ;; - *) new_libs="$new_libs $deplib" ;; - esac - done - compile_deplibs="$new_libs" - - - compile_command="$compile_command $compile_deplibs" - finalize_command="$finalize_command $finalize_deplibs" - - if test -n "$rpath$xrpath"; then - # If the user specified any rpath flags, then add them. - for libdir in $rpath $xrpath; do - # This is the magic to use -rpath. - case "$finalize_rpath " in - *" $libdir "*) ;; - *) finalize_rpath="$finalize_rpath $libdir" ;; - esac - done - fi - - # Now hardcode the library paths - rpath= - hardcode_libdirs= - for libdir in $compile_rpath $finalize_rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - rpath="$rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$perm_rpath " in - *" $libdir "*) ;; - *) perm_rpath="$perm_rpath $libdir" ;; - esac - fi - case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2*) - testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` - case :$dllsearchpath: in - *":$libdir:"*) ;; - *) dllsearchpath="$dllsearchpath:$libdir";; - esac - case :$dllsearchpath: in - *":$testbindir:"*) ;; - *) dllsearchpath="$dllsearchpath:$testbindir";; - esac - ;; - esac - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - eval rpath=\" $hardcode_libdir_flag_spec\" - fi - compile_rpath="$rpath" - - rpath= - hardcode_libdirs= - for libdir in $finalize_rpath; do - if test -n "$hardcode_libdir_flag_spec"; then - if test -n "$hardcode_libdir_separator"; then - if test -z "$hardcode_libdirs"; then - hardcode_libdirs="$libdir" - else - # Just accumulate the unique libdirs. - case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in - *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) - ;; - *) - hardcode_libdirs="$hardcode_libdirs$hardcode_libdir_separator$libdir" - ;; - esac - fi - else - eval flag=\"$hardcode_libdir_flag_spec\" - rpath="$rpath $flag" - fi - elif test -n "$runpath_var"; then - case "$finalize_perm_rpath " in - *" $libdir "*) ;; - *) finalize_perm_rpath="$finalize_perm_rpath $libdir" ;; - esac - fi - done - # Substitute the hardcoded libdirs into the rpath. - if test -n "$hardcode_libdir_separator" && - test -n "$hardcode_libdirs"; then - libdir="$hardcode_libdirs" - eval rpath=\" $hardcode_libdir_flag_spec\" - fi - finalize_rpath="$rpath" - - if test -n "$libobjs" && test "$build_old_libs" = yes; then - # Transform all the library objects into standard objects. - compile_command=`$ECHO "X$compile_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - finalize_command=`$ECHO "X$finalize_command" | $SP2NL | $Xsed -e "$lo2o" | $NL2SP` - fi - - func_generate_dlsyms "$outputname" "@PROGRAM@" "no" - - # template prelinking step - if test -n "$prelink_cmds"; then - func_execute_cmds "$prelink_cmds" 'exit $?' - fi - - wrappers_required=yes - case $host in - *cygwin* | *mingw* ) - if test "$build_libtool_libs" != yes; then - wrappers_required=no - fi - ;; - *) - if test "$need_relink" = no || test "$build_libtool_libs" != yes; then - wrappers_required=no - fi - ;; - esac - if test "$wrappers_required" = no; then - # Replace the output file specification. - compile_command=`$ECHO "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` - link_command="$compile_command$compile_rpath" - - # We have no uninstalled library dependencies, so finalize right now. - exit_status=0 - func_show_eval "$link_command" 'exit_status=$?' - - # Delete the generated files. - if test -f "$output_objdir/${outputname}S.${objext}"; then - func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' - fi - - exit $exit_status - fi - - if test -n "$compile_shlibpath$finalize_shlibpath"; then - compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" - fi - if test -n "$finalize_shlibpath"; then - finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" - fi - - compile_var= - finalize_var= - if test -n "$runpath_var"; then - if test -n "$perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $perm_rpath; do - rpath="$rpath$dir:" - done - compile_var="$runpath_var=\"$rpath\$$runpath_var\" " - fi - if test -n "$finalize_perm_rpath"; then - # We should set the runpath_var. - rpath= - for dir in $finalize_perm_rpath; do - rpath="$rpath$dir:" - done - finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " - fi - fi - - if test "$no_install" = yes; then - # We don't need to create a wrapper script. - link_command="$compile_var$compile_command$compile_rpath" - # Replace the output file specification. - link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` - # Delete the old output file. - $opt_dry_run || $RM $output - # Link the executable and exit - func_show_eval "$link_command" 'exit $?' - exit $EXIT_SUCCESS - fi - - if test "$hardcode_action" = relink; then - # Fast installation is not supported - link_command="$compile_var$compile_command$compile_rpath" - relink_command="$finalize_var$finalize_command$finalize_rpath" - - func_warning "this platform does not like uninstalled shared libraries" - func_warning "\`$output' will be relinked during installation" - else - if test "$fast_install" != no; then - link_command="$finalize_var$compile_command$finalize_rpath" - if test "$fast_install" = yes; then - relink_command=`$ECHO "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` - else - # fast_install is set to needless - relink_command= - fi - else - link_command="$compile_var$compile_command$compile_rpath" - relink_command="$finalize_var$finalize_command$finalize_rpath" - fi - fi - - # Replace the output file specification. - link_command=`$ECHO "X$link_command" | $Xsed -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` - - # Delete the old output files. - $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname - - func_show_eval "$link_command" 'exit $?' - - # Now create the wrapper script. - func_verbose "creating $output" - - # Quote the relink command for shipping. - if test -n "$relink_command"; then - # Preserve any variables that may affect compiler behavior - for var in $variables_saved_for_relink; do - if eval test -z \"\${$var+set}\"; then - relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" - elif eval var_value=\$$var; test -z "$var_value"; then - relink_command="$var=; export $var; $relink_command" - else - func_quote_for_eval "$var_value" - relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" - fi - done - relink_command="(cd `pwd`; $relink_command)" - relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` - fi - - # Quote $ECHO for shipping. - if test "X$ECHO" = "X$SHELL $progpath --fallback-echo"; then - case $progpath in - [\\/]* | [A-Za-z]:[\\/]*) qecho="$SHELL $progpath --fallback-echo";; - *) qecho="$SHELL `pwd`/$progpath --fallback-echo";; - esac - qecho=`$ECHO "X$qecho" | $Xsed -e "$sed_quote_subst"` - else - qecho=`$ECHO "X$ECHO" | $Xsed -e "$sed_quote_subst"` - fi - - # Only actually do things if not in dry run mode. - $opt_dry_run || { - # win32 will think the script is a binary if it has - # a .exe suffix, so we strip it off here. - case $output in - *.exe) func_stripname '' '.exe' "$output" - output=$func_stripname_result ;; - esac - # test for cygwin because mv fails w/o .exe extensions - case $host in - *cygwin*) - exeext=.exe - func_stripname '' '.exe' "$outputname" - outputname=$func_stripname_result ;; - *) exeext= ;; - esac - case $host in - *cygwin* | *mingw* ) - func_dirname_and_basename "$output" "" "." - output_name=$func_basename_result - output_path=$func_dirname_result - cwrappersource="$output_path/$objdir/lt-$output_name.c" - cwrapper="$output_path/$output_name.exe" - $RM $cwrappersource $cwrapper - trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 - - func_emit_cwrapperexe_src > $cwrappersource - - # we should really use a build-platform specific compiler - # here, but OTOH, the wrappers (shell script and this C one) - # are only useful if you want to execute the "real" binary. - # Since the "real" binary is built for $host, then this - # wrapper might as well be built for $host, too. - $opt_dry_run || { - $LTCC $LTCFLAGS -o $cwrapper $cwrappersource - $STRIP $cwrapper - } - - # Now, create the wrapper script for func_source use: - func_ltwrapper_scriptname $cwrapper - $RM $func_ltwrapper_scriptname_result - trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 - $opt_dry_run || { - # note: this script will not be executed, so do not chmod. - if test "x$build" = "x$host" ; then - $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result - else - func_emit_wrapper no > $func_ltwrapper_scriptname_result - fi - } - ;; - * ) - $RM $output - trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 - - func_emit_wrapper no > $output - chmod +x $output - ;; - esac - } - exit $EXIT_SUCCESS - ;; - esac - - # See if we need to build an old-fashioned archive. - for oldlib in $oldlibs; do - - if test "$build_libtool_libs" = convenience; then - oldobjs="$libobjs_save $symfileobj" - addlibs="$convenience" - build_libtool_libs=no - else - if test "$build_libtool_libs" = module; then - oldobjs="$libobjs_save" - build_libtool_libs=no - else - oldobjs="$old_deplibs $non_pic_objects" - if test "$preload" = yes && test -f "$symfileobj"; then - oldobjs="$oldobjs $symfileobj" - fi - fi - addlibs="$old_convenience" - fi - - if test -n "$addlibs"; then - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $addlibs - oldobjs="$oldobjs $func_extract_archives_result" - fi - - # Do each command in the archive commands. - if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then - cmds=$old_archive_from_new_cmds - else - - # Add any objects from preloaded convenience libraries - if test -n "$dlprefiles"; then - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - - func_extract_archives $gentop $dlprefiles - oldobjs="$oldobjs $func_extract_archives_result" - fi - - # POSIX demands no paths to be encoded in archives. We have - # to avoid creating archives with duplicate basenames if we - # might have to extract them afterwards, e.g., when creating a - # static archive out of a convenience library, or when linking - # the entirety of a libtool archive into another (currently - # not supported by libtool). - if (for obj in $oldobjs - do - func_basename "$obj" - $ECHO "$func_basename_result" - done | sort | sort -uc >/dev/null 2>&1); then - : - else - $ECHO "copying selected object files to avoid basename conflicts..." - gentop="$output_objdir/${outputname}x" - generated="$generated $gentop" - func_mkdir_p "$gentop" - save_oldobjs=$oldobjs - oldobjs= - counter=1 - for obj in $save_oldobjs - do - func_basename "$obj" - objbase="$func_basename_result" - case " $oldobjs " in - " ") oldobjs=$obj ;; - *[\ /]"$objbase "*) - while :; do - # Make sure we don't pick an alternate name that also - # overlaps. - newobj=lt$counter-$objbase - func_arith $counter + 1 - counter=$func_arith_result - case " $oldobjs " in - *[\ /]"$newobj "*) ;; - *) if test ! -f "$gentop/$newobj"; then break; fi ;; - esac - done - func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" - oldobjs="$oldobjs $gentop/$newobj" - ;; - *) oldobjs="$oldobjs $obj" ;; - esac - done - fi - eval cmds=\"$old_archive_cmds\" - - func_len " $cmds" - len=$func_len_result - if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then - cmds=$old_archive_cmds - else - # the command line is too long to link in one step, link in parts - func_verbose "using piecewise archive linking..." - save_RANLIB=$RANLIB - RANLIB=: - objlist= - concat_cmds= - save_oldobjs=$oldobjs - oldobjs= - # Is there a better way of finding the last object in the list? - for obj in $save_oldobjs - do - last_oldobj=$obj - done - eval test_cmds=\"$old_archive_cmds\" - func_len " $test_cmds" - len0=$func_len_result - len=$len0 - for obj in $save_oldobjs - do - func_len " $obj" - func_arith $len + $func_len_result - len=$func_arith_result - func_append objlist " $obj" - if test "$len" -lt "$max_cmd_len"; then - : - else - # the above command should be used before it gets too long - oldobjs=$objlist - if test "$obj" = "$last_oldobj" ; then - RANLIB=$save_RANLIB - fi - test -z "$concat_cmds" || concat_cmds=$concat_cmds~ - eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" - objlist= - len=$len0 - fi - done - RANLIB=$save_RANLIB - oldobjs=$objlist - if test "X$oldobjs" = "X" ; then - eval cmds=\"\$concat_cmds\" - else - eval cmds=\"\$concat_cmds~\$old_archive_cmds\" - fi - fi - fi - func_execute_cmds "$cmds" 'exit $?' - done - - test -n "$generated" && \ - func_show_eval "${RM}r$generated" - - # Now create the libtool archive. - case $output in - *.la) - old_library= - test "$build_old_libs" = yes && old_library="$libname.$libext" - func_verbose "creating $output" - - # Preserve any variables that may affect compiler behavior - for var in $variables_saved_for_relink; do - if eval test -z \"\${$var+set}\"; then - relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" - elif eval var_value=\$$var; test -z "$var_value"; then - relink_command="$var=; export $var; $relink_command" - else - func_quote_for_eval "$var_value" - relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" - fi - done - # Quote the link command for shipping. - relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" - relink_command=`$ECHO "X$relink_command" | $Xsed -e "$sed_quote_subst"` - if test "$hardcode_automatic" = yes ; then - relink_command= - fi - - # Only create the output if not a dry run. - $opt_dry_run || { - for installed in no yes; do - if test "$installed" = yes; then - if test -z "$install_libdir"; then - break - fi - output="$output_objdir/$outputname"i - # Replace all uninstalled libtool libraries with the installed ones - newdependency_libs= - for deplib in $dependency_libs; do - case $deplib in - *.la) - func_basename "$deplib" - name="$func_basename_result" - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` - test -z "$libdir" && \ - func_fatal_error "\`$deplib' is not a valid libtool archive" - newdependency_libs="$newdependency_libs $libdir/$name" - ;; - *) newdependency_libs="$newdependency_libs $deplib" ;; - esac - done - dependency_libs="$newdependency_libs" - newdlfiles= - - for lib in $dlfiles; do - case $lib in - *.la) - func_basename "$lib" - name="$func_basename_result" - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` - test -z "$libdir" && \ - func_fatal_error "\`$lib' is not a valid libtool archive" - newdlfiles="$newdlfiles $libdir/$name" - ;; - *) newdlfiles="$newdlfiles $lib" ;; - esac - done - dlfiles="$newdlfiles" - newdlprefiles= - for lib in $dlprefiles; do - case $lib in - *.la) - # Only pass preopened files to the pseudo-archive (for - # eventual linking with the app. that links it) if we - # didn't already link the preopened objects directly into - # the library: - func_basename "$lib" - name="$func_basename_result" - eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` - test -z "$libdir" && \ - func_fatal_error "\`$lib' is not a valid libtool archive" - newdlprefiles="$newdlprefiles $libdir/$name" - ;; - esac - done - dlprefiles="$newdlprefiles" - else - newdlfiles= - for lib in $dlfiles; do - case $lib in - [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; - *) abs=`pwd`"/$lib" ;; - esac - newdlfiles="$newdlfiles $abs" - done - dlfiles="$newdlfiles" - newdlprefiles= - for lib in $dlprefiles; do - case $lib in - [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; - *) abs=`pwd`"/$lib" ;; - esac - newdlprefiles="$newdlprefiles $abs" - done - dlprefiles="$newdlprefiles" - fi - $RM $output - # place dlname in correct position for cygwin - tdlname=$dlname - case $host,$output,$installed,$module,$dlname in - *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;; - esac - $ECHO > $output "\ -# $outputname - a libtool library file -# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION -# -# Please DO NOT delete this file! -# It is necessary for linking the library. - -# The name that we can dlopen(3). -dlname='$tdlname' - -# Names of this library. -library_names='$library_names' - -# The name of the static archive. -old_library='$old_library' - -# Linker flags that can not go in dependency_libs. -inherited_linker_flags='$new_inherited_linker_flags' - -# Libraries that this one depends upon. -dependency_libs='$dependency_libs' - -# Names of additional weak libraries provided by this library -weak_library_names='$weak_libs' - -# Version information for $libname. -current=$current -age=$age -revision=$revision - -# Is this an already installed library? -installed=$installed - -# Should we warn about portability when linking against -modules? -shouldnotlink=$module - -# Files to dlopen/dlpreopen -dlopen='$dlfiles' -dlpreopen='$dlprefiles' - -# Directory that this library needs to be installed in: -libdir='$install_libdir'" - if test "$installed" = no && test "$need_relink" = yes; then - $ECHO >> $output "\ -relink_command=\"$relink_command\"" - fi - done - } - - # Do a symbolic link so that the libtool archive can be found in - # LD_LIBRARY_PATH before the program is installed. - func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' - ;; - esac - exit $EXIT_SUCCESS -} - -{ test "$mode" = link || test "$mode" = relink; } && - func_mode_link ${1+"$@"} - - -# func_mode_uninstall arg... -func_mode_uninstall () -{ - $opt_debug - RM="$nonopt" - files= - rmforce= - exit_status=0 - - # This variable tells wrapper scripts just to set variables rather - # than running their programs. - libtool_install_magic="$magic" - - for arg - do - case $arg in - -f) RM="$RM $arg"; rmforce=yes ;; - -*) RM="$RM $arg" ;; - *) files="$files $arg" ;; - esac - done - - test -z "$RM" && \ - func_fatal_help "you must specify an RM program" - - rmdirs= - - origobjdir="$objdir" - for file in $files; do - func_dirname "$file" "" "." - dir="$func_dirname_result" - if test "X$dir" = X.; then - objdir="$origobjdir" - else - objdir="$dir/$origobjdir" - fi - func_basename "$file" - name="$func_basename_result" - test "$mode" = uninstall && objdir="$dir" - - # Remember objdir for removal later, being careful to avoid duplicates - if test "$mode" = clean; then - case " $rmdirs " in - *" $objdir "*) ;; - *) rmdirs="$rmdirs $objdir" ;; - esac - fi - - # Don't error if the file doesn't exist and rm -f was used. - if { test -L "$file"; } >/dev/null 2>&1 || - { test -h "$file"; } >/dev/null 2>&1 || - test -f "$file"; then - : - elif test -d "$file"; then - exit_status=1 - continue - elif test "$rmforce" = yes; then - continue - fi - - rmfiles="$file" - - case $name in - *.la) - # Possibly a libtool archive, so verify it. - if func_lalib_p "$file"; then - func_source $dir/$name - - # Delete the libtool libraries and symlinks. - for n in $library_names; do - rmfiles="$rmfiles $objdir/$n" - done - test -n "$old_library" && rmfiles="$rmfiles $objdir/$old_library" - - case "$mode" in - clean) - case " $library_names " in - # " " in the beginning catches empty $dlname - *" $dlname "*) ;; - *) rmfiles="$rmfiles $objdir/$dlname" ;; - esac - test -n "$libdir" && rmfiles="$rmfiles $objdir/$name $objdir/${name}i" - ;; - uninstall) - if test -n "$library_names"; then - # Do each command in the postuninstall commands. - func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' - fi - - if test -n "$old_library"; then - # Do each command in the old_postuninstall commands. - func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' - fi - # FIXME: should reinstall the best remaining shared library. - ;; - esac - fi - ;; - - *.lo) - # Possibly a libtool object, so verify it. - if func_lalib_p "$file"; then - - # Read the .lo file - func_source $dir/$name - - # Add PIC object to the list of files to remove. - if test -n "$pic_object" && - test "$pic_object" != none; then - rmfiles="$rmfiles $dir/$pic_object" - fi - - # Add non-PIC object to the list of files to remove. - if test -n "$non_pic_object" && - test "$non_pic_object" != none; then - rmfiles="$rmfiles $dir/$non_pic_object" - fi - fi - ;; - - *) - if test "$mode" = clean ; then - noexename=$name - case $file in - *.exe) - func_stripname '' '.exe' "$file" - file=$func_stripname_result - func_stripname '' '.exe' "$name" - noexename=$func_stripname_result - # $file with .exe has already been added to rmfiles, - # add $file without .exe - rmfiles="$rmfiles $file" - ;; - esac - # Do a test to see if this is a libtool program. - if func_ltwrapper_p "$file"; then - if func_ltwrapper_executable_p "$file"; then - func_ltwrapper_scriptname "$file" - relink_command= - func_source $func_ltwrapper_scriptname_result - rmfiles="$rmfiles $func_ltwrapper_scriptname_result" - else - relink_command= - func_source $dir/$noexename - fi - - # note $name still contains .exe if it was in $file originally - # as does the version of $file that was added into $rmfiles - rmfiles="$rmfiles $objdir/$name $objdir/${name}S.${objext}" - if test "$fast_install" = yes && test -n "$relink_command"; then - rmfiles="$rmfiles $objdir/lt-$name" - fi - if test "X$noexename" != "X$name" ; then - rmfiles="$rmfiles $objdir/lt-${noexename}.c" - fi - fi - fi - ;; - esac - func_show_eval "$RM $rmfiles" 'exit_status=1' - done - objdir="$origobjdir" - - # Try to remove the ${objdir}s in the directories where we deleted files - for dir in $rmdirs; do - if test -d "$dir"; then - func_show_eval "rmdir $dir >/dev/null 2>&1" - fi - done - - exit $exit_status -} - -{ test "$mode" = uninstall || test "$mode" = clean; } && - func_mode_uninstall ${1+"$@"} - -test -z "$mode" && { - help="$generic_help" - func_fatal_help "you must specify a MODE" -} - -test -z "$exec_cmd" && \ - func_fatal_help "invalid operation mode \`$mode'" - -if test -n "$exec_cmd"; then - eval exec "$exec_cmd" - exit $EXIT_FAILURE -fi - -exit $exit_status - - -# The TAGs below are defined such that we never get into a situation -# in which we disable both kinds of libraries. Given conflicting -# choices, we go for a static library, that is the most portable, -# since we can't tell whether shared libraries were disabled because -# the user asked for that or because the platform doesn't support -# them. This is particularly important on AIX, because we don't -# support having both static and shared libraries enabled at the same -# time on that platform, so we default to a shared-only configuration. -# If a disable-shared tag is given, we'll fallback to a static-only -# configuration. But we'll never go from static-only to shared-only. - -# ### BEGIN LIBTOOL TAG CONFIG: disable-shared -build_libtool_libs=no -build_old_libs=yes -# ### END LIBTOOL TAG CONFIG: disable-shared - -# ### BEGIN LIBTOOL TAG CONFIG: disable-static -build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` -# ### END LIBTOOL TAG CONFIG: disable-static - -# Local Variables: -# mode:shell-script -# sh-indentation:2 -# End: -# vi:sw=2 - diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/macho.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/macho.c deleted file mode 100644 index b43ea22..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/macho.c +++ /dev/null @@ -1,1418 +0,0 @@ -/* macho.c -- Get debug data from an Mach-O file for backtraces. - Copyright (C) 2012-2016 Free Software Foundation, Inc. - Written by John Colanduoni. - - Pending upstream pull request: - https://github.com/ianlancetaylor/libbacktrace/pull/2 - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -/* We can't use autotools to detect the pointer width of our program because - we may be building a fat Mach-O file containing both 32-bit and 64-bit - variants. However Mach-O runs a limited set of platforms so detection - via preprocessor is not difficult. */ - -#if defined(__MACH__) -#if defined(__LP64__) -#define BACKTRACE_BITS 64 -#else -#define BACKTRACE_BITS 32 -#endif -#else -#error Attempting to build Mach-O support on incorrect platform -#endif - -#if defined(__x86_64__) -#define NATIVE_CPU_TYPE CPU_TYPE_X86_64 -#elif defined(__i386__) -#define NATIVE_CPU_TYPE CPU_TYPE_X86 -#elif defined(__aarch64__) -#define NATIVE_CPU_TYPE CPU_TYPE_ARM64 -#elif defined(__arm__) -#define NATIVE_CPU_TYPE CPU_TYPE_ARM -#else -#error Could not detect native Mach-O cpu_type_t -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -struct macho_commands_view -{ - struct backtrace_view view; - uint32_t commands_count; - uint32_t commands_total_size; - int bytes_swapped; - size_t base_offset; -}; - -enum debug_section -{ - DEBUG_INFO, - DEBUG_LINE, - DEBUG_ABBREV, - DEBUG_RANGES, - DEBUG_STR, - DEBUG_MAX -}; - -static const char *const debug_section_names[DEBUG_MAX] = - { - "__debug_info", - "__debug_line", - "__debug_abbrev", - "__debug_ranges", - "__debug_str" - }; - -struct found_dwarf_section -{ - uint32_t file_offset; - uintptr_t file_size; - const unsigned char *data; -}; - -/* Mach-O symbols don't have a length. As a result we have to infer it - by sorting the symbol addresses for each image and recording the - memory range attributed to each image. */ -struct macho_symbol -{ - uintptr_t addr; - size_t size; - const char *name; -}; - -struct macho_syminfo_data -{ - struct macho_syminfo_data *next; - struct macho_symbol *symbols; - size_t symbol_count; - uintptr_t min_addr; - uintptr_t max_addr; -}; - -uint16_t -macho_file_to_host_u16 (int file_bytes_swapped, uint16_t input) -{ - if (file_bytes_swapped) - return (input >> 8) | (input << 8); - else - return input; -} - -uint32_t -macho_file_to_host_u32 (int file_bytes_swapped, uint32_t input) -{ - if (file_bytes_swapped) - { - return ((input >> 24) & 0x000000FF) - | ((input >> 8) & 0x0000FF00) - | ((input << 8) & 0x00FF0000) - | ((input << 24) & 0xFF000000); - } - else - { - return input; - } -} - -uint64_t -macho_file_to_host_u64 (int file_bytes_swapped, uint64_t input) -{ - if (file_bytes_swapped) - { - return macho_file_to_host_u32 (file_bytes_swapped, - (uint32_t) (input >> 32)) - | (((uint64_t) macho_file_to_host_u32 (file_bytes_swapped, - (uint32_t) input)) << 32); - } - else - { - return input; - } -} - -#if BACKTRACE_BITS == 64 -#define macho_file_to_host_usize macho_file_to_host_u64 -typedef struct mach_header_64 mach_header_native_t; -#define LC_SEGMENT_NATIVE LC_SEGMENT_64 -typedef struct segment_command_64 segment_command_native_t; -typedef struct nlist_64 nlist_native_t; -typedef struct section_64 section_native_t; -#else /* BACKTRACE_BITS == 32 */ -#define macho_file_to_host_usize macho_file_to_host_u32 -typedef struct mach_header mach_header_native_t; -#define LC_SEGMENT_NATIVE LC_SEGMENT -typedef struct segment_command segment_command_native_t; -typedef struct nlist nlist_native_t; -typedef struct section section_native_t; -#endif - -// Gets a view into a Mach-O image, taking any slice offset into account -int -macho_get_view (struct backtrace_state *state, int descriptor, - off_t offset, size_t size, - backtrace_error_callback error_callback, - void *data, struct macho_commands_view *commands_view, - struct backtrace_view *view) -{ - return backtrace_get_view (state, descriptor, - commands_view->base_offset + offset, size, - error_callback, data, view); -} - -int -macho_get_commands (struct backtrace_state *state, int descriptor, - backtrace_error_callback error_callback, - void *data, struct macho_commands_view *commands_view, - int *incompatible) -{ - int ret = 0; - int is_fat = 0; - struct backtrace_view file_header_view; - int file_header_view_valid = 0; - struct backtrace_view fat_archs_view; - int fat_archs_view_valid = 0; - const mach_header_native_t *file_header; - uint64_t commands_offset; - - *incompatible = 0; - - if (!backtrace_get_view (state, descriptor, 0, sizeof (mach_header_native_t), - error_callback, data, &file_header_view)) - goto end; - file_header_view_valid = 1; - - switch (*(uint32_t *) file_header_view.data) - { - case MH_MAGIC: - if (BACKTRACE_BITS == 32) - commands_view->bytes_swapped = 0; - else - { - *incompatible = 1; - goto end; - } - break; - case MH_CIGAM: - if (BACKTRACE_BITS == 32) - commands_view->bytes_swapped = 1; - else - { - *incompatible = 1; - goto end; - } - break; - case MH_MAGIC_64: - if (BACKTRACE_BITS == 64) - commands_view->bytes_swapped = 0; - else - { - *incompatible = 1; - goto end; - } - break; - case MH_CIGAM_64: - if (BACKTRACE_BITS == 64) - commands_view->bytes_swapped = 1; - else - { - *incompatible = 1; - goto end; - } - break; - case FAT_MAGIC: - is_fat = 1; - commands_view->bytes_swapped = 0; - break; - case FAT_CIGAM: - is_fat = 1; - commands_view->bytes_swapped = 1; - break; - default: - goto end; - } - - if (is_fat) - { - uint32_t native_slice_offset; - size_t archs_total_size; - uint32_t arch_count; - const struct fat_header *fat_header; - const struct fat_arch *archs; - uint32_t i; - - fat_header = file_header_view.data; - arch_count = - macho_file_to_host_u32 (commands_view->bytes_swapped, - fat_header->nfat_arch); - - archs_total_size = arch_count * sizeof (struct fat_arch); - - if (!backtrace_get_view (state, descriptor, sizeof (struct fat_header), - archs_total_size, error_callback, - data, &fat_archs_view)) - goto end; - fat_archs_view_valid = 1; - - native_slice_offset = 0; - archs = fat_archs_view.data; - for (i = 0; i < arch_count; i++) - { - const struct fat_arch *raw_arch = archs + i; - int cpu_type = - (int) macho_file_to_host_u32 (commands_view->bytes_swapped, - (uint32_t) raw_arch->cputype); - - if (cpu_type == NATIVE_CPU_TYPE) - { - native_slice_offset = - macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_arch->offset); - - break; - } - } - - if (native_slice_offset == 0) - { - *incompatible = 1; - goto end; - } - - backtrace_release_view (state, &file_header_view, error_callback, data); - file_header_view_valid = 0; - if (!backtrace_get_view (state, descriptor, native_slice_offset, - sizeof (mach_header_native_t), error_callback, - data, &file_header_view)) - goto end; - file_header_view_valid = 1; - - // The endianess of the slice may be different than the fat image - switch (*(uint32_t *) file_header_view.data) - { - case MH_MAGIC: - if (BACKTRACE_BITS == 32) - commands_view->bytes_swapped = 0; - else - goto end; - break; - case MH_CIGAM: - if (BACKTRACE_BITS == 32) - commands_view->bytes_swapped = 1; - else - goto end; - break; - case MH_MAGIC_64: - if (BACKTRACE_BITS == 64) - commands_view->bytes_swapped = 0; - else - goto end; - break; - case MH_CIGAM_64: - if (BACKTRACE_BITS == 64) - commands_view->bytes_swapped = 1; - else - goto end; - break; - default: - goto end; - } - - commands_view->base_offset = native_slice_offset; - } - else - commands_view->base_offset = 0; - - file_header = file_header_view.data; - commands_view->commands_count = - macho_file_to_host_u32 (commands_view->bytes_swapped, - file_header->ncmds); - commands_view->commands_total_size = - macho_file_to_host_u32 (commands_view->bytes_swapped, - file_header->sizeofcmds); - commands_offset = - commands_view->base_offset + sizeof (mach_header_native_t); - - if (!backtrace_get_view (state, descriptor, commands_offset, - commands_view->commands_total_size, error_callback, - data, &commands_view->view)) - goto end; - - ret = 1; - -end: - if (file_header_view_valid) - backtrace_release_view (state, &file_header_view, error_callback, data); - if (fat_archs_view_valid) - backtrace_release_view (state, &fat_archs_view, error_callback, data); - return ret; -} - -int -macho_get_uuid (struct backtrace_state *state ATTRIBUTE_UNUSED, - int descriptor ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, - void *data, struct macho_commands_view *commands_view, - uuid_t *uuid) -{ - size_t offset = 0; - uint32_t i = 0; - - for (i = 0; i < commands_view->commands_count; i++) - { - const struct load_command *raw_command; - struct load_command command; - - if (offset + sizeof (struct load_command) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - raw_command = - commands_view->view.data + offset; - command.cmd = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmd); - command.cmdsize = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmdsize); - - if (command.cmd == LC_UUID) - { - const struct uuid_command *uuid_command; - - if (offset + sizeof (struct uuid_command) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - uuid_command = - (struct uuid_command *) raw_command; - memcpy (uuid, uuid_command->uuid, sizeof (uuid_t)); - return 1; - } - - offset += command.cmdsize; - } - - error_callback (data, "executable file is missing an identifying UUID", 0); - return 0; -} - -/* Returns the base address of a Mach-O image, as encoded in the file header. - * WARNING: This does not take ASLR into account, which is ubiquitous on recent - * Darwin platforms. - */ -int -macho_get_addr_range (struct backtrace_state *state ATTRIBUTE_UNUSED, - int descriptor ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, - void *data, struct macho_commands_view *commands_view, - uintptr_t *base_address, uintptr_t *max_address) -{ - size_t offset = 0; - int found_text = 0; - uint32_t i = 0; - - *max_address = 0; - - for (i = 0; i < commands_view->commands_count; i++) - { - const struct load_command *raw_command; - struct load_command command; - - if (offset + sizeof (struct load_command) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - raw_command = commands_view->view.data + offset; - command.cmd = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmd); - command.cmdsize = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmdsize); - - if (command.cmd == LC_SEGMENT_NATIVE) - { - const segment_command_native_t *raw_segment; - uintptr_t segment_vmaddr; - uintptr_t segment_vmsize; - uintptr_t segment_maxaddr; - uintptr_t text_fileoff; - - if (offset + sizeof (segment_command_native_t) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - raw_segment = (segment_command_native_t *) raw_command; - - segment_vmaddr = macho_file_to_host_usize ( - commands_view->bytes_swapped, raw_segment->vmaddr); - segment_vmsize = macho_file_to_host_usize ( - commands_view->bytes_swapped, raw_segment->vmsize); - segment_maxaddr = segment_vmaddr + segment_vmsize; - - if (strncmp (raw_segment->segname, "__TEXT", - sizeof (raw_segment->segname)) == 0) - { - text_fileoff = macho_file_to_host_usize ( - commands_view->bytes_swapped, raw_segment->fileoff); - *base_address = segment_vmaddr - text_fileoff; - - found_text = 1; - } - - if (segment_maxaddr > *max_address) - *max_address = segment_maxaddr; - } - - offset += command.cmdsize; - } - - if (found_text) - return 1; - else - { - error_callback (data, "executable is missing __TEXT segment", 0); - return 0; - } -} - -static int -macho_symbol_compare_addr (const void *left_raw, const void *right_raw) -{ - const struct macho_symbol *left = left_raw; - const struct macho_symbol *right = right_raw; - - if (left->addr > right->addr) - return 1; - else if (left->addr < right->addr) - return -1; - else - return 0; -} - -int -macho_symbol_type_relevant (uint8_t type) -{ - uint8_t type_field = (uint8_t) (type & N_TYPE); - - return !(type & N_EXT) && - (type_field == N_ABS || type_field == N_SECT); -} - -int -macho_add_symtab (struct backtrace_state *state, - backtrace_error_callback error_callback, - void *data, int descriptor, - struct macho_commands_view *commands_view, - uintptr_t base_address, uintptr_t max_image_address, - intptr_t vmslide, int *found_sym) -{ - struct macho_syminfo_data *syminfo_data; - - int ret = 0; - size_t offset = 0; - struct backtrace_view symtab_view; - int symtab_view_valid = 0; - struct backtrace_view strtab_view; - int strtab_view_valid = 0; - size_t syminfo_index = 0; - size_t function_count = 0; - uint32_t i = 0; - uint32_t j = 0; - uint32_t symtab_index = 0; - - *found_sym = 0; - - for (i = 0; i < commands_view->commands_count; i++) - { - const struct load_command *raw_command; - struct load_command command; - - if (offset + sizeof (struct load_command) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - raw_command = commands_view->view.data + offset; - command.cmd = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmd); - command.cmdsize = macho_file_to_host_u32 (commands_view->bytes_swapped, - raw_command->cmdsize); - - if (command.cmd == LC_SYMTAB) - { - const struct symtab_command *symtab_command; - uint32_t symbol_table_offset; - uint32_t symbol_count; - uint32_t string_table_offset; - uint32_t string_table_size; - - if (offset + sizeof (struct symtab_command) - > commands_view->commands_total_size) - { - error_callback (data, - "executable file contains out of range command offset", - 0); - return 0; - } - - symtab_command = (struct symtab_command *) raw_command; - - symbol_table_offset = macho_file_to_host_u32 ( - commands_view->bytes_swapped, symtab_command->symoff); - symbol_count = macho_file_to_host_u32 ( - commands_view->bytes_swapped, symtab_command->nsyms); - string_table_offset = macho_file_to_host_u32 ( - commands_view->bytes_swapped, symtab_command->stroff); - string_table_size = macho_file_to_host_u32 ( - commands_view->bytes_swapped, symtab_command->strsize); - - - if (!macho_get_view (state, descriptor, symbol_table_offset, - symbol_count * sizeof (nlist_native_t), - error_callback, data, commands_view, - &symtab_view)) - goto end; - symtab_view_valid = 1; - - if (!macho_get_view (state, descriptor, string_table_offset, - string_table_size, error_callback, data, - commands_view, &strtab_view)) - goto end; - strtab_view_valid = 1; - - // Count functions first - for (j = 0; j < symbol_count; j++) - { - const nlist_native_t *raw_sym = - ((const nlist_native_t *) symtab_view.data) + j; - - if (macho_symbol_type_relevant (raw_sym->n_type)) - { - function_count += 1; - } - } - - // Allocate space for the: - // (a) macho_syminfo_data for this image - // (b) macho_symbol entries - syminfo_data = - backtrace_alloc (state, - sizeof (struct macho_syminfo_data), - error_callback, data); - if (syminfo_data == NULL) - goto end; - - syminfo_data->symbols = backtrace_alloc ( - state, function_count * sizeof (struct macho_symbol), - error_callback, data); - if (syminfo_data->symbols == NULL) - goto end; - - syminfo_data->symbol_count = function_count; - syminfo_data->next = NULL; - syminfo_data->min_addr = base_address; - syminfo_data->max_addr = max_image_address; - - for (symtab_index = 0; - symtab_index < symbol_count; symtab_index++) - { - const nlist_native_t *raw_sym = - ((const nlist_native_t *) symtab_view.data) + - symtab_index; - - if (macho_symbol_type_relevant (raw_sym->n_type)) - { - size_t strtab_index; - const char *name; - size_t max_len_plus_one; - - syminfo_data->symbols[syminfo_index].addr = - macho_file_to_host_usize (commands_view->bytes_swapped, - raw_sym->n_value) + vmslide; - - strtab_index = macho_file_to_host_u32 ( - commands_view->bytes_swapped, - raw_sym->n_un.n_strx); - - // Check the range of the supposed "string" we've been - // given - if (strtab_index >= string_table_size) - { - error_callback ( - data, - "dSYM file contains out of range string table index", - 0); - goto end; - } - - name = strtab_view.data + strtab_index; - max_len_plus_one = string_table_size - strtab_index; - - if (strnlen (name, max_len_plus_one) >= max_len_plus_one) - { - error_callback ( - data, - "dSYM file contains unterminated string", - 0); - goto end; - } - - // Remove underscore prefixes - if (name[0] == '_') - { - name = name + 1; - } - - syminfo_data->symbols[syminfo_index].name = name; - - syminfo_index += 1; - } - } - - backtrace_qsort (syminfo_data->symbols, - syminfo_data->symbol_count, - sizeof (struct macho_symbol), - macho_symbol_compare_addr); - - // Calculate symbol sizes - for (syminfo_index = 0; - syminfo_index < syminfo_data->symbol_count; syminfo_index++) - { - if (syminfo_index + 1 < syminfo_data->symbol_count) - { - syminfo_data->symbols[syminfo_index].size = - syminfo_data->symbols[syminfo_index + 1].addr - - syminfo_data->symbols[syminfo_index].addr; - } - else - { - syminfo_data->symbols[syminfo_index].size = - max_image_address - - syminfo_data->symbols[syminfo_index].addr; - } - } - - if (!state->threaded) - { - struct macho_syminfo_data **pp; - - for (pp = (struct macho_syminfo_data **) (void *) &state->syminfo_data; - *pp != NULL; - pp = &(*pp)->next); - *pp = syminfo_data; - } - else - { - while (1) - { - struct macho_syminfo_data **pp; - - pp = (struct macho_syminfo_data **) (void *) &state->syminfo_data; - - while (1) - { - struct macho_syminfo_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, syminfo_data)) - break; - } - } - - strtab_view_valid = 0; // We need to keep string table around - *found_sym = 1; - ret = 1; - goto end; - } - - offset += command.cmdsize; - } - - // No symbol table here - ret = 1; - goto end; - -end: - if (symtab_view_valid) - backtrace_release_view (state, &symtab_view, error_callback, data); - if (strtab_view_valid) - backtrace_release_view (state, &strtab_view, error_callback, data); - return ret; -} - -int -macho_try_dwarf (struct backtrace_state *state, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn, uuid_t *executable_uuid, - uintptr_t base_address, uintptr_t max_image_address, - intptr_t vmslide, char *dwarf_filename, int *matched, - int *found_sym, int *found_dwarf) -{ - uuid_t dwarf_uuid; - - int ret = 0; - int dwarf_descriptor; - int dwarf_descriptor_valid = 0; - struct macho_commands_view commands_view; - int commands_view_valid = 0; - struct backtrace_view dwarf_view; - int dwarf_view_valid = 0; - size_t offset = 0; - struct found_dwarf_section dwarf_sections[DEBUG_MAX]; - uintptr_t min_dwarf_offset = 0; - uintptr_t max_dwarf_offset = 0; - uint32_t i = 0; - uint32_t j = 0; - int k = 0; - - *matched = 0; - *found_sym = 0; - *found_dwarf = 0; - - if ((dwarf_descriptor = backtrace_open (dwarf_filename, error_callback, - data, NULL)) == 0) - goto end; - dwarf_descriptor_valid = 1; - - int incompatible; - if (!macho_get_commands (state, dwarf_descriptor, error_callback, data, - &commands_view, &incompatible)) - { - // Failing to read the header here is fine, because this dSYM may be - // for a different architecture - if (incompatible) - { - ret = 1; - } - goto end; - } - commands_view_valid = 1; - - // Get dSYM UUID and compare - if (!macho_get_uuid (state, dwarf_descriptor, error_callback, data, - &commands_view, &dwarf_uuid)) - { - error_callback (data, "dSYM file is missing an identifying uuid", 0); - goto end; - } - if (memcmp (executable_uuid, &dwarf_uuid, sizeof (uuid_t)) != 0) - { - // DWARF doesn't belong to desired executable - ret = 1; - goto end; - } - - *matched = 1; - - // Read symbol table - if (!macho_add_symtab (state, error_callback, data, dwarf_descriptor, - &commands_view, base_address, max_image_address, - vmslide, found_sym)) - goto end; - - // Get DWARF sections - - memset (dwarf_sections, 0, sizeof (dwarf_sections)); - offset = 0; - for (i = 0; i < commands_view.commands_count; i++) - { - const struct load_command *raw_command; - struct load_command command; - - if (offset + sizeof (struct load_command) - > commands_view.commands_total_size) - { - error_callback (data, - "dSYM file contains out of range command offset", 0); - goto end; - } - - raw_command = commands_view.view.data + offset; - command.cmd = macho_file_to_host_u32 (commands_view.bytes_swapped, - raw_command->cmd); - command.cmdsize = macho_file_to_host_u32 (commands_view.bytes_swapped, - raw_command->cmdsize); - - if (command.cmd == LC_SEGMENT_NATIVE) - { - uint32_t section_count; - size_t section_offset; - const segment_command_native_t *raw_segment; - - if (offset + sizeof (segment_command_native_t) - > commands_view.commands_total_size) - { - error_callback (data, - "dSYM file contains out of range command offset", - 0); - goto end; - } - - raw_segment = (const segment_command_native_t *) raw_command; - - if (strncmp (raw_segment->segname, "__DWARF", - sizeof (raw_segment->segname)) == 0) - { - section_count = macho_file_to_host_u32 ( - commands_view.bytes_swapped, - raw_segment->nsects); - - section_offset = offset + sizeof (segment_command_native_t); - - // Search sections for relevant DWARF section names - for (j = 0; j < section_count; j++) - { - const section_native_t *raw_section; - - if (section_offset + sizeof (section_native_t) > - commands_view.commands_total_size) - { - error_callback (data, - "dSYM file contains out of range command offset", - 0); - goto end; - } - - raw_section = commands_view.view.data + section_offset; - - for (k = 0; k < DEBUG_MAX; k++) - { - uintptr_t dwarf_section_end; - - if (strncmp (raw_section->sectname, - debug_section_names[k], - sizeof (raw_section->sectname)) == 0) - { - *found_dwarf = 1; - - dwarf_sections[k].file_offset = - macho_file_to_host_u32 ( - commands_view.bytes_swapped, - raw_section->offset); - dwarf_sections[k].file_size = - macho_file_to_host_usize ( - commands_view.bytes_swapped, - raw_section->size); - - if (min_dwarf_offset == 0 || - dwarf_sections[k].file_offset < - min_dwarf_offset) - min_dwarf_offset = dwarf_sections[k].file_offset; - - dwarf_section_end = - dwarf_sections[k].file_offset + - dwarf_sections[k].file_size; - if (dwarf_section_end > max_dwarf_offset) - max_dwarf_offset = dwarf_section_end; - - break; - } - } - - section_offset += sizeof (section_native_t); - } - - break; - } - } - - offset += command.cmdsize; - } - - if (!*found_dwarf) - { - // No DWARF in this file - ret = 1; - goto end; - } - - if (!macho_get_view (state, dwarf_descriptor, (off_t) min_dwarf_offset, - max_dwarf_offset - min_dwarf_offset, error_callback, - data, &commands_view, &dwarf_view)) - goto end; - dwarf_view_valid = 1; - - for (i = 0; i < DEBUG_MAX; i++) - { - if (dwarf_sections[i].file_offset == 0) - dwarf_sections[i].data = NULL; - else - dwarf_sections[i].data = - dwarf_view.data + dwarf_sections[i].file_offset - min_dwarf_offset; - } - - if (!backtrace_dwarf_add (state, vmslide, - dwarf_sections[DEBUG_INFO].data, - dwarf_sections[DEBUG_INFO].file_size, - dwarf_sections[DEBUG_LINE].data, - dwarf_sections[DEBUG_LINE].file_size, - dwarf_sections[DEBUG_ABBREV].data, - dwarf_sections[DEBUG_ABBREV].file_size, - dwarf_sections[DEBUG_RANGES].data, - dwarf_sections[DEBUG_RANGES].file_size, - dwarf_sections[DEBUG_STR].data, - dwarf_sections[DEBUG_STR].file_size, - ((__DARWIN_BYTE_ORDER == __DARWIN_BIG_ENDIAN) - ^ commands_view.bytes_swapped), - error_callback, data, fileline_fn)) - goto end; - - // Don't release the DWARF view because it is still in use - dwarf_descriptor_valid = 0; - dwarf_view_valid = 0; - ret = 1; - -end: - if (dwarf_descriptor_valid) - backtrace_close (dwarf_descriptor, error_callback, data); - if (commands_view_valid) - backtrace_release_view (state, &commands_view.view, error_callback, data); - if (dwarf_view_valid) - backtrace_release_view (state, &dwarf_view, error_callback, data); - return ret; -} - -int -macho_try_dsym (struct backtrace_state *state, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn, uuid_t *executable_uuid, - uintptr_t base_address, uintptr_t max_image_address, - intptr_t vmslide, char *dsym_filename, int *matched, - int *found_sym, int *found_dwarf) -{ - int ret = 0; - char dwarf_image_dir_path[PATH_MAX]; - DIR *dwarf_image_dir; - int dwarf_image_dir_valid = 0; - struct dirent *directory_entry; - char dwarf_filename[PATH_MAX]; - int dwarf_matched; - int dwarf_had_sym; - int dwarf_had_dwarf; - - *matched = 0; - *found_sym = 0; - *found_dwarf = 0; - - strncpy (dwarf_image_dir_path, dsym_filename, PATH_MAX); - strncat (dwarf_image_dir_path, "/Contents/Resources/DWARF", PATH_MAX); - - if (!(dwarf_image_dir = opendir (dwarf_image_dir_path))) - { - error_callback (data, "could not open DWARF directory in dSYM", - 0); - goto end; - } - dwarf_image_dir_valid = 1; - - while ((directory_entry = readdir (dwarf_image_dir))) - { - if (directory_entry->d_type != DT_REG) - continue; - - strncpy (dwarf_filename, dwarf_image_dir_path, PATH_MAX); - strncat (dwarf_filename, "/", PATH_MAX); - strncat (dwarf_filename, directory_entry->d_name, PATH_MAX); - - if (!macho_try_dwarf (state, error_callback, data, fileline_fn, - executable_uuid, base_address, max_image_address, - vmslide, dwarf_filename, - &dwarf_matched, &dwarf_had_sym, &dwarf_had_dwarf)) - goto end; - - if (dwarf_matched) - { - *matched = 1; - *found_sym = dwarf_had_sym; - *found_dwarf = dwarf_had_dwarf; - ret = 1; - goto end; - } - } - - // No matching DWARF in this dSYM - ret = 1; - goto end; - -end: - if (dwarf_image_dir_valid) - closedir (dwarf_image_dir); - return ret; -} - -int -macho_add (struct backtrace_state *state, - backtrace_error_callback error_callback, void *data, int descriptor, - const char *filename, fileline *fileline_fn, intptr_t vmslide, - int *found_sym, int *found_dwarf) -{ - uuid_t image_uuid; - uintptr_t image_file_base_address; - uintptr_t image_file_max_address; - uintptr_t image_actual_base_address = 0; - uintptr_t image_actual_max_address = 0; - - int ret = 0; - struct macho_commands_view commands_view; - int commands_view_valid = 0; - char executable_dirname[PATH_MAX]; - size_t filename_len; - DIR *executable_dir = NULL; - int executable_dir_valid = 0; - struct dirent *directory_entry; - char dsym_full_path[PATH_MAX]; - static const char *extension; - size_t extension_len; - ssize_t i; - - *found_sym = 0; - *found_dwarf = 0; - - // Find Mach-O commands list - int incompatible; - if (!macho_get_commands (state, descriptor, error_callback, data, - &commands_view, &incompatible)) - goto end; - commands_view_valid = 1; - - // First we need to get the uuid of our file so we can hunt down the correct - // dSYM - if (!macho_get_uuid (state, descriptor, error_callback, data, &commands_view, - &image_uuid)) - goto end; - - // Now we need to find the in memory base address. Step one is to find out - // what the executable thinks the base address is - if (!macho_get_addr_range (state, descriptor, error_callback, data, - &commands_view, - &image_file_base_address, - &image_file_max_address)) - goto end; - - image_actual_base_address = - image_file_base_address + vmslide; - image_actual_max_address = - image_file_max_address + vmslide; - - if (image_actual_base_address == 0) - { - error_callback (data, "executable file is not loaded", 0); - goto end; - } - - // Look for dSYM in our executable's directory - strncpy (executable_dirname, filename, PATH_MAX); - filename_len = strlen (executable_dirname); - for (i = filename_len - 1; i >= 0; i--) - { - if (executable_dirname[i] == '/') - { - executable_dirname[i] = '\0'; - break; - } - else if (i == 0) - { - executable_dirname[0] = '.'; - executable_dirname[1] = '\0'; - break; - } - } - - if (!(executable_dir = opendir (executable_dirname))) - { - error_callback (data, "could not open directory containing executable", - 0); - goto end; - } - executable_dir_valid = 1; - - extension = ".dSYM"; - extension_len = strlen (extension); - while ((directory_entry = readdir (executable_dir))) - { - if (directory_entry->d_namlen < extension_len) - continue; - if (strncasecmp (directory_entry->d_name + directory_entry->d_namlen - - extension_len, extension, extension_len) == 0) - { - int matched; - int dsym_had_sym; - int dsym_had_dwarf; - - // Found a dSYM - strncpy (dsym_full_path, executable_dirname, PATH_MAX); - strncat (dsym_full_path, "/", PATH_MAX); - strncat (dsym_full_path, directory_entry->d_name, PATH_MAX); - - if (!macho_try_dsym (state, error_callback, data, - fileline_fn, &image_uuid, - image_actual_base_address, - image_actual_max_address, vmslide, - dsym_full_path, - &matched, &dsym_had_sym, &dsym_had_dwarf)) - goto end; - - if (matched) - { - *found_sym = dsym_had_sym; - *found_dwarf = dsym_had_dwarf; - ret = 1; - goto end; - } - } - } - - // No matching dSYM - ret = 1; - goto end; - -end: - if (commands_view_valid) - backtrace_release_view (state, &commands_view.view, error_callback, - data); - if (executable_dir_valid) - closedir (executable_dir); - return ret; -} - -static int -macho_symbol_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct macho_symbol *entry = (const struct macho_symbol *) ventry; - uintptr_t addr; - - addr = *key; - if (addr < entry->addr) - return -1; - else if (addr >= entry->addr + entry->size) - return 1; - else - return 0; -} - -static void -macho_syminfo (struct backtrace_state *state, - uintptr_t addr, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data) -{ - struct macho_syminfo_data *edata; - struct macho_symbol *sym = NULL; - - if (!state->threaded) - { - for (edata = (struct macho_syminfo_data *) state->syminfo_data; - edata != NULL; - edata = edata->next) - { - if (addr >= edata->min_addr && addr <= edata->max_addr) - { - sym = ((struct macho_symbol *) - bsearch (&addr, edata->symbols, edata->symbol_count, - sizeof (struct macho_symbol), macho_symbol_search)); - if (sym != NULL) - break; - } - } - } - else - { - struct macho_syminfo_data **pp; - - pp = (struct macho_syminfo_data **) (void *) &state->syminfo_data; - while (1) - { - edata = backtrace_atomic_load_pointer (pp); - if (edata == NULL) - break; - - if (addr >= edata->min_addr && addr <= edata->max_addr) - { - sym = ((struct macho_symbol *) - bsearch (&addr, edata->symbols, edata->symbol_count, - sizeof (struct macho_symbol), macho_symbol_search)); - if (sym != NULL) - break; - } - - pp = &edata->next; - } - } - - if (sym == NULL) - callback (data, addr, NULL, 0, 0); - else - callback (data, addr, sym->name, sym->addr, sym->size); -} - - -static int -macho_nodebug (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t pc ATTRIBUTE_UNUSED, - backtrace_full_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no debug info in Mach-O executable", -1); - return 0; -} - -static void -macho_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t addr ATTRIBUTE_UNUSED, - backtrace_syminfo_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no symbol table in Mach-O executable", -1); -} - -int -backtrace_initialize (struct backtrace_state *state, - const char *filename, - int descriptor, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn) -{ - int ret; - fileline macho_fileline_fn = macho_nodebug; - int found_sym = 0; - int found_dwarf = 0; - uint32_t i = 0; - uint32_t loaded_image_count; - - // Add all loaded images - loaded_image_count = _dyld_image_count (); - for (i = 0; i < loaded_image_count; i++) - { - int current_found_sym; - int current_found_dwarf; - int current_descriptor; - intptr_t current_vmslide; - const char *current_name; - - current_vmslide = _dyld_get_image_vmaddr_slide (i); - current_name = _dyld_get_image_name (i); - - if (current_name == NULL || (i != 0 && current_vmslide == 0)) - continue; - - if (!(current_descriptor = - backtrace_open (current_name, error_callback, data, NULL))) - { - continue; - } - - if (macho_add (state, error_callback, data, current_descriptor, - current_name, &macho_fileline_fn, current_vmslide, - ¤t_found_sym, ¤t_found_dwarf)) - { - found_sym = found_sym || current_found_sym; - found_dwarf = found_dwarf || current_found_dwarf; - } - - backtrace_close (current_descriptor, error_callback, data); - } - - if (!state->threaded) - { - if (found_sym) - state->syminfo_fn = macho_syminfo; - else if (state->syminfo_fn == NULL) - state->syminfo_fn = macho_nosyms; - } - else - { - if (found_sym) - backtrace_atomic_store_pointer (&state->syminfo_fn, macho_syminfo); - else - (void) __sync_bool_compare_and_swap (&state->syminfo_fn, NULL, - macho_nosyms); - } - - if (!state->threaded) - { - if (state->fileline_fn == NULL || state->fileline_fn == macho_nodebug) - *fileline_fn = macho_fileline_fn; - } - else - { - fileline current_fn; - - current_fn = backtrace_atomic_load_pointer (&state->fileline_fn); - if (current_fn == NULL || current_fn == macho_nodebug) - *fileline_fn = macho_fileline_fn; - } - - return 1; -} - diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/missing b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/missing deleted file mode 100755 index 86a8fc3..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/missing +++ /dev/null @@ -1,331 +0,0 @@ -#! /bin/sh -# Common stub for a few missing GNU programs while installing. - -scriptversion=2012-01-06.13; # UTC - -# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006, -# 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc. -# Originally by Fran,cois Pinard , 1996. - -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2, or (at your option) -# any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -# As a special exception to the GNU General Public License, if you -# distribute this file as part of a program that contains a -# configuration script generated by Autoconf, you may include it under -# the same distribution terms that you use for the rest of that program. - -if test $# -eq 0; then - echo 1>&2 "Try \`$0 --help' for more information" - exit 1 -fi - -run=: -sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' -sed_minuso='s/.* -o \([^ ]*\).*/\1/p' - -# In the cases where this matters, `missing' is being run in the -# srcdir already. -if test -f configure.ac; then - configure_ac=configure.ac -else - configure_ac=configure.in -fi - -msg="missing on your system" - -case $1 in ---run) - # Try to run requested program, and just exit if it succeeds. - run= - shift - "$@" && exit 0 - # Exit code 63 means version mismatch. This often happens - # when the user try to use an ancient version of a tool on - # a file that requires a minimum version. In this case we - # we should proceed has if the program had been absent, or - # if --run hadn't been passed. - if test $? = 63; then - run=: - msg="probably too old" - fi - ;; - - -h|--h|--he|--hel|--help) - echo "\ -$0 [OPTION]... PROGRAM [ARGUMENT]... - -Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an -error status if there is no known handling for PROGRAM. - -Options: - -h, --help display this help and exit - -v, --version output version information and exit - --run try to run the given command, and emulate it if it fails - -Supported PROGRAM values: - aclocal touch file \`aclocal.m4' - autoconf touch file \`configure' - autoheader touch file \`config.h.in' - autom4te touch the output file, or create a stub one - automake touch all \`Makefile.in' files - bison create \`y.tab.[ch]', if possible, from existing .[ch] - flex create \`lex.yy.c', if possible, from existing .c - help2man touch the output file - lex create \`lex.yy.c', if possible, from existing .c - makeinfo touch the output file - yacc create \`y.tab.[ch]', if possible, from existing .[ch] - -Version suffixes to PROGRAM as well as the prefixes \`gnu-', \`gnu', and -\`g' are ignored when checking the name. - -Send bug reports to ." - exit $? - ;; - - -v|--v|--ve|--ver|--vers|--versi|--versio|--version) - echo "missing $scriptversion (GNU Automake)" - exit $? - ;; - - -*) - echo 1>&2 "$0: Unknown \`$1' option" - echo 1>&2 "Try \`$0 --help' for more information" - exit 1 - ;; - -esac - -# normalize program name to check for. -program=`echo "$1" | sed ' - s/^gnu-//; t - s/^gnu//; t - s/^g//; t'` - -# Now exit if we have it, but it failed. Also exit now if we -# don't have it and --version was passed (most likely to detect -# the program). This is about non-GNU programs, so use $1 not -# $program. -case $1 in - lex*|yacc*) - # Not GNU programs, they don't have --version. - ;; - - *) - if test -z "$run" && ($1 --version) > /dev/null 2>&1; then - # We have it, but it failed. - exit 1 - elif test "x$2" = "x--version" || test "x$2" = "x--help"; then - # Could not run --version or --help. This is probably someone - # running `$TOOL --version' or `$TOOL --help' to check whether - # $TOOL exists and not knowing $TOOL uses missing. - exit 1 - fi - ;; -esac - -# If it does not exist, or fails to run (possibly an outdated version), -# try to emulate it. -case $program in - aclocal*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified \`acinclude.m4' or \`${configure_ac}'. You might want - to install the \`Automake' and \`Perl' packages. Grab them from - any GNU archive site." - touch aclocal.m4 - ;; - - autoconf*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified \`${configure_ac}'. You might want to install the - \`Autoconf' and \`GNU m4' packages. Grab them from any GNU - archive site." - touch configure - ;; - - autoheader*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified \`acconfig.h' or \`${configure_ac}'. You might want - to install the \`Autoconf' and \`GNU m4' packages. Grab them - from any GNU archive site." - files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` - test -z "$files" && files="config.h" - touch_files= - for f in $files; do - case $f in - *:*) touch_files="$touch_files "`echo "$f" | - sed -e 's/^[^:]*://' -e 's/:.*//'`;; - *) touch_files="$touch_files $f.in";; - esac - done - touch $touch_files - ;; - - automake*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. - You might want to install the \`Automake' and \`Perl' packages. - Grab them from any GNU archive site." - find . -type f -name Makefile.am -print | - sed 's/\.am$/.in/' | - while read f; do touch "$f"; done - ;; - - autom4te*) - echo 1>&2 "\ -WARNING: \`$1' is needed, but is $msg. - You might have modified some files without having the - proper tools for further handling them. - You can get \`$1' as part of \`Autoconf' from any GNU - archive site." - - file=`echo "$*" | sed -n "$sed_output"` - test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` - if test -f "$file"; then - touch $file - else - test -z "$file" || exec >$file - echo "#! /bin/sh" - echo "# Created by GNU Automake missing as a replacement of" - echo "# $ $@" - echo "exit 0" - chmod +x $file - exit 1 - fi - ;; - - bison*|yacc*) - echo 1>&2 "\ -WARNING: \`$1' $msg. You should only need it if - you modified a \`.y' file. You may need the \`Bison' package - in order for those modifications to take effect. You can get - \`Bison' from any GNU archive site." - rm -f y.tab.c y.tab.h - if test $# -ne 1; then - eval LASTARG=\${$#} - case $LASTARG in - *.y) - SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` - if test -f "$SRCFILE"; then - cp "$SRCFILE" y.tab.c - fi - SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` - if test -f "$SRCFILE"; then - cp "$SRCFILE" y.tab.h - fi - ;; - esac - fi - if test ! -f y.tab.h; then - echo >y.tab.h - fi - if test ! -f y.tab.c; then - echo 'main() { return 0; }' >y.tab.c - fi - ;; - - lex*|flex*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified a \`.l' file. You may need the \`Flex' package - in order for those modifications to take effect. You can get - \`Flex' from any GNU archive site." - rm -f lex.yy.c - if test $# -ne 1; then - eval LASTARG=\${$#} - case $LASTARG in - *.l) - SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` - if test -f "$SRCFILE"; then - cp "$SRCFILE" lex.yy.c - fi - ;; - esac - fi - if test ! -f lex.yy.c; then - echo 'main() { return 0; }' >lex.yy.c - fi - ;; - - help2man*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified a dependency of a manual page. You may need the - \`Help2man' package in order for those modifications to take - effect. You can get \`Help2man' from any GNU archive site." - - file=`echo "$*" | sed -n "$sed_output"` - test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` - if test -f "$file"; then - touch $file - else - test -z "$file" || exec >$file - echo ".ab help2man is required to generate this page" - exit $? - fi - ;; - - makeinfo*) - echo 1>&2 "\ -WARNING: \`$1' is $msg. You should only need it if - you modified a \`.texi' or \`.texinfo' file, or any other file - indirectly affecting the aspect of the manual. The spurious - call might also be the consequence of using a buggy \`make' (AIX, - DU, IRIX). You might want to install the \`Texinfo' package or - the \`GNU make' package. Grab either from any GNU archive site." - # The file to touch is that specified with -o ... - file=`echo "$*" | sed -n "$sed_output"` - test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` - if test -z "$file"; then - # ... or it is the one specified with @setfilename ... - infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` - file=`sed -n ' - /^@setfilename/{ - s/.* \([^ ]*\) *$/\1/ - p - q - }' $infile` - # ... or it is derived from the source name (dir/f.texi becomes f.info) - test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info - fi - # If the file does not exist, the user really needs makeinfo; - # let's fail without touching anything. - test -f $file || exit 1 - touch $file - ;; - - *) - echo 1>&2 "\ -WARNING: \`$1' is needed, and is $msg. - You might have modified some files without having the - proper tools for further handling them. Check the \`README' file, - it often tells you about the needed prerequisites for installing - this package. You may also peek at any GNU archive site, in case - some other package would contain this missing \`$1' program." - exit 1 - ;; -esac - -exit 0 - -# Local variables: -# eval: (add-hook 'write-file-hooks 'time-stamp) -# time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" -# time-stamp-time-zone: "UTC" -# time-stamp-end: "; # UTC" -# End: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmap.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmap.c deleted file mode 100644 index 32fcba6..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmap.c +++ /dev/null @@ -1,325 +0,0 @@ -/* mmap.c -- Memory allocation with mmap. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* Memory allocation on systems that provide anonymous mmap. This - permits the backtrace functions to be invoked from a signal - handler, assuming that mmap is async-signal safe. */ - -#ifndef MAP_ANONYMOUS -#define MAP_ANONYMOUS MAP_ANON -#endif - -#ifndef MAP_FAILED -#define MAP_FAILED ((void *)-1) -#endif - -/* A list of free memory blocks. */ - -struct backtrace_freelist_struct -{ - /* Next on list. */ - struct backtrace_freelist_struct *next; - /* Size of this block, including this structure. */ - size_t size; -}; - -/* Free memory allocated by backtrace_alloc. */ - -static void -backtrace_free_locked (struct backtrace_state *state, void *addr, size_t size) -{ - /* Just leak small blocks. We don't have to be perfect. Don't put - more than 16 entries on the free list, to avoid wasting time - searching when allocating a block. If we have more than 16 - entries, leak the smallest entry. */ - - if (size >= sizeof (struct backtrace_freelist_struct)) - { - size_t c; - struct backtrace_freelist_struct **ppsmall; - struct backtrace_freelist_struct **pp; - struct backtrace_freelist_struct *p; - - c = 0; - ppsmall = NULL; - for (pp = &state->freelist; *pp != NULL; pp = &(*pp)->next) - { - if (ppsmall == NULL || (*pp)->size < (*ppsmall)->size) - ppsmall = pp; - ++c; - } - if (c >= 16) - { - if (size <= (*ppsmall)->size) - return; - *ppsmall = (*ppsmall)->next; - } - - p = (struct backtrace_freelist_struct *) addr; - p->next = state->freelist; - p->size = size; - state->freelist = p; - } -} - -/* Allocate memory like malloc. If ERROR_CALLBACK is NULL, don't - report an error. */ - -void * -backtrace_alloc (struct backtrace_state *state, - size_t size, backtrace_error_callback error_callback, - void *data) -{ - void *ret; - int locked; - struct backtrace_freelist_struct **pp; - size_t pagesize; - size_t asksize; - void *page; - - ret = NULL; - - /* If we can acquire the lock, then see if there is space on the - free list. If we can't acquire the lock, drop straight into - using mmap. __sync_lock_test_and_set returns the old state of - the lock, so we have acquired it if it returns 0. */ - - if (!state->threaded) - locked = 1; - else - locked = __sync_lock_test_and_set (&state->lock_alloc, 1) == 0; - - if (locked) - { - for (pp = &state->freelist; *pp != NULL; pp = &(*pp)->next) - { - if ((*pp)->size >= size) - { - struct backtrace_freelist_struct *p; - - p = *pp; - *pp = p->next; - - /* Round for alignment; we assume that no type we care about - is more than 8 bytes. */ - size = (size + 7) & ~ (size_t) 7; - if (size < p->size) - backtrace_free_locked (state, (char *) p + size, - p->size - size); - - ret = (void *) p; - - break; - } - } - - if (state->threaded) - __sync_lock_release (&state->lock_alloc); - } - - if (ret == NULL) - { - /* Allocate a new page. */ - - pagesize = getpagesize (); - asksize = (size + pagesize - 1) & ~ (pagesize - 1); - page = mmap (NULL, asksize, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - if (page == MAP_FAILED) - { - if (error_callback) - error_callback (data, "mmap", errno); - } - else - { - size = (size + 7) & ~ (size_t) 7; - if (size < asksize) - backtrace_free (state, (char *) page + size, asksize - size, - error_callback, data); - - ret = page; - } - } - - return ret; -} - -/* Free memory allocated by backtrace_alloc. */ - -void -backtrace_free (struct backtrace_state *state, void *addr, size_t size, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data ATTRIBUTE_UNUSED) -{ - int locked; - - /* If we are freeing a large aligned block, just release it back to - the system. This case arises when growing a vector for a large - binary with lots of debug info. Calling munmap here may cause us - to call mmap again if there is also a large shared library; we - just live with that. */ - if (size >= 16 * 4096) - { - size_t pagesize; - - pagesize = getpagesize (); - if (((uintptr_t) addr & (pagesize - 1)) == 0 - && (size & (pagesize - 1)) == 0) - { - /* If munmap fails for some reason, just add the block to - the freelist. */ - if (munmap (addr, size) == 0) - return; - } - } - - /* If we can acquire the lock, add the new space to the free list. - If we can't acquire the lock, just leak the memory. - __sync_lock_test_and_set returns the old state of the lock, so we - have acquired it if it returns 0. */ - - if (!state->threaded) - locked = 1; - else - locked = __sync_lock_test_and_set (&state->lock_alloc, 1) == 0; - - if (locked) - { - backtrace_free_locked (state, addr, size); - - if (state->threaded) - __sync_lock_release (&state->lock_alloc); - } -} - -/* Grow VEC by SIZE bytes. */ - -void * -backtrace_vector_grow (struct backtrace_state *state,size_t size, - backtrace_error_callback error_callback, - void *data, struct backtrace_vector *vec) -{ - void *ret; - - if (size > vec->alc) - { - size_t pagesize; - size_t alc; - void *base; - - pagesize = getpagesize (); - alc = vec->size + size; - if (vec->size == 0) - alc = 16 * size; - else if (alc < pagesize) - { - alc *= 2; - if (alc > pagesize) - alc = pagesize; - } - else - { - alc *= 2; - alc = (alc + pagesize - 1) & ~ (pagesize - 1); - } - base = backtrace_alloc (state, alc, error_callback, data); - if (base == NULL) - return NULL; - if (vec->base != NULL) - { - memcpy (base, vec->base, vec->size); - backtrace_free (state, vec->base, vec->size + vec->alc, - error_callback, data); - } - vec->base = base; - vec->alc = alc - vec->size; - } - - ret = (char *) vec->base + vec->size; - vec->size += size; - vec->alc -= size; - return ret; -} - -/* Finish the current allocation on VEC. */ - -void * -backtrace_vector_finish ( - struct backtrace_state *state ATTRIBUTE_UNUSED, - struct backtrace_vector *vec, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data ATTRIBUTE_UNUSED) -{ - void *ret; - - ret = vec->base; - vec->base = (char *) vec->base + vec->size; - vec->size = 0; - return ret; -} - -/* Release any extra space allocated for VEC. */ - -int -backtrace_vector_release (struct backtrace_state *state, - struct backtrace_vector *vec, - backtrace_error_callback error_callback, - void *data) -{ - size_t size; - size_t alc; - size_t aligned; - - /* Make sure that the block that we free is aligned on an 8-byte - boundary. */ - size = vec->size; - alc = vec->alc; - aligned = (size + 7) & ~ (size_t) 7; - alc -= aligned - size; - - backtrace_free (state, (char *) vec->base + aligned, alc, - error_callback, data); - vec->alc = 0; - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmapio.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmapio.c deleted file mode 100644 index 94e8c93..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/mmapio.c +++ /dev/null @@ -1,100 +0,0 @@ -/* mmapio.c -- File views using mmap. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -#ifndef MAP_FAILED -#define MAP_FAILED ((void *)-1) -#endif - -/* This file implements file views and memory allocation when mmap is - available. */ - -/* Create a view of SIZE bytes from DESCRIPTOR at OFFSET. */ - -int -backtrace_get_view (struct backtrace_state *state ATTRIBUTE_UNUSED, - int descriptor, off_t offset, size_t size, - backtrace_error_callback error_callback, - void *data, struct backtrace_view *view) -{ - size_t pagesize; - unsigned int inpage; - off_t pageoff; - void *map; - - pagesize = getpagesize (); - inpage = offset % pagesize; - pageoff = offset - inpage; - - size += inpage; - size = (size + (pagesize - 1)) & ~ (pagesize - 1); - - map = mmap (NULL, size, PROT_READ, MAP_PRIVATE, descriptor, pageoff); - if (map == MAP_FAILED) - { - error_callback (data, "mmap", errno); - return 0; - } - - view->data = (char *) map + inpage; - view->base = map; - view->len = size; - - return 1; -} - -/* Release a view read by backtrace_get_view. */ - -void -backtrace_release_view (struct backtrace_state *state ATTRIBUTE_UNUSED, - struct backtrace_view *view, - backtrace_error_callback error_callback, - void *data) -{ - union { - const void *cv; - void *v; - } const_cast; - - const_cast.cv = view->base; - if (munmap (const_cast.v, view->len) < 0) - error_callback (data, "munmap", errno); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/move-if-change b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/move-if-change deleted file mode 100644 index 88d9574..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/move-if-change +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/sh -# Like mv $1 $2, but if the files are the same, just delete $1. -# Status is zero if successful, nonzero otherwise. - -VERSION='2012-01-06 07:23'; # UTC -# The definition above must lie within the first 8 lines in order -# for the Emacs time-stamp write hook (at end) to update it. -# If you change this file with Emacs, please let the write hook -# do its job. Otherwise, update this string manually. - -# Copyright (C) 2002-2014 Free Software Foundation, Inc. - -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. - -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. - -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -usage="usage: $0 SOURCE DEST" - -help="$usage - or: $0 OPTION -If SOURCE is different than DEST, then move it to DEST; else remove SOURCE. - - --help display this help and exit - --version output version information and exit - -The variable CMPPROG can be used to specify an alternative to 'cmp'. - -Report bugs to ." - -version=`expr "$VERSION" : '\([^ ]*\)'` -version="move-if-change (gnulib) $version -Copyright (C) 2011 Free Software Foundation, Inc. -License GPLv3+: GNU GPL version 3 or later -This is free software: you are free to change and redistribute it. -There is NO WARRANTY, to the extent permitted by law." - -cmpprog=${CMPPROG-cmp} - -for arg -do - case $arg in - --help | --hel | --he | --h) - exec echo "$help" ;; - --version | --versio | --versi | --vers | --ver | --ve | --v) - exec echo "$version" ;; - --) - shift - break ;; - -*) - echo "$0: invalid option: $arg" >&2 - exit 1 ;; - *) - break ;; - esac -done - -test $# -eq 2 || { echo "$0: $usage" >&2; exit 1; } - -if test -r "$2" && $cmpprog -- "$1" "$2" >/dev/null; then - rm -f -- "$1" -else - if mv -f -- "$1" "$2"; then :; else - # Ignore failure due to a concurrent move-if-change. - test -r "$2" && $cmpprog -- "$1" "$2" >/dev/null && rm -f -- "$1" - fi -fi - -## Local Variables: -## eval: (add-hook 'write-file-hooks 'time-stamp) -## time-stamp-start: "VERSION='" -## time-stamp-format: "%:y-%02m-%02d %02H:%02M" -## time-stamp-time-zone: "UTC" -## time-stamp-end: "'; # UTC" -## End: diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/nounwind.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/nounwind.c deleted file mode 100644 index 0a046cc..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/nounwind.c +++ /dev/null @@ -1,66 +0,0 @@ -/* backtrace.c -- Entry point for stack backtrace library. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include - -#include "backtrace.h" - -#include "internal.h" - -/* This source file is compiled if the unwind library is not - available. */ - -int -backtrace_full (struct backtrace_state *state ATTRIBUTE_UNUSED, - int skip ATTRIBUTE_UNUSED, - backtrace_full_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, - "no stack trace because unwind library not available", - 0); - return 0; -} - -int -backtrace_simple (struct backtrace_state *state ATTRIBUTE_UNUSED, - int skip ATTRIBUTE_UNUSED, - backtrace_simple_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, - "no stack trace because unwind library not available", - 0); - return 0; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/pecoff.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/pecoff.c deleted file mode 100644 index 049d7e3..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/pecoff.c +++ /dev/null @@ -1,943 +0,0 @@ -/* pecoff.c -- Get debug data from a PE/COFFF file for backtraces. - Copyright (C) 2015-2018 Free Software Foundation, Inc. - Adapted from elf.c by Tristan Gingold, AdaCore. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* Coff file header. */ - -typedef struct { - uint16_t machine; - uint16_t number_of_sections; - uint32_t time_date_stamp; - uint32_t pointer_to_symbol_table; - uint32_t number_of_symbols; - uint16_t size_of_optional_header; - uint16_t characteristics; -} b_coff_file_header; - -/* Coff optional header. */ - -typedef struct { - uint16_t magic; - uint8_t major_linker_version; - uint8_t minor_linker_version; - uint32_t size_of_code; - uint32_t size_of_initialized_data; - uint32_t size_of_uninitialized_data; - uint32_t address_of_entry_point; - uint32_t base_of_code; - union { - struct { - uint32_t base_of_data; - uint32_t image_base; - } pe; - struct { - uint64_t image_base; - } pep; - } u; -} b_coff_optional_header; - -/* Values of magic in optional header. */ - -#define PE_MAGIC 0x10b /* PE32 executable. */ -#define PEP_MAGIC 0x20b /* PE32+ executable (for 64bit targets). */ - -/* Coff section header. */ - -typedef struct { - char name[8]; - uint32_t virtual_size; - uint32_t virtual_address; - uint32_t size_of_raw_data; - uint32_t pointer_to_raw_data; - uint32_t pointer_to_relocations; - uint32_t pointer_to_line_numbers; - uint16_t number_of_relocations; - uint16_t number_of_line_numbers; - uint32_t characteristics; -} b_coff_section_header; - -/* Coff symbol name. */ - -typedef union { - char short_name[8]; - struct { - unsigned char zeroes[4]; - unsigned char off[4]; - } long_name; -} b_coff_name; - -/* Coff symbol (external representation which is unaligned). */ - -typedef struct { - b_coff_name name; - unsigned char value[4]; - unsigned char section_number[2]; - unsigned char type[2]; - unsigned char storage_class; - unsigned char number_of_aux_symbols; -} b_coff_external_symbol; - -/* Symbol types. */ - -#define N_TBSHFT 4 /* Shift for the derived type. */ -#define IMAGE_SYM_DTYPE_FUNCTION 2 /* Function derived type. */ - -/* Size of a coff symbol. */ - -#define SYM_SZ 18 - -/* Coff symbol, internal representation (aligned). */ - -typedef struct { - const char *name; - uint32_t value; - int16_t sec; - uint16_t type; - uint16_t sc; -} b_coff_internal_symbol; - -/* An index of sections we care about. */ - -enum debug_section -{ - DEBUG_INFO, - DEBUG_LINE, - DEBUG_ABBREV, - DEBUG_RANGES, - DEBUG_STR, - DEBUG_MAX -}; - -/* Names of sections, indexed by enum debug_section. */ - -static const char * const debug_section_names[DEBUG_MAX] = -{ - ".debug_info", - ".debug_line", - ".debug_abbrev", - ".debug_ranges", - ".debug_str" -}; - -/* Information we gather for the sections we care about. */ - -struct debug_section_info -{ - /* Section file offset. */ - off_t offset; - /* Section size. */ - size_t size; - /* Section contents, after read from file. */ - const unsigned char *data; -}; - -/* Information we keep for an coff symbol. */ - -struct coff_symbol -{ - /* The name of the symbol. */ - const char *name; - /* The address of the symbol. */ - uintptr_t address; -}; - -/* Information to pass to coff_syminfo. */ - -struct coff_syminfo_data -{ - /* Symbols for the next module. */ - struct coff_syminfo_data *next; - /* The COFF symbols, sorted by address. */ - struct coff_symbol *symbols; - /* The number of symbols. */ - size_t count; -}; - -/* A dummy callback function used when we can't find any debug info. */ - -static int -coff_nodebug (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t pc ATTRIBUTE_UNUSED, - backtrace_full_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no debug info in PE/COFF executable", -1); - return 0; -} - -/* A dummy callback function used when we can't find a symbol - table. */ - -static void -coff_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t addr ATTRIBUTE_UNUSED, - backtrace_syminfo_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no symbol table in PE/COFF executable", -1); -} - -/* Read a potentially unaligned 4 byte word at P, using native endianness. */ - -static uint32_t -coff_read4 (const unsigned char *p) -{ - uint32_t res; - - memcpy (&res, p, 4); - return res; -} - -/* Read a potentially unaligned 2 byte word at P, using native endianness. - All 2 byte word in symbols are always aligned, but for coherency all - fields are declared as char arrays. */ - -static uint16_t -coff_read2 (const unsigned char *p) -{ - uint16_t res; - - memcpy (&res, p, sizeof (res)); - return res; -} - -/* Return the length (without the trailing 0) of a COFF short name. */ - -static size_t -coff_short_name_len (const char *name) -{ - int i; - - for (i = 0; i < 8; i++) - if (name[i] == 0) - return i; - return 8; -} - -/* Return true iff COFF short name CNAME is the same as NAME (a NUL-terminated - string). */ - -static int -coff_short_name_eq (const char *name, const char *cname) -{ - int i; - - for (i = 0; i < 8; i++) - { - if (name[i] != cname[i]) - return 0; - if (name[i] == 0) - return 1; - } - return name[8] == 0; -} - -/* Return true iff NAME is the same as string at offset OFF. */ - -static int -coff_long_name_eq (const char *name, unsigned int off, - struct backtrace_view *str_view) -{ - if (off >= str_view->len) - return 0; - return strcmp (name, (const char *)str_view->data + off) == 0; -} - -/* Compare struct coff_symbol for qsort. */ - -static int -coff_symbol_compare (const void *v1, const void *v2) -{ - const struct coff_symbol *e1 = (const struct coff_symbol *) v1; - const struct coff_symbol *e2 = (const struct coff_symbol *) v2; - - if (e1->address < e2->address) - return -1; - else if (e1->address > e2->address) - return 1; - else - return 0; -} - -/* Convert SYM to internal (and aligned) format ISYM, using string table - from STRTAB and STRTAB_SIZE, and number of sections SECTS_NUM. - Return -1 in case of error (invalid section number or string index). */ - -static int -coff_expand_symbol (b_coff_internal_symbol *isym, - const b_coff_external_symbol *sym, - uint16_t sects_num, - const unsigned char *strtab, size_t strtab_size) -{ - isym->type = coff_read2 (sym->type); - isym->sec = coff_read2 (sym->section_number); - isym->sc = sym->storage_class; - - if (isym->sec > 0 && (uint16_t) isym->sec > sects_num) - return -1; - if (sym->name.short_name[0] != 0) - isym->name = sym->name.short_name; - else - { - uint32_t off = coff_read4 (sym->name.long_name.off); - - if (off >= strtab_size) - return -1; - isym->name = (const char *) strtab + off; - } - return 0; -} - -/* Return true iff SYM is a defined symbol for a function. Data symbols - aren't considered because they aren't easily identified (same type as - section names, presence of symbols defined by the linker script). */ - -static int -coff_is_function_symbol (const b_coff_internal_symbol *isym) -{ - return (isym->type >> N_TBSHFT) == IMAGE_SYM_DTYPE_FUNCTION - && isym->sec > 0; -} - -/* Initialize the symbol table info for coff_syminfo. */ - -static int -coff_initialize_syminfo (struct backtrace_state *state, - uintptr_t base_address, - const b_coff_section_header *sects, size_t sects_num, - const b_coff_external_symbol *syms, size_t syms_size, - const unsigned char *strtab, size_t strtab_size, - backtrace_error_callback error_callback, - void *data, struct coff_syminfo_data *sdata) -{ - size_t syms_count; - char *coff_symstr; - size_t coff_symstr_len; - size_t coff_symbol_count; - size_t coff_symbol_size; - struct coff_symbol *coff_symbols; - struct coff_symbol *coff_sym; - char *coff_str; - size_t i; - - syms_count = syms_size / SYM_SZ; - - /* We only care about function symbols. Count them. Also count size of - strings for in-symbol names. */ - coff_symbol_count = 0; - coff_symstr_len = 0; - for (i = 0; i < syms_count; ++i) - { - const b_coff_external_symbol *asym = &syms[i]; - b_coff_internal_symbol isym; - - if (coff_expand_symbol (&isym, asym, sects_num, strtab, strtab_size) < 0) - { - error_callback (data, "invalid section or offset in coff symbol", 0); - return 0; - } - if (coff_is_function_symbol (&isym)) - { - ++coff_symbol_count; - if (asym->name.short_name[0] != 0) - coff_symstr_len += coff_short_name_len (asym->name.short_name) + 1; - } - - i += asym->number_of_aux_symbols; - } - - coff_symbol_size = (coff_symbol_count + 1) * sizeof (struct coff_symbol); - coff_symbols = ((struct coff_symbol *) - backtrace_alloc (state, coff_symbol_size, error_callback, - data)); - if (coff_symbols == NULL) - return 0; - - /* Allocate memory for symbols strings. */ - if (coff_symstr_len > 0) - { - coff_symstr = ((char *) - backtrace_alloc (state, coff_symstr_len, error_callback, - data)); - if (coff_symstr == NULL) - { - backtrace_free (state, coff_symbols, coff_symbol_size, - error_callback, data); - return 0; - } - } - else - coff_symstr = NULL; - - /* Copy symbols. */ - coff_sym = coff_symbols; - coff_str = coff_symstr; - for (i = 0; i < syms_count; ++i) - { - const b_coff_external_symbol *asym = &syms[i]; - b_coff_internal_symbol isym; - - if (coff_expand_symbol (&isym, asym, sects_num, strtab, strtab_size)) - { - /* Should not fail, as it was already tested in the previous - loop. */ - abort (); - } - if (coff_is_function_symbol (&isym)) - { - const char *name; - int16_t secnum; - - if (asym->name.short_name[0] != 0) - { - size_t len = coff_short_name_len (isym.name); - name = coff_str; - memcpy (coff_str, isym.name, len); - coff_str[len] = 0; - coff_str += len + 1; - } - else - name = isym.name; - - /* Strip leading '_'. */ - if (name[0] == '_') - name++; - - /* Symbol value is section relative, so we need to read the address - of its section. */ - secnum = coff_read2 (asym->section_number); - - coff_sym->name = name; - coff_sym->address = (coff_read4 (asym->value) - + sects[secnum - 1].virtual_address - + base_address); - coff_sym++; - } - - i += asym->number_of_aux_symbols; - } - - /* End of symbols marker. */ - coff_sym->name = NULL; - coff_sym->address = -1; - - backtrace_qsort (coff_symbols, coff_symbol_count, - sizeof (struct coff_symbol), coff_symbol_compare); - - sdata->next = NULL; - sdata->symbols = coff_symbols; - sdata->count = coff_symbol_count; - - return 1; -} - -/* Add EDATA to the list in STATE. */ - -static void -coff_add_syminfo_data (struct backtrace_state *state, - struct coff_syminfo_data *sdata) -{ - if (!state->threaded) - { - struct coff_syminfo_data **pp; - - for (pp = (struct coff_syminfo_data **) (void *) &state->syminfo_data; - *pp != NULL; - pp = &(*pp)->next) - ; - *pp = sdata; - } - else - { - while (1) - { - struct coff_syminfo_data **pp; - - pp = (struct coff_syminfo_data **) (void *) &state->syminfo_data; - - while (1) - { - struct coff_syminfo_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, sdata)) - break; - } - } -} - -/* Compare an ADDR against an elf_symbol for bsearch. We allocate one - extra entry in the array so that this can look safely at the next - entry. */ - -static int -coff_symbol_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct coff_symbol *entry = (const struct coff_symbol *) ventry; - uintptr_t addr; - - addr = *key; - if (addr < entry->address) - return -1; - else if (addr >= entry[1].address) - return 1; - else - return 0; -} - -/* Return the symbol name and value for an ADDR. */ - -static void -coff_syminfo (struct backtrace_state *state, uintptr_t addr, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data) -{ - struct coff_syminfo_data *sdata; - struct coff_symbol *sym = NULL; - - if (!state->threaded) - { - for (sdata = (struct coff_syminfo_data *) state->syminfo_data; - sdata != NULL; - sdata = sdata->next) - { - sym = ((struct coff_symbol *) - bsearch (&addr, sdata->symbols, sdata->count, - sizeof (struct coff_symbol), coff_symbol_search)); - if (sym != NULL) - break; - } - } - else - { - struct coff_syminfo_data **pp; - - pp = (struct coff_syminfo_data **) (void *) &state->syminfo_data; - while (1) - { - sdata = backtrace_atomic_load_pointer (pp); - if (sdata == NULL) - break; - - sym = ((struct coff_symbol *) - bsearch (&addr, sdata->symbols, sdata->count, - sizeof (struct coff_symbol), coff_symbol_search)); - if (sym != NULL) - break; - - pp = &sdata->next; - } - } - - if (sym == NULL) - callback (data, addr, NULL, 0, 0); - else - callback (data, addr, sym->name, sym->address, 0); -} - -/* Add the backtrace data for one PE/COFF file. Returns 1 on success, - 0 on failure (in both cases descriptor is closed). */ - -static int -coff_add (struct backtrace_state *state, int descriptor, - backtrace_error_callback error_callback, void *data, - fileline *fileline_fn, int *found_sym, int *found_dwarf) -{ - struct backtrace_view fhdr_view; - off_t fhdr_off; - int magic_ok; - b_coff_file_header fhdr; - off_t opt_sects_off; - size_t opt_sects_size; - unsigned int sects_num; - struct backtrace_view sects_view; - int sects_view_valid; - const b_coff_optional_header *opt_hdr; - const b_coff_section_header *sects; - struct backtrace_view str_view; - int str_view_valid; - uint32_t str_size; - off_t str_off; - // NOTE: upstream doesn't have `{0}`, this is a fix for Rust issue #39468. - // If syms_view is not initialized, then `free(syms_view.base)` may segfault later. - struct backtrace_view syms_view = {0}; - off_t syms_off; - size_t syms_size; - int syms_view_valid; - unsigned int syms_num; - unsigned int i; - struct debug_section_info sections[DEBUG_MAX]; - off_t min_offset; - off_t max_offset; - struct backtrace_view debug_view; - int debug_view_valid; - uintptr_t image_base; - - *found_sym = 0; - *found_dwarf = 0; - - sects_view_valid = 0; - syms_view_valid = 0; - str_view_valid = 0; - debug_view_valid = 0; - - /* Map the MS-DOS stub (if any) and extract file header offset. */ - if (!backtrace_get_view (state, descriptor, 0, 0x40, error_callback, - data, &fhdr_view)) - goto fail; - - { - const unsigned char *vptr = fhdr_view.data; - - if (vptr[0] == 'M' && vptr[1] == 'Z') - fhdr_off = coff_read4 (vptr + 0x3c); - else - fhdr_off = 0; - } - - backtrace_release_view (state, &fhdr_view, error_callback, data); - - /* Map the coff file header. */ - if (!backtrace_get_view (state, descriptor, fhdr_off, - sizeof (b_coff_file_header) + 4, - error_callback, data, &fhdr_view)) - goto fail; - - if (fhdr_off != 0) - { - const char *magic = (const char *) fhdr_view.data; - magic_ok = memcmp (magic, "PE\0", 4) == 0; - fhdr_off += 4; - - memcpy (&fhdr, fhdr_view.data + 4, sizeof fhdr); - } - else - { - memcpy (&fhdr, fhdr_view.data, sizeof fhdr); - /* TODO: test fhdr.machine for coff but non-PE platforms. */ - magic_ok = 0; - } - backtrace_release_view (state, &fhdr_view, error_callback, data); - - if (!magic_ok) - { - error_callback (data, "executable file is not COFF", 0); - goto fail; - } - - sects_num = fhdr.number_of_sections; - syms_num = fhdr.number_of_symbols; - - opt_sects_off = fhdr_off + sizeof (fhdr); - opt_sects_size = (fhdr.size_of_optional_header - + sects_num * sizeof (b_coff_section_header)); - - /* To translate PC to file/line when using DWARF, we need to find - the .debug_info and .debug_line sections. */ - - /* Read the optional header and the section headers. */ - - if (!backtrace_get_view (state, descriptor, opt_sects_off, opt_sects_size, - error_callback, data, §s_view)) - goto fail; - sects_view_valid = 1; - opt_hdr = (const b_coff_optional_header *) sects_view.data; - sects = (const b_coff_section_header *) - (sects_view.data + fhdr.size_of_optional_header); - - if (fhdr.size_of_optional_header > sizeof (*opt_hdr)) - { - if (opt_hdr->magic == PE_MAGIC) - image_base = opt_hdr->u.pe.image_base; - else if (opt_hdr->magic == PEP_MAGIC) - image_base = opt_hdr->u.pep.image_base; - else - { - error_callback (data, "bad magic in PE optional header", 0); - goto fail; - } - } - else - image_base = 0; - - /* Read the symbol table and the string table. */ - - if (fhdr.pointer_to_symbol_table == 0) - { - /* No symbol table, no string table. */ - str_off = 0; - str_size = 0; - syms_num = 0; - syms_size = 0; - } - else - { - /* Symbol table is followed by the string table. The string table - starts with its length (on 4 bytes). - Map the symbol table and the length of the string table. */ - syms_off = fhdr.pointer_to_symbol_table; - syms_size = syms_num * SYM_SZ; - - if (!backtrace_get_view (state, descriptor, syms_off, syms_size + 4, - error_callback, data, &syms_view)) - goto fail; - syms_view_valid = 1; - - str_size = coff_read4 (syms_view.data + syms_size); - - str_off = syms_off + syms_size; - - if (str_size > 4) - { - /* Map string table (including the length word). */ - - if (!backtrace_get_view (state, descriptor, str_off, str_size, - error_callback, data, &str_view)) - goto fail; - str_view_valid = 1; - } - } - - memset (sections, 0, sizeof sections); - - /* Look for the symbol table. */ - for (i = 0; i < sects_num; ++i) - { - const b_coff_section_header *s = sects + i; - unsigned int str_off; - int j; - - if (s->name[0] == '/') - { - /* Extended section name. */ - str_off = atoi (s->name + 1); - } - else - str_off = 0; - - for (j = 0; j < (int) DEBUG_MAX; ++j) - { - const char *dbg_name = debug_section_names[j]; - int match; - - if (str_off != 0) - match = coff_long_name_eq (dbg_name, str_off, &str_view); - else - match = coff_short_name_eq (dbg_name, s->name); - if (match) - { - sections[j].offset = s->pointer_to_raw_data; - sections[j].size = s->virtual_size <= s->size_of_raw_data ? - s->virtual_size : s->size_of_raw_data; - break; - } - } - } - - if (syms_num != 0) - { - struct coff_syminfo_data *sdata; - - sdata = ((struct coff_syminfo_data *) - backtrace_alloc (state, sizeof *sdata, error_callback, data)); - if (sdata == NULL) - goto fail; - - if (!coff_initialize_syminfo (state, image_base, - sects, sects_num, - syms_view.data, syms_size, - str_view.data, str_size, - error_callback, data, sdata)) - { - backtrace_free (state, sdata, sizeof *sdata, error_callback, data); - goto fail; - } - - *found_sym = 1; - - coff_add_syminfo_data (state, sdata); - } - - backtrace_release_view (state, §s_view, error_callback, data); - sects_view_valid = 0; - if (syms_view_valid) - { - backtrace_release_view (state, &syms_view, error_callback, data); - syms_view_valid = 0; - } - - /* Read all the debug sections in a single view, since they are - probably adjacent in the file. We never release this view. */ - - min_offset = 0; - max_offset = 0; - for (i = 0; i < (int) DEBUG_MAX; ++i) - { - off_t end; - - if (sections[i].size == 0) - continue; - if (min_offset == 0 || sections[i].offset < min_offset) - min_offset = sections[i].offset; - end = sections[i].offset + sections[i].size; - if (end > max_offset) - max_offset = end; - } - if (min_offset == 0 || max_offset == 0) - { - if (!backtrace_close (descriptor, error_callback, data)) - goto fail; - *fileline_fn = coff_nodebug; - return 1; - } - - if (!backtrace_get_view (state, descriptor, min_offset, - max_offset - min_offset, - error_callback, data, &debug_view)) - goto fail; - debug_view_valid = 1; - - /* We've read all we need from the executable. */ - if (!backtrace_close (descriptor, error_callback, data)) - goto fail; - descriptor = -1; - - for (i = 0; i < (int) DEBUG_MAX; ++i) - { - if (sections[i].size == 0) - sections[i].data = NULL; - else - sections[i].data = ((const unsigned char *) debug_view.data - + (sections[i].offset - min_offset)); - } - - if (!backtrace_dwarf_add (state, /* base_address */ 0, - sections[DEBUG_INFO].data, - sections[DEBUG_INFO].size, - sections[DEBUG_LINE].data, - sections[DEBUG_LINE].size, - sections[DEBUG_ABBREV].data, - sections[DEBUG_ABBREV].size, - sections[DEBUG_RANGES].data, - sections[DEBUG_RANGES].size, - sections[DEBUG_STR].data, - sections[DEBUG_STR].size, - 0, /* FIXME */ - error_callback, data, fileline_fn)) - goto fail; - - *found_dwarf = 1; - - return 1; - - fail: - if (sects_view_valid) - backtrace_release_view (state, §s_view, error_callback, data); - if (str_view_valid) - backtrace_release_view (state, &str_view, error_callback, data); - if (syms_view_valid) - backtrace_release_view (state, &syms_view, error_callback, data); - if (debug_view_valid) - backtrace_release_view (state, &debug_view, error_callback, data); - if (descriptor != -1) - backtrace_close (descriptor, error_callback, data); - return 0; -} - -/* Initialize the backtrace data we need from an ELF executable. At - the ELF level, all we need to do is find the debug info - sections. */ - -int -backtrace_initialize (struct backtrace_state *state, - const char *filename ATTRIBUTE_UNUSED, int descriptor, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn) -{ - int ret; - int found_sym; - int found_dwarf; - fileline coff_fileline_fn; - - ret = coff_add (state, descriptor, error_callback, data, - &coff_fileline_fn, &found_sym, &found_dwarf); - if (!ret) - return 0; - - if (!state->threaded) - { - if (found_sym) - state->syminfo_fn = coff_syminfo; - else if (state->syminfo_fn == NULL) - state->syminfo_fn = coff_nosyms; - } - else - { - if (found_sym) - backtrace_atomic_store_pointer (&state->syminfo_fn, coff_syminfo); - else - __sync_bool_compare_and_swap (&state->syminfo_fn, NULL, coff_nosyms); - } - - if (!state->threaded) - { - if (state->fileline_fn == NULL || state->fileline_fn == coff_nodebug) - *fileline_fn = coff_fileline_fn; - } - else - { - fileline current_fn; - - current_fn = backtrace_atomic_load_pointer (&state->fileline_fn); - if (current_fn == NULL || current_fn == coff_nodebug) - *fileline_fn = coff_fileline_fn; - } - - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/posix.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/posix.c deleted file mode 100644 index ce441d9..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/posix.c +++ /dev/null @@ -1,100 +0,0 @@ -/* posix.c -- POSIX file I/O routines for the backtrace library. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -#ifndef O_BINARY -#define O_BINARY 0 -#endif - -#ifndef O_CLOEXEC -#define O_CLOEXEC 0 -#endif - -#ifndef FD_CLOEXEC -#define FD_CLOEXEC 1 -#endif - -/* Open a file for reading. */ - -int -backtrace_open (const char *filename, backtrace_error_callback error_callback, - void *data, int *does_not_exist) -{ - int descriptor; - - if (does_not_exist != NULL) - *does_not_exist = 0; - - descriptor = open (filename, (int) (O_RDONLY | O_BINARY | O_CLOEXEC)); - if (descriptor < 0) - { - if (does_not_exist != NULL && errno == ENOENT) - *does_not_exist = 1; - else - error_callback (data, filename, errno); - return -1; - } - -#ifdef HAVE_FCNTL - /* Set FD_CLOEXEC just in case the kernel does not support - O_CLOEXEC. It doesn't matter if this fails for some reason. - FIXME: At some point it should be safe to only do this if - O_CLOEXEC == 0. */ - fcntl (descriptor, F_SETFD, FD_CLOEXEC); -#endif - - return descriptor; -} - -/* Close DESCRIPTOR. */ - -int -backtrace_close (int descriptor, backtrace_error_callback error_callback, - void *data) -{ - if (close (descriptor) < 0) - { - error_callback (data, "close", errno); - return 0; - } - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/print.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/print.c deleted file mode 100644 index 3c6bad2..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/print.c +++ /dev/null @@ -1,92 +0,0 @@ -/* print.c -- Print the current backtrace. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* Passed to callbacks. */ - -struct print_data -{ - struct backtrace_state *state; - FILE *f; -}; - -/* Print one level of a backtrace. */ - -static int -print_callback (void *data, uintptr_t pc, const char *filename, int lineno, - const char *function) -{ - struct print_data *pdata = (struct print_data *) data; - - fprintf (pdata->f, "0x%lx %s\n\t%s:%d\n", - (unsigned long) pc, - function == NULL ? "???" : function, - filename == NULL ? "???" : filename, - lineno); - return 0; -} - -/* Print errors to stderr. */ - -static void -error_callback (void *data, const char *msg, int errnum) -{ - struct print_data *pdata = (struct print_data *) data; - - if (pdata->state->filename != NULL) - fprintf (stderr, "%s: ", pdata->state->filename); - fprintf (stderr, "libbacktrace: %s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fputc ('\n', stderr); -} - -/* Print a backtrace. */ - -void -backtrace_print (struct backtrace_state *state, int skip, FILE *f) -{ - struct print_data data; - - data.state = state; - data.f = f; - backtrace_full (state, skip + 1, print_callback, error_callback, - (void *) &data); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/read.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/read.c deleted file mode 100644 index 211d645..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/read.c +++ /dev/null @@ -1,96 +0,0 @@ -/* read.c -- File views without mmap. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* This file implements file views when mmap is not available. */ - -/* Create a view of SIZE bytes from DESCRIPTOR at OFFSET. */ - -int -backtrace_get_view (struct backtrace_state *state, int descriptor, - off_t offset, size_t size, - backtrace_error_callback error_callback, - void *data, struct backtrace_view *view) -{ - ssize_t got; - - if (lseek (descriptor, offset, SEEK_SET) < 0) - { - error_callback (data, "lseek", errno); - return 0; - } - - view->base = backtrace_alloc (state, size, error_callback, data); - if (view->base == NULL) - return 0; - view->data = view->base; - view->len = size; - - got = read (descriptor, view->base, size); - if (got < 0) - { - error_callback (data, "read", errno); - free (view->base); - return 0; - } - - if ((size_t) got < size) - { - error_callback (data, "file too short", 0); - free (view->base); - return 0; - } - - return 1; -} - -/* Release a view read by backtrace_get_view. */ - -void -backtrace_release_view (struct backtrace_state *state, - struct backtrace_view *view, - backtrace_error_callback error_callback, - void *data) -{ - backtrace_free (state, view->base, view->len, error_callback, data); - view->data = NULL; - view->base = NULL; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/simple.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/simple.c deleted file mode 100644 index 510877c..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/simple.c +++ /dev/null @@ -1,108 +0,0 @@ -/* simple.c -- The backtrace_simple function. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include "unwind.h" -#include "backtrace.h" - -/* The simple_backtrace routine. */ - -/* Data passed through _Unwind_Backtrace. */ - -struct backtrace_simple_data -{ - /* Number of frames to skip. */ - int skip; - /* Library state. */ - struct backtrace_state *state; - /* Callback routine. */ - backtrace_simple_callback callback; - /* Error callback routine. */ - backtrace_error_callback error_callback; - /* Data to pass to callback routine. */ - void *data; - /* Value to return from backtrace. */ - int ret; -}; - -/* Unwind library callback routine. This is passd to - _Unwind_Backtrace. */ - -static _Unwind_Reason_Code -simple_unwind (struct _Unwind_Context *context, void *vdata) -{ - struct backtrace_simple_data *bdata = (struct backtrace_simple_data *) vdata; - uintptr_t pc; - int ip_before_insn = 0; - -#ifdef HAVE_GETIPINFO - pc = _Unwind_GetIPInfo (context, &ip_before_insn); -#else - pc = _Unwind_GetIP (context); -#endif - - if (bdata->skip > 0) - { - --bdata->skip; - return _URC_NO_REASON; - } - - if (!ip_before_insn) - --pc; - - bdata->ret = bdata->callback (bdata->data, pc); - - if (bdata->ret != 0) - return _URC_END_OF_STACK; - - return _URC_NO_REASON; -} - -/* Get a simple stack backtrace. */ - -int -backtrace_simple (struct backtrace_state *state, int skip, - backtrace_simple_callback callback, - backtrace_error_callback error_callback, void *data) -{ - struct backtrace_simple_data bdata; - - bdata.skip = skip + 1; - bdata.state = state; - bdata.callback = callback; - bdata.error_callback = error_callback; - bdata.data = data; - bdata.ret = 0; - _Unwind_Backtrace (simple_unwind, &bdata); - return bdata.ret; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/sort.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/sort.c deleted file mode 100644 index 9121bcb..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/sort.c +++ /dev/null @@ -1,108 +0,0 @@ -/* sort.c -- Sort without allocating memory - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* The GNU glibc version of qsort allocates memory, which we must not - do if we are invoked by a signal handler. So provide our own - sort. */ - -static void -swap (char *a, char *b, size_t size) -{ - size_t i; - - for (i = 0; i < size; i++, a++, b++) - { - char t; - - t = *a; - *a = *b; - *b = t; - } -} - -void -backtrace_qsort (void *basearg, size_t count, size_t size, - int (*compar) (const void *, const void *)) -{ - char *base = (char *) basearg; - size_t i; - size_t mid; - - tail_recurse: - if (count < 2) - return; - - /* The symbol table and DWARF tables, which is all we use this - routine for, tend to be roughly sorted. Pick the middle element - in the array as our pivot point, so that we are more likely to - cut the array in half for each recursion step. */ - swap (base, base + (count / 2) * size, size); - - mid = 0; - for (i = 1; i < count; i++) - { - if ((*compar) (base, base + i * size) > 0) - { - ++mid; - if (i != mid) - swap (base + mid * size, base + i * size, size); - } - } - - if (mid > 0) - swap (base, base + mid * size, size); - - /* Recurse with the smaller array, loop with the larger one. That - ensures that our maximum stack depth is log count. */ - if (2 * mid < count) - { - backtrace_qsort (base, mid, size, compar); - base += (mid + 1) * size; - count -= mid + 1; - goto tail_recurse; - } - else - { - backtrace_qsort (base + (mid + 1) * size, count - (mid + 1), - size, compar); - count = mid; - goto tail_recurse; - } -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/state.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/state.c deleted file mode 100644 index ad360a6..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/state.c +++ /dev/null @@ -1,72 +0,0 @@ -/* state.c -- Create the backtrace state. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include - -#include "backtrace.h" -#include "backtrace-supported.h" -#include "internal.h" - -/* Create the backtrace state. This will then be passed to all the - other routines. */ - -struct backtrace_state * -backtrace_create_state (const char *filename, int threaded, - backtrace_error_callback error_callback, - void *data) -{ - struct backtrace_state init_state; - struct backtrace_state *state; - -#ifndef HAVE_SYNC_FUNCTIONS - if (threaded) - { - error_callback (data, "backtrace library does not support threads", 0); - return NULL; - } -#endif - - memset (&init_state, 0, sizeof init_state); - init_state.filename = filename; - init_state.threaded = threaded; - - state = ((struct backtrace_state *) - backtrace_alloc (&init_state, sizeof *state, error_callback, data)); - if (state == NULL) - return NULL; - *state = init_state; - - return state; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/stest.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/stest.c deleted file mode 100644 index 2eb9880..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/stest.c +++ /dev/null @@ -1,137 +0,0 @@ -/* stest.c -- Test for libbacktrace internal sort function - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include - -#include "backtrace.h" -#include "internal.h" - -/* Test the local qsort implementation. */ - -#define MAX 10 - -struct test -{ - size_t count; - int input[MAX]; - int output[MAX]; -}; - -static struct test tests[] = - { - { - 10, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } - }, - { - 9, - { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9 } - }, - { - 10, - { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, - }, - { - 9, - { 9, 8, 7, 6, 5, 4, 3, 2, 1 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - }, - { - 10, - { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 }, - { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, - }, - { - 5, - { 4, 5, 3, 1, 2 }, - { 1, 2, 3, 4, 5 }, - }, - { - 5, - { 1, 1, 1, 1, 1 }, - { 1, 1, 1, 1, 1 }, - }, - { - 5, - { 1, 1, 2, 1, 1 }, - { 1, 1, 1, 1, 2 }, - }, - { - 5, - { 2, 1, 1, 1, 1 }, - { 1, 1, 1, 1, 2 }, - }, - }; - -static int -compare (const void *a, const void *b) -{ - const int *ai = (const int *) a; - const int *bi = (const int *) b; - - return *ai - *bi; -} - -int -main (int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) -{ - int failures; - size_t i; - int a[MAX]; - - failures = 0; - for (i = 0; i < sizeof tests / sizeof tests[0]; i++) - { - memcpy (a, tests[i].input, tests[i].count * sizeof (int)); - backtrace_qsort (a, tests[i].count, sizeof (int), compare); - if (memcmp (a, tests[i].output, tests[i].count * sizeof (int)) != 0) - { - size_t j; - - fprintf (stderr, "test %d failed:", (int) i); - for (j = 0; j < tests[i].count; j++) - fprintf (stderr, " %d", a[j]); - fprintf (stderr, "\n"); - ++failures; - } - } - - exit (failures > 0 ? EXIT_FAILURE : EXIT_SUCCESS); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.c deleted file mode 100644 index 6dbef7c..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.c +++ /dev/null @@ -1,234 +0,0 @@ -/* testlib.c -- test functions for libbacktrace library - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include -#include -#include -#include - -#include "filenames.h" - -#include "backtrace.h" - -#include "testlib.h" - -/* The backtrace state. */ - -void *state; - -/* The number of failures. */ - -int failures; - -/* Return the base name in a path. */ - -const char * -base (const char *p) -{ - const char *last; - const char *s; - - last = NULL; - for (s = p; *s != '\0'; ++s) - { - if (IS_DIR_SEPARATOR (*s)) - last = s + 1; - } - return last != NULL ? last : p; -} - -/* Check an entry in a struct info array. */ - -void -check (const char *name, int index, const struct info *all, int want_lineno, - const char *want_function, const char *want_file, int *failed) -{ - if (*failed) - return; - if (all[index].filename == NULL || all[index].function == NULL) - { - fprintf (stderr, "%s: [%d]: missing file name or function name\n", - name, index); - *failed = 1; - return; - } - if (strcmp (base (all[index].filename), want_file) != 0) - { - fprintf (stderr, "%s: [%d]: got %s expected %s\n", name, index, - all[index].filename, want_file); - *failed = 1; - } - if (all[index].lineno != want_lineno) - { - fprintf (stderr, "%s: [%d]: got %d expected %d\n", name, index, - all[index].lineno, want_lineno); - *failed = 1; - } - if (strcmp (all[index].function, want_function) != 0) - { - fprintf (stderr, "%s: [%d]: got %s expected %s\n", name, index, - all[index].function, want_function); - *failed = 1; - } -} - -/* The backtrace callback function. */ - -int -callback_one (void *vdata, uintptr_t pc ATTRIBUTE_UNUSED, - const char *filename, int lineno, const char *function) -{ - struct bdata *data = (struct bdata *) vdata; - struct info *p; - - if (data->index >= data->max) - { - fprintf (stderr, "callback_one: callback called too many times\n"); - data->failed = 1; - return 1; - } - - p = &data->all[data->index]; - if (filename == NULL) - p->filename = NULL; - else - { - p->filename = strdup (filename); - assert (p->filename != NULL); - } - p->lineno = lineno; - if (function == NULL) - p->function = NULL; - else - { - p->function = strdup (function); - assert (p->function != NULL); - } - ++data->index; - - return 0; -} - -/* An error callback passed to backtrace. */ - -void -error_callback_one (void *vdata, const char *msg, int errnum) -{ - struct bdata *data = (struct bdata *) vdata; - - fprintf (stderr, "%s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fprintf (stderr, "\n"); - data->failed = 1; -} - -/* The backtrace_simple callback function. */ - -int -callback_two (void *vdata, uintptr_t pc) -{ - struct sdata *data = (struct sdata *) vdata; - - if (data->index >= data->max) - { - fprintf (stderr, "callback_two: callback called too many times\n"); - data->failed = 1; - return 1; - } - - data->addrs[data->index] = pc; - ++data->index; - - return 0; -} - -/* An error callback passed to backtrace_simple. */ - -void -error_callback_two (void *vdata, const char *msg, int errnum) -{ - struct sdata *data = (struct sdata *) vdata; - - fprintf (stderr, "%s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fprintf (stderr, "\n"); - data->failed = 1; -} - -/* The backtrace_syminfo callback function. */ - -void -callback_three (void *vdata, uintptr_t pc ATTRIBUTE_UNUSED, - const char *symname, uintptr_t symval, - uintptr_t symsize) -{ - struct symdata *data = (struct symdata *) vdata; - - if (symname == NULL) - data->name = NULL; - else - { - data->name = strdup (symname); - assert (data->name != NULL); - } - data->val = symval; - data->size = symsize; -} - -/* The backtrace_syminfo error callback function. */ - -void -error_callback_three (void *vdata, const char *msg, int errnum) -{ - struct symdata *data = (struct symdata *) vdata; - - fprintf (stderr, "%s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fprintf (stderr, "\n"); - data->failed = 1; -} - -/* The backtrace_create_state error callback function. */ - -void -error_callback_create (void *data ATTRIBUTE_UNUSED, const char *msg, - int errnum) -{ - fprintf (stderr, "%s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fprintf (stderr, "\n"); - exit (EXIT_FAILURE); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.h b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.h deleted file mode 100644 index 5094656..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/testlib.h +++ /dev/null @@ -1,110 +0,0 @@ -/* testlib.h -- Header for test functions for libbacktrace library - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#ifndef LIBBACKTRACE_TESTLIB_H -#define LIBBACKTRACE_TESTLIB_H - -/* Portable attribute syntax. Actually some of these tests probably - won't work if the attributes are not recognized. */ - -#ifndef GCC_VERSION -# define GCC_VERSION (__GNUC__ * 1000 + __GNUC_MINOR__) -#endif - -#if (GCC_VERSION < 2007) -# define __attribute__(x) -#endif - -#ifndef ATTRIBUTE_UNUSED -# define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) -#endif - -/* Used to collect backtrace info. */ - -struct info -{ - char *filename; - int lineno; - char *function; -}; - -/* Passed to backtrace callback function. */ - -struct bdata -{ - struct info *all; - size_t index; - size_t max; - int failed; -}; - -/* Passed to backtrace_simple callback function. */ - -struct sdata -{ - uintptr_t *addrs; - size_t index; - size_t max; - int failed; -}; - -/* Passed to backtrace_syminfo callback function. */ - -struct symdata -{ - const char *name; - uintptr_t val, size; - int failed; -}; - -/* The backtrace state. */ - -extern void *state; - -/* The number of failures. */ - -extern int failures; - -extern const char *base (const char *p); -extern void check (const char *name, int index, const struct info *all, - int want_lineno, const char *want_function, - const char *want_file, int *failed); -extern int callback_one (void *, uintptr_t, const char *, int, const char *); -extern void error_callback_one (void *, const char *, int); -extern int callback_two (void *, uintptr_t); -extern void error_callback_two (void *, const char *, int); -extern void callback_three (void *, uintptr_t, const char *, uintptr_t, - uintptr_t); -extern void error_callback_three (void *, const char *, int); -extern void error_callback_create (void *, const char *, int); - -#endif /* !defined(LIBBACKTRACE_TESTLIB_H) */ diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ttest.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ttest.c deleted file mode 100644 index ca55e9b..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ttest.c +++ /dev/null @@ -1,161 +0,0 @@ -/* ttest.c -- Test for libbacktrace library - Copyright (C) 2017-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -/* Test using the libbacktrace library from multiple threads. */ - -#include -#include -#include -#include - -#include - -#include "filenames.h" - -#include "backtrace.h" -#include "backtrace-supported.h" - -#include "testlib.h" - -static int f2 (int) __attribute__ ((noinline)); -static int f3 (int, int) __attribute__ ((noinline)); - -/* Test that a simple backtrace works. This is called via - pthread_create. It returns the number of failures, as void *. */ - -static void * -test1_thread (void *arg ATTRIBUTE_UNUSED) -{ - /* Returning a value here and elsewhere avoids a tailcall which - would mess up the backtrace. */ - return (void *) (uintptr_t) (f2 (__LINE__) - 2); -} - -static int -f2 (int f1line) -{ - return f3 (f1line, __LINE__) + 2; -} - -static int -f3 (int f1line, int f2line) -{ - struct info all[20]; - struct bdata data; - int f3line; - int i; - - data.all = &all[0]; - data.index = 0; - data.max = 20; - data.failed = 0; - - f3line = __LINE__ + 1; - i = backtrace_full (state, 0, callback_one, error_callback_one, &data); - - if (i != 0) - { - fprintf (stderr, "test1: unexpected return value %d\n", i); - data.failed = 1; - } - - if (data.index < 3) - { - fprintf (stderr, - "test1: not enough frames; got %zu, expected at least 3\n", - data.index); - data.failed = 1; - } - - check ("test1", 0, all, f3line, "f3", "ttest.c", &data.failed); - check ("test1", 1, all, f2line, "f2", "ttest.c", &data.failed); - check ("test1", 2, all, f1line, "test1_thread", "ttest.c", &data.failed); - - return data.failed; -} - -/* Run the test with 10 threads simultaneously. */ - -#define THREAD_COUNT 10 - -static void test1 (void) __attribute__ ((unused)); - -static void -test1 (void) -{ - pthread_t atid[THREAD_COUNT]; - int i; - int errnum; - int this_fail; - void *ret; - - for (i = 0; i < THREAD_COUNT; i++) - { - errnum = pthread_create (&atid[i], NULL, test1_thread, NULL); - if (errnum != 0) - { - fprintf (stderr, "pthread_create %d: %s\n", i, strerror (errnum)); - exit (EXIT_FAILURE); - } - } - - this_fail = 0; - for (i = 0; i < THREAD_COUNT; i++) - { - errnum = pthread_join (atid[i], &ret); - if (errnum != 0) - { - fprintf (stderr, "pthread_join %d: %s\n", i, strerror (errnum)); - exit (EXIT_FAILURE); - } - this_fail += (int) (uintptr_t) ret; - } - - printf ("%s: threaded backtrace_full noinline\n", this_fail > 0 ? "FAIL" : "PASS"); - - failures += this_fail; -} - -int -main (int argc ATTRIBUTE_UNUSED, char **argv) -{ - state = backtrace_create_state (argv[0], BACKTRACE_SUPPORTS_THREADS, - error_callback_create, NULL); - -#if BACKTRACE_SUPPORTED -#if BACKTRACE_SUPPORTS_THREADS - test1 (); -#endif -#endif - - exit (failures ? EXIT_FAILURE : EXIT_SUCCESS); -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/unknown.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/unknown.c deleted file mode 100644 index be521a8..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/unknown.c +++ /dev/null @@ -1,65 +0,0 @@ -/* unknown.c -- used when backtrace configury does not know file format. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include - -#include "backtrace.h" -#include "internal.h" - -/* A trivial routine that always fails to find fileline data. */ - -static int -unknown_fileline (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t pc, backtrace_full_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data) - -{ - return callback (data, pc, NULL, 0, NULL); -} - -/* Initialize the backtrace data when we don't know how to read the - debug info. */ - -int -backtrace_initialize (struct backtrace_state *state ATTRIBUTE_UNUSED, - const char *filename ATTRIBUTE_UNUSED, - int descriptor ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data ATTRIBUTE_UNUSED, fileline *fileline_fn) -{ - state->fileline_data = NULL; - *fileline_fn = unknown_fileline; - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/xcoff.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/xcoff.c deleted file mode 100644 index 1ae001d..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/xcoff.c +++ /dev/null @@ -1,1642 +0,0 @@ -/* xcoff.c -- Get debug data from an XCOFF file for backtraces. - Copyright (C) 2012-2018 Free Software Foundation, Inc. - Adapted from elf.c. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include - -#ifdef HAVE_LOADQUERY -#include -#endif - -#include "backtrace.h" -#include "internal.h" - -/* The configure script must tell us whether we are 32-bit or 64-bit - XCOFF. We could make this code test and support either possibility, - but there is no point. This code only works for the currently - running executable, which means that we know the XCOFF mode at - configure time. */ - -#if BACKTRACE_XCOFF_SIZE != 32 && BACKTRACE_XCOFF_SIZE != 64 -#error "Unknown BACKTRACE_XCOFF_SIZE" -#endif - -/* XCOFF file header. */ - -#if BACKTRACE_XCOFF_SIZE == 32 - -typedef struct { - uint16_t f_magic; - uint16_t f_nscns; - uint32_t f_timdat; - uint32_t f_symptr; - uint32_t f_nsyms; - uint16_t f_opthdr; - uint16_t f_flags; -} b_xcoff_filhdr; - -#define XCOFF_MAGIC 0737 - -#else /* BACKTRACE_XCOFF_SIZE != 32 */ - -typedef struct { - uint16_t f_magic; - uint16_t f_nscns; - uint32_t f_timdat; - uint64_t f_symptr; - uint16_t f_opthdr; - uint16_t f_flags; - uint32_t f_nsyms; -} b_xcoff_filhdr; - -#define XCOFF_MAGIC 0767 - -#endif /* BACKTRACE_XCOFF_SIZE != 32 */ - -#define F_SHROBJ 0x2000 /* File is a shared object. */ - -/* XCOFF section header. */ - -#if BACKTRACE_XCOFF_SIZE == 32 - -typedef struct { - char s_name[8]; - uint32_t s_paddr; - uint32_t s_vaddr; - uint32_t s_size; - uint32_t s_scnptr; - uint32_t s_relptr; - uint32_t s_lnnoptr; - uint16_t s_nreloc; - uint16_t s_nlnno; - uint32_t s_flags; -} b_xcoff_scnhdr; - -#define _OVERFLOW_MARKER 65535 - -#else /* BACKTRACE_XCOFF_SIZE != 32 */ - -typedef struct { - char name[8]; - uint64_t s_paddr; - uint64_t s_vaddr; - uint64_t s_size; - uint64_t s_scnptr; - uint64_t s_relptr; - uint64_t s_lnnoptr; - uint32_t s_nreloc; - uint32_t s_nlnno; - uint32_t s_flags; -} b_xcoff_scnhdr; - -#endif /* BACKTRACE_XCOFF_SIZE != 32 */ - -#define STYP_DWARF 0x10 /* DWARF debugging section. */ -#define STYP_TEXT 0x20 /* Executable text (code) section. */ -#define STYP_OVRFLO 0x8000 /* Line-number field overflow section. */ - -#define SSUBTYP_DWINFO 0x10000 /* DWARF info section. */ -#define SSUBTYP_DWLINE 0x20000 /* DWARF line-number section. */ -#define SSUBTYP_DWARNGE 0x50000 /* DWARF aranges section. */ -#define SSUBTYP_DWABREV 0x60000 /* DWARF abbreviation section. */ -#define SSUBTYP_DWSTR 0x70000 /* DWARF strings section. */ - -/* XCOFF symbol. */ - -#define SYMNMLEN 8 - -#if BACKTRACE_XCOFF_SIZE == 32 - -typedef struct { - union { - char _name[SYMNMLEN]; - struct { - uint32_t _zeroes; - uint32_t _offset; - } _s; - } _u; -#define n_name _u._name -#define n_zeroes _u._s._zeroes -#define n_offset_ _u._s._offset - - uint32_t n_value; - int16_t n_scnum; - uint16_t n_type; - uint8_t n_sclass; - uint8_t n_numaux; -} __attribute__ ((packed)) b_xcoff_syment; - -#else /* BACKTRACE_XCOFF_SIZE != 32 */ - -typedef struct { - uint64_t n_value; - uint32_t n_offset_; - int16_t n_scnum; - uint16_t n_type; - uint8_t n_sclass; - uint8_t n_numaux; -} __attribute__ ((packed)) b_xcoff_syment; - -#endif /* BACKTRACE_XCOFF_SIZE != 32 */ - -#define SYMESZ 18 - -#define C_EXT 2 /* External symbol. */ -#define C_FCN 101 /* Beginning or end of function. */ -#define C_FILE 103 /* Source file name. */ -#define C_HIDEXT 107 /* Unnamed external symbol. */ -#define C_BINCL 108 /* Beginning of include file. */ -#define C_EINCL 109 /* End of include file. */ -#define C_WEAKEXT 111 /* Weak external symbol. */ - -#define ISFCN(x) ((x) & 0x0020) - -/* XCOFF AUX entry. */ - -#define AUXESZ 18 -#define FILNMLEN 14 - -typedef union { -#if BACKTRACE_XCOFF_SIZE == 32 - struct { - uint16_t pad; - uint16_t x_lnnohi; - uint16_t x_lnno; - } x_block; -#else - struct { - uint32_t x_lnno; - } x_block; -#endif - union { - char x_fname[FILNMLEN]; - struct { - uint32_t x_zeroes; - uint32_t x_offset; - char pad[FILNMLEN-8]; - uint8_t x_ftype; - } _x; - } x_file; -#if BACKTRACE_XCOFF_SIZE == 32 - struct { - uint32_t x_exptr; - uint32_t x_fsize; - uint32_t x_lnnoptr; - uint32_t x_endndx; - } x_fcn; -#else - struct { - uint64_t x_lnnoptr; - uint32_t x_fsize; - uint32_t x_endndx; - } x_fcn; -#endif - struct { - uint8_t pad[AUXESZ-1]; - uint8_t x_auxtype; - } x_auxtype; -} __attribute__ ((packed)) b_xcoff_auxent; - -/* XCOFF line number entry. */ - -#if BACKTRACE_XCOFF_SIZE == 32 - -typedef struct { - union { - uint32_t l_symndx; - uint32_t l_paddr; - } l_addr; - uint16_t l_lnno; -} b_xcoff_lineno; - -#define LINESZ 6 - -#else /* BACKTRACE_XCOFF_SIZE != 32 */ - -typedef struct { - union { - uint32_t l_symndx; - uint64_t l_paddr; - } l_addr; - uint32_t l_lnno; -} b_xcoff_lineno; - -#define LINESZ 12 - -#endif /* BACKTRACE_XCOFF_SIZE != 32 */ - -#if BACKTRACE_XCOFF_SIZE == 32 -#define XCOFF_AIX_TEXTBASE 0x10000000u -#else -#define XCOFF_AIX_TEXTBASE 0x100000000ul -#endif - -/* AIX big archive fixed-length header. */ - -#define AIAMAGBIG "\n" - -typedef struct { - char fl_magic[8]; /* Archive magic string. */ - char fl_memoff[20]; /* Offset to member table. */ - char fl_gstoff[20]; /* Offset to global symbol table. */ - char fl_gst64off[20]; /* Offset to global symbol table for 64-bit objects. */ - char fl_fstmoff[20]; /* Offset to first archive member. */ - char fl_freeoff[20]; /* Offset to first member on free list. */ -} b_ar_fl_hdr; - -/* AIX big archive file member header. */ - -typedef struct { - char ar_size[20]; /* File member size - decimal. */ - char ar_nxtmem[20]; /* Next member offset - decimal. */ - char ar_prvmem[20]; /* Previous member offset - decimal. */ - char ar_date[12]; /* File member date - decimal. */ - char ar_uid[12]; /* File member userid - decimal. */ - char ar_gid[12]; /* File member group id - decimal. */ - char ar_mode[12]; /* File member mode - octal. */ - char ar_namlen[4]; /* File member name length - decimal. */ - char ar_name[2]; /* Start of member name. */ -} b_ar_hdr; - - -/* Information we keep for an XCOFF symbol. */ - -struct xcoff_symbol -{ - /* The name of the symbol. */ - const char *name; - /* The address of the symbol. */ - uintptr_t address; - /* The size of the symbol. */ - size_t size; -}; - -/* Information to pass to xcoff_syminfo. */ - -struct xcoff_syminfo_data -{ - /* Symbols for the next module. */ - struct xcoff_syminfo_data *next; - /* The XCOFF symbols, sorted by address. */ - struct xcoff_symbol *symbols; - /* The number of symbols. */ - size_t count; -}; - -/* Information about an include file. */ - -struct xcoff_incl -{ - /* File name. */ - const char *filename; - /* Offset to first line number from the include file. */ - uintptr_t begin; - /* Offset to last line number from the include file. */ - uintptr_t end; -}; - -/* A growable vector of include files information. */ - -struct xcoff_incl_vector -{ - /* Memory. This is an array of struct xcoff_incl. */ - struct backtrace_vector vec; - /* Number of include files. */ - size_t count; -}; - -/* Map a single PC value to a file/function/line. */ - -struct xcoff_line -{ - /* PC. */ - uintptr_t pc; - /* File name. Many entries in the array are expected to point to - the same file name. */ - const char *filename; - /* Function name. */ - const char *function; - /* Line number. */ - int lineno; -}; - -/* A growable vector of line number information. This is used while - reading the line numbers. */ - -struct xcoff_line_vector -{ - /* Memory. This is an array of struct xcoff_line. */ - struct backtrace_vector vec; - /* Number of valid mappings. */ - size_t count; -}; - -/* The information we need to map a PC to a file and line. */ - -struct xcoff_fileline_data -{ - /* The data for the next file we know about. */ - struct xcoff_fileline_data *next; - /* Line number information. */ - struct xcoff_line_vector vec; -}; - -/* An index of DWARF sections we care about. */ - -enum dwarf_section -{ - DWSECT_INFO, - DWSECT_LINE, - DWSECT_ABBREV, - DWSECT_RANGES, - DWSECT_STR, - DWSECT_MAX -}; - -/* Information we gather for the DWARF sections we care about. */ - -struct dwsect_info -{ - /* Section file offset. */ - off_t offset; - /* Section size. */ - size_t size; - /* Section contents, after read from file. */ - const unsigned char *data; -}; - -/* A dummy callback function used when we can't find any debug info. */ - -static int -xcoff_nodebug (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t pc ATTRIBUTE_UNUSED, - backtrace_full_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no debug info in XCOFF executable", -1); - return 0; -} - -/* A dummy callback function used when we can't find a symbol - table. */ - -static void -xcoff_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED, - uintptr_t addr ATTRIBUTE_UNUSED, - backtrace_syminfo_callback callback ATTRIBUTE_UNUSED, - backtrace_error_callback error_callback, void *data) -{ - error_callback (data, "no symbol table in XCOFF executable", -1); -} - -/* Compare struct xcoff_symbol for qsort. */ - -static int -xcoff_symbol_compare (const void *v1, const void *v2) -{ - const struct xcoff_symbol *e1 = (const struct xcoff_symbol *) v1; - const struct xcoff_symbol *e2 = (const struct xcoff_symbol *) v2; - - if (e1->address < e2->address) - return -1; - else if (e1->address > e2->address) - return 1; - else - return 0; -} - -/* Compare an ADDR against an xcoff_symbol for bsearch. */ - -static int -xcoff_symbol_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct xcoff_symbol *entry = (const struct xcoff_symbol *) ventry; - uintptr_t addr; - - addr = *key; - if (addr < entry->address) - return -1; - else if ((entry->size == 0 && addr > entry->address) - || (entry->size > 0 && addr >= entry->address + entry->size)) - return 1; - else - return 0; -} - -/* Add XDATA to the list in STATE. */ - -static void -xcoff_add_syminfo_data (struct backtrace_state *state, - struct xcoff_syminfo_data *xdata) -{ - if (!state->threaded) - { - struct xcoff_syminfo_data **pp; - - for (pp = (struct xcoff_syminfo_data **) (void *) &state->syminfo_data; - *pp != NULL; - pp = &(*pp)->next) - ; - *pp = xdata; - } - else - { - while (1) - { - struct xcoff_syminfo_data **pp; - - pp = (struct xcoff_syminfo_data **) (void *) &state->syminfo_data; - - while (1) - { - struct xcoff_syminfo_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, xdata)) - break; - } - } -} - -/* Return the symbol name and value for an ADDR. */ - -static void -xcoff_syminfo (struct backtrace_state *state ATTRIBUTE_UNUSED, uintptr_t addr, - backtrace_syminfo_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data) -{ - struct xcoff_syminfo_data *edata; - struct xcoff_symbol *sym = NULL; - - if (!state->threaded) - { - for (edata = (struct xcoff_syminfo_data *) state->syminfo_data; - edata != NULL; - edata = edata->next) - { - sym = ((struct xcoff_symbol *) - bsearch (&addr, edata->symbols, edata->count, - sizeof (struct xcoff_symbol), xcoff_symbol_search)); - if (sym != NULL) - break; - } - } - else - { - struct xcoff_syminfo_data **pp; - - pp = (struct xcoff_syminfo_data **) (void *) &state->syminfo_data; - while (1) - { - edata = backtrace_atomic_load_pointer (pp); - if (edata == NULL) - break; - - sym = ((struct xcoff_symbol *) - bsearch (&addr, edata->symbols, edata->count, - sizeof (struct xcoff_symbol), xcoff_symbol_search)); - if (sym != NULL) - break; - - pp = &edata->next; - } - } - - if (sym == NULL) - callback (data, addr, NULL, 0, 0); - else - callback (data, addr, sym->name, sym->address, sym->size); -} - -/* Return the name of an XCOFF symbol. */ - -static const char * -xcoff_symname (const b_xcoff_syment *asym, - const unsigned char *strtab, size_t strtab_size) -{ -#if BACKTRACE_XCOFF_SIZE == 32 - if (asym->n_zeroes != 0) - { - /* Make a copy as we will release the symtab view. */ - char name[SYMNMLEN+1]; - strncpy (name, asym->n_name, SYMNMLEN); - name[SYMNMLEN] = '\0'; - return strdup (name); - } -#endif - if (asym->n_sclass & 0x80) - return NULL; /* .debug */ - if (asym->n_offset_ >= strtab_size) - return NULL; - return (const char *) strtab + asym->n_offset_; -} - -/* Initialize the symbol table info for xcoff_syminfo. */ - -static int -xcoff_initialize_syminfo (struct backtrace_state *state, - uintptr_t base_address, - const b_xcoff_scnhdr *sects, - const b_xcoff_syment *syms, size_t nsyms, - const unsigned char *strtab, size_t strtab_size, - backtrace_error_callback error_callback, void *data, - struct xcoff_syminfo_data *sdata) -{ - size_t xcoff_symbol_count; - size_t xcoff_symbol_size; - struct xcoff_symbol *xcoff_symbols; - size_t i; - unsigned int j; - - /* We only care about function symbols. Count them. */ - xcoff_symbol_count = 0; - for (i = 0; i < nsyms; ++i) - { - const b_xcoff_syment *asym = &syms[i]; - if ((asym->n_sclass == C_EXT || asym->n_sclass == C_HIDEXT - || asym->n_sclass == C_WEAKEXT) - && ISFCN (asym->n_type) && asym->n_numaux > 0 && asym->n_scnum > 0) - ++xcoff_symbol_count; - - i += asym->n_numaux; - } - - xcoff_symbol_size = xcoff_symbol_count * sizeof (struct xcoff_symbol); - xcoff_symbols = ((struct xcoff_symbol *) - backtrace_alloc (state, xcoff_symbol_size, error_callback, - data)); - if (xcoff_symbols == NULL) - return 0; - - j = 0; - for (i = 0; i < nsyms; ++i) - { - const b_xcoff_syment *asym = &syms[i]; - if ((asym->n_sclass == C_EXT || asym->n_sclass == C_HIDEXT - || asym->n_sclass == C_WEAKEXT) - && ISFCN (asym->n_type) && asym->n_numaux > 0 && asym->n_scnum > 0) - { - const b_xcoff_auxent *aux = (const b_xcoff_auxent *) (asym + 1); - xcoff_symbols[j].name = xcoff_symname (asym, strtab, strtab_size); - xcoff_symbols[j].address = base_address + asym->n_value - - sects[asym->n_scnum - 1].s_paddr; - /* x_fsize will be 0 if there is no debug information. */ - xcoff_symbols[j].size = aux->x_fcn.x_fsize; - ++j; - } - - i += asym->n_numaux; - } - - backtrace_qsort (xcoff_symbols, xcoff_symbol_count, - sizeof (struct xcoff_symbol), xcoff_symbol_compare); - - sdata->next = NULL; - sdata->symbols = xcoff_symbols; - sdata->count = xcoff_symbol_count; - - return 1; -} - -/* Compare struct xcoff_line for qsort. */ - -static int -xcoff_line_compare (const void *v1, const void *v2) -{ - const struct xcoff_line *ln1 = (const struct xcoff_line *) v1; - const struct xcoff_line *ln2 = (const struct xcoff_line *) v2; - - if (ln1->pc < ln2->pc) - return -1; - else if (ln1->pc > ln2->pc) - return 1; - else - return 0; -} - -/* Find a PC in a line vector. We always allocate an extra entry at - the end of the lines vector, so that this routine can safely look - at the next entry. */ - -static int -xcoff_line_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct xcoff_line *entry = (const struct xcoff_line *) ventry; - uintptr_t pc; - - pc = *key; - if (pc < entry->pc) - return -1; - else if ((entry + 1)->pc == (uintptr_t) -1 || pc >= (entry + 1)->pc) - return 1; - else - return 0; -} - -/* Look for a PC in the line vector for one module. On success, - call CALLBACK and return whatever it returns. On error, call - ERROR_CALLBACK and return 0. Sets *FOUND to 1 if the PC is found, - 0 if not. */ - -static int -xcoff_lookup_pc (struct backtrace_state *state ATTRIBUTE_UNUSED, - struct xcoff_fileline_data *fdata, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback ATTRIBUTE_UNUSED, - void *data, int *found) -{ - const struct xcoff_line *ln; - const char *function; - - *found = 1; - - ln = (struct xcoff_line *) bsearch (&pc, fdata->vec.vec.base, - fdata->vec.count, - sizeof (struct xcoff_line), - xcoff_line_search); - if (ln == NULL) - { - *found = 0; - return 0; - } - - function = ln->function; - /* AIX prepends a '.' to function entry points, remove it. */ - if (*function == '.') - ++function; - return callback (data, pc, ln->filename, ln->lineno, function); -} - -/* Return the file/line information for a PC using the XCOFF lineno - mapping we built earlier. */ - -static int -xcoff_fileline (struct backtrace_state *state, uintptr_t pc, - backtrace_full_callback callback, - backtrace_error_callback error_callback, void *data) - -{ - struct xcoff_fileline_data *fdata; - int found; - int ret; - - if (!state->threaded) - { - for (fdata = (struct xcoff_fileline_data *) state->fileline_data; - fdata != NULL; - fdata = fdata->next) - { - ret = xcoff_lookup_pc (state, fdata, pc, callback, error_callback, - data, &found); - if (ret != 0 || found) - return ret; - } - } - else - { - struct xcoff_fileline_data **pp; - - pp = (struct xcoff_fileline_data **) (void *) &state->fileline_data; - while (1) - { - fdata = backtrace_atomic_load_pointer (pp); - if (fdata == NULL) - break; - - ret = xcoff_lookup_pc (state, fdata, pc, callback, error_callback, - data, &found); - if (ret != 0 || found) - return ret; - - pp = &fdata->next; - } - } - - /* FIXME: See if any libraries have been dlopen'ed. */ - - return callback (data, pc, NULL, 0, NULL); -} - -/* Compare struct xcoff_incl for qsort. */ - -static int -xcoff_incl_compare (const void *v1, const void *v2) -{ - const struct xcoff_incl *in1 = (const struct xcoff_incl *) v1; - const struct xcoff_incl *in2 = (const struct xcoff_incl *) v2; - - if (in1->begin < in2->begin) - return -1; - else if (in1->begin > in2->begin) - return 1; - else - return 0; -} - -/* Find a lnnoptr in an include file. */ - -static int -xcoff_incl_search (const void *vkey, const void *ventry) -{ - const uintptr_t *key = (const uintptr_t *) vkey; - const struct xcoff_incl *entry = (const struct xcoff_incl *) ventry; - uintptr_t lnno; - - lnno = *key; - if (lnno < entry->begin) - return -1; - else if (lnno > entry->end) - return 1; - else - return 0; -} - -/* Add a new mapping to the vector of line mappings that we are - building. Returns 1 on success, 0 on failure. */ - -static int -xcoff_add_line (struct backtrace_state *state, uintptr_t pc, - const char *filename, const char *function, uint32_t lnno, - backtrace_error_callback error_callback, void *data, - struct xcoff_line_vector *vec) -{ - struct xcoff_line *ln; - - ln = ((struct xcoff_line *) - backtrace_vector_grow (state, sizeof (struct xcoff_line), - error_callback, data, &vec->vec)); - if (ln == NULL) - return 0; - - ln->pc = pc; - ln->filename = filename; - ln->function = function; - ln->lineno = lnno; - - ++vec->count; - - return 1; -} - -/* Add the line number entries for a function to the line vector. */ - -static int -xcoff_process_linenos (struct backtrace_state *state, uintptr_t base_address, - const b_xcoff_syment *fsym, const char *filename, - const b_xcoff_scnhdr *sects, - const unsigned char *strtab, size_t strtab_size, - uint32_t fcn_lnno, struct xcoff_incl_vector *vec, - struct xcoff_line_vector *lvec, - const unsigned char *linenos, size_t linenos_size, - uintptr_t lnnoptr0, - backtrace_error_callback error_callback, void *data) -{ - const b_xcoff_auxent *aux; - const b_xcoff_lineno *lineno; - const unsigned char *lineptr; - const char *function; - struct xcoff_incl *incl = NULL; - uintptr_t lnnoptr; - uintptr_t pc; - uint32_t lnno; - int begincl; - - aux = (const b_xcoff_auxent *) (fsym + 1); - lnnoptr = aux->x_fcn.x_lnnoptr; - - if (lnnoptr < lnnoptr0 || lnnoptr + LINESZ > lnnoptr0 + linenos_size) - return 0; - - function = xcoff_symname (fsym, strtab, strtab_size); - if (function == NULL) - return 0; - - /* Skip first entry that points to symtab. */ - - lnnoptr += LINESZ; - - lineptr = linenos + (lnnoptr - lnnoptr0); - - begincl = -1; - while (lineptr + LINESZ <= linenos + linenos_size) - { - lineno = (const b_xcoff_lineno *) lineptr; - - lnno = lineno->l_lnno; - if (lnno == 0) - break; - - /* If part of a function other than the beginning comes from an - include file, the line numbers are absolute, rather than - relative to the beginning of the function. */ - incl = (struct xcoff_incl *) bsearch (&lnnoptr, vec->vec.base, - vec->count, - sizeof (struct xcoff_incl), - xcoff_incl_search); - if (begincl == -1) - begincl = incl != NULL; - if (incl != NULL) - { - filename = incl->filename; - if (begincl == 1) - lnno += fcn_lnno - 1; - } - else - lnno += fcn_lnno - 1; - - pc = base_address + lineno->l_addr.l_paddr - - sects[fsym->n_scnum - 1].s_paddr; - xcoff_add_line (state, pc, filename, function, lnno, error_callback, - data, lvec); - - lnnoptr += LINESZ; - lineptr += LINESZ; - } - - return 1; -} - -/* Initialize the line vector info for xcoff_fileline. */ - -static int -xcoff_initialize_fileline (struct backtrace_state *state, - uintptr_t base_address, - const b_xcoff_scnhdr *sects, - const b_xcoff_syment *syms, size_t nsyms, - const unsigned char *strtab, size_t strtab_size, - const unsigned char *linenos, size_t linenos_size, - uint64_t lnnoptr0, - backtrace_error_callback error_callback, void *data) -{ - struct xcoff_fileline_data *fdata; - struct xcoff_incl_vector vec; - struct xcoff_line *ln; - const b_xcoff_syment *fsym; - const b_xcoff_auxent *aux; - const char *filename; - const char *name; - struct xcoff_incl *incl; - uintptr_t begin, end; - uintptr_t lnno; - size_t i; - - fdata = ((struct xcoff_fileline_data *) - backtrace_alloc (state, sizeof (struct xcoff_fileline_data), - error_callback, data)); - if (fdata == NULL) - return 0; - - memset (fdata, 0, sizeof *fdata); - memset (&vec, 0, sizeof vec); - - /* Process include files first. */ - - begin = 0; - for (i = 0; i < nsyms; ++i) - { - const b_xcoff_syment *asym = &syms[i]; - - switch (asym->n_sclass) - { - case C_BINCL: - begin = asym->n_value; - break; - - case C_EINCL: - if (begin == 0) - break; - end = asym->n_value; - incl = ((struct xcoff_incl *) - backtrace_vector_grow (state, sizeof (struct xcoff_incl), - error_callback, data, &vec.vec)); - if (incl != NULL) - { - incl->filename = xcoff_symname (asym, strtab, strtab_size); - incl->begin = begin; - incl->end = end; - ++vec.count; - } - begin = 0; - break; - } - - i += asym->n_numaux; - } - - backtrace_qsort (vec.vec.base, vec.count, - sizeof (struct xcoff_incl), xcoff_incl_compare); - - filename = NULL; - fsym = NULL; - for (i = 0; i < nsyms; ++i) - { - const b_xcoff_syment *asym = &syms[i]; - - switch (asym->n_sclass) - { - case C_FILE: - filename = xcoff_symname (asym, strtab, strtab_size); - if (filename == NULL) - break; - - /* If the file auxiliary entry is not used, the symbol name is - the name of the source file. If the file auxiliary entry is - used, then the symbol name should be .file, and the first - file auxiliary entry (by convention) contains the source - file name. */ - - if (asym->n_numaux > 0 && !strcmp (filename, ".file")) - { - aux = (const b_xcoff_auxent *) (asym + 1); - if (aux->x_file._x.x_zeroes != 0) - { - /* Make a copy as we will release the symtab view. */ - char name[FILNMLEN+1]; - strncpy (name, aux->x_file.x_fname, FILNMLEN); - name[FILNMLEN] = '\0'; - filename = strdup (name); - } - else if (aux->x_file._x.x_offset < strtab_size) - filename = (const char *) strtab + aux->x_file._x.x_offset; - else - filename = NULL; - } - break; - - case C_EXT: - case C_HIDEXT: - case C_WEAKEXT: - fsym = NULL; - if (!ISFCN (asym->n_type) || asym->n_numaux == 0) - break; - if (filename == NULL) - break; - fsym = asym; - break; - - case C_FCN: - if (asym->n_numaux == 0) - break; - if (fsym == NULL) - break; - name = xcoff_symname (asym, strtab, strtab_size); - if (name == NULL) - break; - aux = (const b_xcoff_auxent *) (asym + 1); -#if BACKTRACE_XCOFF_SIZE == 32 - lnno = (uint32_t) aux->x_block.x_lnnohi << 16 - | aux->x_block.x_lnno; -#else - lnno = aux->x_block.x_lnno; -#endif - if (!strcmp (name, ".bf")) - { - xcoff_process_linenos (state, base_address, fsym, filename, - sects, strtab, strtab_size, lnno, &vec, - &fdata->vec, linenos, linenos_size, - lnnoptr0, error_callback, data); - } - else if (!strcmp (name, ".ef")) - { - fsym = NULL; - } - break; - } - - i += asym->n_numaux; - } - - /* Allocate one extra entry at the end. */ - ln = ((struct xcoff_line *) - backtrace_vector_grow (state, sizeof (struct xcoff_line), - error_callback, data, &fdata->vec.vec)); - if (ln == NULL) - goto fail; - ln->pc = (uintptr_t) -1; - ln->filename = NULL; - ln->function = NULL; - ln->lineno = 0; - - if (!backtrace_vector_release (state, &fdata->vec.vec, error_callback, data)) - goto fail; - - backtrace_qsort (fdata->vec.vec.base, fdata->vec.count, - sizeof (struct xcoff_line), xcoff_line_compare); - - if (!state->threaded) - { - struct xcoff_fileline_data **pp; - - for (pp = (struct xcoff_fileline_data **) (void *) &state->fileline_data; - *pp != NULL; - pp = &(*pp)->next) - ; - *pp = fdata; - } - else - { - while (1) - { - struct xcoff_fileline_data **pp; - - pp = (struct xcoff_fileline_data **) (void *) &state->fileline_data; - - while (1) - { - struct xcoff_fileline_data *p; - - p = backtrace_atomic_load_pointer (pp); - - if (p == NULL) - break; - - pp = &p->next; - } - - if (__sync_bool_compare_and_swap (pp, NULL, fdata)) - break; - } - } - - return 1; - -fail: - return 0; -} - -/* Add the backtrace data for one XCOFF file. Returns 1 on success, - 0 on failure (in both cases descriptor is closed). */ - -static int -xcoff_add (struct backtrace_state *state, int descriptor, off_t offset, - uintptr_t base_address, backtrace_error_callback error_callback, - void *data, fileline *fileline_fn, int *found_sym, int exe) -{ - struct backtrace_view fhdr_view; - struct backtrace_view sects_view; - struct backtrace_view linenos_view; - struct backtrace_view syms_view; - struct backtrace_view str_view; - struct backtrace_view dwarf_view; - b_xcoff_filhdr fhdr; - const b_xcoff_scnhdr *sects; - const b_xcoff_scnhdr *stext; - uint64_t lnnoptr; - uint32_t nlnno; - off_t str_off; - off_t min_offset; - off_t max_offset; - struct dwsect_info dwsect[DWSECT_MAX]; - size_t sects_size; - size_t syms_size; - int32_t str_size; - int sects_view_valid; - int linenos_view_valid; - int syms_view_valid; - int str_view_valid; - int dwarf_view_valid; - int magic_ok; - int i; - - *found_sym = 0; - - sects_view_valid = 0; - linenos_view_valid = 0; - syms_view_valid = 0; - str_view_valid = 0; - dwarf_view_valid = 0; - - str_size = 0; - - /* Map the XCOFF file header. */ - if (!backtrace_get_view (state, descriptor, offset, sizeof (b_xcoff_filhdr), - error_callback, data, &fhdr_view)) - goto fail; - - memcpy (&fhdr, fhdr_view.data, sizeof fhdr); - magic_ok = (fhdr.f_magic == XCOFF_MAGIC); - - backtrace_release_view (state, &fhdr_view, error_callback, data); - - if (!magic_ok) - { - if (exe) - error_callback (data, "executable file is not XCOFF", 0); - goto fail; - } - - /* Verify object is of expected type. */ - if ((exe && (fhdr.f_flags & F_SHROBJ)) - || (!exe && !(fhdr.f_flags & F_SHROBJ))) - goto fail; - - /* Read the section headers. */ - - sects_size = fhdr.f_nscns * sizeof (b_xcoff_scnhdr); - - if (!backtrace_get_view (state, descriptor, - offset + sizeof (fhdr) + fhdr.f_opthdr, - sects_size, error_callback, data, §s_view)) - goto fail; - sects_view_valid = 1; - sects = (const b_xcoff_scnhdr *) sects_view.data; - - /* FIXME: assumes only one .text section. */ - for (i = 0; i < fhdr.f_nscns; ++i) - if ((sects[i].s_flags & 0xffff) == STYP_TEXT) - break; - if (i == fhdr.f_nscns) - goto fail; - - stext = §s[i]; - - /* AIX ldinfo_textorg includes the XCOFF headers. */ - base_address = (exe ? XCOFF_AIX_TEXTBASE : base_address) + stext->s_scnptr; - - lnnoptr = stext->s_lnnoptr; - nlnno = stext->s_nlnno; - -#if BACKTRACE_XCOFF_SIZE == 32 - if (nlnno == _OVERFLOW_MARKER) - { - int sntext = i + 1; - /* Find the matching .ovrflo section. */ - for (i = 0; i < fhdr.f_nscns; ++i) - { - if (((sects[i].s_flags & 0xffff) == STYP_OVRFLO) - && sects[i].s_nlnno == sntext) - { - nlnno = sects[i].s_vaddr; - break; - } - } - } -#endif - - /* Read the symbol table and the string table. */ - - if (fhdr.f_symptr != 0) - { - struct xcoff_syminfo_data *sdata; - - /* Symbol table is followed by the string table. The string table - starts with its length (on 4 bytes). - Map the symbol table and the length of the string table. */ - syms_size = fhdr.f_nsyms * sizeof (b_xcoff_syment); - - if (!backtrace_get_view (state, descriptor, offset + fhdr.f_symptr, - syms_size + 4, error_callback, data, - &syms_view)) - goto fail; - syms_view_valid = 1; - - memcpy (&str_size, syms_view.data + syms_size, 4); - - str_off = fhdr.f_symptr + syms_size; - - if (str_size > 4) - { - /* Map string table (including the length word). */ - - if (!backtrace_get_view (state, descriptor, offset + str_off, - str_size, error_callback, data, &str_view)) - goto fail; - str_view_valid = 1; - } - - sdata = ((struct xcoff_syminfo_data *) - backtrace_alloc (state, sizeof *sdata, error_callback, data)); - if (sdata == NULL) - goto fail; - - if (!xcoff_initialize_syminfo (state, base_address, sects, - syms_view.data, fhdr.f_nsyms, - str_view.data, str_size, - error_callback, data, sdata)) - { - backtrace_free (state, sdata, sizeof *sdata, error_callback, data); - goto fail; - } - - *found_sym = 1; - - xcoff_add_syminfo_data (state, sdata); - } - - /* Read all the DWARF sections in a single view, since they are - probably adjacent in the file. We never release this view. */ - - min_offset = 0; - max_offset = 0; - memset (dwsect, 0, sizeof dwsect); - for (i = 0; i < fhdr.f_nscns; ++i) - { - off_t end; - int idx; - - if ((sects[i].s_flags & 0xffff) != STYP_DWARF - || sects[i].s_size == 0) - continue; - /* Map DWARF section to array index. */ - switch (sects[i].s_flags & 0xffff0000) - { - case SSUBTYP_DWINFO: - idx = DWSECT_INFO; - break; - case SSUBTYP_DWLINE: - idx = DWSECT_LINE; - break; - case SSUBTYP_DWABREV: - idx = DWSECT_ABBREV; - break; - case SSUBTYP_DWARNGE: - idx = DWSECT_RANGES; - break; - case SSUBTYP_DWSTR: - idx = DWSECT_STR; - break; - default: - continue; - } - if (min_offset == 0 || (off_t) sects[i].s_scnptr < min_offset) - min_offset = sects[i].s_scnptr; - end = sects[i].s_scnptr + sects[i].s_size; - if (end > max_offset) - max_offset = end; - dwsect[idx].offset = sects[i].s_scnptr; - dwsect[idx].size = sects[i].s_size; - } - if (min_offset != 0 && max_offset != 0) - { - if (!backtrace_get_view (state, descriptor, offset + min_offset, - max_offset - min_offset, - error_callback, data, &dwarf_view)) - goto fail; - dwarf_view_valid = 1; - - for (i = 0; i < (int) DWSECT_MAX; ++i) - { - if (dwsect[i].offset == 0) - dwsect[i].data = NULL; - else - dwsect[i].data = ((const unsigned char *) dwarf_view.data - + (dwsect[i].offset - min_offset)); - } - - if (!backtrace_dwarf_add (state, 0, - dwsect[DWSECT_INFO].data, - dwsect[DWSECT_INFO].size, -#if BACKTRACE_XCOFF_SIZE == 32 - /* XXX workaround for broken lineoff */ - dwsect[DWSECT_LINE].data - 4, -#else - /* XXX workaround for broken lineoff */ - dwsect[DWSECT_LINE].data - 12, -#endif - dwsect[DWSECT_LINE].size, - dwsect[DWSECT_ABBREV].data, - dwsect[DWSECT_ABBREV].size, - dwsect[DWSECT_RANGES].data, - dwsect[DWSECT_RANGES].size, - dwsect[DWSECT_STR].data, - dwsect[DWSECT_STR].size, - 1, /* big endian */ - error_callback, data, fileline_fn)) - goto fail; - } - - /* Read the XCOFF line number entries if DWARF sections not found. */ - - if (!dwarf_view_valid && fhdr.f_symptr != 0 && lnnoptr != 0) - { - size_t linenos_size = (size_t) nlnno * LINESZ; - - if (!backtrace_get_view (state, descriptor, offset + lnnoptr, - linenos_size, - error_callback, data, &linenos_view)) - goto fail; - linenos_view_valid = 1; - - if (xcoff_initialize_fileline (state, base_address, sects, - syms_view.data, fhdr.f_nsyms, - str_view.data, str_size, - linenos_view.data, linenos_size, - lnnoptr, error_callback, data)) - *fileline_fn = xcoff_fileline; - - backtrace_release_view (state, &linenos_view, error_callback, data); - linenos_view_valid = 0; - } - - backtrace_release_view (state, §s_view, error_callback, data); - sects_view_valid = 0; - if (syms_view_valid) - backtrace_release_view (state, &syms_view, error_callback, data); - syms_view_valid = 0; - - /* We've read all we need from the executable. */ - if (!backtrace_close (descriptor, error_callback, data)) - goto fail; - descriptor = -1; - - return 1; - - fail: - if (sects_view_valid) - backtrace_release_view (state, §s_view, error_callback, data); - if (str_view_valid) - backtrace_release_view (state, &str_view, error_callback, data); - if (syms_view_valid) - backtrace_release_view (state, &syms_view, error_callback, data); - if (linenos_view_valid) - backtrace_release_view (state, &linenos_view, error_callback, data); - if (dwarf_view_valid) - backtrace_release_view (state, &dwarf_view, error_callback, data); - if (descriptor != -1 && offset == 0) - backtrace_close (descriptor, error_callback, data); - return 0; -} - -#ifdef HAVE_LOADQUERY - -/* Read an integer value in human-readable format from an AIX - big archive fixed-length or member header. */ - -static int -xcoff_parse_decimal (const char *buf, size_t size, off_t *off) -{ - char str[32]; - char *end; - - if (size >= sizeof str) - return 0; - memcpy (str, buf, size); - str[size] = '\0'; - *off = strtol (str, &end, 10); - if (*end != '\0' && *end != ' ') - return 0; - - return 1; -} - -/* Add the backtrace data for a member of an AIX big archive. - Returns 1 on success, 0 on failure. */ - -static int -xcoff_armem_add (struct backtrace_state *state, int descriptor, - uintptr_t base_address, const char *member, - backtrace_error_callback error_callback, void *data, - fileline *fileline_fn, int *found_sym) -{ - struct backtrace_view view; - b_ar_fl_hdr fl_hdr; - const b_ar_hdr *ar_hdr; - off_t off; - off_t len; - int memlen; - - *found_sym = 0; - - /* Map archive fixed-length header. */ - - if (!backtrace_get_view (state, descriptor, 0, sizeof (b_ar_fl_hdr), - error_callback, data, &view)) - goto fail; - - memcpy (&fl_hdr, view.data, sizeof (b_ar_fl_hdr)); - - backtrace_release_view (state, &view, error_callback, data); - - if (memcmp (fl_hdr.fl_magic, AIAMAGBIG, 8) != 0) - goto fail; - - memlen = strlen (member); - - /* Read offset of first archive member. */ - if (!xcoff_parse_decimal (fl_hdr.fl_fstmoff, sizeof fl_hdr.fl_fstmoff, &off)) - goto fail; - while (off != 0) - { - /* Map archive member header and member name. */ - - if (!backtrace_get_view (state, descriptor, off, - sizeof (b_ar_hdr) + memlen, - error_callback, data, &view)) - break; - - ar_hdr = (const b_ar_hdr *) view.data; - - /* Read archive member name length. */ - if (!xcoff_parse_decimal (ar_hdr->ar_namlen, sizeof ar_hdr->ar_namlen, - &len)) - { - backtrace_release_view (state, &view, error_callback, data); - break; - } - if (len == memlen && !memcmp (ar_hdr->ar_name, member, memlen)) - { - off = (off + sizeof (b_ar_hdr) + memlen + 1) & ~1; - - /* The archive can contain several members with the same name - (e.g. 32-bit and 64-bit), so continue if not ok. */ - - if (xcoff_add (state, descriptor, off, base_address, error_callback, - data, fileline_fn, found_sym, 0)) - { - backtrace_release_view (state, &view, error_callback, data); - return 1; - } - } - - /* Read offset of next archive member. */ - if (!xcoff_parse_decimal (ar_hdr->ar_nxtmem, sizeof ar_hdr->ar_nxtmem, - &off)) - { - backtrace_release_view (state, &view, error_callback, data); - break; - } - backtrace_release_view (state, &view, error_callback, data); - } - - fail: - /* No matching member found. */ - backtrace_close (descriptor, error_callback, data); - return 0; -} - -/* Add the backtrace data for dynamically loaded libraries. */ - -static void -xcoff_add_shared_libs (struct backtrace_state *state, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn, int *found_sym) -{ - const struct ld_info *ldinfo; - void *buf; - unsigned int buflen; - const char *member; - int descriptor; - int does_not_exist; - int lib_found_sym; - int ret; - - /* Retrieve the list of loaded libraries. */ - - buf = NULL; - buflen = 512; - do - { - buf = realloc (buf, buflen); - if (buf == NULL) - { - ret = -1; - break; - } - ret = loadquery (L_GETINFO, buf, buflen); - if (ret == 0) - break; - buflen *= 2; - } - while (ret == -1 && errno == ENOMEM); - if (ret != 0) - { - free (buf); - return; - } - - ldinfo = (const struct ld_info *) buf; - while ((const char *) ldinfo < (const char *) buf + buflen) - { - if (*ldinfo->ldinfo_filename != '/') - goto next; - - descriptor = backtrace_open (ldinfo->ldinfo_filename, error_callback, - data, &does_not_exist); - if (descriptor < 0) - goto next; - - /* Check if it is an archive (member name not empty). */ - - member = ldinfo->ldinfo_filename + strlen (ldinfo->ldinfo_filename) + 1; - if (*member) - { - xcoff_armem_add (state, descriptor, - (uintptr_t) ldinfo->ldinfo_textorg, member, - error_callback, data, fileline_fn, &lib_found_sym); - } - else - { - xcoff_add (state, descriptor, 0, (uintptr_t) ldinfo->ldinfo_textorg, - error_callback, data, fileline_fn, &lib_found_sym, 0); - } - if (lib_found_sym) - *found_sym = 1; - - next: - if (ldinfo->ldinfo_next == 0) - break; - ldinfo = (const struct ld_info *) ((const char *) ldinfo - + ldinfo->ldinfo_next); - } - - free (buf); -} -#endif /* HAVE_LOADQUERY */ - -/* Initialize the backtrace data we need from an XCOFF executable. - Returns 1 on success, 0 on failure. */ - -int -backtrace_initialize (struct backtrace_state *state, - const char *filename ATTRIBUTE_UNUSED, int descriptor, - backtrace_error_callback error_callback, - void *data, fileline *fileline_fn) -{ - int ret; - int found_sym; - fileline xcoff_fileline_fn = xcoff_nodebug; - - ret = xcoff_add (state, descriptor, 0, 0, error_callback, data, - &xcoff_fileline_fn, &found_sym, 1); - if (!ret) - return 0; - -#ifdef HAVE_LOADQUERY - xcoff_add_shared_libs (state, error_callback, data, &xcoff_fileline_fn, - &found_sym); -#endif - - if (!state->threaded) - { - if (found_sym) - state->syminfo_fn = xcoff_syminfo; - else if (state->syminfo_fn == NULL) - state->syminfo_fn = xcoff_nosyms; - } - else - { - if (found_sym) - backtrace_atomic_store_pointer (&state->syminfo_fn, xcoff_syminfo); - else - __sync_bool_compare_and_swap (&state->syminfo_fn, NULL, xcoff_nosyms); - } - - if (!state->threaded) - { - if (state->fileline_fn == NULL || state->fileline_fn == xcoff_nodebug) - *fileline_fn = xcoff_fileline_fn; - } - else - { - fileline current_fn; - - current_fn = backtrace_atomic_load_pointer (&state->fileline_fn); - if (current_fn == NULL || current_fn == xcoff_nodebug) - *fileline_fn = xcoff_fileline_fn; - } - - return 1; -} diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ztest.c b/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ztest.c deleted file mode 100644 index 9cd712a..0000000 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/src/libbacktrace/ztest.c +++ /dev/null @@ -1,537 +0,0 @@ -/* ztest.c -- Test for libbacktrace inflate code. - Copyright (C) 2017-2018 Free Software Foundation, Inc. - Written by Ian Lance Taylor, Google. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - (1) Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - (2) 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. - - (3) The name of the author may not be used to - endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 THE AUTHOR 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. */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_ZLIB -#include -#endif - -#include "backtrace.h" -#include "backtrace-supported.h" - -#include "internal.h" -#include "testlib.h" - -#ifndef HAVE_CLOCK_GETTIME - -typedef int xclockid_t; - -static int -xclock_gettime (xclockid_t id ATTRIBUTE_UNUSED, - struct timespec *ts ATTRIBUTE_UNUSED) -{ - errno = EINVAL; - return -1; -} - -#define clockid_t xclockid_t -#define clock_gettime xclock_gettime -#undef CLOCK_REALTIME -#define CLOCK_REALTIME 0 - -#endif /* !defined(HAVE_CLOCK_GETTIME) */ - -#ifdef CLOCK_PROCESS_CPUTIME_ID -#define ZLIB_CLOCK_GETTIME_ARG CLOCK_PROCESS_CPUTIME_ID -#else -#define ZLIB_CLOCK_GETTIME_ARG CLOCK_REALTIME -#endif - -/* Some tests for the local zlib inflation code. */ - -struct zlib_test -{ - const char *name; - const char *uncompressed; - size_t uncompressed_len; - const char *compressed; - size_t compressed_len; -}; - -/* Error callback. */ - -static void -error_callback_compress (void *vdata, const char *msg, int errnum) -{ - fprintf (stderr, "%s", msg); - if (errnum > 0) - fprintf (stderr, ": %s", strerror (errnum)); - fprintf (stderr, "\n"); - exit (EXIT_FAILURE); -} - -static const struct zlib_test tests[] = -{ - { - "empty", - "", - 0, - "\x78\x9c\x03\x00\x00\x00\x00\x01", - 8, - }, - { - "hello", - "hello, world\n", - 0, - ("\x78\x9c\xca\x48\xcd\xc9\xc9\xd7\x51\x28\xcf" - "\x2f\xca\x49\xe1\x02\x04\x00\x00\xff\xff\x21\xe7\x04\x93"), - 25, - }, - { - "goodbye", - "goodbye, world", - 0, - ("\x78\x9c\x4b\xcf\xcf\x4f\x49\xaa" - "\x4c\xd5\x51\x28\xcf\x2f\xca\x49" - "\x01\x00\x28\xa5\x05\x5e"), - 22, - }, - { - "ranges", - ("\xcc\x11\x00\x00\x00\x00\x00\x00\xd5\x13\x00\x00\x00\x00\x00\x00" - "\x1c\x14\x00\x00\x00\x00\x00\x00\x72\x14\x00\x00\x00\x00\x00\x00" - "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\xfb\x12\x00\x00\x00\x00\x00\x00\x09\x13\x00\x00\x00\x00\x00\x00" - "\x0c\x13\x00\x00\x00\x00\x00\x00\xcb\x13\x00\x00\x00\x00\x00\x00" - "\x29\x14\x00\x00\x00\x00\x00\x00\x4e\x14\x00\x00\x00\x00\x00\x00" - "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\xfb\x12\x00\x00\x00\x00\x00\x00\x09\x13\x00\x00\x00\x00\x00\x00" - "\x67\x13\x00\x00\x00\x00\x00\x00\xcb\x13\x00\x00\x00\x00\x00\x00" - "\x9d\x14\x00\x00\x00\x00\x00\x00\xd5\x14\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x5f\x0b\x00\x00\x00\x00\x00\x00\x6c\x0b\x00\x00\x00\x00\x00\x00" - "\x7d\x0b\x00\x00\x00\x00\x00\x00\x7e\x0c\x00\x00\x00\x00\x00\x00" - "\x38\x0f\x00\x00\x00\x00\x00\x00\x5c\x0f\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x83\x0c\x00\x00\x00\x00\x00\x00\xfa\x0c\x00\x00\x00\x00\x00\x00" - "\xfd\x0d\x00\x00\x00\x00\x00\x00\xef\x0e\x00\x00\x00\x00\x00\x00" - "\x14\x0f\x00\x00\x00\x00\x00\x00\x38\x0f\x00\x00\x00\x00\x00\x00" - "\x9f\x0f\x00\x00\x00\x00\x00\x00\xac\x0f\x00\x00\x00\x00\x00\x00" - "\xdb\x0f\x00\x00\x00\x00\x00\x00\xff\x0f\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\xfd\x0d\x00\x00\x00\x00\x00\x00\xd8\x0e\x00\x00\x00\x00\x00\x00" - "\x9f\x0f\x00\x00\x00\x00\x00\x00\xac\x0f\x00\x00\x00\x00\x00\x00" - "\xdb\x0f\x00\x00\x00\x00\x00\x00\xff\x0f\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\xfa\x0c\x00\x00\x00\x00\x00\x00\xea\x0d\x00\x00\x00\x00\x00\x00" - "\xef\x0e\x00\x00\x00\x00\x00\x00\x14\x0f\x00\x00\x00\x00\x00\x00" - "\x5c\x0f\x00\x00\x00\x00\x00\x00\x9f\x0f\x00\x00\x00\x00\x00\x00" - "\xac\x0f\x00\x00\x00\x00\x00\x00\xdb\x0f\x00\x00\x00\x00\x00\x00" - "\xff\x0f\x00\x00\x00\x00\x00\x00\x2c\x10\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x60\x11\x00\x00\x00\x00\x00\x00\xd1\x16\x00\x00\x00\x00\x00\x00" - "\x40\x0b\x00\x00\x00\x00\x00\x00\x2c\x10\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x7a\x00\x00\x00\x00\x00\x00\x00\xb6\x00\x00\x00\x00\x00\x00\x00" - "\x9f\x01\x00\x00\x00\x00\x00\x00\xa7\x01\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" - "\x7a\x00\x00\x00\x00\x00\x00\x00\xa9\x00\x00\x00\x00\x00\x00\x00" - "\x9f\x01\x00\x00\x00\x00\x00\x00\xa7\x01\x00\x00\x00\x00\x00\x00" - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), - 672, - ("\x78\x9c\x3b\x23\xc8\x00\x06\x57\x85\x21\xb4\x8c\x08\x84\x2e\x82" - "\xd2\x73\xa1\xf4\x55\x28\x8d\x0e\x7e\x0b\x41\x68\x4e\xa8\x7e\x1e" - "\x28\x7d\x1a\x4a\x6b\x42\xf5\xf9\x91\x69\x5e\x3a\x9a\x79\x84\xf4" - "\xc7\x73\x43\xe8\x1c\x28\x5d\x0b\xa5\xeb\x78\x20\xb4\x05\x3f\x84" - "\x8e\xe1\xc7\xae\xbf\x19\xaa\xee\x17\x94\xfe\xcb\x0b\xa1\xdf\xf3" - "\x41\x68\x11\x7e\x54\x73\xe6\x43\xe9\x35\x50\xfa\x36\x94\xfe\x8f" - "\xc3\x7c\x98\x79\x37\xf8\xc8\xd3\x0f\x73\xd7\x2b\x1c\xee\x8a\x21" - "\xd2\x5d\x3a\x02\xd8\xcd\x4f\x80\xa6\x87\x8b\x62\x10\xda\x81\x1b" - "\xbf\xfa\x2a\x28\xbd\x0d\x4a\xcf\x67\x84\xd0\xcb\x19\xf1\xab\x5f" - "\x49\xa4\x7a\x00\x48\x97\x29\xd4"), - 152, - } -}; - -/* Test the hand coded samples. */ - -static void -test_samples (struct backtrace_state *state) -{ - size_t i; - - for (i = 0; i < sizeof tests / sizeof tests[0]; ++i) - { - char *p; - size_t v; - size_t j; - unsigned char *uncompressed; - size_t uncompressed_len; - - p = malloc (12 + tests[i].compressed_len); - memcpy (p, "ZLIB", 4); - v = tests[i].uncompressed_len; - if (v == 0) - v = strlen (tests[i].uncompressed); - for (j = 0; j < 8; ++j) - p[j + 4] = (v >> ((7 - j) * 8)) & 0xff; - memcpy (p + 12, tests[i].compressed, tests[i].compressed_len); - uncompressed = NULL; - uncompressed_len = 0; - if (!backtrace_uncompress_zdebug (state, (unsigned char *) p, - tests[i].compressed_len + 12, - error_callback_compress, NULL, - &uncompressed, &uncompressed_len)) - { - fprintf (stderr, "test %s: uncompress failed\n", tests[i].name); - ++failures; - } - else - { - if (uncompressed_len != v) - { - fprintf (stderr, - "test %s: got uncompressed length %zu, want %zu\n", - tests[i].name, uncompressed_len, v); - ++failures; - } - else if (memcmp (tests[i].uncompressed, uncompressed, v) != 0) - { - size_t j; - - fprintf (stderr, "test %s: uncompressed data mismatch\n", - tests[i].name); - for (j = 0; j < v; ++j) - if (tests[i].uncompressed[j] != uncompressed[j]) - fprintf (stderr, " %zu: got %#x want %#x\n", j, - uncompressed[j], tests[i].uncompressed[j]); - ++failures; - } - else - printf ("PASS: inflate %s\n", tests[i].name); - - backtrace_free (state, uncompressed, uncompressed_len, - error_callback_compress, NULL); - } - } -} - -#ifdef HAVE_ZLIB - -/* Given a set of TRIALS timings, discard the lowest and highest - values and return the mean average of the rest. */ - -static size_t -average_time (const size_t *times, size_t trials) -{ - size_t imax; - size_t max; - size_t imin; - size_t min; - size_t i; - size_t sum; - - imin = 0; - imax = 0; - min = times[0]; - max = times[0]; - for (i = 1; i < trials; ++i) - { - if (times[i] < min) - { - imin = i; - min = times[i]; - } - if (times[i] > max) - { - imax = i; - max = times[i]; - } - } - - sum = 0; - for (i = 0; i < trials; ++i) - { - if (i != imax && i != imin) - sum += times[i]; - } - return sum / (trials - 2); -} - -#endif - -/* Test a larger text, if available. */ - -static void -test_large (struct backtrace_state *state) -{ -#ifdef HAVE_ZLIB - unsigned char *orig_buf; - size_t orig_bufsize; - size_t i; - char *compressed_buf; - size_t compressed_bufsize; - unsigned long compress_sizearg; - unsigned char *uncompressed_buf; - size_t uncompressed_bufsize; - int r; - clockid_t cid; - struct timespec ts1; - struct timespec ts2; - size_t ctime; - size_t ztime; - const size_t trials = 16; - size_t ctimes[16]; - size_t ztimes[16]; - static const char * const names[] = { - "Mark.Twain-Tom.Sawyer.txt", - "../libgo/go/compress/testdata/Mark.Twain-Tom.Sawyer.txt" - }; - - orig_buf = NULL; - orig_bufsize = 0; - uncompressed_buf = NULL; - compressed_buf = NULL; - - for (i = 0; i < sizeof names / sizeof names[0]; ++i) - { - size_t len; - char *namebuf; - FILE *e; - struct stat st; - char *rbuf; - size_t got; - - len = strlen (SRCDIR) + strlen (names[i]) + 2; - namebuf = malloc (len); - if (namebuf == NULL) - { - perror ("malloc"); - goto fail; - } - snprintf (namebuf, len, "%s/%s", SRCDIR, names[i]); - e = fopen (namebuf, "r"); - free (namebuf); - if (e == NULL) - continue; - if (fstat (fileno (e), &st) < 0) - { - perror ("fstat"); - fclose (e); - continue; - } - rbuf = malloc (st.st_size); - if (rbuf == NULL) - { - perror ("malloc"); - goto fail; - } - got = fread (rbuf, 1, st.st_size, e); - fclose (e); - if (got > 0) - { - orig_buf = rbuf; - orig_bufsize = got; - break; - } - free (rbuf); - } - - if (orig_buf == NULL) - { - /* We couldn't find an input file. */ - printf ("UNSUPPORTED: inflate large\n"); - return; - } - - compressed_bufsize = compressBound (orig_bufsize) + 12; - compressed_buf = malloc (compressed_bufsize); - if (compressed_buf == NULL) - { - perror ("malloc"); - goto fail; - } - - compress_sizearg = compressed_bufsize - 12; - r = compress (compressed_buf + 12, &compress_sizearg, - orig_buf, orig_bufsize); - if (r != Z_OK) - { - fprintf (stderr, "zlib compress failed: %d\n", r); - goto fail; - } - - compressed_bufsize = compress_sizearg + 12; - - /* Prepare the header that our library expects. */ - memcpy (compressed_buf, "ZLIB", 4); - for (i = 0; i < 8; ++i) - compressed_buf[i + 4] = (orig_bufsize >> ((7 - i) * 8)) & 0xff; - - uncompressed_buf = malloc (orig_bufsize); - if (uncompressed_buf == NULL) - { - perror ("malloc"); - goto fail; - } - uncompressed_bufsize = orig_bufsize; - - if (!backtrace_uncompress_zdebug (state, compressed_buf, compressed_bufsize, - error_callback_compress, NULL, - &uncompressed_buf, &uncompressed_bufsize)) - { - fprintf (stderr, "inflate large: backtrace_uncompress_zdebug failed\n"); - goto fail; - } - - if (uncompressed_bufsize != orig_bufsize) - { - fprintf (stderr, - "inflate large: got uncompressed length %zu, want %zu\n", - uncompressed_bufsize, orig_bufsize); - goto fail; - } - - if (memcmp (uncompressed_buf, orig_buf, uncompressed_bufsize) != 0) - { - fprintf (stderr, "inflate large: uncompressed data mismatch\n"); - goto fail; - } - - printf ("PASS: inflate large\n"); - - for (i = 0; i < trials; ++i) - { - unsigned long uncompress_sizearg; - - cid = ZLIB_CLOCK_GETTIME_ARG; - if (clock_gettime (cid, &ts1) < 0) - { - if (errno == EINVAL) - return; - perror ("clock_gettime"); - return; - } - - if (!backtrace_uncompress_zdebug (state, compressed_buf, - compressed_bufsize, - error_callback_compress, NULL, - &uncompressed_buf, - &uncompressed_bufsize)) - { - fprintf (stderr, - ("inflate large: " - "benchmark backtrace_uncompress_zdebug failed\n")); - return; - } - - if (clock_gettime (cid, &ts2) < 0) - { - perror ("clock_gettime"); - return; - } - - ctime = (ts2.tv_sec - ts1.tv_sec) * 1000000000; - ctime += ts2.tv_nsec - ts1.tv_nsec; - ctimes[i] = ctime; - - if (clock_gettime (cid, &ts1) < 0) - { - perror("clock_gettime"); - return; - } - - uncompress_sizearg = uncompressed_bufsize; - r = uncompress (uncompressed_buf, &uncompress_sizearg, - compressed_buf + 12, compressed_bufsize - 12); - - if (clock_gettime (cid, &ts2) < 0) - { - perror ("clock_gettime"); - return; - } - - if (r != Z_OK) - { - fprintf (stderr, - "inflate large: benchmark zlib uncompress failed: %d\n", - r); - return; - } - - ztime = (ts2.tv_sec - ts1.tv_sec) * 1000000000; - ztime += ts2.tv_nsec - ts1.tv_nsec; - ztimes[i] = ztime; - } - - /* Toss the highest and lowest times and average the rest. */ - ctime = average_time (ctimes, trials); - ztime = average_time (ztimes, trials); - - printf ("backtrace: %zu ns\n", ctime); - printf ("zlib : %zu ns\n", ztime); - printf ("ratio : %g\n", (double) ztime / (double) ctime); - - return; - - fail: - printf ("FAIL: inflate large\n"); - ++failures; - - if (orig_buf != NULL) - free (orig_buf); - if (compressed_buf != NULL) - free (compressed_buf); - if (uncompressed_buf != NULL) - free (uncompressed_buf); - -#else /* !HAVE_ZLIB */ - - printf ("UNSUPPORTED: inflate large\n"); - -#endif /* !HAVE_ZLIB */ -} - -int -main (int argc ATTRIBUTE_UNUSED, char **argv) -{ - struct backtrace_state *state; - - state = backtrace_create_state (argv[0], BACKTRACE_SUPPORTS_THREADS, - error_callback_create, NULL); - - test_samples (state); - test_large (state); - - exit (failures != 0 ? EXIT_FAILURE : EXIT_SUCCESS); -} diff --git a/third_party/cargo/vendor/calloop-0.4.4/.cargo-checksum.json b/third_party/cargo/vendor/calloop-0.4.4/.cargo-checksum.json new file mode 100644 index 0000000..8120dfc --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"db77b3b5afe8c377f18724aaea479d9e94f0f7edc3b0a845af0836c7ad3ef789","Cargo.toml":"bad1b5b8ca1bc7b5dfd1110d3fd480e3f49e14e55a5edf5a1c664e785cb9953b","LICENSE.txt":"4b71658d3410d813b6fc6ceb654ce2aa8c2d3094c944dc59c2041da6227810e3","README.md":"e4134dbdd253028a5ec516bc966c0b0535b29916320b3f9f5d4a48cb227dcd87","README.tpl":"1666549ee42d21584d5d15eacc4dde880b1b497074549e1cbf984e6a658d5a8b","doc_index.html":"237e960e25521efab85cf689c555a21612d9205310d87f764309a3d2f3d8be65","src/lib.rs":"db5c09203d1734b291fd32f1a8f134776ebc8cb22696ff7cf108ebbb44753eee","src/list.rs":"caea64702b3dc3c92aac6a74a214d30868af3257e72d03ca31b4929bc7fc314f","src/loop_logic.rs":"dc6e06f1cd53257eb2db0cda7218bc62fb841d8d26b939d672ae3f66dc42940f","src/sources/channel.rs":"598c1b2cb5cb5269aacd61d4b7b34f7898ed211608a3a7c5b0f0b1f05ea60d93","src/sources/generic.rs":"70e2efd01381d3273d270bc125057c2940e61392c840b7d06d73c78a80b4f353","src/sources/mod.rs":"0e4ff41203913cf252a0f8860534d20169e715d88953a428d99c5a8b77fa6288","src/sources/signals.rs":"52bdbe405f08c8bcafc0c17a4a2afc8caec2f0e23b593889b3526b5389c6b5bd","src/sources/timer.rs":"b2876895a05ffe25b50f6005dd3deb0d189841dfb4984fd647368c27ec444a78","tests/signals.rs":"f99b2a569e336eedae741d2c05f18845499e0effcbdefbd29b9ef7fed9ac12fd"},"package":"7aa2097be53a00de9e8fc349fea6d76221f398f5c4fa550d420669906962d160"} \ No newline at end of file diff --git a/third_party/cargo/vendor/calloop-0.4.4/BUILD b/third_party/cargo/vendor/calloop-0.4.4/BUILD new file mode 100644 index 0000000..64891ca --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/BUILD @@ -0,0 +1,46 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "calloop", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/mio-0.6.21:mio", + "//third_party/cargo/vendor/mio-extras-2.0.6:mio_extras", + "//third_party/cargo/vendor/nix-0.14.1:nix", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.4.4", + crate_features = [ + ], +) + +# Unsupported target "signals" with type "test" omitted diff --git a/third_party/cargo/vendor/calloop-0.4.4/CHANGELOG.md b/third_party/cargo/vendor/calloop-0.4.4/CHANGELOG.md new file mode 100644 index 0000000..3af6bf1 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/CHANGELOG.md @@ -0,0 +1,69 @@ +# Change Log + +## Unreleased + +## 0.4.4 -- 2019-06-13 + +- Update `nix` dependency to `0.14` + +## 0.4.3 -- 2019-02-17 + +- Update `mio` dependency +- Update `nix` dependency + +## 0.4.2 -- 2018-11-15 + +- Implement `Debug` for `InsertError`. + +## 0.4.1 -- 2018-11-14 + +- Disable the `sources::signal` module on FreeBSD so that the library can be built on this + platform. + +## 0.4.0 -- 2018-11-04 + +- **Breaking** Use `mio-extras` instead of `mio-more` which is not maintained. +- **Breaking** Reexport `mio` rather than selectively re-exporting some of its types. +- Add methods to `Generic` to retrive the inner `Rc` and construct it from an `Rc` +- **Breaking** `LoopHandle::insert_source` now allows to retrieve the source on error. + +## 0.3.2 -- 2018-09-25 + +- Fix the contents of `EventedRawFd` which was erroneously not public. + +## 0.3.1 -- 2018-09-25 + +- introduce `EventedRawFd` as a special case for the `Generic` event source, for when + you really have to manipulate raw fds +- Don't panic when the removal of an event source trigger the removal of an other one + +## 0.3.0 -- 2018-09-10 + +- Fixed a bug where inserting an event source from within a callback caused a panic. +- **[breaking]** Erase the `Data` type parameter from `Source` and `Idle`, for + improved ergonomics. + +## 0.2.2 -- 2018-09-10 + +- Introduce an `EventLoop::run` method, as well as the `LoopSignal` handle allowing to + wakeup or stop the event loop from anywhere. + +## 0.2.1 -- 2018-09-01 + +- Use `FnOnce` for insertion in idle callbacks. + +## 0.2.0 -- 2018-08-30 + +- **[breaking]** Add a `&mut shared_data` argument to `EventLoop::dispatch(..)` to share data + between callbacks. + +## 0.1.1 -- 2018-08-29 + +- `Generic` event source for wrapping arbitrary `Evented` types +- timer event sources +- UNIX signal event sources +- channel event sources + +## 0.1.0 -- 2018-08-24 + +Initial release diff --git a/third_party/cargo/vendor/calloop-0.4.4/Cargo.toml b/third_party/cargo/vendor/calloop-0.4.4/Cargo.toml new file mode 100644 index 0000000..a7f1533 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/Cargo.toml @@ -0,0 +1,40 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "calloop" +version = "0.4.4" +authors = ["Victor Berger "] +autotests = false +description = "A callback-based event loop" +documentation = "https://docs.rs/calloop/" +keywords = ["events", "loop", "callback"] +license = "MIT" +repository = "https://github.com/Smithay/calloop" + +[[test]] +name = "signals" +harness = false +[dependencies.mio] +version = "0.6" + +[dependencies.mio-extras] +version = "2.0" +[dev-dependencies.lazycell] +version = "=1.0.0" +[target."cfg(unix)".dependencies.nix] +version = "0.14.1" +[badges.codecov] +repository = "Smithay/calloop" + +[badges.travis-ci] +repository = "Smithay/calloop" diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/LICENSE-MIT b/third_party/cargo/vendor/calloop-0.4.4/LICENSE.txt similarity index 96% rename from third_party/cargo/vendor/num_cpus-1.12.0/LICENSE-MIT rename to third_party/cargo/vendor/calloop-0.4.4/LICENSE.txt index 8e91dc9..5da38c6 100644 --- a/third_party/cargo/vendor/num_cpus-1.12.0/LICENSE-MIT +++ b/third_party/cargo/vendor/calloop-0.4.4/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2015 +Copyright (c) 2018 Victor Berger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -17,4 +17,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/third_party/cargo/vendor/calloop-0.4.4/README.md b/third_party/cargo/vendor/calloop-0.4.4/README.md new file mode 100644 index 0000000..575e146 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/README.md @@ -0,0 +1,86 @@ +[![crates.io](http://meritbadge.herokuapp.com/calloop)](https://crates.io/crates/calloop) +[![docs.rs](https://docs.rs/calloop/badge.svg)](https://docs.rs/calloop) +[![Build Status](https://travis-ci.org/Smithay/calloop.svg?branch=master)](https://travis-ci.org/Smithay/calloop) +[![Coverage Status](https://codecov.io/gh/Smithay/calloop/branch/master/graph/badge.svg)](https://codecov.io/gh/Smithay/calloop) + +# calloop + +Calloop, a Callback-based Event Loop + +This crate provides an `EventLoop` type, which is a small abstraction +over an `mio`-based event loop. The main difference between this crate +and other traditional rust event loops is that it is based on callbacks: +you can register several event sources, each being associated with a callback +closure that will be invoked whenever the associated event source generates +events. + +This crate was initially an implementation detail of `wayland-server`, and has been +split-off for reuse. I expect it to be more useful for GUI programs or graphical +servers (like wayland-based apps) than performance critial networking code, which are +more versed towards `tokio` and async-await. It mostly shines in the conception of +modular infrastructures, allowing different modules to use the same event loop without +needing to know about each other. + +### How to use it + +```rust +extern crate calloop; + +use std::time::Duration; + +fn main() { + // Create the event loop + let mut event_loop = calloop::EventLoop::new().expect("Failed to initialize the event loop!"); + // Retrieve an handle. It is used to insert new sources into the event loop + // It can be cloned, allowing you to insert sources from within sources + let handle = event_loop.handle(); + + /* + * Setup your program, inserting event sources in the loop + */ + + // Actual run of your loop + loop { + // Dispatch received events to their callbacks, waiting at most 20 ms for + // new events + // + // The `&mut shared_data` is a mutable reference that will be forwarded to all + // your callbacks, allowing them to easily share some state + event_loop.dispatch(Some(Duration::from_millis(20)), &mut shared_data); + + /* + * Insert here the processing you need to do do between each event loop run + * like your drawing logic if you're doing a GUI app for example. + */ + } +} +``` + +### Event source types + +The event loop is backed by `mio`, as such anything implementing the `mio::Evented` trait +can be used as an event source, with some adapter code (see the `EventSource` trait). + +This crate also provide some adapters for common event sources such as: + +- MPSC channels +- Timers +- unix signals + +As well as generic `mio::Evented` objects. + +It is also possible to insert "idle" callbacks. These callbacks represent computations that +need to be done at some point, but are not as urgent as processing the events. These callbacks +are stored and then executed during `EventLoop::dispatch(..)`, once all events from the sources +have been processed. + +### Custom event sources + +You can create custom event sources can will be inserted in the event loop by +implementing the `EventSource` trait. This notably involves the creation of an +internal type implementing the `EventDispatcher` trait, that will convert +readiness notifications from `mio` into events generated by your sources. For example, +by reading the new messages from a display server socket and producing an event and +calling the user callback for each of them. + +License: MIT diff --git a/third_party/cargo/vendor/calloop-0.4.4/README.tpl b/third_party/cargo/vendor/calloop-0.4.4/README.tpl new file mode 100644 index 0000000..41beef0 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/README.tpl @@ -0,0 +1,9 @@ +[![crates.io](http://meritbadge.herokuapp.com/calloop)](https://crates.io/crates/calloop) +[![docs.rs](https://docs.rs/calloop/badge.svg)](https://docs.rs/calloop) +{{badges}} + +# {{crate}} + +{{readme}} + +License: {{license}} \ No newline at end of file diff --git a/third_party/cargo/vendor/calloop-0.4.4/doc_index.html b/third_party/cargo/vendor/calloop-0.4.4/doc_index.html new file mode 100644 index 0000000..c2510eb --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/doc_index.html @@ -0,0 +1,6 @@ + + + + + + diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/lib.rs b/third_party/cargo/vendor/calloop-0.4.4/src/lib.rs new file mode 100644 index 0000000..42e4b4d --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/lib.rs @@ -0,0 +1,92 @@ +//! Calloop, a Callback-based Event Loop +//! +//! This crate provides an `EventLoop` type, which is a small abstraction +//! over an `mio`-based event loop. The main difference between this crate +//! and other traditional rust event loops is that it is based on callbacks: +//! you can register several event sources, each being associated with a callback +//! closure that will be invoked whenever the associated event source generates +//! events. +//! +//! This crate was initially an implementation detail of `wayland-server`, and has been +//! split-off for reuse. I expect it to be more useful for GUI programs or graphical +//! servers (like wayland-based apps) than performance critial networking code, which are +//! more versed towards `tokio` and async-await. It mostly shines in the conception of +//! modular infrastructures, allowing different modules to use the same event loop without +//! needing to know about each other. +//! +//! ## How to use it +//! +//! ```no_run +//! extern crate calloop; +//! +//! use std::time::Duration; +//! +//! fn main() { +//! // Create the event loop +//! let mut event_loop = calloop::EventLoop::new().expect("Failed to initialize the event loop!"); +//! // Retrieve an handle. It is used to insert new sources into the event loop +//! // It can be cloned, allowing you to insert sources from within sources +//! let handle = event_loop.handle(); +//! +//! /* +//! * Setup your program, inserting event sources in the loop +//! */ +//! +//! // Actual run of your loop +//! loop { +//! // Dispatch received events to their callbacks, waiting at most 20 ms for +//! // new events +//! // +//! // The `&mut shared_data` is a mutable reference that will be forwarded to all +//! // your callbacks, allowing them to easily share some state +//! # let mut shared_data = unimplemented!(); +//! event_loop.dispatch(Some(Duration::from_millis(20)), &mut shared_data); +//! +//! /* +//! * Insert here the processing you need to do do between each event loop run +//! * like your drawing logic if you're doing a GUI app for example. +//! */ +//! } +//! } +//! ``` +//! +//! ## Event source types +//! +//! The event loop is backed by `mio`, as such anything implementing the `mio::Evented` trait +//! can be used as an event source, with some adapter code (see the `EventSource` trait). +//! +//! This crate also provide some adapters for common event sources such as: +//! +//! - MPSC channels +//! - Timers +//! - unix signals +//! +//! As well as generic `mio::Evented` objects. +//! +//! It is also possible to insert "idle" callbacks. These callbacks represent computations that +//! need to be done at some point, but are not as urgent as processing the events. These callbacks +//! are stored and then executed during `EventLoop::dispatch(..)`, once all events from the sources +//! have been processed. +//! +//! ## Custom event sources +//! +//! You can create custom event sources can will be inserted in the event loop by +//! implementing the `EventSource` trait. This notably involves the creation of an +//! internal type implementing the `EventDispatcher` trait, that will convert +//! readiness notifications from `mio` into events generated by your sources. For example, +//! by reading the new messages from a display server socket and producing an event and +//! calling the user callback for each of them. + +#![warn(missing_docs)] + +pub extern crate mio; +extern crate mio_extras; +#[cfg(unix)] +extern crate nix; + +pub use self::loop_logic::{EventLoop, InsertError, LoopHandle, LoopSignal}; +pub use self::sources::*; + +mod list; +mod loop_logic; +mod sources; diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/list.rs b/third_party/cargo/vendor/calloop-0.4.4/src/list.rs new file mode 100644 index 0000000..e9e1356 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/list.rs @@ -0,0 +1,61 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use mio::Token; + +use sources::EventDispatcher; + +pub(crate) struct SourceList { + sources: Vec>>>>, +} + +impl SourceList { + pub(crate) fn new() -> SourceList { + SourceList { + sources: Vec::new(), + } + } + + pub(crate) fn get_dispatcher( + &self, + token: Token, + ) -> Option>>> { + match self.sources.get(token.0) { + Some(&Some(ref dispatcher)) => Some(dispatcher.clone()), + _ => None, + } + } + + pub(crate) fn add_source(&mut self, dispatcher: Rc>>) -> Token { + let free_id = self.sources.iter().position(Option::is_none); + if let Some(id) = free_id { + self.sources[id] = Some(dispatcher); + Token(id) + } else { + self.sources.push(Some(dispatcher)); + Token(self.sources.len() - 1) + } + } + + // this method returns the removed dispatcher to ensure it is not dropped + // while the refcell containing the list is borrowed, as dropping a dispatcher + // can trigger the removal of an other source + pub(crate) fn del_source( + &mut self, + token: Token, + ) -> Option>>> { + ::std::mem::replace(&mut self.sources[token.0], None) + } +} + +pub(crate) trait ErasedList { + // this returs a value for the same reason as above, but we must erase its type + // due to the `Data` parameter, hence Box + fn del_source(&mut self, token: Token) -> Box<::std::any::Any>; +} + +impl ErasedList for SourceList { + fn del_source(&mut self, token: Token) -> Box<::std::any::Any> { + Box::new(self.del_source(token)) + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/loop_logic.rs b/third_party/cargo/vendor/calloop-0.4.4/src/loop_logic.rs new file mode 100644 index 0000000..57850e1 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/loop_logic.rs @@ -0,0 +1,335 @@ +use std::cell::RefCell; +use std::fmt::{self, Debug, Formatter}; +use std::io; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use mio::{Events, Poll, PollOpt, Ready, Registration, SetReadiness}; + +use list::SourceList; +use sources::{EventSource, Idle, Source}; + +/// An handle to an event loop +/// +/// This handle allows you to insert new sources and idles in this event loop, +/// it can be cloned, and it is possible to insert new sources from within a source +/// callback. +pub struct LoopHandle { + poll: Rc, + list: Rc>>, + idles: Rc>>>>>>, +} + +impl Clone for LoopHandle { + fn clone(&self) -> LoopHandle { + LoopHandle { + poll: self.poll.clone(), + list: self.list.clone(), + idles: self.idles.clone(), + } + } +} + +/// An error generated when trying to insert an event source +pub struct InsertError { + /// The source that could not be inserted + pub source: E, + /// The generated error + pub error: io::Error, +} + +impl Debug for InsertError { + fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { + write!(formatter, "{:?}", self.error) + } +} + +impl From> for io::Error { + fn from(e: InsertError) -> io::Error { + e.error + } +} + +impl LoopHandle { + /// Insert an new event source in the loop + /// + /// The provided callback will be called during the dispatching cycles whenever the + /// associated source generates events, see `EventLoop::dispatch(..)` for details. + pub fn insert_source( + &self, + source: E, + callback: F, + ) -> Result, InsertError> { + let dispatcher = source.make_dispatcher(callback); + + let token = self.list.borrow_mut().add_source(dispatcher); + + let interest = source.interest(); + let opt = source.pollopts(); + + if let Err(e) = self.poll.register(&source, token, interest, opt) { + return Err(InsertError { source, error: e }); + } + + Ok(Source { + source, + poll: self.poll.clone(), + list: self.list.clone(), + token, + }) + } + + /// Insert an idle callback + /// + /// This callback will be called during a dispatching cycle when the event loop has + /// finished processing all pending events from the sources and becomes idle. + pub fn insert_idle(&self, callback: F) -> Idle { + let mut opt_cb = Some(callback); + let callback = Rc::new(RefCell::new(Some(Box::new(move |data: &mut Data| { + if let Some(cb) = opt_cb.take() { + cb(data); + } + }) as Box))); + self.idles.borrow_mut().push(callback.clone()); + Idle { callback } + } +} + +/// An event loop +/// +/// This loop can host several event sources, that can be dynamically added or removed. +pub struct EventLoop { + handle: LoopHandle, + events_buffer: Events, + stop_signal: Arc, + wakeup: SetReadiness, +} + +impl EventLoop { + /// Create a new event loop + /// + /// It is backed by an `mio` provided machinnery, and will fail if the `mio` + /// initialization fails. + pub fn new() -> io::Result> { + let handle = LoopHandle { + poll: Rc::new(Poll::new()?), + list: Rc::new(RefCell::new(SourceList::new())), + idles: Rc::new(RefCell::new(Vec::new())), + }; + // create a wakeup event source + let (wakeup_registration, wakeup_readiness) = Registration::new2(); + let mut wakeup_source = ::sources::generic::Generic::new(wakeup_registration); + wakeup_source.set_interest(Ready::readable()); + wakeup_source.set_pollopts(PollOpt::edge()); + let readiness2 = wakeup_readiness.clone(); + handle.insert_source(wakeup_source, move |_, _| { + // unmark the readiness so that the wakeup source is not + // processed in a loop + readiness2.set_readiness(Ready::empty()).unwrap(); + })?; + Ok(EventLoop { + handle, + events_buffer: Events::with_capacity(32), + stop_signal: Arc::new(AtomicBool::new(false)), + wakeup: wakeup_readiness, + }) + } + + /// Retrieve a loop handle + pub fn handle(&self) -> LoopHandle { + self.handle.clone() + } + + fn dispatch_events(&mut self, timeout: Option, data: &mut Data) -> io::Result<()> { + self.events_buffer.clear(); + self.handle.poll.poll(&mut self.events_buffer, timeout)?; + + loop { + if self.events_buffer.is_empty() { + break; + } + + for event in &self.events_buffer { + let opt_dispatcher = self.handle.list.borrow().get_dispatcher(event.token()); + if let Some(dispatcher) = opt_dispatcher { + dispatcher.borrow_mut().ready(event.readiness(), data); + } + } + + // process remaining events if any + self.events_buffer.clear(); + self.handle + .poll + .poll(&mut self.events_buffer, Some(Duration::from_millis(0)))?; + } + + Ok(()) + } + + fn dispatch_idles(&mut self, data: &mut Data) { + let idles = ::std::mem::replace(&mut *self.handle.idles.borrow_mut(), Vec::new()); + for idle in idles { + if let Some(ref mut callback) = *idle.borrow_mut() { + callback(data); + } + } + } + + /// Dispatch pending events to their callbacks + /// + /// Some source have events available, their callbacks will be immediatly called. + /// Otherwise this will wait until an event is receive or the provided `timeout` + /// is reached. If `timeout` is `None`, it will wait without a duration limit. + /// + /// Once pending events have been processed or the timeout is reached, all pending + /// idle callbacks will be fired before this method returns. + pub fn dispatch(&mut self, timeout: Option, data: &mut Data) -> io::Result<()> { + self.dispatch_events(timeout, data)?; + + self.dispatch_idles(data); + + Ok(()) + } + + /// Get a signal to stop this event loop from running + /// + /// To be used in conjunction with the `run()` method. + pub fn get_signal(&self) -> LoopSignal { + LoopSignal { + signal: self.stop_signal.clone(), + wakeup: self.wakeup.clone(), + } + } + + /// Run this event loop + /// + /// This will repeatedly try to dispatch events (see the `dispatch()` method) on + /// this event loop, waiting at most `timeout` every time. + /// + /// Between each dispatch wait, your provided callback will be called. + /// + /// You can use the `get_signal()` method to retrieve a way to stop or wakeup + /// the event loop from anywhere. + pub fn run( + &mut self, + timeout: Option, + data: &mut Data, + mut cb: F, + ) -> io::Result<()> + where + F: FnMut(&mut Data), + { + self.stop_signal.store(false, Ordering::Release); + while !self.stop_signal.load(Ordering::Acquire) { + self.dispatch(timeout, data)?; + cb(data); + } + Ok(()) + } +} + +/// A signal that can be shared between thread to stop or wakeup a running +/// event loop +#[derive(Clone)] +pub struct LoopSignal { + signal: Arc, + wakeup: SetReadiness, +} + +impl LoopSignal { + /// Stop the event loop + /// + /// Once this method is called, the next time the event loop has finished + /// waiting for events, it will return rather than starting to wait again. + /// + /// This is only usefull if you are using the `EventLoop::run()` method. + pub fn stop(&self) { + self.signal.store(true, Ordering::Release); + } + + /// Wake up the event loop + /// + /// This sends a dummy event to the event loop to simulate the reception + /// of an event, making the wait return early. Called after `stop()`, this + /// ensures the event loop will terminate quickly if you specified a long + /// timeout (or no timeout at all) to the `dispatch` or `run` method. + pub fn wakeup(&self) { + self.wakeup.set_readiness(Ready::readable()).unwrap(); + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::EventLoop; + + #[test] + fn dispatch_idle() { + let mut event_loop = EventLoop::new().unwrap(); + + let mut dispatched = false; + + event_loop.handle().insert_idle(|d| { + *d = true; + }); + + event_loop + .dispatch(Some(Duration::from_millis(0)), &mut dispatched) + .unwrap(); + + assert!(dispatched); + } + + #[test] + fn cancel_idle() { + let mut event_loop = EventLoop::new().unwrap(); + + let mut dispatched = false; + + let idle = event_loop.handle().insert_idle(move |d| { + *d = true; + }); + + idle.cancel(); + + event_loop + .dispatch(Some(Duration::from_millis(0)), &mut dispatched) + .unwrap(); + + assert!(!dispatched); + } + + #[test] + fn wakeup() { + let mut event_loop = EventLoop::new().unwrap(); + + let signal = event_loop.get_signal(); + + ::std::thread::spawn(move || { + ::std::thread::sleep(Duration::from_millis(500)); + signal.wakeup(); + }); + + // the test should return + event_loop.dispatch(None, &mut ()).unwrap(); + } + + #[test] + fn wakeup_stop() { + let mut event_loop = EventLoop::new().unwrap(); + + let signal = event_loop.get_signal(); + + ::std::thread::spawn(move || { + ::std::thread::sleep(Duration::from_millis(500)); + signal.stop(); + signal.wakeup(); + }); + + // the test should return + event_loop.run(None, &mut (), |_| {}).unwrap(); + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/sources/channel.rs b/third_party/cargo/vendor/calloop-0.4.4/src/sources/channel.rs new file mode 100644 index 0000000..7c72270 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/sources/channel.rs @@ -0,0 +1,183 @@ +//! An MPSC channel whose receiving end is an event source +//! +//! Create a channel using `Channel::::new()`, which returns a +//! `Sender` that can be cloned and sent accross threads if `T: Send`, +//! and a `Channel` that can be inserted into an `EventLoop`. It will generate +//! one event per message. +//! +//! This implementation is based on +//! [`mio_more::channel`](https://docs.rs/mio-more/*/mio_more/channel/index.html). + +use std::cell::RefCell; +use std::io; +use std::rc::Rc; +use std::sync::mpsc::TryRecvError; + +use mio::{Evented, Poll, PollOpt, Ready, Token}; + +use mio_extras::channel::{self as miochan, Receiver}; +pub use mio_extras::channel::{SendError, Sender, SyncSender, TrySendError}; + +use {EventDispatcher, EventSource}; + +/// The events generated by the channel event source +pub enum Event { + /// A message was received and is bundled here + Msg(T), + /// The channel was closed + /// + /// This means all the `Sender`s associated with this channel + /// have been dropped, no more messages will ever be received. + Closed, +} + +/// The receiving end of the channel +/// +/// This is the event source to be inserted into your `EventLoop`. +pub struct Channel { + receiver: Rc>, +} + +/// Create a new asynchronous channel +pub fn channel() -> (Sender, Channel) { + let (sender, receiver) = miochan::channel(); + ( + sender, + Channel { + receiver: Rc::new(receiver), + }, + ) +} + +/// Create a new synchronous, bounded channel +pub fn sync_channel(bound: usize) -> (SyncSender, Channel) { + let (sender, receiver) = miochan::sync_channel(bound); + ( + sender, + Channel { + receiver: Rc::new(receiver), + }, + ) +} + +impl Evented for Channel { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.receiver.register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.receiver.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.receiver.deregister(poll) + } +} + +impl EventSource for Channel { + type Event = Event; + + fn interest(&self) -> Ready { + Ready::readable() + } + + fn pollopts(&self) -> PollOpt { + PollOpt::edge() + } + + fn make_dispatcher, &mut Data) + 'static>( + &self, + callback: F, + ) -> Rc>> { + Rc::new(RefCell::new(Dispatcher { + _data: ::std::marker::PhantomData, + receiver: self.receiver.clone(), + callback, + })) + } +} + +struct Dispatcher, &mut Data)> { + _data: ::std::marker::PhantomData, + receiver: Rc>, + callback: F, +} + +impl, &mut Data)> EventDispatcher for Dispatcher { + fn ready(&mut self, _: Ready, data: &mut Data) { + loop { + match self.receiver.try_recv() { + Ok(val) => (self.callback)(Event::Msg(val), data), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + (self.callback)(Event::Closed, data); + break; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn basic_channel() { + let mut event_loop = ::EventLoop::new().unwrap(); + + let handle = event_loop.handle(); + + let (tx, rx) = channel::<()>(); + + // (got_msg, got_closed) + let mut got = (false, false); + + let _source = handle + .insert_source(rx, move |evt, got: &mut (bool, bool)| match evt { + Event::Msg(()) => { + got.0 = true; + } + Event::Closed => { + got.1 = true; + } + }) + .map_err(Into::::into) + .unwrap(); + + // nothing is sent, nothing is received + event_loop + .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) + .unwrap(); + + assert_eq!(got, (false, false)); + + // a message is send + tx.send(()).unwrap(); + event_loop + .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) + .unwrap(); + + assert_eq!(got, (true, false)); + + // the sender is dropped + ::std::mem::drop(tx); + event_loop + .dispatch(Some(::std::time::Duration::from_millis(0)), &mut got) + .unwrap(); + + assert_eq!(got, (true, true)); + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/sources/generic.rs b/third_party/cargo/vendor/calloop-0.4.4/src/sources/generic.rs new file mode 100644 index 0000000..dc70471 --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/sources/generic.rs @@ -0,0 +1,301 @@ +//! A generic event source wrapping an `Evented` type + +use std::cell::RefCell; +use std::io; +#[cfg(unix)] +use std::os::unix::io::{AsRawFd, RawFd}; +use std::rc::Rc; + +use mio::{Evented, Poll, PollOpt, Ready, Token}; + +use {EventDispatcher, EventSource}; + +/// A generic event source wrapping an `Evented` type +/// +/// It will simply forward the readiness and an acces to +/// the wrapped `Evented` type to the suer callback. See +/// the `Event` type in this module. +pub struct Generic { + inner: Rc>, + interest: Ready, + pollopts: PollOpt, +} + +impl Generic { + /// Wrap an `Evented` type into a `Generic` event source + /// + /// It is initialized with no interest nor poll options, + /// as such you should set them using the `set_interest` + /// and `set_pollopts` methods before inserting it in the + /// event loop. + pub fn new(source: E) -> Generic { + Generic { + inner: Rc::new(RefCell::new(source)), + interest: Ready::empty(), + pollopts: PollOpt::empty(), + } + } + + /// Wrap an `Evented` type from an `Rc` into a `Generic` event source + /// + /// Same as the `new` method, but you can provide a source that is alreay + /// in a reference counted pointer, so that `Generic` won't add a new + /// layer. This is useful if you need to share this source accross multiple + /// modules, and `calloop` is not the first one to be initialized. + pub fn from_rc(source: Rc>) -> Generic { + Generic { + inner: source, + interest: Ready::empty(), + pollopts: PollOpt::empty(), + } + } + + /// Change the interest for this evented source + /// + /// If the source was already inserted in an event loop, + /// it needs to be re-registered for the change to take + /// effect. + pub fn set_interest(&mut self, interest: Ready) { + self.interest = interest; + } + + /// Change the poll options for this evented source + /// + /// If the source was already inserted in an event loop, + /// it needs to be re-registered for the change to take + /// effect. + pub fn set_pollopts(&mut self, pollopts: PollOpt) { + self.pollopts = pollopts; + } + + /// Get a clone of the inner `Rc` wrapping your event source + pub fn clone_inner(&self) -> Rc> { + self.inner.clone() + } + + /// Unwrap the `Generic` source to retrieve the underlying `Evented`. + /// + /// If you didn't clone the `Rc>` from the `Event` you received, + /// the returned `Rc` should be unique. + pub fn unwrap(self) -> Rc> { + self.inner + } +} + +impl Generic> { + /// Wrap a file descriptor based source into a `Generic` event source. + /// + /// This will only work with poll-compatible file descriptors, which typically + /// not include basic files. + #[cfg(unix)] + pub fn from_fd_source(source: Fd) -> Generic> { + Generic::new(EventedFd(source)) + } +} + +impl Generic { + /// Wrap a raw file descriptor into a `Generic` event source. + /// + /// This will only work with poll-compatible file descriptors, which typically + /// not include basic files. + /// + /// This does _not_ take ownership of the file descriptor, hence you are responsible + /// of its correct lifetime. + #[cfg(unix)] + pub fn from_raw_fd(fd: RawFd) -> Generic { + Generic::new(EventedRawFd(fd)) + } +} + +/// An event generated by the `Generic` source +pub struct Event { + /// An access to the source that generated this event + pub source: Rc>, + /// The associated rediness + pub readiness: Ready, +} + +/// An owning wrapper implementing Evented for any file descriptor based type in Unix +#[cfg(unix)] +pub struct EventedFd(pub F); + +impl Evented for EventedFd { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0.as_raw_fd()).deregister(poll) + } +} + +/// A wrapper implementing Evented for any raw file descriptor. +/// +/// It does _not_ take ownership of the file descriptor, you are +/// responsible for ensuring its correct lifetime. +#[cfg(unix)] +pub struct EventedRawFd(pub RawFd); + +impl Evented for EventedRawFd { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0).register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + ::mio::unix::EventedFd(&self.0).deregister(poll) + } +} + +impl Evented for Generic { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.inner.borrow().register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.inner.borrow().reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner.borrow().deregister(poll) + } +} + +impl EventSource for Generic { + type Event = Event; + + fn interest(&self) -> Ready { + self.interest + } + + fn pollopts(&self) -> PollOpt { + self.pollopts + } + + fn make_dispatcher, &mut Data) + 'static>( + &self, + callback: F, + ) -> Rc>> { + Rc::new(RefCell::new(Dispatcher { + _data: ::std::marker::PhantomData, + inner: self.inner.clone(), + callback, + })) + } +} + +struct Dispatcher, &mut Data)> { + _data: ::std::marker::PhantomData, + inner: Rc>, + callback: F, +} + +impl, &mut Data)> EventDispatcher + for Dispatcher +{ + fn ready(&mut self, ready: Ready, data: &mut Data) { + (self.callback)( + Event { + source: self.inner.clone(), + readiness: ready, + }, + data, + ) + } +} + +#[cfg(test)] +mod test { + use std::io::{self, Read, Write}; + + use super::{Event, Generic}; + #[cfg(unix)] + #[test] + fn dispatch_unix() { + use std::os::unix::net::UnixStream; + + let mut event_loop = ::EventLoop::new().unwrap(); + + let handle = event_loop.handle(); + + let (mut tx, rx) = UnixStream::pair().unwrap(); + + let mut generic = Generic::from_fd_source(rx); + generic.set_interest(::mio::Ready::readable()); + + let mut dispached = false; + + handle + .insert_source(generic, move |Event { source, readiness }, d| { + assert!(readiness.is_readable()); + // we have not registered for writability + assert!(!readiness.is_writable()); + let mut buffer = vec![0; 10]; + let ret = source.borrow_mut().0.read(&mut buffer).unwrap(); + assert_eq!(ret, 6); + assert_eq!(&buffer[..6], &[1, 2, 3, 4, 5, 6]); + + *d = true; + }) + .map_err(Into::::into) + .unwrap(); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached) + .unwrap(); + + assert!(!dispached); + + tx.write(&[1, 2, 3, 4, 5, 6]).unwrap(); + tx.flush().unwrap(); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(0)), &mut dispached) + .unwrap(); + + assert!(dispached); + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/sources/mod.rs b/third_party/cargo/vendor/calloop-0.4.4/src/sources/mod.rs new file mode 100644 index 0000000..68e40ba --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/sources/mod.rs @@ -0,0 +1,123 @@ +use std::cell::RefCell; +use std::io; +use std::rc::Rc; + +use mio::{Evented, Poll, PollOpt, Ready, Token}; + +use list::ErasedList; + +pub mod channel; +pub mod generic; +#[cfg(target_os = "linux")] +pub mod signals; +pub mod timer; + +/// Trait representing a source that can be inserted into an EventLoop +/// +/// This is the interface between the source and the loop, you need to +/// implement it to use your custom event sources. +pub trait EventSource: Evented { + /// The type of events generated by your sources + type Event; + + /// The interest value that will be given to `mio` when registering your source + fn interest(&self) -> Ready; + + /// The pollopt value that will be given to `mio` when registering your source + fn pollopts(&self) -> PollOpt; + + /// Wrap an user callback into a dispatcher, that will convert an `mio` readiness + /// into an event + fn make_dispatcher( + &self, + callback: F, + ) -> Rc>>; +} + +/// An event dispatcher +/// +/// It is the junction between user callbacks and and an event source, +/// receiving `mio` readinesses, converting them into appropriate events +/// and calling their inner user callback. +pub trait EventDispatcher { + /// The source has a readiness event + fn ready(&mut self, ready: Ready, data: &mut Data); +} + +/// An event source that has been inserted into the event loop +/// +/// This handle allows you to remove it, and possibly more interactions +/// depending on the source kind that will be provided by the `Deref` +/// implementation of this struct to the evented object. +/// +/// Dropping this handle does not deregister this source from the event loop, +/// but will drop the wrapped `EventSource`, maybe rendering it inert depending on +/// its implementation. +pub struct Source { + pub(crate) source: E, + pub(crate) poll: Rc, + pub(crate) list: Rc>, + pub(crate) token: Token, +} + +impl Source { + /// Refresh the registration of this event source to the loop + /// + /// This can be necessary if the evented object provides methods to change + /// its behavior. Its documentation should inform you of the need for re-registration. + pub fn reregister(&self) -> io::Result<()> { + self.poll.reregister( + &self.source, + self.token, + self.source.interest(), + self.source.pollopts(), + ) + } + + /// Remove this source from the event loop + /// + /// You are given the evented object back. + pub fn remove(self) -> E { + let _ = self.poll.deregister(&self.source); + let _dispatcher = self.list.borrow_mut().del_source(self.token); + self.source + } +} + +impl ::std::ops::Deref for Source { + type Target = E; + fn deref(&self) -> &E { + &self.source + } +} + +impl ::std::ops::DerefMut for Source { + fn deref_mut(&mut self) -> &mut E { + &mut self.source + } +} + +/// An idle callback that was inserted in this loop +/// +/// This handle allows you to cancel the callback. Dropping +/// it will *not* cancel it. +pub struct Idle { + pub(crate) callback: Rc>, +} + +impl Idle { + /// Cancel the idle callback if it was not already run + pub fn cancel(self) { + self.callback.borrow_mut().cancel(); + } +} + +pub(crate) trait ErasedIdle { + fn cancel(&mut self); +} + +impl ErasedIdle for Option> { + fn cancel(&mut self) { + self.take(); + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/sources/signals.rs b/third_party/cargo/vendor/calloop-0.4.4/src/sources/signals.rs new file mode 100644 index 0000000..299940d --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/sources/signals.rs @@ -0,0 +1,217 @@ +//! Event source for tracking Unix signals +//! +//! Only available on `#[cfg(unix)]`. +//! +//! This allows you to track and receive Unix signals through the event loop +//! rather than by registering signal handlers. It uses `signalfd` under the hood. +//! +//! The source will take care of masking and unmasking signals for the thread it runs on, +//! but you are responsible for masking them on other threads if you run them. The simplest +//! way to ensure that is to setup the signal event source before spawning any thread, as +//! they'll inherit their parent signal mask. + +use std::cell::RefCell; +use std::io; +use std::os::raw::c_int; +use std::os::unix::io::AsRawFd; +use std::rc::Rc; + +use mio::{Evented, Poll, PollOpt, Ready, Token}; + +use nix::sys::signal::SigSet; +pub use nix::sys::signal::Signal; +pub use nix::sys::signalfd::siginfo; +use nix::sys::signalfd::{SfdFlags, SignalFd}; + +use {EventDispatcher, EventSource}; + +/// An event generated by the signal event source +#[derive(Copy, Clone)] +pub struct Event { + info: siginfo, +} + +impl Event { + /// Retrieve the signal number that was receive + pub fn signal(&self) -> Signal { + Signal::from_c_int(self.info.ssi_signo as c_int).unwrap() + } + + /// Access the full `siginfo_t` associated with this signal event + pub fn full_info(&self) -> siginfo { + self.info + } +} + +/// An event source for receiving Unix signals +pub struct Signals { + sfd: Rc>, + mask: SigSet, +} + +impl Signals { + /// Create a new signal event source listening on the specified list of signals + pub fn new(signals: &[Signal]) -> io::Result { + let mut mask = SigSet::empty(); + for &s in signals { + mask.add(s); + } + + // Mask the signals for this thread + mask.thread_block().map_err(no_nix_err)?; + // Create the SignalFd + let sfd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK | SfdFlags::SFD_CLOEXEC) + .map_err(no_nix_err)?; + + Ok(Signals { + sfd: Rc::new(RefCell::new(sfd)), + mask, + }) + } + + /// Add a list of signals to the signals source + /// + /// If this function returns an error, the signal mask of the thread may + /// have still been changed. + pub fn add_signals(&mut self, signals: &[Signal]) -> io::Result<()> { + for &s in signals { + self.mask.add(s); + } + self.mask.thread_block().map_err(no_nix_err)?; + self.sfd + .borrow_mut() + .set_mask(&self.mask) + .map_err(no_nix_err)?; + Ok(()) + } + + /// Remove a list of signals to the signals source + /// + /// If this function returns an error, the signal mask of the thread may + /// have still been changed. + pub fn remove_signals(&mut self, signals: &[Signal]) -> io::Result<()> { + let mut removed = SigSet::empty(); + for &s in signals { + self.mask.remove(s); + removed.add(s); + } + removed.thread_unblock().map_err(no_nix_err)?; + self.sfd + .borrow_mut() + .set_mask(&self.mask) + .map_err(no_nix_err)?; + Ok(()) + } + + /// Replace the list of signals of the source + /// + /// If this function returns an error, the signal mask of the thread may + /// have still been changed. + pub fn set_signals(&mut self, signals: &[Signal]) -> io::Result<()> { + let mut new_mask = SigSet::empty(); + for &s in signals { + new_mask.add(s); + } + + self.mask.thread_unblock().map_err(no_nix_err)?; + new_mask.thread_block().map_err(no_nix_err)?; + self.sfd + .borrow_mut() + .set_mask(&new_mask) + .map_err(no_nix_err)?; + self.mask = new_mask; + + Ok(()) + } +} + +impl Drop for Signals { + fn drop(&mut self) { + // we cannot handle error here + if let Err(e) = self.mask.thread_unblock() { + eprintln!("[calloop] Failed to unmask signals: {:?}", e); + } + } +} + +fn no_nix_err(err: ::nix::Error) -> io::Error { + match err { + ::nix::Error::Sys(errno) => errno.into(), + _ => unreachable!(), + } +} + +impl Evented for Signals { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.sfd.borrow().as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + ::mio::unix::EventedFd(&self.sfd.borrow().as_raw_fd()) + .reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + ::mio::unix::EventedFd(&self.sfd.borrow().as_raw_fd()).deregister(poll) + } +} + +impl EventSource for Signals { + type Event = Event; + + fn interest(&self) -> Ready { + Ready::readable() + } + + fn pollopts(&self) -> PollOpt { + PollOpt::edge() + } + + fn make_dispatcher( + &self, + callback: F, + ) -> Rc>> { + Rc::new(RefCell::new(Dispatcher { + _data: ::std::marker::PhantomData, + callback, + sfd: self.sfd.clone(), + })) + } +} + +struct Dispatcher { + _data: ::std::marker::PhantomData, + callback: F, + sfd: Rc>, +} + +impl EventDispatcher for Dispatcher { + fn ready(&mut self, _: Ready, data: &mut Data) { + loop { + let ret = self.sfd.borrow_mut().read_signal(); + match ret { + Ok(Some(info)) => (self.callback)(Event { info }, data), + Ok(None) => { + // nothing more to read + break; + } + Err(e) => { + eprintln!("[calloop] Error reading from signalfd: {:?}", e); + break; + } + } + } + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/src/sources/timer.rs b/third_party/cargo/vendor/calloop-0.4.4/src/sources/timer.rs new file mode 100644 index 0000000..57ff43e --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/src/sources/timer.rs @@ -0,0 +1,311 @@ +//! Timer-based event sources +//! +//! A `Timer` is a general time-tracking object. It is used by setting timeouts, +//! and generates events whenever a timeout expires. +//! +//! The `Timer` event source provides an handle `TimerHandle`, which is used +//! to set or cancel timeouts. This handle is cloneable and can be send accross threads +//! if `T: Send`, allowing you to setup timeouts from any point of your program. +//! +//! This implementation is based on +//! [`mio_more::timer`](https://docs.rs/mio-more/*/mio_more/timer/index.html). + +use std::cell::RefCell; +use std::io; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use mio::{Evented, Poll, PollOpt, Ready, Token}; + +use mio_extras::timer as mio_timer; + +pub use self::mio_timer::Timeout; + +use {EventDispatcher, EventSource}; + +/// A Timer event source +/// +/// It generates events of type `(T, TimerHandle)`, providing you +/// an handle inside the event callback, allowing you to set new timeouts +/// as a response to a timeout being reached (for reccuring ticks for example). +pub struct Timer { + inner: Arc>>, +} + +impl Timer { + /// Create a new timer with default parameters + /// + /// Default time resolution is 100ms + pub fn new() -> Timer { + Timer { + inner: Arc::new(Mutex::new(mio_timer::Builder::default().build())), + } + } + + /// Create a new timer with a specific time resolution + pub fn with_resolution(resolution: Duration) -> Timer { + Timer { + inner: Arc::new(Mutex::new( + mio_timer::Builder::default() + .tick_duration(resolution) + .build(), + )), + } + } + + /// Get an handle for this timer + pub fn handle(&self) -> TimerHandle { + TimerHandle { + inner: self.inner.clone(), + } + } +} + +/// An handle to a timer, used to set or cancel timeouts +/// +/// This handle can be cloned, and can be sent accross thread as long +/// as `T: Send`. +pub struct TimerHandle { + inner: Arc>>, +} + +// Manual impl of `Clone` as #[derive(Clone)] adds a `T: Clone` bound +impl Clone for TimerHandle { + fn clone(&self) -> TimerHandle { + TimerHandle { + inner: self.inner.clone(), + } + } +} + +impl TimerHandle { + /// Set a new timeout + /// + /// The associated `data` will be given as argument to the callback. + /// + /// The returned `Timeout` can be used to cancel it. You can drop it if you don't + /// plan to cancel this timeout. + /// + /// This method can fail if the timer already has too many pending timeouts, currently + /// capacity is `2^16`. + pub fn add_timeout(&self, delay_from_now: Duration, data: T) -> Timeout { + self.inner.lock().unwrap().set_timeout(delay_from_now, data) + } + + /// Cancel a previsouly set timeout and retrieve the associated data + /// + /// This method returns `None` if the timeout does not exist (it has already fired + /// or has already been cancelled). + pub fn cancel_timeout(&self, timeout: &Timeout) -> Option { + self.inner.lock().unwrap().cancel_timeout(timeout) + } +} + +impl Evented for Timer { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.inner + .lock() + .unwrap() + .register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.inner + .lock() + .unwrap() + .reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner.lock().unwrap().deregister(poll) + } +} + +impl EventSource for Timer { + type Event = (T, TimerHandle); + + fn interest(&self) -> Ready { + Ready::readable() + } + + fn pollopts(&self) -> PollOpt { + PollOpt::edge() + } + + fn make_dispatcher), &mut Data) + 'static>( + &self, + callback: F, + ) -> Rc>> { + Rc::new(RefCell::new(Dispatcher { + _data: ::std::marker::PhantomData, + timer: self.inner.clone(), + callback, + })) + } +} + +struct Dispatcher), &mut Data)> { + _data: ::std::marker::PhantomData, + timer: Arc>>, + callback: F, +} + +impl), &mut Data)> EventDispatcher + for Dispatcher +{ + fn ready(&mut self, _: Ready, data: &mut Data) { + let handle = TimerHandle { + inner: self.timer.clone(), + }; + loop { + let opt_evt = self.timer.lock().unwrap().poll(); + match opt_evt { + Some(val) => (self.callback)((val, handle.clone()), data), + None => break, + } + } + } +} + +#[cfg(test)] +mod tests { + use std::io; + use std::time::Duration; + + use super::*; + + #[test] + fn single_timer() { + let mut event_loop = ::EventLoop::new().unwrap(); + + let evl_handle = event_loop.handle(); + + let mut fired = false; + + let timer = evl_handle + .insert_source(Timer::<()>::new(), move |((), _), f| { + *f = true; + }) + .map_err(Into::::into) + .unwrap(); + + timer.handle().add_timeout(Duration::from_millis(300), ()); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(100)), &mut fired) + .unwrap(); + + // it should not have fired yet + assert!(!fired); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(300)), &mut fired) + .unwrap(); + + // it should have fired now + assert!(fired); + } + + #[test] + fn multi_timout_order() { + let mut event_loop = ::EventLoop::new().unwrap(); + + let evl_handle = event_loop.handle(); + + let mut fired = Vec::new(); + + let timer = evl_handle + .insert_source(Timer::new(), |(val, _), fired: &mut Vec| { + fired.push(val); + }) + .map_err(Into::::into) + .unwrap(); + + timer.handle().add_timeout(Duration::from_millis(300), 1); + timer.handle().add_timeout(Duration::from_millis(100), 2); + timer.handle().add_timeout(Duration::from_millis(600), 3); + + // 3 dispatches as each returns once at least one event occured + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(200)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2]); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(300)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2, 1]); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(400)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2, 1, 3]); + } + + #[test] + fn timer_cancel() { + let mut event_loop = ::EventLoop::new().unwrap(); + + let evl_handle = event_loop.handle(); + + let mut fired = Vec::new(); + + let timer = evl_handle + .insert_source(Timer::new(), |(val, _), fired: &mut Vec| { + fired.push(val) + }) + .map_err(Into::::into) + .unwrap(); + + let timeout1 = timer.handle().add_timeout(Duration::from_millis(300), 1); + let timeout2 = timer.handle().add_timeout(Duration::from_millis(100), 2); + let timeout3 = timer.handle().add_timeout(Duration::from_millis(600), 3); + + // 3 dispatches as each returns once at least one event occured + // + // The timeouts 1 and 3 and not cancelled right away, but still before they + // fire + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(200)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2]); + + // timeout2 has already fired, we cancel timeout1 + assert_eq!(timer.handle().cancel_timeout(&timeout2), None); + assert_eq!(timer.handle().cancel_timeout(&timeout1), Some(1)); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(300)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2]); + + // cancel timeout3 + assert_eq!(timer.handle().cancel_timeout(&timeout3), Some(3)); + + event_loop + .dispatch(Some(::std::time::Duration::from_millis(600)), &mut fired) + .unwrap(); + + assert_eq!(&fired, &[2]); + } +} diff --git a/third_party/cargo/vendor/calloop-0.4.4/tests/signals.rs b/third_party/cargo/vendor/calloop-0.4.4/tests/signals.rs new file mode 100644 index 0000000..5a1c19c --- /dev/null +++ b/third_party/cargo/vendor/calloop-0.4.4/tests/signals.rs @@ -0,0 +1,134 @@ +// These tests cannot run as a regular test because cargo would spawn a thread to run it, +// failing the signal masking. So we make our own, non-threaded harnessing + +#[cfg(unix)] +fn main() { + for test in self::test::TESTS { + test(); + // reset the signal mask between tests + self::test::reset_mask(); + } +} + +#[cfg(not(unix))] +fn main() {} + +#[cfg(unix)] +mod test { + extern crate calloop; + extern crate nix; + + use std::io; + use std::time::Duration; + + use self::calloop::signals::{Signal, Signals}; + use self::calloop::EventLoop; + + use self::nix::sys::signal::{kill, SigSet}; + use self::nix::unistd::Pid; + + pub const TESTS: &'static [fn()] = &[single_usr1, usr2_added_afterwards, usr2_signal_removed]; + + pub fn reset_mask() { + SigSet::empty().thread_set_mask().unwrap(); + } + + fn single_usr1() { + let mut event_loop = EventLoop::new().unwrap(); + + let mut signal_received = false; + + let _signal_source = event_loop + .handle() + .insert_source( + Signals::new(&[Signal::SIGUSR1]).unwrap(), + move |evt, rcv| { + assert!(evt.signal() == Signal::SIGUSR1); + *rcv = true; + }, + ) + .map_err(Into::::into) + .unwrap(); + + // send ourselves a SIGUSR1 + kill(Pid::this(), Signal::SIGUSR1).unwrap(); + + event_loop + .dispatch(Some(Duration::from_millis(10)), &mut signal_received) + .unwrap(); + + assert!(signal_received); + } + + fn usr2_added_afterwards() { + let mut event_loop = EventLoop::new().unwrap(); + + let mut signal_received = None; + + let mut signal_source = event_loop + .handle() + .insert_source( + Signals::new(&[Signal::SIGUSR1]).unwrap(), + move |evt, rcv| { + *rcv = Some(evt.signal()); + }, + ) + .map_err(Into::::into) + .unwrap(); + + signal_source.add_signals(&[Signal::SIGUSR2]).unwrap(); + + // send ourselves a SIGUSR2 + kill(Pid::this(), Signal::SIGUSR2).unwrap(); + + event_loop + .dispatch(Some(Duration::from_millis(10)), &mut signal_received) + .unwrap(); + + assert_eq!(signal_received, Some(Signal::SIGUSR2)); + } + + fn usr2_signal_removed() { + let mut event_loop = EventLoop::new().unwrap(); + + let mut signal_received = None; + + let mut signal_source = event_loop + .handle() + .insert_source( + Signals::new(&[Signal::SIGUSR1, Signal::SIGUSR2]).unwrap(), + move |evt, rcv| { + *rcv = Some(evt.signal()); + }, + ) + .map_err(Into::::into) + .unwrap(); + + signal_source.remove_signals(&[Signal::SIGUSR2]).unwrap(); + + // block sigusr2 anyway, to not be killed by it + let mut set = SigSet::empty(); + set.add(Signal::SIGUSR2); + set.thread_block().unwrap(); + + // send ourselves a SIGUSR2 + kill(Pid::this(), Signal::SIGUSR2).unwrap(); + + event_loop + .dispatch(Some(Duration::from_millis(10)), &mut signal_received) + .unwrap(); + + // we should not have received anything, as we don't listen to SIGUSR2 any more + assert!(signal_received.is_none()); + + // swap the signals from [SIGUSR1] to [SIGUSR2] + signal_source.set_signals(&[Signal::SIGUSR2]).unwrap(); + + event_loop + .dispatch(Some(Duration::from_millis(10)), &mut signal_received) + .unwrap(); + + // we should get back the pending SIGUSR2 now + assert_eq!(signal_received, Some(Signal::SIGUSR2)); + } +} diff --git a/third_party/cargo/vendor/cocoa-0.18.5/.cargo-checksum.json b/third_party/cargo/vendor/cocoa-0.18.5/.cargo-checksum.json deleted file mode 100644 index a0c0c5d..0000000 --- a/third_party/cargo/vendor/cocoa-0.18.5/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"20ce8f189d4910352c569016fec1e3a8c6b4a92c767f9d1c8507298abc49d3c4","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"6e4bf5158734b84c98500797326b90bb9da1d0b8dd6ccdba6dbc4284e41713a4","examples/fullscreen.rs":"f5ad7a0f9c44944c5ee84413ab9a106abd4d4e53534867c602651db7be722165","examples/hello_world.rs":"7efe2a29de4d4dfc1d8821f469e13b1456f72de478bab55f813d08d4e5aafd5c","examples/tab_view.rs":"e6a3187eeac2f46210994293c2db7756757f4cad07e519902fa994c6d5c1a7d6","src/appkit.rs":"24fff19b363dc1582557088856eb53642e6824761d60f8e0e11e5df0bfd9eccb","src/base.rs":"6c56d1758a9b0a7f8927771fe8b0bb43c6f19e4531bf9accecc786028eaad845","src/foundation.rs":"27f58705d615ddd401b710bf4741edb4f9cbf23d59dd3463a4b60f7d10eebde6","src/lib.rs":"55ba91363c74525de075864e78fc5f6ac8f3121daef9ed835988a09daae74d2d","src/quartzcore.rs":"cb4f96b4b095e9d623346a42b1e119a5299bf2af73ed81256dd548c688d525e2","tests/foundation.rs":"6a09eb4116e338281d7fdf6487fdebd580cfb82915627b58e8d8beeaec99eb5f"},"package":"1706996401131526e36b3b49f0c4d912639ce110996f3ca144d78946727bce54"} \ No newline at end of file diff --git a/third_party/cargo/vendor/cocoa-0.19.1/.cargo-checksum.json b/third_party/cargo/vendor/cocoa-0.19.1/.cargo-checksum.json new file mode 100644 index 0000000..8e9ee70 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.19.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.lock":"17a7bea6d9dc55027974371b67cac9b7e88d7a8d82993a66b4dd0fde612fb83c","Cargo.toml":"97c04060532c13f38c492e9623e3f20ae674dfad8ece40ba2d40ac9559cb3c5b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"29542cb34adb016506822ef78bceacf1774dbe8c27818a4d47b7d7b71ed4e1ac","examples/color.rs":"5211a85ab9ec4cbb98f8f677de50bb2f1d300400f50226ebfd714d40b9d32485","examples/fullscreen.rs":"f8719268b6eb1d19078af347e02f9993c9d29633ef2d38dcc4fac26cbd731c2d","examples/hello_world.rs":"7efe2a29de4d4dfc1d8821f469e13b1456f72de478bab55f813d08d4e5aafd5c","examples/tab_view.rs":"e6a3187eeac2f46210994293c2db7756757f4cad07e519902fa994c6d5c1a7d6","src/appkit.rs":"a21c6d612d0ec45dbbb5df45fe96d84b76c5a9982d09bdf74714ce63723da558","src/base.rs":"6c56d1758a9b0a7f8927771fe8b0bb43c6f19e4531bf9accecc786028eaad845","src/foundation.rs":"f0a8c0d2e3aee6bde64f480085025dfa92f903a39d6c15251ba392523aa153a3","src/lib.rs":"ed6164b3e0fe68579218185267d79229a2989c86efce690d7273f779c5239ec3","src/macros.rs":"0de0a8ea9a23f03cad94266a92051c3be8ff3f8f7d7d60f95dafe6c663204d48","src/quartzcore.rs":"cb4f96b4b095e9d623346a42b1e119a5299bf2af73ed81256dd548c688d525e2","tests/foundation.rs":"728eb7dcc9edbfb43dcb6aa1ebcc391658a7d47846d94a71905bcedfce833260"},"package":"f29f7768b2d1be17b96158e3285951d366b40211320fb30826a76cb7a0da6400"} \ No newline at end of file diff --git a/third_party/cargo/vendor/cocoa-0.18.5/BUILD b/third_party/cargo/vendor/cocoa-0.19.1/BUILD similarity index 94% rename from third_party/cargo/vendor/cocoa-0.18.5/BUILD rename to third_party/cargo/vendor/cocoa-0.19.1/BUILD index 9aa1730..1643499 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/BUILD +++ b/third_party/cargo/vendor/cocoa-0.19.1/BUILD @@ -42,11 +42,12 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.18.5", + version = "0.19.1", crate_features = [ ], ) +# Unsupported target "color" with type "example" omitted # Unsupported target "foundation" with type "test" omitted # Unsupported target "fullscreen" with type "example" omitted # Unsupported target "hello_world" with type "example" omitted diff --git a/third_party/cargo/vendor/cocoa-0.18.5/COPYRIGHT b/third_party/cargo/vendor/cocoa-0.19.1/COPYRIGHT similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/COPYRIGHT rename to third_party/cargo/vendor/cocoa-0.19.1/COPYRIGHT diff --git a/third_party/cargo/vendor/cocoa-0.19.1/Cargo.lock b/third_party/cargo/vendor/cocoa-0.19.1/Cargo.lock new file mode 100644 index 0000000..d354080 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.19.1/Cargo.lock @@ -0,0 +1,95 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cocoa" +version = "0.19.1" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.64 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.64 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation-sys" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "core-graphics" +version = "0.17.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.64 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.64" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.64 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "objc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +"checksum core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" +"checksum core-foundation-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" +"checksum core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)" = "56790968ab1c8a1202a102e6de05fc6e1ec87da99e4e93e9a7d13efbfc1e95a9" +"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +"checksum libc 0.2.64 (registry+https://github.com/rust-lang/crates.io-index)" = "74dfca3d9957906e8d1e6a0b641dc9a59848e793f1da2165889fd4f62d10d79c" +"checksum malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +"checksum objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "31d20fd2b37e07cf5125be68357b588672e8cefe9a96f8c17a9d46053b3e590d" diff --git a/third_party/cargo/vendor/cocoa-0.18.5/Cargo.toml b/third_party/cargo/vendor/cocoa-0.19.1/Cargo.toml similarity index 94% rename from third_party/cargo/vendor/cocoa-0.18.5/Cargo.toml rename to third_party/cargo/vendor/cocoa-0.19.1/Cargo.toml index dc11e2d..26f03e1 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/Cargo.toml +++ b/third_party/cargo/vendor/cocoa-0.19.1/Cargo.toml @@ -12,9 +12,9 @@ [package] name = "cocoa" -version = "0.18.5" +version = "0.19.1" authors = ["The Servo Project Developers"] -description = "Bindings to Cocoa for OS X" +description = "Bindings to Cocoa for macOS" homepage = "https://github.com/servo/core-foundation-rs" license = "MIT / Apache-2.0" repository = "https://github.com/servo/core-foundation-rs" diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/LICENSE-APACHE b/third_party/cargo/vendor/cocoa-0.19.1/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/arrayvec-0.4.12/LICENSE-APACHE rename to third_party/cargo/vendor/cocoa-0.19.1/LICENSE-APACHE diff --git a/third_party/cargo/vendor/cocoa-0.18.5/LICENSE-MIT b/third_party/cargo/vendor/cocoa-0.19.1/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/LICENSE-MIT rename to third_party/cargo/vendor/cocoa-0.19.1/LICENSE-MIT diff --git a/third_party/cargo/vendor/cocoa-0.18.5/README.md b/third_party/cargo/vendor/cocoa-0.19.1/README.md similarity index 68% rename from third_party/cargo/vendor/cocoa-0.18.5/README.md rename to third_party/cargo/vendor/cocoa-0.19.1/README.md index 3024bde..d1818d1 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/README.md +++ b/third_party/cargo/vendor/cocoa-0.19.1/README.md @@ -1,6 +1,6 @@ Cocoa-rs -------- -This crate provides Rust bindings to Cocoa for OSX. It's dual-licensed MIT / +This crate provides Rust bindings to Cocoa for macOS. It's dual-licensed MIT / Apache 2.0. If you'd like to help improve cocoa-rs, check out [the Servo contributing guide](https://github.com/servo/servo/blob/master/CONTRIBUTING.md)! diff --git a/third_party/cargo/vendor/cocoa-0.19.1/examples/color.rs b/third_party/cargo/vendor/cocoa-0.19.1/examples/color.rs new file mode 100644 index 0000000..af31514 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.19.1/examples/color.rs @@ -0,0 +1,120 @@ +extern crate cocoa; + +use cocoa::base::{selector, id, nil, NO}; + +use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, + NSString}; +use cocoa::appkit::{NSApp, NSColor, NSColorSpace, NSApplication, NSApplicationActivationPolicyRegular, + NSMenu, NSMenuItem, NSWindowStyleMask, NSBackingStoreType, NSWindow, + NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; + + +fn main() { + unsafe { + // Create the app. + let app = create_app(); + + // Create some colors + let clear = NSColor::clearColor(nil); + let black = NSColor::colorWithRed_green_blue_alpha_(nil, 0.0, 0.0, 0.0, 1.0); + let srgb_red = NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 1.0, 0.0, 0.0, 1.0); + let device_green = NSColor::colorWithDeviceRed_green_blue_alpha_(nil, 0.0, 1.0, 0.0, 1.0); + let display_p3_blue = NSColor::colorWithDisplayP3Red_green_blue_alpha_(nil, 0.0, 0.0, 1.0, 1.0); + let calibrated_cyan = NSColor::colorWithCalibratedRed_green_blue_alpha_(nil, 0.0, 1.0, 1.0, 1.0); + + // Create windows with different color types. + let _win_clear = create_window(NSString::alloc(nil).init_str("clear"), clear); + let _win_black = create_window(NSString::alloc(nil).init_str("black"), black); + let _win_srgb_red = create_window(NSString::alloc(nil).init_str("srgb_red"), srgb_red); + let _win_device_green = create_window(NSString::alloc(nil).init_str("device_green"), device_green); + let _win_display_p3_blue = create_window(NSString::alloc(nil).init_str("display_p3_blue"), display_p3_blue); + let _win_calibrated_cyan = create_window(NSString::alloc(nil).init_str("calibrated_cyan"), calibrated_cyan); + + // Extract component values from a color. + // NOTE: some components will raise an exception if the color is not + // in the correct NSColorSpace. Refer to Apple's documentation for details. + // https://developer.apple.com/documentation/appkit/nscolor?language=objc + let my_color = NSColor::colorWithRed_green_blue_alpha_(nil, 0.25, 0.75, 0.5, 0.25); + println!("alphaComponent: {:?}", my_color.alphaComponent()); + println!("redComponent: {:?}", my_color.redComponent()); + println!("greenComponent: {:?}", my_color.greenComponent()); + println!("blueComponent: {:?}", my_color.blueComponent()); + println!("hueComponent: {:?}", my_color.hueComponent()); + println!("saturationComponent: {:?}", my_color.saturationComponent()); + println!("brightnessComponent: {:?}", my_color.brightnessComponent()); + + // Changing color spaces. + let my_color_cmyk_cs = my_color.colorUsingColorSpace_(NSColorSpace::deviceCMYKColorSpace(nil)); + println!("blackComponent: {:?}", my_color_cmyk_cs.blackComponent()); + println!("cyanComponent: {:?}", my_color_cmyk_cs.cyanComponent()); + println!("magentaComponent: {:?}", my_color_cmyk_cs.magentaComponent()); + println!("yellowComponent: {:?}", my_color_cmyk_cs.yellowComponent()); + + // Getting NSColorSpace name. + let cs = NSColorSpace::genericGamma22GrayColorSpace(nil); + let cs_name = cs.localizedName(); + let cs_name_bytes = cs_name.UTF8String() as *const u8; + let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + println!("NSColorSpace: {:?}", cs_name_string); + + // Creating an NSColorSpace from CGColorSpaceRef. + let cg_cs = cs.CGColorSpace(); + let cs = NSColorSpace::alloc(nil).initWithCGColorSpace_(cg_cs); + let cs_name = cs.localizedName(); + let cs_name_bytes = cs_name.UTF8String() as *const u8; + let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + println!("initWithCGColorSpace_: {:?}", cs_name_string); + + app.run(); + } +} + +unsafe fn create_window(title: id, color: id) -> id { + let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask | + NSWindowStyleMask::NSClosableWindowMask | + NSWindowStyleMask::NSResizableWindowMask | + NSWindowStyleMask::NSMiniaturizableWindowMask | + NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, + NSBackingStoreType::NSBackingStoreBuffered, + NO + ).autorelease(); + + window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); + window.setTitle_(title); + window.setBackgroundColor_(color); + window.makeKeyAndOrderFront_(nil); + window +} + +unsafe fn create_app() -> id { + let _pool = NSAutoreleasePool::new(nil); + + let app = NSApp(); + app.setActivationPolicy_(NSApplicationActivationPolicyRegular); + + // create Menu Bar + let menubar = NSMenu::new(nil).autorelease(); + let app_menu_item = NSMenuItem::new(nil).autorelease(); + menubar.addItem_(app_menu_item); + app.setMainMenu_(menubar); + + // create Application menu + let app_menu = NSMenu::new(nil).autorelease(); + let quit_prefix = NSString::alloc(nil).init_str("Quit "); + let quit_title = + quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); + let quit_action = selector("terminate:"); + let quit_key = NSString::alloc(nil).init_str("q"); + let quit_item = NSMenuItem::alloc(nil) + .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) + .autorelease(); + app_menu.addItem_(quit_item); + app_menu_item.setSubmenu_(app_menu); + + let current_app = NSRunningApplication::currentApplication(nil); + current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); + + return app; +} diff --git a/third_party/cargo/vendor/cocoa-0.18.5/examples/fullscreen.rs b/third_party/cargo/vendor/cocoa-0.19.1/examples/fullscreen.rs similarity index 97% rename from third_party/cargo/vendor/cocoa-0.18.5/examples/fullscreen.rs rename to third_party/cargo/vendor/cocoa-0.19.1/examples/fullscreen.rs index df09d57..c826a29 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/examples/fullscreen.rs +++ b/third_party/cargo/vendor/cocoa-0.19.1/examples/fullscreen.rs @@ -76,7 +76,7 @@ fn main() { // create Window let display = CGDisplay::main(); - let size = NSSize::new(display.pixels_wide() as f64, display.pixels_high() as f64); + let size = NSSize::new(display.pixels_wide() as _, display.pixels_high() as _); let window = NSWindow::alloc(nil) .initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), size), NSWindowStyleMask::NSTitledWindowMask, diff --git a/third_party/cargo/vendor/cocoa-0.18.5/examples/hello_world.rs b/third_party/cargo/vendor/cocoa-0.19.1/examples/hello_world.rs similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/examples/hello_world.rs rename to third_party/cargo/vendor/cocoa-0.19.1/examples/hello_world.rs diff --git a/third_party/cargo/vendor/cocoa-0.18.5/examples/tab_view.rs b/third_party/cargo/vendor/cocoa-0.19.1/examples/tab_view.rs similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/examples/tab_view.rs rename to third_party/cargo/vendor/cocoa-0.19.1/examples/tab_view.rs diff --git a/third_party/cargo/vendor/cocoa-0.18.5/src/appkit.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/appkit.rs similarity index 91% rename from third_party/cargo/vendor/cocoa-0.18.5/src/appkit.rs rename to third_party/cargo/vendor/cocoa-0.19.1/src/appkit.rs index 883983b..53afce4 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/src/appkit.rs +++ b/third_party/cargo/vendor/cocoa-0.19.1/src/appkit.rs @@ -12,7 +12,7 @@ use base::{id, BOOL, SEL}; use block::Block; use foundation::{NSInteger, NSUInteger, NSTimeInterval, - NSPoint, NSSize, NSRect, NSRectEdge}; + NSPoint, NSSize, NSRect, NSRange, NSRectEdge}; use libc; pub use core_graphics::base::CGFloat; @@ -28,7 +28,7 @@ use std::os::raw::c_void; pub type CGLContextObj = *mut c_void; -pub type GLint = libc::int32_t; +pub type GLint = i32; #[link(name = "AppKit", kind = "framework")] extern { @@ -207,6 +207,14 @@ pub enum NSWindowTitleVisibility { NSWindowTitleHidden = 1 } +#[repr(i64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSWindowTabbingMode { + NSWindowTabbingModeAutomatic = 0, + NSWindowTabbingModeDisallowed = 1, + NSWindowTabbingModePreferred = 2 +} + #[repr(u64)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum NSBackingStoreType { @@ -363,7 +371,7 @@ pub enum NSRequestUserAttentionType { NSInformationalRequest = 10, } -pub static NSMainMenuWindowLevel: libc::int32_t = 24; +pub static NSMainMenuWindowLevel: i32 = 24; pub trait NSApplication: Sized { unsafe fn sharedApplication(_: Self) -> id { @@ -508,7 +516,7 @@ pub trait NSPasteboard: Sized { unsafe fn clearContents(self) -> NSInteger; unsafe fn writeObjects(self, objects: id) -> BOOL; - unsafe fn sendData_forType(self, data: id, dataType: id) -> BOOL; + unsafe fn setData_forType(self, data: id, dataType: id) -> BOOL; unsafe fn setPropertyList_forType(self, plist: id, dataType: id) -> BOOL; unsafe fn setString_forType(self, string: id, dataType: id) -> BOOL; @@ -552,8 +560,8 @@ impl NSPasteboard for id { msg_send![self, writeObjects:objects] } - unsafe fn sendData_forType(self, data: id, dataType: id) -> BOOL { - msg_send![self, sendData:data forType:dataType] + unsafe fn setData_forType(self, data: id, dataType: id) -> BOOL { + msg_send![self, setData:data forType:dataType] } unsafe fn setPropertyList_forType(self, plist: id, dataType: id) -> BOOL { @@ -813,6 +821,7 @@ pub trait NSMenuItem: Sized { unsafe fn initWithTitle_action_keyEquivalent_(self, title: id, action: SEL, key: id) -> id; unsafe fn setKeyEquivalentModifierMask_(self, mask: NSEventModifierFlags); unsafe fn setSubmenu_(self, submenu: id); + unsafe fn setTarget_(self, target: id); } impl NSMenuItem for id { @@ -827,6 +836,10 @@ impl NSMenuItem for id { unsafe fn setSubmenu_(self, submenu: id) { msg_send![self, setSubmenu:submenu] } + + unsafe fn setTarget_(self, target: id) { + msg_send![self, setTarget:target] + } } pub type NSWindowDepth = libc::c_int; @@ -1001,6 +1014,15 @@ pub trait NSWindow: Sized { // Managing Title Bars unsafe fn standardWindowButton_(self, windowButtonKind: NSWindowButton) -> id; + // Managing Window Tabs + unsafe fn allowsAutomaticWindowTabbing(_: Self) -> BOOL; + unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL); + unsafe fn tabbingIdentifier(self) -> id; + unsafe fn tabbingMode(self) -> NSWindowTabbingMode; + unsafe fn setTabbingMode_(self, tabbingMode: NSWindowTabbingMode); + unsafe fn addTabbedWindow_ordered_(self, window: id, ordering_mode: NSWindowOrderingMode); + unsafe fn toggleTabBar_(self, sender: id); + // TODO: Managing Tooltips // TODO: Handling Events @@ -1507,6 +1529,34 @@ impl NSWindow for id { msg_send![self, standardWindowButton:windowButtonKind] } + // Managing Window Tabs + unsafe fn allowsAutomaticWindowTabbing(_: Self) -> BOOL { + msg_send![class!(NSWindow), allowsAutomaticWindowTabbing] + } + + unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL) { + msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:allowsAutomaticWindowTabbing] + } + + unsafe fn tabbingIdentifier(self) -> id { + msg_send![self, tabbingIdentifier] + } + + unsafe fn tabbingMode(self) -> NSWindowTabbingMode { + msg_send!(self, tabbingMode) + } + + unsafe fn setTabbingMode_(self, tabbingMode: NSWindowTabbingMode) { + msg_send![self, setTabbingMode: tabbingMode] + } + + unsafe fn addTabbedWindow_ordered_(self, window: id, ordering_mode: NSWindowOrderingMode) { + msg_send![self, addTabbedWindow:window ordered: ordering_mode] + } + + unsafe fn toggleTabBar_(self, sender: id) { + msg_send![self, toggleTabBar:sender] + } // TODO: Managing Tooltips // TODO: Handling Events @@ -2309,6 +2359,7 @@ pub trait NSEvent: Sized { unsafe fn characters(self) -> id /* (NSString *) */; unsafe fn charactersIgnoringModifiers(self) -> id /* (NSString *) */; unsafe fn keyCode(self) -> libc::c_ushort; + unsafe fn isARepeat(self) -> BOOL; // Getting Mouse Event Information unsafe fn pressedMouseButtons(_: Self) -> NSUInteger; @@ -2557,6 +2608,10 @@ impl NSEvent for id { msg_send![self, keyCode] } + unsafe fn isARepeat(self) -> BOOL { + msg_send![self, isARepeat] + } + // Getting Mouse Event Information unsafe fn pressedMouseButtons(_: Self) -> NSUInteger { @@ -2866,6 +2921,45 @@ impl NSScreen for id { } } +// https://developer.apple.com/documentation/appkit/nscontrol?language=objc +pub trait NSControl: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSControl), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn isEnabled_(self) -> BOOL; + unsafe fn setEnabled_(self, enabled: BOOL) -> BOOL; +} + +impl NSControl for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn isEnabled_(self) -> BOOL { + msg_send![self, isEnabled] + } + unsafe fn setEnabled_(self, enabled: BOOL) -> BOOL { + msg_send![self, setEnabled:enabled] + } +} + +pub trait NSImageView: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSImageView), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setImage_(self, img: id /* (NSImage *) */); +} + +impl NSImageView for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn setImage_(self, img: id /* (NSImage *) */) { + msg_send![self, setImage:img] + } +} + pub trait NSButton: Sized { unsafe fn setImage_(self, img: id /* (NSImage *) */); unsafe fn setBezelStyle_(self, style: NSBezelStyle); @@ -2874,6 +2968,8 @@ pub trait NSButton: Sized { msg_send![class!(NSButton), alloc] } unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setTarget_(self, target: id /* Instance */); + unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance *) */); } impl NSButton for id { @@ -2889,6 +2985,13 @@ impl NSButton for id { unsafe fn setImage_(self, img: id /* (NSImage *) */) { msg_send![self, setImage:img] } + unsafe fn setTarget_(self, target: id /* (Instance *) */) { + msg_send![self, setTarget:target] + } + + unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance method *) */) { + msg_send![self, setAction:selector] + } } pub trait NSImage: Sized { @@ -3508,7 +3611,7 @@ pub trait NSTabView: Sized { unsafe fn new(_: Self) -> id { msg_send![class!(NSTabView), new] } - + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; unsafe fn addTabViewItem_(self, tabViewItem: id); unsafe fn insertTabViewItem_atIndex_(self,tabViewItem:id, index:NSInteger); @@ -3803,16 +3906,166 @@ impl NSLayoutDimension for id { unsafe fn constraintGreaterThanOrEqualToConstant(self, c: CGFloat) -> id { msg_send![self, constraintGreaterThanOrEqualToConstant:c] } - } +} + +pub trait NSColorSpace: Sized { + unsafe fn deviceRGBColorSpace(_:Self) -> id; + unsafe fn genericRGBColorSpace(_:Self) -> id; + unsafe fn deviceCMYKColorSpace(_:Self) -> id; + unsafe fn genericCMYKColorSpace(_:Self) -> id; + unsafe fn deviceGrayColorSpace(_:Self) -> id; + unsafe fn genericGrayColorSpace(_:Self) -> id; + unsafe fn sRGBColorSpace(_:Self) -> id; + unsafe fn extendedSRGBColorSpace(_:Self) -> id; + unsafe fn displayP3ColorSpace(_:Self) -> id; + unsafe fn genericGamma22GrayColorSpace(_:Self) -> id; + unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id; + unsafe fn adobeRGB1998ColorSpace(_:Self) -> id; + + unsafe fn alloc(_: Self) -> id; + + unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id; + unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */; + unsafe fn localizedName(self) -> id; +} + +impl NSColorSpace for id { + unsafe fn deviceRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceRGBColorSpace] + } + unsafe fn genericRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericRGBColorSpace] + } + unsafe fn deviceCMYKColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceCMYKColorSpace] + } + unsafe fn genericCMYKColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericCMYKColorSpace] + } + unsafe fn deviceGrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceGrayColorSpace] + } + unsafe fn genericGrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericGrayColorSpace] + } + unsafe fn sRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), sRGBColorSpace] + } + unsafe fn extendedSRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), extendedSRGBColorSpace] + } + unsafe fn displayP3ColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), displayP3ColorSpace] + } + unsafe fn genericGamma22GrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericGamma22GrayColorSpace] + } + unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), extendedGenericGamma22GrayColorSpace] + } + unsafe fn adobeRGB1998ColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), adobeRGB1998ColorSpace] + } + + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSColorSpace), alloc] + } + + unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id { + msg_send![self, initWithCGColorSpace:cg_color_space] + } + unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */ { + msg_send![self, CGColorSpace] + } + unsafe fn localizedName(self) -> id { + msg_send![self, localizedName] + } +} pub trait NSColor: Sized { unsafe fn clearColor(_: Self) -> id; + unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + + unsafe fn colorUsingColorSpace_(self, color_space: id) -> id; + + unsafe fn alphaComponent(self) -> CGFloat; + unsafe fn whiteComponent(self) -> CGFloat; + unsafe fn redComponent(self) -> CGFloat; + unsafe fn greenComponent(self) -> CGFloat; + unsafe fn blueComponent(self) -> CGFloat; + unsafe fn cyanComponent(self) -> CGFloat; + unsafe fn magentaComponent(self) -> CGFloat; + unsafe fn yellowComponent(self) -> CGFloat; + unsafe fn blackComponent(self) -> CGFloat; + unsafe fn hueComponent(self) -> CGFloat; + unsafe fn saturationComponent(self) -> CGFloat; + unsafe fn brightnessComponent(self) -> CGFloat; } impl NSColor for id { unsafe fn clearColor(_: Self) -> id { msg_send![class!(NSColor), clearColor] } + unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithSRGBRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithDeviceRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithDisplayP3Red:r green:g blue:b alpha:a] + } + unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithCalibratedRed:r green:g blue:b alpha:a] + } + + unsafe fn colorUsingColorSpace_(self, color_space: id) -> id { + msg_send![self, colorUsingColorSpace:color_space] + } + + unsafe fn alphaComponent(self) -> CGFloat { + msg_send![self, alphaComponent] + } + unsafe fn whiteComponent(self) -> CGFloat { + msg_send![self, whiteComponent] + } + unsafe fn redComponent(self) -> CGFloat { + msg_send![self, redComponent] + } + unsafe fn greenComponent(self) -> CGFloat { + msg_send![self, greenComponent] + } + unsafe fn blueComponent(self) -> CGFloat { + msg_send![self, blueComponent] + } + unsafe fn cyanComponent(self) -> CGFloat { + msg_send![self, cyanComponent] + } + unsafe fn magentaComponent(self) -> CGFloat { + msg_send![self, magentaComponent] + } + unsafe fn yellowComponent(self) -> CGFloat { + msg_send![self, yellowComponent] + } + unsafe fn blackComponent(self) -> CGFloat { + msg_send![self, blackComponent] + } + unsafe fn hueComponent(self) -> CGFloat { + msg_send![self, hueComponent] + } + unsafe fn saturationComponent(self) -> CGFloat { + msg_send![self, saturationComponent] + } + unsafe fn brightnessComponent(self) -> CGFloat { + msg_send![self, brightnessComponent] + } } pub trait NSToolbar: Sized { @@ -3845,6 +4098,81 @@ impl NSToolbar for id { } } +pub trait NSSpellChecker : Sized { + unsafe fn sharedSpellChecker(_: Self) -> id; + unsafe fn checkSpellingOfString_startingAt(self, + stringToCheck: id, + startingOffset: NSInteger) -> NSRange; + unsafe fn checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount( + self, + stringToCheck: id, + startingOffset: NSInteger, + language: id, + wrapFlag: BOOL, + tag: NSInteger) -> (NSRange, NSInteger); + unsafe fn uniqueSpellDocumentTag(_: Self) -> NSInteger; + unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger); + unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger); +} + +impl NSSpellChecker for id { + unsafe fn sharedSpellChecker(_: Self) -> id { + msg_send![class!(NSSpellChecker), sharedSpellChecker] + } + + unsafe fn checkSpellingOfString_startingAt(self, + stringToCheck: id, + startingOffset: NSInteger) -> NSRange { + msg_send![self, checkSpellingOfString:stringToCheck startingAt:startingOffset] + } + + unsafe fn checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount( + self, + stringToCheck: id, + startingOffset: NSInteger, + language: id, + wrapFlag: BOOL, + tag: NSInteger) -> (NSRange, NSInteger) { + let mut wordCount = 0; + let range = msg_send![self, + checkSpellingOfString:stringToCheck + startingAt:startingOffset + language:language + wrap:wrapFlag + inSpellDocumentWithTag:tag + wordCount:&mut wordCount + ]; + (range, wordCount) + } + + unsafe fn uniqueSpellDocumentTag(_: Self) -> NSInteger { + msg_send![class!(NSSpellChecker), uniqueSpellDocumentTag] + } + + unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger) { + msg_send![self, closeSpellDocumentWithTag:tag] + } + + unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger) { + msg_send![self, ignoreWord:wordToIgnore inSpellDocumentWithTag:tag] + } +} + +pub trait NSNib: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSNib), alloc] + } + + unsafe fn initWithNibNamed_bundle_(self, name: id, bundle: id) -> id; +} + +impl NSNib for id { + unsafe fn initWithNibNamed_bundle_(self, name: id, bundle: id) -> id { + msg_send![self, initWithNibNamed:name bundle:bundle] + } +} + + #[cfg(test)] mod test { use super::*; diff --git a/third_party/cargo/vendor/cocoa-0.18.5/src/base.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/base.rs similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/src/base.rs rename to third_party/cargo/vendor/cocoa-0.19.1/src/base.rs diff --git a/third_party/cargo/vendor/cocoa-0.18.5/src/foundation.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/foundation.rs similarity index 61% rename from third_party/cargo/vendor/cocoa-0.18.5/src/foundation.rs rename to third_party/cargo/vendor/cocoa-0.19.1/src/foundation.rs index b70e0cd..d87c446 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/src/foundation.rs +++ b/third_party/cargo/vendor/cocoa-0.19.1/src/foundation.rs @@ -26,6 +26,9 @@ pub type NSInteger = libc::c_long; #[cfg(target_pointer_width = "64")] pub type NSUInteger = libc::c_ulong; +pub const NSIntegerMax: NSInteger = NSInteger::max_value(); +pub const NSNotFound: NSInteger = NSIntegerMax; + const UTF8_ENCODING: usize = 4; #[cfg(target_os = "macos")] @@ -39,13 +42,13 @@ mod macos { #[repr(C)] #[derive(Copy, Clone)] pub struct NSPoint { - pub x: f64, - pub y: f64, + pub x: CGFloat, + pub y: CGFloat, } impl NSPoint { #[inline] - pub fn new(x: f64, y: f64) -> NSPoint { + pub fn new(x: CGFloat, y: CGFloat) -> NSPoint { NSPoint { x: x, y: y, @@ -56,8 +59,8 @@ mod macos { unsafe impl objc::Encode for NSPoint { fn encode() -> objc::Encoding { let encoding = format!("{{CGPoint={}{}}}", - f64::encode().as_str(), - f64::encode().as_str()); + CGFloat::encode().as_str(), + CGFloat::encode().as_str()); unsafe { objc::Encoding::from_str(&encoding) } } } @@ -65,13 +68,13 @@ mod macos { #[repr(C)] #[derive(Copy, Clone)] pub struct NSSize { - pub width: f64, - pub height: f64, + pub width: CGFloat, + pub height: CGFloat, } impl NSSize { #[inline] - pub fn new(width: f64, height: f64) -> NSSize { + pub fn new(width: CGFloat, height: CGFloat) -> NSSize { NSSize { width: width, height: height, @@ -82,8 +85,8 @@ mod macos { unsafe impl objc::Encode for NSSize { fn encode() -> objc::Encoding { let encoding = format!("{{CGSize={}{}}}", - f64::encode().as_str(), - f64::encode().as_str()); + CGFloat::encode().as_str(), + CGFloat::encode().as_str()); unsafe { objc::Encoding::from_str(&encoding) } } } @@ -160,6 +163,7 @@ mod macos { pub use self::macos::*; #[repr(C)] +#[derive(Copy, Clone)] pub struct NSRange { pub location: NSUInteger, pub length: NSUInteger, @@ -229,11 +233,24 @@ pub trait NSArray: Sized { msg_send![class!(NSArray), arrayWithObject:object] } + unsafe fn init(self) -> id; + + unsafe fn count(self) -> NSUInteger; + unsafe fn arrayByAddingObjectFromArray(self, object: id) -> id; unsafe fn arrayByAddingObjectsFromArray(self, objects: id) -> id; + unsafe fn objectAtIndex(self, index: NSUInteger) -> id; } impl NSArray for id { + unsafe fn init(self) -> id { + msg_send![self, init] + } + + unsafe fn count(self) -> NSUInteger { + msg_send![self, count] + } + unsafe fn arrayByAddingObjectFromArray(self, object: id) -> id { msg_send![self, arrayByAddingObjectFromArray:object] } @@ -241,6 +258,10 @@ impl NSArray for id { unsafe fn arrayByAddingObjectsFromArray(self, objects: id) -> id { msg_send![self, arrayByAddingObjectsFromArray:objects] } + + unsafe fn objectAtIndex(self, index: NSUInteger) -> id { + msg_send![self, objectAtIndex:index] + } } pub trait NSDictionary: Sized { @@ -555,6 +576,7 @@ pub trait NSString: Sized { unsafe fn UTF8String(self) -> *const libc::c_char; unsafe fn len(self) -> usize; unsafe fn isEqualToString(self, &str) -> bool; + unsafe fn substringWithRange(self, range: NSRange) -> id; } impl NSString for id { @@ -582,6 +604,10 @@ impl NSString for id { unsafe fn UTF8String(self) -> *const libc::c_char { msg_send![self, UTF8String] } + + unsafe fn substringWithRange(self, range: NSRange) -> id { + msg_send![self, substringWithRange:range] + } } pub trait NSDate: Sized { @@ -701,6 +727,365 @@ impl NSRunLoop for id { } } +bitflags! { + pub struct NSURLBookmarkCreationOptions: NSUInteger { + const NSURLBookmarkCreationPreferFileIDResolution = 1 << 8; + const NSURLBookmarkCreationMinimalBookmark = 1 << 9; + const NSURLBookmarkCreationSuitableForBookmarkFile = 1 << 10; + const NSURLBookmarkCreationWithSecurityScope = 1 << 11; + const NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess = 1 << 12; + } +} + +pub type NSURLBookmarkFileCreationOptions = NSURLBookmarkCreationOptions; + +bitflags! { + pub struct NSURLBookmarkResolutionOptions: NSUInteger { + const NSURLBookmarkResolutionWithoutUI = 1 << 8; + const NSURLBookmarkResolutionWithoutMounting = 1 << 9; + const NSURLBookmarkResolutionWithSecurityScope = 1 << 10; + } +} + + +pub trait NSURL: Sized { + unsafe fn alloc(_: Self) -> id; + + unsafe fn URLWithString_(_:Self, string: id) -> id; + unsafe fn initWithString_(self, string: id) -> id; + unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id; + unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id; + unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id; + unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id; + unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id; + unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id; + unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id; + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id; + unsafe fn fileURLWithPath_(_:Self, path: id) -> id; + unsafe fn initFileURLWithPath_(self, path: id) -> id; + unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id; + unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id; + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; + // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + // unsafe fn getFileSystemRepresentation_maxLength_ + // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; + unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; + unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; + unsafe fn dataRepresentation(self) -> id /* (NSData) */; + + unsafe fn isEqual_(self, id: id) -> BOOL; + + unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL; + unsafe fn isFileReferenceURL(self) -> BOOL; + unsafe fn isFileURL(self) -> BOOL; + + unsafe fn absoluteString(self) -> id /* (NSString) */; + unsafe fn absoluteURL(self) -> id /* (NSURL) */; + unsafe fn baseURL(self) -> id /* (NSURL) */; + // unsafe fn fileSystemRepresentation + unsafe fn fragment(self) -> id /* (NSString) */; + unsafe fn host(self) -> id /* (NSString) */; + unsafe fn lastPathComponent(self) -> id /* (NSString) */; + unsafe fn parameterString(self) -> id /* (NSString) */; + unsafe fn password(self) -> id /* (NSString) */; + unsafe fn path(self) -> id /* (NSString) */; + unsafe fn pathComponents(self) -> id /* (NSArray) */; + unsafe fn pathExtension(self) -> id /* (NSString) */; + unsafe fn port(self) -> id /* (NSNumber) */; + unsafe fn query(self) -> id /* (NSString) */; + unsafe fn relativePath(self) -> id /* (NSString) */; + unsafe fn relativeString(self) -> id /* (NSString) */; + unsafe fn resourceSpecifier(self) -> id /* (NSString) */; + unsafe fn scheme(self) -> id /* (NSString) */; + unsafe fn standardizedURL(self) -> id /* (NSURL) */; + unsafe fn user(self) -> id /* (NSString) */; + + // unsafe fn resourceValuesForKeys_error_ + // unsafe fn getResourceValue_forKey_error_ + // unsafe fn setResourceValue_forKey_error_ + // unsafe fn setResourceValues_error_ + // unsafe fn removeAllCachedResourceValues + // unsafe fn removeCachedResourceValueForKey_ + // unsafe fn setTemporaryResourceValue_forKey_ + unsafe fn NSURLResourceKey(self) -> id /* (NSString) */; + + unsafe fn filePathURL(self) -> id; + unsafe fn fileReferenceURL(self) -> id; + unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id; + unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id; + unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id; + unsafe fn URLByDeletingLastPathComponent(self) -> id; + unsafe fn URLByDeletingPathExtension(self) -> id; + unsafe fn URLByResolvingSymlinksInPath(self) -> id; + unsafe fn URLByStandardizingPath(self) -> id; + unsafe fn hasDirectoryPath(self) -> BOOL; + + unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; + // unsafe fn resourceValuesForKeys_fromBookmarkData_ + unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id; + unsafe fn startAccessingSecurityScopedResource(self) -> BOOL; + unsafe fn stopAccessingSecurityScopedResource(self); + unsafe fn NSURLBookmarkFileCreationOptions(self) -> NSURLBookmarkFileCreationOptions; + unsafe fn NSURLBookmarkCreationOptions(self) -> NSURLBookmarkCreationOptions; + unsafe fn NSURLBookmarkResolutionOptions(self) -> NSURLBookmarkResolutionOptions; + + // unsafe fn checkPromisedItemIsReachableAndReturnError_ + // unsafe fn getPromisedItemResourceValue_forKey_error_ + // unsafe fn promisedItemResourceValuesForKeys_error_ + + // unsafe fn URLFromPasteboard_ + // unsafe fn writeToPasteboard_ +} + +impl NSURL for id { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSURL), alloc] + } + + unsafe fn URLWithString_(_:Self, string: id) -> id { + msg_send![class!(NSURL), URLWithString:string] + } + unsafe fn initWithString_(self, string: id) -> id { + msg_send![self, initWithString:string] + } + unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id { + msg_send![class!(NSURL), URLWithString: string relativeToURL:url] + } + unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id { + msg_send![self, initWithString:string relativeToURL:url] + } + unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id { + msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir] + } + unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id { + msg_send![self, initFileURLWithPath:path isDirectory:is_dir] + } + unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path relativeToURL:url] + } + unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id { + msg_send![self, initFileURLWithPath:path relativeToURL:url] + } + unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir relativeToURL:url] + } + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id { + msg_send![self, initFileURLWithPath:path isDirectory:is_dir relativeToURL:url] + } + unsafe fn fileURLWithPath_(_:Self, path: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path] + } + unsafe fn initFileURLWithPath_(self, path: id) -> id { + msg_send![self, initFileURLWithPath:path] + } + unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id { + msg_send![class!(NSURL), fileURLWithPathComponents:path_components] + } + unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), URLByResolvingAliasFileAtURL:url options:options error:error] + } + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), URLByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] + } + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![self, initByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] + } + // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + // unsafe fn getFileSystemRepresentation_maxLength_ + // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + msg_send![class!(NSURL), absoluteURLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + msg_send![self, initAbsoluteURLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + msg_send![class!(NSURL), URLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + msg_send![self, initWithDataRepresentation:data relativeToURL:url] + } + unsafe fn dataRepresentation(self) -> id /* (NSData) */ { + msg_send![self, dataRepresentation] + } + + unsafe fn isEqual_(self, id: id) -> BOOL { + msg_send![self, isEqual:id] + } + + unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL { + msg_send![self, checkResourceIsReachableAndReturnError:error] + } + unsafe fn isFileReferenceURL(self) -> BOOL { + msg_send![self, isFileReferenceURL] + } + unsafe fn isFileURL(self) -> BOOL { + msg_send![self, isFileURL] + } + + unsafe fn absoluteString(self) -> id /* (NSString) */ { + msg_send![self, absoluteString] + } + unsafe fn absoluteURL(self) -> id /* (NSURL) */ { + msg_send![self, absoluteURL] + } + unsafe fn baseURL(self) -> id /* (NSURL) */ { + msg_send![self, baseURL] + } + // unsafe fn fileSystemRepresentation + unsafe fn fragment(self) -> id /* (NSString) */ { + msg_send![self, fragment] + } + unsafe fn host(self) -> id /* (NSString) */ { + msg_send![self, host] + } + unsafe fn lastPathComponent(self) -> id /* (NSString) */ { + msg_send![self, lastPathComponent] + } + unsafe fn parameterString(self) -> id /* (NSString) */ { + msg_send![self, parameterString] + } + unsafe fn password(self) -> id /* (NSString) */ { + msg_send![self, password] + } + unsafe fn path(self) -> id /* (NSString) */ { + msg_send![self, path] + } + unsafe fn pathComponents(self) -> id /* (NSArray) */ { + msg_send![self, pathComponents] + } + unsafe fn pathExtension(self) -> id /* (NSString) */ { + msg_send![self, pathExtension] + } + unsafe fn port(self) -> id /* (NSNumber) */ { + msg_send![self, port] + } + unsafe fn query(self) -> id /* (NSString) */ { + msg_send![self, query] + } + unsafe fn relativePath(self) -> id /* (NSString) */ { + msg_send![self, relativePath] + } + unsafe fn relativeString(self) -> id /* (NSString) */ { + msg_send![self, relativeString] + } + unsafe fn resourceSpecifier(self) -> id /* (NSString) */ { + msg_send![self, resourceSpecifier] + } + unsafe fn scheme(self) -> id /* (NSString) */ { + msg_send![self, scheme] + } + unsafe fn standardizedURL(self) -> id /* (NSURL) */ { + msg_send![self, standardizedURL] + } + unsafe fn user(self) -> id /* (NSString) */ { + msg_send![self, user] + } + + // unsafe fn resourceValuesForKeys_error_ + // unsafe fn getResourceValue_forKey_error_ + // unsafe fn setResourceValue_forKey_error_ + // unsafe fn setResourceValues_error_ + // unsafe fn removeAllCachedResourceValues + // unsafe fn removeCachedResourceValueForKey_ + // unsafe fn setTemporaryResourceValue_forKey_ + unsafe fn NSURLResourceKey(self) -> id /* (NSString) */ { + msg_send![self, NSURLResourceKey] + } + + unsafe fn filePathURL(self) -> id { + msg_send![self, filePathURL] + } + unsafe fn fileReferenceURL(self) -> id { + msg_send![self, fileReferenceURL] + } + unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id { + msg_send![self, URLByAppendingPathComponent:path_component] + } + unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id { + msg_send![self, URLByAppendingPathComponent:path_component isDirectory:is_dir] + } + unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id { + msg_send![self, URLByAppendingPathExtension:extension] + } + unsafe fn URLByDeletingLastPathComponent(self) -> id { + msg_send![self, URLByDeletingLastPathComponent] + } + unsafe fn URLByDeletingPathExtension(self) -> id { + msg_send![self, URLByDeletingPathExtension] + } + unsafe fn URLByResolvingSymlinksInPath(self) -> id { + msg_send![self, URLByResolvingSymlinksInPath] + } + unsafe fn URLByStandardizingPath(self) -> id { + msg_send![self, URLByStandardizingPath] + } + unsafe fn hasDirectoryPath(self) -> BOOL { + msg_send![self, hasDirectoryPath] + } + + unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + msg_send![class!(NSURL), bookmarkDataWithContentsOfURL:url error:error] + } + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + msg_send![self, bookmarkDataWithOptions:options includingResourceValuesForKeys:resource_value_for_keys relativeToURL:relative_to_url error:error] + } + // unsafe fn resourceValuesForKeys_fromBookmarkData_ + unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), writeBookmarkData:data toURL:to_url options:options error:error] + } + unsafe fn startAccessingSecurityScopedResource(self) -> BOOL { + msg_send![self, startAccessingSecurityScopedResource] + } + unsafe fn stopAccessingSecurityScopedResource(self) { + msg_send![self, stopAccessingSecurityScopedResource] + } + unsafe fn NSURLBookmarkFileCreationOptions(self) -> NSURLBookmarkFileCreationOptions { + msg_send![self, NSURLBookmarkFileCreationOptions] + } + unsafe fn NSURLBookmarkCreationOptions(self) -> NSURLBookmarkCreationOptions { + msg_send![self, NSURLBookmarkCreationOptions] + } + unsafe fn NSURLBookmarkResolutionOptions(self) -> NSURLBookmarkResolutionOptions { + msg_send![self, NSURLBookmarkResolutionOptions] + } + + // unsafe fn checkPromisedItemIsReachableAndReturnError_ + // unsafe fn getPromisedItemResourceValue_forKey_error_ + // unsafe fn promisedItemResourceValuesForKeys_error_ + + // unsafe fn URLFromPasteboard_ + // unsafe fn writeToPasteboard_ +} + +pub trait NSBundle: Sized { + unsafe fn mainBundle() -> Self; + + unsafe fn loadNibNamed_owner_topLevelObjects_(self, + name: id /* NSString */, + owner: id, + topLevelObjects: *mut id /* NSArray */) -> BOOL; +} + +impl NSBundle for id { + unsafe fn mainBundle() -> id { + msg_send![class!(NSBundle), mainBundle] + } + + unsafe fn loadNibNamed_owner_topLevelObjects_(self, + name: id /* NSString */, + owner: id, + topLevelObjects: *mut id /* NSArray* */) -> BOOL { + msg_send![self, loadNibNamed:name + owner:owner + topLevelObjects:topLevelObjects] + } +} + pub trait NSData: Sized { unsafe fn data(_: Self) -> id { msg_send![class!(NSData), data] diff --git a/third_party/cargo/vendor/cocoa-0.18.5/src/lib.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/lib.rs similarity index 97% rename from third_party/cargo/vendor/cocoa-0.18.5/src/lib.rs rename to third_party/cargo/vendor/cocoa-0.19.1/src/lib.rs index 179c0d3..4c5cce0 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/src/lib.rs +++ b/third_party/cargo/vendor/cocoa-0.19.1/src/lib.rs @@ -28,3 +28,5 @@ pub mod base; pub mod foundation; #[cfg(target_os = "macos")] pub mod quartzcore; +#[macro_use] +mod macros; diff --git a/third_party/cargo/vendor/cocoa-0.19.1/src/macros.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/macros.rs new file mode 100644 index 0000000..77c6a16 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.19.1/src/macros.rs @@ -0,0 +1,79 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Creates a Cocoa delegate to use e.g. with `NSWindow.setDelegate_`. +/// Adds instance variables and methods to the definition. +/// +/// # Example with NSWindowDelegate +/// ``` no_run +/// #[macro_use] extern crate cocoa; +/// #[macro_use] extern crate objc; +/// +/// use cocoa::appkit::NSWindow; +/// use cocoa::base::{id, nil}; +/// +/// use objc::runtime::{Object, Sel}; +/// +/// # fn main() { +/// unsafe { +/// let my_window: id = NSWindow::alloc(nil); +/// +/// extern fn on_enter_fullscreen(this: &Object, _cmd: Sel, _notification: id) { +/// unsafe { +/// let window: id = *this.get_ivar("window"); +/// window.setToolbar_(nil); +/// } +/// } +/// +/// my_window.setDelegate_(delegate!("MyWindowDelegate", { +/// window: id = my_window, // Declare instance variable(s) +/// (onWindowWillEnterFullscreen:) => on_enter_fullscreen as extern fn(&Object, Sel, id) // Declare function(s) +/// })); +/// } +/// # } +/// ``` +#[macro_export] +macro_rules! delegate { + ( + $name:expr, { + $( ($($sel:ident :)+) => $func:expr),* + } + ) => ( + delegate!($name, { + , + $( ($($sel :)+) => $func),* + }) + ); + + ( + $name:expr, { + $($var:ident : $var_type:ty = $value:expr),* , + $( ($($sel:ident :)+) => $func:expr),* + } + ) => ({ + let mut decl = objc::declare::ClassDecl::new($name, class!(NSObject)).unwrap(); + + $( + decl.add_ivar::<$var_type>(stringify!($var)); + )* + + $( + decl.add_method(sel!($($sel :)+), $func); + )* + + let cl = decl.register(); + let delegate: id = msg_send![cl, alloc]; + + $( + (*delegate).set_ivar(stringify!($var), $value); + )* + + delegate + }); +} diff --git a/third_party/cargo/vendor/cocoa-0.18.5/src/quartzcore.rs b/third_party/cargo/vendor/cocoa-0.19.1/src/quartzcore.rs similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/src/quartzcore.rs rename to third_party/cargo/vendor/cocoa-0.19.1/src/quartzcore.rs diff --git a/third_party/cargo/vendor/cocoa-0.18.5/tests/foundation.rs b/third_party/cargo/vendor/cocoa-0.19.1/tests/foundation.rs similarity index 85% rename from third_party/cargo/vendor/cocoa-0.18.5/tests/foundation.rs rename to third_party/cargo/vendor/cocoa-0.19.1/tests/foundation.rs index f1be870..c491501 100644 --- a/third_party/cargo/vendor/cocoa-0.18.5/tests/foundation.rs +++ b/third_party/cargo/vendor/cocoa-0.19.1/tests/foundation.rs @@ -19,8 +19,8 @@ mod foundation { let bytes = built.UTF8String() as *const u8; let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) .unwrap(); - assert!(objc_string.len() == expected.len()); - assert!(objc_string == expected); + assert_eq!(objc_string.len(), expected.len()); + assert_eq!(objc_string, expected); } } @@ -32,8 +32,8 @@ mod foundation { let bytes = built.UTF8String() as *const u8; let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) .unwrap(); - assert!(objc_string.len() == expected.len()); - assert!(objc_string == expected); + assert_eq!(objc_string.len(), expected.len()); + assert_eq!(objc_string, expected); } } @@ -42,7 +42,7 @@ mod foundation { let expected = "Hello!"; unsafe { let built = NSString::alloc(nil).init_str(expected); - assert!(built.len() == expected.len()); + assert_eq!(built.len(), expected.len()); } } @@ -58,7 +58,7 @@ mod foundation { let bytes = append_string.UTF8String() as *const u8; let objc_string = str::from_utf8(slice::from_raw_parts(bytes, append_string.len())) .unwrap(); - assert!(objc_string == expected); + assert_eq!(objc_string, expected); } } } @@ -148,14 +148,20 @@ mod foundation { // sorted iterators to ensure that each item is the same as its counterpart in // the vector. + fn compare_function(s0: &id, s1: &id) -> Ordering { + unsafe { + let (bytes0, len0) = (s0.UTF8String() as *const u8, s0.len()); + let (bytes1, len1) = (s1.UTF8String() as *const u8, s1.len()); + let (s0, s1) = (str::from_utf8(slice::from_raw_parts(bytes0, len0)).unwrap(), + str::from_utf8(slice::from_raw_parts(bytes1, len1)).unwrap()); + let (c0, c1) = (s0.chars().next().unwrap(), s1.chars().next().unwrap()); + c0.cmp(&c1) + } + } + // First test cocoa sorting... let mut comparator = ConcreteBlock::new(|s0: id, s1: id| { - let (bytes0, len0) = (s0.UTF8String() as *const u8, s0.len()); - let (bytes1, len1) = (s1.UTF8String() as *const u8, s1.len()); - let (s0, s1) = (str::from_utf8(slice::from_raw_parts(bytes0, len0)).unwrap(), - str::from_utf8(slice::from_raw_parts(bytes1, len1)).unwrap()); - let (c0, c1) = (s0.chars().next().unwrap(), s1.chars().next().unwrap()); - match c0.cmp(&c1) { + match compare_function(&s0, &s1) { Ordering::Less => NSComparisonResult::NSOrderedAscending, Ordering::Equal => NSComparisonResult::NSOrderedSame, Ordering::Greater => NSComparisonResult::NSOrderedDescending, @@ -173,13 +179,13 @@ mod foundation { // Then use rust sorting let mut keys_arr = dict.allKeys().iter().collect::>(); - keys_arr.sort(); + keys_arr.sort_by(compare_function); for (k0, k1) in keys_arr.into_iter().zip(keys.iter()) { assert!(k0.isEqualToString(k1)); } let mut objects_arr = dict.allValues().iter().collect::>(); - objects_arr.sort(); + objects_arr.sort_by(compare_function); for (v0, v1) in objects_arr.into_iter().zip(objects.iter()) { assert!(v0.isEqualToString(v1)); } diff --git a/third_party/cargo/vendor/cocoa-0.20.0/.cargo-checksum.json b/third_party/cargo/vendor/cocoa-0.20.0/.cargo-checksum.json new file mode 100644 index 0000000..61b70cf --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.lock":"0effdfa775e787f93cfabf50aa7039d7a4999e0dd92d57d3d5745a5f5926a962","Cargo.toml":"280ff6f510cff8a892ddbba326304fd8b16ac2eb1ad111948405abe3a6a90d51","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"29542cb34adb016506822ef78bceacf1774dbe8c27818a4d47b7d7b71ed4e1ac","examples/color.rs":"5211a85ab9ec4cbb98f8f677de50bb2f1d300400f50226ebfd714d40b9d32485","examples/fullscreen.rs":"f8719268b6eb1d19078af347e02f9993c9d29633ef2d38dcc4fac26cbd731c2d","examples/hello_world.rs":"7efe2a29de4d4dfc1d8821f469e13b1456f72de478bab55f813d08d4e5aafd5c","examples/tab_view.rs":"e6a3187eeac2f46210994293c2db7756757f4cad07e519902fa994c6d5c1a7d6","src/appkit.rs":"a21c6d612d0ec45dbbb5df45fe96d84b76c5a9982d09bdf74714ce63723da558","src/base.rs":"6c56d1758a9b0a7f8927771fe8b0bb43c6f19e4531bf9accecc786028eaad845","src/foundation.rs":"f0a8c0d2e3aee6bde64f480085025dfa92f903a39d6c15251ba392523aa153a3","src/lib.rs":"ed6164b3e0fe68579218185267d79229a2989c86efce690d7273f779c5239ec3","src/macros.rs":"0de0a8ea9a23f03cad94266a92051c3be8ff3f8f7d7d60f95dafe6c663204d48","src/quartzcore.rs":"cb4f96b4b095e9d623346a42b1e119a5299bf2af73ed81256dd548c688d525e2","tests/foundation.rs":"728eb7dcc9edbfb43dcb6aa1ebcc391658a7d47846d94a71905bcedfce833260"},"package":"0a4736c86d51bd878b474400d9ec888156f4037015f5d09794fab9f26eab1ad4"} \ No newline at end of file diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/BUILD b/third_party/cargo/vendor/cocoa-0.20.0/BUILD similarity index 51% rename from third_party/cargo/vendor/objc-foundation-0.1.1/BUILD rename to third_party/cargo/vendor/cocoa-0.20.0/BUILD index d2ba058..b1ba891 100644 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/BUILD +++ b/third_party/cargo/vendor/cocoa-0.20.0/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "MIT" + "notice", # "MIT,Apache-2.0" ]) load( @@ -23,25 +23,32 @@ load( ) -# Unsupported target "custom_class" with type "example" omitted -# Unsupported target "example" with type "example" omitted rust_library( - name = "objc_foundation", + name = "cocoa", crate_root = "src/lib.rs", - crate_type = "lib", + crate_type = "rlib", edition = "2015", srcs = glob(["**/*.rs"]), deps = [ + "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", "//third_party/cargo/vendor/block-0.1.6:block", + "//third_party/cargo/vendor/core-foundation-0.7.0:core_foundation", + "//third_party/cargo/vendor/core-graphics-0.19.0:core_graphics", + "//third_party/cargo/vendor/foreign-types-0.3.2:foreign_types", + "//third_party/cargo/vendor/libc-0.2.67:libc", "//third_party/cargo/vendor/objc-0.2.7:objc", - "//third_party/cargo/vendor/objc_id-0.1.1:objc_id", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.1.1", + version = "0.20.0", crate_features = [ ], ) +# Unsupported target "color" with type "example" omitted +# Unsupported target "foundation" with type "test" omitted +# Unsupported target "fullscreen" with type "example" omitted +# Unsupported target "hello_world" with type "example" omitted +# Unsupported target "tab_view" with type "example" omitted diff --git a/third_party/cargo/vendor/cocoa-0.20.0/COPYRIGHT b/third_party/cargo/vendor/cocoa-0.20.0/COPYRIGHT new file mode 100644 index 0000000..8b7291a --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/COPYRIGHT @@ -0,0 +1,5 @@ +Licensed under the Apache License, Version 2.0 or the MIT license +, at your +option. All files in the project carrying such notice may not be +copied, modified, or distributed except according to those terms. diff --git a/third_party/cargo/vendor/cocoa-0.20.0/Cargo.lock b/third_party/cargo/vendor/cocoa-0.20.0/Cargo.lock new file mode 100644 index 0000000..33c9e21 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/Cargo.lock @@ -0,0 +1,95 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cocoa" +version = "0.20.0" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation-sys 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation-sys" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "core-graphics" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.65" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +"checksum core-foundation 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" +"checksum core-foundation-sys 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac" +"checksum core-graphics 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)" = "59e78b2e0aaf43f08e7ae0d6bc96895ef72ff0921c7d4ff4762201b2dba376dd" +"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +"checksum libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)" = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8" +"checksum malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +"checksum objc 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/Cargo.toml b/third_party/cargo/vendor/cocoa-0.20.0/Cargo.toml similarity index 50% rename from third_party/cargo/vendor/num_cpus-1.12.0/Cargo.toml rename to third_party/cargo/vendor/cocoa-0.20.0/Cargo.toml index 949e0fe..994c2ca 100644 --- a/third_party/cargo/vendor/num_cpus-1.12.0/Cargo.toml +++ b/third_party/cargo/vendor/cocoa-0.20.0/Cargo.toml @@ -11,19 +11,34 @@ # will likely look very different (and much more reasonable) [package] -name = "num_cpus" -version = "1.12.0" -authors = ["Sean McArthur "] -description = "Get the number of CPUs on a machine." -documentation = "https://docs.rs/num_cpus" -readme = "README.md" -keywords = ["cpu", "cpus", "cores"] -categories = ["hardware-support"] -license = "MIT/Apache-2.0" -repository = "https://github.com/seanmonstar/num_cpus" -[dependencies.libc] -version = "0.2.26" -[dev-dependencies.doc-comment] +name = "cocoa" +version = "0.20.0" +authors = ["The Servo Project Developers"] +description = "Bindings to Cocoa for macOS" +homepage = "https://github.com/servo/core-foundation-rs" +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" + +[lib] +name = "cocoa" +crate-type = ["rlib"] +[dependencies.bitflags] +version = "1.0" + +[dependencies.block] +version = "0.1" + +[dependencies.core-foundation] +version = "0.7" + +[dependencies.core-graphics] +version = "0.19" + +[dependencies.foreign-types] version = "0.3" -[target."cfg(all(any(target_arch = \"x86_64\", target_arch = \"aarch64\"), target_os = \"hermit\"))".dependencies.hermit-abi] -version = "0.1.3" + +[dependencies.libc] +version = "0.2" + +[dependencies.objc] +version = "0.2.3" diff --git a/third_party/cargo/vendor/backtrace-0.3.45/LICENSE-APACHE b/third_party/cargo/vendor/cocoa-0.20.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/backtrace-0.3.45/LICENSE-APACHE rename to third_party/cargo/vendor/cocoa-0.20.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-MIT b/third_party/cargo/vendor/cocoa-0.20.0/LICENSE-MIT similarity index 95% rename from third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-MIT rename to third_party/cargo/vendor/cocoa-0.20.0/LICENSE-MIT index fb7494a..807526f 100644 --- a/third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-MIT +++ b/third_party/cargo/vendor/cocoa-0.20.0/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2016 Steve Klabnik +Copyright (c) 2012-2013 Mozilla Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/cocoa-0.20.0/README.md b/third_party/cargo/vendor/cocoa-0.20.0/README.md new file mode 100644 index 0000000..d1818d1 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/README.md @@ -0,0 +1,6 @@ +Cocoa-rs +-------- + +This crate provides Rust bindings to Cocoa for macOS. It's dual-licensed MIT / +Apache 2.0. If you'd like to help improve cocoa-rs, check out [the Servo +contributing guide](https://github.com/servo/servo/blob/master/CONTRIBUTING.md)! diff --git a/third_party/cargo/vendor/cocoa-0.20.0/examples/color.rs b/third_party/cargo/vendor/cocoa-0.20.0/examples/color.rs new file mode 100644 index 0000000..af31514 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/examples/color.rs @@ -0,0 +1,120 @@ +extern crate cocoa; + +use cocoa::base::{selector, id, nil, NO}; + +use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, + NSString}; +use cocoa::appkit::{NSApp, NSColor, NSColorSpace, NSApplication, NSApplicationActivationPolicyRegular, + NSMenu, NSMenuItem, NSWindowStyleMask, NSBackingStoreType, NSWindow, + NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; + + +fn main() { + unsafe { + // Create the app. + let app = create_app(); + + // Create some colors + let clear = NSColor::clearColor(nil); + let black = NSColor::colorWithRed_green_blue_alpha_(nil, 0.0, 0.0, 0.0, 1.0); + let srgb_red = NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 1.0, 0.0, 0.0, 1.0); + let device_green = NSColor::colorWithDeviceRed_green_blue_alpha_(nil, 0.0, 1.0, 0.0, 1.0); + let display_p3_blue = NSColor::colorWithDisplayP3Red_green_blue_alpha_(nil, 0.0, 0.0, 1.0, 1.0); + let calibrated_cyan = NSColor::colorWithCalibratedRed_green_blue_alpha_(nil, 0.0, 1.0, 1.0, 1.0); + + // Create windows with different color types. + let _win_clear = create_window(NSString::alloc(nil).init_str("clear"), clear); + let _win_black = create_window(NSString::alloc(nil).init_str("black"), black); + let _win_srgb_red = create_window(NSString::alloc(nil).init_str("srgb_red"), srgb_red); + let _win_device_green = create_window(NSString::alloc(nil).init_str("device_green"), device_green); + let _win_display_p3_blue = create_window(NSString::alloc(nil).init_str("display_p3_blue"), display_p3_blue); + let _win_calibrated_cyan = create_window(NSString::alloc(nil).init_str("calibrated_cyan"), calibrated_cyan); + + // Extract component values from a color. + // NOTE: some components will raise an exception if the color is not + // in the correct NSColorSpace. Refer to Apple's documentation for details. + // https://developer.apple.com/documentation/appkit/nscolor?language=objc + let my_color = NSColor::colorWithRed_green_blue_alpha_(nil, 0.25, 0.75, 0.5, 0.25); + println!("alphaComponent: {:?}", my_color.alphaComponent()); + println!("redComponent: {:?}", my_color.redComponent()); + println!("greenComponent: {:?}", my_color.greenComponent()); + println!("blueComponent: {:?}", my_color.blueComponent()); + println!("hueComponent: {:?}", my_color.hueComponent()); + println!("saturationComponent: {:?}", my_color.saturationComponent()); + println!("brightnessComponent: {:?}", my_color.brightnessComponent()); + + // Changing color spaces. + let my_color_cmyk_cs = my_color.colorUsingColorSpace_(NSColorSpace::deviceCMYKColorSpace(nil)); + println!("blackComponent: {:?}", my_color_cmyk_cs.blackComponent()); + println!("cyanComponent: {:?}", my_color_cmyk_cs.cyanComponent()); + println!("magentaComponent: {:?}", my_color_cmyk_cs.magentaComponent()); + println!("yellowComponent: {:?}", my_color_cmyk_cs.yellowComponent()); + + // Getting NSColorSpace name. + let cs = NSColorSpace::genericGamma22GrayColorSpace(nil); + let cs_name = cs.localizedName(); + let cs_name_bytes = cs_name.UTF8String() as *const u8; + let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + println!("NSColorSpace: {:?}", cs_name_string); + + // Creating an NSColorSpace from CGColorSpaceRef. + let cg_cs = cs.CGColorSpace(); + let cs = NSColorSpace::alloc(nil).initWithCGColorSpace_(cg_cs); + let cs_name = cs.localizedName(); + let cs_name_bytes = cs_name.UTF8String() as *const u8; + let cs_name_string = std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap(); + println!("initWithCGColorSpace_: {:?}", cs_name_string); + + app.run(); + } +} + +unsafe fn create_window(title: id, color: id) -> id { + let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask | + NSWindowStyleMask::NSClosableWindowMask | + NSWindowStyleMask::NSResizableWindowMask | + NSWindowStyleMask::NSMiniaturizableWindowMask | + NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, + NSBackingStoreType::NSBackingStoreBuffered, + NO + ).autorelease(); + + window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); + window.setTitle_(title); + window.setBackgroundColor_(color); + window.makeKeyAndOrderFront_(nil); + window +} + +unsafe fn create_app() -> id { + let _pool = NSAutoreleasePool::new(nil); + + let app = NSApp(); + app.setActivationPolicy_(NSApplicationActivationPolicyRegular); + + // create Menu Bar + let menubar = NSMenu::new(nil).autorelease(); + let app_menu_item = NSMenuItem::new(nil).autorelease(); + menubar.addItem_(app_menu_item); + app.setMainMenu_(menubar); + + // create Application menu + let app_menu = NSMenu::new(nil).autorelease(); + let quit_prefix = NSString::alloc(nil).init_str("Quit "); + let quit_title = + quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); + let quit_action = selector("terminate:"); + let quit_key = NSString::alloc(nil).init_str("q"); + let quit_item = NSMenuItem::alloc(nil) + .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) + .autorelease(); + app_menu.addItem_(quit_item); + app_menu_item.setSubmenu_(app_menu); + + let current_app = NSRunningApplication::currentApplication(nil); + current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); + + return app; +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/examples/fullscreen.rs b/third_party/cargo/vendor/cocoa-0.20.0/examples/fullscreen.rs new file mode 100644 index 0000000..c826a29 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/examples/fullscreen.rs @@ -0,0 +1,97 @@ +extern crate cocoa; +extern crate core_graphics; + +#[macro_use] +extern crate objc; + +use cocoa::base::{selector, nil, NO, id}; +use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, + NSString, NSUInteger}; +use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, + NSBackingStoreBuffered, NSMenu, NSMenuItem, NSWindowStyleMask, + NSRunningApplication, NSApplicationActivateIgnoringOtherApps, + NSWindowCollectionBehavior, NSApplicationPresentationOptions}; + +use core_graphics::display::CGDisplay; + +use objc::runtime::{Object, Sel}; +use objc::declare::ClassDecl; + +fn main() { + unsafe { + let _pool = NSAutoreleasePool::new(nil); + + let app = NSApp(); + app.setActivationPolicy_(NSApplicationActivationPolicyRegular); + + // create Menu Bar + let menubar = NSMenu::new(nil).autorelease(); + let app_menu_item = NSMenuItem::new(nil).autorelease(); + menubar.addItem_(app_menu_item); + app.setMainMenu_(menubar); + + // create Application menu + let app_menu = NSMenu::new(nil).autorelease(); + let quit_prefix = NSString::alloc(nil).init_str("Quit "); + let quit_title = + quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); + let quit_action = selector("terminate:"); + let quit_key = NSString::alloc(nil).init_str("q"); + let quit_item = NSMenuItem::alloc(nil) + .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) + .autorelease(); + app_menu.addItem_(quit_item); + app_menu_item.setSubmenu_(app_menu); + + // Create NSWindowDelegate + let superclass = class!(NSObject); + let mut decl = ClassDecl::new("MyWindowDelegate", superclass).unwrap(); + + extern fn will_use_fillscreen_presentation_options(_: &Object, _: Sel, _: id, _: NSUInteger) -> NSUInteger { + // Set initial presentation options for fullscreen + let options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen + | NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar + | NSApplicationPresentationOptions::NSApplicationPresentationDisableProcessSwitching; + options.bits() + } + + extern fn window_entering_fullscreen(_: &Object, _: Sel, _: id) { + // Reset HideDock and HideMenuBar settings during/after we entered fullscreen. + let options = NSApplicationPresentationOptions::NSApplicationPresentationHideDock | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; + unsafe { + NSApp().setPresentationOptions_(options); + } + } + + decl.add_method(sel!(window:willUseFullScreenPresentationOptions:), + will_use_fillscreen_presentation_options as extern fn(&Object, Sel, id, NSUInteger) -> NSUInteger); + decl.add_method(sel!(windowWillEnterFullScreen:), + window_entering_fullscreen as extern fn(&Object, Sel, id)); + decl.add_method(sel!(windowDidEnterFullScreen:), + window_entering_fullscreen as extern fn(&Object, Sel, id)); + + let delegate_class = decl.register(); + let delegate_object = msg_send![delegate_class, new]; + + // create Window + let display = CGDisplay::main(); + let size = NSSize::new(display.pixels_wide() as _, display.pixels_high() as _); + let window = NSWindow::alloc(nil) + .initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), size), + NSWindowStyleMask::NSTitledWindowMask, + NSBackingStoreBuffered, + NO) + .autorelease(); + window.setDelegate_(delegate_object); + let title = NSString::alloc(nil).init_str("Fullscreen!"); + window.setTitle_(title); + window.makeKeyAndOrderFront_(nil); + + let current_app = NSRunningApplication::currentApplication(nil); + current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); + window.setCollectionBehavior_(NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenPrimary); + window.toggleFullScreen_(nil); + app.run(); + } +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/examples/hello_world.rs b/third_party/cargo/vendor/cocoa-0.20.0/examples/hello_world.rs new file mode 100644 index 0000000..4d5c1b0 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/examples/hello_world.rs @@ -0,0 +1,53 @@ +extern crate cocoa; + +use cocoa::base::{selector, nil, NO}; +use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, + NSString}; +use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, + NSBackingStoreBuffered, NSMenu, NSMenuItem, NSWindowStyleMask, + NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; + +fn main() { + unsafe { + let _pool = NSAutoreleasePool::new(nil); + + let app = NSApp(); + app.setActivationPolicy_(NSApplicationActivationPolicyRegular); + + // create Menu Bar + let menubar = NSMenu::new(nil).autorelease(); + let app_menu_item = NSMenuItem::new(nil).autorelease(); + menubar.addItem_(app_menu_item); + app.setMainMenu_(menubar); + + // create Application menu + let app_menu = NSMenu::new(nil).autorelease(); + let quit_prefix = NSString::alloc(nil).init_str("Quit "); + let quit_title = + quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); + let quit_action = selector("terminate:"); + let quit_key = NSString::alloc(nil).init_str("q"); + let quit_item = NSMenuItem::alloc(nil) + .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) + .autorelease(); + app_menu.addItem_(quit_item); + app_menu_item.setSubmenu_(app_menu); + + // create Window + let window = NSWindow::alloc(nil) + .initWithContentRect_styleMask_backing_defer_(NSRect::new(NSPoint::new(0., 0.), + NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask, + NSBackingStoreBuffered, + NO) + .autorelease(); + window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); + window.center(); + let title = NSString::alloc(nil).init_str("Hello World!"); + window.setTitle_(title); + window.makeKeyAndOrderFront_(nil); + let current_app = NSRunningApplication::currentApplication(nil); + current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); + app.run(); + } +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/examples/tab_view.rs b/third_party/cargo/vendor/cocoa-0.20.0/examples/tab_view.rs new file mode 100644 index 0000000..985487f --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/examples/tab_view.rs @@ -0,0 +1,87 @@ +extern crate cocoa; + +use cocoa::base::{selector, id, nil, NO}; + + +use cocoa::foundation::{NSRect, NSPoint, NSSize, NSAutoreleasePool, NSProcessInfo, + NSString}; +use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular, NSWindow, + NSMenu, NSMenuItem, NSTabView, NSWindowStyleMask, NSBackingStoreType, + NSTabViewItem, NSRunningApplication, NSApplicationActivateIgnoringOtherApps}; + + +fn main() { + unsafe { + + // create a tab View + let tab_view = NSTabView::new(nil) + .initWithFrame_(NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.))); + + // create a tab view item + let tab_view_item = NSTabViewItem::new(nil) + .initWithIdentifier_(NSString::alloc(nil).init_str("TabView1")); + + tab_view_item.setLabel_(NSString::alloc(nil).init_str("Tab view item 1")); + tab_view.addTabViewItem_(tab_view_item); + + // create a second tab view item + let tab_view_item2 = NSTabViewItem::new(nil) + .initWithIdentifier_(NSString::alloc(nil).init_str("TabView2")); + + tab_view_item2.setLabel_(NSString::alloc(nil).init_str("Tab view item 2")); + tab_view.addTabViewItem_(tab_view_item2); + + // Create the app and set the content. + let app = create_app(NSString::alloc(nil).init_str("Tab View"), tab_view); + app.run(); + } +} + +unsafe fn create_app(title: id, content: id) -> id { + let _pool = NSAutoreleasePool::new(nil); + + let app = NSApp(); + app.setActivationPolicy_(NSApplicationActivationPolicyRegular); + + // create Menu Bar + let menubar = NSMenu::new(nil).autorelease(); + let app_menu_item = NSMenuItem::new(nil).autorelease(); + menubar.addItem_(app_menu_item); + app.setMainMenu_(menubar); + + // create Application menu + let app_menu = NSMenu::new(nil).autorelease(); + let quit_prefix = NSString::alloc(nil).init_str("Quit "); + let quit_title = + quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName()); + let quit_action = selector("terminate:"); + let quit_key = NSString::alloc(nil).init_str("q"); + let quit_item = NSMenuItem::alloc(nil) + .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key) + .autorelease(); + app_menu.addItem_(quit_item); + app_menu_item.setSubmenu_(app_menu); + + // create Window + let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( + NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)), + NSWindowStyleMask::NSTitledWindowMask | + NSWindowStyleMask::NSClosableWindowMask | + NSWindowStyleMask::NSResizableWindowMask | + NSWindowStyleMask::NSMiniaturizableWindowMask | + NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask, + NSBackingStoreType::NSBackingStoreBuffered, + NO + ).autorelease(); + window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.)); + window.center(); + + window.setTitle_(title); + window.makeKeyAndOrderFront_(nil); + + window.setContentView_(content); + let current_app = NSRunningApplication::currentApplication(nil); + current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); + + return app; +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/appkit.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/appkit.rs new file mode 100644 index 0000000..53afce4 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/appkit.rs @@ -0,0 +1,4186 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +use base::{id, BOOL, SEL}; +use block::Block; +use foundation::{NSInteger, NSUInteger, NSTimeInterval, + NSPoint, NSSize, NSRect, NSRange, NSRectEdge}; +use libc; + +pub use core_graphics::base::CGFloat; +pub use core_graphics::geometry::CGPoint; + +pub use self::NSApplicationActivationPolicy::*; +pub use self::NSApplicationActivationOptions::*; +pub use self::NSBackingStoreType::*; +pub use self::NSOpenGLPixelFormatAttribute::*; +pub use self::NSOpenGLPFAOpenGLProfiles::*; +pub use self::NSEventType::*; +use std::os::raw::c_void; + +pub type CGLContextObj = *mut c_void; + +pub type GLint = i32; + +#[link(name = "AppKit", kind = "framework")] +extern { + pub static NSAppKitVersionNumber: f64; + + // Types for Standard Data - OS X v10.6 and later. (NSString *const) + pub static NSPasteboardTypeString: id; + pub static NSPasteboardTypePDF: id; + pub static NSPasteboardTypeTIFF: id; + pub static NSPasteboardTypePNG: id; + pub static NSPasteboardTypeRTF: id; + pub static NSPasteboardTypeRTFD: id; + pub static NSPasteboardTypeHTML: id; + pub static NSPasteboardTypeTabularText: id; + pub static NSPasteboardTypeFont: id; + pub static NSPasteboardTypeRuler: id; + pub static NSPasteboardTypeColor: id; + pub static NSPasteboardTypeSound: id; + pub static NSPasteboardTypeMultipleTextSelection: id; + pub static NSPasteboardTypeFindPanelSearchOptions: id; + + // Types for Standard Data - OS X v10.5 and earlier. (NSString *) + pub static NSStringPboardType: id; + pub static NSFilenamesPboardType: id; + pub static NSPostScriptPboardType: id; + pub static NSTIFFPboardType: id; + pub static NSRTFPboardType: id; + pub static NSTabularTextPboardType: id; + pub static NSFontPboardType: id; + pub static NSRulerPboardType: id; + pub static NSFileContentsPboardType: id; + pub static NSColorPboardType: id; + pub static NSRTFDPboardType: id; + pub static NSHTMLPboardType: id; + pub static NSPICTPboardType: id; + pub static NSURLPboardType: id; + pub static NSPDFPboardType: id; + pub static NSVCardPboardType: id; + pub static NSFilesPromisePboardType: id; + pub static NSMultipleTextSelectionPboardType: id; + pub static NSSoundPboardType: id; + + // Names of provided pasteboards. (NSString *) + pub static NSGeneralPboard: id; + pub static NSFontPboard: id; + pub static NSRulerPboard: id; + pub static NSFindPboard: id; + pub static NSDragPboard: id; + + // Pasteboard reading options - OS X v10.6 and later. (NSString *) + pub static NSPasteboardURLReadingFileURLsOnlyKey: id; + pub static NSPasteboardURLReadingContentsConformToTypesKey: id; + + // NSAppearance names. (NSString *) + pub static NSAppearanceNameVibrantDark: id; + pub static NSAppearanceNameVibrantLight: id; + + // Fullscreen mode options - OS X v10.5 and later. (NSString *) + pub static NSFullScreenModeAllScreens: id; + pub static NSFullScreenModeSetting: id; + pub static NSFullScreenModeWindowLevel: id; + pub static NSFullScreenModeApplicationPresentationOptions: id; +} + +pub const NSAppKitVersionNumber10_0: f64 = 577.0; +pub const NSAppKitVersionNumber10_1: f64 = 620.0; +pub const NSAppKitVersionNumber10_2: f64 = 663.0; +pub const NSAppKitVersionNumber10_2_3: f64 = 663.6; +pub const NSAppKitVersionNumber10_3: f64 = 743.0; +pub const NSAppKitVersionNumber10_3_2: f64 = 743.14; +pub const NSAppKitVersionNumber10_3_3: f64 = 743.2; +pub const NSAppKitVersionNumber10_3_5: f64 = 743.24; +pub const NSAppKitVersionNumber10_3_7: f64 = 743.33; +pub const NSAppKitVersionNumber10_3_9: f64 = 743.36; +pub const NSAppKitVersionNumber10_4: f64 = 824.0; +pub const NSAppKitVersionNumber10_4_1: f64 = 824.1; +pub const NSAppKitVersionNumber10_4_3: f64 = 824.23; +pub const NSAppKitVersionNumber10_4_4: f64 = 824.33; +pub const NSAppKitVersionNumber10_4_7: f64 = 824.41; +pub const NSAppKitVersionNumber10_5: f64 = 949.0; +pub const NSAppKitVersionNumber10_5_2: f64 = 949.27; +pub const NSAppKitVersionNumber10_5_3: f64 = 949.33; +pub const NSAppKitVersionNumber10_6: f64 = 1038.0; +pub const NSAppKitVersionNumber10_7: f64 = 1138.0; +pub const NSAppKitVersionNumber10_7_2: f64 = 1138.23; +pub const NSAppKitVersionNumber10_7_3: f64 = 1138.32; +pub const NSAppKitVersionNumber10_7_4: f64 = 1138.47; +pub const NSAppKitVersionNumber10_8: f64 = 1187.0; +pub const NSAppKitVersionNumber10_9: f64 = 1265.0; +pub const NSAppKitVersionNumber10_10: f64 = 1343.0; +pub const NSAppKitVersionNumber10_10_2: f64 = 1344.0; +pub const NSAppKitVersionNumber10_10_3: f64 = 1347.0; +pub const NSAppKitVersionNumber10_10_4: f64 = 1348.0; +pub const NSAppKitVersionNumber10_10_5: f64 = 1348.0; +pub const NSAppKitVersionNumber10_10_Max: f64 = 1349.0; +pub const NSAppKitVersionNumber10_11: f64 = 1404.0; +pub const NSAppKitVersionNumber10_11_1: f64 = 1404.13; +pub const NSAppKitVersionNumber10_11_2: f64 = 1404.34; +pub const NSAppKitVersionNumber10_11_3: f64 = 1404.34; +pub const NSAppKitVersionNumber10_12: f64 = 1504.0; +pub const NSAppKitVersionNumber10_12_1: f64 = 1504.60; +pub const NSAppKitVersionNumber10_12_2: f64 = 1504.76; +pub const NSAppKitVersionNumber10_13: f64 = 1561.0; +pub const NSAppKitVersionNumber10_13_1: f64 = 1561.1; +pub const NSAppKitVersionNumber10_13_2: f64 = 1561.2; +pub const NSAppKitVersionNumber10_13_4: f64 = 1561.4; + +pub unsafe fn NSApp() -> id { + msg_send![class!(NSApplication), sharedApplication] +} + +#[repr(i64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSApplicationActivationPolicy { + NSApplicationActivationPolicyRegular = 0, + NSApplicationActivationPolicyAccessory = 1, + NSApplicationActivationPolicyProhibited = 2, + NSApplicationActivationPolicyERROR = -1 +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSApplicationActivationOptions { + NSApplicationActivateAllWindows = 1 << 0, + NSApplicationActivateIgnoringOtherApps = 1 << 1 +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSApplicationTerminateReply { + NSTerminateCancel = 0, + NSTerminateNow = 1, + NSTerminateLater = 2, +} + +bitflags! { + pub struct NSApplicationPresentationOptions : NSUInteger { + const NSApplicationPresentationDefault = 0; + const NSApplicationPresentationAutoHideDock = 1 << 0; + const NSApplicationPresentationHideDock = 1 << 1; + const NSApplicationPresentationAutoHideMenuBar = 1 << 2; + const NSApplicationPresentationHideMenuBar = 1 << 3; + const NSApplicationPresentationDisableAppleMenu = 1 << 4; + const NSApplicationPresentationDisableProcessSwitching = 1 << 5; + const NSApplicationPresentationDisableForceQuit = 1 << 6; + const NSApplicationPresentationDisableSessionTermination = 1 << 7; + const NSApplicationPresentationDisableHideApplication = 1 << 8; + const NSApplicationPresentationDisableMenuBarTransparency = 1 << 9; + const NSApplicationPresentationFullScreen = 1 << 10; + const NSApplicationPresentationAutoHideToolbar = 1 << 11; + } +} + +bitflags! { + pub struct NSWindowStyleMask: NSUInteger { + const NSBorderlessWindowMask = 0; + const NSTitledWindowMask = 1 << 0; + const NSClosableWindowMask = 1 << 1; + const NSMiniaturizableWindowMask = 1 << 2; + const NSResizableWindowMask = 1 << 3; + + const NSTexturedBackgroundWindowMask = 1 << 8; + + const NSUnifiedTitleAndToolbarWindowMask = 1 << 12; + + const NSFullScreenWindowMask = 1 << 14; + + const NSFullSizeContentViewWindowMask = 1 << 15; + } +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSWindowTitleVisibility { + NSWindowTitleVisible = 0, + NSWindowTitleHidden = 1 +} + +#[repr(i64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSWindowTabbingMode { + NSWindowTabbingModeAutomatic = 0, + NSWindowTabbingModeDisallowed = 1, + NSWindowTabbingModePreferred = 2 +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSBackingStoreType { + NSBackingStoreRetained = 0, + NSBackingStoreNonretained = 1, + NSBackingStoreBuffered = 2 +} + +bitflags! { + pub struct NSWindowOrderingMode: NSInteger { + const NSWindowAbove = 1; + const NSWindowBelow = -1; + const NSWindowOut = 0; + } +} + +bitflags! { + pub struct NSAlignmentOptions: libc::c_ulonglong { + const NSAlignMinXInward = 1 << 0; + const NSAlignMinYInward = 1 << 1; + const NSAlignMaxXInward = 1 << 2; + const NSAlignMaxYInward = 1 << 3; + const NSAlignWidthInward = 1 << 4; + const NSAlignHeightInward = 1 << 5; + const NSAlignMinXOutward = 1 << 8; + const NSAlignMinYOutward = 1 << 9; + const NSAlignMaxXOutward = 1 << 10; + const NSAlignMaxYOutward = 1 << 11; + const NSAlignWidthOutward = 1 << 12; + const NSAlignHeightOutward = 1 << 13; + const NSAlignMinXNearest = 1 << 16; + const NSAlignMinYNearest = 1 << 17; + const NSAlignMaxXNearest = 1 << 18; + const NSAlignMaxYNearest = 1 << 19; + const NSAlignWidthNearest = 1 << 20; + const NSAlignHeightNearest = 1 << 21; + const NSAlignRectFlipped = 1 << 63; + const NSAlignAllEdgesInward = NSAlignmentOptions::NSAlignMinXInward.bits + | NSAlignmentOptions::NSAlignMaxXInward.bits + | NSAlignmentOptions::NSAlignMinYInward.bits + | NSAlignmentOptions::NSAlignMaxYInward.bits; + const NSAlignAllEdgesOutward = NSAlignmentOptions::NSAlignMinXOutward.bits + | NSAlignmentOptions::NSAlignMaxXOutward.bits + | NSAlignmentOptions::NSAlignMinYOutward.bits + | NSAlignmentOptions::NSAlignMaxYOutward.bits; + const NSAlignAllEdgesNearest = NSAlignmentOptions::NSAlignMinXNearest.bits + | NSAlignmentOptions::NSAlignMaxXNearest.bits + | NSAlignmentOptions::NSAlignMinYNearest.bits + | NSAlignmentOptions::NSAlignMaxYNearest.bits; + } +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSOpenGLPixelFormatAttribute { + NSOpenGLPFAAllRenderers = 1, + NSOpenGLPFATripleBuffer = 3, + NSOpenGLPFADoubleBuffer = 5, + NSOpenGLPFAStereo = 6, + NSOpenGLPFAAuxBuffers = 7, + NSOpenGLPFAColorSize = 8, + NSOpenGLPFAAlphaSize = 11, + NSOpenGLPFADepthSize = 12, + NSOpenGLPFAStencilSize = 13, + NSOpenGLPFAAccumSize = 14, + NSOpenGLPFAMinimumPolicy = 51, + NSOpenGLPFAMaximumPolicy = 52, + NSOpenGLPFAOffScreen = 53, + NSOpenGLPFAFullScreen = 54, + NSOpenGLPFASampleBuffers = 55, + NSOpenGLPFASamples = 56, + NSOpenGLPFAAuxDepthStencil = 57, + NSOpenGLPFAColorFloat = 58, + NSOpenGLPFAMultisample = 59, + NSOpenGLPFASupersample = 60, + NSOpenGLPFASampleAlpha = 61, + NSOpenGLPFARendererID = 70, + NSOpenGLPFASingleRenderer = 71, + NSOpenGLPFANoRecovery = 72, + NSOpenGLPFAAccelerated = 73, + NSOpenGLPFAClosestPolicy = 74, + NSOpenGLPFARobust = 75, + NSOpenGLPFABackingStore = 76, + NSOpenGLPFAMPSafe = 78, + NSOpenGLPFAWindow = 80, + NSOpenGLPFAMultiScreen = 81, + NSOpenGLPFACompliant = 83, + NSOpenGLPFAScreenMask = 84, + NSOpenGLPFAPixelBuffer = 90, + NSOpenGLPFARemotePixelBuffer = 91, + NSOpenGLPFAAllowOfflineRenderers = 96, + NSOpenGLPFAAcceleratedCompute = 97, + NSOpenGLPFAOpenGLProfile = 99, + NSOpenGLPFAVirtualScreenCount = 128, +} + +#[repr(u64)] +#[allow(non_camel_case_types)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSOpenGLPFAOpenGLProfiles { + NSOpenGLProfileVersionLegacy = 0x1000, + NSOpenGLProfileVersion3_2Core = 0x3200, + NSOpenGLProfileVersion4_1Core = 0x4100, +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSOpenGLContextParameter { + NSOpenGLCPSwapInterval = 222, + NSOpenGLCPSurfaceOrder = 235, + NSOpenGLCPSurfaceOpacity = 236, + NSOpenGLCPSurfaceBackingSize = 304, + NSOpenGLCPReclaimResources = 308, + NSOpenGLCPCurrentRendererID = 309, + NSOpenGLCPGPUVertexProcessing = 310, + NSOpenGLCPGPUFragmentProcessing = 311, + NSOpenGLCPHasDrawable = 314, + NSOpenGLCPMPSwapsInFlight = 315, +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSWindowButton { + NSWindowCloseButton = 0, + NSWindowMiniaturizeButton = 1, + NSWindowZoomButton = 2, + NSWindowToolbarButton = 3, + NSWindowDocumentIconButton = 4, + NSWindowDocumentVersionsButton = 6, + NSWindowFullScreenButton = 7, +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSBezelStyle { + NSRoundedBezelStyle = 1, + NSRegularSquareBezelStyle = 2, + NSDisclosureBezelStyle = 5, + NSShadowlessSquareBezelStyle = 6, + NSCircularBezelStyle = 7, + NSTexturedSquareBezelStyle = 8, + NSHelpButtonBezelStyle = 9, + NSSmallSquareBezelStyle = 10, + NSTexturedRoundedBezelStyle = 11, + NSRoundRectBezelStyle = 12, + NSRecessedBezelStyle = 13, + NSRoundedDisclosureBezelStyle = 14, +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSRequestUserAttentionType { + NSCriticalRequest = 0, + NSInformationalRequest = 10, +} + +pub static NSMainMenuWindowLevel: i32 = 24; + +pub trait NSApplication: Sized { + unsafe fn sharedApplication(_: Self) -> id { + msg_send![class!(NSApplication), sharedApplication] + } + + unsafe fn mainMenu(self) -> id; + unsafe fn setActivationPolicy_(self, policy: NSApplicationActivationPolicy) -> BOOL; + unsafe fn setPresentationOptions_(self, options: NSApplicationPresentationOptions) -> BOOL; + unsafe fn presentationOptions_(self) -> NSApplicationPresentationOptions; + unsafe fn setMainMenu_(self, menu: id); + unsafe fn setServicesMenu_(self, menu: id); + unsafe fn setWindowsMenu_(self, menu: id); + unsafe fn activateIgnoringOtherApps_(self, ignore: BOOL); + unsafe fn run(self); + unsafe fn finishLaunching(self); + unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_(self, + mask: NSUInteger, + expiration: id, + in_mode: id, + dequeue: BOOL) -> id; + unsafe fn sendEvent_(self, an_event: id); + unsafe fn postEvent_atStart_(self, anEvent: id, flag: BOOL); + unsafe fn stop_(self, sender: id); + unsafe fn setApplicationIconImage_(self, image: id); + unsafe fn requestUserAttention_(self, requestType: NSRequestUserAttentionType); +} + +impl NSApplication for id { + unsafe fn mainMenu(self) -> id { + msg_send![self, mainMenu] + } + + unsafe fn setActivationPolicy_(self, policy: NSApplicationActivationPolicy) -> BOOL { + msg_send![self, setActivationPolicy:policy as NSInteger] + } + + unsafe fn setPresentationOptions_(self, options: NSApplicationPresentationOptions) -> BOOL { + msg_send![self, setPresentationOptions:options.bits] + } + + unsafe fn presentationOptions_(self) -> NSApplicationPresentationOptions { + let options = msg_send![self, presentationOptions]; + return NSApplicationPresentationOptions::from_bits(options).unwrap(); + } + + unsafe fn setMainMenu_(self, menu: id) { + msg_send![self, setMainMenu:menu] + } + + unsafe fn setServicesMenu_(self, menu: id) { + msg_send![self, setServicesMenu:menu] + } + + unsafe fn setWindowsMenu_(self, menu: id) { + msg_send![self, setWindowsMenu:menu] + } + + unsafe fn activateIgnoringOtherApps_(self, ignore: BOOL) { + msg_send![self, activateIgnoringOtherApps:ignore] + } + + unsafe fn run(self) { + msg_send![self, run] + } + + unsafe fn finishLaunching(self) { + msg_send![self, finishLaunching] + } + + unsafe fn nextEventMatchingMask_untilDate_inMode_dequeue_(self, + mask: NSUInteger, + expiration: id, + in_mode: id, + dequeue: BOOL) -> id { + msg_send![self, nextEventMatchingMask:mask + untilDate:expiration + inMode:in_mode + dequeue:dequeue] + } + + unsafe fn sendEvent_(self, an_event: id) { + msg_send![self, sendEvent:an_event] + } + + unsafe fn postEvent_atStart_(self, anEvent: id, flag: BOOL) { + msg_send![self, postEvent:anEvent atStart:flag] + } + + unsafe fn stop_(self, sender: id) { + msg_send![self, stop:sender] + } + + unsafe fn setApplicationIconImage_(self, icon: id) { + msg_send![self, setApplicationIconImage:icon] + } + + unsafe fn requestUserAttention_(self, requestType: NSRequestUserAttentionType) { + msg_send![self, requestUserAttention:requestType] + } +} + +pub trait NSRunningApplication: Sized { + unsafe fn currentApplication(_: Self) -> id { + msg_send![class!(NSRunningApplication), currentApplication] + } + unsafe fn activateWithOptions_(self, options: NSApplicationActivationOptions) -> BOOL; +} + +impl NSRunningApplication for id { + unsafe fn activateWithOptions_(self, options: NSApplicationActivationOptions) -> BOOL { + msg_send![self, activateWithOptions:options as NSUInteger] + } +} + +pub trait NSPasteboard: Sized { + unsafe fn generalPasteboard(_: Self) -> id { + msg_send![class!(NSPasteboard), generalPasteboard] + } + + unsafe fn pasteboardByFilteringData_ofType(_: Self, data: id, _type: id) -> id { + msg_send![class!(NSPasteboard), pasteboardByFilteringData:data ofType:_type] + } + + unsafe fn pasteboardByFilteringFile(_: Self, file: id) -> id { + msg_send![class!(NSPasteboard), pasteboardByFilteringFile:file] + } + + unsafe fn pasteboardByFilteringTypesInPasteboard(_: Self, pboard: id) -> id { + msg_send![class!(NSPasteboard), pasteboardByFilteringTypesInPasteboard:pboard] + } + + unsafe fn pasteboardWithName(_: Self, name: id) -> id { + msg_send![class!(NSPasteboard), pasteboardWithName:name] + } + + unsafe fn pasteboardWithUniqueName(_: Self) -> id { + msg_send![class!(NSPasteboard), pasteboardWithUniqueName] + } + + unsafe fn releaseGlobally(self); + + unsafe fn clearContents(self) -> NSInteger; + unsafe fn writeObjects(self, objects: id) -> BOOL; + unsafe fn setData_forType(self, data: id, dataType: id) -> BOOL; + unsafe fn setPropertyList_forType(self, plist: id, dataType: id) -> BOOL; + unsafe fn setString_forType(self, string: id, dataType: id) -> BOOL; + + unsafe fn readObjectsForClasses_options(self, classArray: id, options: id) -> id; + unsafe fn pasteboardItems(self) -> id; + unsafe fn indexOfPasteboardItem(self, pasteboardItem: id) -> NSInteger; + unsafe fn dataForType(self, dataType: id) -> id; + unsafe fn propertyListForType(self, dataType: id) -> id; + unsafe fn stringForType(self, dataType: id) -> id; + + unsafe fn availableTypeFromArray(self, types: id) -> id; + unsafe fn canReadItemWithDataConformingToTypes(self, types: id) -> BOOL; + unsafe fn canReadObjectForClasses_options(self, classArray: id, options: id) -> BOOL; + unsafe fn types(self) -> id; + unsafe fn typesFilterableTo(_: Self, _type: id) -> id { + msg_send![class!(NSPasteboard), typesFilterableTo:_type] + } + + unsafe fn name(self) -> id; + unsafe fn changeCount(self) -> NSInteger; + + unsafe fn declareTypes_owner(self, newTypes: id, newOwner: id) -> NSInteger; + unsafe fn addTypes_owner(self, newTypes: id, newOwner: id) -> NSInteger; + unsafe fn writeFileContents(self, filename: id) -> BOOL; + unsafe fn writeFileWrapper(self, wrapper: id) -> BOOL; + + unsafe fn readFileContentsType_toFile(self, _type: id, filename: id) -> id; + unsafe fn readFileWrapper(self) -> id; +} + +impl NSPasteboard for id { + unsafe fn releaseGlobally(self) { + msg_send![self, releaseGlobally] + } + + unsafe fn clearContents(self) -> NSInteger { + msg_send![self, clearContents] + } + + unsafe fn writeObjects(self, objects: id) -> BOOL { + msg_send![self, writeObjects:objects] + } + + unsafe fn setData_forType(self, data: id, dataType: id) -> BOOL { + msg_send![self, setData:data forType:dataType] + } + + unsafe fn setPropertyList_forType(self, plist: id, dataType: id) -> BOOL { + msg_send![self, setPropertyList:plist forType:dataType] + } + + unsafe fn setString_forType(self, string: id, dataType: id) -> BOOL { + msg_send![self, setString:string forType:dataType] + } + + unsafe fn readObjectsForClasses_options(self, classArray: id, options: id) -> id { + msg_send![self, readObjectsForClasses:classArray options:options] + } + + unsafe fn pasteboardItems(self) -> id { + msg_send![self, pasteboardItems] + } + + unsafe fn indexOfPasteboardItem(self, pasteboardItem: id) -> NSInteger { + msg_send![self, indexOfPasteboardItem:pasteboardItem] + } + + unsafe fn dataForType(self, dataType: id) -> id { + msg_send![self, dataForType:dataType] + } + + unsafe fn propertyListForType(self, dataType: id) -> id { + msg_send![self, propertyListForType:dataType] + } + + unsafe fn stringForType(self, dataType: id) -> id { + msg_send![self, stringForType:dataType] + } + + unsafe fn availableTypeFromArray(self, types: id) -> id { + msg_send![self, availableTypeFromArray:types] + } + + unsafe fn canReadItemWithDataConformingToTypes(self, types: id) -> BOOL { + msg_send![self, canReadItemWithDataConformingToTypes:types] + } + + unsafe fn canReadObjectForClasses_options(self, classArray: id, options: id) -> BOOL { + msg_send![self, canReadObjectForClasses:classArray options:options] + } + + unsafe fn types(self) -> id { + msg_send![self, types] + } + + unsafe fn name(self) -> id { + msg_send![self, name] + } + + unsafe fn changeCount(self) -> NSInteger { + msg_send![self, changeCount] + } + + unsafe fn declareTypes_owner(self, newTypes: id, newOwner: id) -> NSInteger { + msg_send![self, declareTypes:newTypes owner:newOwner] + } + + unsafe fn addTypes_owner(self, newTypes: id, newOwner: id) -> NSInteger { + msg_send![self, addTypes:newTypes owner:newOwner] + } + + unsafe fn writeFileContents(self, filename: id) -> BOOL { + msg_send![self, writeFileContents:filename] + } + + unsafe fn writeFileWrapper(self, wrapper: id) -> BOOL { + msg_send![self, writeFileWrapper:wrapper] + } + + unsafe fn readFileContentsType_toFile(self, _type: id, filename: id) -> id { + msg_send![self, readFileContentsType:_type toFile:filename] + } + + unsafe fn readFileWrapper(self) -> id { + msg_send![self, readFileWrapper] + } + +} + +pub trait NSPasteboardItem: Sized { + unsafe fn types(self) -> id; + + unsafe fn setDataProvider_forTypes(self, dataProvider: id, types: id) -> BOOL; + unsafe fn setData_forType(self, data: id, _type: id) -> BOOL; + unsafe fn setString_forType(self, string: id, _type: id) -> BOOL; + unsafe fn setPropertyList_forType(self, propertyList: id, _type: id) -> BOOL; + + unsafe fn dataForType(self, _type: id) -> id; + unsafe fn stringForType(self, _type: id) -> id; + unsafe fn propertyListForType(self, _type: id) -> id; +} + +impl NSPasteboardItem for id { + unsafe fn types(self) -> id { + msg_send![self, types] + } + + unsafe fn setDataProvider_forTypes(self, dataProvider: id, types: id) -> BOOL { + msg_send![self, setDataProvider:dataProvider forTypes:types] + } + + unsafe fn setData_forType(self, data: id, _type: id) -> BOOL { + msg_send![self, setData:data forType:_type] + } + + unsafe fn setString_forType(self, string: id, _type: id) -> BOOL { + msg_send![self, setString:string forType:_type] + } + + unsafe fn setPropertyList_forType(self, propertyList: id, _type: id) -> BOOL { + msg_send![self, setPropertyList:propertyList forType:_type] + } + + unsafe fn dataForType(self, _type: id) -> id { + msg_send![self, dataForType:_type] + } + + unsafe fn stringForType(self, _type: id) -> id { + msg_send![self, stringForType:_type] + } + + unsafe fn propertyListForType(self, _type: id) -> id { + msg_send![self, propertyListForType:_type] + } +} + +pub trait NSPasteboardItemDataProvider: Sized { + unsafe fn pasteboard_item_provideDataForType(self, pasteboard: id, item: id, _type: id); + unsafe fn pasteboardFinishedWithDataProvider(self, pasteboard: id); +} + +impl NSPasteboardItemDataProvider for id { + unsafe fn pasteboard_item_provideDataForType(self, pasteboard: id, item: id, _type: id) { + msg_send![self, pasteboard:pasteboard item:item provideDataForType:_type] + } + + unsafe fn pasteboardFinishedWithDataProvider(self, pasteboard: id) { + msg_send![self, pasteboardFinishedWithDataProvider:pasteboard] + } +} + +pub trait NSPasteboardWriting: Sized { + unsafe fn writableTypesForPasteboard(self, pasteboard: id) -> id; + unsafe fn writingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardWritingOptions; + + unsafe fn pasteboardPropertyListForType(self, _type: id) -> id; +} + +impl NSPasteboardWriting for id { + unsafe fn writableTypesForPasteboard(self, pasteboard: id) -> id { + msg_send![self, writableTypesForPasteboard:pasteboard] + } + + unsafe fn writingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardWritingOptions { + msg_send![self, writingOptionsForType:_type pasteboard:pasteboard] + } + + unsafe fn pasteboardPropertyListForType(self, _type: id) -> id { + msg_send![self, pasteboardPropertyListForType:_type] + } +} + +pub trait NSPasteboardReading: Sized { + unsafe fn initWithPasteboardPropertyList_ofType(self, propertyList: id, _type: id) -> id; + + unsafe fn readableTypesForPasteboard(self, pasteboard: id) -> id; + unsafe fn readingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardReadingOptions; +} + +impl NSPasteboardReading for id { + unsafe fn initWithPasteboardPropertyList_ofType(self, propertyList: id, _type: id) -> id { + msg_send![self, initWithPasteboardPropertyList:propertyList ofType:_type] + } + + unsafe fn readableTypesForPasteboard(self, pasteboard: id) -> id { + let class: id = msg_send![self, class]; + msg_send![class, readableTypesForPasteboard:pasteboard] + } + unsafe fn readingOptionsForType_pasteboard(self, _type: id, pasteboard: id) -> NSPasteboardReadingOptions { + let class: id = msg_send![self, class]; + msg_send![class, readingOptionsForType:_type pasteboard:pasteboard] + } +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSPasteboardReadingOptions { + NSPasteboardReadingAsData = 0, + NSPasteboardReadingAsString = 1 << 0, + NSPasteboardReadingAsPropertyList = 1 << 1, + NSPasteboardReadingAsKeyedArchive = 1 << 2 +} + +#[repr(u64)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NSPasteboardWritingOptions { + NSPasteboardWritingPromised = 1 << 9, +} + +pub trait NSMenu: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSMenu), alloc] + } + + unsafe fn new(_: Self) -> id { + msg_send![class!(NSMenu), new] + } + + unsafe fn initWithTitle_(self, title: id /* NSString */) -> id; + unsafe fn setAutoenablesItems(self, state: BOOL); + + unsafe fn addItem_(self, menu_item: id); + unsafe fn addItemWithTitle_action_keyEquivalent(self, title: id, action: SEL, key: id) -> id; + unsafe fn itemAtIndex_(self, index: NSInteger) -> id; +} + +impl NSMenu for id { + unsafe fn initWithTitle_(self, title: id /* NSString */) -> id { + msg_send![self, initWithTitle:title] + } + + unsafe fn setAutoenablesItems(self, state: BOOL) { + msg_send![self, setAutoenablesItems: state] + } + + unsafe fn addItem_(self, menu_item: id) { + msg_send![self, addItem:menu_item] + } + + unsafe fn addItemWithTitle_action_keyEquivalent(self, title: id, action: SEL, key: id) -> id { + msg_send![self, addItemWithTitle:title action:action keyEquivalent:key] + } + + unsafe fn itemAtIndex_(self, index: NSInteger) -> id { + msg_send![self, itemAtIndex:index] + } +} + +pub trait NSMenuItem: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSMenuItem), alloc] + } + + unsafe fn new(_: Self) -> id { + msg_send![class!(NSMenuItem), new] + } + + unsafe fn separatorItem(_: Self) -> id { + msg_send![class!(NSMenuItem), separatorItem] + } + + unsafe fn initWithTitle_action_keyEquivalent_(self, title: id, action: SEL, key: id) -> id; + unsafe fn setKeyEquivalentModifierMask_(self, mask: NSEventModifierFlags); + unsafe fn setSubmenu_(self, submenu: id); + unsafe fn setTarget_(self, target: id); +} + +impl NSMenuItem for id { + unsafe fn initWithTitle_action_keyEquivalent_(self, title: id, action: SEL, key: id) -> id { + msg_send![self, initWithTitle:title action:action keyEquivalent:key] + } + + unsafe fn setKeyEquivalentModifierMask_(self, mask: NSEventModifierFlags) { + msg_send![self, setKeyEquivalentModifierMask:mask] + } + + unsafe fn setSubmenu_(self, submenu: id) { + msg_send![self, setSubmenu:submenu] + } + + unsafe fn setTarget_(self, target: id) { + msg_send![self, setTarget:target] + } +} + +pub type NSWindowDepth = libc::c_int; + +bitflags! { + pub struct NSWindowCollectionBehavior: NSUInteger { + const NSWindowCollectionBehaviorDefault = 0; + const NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0; + const NSWindowCollectionBehaviorMoveToActiveSpace = 1 << 1; + + const NSWindowCollectionBehaviorManaged = 1 << 2; + const NSWindowCollectionBehaviorTransient = 1 << 3; + const NSWindowCollectionBehaviorStationary = 1 << 4; + + const NSWindowCollectionBehaviorParticipatesInCycle = 1 << 5; + const NSWindowCollectionBehaviorIgnoresCycle = 1 << 6; + + const NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7; + const NSWindowCollectionBehaviorFullScreenAuxiliary = 1 << 8; + } +} + +bitflags! { + pub struct NSWindowOcclusionState: NSUInteger { + const NSWindowOcclusionStateVisible = 1 << 1; + } +} + +pub trait NSWindow: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSWindow), alloc] + } + + // Creating Windows + unsafe fn initWithContentRect_styleMask_backing_defer_(self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL) -> id; + unsafe fn initWithContentRect_styleMask_backing_defer_screen_(self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + screen: id) -> id; + + // Configuring Windows + unsafe fn styleMask(self) -> NSWindowStyleMask; + unsafe fn setStyleMask_(self, styleMask: NSWindowStyleMask); + unsafe fn toggleFullScreen_(self, sender: id); + unsafe fn worksWhenModal(self) -> BOOL; + unsafe fn alphaValue(self) -> CGFloat; + unsafe fn setAlphaValue_(self, windowAlpha: CGFloat); + unsafe fn backgroundColor(self) -> id; + unsafe fn setBackgroundColor_(self, color: id); + unsafe fn colorSpace(self) -> id; + unsafe fn setColorSpace_(self, colorSpace: id); + unsafe fn contentView(self) -> id; + unsafe fn setContentView_(self, view: id); + unsafe fn canHide(self) -> BOOL; + unsafe fn setCanHide_(self, canHide: BOOL); + unsafe fn hidesOnDeactivate(self) -> BOOL; + unsafe fn setHidesOnDeactivate_(self, hideOnDeactivate: BOOL); + unsafe fn collectionBehavior(self) -> NSWindowCollectionBehavior; + unsafe fn setCollectionBehavior_(self, collectionBehavior: NSWindowCollectionBehavior); + unsafe fn setOpaque_(self, opaque: BOOL); + unsafe fn hasShadow(self) -> BOOL; + unsafe fn setHasShadow_(self, hasShadow: BOOL); + unsafe fn invalidateShadow(self); + unsafe fn autorecalculatesContentBorderThicknessForEdge_(self, edge: NSRectEdge) -> BOOL; + unsafe fn setAutorecalculatesContentBorderThickness_forEdge_(self, + autorecalculateContentBorderThickness: BOOL, + edge: NSRectEdge) -> BOOL; + unsafe fn contentBorderThicknessForEdge_(self, edge: NSRectEdge) -> CGFloat; + unsafe fn setContentBorderThickness_forEdge_(self, borderThickness: CGFloat, edge: NSRectEdge); + unsafe fn delegate(self) -> id; + unsafe fn setDelegate_(self, delegate: id); + unsafe fn preventsApplicationTerminationWhenModal(self) -> BOOL; + unsafe fn setPreventsApplicationTerminationWhenModal_(self, flag: BOOL); + + // TODO: Accessing Window Information + + // Getting Layout Information + unsafe fn contentRectForFrameRect_styleMask_(self, windowFrame: NSRect, windowStyle: NSWindowStyleMask) -> NSRect; + unsafe fn frameRectForContentRect_styleMask_(self, windowContentRect: NSRect, windowStyle: NSWindowStyleMask) -> NSRect; + unsafe fn minFrameWidthWithTitle_styleMask_(self, windowTitle: id, windowStyle: NSWindowStyleMask) -> CGFloat; + unsafe fn contentRectForFrameRect_(self, windowFrame: NSRect) -> NSRect; + unsafe fn frameRectForContentRect_(self, windowContent: NSRect) -> NSRect; + + // Managing Windows + unsafe fn drawers(self) -> id; + unsafe fn windowController(self) -> id; + unsafe fn setWindowController_(self, windowController: id); + + // TODO: Managing Sheets + + // Sizing Windows + unsafe fn frame(self) -> NSRect; + unsafe fn setFrameOrigin_(self, point: NSPoint); + unsafe fn setFrameTopLeftPoint_(self, point: NSPoint); + unsafe fn constrainFrameRect_toScreen_(self, frameRect: NSRect, screen: id); + unsafe fn cascadeTopLeftFromPoint_(self, topLeft: NSPoint) -> NSPoint; + unsafe fn setFrame_display_(self, windowFrame: NSRect, display: BOOL); + unsafe fn setFrame_displayViews_(self, windowFrame: NSRect, display: BOOL); + unsafe fn aspectRatio(self) -> NSSize; + unsafe fn setAspectRatio_(self, aspectRatio: NSSize); + unsafe fn minSize(self) -> NSSize; + unsafe fn setMinSize_(self, minSize: NSSize); + unsafe fn maxSize(self) -> NSSize; + unsafe fn setMaxSize_(self, maxSize: NSSize); + unsafe fn performZoom_(self, sender: id); + unsafe fn zoom_(self, sender: id); + unsafe fn resizeFlags(self) -> NSInteger; + unsafe fn showsResizeIndicator(self) -> BOOL; + unsafe fn setShowsResizeIndicator_(self, showsResizeIndicator: BOOL); + unsafe fn resizeIncrements(self) -> NSSize; + unsafe fn setResizeIncrements_(self, resizeIncrements: NSSize); + unsafe fn preservesContentDuringLiveResize(self) -> BOOL; + unsafe fn setPreservesContentDuringLiveResize_(self, preservesContentDuringLiveResize: BOOL); + unsafe fn inLiveResize(self) -> BOOL; + + // Sizing Content + unsafe fn contentAspectRatio(self) -> NSSize; + unsafe fn setContentAspectRatio_(self, contentAspectRatio: NSSize); + unsafe fn contentMinSize(self) -> NSSize; + unsafe fn setContentMinSize_(self, contentMinSize: NSSize); + unsafe fn contentSize(self) -> NSSize; + unsafe fn setContentSize_(self, contentSize: NSSize); + unsafe fn contentMaxSize(self) -> NSSize; + unsafe fn setContentMaxSize_(self, contentMaxSize: NSSize); + unsafe fn contentResizeIncrements(self) -> NSSize; + unsafe fn setContentResizeIncrements_(self, contentResizeIncrements: NSSize); + + // Managing Window Visibility and Occlusion State + unsafe fn isVisible(self) -> BOOL; // NOTE: Deprecated in 10.9 + unsafe fn occlusionState(self) -> NSWindowOcclusionState; + + // Managing Window Layers + unsafe fn orderOut_(self, sender: id); + unsafe fn orderBack_(self, sender: id); + unsafe fn orderFront_(self, sender: id); + unsafe fn orderFrontRegardless(self); + unsafe fn orderFrontWindow_relativeTo_(self, orderingMode: NSWindowOrderingMode, otherWindowNumber: NSInteger); + unsafe fn level(self) -> NSInteger; + unsafe fn setLevel_(self, level: NSInteger); + + // Managing Key Status + unsafe fn canBecomeKeyWindow(self) -> BOOL; + unsafe fn makeKeyWindow(self); + unsafe fn makeKeyAndOrderFront_(self, sender: id); + // skipped: becomeKeyWindow (should not be invoked directly, according to Apple's documentation) + // skipped: resignKeyWindow (should not be invoked directly, according to Apple's documentation) + + // Managing Main Status + unsafe fn canBecomeMainWindow(self) -> BOOL; + unsafe fn makeMainWindow(self); + // skipped: becomeMainWindow (should not be invoked directly, according to Apple's documentation) + // skipped: resignMainWindow (should not be invoked directly, according to Apple's documentation) + + // Managing Toolbars + unsafe fn toolbar(self) -> id /* NSToolbar */; + unsafe fn setToolbar_(self, toolbar: id /* NSToolbar */); + unsafe fn runToolbarCustomizationPalette(self, sender: id); + + // TODO: Managing Attached Windows + // TODO: Managing Window Buffers + // TODO: Managing Default Buttons + // TODO: Managing Field Editors + // TODO: Managing the Window Menu + // TODO: Managing Cursor Rectangles + + // Managing Title Bars + unsafe fn standardWindowButton_(self, windowButtonKind: NSWindowButton) -> id; + + // Managing Window Tabs + unsafe fn allowsAutomaticWindowTabbing(_: Self) -> BOOL; + unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL); + unsafe fn tabbingIdentifier(self) -> id; + unsafe fn tabbingMode(self) -> NSWindowTabbingMode; + unsafe fn setTabbingMode_(self, tabbingMode: NSWindowTabbingMode); + unsafe fn addTabbedWindow_ordered_(self, window: id, ordering_mode: NSWindowOrderingMode); + unsafe fn toggleTabBar_(self, sender: id); + + // TODO: Managing Tooltips + // TODO: Handling Events + + // Managing Responders + unsafe fn initialFirstResponder(self) -> id; + unsafe fn firstResponder(self) -> id; + unsafe fn setInitialFirstResponder_(self, responder: id); + unsafe fn makeFirstResponder_(self, responder: id) -> BOOL; + + // TODO: Managing the Key View Loop + + // Handling Keyboard Events + unsafe fn keyDown_(self, event: id); + + // Handling Mouse Events + unsafe fn acceptsMouseMovedEvents(self) -> BOOL; + unsafe fn ignoresMouseEvents(self) -> BOOL; + unsafe fn setIgnoresMouseEvents_(self, ignoreMouseEvents: BOOL); + unsafe fn mouseLocationOutsideOfEventStream(self) -> NSPoint; + unsafe fn setAcceptsMouseMovedEvents_(self, acceptMouseMovedEvents: BOOL); + unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_(self, + point: NSPoint, + windowNumber: NSInteger) -> NSInteger; + + // TODO: Handling Window Restoration + // TODO: Bracketing Drawing Operations + // TODO: Drawing Windows + // TODO: Window Animation + // TODO: Updating Windows + // TODO: Dragging Items + + // Converting Coordinates + unsafe fn backingScaleFactor(self) -> CGFloat; + unsafe fn backingAlignedRect_options_(self, rect: NSRect, options: NSAlignmentOptions) -> NSRect; + unsafe fn convertRectFromBacking_(self, rect: NSRect) -> NSRect; + unsafe fn convertRectToBacking_(self, rect: NSRect) -> NSRect; + unsafe fn convertRectToScreen_(self, rect: NSRect) -> NSRect; + unsafe fn convertRectFromScreen_(self, rect: NSRect) -> NSRect; + + // Accessing Edited Status + unsafe fn setDocumentEdited_(self, documentEdited: BOOL); + + // Managing Titles + unsafe fn title(self) -> id; + unsafe fn setTitle_(self, title: id); + unsafe fn setTitleWithRepresentedFilename_(self, filePath: id); + unsafe fn setTitleVisibility_(self, visibility: NSWindowTitleVisibility); + unsafe fn setTitlebarAppearsTransparent_(self, transparent: BOOL); + unsafe fn representedFilename(self) -> id; + unsafe fn setRepresentedFilename_(self, filePath: id); + unsafe fn representedURL(self) -> id; + unsafe fn setRepresentedURL_(self, representedURL: id); + + // Accessing Screen Information + unsafe fn screen(self) -> id; + unsafe fn deepestScreen(self) -> id; + unsafe fn displaysWhenScreenProfileChanges(self) -> BOOL; + unsafe fn setDisplaysWhenScreenProfileChanges_(self, displaysWhenScreenProfileChanges: BOOL); + + // Moving Windows + unsafe fn setMovableByWindowBackground_(self, movableByWindowBackground: BOOL); + unsafe fn setMovable_(self, movable: BOOL); + unsafe fn center(self); + + // Closing Windows + unsafe fn performClose_(self, sender: id); + unsafe fn close(self); + unsafe fn setReleasedWhenClosed_(self, releasedWhenClosed: BOOL); + + // Minimizing Windows + unsafe fn performMiniaturize_(self, sender: id); + unsafe fn miniaturize_(self, sender: id); + unsafe fn deminiaturize_(self, sender: id); + unsafe fn miniwindowImage(self) -> id; + unsafe fn setMiniwindowImage_(self, miniwindowImage: id); + unsafe fn miniwindowTitle(self) -> id; + unsafe fn setMiniwindowTitle_(self, miniwindowTitle: id); + + // TODO: Getting the Dock Tile + // TODO: Printing Windows + // TODO: Providing Services + // TODO: Working with Carbon + // TODO: Triggering Constraint-Based Layout + // TODO: Debugging Constraint-Based Layout + // TODO: Constraint-Based Layouts +} + +impl NSWindow for id { + // Creating Windows + + unsafe fn initWithContentRect_styleMask_backing_defer_(self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL) -> id { + msg_send![self, initWithContentRect:rect + styleMask:style.bits + backing:backing as NSUInteger + defer:defer] + } + + unsafe fn initWithContentRect_styleMask_backing_defer_screen_(self, + rect: NSRect, + style: NSWindowStyleMask, + backing: NSBackingStoreType, + defer: BOOL, + screen: id) -> id { + msg_send![self, initWithContentRect:rect + styleMask:style.bits + backing:backing as NSUInteger + defer:defer + screen:screen] + } + + // Configuring Windows + + unsafe fn styleMask(self) -> NSWindowStyleMask { + NSWindowStyleMask::from_bits_truncate(msg_send![self, styleMask]) + } + + unsafe fn setStyleMask_(self, styleMask: NSWindowStyleMask) { + msg_send![self, setStyleMask:styleMask.bits] + } + + unsafe fn toggleFullScreen_(self, sender: id) { + msg_send![self, toggleFullScreen:sender] + } + + unsafe fn worksWhenModal(self) -> BOOL { + msg_send![self, worksWhenModal] + } + + unsafe fn alphaValue(self) -> CGFloat { + msg_send![self, alphaValue] + } + + unsafe fn setAlphaValue_(self, windowAlpha: CGFloat) { + msg_send![self, setAlphaValue:windowAlpha] + } + + unsafe fn backgroundColor(self) -> id { + msg_send![self, backgroundColor] + } + + unsafe fn setBackgroundColor_(self, color: id) { + msg_send![self, setBackgroundColor:color] + } + + unsafe fn colorSpace(self) -> id { + msg_send![self, colorSpace] + } + + unsafe fn setColorSpace_(self, colorSpace: id) { + msg_send![self, setColorSpace:colorSpace] + } + + unsafe fn contentView(self) -> id { + msg_send![self, contentView] + } + + unsafe fn setContentView_(self, view: id) { + msg_send![self, setContentView:view] + } + + unsafe fn canHide(self) -> BOOL { + msg_send![self, canHide] + } + + unsafe fn setCanHide_(self, canHide: BOOL) { + msg_send![self, setCanHide:canHide] + } + + unsafe fn hidesOnDeactivate(self) -> BOOL { + msg_send![self, hidesOnDeactivate] + } + + unsafe fn setHidesOnDeactivate_(self, hideOnDeactivate: BOOL) { + msg_send![self, setHidesOnDeactivate:hideOnDeactivate] + } + + unsafe fn collectionBehavior(self) -> NSWindowCollectionBehavior { + msg_send![self, collectionBehavior] + } + + unsafe fn setCollectionBehavior_(self, collectionBehavior: NSWindowCollectionBehavior) { + msg_send![self, setCollectionBehavior:collectionBehavior] + } + + unsafe fn setOpaque_(self, opaque: BOOL) { + msg_send![self, setOpaque:opaque] + } + + unsafe fn hasShadow(self) -> BOOL { + msg_send![self, hasShadow] + } + + unsafe fn setHasShadow_(self, hasShadow: BOOL) { + msg_send![self, setHasShadow:hasShadow] + } + + unsafe fn invalidateShadow(self) { + msg_send![self, invalidateShadow] + } + + unsafe fn autorecalculatesContentBorderThicknessForEdge_(self, edge: NSRectEdge) -> BOOL { + msg_send![self, autorecalculatesContentBorderThicknessForEdge:edge] + } + + unsafe fn setAutorecalculatesContentBorderThickness_forEdge_(self, + autorecalculateContentBorderThickness: BOOL, + edge: NSRectEdge) -> BOOL { + msg_send![self, setAutorecalculatesContentBorderThickness: + autorecalculateContentBorderThickness forEdge:edge] + } + + unsafe fn contentBorderThicknessForEdge_(self, edge: NSRectEdge) -> CGFloat { + msg_send![self, contentBorderThicknessForEdge:edge] + } + + unsafe fn setContentBorderThickness_forEdge_(self, borderThickness: CGFloat, edge: NSRectEdge) { + msg_send![self, setContentBorderThickness:borderThickness forEdge:edge] + } + + unsafe fn delegate(self) -> id { + msg_send![self, delegate] + } + + unsafe fn setDelegate_(self, delegate: id) { + msg_send![self, setDelegate:delegate] + } + + unsafe fn preventsApplicationTerminationWhenModal(self) -> BOOL { + msg_send![self, preventsApplicationTerminationWhenModal] + } + + unsafe fn setPreventsApplicationTerminationWhenModal_(self, flag: BOOL) { + msg_send![self, setPreventsApplicationTerminationWhenModal:flag] + } + + // TODO: Accessing Window Information + + // Getting Layout Information + + unsafe fn contentRectForFrameRect_styleMask_(self, windowFrame: NSRect, windowStyle: NSWindowStyleMask) -> NSRect { + msg_send![self, contentRectForFrameRect:windowFrame styleMask:windowStyle.bits] + } + + unsafe fn frameRectForContentRect_styleMask_(self, windowContentRect: NSRect, windowStyle: NSWindowStyleMask) -> NSRect { + msg_send![self, frameRectForContentRect:windowContentRect styleMask:windowStyle.bits] + } + + unsafe fn minFrameWidthWithTitle_styleMask_(self, windowTitle: id, windowStyle: NSWindowStyleMask) -> CGFloat { + msg_send![self, minFrameWidthWithTitle:windowTitle styleMask:windowStyle.bits] + } + + unsafe fn contentRectForFrameRect_(self, windowFrame: NSRect) -> NSRect { + msg_send![self, contentRectForFrameRect:windowFrame] + } + + unsafe fn frameRectForContentRect_(self, windowContent: NSRect) -> NSRect { + msg_send![self, frameRectForContentRect:windowContent] + } + + // Managing Windows + + unsafe fn drawers(self) -> id { + msg_send![self, drawers] + } + + unsafe fn windowController(self) -> id { + msg_send![self, windowController] + } + + unsafe fn setWindowController_(self, windowController: id) { + msg_send![self, setWindowController:windowController] + } + + // TODO: Managing Sheets + + // Sizing Windows + + unsafe fn frame(self) -> NSRect { + msg_send![self, frame] + } + + unsafe fn setFrameOrigin_(self, point: NSPoint) { + msg_send![self, setFrameOrigin:point] + } + + unsafe fn setFrameTopLeftPoint_(self, point: NSPoint) { + msg_send![self, setFrameTopLeftPoint:point] + } + + unsafe fn constrainFrameRect_toScreen_(self, frameRect: NSRect, screen: id) { + msg_send![self, constrainFrameRect:frameRect toScreen:screen] + } + + unsafe fn cascadeTopLeftFromPoint_(self, topLeft: NSPoint) -> NSPoint { + msg_send![self, cascadeTopLeftFromPoint:topLeft] + } + + unsafe fn setFrame_display_(self, windowFrame: NSRect, display: BOOL) { + msg_send![self, setFrame:windowFrame display:display] + } + + unsafe fn setFrame_displayViews_(self, windowFrame: NSRect, display: BOOL) { + msg_send![self, setFrame:windowFrame displayViews:display] + } + + unsafe fn aspectRatio(self) -> NSSize { + msg_send![self, aspectRatio] + } + + unsafe fn setAspectRatio_(self, aspectRatio: NSSize) { + msg_send![self, setAspectRatio:aspectRatio] + } + + unsafe fn minSize(self) -> NSSize { + msg_send![self, minSize] + } + + unsafe fn setMinSize_(self, minSize: NSSize) { + msg_send![self, setMinSize:minSize] + } + + unsafe fn maxSize(self) -> NSSize { + msg_send![self, maxSize] + } + + unsafe fn setMaxSize_(self, maxSize: NSSize) { + msg_send![self, setMaxSize:maxSize] + } + + unsafe fn performZoom_(self, sender: id) { + msg_send![self, performZoom:sender] + } + + unsafe fn zoom_(self, sender: id) { + msg_send![self, zoom:sender] + } + + unsafe fn resizeFlags(self) -> NSInteger { + msg_send![self, resizeFlags] + } + + unsafe fn showsResizeIndicator(self) -> BOOL { + msg_send![self, showsResizeIndicator] + } + + unsafe fn setShowsResizeIndicator_(self, showsResizeIndicator: BOOL) { + msg_send![self, setShowsResizeIndicator:showsResizeIndicator] + } + + unsafe fn resizeIncrements(self) -> NSSize { + msg_send![self, resizeIncrements] + } + + unsafe fn setResizeIncrements_(self, resizeIncrements: NSSize) { + msg_send![self, setResizeIncrements:resizeIncrements] + } + + unsafe fn preservesContentDuringLiveResize(self) -> BOOL { + msg_send![self, preservesContentDuringLiveResize] + } + + unsafe fn setPreservesContentDuringLiveResize_(self, preservesContentDuringLiveResize: BOOL) { + msg_send![self, setPreservesContentDuringLiveResize:preservesContentDuringLiveResize] + } + + unsafe fn inLiveResize(self) -> BOOL { + msg_send![self, inLiveResize] + } + + // Sizing Content + + unsafe fn contentAspectRatio(self) -> NSSize { + msg_send![self, contentAspectRatio] + } + + unsafe fn setContentAspectRatio_(self, contentAspectRatio: NSSize) { + msg_send![self, setContentAspectRatio:contentAspectRatio] + } + + unsafe fn contentMinSize(self) -> NSSize { + msg_send![self, contentMinSize] + } + + unsafe fn setContentMinSize_(self, contentMinSize: NSSize) { + msg_send![self, setContentMinSize:contentMinSize] + } + + unsafe fn contentSize(self) -> NSSize { + msg_send![self, contentSize] + } + + unsafe fn setContentSize_(self, contentSize: NSSize) { + msg_send![self, setContentSize:contentSize] + } + + unsafe fn contentMaxSize(self) -> NSSize { + msg_send![self, contentMaxSize] + } + + unsafe fn setContentMaxSize_(self, contentMaxSize: NSSize) { + msg_send![self, setContentMaxSize:contentMaxSize] + } + + unsafe fn contentResizeIncrements(self) -> NSSize { + msg_send![self, contentResizeIncrements] + } + + unsafe fn setContentResizeIncrements_(self, contentResizeIncrements: NSSize) { + msg_send![self, setContentResizeIncrements:contentResizeIncrements] + } + + // Managing Window Visibility and Occlusion State + + unsafe fn isVisible(self) -> BOOL { + msg_send![self, isVisible] + } + + unsafe fn occlusionState(self) -> NSWindowOcclusionState { + msg_send![self, occlusionState] + } + + // Managing Window Layers + + unsafe fn orderOut_(self, sender: id) { + msg_send![self, orderOut:sender] + } + + unsafe fn orderBack_(self, sender: id) { + msg_send![self, orderBack:sender] + } + + unsafe fn orderFront_(self, sender: id) { + msg_send![self, orderFront:sender] + } + + unsafe fn orderFrontRegardless(self) { + msg_send![self, orderFrontRegardless] + } + + unsafe fn orderFrontWindow_relativeTo_(self, ordering_mode: NSWindowOrderingMode, other_window_number: NSInteger) { + msg_send![self, orderWindow:ordering_mode relativeTo:other_window_number] + } + + unsafe fn level(self) -> NSInteger { + msg_send![self, level] + } + + unsafe fn setLevel_(self, level: NSInteger) { + msg_send![self, setLevel:level] + } + + // Managing Key Status + + unsafe fn canBecomeKeyWindow(self) -> BOOL { + msg_send![self, canBecomeKeyWindow] + } + + unsafe fn makeKeyWindow(self) { + msg_send![self, makeKeyWindow] + } + + unsafe fn makeKeyAndOrderFront_(self, sender: id) { + msg_send![self, makeKeyAndOrderFront:sender] + } + + // Managing Main Status + + unsafe fn canBecomeMainWindow(self) -> BOOL { + msg_send![self, canBecomeMainWindow] + } + + unsafe fn makeMainWindow(self) { + msg_send![self, makeMainWindow] + } + + // Managing Toolbars + + unsafe fn toolbar(self) -> id /* NSToolbar */ { + msg_send![self, toolbar] + } + + unsafe fn setToolbar_(self, toolbar: id /* NSToolbar */) { + msg_send![self, setToolbar:toolbar] + } + + unsafe fn runToolbarCustomizationPalette(self, sender: id) { + msg_send![self, runToolbarCustomizationPalette:sender] + } + + // TODO: Managing Attached Windows + // TODO: Managing Window Buffers + // TODO: Managing Default Buttons + // TODO: Managing Field Editors + // TODO: Managing the Window Menu + // TODO: Managing Cursor Rectangles + + // Managing Title Bars + + unsafe fn standardWindowButton_(self, windowButtonKind: NSWindowButton) -> id { + msg_send![self, standardWindowButton:windowButtonKind] + } + + // Managing Window Tabs + unsafe fn allowsAutomaticWindowTabbing(_: Self) -> BOOL { + msg_send![class!(NSWindow), allowsAutomaticWindowTabbing] + } + + unsafe fn setAllowsAutomaticWindowTabbing_(_: Self, allowsAutomaticWindowTabbing: BOOL) { + msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:allowsAutomaticWindowTabbing] + } + + unsafe fn tabbingIdentifier(self) -> id { + msg_send![self, tabbingIdentifier] + } + + unsafe fn tabbingMode(self) -> NSWindowTabbingMode { + msg_send!(self, tabbingMode) + } + + unsafe fn setTabbingMode_(self, tabbingMode: NSWindowTabbingMode) { + msg_send![self, setTabbingMode: tabbingMode] + } + + unsafe fn addTabbedWindow_ordered_(self, window: id, ordering_mode: NSWindowOrderingMode) { + msg_send![self, addTabbedWindow:window ordered: ordering_mode] + } + + unsafe fn toggleTabBar_(self, sender: id) { + msg_send![self, toggleTabBar:sender] + } + // TODO: Managing Tooltips + // TODO: Handling Events + + // Managing Responders + + unsafe fn initialFirstResponder(self) -> id { + msg_send![self, initialFirstResponder] + } + + unsafe fn firstResponder(self) -> id { + msg_send![self, firstResponder] + } + + unsafe fn setInitialFirstResponder_(self, responder: id) { + msg_send![self, setInitialFirstResponder:responder] + } + + unsafe fn makeFirstResponder_(self, responder: id) -> BOOL { + msg_send![self, makeFirstResponder:responder] + } + + // TODO: Managing the Key View Loop + + // Handling Keyboard Events + + unsafe fn keyDown_(self, event: id) { + msg_send![self, keyDown:event] + } + + // Handling Mouse Events + + unsafe fn acceptsMouseMovedEvents(self) -> BOOL { + msg_send![self, acceptsMouseMovedEvents] + } + + unsafe fn ignoresMouseEvents(self) -> BOOL { + msg_send![self, ignoresMouseEvents] + } + + unsafe fn setIgnoresMouseEvents_(self, ignoreMouseEvents: BOOL) { + msg_send![self, setIgnoresMouseEvents:ignoreMouseEvents] + } + + unsafe fn mouseLocationOutsideOfEventStream(self) -> NSPoint { + msg_send![self, mouseLocationOutsideOfEventStream] + } + + unsafe fn setAcceptsMouseMovedEvents_(self, acceptMouseMovedEvents: BOOL) { + msg_send![self, setAcceptsMouseMovedEvents:acceptMouseMovedEvents] + } + + unsafe fn windowNumberAtPoint_belowWindowWithWindowNumber_(self, + point: NSPoint, + windowNumber: NSInteger) -> NSInteger { + msg_send![self, windowNumberAtPoint:point belowWindowWithWindowNumber:windowNumber] + } + + // Converting Coordinates + + unsafe fn backingScaleFactor(self) -> CGFloat { + msg_send![self, backingScaleFactor] + } + + unsafe fn backingAlignedRect_options_(self, rect: NSRect, options: NSAlignmentOptions) -> NSRect { + msg_send![self, backingAlignedRect:rect options:options] + } + + unsafe fn convertRectFromBacking_(self, rect: NSRect) -> NSRect { + msg_send![self, convertRectFromBacking:rect] + } + + unsafe fn convertRectToBacking_(self, rect: NSRect) -> NSRect { + msg_send![self, convertRectToBacking:rect] + } + + unsafe fn convertRectToScreen_(self, rect: NSRect) -> NSRect { + msg_send![self, convertRectToScreen:rect] + } + + unsafe fn convertRectFromScreen_(self, rect: NSRect) -> NSRect { + msg_send![self, convertRectFromScreen:rect] + } + + // Accessing Edited Status + + unsafe fn setDocumentEdited_(self, documentEdited: BOOL) { + msg_send![self, setDocumentEdited:documentEdited] + } + + // Managing Titles + + unsafe fn title(self) -> id { + msg_send![self, title] + } + + unsafe fn setTitle_(self, title: id) { + msg_send![self, setTitle:title] + } + + unsafe fn setTitleWithRepresentedFilename_(self, filePath: id) { + msg_send![self, setTitleWithRepresentedFilename:filePath] + } + + unsafe fn setTitleVisibility_(self, visibility: NSWindowTitleVisibility) { + msg_send![self, setTitleVisibility:visibility] + } + + unsafe fn setTitlebarAppearsTransparent_(self, transparent: BOOL) { + msg_send![self, setTitlebarAppearsTransparent:transparent] + } + + unsafe fn representedFilename(self) -> id { + msg_send![self, representedFilename] + } + + unsafe fn setRepresentedFilename_(self, filePath: id) { + msg_send![self, setRepresentedFilename:filePath] + } + + unsafe fn representedURL(self) -> id { + msg_send![self, representedURL] + } + + unsafe fn setRepresentedURL_(self, representedURL: id) { + msg_send![self, setRepresentedURL:representedURL] + } + + // Accessing Screen Information + + unsafe fn screen(self) -> id { + msg_send![self, screen] + } + + unsafe fn deepestScreen(self) -> id { + msg_send![self, deepestScreen] + } + + unsafe fn displaysWhenScreenProfileChanges(self) -> BOOL { + msg_send![self, displaysWhenScreenProfileChanges] + } + + unsafe fn setDisplaysWhenScreenProfileChanges_(self, displaysWhenScreenProfileChanges: BOOL) { + msg_send![self, setDisplaysWhenScreenProfileChanges:displaysWhenScreenProfileChanges] + } + + // Moving Windows + + unsafe fn setMovableByWindowBackground_(self, movableByWindowBackground: BOOL) { + msg_send![self, setMovableByWindowBackground:movableByWindowBackground] + } + + unsafe fn setMovable_(self, movable: BOOL) { + msg_send![self, setMovable:movable] + } + + unsafe fn center(self) { + msg_send![self, center] + } + + // Closing Windows + + unsafe fn performClose_(self, sender: id) { + msg_send![self, performClose:sender] + } + + unsafe fn close(self) { + msg_send![self, close] + } + + unsafe fn setReleasedWhenClosed_(self, releasedWhenClosed: BOOL) { + msg_send![self, setReleasedWhenClosed:releasedWhenClosed] + } + + // Minimizing Windows + + unsafe fn performMiniaturize_(self, sender: id) { + msg_send![self, performMiniaturize:sender] + } + + unsafe fn miniaturize_(self, sender: id) { + msg_send![self, miniaturize:sender] + } + + unsafe fn deminiaturize_(self, sender: id) { + msg_send![self, deminiaturize:sender] + } + + unsafe fn miniwindowImage(self) -> id { + msg_send![self, miniwindowImage] + } + + unsafe fn setMiniwindowImage_(self, miniwindowImage: id) { + msg_send![self, setMiniwindowImage:miniwindowImage] + } + + unsafe fn miniwindowTitle(self) -> id { + msg_send![self, miniwindowTitle] + } + + unsafe fn setMiniwindowTitle_(self, miniwindowTitle: id) { + msg_send![self, setMiniwindowTitle:miniwindowTitle] + } + + // TODO: Getting the Dock Tile + // TODO: Printing Windows + // TODO: Providing Services + // TODO: Working with Carbon + // TODO: Triggering Constraint-Based Layout + // TODO: Debugging Constraint-Based Layout + // TODO: Constraint-Based Layouts +} + +pub trait NSView: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSView), alloc] + } + + unsafe fn init(self) -> id; + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn bounds(self) -> NSRect; + unsafe fn frame(self) -> NSRect; + unsafe fn display_(self); + unsafe fn setWantsBestResolutionOpenGLSurface_(self, flag: BOOL); + unsafe fn convertPoint_fromView_(self, point: NSPoint, view: id) -> NSPoint; + unsafe fn addSubview_(self, view: id); + unsafe fn superview(self) -> id; + unsafe fn removeFromSuperview(self); + unsafe fn setAutoresizingMask_(self, autoresizingMask: NSAutoresizingMaskOptions); + + unsafe fn wantsLayer(self) -> BOOL; + unsafe fn setWantsLayer(self, wantsLayer: BOOL); + unsafe fn layer(self) -> id; + unsafe fn setLayer(self, layer: id); + + unsafe fn widthAnchor(self) -> id; + unsafe fn heightAnchor(self) -> id; + unsafe fn convertRectToBacking(self, rect: NSRect) -> NSRect; +} + +impl NSView for id { + unsafe fn init(self) -> id { + msg_send![self, init] + } + + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + + unsafe fn bounds(self) -> NSRect { + msg_send![self, bounds] + } + + unsafe fn frame(self) -> NSRect { + msg_send![self, frame] + } + + unsafe fn display_(self) { + msg_send![self, display] + } + + unsafe fn setWantsBestResolutionOpenGLSurface_(self, flag: BOOL) { + msg_send![self, setWantsBestResolutionOpenGLSurface:flag] + } + + unsafe fn convertPoint_fromView_(self, point: NSPoint, view: id) -> NSPoint { + msg_send![self, convertPoint:point fromView:view] + } + + unsafe fn addSubview_(self, view: id) { + msg_send![self, addSubview:view] + } + + unsafe fn superview(self) -> id { + msg_send![self, superview] + } + + unsafe fn removeFromSuperview(self) { + msg_send![self, removeFromSuperview] + } + + unsafe fn setAutoresizingMask_(self, autoresizingMask: NSAutoresizingMaskOptions) { + msg_send![self, setAutoresizingMask:autoresizingMask] + } + + unsafe fn wantsLayer(self) -> BOOL { + msg_send![self, wantsLayer] + } + + unsafe fn setWantsLayer(self, wantsLayer: BOOL) { + msg_send![self, setWantsLayer:wantsLayer] + } + + unsafe fn layer(self) -> id { + msg_send![self, layer] + } + + unsafe fn setLayer(self, layer: id) { + msg_send![self, setLayer:layer] + } + + unsafe fn widthAnchor(self) -> id { + msg_send![self, widthAnchor] + } + + unsafe fn heightAnchor(self) -> id { + msg_send![self, heightAnchor] + } + + unsafe fn convertRectToBacking(self, rect: NSRect) -> NSRect { + msg_send![self, convertRectToBacking:rect] + } +} + +pub type NSAutoresizingMaskOptions = u64; + +pub const NSViewNotSizable: u64 = 0; +pub const NSViewMinXMargin: u64 = 1; +pub const NSViewWidthSizable: u64 = 2; +pub const NSViewMaxXMargin: u64 = 4; +pub const NSViewMinYMargin: u64 = 8; +pub const NSViewHeightSizable: u64 = 16; +pub const NSViewMaxYMargin: u64 = 32; + +pub trait NSOpenGLView: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSOpenGLView), alloc] + } + + unsafe fn initWithFrame_pixelFormat_(self, frameRect: NSRect, format: id) -> id; + unsafe fn display_(self); + unsafe fn setOpenGLContext_(self, context: id); + unsafe fn setPixelFormat_(self, pixelformat: id); +} + +impl NSOpenGLView for id { + unsafe fn initWithFrame_pixelFormat_(self, frameRect: NSRect, format: id) -> id { + msg_send![self, initWithFrame:frameRect pixelFormat:format] + } + + unsafe fn display_(self) { + msg_send![self, display] + } + + unsafe fn setOpenGLContext_(self, context: id) { + msg_send![self, setOpenGLContext:context] + } + + unsafe fn setPixelFormat_(self, pixelformat: id) { + msg_send![self, setPixelFormat:pixelformat] + } +} + +pub trait NSOpenGLPixelFormat: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSOpenGLPixelFormat), alloc] + } + + // Creating an NSOpenGLPixelFormat Object + + unsafe fn initWithAttributes_(self, attributes: &[u32]) -> id; + + // Managing the Pixel Format + + unsafe fn getValues_forAttribute_forVirtualScreen_(self, val: *mut GLint, attrib: NSOpenGLPixelFormatAttribute, screen: GLint); + unsafe fn numberOfVirtualScreens(self) -> GLint; + +} + +impl NSOpenGLPixelFormat for id { + // Creating an NSOpenGLPixelFormat Object + + unsafe fn initWithAttributes_(self, attributes: &[u32]) -> id { + msg_send![self, initWithAttributes:attributes] + } + + // Managing the Pixel Format + + unsafe fn getValues_forAttribute_forVirtualScreen_(self, val: *mut GLint, attrib: NSOpenGLPixelFormatAttribute, screen: GLint) { + msg_send![self, getValues:val forAttribute:attrib forVirtualScreen:screen] + } + + unsafe fn numberOfVirtualScreens(self) -> GLint { + msg_send![self, numberOfVirtualScreens] + } +} + +pub trait NSOpenGLContext: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSOpenGLContext), alloc] + } + + // Context Creation + unsafe fn initWithFormat_shareContext_(self, format: id /* (NSOpenGLPixelFormat *) */, shareContext: id /* (NSOpenGLContext *) */) -> id /* (instancetype) */; + unsafe fn initWithCGLContextObj_(self, context: CGLContextObj) -> id /* (instancetype) */; + + // Managing the Current Context + unsafe fn clearCurrentContext(_: Self); + unsafe fn currentContext(_: Self) -> id /* (NSOpenGLContext *) */; + unsafe fn makeCurrentContext(self); + + // Drawable Object Management + unsafe fn setView_(self, view: id /* (NSView *) */); + unsafe fn view(self) -> id /* (NSView *) */; + unsafe fn clearDrawable(self); + unsafe fn update(self); + + // Flushing the Drawing Buffer + unsafe fn flushBuffer(self); + + // Context Parameter Handling + unsafe fn setValues_forParameter_(self, vals: *const GLint, param: NSOpenGLContextParameter); + unsafe fn getValues_forParameter_(self, vals: *mut GLint, param: NSOpenGLContextParameter); + + // Working with Virtual Screens + unsafe fn setCurrentVirtualScreen_(self, screen: GLint); + unsafe fn currentVirtualScreen(self) -> GLint; + + // Getting the CGL Context Object + unsafe fn CGLContextObj(self) -> CGLContextObj; +} + +impl NSOpenGLContext for id { + // Context Creation + + unsafe fn initWithFormat_shareContext_(self, format: id /* (NSOpenGLPixelFormat *) */, shareContext: id /* (NSOpenGLContext *) */) -> id /* (instancetype) */ { + msg_send![self, initWithFormat:format shareContext:shareContext] + } + + unsafe fn initWithCGLContextObj_(self, context: CGLContextObj) -> id /* (instancetype) */ { + msg_send![self, initWithCGLContextObj:context] + } + + // Managing the Current Context + + unsafe fn clearCurrentContext(_: Self) { + msg_send![class!(NSOpenGLContext), clearCurrentContext] + } + + unsafe fn currentContext(_: Self) -> id /* (NSOpenGLContext *) */ { + msg_send![class!(NSOpenGLContext), currentContext] + } + + unsafe fn makeCurrentContext(self) { + msg_send![self, makeCurrentContext] + } + + // Drawable Object Management + + unsafe fn setView_(self, view: id /* (NSView *) */) { + msg_send![self, setView:view] + } + + unsafe fn view(self) -> id /* (NSView *) */ { + msg_send![self, view] + } + + unsafe fn clearDrawable(self) { + msg_send![self, clearDrawable] + } + + unsafe fn update(self) { + msg_send![self, update] + } + + // Flushing the Drawing Buffer + + unsafe fn flushBuffer(self) { + msg_send![self, flushBuffer] + } + + // Context Parameter Handling + + unsafe fn setValues_forParameter_(self, vals: *const GLint, param: NSOpenGLContextParameter) { + msg_send![self, setValues:vals forParameter:param] + } + + unsafe fn getValues_forParameter_(self, vals: *mut GLint, param: NSOpenGLContextParameter) { + msg_send![self, getValues:vals forParameter:param] + } + + // Working with Virtual Screens + + unsafe fn setCurrentVirtualScreen_(self, screen: GLint) { + msg_send![self, setCurrentVirtualScreen:screen] + } + + unsafe fn currentVirtualScreen(self) -> GLint { + msg_send![self, currentVirtualScreen] + } + + // Getting the CGL Context Object + + unsafe fn CGLContextObj(self) -> CGLContextObj { + msg_send![self, CGLContextObj] + } +} + +bitflags! { + pub struct NSEventSwipeTrackingOptions: NSUInteger { + const NSEventSwipeTrackingLockDirection = 0x1 << 0; + const NSEventSwipeTrackingClampGestureAmount = 0x1 << 1; + } +} + +#[repr(i64)] // NSInteger +pub enum NSEventGestureAxis { + NSEventGestureAxisNone = 0, + NSEventGestureAxisHorizontal, + NSEventGestureAxisVertical, +} + +bitflags! { + pub struct NSEventPhase: NSUInteger { + const NSEventPhaseNone = 0; + const NSEventPhaseBegan = 0x1 << 0; + const NSEventPhaseStationary = 0x1 << 1; + const NSEventPhaseChanged = 0x1 << 2; + const NSEventPhaseEnded = 0x1 << 3; + const NSEventPhaseCancelled = 0x1 << 4; + const NSEventPhaseMayBegin = 0x1 << 5; + } +} + +bitflags! { + pub struct NSTouchPhase: NSUInteger { + const NSTouchPhaseBegan = 1 << 0; + const NSTouchPhaseMoved = 1 << 1; + const NSTouchPhaseStationary = 1 << 2; + const NSTouchPhaseEnded = 1 << 3; + const NSTouchPhaseCancelled = 1 << 4; + const NSTouchPhaseTouching = NSTouchPhase::NSTouchPhaseBegan.bits + | NSTouchPhase::NSTouchPhaseMoved.bits + | NSTouchPhase::NSTouchPhaseStationary.bits; + const NSTouchPhaseAny = !0; // NSUIntegerMax + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(u64)] // NSUInteger +pub enum NSEventType { + NSLeftMouseDown = 1, + NSLeftMouseUp = 2, + NSRightMouseDown = 3, + NSRightMouseUp = 4, + NSMouseMoved = 5, + NSLeftMouseDragged = 6, + NSRightMouseDragged = 7, + NSMouseEntered = 8, + NSMouseExited = 9, + NSKeyDown = 10, + NSKeyUp = 11, + NSFlagsChanged = 12, + NSAppKitDefined = 13, + NSSystemDefined = 14, + NSApplicationDefined = 15, + NSPeriodic = 16, + NSCursorUpdate = 17, + NSScrollWheel = 22, + NSTabletPoint = 23, + NSTabletProximity = 24, + NSOtherMouseDown = 25, + NSOtherMouseUp = 26, + NSOtherMouseDragged = 27, + NSEventTypeGesture = 29, + NSEventTypeMagnify = 30, + NSEventTypeSwipe = 31, + NSEventTypeRotate = 18, + NSEventTypeBeginGesture = 19, + NSEventTypeEndGesture = 20, + NSEventTypePressure = 34, +} + +bitflags! { + pub struct NSEventMask: libc::c_ulonglong { + const NSLeftMouseDownMask = 1 << NSLeftMouseDown as libc::c_ulonglong; + const NSLeftMouseUpMask = 1 << NSLeftMouseUp as libc::c_ulonglong; + const NSRightMouseDownMask = 1 << NSRightMouseDown as libc::c_ulonglong; + const NSRightMouseUpMask = 1 << NSRightMouseUp as libc::c_ulonglong; + const NSMouseMovedMask = 1 << NSMouseMoved as libc::c_ulonglong; + const NSLeftMouseDraggedMask = 1 << NSLeftMouseDragged as libc::c_ulonglong; + const NSRightMouseDraggedMask = 1 << NSRightMouseDragged as libc::c_ulonglong; + const NSMouseEnteredMask = 1 << NSMouseEntered as libc::c_ulonglong; + const NSMouseExitedMask = 1 << NSMouseExited as libc::c_ulonglong; + const NSKeyDownMask = 1 << NSKeyDown as libc::c_ulonglong; + const NSKeyUpMask = 1 << NSKeyUp as libc::c_ulonglong; + const NSFlagsChangedMask = 1 << NSFlagsChanged as libc::c_ulonglong; + const NSAppKitDefinedMask = 1 << NSAppKitDefined as libc::c_ulonglong; + const NSSystemDefinedMask = 1 << NSSystemDefined as libc::c_ulonglong; + const NSApplicationDefinedMask = 1 << NSApplicationDefined as libc::c_ulonglong; + const NSPeriodicMask = 1 << NSPeriodic as libc::c_ulonglong; + const NSCursorUpdateMask = 1 << NSCursorUpdate as libc::c_ulonglong; + const NSScrollWheelMask = 1 << NSScrollWheel as libc::c_ulonglong; + const NSTabletPointMask = 1 << NSTabletPoint as libc::c_ulonglong; + const NSTabletProximityMask = 1 << NSTabletProximity as libc::c_ulonglong; + const NSOtherMouseDownMask = 1 << NSOtherMouseDown as libc::c_ulonglong; + const NSOtherMouseUpMask = 1 << NSOtherMouseUp as libc::c_ulonglong; + const NSOtherMouseDraggedMask = 1 << NSOtherMouseDragged as libc::c_ulonglong; + const NSEventMaskGesture = 1 << NSEventTypeGesture as libc::c_ulonglong; + const NSEventMaskSwipe = 1 << NSEventTypeSwipe as libc::c_ulonglong; + const NSEventMaskRotate = 1 << NSEventTypeRotate as libc::c_ulonglong; + const NSEventMaskBeginGesture = 1 << NSEventTypeBeginGesture as libc::c_ulonglong; + const NSEventMaskEndGesture = 1 << NSEventTypeEndGesture as libc::c_ulonglong; + const NSEventMaskPressure = 1 << NSEventTypePressure as libc::c_ulonglong; + const NSAnyEventMask = 0xffffffffffffffff; + } +} + +impl NSEventMask { + pub fn from_type(ty: NSEventType) -> NSEventMask { + NSEventMask { bits: 1 << ty as libc::c_ulonglong } + } +} + +bitflags! { + pub struct NSEventModifierFlags: NSUInteger { + const NSAlphaShiftKeyMask = 1 << 16; + const NSShiftKeyMask = 1 << 17; + const NSControlKeyMask = 1 << 18; + const NSAlternateKeyMask = 1 << 19; + const NSCommandKeyMask = 1 << 20; + const NSNumericPadKeyMask = 1 << 21; + const NSHelpKeyMask = 1 << 22; + const NSFunctionKeyMask = 1 << 23; + const NSDeviceIndependentModifierFlagsMask = 0xffff0000; + } +} + +// Not sure of the type here +pub enum NSPointingDeviceType { + // TODO: Not sure what these values are + // NSUnknownPointingDevice = NX_TABLET_POINTER_UNKNOWN, + // NSPenPointingDevice = NX_TABLET_POINTER_PEN, + // NSCursorPointingDevice = NX_TABLET_POINTER_CURSOR, + // NSEraserPointingDevice = NX_TABLET_POINTER_ERASER, +} + +// Not sure of the type here +pub enum NSEventButtonMask { + // TODO: Not sure what these values are + // NSPenTipMask = NX_TABLET_BUTTON_PENTIPMASK, + // NSPenLowerSideMask = NX_TABLET_BUTTON_PENLOWERSIDEMASK, + // NSPenUpperSideMask = NX_TABLET_BUTTON_PENUPPERSIDEMASK, +} + +#[repr(i16)] +pub enum NSEventSubtype { + // TODO: Not sure what these values are + // NSMouseEventSubtype = NX_SUBTYPE_DEFAULT, + // NSTabletPointEventSubtype = NX_SUBTYPE_TABLET_POINT, + // NSTabletProximityEventSubtype = NX_SUBTYPE_TABLET_PROXIMITY + // NSTouchEventSubtype = NX_SUBTYPE_MOUSE_TOUCH, + NSWindowExposedEventType = 0, + NSApplicationActivatedEventType = 1, + NSApplicationDeactivatedEventType = 2, + NSWindowMovedEventType = 4, + NSScreenChangedEventType = 8, + NSAWTEventType = 16, +} + +pub const NSUpArrowFunctionKey: libc::c_ushort = 0xF700; +pub const NSDownArrowFunctionKey: libc::c_ushort = 0xF701; +pub const NSLeftArrowFunctionKey: libc::c_ushort = 0xF702; +pub const NSRightArrowFunctionKey: libc::c_ushort = 0xF703; +pub const NSF1FunctionKey: libc::c_ushort = 0xF704; +pub const NSF2FunctionKey: libc::c_ushort = 0xF705; +pub const NSF3FunctionKey: libc::c_ushort = 0xF706; +pub const NSF4FunctionKey: libc::c_ushort = 0xF707; +pub const NSF5FunctionKey: libc::c_ushort = 0xF708; +pub const NSF6FunctionKey: libc::c_ushort = 0xF709; +pub const NSF7FunctionKey: libc::c_ushort = 0xF70A; +pub const NSF8FunctionKey: libc::c_ushort = 0xF70B; +pub const NSF9FunctionKey: libc::c_ushort = 0xF70C; +pub const NSF10FunctionKey: libc::c_ushort = 0xF70D; +pub const NSF11FunctionKey: libc::c_ushort = 0xF70E; +pub const NSF12FunctionKey: libc::c_ushort = 0xF70F; +pub const NSF13FunctionKey: libc::c_ushort = 0xF710; +pub const NSF14FunctionKey: libc::c_ushort = 0xF711; +pub const NSF15FunctionKey: libc::c_ushort = 0xF712; +pub const NSF16FunctionKey: libc::c_ushort = 0xF713; +pub const NSF17FunctionKey: libc::c_ushort = 0xF714; +pub const NSF18FunctionKey: libc::c_ushort = 0xF715; +pub const NSF19FunctionKey: libc::c_ushort = 0xF716; +pub const NSF20FunctionKey: libc::c_ushort = 0xF717; +pub const NSF21FunctionKey: libc::c_ushort = 0xF718; +pub const NSF22FunctionKey: libc::c_ushort = 0xF719; +pub const NSF23FunctionKey: libc::c_ushort = 0xF71A; +pub const NSF24FunctionKey: libc::c_ushort = 0xF71B; +pub const NSF25FunctionKey: libc::c_ushort = 0xF71C; +pub const NSF26FunctionKey: libc::c_ushort = 0xF71D; +pub const NSF27FunctionKey: libc::c_ushort = 0xF71E; +pub const NSF28FunctionKey: libc::c_ushort = 0xF71F; +pub const NSF29FunctionKey: libc::c_ushort = 0xF720; +pub const NSF30FunctionKey: libc::c_ushort = 0xF721; +pub const NSF31FunctionKey: libc::c_ushort = 0xF722; +pub const NSF32FunctionKey: libc::c_ushort = 0xF723; +pub const NSF33FunctionKey: libc::c_ushort = 0xF724; +pub const NSF34FunctionKey: libc::c_ushort = 0xF725; +pub const NSF35FunctionKey: libc::c_ushort = 0xF726; +pub const NSInsertFunctionKey: libc::c_ushort = 0xF727; +pub const NSDeleteFunctionKey: libc::c_ushort = 0xF728; +pub const NSHomeFunctionKey: libc::c_ushort = 0xF729; +pub const NSBeginFunctionKey: libc::c_ushort = 0xF72A; +pub const NSEndFunctionKey: libc::c_ushort = 0xF72B; +pub const NSPageUpFunctionKey: libc::c_ushort = 0xF72C; +pub const NSPageDownFunctionKey: libc::c_ushort = 0xF72D; +pub const NSPrintScreenFunctionKey: libc::c_ushort = 0xF72E; +pub const NSScrollLockFunctionKey: libc::c_ushort = 0xF72F; +pub const NSPauseFunctionKey: libc::c_ushort = 0xF730; +pub const NSSysReqFunctionKey: libc::c_ushort = 0xF731; +pub const NSBreakFunctionKey: libc::c_ushort = 0xF732; +pub const NSResetFunctionKey: libc::c_ushort = 0xF733; +pub const NSStopFunctionKey: libc::c_ushort = 0xF734; +pub const NSMenuFunctionKey: libc::c_ushort = 0xF735; +pub const NSUserFunctionKey: libc::c_ushort = 0xF736; +pub const NSSystemFunctionKey: libc::c_ushort = 0xF737; +pub const NSPrintFunctionKey: libc::c_ushort = 0xF738; +pub const NSClearLineFunctionKey: libc::c_ushort = 0xF739; +pub const NSClearDisplayFunctionKey: libc::c_ushort = 0xF73A; +pub const NSInsertLineFunctionKey: libc::c_ushort = 0xF73B; +pub const NSDeleteLineFunctionKey: libc::c_ushort = 0xF73C; +pub const NSInsertCharFunctionKey: libc::c_ushort = 0xF73D; +pub const NSDeleteCharFunctionKey: libc::c_ushort = 0xF73E; +pub const NSPrevFunctionKey: libc::c_ushort = 0xF73F; +pub const NSNextFunctionKey: libc::c_ushort = 0xF740; +pub const NSSelectFunctionKey: libc::c_ushort = 0xF741; +pub const NSExecuteFunctionKey: libc::c_ushort = 0xF742; +pub const NSUndoFunctionKey: libc::c_ushort = 0xF743; +pub const NSRedoFunctionKey: libc::c_ushort = 0xF744; +pub const NSFindFunctionKey: libc::c_ushort = 0xF745; +pub const NSHelpFunctionKey: libc::c_ushort = 0xF746; +pub const NSModeSwitchFunctionKey: libc::c_ushort = 0xF747; + +pub trait NSEvent: Sized { + // Creating Events + unsafe fn keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + characters: id /* (NSString *) */, + unmodCharacters: id /* (NSString *) */, + repeatKey: BOOL, + code: libc::c_ushort) -> id /* (NSEvent *) */; + unsafe fn mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + eventNumber: NSInteger, + clickCount: NSInteger, + pressure: libc::c_float) -> id /* (NSEvent *) */; + unsafe fn enterExitEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_trackingNumber_userData_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + eventNumber: NSInteger, + trackingNumber: NSInteger, + userData: *mut c_void) -> id /* (NSEvent *) */; + unsafe fn otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + subtype: NSEventSubtype, + data1: NSInteger, + data2: NSInteger) -> id /* (NSEvent *) */; + unsafe fn eventWithEventRef_(_: Self, eventRef: *const c_void) -> id; + unsafe fn eventWithCGEvent_(_: Self, cgEvent: *mut c_void /* CGEventRef */) -> id; + + // Getting General Event Information + unsafe fn context(self) -> id /* (NSGraphicsContext *) */; + unsafe fn locationInWindow(self) -> NSPoint; + unsafe fn modifierFlags(self) -> NSEventModifierFlags; + unsafe fn timestamp(self) -> NSTimeInterval; + // NOTE: renamed from `- type` due to Rust keyword collision + unsafe fn eventType(self) -> NSEventType; + unsafe fn window(self) -> id /* (NSWindow *) */; + unsafe fn windowNumber(self) -> NSInteger; + unsafe fn eventRef(self) -> *const c_void; + unsafe fn CGEvent(self) -> *mut c_void /* CGEventRef */; + + // Getting Key Event Information + // NOTE: renamed from `+ modifierFlags` due to conflict with `- modifierFlags` + unsafe fn currentModifierFlags(_: Self) -> NSEventModifierFlags; + unsafe fn keyRepeatDelay(_: Self) -> NSTimeInterval; + unsafe fn keyRepeatInterval(_: Self) -> NSTimeInterval; + unsafe fn characters(self) -> id /* (NSString *) */; + unsafe fn charactersIgnoringModifiers(self) -> id /* (NSString *) */; + unsafe fn keyCode(self) -> libc::c_ushort; + unsafe fn isARepeat(self) -> BOOL; + + // Getting Mouse Event Information + unsafe fn pressedMouseButtons(_: Self) -> NSUInteger; + unsafe fn doubleClickInterval(_: Self) -> NSTimeInterval; + unsafe fn mouseLocation(_: Self) -> NSPoint; + unsafe fn buttonNumber(self) -> NSInteger; + unsafe fn clickCount(self) -> NSInteger; + unsafe fn pressure(self) -> libc::c_float; + unsafe fn stage(self) -> NSInteger; + unsafe fn setMouseCoalescingEnabled_(_: Self, flag: BOOL); + unsafe fn isMouseCoalescingEnabled(_: Self) -> BOOL; + + // Getting Mouse-Tracking Event Information + unsafe fn eventNumber(self) -> NSInteger; + unsafe fn trackingNumber(self) -> NSInteger; + unsafe fn trackingArea(self) -> id /* (NSTrackingArea *) */; + unsafe fn userData(self) -> *const c_void; + + // Getting Custom Event Information + unsafe fn data1(self) -> NSInteger; + unsafe fn data2(self) -> NSInteger; + unsafe fn subtype(self) -> NSEventSubtype; + + // Getting Scroll Wheel Event Information + unsafe fn deltaX(self) -> CGFloat; + unsafe fn deltaY(self) -> CGFloat; + unsafe fn deltaZ(self) -> CGFloat; + + // Getting Tablet Proximity Information + unsafe fn capabilityMask(self) -> NSUInteger; + unsafe fn deviceID(self) -> NSUInteger; + unsafe fn pointingDeviceID(self) -> NSUInteger; + unsafe fn pointingDeviceSerialNumber(self) -> NSUInteger; + unsafe fn pointingDeviceType(self) -> NSPointingDeviceType; + unsafe fn systemTabletID(self) -> NSUInteger; + unsafe fn tabletID(self) -> NSUInteger; + unsafe fn uniqueID(self) -> libc::c_ulonglong; + unsafe fn vendorID(self) -> NSUInteger; + unsafe fn vendorPointingDeviceType(self) -> NSUInteger; + + // Getting Tablet Pointing Information + unsafe fn absoluteX(self) -> NSInteger; + unsafe fn absoluteY(self) -> NSInteger; + unsafe fn absoluteZ(self) -> NSInteger; + unsafe fn buttonMask(self) -> NSEventButtonMask; + unsafe fn rotation(self) -> libc::c_float; + unsafe fn tangentialPressure(self) -> libc::c_float; + unsafe fn tilt(self) -> NSPoint; + unsafe fn vendorDefined(self) -> id; + + // Requesting and Stopping Periodic Events + unsafe fn startPeriodicEventsAfterDelay_withPeriod_(_: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval); + unsafe fn stopPeriodicEvents(_: Self); + + // Getting Touch and Gesture Information + unsafe fn magnification(self) -> CGFloat; + unsafe fn touchesMatchingPhase_inView_(self, phase: NSTouchPhase, view: id /* (NSView *) */) -> id /* (NSSet *) */; + unsafe fn isSwipeTrackingFromScrollEventsEnabled(_: Self) -> BOOL; + + // Monitoring Application Events + // TODO: addGlobalMonitorForEventsMatchingMask_handler_ (unsure how to bind to blocks) + // TODO: addLocalMonitorForEventsMatchingMask_handler_ (unsure how to bind to blocks) + unsafe fn removeMonitor_(_: Self, eventMonitor: id); + + // Scroll Wheel and Flick Events + unsafe fn hasPreciseScrollingDeltas(self) -> BOOL; + unsafe fn scrollingDeltaX(self) -> CGFloat; + unsafe fn scrollingDeltaY(self) -> CGFloat; + unsafe fn momentumPhase(self) -> NSEventPhase; + unsafe fn phase(self) -> NSEventPhase; + // TODO: trackSwipeEventWithOptions_dampenAmountThresholdMin_max_usingHandler_ (unsure how to bind to blocks) + + // Converting a Mouse Event’s Position into a Sprite Kit Node’s Coordinate Space + unsafe fn locationInNode_(self, node: id /* (SKNode *) */) -> CGPoint; +} + +impl NSEvent for id { + // Creating Events + + unsafe fn keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + characters: id /* (NSString *) */, + unmodCharacters: id /* (NSString *) */, + repeatKey: BOOL, + code: libc::c_ushort) -> id /* (NSEvent *) */ + { + msg_send![class!(NSEvent), keyEventWithType:eventType + location:location + modifierFlags:modifierFlags + timestamp:timestamp + windowNumber:windowNumber + context:context + characters:characters + charactersIgnoringModifiers:unmodCharacters + isARepeat:repeatKey + keyCode:code] + } + + unsafe fn mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + eventNumber: NSInteger, + clickCount: NSInteger, + pressure: libc::c_float) -> id /* (NSEvent *) */ + { + msg_send![class!(NSEvent), mouseEventWithType:eventType + location:location + modifierFlags:modifierFlags + timestamp:timestamp + windowNumber:windowNumber + context:context + eventNumber:eventNumber + clickCount:clickCount + pressure:pressure] + } + + unsafe fn enterExitEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_trackingNumber_userData_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + eventNumber: NSInteger, + trackingNumber: NSInteger, + userData: *mut c_void) -> id /* (NSEvent *) */ + { + msg_send![class!(NSEvent), enterExitEventWithType:eventType + location:location + modifierFlags:modifierFlags + timestamp:timestamp + windowNumber:windowNumber + context:context + eventNumber:eventNumber + trackingNumber:trackingNumber + userData:userData] + } + + unsafe fn otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( + _: Self, + eventType: NSEventType, + location: NSPoint, + modifierFlags: NSEventModifierFlags, + timestamp: NSTimeInterval, + windowNumber: NSInteger, + context: id /* (NSGraphicsContext *) */, + subtype: NSEventSubtype, + data1: NSInteger, + data2: NSInteger) -> id /* (NSEvent *) */ + { + msg_send![class!(NSEvent), otherEventWithType:eventType + location:location + modifierFlags:modifierFlags + timestamp:timestamp + windowNumber:windowNumber + context:context + subtype:subtype + data1:data1 + data2:data2] + } + + unsafe fn eventWithEventRef_(_: Self, eventRef: *const c_void) -> id { + msg_send![class!(NSEvent), eventWithEventRef:eventRef] + } + + unsafe fn eventWithCGEvent_(_: Self, cgEvent: *mut c_void /* CGEventRef */) -> id { + msg_send![class!(NSEvent), eventWithCGEvent:cgEvent] + } + + // Getting General Event Information + + unsafe fn context(self) -> id /* (NSGraphicsContext *) */ { + msg_send![self, context] + } + + unsafe fn locationInWindow(self) -> NSPoint { + msg_send![self, locationInWindow] + } + + unsafe fn modifierFlags(self) -> NSEventModifierFlags { + msg_send![self, modifierFlags] + } + + unsafe fn timestamp(self) -> NSTimeInterval { + msg_send![self, timestamp] + } + // NOTE: renamed from `- type` due to Rust keyword collision + + unsafe fn eventType(self) -> NSEventType { + msg_send![self, type] + } + + unsafe fn window(self) -> id /* (NSWindow *) */ { + msg_send![self, window] + } + + unsafe fn windowNumber(self) -> NSInteger { + msg_send![self, windowNumber] + } + + unsafe fn eventRef(self) -> *const c_void { + msg_send![self, eventRef] + } + + unsafe fn CGEvent(self) -> *mut c_void /* CGEventRef */ { + msg_send![self, CGEvent] + } + + // Getting Key Event Information + + // NOTE: renamed from `+ modifierFlags` due to conflict with `- modifierFlags` + + unsafe fn currentModifierFlags(_: Self) -> NSEventModifierFlags { + msg_send![class!(NSEvent), currentModifierFlags] + } + + unsafe fn keyRepeatDelay(_: Self) -> NSTimeInterval { + msg_send![class!(NSEvent), keyRepeatDelay] + } + + unsafe fn keyRepeatInterval(_: Self) -> NSTimeInterval { + msg_send![class!(NSEvent), keyRepeatInterval] + } + + unsafe fn characters(self) -> id /* (NSString *) */ { + msg_send![self, characters] + } + + unsafe fn charactersIgnoringModifiers(self) -> id /* (NSString *) */ { + msg_send![self, charactersIgnoringModifiers] + } + + unsafe fn keyCode(self) -> libc::c_ushort { + msg_send![self, keyCode] + } + + unsafe fn isARepeat(self) -> BOOL { + msg_send![self, isARepeat] + } + + // Getting Mouse Event Information + + unsafe fn pressedMouseButtons(_: Self) -> NSUInteger { + msg_send![class!(NSEvent), pressedMouseButtons] + } + + unsafe fn doubleClickInterval(_: Self) -> NSTimeInterval { + msg_send![class!(NSEvent), doubleClickInterval] + } + + unsafe fn mouseLocation(_: Self) -> NSPoint { + msg_send![class!(NSEvent), mouseLocation] + } + + unsafe fn buttonNumber(self) -> NSInteger { + msg_send![self, buttonNumber] + } + + unsafe fn clickCount(self) -> NSInteger { + msg_send![self, clickCount] + } + + unsafe fn pressure(self) -> libc::c_float { + msg_send![self, pressure] + } + + unsafe fn stage(self) -> NSInteger{ + msg_send![self, stage] + } + + unsafe fn setMouseCoalescingEnabled_(_: Self, flag: BOOL) { + msg_send![class!(NSEvent), setMouseCoalescingEnabled:flag] + } + + unsafe fn isMouseCoalescingEnabled(_: Self) -> BOOL { + msg_send![class!(NSEvent), isMouseCoalescingEnabled] + } + + // Getting Mouse-Tracking Event Information + + unsafe fn eventNumber(self) -> NSInteger { + msg_send![self, eventNumber] + } + + unsafe fn trackingNumber(self) -> NSInteger { + msg_send![self, trackingNumber] + } + + unsafe fn trackingArea(self) -> id /* (NSTrackingArea *) */ { + msg_send![self, trackingArea] + } + + unsafe fn userData(self) -> *const c_void { + msg_send![self, userData] + } + + // Getting Custom Event Information + + unsafe fn data1(self) -> NSInteger { + msg_send![self, data1] + } + + unsafe fn data2(self) -> NSInteger { + msg_send![self, data2] + } + + unsafe fn subtype(self) -> NSEventSubtype { + msg_send![self, subtype] + } + + // Getting Scroll Wheel Event Information + + unsafe fn deltaX(self) -> CGFloat { + msg_send![self, deltaX] + } + + unsafe fn deltaY(self) -> CGFloat { + msg_send![self, deltaY] + } + + unsafe fn deltaZ(self) -> CGFloat { + msg_send![self, deltaZ] + } + + // Getting Tablet Proximity Information + + unsafe fn capabilityMask(self) -> NSUInteger { + msg_send![self, capabilityMask] + } + + unsafe fn deviceID(self) -> NSUInteger { + msg_send![self, deviceID] + } + + unsafe fn pointingDeviceID(self) -> NSUInteger { + msg_send![self, pointingDeviceID] + } + + unsafe fn pointingDeviceSerialNumber(self) -> NSUInteger { + msg_send![self, pointingDeviceSerialNumber] + } + + unsafe fn pointingDeviceType(self) -> NSPointingDeviceType { + msg_send![self, pointingDeviceType] + } + + unsafe fn systemTabletID(self) -> NSUInteger { + msg_send![self, systemTabletID] + } + + unsafe fn tabletID(self) -> NSUInteger { + msg_send![self, tabletID] + } + + unsafe fn uniqueID(self) -> libc::c_ulonglong { + msg_send![self, uniqueID] + } + + unsafe fn vendorID(self) -> NSUInteger { + msg_send![self, vendorID] + } + + unsafe fn vendorPointingDeviceType(self) -> NSUInteger { + msg_send![self, vendorPointingDeviceType] + } + + // Getting Tablet Pointing Information + + unsafe fn absoluteX(self) -> NSInteger { + msg_send![self, absoluteX] + } + + unsafe fn absoluteY(self) -> NSInteger { + msg_send![self, absoluteY] + } + + unsafe fn absoluteZ(self) -> NSInteger { + msg_send![self, absoluteZ] + } + + unsafe fn buttonMask(self) -> NSEventButtonMask { + msg_send![self, buttonMask] + } + + unsafe fn rotation(self) -> libc::c_float { + msg_send![self, rotation] + } + + unsafe fn tangentialPressure(self) -> libc::c_float { + msg_send![self, tangentialPressure] + } + + unsafe fn tilt(self) -> NSPoint { + msg_send![self, tilt] + } + + unsafe fn vendorDefined(self) -> id { + msg_send![self, vendorDefined] + } + + // Requesting and Stopping Periodic Events + + unsafe fn startPeriodicEventsAfterDelay_withPeriod_(_: Self, delaySeconds: NSTimeInterval, periodSeconds: NSTimeInterval) { + msg_send![class!(NSEvent), startPeriodicEventsAfterDelay:delaySeconds withPeriod:periodSeconds] + } + + unsafe fn stopPeriodicEvents(_: Self) { + msg_send![class!(NSEvent), stopPeriodicEvents] + } + + // Getting Touch and Gesture Information + + unsafe fn magnification(self) -> CGFloat { + msg_send![self, magnification] + } + + unsafe fn touchesMatchingPhase_inView_(self, phase: NSTouchPhase, view: id /* (NSView *) */) -> id /* (NSSet *) */ { + msg_send![self, touchesMatchingPhase:phase inView:view] + } + + unsafe fn isSwipeTrackingFromScrollEventsEnabled(_: Self) -> BOOL { + msg_send![class!(NSEvent), isSwipeTrackingFromScrollEventsEnabled] + } + + // Monitoring Application Events + + // TODO: addGlobalMonitorForEventsMatchingMask_handler_ (unsure how to bind to blocks) + // TODO: addLocalMonitorForEventsMatchingMask_handler_ (unsure how to bind to blocks) + + unsafe fn removeMonitor_(_: Self, eventMonitor: id) { + msg_send![class!(NSEvent), removeMonitor:eventMonitor] + } + + // Scroll Wheel and Flick Events + + unsafe fn hasPreciseScrollingDeltas(self) -> BOOL { + msg_send![self, hasPreciseScrollingDeltas] + } + + unsafe fn scrollingDeltaX(self) -> CGFloat { + msg_send![self, scrollingDeltaX] + } + + unsafe fn scrollingDeltaY(self) -> CGFloat { + msg_send![self, scrollingDeltaY] + } + + unsafe fn momentumPhase(self) -> NSEventPhase { + msg_send![self, momentumPhase] + } + + unsafe fn phase(self) -> NSEventPhase { + msg_send![self, phase] + } + + // TODO: trackSwipeEventWithOptions_dampenAmountThresholdMin_max_usingHandler_ (unsure how to bind to blocks) + + // Converting a Mouse Event’s Position into a Sprite Kit Node’s Coordinate Space + unsafe fn locationInNode_(self, node: id /* (SKNode *) */) -> CGPoint { + msg_send![self, locationInNode:node] + } +} + +pub trait NSScreen: Sized { + // Getting NSScreen Objects + unsafe fn mainScreen(_: Self) -> id /* (NSScreen *) */; + unsafe fn deepestScreen(_: Self) -> id /* (NSScreen *) */; + unsafe fn screens(_: Self) -> id /* (NSArray *) */; + + // Getting Screen Information + unsafe fn depth(self) -> NSWindowDepth; + unsafe fn frame(self) -> NSRect; + unsafe fn supportedWindowDepths(self) -> *const NSWindowDepth; + unsafe fn deviceDescription(self) -> id /* (NSDictionary *) */; + unsafe fn visibleFrame(self) -> NSRect; + unsafe fn colorSpace(self) -> id /* (NSColorSpace *) */; + unsafe fn screensHaveSeparateSpaces(_: Self) -> BOOL; + + // Screen Backing Coordinate Conversion + unsafe fn backingAlignedRect_options_(self, aRect: NSRect, options: NSAlignmentOptions) -> NSRect; + unsafe fn backingScaleFactor(self) -> CGFloat; + unsafe fn convertRectFromBacking_(self, aRect: NSRect) -> NSRect; + unsafe fn convertRectToBacking_(self, aRect: NSRect) -> NSRect; +} + +impl NSScreen for id { + // Getting NSScreen Objects + + unsafe fn mainScreen(_: Self) -> id /* (NSScreen *) */ { + msg_send![class!(NSScreen), mainScreen] + } + + unsafe fn deepestScreen(_: Self) -> id /* (NSScreen *) */ { + msg_send![class!(NSScreen), deepestScreen] + } + + unsafe fn screens(_: Self) -> id /* (NSArray *) */ { + msg_send![class!(NSScreen), screens] + } + + // Getting Screen Information + + unsafe fn depth(self) -> NSWindowDepth { + msg_send![self, depth] + } + + unsafe fn frame(self) -> NSRect { + msg_send![self, frame] + } + + unsafe fn supportedWindowDepths(self) -> *const NSWindowDepth { + msg_send![self, supportedWindowDepths] + } + + unsafe fn deviceDescription(self) -> id /* (NSDictionary *) */ { + msg_send![self, deviceDescription] + } + + unsafe fn visibleFrame(self) -> NSRect { + msg_send![self, visibleFrame] + } + + unsafe fn colorSpace(self) -> id /* (NSColorSpace *) */ { + msg_send![self, colorSpace] + } + + unsafe fn screensHaveSeparateSpaces(_: Self) -> BOOL { + msg_send![class!(NSScreen), screensHaveSeparateSpaces] + } + + // Screen Backing Coordinate Conversion + + unsafe fn backingAlignedRect_options_(self, aRect: NSRect, options: NSAlignmentOptions) -> NSRect { + msg_send![self, backingAlignedRect:aRect options:options] + } + + unsafe fn backingScaleFactor(self) -> CGFloat { + msg_send![self, backingScaleFactor] + } + + unsafe fn convertRectFromBacking_(self, aRect: NSRect) -> NSRect { + msg_send![self, convertRectFromBacking:aRect] + } + + unsafe fn convertRectToBacking_(self, aRect: NSRect) -> NSRect { + msg_send![self, convertRectToBacking:aRect] + } +} + +// https://developer.apple.com/documentation/appkit/nscontrol?language=objc +pub trait NSControl: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSControl), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn isEnabled_(self) -> BOOL; + unsafe fn setEnabled_(self, enabled: BOOL) -> BOOL; +} + +impl NSControl for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn isEnabled_(self) -> BOOL { + msg_send![self, isEnabled] + } + unsafe fn setEnabled_(self, enabled: BOOL) -> BOOL { + msg_send![self, setEnabled:enabled] + } +} + +pub trait NSImageView: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSImageView), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setImage_(self, img: id /* (NSImage *) */); +} + +impl NSImageView for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn setImage_(self, img: id /* (NSImage *) */) { + msg_send![self, setImage:img] + } +} + +pub trait NSButton: Sized { + unsafe fn setImage_(self, img: id /* (NSImage *) */); + unsafe fn setBezelStyle_(self, style: NSBezelStyle); + unsafe fn setTitle_(self, title: id /* (NSString*) */); + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSButton), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setTarget_(self, target: id /* Instance */); + unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance *) */); +} + +impl NSButton for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn setBezelStyle_(self, style: NSBezelStyle) { + msg_send![self, setBezelStyle:style] + } + unsafe fn setTitle_(self, title: id /* (NSString*) */) { + msg_send![self, setTitle:title] + } + unsafe fn setImage_(self, img: id /* (NSImage *) */) { + msg_send![self, setImage:img] + } + unsafe fn setTarget_(self, target: id /* (Instance *) */) { + msg_send![self, setTarget:target] + } + + unsafe fn setAction_(self, selector: objc::runtime::Sel /* (Instance method *) */) { + msg_send![self, setAction:selector] + } +} + +pub trait NSImage: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSImage), alloc] + } + + unsafe fn initByReferencingFile_(self, file_name: id /* (NSString *) */) -> id; + unsafe fn initWithContentsOfFile_(self, file_name: id /* (NSString *) */) -> id; + unsafe fn initWithData_(self, data: id /* (NSData *) */) -> id; + unsafe fn initWithDataIgnoringOrientation_(self, data: id /* (NSData *) */) -> id; + unsafe fn initWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> id; + unsafe fn initWithSize_flipped_drawingHandler_(self, size: NSSize, + drawingHandlerShouldBeCalledWithFlippedContext: BOOL, + drawingHandler: *mut Block<(NSRect,), BOOL>); + unsafe fn initWithSize_(self, aSize: NSSize) -> id; + + unsafe fn imageNamed_(_: Self, name: id /* (NSString *) */) -> id { + msg_send![class!(NSImage), imageNamed:name] + } + + unsafe fn name(self) -> id /* (NSString *) */; + unsafe fn setName_(self, name: id /* (NSString *) */) -> BOOL; + + unsafe fn size(self) -> NSSize; + unsafe fn template(self) -> BOOL; + + unsafe fn canInitWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> BOOL; + unsafe fn imageTypes(self) -> id /* (NSArray ) */; + unsafe fn imageUnfilteredTypes(self) -> id /* (NSArray ) */; + + unsafe fn addRepresentation_(self, imageRep: id /* (NSImageRep *) */); + unsafe fn addRepresentations_(self, imageReps: id /* (NSArray *) */); + unsafe fn representations(self) -> id /* (NSArray *) */; + unsafe fn removeRepresentation_(self, imageRep: id /* (NSImageRep *) */); + unsafe fn bestRepresentationForRect_context_hints_(self, rect: NSRect, + referenceContext: id /* (NSGraphicsContext *) */, + hints: id /* (NSDictionary *) */) + -> id /* (NSImageRep *) */; + unsafe fn prefersColorMatch(self) -> BOOL; + unsafe fn usesEPSOnResolutionMismatch(self) -> BOOL; + unsafe fn matchesOnMultipleResolution(self) -> BOOL; + + unsafe fn drawInRect_(self, rect: NSRect); + unsafe fn drawAtPoint_fromRect_operation_fraction_(self, point: NSPoint, srcRect: NSRect, + op: NSCompositingOperation, delta: CGFloat); + unsafe fn drawInRect_fromRect_operation_fraction_(self, dstRect: NSRect, srcRect: NSRect, + op: NSCompositingOperation, delta: CGFloat); + unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_(self, dstSpacePortionRect: NSRect, + srcSpacePortionRect: NSRect, op: NSCompositingOperation, delta: CGFloat, respectContextIsFlipped: BOOL, + hints: id /* (NSDictionary *) */); + unsafe fn drawRepresentation_inRect_(self, imageRep: id /* (NSImageRep *) */, dstRect: NSRect); + + unsafe fn isValid(self) -> BOOL; + unsafe fn backgroundColor(self) -> id /* (NSColor *) */; + + unsafe fn lockFocus(self); + unsafe fn lockFocusFlipped_(self, flipped: BOOL); + unsafe fn unlockFocus(self); + + unsafe fn alignmentRect(self) -> NSRect; + + unsafe fn cacheMode(self) -> NSImageCacheMode; + unsafe fn recache(self); + + unsafe fn delegate(self) -> id /* (id *) */; + + unsafe fn TIFFRepresentation(self) -> id /* (NSData *) */; + unsafe fn TIFFRepresentationUsingCompression_factor_(self, comp: NSTIFFCompression, aFloat: f32) + -> id /* (NSData *) */; + + unsafe fn cancelIncrementalLoad(self); + + unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_(self, testRectDestSpace: NSRect, + imageRectDestSpace: NSRect, referenceContext: id /* (NSGraphicsContext *) */, + hints: id /* (NSDictionary *) */, flipped: BOOL) -> BOOL; + + unsafe fn accessibilityDescription(self) -> id /* (NSString *) */; + + unsafe fn layerContentsForContentsScale_(self, layerContentsScale: CGFloat) -> id /* (id) */; + unsafe fn recommendedLayerContentsScale_(self, preferredContentsScale: CGFloat) -> CGFloat; + + unsafe fn matchesOnlyOnBestFittingAxis(self) -> BOOL; +} + +impl NSImage for id { + unsafe fn initByReferencingFile_(self, file_name: id /* (NSString *) */) -> id { + msg_send![self, initByReferencingFile:file_name] + } + + unsafe fn initWithContentsOfFile_(self, file_name: id /* (NSString *) */) -> id { + msg_send![self, initWithContentsOfFile:file_name] + } + + unsafe fn initWithData_(self, data: id /* (NSData *) */) -> id { + msg_send![self, initWithData:data] + } + + unsafe fn initWithDataIgnoringOrientation_(self, data: id /* (NSData *) */) -> id { + msg_send![self, initWithDataIgnoringOrientation:data] + } + + unsafe fn initWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> id { + msg_send![self, initWithPasteboard:pasteboard] + } + + unsafe fn initWithSize_flipped_drawingHandler_(self, size: NSSize, + drawingHandlerShouldBeCalledWithFlippedContext: BOOL, + drawingHandler: *mut Block<(NSRect,), BOOL>) { + msg_send![self, initWithSize:size + flipped:drawingHandlerShouldBeCalledWithFlippedContext + drawingHandler:drawingHandler] + } + + unsafe fn initWithSize_(self, aSize: NSSize) -> id { + msg_send![self, initWithSize:aSize] + } + + unsafe fn name(self) -> id /* (NSString *) */ { + msg_send![self, name] + } + + unsafe fn setName_(self, name: id /* (NSString *) */) -> BOOL { + msg_send![self, setName:name] + } + + unsafe fn size(self) -> NSSize { + msg_send![self, size] + } + + unsafe fn template(self) -> BOOL { + msg_send![self, template] + } + + unsafe fn canInitWithPasteboard_(self, pasteboard: id /* (NSPasteboard *) */) -> BOOL { + msg_send![self, canInitWithPasteboard:pasteboard] + } + + unsafe fn imageTypes(self) -> id /* (NSArray ) */ { + msg_send![self, imageTypes] + } + + unsafe fn imageUnfilteredTypes(self) -> id /* (NSArray ) */ { + msg_send![self, imageUnfilteredTypes] + } + + unsafe fn addRepresentation_(self, imageRep: id /* (NSImageRep *) */) { + msg_send![self, addRepresentation:imageRep] + } + + unsafe fn addRepresentations_(self, imageReps: id /* (NSArray *) */) { + msg_send![self, addRepresentations:imageReps] + } + + unsafe fn representations(self) -> id /* (NSArray *) */ { + msg_send![self, representations] + } + + unsafe fn removeRepresentation_(self, imageRep: id /* (NSImageRep *) */) { + msg_send![self, removeRepresentation:imageRep] + } + + unsafe fn bestRepresentationForRect_context_hints_(self, rect: NSRect, + referenceContext: id /* (NSGraphicsContext *) */, + hints: id /* (NSDictionary *) */) + -> id /* (NSImageRep *) */ { + msg_send![self, bestRepresentationForRect:rect context:referenceContext hints:hints] + } + + unsafe fn prefersColorMatch(self) -> BOOL { + msg_send![self, prefersColorMatch] + } + + unsafe fn usesEPSOnResolutionMismatch(self) -> BOOL { + msg_send![self, usesEPSOnResolutionMismatch] + } + + unsafe fn matchesOnMultipleResolution(self) -> BOOL { + msg_send![self, matchesOnMultipleResolution] + } + + unsafe fn drawInRect_(self, rect: NSRect) { + msg_send![self, drawInRect:rect] + } + + unsafe fn drawAtPoint_fromRect_operation_fraction_(self, point: NSPoint, srcRect: NSRect, + op: NSCompositingOperation, delta: CGFloat) { + msg_send![self, drawAtPoint:point fromRect:srcRect operation:op fraction:delta] + } + + unsafe fn drawInRect_fromRect_operation_fraction_(self, dstRect: NSRect, srcRect: NSRect, + op: NSCompositingOperation, delta: CGFloat) { + msg_send![self, drawInRect:dstRect fromRect:srcRect operation:op fraction:delta] + } + + unsafe fn drawInRect_fromRect_operation_fraction_respectFlipped_hints_(self, dstSpacePortionRect: NSRect, + srcSpacePortionRect: NSRect, op: NSCompositingOperation, delta: CGFloat, respectContextIsFlipped: BOOL, + hints: id /* (NSDictionary *) */) { + msg_send![self, drawInRect:dstSpacePortionRect + fromRect:srcSpacePortionRect + operation:op + fraction:delta + respectFlipped:respectContextIsFlipped + hints:hints] + } + + unsafe fn drawRepresentation_inRect_(self, imageRep: id /* (NSImageRep *) */, dstRect: NSRect) { + msg_send![self, drawRepresentation:imageRep inRect:dstRect] + } + + unsafe fn isValid(self) -> BOOL { + msg_send![self, isValid] + } + + unsafe fn backgroundColor(self) -> id /* (NSColor *) */ { + msg_send![self, backgroundColor] + } + + unsafe fn lockFocus(self) { + msg_send![self, lockFocus] + } + + unsafe fn lockFocusFlipped_(self, flipped: BOOL) { + msg_send![self, lockFocusFlipped:flipped] + } + + unsafe fn unlockFocus(self) { + msg_send![self, unlockFocus] + } + + unsafe fn alignmentRect(self) -> NSRect { + msg_send![self, alignmentRect] + } + + unsafe fn cacheMode(self) -> NSImageCacheMode { + msg_send![self, cacheMode] + } + + unsafe fn recache(self) { + msg_send![self, recache] + } + + unsafe fn delegate(self) -> id /* (id *) */ { + msg_send![self, delegate] + } + + unsafe fn TIFFRepresentation(self) -> id /* (NSData *) */ { + msg_send![self, TIFFRepresentation] + } + + unsafe fn TIFFRepresentationUsingCompression_factor_(self, comp: NSTIFFCompression, aFloat: f32) + -> id /* (NSData *) */ { + msg_send![self, TIFFRepresentationUsingCompression:comp factor:aFloat] + } + + unsafe fn cancelIncrementalLoad(self) { + msg_send![self, cancelIncrementalLoad] + } + + unsafe fn hitTestRect_withImageDestinationRect_context_hints_flipped_(self, testRectDestSpace: NSRect, + imageRectDestSpace: NSRect, referenceContext: id /* (NSGraphicsContext *) */, + hints: id /* (NSDictionary *) */, flipped: BOOL) -> BOOL { + msg_send![self, hitTestRect:testRectDestSpace + withImageDestinationRect:imageRectDestSpace + context:referenceContext + hints:hints + flipped:flipped] + } + + unsafe fn accessibilityDescription(self) -> id /* (NSString *) */ { + msg_send![self, accessibilityDescription] + } + + unsafe fn layerContentsForContentsScale_(self, layerContentsScale: CGFloat) -> id /* (id) */ { + msg_send![self, layerContentsForContentsScale:layerContentsScale] + } + + unsafe fn recommendedLayerContentsScale_(self, preferredContentsScale: CGFloat) -> CGFloat { + msg_send![self, recommendedLayerContentsScale:preferredContentsScale] + } + + unsafe fn matchesOnlyOnBestFittingAxis(self) -> BOOL { + msg_send![self, matchesOnlyOnBestFittingAxis] + } +} + +#[link(name = "AppKit", kind = "framework")] +extern { + // Image hints (NSString* const) + pub static NSImageHintCTM: id; + pub static NSImageHintInterpolation: id; + + // System image names (NSString const*) + pub static NSImageNameQuickLookTemplate: id; + pub static NSImageNameBluetoothTemplate: id; + pub static NSImageNameIChatTheaterTemplate: id; + pub static NSImageNameSlideshowTemplate: id; + pub static NSImageNameActionTemplate: id; + pub static NSImageNameSmartBadgeTemplate: id; + pub static NSImageNamePathTemplate: id; + pub static NSImageNameInvalidDataFreestandingTemplate: id; + pub static NSImageNameLockLockedTemplate: id; + pub static NSImageNameLockUnlockedTemplate: id; + pub static NSImageNameGoRightTemplate: id; + pub static NSImageNameGoLeftTemplate: id; + pub static NSImageNameRightFacingTriangleTemplate: id; + pub static NSImageNameLeftFacingTriangleTemplate: id; + pub static NSImageNameAddTemplate: id; + pub static NSImageNameRemoveTemplate: id; + pub static NSImageNameRevealFreestandingTemplate: id; + pub static NSImageNameFollowLinkFreestandingTemplate: id; + pub static NSImageNameEnterFullScreenTemplate: id; + pub static NSImageNameExitFullScreenTemplate: id; + pub static NSImageNameStopProgressTemplate: id; + pub static NSImageNameStopProgressFreestandingTemplate: id; + pub static NSImageNameRefreshTemplate: id; + pub static NSImageNameRefreshFreestandingTemplate: id; + + pub static NSImageNameMultipleDocuments: id; + + pub static NSImageNameUser: id; + pub static NSImageNameUserGroup: id; + pub static NSImageNameEveryone: id; + pub static NSImageNameUserGuest: id; + + pub static NSImageNameBonjour: id; + pub static NSImageNameDotMac: id; + pub static NSImageNameComputer: id; + pub static NSImageNameFolderBurnable: id; + pub static NSImageNameFolderSmart: id; + pub static NSImageNameNetwork: id; + + pub static NSImageNameUserAccounts: id; + pub static NSImageNamePreferencesGeneral: id; + pub static NSImageNameAdvanced: id; + pub static NSImageNameInfo: id; + pub static NSImageNameFontPanel: id; + pub static NSImageNameColorPanel: id; + pub static NSImageNameFolder: id; + pub static NSImageNameTrashEmpty: id; + pub static NSImageNameTrashFull: id; + pub static NSImageNameHomeTemplate: id; + pub static NSImageNameBookmarksTemplate: id; + pub static NSImageNameCaution: id; + pub static NSImageNameStatusAvailable: id; + pub static NSImageNameStatusPartiallyAvailable: id; + pub static NSImageNameStatusUnavailable: id; + pub static NSImageNameStatusNone: id; + pub static NSImageNameApplicationIcon: id; + pub static NSImageNameMenuOnStateTemplate: id; + pub static NSImageNameMenuMixedStateTemplate: id; + pub static NSImageNameMobileMe: id; + + pub static NSImageNameIconViewTemplate: id; + pub static NSImageNameListViewTemplate: id; + pub static NSImageNameColumnViewTemplate: id; + pub static NSImageNameFlowViewTemplate: id; + pub static NSImageNameShareTemplate: id; +} + +#[repr(usize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NSCompositingOperation { + NSCompositeClear = 0, + NSCompositeCopy = 1, + NSCompositeSourceOver = 2, + NSCompositeSourceIn = 3, + NSCompositeSourceOut = 4, + NSCompositeSourceAtop = 5, + NSCompositeDestinationOver = 6, + NSCompositeDestinationIn = 7, + NSCompositeDestinationOut = 8, + NSCompositeDestinationAtop = 9, + NSCompositeXOR = 10, + NSCompositePlusDarker = 11, + NSCompositeHighlight = 12, + NSCompositePlusLighter = 13 +} + +#[repr(usize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NSImageCacheMode { + NSImageCacheDefault, + NSImageCacheAlways, + NSImageCacheBySize, + NSImageCacheNever +} + +#[repr(usize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NSTIFFCompression { + NSTIFFCompressionNone = 1, + NSTIFFCompressionCCITTFAX3 = 3, + NSTIFFCompressionCCITTFAX4 = 4, + NSTIFFCompressionLZW = 5, + NSTIFFCompressionJPEG = 6, + NSTIFFCompressionNEXT = 32766, + NSTIFFCompressionPackBits = 32773, + NSTIFFCompressionOldJPEG = 32865 +} + +#[repr(usize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NSImageLoadStatus { + NSImageLoadStatusCompleted, + NSImageLoadStatusCancelled, + NSImageLoadStatusInvalidData, + NSImageLoadStatusUnexpectedEOF, + NSImageLoadStatusReadError +} + +pub trait NSSound: Sized { + unsafe fn canInitWithPasteboard_(_: Self, pasteboard: id) -> BOOL { + msg_send![class!(NSSound), canInitWithPasteboard:pasteboard] + } + + unsafe fn initWithContentsOfFile_withReference_(self, filepath: id, byRef: BOOL) -> id; + unsafe fn initWithContentsOfURL_withReference_(self, fileUrl: id, byRef: BOOL) -> id; + unsafe fn initWithData_(self, audioData: id) -> id; + unsafe fn initWithPasteboard_(self, pasteboard: id) -> id; + + unsafe fn name(self) -> id; + unsafe fn volume(self) -> f32; + unsafe fn currentTime(self) -> NSTimeInterval; + unsafe fn loops(self) -> BOOL; + unsafe fn playbackDeviceIdentifier(self) -> id; + unsafe fn delegate(self) -> id; + + unsafe fn soundUnfilteredTypes(_: Self) -> id { + msg_send![class!(NSSound), soundUnfilteredTypes] + } + + unsafe fn soundNamed_(_: Self, soundName: id) -> id { + msg_send![class!(NSSound), soundNamed:soundName] + } + + unsafe fn duration(self) -> NSTimeInterval; + + unsafe fn playing(self) -> BOOL; + unsafe fn pause(self) -> BOOL; + unsafe fn play(self) -> BOOL; + unsafe fn resume(self) -> BOOL; + unsafe fn stop(self) -> BOOL; + + unsafe fn writeToPasteboard_(self, pasteboard: id); +} + +impl NSSound for id { + unsafe fn initWithContentsOfFile_withReference_(self, filepath: id, byRef: BOOL) -> id { + msg_send![self, initWithContentsOfFile:filepath withReference:byRef] + } + + unsafe fn initWithContentsOfURL_withReference_(self, fileUrl: id, byRef: BOOL) -> id { + msg_send![self, initWithContentsOfURL:fileUrl withReference:byRef] + } + + unsafe fn initWithData_(self, audioData: id) -> id { + msg_send![self, initWithData:audioData] + } + + unsafe fn initWithPasteboard_(self, pasteboard: id) -> id { + msg_send![self, initWithPasteboard:pasteboard] + } + + unsafe fn name(self) -> id { + msg_send![self, name] + } + + unsafe fn volume(self) -> f32 { + msg_send![self, volume] + } + + unsafe fn currentTime(self) -> NSTimeInterval { + msg_send![self, currentTime] + } + + unsafe fn loops(self) -> BOOL { + msg_send![self, loops] + } + + unsafe fn playbackDeviceIdentifier(self) -> id { + msg_send![self, playbackDeviceIdentifier] + } + + unsafe fn delegate(self) -> id { + msg_send![self, delegate] + } + + unsafe fn duration(self) -> NSTimeInterval { + msg_send![self, duration] + } + + unsafe fn playing(self) -> BOOL { + msg_send![self, playing] + } + + unsafe fn pause(self) -> BOOL { + msg_send![self, pause] + } + + unsafe fn play(self) -> BOOL { + msg_send![self, play] + } + + unsafe fn resume(self) -> BOOL { + msg_send![self, resume] + } + + unsafe fn stop(self) -> BOOL { + msg_send![self, stop] + } + + unsafe fn writeToPasteboard_(self, pasteboard: id) { + msg_send![self, writeToPasteboard:pasteboard] + } +} + +pub const NSVariableStatusItemLength: CGFloat = -1.0; +pub const NSSquareStatusItemLength: CGFloat = -2.0; + +pub trait NSStatusItem: Sized { + unsafe fn statusBar(self) -> id /* (NSStatusBar *) */; + unsafe fn button(self) -> id /* (NSStatusBarButton *) */; + unsafe fn menu(self) -> id; + unsafe fn setMenu_(self, menu: id); + unsafe fn length(self) -> CGFloat; + unsafe fn setLength_(self, length: CGFloat); +} + +impl NSStatusItem for id { + unsafe fn statusBar(self) -> id /* (NSStatusBar *) */ { + msg_send![self, statusBar] + } + + unsafe fn button(self) -> id /* (NSStatusBarButton *) */ { + msg_send![self, button] + } + + unsafe fn menu(self) -> id { + msg_send![self, menu] + } + + unsafe fn setMenu_(self, menu: id) { + msg_send![self, setMenu:menu] + } + + unsafe fn length(self) -> CGFloat { + msg_send![self, length] + } + + unsafe fn setLength_(self, length: CGFloat) { + msg_send![self, setLength: length] + } +} + +pub trait NSStatusBar: Sized { + unsafe fn systemStatusBar(_: Self) -> id { + msg_send![class!(NSStatusBar), systemStatusBar] + } + + unsafe fn statusItemWithLength_(self, length: CGFloat) -> id /* (NSStatusItem *) */; + unsafe fn removeStatusItem_(self, item: id /* (NSStatusItem *) */); + unsafe fn isVertical(self) -> BOOL; +} + +impl NSStatusBar for id { + unsafe fn statusItemWithLength_(self, length: CGFloat) -> id /* (NSStatusItem *) */ { + msg_send![self, statusItemWithLength:length] + } + + unsafe fn removeStatusItem_(self, item: id /* (NSStatusItem *) */) { + msg_send![self, removeStatusItem:item] + } + + unsafe fn isVertical(self) -> BOOL { + msg_send![self, isVertical] + } +} + +extern { + pub fn NSRectFill(rect: NSRect); +} + +pub trait NSTextField: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSTextField), alloc] + } + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn setEditable_(self, editable: BOOL); + unsafe fn setStringValue_(self, label: id /* NSString */); +} + +impl NSTextField for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + unsafe fn setEditable_(self, editable: BOOL) { + msg_send![self, setEditable:editable] + } + unsafe fn setStringValue_(self, label: id) { + msg_send![self, setStringValue:label] + } +} + +#[repr(u64)] +pub enum NSTabViewType { + NSTopTabsBezelBorder = 0, + NSLeftTabsBezelBorder = 1, + NSBottomTabsBezelBorder = 2, + NSRightTabsBezelBorder = 3, + NSNoTabsBezelBorder = 4, + NSNoTabsLineBorder = 5, + NSNoTabsNoBorder = 6 +} + +pub trait NSTabView: Sized { + unsafe fn new(_: Self) -> id { + msg_send![class!(NSTabView), new] + } + + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id; + unsafe fn addTabViewItem_(self, tabViewItem: id); + unsafe fn insertTabViewItem_atIndex_(self,tabViewItem:id, index:NSInteger); + unsafe fn removeTabViewItem_(self,tabViewItem:id); + unsafe fn indexOfTabViewItem_(self, tabViewItem:id) -> id; + unsafe fn indexOfTabViewItemWithIdentifier_(self,identifier:id) -> id; + unsafe fn numberOfTabViewItems(self) -> id; + unsafe fn tabViewItemAtIndex_(self,index:id) -> id; + unsafe fn tabViewItems(self) -> id; + unsafe fn selectFirstTabViewItem_(self,sender:id); + unsafe fn selectLastTabViewItem_(self,sender:id); + unsafe fn selectNextTabViewItem_(self, sender:id); + unsafe fn selectPreviousTabViewItem_(self,sender:id); + unsafe fn selectTabViewItem_(self,tabViewItem:id); + unsafe fn selectTabViewItemAtIndex_(self,index:id); + unsafe fn selectTabViewItemWithIdentifier_(self,identifier:id); + unsafe fn selectedTabViewItem(self) -> id; + unsafe fn takeSelectedTabViewItemFromSender_(self,sender:id); + unsafe fn font(self) -> id; + unsafe fn setFont_(self, font:id); + unsafe fn tabViewType(self) -> NSTabViewType; + unsafe fn setTabViewType_(self,tabViewType: NSTabViewType); + unsafe fn controlTint(self) -> id; + unsafe fn setControlTint_(self,controlTint:id); + unsafe fn drawsBackground(self) -> BOOL; + unsafe fn setDrawsBackground_(self,drawsBackground:BOOL); + unsafe fn minimumSize(self) -> id; + unsafe fn contentRect(self) -> id; + unsafe fn controlSize(self) -> id; + unsafe fn setControlSize_(self,controlSize:id); + unsafe fn allowsTruncatedLabels(self) -> BOOL; + unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels:BOOL); + unsafe fn setDelegate_(self, delegate:id); + unsafe fn delegate(self) -> id ; + unsafe fn tabViewAtPoint_(self, point:id) -> id; +} + +impl NSTabView for id { + unsafe fn initWithFrame_(self, frameRect: NSRect) -> id { + msg_send![self, initWithFrame:frameRect] + } + + unsafe fn addTabViewItem_(self, tabViewItem: id) { + msg_send![self, addTabViewItem:tabViewItem] + } + unsafe fn insertTabViewItem_atIndex_(self, tabViewItem: id,index:NSInteger) { + msg_send![self, addTabViewItem:tabViewItem atIndex:index] + } + unsafe fn removeTabViewItem_(self,tabViewItem:id){ + msg_send![self, removeTabViewItem:tabViewItem] + } + + unsafe fn indexOfTabViewItem_(self, tabViewItem:id) -> id{ + msg_send![self, indexOfTabViewItem:tabViewItem] + } + + unsafe fn indexOfTabViewItemWithIdentifier_(self,identifier:id) -> id{ + msg_send![self, indexOfTabViewItemWithIdentifier:identifier] + } + unsafe fn numberOfTabViewItems(self) -> id{ + msg_send![self, numberOfTabViewItems] + } + + unsafe fn tabViewItemAtIndex_(self,index:id)->id{ + msg_send![self, tabViewItemAtIndex:index] + } + + unsafe fn tabViewItems(self)->id{ + msg_send![self, tabViewItems] + } + + unsafe fn selectFirstTabViewItem_(self,sender:id){ + msg_send![self, selectFirstTabViewItem:sender] + } + + unsafe fn selectLastTabViewItem_(self,sender:id){ + msg_send![self, selectLastTabViewItem:sender] + } + unsafe fn selectNextTabViewItem_(self, sender:id){ + msg_send![self, selectNextTabViewItem:sender] + } + unsafe fn selectPreviousTabViewItem_(self,sender:id){ + msg_send![self, selectPreviousTabViewItem:sender] + } + + unsafe fn selectTabViewItem_(self,tabViewItem:id){ + msg_send![self, selectTabViewItem:tabViewItem] + } + + unsafe fn selectTabViewItemAtIndex_(self,index:id){ + msg_send![self, selectTabViewItemAtIndex:index] + } + unsafe fn selectTabViewItemWithIdentifier_(self,identifier:id){ + msg_send![self, selectTabViewItemWithIdentifier:identifier] + } + unsafe fn selectedTabViewItem(self) -> id{ + msg_send![self, selectedTabViewItem] + } + unsafe fn takeSelectedTabViewItemFromSender_(self,sender:id){ + msg_send![self, takeSelectedTabViewItemFromSender:sender] + } + + unsafe fn font(self)->id{ + msg_send![self, font] + } + + unsafe fn setFont_(self, font:id){ + msg_send![self, setFont:font] + } + + unsafe fn tabViewType(self)->NSTabViewType{ + msg_send![self, tabViewType] + } + unsafe fn setTabViewType_(self,tabViewType: NSTabViewType){ + msg_send![self, setTabViewType:tabViewType] + } + + unsafe fn controlTint(self) -> id{ + msg_send![self, controlTint] + } + unsafe fn setControlTint_(self,controlTint:id){ + msg_send![self, setControlTint:controlTint] + } + + unsafe fn drawsBackground(self) -> BOOL{ + msg_send![self, drawsBackground] + } + unsafe fn setDrawsBackground_(self,drawsBackground:BOOL){ + msg_send![self, setDrawsBackground:drawsBackground as libc::c_int] + } + + unsafe fn minimumSize(self) -> id{ + msg_send![self, minimumSize] + } + unsafe fn contentRect(self) -> id{ + msg_send![self, contentRect] + } + unsafe fn controlSize(self) -> id{ + msg_send![self, controlSize] + } + unsafe fn setControlSize_(self,controlSize:id){ + msg_send![self, setControlSize:controlSize] + } + + unsafe fn allowsTruncatedLabels(self) -> BOOL{ + msg_send![self, allowsTruncatedLabels] + } + unsafe fn setAllowsTruncatedLabels_(self, allowTruncatedLabels:BOOL){ + msg_send![self, setAllowsTruncatedLabels:allowTruncatedLabels as libc::c_int] + } + + unsafe fn setDelegate_(self, delegate:id){ + msg_send![self, setDelegate:delegate] + } + unsafe fn delegate(self) -> id { + msg_send![self, delegate] + } + + unsafe fn tabViewAtPoint_(self, point:id) -> id{ + msg_send![self, tabViewAtPoint:point] + } +} + +#[repr(u64)] +pub enum NSTabState { + NSSelectedTab = 0, + NSBackgroundTab = 1, + NSPressedTab = 2 +} + +pub trait NSTabViewItem: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSTabViewItem), alloc] + } + unsafe fn new(_: Self) -> id { + msg_send![class!(NSTabViewItem), new] + } + + unsafe fn initWithIdentifier_(self, identifier:id) -> id; + unsafe fn drawLabel_inRect_(self,shouldTruncateLabel:BOOL,labelRect:NSRect); + unsafe fn label(self) -> id; + unsafe fn setLabel_(self,label:id); + unsafe fn sizeOfLabel_(self, computeMin:BOOL); + unsafe fn tabState(self) -> NSTabState; + unsafe fn identifier(self)-> id; + unsafe fn setIdentifier_(self,identifier:id); + unsafe fn color(self)-> id; + unsafe fn setColor_(self,color:id); + unsafe fn view(self) -> id; + unsafe fn setView_(self, view:id); + unsafe fn initialFirstResponder(self)->id; + unsafe fn setInitialFirstResponder_(self,initialFirstResponder:id); + unsafe fn tabView(self) -> id; + unsafe fn tooltip(self) -> id; + unsafe fn setTooltip_(self,toolTip:id); +} + +impl NSTabViewItem for id { + unsafe fn initWithIdentifier_(self, identifier: id) -> id { + msg_send![self, initWithIdentifier:identifier] + } + + unsafe fn drawLabel_inRect_(self, shouldTruncateLabel:BOOL,labelRect:NSRect){ + msg_send![self, drawLabel:shouldTruncateLabel as libc::c_int inRect:labelRect] + } + + unsafe fn label(self)->id{ + msg_send![self, label] + } + unsafe fn setLabel_(self,label : id){ + msg_send![self, setLabel:label] + } + + unsafe fn sizeOfLabel_(self,computeMin:BOOL){ + msg_send![self, sizeOfLabel:computeMin as libc::c_int] + } + + unsafe fn tabState(self) -> NSTabState{ + msg_send![self, tabState] + } + + unsafe fn identifier(self)-> id { + msg_send![self, identifier] + } + + unsafe fn setIdentifier_(self,identifier:id){ + msg_send![self, identifier:identifier] + } + + unsafe fn color(self)-> id{ + msg_send![self, color] + } + + unsafe fn setColor_(self,color:id){ + msg_send![self, color:color] + } + + unsafe fn view(self) -> id { + msg_send![self, view] + } + + unsafe fn setView_(self, view:id){ + msg_send![self, setView:view] + } + + unsafe fn initialFirstResponder(self)->id{ + msg_send![self, initialFirstResponder] + } + + unsafe fn setInitialFirstResponder_(self,initialFirstResponder:id){ + msg_send![self, setInitialFirstResponder:initialFirstResponder] + } + + unsafe fn tabView(self) -> id{ + msg_send![self, tabView] + } + + unsafe fn tooltip(self) -> id{ + msg_send![self, tooltip] + } + + unsafe fn setTooltip_(self,toolTip:id){ + msg_send![self, setTooltip:toolTip] + } +} + +pub trait NSLayoutConstraint: Sized { + unsafe fn activateConstraints(_: Self, constraints: id) -> id; +} + +impl NSLayoutConstraint for id { + unsafe fn activateConstraints(_: Self, constraints: id) -> id { + msg_send![class!(NSLayoutConstraint), activateConstraints:constraints] + } +} + +pub trait NSLayoutDimension: Sized { + unsafe fn constraintEqualToConstant(self, c: CGFloat) -> id; + unsafe fn constraintLessThanOrEqualToConstant(self, c: CGFloat) -> id; + unsafe fn constraintGreaterThanOrEqualToConstant(self, c: CGFloat) -> id; +} + +impl NSLayoutDimension for id { + unsafe fn constraintEqualToConstant(self, c: CGFloat) -> id { + msg_send![self, constraintEqualToConstant:c] + } + + unsafe fn constraintLessThanOrEqualToConstant(self, c: CGFloat) -> id { + msg_send![self, constraintLessThanOrEqualToConstant:c] + } + + unsafe fn constraintGreaterThanOrEqualToConstant(self, c: CGFloat) -> id { + msg_send![self, constraintGreaterThanOrEqualToConstant:c] + } +} + +pub trait NSColorSpace: Sized { + unsafe fn deviceRGBColorSpace(_:Self) -> id; + unsafe fn genericRGBColorSpace(_:Self) -> id; + unsafe fn deviceCMYKColorSpace(_:Self) -> id; + unsafe fn genericCMYKColorSpace(_:Self) -> id; + unsafe fn deviceGrayColorSpace(_:Self) -> id; + unsafe fn genericGrayColorSpace(_:Self) -> id; + unsafe fn sRGBColorSpace(_:Self) -> id; + unsafe fn extendedSRGBColorSpace(_:Self) -> id; + unsafe fn displayP3ColorSpace(_:Self) -> id; + unsafe fn genericGamma22GrayColorSpace(_:Self) -> id; + unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id; + unsafe fn adobeRGB1998ColorSpace(_:Self) -> id; + + unsafe fn alloc(_: Self) -> id; + + unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id; + unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */; + unsafe fn localizedName(self) -> id; +} + +impl NSColorSpace for id { + unsafe fn deviceRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceRGBColorSpace] + } + unsafe fn genericRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericRGBColorSpace] + } + unsafe fn deviceCMYKColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceCMYKColorSpace] + } + unsafe fn genericCMYKColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericCMYKColorSpace] + } + unsafe fn deviceGrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), deviceGrayColorSpace] + } + unsafe fn genericGrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericGrayColorSpace] + } + unsafe fn sRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), sRGBColorSpace] + } + unsafe fn extendedSRGBColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), extendedSRGBColorSpace] + } + unsafe fn displayP3ColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), displayP3ColorSpace] + } + unsafe fn genericGamma22GrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), genericGamma22GrayColorSpace] + } + unsafe fn extendedGenericGamma22GrayColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), extendedGenericGamma22GrayColorSpace] + } + unsafe fn adobeRGB1998ColorSpace(_:Self) -> id { + msg_send![class!(NSColorSpace), adobeRGB1998ColorSpace] + } + + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSColorSpace), alloc] + } + + unsafe fn initWithCGColorSpace_(self, cg_color_space: *const c_void /* (CGColorSpaceRef) */) -> id { + msg_send![self, initWithCGColorSpace:cg_color_space] + } + unsafe fn CGColorSpace(self) -> *const c_void /* (CGColorSpaceRef) */ { + msg_send![self, CGColorSpace] + } + unsafe fn localizedName(self) -> id { + msg_send![self, localizedName] + } +} + +pub trait NSColor: Sized { + unsafe fn clearColor(_: Self) -> id; + unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id; + + unsafe fn colorUsingColorSpace_(self, color_space: id) -> id; + + unsafe fn alphaComponent(self) -> CGFloat; + unsafe fn whiteComponent(self) -> CGFloat; + unsafe fn redComponent(self) -> CGFloat; + unsafe fn greenComponent(self) -> CGFloat; + unsafe fn blueComponent(self) -> CGFloat; + unsafe fn cyanComponent(self) -> CGFloat; + unsafe fn magentaComponent(self) -> CGFloat; + unsafe fn yellowComponent(self) -> CGFloat; + unsafe fn blackComponent(self) -> CGFloat; + unsafe fn hueComponent(self) -> CGFloat; + unsafe fn saturationComponent(self) -> CGFloat; + unsafe fn brightnessComponent(self) -> CGFloat; +} + +impl NSColor for id { + unsafe fn clearColor(_: Self) -> id { + msg_send![class!(NSColor), clearColor] + } + unsafe fn colorWithRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithSRGBRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithSRGBRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithDeviceRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithDeviceRed:r green:g blue:b alpha:a] + } + unsafe fn colorWithDisplayP3Red_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithDisplayP3Red:r green:g blue:b alpha:a] + } + unsafe fn colorWithCalibratedRed_green_blue_alpha_(_:Self, r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> id { + msg_send![class!(NSColor), colorWithCalibratedRed:r green:g blue:b alpha:a] + } + + unsafe fn colorUsingColorSpace_(self, color_space: id) -> id { + msg_send![self, colorUsingColorSpace:color_space] + } + + unsafe fn alphaComponent(self) -> CGFloat { + msg_send![self, alphaComponent] + } + unsafe fn whiteComponent(self) -> CGFloat { + msg_send![self, whiteComponent] + } + unsafe fn redComponent(self) -> CGFloat { + msg_send![self, redComponent] + } + unsafe fn greenComponent(self) -> CGFloat { + msg_send![self, greenComponent] + } + unsafe fn blueComponent(self) -> CGFloat { + msg_send![self, blueComponent] + } + unsafe fn cyanComponent(self) -> CGFloat { + msg_send![self, cyanComponent] + } + unsafe fn magentaComponent(self) -> CGFloat { + msg_send![self, magentaComponent] + } + unsafe fn yellowComponent(self) -> CGFloat { + msg_send![self, yellowComponent] + } + unsafe fn blackComponent(self) -> CGFloat { + msg_send![self, blackComponent] + } + unsafe fn hueComponent(self) -> CGFloat { + msg_send![self, hueComponent] + } + unsafe fn saturationComponent(self) -> CGFloat { + msg_send![self, saturationComponent] + } + unsafe fn brightnessComponent(self) -> CGFloat { + msg_send![self, brightnessComponent] + } +} + +pub trait NSToolbar: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSToolbar), alloc] + } + + unsafe fn init_(self) -> id /* NSToolbar */; + unsafe fn initWithIdentifier_(self, identifier: id) -> id /* NSToolbar */; + + unsafe fn showsBaselineSeparator(self) -> BOOL; + unsafe fn setShowsBaselineSeparator_(self, value: BOOL); +} + +impl NSToolbar for id { + unsafe fn init_(self) -> id /* NSToolbar */ { + msg_send![self, init] + } + + unsafe fn initWithIdentifier_(self, identifier: id) -> id /* NSToolbar */ { + msg_send![self, initWithIdentifier:identifier] + } + + unsafe fn showsBaselineSeparator(self) -> BOOL { + msg_send![self, showsBaselineSeparator] + } + + unsafe fn setShowsBaselineSeparator_(self, value: BOOL) { + msg_send![self, setShowsBaselineSeparator:value] + } +} + +pub trait NSSpellChecker : Sized { + unsafe fn sharedSpellChecker(_: Self) -> id; + unsafe fn checkSpellingOfString_startingAt(self, + stringToCheck: id, + startingOffset: NSInteger) -> NSRange; + unsafe fn checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount( + self, + stringToCheck: id, + startingOffset: NSInteger, + language: id, + wrapFlag: BOOL, + tag: NSInteger) -> (NSRange, NSInteger); + unsafe fn uniqueSpellDocumentTag(_: Self) -> NSInteger; + unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger); + unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger); +} + +impl NSSpellChecker for id { + unsafe fn sharedSpellChecker(_: Self) -> id { + msg_send![class!(NSSpellChecker), sharedSpellChecker] + } + + unsafe fn checkSpellingOfString_startingAt(self, + stringToCheck: id, + startingOffset: NSInteger) -> NSRange { + msg_send![self, checkSpellingOfString:stringToCheck startingAt:startingOffset] + } + + unsafe fn checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount( + self, + stringToCheck: id, + startingOffset: NSInteger, + language: id, + wrapFlag: BOOL, + tag: NSInteger) -> (NSRange, NSInteger) { + let mut wordCount = 0; + let range = msg_send![self, + checkSpellingOfString:stringToCheck + startingAt:startingOffset + language:language + wrap:wrapFlag + inSpellDocumentWithTag:tag + wordCount:&mut wordCount + ]; + (range, wordCount) + } + + unsafe fn uniqueSpellDocumentTag(_: Self) -> NSInteger { + msg_send![class!(NSSpellChecker), uniqueSpellDocumentTag] + } + + unsafe fn closeSpellDocumentWithTag(self, tag: NSInteger) { + msg_send![self, closeSpellDocumentWithTag:tag] + } + + unsafe fn ignoreWord_inSpellDocumentWithTag(self, wordToIgnore: id, tag: NSInteger) { + msg_send![self, ignoreWord:wordToIgnore inSpellDocumentWithTag:tag] + } +} + +pub trait NSNib: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSNib), alloc] + } + + unsafe fn initWithNibNamed_bundle_(self, name: id, bundle: id) -> id; +} + +impl NSNib for id { + unsafe fn initWithNibNamed_bundle_(self, name: id, bundle: id) -> id { + msg_send![self, initWithNibNamed:name bundle:bundle] + } +} + + +#[cfg(test)] +mod test { + use super::*; + + #[test] + pub fn test_nsapp() { + unsafe { + let _nsApp = NSApp(); + } + } +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/base.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/base.rs new file mode 100644 index 0000000..028205e --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/base.rs @@ -0,0 +1,28 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use objc::runtime; + +pub use objc::runtime::{BOOL, NO, YES}; + +pub type Class = *mut runtime::Class; +#[allow(non_camel_case_types)] +pub type id = *mut runtime::Object; +pub type SEL = runtime::Sel; + +#[allow(non_upper_case_globals)] +pub const nil: id = 0 as id; +#[allow(non_upper_case_globals)] +pub const Nil: Class = 0 as Class; + +/// A convenience method to convert the name of a selector to the selector object. +#[inline] +pub fn selector(name: &str) -> SEL { + runtime::Sel::register(name) +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/foundation.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/foundation.rs new file mode 100644 index 0000000..d87c446 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/foundation.rs @@ -0,0 +1,1318 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +use std::ptr; +use std::os::raw::c_void; +use base::{id, BOOL, NO, SEL, nil}; +use block::Block; +use libc; + + +#[cfg(target_pointer_width = "32")] +pub type NSInteger = libc::c_int; +#[cfg(target_pointer_width = "32")] +pub type NSUInteger = libc::c_uint; + +#[cfg(target_pointer_width = "64")] +pub type NSInteger = libc::c_long; +#[cfg(target_pointer_width = "64")] +pub type NSUInteger = libc::c_ulong; + +pub const NSIntegerMax: NSInteger = NSInteger::max_value(); +pub const NSNotFound: NSInteger = NSIntegerMax; + +const UTF8_ENCODING: usize = 4; + +#[cfg(target_os = "macos")] +mod macos { + use std::mem; + use base::id; + use core_graphics::base::CGFloat; + use core_graphics::geometry::CGRect; + use objc; + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct NSPoint { + pub x: CGFloat, + pub y: CGFloat, + } + + impl NSPoint { + #[inline] + pub fn new(x: CGFloat, y: CGFloat) -> NSPoint { + NSPoint { + x: x, + y: y, + } + } + } + + unsafe impl objc::Encode for NSPoint { + fn encode() -> objc::Encoding { + let encoding = format!("{{CGPoint={}{}}}", + CGFloat::encode().as_str(), + CGFloat::encode().as_str()); + unsafe { objc::Encoding::from_str(&encoding) } + } + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct NSSize { + pub width: CGFloat, + pub height: CGFloat, + } + + impl NSSize { + #[inline] + pub fn new(width: CGFloat, height: CGFloat) -> NSSize { + NSSize { + width: width, + height: height, + } + } + } + + unsafe impl objc::Encode for NSSize { + fn encode() -> objc::Encoding { + let encoding = format!("{{CGSize={}{}}}", + CGFloat::encode().as_str(), + CGFloat::encode().as_str()); + unsafe { objc::Encoding::from_str(&encoding) } + } + } + + #[repr(C)] + #[derive(Copy, Clone)] + pub struct NSRect { + pub origin: NSPoint, + pub size: NSSize, + } + + impl NSRect { + #[inline] + pub fn new(origin: NSPoint, size: NSSize) -> NSRect { + NSRect { + origin: origin, + size: size + } + } + + #[inline] + pub fn as_CGRect(&self) -> &CGRect { + unsafe { + mem::transmute::<&NSRect, &CGRect>(self) + } + } + + #[inline] + pub fn inset(&self, x: CGFloat, y: CGFloat) -> NSRect { + unsafe { + NSInsetRect(*self, x, y) + } + } + } + + unsafe impl objc::Encode for NSRect { + fn encode() -> objc::Encoding { + let encoding = format!("{{CGRect={}{}}}", + NSPoint::encode().as_str(), + NSSize::encode().as_str()); + unsafe { objc::Encoding::from_str(&encoding) } + } + } + + // Same as CGRectEdge + #[repr(u32)] + pub enum NSRectEdge { + NSRectMinXEdge, + NSRectMinYEdge, + NSRectMaxXEdge, + NSRectMaxYEdge, + } + + #[link(name = "Foundation", kind = "framework")] + extern { + fn NSInsetRect(rect: NSRect, x: CGFloat, y: CGFloat) -> NSRect; + } + + pub trait NSValue: Sized { + unsafe fn valueWithPoint(_: Self, point: NSPoint) -> id { + msg_send![class!(NSValue), valueWithPoint:point] + } + + unsafe fn valueWithSize(_: Self, size: NSSize) -> id { + msg_send![class!(NSValue), valueWithSize:size] + } + } + + impl NSValue for id { + } +} + +#[cfg(target_os = "macos")] +pub use self::macos::*; + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct NSRange { + pub location: NSUInteger, + pub length: NSUInteger, +} + +impl NSRange { + #[inline] + pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { + NSRange { + location: location, + length: length + } + } +} + +#[link(name = "Foundation", kind = "framework")] +extern { + pub static NSDefaultRunLoopMode: id; +} + +pub trait NSAutoreleasePool: Sized { + unsafe fn new(_: Self) -> id { + msg_send![class!(NSAutoreleasePool), new] + } + + unsafe fn autorelease(self) -> Self; + unsafe fn drain(self); +} + +impl NSAutoreleasePool for id { + unsafe fn autorelease(self) -> id { + msg_send![self, autorelease] + } + + unsafe fn drain(self) { + msg_send![self, drain] + } +} + +pub trait NSProcessInfo: Sized { + unsafe fn processInfo(_: Self) -> id { + msg_send![class!(NSProcessInfo), processInfo] + } + + unsafe fn processName(self) -> id; +} + +impl NSProcessInfo for id { + unsafe fn processName(self) -> id { + msg_send![self, processName] + } +} + +pub type NSTimeInterval = libc::c_double; + +pub trait NSArray: Sized { + unsafe fn array(_: Self) -> id { + msg_send![class!(NSArray), array] + } + + unsafe fn arrayWithObjects(_: Self, objects: &[id]) -> id { + msg_send![class!(NSArray), arrayWithObjects:objects.as_ptr() + count:objects.len()] + } + + unsafe fn arrayWithObject(_: Self, object: id) -> id { + msg_send![class!(NSArray), arrayWithObject:object] + } + + unsafe fn init(self) -> id; + + unsafe fn count(self) -> NSUInteger; + + unsafe fn arrayByAddingObjectFromArray(self, object: id) -> id; + unsafe fn arrayByAddingObjectsFromArray(self, objects: id) -> id; + unsafe fn objectAtIndex(self, index: NSUInteger) -> id; +} + +impl NSArray for id { + unsafe fn init(self) -> id { + msg_send![self, init] + } + + unsafe fn count(self) -> NSUInteger { + msg_send![self, count] + } + + unsafe fn arrayByAddingObjectFromArray(self, object: id) -> id { + msg_send![self, arrayByAddingObjectFromArray:object] + } + + unsafe fn arrayByAddingObjectsFromArray(self, objects: id) -> id { + msg_send![self, arrayByAddingObjectsFromArray:objects] + } + + unsafe fn objectAtIndex(self, index: NSUInteger) -> id { + msg_send![self, objectAtIndex:index] + } +} + +pub trait NSDictionary: Sized { + unsafe fn dictionary(_: Self) -> id { + msg_send![class!(NSDictionary), dictionary] + } + + unsafe fn dictionaryWithContentsOfFile_(_: Self, path: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithContentsOfFile:path] + } + + unsafe fn dictionaryWithContentsOfURL_(_: Self, aURL: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithContentsOfURL:aURL] + } + + unsafe fn dictionaryWithDictionary_(_: Self, otherDictionary: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithDictionary:otherDictionary] + } + + unsafe fn dictionaryWithObject_forKey_(_: Self, anObject: id, aKey: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithObject:anObject forKey:aKey] + } + + unsafe fn dictionaryWithObjects_forKeys_(_: Self, objects: id, keys: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithObjects:objects forKeys:keys] + } + + unsafe fn dictionaryWithObjects_forKeys_count_(_: Self, objects: *const id, keys: *const id, count: NSUInteger) -> id { + msg_send![class!(NSDictionary), dictionaryWithObjects:objects forKeys:keys count:count] + } + + unsafe fn dictionaryWithObjectsAndKeys_(_: Self, firstObject: id) -> id { + msg_send![class!(NSDictionary), dictionaryWithObjectsAndKeys:firstObject] + } + + unsafe fn init(self) -> id; + unsafe fn initWithContentsOfFile_(self, path: id) -> id; + unsafe fn initWithContentsOfURL_(self, aURL: id) -> id; + unsafe fn initWithDictionary_(self, otherDicitonary: id) -> id; + unsafe fn initWithDictionary_copyItems_(self, otherDicitonary: id, flag: BOOL) -> id; + unsafe fn initWithObjects_forKeys_(self, objects: id, keys: id) -> id; + unsafe fn initWithObjects_forKeys_count_(self, objects: id, keys: id, count: NSUInteger) -> id; + unsafe fn initWithObjectsAndKeys_(self, firstObject: id) -> id; + + unsafe fn sharedKeySetForKeys_(_: Self, keys: id) -> id { + msg_send![class!(NSDictionary), sharedKeySetForKeys:keys] + } + + unsafe fn count(self) -> NSUInteger; + + unsafe fn isEqualToDictionary_(self, otherDictionary: id) -> BOOL; + + unsafe fn allKeys(self) -> id; + unsafe fn allKeysForObject_(self, anObject: id) -> id; + unsafe fn allValues(self) -> id; + unsafe fn objectForKey_(self, aKey: id) -> id; + unsafe fn objectForKeyedSubscript_(self, key: id) -> id; + unsafe fn objectsForKeys_notFoundMarker_(self, keys: id, anObject: id) -> id; + unsafe fn valueForKey_(self, key: id) -> id; + + unsafe fn keyEnumerator(self) -> id; + unsafe fn objectEnumerator(self) -> id; + unsafe fn enumerateKeysAndObjectsUsingBlock_(self, block: *mut Block<(id, id, *mut BOOL), ()>); + unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_(self, opts: NSEnumerationOptions, + block: *mut Block<(id, id, *mut BOOL), ()>); + + unsafe fn keysSortedByValueUsingSelector_(self, comparator: SEL) -> id; + unsafe fn keysSortedByValueUsingComparator_(self, cmptr: NSComparator) -> id; + unsafe fn keysSortedByValueWithOptions_usingComparator_(self, opts: NSEnumerationOptions, cmptr: NSComparator) -> id; + + unsafe fn keysOfEntriesPassingTest_(self, predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id; + unsafe fn keysOfEntriesWithOptions_PassingTest_(self, opts: NSEnumerationOptions, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id; + + unsafe fn writeToFile_atomically_(self, path: id, flag: BOOL) -> BOOL; + unsafe fn writeToURL_atomically_(self, aURL: id, flag: BOOL) -> BOOL; + + unsafe fn fileCreationDate(self) -> id; + unsafe fn fileExtensionHidden(self) -> BOOL; + unsafe fn fileGroupOwnerAccountID(self) -> id; + unsafe fn fileGroupOwnerAccountName(self) -> id; + unsafe fn fileIsAppendOnly(self) -> BOOL; + unsafe fn fileIsImmutable(self) -> BOOL; + unsafe fn fileModificationDate(self) -> id; + unsafe fn fileOwnerAccountID(self) -> id; + unsafe fn fileOwnerAccountName(self) -> id; + unsafe fn filePosixPermissions(self) -> NSUInteger; + unsafe fn fileSize(self) -> libc::c_ulonglong; + unsafe fn fileSystemFileNumber(self) -> NSUInteger; + unsafe fn fileSystemNumber(self) -> NSInteger; + unsafe fn fileType(self) -> id; + + unsafe fn description(self) -> id; + unsafe fn descriptionInStringsFileFormat(self) -> id; + unsafe fn descriptionWithLocale_(self, locale: id) -> id; + unsafe fn descriptionWithLocale_indent_(self, locale: id, indent: NSUInteger) -> id; +} + +impl NSDictionary for id { + unsafe fn init(self) -> id { + msg_send![self, init] + } + + unsafe fn initWithContentsOfFile_(self, path: id) -> id { + msg_send![self, initWithContentsOfFile:path] + } + + unsafe fn initWithContentsOfURL_(self, aURL: id) -> id { + msg_send![self, initWithContentsOfURL:aURL] + } + + unsafe fn initWithDictionary_(self, otherDictionary: id) -> id { + msg_send![self, initWithDictionary:otherDictionary] + } + + unsafe fn initWithDictionary_copyItems_(self, otherDictionary: id, flag: BOOL) -> id { + msg_send![self, initWithDictionary:otherDictionary copyItems:flag] + } + + unsafe fn initWithObjects_forKeys_(self, objects: id, keys: id) -> id { + msg_send![self, initWithObjects:objects forKeys:keys] + } + + unsafe fn initWithObjects_forKeys_count_(self, objects: id, keys: id, count: NSUInteger) -> id { + msg_send![self, initWithObjects:objects forKeys:keys count:count] + } + + unsafe fn initWithObjectsAndKeys_(self, firstObject: id) -> id { + msg_send![self, initWithObjectsAndKeys:firstObject] + } + + unsafe fn count(self) -> NSUInteger { + msg_send![self, count] + } + + unsafe fn isEqualToDictionary_(self, otherDictionary: id) -> BOOL { + msg_send![self, isEqualToDictionary:otherDictionary] + } + + unsafe fn allKeys(self) -> id { + msg_send![self, allKeys] + } + + unsafe fn allKeysForObject_(self, anObject: id) -> id { + msg_send![self, allKeysForObject:anObject] + } + + unsafe fn allValues(self) -> id { + msg_send![self, allValues] + } + + unsafe fn objectForKey_(self, aKey: id) -> id { + msg_send![self, objectForKey:aKey] + } + + unsafe fn objectForKeyedSubscript_(self, key: id) -> id { + msg_send![self, objectForKeyedSubscript:key] + } + + unsafe fn objectsForKeys_notFoundMarker_(self, keys: id, anObject: id) -> id { + msg_send![self, objectsForKeys:keys notFoundMarker:anObject] + } + + unsafe fn valueForKey_(self, key: id) -> id { + msg_send![self, valueForKey:key] + } + + unsafe fn keyEnumerator(self) -> id { + msg_send![self, keyEnumerator] + } + + unsafe fn objectEnumerator(self) -> id { + msg_send![self, objectEnumerator] + } + + unsafe fn enumerateKeysAndObjectsUsingBlock_(self, block: *mut Block<(id, id, *mut BOOL), ()>) { + msg_send![self, enumerateKeysAndObjectsUsingBlock:block] + } + + unsafe fn enumerateKeysAndObjectsWithOptions_usingBlock_(self, opts: NSEnumerationOptions, + block: *mut Block<(id, id, *mut BOOL), ()>) { + msg_send![self, enumerateKeysAndObjectsWithOptions:opts usingBlock:block] + } + + unsafe fn keysSortedByValueUsingSelector_(self, comparator: SEL) -> id { + msg_send![self, keysSortedByValueUsingSelector:comparator] + } + + unsafe fn keysSortedByValueUsingComparator_(self, cmptr: NSComparator) -> id { + msg_send![self, keysSortedByValueUsingComparator:cmptr] + } + + unsafe fn keysSortedByValueWithOptions_usingComparator_(self, opts: NSEnumerationOptions, cmptr: NSComparator) -> id { + let rv: id = msg_send![self, keysSortedByValueWithOptions:opts usingComparator:cmptr]; + rv + } + + unsafe fn keysOfEntriesPassingTest_(self, predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id { + msg_send![self, keysOfEntriesPassingTest:predicate] + } + + unsafe fn keysOfEntriesWithOptions_PassingTest_(self, opts: NSEnumerationOptions, + predicate: *mut Block<(id, id, *mut BOOL), BOOL>) -> id { + msg_send![self, keysOfEntriesWithOptions:opts PassingTest:predicate] + } + + unsafe fn writeToFile_atomically_(self, path: id, flag: BOOL) -> BOOL { + msg_send![self, writeToFile:path atomically:flag] + } + + unsafe fn writeToURL_atomically_(self, aURL: id, flag: BOOL) -> BOOL { + msg_send![self, writeToURL:aURL atomically:flag] + } + + unsafe fn fileCreationDate(self) -> id { + msg_send![self, fileCreationDate] + } + + unsafe fn fileExtensionHidden(self) -> BOOL { + msg_send![self, fileExtensionHidden] + } + + unsafe fn fileGroupOwnerAccountID(self) -> id { + msg_send![self, fileGroupOwnerAccountID] + } + + unsafe fn fileGroupOwnerAccountName(self) -> id { + msg_send![self, fileGroupOwnerAccountName] + } + + unsafe fn fileIsAppendOnly(self) -> BOOL { + msg_send![self, fileIsAppendOnly] + } + + unsafe fn fileIsImmutable(self) -> BOOL { + msg_send![self, fileIsImmutable] + } + + unsafe fn fileModificationDate(self) -> id { + msg_send![self, fileModificationDate] + } + + unsafe fn fileOwnerAccountID(self) -> id { + msg_send![self, fileOwnerAccountID] + } + + unsafe fn fileOwnerAccountName(self) -> id { + msg_send![self, fileOwnerAccountName] + } + + unsafe fn filePosixPermissions(self) -> NSUInteger { + msg_send![self, filePosixPermissions] + } + + unsafe fn fileSize(self) -> libc::c_ulonglong { + msg_send![self, fileSize] + } + + unsafe fn fileSystemFileNumber(self) -> NSUInteger { + msg_send![self, fileSystemFileNumber] + } + + unsafe fn fileSystemNumber(self) -> NSInteger { + msg_send![self, fileSystemNumber] + } + + unsafe fn fileType(self) -> id { + msg_send![self, fileType] + } + + unsafe fn description(self) -> id { + msg_send![self, description] + } + + unsafe fn descriptionInStringsFileFormat(self) -> id { + msg_send![self, descriptionInStringsFileFormat] + } + + unsafe fn descriptionWithLocale_(self, locale: id) -> id { + msg_send![self, descriptionWithLocale:locale] + } + + unsafe fn descriptionWithLocale_indent_(self, locale: id, indent: NSUInteger) -> id { + msg_send![self, descriptionWithLocale:locale indent:indent] + } +} + +bitflags! { + pub struct NSEnumerationOptions: libc::c_ulonglong { + const NSEnumerationConcurrent = 1 << 0; + const NSEnumerationReverse = 1 << 1; + } +} + +pub type NSComparator = *mut Block<(id, id), NSComparisonResult>; + +#[repr(isize)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NSComparisonResult { + NSOrderedAscending = -1, + NSOrderedSame = 0, + NSOrderedDescending = 1 +} + +pub trait NSString: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSString), alloc] + } + + unsafe fn stringByAppendingString_(self, other: id) -> id; + unsafe fn init_str(self, string: &str) -> Self; + unsafe fn UTF8String(self) -> *const libc::c_char; + unsafe fn len(self) -> usize; + unsafe fn isEqualToString(self, &str) -> bool; + unsafe fn substringWithRange(self, range: NSRange) -> id; +} + +impl NSString for id { + unsafe fn isEqualToString(self, other: &str) -> bool { + let other = NSString::alloc(nil).init_str(other); + let rv: BOOL = msg_send![self, isEqualToString:other]; + rv != NO + } + + unsafe fn stringByAppendingString_(self, other: id) -> id { + msg_send![self, stringByAppendingString:other] + } + + unsafe fn init_str(self, string: &str) -> id { + return msg_send![self, + initWithBytes:string.as_ptr() + length:string.len() + encoding:UTF8_ENCODING as id]; + } + + unsafe fn len(self) -> usize { + msg_send![self, lengthOfBytesUsingEncoding:UTF8_ENCODING] + } + + unsafe fn UTF8String(self) -> *const libc::c_char { + msg_send![self, UTF8String] + } + + unsafe fn substringWithRange(self, range: NSRange) -> id { + msg_send![self, substringWithRange:range] + } +} + +pub trait NSDate: Sized { + unsafe fn distantPast(_: Self) -> id { + msg_send![class!(NSDate), distantPast] + } + + unsafe fn distantFuture(_: Self) -> id { + msg_send![class!(NSDate), distantFuture] + } +} + +impl NSDate for id { + +} + +#[repr(C)] +struct NSFastEnumerationState { + pub state: libc::c_ulong, + pub items_ptr: *mut id, + pub mutations_ptr: *mut libc::c_ulong, + pub extra: [libc::c_ulong; 5] +} + +const NS_FAST_ENUM_BUF_SIZE: usize = 16; + +pub struct NSFastIterator { + state: NSFastEnumerationState, + buffer: [id; NS_FAST_ENUM_BUF_SIZE], + mut_val: Option, + len: usize, + idx: usize, + object: id +} + +impl Iterator for NSFastIterator { + type Item = id; + + fn next(&mut self) -> Option { + if self.idx >= self.len { + self.len = unsafe { + msg_send![self.object, countByEnumeratingWithState:&mut self.state objects:self.buffer.as_mut_ptr() count:NS_FAST_ENUM_BUF_SIZE] + }; + self.idx = 0; + } + + let new_mut = unsafe { + *self.state.mutations_ptr + }; + + if let Some(old_mut) = self.mut_val { + assert!(old_mut == new_mut, "The collection was mutated while being enumerated"); + } + + if self.idx < self.len { + let object = unsafe { + *self.state.items_ptr.offset(self.idx as isize) + }; + self.mut_val = Some(new_mut); + self.idx += 1; + Some(object) + } else { + None + } + } +} + +pub trait NSFastEnumeration: Sized { + unsafe fn iter(self) -> NSFastIterator; +} + +impl NSFastEnumeration for id { + unsafe fn iter(self) -> NSFastIterator { + NSFastIterator { + state: NSFastEnumerationState { + state: 0, + items_ptr: ptr::null_mut(), + mutations_ptr: ptr::null_mut(), + extra: [0; 5] + }, + buffer: [nil; NS_FAST_ENUM_BUF_SIZE], + mut_val: None, + len: 0, + idx: 0, + object: self + } + } +} + +pub trait NSRunLoop: Sized { + unsafe fn currentRunLoop() -> Self; + + unsafe fn performSelector_target_argument_order_modes_(self, + aSelector: SEL, + target: id, + anArgument: id, + order: NSUInteger, + modes: id); +} + +impl NSRunLoop for id { + unsafe fn currentRunLoop() -> id { + msg_send![class!(NSRunLoop), currentRunLoop] + } + + unsafe fn performSelector_target_argument_order_modes_(self, + aSelector: SEL, + target: id, + anArgument: id, + order: NSUInteger, + modes: id) { + msg_send![self, performSelector:aSelector + target:target + argument:anArgument + order:order + modes:modes] + } +} + +bitflags! { + pub struct NSURLBookmarkCreationOptions: NSUInteger { + const NSURLBookmarkCreationPreferFileIDResolution = 1 << 8; + const NSURLBookmarkCreationMinimalBookmark = 1 << 9; + const NSURLBookmarkCreationSuitableForBookmarkFile = 1 << 10; + const NSURLBookmarkCreationWithSecurityScope = 1 << 11; + const NSURLBookmarkCreationSecurityScopeAllowOnlyReadAccess = 1 << 12; + } +} + +pub type NSURLBookmarkFileCreationOptions = NSURLBookmarkCreationOptions; + +bitflags! { + pub struct NSURLBookmarkResolutionOptions: NSUInteger { + const NSURLBookmarkResolutionWithoutUI = 1 << 8; + const NSURLBookmarkResolutionWithoutMounting = 1 << 9; + const NSURLBookmarkResolutionWithSecurityScope = 1 << 10; + } +} + + +pub trait NSURL: Sized { + unsafe fn alloc(_: Self) -> id; + + unsafe fn URLWithString_(_:Self, string: id) -> id; + unsafe fn initWithString_(self, string: id) -> id; + unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id; + unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id; + unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id; + unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id; + unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id; + unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id; + unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id; + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id; + unsafe fn fileURLWithPath_(_:Self, path: id) -> id; + unsafe fn initFileURLWithPath_(self, path: id) -> id; + unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id; + unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id; + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id; + // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + // unsafe fn getFileSystemRepresentation_maxLength_ + // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; + unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id; + unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id; + unsafe fn dataRepresentation(self) -> id /* (NSData) */; + + unsafe fn isEqual_(self, id: id) -> BOOL; + + unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL; + unsafe fn isFileReferenceURL(self) -> BOOL; + unsafe fn isFileURL(self) -> BOOL; + + unsafe fn absoluteString(self) -> id /* (NSString) */; + unsafe fn absoluteURL(self) -> id /* (NSURL) */; + unsafe fn baseURL(self) -> id /* (NSURL) */; + // unsafe fn fileSystemRepresentation + unsafe fn fragment(self) -> id /* (NSString) */; + unsafe fn host(self) -> id /* (NSString) */; + unsafe fn lastPathComponent(self) -> id /* (NSString) */; + unsafe fn parameterString(self) -> id /* (NSString) */; + unsafe fn password(self) -> id /* (NSString) */; + unsafe fn path(self) -> id /* (NSString) */; + unsafe fn pathComponents(self) -> id /* (NSArray) */; + unsafe fn pathExtension(self) -> id /* (NSString) */; + unsafe fn port(self) -> id /* (NSNumber) */; + unsafe fn query(self) -> id /* (NSString) */; + unsafe fn relativePath(self) -> id /* (NSString) */; + unsafe fn relativeString(self) -> id /* (NSString) */; + unsafe fn resourceSpecifier(self) -> id /* (NSString) */; + unsafe fn scheme(self) -> id /* (NSString) */; + unsafe fn standardizedURL(self) -> id /* (NSURL) */; + unsafe fn user(self) -> id /* (NSString) */; + + // unsafe fn resourceValuesForKeys_error_ + // unsafe fn getResourceValue_forKey_error_ + // unsafe fn setResourceValue_forKey_error_ + // unsafe fn setResourceValues_error_ + // unsafe fn removeAllCachedResourceValues + // unsafe fn removeCachedResourceValueForKey_ + // unsafe fn setTemporaryResourceValue_forKey_ + unsafe fn NSURLResourceKey(self) -> id /* (NSString) */; + + unsafe fn filePathURL(self) -> id; + unsafe fn fileReferenceURL(self) -> id; + unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id; + unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id; + unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id; + unsafe fn URLByDeletingLastPathComponent(self) -> id; + unsafe fn URLByDeletingPathExtension(self) -> id; + unsafe fn URLByResolvingSymlinksInPath(self) -> id; + unsafe fn URLByStandardizingPath(self) -> id; + unsafe fn hasDirectoryPath(self) -> BOOL; + + unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */; + // unsafe fn resourceValuesForKeys_fromBookmarkData_ + unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id; + unsafe fn startAccessingSecurityScopedResource(self) -> BOOL; + unsafe fn stopAccessingSecurityScopedResource(self); + unsafe fn NSURLBookmarkFileCreationOptions(self) -> NSURLBookmarkFileCreationOptions; + unsafe fn NSURLBookmarkCreationOptions(self) -> NSURLBookmarkCreationOptions; + unsafe fn NSURLBookmarkResolutionOptions(self) -> NSURLBookmarkResolutionOptions; + + // unsafe fn checkPromisedItemIsReachableAndReturnError_ + // unsafe fn getPromisedItemResourceValue_forKey_error_ + // unsafe fn promisedItemResourceValuesForKeys_error_ + + // unsafe fn URLFromPasteboard_ + // unsafe fn writeToPasteboard_ +} + +impl NSURL for id { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSURL), alloc] + } + + unsafe fn URLWithString_(_:Self, string: id) -> id { + msg_send![class!(NSURL), URLWithString:string] + } + unsafe fn initWithString_(self, string: id) -> id { + msg_send![self, initWithString:string] + } + unsafe fn URLWithString_relativeToURL_(_:Self, string: id, url: id) -> id { + msg_send![class!(NSURL), URLWithString: string relativeToURL:url] + } + unsafe fn initWithString_relativeToURL_(self, string: id, url: id) -> id { + msg_send![self, initWithString:string relativeToURL:url] + } + unsafe fn fileURLWithPath_isDirectory_(_:Self, path: id, is_dir: BOOL) -> id { + msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir] + } + unsafe fn initFileURLWithPath_isDirectory_(self, path: id, is_dir: BOOL) -> id { + msg_send![self, initFileURLWithPath:path isDirectory:is_dir] + } + unsafe fn fileURLWithPath_relativeToURL_(_:Self, path: id, url: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path relativeToURL:url] + } + unsafe fn initFileURLWithPath_relativeToURL_(self, path: id, url: id) -> id { + msg_send![self, initFileURLWithPath:path relativeToURL:url] + } + unsafe fn fileURLWithPath_isDirectory_relativeToURL_(_:Self, path: id, is_dir: BOOL, url: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path isDirectory:is_dir relativeToURL:url] + } + unsafe fn initFileURLWithPath_isDirectory_relativeToURL_(self, path: id, is_dir: BOOL, url: id) -> id { + msg_send![self, initFileURLWithPath:path isDirectory:is_dir relativeToURL:url] + } + unsafe fn fileURLWithPath_(_:Self, path: id) -> id { + msg_send![class!(NSURL), fileURLWithPath:path] + } + unsafe fn initFileURLWithPath_(self, path: id) -> id { + msg_send![self, initFileURLWithPath:path] + } + unsafe fn fileURLWithPathComponents_(_:Self, path_components: id /* (NSArray*) */) -> id { + msg_send![class!(NSURL), fileURLWithPathComponents:path_components] + } + unsafe fn URLByResolvingAliasFileAtURL_options_error_(_:Self, url: id, options: NSURLBookmarkResolutionOptions, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), URLByResolvingAliasFileAtURL:url options:options error:error] + } + unsafe fn URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(_:Self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), URLByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] + } + unsafe fn initByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(self, data: id /* (NSData) */, options: NSURLBookmarkResolutionOptions, relative_to_url: id, is_stale: *mut BOOL, error: *mut id /* (NSError _Nullable) */) -> id { + msg_send![self, initByResolvingBookmarkData:data options:options relativeToURL:relative_to_url bookmarkDataIsStale:is_stale error:error] + } + // unsafe fn fileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + // unsafe fn getFileSystemRepresentation_maxLength_ + // unsafe fn initFileURLWithFileSystemRepresentation_isDirectory_relativeToURL_ + unsafe fn absoluteURLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + msg_send![class!(NSURL), absoluteURLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn initAbsoluteURLWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + msg_send![self, initAbsoluteURLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn URLWithDataRepresentation_relativeToURL_(_:Self, data: id /* (NSData) */, url: id) -> id { + msg_send![class!(NSURL), URLWithDataRepresentation:data relativeToURL:url] + } + unsafe fn initWithDataRepresentation_relativeToURL_(self, data: id /* (NSData) */, url: id) -> id { + msg_send![self, initWithDataRepresentation:data relativeToURL:url] + } + unsafe fn dataRepresentation(self) -> id /* (NSData) */ { + msg_send![self, dataRepresentation] + } + + unsafe fn isEqual_(self, id: id) -> BOOL { + msg_send![self, isEqual:id] + } + + unsafe fn checkResourceIsReachableAndReturnError_(self, error: id /* (NSError _Nullable) */) -> BOOL { + msg_send![self, checkResourceIsReachableAndReturnError:error] + } + unsafe fn isFileReferenceURL(self) -> BOOL { + msg_send![self, isFileReferenceURL] + } + unsafe fn isFileURL(self) -> BOOL { + msg_send![self, isFileURL] + } + + unsafe fn absoluteString(self) -> id /* (NSString) */ { + msg_send![self, absoluteString] + } + unsafe fn absoluteURL(self) -> id /* (NSURL) */ { + msg_send![self, absoluteURL] + } + unsafe fn baseURL(self) -> id /* (NSURL) */ { + msg_send![self, baseURL] + } + // unsafe fn fileSystemRepresentation + unsafe fn fragment(self) -> id /* (NSString) */ { + msg_send![self, fragment] + } + unsafe fn host(self) -> id /* (NSString) */ { + msg_send![self, host] + } + unsafe fn lastPathComponent(self) -> id /* (NSString) */ { + msg_send![self, lastPathComponent] + } + unsafe fn parameterString(self) -> id /* (NSString) */ { + msg_send![self, parameterString] + } + unsafe fn password(self) -> id /* (NSString) */ { + msg_send![self, password] + } + unsafe fn path(self) -> id /* (NSString) */ { + msg_send![self, path] + } + unsafe fn pathComponents(self) -> id /* (NSArray) */ { + msg_send![self, pathComponents] + } + unsafe fn pathExtension(self) -> id /* (NSString) */ { + msg_send![self, pathExtension] + } + unsafe fn port(self) -> id /* (NSNumber) */ { + msg_send![self, port] + } + unsafe fn query(self) -> id /* (NSString) */ { + msg_send![self, query] + } + unsafe fn relativePath(self) -> id /* (NSString) */ { + msg_send![self, relativePath] + } + unsafe fn relativeString(self) -> id /* (NSString) */ { + msg_send![self, relativeString] + } + unsafe fn resourceSpecifier(self) -> id /* (NSString) */ { + msg_send![self, resourceSpecifier] + } + unsafe fn scheme(self) -> id /* (NSString) */ { + msg_send![self, scheme] + } + unsafe fn standardizedURL(self) -> id /* (NSURL) */ { + msg_send![self, standardizedURL] + } + unsafe fn user(self) -> id /* (NSString) */ { + msg_send![self, user] + } + + // unsafe fn resourceValuesForKeys_error_ + // unsafe fn getResourceValue_forKey_error_ + // unsafe fn setResourceValue_forKey_error_ + // unsafe fn setResourceValues_error_ + // unsafe fn removeAllCachedResourceValues + // unsafe fn removeCachedResourceValueForKey_ + // unsafe fn setTemporaryResourceValue_forKey_ + unsafe fn NSURLResourceKey(self) -> id /* (NSString) */ { + msg_send![self, NSURLResourceKey] + } + + unsafe fn filePathURL(self) -> id { + msg_send![self, filePathURL] + } + unsafe fn fileReferenceURL(self) -> id { + msg_send![self, fileReferenceURL] + } + unsafe fn URLByAppendingPathComponent_(self, path_component: id /* (NSString) */) -> id { + msg_send![self, URLByAppendingPathComponent:path_component] + } + unsafe fn URLByAppendingPathComponent_isDirectory_(self, path_component: id /* (NSString) */, is_dir: BOOL) -> id { + msg_send![self, URLByAppendingPathComponent:path_component isDirectory:is_dir] + } + unsafe fn URLByAppendingPathExtension_(self, extension: id /* (NSString) */) -> id { + msg_send![self, URLByAppendingPathExtension:extension] + } + unsafe fn URLByDeletingLastPathComponent(self) -> id { + msg_send![self, URLByDeletingLastPathComponent] + } + unsafe fn URLByDeletingPathExtension(self) -> id { + msg_send![self, URLByDeletingPathExtension] + } + unsafe fn URLByResolvingSymlinksInPath(self) -> id { + msg_send![self, URLByResolvingSymlinksInPath] + } + unsafe fn URLByStandardizingPath(self) -> id { + msg_send![self, URLByStandardizingPath] + } + unsafe fn hasDirectoryPath(self) -> BOOL { + msg_send![self, hasDirectoryPath] + } + + unsafe fn bookmarkDataWithContentsOfURL_error_(_:Self, url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + msg_send![class!(NSURL), bookmarkDataWithContentsOfURL:url error:error] + } + unsafe fn bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(self, options: NSURLBookmarkCreationOptions, resource_value_for_keys: id /* (NSArray) */, relative_to_url: id, error: id /* (NSError _Nullable) */) -> id /* (NSData) */ { + msg_send![self, bookmarkDataWithOptions:options includingResourceValuesForKeys:resource_value_for_keys relativeToURL:relative_to_url error:error] + } + // unsafe fn resourceValuesForKeys_fromBookmarkData_ + unsafe fn writeBookmarkData_toURL_options_error_(_:Self, data: id /* (NSData) */, to_url: id, options: NSURLBookmarkFileCreationOptions, error: id /* (NSError _Nullable) */) -> id { + msg_send![class!(NSURL), writeBookmarkData:data toURL:to_url options:options error:error] + } + unsafe fn startAccessingSecurityScopedResource(self) -> BOOL { + msg_send![self, startAccessingSecurityScopedResource] + } + unsafe fn stopAccessingSecurityScopedResource(self) { + msg_send![self, stopAccessingSecurityScopedResource] + } + unsafe fn NSURLBookmarkFileCreationOptions(self) -> NSURLBookmarkFileCreationOptions { + msg_send![self, NSURLBookmarkFileCreationOptions] + } + unsafe fn NSURLBookmarkCreationOptions(self) -> NSURLBookmarkCreationOptions { + msg_send![self, NSURLBookmarkCreationOptions] + } + unsafe fn NSURLBookmarkResolutionOptions(self) -> NSURLBookmarkResolutionOptions { + msg_send![self, NSURLBookmarkResolutionOptions] + } + + // unsafe fn checkPromisedItemIsReachableAndReturnError_ + // unsafe fn getPromisedItemResourceValue_forKey_error_ + // unsafe fn promisedItemResourceValuesForKeys_error_ + + // unsafe fn URLFromPasteboard_ + // unsafe fn writeToPasteboard_ +} + +pub trait NSBundle: Sized { + unsafe fn mainBundle() -> Self; + + unsafe fn loadNibNamed_owner_topLevelObjects_(self, + name: id /* NSString */, + owner: id, + topLevelObjects: *mut id /* NSArray */) -> BOOL; +} + +impl NSBundle for id { + unsafe fn mainBundle() -> id { + msg_send![class!(NSBundle), mainBundle] + } + + unsafe fn loadNibNamed_owner_topLevelObjects_(self, + name: id /* NSString */, + owner: id, + topLevelObjects: *mut id /* NSArray* */) -> BOOL { + msg_send![self, loadNibNamed:name + owner:owner + topLevelObjects:topLevelObjects] + } +} + +pub trait NSData: Sized { + unsafe fn data(_: Self) -> id { + msg_send![class!(NSData), data] + } + + unsafe fn dataWithBytes_length_(_: Self, bytes: *const c_void, length: NSUInteger) -> id { + msg_send![class!(NSData), dataWithBytes:bytes length:length] + } + + unsafe fn dataWithBytesNoCopy_length_(_: Self, bytes: *const c_void, length: NSUInteger) -> id { + msg_send![class!(NSData), dataWithBytesNoCopy:bytes length:length] + } + + unsafe fn dataWithBytesNoCopy_length_freeWhenDone_(_: Self, bytes: *const c_void, + length: NSUInteger, freeWhenDone: BOOL) -> id { + msg_send![class!(NSData), dataWithBytesNoCopy:bytes length:length freeWhenDone:freeWhenDone] + } + + unsafe fn dataWithContentsOfFile_(_: Self, path: id) -> id { + msg_send![class!(NSData), dataWithContentsOfFile:path] + } + + unsafe fn dataWithContentsOfFile_options_error_(_: Self, path: id, mask: NSDataReadingOptions, + errorPtr: *mut id) -> id { + msg_send![class!(NSData), dataWithContentsOfFile:path options:mask error:errorPtr] + } + + unsafe fn dataWithContentsOfURL_(_: Self, aURL: id) -> id { + msg_send![class!(NSData), dataWithContentsOfURL:aURL] + } + + unsafe fn dataWithContentsOfURL_options_error_(_: Self, aURL: id, mask: NSDataReadingOptions, + errorPtr: *mut id) -> id { + msg_send![class!(NSData), dataWithContentsOfURL:aURL options:mask error:errorPtr] + } + + unsafe fn dataWithData_(_: Self, aData: id) -> id { + msg_send![class!(NSData), dataWithData:aData] + } + + unsafe fn initWithBase64EncodedData_options_(self, base64Data: id, options: NSDataBase64DecodingOptions) + -> id; + unsafe fn initWithBase64EncodedString_options_(self, base64String: id, options: NSDataBase64DecodingOptions) + -> id; + unsafe fn initWithBytes_length_(self, bytes: *const c_void, length: NSUInteger) -> id; + unsafe fn initWithBytesNoCopy_length_(self, bytes: *const c_void, length: NSUInteger) -> id; + unsafe fn initWithBytesNoCopy_length_deallocator_(self, bytes: *const c_void, length: NSUInteger, + deallocator: *mut Block<(*const c_void, NSUInteger), ()>) + -> id; + unsafe fn initWithBytesNoCopy_length_freeWhenDone_(self, bytes: *const c_void, + length: NSUInteger, freeWhenDone: BOOL) -> id; + unsafe fn initWithContentsOfFile_(self, path: id) -> id; + unsafe fn initWithContentsOfFile_options_error(self, path: id, mask: NSDataReadingOptions, errorPtr: *mut id) + -> id; + unsafe fn initWithContentsOfURL_(self, aURL: id) -> id; + unsafe fn initWithContentsOfURL_options_error_(self, aURL: id, mask: NSDataReadingOptions, errorPtr: *mut id) + -> id; + unsafe fn initWithData_(self, data: id) -> id; + + unsafe fn bytes(self) -> *const c_void; + unsafe fn description(self) -> id; + unsafe fn enumerateByteRangesUsingBlock_(self, block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>); + unsafe fn getBytes_length_(self, buffer: *mut c_void, length: NSUInteger); + unsafe fn getBytes_range_(self, buffer: *mut c_void, range: NSRange); + unsafe fn subdataWithRange_(self, range: NSRange) -> id; + unsafe fn rangeOfData_options_range_(self, dataToFind: id, options: NSDataSearchOptions, searchRange: NSRange) + -> NSRange; + + unsafe fn base64EncodedDataWithOptions_(self, options: NSDataBase64EncodingOptions) -> id; + unsafe fn base64EncodedStringWithOptions_(self, options: NSDataBase64EncodingOptions) -> id; + + unsafe fn isEqualToData_(self, otherData: id) -> id; + unsafe fn length(self) -> NSUInteger; + + unsafe fn writeToFile_atomically_(self, path: id, atomically: BOOL) -> BOOL; + unsafe fn writeToFile_options_error_(self, path: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL; + unsafe fn writeToURL_atomically_(self, aURL: id, atomically: BOOL) -> BOOL; + unsafe fn writeToURL_options_error_(self, aURL: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL; +} + +impl NSData for id { + unsafe fn initWithBase64EncodedData_options_(self, base64Data: id, options: NSDataBase64DecodingOptions) + -> id { + msg_send![self, initWithBase64EncodedData:base64Data options:options] + } + + unsafe fn initWithBase64EncodedString_options_(self, base64String: id, options: NSDataBase64DecodingOptions) + -> id { + msg_send![self, initWithBase64EncodedString:base64String options:options] + } + + unsafe fn initWithBytes_length_(self, bytes: *const c_void, length: NSUInteger) -> id { + msg_send![self,initWithBytes:bytes length:length] + } + + unsafe fn initWithBytesNoCopy_length_(self, bytes: *const c_void, length: NSUInteger) -> id { + msg_send![self, initWithBytesNoCopy:bytes length:length] + } + + unsafe fn initWithBytesNoCopy_length_deallocator_(self, bytes: *const c_void, length: NSUInteger, + deallocator: *mut Block<(*const c_void, NSUInteger), ()>) + -> id { + msg_send![self, initWithBytesNoCopy:bytes length:length deallocator:deallocator] + } + + unsafe fn initWithBytesNoCopy_length_freeWhenDone_(self, bytes: *const c_void, + length: NSUInteger, freeWhenDone: BOOL) -> id { + msg_send![self, initWithBytesNoCopy:bytes length:length freeWhenDone:freeWhenDone] + } + + unsafe fn initWithContentsOfFile_(self, path: id) -> id { + msg_send![self, initWithContentsOfFile:path] + } + + unsafe fn initWithContentsOfFile_options_error(self, path: id, mask: NSDataReadingOptions, errorPtr: *mut id) + -> id { + msg_send![self, initWithContentsOfFile:path options:mask error:errorPtr] + } + + unsafe fn initWithContentsOfURL_(self, aURL: id) -> id { + msg_send![self, initWithContentsOfURL:aURL] + } + + unsafe fn initWithContentsOfURL_options_error_(self, aURL: id, mask: NSDataReadingOptions, errorPtr: *mut id) + -> id { + msg_send![self, initWithContentsOfURL:aURL options:mask error:errorPtr] + } + + unsafe fn initWithData_(self, data: id) -> id { + msg_send![self, initWithData:data] + } + + unsafe fn bytes(self) -> *const c_void { + msg_send![self, bytes] + } + + unsafe fn description(self) -> id { + msg_send![self, description] + } + + unsafe fn enumerateByteRangesUsingBlock_(self, block: *mut Block<(*const c_void, NSRange, *mut BOOL), ()>) { + msg_send![self, enumerateByteRangesUsingBlock:block] + } + + unsafe fn getBytes_length_(self, buffer: *mut c_void, length: NSUInteger) { + msg_send![self, getBytes:buffer length:length] + } + + unsafe fn getBytes_range_(self, buffer: *mut c_void, range: NSRange) { + msg_send![self, getBytes:buffer range:range] + } + + unsafe fn subdataWithRange_(self, range: NSRange) -> id { + msg_send![self, subdataWithRange:range] + } + + unsafe fn rangeOfData_options_range_(self, dataToFind: id, options: NSDataSearchOptions, searchRange: NSRange) + -> NSRange { + msg_send![self, rangeOfData:dataToFind options:options range:searchRange] + } + + unsafe fn base64EncodedDataWithOptions_(self, options: NSDataBase64EncodingOptions) -> id { + msg_send![self, base64EncodedDataWithOptions:options] + } + + unsafe fn base64EncodedStringWithOptions_(self, options: NSDataBase64EncodingOptions) -> id { + msg_send![self, base64EncodedStringWithOptions:options] + } + + unsafe fn isEqualToData_(self, otherData: id) -> id { + msg_send![self, isEqualToData:otherData] + } + + unsafe fn length(self) -> NSUInteger { + msg_send![self, length] + } + + unsafe fn writeToFile_atomically_(self, path: id, atomically: BOOL) -> BOOL { + msg_send![self, writeToFile:path atomically:atomically] + } + + unsafe fn writeToFile_options_error_(self, path: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL { + msg_send![self, writeToFile:path options:mask error:errorPtr] + } + + unsafe fn writeToURL_atomically_(self, aURL: id, atomically: BOOL) -> BOOL { + msg_send![self, writeToURL:aURL atomically:atomically] + } + + unsafe fn writeToURL_options_error_(self, aURL: id, mask: NSDataWritingOptions, errorPtr: *mut id) -> BOOL { + msg_send![self, writeToURL:aURL options:mask error:errorPtr] + } +} + +bitflags! { + pub struct NSDataReadingOptions: libc::c_ulonglong { + const NSDataReadingMappedIfSafe = 1 << 0; + const NSDataReadingUncached = 1 << 1; + const NSDataReadingMappedAlways = 1 << 3; + } +} + +bitflags! { + pub struct NSDataBase64EncodingOptions: libc::c_ulonglong { + const NSDataBase64Encoding64CharacterLineLength = 1 << 0; + const NSDataBase64Encoding76CharacterLineLength = 1 << 1; + const NSDataBase64EncodingEndLineWithCarriageReturn = 1 << 4; + const NSDataBase64EncodingEndLineWithLineFeed = 1 << 5; + } +} + +bitflags! { + pub struct NSDataBase64DecodingOptions: libc::c_ulonglong { + const NSDataBase64DecodingIgnoreUnknownCharacters = 1 << 0; + } +} + +bitflags! { + pub struct NSDataWritingOptions: libc::c_ulonglong { + const NSDataWritingAtomic = 1 << 0; + const NSDataWritingWithoutOverwriting = 1 << 1; + } +} + +bitflags! { + pub struct NSDataSearchOptions: libc::c_ulonglong { + const NSDataSearchBackwards = 1 << 0; + const NSDataSearchAnchored = 1 << 1; + } +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/lib.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/lib.rs new file mode 100644 index 0000000..4c5cce0 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/lib.rs @@ -0,0 +1,32 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_name = "cocoa"] +#![crate_type = "rlib"] + +#![allow(non_snake_case)] + +extern crate block; +#[macro_use] +extern crate bitflags; +extern crate core_foundation; +extern crate core_graphics; +extern crate foreign_types; +extern crate libc; +#[macro_use] +extern crate objc; + +#[cfg(target_os = "macos")] +pub mod appkit; +pub mod base; +pub mod foundation; +#[cfg(target_os = "macos")] +pub mod quartzcore; +#[macro_use] +mod macros; diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/macros.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/macros.rs new file mode 100644 index 0000000..77c6a16 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/macros.rs @@ -0,0 +1,79 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Creates a Cocoa delegate to use e.g. with `NSWindow.setDelegate_`. +/// Adds instance variables and methods to the definition. +/// +/// # Example with NSWindowDelegate +/// ``` no_run +/// #[macro_use] extern crate cocoa; +/// #[macro_use] extern crate objc; +/// +/// use cocoa::appkit::NSWindow; +/// use cocoa::base::{id, nil}; +/// +/// use objc::runtime::{Object, Sel}; +/// +/// # fn main() { +/// unsafe { +/// let my_window: id = NSWindow::alloc(nil); +/// +/// extern fn on_enter_fullscreen(this: &Object, _cmd: Sel, _notification: id) { +/// unsafe { +/// let window: id = *this.get_ivar("window"); +/// window.setToolbar_(nil); +/// } +/// } +/// +/// my_window.setDelegate_(delegate!("MyWindowDelegate", { +/// window: id = my_window, // Declare instance variable(s) +/// (onWindowWillEnterFullscreen:) => on_enter_fullscreen as extern fn(&Object, Sel, id) // Declare function(s) +/// })); +/// } +/// # } +/// ``` +#[macro_export] +macro_rules! delegate { + ( + $name:expr, { + $( ($($sel:ident :)+) => $func:expr),* + } + ) => ( + delegate!($name, { + , + $( ($($sel :)+) => $func),* + }) + ); + + ( + $name:expr, { + $($var:ident : $var_type:ty = $value:expr),* , + $( ($($sel:ident :)+) => $func:expr),* + } + ) => ({ + let mut decl = objc::declare::ClassDecl::new($name, class!(NSObject)).unwrap(); + + $( + decl.add_ivar::<$var_type>(stringify!($var)); + )* + + $( + decl.add_method(sel!($($sel :)+), $func); + )* + + let cl = decl.register(); + let delegate: id = msg_send![cl, alloc]; + + $( + (*delegate).set_ivar(stringify!($var), $value); + )* + + delegate + }); +} diff --git a/third_party/cargo/vendor/cocoa-0.20.0/src/quartzcore.rs b/third_party/cargo/vendor/cocoa-0.20.0/src/quartzcore.rs new file mode 100644 index 0000000..5a63f4a --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/src/quartzcore.rs @@ -0,0 +1,1859 @@ +// Copyright 2018 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::base::{CFType, CFTypeRef, TCFType}; +use core_foundation::date::CFTimeInterval; +use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; +use core_foundation::string::{CFString, CFStringRef}; +use core_graphics::base::CGFloat; +use core_graphics::color::{CGColor, SysCGColorRef}; +use core_graphics::color_space::CGColorSpace; +use core_graphics::context::CGContext; +use core_graphics::geometry::{CGAffineTransform, CGPoint, CGRect, CGSize}; +use core_graphics::path::{CGPath, SysCGPathRef}; +use foreign_types::ForeignType; +use std::ops::Mul; +use std::ptr; + +use appkit::CGLContextObj; +use base::{BOOL, id, nil, YES}; +use foundation::NSUInteger; + +// CABase.h + +pub fn current_media_time() -> CFTimeInterval { + unsafe { + CACurrentMediaTime() + } +} + +// CALayer.h + +pub struct CALayer(id); + +unsafe impl Send for CALayer {} +unsafe impl Sync for CALayer {} + +impl Clone for CALayer { + #[inline] + fn clone(&self) -> CALayer { + unsafe { + CALayer(msg_send![self.id(), retain]) + } + } +} + +impl Drop for CALayer { + #[inline] + fn drop(&mut self) { + unsafe { + msg_send![self.id(), release] + } + } +} + +impl CALayer { + #[inline] + pub fn id(&self) -> id { + self.0 + } + + #[inline] + pub fn new() -> CALayer { + unsafe { + CALayer(msg_send![class!(CALayer), layer]) + } + } + + #[inline] + pub fn from_layer(other: &CALayer) -> CALayer { + unsafe { + let layer: id = msg_send![class!(CALayer), alloc]; + CALayer(msg_send![layer, initWithLayer:other.id()]) + } + } + + #[inline] + pub fn presentation_layer(&self) -> CALayer { + unsafe { + CALayer(msg_send![self.id(), presentationLayer]) + } + } + + #[inline] + pub fn model_layer(&self) -> CALayer { + unsafe { + CALayer(msg_send![self.id(), modelLayer]) + } + } + + #[inline] + pub fn default_value_for_key(key: &CFString) -> id { + unsafe { + msg_send![class!(CALayer), defaultValueForKey:(key.as_CFTypeRef())] + } + } + + #[inline] + pub fn needs_display_for_key(key: &CFString) -> bool { + unsafe { + let flag: BOOL = msg_send![class!(CALayer), needsDisplayForKey:(key.as_CFTypeRef())]; + flag == YES + } + } + + #[inline] + pub fn should_archive_value_for_key(key: &CFString) -> bool { + unsafe { + let flag: BOOL = msg_send![class!(CALayer), shouldArchiveValueForKey:(key.as_CFTypeRef())]; + flag == YES + } + } + + #[inline] + pub fn bounds(&self) -> CGRect { + unsafe { + msg_send![self.id(), bounds] + } + } + + #[inline] + pub fn set_bounds(&self, bounds: &CGRect) { + unsafe { + msg_send![self.id(), setBounds:*bounds] + } + } + + #[inline] + pub fn position(&self) -> CGPoint { + unsafe { + msg_send![self.id(), position] + } + } + + #[inline] + pub fn set_position(&self, position: &CGPoint) { + unsafe { + msg_send![self.id(), setPosition:*position] + } + } + + #[inline] + pub fn z_position(&self) -> CGFloat { + unsafe { + msg_send![self.id(), zPosition] + } + } + + #[inline] + pub fn set_z_position(&self, z_position: CGFloat) { + unsafe { + msg_send![self.id(), setZPosition:z_position] + } + } + + #[inline] + pub fn anchor_point(&self) -> CGPoint { + unsafe { + msg_send![self.id(), anchorPoint] + } + } + + #[inline] + pub fn set_anchor_point(&self, anchor_point: &CGPoint) { + unsafe { + msg_send![self.id(), setAnchorPoint:*anchor_point] + } + } + + #[inline] + pub fn anchor_point_z(&self) -> CGFloat { + unsafe { + msg_send![self.id(), anchorPointZ] + } + } + + #[inline] + pub fn set_anchor_point_z(&self, anchor_point_z: CGFloat) { + unsafe { + msg_send![self.id(), setAnchorPointZ:anchor_point_z] + } + } + + #[inline] + pub fn transform(&self) -> CATransform3D { + unsafe { + msg_send![self.id(), transform] + } + } + + #[inline] + pub fn set_transform(&self, transform: &CATransform3D) { + unsafe { + msg_send![self.id(), setTransform:*transform] + } + } + + #[inline] + pub fn affine_transform(&self) -> CGAffineTransform { + unsafe { + msg_send![self.id(), affineTransform] + } + } + + #[inline] + pub fn set_affine_transform(&self, affine_transform: &CGAffineTransform) { + unsafe { + msg_send![self.id(), setAffineTransform:*affine_transform] + } + } + + #[inline] + pub fn frame(&self) -> CGRect { + unsafe { + msg_send![self.id(), frame] + } + } + + #[inline] + pub fn set_frame(&self, frame: &CGRect) { + unsafe { + msg_send![self.id(), setFrame:*frame] + } + } + + #[inline] + pub fn is_hidden(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), isHidden]; + flag == YES + } + } + + #[inline] + pub fn set_hidden(&self, hidden: bool) { + unsafe { + msg_send![self.id(), setHidden:hidden as BOOL] + } + } + + #[inline] + pub fn is_double_sided(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), isDoubleSided]; + flag == YES + } + } + + #[inline] + pub fn set_double_sided(&self, double_sided: bool) { + unsafe { + msg_send![self.id(), setDoubleSided:double_sided as BOOL] + } + } + + #[inline] + pub fn is_geometry_flipped(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), isGeometryFlipped]; + flag == YES + } + } + + #[inline] + pub fn set_geometry_flipped(&self, geometry_flipped: bool) { + unsafe { + msg_send![self.id(), setGeometryFlipped:geometry_flipped as BOOL] + } + } + + #[inline] + pub fn contents_are_flipped(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), contentsAreFlipped]; + flag == YES + } + } + + #[inline] + pub fn superlayer(&self) -> Option { + unsafe { + let superlayer: id = msg_send![self.id(), superlayer]; + if superlayer.is_null() { + None + } else { + Some(CALayer(superlayer)) + } + } + } + + #[inline] + pub fn remove_from_superlayer(&self) { + unsafe { + msg_send![self.id(), removeFromSuperlayer] + } + } + + #[inline] + pub fn sublayers(&self) -> CFArray { + unsafe { + let sublayers: CFArrayRef = msg_send![self.id(), sublayers]; + TCFType::wrap_under_create_rule(sublayers) + } + } + + #[inline] + pub fn add_sublayer(&self, sublayer: &CALayer) { + unsafe { + msg_send![self.id(), addSublayer:sublayer.id()] + } + } + + #[inline] + pub fn insert_sublayer_at_index(&self, sublayer: &CALayer, index: u32) { + unsafe { + msg_send![self.id(), insertSublayer:sublayer.id() atIndex:index] + } + } + + #[inline] + pub fn insert_sublayer_below(&self, sublayer: &CALayer, sibling: &CALayer) { + unsafe { + msg_send![self.id(), insertSublayer:sublayer.id() below:sibling.id()] + } + } + + #[inline] + pub fn insert_sublayer_above(&self, sublayer: &CALayer, sibling: &CALayer) { + unsafe { + msg_send![self.id(), insertSublayer:sublayer.id() above:sibling.id()] + } + } + + #[inline] + pub fn replace_sublayer_with(&self, old_layer: &CALayer, new_layer: &CALayer) { + unsafe { + msg_send![self.id(), replaceSublayer:old_layer.id() with:new_layer.id()] + } + } + + #[inline] + pub fn sublayer_transform(&self) -> CATransform3D { + unsafe { + msg_send![self.id(), sublayerTransform] + } + } + + #[inline] + pub fn set_sublayer_transform(&self, sublayer_transform: CATransform3D) { + unsafe { + msg_send![self.id(), setSublayerTransform:sublayer_transform] + } + } + + #[inline] + pub fn mask(&self) -> Option { + unsafe { + let mask: id = msg_send![self.id(), mask]; + if mask.is_null() { + None + } else { + Some(CALayer(mask)) + } + } + } + + #[inline] + pub fn set_mask(&self, mask: Option) { + unsafe { + match mask { + None => msg_send![self.id(), setMask:nil], + Some(mask) => msg_send![self.id(), setMask:(mask.id())], + } + } + } + + #[inline] + pub fn masks_to_bounds(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), masksToBounds]; + flag == YES + } + } + + #[inline] + pub fn set_masks_to_bounds(&self, flag: bool) { + unsafe { + msg_send![self.id(), setMasksToBounds:flag as BOOL] + } + } + + #[inline] + pub fn convert_point_from_layer(&self, point: &CGPoint, layer: Option) -> CGPoint { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertPoint:*point fromLayer:layer] + } + } + + #[inline] + pub fn convert_point_to_layer(&self, point: &CGPoint, layer: Option) -> CGPoint { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertPoint:*point toLayer:layer] + } + } + + #[inline] + pub fn convert_rect_from_layer(&self, rect: &CGRect, layer: Option) -> CGRect { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertRect:*rect fromLayer:layer] + } + } + + #[inline] + pub fn convert_rect_to_layer(&self, rect: &CGRect, layer: Option) -> CGRect { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertRect:*rect toLayer:layer] + } + } + + #[inline] + pub fn convert_time_from_layer(&self, time: CFTimeInterval, layer: Option) + -> CFTimeInterval { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertTime:time fromLayer:layer] + } + } + + #[inline] + pub fn convert_time_to_layer(&self, time: CFTimeInterval, layer: Option) + -> CFTimeInterval { + unsafe { + let layer = match layer { + None => nil, + Some(ref layer) => layer.id(), + }; + msg_send![self.id(), convertTime:time toLayer:layer] + } + } + + #[inline] + pub fn hit_test(&self, point: &CGPoint) -> Option { + unsafe { + let layer: id = msg_send![self.id(), hitTest:*point]; + if layer == nil { + None + } else { + Some(CALayer(layer)) + } + } + } + + #[inline] + pub fn contains_point(&self, point: &CGPoint) -> bool { + unsafe { + let result: BOOL = msg_send![self.id(), containsPoint:*point]; + result == YES + } + } + + #[inline] + pub fn contents(&self) -> id { + unsafe { + msg_send![self.id(), contents] + } + } + + #[inline] + pub unsafe fn set_contents(&self, contents: id) { + msg_send![self.id(), setContents:contents] + } + + #[inline] + pub fn contents_rect(&self) -> CGRect { + unsafe { + msg_send![self.id(), contentsRect] + } + } + + #[inline] + pub fn set_contents_rect(&self, contents_rect: &CGRect) { + unsafe { + msg_send![self.id(), setContentsRect:*contents_rect] + } + } + + #[inline] + pub fn contents_gravity(&self) -> ContentsGravity { + unsafe { + let string: CFStringRef = msg_send![self.id(), contentsGravity]; + ContentsGravity::from_CFString(TCFType::wrap_under_create_rule(string)) + } + } + + #[inline] + pub fn set_contents_gravity(&self, new_contents_gravity: ContentsGravity) { + unsafe { + let contents_gravity: CFString = new_contents_gravity.into_CFString(); + msg_send![self.id(), setContentsGravity:contents_gravity.as_CFTypeRef()] + } + } + + #[inline] + pub fn contents_scale(&self) -> CGFloat { + unsafe { + msg_send![self.id(), contentsScale] + } + } + + #[inline] + pub fn set_contents_scale(&self, new_contents_scale: CGFloat) { + unsafe { + msg_send![self.id(), setContentsScale:new_contents_scale] + } + } + + #[inline] + pub fn contents_center(&self) -> CGRect { + unsafe { + msg_send![self.id(), contentsCenter] + } + } + + #[inline] + pub fn set_contents_center(&self, new_rect: &CGRect) { + unsafe { + msg_send![self.id(), setContentsCenter:*new_rect] + } + } + + #[inline] + pub fn contents_format(&self) -> ContentsFormat { + unsafe { + let string: CFStringRef = msg_send![self.id(), contentsFormat]; + ContentsFormat::from_CFString(TCFType::wrap_under_create_rule(string)) + } + } + + #[inline] + pub fn set_contents_format(&self, new_contents_format: ContentsFormat) { + unsafe { + let contents_format: CFString = new_contents_format.into_CFString(); + msg_send![self.id(), setContentsFormat:contents_format.as_CFTypeRef()] + } + } + + #[inline] + pub fn minification_filter(&self) -> Filter { + unsafe { + let string: CFStringRef = msg_send![self.id(), minificationFilter]; + Filter::from_CFString(TCFType::wrap_under_create_rule(string)) + } + } + + #[inline] + pub fn set_minification_filter(&self, new_filter: Filter) { + unsafe { + let filter: CFString = new_filter.into_CFString(); + msg_send![self.id(), setMinificationFilter:filter.as_CFTypeRef()] + } + } + + #[inline] + pub fn magnification_filter(&self) -> Filter { + unsafe { + let string: CFStringRef = msg_send![self.id(), magnificationFilter]; + Filter::from_CFString(TCFType::wrap_under_create_rule(string)) + } + } + + #[inline] + pub fn set_magnification_filter(&self, new_filter: Filter) { + unsafe { + let filter: CFString = new_filter.into_CFString(); + msg_send![self.id(), setMagnificationFilter:filter.as_CFTypeRef()] + } + } + + #[inline] + pub fn minification_filter_bias(&self) -> f32 { + unsafe { + msg_send![self.id(), minificationFilterBias] + } + } + + #[inline] + pub fn set_minification_filter_bias(&self, new_filter_bias: f32) { + unsafe { + msg_send![self.id(), setMinificationFilterBias:new_filter_bias] + } + } + + #[inline] + pub fn is_opaque(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), isOpaque]; + flag == YES + } + } + + #[inline] + pub fn set_opaque(&self, opaque: bool) { + unsafe { + msg_send![self.id(), setOpaque:opaque as BOOL] + } + } + + #[inline] + pub fn display(&self) { + unsafe { + msg_send![self.id(), display] + } + } + + #[inline] + pub fn set_needs_display(&self) { + unsafe { + msg_send![self.id(), setNeedsDisplay] + } + } + + #[inline] + pub fn set_needs_display_in_rect(&self, rect: &CGRect) { + unsafe { + msg_send![self.id(), setNeedsDisplayInRect:*rect] + } + } + + #[inline] + pub fn needs_display(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), needsDisplay]; + flag == YES + } + } + + #[inline] + pub fn display_if_needed(&self) { + unsafe { + msg_send![self.id(), displayIfNeeded] + } + } + + #[inline] + pub fn needs_display_on_bounds_change(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), needsDisplayOnBoundsChange]; + flag == YES + } + } + + #[inline] + pub fn set_needs_display_on_bounds_change(&self, flag: bool) { + unsafe { + msg_send![self.id(), setNeedsDisplayOnBoundsChange:flag as BOOL] + } + } + + #[inline] + pub fn draws_asynchronously(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), drawsAsynchronously]; + flag == YES + } + } + + #[inline] + pub fn set_draws_asynchronously(&self, flag: bool) { + unsafe { + msg_send![self.id(), setDrawsAsynchronously:flag as BOOL] + } + } + + #[inline] + pub fn draw_in_context(&self, context: &CGContext) { + unsafe { + msg_send![self.id(), drawInContext:(*context).as_ptr()] + } + } + + #[inline] + pub fn render_in_context(&self, context: &CGContext) { + unsafe { + msg_send![self.id(), renderInContext:(*context).as_ptr()] + } + } + + #[inline] + pub fn edge_antialiasing_mask(&self) -> EdgeAntialiasingMask { + unsafe { + EdgeAntialiasingMask::from_bits_truncate(msg_send![self.id(), edgeAntialiasingMask]) + } + } + + #[inline] + pub fn set_edge_antialiasing_mask(&self, mask: EdgeAntialiasingMask) { + unsafe { + msg_send![self.id(), setEdgeAntialiasingMask:mask.bits()] + } + } + + #[inline] + pub fn background_color(&self) -> Option { + unsafe { + let color: SysCGColorRef = msg_send![self.id(), backgroundColor]; + if color.is_null() { + None + } else { + Some(CGColor::wrap_under_get_rule(color)) + } + } + } + + #[inline] + pub fn set_background_color(&self, color: Option) { + unsafe { + let color = match color { + None => ptr::null(), + Some(color) => color.as_CFTypeRef(), + }; + msg_send![self.id(), setBackgroundColor:color] + } + } + + #[inline] + pub fn corner_radius(&self) -> CGFloat { + unsafe { + msg_send![self.id(), cornerRadius] + } + } + + #[inline] + pub fn set_corner_radius(&self, radius: CGFloat) { + unsafe { + msg_send![self.id(), setCornerRadius:radius] + } + } + + #[inline] + pub fn masked_corners(&self) -> CornerMask { + unsafe { + CornerMask::from_bits_truncate(msg_send![self.id(), maskedCorners]) + } + } + + #[inline] + pub fn set_masked_corners(&self, mask: CornerMask) { + unsafe { + msg_send![self.id(), setCornerMask:mask.bits()] + } + } + + #[inline] + pub fn border_width(&self) -> CGFloat { + unsafe { + msg_send![self.id(), borderWidth] + } + } + + #[inline] + pub fn set_border_width(&self, border_width: CGFloat) { + unsafe { + msg_send![self.id(), setBorderWidth:border_width] + } + } + + #[inline] + pub fn border_color(&self) -> Option { + unsafe { + let color: SysCGColorRef = msg_send![self.id(), borderColor]; + if color.is_null() { + None + } else { + Some(CGColor::wrap_under_get_rule(color)) + } + } + } + + #[inline] + pub fn set_border_color(&self, color: Option) { + unsafe { + let color = match color { + None => ptr::null(), + Some(color) => color.as_CFTypeRef(), + }; + msg_send![self.id(), setBorderColor:color] + } + } + + #[inline] + pub fn opacity(&self) -> f32 { + unsafe { + msg_send![self.id(), opacity] + } + } + + #[inline] + pub fn set_opacity(&self, opacity: f32) { + unsafe { + msg_send![self.id(), setOpacity:opacity] + } + } + + #[inline] + pub fn compositing_filter(&self) -> id { + unsafe { + msg_send![self.id(), compositingFilter] + } + } + + #[inline] + pub unsafe fn set_compositing_filter(&self, filter: id) { + msg_send![self.id(), setCompositingFilter:filter] + } + + #[inline] + pub unsafe fn filters(&self) -> Option { + let filters: CFArrayRef = msg_send![self.id(), filters]; + if filters.is_null() { + None + } else { + Some(CFArray::wrap_under_get_rule(filters)) + } + } + + #[inline] + pub unsafe fn set_filters(&self, filters: Option) { + let filters: CFTypeRef = match filters { + Some(ref filters) => filters.as_CFTypeRef(), + None => ptr::null(), + }; + msg_send![self.id(), setFilters:filters] + } + + #[inline] + pub unsafe fn background_filters(&self) -> Option { + let filters: CFArrayRef = msg_send![self.id(), backgroundFilters]; + if filters.is_null() { + None + } else { + Some(CFArray::wrap_under_get_rule(filters)) + } + } + + #[inline] + pub unsafe fn set_background_filters(&self, filters: Option) { + let filters: CFTypeRef = match filters { + Some(ref filters) => filters.as_CFTypeRef(), + None => ptr::null(), + }; + msg_send![self.id(), setBackgroundFilters:filters] + } + + #[inline] + pub fn should_rasterize(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), shouldRasterize]; + flag == YES + } + } + + #[inline] + pub fn set_should_rasterize(&self, flag: bool) { + unsafe { + msg_send![self.id(), setShouldRasterize:(flag as BOOL)] + } + } + + #[inline] + pub fn rasterization_scale(&self) -> CGFloat { + unsafe { + msg_send![self.id(), rasterizationScale] + } + } + + #[inline] + pub fn set_rasterization_scale(&self, scale: CGFloat) { + unsafe { + msg_send![self.id(), setRasterizationScale:scale] + } + } + + // Shadow properties + + #[inline] + pub fn shadow_color(&self) -> Option { + unsafe { + let color: SysCGColorRef = msg_send![self.id(), shadowColor]; + if color.is_null() { + None + } else { + Some(CGColor::wrap_under_get_rule(color)) + } + } + } + + #[inline] + pub fn set_shadow_color(&self, color: Option) { + unsafe { + let color = match color { + None => ptr::null(), + Some(color) => color.as_CFTypeRef(), + }; + msg_send![self.id(), setShadowColor:color] + } + } + + #[inline] + pub fn shadow_opacity(&self) -> f32 { + unsafe { + msg_send![self.id(), shadowOpacity] + } + } + + #[inline] + pub fn set_shadow_opacity(&self, opacity: f32) { + unsafe { + msg_send![self.id(), setShadowOpacity:opacity] + } + } + + #[inline] + pub fn shadow_offset(&self) -> CGSize { + unsafe { + msg_send![self.id(), shadowOffset] + } + } + + #[inline] + pub fn set_shadow_offset(&self, offset: &CGSize) { + unsafe { + msg_send![self.id(), setShadowOffset:*offset] + } + } + + #[inline] + pub fn shadow_radius(&self) -> CGFloat { + unsafe { + msg_send![self.id(), shadowRadius] + } + } + + #[inline] + pub fn set_shadow_radius(&self, radius: CGFloat) { + unsafe { + msg_send![self.id(), setShadowRadius:radius] + } + } + + #[inline] + pub fn shadow_path(&self) -> Option { + unsafe { + let path: SysCGPathRef = msg_send![self.id(), shadowPath]; + if path.is_null() { + None + } else { + Some(CGPath::from_ptr(path)) + } + } + } + + #[inline] + pub fn set_shadow_path(&self, path: Option) { + unsafe { + let sys_path_ref = match path { + None => ptr::null(), + Some(path) => path.as_ptr(), + }; + msg_send![self.id(), setShadowPath:sys_path_ref] + } + } + + // Layout methods + + #[inline] + pub fn autoresizing_mask(&self) -> AutoresizingMask { + unsafe { + AutoresizingMask::from_bits_truncate(msg_send![self.id(), autoresizingMask]) + } + } + + #[inline] + pub fn set_autoresizing_mask(&self, mask: AutoresizingMask) { + unsafe { + msg_send![self.id(), setAutoresizingMask:mask.bits()] + } + } + + #[inline] + pub fn layout_manager(&self) -> id { + unsafe { + msg_send![self.id(), layoutManager] + } + } + + #[inline] + pub unsafe fn set_layout_manager(&self, manager: id) { + msg_send![self.id(), setLayoutManager:manager] + } + + #[inline] + pub fn preferred_frame_size(&self) -> CGSize { + unsafe { + msg_send![self.id(), preferredFrameSize] + } + } + + #[inline] + pub fn set_needs_layout(&self) { + unsafe { + msg_send![self.id(), setNeedsLayout] + } + } + + #[inline] + pub fn needs_layout(&self) -> bool { + unsafe { + let flag: BOOL = msg_send![self.id(), needsLayout]; + flag == YES + } + } + + #[inline] + pub fn layout_if_needed(&self) { + unsafe { + msg_send![self.id(), layoutIfNeeded] + } + } + + #[inline] + pub fn layout_sublayers(&self) { + unsafe { + msg_send![self.id(), layoutSublayers] + } + } + + #[inline] + pub fn resize_sublayers_with_old_size(&self, size: &CGSize) { + unsafe { + msg_send![self.id(), resizeSublayersWithOldSize:*size] + } + } + + #[inline] + pub fn resize_with_old_superlayer_size(&self, size: &CGSize) { + unsafe { + msg_send![self.id(), resizeWithOldSuperlayerSize:*size] + } + } + + // Action methods + + #[inline] + pub fn default_action_for_key(event: &str) -> id { + unsafe { + let event: CFString = CFString::from(event); + msg_send![class!(CALayer), defaultActionForKey:event.as_CFTypeRef()] + } + } + + #[inline] + pub fn action_for_key(&self, event: &str) -> id { + unsafe { + let event: CFString = CFString::from(event); + msg_send![self.id(), actionForKey:event.as_CFTypeRef()] + } + } + + #[inline] + pub fn actions(&self) -> CFDictionary { + unsafe { + msg_send![self.id(), actions] + } + } + + #[inline] + pub unsafe fn set_actions(&self, actions: CFDictionary) { + msg_send![self.id(), setActions:actions] + } + + // TODO(pcwalton): Wrap `CAAnimation`. + #[inline] + pub unsafe fn add_animation_for_key(&self, animation: id, for_key: Option<&str>) { + let for_key: Option = for_key.map(CFString::from); + let for_key: CFTypeRef = match for_key { + Some(ref for_key) => for_key.as_CFTypeRef(), + None => ptr::null(), + }; + msg_send![self.id(), addAnimation:animation forKey:for_key] + } + + #[inline] + pub fn remove_all_animation(&self) { + unsafe { + msg_send![self.id(), removeAllAnimations] + } + } + + #[inline] + pub fn remove_animation_for_key(&self, key: &str) { + unsafe { + let key = CFString::from(key); + msg_send![self.id(), removeAnimationForKey:key.as_CFTypeRef()] + } + } + + #[inline] + pub fn animation_keys(&self) -> Vec { + unsafe { + let keys: CFArrayRef = msg_send![self.id(), animationKeys]; + let keys: CFArray = TCFType::wrap_under_create_rule(keys); + keys.into_iter().map(|string| { + CFString::wrap_under_get_rule(*string as CFStringRef).to_string() + }).collect() + } + } + + #[inline] + pub fn animation_for_key(&self, key: &str) -> id { + unsafe { + let key = CFString::from(key); + msg_send![self.id(), animationForKey:key.as_CFTypeRef()] + } + } + + // Miscellaneous properties + + #[inline] + pub fn name(&self) -> String { + unsafe { + let name: CFStringRef = msg_send![self.id(), name]; + CFString::wrap_under_get_rule(name).to_string() + } + } + + #[inline] + pub fn set_name(&self, name: &str) { + unsafe { + let name = CFString::from(name); + msg_send![self.id(), setName:name.as_CFTypeRef()] + } + } + + #[inline] + pub fn delegate(&self) -> id { + unsafe { + msg_send![self.id(), delegate] + } + } + + #[inline] + pub unsafe fn set_delegate(&self, delegate: id) { + msg_send![self.id(), setDelegate:delegate] + } + + #[inline] + pub fn style(&self) -> Option { + unsafe { + let dictionary: CFDictionaryRef = msg_send![self.id(), style]; + if dictionary.is_null() { + None + } else { + Some(CFDictionary::wrap_under_get_rule(dictionary)) + } + } + } + + #[inline] + pub fn set_style(&self, dictionary: Option) { + unsafe { + let dictionary = match dictionary { + None => ptr::null(), + Some(ref dictionary) => dictionary.as_CFTypeRef(), + }; + msg_send![self.id(), setStyle:dictionary] + } + } + + // Private methods + + #[inline] + pub fn reload_value_for_key_path(&self, key: &str) { + unsafe { + let key = CFString::from(key); + msg_send![self.id(), reloadValueForKeyPath:key.as_CFTypeRef()] + } + } + + #[inline] + pub fn set_contents_opaque(&self, opaque: bool) { + unsafe { + msg_send![self.id(), setContentsOpaque:opaque as BOOL] + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ContentsGravity { + Center, + Top, + Bottom, + Left, + Right, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + Resize, + ResizeAspect, + ResizeAspectFill, + Other(CFString), +} + +impl ContentsGravity { + fn into_CFString(self) -> CFString { + let string = match self { + ContentsGravity::Center => "center", + ContentsGravity::Top => "top", + ContentsGravity::Bottom => "bottom", + ContentsGravity::Left => "left", + ContentsGravity::Right => "right", + ContentsGravity::TopLeft => "topLeft", + ContentsGravity::TopRight => "topRight", + ContentsGravity::BottomLeft => "bottomLeft", + ContentsGravity::BottomRight => "bottomRight", + ContentsGravity::Resize => "resize", + ContentsGravity::ResizeAspect => "resizeAspect", + ContentsGravity::ResizeAspectFill => "resizeAspectFill", + ContentsGravity::Other(other) => return other, + }; + CFString::from(string) + } + + // FIXME(pcwalton): Inefficient. + fn from_CFString(string: CFString) -> ContentsGravity { + match string.to_string() { + ref s if s == "center" => ContentsGravity::Center, + ref s if s == "top" => ContentsGravity::Top, + ref s if s == "bottom" => ContentsGravity::Bottom, + ref s if s == "left" => ContentsGravity::Left, + ref s if s == "right" => ContentsGravity::Right, + ref s if s == "topLeft" => ContentsGravity::TopLeft, + ref s if s == "topRight" => ContentsGravity::TopRight, + ref s if s == "bottomLeft" => ContentsGravity::BottomLeft, + ref s if s == "bottomRight" => ContentsGravity::BottomRight, + ref s if s == "resize" => ContentsGravity::Resize, + ref s if s == "resizeAspect" => ContentsGravity::ResizeAspect, + ref s if s == "resizeAspectFill" => ContentsGravity::ResizeAspectFill, + _ => ContentsGravity::Other(string), + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ContentsFormat { + RGBA8Uint, // kCAContentsFormatRGBA8Uint, "RGBA" + RGBA16Float, // kCAContentsFormatRGBA16Float, "RGBAh" + Gray8Uint, // kCAContentsFormatGray8Uint, "Gray8" + Other(CFString), +} + +impl ContentsFormat { + fn into_CFString(self) -> CFString { + let string = match self { + ContentsFormat::RGBA8Uint => "RGBA8", + ContentsFormat::RGBA16Float => "RGBAh", + ContentsFormat::Gray8Uint => "Gray8", + ContentsFormat::Other(other) => return other, + }; + CFString::from(string) + } + + // FIXME(pcwalton): Inefficient. + fn from_CFString(string: CFString) -> ContentsFormat { + match string.to_string() { + ref s if s == "RGBA8" => ContentsFormat::RGBA8Uint, + ref s if s == "RGBAh" => ContentsFormat::RGBA16Float, + ref s if s == "Gray8" => ContentsFormat::Gray8Uint, + _ => ContentsFormat::Other(string), + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Filter { + Nearest, + Linear, + Trilinear, + Other(CFString), +} + +impl Filter { + fn into_CFString(self) -> CFString { + let string = match self { + Filter::Nearest => "nearest", + Filter::Linear => "linear", + Filter::Trilinear => "trilinear", + Filter::Other(other) => return other, + }; + CFString::from(string) + } + + // FIXME(pcwalton): Inefficient. + fn from_CFString(string: CFString) -> Filter { + match string.to_string() { + ref s if s == "nearest" => Filter::Nearest, + ref s if s == "linear" => Filter::Linear, + ref s if s == "trilinear" => Filter::Trilinear, + _ => Filter::Other(string), + } + } +} + +bitflags! { + pub struct EdgeAntialiasingMask: u32 { + const LEFT_EDGE = 1 << 0; // kCALayerLeftEdge + const RIGHT_EDGE = 1 << 1; // kCALayerRightEdge + const BOTTOM_EDGE = 1 << 2; // kCALayerBottomEdge + const TOP_EDGE = 1 << 3; // kCALayerTopEdge + } +} + +bitflags! { + pub struct CornerMask: NSUInteger { + const MIN_X_MIN_Y_CORNER = 1 << 0; // kCALayerMinXMinYCorner + const MAX_X_MIN_Y_CORNER = 1 << 1; // kCALayerMaxXMinYCorner + const MIN_X_MAX_Y_CORNER = 1 << 2; // kCALayerMinXMaxYCorner + const MAX_X_MAX_Y_CORNER = 1 << 3; // kCALayerMaxXMaxYCorner + } +} + +bitflags! { + pub struct AutoresizingMask: u32 { + const NOT_SIZABLE = 0; // kCALayerNotSizable + const MIN_X_MARGIN = 1 << 0; // kCALayerMinXMargin + const WIDTH_SIZABLE = 1 << 1; // kCALayerWidthSizable + const MAX_X_MARGIN = 1 << 2; // kCALayerMaxXMargin + const MIN_Y_MARGIN = 1 << 3; // kCALayerMinYMargin + const HEIGHT_SIZABLE = 1 << 4; // kCALayerHeightSizable + const MAX_Y_MARGIN = 1 << 5; // kCALayerMaxYMargin + } +} + +// CARenderer.h + +pub struct CARenderer(id); + +unsafe impl Send for CARenderer {} +unsafe impl Sync for CARenderer {} + +impl Clone for CARenderer { + #[inline] + fn clone(&self) -> CARenderer { + unsafe { + CARenderer(msg_send![self.id(), retain]) + } + } +} + +impl Drop for CARenderer { + #[inline] + fn drop(&mut self) { + unsafe { + msg_send![self.id(), release] + } + } +} + +impl CARenderer { + #[inline] + pub fn id(&self) -> id { + self.0 + } + + #[inline] + pub unsafe fn from_cgl_context(context: CGLContextObj, color_space: Option) + -> CARenderer { + let mut pairs: Vec<(CFString, CFType)> = vec![]; + if let Some(color_space) = color_space { + pairs.push((CFString::wrap_under_get_rule(kCARendererColorSpace), + CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _))) + } + + let options: CFDictionary = CFDictionary::from_CFType_pairs(&pairs); + + let renderer: id = + msg_send![class!(CARenderer), rendererWithCGLContext:context + options:options.as_CFTypeRef()]; + debug_assert!(renderer != nil); + CARenderer(renderer) + } + + #[inline] + pub unsafe fn from_metal_texture(metal_texture: id, + metal_command_queue: id, + color_space: Option) + -> CARenderer { + let mut pairs: Vec<(CFString, CFType)> = vec![ + (CFString::wrap_under_get_rule(kCARendererMetalCommandQueue), + CFType::wrap_under_get_rule(metal_command_queue as *const _ as *const _)), + ]; + if let Some(color_space) = color_space { + pairs.push((CFString::wrap_under_get_rule(kCARendererColorSpace), + CFType::wrap_under_get_rule(color_space.as_ptr() as *const _ as *const _))) + } + + let options: CFDictionary = CFDictionary::from_CFType_pairs(&pairs); + + let renderer: id = + msg_send![class!(CARenderer), rendererWithMTLTexture:metal_texture + options:options.as_CFTypeRef()]; + debug_assert!(renderer != nil); + CARenderer(renderer) + } + + #[inline] + pub fn layer(&self) -> Option { + unsafe { + let layer: id = msg_send![self.id(), layer]; + if layer.is_null() { + None + } else { + Some(CALayer(layer)) + } + } + } + + #[inline] + pub fn set_layer(&self, layer: Option) { + unsafe { + let layer = match layer { + Some(ref layer) => layer.id(), + None => nil, + }; + msg_send![self.id(), setLayer:layer] + } + } + + #[inline] + pub fn bounds(&self) -> CGRect { + unsafe { + msg_send![self.id(), bounds] + } + } + + #[inline] + pub fn set_bounds(&self, bounds: CGRect) { + unsafe { + msg_send![self.id(), setBounds:bounds] + } + } + + #[inline] + pub fn begin_frame_at(&self, time: CFTimeInterval, timestamp: Option<&CVTimeStamp>) { + unsafe { + msg_send![self.id(), beginFrameAtTime:time timeStamp:timestamp] + } + } + + #[inline] + pub fn update_bounds(&self) -> CGRect { + unsafe { + msg_send![self.id(), updateBounds] + } + } + + #[inline] + pub fn add_update_rect(&self, rect: CGRect) { + unsafe { + msg_send![self.id(), addUpdateRect:rect] + } + } + + #[inline] + pub fn render(&self) { + unsafe { + msg_send![self.id(), render] + } + } + + #[inline] + pub fn next_frame_time(&self) -> CFTimeInterval { + unsafe { + msg_send![self.id(), nextFrameTime] + } + } + + #[inline] + pub fn end_frame(&self) { + unsafe { + msg_send![self.id(), endFrame] + } + } + + #[inline] + pub unsafe fn set_destination(&self, metal_texture: id) { + msg_send![self.id(), setDestination:metal_texture] + } +} + +// CATransaction.h + +// You can't actually construct any `CATransaction` objects, so that class is +// really just a module. +pub mod transaction { + use block::{Block, ConcreteBlock, IntoConcreteBlock, RcBlock}; + use core_foundation::date::CFTimeInterval; + use core_foundation::string::CFString; + + use base::{BOOL, YES, id}; + + #[inline] + pub fn begin() { + unsafe { + msg_send![class!(CATransaction), begin] + } + } + + #[inline] + pub fn commit() { + unsafe { + msg_send![class!(CATransaction), commit] + } + } + + #[inline] + pub fn flush() { + unsafe { + msg_send![class!(CATransaction), flush] + } + } + + #[inline] + pub fn lock() { + unsafe { + msg_send![class!(CATransaction), lock] + } + } + + #[inline] + pub fn unlock() { + unsafe { + msg_send![class!(CATransaction), unlock] + } + } + + #[inline] + pub fn animation_duration() -> CFTimeInterval { + unsafe { + msg_send![class!(CATransaction), animationDuration] + } + } + + #[inline] + pub fn set_animation_duration(duration: CFTimeInterval) { + unsafe { + msg_send![class!(CATransaction), setAnimationDuration:duration] + } + } + + #[inline] + pub fn animation_timing_function() -> id { + unsafe { + msg_send![class!(CATransaction), animationTimingFunction] + } + } + + #[inline] + pub unsafe fn set_animation_timing_function(function: id) { + msg_send![class!(CATransaction), setAnimationTimingFunction:function] + } + + #[inline] + pub fn disable_actions() -> bool { + unsafe { + let flag: BOOL = msg_send![class!(CATransaction), disableActions]; + flag == YES + } + } + + #[inline] + pub fn set_disable_actions(flag: bool) { + unsafe { + msg_send![class!(CATransaction), setDisableActions:flag as BOOL] + } + } + + #[inline] + pub fn completion_block() -> Option> { + unsafe { + let completion_block: *mut Block<(), ()> = + msg_send![class!(CATransaction), completionBlock]; + if completion_block.is_null() { + None + } else { + Some(RcBlock::new(completion_block)) + } + } + } + + #[inline] + pub fn set_completion_block(block: ConcreteBlock<(), (), F>) + where F: 'static + IntoConcreteBlock<(), Ret = ()> { + unsafe { + let block = block.copy(); + msg_send![class!(CATransaction), setCompletionBlock:&*block] + } + } + + #[inline] + pub fn value_for_key(key: &str) -> id { + unsafe { + let key: CFString = CFString::from(key); + msg_send![class!(CATransaction), valueForKey:key] + } + } + + #[inline] + pub fn set_value_for_key(value: id, key: &str) { + unsafe { + let key: CFString = CFString::from(key); + msg_send![class!(CATransaction), setValue:value forKey:key] + } + } +} + +// CATransform3D.h + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CATransform3D { + pub m11: CGFloat, pub m12: CGFloat, pub m13: CGFloat, pub m14: CGFloat, + pub m21: CGFloat, pub m22: CGFloat, pub m23: CGFloat, pub m24: CGFloat, + pub m31: CGFloat, pub m32: CGFloat, pub m33: CGFloat, pub m34: CGFloat, + pub m41: CGFloat, pub m42: CGFloat, pub m43: CGFloat, pub m44: CGFloat, +} + +impl PartialEq for CATransform3D { + #[inline] + fn eq(&self, other: &CATransform3D) -> bool { + unsafe { + CATransform3DEqualToTransform(*self, *other) + } + } +} + +impl Mul for CATransform3D { + type Output = CATransform3D; + + #[inline] + fn mul(self, other: CATransform3D) -> CATransform3D { + unsafe { + CATransform3DConcat(self, other) + } + } +} + +impl CATransform3D { + pub const IDENTITY: CATransform3D = CATransform3D { + m11: 1.0, m12: 0.0, m13: 0.0, m14: 0.0, + m21: 0.0, m22: 1.0, m23: 0.0, m24: 0.0, + m31: 0.0, m32: 0.0, m33: 1.0, m34: 0.0, + m41: 0.0, m42: 0.0, m43: 0.0, m44: 1.0, + }; + + #[inline] + pub fn from_translation(tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D { + unsafe { + CATransform3DMakeTranslation(tx, ty, tz) + } + } + + #[inline] + pub fn from_scale(sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D { + unsafe { + CATransform3DMakeScale(sx, sy, sz) + } + } + + #[inline] + pub fn from_rotation(angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) -> CATransform3D { + unsafe { + CATransform3DMakeRotation(angle, x, y, z) + } + } + + #[inline] + pub fn affine(affine_transform: CGAffineTransform) -> CATransform3D { + unsafe { + CATransform3DMakeAffineTransform(affine_transform) + } + } + + #[inline] + pub fn is_identity(&self) -> bool { + unsafe { + CATransform3DIsIdentity(*self) + } + } + + #[inline] + pub fn translate(&self, tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D { + unsafe { + CATransform3DTranslate(*self, tx, ty, tz) + } + } + + #[inline] + pub fn scale(&self, sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D { + unsafe { + CATransform3DScale(*self, sx, sy, sz) + } + } + + #[inline] + pub fn rotate(&self, angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) -> CATransform3D { + unsafe { + CATransform3DRotate(*self, angle, x, y, z) + } + } + + #[inline] + pub fn invert(&self) -> CATransform3D { + unsafe { + CATransform3DInvert(*self) + } + } + + #[inline] + pub fn is_affine(&self) -> bool { + unsafe { + CATransform3DIsAffine(*self) + } + } + + #[inline] + pub fn to_affine(&self) -> CGAffineTransform { + unsafe { + CATransform3DGetAffineTransform(*self) + } + } +} + +#[link(name = "QuartzCore", kind = "framework")] +extern { + static kCARendererColorSpace: CFStringRef; + static kCARendererMetalCommandQueue: CFStringRef; + + fn CACurrentMediaTime() -> CFTimeInterval; + + fn CATransform3DIsIdentity(t: CATransform3D) -> bool; + fn CATransform3DEqualToTransform(a: CATransform3D, b: CATransform3D) -> bool; + fn CATransform3DMakeTranslation(tx: CGFloat, ty: CGFloat, tz: CGFloat) -> CATransform3D; + fn CATransform3DMakeScale(sx: CGFloat, sy: CGFloat, sz: CGFloat) -> CATransform3D; + fn CATransform3DMakeRotation(angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) + -> CATransform3D; + fn CATransform3DTranslate(t: CATransform3D, tx: CGFloat, ty: CGFloat, tz: CGFloat) + -> CATransform3D; + fn CATransform3DScale(t: CATransform3D, sx: CGFloat, sy: CGFloat, sz: CGFloat) + -> CATransform3D; + fn CATransform3DRotate(t: CATransform3D, angle: CGFloat, x: CGFloat, y: CGFloat, z: CGFloat) + -> CATransform3D; + fn CATransform3DConcat(a: CATransform3D, b: CATransform3D) -> CATransform3D; + fn CATransform3DInvert(t: CATransform3D) -> CATransform3D; + fn CATransform3DMakeAffineTransform(m: CGAffineTransform) -> CATransform3D; + fn CATransform3DIsAffine(t: CATransform3D) -> bool; + fn CATransform3DGetAffineTransform(t: CATransform3D) -> CGAffineTransform; +} + +// Miscellaneous structures in other frameworks. +// +// These should be moved elsewhere eventually. + +// CoreVideo/CVBase.h + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CVTimeStamp { + pub version: u32, + pub videoTimeScale: i32, + pub videoTime: i64, + pub hostTime: u64, + pub rateScalar: f64, + pub videoRefreshPeriod: i64, + pub smpteTime: CVSMPTETime, + pub flags: u64, + pub reserved: u64, +} + +pub type CVTimeStampFlags = u64; + +pub const kCVTimeStampVideoTimeValid: CVTimeStampFlags = 1 << 0; +pub const kCVTimeStampHostTimeValid: CVTimeStampFlags = 1 << 1; +pub const kCVTimeStampSMPTETimeValid: CVTimeStampFlags = 1 << 2; +pub const kCVTimeStampVideoRefreshPeriodValid: CVTimeStampFlags = 1 << 3; +pub const kCVTimeStampRateScalarValid: CVTimeStampFlags = 1 << 4; +pub const kCVTimeStampTopField: CVTimeStampFlags = 1 << 16; +pub const kCVTimeStampBottomField: CVTimeStampFlags = 1 << 17; +pub const kCVTimeStampVideoHostTimeValid: CVTimeStampFlags = + kCVTimeStampVideoTimeValid | kCVTimeStampHostTimeValid; +pub const kCVTimeStampIsInterlaced: CVTimeStampFlags = + kCVTimeStampTopField | kCVTimeStampBottomField; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CVSMPTETime { + pub subframes: i16, + pub subframeDivisor: i16, + pub counter: u32, + pub time_type: u32, + pub flags: u32, + pub hours: i16, + pub minutes: i16, + pub seconds: i16, + pub frames: i16, +} + +pub type CVSMPTETimeType = u32; + +pub const kCVSMPTETimeType24: CVSMPTETimeType = 0; +pub const kCVSMPTETimeType25: CVSMPTETimeType = 1; +pub const kCVSMPTETimeType30Drop: CVSMPTETimeType = 2; +pub const kCVSMPTETimeType30: CVSMPTETimeType = 3; +pub const kCVSMPTETimeType2997: CVSMPTETimeType = 4; +pub const kCVSMPTETimeType2997Drop: CVSMPTETimeType = 5; +pub const kCVSMPTETimeType60: CVSMPTETimeType = 6; +pub const kCVSMPTETimeType5994: CVSMPTETimeType = 7; + +pub type CVSMPTETimeFlags = u32; + +pub const kCVSMPTETimeValid: CVSMPTETimeFlags = 1 << 0; +pub const kCVSMPTETimeRunning: CVSMPTETimeFlags = 1 << 1; diff --git a/third_party/cargo/vendor/cocoa-0.20.0/tests/foundation.rs b/third_party/cargo/vendor/cocoa-0.20.0/tests/foundation.rs new file mode 100644 index 0000000..c491501 --- /dev/null +++ b/third_party/cargo/vendor/cocoa-0.20.0/tests/foundation.rs @@ -0,0 +1,195 @@ +#[macro_use] +extern crate objc; +extern crate block; +extern crate cocoa; + +#[cfg(test)] +mod foundation { + mod nsstring { + use cocoa::foundation::NSString; + use cocoa::base::nil; + use std::slice; + use std::str; + + #[test] + fn test_utf8() { + let expected = "Iñtërnâtiônàlizætiøn"; + unsafe { + let built = NSString::alloc(nil).init_str(expected); + let bytes = built.UTF8String() as *const u8; + let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) + .unwrap(); + assert_eq!(objc_string.len(), expected.len()); + assert_eq!(objc_string, expected); + } + } + + #[test] + fn test_string() { + let expected = "Hello World!"; + unsafe { + let built = NSString::alloc(nil).init_str(expected); + let bytes = built.UTF8String() as *const u8; + let objc_string = str::from_utf8(slice::from_raw_parts(bytes, built.len())) + .unwrap(); + assert_eq!(objc_string.len(), expected.len()); + assert_eq!(objc_string, expected); + } + } + + #[test] + fn test_length() { + let expected = "Hello!"; + unsafe { + let built = NSString::alloc(nil).init_str(expected); + assert_eq!(built.len(), expected.len()); + } + } + + #[test] + fn test_append_by_appending_string() { + let initial_str = "Iñtërnâtiônàlizætiøn"; + let to_append = "_more_strings"; + let expected = concat!("Iñtërnâtiônàlizætiøn", "_more_strings"); + unsafe { + let built = NSString::alloc(nil).init_str(initial_str); + let built_to_append = NSString::alloc(nil).init_str(to_append); + let append_string = built.stringByAppendingString_(built_to_append); + let bytes = append_string.UTF8String() as *const u8; + let objc_string = str::from_utf8(slice::from_raw_parts(bytes, append_string.len())) + .unwrap(); + assert_eq!(objc_string, expected); + } + } + } + + mod nsfastenumeration { + use std::str; + use std::slice; + use cocoa::foundation::{NSString, NSFastEnumeration}; + use cocoa::base::{id, nil}; + + #[test] + fn test_iter() { + unsafe { + let string = NSString::alloc(nil).init_str("this is a test string"); + let separator = NSString::alloc(nil).init_str(" "); + let components: id = msg_send![string, componentsSeparatedByString: separator]; + + let combined = components.iter() + .map(|s| { + let bytes = s.UTF8String() as *const u8; + str::from_utf8(slice::from_raw_parts(bytes, s.len())).unwrap() + }) + .fold(String::new(), |mut acc, s| { + acc.push_str(s); + acc + }); + + assert_eq!(combined, "thisisateststring"); + } + } + + #[test] + #[should_panic] + fn test_mutation() { + unsafe { + let string = NSString::alloc(nil).init_str("this is a test string"); + let separator = NSString::alloc(nil).init_str(" "); + let components: id = msg_send![string, componentsSeparatedByString: separator]; + let mut_components: id = msg_send![components, mutableCopy]; + let mut iter = mut_components.iter(); + iter.next(); + let () = msg_send![mut_components, removeObjectAtIndex:1]; + iter.next(); + } + } + } + + mod nsdictionary { + use block::ConcreteBlock; + use cocoa::foundation::{NSArray, NSComparisonResult, NSDictionary, NSFastEnumeration, + NSString}; + use cocoa::base::{id, nil}; + + #[test] + fn test_get() { + const KEY: &'static str = "The key"; + const VALUE: &'static str = "Some value"; + unsafe { + let key = NSString::alloc(nil).init_str(KEY); + let value = NSString::alloc(nil).init_str(VALUE); + let dict = NSDictionary::dictionaryWithObject_forKey_(nil, value, key); + + let retrieved_value = dict.objectForKey_(key); + assert!(retrieved_value.isEqualToString(VALUE)); + } + } + + #[test] + fn test_iter() { + let mkstr = |s| unsafe { NSString::alloc(nil).init_str(s) }; + let keys = vec!["a", "b", "c", "d", "e", "f"]; + let objects = vec!["1", "2", "3", "4", "5", "6"]; + unsafe { + use std::{slice, str}; + use std::cmp::{Ord, Ordering}; + + let keys_raw_vec = keys.clone().into_iter().map(&mkstr).collect::>(); + let objs_raw_vec = objects.clone().into_iter().map(&mkstr).collect::>(); + + let keys_array = NSArray::arrayWithObjects(nil, &keys_raw_vec); + let objs_array = NSArray::arrayWithObjects(nil, &objs_raw_vec); + + let dict = + NSDictionary::dictionaryWithObjects_forKeys_(nil, objs_array, keys_array); + + // NSDictionary does not store its contents in order of insertion, so ask for + // sorted iterators to ensure that each item is the same as its counterpart in + // the vector. + + fn compare_function(s0: &id, s1: &id) -> Ordering { + unsafe { + let (bytes0, len0) = (s0.UTF8String() as *const u8, s0.len()); + let (bytes1, len1) = (s1.UTF8String() as *const u8, s1.len()); + let (s0, s1) = (str::from_utf8(slice::from_raw_parts(bytes0, len0)).unwrap(), + str::from_utf8(slice::from_raw_parts(bytes1, len1)).unwrap()); + let (c0, c1) = (s0.chars().next().unwrap(), s1.chars().next().unwrap()); + c0.cmp(&c1) + } + } + + // First test cocoa sorting... + let mut comparator = ConcreteBlock::new(|s0: id, s1: id| { + match compare_function(&s0, &s1) { + Ordering::Less => NSComparisonResult::NSOrderedAscending, + Ordering::Equal => NSComparisonResult::NSOrderedSame, + Ordering::Greater => NSComparisonResult::NSOrderedDescending, + } + }); + + let associated_iter = keys.iter().zip(objects.iter()); + for (k_id, (k, v)) in dict.keysSortedByValueUsingComparator_(&mut *comparator) + .iter() + .zip(associated_iter) { + assert!(k_id.isEqualToString(k)); + let v_id = dict.objectForKey_(k_id); + assert!(v_id.isEqualToString(v)); + } + + // Then use rust sorting + let mut keys_arr = dict.allKeys().iter().collect::>(); + keys_arr.sort_by(compare_function); + for (k0, k1) in keys_arr.into_iter().zip(keys.iter()) { + assert!(k0.isEqualToString(k1)); + } + + let mut objects_arr = dict.allValues().iter().collect::>(); + objects_arr.sort_by(compare_function); + for (v0, v1) in objects_arr.into_iter().zip(objects.iter()) { + assert!(v0.isEqualToString(v1)); + } + } + } + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/.cargo-checksum.json b/third_party/cargo/vendor/core-foundation-0.7.0/.cargo-checksum.json new file mode 100644 index 0000000..d6b4235 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b5b2f9b692bbd5d0b445bfc43eb2dad8e236fd14be6fea6511e2f972f2177b92","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","src/array.rs":"221e81de15d95ca453df39466ba65faf879f2923202145958dfcebe63bfef97f","src/attributed_string.rs":"e6b32d673fa957611dbac2480675fab3c697fca8043077f2015f0a0801b20425","src/base.rs":"394764fa59518507fd8d53024b9574ab914eb856c1a873e6b1b4d84cdcde1c31","src/boolean.rs":"f5b4d295aaf6cc3681212afebeae2974c5d551125badcc066e6089ac0d2a0873","src/bundle.rs":"b652810146ee35c7c08ccb8e0b920359bf0313f4e8ca20111627754854ca93b5","src/characterset.rs":"a3ffb46c5463c99813eebfc177a65794f44a1b9343534e28bbccd262034714c2","src/data.rs":"a1d7e6430c745731fc7b2aee49af9f14e79c8a288951c82ea6507689a3356af8","src/date.rs":"a02f6cca7b6e8fbabc7713177429012658dba5146556e14a08e7baaf81958d83","src/dictionary.rs":"ed8080eb00507e342521fb2c513a83c5706e883c3f8d67d8f38e9a0ed685c7eb","src/error.rs":"22c21087d9c2c103d1bcb2c4af33b684317bbda5d4747902e510d410f8c1a14b","src/filedescriptor.rs":"6c2087a8e101bfb31a6b916759a69a82852b18b2174c818f6ec9211ccdcaf1e6","src/lib.rs":"bbf7e392e1c8e5f4cd491601b6601ea26b389b47dc4e32217481a7b86020843c","src/number.rs":"5a6cc9036c156e7e9d787864dd671087677abf4175cd840cbf123ccd89abcafe","src/propertylist.rs":"557ff9c346fbc70d19a887e0ce9977b84066f5d4bb6ba53ece8b733a5f0526e3","src/runloop.rs":"048772c566cf3a1ec3e478958293aa9f3af38ff40b71ab7695f86b61d12f2023","src/set.rs":"c61d7cacdbe7c3c69b2add3d2f1721960f6df710ef4db6a442cd8b05e8e929f3","src/string.rs":"28cead4283dfeeeb1c8c8bcf855823ed4b952e3a54cb8ca1c8f5f9a25d77bc0b","src/timezone.rs":"65859378232ee55f04bc4544b88f5dbc21f5db01bd16f2df3e82136ee3ce26b4","src/url.rs":"6d009ad7991af80c3131cd63070309e5c4054076cc7b05c99caf88cea660bf43","src/uuid.rs":"c3457e43fc22ba0f3fcab3ee8108500585ba005dbcbfa7edad0d389701ddf379","tests/use_macro_outside_crate.rs":"ed5e74ac9e988f2609c0b785189f1e6368d693f6401603ad065521f3ab51df94"},"package":"57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171"} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/BUILD b/third_party/cargo/vendor/core-foundation-0.7.0/BUILD new file mode 100644 index 0000000..7d54876 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/BUILD @@ -0,0 +1,45 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT,Apache-2.0" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "core_foundation", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/core-foundation-sys-0.7.0:core_foundation_sys", + "//third_party/cargo/vendor/libc-0.2.67:libc", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.7.0", + crate_features = [ + ], +) + +# Unsupported target "use_macro_outside_crate" with type "test" omitted diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/Cargo.toml b/third_party/cargo/vendor/core-foundation-0.7.0/Cargo.toml new file mode 100644 index 0000000..621f81b --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/Cargo.toml @@ -0,0 +1,41 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "core-foundation" +version = "0.7.0" +authors = ["The Servo Project Developers"] +description = "Bindings to Core Foundation for macOS" +homepage = "https://github.com/servo/core-foundation-rs" +keywords = ["macos", "framework", "objc"] +categories = ["os::macos-apis"] +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" +[dependencies.chrono] +version = "0.4" +optional = true + +[dependencies.core-foundation-sys] +version = "0.7" + +[dependencies.libc] +version = "0.2" + +[dependencies.uuid] +version = "0.5" +optional = true + +[features] +mac_os_10_7_support = ["core-foundation-sys/mac_os_10_7_support"] +mac_os_10_8_features = ["core-foundation-sys/mac_os_10_8_features"] +with-chrono = ["chrono"] +with-uuid = ["uuid"] diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/LICENSE-APACHE b/third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/backtrace-sys-0.1.34/LICENSE-APACHE rename to third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-MIT b/third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-MIT new file mode 100644 index 0000000..807526f --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2012-2013 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/array.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/array.rs new file mode 100644 index 0000000..f13ea19 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/array.rs @@ -0,0 +1,286 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Heterogeneous immutable arrays. + +pub use core_foundation_sys::array::*; +pub use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; +use std::mem; +use std::marker::PhantomData; +use std::os::raw::c_void; +use std::ptr; +use ConcreteCFType; + +use base::{CFIndexConvertible, TCFType, CFRange}; +use base::{FromVoid, ItemRef}; + +/// A heterogeneous immutable array. +pub struct CFArray(CFArrayRef, PhantomData); + +impl Drop for CFArray { + fn drop(&mut self) { + unsafe { CFRelease(self.as_CFTypeRef()) } + } +} + +pub struct CFArrayIterator<'a, T: 'a> { + array: &'a CFArray, + index: CFIndex, + len: CFIndex, +} + +impl<'a, T: FromVoid> Iterator for CFArrayIterator<'a, T> { + type Item = ItemRef<'a, T>; + + fn next(&mut self) -> Option> { + if self.index >= self.len { + None + } else { + let value = unsafe { self.array.get_unchecked(self.index) }; + self.index += 1; + Some(value) + } + } +} + +impl<'a, T: FromVoid> ExactSizeIterator for CFArrayIterator<'a, T> { + fn len(&self) -> usize { + (self.array.len() - self.index) as usize + } +} + +impl_TCFType!(CFArray, CFArrayRef, CFArrayGetTypeID); +impl_CFTypeDescription!(CFArray); + +unsafe impl ConcreteCFType for CFArray<*const c_void> {} + +impl CFArray { + /// Creates a new `CFArray` with the given elements, which must implement `Copy`. + pub fn from_copyable(elems: &[T]) -> CFArray where T: Copy { + unsafe { + let array_ref = CFArrayCreate(kCFAllocatorDefault, + elems.as_ptr() as *const *const c_void, + elems.len().to_CFIndex(), + ptr::null()); + TCFType::wrap_under_create_rule(array_ref) + } + } + + /// Creates a new `CFArray` with the given elements, which must be `CFType` objects. + pub fn from_CFTypes(elems: &[T]) -> CFArray where T: TCFType { + unsafe { + let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); + let array_ref = CFArrayCreate(kCFAllocatorDefault, + elems.as_ptr(), + elems.len().to_CFIndex(), + &kCFTypeArrayCallBacks); + TCFType::wrap_under_create_rule(array_ref) + } + } + + #[inline] + pub fn to_untyped(&self) -> CFArray { + unsafe { CFArray::wrap_under_get_rule(self.0) } + } + + /// Returns the same array, but with the type reset to void pointers. + /// Equal to `to_untyped`, but is faster since it does not increment the retain count. + #[inline] + pub fn into_untyped(self) -> CFArray { + let reference = self.0; + mem::forget(self); + unsafe { CFArray::wrap_under_create_rule(reference) } + } + + /// Iterates over the elements of this `CFArray`. + /// + /// Careful; the loop body must wrap the reference properly. Generally, when array elements are + /// Core Foundation objects (not always true), they need to be wrapped with + /// `TCFType::wrap_under_get_rule()`. + #[inline] + pub fn iter<'a>(&'a self) -> CFArrayIterator<'a, T> { + CFArrayIterator { + array: self, + index: 0, + len: self.len(), + } + } + + #[inline] + pub fn len(&self) -> CFIndex { + unsafe { + CFArrayGetCount(self.0) + } + } + + #[inline] + pub unsafe fn get_unchecked<'a>(&'a self, index: CFIndex) -> ItemRef<'a, T> where T: FromVoid { + T::from_void(CFArrayGetValueAtIndex(self.0, index)) + } + + #[inline] + pub fn get<'a>(&'a self, index: CFIndex) -> Option> where T: FromVoid { + if index < self.len() { + Some(unsafe { T::from_void(CFArrayGetValueAtIndex(self.0, index)) } ) + } else { + None + } + } + + pub fn get_values(&self, range: CFRange) -> Vec<*const c_void> { + let mut vec = Vec::with_capacity(range.length as usize); + unsafe { + CFArrayGetValues(self.0, range, vec.as_mut_ptr()); + vec.set_len(range.length as usize); + vec + } + } + + pub fn get_all_values(&self) -> Vec<*const c_void> { + self.get_values(CFRange { + location: 0, + length: self.len() + }) + } +} + +impl<'a, T: FromVoid> IntoIterator for &'a CFArray { + type Item = ItemRef<'a, T>; + type IntoIter = CFArrayIterator<'a, T>; + + fn into_iter(self) -> CFArrayIterator<'a, T> { + self.iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem; + use base::CFType; + + #[test] + fn to_untyped_correct_retain_count() { + let array = CFArray::::from_CFTypes(&[]); + assert_eq!(array.retain_count(), 1); + + let untyped_array = array.to_untyped(); + assert_eq!(array.retain_count(), 2); + assert_eq!(untyped_array.retain_count(), 2); + + mem::drop(array); + assert_eq!(untyped_array.retain_count(), 1); + } + + #[test] + fn into_untyped() { + let array = CFArray::::from_CFTypes(&[]); + let array2 = array.to_untyped(); + assert_eq!(array.retain_count(), 2); + + let untyped_array = array.into_untyped(); + assert_eq!(untyped_array.retain_count(), 2); + + mem::drop(array2); + assert_eq!(untyped_array.retain_count(), 1); + } + + #[test] + fn borrow() { + use string::CFString; + + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let x; + { + let arr: CFArray = CFArray::from_CFTypes(&[string]); + { + let p = arr.get(0).unwrap(); + assert_eq!(p.retain_count(), 1); + } + { + x = arr.get(0).unwrap().clone(); + assert_eq!(x.retain_count(), 2); + assert_eq!(x.to_string(), "bar"); + } + } + assert_eq!(x.retain_count(), 1); + } + + #[test] + fn iter_untyped_array() { + use string::{CFString, CFStringRef}; + use base::TCFTypeRef; + + let cf_string = CFString::from_static_string("bar"); + let array: CFArray = CFArray::from_CFTypes(&[cf_string.clone()]).into_untyped(); + + let cf_strings = array.iter().map(|ptr| { + unsafe { CFString::wrap_under_get_rule(CFStringRef::from_void_ptr(*ptr)) } + }).collect::>(); + let strings = cf_strings.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(cf_string.retain_count(), 3); + assert_eq!(&strings[..], &["bar"]); + } + + #[test] + fn should_box_and_unbox() { + use number::CFNumber; + + let n0 = CFNumber::from(0); + let n1 = CFNumber::from(1); + let n2 = CFNumber::from(2); + let n3 = CFNumber::from(3); + let n4 = CFNumber::from(4); + let n5 = CFNumber::from(5); + + let arr = CFArray::from_CFTypes(&[ + n0.as_CFType(), + n1.as_CFType(), + n2.as_CFType(), + n3.as_CFType(), + n4.as_CFType(), + n5.as_CFType(), + ]); + + assert_eq!( + arr.get_all_values(), + &[ + n0.as_CFTypeRef(), + n1.as_CFTypeRef(), + n2.as_CFTypeRef(), + n3.as_CFTypeRef(), + n4.as_CFTypeRef(), + n5.as_CFTypeRef() + ] + ); + + let mut sum = 0; + + let mut iter = arr.iter(); + assert_eq!(iter.len(), 6); + assert!(iter.next().is_some()); + assert_eq!(iter.len(), 5); + + for elem in iter { + let number: CFNumber = elem.downcast::().unwrap(); + sum += number.to_i64().unwrap() + } + + assert_eq!(sum, 15); + + for elem in arr.iter() { + let number: CFNumber = elem.downcast::().unwrap(); + sum += number.to_i64().unwrap() + } + + assert_eq!(sum, 30); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/attributed_string.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/attributed_string.rs new file mode 100644 index 0000000..e0fa576 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/attributed_string.rs @@ -0,0 +1,85 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use core_foundation_sys::attributed_string::*; + +use base::TCFType; +use core_foundation_sys::base::{CFIndex, CFRange, kCFAllocatorDefault}; +use std::ptr::null; +use string::{CFString, CFStringRef}; + +declare_TCFType!{ + CFAttributedString, CFAttributedStringRef +} +impl_TCFType!(CFAttributedString, CFAttributedStringRef, CFAttributedStringGetTypeID); + +impl CFAttributedString { + #[inline] + pub fn new(string: &CFString) -> Self { + unsafe { + let astr_ref = CFAttributedStringCreate( + kCFAllocatorDefault, string.as_concrete_TypeRef(), null()); + + CFAttributedString::wrap_under_create_rule(astr_ref) + } + } + + #[inline] + pub fn char_len(&self) -> CFIndex { + unsafe { + CFAttributedStringGetLength(self.0) + } + } +} + +declare_TCFType!{ + CFMutableAttributedString, CFMutableAttributedStringRef +} +impl_TCFType!(CFMutableAttributedString, CFMutableAttributedStringRef, CFMutableAttributedStringGetTypeID); + +impl CFMutableAttributedString { + #[inline] + pub fn new() -> Self { + unsafe { + let astr_ref = CFAttributedStringCreateMutable( + kCFAllocatorDefault, 0); + + CFMutableAttributedString::wrap_under_create_rule(astr_ref) + } + } + + #[inline] + pub fn char_len(&self) -> CFIndex { + unsafe { + CFAttributedStringGetLength(self.0) + } + } + + #[inline] + pub fn replace_str(&mut self, string: &CFString, range: CFRange) { + unsafe { + CFAttributedStringReplaceString( + self.0, range, string.as_concrete_TypeRef()); + } + } + + #[inline] + pub fn set_attribute(&mut self, range: CFRange, name: CFStringRef, value: T) { + unsafe { + CFAttributedStringSetAttribute( + self.0, range, name, value.as_CFTypeRef()); + } + } +} + +impl Default for CFMutableAttributedString { + fn default() -> Self { + Self::new() + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/base.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/base.rs new file mode 100644 index 0000000..1a09ee6 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/base.rs @@ -0,0 +1,450 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std; +use std::fmt; +use std::marker::PhantomData; +use std::mem; +use std::mem::ManuallyDrop; +use std::ops::{Deref, DerefMut}; +use std::os::raw::c_void; + +pub use core_foundation_sys::base::*; + +use string::CFString; +use ConcreteCFType; + +pub trait CFIndexConvertible { + /// Always use this method to construct a `CFIndex` value. It performs bounds checking to + /// ensure the value is in range. + fn to_CFIndex(self) -> CFIndex; +} + +impl CFIndexConvertible for usize { + #[inline] + fn to_CFIndex(self) -> CFIndex { + let max_CFIndex = CFIndex::max_value(); + if self > (max_CFIndex as usize) { + panic!("value out of range") + } + self as CFIndex + } +} + +declare_TCFType!{ + /// Superclass of all Core Foundation objects. + CFType, CFTypeRef +} + +impl CFType { + /// Try to downcast the `CFType` to a subclass. Checking if the instance is the + /// correct subclass happens at runtime and `None` is returned if it is not the correct type. + /// Works similar to [`Box::downcast`] and [`CFPropertyList::downcast`]. + /// + /// # Examples + /// + /// ``` + /// # use core_foundation::string::CFString; + /// # use core_foundation::boolean::CFBoolean; + /// # use core_foundation::base::{CFType, TCFType}; + /// # + /// // Create a string. + /// let string: CFString = CFString::from_static_string("FooBar"); + /// // Cast it up to a CFType. + /// let cf_type: CFType = string.as_CFType(); + /// // Cast it down again. + /// assert_eq!(cf_type.downcast::().unwrap().to_string(), "FooBar"); + /// // Casting it to some other type will yield `None` + /// assert!(cf_type.downcast::().is_none()); + /// ``` + /// + /// ```compile_fail + /// # use core_foundation::array::CFArray; + /// # use core_foundation::base::TCFType; + /// # use core_foundation::boolean::CFBoolean; + /// # use core_foundation::string::CFString; + /// # + /// let boolean_array = CFArray::from_CFTypes(&[CFBoolean::true_value()]).into_CFType(); + /// + /// // This downcast is not allowed and causes compiler error, since it would cause undefined + /// // behavior to access the elements of the array as a CFString: + /// let invalid_string_array = boolean_array + /// .downcast_into::>() + /// .unwrap(); + /// ``` + /// + /// [`Box::downcast`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.downcast + /// [`CFPropertyList::downcast`]: ../propertylist/struct.CFPropertyList.html#method.downcast + #[inline] + pub fn downcast(&self) -> Option { + if self.instance_of::() { + unsafe { + let reference = T::Ref::from_void_ptr(self.0); + Some(T::wrap_under_get_rule(reference)) + } + } else { + None + } + } + + /// Similar to [`downcast`], but consumes self and can thus avoid touching the retain count. + /// + /// [`downcast`]: #method.downcast + #[inline] + pub fn downcast_into(self) -> Option { + if self.instance_of::() { + unsafe { + let reference = T::Ref::from_void_ptr(self.0); + mem::forget(self); + Some(T::wrap_under_create_rule(reference)) + } + } else { + None + } + } +} + +impl fmt::Debug for CFType { + /// Formats the value using [`CFCopyDescription`]. + /// + /// [`CFCopyDescription`]: https://developer.apple.com/documentation/corefoundation/1521252-cfcopydescription?language=objc + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let desc = unsafe { + CFString::wrap_under_create_rule(CFCopyDescription(self.0)) + }; + desc.fmt(f) + } +} + +impl Clone for CFType { + #[inline] + fn clone(&self) -> CFType { + unsafe { + TCFType::wrap_under_get_rule(self.0) + } + } +} + +impl PartialEq for CFType { + #[inline] + fn eq(&self, other: &CFType) -> bool { + unsafe { + CFEqual(self.as_CFTypeRef(), other.as_CFTypeRef()) != 0 + } + } +} + +declare_TCFType!(CFAllocator, CFAllocatorRef); +impl_TCFType!(CFAllocator, CFAllocatorRef, CFAllocatorGetTypeID); + +impl CFAllocator { + #[inline] + pub fn new(mut context: CFAllocatorContext) -> CFAllocator { + unsafe { + let allocator_ref = CFAllocatorCreate(kCFAllocatorDefault, &mut context); + TCFType::wrap_under_create_rule(allocator_ref) + } + } +} + + +/// All Core Foundation types implement this trait. The associated type `Ref` specifies the +/// associated Core Foundation type: e.g. for `CFType` this is `CFTypeRef`; for `CFArray` this is +/// `CFArrayRef`. +/// +/// Most structs that implement this trait will do so via the [`impl_TCFType`] macro. +/// +/// [`impl_TCFType`]: ../macro.impl_TCFType.html +pub trait TCFType { + /// The reference type wrapped inside this type. + type Ref: TCFTypeRef; + + /// Returns the object as its concrete TypeRef. + fn as_concrete_TypeRef(&self) -> Self::Ref; + + /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this + /// when following Core Foundation's "Create Rule". The reference count is *not* bumped. + unsafe fn wrap_under_create_rule(obj: Self::Ref) -> Self; + + /// Returns the type ID for this class. + fn type_id() -> CFTypeID; + + /// Returns the object as a wrapped `CFType`. The reference count is incremented by one. + #[inline] + fn as_CFType(&self) -> CFType { + unsafe { + TCFType::wrap_under_get_rule(self.as_CFTypeRef()) + } + } + + /// Returns the object as a wrapped `CFType`. Consumes self and avoids changing the reference + /// count. + #[inline] + fn into_CFType(self) -> CFType + where + Self: Sized, + { + let reference = self.as_CFTypeRef(); + mem::forget(self); + unsafe { TCFType::wrap_under_create_rule(reference) } + } + + /// Returns the object as a raw `CFTypeRef`. The reference count is not adjusted. + fn as_CFTypeRef(&self) -> CFTypeRef; + + /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this + /// when following Core Foundation's "Get Rule". The reference count *is* bumped. + unsafe fn wrap_under_get_rule(reference: Self::Ref) -> Self; + + /// Returns the reference count of the object. It is unwise to do anything other than test + /// whether the return value of this method is greater than zero. + #[inline] + fn retain_count(&self) -> CFIndex { + unsafe { + CFGetRetainCount(self.as_CFTypeRef()) + } + } + + /// Returns the type ID of this object. + #[inline] + fn type_of(&self) -> CFTypeID { + unsafe { + CFGetTypeID(self.as_CFTypeRef()) + } + } + + /// Writes a debugging version of this object on standard error. + fn show(&self) { + unsafe { + CFShow(self.as_CFTypeRef()) + } + } + + /// Returns true if this value is an instance of another type. + #[inline] + fn instance_of(&self) -> bool { + self.type_of() == OtherCFType::type_id() + } +} + +impl TCFType for CFType { + type Ref = CFTypeRef; + + #[inline] + fn as_concrete_TypeRef(&self) -> CFTypeRef { + self.0 + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: CFTypeRef) -> CFType { + let reference: CFTypeRef = CFRetain(reference); + TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> CFTypeRef { + self.as_concrete_TypeRef() + } + + #[inline] + unsafe fn wrap_under_create_rule(obj: CFTypeRef) -> CFType { + CFType(obj) + } + + #[inline] + fn type_id() -> CFTypeID { + // FIXME(pcwalton): Is this right? + 0 + } +} + +/// A reference to an element inside a container +pub struct ItemRef<'a, T: 'a>(ManuallyDrop, PhantomData<&'a T>); + +impl<'a, T> Deref for ItemRef<'a, T> { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl<'a, T: fmt::Debug> fmt::Debug for ItemRef<'a, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + +impl<'a, T: PartialEq> PartialEq for ItemRef<'a, T> { + fn eq(&self, other: &Self) -> bool { + self.0.eq(&other.0) + } +} + +/// A reference to a mutable element inside a container +pub struct ItemMutRef<'a, T: 'a>(ManuallyDrop, PhantomData<&'a T>); + +impl<'a, T> Deref for ItemMutRef<'a, T> { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl<'a, T> DerefMut for ItemMutRef<'a, T> { + fn deref_mut(&mut self) -> &mut T { + &mut self.0 + } +} + +impl<'a, T: fmt::Debug> fmt::Debug for ItemMutRef<'a, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + self.0.fmt(f) + } +} + +impl<'a, T: PartialEq> PartialEq for ItemMutRef<'a, T> { + fn eq(&self, other: &Self) -> bool { + self.0.eq(&other.0) + } +} + +/// A trait describing how to convert from the stored *mut c_void to the desired T +pub unsafe trait FromMutVoid { + unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> where Self: std::marker::Sized; +} + +unsafe impl FromMutVoid for u32 { + unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> { + ItemMutRef(ManuallyDrop::new(x as u32), PhantomData) + } +} + +unsafe impl FromMutVoid for *const c_void { + unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> { + ItemMutRef(ManuallyDrop::new(x), PhantomData) + } +} + +unsafe impl FromMutVoid for T { + unsafe fn from_mut_void<'a>(x: *mut c_void) -> ItemMutRef<'a, Self> { + ItemMutRef(ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), PhantomData) + } +} + +/// A trait describing how to convert from the stored *const c_void to the desired T +pub unsafe trait FromVoid { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> where Self: std::marker::Sized; +} + +unsafe impl FromVoid for u32 { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { + // Functions like CGFontCopyTableTags treat the void*'s as u32's + // so we convert by casting directly + ItemRef(ManuallyDrop::new(x as u32), PhantomData) + } +} + +unsafe impl FromVoid for *const c_void { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { + ItemRef(ManuallyDrop::new(x), PhantomData) + } +} + +unsafe impl FromVoid for T { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { + ItemRef(ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), PhantomData) + } +} + +/// A trait describing how to convert from the stored *const c_void to the desired T +pub unsafe trait ToVoid { + fn to_void(&self) -> *const c_void; +} + +unsafe impl ToVoid<*const c_void> for *const c_void { + fn to_void(&self) -> *const c_void { + *self + } +} + +unsafe impl<'a> ToVoid for &'a CFType { + fn to_void(&self) -> *const ::std::os::raw::c_void { + self.as_concrete_TypeRef().as_void_ptr() + } +} + +unsafe impl ToVoid for CFType { + fn to_void(&self) -> *const ::std::os::raw::c_void { + self.as_concrete_TypeRef().as_void_ptr() + } +} + +unsafe impl ToVoid for CFTypeRef { + fn to_void(&self) -> *const ::std::os::raw::c_void { + self.as_void_ptr() + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use std::mem; + use boolean::CFBoolean; + + #[test] + fn cftype_instance_of() { + let string = CFString::from_static_string("foo"); + let cftype = string.as_CFType(); + + assert!(cftype.instance_of::()); + assert!(!cftype.instance_of::()); + } + + #[test] + fn as_cftype_retain_count() { + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let cftype = string.as_CFType(); + assert_eq!(cftype.retain_count(), 2); + mem::drop(string); + assert_eq!(cftype.retain_count(), 1); + } + + #[test] + fn into_cftype_retain_count() { + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let cftype = string.into_CFType(); + assert_eq!(cftype.retain_count(), 1); + } + + #[test] + fn as_cftype_and_downcast() { + let string = CFString::from_static_string("bar"); + let cftype = string.as_CFType(); + let string2 = cftype.downcast::().unwrap(); + assert_eq!(string2.to_string(), "bar"); + + assert_eq!(string.retain_count(), 3); + assert_eq!(cftype.retain_count(), 3); + assert_eq!(string2.retain_count(), 3); + } + + #[test] + fn into_cftype_and_downcast_into() { + let string = CFString::from_static_string("bar"); + let cftype = string.into_CFType(); + let string2 = cftype.downcast_into::().unwrap(); + assert_eq!(string2.to_string(), "bar"); + assert_eq!(string2.retain_count(), 1); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/boolean.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/boolean.rs new file mode 100644 index 0000000..8c13b90 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/boolean.rs @@ -0,0 +1,70 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A Boolean type. + +pub use core_foundation_sys::number::{CFBooleanRef, CFBooleanGetTypeID, kCFBooleanTrue, kCFBooleanFalse}; + +use base::TCFType; + + +declare_TCFType!{ + /// A Boolean type. + /// + /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. + CFBoolean, CFBooleanRef +} +impl_TCFType!(CFBoolean, CFBooleanRef, CFBooleanGetTypeID); +impl_CFTypeDescription!(CFBoolean); + +impl CFBoolean { + pub fn true_value() -> CFBoolean { + unsafe { + TCFType::wrap_under_get_rule(kCFBooleanTrue) + } + } + + pub fn false_value() -> CFBoolean { + unsafe { + TCFType::wrap_under_get_rule(kCFBooleanFalse) + } + } +} + +impl From for CFBoolean { + fn from(value: bool) -> CFBoolean { + if value { + CFBoolean::true_value() + } else { + CFBoolean::false_value() + } + } +} + +impl From for bool { + fn from(value: CFBoolean) -> bool { + value.0 == unsafe { kCFBooleanTrue } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn to_and_from_bool() { + let b_false = CFBoolean::from(false); + let b_true = CFBoolean::from(true); + assert_ne!(b_false, b_true); + assert_eq!(b_false, CFBoolean::false_value()); + assert_eq!(b_true, CFBoolean::true_value()); + assert!(!bool::from(b_false)); + assert!(bool::from(b_true)); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/bundle.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/bundle.rs new file mode 100644 index 0000000..7d051ff --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/bundle.rs @@ -0,0 +1,152 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation Bundle Type + +pub use core_foundation_sys::bundle::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::{CFType, TCFType}; +use url::CFURL; +use dictionary::CFDictionary; +use std::os::raw::c_void; +use string::CFString; + +declare_TCFType!{ + /// A Bundle type. + CFBundle, CFBundleRef +} +impl_TCFType!(CFBundle, CFBundleRef, CFBundleGetTypeID); + +impl CFBundle { + pub fn new(bundleURL: CFURL) -> Option { + unsafe { + let bundle_ref = CFBundleCreate(kCFAllocatorDefault, bundleURL.as_concrete_TypeRef()); + if bundle_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(bundle_ref)) + } + } + } + + pub fn bundle_with_identifier(identifier: CFString) -> Option { + unsafe { + let bundle_ref = CFBundleGetBundleWithIdentifier(identifier.as_concrete_TypeRef()); + if bundle_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_get_rule(bundle_ref)) + } + } + } + + pub fn function_pointer_for_name(&self, function_name: CFString) -> *const c_void { + unsafe { + CFBundleGetFunctionPointerForName(self.as_concrete_TypeRef(), + function_name.as_concrete_TypeRef()) + } + } + + pub fn main_bundle() -> CFBundle { + unsafe { + let bundle_ref = CFBundleGetMainBundle(); + TCFType::wrap_under_get_rule(bundle_ref) + } + } + + pub fn info_dictionary(&self) -> CFDictionary { + unsafe { + let info_dictionary = CFBundleGetInfoDictionary(self.0); + TCFType::wrap_under_get_rule(info_dictionary) + } + } + + pub fn executable_url(&self) -> Option { + unsafe { + let exe_url = CFBundleCopyExecutableURL(self.0); + if exe_url.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(exe_url)) + } + } + } + + pub fn private_frameworks_url(&self) -> Option { + unsafe { + let fw_url = CFBundleCopyPrivateFrameworksURL(self.0); + if fw_url.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(fw_url)) + } + } + } + + pub fn shared_support_url(&self) -> Option { + unsafe { + let fw_url = CFBundleCopySharedSupportURL(self.0); + if fw_url.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(fw_url)) + } + } + } +} + + +#[test] +fn safari_executable_url() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_executable = CFBundle::new(cfurl_path) + .expect("Safari not present") + .executable_url(); + assert!(cfurl_executable.is_some()); + assert_eq!(cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/MacOS/Safari"); +} + +#[test] +fn safari_private_frameworks_url() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_executable = CFBundle::new(cfurl_path) + .expect("Safari not present") + .private_frameworks_url(); + assert!(cfurl_executable.is_some()); + assert_eq!(cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/Frameworks"); +} + +#[test] +fn non_existant_bundle() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/usr/local/foo"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + assert!(CFBundle::new(cfurl_path).is_none()); +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/characterset.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/characterset.rs new file mode 100644 index 0000000..d1b9439 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/characterset.rs @@ -0,0 +1,21 @@ +// Copyright 2019 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A set of Unicode compliant characters. + +pub use core_foundation_sys::characterset::*; + +use base::TCFType; + +declare_TCFType!{ + /// An immutable set of Unicde characters. + CFCharacterSet, CFCharacterSetRef +} +impl_TCFType!(CFCharacterSet, CFCharacterSetRef, CFCharacterSetGetTypeID); +impl_CFTypeDescription!(CFCharacterSet); diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/data.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/data.rs new file mode 100644 index 0000000..2b5010a --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/data.rs @@ -0,0 +1,63 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation byte buffers. + +pub use core_foundation_sys::data::*; +use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{kCFAllocatorDefault}; +use std::ops::Deref; +use std::slice; + +use base::{CFIndexConvertible, TCFType}; + + +declare_TCFType!{ + /// A byte buffer. + CFData, CFDataRef +} +impl_TCFType!(CFData, CFDataRef, CFDataGetTypeID); +impl_CFTypeDescription!(CFData); + +impl CFData { + pub fn from_buffer(buffer: &[u8]) -> CFData { + unsafe { + let data_ref = CFDataCreate(kCFAllocatorDefault, + buffer.as_ptr(), + buffer.len().to_CFIndex()); + TCFType::wrap_under_create_rule(data_ref) + } + } + + /// Returns a pointer to the underlying bytes in this data. Note that this byte buffer is + /// read-only. + #[inline] + pub fn bytes<'a>(&'a self) -> &'a [u8] { + unsafe { + slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) + } + } + + /// Returns the length of this byte buffer. + #[inline] + pub fn len(&self) -> CFIndex { + unsafe { + CFDataGetLength(self.0) + } + } +} + +impl Deref for CFData { + type Target = [u8]; + + #[inline] + fn deref(&self) -> &[u8] { + self.bytes() + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/date.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/date.rs new file mode 100644 index 0000000..57ee721 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/date.rs @@ -0,0 +1,130 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation date objects. + +pub use core_foundation_sys::date::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; + +#[cfg(feature = "with-chrono")] +use chrono::NaiveDateTime; + + +declare_TCFType!{ + /// A date. + CFDate, CFDateRef +} +impl_TCFType!(CFDate, CFDateRef, CFDateGetTypeID); +impl_CFTypeDescription!(CFDate); +impl_CFComparison!(CFDate, CFDateCompare); + +impl CFDate { + #[inline] + pub fn new(time: CFAbsoluteTime) -> CFDate { + unsafe { + let date_ref = CFDateCreate(kCFAllocatorDefault, time); + TCFType::wrap_under_create_rule(date_ref) + } + } + + #[inline] + pub fn now() -> CFDate { + CFDate::new(unsafe { CFAbsoluteTimeGetCurrent() }) + } + + #[inline] + pub fn abs_time(&self) -> CFAbsoluteTime { + unsafe { + CFDateGetAbsoluteTime(self.0) + } + } + + #[cfg(feature = "with-chrono")] + pub fn naive_utc(&self) -> NaiveDateTime { + let ts = unsafe { + self.abs_time() + kCFAbsoluteTimeIntervalSince1970 + }; + let (secs, nanos) = if ts.is_sign_positive() { + (ts.trunc() as i64, ts.fract()) + } else { + // nanoseconds can't be negative in NaiveDateTime + (ts.trunc() as i64 - 1, 1.0 - ts.fract().abs()) + }; + NaiveDateTime::from_timestamp(secs, (nanos * 1e9).floor() as u32) + } + + #[cfg(feature = "with-chrono")] + pub fn from_naive_utc(time: NaiveDateTime) -> CFDate { + let secs = time.timestamp(); + let nanos = time.timestamp_subsec_nanos(); + let ts = unsafe { + secs as f64 + (nanos as f64 / 1e9) - kCFAbsoluteTimeIntervalSince1970 + }; + CFDate::new(ts) + } +} + +#[cfg(test)] +mod test { + use super::CFDate; + use std::cmp::Ordering; + + #[cfg(feature = "with-chrono")] + use chrono::NaiveDateTime; + + #[cfg(feature = "with-chrono")] + fn approx_eq(a: f64, b: f64) -> bool { + use std::f64; + + let same_sign = a.is_sign_positive() == b.is_sign_positive(); + let equal = ((a - b).abs() / f64::min(a.abs() + b.abs(), f64::MAX)) < f64::EPSILON; + (same_sign && equal) + } + + #[test] + fn date_comparison() { + let now = CFDate::now(); + let past = CFDate::new(now.abs_time() - 1.0); + assert_eq!(now.cmp(&past), Ordering::Greater); + assert_eq!(now.cmp(&now), Ordering::Equal); + assert_eq!(past.cmp(&now), Ordering::Less); + } + + #[test] + fn date_equality() { + let now = CFDate::now(); + let same_time = CFDate::new(now.abs_time()); + assert_eq!(now, same_time); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn date_chrono_conversion_positive() { + let date = CFDate::now(); + let datetime = date.naive_utc(); + let converted = CFDate::from_naive_utc(datetime); + assert!(approx_eq(date.abs_time(), converted.abs_time())); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn date_chrono_conversion_negative() { + use super::kCFAbsoluteTimeIntervalSince1970; + + let ts = unsafe { + kCFAbsoluteTimeIntervalSince1970 - 420.0 + }; + let date = CFDate::new(ts); + let datetime: NaiveDateTime = date.naive_utc(); + let converted = CFDate::from_naive_utc(datetime); + assert!(approx_eq(date.abs_time(), converted.abs_time())); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/dictionary.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/dictionary.rs new file mode 100644 index 0000000..f954b71 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/dictionary.rs @@ -0,0 +1,409 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Dictionaries of key-value pairs. + +pub use core_foundation_sys::dictionary::*; + +use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; +use std::mem; +use std::os::raw::c_void; +use std::ptr; +use std::marker::PhantomData; + +use base::{ItemRef, FromVoid, ToVoid}; +use base::{CFIndexConvertible, TCFType}; +use ConcreteCFType; + +// consume the type parameters with PhantomDatas +pub struct CFDictionary(CFDictionaryRef, PhantomData, PhantomData); + +impl Drop for CFDictionary { + fn drop(&mut self) { + unsafe { CFRelease(self.as_CFTypeRef()) } + } +} + +impl_TCFType!(CFDictionary, CFDictionaryRef, CFDictionaryGetTypeID); +impl_CFTypeDescription!(CFDictionary); + +unsafe impl ConcreteCFType for CFDictionary<*const c_void, *const c_void> {} + +impl CFDictionary { + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFDictionary where K: TCFType, V: TCFType { + let (keys, values): (Vec, Vec) = pairs + .iter() + .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef())) + .unzip(); + + unsafe { + let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, + keys.as_ptr(), + values.as_ptr(), + keys.len().to_CFIndex(), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + TCFType::wrap_under_create_rule(dictionary_ref) + } + } + + #[inline] + pub fn to_untyped(&self) -> CFDictionary { + unsafe { CFDictionary::wrap_under_get_rule(self.0) } + } + + /// Returns a `CFMutableDictionary` pointing to the same underlying dictionary as this immutable one. + /// This should only be used when the underlying dictionary is mutable. + #[inline] + pub unsafe fn to_mutable(&self) -> CFMutableDictionary { + CFMutableDictionary::wrap_under_get_rule(self.0 as CFMutableDictionaryRef) + } + + /// Returns the same dictionary, but with the types reset to void pointers. + /// Equal to `to_untyped`, but is faster since it does not increment the retain count. + #[inline] + pub fn into_untyped(self) -> CFDictionary { + let reference = self.0; + mem::forget(self); + unsafe { CFDictionary::wrap_under_create_rule(reference) } + } + + #[inline] + pub fn len(&self) -> usize { + unsafe { + CFDictionaryGetCount(self.0) as usize + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn contains_key(&self, key: &K) -> bool where K: ToVoid { + unsafe { CFDictionaryContainsKey(self.0, key.to_void()) != 0 } + } + + #[inline] + pub fn find<'a, T: ToVoid>(&'a self, key: T) -> Option> where V: FromVoid, K: ToVoid { + unsafe { + let mut value: *const c_void = ptr::null(); + if CFDictionaryGetValueIfPresent(self.0, key.to_void(), &mut value) != 0 { + Some(V::from_void(value)) + } else { + None + } + } + } + + /// # Panics + /// + /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead + /// of panicking. + #[inline] + pub fn get<'a, T: ToVoid>(&'a self, key: T) -> ItemRef<'a, V> where V: FromVoid, K: ToVoid { + let ptr = key.to_void(); + self.find(key).unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) + } + + pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { + let length = self.len(); + let mut keys = Vec::with_capacity(length); + let mut values = Vec::with_capacity(length); + + unsafe { + CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr()); + keys.set_len(length); + values.set_len(length); + } + + (keys, values) + } +} + +// consume the type parameters with PhantomDatas +pub struct CFMutableDictionary(CFMutableDictionaryRef, PhantomData, PhantomData); + +impl Drop for CFMutableDictionary { + fn drop(&mut self) { + unsafe { CFRelease(self.as_CFTypeRef()) } + } +} + +impl_TCFType!(CFMutableDictionary, CFMutableDictionaryRef, CFDictionaryGetTypeID); +impl_CFTypeDescription!(CFMutableDictionary); + +impl CFMutableDictionary { + pub fn new() -> Self { + Self::with_capacity(0) + } + + pub fn with_capacity(capacity: isize) -> Self { + unsafe { + let dictionary_ref = CFDictionaryCreateMutable(kCFAllocatorDefault, + capacity as _, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + TCFType::wrap_under_create_rule(dictionary_ref) + } + } + + pub fn copy_with_capacity(&self, capacity: isize) -> Self { + unsafe { + let dictionary_ref = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, capacity as _, self.0); + TCFType::wrap_under_get_rule(dictionary_ref) + } + } + + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFMutableDictionary where K: ToVoid, V: ToVoid { + let mut result = Self::with_capacity(pairs.len() as _); + for &(ref key, ref value) in pairs { + result.add(key, value); + } + result + } + + #[inline] + pub fn to_untyped(&self) -> CFMutableDictionary { + unsafe { CFMutableDictionary::wrap_under_get_rule(self.0) } + } + + /// Returns the same dictionary, but with the types reset to void pointers. + /// Equal to `to_untyped`, but is faster since it does not increment the retain count. + #[inline] + pub fn into_untyped(self) -> CFMutableDictionary { + let reference = self.0; + mem::forget(self); + unsafe { CFMutableDictionary::wrap_under_create_rule(reference) } + } + + /// Returns a `CFDictionary` pointing to the same underlying dictionary as this mutable one. + #[inline] + pub fn to_immutable(&self) -> CFDictionary { + unsafe { CFDictionary::wrap_under_get_rule(self.0) } + } + + // Immutable interface + + #[inline] + pub fn len(&self) -> usize { + unsafe { + CFDictionaryGetCount(self.0) as usize + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn contains_key(&self, key: *const c_void) -> bool { + unsafe { + CFDictionaryContainsKey(self.0, key) != 0 + } + } + + #[inline] + pub fn find<'a>(&'a self, key: &K) -> Option> where V: FromVoid, K: ToVoid { + unsafe { + let mut value: *const c_void = ptr::null(); + if CFDictionaryGetValueIfPresent(self.0, key.to_void(), &mut value) != 0 { + Some(V::from_void(value)) + } else { + None + } + } + } + + /// # Panics + /// + /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead + /// of panicking. + #[inline] + pub fn get<'a>(&'a self, key: &K) -> ItemRef<'a, V> where V: FromVoid, K: ToVoid { + let ptr = key.to_void(); + self.find(&key).unwrap_or_else(|| panic!("No entry found for key {:p}", ptr)) + } + + pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { + let length = self.len(); + let mut keys = Vec::with_capacity(length); + let mut values = Vec::with_capacity(length); + + unsafe { + CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr()); + keys.set_len(length); + values.set_len(length); + } + + (keys, values) + } + + // Mutable interface + + /// Adds the key-value pair to the dictionary if no such key already exist. + #[inline] + pub fn add(&mut self, key: &K, value: &V) where K: ToVoid, V: ToVoid { + unsafe { CFDictionaryAddValue(self.0, key.to_void(), value.to_void()) } + } + + /// Sets the value of the key in the dictionary. + #[inline] + pub fn set(&mut self, key: K, value: V) where K: ToVoid, V: ToVoid { + unsafe { CFDictionarySetValue(self.0, key.to_void(), value.to_void()) } + } + + /// Replaces the value of the key in the dictionary. + #[inline] + pub fn replace(&mut self, key: K, value: V) where K: ToVoid, V: ToVoid { + unsafe { CFDictionaryReplaceValue(self.0, key.to_void(), value.to_void()) } + } + + /// Removes the value of the key from the dictionary. + #[inline] + pub fn remove(&mut self, key: K) where K: ToVoid { + unsafe { CFDictionaryRemoveValue(self.0, key.to_void()) } + } + + #[inline] + pub fn remove_all(&mut self) { + unsafe { CFDictionaryRemoveAllValues(self.0) } + } +} + +impl Default for CFMutableDictionary { + fn default() -> Self { + Self::new() + } +} + +impl<'a, K, V> From<&'a CFDictionary> for CFMutableDictionary { + /// Creates a new mutable dictionary with the key-value pairs from another dictionary. + /// The capacity of the new mutable dictionary is not limited. + fn from(dict: &'a CFDictionary) -> Self { + unsafe { + let mut_dict_ref = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, dict.0); + TCFType::wrap_under_create_rule(mut_dict_ref) + } + } +} + + +#[cfg(test)] +pub mod test { + use super::*; + use base::{CFType, TCFType}; + use boolean::CFBoolean; + use number::CFNumber; + use string::CFString; + + + #[test] + fn dictionary() { + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let d = CFDictionary::from_CFType_pairs(&[ + (bar.as_CFType(), boo.as_CFType()), + (baz.as_CFType(), tru.as_CFType()), + (foo.as_CFType(), n42.as_CFType()), + ]); + + let (v1, v2) = d.get_keys_and_values(); + assert_eq!(v1, &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert_eq!(v2, &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + } + + #[test] + fn mutable_dictionary() { + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let mut d = CFMutableDictionary::::new(); + d.add(&bar, &boo.as_CFType()); + d.add(&baz, &tru.as_CFType()); + d.add(&foo, &n42.as_CFType()); + assert_eq!(d.len(), 3); + + let (v1, v2) = d.get_keys_and_values(); + assert_eq!(v1, &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert_eq!(v2, &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + + d.remove(baz); + assert_eq!(d.len(), 2); + + let (v1, v2) = d.get_keys_and_values(); + assert_eq!(v1, &[bar.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert_eq!(v2, &[boo.as_CFTypeRef(), n42.as_CFTypeRef()]); + + d.remove_all(); + assert_eq!(d.len(), 0) + } + + #[test] + fn dict_find_and_contains_key() { + let dict = CFDictionary::from_CFType_pairs(&[ + ( + CFString::from_static_string("hello"), + CFBoolean::true_value(), + ), + ]); + let key = CFString::from_static_string("hello"); + let invalid_key = CFString::from_static_string("foobar"); + + assert!(dict.contains_key(&key)); + assert!(!dict.contains_key(&invalid_key)); + + let value = dict.find(&key).unwrap().clone(); + assert_eq!(value, CFBoolean::true_value()); + assert_eq!(dict.find(&invalid_key), None); + } + + #[test] + fn convert_immutable_to_mutable_dict() { + let dict: CFDictionary = CFDictionary::from_CFType_pairs(&[ + (CFString::from_static_string("Foo"), CFBoolean::true_value()), + ]); + let mut mut_dict = CFMutableDictionary::from(&dict); + assert_eq!(dict.retain_count(), 1); + assert_eq!(mut_dict.retain_count(), 1); + + assert_eq!(mut_dict.len(), 1); + assert_eq!(*mut_dict.get(&CFString::from_static_string("Foo")), CFBoolean::true_value()); + + mut_dict.add(&CFString::from_static_string("Bar"), &CFBoolean::false_value()); + assert_eq!(dict.len(), 1); + assert_eq!(mut_dict.len(), 2); + } + + #[test] + fn mutable_dictionary_as_immutable() { + let mut mut_dict: CFMutableDictionary = CFMutableDictionary::new(); + mut_dict.add(&CFString::from_static_string("Bar"), &CFBoolean::false_value()); + assert_eq!(mut_dict.retain_count(), 1); + + let dict = mut_dict.to_immutable(); + assert_eq!(mut_dict.retain_count(), 2); + assert_eq!(dict.retain_count(), 2); + assert_eq!(*dict.get(&CFString::from_static_string("Bar")), CFBoolean::false_value()); + + mem::drop(dict); + assert_eq!(mut_dict.retain_count(), 1); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/error.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/error.rs new file mode 100644 index 0000000..f100171 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/error.rs @@ -0,0 +1,71 @@ +// Copyright 2016 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation errors. + +pub use core_foundation_sys::error::*; + +use std::error::Error; +use std::fmt; + +use base::{CFIndex, TCFType}; +use string::CFString; + + +declare_TCFType!{ + /// An error value. + CFError, CFErrorRef +} +impl_TCFType!(CFError, CFErrorRef, CFErrorGetTypeID); + +impl fmt::Debug for CFError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("CFError") + .field("domain", &self.domain()) + .field("code", &self.code()) + .field("description", &self.description()) + .finish() + } +} + +impl fmt::Display for CFError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}", self.description()) + } +} + +impl Error for CFError { + fn description(&self) -> &str { + "a Core Foundation error" + } +} + +impl CFError { + /// Returns a string identifying the domain with which this error is + /// associated. + pub fn domain(&self) -> CFString { + unsafe { + let s = CFErrorGetDomain(self.0); + CFString::wrap_under_get_rule(s) + } + } + + /// Returns the code identifying this type of error. + pub fn code(&self) -> CFIndex { + unsafe { CFErrorGetCode(self.0) } + } + + /// Returns a human-presentable description of the error. + pub fn description(&self) -> CFString { + unsafe { + let s = CFErrorCopyDescription(self.0); + CFString::wrap_under_create_rule(s) + } + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/filedescriptor.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/filedescriptor.rs new file mode 100644 index 0000000..061bd2d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/filedescriptor.rs @@ -0,0 +1,210 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use core_foundation_sys::filedescriptor::*; + +use core_foundation_sys::base::{Boolean, CFIndex}; +use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; + +use base::TCFType; +use runloop::CFRunLoopSource; + +use std::mem::MaybeUninit; +use std::os::unix::io::{AsRawFd, RawFd}; +use std::ptr; + +declare_TCFType!{ + CFFileDescriptor, CFFileDescriptorRef +} +impl_TCFType!(CFFileDescriptor, CFFileDescriptorRef, CFFileDescriptorGetTypeID); + +impl CFFileDescriptor { + pub fn new(fd: RawFd, + closeOnInvalidate: bool, + callout: CFFileDescriptorCallBack, + context: Option<&CFFileDescriptorContext>) -> Option { + let context = context.map_or(ptr::null(), |c| c as *const _); + unsafe { + let fd_ref = CFFileDescriptorCreate(kCFAllocatorDefault, + fd, + closeOnInvalidate as Boolean, + callout, + context); + if fd_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(fd_ref)) + } + } + } + + pub fn context(&self) -> CFFileDescriptorContext { + unsafe { + let mut context = MaybeUninit::::uninit(); + CFFileDescriptorGetContext(self.0, context.as_mut_ptr()); + context.assume_init() + } + } + + pub fn enable_callbacks(&self, callback_types: CFOptionFlags) { + unsafe { + CFFileDescriptorEnableCallBacks(self.0, callback_types) + } + } + + pub fn disable_callbacks(&self, callback_types: CFOptionFlags) { + unsafe { + CFFileDescriptorDisableCallBacks(self.0, callback_types) + } + } + + pub fn valid(&self) -> bool { + unsafe { + CFFileDescriptorIsValid(self.0) != 0 + } + } + + pub fn invalidate(&self) { + unsafe { + CFFileDescriptorInvalidate(self.0) + } + } + + pub fn to_run_loop_source(&self, order: CFIndex) -> Option { + unsafe { + let source_ref = CFFileDescriptorCreateRunLoopSource( + kCFAllocatorDefault, + self.0, + order + ); + if source_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(source_ref)) + } + } + } +} + +impl AsRawFd for CFFileDescriptor { + fn as_raw_fd(&self) -> RawFd { + unsafe { + CFFileDescriptorGetNativeDescriptor(self.0) + } + } +} + + +#[cfg(test)] +mod test { + extern crate libc; + + use super::*; + use std::ffi::CString; + use std::os::raw::c_void; + use core_foundation_sys::base::{CFOptionFlags}; + use core_foundation_sys::runloop::{kCFRunLoopDefaultMode}; + use libc::O_RDWR; + use runloop::{CFRunLoop}; + + #[test] + fn test_consumed() { + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, true, never_callback, None); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + + // close() should fail + assert_eq!(unsafe { libc::close(raw_fd) }, -1); + } + + #[test] + fn test_unconsumed() { + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, false, never_callback, None); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + + // close() should succeed + assert_eq!(unsafe { libc::close(raw_fd) }, 0); + } + + extern "C" fn never_callback(_f: CFFileDescriptorRef, + _callback_types: CFOptionFlags, + _info_ptr: *mut c_void) { + unreachable!(); + } + + struct TestInfo { + value: CFOptionFlags + } + + #[test] + fn test_callback() { + let mut info = TestInfo { value: 0 }; + let context = CFFileDescriptorContext { + version: 0, + info: &mut info as *mut _ as *mut c_void, + retain: None, + release: None, + copyDescription: None + }; + + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, true, callback, Some(&context)); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + + let run_loop = CFRunLoop::get_current(); + let source = CFRunLoopSource::from_file_descriptor(&cf_fd, 0); + assert!(source.is_some()); + unsafe { + run_loop.add_source(&source.unwrap(), kCFRunLoopDefaultMode); + } + + info.value = 0; + cf_fd.enable_callbacks(kCFFileDescriptorReadCallBack); + CFRunLoop::run_current(); + assert_eq!(info.value, kCFFileDescriptorReadCallBack); + + info.value = 0; + cf_fd.enable_callbacks(kCFFileDescriptorWriteCallBack); + CFRunLoop::run_current(); + assert_eq!(info.value, kCFFileDescriptorWriteCallBack); + + info.value = 0; + cf_fd.disable_callbacks(kCFFileDescriptorReadCallBack | kCFFileDescriptorWriteCallBack); + + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + } + + extern "C" fn callback(_f: CFFileDescriptorRef, callback_types: CFOptionFlags, info_ptr: *mut c_void) { + assert!(!info_ptr.is_null()); + + let info: *mut TestInfo = info_ptr as *mut TestInfo; + + unsafe { (*info).value = callback_types }; + + CFRunLoop::get_current().stop(); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/lib.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/lib.rs new file mode 100644 index 0000000..c3c6122 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/lib.rs @@ -0,0 +1,233 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_snake_case)] + +//! This crate provides wrappers around the underlying CoreFoundation +//! types and functions that are available on Apple's operating systems. +//! +//! It also provides a framework for other crates to use when wrapping +//! other frameworks that use the CoreFoundation framework. + +extern crate core_foundation_sys; +extern crate libc; + +#[cfg(feature = "with-chrono")] +extern crate chrono; + +use base::TCFType; + +pub unsafe trait ConcreteCFType: TCFType {} + +/// Declare a Rust type that wraps an underlying CoreFoundation type. +/// +/// This will provide an implementation of `Drop` using [`CFRelease`]. +/// The type must have an implementation of the [`TCFType`] trait, usually +/// provided using the [`impl_TCFType`] macro. +/// +/// ``` +/// #[macro_use] extern crate core_foundation; +/// // Make sure that the `TCFType` trait is in scope. +/// use core_foundation::base::{CFTypeID, TCFType}; +/// +/// extern "C" { +/// // We need a function that returns the `CFTypeID`. +/// pub fn ShrubberyGetTypeID() -> CFTypeID; +/// } +/// +/// pub struct __Shrubbery {} +/// // The ref type must be a pointer to the underlying struct. +/// pub type ShrubberyRef = *const __Shrubbery; +/// +/// declare_TCFType!(Shrubbery, ShrubberyRef); +/// impl_TCFType!(Shrubbery, ShrubberyRef, ShrubberyGetTypeID); +/// # fn main() {} +/// ``` +/// +/// [`CFRelease`]: https://developer.apple.com/documentation/corefoundation/1521153-cfrelease +/// [`TCFType`]: base/trait.TCFType.html +/// [`impl_TCFType`]: macro.impl_TCFType.html +#[macro_export] +macro_rules! declare_TCFType { + ( + $(#[$doc:meta])* + $ty:ident, $raw:ident + ) => { + $(#[$doc])* + pub struct $ty($raw); + + impl Drop for $ty { + fn drop(&mut self) { + unsafe { $crate::base::CFRelease(self.as_CFTypeRef()) } + } + } + } +} + +/// Provide an implementation of the [`TCFType`] trait for the Rust +/// wrapper type around an underlying CoreFoundation type. +/// +/// See [`declare_TCFType`] for details. +/// +/// [`declare_TCFType`]: macro.declare_TCFType.html +/// [`TCFType`]: base/trait.TCFType.html +#[macro_export] +macro_rules! impl_TCFType { + ($ty:ident, $ty_ref:ident, $ty_id:ident) => { + impl_TCFType!($ty<>, $ty_ref, $ty_id); + unsafe impl $crate::ConcreteCFType for $ty { } + }; + + ($ty:ident<$($p:ident $(: $bound:path)*),*>, $ty_ref:ident, $ty_id:ident) => { + impl<$($p $(: $bound)*),*> $crate::base::TCFType for $ty<$($p),*> { + type Ref = $ty_ref; + + #[inline] + fn as_concrete_TypeRef(&self) -> $ty_ref { + self.0 + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: $ty_ref) -> Self { + let reference = $crate::base::CFRetain(reference as *const ::std::os::raw::c_void) as $ty_ref; + $crate::base::TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> $crate::base::CFTypeRef { + self.as_concrete_TypeRef() as $crate::base::CFTypeRef + } + + #[inline] + unsafe fn wrap_under_create_rule(reference: $ty_ref) -> Self { + // we need one PhantomData for each type parameter so call ourselves + // again with @Phantom $p to produce that + $ty(reference $(, impl_TCFType!(@Phantom $p))*) + } + + #[inline] + fn type_id() -> $crate::base::CFTypeID { + unsafe { + $ty_id() + } + } + } + + impl Clone for $ty { + #[inline] + fn clone(&self) -> $ty { + unsafe { + $ty::wrap_under_get_rule(self.0) + } + } + } + + impl PartialEq for $ty { + #[inline] + fn eq(&self, other: &$ty) -> bool { + self.as_CFType().eq(&other.as_CFType()) + } + } + + impl Eq for $ty { } + + unsafe impl<'a> $crate::base::ToVoid<$ty> for &'a $ty { + fn to_void(&self) -> *const ::std::os::raw::c_void { + use $crate::base::TCFTypeRef; + self.as_concrete_TypeRef().as_void_ptr() + } + } + + unsafe impl $crate::base::ToVoid<$ty> for $ty { + fn to_void(&self) -> *const ::std::os::raw::c_void { + use $crate::base::TCFTypeRef; + self.as_concrete_TypeRef().as_void_ptr() + } + } + + unsafe impl $crate::base::ToVoid<$ty> for $ty_ref { + fn to_void(&self) -> *const ::std::os::raw::c_void { + use $crate::base::TCFTypeRef; + self.as_void_ptr() + } + } + + }; + + (@Phantom $x:ident) => { ::std::marker::PhantomData }; +} + + +/// Implement `std::fmt::Debug` for the given type. +/// +/// This will invoke the implementation of `Debug` for [`CFType`] +/// which invokes [`CFCopyDescription`]. +/// +/// The type must have an implementation of the [`TCFType`] trait, usually +/// provided using the [`impl_TCFType`] macro. +/// +/// [`CFType`]: base/struct.CFType.html#impl-Debug +/// [`CFCopyDescription`]: https://developer.apple.com/documentation/corefoundation/1521252-cfcopydescription?language=objc +/// [`TCFType`]: base/trait.TCFType.html +/// [`impl_TCFType`]: macro.impl_TCFType.html +#[macro_export] +macro_rules! impl_CFTypeDescription { + ($ty:ident) => { + // it's fine to use an empty <> list + impl_CFTypeDescription!($ty<>); + }; + ($ty:ident<$($p:ident $(: $bound:path)*),*>) => { + impl<$($p $(: $bound)*),*> ::std::fmt::Debug for $ty<$($p),*> { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + self.as_CFType().fmt(f) + } + } + } +} + +#[macro_export] +macro_rules! impl_CFComparison { + ($ty:ident, $compare:ident) => { + impl PartialOrd for $ty { + #[inline] + fn partial_cmp(&self, other: &$ty) -> Option<::std::cmp::Ordering> { + unsafe { + Some($compare(self.as_concrete_TypeRef(), other.as_concrete_TypeRef(), ::std::ptr::null_mut()).into()) + } + } + } + + impl Ord for $ty { + #[inline] + fn cmp(&self, other: &$ty) -> ::std::cmp::Ordering { + self.partial_cmp(other).unwrap() + } + } + } +} + +pub mod array; +pub mod attributed_string; +pub mod base; +pub mod boolean; +pub mod characterset; +pub mod data; +pub mod date; +pub mod dictionary; +pub mod error; +pub mod filedescriptor; +pub mod number; +pub mod set; +pub mod string; +pub mod url; +pub mod bundle; +pub mod propertylist; +pub mod runloop; +pub mod timezone; +pub mod uuid; diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/number.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/number.rs new file mode 100644 index 0000000..a4b2aff --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/number.rs @@ -0,0 +1,120 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Immutable numbers. + +use core_foundation_sys::base::kCFAllocatorDefault; +pub use core_foundation_sys::number::*; +use std::os::raw::c_void; + +use base::TCFType; + + +declare_TCFType!{ + /// An immutable numeric value. + CFNumber, CFNumberRef +} +impl_TCFType!(CFNumber, CFNumberRef, CFNumberGetTypeID); +impl_CFTypeDescription!(CFNumber); +impl_CFComparison!(CFNumber, CFNumberCompare); + +impl CFNumber { + + #[inline] + pub fn to_i32(&self) -> Option { + unsafe { + let mut value: i32 = 0; + let ok = CFNumberGetValue(self.0, kCFNumberSInt32Type, &mut value as *mut i32 as *mut c_void); + if ok { Some(value) } else { None } + } + } + + #[inline] + pub fn to_i64(&self) -> Option { + unsafe { + let mut value: i64 = 0; + let ok = CFNumberGetValue(self.0, kCFNumberSInt64Type, &mut value as *mut i64 as *mut c_void); + if ok { Some(value) } else { None } + } + } + + #[inline] + pub fn to_f32(&self) -> Option { + unsafe { + let mut value: f32 = 0.0; + let ok = CFNumberGetValue(self.0, kCFNumberFloat32Type, &mut value as *mut f32 as *mut c_void); + if ok { Some(value) } else { None } + } + } + + #[inline] + pub fn to_f64(&self) -> Option { + unsafe { + let mut value: f64 = 0.0; + let ok = CFNumberGetValue(self.0, kCFNumberFloat64Type, &mut value as *mut f64 as *mut c_void); + if ok { Some(value) } else { None } + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: i32) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberSInt32Type, + &value as *const i32 as *const c_void, + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: i64) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberSInt64Type, + &value as *const i64 as *const c_void, + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: f32) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberFloat32Type, + &value as *const f32 as *const c_void, + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: f64) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberFloat64Type, + &value as *const f64 as *const c_void, + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/propertylist.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/propertylist.rs new file mode 100644 index 0000000..14ae173 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/propertylist.rs @@ -0,0 +1,325 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation property lists + +use std::ptr; +use std::mem; +use std::os::raw::c_void; + +use error::CFError; +use data::CFData; +use base::{CFType, TCFType, TCFTypeRef}; + +pub use core_foundation_sys::propertylist::*; +use core_foundation_sys::error::CFErrorRef; +use core_foundation_sys::base::{CFGetRetainCount, CFGetTypeID, CFIndex, CFRetain, + CFShow, CFTypeID, kCFAllocatorDefault}; + +pub fn create_with_data(data: CFData, + options: CFPropertyListMutabilityOptions) + -> Result<(*const c_void, CFPropertyListFormat), CFError> { + unsafe { + let mut error: CFErrorRef = ptr::null_mut(); + let mut format: CFPropertyListFormat = 0; + let property_list = CFPropertyListCreateWithData(kCFAllocatorDefault, + data.as_concrete_TypeRef(), + options, + &mut format, + &mut error); + if property_list.is_null() { + Err(TCFType::wrap_under_create_rule(error)) + } else { + Ok((property_list, format)) + } + } +} + +pub fn create_data(property_list: *const c_void, format: CFPropertyListFormat) -> Result { + unsafe { + let mut error: CFErrorRef = ptr::null_mut(); + let data_ref = CFPropertyListCreateData(kCFAllocatorDefault, + property_list, + format, + 0, + &mut error); + if data_ref.is_null() { + Err(TCFType::wrap_under_create_rule(error)) + } else { + Ok(TCFType::wrap_under_create_rule(data_ref)) + } + } +} + + +/// Trait for all subclasses of [`CFPropertyList`]. +/// +/// [`CFPropertyList`]: struct.CFPropertyList.html +pub trait CFPropertyListSubClass: TCFType { + /// Create an instance of the superclass type [`CFPropertyList`] for this instance. + /// + /// [`CFPropertyList`]: struct.CFPropertyList.html + #[inline] + fn to_CFPropertyList(&self) -> CFPropertyList { + unsafe { CFPropertyList::wrap_under_get_rule(self.as_concrete_TypeRef().as_void_ptr()) } + } + + /// Equal to [`to_CFPropertyList`], but consumes self and avoids changing the reference count. + /// + /// [`to_CFPropertyList`]: #method.to_CFPropertyList + #[inline] + fn into_CFPropertyList(self) -> CFPropertyList + where + Self: Sized, + { + let reference = self.as_concrete_TypeRef().as_void_ptr(); + mem::forget(self); + unsafe { CFPropertyList::wrap_under_create_rule(reference) } + } +} + +impl CFPropertyListSubClass for ::data::CFData {} +impl CFPropertyListSubClass for ::string::CFString {} +impl CFPropertyListSubClass for ::array::CFArray {} +impl CFPropertyListSubClass for ::dictionary::CFDictionary {} +impl CFPropertyListSubClass for ::date::CFDate {} +impl CFPropertyListSubClass for ::boolean::CFBoolean {} +impl CFPropertyListSubClass for ::number::CFNumber {} + + +declare_TCFType!{ + /// A CFPropertyList struct. This is superclass to [`CFData`], [`CFString`], [`CFArray`], + /// [`CFDictionary`], [`CFDate`], [`CFBoolean`], and [`CFNumber`]. + /// + /// This superclass type does not have its own `CFTypeID`, instead each instance has the `CFTypeID` + /// of the subclass it is an instance of. Thus, this type cannot implement the [`TCFType`] trait, + /// since it cannot implement the static [`TCFType::type_id()`] method. + /// + /// [`CFData`]: ../data/struct.CFData.html + /// [`CFString`]: ../string/struct.CFString.html + /// [`CFArray`]: ../array/struct.CFArray.html + /// [`CFDictionary`]: ../dictionary/struct.CFDictionary.html + /// [`CFDate`]: ../date/struct.CFDate.html + /// [`CFBoolean`]: ../boolean/struct.CFBoolean.html + /// [`CFNumber`]: ../number/struct.CFNumber.html + /// [`TCFType`]: ../base/trait.TCFType.html + /// [`TCFType::type_id()`]: ../base/trait.TCFType.html#method.type_of + CFPropertyList, CFPropertyListRef +} + +impl CFPropertyList { + #[inline] + pub fn as_concrete_TypeRef(&self) -> CFPropertyListRef { + self.0 + } + + #[inline] + pub unsafe fn wrap_under_get_rule(reference: CFPropertyListRef) -> CFPropertyList { + let reference = CFRetain(reference); + CFPropertyList(reference) + } + + #[inline] + pub fn as_CFType(&self) -> CFType { + unsafe { CFType::wrap_under_get_rule(self.as_CFTypeRef()) } + } + + #[inline] + pub fn into_CFType(self) -> CFType + where + Self: Sized, + { + let reference = self.as_CFTypeRef(); + mem::forget(self); + unsafe { TCFType::wrap_under_create_rule(reference) } + } + + #[inline] + pub fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { + self.as_concrete_TypeRef() + } + + #[inline] + pub unsafe fn wrap_under_create_rule(obj: CFPropertyListRef) -> CFPropertyList { + CFPropertyList(obj) + } + + /// Returns the reference count of the object. It is unwise to do anything other than test + /// whether the return value of this method is greater than zero. + #[inline] + pub fn retain_count(&self) -> CFIndex { + unsafe { CFGetRetainCount(self.as_CFTypeRef()) } + } + + /// Returns the type ID of this object. Will be one of CFData, CFString, CFArray, CFDictionary, + /// CFDate, CFBoolean, or CFNumber. + #[inline] + pub fn type_of(&self) -> CFTypeID { + unsafe { CFGetTypeID(self.as_CFTypeRef()) } + } + + /// Writes a debugging version of this object on standard error. + pub fn show(&self) { + unsafe { CFShow(self.as_CFTypeRef()) } + } + + /// Returns true if this value is an instance of another type. + #[inline] + pub fn instance_of(&self) -> bool { + self.type_of() == OtherCFType::type_id() + } +} + +impl Clone for CFPropertyList { + #[inline] + fn clone(&self) -> CFPropertyList { + unsafe { CFPropertyList::wrap_under_get_rule(self.0) } + } +} + +impl PartialEq for CFPropertyList { + #[inline] + fn eq(&self, other: &CFPropertyList) -> bool { + self.as_CFType().eq(&other.as_CFType()) + } +} + +impl Eq for CFPropertyList {} + +impl CFPropertyList { + /// Try to downcast the [`CFPropertyList`] to a subclass. Checking if the instance is the + /// correct subclass happens at runtime and `None` is returned if it is not the correct type. + /// Works similar to [`Box::downcast`] and [`CFType::downcast`]. + /// + /// # Examples + /// + /// ``` + /// # use core_foundation::string::CFString; + /// # use core_foundation::propertylist::{CFPropertyList, CFPropertyListSubClass}; + /// # + /// // Create a string. + /// let string: CFString = CFString::from_static_string("FooBar"); + /// // Cast it up to a property list. + /// let propertylist: CFPropertyList = string.to_CFPropertyList(); + /// // Cast it down again. + /// assert_eq!(propertylist.downcast::().unwrap().to_string(), "FooBar"); + /// ``` + /// + /// [`CFPropertyList`]: struct.CFPropertyList.html + /// [`Box::downcast`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.downcast + pub fn downcast(&self) -> Option { + if self.instance_of::() { + unsafe { + let subclass_ref = T::Ref::from_void_ptr(self.0); + Some(T::wrap_under_get_rule(subclass_ref)) + } + } else { + None + } + } + + /// Similar to [`downcast`], but consumes self and can thus avoid touching the retain count. + /// + /// [`downcast`]: #method.downcast + pub fn downcast_into(self) -> Option { + if self.instance_of::() { + unsafe { + let subclass_ref = T::Ref::from_void_ptr(self.0); + mem::forget(self); + Some(T::wrap_under_create_rule(subclass_ref)) + } + } else { + None + } + } +} + + + +#[cfg(test)] +pub mod test { + use super::*; + use string::CFString; + use boolean::CFBoolean; + + #[test] + fn test_property_list_serialization() { + use base::{TCFType, CFEqual}; + use boolean::CFBoolean; + use number::CFNumber; + use dictionary::CFDictionary; + use string::CFString; + use super::*; + + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let dict1 = CFDictionary::from_CFType_pairs(&[(bar.as_CFType(), boo.as_CFType()), + (baz.as_CFType(), tru.as_CFType()), + (foo.as_CFType(), n42.as_CFType())]); + + let data = create_data(dict1.as_CFTypeRef(), kCFPropertyListXMLFormat_v1_0).unwrap(); + let (dict2, _) = create_with_data(data, kCFPropertyListImmutable).unwrap(); + unsafe { + assert_eq!(CFEqual(dict1.as_CFTypeRef(), dict2), 1); + } + } + + #[test] + fn to_propertylist_retain_count() { + let string = CFString::from_static_string("Bar"); + assert_eq!(string.retain_count(), 1); + + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + assert_eq!(propertylist.retain_count(), 2); + + mem::drop(string); + assert_eq!(propertylist.retain_count(), 1); + } + + #[test] + fn downcast_string() { + let propertylist = CFString::from_static_string("Bar").to_CFPropertyList(); + assert_eq!(propertylist.downcast::().unwrap().to_string(), "Bar"); + assert!(propertylist.downcast::().is_none()); + } + + #[test] + fn downcast_boolean() { + let propertylist = CFBoolean::true_value().to_CFPropertyList(); + assert!(propertylist.downcast::().is_some()); + assert!(propertylist.downcast::().is_none()); + } + + #[test] + fn downcast_into_fail() { + let string = CFString::from_static_string("Bar"); + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + + assert!(propertylist.downcast_into::().is_none()); + assert_eq!(string.retain_count(), 1); + } + + #[test] + fn downcast_into() { + let string = CFString::from_static_string("Bar"); + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + + let string2 = propertylist.downcast_into::().unwrap(); + assert_eq!(string2.to_string(), "Bar"); + assert_eq!(string2.retain_count(), 2); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/runloop.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/runloop.rs new file mode 100644 index 0000000..5b27028 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/runloop.rs @@ -0,0 +1,198 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +pub use core_foundation_sys::runloop::*; +use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; +use core_foundation_sys::string::CFStringRef; + +use base::{TCFType}; +use date::{CFAbsoluteTime, CFTimeInterval}; +use filedescriptor::CFFileDescriptor; +use string::{CFString}; + +pub type CFRunLoopMode = CFStringRef; + + +declare_TCFType!(CFRunLoop, CFRunLoopRef); +impl_TCFType!(CFRunLoop, CFRunLoopRef, CFRunLoopGetTypeID); +impl_CFTypeDescription!(CFRunLoop); + +impl CFRunLoop { + pub fn get_current() -> CFRunLoop { + unsafe { + let run_loop_ref = CFRunLoopGetCurrent(); + TCFType::wrap_under_get_rule(run_loop_ref) + } + } + + pub fn get_main() -> CFRunLoop { + unsafe { + let run_loop_ref = CFRunLoopGetMain(); + TCFType::wrap_under_get_rule(run_loop_ref) + } + } + + pub fn run_current() { + unsafe { + CFRunLoopRun(); + } + } + + pub fn stop(&self) { + unsafe { + CFRunLoopStop(self.0); + } + } + + pub fn current_mode(&self) -> Option { + unsafe { + let string_ref = CFRunLoopCopyCurrentMode(self.0); + if string_ref.is_null() { + return None; + } + + let cf_string: CFString = TCFType::wrap_under_create_rule(string_ref); + Some(cf_string.to_string()) + } + } + + pub fn contains_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsTimer(self.0, timer.0, mode) != 0 + } + } + + pub fn add_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddTimer(self.0, timer.0, mode); + } + } + + pub fn remove_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveTimer(self.0, timer.0, mode); + } + } + + pub fn contains_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsSource(self.0, source.0, mode) != 0 + } + } + + pub fn add_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddSource(self.0, source.0, mode); + } + } + + pub fn remove_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveSource(self.0, source.0, mode); + } + } + + pub fn contains_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsObserver(self.0, observer.0, mode) != 0 + } + } + + pub fn add_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddObserver(self.0, observer.0, mode); + } + } + + pub fn remove_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveObserver(self.0, observer.0, mode); + } + } + +} + + +declare_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef); +impl_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef, CFRunLoopTimerGetTypeID); + +impl CFRunLoopTimer { + pub fn new(fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimer { + unsafe { + let timer_ref = CFRunLoopTimerCreate(kCFAllocatorDefault, fireDate, interval, flags, order, callout, context); + TCFType::wrap_under_create_rule(timer_ref) + } + } +} + + +declare_TCFType!(CFRunLoopSource, CFRunLoopSourceRef); +impl_TCFType!(CFRunLoopSource, CFRunLoopSourceRef, CFRunLoopSourceGetTypeID); + +impl CFRunLoopSource { + pub fn from_file_descriptor(fd: &CFFileDescriptor, order: CFIndex) -> Option { + fd.to_run_loop_source(order) + } +} + +declare_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef); +impl_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef, CFRunLoopObserverGetTypeID); + +#[cfg(test)] +mod test { + use super::*; + use date::{CFDate, CFAbsoluteTime}; + use std::mem; + use std::os::raw::c_void; + use std::sync::mpsc; + + #[test] + fn wait_200_milliseconds() { + let run_loop = CFRunLoop::get_current(); + + let now = CFDate::now().abs_time(); + let (elapsed_tx, elapsed_rx) = mpsc::channel(); + let mut info = Info { + start_time: now, + elapsed_tx, + }; + let mut context = CFRunLoopTimerContext { + version: 0, + info: &mut info as *mut _ as *mut c_void, + retain: None, + release: None, + copyDescription: None, + }; + + let run_loop_timer = CFRunLoopTimer::new(now + 0.20f64, 0f64, 0, 0, timer_popped, &mut context); + unsafe { + run_loop.add_timer(&run_loop_timer, kCFRunLoopDefaultMode); + } + CFRunLoop::run_current(); + let elapsed = elapsed_rx.try_recv().unwrap(); + println!("wait_200_milliseconds, elapsed: {}", elapsed); + assert!(elapsed > 0.19 && elapsed < 0.30); + } + + struct Info { + start_time: CFAbsoluteTime, + elapsed_tx: mpsc::Sender, + } + + extern "C" fn timer_popped(_timer: CFRunLoopTimerRef, raw_info: *mut c_void) { + let info: *mut Info = unsafe { mem::transmute(raw_info) }; + let now = CFDate::now().abs_time(); + let elapsed = now - unsafe { (*info).start_time }; + let _ = unsafe { (*info).elapsed_tx.send(elapsed) }; + CFRunLoop::get_current().stop(); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/set.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/set.rs new file mode 100644 index 0000000..f06d8a3 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/set.rs @@ -0,0 +1,44 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! An immutable bag of elements. + +pub use core_foundation_sys::set::*; +use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; + +use base::{CFIndexConvertible, TCFType}; + +use std::os::raw::c_void; +use std::marker::PhantomData; + +/// An immutable bag of elements. +pub struct CFSet(CFSetRef, PhantomData); + +impl Drop for CFSet { + fn drop(&mut self) { + unsafe { CFRelease(self.as_CFTypeRef()) } + } +} + +impl_TCFType!(CFSet, CFSetRef, CFSetGetTypeID); +impl_CFTypeDescription!(CFSet); + +impl CFSet { + /// Creates a new set from a list of `CFType` instances. + pub fn from_slice(elems: &[T]) -> CFSet where T: TCFType { + unsafe { + let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); + let set_ref = CFSetCreate(kCFAllocatorDefault, + elems.as_ptr(), + elems.len().to_CFIndex(), + &kCFTypeSetCallBacks); + TCFType::wrap_under_create_rule(set_ref) + } + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/string.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/string.rs new file mode 100644 index 0000000..021479c --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/string.rs @@ -0,0 +1,150 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Immutable strings. + +pub use core_foundation_sys::string::*; + +use base::{CFIndexConvertible, TCFType}; + +use core_foundation_sys::base::{Boolean, CFIndex, CFRange}; +use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull}; +use std::borrow::Cow; +use std::fmt; +use std::str::{self, FromStr}; +use std::ptr; +use std::ffi::CStr; + + +declare_TCFType!{ + /// An immutable string in one of a variety of encodings. + CFString, CFStringRef +} +impl_TCFType!(CFString, CFStringRef, CFStringGetTypeID); + +impl FromStr for CFString { + type Err = (); + + /// See also CFString::new for a variant of this which does not return a Result + #[inline] + fn from_str(string: &str) -> Result { + Ok(CFString::new(string)) + } +} + +impl<'a> From<&'a str> for CFString { + #[inline] + fn from(string: &'a str) -> CFString { + CFString::new(string) + } +} + +impl<'a> From<&'a CFString> for Cow<'a, str> { + fn from(cf_str: &'a CFString) -> Cow<'a, str> { + unsafe { + // Do this without allocating if we can get away with it + let c_string = CFStringGetCStringPtr(cf_str.0, kCFStringEncodingUTF8); + if !c_string.is_null() { + let c_str = CStr::from_ptr(c_string); + Cow::Borrowed(str::from_utf8_unchecked(c_str.to_bytes())) + } else { + let char_len = cf_str.char_len(); + + // First, ask how big the buffer ought to be. + let mut bytes_required: CFIndex = 0; + CFStringGetBytes(cf_str.0, + CFRange { location: 0, length: char_len }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + ptr::null_mut(), + 0, + &mut bytes_required); + + // Then, allocate the buffer and actually copy. + let mut buffer = vec![b'\x00'; bytes_required as usize]; + + let mut bytes_used: CFIndex = 0; + let chars_written = CFStringGetBytes(cf_str.0, + CFRange { location: 0, length: char_len }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + buffer.as_mut_ptr(), + buffer.len().to_CFIndex(), + &mut bytes_used); + assert_eq!(chars_written, char_len); + + // This is dangerous; we over-allocate and null-terminate the string (during + // initialization). + assert_eq!(bytes_used, buffer.len().to_CFIndex()); + Cow::Owned(String::from_utf8_unchecked(buffer)) + } + } + } +} + +impl fmt::Display for CFString { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(&Cow::from(self)) + } +} + +impl fmt::Debug for CFString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "\"{}\"", self) + } +} + + +impl CFString { + /// Creates a new `CFString` instance from a Rust string. + #[inline] + pub fn new(string: &str) -> CFString { + unsafe { + let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean); + CFString::wrap_under_create_rule(string_ref) + } + } + + /// Like `CFString::new`, but references a string that can be used as a backing store + /// by virtue of being statically allocated. + #[inline] + pub fn from_static_string(string: &'static str) -> CFString { + unsafe { + let string_ref = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean, + kCFAllocatorNull); + TCFType::wrap_under_create_rule(string_ref) + } + } + + /// Returns the number of characters in the string. + #[inline] + pub fn char_len(&self) -> CFIndex { + unsafe { + CFStringGetLength(self.0) + } + } +} + +#[test] +fn string_and_back() { + let original = "The quick brown fox jumped over the slow lazy dog."; + let cfstr = CFString::from_static_string(original); + let converted = cfstr.to_string(); + assert_eq!(converted, original); +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/timezone.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/timezone.rs new file mode 100644 index 0000000..66aadb7 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/timezone.rs @@ -0,0 +1,95 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation time zone objects. + +pub use core_foundation_sys::timezone::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; +use date::{CFDate, CFTimeInterval}; + +#[cfg(feature = "with-chrono")] +use chrono::{FixedOffset, NaiveDateTime}; + + +declare_TCFType!{ + /// A time zone. + CFTimeZone, CFTimeZoneRef +} +impl_TCFType!(CFTimeZone, CFTimeZoneRef, CFTimeZoneGetTypeID); +impl_CFTypeDescription!(CFTimeZone); + +impl Default for CFTimeZone { + fn default() -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCopyDefault(); + TCFType::wrap_under_create_rule(tz_ref) + } + } +} + +impl CFTimeZone { + #[inline] + pub fn new(interval: CFTimeInterval) -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, interval); + TCFType::wrap_under_create_rule(tz_ref) + } + } + + #[inline] + pub fn system() -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCopySystem(); + TCFType::wrap_under_create_rule(tz_ref) + } + } + + pub fn seconds_from_gmt(&self, date: CFDate) -> CFTimeInterval { + unsafe { + CFTimeZoneGetSecondsFromGMT(self.0, date.abs_time()) + } + } + + #[cfg(feature = "with-chrono")] + pub fn offset_at_date(&self, date: NaiveDateTime) -> FixedOffset { + let date = CFDate::from_naive_utc(date); + FixedOffset::east(self.seconds_from_gmt(date) as i32) + } + + #[cfg(feature = "with-chrono")] + pub fn from_offset(offset: FixedOffset) -> CFTimeZone { + CFTimeZone::new(offset.local_minus_utc() as f64) + } +} + +#[cfg(test)] +mod test { + use super::CFTimeZone; + + #[cfg(feature = "with-chrono")] + use chrono::{NaiveDateTime, FixedOffset}; + + #[test] + fn timezone_comparison() { + let system = CFTimeZone::system(); + let default = CFTimeZone::default(); + assert_eq!(system, default); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn timezone_chrono_conversion() { + let offset = FixedOffset::west(28800); + let tz = CFTimeZone::from_offset(offset); + let converted = tz.offset_at_date(NaiveDateTime::from_timestamp(0, 0)); + assert_eq!(offset, converted); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/url.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/url.rs new file mode 100644 index 0000000..86470de --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/url.rs @@ -0,0 +1,156 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A URL type for Core Foundation. + +pub use core_foundation_sys::url::*; + +use base::{TCFType, CFIndex}; +use string::{CFString}; + +use core_foundation_sys::base::{kCFAllocatorDefault, Boolean}; +use std::fmt; +use std::mem::MaybeUninit; +use std::ptr; +use std::path::{Path, PathBuf}; + +use libc::{c_char, strlen, PATH_MAX}; + +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt; +#[cfg(unix)] +use std::ffi::OsStr; + + +declare_TCFType!(CFURL, CFURLRef); +impl_TCFType!(CFURL, CFURLRef, CFURLGetTypeID); + +impl fmt::Debug for CFURL { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let string: CFString = TCFType::wrap_under_get_rule(CFURLGetString(self.0)); + write!(f, "{}", string.to_string()) + } + } +} + +impl CFURL { + pub fn from_path>(path: P, isDirectory: bool) -> Option { + let path_bytes; + #[cfg(unix)] + { + path_bytes = path.as_ref().as_os_str().as_bytes() + } + #[cfg(not(unix))] + { + // XXX: Getting non-valid UTF8 paths into CoreFoundation on Windows is going to be unpleasant + // CFURLGetWideFileSystemRepresentation might help + path_bytes = match path.as_ref().to_str() { + Some(path) => path, + None => return None, + } + } + + unsafe { + let url_ref = CFURLCreateFromFileSystemRepresentation(ptr::null_mut(), path_bytes.as_ptr(), path_bytes.len() as CFIndex, isDirectory as u8); + if url_ref.is_null() { + return None; + } + Some(TCFType::wrap_under_create_rule(url_ref)) + } + } + + pub fn from_file_system_path(filePath: CFString, pathStyle: CFURLPathStyle, isDirectory: bool) -> CFURL { + unsafe { + let url_ref = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath.as_concrete_TypeRef(), pathStyle, isDirectory as u8); + TCFType::wrap_under_create_rule(url_ref) + } + } + + #[cfg(unix)] + pub fn to_path(&self) -> Option { + // implementing this on Windows is more complicated because of the different OsStr representation + unsafe { + let mut buf = [0u8; PATH_MAX as usize]; + let result = CFURLGetFileSystemRepresentation(self.0, true as Boolean, buf.as_mut_ptr(), buf.len() as CFIndex); + if result == false as Boolean { + return None; + } + let len = strlen(buf.as_ptr() as *const c_char); + let path = OsStr::from_bytes(&buf[0..len]); + Some(PathBuf::from(path)) + } + } + + pub fn get_string(&self) -> CFString { + unsafe { + TCFType::wrap_under_get_rule(CFURLGetString(self.0)) + } + } + + pub fn get_file_system_path(&self, pathStyle: CFURLPathStyle) -> CFString { + unsafe { + TCFType::wrap_under_create_rule(CFURLCopyFileSystemPath(self.as_concrete_TypeRef(), pathStyle)) + } + } + + pub fn absolute(&self) -> CFURL { + unsafe { + TCFType::wrap_under_create_rule(CFURLCopyAbsoluteURL(self.as_concrete_TypeRef())) + } + } +} + +#[test] +fn file_url_from_path() { + let path = "/usr/local/foo/"; + let cfstr_path = CFString::from_static_string(path); + let cfurl = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + assert_eq!(cfurl.get_string().to_string(), "file:///usr/local/foo/"); +} + +#[cfg(unix)] +#[test] +fn non_utf8() { + use std::ffi::OsStr; + let path = Path::new(OsStr::from_bytes(b"/\xC0/blame")); + let cfurl = CFURL::from_path(path, false).unwrap(); + assert_eq!(cfurl.to_path().unwrap(), path); + let len = unsafe { CFURLGetBytes(cfurl.as_concrete_TypeRef(), ptr::null_mut(), 0) }; + assert_eq!(len, 17); +} + +#[test] +fn absolute_file_url() { + use core_foundation_sys::url::CFURLCreateWithFileSystemPathRelativeToBase; + use std::path::PathBuf; + + let path = "/usr/local/foo"; + let file = "bar"; + + let cfstr_path = CFString::from_static_string(path); + let cfstr_file = CFString::from_static_string(file); + let cfurl_base = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_relative: CFURL = unsafe { + let url_ref = CFURLCreateWithFileSystemPathRelativeToBase(kCFAllocatorDefault, + cfstr_file.as_concrete_TypeRef(), + kCFURLPOSIXPathStyle, + false as u8, + cfurl_base.as_concrete_TypeRef()); + TCFType::wrap_under_create_rule(url_ref) + }; + + let mut absolute_path = PathBuf::from(path); + absolute_path.push(file); + + assert_eq!(cfurl_relative.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), file); + assert_eq!(cfurl_relative.absolute().get_file_system_path(kCFURLPOSIXPathStyle).to_string(), + absolute_path.to_str().unwrap()); +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/src/uuid.rs b/third_party/cargo/vendor/core-foundation-0.7.0/src/uuid.rs new file mode 100644 index 0000000..6be734d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/src/uuid.rs @@ -0,0 +1,118 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation UUID objects. + +#[cfg(feature = "with-uuid")] +extern crate uuid; + +pub use core_foundation_sys::uuid::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; + +#[cfg(feature = "with-uuid")] +use self::uuid::Uuid; + + +declare_TCFType! { + /// A UUID. + CFUUID, CFUUIDRef +} +impl_TCFType!(CFUUID, CFUUIDRef, CFUUIDGetTypeID); +impl_CFTypeDescription!(CFUUID); + +impl CFUUID { + #[inline] + pub fn new() -> CFUUID { + unsafe { + let uuid_ref = CFUUIDCreate(kCFAllocatorDefault); + TCFType::wrap_under_create_rule(uuid_ref) + } + } +} + +impl Default for CFUUID { + fn default() -> Self { + Self::new() + } +} + +#[cfg(feature = "with-uuid")] +impl Into for CFUUID { + fn into(self) -> Uuid { + let b = unsafe { + CFUUIDGetUUIDBytes(self.0) + }; + let bytes = [ + b.byte0, + b.byte1, + b.byte2, + b.byte3, + b.byte4, + b.byte5, + b.byte6, + b.byte7, + b.byte8, + b.byte9, + b.byte10, + b.byte11, + b.byte12, + b.byte13, + b.byte14, + b.byte15, + ]; + Uuid::from_bytes(&bytes).unwrap() + } +} + +#[cfg(feature = "with-uuid")] +impl From for CFUUID { + fn from(uuid: Uuid) -> CFUUID { + let b = uuid.as_bytes(); + let bytes = CFUUIDBytes { + byte0: b[0], + byte1: b[1], + byte2: b[2], + byte3: b[3], + byte4: b[4], + byte5: b[5], + byte6: b[6], + byte7: b[7], + byte8: b[8], + byte9: b[9], + byte10: b[10], + byte11: b[11], + byte12: b[12], + byte13: b[13], + byte14: b[14], + byte15: b[15], + }; + unsafe { + let uuid_ref = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, bytes); + TCFType::wrap_under_create_rule(uuid_ref) + } + } +} + + +#[cfg(test)] +#[cfg(feature = "with-uuid")] +mod test { + use super::CFUUID; + use uuid::Uuid; + + #[test] + fn uuid_conversion() { + let cf_uuid = CFUUID::new(); + let uuid: Uuid = cf_uuid.clone().into(); + let converted = CFUUID::from(uuid); + assert_eq!(cf_uuid, converted); + } +} diff --git a/third_party/cargo/vendor/core-foundation-0.7.0/tests/use_macro_outside_crate.rs b/third_party/cargo/vendor/core-foundation-0.7.0/tests/use_macro_outside_crate.rs new file mode 100644 index 0000000..ff1c17d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-0.7.0/tests/use_macro_outside_crate.rs @@ -0,0 +1,28 @@ +#[macro_use] +extern crate core_foundation; + +use core_foundation::base::{CFComparisonResult, TCFType}; +use std::os::raw::c_void; + +// sys equivalent stuff that must be declared + +#[repr(C)] +pub struct __CFFooBar(c_void); + +pub type CFFooBarRef = *const __CFFooBar; + +extern "C" { + pub fn CFFooBarGetTypeID() -> core_foundation::base::CFTypeID; + pub fn fake_compare( + this: CFFooBarRef, + other: CFFooBarRef, + context: *mut c_void, + ) -> CFComparisonResult; +} + +// Try to use the macros outside of the crate + +declare_TCFType!(CFFooBar, CFFooBarRef); +impl_TCFType!(CFFooBar, CFFooBarRef, CFFooBarGetTypeID); +impl_CFTypeDescription!(CFFooBar); +impl_CFComparison!(CFFooBar, fake_compare); diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/.cargo-checksum.json b/third_party/cargo/vendor/core-foundation-sys-0.7.0/.cargo-checksum.json new file mode 100644 index 0000000..86e911d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2f56db7bbb02e7e0e2329179c2bb533fbe36a6196b7f0a539b710291cced25ae","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","build.rs":"9433ed3b20cc99e716dda4c6d8507c29bc04882544cbbea8d4e48ba80fd0fa12","src/array.rs":"40c305658e16b07d86353a5ad34e7b5fb98720f19cc2b5173360d6a61ce2642f","src/attributed_string.rs":"693b6c745c5aef1929595c94363d500b4b25ebcfed0b4b8dee0103b8fc0537f8","src/base.rs":"369fb6710bb342f488c1207db2339f16d51bea7b7cb437c88dfb9b3ecb55f788","src/bundle.rs":"701b99db500b1260b3327182e965483d7cc1b220e0c2b3b7b97a3bf1a17b9dcb","src/characterset.rs":"a10bbb42ddc74b3dc50b43ae6a50cc9d9a1cd08b975a1ce1b092be4bf64448a6","src/data.rs":"7cf4ddbc62635434fd3552739ffae9dde5f5d34f0ad0bb818068d3ac26403784","src/date.rs":"c064ee4c3ebd1927532c34871e2e41179d6e3c3e400f6b409a18ad9e2337477f","src/dictionary.rs":"3327a6f90f1e0db5e3fde1973e2df4143ca896716a816d03f2b17c8e988c5159","src/error.rs":"6205ebeb7631daa8bcd560862b6daa10f640c8c117ce5f6f7184f268dcbcb42a","src/filedescriptor.rs":"49580654b657811fade7adaa256f5f895cb011c9baa4731e2f44a6ec7fdba235","src/lib.rs":"f815234d32327532da600f47e9a006550d8993dcd695b803d0660316899f9319","src/messageport.rs":"e9227d5907cba8e29cdeea41bcb3ae5c7840220442953ab19aace31a84542f47","src/number.rs":"b1154203e74cb2258ba5520e20bcd4d524f1a957e09a19dd026b18d23baa3868","src/propertylist.rs":"7ec928438826c4ce40befedf3de0a37c8ecbc0fc17896dfa629d5864000b2cfe","src/runloop.rs":"26ca33e2472d191f583e01c24e8cd262f54de8b542fbe7278f33ab08b2925794","src/set.rs":"8aef5f4ba75a067e271ad6cb960569f1d22a0acee0eb6c79e31bb8b636619d9d","src/string.rs":"ef2c408bf1fcea5d9106329fc48d659aabbdbca05eb121dfa27a221829bc4b89","src/timezone.rs":"42741f556af081be32987d2705488959c60aeb794e7c737b092f0dce5851ca89","src/url.rs":"4358f756ed3d5e9afd5a7f3e2e9115adc6133b47dc7ce59d6ebb32c6610b0e8f","src/uuid.rs":"82f75efa73d0842dff2e13d299c166c6593a77fcb69c4b7629a2df1c17ae507d"},"package":"b3a71ab494c0b5b860bdc8407ae08978052417070c2ced38573a9157ad75b8ac"} \ No newline at end of file diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/BUILD b/third_party/cargo/vendor/core-foundation-sys-0.7.0/BUILD similarity index 87% rename from third_party/cargo/vendor/semver-parser-0.7.0/BUILD rename to third_party/cargo/vendor/core-foundation-sys-0.7.0/BUILD index 8aaf66e..9ba1e73 100644 --- a/third_party/cargo/vendor/semver-parser-0.7.0/BUILD +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/BUILD @@ -23,9 +23,10 @@ load( ) +# Unsupported target "build-script-build" with type "custom-build" omitted rust_library( - name = "semver_parser", + name = "core_foundation_sys", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/Cargo.toml b/third_party/cargo/vendor/core-foundation-sys-0.7.0/Cargo.toml new file mode 100644 index 0000000..1098711 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/Cargo.toml @@ -0,0 +1,27 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "core-foundation-sys" +version = "0.7.0" +authors = ["The Servo Project Developers"] +build = "build.rs" +description = "Bindings to Core Foundation for macOS" +homepage = "https://github.com/servo/core-foundation-rs" +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" + +[dependencies] + +[features] +mac_os_10_7_support = [] +mac_os_10_8_features = [] diff --git a/third_party/cargo/vendor/cocoa-0.18.5/LICENSE-APACHE b/third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/cocoa-0.18.5/LICENSE-APACHE rename to third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-MIT b/third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-MIT new file mode 100644 index 0000000..807526f --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2012-2013 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/build.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/build.rs new file mode 100644 index 0000000..1f03b06 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/build.rs @@ -0,0 +1,14 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + if std::env::var("TARGET").unwrap().contains("-apple") { + println!("cargo:rustc-link-lib=framework=CoreFoundation"); + } +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/array.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/array.rs new file mode 100644 index 0000000..5090302 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/array.rs @@ -0,0 +1,55 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFRange, CFIndex, CFAllocatorRef, CFTypeID, Boolean}; +use string::CFStringRef; + +pub type CFArrayRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFArrayReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFArrayCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; +pub type CFArrayEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFArrayCallBacks { + pub version: CFIndex, + pub retain: CFArrayRetainCallBack, + pub release: CFArrayReleaseCallBack, + pub copyDescription: CFArrayCopyDescriptionCallBack, + pub equal: CFArrayEqualCallBack, +} + +#[repr(C)] +pub struct __CFArray(c_void); + +pub type CFArrayRef = *const __CFArray; + +extern { + /* + * CFArray.h + */ + pub static kCFTypeArrayCallBacks: CFArrayCallBacks; + + pub fn CFArrayCreate(allocator: CFAllocatorRef, values: *const *const c_void, + numValues: CFIndex, callBacks: *const CFArrayCallBacks) -> CFArrayRef; + pub fn CFArrayCreateCopy(allocator: CFAllocatorRef , theArray: CFArrayRef) -> CFArrayRef; + + // CFArrayBSearchValues + // CFArrayContainsValue + pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; + // CFArrayGetCountOfValue + // CFArrayGetFirstIndexOfValue + // CFArrayGetLastIndexOfValue + pub fn CFArrayGetValues(theArray: CFArrayRef, range: CFRange, values: *mut *const c_void); + pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; + // CFArrayApplyFunction + pub fn CFArrayGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/attributed_string.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/attributed_string.rs new file mode 100644 index 0000000..ecdffe6 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/attributed_string.rs @@ -0,0 +1,56 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; +use base::{CFAllocatorRef, CFTypeRef, CFIndex, CFRange, CFTypeID}; +use string::CFStringRef; +use dictionary::CFDictionaryRef; + +#[repr(C)] +pub struct __CFAttributedString(c_void); + +pub type CFAttributedStringRef = *const __CFAttributedString; +pub type CFMutableAttributedStringRef = *const __CFAttributedString; + +extern { + /* CFAttributedString */ + + pub fn CFAttributedStringCreate( + allocator: CFAllocatorRef, + str: CFStringRef, + attributes: CFDictionaryRef, + ) -> CFAttributedStringRef; + + pub fn CFAttributedStringGetLength(astr: CFAttributedStringRef) -> CFIndex; + + pub fn CFAttributedStringGetTypeID() -> CFTypeID; + + /* CFMutableAttributedString */ + + pub fn CFAttributedStringCreateMutableCopy( + allocator: CFAllocatorRef, max_length: CFIndex, astr: CFAttributedStringRef + ) -> CFMutableAttributedStringRef; + + pub fn CFAttributedStringCreateMutable( + allocator: CFAllocatorRef, + max_length: CFIndex, + ) -> CFMutableAttributedStringRef; + + pub fn CFAttributedStringReplaceString( + astr: CFMutableAttributedStringRef, range: CFRange, replacement: CFStringRef); + + pub fn CFAttributedStringSetAttribute( + astr: CFMutableAttributedStringRef, + range: CFRange, + attr_name: CFStringRef, + value: CFTypeRef, + ); + + pub fn CFMutableAttributedStringGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/base.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/base.rs new file mode 100644 index 0000000..3abed34 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/base.rs @@ -0,0 +1,154 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp::Ordering; +use std::os::raw::{c_uint, c_void, c_int}; +use string::CFStringRef; + +pub type Boolean = u8; +pub type mach_port_t = c_uint; +pub type CFAllocatorRef = *const c_void; +pub type CFNullRef = *const c_void; +pub type CFTypeRef = *const c_void; +pub type OSStatus = i32; +pub type SInt32 = c_int; +pub type CFTypeID = usize; +pub type CFOptionFlags = usize; +pub type CFHashCode = usize; +pub type CFIndex = isize; + +#[repr(isize)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum CFComparisonResult { + LessThan = -1, + EqualTo = 0, + GreaterThan = 1, +} + +impl Into for CFComparisonResult { + fn into(self) -> Ordering { + match self { + CFComparisonResult::LessThan => Ordering::Less, + CFComparisonResult::EqualTo => Ordering::Equal, + CFComparisonResult::GreaterThan => Ordering::Greater + } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFRange { + pub location: CFIndex, + pub length: CFIndex +} + +// for back-compat +impl CFRange { + pub fn init(location: CFIndex, length: CFIndex) -> CFRange { + CFRange { + location: location, + length: length, + } + } +} + +pub type CFAllocatorRetainCallBack = extern "C" fn(info: *mut c_void) -> *mut c_void; +pub type CFAllocatorReleaseCallBack = extern "C" fn(info: *mut c_void); +pub type CFAllocatorCopyDescriptionCallBack = extern "C" fn(info: *mut c_void) -> CFStringRef; +pub type CFAllocatorAllocateCallBack = extern "C" fn(allocSize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorReallocateCallBack = extern "C" fn(ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorDeallocateCallBack = extern "C" fn(ptr: *mut c_void, info: *mut c_void); +pub type CFAllocatorPreferredSizeCallBack = extern "C" fn(size: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> CFIndex; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFAllocatorContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: CFAllocatorRetainCallBack, + pub release: CFAllocatorReleaseCallBack, + pub copyDescription: CFAllocatorCopyDescriptionCallBack, + pub allocate: CFAllocatorAllocateCallBack, + pub reallocate: CFAllocatorReallocateCallBack, + pub deallocate: CFAllocatorDeallocateCallBack, + pub preferredSize: CFAllocatorPreferredSizeCallBack +} + +/// Trait for all types which are Core Foundation reference types. +pub trait TCFTypeRef { + fn as_void_ptr(&self) -> *const c_void; + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self; +} + +impl TCFTypeRef for *const T { + fn as_void_ptr(&self) -> *const c_void { + (*self) as *const c_void + } + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self { + ptr as *const T + } +} + +impl TCFTypeRef for *mut T { + fn as_void_ptr(&self) -> *const c_void { + (*self) as *const T as *const c_void + } + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self { + ptr as *const T as *mut T + } +} + +extern { + /* + * CFBase.h + */ + + /* CFAllocator Reference */ + + pub static kCFAllocatorDefault: CFAllocatorRef; + pub static kCFAllocatorSystemDefault: CFAllocatorRef; + pub static kCFAllocatorMalloc: CFAllocatorRef; + pub static kCFAllocatorMallocZone: CFAllocatorRef; + pub static kCFAllocatorNull: CFAllocatorRef; + pub static kCFAllocatorUseContext: CFAllocatorRef; + + pub fn CFAllocatorCreate(allocator: CFAllocatorRef, context: *mut CFAllocatorContext) -> CFAllocatorRef; + pub fn CFAllocatorAllocate(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorDeallocate(allocator: CFAllocatorRef, ptr: *mut c_void); + pub fn CFAllocatorGetPreferredSizeForSize(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> CFIndex; + pub fn CFAllocatorReallocate(allocator: CFAllocatorRef, ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorGetDefault() -> CFAllocatorRef; + pub fn CFAllocatorSetDefault(allocator: CFAllocatorRef); + pub fn CFAllocatorGetContext(allocator: CFAllocatorRef, context: *mut CFAllocatorContext); + pub fn CFAllocatorGetTypeID() -> CFTypeID; + + /* CFNull Reference */ + + pub static kCFNull: CFNullRef; + + /* CFType Reference */ + + //fn CFCopyTypeIDDescription + //fn CFGetAllocator + pub fn CFCopyDescription(cf: CFTypeRef) -> CFStringRef; + pub fn CFEqual(cf1: CFTypeRef, cf2: CFTypeRef) -> Boolean; + pub fn CFGetRetainCount(cf: CFTypeRef) -> CFIndex; + pub fn CFGetTypeID(cf: CFTypeRef) -> CFTypeID; + pub fn CFHash(cf: CFTypeRef) -> CFHashCode; + //fn CFMakeCollectable + pub fn CFRelease(cf: CFTypeRef); + pub fn CFRetain(cf: CFTypeRef) -> CFTypeRef; + pub fn CFShow(obj: CFTypeRef); + + /* Base Utilities Reference */ + // N.B. Some things missing here. +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/bundle.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/bundle.rs new file mode 100644 index 0000000..b4045d0 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/bundle.rs @@ -0,0 +1,37 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFTypeID, CFAllocatorRef}; +use url::CFURLRef; +use dictionary::CFDictionaryRef; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFBundle(c_void); + +pub type CFBundleRef = *mut __CFBundle; + +extern { + /* + * CFBundle.h + */ + pub fn CFBundleCreate(allocator: CFAllocatorRef, bundleURL: CFURLRef) -> CFBundleRef; + + pub fn CFBundleGetBundleWithIdentifier(bundleID: CFStringRef) -> CFBundleRef; + pub fn CFBundleGetFunctionPointerForName(bundle: CFBundleRef, function_name: CFStringRef) -> *const c_void; + pub fn CFBundleGetMainBundle() -> CFBundleRef; + pub fn CFBundleGetInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; + + pub fn CFBundleGetTypeID() -> CFTypeID; + pub fn CFBundleCopyExecutableURL(bundle: CFBundleRef) -> CFURLRef; + pub fn CFBundleCopyPrivateFrameworksURL(bundle: CFBundleRef) -> CFURLRef; + pub fn CFBundleCopySharedSupportURL(bundle: CFBundleRef) -> CFURLRef; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/characterset.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/characterset.rs new file mode 100644 index 0000000..6b347a5 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/characterset.rs @@ -0,0 +1,58 @@ +// Copyright 2019 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; +use base::{Boolean, CFAllocatorRef, CFIndex, CFRange, CFTypeID}; +use data::CFDataRef; +use string::{CFStringRef, UniChar}; + +pub type CFCharacterSetPredefinedSet = CFIndex; + +// Members of CFCharacterSetPredefinedSet enum +pub static kCFCharacterSetControl: CFCharacterSetPredefinedSet = 1; +pub static kCFCharacterSetWhitespace: CFCharacterSetPredefinedSet = 2; +pub static kCFCharacterSetWhitespaceAndNewline: CFCharacterSetPredefinedSet = 3; +pub static kCFCharacterSetDecimalDigit: CFCharacterSetPredefinedSet = 4; +pub static kCFCharacterSetLetter: CFCharacterSetPredefinedSet = 5; +pub static kCFCharacterSetLowercaseLetter: CFCharacterSetPredefinedSet = 6; +pub static kCFCharacterSetUppercaseLetter: CFCharacterSetPredefinedSet = 7; +pub static kCFCharacterSetNonBase: CFCharacterSetPredefinedSet = 8; +pub static kCFCharacterSetDecomposable: CFCharacterSetPredefinedSet = 9; +pub static kCFCharacterSetAlphaNumeric: CFCharacterSetPredefinedSet = 10; +pub static kCFCharacterSetPunctuation: CFCharacterSetPredefinedSet = 11; +pub static kCFCharacterSetIllegal: CFCharacterSetPredefinedSet = 12; +pub static kCFCharacterSetCapitalizedLetter: CFCharacterSetPredefinedSet = 13; +pub static kCFCharacterSetSymbol: CFCharacterSetPredefinedSet = 14; +pub static kCFCharacterSetNewline: CFCharacterSetPredefinedSet = 15; + +#[repr(C)] +pub struct __CFCharacterSet(c_void); + +pub type CFCharacterSetRef = *const __CFCharacterSet; +pub type CFMutableCharacterSetRef = *const __CFCharacterSet; + +extern { + pub fn CFCharacterSetGetTypeID() -> CFTypeID; + pub fn CFCharacterSetGetPredefined(theSetIdentifier: CFCharacterSetPredefinedSet) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithCharactersInRange(alloc: CFAllocatorRef, theRange: CFRange) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithCharactersInString(alloc: CFAllocatorRef, theString: CFStringRef) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateWithBitmapRepresentation(alloc: CFAllocatorRef, theData: CFDataRef) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateMutable(alloc: CFAllocatorRef) -> CFMutableCharacterSetRef; + pub fn CFCharacterSetCreateCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFCharacterSetRef; + pub fn CFCharacterSetCreateMutableCopy(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFMutableCharacterSetRef; + pub fn CFCharacterSetIsCharacterMember(theSet: CFCharacterSetRef, theChar: UniChar) -> Boolean; + pub fn CFCharacterSetCreateBitmapRepresentation(alloc: CFAllocatorRef, theSet: CFCharacterSetRef) -> CFDataRef; + pub fn CFCharacterSetAddCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); + pub fn CFCharacterSetRemoveCharactersInRange(theSet: CFMutableCharacterSetRef, theRange: CFRange); + pub fn CFCharacterSetAddCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); + pub fn CFCharacterSetRemoveCharactersInString(theSet: CFMutableCharacterSetRef, theString: CFStringRef); + pub fn CFCharacterSetUnion(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); + pub fn CFCharacterSetIntersect(theSet: CFMutableCharacterSetRef, theOtherSet: CFCharacterSetRef); + pub fn CFCharacterSetInvert(theSet: CFMutableCharacterSetRef); +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/data.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/data.rs new file mode 100644 index 0000000..7a62c9b --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/data.rs @@ -0,0 +1,32 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFTypeID, CFIndex, CFRange}; + +#[repr(C)] +pub struct __CFData(c_void); + +pub type CFDataRef = *const __CFData; + +extern { + /* + * CFData.h + */ + + pub fn CFDataCreate(allocator: CFAllocatorRef, + bytes: *const u8, length: CFIndex) -> CFDataRef; + //fn CFDataFind + pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const u8; + pub fn CFDataGetBytes(theData: CFDataRef, range: CFRange, buffer: *mut u8); + pub fn CFDataGetLength(theData: CFDataRef) -> CFIndex; + + pub fn CFDataGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/date.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/date.rs new file mode 100644 index 0000000..f83ce1d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/date.rs @@ -0,0 +1,34 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFComparisonResult, CFTypeID}; + +#[repr(C)] +pub struct __CFDate(c_void); + +pub type CFDateRef = *const __CFDate; + +pub type CFTimeInterval = f64; +pub type CFAbsoluteTime = CFTimeInterval; + +extern { + pub static kCFAbsoluteTimeIntervalSince1904: CFTimeInterval; + pub static kCFAbsoluteTimeIntervalSince1970: CFTimeInterval; + + pub fn CFAbsoluteTimeGetCurrent() -> CFAbsoluteTime; + + pub fn CFDateCreate(allocator: CFAllocatorRef, at: CFAbsoluteTime) -> CFDateRef; + pub fn CFDateGetAbsoluteTime(date: CFDateRef) -> CFAbsoluteTime; + pub fn CFDateGetTimeIntervalSinceDate(date: CFDateRef, other: CFDateRef) -> CFTimeInterval; + pub fn CFDateCompare(date: CFDateRef, other: CFDateRef, context: *mut c_void) -> CFComparisonResult; + + pub fn CFDateGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/dictionary.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/dictionary.rs new file mode 100644 index 0000000..d10e9c1 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/dictionary.rs @@ -0,0 +1,91 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFHashCode, CFIndex, CFTypeID, Boolean}; +use string::CFStringRef; + +pub type CFDictionaryApplierFunction = extern "C" fn(key: *const c_void, value: *const c_void, context: *mut c_void); + +pub type CFDictionaryRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFDictionaryReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFDictionaryCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; +pub type CFDictionaryEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFDictionaryHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFDictionaryKeyCallBacks { + pub version: CFIndex, + pub retain: CFDictionaryRetainCallBack, + pub release: CFDictionaryReleaseCallBack, + pub copyDescription: CFDictionaryCopyDescriptionCallBack, + pub equal: CFDictionaryEqualCallBack, + pub hash: CFDictionaryHashCallBack +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFDictionaryValueCallBacks { + pub version: CFIndex, + pub retain: CFDictionaryRetainCallBack, + pub release: CFDictionaryReleaseCallBack, + pub copyDescription: CFDictionaryCopyDescriptionCallBack, + pub equal: CFDictionaryEqualCallBack +} + +#[repr(C)] +pub struct __CFDictionary(c_void); + +pub type CFDictionaryRef = *const __CFDictionary; +pub type CFMutableDictionaryRef = *mut __CFDictionary; + +extern { + /* + * CFDictionary.h + */ + + pub static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; + pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; + + pub fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *const c_void) -> Boolean; + pub fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: *const *const c_void, values: *const *const c_void, + numValues: CFIndex, keyCallBacks: *const CFDictionaryKeyCallBacks, + valueCallBacks: *const CFDictionaryValueCallBacks) + -> CFDictionaryRef; + pub fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; + pub fn CFDictionaryGetTypeID() -> CFTypeID; + pub fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *const c_void, value: *mut *const c_void) + -> Boolean; + pub fn CFDictionaryApplyFunction(theDict: CFDictionaryRef, + applier: CFDictionaryApplierFunction, + context: *mut c_void); + pub fn CFDictionaryGetKeysAndValues(theDict: CFDictionaryRef, + keys: *mut *const c_void, + values: *mut *const c_void); + + pub fn CFDictionaryCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, + keyCallbacks: *const CFDictionaryKeyCallBacks, + valueCallbacks: *const CFDictionaryValueCallBacks) -> CFMutableDictionaryRef; + pub fn CFDictionaryCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, + theDict: CFDictionaryRef) -> CFMutableDictionaryRef; + pub fn CFDictionaryAddValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionarySetValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionaryReplaceValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionaryRemoveValue(theDict: CFMutableDictionaryRef, + key: *const c_void); + pub fn CFDictionaryRemoveAllValues(theDict: CFMutableDictionaryRef); +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/error.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/error.rs new file mode 100644 index 0000000..8a4c1d4 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/error.rs @@ -0,0 +1,32 @@ +// Copyright 2016 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFTypeID, CFIndex}; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFError(c_void); + +pub type CFErrorRef = *mut __CFError; + +extern "C" { + pub fn CFErrorGetTypeID() -> CFTypeID; + + pub static kCFErrorDomainPOSIX: CFStringRef; + pub static kCFErrorDomainOSStatus: CFStringRef; + pub static kCFErrorDomainMach: CFStringRef; + pub static kCFErrorDomainCocoa: CFStringRef; + + pub fn CFErrorGetDomain(err: CFErrorRef) -> CFStringRef; + pub fn CFErrorGetCode(err: CFErrorRef) -> CFIndex; + + pub fn CFErrorCopyDescription(err: CFErrorRef) -> CFStringRef; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/filedescriptor.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/filedescriptor.rs new file mode 100644 index 0000000..3f51d10 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/filedescriptor.rs @@ -0,0 +1,58 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::{c_int, c_void}; + +use base::{Boolean, CFIndex, CFTypeID, CFOptionFlags, CFAllocatorRef}; +use string::CFStringRef; +use runloop::CFRunLoopSourceRef; + +pub type CFFileDescriptorNativeDescriptor = c_int; + +#[repr(C)] +pub struct __CFFileDescriptor(c_void); + +pub type CFFileDescriptorRef = *mut __CFFileDescriptor; + +/* Callback Reason Types */ +pub const kCFFileDescriptorReadCallBack: CFOptionFlags = 1 << 0; +pub const kCFFileDescriptorWriteCallBack: CFOptionFlags = 1 << 1; + +pub type CFFileDescriptorCallBack = extern "C" fn (f: CFFileDescriptorRef, callBackTypes: CFOptionFlags, info: *mut c_void); + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFFileDescriptorContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +extern { + /* + * CFFileDescriptor.h + */ + pub fn CFFileDescriptorGetTypeID() -> CFTypeID; + + pub fn CFFileDescriptorCreate(allocator: CFAllocatorRef, fd: CFFileDescriptorNativeDescriptor, closeOnInvalidate: Boolean, callout: CFFileDescriptorCallBack, context: *const CFFileDescriptorContext) -> CFFileDescriptorRef; + + pub fn CFFileDescriptorGetNativeDescriptor(f: CFFileDescriptorRef) -> CFFileDescriptorNativeDescriptor; + + pub fn CFFileDescriptorGetContext(f: CFFileDescriptorRef, context: *mut CFFileDescriptorContext); + + pub fn CFFileDescriptorEnableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); + pub fn CFFileDescriptorDisableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); + + pub fn CFFileDescriptorInvalidate(f: CFFileDescriptorRef); + pub fn CFFileDescriptorIsValid(f: CFFileDescriptorRef) -> Boolean; + + pub fn CFFileDescriptorCreateRunLoopSource(allocator: CFAllocatorRef, f: CFFileDescriptorRef, order: CFIndex) -> CFRunLoopSourceRef; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/lib.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/lib.rs new file mode 100644 index 0000000..9b1056b --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/lib.rs @@ -0,0 +1,31 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, improper_ctypes)] + +#![cfg_attr(all(feature="mac_os_10_7_support", feature="mac_os_10_8_features"), feature(linkage))] // back-compat requires weak linkage + +pub mod array; +pub mod attributed_string; +pub mod base; +pub mod bundle; +pub mod characterset; +pub mod data; +pub mod date; +pub mod dictionary; +pub mod error; +pub mod filedescriptor; +pub mod messageport; +pub mod number; +pub mod propertylist; +pub mod runloop; +pub mod set; +pub mod string; +pub mod timezone; +pub mod url; +pub mod uuid; diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/messageport.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/messageport.rs new file mode 100644 index 0000000..e33d9aa --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/messageport.rs @@ -0,0 +1,79 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean}; +use data::CFDataRef; +use date::CFTimeInterval; +use runloop::CFRunLoopSourceRef; +use string::CFStringRef; + +#[repr(C)] +#[derive(Copy, Clone)] +#[derive(Debug)] +pub struct CFMessagePortContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +pub type CFMessagePortCallBack = Option< + unsafe extern fn(local: CFMessagePortRef, + msgid: i32, + data: CFDataRef, + info: *mut c_void) -> CFDataRef>; + +pub type CFMessagePortInvalidationCallBack = Option< + unsafe extern "C" fn(ms: CFMessagePortRef, info: *mut c_void)>; + +#[repr(C)] +pub struct __CFMessagePort(c_void); +pub type CFMessagePortRef = *mut __CFMessagePort; + +extern { + /* + * CFMessagePort.h + */ + pub fn CFMessagePortGetTypeID() -> CFTypeID; + pub fn CFMessagePortCreateLocal(allocator: CFAllocatorRef, + name: CFStringRef, + callout: CFMessagePortCallBack, + context: *const CFMessagePortContext, + shouldFreeInfo: *mut Boolean) + -> CFMessagePortRef; + pub fn CFMessagePortCreateRemote(allocator: CFAllocatorRef, + name: CFStringRef) -> CFMessagePortRef; + pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean; + pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef; + pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) + -> Boolean; + pub fn CFMessagePortGetContext(ms: CFMessagePortRef, + context: *mut CFMessagePortContext); + pub fn CFMessagePortInvalidate(ms: CFMessagePortRef); + pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean; + pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef) + -> CFMessagePortInvalidationCallBack; + pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef, + callout: CFMessagePortInvalidationCallBack); + pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32, + data: CFDataRef, + sendTimeout: CFTimeInterval, + rcvTimeout: CFTimeInterval, + replyMode: CFStringRef, + returnData: *mut CFDataRef) -> i32; + pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef, + local: CFMessagePortRef, + order: CFIndex) + -> CFRunLoopSourceRef; + // CFMessagePortSetDispatchQueue +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/number.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/number.rs new file mode 100644 index 0000000..931b95d --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/number.rs @@ -0,0 +1,60 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFTypeID, CFComparisonResult}; + +#[repr(C)] +pub struct __CFBoolean(c_void); + +pub type CFBooleanRef = *const __CFBoolean; + +pub type CFNumberType = u32; + +// members of enum CFNumberType +// static kCFNumberSInt8Type: CFNumberType = 1; +// static kCFNumberSInt16Type: CFNumberType = 2; +pub static kCFNumberSInt32Type: CFNumberType = 3; +pub static kCFNumberSInt64Type: CFNumberType = 4; +pub static kCFNumberFloat32Type: CFNumberType = 5; +pub static kCFNumberFloat64Type: CFNumberType = 6; +// static kCFNumberCharType: CFNumberType = 7; +// static kCFNumberShortType: CFNumberType = 8; +// static kCFNumberIntType: CFNumberType = 9; +// static kCFNumberLongType: CFNumberType = 10; +// static kCFNumberLongLongType: CFNumberType = 11; +// static kCFNumberFloatType: CFNumberType = 12; +// static kCFNumberDoubleType: CFNumberType = 13; +// static kCFNumberCFIndexType: CFNumberType = 14; +// static kCFNumberNSIntegerType: CFNumberType = 15; +// static kCFNumberCGFloatType: CFNumberType = 16; +// static kCFNumberMaxType: CFNumberType = 16; + +// This is an enum due to zero-sized types warnings. +// For more details see https://github.com/rust-lang/rust/issues/27303 +pub enum __CFNumber {} + +pub type CFNumberRef = *const __CFNumber; + +extern { + /* + * CFNumber.h + */ + pub static kCFBooleanTrue: CFBooleanRef; + pub static kCFBooleanFalse: CFBooleanRef; + + pub fn CFBooleanGetTypeID() -> CFTypeID; + pub fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *const c_void) + -> CFNumberRef; + //fn CFNumberGetByteSize + pub fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; + pub fn CFNumberCompare(date: CFNumberRef, other: CFNumberRef, context: *mut c_void) -> CFComparisonResult; + pub fn CFNumberGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/propertylist.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/propertylist.rs new file mode 100644 index 0000000..574c4d1 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/propertylist.rs @@ -0,0 +1,46 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeRef}; +use data::CFDataRef; +use error::CFErrorRef; + +pub type CFPropertyListRef = CFTypeRef; + +pub type CFPropertyListFormat = CFIndex; +pub const kCFPropertyListOpenStepFormat: CFPropertyListFormat = 1; +pub const kCFPropertyListXMLFormat_v1_0: CFPropertyListFormat = 100; +pub const kCFPropertyListBinaryFormat_v1_0: CFPropertyListFormat = 200; + +pub type CFPropertyListMutabilityOptions = CFOptionFlags; +pub const kCFPropertyListImmutable: CFPropertyListMutabilityOptions = 0; +pub const kCFPropertyListMutableContainers: CFPropertyListMutabilityOptions = 1; +pub const kCFPropertyListMutableContainersAndLeaves: CFPropertyListMutabilityOptions = 2; + +extern "C" { + // CFPropertyList.h + // + + // fn CFPropertyListCreateDeepCopy + // fn CFPropertyListIsValid + pub fn CFPropertyListCreateWithData(allocator: CFAllocatorRef, + data: CFDataRef, + options: CFPropertyListMutabilityOptions, + format: *mut CFPropertyListFormat, + error: *mut CFErrorRef) + -> CFPropertyListRef; + // fn CFPropertyListCreateWithStream + // fn CFPropertyListWrite + pub fn CFPropertyListCreateData(allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + format: CFPropertyListFormat, + options: CFOptionFlags, + error: *mut CFErrorRef) + -> CFDataRef; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/runloop.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/runloop.rs new file mode 100644 index 0000000..53035a2 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/runloop.rs @@ -0,0 +1,164 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use array::CFArrayRef; +use base::{Boolean, CFIndex, CFTypeID, CFAllocatorRef, CFOptionFlags, CFHashCode, mach_port_t}; +use date::{CFAbsoluteTime, CFTimeInterval}; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFRunLoop(c_void); + +pub type CFRunLoopRef = *mut __CFRunLoop; + +#[repr(C)] +pub struct __CFRunLoopSource(c_void); + +pub type CFRunLoopSourceRef = *mut __CFRunLoopSource; + +#[repr(C)] +pub struct __CFRunLoopObserver(c_void); + +pub type CFRunLoopObserverRef = *mut __CFRunLoopObserver; + +// Reasons for CFRunLoopRunInMode() to Return +pub const kCFRunLoopRunFinished: i32 = 1; +pub const kCFRunLoopRunStopped: i32 = 2; +pub const kCFRunLoopRunTimedOut: i32 = 3; +pub const kCFRunLoopRunHandledSource: i32 = 4; + +// Run Loop Observer Activities +//typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) { +pub type CFRunLoopActivity = CFOptionFlags; +pub const kCFRunLoopEntry: CFOptionFlags = 1 << 0; +pub const kCFRunLoopBeforeTimers: CFOptionFlags = 1 << 1; +pub const kCFRunLoopBeforeSources: CFOptionFlags = 1 << 2; +pub const kCFRunLoopBeforeWaiting: CFOptionFlags = 1 << 5; +pub const kCFRunLoopAfterWaiting: CFOptionFlags = 1 << 6; +pub const kCFRunLoopExit: CFOptionFlags = 1 << 7; +pub const kCFRunLoopAllActivities: CFOptionFlags = 0x0FFFFFFF; + +#[repr(C)] +pub struct CFRunLoopSourceContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, + pub schedule: Option, + pub cancel: Option, + pub perform: extern "C" fn (info: *const c_void), +} + +#[repr(C)] +pub struct CFRunLoopSourceContext1 { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, + // note that the following two fields are platform dependent in the C header, the ones here are for macOS + pub getPort: extern "C" fn (info: *mut c_void) -> mach_port_t, + pub perform: extern "C" fn (msg: *mut c_void, size: CFIndex, allocator: CFAllocatorRef, info: *mut c_void) -> *mut c_void, +} + +#[repr(C)] +pub struct CFRunLoopObserverContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +pub type CFRunLoopObserverCallBack = extern "C" fn (observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); + +#[repr(C)] +pub struct CFRunLoopTimerContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +pub type CFRunLoopTimerCallBack = extern "C" fn (timer: CFRunLoopTimerRef, info: *mut c_void); + +#[repr(C)] +pub struct __CFRunLoopTimer(c_void); + +pub type CFRunLoopTimerRef = *mut __CFRunLoopTimer; + +extern { + /* + * CFRunLoop.h + */ + pub static kCFRunLoopDefaultMode: CFStringRef; + pub static kCFRunLoopCommonModes: CFStringRef; + pub fn CFRunLoopGetTypeID() -> CFTypeID; + pub fn CFRunLoopGetCurrent() -> CFRunLoopRef; + pub fn CFRunLoopGetMain() -> CFRunLoopRef; + pub fn CFRunLoopCopyCurrentMode(rl: CFRunLoopRef) -> CFStringRef; + pub fn CFRunLoopCopyAllModes(rl: CFRunLoopRef) -> CFArrayRef; + pub fn CFRunLoopAddCommonMode(rl: CFRunLoopRef, mode: CFStringRef); + pub fn CFRunLoopGetNextTimerFireDate(rl: CFRunLoopRef, mode: CFStringRef) -> CFAbsoluteTime; + pub fn CFRunLoopRun(); + pub fn CFRunLoopRunInMode(mode: CFStringRef, seconds: CFTimeInterval, returnAfterSourceHandled: Boolean) -> i32; + pub fn CFRunLoopIsWaiting(rl: CFRunLoopRef) -> Boolean; + pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); + pub fn CFRunLoopStop(rl: CFRunLoopRef); + // fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: void (^)(void)); + pub fn CFRunLoopContainsSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); + pub fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); + pub fn CFRunLoopContainsObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); + pub fn CFRunLoopRemoveObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); + pub fn CFRunLoopContainsTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); + pub fn CFRunLoopRemoveTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); + + pub fn CFRunLoopSourceGetTypeID() -> CFTypeID; + pub fn CFRunLoopSourceCreate(allocator: CFAllocatorRef, order: CFIndex, context: *mut CFRunLoopSourceContext) -> CFRunLoopSourceRef; + pub fn CFRunLoopSourceGetOrder(source: CFRunLoopSourceRef) -> CFIndex; + pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); + pub fn CFRunLoopSourceIsValid(source: CFRunLoopSourceRef) -> Boolean; + pub fn CFRunLoopSourceGetContext(source: CFRunLoopSourceRef, context: *mut CFRunLoopSourceContext); + pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); + + pub fn CFRunLoopObserverGetTypeID() -> CFTypeID; + pub fn CFRunLoopObserverCreate(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, callout: CFRunLoopObserverCallBack, context: *mut CFRunLoopObserverContext) -> CFRunLoopObserverRef; + // fn CFRunLoopObserverCreateWithHandler(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, block: void (^) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) -> CFRunLoopObserverRef; + pub fn CFRunLoopObserverGetActivities(observer: CFRunLoopObserverRef) -> CFOptionFlags; + pub fn CFRunLoopObserverDoesRepeat(observer: CFRunLoopObserverRef) -> Boolean; + pub fn CFRunLoopObserverGetOrder(observer: CFRunLoopObserverRef) -> CFIndex; + pub fn CFRunLoopObserverInvalidate(observer: CFRunLoopObserverRef); + pub fn CFRunLoopObserverIsValid(observer: CFRunLoopObserverRef) -> Boolean; + pub fn CFRunLoopObserverGetContext(observer: CFRunLoopObserverRef, context: *mut CFRunLoopObserverContext); + + pub fn CFRunLoopTimerGetTypeID() -> CFTypeID; + pub fn CFRunLoopTimerCreate(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimerRef; + // fn CFRunLoopTimerCreateWithHandler(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, block: void (^) (CFRunLoopTimerRef timer)) -> CFRunLoopTimerRef; + pub fn CFRunLoopTimerGetNextFireDate(timer: CFRunLoopTimerRef) -> CFAbsoluteTime; + pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); + pub fn CFRunLoopTimerGetInterval(timer: CFRunLoopTimerRef) -> CFTimeInterval; + pub fn CFRunLoopTimerDoesRepeat(timer: CFRunLoopTimerRef) -> Boolean; + pub fn CFRunLoopTimerGetOrder(timer: CFRunLoopTimerRef) -> CFIndex; + pub fn CFRunLoopTimerInvalidate(timer: CFRunLoopTimerRef); + pub fn CFRunLoopTimerIsValid(timer: CFRunLoopTimerRef) -> Boolean; + pub fn CFRunLoopTimerGetContext(timer: CFRunLoopTimerRef, context: *mut CFRunLoopTimerContext); + pub fn CFRunLoopTimerGetTolerance(timer: CFRunLoopTimerRef) -> CFTimeInterval; + pub fn CFRunLoopTimerSetTolerance(timer: CFRunLoopTimerRef, tolerance: CFTimeInterval); +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/set.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/set.rs new file mode 100644 index 0000000..ec4a4bd --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/set.rs @@ -0,0 +1,58 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFIndex, CFTypeID}; + +pub type CFSetApplierFunction = extern "C" fn (value: *const c_void, + context: *const c_void); +pub type CFSetRetainCallBack = *const u8; +pub type CFSetReleaseCallBack = *const u8; +pub type CFSetCopyDescriptionCallBack = *const u8; +pub type CFSetEqualCallBack = *const u8; +pub type CFSetHashCallBack = *const u8; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFSetCallBacks { + pub version: CFIndex, + pub retain: CFSetRetainCallBack, + pub release: CFSetReleaseCallBack, + pub copyDescription: CFSetCopyDescriptionCallBack, + pub equal: CFSetEqualCallBack, + pub hash: CFSetHashCallBack, +} + +#[repr(C)] +pub struct __CFSet(c_void); + +pub type CFSetRef = *const __CFSet; + +extern { + /* + * CFSet.h + */ + + pub static kCFTypeSetCallBacks: CFSetCallBacks; + + /* Creating Sets */ + pub fn CFSetCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, + callBacks: *const CFSetCallBacks) -> CFSetRef; + + /* Applying a Function to Set Members */ + pub fn CFSetApplyFunction(theSet: CFSetRef, + applier: CFSetApplierFunction, + context: *const c_void); + + pub fn CFSetGetCount(theSet: CFSetRef) -> CFIndex; + + pub fn CFSetGetTypeID() -> CFTypeID; +} + diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/string.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/string.rs new file mode 100644 index 0000000..8b92024 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/string.rs @@ -0,0 +1,319 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::{c_char, c_ushort, c_void}; + +use base::{Boolean, CFOptionFlags, CFIndex, CFAllocatorRef, CFRange, CFTypeID}; + +pub type UniChar = c_ushort; + +// CFString.h + +pub type CFStringCompareFlags = CFOptionFlags; +//static kCFCompareCaseInsensitive: CFStringCompareFlags = 1; +//static kCFCompareBackwards: CFStringCompareFlags = 4; +//static kCFCompareAnchored: CFStringCompareFlags = 8; +//static kCFCompareNonliteral: CFStringCompareFlags = 16; +//static kCFCompareLocalized: CFStringCompareFlags = 32; +//static kCFCompareNumerically: CFStringCompareFlags = 64; +//static kCFCompareDiacriticInsensitive: CFStringCompareFlags = 128; +//static kCFCompareWidthInsensitive: CFStringCompareFlags = 256; +//static kCFCompareForcedOrdering: CFStringCompareFlags = 512; + +pub type CFStringEncoding = u32; + +// macOS built-in encodings. + +//static kCFStringEncodingMacRoman: CFStringEncoding = 0; +//static kCFStringEncodingWindowsLatin1: CFStringEncoding = 0x0500; +//static kCFStringEncodingISOLatin1: CFStringEncoding = 0x0201; +//static kCFStringEncodingNextStepLatin: CFStringEncoding = 0x0B01; +//static kCFStringEncodingASCII: CFStringEncoding = 0x0600; +//static kCFStringEncodingUnicode: CFStringEncoding = 0x0100; +pub static kCFStringEncodingUTF8: CFStringEncoding = 0x08000100; +//static kCFStringEncodingNonLossyASCII: CFStringEncoding = 0x0BFF; + +//static kCFStringEncodingUTF16: CFStringEncoding = 0x0100; +//static kCFStringEncodingUTF16BE: CFStringEncoding = 0x10000100; +//static kCFStringEncodingUTF16LE: CFStringEncoding = 0x14000100; +//static kCFStringEncodingUTF32: CFStringEncoding = 0x0c000100; +//static kCFStringEncodingUTF32BE: CFStringEncoding = 0x18000100; +//static kCFStringEncodingUTF32LE: CFStringEncoding = 0x1c000100; + + +// CFStringEncodingExt.h + +pub type CFStringEncodings = CFIndex; + +// External encodings, except those defined above. +// Defined above: kCFStringEncodingMacRoman = 0 +//static kCFStringEncodingMacJapanese: CFStringEncoding = 1; +//static kCFStringEncodingMacChineseTrad: CFStringEncoding = 2; +//static kCFStringEncodingMacKorean: CFStringEncoding = 3; +//static kCFStringEncodingMacArabic: CFStringEncoding = 4; +//static kCFStringEncodingMacHebrew: CFStringEncoding = 5; +//static kCFStringEncodingMacGreek: CFStringEncoding = 6; +//static kCFStringEncodingMacCyrillic: CFStringEncoding = 7; +//static kCFStringEncodingMacDevanagari: CFStringEncoding = 9; +//static kCFStringEncodingMacGurmukhi: CFStringEncoding = 10; +//static kCFStringEncodingMacGujarati: CFStringEncoding = 11; +//static kCFStringEncodingMacOriya: CFStringEncoding = 12; +//static kCFStringEncodingMacBengali: CFStringEncoding = 13; +//static kCFStringEncodingMacTamil: CFStringEncoding = 14; +//static kCFStringEncodingMacTelugu: CFStringEncoding = 15; +//static kCFStringEncodingMacKannada: CFStringEncoding = 16; +//static kCFStringEncodingMacMalayalam: CFStringEncoding = 17; +//static kCFStringEncodingMacSinhalese: CFStringEncoding = 18; +//static kCFStringEncodingMacBurmese: CFStringEncoding = 19; +//static kCFStringEncodingMacKhmer: CFStringEncoding = 20; +//static kCFStringEncodingMacThai: CFStringEncoding = 21; +//static kCFStringEncodingMacLaotian: CFStringEncoding = 22; +//static kCFStringEncodingMacGeorgian: CFStringEncoding = 23; +//static kCFStringEncodingMacArmenian: CFStringEncoding = 24; +//static kCFStringEncodingMacChineseSimp: CFStringEncoding = 25; +//static kCFStringEncodingMacTibetan: CFStringEncoding = 26; +//static kCFStringEncodingMacMongolian: CFStringEncoding = 27; +//static kCFStringEncodingMacEthiopic: CFStringEncoding = 28; +//static kCFStringEncodingMacCentralEurRoman: CFStringEncoding = 29; +//static kCFStringEncodingMacVietnamese: CFStringEncoding = 30; +//static kCFStringEncodingMacExtArabic: CFStringEncoding = 31; +//static kCFStringEncodingMacSymbol: CFStringEncoding = 33; +//static kCFStringEncodingMacDingbats: CFStringEncoding = 34; +//static kCFStringEncodingMacTurkish: CFStringEncoding = 35; +//static kCFStringEncodingMacCroatian: CFStringEncoding = 36; +//static kCFStringEncodingMacIcelandic: CFStringEncoding = 37; +//static kCFStringEncodingMacRomanian: CFStringEncoding = 38; +//static kCFStringEncodingMacCeltic: CFStringEncoding = 39; +//static kCFStringEncodingMacGaelic: CFStringEncoding = 40; +//static kCFStringEncodingMacFarsi: CFStringEncoding = 0x8C; +//static kCFStringEncodingMacUkrainian: CFStringEncoding = 0x98; +//static kCFStringEncodingMacInuit: CFStringEncoding = 0xEC; +//static kCFStringEncodingMacVT100: CFStringEncoding = 0xFC; +//static kCFStringEncodingMacHFS: CFStringEncoding = 0xFF; +// Defined above: kCFStringEncodingISOLatin1 = 0x0201 +//static kCFStringEncodingISOLatin2: CFStringEncoding = 0x0202; +//static kCFStringEncodingISOLatin3: CFStringEncoding = 0x0203; +//static kCFStringEncodingISOLatin4: CFStringEncoding = 0x0204; +//static kCFStringEncodingISOLatinCyrillic: CFStringEncoding = 0x0205; +//static kCFStringEncodingISOLatinArabic: CFStringEncoding = 0x0206; +//static kCFStringEncodingISOLatinGreek: CFStringEncoding = 0x0207; +//static kCFStringEncodingISOLatinHebrew: CFStringEncoding = 0x0208; +//static kCFStringEncodingISOLatin5: CFStringEncoding = 0x0209; +//static kCFStringEncodingISOLatin6: CFStringEncoding = 0x020A; +//static kCFStringEncodingISOLatinThai: CFStringEncoding = 0x020B; +//static kCFStringEncodingISOLatin7: CFStringEncoding = 0x020D; +//static kCFStringEncodingISOLatin8: CFStringEncoding = 0x020E; +//static kCFStringEncodingISOLatin9: CFStringEncoding = 0x020F; +//static kCFStringEncodingISOLatin10: CFStringEncoding = 0x0210; +//static kCFStringEncodingDOSLatinUS: CFStringEncoding = 0x0400; +//static kCFStringEncodingDOSGreek: CFStringEncoding = 0x0405; +//static kCFStringEncodingDOSBalticRim: CFStringEncoding = 0x0406; +//static kCFStringEncodingDOSLatin1: CFStringEncoding = 0x0410; +//static kCFStringEncodingDOSGreek1: CFStringEncoding = 0x0411; +//static kCFStringEncodingDOSLatin2: CFStringEncoding = 0x0412; +//static kCFStringEncodingDOSCyrillic: CFStringEncoding = 0x0413; +//static kCFStringEncodingDOSTurkish: CFStringEncoding = 0x0414; +//static kCFStringEncodingDOSPortuguese: CFStringEncoding = 0x0415; +//static kCFStringEncodingDOSIcelandic: CFStringEncoding = 0x0416; +//static kCFStringEncodingDOSHebrew: CFStringEncoding = 0x0417; +//static kCFStringEncodingDOSCanadianFrench: CFStringEncoding = 0x0418; +//static kCFStringEncodingDOSArabic: CFStringEncoding = 0x0419; +//static kCFStringEncodingDOSNordic: CFStringEncoding = 0x041A; +//static kCFStringEncodingDOSRussian: CFStringEncoding = 0x041B; +//static kCFStringEncodingDOSGreek2: CFStringEncoding = 0x041C; +//static kCFStringEncodingDOSThai: CFStringEncoding = 0x041D; +//static kCFStringEncodingDOSJapanese: CFStringEncoding = 0x0420; +//static kCFStringEncodingDOSChineseSimplif: CFStringEncoding = 0x0421; +//static kCFStringEncodingDOSKorean: CFStringEncoding = 0x0422; +//static kCFStringEncodingDOSChineseTrad: CFStringEncoding = 0x0423; +// Defined above: kCFStringEncodingWindowsLatin1 = 0x0500 +//static kCFStringEncodingWindowsLatin2: CFStringEncoding = 0x0501; +//static kCFStringEncodingWindowsCyrillic: CFStringEncoding = 0x0502; +//static kCFStringEncodingWindowsGreek: CFStringEncoding = 0x0503; +//static kCFStringEncodingWindowsLatin5: CFStringEncoding = 0x0504; +//static kCFStringEncodingWindowsHebrew: CFStringEncoding = 0x0505; +//static kCFStringEncodingWindowsArabic: CFStringEncoding = 0x0506; +//static kCFStringEncodingWindowsBalticRim: CFStringEncoding = 0x0507; +//static kCFStringEncodingWindowsVietnamese: CFStringEncoding = 0x0508; +//static kCFStringEncodingWindowsKoreanJohab: CFStringEncoding = 0x0510; +// Defined above: kCFStringEncodingASCII = 0x0600 +//static kCFStringEncodingANSEL: CFStringEncoding = 0x0601; +//static kCFStringEncodingJIS_X0201_76: CFStringEncoding = 0x0620; +//static kCFStringEncodingJIS_X0208_83: CFStringEncoding = 0x0621; +//static kCFStringEncodingJIS_X0208_90: CFStringEncoding = 0x0622; +//static kCFStringEncodingJIS_X0212_90: CFStringEncoding = 0x0623; +//static kCFStringEncodingJIS_C6226_78: CFStringEncoding = 0x0624; +//static kCFStringEncodingShiftJIS_X0213: CFStringEncoding = 0x0628; +//static kCFStringEncodingShiftJIS_X0213_MenKuTen: CFStringEncoding = 0x0629; +//static kCFStringEncodingGB_2312_80: CFStringEncoding = 0x0630; +//static kCFStringEncodingGBK_95: CFStringEncoding = 0x0631; +//static kCFStringEncodingGB_18030_2000: CFStringEncoding = 0x0632; +//static kCFStringEncodingKSC_5601_87: CFStringEncoding = 0x0640; +//static kCFStringEncodingKSC_5601_92_Johab: CFStringEncoding = 0x0641; +//static kCFStringEncodingCNS_11643_92_P1: CFStringEncoding = 0x0651; +//static kCFStringEncodingCNS_11643_92_P2: CFStringEncoding = 0x0652; +//static kCFStringEncodingCNS_11643_92_P3: CFStringEncoding = 0x0653; +//static kCFStringEncodingISO_2022_JP: CFStringEncoding = 0x0820; +//static kCFStringEncodingISO_2022_JP_2: CFStringEncoding = 0x0821; +//static kCFStringEncodingISO_2022_JP_1: CFStringEncoding = 0x0822; +//static kCFStringEncodingISO_2022_JP_3: CFStringEncoding = 0x0823; +//static kCFStringEncodingISO_2022_CN: CFStringEncoding = 0x0830; +//static kCFStringEncodingISO_2022_CN_EXT: CFStringEncoding = 0x0831; +//static kCFStringEncodingISO_2022_KR: CFStringEncoding = 0x0840; +//static kCFStringEncodingEUC_JP: CFStringEncoding = 0x0920; +//static kCFStringEncodingEUC_CN: CFStringEncoding = 0x0930; +//static kCFStringEncodingEUC_TW: CFStringEncoding = 0x0931; +//static kCFStringEncodingEUC_KR: CFStringEncoding = 0x0940; +//static kCFStringEncodingShiftJIS: CFStringEncoding = 0x0A01; +//static kCFStringEncodingKOI8_R: CFStringEncoding = 0x0A02; +//static kCFStringEncodingBig5: CFStringEncoding = 0x0A03; +//static kCFStringEncodingMacRomanLatin1: CFStringEncoding = 0x0A04; +//static kCFStringEncodingHZ_GB_2312: CFStringEncoding = 0x0A05; +//static kCFStringEncodingBig5_HKSCS_1999: CFStringEncoding = 0x0A06; +//static kCFStringEncodingVISCII: CFStringEncoding = 0x0A07; +//static kCFStringEncodingKOI8_U: CFStringEncoding = 0x0A08; +//static kCFStringEncodingBig5_E: CFStringEncoding = 0x0A09; +// Defined above: kCFStringEncodingNextStepLatin = 0x0B01 +//static kCFStringEncodingNextStepJapanese: CFStringEncoding = 0x0B02; +//static kCFStringEncodingEBCDIC_US: CFStringEncoding = 0x0C01; +//static kCFStringEncodingEBCDIC_CP037: CFStringEncoding = 0x0C02; +//static kCFStringEncodingUTF7: CFStringEncoding = 0x04000100; +//static kCFStringEncodingUTF7_IMAP: CFStringEncoding = 0x0A10; +//static kCFStringEncodingShiftJIS_X0213_00: CFStringEncoding = 0x0628; /* Deprecated */ + +#[repr(C)] +pub struct __CFString(c_void); + +pub type CFStringRef = *const __CFString; + +extern { + /* + * CFString.h + */ + + // N.B. organized according to "Functions by task" in docs + + /* Creating a CFString */ + //fn CFSTR + //fn CFStringCreateArrayBySeparatingStrings + //fn CFStringCreateByCombiningStrings + //fn CFStringCreateCopy + //fn CFStringCreateFromExternalRepresentation + pub fn CFStringCreateWithBytes(alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean) + -> CFStringRef; + pub fn CFStringCreateWithBytesNoCopy(alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + contentsDeallocator: CFAllocatorRef) + -> CFStringRef; + //fn CFStringCreateWithCharacters + //fn CFStringCreateWithCharactersNoCopy + pub fn CFStringCreateWithCString(alloc: CFAllocatorRef, + cStr: *const c_char, + encoding: CFStringEncoding) + -> CFStringRef; + //fn CFStringCreateWithCStringNoCopy + //fn CFStringCreateWithFormat + //fn CFStringCreateWithFormatAndArguments + //fn CFStringCreateWithPascalString + //fn CFStringCreateWithPascalStringNoCopy + //fn CFStringCreateWithSubstring + + /* Searching Strings */ + //fn CFStringCreateArrayWithFindResults + //fn CFStringFind + //fn CFStringFindCharacterFromSet + //fn CFStringFindWithOptions + //fn CFStringFindWithOptionsAndLocale + //fn CFStringGetLineBounds + + /* Comparing Strings */ + //fn CFStringCompare + //fn CFStringCompareWithOptions + //fn CFStringCompareWithOptionsAndLocale + //fn CFStringHasPrefix + //fn CFStringHasSuffix + + /* Accessing Characters */ + //fn CFStringCreateExternalRepresentation + pub fn CFStringGetBytes(theString: CFStringRef, + range: CFRange, + encoding: CFStringEncoding, + lossByte: u8, + isExternalRepresentation: Boolean, + buffer: *mut u8, + maxBufLen: CFIndex, + usedBufLen: *mut CFIndex) + -> CFIndex; + //fn CFStringGetCharacterAtIndex + //fn CFStringGetCharacters + //fn CFStringGetCharactersPtr + //fn CFStringGetCharacterFromInlineBuffer + pub fn CFStringGetCString(theString: CFStringRef, + buffer: *mut c_char, + bufferSize: CFIndex, + encoding: CFStringEncoding) + -> Boolean; + pub fn CFStringGetCStringPtr(theString: CFStringRef, + encoding: CFStringEncoding) + -> *const c_char; + pub fn CFStringGetLength(theString: CFStringRef) -> CFIndex; + //fn CFStringGetPascalString + //fn CFStringGetPascalStringPtr + //fn CFStringGetRangeOfComposedCharactersAtIndex + //fn CFStringInitInlineBuffer + + /* Working With Hyphenation */ + //fn CFStringGetHyphenationLocationBeforeIndex + //fn CFStringIsHyphenationAvailableForLocale + + /* Working With Encodings */ + //fn CFStringConvertEncodingToIANACharSetName + //fn CFStringConvertEncodingToNSStringEncoding + //fn CFStringConvertEncodingToWindowsCodepage + //fn CFStringConvertIANACharSetNameToEncoding + //fn CFStringConvertNSStringEncodingToEncoding + //fn CFStringConvertWindowsCodepageToEncoding + //fn CFStringGetFastestEncoding + //fn CFStringGetListOfAvailableEncodings + //fn CFStringGetMaximumSizeForEncoding + //fn CFStringGetMostCompatibleMacStringEncoding + //fn CFStringGetNameOfEncoding + //fn CFStringGetSmallestEncoding + //fn CFStringGetSystemEncoding + //fn CFStringIsEncodingAvailable + + /* Getting Numeric Values */ + //fn CFStringGetDoubleValue + //fn CFStringGetIntValue + + /* Getting String Properties */ + //fn CFShowStr + pub fn CFStringGetTypeID() -> CFTypeID; + + /* String File System Representations */ + //fn CFStringCreateWithFileSystemRepresentation + //fn CFStringGetFileSystemRepresentation + //fn CFStringGetMaximumSizeOfFileSystemRepresentation + + /* Getting Paragraph Bounds */ + //fn CFStringGetParagraphBounds + + /* Managing Surrogates */ + //fn CFStringGetLongCharacterForSurrogatePair + //fn CFStringGetSurrogatePairForLongCharacter + //fn CFStringIsSurrogateHighCharacter + //fn CFStringIsSurrogateLowCharacter +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/timezone.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/timezone.rs new file mode 100644 index 0000000..376cfdc --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/timezone.rs @@ -0,0 +1,27 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFTypeID}; +use date::{CFTimeInterval, CFAbsoluteTime}; + +#[repr(C)] +pub struct __CFTimeZone(c_void); + +pub type CFTimeZoneRef = *const __CFTimeZone; + +extern { + pub fn CFTimeZoneCopySystem() -> CFTimeZoneRef; + pub fn CFTimeZoneCopyDefault() -> CFTimeZoneRef; + pub fn CFTimeZoneCreateWithTimeIntervalFromGMT(allocator: CFAllocatorRef, interval: CFTimeInterval) -> CFTimeZoneRef; + pub fn CFTimeZoneGetSecondsFromGMT(tz: CFTimeZoneRef, time: CFAbsoluteTime) -> CFTimeInterval; + + pub fn CFTimeZoneGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/url.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/url.rs new file mode 100644 index 0000000..08e7bcd --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/url.rs @@ -0,0 +1,169 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFOptionFlags, CFIndex, CFAllocatorRef, Boolean, CFTypeID, CFTypeRef, SInt32}; +use data::CFDataRef; +use array::CFArrayRef; +use dictionary::CFDictionaryRef; +use string::{CFStringRef, CFStringEncoding}; +use error::CFErrorRef; + +#[repr(C)] +pub struct __CFURL(c_void); + +pub type CFURLRef = *const __CFURL; + +pub type CFURLBookmarkCreationOptions = CFOptionFlags; +pub type CFURLBookmarkResolutionOptions = CFOptionFlags; +pub type CFURLBookmarkFileCreationOptions = CFOptionFlags; + +pub type CFURLPathStyle = CFIndex; + +/* typedef CF_ENUM(CFIndex, CFURLPathStyle) */ +pub const kCFURLPOSIXPathStyle: CFURLPathStyle = 0; +pub const kCFURLHFSPathStyle: CFURLPathStyle = 1; +pub const kCFURLWindowsPathStyle: CFURLPathStyle = 2; + +pub static kCFURLBookmarkCreationPreferFileIDResolutionMask: CFURLBookmarkCreationOptions = + (1u32 << 8) as usize; +pub static kCFURLBookmarkCreationMinimalBookmarkMask: CFURLBookmarkCreationOptions = + (1u32 << 9) as usize; +pub static kCFURLBookmarkCreationSuitableForBookmarkFile: CFURLBookmarkCreationOptions = + (1u32 << 10) as usize; +pub static kCFURLBookmarkCreationWithSecurityScope: CFURLBookmarkCreationOptions = + (1u32 << 11) as usize; +pub static kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess: CFURLBookmarkCreationOptions = + (1u32 << 12) as usize; + +// TODO: there are a lot of missing keys and constants. Add if you are bored or need them. + +extern { + /* + * CFURL.h + */ + + /* Common File System Resource Keys */ + pub static kCFURLAttributeModificationDateKey: CFStringRef; + pub static kCFURLContentAccessDateKey: CFStringRef; + pub static kCFURLContentModificationDateKey: CFStringRef; + pub static kCFURLCreationDateKey: CFStringRef; + pub static kCFURLFileResourceIdentifierKey: CFStringRef; + pub static kCFURLFileSecurityKey: CFStringRef; + pub static kCFURLHasHiddenExtensionKey: CFStringRef; + pub static kCFURLIsDirectoryKey: CFStringRef; + pub static kCFURLIsExecutableKey: CFStringRef; + pub static kCFURLIsHiddenKey: CFStringRef; + pub static kCFURLIsPackageKey: CFStringRef; + pub static kCFURLIsReadableKey: CFStringRef; + pub static kCFURLIsRegularFileKey: CFStringRef; + pub static kCFURLIsSymbolicLinkKey: CFStringRef; + pub static kCFURLIsSystemImmutableKey: CFStringRef; + pub static kCFURLIsUserImmutableKey: CFStringRef; + pub static kCFURLIsVolumeKey: CFStringRef; + pub static kCFURLIsWritableKey: CFStringRef; + pub static kCFURLLabelNumberKey: CFStringRef; + pub static kCFURLLinkCountKey: CFStringRef; + pub static kCFURLLocalizedLabelKey: CFStringRef; + pub static kCFURLLocalizedNameKey: CFStringRef; + pub static kCFURLLocalizedTypeDescriptionKey: CFStringRef; + pub static kCFURLNameKey: CFStringRef; + pub static kCFURLParentDirectoryURLKey: CFStringRef; + pub static kCFURLPreferredIOBlockSizeKey: CFStringRef; + pub static kCFURLTypeIdentifierKey: CFStringRef; + pub static kCFURLVolumeIdentifierKey: CFStringRef; + pub static kCFURLVolumeURLKey: CFStringRef; + + #[cfg(feature="mac_os_10_8_features")] + #[cfg_attr(feature = "mac_os_10_7_support", linkage = "extern_weak")] + pub static kCFURLIsExcludedFromBackupKey: CFStringRef; + pub static kCFURLFileResourceTypeKey: CFStringRef; + + /* Creating a CFURL */ + pub fn CFURLCopyAbsoluteURL(anURL: CFURLRef) -> CFURLRef; + pub fn CFURLCreateAbsoluteURLWithBytes(allocator: CFAllocatorRef, relativeURLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef, useCompatibilityMode: Boolean) -> CFURLRef; + pub fn CFURLCreateByResolvingBookmarkData(allocator: CFAllocatorRef, bookmark: CFDataRef, options: CFURLBookmarkResolutionOptions, relativeToURL: CFURLRef, resourcePropertiesToInclude: CFArrayRef, isStale: *mut Boolean, error: *mut CFErrorRef) -> CFURLRef; + //fn CFURLCreateCopyAppendingPathComponent + //fn CFURLCreateCopyAppendingPathExtension + //fn CFURLCreateCopyDeletingLastPathComponent + //fn CFURLCreateCopyDeletingPathExtension + pub fn CFURLCreateFilePathURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; + //fn CFURLCreateFileReferenceURL + pub fn CFURLCreateFromFileSystemRepresentation(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean) -> CFURLRef; + //fn CFURLCreateFromFileSystemRepresentationRelativeToBase + //fn CFURLCreateFromFSRef + pub fn CFURLCreateWithBytes(allocator: CFAllocatorRef, URLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPath(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPathRelativeToBase(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean, baseURL: CFURLRef) -> CFURLRef; + //fn CFURLCreateWithString(allocator: CFAllocatorRef, urlString: CFStringRef, + // baseURL: CFURLRef) -> CFURLRef; + + /* Accessing the Parts of a URL */ + pub fn CFURLCanBeDecomposed(anURL: CFURLRef) -> Boolean; + pub fn CFURLCopyFileSystemPath(anURL: CFURLRef, pathStyle: CFURLPathStyle) -> CFStringRef; + pub fn CFURLCopyFragment(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyHostName(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyLastPathComponent(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyNetLocation(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyParameterString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyPassword(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyPath(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyPathExtension(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyQueryString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyResourceSpecifier(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyScheme(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyStrictPath(anURL: CFURLRef, isAbsolute: *mut Boolean) -> CFStringRef; + pub fn CFURLCopyUserName(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLGetPortNumber(anURL: CFURLRef) -> SInt32; + pub fn CFURLHasDirectoryPath(anURL: CFURLRef) -> Boolean; + + /* Converting URLs to Other Representations */ + //fn CFURLCreateData(allocator: CFAllocatorRef, url: CFURLRef, + // encoding: CFStringEncoding, escapeWhitespace: bool) -> CFDataRef; + //fn CFURLCreateStringByAddingPercentEscapes + //fn CFURLCreateStringByReplacingPercentEscapes + //fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding + pub fn CFURLGetFileSystemRepresentation(anURL: CFURLRef, resolveAgainstBase: Boolean, buffer: *mut u8, maxBufLen: CFIndex) -> Boolean; + + //fn CFURLGetFSRef + pub fn CFURLGetString(anURL: CFURLRef) -> CFStringRef; + + /* Getting URL Properties */ + //fn CFURLGetBaseURL(anURL: CFURLRef) -> CFURLRef; + pub fn CFURLGetBytes(anURL: CFURLRef, buffer: *mut u8, bufferLength: CFIndex) -> CFIndex; + //fn CFURLGetByteRangeForComponent + pub fn CFURLGetTypeID() -> CFTypeID; + //fn CFURLResourceIsReachable + + /* Getting and Setting File System Resource Properties */ + pub fn CFURLClearResourcePropertyCache(url: CFURLRef); + //fn CFURLClearResourcePropertyCacheForKey + //fn CFURLCopyResourcePropertiesForKeys + //fn CFURLCopyResourcePropertyForKey + pub fn CFURLCreateResourcePropertiesForKeysFromBookmarkData(allocator: CFAllocatorRef, resourcePropertiesToReturn: CFArrayRef, bookmark: CFDataRef) -> CFDictionaryRef; + pub fn CFURLCreateResourcePropertyForKeyFromBookmarkData(allocator: CFAllocatorRef, resourcePropertyKey: CFStringRef, bookmark: CFDataRef) -> CFTypeRef; + //fn CFURLSetResourcePropertiesForKeys + pub fn CFURLSetResourcePropertyForKey(url: CFURLRef, key: CFStringRef, value: CFTypeRef, error: *mut CFErrorRef) -> Boolean; + //fn CFURLSetTemporaryResourcePropertyForKey + + /* Working with Bookmark Data */ + pub fn CFURLCreateBookmarkData(allocator: CFAllocatorRef, url: CFURLRef, options: CFURLBookmarkCreationOptions, resourcePropertiesToInclude: CFArrayRef, relativeToURL: CFURLRef, error: *mut CFErrorRef) -> CFDataRef; + pub fn CFURLCreateBookmarkDataFromAliasRecord(allocator: CFAllocatorRef, aliasRecordDataRef: CFDataRef) -> CFDataRef; + pub fn CFURLCreateBookmarkDataFromFile(allocator: CFAllocatorRef, fileURL: CFURLRef, errorRef: *mut CFErrorRef) -> CFDataRef; + pub fn CFURLWriteBookmarkDataToFile(bookmarkRef: CFDataRef, fileURL: CFURLRef, options: CFURLBookmarkFileCreationOptions, errorRef: *mut CFErrorRef) -> Boolean; + pub fn CFURLStartAccessingSecurityScopedResource(url: CFURLRef) -> Boolean; + pub fn CFURLStopAccessingSecurityScopedResource(url: CFURLRef); +} + +#[test] +#[cfg(feature="mac_os_10_8_features")] +fn can_see_excluded_from_backup_key() { + let _ = unsafe { kCFURLIsExcludedFromBackupKey }; +} diff --git a/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/uuid.rs b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/uuid.rs new file mode 100644 index 0000000..4253952 --- /dev/null +++ b/third_party/cargo/vendor/core-foundation-sys-0.7.0/src/uuid.rs @@ -0,0 +1,49 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +use base::{CFAllocatorRef, CFTypeID}; + +#[repr(C)] +pub struct __CFUUID(c_void); + +pub type CFUUIDRef = *const __CFUUID; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct CFUUIDBytes { + pub byte0: u8, + pub byte1: u8, + pub byte2: u8, + pub byte3: u8, + pub byte4: u8, + pub byte5: u8, + pub byte6: u8, + pub byte7: u8, + pub byte8: u8, + pub byte9: u8, + pub byte10: u8, + pub byte11: u8, + pub byte12: u8, + pub byte13: u8, + pub byte14: u8, + pub byte15: u8 +} + +extern { + /* + * CFUUID.h + */ + pub fn CFUUIDCreate(allocator: CFAllocatorRef) -> CFUUIDRef; + pub fn CFUUIDCreateFromUUIDBytes(allocator: CFAllocatorRef, bytes: CFUUIDBytes) -> CFUUIDRef; + pub fn CFUUIDGetUUIDBytes(uuid: CFUUIDRef) -> CFUUIDBytes; + + pub fn CFUUIDGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/.cargo-checksum.json b/third_party/cargo/vendor/core-graphics-0.19.0/.cargo-checksum.json new file mode 100644 index 0000000..deede98 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"fccf58052cf6a36aba8ce4936d5e62d953f73a1fbedbe89b6d099bcd3848a5a5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"6745c3c38183d2eda9b1fa265fb0a95018db5c110cbabc00b32327d951bbe2ea","src/base.rs":"89e01071e66f0c66fa22d94fd666100c89f6a20d988fb8bacbf86b8ed633bcbd","src/color.rs":"4c8ec4ab828cbc1b2a1538a34a51f5b380927f2f1daf187dff6f732f57a43656","src/color_space.rs":"b3d7ee8a21703c789160867cb8eb2188bd1daa193e3d030f21adb6f1a6f872de","src/context.rs":"b4b05d7c75337e8f8ece3143d1f1a48b3ae6868c473469c2ce7fd030512f9aff","src/data_provider.rs":"9e8a17075b1527f87111fd4102252e086bf9fde147483f21a661773e133f7c71","src/display.rs":"cc691712c3d27342ae97f04df6032d6f682570239ba51936fcc796c61bf08c8b","src/event.rs":"593d7f6c0621f8803546562548f98985f171eb74b513d6f9b9081fe6f2d1a1a8","src/event_source.rs":"d55a4f5b5e62789325028febc51bbf54c74b15ab1a4e70c6ad749a2f9753e081","src/font.rs":"e1d2be7f909fd5876f3cd1649d54ef0a9d7dcd4151c027a25049be7084ca8a9f","src/geometry.rs":"49d27dde6672e5654f796ec3399216ab6d1cf9ed9d3506a824c8e9eec6e3db00","src/image.rs":"0af720ee020fb1c6a2f4b1ce49e3d27f8f21f0be6b81ba4b9c824f87564efa58","src/lib.rs":"9b9601462de1bbc806e881b2b42e86b16372cad8eeefe1a96b772a9f7329958d","src/path.rs":"c429afeaed999b02ac00f89a867b5fc64f1e223039079a4e0529306b734ff117","src/private.rs":"da3fd61338bab2d8e26aa5433b2e18ecd2a0a408c62e1ac2b33a0f87f2dad88a","src/sys.rs":"cc90b690f172da51a87ffb234f6e74a9f501c4f1630d7b51fa2d5846e80fc164","src/window.rs":"2f6c3dc958ae2c0c9e2fc5033300b96e60ed0abee9823ea1f03797d64df0911a"},"package":"59e78b2e0aaf43f08e7ae0d6bc96895ef72ff0921c7d4ff4762201b2dba376dd"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/BUILD b/third_party/cargo/vendor/core-graphics-0.19.0/BUILD similarity index 70% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/BUILD rename to third_party/cargo/vendor/core-graphics-0.19.0/BUILD index 9f26bee..1d99e8b 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/BUILD +++ b/third_party/cargo/vendor/core-graphics-0.19.0/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "Apache-2.0,MIT" + "notice", # "MIT,Apache-2.0" ]) load( @@ -23,24 +23,25 @@ load( ) -# Unsupported target "build-script-build" with type "custom-build" omitted rust_library( - name = "parking_lot_core", + name = "core_graphics", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", srcs = glob(["**/*.rs"]), deps = [ + "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", + "//third_party/cargo/vendor/core-foundation-0.7.0:core_foundation", + "//third_party/cargo/vendor/foreign-types-0.3.2:foreign_types", "//third_party/cargo/vendor/libc-0.2.67:libc", - "//third_party/cargo/vendor/rand-0.6.5:rand", - "//third_party/cargo/vendor/smallvec-0.6.13:smallvec", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.4.0", + version = "0.19.0", crate_features = [ + "default", ], ) diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/COPYRIGHT b/third_party/cargo/vendor/core-graphics-0.19.0/COPYRIGHT new file mode 100644 index 0000000..8b7291a --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/COPYRIGHT @@ -0,0 +1,5 @@ +Licensed under the Apache License, Version 2.0 or the MIT license +, at your +option. All files in the project carrying such notice may not be +copied, modified, or distributed except according to those terms. diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/Cargo.toml b/third_party/cargo/vendor/core-graphics-0.19.0/Cargo.toml new file mode 100644 index 0000000..ccffdb8 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/Cargo.toml @@ -0,0 +1,36 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "core-graphics" +version = "0.19.0" +authors = ["The Servo Project Developers"] +description = "Bindings to Core Graphics for macOS" +homepage = "https://github.com/servo/core-graphics-rs" +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" +[dependencies.bitflags] +version = "1.0" + +[dependencies.core-foundation] +version = "0.7" + +[dependencies.foreign-types] +version = "0.3.0" + +[dependencies.libc] +version = "0.2" + +[features] +default = [] +elcapitan = [] +highsierra = [] diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/LICENSE-APACHE b/third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-0.5.0/LICENSE-APACHE rename to third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-MIT b/third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-MIT new file mode 100644 index 0000000..807526f --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2012-2013 Mozilla Foundation + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/README.md b/third_party/cargo/vendor/core-graphics-0.19.0/README.md new file mode 100644 index 0000000..2217568 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/README.md @@ -0,0 +1,3 @@ +# core-graphics-rs + +[![Build Status](https://travis-ci.com/servo/core-graphics-rs.svg?branch=master)](https://travis-ci.com/servo/core-graphics-rs) diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/base.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/base.rs new file mode 100644 index 0000000..89ca6b0 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/base.rs @@ -0,0 +1,59 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// this file defines CGFloat, as well as stubbed data types. + +#![allow(non_camel_case_types)] +#![allow(non_upper_case_globals)] + +use libc; + +#[cfg(any(target_arch = "x86", + target_arch = "arm", + target_arch = "aarch64"))] +pub type boolean_t = libc::c_int; +#[cfg(target_arch = "x86_64")] +pub type boolean_t = libc::c_uint; + +#[cfg(target_pointer_width = "64")] +pub type CGFloat = libc::c_double; +#[cfg(not(target_pointer_width = "64"))] +pub type CGFloat = libc::c_float; + +pub type CGError = i32; + +pub const kCGImageAlphaNone: u32 = 0; +pub const kCGImageAlphaPremultipliedLast: u32 = 1; +pub const kCGImageAlphaPremultipliedFirst: u32 = 2; +pub const kCGImageAlphaLast: u32 = 3; +pub const kCGImageAlphaFirst: u32 = 4; +pub const kCGImageAlphaNoneSkipLast: u32 = 5; +pub const kCGImageAlphaNoneSkipFirst: u32 = 6; + +pub const kCGBitmapByteOrderDefault: u32 = (0 << 12); +pub const kCGBitmapByteOrder16Little: u32 = (1 << 12); +pub const kCGBitmapByteOrder32Little: u32 = (2 << 12); +pub const kCGBitmapByteOrder16Big: u32 = (3 << 12); +pub const kCGBitmapByteOrder32Big: u32 = (4 << 12); + +pub const kCGRenderingIntentDefault: u32 = 0; +pub const kCGRenderingIntentAbsoluteColorimetric: u32 = 1; +pub const kCGRenderingIntentRelativeColorimetric: u32 = 2; +pub const kCGRenderingIntentPerceptual: u32 = 3; +pub const kCGRenderingIntentSaturation: u32 = 4; + +#[cfg(target_endian = "big")] +pub const kCGBitmapByteOrder16Host: u32 = kCGBitmapByteOrder16Big; +#[cfg(target_endian = "big")] +pub const kCGBitmapByteOrder32Host: u32 = kCGBitmapByteOrder32Big; + +#[cfg(target_endian = "little")] +pub const kCGBitmapByteOrder16Host: u32 = kCGBitmapByteOrder16Little; +#[cfg(target_endian = "little")] +pub const kCGBitmapByteOrder32Host: u32 = kCGBitmapByteOrder32Little; diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/color.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/color.rs new file mode 100644 index 0000000..79ef9a0 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/color.rs @@ -0,0 +1,35 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core_foundation::base::{CFTypeID}; +use base::CGFloat; +use core_foundation::base::TCFType; +use super::sys::{CGColorRef}; + +pub use super::sys::CGColorRef as SysCGColorRef; + +declare_TCFType!{ + CGColor, CGColorRef +} +impl_TCFType!(CGColor, CGColorRef, CGColorGetTypeID); + +impl CGColor { + pub fn rgb(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> Self { + unsafe { + let ptr = CGColorCreateGenericRGB(red, green, blue, alpha); + CGColor::wrap_under_create_rule(ptr) + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + fn CGColorCreateGenericRGB(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> ::sys::CGColorRef; + fn CGColorGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/color_space.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/color_space.rs new file mode 100644 index 0000000..9eef09c --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/color_space.rs @@ -0,0 +1,69 @@ +// Copyright 2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core_foundation::base::{CFRelease, CFRetain, CFTypeID}; +use core_foundation::string::CFStringRef; +use foreign_types::ForeignType; + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGColorSpace; + fn drop = |p| CFRelease(p as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGColorSpace; + pub struct CGColorSpaceRef; +} + +impl CGColorSpace { + pub fn type_id() -> CFTypeID { + unsafe { + CGColorSpaceGetTypeID() + } + } + + pub fn create_with_name(name: CFStringRef) -> Option { + unsafe { + let p = CGColorSpaceCreateWithName(name); + if !p.is_null() {Some(CGColorSpace::from_ptr(p))} else {None} + } + } + + #[inline] + pub fn create_device_rgb() -> CGColorSpace { + unsafe { + let result = CGColorSpaceCreateDeviceRGB(); + CGColorSpace::from_ptr(result) + } + } + + #[inline] + pub fn create_device_gray() -> CGColorSpace { + unsafe { + let result = CGColorSpaceCreateDeviceGray(); + CGColorSpace::from_ptr(result) + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + pub static kCGColorSpaceSRGB: CFStringRef; + pub static kCGColorSpaceAdobeRGB1998: CFStringRef; + pub static kCGColorSpaceGenericGray: CFStringRef; + pub static kCGColorSpaceGenericRGB: CFStringRef; + pub static kCGColorSpaceGenericCMYK: CFStringRef; + pub static kCGColorSpaceGenericRGBLinear: CFStringRef; + pub static kCGColorSpaceGenericGrayGamma2_2: CFStringRef; + + fn CGColorSpaceCreateDeviceRGB() -> ::sys::CGColorSpaceRef; + fn CGColorSpaceCreateDeviceGray() -> ::sys::CGColorSpaceRef; + fn CGColorSpaceCreateWithName(name: CFStringRef) -> ::sys::CGColorSpaceRef; + fn CGColorSpaceGetTypeID() -> CFTypeID; +} + diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/context.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/context.rs new file mode 100644 index 0000000..ec0b7b1 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/context.rs @@ -0,0 +1,685 @@ +// Copyright 2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use base::CGFloat; +use color_space::CGColorSpace; +use core_foundation::base::{ToVoid, CFRelease, CFRetain, CFTypeID}; +use font::{CGFont, CGGlyph}; +use geometry::CGPoint; +use color::CGColor; +use path::CGPathRef; +use libc::{c_int, size_t}; +use std::os::raw::c_void; + +use std::cmp; +use std::ptr; +use std::slice; +use geometry::{CGAffineTransform, CGRect}; +use image::CGImage; +use foreign_types::{ForeignType, ForeignTypeRef}; + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGBlendMode { + Normal = 0, + Multiply, + Screen, + Overlay, + Darken, + Lighten, + ColorDodge, + ColorBurn, + SoftLight, + HardLight, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, + // 10.5 and up: + Clear, + Copy, + SourceIn, + SourceOut, + SourceAtop, + DestinationOver, + DestinationIn, + DestinationOut, + DestinationAtop, + Xor, + PlusDarker, + PlusLighter, +} + +#[repr(C)] +pub enum CGTextDrawingMode { + CGTextFill, + CGTextStroke, + CGTextFillStroke, + CGTextInvisible, + CGTextFillClip, + CGTextStrokeClip, + CGTextClip +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGLineCap { + CGLineCapButt, + CGLineCapRound, + CGLineCapSquare, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGLineJoin { + CGLineJoinMiter, + CGLineJoinRound, + CGLineJoinBevel, +} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGPathDrawingMode { + CGPathFill, + CGPathEOFill, + CGPathStroke, + CGPathFillStroke, + CGPathEOFillStroke, +} + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGContext; + fn drop = |cs| CFRelease(cs as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGContext; + pub struct CGContextRef; +} + +impl CGContext { + pub fn type_id() -> CFTypeID { + unsafe { + CGContextGetTypeID() + } + } + + pub fn create_bitmap_context(data: Option<*mut c_void>, + width: size_t, + height: size_t, + bits_per_component: size_t, + bytes_per_row: size_t, + space: &CGColorSpace, + bitmap_info: u32) + -> CGContext { + unsafe { + let result = CGBitmapContextCreate(data.unwrap_or(ptr::null_mut()), + width, + height, + bits_per_component, + bytes_per_row, + space.as_ptr(), + bitmap_info); + assert!(!result.is_null()); + Self::from_ptr(result) + } + } + + pub fn data(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut( + CGBitmapContextGetData(self.as_ptr()) as *mut u8, + (self.height() * self.bytes_per_row()) as usize) + } + } +} + +impl CGContextRef { + pub fn flush(&self) { + unsafe { + CGContextFlush(self.as_ptr()) + } + } + + pub fn width(&self) -> size_t { + unsafe { + CGBitmapContextGetWidth(self.as_ptr()) + } + } + + pub fn height(&self) -> size_t { + unsafe { + CGBitmapContextGetHeight(self.as_ptr()) + } + } + + pub fn bytes_per_row(&self) -> size_t { + unsafe { + CGBitmapContextGetBytesPerRow(self.as_ptr()) + } + } + + pub fn clip_bounding_box(&self) -> CGRect { + unsafe { + CGContextGetClipBoundingBox(self.as_ptr()) + } + } + + pub fn set_fill_color(&self, color: &CGColor) { + unsafe { + CGContextSetFillColorWithColor(self.as_ptr(), color.to_void()); + } + } + + pub fn set_rgb_fill_color(&self, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { + unsafe { + CGContextSetRGBFillColor(self.as_ptr(), red, green, blue, alpha) + } + } + + pub fn set_rgb_stroke_color(&self, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { + unsafe { + CGContextSetRGBStrokeColor(self.as_ptr(), red, green, blue, alpha) + } + } + + pub fn set_gray_fill_color(&self, gray: CGFloat, alpha: CGFloat) { + unsafe { + CGContextSetGrayFillColor(self.as_ptr(), gray, alpha) + } + } + + pub fn set_blend_mode(&self, blend_mode: CGBlendMode) { + unsafe { + CGContextSetBlendMode(self.as_ptr(), blend_mode) + } + } + + pub fn set_allows_font_smoothing(&self, allows_font_smoothing: bool) { + unsafe { + CGContextSetAllowsFontSmoothing(self.as_ptr(), allows_font_smoothing) + } + } + + pub fn set_font_smoothing_style(&self, style: i32) { + unsafe { + CGContextSetFontSmoothingStyle(self.as_ptr(), style as _); + } + } + + pub fn set_should_smooth_fonts(&self, should_smooth_fonts: bool) { + unsafe { + CGContextSetShouldSmoothFonts(self.as_ptr(), should_smooth_fonts) + } + } + + pub fn set_allows_antialiasing(&self, allows_antialiasing: bool) { + unsafe { + CGContextSetAllowsAntialiasing(self.as_ptr(), allows_antialiasing) + } + } + + pub fn set_should_antialias(&self, should_antialias: bool) { + unsafe { + CGContextSetShouldAntialias(self.as_ptr(), should_antialias) + } + } + + pub fn set_allows_font_subpixel_quantization(&self, allows_font_subpixel_quantization: bool) { + unsafe { + CGContextSetAllowsFontSubpixelQuantization(self.as_ptr(), allows_font_subpixel_quantization) + } + } + + pub fn set_should_subpixel_quantize_fonts(&self, should_subpixel_quantize_fonts: bool) { + unsafe { + CGContextSetShouldSubpixelQuantizeFonts(self.as_ptr(), should_subpixel_quantize_fonts) + } + } + + pub fn set_allows_font_subpixel_positioning(&self, allows_font_subpixel_positioning: bool) { + unsafe { + CGContextSetAllowsFontSubpixelPositioning(self.as_ptr(), allows_font_subpixel_positioning) + } + } + + pub fn set_should_subpixel_position_fonts(&self, should_subpixel_position_fonts: bool) { + unsafe { + CGContextSetShouldSubpixelPositionFonts(self.as_ptr(), should_subpixel_position_fonts) + } + } + + pub fn set_text_drawing_mode(&self, mode: CGTextDrawingMode) { + unsafe { + CGContextSetTextDrawingMode(self.as_ptr(), mode) + } + } + + pub fn set_line_cap(&self, cap: CGLineCap) { + unsafe { + CGContextSetLineCap(self.as_ptr(), cap) + } + } + + pub fn set_line_dash(&self, phase: CGFloat, lengths: &[CGFloat]) { + unsafe { + CGContextSetLineDash(self.as_ptr(), phase, lengths.as_ptr(), lengths.len()) + } + } + + pub fn set_line_join(&self, join: CGLineJoin) { + unsafe { + CGContextSetLineJoin(self.as_ptr(), join) + } + } + + pub fn set_line_width(&self, width: CGFloat) { + unsafe { + CGContextSetLineWidth(self.as_ptr(), width) + } + } + + pub fn set_miter_limit(&self, limit: CGFloat) { + unsafe { + CGContextSetMiterLimit(self.as_ptr(), limit) + } + } + + pub fn add_path(&self, path: &CGPathRef) { + unsafe { + CGContextAddPath(self.as_ptr(), path.as_ptr()); + } + } + + pub fn add_curve_to_point(&self, + cp1x: CGFloat, + cp1y: CGFloat, + cp2x: CGFloat, + cp2y: CGFloat, + x: CGFloat, + y: CGFloat) { + unsafe { + CGContextAddCurveToPoint(self.as_ptr(), + cp1x, cp1y, + cp2x, cp2y, + x, y); + } + } + + pub fn add_quad_curve_to_point(&self, + cpx: CGFloat, + cpy: CGFloat, + x: CGFloat, + y: CGFloat) { + unsafe { + CGContextAddQuadCurveToPoint(self.as_ptr(), + cpx, cpy, + x, y); + } + } + + pub fn add_line_to_point(&self, x: CGFloat, y: CGFloat) { + unsafe { + CGContextAddLineToPoint(self.as_ptr(), x, y); + } + } + + pub fn begin_path(&self) { + unsafe { + CGContextBeginPath(self.as_ptr()); + } + } + + pub fn close_path(&self) { + unsafe { + CGContextClosePath(self.as_ptr()); + } + } + + pub fn move_to_point(&self, x: CGFloat, y: CGFloat) { + unsafe { + CGContextMoveToPoint(self.as_ptr(), x, y); + } + } + + pub fn clip(&self) { + unsafe { + CGContextClip(self.as_ptr()); + } + } + + pub fn eo_clip(&self) { + unsafe { + CGContextEOClip(self.as_ptr()); + } + } + + pub fn draw_path(&self, mode: CGPathDrawingMode) { + unsafe { + CGContextDrawPath(self.as_ptr(), mode); + } + } + + pub fn fill_path(&self) { + unsafe { + CGContextFillPath(self.as_ptr()); + } + } + + pub fn eo_fill_path(&self) { + unsafe { + CGContextEOFillPath(self.as_ptr()); + } + } + + pub fn stroke_path(&self) { + unsafe { + CGContextStrokePath(self.as_ptr()); + } + } + + pub fn fill_rect(&self, rect: CGRect) { + unsafe { + CGContextFillRect(self.as_ptr(), rect) + } + } + + pub fn fill_rects(&self, rects: &[CGRect]) { + unsafe { + CGContextFillRects(self.as_ptr(), rects.as_ptr(), rects.len()) + } + } + + pub fn clear_rect(&self, rect: CGRect) { + unsafe { + CGContextClearRect(self.as_ptr(), rect) + } + } + + pub fn stroke_rect(&self, rect: CGRect) { + unsafe { + CGContextStrokeRect(self.as_ptr(), rect) + } + } + + pub fn stroke_rect_with_width(&self, rect: CGRect, width: CGFloat) { + unsafe { + CGContextStrokeRectWithWidth(self.as_ptr(), rect, width) + } + } + + pub fn clip_to_rect(&self, rect: CGRect) { + unsafe { + CGContextClipToRect(self.as_ptr(), rect) + } + } + + pub fn clip_to_rects(&self, rects: &[CGRect]) { + unsafe { + CGContextClipToRects(self.as_ptr(), rects.as_ptr(), rects.len()) + } + } + + pub fn replace_path_with_stroked_path(&self) { + unsafe { + CGContextReplacePathWithStrokedPath(self.as_ptr()) + } + } + + pub fn fill_ellipse_in_rect(&self, rect: CGRect) { + unsafe { + CGContextFillEllipseInRect(self.as_ptr(), rect) + } + } + + pub fn stroke_ellipse_in_rect(&self, rect: CGRect) { + unsafe { + CGContextStrokeEllipseInRect(self.as_ptr(), rect) + } + } + + pub fn stroke_line_segments(&self, points: &[CGPoint]) { + unsafe { + CGContextStrokeLineSegments(self.as_ptr(), points.as_ptr(), points.len()) + } + } + + pub fn draw_image(&self, rect: CGRect, image: &CGImage) { + unsafe { + CGContextDrawImage(self.as_ptr(), rect, image.as_ptr()); + } + } + + pub fn create_image(&self) -> Option { + let image = unsafe { CGBitmapContextCreateImage(self.as_ptr()) }; + if !image.is_null() { + Some(unsafe { CGImage::from_ptr(image) }) + } else { + None + } + } + + pub fn set_font(&self, font: &CGFont) { + unsafe { + CGContextSetFont(self.as_ptr(), font.as_ptr()) + } + } + + pub fn set_font_size(&self, size: CGFloat) { + unsafe { + CGContextSetFontSize(self.as_ptr(), size) + } + } + + pub fn set_text_matrix(&self, t: &CGAffineTransform) { + unsafe { + CGContextSetTextMatrix(self.as_ptr(), *t) + } + } + + pub fn show_glyphs_at_positions(&self, glyphs: &[CGGlyph], positions: &[CGPoint]) { + unsafe { + let count = cmp::min(glyphs.len(), positions.len()); + CGContextShowGlyphsAtPositions(self.as_ptr(), + glyphs.as_ptr(), + positions.as_ptr(), + count) + } + } + + pub fn save(&self) { + unsafe { + CGContextSaveGState(self.as_ptr()); + } + } + + pub fn restore(&self) { + unsafe { + CGContextRestoreGState(self.as_ptr()); + } + } + + pub fn translate(&self, tx: CGFloat, ty: CGFloat) { + unsafe { + CGContextTranslateCTM(self.as_ptr(), tx, ty); + } + } + + pub fn scale(&self, sx: CGFloat, sy: CGFloat) { + unsafe { + CGContextScaleCTM(self.as_ptr(), sx, sy); + } + } + + pub fn rotate(&self, angle: CGFloat) { + unsafe { + CGContextRotateCTM(self.as_ptr(), angle); + } + } + + pub fn get_ctm(&self) -> CGAffineTransform { + unsafe { + CGContextGetCTM(self.as_ptr()) + } + } + + pub fn concat_ctm(&self, transform: CGAffineTransform) { + unsafe { + CGContextConcatCTM(self.as_ptr(), transform) + } + } +} + +#[test] +fn create_bitmap_context_test() { + use geometry::*; + + let cs = CGColorSpace::create_device_rgb(); + let ctx = CGContext::create_bitmap_context(None, + 16, 8, + 8, 0, + &cs, + ::base::kCGImageAlphaPremultipliedLast); + ctx.set_rgb_fill_color(1.,0.,1.,1.); + ctx.set_miter_limit(4.); + ctx.fill_rect(CGRect::new(&CGPoint::new(0.,0.), &CGSize::new(8.,8.))); + let img = ctx.create_image().unwrap(); + assert_eq!(16, img.width()); + assert_eq!(8, img.height()); + assert_eq!(8, img.bits_per_component()); + assert_eq!(32, img.bits_per_pixel()); + let data = img.data(); + assert_eq!(255, data.bytes()[0]); + assert_eq!(0, data.bytes()[1]); + assert_eq!(255, data.bytes()[2]); + assert_eq!(255, data.bytes()[3]); +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + fn CGBitmapContextCreate(data: *mut c_void, + width: size_t, + height: size_t, + bitsPerComponent: size_t, + bytesPerRow: size_t, + space: ::sys::CGColorSpaceRef, + bitmapInfo: u32) + -> ::sys::CGContextRef; + fn CGBitmapContextGetData(context: ::sys::CGContextRef) -> *mut c_void; + fn CGBitmapContextGetWidth(context: ::sys::CGContextRef) -> size_t; + fn CGBitmapContextGetHeight(context: ::sys::CGContextRef) -> size_t; + fn CGBitmapContextGetBytesPerRow(context: ::sys::CGContextRef) -> size_t; + fn CGBitmapContextCreateImage(context: ::sys::CGContextRef) -> ::sys::CGImageRef; + fn CGContextGetTypeID() -> CFTypeID; + fn CGContextGetClipBoundingBox(c: ::sys::CGContextRef) -> CGRect; + fn CGContextFlush(c: ::sys::CGContextRef); + fn CGContextSetBlendMode(c: ::sys::CGContextRef, blendMode: CGBlendMode); + fn CGContextSetAllowsFontSmoothing(c: ::sys::CGContextRef, allowsFontSmoothing: bool); + fn CGContextSetShouldSmoothFonts(c: ::sys::CGContextRef, shouldSmoothFonts: bool); + fn CGContextSetFontSmoothingStyle(c: ::sys::CGContextRef, style: c_int); + fn CGContextSetAllowsAntialiasing(c: ::sys::CGContextRef, allowsAntialiasing: bool); + fn CGContextSetShouldAntialias(c: ::sys::CGContextRef, shouldAntialias: bool); + fn CGContextSetAllowsFontSubpixelQuantization(c: ::sys::CGContextRef, + allowsFontSubpixelQuantization: bool); + fn CGContextSetShouldSubpixelQuantizeFonts(c: ::sys::CGContextRef, + shouldSubpixelQuantizeFonts: bool); + fn CGContextSetAllowsFontSubpixelPositioning(c: ::sys::CGContextRef, + allowsFontSubpixelPositioning: bool); + fn CGContextSetShouldSubpixelPositionFonts(c: ::sys::CGContextRef, + shouldSubpixelPositionFonts: bool); + fn CGContextSetTextDrawingMode(c: ::sys::CGContextRef, mode: CGTextDrawingMode); + fn CGContextSetFillColorWithColor(c: ::sys::CGContextRef, color: *const c_void); + fn CGContextSetLineCap(c: ::sys::CGContextRef, cap: CGLineCap); + fn CGContextSetLineDash(c: ::sys::CGContextRef, phase: CGFloat, lengths: *const CGFloat, count: size_t); + fn CGContextSetLineJoin(c: ::sys::CGContextRef, join: CGLineJoin); + fn CGContextSetLineWidth(c: ::sys::CGContextRef, width: CGFloat); + fn CGContextSetMiterLimit(c: ::sys::CGContextRef, limit: CGFloat); + + fn CGContextAddPath(c: ::sys::CGContextRef, path: ::sys::CGPathRef); + fn CGContextAddCurveToPoint(c: ::sys::CGContextRef, + cp1x: CGFloat, + cp1y: CGFloat, + cp2x: CGFloat, + cp2y: CGFloat, + x: CGFloat, + y: CGFloat); + fn CGContextAddQuadCurveToPoint(c: ::sys::CGContextRef, + cpx: CGFloat, + cpy: CGFloat, + x: CGFloat, + y: CGFloat); + fn CGContextAddLineToPoint(c: ::sys::CGContextRef, + x: CGFloat, + y: CGFloat); + fn CGContextBeginPath(c: ::sys::CGContextRef); + fn CGContextClosePath(c: ::sys::CGContextRef); + fn CGContextMoveToPoint(c: ::sys::CGContextRef, + x: CGFloat, + y: CGFloat); + fn CGContextDrawPath(c: ::sys::CGContextRef, mode: CGPathDrawingMode); + fn CGContextFillPath(c: ::sys::CGContextRef); + fn CGContextEOFillPath(c: ::sys::CGContextRef); + fn CGContextClip(c: ::sys::CGContextRef); + fn CGContextEOClip(c: ::sys::CGContextRef); + fn CGContextStrokePath(c: ::sys::CGContextRef); + fn CGContextSetRGBFillColor(context: ::sys::CGContextRef, + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat); + fn CGContextSetRGBStrokeColor(context: ::sys::CGContextRef, + red: CGFloat, + green: CGFloat, + blue: CGFloat, + alpha: CGFloat); + fn CGContextSetGrayFillColor(context: ::sys::CGContextRef, gray: CGFloat, alpha: CGFloat); + fn CGContextClearRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextFillRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextFillRects(context: ::sys::CGContextRef, + rects: *const CGRect, + count: size_t); + fn CGContextStrokeRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextStrokeRectWithWidth(context: ::sys::CGContextRef, + rect: CGRect, + width: CGFloat); + fn CGContextClipToRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextClipToRects(context: ::sys::CGContextRef, + rects: *const CGRect, + count: size_t); + fn CGContextReplacePathWithStrokedPath(context: ::sys::CGContextRef); + fn CGContextFillEllipseInRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextStrokeEllipseInRect(context: ::sys::CGContextRef, + rect: CGRect); + fn CGContextStrokeLineSegments(context: ::sys::CGContextRef, + points: *const CGPoint, + count: size_t); + fn CGContextDrawImage(c: ::sys::CGContextRef, rect: CGRect, image: ::sys::CGImageRef); + fn CGContextSetFont(c: ::sys::CGContextRef, font: ::sys::CGFontRef); + fn CGContextSetFontSize(c: ::sys::CGContextRef, size: CGFloat); + fn CGContextSetTextMatrix(c: ::sys::CGContextRef, t: CGAffineTransform); + fn CGContextShowGlyphsAtPositions(c: ::sys::CGContextRef, + glyphs: *const CGGlyph, + positions: *const CGPoint, + count: size_t); + + fn CGContextSaveGState(c: ::sys::CGContextRef); + fn CGContextRestoreGState(c: ::sys::CGContextRef); + fn CGContextTranslateCTM(c: ::sys::CGContextRef, tx: CGFloat, ty: CGFloat); + fn CGContextScaleCTM(c: ::sys::CGContextRef, sx: CGFloat, sy: CGFloat); + fn CGContextRotateCTM(c: ::sys::CGContextRef, angle: CGFloat); + fn CGContextGetCTM(c: ::sys::CGContextRef) -> CGAffineTransform; + fn CGContextConcatCTM(c: ::sys::CGContextRef, transform: CGAffineTransform); +} + diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/data_provider.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/data_provider.rs new file mode 100644 index 0000000..d2d52d8 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/data_provider.rs @@ -0,0 +1,125 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core_foundation::base::{CFRelease, CFRetain, CFTypeID, TCFType}; +use core_foundation::data::{CFData, CFDataRef}; + +use libc::{size_t, off_t}; +use std::mem; +use std::ptr; +use std::sync::Arc; +use std::os::raw::c_void; + +use foreign_types::{ForeignType, ForeignTypeRef}; + +pub type CGDataProviderGetBytesCallback = Option size_t>; +pub type CGDataProviderReleaseInfoCallback = Option; +pub type CGDataProviderRewindCallback = Option; +pub type CGDataProviderSkipBytesCallback = Option; +pub type CGDataProviderSkipForwardCallback = Option off_t>; + +pub type CGDataProviderGetBytePointerCallback = Option *mut c_void>; +pub type CGDataProviderGetBytesAtOffsetCallback = Option; +pub type CGDataProviderReleaseBytePointerCallback = Option; +pub type CGDataProviderReleaseDataCallback = Option; +pub type CGDataProviderGetBytesAtPositionCallback = Option; + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGDataProvider; + fn drop = |cs| CFRelease(cs as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGDataProvider; + pub struct CGDataProviderRef; +} + +impl CGDataProvider { + pub fn type_id() -> CFTypeID { + unsafe { + CGDataProviderGetTypeID() + } + } + + /// Creates a data provider from the given reference-counted buffer. + /// + /// The `CGDataProvider` object takes ownership of the reference. Once the data provider + /// is destroyed, the reference count of the buffer is automatically decremented. + pub fn from_buffer(buffer: Arc>) -> Self { + unsafe { + let ptr = (*buffer).as_ptr() as *const c_void; + let len = buffer.len() as size_t; + let info = mem::transmute::>, *mut c_void>(buffer); + let result = CGDataProviderCreateWithData(info, ptr, len, Some(release)); + return CGDataProvider::from_ptr(result); + } + + unsafe extern "C" fn release(info: *mut c_void, _: *const c_void, _: size_t) { + drop(mem::transmute::<*mut c_void, Arc>>(info)) + } + } + + /// Creates a data prvider from a given slice. The data provider does not own the slice in this + /// case, so it's up to the user to ensure the memory safety here. + pub unsafe fn from_slice(buffer: &[u8]) -> Self { + let ptr = buffer.as_ptr() as *const c_void; + let len = buffer.len() as size_t; + let result = CGDataProviderCreateWithData(ptr::null_mut(), ptr, len, None); + CGDataProvider::from_ptr(result) + } + + /// Creates a data provider from the given raw pointer, length, and destructor function. + /// + /// This is double-boxed because the Core Text API requires that the userdata be a single + /// pointer. + pub unsafe fn from_custom_data(custom_data: Box>) -> Self { + let (ptr, len) = (custom_data.ptr() as *const c_void, custom_data.len()); + let userdata = mem::transmute::>, &mut c_void>(custom_data); + let data_provider = CGDataProviderCreateWithData(userdata, ptr, len, Some(release)); + return CGDataProvider::from_ptr(data_provider); + + unsafe extern "C" fn release(info: *mut c_void, _: *const c_void, _: size_t) { + drop(mem::transmute::<*mut c_void, Box>>(info)) + } + } +} + +impl CGDataProviderRef { + /// Creates a copy of the data from the underlying `CFDataProviderRef`. + pub fn copy_data(&self) -> CFData { + unsafe { CFData::wrap_under_create_rule(CGDataProviderCopyData(self.as_ptr())) } + } +} + +/// Encapsulates custom data that can be wrapped. +pub trait CustomData { + /// Returns a pointer to the start of the custom data. This pointer *must not change* during + /// the lifespan of this CustomData. + unsafe fn ptr(&self) -> *const u8; + /// Returns the length of this custom data. This value must not change during the lifespan of + /// this CustomData. + unsafe fn len(&self) -> usize; +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + fn CGDataProviderCopyData(provider: ::sys::CGDataProviderRef) -> CFDataRef; + //fn CGDataProviderCreateDirect + //fn CGDataProviderCreateSequential + //fn CGDataProviderCreateWithCFData + fn CGDataProviderCreateWithData(info: *mut c_void, + data: *const c_void, + size: size_t, + releaseData: CGDataProviderReleaseDataCallback + ) -> ::sys::CGDataProviderRef; + //fn CGDataProviderCreateWithFilename(filename: *c_char) -> CGDataProviderRef; + //fn CGDataProviderCreateWithURL + fn CGDataProviderGetTypeID() -> CFTypeID; + //fn CGDataProviderRelease(provider: CGDataProviderRef); + //fn CGDataProviderRetain(provider: CGDataProviderRef) -> CGDataProviderRef; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/display.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/display.rs new file mode 100644 index 0000000..f677408 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/display.rs @@ -0,0 +1,718 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +use libc; +use std::ptr; +use std::ops::Deref; + +pub use base::{CGError, boolean_t}; +pub use geometry::{CGRect, CGPoint, CGSize}; + +use core_foundation::string::{CFString, CFStringRef}; +use core_foundation::base::{CFRetain, TCFType}; +use image::CGImage; +use foreign_types::ForeignType; + +pub type CGDirectDisplayID = u32; +pub type CGWindowID = u32; + +pub const kCGNullWindowID: CGWindowID = 0 as CGWindowID; +pub const kCGNullDirectDisplayID: CGDirectDisplayID = 0 as CGDirectDisplayID; + +pub type CGWindowListOption = u32; + +pub const kCGWindowListOptionAll: CGWindowListOption = 0; +pub const kCGWindowListOptionOnScreenOnly: CGWindowListOption = 1 << 0; +pub const kCGWindowListOptionOnScreenAboveWindow: CGWindowListOption = 1 << 1; +pub const kCGWindowListOptionOnScreenBelowWindow: CGWindowListOption = 1 << 2; +pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 3; +pub const kCGWindowListExcludeDesktopElements: CGWindowListOption = 1 << 4; + +pub type CGWindowImageOption = u32; + +pub const kCGWindowImageDefault: CGWindowImageOption = 0; +pub const kCGWindowImageBoundsIgnoreFraming: CGWindowImageOption = 1 << 0; +pub const kCGWindowImageShouldBeOpaque: CGWindowImageOption = 1 << 1; +pub const kCGWindowImageOnlyShadows: CGWindowImageOption = 1 << 2; +pub const kCGWindowImageBestResolution: CGWindowImageOption = 1 << 3; +pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4; + +pub const kDisplayModeValidFlag: u32 = 0x00000001; +pub const kDisplayModeSafeFlag: u32 = 0x00000002; +pub const kDisplayModeDefaultFlag: u32 = 0x00000004; +pub const kDisplayModeAlwaysShowFlag: u32 = 0x00000008; +pub const kDisplayModeNeverShowFlag: u32 = 0x00000080; +pub const kDisplayModeNotResizeFlag: u32 = 0x00000010; +pub const kDisplayModeRequiresPanFlag: u32 = 0x00000020; +pub const kDisplayModeInterlacedFlag: u32 = 0x00000040; +pub const kDisplayModeSimulscanFlag: u32 = 0x00000100; +pub const kDisplayModeBuiltInFlag: u32 = 0x00000400; +pub const kDisplayModeNotPresetFlag: u32 = 0x00000200; +pub const kDisplayModeStretchedFlag: u32 = 0x00000800; +pub const kDisplayModeNotGraphicsQualityFlag: u32 = 0x00001000; +pub const kDisplayModeValidateAgainstDisplay: u32 = 0x00002000; +pub const kDisplayModeTelevisionFlag: u32 = 0x00100000; +pub const kDisplayModeValidForMirroringFlag: u32 = 0x00200000; +pub const kDisplayModeAcceleratorBackedFlag: u32 = 0x00400000; +pub const kDisplayModeValidForHiResFlag: u32 = 0x00800000; +pub const kDisplayModeValidForAirPlayFlag: u32 = 0x01000000; +pub const kDisplayModeNativeFlag: u32 = 0x02000000; + +pub const kDisplayModeSafetyFlags: u32 = 0x00000007; + +pub const IO1BitIndexedPixels: &str = "P"; +pub const IO2BitIndexedPixels: &str = "PP"; +pub const IO4BitIndexedPixels: &str = "PPPP"; +pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; +pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; +pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; +pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; +pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; +pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; +pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; +pub const IOYUV422Pixels: &str = "Y4U2V2"; +pub const IO8BitOverlayPixels: &str = "O8"; + + +pub use core_foundation::dictionary::{ CFDictionary, CFDictionaryRef, CFDictionaryGetValueIfPresent }; +pub use core_foundation::array::{ CFArray, CFArrayRef }; +pub use core_foundation::array::{ CFArrayGetCount, CFArrayGetValueAtIndex }; +pub use core_foundation::base::{ CFIndex, CFRelease, CFTypeRef }; + +pub type CGDisplayConfigRef = *mut libc::c_void; + +#[repr(u32)] +#[derive(Clone, Copy)] +pub enum CGConfigureOption { + ConfigureForAppOnly = 0, + ConfigureForSession = 1, + ConfigurePermanently = 2, +} + +#[derive(Copy, Clone, Debug)] +pub struct CGDisplay { + pub id: CGDirectDisplayID, +} + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGDisplayMode; + fn drop = CGDisplayModeRelease; + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGDisplayMode; + pub struct CGDisplayModeRef; +} + +impl CGDisplay { + #[inline] + pub fn new(id: CGDirectDisplayID) -> CGDisplay { + CGDisplay { id: id } + } + + /// Returns the the main display. + #[inline] + pub fn main() -> CGDisplay { + CGDisplay::new(unsafe { CGMainDisplayID() }) + } + + /// A value that will never correspond to actual hardware. + pub fn null_display() -> CGDisplay { + CGDisplay::new(kCGNullDirectDisplayID) + } + + /// Returns the bounds of a display in the global display coordinate space. + #[inline] + pub fn bounds(&self) -> CGRect { + unsafe { CGDisplayBounds(self.id) } + } + + /// Returns information about a display's current configuration. + #[inline] + pub fn display_mode(&self) -> Option { + unsafe { + let mode_ref = CGDisplayCopyDisplayMode(self.id); + if !mode_ref.is_null() { + Some(CGDisplayMode::from_ptr(mode_ref)) + } else { + None + } + } + } + + /// Begins a new set of display configuration changes. + pub fn begin_configuration(&self) -> Result { + unsafe { + let mut config_ref: CGDisplayConfigRef = ptr::null_mut(); + let result = CGBeginDisplayConfiguration(&mut config_ref); + if result == 0 { + Ok(config_ref) + } else { + Err(result) + } + } + } + + /// Cancels a set of display configuration changes. + pub fn cancel_configuration(&self, config_ref: &CGDisplayConfigRef) -> Result<(), CGError> { + let result = unsafe { CGCancelDisplayConfiguration(*config_ref) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Completes a set of display configuration changes. + pub fn complete_configuration( + &self, + config_ref: &CGDisplayConfigRef, + option: CGConfigureOption, + ) -> Result<(), CGError> { + let result = unsafe { CGCompleteDisplayConfiguration(*config_ref, option) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Configures the display mode of a display. + pub fn configure_display_with_display_mode( + &self, + config_ref: &CGDisplayConfigRef, + display_mode: &CGDisplayMode, + ) -> Result<(), CGError> { + let result = unsafe { + CGConfigureDisplayWithDisplayMode( + *config_ref, + self.id, + display_mode.as_ptr(), + ptr::null(), + ) + }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Configures the origin of a display in the global display coordinate space. + pub fn configure_display_origin( + &self, + config_ref: &CGDisplayConfigRef, + x: i32, + y: i32, + ) -> Result<(), CGError> { + let result = unsafe { CGConfigureDisplayOrigin(*config_ref, self.id, x, y) }; + + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Changes the configuration of a mirroring set. + pub fn configure_display_mirror_of_display( + &self, + config_ref: &CGDisplayConfigRef, + master: &CGDisplay, + ) -> Result<(), CGError> { + let result = unsafe { CGConfigureDisplayMirrorOfDisplay(*config_ref, self.id, master.id) }; + + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Returns an image containing the contents of the specified display. + #[inline] + pub fn image(&self) -> Option { + unsafe { + let image_ref = CGDisplayCreateImage(self.id); + if !image_ref.is_null() { + Some(CGImage::from_ptr(image_ref)) + } else { + None + } + } + } + + /// Returns a composite image based on a dynamically generated list of + /// windows. + #[inline] + pub fn screenshot( + bounds: CGRect, + list_option: CGWindowListOption, + window_id: CGWindowID, + image_option: CGWindowImageOption, + ) -> Option { + unsafe { + let image_ref = CGWindowListCreateImage(bounds, list_option, window_id, image_option); + if !image_ref.is_null() { + Some(CGImage::from_ptr(image_ref)) + } else { + None + } + } + } + + /// Returns a composite image of the specified windows. + #[inline] + pub fn screenshot_from_windows( + bounds: CGRect, + windows: CFArray, + image_option: CGWindowImageOption, + ) -> Option { + unsafe { + let image_ref = CGWindowListCreateImageFromArray( + bounds, + windows.as_concrete_TypeRef(), + image_option, + ); + if !image_ref.is_null() { + Some(CGImage::from_ptr(image_ref)) + } else { + None + } + } + } + + /// Generates and returns information about the selected windows in the + /// current user session. + pub fn window_list_info( + option: CGWindowListOption, + relative_to_window: Option, + ) -> Option { + let relative_to_window = relative_to_window.unwrap_or(kCGNullWindowID); + let array_ref = unsafe { CGWindowListCopyWindowInfo(option, relative_to_window) }; + if !array_ref.is_null() { + Some(unsafe { TCFType::wrap_under_create_rule(array_ref) }) + } else { + None + } + } + + /// Returns a Boolean value indicating whether a display is active. + #[inline] + pub fn is_active(&self) -> bool { + unsafe { CGDisplayIsActive(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is always in a + /// mirroring set. + #[inline] + pub fn is_always_in_mirror_set(&self) -> bool { + unsafe { CGDisplayIsAlwaysInMirrorSet(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is sleeping (and is + /// therefore not drawable.) + #[inline] + pub fn is_asleep(&self) -> bool { + unsafe { CGDisplayIsAsleep(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is built-in, such as + /// the internal display in portable systems. + #[inline] + pub fn is_builtin(&self) -> bool { + unsafe { CGDisplayIsBuiltin(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is in a hardware + /// mirroring set. + #[inline] + pub fn is_in_hw_mirror_set(&self) -> bool { + unsafe { CGDisplayIsInHWMirrorSet(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is in a mirroring set. + #[inline] + pub fn is_in_mirror_set(&self) -> bool { + unsafe { CGDisplayIsInMirrorSet(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is the main display. + #[inline] + pub fn is_main(&self) -> bool { + unsafe { CGDisplayIsMain(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is connected or online. + #[inline] + pub fn is_online(&self) -> bool { + unsafe { CGDisplayIsOnline(self.id) != 0 } + } + + /// Returns a boolean indicating whether Quartz is using OpenGL-based + /// window acceleration (Quartz Extreme) to render in a display. + #[inline] + pub fn uses_open_gl_acceleration(&self) -> bool { + unsafe { CGDisplayUsesOpenGLAcceleration(self.id) != 0 } + } + + /// Returns a boolean indicating whether a display is running in a stereo + /// graphics mode. + #[inline] + pub fn is_stereo(&self) -> bool { + unsafe { CGDisplayIsStereo(self.id) != 0 } + } + + /// For a secondary display in a mirroring set, returns the primary + /// display. + #[inline] + pub fn mirrors_display(&self) -> CGDirectDisplayID { + unsafe { CGDisplayMirrorsDisplay(self.id) } + } + + /// Returns the primary display in a hardware mirroring set. + #[inline] + pub fn primary_display(&self) -> CGDirectDisplayID { + unsafe { CGDisplayPrimaryDisplay(self.id) } + } + + /// Returns the rotation angle of a display in degrees. + #[inline] + pub fn rotation(&self) -> f64 { + unsafe { CGDisplayRotation(self.id) } + } + + /// Returns the width and height of a display in millimeters. + #[inline] + pub fn screen_size(&self) -> CGSize { + unsafe { CGDisplayScreenSize(self.id) } + } + + /// Returns the serial number of a display monitor. + #[inline] + pub fn serial_number(&self) -> u32 { + unsafe { CGDisplaySerialNumber(self.id) } + } + + /// Returns the logical unit number of a display. + #[inline] + pub fn unit_number(&self) -> u32 { + unsafe { CGDisplayUnitNumber(self.id) } + } + + /// Returns the vendor number of the specified display's monitor. + #[inline] + pub fn vendor_number(&self) -> u32 { + unsafe { CGDisplayVendorNumber(self.id) } + } + + /// Returns the model number of a display monitor. + #[inline] + pub fn model_number(&self) -> u32 { + unsafe { CGDisplayModelNumber(self.id) } + } + + /// Returns the display height in pixel units. + #[inline] + pub fn pixels_high(&self) -> u64 { + unsafe { CGDisplayPixelsHigh(self.id) as u64 } + } + + /// Returns the display width in pixel units. + #[inline] + pub fn pixels_wide(&self) -> u64 { + unsafe { CGDisplayPixelsWide(self.id) as u64 } + } + + /// Provides a list of displays that are active (or drawable). + #[inline] + pub fn active_displays() -> Result, CGError> { + let count = CGDisplay::active_display_count()?; + let mut buf: Vec = vec![0; count as usize]; + let result = + unsafe { CGGetActiveDisplayList(count as u32, buf.as_mut_ptr(), ptr::null_mut()) }; + if result == 0 { + Ok(buf) + } else { + Err(result) + } + } + + /// Provides count of displays that are active (or drawable). + #[inline] + pub fn active_display_count() -> Result { + let mut count: u32 = 0; + let result = unsafe { CGGetActiveDisplayList(0, ptr::null_mut(), &mut count) }; + if result == 0 { + Ok(count as u32) + } else { + Err(result) + } + } + + /// Hides the mouse cursor, and increments the hide cursor count. + #[inline] + pub fn hide_cursor(&self) -> Result<(), CGError> { + let result = unsafe { CGDisplayHideCursor(self.id) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Decrements the hide cursor count, and shows the mouse cursor if the + /// count is 0. + #[inline] + pub fn show_cursor(&self) -> Result<(), CGError> { + let result = unsafe { CGDisplayShowCursor(self.id) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Moves the mouse cursor to a specified point relative to the display + /// origin (the upper-left corner of the display). + #[inline] + pub fn move_cursor_to_point(&self, point: CGPoint) -> Result<(), CGError> { + let result = unsafe { CGDisplayMoveCursorToPoint(self.id, point) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Moves the mouse cursor without generating events. + #[inline] + pub fn warp_mouse_cursor_position(point: CGPoint) -> Result<(), CGError> { + let result = unsafe { CGWarpMouseCursorPosition(point) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } + + /// Connects or disconnects the mouse and cursor while an application is + /// in the foreground. + #[inline] + pub fn associate_mouse_and_mouse_cursor_position(connected: bool) -> Result<(), CGError> { + let result = unsafe { CGAssociateMouseAndMouseCursorPosition(connected as boolean_t) }; + if result == 0 { + Ok(()) + } else { + Err(result) + } + } +} + +impl CGDisplayMode { + /// Returns all display modes for the specified display id. + pub fn all_display_modes( + display_id: CGDirectDisplayID, + options: CFDictionaryRef, + ) -> Option> { + let array_opt: Option = unsafe { + let array_ref = CGDisplayCopyAllDisplayModes(display_id, options); + if !array_ref.is_null() { + Some(CFArray::wrap_under_create_rule(array_ref)) + } else { + None + } + }; + match array_opt { + Some(modes) => { + let vec: Vec = modes + .into_iter() + .map(|value0| { + let x = *value0.deref() as *mut ::sys::CGDisplayMode; + unsafe { CGDisplayMode::from_ptr(x) } + }).collect(); + Some(vec) + } + None => None, + } + } + + /// Returns the height of the specified display mode. + #[inline] + pub fn height(&self) -> u64 { + unsafe { CGDisplayModeGetHeight(self.as_ptr()) as u64 } + } + + /// Returns the width of the specified display mode. + #[inline] + pub fn width(&self) -> u64 { + unsafe { CGDisplayModeGetWidth(self.as_ptr()) as u64 } + } + + /// Returns the pixel height of the specified display mode. + #[inline] + pub fn pixel_height(&self) -> u64 { + unsafe { CGDisplayModeGetPixelHeight(self.as_ptr()) as u64 } + } + + /// Returns the pixel width of the specified display mode. + #[inline] + pub fn pixel_width(&self) -> u64 { + unsafe { CGDisplayModeGetPixelWidth(self.as_ptr()) as u64 } + } + + #[inline] + pub fn refresh_rate(&self) -> f64 { + unsafe { CGDisplayModeGetRefreshRate(self.as_ptr()) } + } + + /// Returns the I/O Kit flags of the specified display mode. + #[inline] + pub fn io_flags(&self) -> u32 { + unsafe { CGDisplayModeGetIOFlags(self.as_ptr()) as u32 } + } + + /// Returns the pixel encoding of the specified display mode. + #[inline] + pub fn pixel_encoding(&self) -> CFString { + unsafe { CFString::wrap_under_create_rule(CGDisplayModeCopyPixelEncoding(self.as_ptr())) } + } + + /// Returns the number of bits per pixel of the specified display mode. + pub fn bit_depth(&self) -> usize { + let pixel_encoding = self.pixel_encoding().to_string(); + // my numerical representation for kIO16BitFloatPixels and kIO32bitFloatPixels + // are made up and possibly non-sensical + if pixel_encoding.eq_ignore_ascii_case(kIO32BitFloatPixels) { + 96 + } else if pixel_encoding.eq_ignore_ascii_case(kIO64BitDirectPixels) { + 64 + } else if pixel_encoding.eq_ignore_ascii_case(kIO16BitFloatPixels) { + 48 + } else if pixel_encoding.eq_ignore_ascii_case(IO32BitDirectPixels) { + 32 + } else if pixel_encoding.eq_ignore_ascii_case(kIO30BitDirectPixels) { + 30 + } else if pixel_encoding.eq_ignore_ascii_case(IO16BitDirectPixels) { + 16 + } else if pixel_encoding.eq_ignore_ascii_case(IO8BitIndexedPixels) { + 8 + }else{ + 0 + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern "C" { + pub static CGRectNull: CGRect; + pub static CGRectInfinite: CGRect; + + pub static kCGDisplayShowDuplicateLowResolutionModes: CFStringRef; + + pub fn CGDisplayModeRelease(mode: ::sys::CGDisplayModeRef); + + pub fn CGMainDisplayID() -> CGDirectDisplayID; + pub fn CGDisplayIsActive(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsAlwaysInMirrorSet(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsAsleep(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsBuiltin(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsInHWMirrorSet(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsInMirrorSet(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsMain(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsOnline(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayIsStereo(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayMirrorsDisplay(display: CGDirectDisplayID) -> CGDirectDisplayID; + pub fn CGDisplayPrimaryDisplay(display: CGDirectDisplayID) -> CGDirectDisplayID; + pub fn CGDisplayRotation(display: CGDirectDisplayID) -> libc::c_double; + pub fn CGDisplayScreenSize(display: CGDirectDisplayID) -> CGSize; + pub fn CGDisplaySerialNumber(display: CGDirectDisplayID) -> u32; + pub fn CGDisplayUnitNumber(display: CGDirectDisplayID) -> u32; + pub fn CGDisplayUsesOpenGLAcceleration(display: CGDirectDisplayID) -> boolean_t; + pub fn CGDisplayVendorNumber(display: CGDirectDisplayID) -> u32; + pub fn CGGetActiveDisplayList( + max_displays: u32, + active_displays: *mut CGDirectDisplayID, + display_count: *mut u32, + ) -> CGError; + pub fn CGGetDisplaysWithRect( + rect: CGRect, + max_displays: u32, + displays: *mut CGDirectDisplayID, + matching_display_count: *mut u32, + ) -> CGError; + pub fn CGDisplayModelNumber(display: CGDirectDisplayID) -> u32; + pub fn CGDisplayPixelsHigh(display: CGDirectDisplayID) -> libc::size_t; + pub fn CGDisplayPixelsWide(display: CGDirectDisplayID) -> libc::size_t; + pub fn CGDisplayBounds(display: CGDirectDisplayID) -> CGRect; + pub fn CGDisplayCreateImage(display: CGDirectDisplayID) -> ::sys::CGImageRef; + + pub fn CGBeginDisplayConfiguration(config: *mut CGDisplayConfigRef) -> CGError; + pub fn CGCancelDisplayConfiguration(config: CGDisplayConfigRef) -> CGError; + pub fn CGCompleteDisplayConfiguration( + config: CGDisplayConfigRef, + option: CGConfigureOption, + ) -> CGError; + pub fn CGConfigureDisplayWithDisplayMode( + config: CGDisplayConfigRef, + display: CGDirectDisplayID, + mode: ::sys::CGDisplayModeRef, + options: CFDictionaryRef, + ) -> CGError; + pub fn CGConfigureDisplayMirrorOfDisplay( + config: CGDisplayConfigRef, + display: CGDirectDisplayID, + master: CGDirectDisplayID, + ) -> CGError; + pub fn CGConfigureDisplayOrigin( + config: CGDisplayConfigRef, + display: CGDirectDisplayID, + x: i32, + y: i32, + ) -> CGError; + + pub fn CGDisplayCopyDisplayMode(display: CGDirectDisplayID) -> ::sys::CGDisplayModeRef; + pub fn CGDisplayModeGetHeight(mode: ::sys::CGDisplayModeRef) -> libc::size_t; + pub fn CGDisplayModeGetWidth(mode: ::sys::CGDisplayModeRef) -> libc::size_t; + pub fn CGDisplayModeGetPixelHeight(mode: ::sys::CGDisplayModeRef) -> libc::size_t; + pub fn CGDisplayModeGetPixelWidth(mode: ::sys::CGDisplayModeRef) -> libc::size_t; + pub fn CGDisplayModeGetRefreshRate(mode: ::sys::CGDisplayModeRef) -> libc::c_double; + pub fn CGDisplayModeGetIOFlags(mode: ::sys::CGDisplayModeRef) -> u32; + pub fn CGDisplayModeCopyPixelEncoding(mode: ::sys::CGDisplayModeRef) -> CFStringRef; + + pub fn CGDisplayCopyAllDisplayModes( + display: CGDirectDisplayID, + options: CFDictionaryRef, + ) -> CFArrayRef; + + // mouse stuff + pub fn CGDisplayHideCursor(display: CGDirectDisplayID) -> CGError; + pub fn CGDisplayShowCursor(display: CGDirectDisplayID) -> CGError; + pub fn CGDisplayMoveCursorToPoint(display: CGDirectDisplayID, point: CGPoint) -> CGError; + pub fn CGWarpMouseCursorPosition(point: CGPoint) -> CGError; + pub fn CGAssociateMouseAndMouseCursorPosition(connected: boolean_t) -> CGError; + + // Window Services Reference + pub fn CGWindowListCopyWindowInfo( + option: CGWindowListOption, + relativeToWindow: CGWindowID, + ) -> CFArrayRef; + pub fn CGWindowListCreateImage( + screenBounds: CGRect, + listOptions: CGWindowListOption, + windowId: CGWindowID, + imageOptions: CGWindowImageOption, + ) -> ::sys::CGImageRef; + pub fn CGWindowListCreateImageFromArray( + screenBounds: CGRect, + windowArray: CFArrayRef, + imageOptions: CGWindowImageOption, + ) -> ::sys::CGImageRef; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/event.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/event.rs new file mode 100644 index 0000000..770ca08 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/event.rs @@ -0,0 +1,669 @@ +#![allow(non_upper_case_globals)] + +use core_foundation::base::{CFRelease, CFRetain, CFTypeID}; +use geometry::CGPoint; +use event_source::CGEventSource; + +use libc; + +use foreign_types::ForeignType; + +pub type CGEventField = u32; +pub type CGKeyCode = u16; +pub type CGScrollEventUnit = u32; + +/// Flags for events +/// +/// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h) +bitflags! { + #[repr(C)] + pub struct CGEventFlags: u64 { + const CGEventFlagNull = 0; + + // Device-independent modifier key bits. + const CGEventFlagAlphaShift = 0x00010000; + const CGEventFlagShift = 0x00020000; + const CGEventFlagControl = 0x00040000; + const CGEventFlagAlternate = 0x00080000; + const CGEventFlagCommand = 0x00100000; + + // Special key identifiers. + const CGEventFlagHelp = 0x00400000; + const CGEventFlagSecondaryFn = 0x00800000; + + // Identifies key events from numeric keypad area on extended keyboards. + const CGEventFlagNumericPad = 0x00200000; + + // Indicates if mouse/pen movement events are not being coalesced + const CGEventFlagNonCoalesced = 0x00000100; + } +} + +/// Key codes for keys that are independent of keyboard layout. +/// +/// [Ref](https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.13.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h) +#[repr(C)] +pub struct KeyCode; +impl KeyCode { + pub const RETURN: CGKeyCode = 0x24; + pub const TAB: CGKeyCode = 0x30; + pub const SPACE: CGKeyCode = 0x31; + pub const DELETE: CGKeyCode = 0x33; + pub const ESCAPE: CGKeyCode = 0x35; + pub const COMMAND: CGKeyCode = 0x37; + pub const SHIFT: CGKeyCode = 0x38; + pub const CAPS_LOCK: CGKeyCode = 0x39; + pub const OPTION: CGKeyCode = 0x3A; + pub const CONTROL: CGKeyCode = 0x3B; + pub const RIGHT_COMMAND: CGKeyCode = 0x36; + pub const RIGHT_SHIFT: CGKeyCode = 0x3C; + pub const RIGHT_OPTION: CGKeyCode = 0x3D; + pub const RIGHT_CONTROL: CGKeyCode = 0x3E; + pub const FUNCTION: CGKeyCode = 0x3F; + pub const VOLUME_UP: CGKeyCode = 0x48; + pub const VOLUME_DOWN: CGKeyCode = 0x49; + pub const MUTE: CGKeyCode = 0x4A; + pub const F1: CGKeyCode = 0x7A; + pub const F2: CGKeyCode = 0x78; + pub const F3: CGKeyCode = 0x63; + pub const F4: CGKeyCode = 0x76; + pub const F5: CGKeyCode = 0x60; + pub const F6: CGKeyCode = 0x61; + pub const F7: CGKeyCode = 0x62; + pub const F8: CGKeyCode = 0x64; + pub const F9: CGKeyCode = 0x65; + pub const F10: CGKeyCode = 0x6D; + pub const F11: CGKeyCode = 0x67; + pub const F12: CGKeyCode = 0x6F; + pub const F13: CGKeyCode = 0x69; + pub const F14: CGKeyCode = 0x6B; + pub const F15: CGKeyCode = 0x71; + pub const F16: CGKeyCode = 0x6A; + pub const F17: CGKeyCode = 0x40; + pub const F18: CGKeyCode = 0x4F; + pub const F19: CGKeyCode = 0x50; + pub const F20: CGKeyCode = 0x5A; + pub const HELP: CGKeyCode = 0x72; + pub const HOME: CGKeyCode = 0x73; + pub const PAGE_UP: CGKeyCode = 0x74; + pub const FORWARD_DELETE: CGKeyCode = 0x75; + pub const END: CGKeyCode = 0x77; + pub const PAGE_DOWN: CGKeyCode = 0x79; + pub const LEFT_ARROW: CGKeyCode = 0x7B; + pub const RIGHT_ARROW: CGKeyCode = 0x7C; + pub const DOWN_ARROW: CGKeyCode = 0x7D; + pub const UP_ARROW: CGKeyCode = 0x7E; +} + +#[repr(C)] +pub struct ScrollEventUnit {} +impl ScrollEventUnit { + pub const PIXEL: CGScrollEventUnit = 0; + pub const LINE: CGScrollEventUnit = 1; +} + +/// Constants that specify the different types of input events. +/// +/// [Ref](http://opensource.apple.com/source/IOHIDFamily/IOHIDFamily-700/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h) +#[repr(u32)] +#[derive(Clone, Copy, Debug)] +pub enum CGEventType { + Null = 0, + + // Mouse events. + LeftMouseDown = 1, + LeftMouseUp = 2, + RightMouseDown = 3, + RightMouseUp = 4, + MouseMoved = 5, + LeftMouseDragged = 6, + RightMouseDragged = 7, + + // Keyboard events. + KeyDown = 10, + KeyUp = 11, + FlagsChanged = 12, + + // Specialized control devices. + ScrollWheel = 22, + TabletPointer = 23, + TabletProximity = 24, + OtherMouseDown = 25, + OtherMouseUp = 26, + OtherMouseDragged = 27, + + // Out of band event types. These are delivered to the event tap callback + // to notify it of unusual conditions that disable the event tap. + TapDisabledByTimeout = 0xFFFFFFFE, + TapDisabledByUserInput = 0xFFFFFFFF, +} + +/// Constants used as keys to access specialized fields in low-level events. +/// +/// [Ref](https://developer.apple.com/documentation/coregraphics/cgeventfield) +pub struct EventField; +impl EventField { + /// Key to access an integer field that contains the mouse button event + /// number. Matching mouse-down and mouse-up events will have the same + /// event number. + pub const MOUSE_EVENT_NUMBER: CGEventField = 0; + + /// Key to access an integer field that contains the mouse button click + /// state. A click state of 1 represents a single click. A click state of + /// 2 represents a double-click. A click state of 3 represents a + /// triple-click. + pub const MOUSE_EVENT_CLICK_STATE: CGEventField = 1; + + /// Key to access a double field that contains the mouse button pressure. + /// The pressure value may range from 0 to 1, with 0 representing the + /// mouse being up. This value is commonly set by tablet pens mimicking a + /// mouse. + pub const MOUSE_EVENT_PRESSURE: CGEventField = 2; + + /// Key to access an integer field that contains the mouse button number. + pub const MOUSE_EVENT_BUTTON_NUMBER: CGEventField = 3; + + /// Key to access an integer field that contains the horizontal mouse + /// delta since the last mouse movement event. + pub const MOUSE_EVENT_DELTA_X: CGEventField = 4; + + /// Key to access an integer field that contains the vertical mouse delta + /// since the last mouse movement event. + pub const MOUSE_EVENT_DELTA_Y: CGEventField = 5; + + /// Key to access an integer field. The value is non-zero if the event + /// should be ignored by the Inkwell subsystem. + pub const MOUSE_EVENT_INSTANT_MOUSER: CGEventField = 6; + + /// Key to access an integer field that encodes the mouse event subtype as + /// a `kCFNumberIntType'. + pub const MOUSE_EVENT_SUB_TYPE: CGEventField = 7; + + /// Key to access an integer field, non-zero when this is an autorepeat of + /// a key-down, and zero otherwise. + pub const KEYBOARD_EVENT_AUTOREPEAT: CGEventField = 8; + + /// Key to access an integer field that contains the virtual keycode of the + /// key-down or key-up event. + pub const KEYBOARD_EVENT_KEYCODE: CGEventField = 9; + + /// Key to access an integer field that contains the keyboard type + /// identifier. + pub const KEYBOARD_EVENT_KEYBOARD_TYPE: CGEventField = 10; + + /// Key to access an integer field that contains scrolling data. This field + /// typically contains the change in vertical position since the last + /// scrolling event from a Mighty Mouse scroller or a single-wheel mouse + /// scroller. + pub const SCROLL_WHEEL_EVENT_DELTA_AXIS_1: CGEventField = 11; + + /// Key to access an integer field that contains scrolling data. This field + /// typically contains the change in horizontal position since the last + /// scrolling event from a Mighty Mouse scroller. + pub const SCROLL_WHEEL_EVENT_DELTA_AXIS_2: CGEventField = 12; + + /// Key to access a field that contains scrolling data. The scrolling data + /// represents a line-based or pixel-based change in vertical position + /// since the last scrolling event from a Mighty Mouse scroller or a + /// single-wheel mouse scroller. The scrolling data uses a fixed-point + /// 16.16 signed integer format. If this key is passed to + /// `CGEventGetDoubleValueField', the fixed-point value is converted to a + /// double value. + pub const SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_1: CGEventField = 93; + + /// Key to access a field that contains scrolling data. The scrolling data + /// represents a line-based or pixel-based change in horizontal position + /// since the last scrolling event from a Mighty Mouse scroller. The + /// scrolling data uses a fixed-point 16.16 signed integer format. If this + /// key is passed to `CGEventGetDoubleValueField', the fixed-point value is + /// converted to a double value. + pub const SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_2: CGEventField = 94; + + /// Key to access an integer field that contains pixel-based scrolling + /// data. The scrolling data represents the change in vertical position + /// since the last scrolling event from a Mighty Mouse scroller or a + /// single-wheel mouse scroller. + pub const SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_1: CGEventField = 96; + + /// Key to access an integer field that contains pixel-based scrolling + /// data. The scrolling data represents the change in horizontal position + /// since the last scrolling event from a Mighty Mouse scroller. + pub const SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_2: CGEventField = 97; + + /// Key to access an integer field that indicates whether the event should + /// be ignored by the Inkwell subsystem. If the value is non-zero, the + /// event should be ignored. + pub const SCROLL_WHEEL_EVENT_INSTANT_MOUSER: CGEventField = 14; + + /// Key to access an integer field that contains the absolute X coordinate + /// in tablet space at full tablet resolution. + pub const TABLET_EVENT_POINT_X: CGEventField = 15; + + /// Key to access an integer field that contains the absolute Y coordinate + /// in tablet space at full tablet resolution. + pub const TABLET_EVENT_POINT_Y: CGEventField = 16; + + /// Key to access an integer field that contains the absolute Z coordinate + /// in tablet space at full tablet resolution. + pub const TABLET_EVENT_POINT_Z: CGEventField = 17; + + /// Key to access an integer field that contains the tablet button state. + /// Bit 0 is the first button, and a set bit represents a closed or pressed + /// button. Up to 16 buttons are supported. + pub const TABLET_EVENT_POINT_BUTTONS: CGEventField = 18; + + /// Key to access a double field that contains the tablet pen pressure. A + /// value of 0.0 represents no pressure, and 1.0 represents maximum + /// pressure. + pub const TABLET_EVENT_POINT_PRESSURE: CGEventField = 19; + + /// Key to access a double field that contains the horizontal tablet pen + /// tilt. A value of 0 represents no tilt, and 1 represents maximum tilt. + pub const TABLET_EVENT_TILT_X: CGEventField = 20; + + /// Key to access a double field that contains the vertical tablet pen + /// tilt. A value of 0 represents no tilt, and 1 represents maximum tilt. + pub const TABLET_EVENT_TILT_Y: CGEventField = 21; + + /// Key to access a double field that contains the tablet pen rotation. + pub const TABLET_EVENT_ROTATION: CGEventField = 22; + + /// Key to access a double field that contains the tangential pressure on + /// the device. A value of 0.0 represents no pressure, and 1.0 represents + /// maximum pressure. + pub const TABLET_EVENT_TANGENTIAL_PRESSURE: CGEventField = 23; + + /// Key to access an integer field that contains the system-assigned unique + /// device ID. + pub const TABLET_EVENT_DEVICE_ID: CGEventField = 24; + + /// Key to access an integer field that contains a vendor-specified value. + pub const TABLET_EVENT_VENDOR_1: CGEventField = 25; + + /// Key to access an integer field that contains a vendor-specified value. + pub const TABLET_EVENT_VENDOR_2: CGEventField = 26; + + /// Key to access an integer field that contains a vendor-specified value. + pub const TABLET_EVENT_VENDOR_3: CGEventField = 27; + + /// Key to access an integer field that contains the vendor-defined ID, + /// typically the USB vendor ID. + pub const TABLET_PROXIMITY_EVENT_VENDOR_ID: CGEventField = 28; + + /// Key to access an integer field that contains the vendor-defined tablet + /// ID, typically the USB product ID. + pub const TABLET_PROXIMITY_EVENT_TABLET_ID: CGEventField = 29; + + /// Key to access an integer field that contains the vendor-defined ID of + /// the pointing device. + pub const TABLET_PROXIMITY_EVENT_POINTER_ID: CGEventField = 30; + + /// Key to access an integer field that contains the system-assigned + /// device ID. + pub const TABLET_PROXIMITY_EVENT_DEVICE_ID: CGEventField = 31; + + /// Key to access an integer field that contains the system-assigned + /// unique tablet ID. + pub const TABLET_PROXIMITY_EVENT_SYSTEM_TABLET_ID: CGEventField = 32; + + /// Key to access an integer field that contains the vendor-assigned + /// pointer type. + pub const TABLET_PROXIMITY_EVENT_VENDOR_POINTER_TYPE: CGEventField = 33; + + /// Key to access an integer field that contains the vendor-defined + /// pointer serial number. + pub const TABLET_PROXIMITY_EVENT_VENDOR_POINTER_SERIAL_NUMBER: CGEventField = 34; + + /// Key to access an integer field that contains the vendor-defined unique + /// ID. + pub const TABLET_PROXIMITY_EVENT_VENDOR_UNIQUE_ID: CGEventField = 35; + + /// Key to access an integer field that contains the device capabilities + /// mask. + pub const TABLET_PROXIMITY_EVENT_CAPABILITY_MASK: CGEventField = 36; + + /// Key to access an integer field that contains the pointer type. + pub const TABLET_PROXIMITY_EVENT_POINTER_TYPE: CGEventField = 37; + + /// Key to access an integer field that indicates whether the pen is in + /// proximity to the tablet. The value is non-zero if the pen is in + /// proximity to the tablet and zero when leaving the tablet. + pub const TABLET_PROXIMITY_EVENT_ENTER_PROXIMITY: CGEventField = 38; + + /// Key to access a field that contains the event target process serial + /// number. The value is a 64-bit value. + pub const EVENT_TARGET_PROCESS_SERIAL_NUMBER: CGEventField = 39; + + /// Key to access a field that contains the event target Unix process ID. + pub const EVENT_TARGET_UNIX_PROCESS_ID: CGEventField = 40; + + /// Key to access a field that contains the event source Unix process ID. + pub const EVENT_SOURCE_UNIX_PROCESS_ID: CGEventField = 41; + + /// Key to access a field that contains the event source user-supplied + /// data, up to 64 bits. + pub const EVENT_SOURCE_USER_DATA: CGEventField = 42; + + /// Key to access a field that contains the event source Unix effective UID. + pub const EVENT_SOURCE_USER_ID: CGEventField = 43; + + /// Key to access a field that contains the event source Unix effective + /// GID. + pub const EVENT_SOURCE_GROUP_ID: CGEventField = 44; + + /// Key to access a field that contains the event source state ID used to + /// create this event. + pub const EVENT_SOURCE_STATE_ID: CGEventField = 45; + + /// Key to access an integer field that indicates whether a scrolling event + /// contains continuous, pixel-based scrolling data. The value is non-zero + /// when the scrolling data is pixel-based and zero when the scrolling data + /// is line-based. + pub const SCROLL_WHEEL_EVENT_IS_CONTINUOUS: CGEventField = 88; + + /// Added in 10.5; made public in 10.7. + pub const MOUSE_EVENT_WINDOW_UNDER_MOUSE_POINTER: CGEventField = 91; + pub const MOUSE_EVENT_WINDOW_UNDER_MOUSE_POINTER_THAT_CAN_HANDLE_THIS_EVENT: CGEventField = 92; +} + +// Constants that specify buttons on a one, two, or three-button mouse. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGMouseButton { + Left, + Right, + Center, +} + +/// Possible tapping points for events. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGEventTapLocation { + HID, + Session, + AnnotatedSession, +} + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGEvent; + fn drop = |p| CFRelease(p as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGEvent; + pub struct CGEventRef; +} + +impl CGEvent { + pub fn type_id() -> CFTypeID { + unsafe { + CGEventGetTypeID() + } + } + + pub fn new(source: CGEventSource) -> Result { + unsafe { + let event_ref = CGEventCreate(source.as_ptr()); + if !event_ref.is_null() { + Ok(Self::from_ptr(event_ref)) + } else { + Err(()) + } + } + } + + pub fn new_keyboard_event( + source: CGEventSource, + keycode: CGKeyCode, + keydown: bool + ) -> Result { + unsafe { + let event_ref = CGEventCreateKeyboardEvent(source.as_ptr(), keycode, keydown); + if !event_ref.is_null() { + Ok(Self::from_ptr(event_ref)) + } else { + Err(()) + } + } + } + + pub fn new_mouse_event( + source: CGEventSource, + mouse_type: CGEventType, + mouse_cursor_position: CGPoint, + mouse_button: CGMouseButton + ) -> Result { + unsafe { + let event_ref = CGEventCreateMouseEvent(source.as_ptr(), mouse_type, + mouse_cursor_position, mouse_button); + if !event_ref.is_null() { + Ok(Self::from_ptr(event_ref)) + } else { + Err(()) + } + } + } + + #[cfg(feature = "highsierra")] + pub fn new_scroll_event( + source: CGEventSource, + units: CGScrollEventUnit, + wheel_count: u32, + wheel1: i32, + wheel2: i32, + wheel3: i32, + ) -> Result { + unsafe { + let event_ref = CGEventCreateScrollWheelEvent2( + source.as_ptr(), + units, + wheel_count, + wheel1, + wheel2, + wheel3, + ); + if !event_ref.is_null() { + Ok(Self::from_ptr(event_ref)) + } else { + Err(()) + } + } + } + + pub fn post(&self, tap_location: CGEventTapLocation) { + unsafe { + CGEventPost(tap_location, self.as_ptr()); + } + } + + pub fn location(&self) -> CGPoint { + unsafe { + CGEventGetLocation(self.as_ptr()) + } + } + + #[cfg(feature = "elcapitan")] + pub fn post_to_pid(&self, pid: libc::pid_t) { + unsafe { + CGEventPostToPid(pid, self.as_ptr()); + } + } + + pub fn set_flags(&self, flags: CGEventFlags) { + unsafe { + CGEventSetFlags(self.as_ptr(), flags); + } + } + + pub fn get_flags(&self) -> CGEventFlags { + unsafe { + CGEventGetFlags(self.as_ptr()) + } + } + + pub fn set_type(&self, event_type: CGEventType) { + unsafe { + CGEventSetType(self.as_ptr(), event_type); + } + } + + pub fn get_type(&self) -> CGEventType { + unsafe { + CGEventGetType(self.as_ptr()) + } + } + + pub fn set_string_from_utf16_unchecked(&self, buf: &[u16]) { + let buflen = buf.len() as libc::c_ulong; + unsafe { + CGEventKeyboardSetUnicodeString(self.as_ptr(), buflen, buf.as_ptr()); + } + } + + pub fn set_string(&self, string: &str) { + let buf: Vec = string.encode_utf16().collect(); + self.set_string_from_utf16_unchecked(&buf); + } + + pub fn get_integer_value_field(&self, field: CGEventField) -> i64 { + unsafe { CGEventGetIntegerValueField(self.as_ptr(), field) } + } + + pub fn set_integer_value_field(&self, field: CGEventField, value: i64) { + unsafe { CGEventSetIntegerValueField(self.as_ptr(), field, value) } + } + + pub fn get_double_value_field(&self, field: CGEventField) -> f64 { + unsafe { CGEventGetDoubleValueField(self.as_ptr(), field) } + } + + pub fn set_double_value_field(&self, field: CGEventField, value: f64) { + unsafe { CGEventSetDoubleValueField(self.as_ptr(), field, value) } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + /// Return the type identifier for the opaque type `CGEventRef'. + fn CGEventGetTypeID() -> CFTypeID; + + /// Return a new event using the event source `source'. If `source' is NULL, + /// the default source is used. + fn CGEventCreate(source: ::sys::CGEventSourceRef) -> ::sys::CGEventRef; + + /// Return a new keyboard event. + /// + /// The event source may be taken from another event, or may be NULL. Based + /// on the virtual key code values entered, the appropriate key down, key up, + /// or flags changed events are generated. + /// + /// All keystrokes needed to generate a character must be entered, including + /// SHIFT, CONTROL, OPTION, and COMMAND keys. For example, to produce a 'Z', + /// the SHIFT key must be down, the 'z' key must go down, and then the SHIFT + /// and 'z' key must be released: + fn CGEventCreateKeyboardEvent(source: ::sys::CGEventSourceRef, keycode: CGKeyCode, + keydown: bool) -> ::sys::CGEventRef; + + /// Return a new mouse event. + /// + /// The event source may be taken from another event, or may be NULL. + /// `mouseType' should be one of the mouse event types. `mouseCursorPosition' + /// should be the position of the mouse cursor in global coordinates. + /// `mouseButton' should be the button that's changing state; `mouseButton' + /// is ignored unless `mouseType' is one of `kCGEventOtherMouseDown', + /// `kCGEventOtherMouseDragged', or `kCGEventOtherMouseUp'. + /// + /// The current implementation of the event system supports a maximum of + /// thirty-two buttons. Mouse button 0 is the primary button on the mouse. + /// Mouse button 1 is the secondary mouse button (right). Mouse button 2 is + /// the center button, and the remaining buttons are in USB device order. + fn CGEventCreateMouseEvent(source: ::sys::CGEventSourceRef, mouseType: CGEventType, + mouseCursorPosition: CGPoint, mouseButton: CGMouseButton) -> ::sys::CGEventRef; + + /// A non-variadic variant version of CGEventCreateScrollWheelEvent. + /// + /// Returns a new Quartz scrolling event. + /// + /// This function allows you to create a scrolling event and customize the + /// event before posting it to the event system. + #[cfg(feature = "highsierra")] + fn CGEventCreateScrollWheelEvent2( + source: ::sys::CGEventSourceRef, + units: CGScrollEventUnit, + wheelCount: u32, + wheel1: i32, + wheel2: i32, + wheel3: i32, + ) -> ::sys::CGEventRef; + + /// Post an event into the event stream at a specified location. + /// + /// This function posts the specified event immediately before any event taps + /// instantiated for that location, and the event passes through any such + /// taps. + fn CGEventPost(tapLocation: CGEventTapLocation, event: ::sys::CGEventRef); + + #[cfg(feature = "elcapitan")] + /// Post an event to a specified process ID + fn CGEventPostToPid(pid: libc::pid_t, event: ::sys::CGEventRef); + + /// Set the event flags of an event. + fn CGEventSetFlags(event: ::sys::CGEventRef, flags: CGEventFlags); + + /// Return the event flags of an event. + fn CGEventGetFlags(event: ::sys::CGEventRef) -> CGEventFlags; + + /// Return the location of an event in global display coordinates. + /// CGPointZero is returned if event is not a valid ::sys::CGEventRef. + fn CGEventGetLocation(event: ::sys::CGEventRef) -> CGPoint; + + /// Set the event type of an event. + fn CGEventSetType(event: ::sys::CGEventRef, eventType: CGEventType); + + /// Return the event type of an event (left mouse down, for example). + fn CGEventGetType(event: ::sys::CGEventRef) -> CGEventType; + + /// Set the Unicode string associated with a keyboard event. + /// + /// By default, the system translates the virtual key code in a keyboard + /// event into a Unicode string based on the keyboard ID in the event + /// source. This function allows you to manually override this string. + /// Note that application frameworks may ignore the Unicode string in a + /// keyboard event and do their own translation based on the virtual + /// keycode and perceived event state. + fn CGEventKeyboardSetUnicodeString(event: ::sys::CGEventRef, + length: libc::c_ulong, + string: *const u16); + + /// Return the integer value of a field in an event. + fn CGEventGetIntegerValueField(event: ::sys::CGEventRef, field: CGEventField) -> i64; + + /// Set the integer value of a field in an event. + /// + /// Before calling this function, the event type must be set using a typed + /// event creation function such as `CGEventCreateMouseEvent', or by + /// calling `CGEventSetType'. + /// + /// If you are creating a mouse event generated by a tablet, call this + /// function and specify the field `kCGMouseEventSubtype' with a value of + /// `kCGEventMouseSubtypeTabletPoint' or + /// `kCGEventMouseSubtypeTabletProximity' before setting other parameters. + fn CGEventSetIntegerValueField(event: ::sys::CGEventRef, field: CGEventField, value: i64); + + /// Return the floating-point value of a field in an event. + /// + /// In cases where the field value is represented within the event by a fixed + /// point number or an integer, the result is scaled to the appropriate range + /// as part of creating the floating-point representation. + fn CGEventGetDoubleValueField(event: ::sys::CGEventRef, field: CGEventField) -> f64; + + /// Set the floating-point value of a field in an event. + /// + /// Before calling this function, the event type must be set using a typed + /// event creation function such as `CGEventCreateMouseEvent', or by calling + /// `CGEventSetType'. + /// + /// In cases where the field’s value is represented within the event by a + /// fixed point number or integer, the value parameter is scaled as needed + /// and converted to the appropriate type. + fn CGEventSetDoubleValueField(event: ::sys::CGEventRef, field: CGEventField, value: f64); +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/event_source.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/event_source.rs new file mode 100644 index 0000000..ce13f5a --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/event_source.rs @@ -0,0 +1,48 @@ +use core_foundation::base::{CFRelease, CFRetain, CFTypeID}; +use foreign_types::ForeignType; + +/// Possible source states of an event source. +#[repr(C)] +#[derive(Clone, Copy, Debug)] +pub enum CGEventSourceStateID { + Private = -1, + CombinedSessionState = 0, + HIDSystemState = 1, +} + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGEventSource; + fn drop = |p| CFRelease(p as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGEventSource; + pub struct CGEventSourceRef; +} + +impl CGEventSource { + pub fn type_id() -> CFTypeID { + unsafe { + CGEventSourceGetTypeID() + } + } + + pub fn new(state_id: CGEventSourceStateID) -> Result { + unsafe { + let event_source_ref = CGEventSourceCreate(state_id); + if !event_source_ref.is_null() { + Ok(Self::from_ptr(event_source_ref)) + } else { + Err(()) + } + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + /// Return the type identifier for the opaque type `CGEventSourceRef'. + fn CGEventSourceGetTypeID() -> CFTypeID; + + /// Return a Quartz event source created with a specified source state. + fn CGEventSourceCreate(stateID: CGEventSourceStateID) -> ::sys::CGEventSourceRef; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/font.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/font.rs new file mode 100644 index 0000000..0309520 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/font.rs @@ -0,0 +1,156 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core_foundation::base::{CFRelease, CFRetain, CFTypeID, TCFType}; +use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::data::{CFData, CFDataRef}; +use core_foundation::number::CFNumber; +use core_foundation::string::{CFString, CFStringRef}; +use core_foundation::dictionary::{CFDictionary, CFDictionaryRef}; +use data_provider::CGDataProvider; +use geometry::CGRect; + +use foreign_types::ForeignType; + +use libc::{self, c_int, size_t}; + +pub type CGGlyph = libc::c_ushort; + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGFont; + fn drop = |p| CFRelease(p as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGFont; + pub struct CGFontRef; +} + +unsafe impl Send for CGFont {} +unsafe impl Sync for CGFont {} + +impl CGFont { + pub fn type_id() -> CFTypeID { + unsafe { + CGFontGetTypeID() + } + } + + pub fn from_data_provider(provider: CGDataProvider) -> Result { + unsafe { + let font_ref = CGFontCreateWithDataProvider(provider.as_ptr()); + if !font_ref.is_null() { + Ok(CGFont::from_ptr(font_ref)) + } else { + Err(()) + } + } + } + + pub fn from_name(name: &CFString) -> Result { + unsafe { + let font_ref = CGFontCreateWithFontName(name.as_concrete_TypeRef()); + if !font_ref.is_null() { + Ok(CGFont::from_ptr(font_ref)) + } else { + Err(()) + } + } + } + + pub fn create_copy_from_variations(&self, vars: &CFDictionary) -> Result { + unsafe { + let font_ref = CGFontCreateCopyWithVariations(self.as_ptr(), + vars.as_concrete_TypeRef()); + if !font_ref.is_null() { + Ok(CGFont::from_ptr(font_ref)) + } else { + Err(()) + } + } + } + + pub fn postscript_name(&self) -> CFString { + unsafe { + let string_ref = CGFontCopyPostScriptName(self.as_ptr()); + TCFType::wrap_under_create_rule(string_ref) + } + } + + pub fn get_glyph_b_boxes(&self, glyphs: &[CGGlyph], bboxes: &mut [CGRect]) -> bool { + unsafe { + assert!(bboxes.len() >= glyphs.len()); + CGFontGetGlyphBBoxes(self.as_ptr(), + glyphs.as_ptr(), + glyphs.len(), + bboxes.as_mut_ptr()) + } + } + + pub fn get_glyph_advances(&self, glyphs: &[CGGlyph], advances: &mut [c_int]) -> bool { + unsafe { + assert!(advances.len() >= glyphs.len()); + CGFontGetGlyphAdvances(self.as_ptr(), + glyphs.as_ptr(), + glyphs.len(), + advances.as_mut_ptr()) + } + } + + pub fn get_units_per_em(&self) -> c_int { + unsafe { + CGFontGetUnitsPerEm(self.as_ptr()) + } + } + + pub fn copy_table_tags(&self) -> CFArray { + unsafe { + TCFType::wrap_under_create_rule(CGFontCopyTableTags(self.as_ptr())) + } + } + + pub fn copy_table_for_tag(&self, tag: u32) -> Option { + let data_ref = unsafe { CGFontCopyTableForTag(self.as_ptr(), tag) }; + if !data_ref.is_null() { + Some(unsafe { TCFType::wrap_under_create_rule(data_ref) }) + } else { + None + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + // TODO: basically nothing has bindings (even commented-out) besides what we use. + fn CGFontCreateWithDataProvider(provider: ::sys::CGDataProviderRef) -> ::sys::CGFontRef; + fn CGFontCreateWithFontName(name: CFStringRef) -> ::sys::CGFontRef; + fn CGFontCreateCopyWithVariations(font: ::sys::CGFontRef, vars: CFDictionaryRef) -> ::sys::CGFontRef; + fn CGFontGetTypeID() -> CFTypeID; + + fn CGFontCopyPostScriptName(font: ::sys::CGFontRef) -> CFStringRef; + + // These do the same thing as CFRetain/CFRelease, except + // gracefully handle a NULL argument. We don't use them. + //fn CGFontRetain(font: ::sys::CGFontRef); + //fn CGFontRelease(font: ::sys::CGFontRef); + + fn CGFontGetGlyphBBoxes(font: ::sys::CGFontRef, + glyphs: *const CGGlyph, + count: size_t, + bboxes: *mut CGRect) + -> bool; + fn CGFontGetGlyphAdvances(font: ::sys::CGFontRef, + glyphs: *const CGGlyph, + count: size_t, + advances: *mut c_int) + -> bool; + fn CGFontGetUnitsPerEm(font: ::sys::CGFontRef) -> c_int; + + fn CGFontCopyTableTags(font: ::sys::CGFontRef) -> CFArrayRef; + fn CGFontCopyTableForTag(font: ::sys::CGFontRef, tag: u32) -> CFDataRef; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/geometry.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/geometry.rs new file mode 100644 index 0000000..c3a7bda --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/geometry.rs @@ -0,0 +1,216 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use base::CGFloat; +use core_foundation::base::TCFType; +use core_foundation::dictionary::CFDictionary; + +pub const CG_ZERO_POINT: CGPoint = CGPoint { + x: 0.0, + y: 0.0, +}; + +pub const CG_ZERO_SIZE: CGSize = CGSize { + width: 0.0, + height: 0.0, +}; + +pub const CG_ZERO_RECT: CGRect = CGRect { + origin: CG_ZERO_POINT, + size: CG_ZERO_SIZE, +}; + +pub const CG_AFFINE_TRANSFORM_IDENTITY: CGAffineTransform = CGAffineTransform { + a: 1.0, b: 0.0, + c: 0.0, d: 1.0, + tx: 0.0, ty: 0.0, +}; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CGSize { + pub width: CGFloat, + pub height: CGFloat, +} + +impl CGSize { + #[inline] + pub fn new(width: CGFloat, height: CGFloat) -> CGSize { + CGSize { + width: width, + height: height, + } + } + + #[inline] + pub fn apply_transform(&self, t: &CGAffineTransform) -> CGSize { + unsafe { + ffi::CGSizeApplyAffineTransform(*self, *t) + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CGPoint { + pub x: CGFloat, + pub y: CGFloat, +} + +impl CGPoint { + #[inline] + pub fn new(x: CGFloat, y: CGFloat) -> CGPoint { + CGPoint { + x: x, + y: y, + } + } + + #[inline] + pub fn apply_transform(&self, t: &CGAffineTransform) -> CGPoint { + unsafe { + ffi::CGPointApplyAffineTransform(*self, *t) + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct CGRect { + pub origin: CGPoint, + pub size: CGSize +} + +impl CGRect { + #[inline] + pub fn new(origin: &CGPoint, size: &CGSize) -> CGRect { + CGRect { + origin: *origin, + size: *size, + } + } + + #[inline] + pub fn inset(&self, size: &CGSize) -> CGRect { + unsafe { + ffi::CGRectInset(*self, size.width, size.height) + } + } + + #[inline] + pub fn from_dict_representation(dict: &CFDictionary) -> Option { + let mut rect = CGRect::new(&CGPoint::new(0., 0.), &CGSize::new(0., 0.)); + let result = unsafe { + ffi::CGRectMakeWithDictionaryRepresentation(dict.as_concrete_TypeRef(), &mut rect) + }; + if result == 0 { + None + } else { + Some(rect) + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + unsafe { + // I use one, as it seems that `YES` is not available from this crate. + ffi::CGRectIsEmpty(*self) == 1 + } + } + + #[inline] + pub fn is_intersects(&self, other: &CGRect) -> bool { + unsafe { + // I use one, as it seems that `YES` is not available from this crate. + ffi::CGRectIntersectsRect(*self, *other) == 1 + } + } + + #[inline] + pub fn apply_transform(&self, t: &CGAffineTransform) -> CGRect { + unsafe { + ffi::CGRectApplyAffineTransform(*self, *t) + } + } +} + +impl PartialEq for CGRect { + #[inline] + fn eq(&self, other: &CGRect) -> bool { + unsafe { + ffi::CGRectEqualToRect(*self, *other) != 0 + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct CGAffineTransform { + pub a: CGFloat, + pub b: CGFloat, + pub c: CGFloat, + pub d: CGFloat, + pub tx: CGFloat, + pub ty: CGFloat, +} + +impl CGAffineTransform { + #[inline] + pub fn new( + a: CGFloat, + b: CGFloat, + c: CGFloat, + d: CGFloat, + tx: CGFloat, + ty: CGFloat, + ) -> CGAffineTransform { + CGAffineTransform { a, b, c, d, tx, ty } + } + + #[inline] + pub fn invert(&self) -> CGAffineTransform { + unsafe { + ffi::CGAffineTransformInvert(*self) + } + } +} + +impl PartialEq for CGAffineTransform { + #[inline] + fn eq(&self, other: &CGAffineTransform) -> bool { + unsafe { + ffi::CGAffineTransformEqualToTransform(*self, *other) != 0 + } + } +} + +mod ffi { + use base::{CGFloat, boolean_t}; + use geometry::{CGAffineTransform, CGPoint, CGRect, CGSize}; + use core_foundation::dictionary::CFDictionaryRef; + + #[link(name = "CoreGraphics", kind = "framework")] + extern { + pub fn CGRectInset(rect: CGRect, dx: CGFloat, dy: CGFloat) -> CGRect; + pub fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef, + rect: *mut CGRect) -> boolean_t; + pub fn CGRectIsEmpty(rect: CGRect) -> boolean_t; + pub fn CGRectIntersectsRect(rect1: CGRect, rect2: CGRect) -> boolean_t; + pub fn CGRectEqualToRect(rect1: CGRect, rect2: CGRect) -> boolean_t; + + pub fn CGAffineTransformInvert(t: CGAffineTransform) -> CGAffineTransform; + pub fn CGAffineTransformEqualToTransform(t1: CGAffineTransform, + t2: CGAffineTransform) -> boolean_t; + + pub fn CGPointApplyAffineTransform(point: CGPoint, t: CGAffineTransform) -> CGPoint; + pub fn CGRectApplyAffineTransform(rect: CGRect, t: CGAffineTransform) -> CGRect; + pub fn CGSizeApplyAffineTransform(size: CGSize, t: CGAffineTransform) -> CGSize; + } +} + diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/image.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/image.rs new file mode 100644 index 0000000..84945e8 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/image.rs @@ -0,0 +1,165 @@ +use std::ptr; + +use base::CGFloat; +use core_foundation::base::{CFRetain, CFTypeID}; +use core_foundation::data::CFData; +use color_space::CGColorSpace; +use data_provider::{CGDataProviderRef, CGDataProvider}; +use geometry::CGRect; +use libc::size_t; +use foreign_types::{ForeignType, ForeignTypeRef}; + +#[repr(C)] +pub enum CGImageAlphaInfo { + CGImageAlphaNone, /* For example, RGB. */ + CGImageAlphaPremultipliedLast, /* For example, premultiplied RGBA */ + CGImageAlphaPremultipliedFirst, /* For example, premultiplied ARGB */ + CGImageAlphaLast, /* For example, non-premultiplied RGBA */ + CGImageAlphaFirst, /* For example, non-premultiplied ARGB */ + CGImageAlphaNoneSkipLast, /* For example, RBGX. */ + CGImageAlphaNoneSkipFirst, /* For example, XRBG. */ + CGImageAlphaOnly /* No color data, alpha data only */ +} + +#[repr(C)] +pub enum CGImageByteOrderInfo { + CGImageByteOrderMask = 0x7000, + CGImageByteOrder16Little = (1 << 12), + CGImageByteOrder32Little = (2 << 12), + CGImageByteOrder16Big = (3 << 12), + CGImageByteOrder32Big = (4 << 12) +} + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGImage; + fn drop = CGImageRelease; + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGImage; + pub struct CGImageRef; +} + +impl CGImage { + pub fn new(width: size_t, + height: size_t, + bits_per_component: size_t, + bits_per_pixel: size_t, + bytes_per_row: size_t, + colorspace: &CGColorSpace, + bitmap_info: u32, + provider: &CGDataProvider, + should_interpolate: bool, + rendering_intent: u32) + -> Self { + unsafe { + let result = CGImageCreate(width, + height, + bits_per_component, + bits_per_pixel, + bytes_per_row, + colorspace.as_ptr(), + bitmap_info, + provider.as_ptr(), + ptr::null_mut(), + should_interpolate, + rendering_intent); + assert!(!result.is_null()); + Self::from_ptr(result) + } + } + + pub fn type_id() -> CFTypeID { + unsafe { + CGImageGetTypeID() + } + } +} + +impl CGImageRef { + pub fn width(&self) -> size_t { + unsafe { + CGImageGetWidth(self.as_ptr()) + } + } + + pub fn height(&self) -> size_t { + unsafe { + CGImageGetHeight(self.as_ptr()) + } + } + + pub fn bits_per_component(&self) -> size_t { + unsafe { + CGImageGetBitsPerComponent(self.as_ptr()) + } + } + + pub fn bits_per_pixel(&self) -> size_t { + unsafe { + CGImageGetBitsPerPixel(self.as_ptr()) + } + } + + pub fn bytes_per_row(&self) -> size_t { + unsafe { + CGImageGetBytesPerRow(self.as_ptr()) + } + } + + pub fn color_space(&self) -> CGColorSpace { + unsafe { + let cs = CGImageGetColorSpace(self.as_ptr()); + CFRetain(cs as *mut _); + CGColorSpace::from_ptr(cs) + } + } + + /// Returns the raw image bytes wrapped in `CFData`. Note, the returned `CFData` owns the + /// underlying buffer. + pub fn data(&self) -> CFData { + let data_provider = unsafe { + CGDataProviderRef::from_ptr(CGImageGetDataProvider(self.as_ptr())) + }; + data_provider.copy_data() + } + + /// Returns a cropped image. If the `rect` specifies a rectangle which lies outside of the + /// image bounds, the `None` is returned. + pub fn cropped(&self, rect: CGRect) -> Option { + let image_ptr = unsafe { CGImageCreateWithImageInRect(self.as_ptr(), rect) }; + if !image_ptr.is_null() { + Some(unsafe { CGImage::from_ptr(image_ptr) }) + } else { + None + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + fn CGImageGetTypeID() -> CFTypeID; + fn CGImageGetWidth(image: ::sys::CGImageRef) -> size_t; + fn CGImageGetHeight(image: ::sys::CGImageRef) -> size_t; + fn CGImageGetBitsPerComponent(image: ::sys::CGImageRef) -> size_t; + fn CGImageGetBitsPerPixel(image: ::sys::CGImageRef) -> size_t; + fn CGImageGetBytesPerRow(image: ::sys::CGImageRef) -> size_t; + fn CGImageGetColorSpace(image: ::sys::CGImageRef) -> ::sys::CGColorSpaceRef; + fn CGImageGetDataProvider(image: ::sys::CGImageRef) -> ::sys::CGDataProviderRef; + fn CGImageRelease(image: ::sys::CGImageRef); + fn CGImageCreate(width: size_t, + height: size_t, + bitsPerComponent: size_t, + bitsPerPixel: size_t, + bytesPerRow: size_t, + space: ::sys::CGColorSpaceRef, + bitmapInfo: u32, + provider: ::sys::CGDataProviderRef, + decode: *const CGFloat, + shouldInterpolate: bool, + intent: u32) + -> ::sys::CGImageRef; + fn CGImageCreateWithImageInRect(image: ::sys::CGImageRef, rect: CGRect) -> ::sys::CGImageRef; + + //fn CGImageGetAlphaInfo(image: ::sys::CGImageRef) -> CGImageAlphaInfo; + //fn CGImageCreateCopyWithColorSpace(image: ::sys::CGImageRef, space: ::sys::CGColorSpaceRef) -> ::sys::CGImageRef +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/lib.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/lib.rs new file mode 100644 index 0000000..981883c --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/lib.rs @@ -0,0 +1,41 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate libc; + +#[macro_use] +extern crate core_foundation; + +#[macro_use] +#[cfg(target_os = "macos")] +extern crate bitflags; + +#[macro_use] +extern crate foreign_types; + +pub mod base; +pub mod color; +pub mod color_space; +pub mod context; +pub mod data_provider; +#[cfg(target_os = "macos")] +pub mod display; +#[cfg(target_os = "macos")] +pub mod event; +#[cfg(target_os = "macos")] +pub mod event_source; +pub mod font; +pub mod geometry; +#[cfg(target_os = "macos")] +pub mod window; +#[cfg(target_os = "macos")] +pub mod private; +pub mod image; +pub mod path; +mod sys; diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/path.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/path.rs new file mode 100644 index 0000000..dc1c804 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/path.rs @@ -0,0 +1,129 @@ +// Copyright 2017 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use sys::CGPathRef as SysCGPathRef; + +use core_foundation::base::{CFRelease, CFRetain, CFTypeID}; +use foreign_types::ForeignType; +use geometry::{CGAffineTransform, CGPoint, CGRect}; +use libc::c_void; +use std::fmt::{self, Debug, Formatter}; +use std::marker::PhantomData; +use std::ops::Deref; +use std::ptr; +use std::slice; + +foreign_type! { + #[doc(hidden)] + type CType = ::sys::CGPath; + fn drop = |p| CFRelease(p as *mut _); + fn clone = |p| CFRetain(p as *const _) as *mut _; + pub struct CGPath; + pub struct CGPathRef; +} + +impl CGPath { + pub fn from_rect(rect: CGRect, transform: Option<&CGAffineTransform>) -> CGPath { + unsafe { + let transform = match transform { + None => ptr::null(), + Some(transform) => transform as *const CGAffineTransform, + }; + CGPath(CGPathCreateWithRect(rect, transform)) + } + } + + pub fn type_id() -> CFTypeID { + unsafe { + CGPathGetTypeID() + } + } + + pub fn apply<'a, F>(&'a self, mut closure: &'a F) where F: FnMut(CGPathElementRef<'a>) { + unsafe { + CGPathApply(self.as_ptr(), &mut closure as *mut _ as *mut c_void, do_apply::); + } + + unsafe extern "C" fn do_apply<'a, F>(info: *mut c_void, element: *const CGPathElement) + where F: FnMut(CGPathElementRef<'a>) { + let closure = info as *mut *mut F; + (**closure)(CGPathElementRef::new(element)) + } + } +} + +#[repr(i32)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum CGPathElementType { + MoveToPoint = 0, + AddLineToPoint = 1, + AddQuadCurveToPoint = 2, + AddCurveToPoint = 3, + CloseSubpath = 4, +} + +pub struct CGPathElementRef<'a> { + element: *const CGPathElement, + phantom: PhantomData<&'a CGPathElement>, +} + +impl<'a> CGPathElementRef<'a> { + fn new<'b>(element: *const CGPathElement) -> CGPathElementRef<'b> { + CGPathElementRef { + element: element, + phantom: PhantomData, + } + } +} + +impl<'a> Deref for CGPathElementRef<'a> { + type Target = CGPathElement; + fn deref(&self) -> &CGPathElement { + unsafe { + &*self.element + } + } +} + +#[repr(C)] +pub struct CGPathElement { + pub element_type: CGPathElementType, + points: *mut CGPoint, +} + +impl Debug for CGPathElement { + fn fmt(&self, formatter: &mut Formatter) -> Result<(), fmt::Error> { + write!(formatter, "{:?}: {:?}", self.element_type, self.points()) + } +} + +impl CGPathElement { + pub fn points(&self) -> &[CGPoint] { + unsafe { + match self.element_type { + CGPathElementType::CloseSubpath => &[], + CGPathElementType::MoveToPoint | CGPathElementType::AddLineToPoint => { + slice::from_raw_parts(self.points, 1) + } + CGPathElementType::AddQuadCurveToPoint => slice::from_raw_parts(self.points, 2), + CGPathElementType::AddCurveToPoint => slice::from_raw_parts(self.points, 3), + } + } + } +} + +type CGPathApplierFunction = unsafe extern "C" fn(info: *mut c_void, + element: *const CGPathElement); + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + fn CGPathCreateWithRect(rect: CGRect, transform: *const CGAffineTransform) -> ::sys::CGPathRef; + fn CGPathApply(path: ::sys::CGPathRef, info: *mut c_void, function: CGPathApplierFunction); + fn CGPathGetTypeID() -> CFTypeID; +} diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/private.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/private.rs new file mode 100644 index 0000000..0bc193b --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/private.rs @@ -0,0 +1,116 @@ +// Copyright 2016 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Evil private APIs. +//! +//! These are liable to change at any time. Use with caution! + +use geometry::CGRect; +use libc::{c_int, c_uint}; +use std::ptr; + +pub struct CGSRegion { + region: ffi::CGSRegionRef, +} + +impl Drop for CGSRegion { + fn drop(&mut self) { + unsafe { + ffi::CGSRegionRelease(self.region) + } + } +} + +impl CGSRegion { + #[inline] + pub fn from_rect(rect: &CGRect) -> CGSRegion { + unsafe { + let mut region = ptr::null_mut(); + assert!(ffi::CGSNewRegionWithRect(rect, &mut region) == 0); + CGSRegion { + region: region, + } + } + } + + #[inline] + pub fn from_rects(rects: &[CGRect]) -> CGSRegion { + unsafe { + let mut region = ptr::null_mut(); + assert!(ffi::CGSNewRegionWithRectList(rects.as_ptr(), + rects.len() as c_uint, + &mut region) == 0); + CGSRegion { + region: region, + } + } + } +} + +/// This should always be memory-safe; the window server rejects any invalid surface IDs. +pub struct CGSSurface { + context_id: c_uint, + window_number: c_int, + surface_id: c_uint, +} + +impl CGSSurface { + #[inline] + pub fn from_ids(context_id: c_uint, window_number: c_int, surface_id: c_uint) -> CGSSurface { + CGSSurface { + context_id: context_id, + window_number: window_number, + surface_id: surface_id, + } + } + + #[inline] + pub fn id(&self) -> c_uint { + self.surface_id + } + + #[inline] + pub fn set_shape(&self, region: &CGSRegion) { + unsafe { + assert!(ffi::CGSSetSurfaceShape(self.context_id, + self.window_number, + self.surface_id, + region.region) == 0) + } + } +} + +mod ffi { + use geometry::CGRect; + use libc::{c_int, c_uint}; + + // This is an enum so that we can't easily make instances of this opaque type. + pub enum CGSRegionObject {} + + pub type CGError = OSStatus; + pub type CGSRegionRef = *mut CGSRegionObject; + pub type OSStatus = i32; + + #[link(name = "CoreGraphics", kind = "framework")] + extern { + pub fn CGSRegionRelease(region: CGSRegionRef); + pub fn CGSNewRegionWithRect(rect: *const CGRect, outRegion: *mut CGSRegionRef) -> CGError; + pub fn CGSNewRegionWithRectList(rects: *const CGRect, + rectCount: c_uint, + outRegion: *mut CGSRegionRef) + -> CGError; + + pub fn CGSSetSurfaceShape(contextID: c_uint, + windowNumber: c_int, + surfaceID: c_uint, + region: CGSRegionRef) + -> CGError; + } +} + diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/sys.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/sys.rs new file mode 100644 index 0000000..ccf0625 --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/sys.rs @@ -0,0 +1,39 @@ +use std::os::raw::c_void; + +pub enum CGImage {} +pub type CGImageRef = *mut CGImage; + +#[repr(C)] +pub struct __CGColor(c_void); + +pub type CGColorRef = *const __CGColor; + +pub enum CGColorSpace {} +pub type CGColorSpaceRef = *mut CGColorSpace; + +pub enum CGPath {} +pub type CGPathRef = *mut CGPath; + +pub enum CGDataProvider {} +pub type CGDataProviderRef = *mut CGDataProvider; + +pub enum CGFont {} +pub type CGFontRef = *mut CGFont; + +pub enum CGContext {} +pub type CGContextRef = *mut CGContext; + +#[cfg(target_os = "macos")] +mod macos { + pub enum CGEvent {} + pub type CGEventRef = *mut CGEvent; + + pub enum CGEventSource {} + pub type CGEventSourceRef = *mut CGEventSource; + + pub enum CGDisplayMode {} + pub type CGDisplayModeRef = *mut CGDisplayMode; +} + +#[cfg(target_os = "macos")] +pub use self::macos::*; diff --git a/third_party/cargo/vendor/core-graphics-0.19.0/src/window.rs b/third_party/cargo/vendor/core-graphics-0.19.0/src/window.rs new file mode 100644 index 0000000..aa7293f --- /dev/null +++ b/third_party/cargo/vendor/core-graphics-0.19.0/src/window.rs @@ -0,0 +1,149 @@ +// Copyright 2018 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +use core_foundation::array::{CFArray, CFArrayRef}; +use core_foundation::base::{CFType, TCFType}; +use core_foundation::dictionary::CFDictionary; +use core_foundation::string::{CFString, CFStringRef}; +use foreign_types::ForeignType; + +use geometry::CGRect; +use image::CGImage; +use sys; + +pub type CGWindowID = u32; + +pub type CGWindowSharingType = u32; +pub const kCGWindowSharingNone: CGWindowSharingType = 0; +pub const kCGWindowSharingReadOnly: CGWindowSharingType = 1; +pub const kCGWindowSharingReadWrite: CGWindowSharingType = 1; + +pub type CGWindowBackingType = u32; +pub const kCGWindowBackingStoreRetained: CGWindowBackingType = 0; +pub const kCGWindowBackingStoreNonretained: CGWindowBackingType = 1; +pub const kCGWindowBackingStoreBuffered: CGWindowBackingType = 2; + +pub type CGWindowListOption = u32; +pub const kCGWindowListOptionAll: CGWindowListOption = 1 << 0; +pub const kCGWindowListOptionOnScreenOnly: CGWindowListOption = 1 << 1; +pub const kCGWindowListOptionOnScreenAboveWindow: CGWindowListOption = 1 << 2; +pub const kCGWindowListOptionOnScreenBelowWindow: CGWindowListOption = 1 << 3; +pub const kCGWindowListOptionIncludingWindow: CGWindowListOption = 1 << 4; +pub const kCGWindowListOptionExcludeDesktopElements: CGWindowListOption = 1 << 5; + +pub type CGWindowImageOption = u32; +pub const kCGWindowImageDefault: CGWindowImageOption = 0; +pub const kCGWindowImageBoundsIgnoreFraming: CGWindowImageOption = 1 << 0; +pub const kCGWindowImageShouldBeOpaque: CGWindowImageOption = 1 << 1; +pub const kCGWindowImageOnlyShadows: CGWindowImageOption = 1 << 2; +pub const kCGWindowImageBestResolution: CGWindowImageOption = 1 << 3; +pub const kCGWindowImageNominalResolution: CGWindowImageOption = 1 << 4; + +pub const kCGNullWindowID: CGWindowID = 0; + +pub fn copy_window_info(option: CGWindowListOption, relative_to_window: CGWindowID) + -> Option { + unsafe { + let array = CGWindowListCopyWindowInfo(option, relative_to_window); + if array.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(array)) + } + } +} + +pub fn create_window_list(option: CGWindowListOption, relative_to_window: CGWindowID) + -> Option> { + unsafe { + let array = CGWindowListCreate(option, relative_to_window); + if array.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(array)) + } + } +} + +pub fn create_description_from_array(window_array: CFArray) -> + Option>> { + unsafe { + let array = CGWindowListCreateDescriptionFromArray(window_array.as_concrete_TypeRef()); + if array.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(array)) + } + } +} + +pub fn create_image(screen_bounds: CGRect, + list_option: CGWindowListOption, + window_id: CGWindowID, + image_option: CGWindowImageOption) + -> Option { + unsafe { + let image = CGWindowListCreateImage(screen_bounds, list_option, window_id, image_option); + if image.is_null() { + None + } else { + Some(CGImage::from_ptr(image)) + } + } +} + +pub fn create_image_from_array(screen_bounds: CGRect, + window_array: CFArray, + image_option: CGWindowImageOption) + -> Option { + unsafe { + let image = CGWindowListCreateImageFromArray(screen_bounds, + window_array.as_concrete_TypeRef(), + image_option); + if image.is_null() { + None + } else { + Some(CGImage::from_ptr(image)) + } + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern { + pub static kCGWindowNumber: CFStringRef; + pub static kCGWindowStoreType: CFStringRef; + pub static kCGWindowLayer: CFStringRef; + pub static kCGWindowBounds: CFStringRef; + pub static kCGWindowSharingState: CFStringRef; + pub static kCGWindowAlpha: CFStringRef; + pub static kCGWindowOwnerPID: CFStringRef; + pub static kCGWindowMemoryUsage: CFStringRef; + pub static kCGWindowWorkspace: CFStringRef; + pub static kCGWindowOwnerName: CFStringRef; + pub static kCGWindowName: CFStringRef; + pub static kCGWindowIsOnscreen: CFStringRef; + pub static kCGWindowBackingLocationVideoMemory: CFStringRef; + + pub fn CGWindowListCopyWindowInfo(option: CGWindowListOption, relativeToWindow: CGWindowID) + -> CFArrayRef; + pub fn CGWindowListCreate(option: CGWindowListOption, relativeToWindow: CGWindowID) + -> CFArrayRef; + pub fn CGWindowListCreateDescriptionFromArray(windowArray: CFArrayRef) -> CFArrayRef; + pub fn CGWindowListCreateImage(screenBounds: CGRect, + listOption: CGWindowListOption, + windowID: CGWindowID, + imageOption: CGWindowImageOption) + -> *mut sys::CGImage; + pub fn CGWindowListCreateImageFromArray(screenBounds: CGRect, + windowArray: CFArrayRef, + imageOption: CGWindowImageOption) + -> *mut sys::CGImage; +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/.cargo-checksum.json b/third_party/cargo/vendor/core-video-sys-0.1.3/.cargo-checksum.json new file mode 100644 index 0000000..f8db7d3 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b90dee90d0900e4e1b38b183cf1c7dba49a4cd3be5e86c8da7a25745b2520c45","LICENSE":"439952354cd78da9e99d020667b01c011e89dfa57e8e091fe6e099bd7804d86b","build.rs":"d5ce402947ab6c65bd131c19def4fc1e0007d95630432988787b6dc8e4124ee6","src/base.rs":"8fb57ef931405a2effc82b09087ba54ee0224420252e0e77e5d23ded87c71d41","src/buffer.rs":"c15f89522f11c9a5fbc27cc80b36dc4a614294ede18a3048320ed0d17b08c410","src/display_link.rs":"87863c61a85dec42cb0a72f7ab33d4f37a7be6b2aee072b7982a72feb957291c","src/host_time.rs":"11ac7e6ec65c6499e620c28e167f40a60d7787c988bd42f6f89f5be1bc2203fe","src/image_buffer.rs":"aecc238c57cea8d67db2c9507d30ee425124a4bfc3adbf7770a9abb5d10a25c0","src/lib.rs":"1fac840e83b70489938063ab3e4acfa8eda80dae6c33290c1be7150d3599ec08","src/metal_texture.rs":"1e48454a983253093bb8c8f2a426043456a3ea5c7669d76998bb44ee5df8bbe9","src/metal_texture_cache.rs":"e451ca31cd68d37ff323984306196ae6c6de701e949b8261bd1967849abe90b9","src/open_gl_es_texture.rs":"57e5cddfa0de2fa6a24b166e481c0bf3a7491789f27f7e51b0614474a9dc7c5a","src/open_gl_es_texture_cache.rs":"8d9340cc63a4f0ac6b6ec4d988fdfc14e6ab0ca65f678fd86e004e92d2df712c","src/opengl_buffer.rs":"82145551623ed561c32dc206c7fd5ad57d674b3f5e0ef7753a83e8a57ff8c614","src/opengl_buffer_pool.rs":"3cb6c8c2443a567af7dfdef3b3ddda64a64536d4c46617a49ccbd905f27216db","src/opengl_texture.rs":"8369a59288e3b3a0d79725379034e71bcbfb84c10e08290028067c261e767500","src/opengl_texture_cache.rs":"dab814ba2c9b9b1319d57a2260b8283a973eea23cca941c211ac371c109dfce3","src/pixel_buffer.rs":"dd525165a667b2a28ceee3e488989221f02fdb4f3a8e79ebd72a4d30bf263f15","src/pixel_buffer_io_surface.rs":"c007270f9e6db4bab3ac963135a2ca9d761aa0aa40ab1411177d04e006d3c11d","src/pixel_buffer_pool.rs":"6b36547f222ab36ae01497b541fa6685f6a6b7a6d022923e41c57e524cb6648a","src/pixel_format_description.rs":"a2fbe12c6dfc813a0910ea082f334d9441f6a5fa8accfbcb6621ab61ac863970","src/return_.rs":"1702ae3e29a7439d7caa95b43a30747dbc3535e9479d91097850669d18a8bba8"},"package":"8dc065219542086f72d1e9f7aadbbab0989e980263695d129d502082d063a9d0"} \ No newline at end of file diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/BUILD b/third_party/cargo/vendor/core-video-sys-0.1.3/BUILD similarity index 60% rename from third_party/cargo/vendor/arrayvec-0.4.12/BUILD rename to third_party/cargo/vendor/core-video-sys-0.1.3/BUILD index e50ab68..eb65ef7 100644 --- a/third_party/cargo/vendor/arrayvec-0.4.12/BUILD +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "MIT,Apache-2.0" + "notice", # "MIT" ]) load( @@ -23,26 +23,29 @@ load( ) -# Unsupported target "arraystring" with type "bench" omitted +# Unsupported target "build-script-build" with type "custom-build" omitted rust_library( - name = "arrayvec", + name = "core_video_sys", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/nodrop-0.1.14:nodrop", + "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", + "//third_party/cargo/vendor/core-foundation-sys-0.6.2:core_foundation_sys", + "//third_party/cargo/vendor/core-graphics-0.17.3:core_graphics", + "//third_party/cargo/vendor/libc-0.2.67:libc", + "//third_party/cargo/vendor/objc-0.2.7:objc", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.4.12", + version = "0.1.3", crate_features = [ + "core-graphics", + "display_link", + "opengl", ], ) -# Unsupported target "build-script-build" with type "custom-build" omitted -# Unsupported target "extend" with type "bench" omitted -# Unsupported target "serde" with type "test" omitted -# Unsupported target "tests" with type "test" omitted diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/Cargo.toml b/third_party/cargo/vendor/core-video-sys-0.1.3/Cargo.toml new file mode 100644 index 0000000..3e5fad1 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/Cargo.toml @@ -0,0 +1,51 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "core-video-sys" +version = "0.1.3" +authors = ["luozijun ", "michael.laifx "] +build = "build.rs" +description = "Bindings to CoreVideo.framework for macOS and iOS" +homepage = "https://github.com/luozijun/rust-core-video-sys" +documentation = "https://docs.rs/core-video-sys/*/x86_64-apple-darwin/core-video-sys" +license = "MIT" +repository = "https://github.com/luozijun/rust-core-video-sys" +[dependencies.cfg-if] +version = "0.1" + +[dependencies.core-foundation-sys] +version = "0.6.2" + +[dependencies.core-graphics] +version = "0.17.3" +optional = true + +[dependencies.libc] +version = "0.2.47" + +[dependencies.metal] +version = "0.14.0" +features = ["private"] +optional = true + +[dependencies.objc] +version = "0.2.5" + +[features] +all = ["display_link", "direct3d", "io_suface", "opengl"] +default = ["display_link", "metal"] +direct3d = [] +display_link = ["opengl", "core-graphics"] +io_suface = [] +opengl = [] diff --git a/third_party/cargo/vendor/memoffset-0.2.1/LICENSE b/third_party/cargo/vendor/core-video-sys-0.1.3/LICENSE similarity index 95% rename from third_party/cargo/vendor/memoffset-0.2.1/LICENSE rename to third_party/cargo/vendor/core-video-sys-0.1.3/LICENSE index 61f6081..dbc8417 100644 --- a/third_party/cargo/vendor/memoffset-0.2.1/LICENSE +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/LICENSE @@ -1,4 +1,6 @@ -Copyright (c) 2017 Gilad Naaman +MIT License + +Copyright (c) 2018 寧靜 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -16,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/build.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/build.rs new file mode 100644 index 0000000..ace9da3 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/build.rs @@ -0,0 +1,6 @@ + +fn main() { + if std::env::var("TARGET").unwrap().contains("-apple") { + println!("cargo:rustc-link-lib=framework=CoreVideo"); + } +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/base.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/base.rs new file mode 100644 index 0000000..de659e4 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/base.rs @@ -0,0 +1,83 @@ +use crate::libc::{ c_double, int16_t, int32_t, int64_t, uint32_t, uint64_t, }; + + +// https://developer.apple.com/documentation/corevideo/cvoptionflags?language=objc +pub type CVOptionFlags = uint64_t; +pub type CVSMPTETimeType = uint32_t; +pub type CVSMPTETimeFlags = uint32_t; +pub type CVTimeFlags = int32_t; +pub type CVTimeStampFlags = uint64_t; + + +pub const kCVSMPTETimeType24: CVSMPTETimeType = 0; +pub const kCVSMPTETimeType25: CVSMPTETimeType = 1; +pub const kCVSMPTETimeType30Drop: CVSMPTETimeType = 2; +pub const kCVSMPTETimeType30: CVSMPTETimeType = 3; +pub const kCVSMPTETimeType2997: CVSMPTETimeType = 4; +pub const kCVSMPTETimeType2997Drop: CVSMPTETimeType = 5; +pub const kCVSMPTETimeType60: CVSMPTETimeType = 6; +pub const kCVSMPTETimeType5994: CVSMPTETimeType = 7; + +pub const kCVSMPTETimeValid: CVSMPTETimeFlags = (1 << 0); +pub const kCVSMPTETimeRunning: CVSMPTETimeFlags = (1 << 1); + +pub const kCVTimeIsIndefinite: CVTimeFlags = 1 << 0; + + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CVSMPTETime { + pub subframes: int16_t, + pub subframeDivisor: int16_t, + pub counter: uint32_t, + pub type_: uint32_t, + pub flags: uint32_t, + pub hours: int16_t, + pub minutes: int16_t, + pub seconds: int16_t, + pub frames: int16_t, +} + + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CVTime { + pub timeValue: int64_t, + pub timeScale: int32_t, + pub flags: int32_t +} + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CVTimeStamp { + pub version: uint32_t, + pub videoTimeScale: int32_t, + pub videoTime: int64_t, + pub hostTime: uint64_t, + pub rateScalar: c_double, + pub videoRefreshPeriod: int64_t, + pub smpteTime: CVSMPTETime, + pub flags: uint64_t, + pub reserved: uint64_t, +} + + +pub const kCVTimeStampVideoTimeValid: CVTimeStampFlags = (1 << 0); +pub const kCVTimeStampHostTimeValid: CVTimeStampFlags = (1 << 1); +pub const kCVTimeStampSMPTETimeValid: CVTimeStampFlags = (1 << 2); +pub const kCVTimeStampVideoRefreshPeriodValid: CVTimeStampFlags = (1 << 3); +pub const kCVTimeStampRateScalarValid: CVTimeStampFlags = (1 << 4); + +// There are flags for each field to make it easier to detect interlaced vs progressive output +pub const kCVTimeStampTopField: CVTimeStampFlags = (1 << 16); +pub const kCVTimeStampBottomField: CVTimeStampFlags = (1 << 17); + +// Some commonly used combinations of timestamp flags +pub const kCVTimeStampVideoHostTimeValid: CVTimeStampFlags = (kCVTimeStampVideoTimeValid | kCVTimeStampHostTimeValid); +pub const kCVTimeStampIsInterlaced: CVTimeStampFlags = (kCVTimeStampTopField | kCVTimeStampBottomField); + + +extern "C" { + pub static kCVZeroTime: CVTime; + pub static kCVIndefiniteTime: CVTime; +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/buffer.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/buffer.rs new file mode 100644 index 0000000..ae90ec9 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/buffer.rs @@ -0,0 +1,48 @@ +use crate::libc::{ uint32_t, }; +use crate::core_foundation_sys::{ + base::{ CFTypeRef, }, + string::CFStringRef, + dictionary::CFDictionaryRef, +}; + + + +#[derive(Debug, Copy, Clone)] +pub enum __CVBuffer { } +pub type CVBufferRef = *mut __CVBuffer; + + +pub type CVAttachmentMode = uint32_t; +pub const kCVAttachmentMode_ShouldNotPropagate: CVAttachmentMode = 0; +pub const kCVAttachmentMode_ShouldPropagate: CVAttachmentMode = 1; + + +extern "C" { + pub static kCVBufferPropagatedAttachmentsKey: CFStringRef; + pub static kCVBufferNonPropagatedAttachmentsKey: CFStringRef; + + pub static kCVBufferMovieTimeKey: CFStringRef; + pub static kCVBufferTimeValueKey: CFStringRef; + pub static kCVBufferTimeScaleKey: CFStringRef; + + pub fn CVBufferRetain(buffer: CVBufferRef) -> CVBufferRef; + pub fn CVBufferRelease(buffer: CVBufferRef); + pub fn CVBufferSetAttachment(buffer: CVBufferRef, + key: CFStringRef, + value: CFTypeRef, + attachmentMode: CVAttachmentMode); + pub fn CVBufferGetAttachment(buffer: CVBufferRef, + key: CFStringRef, + attachmentMode: *mut CVAttachmentMode) -> CFTypeRef; + pub fn CVBufferRemoveAttachment(buffer: CVBufferRef, + key: CFStringRef); + pub fn CVBufferRemoveAllAttachments(buffer: CVBufferRef); + pub fn CVBufferGetAttachments(buffer: CVBufferRef, + attachmentMode: CVAttachmentMode) -> CFDictionaryRef; + pub fn CVBufferSetAttachments(buffer: CVBufferRef, + theAttachments: CFDictionaryRef, + attachmentMode: CVAttachmentMode); + pub fn CVBufferPropagateAttachments(sourceBuffer: CVBufferRef, + destinationBuffer: CVBufferRef); + +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/display_link.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/display_link.rs new file mode 100644 index 0000000..b40011c --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/display_link.rs @@ -0,0 +1,16 @@ +use crate::{ + core_foundation_sys::base::CFTypeID, + core_graphics::display::CGDirectDisplayID, + CVReturn, CVTime, +}; + +#[derive(Debug, Copy, Clone)] +pub enum __CVDisplayLink { } +pub type CVDisplayLinkRef = *mut __CVDisplayLink; + +extern "C" { + pub fn CVDisplayLinkGetTypeID() -> CFTypeID; + pub fn CVDisplayLinkCreateWithCGDisplay(displayID: CGDirectDisplayID, displayLinkOut: *mut CVDisplayLinkRef) -> CVReturn; + pub fn CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLink: CVDisplayLinkRef) -> CVTime; + pub fn CVDisplayLinkRelease(displayLink: CVDisplayLinkRef); +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/host_time.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/host_time.rs new file mode 100644 index 0000000..e7ae7a2 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/host_time.rs @@ -0,0 +1,28 @@ +use crate::libc::{ c_double, uint32_t, uint64_t, }; + +extern "C" { + /// @function CVGetCurrentHostTime + /// @abstract Retrieve the current value of the host time base. + /// @discussion On Mac OS X, the host time base for CoreVideo and CoreAudio are identical, and the values returned from either API + /// may be used interchangeably. + /// @result The current host time. + pub fn CVGetCurrentHostTime() -> uint64_t; + /// @function CVGetHostClockFrequency + /// @abstract Retrieve the frequency of the host time base. + /// @discussion On Mac OS X, the host time base for CoreVideo and CoreAudio are identical, and the values returned from either API + /// may be used interchangeably. + /// @result The current host frequency. + pub fn CVGetHostClockFrequency() -> c_double; + /// @function CVGetHostClockMinimumTimeDelta + /// @abstract Retrieve the smallest possible increment in the host time base. + /// @result The smallest valid increment in the host time base. + pub fn CVGetHostClockMinimumTimeDelta() -> uint32_t; +} + + +#[test] +fn test_get_curr_time() { + unsafe { + assert_eq!(CVGetCurrentHostTime() > 0, true); + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/image_buffer.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/image_buffer.rs new file mode 100644 index 0000000..e30b196 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/image_buffer.rs @@ -0,0 +1,3 @@ +use crate::buffer::CVBufferRef; + +pub type CVImageBufferRef = CVBufferRef; diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/lib.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/lib.rs new file mode 100644 index 0000000..36780b5 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/lib.rs @@ -0,0 +1,91 @@ +#![allow( + non_snake_case, + non_camel_case_types, + non_upper_case_globals, + improper_ctypes +)] + +#[macro_use] +extern crate cfg_if; +extern crate libc; +extern crate objc; +extern crate core_foundation_sys; + + +pub(crate) type OSType = u32; +pub(crate) type GLenum = libc::c_uint; +pub(crate) type GLsizei = libc::c_int; +pub(crate) type GLint = libc::c_int; +pub(crate) type GLuint = libc::c_uint; + + +pub mod base; +pub mod buffer; +pub mod return_; +pub mod image_buffer; +pub mod pixel_buffer; +pub mod pixel_buffer_pool; +pub mod pixel_format_description; + +pub use self::base::*; +pub use self::buffer::*; +pub use self::return_::*; +pub use self::image_buffer::*; +pub use self::pixel_buffer::*; +pub use self::pixel_buffer_pool::*; +pub use self::pixel_format_description::*; + +cfg_if! { + if #[cfg(feature = "metal")] { + extern crate metal; + + pub mod metal_texture; + pub mod metal_texture_cache; + + pub use self::metal_texture::*; + pub use self::metal_texture_cache::*; + } +} + +cfg_if! { + if #[cfg(feature = "display_link")] { + extern crate core_graphics; + + pub mod host_time; + pub mod display_link; + + pub use self::host_time::*; + pub use self::display_link::*; + } +} + +cfg_if! { + if #[cfg(feature = "opengl")] { + pub mod opengl_buffer; + pub mod opengl_buffer_pool; + pub mod opengl_texture; + pub mod opengl_texture_cache; + + pub use self::opengl_buffer::*; + pub use self::opengl_buffer_pool::*; + pub use self::opengl_texture::*; + pub use self::opengl_texture_cache::*; + } +} + +cfg_if! { + if #[cfg(feature = "io_suface")] { + pub mod pixel_buffer_io_surface; + + pub use self::pixel_buffer_io_surface::*; + } +} + + +pub mod open_gl_es_texture; +pub mod open_gl_es_texture_cache; + +pub use self::open_gl_es_texture::*; +pub use self::open_gl_es_texture_cache::*; + + diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture.rs new file mode 100644 index 0000000..f9b9408 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture.rs @@ -0,0 +1,27 @@ +use crate::metal::Texture; +use crate::core_foundation_sys::{ + base::{ Boolean, CFTypeID, }, + string::CFStringRef, +}; + +use crate::{ + image_buffer::CVImageBufferRef, +}; + + +pub type CVMetalTextureRef = CVImageBufferRef; + +extern "C" { + pub static kCVMetalTextureUsage: CFStringRef; + + + pub fn CVMetalTextureGetTypeID() -> CFTypeID; + pub fn CVMetalTextureGetTexture(image: CVMetalTextureRef) -> Texture; + pub fn CVMetalTextureIsFlipped(image: CVMetalTextureRef) -> Boolean; + // CV_EXPORT void CVMetalTextureGetCleanTexCoords( CVMetalTextureRef CV_NONNULL image, + // float lowerLeft[2], + // float lowerRight[2], + // float upperRight[2], + // float upperLeft[2] ) API_AVAILABLE(macosx(10.11), ios(8.0), tvos(9.0)) __WATCHOS_PROHIBITED; + +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture_cache.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture_cache.rs new file mode 100644 index 0000000..69b1b7a --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/metal_texture_cache.rs @@ -0,0 +1,42 @@ +use crate::libc::size_t; +use crate::core_foundation_sys::{ + base::{CFAllocatorRef, CFTypeID, CFTypeRef}, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; +use crate::{ + base::CVOptionFlags, + image_buffer::CVImageBufferRef, + metal_texture::CVMetalTextureRef, + return_::CVReturn, +}; + + +pub type CVMetalTextureCacheRef = CFTypeRef; + +extern "C" { + pub static kCVMetalTextureCacheMaximumTextureAgeKey: CFStringRef; + + + pub fn CVMetalTextureCacheGetTypeID() -> CFTypeID; + pub fn CVMetalTextureCacheCreate( + allocator: CFAllocatorRef, + cacheAttributes: CFDictionaryRef, + metalDevice: metal::Device, + textureAttributes: CFDictionaryRef, + cacheOut: *mut CVMetalTextureCacheRef, + ) -> CVReturn; + pub fn CVMetalTextureCacheCreateTextureFromImage( + allocator: CFAllocatorRef, + textureCache: CVMetalTextureCacheRef, + sourceImage: CVImageBufferRef, + textureAttributes: CFDictionaryRef, + pixelFormat: metal::MTLPixelFormat, + width: size_t, + height: size_t, + planeIndex: size_t, + textureOut: *mut CVMetalTextureRef, + ) -> CVReturn; + pub fn CVMetalTextureCacheFlush(textureCache: CVMetalTextureCacheRef, + options: CVOptionFlags); +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture.rs new file mode 100644 index 0000000..1aee72f --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture.rs @@ -0,0 +1,26 @@ +use crate::core_foundation_sys::base::{ Boolean, CFTypeID }; + +use crate::{ + GLenum, GLuint, + image_buffer::CVImageBufferRef, +}; + + +pub type CVOpenGLESTextureRef = CVImageBufferRef; + +extern "C" { + pub fn CVOpenGLESTextureGetTypeID() -> CFTypeID; + + pub fn CVOpenGLESTextureGetTarget(image: CVOpenGLESTextureRef) -> GLenum; + + pub fn CVOpenGLESTextureGetName(image: CVOpenGLESTextureRef) -> GLuint; + + pub fn CVOpenGLESTextureIsFlipped(image: CVOpenGLESTextureRef) -> Boolean; + +//pub fn CVOpenGLESTextureGetCleanTexCoords( image:CVOpenGLESTextureRef , +// GLfloat lowerLeft[ 2], +// GLfloat lowerRight[ 2], +// GLfloat upperRight[ 2], +// GLfloat upperLeft[ 2] ); + +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture_cache.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture_cache.rs new file mode 100644 index 0000000..d7f9518 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/open_gl_es_texture_cache.rs @@ -0,0 +1,42 @@ +use crate::libc::size_t; +use crate::objc::runtime::Object; +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, CFTypeRef }, + dictionary::CFDictionaryRef, +}; + +use crate::{ + GLenum, GLint, GLsizei, + return_::CVReturn, + image_buffer::CVImageBufferRef, + open_gl_es_texture::CVOpenGLESTextureRef, +}; + + +pub type CVOpenGLESTextureCacheRef = CFTypeRef; +pub type CVEAGLContext = *mut Object; + +extern "C" { + pub fn CVOpenGLESTextureCacheCreate( + allocator: CFAllocatorRef, + cacheAttributes: CFDictionaryRef, + eaglContext: CVEAGLContext, + textureAttributes: CFDictionaryRef, + cacheOut: *mut CVOpenGLESTextureCacheRef, + ) -> CVReturn; + + pub fn CVOpenGLESTextureCacheCreateTextureFromImage( + allocator: CFAllocatorRef, + textureCache: CVOpenGLESTextureCacheRef, + sourceImage: CVImageBufferRef, + textureAttributes: CFDictionaryRef, + target: GLenum, + internalFormat: GLint, + width: GLsizei, + height: GLsizei, + format: GLenum, + type_: GLenum, + planeIndex: size_t, + textureOut: *mut CVOpenGLESTextureRef, + ) -> CVReturn; +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer.rs new file mode 100644 index 0000000..8e2caf2 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer.rs @@ -0,0 +1,42 @@ +use crate::libc::{ size_t, }; +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, CFTypeID, }, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; +use crate::{ + GLenum, GLint, + return_::CVReturn, + image_buffer::CVImageBufferRef, +}; + + +pub type CVOpenGLBufferRef = CVImageBufferRef; +// https://developer.apple.com/documentation/appkit/nsopenglcontext/1436158-cglcontextobj?language=objc +pub type CGLContextObj = CVImageBufferRef; +// https://developer.apple.com/documentation/appkit/nsopenglpixelformat/1436148-cglpixelformatobj +pub type CGLPixelFormatObj = CVImageBufferRef; + +extern "C" { + pub static kCVOpenGLBufferWidth: CFStringRef; + pub static kCVOpenGLBufferHeight: CFStringRef; + pub static kCVOpenGLBufferTarget: CFStringRef; + pub static kCVOpenGLBufferInternalFormat: CFStringRef; + pub static kCVOpenGLBufferMaximumMipmapLevel: CFStringRef; + + + pub fn CVOpenGLBufferGetTypeID() -> CFTypeID; + pub fn CVOpenGLBufferRetain(buffer: CVOpenGLBufferRef) -> CVOpenGLBufferRef; + pub fn CVOpenGLBufferRelease(buffer: CVOpenGLBufferRef); + pub fn CVOpenGLBufferCreate(allocator: CFAllocatorRef, + width: size_t, + height: size_t, + attributes: CFDictionaryRef, + bufferOut: *mut CVOpenGLBufferRef) -> CVReturn; + pub fn CVOpenGLBufferGetAttributes(openGLBuffer: CVOpenGLBufferRef) -> CFDictionaryRef; + pub fn CVOpenGLBufferAttach(openGLBuffer: CVOpenGLBufferRef, + cglContext: CGLContextObj, + face: GLenum, + level: GLint, + screen: GLint) -> CVReturn; +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer_pool.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer_pool.rs new file mode 100644 index 0000000..2a0c23c --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_buffer_pool.rs @@ -0,0 +1,32 @@ +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, CFTypeID, }, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; + +use crate::{ + return_::CVReturn, + image_buffer::CVImageBufferRef, + opengl_buffer::{ CVOpenGLBufferRef, }, +}; + + +pub type CVOpenGLBufferPoolRef = CVImageBufferRef; + + +extern "C" { + pub static kCVOpenGLBufferPoolMinimumBufferCountKey: CFStringRef; + pub static kCVOpenGLBufferPoolMaximumBufferAgeKey: CFStringRef; + + pub fn CVOpenGLBufferPoolGetTypeID() -> CFTypeID; + pub fn CVOpenGLBufferPoolRetain(openGLBufferPool: CVOpenGLBufferPoolRef) -> CVOpenGLBufferPoolRef; + pub fn CVOpenGLBufferPoolRelease(openGLBufferPool: CVOpenGLBufferPoolRef); + pub fn CVOpenGLBufferPoolCreate(allocator: CFAllocatorRef, + poolAttributes: CFDictionaryRef, + openGLBufferAttributes: CFDictionaryRef, + poolOut: *mut CVOpenGLBufferPoolRef) -> CVReturn; + pub fn CVOpenGLBufferPoolGetAttributes(pool: CVOpenGLBufferPoolRef) -> CFDictionaryRef; + pub fn CVOpenGLBufferPoolCreateOpenGLBuffer(allocator: CFAllocatorRef, + openGLBufferPool: CVOpenGLBufferPoolRef, + openGLBufferOut: *mut CVOpenGLBufferRef) -> CVReturn; +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture.rs new file mode 100644 index 0000000..ff5a858 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture.rs @@ -0,0 +1,26 @@ +use crate::core_foundation_sys::{ + base::{ Boolean, CFTypeID, }, +}; + +use crate::{ + GLenum, GLuint, + image_buffer::CVImageBufferRef, +}; + + +pub type CVOpenGLTextureRef = CVImageBufferRef; + + +extern "C" { + pub fn CVOpenGLTextureGetTypeID() -> CFTypeID; + pub fn CVOpenGLTextureRetain(texture: CVOpenGLTextureRef) -> CVOpenGLTextureRef; + pub fn CVOpenGLTextureRelease(texture: CVOpenGLTextureRef); + pub fn CVOpenGLTextureGetTarget(image: CVOpenGLTextureRef) -> GLenum; + pub fn CVOpenGLTextureGetName(image: CVOpenGLTextureRef) -> GLuint; + pub fn CVOpenGLTextureIsFlipped(image: CVOpenGLTextureRef) -> Boolean; + // CV_EXPORT void CVOpenGLTextureGetCleanTexCoords( CVOpenGLTextureRef CV_NONNULL image, + // GLfloat lowerLeft[2], + // GLfloat lowerRight[2], + // GLfloat upperRight[2], + // GLfloat upperLeft[2] ) AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER; +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture_cache.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture_cache.rs new file mode 100644 index 0000000..bf3467e --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/opengl_texture_cache.rs @@ -0,0 +1,42 @@ +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, CFTypeID, }, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; + +use crate::{ + base::CVOptionFlags, + return_::CVReturn, + image_buffer::CVImageBufferRef, + opengl_buffer::{ CGLContextObj, CGLPixelFormatObj, }, + opengl_texture::CVOpenGLTextureRef, + +}; + + +pub type CVOpenGLTextureCacheRef = CVImageBufferRef; + + +extern "C" { + pub static kCVOpenGLTextureCacheChromaSamplingModeKey: CFStringRef; + pub static kCVOpenGLTextureCacheChromaSamplingModeAutomatic: CFStringRef; + pub static kCVOpenGLTextureCacheChromaSamplingModeHighestQuality: CFStringRef; + pub static kCVOpenGLTextureCacheChromaSamplingModeBestPerformance: CFStringRef; + + pub fn CVOpenGLTextureCacheGetTypeID() -> CFTypeID; + pub fn CVOpenGLTextureCacheRetain(textureCache: CVOpenGLTextureCacheRef) -> CVOpenGLTextureCacheRef; + pub fn CVOpenGLTextureCacheRelease(textureCache: CVOpenGLTextureCacheRef); + pub fn CVOpenGLTextureCacheCreate(allocator: CFAllocatorRef, + cacheAttributes: CFDictionaryRef, + cglContext: CGLContextObj, + cglPixelFormat: CGLPixelFormatObj, + textureAttributes: CFDictionaryRef, + cacheOut: *mut CVOpenGLTextureCacheRef) -> CVReturn; + pub fn CVOpenGLTextureCacheCreateTextureFromImage(allocator: CFAllocatorRef, + textureCache: CVOpenGLTextureCacheRef, + sourceImage: CVImageBufferRef, + attributes: CFDictionaryRef, + textureOut: *mut CVOpenGLTextureRef) -> CVReturn; + pub fn CVOpenGLTextureCacheFlush(textureCache: CVOpenGLTextureCacheRef, + options: CVOptionFlags); +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer.rs new file mode 100644 index 0000000..d5a0dfc --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer.rs @@ -0,0 +1,219 @@ +use crate::libc::{ c_void, int32_t, uint32_t, size_t, }; +use crate::core_foundation_sys::{ + base::{ Boolean, CFAllocatorRef, CFTypeID }, + dictionary::CFDictionaryRef, + array::CFArrayRef, + string::CFStringRef, +}; + +use crate::{ + OSType, + base::CVOptionFlags, + image_buffer::CVImageBufferRef, + return_::CVReturn, +}; + + +const fn as_u32_be(array: &[u8; 4]) -> u32 { + ((array[0] as u32) << 24) + + ((array[1] as u32) << 16) + + ((array[2] as u32) << 8) + + ((array[3] as u32) << 0) +} + + +pub type CVPixelBufferLockFlags = u64; +pub type CVPixelBufferRef = CVImageBufferRef; + + +pub const kCVPixelFormatType_1Monochrome: OSType = 0x00000001; /* 1 bit indexed */ +pub const kCVPixelFormatType_2Indexed: OSType = 0x00000002; /* 2 bit indexed */ +pub const kCVPixelFormatType_4Indexed: OSType = 0x00000004; /* 4 bit indexed */ +pub const kCVPixelFormatType_8Indexed: OSType = 0x00000008; /* 8 bit indexed */ +pub const kCVPixelFormatType_1IndexedGray_WhiteIsZero: OSType = 0x00000021; /* 1 bit indexed gray, white is zero */ +pub const kCVPixelFormatType_2IndexedGray_WhiteIsZero: OSType = 0x00000022; /* 2 bit indexed gray, white is zero */ +pub const kCVPixelFormatType_4IndexedGray_WhiteIsZero: OSType = 0x00000024; /* 4 bit indexed gray, white is zero */ +pub const kCVPixelFormatType_8IndexedGray_WhiteIsZero: OSType = 0x00000028; /* 8 bit indexed gray, white is zero */ +pub const kCVPixelFormatType_16BE555: OSType = 0x00000010; /* 16 bit BE RGB 555 */ +pub const kCVPixelFormatType_16LE555: OSType = as_u32_be(b"L555"); /* 16 bit LE RGB 555 */ +pub const kCVPixelFormatType_16LE5551: OSType = as_u32_be(b"5551"); /* 16 bit LE RGB 5551 */ +pub const kCVPixelFormatType_16BE565: OSType = as_u32_be(b"B565"); /* 16 bit BE RGB 565 */ +pub const kCVPixelFormatType_16LE565: OSType = as_u32_be(b"L565"); /* 16 bit LE RGB 565 */ +pub const kCVPixelFormatType_24RGB: OSType = 0x00000018; /* 24 bit RGB */ +pub const kCVPixelFormatType_24BGR: OSType = as_u32_be(b"24BG"); /* 24 bit BGR */ +pub const kCVPixelFormatType_32ARGB: OSType = 0x00000020; /* 32 bit ARGB */ +pub const kCVPixelFormatType_32BGRA: OSType = as_u32_be(b"BGRA"); /* 32 bit BGRA */ +pub const kCVPixelFormatType_32ABGR: OSType = as_u32_be(b"ABGR"); /* 32 bit ABGR */ +pub const kCVPixelFormatType_32RGBA: OSType = as_u32_be(b"RGBA"); /* 32 bit RGBA */ +pub const kCVPixelFormatType_64ARGB: OSType = as_u32_be(b"b64a"); /* 64 bit ARGB, 16-bit big-endian samples */ +pub const kCVPixelFormatType_48RGB: OSType = as_u32_be(b"b48r"); /* 48 bit RGB, 16-bit big-endian samples */ +pub const kCVPixelFormatType_32AlphaGray: OSType = as_u32_be(b"b32a"); /* 32 bit AlphaGray, 16-bit big-endian samples, black is zero */ +pub const kCVPixelFormatType_16Gray: OSType = as_u32_be(b"b16g"); /* 16 bit Grayscale, 16-bit big-endian samples, black is zero */ +pub const kCVPixelFormatType_30RGB: OSType = as_u32_be(b"R10k"); /* 30 bit RGB, 10-bit big-endian samples, 2 unused padding bits (at least significant end). */ +pub const kCVPixelFormatType_422YpCbCr8: OSType = as_u32_be(b"2vuy"); /* Component Y'CbCr 8-bit 4:2:2, ordered Cb Y'0 Cr Y'1 */ +pub const kCVPixelFormatType_4444YpCbCrA8: OSType = as_u32_be(b"v408"); /* Component Y'CbCrA 8-bit 4:4:4:4, ordered Cb Y' Cr A */ +pub const kCVPixelFormatType_4444YpCbCrA8R: OSType = as_u32_be(b"r408"); /* Component Y'CbCrA 8-bit 4:4:4:4, rendering format. full range alpha, zero biased YUV, ordered A Y' Cb Cr */ +pub const kCVPixelFormatType_4444AYpCbCr8: OSType = as_u32_be(b"y408"); /* Component Y'CbCrA 8-bit 4:4:4:4, ordered A Y' Cb Cr, full range alpha, video range Y'CbCr. */ +pub const kCVPixelFormatType_4444AYpCbCr16: OSType = as_u32_be(b"y416"); /* Component Y'CbCrA 16-bit 4:4:4:4, ordered A Y' Cb Cr, full range alpha, video range Y'CbCr, 16-bit little-endian samples. */ +pub const kCVPixelFormatType_444YpCbCr8: OSType = as_u32_be(b"v308"); /* Component Y'CbCr 8-bit 4:4:4 */ +pub const kCVPixelFormatType_422YpCbCr16: OSType = as_u32_be(b"v216"); /* Component Y'CbCr 10,12,14,16-bit 4:2:2 */ +pub const kCVPixelFormatType_422YpCbCr10: OSType = as_u32_be(b"v210"); /* Component Y'CbCr 10-bit 4:2:2 */ +pub const kCVPixelFormatType_444YpCbCr10: OSType = as_u32_be(b"v410"); /* Component Y'CbCr 10-bit 4:4:4 */ +pub const kCVPixelFormatType_420YpCbCr8Planar: OSType = as_u32_be(b"y420"); /* Planar Component Y'CbCr 8-bit 4:2:0. baseAddr points to a big-endian CVPlanarPixelBufferInfo_YCbCrPlanar struct */ +pub const kCVPixelFormatType_420YpCbCr8PlanarFullRange: OSType = as_u32_be(b"f420"); /* Planar Component Y'CbCr 8-bit 4:2:0, full range. baseAddr points to a big-endian CVPlanarPixelBufferInfo_YCbCrPlanar struct */ +pub const kCVPixelFormatType_422YpCbCr_4A_8BiPlanar: OSType = as_u32_be(b"a2vy"); /* First plane: Video-range Component Y'CbCr 8-bit 4:2:2, ordered Cb Y'0 Cr Y'1; second plane: alpha 8-bit 0-255 */ +pub const kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange: OSType = as_u32_be(b"420v"); /* Bi-Planar Component Y'CbCr 8-bit 4:2:0, video-range (luma=[16,235] chroma=[16,240]). baseAddr points to a big-endian CVPlanarPixelBufferInfo_YCbCrBiPlanar struct */ +pub const kCVPixelFormatType_420YpCbCr8BiPlanarFullRange: OSType = as_u32_be(b"420f"); /* Bi-Planar Component Y'CbCr 8-bit 4:2:0, full-range (luma=[0,255] chroma=[1,255]). baseAddr points to a big-endian CVPlanarPixelBufferInfo_YCbCrBiPlanar struct */ +pub const kCVPixelFormatType_422YpCbCr8_yuvs: OSType = as_u32_be(b"yuvs"); /* Component Y'CbCr 8-bit 4:2:2, ordered Y'0 Cb Y'1 Cr */ +pub const kCVPixelFormatType_422YpCbCr8FullRange: OSType = as_u32_be(b"yuvf"); /* Component Y'CbCr 8-bit 4:2:2, full range, ordered Y'0 Cb Y'1 Cr */ +pub const kCVPixelFormatType_OneComponent8: OSType = as_u32_be(b"L008"); /* 8 bit one component, black is zero */ +pub const kCVPixelFormatType_TwoComponent8: OSType = as_u32_be(b"2C08"); /* 8 bit two component, black is zero */ +pub const kCVPixelFormatType_30RGBLEPackedWideGamut: OSType = as_u32_be(b"w30r"); /* little-endian RGB101010, 2 MSB are zero, wide-gamut (384-895) */ +pub const kCVPixelFormatType_ARGB2101010LEPacked: OSType = as_u32_be(b"l10r"); /* little-endian ARGB2101010 full-range ARGB */ +pub const kCVPixelFormatType_OneComponent16Half: OSType = as_u32_be(b"L00h"); /* 16 bit one component IEEE half-precision float, 16-bit little-endian samples */ +pub const kCVPixelFormatType_OneComponent32Float: OSType = as_u32_be(b"L00f"); /* 32 bit one component IEEE float, 32-bit little-endian samples */ +pub const kCVPixelFormatType_TwoComponent16Half: OSType = as_u32_be(b"2C0h"); /* 16 bit two component IEEE half-precision float, 16-bit little-endian samples */ +pub const kCVPixelFormatType_TwoComponent32Float: OSType = as_u32_be(b"2C0f"); /* 32 bit two component IEEE float, 32-bit little-endian samples */ +pub const kCVPixelFormatType_64RGBAHalf: OSType = as_u32_be(b"RGhA"); /* 64 bit RGBA IEEE half-precision float, 16-bit little-endian samples */ +pub const kCVPixelFormatType_128RGBAFloat: OSType = as_u32_be(b"RGfA"); /* 128 bit RGBA IEEE float, 32-bit little-endian samples */ +pub const kCVPixelFormatType_14Bayer_GRBG: OSType = as_u32_be(b"grb4"); /* Bayer 14-bit Little-Endian, packed in 16-bits, ordered G R G R... alternating with B G B G... */ +pub const kCVPixelFormatType_14Bayer_RGGB: OSType = as_u32_be(b"rgg4"); /* Bayer 14-bit Little-Endian, packed in 16-bits, ordered R G R G... alternating with G B G B... */ +pub const kCVPixelFormatType_14Bayer_BGGR: OSType = as_u32_be(b"bgg4"); /* Bayer 14-bit Little-Endian, packed in 16-bits, ordered B G B G... alternating with G R G R... */ +pub const kCVPixelFormatType_14Bayer_GBRG: OSType = as_u32_be(b"gbr4"); /* Bayer 14-bit Little-Endian, packed in 16-bits, ordered G B G B... alternating with R G R G... */ +pub const kCVPixelFormatType_DisparityFloat16: OSType = as_u32_be(b"hdis"); /* IEEE754-2008 binary16 (half float), describing the normalized shift when comparing two images. Units are 1/meters: ( pixelShift / (pixelFocalLength * baselineInMeters) ) */ +pub const kCVPixelFormatType_DisparityFloat32: OSType = as_u32_be(b"fdis"); /* IEEE754-2008 binary32 float, describing the normalized shift when comparing two images. Units are 1/meters: ( pixelShift / (pixelFocalLength * baselineInMeters) ) */ +pub const kCVPixelFormatType_DepthFloat16: OSType = as_u32_be(b"hdep"); /* IEEE754-2008 binary16 (half float), describing the depth (distance to an object) in meters */ +pub const kCVPixelFormatType_DepthFloat32: OSType = as_u32_be(b"fdep"); /* IEEE754-2008 binary32 float, describing the depth (distance to an object) in meters */ +pub const kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange: OSType = as_u32_be(b"x420"); /* 2 plane YCbCr10 4:2:0, each 10 bits in the MSBs of 16bits, video-range (luma=[64,940] chroma=[64,960]) */ +pub const kCVPixelFormatType_422YpCbCr10BiPlanarVideoRange: OSType = as_u32_be(b"x422"); /* 2 plane YCbCr10 4:2:2, each 10 bits in the MSBs of 16bits, video-range (luma=[64,940] chroma=[64,960]) */ +pub const kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange: OSType = as_u32_be(b"x444"); /* 2 plane YCbCr10 4:4:4, each 10 bits in the MSBs of 16bits, video-range (luma=[64,940] chroma=[64,960]) */ +pub const kCVPixelFormatType_420YpCbCr10BiPlanarFullRange: OSType = as_u32_be(b"xf20"); /* 2 plane YCbCr10 4:2:0, each 10 bits in the MSBs of 16bits, full-range (Y range 0-1023) */ +pub const kCVPixelFormatType_422YpCbCr10BiPlanarFullRange: OSType = as_u32_be(b"xf22"); /* 2 plane YCbCr10 4:2:2, each 10 bits in the MSBs of 16bits, full-range (Y range 0-1023) */ +pub const kCVPixelFormatType_444YpCbCr10BiPlanarFullRange: OSType = as_u32_be(b"xf44"); /* 2 plane YCbCr10 4:4:4, each 10 bits in the MSBs of 16bits, full-range (Y range 0-1023) */ + + +pub const kCVPixelBufferLock_ReadOnly: CVPixelBufferLockFlags = 1; + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CVPlanarComponentInfo { + /// offset from main base address to base address of this plane, big-endian + pub offset: int32_t, + /// bytes per row of this plane, big-endian + pub rowBytes: uint32_t, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CVPlanarPixelBufferInfo { + pub componentInfo: [CVPlanarComponentInfo; 1], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CVPlanarPixelBufferInfo_YCbCrPlanar { + pub componentInfoY: CVPlanarComponentInfo, + pub componentInfoCb: CVPlanarComponentInfo, + pub componentInfoCr: CVPlanarComponentInfo, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CVPlanarPixelBufferInfo_YCbCrBiPlanar { + pub componentInfoY: CVPlanarComponentInfo, + pub componentInfoCbCr: CVPlanarComponentInfo, +} + + + +pub type CVPixelBufferReleaseBytesCallback = extern "C" fn (releaseRefCon: *mut c_void, + baseAddress: *const *const c_void); +pub type CVPixelBufferReleasePlanarBytesCallback = extern "C" fn (releaseRefCon: *mut c_void, + dataPtr: *const *const c_void, + dataSize: size_t, + numberOfPlanes: size_t, + planeAddresses: *const *const c_void); + +extern "C" { + pub static kCVPixelBufferPixelFormatTypeKey: CFStringRef; + pub static kCVPixelBufferMemoryAllocatorKey: CFStringRef; + pub static kCVPixelBufferWidthKey: CFStringRef; + pub static kCVPixelBufferHeightKey: CFStringRef; + pub static kCVPixelBufferExtendedPixelsLeftKey: CFStringRef; + pub static kCVPixelBufferExtendedPixelsTopKey: CFStringRef; + pub static kCVPixelBufferExtendedPixelsRightKey: CFStringRef; + pub static kCVPixelBufferExtendedPixelsBottomKey: CFStringRef; + pub static kCVPixelBufferBytesPerRowAlignmentKey: CFStringRef; + pub static kCVPixelBufferCGBitmapContextCompatibilityKey: CFStringRef; + pub static kCVPixelBufferCGImageCompatibilityKey: CFStringRef; + pub static kCVPixelBufferOpenGLCompatibilityKey: CFStringRef; + pub static kCVPixelBufferPlaneAlignmentKey: CFStringRef; + pub static kCVPixelBufferIOSurfacePropertiesKey: CFStringRef; + pub static kCVPixelBufferOpenGLESCompatibilityKey: CFStringRef; + pub static kCVPixelBufferMetalCompatibilityKey: CFStringRef; + pub static kCVPixelBufferOpenGLTextureCacheCompatibilityKey: CFStringRef; + pub static kCVPixelBufferOpenGLESTextureCacheCompatibilityKey: CFStringRef; + + + pub fn CVBufferGetTypeID() -> CFTypeID; + pub fn CVPixelBufferRetain(texture: CVPixelBufferRef) -> CVPixelBufferRef; + pub fn CVPixelBufferRelease(texture: CVPixelBufferRef); + pub fn CVPixelBufferCreateResolvedAttributesDictionary(allocator: CFAllocatorRef, + attributes: CFArrayRef, + resolvedDictionaryOut: *mut CFDictionaryRef) -> CVReturn; + pub fn CVPixelBufferCreate( + allocator: CFAllocatorRef, + width: size_t, + height: size_t, + pixelFormatType: OSType, + pixelBufferAttributes: CFDictionaryRef, + pixelBufferOut: *mut CVPixelBufferRef, + ) -> CVReturn; + // pub fn CVPixelBufferCreateWithBytes(allocator: CFAllocatorRef, + // width: size_t, + // height: size_t, + // pixelFormatType: OSType, + // baseAddress: *const c_void, + // bytesPerRow: size_t, + // releaseCallback: CVPixelBufferReleaseBytesCallback, + // releaseRefCon: *const c_void, + // pixelBufferAttributes: CFDictionaryRef, + // pixelBufferOut: *mut CVPixelBufferRef) -> CVReturn; + // pub fn CVPixelBufferCreateWithPlanarBytes(allocator: CFAllocatorRef, + // width: size_t, + // height: size_t, + // pixelFormatType: OSType, + // dataPtr: *const c_void, + // dataSize: size_t, + // numberOfPlanes: size_t, + // planeBaseAddress: *const *const c_void, + // ) -> CVReturn; + + pub fn CVPixelBufferLockBaseAddress(pixelBuffer: CVPixelBufferRef, + lockFlags: CVOptionFlags) -> CVReturn; + pub fn CVPixelBufferUnlockBaseAddress(pixelBuffer: CVPixelBufferRef, + unlockFlags: CVOptionFlags) -> CVReturn; + pub fn CVPixelBufferGetWidth(pixelBuffer: CVPixelBufferRef) -> size_t; + pub fn CVPixelBufferGetHeight(pixelBuffer: CVPixelBufferRef) -> size_t; + pub fn CVPixelBufferGetPixelFormatType(pixelBuffer: CVPixelBufferRef) -> OSType; + + pub fn CVPixelBufferGetBaseAddress(pixelBuffer: CVPixelBufferRef) -> *mut c_void; + pub fn CVPixelBufferGetBytesPerRow(pixelBuffer: CVPixelBufferRef) -> size_t; + pub fn CVPixelBufferIsPlanar(pixelBuffer: CVPixelBufferRef) -> Boolean; + pub fn CVPixelBufferGetPlaneCount(pixelBuffer: CVPixelBufferRef) -> size_t; + pub fn CVPixelBufferGetWidthOfPlane(pixelBuffer: CVPixelBufferRef, + planeIndex: size_t) -> size_t; + pub fn CVPixelBufferGetHeightOfPlane(pixelBuffer: CVPixelBufferRef, + planeIndex: size_t) -> size_t; + pub fn CVPixelBufferGetBaseAddressOfPlane(pixelBuffer: CVPixelBufferRef, + planeIndex: size_t) -> *mut c_void; + pub fn CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer: CVPixelBufferRef, + planeIndex: size_t) -> size_t; + + pub fn CVPixelBufferGetExtendedPixels(pixelBuffer: CVPixelBufferRef, + extraColumnsOnLeft: *const size_t, + extraColumnsOnRight: *const size_t, + extraRowsOnTop: *const size_t, + extraRowsOnBottom: *const size_t); + pub fn CVPixelBufferFillExtendedPixels(pixelBuffer: CVPixelBufferRef) -> CVReturn; +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_io_surface.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_io_surface.rs new file mode 100644 index 0000000..204bd82 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_io_surface.rs @@ -0,0 +1,33 @@ +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, }, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; + +use crate::{ + pixel_buffer::CVPixelBufferRef, + return_::CVReturn, +}; + + +// https://developer.apple.com/documentation/iosurface/iosurfaceref?language=objc +#[derive(Debug, Copy, Clone)] +pub enum _IOSurface { } +pub type IOSurfaceRef = *mut _IOSurface; + + +extern "C" { + pub static kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey: CFStringRef; + pub static kCVPixelBufferIOSurfaceOpenGLFBOCompatibilityKey: CFStringRef; + pub static kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey: CFStringRef; + + pub static kCVPixelBufferIOSurfaceOpenGLESTextureCompatibilityKey: CFStringRef; + pub static kCVPixelBufferIOSurfaceOpenGLESFBOCompatibilityKey: CFStringRef; + + + pub fn CVPixelBufferGetIOSurface(pixelBuffer: CVPixelBufferRef) -> IOSurfaceRef; + pub fn CVPixelBufferCreateWithIOSurface(allocator: CFAllocatorRef, + surface: IOSurfaceRef, + pixelBufferAttributes: CFDictionaryRef, + pixelBufferOut: *mut CVPixelBufferRef) -> CVReturn; +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_pool.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_pool.rs new file mode 100644 index 0000000..d718c56 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_buffer_pool.rs @@ -0,0 +1,46 @@ +use crate::libc::{ c_void, }; +use crate::core_foundation_sys::{ + base::{ CFAllocatorRef, CFTypeID, CFTypeRef }, + dictionary::CFDictionaryRef, + string::CFStringRef, +}; + +use crate::{ + base::CVOptionFlags, + pixel_buffer::CVPixelBufferRef, + return_::CVReturn, + +}; + + +pub type CVPixelBufferPoolRef = CFTypeRef; +pub type CVPixelBufferPoolFlushFlags = CVOptionFlags; + +pub const kCVPixelBufferPoolFlushExcessBuffers: CVPixelBufferPoolFlushFlags = 1; + +extern "C" { + pub static kCVPixelBufferPoolMinimumBufferCountKey: CFStringRef; + pub static kCVPixelBufferPoolMaximumBufferAgeKey: CFStringRef; + + pub static kCVPixelBufferPoolAllocationThresholdKey: CFStringRef; + pub static kCVPixelBufferPoolFreeBufferNotification: CFStringRef; + + pub fn CVPixelBufferPoolGetTypeID() -> CFTypeID; + pub fn CVPixelBufferPoolRetain(pixelBufferPool: CVPixelBufferPoolRef) -> CVPixelBufferPoolRef; + pub fn CVPixelBufferPoolRelease(pixelBufferPool: CVPixelBufferPoolRef) -> c_void; + pub fn CVPixelBufferPoolCreate(allocator: CFAllocatorRef, + poolAttributes: CFDictionaryRef, + pixelBufferAttributes: CFDictionaryRef, + poolOut: *mut CVPixelBufferPoolRef) -> CVReturn; + pub fn CVPixelBufferPoolGetAttributes(pool: CVPixelBufferPoolRef) -> CFDictionaryRef; + pub fn CVPixelBufferPoolGetPixelBufferAttributes(pool: CVPixelBufferPoolRef) -> CFDictionaryRef; + pub fn CVPixelBufferPoolCreatePixelBuffer(allocator: CFAllocatorRef, + pixelBufferPool: CVPixelBufferPoolRef, + pixelBufferOut: *mut CVPixelBufferRef) -> CVReturn; + pub fn CVPixelBufferPoolCreatePixelBufferWithAuxAttributes(allocator: CFAllocatorRef, + pixelBufferPool: CVPixelBufferPoolRef, + auxAttributes: CFDictionaryRef, + pixelBufferOut: *mut CVPixelBufferRef) -> CVReturn; + pub fn CVPixelBufferPoolFlush(pool: CVPixelBufferPoolRef, + options: CVPixelBufferPoolFlushFlags); +} \ No newline at end of file diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_format_description.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_format_description.rs new file mode 100644 index 0000000..e1ebab9 --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/pixel_format_description.rs @@ -0,0 +1,121 @@ +use crate::libc::{ c_void, }; +use crate::core_foundation_sys::{ + base::{ Boolean, CFAllocatorRef, CFIndex, }, + dictionary::CFDictionaryRef, + array::CFArrayRef, + string::CFStringRef, +}; + +use crate::{ + OSType, + pixel_buffer::CVPixelBufferRef, +}; + + +pub type CVFillExtendedPixelsCallBack = extern "C" fn (pixelBuffer: CVPixelBufferRef, + refCon: *mut c_void) -> Boolean; + + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CVFillExtendedPixelsCallBackData { + pub version: CFIndex, + pub fillCallBack: CVFillExtendedPixelsCallBack, + pub refCon: *mut c_void, + +} + + +extern "C" { + pub static kCVPixelFormatName: CFStringRef; + + /// QuickTime/QuickDraw Pixel Format Type constant (OSType) + pub static kCVPixelFormatConstant: CFStringRef; + + /// This is the codec type constant, i.e. '2vuy' or k422YpCbCr8CodecType + pub static kCVPixelFormatCodecType: CFStringRef; + + /// This is the equivalent Microsoft FourCC code for this pixel format + pub static kCVPixelFormatFourCC: CFStringRef; + + /// kCFBooleanTrue indicates that the format contains alpha and some images may be considered transparent + /// kCFBooleanFalse indicates that there is no alpha and images are always opaque. + pub static kCVPixelFormatContainsAlpha: CFStringRef; + + /// kCFBooleanTrue indicates that the format contains YCbCr data + pub static kCVPixelFormatContainsYCbCr: CFStringRef; + + /// kCFBooleanTrue indicates that the format contains RGB data + pub static kCVPixelFormatContainsRGB: CFStringRef; + + pub static kCVPixelFormatComponentRange: CFStringRef; + + pub static kCVPixelFormatComponentRange_VideoRange: CFStringRef; + + pub static kCVPixelFormatComponentRange_FullRange: CFStringRef; + + pub static kCVPixelFormatComponentRange_WideRange: CFStringRef; + + /// All buffers have one or more image planes. + /// Each plane may contain a single or an interleaved set of components + /// For simplicity sake, + /// pixel formats that are not planar may place the required format keys at the top level dictionary. + pub static kCVPixelFormatPlanes: CFStringRef; + + + pub static kCVPixelFormatBlockWidth: CFStringRef; + pub static kCVPixelFormatBlockHeight: CFStringRef; + + /// This value must be present. + /// For simple pixel formats this will be equivalent to the traditional bitsPerPixel value. + pub static kCVPixelFormatBitsPerBlock: CFStringRef; + + /// Used to state requirements on block multiples. v210 would be '8' here for the horizontal case, + /// to match the standard v210 row alignment value of 48. + /// These may be assumed as 1 if not present. + pub static kCVPixelFormatBlockHorizontalAlignment: CFStringRef; + pub static kCVPixelFormatBlockVerticalAlignment: CFStringRef; + + /// CFData containing the bit pattern for a block of black pixels. If absent, black is assumed to be all zeros. + /// If present, this should be bitsPerPixel bits long -- if bitsPerPixel is less than a byte, repeat the bit pattern + /// for the full byte. + pub static kCVPixelFormatBlackBlock: CFStringRef; + + /// Subsampling information for this plane. Assumed to be '1' if not present. + pub static kCVPixelFormatHorizontalSubsampling: CFStringRef; + pub static kCVPixelFormatVerticalSubsampling: CFStringRef; + + /// If present, these two keys describe the OpenGL format and type enums you would use to describe this + /// image plane to OpenGL + pub static kCVPixelFormatOpenGLFormat: CFStringRef; + pub static kCVPixelFormatOpenGLType: CFStringRef; + pub static kCVPixelFormatOpenGLInternalFormat: CFStringRef; + + /// CGBitmapInfo value, if required + pub static kCVPixelFormatCGBitmapInfo: CFStringRef; + + /// Pixel format compatibility flags + pub static kCVPixelFormatQDCompatibility: CFStringRef; + pub static kCVPixelFormatCGBitmapContextCompatibility: CFStringRef; + pub static kCVPixelFormatCGImageCompatibility: CFStringRef; + pub static kCVPixelFormatOpenGLCompatibility: CFStringRef; + pub static kCVPixelFormatOpenGLESCompatibility: CFStringRef; + + pub static kCVPixelFormatFillExtendedPixelsCallback: CFStringRef; + + + pub fn CVPixelFormatDescriptionCreateWithPixelFormatType(allocator: CFAllocatorRef, + pixelFormat: OSType) -> CFDictionaryRef; + pub fn CVPixelFormatDescriptionArrayCreateWithAllPixelFormatTypes(allocator: CFAllocatorRef) -> CFArrayRef; + pub fn CVPixelFormatDescriptionRegisterDescriptionWithPixelFormatType(description: CFDictionaryRef, + pixelFormat: OSType); +} + + +#[cfg(feature = "direct3d")] +extern "C" { + pub static kCVPixelFormatDirect3DFormat: CFStringRef; + pub static kCVPixelFormatDirect3DType: CFStringRef; + pub static kCVPixelFormatDirect3DInternalFormat: CFStringRef; + pub static kCVPixelFormatDirect3DCompatibility: CFStringRef; +} diff --git a/third_party/cargo/vendor/core-video-sys-0.1.3/src/return_.rs b/third_party/cargo/vendor/core-video-sys-0.1.3/src/return_.rs new file mode 100644 index 0000000..24d860a --- /dev/null +++ b/third_party/cargo/vendor/core-video-sys-0.1.3/src/return_.rs @@ -0,0 +1,32 @@ +use crate::libc::{ int32_t, }; + +pub type CVReturn = int32_t; + + +pub const kCVReturnSuccess: CVReturn = 0; +pub const kCVReturnFirst: CVReturn = -6660; +pub const kCVReturnError: CVReturn = kCVReturnFirst; +pub const kCVReturnInvalidArgument: CVReturn = -6661; +pub const kCVReturnAllocationFailed: CVReturn = -6662; +pub const kCVReturnUnsupported: CVReturn = -6663; + +// DisplayLink related errors +pub const kCVReturnInvalidDisplay: CVReturn = -6670; +pub const kCVReturnDisplayLinkAlreadyRunning: CVReturn = -6671; +pub const kCVReturnDisplayLinkNotRunning: CVReturn = -6672; +pub const kCVReturnDisplayLinkCallbacksNotSet: CVReturn = -6673; + +// Buffer related errors +pub const kCVReturnInvalidPixelFormat: CVReturn = -6680; +pub const kCVReturnInvalidSize: CVReturn = -6681; +pub const kCVReturnInvalidPixelBufferAttributes: CVReturn = -6682; +pub const kCVReturnPixelBufferNotOpenGLCompatible: CVReturn = -6683; +pub const kCVReturnPixelBufferNotMetalCompatible: CVReturn = -6684; + +// Buffer Pool related errors +pub const kCVReturnWouldExceedAllocationThreshold: CVReturn = -6689; +pub const kCVReturnPoolAllocationFailed: CVReturn = -6690; +pub const kCVReturnInvalidPoolAttributes: CVReturn = -6691; +pub const kCVReturnRetry: CVReturn = -6692; + +pub const kCVReturnLast: CVReturn = -669; diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-0.5.0/.cargo-checksum.json deleted file mode 100644 index 0bb2060..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"036c480cc86b109f9df6aaf23a1fa7322ea27cd1119ad316a1f732ea11fe5c07","Cargo.toml":"6581ed402f6ae3b68043f72dbab0921a01ea6ac9e017778a70e5c3d4d8379fce","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.md":"2f985ee8cd18fece6bc6e8c24da3b49f7e77f37f5721bff1f378c3e2a72b308e","src/arc_cell.rs":"e3b159a4dda2df52f07c19e5622a8e09bb11a7b98df9b78c6dccd8d1c11d59b8","src/atomic_cell.rs":"501db20a0710025305c0d2ad4a6f969a3fb1c5443bf70495d36f0c8b50d9bf29","src/lib.rs":"98ccb355d6a31cf008a5f13310442dc5c49c2c0bb5d161c5daf29ec7bc4c95c1","src/ms_queue.rs":"2f540462df32968e07054aea4cb6e6378085c2f01641028e9b771c9cc84da96f","src/seg_queue.rs":"3c8831aabc4c7102bfb11f070c533fafc9f72eea909398eb26069b8b3d9da78e","src/sharded_lock.rs":"dd0eaf1b2cedae088702707ff3fde528fb74b85663e78b1ccb2dbd7a22d143b1","src/treiber_stack.rs":"44ae78ae52d75371b7159456773a58e191534b6394e644ecc031efabcaa118b9","src/wait_group.rs":"8ad847036fb440b7eab2eec8f9f4b966c337dae0c930518c2108f09691365e2f","tests/atomic_cell.rs":"1685dc1479c02f2986edf5e970c18f0cc32b2a17c85ffa8bb76a38199db61ddd","tests/subcrates.rs":"b67663afaedd59cd1f8b50b30cf727f073ecadbddc3d5ebc1304ef9f72c8827a","tests/wait_group.rs":"2d701e556f30d14b1a0c7878e1dcc2eba0277b50eb7199c61b921340f87678fe"},"package":"d1c92ff2d7a202d592f5a412d75cf421495c913817781c1cb383bf12a77e185f"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/README.md b/third_party/cargo/vendor/crossbeam-0.5.0/README.md deleted file mode 100644 index ae9c9f8..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# Crossbeam: support for concurrent programming - -[![Build Status](https://travis-ci.org/crossbeam-rs/crossbeam.svg?branch=master)]( -https://travis-ci.org/crossbeam-rs/crossbeam) -[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( -https://github.com/crossbeam-rs/crossbeam) -[![Cargo](https://img.shields.io/crates/v/crossbeam.svg)]( -https://crates.io/crates/crossbeam) -[![Documentation](https://docs.rs/crossbeam/badge.svg)]( -https://docs.rs/crossbeam) - -Crossbeam supports concurrent programming, especially focusing on memory -management, synchronization, and non-blocking data structures. - -Crossbeam consists of several submodules: - - - `atomic` for **enhancing `std::sync` API**. `AtomicConsume` provides - C/C++11-style "consume" atomic operations (re-exported from - [`crossbeam-utils`]). `ArcCell` provides atomic storage and retrieval of - `Arc`. - - - `utils` and `thread` for **utilities**, re-exported from [`crossbeam-utils`]. - The "scoped" thread API in `thread` makes it possible to spawn threads that - share stack data with their parents. The `utils::CachePadded` struct inserts - padding to align data with the size of a cacheline. This crate also seeks to - expand the standard library's few synchronization primitives (locks, - barriers, etc) to include advanced/niche primitives, as well as userspace - alternatives. - - - `epoch` for **memory management**, re-exported from [`crossbeam-epoch`]. - Because non-blocking data structures avoid global synchronization, it is not - easy to tell when internal data can be safely freed. The crate provides - generic, easy to use, and high-performance APIs for managing memory in these - cases. We plan to support other memory management schemes, e.g. hazard - pointers (HP) and quiescent state-based reclamation (QSBR). - - - **Concurrent data structures** which are non-blocking and much superior to - wrapping sequential ones with a `Mutex`. Crossbeam currently provides - channels (re-exported from [`crossbeam-channel`]), deques - (re-exported from [`crossbeam-deque`]), queues, and stacks. Ultimately the - goal is to also include bags, sets and maps. - -# Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -crossbeam = "0.5" -``` - -Next, add this to your crate: - -```rust -extern crate crossbeam; -``` - -The minimum required Rust version is 1.26. - -[`crossbeam-epoch`]: https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch -[`crossbeam-utils`]: https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils -[`crossbeam-channel`]: https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel -[`crossbeam-deque`]: https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque - -## License - -Licensed under the terms of MIT license and the Apache License (Version 2.0). - -See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details. diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/arc_cell.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/arc_cell.rs deleted file mode 100644 index ddec0fa..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/arc_cell.rs +++ /dev/null @@ -1,109 +0,0 @@ -use alloc::sync::Arc; -use core::marker::PhantomData; -use core::mem; -use core::sync::atomic::{AtomicUsize, Ordering}; - -/// A type providing atomic storage and retrieval of an `Arc`. -#[derive(Debug)] -pub struct ArcCell(AtomicUsize, PhantomData>); - -impl Drop for ArcCell { - fn drop(&mut self) { - self.take(); - } -} - -impl ArcCell { - /// Creates a new `ArcCell`. - pub fn new(t: Arc) -> ArcCell { - ArcCell(AtomicUsize::new(unsafe { mem::transmute(t) }), PhantomData) - } - - fn take(&self) -> Arc { - loop { - match self.0.swap(0, Ordering::Acquire) { - 0 => {} - n => return unsafe { mem::transmute(n) }, - } - } - } - - fn put(&self, t: Arc) { - debug_assert_eq!(self.0.load(Ordering::SeqCst), 0); - self.0 - .store(unsafe { mem::transmute(t) }, Ordering::Release); - } - - /// Stores a new value in the `ArcCell`, returning the previous - /// value. - pub fn set(&self, t: Arc) -> Arc { - let old = self.take(); - self.put(t); - old - } - - /// Returns a copy of the value stored by the `ArcCell`. - pub fn get(&self) -> Arc { - let t = self.take(); - // NB: correctness here depends on Arc's clone impl not panicking - let out = t.clone(); - self.put(t); - out - } -} - -impl Default for ArcCell { - fn default() -> Self { - ArcCell::new(Arc::default()) - } -} - -impl From> for ArcCell { - fn from(value: Arc) -> Self { - ArcCell::new(value) - } -} - -impl From for ArcCell { - fn from(value: T) -> Self { - ArcCell::new(Arc::new(value)) - } -} - -#[cfg(test)] -mod test { - use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; - use std::sync::Arc; - - use super::*; - - #[test] - fn basic() { - let r = ArcCell::new(Arc::new(0)); - assert_eq!(*r.get(), 0); - assert_eq!(*r.set(Arc::new(1)), 0); - assert_eq!(*r.get(), 1); - } - - #[test] - fn drop_runs() { - static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; - - struct Foo; - - impl Drop for Foo { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::SeqCst); - } - } - - let r = ArcCell::new(Arc::new(Foo)); - let _f = r.get(); - r.get(); - r.set(Arc::new(Foo)); - drop(_f); - assert_eq!(DROPS.load(Ordering::SeqCst), 1); - drop(r); - assert_eq!(DROPS.load(Ordering::SeqCst), 2); - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/atomic_cell.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/atomic_cell.rs deleted file mode 100644 index a826130..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/atomic_cell.rs +++ /dev/null @@ -1,904 +0,0 @@ -use core::cell::UnsafeCell; -use core::fmt; -use core::mem; -use core::ptr; -use core::slice; -use core::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; - -/// A thread-safe mutable memory location. -/// -/// This type is equivalent to [`Cell`], except it can also be shared among multiple threads. -/// -/// Operations on `AtomicCell`s use atomic instructions whenever possible, and synchronize using -/// global locks otherwise. You can call [`AtomicCell::::is_lock_free()`] to check whether -/// atomic instructions or locks will be used. -/// -/// [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html -/// [`AtomicCell::::is_lock_free()`]: struct.AtomicCell.html#method.is_lock_free -pub struct AtomicCell { - /// The inner value. - /// - /// If this value can be transmuted into a primitive atomic type, it will be treated as such. - /// Otherwise, all potentially concurrent operations on this data will be protected by a global - /// lock. - value: UnsafeCell, -} - -unsafe impl Send for AtomicCell {} -unsafe impl Sync for AtomicCell {} - -impl AtomicCell { - /// Creates a new atomic cell initialized with `val`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(7); - /// ``` - pub fn new(val: T) -> AtomicCell { - AtomicCell { - value: UnsafeCell::new(val), - } - } - - /// Returns a mutable reference to the inner value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let mut a = AtomicCell::new(7); - /// *a.get_mut() += 1; - /// - /// assert_eq!(a.load(), 8); - /// ``` - pub fn get_mut(&mut self) -> &mut T { - unsafe { &mut *self.value.get() } - } - - /// Unwraps the atomic cell and returns its inner value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let mut a = AtomicCell::new(7); - /// let v = a.into_inner(); - /// - /// assert_eq!(v, 7); - /// ``` - pub fn into_inner(self) -> T { - self.value.into_inner() - } - - /// Returns `true` if operations on values of this type are lock-free. - /// - /// If the compiler or the platform doesn't support the necessary atomic instructions, - /// `AtomicCell` will use global locks for every potentially concurrent atomic operation. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// // This type is internally represented as `AtomicUsize` so we can just use atomic - /// // operations provided by it. - /// assert_eq!(AtomicCell::::is_lock_free(), true); - /// - /// // A wrapper struct around `isize`. - /// struct Foo { - /// bar: isize, - /// } - /// // `AtomicCell` will be internally represented as `AtomicIsize`. - /// assert_eq!(AtomicCell::::is_lock_free(), true); - /// - /// // Operations on zero-sized types are always lock-free. - /// assert_eq!(AtomicCell::<()>::is_lock_free(), true); - /// - /// // Very large types cannot be represented as any of the standard atomic types, so atomic - /// // operations on them will have to use global locks for synchronization. - /// assert_eq!(AtomicCell::<[u8; 1000]>::is_lock_free(), false); - /// ``` - pub fn is_lock_free() -> bool { - atomic_is_lock_free::() - } - - /// Stores `val` into the atomic cell. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(7); - /// - /// assert_eq!(a.load(), 7); - /// a.store(8); - /// assert_eq!(a.load(), 8); - /// ``` - pub fn store(&self, val: T) { - if mem::needs_drop::() { - drop(self.swap(val)); - } else { - unsafe { - atomic_store(self.value.get(), val); - } - } - } - - /// Stores `val` into the atomic cell and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(7); - /// - /// assert_eq!(a.load(), 7); - /// assert_eq!(a.swap(8), 7); - /// assert_eq!(a.load(), 8); - /// ``` - pub fn swap(&self, val: T) -> T { - unsafe { atomic_swap(self.value.get(), val) } - } -} - -impl AtomicCell { - /// Loads a value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(7); - /// - /// assert_eq!(a.load(), 7); - /// ``` - pub fn load(&self) -> T { - unsafe { atomic_load(self.value.get()) } - } -} - -impl AtomicCell { - /// If the current value equals `current`, stores `new` into the atomic cell. - /// - /// The return value is always the previous value. If it is equal to `current`, then the value - /// was updated. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(1); - /// - /// assert_eq!(a.compare_exchange(2, 3), Err(1)); - /// assert_eq!(a.load(), 1); - /// - /// assert_eq!(a.compare_exchange(1, 2), Ok(1)); - /// assert_eq!(a.load(), 2); - /// ``` - pub fn compare_and_swap(&self, current: T, new: T) -> T { - match self.compare_exchange(current, new) { - Ok(v) => v, - Err(v) => v, - } - } - - /// If the current value equals `current`, stores `new` into the atomic cell. - /// - /// The return value is a result indicating whether the new value was written and containing - /// the previous value. On success this value is guaranteed to be equal to `current`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(1); - /// - /// assert_eq!(a.compare_exchange(2, 3), Err(1)); - /// assert_eq!(a.load(), 1); - /// - /// assert_eq!(a.compare_exchange(1, 2), Ok(1)); - /// assert_eq!(a.load(), 2); - /// ``` - pub fn compare_exchange(&self, mut current: T, new: T) -> Result { - loop { - match unsafe { atomic_compare_exchange_weak(self.value.get(), current, new) } { - Ok(_) => return Ok(current), - Err(previous) => { - if previous != current { - return Err(previous); - } - - // The compare-exchange operation has failed and didn't store `new`. The - // failure is either spurious, or `previous` was semantically equal to - // `current` but not byte-equal. Let's retry with `previous` as the new - // `current`. - current = previous; - } - } - } - } -} - -macro_rules! impl_arithmetic { - ($t:ty, $example:tt) => { - impl AtomicCell<$t> { - /// Increments the current value by `val` and returns the previous value. - /// - /// The addition wraps on overflow. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_add(3), 7); - /// assert_eq!(a.load(), 10); - /// ``` - #[inline] - pub fn fetch_add(&self, val: $t) -> $t { - if can_transmute::<$t, atomic::AtomicUsize>() { - let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) }; - a.fetch_add(val as usize, Ordering::SeqCst) as $t - } else { - let _guard = lock(self.value.get() as usize).write(); - let value = unsafe { &mut *(self.value.get()) }; - let old = *value; - *value = value.wrapping_add(val); - old - } - } - - /// Decrements the current value by `val` and returns the previous value. - /// - /// The subtraction wraps on overflow. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_sub(3), 7); - /// assert_eq!(a.load(), 4); - /// ``` - #[inline] - pub fn fetch_sub(&self, val: $t) -> $t { - if can_transmute::<$t, atomic::AtomicUsize>() { - let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) }; - a.fetch_sub(val as usize, Ordering::SeqCst) as $t - } else { - let _guard = lock(self.value.get() as usize).write(); - let value = unsafe { &mut *(self.value.get()) }; - let old = *value; - *value = value.wrapping_sub(val); - old - } - } - - /// Applies bitwise "and" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_and(3), 7); - /// assert_eq!(a.load(), 3); - /// ``` - #[inline] - pub fn fetch_and(&self, val: $t) -> $t { - if can_transmute::<$t, atomic::AtomicUsize>() { - let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) }; - a.fetch_and(val as usize, Ordering::SeqCst) as $t - } else { - let _guard = lock(self.value.get() as usize).write(); - let value = unsafe { &mut *(self.value.get()) }; - let old = *value; - *value &= val; - old - } - } - - /// Applies bitwise "or" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_or(16), 7); - /// assert_eq!(a.load(), 23); - /// ``` - #[inline] - pub fn fetch_or(&self, val: $t) -> $t { - if can_transmute::<$t, atomic::AtomicUsize>() { - let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) }; - a.fetch_or(val as usize, Ordering::SeqCst) as $t - } else { - let _guard = lock(self.value.get() as usize).write(); - let value = unsafe { &mut *(self.value.get()) }; - let old = *value; - *value |= val; - old - } - } - - /// Applies bitwise "xor" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_xor(2), 7); - /// assert_eq!(a.load(), 5); - /// ``` - #[inline] - pub fn fetch_xor(&self, val: $t) -> $t { - if can_transmute::<$t, atomic::AtomicUsize>() { - let a = unsafe { &*(self.value.get() as *const atomic::AtomicUsize) }; - a.fetch_xor(val as usize, Ordering::SeqCst) as $t - } else { - let _guard = lock(self.value.get() as usize).write(); - let value = unsafe { &mut *(self.value.get()) }; - let old = *value; - *value ^= val; - old - } - } - } - }; - ($t:ty, $atomic:ty, $example:tt) => { - impl AtomicCell<$t> { - /// Increments the current value by `val` and returns the previous value. - /// - /// The addition wraps on overflow. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_add(3), 7); - /// assert_eq!(a.load(), 10); - /// ``` - #[inline] - pub fn fetch_add(&self, val: $t) -> $t { - let a = unsafe { &*(self.value.get() as *const $atomic) }; - a.fetch_add(val, Ordering::SeqCst) - } - - /// Decrements the current value by `val` and returns the previous value. - /// - /// The subtraction wraps on overflow. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_sub(3), 7); - /// assert_eq!(a.load(), 4); - /// ``` - #[inline] - pub fn fetch_sub(&self, val: $t) -> $t { - let a = unsafe { &*(self.value.get() as *const $atomic) }; - a.fetch_sub(val, Ordering::SeqCst) - } - - /// Applies bitwise "and" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_and(3), 7); - /// assert_eq!(a.load(), 3); - /// ``` - #[inline] - pub fn fetch_and(&self, val: $t) -> $t { - let a = unsafe { &*(self.value.get() as *const $atomic) }; - a.fetch_and(val, Ordering::SeqCst) - } - - /// Applies bitwise "or" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_or(16), 7); - /// assert_eq!(a.load(), 23); - /// ``` - #[inline] - pub fn fetch_or(&self, val: $t) -> $t { - let a = unsafe { &*(self.value.get() as *const $atomic) }; - a.fetch_or(val, Ordering::SeqCst) - } - - /// Applies bitwise "xor" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - #[doc = $example] - /// - /// assert_eq!(a.fetch_xor(2), 7); - /// assert_eq!(a.load(), 5); - /// ``` - #[inline] - pub fn fetch_xor(&self, val: $t) -> $t { - let a = unsafe { &*(self.value.get() as *const $atomic) }; - a.fetch_xor(val, Ordering::SeqCst) - } - } - }; -} - -cfg_if! { - if #[cfg(feature = "nightly")] { - impl_arithmetic!(u8, atomic::AtomicU8, "let a = AtomicCell::new(7u8);"); - impl_arithmetic!(i8, atomic::AtomicI8, "let a = AtomicCell::new(7i8);"); - impl_arithmetic!(u16, atomic::AtomicU16, "let a = AtomicCell::new(7u16);"); - impl_arithmetic!(i16, atomic::AtomicI16, "let a = AtomicCell::new(7i16);"); - impl_arithmetic!(u32, atomic::AtomicU32, "let a = AtomicCell::new(7u32);"); - impl_arithmetic!(i32, atomic::AtomicI32, "let a = AtomicCell::new(7i32);"); - impl_arithmetic!(u64, atomic::AtomicU64, "let a = AtomicCell::new(7u64);"); - impl_arithmetic!(i64, atomic::AtomicI64, "let a = AtomicCell::new(7i64);"); - } else { - impl_arithmetic!(u8, "let a = AtomicCell::new(7u8);"); - impl_arithmetic!(i8, "let a = AtomicCell::new(7i8);"); - impl_arithmetic!(u16, "let a = AtomicCell::new(7u16);"); - impl_arithmetic!(i16, "let a = AtomicCell::new(7i16);"); - impl_arithmetic!(u32, "let a = AtomicCell::new(7u32);"); - impl_arithmetic!(i32, "let a = AtomicCell::new(7i32);"); - impl_arithmetic!(u64, "let a = AtomicCell::new(7u64);"); - impl_arithmetic!(i64, "let a = AtomicCell::new(7i64);"); - } -} - -impl_arithmetic!( - usize, - atomic::AtomicUsize, - "let a = AtomicCell::new(7usize);" -); -impl_arithmetic!( - isize, - atomic::AtomicIsize, - "let a = AtomicCell::new(7isize);" -); - -impl AtomicCell { - /// Applies logical "and" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(true); - /// - /// assert_eq!(a.fetch_and(true), true); - /// assert_eq!(a.load(), true); - /// - /// assert_eq!(a.fetch_and(false), true); - /// assert_eq!(a.load(), false); - /// ``` - #[inline] - pub fn fetch_and(&self, val: bool) -> bool { - let a = unsafe { &*(self.value.get() as *const AtomicBool) }; - a.fetch_and(val, Ordering::SeqCst) - } - - /// Applies logical "or" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(false); - /// - /// assert_eq!(a.fetch_or(false), false); - /// assert_eq!(a.load(), false); - /// - /// assert_eq!(a.fetch_or(true), false); - /// assert_eq!(a.load(), true); - /// ``` - #[inline] - pub fn fetch_or(&self, val: bool) -> bool { - let a = unsafe { &*(self.value.get() as *const AtomicBool) }; - a.fetch_or(val, Ordering::SeqCst) - } - - /// Applies logical "xor" to the current value and returns the previous value. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::atomic::AtomicCell; - /// - /// let a = AtomicCell::new(true); - /// - /// assert_eq!(a.fetch_xor(false), true); - /// assert_eq!(a.load(), true); - /// - /// assert_eq!(a.fetch_xor(true), true); - /// assert_eq!(a.load(), false); - /// ``` - #[inline] - pub fn fetch_xor(&self, val: bool) -> bool { - let a = unsafe { &*(self.value.get() as *const AtomicBool) }; - a.fetch_xor(val, Ordering::SeqCst) - } -} - -impl Default for AtomicCell { - fn default() -> AtomicCell { - AtomicCell::new(T::default()) - } -} - -impl fmt::Debug for AtomicCell { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("AtomicCell") - .field("value", &self.load()) - .finish() - } -} - -/// Returns `true` if the two values are equal byte-for-byte. -fn byte_eq(a: &T, b: &T) -> bool { - unsafe { - let a = slice::from_raw_parts(a as *const _ as *const u8, mem::size_of::()); - let b = slice::from_raw_parts(b as *const _ as *const u8, mem::size_of::()); - a == b - } -} - -/// Returns `true` if values of type `A` can be transmuted into values of type `B`. -fn can_transmute() -> bool { - // Sizes must be equal, but alignment of `A` must be greater or equal than that of `B`. - mem::size_of::() == mem::size_of::() && mem::align_of::() >= mem::align_of::() -} - -/// A simple stamped lock. -struct Lock { - /// The current state of the lock. - /// - /// All bits except the least significant one hold the current stamp. When locked, the state - /// equals 1 and doesn't contain a valid stamp. - state: AtomicUsize, -} - -impl Lock { - /// If not locked, returns the current stamp. - /// - /// This method should be called before optimistic reads. - #[inline] - fn optimistic_read(&self) -> Option { - let state = self.state.load(Ordering::Acquire); - if state == 1 { - None - } else { - Some(state) - } - } - - /// Returns `true` if the current stamp is equal to `stamp`. - /// - /// This method should be called after optimistic reads to check whether they are valid. The - /// argument `stamp` should correspond to the one returned by method `optimistic_read`. - #[inline] - fn validate_read(&self, stamp: usize) -> bool { - atomic::fence(Ordering::Acquire); - self.state.load(Ordering::Relaxed) == stamp - } - - /// Grabs the lock for writing. - #[inline] - fn write(&'static self) -> WriteGuard { - let mut step = 0usize; - - loop { - let previous = self.state.swap(1, Ordering::Acquire); - - if previous != 1 { - atomic::fence(Ordering::Release); - - return WriteGuard { - lock: self, - state: previous, - }; - } - - if step < 10 { - atomic::spin_loop_hint(); - } else { - #[cfg(not(feature = "std"))] - atomic::spin_loop_hint(); - - #[cfg(feature = "std")] - ::std::thread::yield_now(); - } - - step = step.wrapping_add(1); - } - } -} - -/// A RAII guard that releases the lock and increments the stamp when dropped. -struct WriteGuard { - /// The parent lock. - lock: &'static Lock, - - /// The stamp before locking. - state: usize, -} - -impl WriteGuard { - /// Releases the lock without incrementing the stamp. - #[inline] - fn abort(self) { - self.lock.state.store(self.state, Ordering::Release); - } -} - -impl Drop for WriteGuard { - #[inline] - fn drop(&mut self) { - // Release the lock and increment the stamp. - self.lock - .state - .store(self.state.wrapping_add(2), Ordering::Release); - } -} - -/// Returns a reference to the global lock associated with the `AtomicCell` at address `addr`. -/// -/// This function is used to protect atomic data which doesn't fit into any of the primitive atomic -/// types in `std::sync::atomic`. Operations on such atomics must therefore use a global lock. -/// -/// However, there is not only one global lock but an array of many locks, and one of them is -/// picked based on the given address. Having many locks reduces contention and improves -/// scalability. -#[inline] -#[must_use] -fn lock(addr: usize) -> &'static Lock { - // The number of locks is prime. - const LEN: usize = 97; - - const L: Lock = Lock { - state: AtomicUsize::new(0), - }; - static LOCKS: [Lock; LEN] = [ - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, - L, L, L, L, L, L, L, - ]; - - // If the modulus is a constant number, the compiler will use crazy math to transform this into - // a sequence of cheap arithmetic operations rather than using the slow modulo instruction. - &LOCKS[addr % LEN] -} - -/// An atomic `()`. -/// -/// All operations are noops. -struct AtomicUnit; - -impl AtomicUnit { - #[inline] - fn load(&self, _order: Ordering) {} - - #[inline] - fn store(&self, _val: (), _order: Ordering) {} - - #[inline] - fn swap(&self, _val: (), _order: Ordering) {} - - #[inline] - fn compare_exchange_weak( - &self, - _current: (), - _new: (), - _success: Ordering, - _failure: Ordering, - ) -> Result<(), ()> { - Ok(()) - } -} - -macro_rules! atomic { - // If values of type `$t` can be transmuted into values of the primitive atomic type `$atomic`, - // declares variable `$a` of type `$atomic` and executes `$atomic_op`, breaking out of the loop. - (@check, $t:ty, $atomic:ty, $a:ident, $atomic_op:expr) => { - if can_transmute::<$t, $atomic>() { - let $a: &$atomic; - break $atomic_op; - } - }; - - // If values of type `$t` can be transmuted into values of a primitive atomic type, declares - // variable `$a` of that type and executes `$atomic_op`. Otherwise, just executes - // `$fallback_op`. - ($t:ty, $a:ident, $atomic_op:expr, $fallback_op:expr) => { - loop { - atomic!(@check, $t, AtomicUnit, $a, $atomic_op); - atomic!(@check, $t, atomic::AtomicUsize, $a, $atomic_op); - - #[cfg(feature = "nightly")] - { - #[cfg(target_has_atomic = "8")] - atomic!(@check, $t, atomic::AtomicU8, $a, $atomic_op); - #[cfg(target_has_atomic = "16")] - atomic!(@check, $t, atomic::AtomicU16, $a, $atomic_op); - #[cfg(target_has_atomic = "32")] - atomic!(@check, $t, atomic::AtomicU32, $a, $atomic_op); - #[cfg(target_has_atomic = "64")] - atomic!(@check, $t, atomic::AtomicU64, $a, $atomic_op); - } - - break $fallback_op; - } - }; -} - -/// Returns `true` if operations on `AtomicCell` are lock-free. -fn atomic_is_lock_free() -> bool { - atomic! { T, _a, true, false } -} - -/// Atomically reads data from `src`. -/// -/// This operation uses the `SeqCst` ordering. If possible, an atomic instructions is used, and a -/// global lock otherwise. -unsafe fn atomic_load(src: *mut T) -> T -where - T: Copy, -{ - atomic! { - T, a, - { - a = &*(src as *const _ as *const _); - mem::transmute_copy(&a.load(Ordering::SeqCst)) - }, - { - let lock = lock(src as usize); - - // Try doing an optimistic read first. - if let Some(stamp) = lock.optimistic_read() { - // We need a volatile read here because other threads might concurrently modify the - // value. In theory, data races are *always* UB, even if we use volatile reads and - // discard the data when a data race is detected. The proper solution would be to - // do atomic reads and atomic writes, but we can't atomically read and write all - // kinds of data since `AtomicU8` is not available on stable Rust yet. - let val = ptr::read_volatile(src); - - if lock.validate_read(stamp) { - return val; - } - } - - // Grab a regular write lock so that writers don't starve this load. - let guard = lock.write(); - let val = ptr::read(src); - // The value hasn't been changed. Drop the guard without incrementing the stamp. - guard.abort(); - val - } - } -} - -/// Atomically writes `val` to `dst`. -/// -/// This operation uses the `SeqCst` ordering. If possible, an atomic instructions is used, and a -/// global lock otherwise. -unsafe fn atomic_store(dst: *mut T, val: T) { - atomic! { - T, a, - { - a = &*(dst as *const _ as *const _); - let res = a.store(mem::transmute_copy(&val), Ordering::SeqCst); - mem::forget(val); - res - }, - { - let _guard = lock(dst as usize).write(); - ptr::write(dst, val) - } - } -} - -/// Atomically swaps data at `dst` with `val`. -/// -/// This operation uses the `SeqCst` ordering. If possible, an atomic instructions is used, and a -/// global lock otherwise. -unsafe fn atomic_swap(dst: *mut T, val: T) -> T { - atomic! { - T, a, - { - a = &*(dst as *const _ as *const _); - let res = mem::transmute_copy(&a.swap(mem::transmute_copy(&val), Ordering::SeqCst)); - mem::forget(val); - res - }, - { - let _guard = lock(dst as usize).write(); - ptr::replace(dst, val) - } - } -} - -/// Atomically compares data at `dst` to `current` and, if equal byte-for-byte, exchanges data at -/// `dst` with `new`. -/// -/// Returns the old value on success, or the current value at `dst` on failure. -/// -/// This operation uses the `SeqCst` ordering. If possible, an atomic instructions is used, and a -/// global lock otherwise. -unsafe fn atomic_compare_exchange_weak(dst: *mut T, current: T, new: T) -> Result -where - T: Copy, -{ - atomic! { - T, a, - { - a = &*(dst as *const _ as *const _); - let res = a.compare_exchange_weak( - mem::transmute_copy(¤t), - mem::transmute_copy(&new), - Ordering::SeqCst, - Ordering::SeqCst, - ); - match res { - Ok(v) => Ok(mem::transmute_copy(&v)), - Err(v) => Err(mem::transmute_copy(&v)), - } - }, - { - let guard = lock(dst as usize).write(); - - if byte_eq(&*dst, ¤t) { - Ok(ptr::replace(dst, new)) - } else { - let val = ptr::read(dst); - // The value hasn't been changed. Drop the guard without incrementing the stamp. - guard.abort(); - Err(val) - } - } - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/lib.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/lib.rs deleted file mode 100644 index 68ae831..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/lib.rs +++ /dev/null @@ -1,131 +0,0 @@ -//! Crossbeam supports concurrent programming, especially focusing on memory -//! management, synchronization, and non-blocking data structures. -//! -//! Crossbeam consists of several submodules: -//! -//! - `atomic` for **enhancing `std::sync` API**. `AtomicConsume` provides -//! C/C++11-style "consume" atomic operations (re-exported from -//! [`crossbeam-utils`]). `ArcCell` provides atomic storage and retrieval of -//! `Arc`. -//! -//! - `utils` and `thread` for **utilities**, re-exported from [`crossbeam-utils`]. -//! The "scoped" thread API in `thread` makes it possible to spawn threads that -//! share stack data with their parents. The `utils::CachePadded` struct inserts -//! padding to align data with the size of a cacheline. This crate also seeks to -//! expand the standard library's few synchronization primitives (locks, -//! barriers, etc) to include advanced/niche primitives, as well as userspace -//! alternatives. -//! -//! - `epoch` for **memory management**, re-exported from [`crossbeam-epoch`]. -//! Because non-blocking data structures avoid global synchronization, it is not -//! easy to tell when internal data can be safely freed. The crate provides -//! generic, easy to use, and high-performance APIs for managing memory in these -//! cases. We plan to support other memory management schemes, e.g. hazard -//! pointers (HP) and quiescent state-based reclamation (QSBR). -//! -//! - **Concurrent data structures** which are non-blocking and much superior to -//! wrapping sequential ones with a `Mutex`. Crossbeam currently provides -//! channels (re-exported from [`crossbeam-channel`]), deques -//! (re-exported from [`crossbeam-deque`]), queues, and stacks. Ultimately the -//! goal is to also include bags, sets and maps. - -#![warn(missing_docs)] -// #![warn(missing_debug_implementations)] // TODO: Uncomment this. -#![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(feature = "nightly", feature(alloc))] -#![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))] -#![cfg_attr(feature = "nightly", feature(integer_atomics))] - -#[macro_use] -extern crate cfg_if; -#[cfg(feature = "std")] -extern crate core; - -cfg_if! { - if #[cfg(feature = "nightly")] { - extern crate alloc; - } else { - mod alloc { - extern crate std; - pub use self::std::*; - } - } -} - -mod _epoch { - pub extern crate crossbeam_epoch; -} -pub use _epoch::crossbeam_epoch as epoch; - -mod arc_cell; -mod atomic_cell; - -extern crate crossbeam_utils; - -/// Additional utilities for atomics. -pub mod atomic { - pub use arc_cell::ArcCell; - pub use atomic_cell::AtomicCell; - pub use crossbeam_utils::atomic::AtomicConsume; -} - -/// Utilities for concurrent programming. -/// -/// See [the `crossbeam-utils` crate](https://github.com/crossbeam-rs/crossbeam-utils) for more -/// information. -pub mod utils { - pub use crossbeam_utils::CachePadded; -} - -cfg_if! { - if #[cfg(feature = "std")] { - pub use crossbeam_utils::thread; - - // Export `crossbeam_utils::thread::scope` into the crate root because it's become an - // established pattern. - pub use crossbeam_utils::thread::scope; - - mod _deque { - pub extern crate crossbeam_deque; - } - pub use _deque::crossbeam_deque as deque; - - mod _channel { - pub extern crate crossbeam_channel; - pub use self::crossbeam_channel::*; - } - pub use _channel::crossbeam_channel as channel; - - // HACK(stjepang): This is the only way to reexport `select!` in Rust older than 1.30.0 - #[doc(hidden)] - pub use _channel::*; - - #[macro_use] - extern crate lazy_static; - extern crate num_cpus; - extern crate parking_lot; - - mod ms_queue; - mod seg_queue; - mod sharded_lock; - mod treiber_stack; - mod wait_group; - - /// Concurrent queues. - pub mod queue { - pub use ms_queue::MsQueue; - pub use seg_queue::SegQueue; - } - - /// Concurrent stacks. - pub mod stack { - pub use treiber_stack::TreiberStack; - } - - /// Utilities for thread synchronization. - pub mod sync { - pub use sharded_lock::{ShardedLock, ShardedLockReadGuard, ShardedLockWriteGuard}; - pub use wait_group::WaitGroup; - } - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/ms_queue.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/ms_queue.rs deleted file mode 100644 index 49a4417..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/ms_queue.rs +++ /dev/null @@ -1,557 +0,0 @@ -use std::mem::{self, ManuallyDrop}; -use std::ptr; -use std::sync::atomic::AtomicBool; -use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; -use std::thread::{self, Thread}; - -use epoch::{self, Atomic, Owned, Shared}; -use utils::CachePadded; - -/// A Michael-Scott lock-free queue, with support for blocking `pop`s. -/// -/// Usable with any number of producers and consumers. -// The representation here is a singly-linked list, with a sentinel -// node at the front. In general the `tail` pointer may lag behind the -// actual tail. Non-sentinel nodes are either all `Data` or all -// `Blocked` (requests for data from blocked threads). -#[derive(Debug)] -pub struct MsQueue { - head: CachePadded>>, - tail: CachePadded>>, -} - -#[derive(Debug)] -struct Node { - payload: Payload, - next: Atomic>, -} - -#[derive(Debug)] -enum Payload { - /// A node with actual data that can be popped. - Data(ManuallyDrop), - /// A node representing a blocked request for data. - Blocked(*mut Signal), -} - -/// A blocked request for data, which includes a slot to write the data. -#[derive(Debug)] -struct Signal { - /// Thread to unpark when data is ready. - thread: Thread, - /// The actual data, when available. - data: Option, - /// Is the data ready? Needed to cope with spurious wakeups. - ready: AtomicBool, -} - -impl Node { - fn is_data(&self) -> bool { - if let Payload::Data(_) = self.payload { - true - } else { - false - } - } -} - -// Any particular `T` should never accessed concurrently, so no need -// for Sync. -unsafe impl Sync for MsQueue {} -unsafe impl Send for MsQueue {} - -impl MsQueue { - /// Create a new, empty queue. - pub fn new() -> MsQueue { - let q = MsQueue { - head: CachePadded::new(Atomic::null()), - tail: CachePadded::new(Atomic::null()), - }; - let sentinel = Owned::new(Node { - payload: Payload::Data(unsafe { mem::uninitialized() }), - next: Atomic::null(), - }); - let guard = epoch::pin(); - let sentinel = sentinel.into_shared(&guard); - q.head.store(sentinel, Relaxed); - q.tail.store(sentinel, Relaxed); - q - } - - #[inline(always)] - /// Attempt to atomically place `n` into the `next` pointer of `onto`. - /// - /// If unsuccessful, returns ownership of `n`, possibly updating - /// the queue's `tail` pointer. - fn push_internal( - &self, - guard: &epoch::Guard, - onto: Shared>, - n: Owned>, - ) -> Result<(), Owned>> { - // is `onto` the actual tail? - let next_atomic = &unsafe { onto.as_ref() }.unwrap().next; - let next_shared = next_atomic.load(Acquire, guard); - if unsafe { next_shared.as_ref() }.is_some() { - // if not, try to "help" by moving the tail pointer forward - let _ = self.tail.compare_and_set(onto, next_shared, Release, guard); - Err(n) - } else { - // looks like the actual tail; attempt to link in `n` - next_atomic - .compare_and_set(Shared::null(), n, Release, guard) - .map(|shared| { - // try to move the tail pointer forward - let _ = self.tail.compare_and_set(onto, shared, Release, guard); - }).map_err(|e| e.new) - } - } - - /// Add `t` to the back of the queue, possibly waking up threads - /// blocked on `pop`. - pub fn push(&self, t: T) { - /// We may or may not need to allocate a node; once we do, - /// we cache that allocation. - enum Cache { - Data(T), - Node(Owned>), - } - - impl Cache { - /// Extract the node if cached, or allocate if not. - fn into_node(self) -> Owned> { - match self { - Cache::Data(t) => Owned::new(Node { - payload: Payload::Data(ManuallyDrop::new(t)), - next: Atomic::null(), - }), - Cache::Node(n) => n, - } - } - - /// Extract the data from the cache, deallocating any cached node. - fn into_data(self) -> T { - match self { - Cache::Data(t) => t, - Cache::Node(node) => match (*node.into_box()).payload { - Payload::Data(t) => ManuallyDrop::into_inner(t), - _ => unreachable!(), - }, - } - } - } - - let mut cache = Cache::Data(t); // don't allocate up front - let guard = epoch::pin(); - - loop { - // We push onto the tail, so we'll start optimistically by looking - // there first. - let tail_shared = self.tail.load(Acquire, &guard); - let tail_ref = unsafe { tail_shared.as_ref() }.unwrap(); - - // Is the queue in Data mode (empty queues can be viewed as either mode)? - if tail_ref.is_data() || self.head.load(Relaxed, &guard) == tail_shared { - // Attempt to push onto the `tail` snapshot; fails if - // `tail.next` has changed, which will always be the case if the - // queue has transitioned to blocking mode. - match self.push_internal(&guard, tail_shared, cache.into_node()) { - Ok(_) => return, - Err(n) => { - // replace the cache, retry whole thing - cache = Cache::Node(n) - } - } - } else { - // Queue is in blocking mode. Attempt to unblock a thread. - let head_shared = self.head.load(Acquire, &guard); - let head = unsafe { head_shared.as_ref() }.unwrap(); - // Get a handle on the first blocked node. Racy, so queue might - // be empty or in data mode by the time we see it. - let next_shared = head.next.load(Acquire, &guard); - let request = unsafe { next_shared.as_ref() }.and_then(|next| match next.payload { - Payload::Blocked(signal) => Some((next_shared, signal)), - Payload::Data(_) => None, - }); - if let Some((blocked_node, signal)) = request { - // race to dequeue the node - if self - .head - .compare_and_set(head_shared, blocked_node, Release, &guard) - .is_ok() - { - unsafe { - // signal the thread - (*signal).data = Some(cache.into_data()); - let thread = (*signal).thread.clone(); - - (*signal).ready.store(true, Release); - thread.unpark(); - guard.defer_destroy(head_shared); - return; - } - } - } - } - } - } - - // Attempt to pop a data node. `Ok(None)` if queue is empty or in blocking - // mode; `Err(())` if lost race to pop. - #[inline(always)] - fn pop_internal(&self, guard: &epoch::Guard) -> Result, ()> { - let head_shared = self.head.load(Acquire, guard); - let head = unsafe { head_shared.as_ref() }.unwrap(); - let next_shared = head.next.load(Acquire, guard); - if let Some(next) = unsafe { next_shared.as_ref() } { - if let Payload::Data(ref t) = next.payload { - unsafe { - if self - .head - .compare_and_set(head_shared, next_shared, Release, guard) - .is_ok() - { - guard.defer_destroy(head_shared); - Ok(Some(ManuallyDrop::into_inner(ptr::read(t)))) - } else { - Err(()) - } - } - } else { - Ok(None) - } - } else { - Ok(None) - } - } - - /// Check if this queue is empty. - pub fn is_empty(&self) -> bool { - let guard = epoch::pin(); - let head = unsafe { self.head.load(Acquire, &guard).as_ref() }.unwrap(); - - if let Some(next) = unsafe { head.next.load(Acquire, &guard).as_ref() } { - if let Payload::Data(_) = next.payload { - false - } else { - true - } - } else { - true - } - } - - /// Attempt to dequeue from the front. - /// - /// Returns `None` if the queue is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - if let Ok(r) = self.pop_internal(&guard) { - return r; - } - } - } - - /// Dequeue an element from the front of the queue, blocking if the queue is - /// empty. - pub fn pop(&self) -> T { - let guard = epoch::pin(); - - // Fast path: keep retrying until we observe that the queue has no data, - // avoiding the allocation of a blocked node. - loop { - match self.pop_internal(&guard) { - Ok(Some(r)) => { - return r; - } - Ok(None) => { - break; - } - Err(()) => {} - } - } - - // The signal gets to live on the stack, since this stack frame will be - // blocked until receiving the signal. - let mut signal = Signal { - thread: thread::current(), - data: None, - ready: AtomicBool::new(false), - }; - - // Go ahead and allocate the blocked node; chances are, we'll need it. - let mut node = Owned::new(Node { - payload: Payload::Blocked(&mut signal), - next: Atomic::null(), - }); - - loop { - // try a normal pop - if let Ok(Some(r)) = self.pop_internal(&guard) { - return r; - } - - // At this point, we believe the queue is empty/blocked. - // Snapshot the tail, onto which we want to push a blocked node. - let tail_shared = self.tail.load(Acquire, &guard); - let tail = unsafe { tail_shared.as_ref() }.unwrap(); - - // Double-check that we're in blocking mode - if tail.is_data() { - // The current tail is in data mode, so we probably need to abort. - // BUT, it might be the sentinel, so check for that first. - let head_shared = self.head.load(Relaxed, &guard); - if tail.is_data() && tail_shared != head_shared { - continue; - } - } - - // At this point, the tail snapshot is either a blocked node deep in - // the queue, the sentinel, or no longer accessible from the queue. - // In *ALL* of these cases, if we succeed in pushing onto the - // snapshot, we know we are maintaining the core invariant: all - // reachable, non-sentinel nodes have the same payload mode, in this - // case, blocked. - match self.push_internal(&guard, tail_shared, node) { - Ok(()) => break, - Err(n) => { - node = n; - } - } - } - - drop(guard); - - while !signal.ready.load(Acquire) { - thread::park(); - } - signal.data.unwrap() - } -} - -impl Drop for MsQueue { - fn drop(&mut self) { - while self.try_pop().is_some() {} - - // Destroy the remaining sentinel node. - let guard = epoch::pin(); - let sentinel = self.head.load(Relaxed, &guard).as_raw() as *mut Node; - unsafe { - drop(Vec::from_raw_parts(sentinel, 0, 1)); - } - } -} - -impl Default for MsQueue { - fn default() -> Self { - MsQueue::new() - } -} - -#[cfg(test)] -mod test { - const CONC_COUNT: i64 = 1000000; - - use super::*; - use scope; - - #[test] - fn push_try_pop_1() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(37)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_2() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - q.push(48); - assert_eq!(q.try_pop(), Some(37)); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(48)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_seq() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.try_pop(), Some(i)); - } - assert!(q.is_empty()); - } - - #[test] - fn push_pop_1() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.pop(), 37); - assert!(q.is_empty()); - } - - #[test] - fn push_pop_2() { - let q: MsQueue = MsQueue::new(); - q.push(37); - q.push(48); - assert_eq!(q.pop(), 37); - assert_eq!(q.pop(), 48); - } - - #[test] - fn push_pop_many_seq() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.pop(), i); - } - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_spsc() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - - scope(|scope| { - scope.spawn(|_| { - let mut next = 0; - - while next < CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert_eq!(elem, next); - next += 1; - } - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }).unwrap(); - } - - #[test] - fn push_try_pop_many_spmc() { - fn recv(_t: i32, q: &MsQueue) { - let mut cur = -1; - for _i in 0..CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert!(elem > cur); - cur = elem; - - if cur == CONC_COUNT - 1 { - break; - } - } - } - } - - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - let qr = &q; - scope(|scope| { - for i in 0..3 { - scope.spawn(|_| recv(i, qr)); - } - - scope.spawn(|_| { - for i in 0..CONC_COUNT { - q.push(i); - } - }); - }).unwrap(); - } - - #[test] - fn push_try_pop_many_mpmc() { - enum LR { - Left(i64), - Right(i64), - } - - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - - scope(|scope| { - for _t in 0..2 { - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Left(i)) - } - }); - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Right(i)) - } - }); - scope.spawn(|_| { - let mut vl = vec![]; - let mut vr = vec![]; - for _i in 0..CONC_COUNT { - match q.try_pop() { - Some(LR::Left(x)) => vl.push(x), - Some(LR::Right(x)) => vr.push(x), - _ => {} - } - } - - let mut vl2 = vl.clone(); - let mut vr2 = vr.clone(); - vl2.sort(); - vr2.sort(); - - assert_eq!(vl, vl2); - assert_eq!(vr, vr2); - }); - } - }).unwrap(); - } - - #[test] - fn push_pop_many_spsc() { - let q: MsQueue = MsQueue::new(); - - scope(|scope| { - scope.spawn(|_| { - let mut next = 0; - while next < CONC_COUNT { - assert_eq!(q.pop(), next); - next += 1; - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }).unwrap(); - assert!(q.is_empty()); - } - - #[test] - fn is_empty_dont_pop() { - let q: MsQueue = MsQueue::new(); - q.push(20); - q.push(20); - assert!(!q.is_empty()); - assert!(!q.is_empty()); - assert!(q.try_pop().is_some()); - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/seg_queue.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/seg_queue.rs deleted file mode 100644 index dc9eac3..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/seg_queue.rs +++ /dev/null @@ -1,313 +0,0 @@ -use std::cell::UnsafeCell; -use std::cmp; -use std::fmt; -use std::mem::{self, ManuallyDrop}; -use std::ptr; -use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; -use std::sync::atomic::{AtomicBool, AtomicUsize}; - -use epoch::{self, Atomic, Owned}; - -const SEG_SIZE: usize = 32; - -/// A Michael-Scott queue that allocates "segments" (arrays of nodes) -/// for efficiency. -/// -/// Usable with any number of producers and consumers. -#[derive(Debug)] -pub struct SegQueue { - head: Atomic>, - tail: Atomic>, -} - -struct Segment { - low: AtomicUsize, - data: ManuallyDrop<[UnsafeCell<(T, AtomicBool)>; SEG_SIZE]>, - high: AtomicUsize, - next: Atomic>, -} - -impl fmt::Debug for Segment { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Segment {{ ... }}") - } -} - -unsafe impl Sync for Segment {} - -impl Segment { - fn new() -> Segment { - let rqueue = Segment { - data: unsafe { ManuallyDrop::new(mem::uninitialized()) }, - low: AtomicUsize::new(0), - high: AtomicUsize::new(0), - next: Atomic::null(), - }; - for val in rqueue.data.iter() { - unsafe { - (*val.get()).1 = AtomicBool::new(false); - } - } - rqueue - } -} - -impl SegQueue { - /// Create a new, empty queue. - pub fn new() -> SegQueue { - let q = SegQueue { - head: Atomic::null(), - tail: Atomic::null(), - }; - let sentinel = Owned::new(Segment::new()); - let guard = epoch::pin(); - let sentinel = sentinel.into_shared(&guard); - q.head.store(sentinel, Relaxed); - q.tail.store(sentinel, Relaxed); - q - } - - /// Add `t` to the back of the queue. - pub fn push(&self, t: T) { - let guard = epoch::pin(); - loop { - let tail = unsafe { self.tail.load(Acquire, &guard).as_ref() }.unwrap(); - if tail.high.load(Relaxed) >= SEG_SIZE { - continue; - } - let i = tail.high.fetch_add(1, Relaxed); - unsafe { - if i < SEG_SIZE { - let cell = (*tail).data.get_unchecked(i).get(); - ptr::write(&mut (*cell).0, t); - (*cell).1.store(true, Release); - - if i + 1 == SEG_SIZE { - let tail_new = Owned::new(Segment::new()).into_shared(&guard); - tail.next.store(tail_new, Release); - self.tail.store(tail_new, Release); - } - - return; - } - } - } - } - - /// Judge if the queue is empty. - /// - /// Returns `true` if the queue is empty. - pub fn is_empty(&self) -> bool { - let guard = epoch::pin(); - let head = self.head.load(Acquire, &guard); - let tail = self.tail.load(Acquire, &guard); - if head != tail { - return false; - } - - let head_ref = unsafe { head.as_ref() }.unwrap(); - let low = head_ref.low.load(Relaxed); - low >= cmp::min(head_ref.high.load(Relaxed), SEG_SIZE) - } - - /// Attempt to dequeue from the front. - /// - /// Returns `None` if the queue is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - let head_shared = self.head.load(Acquire, &guard); - let head = unsafe { head_shared.as_ref() }.unwrap(); - loop { - let low = head.low.load(Relaxed); - if low >= cmp::min(head.high.load(Relaxed), SEG_SIZE) { - break; - } - if head.low.compare_and_swap(low, low + 1, Relaxed) == low { - unsafe { - let cell = (*head).data.get_unchecked(low).get(); - loop { - if (*cell).1.load(Acquire) { - break; - } - } - if low + 1 == SEG_SIZE { - loop { - let next_shared = head.next.load(Acquire, &guard); - if next_shared.as_ref().is_some() { - self.head.store(next_shared, Release); - guard.defer_destroy(head_shared); - break; - } - } - } - return Some(ptr::read(&(*cell).0)); - } - } - } - if head.next.load(Relaxed, &guard).is_null() { - return None; - } - } - } -} - -impl Drop for SegQueue { - fn drop(&mut self) { - while self.try_pop().is_some() {} - - // Destroy the remaining sentinel segment. - let guard = epoch::pin(); - let sentinel = self.head.load(Relaxed, &guard).as_raw() as *mut Segment; - unsafe { - drop(Vec::from_raw_parts(sentinel, 0, 1)); - } - } -} - -impl Default for SegQueue { - fn default() -> Self { - SegQueue::new() - } -} - -#[cfg(test)] -mod test { - const CONC_COUNT: i64 = 1000000; - - use super::*; - use scope; - - #[test] - fn push_pop_1() { - let q: SegQueue = SegQueue::new(); - q.push(37); - assert_eq!(q.try_pop(), Some(37)); - } - - #[test] - fn push_pop_2() { - let q: SegQueue = SegQueue::new(); - q.push(37); - q.push(48); - assert_eq!(q.try_pop(), Some(37)); - assert_eq!(q.try_pop(), Some(48)); - } - - #[test] - fn push_pop_empty_check() { - let q: SegQueue = SegQueue::new(); - assert_eq!(q.is_empty(), true); - q.push(42); - assert_eq!(q.is_empty(), false); - assert_eq!(q.try_pop(), Some(42)); - assert_eq!(q.is_empty(), true); - } - - #[test] - fn push_pop_many_seq() { - let q: SegQueue = SegQueue::new(); - for i in 0..200 { - q.push(i) - } - for i in 0..200 { - assert_eq!(q.try_pop(), Some(i)); - } - } - - #[test] - fn push_pop_many_spsc() { - let q: SegQueue = SegQueue::new(); - - scope(|scope| { - scope.spawn(|_| { - let mut next = 0; - - while next < CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert_eq!(elem, next); - next += 1; - } - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }).unwrap(); - } - - #[test] - fn push_pop_many_spmc() { - fn recv(_t: i32, q: &SegQueue) { - let mut cur = -1; - for _i in 0..CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert!(elem > cur); - cur = elem; - - if cur == CONC_COUNT - 1 { - break; - } - } - } - } - - let q: SegQueue = SegQueue::new(); - scope(|scope| { - for i in 0..3 { - scope.spawn(|_| recv(i, &q)); - } - - scope.spawn(|_| { - for i in 0..CONC_COUNT { - q.push(i); - } - }); - }).unwrap(); - } - - #[test] - fn push_pop_many_mpmc() { - enum LR { - Left(i64), - Right(i64), - } - - let q: SegQueue = SegQueue::new(); - - scope(|scope| { - for _t in 0..2 { - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Left(i)) - } - }); - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Right(i)) - } - }); - scope.spawn(|_| { - let mut vl = vec![]; - let mut vr = vec![]; - for _i in 0..CONC_COUNT { - match q.try_pop() { - Some(LR::Left(x)) => vl.push(x), - Some(LR::Right(x)) => vr.push(x), - _ => {} - } - } - - let mut vl2 = vl.clone(); - let mut vr2 = vr.clone(); - vl2.sort(); - vr2.sort(); - - assert_eq!(vl, vl2); - assert_eq!(vr, vr2); - }); - } - }).unwrap(); - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/sharded_lock.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/sharded_lock.rs deleted file mode 100644 index a8709a1..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/sharded_lock.rs +++ /dev/null @@ -1,217 +0,0 @@ -//! A scalable reader-writer lock. -//! -//! This implementation makes read operations faster and more scalable due to less contention, -//! while making write operations slower. It also incurs much higher memory overhead than -//! traditional reader-writer locks. - -use std::cell::UnsafeCell; -use std::collections::HashMap; -use std::marker::PhantomData; -use std::mem; -use std::ops::{Deref, DerefMut}; -use std::thread::{self, ThreadId}; - -use crossbeam_utils::CachePadded; -use num_cpus; -use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; - -/// A scalable reader-writer lock. -/// -/// This type of lock allows a number of readers or at most one writer at any point in time. The -/// write portion of this lock typically allows modification of the underlying data (exclusive -/// access) and the read portion of this lock typically allows for read-only access (shared -/// access). -/// -/// This reader-writer lock differs from typical implementations in that it internally creates a -/// list of reader-writer locks called 'shards'. Shards are aligned and padded to the cache line -/// size. -/// -/// Read operations lock only one shard specific to the current thread, while write operations lock -/// every shard in succession. This strategy makes concurrent read operations faster due to less -/// contention, but write operations are slower due to increased amount of locking. -pub struct ShardedLock { - /// A list of locks protecting the internal data. - shards: Vec>>, - - /// The internal data. - value: UnsafeCell, -} - -unsafe impl Send for ShardedLock {} -unsafe impl Sync for ShardedLock {} - -impl ShardedLock { - /// Creates a new `ShardedLock` initialized with `value`. - pub fn new(value: T) -> ShardedLock { - // The number of shards is a power of two so that the modulo operation in `read` becomes a - // simple bitwise "and". - let num_shards = num_cpus::get().next_power_of_two(); - - ShardedLock { - shards: (0..num_shards) - .map(|_| CachePadded::new(RwLock::new(()))) - .collect(), - value: UnsafeCell::new(value), - } - } - - /// Locks with shared read access, blocking the current thread until it can be acquired. - /// - /// The calling thread will be blocked until there are no more writers which hold the lock. - /// There may be other readers currently inside the lock when this method returns. This method - /// does not provide any guarantees with respect to the ordering of whether contentious readers - /// or writers will acquire the lock first. - /// - /// Returns an RAII guard which will drop the read access of this lock when dropped. - pub fn read(&self) -> ShardedLockReadGuard { - // Take the current thread index and map it to a shard index. Thread indices will tend to - // distribute shards among threads equally, thus reducing contention due to read-locking. - let current_index = current_index().unwrap_or(0); - let shard_index = current_index & (self.shards.len() - 1); - - ShardedLockReadGuard { - parent: self, - _guard: self.shards[shard_index].read(), - _marker: PhantomData, - } - } - - /// Locks with exclusive write access, blocking the current thread until it can be acquired. - /// - /// This function will not return while other writers or other readers currently have access to - /// the lock. - /// - /// Returns an RAII guard which will drop the write access of this lock when dropped. - pub fn write(&self) -> ShardedLockWriteGuard { - // Write-lock each shard in succession. - for shard in &self.shards { - // The write guard is forgotten, but the lock will be manually unlocked in `drop`. - mem::forget(shard.write()); - } - - ShardedLockWriteGuard { - parent: self, - _marker: PhantomData, - } - } -} - -/// A guard used to release the shared read access of a `ShardedLock` when dropped. -pub struct ShardedLockReadGuard<'a, T: 'a> { - parent: &'a ShardedLock, - _guard: RwLockReadGuard<'a, ()>, - _marker: PhantomData>, -} - -unsafe impl<'a, T: Sync> Sync for ShardedLockReadGuard<'a, T> {} - -impl<'a, T> Deref for ShardedLockReadGuard<'a, T> { - type Target = T; - - fn deref(&self) -> &T { - unsafe { &*self.parent.value.get() } - } -} - -/// A guard used to release the exclusive write access of a `ShardedLock` when dropped. -pub struct ShardedLockWriteGuard<'a, T: 'a> { - parent: &'a ShardedLock, - _marker: PhantomData>, -} - -unsafe impl<'a, T: Sync> Sync for ShardedLockWriteGuard<'a, T> {} - -impl<'a, T> Drop for ShardedLockWriteGuard<'a, T> { - fn drop(&mut self) { - // Unlock the shards in reverse order of locking. - for shard in self.parent.shards.iter().rev() { - unsafe { - (**shard).force_unlock_write(); - } - } - } -} - -impl<'a, T> Deref for ShardedLockWriteGuard<'a, T> { - type Target = T; - - fn deref(&self) -> &T { - unsafe { &*self.parent.value.get() } - } -} - -impl<'a, T> DerefMut for ShardedLockWriteGuard<'a, T> { - fn deref_mut(&mut self) -> &mut T { - unsafe { &mut *self.parent.value.get() } - } -} - -/// Returns a `usize` that identifies the current thread. -/// -/// Each thread is associated with an 'index'. While there are no particular guarantees, indices -/// usually tend to be consecutive numbers between 0 and the number of running threads. -/// -/// Since this function accesses TLS, `None` might be returned if the current thread's TLS is -/// tearing down. -#[inline] -fn current_index() -> Option { - REGISTRATION.try_with(|reg| reg.index).ok() -} - -/// The global registry keeping track of registered threads and indices. -struct ThreadIndices { - /// Mapping from `ThreadId` to thread index. - mapping: HashMap, - - /// A list of free indices. - free_list: Vec, - - /// The next index to allocate if the free list is empty. - next_index: usize, -} - -lazy_static! { - static ref THREAD_INDICES: Mutex = Mutex::new(ThreadIndices { - mapping: HashMap::new(), - free_list: Vec::new(), - next_index: 0, - }); -} - -/// A registration of a thread with an index. -/// -/// When dropped, unregisters the thread and frees the reserved index. -struct Registration { - index: usize, - thread_id: ThreadId, -} - -impl Drop for Registration { - fn drop(&mut self) { - let mut indices = THREAD_INDICES.lock(); - indices.mapping.remove(&self.thread_id); - indices.free_list.push(self.index); - } -} - -thread_local! { - static REGISTRATION: Registration = { - let thread_id = thread::current().id(); - let mut indices = THREAD_INDICES.lock(); - - let index = match indices.free_list.pop() { - Some(i) => i, - None => { - let i = indices.next_index; - indices.next_index += 1; - i - } - }; - indices.mapping.insert(thread_id, index); - - Registration { - index, - thread_id, - } - }; -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/treiber_stack.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/treiber_stack.rs deleted file mode 100644 index 1fbd121..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/treiber_stack.rs +++ /dev/null @@ -1,140 +0,0 @@ -use std::mem::ManuallyDrop; -use std::ptr; -use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; - -use epoch::{self, Atomic, Owned}; - -/// Treiber's lock-free stack. -/// -/// Usable with any number of producers and consumers. -#[derive(Debug)] -pub struct TreiberStack { - head: Atomic>, -} - -#[derive(Debug)] -struct Node { - data: ManuallyDrop, - next: Atomic>, -} - -impl TreiberStack { - /// Create a new, empty stack. - pub fn new() -> TreiberStack { - TreiberStack { - head: Atomic::null(), - } - } - - /// Push `t` on top of the stack. - pub fn push(&self, t: T) { - let mut n = Owned::new(Node { - data: ManuallyDrop::new(t), - next: Atomic::null(), - }); - let guard = epoch::pin(); - loop { - let head = self.head.load(Relaxed, &guard); - n.next.store(head, Relaxed); - match self.head.compare_and_set(head, n, Release, &guard) { - Ok(_) => break, - Err(e) => n = e.new, - } - } - } - - /// Attempt to pop the top element of the stack. - /// - /// Returns `None` if the stack is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - let head_shared = self.head.load(Acquire, &guard); - match unsafe { head_shared.as_ref() } { - Some(head) => { - let next = head.next.load(Relaxed, &guard); - if self - .head - .compare_and_set(head_shared, next, Release, &guard) - .is_ok() - { - unsafe { - guard.defer_destroy(head_shared); - return Some(ManuallyDrop::into_inner(ptr::read(&(*head).data))); - } - } - } - None => return None, - } - } - } - - /// Check if this queue is empty. - pub fn is_empty(&self) -> bool { - let guard = epoch::pin(); - self.head.load(Acquire, &guard).is_null() - } -} - -impl Drop for TreiberStack { - fn drop(&mut self) { - while self.try_pop().is_some() {} - } -} - -impl Default for TreiberStack { - fn default() -> Self { - TreiberStack::new() - } -} - -#[cfg(test)] -mod test { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - use {epoch, thread}; - - #[test] - fn is_empty() { - let q: TreiberStack = TreiberStack::new(); - assert!(q.is_empty()); - q.push(20); - q.push(20); - assert!(!q.is_empty()); - assert!(!q.is_empty()); - assert!(q.try_pop().is_some()); - assert!(q.try_pop().is_some()); - assert!(q.is_empty()); - q.push(25); - assert!(!q.is_empty()); - } - - #[test] - fn no_double_drop() { - static DROP_COUNT: AtomicUsize = AtomicUsize::new(0); - - struct Dropper; - - impl Drop for Dropper { - fn drop(&mut self) { - DROP_COUNT.fetch_add(1, Ordering::SeqCst); - } - } - - const N_THREADS: usize = 8; - thread::scope(|s| { - for _ in 0..N_THREADS { - s.spawn(|_| { - let s: TreiberStack = TreiberStack::new(); - for _ in 0..4 { - s.push(Dropper); - } - drop(s); - epoch::pin().flush(); - }); - } - }).unwrap(); - - assert!(DROP_COUNT.load(Ordering::SeqCst) == N_THREADS * 4); - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/src/wait_group.rs b/third_party/cargo/vendor/crossbeam-0.5.0/src/wait_group.rs deleted file mode 100644 index 95755ab..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/src/wait_group.rs +++ /dev/null @@ -1,144 +0,0 @@ -use std::fmt; -use std::process; -use std::sync::Arc; - -use parking_lot::{Condvar, Mutex}; - -/// Enables multiple threads to synchronize the beginning or end of some computation. -/// -/// # Wait groups vs barriers -/// -/// `WaitGroup` is very similar to [`Barrier`], but there are a few differences: -/// -/// * `Barrier` needs to know the number of threads at construction, while `WaitGroup` is cloned to -/// register more threads. -/// -/// * A `Barrier` can be reused even after all threads have synchronized, while a `WaitGroup` -/// synchronizes threads only once. -/// -/// * All threads wait for others to reach the `Barrier`. With `WaitGroup`, each thread can choose -/// to either wait for other threads or to continue without blocking. -/// -/// # Examples -/// -/// ``` -/// use crossbeam::sync::WaitGroup; -/// use std::thread; -/// -/// // Create a new wait group. -/// let wg = WaitGroup::new(); -/// -/// for _ in 0..4 { -/// // Create another reference to the wait group. -/// let wg = wg.clone(); -/// -/// thread::spawn(move || { -/// // Do some work. -/// -/// // Drop the reference to the wait group. -/// drop(wg); -/// }); -/// } -/// -/// // Block until all threads have finished their work. -/// wg.wait(); -/// ``` -/// -/// [`Barrier`]: https://doc.rust-lang.org/std/sync/struct.Barrier.html -pub struct WaitGroup { - inner: Arc, -} - -/// Inner state of a `WaitGroup`. -struct Inner { - cvar: Condvar, - count: Mutex, -} - -impl WaitGroup { - /// Creates a new wait group and returns the single reference to it. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::sync::WaitGroup; - /// - /// let wg = WaitGroup::new(); - /// ``` - pub fn new() -> WaitGroup { - WaitGroup { - inner: Arc::new(Inner { - cvar: Condvar::new(), - count: Mutex::new(1), - }), - } - } - - /// Drops this reference and waits until all other references are dropped. - /// - /// # Examples - /// - /// ``` - /// use crossbeam::sync::WaitGroup; - /// use std::thread; - /// - /// let wg = WaitGroup::new(); - /// - /// thread::spawn({ - /// let wg = wg.clone(); - /// move || { - /// // Block until both threads have reached `wait()`. - /// wg.wait(); - /// } - /// }); - /// - /// // Block until both threads have reached `wait()`. - /// wg.wait(); - /// ``` - pub fn wait(self) { - if *self.inner.count.lock() == 1 { - return; - } - - let inner = self.inner.clone(); - drop(self); - - let mut count = inner.count.lock(); - while *count > 0 { - inner.cvar.wait(&mut count); - } - } -} - -impl Drop for WaitGroup { - fn drop(&mut self) { - let mut count = self.inner.count.lock(); - *count -= 1; - - if *count == 0 { - self.inner.cvar.notify_all(); - } - } -} - -impl Clone for WaitGroup { - fn clone(&self) -> WaitGroup { - let mut count = self.inner.count.lock(); - *count += 1; - - if *count > isize::max_value() as usize { - process::abort(); - } - - WaitGroup { - inner: self.inner.clone(), - } - } -} - -impl fmt::Debug for WaitGroup { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let count = self.inner.count.lock(); - write!(f, "WaitGroup {{ count: {:?} }}", *count) - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/tests/atomic_cell.rs b/third_party/cargo/vendor/crossbeam-0.5.0/tests/atomic_cell.rs deleted file mode 100644 index d17b985..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/tests/atomic_cell.rs +++ /dev/null @@ -1,208 +0,0 @@ -extern crate crossbeam; - -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::SeqCst; - -use crossbeam::atomic::AtomicCell; - -#[test] -fn is_lock_free() { - struct UsizeWrap(usize); - struct U8Wrap(bool); - - assert_eq!(AtomicCell::::is_lock_free(), true); - assert_eq!(AtomicCell::::is_lock_free(), true); - assert_eq!(AtomicCell::::is_lock_free(), true); - - assert_eq!(AtomicCell::::is_lock_free(), cfg!(feature = "nightly")); - assert_eq!( - AtomicCell::::is_lock_free(), - cfg!(feature = "nightly") - ); - assert_eq!( - AtomicCell::::is_lock_free(), - cfg!(feature = "nightly") - ); -} - -#[test] -fn drops_unit() { - static CNT: AtomicUsize = AtomicUsize::new(0); - CNT.store(0, SeqCst); - - #[derive(Debug, PartialEq, Eq)] - struct Foo(); - - impl Foo { - fn new() -> Foo { - CNT.fetch_add(1, SeqCst); - Foo() - } - } - - impl Drop for Foo { - fn drop(&mut self) { - CNT.fetch_sub(1, SeqCst); - } - } - - impl Default for Foo { - fn default() -> Foo { - Foo::new() - } - } - - let a = AtomicCell::new(Foo::new()); - - assert_eq!(a.swap(Foo::new()), Foo::new()); - assert_eq!(CNT.load(SeqCst), 1); - - a.store(Foo::new()); - assert_eq!(CNT.load(SeqCst), 1); - - assert_eq!(a.swap(Foo::default()), Foo::new()); - assert_eq!(CNT.load(SeqCst), 1); - - drop(a); - assert_eq!(CNT.load(SeqCst), 0); -} - -#[test] -fn drops_u8() { - static CNT: AtomicUsize = AtomicUsize::new(0); - CNT.store(0, SeqCst); - - #[derive(Debug, PartialEq, Eq)] - struct Foo(u8); - - impl Foo { - fn new(val: u8) -> Foo { - CNT.fetch_add(1, SeqCst); - Foo(val) - } - } - - impl Drop for Foo { - fn drop(&mut self) { - CNT.fetch_sub(1, SeqCst); - } - } - - impl Default for Foo { - fn default() -> Foo { - Foo::new(0) - } - } - - let a = AtomicCell::new(Foo::new(5)); - - assert_eq!(a.swap(Foo::new(6)), Foo::new(5)); - assert_eq!(a.swap(Foo::new(1)), Foo::new(6)); - assert_eq!(CNT.load(SeqCst), 1); - - a.store(Foo::new(2)); - assert_eq!(CNT.load(SeqCst), 1); - - assert_eq!(a.swap(Foo::default()), Foo::new(2)); - assert_eq!(CNT.load(SeqCst), 1); - - assert_eq!(a.swap(Foo::default()), Foo::new(0)); - assert_eq!(CNT.load(SeqCst), 1); - - drop(a); - assert_eq!(CNT.load(SeqCst), 0); -} - -#[test] -fn drops_usize() { - static CNT: AtomicUsize = AtomicUsize::new(0); - CNT.store(0, SeqCst); - - #[derive(Debug, PartialEq, Eq)] - struct Foo(usize); - - impl Foo { - fn new(val: usize) -> Foo { - CNT.fetch_add(1, SeqCst); - Foo(val) - } - } - - impl Drop for Foo { - fn drop(&mut self) { - CNT.fetch_sub(1, SeqCst); - } - } - - impl Default for Foo { - fn default() -> Foo { - Foo::new(0) - } - } - - let a = AtomicCell::new(Foo::new(5)); - - assert_eq!(a.swap(Foo::new(6)), Foo::new(5)); - assert_eq!(a.swap(Foo::new(1)), Foo::new(6)); - assert_eq!(CNT.load(SeqCst), 1); - - a.store(Foo::new(2)); - assert_eq!(CNT.load(SeqCst), 1); - - assert_eq!(a.swap(Foo::default()), Foo::new(2)); - assert_eq!(CNT.load(SeqCst), 1); - - assert_eq!(a.swap(Foo::default()), Foo::new(0)); - assert_eq!(CNT.load(SeqCst), 1); - - drop(a); - assert_eq!(CNT.load(SeqCst), 0); -} - -#[test] -fn modular_u8() { - #[derive(Clone, Copy, Eq, Debug, Default)] - struct Foo(u8); - - impl PartialEq for Foo { - fn eq(&self, other: &Foo) -> bool { - self.0 % 5 == other.0 % 5 - } - } - - let a = AtomicCell::new(Foo(1)); - - assert_eq!(a.load(), Foo(1)); - assert_eq!(a.swap(Foo(2)), Foo(11)); - assert_eq!(a.load(), Foo(52)); - - a.store(Foo(0)); - assert_eq!(a.compare_exchange(Foo(0), Foo(5)), Ok(Foo(100))); - assert_eq!(a.load().0, 5); - assert_eq!(a.compare_exchange(Foo(10), Foo(15)), Ok(Foo(100))); - assert_eq!(a.load().0, 15); -} - -#[test] -fn modular_usize() { - #[derive(Clone, Copy, Eq, Debug, Default)] - struct Foo(usize); - - impl PartialEq for Foo { - fn eq(&self, other: &Foo) -> bool { - self.0 % 5 == other.0 % 5 - } - } - - let a = AtomicCell::new(Foo(1)); - - assert_eq!(a.load(), Foo(1)); - assert_eq!(a.swap(Foo(2)), Foo(11)); - assert_eq!(a.load(), Foo(52)); - - a.store(Foo(0)); - assert_eq!(a.compare_exchange(Foo(0), Foo(5)), Ok(Foo(100))); - assert_eq!(a.load().0, 5); - assert_eq!(a.compare_exchange(Foo(10), Foo(15)), Ok(Foo(100))); - assert_eq!(a.load().0, 15); -} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/tests/wait_group.rs b/third_party/cargo/vendor/crossbeam-0.5.0/tests/wait_group.rs deleted file mode 100644 index bd15f61..0000000 --- a/third_party/cargo/vendor/crossbeam-0.5.0/tests/wait_group.rs +++ /dev/null @@ -1,66 +0,0 @@ -extern crate crossbeam; - -use std::sync::mpsc; -use std::thread; -use std::time::Duration; - -use crossbeam::sync::WaitGroup; - -const THREADS: usize = 10; - -#[test] -fn wait() { - let wg = WaitGroup::new(); - let (tx, rx) = mpsc::channel(); - - for _ in 0..THREADS { - let wg = wg.clone(); - let tx = tx.clone(); - - thread::spawn(move || { - wg.wait(); - tx.send(()).unwrap(); - }); - } - - thread::sleep(Duration::from_millis(100)); - - // At this point, all spawned threads should be blocked, so we shouldn't get anything from the - // channel. - assert!(rx.try_recv().is_err()); - - wg.wait(); - - // Now, the wait group is cleared and we should receive messages. - for _ in 0..THREADS { - rx.recv().unwrap(); - } -} - -#[test] -fn wait_and_drop() { - let wg = WaitGroup::new(); - let (tx, rx) = mpsc::channel(); - - for _ in 0..THREADS { - let wg = wg.clone(); - let tx = tx.clone(); - - thread::spawn(move || { - thread::sleep(Duration::from_millis(100)); - tx.send(()).unwrap(); - drop(wg); - }); - } - - // At this point, all spawned threads should be sleeping, so we shouldn't get anything from the - // channel. - assert!(rx.try_recv().is_err()); - - wg.wait(); - - // Now, the wait group is cleared and we should receive messages. - for _ in 0..THREADS { - rx.try_recv().unwrap(); - } -} diff --git a/third_party/cargo/vendor/crossbeam-0.7.3/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-0.7.3/.cargo-checksum.json new file mode 100644 index 0000000..8a90ca4 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-0.7.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"e949ef021cda157e3b6af28cd2674e75543100995d813edaa72962954dccb940","Cargo.toml":"fac878f01541e42b41814c6083fb8abaf9361016891ec594e579795162c157c8","LICENSE-APACHE":"6f712474a3e3be1386d2d0c29449850ea788da64d35cff0fc8799acf741e9ecd","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"298c42374496e5ee59ff54afe30bd7125cfb64090200b7dcbd77cbf93353ba1b","src/lib.rs":"2f3fccf9e9bc46507b7172bea4c73060f8f027a65f220be9b9c59af7223f7271","tests/subcrates.rs":"b02598b4a55259574dea828e0c73a791091bd9051cad1a250ab32fe18b573626"},"package":"69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/BUILD b/third_party/cargo/vendor/crossbeam-0.7.3/BUILD similarity index 61% rename from third_party/cargo/vendor/crossbeam-0.5.0/BUILD rename to third_party/cargo/vendor/crossbeam-0.7.3/BUILD index 975fb56..0426edf 100644 --- a/third_party/cargo/vendor/crossbeam-0.5.0/BUILD +++ b/third_party/cargo/vendor/crossbeam-0.7.3/BUILD @@ -23,7 +23,6 @@ load( ) -# Unsupported target "atomic_cell" with type "test" omitted rust_library( name = "crossbeam", @@ -33,23 +32,23 @@ rust_library( srcs = glob(["**/*.rs"]), deps = [ "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", - "//third_party/cargo/vendor/crossbeam-channel-0.3.9:crossbeam_channel", - "//third_party/cargo/vendor/crossbeam-deque-0.6.3:crossbeam_deque", - "//third_party/cargo/vendor/crossbeam-epoch-0.6.1:crossbeam_epoch", - "//third_party/cargo/vendor/crossbeam-utils-0.6.6:crossbeam_utils", - "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", - "//third_party/cargo/vendor/num_cpus-1.12.0:num_cpus", - "//third_party/cargo/vendor/parking_lot-0.6.4:parking_lot", + "//third_party/cargo/vendor/crossbeam-channel-0.4.2:crossbeam_channel", + "//third_party/cargo/vendor/crossbeam-deque-0.7.3:crossbeam_deque", + "//third_party/cargo/vendor/crossbeam-epoch-0.8.2:crossbeam_epoch", + "//third_party/cargo/vendor/crossbeam-queue-0.2.1:crossbeam_queue", + "//third_party/cargo/vendor/crossbeam-utils-0.7.2:crossbeam_utils", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.5.0", + version = "0.7.3", crate_features = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-queue", "default", "std", ], ) # Unsupported target "subcrates" with type "test" omitted -# Unsupported target "wait_group" with type "test" omitted diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-0.7.3/CHANGELOG.md similarity index 70% rename from third_party/cargo/vendor/crossbeam-0.5.0/CHANGELOG.md rename to third_party/cargo/vendor/crossbeam-0.7.3/CHANGELOG.md index 7019fc0..5a97039 100644 --- a/third_party/cargo/vendor/crossbeam-0.5.0/CHANGELOG.md +++ b/third_party/cargo/vendor/crossbeam-0.7.3/CHANGELOG.md @@ -1,3 +1,35 @@ +# Version 0.7.3 + +- Fix breakage with nightly feature due to rust-lang/rust#65214. +- Bump `crossbeam-channel` to `0.4`. +- Bump `crossbeam-epoch` to `0.8`. +- Bump `crossbeam-queue` to `0.2`. +- Bump `crossbeam-utils` to `0.7`. + +# Version 0.7.2 + +- Bump `crossbeam-channel` to `0.3.9`. +- Bump `crossbeam-epoch` to `0.7.2`. +- Bump `crossbeam-utils` to `0.6.6`. + +# Version 0.7.1 + +- Bump `crossbeam-utils` to `0.6.5`. + +# Version 0.7.0 + +- Remove `ArcCell`, `MsQueue`, and `TreiberStack`. +- Change the interface of `ShardedLock` to match `RwLock`. +- Add `SegQueue::len()`. +- Rename `SegQueue::try_pop()` to `SegQueue::pop()`. +- Change the return type of `SegQueue::pop()` to `Result`. +- Introduce `ArrayQueue`. +- Update dependencies. + +# Version 0.6.0 + +- Update dependencies. + # Version 0.5.0 - Update `crossbeam-channel` to 0.3. diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/Cargo.toml b/third_party/cargo/vendor/crossbeam-0.7.3/Cargo.toml similarity index 70% rename from third_party/cargo/vendor/crossbeam-0.5.0/Cargo.toml rename to third_party/cargo/vendor/crossbeam-0.7.3/Cargo.toml index b379854..87d104d 100644 --- a/third_party/cargo/vendor/crossbeam-0.5.0/Cargo.toml +++ b/third_party/cargo/vendor/crossbeam-0.7.3/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,46 +12,46 @@ [package] name = "crossbeam" -version = "0.5.0" +version = "0.7.3" authors = ["The Crossbeam Project Developers"] exclude = ["/ci/*", "/.travis.yml", "/bors.toml"] -description = "Support for concurrent programming: memory management, utilities, non-blocking data structures" +description = "Tools for concurrent programming" homepage = "https://github.com/crossbeam-rs/crossbeam" documentation = "https://docs.rs/crossbeam" readme = "README.md" keywords = ["atomic", "garbage", "non-blocking", "lock-free", "rcu"] -categories = ["concurrency", "memory-management", "data-structures"] +categories = ["concurrency", "memory-management", "data-structures", "no-std"] license = "MIT/Apache-2.0" repository = "https://github.com/crossbeam-rs/crossbeam" [dependencies.cfg-if] -version = "0.1" +version = "0.1.2" [dependencies.crossbeam-channel] -version = "0.3" +version = "0.4" +optional = true [dependencies.crossbeam-deque] -version = "0.6" +version = "0.7.0" +optional = true [dependencies.crossbeam-epoch] -version = "0.6" +version = "0.8" +default-features = false + +[dependencies.crossbeam-queue] +version = "0.2" +optional = true [dependencies.crossbeam-utils] +version = "0.7" +default-features = false +[dev-dependencies.rand] version = "0.6" -[dependencies.lazy_static] -version = "1.1.0" - -[dependencies.num_cpus] -version = "1.8.0" - -[dependencies.parking_lot] -version = "0.6.4" -[dev-dependencies.rand] -version = "0.5" - [features] +alloc = ["crossbeam-epoch/alloc", "crossbeam-utils/alloc"] default = ["std"] nightly = ["crossbeam-epoch/nightly", "crossbeam-utils/nightly"] -std = ["crossbeam-epoch/std", "crossbeam-utils/std"] +std = ["crossbeam-channel", "crossbeam-deque", "crossbeam-epoch/std", "crossbeam-queue", "crossbeam-utils/std"] [badges.travis-ci] repository = "crossbeam-rs/crossbeam" diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-0.7.3/LICENSE-APACHE similarity index 99% rename from third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-0.7.3/LICENSE-APACHE index 16fe87b..bb9abdd 100644 --- a/third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-APACHE +++ b/third_party/cargo/vendor/crossbeam-0.7.3/LICENSE-APACHE @@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work. same "printed page" as the copyright notice for easier identification within third-party archives. -Copyright [yyyy] [name of copyright owner] +Copyright 2019 The Crossbeam Project Developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-0.7.3/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-0.7.3/LICENSE-MIT diff --git a/third_party/cargo/vendor/crossbeam-0.7.3/README.md b/third_party/cargo/vendor/crossbeam-0.7.3/README.md new file mode 100644 index 0000000..fdf42fe --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-0.7.3/README.md @@ -0,0 +1,162 @@ +# Crossbeam + +[![Build Status](https://travis-ci.org/crossbeam-rs/crossbeam.svg?branch=master)]( +https://travis-ci.org/crossbeam-rs/crossbeam) +[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( +https://github.com/crossbeam-rs/crossbeam) +[![Cargo](https://img.shields.io/crates/v/crossbeam.svg)]( +https://crates.io/crates/crossbeam) +[![Documentation](https://docs.rs/crossbeam/badge.svg)]( +https://docs.rs/crossbeam) +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( +https://www.rust-lang.org) +[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/JXYwgWZ) + +This crate provides a set of tools for concurrent programming: + +#### Atomics + +* [`AtomicCell`], a thread-safe mutable memory location.(no_std) +* [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering.(no_std) + +#### Data structures + +* [`deque`], work-stealing deques for building task schedulers. +* [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. +* [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. + +#### Memory management + +* [`epoch`], an epoch-based garbage collector.(alloc) + +#### Thread synchronization + +* [`channel`], multi-producer multi-consumer channels for message passing. +* [`Parker`], a thread parking primitive. +* [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads. +* [`WaitGroup`], for synchronizing the beginning or end of some computation. + +#### Utilities + +* [`Backoff`], for exponential backoff in spin loops.(no_std) +* [`CachePadded`], for padding and aligning a value to the length of a cache line.(no_std) +* [`scope`], for spawning threads that borrow local variables from the stack. + +*Features marked with (no_std) can be used in `no_std` environments.*
+*Features marked with (alloc) can be used in `no_std` environments, but only if `alloc` +and `nightly` are enabled.* + +[`AtomicCell`]: https://docs.rs/crossbeam/*/crossbeam/atomic/struct.AtomicCell.html +[`AtomicConsume`]: https://docs.rs/crossbeam/*/crossbeam/atomic/trait.AtomicConsume.html +[`deque`]: https://docs.rs/crossbeam/*/crossbeam/deque/index.html +[`ArrayQueue`]: https://docs.rs/crossbeam/*/crossbeam/queue/struct.ArrayQueue.html +[`SegQueue`]: https://docs.rs/crossbeam/*/crossbeam/queue/struct.SegQueue.html +[`channel`]: https://docs.rs/crossbeam/*/crossbeam/channel/index.html +[`Parker`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.Parker.html +[`ShardedLock`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.ShardedLock.html +[`WaitGroup`]: https://docs.rs/crossbeam/*/crossbeam/sync/struct.WaitGroup.html +[`epoch`]: https://docs.rs/crossbeam/*/crossbeam/epoch/index.html +[`Backoff`]: https://docs.rs/crossbeam/*/crossbeam/utils/struct.Backoff.html +[`CachePadded`]: https://docs.rs/crossbeam/*/crossbeam/utils/struct.CachePadded.html +[`scope`]: https://docs.rs/crossbeam/*/crossbeam/fn.scope.html + +## Crates + +The main `crossbeam` crate just [re-exports](src/lib.rs) tools from +smaller subcrates: + +* [`crossbeam-channel`](crossbeam-channel) + provides multi-producer multi-consumer channels for message passing. +* [`crossbeam-deque`](crossbeam-deque) + provides work-stealing deques, which are primarily intended for building task schedulers. +* [`crossbeam-epoch`](crossbeam-epoch) + provides epoch-based garbage collection for building concurrent data structures. +* [`crossbeam-queue`](crossbeam-queue) + provides concurrent queues that can be shared among threads. +* [`crossbeam-utils`](crossbeam-utils) + provides atomics, synchronization primitives, scoped threads, and other utilities. + +There is one more experimental subcrate that is not yet included in `crossbeam`: + +* [`crossbeam-skiplist`](crossbeam-skiplist) + provides concurrent maps and sets based on lock-free skip lists. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +crossbeam = "0.7" +``` + +Next, add this to your crate: + +```rust +extern crate crossbeam; +``` + +## Compatibility + +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. + +## Contributing + +Crossbeam welcomes contribution from everyone in the form of suggestions, bug reports, +pull requests, and feedback. 💛 + +If you need ideas for contribution, there are several ways to get started: + +* Found a bug or have a feature request? + [Submit an issue](https://github.com/crossbeam-rs/crossbeam/issues/new)! +* Issues and PRs labeled with + [feedback wanted](https://github.com/crossbeam-rs/crossbeam/issues?utf8=%E2%9C%93&q=is%3Aopen+sort%3Aupdated-desc+label%3A%22feedback+wanted%22+) + need feedback from users and contributors. +* Issues labeled with + [good first issue](https://github.com/crossbeam-rs/crossbeam/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22good+first+issue%22) + are relatively easy starter issues. + +#### RFCs + +We also have the [RFCs](https://github.com/crossbeam-rs/rfcs) repository for more +high-level discussion, which is the place where we brainstorm ideas and propose +substantial changes to Crossbeam. + +You are welcome to participate in any open +[issues](https://github.com/crossbeam-rs/rfcs/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) +or +[pull requests](https://github.com/crossbeam-rs/rfcs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc). + +#### Learning resources + +If you'd like to learn more about concurrency and non-blocking data structures, there's a +list of learning resources in our [wiki](https://github.com/crossbeam-rs/rfcs/wiki), +which includes relevant blog posts, papers, videos, and other similar projects. + +Another good place to visit is [merged RFCs](https://github.com/crossbeam-rs/rfcs/tree/master/text). +They contain elaborate descriptions and rationale for features we've introduced to +Crossbeam, but keep in mind that some of the written information is now out of date. + +#### Conduct + +The Crossbeam project adheres to the +[Rust Code of Conduct](https://github.com/rust-lang/rust/blob/master/CODE_OF_CONDUCT.md). +This describes the minimum behavior expected from all contributors. + +## License + +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. + +Some Crossbeam subcrates have additional licensing notices. +Take a look at other readme files in this repository for more information. + +#### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/third_party/cargo/vendor/crossbeam-0.7.3/src/lib.rs b/third_party/cargo/vendor/crossbeam-0.7.3/src/lib.rs new file mode 100644 index 0000000..01c5a8f --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-0.7.3/src/lib.rs @@ -0,0 +1,109 @@ +//! Tools for concurrent programming. +//! +//! ## Atomics +//! +//! * [`AtomicCell`], a thread-safe mutable memory location. +//! * [`AtomicConsume`], for reading from primitive atomic types with "consume" ordering. +//! +//! ## Data structures +//! +//! * [`deque`], work-stealing deques for building task schedulers. +//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. +//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. +//! +//! ## Memory management +//! +//! * [`epoch`], an epoch-based garbage collector. +//! +//! ## Thread synchronization +//! +//! * [`channel`], multi-producer multi-consumer channels for message passing. +//! * [`Parker`], a thread parking primitive. +//! * [`ShardedLock`], a sharded reader-writer lock with fast concurrent reads. +//! * [`WaitGroup`], for synchronizing the beginning or end of some computation. +//! +//! ## Utilities +//! +//! * [`Backoff`], for exponential backoff in spin loops. +//! * [`CachePadded`], for padding and aligning a value to the length of a cache line. +//! * [`scope`], for spawning threads that borrow local variables from the stack. +//! +//! [`AtomicCell`]: atomic/struct.AtomicCell.html +//! [`AtomicConsume`]: atomic/trait.AtomicConsume.html +//! [`deque`]: deque/index.html +//! [`ArrayQueue`]: queue/struct.ArrayQueue.html +//! [`SegQueue`]: queue/struct.SegQueue.html +//! [`channel`]: channel/index.html +//! [`Parker`]: sync/struct.Parker.html +//! [`ShardedLock`]: sync/struct.ShardedLock.html +//! [`WaitGroup`]: sync/struct.WaitGroup.html +//! [`epoch`]: epoch/index.html +//! [`Backoff`]: utils/struct.Backoff.html +//! [`CachePadded`]: utils/struct.CachePadded.html +//! [`scope`]: fn.scope.html + +#![warn(missing_docs)] +#![warn(missing_debug_implementations)] +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))] + +#[macro_use] +extern crate cfg_if; +#[cfg(feature = "std")] +extern crate core; + +cfg_if! { + if #[cfg(feature = "alloc")] { + extern crate alloc; + } else if #[cfg(feature = "std")] { + extern crate std as alloc; + } +} + +mod _epoch { + pub extern crate crossbeam_epoch; +} +#[doc(inline)] +pub use _epoch::crossbeam_epoch as epoch; + +extern crate crossbeam_utils; + +#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))] +pub use crossbeam_utils::atomic; + +/// Miscellaneous utilities. +pub mod utils { + pub use crossbeam_utils::Backoff; + pub use crossbeam_utils::CachePadded; +} + +cfg_if! { + if #[cfg(feature = "std")] { + mod _deque { + pub extern crate crossbeam_deque; + } + #[doc(inline)] + pub use _deque::crossbeam_deque as deque; + + mod _channel { + pub extern crate crossbeam_channel; + pub use self::crossbeam_channel::*; + } + #[doc(inline)] + pub use _channel::crossbeam_channel as channel; + + // HACK(stjepang): This is the only way to reexport `select!` in Rust older than 1.30.0 + #[doc(hidden)] + pub use _channel::*; + + mod _queue { + pub extern crate crossbeam_queue; + } + #[doc(inline)] + pub use _queue::crossbeam_queue as queue; + + pub use crossbeam_utils::sync; + pub use crossbeam_utils::thread; + pub use crossbeam_utils::thread::scope; + } +} diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/tests/subcrates.rs b/third_party/cargo/vendor/crossbeam-0.7.3/tests/subcrates.rs similarity index 66% rename from third_party/cargo/vendor/crossbeam-0.5.0/tests/subcrates.rs rename to third_party/cargo/vendor/crossbeam-0.7.3/tests/subcrates.rs index 553684f..b9a3b0d 100644 --- a/third_party/cargo/vendor/crossbeam-0.5.0/tests/subcrates.rs +++ b/third_party/cargo/vendor/crossbeam-0.7.3/tests/subcrates.rs @@ -1,4 +1,4 @@ -//! Makes sure subcrates are properly reexported. +//! Makes sure subcrates are properly re-exported. #[macro_use] extern crate crossbeam; @@ -15,10 +15,9 @@ fn channel() { #[test] fn deque() { - let (w, s) = crossbeam::deque::fifo(); + let w = crossbeam::deque::Worker::new_fifo(); w.push(1); let _ = w.pop(); - let _ = s.steal(); } #[test] @@ -26,15 +25,24 @@ fn epoch() { crossbeam::epoch::pin(); } +#[test] +fn queue() { + let a = crossbeam::queue::ArrayQueue::new(10); + let _ = a.push(1); + let _ = a.pop(); +} + #[test] fn utils() { crossbeam::utils::CachePadded::new(7); crossbeam::scope(|scope| { scope.spawn(|_| ()); - }).unwrap(); + }) + .unwrap(); crossbeam::thread::scope(|scope| { scope.spawn(|_| ()); - }).unwrap(); + }) + .unwrap(); } diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-channel-0.3.9/.cargo-checksum.json deleted file mode 100644 index 30e766e..0000000 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"accbc6a8bd5581eebf4322ebd693a4594a991ab80f6ddbac113f30ec2c09d46f","Cargo.toml":"ee485fd4a91cbb65fcc1ee07e4dc1e76a3cbe61fa49626653fb1b95ee96a3f06","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","LICENSE-THIRD-PARTY":"924a49392dc8304def57586be4ebd69aaf51e16fd245b55b4b69ad2cce6b715a","README.md":"996dd8dedfb47a96f8c3b15abef9045285372893ed2f3ba89354d28a0af1c779","benches/crossbeam.rs":"baef02dffd58ee4d84d33a4e999254e81fcf45241623cfa6c4b1ef73dbd7479d","examples/fibonacci.rs":"8755bcb9cf05e391d8679fbb51db40ed9692703c3b66341cd1c1e4cca2068874","examples/matching.rs":"a1bdd7d211cf8612d649de3de3e24f56e911bc8d5e95b86b06f412314f9edd6c","examples/stopwatch.rs":"4e90ce134475859a421da0a095baea52a575b03e41fb8fb50cf47446f422ee6e","src/channel.rs":"4483ddf38c4b9b308b81dd156653ccb590524aae1e5ff8efcab6b8f44a8d3dfc","src/context.rs":"48eb848538482aeadd5bafb8fd24695dcf5635243d6f9d3b059a22538ce67014","src/counter.rs":"8b6d4d69db59bc992ddc7ed33f709788c3fab482521bb1adf985f77499506c09","src/err.rs":"1a9ac9d7f4d5561f9c3e513b2f776782783954efa0bf9428598f3ad9ccb9d5c9","src/flavors/after.rs":"4f761618efe21036145e44f01506bdfbc2524879368ac138600e0feed921a6a7","src/flavors/array.rs":"3726a68712c3ba25a325fe91fc74da831d27e22e751d0b8d5dfd9d7022f54e04","src/flavors/list.rs":"969f925ea094d7d4e25b7ff294ea5c9a62cdae17238b41b915ece211def666fe","src/flavors/mod.rs":"a5af9b6105207e293c0d64928b4486fb1da9bfe0318354c66c8b5069e41ec31f","src/flavors/never.rs":"86e21b4d8b154e5d795cf72c7203a1d16a846c4d670095c8b592c12569f35a98","src/flavors/tick.rs":"654e7874805eb37d1fbd81d88ca23697a05eeaaa308b748860b9d2342f9752bd","src/flavors/zero.rs":"a24c2fb547586ab4bf2a09efb8af5264274f7b373749cd259a7dd3c843c8aac5","src/lib.rs":"854539dd0e7519bb3b087269d294930dc1f5b1880a98f5ede9e9d6ac33ea9f21","src/select.rs":"56788172014c4f3365493f63506f252235142063a7b8af6d707d81aec3f6f40a","src/select_macro.rs":"fa4fd99e1eab0eed621106f9286cf767d14a0d7d446142937e9cce3b0a6723ad","src/utils.rs":"8b1184222df9047355e6044ad7e3fefd6065a5dda98b968cae45cca5f4b2fb5d","src/waker.rs":"345b551d467389a3a18dc22b351674dfbf288945b984450f607e644faa8a9731","tests/after.rs":"effb341c02f03a45ce09ab7862bc5b191191e0175997c494f988e6daca1ef8af","tests/array.rs":"3987b6cb98b38fbda6061106e8fe1794f9c73b119508a4f7fc1ff3f5af3872a4","tests/golang.rs":"84875ee41f19d7475de697f1bb5e93535b9e1fe0c90f76f1a2dbdfcc46aec30a","tests/iter.rs":"b6df3f21273bb21dfecda47ffc0c296541214cde6bed876a31db5f2410839e83","tests/list.rs":"531891f8f2e9961c729174063eeb2ef7a141b5f7883abf10ea14d11feac12423","tests/mpsc.rs":"965e18abbfcdebec09380f8ec9bb62e5556ad2aa0176ed088ce091994c1d2500","tests/never.rs":"cd455a4c78403d9a96fe0f3a4e968164cca533cc85c96aaa4558987f9b088fcc","tests/ready.rs":"8d394399aed5c928b9764493709e2907a652c909b4968abd26ce4801dffc5d69","tests/same_channel.rs":"bd93f72e982f9881235848a4a2da67276feca810ed1e4d22e0e2bda8675cae4a","tests/select.rs":"1b23969236f443a129c1dd4a4c5930c3ee60ecd04614ef7ef67d470bceef8d53","tests/select_macro.rs":"2fb99a1d72185301cad010e2c923bbf612ab9149ce0fe72b8e8f9068f7772322","tests/thread_locals.rs":"845f8c8f1a37a14e4235fc9fc20d8b7288fd9fda307c075c0e61e6ab79b33921","tests/tick.rs":"dd4257f1f8de01477d542e20a816eede3b4e2e4dc6fcdf07d554220f0ef8a86f","tests/zero.rs":"f65f69127bc0bc84e2c2b42cd3384ce5b099eb4d11b3df079b88f3f3ca5edb0a"},"package":"c8ec7fcd21571dc78f96cc96243cab8d8f035247c3efd16c687be154c3fa9efa"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-channel-0.4.2/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-channel-0.4.2/.cargo-checksum.json new file mode 100644 index 0000000..e3095e7 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"40140368f7acf7657e37bedea150e10b9ba38b50b98b1b234c076ffc470af1ca","Cargo.lock":"476677c500d3cff5eedb562013fa5352560a66bf0fe30be758f4e4055cbe5986","Cargo.toml":"a0642274b237f6996a61472bad73512ec5f6d1559cf8891714f7806d344bb64b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","LICENSE-THIRD-PARTY":"924a49392dc8304def57586be4ebd69aaf51e16fd245b55b4b69ad2cce6b715a","README.md":"7967172d90f7ebc20531d76c5a2bad7be8d81670fbc64abc33be4315d1430757","benches/crossbeam.rs":"baef02dffd58ee4d84d33a4e999254e81fcf45241623cfa6c4b1ef73dbd7479d","examples/fibonacci.rs":"8755bcb9cf05e391d8679fbb51db40ed9692703c3b66341cd1c1e4cca2068874","examples/matching.rs":"a1bdd7d211cf8612d649de3de3e24f56e911bc8d5e95b86b06f412314f9edd6c","examples/stopwatch.rs":"4e90ce134475859a421da0a095baea52a575b03e41fb8fb50cf47446f422ee6e","src/channel.rs":"4483ddf38c4b9b308b81dd156653ccb590524aae1e5ff8efcab6b8f44a8d3dfc","src/context.rs":"48eb848538482aeadd5bafb8fd24695dcf5635243d6f9d3b059a22538ce67014","src/counter.rs":"8b6d4d69db59bc992ddc7ed33f709788c3fab482521bb1adf985f77499506c09","src/err.rs":"80c47848fbfeeabaa83ea49c0928274cd4ae0ced7ebf214a075322fe301f3fa6","src/flavors/after.rs":"4f761618efe21036145e44f01506bdfbc2524879368ac138600e0feed921a6a7","src/flavors/array.rs":"606e27d3376c3cee128656b3690bd429964a22e3078886b6b7bf10cfa072fabb","src/flavors/list.rs":"0e2bf126b07ba8c2ef5db881043a3987b5f91013d47ae2da147a1c61a033c320","src/flavors/mod.rs":"a5af9b6105207e293c0d64928b4486fb1da9bfe0318354c66c8b5069e41ec31f","src/flavors/never.rs":"86e21b4d8b154e5d795cf72c7203a1d16a846c4d670095c8b592c12569f35a98","src/flavors/tick.rs":"d80858e0d5d1d7ec3886fb607e49bbc9577d64dc7c7304c5d3e6c8629a065476","src/flavors/zero.rs":"a24c2fb547586ab4bf2a09efb8af5264274f7b373749cd259a7dd3c843c8aac5","src/lib.rs":"1f0e6c4fb470dfe2fbdda90b7ac17f72c32fd62d41bccb4db9a756a88481fb44","src/select.rs":"f917459c033f8edbb45f377d6a4af24ffb583583d039182e72252d4af64a8807","src/select_macro.rs":"b1a3d2b9d4c64b48f6b176d2ff8b44c3d754f157ddbe830e8a1e86e4c100e0e9","src/utils.rs":"8b1184222df9047355e6044ad7e3fefd6065a5dda98b968cae45cca5f4b2fb5d","src/waker.rs":"345b551d467389a3a18dc22b351674dfbf288945b984450f607e644faa8a9731","tests/after.rs":"effb341c02f03a45ce09ab7862bc5b191191e0175997c494f988e6daca1ef8af","tests/array.rs":"35cd46fc7310f4206e3bbd81f900c18053a3a22943e221fbb81f9b89505fee46","tests/golang.rs":"9cb210ef2668428f7efb542ff4a8ab4e61f77dd4ff7e39720d63ad0797ff4ec1","tests/iter.rs":"b6df3f21273bb21dfecda47ffc0c296541214cde6bed876a31db5f2410839e83","tests/list.rs":"eb6cfc9a0f02c77df6d6d608fbbe1f82e09901e167b4b86993c49f9d6052a8ee","tests/mpsc.rs":"965e18abbfcdebec09380f8ec9bb62e5556ad2aa0176ed088ce091994c1d2500","tests/never.rs":"cd455a4c78403d9a96fe0f3a4e968164cca533cc85c96aaa4558987f9b088fcc","tests/ready.rs":"b91cebde45a6c46bd2cf16b1fc58b2ec258dcc960cb9f8eb5b4c39b1a144cadc","tests/same_channel.rs":"bd93f72e982f9881235848a4a2da67276feca810ed1e4d22e0e2bda8675cae4a","tests/select.rs":"57558f93834dc1ae1a56fe8d1211536e16015a74c8c7458c653852472c21ddcd","tests/select_macro.rs":"1cd5250d46d6d2e8c0a87ee9b1c0a5d80aac193c3eb0a86877249684e7aabd39","tests/thread_locals.rs":"845f8c8f1a37a14e4235fc9fc20d8b7288fd9fda307c075c0e61e6ab79b33921","tests/tick.rs":"dd4257f1f8de01477d542e20a816eede3b4e2e4dc6fcdf07d554220f0ef8a86f","tests/zero.rs":"088804df377904eca4a985d8f1703f98550e51304d6849bfce143fcd0b69c349"},"package":"cced8691919c02aac3cb0a1bc2e9b73d89e832bf9a06fc579d4e71b68a2da061"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/BUILD b/third_party/cargo/vendor/crossbeam-channel-0.4.2/BUILD similarity index 92% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/BUILD rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/BUILD index 5788523..96978ff 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/BUILD +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/BUILD @@ -35,12 +35,13 @@ rust_library( edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/crossbeam-utils-0.6.6:crossbeam_utils", + "//third_party/cargo/vendor/crossbeam-utils-0.7.2:crossbeam_utils", + "//third_party/cargo/vendor/maybe-uninit-2.0.0:maybe_uninit", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.3.9", + version = "0.4.2", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-channel-0.4.2/CHANGELOG.md similarity index 93% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/CHANGELOG.md rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/CHANGELOG.md index 505ad25..c1fcf3f 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/CHANGELOG.md +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/CHANGELOG.md @@ -1,3 +1,17 @@ +# Version 0.4.2 + +- Fix bug in release (yanking 0.4.1) + +# Version 0.4.1 + +- Avoid time drift in `channel::tick`. (#456) +- Fix unsoundness issues by adopting `MaybeUninit`. (#458) + +# Version 0.4.0 + +- Bump the minimum required version to 1.28. +- Bump `crossbeam-utils` to `0.7`. + # Version 0.3.9 - Fix a bug in reference counting. diff --git a/third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.lock b/third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.lock new file mode 100644 index 0000000..5559700 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.lock @@ -0,0 +1,264 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "arc-swap" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-channel" +version = "0.4.2" +dependencies = [ + "crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "signal-hook 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "hermit-abi" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "num_cpus" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "hermit-abi 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_jitter 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_chacha" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand_hc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_isaac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_jitter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_os" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_pcg" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_xorshift" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rdrand" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "signal-hook" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "signal-hook-registry" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d7b8a9123b8027467bce0099fe556c628a53c8d83df0507084c31e9ba2e39aff" +"checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" +"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum crossbeam-utils 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum hermit-abi 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "e2c55f143919fbc0bc77e427fe2d74cf23786d7c1875666f2fde3ac3c659bb67" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +"checksum libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)" = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" +"checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" +"checksum num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" +"checksum rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" +"checksum rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" +"checksum rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" +"checksum rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" +"checksum rand_jitter 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" +"checksum rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" +"checksum rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" +"checksum rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" +"checksum rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +"checksum signal-hook 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "10b9f3a1686a29f53cfd91ee5e3db3c12313ec02d33765f02c1a9645a1811e2c" +"checksum signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/Cargo.toml b/third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.toml similarity index 93% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/Cargo.toml rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.toml index 1e36a44..0b700b1 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/Cargo.toml +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "crossbeam-channel" -version = "0.3.9" +version = "0.4.2" authors = ["The Crossbeam Project Developers"] description = "Multi-producer multi-consumer channels for message passing" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel" @@ -23,7 +23,10 @@ categories = ["algorithms", "concurrency", "data-structures"] license = "MIT/Apache-2.0 AND BSD-2-Clause" repository = "https://github.com/crossbeam-rs/crossbeam" [dependencies.crossbeam-utils] -version = "0.6.5" +version = "0.7" + +[dependencies.maybe-uninit] +version = "2.0.0" [dev-dependencies.num_cpus] version = "1.10.0" diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-APACHE diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-MIT diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-THIRD-PARTY b/third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-THIRD-PARTY similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/LICENSE-THIRD-PARTY rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/LICENSE-THIRD-PARTY diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/README.md b/third_party/cargo/vendor/crossbeam-channel-0.4.2/README.md similarity index 94% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/README.md rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/README.md index 2e16a04..be2e0b8 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/README.md +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam-channel) https://crates.io/crates/crossbeam-channel) [![Documentation](https://docs.rs/crossbeam-channel/badge.svg)]( https://docs.rs/crossbeam-channel) -[![Rust 1.26+](https://img.shields.io/badge/rust-1.26+-lightgray.svg)]( +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/BBYwKq) @@ -41,7 +41,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -crossbeam-channel = "0.3" +crossbeam-channel = "0.4" ``` Next, add this to your crate: @@ -51,6 +51,10 @@ Next, add this to your crate: extern crate crossbeam_channel; ``` +## Compatibility + +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. + ## License Licensed under either of diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/benches/crossbeam.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/benches/crossbeam.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/benches/crossbeam.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/benches/crossbeam.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/fibonacci.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/fibonacci.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/fibonacci.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/fibonacci.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/matching.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/matching.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/matching.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/matching.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/stopwatch.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/stopwatch.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/examples/stopwatch.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/examples/stopwatch.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/channel.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/channel.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/channel.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/channel.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/context.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/context.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/context.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/context.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/counter.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/counter.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/counter.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/counter.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/err.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/err.rs similarity index 96% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/err.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/err.rs index 02c7d44..468ce5c 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/err.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/err.rs @@ -132,7 +132,7 @@ impl error::Error for SendError { "sending on a disconnected channel" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -183,7 +183,7 @@ impl error::Error for TrySendError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -254,7 +254,7 @@ impl error::Error for SendTimeoutError { "sending on an empty and disconnected channel" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -317,7 +317,7 @@ impl error::Error for RecvError { "receiving on an empty and disconnected channel" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -339,7 +339,7 @@ impl error::Error for TryRecvError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -387,7 +387,7 @@ impl error::Error for RecvTimeoutError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -429,7 +429,7 @@ impl error::Error for TrySelectError { "all operations in select would block" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -445,7 +445,7 @@ impl error::Error for SelectTimeoutError { "timed out waiting on select" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/after.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/after.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/after.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/after.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/array.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/array.rs similarity index 98% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/array.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/array.rs index 1537c09..659fce6 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/array.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/array.rs @@ -22,6 +22,8 @@ use std::time::Instant; use crossbeam_utils::{Backoff, CachePadded}; +use maybe_uninit::MaybeUninit; + use context::Context; use err::{RecvTimeoutError, SendTimeoutError, TryRecvError, TrySendError}; use select::{Operation, SelectHandle, Selected, Token}; @@ -33,7 +35,7 @@ struct Slot { stamp: AtomicUsize, /// The message in this slot. - msg: UnsafeCell, + msg: UnsafeCell>, } /// The token type for the array flavor. @@ -233,7 +235,7 @@ impl Channel { let slot: &Slot = &*(token.array.slot as *const Slot); // Write the message into the slot and update the stamp. - slot.msg.get().write(msg); + slot.msg.get().write(MaybeUninit::new(msg)); slot.stamp.store(token.array.stamp, Ordering::Release); // Wake a sleeping receiver. @@ -323,7 +325,7 @@ impl Channel { let slot: &Slot = &*(token.array.slot as *const Slot); // Read the message from the slot and update the stamp. - let msg = slot.msg.get().read(); + let msg = slot.msg.get().read().assume_init(); slot.stamp.store(token.array.stamp, Ordering::Release); // Wake a sleeping sender. @@ -542,7 +544,12 @@ impl Drop for Channel { }; unsafe { - self.buffer.add(index).drop_in_place(); + let p = { + let slot = &mut *self.buffer.add(index); + let msg = &mut *slot.msg.get(); + msg.as_mut_ptr() + }; + p.drop_in_place(); } } diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/list.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/list.rs similarity index 96% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/list.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/list.rs index ae286d3..dd9e6e9 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/list.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/list.rs @@ -2,13 +2,14 @@ use std::cell::UnsafeCell; use std::marker::PhantomData; -use std::mem::{self, ManuallyDrop}; use std::ptr; use std::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering}; use std::time::Instant; use crossbeam_utils::{Backoff, CachePadded}; +use maybe_uninit::MaybeUninit; + use context::Context; use err::{RecvTimeoutError, SendTimeoutError, TryRecvError, TrySendError}; use select::{Operation, SelectHandle, Selected, Token}; @@ -42,7 +43,7 @@ const MARK_BIT: usize = 1; /// A slot in a block. struct Slot { /// The message. - msg: UnsafeCell>, + msg: UnsafeCell>, /// The state of the slot. state: AtomicUsize, @@ -72,7 +73,13 @@ struct Block { impl Block { /// Creates an empty block. fn new() -> Block { - unsafe { mem::zeroed() } + // SAFETY: This is safe because: + // [1] `Block::next` (AtomicPtr) may be safely zero initialized. + // [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4]. + // [3] `Slot::msg` (UnsafeCell) may be safely zero initialized because it + // holds a MaybeUninit. + // [4] `Slot::state` (AtomicUsize) may be safely zero initialized. + unsafe { MaybeUninit::zeroed().assume_init() } } /// Waits until the next pointer is set. @@ -280,7 +287,7 @@ impl Channel { let block = token.list.block as *mut Block; let offset = token.list.offset; let slot = (*block).slots.get_unchecked(offset); - slot.msg.get().write(ManuallyDrop::new(msg)); + slot.msg.get().write(MaybeUninit::new(msg)); slot.state.fetch_or(WRITE, Ordering::Release); // Wake a sleeping receiver. @@ -385,8 +392,7 @@ impl Channel { let offset = token.list.offset; let slot = (*block).slots.get_unchecked(offset); slot.wait_write(); - let m = slot.msg.get().read(); - let msg = ManuallyDrop::into_inner(m); + let msg = slot.msg.get().read().assume_init(); // Destroy the block if we've reached the end, or if another thread wanted to destroy but // couldn't because we were busy reading from the slot. @@ -572,7 +578,8 @@ impl Drop for Channel { if offset < BLOCK_CAP { // Drop the message in the slot. let slot = (*block).slots.get_unchecked(offset); - ManuallyDrop::drop(&mut *(*slot).msg.get()); + let p = &mut *slot.msg.get(); + p.as_mut_ptr().drop_in_place(); } else { // Deallocate the block and move to the next one. let next = (*block).next.load(Ordering::Relaxed); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/mod.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/mod.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/mod.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/mod.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/never.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/never.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/never.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/never.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/tick.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/tick.rs similarity index 79% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/tick.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/tick.rs index 3933886..2941117 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/tick.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/tick.rs @@ -58,34 +58,28 @@ impl Channel { #[inline] pub fn recv(&self, deadline: Option) -> Result { loop { - // Compute the time to sleep until the next message or the deadline. - let offset = { - let delivery_time = self.delivery_time.load(); - let now = Instant::now(); + let delivery_time = self.delivery_time.load(); + let now = Instant::now(); - // Check if we can receive the next message. - if now >= delivery_time - && self - .delivery_time - .compare_exchange(delivery_time, now + self.duration) - .is_ok() - { - return Ok(delivery_time); - } - - // Check if the operation deadline has been reached. - if let Some(d) = deadline { - if now >= d { - return Err(RecvTimeoutError::Timeout); + if let Some(d) = deadline { + if d < delivery_time { + if now < d { + thread::sleep(d - now); } - - delivery_time.min(d) - now - } else { - delivery_time - now + return Err(RecvTimeoutError::Timeout); } - }; + } - thread::sleep(offset); + if self + .delivery_time + .compare_exchange(delivery_time, delivery_time.max(now) + self.duration) + .is_ok() + { + if now < delivery_time { + thread::sleep(delivery_time - now); + } + return Ok(delivery_time); + } } } diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/zero.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/zero.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/flavors/zero.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/flavors/zero.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/lib.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/lib.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/lib.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/lib.rs index 1d51600..8982396 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/lib.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/lib.rs @@ -348,6 +348,7 @@ #![warn(missing_debug_implementations)] extern crate crossbeam_utils; +extern crate maybe_uninit; mod channel; mod context; diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select.rs similarity index 97% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select.rs index a586c6b..60c6a45 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select.rs @@ -171,7 +171,7 @@ enum Timeout { /// Successful receive operations will have to be followed up by `channel::read()` and successful /// send operations by `channel::write()`. fn run_select( - handles: &mut [(&SelectHandle, usize, *const u8)], + handles: &mut [(&dyn SelectHandle, usize, *const u8)], timeout: Timeout, ) -> Option<(Token, usize, *const u8)> { if handles.is_empty() { @@ -220,7 +220,7 @@ fn run_select( registered_count += 1; // If registration returns `false`, that means the operation has just become ready. - if handle.register(Operation::hook::<&SelectHandle>(handle), cx) { + if handle.register(Operation::hook::<&dyn SelectHandle>(handle), cx) { // Try aborting select. sel = match cx.try_select(Selected::Aborted) { Ok(()) => { @@ -259,7 +259,7 @@ fn run_select( // Unregister all registered operations. for (handle, _, _) in handles.iter_mut().take(registered_count) { - handle.unregister(Operation::hook::<&SelectHandle>(handle)); + handle.unregister(Operation::hook::<&dyn SelectHandle>(handle)); } match sel { @@ -279,7 +279,8 @@ fn run_select( // Find the selected operation. for (handle, i, ptr) in handles.iter_mut() { // Is this the selected operation? - if sel == Selected::Operation(Operation::hook::<&SelectHandle>(handle)) { + if sel == Selected::Operation(Operation::hook::<&dyn SelectHandle>(handle)) + { // Try selecting this operation. if handle.accept(&mut token, cx) { return Some((*i, *ptr)); @@ -317,7 +318,10 @@ fn run_select( } /// Runs until one of the operations becomes ready, potentially blocking the current thread. -fn run_ready(handles: &mut [(&SelectHandle, usize, *const u8)], timeout: Timeout) -> Option { +fn run_ready( + handles: &mut [(&dyn SelectHandle, usize, *const u8)], + timeout: Timeout, +) -> Option { if handles.is_empty() { // Wait until the timeout and return. match timeout { @@ -372,7 +376,7 @@ fn run_ready(handles: &mut [(&SelectHandle, usize, *const u8)], timeout: Timeout // Begin watching all operations. for (handle, _, _) in handles.iter_mut() { registered_count += 1; - let oper = Operation::hook::<&SelectHandle>(handle); + let oper = Operation::hook::<&dyn SelectHandle>(handle); // If registration returns `false`, that means the operation has just become ready. if handle.watch(oper, cx) { @@ -410,7 +414,7 @@ fn run_ready(handles: &mut [(&SelectHandle, usize, *const u8)], timeout: Timeout // Unwatch all operations. for (handle, _, _) in handles.iter_mut().take(registered_count) { - handle.unwatch(Operation::hook::<&SelectHandle>(handle)); + handle.unwatch(Operation::hook::<&dyn SelectHandle>(handle)); } match sel { @@ -419,7 +423,7 @@ fn run_ready(handles: &mut [(&SelectHandle, usize, *const u8)], timeout: Timeout Selected::Disconnected => {} Selected::Operation(_) => { for (handle, i, _) in handles.iter_mut() { - let oper = Operation::hook::<&SelectHandle>(handle); + let oper = Operation::hook::<&dyn SelectHandle>(handle); if sel == Selected::Operation(oper) { return Some(*i); } @@ -440,7 +444,7 @@ fn run_ready(handles: &mut [(&SelectHandle, usize, *const u8)], timeout: Timeout /// Attempts to select one of the operations without blocking. #[inline] pub fn try_select<'a>( - handles: &mut [(&'a SelectHandle, usize, *const u8)], + handles: &mut [(&'a dyn SelectHandle, usize, *const u8)], ) -> Result, TrySelectError> { match run_select(handles, Timeout::Now) { None => Err(TrySelectError), @@ -455,7 +459,9 @@ pub fn try_select<'a>( /// Blocks until one of the operations becomes ready and selects it. #[inline] -pub fn select<'a>(handles: &mut [(&'a SelectHandle, usize, *const u8)]) -> SelectedOperation<'a> { +pub fn select<'a>( + handles: &mut [(&'a dyn SelectHandle, usize, *const u8)], +) -> SelectedOperation<'a> { if handles.is_empty() { panic!("no operations have been added to `Select`"); } @@ -472,7 +478,7 @@ pub fn select<'a>(handles: &mut [(&'a SelectHandle, usize, *const u8)]) -> Selec /// Blocks for a limited time until one of the operations becomes ready and selects it. #[inline] pub fn select_timeout<'a>( - handles: &mut [(&'a SelectHandle, usize, *const u8)], + handles: &mut [(&'a dyn SelectHandle, usize, *const u8)], timeout: Duration, ) -> Result, SelectTimeoutError> { let timeout = Timeout::At(Instant::now() + timeout); @@ -573,7 +579,7 @@ pub fn select_timeout<'a>( /// [`ready_timeout`]: struct.Select.html#method.ready_timeout pub struct Select<'a> { /// A list of senders and receivers participating in selection. - handles: Vec<(&'a SelectHandle, usize, *const u8)>, + handles: Vec<(&'a dyn SelectHandle, usize, *const u8)>, /// The next index to assign to an operation. next_index: usize, diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select_macro.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select_macro.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select_macro.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select_macro.rs index 8116a5d..9aaaa9e 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/select_macro.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/select_macro.rs @@ -764,7 +764,7 @@ macro_rules! crossbeam_channel_internal { let _handle: &$crate::internal::SelectHandle = &$crate::never::<()>(); #[allow(unused_mut)] - let mut _sel = [(_handle, 0, 0 as *const u8); _LEN]; + let mut _sel = [(_handle, 0, ::std::ptr::null()); _LEN]; crossbeam_channel_internal!( @add @@ -858,7 +858,7 @@ macro_rules! crossbeam_channel_internal { match _oper { None => { - ::std::mem::drop($sel); + { $sel }; $body } Some(_oper) => { @@ -889,7 +889,7 @@ macro_rules! crossbeam_channel_internal { match _oper { ::std::option::Option::None => { - ::std::mem::drop($sel); + { $sel }; $body } ::std::option::Option::Some(_oper) => { @@ -987,7 +987,7 @@ macro_rules! crossbeam_channel_internal { ) => {{ if $oper.index() == $i { let _res = $oper.recv($r); - ::std::mem::drop($sel); + { $sel }; let $res = _res; $body @@ -1008,7 +1008,7 @@ macro_rules! crossbeam_channel_internal { ) => {{ if $oper.index() == $i { let _res = $oper.send($s, $m); - ::std::mem::drop($sel); + { $sel }; let $res = _res; $body diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/utils.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/utils.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/utils.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/utils.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/src/waker.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/src/waker.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/src/waker.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/src/waker.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/after.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/after.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/after.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/after.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/array.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/array.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/array.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/array.rs index bc97f8b..a6fc845 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/array.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/array.rs @@ -624,7 +624,7 @@ fn recv_in_send() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; let (s, r) = bounded::(1); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/golang.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/golang.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/golang.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/golang.rs index 8f48db6..be015b2 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/golang.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/golang.rs @@ -1289,7 +1289,7 @@ mod chan_test { fn test_chan_send_interface() { struct Mt; - let c = make::>(1); + let c = make::>(1); c.send(Box::new(Mt)); select! { diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/iter.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/iter.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/iter.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/iter.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/list.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/list.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/list.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/list.rs index 2bf4c16..ed1d4c4 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/list.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/list.rs @@ -503,7 +503,7 @@ fn recv_in_send() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; let (s, r) = unbounded::(); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/mpsc.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/mpsc.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/mpsc.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/mpsc.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/never.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/never.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/never.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/never.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/ready.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/ready.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/ready.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/ready.rs index f5efd08..23769b7 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/ready.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/ready.rs @@ -673,7 +673,7 @@ fn send_recv_same_channel() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; for cap in 1..4 { let (s, r) = bounded::(cap); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/same_channel.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/same_channel.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/same_channel.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/same_channel.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select.rs index 7c62a4c..b18d66d 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select.rs @@ -947,7 +947,7 @@ fn matching_with_leftover() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; for cap in 0..3 { let (s, r) = bounded::(cap); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select_macro.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select_macro.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select_macro.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select_macro.rs index 0a7eddb..a9cc7fa 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/select_macro.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/select_macro.rs @@ -687,7 +687,7 @@ fn matching_with_leftover() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; for cap in 0..3 { let (s, r) = bounded::(cap); diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/thread_locals.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/thread_locals.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/thread_locals.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/thread_locals.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/tick.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/tick.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/tick.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/tick.rs diff --git a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/zero.rs b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/zero.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/zero.rs rename to third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/zero.rs index b38227d..bd336ee 100644 --- a/third_party/cargo/vendor/crossbeam-channel-0.3.9/tests/zero.rs +++ b/third_party/cargo/vendor/crossbeam-channel-0.4.2/tests/zero.rs @@ -524,7 +524,7 @@ fn recv_in_send() { fn channel_through_channel() { const COUNT: usize = 1000; - type T = Box; + type T = Box; let (s, r) = bounded::(0); diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-deque-0.6.3/.cargo-checksum.json deleted file mode 100644 index 924b2b0..0000000 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"8c3a2735652220d8601067e0fa560b8c1146671fefb41a78f1cd4d08a12fe697","Cargo.toml":"f221e962c757551c11c9e145b5ef6dc943a8d4670d2230e76c8a6642c2667952","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"b9257b4c9a56e01992ad1ea6dc65e2928cfb27475222e5ef521f9469b8870e48","src/lib.rs":"54d40e045740c2ed857e0b04992b4f718404ec0af48938a9ae33ae59f73e2d84","tests/fifo.rs":"54b78bdd4f53e217291451bef579cdbe571b290ddde7f40dce05c5160a0c2de8","tests/lifo.rs":"8393e2f8f689135d4e9a3ea2da39d665b6cbe55a53be2d07f83969506a8003a6"},"package":"05e44b8cf3e1a625844d1750e1f7820da46044ff6d28f4d43e455ba3e5bb2c13"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/src/lib.rs b/third_party/cargo/vendor/crossbeam-deque-0.6.3/src/lib.rs deleted file mode 100644 index 87e8c77..0000000 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/src/lib.rs +++ /dev/null @@ -1,879 +0,0 @@ -//! A concurrent work-stealing deque. -//! -//! This data structure is most commonly used in schedulers. The typical setup involves a number of -//! threads where each thread has its own deque containing tasks. A thread may push tasks into its -//! deque as well as pop tasks from it. Once it runs out of tasks, it may steal some from other -//! threads to help complete tasks more quickly. Therefore, work-stealing deques supports three -//! essential operations: *push*, *pop*, and *steal*. -//! -//! # Types of deques -//! -//! There are two types of deques, differing only in which order tasks get pushed and popped. The -//! two task ordering strategies are: -//! -//! * First-in first-out (FIFO) -//! * Last-in first-out (LIFO) -//! -//! A deque is a buffer with two ends, front and back. In a FIFO deque, tasks are pushed into the -//! back, popped from the front, and stolen from the front. However, in a LIFO deque, tasks are -//! popped from the back instead - that is the only difference. -//! -//! # Workers and stealers -//! -//! There are two functions that construct a deque: [`fifo`] and [`lifo`]. These functions return a -//! [`Worker`] and a [`Stealer`]. The thread which owns the deque is usually called *worker*, while -//! all other threads are *stealers*. -//! -//! [`Worker`] is able to push and pop tasks. It cannot be shared among multiple threads - only -//! one thread owns it. -//! -//! [`Stealer`] can only steal tasks. It can be shared among multiple threads by reference or by -//! cloning. Cloning a [`Stealer`] simply creates another one associated with the same deque. -//! -//! # Examples -//! -//! ``` -//! use crossbeam_deque::{self as deque, Pop, Steal}; -//! use std::thread; -//! -//! // Create a LIFO deque. -//! let (w, s) = deque::lifo(); -//! -//! // Push several elements into the back. -//! w.push(1); -//! w.push(2); -//! w.push(3); -//! -//! // This is a LIFO deque, which means an element is popped from the back. -//! // If it was a FIFO deque, `w.pop()` would return `Some(1)`. -//! assert_eq!(w.pop(), Pop::Data(3)); -//! -//! // Create a stealer thread. -//! thread::spawn(move || { -//! assert_eq!(s.steal(), Steal::Data(1)); -//! assert_eq!(s.steal(), Steal::Data(2)); -//! }).join().unwrap(); -//! ``` -//! -//! [`Worker`]: struct.Worker.html -//! [`Stealer`]: struct.Stealer.html -//! [`fifo`]: fn.fifo.html -//! [`lifo`]: fn.lifo.html - -#![warn(missing_docs)] -#![warn(missing_debug_implementations)] - -extern crate crossbeam_epoch as epoch; -extern crate crossbeam_utils as utils; - -use std::cell::Cell; -use std::cmp; -use std::fmt; -use std::marker::PhantomData; -use std::mem; -use std::ptr; -use std::sync::atomic::{self, AtomicIsize, Ordering}; -use std::sync::Arc; - -use epoch::{Atomic, Owned}; -use utils::CachePadded; - -/// Minimum buffer capacity for a deque. -const MIN_CAP: usize = 32; - -/// Maximum number of additional elements that can be stolen in `steal_many`. -const MAX_BATCH: usize = 128; - -/// If a buffer of at least this size is retired, thread-local garbage is flushed so that it gets -/// deallocated as soon as possible. -const FLUSH_THRESHOLD_BYTES: usize = 1 << 10; - -/// Creates a work-stealing deque with the first-in first-out strategy. -/// -/// Elements are pushed into the back, popped from the front, and stolen from the front. In other -/// words, the worker side behaves as a FIFO queue. -/// -/// # Examples -/// -/// ``` -/// use crossbeam_deque::{self as deque, Pop, Steal}; -/// -/// let (w, s) = deque::fifo::(); -/// w.push(1); -/// w.push(2); -/// w.push(3); -/// -/// assert_eq!(s.steal(), Steal::Data(1)); -/// assert_eq!(w.pop(), Pop::Data(2)); -/// assert_eq!(w.pop(), Pop::Data(3)); -/// ``` -pub fn fifo() -> (Worker, Stealer) { - let buffer = Buffer::alloc(MIN_CAP); - - let inner = Arc::new(CachePadded::new(Inner { - front: AtomicIsize::new(0), - back: AtomicIsize::new(0), - buffer: Atomic::new(buffer), - })); - - let w = Worker { - inner: inner.clone(), - cached_buffer: Cell::new(buffer), - flavor: Flavor::Fifo, - _marker: PhantomData, - }; - let s = Stealer { - inner, - flavor: Flavor::Fifo, - }; - (w, s) -} - -/// Creates a work-stealing deque with the last-in first-out strategy. -/// -/// Elements are pushed into the back, popped from the back, and stolen from the front. In other -/// words, the worker side behaves as a LIFO stack. -/// -/// # Examples -/// -/// ``` -/// use crossbeam_deque::{self as deque, Pop, Steal}; -/// -/// let (w, s) = deque::lifo::(); -/// w.push(1); -/// w.push(2); -/// w.push(3); -/// -/// assert_eq!(s.steal(), Steal::Data(1)); -/// assert_eq!(w.pop(), Pop::Data(3)); -/// assert_eq!(w.pop(), Pop::Data(2)); -/// ``` -pub fn lifo() -> (Worker, Stealer) { - let buffer = Buffer::alloc(MIN_CAP); - - let inner = Arc::new(CachePadded::new(Inner { - front: AtomicIsize::new(0), - back: AtomicIsize::new(0), - buffer: Atomic::new(buffer), - })); - - let w = Worker { - inner: inner.clone(), - cached_buffer: Cell::new(buffer), - flavor: Flavor::Lifo, - _marker: PhantomData, - }; - let s = Stealer { - inner, - flavor: Flavor::Lifo, - }; - (w, s) -} - -/// A buffer that holds elements in a deque. -/// -/// This is just a pointer to the buffer and its length - dropping an instance of this struct will -/// *not* deallocate the buffer. -struct Buffer { - /// Pointer to the allocated memory. - ptr: *mut T, - - /// Capacity of the buffer. Always a power of two. - cap: usize, -} - -unsafe impl Send for Buffer {} - -impl Buffer { - /// Allocates a new buffer with the specified capacity. - fn alloc(cap: usize) -> Self { - debug_assert_eq!(cap, cap.next_power_of_two()); - - let mut v = Vec::with_capacity(cap); - let ptr = v.as_mut_ptr(); - mem::forget(v); - - Buffer { ptr, cap } - } - - /// Deallocates the buffer. - unsafe fn dealloc(self) { - drop(Vec::from_raw_parts(self.ptr, 0, self.cap)); - } - - /// Returns a pointer to the element at the specified `index`. - unsafe fn at(&self, index: isize) -> *mut T { - // `self.cap` is always a power of two. - self.ptr.offset(index & (self.cap - 1) as isize) - } - - /// Writes `value` into the specified `index`. - /// - /// Using this concurrently with another `read` or `write` is technically - /// speaking UB due to data races. We should be using relaxed accesses, but - /// that would cost too much performance. Hence, as a HACK, we use volatile - /// accesses instead. Experimental evidence shows that this works. - unsafe fn write(&self, index: isize, value: T) { - ptr::write_volatile(self.at(index), value) - } - - /// Reads a value from the specified `index`. - /// - /// Using this concurrently with a `write` is technically speaking UB due to - /// data races. We should be using relaxed accesses, but that would cost - /// too much performance. Hence, as a HACK, we use volatile accesses - /// instead. Experimental evidence shows that this works. - unsafe fn read(&self, index: isize) -> T { - ptr::read_volatile(self.at(index)) - } -} - -impl Clone for Buffer { - fn clone(&self) -> Buffer { - Buffer { - ptr: self.ptr, - cap: self.cap, - } - } -} - -impl Copy for Buffer {} - -/// Possible outcomes of a pop operation. -#[must_use] -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] -pub enum Pop { - /// The deque was empty at the time of popping. - Empty, - - /// Some data has been successfully popped. - Data(T), - - /// Lost the race for popping data to another concurrent steal operation. Try again. - Retry, -} - -/// Possible outcomes of a steal operation. -#[must_use] -#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] -pub enum Steal { - /// The deque was empty at the time of stealing. - Empty, - - /// Some data has been successfully stolen. - Data(T), - - /// Lost the race for stealing data to another concurrent steal or pop operation. Try again. - Retry, -} - -/// Internal data that is shared between the worker and stealers. -/// -/// The implementation is based on the following work: -/// -/// 1. [Chase and Lev. Dynamic circular work-stealing deque. SPAA 2005.][chase-lev] -/// 2. [Le, Pop, Cohen, and Nardelli. Correct and efficient work-stealing for weak memory models. -/// PPoPP 2013.][weak-mem] -/// 3. [Norris and Demsky. CDSchecker: checking concurrent data structures written with C/C++ -/// atomics. OOPSLA 2013.][checker] -/// -/// [chase-lev]: https://dl.acm.org/citation.cfm?id=1073974 -/// [weak-mem]: https://dl.acm.org/citation.cfm?id=2442524 -/// [checker]: https://dl.acm.org/citation.cfm?id=2509514 -struct Inner { - /// The front index. - front: AtomicIsize, - - /// The back index. - back: AtomicIsize, - - /// The underlying buffer. - buffer: Atomic>, -} - -impl Drop for Inner { - fn drop(&mut self) { - // Load the back index, front index, and buffer. - let b = self.back.load(Ordering::Relaxed); - let f = self.front.load(Ordering::Relaxed); - - unsafe { - let buffer = self.buffer.load(Ordering::Relaxed, epoch::unprotected()); - - // Go through the buffer from front to back and drop all elements in the deque. - let mut i = f; - while i != b { - ptr::drop_in_place(buffer.deref().at(i)); - i = i.wrapping_add(1); - } - - // Free the memory allocated by the buffer. - buffer.into_owned().into_box().dealloc(); - } - } -} - -/// The flavor of a deque: FIFO or LIFO. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum Flavor { - /// The first-in first-out flavor. - Fifo, - - /// The last-in first-out flavor. - Lifo, -} - -/// The worker side of a deque. -/// -/// Workers push elements into the back and pop elements depending on the strategy: -/// -/// * In FIFO deques, elements are popped from the front. -/// * In LIFO deques, elements are popped from the back. -/// -/// A deque has only one worker. Workers are not intended to be shared among multiple threads. -pub struct Worker { - /// A reference to the inner representation of the deque. - inner: Arc>>, - - /// A copy of `inner.buffer` for quick access. - cached_buffer: Cell>, - - /// The flavor of the deque. - flavor: Flavor, - - /// Indicates that the worker cannot be shared among threads. - _marker: PhantomData<*mut ()>, // !Send + !Sync -} - -unsafe impl Send for Worker {} - -impl Worker { - /// Resizes the internal buffer to the new capacity of `new_cap`. - #[cold] - unsafe fn resize(&self, new_cap: usize) { - // Load the back index, front index, and buffer. - let b = self.inner.back.load(Ordering::Relaxed); - let f = self.inner.front.load(Ordering::Relaxed); - let buffer = self.cached_buffer.get(); - - // Allocate a new buffer. - let new = Buffer::alloc(new_cap); - self.cached_buffer.set(new); - - // Copy data from the old buffer to the new one. - let mut i = f; - while i != b { - ptr::copy_nonoverlapping(buffer.at(i), new.at(i), 1); - i = i.wrapping_add(1); - } - - let guard = &epoch::pin(); - - // Replace the old buffer with the new one. - let old = - self.inner - .buffer - .swap(Owned::new(new).into_shared(guard), Ordering::Release, guard); - - // Destroy the old buffer later. - guard.defer_unchecked(move || old.into_owned().into_box().dealloc()); - - // If the buffer is very large, then flush the thread-local garbage in order to deallocate - // it as soon as possible. - if mem::size_of::() * new_cap >= FLUSH_THRESHOLD_BYTES { - guard.flush(); - } - } - - /// Reserves enough capacity so that `reserve_cap` elements can be pushed without growing the - /// buffer. - fn reserve(&self, reserve_cap: usize) { - if reserve_cap > 0 { - // Compute the current length. - let b = self.inner.back.load(Ordering::Relaxed); - let f = self.inner.front.load(Ordering::SeqCst); - let len = b.wrapping_sub(f) as usize; - - // The current capacity. - let cap = self.cached_buffer.get().cap; - - // Is there enough capacity to push `reserve_cap` elements? - if cap - len < reserve_cap { - // Keep doubling the capacity as much as is needed. - let mut new_cap = cap * 2; - while new_cap - len < reserve_cap { - new_cap *= 2; - } - - // Resize the buffer. - unsafe { - self.resize(new_cap); - } - } - } - } - - /// Returns `true` if the deque is empty. - /// - /// ``` - /// use crossbeam_deque as deque; - /// - /// let (w, _) = deque::lifo(); - /// assert!(w.is_empty()); - /// w.push(1); - /// assert!(!w.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { - let b = self.inner.back.load(Ordering::Relaxed); - let f = self.inner.front.load(Ordering::SeqCst); - b.wrapping_sub(f) <= 0 - } - - /// Pushes an element into the back of the deque. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_deque as deque; - /// - /// let (w, _) = deque::lifo(); - /// w.push(1); - /// w.push(2); - /// ``` - pub fn push(&self, value: T) { - // Load the back index, front index, and buffer. - let b = self.inner.back.load(Ordering::Relaxed); - let f = self.inner.front.load(Ordering::Acquire); - let mut buffer = self.cached_buffer.get(); - - // Calculate the length of the deque. - let len = b.wrapping_sub(f); - - // Is the deque full? - if len >= buffer.cap as isize { - // Yes. Grow the underlying buffer. - unsafe { - self.resize(2 * buffer.cap); - } - buffer = self.cached_buffer.get(); - } - - // Write `value` into the slot. - unsafe { - buffer.write(b, value); - } - - atomic::fence(Ordering::Release); - - // Increment the back index. - // - // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data - // races because it doesn't understand fences. - self.inner.back.store(b.wrapping_add(1), Ordering::Release); - } - - /// Pops an element from the deque. - /// - /// Which end of the deque is used depends on the strategy: - /// - /// * If this is a FIFO deque, an element is popped from the front. - /// * If this is a LIFO deque, an element is popped from the back. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_deque::{self as deque, Pop}; - /// - /// let (w, _) = deque::fifo(); - /// w.push(1); - /// w.push(2); - /// - /// assert_eq!(w.pop(), Pop::Data(1)); - /// assert_eq!(w.pop(), Pop::Data(2)); - /// assert_eq!(w.pop(), Pop::Empty); - /// ``` - pub fn pop(&self) -> Pop { - // Load the back and front index. - let b = self.inner.back.load(Ordering::Relaxed); - let f = self.inner.front.load(Ordering::Relaxed); - - // Calculate the length of the deque. - let len = b.wrapping_sub(f); - - // Is the deque empty? - if len <= 0 { - return Pop::Empty; - } - - match self.flavor { - // Pop from the front of the deque. - Flavor::Fifo => { - // Try incrementing the front index to pop the value. - if self - .inner - .front - .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) - .is_ok() - { - unsafe { - // Read the popped value. - let buffer = self.cached_buffer.get(); - let data = buffer.read(f); - - // Shrink the buffer if `len - 1` is less than one fourth of the capacity. - if buffer.cap > MIN_CAP && len <= buffer.cap as isize / 4 { - self.resize(buffer.cap / 2); - } - - return Pop::Data(data); - } - } - - Pop::Retry - } - - // Pop from the back of the deque. - Flavor::Lifo => { - // Decrement the back index. - let b = b.wrapping_sub(1); - self.inner.back.store(b, Ordering::Relaxed); - - atomic::fence(Ordering::SeqCst); - - // Load the front index. - let f = self.inner.front.load(Ordering::Relaxed); - - // Compute the length after the back index was decremented. - let len = b.wrapping_sub(f); - - if len < 0 { - // The deque is empty. Restore the back index to the original value. - self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed); - Pop::Empty - } else { - // Read the value to be popped. - let buffer = self.cached_buffer.get(); - let mut value = unsafe { Some(buffer.read(b)) }; - - // Are we popping the last element from the deque? - if len == 0 { - // Try incrementing the front index. - if self - .inner - .front - .compare_exchange( - f, - f.wrapping_add(1), - Ordering::SeqCst, - Ordering::Relaxed, - ).is_err() - { - // Failed. We didn't pop anything. - mem::forget(value.take()); - } - - // Restore the back index to the original value. - self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed); - } else { - // Shrink the buffer if `len` is less than one fourth of the capacity. - if buffer.cap > MIN_CAP && len < buffer.cap as isize / 4 { - unsafe { - self.resize(buffer.cap / 2); - } - } - } - - match value { - None => Pop::Empty, - Some(data) => Pop::Data(data), - } - } - } - } - } -} - -impl fmt::Debug for Worker { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("Worker { .. }") - } -} - -/// The stealer side of a deque. -/// -/// Stealers can only steal elements from the front of the deque. -/// -/// Stealers are cloneable so that they can be easily shared among multiple threads. -pub struct Stealer { - /// A reference to the inner representation of the deque. - inner: Arc>>, - - /// The flavor of the deque. - flavor: Flavor, -} - -unsafe impl Send for Stealer {} -unsafe impl Sync for Stealer {} - -impl Stealer { - /// Returns `true` if the deque is empty. - /// - /// ``` - /// use crossbeam_deque as deque; - /// - /// let (w, s) = deque::lifo(); - /// assert!(s.is_empty()); - /// w.push(1); - /// assert!(!s.is_empty()); - /// ``` - pub fn is_empty(&self) -> bool { - let f = self.inner.front.load(Ordering::Acquire); - atomic::fence(Ordering::SeqCst); - let b = self.inner.back.load(Ordering::Acquire); - b.wrapping_sub(f) <= 0 - } - - /// Steals an element from the front of the deque. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_deque::{self as deque, Steal}; - /// - /// let (w, s) = deque::lifo(); - /// w.push(1); - /// w.push(2); - /// - /// assert_eq!(s.steal(), Steal::Data(1)); - /// assert_eq!(s.steal(), Steal::Data(2)); - /// assert_eq!(s.steal(), Steal::Empty); - /// ``` - pub fn steal(&self) -> Steal { - // Load the front index. - let f = self.inner.front.load(Ordering::Acquire); - - // A SeqCst fence is needed here. - // - // If the current thread is already pinned (reentrantly), we must manually issue the - // fence. Otherwise, the following pinning will issue the fence anyway, so we don't - // have to. - if epoch::is_pinned() { - atomic::fence(Ordering::SeqCst); - } - - let guard = &epoch::pin(); - - // Load the back index. - let b = self.inner.back.load(Ordering::Acquire); - - // Is the deque empty? - if b.wrapping_sub(f) <= 0 { - return Steal::Empty; - } - - // Load the buffer and read the value at the front. - let buffer = self.inner.buffer.load(Ordering::Acquire, guard); - let value = unsafe { buffer.deref().read(f) }; - - // Try incrementing the front index to steal the value. - if self - .inner - .front - .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) - .is_err() - { - // We didn't steal this value, forget it. - mem::forget(value); - return Steal::Retry; - } - - // Return the stolen value. - Steal::Data(value) - } - - /// Steals elements from the front of the deque. - /// - /// If at least one element can be stolen, it will be returned. Additionally, some of the - /// remaining elements will be stolen and pushed into the back of worker `dest` in order to - /// balance the work among deques. There is no hard guarantee on exactly how many elements will - /// be stolen, but it should be around half of the deque. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_deque::{self as deque, Steal}; - /// - /// let (w1, s1) = deque::fifo(); - /// let (w2, s2) = deque::fifo(); - /// - /// w1.push(1); - /// w1.push(2); - /// w1.push(3); - /// w1.push(4); - /// - /// assert_eq!(s1.steal_many(&w2), Steal::Data(1)); - /// assert_eq!(s2.steal(), Steal::Data(2)); - /// ``` - pub fn steal_many(&self, dest: &Worker) -> Steal { - // Load the front index. - let mut f = self.inner.front.load(Ordering::Acquire); - - // A SeqCst fence is needed here. - // - // If the current thread is already pinned (reentrantly), we must manually issue the - // fence. Otherwise, the following pinning will issue the fence anyway, so we don't - // have to. - if epoch::is_pinned() { - atomic::fence(Ordering::SeqCst); - } - - let guard = &epoch::pin(); - - // Load the back index. - let b = self.inner.back.load(Ordering::Acquire); - - // Is the deque empty? - let len = b.wrapping_sub(f); - if len <= 0 { - return Steal::Empty; - } - - // Reserve capacity for the stolen additional elements. - let additional = cmp::min((len as usize - 1) / 2, MAX_BATCH); - dest.reserve(additional); - let additional = additional as isize; - - // Get the destination buffer and back index. - let dest_buffer = dest.cached_buffer.get(); - let mut dest_b = dest.inner.back.load(Ordering::Relaxed); - - // Load the buffer and read the value at the front. - let buffer = self.inner.buffer.load(Ordering::Acquire, guard); - let value = unsafe { buffer.deref().read(f) }; - - match self.flavor { - // Steal a batch of elements from the front at once. - Flavor::Fifo => { - // Copy the additional elements from the source to the destination buffer. - for i in 0..additional { - unsafe { - let value = buffer.deref().read(f.wrapping_add(i + 1)); - dest_buffer.write(dest_b.wrapping_add(i), value); - } - } - - // Try incrementing the front index to steal the batch. - if self - .inner - .front - .compare_exchange( - f, - f.wrapping_add(additional + 1), - Ordering::SeqCst, - Ordering::Relaxed, - ).is_err() - { - // We didn't steal this value, forget it. - mem::forget(value); - return Steal::Retry; - } - - atomic::fence(Ordering::Release); - - // Success! Update the back index in the destination deque. - // - // This ordering could be `Relaxed`, but then thread sanitizer would falsely report - // data races because it doesn't understand fences. - dest.inner - .back - .store(dest_b.wrapping_add(additional), Ordering::Release); - - // Return the first stolen value. - Steal::Data(value) - } - - // Steal a batch of elements from the front one by one. - Flavor::Lifo => { - // Try incrementing the front index to steal the value. - if self - .inner - .front - .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) - .is_err() - { - // We didn't steal this value, forget it. - mem::forget(value); - return Steal::Retry; - } - - // Move the front index one step forward. - f = f.wrapping_add(1); - - // Repeat the same procedure for the additional steals. - for _ in 0..additional { - // We've already got the current front index. Now execute the fence to - // synchronize with other threads. - atomic::fence(Ordering::SeqCst); - - // Load the back index. - let b = self.inner.back.load(Ordering::Acquire); - - // Is the deque empty? - if b.wrapping_sub(f) <= 0 { - break; - } - - // Read the value at the front. - let value = unsafe { buffer.deref().read(f) }; - - // Try incrementing the front index to steal the value. - if self - .inner - .front - .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) - .is_err() - { - // We didn't steal this value, forget it and break from the loop. - mem::forget(value); - break; - } - - // Write the stolen value into the destination buffer. - unsafe { - dest_buffer.write(dest_b, value); - } - - // Move the source front index and the destination back index one step forward. - f = f.wrapping_add(1); - dest_b = dest_b.wrapping_add(1); - - atomic::fence(Ordering::Release); - - // Update the destination back index. - // - // This ordering could be `Relaxed`, but then thread sanitizer would falsely - // report data races because it doesn't understand fences. - dest.inner.back.store(dest_b, Ordering::Release); - } - - // Return the first stolen value. - Steal::Data(value) - } - } - } -} - -impl Clone for Stealer { - fn clone(&self) -> Stealer { - Stealer { - inner: self.inner.clone(), - flavor: self.flavor, - } - } -} - -impl fmt::Debug for Stealer { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("Stealer { .. }") - } -} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/fifo.rs b/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/fifo.rs deleted file mode 100644 index e97db11..0000000 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/fifo.rs +++ /dev/null @@ -1,371 +0,0 @@ -extern crate crossbeam_deque as deque; -extern crate crossbeam_epoch as epoch; -extern crate rand; - -use std::sync::atomic::Ordering::SeqCst; -use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::sync::{Arc, Mutex}; -use std::thread; - -use deque::{Pop, Steal}; -use rand::Rng; - -#[test] -fn smoke() { - let (w, s) = deque::fifo::(); - assert_eq!(w.pop(), Pop::Empty); - assert_eq!(s.steal(), Steal::Empty); - - w.push(1); - assert_eq!(w.pop(), Pop::Data(1)); - assert_eq!(w.pop(), Pop::Empty); - assert_eq!(s.steal(), Steal::Empty); - - w.push(2); - assert_eq!(s.steal(), Steal::Data(2)); - assert_eq!(s.steal(), Steal::Empty); - assert_eq!(w.pop(), Pop::Empty); - - w.push(3); - w.push(4); - w.push(5); - assert_eq!(s.steal(), Steal::Data(3)); - assert_eq!(s.steal(), Steal::Data(4)); - assert_eq!(s.steal(), Steal::Data(5)); - assert_eq!(s.steal(), Steal::Empty); - - w.push(6); - w.push(7); - w.push(8); - w.push(9); - assert_eq!(w.pop(), Pop::Data(6)); - assert_eq!(s.steal(), Steal::Data(7)); - assert_eq!(w.pop(), Pop::Data(8)); - assert_eq!(w.pop(), Pop::Data(9)); - assert_eq!(w.pop(), Pop::Empty); -} - -#[test] -fn steal_push() { - const STEPS: usize = 50_000; - - let (w, s) = deque::fifo(); - let t = thread::spawn(move || { - for i in 0..STEPS { - loop { - if let Steal::Data(v) = s.steal() { - assert_eq!(i, v); - break; - } - } - } - }); - - for i in 0..STEPS { - w.push(i); - } - t.join().unwrap(); -} - -#[test] -fn stampede() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::fifo(); - - for i in 0..COUNT { - w.push(Box::new(i + 1)); - } - let remaining = Arc::new(AtomicUsize::new(COUNT)); - - let threads = (0..THREADS) - .map(|_| { - let s = s.clone(); - let remaining = remaining.clone(); - - thread::spawn(move || { - let mut last = 0; - while remaining.load(SeqCst) > 0 { - if let Steal::Data(x) = s.steal() { - assert!(last < *x); - last = *x; - remaining.fetch_sub(1, SeqCst); - } - } - }) - }).collect::>(); - - let mut last = 0; - while remaining.load(SeqCst) > 0 { - loop { - match w.pop() { - Pop::Data(x) => { - assert!(last < *x); - last = *x; - remaining.fetch_sub(1, SeqCst); - break; - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - - for t in threads { - t.join().unwrap(); - } -} - -fn run_stress() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::fifo(); - let done = Arc::new(AtomicBool::new(false)); - let hits = Arc::new(AtomicUsize::new(0)); - - let threads = (0..THREADS) - .map(|_| { - let s = s.clone(); - let done = done.clone(); - let hits = hits.clone(); - - thread::spawn(move || { - let (w2, _) = deque::fifo(); - - while !done.load(SeqCst) { - if let Steal::Data(_) = s.steal() { - hits.fetch_add(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - hits.fetch_add(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }).collect::>(); - - let mut rng = rand::thread_rng(); - let mut expected = 0; - while expected < COUNT { - if rng.gen_range(0, 3) == 0 { - loop { - match w.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } else { - w.push(expected); - expected += 1; - } - } - - while hits.load(SeqCst) < COUNT { - loop { - match w.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - done.store(true, SeqCst); - - for t in threads { - t.join().unwrap(); - } -} - -#[test] -fn stress() { - run_stress(); -} - -#[test] -fn stress_pinned() { - let _guard = epoch::pin(); - run_stress(); -} - -#[test] -fn no_starvation() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::fifo(); - let done = Arc::new(AtomicBool::new(false)); - - let (threads, hits): (Vec<_>, Vec<_>) = (0..THREADS) - .map(|_| { - let s = s.clone(); - let done = done.clone(); - let hits = Arc::new(AtomicUsize::new(0)); - - let t = { - let hits = hits.clone(); - thread::spawn(move || { - let (w2, _) = deque::fifo(); - - while !done.load(SeqCst) { - if let Steal::Data(_) = s.steal() { - hits.fetch_add(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - hits.fetch_add(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }; - - (t, hits) - }).unzip(); - - let mut rng = rand::thread_rng(); - let mut my_hits = 0; - loop { - for i in 0..rng.gen_range(0, COUNT) { - if rng.gen_range(0, 3) == 0 && my_hits == 0 { - loop { - match w.pop() { - Pop::Data(_) => my_hits += 1, - Pop::Empty => break, - Pop::Retry => {} - } - } - } else { - w.push(i); - } - } - - if my_hits > 0 && hits.iter().all(|h| h.load(SeqCst) > 0) { - break; - } - } - done.store(true, SeqCst); - - for t in threads { - t.join().unwrap(); - } -} - -#[test] -fn destructors() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - const STEPS: usize = 1000; - - struct Elem(usize, Arc>>); - - impl Drop for Elem { - fn drop(&mut self) { - self.1.lock().unwrap().push(self.0); - } - } - - let (w, s) = deque::fifo(); - - let dropped = Arc::new(Mutex::new(Vec::new())); - let remaining = Arc::new(AtomicUsize::new(COUNT)); - for i in 0..COUNT { - w.push(Elem(i, dropped.clone())); - } - - let threads = (0..THREADS) - .map(|_| { - let remaining = remaining.clone(); - let s = s.clone(); - - thread::spawn(move || { - let (w2, _) = deque::fifo(); - let mut cnt = 0; - - while cnt < STEPS { - if let Steal::Data(_) = s.steal() { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }).collect::>(); - - for _ in 0..STEPS { - loop { - match w.pop() { - Pop::Data(_) => { - remaining.fetch_sub(1, SeqCst); - break; - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - - for t in threads { - t.join().unwrap(); - } - - let rem = remaining.load(SeqCst); - assert!(rem > 0); - - { - let mut v = dropped.lock().unwrap(); - assert_eq!(v.len(), COUNT - rem); - v.clear(); - } - - drop((w, s)); - - { - let mut v = dropped.lock().unwrap(); - assert_eq!(v.len(), rem); - v.sort(); - for pair in v.windows(2) { - assert_eq!(pair[0] + 1, pair[1]); - } - } -} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/lifo.rs b/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/lifo.rs deleted file mode 100644 index e566327..0000000 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/tests/lifo.rs +++ /dev/null @@ -1,371 +0,0 @@ -extern crate crossbeam_deque as deque; -extern crate crossbeam_epoch as epoch; -extern crate rand; - -use std::sync::atomic::Ordering::SeqCst; -use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::sync::{Arc, Mutex}; -use std::thread; - -use deque::{Pop, Steal}; -use rand::Rng; - -#[test] -fn smoke() { - let (w, s) = deque::lifo::(); - assert_eq!(w.pop(), Pop::Empty); - assert_eq!(s.steal(), Steal::Empty); - - w.push(1); - assert_eq!(w.pop(), Pop::Data(1)); - assert_eq!(w.pop(), Pop::Empty); - assert_eq!(s.steal(), Steal::Empty); - - w.push(2); - assert_eq!(s.steal(), Steal::Data(2)); - assert_eq!(s.steal(), Steal::Empty); - assert_eq!(w.pop(), Pop::Empty); - - w.push(3); - w.push(4); - w.push(5); - assert_eq!(s.steal(), Steal::Data(3)); - assert_eq!(s.steal(), Steal::Data(4)); - assert_eq!(s.steal(), Steal::Data(5)); - assert_eq!(s.steal(), Steal::Empty); - - w.push(6); - w.push(7); - w.push(8); - w.push(9); - assert_eq!(w.pop(), Pop::Data(9)); - assert_eq!(s.steal(), Steal::Data(6)); - assert_eq!(w.pop(), Pop::Data(8)); - assert_eq!(w.pop(), Pop::Data(7)); - assert_eq!(w.pop(), Pop::Empty); -} - -#[test] -fn steal_push() { - const STEPS: usize = 50_000; - - let (w, s) = deque::lifo(); - let t = thread::spawn(move || { - for i in 0..STEPS { - loop { - if let Steal::Data(v) = s.steal() { - assert_eq!(i, v); - break; - } - } - } - }); - - for i in 0..STEPS { - w.push(i); - } - t.join().unwrap(); -} - -#[test] -fn stampede() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::lifo(); - - for i in 0..COUNT { - w.push(Box::new(i + 1)); - } - let remaining = Arc::new(AtomicUsize::new(COUNT)); - - let threads = (0..THREADS) - .map(|_| { - let s = s.clone(); - let remaining = remaining.clone(); - - thread::spawn(move || { - let mut last = 0; - while remaining.load(SeqCst) > 0 { - if let Steal::Data(x) = s.steal() { - assert!(last < *x); - last = *x; - remaining.fetch_sub(1, SeqCst); - } - } - }) - }).collect::>(); - - let mut last = COUNT + 1; - while remaining.load(SeqCst) > 0 { - loop { - match w.pop() { - Pop::Data(x) => { - assert!(last > *x); - last = *x; - remaining.fetch_sub(1, SeqCst); - break; - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - - for t in threads { - t.join().unwrap(); - } -} - -fn run_stress() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::lifo(); - let done = Arc::new(AtomicBool::new(false)); - let hits = Arc::new(AtomicUsize::new(0)); - - let threads = (0..THREADS) - .map(|_| { - let s = s.clone(); - let done = done.clone(); - let hits = hits.clone(); - - thread::spawn(move || { - let (w2, _) = deque::lifo(); - - while !done.load(SeqCst) { - if let Steal::Data(_) = s.steal() { - hits.fetch_add(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - hits.fetch_add(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }).collect::>(); - - let mut rng = rand::thread_rng(); - let mut expected = 0; - while expected < COUNT { - if rng.gen_range(0, 3) == 0 { - loop { - match w.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } else { - w.push(expected); - expected += 1; - } - } - - while hits.load(SeqCst) < COUNT { - loop { - match w.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - done.store(true, SeqCst); - - for t in threads { - t.join().unwrap(); - } -} - -#[test] -fn stress() { - run_stress(); -} - -#[test] -fn stress_pinned() { - let _guard = epoch::pin(); - run_stress(); -} - -#[test] -fn no_starvation() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - - let (w, s) = deque::lifo(); - let done = Arc::new(AtomicBool::new(false)); - - let (threads, hits): (Vec<_>, Vec<_>) = (0..THREADS) - .map(|_| { - let s = s.clone(); - let done = done.clone(); - let hits = Arc::new(AtomicUsize::new(0)); - - let t = { - let hits = hits.clone(); - thread::spawn(move || { - let (w2, _) = deque::lifo(); - - while !done.load(SeqCst) { - if let Steal::Data(_) = s.steal() { - hits.fetch_add(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - hits.fetch_add(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - hits.fetch_add(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }; - - (t, hits) - }).unzip(); - - let mut rng = rand::thread_rng(); - let mut my_hits = 0; - loop { - for i in 0..rng.gen_range(0, COUNT) { - if rng.gen_range(0, 3) == 0 && my_hits == 0 { - loop { - match w.pop() { - Pop::Data(_) => my_hits += 1, - Pop::Empty => break, - Pop::Retry => {} - } - } - } else { - w.push(i); - } - } - - if my_hits > 0 && hits.iter().all(|h| h.load(SeqCst) > 0) { - break; - } - } - done.store(true, SeqCst); - - for t in threads { - t.join().unwrap(); - } -} - -#[test] -fn destructors() { - const THREADS: usize = 8; - const COUNT: usize = 50_000; - const STEPS: usize = 1000; - - struct Elem(usize, Arc>>); - - impl Drop for Elem { - fn drop(&mut self) { - self.1.lock().unwrap().push(self.0); - } - } - - let (w, s) = deque::lifo(); - - let dropped = Arc::new(Mutex::new(Vec::new())); - let remaining = Arc::new(AtomicUsize::new(COUNT)); - for i in 0..COUNT { - w.push(Elem(i, dropped.clone())); - } - - let threads = (0..THREADS) - .map(|_| { - let remaining = remaining.clone(); - let s = s.clone(); - - thread::spawn(move || { - let (w2, _) = deque::lifo(); - let mut cnt = 0; - - while cnt < STEPS { - if let Steal::Data(_) = s.steal() { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - } - - if let Steal::Data(_) = s.steal_many(&w2) { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - - loop { - match w2.pop() { - Pop::Data(_) => { - cnt += 1; - remaining.fetch_sub(1, SeqCst); - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - } - }) - }).collect::>(); - - for _ in 0..STEPS { - loop { - match w.pop() { - Pop::Data(_) => { - remaining.fetch_sub(1, SeqCst); - break; - } - Pop::Empty => break, - Pop::Retry => {} - } - } - } - - for t in threads { - t.join().unwrap(); - } - - let rem = remaining.load(SeqCst); - assert!(rem > 0); - - { - let mut v = dropped.lock().unwrap(); - assert_eq!(v.len(), COUNT - rem); - v.clear(); - } - - drop((w, s)); - - { - let mut v = dropped.lock().unwrap(); - assert_eq!(v.len(), rem); - v.sort(); - for pair in v.windows(2) { - assert_eq!(pair[0] + 1, pair[1]); - } - } -} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-deque-0.7.3/.cargo-checksum.json new file mode 100644 index 0000000..202fdfe --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"f917b6e83aed21fcdb7615602b74377374144b6e075d1d96e9dac8c266795cab","Cargo.toml":"d160e0a9f564fa20e503f81a837057b09bdc8632d8b71c6a3d4a0a67c0bcaa21","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"c1e2f0e311bab5c2b82a9346e7b2fdaf17050a66913aad57fac40665fb65bb7b","src/lib.rs":"78b31a8d769607304d5d6250f8b06f257160b7c8b43ced5ef40f4ec3a51e076b","tests/fifo.rs":"7546ce471330a9d928a54f6ca41ddd36e9f4999852fdc4719bf9b24122a1c15f","tests/injector.rs":"c9107b437f790dbfab333f94d7211df29bb9a868d2d86304ad9fd7fa8db57d0a","tests/lifo.rs":"264967bc868870211e12a826f448a6d9e19ab5f7cc0e0bde86496cf76bb96e56","tests/steal.rs":"519549c18429db563c5238d7147e733901336943ca099669af2b553933b82694"},"package":"9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/BUILD b/third_party/cargo/vendor/crossbeam-deque-0.7.3/BUILD similarity index 72% rename from third_party/cargo/vendor/crossbeam-deque-0.6.3/BUILD rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/BUILD index e9ba6b2..f7379ef 100644 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/BUILD +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/BUILD @@ -31,16 +31,19 @@ rust_library( edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/crossbeam-epoch-0.7.2:crossbeam_epoch", - "//third_party/cargo/vendor/crossbeam-utils-0.6.6:crossbeam_utils", + "//third_party/cargo/vendor/crossbeam-epoch-0.8.2:crossbeam_epoch", + "//third_party/cargo/vendor/crossbeam-utils-0.7.2:crossbeam_utils", + "//third_party/cargo/vendor/maybe-uninit-2.0.0:maybe_uninit", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.6.3", + version = "0.7.3", crate_features = [ ], ) # Unsupported target "fifo" with type "test" omitted +# Unsupported target "injector" with type "test" omitted # Unsupported target "lifo" with type "test" omitted +# Unsupported target "steal" with type "test" omitted diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-deque-0.7.3/CHANGELOG.md similarity index 68% rename from third_party/cargo/vendor/crossbeam-deque-0.6.3/CHANGELOG.md rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/CHANGELOG.md index 15fa29f..54e9ae4 100644 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/CHANGELOG.md +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/CHANGELOG.md @@ -1,3 +1,27 @@ +# Version 0.7.3 + +- Stop stealing from the same deque. (#448) +- Fix unsoundness issues by adopting `MaybeUninit`. (#458) + +# Version 0.7.2 + +- Bump `crossbeam-epoch` to `0.8`. +- Bump `crossbeam-utils` to `0.7`. + +# Version 0.7.1 + +- Bump the minimum required version of `crossbeam-utils`. + +# Version 0.7.0 + +- Make `Worker::pop()` faster in the FIFO case. +- Replace `fifo()` nad `lifo()` with `Worker::new_fifo()` and `Worker::new_lifo()`. +- Add more batched steal methods. +- Introduce `Injector`, a MPMC queue. +- Rename `Steal::Data` to `Steal::Success`. +- Add `Steal::or_else()` and implement `FromIterator` for `Steal`. +- Add `#[must_use]` to `Steal`. + # Version 0.6.3 - Bump `crossbeam-epoch` to `0.7`. diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/Cargo.toml b/third_party/cargo/vendor/crossbeam-deque-0.7.3/Cargo.toml similarity index 82% rename from third_party/cargo/vendor/crossbeam-deque-0.6.3/Cargo.toml rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/Cargo.toml index f22f5aa..0cf94c2 100644 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/Cargo.toml +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,10 +12,10 @@ [package] name = "crossbeam-deque" -version = "0.6.3" +version = "0.7.3" authors = ["The Crossbeam Project Developers"] description = "Concurrent work-stealing deque" -homepage = "https://github.com/crossbeam-rs/crossbeam" +homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-deque" documentation = "https://docs.rs/crossbeam-deque" readme = "README.md" keywords = ["chase-lev", "lock-free", "scheduler", "scheduling"] @@ -23,9 +23,12 @@ categories = ["algorithms", "concurrency", "data-structures"] license = "MIT/Apache-2.0" repository = "https://github.com/crossbeam-rs/crossbeam" [dependencies.crossbeam-epoch] -version = "0.7" +version = "0.8" [dependencies.crossbeam-utils] -version = "0.6" +version = "0.7" + +[dependencies.maybe-uninit] +version = "2.0.0" [dev-dependencies.rand] version = "0.6" diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-deque-0.7.3/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-deque-0.6.3/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/LICENSE-APACHE diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-deque-0.7.3/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/LICENSE-MIT diff --git a/third_party/cargo/vendor/crossbeam-deque-0.6.3/README.md b/third_party/cargo/vendor/crossbeam-deque-0.7.3/README.md similarity index 80% rename from third_party/cargo/vendor/crossbeam-deque-0.6.3/README.md rename to third_party/cargo/vendor/crossbeam-deque-0.7.3/README.md index 7ebebd0..a5ef93a 100644 --- a/third_party/cargo/vendor/crossbeam-deque-0.6.3/README.md +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/README.md @@ -8,8 +8,9 @@ https://github.com/crossbeam-rs/crossbeam-deque) https://crates.io/crates/crossbeam-deque) [![Documentation](https://docs.rs/crossbeam-deque/badge.svg)]( https://docs.rs/crossbeam-deque) -[![Rust 1.26+](https://img.shields.io/badge/rust-1.26+-lightgray.svg)]( +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( https://www.rust-lang.org) +[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/BBYwKq) This crate provides work-stealing deques, which are primarily intended for building task schedulers. @@ -20,7 +21,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -crossbeam-deque = "0.6" +crossbeam-deque = "0.7" ``` Next, add this to your crate: @@ -31,9 +32,7 @@ extern crate crossbeam_deque; ## Compatibility -The minimum supported Rust version is 1.26. - -This crate does not work in `no_std` environments. +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. ## License @@ -44,7 +43,7 @@ Licensed under either of at your option. -### Contribution +#### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/src/lib.rs b/third_party/cargo/vendor/crossbeam-deque-0.7.3/src/lib.rs new file mode 100644 index 0000000..5900417 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/src/lib.rs @@ -0,0 +1,2016 @@ +//! Concurrent work-stealing deques. +//! +//! These data structures are most commonly used in work-stealing schedulers. The typical setup +//! involves a number of threads, each having its own FIFO or LIFO queue (*worker*). There is also +//! one global FIFO queue (*injector*) and a list of references to *worker* queues that are able to +//! steal tasks (*stealers*). +//! +//! We spawn a new task onto the scheduler by pushing it into the *injector* queue. Each worker +//! thread waits in a loop until it finds the next task to run and then runs it. To find a task, it +//! first looks into its local *worker* queue, and then into the *injector* and *stealers*. +//! +//! # Queues +//! +//! [`Injector`] is a FIFO queue, where tasks are pushed and stolen from opposite ends. It is +//! shared among threads and is usually the entry point for new tasks. +//! +//! [`Worker`] has two constructors: +//! +//! * [`new_fifo()`] - Creates a FIFO queue, in which tasks are pushed and popped from opposite +//! ends. +//! * [`new_lifo()`] - Creates a LIFO queue, in which tasks are pushed and popped from the same +//! end. +//! +//! Each [`Worker`] is owned by a single thread and supports only push and pop operations. +//! +//! Method [`stealer()`] creates a [`Stealer`] that may be shared among threads and can only steal +//! tasks from its [`Worker`]. Tasks are stolen from the end opposite to where they get pushed. +//! +//! # Stealing +//! +//! Steal operations come in three flavors: +//! +//! 1. [`steal()`] - Steals one task. +//! 2. [`steal_batch()`] - Steals a batch of tasks and moves them into another worker. +//! 3. [`steal_batch_and_pop()`] - Steals a batch of tasks, moves them into another queue, and pops +//! one task from that worker. +//! +//! In contrast to push and pop operations, stealing can spuriously fail with [`Steal::Retry`], in +//! which case the steal operation needs to be retried. +//! +//! # Examples +//! +//! Suppose a thread in a work-stealing scheduler is idle and looking for the next task to run. To +//! find an available task, it might do the following: +//! +//! 1. Try popping one task from the local worker queue. +//! 2. Try stealing a batch of tasks from the global injector queue. +//! 3. Try stealing one task from another thread using the stealer list. +//! +//! An implementation of this work-stealing strategy: +//! +//! ``` +//! use crossbeam_deque::{Injector, Steal, Stealer, Worker}; +//! use std::iter; +//! +//! fn find_task( +//! local: &Worker, +//! global: &Injector, +//! stealers: &[Stealer], +//! ) -> Option { +//! // Pop a task from the local queue, if not empty. +//! local.pop().or_else(|| { +//! // Otherwise, we need to look for a task elsewhere. +//! iter::repeat_with(|| { +//! // Try stealing a batch of tasks from the global queue. +//! global.steal_batch_and_pop(local) +//! // Or try stealing a task from one of the other threads. +//! .or_else(|| stealers.iter().map(|s| s.steal()).collect()) +//! }) +//! // Loop while no task was stolen and any steal operation needs to be retried. +//! .find(|s| !s.is_retry()) +//! // Extract the stolen task, if there is one. +//! .and_then(|s| s.success()) +//! }) +//! } +//! ``` +//! +//! [`Worker`]: struct.Worker.html +//! [`Stealer`]: struct.Stealer.html +//! [`Injector`]: struct.Injector.html +//! [`Steal::Retry`]: enum.Steal.html#variant.Retry +//! [`new_fifo()`]: struct.Worker.html#method.new_fifo +//! [`new_lifo()`]: struct.Worker.html#method.new_lifo +//! [`stealer()`]: struct.Worker.html#method.stealer +//! [`steal()`]: struct.Stealer.html#method.steal +//! [`steal_batch()`]: struct.Stealer.html#method.steal_batch +//! [`steal_batch_and_pop()`]: struct.Stealer.html#method.steal_batch_and_pop + +#![warn(missing_docs)] +#![warn(missing_debug_implementations)] + +extern crate crossbeam_epoch as epoch; +extern crate crossbeam_utils as utils; + +extern crate maybe_uninit; + +use std::cell::{Cell, UnsafeCell}; +use std::cmp; +use std::fmt; +use std::iter::FromIterator; +use std::marker::PhantomData; +use std::mem; +use std::ptr; +use std::sync::atomic::{self, AtomicIsize, AtomicPtr, AtomicUsize, Ordering}; +use std::sync::Arc; + +use epoch::{Atomic, Owned}; +use utils::{Backoff, CachePadded}; + +use maybe_uninit::MaybeUninit; + +// Minimum buffer capacity. +const MIN_CAP: usize = 64; +// Maximum number of tasks that can be stolen in `steal_batch()` and `steal_batch_and_pop()`. +const MAX_BATCH: usize = 32; +// If a buffer of at least this size is retired, thread-local garbage is flushed so that it gets +// deallocated as soon as possible. +const FLUSH_THRESHOLD_BYTES: usize = 1 << 10; + +/// A buffer that holds tasks in a worker queue. +/// +/// This is just a pointer to the buffer and its length - dropping an instance of this struct will +/// *not* deallocate the buffer. +struct Buffer { + /// Pointer to the allocated memory. + ptr: *mut T, + + /// Capacity of the buffer. Always a power of two. + cap: usize, +} + +unsafe impl Send for Buffer {} + +impl Buffer { + /// Allocates a new buffer with the specified capacity. + fn alloc(cap: usize) -> Buffer { + debug_assert_eq!(cap, cap.next_power_of_two()); + + let mut v = Vec::with_capacity(cap); + let ptr = v.as_mut_ptr(); + mem::forget(v); + + Buffer { ptr, cap } + } + + /// Deallocates the buffer. + unsafe fn dealloc(self) { + drop(Vec::from_raw_parts(self.ptr, 0, self.cap)); + } + + /// Returns a pointer to the task at the specified `index`. + unsafe fn at(&self, index: isize) -> *mut T { + // `self.cap` is always a power of two. + self.ptr.offset(index & (self.cap - 1) as isize) + } + + /// Writes `task` into the specified `index`. + /// + /// This method might be concurrently called with another `read` at the same index, which is + /// technically speaking a data race and therefore UB. We should use an atomic store here, but + /// that would be more expensive and difficult to implement generically for all types `T`. + /// Hence, as a hack, we use a volatile write instead. + unsafe fn write(&self, index: isize, task: T) { + ptr::write_volatile(self.at(index), task) + } + + /// Reads a task from the specified `index`. + /// + /// This method might be concurrently called with another `write` at the same index, which is + /// technically speaking a data race and therefore UB. We should use an atomic load here, but + /// that would be more expensive and difficult to implement generically for all types `T`. + /// Hence, as a hack, we use a volatile write instead. + unsafe fn read(&self, index: isize) -> T { + ptr::read_volatile(self.at(index)) + } +} + +impl Clone for Buffer { + fn clone(&self) -> Buffer { + Buffer { + ptr: self.ptr, + cap: self.cap, + } + } +} + +impl Copy for Buffer {} + +/// Internal queue data shared between the worker and stealers. +/// +/// The implementation is based on the following work: +/// +/// 1. [Chase and Lev. Dynamic circular work-stealing deque. SPAA 2005.][chase-lev] +/// 2. [Le, Pop, Cohen, and Nardelli. Correct and efficient work-stealing for weak memory models. +/// PPoPP 2013.][weak-mem] +/// 3. [Norris and Demsky. CDSchecker: checking concurrent data structures written with C/C++ +/// atomics. OOPSLA 2013.][checker] +/// +/// [chase-lev]: https://dl.acm.org/citation.cfm?id=1073974 +/// [weak-mem]: https://dl.acm.org/citation.cfm?id=2442524 +/// [checker]: https://dl.acm.org/citation.cfm?id=2509514 +struct Inner { + /// The front index. + front: AtomicIsize, + + /// The back index. + back: AtomicIsize, + + /// The underlying buffer. + buffer: CachePadded>>, +} + +impl Drop for Inner { + fn drop(&mut self) { + // Load the back index, front index, and buffer. + let b = self.back.load(Ordering::Relaxed); + let f = self.front.load(Ordering::Relaxed); + + unsafe { + let buffer = self.buffer.load(Ordering::Relaxed, epoch::unprotected()); + + // Go through the buffer from front to back and drop all tasks in the queue. + let mut i = f; + while i != b { + buffer.deref().at(i).drop_in_place(); + i = i.wrapping_add(1); + } + + // Free the memory allocated by the buffer. + buffer.into_owned().into_box().dealloc(); + } + } +} + +/// Worker queue flavor: FIFO or LIFO. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Flavor { + /// The first-in first-out flavor. + Fifo, + + /// The last-in first-out flavor. + Lifo, +} + +/// A worker queue. +/// +/// This is a FIFO or LIFO queue that is owned by a single thread, but other threads may steal +/// tasks from it. Task schedulers typically create a single worker queue per thread. +/// +/// # Examples +/// +/// A FIFO worker: +/// +/// ``` +/// use crossbeam_deque::{Steal, Worker}; +/// +/// let w = Worker::new_fifo(); +/// let s = w.stealer(); +/// +/// w.push(1); +/// w.push(2); +/// w.push(3); +/// +/// assert_eq!(s.steal(), Steal::Success(1)); +/// assert_eq!(w.pop(), Some(2)); +/// assert_eq!(w.pop(), Some(3)); +/// ``` +/// +/// A LIFO worker: +/// +/// ``` +/// use crossbeam_deque::{Steal, Worker}; +/// +/// let w = Worker::new_lifo(); +/// let s = w.stealer(); +/// +/// w.push(1); +/// w.push(2); +/// w.push(3); +/// +/// assert_eq!(s.steal(), Steal::Success(1)); +/// assert_eq!(w.pop(), Some(3)); +/// assert_eq!(w.pop(), Some(2)); +/// ``` +pub struct Worker { + /// A reference to the inner representation of the queue. + inner: Arc>>, + + /// A copy of `inner.buffer` for quick access. + buffer: Cell>, + + /// The flavor of the queue. + flavor: Flavor, + + /// Indicates that the worker cannot be shared among threads. + _marker: PhantomData<*mut ()>, // !Send + !Sync +} + +unsafe impl Send for Worker {} + +impl Worker { + /// Creates a FIFO worker queue. + /// + /// Tasks are pushed and popped from opposite ends. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::::new_fifo(); + /// ``` + pub fn new_fifo() -> Worker { + let buffer = Buffer::alloc(MIN_CAP); + + let inner = Arc::new(CachePadded::new(Inner { + front: AtomicIsize::new(0), + back: AtomicIsize::new(0), + buffer: CachePadded::new(Atomic::new(buffer)), + })); + + Worker { + inner, + buffer: Cell::new(buffer), + flavor: Flavor::Fifo, + _marker: PhantomData, + } + } + + /// Creates a LIFO worker queue. + /// + /// Tasks are pushed and popped from the same end. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::::new_lifo(); + /// ``` + pub fn new_lifo() -> Worker { + let buffer = Buffer::alloc(MIN_CAP); + + let inner = Arc::new(CachePadded::new(Inner { + front: AtomicIsize::new(0), + back: AtomicIsize::new(0), + buffer: CachePadded::new(Atomic::new(buffer)), + })); + + Worker { + inner, + buffer: Cell::new(buffer), + flavor: Flavor::Lifo, + _marker: PhantomData, + } + } + + /// Creates a stealer for this queue. + /// + /// The returned stealer can be shared among threads and cloned. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::::new_lifo(); + /// let s = w.stealer(); + /// ``` + pub fn stealer(&self) -> Stealer { + Stealer { + inner: self.inner.clone(), + flavor: self.flavor, + } + } + + /// Resizes the internal buffer to the new capacity of `new_cap`. + #[cold] + unsafe fn resize(&self, new_cap: usize) { + // Load the back index, front index, and buffer. + let b = self.inner.back.load(Ordering::Relaxed); + let f = self.inner.front.load(Ordering::Relaxed); + let buffer = self.buffer.get(); + + // Allocate a new buffer and copy data from the old buffer to the new one. + let new = Buffer::alloc(new_cap); + let mut i = f; + while i != b { + ptr::copy_nonoverlapping(buffer.at(i), new.at(i), 1); + i = i.wrapping_add(1); + } + + let guard = &epoch::pin(); + + // Replace the old buffer with the new one. + self.buffer.replace(new); + let old = + self.inner + .buffer + .swap(Owned::new(new).into_shared(guard), Ordering::Release, guard); + + // Destroy the old buffer later. + guard.defer_unchecked(move || old.into_owned().into_box().dealloc()); + + // If the buffer is very large, then flush the thread-local garbage in order to deallocate + // it as soon as possible. + if mem::size_of::() * new_cap >= FLUSH_THRESHOLD_BYTES { + guard.flush(); + } + } + + /// Reserves enough capacity so that `reserve_cap` tasks can be pushed without growing the + /// buffer. + fn reserve(&self, reserve_cap: usize) { + if reserve_cap > 0 { + // Compute the current length. + let b = self.inner.back.load(Ordering::Relaxed); + let f = self.inner.front.load(Ordering::SeqCst); + let len = b.wrapping_sub(f) as usize; + + // The current capacity. + let cap = self.buffer.get().cap; + + // Is there enough capacity to push `reserve_cap` tasks? + if cap - len < reserve_cap { + // Keep doubling the capacity as much as is needed. + let mut new_cap = cap * 2; + while new_cap - len < reserve_cap { + new_cap *= 2; + } + + // Resize the buffer. + unsafe { + self.resize(new_cap); + } + } + } + } + + /// Returns `true` if the queue is empty. + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::new_lifo(); + /// + /// assert!(w.is_empty()); + /// w.push(1); + /// assert!(!w.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + let b = self.inner.back.load(Ordering::Relaxed); + let f = self.inner.front.load(Ordering::SeqCst); + b.wrapping_sub(f) <= 0 + } + + /// Pushes a task into the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::new_lifo(); + /// w.push(1); + /// w.push(2); + /// ``` + pub fn push(&self, task: T) { + // Load the back index, front index, and buffer. + let b = self.inner.back.load(Ordering::Relaxed); + let f = self.inner.front.load(Ordering::Acquire); + let mut buffer = self.buffer.get(); + + // Calculate the length of the queue. + let len = b.wrapping_sub(f); + + // Is the queue full? + if len >= buffer.cap as isize { + // Yes. Grow the underlying buffer. + unsafe { + self.resize(2 * buffer.cap); + } + buffer = self.buffer.get(); + } + + // Write `task` into the slot. + unsafe { + buffer.write(b, task); + } + + atomic::fence(Ordering::Release); + + // Increment the back index. + // + // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data + // races because it doesn't understand fences. + self.inner.back.store(b.wrapping_add(1), Ordering::Release); + } + + /// Pops a task from the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::new_fifo(); + /// w.push(1); + /// w.push(2); + /// + /// assert_eq!(w.pop(), Some(1)); + /// assert_eq!(w.pop(), Some(2)); + /// assert_eq!(w.pop(), None); + /// ``` + pub fn pop(&self) -> Option { + // Load the back and front index. + let b = self.inner.back.load(Ordering::Relaxed); + let f = self.inner.front.load(Ordering::Relaxed); + + // Calculate the length of the queue. + let len = b.wrapping_sub(f); + + // Is the queue empty? + if len <= 0 { + return None; + } + + match self.flavor { + // Pop from the front of the queue. + Flavor::Fifo => { + // Try incrementing the front index to pop the task. + let f = self.inner.front.fetch_add(1, Ordering::SeqCst); + let new_f = f.wrapping_add(1); + + if b.wrapping_sub(new_f) < 0 { + self.inner.front.store(f, Ordering::Relaxed); + return None; + } + + unsafe { + // Read the popped task. + let buffer = self.buffer.get(); + let task = buffer.read(f); + + // Shrink the buffer if `len - 1` is less than one fourth of the capacity. + if buffer.cap > MIN_CAP && len <= buffer.cap as isize / 4 { + self.resize(buffer.cap / 2); + } + + Some(task) + } + } + + // Pop from the back of the queue. + Flavor::Lifo => { + // Decrement the back index. + let b = b.wrapping_sub(1); + self.inner.back.store(b, Ordering::Relaxed); + + atomic::fence(Ordering::SeqCst); + + // Load the front index. + let f = self.inner.front.load(Ordering::Relaxed); + + // Compute the length after the back index was decremented. + let len = b.wrapping_sub(f); + + if len < 0 { + // The queue is empty. Restore the back index to the original task. + self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed); + None + } else { + // Read the task to be popped. + let buffer = self.buffer.get(); + let mut task = unsafe { Some(buffer.read(b)) }; + + // Are we popping the last task from the queue? + if len == 0 { + // Try incrementing the front index. + if self + .inner + .front + .compare_exchange( + f, + f.wrapping_add(1), + Ordering::SeqCst, + Ordering::Relaxed, + ) + .is_err() + { + // Failed. We didn't pop anything. + mem::forget(task.take()); + } + + // Restore the back index to the original task. + self.inner.back.store(b.wrapping_add(1), Ordering::Relaxed); + } else { + // Shrink the buffer if `len` is less than one fourth of the capacity. + if buffer.cap > MIN_CAP && len < buffer.cap as isize / 4 { + unsafe { + self.resize(buffer.cap / 2); + } + } + } + + task + } + } + } + } +} + +impl fmt::Debug for Worker { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("Worker { .. }") + } +} + +/// A stealer handle of a worker queue. +/// +/// Stealers can be shared among threads. +/// +/// Task schedulers typically have a single worker queue per worker thread. +/// +/// # Examples +/// +/// ``` +/// use crossbeam_deque::{Steal, Worker}; +/// +/// let w = Worker::new_lifo(); +/// w.push(1); +/// w.push(2); +/// +/// let s = w.stealer(); +/// assert_eq!(s.steal(), Steal::Success(1)); +/// assert_eq!(s.steal(), Steal::Success(2)); +/// assert_eq!(s.steal(), Steal::Empty); +/// ``` +pub struct Stealer { + /// A reference to the inner representation of the queue. + inner: Arc>>, + + /// The flavor of the queue. + flavor: Flavor, +} + +unsafe impl Send for Stealer {} +unsafe impl Sync for Stealer {} + +impl Stealer { + /// Returns `true` if the queue is empty. + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w = Worker::new_lifo(); + /// let s = w.stealer(); + /// + /// assert!(s.is_empty()); + /// w.push(1); + /// assert!(!s.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + let f = self.inner.front.load(Ordering::Acquire); + atomic::fence(Ordering::SeqCst); + let b = self.inner.back.load(Ordering::Acquire); + b.wrapping_sub(f) <= 0 + } + + /// Steals a task from the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::{Steal, Worker}; + /// + /// let w = Worker::new_lifo(); + /// w.push(1); + /// w.push(2); + /// + /// let s = w.stealer(); + /// assert_eq!(s.steal(), Steal::Success(1)); + /// assert_eq!(s.steal(), Steal::Success(2)); + /// ``` + pub fn steal(&self) -> Steal { + // Load the front index. + let f = self.inner.front.load(Ordering::Acquire); + + // A SeqCst fence is needed here. + // + // If the current thread is already pinned (reentrantly), we must manually issue the + // fence. Otherwise, the following pinning will issue the fence anyway, so we don't + // have to. + if epoch::is_pinned() { + atomic::fence(Ordering::SeqCst); + } + + let guard = &epoch::pin(); + + // Load the back index. + let b = self.inner.back.load(Ordering::Acquire); + + // Is the queue empty? + if b.wrapping_sub(f) <= 0 { + return Steal::Empty; + } + + // Load the buffer and read the task at the front. + let buffer = self.inner.buffer.load(Ordering::Acquire, guard); + let task = unsafe { buffer.deref().read(f) }; + + // Try incrementing the front index to steal the task. + if self + .inner + .front + .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) + .is_err() + { + // We didn't steal this task, forget it. + mem::forget(task); + return Steal::Retry; + } + + // Return the stolen task. + Steal::Success(task) + } + + /// Steals a batch of tasks and pushes them into another worker. + /// + /// How many tasks exactly will be stolen is not specified. That said, this method will try to + /// steal around half of the tasks in the queue, but also not more than some constant limit. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Worker; + /// + /// let w1 = Worker::new_fifo(); + /// w1.push(1); + /// w1.push(2); + /// w1.push(3); + /// w1.push(4); + /// + /// let s = w1.stealer(); + /// let w2 = Worker::new_fifo(); + /// + /// s.steal_batch(&w2); + /// assert_eq!(w2.pop(), Some(1)); + /// assert_eq!(w2.pop(), Some(2)); + /// ``` + pub fn steal_batch(&self, dest: &Worker) -> Steal<()> { + if Arc::ptr_eq(&self.inner, &dest.inner) { + if dest.is_empty() { + return Steal::Empty; + } else { + return Steal::Success(()); + } + } + + // Load the front index. + let mut f = self.inner.front.load(Ordering::Acquire); + + // A SeqCst fence is needed here. + // + // If the current thread is already pinned (reentrantly), we must manually issue the + // fence. Otherwise, the following pinning will issue the fence anyway, so we don't + // have to. + if epoch::is_pinned() { + atomic::fence(Ordering::SeqCst); + } + + let guard = &epoch::pin(); + + // Load the back index. + let b = self.inner.back.load(Ordering::Acquire); + + // Is the queue empty? + let len = b.wrapping_sub(f); + if len <= 0 { + return Steal::Empty; + } + + // Reserve capacity for the stolen batch. + let batch_size = cmp::min((len as usize + 1) / 2, MAX_BATCH); + dest.reserve(batch_size); + let mut batch_size = batch_size as isize; + + // Get the destination buffer and back index. + let dest_buffer = dest.buffer.get(); + let mut dest_b = dest.inner.back.load(Ordering::Relaxed); + + // Load the buffer. + let buffer = self.inner.buffer.load(Ordering::Acquire, guard); + + match self.flavor { + // Steal a batch of tasks from the front at once. + Flavor::Fifo => { + // Copy the batch from the source to the destination buffer. + match dest.flavor { + Flavor::Fifo => { + for i in 0..batch_size { + unsafe { + let task = buffer.deref().read(f.wrapping_add(i)); + dest_buffer.write(dest_b.wrapping_add(i), task); + } + } + } + Flavor::Lifo => { + for i in 0..batch_size { + unsafe { + let task = buffer.deref().read(f.wrapping_add(i)); + dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task); + } + } + } + } + + // Try incrementing the front index to steal the batch. + if self + .inner + .front + .compare_exchange( + f, + f.wrapping_add(batch_size), + Ordering::SeqCst, + Ordering::Relaxed, + ) + .is_err() + { + return Steal::Retry; + } + + dest_b = dest_b.wrapping_add(batch_size); + } + + // Steal a batch of tasks from the front one by one. + Flavor::Lifo => { + for i in 0..batch_size { + // If this is not the first steal, check whether the queue is empty. + if i > 0 { + // We've already got the current front index. Now execute the fence to + // synchronize with other threads. + atomic::fence(Ordering::SeqCst); + + // Load the back index. + let b = self.inner.back.load(Ordering::Acquire); + + // Is the queue empty? + if b.wrapping_sub(f) <= 0 { + batch_size = i; + break; + } + } + + // Read the task at the front. + let task = unsafe { buffer.deref().read(f) }; + + // Try incrementing the front index to steal the task. + if self + .inner + .front + .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) + .is_err() + { + // We didn't steal this task, forget it and break from the loop. + mem::forget(task); + batch_size = i; + break; + } + + // Write the stolen task into the destination buffer. + unsafe { + dest_buffer.write(dest_b, task); + } + + // Move the source front index and the destination back index one step forward. + f = f.wrapping_add(1); + dest_b = dest_b.wrapping_add(1); + } + + // If we didn't steal anything, the operation needs to be retried. + if batch_size == 0 { + return Steal::Retry; + } + + // If stealing into a FIFO queue, stolen tasks need to be reversed. + if dest.flavor == Flavor::Fifo { + for i in 0..batch_size / 2 { + unsafe { + let i1 = dest_b.wrapping_sub(batch_size - i); + let i2 = dest_b.wrapping_sub(i + 1); + let t1 = dest_buffer.read(i1); + let t2 = dest_buffer.read(i2); + dest_buffer.write(i1, t2); + dest_buffer.write(i2, t1); + } + } + } + } + } + + atomic::fence(Ordering::Release); + + // Update the back index in the destination queue. + // + // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data + // races because it doesn't understand fences. + dest.inner.back.store(dest_b, Ordering::Release); + + // Return with success. + Steal::Success(()) + } + + /// Steals a batch of tasks, pushes them into another worker, and pops a task from that worker. + /// + /// How many tasks exactly will be stolen is not specified. That said, this method will try to + /// steal around half of the tasks in the queue, but also not more than some constant limit. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::{Steal, Worker}; + /// + /// let w1 = Worker::new_fifo(); + /// w1.push(1); + /// w1.push(2); + /// w1.push(3); + /// w1.push(4); + /// + /// let s = w1.stealer(); + /// let w2 = Worker::new_fifo(); + /// + /// assert_eq!(s.steal_batch_and_pop(&w2), Steal::Success(1)); + /// assert_eq!(w2.pop(), Some(2)); + /// ``` + pub fn steal_batch_and_pop(&self, dest: &Worker) -> Steal { + if Arc::ptr_eq(&self.inner, &dest.inner) { + match dest.pop() { + None => return Steal::Empty, + Some(task) => return Steal::Success(task), + } + } + + // Load the front index. + let mut f = self.inner.front.load(Ordering::Acquire); + + // A SeqCst fence is needed here. + // + // If the current thread is already pinned (reentrantly), we must manually issue the + // fence. Otherwise, the following pinning will issue the fence anyway, so we don't + // have to. + if epoch::is_pinned() { + atomic::fence(Ordering::SeqCst); + } + + let guard = &epoch::pin(); + + // Load the back index. + let b = self.inner.back.load(Ordering::Acquire); + + // Is the queue empty? + let len = b.wrapping_sub(f); + if len <= 0 { + return Steal::Empty; + } + + // Reserve capacity for the stolen batch. + let batch_size = cmp::min((len as usize - 1) / 2, MAX_BATCH - 1); + dest.reserve(batch_size); + let mut batch_size = batch_size as isize; + + // Get the destination buffer and back index. + let dest_buffer = dest.buffer.get(); + let mut dest_b = dest.inner.back.load(Ordering::Relaxed); + + // Load the buffer + let buffer = self.inner.buffer.load(Ordering::Acquire, guard); + + // Read the task at the front. + let mut task = unsafe { buffer.deref().read(f) }; + + match self.flavor { + // Steal a batch of tasks from the front at once. + Flavor::Fifo => { + // Copy the batch from the source to the destination buffer. + match dest.flavor { + Flavor::Fifo => { + for i in 0..batch_size { + unsafe { + let task = buffer.deref().read(f.wrapping_add(i + 1)); + dest_buffer.write(dest_b.wrapping_add(i), task); + } + } + } + Flavor::Lifo => { + for i in 0..batch_size { + unsafe { + let task = buffer.deref().read(f.wrapping_add(i + 1)); + dest_buffer.write(dest_b.wrapping_add(batch_size - 1 - i), task); + } + } + } + } + + // Try incrementing the front index to steal the batch. + if self + .inner + .front + .compare_exchange( + f, + f.wrapping_add(batch_size + 1), + Ordering::SeqCst, + Ordering::Relaxed, + ) + .is_err() + { + // We didn't steal this task, forget it. + mem::forget(task); + return Steal::Retry; + } + + dest_b = dest_b.wrapping_add(batch_size); + } + + // Steal a batch of tasks from the front one by one. + Flavor::Lifo => { + // Try incrementing the front index to steal the task. + if self + .inner + .front + .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) + .is_err() + { + // We didn't steal this task, forget it. + mem::forget(task); + return Steal::Retry; + } + + // Move the front index one step forward. + f = f.wrapping_add(1); + + // Repeat the same procedure for the batch steals. + for i in 0..batch_size { + // We've already got the current front index. Now execute the fence to + // synchronize with other threads. + atomic::fence(Ordering::SeqCst); + + // Load the back index. + let b = self.inner.back.load(Ordering::Acquire); + + // Is the queue empty? + if b.wrapping_sub(f) <= 0 { + batch_size = i; + break; + } + + // Read the task at the front. + let tmp = unsafe { buffer.deref().read(f) }; + + // Try incrementing the front index to steal the task. + if self + .inner + .front + .compare_exchange(f, f.wrapping_add(1), Ordering::SeqCst, Ordering::Relaxed) + .is_err() + { + // We didn't steal this task, forget it and break from the loop. + mem::forget(tmp); + batch_size = i; + break; + } + + // Write the previously stolen task into the destination buffer. + unsafe { + dest_buffer.write(dest_b, mem::replace(&mut task, tmp)); + } + + // Move the source front index and the destination back index one step forward. + f = f.wrapping_add(1); + dest_b = dest_b.wrapping_add(1); + } + + // If stealing into a FIFO queue, stolen tasks need to be reversed. + if dest.flavor == Flavor::Fifo { + for i in 0..batch_size / 2 { + unsafe { + let i1 = dest_b.wrapping_sub(batch_size - i); + let i2 = dest_b.wrapping_sub(i + 1); + let t1 = dest_buffer.read(i1); + let t2 = dest_buffer.read(i2); + dest_buffer.write(i1, t2); + dest_buffer.write(i2, t1); + } + } + } + } + } + + atomic::fence(Ordering::Release); + + // Update the back index in the destination queue. + // + // This ordering could be `Relaxed`, but then thread sanitizer would falsely report data + // races because it doesn't understand fences. + dest.inner.back.store(dest_b, Ordering::Release); + + // Return with success. + Steal::Success(task) + } +} + +impl Clone for Stealer { + fn clone(&self) -> Stealer { + Stealer { + inner: self.inner.clone(), + flavor: self.flavor, + } + } +} + +impl fmt::Debug for Stealer { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("Stealer { .. }") + } +} + +// Bits indicating the state of a slot: +// * If a task has been written into the slot, `WRITE` is set. +// * If a task has been read from the slot, `READ` is set. +// * If the block is being destroyed, `DESTROY` is set. +const WRITE: usize = 1; +const READ: usize = 2; +const DESTROY: usize = 4; + +// Each block covers one "lap" of indices. +const LAP: usize = 64; +// The maximum number of values a block can hold. +const BLOCK_CAP: usize = LAP - 1; +// How many lower bits are reserved for metadata. +const SHIFT: usize = 1; +// Indicates that the block is not the last one. +const HAS_NEXT: usize = 1; + +/// A slot in a block. +struct Slot { + /// The task. + task: UnsafeCell>, + + /// The state of the slot. + state: AtomicUsize, +} + +impl Slot { + /// Waits until a task is written into the slot. + fn wait_write(&self) { + let backoff = Backoff::new(); + while self.state.load(Ordering::Acquire) & WRITE == 0 { + backoff.snooze(); + } + } +} + +/// A block in a linked list. +/// +/// Each block in the list can hold up to `BLOCK_CAP` values. +struct Block { + /// The next block in the linked list. + next: AtomicPtr>, + + /// Slots for values. + slots: [Slot; BLOCK_CAP], +} + +impl Block { + /// Creates an empty block that starts at `start_index`. + fn new() -> Block { + // SAFETY: This is safe because: + // [1] `Block::next` (AtomicPtr) may be safely zero initialized. + // [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4]. + // [3] `Slot::task` (UnsafeCell) may be safely zero initialized because it + // holds a MaybeUninit. + // [4] `Slot::state` (AtomicUsize) may be safely zero initialized. + unsafe { MaybeUninit::zeroed().assume_init() } + } + + /// Waits until the next pointer is set. + fn wait_next(&self) -> *mut Block { + let backoff = Backoff::new(); + loop { + let next = self.next.load(Ordering::Acquire); + if !next.is_null() { + return next; + } + backoff.snooze(); + } + } + + /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block. + unsafe fn destroy(this: *mut Block, count: usize) { + // It is not necessary to set the `DESTROY` bit in the last slot because that slot has + // begun destruction of the block. + for i in (0..count).rev() { + let slot = (*this).slots.get_unchecked(i); + + // Mark the `DESTROY` bit if a thread is still using the slot. + if slot.state.load(Ordering::Acquire) & READ == 0 + && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0 + { + // If a thread is still using the slot, it will continue destruction of the block. + return; + } + } + + // No thread is using the block, now it is safe to destroy it. + drop(Box::from_raw(this)); + } +} + +/// A position in a queue. +struct Position { + /// The index in the queue. + index: AtomicUsize, + + /// The block in the linked list. + block: AtomicPtr>, +} + +/// An injector queue. +/// +/// This is a FIFO queue that can be shared among multiple threads. Task schedulers typically have +/// a single injector queue, which is the entry point for new tasks. +/// +/// # Examples +/// +/// ``` +/// use crossbeam_deque::{Injector, Steal}; +/// +/// let q = Injector::new(); +/// q.push(1); +/// q.push(2); +/// +/// assert_eq!(q.steal(), Steal::Success(1)); +/// assert_eq!(q.steal(), Steal::Success(2)); +/// assert_eq!(q.steal(), Steal::Empty); +/// ``` +pub struct Injector { + /// The head of the queue. + head: CachePadded>, + + /// The tail of the queue. + tail: CachePadded>, + + /// Indicates that dropping a `Injector` may drop values of type `T`. + _marker: PhantomData, +} + +unsafe impl Send for Injector {} +unsafe impl Sync for Injector {} + +impl Injector { + /// Creates a new injector queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Injector; + /// + /// let q = Injector::::new(); + /// ``` + pub fn new() -> Injector { + let block = Box::into_raw(Box::new(Block::::new())); + Injector { + head: CachePadded::new(Position { + block: AtomicPtr::new(block), + index: AtomicUsize::new(0), + }), + tail: CachePadded::new(Position { + block: AtomicPtr::new(block), + index: AtomicUsize::new(0), + }), + _marker: PhantomData, + } + } + + /// Pushes a task into the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Injector; + /// + /// let w = Injector::new(); + /// w.push(1); + /// w.push(2); + /// ``` + pub fn push(&self, task: T) { + let backoff = Backoff::new(); + let mut tail = self.tail.index.load(Ordering::Acquire); + let mut block = self.tail.block.load(Ordering::Acquire); + let mut next_block = None; + + loop { + // Calculate the offset of the index into the block. + let offset = (tail >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + tail = self.tail.index.load(Ordering::Acquire); + block = self.tail.block.load(Ordering::Acquire); + continue; + } + + // If we're going to have to install the next block, allocate it in advance in order to + // make the wait for other threads as short as possible. + if offset + 1 == BLOCK_CAP && next_block.is_none() { + next_block = Some(Box::new(Block::::new())); + } + + let new_tail = tail + (1 << SHIFT); + + // Try advancing the tail forward. + match self.tail.index.compare_exchange_weak( + tail, + new_tail, + Ordering::SeqCst, + Ordering::Acquire, + ) { + Ok(_) => unsafe { + // If we've reached the end of the block, install the next one. + if offset + 1 == BLOCK_CAP { + let next_block = Box::into_raw(next_block.unwrap()); + let next_index = new_tail.wrapping_add(1 << SHIFT); + + self.tail.block.store(next_block, Ordering::Release); + self.tail.index.store(next_index, Ordering::Release); + (*block).next.store(next_block, Ordering::Release); + } + + // Write the task into the slot. + let slot = (*block).slots.get_unchecked(offset); + slot.task.get().write(MaybeUninit::new(task)); + slot.state.fetch_or(WRITE, Ordering::Release); + + return; + }, + Err(t) => { + tail = t; + block = self.tail.block.load(Ordering::Acquire); + backoff.spin(); + } + } + } + } + + /// Steals a task from the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::{Injector, Steal}; + /// + /// let q = Injector::new(); + /// q.push(1); + /// q.push(2); + /// + /// assert_eq!(q.steal(), Steal::Success(1)); + /// assert_eq!(q.steal(), Steal::Success(2)); + /// assert_eq!(q.steal(), Steal::Empty); + /// ``` + pub fn steal(&self) -> Steal { + let mut head; + let mut block; + let mut offset; + + let backoff = Backoff::new(); + loop { + head = self.head.index.load(Ordering::Acquire); + block = self.head.block.load(Ordering::Acquire); + + // Calculate the offset of the index into the block. + offset = (head >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + } else { + break; + } + } + + let mut new_head = head + (1 << SHIFT); + + if new_head & HAS_NEXT == 0 { + atomic::fence(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::Relaxed); + + // If the tail equals the head, that means the queue is empty. + if head >> SHIFT == tail >> SHIFT { + return Steal::Empty; + } + + // If head and tail are not in the same block, set `HAS_NEXT` in head. + if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP { + new_head |= HAS_NEXT; + } + } + + // Try moving the head index forward. + if self + .head + .index + .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire) + .is_err() + { + return Steal::Retry; + } + + unsafe { + // If we've reached the end of the block, move to the next one. + if offset + 1 == BLOCK_CAP { + let next = (*block).wait_next(); + let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT); + if !(*next).next.load(Ordering::Relaxed).is_null() { + next_index |= HAS_NEXT; + } + + self.head.block.store(next, Ordering::Release); + self.head.index.store(next_index, Ordering::Release); + } + + // Read the task. + let slot = (*block).slots.get_unchecked(offset); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + // Destroy the block if we've reached the end, or if another thread wanted to destroy + // but couldn't because we were busy reading from the slot. + if offset + 1 == BLOCK_CAP { + Block::destroy(block, offset); + } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 { + Block::destroy(block, offset); + } + + Steal::Success(task) + } + } + + /// Steals a batch of tasks and pushes them into a worker. + /// + /// How many tasks exactly will be stolen is not specified. That said, this method will try to + /// steal around half of the tasks in the queue, but also not more than some constant limit. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::{Injector, Worker}; + /// + /// let q = Injector::new(); + /// q.push(1); + /// q.push(2); + /// q.push(3); + /// q.push(4); + /// + /// let w = Worker::new_fifo(); + /// q.steal_batch(&w); + /// assert_eq!(w.pop(), Some(1)); + /// assert_eq!(w.pop(), Some(2)); + /// ``` + pub fn steal_batch(&self, dest: &Worker) -> Steal<()> { + let mut head; + let mut block; + let mut offset; + + let backoff = Backoff::new(); + loop { + head = self.head.index.load(Ordering::Acquire); + block = self.head.block.load(Ordering::Acquire); + + // Calculate the offset of the index into the block. + offset = (head >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + } else { + break; + } + } + + let mut new_head = head; + let advance; + + if new_head & HAS_NEXT == 0 { + atomic::fence(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::Relaxed); + + // If the tail equals the head, that means the queue is empty. + if head >> SHIFT == tail >> SHIFT { + return Steal::Empty; + } + + // If head and tail are not in the same block, set `HAS_NEXT` in head. Also, calculate + // the right batch size to steal. + if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP { + new_head |= HAS_NEXT; + // We can steal all tasks till the end of the block. + advance = (BLOCK_CAP - offset).min(MAX_BATCH); + } else { + let len = (tail - head) >> SHIFT; + // Steal half of the available tasks. + advance = ((len + 1) / 2).min(MAX_BATCH); + } + } else { + // We can steal all tasks till the end of the block. + advance = (BLOCK_CAP - offset).min(MAX_BATCH); + } + + new_head += advance << SHIFT; + let new_offset = offset + advance; + + // Try moving the head index forward. + if self + .head + .index + .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire) + .is_err() + { + return Steal::Retry; + } + + // Reserve capacity for the stolen batch. + let batch_size = new_offset - offset; + dest.reserve(batch_size); + + // Get the destination buffer and back index. + let dest_buffer = dest.buffer.get(); + let dest_b = dest.inner.back.load(Ordering::Relaxed); + + unsafe { + // If we've reached the end of the block, move to the next one. + if new_offset == BLOCK_CAP { + let next = (*block).wait_next(); + let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT); + if !(*next).next.load(Ordering::Relaxed).is_null() { + next_index |= HAS_NEXT; + } + + self.head.block.store(next, Ordering::Release); + self.head.index.store(next_index, Ordering::Release); + } + + // Copy values from the injector into the destination queue. + match dest.flavor { + Flavor::Fifo => { + for i in 0..batch_size { + // Read the task. + let slot = (*block).slots.get_unchecked(offset + i); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + // Write it into the destination queue. + dest_buffer.write(dest_b.wrapping_add(i as isize), task); + } + } + + Flavor::Lifo => { + for i in 0..batch_size { + // Read the task. + let slot = (*block).slots.get_unchecked(offset + i); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + // Write it into the destination queue. + dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task); + } + } + } + + atomic::fence(Ordering::Release); + + // Update the back index in the destination queue. + // + // This ordering could be `Relaxed`, but then thread sanitizer would falsely report + // data races because it doesn't understand fences. + dest.inner + .back + .store(dest_b.wrapping_add(batch_size as isize), Ordering::Release); + + // Destroy the block if we've reached the end, or if another thread wanted to destroy + // but couldn't because we were busy reading from the slot. + if new_offset == BLOCK_CAP { + Block::destroy(block, offset); + } else { + for i in offset..new_offset { + let slot = (*block).slots.get_unchecked(i); + + if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 { + Block::destroy(block, offset); + break; + } + } + } + + Steal::Success(()) + } + } + + /// Steals a batch of tasks, pushes them into a worker, and pops a task from that worker. + /// + /// How many tasks exactly will be stolen is not specified. That said, this method will try to + /// steal around half of the tasks in the queue, but also not more than some constant limit. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::{Injector, Steal, Worker}; + /// + /// let q = Injector::new(); + /// q.push(1); + /// q.push(2); + /// q.push(3); + /// q.push(4); + /// + /// let w = Worker::new_fifo(); + /// assert_eq!(q.steal_batch_and_pop(&w), Steal::Success(1)); + /// assert_eq!(w.pop(), Some(2)); + /// ``` + pub fn steal_batch_and_pop(&self, dest: &Worker) -> Steal { + let mut head; + let mut block; + let mut offset; + + let backoff = Backoff::new(); + loop { + head = self.head.index.load(Ordering::Acquire); + block = self.head.block.load(Ordering::Acquire); + + // Calculate the offset of the index into the block. + offset = (head >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + } else { + break; + } + } + + let mut new_head = head; + let advance; + + if new_head & HAS_NEXT == 0 { + atomic::fence(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::Relaxed); + + // If the tail equals the head, that means the queue is empty. + if head >> SHIFT == tail >> SHIFT { + return Steal::Empty; + } + + // If head and tail are not in the same block, set `HAS_NEXT` in head. + if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP { + new_head |= HAS_NEXT; + // We can steal all tasks till the end of the block. + advance = (BLOCK_CAP - offset).min(MAX_BATCH + 1); + } else { + let len = (tail - head) >> SHIFT; + // Steal half of the available tasks. + advance = ((len + 1) / 2).min(MAX_BATCH + 1); + } + } else { + // We can steal all tasks till the end of the block. + advance = (BLOCK_CAP - offset).min(MAX_BATCH + 1); + } + + new_head += advance << SHIFT; + let new_offset = offset + advance; + + // Try moving the head index forward. + if self + .head + .index + .compare_exchange_weak(head, new_head, Ordering::SeqCst, Ordering::Acquire) + .is_err() + { + return Steal::Retry; + } + + // Reserve capacity for the stolen batch. + let batch_size = new_offset - offset - 1; + dest.reserve(batch_size); + + // Get the destination buffer and back index. + let dest_buffer = dest.buffer.get(); + let dest_b = dest.inner.back.load(Ordering::Relaxed); + + unsafe { + // If we've reached the end of the block, move to the next one. + if new_offset == BLOCK_CAP { + let next = (*block).wait_next(); + let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT); + if !(*next).next.load(Ordering::Relaxed).is_null() { + next_index |= HAS_NEXT; + } + + self.head.block.store(next, Ordering::Release); + self.head.index.store(next_index, Ordering::Release); + } + + // Read the task. + let slot = (*block).slots.get_unchecked(offset); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + match dest.flavor { + Flavor::Fifo => { + // Copy values from the injector into the destination queue. + for i in 0..batch_size { + // Read the task. + let slot = (*block).slots.get_unchecked(offset + i + 1); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + // Write it into the destination queue. + dest_buffer.write(dest_b.wrapping_add(i as isize), task); + } + } + + Flavor::Lifo => { + // Copy values from the injector into the destination queue. + for i in 0..batch_size { + // Read the task. + let slot = (*block).slots.get_unchecked(offset + i + 1); + slot.wait_write(); + let task = slot.task.get().read().assume_init(); + + // Write it into the destination queue. + dest_buffer.write(dest_b.wrapping_add((batch_size - 1 - i) as isize), task); + } + } + } + + atomic::fence(Ordering::Release); + + // Update the back index in the destination queue. + // + // This ordering could be `Relaxed`, but then thread sanitizer would falsely report + // data races because it doesn't understand fences. + dest.inner + .back + .store(dest_b.wrapping_add(batch_size as isize), Ordering::Release); + + // Destroy the block if we've reached the end, or if another thread wanted to destroy + // but couldn't because we were busy reading from the slot. + if new_offset == BLOCK_CAP { + Block::destroy(block, offset); + } else { + for i in offset..new_offset { + let slot = (*block).slots.get_unchecked(i); + + if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 { + Block::destroy(block, offset); + break; + } + } + } + + Steal::Success(task) + } + } + + /// Returns `true` if the queue is empty. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Injector; + /// + /// let q = Injector::new(); + /// + /// assert!(q.is_empty()); + /// q.push(1); + /// assert!(!q.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + let head = self.head.index.load(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::SeqCst); + head >> SHIFT == tail >> SHIFT + } +} + +impl Drop for Injector { + fn drop(&mut self) { + let mut head = self.head.index.load(Ordering::Relaxed); + let mut tail = self.tail.index.load(Ordering::Relaxed); + let mut block = self.head.block.load(Ordering::Relaxed); + + // Erase the lower bits. + head &= !((1 << SHIFT) - 1); + tail &= !((1 << SHIFT) - 1); + + unsafe { + // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks. + while head != tail { + let offset = (head >> SHIFT) % LAP; + + if offset < BLOCK_CAP { + // Drop the task in the slot. + let slot = (*block).slots.get_unchecked(offset); + let p = &mut *slot.task.get(); + p.as_mut_ptr().drop_in_place(); + } else { + // Deallocate the block and move to the next one. + let next = (*block).next.load(Ordering::Relaxed); + drop(Box::from_raw(block)); + block = next; + } + + head = head.wrapping_add(1 << SHIFT); + } + + // Deallocate the last remaining block. + drop(Box::from_raw(block)); + } + } +} + +impl fmt::Debug for Injector { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("Worker { .. }") + } +} + +/// Possible outcomes of a steal operation. +/// +/// # Examples +/// +/// There are lots of ways to chain results of steal operations together: +/// +/// ``` +/// use crossbeam_deque::Steal::{self, Empty, Retry, Success}; +/// +/// let collect = |v: Vec>| v.into_iter().collect::>(); +/// +/// assert_eq!(collect(vec![Empty, Empty, Empty]), Empty); +/// assert_eq!(collect(vec![Empty, Retry, Empty]), Retry); +/// assert_eq!(collect(vec![Retry, Success(1), Empty]), Success(1)); +/// +/// assert_eq!(collect(vec![Empty, Empty]).or_else(|| Retry), Retry); +/// assert_eq!(collect(vec![Retry, Empty]).or_else(|| Success(1)), Success(1)); +/// ``` +#[must_use] +#[derive(PartialEq, Eq, Copy, Clone)] +pub enum Steal { + /// The queue was empty at the time of stealing. + Empty, + + /// At least one task was successfully stolen. + Success(T), + + /// The steal operation needs to be retried. + Retry, +} + +impl Steal { + /// Returns `true` if the queue was empty at the time of stealing. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Steal::{Empty, Retry, Success}; + /// + /// assert!(!Success(7).is_empty()); + /// assert!(!Retry::.is_empty()); + /// + /// assert!(Empty::.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + match self { + Steal::Empty => true, + _ => false, + } + } + + /// Returns `true` if at least one task was stolen. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Steal::{Empty, Retry, Success}; + /// + /// assert!(!Empty::.is_success()); + /// assert!(!Retry::.is_success()); + /// + /// assert!(Success(7).is_success()); + /// ``` + pub fn is_success(&self) -> bool { + match self { + Steal::Success(_) => true, + _ => false, + } + } + + /// Returns `true` if the steal operation needs to be retried. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Steal::{Empty, Retry, Success}; + /// + /// assert!(!Empty::.is_retry()); + /// assert!(!Success(7).is_retry()); + /// + /// assert!(Retry::.is_retry()); + /// ``` + pub fn is_retry(&self) -> bool { + match self { + Steal::Retry => true, + _ => false, + } + } + + /// Returns the result of the operation, if successful. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Steal::{Empty, Retry, Success}; + /// + /// assert_eq!(Empty::.success(), None); + /// assert_eq!(Retry::.success(), None); + /// + /// assert_eq!(Success(7).success(), Some(7)); + /// ``` + pub fn success(self) -> Option { + match self { + Steal::Success(res) => Some(res), + _ => None, + } + } + + /// If no task was stolen, attempts another steal operation. + /// + /// Returns this steal result if it is `Success`. Otherwise, closure `f` is invoked and then: + /// + /// * If the second steal resulted in `Success`, it is returned. + /// * If both steals were unsuccessful but any resulted in `Retry`, then `Retry` is returned. + /// * If both resulted in `None`, then `None` is returned. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_deque::Steal::{Empty, Retry, Success}; + /// + /// assert_eq!(Success(1).or_else(|| Success(2)), Success(1)); + /// assert_eq!(Retry.or_else(|| Success(2)), Success(2)); + /// + /// assert_eq!(Retry.or_else(|| Empty), Retry::); + /// assert_eq!(Empty.or_else(|| Retry), Retry::); + /// + /// assert_eq!(Empty.or_else(|| Empty), Empty::); + /// ``` + pub fn or_else(self, f: F) -> Steal + where + F: FnOnce() -> Steal, + { + match self { + Steal::Empty => f(), + Steal::Success(_) => self, + Steal::Retry => { + if let Steal::Success(res) = f() { + Steal::Success(res) + } else { + Steal::Retry + } + } + } + } +} + +impl fmt::Debug for Steal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Steal::Empty => f.pad("Empty"), + Steal::Success(_) => f.pad("Success(..)"), + Steal::Retry => f.pad("Retry"), + } + } +} + +impl FromIterator> for Steal { + /// Consumes items until a `Success` is found and returns it. + /// + /// If no `Success` was found, but there was at least one `Retry`, then returns `Retry`. + /// Otherwise, `Empty` is returned. + fn from_iter(iter: I) -> Steal + where + I: IntoIterator>, + { + let mut retry = false; + for s in iter { + match &s { + Steal::Empty => {} + Steal::Success(_) => return s, + Steal::Retry => retry = true, + } + } + + if retry { + Steal::Retry + } else { + Steal::Empty + } + } +} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/fifo.rs b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/fifo.rs new file mode 100644 index 0000000..4a3216e --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/fifo.rs @@ -0,0 +1,342 @@ +extern crate crossbeam_deque as deque; +extern crate crossbeam_utils as utils; +extern crate rand; + +use std::sync::atomic::Ordering::SeqCst; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::sync::{Arc, Mutex}; + +use deque::Steal::{Empty, Success}; +use deque::Worker; +use rand::Rng; +use utils::thread::scope; + +#[test] +fn smoke() { + let w = Worker::new_fifo(); + let s = w.stealer(); + assert_eq!(w.pop(), None); + assert_eq!(s.steal(), Empty); + + w.push(1); + assert_eq!(w.pop(), Some(1)); + assert_eq!(w.pop(), None); + assert_eq!(s.steal(), Empty); + + w.push(2); + assert_eq!(s.steal(), Success(2)); + assert_eq!(s.steal(), Empty); + assert_eq!(w.pop(), None); + + w.push(3); + w.push(4); + w.push(5); + assert_eq!(s.steal(), Success(3)); + assert_eq!(s.steal(), Success(4)); + assert_eq!(s.steal(), Success(5)); + assert_eq!(s.steal(), Empty); + + w.push(6); + w.push(7); + w.push(8); + w.push(9); + assert_eq!(w.pop(), Some(6)); + assert_eq!(s.steal(), Success(7)); + assert_eq!(w.pop(), Some(8)); + assert_eq!(w.pop(), Some(9)); + assert_eq!(w.pop(), None); +} + +#[test] +fn is_empty() { + let w = Worker::new_fifo(); + let s = w.stealer(); + + assert!(w.is_empty()); + w.push(1); + assert!(!w.is_empty()); + w.push(2); + assert!(!w.is_empty()); + let _ = w.pop(); + assert!(!w.is_empty()); + let _ = w.pop(); + assert!(w.is_empty()); + + assert!(s.is_empty()); + w.push(1); + assert!(!s.is_empty()); + w.push(2); + assert!(!s.is_empty()); + let _ = s.steal(); + assert!(!s.is_empty()); + let _ = s.steal(); + assert!(s.is_empty()); +} + +#[test] +fn spsc() { + const STEPS: usize = 50_000; + + let w = Worker::new_fifo(); + let s = w.stealer(); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..STEPS { + loop { + if let Success(v) = s.steal() { + assert_eq!(i, v); + break; + } + } + } + + assert_eq!(s.steal(), Empty); + }); + + for i in 0..STEPS { + w.push(i); + } + }) + .unwrap(); +} + +#[test] +fn stampede() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_fifo(); + + for i in 0..COUNT { + w.push(Box::new(i + 1)); + } + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let remaining = remaining.clone(); + + scope.spawn(move |_| { + let mut last = 0; + while remaining.load(SeqCst) > 0 { + if let Success(x) = s.steal() { + assert!(last < *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + let mut last = 0; + while remaining.load(SeqCst) > 0 { + if let Some(x) = w.pop() { + assert!(last < *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); +} + +#[test] +fn stress() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_fifo(); + let done = Arc::new(AtomicBool::new(false)); + let hits = Arc::new(AtomicUsize::new(0)); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let done = done.clone(); + let hits = hits.clone(); + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + + while !done.load(SeqCst) { + if let Success(_) = s.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut expected = 0; + while expected < COUNT { + if rng.gen_range(0, 3) == 0 { + while let Some(_) = w.pop() { + hits.fetch_add(1, SeqCst); + } + } else { + w.push(expected); + expected += 1; + } + } + + while hits.load(SeqCst) < COUNT { + while let Some(_) = w.pop() { + hits.fetch_add(1, SeqCst); + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn no_starvation() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_fifo(); + let done = Arc::new(AtomicBool::new(false)); + let mut all_hits = Vec::new(); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let done = done.clone(); + let hits = Arc::new(AtomicUsize::new(0)); + all_hits.push(hits.clone()); + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + + while !done.load(SeqCst) { + if let Success(_) = s.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut my_hits = 0; + loop { + for i in 0..rng.gen_range(0, COUNT) { + if rng.gen_range(0, 3) == 0 && my_hits == 0 { + while let Some(_) = w.pop() { + my_hits += 1; + } + } else { + w.push(i); + } + } + + if my_hits > 0 && all_hits.iter().all(|h| h.load(SeqCst) > 0) { + break; + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn destructors() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + const STEPS: usize = 1000; + + struct Elem(usize, Arc>>); + + impl Drop for Elem { + fn drop(&mut self) { + self.1.lock().unwrap().push(self.0); + } + } + + let w = Worker::new_fifo(); + let dropped = Arc::new(Mutex::new(Vec::new())); + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + for i in 0..COUNT { + w.push(Elem(i, dropped.clone())); + } + + scope(|scope| { + for _ in 0..THREADS { + let remaining = remaining.clone(); + let s = w.stealer(); + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + let mut cnt = 0; + + while cnt < STEPS { + if let Success(_) = s.steal() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + while let Some(_) = w2.pop() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + for _ in 0..STEPS { + if let Some(_) = w.pop() { + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); + + let rem = remaining.load(SeqCst); + assert!(rem > 0); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), COUNT - rem); + v.clear(); + } + + drop(w); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), rem); + v.sort(); + for pair in v.windows(2) { + assert_eq!(pair[0] + 1, pair[1]); + } + } +} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/injector.rs b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/injector.rs new file mode 100644 index 0000000..0692153 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/injector.rs @@ -0,0 +1,353 @@ +extern crate crossbeam_deque as deque; +extern crate crossbeam_utils as utils; +extern crate rand; + +use std::sync::atomic::Ordering::SeqCst; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::sync::{Arc, Mutex}; + +use deque::Steal::{Empty, Success}; +use deque::{Injector, Worker}; +use rand::Rng; +use utils::thread::scope; + +#[test] +fn smoke() { + let q = Injector::new(); + assert_eq!(q.steal(), Empty); + + q.push(1); + q.push(2); + assert_eq!(q.steal(), Success(1)); + assert_eq!(q.steal(), Success(2)); + assert_eq!(q.steal(), Empty); + + q.push(3); + assert_eq!(q.steal(), Success(3)); + assert_eq!(q.steal(), Empty); +} + +#[test] +fn is_empty() { + let q = Injector::new(); + assert!(q.is_empty()); + + q.push(1); + assert!(!q.is_empty()); + q.push(2); + assert!(!q.is_empty()); + + let _ = q.steal(); + assert!(!q.is_empty()); + let _ = q.steal(); + assert!(q.is_empty()); + + q.push(3); + assert!(!q.is_empty()); + let _ = q.steal(); + assert!(q.is_empty()); +} + +#[test] +fn spsc() { + const COUNT: usize = 100_000; + + let q = Injector::new(); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..COUNT { + loop { + if let Success(v) = q.steal() { + assert_eq!(i, v); + break; + } + } + } + + assert_eq!(q.steal(), Empty); + }); + + for i in 0..COUNT { + q.push(i); + } + }) + .unwrap(); +} + +#[test] +fn mpmc() { + const COUNT: usize = 25_000; + const THREADS: usize = 4; + + let q = Injector::new(); + let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); + + scope(|scope| { + for _ in 0..THREADS { + scope.spawn(|_| { + for i in 0..COUNT { + q.push(i); + } + }); + } + + for _ in 0..THREADS { + scope.spawn(|_| { + for _ in 0..COUNT { + loop { + if let Success(n) = q.steal() { + v[n].fetch_add(1, SeqCst); + break; + } + } + } + }); + } + }) + .unwrap(); + + for c in v { + assert_eq!(c.load(SeqCst), THREADS); + } +} + +#[test] +fn stampede() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let q = Injector::new(); + + for i in 0..COUNT { + q.push(Box::new(i + 1)); + } + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + scope(|scope| { + for _ in 0..THREADS { + let remaining = remaining.clone(); + let q = &q; + + scope.spawn(move |_| { + let mut last = 0; + while remaining.load(SeqCst) > 0 { + if let Success(x) = q.steal() { + assert!(last < *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + let mut last = 0; + while remaining.load(SeqCst) > 0 { + if let Success(x) = q.steal() { + assert!(last < *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); +} + +#[test] +fn stress() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let q = Injector::new(); + let done = Arc::new(AtomicBool::new(false)); + let hits = Arc::new(AtomicUsize::new(0)); + + scope(|scope| { + for _ in 0..THREADS { + let done = done.clone(); + let hits = hits.clone(); + let q = &q; + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + + while !done.load(SeqCst) { + if let Success(_) = q.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = q.steal_batch(&w2); + + if let Success(_) = q.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut expected = 0; + while expected < COUNT { + if rng.gen_range(0, 3) == 0 { + while let Success(_) = q.steal() { + hits.fetch_add(1, SeqCst); + } + } else { + q.push(expected); + expected += 1; + } + } + + while hits.load(SeqCst) < COUNT { + while let Success(_) = q.steal() { + hits.fetch_add(1, SeqCst); + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn no_starvation() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let q = Injector::new(); + let done = Arc::new(AtomicBool::new(false)); + let mut all_hits = Vec::new(); + + scope(|scope| { + for _ in 0..THREADS { + let done = done.clone(); + let hits = Arc::new(AtomicUsize::new(0)); + all_hits.push(hits.clone()); + let q = &q; + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + + while !done.load(SeqCst) { + if let Success(_) = q.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = q.steal_batch(&w2); + + if let Success(_) = q.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut my_hits = 0; + loop { + for i in 0..rng.gen_range(0, COUNT) { + if rng.gen_range(0, 3) == 0 && my_hits == 0 { + while let Success(_) = q.steal() { + my_hits += 1; + } + } else { + q.push(i); + } + } + + if my_hits > 0 && all_hits.iter().all(|h| h.load(SeqCst) > 0) { + break; + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn destructors() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + const STEPS: usize = 1000; + + struct Elem(usize, Arc>>); + + impl Drop for Elem { + fn drop(&mut self) { + self.1.lock().unwrap().push(self.0); + } + } + + let q = Injector::new(); + let dropped = Arc::new(Mutex::new(Vec::new())); + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + for i in 0..COUNT { + q.push(Elem(i, dropped.clone())); + } + + scope(|scope| { + for _ in 0..THREADS { + let remaining = remaining.clone(); + let q = &q; + + scope.spawn(move |_| { + let w2 = Worker::new_fifo(); + let mut cnt = 0; + + while cnt < STEPS { + if let Success(_) = q.steal() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + let _ = q.steal_batch(&w2); + + if let Success(_) = q.steal_batch_and_pop(&w2) { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + while let Some(_) = w2.pop() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + for _ in 0..STEPS { + if let Success(_) = q.steal() { + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); + + let rem = remaining.load(SeqCst); + assert!(rem > 0); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), COUNT - rem); + v.clear(); + } + + drop(q); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), rem); + v.sort(); + for pair in v.windows(2) { + assert_eq!(pair[0] + 1, pair[1]); + } + } +} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/lifo.rs b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/lifo.rs new file mode 100644 index 0000000..a44edfe --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/lifo.rs @@ -0,0 +1,342 @@ +extern crate crossbeam_deque as deque; +extern crate crossbeam_utils as utils; +extern crate rand; + +use std::sync::atomic::Ordering::SeqCst; +use std::sync::atomic::{AtomicBool, AtomicUsize}; +use std::sync::{Arc, Mutex}; + +use deque::Steal::{Empty, Success}; +use deque::Worker; +use rand::Rng; +use utils::thread::scope; + +#[test] +fn smoke() { + let w = Worker::new_lifo(); + let s = w.stealer(); + assert_eq!(w.pop(), None); + assert_eq!(s.steal(), Empty); + + w.push(1); + assert_eq!(w.pop(), Some(1)); + assert_eq!(w.pop(), None); + assert_eq!(s.steal(), Empty); + + w.push(2); + assert_eq!(s.steal(), Success(2)); + assert_eq!(s.steal(), Empty); + assert_eq!(w.pop(), None); + + w.push(3); + w.push(4); + w.push(5); + assert_eq!(s.steal(), Success(3)); + assert_eq!(s.steal(), Success(4)); + assert_eq!(s.steal(), Success(5)); + assert_eq!(s.steal(), Empty); + + w.push(6); + w.push(7); + w.push(8); + w.push(9); + assert_eq!(w.pop(), Some(9)); + assert_eq!(s.steal(), Success(6)); + assert_eq!(w.pop(), Some(8)); + assert_eq!(w.pop(), Some(7)); + assert_eq!(w.pop(), None); +} + +#[test] +fn is_empty() { + let w = Worker::new_lifo(); + let s = w.stealer(); + + assert!(w.is_empty()); + w.push(1); + assert!(!w.is_empty()); + w.push(2); + assert!(!w.is_empty()); + let _ = w.pop(); + assert!(!w.is_empty()); + let _ = w.pop(); + assert!(w.is_empty()); + + assert!(s.is_empty()); + w.push(1); + assert!(!s.is_empty()); + w.push(2); + assert!(!s.is_empty()); + let _ = s.steal(); + assert!(!s.is_empty()); + let _ = s.steal(); + assert!(s.is_empty()); +} + +#[test] +fn spsc() { + const STEPS: usize = 50_000; + + let w = Worker::new_lifo(); + let s = w.stealer(); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..STEPS { + loop { + if let Success(v) = s.steal() { + assert_eq!(i, v); + break; + } + } + } + + assert_eq!(s.steal(), Empty); + }); + + for i in 0..STEPS { + w.push(i); + } + }) + .unwrap(); +} + +#[test] +fn stampede() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_lifo(); + + for i in 0..COUNT { + w.push(Box::new(i + 1)); + } + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let remaining = remaining.clone(); + + scope.spawn(move |_| { + let mut last = 0; + while remaining.load(SeqCst) > 0 { + if let Success(x) = s.steal() { + assert!(last < *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + let mut last = COUNT + 1; + while remaining.load(SeqCst) > 0 { + if let Some(x) = w.pop() { + assert!(last > *x); + last = *x; + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); +} + +#[test] +fn stress() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_lifo(); + let done = Arc::new(AtomicBool::new(false)); + let hits = Arc::new(AtomicUsize::new(0)); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let done = done.clone(); + let hits = hits.clone(); + + scope.spawn(move |_| { + let w2 = Worker::new_lifo(); + + while !done.load(SeqCst) { + if let Success(_) = s.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut expected = 0; + while expected < COUNT { + if rng.gen_range(0, 3) == 0 { + while let Some(_) = w.pop() { + hits.fetch_add(1, SeqCst); + } + } else { + w.push(expected); + expected += 1; + } + } + + while hits.load(SeqCst) < COUNT { + while let Some(_) = w.pop() { + hits.fetch_add(1, SeqCst); + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn no_starvation() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + + let w = Worker::new_lifo(); + let done = Arc::new(AtomicBool::new(false)); + let mut all_hits = Vec::new(); + + scope(|scope| { + for _ in 0..THREADS { + let s = w.stealer(); + let done = done.clone(); + let hits = Arc::new(AtomicUsize::new(0)); + all_hits.push(hits.clone()); + + scope.spawn(move |_| { + let w2 = Worker::new_lifo(); + + while !done.load(SeqCst) { + if let Success(_) = s.steal() { + hits.fetch_add(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + hits.fetch_add(1, SeqCst); + } + + while let Some(_) = w2.pop() { + hits.fetch_add(1, SeqCst); + } + } + }); + } + + let mut rng = rand::thread_rng(); + let mut my_hits = 0; + loop { + for i in 0..rng.gen_range(0, COUNT) { + if rng.gen_range(0, 3) == 0 && my_hits == 0 { + while let Some(_) = w.pop() { + my_hits += 1; + } + } else { + w.push(i); + } + } + + if my_hits > 0 && all_hits.iter().all(|h| h.load(SeqCst) > 0) { + break; + } + } + done.store(true, SeqCst); + }) + .unwrap(); +} + +#[test] +fn destructors() { + const THREADS: usize = 8; + const COUNT: usize = 50_000; + const STEPS: usize = 1000; + + struct Elem(usize, Arc>>); + + impl Drop for Elem { + fn drop(&mut self) { + self.1.lock().unwrap().push(self.0); + } + } + + let w = Worker::new_lifo(); + let dropped = Arc::new(Mutex::new(Vec::new())); + let remaining = Arc::new(AtomicUsize::new(COUNT)); + + for i in 0..COUNT { + w.push(Elem(i, dropped.clone())); + } + + scope(|scope| { + for _ in 0..THREADS { + let remaining = remaining.clone(); + let s = w.stealer(); + + scope.spawn(move |_| { + let w2 = Worker::new_lifo(); + let mut cnt = 0; + + while cnt < STEPS { + if let Success(_) = s.steal() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + let _ = s.steal_batch(&w2); + + if let Success(_) = s.steal_batch_and_pop(&w2) { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + + while let Some(_) = w2.pop() { + cnt += 1; + remaining.fetch_sub(1, SeqCst); + } + } + }); + } + + for _ in 0..STEPS { + if let Some(_) = w.pop() { + remaining.fetch_sub(1, SeqCst); + } + } + }) + .unwrap(); + + let rem = remaining.load(SeqCst); + assert!(rem > 0); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), COUNT - rem); + v.clear(); + } + + drop(w); + + { + let mut v = dropped.lock().unwrap(); + assert_eq!(v.len(), rem); + v.sort(); + for pair in v.windows(2) { + assert_eq!(pair[0] + 1, pair[1]); + } + } +} diff --git a/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/steal.rs b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/steal.rs new file mode 100644 index 0000000..3e874df --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-deque-0.7.3/tests/steal.rs @@ -0,0 +1,214 @@ +extern crate crossbeam_deque as deque; + +use deque::Steal::Success; +use deque::{Injector, Worker}; + +#[test] +fn steal_fifo() { + let w = Worker::new_fifo(); + for i in 1..=3 { + w.push(i); + } + + let s = w.stealer(); + assert_eq!(s.steal(), Success(1)); + assert_eq!(s.steal(), Success(2)); + assert_eq!(s.steal(), Success(3)); +} + +#[test] +fn steal_lifo() { + let w = Worker::new_lifo(); + for i in 1..=3 { + w.push(i); + } + + let s = w.stealer(); + assert_eq!(s.steal(), Success(1)); + assert_eq!(s.steal(), Success(2)); + assert_eq!(s.steal(), Success(3)); +} + +#[test] +fn steal_injector() { + let q = Injector::new(); + for i in 1..=3 { + q.push(i); + } + + assert_eq!(q.steal(), Success(1)); + assert_eq!(q.steal(), Success(2)); + assert_eq!(q.steal(), Success(3)); +} + +#[test] +fn steal_batch_fifo_fifo() { + let w = Worker::new_fifo(); + for i in 1..=4 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_fifo(); + + assert_eq!(s.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(1)); + assert_eq!(w2.pop(), Some(2)); +} + +#[test] +fn steal_batch_lifo_lifo() { + let w = Worker::new_lifo(); + for i in 1..=4 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_lifo(); + + assert_eq!(s.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(1)); +} + +#[test] +fn steal_batch_fifo_lifo() { + let w = Worker::new_fifo(); + for i in 1..=4 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_lifo(); + + assert_eq!(s.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(1)); + assert_eq!(w2.pop(), Some(2)); +} + +#[test] +fn steal_batch_lifo_fifo() { + let w = Worker::new_lifo(); + for i in 1..=4 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_fifo(); + + assert_eq!(s.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(1)); +} + +#[test] +fn steal_batch_injector_fifo() { + let q = Injector::new(); + for i in 1..=4 { + q.push(i); + } + + let w2 = Worker::new_fifo(); + assert_eq!(q.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(1)); + assert_eq!(w2.pop(), Some(2)); +} + +#[test] +fn steal_batch_injector_lifo() { + let q = Injector::new(); + for i in 1..=4 { + q.push(i); + } + + let w2 = Worker::new_lifo(); + assert_eq!(q.steal_batch(&w2), Success(())); + assert_eq!(w2.pop(), Some(1)); + assert_eq!(w2.pop(), Some(2)); +} + +#[test] +fn steal_batch_and_pop_fifo_fifo() { + let w = Worker::new_fifo(); + for i in 1..=6 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_fifo(); + + assert_eq!(s.steal_batch_and_pop(&w2), Success(1)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(3)); +} + +#[test] +fn steal_batch_and_pop_lifo_lifo() { + let w = Worker::new_lifo(); + for i in 1..=6 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_lifo(); + + assert_eq!(s.steal_batch_and_pop(&w2), Success(3)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(1)); +} + +#[test] +fn steal_batch_and_pop_fifo_lifo() { + let w = Worker::new_fifo(); + for i in 1..=6 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_lifo(); + + assert_eq!(s.steal_batch_and_pop(&w2), Success(1)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(3)); +} + +#[test] +fn steal_batch_and_pop_lifo_fifo() { + let w = Worker::new_lifo(); + for i in 1..=6 { + w.push(i); + } + + let s = w.stealer(); + let w2 = Worker::new_fifo(); + + assert_eq!(s.steal_batch_and_pop(&w2), Success(3)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(1)); +} + +#[test] +fn steal_batch_and_pop_injector_fifo() { + let q = Injector::new(); + for i in 1..=6 { + q.push(i); + } + + let w2 = Worker::new_fifo(); + assert_eq!(q.steal_batch_and_pop(&w2), Success(1)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(3)); +} + +#[test] +fn steal_batch_and_pop_injector_lifo() { + let q = Injector::new(); + for i in 1..=6 { + q.push(i); + } + + let w2 = Worker::new_lifo(); + assert_eq!(q.steal_batch_and_pop(&w2), Success(1)); + assert_eq!(w2.pop(), Some(2)); + assert_eq!(w2.pop(), Some(3)); +} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/.cargo-checksum.json deleted file mode 100644 index 3d5e5a5..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"20401c46253ffb390d38018099328d3437b609bcf96264870367240af6938f3e","Cargo.toml":"e352fedefc606af80d9a858d84983da613f3b444f6ca1dde20312062ef670945","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"7fa0403233bce3f904f368981e4ce13b6769cf920154f31393dd4ef3574eb974","benches/defer.rs":"c4fcf1ebb596c1cde9661b64d6ea18e380b4ef56ae426d0c76edb5226cc591bb","benches/flush.rs":"773685fe76781e0d2d295af2153cf8a0320559306f2dab5bb407bfa94f8442c5","benches/pin.rs":"260ff2bc470b7e39075163a7eb70d4576b179873b460b6b58e37ddb5eac13d7e","examples/sanitize.rs":"487855c366f86e9fa8036a7ac8698fb318e03b01cbb7e8591cf9deff18c2cdc4","src/atomic.rs":"f2690b5fcf263355eb59ad57c470e90ff7435929bf7732f8bc3abf840e392f53","src/collector.rs":"6ee2c88365b458c93eec150d283487c028cd9a004d1af23a3015c442c63461de","src/default.rs":"6afda8fd141ad594bed62baeb73f2e97c5ef33b051969a542bb908946fe39dd1","src/deferred.rs":"0da22346bd86e25b5b676e6aefd80a1aaac12e12df267cac550ab893cb08d07b","src/epoch.rs":"76dd63356d5bc52e741883d39abb636e4ccb04d20499fb2a0ce797bb81aa4e91","src/guard.rs":"b56f1b2cf75f3f1af9ca138422e44bf0c9d6835f19e5c346e49d25f6240931c8","src/internal.rs":"7b9d705261ee490048cd493662eeac0e13569a41dbbb072828ace7deca9b7ac6","src/lib.rs":"8633a59dd9a4d167dfb3b4470102fa6e70f6902f265f179f5bf522b9084ec6a6","src/sync/list.rs":"96f0acfa33197c6ba0711e1a7e21eab68faa811283544317b6844bf00f6be490","src/sync/mod.rs":"2da979ca3a2293f7626a2e6a9ab2fad758d92e3d2bed6cc712ef59eeeea87eab","src/sync/queue.rs":"d34c527178c77b4936390f4c8c140e8d8a5873294926261902ee014b9fcaaa82"},"package":"2449aaa4ec7ef96e5fb24db16024b935df718e9ae1cec0a1e68feeca2efca7b8"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/BUILD b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/BUILD deleted file mode 100644 index 78c183c..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/BUILD +++ /dev/null @@ -1,55 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "MIT,Apache-2.0" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - - -rust_library( - name = "crossbeam_epoch", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2015", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/arrayvec-0.4.12:arrayvec", - "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", - "//third_party/cargo/vendor/crossbeam-utils-0.6.6:crossbeam_utils", - "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", - "//third_party/cargo/vendor/memoffset-0.2.1:memoffset", - "//third_party/cargo/vendor/scopeguard-0.3.3:scopeguard", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.6.1", - crate_features = [ - "default", - "lazy_static", - "std", - ], -) - -# Unsupported target "defer" with type "bench" omitted -# Unsupported target "flush" with type "bench" omitted -# Unsupported target "pin" with type "bench" omitted -# Unsupported target "sanitize" with type "example" omitted diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/CHANGELOG.md deleted file mode 100644 index fab4f70..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/CHANGELOG.md +++ /dev/null @@ -1,66 +0,0 @@ -# Version 0.6.1 - -- Update `crossbeam-utils` to `0.6`. - -# Version 0.6.0 - -- `defer` now requires `F: Send + 'static`. -- Bump the minimum Rust version to 1.26. -- Pinning while TLS is tearing down does not fail anymore. -- Rename `Handle` to `LocalHandle`. -- Add `defer_unchecked` and `defer_destroy`. -- Remove `Clone` impl for `LocalHandle`. - -# Version 0.5.2 - -- Update `crossbeam-utils` to `0.5`. - -# Version 0.5.1 - -- Fix compatibility with the latest Rust nightly. - -# Version 0.5.0 - -- Update `crossbeam-utils` to `0.4`. -- Specify the minimum Rust version to `1.25.0`. - -# Version 0.4.3 - -- Downgrade `crossbeam-utils` to `0.3` because it was a breaking change. - -# Version 0.4.2 - -- Expose the `Pointer` trait. -- Warn missing docs and missing debug impls. -- Update `crossbeam-utils` to `0.4`. - -# Version 0.4.1 - -- Add `Debug` impls for `Collector`, `Handle`, and `Guard`. -- Add `load_consume` to `Atomic`. -- Rename `Collector::handle` to `Collector::register`. -- Remove the `Send` implementation for `Handle` (this was a bug). Only - `Collector`s can be shared among multiple threads, while `Handle`s and - `Guard`s must stay within the thread in which they were created. - -# Version 0.4.0 - -- Update dependencies. -- Remove support for Rust 1.13. - -# Version 0.3.0 - -- Add support for Rust 1.13. -- Improve documentation for CAS. - -# Version 0.2.0 - -- Add method `Owned::into_box`. -- Fix a use-after-free bug in `Local::finalize`. -- Fix an ordering bug in `Global::push_bag`. -- Fix a bug in calculating distance between epochs. -- Remove `impl Into> for Owned`. - -# Version 0.1.0 - -- First version of the new epoch-based GC. diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/Cargo.toml b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/Cargo.toml deleted file mode 100644 index 4d99b26..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/Cargo.toml +++ /dev/null @@ -1,53 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "crossbeam-epoch" -version = "0.6.1" -authors = ["The Crossbeam Project Developers"] -description = "Epoch-based garbage collection" -homepage = "https://github.com/crossbeam-rs/crossbeam" -documentation = "https://docs.rs/crossbeam-epoch" -readme = "README.md" -keywords = ["lock-free", "rcu", "atomic", "garbage"] -categories = ["concurrency", "memory-management"] -license = "MIT/Apache-2.0" -repository = "https://github.com/crossbeam-rs/crossbeam" -[dependencies.arrayvec] -version = "0.4" -default-features = false - -[dependencies.cfg-if] -version = "0.1" - -[dependencies.crossbeam-utils] -version = "0.6" -default-features = false - -[dependencies.lazy_static] -version = "1" -optional = true - -[dependencies.memoffset] -version = "0.2" - -[dependencies.scopeguard] -version = "0.3" -default-features = false -[dev-dependencies.rand] -version = "0.5" - -[features] -default = ["std"] -nightly = ["arrayvec/use_union"] -sanitize = [] -std = ["lazy_static", "crossbeam-utils/std"] diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/README.md b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/README.md deleted file mode 100644 index d5c1e6d..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# Epoch-based garbage collection - -[![Build Status](https://travis-ci.org/crossbeam-rs/crossbeam.svg?branch=master)]( -https://travis-ci.org/crossbeam-rs/crossbeam) -[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( -https://github.com/crossbeam-rs/crossbeam-epoch) -[![Cargo](https://img.shields.io/crates/v/crossbeam-epoch.svg)]( -https://crates.io/crates/crossbeam-epoch) -[![Documentation](https://docs.rs/crossbeam-epoch/badge.svg)]( -https://docs.rs/crossbeam-epoch) - -This crate provides epoch-based garbage collection for use in concurrent data structures. - -If a thread removes a node from a concurrent data structure, other threads -may still have pointers to that node, so it cannot be immediately destructed. -Epoch GC allows deferring destruction until it becomes safe to do so. - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -crossbeam-epoch = "0.6" -``` - -Next, add this to your crate: - -```rust -extern crate crossbeam_epoch as epoch; -``` - -The minimum required Rust version is 1.26. - -## License - -Licensed under the terms of MIT license and the Apache License (Version 2.0). - -See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details. diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/defer.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/defer.rs deleted file mode 100644 index 7d0bace..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/defer.rs +++ /dev/null @@ -1,69 +0,0 @@ -#![feature(test)] - -extern crate crossbeam_epoch as epoch; -extern crate crossbeam_utils as utils; -extern crate test; - -use epoch::Owned; -use test::Bencher; -use utils::thread::scope; - -#[bench] -fn single_alloc_defer_free(b: &mut Bencher) { - b.iter(|| { - let guard = &epoch::pin(); - let p = Owned::new(1).into_shared(guard); - unsafe { - guard.defer_destroy(p); - } - }); -} - -#[bench] -fn single_defer(b: &mut Bencher) { - b.iter(|| { - let guard = &epoch::pin(); - guard.defer(move || ()); - }); -} - -#[bench] -fn multi_alloc_defer_free(b: &mut Bencher) { - const THREADS: usize = 16; - const STEPS: usize = 10_000; - - b.iter(|| { - scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - for _ in 0..STEPS { - let guard = &epoch::pin(); - let p = Owned::new(1).into_shared(guard); - unsafe { - guard.defer_destroy(p); - } - } - }); - } - }).unwrap(); - }); -} - -#[bench] -fn multi_defer(b: &mut Bencher) { - const THREADS: usize = 16; - const STEPS: usize = 10_000; - - b.iter(|| { - scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - for _ in 0..STEPS { - let guard = &epoch::pin(); - guard.defer(move || ()); - } - }); - } - }).unwrap(); - }); -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/flush.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/flush.rs deleted file mode 100644 index 4503ae9..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/flush.rs +++ /dev/null @@ -1,51 +0,0 @@ -#![feature(test)] - -extern crate crossbeam_epoch as epoch; -extern crate crossbeam_utils as utils; -extern crate test; - -use std::sync::Barrier; - -use test::Bencher; -use utils::thread::scope; - -#[bench] -fn single_flush(b: &mut Bencher) { - const THREADS: usize = 16; - - let start = Barrier::new(THREADS + 1); - let end = Barrier::new(THREADS + 1); - - scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - epoch::pin(); - start.wait(); - end.wait(); - }); - } - - start.wait(); - b.iter(|| epoch::pin().flush()); - end.wait(); - }).unwrap(); -} - -#[bench] -fn multi_flush(b: &mut Bencher) { - const THREADS: usize = 16; - const STEPS: usize = 10_000; - - b.iter(|| { - scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - for _ in 0..STEPS { - let guard = &epoch::pin(); - guard.flush(); - } - }); - } - }).unwrap(); - }); -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/pin.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/pin.rs deleted file mode 100644 index b709782..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/benches/pin.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![feature(test)] - -extern crate crossbeam_epoch as epoch; -extern crate crossbeam_utils as utils; -extern crate test; - -use test::Bencher; -use utils::thread::scope; - -#[bench] -fn single_pin(b: &mut Bencher) { - b.iter(|| epoch::pin()); -} - -#[bench] -fn multi_pin(b: &mut Bencher) { - const THREADS: usize = 16; - const STEPS: usize = 100_000; - - b.iter(|| { - scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - for _ in 0..STEPS { - epoch::pin(); - } - }); - } - }).unwrap(); - }); -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/examples/sanitize.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/examples/sanitize.rs deleted file mode 100644 index 4586cd5..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/examples/sanitize.rs +++ /dev/null @@ -1,68 +0,0 @@ -extern crate crossbeam_epoch as epoch; -extern crate rand; - -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed}; -use std::sync::Arc; -use std::thread; -use std::time::{Duration, Instant}; - -use epoch::{Atomic, Collector, LocalHandle, Owned, Shared}; -use rand::Rng; - -fn worker(a: Arc>, handle: LocalHandle) -> usize { - let mut rng = rand::thread_rng(); - let mut sum = 0; - - if rng.gen() { - thread::sleep(Duration::from_millis(1)); - } - let timeout = Duration::from_millis(rng.gen_range(0, 10)); - let now = Instant::now(); - - while now.elapsed() < timeout { - for _ in 0..100 { - let guard = &handle.pin(); - guard.flush(); - - let val = if rng.gen() { - let p = a.swap(Owned::new(AtomicUsize::new(sum)), AcqRel, guard); - unsafe { - guard.defer_destroy(p); - guard.flush(); - p.deref().load(Relaxed) - } - } else { - let p = a.load(Acquire, guard); - unsafe { p.deref().fetch_add(sum, Relaxed) } - }; - - sum = sum.wrapping_add(val); - } - } - - sum -} - -fn main() { - for _ in 0..100 { - let collector = Collector::new(); - let a = Arc::new(Atomic::new(AtomicUsize::new(777))); - - let threads = (0..16) - .map(|_| { - let a = a.clone(); - let c = collector.clone(); - thread::spawn(move || worker(a, c.register())) - }).collect::>(); - - for t in threads { - t.join().unwrap(); - } - - unsafe { - a.swap(Shared::null(), AcqRel, epoch::unprotected()) - .into_owned(); - } - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/atomic.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/atomic.rs deleted file mode 100644 index a69e061..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/atomic.rs +++ /dev/null @@ -1,1124 +0,0 @@ -use alloc::boxed::Box; -use core::borrow::{Borrow, BorrowMut}; -use core::cmp; -use core::fmt; -use core::marker::PhantomData; -use core::mem; -use core::ops::{Deref, DerefMut}; -use core::ptr; -use core::sync::atomic::Ordering; -use core::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; - -use crossbeam_utils::atomic::AtomicConsume; -use guard::Guard; - -/// Given ordering for the success case in a compare-exchange operation, returns the strongest -/// appropriate ordering for the failure case. -#[inline] -fn strongest_failure_ordering(ord: Ordering) -> Ordering { - use self::Ordering::*; - match ord { - Relaxed | Release => Relaxed, - Acquire | AcqRel => Acquire, - _ => SeqCst, - } -} - -/// The error returned on failed compare-and-set operation. -pub struct CompareAndSetError<'g, T: 'g, P: Pointer> { - /// The value in the atomic pointer at the time of the failed operation. - pub current: Shared<'g, T>, - - /// The new value, which the operation failed to store. - pub new: P, -} - -impl<'g, T: 'g, P: Pointer + fmt::Debug> fmt::Debug for CompareAndSetError<'g, T, P> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("CompareAndSetError") - .field("current", &self.current) - .field("new", &self.new) - .finish() - } -} - -/// Memory orderings for compare-and-set operations. -/// -/// A compare-and-set operation can have different memory orderings depending on whether it -/// succeeds or fails. This trait generalizes different ways of specifying memory orderings. -/// -/// The two ways of specifying orderings for compare-and-set are: -/// -/// 1. Just one `Ordering` for the success case. In case of failure, the strongest appropriate -/// ordering is chosen. -/// 2. A pair of `Ordering`s. The first one is for the success case, while the second one is -/// for the failure case. -pub trait CompareAndSetOrdering { - /// The ordering of the operation when it succeeds. - fn success(&self) -> Ordering; - - /// The ordering of the operation when it fails. - /// - /// The failure ordering can't be `Release` or `AcqRel` and must be equivalent or weaker than - /// the success ordering. - fn failure(&self) -> Ordering; -} - -impl CompareAndSetOrdering for Ordering { - #[inline] - fn success(&self) -> Ordering { - *self - } - - #[inline] - fn failure(&self) -> Ordering { - strongest_failure_ordering(*self) - } -} - -impl CompareAndSetOrdering for (Ordering, Ordering) { - #[inline] - fn success(&self) -> Ordering { - self.0 - } - - #[inline] - fn failure(&self) -> Ordering { - self.1 - } -} - -/// Panics if the pointer is not properly unaligned. -#[inline] -fn ensure_aligned(raw: *const T) { - assert_eq!(raw as usize & low_bits::(), 0, "unaligned pointer"); -} - -/// Returns a bitmask containing the unused least significant bits of an aligned pointer to `T`. -#[inline] -fn low_bits() -> usize { - (1 << mem::align_of::().trailing_zeros()) - 1 -} - -/// Given a tagged pointer `data`, returns the same pointer, but tagged with `tag`. -/// -/// `tag` is truncated to fit into the unused bits of the pointer to `T`. -#[inline] -fn data_with_tag(data: usize, tag: usize) -> usize { - (data & !low_bits::()) | (tag & low_bits::()) -} - -/// Decomposes a tagged pointer `data` into the pointer and the tag. -#[inline] -fn decompose_data(data: usize) -> (*mut T, usize) { - let raw = (data & !low_bits::()) as *mut T; - let tag = data & low_bits::(); - (raw, tag) -} - -/// An atomic pointer that can be safely shared between threads. -/// -/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused -/// least significant bits of the address. More precisely, a tag should be less than `(1 << -/// mem::align_of::().trailing_zeros())`. -/// -/// Any method that loads the pointer must be passed a reference to a [`Guard`]. -/// -/// [`Guard`]: struct.Guard.html -pub struct Atomic { - data: AtomicUsize, - _marker: PhantomData<*mut T>, -} - -unsafe impl Send for Atomic {} -unsafe impl Sync for Atomic {} - -impl Atomic { - /// Returns a new atomic pointer pointing to the tagged pointer `data`. - fn from_usize(data: usize) -> Self { - Self { - data: AtomicUsize::new(data), - _marker: PhantomData, - } - } - - /// Returns a new null atomic pointer. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Atomic; - /// - /// let a = Atomic::::null(); - /// ``` - #[cfg(not(feature = "nightly"))] - pub fn null() -> Atomic { - Self { - data: ATOMIC_USIZE_INIT, - _marker: PhantomData, - } - } - - /// Returns a new null atomic pointer. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Atomic; - /// - /// let a = Atomic::::null(); - /// ``` - #[cfg(feature = "nightly")] - pub const fn null() -> Atomic { - Self { - data: ATOMIC_USIZE_INIT, - _marker: PhantomData, - } - } - - /// Allocates `value` on the heap and returns a new atomic pointer pointing to it. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Atomic; - /// - /// let a = Atomic::new(1234); - /// ``` - pub fn new(value: T) -> Atomic { - Self::from(Owned::new(value)) - } - - /// Loads a `Shared` from the atomic pointer. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// let p = a.load(SeqCst, guard); - /// ``` - pub fn load<'g>(&self, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.load(ord)) } - } - - /// Loads a `Shared` from the atomic pointer using a "consume" memory ordering. - /// - /// This is similar to the "acquire" ordering, except that an ordering is - /// only guaranteed with operations that "depend on" the result of the load. - /// However consume loads are usually much faster than acquire loads on - /// architectures with a weak memory model since they don't require memory - /// fence instructions. - /// - /// The exact definition of "depend on" is a bit vague, but it works as you - /// would expect in practice since a lot of software, especially the Linux - /// kernel, rely on this behavior. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// let p = a.load_consume(guard); - /// ``` - pub fn load_consume<'g>(&self, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.load_consume()) } - } - - /// Stores a `Shared` or `Owned` pointer into the atomic pointer. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// a.store(Shared::null(), SeqCst); - /// a.store(Owned::new(1234), SeqCst); - /// ``` - pub fn store<'g, P: Pointer>(&self, new: P, ord: Ordering) { - self.data.store(new.into_usize(), ord); - } - - /// Stores a `Shared` or `Owned` pointer into the atomic pointer, returning the previous - /// `Shared`. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// let p = a.swap(Shared::null(), SeqCst, guard); - /// ``` - pub fn swap<'g, P: Pointer>(&self, new: P, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.swap(new.into_usize(), ord)) } - } - - /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current - /// value is the same as `current`. The tag is also taken into account, so two pointers to the - /// same object, but with different tags, will not be considered equal. - /// - /// The return value is a result indicating whether the new pointer was written. On success the - /// pointer that was written is returned. On failure the actual current value and `new` are - /// returned. - /// - /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory - /// ordering of this operation. - /// - /// [`CompareAndSetOrdering`]: trait.CompareAndSetOrdering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// - /// let guard = &epoch::pin(); - /// let mut curr = a.load(SeqCst, guard); - /// let res1 = a.compare_and_set(curr, Shared::null(), SeqCst, guard); - /// let res2 = a.compare_and_set(curr, Owned::new(5678), SeqCst, guard); - /// ``` - pub fn compare_and_set<'g, O, P>( - &self, - current: Shared, - new: P, - ord: O, - _: &'g Guard, - ) -> Result, CompareAndSetError<'g, T, P>> - where - O: CompareAndSetOrdering, - P: Pointer, - { - let new = new.into_usize(); - self.data - .compare_exchange(current.into_usize(), new, ord.success(), ord.failure()) - .map(|_| unsafe { Shared::from_usize(new) }) - .map_err(|current| unsafe { - CompareAndSetError { - current: Shared::from_usize(current), - new: P::from_usize(new), - } - }) - } - - /// Stores the pointer `new` (either `Shared` or `Owned`) into the atomic pointer if the current - /// value is the same as `current`. The tag is also taken into account, so two pointers to the - /// same object, but with different tags, will not be considered equal. - /// - /// Unlike [`compare_and_set`], this method is allowed to spuriously fail even when comparison - /// succeeds, which can result in more efficient code on some platforms. The return value is a - /// result indicating whether the new pointer was written. On success the pointer that was - /// written is returned. On failure the actual current value and `new` are returned. - /// - /// This method takes a [`CompareAndSetOrdering`] argument which describes the memory - /// ordering of this operation. - /// - /// [`compare_and_set`]: struct.Atomic.html#method.compare_and_set - /// [`CompareAndSetOrdering`]: trait.CompareAndSetOrdering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// - /// let mut new = Owned::new(5678); - /// let mut ptr = a.load(SeqCst, guard); - /// loop { - /// match a.compare_and_set_weak(ptr, new, SeqCst, guard) { - /// Ok(p) => { - /// ptr = p; - /// break; - /// } - /// Err(err) => { - /// ptr = err.current; - /// new = err.new; - /// } - /// } - /// } - /// - /// let mut curr = a.load(SeqCst, guard); - /// loop { - /// match a.compare_and_set_weak(curr, Shared::null(), SeqCst, guard) { - /// Ok(_) => break, - /// Err(err) => curr = err.current, - /// } - /// } - /// ``` - pub fn compare_and_set_weak<'g, O, P>( - &self, - current: Shared, - new: P, - ord: O, - _: &'g Guard, - ) -> Result, CompareAndSetError<'g, T, P>> - where - O: CompareAndSetOrdering, - P: Pointer, - { - let new = new.into_usize(); - self.data - .compare_exchange_weak(current.into_usize(), new, ord.success(), ord.failure()) - .map(|_| unsafe { Shared::from_usize(new) }) - .map_err(|current| unsafe { - CompareAndSetError { - current: Shared::from_usize(current), - new: P::from_usize(new), - } - }) - } - - /// Bitwise "and" with the current tag. - /// - /// Performs a bitwise "and" operation on the current tag and the argument `val`, and sets the - /// new tag to the result. Returns the previous pointer. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::::from(Shared::null().with_tag(3)); - /// let guard = &epoch::pin(); - /// assert_eq!(a.fetch_and(2, SeqCst, guard).tag(), 3); - /// assert_eq!(a.load(SeqCst, guard).tag(), 2); - /// ``` - pub fn fetch_and<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.fetch_and(val | !low_bits::(), ord)) } - } - - /// Bitwise "or" with the current tag. - /// - /// Performs a bitwise "or" operation on the current tag and the argument `val`, and sets the - /// new tag to the result. Returns the previous pointer. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::::from(Shared::null().with_tag(1)); - /// let guard = &epoch::pin(); - /// assert_eq!(a.fetch_or(2, SeqCst, guard).tag(), 1); - /// assert_eq!(a.load(SeqCst, guard).tag(), 3); - /// ``` - pub fn fetch_or<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.fetch_or(val & low_bits::(), ord)) } - } - - /// Bitwise "xor" with the current tag. - /// - /// Performs a bitwise "xor" operation on the current tag and the argument `val`, and sets the - /// new tag to the result. Returns the previous pointer. - /// - /// This method takes an [`Ordering`] argument which describes the memory ordering of this - /// operation. - /// - /// [`Ordering`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Shared}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::::from(Shared::null().with_tag(1)); - /// let guard = &epoch::pin(); - /// assert_eq!(a.fetch_xor(3, SeqCst, guard).tag(), 1); - /// assert_eq!(a.load(SeqCst, guard).tag(), 2); - /// ``` - pub fn fetch_xor<'g>(&self, val: usize, ord: Ordering, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.data.fetch_xor(val & low_bits::(), ord)) } - } -} - -impl fmt::Debug for Atomic { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let data = self.data.load(Ordering::SeqCst); - let (raw, tag) = decompose_data::(data); - - f.debug_struct("Atomic") - .field("raw", &raw) - .field("tag", &tag) - .finish() - } -} - -impl fmt::Pointer for Atomic { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let data = self.data.load(Ordering::SeqCst); - let (raw, _) = decompose_data::(data); - fmt::Pointer::fmt(&raw, f) - } -} - -impl Clone for Atomic { - /// Returns a copy of the atomic value. - /// - /// Note that a `Relaxed` load is used here. If you need synchronization, use it with other - /// atomics or fences. - fn clone(&self) -> Self { - let data = self.data.load(Ordering::Relaxed); - Atomic::from_usize(data) - } -} - -impl Default for Atomic { - fn default() -> Self { - Atomic::null() - } -} - -impl From> for Atomic { - /// Returns a new atomic pointer pointing to `owned`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{Atomic, Owned}; - /// - /// let a = Atomic::::from(Owned::new(1234)); - /// ``` - fn from(owned: Owned) -> Self { - let data = owned.data; - mem::forget(owned); - Self::from_usize(data) - } -} - -impl From> for Atomic { - fn from(b: Box) -> Self { - Self::from(Owned::from(b)) - } -} - -impl From for Atomic { - fn from(t: T) -> Self { - Self::new(t) - } -} - -impl<'g, T> From> for Atomic { - /// Returns a new atomic pointer pointing to `ptr`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{Atomic, Shared}; - /// - /// let a = Atomic::::from(Shared::::null()); - /// ``` - fn from(ptr: Shared<'g, T>) -> Self { - Self::from_usize(ptr.data) - } -} - -impl From<*const T> for Atomic { - /// Returns a new atomic pointer pointing to `raw`. - /// - /// # Examples - /// - /// ``` - /// use std::ptr; - /// use crossbeam_epoch::Atomic; - /// - /// let a = Atomic::::from(ptr::null::()); - /// ``` - fn from(raw: *const T) -> Self { - Self::from_usize(raw as usize) - } -} - -/// A trait for either `Owned` or `Shared` pointers. -pub trait Pointer { - /// Returns the machine representation of the pointer. - fn into_usize(self) -> usize; - - /// Returns a new pointer pointing to the tagged pointer `data`. - unsafe fn from_usize(data: usize) -> Self; -} - -/// An owned heap-allocated object. -/// -/// This type is very similar to `Box`. -/// -/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused -/// least significant bits of the address. -pub struct Owned { - data: usize, - _marker: PhantomData>, -} - -impl Pointer for Owned { - #[inline] - fn into_usize(self) -> usize { - let data = self.data; - mem::forget(self); - data - } - - /// Returns a new pointer pointing to the tagged pointer `data`. - /// - /// # Panics - /// - /// Panics if the data is zero in debug mode. - #[inline] - unsafe fn from_usize(data: usize) -> Self { - debug_assert!(data != 0, "converting zero into `Owned`"); - Owned { - data: data, - _marker: PhantomData, - } - } -} - -impl Owned { - /// Allocates `value` on the heap and returns a new owned pointer pointing to it. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Owned; - /// - /// let o = Owned::new(1234); - /// ``` - pub fn new(value: T) -> Owned { - Self::from(Box::new(value)) - } - - /// Returns a new owned pointer pointing to `raw`. - /// - /// This function is unsafe because improper use may lead to memory problems. Argument `raw` - /// must be a valid pointer. Also, a double-free may occur if the function is called twice on - /// the same raw pointer. - /// - /// # Panics - /// - /// Panics if `raw` is not properly aligned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Owned; - /// - /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) }; - /// ``` - pub unsafe fn from_raw(raw: *mut T) -> Owned { - ensure_aligned(raw); - Self::from_usize(raw as usize) - } - - /// Converts the owned pointer into a [`Shared`]. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Owned}; - /// - /// let o = Owned::new(1234); - /// let guard = &epoch::pin(); - /// let p = o.into_shared(guard); - /// ``` - /// - /// [`Shared`]: struct.Shared.html - pub fn into_shared<'g>(self, _: &'g Guard) -> Shared<'g, T> { - unsafe { Shared::from_usize(self.into_usize()) } - } - - /// Converts the owned pointer into a `Box`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Owned}; - /// - /// let o = Owned::new(1234); - /// let b: Box = o.into_box(); - /// assert_eq!(*b, 1234); - /// ``` - pub fn into_box(self) -> Box { - let (raw, _) = decompose_data::(self.data); - mem::forget(self); - unsafe { Box::from_raw(raw) } - } - - /// Returns the tag stored within the pointer. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Owned; - /// - /// assert_eq!(Owned::new(1234).tag(), 0); - /// ``` - pub fn tag(&self) -> usize { - let (_, tag) = decompose_data::(self.data); - tag - } - - /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the - /// unused bits of the pointer to `T`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Owned; - /// - /// let o = Owned::new(0u64); - /// assert_eq!(o.tag(), 0); - /// let o = o.with_tag(2); - /// assert_eq!(o.tag(), 2); - /// ``` - pub fn with_tag(self, tag: usize) -> Owned { - let data = self.into_usize(); - unsafe { Self::from_usize(data_with_tag::(data, tag)) } - } -} - -impl Drop for Owned { - fn drop(&mut self) { - let (raw, _) = decompose_data::(self.data); - unsafe { - drop(Box::from_raw(raw)); - } - } -} - -impl fmt::Debug for Owned { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let (raw, tag) = decompose_data::(self.data); - - f.debug_struct("Owned") - .field("raw", &raw) - .field("tag", &tag) - .finish() - } -} - -impl Clone for Owned { - fn clone(&self) -> Self { - Owned::new((**self).clone()).with_tag(self.tag()) - } -} - -impl Deref for Owned { - type Target = T; - - fn deref(&self) -> &T { - let (raw, _) = decompose_data::(self.data); - unsafe { &*raw } - } -} - -impl DerefMut for Owned { - fn deref_mut(&mut self) -> &mut T { - let (raw, _) = decompose_data::(self.data); - unsafe { &mut *raw } - } -} - -impl From for Owned { - fn from(t: T) -> Self { - Owned::new(t) - } -} - -impl From> for Owned { - /// Returns a new owned pointer pointing to `b`. - /// - /// # Panics - /// - /// Panics if the pointer (the `Box`) is not properly aligned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Owned; - /// - /// let o = unsafe { Owned::from_raw(Box::into_raw(Box::new(1234))) }; - /// ``` - fn from(b: Box) -> Self { - unsafe { Self::from_raw(Box::into_raw(b)) } - } -} - -impl Borrow for Owned { - fn borrow(&self) -> &T { - &**self - } -} - -impl BorrowMut for Owned { - fn borrow_mut(&mut self) -> &mut T { - &mut **self - } -} - -impl AsRef for Owned { - fn as_ref(&self) -> &T { - &**self - } -} - -impl AsMut for Owned { - fn as_mut(&mut self) -> &mut T { - &mut **self - } -} - -/// A pointer to an object protected by the epoch GC. -/// -/// The pointer is valid for use only during the lifetime `'g`. -/// -/// The pointer must be properly aligned. Since it is aligned, a tag can be stored into the unused -/// least significant bits of the address. -pub struct Shared<'g, T: 'g> { - data: usize, - _marker: PhantomData<(&'g (), *const T)>, -} - -impl<'g, T> Clone for Shared<'g, T> { - fn clone(&self) -> Self { - Shared { - data: self.data, - _marker: PhantomData, - } - } -} - -impl<'g, T> Copy for Shared<'g, T> {} - -impl<'g, T> Pointer for Shared<'g, T> { - #[inline] - fn into_usize(self) -> usize { - self.data - } - - #[inline] - unsafe fn from_usize(data: usize) -> Self { - Shared { - data: data, - _marker: PhantomData, - } - } -} - -impl<'g, T> Shared<'g, T> { - /// Returns a new null pointer. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Shared; - /// - /// let p = Shared::::null(); - /// assert!(p.is_null()); - /// ``` - pub fn null() -> Shared<'g, T> { - Shared { - data: 0, - _marker: PhantomData, - } - } - - /// Returns `true` if the pointer is null. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::null(); - /// let guard = &epoch::pin(); - /// assert!(a.load(SeqCst, guard).is_null()); - /// a.store(Owned::new(1234), SeqCst); - /// assert!(!a.load(SeqCst, guard).is_null()); - /// ``` - pub fn is_null(&self) -> bool { - self.as_raw().is_null() - } - - /// Converts the pointer to a raw pointer (without the tag). - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let o = Owned::new(1234); - /// let raw = &*o as *const _; - /// let a = Atomic::from(o); - /// - /// let guard = &epoch::pin(); - /// let p = a.load(SeqCst, guard); - /// assert_eq!(p.as_raw(), raw); - /// ``` - pub fn as_raw(&self) -> *const T { - let (raw, _) = decompose_data::(self.data); - raw - } - - /// Dereferences the pointer. - /// - /// Returns a reference to the pointee that is valid during the lifetime `'g`. - /// - /// # Safety - /// - /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory. - /// - /// Another concern is the possiblity of data races due to lack of proper synchronization. - /// For example, consider the following scenario: - /// - /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)` - /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()` - /// - /// The problem is that relaxed orderings don't synchronize initialization of the object with - /// the read from the second thread. This is a data race. A possible solution would be to use - /// `Release` and `Acquire` orderings. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// let p = a.load(SeqCst, guard); - /// unsafe { - /// assert_eq!(p.deref(), &1234); - /// } - /// ``` - pub unsafe fn deref(&self) -> &'g T { - &*self.as_raw() - } - - /// Converts the pointer to a reference. - /// - /// Returns `None` if the pointer is null, or else a reference to the object wrapped in `Some`. - /// - /// # Safety - /// - /// Dereferencing a pointer is unsafe because it could be pointing to invalid memory. - /// - /// Another concern is the possiblity of data races due to lack of proper synchronization. - /// For example, consider the following scenario: - /// - /// 1. A thread creates a new object: `a.store(Owned::new(10), Relaxed)` - /// 2. Another thread reads it: `*a.load(Relaxed, guard).as_ref().unwrap()` - /// - /// The problem is that relaxed orderings don't synchronize initialization of the object with - /// the read from the second thread. This is a data race. A possible solution would be to use - /// `Release` and `Acquire` orderings. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// let guard = &epoch::pin(); - /// let p = a.load(SeqCst, guard); - /// unsafe { - /// assert_eq!(p.as_ref(), Some(&1234)); - /// } - /// ``` - pub unsafe fn as_ref(&self) -> Option<&'g T> { - self.as_raw().as_ref() - } - - /// Takes ownership of the pointee. - /// - /// # Panics - /// - /// Panics if this pointer is null, but only in debug mode. - /// - /// # Safety - /// - /// This method may be called only if the pointer is valid and nobody else is holding a - /// reference to the same object. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(1234); - /// unsafe { - /// let guard = &epoch::unprotected(); - /// let p = a.load(SeqCst, guard); - /// drop(p.into_owned()); - /// } - /// ``` - pub unsafe fn into_owned(self) -> Owned { - debug_assert!( - self.as_raw() != ptr::null(), - "converting a null `Shared` into `Owned`" - ); - Owned::from_usize(self.data) - } - - /// Returns the tag stored within the pointer. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic, Owned}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::::from(Owned::new(0u64).with_tag(2)); - /// let guard = &epoch::pin(); - /// let p = a.load(SeqCst, guard); - /// assert_eq!(p.tag(), 2); - /// ``` - pub fn tag(&self) -> usize { - let (_, tag) = decompose_data::(self.data); - tag - } - - /// Returns the same pointer, but tagged with `tag`. `tag` is truncated to be fit into the - /// unused bits of the pointer to `T`. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new(0u64); - /// let guard = &epoch::pin(); - /// let p1 = a.load(SeqCst, guard); - /// let p2 = p1.with_tag(2); - /// - /// assert_eq!(p1.tag(), 0); - /// assert_eq!(p2.tag(), 2); - /// assert_eq!(p1.as_raw(), p2.as_raw()); - /// ``` - pub fn with_tag(&self, tag: usize) -> Shared<'g, T> { - unsafe { Self::from_usize(data_with_tag::(self.data, tag)) } - } -} - -impl<'g, T> From<*const T> for Shared<'g, T> { - /// Returns a new pointer pointing to `raw`. - /// - /// # Panics - /// - /// Panics if `raw` is not properly aligned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::Shared; - /// - /// let p = unsafe { Shared::from(Box::into_raw(Box::new(1234)) as *const _) }; - /// assert!(!p.is_null()); - /// ``` - fn from(raw: *const T) -> Self { - ensure_aligned(raw); - unsafe { Self::from_usize(raw as usize) } - } -} - -impl<'g, T> PartialEq> for Shared<'g, T> { - fn eq(&self, other: &Self) -> bool { - self.data == other.data - } -} - -impl<'g, T> Eq for Shared<'g, T> {} - -impl<'g, T> PartialOrd> for Shared<'g, T> { - fn partial_cmp(&self, other: &Self) -> Option { - self.data.partial_cmp(&other.data) - } -} - -impl<'g, T> Ord for Shared<'g, T> { - fn cmp(&self, other: &Self) -> cmp::Ordering { - self.data.cmp(&other.data) - } -} - -impl<'g, T> fmt::Debug for Shared<'g, T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let (raw, tag) = decompose_data::(self.data); - - f.debug_struct("Shared") - .field("raw", &raw) - .field("tag", &tag) - .finish() - } -} - -impl<'g, T> fmt::Pointer for Shared<'g, T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Pointer::fmt(&self.as_raw(), f) - } -} - -impl<'g, T> Default for Shared<'g, T> { - fn default() -> Self { - Shared::null() - } -} - -#[cfg(test)] -mod tests { - use super::Shared; - - #[test] - fn valid_tag_i8() { - Shared::::null().with_tag(0); - } - - #[test] - fn valid_tag_i64() { - Shared::::null().with_tag(7); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/collector.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/collector.rs deleted file mode 100644 index 4b17ba5..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/collector.rs +++ /dev/null @@ -1,433 +0,0 @@ -/// Epoch-based garbage collector. -/// -/// # Examples -/// -/// ``` -/// use crossbeam_epoch::Collector; -/// -/// let collector = Collector::new(); -/// -/// let handle = collector.register(); -/// drop(collector); // `handle` still works after dropping `collector` -/// -/// handle.pin().flush(); -/// ``` -use alloc::sync::Arc; -use core::fmt; - -use guard::Guard; -use internal::{Global, Local}; - -/// An epoch-based garbage collector. -pub struct Collector { - pub(crate) global: Arc, -} - -unsafe impl Send for Collector {} -unsafe impl Sync for Collector {} - -impl Collector { - /// Creates a new collector. - pub fn new() -> Self { - Collector { - global: Arc::new(Global::new()), - } - } - - /// Registers a new handle for the collector. - pub fn register(&self) -> LocalHandle { - Local::register(self) - } -} - -impl Clone for Collector { - /// Creates another reference to the same garbage collector. - fn clone(&self) -> Self { - Collector { - global: self.global.clone(), - } - } -} - -impl fmt::Debug for Collector { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Collector").finish() - } -} - -impl PartialEq for Collector { - /// Checks if both handles point to the same collector. - fn eq(&self, rhs: &Collector) -> bool { - Arc::ptr_eq(&self.global, &rhs.global) - } -} -impl Eq for Collector {} - -/// A handle to a garbage collector. -pub struct LocalHandle { - pub(crate) local: *const Local, -} - -impl LocalHandle { - /// Pins the handle. - #[inline] - pub fn pin(&self) -> Guard { - unsafe { (*self.local).pin() } - } - - /// Returns `true` if the handle is pinned. - #[inline] - pub fn is_pinned(&self) -> bool { - unsafe { (*self.local).is_pinned() } - } - - /// Returns the `Collector` associated with this handle. - #[inline] - pub fn collector(&self) -> &Collector { - unsafe { (*self.local).collector() } - } -} - -impl Drop for LocalHandle { - #[inline] - fn drop(&mut self) { - unsafe { - Local::release_handle(&*self.local); - } - } -} - -impl fmt::Debug for LocalHandle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("LocalHandle").finish() - } -} - -#[cfg(test)] -mod tests { - use std::mem; - use std::sync::atomic::Ordering; - use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; - - use crossbeam_utils::thread; - - use {Collector, Owned}; - - const NUM_THREADS: usize = 8; - - #[test] - fn pin_reentrant() { - let collector = Collector::new(); - let handle = collector.register(); - drop(collector); - - assert!(!handle.is_pinned()); - { - let _guard = &handle.pin(); - assert!(handle.is_pinned()); - { - let _guard = &handle.pin(); - assert!(handle.is_pinned()); - } - assert!(handle.is_pinned()); - } - assert!(!handle.is_pinned()); - } - - #[test] - fn flush_local_bag() { - let collector = Collector::new(); - let handle = collector.register(); - drop(collector); - - for _ in 0..100 { - let guard = &handle.pin(); - unsafe { - let a = Owned::new(7).into_shared(guard); - guard.defer_destroy(a); - - assert!(!(*(*guard.local).bag.get()).is_empty()); - - while !(*(*guard.local).bag.get()).is_empty() { - guard.flush(); - } - } - } - } - - #[test] - fn garbage_buffering() { - let collector = Collector::new(); - let handle = collector.register(); - drop(collector); - - let guard = &handle.pin(); - unsafe { - for _ in 0..10 { - let a = Owned::new(7).into_shared(guard); - guard.defer_destroy(a); - } - assert!(!(*(*guard.local).bag.get()).is_empty()); - } - } - - #[test] - fn pin_holds_advance() { - let collector = Collector::new(); - - thread::scope(|scope| { - for _ in 0..NUM_THREADS { - scope.spawn(|_| { - let handle = collector.register(); - for _ in 0..500_000 { - let guard = &handle.pin(); - - let before = collector.global.epoch.load(Ordering::Relaxed); - collector.global.collect(guard); - let after = collector.global.epoch.load(Ordering::Relaxed); - - assert!(after.wrapping_sub(before) <= 2); - } - }); - } - }).unwrap(); - } - - #[test] - fn incremental() { - const COUNT: usize = 100_000; - static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT; - - let collector = Collector::new(); - let handle = collector.register(); - - unsafe { - let guard = &handle.pin(); - for _ in 0..COUNT { - let a = Owned::new(7i32).into_shared(guard); - guard.defer_unchecked(move || { - drop(a.into_owned()); - DESTROYS.fetch_add(1, Ordering::Relaxed); - }); - } - guard.flush(); - } - - let mut last = 0; - - while last < COUNT { - let curr = DESTROYS.load(Ordering::Relaxed); - assert!(curr - last <= 1024); - last = curr; - - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert!(DESTROYS.load(Ordering::Relaxed) == 100_000); - } - - #[test] - fn buffering() { - const COUNT: usize = 10; - static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT; - - let collector = Collector::new(); - let handle = collector.register(); - - unsafe { - let guard = &handle.pin(); - for _ in 0..COUNT { - let a = Owned::new(7i32).into_shared(guard); - guard.defer_unchecked(move || { - drop(a.into_owned()); - DESTROYS.fetch_add(1, Ordering::Relaxed); - }); - } - } - - for _ in 0..100_000 { - collector.global.collect(&handle.pin()); - } - assert!(DESTROYS.load(Ordering::Relaxed) < COUNT); - - handle.pin().flush(); - - while DESTROYS.load(Ordering::Relaxed) < COUNT { - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT); - } - - #[test] - fn count_drops() { - const COUNT: usize = 100_000; - static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; - - struct Elem(i32); - - impl Drop for Elem { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::Relaxed); - } - } - - let collector = Collector::new(); - let handle = collector.register(); - - unsafe { - let guard = &handle.pin(); - - for _ in 0..COUNT { - let a = Owned::new(Elem(7i32)).into_shared(guard); - guard.defer_destroy(a); - } - guard.flush(); - } - - while DROPS.load(Ordering::Relaxed) < COUNT { - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert_eq!(DROPS.load(Ordering::Relaxed), COUNT); - } - - #[test] - fn count_destroy() { - const COUNT: usize = 100_000; - static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT; - - let collector = Collector::new(); - let handle = collector.register(); - - unsafe { - let guard = &handle.pin(); - - for _ in 0..COUNT { - let a = Owned::new(7i32).into_shared(guard); - guard.defer_unchecked(move || { - drop(a.into_owned()); - DESTROYS.fetch_add(1, Ordering::Relaxed); - }); - } - guard.flush(); - } - - while DESTROYS.load(Ordering::Relaxed) < COUNT { - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT); - } - - #[test] - fn drop_array() { - const COUNT: usize = 700; - static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; - - struct Elem(i32); - - impl Drop for Elem { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::Relaxed); - } - } - - let collector = Collector::new(); - let handle = collector.register(); - - let mut guard = handle.pin(); - - let mut v = Vec::with_capacity(COUNT); - for i in 0..COUNT { - v.push(Elem(i as i32)); - } - - { - let a = Owned::new(v).into_shared(&guard); - unsafe { - guard.defer_destroy(a); - } - guard.flush(); - } - - while DROPS.load(Ordering::Relaxed) < COUNT { - guard.repin(); - collector.global.collect(&guard); - } - assert_eq!(DROPS.load(Ordering::Relaxed), COUNT); - } - - #[test] - fn destroy_array() { - const COUNT: usize = 100_000; - static DESTROYS: AtomicUsize = ATOMIC_USIZE_INIT; - - let collector = Collector::new(); - let handle = collector.register(); - - unsafe { - let guard = &handle.pin(); - - let mut v = Vec::with_capacity(COUNT); - for i in 0..COUNT { - v.push(i as i32); - } - - let ptr = v.as_mut_ptr() as usize; - let len = v.len(); - guard.defer_unchecked(move || { - drop(Vec::from_raw_parts(ptr as *const u8 as *mut u8, len, len)); - DESTROYS.fetch_add(len, Ordering::Relaxed); - }); - guard.flush(); - - mem::forget(v); - } - - while DESTROYS.load(Ordering::Relaxed) < COUNT { - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert_eq!(DESTROYS.load(Ordering::Relaxed), COUNT); - } - - #[test] - fn stress() { - const THREADS: usize = 8; - const COUNT: usize = 100_000; - static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; - - struct Elem(i32); - - impl Drop for Elem { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::Relaxed); - } - } - - let collector = Collector::new(); - - thread::scope(|scope| { - for _ in 0..THREADS { - scope.spawn(|_| { - let handle = collector.register(); - for _ in 0..COUNT { - let guard = &handle.pin(); - unsafe { - let a = Owned::new(Elem(7i32)).into_shared(guard); - guard.defer_destroy(a); - } - } - }); - } - }).unwrap(); - - let handle = collector.register(); - while DROPS.load(Ordering::Relaxed) < COUNT * THREADS { - let guard = &handle.pin(); - collector.global.collect(guard); - } - assert_eq!(DROPS.load(Ordering::Relaxed), COUNT * THREADS); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/deferred.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/deferred.rs deleted file mode 100644 index 411428d..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/deferred.rs +++ /dev/null @@ -1,134 +0,0 @@ -use alloc::boxed::Box; -use core::fmt; -use core::marker::PhantomData; -use core::mem; -use core::ptr; - -/// Number of words a piece of `Data` can hold. -/// -/// Three words should be enough for the majority of cases. For example, you can fit inside it the -/// function pointer together with a fat pointer representing an object that needs to be destroyed. -const DATA_WORDS: usize = 3; - -/// Some space to keep a `FnOnce()` object on the stack. -type Data = [usize; DATA_WORDS]; - -/// A `FnOnce()` that is stored inline if small, or otherwise boxed on the heap. -/// -/// This is a handy way of keeping an unsized `FnOnce()` within a sized structure. -pub struct Deferred { - call: unsafe fn(*mut u8), - data: Data, - _marker: PhantomData<*mut ()>, // !Send + !Sync -} - -impl fmt::Debug for Deferred { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, "Deferred {{ ... }}") - } -} - -impl Deferred { - /// Constructs a new `Deferred` from a `FnOnce()`. - pub fn new(f: F) -> Self { - let size = mem::size_of::(); - let align = mem::align_of::(); - - unsafe { - if size <= mem::size_of::() && align <= mem::align_of::() { - let mut data: Data = mem::uninitialized(); - ptr::write(&mut data as *mut Data as *mut F, f); - - unsafe fn call(raw: *mut u8) { - let f: F = ptr::read(raw as *mut F); - f(); - } - - Deferred { - call: call::, - data, - _marker: PhantomData, - } - } else { - let b: Box = Box::new(f); - let mut data: Data = mem::uninitialized(); - ptr::write(&mut data as *mut Data as *mut Box, b); - - unsafe fn call(raw: *mut u8) { - let b: Box = ptr::read(raw as *mut Box); - (*b)(); - } - - Deferred { - call: call::, - data, - _marker: PhantomData, - } - } - } - } - - /// Calls the function. - #[inline] - pub fn call(mut self) { - let call = self.call; - unsafe { call(&mut self.data as *mut Data as *mut u8) }; - } -} - -#[cfg(test)] -mod tests { - use super::Deferred; - use std::cell::Cell; - - #[test] - fn on_stack() { - let fired = &Cell::new(false); - let a = [0usize; 1]; - - let d = Deferred::new(move || { - drop(a); - fired.set(true); - }); - - assert!(!fired.get()); - d.call(); - assert!(fired.get()); - } - - #[test] - fn on_heap() { - let fired = &Cell::new(false); - let a = [0usize; 10]; - - let d = Deferred::new(move || { - drop(a); - fired.set(true); - }); - - assert!(!fired.get()); - d.call(); - assert!(fired.get()); - } - - #[test] - fn string() { - let a = "hello".to_string(); - let d = Deferred::new(move || assert_eq!(a, "hello")); - d.call(); - } - - #[test] - fn boxed_slice_i32() { - let a: Box<[i32]> = vec![2, 3, 5, 7].into_boxed_slice(); - let d = Deferred::new(move || assert_eq!(*a, [2, 3, 5, 7])); - d.call(); - } - - #[test] - fn long_slice_usize() { - let a: [usize; 5] = [2, 3, 5, 7, 11]; - let d = Deferred::new(move || assert_eq!(a, [2, 3, 5, 7, 11])); - d.call(); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/guard.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/guard.rs deleted file mode 100644 index 04ca6f5..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/guard.rs +++ /dev/null @@ -1,547 +0,0 @@ -use core::fmt; -use core::mem; -use core::ptr; - -use atomic::Shared; -use collector::Collector; -use deferred::Deferred; -use internal::Local; - -/// A guard that keeps the current thread pinned. -/// -/// # Pinning -/// -/// The current thread is pinned by calling [`pin`], which returns a new guard: -/// -/// ``` -/// use crossbeam_epoch as epoch; -/// -/// // It is often convenient to prefix a call to `pin` with a `&` in order to create a reference. -/// // This is not really necessary, but makes passing references to the guard a bit easier. -/// let guard = &epoch::pin(); -/// ``` -/// -/// When a guard gets dropped, the current thread is automatically unpinned. -/// -/// # Pointers on the stack -/// -/// Having a guard allows us to create pointers on the stack to heap-allocated objects. -/// For example: -/// -/// ``` -/// use crossbeam_epoch::{self as epoch, Atomic, Owned}; -/// use std::sync::atomic::Ordering::SeqCst; -/// -/// // Create a heap-allocated number. -/// let a = Atomic::new(777); -/// -/// // Pin the current thread. -/// let guard = &epoch::pin(); -/// -/// // Load the heap-allocated object and create pointer `p` on the stack. -/// let p = a.load(SeqCst, guard); -/// -/// // Dereference the pointer and print the value: -/// if let Some(num) = unsafe { p.as_ref() } { -/// println!("The number is {}.", num); -/// } -/// ``` -/// -/// # Multiple guards -/// -/// Pinning is reentrant and it is perfectly legal to create multiple guards. In that case, the -/// thread will actually be pinned only when the first guard is created and unpinned when the last -/// one is dropped: -/// -/// ``` -/// use crossbeam_epoch as epoch; -/// -/// let guard1 = epoch::pin(); -/// let guard2 = epoch::pin(); -/// assert!(epoch::is_pinned()); -/// drop(guard1); -/// assert!(epoch::is_pinned()); -/// drop(guard2); -/// assert!(!epoch::is_pinned()); -/// ``` -/// -/// The same can be achieved by cloning guards: -/// -/// ``` -/// use crossbeam_epoch as epoch; -/// -/// let guard1 = epoch::pin(); -/// let guard2 = guard1.clone(); -/// ``` -/// -/// [`pin`]: fn.pin.html -pub struct Guard { - pub(crate) local: *const Local, -} - -impl Guard { - /// Stores a function so that it can be executed at some point after all currently pinned - /// threads get unpinned. - /// - /// This method first stores `f` into the thread-local (or handle-local) cache. If this cache - /// becomes full, some functions are moved into the global cache. At the same time, some - /// functions from both local and global caches may get executed in order to incrementally - /// clean up the caches as they fill up. - /// - /// There is no guarantee when exactly `f` will be executed. The only guarantee is that it - /// won't be executed until all currently pinned threads get unpinned. In theory, `f` might - /// never run, but the epoch-based garbage collection will make an effort to execute it - /// reasonably soon. - /// - /// If this method is called from an [`unprotected`] guard, the function will simply be - /// executed immediately. - /// - /// [`unprotected`]: fn.unprotected.html - pub fn defer(&self, f: F) - where - F: FnOnce() -> R, - F: Send + 'static, - { - unsafe { - self.defer_unchecked(f); - } - } - - /// Stores a function so that it can be executed at some point after all currently pinned - /// threads get unpinned. - /// - /// This method first stores `f` into the thread-local (or handle-local) cache. If this cache - /// becomes full, some functions are moved into the global cache. At the same time, some - /// functions from both local and global caches may get executed in order to incrementally - /// clean up the caches as they fill up. - /// - /// There is no guarantee when exactly `f` will be executed. The only guarantee is that it - /// won't be executed until all currently pinned threads get unpinned. In theory, `f` might - /// never run, but the epoch-based garbage collection will make an effort to execute it - /// reasonably soon. - /// - /// If this method is called from an [`unprotected`] guard, the function will simply be - /// executed immediately. - /// - /// # Safety - /// - /// The given function must not hold reference onto the stack. It is highly recommended that - /// the passed function is **always** marked with `move` in order to prevent accidental - /// borrows. - /// - /// ``` - /// use crossbeam_epoch as epoch; - /// - /// let guard = &epoch::pin(); - /// let message = "Hello!"; - /// unsafe { - /// // ALWAYS use `move` when sending a closure into `defer_unchecked`. - /// guard.defer_unchecked(move || { - /// println!("{}", message); - /// }); - /// } - /// ``` - /// - /// Apart from that, keep in mind that another thread may execute `f`, so anything accessed by - /// the closure must be `Send`. - /// - /// We intentionally didn't require `F: Send`, because Rust's type systems usually cannot prove - /// `F: Send` for typical use cases. For example, consider the following code snippet, which - /// exemplifies the typical use case of deferring the deallocation of a shared reference: - /// - /// ```ignore - /// let shared = Owned::new(7i32).into_shared(guard); - /// guard.defer_unchecked(move || shared.into_owned()); // `Shared` is not `Send`! - /// ``` - /// - /// While `Shared` is not `Send`, it's safe for another thread to call the deferred function, - /// because it's called only after the grace period and `shared` is no longer shared with other - /// threads. But we don't expect type systems to prove this. - /// - /// # Examples - /// - /// When a heap-allocated object in a data structure becomes unreachable, it has to be - /// deallocated. However, the current thread and other threads may be still holding references - /// on the stack to that same object. Therefore it cannot be deallocated before those references - /// get dropped. This method can defer deallocation until all those threads get unpinned and - /// consequently drop all their references on the stack. - /// - /// ```rust - /// use crossbeam_epoch::{self as epoch, Atomic, Owned}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new("foo"); - /// - /// // Now suppose that `a` is shared among multiple threads and concurrently - /// // accessed and modified... - /// - /// // Pin the current thread. - /// let guard = &epoch::pin(); - /// - /// // Steal the object currently stored in `a` and swap it with another one. - /// let p = a.swap(Owned::new("bar").into_shared(guard), SeqCst, guard); - /// - /// if !p.is_null() { - /// // The object `p` is pointing to is now unreachable. - /// // Defer its deallocation until all currently pinned threads get unpinned. - /// unsafe { - /// // ALWAYS use `move` when sending a closure into `defer_unchecked`. - /// guard.defer_unchecked(move || { - /// println!("{} is now being deallocated.", p.deref()); - /// // Now we have unique access to the object pointed to by `p` and can turn it - /// // into an `Owned`. Dropping the `Owned` will deallocate the object. - /// drop(p.into_owned()); - /// }); - /// } - /// } - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub unsafe fn defer_unchecked(&self, f: F) - where - F: FnOnce() -> R, - { - if let Some(local) = self.local.as_ref() { - local.defer(Deferred::new(move || drop(f())), self); - } - } - - /// Stores a destructor for an object so that it can be deallocated and dropped at some point - /// after all currently pinned threads get unpinned. - /// - /// This method first stores the destructor into the thread-local (or handle-local) cache. If - /// this cache becomes full, some destructors are moved into the global cache. At the same - /// time, some destructors from both local and global caches may get executed in order to - /// incrementally clean up the caches as they fill up. - /// - /// There is no guarantee when exactly the destructor will be executed. The only guarantee is - /// that it won't be executed until all currently pinned threads get unpinned. In theory, the - /// destructor might never run, but the epoch-based garbage collection will make an effort to - /// execute it reasonably soon. - /// - /// If this method is called from an [`unprotected`] guard, the destructor will simply be - /// executed immediately. - /// - /// # Safety - /// - /// The object must not be reachable by other threads anymore, otherwise it might be still in - /// use when the destructor runs. - /// - /// Apart from that, keep in mind that another thread may execute the destructor, so the object - /// must be sendable to other threads. - /// - /// We intentionally didn't require `T: Send`, because Rust's type systems usually cannot prove - /// `T: Send` for typical use cases. For example, consider the following code snippet, which - /// exemplifies the typical use case of deferring the deallocation of a shared reference: - /// - /// ```ignore - /// let shared = Owned::new(7i32).into_shared(guard); - /// guard.defer_destroy(shared); // `Shared` is not `Send`! - /// ``` - /// - /// While `Shared` is not `Send`, it's safe for another thread to call the destructor, because - /// it's called only after the grace period and `shared` is no longer shared with other - /// threads. But we don't expect type systems to prove this. - /// - /// # Examples - /// - /// When a heap-allocated object in a data structure becomes unreachable, it has to be - /// deallocated. However, the current thread and other threads may be still holding references - /// on the stack to that same object. Therefore it cannot be deallocated before those references - /// get dropped. This method can defer deallocation until all those threads get unpinned and - /// consequently drop all their references on the stack. - /// - /// ```rust - /// use crossbeam_epoch::{self as epoch, Atomic, Owned}; - /// use std::sync::atomic::Ordering::SeqCst; - /// - /// let a = Atomic::new("foo"); - /// - /// // Now suppose that `a` is shared among multiple threads and concurrently - /// // accessed and modified... - /// - /// // Pin the current thread. - /// let guard = &epoch::pin(); - /// - /// // Steal the object currently stored in `a` and swap it with another one. - /// let p = a.swap(Owned::new("bar").into_shared(guard), SeqCst, guard); - /// - /// if !p.is_null() { - /// // The object `p` is pointing to is now unreachable. - /// // Defer its deallocation until all currently pinned threads get unpinned. - /// unsafe { - /// guard.defer_destroy(p); - /// } - /// } - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub unsafe fn defer_destroy(&self, ptr: Shared) { - self.defer_unchecked(move || ptr.into_owned()); - } - - /// Clears up the thread-local cache of deferred functions by executing them or moving into the - /// global cache. - /// - /// Call this method after deferring execution of a function if you want to get it executed as - /// soon as possible. Flushing will make sure it is residing in in the global cache, so that - /// any thread has a chance of taking the function and executing it. - /// - /// If this method is called from an [`unprotected`] guard, it is a no-op (nothing happens). - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch as epoch; - /// - /// let guard = &epoch::pin(); - /// unsafe { - /// guard.defer(move || { - /// println!("This better be printed as soon as possible!"); - /// }); - /// } - /// guard.flush(); - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub fn flush(&self) { - if let Some(local) = unsafe { self.local.as_ref() } { - local.flush(self); - } - } - - /// Unpins and then immediately re-pins the thread. - /// - /// This method is useful when you don't want delay the advancement of the global epoch by - /// holding an old epoch. For safety, you should not maintain any guard-based reference across - /// the call (the latter is enforced by `&mut self`). The thread will only be repinned if this - /// is the only active guard for the current thread. - /// - /// If this method is called from an [`unprotected`] guard, then the call will be just no-op. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// use std::thread; - /// use std::time::Duration; - /// - /// let a = Atomic::new(777); - /// let mut guard = epoch::pin(); - /// { - /// let p = a.load(SeqCst, &guard); - /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); - /// } - /// guard.repin(); - /// { - /// let p = a.load(SeqCst, &guard); - /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); - /// } - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub fn repin(&mut self) { - if let Some(local) = unsafe { self.local.as_ref() } { - local.repin(); - } - } - - /// Temporarily unpins the thread, executes the given function and then re-pins the thread. - /// - /// This method is useful when you need to perform a long-running operation (e.g. sleeping) - /// and don't need to maintain any guard-based reference across the call (the latter is enforced - /// by `&mut self`). The thread will only be unpinned if this is the only active guard for the - /// current thread. - /// - /// If this method is called from an [`unprotected`] guard, then the passed function is called - /// directly without unpinning the thread. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch::{self as epoch, Atomic}; - /// use std::sync::atomic::Ordering::SeqCst; - /// use std::thread; - /// use std::time::Duration; - /// - /// let a = Atomic::new(777); - /// let mut guard = epoch::pin(); - /// { - /// let p = a.load(SeqCst, &guard); - /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); - /// } - /// guard.repin_after(|| thread::sleep(Duration::from_millis(50))); - /// { - /// let p = a.load(SeqCst, &guard); - /// assert_eq!(unsafe { p.as_ref() }, Some(&777)); - /// } - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub fn repin_after(&mut self, f: F) -> R - where - F: FnOnce() -> R, - { - if let Some(local) = unsafe { self.local.as_ref() } { - // We need to acquire a handle here to ensure the Local doesn't - // disappear from under us. - local.acquire_handle(); - local.unpin(); - } - - // Ensure the Guard is re-pinned even if the function panics - defer! { - if let Some(local) = unsafe { self.local.as_ref() } { - mem::forget(local.pin()); - local.release_handle(); - } - } - - f() - } - - /// Returns the `Collector` associated with this guard. - /// - /// This method is useful when you need to ensure that all guards used with - /// a data structure come from the same collector. - /// - /// If this method is called from an [`unprotected`] guard, then `None` is returned. - /// - /// # Examples - /// - /// ``` - /// use crossbeam_epoch as epoch; - /// - /// let mut guard1 = epoch::pin(); - /// let mut guard2 = epoch::pin(); - /// assert!(guard1.collector() == guard2.collector()); - /// ``` - /// - /// [`unprotected`]: fn.unprotected.html - pub fn collector(&self) -> Option<&Collector> { - unsafe { self.local.as_ref().map(|local| local.collector()) } - } -} - -impl Drop for Guard { - #[inline] - fn drop(&mut self) { - if let Some(local) = unsafe { self.local.as_ref() } { - local.unpin(); - } - } -} - -impl Clone for Guard { - #[inline] - fn clone(&self) -> Guard { - match unsafe { self.local.as_ref() } { - None => Guard { local: ptr::null() }, - Some(local) => local.pin(), - } - } -} - -impl fmt::Debug for Guard { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Guard").finish() - } -} - -/// Returns a reference to a dummy guard that allows unprotected access to [`Atomic`]s. -/// -/// This guard should be used in special occasions only. Note that it doesn't actually keep any -/// thread pinned - it's just a fake guard that allows loading from [`Atomic`]s unsafely. -/// -/// Note that calling [`defer`] with a dummy guard will not defer the function - it will just -/// execute the function immediately. -/// -/// If necessary, it's possible to create more dummy guards by cloning: `unprotected().clone()`. -/// -/// # Safety -/// -/// Loading and dereferencing data from an [`Atomic`] using this guard is safe only if the -/// [`Atomic`] is not being concurrently modified by other threads. -/// -/// # Examples -/// -/// ``` -/// use crossbeam_epoch::{self as epoch, Atomic}; -/// use std::sync::atomic::Ordering::Relaxed; -/// -/// let a = Atomic::new(7); -/// -/// unsafe { -/// // Load `a` without pinning the current thread. -/// a.load(Relaxed, epoch::unprotected()); -/// -/// // It's possible to create more dummy guards by calling `clone()`. -/// let dummy = &epoch::unprotected().clone(); -/// -/// dummy.defer(move || { -/// println!("This gets executed immediately."); -/// }); -/// -/// // Dropping `dummy` doesn't affect the current thread - it's just a noop. -/// } -/// ``` -/// -/// The most common use of this function is when constructing or destructing a data structure. -/// -/// For example, we can use a dummy guard in the destructor of a Treiber stack because at that -/// point no other thread could concurrently modify the [`Atomic`]s we are accessing. -/// -/// If we were to actually pin the current thread during destruction, that would just unnecessarily -/// delay garbage collection and incur some performance cost, so in cases like these `unprotected` -/// is very helpful. -/// -/// ``` -/// use crossbeam_epoch::{self as epoch, Atomic}; -/// use std::mem::ManuallyDrop; -/// use std::sync::atomic::Ordering::Relaxed; -/// -/// struct Stack { -/// head: Atomic>, -/// } -/// -/// struct Node { -/// data: ManuallyDrop, -/// next: Atomic>, -/// } -/// -/// impl Drop for Stack { -/// fn drop(&mut self) { -/// unsafe { -/// // Unprotected load. -/// let mut node = self.head.load(Relaxed, epoch::unprotected()); -/// -/// while let Some(n) = node.as_ref() { -/// // Unprotected load. -/// let next = n.next.load(Relaxed, epoch::unprotected()); -/// -/// // Take ownership of the node, then drop its data and deallocate it. -/// let mut o = node.into_owned(); -/// ManuallyDrop::drop(&mut o.data); -/// drop(o); -/// -/// node = next; -/// } -/// } -/// } -/// } -/// ``` -/// -/// [`Atomic`]: struct.Atomic.html -/// [`defer`]: struct.Guard.html#method.defer -#[inline] -pub unsafe fn unprotected() -> &'static Guard { - // HACK(stjepang): An unprotected guard is just a `Guard` with its field `local` set to null. - // Since this function returns a `'static` reference to a `Guard`, we must return a reference - // to a global guard. However, it's not possible to create a `static` `Guard` because it does - // not implement `Sync`. To get around the problem, we create a static `usize` initialized to - // zero and then transmute it into a `Guard`. This is safe because `usize` and `Guard` - // (consisting of a single pointer) have the same representation in memory. - static UNPROTECTED: usize = 0; - &*(&UNPROTECTED as *const _ as *const Guard) -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/internal.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/internal.rs deleted file mode 100644 index 8104748..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/internal.rs +++ /dev/null @@ -1,546 +0,0 @@ -//! The global data and participant for garbage collection. -//! -//! # Registration -//! -//! In order to track all participants in one place, we need some form of participant -//! registration. When a participant is created, it is registered to a global lock-free -//! singly-linked list of registries; and when a participant is leaving, it is unregistered from the -//! list. -//! -//! # Pinning -//! -//! Every participant contains an integer that tells whether the participant is pinned and if so, -//! what was the global epoch at the time it was pinned. Participants also hold a pin counter that -//! aids in periodic global epoch advancement. -//! -//! When a participant is pinned, a `Guard` is returned as a witness that the participant is pinned. -//! Guards are necessary for performing atomic operations, and for freeing/dropping locations. -//! -//! # Thread-local bag -//! -//! Objects that get unlinked from concurrent data structures must be stashed away until the global -//! epoch sufficiently advances so that they become safe for destruction. Pointers to such objects -//! are pushed into a thread-local bag, and when it becomes full, the bag is marked with the current -//! global epoch and pushed into the global queue of bags. We store objects in thread-local storages -//! for amortizing the synchronization cost of pushing the garbages to a global queue. -//! -//! # Global queue -//! -//! Whenever a bag is pushed into a queue, the objects in some bags in the queue are collected and -//! destroyed along the way. This design reduces contention on data structures. The global queue -//! cannot be explicitly accessed: the only way to interact with it is by calling functions -//! `defer()` that adds an object tothe thread-local bag, or `collect()` that manually triggers -//! garbage collection. -//! -//! Ideally each instance of concurrent data structure may have its own queue that gets fully -//! destroyed as soon as the data structure gets dropped. - -use alloc::boxed::Box; -use core::cell::{Cell, UnsafeCell}; -use core::mem::{self, ManuallyDrop}; -use core::num::Wrapping; -use core::ptr; -use core::sync::atomic; -use core::sync::atomic::Ordering; - -use arrayvec::ArrayVec; -use crossbeam_utils::CachePadded; - -use atomic::Owned; -use collector::{Collector, LocalHandle}; -use deferred::Deferred; -use epoch::{AtomicEpoch, Epoch}; -use guard::{unprotected, Guard}; -use sync::list::{Entry, IsElement, IterError, List}; -use sync::queue::Queue; - -/// Maximum number of objects a bag can contain. -#[cfg(not(feature = "sanitize"))] -const MAX_OBJECTS: usize = 64; -#[cfg(feature = "sanitize")] -const MAX_OBJECTS: usize = 4; - -/// A bag of deferred functions. -#[derive(Default, Debug)] -pub struct Bag { - /// Stashed objects. - deferreds: ArrayVec<[Deferred; MAX_OBJECTS]>, -} - -/// `Bag::try_push()` requires that it is safe for another thread to execute the given functions. -unsafe impl Send for Bag {} - -impl Bag { - /// Returns a new, empty bag. - pub fn new() -> Self { - Self::default() - } - - /// Returns `true` if the bag is empty. - pub fn is_empty(&self) -> bool { - self.deferreds.is_empty() - } - - /// Attempts to insert a deferred function into the bag. - /// - /// Returns `Ok(())` if successful, and `Err(deferred)` for the given `deferred` if the bag is - /// full. - /// - /// # Safety - /// - /// It should be safe for another thread to execute the given function. - pub unsafe fn try_push(&mut self, deferred: Deferred) -> Result<(), Deferred> { - self.deferreds.try_push(deferred).map_err(|e| e.element()) - } - - /// Seals the bag with the given epoch. - fn seal(self, epoch: Epoch) -> SealedBag { - SealedBag { epoch, bag: self } - } -} - -impl Drop for Bag { - fn drop(&mut self) { - // Call all deferred functions. - for deferred in self.deferreds.drain(..) { - deferred.call(); - } - } -} - -/// A pair of an epoch and a bag. -#[derive(Default, Debug)] -struct SealedBag { - epoch: Epoch, - bag: Bag, -} - -/// It is safe to share `SealedBag` because `is_expired` only inspects the epoch. -unsafe impl Sync for SealedBag {} - -impl SealedBag { - /// Checks if it is safe to drop the bag w.r.t. the given global epoch. - fn is_expired(&self, global_epoch: Epoch) -> bool { - // A pinned participant can witness at most one epoch advancement. Therefore, any bag that - // is within one epoch of the current one cannot be destroyed yet. - global_epoch.wrapping_sub(self.epoch) >= 2 - } -} - -/// The global data for a garbage collector. -pub struct Global { - /// The intrusive linked list of `Local`s. - locals: List, - - /// The global queue of bags of deferred functions. - queue: Queue, - - /// The global epoch. - pub(crate) epoch: CachePadded, -} - -impl Global { - /// Number of bags to destroy. - const COLLECT_STEPS: usize = 8; - - /// Creates a new global data for garbage collection. - #[inline] - pub fn new() -> Self { - Self { - locals: List::new(), - queue: Queue::new(), - epoch: CachePadded::new(AtomicEpoch::new(Epoch::starting())), - } - } - - /// Pushes the bag into the global queue and replaces the bag with a new empty bag. - pub fn push_bag(&self, bag: &mut Bag, guard: &Guard) { - let bag = mem::replace(bag, Bag::new()); - - atomic::fence(Ordering::SeqCst); - - let epoch = self.epoch.load(Ordering::Relaxed); - self.queue.push(bag.seal(epoch), guard); - } - - /// Collects several bags from the global queue and executes deferred functions in them. - /// - /// Note: This may itself produce garbage and in turn allocate new bags. - /// - /// `pin()` rarely calls `collect()`, so we want the compiler to place that call on a cold - /// path. In other words, we want the compiler to optimize branching for the case when - /// `collect()` is not called. - #[cold] - pub fn collect(&self, guard: &Guard) { - let global_epoch = self.try_advance(guard); - - let steps = if cfg!(feature = "sanitize") { - usize::max_value() - } else { - Self::COLLECT_STEPS - }; - - for _ in 0..steps { - match self.queue.try_pop_if( - &|sealed_bag: &SealedBag| sealed_bag.is_expired(global_epoch), - guard, - ) { - None => break, - Some(sealed_bag) => drop(sealed_bag), - } - } - } - - /// Attempts to advance the global epoch. - /// - /// The global epoch can advance only if all currently pinned participants have been pinned in - /// the current epoch. - /// - /// Returns the current global epoch. - /// - /// `try_advance()` is annotated `#[cold]` because it is rarely called. - #[cold] - pub fn try_advance(&self, guard: &Guard) -> Epoch { - let global_epoch = self.epoch.load(Ordering::Relaxed); - atomic::fence(Ordering::SeqCst); - - // TODO(stjepang): `Local`s are stored in a linked list because linked lists are fairly - // easy to implement in a lock-free manner. However, traversal can be slow due to cache - // misses and data dependencies. We should experiment with other data structures as well. - for local in self.locals.iter(&guard) { - match local { - Err(IterError::Stalled) => { - // A concurrent thread stalled this iteration. That thread might also try to - // advance the epoch, in which case we leave the job to it. Otherwise, the - // epoch will not be advanced. - return global_epoch; - } - Ok(local) => { - let local_epoch = local.epoch.load(Ordering::Relaxed); - - // If the participant was pinned in a different epoch, we cannot advance the - // global epoch just yet. - if local_epoch.is_pinned() && local_epoch.unpinned() != global_epoch { - return global_epoch; - } - } - } - } - atomic::fence(Ordering::Acquire); - - // All pinned participants were pinned in the current global epoch. - // Now let's advance the global epoch... - // - // Note that if another thread already advanced it before us, this store will simply - // overwrite the global epoch with the same value. This is true because `try_advance` was - // called from a thread that was pinned in `global_epoch`, and the global epoch cannot be - // advanced two steps ahead of it. - let new_epoch = global_epoch.successor(); - self.epoch.store(new_epoch, Ordering::Release); - new_epoch - } -} - -/// Participant for garbage collection. -pub struct Local { - /// A node in the intrusive linked list of `Local`s. - entry: Entry, - - /// The local epoch. - epoch: AtomicEpoch, - - /// A reference to the global data. - /// - /// When all guards and handles get dropped, this reference is destroyed. - collector: UnsafeCell>, - - /// The local bag of deferred functions. - pub(crate) bag: UnsafeCell, - - /// The number of guards keeping this participant pinned. - guard_count: Cell, - - /// The number of active handles. - handle_count: Cell, - - /// Total number of pinnings performed. - /// - /// This is just an auxilliary counter that sometimes kicks off collection. - pin_count: Cell>, -} - -impl Local { - /// Number of pinnings after which a participant will execute some deferred functions from the - /// global queue. - const PINNINGS_BETWEEN_COLLECT: usize = 128; - - /// Registers a new `Local` in the provided `Global`. - pub fn register(collector: &Collector) -> LocalHandle { - unsafe { - // Since we dereference no pointers in this block, it is safe to use `unprotected`. - - let local = Owned::new(Local { - entry: Entry::default(), - epoch: AtomicEpoch::new(Epoch::starting()), - collector: UnsafeCell::new(ManuallyDrop::new(collector.clone())), - bag: UnsafeCell::new(Bag::new()), - guard_count: Cell::new(0), - handle_count: Cell::new(1), - pin_count: Cell::new(Wrapping(0)), - }).into_shared(&unprotected()); - collector.global.locals.insert(local, &unprotected()); - LocalHandle { - local: local.as_raw(), - } - } - } - - /// Returns a reference to the `Global` in which this `Local` resides. - #[inline] - pub fn global(&self) -> &Global { - &self.collector().global - } - - /// Returns a reference to the `Collector` in which this `Local` resides. - #[inline] - pub fn collector(&self) -> &Collector { - unsafe { &**self.collector.get() } - } - - /// Returns `true` if the current participant is pinned. - #[inline] - pub fn is_pinned(&self) -> bool { - self.guard_count.get() > 0 - } - - /// Adds `deferred` to the thread-local bag. - /// - /// # Safety - /// - /// It should be safe for another thread to execute the given function. - pub unsafe fn defer(&self, mut deferred: Deferred, guard: &Guard) { - let bag = &mut *self.bag.get(); - - while let Err(d) = bag.try_push(deferred) { - self.global().push_bag(bag, guard); - deferred = d; - } - } - - pub fn flush(&self, guard: &Guard) { - let bag = unsafe { &mut *self.bag.get() }; - - if !bag.is_empty() { - self.global().push_bag(bag, guard); - } - - self.global().collect(guard); - } - - /// Pins the `Local`. - #[inline] - pub fn pin(&self) -> Guard { - let guard = Guard { local: self }; - - let guard_count = self.guard_count.get(); - self.guard_count.set(guard_count.checked_add(1).unwrap()); - - if guard_count == 0 { - let global_epoch = self.global().epoch.load(Ordering::Relaxed); - let new_epoch = global_epoch.pinned(); - - // Now we must store `new_epoch` into `self.epoch` and execute a `SeqCst` fence. - // The fence makes sure that any future loads from `Atomic`s will not happen before - // this store. - if cfg!(any(target_arch = "x86", target_arch = "x86_64")) { - // HACK(stjepang): On x86 architectures there are two different ways of executing - // a `SeqCst` fence. - // - // 1. `atomic::fence(SeqCst)`, which compiles into a `mfence` instruction. - // 2. `_.compare_and_swap(_, _, SeqCst)`, which compiles into a `lock cmpxchg` - // instruction. - // - // Both instructions have the effect of a full barrier, but benchmarks have shown - // that the second one makes pinning faster in this particular case. - let current = Epoch::starting(); - let previous = self - .epoch - .compare_and_swap(current, new_epoch, Ordering::SeqCst); - debug_assert_eq!(current, previous, "participant was expected to be unpinned"); - } else { - self.epoch.store(new_epoch, Ordering::Relaxed); - atomic::fence(Ordering::SeqCst); - } - - // Increment the pin counter. - let count = self.pin_count.get(); - self.pin_count.set(count + Wrapping(1)); - - // After every `PINNINGS_BETWEEN_COLLECT` try advancing the epoch and collecting - // some garbage. - if count.0 % Self::PINNINGS_BETWEEN_COLLECT == 0 { - self.global().collect(&guard); - } - } - - guard - } - - /// Unpins the `Local`. - #[inline] - pub fn unpin(&self) { - let guard_count = self.guard_count.get(); - self.guard_count.set(guard_count - 1); - - if guard_count == 1 { - self.epoch.store(Epoch::starting(), Ordering::Release); - - if self.handle_count.get() == 0 { - self.finalize(); - } - } - } - - /// Unpins and then pins the `Local`. - #[inline] - pub fn repin(&self) { - let guard_count = self.guard_count.get(); - - // Update the local epoch only if there's only one guard. - if guard_count == 1 { - let epoch = self.epoch.load(Ordering::Relaxed); - let global_epoch = self.global().epoch.load(Ordering::Relaxed).pinned(); - - // Update the local epoch only if the global epoch is greater than the local epoch. - if epoch != global_epoch { - // We store the new epoch with `Release` because we need to ensure any memory - // accesses from the previous epoch do not leak into the new one. - self.epoch.store(global_epoch, Ordering::Release); - - // However, we don't need a following `SeqCst` fence, because it is safe for memory - // accesses from the new epoch to be executed before updating the local epoch. At - // worse, other threads will see the new epoch late and delay GC slightly. - } - } - } - - /// Increments the handle count. - #[inline] - pub fn acquire_handle(&self) { - let handle_count = self.handle_count.get(); - debug_assert!(handle_count >= 1); - self.handle_count.set(handle_count + 1); - } - - /// Decrements the handle count. - #[inline] - pub fn release_handle(&self) { - let guard_count = self.guard_count.get(); - let handle_count = self.handle_count.get(); - debug_assert!(handle_count >= 1); - self.handle_count.set(handle_count - 1); - - if guard_count == 0 && handle_count == 1 { - self.finalize(); - } - } - - /// Removes the `Local` from the global linked list. - #[cold] - fn finalize(&self) { - debug_assert_eq!(self.guard_count.get(), 0); - debug_assert_eq!(self.handle_count.get(), 0); - - // Temporarily increment handle count. This is required so that the following call to `pin` - // doesn't call `finalize` again. - self.handle_count.set(1); - unsafe { - // Pin and move the local bag into the global queue. It's important that `push_bag` - // doesn't defer destruction on any new garbage. - let guard = &self.pin(); - self.global().push_bag(&mut *self.bag.get(), guard); - } - // Revert the handle count back to zero. - self.handle_count.set(0); - - unsafe { - // Take the reference to the `Global` out of this `Local`. Since we're not protected - // by a guard at this time, it's crucial that the reference is read before marking the - // `Local` as deleted. - let collector: Collector = ptr::read(&*(*self.collector.get())); - - // Mark this node in the linked list as deleted. - self.entry.delete(&unprotected()); - - // Finally, drop the reference to the global. Note that this might be the last reference - // to the `Global`. If so, the global data will be destroyed and all deferred functions - // in its queue will be executed. - drop(collector); - } - } -} - -impl IsElement for Local { - fn entry_of(local: &Local) -> &Entry { - let entry_ptr = (local as *const Local as usize + offset_of!(Local, entry)) as *const Entry; - unsafe { &*entry_ptr } - } - - unsafe fn element_of(entry: &Entry) -> &Local { - // offset_of! macro uses unsafe, but it's unnecessary in this context. - #[allow(unused_unsafe)] - let local_ptr = (entry as *const Entry as usize - offset_of!(Local, entry)) as *const Local; - &*local_ptr - } - - unsafe fn finalize(entry: &Entry) { - let local = Self::element_of(entry); - drop(Box::from_raw(local as *const Local as *mut Local)); - } -} - -#[cfg(test)] -mod tests { - use std::sync::atomic::Ordering; - use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; - - use super::*; - - #[test] - fn check_defer() { - static FLAG: AtomicUsize = ATOMIC_USIZE_INIT; - fn set() { - FLAG.store(42, Ordering::Relaxed); - } - - let d = Deferred::new(set); - assert_eq!(FLAG.load(Ordering::Relaxed), 0); - d.call(); - assert_eq!(FLAG.load(Ordering::Relaxed), 42); - } - - #[test] - fn check_bag() { - static FLAG: AtomicUsize = ATOMIC_USIZE_INIT; - fn incr() { - FLAG.fetch_add(1, Ordering::Relaxed); - } - - let mut bag = Bag::new(); - assert!(bag.is_empty()); - - for _ in 0..MAX_OBJECTS { - assert!(unsafe { bag.try_push(Deferred::new(incr)).is_ok() }); - assert!(!bag.is_empty()); - assert_eq!(FLAG.load(Ordering::Relaxed), 0); - } - - let result = unsafe { bag.try_push(Deferred::new(incr)) }; - assert!(result.is_err()); - assert!(!bag.is_empty()); - assert_eq!(FLAG.load(Ordering::Relaxed), 0); - - drop(bag); - assert_eq!(FLAG.load(Ordering::Relaxed), MAX_OBJECTS); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/lib.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/lib.rs deleted file mode 100644 index 8662571..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/lib.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! Epoch-based memory reclamation. -//! -//! An interesting problem concurrent collections deal with comes from the remove operation. -//! Suppose that a thread removes an element from a lock-free map, while another thread is reading -//! that same element at the same time. The first thread must wait until the second thread stops -//! reading the element. Only then it is safe to destruct it. -//! -//! Programming languages that come with garbage collectors solve this problem trivially. The -//! garbage collector will destruct the removed element when no thread can hold a reference to it -//! anymore. -//! -//! This crate implements a basic memory reclamation mechanism, which is based on epochs. When an -//! element gets removed from a concurrent collection, it is inserted into a pile of garbage and -//! marked with the current epoch. Every time a thread accesses a collection, it checks the current -//! epoch, attempts to increment it, and destructs some garbage that became so old that no thread -//! can be referencing it anymore. -//! -//! That is the general mechanism behind epoch-based memory reclamation, but the details are a bit -//! more complicated. Anyhow, memory reclamation is designed to be fully automatic and something -//! users of concurrent collections don't have to worry much about. -//! -//! # Pointers -//! -//! Concurrent collections are built using atomic pointers. This module provides [`Atomic`], which -//! is just a shared atomic pointer to a heap-allocated object. Loading an [`Atomic`] yields a -//! [`Shared`], which is an epoch-protected pointer through which the loaded object can be safely -//! read. -//! -//! # Pinning -//! -//! Before an [`Atomic`] can be loaded, a participant must be [`pin`]ned. By pinning a participant -//! we declare that any object that gets removed from now on must not be destructed just -//! yet. Garbage collection of newly removed objects is suspended until the participant gets -//! unpinned. -//! -//! # Garbage -//! -//! Objects that get removed from concurrent collections must be stashed away until all currently -//! pinned participants get unpinned. Such objects can be stored into a thread-local or global -//! storage, where they are kept until the right time for their destruction comes. -//! -//! There is a global shared instance of garbage queue. You can [`defer`] the execution of an -//! arbitrary function until the global epoch is advanced enough. Most notably, concurrent data -//! structures may defer the deallocation of an object. -//! -//! # APIs -//! -//! For majority of use cases, just use the default garbage collector by invoking [`pin`]. If you -//! want to create your own garbage collector, use the [`Collector`] API. -//! -//! [`Atomic`]: struct.Atomic.html -//! [`Collector`]: struct.Collector.html -//! [`Shared`]: struct.Shared.html -//! [`pin`]: fn.pin.html -//! [`defer`]: fn.defer.html - -#![warn(missing_docs)] -#![warn(missing_debug_implementations)] -#![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(feature = "nightly", feature(alloc))] -#![cfg_attr(feature = "nightly", feature(const_fn))] - -#[macro_use] -extern crate cfg_if; -#[cfg(feature = "std")] -extern crate core; - -cfg_if! { - if #[cfg(feature = "nightly")] { - extern crate alloc; - } else { - mod alloc { - extern crate std; - pub use self::std::*; - } - } -} - -extern crate arrayvec; -extern crate crossbeam_utils; -#[macro_use] -extern crate memoffset; -#[macro_use] -extern crate scopeguard; - -mod atomic; -mod collector; -mod deferred; -mod epoch; -mod guard; -mod internal; -mod sync; - -pub use self::atomic::{Atomic, CompareAndSetError, CompareAndSetOrdering, Owned, Pointer, Shared}; -pub use self::collector::{Collector, LocalHandle}; -pub use self::guard::{unprotected, Guard}; - -cfg_if! { - if #[cfg(feature = "std")] { - #[macro_use] - extern crate lazy_static; - - mod default; - pub use self::default::{default_collector, is_pinned, pin}; - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/list.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/list.rs deleted file mode 100644 index ac1b49b..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/list.rs +++ /dev/null @@ -1,477 +0,0 @@ -//! Lock-free intrusive linked list. -//! -//! Ideas from Michael. High Performance Dynamic Lock-Free Hash Tables and List-Based Sets. SPAA -//! 2002. http://dl.acm.org/citation.cfm?id=564870.564881 - -use core::marker::PhantomData; -use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; - -use {unprotected, Atomic, Guard, Shared}; - -/// An entry in a linked list. -/// -/// An Entry is accessed from multiple threads, so it would be beneficial to put it in a different -/// cache-line than thread-local data in terms of performance. -#[derive(Debug)] -pub struct Entry { - /// The next entry in the linked list. - /// If the tag is 1, this entry is marked as deleted. - next: Atomic, -} - -/// Implementing this trait asserts that the type `T` can be used as an element in the intrusive -/// linked list defined in this module. `T` has to contain (or otherwise be linked to) an instance -/// of `Entry`. -/// -/// # Example -/// -/// ```ignore -/// struct A { -/// entry: Entry, -/// data: usize, -/// } -/// -/// impl IsElement
for A { -/// fn entry_of(a: &A) -> &Entry { -/// let entry_ptr = ((a as usize) + offset_of!(A, entry)) as *const Entry; -/// unsafe { &*entry_ptr } -/// } -/// -/// unsafe fn element_of(entry: &Entry) -> &T { -/// let elem_ptr = ((entry as usize) - offset_of!(A, entry)) as *const T; -/// &*elem_ptr -/// } -/// -/// unsafe fn finalize(entry: &Entry) { -/// let elem = Self::element_of(entry); -/// drop(Box::from_raw(elem as *const A as *mut A)); -/// } -/// } -/// ``` -/// -/// This trait is implemented on a type separate from `T` (although it can be just `T`), because -/// one type might be placeable into multiple lists, in which case it would require multiple -/// implementations of `IsElement`. In such cases, each struct implementing `IsElement` -/// represents a distinct `Entry` in `T`. -/// -/// For example, we can insert the following struct into two lists using `entry1` for one -/// and `entry2` for the other: -/// -/// ```ignore -/// struct B { -/// entry1: Entry, -/// entry2: Entry, -/// data: usize, -/// } -/// ``` -/// -pub trait IsElement { - /// Returns a reference to this element's `Entry`. - fn entry_of(&T) -> &Entry; - - /// Given a reference to an element's entry, returns that element. - /// - /// ```ignore - /// let elem = ListElement::new(); - /// assert_eq!(elem.entry_of(), - /// unsafe { ListElement::element_of(elem.entry_of()) } ); - /// ``` - /// - /// # Safety - /// The caller has to guarantee that the `Entry` it - /// is called with was retrieved from an instance of the element type (`T`). - unsafe fn element_of(&Entry) -> &T; - - /// Deallocates the whole element given its `Entry`. This is called when the list - /// is ready to actually free the element. - /// - /// # Safety - /// The caller has to guarantee that the `Entry` it - /// is called with was retrieved from an instance of the element type (`T`). - unsafe fn finalize(&Entry); -} - -/// A lock-free, intrusive linked list of type `T`. -#[derive(Debug)] -pub struct List = T> { - /// The head of the linked list. - head: Atomic, - - /// The phantom data for using `T` and `C`. - _marker: PhantomData<(T, C)>, -} - -/// An iterator used for retrieving values from the list. -pub struct Iter<'g, T: 'g, C: IsElement> { - /// The guard that protects the iteration. - guard: &'g Guard, - - /// Pointer from the predecessor to the current entry. - pred: &'g Atomic, - - /// The current entry. - curr: Shared<'g, Entry>, - - /// The list head, needed for restarting iteration. - head: &'g Atomic, - - /// Logically, we store a borrow of an instance of `T` and - /// use the type information from `C`. - _marker: PhantomData<(&'g T, C)>, -} - -/// An error that occurs during iteration over the list. -#[derive(PartialEq, Debug)] -pub enum IterError { - /// A concurrent thread modified the state of the list at the same place that this iterator - /// was inspecting. Subsequent iteration will restart from the beginning of the list. - Stalled, -} - -impl Default for Entry { - /// Returns the empty entry. - fn default() -> Self { - Self { - next: Atomic::null(), - } - } -} - -impl Entry { - /// Marks this entry as deleted, deferring the actual deallocation to a later iteration. - /// - /// # Safety - /// - /// The entry should be a member of a linked list, and it should not have been deleted. - /// It should be safe to call `C::finalize` on the entry after the `guard` is dropped, where `C` - /// is the associated helper for the linked list. - pub unsafe fn delete(&self, guard: &Guard) { - self.next.fetch_or(1, Release, guard); - } -} - -impl> List { - /// Returns a new, empty linked list. - pub fn new() -> Self { - Self { - head: Atomic::null(), - _marker: PhantomData, - } - } - - /// Inserts `entry` into the head of the list. - /// - /// # Safety - /// - /// You should guarantee that: - /// - /// - `container` is not null - /// - `container` is immovable, e.g. inside a `Box` - /// - the same `Entry` is not inserted more than once - /// - the inserted object will be removed before the list is dropped - pub unsafe fn insert<'g>(&'g self, container: Shared<'g, T>, guard: &'g Guard) { - // Insert right after head, i.e. at the beginning of the list. - let to = &self.head; - // Get the intrusively stored Entry of the new element to insert. - let entry: &Entry = C::entry_of(container.deref()); - // Make a Shared ptr to that Entry. - let entry_ptr = Shared::from(entry as *const _); - // Read the current successor of where we want to insert. - let mut next = to.load(Relaxed, guard); - - loop { - // Set the Entry of the to-be-inserted element to point to the previous successor of - // `to`. - entry.next.store(next, Relaxed); - match to.compare_and_set_weak(next, entry_ptr, Release, guard) { - Ok(_) => break, - // We lost the race or weak CAS failed spuriously. Update the successor and try - // again. - Err(err) => next = err.current, - } - } - } - - /// Returns an iterator over all objects. - /// - /// # Caveat - /// - /// Every object that is inserted at the moment this function is called and persists at least - /// until the end of iteration will be returned. Since this iterator traverses a lock-free - /// linked list that may be concurrently modified, some additional caveats apply: - /// - /// 1. If a new object is inserted during iteration, it may or may not be returned. - /// 2. If an object is deleted during iteration, it may or may not be returned. - /// 3. The iteration may be aborted when it lost in a race condition. In this case, the winning - /// thread will continue to iterate over the same list. - pub fn iter<'g>(&'g self, guard: &'g Guard) -> Iter<'g, T, C> { - Iter { - guard, - pred: &self.head, - curr: self.head.load(Acquire, guard), - head: &self.head, - _marker: PhantomData, - } - } -} - -impl> Drop for List { - fn drop(&mut self) { - unsafe { - let guard = &unprotected(); - let mut curr = self.head.load(Relaxed, guard); - while let Some(c) = curr.as_ref() { - let succ = c.next.load(Relaxed, guard); - // Verify that all elements have been removed from the list. - assert_eq!(succ.tag(), 1); - - C::finalize(curr.deref()); - curr = succ; - } - } - } -} - -impl<'g, T: 'g, C: IsElement> Iterator for Iter<'g, T, C> { - type Item = Result<&'g T, IterError>; - - fn next(&mut self) -> Option { - while let Some(c) = unsafe { self.curr.as_ref() } { - let succ = c.next.load(Acquire, self.guard); - - if succ.tag() == 1 { - // This entry was removed. Try unlinking it from the list. - let succ = succ.with_tag(0); - - // The tag should never be zero, because removing a node after a logically deleted - // node leaves the list in an invalid state. - debug_assert!(self.curr.tag() == 0); - - match self - .pred - .compare_and_set(self.curr, succ, Acquire, self.guard) - { - Ok(_) => { - // We succeeded in unlinking this element from the list, so we have to - // schedule deallocation. Deferred drop is okay, because `list.delete()` - // can only be called if `T: 'static`. - unsafe { - let p = self.curr; - self.guard.defer_unchecked(move || C::finalize(p.deref())); - } - - // Move over the removed by only advancing `curr`, not `pred`. - self.curr = succ; - continue; - } - Err(_) => { - // A concurrent thread modified the predecessor node. Since it might've - // been deleted, we need to restart from `head`. - self.pred = self.head; - self.curr = self.head.load(Acquire, self.guard); - - return Some(Err(IterError::Stalled)); - } - } - } - - // Move one step forward. - self.pred = &c.next; - self.curr = succ; - - return Some(Ok(unsafe { C::element_of(c) })); - } - - // We reached the end of the list. - None - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crossbeam_utils::thread; - use std::sync::Barrier; - use {Collector, Owned}; - - impl IsElement for Entry { - fn entry_of(entry: &Entry) -> &Entry { - entry - } - - unsafe fn element_of(entry: &Entry) -> &Entry { - entry - } - - unsafe fn finalize(entry: &Entry) { - drop(Box::from_raw(entry as *const Entry as *mut Entry)); - } - } - - /// Checks whether the list retains inserted elements - /// and returns them in the correct order. - #[test] - fn insert() { - let collector = Collector::new(); - let handle = collector.register(); - let guard = handle.pin(); - - let l: List = List::new(); - - let e1 = Owned::new(Entry::default()).into_shared(&guard); - let e2 = Owned::new(Entry::default()).into_shared(&guard); - let e3 = Owned::new(Entry::default()).into_shared(&guard); - - unsafe { - l.insert(e1, &guard); - l.insert(e2, &guard); - l.insert(e3, &guard); - } - - let mut iter = l.iter(&guard); - let maybe_e3 = iter.next(); - assert!(maybe_e3.is_some()); - assert!(maybe_e3.unwrap().unwrap() as *const Entry == e3.as_raw()); - let maybe_e2 = iter.next(); - assert!(maybe_e2.is_some()); - assert!(maybe_e2.unwrap().unwrap() as *const Entry == e2.as_raw()); - let maybe_e1 = iter.next(); - assert!(maybe_e1.is_some()); - assert!(maybe_e1.unwrap().unwrap() as *const Entry == e1.as_raw()); - assert!(iter.next().is_none()); - - unsafe { - e1.as_ref().unwrap().delete(&guard); - e2.as_ref().unwrap().delete(&guard); - e3.as_ref().unwrap().delete(&guard); - } - } - - /// Checks whether elements can be removed from the list and whether - /// the correct elements are removed. - #[test] - fn delete() { - let collector = Collector::new(); - let handle = collector.register(); - let guard = handle.pin(); - - let l: List = List::new(); - - let e1 = Owned::new(Entry::default()).into_shared(&guard); - let e2 = Owned::new(Entry::default()).into_shared(&guard); - let e3 = Owned::new(Entry::default()).into_shared(&guard); - unsafe { - l.insert(e1, &guard); - l.insert(e2, &guard); - l.insert(e3, &guard); - e2.as_ref().unwrap().delete(&guard); - } - - let mut iter = l.iter(&guard); - let maybe_e3 = iter.next(); - assert!(maybe_e3.is_some()); - assert!(maybe_e3.unwrap().unwrap() as *const Entry == e3.as_raw()); - let maybe_e1 = iter.next(); - assert!(maybe_e1.is_some()); - assert!(maybe_e1.unwrap().unwrap() as *const Entry == e1.as_raw()); - assert!(iter.next().is_none()); - - unsafe { - e1.as_ref().unwrap().delete(&guard); - e3.as_ref().unwrap().delete(&guard); - } - - let mut iter = l.iter(&guard); - assert!(iter.next().is_none()); - } - - const THREADS: usize = 8; - const ITERS: usize = 512; - - /// Contends the list on insert and delete operations to make sure they can run concurrently. - #[test] - fn insert_delete_multi() { - let collector = Collector::new(); - - let l: List = List::new(); - let b = Barrier::new(THREADS); - - thread::scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - b.wait(); - - let handle = collector.register(); - let guard: Guard = handle.pin(); - let mut v = Vec::with_capacity(ITERS); - - for _ in 0..ITERS { - let e = Owned::new(Entry::default()).into_shared(&guard); - v.push(e); - unsafe { - l.insert(e, &guard); - } - } - - for e in v { - unsafe { - e.as_ref().unwrap().delete(&guard); - } - } - }); - } - }).unwrap(); - - let handle = collector.register(); - let guard = handle.pin(); - - let mut iter = l.iter(&guard); - assert!(iter.next().is_none()); - } - - /// Contends the list on iteration to make sure that it can be iterated over concurrently. - #[test] - fn iter_multi() { - let collector = Collector::new(); - - let l: List = List::new(); - let b = Barrier::new(THREADS); - - thread::scope(|s| { - for _ in 0..THREADS { - s.spawn(|_| { - b.wait(); - - let handle = collector.register(); - let guard: Guard = handle.pin(); - let mut v = Vec::with_capacity(ITERS); - - for _ in 0..ITERS { - let e = Owned::new(Entry::default()).into_shared(&guard); - v.push(e); - unsafe { - l.insert(e, &guard); - } - } - - let mut iter = l.iter(&guard); - for _ in 0..ITERS { - assert!(iter.next().is_some()); - } - - for e in v { - unsafe { - e.as_ref().unwrap().delete(&guard); - } - } - }); - } - }).unwrap(); - - let handle = collector.register(); - let guard = handle.pin(); - - let mut iter = l.iter(&guard); - assert!(iter.next().is_none()); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/queue.rs b/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/queue.rs deleted file mode 100644 index 9c3372f..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/queue.rs +++ /dev/null @@ -1,434 +0,0 @@ -//! Michael-Scott lock-free queue. -//! -//! Usable with any number of producers and consumers. -//! -//! Michael and Scott. Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue -//! Algorithms. PODC 1996. http://dl.acm.org/citation.cfm?id=248106 - -use core::mem::{self, ManuallyDrop}; -use core::ptr; -use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; - -use crossbeam_utils::CachePadded; - -use {unprotected, Atomic, Guard, Owned, Shared}; - -// The representation here is a singly-linked list, with a sentinel node at the front. In general -// the `tail` pointer may lag behind the actual tail. Non-sentinel nodes are either all `Data` or -// all `Blocked` (requests for data from blocked threads). -#[derive(Debug)] -pub struct Queue { - head: CachePadded>>, - tail: CachePadded>>, -} - -#[derive(Debug)] -struct Node { - /// The slot in which a value of type `T` can be stored. - /// - /// The type of `data` is `ManuallyDrop` because a `Node` doesn't always contain a `T`. - /// For example, the sentinel node in a queue never contains a value: its slot is always empty. - /// Other nodes start their life with a push operation and contain a value until it gets popped - /// out. After that such empty nodes get added to the collector for destruction. - data: ManuallyDrop, - - next: Atomic>, -} - -// Any particular `T` should never be accessed concurrently, so no need for `Sync`. -unsafe impl Sync for Queue {} -unsafe impl Send for Queue {} - -impl Queue { - /// Create a new, empty queue. - pub fn new() -> Queue { - let q = Queue { - head: CachePadded::new(Atomic::null()), - tail: CachePadded::new(Atomic::null()), - }; - let sentinel = Owned::new(Node { - data: unsafe { mem::uninitialized() }, - next: Atomic::null(), - }); - unsafe { - let guard = &unprotected(); - let sentinel = sentinel.into_shared(guard); - q.head.store(sentinel, Relaxed); - q.tail.store(sentinel, Relaxed); - q - } - } - - /// Attempts to atomically place `n` into the `next` pointer of `onto`, and returns `true` on - /// success. The queue's `tail` pointer may be updated. - #[inline(always)] - fn push_internal(&self, onto: Shared>, new: Shared>, guard: &Guard) -> bool { - // is `onto` the actual tail? - let o = unsafe { onto.deref() }; - let next = o.next.load(Acquire, guard); - if unsafe { next.as_ref().is_some() } { - // if not, try to "help" by moving the tail pointer forward - let _ = self.tail.compare_and_set(onto, next, Release, guard); - false - } else { - // looks like the actual tail; attempt to link in `n` - let result = o - .next - .compare_and_set(Shared::null(), new, Release, guard) - .is_ok(); - if result { - // try to move the tail pointer forward - let _ = self.tail.compare_and_set(onto, new, Release, guard); - } - result - } - } - - /// Adds `t` to the back of the queue, possibly waking up threads blocked on `pop`. - pub fn push(&self, t: T, guard: &Guard) { - let new = Owned::new(Node { - data: ManuallyDrop::new(t), - next: Atomic::null(), - }); - let new = Owned::into_shared(new, guard); - - loop { - // We push onto the tail, so we'll start optimistically by looking there first. - let tail = self.tail.load(Acquire, guard); - - // Attempt to push onto the `tail` snapshot; fails if `tail.next` has changed. - if self.push_internal(tail, new, guard) { - break; - } - } - } - - /// Attempts to pop a data node. `Ok(None)` if queue is empty; `Err(())` if lost race to pop. - #[inline(always)] - fn pop_internal(&self, guard: &Guard) -> Result, ()> { - let head = self.head.load(Acquire, guard); - let h = unsafe { head.deref() }; - let next = h.next.load(Acquire, guard); - match unsafe { next.as_ref() } { - Some(n) => unsafe { - self.head - .compare_and_set(head, next, Release, guard) - .map(|_| { - guard.defer_destroy(head); - Some(ManuallyDrop::into_inner(ptr::read(&n.data))) - }).map_err(|_| ()) - }, - None => Ok(None), - } - } - - /// Attempts to pop a data node, if the data satisfies the given condition. `Ok(None)` if queue - /// is empty or the data does not satisfy the condition; `Err(())` if lost race to pop. - #[inline(always)] - fn pop_if_internal(&self, condition: F, guard: &Guard) -> Result, ()> - where - T: Sync, - F: Fn(&T) -> bool, - { - let head = self.head.load(Acquire, guard); - let h = unsafe { head.deref() }; - let next = h.next.load(Acquire, guard); - match unsafe { next.as_ref() } { - Some(n) if condition(&n.data) => unsafe { - self.head - .compare_and_set(head, next, Release, guard) - .map(|_| { - guard.defer_destroy(head); - Some(ManuallyDrop::into_inner(ptr::read(&n.data))) - }).map_err(|_| ()) - }, - None | Some(_) => Ok(None), - } - } - - /// Attempts to dequeue from the front. - /// - /// Returns `None` if the queue is observed to be empty. - pub fn try_pop(&self, guard: &Guard) -> Option { - loop { - if let Ok(head) = self.pop_internal(guard) { - return head; - } - } - } - - /// Attempts to dequeue from the front, if the item satisfies the given condition. - /// - /// Returns `None` if the queue is observed to be empty, or the head does not satisfy the given - /// condition. - pub fn try_pop_if(&self, condition: F, guard: &Guard) -> Option - where - T: Sync, - F: Fn(&T) -> bool, - { - loop { - if let Ok(head) = self.pop_if_internal(&condition, guard) { - return head; - } - } - } -} - -impl Drop for Queue { - fn drop(&mut self) { - unsafe { - let guard = &unprotected(); - - while let Some(_) = self.try_pop(guard) {} - - // Destroy the remaining sentinel node. - let sentinel = self.head.load(Relaxed, guard); - drop(sentinel.into_owned()); - } - } -} - -#[cfg(test)] -mod test { - use super::*; - use crossbeam_utils::thread; - use pin; - - struct Queue { - queue: super::Queue, - } - - impl Queue { - pub fn new() -> Queue { - Queue { - queue: super::Queue::new(), - } - } - - pub fn push(&self, t: T) { - let guard = &pin(); - self.queue.push(t, guard); - } - - pub fn is_empty(&self) -> bool { - let guard = &pin(); - let head = self.queue.head.load(Acquire, guard); - let h = unsafe { head.deref() }; - h.next.load(Acquire, guard).is_null() - } - - pub fn try_pop(&self) -> Option { - let guard = &pin(); - self.queue.try_pop(guard) - } - - pub fn pop(&self) -> T { - loop { - match self.try_pop() { - None => continue, - Some(t) => return t, - } - } - } - } - - const CONC_COUNT: i64 = 1000000; - - #[test] - fn push_try_pop_1() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(37)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_2() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - q.push(37); - q.push(48); - assert_eq!(q.try_pop(), Some(37)); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(48)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_seq() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.try_pop(), Some(i)); - } - assert!(q.is_empty()); - } - - #[test] - fn push_pop_1() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.pop(), 37); - assert!(q.is_empty()); - } - - #[test] - fn push_pop_2() { - let q: Queue = Queue::new(); - q.push(37); - q.push(48); - assert_eq!(q.pop(), 37); - assert_eq!(q.pop(), 48); - } - - #[test] - fn push_pop_many_seq() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.pop(), i); - } - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_spsc() { - let q: Queue = Queue::new(); - assert!(q.is_empty()); - - thread::scope(|scope| { - scope.spawn(|_| { - let mut next = 0; - - while next < CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert_eq!(elem, next); - next += 1; - } - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }).unwrap(); - } - - #[test] - fn push_try_pop_many_spmc() { - fn recv(_t: i32, q: &Queue) { - let mut cur = -1; - for _i in 0..CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert!(elem > cur); - cur = elem; - - if cur == CONC_COUNT - 1 { - break; - } - } - } - } - - let q: Queue = Queue::new(); - assert!(q.is_empty()); - thread::scope(|scope| { - for i in 0..3 { - scope.spawn(|_| recv(i, &q)); - } - - scope.spawn(|_| { - for i in 0..CONC_COUNT { - q.push(i); - } - }); - }).unwrap(); - } - - #[test] - fn push_try_pop_many_mpmc() { - enum LR { - Left(i64), - Right(i64), - } - - let q: Queue = Queue::new(); - assert!(q.is_empty()); - - thread::scope(|scope| { - for _t in 0..2 { - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Left(i)) - } - }); - scope.spawn(|_| { - for i in CONC_COUNT - 1..CONC_COUNT { - q.push(LR::Right(i)) - } - }); - scope.spawn(|_| { - let mut vl = vec![]; - let mut vr = vec![]; - for _i in 0..CONC_COUNT { - match q.try_pop() { - Some(LR::Left(x)) => vl.push(x), - Some(LR::Right(x)) => vr.push(x), - _ => {} - } - } - - let mut vl2 = vl.clone(); - let mut vr2 = vr.clone(); - vl2.sort(); - vr2.sort(); - - assert_eq!(vl, vl2); - assert_eq!(vr, vr2); - }); - } - }).unwrap(); - } - - #[test] - fn push_pop_many_spsc() { - let q: Queue = Queue::new(); - - thread::scope(|scope| { - scope.spawn(|_| { - let mut next = 0; - while next < CONC_COUNT { - assert_eq!(q.pop(), next); - next += 1; - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }).unwrap(); - assert!(q.is_empty()); - } - - #[test] - fn is_empty_dont_pop() { - let q: Queue = Queue::new(); - q.push(20); - q.push(20); - assert!(!q.is_empty()); - assert!(!q.is_empty()); - assert!(q.try_pop().is_some()); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-epoch-0.7.2/.cargo-checksum.json deleted file mode 100644 index 81aef2a..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"fdffb6df6ae4827aa7c6543788a474ed47d96eb0b1e9d6f4d41ee922f921e9a9","Cargo.toml":"abb9a5a47d688f63ee2f82fa62900d357a8cce329f98a615a5a5a6e8c4516d41","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"2f095ef276fadd1bc42e4ea16c6f9a8d098ff3c39f1e72a899ae02326bcf14a5","benches/defer.rs":"a4b17e7b96bef2f268c76925cfa58744b81504146426fab6f781ff0b2f666f2b","benches/flush.rs":"1d93ac40cb78bf2c55332869d4f7d1b283571bff4a0c6dbe245f02dd65e8e1d8","benches/pin.rs":"dd937ecfc8d7353995d438a7f4be383e91c002e9ee6acd4caa703bb340c97383","examples/sanitize.rs":"90f80709cd620e994f699d84ab9ce88f8552500d08bac64d60def5792460495a","examples/treiber_stack.rs":"b5d3bafa6d57af435b00d04145572a51ea871f64ff2c23ba544054c4c4145d65","src/atomic.rs":"8fc50bf82b298298b6512311df5f6da2c5c909d0b6eafa7776850538e65045e6","src/collector.rs":"a783049d3cb22989ec978366fd865f31562b0acbfbd0bc9ff9b600ceaa5ffa87","src/default.rs":"6afda8fd141ad594bed62baeb73f2e97c5ef33b051969a542bb908946fe39dd1","src/deferred.rs":"d5ace4be72e926cedb699cd19ae4076bbe87d795d650aa68f264106e6ff15bee","src/epoch.rs":"76dd63356d5bc52e741883d39abb636e4ccb04d20499fb2a0ce797bb81aa4e91","src/guard.rs":"1d90d690b02ee735263e845827f720be44faea871852731dd8444b92796f1539","src/internal.rs":"9ff5b0fa05cbfa550ef9eaf8bd2025445a097d9da59efb7b976580dd0a09a2ff","src/lib.rs":"6eaea9a81b55844c1fd084924b8b7f750fed33aae2a75e2d5f430ed054092a44","src/sync/list.rs":"43e09e9cf79d7cf95b5110051de9dd47ab7761e3bc90ea3be16c4cbabce6d4be","src/sync/mod.rs":"2da979ca3a2293f7626a2e6a9ab2fad758d92e3d2bed6cc712ef59eeeea87eab","src/sync/queue.rs":"34991ba75fbc8ba3494bf91559727feb1919f9f39b3c67d6e2aca82376ef9d3c"},"package":"fedcd6772e37f3da2a9af9bf12ebe046c0dfe657992377b4df982a2b54cd37a9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/default.rs b/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/default.rs deleted file mode 100644 index 734a624..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/default.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! The default garbage collector. -//! -//! For each thread, a participant is lazily initialized on its first use, when the current thread -//! is registered in the default collector. If initialized, the thread's participant will get -//! destructed on thread exit, which in turn unregisters the thread. - -use collector::{Collector, LocalHandle}; -use guard::Guard; - -lazy_static! { - /// The global data for the default garbage collector. - static ref COLLECTOR: Collector = Collector::new(); -} - -thread_local! { - /// The per-thread participant for the default garbage collector. - static HANDLE: LocalHandle = COLLECTOR.register(); -} - -/// Pins the current thread. -#[inline] -pub fn pin() -> Guard { - with_handle(|handle| handle.pin()) -} - -/// Returns `true` if the current thread is pinned. -#[inline] -pub fn is_pinned() -> bool { - with_handle(|handle| handle.is_pinned()) -} - -/// Returns the default global collector. -pub fn default_collector() -> &'static Collector { - &COLLECTOR -} - -#[inline] -fn with_handle(mut f: F) -> R -where - F: FnMut(&LocalHandle) -> R, -{ - HANDLE - .try_with(|h| f(h)) - .unwrap_or_else(|_| f(&COLLECTOR.register())) -} - -#[cfg(test)] -mod tests { - use crossbeam_utils::thread; - - #[test] - fn pin_while_exiting() { - struct Foo; - - impl Drop for Foo { - fn drop(&mut self) { - // Pin after `HANDLE` has been dropped. This must not panic. - super::pin(); - } - } - - thread_local! { - static FOO: Foo = Foo; - } - - thread::scope(|scope| { - scope.spawn(|_| { - // Initialize `FOO` and then `HANDLE`. - FOO.with(|_| ()); - super::pin(); - // At thread exit, `HANDLE` gets dropped first and `FOO` second. - }); - }).unwrap(); - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/epoch.rs b/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/epoch.rs deleted file mode 100644 index e7759d9..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/epoch.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! The global epoch -//! -//! The last bit in this number is unused and is always zero. Every so often the global epoch is -//! incremented, i.e. we say it "advances". A pinned participant may advance the global epoch only -//! if all currently pinned participants have been pinned in the current epoch. -//! -//! If an object became garbage in some epoch, then we can be sure that after two advancements no -//! participant will hold a reference to it. That is the crux of safe memory reclamation. - -use core::sync::atomic::{AtomicUsize, Ordering}; - -/// An epoch that can be marked as pinned or unpinned. -/// -/// Internally, the epoch is represented as an integer that wraps around at some unspecified point -/// and a flag that represents whether it is pinned or unpinned. -#[derive(Copy, Clone, Default, Debug, Eq, PartialEq)] -pub struct Epoch { - /// The least significant bit is set if pinned. The rest of the bits hold the epoch. - data: usize, -} - -impl Epoch { - /// Returns the starting epoch in unpinned state. - #[inline] - pub fn starting() -> Self { - Self::default() - } - - /// Returns the number of epochs `self` is ahead of `rhs`. - /// - /// Internally, epochs are represented as numbers in the range `(isize::MIN / 2) .. (isize::MAX - /// / 2)`, so the returned distance will be in the same interval. - pub fn wrapping_sub(self, rhs: Self) -> isize { - // The result is the same with `(self.data & !1).wrapping_sub(rhs.data & !1) as isize >> 1`, - // because the possible difference of LSB in `(self.data & !1).wrapping_sub(rhs.data & !1)` - // will be ignored in the shift operation. - self.data.wrapping_sub(rhs.data & !1) as isize >> 1 - } - - /// Returns `true` if the epoch is marked as pinned. - #[inline] - pub fn is_pinned(self) -> bool { - (self.data & 1) == 1 - } - - /// Returns the same epoch, but marked as pinned. - #[inline] - pub fn pinned(self) -> Epoch { - Epoch { - data: self.data | 1, - } - } - - /// Returns the same epoch, but marked as unpinned. - #[inline] - pub fn unpinned(self) -> Epoch { - Epoch { - data: self.data & !1, - } - } - - /// Returns the successor epoch. - /// - /// The returned epoch will be marked as pinned only if the previous one was as well. - #[inline] - pub fn successor(self) -> Epoch { - Epoch { - data: self.data.wrapping_add(2), - } - } -} - -/// An atomic value that holds an `Epoch`. -#[derive(Default, Debug)] -pub struct AtomicEpoch { - /// Since `Epoch` is just a wrapper around `usize`, an `AtomicEpoch` is similarly represented - /// using an `AtomicUsize`. - data: AtomicUsize, -} - -impl AtomicEpoch { - /// Creates a new atomic epoch. - #[inline] - pub fn new(epoch: Epoch) -> Self { - let data = AtomicUsize::new(epoch.data); - AtomicEpoch { data } - } - - /// Loads a value from the atomic epoch. - #[inline] - pub fn load(&self, ord: Ordering) -> Epoch { - Epoch { - data: self.data.load(ord), - } - } - - /// Stores a value into the atomic epoch. - #[inline] - pub fn store(&self, epoch: Epoch, ord: Ordering) { - self.data.store(epoch.data, ord); - } - - /// Stores a value into the atomic epoch if the current value is the same as `current`. - /// - /// The return value is always the previous value. If it is equal to `current`, then the value - /// is updated. - /// - /// The `Ordering` argument describes the memory ordering of this operation. - #[inline] - pub fn compare_and_swap(&self, current: Epoch, new: Epoch, ord: Ordering) -> Epoch { - let data = self.data.compare_and_swap(current.data, new.data, ord); - Epoch { data } - } -} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/mod.rs b/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/mod.rs deleted file mode 100644 index f8eb259..0000000 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Synchronization primitives. - -pub mod list; -pub mod queue; diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.8.2/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/.cargo-checksum.json new file mode 100644 index 0000000..231351a --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"6f63ac1fc542b3aac4b43cdcd4c1ec549e2afb50c03836d3ca10468531684b5f","Cargo.lock":"cde1950d5785b0962e84cd5e98ce6bbbc981c606c2e73601f060d488ec2bca5f","Cargo.toml":"212414f7fad97f2b0eabff851d380ea75d043d3b16266a54e4724da588cd648d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"30bed3b95612935f87903eeb37dfd09e133e4c064a66eb8b5681eaf97128c8e9","benches/defer.rs":"a4b17e7b96bef2f268c76925cfa58744b81504146426fab6f781ff0b2f666f2b","benches/flush.rs":"1d93ac40cb78bf2c55332869d4f7d1b283571bff4a0c6dbe245f02dd65e8e1d8","benches/pin.rs":"dd937ecfc8d7353995d438a7f4be383e91c002e9ee6acd4caa703bb340c97383","build.rs":"825c47ae19028dc4b28101ec71c04e7e41b8b185f6ecbeacee223596524c86ad","examples/sanitize.rs":"90f80709cd620e994f699d84ab9ce88f8552500d08bac64d60def5792460495a","examples/treiber_stack.rs":"b5d3bafa6d57af435b00d04145572a51ea871f64ff2c23ba544054c4c4145d65","src/atomic.rs":"53c29c8df6a90e2cd3d7747f7ebfe604087966c8ea6473ff2593bdd495f43951","src/collector.rs":"a783049d3cb22989ec978366fd865f31562b0acbfbd0bc9ff9b600ceaa5ffa87","src/default.rs":"7fec6d381ae0efab8c1539c78588f99b8fcd6551ac67740fcfd45be3405ca53a","src/deferred.rs":"2793f8a5d271e7a787f7e99bdff7b07488742704bd47721459f0bb5085e6b3ea","src/epoch.rs":"76dd63356d5bc52e741883d39abb636e4ccb04d20499fb2a0ce797bb81aa4e91","src/guard.rs":"486efbc061b7f402f4c8a96abd1889aff4b28eb10347b65e538c39d539d919ad","src/internal.rs":"82030dc0cdc30741b2ca840455d2074e9fc0b9186c043d18bcf54bab093ce083","src/lib.rs":"c6c94853766d307eb36f75e1f4feabe2b4b13659d20e11ea9b82b6472363ce9f","src/sync/list.rs":"ef59984162102d01279f6eb7ded52d923933287dd4d7785b758b049768a3c118","src/sync/mod.rs":"2da979ca3a2293f7626a2e6a9ab2fad758d92e3d2bed6cc712ef59eeeea87eab","src/sync/queue.rs":"89390788a53ee932dcd92221cd2a8db25fd52a1e0b2b1fb9bd4230dec9eadcac"},"package":"058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/BUILD b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/BUILD similarity index 85% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/BUILD rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/BUILD index 8cdc6d2..f2c51d5 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/BUILD +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/BUILD @@ -23,6 +23,7 @@ load( ) +# Unsupported target "build-script-build" with type "custom-build" omitted rust_library( name = "crossbeam_epoch", @@ -31,17 +32,17 @@ rust_library( edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/arrayvec-0.4.12:arrayvec", "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", - "//third_party/cargo/vendor/crossbeam-utils-0.6.6:crossbeam_utils", + "//third_party/cargo/vendor/crossbeam-utils-0.7.2:crossbeam_utils", "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", + "//third_party/cargo/vendor/maybe-uninit-2.0.0:maybe_uninit", "//third_party/cargo/vendor/memoffset-0.5.4:memoffset", "//third_party/cargo/vendor/scopeguard-1.1.0:scopeguard", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.7.2", + version = "0.8.2", crate_features = [ "default", "lazy_static", diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/CHANGELOG.md similarity index 77% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/CHANGELOG.md rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/CHANGELOG.md index f47f7b8..07e64ef 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/CHANGELOG.md +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/CHANGELOG.md @@ -1,3 +1,22 @@ +# Version 0.8.2 + +- Fix bug in release (yanking 0.8.1) + +# Version 0.8.1 + +- Bump `autocfg` dependency to version 1.0. (#460) +- Reduce stall in list iteration. (#376) +- Stop stealing from the same deque. (#448) +- Fix unsoundness issues by adopting `MaybeUninit`. (#458) +- Fix use-after-free in lock-free queue. (#466) + +# Version 0.8.0 + +- Bump the minimum required version to 1.28. +- Fix breakage with nightly feature due to rust-lang/rust#65214. +- Make `Atomic::null()` const function at 1.31+. +- Bump `crossbeam-utils` to `0.7`. + # Version 0.7.2 - Add `Atomic::into_owned()`. diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.lock b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.lock new file mode 100644 index 0000000..d3f8334 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.lock @@ -0,0 +1,261 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "autocfg" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.2" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-cprng" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "memoffset" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_jitter 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_chacha" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand_hc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_isaac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_jitter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_os" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_pcg" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_xorshift" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rdrand" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" +"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" +"checksum fuchsia-cprng 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +"checksum libc 0.2.67 (registry+https://github.com/rust-lang/crates.io-index)" = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" +"checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" +"checksum memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9" +"checksum rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" +"checksum rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" +"checksum rand_core 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" +"checksum rand_core 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" +"checksum rand_hc 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" +"checksum rand_isaac 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" +"checksum rand_jitter 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" +"checksum rand_os 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" +"checksum rand_pcg 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" +"checksum rand_xorshift 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" +"checksum rdrand 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" +"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +"checksum scopeguard 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/Cargo.toml b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.toml similarity index 89% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/Cargo.toml rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.toml index 93de822..7d5c094 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/Cargo.toml +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "crossbeam-epoch" -version = "0.7.2" +version = "0.8.2" authors = ["The Crossbeam Project Developers"] description = "Epoch-based garbage collection" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch" @@ -22,21 +22,20 @@ keywords = ["lock-free", "rcu", "atomic", "garbage"] categories = ["concurrency", "memory-management", "no-std"] license = "MIT/Apache-2.0" repository = "https://github.com/crossbeam-rs/crossbeam" -[dependencies.arrayvec] -version = "0.4" -default-features = false - [dependencies.cfg-if] version = "0.1.2" [dependencies.crossbeam-utils] -version = "0.6" +version = "0.7" default-features = false [dependencies.lazy_static] version = "1" optional = true +[dependencies.maybe-uninit] +version = "2.0.0" + [dependencies.memoffset] version = "0.5" @@ -45,10 +44,12 @@ version = "1" default-features = false [dev-dependencies.rand] version = "0.6" +[build-dependencies.autocfg] +version = "1" [features] alloc = ["crossbeam-utils/alloc"] default = ["std"] -nightly = ["crossbeam-utils/nightly", "arrayvec/use_union"] +nightly = ["crossbeam-utils/nightly"] sanitize = [] std = ["crossbeam-utils/std", "lazy_static"] diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.6.1/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/LICENSE-APACHE diff --git a/third_party/cargo/vendor/crossbeam-0.5.0/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/LICENSE-MIT similarity index 93% rename from third_party/cargo/vendor/crossbeam-0.5.0/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/LICENSE-MIT index e69282e..068d491 100644 --- a/third_party/cargo/vendor/crossbeam-0.5.0/LICENSE-MIT +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/LICENSE-MIT @@ -1,4 +1,6 @@ -Copyright (c) 2015 The Rust Project Developers +The MIT License (MIT) + +Copyright (c) 2019 The Crossbeam Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/README.md b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/README.md similarity index 89% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/README.md rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/README.md index a1fb414..79b4c77 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/README.md +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam-epoch) https://crates.io/crates/crossbeam-epoch) [![Documentation](https://docs.rs/crossbeam-epoch/badge.svg)]( https://docs.rs/crossbeam-epoch) -[![Rust 1.26+](https://img.shields.io/badge/rust-1.26+-lightgray.svg)]( +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/BBYwKq) @@ -28,7 +28,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -crossbeam-epoch = "0.7" +crossbeam-epoch = "0.8" ``` Next, add this to your crate: @@ -37,6 +37,10 @@ Next, add this to your crate: extern crate crossbeam_epoch as epoch; ``` +## Compatibility + +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. + ## License Licensed under either of diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/defer.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/defer.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/defer.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/defer.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/flush.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/flush.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/flush.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/flush.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/pin.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/pin.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/benches/pin.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/benches/pin.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.8.2/build.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/build.rs new file mode 100644 index 0000000..d451c24 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/build.rs @@ -0,0 +1,8 @@ +extern crate autocfg; + +fn main() { + let cfg = autocfg::new(); + if cfg.probe_rustc_version(1, 31) { + println!("cargo:rustc-cfg=has_min_const_fn"); + } +} diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/examples/sanitize.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/examples/sanitize.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/examples/sanitize.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/examples/sanitize.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/examples/treiber_stack.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/examples/treiber_stack.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/examples/treiber_stack.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/examples/treiber_stack.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/atomic.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/atomic.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/atomic.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/atomic.rs index 0444c11..a204474 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/atomic.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/atomic.rs @@ -150,7 +150,7 @@ impl Atomic { /// /// let a = Atomic::::null(); /// ``` - #[cfg(not(feature = "nightly"))] + #[cfg(not(has_min_const_fn))] pub fn null() -> Atomic { Self { data: AtomicUsize::new(0), @@ -167,7 +167,7 @@ impl Atomic { /// /// let a = Atomic::::null(); /// ``` - #[cfg(feature = "nightly")] + #[cfg(has_min_const_fn)] pub const fn null() -> Atomic { Self { data: AtomicUsize::new(0), diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/collector.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/collector.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/collector.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/collector.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/default.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/default.rs similarity index 98% rename from third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/default.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/default.rs index 734a624..870e590 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/default.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/default.rs @@ -70,6 +70,7 @@ mod tests { super::pin(); // At thread exit, `HANDLE` gets dropped first and `FOO` second. }); - }).unwrap(); + }) + .unwrap(); } } diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/deferred.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/deferred.rs similarity index 89% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/deferred.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/deferred.rs index 574b954..a0970f1 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/deferred.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/deferred.rs @@ -4,6 +4,8 @@ use core::marker::PhantomData; use core::mem; use core::ptr; +use maybe_uninit::MaybeUninit; + /// Number of words a piece of `Data` can hold. /// /// Three words should be enough for the majority of cases. For example, you can fit inside it the @@ -36,8 +38,8 @@ impl Deferred { unsafe { if size <= mem::size_of::() && align <= mem::align_of::() { - let mut data: Data = mem::uninitialized(); - ptr::write(&mut data as *mut Data as *mut F, f); + let mut data = MaybeUninit::::uninit(); + ptr::write(data.as_mut_ptr() as *mut F, f); unsafe fn call(raw: *mut u8) { let f: F = ptr::read(raw as *mut F); @@ -46,13 +48,13 @@ impl Deferred { Deferred { call: call::, - data, + data: data.assume_init(), _marker: PhantomData, } } else { let b: Box = Box::new(f); - let mut data: Data = mem::uninitialized(); - ptr::write(&mut data as *mut Data as *mut Box, b); + let mut data = MaybeUninit::::uninit(); + ptr::write(data.as_mut_ptr() as *mut Box, b); unsafe fn call(raw: *mut u8) { let b: Box = ptr::read(raw as *mut Box); @@ -61,7 +63,7 @@ impl Deferred { Deferred { call: call::, - data, + data: data.assume_init(), _marker: PhantomData, } } diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/epoch.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/epoch.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/epoch.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/epoch.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/guard.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/guard.rs similarity index 99% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/guard.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/guard.rs index 6777d97..df18cb1 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/guard.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/guard.rs @@ -193,6 +193,8 @@ impl Guard { { if let Some(local) = self.local.as_ref() { local.defer(Deferred::new(move || drop(f())), self); + } else { + drop(f()); } } diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/internal.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/internal.rs similarity index 81% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/internal.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/internal.rs index 819e6bd..645511b 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/internal.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/internal.rs @@ -38,14 +38,13 @@ use core::cell::{Cell, UnsafeCell}; use core::mem::{self, ManuallyDrop}; use core::num::Wrapping; -use core::ptr; use core::sync::atomic; use core::sync::atomic::Ordering; +use core::{fmt, ptr}; -use arrayvec::ArrayVec; use crossbeam_utils::CachePadded; -use atomic::{Shared, Owned}; +use atomic::{Owned, Shared}; use collector::{Collector, LocalHandle}; use deferred::Deferred; use epoch::{AtomicEpoch, Epoch}; @@ -60,10 +59,10 @@ const MAX_OBJECTS: usize = 64; const MAX_OBJECTS: usize = 4; /// A bag of deferred functions. -#[derive(Default, Debug)] pub struct Bag { /// Stashed objects. - deferreds: ArrayVec<[Deferred; MAX_OBJECTS]>, + deferreds: [Deferred; MAX_OBJECTS], + len: usize, } /// `Bag::try_push()` requires that it is safe for another thread to execute the given functions. @@ -77,7 +76,7 @@ impl Bag { /// Returns `true` if the bag is empty. pub fn is_empty(&self) -> bool { - self.deferreds.is_empty() + self.len == 0 } /// Attempts to insert a deferred function into the bag. @@ -89,7 +88,13 @@ impl Bag { /// /// It should be safe for another thread to execute the given function. pub unsafe fn try_push(&mut self, deferred: Deferred) -> Result<(), Deferred> { - self.deferreds.try_push(deferred).map_err(|e| e.element()) + if self.len < MAX_OBJECTS { + self.deferreds[self.len] = deferred; + self.len += 1; + Ok(()) + } else { + Err(deferred) + } } /// Seals the bag with the given epoch. @@ -98,15 +103,117 @@ impl Bag { } } +impl Default for Bag { + // TODO(taiki-e): when the minimum supported Rust version is bumped to 1.31+, + // replace this with `#[rustfmt::skip]`. + #[cfg_attr(rustfmt, rustfmt_skip)] + fn default() -> Self { + // TODO: [no_op; MAX_OBJECTS] syntax blocked by https://github.com/rust-lang/rust/issues/49147 + #[cfg(not(feature = "sanitize"))] + return Bag { + len: 0, + deferreds: [ + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + ], + }; + #[cfg(feature = "sanitize")] + return Bag { + len: 0, + deferreds: [ + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + Deferred::new(no_op_func), + ], + }; + } +} + impl Drop for Bag { fn drop(&mut self) { // Call all deferred functions. - for deferred in self.deferreds.drain(..) { - deferred.call(); + for deferred in &mut self.deferreds[..self.len] { + let no_op = Deferred::new(no_op_func); + let owned_deferred = mem::replace(deferred, no_op); + owned_deferred.call(); } } } +// can't #[derive(Debug)] because Debug is not implemented for arrays 64 items long +impl fmt::Debug for Bag { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Bag") + .field("deferreds", &&self.deferreds[..self.len]) + .finish() + } +} + +fn no_op_func() {} + /// A pair of an epoch and a bag. #[derive(Default, Debug)] struct SealedBag { diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/lib.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/lib.rs similarity index 94% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/lib.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/lib.rs index 8ff4bfd..282bbe9 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/lib.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/lib.rs @@ -52,12 +52,11 @@ //! [`Collector`]: struct.Collector.html //! [`Shared`]: struct.Shared.html //! [`pin`]: fn.pin.html -//! [`defer`]: fn.defer.html +//! [`defer`]: struct.Guard.html#method.defer #![warn(missing_docs)] #![warn(missing_debug_implementations)] #![cfg_attr(not(feature = "std"), no_std)] -#![cfg_attr(feature = "nightly", feature(const_fn))] #![cfg_attr(feature = "nightly", feature(cfg_target_has_atomic))] #[macro_use] @@ -65,6 +64,8 @@ extern crate cfg_if; #[cfg(feature = "std")] extern crate core; +extern crate maybe_uninit; + cfg_if! { if #[cfg(feature = "alloc")] { extern crate alloc; @@ -73,13 +74,9 @@ cfg_if! { } } -#[cfg_attr( - feature = "nightly", - cfg(all(target_has_atomic = "cas", target_has_atomic = "ptr")) -)] +#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))] cfg_if! { if #[cfg(any(feature = "alloc", feature = "std"))] { - extern crate arrayvec; extern crate crossbeam_utils; #[macro_use] extern crate memoffset; diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/list.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/list.rs similarity index 92% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/list.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/list.rs index 623fbd2..8e8899e 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/list.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/list.rs @@ -243,35 +243,44 @@ impl<'g, T: 'g, C: IsElement> Iterator for Iter<'g, T, C> { // This entry was removed. Try unlinking it from the list. let succ = succ.with_tag(0); - // The tag should never be zero, because removing a node after a logically deleted + // The tag should always be zero, because removing a node after a logically deleted // node leaves the list in an invalid state. debug_assert!(self.curr.tag() == 0); - match self + // Try to unlink `curr` from the list, and get the new value of `self.pred`. + let succ = match self .pred .compare_and_set(self.curr, succ, Acquire, self.guard) { Ok(_) => { - // We succeeded in unlinking this element from the list, so we have to - // schedule deallocation. Deferred drop is okay, because `list.delete()` - // can only be called if `T: 'static`. + // We succeeded in unlinking `curr`, so we have to schedule + // deallocation. Deferred drop is okay, because `list.delete()` can only be + // called if `T: 'static`. unsafe { C::finalize(self.curr.deref(), self.guard); } - // Move over the removed by only advancing `curr`, not `pred`. - self.curr = succ; - continue; + // `succ` is the new value of `self.pred`. + succ } - Err(_) => { - // A concurrent thread modified the predecessor node. Since it might've - // been deleted, we need to restart from `head`. - self.pred = self.head; - self.curr = self.head.load(Acquire, self.guard); + Err(e) => { + // `e.current` is the current value of `self.pred`. + e.current + } + }; - return Some(Err(IterError::Stalled)); - } + // If the predecessor node is already marked as deleted, we need to restart from + // `head`. + if succ.tag() != 0 { + self.pred = self.head; + self.curr = self.head.load(Acquire, self.guard); + + return Some(Err(IterError::Stalled)); } + + // Move over the removed by only advancing `curr`, not `pred`. + self.curr = succ; + continue; } // Move one step forward. diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/mod.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/mod.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.6.1/src/sync/mod.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/mod.rs diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/queue.rs b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/queue.rs similarity index 90% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/queue.rs rename to third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/queue.rs index 671d046..99fb6a1 100644 --- a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/src/sync/queue.rs +++ b/third_party/cargo/vendor/crossbeam-epoch-0.8.2/src/sync/queue.rs @@ -4,13 +4,16 @@ //! //! Michael and Scott. Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue //! Algorithms. PODC 1996. http://dl.acm.org/citation.cfm?id=248106 +//! +//! Simon Doherty, Lindsay Groves, Victor Luchangco, and Mark Moir. 2004b. Formal Verification of a +//! Practical Lock-Free Queue Algorithm. https://doi.org/10.1007/978-3-540-30232-2_7 -use core::mem::{self, ManuallyDrop}; -use core::ptr; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crossbeam_utils::CachePadded; +use maybe_uninit::MaybeUninit; + use {unprotected, Atomic, Guard, Owned, Shared}; // The representation here is a singly-linked list, with a sentinel node at the front. In general @@ -22,15 +25,14 @@ pub struct Queue { tail: CachePadded>>, } -#[derive(Debug)] struct Node { /// The slot in which a value of type `T` can be stored. /// - /// The type of `data` is `ManuallyDrop` because a `Node` doesn't always contain a `T`. + /// The type of `data` is `MaybeUninit` because a `Node` doesn't always contain a `T`. /// For example, the sentinel node in a queue never contains a value: its slot is always empty. /// Other nodes start their life with a push operation and contain a value until it gets popped /// out. After that such empty nodes get added to the collector for destruction. - data: ManuallyDrop, + data: MaybeUninit, next: Atomic>, } @@ -47,7 +49,7 @@ impl Queue { tail: CachePadded::new(Atomic::null()), }; let sentinel = Owned::new(Node { - data: unsafe { mem::uninitialized() }, + data: MaybeUninit::uninit(), next: Atomic::null(), }); unsafe { @@ -87,7 +89,7 @@ impl Queue { /// Adds `t` to the back of the queue, possibly waking up threads blocked on `pop`. pub fn push(&self, t: T, guard: &Guard) { let new = Owned::new(Node { - data: ManuallyDrop::new(t), + data: MaybeUninit::new(t), next: Atomic::null(), }); let new = Owned::into_shared(new, guard); @@ -114,8 +116,14 @@ impl Queue { self.head .compare_and_set(head, next, Release, guard) .map(|_| { + let tail = self.tail.load(Relaxed, guard); + // Advance the tail so that we don't retire a pointer to a reachable node. + if head == tail { + let _ = self.tail.compare_and_set(tail, next, Release, guard); + } guard.defer_destroy(head); - Some(ManuallyDrop::into_inner(ptr::read(&n.data))) + // TODO: Replace with MaybeUninit::read when api is stable + Some(n.data.as_ptr().read()) }) .map_err(|_| ()) }, @@ -135,12 +143,17 @@ impl Queue { let h = unsafe { head.deref() }; let next = h.next.load(Acquire, guard); match unsafe { next.as_ref() } { - Some(n) if condition(&n.data) => unsafe { + Some(n) if condition(unsafe { &*n.data.as_ptr() }) => unsafe { self.head .compare_and_set(head, next, Release, guard) .map(|_| { + let tail = self.tail.load(Relaxed, guard); + // Advance the tail so that we don't retire a pointer to a reachable node. + if head == tail { + let _ = self.tail.compare_and_set(tail, next, Release, guard); + } guard.defer_destroy(head); - Some(ManuallyDrop::into_inner(ptr::read(&n.data))) + Some(n.data.as_ptr().read()) }) .map_err(|_| ()) }, diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-queue-0.2.1/.cargo-checksum.json new file mode 100644 index 0000000..44a9a3f --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"11a088f907e561d383ff4b317a36adadaa1369eb3b3e30a9a480264198bb0bd7","Cargo.toml":"2de2e2eaa104a973d39f9689f78fd1040765f7263d83f6d374de2fb57205c48d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","LICENSE-THIRD-PARTY":"abb1905b1c2b7db73902e6c328d332d82f3797d7fab61e6fc1c2fc366b132014","README.md":"b487d2d9d9cf9726fbf3b5cf736ddc363f8d1e1410a0a4020dda27c4df72c627","src/array_queue.rs":"ea8f2ac760dc0418d035df8f47b67fe15dbfb94a31836c3ee7d45e02f8d172db","src/err.rs":"cde063a29dc8887d4c3bd0994f7aab08879841d94c61ecf104a8a85f2c436302","src/lib.rs":"75b2c59de7728e6dce4a31565e3c7ba98132260f02a637726d50cd9fbe4f4886","src/seg_queue.rs":"7a27739c9667cc9b57a4a02a1df2176ab252233c579684a5fd64dd3ffccc2cff","tests/array_queue.rs":"3faa35bbe2acb3dabdfab5e81860a19e0237c57513420bbb9afe0cb89ac25909","tests/seg_queue.rs":"885ea52ce2c5d1fa9b4265250957d51ffa3f0781d57b01d28cb871371e32ac92"},"package":"c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/BUILD b/third_party/cargo/vendor/crossbeam-queue-0.2.1/BUILD new file mode 100644 index 0000000..7a69bef --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/BUILD @@ -0,0 +1,49 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" + "restricted", # "Apache-2.0 AND BSD-2-Clause" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + +# Unsupported target "array_queue" with type "test" omitted + +rust_library( + name = "crossbeam_queue", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", + "//third_party/cargo/vendor/crossbeam-utils-0.7.2:crossbeam_utils", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.2.1", + crate_features = [ + "default", + "std", + ], +) + +# Unsupported target "seg_queue" with type "test" omitted diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-queue-0.2.1/CHANGELOG.md new file mode 100644 index 0000000..5677d7c --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/CHANGELOG.md @@ -0,0 +1,20 @@ +# Version 0.2.1 + +- Add `no_std` support. + +# Version 0.2.0 + +- Bump the minimum required version to 1.28. +- Bump `crossbeam-utils` to `0.7`. + +# Version 0.1.2 + +- Update `crossbeam-utils` to `0.6.5`. + +# Version 0.1.1 + +- Update `crossbeam-utils` to `0.6.4`. + +# Version 0.1.0 + +- Initial version with `ArrayQueue` and `SegQueue`. diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/Cargo.toml b/third_party/cargo/vendor/crossbeam-queue-0.2.1/Cargo.toml new file mode 100644 index 0000000..23a74ed --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/Cargo.toml @@ -0,0 +1,37 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "crossbeam-queue" +version = "0.2.1" +authors = ["The Crossbeam Project Developers"] +description = "Concurrent queues" +homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils" +documentation = "https://docs.rs/crossbeam-queue" +readme = "README.md" +keywords = ["queue", "mpmc", "lock-free", "producer", "consumer"] +categories = ["concurrency", "data-structures"] +license = "MIT/Apache-2.0 AND BSD-2-Clause" +repository = "https://github.com/crossbeam-rs/crossbeam" +[dependencies.cfg-if] +version = "0.1.2" + +[dependencies.crossbeam-utils] +version = "0.7" +default-features = false +[dev-dependencies.rand] +version = "0.6" + +[features] +alloc = ["crossbeam-utils/alloc"] +default = ["std"] +std = ["crossbeam-utils/std"] diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.7.2/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.7.2/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-APACHE diff --git a/third_party/cargo/vendor/metal-0.13.1/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-MIT similarity index 93% rename from third_party/cargo/vendor/metal-0.13.1/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-MIT index 25597d5..068d491 100644 --- a/third_party/cargo/vendor/metal-0.13.1/LICENSE-MIT +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-MIT @@ -1,4 +1,6 @@ -Copyright (c) 2010 The Rust Project Developers +The MIT License (MIT) + +Copyright (c) 2019 The Crossbeam Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-THIRD-PARTY b/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-THIRD-PARTY new file mode 100644 index 0000000..8914949 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/LICENSE-THIRD-PARTY @@ -0,0 +1,31 @@ +=============================================================================== + +Bounded MPMC queue +http://www.1024cores.net/home/code-license + +Copyright (c) 2010-2011 Dmitry Vyukov. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. 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. + +THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV OR CONTRIBUTORS 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. + +The views and conclusions contained in the software and documentation are those +of the authors and should not be interpreted as representing official policies, +either expressed or implied, of Dmitry Vyukov. diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/README.md b/third_party/cargo/vendor/crossbeam-queue-0.2.1/README.md new file mode 100644 index 0000000..646f9cf --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/README.md @@ -0,0 +1,67 @@ +# Crossbeam Queue + +[![Build Status](https://travis-ci.org/crossbeam-rs/crossbeam.svg?branch=master)]( +https://travis-ci.org/crossbeam-rs/crossbeam) +[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)]( +https://github.com/crossbeam-rs/crossbeam-queue/tree/master/src) +[![Cargo](https://img.shields.io/crates/v/crossbeam-queue.svg)]( +https://crates.io/crates/crossbeam-queue) +[![Documentation](https://docs.rs/crossbeam-queue/badge.svg)]( +https://docs.rs/crossbeam-queue) +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( +https://www.rust-lang.org) +[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/BBYwKq) + +This crate provides concurrent queues that can be shared among threads: + +* [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. +* [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. + +[`ArrayQueue`]: https://docs.rs/crossbeam-queue/*/crossbeam_queue/struct.ArrayQueue.html +[`SegQueue`]: https://docs.rs/crossbeam-queue/*/crossbeam_queue/struct.SegQueue.html + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +crossbeam-queue = "0.2" +``` + +Next, add this to your crate: + +```rust +extern crate crossbeam_queue; +``` + +## Compatibility + +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. + +## License + +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 the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +#### Third party software + +This product includes copies and modifications of software developed by third parties: + +* [src/array_queue.rs](src/array_queue.rs) is based on + [Bounded MPMC queue](http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue) + by Dmitry Vyukov, licensed under the Simplified BSD License and the Apache License, Version 2.0. + +See the source code files for more details. + +Copies of third party licenses can be found in [LICENSE-THIRD-PARTY](LICENSE-THIRD-PARTY). diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/array_queue.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/array_queue.rs new file mode 100644 index 0000000..683daad --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/array_queue.rs @@ -0,0 +1,433 @@ +//! The implementation is based on Dmitry Vyukov's bounded MPMC queue. +//! +//! Source: +//! - http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue +//! +//! Copyright & License: +//! - Copyright (c) 2010-2011 Dmitry Vyukov +//! - Simplified BSD License and Apache License, Version 2.0 +//! - http://www.1024cores.net/home/code-license + +use alloc::vec::Vec; +use core::cell::UnsafeCell; +use core::fmt; +use core::marker::PhantomData; +use core::mem; +use core::ptr; +use core::sync::atomic::{self, AtomicUsize, Ordering}; + +use crossbeam_utils::{Backoff, CachePadded}; + +use err::{PopError, PushError}; + +/// A slot in a queue. +struct Slot { + /// The current stamp. + /// + /// If the stamp equals the tail, this node will be next written to. If it equals head + 1, + /// this node will be next read from. + stamp: AtomicUsize, + + /// The value in this slot. + value: UnsafeCell, +} + +/// A bounded multi-producer multi-consumer queue. +/// +/// This queue allocates a fixed-capacity buffer on construction, which is used to store pushed +/// elements. The queue cannot hold more elements than the buffer allows. Attempting to push an +/// element into a full queue will fail. Having a buffer allocated upfront makes this queue a bit +/// faster than [`SegQueue`]. +/// +/// [`SegQueue`]: struct.SegQueue.html +/// +/// # Examples +/// +/// ``` +/// use crossbeam_queue::{ArrayQueue, PushError}; +/// +/// let q = ArrayQueue::new(2); +/// +/// assert_eq!(q.push('a'), Ok(())); +/// assert_eq!(q.push('b'), Ok(())); +/// assert_eq!(q.push('c'), Err(PushError('c'))); +/// assert_eq!(q.pop(), Ok('a')); +/// ``` +pub struct ArrayQueue { + /// The head of the queue. + /// + /// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a + /// single `usize`. The lower bits represent the index, while the upper bits represent the lap. + /// + /// Elements are popped from the head of the queue. + head: CachePadded, + + /// The tail of the queue. + /// + /// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a + /// single `usize`. The lower bits represent the index, while the upper bits represent the lap. + /// + /// Elements are pushed into the tail of the queue. + tail: CachePadded, + + /// The buffer holding slots. + buffer: *mut Slot, + + /// The queue capacity. + cap: usize, + + /// A stamp with the value of `{ lap: 1, index: 0 }`. + one_lap: usize, + + /// Indicates that dropping an `ArrayQueue` may drop elements of type `T`. + _marker: PhantomData, +} + +unsafe impl Sync for ArrayQueue {} +unsafe impl Send for ArrayQueue {} + +impl ArrayQueue { + /// Creates a new bounded queue with the given capacity. + /// + /// # Panics + /// + /// Panics if the capacity is zero. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::ArrayQueue; + /// + /// let q = ArrayQueue::::new(100); + /// ``` + pub fn new(cap: usize) -> ArrayQueue { + assert!(cap > 0, "capacity must be non-zero"); + + // Head is initialized to `{ lap: 0, index: 0 }`. + // Tail is initialized to `{ lap: 0, index: 0 }`. + let head = 0; + let tail = 0; + + // Allocate a buffer of `cap` slots. + let buffer = { + let mut v = Vec::>::with_capacity(cap); + let ptr = v.as_mut_ptr(); + mem::forget(v); + ptr + }; + + // Initialize stamps in the slots. + for i in 0..cap { + unsafe { + // Set the stamp to `{ lap: 0, index: i }`. + let slot = buffer.add(i); + ptr::write(&mut (*slot).stamp, AtomicUsize::new(i)); + } + } + + // One lap is the smallest power of two greater than `cap`. + let one_lap = (cap + 1).next_power_of_two(); + + ArrayQueue { + buffer, + cap, + one_lap, + head: CachePadded::new(AtomicUsize::new(head)), + tail: CachePadded::new(AtomicUsize::new(tail)), + _marker: PhantomData, + } + } + + /// Attempts to push an element into the queue. + /// + /// If the queue is full, the element is returned back as an error. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PushError}; + /// + /// let q = ArrayQueue::new(1); + /// + /// assert_eq!(q.push(10), Ok(())); + /// assert_eq!(q.push(20), Err(PushError(20))); + /// ``` + pub fn push(&self, value: T) -> Result<(), PushError> { + let backoff = Backoff::new(); + let mut tail = self.tail.load(Ordering::Relaxed); + + loop { + // Deconstruct the tail. + let index = tail & (self.one_lap - 1); + let lap = tail & !(self.one_lap - 1); + + // Inspect the corresponding slot. + let slot = unsafe { &*self.buffer.add(index) }; + let stamp = slot.stamp.load(Ordering::Acquire); + + // If the tail and the stamp match, we may attempt to push. + if tail == stamp { + let new_tail = if index + 1 < self.cap { + // Same lap, incremented index. + // Set to `{ lap: lap, index: index + 1 }`. + tail + 1 + } else { + // One lap forward, index wraps around to zero. + // Set to `{ lap: lap.wrapping_add(1), index: 0 }`. + lap.wrapping_add(self.one_lap) + }; + + // Try moving the tail. + match self.tail.compare_exchange_weak( + tail, + new_tail, + Ordering::SeqCst, + Ordering::Relaxed, + ) { + Ok(_) => { + // Write the value into the slot and update the stamp. + unsafe { + slot.value.get().write(value); + } + slot.stamp.store(tail + 1, Ordering::Release); + return Ok(()); + } + Err(t) => { + tail = t; + backoff.spin(); + } + } + } else if stamp.wrapping_add(self.one_lap) == tail + 1 { + atomic::fence(Ordering::SeqCst); + let head = self.head.load(Ordering::Relaxed); + + // If the head lags one lap behind the tail as well... + if head.wrapping_add(self.one_lap) == tail { + // ...then the queue is full. + return Err(PushError(value)); + } + + backoff.spin(); + tail = self.tail.load(Ordering::Relaxed); + } else { + // Snooze because we need to wait for the stamp to get updated. + backoff.snooze(); + tail = self.tail.load(Ordering::Relaxed); + } + } + } + + /// Attempts to pop an element from the queue. + /// + /// If the queue is empty, an error is returned. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PopError}; + /// + /// let q = ArrayQueue::new(1); + /// assert_eq!(q.push(10), Ok(())); + /// + /// assert_eq!(q.pop(), Ok(10)); + /// assert_eq!(q.pop(), Err(PopError)); + /// ``` + pub fn pop(&self) -> Result { + let backoff = Backoff::new(); + let mut head = self.head.load(Ordering::Relaxed); + + loop { + // Deconstruct the head. + let index = head & (self.one_lap - 1); + let lap = head & !(self.one_lap - 1); + + // Inspect the corresponding slot. + let slot = unsafe { &*self.buffer.add(index) }; + let stamp = slot.stamp.load(Ordering::Acquire); + + // If the the stamp is ahead of the head by 1, we may attempt to pop. + if head + 1 == stamp { + let new = if index + 1 < self.cap { + // Same lap, incremented index. + // Set to `{ lap: lap, index: index + 1 }`. + head + 1 + } else { + // One lap forward, index wraps around to zero. + // Set to `{ lap: lap.wrapping_add(1), index: 0 }`. + lap.wrapping_add(self.one_lap) + }; + + // Try moving the head. + match self.head.compare_exchange_weak( + head, + new, + Ordering::SeqCst, + Ordering::Relaxed, + ) { + Ok(_) => { + // Read the value from the slot and update the stamp. + let msg = unsafe { slot.value.get().read() }; + slot.stamp + .store(head.wrapping_add(self.one_lap), Ordering::Release); + return Ok(msg); + } + Err(h) => { + head = h; + backoff.spin(); + } + } + } else if stamp == head { + atomic::fence(Ordering::SeqCst); + let tail = self.tail.load(Ordering::Relaxed); + + // If the tail equals the head, that means the channel is empty. + if tail == head { + return Err(PopError); + } + + backoff.spin(); + head = self.head.load(Ordering::Relaxed); + } else { + // Snooze because we need to wait for the stamp to get updated. + backoff.snooze(); + head = self.head.load(Ordering::Relaxed); + } + } + } + + /// Returns the capacity of the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PopError}; + /// + /// let q = ArrayQueue::::new(100); + /// + /// assert_eq!(q.capacity(), 100); + /// ``` + pub fn capacity(&self) -> usize { + self.cap + } + + /// Returns `true` if the queue is empty. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PopError}; + /// + /// let q = ArrayQueue::new(100); + /// + /// assert!(q.is_empty()); + /// q.push(1).unwrap(); + /// assert!(!q.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + let head = self.head.load(Ordering::SeqCst); + let tail = self.tail.load(Ordering::SeqCst); + + // Is the tail lagging one lap behind head? + // Is the tail equal to the head? + // + // Note: If the head changes just before we load the tail, that means there was a moment + // when the channel was not empty, so it is safe to just return `false`. + tail == head + } + + /// Returns `true` if the queue is full. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PopError}; + /// + /// let q = ArrayQueue::new(1); + /// + /// assert!(!q.is_full()); + /// q.push(1).unwrap(); + /// assert!(q.is_full()); + /// ``` + pub fn is_full(&self) -> bool { + let tail = self.tail.load(Ordering::SeqCst); + let head = self.head.load(Ordering::SeqCst); + + // Is the head lagging one lap behind tail? + // + // Note: If the tail changes just before we load the head, that means there was a moment + // when the queue was not full, so it is safe to just return `false`. + head.wrapping_add(self.one_lap) == tail + } + + /// Returns the number of elements in the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{ArrayQueue, PopError}; + /// + /// let q = ArrayQueue::new(100); + /// assert_eq!(q.len(), 0); + /// + /// q.push(10).unwrap(); + /// assert_eq!(q.len(), 1); + /// + /// q.push(20).unwrap(); + /// assert_eq!(q.len(), 2); + /// ``` + pub fn len(&self) -> usize { + loop { + // Load the tail, then load the head. + let tail = self.tail.load(Ordering::SeqCst); + let head = self.head.load(Ordering::SeqCst); + + // If the tail didn't change, we've got consistent values to work with. + if self.tail.load(Ordering::SeqCst) == tail { + let hix = head & (self.one_lap - 1); + let tix = tail & (self.one_lap - 1); + + return if hix < tix { + tix - hix + } else if hix > tix { + self.cap - hix + tix + } else if tail == head { + 0 + } else { + self.cap + }; + } + } + } +} + +impl Drop for ArrayQueue { + fn drop(&mut self) { + // Get the index of the head. + let hix = self.head.load(Ordering::Relaxed) & (self.one_lap - 1); + + // Loop over all slots that hold a message and drop them. + for i in 0..self.len() { + // Compute the index of the next slot holding a message. + let index = if hix + i < self.cap { + hix + i + } else { + hix + i - self.cap + }; + + unsafe { + self.buffer.add(index).drop_in_place(); + } + } + + // Finally, deallocate the buffer, but don't run any destructors. + unsafe { + Vec::from_raw_parts(self.buffer, 0, self.cap); + } + } +} + +impl fmt::Debug for ArrayQueue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("ArrayQueue { .. }") + } +} diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/err.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/err.rs new file mode 100644 index 0000000..42880e8 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/err.rs @@ -0,0 +1,47 @@ +use core::fmt; + +/// Error which occurs when popping from an empty queue. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct PopError; + +impl fmt::Debug for PopError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "PopError".fmt(f) + } +} + +impl fmt::Display for PopError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "popping from an empty queue".fmt(f) + } +} + +#[cfg(features = "std")] +impl std::error::Error for PopError { + fn description(&self) -> &str { + "popping from an empty queue" + } +} + +/// Error which occurs when pushing into a full queue. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct PushError(pub T); + +impl fmt::Debug for PushError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "PushError(..)".fmt(f) + } +} + +impl fmt::Display for PushError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "pushing into a full queue".fmt(f) + } +} + +#[cfg(features = "std")] +impl std::error::Error for PushError { + fn description(&self) -> &str { + "pushing into a full queue" + } +} diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/lib.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/lib.rs new file mode 100644 index 0000000..2eda6b0 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/lib.rs @@ -0,0 +1,40 @@ +//! Concurrent queues. +//! +//! This crate provides concurrent queues that can be shared among threads: +//! +//! * [`ArrayQueue`], a bounded MPMC queue that allocates a fixed-capacity buffer on construction. +//! * [`SegQueue`], an unbounded MPMC queue that allocates small buffers, segments, on demand. +//! +//! [`ArrayQueue`]: struct.ArrayQueue.html +//! [`SegQueue`]: struct.SegQueue.html + +#![warn(missing_docs)] +#![warn(missing_debug_implementations)] +#![cfg_attr(not(feature = "std"), no_std)] + +#[macro_use] +extern crate cfg_if; +#[cfg(feature = "std")] +extern crate core; + +cfg_if! { + if #[cfg(feature = "alloc")] { + extern crate alloc; + } else if #[cfg(feature = "std")] { + extern crate std as alloc; + } +} + +extern crate crossbeam_utils; + +cfg_if! { + if #[cfg(any(feature = "alloc", feature = "std"))] { + mod array_queue; + mod err; + mod seg_queue; + + pub use self::array_queue::ArrayQueue; + pub use self::err::{PopError, PushError}; + pub use self::seg_queue::SegQueue; + } +} diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/seg_queue.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/seg_queue.rs new file mode 100644 index 0000000..2ddfe8b --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/src/seg_queue.rs @@ -0,0 +1,483 @@ +use alloc::boxed::Box; +use core::cell::UnsafeCell; +use core::fmt; +use core::marker::PhantomData; +use core::mem::{self, ManuallyDrop}; +use core::ptr; +use core::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering}; + +use crossbeam_utils::{Backoff, CachePadded}; + +use err::PopError; + +// Bits indicating the state of a slot: +// * If a value has been written into the slot, `WRITE` is set. +// * If a value has been read from the slot, `READ` is set. +// * If the block is being destroyed, `DESTROY` is set. +const WRITE: usize = 1; +const READ: usize = 2; +const DESTROY: usize = 4; + +// Each block covers one "lap" of indices. +const LAP: usize = 32; +// The maximum number of values a block can hold. +const BLOCK_CAP: usize = LAP - 1; +// How many lower bits are reserved for metadata. +const SHIFT: usize = 1; +// Indicates that the block is not the last one. +const HAS_NEXT: usize = 1; + +/// A slot in a block. +struct Slot { + /// The value. + value: UnsafeCell>, + + /// The state of the slot. + state: AtomicUsize, +} + +impl Slot { + /// Waits until a value is written into the slot. + fn wait_write(&self) { + let backoff = Backoff::new(); + while self.state.load(Ordering::Acquire) & WRITE == 0 { + backoff.snooze(); + } + } +} + +/// A block in a linked list. +/// +/// Each block in the list can hold up to `BLOCK_CAP` values. +struct Block { + /// The next block in the linked list. + next: AtomicPtr>, + + /// Slots for values. + slots: [Slot; BLOCK_CAP], +} + +impl Block { + /// Creates an empty block that starts at `start_index`. + fn new() -> Block { + unsafe { mem::zeroed() } + } + + /// Waits until the next pointer is set. + fn wait_next(&self) -> *mut Block { + let backoff = Backoff::new(); + loop { + let next = self.next.load(Ordering::Acquire); + if !next.is_null() { + return next; + } + backoff.snooze(); + } + } + + /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block. + unsafe fn destroy(this: *mut Block, start: usize) { + // It is not necessary to set the `DESTROY` bit in the last slot because that slot has + // begun destruction of the block. + for i in start..BLOCK_CAP - 1 { + let slot = (*this).slots.get_unchecked(i); + + // Mark the `DESTROY` bit if a thread is still using the slot. + if slot.state.load(Ordering::Acquire) & READ == 0 + && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0 + { + // If a thread is still using the slot, it will continue destruction of the block. + return; + } + } + + // No thread is using the block, now it is safe to destroy it. + drop(Box::from_raw(this)); + } +} + +/// A position in a queue. +struct Position { + /// The index in the queue. + index: AtomicUsize, + + /// The block in the linked list. + block: AtomicPtr>, +} + +/// An unbounded multi-producer multi-consumer queue. +/// +/// This queue is implemented as a linked list of segments, where each segment is a small buffer +/// that can hold a handful of elements. There is no limit to how many elements can be in the queue +/// at a time. However, since segments need to be dynamically allocated as elements get pushed, +/// this queue is somewhat slower than [`ArrayQueue`]. +/// +/// [`ArrayQueue`]: struct.ArrayQueue.html +/// +/// # Examples +/// +/// ``` +/// use crossbeam_queue::{PopError, SegQueue}; +/// +/// let q = SegQueue::new(); +/// +/// q.push('a'); +/// q.push('b'); +/// +/// assert_eq!(q.pop(), Ok('a')); +/// assert_eq!(q.pop(), Ok('b')); +/// assert_eq!(q.pop(), Err(PopError)); +/// ``` +pub struct SegQueue { + /// The head of the queue. + head: CachePadded>, + + /// The tail of the queue. + tail: CachePadded>, + + /// Indicates that dropping a `SegQueue` may drop values of type `T`. + _marker: PhantomData, +} + +unsafe impl Send for SegQueue {} +unsafe impl Sync for SegQueue {} + +impl SegQueue { + /// Creates a new unbounded queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::SegQueue; + /// + /// let q = SegQueue::::new(); + /// ``` + pub fn new() -> SegQueue { + SegQueue { + head: CachePadded::new(Position { + block: AtomicPtr::new(ptr::null_mut()), + index: AtomicUsize::new(0), + }), + tail: CachePadded::new(Position { + block: AtomicPtr::new(ptr::null_mut()), + index: AtomicUsize::new(0), + }), + _marker: PhantomData, + } + } + + /// Pushes an element into the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::SegQueue; + /// + /// let q = SegQueue::new(); + /// + /// q.push(10); + /// q.push(20); + /// ``` + pub fn push(&self, value: T) { + let backoff = Backoff::new(); + let mut tail = self.tail.index.load(Ordering::Acquire); + let mut block = self.tail.block.load(Ordering::Acquire); + let mut next_block = None; + + loop { + // Calculate the offset of the index into the block. + let offset = (tail >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + tail = self.tail.index.load(Ordering::Acquire); + block = self.tail.block.load(Ordering::Acquire); + continue; + } + + // If we're going to have to install the next block, allocate it in advance in order to + // make the wait for other threads as short as possible. + if offset + 1 == BLOCK_CAP && next_block.is_none() { + next_block = Some(Box::new(Block::::new())); + } + + // If this is the first push operation, we need to allocate the first block. + if block.is_null() { + let new = Box::into_raw(Box::new(Block::::new())); + + if self + .tail + .block + .compare_and_swap(block, new, Ordering::Release) + == block + { + self.head.block.store(new, Ordering::Release); + block = new; + } else { + next_block = unsafe { Some(Box::from_raw(new)) }; + tail = self.tail.index.load(Ordering::Acquire); + block = self.tail.block.load(Ordering::Acquire); + continue; + } + } + + let new_tail = tail + (1 << SHIFT); + + // Try advancing the tail forward. + match self.tail.index.compare_exchange_weak( + tail, + new_tail, + Ordering::SeqCst, + Ordering::Acquire, + ) { + Ok(_) => unsafe { + // If we've reached the end of the block, install the next one. + if offset + 1 == BLOCK_CAP { + let next_block = Box::into_raw(next_block.unwrap()); + let next_index = new_tail.wrapping_add(1 << SHIFT); + + self.tail.block.store(next_block, Ordering::Release); + self.tail.index.store(next_index, Ordering::Release); + (*block).next.store(next_block, Ordering::Release); + } + + // Write the value into the slot. + let slot = (*block).slots.get_unchecked(offset); + slot.value.get().write(ManuallyDrop::new(value)); + slot.state.fetch_or(WRITE, Ordering::Release); + + return; + }, + Err(t) => { + tail = t; + block = self.tail.block.load(Ordering::Acquire); + backoff.spin(); + } + } + } + } + + /// Pops an element from the queue. + /// + /// If the queue is empty, an error is returned. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{PopError, SegQueue}; + /// + /// let q = SegQueue::new(); + /// + /// q.push(10); + /// assert_eq!(q.pop(), Ok(10)); + /// assert_eq!(q.pop(), Err(PopError)); + /// ``` + pub fn pop(&self) -> Result { + let backoff = Backoff::new(); + let mut head = self.head.index.load(Ordering::Acquire); + let mut block = self.head.block.load(Ordering::Acquire); + + loop { + // Calculate the offset of the index into the block. + let offset = (head >> SHIFT) % LAP; + + // If we reached the end of the block, wait until the next one is installed. + if offset == BLOCK_CAP { + backoff.snooze(); + head = self.head.index.load(Ordering::Acquire); + block = self.head.block.load(Ordering::Acquire); + continue; + } + + let mut new_head = head + (1 << SHIFT); + + if new_head & HAS_NEXT == 0 { + atomic::fence(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::Relaxed); + + // If the tail equals the head, that means the queue is empty. + if head >> SHIFT == tail >> SHIFT { + return Err(PopError); + } + + // If head and tail are not in the same block, set `HAS_NEXT` in head. + if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP { + new_head |= HAS_NEXT; + } + } + + // The block can be null here only if the first push operation is in progress. In that + // case, just wait until it gets initialized. + if block.is_null() { + backoff.snooze(); + head = self.head.index.load(Ordering::Acquire); + block = self.head.block.load(Ordering::Acquire); + continue; + } + + // Try moving the head index forward. + match self.head.index.compare_exchange_weak( + head, + new_head, + Ordering::SeqCst, + Ordering::Acquire, + ) { + Ok(_) => unsafe { + // If we've reached the end of the block, move to the next one. + if offset + 1 == BLOCK_CAP { + let next = (*block).wait_next(); + let mut next_index = (new_head & !HAS_NEXT).wrapping_add(1 << SHIFT); + if !(*next).next.load(Ordering::Relaxed).is_null() { + next_index |= HAS_NEXT; + } + + self.head.block.store(next, Ordering::Release); + self.head.index.store(next_index, Ordering::Release); + } + + // Read the value. + let slot = (*block).slots.get_unchecked(offset); + slot.wait_write(); + let m = slot.value.get().read(); + let value = ManuallyDrop::into_inner(m); + + // Destroy the block if we've reached the end, or if another thread wanted to + // destroy but couldn't because we were busy reading from the slot. + if offset + 1 == BLOCK_CAP { + Block::destroy(block, 0); + } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 { + Block::destroy(block, offset + 1); + } + + return Ok(value); + }, + Err(h) => { + head = h; + block = self.head.block.load(Ordering::Acquire); + backoff.spin(); + } + } + } + } + + /// Returns `true` if the queue is empty. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::SegQueue; + /// + /// let q = SegQueue::new(); + /// + /// assert!(q.is_empty()); + /// q.push(1); + /// assert!(!q.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + let head = self.head.index.load(Ordering::SeqCst); + let tail = self.tail.index.load(Ordering::SeqCst); + head >> SHIFT == tail >> SHIFT + } + + /// Returns the number of elements in the queue. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_queue::{SegQueue, PopError}; + /// + /// let q = SegQueue::new(); + /// assert_eq!(q.len(), 0); + /// + /// q.push(10); + /// assert_eq!(q.len(), 1); + /// + /// q.push(20); + /// assert_eq!(q.len(), 2); + /// ``` + pub fn len(&self) -> usize { + loop { + // Load the tail index, then load the head index. + let mut tail = self.tail.index.load(Ordering::SeqCst); + let mut head = self.head.index.load(Ordering::SeqCst); + + // If the tail index didn't change, we've got consistent indices to work with. + if self.tail.index.load(Ordering::SeqCst) == tail { + // Erase the lower bits. + tail &= !((1 << SHIFT) - 1); + head &= !((1 << SHIFT) - 1); + + // Rotate indices so that head falls into the first block. + let lap = (head >> SHIFT) / LAP; + tail = tail.wrapping_sub((lap * LAP) << SHIFT); + head = head.wrapping_sub((lap * LAP) << SHIFT); + + // Remove the lower bits. + tail >>= SHIFT; + head >>= SHIFT; + + // Fix up indices if they fall onto block ends. + if head == BLOCK_CAP { + head = 0; + tail -= LAP; + } + if tail == BLOCK_CAP { + tail += 1; + } + + // Return the difference minus the number of blocks between tail and head. + return tail - head - tail / LAP; + } + } + } +} + +impl Drop for SegQueue { + fn drop(&mut self) { + let mut head = self.head.index.load(Ordering::Relaxed); + let mut tail = self.tail.index.load(Ordering::Relaxed); + let mut block = self.head.block.load(Ordering::Relaxed); + + // Erase the lower bits. + head &= !((1 << SHIFT) - 1); + tail &= !((1 << SHIFT) - 1); + + unsafe { + // Drop all values between `head` and `tail` and deallocate the heap-allocated blocks. + while head != tail { + let offset = (head >> SHIFT) % LAP; + + if offset < BLOCK_CAP { + // Drop the value in the slot. + let slot = (*block).slots.get_unchecked(offset); + ManuallyDrop::drop(&mut *(*slot).value.get()); + } else { + // Deallocate the block and move to the next one. + let next = (*block).next.load(Ordering::Relaxed); + drop(Box::from_raw(block)); + block = next; + } + + head = head.wrapping_add(1 << SHIFT); + } + + // Deallocate the last remaining block. + if !block.is_null() { + drop(Box::from_raw(block)); + } + } + } +} + +impl fmt::Debug for SegQueue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("SegQueue { .. }") + } +} + +impl Default for SegQueue { + fn default() -> SegQueue { + SegQueue::new() + } +} diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/array_queue.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/array_queue.rs new file mode 100644 index 0000000..a4f64f3 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/array_queue.rs @@ -0,0 +1,254 @@ +extern crate crossbeam_queue; +extern crate crossbeam_utils; +extern crate rand; + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crossbeam_queue::ArrayQueue; +use crossbeam_utils::thread::scope; +use rand::{thread_rng, Rng}; + +#[test] +fn smoke() { + let q = ArrayQueue::new(1); + + q.push(7).unwrap(); + assert_eq!(q.pop(), Ok(7)); + + q.push(8).unwrap(); + assert_eq!(q.pop(), Ok(8)); + assert!(q.pop().is_err()); +} + +#[test] +fn capacity() { + for i in 1..10 { + let q = ArrayQueue::::new(i); + assert_eq!(q.capacity(), i); + } +} + +#[test] +#[should_panic(expected = "capacity must be non-zero")] +fn zero_capacity() { + let _ = ArrayQueue::::new(0); +} + +#[test] +fn len_empty_full() { + let q = ArrayQueue::new(2); + + assert_eq!(q.len(), 0); + assert_eq!(q.is_empty(), true); + assert_eq!(q.is_full(), false); + + q.push(()).unwrap(); + + assert_eq!(q.len(), 1); + assert_eq!(q.is_empty(), false); + assert_eq!(q.is_full(), false); + + q.push(()).unwrap(); + + assert_eq!(q.len(), 2); + assert_eq!(q.is_empty(), false); + assert_eq!(q.is_full(), true); + + q.pop().unwrap(); + + assert_eq!(q.len(), 1); + assert_eq!(q.is_empty(), false); + assert_eq!(q.is_full(), false); +} + +#[test] +fn len() { + const COUNT: usize = 25_000; + const CAP: usize = 1000; + + let q = ArrayQueue::new(CAP); + assert_eq!(q.len(), 0); + + for _ in 0..CAP / 10 { + for i in 0..50 { + q.push(i).unwrap(); + assert_eq!(q.len(), i + 1); + } + + for i in 0..50 { + q.pop().unwrap(); + assert_eq!(q.len(), 50 - i - 1); + } + } + assert_eq!(q.len(), 0); + + for i in 0..CAP { + q.push(i).unwrap(); + assert_eq!(q.len(), i + 1); + } + + for _ in 0..CAP { + q.pop().unwrap(); + } + assert_eq!(q.len(), 0); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..COUNT { + loop { + if let Ok(x) = q.pop() { + assert_eq!(x, i); + break; + } + } + let len = q.len(); + assert!(len <= CAP); + } + }); + + scope.spawn(|_| { + for i in 0..COUNT { + while q.push(i).is_err() {} + let len = q.len(); + assert!(len <= CAP); + } + }); + }) + .unwrap(); + assert_eq!(q.len(), 0); +} + +#[test] +fn spsc() { + const COUNT: usize = 100_000; + + let q = ArrayQueue::new(3); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..COUNT { + loop { + if let Ok(x) = q.pop() { + assert_eq!(x, i); + break; + } + } + } + assert!(q.pop().is_err()); + }); + + scope.spawn(|_| { + for i in 0..COUNT { + while q.push(i).is_err() {} + } + }); + }) + .unwrap(); +} + +#[test] +fn mpmc() { + const COUNT: usize = 25_000; + const THREADS: usize = 4; + + let q = ArrayQueue::::new(3); + let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); + + scope(|scope| { + for _ in 0..THREADS { + scope.spawn(|_| { + for _ in 0..COUNT { + let n = loop { + if let Ok(x) = q.pop() { + break x; + } + }; + v[n].fetch_add(1, Ordering::SeqCst); + } + }); + } + for _ in 0..THREADS { + scope.spawn(|_| { + for i in 0..COUNT { + while q.push(i).is_err() {} + } + }); + } + }) + .unwrap(); + + for c in v { + assert_eq!(c.load(Ordering::SeqCst), THREADS); + } +} + +#[test] +fn drops() { + const RUNS: usize = 100; + + static DROPS: AtomicUsize = AtomicUsize::new(0); + + #[derive(Debug, PartialEq)] + struct DropCounter; + + impl Drop for DropCounter { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + let mut rng = thread_rng(); + + for _ in 0..RUNS { + let steps = rng.gen_range(0, 10_000); + let additional = rng.gen_range(0, 50); + + DROPS.store(0, Ordering::SeqCst); + let q = ArrayQueue::new(50); + + scope(|scope| { + scope.spawn(|_| { + for _ in 0..steps { + while q.pop().is_err() {} + } + }); + + scope.spawn(|_| { + for _ in 0..steps { + while q.push(DropCounter).is_err() { + DROPS.fetch_sub(1, Ordering::SeqCst); + } + } + }); + }) + .unwrap(); + + for _ in 0..additional { + q.push(DropCounter).unwrap(); + } + + assert_eq!(DROPS.load(Ordering::SeqCst), steps); + drop(q); + assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional); + } +} + +#[test] +fn linearizable() { + const COUNT: usize = 25_000; + const THREADS: usize = 4; + + let q = ArrayQueue::new(THREADS); + + scope(|scope| { + for _ in 0..THREADS { + scope.spawn(|_| { + for _ in 0..COUNT { + while q.push(0).is_err() {} + q.pop().unwrap(); + } + }); + } + }) + .unwrap(); +} diff --git a/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/seg_queue.rs b/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/seg_queue.rs new file mode 100644 index 0000000..ec32e1f --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-queue-0.2.1/tests/seg_queue.rs @@ -0,0 +1,167 @@ +extern crate crossbeam_queue; +extern crate crossbeam_utils; +extern crate rand; + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crossbeam_queue::SegQueue; +use crossbeam_utils::thread::scope; +use rand::{thread_rng, Rng}; + +#[test] +fn smoke() { + let q = SegQueue::new(); + q.push(7); + assert_eq!(q.pop(), Ok(7)); + + q.push(8); + assert_eq!(q.pop(), Ok(8)); + assert!(q.pop().is_err()); +} + +#[test] +fn len_empty_full() { + let q = SegQueue::new(); + + assert_eq!(q.len(), 0); + assert_eq!(q.is_empty(), true); + + q.push(()); + + assert_eq!(q.len(), 1); + assert_eq!(q.is_empty(), false); + + q.pop().unwrap(); + + assert_eq!(q.len(), 0); + assert_eq!(q.is_empty(), true); +} + +#[test] +fn len() { + let q = SegQueue::new(); + + assert_eq!(q.len(), 0); + + for i in 0..50 { + q.push(i); + assert_eq!(q.len(), i + 1); + } + + for i in 0..50 { + q.pop().unwrap(); + assert_eq!(q.len(), 50 - i - 1); + } + + assert_eq!(q.len(), 0); +} + +#[test] +fn spsc() { + const COUNT: usize = 100_000; + + let q = SegQueue::new(); + + scope(|scope| { + scope.spawn(|_| { + for i in 0..COUNT { + loop { + if let Ok(x) = q.pop() { + assert_eq!(x, i); + break; + } + } + } + assert!(q.pop().is_err()); + }); + scope.spawn(|_| { + for i in 0..COUNT { + q.push(i); + } + }); + }) + .unwrap(); +} + +#[test] +fn mpmc() { + const COUNT: usize = 25_000; + const THREADS: usize = 4; + + let q = SegQueue::::new(); + let v = (0..COUNT).map(|_| AtomicUsize::new(0)).collect::>(); + + scope(|scope| { + for _ in 0..THREADS { + scope.spawn(|_| { + for _ in 0..COUNT { + let n = loop { + if let Ok(x) = q.pop() { + break x; + } + }; + v[n].fetch_add(1, Ordering::SeqCst); + } + }); + } + for _ in 0..THREADS { + scope.spawn(|_| { + for i in 0..COUNT { + q.push(i); + } + }); + } + }) + .unwrap(); + + for c in v { + assert_eq!(c.load(Ordering::SeqCst), THREADS); + } +} + +#[test] +fn drops() { + static DROPS: AtomicUsize = AtomicUsize::new(0); + + #[derive(Debug, PartialEq)] + struct DropCounter; + + impl Drop for DropCounter { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::SeqCst); + } + } + + let mut rng = thread_rng(); + + for _ in 0..100 { + let steps = rng.gen_range(0, 10_000); + let additional = rng.gen_range(0, 1000); + + DROPS.store(0, Ordering::SeqCst); + let q = SegQueue::new(); + + scope(|scope| { + scope.spawn(|_| { + for _ in 0..steps { + while q.pop().is_err() {} + } + }); + + scope.spawn(|_| { + for _ in 0..steps { + q.push(DropCounter); + } + }); + }) + .unwrap(); + + for _ in 0..additional { + q.push(DropCounter); + } + + assert_eq!(DROPS.load(Ordering::SeqCst), steps); + drop(q); + assert_eq!(DROPS.load(Ordering::SeqCst), steps + additional); + } +} diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-utils-0.6.6/.cargo-checksum.json deleted file mode 100644 index b100cb8..0000000 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"cb975f0361e0cccfe00da4f32d4c87308b20e40f6444d2ef474640fbb15567de","Cargo.toml":"8ad804e9e161a564e57e2cea30349d9658fd3d32bd0b065868073cdcc70a78cb","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"0b293d1b9b129a58f504ff4bc061161ddfaf7c8594e0ca2b526458d4e9acb194","benches/atomic_cell.rs":"fa38d34ddc593bf0999fd65d95ee349c53a11290fbe7bf24870a7e24754ae2ac","src/atomic/atomic_cell.rs":"9f18d8cf7d91750f7646bc2ef7bf5b7444b2c9acdc2e8b6dffd8f0ff696e113b","src/atomic/consume.rs":"bfdc7e2d8370a5a3bb1699b6214347c359d66fcc92a2d1345a513676ac91d821","src/atomic/mod.rs":"404eacae422012f3628cb44262df73a5891fe02a17ab345b832e3062982b5a20","src/backoff.rs":"bc9d2afdd070e0746bc48ff2159bf47b0cfaa68ea09f47eaed18ccc32fc87d67","src/cache_padded.rs":"864f210089eddfd130830f5c700115c2f8b974b71659d7e8ef7bd5e09d7e1f96","src/lib.rs":"3138911610fa97a412c62e4aa5a6cd50524a04f6746c08a5cda8fd1c1d954555","src/sync/mod.rs":"4c8ad6ec4601f212791b0b531b46ee5decec2f1d14746aa7f2c18e36c609cd8e","src/sync/parker.rs":"55324bbea5b7c6838a0f8467a5b8a5dbd5526c8e1c7fd4f6d64dad1ab19f9be9","src/sync/sharded_lock.rs":"7a401ba621233732c26cf49324748269359d7bc5dc27e0ec26c9493e9a5ec97d","src/sync/wait_group.rs":"21708bbd46daa98e9f788765a9a4ef3b087a8d1e97a6e9406b4a960c95e44ca0","src/thread.rs":"ee89256b619c7ed55e04519bb3b9f29e72e6ce1e61e8ba9782a984f5e9fc1bad","tests/atomic_cell.rs":"4423b41f6f23ff2519f4a1f9970436b7fb49968be5bc14dbdbd5ab2d5b1048df","tests/cache_padded.rs":"02235757a554279dae5053d46314a765059ec036c63a05336353994c2aa344d1","tests/parker.rs":"3e5c4e170cebdd9f815f2b31a2b6a01da753fc03e2b1d8e9b899d009f62c6b83","tests/sharded_lock.rs":"3b42218397f1260bed4e0a229f55da83439c0ec9effbbefc86251c9d208979bb","tests/thread.rs":"42baefda11ccd87d9fe1a93bb7d6186b17a86afcf3b9d8f739bc0deefa11ae0f","tests/wait_group.rs":"e3d5168581fb511b760f4249ca487b919cffc60ac2b4610a78db99899772dd5b"},"package":"04973fa96e96579258a5091af6003abde64af786b860f18622b82e026cca60e6"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/mod.rs b/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/mod.rs deleted file mode 100644 index 4205993..0000000 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Atomic types. - -mod atomic_cell; -mod consume; - -pub use self::atomic_cell::AtomicCell; -pub use self::consume::AtomicConsume; diff --git a/third_party/cargo/vendor/crossbeam-utils-0.7.2/.cargo-checksum.json b/third_party/cargo/vendor/crossbeam-utils-0.7.2/.cargo-checksum.json new file mode 100644 index 0000000..47f9d2b --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"ed7fb11c83cc30f6e7af6a42cae2cb087276ba1668da98268c86fccf9069baa7","Cargo.toml":"3c1187fa9a66336c9c959c87c6ad499f6a6adabb6a10506abaf6ed53e02d57cb","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5734ed989dfca1f625b40281ee9f4530f91b2411ec01cb748223e7eb87e201ab","README.md":"9010e511423b1159a33c84433d9e6cb8df1d08938e4d6cc8656bcec9bdde0eb8","benches/atomic_cell.rs":"fa38d34ddc593bf0999fd65d95ee349c53a11290fbe7bf24870a7e24754ae2ac","build.rs":"1ceb20e3c4e089a4dbf326df7924643be0bd6d50512b0b0a0729dbb30522eba8","src/atomic/atomic_cell.rs":"49b8a014e7009292c1eb3b241c2120a661bffcc40bf7b9de83dbb6928b5315b4","src/atomic/consume.rs":"bfdc7e2d8370a5a3bb1699b6214347c359d66fcc92a2d1345a513676ac91d821","src/atomic/mod.rs":"6c3efec60aee6a2e68dfa6fe3c059beab8429c150459ce5cfc736e8b5f95301e","src/atomic/seq_lock.rs":"4797f76beb0ec3eb363c2d49e9548adc8d042867b1602c1b8ca6269463d84e82","src/atomic/seq_lock_wide.rs":"4b2eb90599fbf548e79b8da5e2533d6f7c133245ae8dd48353ef52b1d2aa17f0","src/backoff.rs":"bc9d2afdd070e0746bc48ff2159bf47b0cfaa68ea09f47eaed18ccc32fc87d67","src/cache_padded.rs":"864f210089eddfd130830f5c700115c2f8b974b71659d7e8ef7bd5e09d7e1f96","src/lib.rs":"63096ede0c6ccdee05e910c2cce41da6df283868b658f9aa18c8fba8ac0f901d","src/sync/mod.rs":"02a7cc2a5ebb988a86aeebf7a40752f595e5eb494750e63cdbefd71c4643e2a3","src/sync/parker.rs":"442d8814339fdd9d7074e7e00695c64e6bbb62a2b0c1c8c1e0f4a471c25ccbbd","src/sync/sharded_lock.rs":"756a27476cbbdb03629a18d5b82c6153f7f168d8ef28f0fa17daf103affcc013","src/sync/wait_group.rs":"319611cfba289e272d38bdc9624ce110e37db5ffa2644d23dc330edc153850f0","src/thread.rs":"81f6ee718c5251083024583d351a1713cb6a850c284f68e5fa8a35d2ed4b33ba","tests/atomic_cell.rs":"945885f96d6a5971d6bfbd27ec8da79d337558373a631ffe2c83c6851da360e7","tests/cache_padded.rs":"02235757a554279dae5053d46314a765059ec036c63a05336353994c2aa344d1","tests/parker.rs":"3e5c4e170cebdd9f815f2b31a2b6a01da753fc03e2b1d8e9b899d009f62c6b83","tests/sharded_lock.rs":"3b42218397f1260bed4e0a229f55da83439c0ec9effbbefc86251c9d208979bb","tests/thread.rs":"4be7b293b5f13d7a158a231ba7f7b086bd8fe19aaf11b1c9a8a6cdf7bba6fdfc","tests/wait_group.rs":"e3d5168581fb511b760f4249ca487b919cffc60ac2b4610a78db99899772dd5b"},"package":"c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8"} \ No newline at end of file diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/BUILD b/third_party/cargo/vendor/crossbeam-utils-0.7.2/BUILD similarity index 93% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/BUILD rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/BUILD index 4f69595..d3940a4 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/BUILD +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/BUILD @@ -25,6 +25,7 @@ load( # Unsupported target "atomic_cell" with type "bench" omitted # Unsupported target "atomic_cell" with type "test" omitted +# Unsupported target "build-script-build" with type "custom-build" omitted # Unsupported target "cache_padded" with type "test" omitted rust_library( @@ -40,7 +41,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.6.6", + version = "0.7.2", crate_features = [ "default", "lazy_static", diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/CHANGELOG.md b/third_party/cargo/vendor/crossbeam-utils-0.7.2/CHANGELOG.md similarity index 83% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/CHANGELOG.md rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/CHANGELOG.md index 6e21023..d5fee12 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/CHANGELOG.md +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/CHANGELOG.md @@ -1,3 +1,19 @@ +# Version 0.7.2 + +- Fix bug in release (yanking 0.7.1) + +# Version 0.7.1 + +- Bump `autocfg` dependency to version 1.0. (#460) +- Make `AtomicCell` lockfree for u8, u16, u32, u64 sized values at 1.34+. (#454) + +# Version 0.7.0 + +- Bump the minimum required version to 1.28. +- Fix breakage with nightly feature due to rust-lang/rust#65214. +- Apply `#[repr(transparent)]` to `AtomicCell`. +- Make `AtomicCell::new()` const function at 1.31+. + # Version 0.6.6 - Add `UnwindSafe` and `RefUnwindSafe` impls for `AtomicCell`. @@ -30,7 +46,7 @@ - Fix a soundness bug in `Scope::spawn()`. - Remove the `T: 'scope` bound on `ScopedJoinHandle`. - + # Version 0.6.0 - Move `AtomicConsume` to `atomic` module. diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/Cargo.toml b/third_party/cargo/vendor/crossbeam-utils-0.7.2/Cargo.toml similarity index 95% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/Cargo.toml rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/Cargo.toml index 1dbd675..372e06f 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/Cargo.toml +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "crossbeam-utils" -version = "0.6.6" +version = "0.7.2" authors = ["The Crossbeam Project Developers"] description = "Utilities for concurrent programming" homepage = "https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-utils" @@ -30,6 +30,8 @@ version = "1.1.0" optional = true [dev-dependencies.rand] version = "0.6" +[build-dependencies.autocfg] +version = "1" [features] alloc = [] diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/LICENSE-APACHE b/third_party/cargo/vendor/crossbeam-utils-0.7.2/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/LICENSE-APACHE rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/LICENSE-APACHE diff --git a/third_party/cargo/vendor/arrayvec-0.4.12/LICENSE-MIT b/third_party/cargo/vendor/crossbeam-utils-0.7.2/LICENSE-MIT similarity index 93% rename from third_party/cargo/vendor/arrayvec-0.4.12/LICENSE-MIT rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/LICENSE-MIT index 2c8f27d..068d491 100644 --- a/third_party/cargo/vendor/arrayvec-0.4.12/LICENSE-MIT +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/LICENSE-MIT @@ -1,4 +1,6 @@ -Copyright (c) Ulrik Sverdrup "bluss" 2015-2017 +The MIT License (MIT) + +Copyright (c) 2019 The Crossbeam Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/README.md b/third_party/cargo/vendor/crossbeam-utils-0.7.2/README.md similarity index 93% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/README.md rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/README.md index b4a0f6b..ffb1ab4 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/README.md +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/README.md @@ -8,7 +8,7 @@ https://github.com/crossbeam-rs/crossbeam-utils/tree/master/src) https://crates.io/crates/crossbeam-utils) [![Documentation](https://docs.rs/crossbeam-utils/badge.svg)]( https://docs.rs/crossbeam-utils) -[![Rust 1.26+](https://img.shields.io/badge/rust-1.26+-lightgray.svg)]( +[![Rust 1.28+](https://img.shields.io/badge/rust-1.28+-lightgray.svg)]( https://www.rust-lang.org) [![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.gg/BBYwKq) @@ -48,7 +48,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -crossbeam-utils = "0.6" +crossbeam-utils = "0.7" ``` Next, add this to your crate: @@ -57,6 +57,10 @@ Next, add this to your crate: extern crate crossbeam_utils; ``` +## Compatibility + +The minimum supported Rust version is 1.28. Any change to this is considered a breaking change. + ## License Licensed under either of diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/benches/atomic_cell.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/benches/atomic_cell.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/benches/atomic_cell.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/benches/atomic_cell.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.7.2/build.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/build.rs new file mode 100644 index 0000000..2f5012a --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/build.rs @@ -0,0 +1,14 @@ +extern crate autocfg; + +fn main() { + let cfg = autocfg::new(); + if cfg.probe_rustc_version(1, 31) { + autocfg::emit("has_min_const_fn"); + } + + cfg.emit_type_cfg("core::sync::atomic::AtomicU8", "has_atomic_u8"); + cfg.emit_type_cfg("core::sync::atomic::AtomicU16", "has_atomic_u16"); + cfg.emit_type_cfg("core::sync::atomic::AtomicU32", "has_atomic_u32"); + cfg.emit_type_cfg("core::sync::atomic::AtomicU64", "has_atomic_u64"); + cfg.emit_type_cfg("core::sync::atomic::AtomicU128", "has_atomic_u128"); +} diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/atomic_cell.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/atomic_cell.rs similarity index 85% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/atomic_cell.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/atomic_cell.rs index f3118ec..cf0658a 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/atomic_cell.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/atomic_cell.rs @@ -2,12 +2,12 @@ use core::cell::UnsafeCell; use core::fmt; use core::mem; use core::ptr; -use core::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; +use core::sync::atomic::{self, AtomicBool, Ordering}; #[cfg(feature = "std")] use std::panic::{RefUnwindSafe, UnwindSafe}; -use Backoff; +use super::seq_lock::SeqLock; /// A thread-safe mutable memory location. /// @@ -23,8 +23,7 @@ use Backoff; /// [`AtomicCell::::is_lock_free()`]: struct.AtomicCell.html#method.is_lock_free /// [`Acquire`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html#variant.Acquire /// [`Release`]: https://doc.rust-lang.org/std/sync/atomic/enum.Ordering.html#variant.Release -// TODO(@jeehoonkang): when the minimum supported Rust version is bumped to 1.28+, apply the -// attribute `#[repr(transparent)]`. +#[repr(transparent)] pub struct AtomicCell { /// The inner value. /// @@ -52,12 +51,29 @@ impl AtomicCell { /// /// let a = AtomicCell::new(7); /// ``` + #[cfg(not(has_min_const_fn))] pub fn new(val: T) -> AtomicCell { AtomicCell { value: UnsafeCell::new(val), } } + /// Creates a new atomic cell initialized with `val`. + /// + /// # Examples + /// + /// ``` + /// use crossbeam_utils::atomic::AtomicCell; + /// + /// let a = AtomicCell::new(7); + /// ``` + #[cfg(has_min_const_fn)] + pub const fn new(val: T) -> AtomicCell { + AtomicCell { + value: UnsafeCell::new(val), + } + } + /// Unwraps the atomic cell and returns its inner value. /// /// # Examples @@ -503,37 +519,28 @@ macro_rules! impl_arithmetic { } } }; - ($t:ty, $size:tt, $atomic:ty, $example:tt) => { - #[cfg(target_has_atomic = $size)] - impl_arithmetic!($t, $atomic, $example); - }; } -cfg_if! { - if #[cfg(feature = "nightly")] { - impl_arithmetic!(u8, "8", atomic::AtomicU8, "let a = AtomicCell::new(7u8);"); - impl_arithmetic!(i8, "8", atomic::AtomicI8, "let a = AtomicCell::new(7i8);"); - impl_arithmetic!(u16, "16", atomic::AtomicU16, "let a = AtomicCell::new(7u16);"); - impl_arithmetic!(i16, "16", atomic::AtomicI16, "let a = AtomicCell::new(7i16);"); - impl_arithmetic!(u32, "32", atomic::AtomicU32, "let a = AtomicCell::new(7u32);"); - impl_arithmetic!(i32, "32", atomic::AtomicI32, "let a = AtomicCell::new(7i32);"); - impl_arithmetic!(u64, "64", atomic::AtomicU64, "let a = AtomicCell::new(7u64);"); - impl_arithmetic!(i64, "64", atomic::AtomicI64, "let a = AtomicCell::new(7i64);"); - impl_arithmetic!(u128, "let a = AtomicCell::new(7u128);"); - impl_arithmetic!(i128, "let a = AtomicCell::new(7i128);"); - } else { - impl_arithmetic!(u8, "let a = AtomicCell::new(7u8);"); - impl_arithmetic!(i8, "let a = AtomicCell::new(7i8);"); - impl_arithmetic!(u16, "let a = AtomicCell::new(7u16);"); - impl_arithmetic!(i16, "let a = AtomicCell::new(7i16);"); - impl_arithmetic!(u32, "let a = AtomicCell::new(7u32);"); - impl_arithmetic!(i32, "let a = AtomicCell::new(7i32);"); - impl_arithmetic!(u64, "let a = AtomicCell::new(7u64);"); - impl_arithmetic!(i64, "let a = AtomicCell::new(7i64);"); - impl_arithmetic!(u128, "let a = AtomicCell::new(7u128);"); - impl_arithmetic!(i128, "let a = AtomicCell::new(7i128);"); - } -} +#[cfg(has_atomic_u8)] +impl_arithmetic!(u8, atomic::AtomicU8, "let a = AtomicCell::new(7u8);"); +#[cfg(has_atomic_u8)] +impl_arithmetic!(i8, atomic::AtomicI8, "let a = AtomicCell::new(7i8);"); +#[cfg(has_atomic_u16)] +impl_arithmetic!(u16, atomic::AtomicU16, "let a = AtomicCell::new(7u16);"); +#[cfg(has_atomic_u16)] +impl_arithmetic!(i16, atomic::AtomicI16, "let a = AtomicCell::new(7i16);"); +#[cfg(has_atomic_u32)] +impl_arithmetic!(u32, atomic::AtomicU32, "let a = AtomicCell::new(7u32);"); +#[cfg(has_atomic_u32)] +impl_arithmetic!(i32, atomic::AtomicI32, "let a = AtomicCell::new(7i32);"); +#[cfg(has_atomic_u64)] +impl_arithmetic!(u64, atomic::AtomicU64, "let a = AtomicCell::new(7u64);"); +#[cfg(has_atomic_u64)] +impl_arithmetic!(i64, atomic::AtomicI64, "let a = AtomicCell::new(7i64);"); +#[cfg(has_atomic_u128)] +impl_arithmetic!(u128, atomic::AtomicU128, "let a = AtomicCell::new(7u128);"); +#[cfg(has_atomic_u128)] +impl_arithmetic!(i128, atomic::AtomicI128, "let a = AtomicCell::new(7i128);"); impl_arithmetic!( usize, @@ -631,87 +638,6 @@ fn can_transmute() -> bool { mem::size_of::() == mem::size_of::() && mem::align_of::() >= mem::align_of::() } -/// A simple stamped lock. -struct Lock { - /// The current state of the lock. - /// - /// All bits except the least significant one hold the current stamp. When locked, the state - /// equals 1 and doesn't contain a valid stamp. - state: AtomicUsize, -} - -impl Lock { - /// If not locked, returns the current stamp. - /// - /// This method should be called before optimistic reads. - #[inline] - fn optimistic_read(&self) -> Option { - let state = self.state.load(Ordering::Acquire); - if state == 1 { - None - } else { - Some(state) - } - } - - /// Returns `true` if the current stamp is equal to `stamp`. - /// - /// This method should be called after optimistic reads to check whether they are valid. The - /// argument `stamp` should correspond to the one returned by method `optimistic_read`. - #[inline] - fn validate_read(&self, stamp: usize) -> bool { - atomic::fence(Ordering::Acquire); - self.state.load(Ordering::Relaxed) == stamp - } - - /// Grabs the lock for writing. - #[inline] - fn write(&'static self) -> WriteGuard { - let backoff = Backoff::new(); - loop { - let previous = self.state.swap(1, Ordering::Acquire); - - if previous != 1 { - atomic::fence(Ordering::Release); - - return WriteGuard { - lock: self, - state: previous, - }; - } - - backoff.snooze(); - } - } -} - -/// A RAII guard that releases the lock and increments the stamp when dropped. -struct WriteGuard { - /// The parent lock. - lock: &'static Lock, - - /// The stamp before locking. - state: usize, -} - -impl WriteGuard { - /// Releases the lock without incrementing the stamp. - #[inline] - fn abort(self) { - self.lock.state.store(self.state, Ordering::Release); - } -} - -impl Drop for WriteGuard { - #[inline] - fn drop(&mut self) { - // Release the lock and increment the stamp. - self.lock - .state - .store(self.state.wrapping_add(2), Ordering::Release); - } -} - /// Returns a reference to the global lock associated with the `AtomicCell` at address `addr`. /// /// This function is used to protect atomic data which doesn't fit into any of the primitive atomic @@ -722,7 +648,7 @@ impl Drop for WriteGuard { /// scalability. #[inline] #[must_use] -fn lock(addr: usize) -> &'static Lock { +fn lock(addr: usize) -> &'static SeqLock { // The number of locks is a prime number because we want to make sure `addr % LEN` gets // dispersed across all locks. // @@ -747,10 +673,9 @@ fn lock(addr: usize) -> &'static Lock { // In order to protect from such cases, we simply choose a large prime number for `LEN`. const LEN: usize = 97; - const L: Lock = Lock { - state: AtomicUsize::new(0), - }; - static LOCKS: [Lock; LEN] = [ + const L: SeqLock = SeqLock::INIT; + + static LOCKS: [SeqLock; LEN] = [ L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, L, @@ -807,17 +732,14 @@ macro_rules! atomic { atomic!(@check, $t, AtomicUnit, $a, $atomic_op); atomic!(@check, $t, atomic::AtomicUsize, $a, $atomic_op); - #[cfg(feature = "nightly")] - { - #[cfg(target_has_atomic = "8")] - atomic!(@check, $t, atomic::AtomicU8, $a, $atomic_op); - #[cfg(target_has_atomic = "16")] - atomic!(@check, $t, atomic::AtomicU16, $a, $atomic_op); - #[cfg(target_has_atomic = "32")] - atomic!(@check, $t, atomic::AtomicU32, $a, $atomic_op); - #[cfg(target_has_atomic = "64")] - atomic!(@check, $t, atomic::AtomicU64, $a, $atomic_op); - } + #[cfg(has_atomic_u8)] + atomic!(@check, $t, atomic::AtomicU8, $a, $atomic_op); + #[cfg(has_atomic_u16)] + atomic!(@check, $t, atomic::AtomicU16, $a, $atomic_op); + #[cfg(has_atomic_u32)] + atomic!(@check, $t, atomic::AtomicU32, $a, $atomic_op); + #[cfg(has_atomic_u64)] + atomic!(@check, $t, atomic::AtomicU64, $a, $atomic_op); break $fallback_op; } diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/consume.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/consume.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/atomic/consume.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/consume.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/mod.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/mod.rs new file mode 100644 index 0000000..074b0ca --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/mod.rs @@ -0,0 +1,25 @@ +//! Atomic types. + +cfg_if! { + // Use "wide" sequence lock if the pointer width <= 32 for preventing its counter against wrap + // around. + // + // We are ignoring too wide architectures (pointer width >= 256), since such a system will not + // appear in a conceivable future. + // + // In narrow architectures (pointer width <= 16), the counter is still <= 32-bit and may be + // vulnerable to wrap around. But it's mostly okay, since in such a primitive hardware, the + // counter will not be increased that fast. + if #[cfg(any(target_pointer_width = "64", target_pointer_width = "128"))] { + mod seq_lock; + } else { + #[path = "seq_lock_wide.rs"] + mod seq_lock; + } +} + +mod atomic_cell; +mod consume; + +pub use self::atomic_cell::AtomicCell; +pub use self::consume::AtomicConsume; diff --git a/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock.rs new file mode 100644 index 0000000..533a036 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock.rs @@ -0,0 +1,88 @@ +use core::sync::atomic::{self, AtomicUsize, Ordering}; + +use Backoff; + +/// A simple stamped lock. +pub struct SeqLock { + /// The current state of the lock. + /// + /// All bits except the least significant one hold the current stamp. When locked, the state + /// equals 1 and doesn't contain a valid stamp. + state: AtomicUsize, +} + +impl SeqLock { + pub const INIT: Self = Self { + state: AtomicUsize::new(0), + }; + + /// If not locked, returns the current stamp. + /// + /// This method should be called before optimistic reads. + #[inline] + pub fn optimistic_read(&self) -> Option { + let state = self.state.load(Ordering::Acquire); + if state == 1 { + None + } else { + Some(state) + } + } + + /// Returns `true` if the current stamp is equal to `stamp`. + /// + /// This method should be called after optimistic reads to check whether they are valid. The + /// argument `stamp` should correspond to the one returned by method `optimistic_read`. + #[inline] + pub fn validate_read(&self, stamp: usize) -> bool { + atomic::fence(Ordering::Acquire); + self.state.load(Ordering::Relaxed) == stamp + } + + /// Grabs the lock for writing. + #[inline] + pub fn write(&'static self) -> SeqLockWriteGuard { + let backoff = Backoff::new(); + loop { + let previous = self.state.swap(1, Ordering::Acquire); + + if previous != 1 { + atomic::fence(Ordering::Release); + + return SeqLockWriteGuard { + lock: self, + state: previous, + }; + } + + backoff.snooze(); + } + } +} + +/// An RAII guard that releases the lock and increments the stamp when dropped. +pub struct SeqLockWriteGuard { + /// The parent lock. + lock: &'static SeqLock, + + /// The stamp before locking. + state: usize, +} + +impl SeqLockWriteGuard { + /// Releases the lock without incrementing the stamp. + #[inline] + pub fn abort(self) { + self.lock.state.store(self.state, Ordering::Release); + } +} + +impl Drop for SeqLockWriteGuard { + #[inline] + fn drop(&mut self) { + // Release the lock and increment the stamp. + self.lock + .state + .store(self.state.wrapping_add(2), Ordering::Release); + } +} diff --git a/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock_wide.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock_wide.rs new file mode 100644 index 0000000..857c074 --- /dev/null +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/atomic/seq_lock_wide.rs @@ -0,0 +1,134 @@ +use core::sync::atomic::{self, AtomicUsize, Ordering}; + +use Backoff; + +/// A simple stamped lock. +/// +/// The state is represented as two `AtomicUsize`: `state_hi` for high bits and `state_lo` for low +/// bits. +pub struct SeqLock { + /// The high bits of the current state of the lock. + state_hi: AtomicUsize, + + /// The low bits of the current state of the lock. + /// + /// All bits except the least significant one hold the current stamp. When locked, the state_lo + /// equals 1 and doesn't contain a valid stamp. + state_lo: AtomicUsize, +} + +impl SeqLock { + pub const INIT: Self = Self { + state_hi: AtomicUsize::new(0), + state_lo: AtomicUsize::new(0), + }; + + /// If not locked, returns the current stamp. + /// + /// This method should be called before optimistic reads. + #[inline] + pub fn optimistic_read(&self) -> Option<(usize, usize)> { + // The acquire loads from `state_hi` and `state_lo` synchronize with the release stores in + // `SeqLockWriteGuard::drop`. + // + // As a consequence, we can make sure that (1) all writes within the era of `state_hi - 1` + // happens before now; and therefore, (2) if `state_lo` is even, all writes within the + // critical section of (`state_hi`, `state_lo`) happens before now. + let state_hi = self.state_hi.load(Ordering::Acquire); + let state_lo = self.state_lo.load(Ordering::Acquire); + if state_lo == 1 { + None + } else { + Some((state_hi, state_lo)) + } + } + + /// Returns `true` if the current stamp is equal to `stamp`. + /// + /// This method should be called after optimistic reads to check whether they are valid. The + /// argument `stamp` should correspond to the one returned by method `optimistic_read`. + #[inline] + pub fn validate_read(&self, stamp: (usize, usize)) -> bool { + // Thanks to the fence, if we're noticing any modification to the data at the critical + // section of `(a, b)`, then the critical section's write of 1 to state_lo should be + // visible. + atomic::fence(Ordering::Acquire); + + // So if `state_lo` coincides with `stamp.1`, then either (1) we're noticing no modification + // to the data after the critical section of `(stamp.0, stamp.1)`, or (2) `state_lo` wrapped + // around. + // + // If (2) is the case, the acquire ordering ensures we see the new value of `state_hi`. + let state_lo = self.state_lo.load(Ordering::Acquire); + + // If (2) is the case and `state_hi` coincides with `stamp.0`, then `state_hi` also wrapped + // around, which we give up to correctly validate the read. + let state_hi = self.state_hi.load(Ordering::Relaxed); + + // Except for the case that both `state_hi` and `state_lo` wrapped around, the following + // condition implies that we're noticing no modification to the data after the critical + // section of `(stamp.0, stamp.1)`. + (state_hi, state_lo) == stamp + } + + /// Grabs the lock for writing. + #[inline] + pub fn write(&'static self) -> SeqLockWriteGuard { + let backoff = Backoff::new(); + loop { + let previous = self.state_lo.swap(1, Ordering::Acquire); + + if previous != 1 { + // To synchronize with the acquire fence in `validate_read` via any modification to + // the data at the critical section of `(state_hi, previous)`. + atomic::fence(Ordering::Release); + + return SeqLockWriteGuard { + lock: self, + state_lo: previous, + }; + } + + backoff.snooze(); + } + } +} + +/// An RAII guard that releases the lock and increments the stamp when dropped. +pub struct SeqLockWriteGuard { + /// The parent lock. + lock: &'static SeqLock, + + /// The stamp before locking. + state_lo: usize, +} + +impl SeqLockWriteGuard { + /// Releases the lock without incrementing the stamp. + #[inline] + pub fn abort(self) { + self.lock.state_lo.store(self.state_lo, Ordering::Release); + } +} + +impl Drop for SeqLockWriteGuard { + #[inline] + fn drop(&mut self) { + let state_lo = self.state_lo.wrapping_add(2); + + // Increase the high bits if the low bits wrap around. + // + // Release ordering for synchronizing with `optimistic_read`. + if state_lo == 0 { + let state_hi = self.lock.state_hi.load(Ordering::Relaxed); + self.lock + .state_hi + .store(state_hi.wrapping_add(1), Ordering::Release); + } + + // Release the lock and increment the stamp. + // + // Release ordering for synchronizing with `optimistic_read`. + self.lock.state_lo.store(state_lo, Ordering::Release); + } +} diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/backoff.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/backoff.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/backoff.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/backoff.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/cache_padded.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/cache_padded.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/cache_padded.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/cache_padded.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/lib.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/lib.rs similarity index 94% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/lib.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/lib.rs index 4df2ac8..06f23be 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/lib.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/lib.rs @@ -44,10 +44,7 @@ cfg_if! { } } -#[cfg_attr( - feature = "nightly", - cfg(all(target_has_atomic = "cas", target_has_atomic = "ptr")) -)] +#[cfg_attr(feature = "nightly", cfg(target_has_atomic = "ptr"))] pub mod atomic; mod cache_padded; diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/mod.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/mod.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/mod.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/mod.rs index 31c8ffe..3634963 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/mod.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/mod.rs @@ -12,6 +12,6 @@ mod parker; mod sharded_lock; mod wait_group; -pub use self::sharded_lock::{ShardedLock, ShardedLockReadGuard, ShardedLockWriteGuard}; pub use self::parker::{Parker, Unparker}; +pub use self::sharded_lock::{ShardedLock, ShardedLockReadGuard, ShardedLockWriteGuard}; pub use self::wait_group::WaitGroup; diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/parker.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/parker.rs similarity index 96% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/parker.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/parker.rs index 506db8e..051afe5 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/parker.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/parker.rs @@ -1,8 +1,8 @@ use std::fmt; use std::marker::PhantomData; -use std::sync::{Arc, Condvar, Mutex}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; +use std::sync::{Arc, Condvar, Mutex}; use std::time::Duration; /// A thread parking primitive. @@ -228,7 +228,11 @@ struct Inner { impl Inner { fn park(&self, timeout: Option) { // If we were previously notified then we consume this notification and return quickly. - if self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst).is_ok() { + if self + .state + .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) + .is_ok() + { return; } @@ -266,7 +270,7 @@ impl Inner { match self.state.compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst) { Ok(_) => return, // got a notification - Err(_) => {} // spurious wakeup, go back to sleep + Err(_) => {} // spurious wakeup, go back to sleep } } } @@ -278,7 +282,7 @@ impl Inner { match self.state.swap(EMPTY, SeqCst) { NOTIFIED => {} // got a notification - PARKED => {} // no notification + PARKED => {} // no notification n => panic!("inconsistent park_timeout state: {}", n), } } @@ -291,9 +295,9 @@ impl Inner { // `NOTIFIED` even if `state` is already `NOTIFIED`. That is why this must be a swap rather // than a compare-and-swap that returns if it reads `NOTIFIED` on failure. match self.state.swap(NOTIFIED, SeqCst) { - EMPTY => return, // no one was waiting + EMPTY => return, // no one was waiting NOTIFIED => return, // already unparked - PARKED => {} // gotta go wake someone up + PARKED => {} // gotta go wake someone up _ => panic!("inconsistent state in unpark"), } diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/sharded_lock.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/sharded_lock.rs similarity index 96% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/sharded_lock.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/sharded_lock.rs index 0fbb291..bd269d1 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/sharded_lock.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/sharded_lock.rs @@ -5,8 +5,8 @@ use std::marker::PhantomData; use std::mem; use std::ops::{Deref, DerefMut}; use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::sync::{LockResult, PoisonError, TryLockError, TryLockResult}; +use std::sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::thread::{self, ThreadId}; use CachePadded; @@ -99,10 +99,12 @@ impl ShardedLock { pub fn new(value: T) -> ShardedLock { ShardedLock { shards: (0..NUM_SHARDS) - .map(|_| CachePadded::new(Shard { - lock: RwLock::new(()), - write_guard: UnsafeCell::new(None), - })) + .map(|_| { + CachePadded::new(Shard { + lock: RwLock::new(()), + write_guard: UnsafeCell::new(None), + }) + }) .collect::>() .into_boxed_slice(), value: UnsafeCell::new(value), @@ -232,7 +234,7 @@ impl ShardedLock { _marker: PhantomData, }; Err(TryLockError::Poisoned(PoisonError::new(guard))) - }, + } Err(TryLockError::WouldBlock) => Err(TryLockError::WouldBlock), } } @@ -317,7 +319,7 @@ impl ShardedLock { Err(TryLockError::Poisoned(err)) => { poisoned = true; err.into_inner() - }, + } Err(TryLockError::WouldBlock) => { blocked = Some(i); break; @@ -416,10 +418,14 @@ impl ShardedLock { impl fmt::Debug for ShardedLock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.try_read() { - Ok(guard) => f.debug_struct("ShardedLock").field("data", &&*guard).finish(), - Err(TryLockError::Poisoned(err)) => { - f.debug_struct("ShardedLock").field("data", &&**err.get_ref()).finish() - }, + Ok(guard) => f + .debug_struct("ShardedLock") + .field("data", &&*guard) + .finish(), + Err(TryLockError::Poisoned(err)) => f + .debug_struct("ShardedLock") + .field("data", &&**err.get_ref()) + .finish(), Err(TryLockError::WouldBlock) => { struct LockedPlaceholder; impl fmt::Debug for LockedPlaceholder { @@ -427,7 +433,9 @@ impl fmt::Debug for ShardedLock { f.write_str("") } } - f.debug_struct("ShardedLock").field("data", &LockedPlaceholder).finish() + f.debug_struct("ShardedLock") + .field("data", &LockedPlaceholder) + .finish() } } } diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/wait_group.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/wait_group.rs similarity index 97% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/wait_group.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/wait_group.rs index 16ddc30..0527b31 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/sync/wait_group.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/sync/wait_group.rs @@ -132,8 +132,6 @@ impl Clone for WaitGroup { impl fmt::Debug for WaitGroup { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let count: &usize = &*self.inner.count.lock().unwrap(); - f.debug_struct("WaitGroup") - .field("count", count) - .finish() + f.debug_struct("WaitGroup").field("count", count).finish() } } diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/thread.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/thread.rs similarity index 98% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/src/thread.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/src/thread.rs index 2613fb7..a88c0f1 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/src/thread.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/src/thread.rs @@ -423,8 +423,8 @@ impl<'scope, 'env> ScopedThreadBuilder<'scope, 'env> { let closure = move || closure.take().unwrap()(); // Allocate `clsoure` on the heap and erase the `'env` bound. - let closure: Box = Box::new(closure); - let closure: Box = unsafe { mem::transmute(closure) }; + let closure: Box = Box::new(closure); + let closure: Box = unsafe { mem::transmute(closure) }; // Finally, spawn the closure. let mut closure = closure; diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/atomic_cell.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/atomic_cell.rs similarity index 89% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/atomic_cell.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/atomic_cell.rs index 9406192..e0b7db5 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/atomic_cell.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/atomic_cell.rs @@ -9,20 +9,19 @@ use crossbeam_utils::atomic::AtomicCell; fn is_lock_free() { struct UsizeWrap(usize); struct U8Wrap(bool); + struct I16Wrap(i16); assert_eq!(AtomicCell::::is_lock_free(), true); assert_eq!(AtomicCell::::is_lock_free(), true); assert_eq!(AtomicCell::::is_lock_free(), true); - assert_eq!(AtomicCell::::is_lock_free(), cfg!(feature = "nightly")); - assert_eq!( - AtomicCell::::is_lock_free(), - cfg!(feature = "nightly") - ); - assert_eq!( - AtomicCell::::is_lock_free(), - cfg!(feature = "nightly") - ); + assert_eq!(AtomicCell::::is_lock_free(), cfg!(has_atomic_u8)); + assert_eq!(AtomicCell::::is_lock_free(), cfg!(has_atomic_u8)); + assert_eq!(AtomicCell::::is_lock_free(), cfg!(has_atomic_u8)); + + assert_eq!(AtomicCell::::is_lock_free(), cfg!(has_atomic_u16)); + + assert_eq!(AtomicCell::::is_lock_free(), cfg!(has_atomic_u128)); } #[test] @@ -223,3 +222,12 @@ fn garbage_padding() { assert!(cell.compare_exchange(prev, next).is_ok()); println!(); } + +#[cfg(has_min_const_fn)] +#[test] +fn const_atomic_cell_new() { + static CELL: AtomicCell = AtomicCell::new(0); + + CELL.store(1); + assert_eq!(CELL.load(), 1); +} diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/cache_padded.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/cache_padded.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/cache_padded.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/cache_padded.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/parker.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/parker.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/parker.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/parker.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/sharded_lock.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/sharded_lock.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/sharded_lock.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/sharded_lock.rs diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/thread.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/thread.rs similarity index 97% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/thread.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/thread.rs index b691745..e55d90f 100644 --- a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/thread.rs +++ b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/thread.rs @@ -99,7 +99,7 @@ fn panic_twice() { let err = result.unwrap_err(); let vec = err - .downcast_ref::>>() + .downcast_ref::>>() .unwrap(); assert_eq!(2, vec.len()); @@ -119,7 +119,7 @@ fn panic_many() { let err = result.unwrap_err(); let vec = err - .downcast_ref::>>() + .downcast_ref::>>() .unwrap(); assert_eq!(3, vec.len()); diff --git a/third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/wait_group.rs b/third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/wait_group.rs similarity index 100% rename from third_party/cargo/vendor/crossbeam-utils-0.6.6/tests/wait_group.rs rename to third_party/cargo/vendor/crossbeam-utils-0.7.2/tests/wait_group.rs diff --git a/third_party/cargo/vendor/dispatch-0.2.0/.cargo-checksum.json b/third_party/cargo/vendor/dispatch-0.2.0/.cargo-checksum.json new file mode 100644 index 0000000..73c28ad --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"122b2c045123aa5f9c1d7452839a6f8e9b200323478e3699490b40ff1fd01ed3","Cargo.toml":"bd6cecbea33be54304d73d48e29182b4baff69695a25e68d7ac67ff3e69263a9","README.md":"9e581e0edb3dcc8238feda4bc709c8c91d43c286ac91f42cf6b0004c9335da58","examples/main.rs":"da1d4571dd62e1fcef114a68c15bd340dbb5e83b84391e3bbb7a13cd8e57e88a","src/ffi.rs":"320c101bdd43517d8cdb5663861733aa569705495ca97ab547571afcf2820b87","src/group.rs":"22d17cacb1401da31acfca71ce8cead89dfc728f1873de7192b000f1c7456707","src/lib.rs":"1f75d8f3bb8dbc57449c8727c68d7c75e6a5cf20347617c96ab6a608f186612b","src/once.rs":"b67a020f1ba3ebecf52f065cb058aba61d97b5b1155e6495e5b0fc0b996f7931","src/queue.rs":"efffe03ab4615c85f0708ed47b41973b2ccd4d578e146743b455986ffc95da87","src/sem.rs":"5d74917749799a8b3385bf694caf0c344a11e8a9363c4512a21d956bcf7a14ac"},"package":"bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"} \ No newline at end of file diff --git a/third_party/cargo/vendor/dispatch-0.2.0/BUILD b/third_party/cargo/vendor/dispatch-0.2.0/BUILD new file mode 100644 index 0000000..9652dce --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/BUILD @@ -0,0 +1,43 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "dispatch", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2018", + srcs = glob(["**/*.rs"]), + deps = [ + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.2.0", + crate_features = [ + ], +) + +# Unsupported target "main" with type "example" omitted diff --git a/third_party/cargo/vendor/dispatch-0.2.0/Cargo.lock b/third_party/cargo/vendor/dispatch-0.2.0/Cargo.lock new file mode 100644 index 0000000..0f8ed39 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/Cargo.lock @@ -0,0 +1,6 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "dispatch" +version = "0.2.0" + diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/Cargo.toml b/third_party/cargo/vendor/dispatch-0.2.0/Cargo.toml similarity index 57% rename from third_party/cargo/vendor/owning_ref-0.4.1/Cargo.toml rename to third_party/cargo/vendor/dispatch-0.2.0/Cargo.toml index 057fd5c..5da25a8 100644 --- a/third_party/cargo/vendor/owning_ref-0.4.1/Cargo.toml +++ b/third_party/cargo/vendor/dispatch-0.2.0/Cargo.toml @@ -11,14 +11,14 @@ # will likely look very different (and much more reasonable) [package] -name = "owning_ref" -version = "0.4.1" -authors = ["Marvin Löbel "] -description = "A library for creating references that carry their owner with them." -documentation = "http://kimundi.github.io/owning-ref-rs/owning_ref/index.html" +edition = "2018" +name = "dispatch" +version = "0.2.0" +authors = ["Steven Sheldon"] +exclude = [".gitignore", ".travis.yml", "travis_install.sh", "travis_test.sh", "tests-ios/**"] +description = "Rust wrapper for Apple's Grand Central Dispatch." +documentation = "http://ssheldon.github.io/rust-objc/dispatch/" readme = "README.md" -keywords = ["reference", "sibling", "field", "owning"] +keywords = ["gcd", "objective-c", "osx", "ios"] license = "MIT" -repository = "https://github.com/Kimundi/owning-ref-rs" -[dependencies.stable_deref_trait] -version = "1.0.0" +repository = "http://github.com/SSheldon/rust-dispatch" diff --git a/third_party/cargo/vendor/dispatch-0.2.0/README.md b/third_party/cargo/vendor/dispatch-0.2.0/README.md new file mode 100644 index 0000000..2a6d1a4 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/README.md @@ -0,0 +1,44 @@ +Rust wrapper for Apple's Grand Central Dispatch (GCD). + +GCD is an implementation of task parallelism that allows tasks to be submitted +to queues where they are scheduled to execute. + +For more information, see Apple's [Grand Central Dispatch reference]( +https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html). + +* Documentation: http://ssheldon.github.io/rust-objc/dispatch/ +* Crate: https://crates.io/crates/dispatch + +# Serial Queues + +Serial queues execute tasks serially in FIFO order. The application's main +queue is serial and can be accessed through the `Queue::main` function. + +``` rust +use dispatch::{Queue, QueueAttribute}; + +let queue = Queue::create("com.example.rust", QueueAttribute::Serial); +queue.async(|| println!("Hello")); +queue.async(|| println!("World")); +``` + +# Concurrent Queues + +Concurrent dispatch queues execute tasks concurrently. GCD provides global +concurrent queues that can be accessed through the `Queue::global` function. + +`Queue` has two methods that can simplify processing data in parallel, `foreach` +and `map`: + +``` rust +use dispatch::{Queue, QueuePriority}; + +let queue = Queue::global(QueuePriority::Default); + +let mut nums = vec![1, 2]; +queue.foreach(&mut nums, |x| *x += 1); +assert!(nums == [2, 3]); + +let nums = queue.map(nums, |x| x.to_string()); +assert!(nums[0] == "2"); +``` diff --git a/third_party/cargo/vendor/dispatch-0.2.0/examples/main.rs b/third_party/cargo/vendor/dispatch-0.2.0/examples/main.rs new file mode 100644 index 0000000..c92dcf1 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/examples/main.rs @@ -0,0 +1,51 @@ +extern crate dispatch; + +use std::io; +use std::process::exit; +use dispatch::{Queue, QueuePriority}; + +/// Prompts for a number and adds it to the given sum. +/// +/// Reading from stdin is done on the given queue. +/// All printing is performed on the main queue. +/// Repeats until the user stops entering numbers. +fn prompt(mut sum: i32, queue: Queue) { + queue.clone().exec_async(move || { + let main = Queue::main(); + // Print our prompt on the main thread and wait until it's complete + main.exec_sync(|| { + println!("Enter a number:"); + }); + + // Read the number the user enters + let mut input = String::new(); + io::stdin().read_line(&mut input).unwrap(); + + if let Ok(num) = input.trim().parse::() { + sum += num; + // Print the sum on the main thread and wait until it's complete + main.exec_sync(|| { + println!("Sum is {}\n", sum); + }); + // Do it again! + prompt(sum, queue); + } else { + // Bail if no number was entered + main.exec_async(|| { + println!("Not a number, exiting."); + exit(0); + }); + } + }); +} + +fn main() { + // Read from stdin on a background queue so that the main queue is free + // to handle other events. All printing still occurs through the main + // queue to avoid jumbled output. + prompt(0, Queue::global(QueuePriority::Default)); + + unsafe { + dispatch::ffi::dispatch_main(); + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/ffi.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/ffi.rs new file mode 100644 index 0000000..91dad6f --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/ffi.rs @@ -0,0 +1,173 @@ +#![allow(missing_docs)] +#![allow(non_camel_case_types)] + +use std::os::raw::{c_char, c_long, c_ulong, c_void}; + +#[repr(C)] +pub struct dispatch_object_s { _private: [u8; 0] } + +// dispatch_block_t +pub type dispatch_function_t = extern fn(*mut c_void); +pub type dispatch_semaphore_t = *mut dispatch_object_s; +pub type dispatch_group_t = *mut dispatch_object_s; +pub type dispatch_object_t = *mut dispatch_object_s; +pub type dispatch_once_t = c_long; +pub type dispatch_queue_t = *mut dispatch_object_s; +pub type dispatch_time_t = u64; +// dispatch_source_type_t +// dispatch_fd_t +// dispatch_data_t +// dispatch_data_applier_t +// dispatch_io_t +// dispatch_io_handler_t +// dispatch_io_type_t +// dispatch_io_close_flags_t +// dispatch_io_interval_flags_t +pub type dispatch_queue_attr_t = *const dispatch_object_s; + +#[cfg_attr(any(target_os = "macos", target_os = "ios"), + link(name = "System", kind = "dylib"))] +#[cfg_attr(not(any(target_os = "macos", target_os = "ios")), + link(name = "dispatch", kind = "dylib"))] +extern { + static _dispatch_main_q: dispatch_object_s; + static _dispatch_queue_attr_concurrent: dispatch_object_s; + + pub fn dispatch_get_global_queue(identifier: c_long, flags: c_ulong) -> dispatch_queue_t; + pub fn dispatch_queue_create(label: *const c_char, attr: dispatch_queue_attr_t) -> dispatch_queue_t; + // dispatch_queue_attr_t dispatch_queue_attr_make_with_qos_class ( dispatch_queue_attr_t attr, dispatch_qos_class_t qos_class, int relative_priority ); + pub fn dispatch_queue_get_label(queue: dispatch_queue_t) -> *const c_char; + pub fn dispatch_set_target_queue(object: dispatch_object_t, queue: dispatch_queue_t); + pub fn dispatch_main(); + + // void dispatch_async ( dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_async_f(queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + // void dispatch_sync ( dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_sync_f(queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + // void dispatch_after ( dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_after_f(when: dispatch_time_t, queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + // void dispatch_apply ( size_t iterations, dispatch_queue_t queue, void (^block)(size_t) ); + pub fn dispatch_apply_f(iterations: usize, queue: dispatch_queue_t, context: *mut c_void, work: extern fn(*mut c_void, usize)); + // void dispatch_once ( dispatch_once_t *predicate, dispatch_block_t block ); + pub fn dispatch_once_f(predicate: *mut dispatch_once_t, context: *mut c_void, function: dispatch_function_t); + + // void dispatch_group_async ( dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_group_async_f(group: dispatch_group_t, queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + pub fn dispatch_group_create() -> dispatch_group_t; + pub fn dispatch_group_enter(group: dispatch_group_t); + pub fn dispatch_group_leave(group: dispatch_group_t); + // void dispatch_group_notify ( dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_group_notify_f(group: dispatch_group_t, queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + pub fn dispatch_group_wait(group: dispatch_group_t, timeout: dispatch_time_t) -> c_long; + + pub fn dispatch_get_context(object: dispatch_object_t) -> *mut c_void; + pub fn dispatch_release(object: dispatch_object_t); + pub fn dispatch_resume(object: dispatch_object_t); + pub fn dispatch_retain(object: dispatch_object_t); + pub fn dispatch_set_context(object: dispatch_object_t, context: *mut c_void); + pub fn dispatch_set_finalizer_f(object: dispatch_object_t, finalizer: dispatch_function_t); + pub fn dispatch_suspend(object: dispatch_object_t); + + pub fn dispatch_semaphore_create(value: c_long) -> dispatch_semaphore_t; + pub fn dispatch_semaphore_signal(dsema: dispatch_semaphore_t) -> c_long; + pub fn dispatch_semaphore_wait(dsema: dispatch_semaphore_t, timeout: dispatch_time_t) -> c_long; + + // void dispatch_barrier_async ( dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_barrier_async_f(queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + // void dispatch_barrier_sync ( dispatch_queue_t queue, dispatch_block_t block ); + pub fn dispatch_barrier_sync_f(queue: dispatch_queue_t, context: *mut c_void, work: dispatch_function_t); + + // void dispatch_source_cancel ( dispatch_source_t source ); + // dispatch_source_t dispatch_source_create ( dispatch_source_type_t type, uintptr_t handle, unsigned long mask, dispatch_queue_t queue ); + // unsigned long dispatch_source_get_data ( dispatch_source_t source ); + // uintptr_t dispatch_source_get_handle ( dispatch_source_t source ); + // unsigned long dispatch_source_get_mask ( dispatch_source_t source ); + // void dispatch_source_merge_data ( dispatch_source_t source, unsigned long value ); + // void dispatch_source_set_registration_handler ( dispatch_source_t source, dispatch_block_t handler ); + // void dispatch_source_set_registration_handler_f ( dispatch_source_t source, dispatch_function_t handler ); + // void dispatch_source_set_cancel_handler ( dispatch_source_t source, dispatch_block_t handler ); + // void dispatch_source_set_cancel_handler_f ( dispatch_source_t source, dispatch_function_t handler ); + // void dispatch_source_set_event_handler ( dispatch_source_t source, dispatch_block_t handler ); + // void dispatch_source_set_event_handler_f ( dispatch_source_t source, dispatch_function_t handler ); + // void dispatch_source_set_timer ( dispatch_source_t source, dispatch_time_t start, uint64_t interval, uint64_t leeway ); + // long dispatch_source_testcancel ( dispatch_source_t source ); + + // void dispatch_read ( dispatch_fd_t fd, size_t length, dispatch_queue_t queue, void (^handler)(dispatch_data_t data, int error) ); + // void dispatch_write ( dispatch_fd_t fd, dispatch_data_t data, dispatch_queue_t queue, void (^handler)(dispatch_data_t data, int error) ); + + // dispatch_io_t dispatch_io_create ( dispatch_io_type_t type, dispatch_fd_t fd, dispatch_queue_t queue, void (^cleanup_handler)(int error) ); + // dispatch_io_t dispatch_io_create_with_path ( dispatch_io_type_t type, const char *path, int oflag, mode_t mode, dispatch_queue_t queue, void (^cleanup_handler)(int error) ); + // dispatch_io_t dispatch_io_create_with_io ( dispatch_io_type_t type, dispatch_io_t io, dispatch_queue_t queue, void (^cleanup_handler)(int error) ); + // void dispatch_io_read ( dispatch_io_t channel, off_t offset, size_t length, dispatch_queue_t queue, dispatch_io_handler_t io_handler ); + // void dispatch_io_write ( dispatch_io_t channel, off_t offset, dispatch_data_t data, dispatch_queue_t queue, dispatch_io_handler_t io_handler ); + // void dispatch_io_close ( dispatch_io_t channel, dispatch_io_close_flags_t flags ); + // void dispatch_io_barrier ( dispatch_io_t channel, dispatch_block_t barrier ); + // void dispatch_io_set_high_water ( dispatch_io_t channel, size_t high_water ); + // void dispatch_io_set_low_water ( dispatch_io_t channel, size_t low_water ); + // void dispatch_io_set_interval ( dispatch_io_t channel, uint64_t interval, dispatch_io_interval_flags_t flags ); + // dispatch_fd_t dispatch_io_get_descriptor ( dispatch_io_t channel ); + + // dispatch_data_t dispatch_data_create ( const void *buffer, size_t size, dispatch_queue_t queue, dispatch_block_t destructor ); + // size_t dispatch_data_get_size ( dispatch_data_t data ); + // dispatch_data_t dispatch_data_create_map ( dispatch_data_t data, const void **buffer_ptr, size_t *size_ptr ); + // dispatch_data_t dispatch_data_create_concat ( dispatch_data_t data1, dispatch_data_t data2 ); + // dispatch_data_t dispatch_data_create_subrange ( dispatch_data_t data, size_t offset, size_t length ); + // bool dispatch_data_apply ( dispatch_data_t data, dispatch_data_applier_t applier ); + // dispatch_data_t dispatch_data_copy_region ( dispatch_data_t data, size_t location, size_t *offset_ptr ); + + pub fn dispatch_time(when: dispatch_time_t, delta: i64) -> dispatch_time_t; + // dispatch_time_t dispatch_walltime( const struct timespec *when, int64_t delta); + + // void dispatch_queue_set_specific ( dispatch_queue_t queue, const void *key, void *context, dispatch_function_t destructor ); + // void * dispatch_queue_get_specific ( dispatch_queue_t queue, const void *key ); + // void * dispatch_get_specific ( const void *key ); + + // dispatch_block_t dispatch_block_create(dispatch_block_flags_t flags, dispatch_block_t block); + // dispatch_block_t dispatch_block_create_with_qos_class(dispatch_block_flags_t flags, dispatch_qos_class_t qos_class, int relative_priority, dispatch_block_t block); + // void dispatch_block_perform(dispatch_block_flags_t flags, dispatch_block_t block); + // long dispatch_block_wait(dispatch_block_t block, dispatch_time_t timeout); + // dispatch_block_notify(dispatch_block_t block, dispatch_queue_t queue, dispatch_block_t notification_block); + // void dispatch_block_cancel(dispatch_block_t block); + // long dispatch_block_testcancel(dispatch_block_t block); +} + +pub fn dispatch_get_main_queue() -> dispatch_queue_t { + unsafe { &_dispatch_main_q as *const _ as dispatch_queue_t } +} + +pub const DISPATCH_QUEUE_SERIAL: dispatch_queue_attr_t = 0 as dispatch_queue_attr_t; +pub static DISPATCH_QUEUE_CONCURRENT: &'static dispatch_object_s = unsafe { &_dispatch_queue_attr_concurrent }; + +pub const DISPATCH_QUEUE_PRIORITY_HIGH: c_long = 2; +pub const DISPATCH_QUEUE_PRIORITY_DEFAULT: c_long = 0; +pub const DISPATCH_QUEUE_PRIORITY_LOW: c_long = -2; +pub const DISPATCH_QUEUE_PRIORITY_BACKGROUND: c_long = -1 << 15; + +pub const DISPATCH_TIME_NOW: dispatch_time_t = 0; +pub const DISPATCH_TIME_FOREVER: dispatch_time_t = !0; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ffi_serial_queue() { + use std::os::raw::c_void; + use std::ptr; + + extern fn serial_queue_test_add(num: *mut c_void) { + unsafe { + *(num as *mut u32) = 1; + } + } + + let mut num: u32 = 0; + let num_ptr: *mut u32 = &mut num; + unsafe { + let q = dispatch_queue_create(ptr::null(), DISPATCH_QUEUE_SERIAL); + dispatch_sync_f(q, num_ptr as *mut c_void, serial_queue_test_add); + dispatch_release(q); + } + assert!(num == 1); + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/group.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/group.rs new file mode 100644 index 0000000..6ba6c5b --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/group.rs @@ -0,0 +1,180 @@ +use std::time::Duration; + +use crate::ffi::*; +use crate::{context_and_function, time_after_delay, WaitTimeout}; +use crate::queue::Queue; + +/// A Grand Central Dispatch group. +/// +/// A `Group` is a mechanism for grouping closures and monitoring them. This +/// allows for aggregate synchronization, so you can track when all the +/// closures complete, even if they are running on different queues. +#[derive(Debug)] +pub struct Group { + ptr: dispatch_group_t, +} + +impl Group { + /// Creates a new dispatch `Group`. + pub fn create() -> Group { + unsafe { + Group { ptr: dispatch_group_create() } + } + } + + /// Indicates that a closure has entered self, and increments the current + /// count of outstanding tasks. Returns a `GroupGuard` that should be + /// dropped when the closure leaves self, decrementing the count. + pub fn enter(&self) -> GroupGuard { + GroupGuard::new(self) + } + + /// Submits a closure asynchronously to the given `Queue` and associates it + /// with self. + pub fn exec_async(&self, queue: &Queue, work: F) + where F: 'static + Send + FnOnce() { + let (context, work) = context_and_function(work); + unsafe { + dispatch_group_async_f(self.ptr, queue.ptr, context, work); + } + } + + /// Schedules a closure to be submitted to the given `Queue` when all tasks + /// associated with self have completed. + /// If self is empty, the closure is submitted immediately. + pub fn notify(&self, queue: &Queue, work: F) + where F: 'static + Send + FnOnce() { + let (context, work) = context_and_function(work); + unsafe { + dispatch_group_notify_f(self.ptr, queue.ptr, context, work); + } + } + + /// Waits synchronously for all tasks associated with self to complete. + pub fn wait(&self) { + let result = unsafe { + dispatch_group_wait(self.ptr, DISPATCH_TIME_FOREVER) + }; + assert!(result == 0, "Dispatch group wait errored"); + } + + /// Waits for all tasks associated with self to complete within the + /// specified duration. + /// Returns true if the tasks completed or false if the timeout elapsed. + pub fn wait_timeout(&self, timeout: Duration) -> Result<(), WaitTimeout> { + let when = time_after_delay(timeout); + let result = unsafe { + dispatch_group_wait(self.ptr, when) + }; + if result == 0 { + Ok(()) + } else { + Err(WaitTimeout { duration: timeout }) + } + } + + /// Returns whether self is currently empty. + pub fn is_empty(&self) -> bool { + let result = unsafe { + dispatch_group_wait(self.ptr, DISPATCH_TIME_NOW) + }; + result == 0 + } +} + +unsafe impl Sync for Group { } +unsafe impl Send for Group { } + +impl Clone for Group { + fn clone(&self) -> Self { + unsafe { + dispatch_retain(self.ptr); + } + Group { ptr: self.ptr } + } +} + +impl Drop for Group { + fn drop(&mut self) { + unsafe { + dispatch_release(self.ptr); + } + } +} + +/// An RAII guard which will leave a `Group` when dropped. +#[derive(Debug)] +pub struct GroupGuard { + group: Group, +} + +impl GroupGuard { + fn new(group: &Group) -> GroupGuard { + unsafe { + dispatch_group_enter(group.ptr); + } + GroupGuard { group: group.clone() } + } + + /// Drops self, leaving the `Group`. + pub fn leave(self) { } +} + +impl Clone for GroupGuard { + fn clone(&self) -> Self { + GroupGuard::new(&self.group) + } +} + +impl Drop for GroupGuard { + fn drop(&mut self) { + unsafe { + dispatch_group_leave(self.group.ptr); + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + use crate::{Queue, QueueAttribute}; + use super::Group; + + #[test] + fn test_group() { + let group = Group::create(); + let q = Queue::create("", QueueAttribute::Serial); + let num = Arc::new(Mutex::new(0)); + + let num2 = num.clone(); + group.exec_async(&q, move || { + let mut num = num2.lock().unwrap(); + *num += 1; + }); + + let guard = group.enter(); + assert!(!group.is_empty()); + let num3 = num.clone(); + q.exec_async(move || { + let mut num = num3.lock().unwrap(); + *num += 1; + guard.leave(); + }); + + let notify_group = Group::create(); + let guard = notify_group.enter(); + let num4 = num.clone(); + group.notify(&q, move || { + let mut num = num4.lock().unwrap(); + *num *= 5; + guard.leave(); + }); + + // Wait for the notify block to finish + notify_group.wait(); + // If the notify ran, the group should be empty + assert!(group.is_empty()); + // The notify must have run after the two blocks of the group + assert_eq!(*num.lock().unwrap(), 10); + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/lib.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/lib.rs new file mode 100644 index 0000000..c5cd981 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/lib.rs @@ -0,0 +1,133 @@ +/*! +Rust wrapper for Apple's Grand Central Dispatch (GCD). + +GCD is an implementation of task parallelism that allows tasks to be submitted +to queues where they are scheduled to execute. + +For more information, see Apple's [Grand Central Dispatch reference]( +https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html). + +# Serial Queues + +Serial queues execute tasks serially in FIFO order. The application's main +queue is serial and can be accessed through the `Queue::main` function. + +``` +use dispatch::{Queue, QueueAttribute}; + +let queue = Queue::create("com.example.rust", QueueAttribute::Serial); +queue.exec_async(|| println!("Hello")); +queue.exec_async(|| println!("World")); +``` + +# Concurrent Queues + +Concurrent dispatch queues execute tasks concurrently. GCD provides global +concurrent queues that can be accessed through the `Queue::global` function. + +`Queue` has two methods that can simplify processing data in parallel, `foreach` +and `map`: + +``` +use dispatch::{Queue, QueuePriority}; + +let queue = Queue::global(QueuePriority::Default); + +let mut nums = vec![1, 2]; +queue.for_each(&mut nums, |x| *x += 1); +assert!(nums == [2, 3]); + +let nums = queue.map(nums, |x| x.to_string()); +assert!(nums[0] == "2"); +``` +*/ + +#![warn(missing_docs)] + +use std::error::Error; +use std::fmt; +use std::mem; +use std::os::raw::c_void; +use std::time::Duration; + +use crate::ffi::*; + +pub use crate::group::{Group, GroupGuard}; +pub use crate::once::Once; +pub use crate::queue::{Queue, QueueAttribute, QueuePriority, SuspendGuard}; +pub use crate::sem::{Semaphore, SemaphoreGuard}; + +/// Raw foreign function interface for libdispatch. +pub mod ffi; +mod group; +mod queue; +mod once; +mod sem; + +/// An error indicating a wait timed out. +#[derive(Clone, Debug)] +pub struct WaitTimeout { + duration: Duration, +} + +impl fmt::Display for WaitTimeout { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Wait timed out after duration {:?}", self.duration) + } +} + +impl Error for WaitTimeout { } + +fn time_after_delay(delay: Duration) -> dispatch_time_t { + delay.as_secs().checked_mul(1_000_000_000).and_then(|i| { + i.checked_add(delay.subsec_nanos() as u64) + }).and_then(|i| { + if i < (i64::max_value() as u64) { Some(i as i64) } else { None } + }).map_or(DISPATCH_TIME_FOREVER, |i| unsafe { + dispatch_time(DISPATCH_TIME_NOW, i) + }) +} + +fn context_and_function(closure: F) -> (*mut c_void, dispatch_function_t) + where F: FnOnce() { + extern fn work_execute_closure(context: Box) where F: FnOnce() { + (*context)(); + } + + let closure = Box::new(closure); + let func: extern fn(Box) = work_execute_closure::; + unsafe { + (mem::transmute(closure), mem::transmute(func)) + } +} + +fn context_and_sync_function(closure: &mut Option) -> + (*mut c_void, dispatch_function_t) + where F: FnOnce() { + extern fn work_read_closure(context: &mut Option) where F: FnOnce() { + // This is always passed Some, so it's safe to unwrap + let closure = context.take().unwrap(); + closure(); + } + + let context: *mut Option = closure; + let func: extern fn(&mut Option) = work_read_closure::; + unsafe { + (context as *mut c_void, mem::transmute(func)) + } +} + +fn context_and_apply_function(closure: &F) -> + (*mut c_void, extern fn(*mut c_void, usize)) + where F: Fn(usize) { + extern fn work_apply_closure(context: &F, iter: usize) + where F: Fn(usize) { + context(iter); + } + + let context: *const F = closure; + let func: extern fn(&F, usize) = work_apply_closure::; + unsafe { + (context as *mut c_void, mem::transmute(func)) + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/once.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/once.rs new file mode 100644 index 0000000..c1dbfa8 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/once.rs @@ -0,0 +1,60 @@ +use std::cell::UnsafeCell; + +use crate::ffi::*; +use crate::context_and_sync_function; + +/// A predicate used to execute a closure only once for the lifetime of an +/// application. +#[derive(Debug)] +pub struct Once { + predicate: UnsafeCell, +} + +impl Once { + /// Creates a new `Once`. + pub const fn new() -> Once { + Once { predicate: UnsafeCell::new(0) } + } + + /// Executes a closure once, ensuring that no other closure has been or + /// will be executed by self for the lifetype of the application. + /// + /// If called simultaneously from multiple threads, waits synchronously + // until the work has completed. + #[inline(always)] + pub fn call_once(&'static self, work: F) where F: FnOnce() { + #[cold] + #[inline(never)] + fn once(predicate: *mut dispatch_once_t, work: F) + where F: FnOnce() { + let mut work = Some(work); + let (context, work) = context_and_sync_function(&mut work); + unsafe { + dispatch_once_f(predicate, context, work); + } + } + + unsafe { + let predicate = self.predicate.get(); + if *predicate != !0 { + once(predicate, work); + } + } + } +} + +unsafe impl Sync for Once { } + +#[cfg(test)] +mod tests { + use super::Once; + + #[test] + fn test_once() { + static ONCE: Once = Once::new(); + let mut num = 0; + ONCE.call_once(|| num += 1); + ONCE.call_once(|| num += 1); + assert!(num == 1); + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/queue.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/queue.rs new file mode 100644 index 0000000..46ed9cd --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/queue.rs @@ -0,0 +1,506 @@ +use std::ffi::{CStr, CString}; +use std::os::raw::c_long; +use std::ptr; +use std::str; +use std::time::Duration; + +use crate::ffi::*; +use crate::{ + context_and_function, context_and_sync_function, context_and_apply_function, + time_after_delay, +}; + +/// The type of a dispatch queue. +#[derive(Clone, Debug, Hash, PartialEq)] +pub enum QueueAttribute { + /// The queue executes blocks serially in FIFO order. + Serial, + /// The queue executes blocks concurrently. + Concurrent, +} + +impl QueueAttribute { + #[cfg(not(all(test, target_os = "linux")))] + fn as_raw(&self) -> dispatch_queue_attr_t { + match *self { + QueueAttribute::Serial => DISPATCH_QUEUE_SERIAL, + QueueAttribute::Concurrent => DISPATCH_QUEUE_CONCURRENT, + } + } + + #[cfg(all(test, target_os = "linux"))] + fn as_raw(&self) -> dispatch_queue_attr_t { + // The Linux tests use Ubuntu's libdispatch-dev package, which is + // apparently really old from before OSX 10.7. + // Back then, the attr for dispatch_queue_create must be NULL. + ptr::null() + } +} + +/// The priority of a global concurrent queue. +#[derive(Clone, Debug, Hash, PartialEq)] +pub enum QueuePriority { + /// The queue is scheduled for execution before any default priority or low + /// priority queue. + High, + /// The queue is scheduled for execution after all high priority queues, + /// but before any low priority queues. + Default, + /// The queue is scheduled for execution after all default priority and + /// high priority queues. + Low, + /// The queue is scheduled for execution after all high priority queues + /// have been scheduled. The system runs items on a thread whose + /// priority is set for background status and any disk I/O is throttled to + /// minimize the impact on the system. + Background, +} + +impl QueuePriority { + fn as_raw(&self) -> c_long { + match *self { + QueuePriority::High => DISPATCH_QUEUE_PRIORITY_HIGH, + QueuePriority::Default => DISPATCH_QUEUE_PRIORITY_DEFAULT, + QueuePriority::Low => DISPATCH_QUEUE_PRIORITY_LOW, + QueuePriority::Background => DISPATCH_QUEUE_PRIORITY_BACKGROUND, + } + } +} + +/// A Grand Central Dispatch queue. +/// +/// For more information, see Apple's [Grand Central Dispatch reference]( +/// https://developer.apple.com/library/mac/documentation/Performance/Reference/GCD_libdispatch_Ref/index.html). +#[derive(Debug)] +pub struct Queue { + pub(crate) ptr: dispatch_queue_t, +} + +impl Queue { + /// Returns the serial dispatch `Queue` associated with the application's + /// main thread. + pub fn main() -> Self { + let queue = dispatch_get_main_queue(); + unsafe { + dispatch_retain(queue); + } + Queue { ptr: queue } + } + + /// Returns a system-defined global concurrent `Queue` with the specified + /// priority. + pub fn global(priority: QueuePriority) -> Self { + unsafe { + let queue = dispatch_get_global_queue(priority.as_raw(), 0); + dispatch_retain(queue); + Queue { ptr: queue } + } + } + + /// Creates a new dispatch `Queue`. + pub fn create(label: &str, attr: QueueAttribute) -> Self { + let label = CString::new(label).unwrap(); + let queue = unsafe { + dispatch_queue_create(label.as_ptr(), attr.as_raw()) + }; + Queue { ptr: queue } + } + + /// Creates a new dispatch `Queue` with the given target queue. + /// + /// A dispatch queue's priority is inherited from its target queue. + /// Additionally, if both the queue and its target are serial queues, + /// their blocks will not be invoked concurrently. + pub fn with_target_queue(label: &str, attr: QueueAttribute, target: &Queue) + -> Self { + let queue = Queue::create(label, attr); + unsafe { + dispatch_set_target_queue(queue.ptr, target.ptr); + } + queue + } + + /// Returns the label that was specified for self. + pub fn label(&self) -> &str { + let label = unsafe { + let label_ptr = dispatch_queue_get_label(self.ptr); + if label_ptr.is_null() { + return ""; + } + CStr::from_ptr(label_ptr) + }; + str::from_utf8(label.to_bytes()).unwrap() + } + + /// Submits a closure for execution on self and waits until it completes. + pub fn exec_sync(&self, work: F) -> T + where F: Send + FnOnce() -> T, T: Send { + let mut result = None; + { + let result_ref = &mut result; + let work = move || { + *result_ref = Some(work()); + }; + + let mut work = Some(work); + let (context, work) = context_and_sync_function(&mut work); + unsafe { + dispatch_sync_f(self.ptr, context, work); + } + } + // This was set so it's safe to unwrap + result.unwrap() + } + + /// Submits a closure for asynchronous execution on self and returns + /// immediately. + pub fn exec_async(&self, work: F) where F: 'static + Send + FnOnce() { + let (context, work) = context_and_function(work); + unsafe { + dispatch_async_f(self.ptr, context, work); + } + } + + /// After the specified delay, submits a closure for asynchronous execution + /// on self. + pub fn exec_after(&self, delay: Duration, work: F) + where F: 'static + Send + FnOnce() { + let when = time_after_delay(delay); + let (context, work) = context_and_function(work); + unsafe { + dispatch_after_f(when, self.ptr, context, work); + } + } + + /// Submits a closure to be executed on self the given number of iterations + /// and waits until it completes. + pub fn apply(&self, iterations: usize, work: F) + where F: Sync + Fn(usize) { + let (context, work) = context_and_apply_function(&work); + unsafe { + dispatch_apply_f(iterations, self.ptr, context, work); + } + } + + /// Submits a closure to be executed on self for each element of the + /// provided slice and waits until it completes. + pub fn for_each(&self, slice: &mut [T], work: F) + where F: Sync + Fn(&mut T), T: Send { + let slice_ptr = slice.as_mut_ptr(); + let work = move |i| unsafe { + work(&mut *slice_ptr.offset(i as isize)); + }; + let (context, work) = context_and_apply_function(&work); + unsafe { + dispatch_apply_f(slice.len(), self.ptr, context, work); + } + } + + /// Submits a closure to be executed on self for each element of the + /// provided vector and returns a `Vec` of the mapped elements. + pub fn map(&self, vec: Vec, work: F) -> Vec + where F: Sync + Fn(T) -> U, T: Send, U: Send { + let mut src = vec; + let len = src.len(); + let src_ptr = src.as_ptr(); + + let mut dest: Vec = Vec::with_capacity(len); + let dest_ptr = dest.as_mut_ptr(); + + let work = move |i| unsafe { + let result = work(ptr::read(src_ptr.offset(i as isize))); + ptr::write(dest_ptr.offset(i as isize), result); + }; + let (context, work) = context_and_apply_function(&work); + unsafe { + src.set_len(0); + dispatch_apply_f(len, self.ptr, context, work); + dest.set_len(len); + } + + dest + } + + /// Submits a closure to be executed on self as a barrier and waits until + /// it completes. + /// + /// Barriers create synchronization points within a concurrent queue. + /// If self is concurrent, when it encounters a barrier it delays execution + /// of the closure (and any further ones) until all closures submitted + /// before the barrier finish executing. + /// At that point, the barrier closure executes by itself. + /// Upon completion, self resumes its normal execution behavior. + /// + /// If self is a serial queue or one of the global concurrent queues, + /// this method behaves like the normal `sync` method. + pub fn barrier_sync(&self, work: F) -> T + where F: Send + FnOnce() -> T, T: Send { + let mut result = None; + { + let result_ref = &mut result; + let work = move || { + *result_ref = Some(work()); + }; + + let mut work = Some(work); + let (context, work) = context_and_sync_function(&mut work); + unsafe { + dispatch_barrier_sync_f(self.ptr, context, work); + } + } + // This was set so it's safe to unwrap + result.unwrap() + } + + /// Submits a closure to be executed on self as a barrier and returns + /// immediately. + /// + /// Barriers create synchronization points within a concurrent queue. + /// If self is concurrent, when it encounters a barrier it delays execution + /// of the closure (and any further ones) until all closures submitted + /// before the barrier finish executing. + /// At that point, the barrier closure executes by itself. + /// Upon completion, self resumes its normal execution behavior. + /// + /// If self is a serial queue or one of the global concurrent queues, + /// this method behaves like the normal `async` method. + pub fn barrier_async(&self, work: F) + where F: 'static + Send + FnOnce() { + let (context, work) = context_and_function(work); + unsafe { + dispatch_barrier_async_f(self.ptr, context, work); + } + } + + /// Suspends the invocation of blocks on self and returns a `SuspendGuard` + /// that can be dropped to resume. + /// + /// The suspension occurs after completion of any blocks running at the + /// time of the call. + /// Invocation does not resume until all `SuspendGuard`s have been dropped. + pub fn suspend(&self) -> SuspendGuard { + SuspendGuard::new(self) + } +} + +unsafe impl Sync for Queue { } +unsafe impl Send for Queue { } + +impl Clone for Queue { + fn clone(&self) -> Self { + unsafe { + dispatch_retain(self.ptr); + } + Queue { ptr: self.ptr } + } +} + +impl Drop for Queue { + fn drop(&mut self) { + unsafe { + dispatch_release(self.ptr); + } + } +} + +/// An RAII guard which will resume a suspended `Queue` when dropped. +#[derive(Debug)] +pub struct SuspendGuard { + queue: Queue, +} + +impl SuspendGuard { + fn new(queue: &Queue) -> SuspendGuard { + unsafe { + dispatch_suspend(queue.ptr); + } + SuspendGuard { queue: queue.clone() } + } + + /// Drops self, allowing the suspended `Queue` to resume. + pub fn resume(self) { } +} + +impl Clone for SuspendGuard { + fn clone(&self) -> Self { + SuspendGuard::new(&self.queue) + } +} + +impl Drop for SuspendGuard { + fn drop(&mut self) { + unsafe { + dispatch_resume(self.queue.ptr); + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + use std::time::{Duration, Instant}; + use crate::Group; + use super::*; + + fn async_increment(queue: &Queue, num: &Arc>) { + let num = num.clone(); + queue.exec_async(move || { + let mut num = num.lock().unwrap(); + *num += 1; + }); + } + + #[test] + fn test_serial_queue() { + let q = Queue::create("", QueueAttribute::Serial); + let mut num = 0; + + q.exec_sync(|| num = 1); + assert_eq!(num, 1); + + assert_eq!(q.exec_sync(|| num), 1); + } + + #[test] + fn test_sync_owned() { + let q = Queue::create("", QueueAttribute::Serial); + + let s = "Hello, world!".to_string(); + let len = q.exec_sync(move || s.len()); + assert_eq!(len, 13); + } + + #[test] + fn test_serial_queue_async() { + let q = Queue::create("", QueueAttribute::Serial); + let num = Arc::new(Mutex::new(0)); + + async_increment(&q, &num); + + // Sync an empty block to ensure the async one finishes + q.exec_sync(|| ()); + assert_eq!(*num.lock().unwrap(), 1); + } + + #[test] + fn test_after() { + let q = Queue::create("", QueueAttribute::Serial); + let group = Group::create(); + let num = Arc::new(Mutex::new(0)); + + let delay = Duration::from_millis(5); + let num2 = num.clone(); + let guard = group.enter(); + let start = Instant::now(); + q.exec_after(delay, move || { + let mut num = num2.lock().unwrap(); + *num = 1; + guard.leave(); + }); + + // Wait for the previous block to complete + group.wait_timeout(Duration::from_millis(5000)).unwrap(); + assert!(start.elapsed() >= delay); + assert_eq!(*num.lock().unwrap(), 1); + } + + #[test] + fn test_queue_label() { + let q = Queue::create("com.example.rust", QueueAttribute::Serial); + assert_eq!(q.label(), "com.example.rust"); + } + + #[test] + fn test_apply() { + let q = Queue::create("", QueueAttribute::Serial); + let num = Arc::new(Mutex::new(0)); + + q.apply(5, |_| *num.lock().unwrap() += 1); + assert_eq!(*num.lock().unwrap(), 5); + } + + #[test] + fn test_for_each() { + let q = Queue::create("", QueueAttribute::Serial); + let mut nums = [0, 1]; + + q.for_each(&mut nums, |x| *x += 1); + assert_eq!(nums, [1, 2]); + } + + #[test] + fn test_map() { + let q = Queue::create("", QueueAttribute::Serial); + let nums = vec![0, 1]; + + let result = q.map(nums, |x| x + 1); + assert_eq!(result, [1, 2]); + } + + #[test] + fn test_barrier_sync() { + let q = Queue::create("", QueueAttribute::Concurrent); + let num = Arc::new(Mutex::new(0)); + + async_increment(&q, &num); + async_increment(&q, &num); + + let num2 = num.clone(); + let result = q.barrier_sync(move || { + let mut num = num2.lock().unwrap(); + if *num == 2 { + *num = 10; + } + *num + }); + assert_eq!(result, 10); + + async_increment(&q, &num); + async_increment(&q, &num); + + q.barrier_sync(|| ()); + assert_eq!(*num.lock().unwrap(), 12); + } + + #[test] + fn test_barrier_async() { + let q = Queue::create("", QueueAttribute::Concurrent); + let num = Arc::new(Mutex::new(0)); + + async_increment(&q, &num); + async_increment(&q, &num); + + let num2 = num.clone(); + q.barrier_async(move || { + let mut num = num2.lock().unwrap(); + if *num == 2 { + *num = 10; + } + }); + + async_increment(&q, &num); + async_increment(&q, &num); + + q.barrier_sync(|| ()); + assert_eq!(*num.lock().unwrap(), 12); + } + + #[test] + fn test_suspend() { + let q = Queue::create("", QueueAttribute::Serial); + let num = Arc::new(Mutex::new(0)); + + // Suspend the queue and then dispatch some work to it + let guard = q.suspend(); + async_increment(&q, &num); + + // Sleep and ensure the work doesn't occur + ::std::thread::sleep(Duration::from_millis(5)); + assert_eq!(*num.lock().unwrap(), 0); + + // But ensure the work does complete after we resume + guard.resume(); + q.exec_sync(|| ()); + assert_eq!(*num.lock().unwrap(), 1); + } +} diff --git a/third_party/cargo/vendor/dispatch-0.2.0/src/sem.rs b/third_party/cargo/vendor/dispatch-0.2.0/src/sem.rs new file mode 100644 index 0000000..b6faa24 --- /dev/null +++ b/third_party/cargo/vendor/dispatch-0.2.0/src/sem.rs @@ -0,0 +1,138 @@ +use std::os::raw::c_long; +use std::time::Duration; + +use crate::ffi::*; +use crate::{time_after_delay, WaitTimeout}; + +/// A counting semaphore. +#[derive(Debug)] +pub struct Semaphore { + ptr: dispatch_semaphore_t, +} + +impl Semaphore { + /// Creates a new `Semaphore` with an initial value. + /// + /// A `Semaphore` created with a value greater than 0 cannot be disposed if + /// it has been decremented below its original value. If there are more + /// successful calls to `wait` than `signal`, the system assumes the + /// `Semaphore` is still in use and will abort if it is disposed. + pub fn new(value: u32) -> Self { + let ptr = unsafe { + dispatch_semaphore_create(value as c_long) + }; + Semaphore { ptr } + } + + /// Wait for (decrement) self. + pub fn wait(&self) { + let result = unsafe { + dispatch_semaphore_wait(self.ptr, DISPATCH_TIME_FOREVER) + }; + assert!(result == 0, "Dispatch semaphore wait errored"); + } + + /// Wait for (decrement) self until the specified timeout has elapsed. + pub fn wait_timeout(&self, timeout: Duration) -> Result<(), WaitTimeout> { + let when = time_after_delay(timeout); + let result = unsafe { + dispatch_semaphore_wait(self.ptr, when) + }; + if result == 0 { + Ok(()) + } else { + Err(WaitTimeout { duration: timeout }) + } + } + + /// Signal (increment) self. + /// + /// If the previous value was less than zero, this method wakes a waiting thread. + /// Returns `true` if a thread is woken or `false` otherwise. + pub fn signal(&self) -> bool { + unsafe { + dispatch_semaphore_signal(self.ptr) != 0 + } + } + + /// Wait to access a resource protected by self. + /// This decrements self and returns a guard that increments when dropped. + pub fn access(&self) -> SemaphoreGuard { + self.wait(); + SemaphoreGuard::new(self.clone()) + } + + /// Wait until the specified timeout to access a resource protected by self. + /// This decrements self and returns a guard that increments when dropped. + pub fn access_timeout(&self, timeout: Duration) + -> Result { + self.wait_timeout(timeout)?; + Ok(SemaphoreGuard::new(self.clone())) + } +} + +unsafe impl Sync for Semaphore {} +unsafe impl Send for Semaphore {} + +impl Clone for Semaphore { + fn clone(&self) -> Self { + unsafe { + dispatch_retain(self.ptr); + } + Semaphore { ptr: self.ptr } + } +} + +impl Drop for Semaphore { + fn drop(&mut self) { + unsafe { + dispatch_release(self.ptr); + } + } +} + +/// An RAII guard which will signal a `Semaphore` when dropped. +#[derive(Debug)] +pub struct SemaphoreGuard { + sem: Semaphore, +} + +impl SemaphoreGuard { + fn new(sem: Semaphore) -> SemaphoreGuard { + SemaphoreGuard { sem } + } + + /// Drops self, signaling the `Semaphore`. + pub fn signal(self) { } +} + +impl Drop for SemaphoreGuard { + fn drop(&mut self) { + self.sem.signal(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_semaphore() { + let sem = Semaphore::new(0); + + assert!(!sem.signal()); + sem.wait(); + + assert!(sem.wait_timeout(Duration::from_millis(5)).is_err()); + } + + #[test] + fn test_semaphore_guard() { + let sem = Semaphore::new(1); + + let guard = sem.access(); + assert!(sem.access_timeout(Duration::from_millis(5)).is_err()); + drop(guard); + assert!(sem.access_timeout(Duration::from_millis(5)).is_ok()); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/.cargo-checksum.json b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/.cargo-checksum.json new file mode 100644 index 0000000..482d8e4 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"BUILD.gn":"651b841730c01aa677f22906fd5eee96234a01d13139e4be12943698dd486a17","Cargo.toml":"0f744f8a2ee868ebcb30356bebc5dcf9be09927f9b72fd7c0625d4c4a35b1803","LICENSE":"f82f9062a6dff28145c185f90f94c485eebdc2bb4c6f1c840513709e6d228453","README.md":"f4bff6efc5d888460e2d1eaf62fa0eaca8afe7b51df528ad7829340ec397b32c","examples/BUILD.gn":"51c9291631e59d368709d9959a88bc8be1fe7375c65f2e1fc6e26184e8971137","src/channel.rs":"15c2a404f760d1594b9b8cfbaf8a828f5c506c6cb09a3408b4d5e894360eb1fc","src/cprng.rs":"cd8a163f7e5e75e536ee898a00c1c377b10c748c7dc574c7c3582bb86fdc86c5","src/event.rs":"bbf0c91d154f01ec1618182efbaaa8c71580f05a807cac1d12208b5cbe8f6b74","src/eventpair.rs":"0bf0b1137c2fb08398edb4d09b89ded5990d07f94ffe55b6ec917c7bc9059ebe","src/fifo.rs":"9ac29d11330fdea847902b8dba6b2004ad44878d8ef65d26a197780cd443ebb8","src/handle.rs":"8741c4b5056a200cfb4237af2d2d2c1db083075b112df68166e351e6d81eb3f3","src/job.rs":"827db2e4ea1bbf5ecabec9fb279f2721792032e4223b6bd15b56922d80c7ac01","src/lib.rs":"9f65dd6ba52e56190825542d6d2dfeca2a5610257513f373fa2cdb4d45d9fc6b","src/port.rs":"32501f17218ec9ad4d97741f4ff2d5ca8e89b7da7226473c82441fd06adbecc4","src/process.rs":"0b5e42c4eb79b2a7fff9c70f0d99c8b805cefab99285e94fabf2542290b4b990","src/rights.rs":"679422da3c0ff9f4e4928b8f41098ef0f5ec09af098496e088e2bac82fc9568d","src/signals.rs":"c07501df58b3c6264e37ebc0f5fd28f44ced040273a5ab5e839e3a204d351ea7","src/socket.rs":"cfb2f6ecb5ba9d9e354c18088061d6e5330dd420a20d0ced4a11f05d3332e3b8","src/status.rs":"4831adf17c1fbd4d52a0aacc63eebd98e49f6c0e28c407e8a0e40f380b3f3b2b","src/thread.rs":"d703414c440b5fa597dbafe7b8be925a94d1fe0cf8b47366c786b45eaaec4c60","src/time.rs":"33d9662c58b921ebe701d927d30ebc01d95594d081c38824355093206f29fba0","src/vmar.rs":"e69a51287e3cb016fa39bb8d884c88ffba4799a452c17e881af9d63a507b37f7","src/vmo.rs":"377968eec57b79a7f4b117dff2f59f26a57ba97ca7f2f0334bd27b99fe87b299","tools/gen_status.py":"a2330db86564e12412af2dce60d4c605c0ab203fcdea8039d5c6a8e7f218a3c3"},"package":"2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82"} \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD new file mode 100644 index 0000000..0a74dc4 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD @@ -0,0 +1,44 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "BSD-3-Clause" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "fuchsia_zircon", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", + "//third_party/cargo/vendor/fuchsia-zircon-sys-0.3.3:fuchsia_zircon_sys", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.3.3", + crate_features = [ + ], +) + diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD.gn b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD.gn new file mode 100644 index 0000000..1edb419 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/BUILD.gn @@ -0,0 +1,14 @@ +# Copyright 2017 The Fuchsia Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/rust/rust_library.gni") + +rust_library("fuchsia-zircon") { + deps = [ + "//garnet/public/rust/crates/fuchsia-zircon/fuchsia-zircon-sys", + "//third_party/rust-crates:bitflags-0.7.0", + ] + + with_tests = true +} diff --git a/third_party/cargo/vendor/memoffset-0.2.1/Cargo.toml b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/Cargo.toml similarity index 61% rename from third_party/cargo/vendor/memoffset-0.2.1/Cargo.toml rename to third_party/cargo/vendor/fuchsia-zircon-0.3.3/Cargo.toml index 3b6b907..4f8cd92 100644 --- a/third_party/cargo/vendor/memoffset-0.2.1/Cargo.toml +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/Cargo.toml @@ -11,14 +11,14 @@ # will likely look very different (and much more reasonable) [package] -name = "memoffset" -version = "0.2.1" -authors = ["Gilad Naaman "] -description = "offset_of functionality for Rust structs." -readme = "README.md" -keywords = ["mem", "offset", "offset_of", "offsetof"] -categories = ["no-std"] -license = "MIT" -repository = "https://github.com/Gilnaa/memoffset" +name = "fuchsia-zircon" +version = "0.3.3" +authors = ["Raph Levien "] +description = "Rust bindings for the Zircon kernel" +license = "BSD-3-Clause" +repository = "https://fuchsia.googlesource.com/garnet/" +[dependencies.bitflags] +version = "1.0.0" -[dependencies] +[dependencies.fuchsia-zircon-sys] +version = "0.3.3" diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/LICENSE b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/LICENSE new file mode 100644 index 0000000..ac6402f --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/LICENSE @@ -0,0 +1,27 @@ +// Copyright 2016 The Fuchsia Authors. 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 Google Inc. 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 THE COPYRIGHT +// OWNER OR CONTRIBUTORS 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. diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/README.md b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/README.md new file mode 100644 index 0000000..9a597e0 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/README.md @@ -0,0 +1,12 @@ +Rust bindings for Zircon kernel +================================ + +This repository contains Rust language bindings for Zircon kernel syscalls. The +main crate contains type-safe wrappers, while the inner "sys" crate contains the +raw types and FFI declarations. + +There are two ways to build Rust artifacts targeting Fuchsia; using the +[Fargo](https://fuchsia.googlesource.com/fargo/) cross compiling tool or +including your [artifact in the GN +build](https://fuchsia.googlesource.com/docs/+/master/rust.md). Of the two, +Fargo is likely better for exploration and experimentation. diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/examples/BUILD.gn b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/examples/BUILD.gn new file mode 100644 index 0000000..dee61f5 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/examples/BUILD.gn @@ -0,0 +1,17 @@ +# Copyright 2017 The Fuchsia Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/package.gni") + +package("zircon_rust_examples") { + system_image = true + + deps = [ + "zx_toy", + ] + + binaries = [ { + name = "example_zx_toy" + } ] +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/channel.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/channel.rs new file mode 100644 index 0000000..44ffc6c --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/channel.rs @@ -0,0 +1,418 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon channel objects. + +use {AsHandleRef, HandleBased, Handle, HandleRef, Peered, Status, Time, usize_into_u32, size_to_u32_sat}; +use {sys, ok}; +use std::mem; + +/// An object representing a Zircon +/// [channel](https://fuchsia.googlesource.com/zircon/+/master/docs/objects/channel.md). +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq, Hash)] +pub struct Channel(Handle); +impl_handle_based!(Channel); +impl Peered for Channel {} + +impl Channel { + /// Create a channel, resulting an a pair of `Channel` objects representing both + /// sides of the channel. Messages written into one maybe read from the opposite. + /// + /// Wraps the + /// [zx_channel_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/channel_create.md) + /// syscall. + pub fn create() -> Result<(Channel, Channel), Status> { + unsafe { + let mut handle0 = 0; + let mut handle1 = 0; + let opts = 0; + ok(sys::zx_channel_create(opts, &mut handle0, &mut handle1))?; + Ok(( + Self::from(Handle::from_raw(handle0)), + Self::from(Handle::from_raw(handle1)) + )) + } + } + + /// Read a message from a channel. Wraps the + /// [zx_channel_read](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/channel_read.md) + /// syscall. + /// + /// If the `MessageBuf` lacks the capacity to hold the pending message, + /// returns an `Err` with the number of bytes and number of handles needed. + /// Otherwise returns an `Ok` with the result as usual. + pub fn read_raw(&self, buf: &mut MessageBuf) + -> Result, (usize, usize)> + { + let opts = 0; + unsafe { + buf.clear(); + let raw_handle = self.raw_handle(); + let mut num_bytes: u32 = size_to_u32_sat(buf.bytes.capacity()); + let mut num_handles: u32 = size_to_u32_sat(buf.handles.capacity()); + let status = ok(sys::zx_channel_read(raw_handle, opts, + buf.bytes.as_mut_ptr(), buf.handles.as_mut_ptr() as *mut _, + num_bytes, num_handles, &mut num_bytes, &mut num_handles)); + if status == Err(Status::BUFFER_TOO_SMALL) { + Err((num_bytes as usize, num_handles as usize)) + } else { + Ok(status.map(|()| { + buf.bytes.set_len(num_bytes as usize); + buf.handles.set_len(num_handles as usize); + })) + } + } + } + + /// Read a message from a channel. + /// + /// Note that this method can cause internal reallocations in the `MessageBuf` + /// if it is lacks capacity to hold the full message. If such reallocations + /// are not desirable, use `read_raw` instead. + pub fn read(&self, buf: &mut MessageBuf) -> Result<(), Status> { + loop { + match self.read_raw(buf) { + Ok(result) => return result, + Err((num_bytes, num_handles)) => { + buf.ensure_capacity_bytes(num_bytes); + buf.ensure_capacity_handles(num_handles); + } + } + } + } + + /// Write a message to a channel. Wraps the + /// [zx_channel_write](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/channel_write.md) + /// syscall. + pub fn write(&self, bytes: &[u8], handles: &mut Vec) + -> Result<(), Status> + { + let opts = 0; + let n_bytes = try!(usize_into_u32(bytes.len()).map_err(|_| Status::OUT_OF_RANGE)); + let n_handles = try!(usize_into_u32(handles.len()).map_err(|_| Status::OUT_OF_RANGE)); + unsafe { + let status = sys::zx_channel_write(self.raw_handle(), opts, bytes.as_ptr(), n_bytes, + handles.as_ptr() as *const sys::zx_handle_t, n_handles); + ok(status)?; + // Handles were successfully transferred, forget them on sender side + handles.set_len(0); + Ok(()) + } + } + + /// Send a message consisting of the given bytes and handles to a channel and await a reply. The + /// bytes should start with a four byte 'txid' which is used to identify the matching reply. + /// + /// Wraps the + /// [zx_channel_call](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/channel_call.md) + /// syscall. + /// + /// Note that unlike [`read`][read], the caller must ensure that the MessageBuf has enough + /// capacity for the bytes and handles which will be received, as replies which are too large + /// are discarded. + /// + /// On failure returns the both the main and read status. + /// + /// [read]: struct.Channel.html#method.read + pub fn call(&self, timeout: Time, bytes: &[u8], handles: &mut Vec, + buf: &mut MessageBuf) -> Result<(), (Status, Status)> + { + let write_num_bytes = try!(usize_into_u32(bytes.len()).map_err( + |_| (Status::OUT_OF_RANGE, Status::OK))); + let write_num_handles = try!(usize_into_u32(handles.len()).map_err( + |_| (Status::OUT_OF_RANGE, Status::OK))); + buf.clear(); + let read_num_bytes: u32 = size_to_u32_sat(buf.bytes.capacity()); + let read_num_handles: u32 = size_to_u32_sat(buf.handles.capacity()); + let args = sys::zx_channel_call_args_t { + wr_bytes: bytes.as_ptr(), + wr_handles: handles.as_ptr() as *const sys::zx_handle_t, + rd_bytes: buf.bytes.as_mut_ptr(), + rd_handles: buf.handles.as_mut_ptr() as *mut _, + wr_num_bytes: write_num_bytes, + wr_num_handles: write_num_handles, + rd_num_bytes: read_num_bytes, + rd_num_handles: read_num_handles, + }; + let mut actual_read_bytes: u32 = 0; + let mut actual_read_handles: u32 = 0; + let mut read_status = Status::OK.into_raw(); + let options = 0; + let status = unsafe { + Status::from_raw( + sys::zx_channel_call( + self.raw_handle(), options, timeout.nanos(), &args, &mut actual_read_bytes, + &mut actual_read_handles, &mut read_status)) + }; + + match status { + Status::OK | + Status::TIMED_OUT | + Status::CALL_FAILED => { + // Handles were successfully transferred, + // even if we didn't get a response, so forget + // them on the sender side. + unsafe { handles.set_len(0); } + } + _ => {} + } + + unsafe { + buf.bytes.set_len(actual_read_bytes as usize); + buf.handles.set_len(actual_read_handles as usize); + } + if Status::OK == status { + Ok(()) + } else { + Err((status, Status::from_raw(read_status))) + } + } +} + +#[test] +pub fn test_handle_repr() { + assert_eq!(::std::mem::size_of::(), 4); + assert_eq!(::std::mem::size_of::(), 4); + assert_eq!(::std::mem::align_of::(), ::std::mem::align_of::()); + + // This test asserts that repr(transparent) still works for Handle -> zx_handle_t + + let n: Vec = vec![0, 100, 2<<32-1]; + let v: Vec = n.iter().map(|h| unsafe { Handle::from_raw(*h) } ).collect(); + + for (handle, raw) in v.iter().zip(n.iter()) { + unsafe { + assert_eq!(*(handle as *const _ as *const [u8; 4]), *(raw as *const _ as *const [u8; 4])); + } + } + + for h in v.into_iter() { + ::std::mem::forget(h); + } +} + +impl AsRef for Channel { + fn as_ref(&self) -> &Self { + &self + } +} + +/// A buffer for _receiving_ messages from a channel. +/// +/// A `MessageBuf` is essentially a byte buffer and a vector of +/// handles, but move semantics for "taking" handles requires special handling. +/// +/// Note that for sending messages to a channel, the caller manages the buffers, +/// using a plain byte slice and `Vec`. +#[derive(Default)] +#[derive(Debug)] +pub struct MessageBuf { + bytes: Vec, + handles: Vec, +} + +impl MessageBuf { + /// Create a new, empty, message buffer. + pub fn new() -> Self { + Default::default() + } + + /// Create a new non-empty message buffer. + pub fn new_with(v: Vec, h: Vec) -> Self { + Self{ + bytes: v, + handles: h, + } + } + + /// Ensure that the buffer has the capacity to hold at least `n_bytes` bytes. + pub fn ensure_capacity_bytes(&mut self, n_bytes: usize) { + ensure_capacity(&mut self.bytes, n_bytes); + } + + /// Ensure that the buffer has the capacity to hold at least `n_handles` handles. + pub fn ensure_capacity_handles(&mut self, n_handles: usize) { + ensure_capacity(&mut self.handles, n_handles); + } + + /// Ensure that at least n_bytes bytes are initialized (0 fill). + pub fn ensure_initialized_bytes(&mut self, n_bytes: usize) { + if n_bytes <= self.bytes.len() { + return; + } + self.bytes.resize(n_bytes, 0); + } + + /// Get a reference to the bytes of the message buffer, as a `&[u8]` slice. + pub fn bytes(&self) -> &[u8] { + self.bytes.as_slice() + } + + /// The number of handles in the message buffer. Note this counts the number + /// available when the message was received; `take_handle` does not affect + /// the count. + pub fn n_handles(&self) -> usize { + self.handles.len() + } + + /// Take the handle at the specified index from the message buffer. If the + /// method is called again with the same index, it will return `None`, as + /// will happen if the index exceeds the number of handles available. + pub fn take_handle(&mut self, index: usize) -> Option { + self.handles.get_mut(index).and_then(|handle| + if handle.is_invalid() { + None + } else { + Some(mem::replace(handle, Handle::invalid())) + } + ) + } + + /// Clear the bytes and handles contained in the buf. This will drop any + /// contained handles, resulting in their resources being freed. + pub fn clear(&mut self) { + self.bytes.clear(); + self.handles.clear(); + } +} + +fn ensure_capacity(vec: &mut Vec, size: usize) { + let len = vec.len(); + if size > len { + vec.reserve(size - len); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use {DurationNum, Rights, Signals, Vmo}; + use std::thread; + + #[test] + fn channel_basic() { + let (p1, p2) = Channel::create().unwrap(); + + let mut empty = vec![]; + assert!(p1.write(b"hello", &mut empty).is_ok()); + + let mut buf = MessageBuf::new(); + assert!(p2.read(&mut buf).is_ok()); + assert_eq!(buf.bytes(), b"hello"); + } + + #[test] + fn channel_read_raw_too_small() { + let (p1, p2) = Channel::create().unwrap(); + + let mut empty = vec![]; + assert!(p1.write(b"hello", &mut empty).is_ok()); + + let mut buf = MessageBuf::new(); + let result = p2.read_raw(&mut buf); + assert_eq!(result, Err((5, 0))); + assert_eq!(buf.bytes(), b""); + } + + #[test] + fn channel_send_handle() { + let hello_length: usize = 5; + + // Create a pair of channels and a virtual memory object. + let (p1, p2) = Channel::create().unwrap(); + let vmo = Vmo::create(hello_length as u64).unwrap(); + + // Duplicate VMO handle and send it down the channel. + let duplicate_vmo_handle = vmo.duplicate_handle(Rights::SAME_RIGHTS).unwrap().into(); + let mut handles_to_send: Vec = vec![duplicate_vmo_handle]; + assert!(p1.write(b"", &mut handles_to_send).is_ok()); + // Handle should be removed from vector. + assert!(handles_to_send.is_empty()); + + // Read the handle from the receiving channel. + let mut buf = MessageBuf::new(); + assert!(p2.read(&mut buf).is_ok()); + assert_eq!(buf.n_handles(), 1); + // Take the handle from the buffer. + let received_handle = buf.take_handle(0).unwrap(); + // Should not affect number of handles. + assert_eq!(buf.n_handles(), 1); + // Trying to take it again should fail. + assert!(buf.take_handle(0).is_none()); + + // Now to test that we got the right handle, try writing something to it... + let received_vmo = Vmo::from(received_handle); + assert_eq!(received_vmo.write(b"hello", 0).unwrap(), hello_length); + + // ... and reading it back from the original VMO. + let mut read_vec = vec![0; hello_length]; + assert_eq!(vmo.read(&mut read_vec, 0).unwrap(), hello_length); + assert_eq!(read_vec, b"hello"); + } + + #[test] + fn channel_call_timeout() { + let ten_ms = 10.millis(); + + // Create a pair of channels and a virtual memory object. + let (p1, p2) = Channel::create().unwrap(); + let vmo = Vmo::create(0 as u64).unwrap(); + + // Duplicate VMO handle and send it along with the call. + let duplicate_vmo_handle = vmo.duplicate_handle(Rights::SAME_RIGHTS).unwrap().into(); + let mut handles_to_send: Vec = vec![duplicate_vmo_handle]; + let mut buf = MessageBuf::new(); + assert_eq!(p1.call(ten_ms.after_now(), b"call", &mut handles_to_send, &mut buf), + Err((Status::TIMED_OUT, Status::OK))); + // Handle should be removed from vector even though we didn't get a response, as it was + // still sent over the channel. + assert!(handles_to_send.is_empty()); + + // Should be able to read call even though it timed out waiting for a response. + let mut buf = MessageBuf::new(); + assert!(p2.read(&mut buf).is_ok()); + assert_eq!(buf.bytes(), b"call"); + assert_eq!(buf.n_handles(), 1); + } + + #[test] + fn channel_call() { + // Create a pair of channels + let (p1, p2) = Channel::create().unwrap(); + + // create an mpsc channel for communicating the call data for later assertion + let (tx, rx) = ::std::sync::mpsc::channel(); + + // Start a new thread to respond to the call. + thread::spawn(move || { + let mut buf = MessageBuf::new(); + // if either the read or the write fail, this thread will panic, + // resulting in tx being dropped, which will be noticed by the rx. + p2.wait_handle(Signals::CHANNEL_READABLE, 1.seconds().after_now()).expect("callee wait error"); + p2.read(&mut buf).expect("callee read error"); + p2.write(b"txidresponse", &mut vec![]).expect("callee write error"); + tx.send(buf).expect("callee mpsc send error"); + }); + + // Make the call. + let mut buf = MessageBuf::new(); + buf.ensure_capacity_bytes(12); + // NOTE(raggi): CQ has been seeing some long stalls from channel call, + // and it's as yet unclear why. The timeout here has been made much + // larger in order to avoid that, as the issues are not issues with this + // crate's concerns. The timeout is here just to prevent the tests from + // stalling forever if a developer makes a mistake locally in this + // crate. Tests of Zircon behavior or virtualization behavior should be + // covered elsewhere. See ZX-1324. + p1.call(30.seconds().after_now(), b"txidcall", &mut vec![], &mut buf).expect("channel call error"); + assert_eq!(buf.bytes(), b"txidresponse"); + assert_eq!(buf.n_handles(), 0); + + let sbuf = rx.recv().expect("mpsc channel recv error"); + assert_eq!(sbuf.bytes(), b"txidcall"); + assert_eq!(sbuf.n_handles(), 0); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/cprng.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/cprng.rs new file mode 100644 index 0000000..433ed26 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/cprng.rs @@ -0,0 +1,68 @@ +use {Status, ok, sys}; + +/// Draw random bytes from the kernel's CPRNG to fill the given buffer. Returns the actual number of +/// bytes drawn, which may sometimes be less than the size of the buffer provided. +/// +/// The buffer must have length less than `ZX_CPRNG_DRAW_MAX_LEN`. +/// +/// Wraps the +/// [zx_cprng_draw](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/cprng_draw.md) +/// syscall. +pub fn cprng_draw(buffer: &mut [u8]) -> Result { + let mut actual = 0; + let status = unsafe { sys::zx_cprng_draw(buffer.as_mut_ptr(), buffer.len(), &mut actual) }; + ok(status).map(|()| actual) +} + +/// Mix the given entropy into the kernel CPRNG. +/// +/// The buffer must have length less than `ZX_CPRNG_ADD_ENTROPY_MAX_LEN`. +/// +/// Wraps the +/// [zx_cprng_add_entropy](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/cprng_add_entropy.md) +/// syscall. +pub fn cprng_add_entropy(buffer: &[u8]) -> Result<(), Status> { + let status = unsafe { sys::zx_cprng_add_entropy(buffer.as_ptr(), buffer.len()) }; + ok(status) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cprng() { + let mut buffer = [0; 20]; + assert_eq!(cprng_draw(&mut buffer), Ok(20)); + let mut first_zero = 0; + let mut last_zero = 0; + for _ in 0..30 { + let mut buffer = [0; 20]; + assert_eq!(cprng_draw(&mut buffer), Ok(20)); + if buffer[0] == 0 { + first_zero += 1; + } + if buffer[19] == 0 { + last_zero += 1; + } + } + assert_ne!(first_zero, 30); + assert_ne!(last_zero, 30); + } + + #[test] + fn cprng_too_large() { + let mut buffer = [0; sys::ZX_CPRNG_DRAW_MAX_LEN + 1]; + assert_eq!(cprng_draw(&mut buffer), Err(Status::INVALID_ARGS)); + + for mut s in buffer.chunks_mut(sys::ZX_CPRNG_DRAW_MAX_LEN) { + assert_eq!(cprng_draw(&mut s), Ok(s.len())); + } + } + + #[test] + fn cprng_add() { + let buffer = [0, 1, 2]; + assert_eq!(cprng_add_entropy(&buffer), Ok(())); + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/event.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/event.rs new file mode 100644 index 0000000..533a8aa --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/event.rs @@ -0,0 +1,32 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon event objects. + +use {AsHandleRef, Cookied, HandleBased, Handle, HandleRef, Status}; +use {sys, ok}; + +/// An object representing a Zircon +/// [event object](https://fuchsia.googlesource.com/zircon/+/master/docs/objects/event.md). +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Event(Handle); +impl_handle_based!(Event); +impl Cookied for Event {} + +impl Event { + /// Create an event object, an object which is signalable but nothing else. Wraps the + /// [zx_event_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/event_create.md) + /// syscall. + pub fn create() -> Result { + let mut out = 0; + let opts = 0; + let status = unsafe { sys::zx_event_create(opts, &mut out) }; + ok(status)?; + unsafe { + Ok(Self::from(Handle::from_raw(out))) + } + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/eventpair.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/eventpair.rs new file mode 100644 index 0000000..6f2d298 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/eventpair.rs @@ -0,0 +1,65 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon event pairs. + +use {AsHandleRef, Cookied, HandleBased, Handle, HandleRef, Peered, Status}; +use {sys, ok}; + +/// An object representing a Zircon +/// [event pair](https://fuchsia.googlesource.com/zircon/+/master/docs/concepts.md#Other-IPC_Events_Event-Pairs_and-User-Signals). +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct EventPair(Handle); +impl_handle_based!(EventPair); +impl Peered for EventPair {} +impl Cookied for EventPair {} + +impl EventPair { + /// Create an event pair, a pair of objects which can signal each other. Wraps the + /// [zx_eventpair_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/eventpair_create.md) + /// syscall. + pub fn create() -> Result<(EventPair, EventPair), Status> { + let mut out0 = 0; + let mut out1 = 0; + let options = 0; + let status = unsafe { sys::zx_eventpair_create(options, &mut out0, &mut out1) }; + ok(status)?; + unsafe { + Ok(( + Self::from(Handle::from_raw(out0)), + Self::from(Handle::from_raw(out1)) + )) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use {DurationNum, Signals}; + + #[test] + fn wait_and_signal_peer() { + let (p1, p2) = EventPair::create().unwrap(); + let eighty_ms = 80.millis(); + + // Waiting on one without setting any signal should time out. + assert_eq!(p2.wait_handle(Signals::USER_0, eighty_ms.after_now()), Err(Status::TIMED_OUT)); + + // If we set a signal, we should be able to wait for it. + assert!(p1.signal_peer(Signals::NONE, Signals::USER_0).is_ok()); + assert_eq!(p2.wait_handle(Signals::USER_0, eighty_ms.after_now()).unwrap(), + Signals::USER_0); + + // Should still work, signals aren't automatically cleared. + assert_eq!(p2.wait_handle(Signals::USER_0, eighty_ms.after_now()).unwrap(), + Signals::USER_0); + + // Now clear it, and waiting should time out again. + assert!(p1.signal_peer(Signals::USER_0, Signals::NONE).is_ok()); + assert_eq!(p2.wait_handle(Signals::USER_0, eighty_ms.after_now()), Err(Status::TIMED_OUT)); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/fifo.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/fifo.rs new file mode 100644 index 0000000..20af6f5 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/fifo.rs @@ -0,0 +1,98 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon fifo objects. + +use {AsHandleRef, HandleBased, Handle, HandleRef, Status}; +use {sys, ok}; + +/// An object representing a Zircon fifo. +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Fifo(Handle); +impl_handle_based!(Fifo); + +impl Fifo { + /// Create a pair of fifos and return their endpoints. Writing to one endpoint enqueues an + /// element into the fifo from which the opposing endpoint reads. Wraps the + /// [zx_fifo_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/fifo_create.md) + /// syscall. + pub fn create(elem_count: u32, elem_size: u32) + -> Result<(Fifo, Fifo), Status> + { + let mut out0 = 0; + let mut out1 = 0; + let options = 0; + let status = unsafe { + sys::zx_fifo_create(elem_count, elem_size, options, &mut out0, &mut out1) + }; + ok(status)?; + unsafe { Ok(( + Self::from(Handle::from_raw(out0)), + Self::from(Handle::from_raw(out1)) + ))} + } + + /// Attempts to write some number of elements into the fifo. The number of bytes written will be + /// rounded down to a multiple of the fifo's element size. + /// Return value (on success) is number of elements actually written. + /// + /// Wraps + /// [zx_fifo_write](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/fifo_write.md). + pub fn write(&self, bytes: &[u8]) -> Result { + let mut num_entries_written = 0; + let status = unsafe { + sys::zx_fifo_write(self.raw_handle(), bytes.as_ptr(), bytes.len(), + &mut num_entries_written) + }; + ok(status).map(|()| num_entries_written) + } + + /// Attempts to read some number of elements out of the fifo. The number of bytes read will + /// always be a multiple of the fifo's element size. + /// Return value (on success) is number of elements actually read. + /// + /// Wraps + /// [zx_fifo_read](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/fifo_read.md). + pub fn read(&self, bytes: &mut [u8]) -> Result { + let mut num_entries_read = 0; + let status = unsafe { + sys::zx_fifo_read(self.raw_handle(), bytes.as_mut_ptr(), bytes.len(), + &mut num_entries_read) + }; + ok(status).map(|()| num_entries_read) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fifo_basic() { + let (fifo1, fifo2) = Fifo::create(4, 2).unwrap(); + + // Trying to write less than one element should fail. + assert_eq!(fifo1.write(b""), Err(Status::OUT_OF_RANGE)); + assert_eq!(fifo1.write(b"h"), Err(Status::OUT_OF_RANGE)); + + // Should write one element "he" and ignore the last half-element as it rounds down. + assert_eq!(fifo1.write(b"hex").unwrap(), 1); + + // Should write three elements "ll" "o " "wo" and drop the rest as it is full. + assert_eq!(fifo1.write(b"llo worlds").unwrap(), 3); + + // Now that the fifo is full any further attempts to write should fail. + assert_eq!(fifo1.write(b"blah blah"), Err(Status::SHOULD_WAIT)); + + // Read all 4 entries from the other end. + let mut read_vec = vec![0; 8]; + assert_eq!(fifo2.read(&mut read_vec).unwrap(), 4); + assert_eq!(read_vec, b"hello wo"); + + // Reading again should fail as the fifo is empty. + assert_eq!(fifo2.read(&mut read_vec), Err(Status::SHOULD_WAIT)); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/handle.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/handle.rs new file mode 100644 index 0000000..5c50f29 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/handle.rs @@ -0,0 +1,243 @@ +use {Port, Rights, Signals, Status, Time, WaitAsyncOpts, ok, sys}; +use std::marker::PhantomData; +use std::mem; + +/// An object representing a Zircon +/// [handle](https://fuchsia.googlesource.com/zircon/+/master/docs/handles.md). +/// +/// Internally, it is represented as a 32-bit integer, but this wrapper enforces +/// strict ownership semantics. The `Drop` implementation closes the handle. +/// +/// This type represents the most general reference to a kernel object, and can +/// be interconverted to and from more specific types. Those conversions are not +/// enforced in the type system; attempting to use them will result in errors +/// returned by the kernel. These conversions don't change the underlying +/// representation, but do change the type and thus what operations are available. +#[derive(Debug, Eq, PartialEq, Hash)] +pub struct Handle(sys::zx_handle_t); + +impl AsHandleRef for Handle { + fn as_handle_ref(&self) -> HandleRef { + HandleRef { handle: self.0, phantom: Default::default() } + } +} + +impl HandleBased for Handle {} + +impl Drop for Handle { + fn drop(&mut self) { + if self.0 != sys::ZX_HANDLE_INVALID { + unsafe { sys::zx_handle_close(self.0) }; + } + } +} + +impl Handle { + /// Initialize a handle backed by ZX_HANDLE_INVALID, the only safe non-handle. + pub fn invalid() -> Handle { + Handle(sys::ZX_HANDLE_INVALID) + } + + /// If a raw handle is obtained from some other source, this method converts + /// it into a type-safe owned handle. + pub unsafe fn from_raw(raw: sys::zx_handle_t) -> Handle { + Handle(raw) + } + + pub fn is_invalid(&self) -> bool { + self.0 == sys::ZX_HANDLE_INVALID + } + + pub fn replace(self, rights: Rights) -> Result { + let handle = self.0; + let mut out = 0; + let status = unsafe { sys::zx_handle_replace(handle, rights.bits(), &mut out) }; + ok(status).map(|()| Handle(out)) + } +} + +/// A borrowed reference to a `Handle`. +/// +/// Mostly useful as part of a `WaitItem`. +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub struct HandleRef<'a> { + handle: sys::zx_handle_t, + phantom: PhantomData<&'a sys::zx_handle_t>, +} + +impl<'a> HandleRef<'a> { + pub fn raw_handle(&self) -> sys::zx_handle_t { + self.handle + } + + pub fn duplicate(&self, rights: Rights) -> Result { + let handle = self.handle; + let mut out = 0; + let status = unsafe { sys::zx_handle_duplicate(handle, rights.bits(), &mut out) }; + ok(status).map(|()| Handle(out)) + } + + pub fn signal(&self, clear_mask: Signals, set_mask: Signals) -> Result<(), Status> { + let handle = self.handle; + let status = unsafe { sys::zx_object_signal(handle, clear_mask.bits(), set_mask.bits()) }; + ok(status) + } + + pub fn wait(&self, signals: Signals, deadline: Time) -> Result { + let handle = self.handle; + let mut pending = Signals::empty().bits(); + let status = unsafe { + sys::zx_object_wait_one(handle, signals.bits(), deadline.nanos(), &mut pending) + }; + ok(status).map(|()| Signals::from_bits_truncate(pending)) + } + + pub fn wait_async(&self, port: &Port, key: u64, signals: Signals, options: WaitAsyncOpts) + -> Result<(), Status> + { + let handle = self.handle; + let status = unsafe { + sys::zx_object_wait_async( + handle, port.raw_handle(), key, signals.bits(), options as u32) + }; + ok(status) + } +} + +/// A trait to get a reference to the underlying handle of an object. +pub trait AsHandleRef { + /// Get a reference to the handle. One important use of such a reference is + /// for `object_wait_many`. + fn as_handle_ref(&self) -> HandleRef; + + /// Interpret the reference as a raw handle (an integer type). Two distinct + /// handles will have different raw values (so it can perhaps be used as a + /// key in a data structure). + fn raw_handle(&self) -> sys::zx_handle_t { + self.as_handle_ref().raw_handle() + } + + /// Set and clear userspace-accessible signal bits on an object. Wraps the + /// [zx_object_signal](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/object_signal.md) + /// syscall. + fn signal_handle(&self, clear_mask: Signals, set_mask: Signals) -> Result<(), Status> { + self.as_handle_ref().signal(clear_mask, set_mask) + } + + /// Waits on a handle. Wraps the + /// [zx_object_wait_one](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/object_wait_one.md) + /// syscall. + fn wait_handle(&self, signals: Signals, deadline: Time) -> Result { + self.as_handle_ref().wait(signals, deadline) + } + + /// Causes packet delivery on the given port when the object changes state and matches signals. + /// [zx_object_wait_async](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/object_wait_async.md) + /// syscall. + fn wait_async_handle(&self, port: &Port, key: u64, signals: Signals, options: WaitAsyncOpts) + -> Result<(), Status> + { + self.as_handle_ref().wait_async(port, key, signals, options) + } +} + +impl<'a> AsHandleRef for HandleRef<'a> { + fn as_handle_ref(&self) -> HandleRef { *self } +} + +/// A trait implemented by all handle-based types. +/// +/// Note: it is reasonable for user-defined objects wrapping a handle to implement +/// this trait. For example, a specific interface in some protocol might be +/// represented as a newtype of `Channel`, and implement the `as_handle_ref` +/// method and the `From` trait to facilitate conversion from and to the +/// interface. +pub trait HandleBased: AsHandleRef + From + Into { + /// Duplicate a handle, possibly reducing the rights available. Wraps the + /// [zx_handle_duplicate](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/handle_duplicate.md) + /// syscall. + fn duplicate_handle(&self, rights: Rights) -> Result { + self.as_handle_ref().duplicate(rights).map(|handle| Self::from(handle)) + } + + /// Create a replacement for a handle, possibly reducing the rights available. This invalidates + /// the original handle. Wraps the + /// [zx_handle_replace](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/handle_replace.md) + /// syscall. + fn replace_handle(self, rights: Rights) -> Result { + >::into(self) + .replace(rights).map(|handle| Self::from(handle)) + } + + /// Converts the value into its inner handle. + /// + /// This is a convenience function which simply forwards to the `Into` trait. + fn into_handle(self) -> Handle { + self.into() + } + + /// Converts the handle into it's raw representation. + /// + /// The caller takes ownership over the raw handle, and must close or transfer it to avoid a handle leak. + fn into_raw(self) -> sys::zx_handle_t { + let h = self.into_handle(); + let r = h.0; + mem::forget(h); + r + } + + /// Creates an instance of this type from a handle. + /// + /// This is a convenience function which simply forwards to the `From` trait. + fn from_handle(handle: Handle) -> Self { + Self::from(handle) + } + + /// Creates an instance of another handle-based type from this value's inner handle. + fn into_handle_based(self) -> H { + H::from_handle(self.into_handle()) + } + + /// Creates an instance of this type from the inner handle of another + /// handle-based type. + fn from_handle_based(h: H) -> Self { + Self::from_handle(h.into_handle()) + } +} + +/// A trait implemented by all handles for objects which have a peer. +pub trait Peered: HandleBased { + /// Set and clear userspace-accessible signal bits on the object's peer. Wraps the + /// [zx_object_signal_peer](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/object_signal.md) + /// syscall. + fn signal_peer(&self, clear_mask: Signals, set_mask: Signals) -> Result<(), Status> { + let handle = self.as_handle_ref().handle; + let status = unsafe { + sys::zx_object_signal_peer(handle, clear_mask.bits(), set_mask.bits()) + }; + ok(status) + } +} + +/// A trait implemented by all handles for objects which can have a cookie attached. +pub trait Cookied: HandleBased { + /// Get the cookie attached to this object, if any. Wraps the + /// [zx_object_get_cookie](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/object_get_cookie.md) + /// syscall. + fn get_cookie(&self, scope: &HandleRef) -> Result { + let handle = self.as_handle_ref().handle; + let mut cookie = 0; + let status = unsafe { sys::zx_object_get_cookie(handle, scope.handle, &mut cookie) }; + ok(status).map(|()| cookie) + } + + /// Attach an opaque cookie to this object with the given scope. The cookie may be read or + /// changed in future only with the same scope. Wraps the + /// [zx_object_set_cookie](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/object_set_cookie.md) + /// syscall. + fn set_cookie(&self, scope: &HandleRef, cookie: u64) -> Result<(), Status> { + let handle = self.as_handle_ref().handle; + let status = unsafe { sys::zx_object_set_cookie(handle, scope.handle, cookie) }; + ok(status) + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/job.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/job.rs new file mode 100644 index 0000000..1bb1ef2 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/job.rs @@ -0,0 +1,14 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon job. + +use {AsHandleRef, HandleBased, Handle, HandleRef}; + +/// An object representing a Zircon job. +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Job(Handle); +impl_handle_based!(Job); \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/lib.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/lib.rs new file mode 100644 index 0000000..2644440 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/lib.rs @@ -0,0 +1,365 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon kernel +//! [syscalls](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls.md). + +#![deny(warnings)] + +#[macro_use] +extern crate bitflags; + +pub extern crate fuchsia_zircon_sys as sys; + +#[deprecated(note="use fuchsia_zircon::sys::ZX_CPRNG_DRAW_MAX_LEN instead")] +#[doc(hidden)] +pub use sys::ZX_CPRNG_DRAW_MAX_LEN; + +// Implements the HandleBased traits for a Handle newtype struct +macro_rules! impl_handle_based { + ($type_name:path) => { + impl AsHandleRef for $type_name { + fn as_handle_ref(&self) -> HandleRef { + self.0.as_handle_ref() + } + } + + impl From for $type_name { + fn from(handle: Handle) -> Self { + $type_name(handle) + } + } + + impl From<$type_name> for Handle { + fn from(x: $type_name) -> Handle { + x.0 + } + } + + impl HandleBased for $type_name {} + } +} + +// Creates associated constants of TypeName of the form +// `pub const NAME: TypeName = TypeName(value);` +macro_rules! assoc_consts { + ($typename:ident, [$($name:ident = $num:expr;)*]) => { + #[allow(non_upper_case_globals)] + impl $typename { + $( + pub const $name: $typename = $typename($num); + )* + } + } +} + +mod channel; +mod cprng; +mod event; +mod eventpair; +mod fifo; +mod handle; +mod job; +mod port; +mod process; +mod rights; +mod socket; +mod signals; +mod status; +mod time; +mod thread; +mod vmar; +mod vmo; + +pub use channel::*; +pub use cprng::*; +pub use event::*; +pub use eventpair::*; +pub use fifo::*; +pub use handle::*; +pub use job::*; +pub use port::*; +pub use process::*; +pub use rights::*; +pub use socket::*; +pub use signals::*; +pub use status::*; +pub use thread::*; +pub use time::*; +pub use vmar::*; +pub use vmo::*; + +/// Prelude containing common utility traits. +/// Designed for use like `use fuchsia_zircon::prelude::*;` +pub mod prelude { + pub use { + AsHandleRef, + Cookied, + DurationNum, + HandleBased, + Peered, + }; +} + +/// Convenience re-export of `Status::ok`. +pub fn ok(raw: sys::zx_status_t) -> Result<(), Status> { + Status::ok(raw) +} + +/// A "wait item" containing a handle reference and information about what signals +/// to wait on, and, on return from `object_wait_many`, which are pending. +#[repr(C)] +#[derive(Debug)] +pub struct WaitItem<'a> { + /// The handle to wait on. + pub handle: HandleRef<'a>, + /// A set of signals to wait for. + pub waitfor: Signals, + /// The set of signals pending, on return of `object_wait_many`. + pub pending: Signals, +} + +/// An identifier to select a particular clock. See +/// [zx_time_get](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/time_get.md) +/// for more information about the possible values. +#[repr(u32)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ClockId { + /// The number of nanoseconds since the system was powered on. Corresponds to + /// `ZX_CLOCK_MONOTONIC`. + Monotonic = 0, + /// The number of wall clock nanoseconds since the Unix epoch (midnight on January 1 1970) in + /// UTC. Corresponds to ZX_CLOCK_UTC. + UTC = 1, + /// The number of nanoseconds the current thread has been running for. Corresponds to + /// ZX_CLOCK_THREAD. + Thread = 2, +} + +/// Wait on multiple handles. +/// The success return value is a bool indicating whether one or more of the +/// provided handle references was closed during the wait. +/// +/// Wraps the +/// [zx_object_wait_many](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/object_wait_many.md) +/// syscall. +pub fn object_wait_many(items: &mut [WaitItem], deadline: Time) -> Result +{ + let len = try!(usize_into_u32(items.len()).map_err(|_| Status::OUT_OF_RANGE)); + let items_ptr = items.as_mut_ptr() as *mut sys::zx_wait_item_t; + let status = unsafe { sys::zx_object_wait_many( items_ptr, len, deadline.nanos()) }; + if status == sys::ZX_ERR_CANCELED { + return Ok(true) + } + ok(status).map(|()| false) +} + +#[cfg(test)] +mod tests { + use super::*; + #[allow(unused_imports)] + use super::prelude::*; + + #[test] + fn monotonic_time_increases() { + let time1 = Time::get(ClockId::Monotonic); + 1_000.nanos().sleep(); + let time2 = Time::get(ClockId::Monotonic); + assert!(time2 > time1); + } + + #[test] + fn utc_time_increases() { + let time1 = Time::get(ClockId::UTC); + 1_000.nanos().sleep(); + let time2 = Time::get(ClockId::UTC); + assert!(time2 > time1); + } + + #[test] + fn thread_time_increases() { + let time1 = Time::get(ClockId::Thread); + 1_000.nanos().sleep(); + let time2 = Time::get(ClockId::Thread); + assert!(time2 > time1); + } + + #[test] + fn ticks_increases() { + let ticks1 = ticks_get(); + 1_000.nanos().sleep(); + let ticks2 = ticks_get(); + assert!(ticks2 > ticks1); + } + + #[test] + fn tick_length() { + let sleep_time = 1.milli(); + let ticks1 = ticks_get(); + sleep_time.sleep(); + let ticks2 = ticks_get(); + + // The number of ticks should have increased by at least 1 ms worth + let sleep_ticks = sleep_time.millis() * ticks_per_second() / 1000; + assert!(ticks2 >= (ticks1 + sleep_ticks)); + } + + #[test] + fn into_raw() { + let vmo = Vmo::create(1).unwrap(); + let h = vmo.into_raw(); + let vmo2 = Vmo::from(unsafe { Handle::from_raw(h) }); + assert!(vmo2.write(b"1", 0).is_ok()); + } + + #[test] + fn sleep() { + let sleep_ns = 1.millis(); + let time1 = Time::get(ClockId::Monotonic); + sleep_ns.sleep(); + let time2 = Time::get(ClockId::Monotonic); + assert!(time2 > time1 + sleep_ns); + } + + /// Test duplication by means of a VMO + #[test] + fn duplicate() { + let hello_length: usize = 5; + + // Create a VMO and write some data to it. + let vmo = Vmo::create(hello_length as u64).unwrap(); + assert!(vmo.write(b"hello", 0).is_ok()); + + // Replace, reducing rights to read. + let readonly_vmo = vmo.duplicate_handle(Rights::READ).unwrap(); + // Make sure we can read but not write. + let mut read_vec = vec![0; hello_length]; + assert_eq!(readonly_vmo.read(&mut read_vec, 0).unwrap(), hello_length); + assert_eq!(read_vec, b"hello"); + assert_eq!(readonly_vmo.write(b"", 0), Err(Status::ACCESS_DENIED)); + + // Write new data to the original handle, and read it from the new handle + assert!(vmo.write(b"bye", 0).is_ok()); + assert_eq!(readonly_vmo.read(&mut read_vec, 0).unwrap(), hello_length); + assert_eq!(read_vec, b"byelo"); + } + + // Test replace by means of a VMO + #[test] + fn replace() { + let hello_length: usize = 5; + + // Create a VMO and write some data to it. + let vmo = Vmo::create(hello_length as u64).unwrap(); + assert!(vmo.write(b"hello", 0).is_ok()); + + // Replace, reducing rights to read. + let readonly_vmo = vmo.replace_handle(Rights::READ).unwrap(); + // Make sure we can read but not write. + let mut read_vec = vec![0; hello_length]; + assert_eq!(readonly_vmo.read(&mut read_vec, 0).unwrap(), hello_length); + assert_eq!(read_vec, b"hello"); + assert_eq!(readonly_vmo.write(b"", 0), Err(Status::ACCESS_DENIED)); + } + + #[test] + fn wait_and_signal() { + let event = Event::create().unwrap(); + let ten_ms = 10.millis(); + + // Waiting on it without setting any signal should time out. + assert_eq!(event.wait_handle( + Signals::USER_0, ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // If we set a signal, we should be able to wait for it. + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + assert_eq!(event.wait_handle(Signals::USER_0, ten_ms.after_now()).unwrap(), + Signals::USER_0); + + // Should still work, signals aren't automatically cleared. + assert_eq!(event.wait_handle(Signals::USER_0, ten_ms.after_now()).unwrap(), + Signals::USER_0); + + // Now clear it, and waiting should time out again. + assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok()); + assert_eq!(event.wait_handle( + Signals::USER_0, ten_ms.after_now()), Err(Status::TIMED_OUT)); + } + + #[test] + fn wait_many_and_signal() { + let ten_ms = 10.millis(); + let e1 = Event::create().unwrap(); + let e2 = Event::create().unwrap(); + + // Waiting on them now should time out. + let mut items = vec![ + WaitItem { handle: e1.as_handle_ref(), waitfor: Signals::USER_0, pending: Signals::NONE }, + WaitItem { handle: e2.as_handle_ref(), waitfor: Signals::USER_1, pending: Signals::NONE }, + ]; + assert_eq!(object_wait_many(&mut items, ten_ms.after_now()), Err(Status::TIMED_OUT)); + assert_eq!(items[0].pending, Signals::NONE); + assert_eq!(items[1].pending, Signals::NONE); + + // Signal one object and it should return success. + assert!(e1.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + assert!(object_wait_many(&mut items, ten_ms.after_now()).is_ok()); + assert_eq!(items[0].pending, Signals::USER_0); + assert_eq!(items[1].pending, Signals::NONE); + + // Signal the other and it should return both. + assert!(e2.signal_handle(Signals::NONE, Signals::USER_1).is_ok()); + assert!(object_wait_many(&mut items, ten_ms.after_now()).is_ok()); + assert_eq!(items[0].pending, Signals::USER_0); + assert_eq!(items[1].pending, Signals::USER_1); + + // Clear signals on both; now it should time out again. + assert!(e1.signal_handle(Signals::USER_0, Signals::NONE).is_ok()); + assert!(e2.signal_handle(Signals::USER_1, Signals::NONE).is_ok()); + assert_eq!(object_wait_many(&mut items, ten_ms.after_now()), Err(Status::TIMED_OUT)); + assert_eq!(items[0].pending, Signals::NONE); + assert_eq!(items[1].pending, Signals::NONE); + } + + #[test] + fn cookies() { + let event = Event::create().unwrap(); + let scope = Event::create().unwrap(); + + // Getting a cookie when none has been set should fail. + assert_eq!(event.get_cookie(&scope.as_handle_ref()), Err(Status::ACCESS_DENIED)); + + // Set a cookie. + assert_eq!(event.set_cookie(&scope.as_handle_ref(), 42), Ok(())); + + // Should get it back.... + assert_eq!(event.get_cookie(&scope.as_handle_ref()), Ok(42)); + + // but not with the wrong scope! + assert_eq!(event.get_cookie(&event.as_handle_ref()), Err(Status::ACCESS_DENIED)); + + // Can change it, with the same scope... + assert_eq!(event.set_cookie(&scope.as_handle_ref(), 123), Ok(())); + + // but not with a different scope. + assert_eq!(event.set_cookie(&event.as_handle_ref(), 123), Err(Status::ACCESS_DENIED)); + } +} + +pub fn usize_into_u32(n: usize) -> Result { + if n > ::std::u32::MAX as usize || n < ::std::u32::MIN as usize { + return Err(()) + } + Ok(n as u32) +} + +pub fn size_to_u32_sat(n: usize) -> u32 { + if n > ::std::u32::MAX as usize { + return ::std::u32::MAX; + } + if n < ::std::u32::MIN as usize { + return ::std::u32::MIN; + } + n as u32 +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/port.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/port.rs new file mode 100644 index 0000000..6a9e8a8 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/port.rs @@ -0,0 +1,344 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon port objects. + +use std::mem; + +use {AsHandleRef, HandleBased, Handle, HandleRef, Signals, Status, Time}; +use {sys, ok}; + +/// An object representing a Zircon +/// [port](https://fuchsia.googlesource.com/zircon/+/master/docs/objects/port.md). +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Port(Handle); +impl_handle_based!(Port); + +/// A packet sent through a port. This is a type-safe wrapper for +/// [zx_port_packet_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md). +#[derive(PartialEq, Eq, Debug)] +pub struct Packet(sys::zx_port_packet_t); + +/// The contents of a `Packet`. +#[derive(Debug, Copy, Clone)] +pub enum PacketContents { + /// A user-generated packet. + User(UserPacket), + /// A one-shot signal packet generated via `object_wait_async`. + SignalOne(SignalPacket), + /// A repeating signal packet generated via `object_wait_async`. + SignalRep(SignalPacket), + + #[doc(hidden)] + __Nonexhaustive +} + +/// Contents of a user packet (one sent by `port_queue`). This is a type-safe wrapper for +/// [zx_packet_user_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md). +#[derive(Debug, Copy, Clone)] +pub struct UserPacket(sys::zx_packet_user_t); + +/// Contents of a signal packet (one generated by the kernel). This is a type-safe wrapper for +/// [zx_packet_signal_t](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md). +#[derive(Debug, Copy, Clone)] +pub struct SignalPacket(sys::zx_packet_signal_t); + +impl Packet { + /// Creates a new packet with `UserPacket` data. + pub fn from_user_packet(key: u64, status: i32, user: UserPacket) -> Packet { + Packet( + sys::zx_port_packet_t { + key: key, + packet_type: sys::zx_packet_type_t::ZX_PKT_TYPE_USER, + status: status, + union: user.0, + } + ) + } + + /// The packet's key. + pub fn key(&self) -> u64 { + self.0.key + } + + /// The packet's status. + // TODO: should this type be wrapped? + pub fn status(&self) -> i32 { + self.0.status + } + + /// The contents of the packet. + pub fn contents(&self) -> PacketContents { + if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_USER { + PacketContents::User(UserPacket(self.0.union)) + } else if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_SIGNAL_ONE { + PacketContents::SignalOne(SignalPacket(unsafe { mem::transmute_copy(&self.0.union) })) + } else if self.0.packet_type == sys::zx_packet_type_t::ZX_PKT_TYPE_SIGNAL_REP { + PacketContents::SignalRep(SignalPacket(unsafe { mem::transmute_copy(&self.0.union) })) + } else { + panic!("unexpected packet type"); + } + } +} + +impl UserPacket { + pub fn from_u8_array(val: [u8; 32]) -> UserPacket { + UserPacket(val) + } + + pub fn as_u8_array(&self) -> &[u8; 32] { + &self.0 + } + + pub fn as_mut_u8_array(&mut self) -> &mut [u8; 32] { + &mut self.0 + } +} + +impl SignalPacket { + /// The signals used in the call to `object_wait_async`. + pub fn trigger(&self) -> Signals { + Signals::from_bits_truncate(self.0.trigger) + } + + /// The observed signals. + pub fn observed(&self) -> Signals { + Signals::from_bits_truncate(self.0.observed) + } + + /// A per object count of pending operations. + pub fn count(&self) -> u64 { + self.0.count + } +} + +impl Port { + /// Create an IO port, allowing IO packets to be read and enqueued. + /// + /// Wraps the + /// [zx_port_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_create.md) + /// syscall. + pub fn create() -> Result { + unsafe { + let mut handle = 0; + let opts = 0; + let status = sys::zx_port_create(opts, &mut handle); + ok(status)?; + Ok(Handle::from_raw(handle).into()) + } + } + + /// Attempt to queue a user packet to the IO port. + /// + /// Wraps the + /// [zx_port_queue](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_queue.md) + /// syscall. + pub fn queue(&self, packet: &Packet) -> Result<(), Status> { + let status = unsafe { + sys::zx_port_queue(self.raw_handle(), + &packet.0 as *const sys::zx_port_packet_t, 0) + }; + ok(status) + } + + /// Wait for a packet to arrive on a (V2) port. + /// + /// Wraps the + /// [zx_port_wait](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/port_wait.md) + /// syscall. + pub fn wait(&self, deadline: Time) -> Result { + let mut packet = Default::default(); + let status = unsafe { + sys::zx_port_wait(self.raw_handle(), deadline.nanos(), + &mut packet as *mut sys::zx_port_packet_t, 0) + }; + ok(status)?; + Ok(Packet(packet)) + } + + /// Cancel pending wait_async calls for an object with the given key. + /// + /// Wraps the + /// [zx_port_cancel](https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/port_cancel.md) + /// syscall. + pub fn cancel(&self, source: &H, key: u64) -> Result<(), Status> where H: HandleBased { + let status = unsafe { + sys::zx_port_cancel(self.raw_handle(), source.raw_handle(), key) + }; + ok(status) + } +} + +/// Options for wait_async. +#[repr(u32)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum WaitAsyncOpts { + Once = sys::ZX_WAIT_ASYNC_ONCE, + Repeating = sys::ZX_WAIT_ASYNC_REPEATING, +} + +#[cfg(test)] +mod tests { + use super::*; + use {DurationNum, Event}; + + #[test] + fn port_basic() { + let ten_ms = 10.millis(); + + let port = Port::create().unwrap(); + + // Waiting now should time out. + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // Send a valid packet. + let packet = Packet::from_user_packet( + 42, + 123, + UserPacket::from_u8_array([13; 32]), + ); + assert!(port.queue(&packet).is_ok()); + + // Waiting should succeed this time. We should get back the packet we sent. + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet, packet); + } + + #[test] + fn wait_async_once() { + let ten_ms = 10.millis(); + let key = 42; + + let port = Port::create().unwrap(); + let event = Event::create().unwrap(); + + assert!(event.wait_async_handle(&port, key, Signals::USER_0 | Signals::USER_1, + WaitAsyncOpts::Once).is_ok()); + + // Waiting without setting any signal should time out. + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // If we set a signal, we should be able to wait for it. + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet.key(), key); + assert_eq!(read_packet.status(), 0); + match read_packet.contents() { + PacketContents::SignalOne(sig) => { + assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1); + assert_eq!(sig.observed(), Signals::USER_0); + assert_eq!(sig.count(), 1); + } + _ => panic!("wrong packet type"), + } + + // Shouldn't get any more packets. + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // Calling wait_async again should result in another packet. + assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok()); + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet.key(), key); + assert_eq!(read_packet.status(), 0); + match read_packet.contents() { + PacketContents::SignalOne(sig) => { + assert_eq!(sig.trigger(), Signals::USER_0); + assert_eq!(sig.observed(), Signals::USER_0); + assert_eq!(sig.count(), 1); + } + _ => panic!("wrong packet type"), + } + + // Calling wait_async_handle then cancel, we should not get a packet as cancel will + // remove it from the queue. + assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok()); + assert!(port.cancel(&event, key).is_ok()); + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // If the event is signalled after the cancel, we also shouldn't get a packet. + assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok()); // clear signal + assert!(event.wait_async_handle(&port, key, Signals::USER_0, WaitAsyncOpts::Once).is_ok()); + assert!(port.cancel(&event, key).is_ok()); + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + } + + #[test] + fn wait_async_repeating() { + let ten_ms = 10.millis(); + let key = 42; + + let port = Port::create().unwrap(); + let event = Event::create().unwrap(); + + assert!(event.wait_async_handle(&port, key, Signals::USER_0 | Signals::USER_1, + WaitAsyncOpts::Repeating).is_ok()); + + // Waiting without setting any signal should time out. + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // If we set a signal, we should be able to wait for it. + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet.key(), key); + assert_eq!(read_packet.status(), 0); + match read_packet.contents() { + PacketContents::SignalRep(sig) => { + assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1); + assert_eq!(sig.observed(), Signals::USER_0); + assert_eq!(sig.count(), 1); + } + _ => panic!("wrong packet type"), + } + + // Should not get any more packets, as ZX_WAIT_ASYNC_REPEATING is edge triggered rather than + // level triggered. + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // If we clear and resignal, we should get the same packet again, + // even though we didn't call event.wait_async again. + assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok()); // clear signal + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet.key(), key); + assert_eq!(read_packet.status(), 0); + match read_packet.contents() { + PacketContents::SignalRep(sig) => { + assert_eq!(sig.trigger(), Signals::USER_0 | Signals::USER_1); + assert_eq!(sig.observed(), Signals::USER_0); + assert_eq!(sig.count(), 1); + } + _ => panic!("wrong packet type"), + } + + // Cancelling the wait should stop us getting packets... + assert!(port.cancel(&event, key).is_ok()); + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + // ... even if we clear and resignal + assert!(event.signal_handle(Signals::USER_0, Signals::NONE).is_ok()); // clear signal + assert!(event.signal_handle(Signals::NONE, Signals::USER_0).is_ok()); + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + + // Calling wait_async again should result in another packet. + assert!(event.wait_async_handle( + &port, key, Signals::USER_0, WaitAsyncOpts::Repeating).is_ok()); + let read_packet = port.wait(ten_ms.after_now()).unwrap(); + assert_eq!(read_packet.key(), key); + assert_eq!(read_packet.status(), 0); + match read_packet.contents() { + PacketContents::SignalRep(sig) => { + assert_eq!(sig.trigger(), Signals::USER_0); + assert_eq!(sig.observed(), Signals::USER_0); + assert_eq!(sig.count(), 1); + } + _ => panic!("wrong packet type"), + } + + // Closing the handle should stop us getting packets. + drop(event); + assert_eq!(port.wait(ten_ms.after_now()), Err(Status::TIMED_OUT)); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/process.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/process.rs new file mode 100644 index 0000000..b46f1bd --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/process.rs @@ -0,0 +1,14 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon process. + +use {AsHandleRef, HandleBased, Handle, HandleRef}; + +/// An object representing a Zircon process. +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Process(Handle); +impl_handle_based!(Process); \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/rights.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/rights.rs new file mode 100644 index 0000000..a41ad12 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/rights.rs @@ -0,0 +1,28 @@ +use sys; + +bitflags! { + /// Rights associated with a handle. + /// + /// See [rights.md](https://fuchsia.googlesource.com/zircon/+/master/docs/rights.md) + /// for more information. + #[repr(C)] + pub struct Rights: sys::zx_rights_t { + const NONE = sys::ZX_RIGHT_NONE; + const DUPLICATE = sys::ZX_RIGHT_DUPLICATE; + const TRANSFER = sys::ZX_RIGHT_TRANSFER; + const READ = sys::ZX_RIGHT_READ; + const WRITE = sys::ZX_RIGHT_WRITE; + const EXECUTE = sys::ZX_RIGHT_EXECUTE; + const MAP = sys::ZX_RIGHT_MAP; + const GET_PROPERTY = sys::ZX_RIGHT_GET_PROPERTY; + const SET_PROPERTY = sys::ZX_RIGHT_SET_PROPERTY; + const ENUMERATE = sys::ZX_RIGHT_ENUMERATE; + const DESTROY = sys::ZX_RIGHT_DESTROY; + const SET_POLICY = sys::ZX_RIGHT_SET_POLICY; + const GET_POLICY = sys::ZX_RIGHT_GET_POLICY; + const SIGNAL = sys::ZX_RIGHT_SIGNAL; + const SIGNAL_PEER = sys::ZX_RIGHT_SIGNAL_PEER; + const WAIT = sys::ZX_RIGHT_WAIT; + const SAME_RIGHTS = sys::ZX_RIGHT_SAME_RIGHTS; + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/signals.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/signals.rs new file mode 100644 index 0000000..e5189f5 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/signals.rs @@ -0,0 +1,105 @@ +use sys::*; + +bitflags! { + /// Signals that can be waited upon. + /// + /// See + /// [Objects and signals](https://fuchsia.googlesource.com/zircon/+/master/docs/concepts.md#Objects-and-Signals) + /// in the Zircon kernel documentation. Note: the names of signals are still in flux. + #[repr(C)] + pub struct Signals: zx_signals_t { + const NONE = ZX_SIGNAL_NONE; + const OBJECT_ALL = ZX_OBJECT_SIGNAL_ALL; + const USER_ALL = ZX_USER_SIGNAL_ALL; + const OBJECT_0 = ZX_OBJECT_SIGNAL_0; + const OBJECT_1 = ZX_OBJECT_SIGNAL_1; + const OBJECT_2 = ZX_OBJECT_SIGNAL_2; + const OBJECT_3 = ZX_OBJECT_SIGNAL_3; + const OBJECT_4 = ZX_OBJECT_SIGNAL_4; + const OBJECT_5 = ZX_OBJECT_SIGNAL_5; + const OBJECT_6 = ZX_OBJECT_SIGNAL_6; + const OBJECT_7 = ZX_OBJECT_SIGNAL_7; + const OBJECT_8 = ZX_OBJECT_SIGNAL_8; + const OBJECT_9 = ZX_OBJECT_SIGNAL_9; + const OBJECT_10 = ZX_OBJECT_SIGNAL_10; + const OBJECT_11 = ZX_OBJECT_SIGNAL_11; + const OBJECT_12 = ZX_OBJECT_SIGNAL_12; + const OBJECT_13 = ZX_OBJECT_SIGNAL_13; + const OBJECT_14 = ZX_OBJECT_SIGNAL_14; + const OBJECT_15 = ZX_OBJECT_SIGNAL_15; + const OBJECT_16 = ZX_OBJECT_SIGNAL_16; + const OBJECT_17 = ZX_OBJECT_SIGNAL_17; + const OBJECT_18 = ZX_OBJECT_SIGNAL_18; + const OBJECT_19 = ZX_OBJECT_SIGNAL_19; + const OBJECT_20 = ZX_OBJECT_SIGNAL_20; + const OBJECT_21 = ZX_OBJECT_SIGNAL_21; + const OBJECT_22 = ZX_OBJECT_SIGNAL_22; + const OBJECT_HANDLE_CLOSED = ZX_OBJECT_HANDLE_CLOSED; + const USER_0 = ZX_USER_SIGNAL_0; + const USER_1 = ZX_USER_SIGNAL_1; + const USER_2 = ZX_USER_SIGNAL_2; + const USER_3 = ZX_USER_SIGNAL_3; + const USER_4 = ZX_USER_SIGNAL_4; + const USER_5 = ZX_USER_SIGNAL_5; + const USER_6 = ZX_USER_SIGNAL_6; + const USER_7 = ZX_USER_SIGNAL_7; + + const OBJECT_READABLE = ZX_OBJECT_READABLE; + const OBJECT_WRITABLE = ZX_OBJECT_WRITABLE; + const OBJECT_PEER_CLOSED = ZX_OBJECT_PEER_CLOSED; + + // Cancelation (handle was closed while waiting with it) + const HANDLE_CLOSED = ZX_SIGNAL_HANDLE_CLOSED; + + // Event + const EVENT_SIGNALED = ZX_EVENT_SIGNALED; + + // EventPair + const EVENT_PAIR_SIGNALED = ZX_EPAIR_SIGNALED; + const EVENT_PAIR_CLOSED = ZX_EPAIR_CLOSED; + + // Task signals (process, thread, job) + const TASK_TERMINATED = ZX_TASK_TERMINATED; + + // Channel + const CHANNEL_READABLE = ZX_CHANNEL_READABLE; + const CHANNEL_WRITABLE = ZX_CHANNEL_WRITABLE; + const CHANNEL_PEER_CLOSED = ZX_CHANNEL_PEER_CLOSED; + + // Socket + const SOCKET_READABLE = ZX_SOCKET_READABLE; + const SOCKET_WRITABLE = ZX_SOCKET_WRITABLE; + const SOCKET_PEER_CLOSED = ZX_SOCKET_PEER_CLOSED; + + // Port + const PORT_READABLE = ZX_PORT_READABLE; + + // Resource + const RESOURCE_DESTROYED = ZX_RESOURCE_DESTROYED; + const RESOURCE_READABLE = ZX_RESOURCE_READABLE; + const RESOURCE_WRITABLE = ZX_RESOURCE_WRITABLE; + const RESOURCE_CHILD_ADDED = ZX_RESOURCE_CHILD_ADDED; + + // Fifo + const FIFO_READABLE = ZX_FIFO_READABLE; + const FIFO_WRITABLE = ZX_FIFO_WRITABLE; + const FIFO_PEER_CLOSED = ZX_FIFO_PEER_CLOSED; + + // Job + const JOB_NO_PROCESSES = ZX_JOB_NO_PROCESSES; + const JOB_NO_JOBS = ZX_JOB_NO_JOBS; + + // Process + const PROCESS_TERMINATED = ZX_PROCESS_TERMINATED; + + // Thread + const THREAD_TERMINATED = ZX_THREAD_TERMINATED; + + // Log + const LOG_READABLE = ZX_LOG_READABLE; + const LOG_WRITABLE = ZX_LOG_WRITABLE; + + // Timer + const TIMER_SIGNALED = ZX_TIMER_SIGNALED; + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/socket.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/socket.rs new file mode 100644 index 0000000..c93e98c --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/socket.rs @@ -0,0 +1,126 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon sockets. + +use {AsHandleRef, HandleBased, Handle, HandleRef, Peered}; +use {sys, Status, ok}; + +use std::ptr; + +/// An object representing a Zircon +/// [socket](https://fuchsia.googlesource.com/zircon/+/master/docs/concepts.md#Message-Passing_Sockets-and-Channels). +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Socket(Handle); +impl_handle_based!(Socket); +impl Peered for Socket {} + +impl Socket { + /// Create a socket, accessed through a pair of endpoints. Data written + /// into one may be read from the other. + /// + /// Wraps + /// [zx_socket_create](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/socket_create.md). + pub fn create() -> Result<(Socket, Socket), Status> { + unsafe { + let mut out0 = 0; + let mut out1 = 0; + let opts = 0; + let status = sys::zx_socket_create(opts, &mut out0, &mut out1); + ok(status)?; + Ok(( + Self::from(Handle::from_raw(out0)), + Self::from(Handle::from_raw(out1)) + )) + } + } + + /// Write the given bytes into the socket. + /// Return value (on success) is number of bytes actually written. + /// + /// Wraps + /// [zx_socket_write](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/socket_write.md). + pub fn write(&self, bytes: &[u8]) -> Result { + let mut actual = 0; + let opts = 0; + let status = unsafe { + sys::zx_socket_write(self.raw_handle(), opts, bytes.as_ptr(), bytes.len(), + &mut actual) + }; + ok(status).map(|()| actual) + } + + /// Read the given bytes from the socket. + /// Return value (on success) is number of bytes actually read. + /// + /// Wraps + /// [zx_socket_read](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/socket_read.md). + pub fn read(&self, bytes: &mut [u8]) -> Result { + let mut actual = 0; + let opts = 0; + let status = unsafe { + sys::zx_socket_read(self.raw_handle(), opts, bytes.as_mut_ptr(), + bytes.len(), &mut actual) + }; + ok(status) + .map(|()| actual) + .map_err(|status| { + // If an error is returned then actual is undefined, so to be safe + // we set it to 0 and ignore any data that is set in bytes. + actual = 0; + status + }) + } + + /// Close half of the socket, so attempts by the other side to write will fail. + /// + /// Implements the `ZX_SOCKET_HALF_CLOSE` option of + /// [zx_socket_write](https://fuchsia.googlesource.com/zircon/+/master/docs/syscalls/socket_write.md). + pub fn half_close(&self) -> Result<(), Status> { + let status = unsafe { sys::zx_socket_write(self.raw_handle(), sys::ZX_SOCKET_HALF_CLOSE, + ptr::null(), 0, ptr::null_mut()) }; + ok(status) + } + + pub fn outstanding_read_bytes(&self) -> Result { + let mut outstanding = 0; + let status = unsafe { + sys::zx_socket_read(self.raw_handle(), 0, ptr::null_mut(), 0, &mut outstanding) + }; + ok(status).map(|()| outstanding) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn socket_basic() { + let (s1, s2) = Socket::create().unwrap(); + + // Write in one end and read it back out the other. + assert_eq!(s1.write(b"hello").unwrap(), 5); + + let mut read_vec = vec![0; 8]; + assert_eq!(s2.read(&mut read_vec).unwrap(), 5); + assert_eq!(&read_vec[0..5], b"hello"); + + // Try reading when there is nothing to read. + assert_eq!(s2.read(&mut read_vec), Err(Status::SHOULD_WAIT)); + + // Close the socket from one end. + assert!(s1.half_close().is_ok()); + assert_eq!(s2.read(&mut read_vec), Err(Status::BAD_STATE)); + assert_eq!(s1.write(b"fail"), Err(Status::BAD_STATE)); + + // Writing in the other direction should still work. + assert_eq!(s1.read(&mut read_vec), Err(Status::SHOULD_WAIT)); + assert_eq!(s2.write(b"back").unwrap(), 4); + assert_eq!(s1.read(&mut read_vec).unwrap(), 4); + assert_eq!(&read_vec[0..4], b"back"); + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/status.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/status.rs new file mode 100644 index 0000000..4f3e38f --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/status.rs @@ -0,0 +1,162 @@ +use std::ffi::NulError; +use std::io; +use sys; + +/// Status type indicating the result of a Fuchsia syscall. +/// +/// This type is generally used to indicate the reason for an error. +/// While this type can contain `Status::OK` (`ZX_OK` in C land), elements of this type are +/// generally constructed using the `ok` method, which checks for `ZX_OK` and returns a +/// `Result<(), Status>` appropriately. +#[repr(C)] +#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] +pub struct Status(sys::zx_status_t); +impl Status { + /// Returns `Ok(())` if the status was `OK`, + /// otherwise returns `Err(status)`. + pub fn ok(raw: sys::zx_status_t) -> Result<(), Status> { + if raw == Status::OK.0 { + Ok(()) + } else { + Err(Status(raw)) + } + } + + pub fn from_raw(raw: sys::zx_status_t) -> Self { + Status(raw) + } + + pub fn into_raw(self) -> sys::zx_status_t { + self.0 + } +} +assoc_consts!(Status, [ + OK = sys::ZX_OK; + INTERNAL = sys::ZX_ERR_INTERNAL; + NOT_SUPPORTED = sys::ZX_ERR_NOT_SUPPORTED; + NO_RESOURCES = sys::ZX_ERR_NO_RESOURCES; + NO_MEMORY = sys::ZX_ERR_NO_MEMORY; + CALL_FAILED = sys::ZX_ERR_CALL_FAILED; + INTERRUPTED_RETRY = sys::ZX_ERR_INTERRUPTED_RETRY; + INVALID_ARGS = sys::ZX_ERR_INVALID_ARGS; + BAD_HANDLE = sys::ZX_ERR_BAD_HANDLE; + WRONG_TYPE = sys::ZX_ERR_WRONG_TYPE; + BAD_SYSCALL = sys::ZX_ERR_BAD_SYSCALL; + OUT_OF_RANGE = sys::ZX_ERR_OUT_OF_RANGE; + BUFFER_TOO_SMALL = sys::ZX_ERR_BUFFER_TOO_SMALL; + BAD_STATE = sys::ZX_ERR_BAD_STATE; + TIMED_OUT = sys::ZX_ERR_TIMED_OUT; + SHOULD_WAIT = sys::ZX_ERR_SHOULD_WAIT; + CANCELED = sys::ZX_ERR_CANCELED; + PEER_CLOSED = sys::ZX_ERR_PEER_CLOSED; + NOT_FOUND = sys::ZX_ERR_NOT_FOUND; + ALREADY_EXISTS = sys::ZX_ERR_ALREADY_EXISTS; + ALREADY_BOUND = sys::ZX_ERR_ALREADY_BOUND; + UNAVAILABLE = sys::ZX_ERR_UNAVAILABLE; + ACCESS_DENIED = sys::ZX_ERR_ACCESS_DENIED; + IO = sys::ZX_ERR_IO; + IO_REFUSED = sys::ZX_ERR_IO_REFUSED; + IO_DATA_INTEGRITY = sys::ZX_ERR_IO_DATA_INTEGRITY; + IO_DATA_LOSS = sys::ZX_ERR_IO_DATA_LOSS; + BAD_PATH = sys::ZX_ERR_BAD_PATH; + NOT_DIR = sys::ZX_ERR_NOT_DIR; + NOT_FILE = sys::ZX_ERR_NOT_FILE; + FILE_BIG = sys::ZX_ERR_FILE_BIG; + NO_SPACE = sys::ZX_ERR_NO_SPACE; + STOP = sys::ZX_ERR_STOP; + NEXT = sys::ZX_ERR_NEXT; +]); + +impl Status { + pub fn into_io_error(self) -> io::Error { + self.into() + } +} + +impl From for Status { + fn from(kind: io::ErrorKind) -> Self { + use std::io::ErrorKind::*; + match kind { + NotFound => Status::NOT_FOUND, + PermissionDenied => Status::ACCESS_DENIED, + ConnectionRefused => Status::IO_REFUSED, + ConnectionAborted => Status::PEER_CLOSED, + AddrInUse => Status::ALREADY_BOUND, + AddrNotAvailable => Status::UNAVAILABLE, + BrokenPipe => Status::PEER_CLOSED, + AlreadyExists => Status::ALREADY_EXISTS, + WouldBlock => Status::SHOULD_WAIT, + InvalidInput => Status::INVALID_ARGS, + TimedOut => Status::TIMED_OUT, + Interrupted => Status::INTERRUPTED_RETRY, + UnexpectedEof | + WriteZero | + ConnectionReset | + NotConnected | + Other | _ => Status::IO, + } + } +} + +impl From for io::ErrorKind { + fn from(status: Status) -> io::ErrorKind { + use std::io::ErrorKind::*; + match status { + Status::INTERRUPTED_RETRY => Interrupted, + Status::BAD_HANDLE => BrokenPipe, + Status::TIMED_OUT => TimedOut, + Status::SHOULD_WAIT => WouldBlock, + Status::PEER_CLOSED => ConnectionAborted, + Status::NOT_FOUND => NotFound, + Status::ALREADY_EXISTS => AlreadyExists, + Status::ALREADY_BOUND => AlreadyExists, + Status::UNAVAILABLE => AddrNotAvailable, + Status::ACCESS_DENIED => PermissionDenied, + Status::IO_REFUSED => ConnectionRefused, + Status::IO_DATA_INTEGRITY => InvalidData, + + Status::BAD_PATH | + Status::INVALID_ARGS | + Status::OUT_OF_RANGE | + Status::WRONG_TYPE => InvalidInput, + + Status::OK | + Status::NEXT | + Status::STOP | + Status::NO_SPACE | + Status::FILE_BIG | + Status::NOT_FILE | + Status::NOT_DIR | + Status::IO_DATA_LOSS | + Status::IO | + Status::CANCELED | + Status::BAD_STATE | + Status::BUFFER_TOO_SMALL | + Status::BAD_SYSCALL | + Status::INTERNAL | + Status::NOT_SUPPORTED | + Status::NO_RESOURCES | + Status::NO_MEMORY | + Status::CALL_FAILED | + _ => Other, + } + } +} + +impl From for Status { + fn from(err: io::Error) -> Status { + err.kind().into() + } +} + +impl From for io::Error { + fn from(status: Status) -> io::Error { + io::Error::from(io::ErrorKind::from(status)) + } +} + +impl From for Status { + fn from(_error: NulError) -> Status { + Status::INVALID_ARGS + } +} diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/thread.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/thread.rs new file mode 100644 index 0000000..be48237 --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/thread.rs @@ -0,0 +1,14 @@ +// Copyright 2017 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon thread. + +use {AsHandleRef, HandleBased, Handle, HandleRef}; + +/// An object representing a Zircon thread. +/// +/// As essentially a subtype of `Handle`, it can be freely interconverted. +#[derive(Debug, Eq, PartialEq)] +pub struct Thread(Handle); +impl_handle_based!(Thread); \ No newline at end of file diff --git a/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/time.rs b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/time.rs new file mode 100644 index 0000000..1b1deac --- /dev/null +++ b/third_party/cargo/vendor/fuchsia-zircon-0.3.3/src/time.rs @@ -0,0 +1,346 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! Type-safe bindings for Zircon timer objects. + +use {AsHandleRef, ClockId, HandleBased, Handle, HandleRef, Status}; +use {sys, ok}; +use std::ops; +use std::time as stdtime; + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct Duration(sys::zx_duration_t); + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct Time(sys::zx_time_t); + +impl From for Duration { + fn from(dur: stdtime::Duration) -> Self { + Duration::from_seconds(dur.as_secs()) + + Duration::from_nanos(dur.subsec_nanos() as u64) + } +} + +impl From for stdtime::Duration { + fn from(dur: Duration) -> Self { + let secs = dur.seconds(); + let nanos = (dur.nanos() - (secs * 1_000_000_000)) as u32; + stdtime::Duration::new(secs, nanos) + } +} + +impl ops::Add for Time { + type Output = Time; + fn add(self, dur: Duration) -> Time { + Time::from_nanos(dur.nanos() + self.nanos()) + } +} + +impl ops::Add +## v1.2.1 (2018-12-03) + + +#### Features + +* Implement Clone for LazyCell and AtomicLazyCell ([30fe4a8f](https://github.com/indiv0/lazycell/commit/30fe4a8f568059b3c78ed149a810962a676cb2b2)) + + + + +## v1.2.0 (2018-09-19) + + +#### Features + +* add `LazyCell::replace` for infallible access ([a63ffb90](https://github.com/indiv0/lazycell/commit/a63ffb9040a5e0683a9bbf9d3d5ef589f2ca8b7c)) + + + + +## v1.1.0 (2018-09-10) + + +#### Documentation + +* add note regarding LazyCell::borrow_mut ([9d634d1f](https://github.com/indiv0/lazycell/commit/9d634d1fd9a21b7aa075d407bedf9fe77ba8b79f)) +* describe mutability more consistently ([b8078029](https://github.com/indiv0/lazycell/commit/b80780294611e92efddcdd33a701b3049ab5c5eb), closes [#78](https://github.com/indiv0/lazycell/issues/78)) + +#### Improvements + +* add NONE constant for an empty AtomicLazyCell ([31aff0da](https://github.com/indiv0/lazycell/commit/31aff0dacf824841c5f38ef4acf0aa71ec4c36eb), closes [#87](https://github.com/indiv0/lazycell/issues/87)) +* add `LazyCell::borrow_mut_with` and `LazyCell::try_borrow_mut_with` ([fdc6d268](https://github.com/indiv0/lazycell/commit/fdc6d268f0e9a6668768302f45fe2bb4aa9a7c34), closes [#79](https://github.com/indiv0/lazycell/issues/79), [#80](https://github.com/indiv0/lazycell/issues/80)) + + + + +## v1.0.0 (2018-06-06) + + +#### Features + +* Add #![no_std] ([e59f6b55](https://github.com/indiv0/lazycell/commit/e59f6b5531e310d3df26b0eb40b1431937f38096)) + + + + +## 0.6.0 (2017-11-25) + + +#### Bug Fixes + +* fix soundness hole in borrow_with ([d1f46bef](https://github.com/indiv0/lazycell/commit/d1f46bef9d1397570aa9c3e87e18e0d16e6d1585)) + +#### Features + +* add Default derives ([71bc5088](https://github.com/indiv0/lazycell/commit/71bc50880cd8e20002038197c9b890f5b76ad096)) +* add LazyCell::try_borrow_with ([bffa4028](https://github.com/indiv0/lazycell/commit/bffa402896670b5c78a9ec050d82a58ee98de6fb)) +* add LazyCell::borrow_mut method ([fd419dea](https://github.com/indiv0/lazycell/commit/fd419dea965ff1ad3853f26f37e8d107c6ca096c)) + +#### Breaking Changes + +* add `T: Send` for `AtomicLazyCell` `Sync` impl ([668bb2fa](https://github.com/indiv0/lazycell/commit/668bb2fa974fd6707c4c7edad292c76a9017d74d), closes [#67](https://github.com/indiv0/lazycell/issues/67)) + +#### Improvements + +* add `T: Send` for `AtomicLazyCell` `Sync` impl ([668bb2fa](https://github.com/indiv0/lazycell/commit/668bb2fa974fd6707c4c7edad292c76a9017d74d), closes [#67](https://github.com/indiv0/lazycell/issues/67)) + + + + +## v0.5.1 (2017-03-24) + + +#### Documentation + +* fix missing backticks ([44bafaaf](https://github.com/indiv0/lazycell/commit/44bafaaf93a91641261f58ee38adadcd4af6458e)) + +#### Improvements + +* derive `Debug` impls ([9da0a5a2](https://github.com/indiv0/lazycell/commit/9da0a5a2ffac1fef03ef02851c2c89d26d67d225)) + +#### Features + +* Add get method for Copy types ([dc8f8209](https://github.com/indiv0/lazycell/commit/dc8f8209888b6eba6d18717eba6a22614629b997)) + + + + +## v0.5.0 (2016-12-08) + + +#### Features + +* add borrow_with to LazyCell ([a15efa35](https://github.com/indiv0/lazycell/commit/a15efa359ea5a31a66ba57fc5b25f90c87b4b0dd)) + + + + +## (2016-08-17) + + +#### Breaking Changes + +* **LazyCell:** return Err(value) on full cell ([68f3415d](https://github.com/indiv0/lazycell/commit/68f3415dd5d6a66ba047a133b7028ebe4f1c5070), breaks [#](https://github.com/indiv0/lazycell/issues/)) + +#### Improvements + +* **LazyCell:** return Err(value) on full cell ([68f3415d](https://github.com/indiv0/lazycell/commit/68f3415dd5d6a66ba047a133b7028ebe4f1c5070), breaks [#](https://github.com/indiv0/lazycell/issues/)) + + + + +## (2016-08-16) + + +#### Features + +* add AtomicLazyCell which is thread-safe ([85afbd36](https://github.com/indiv0/lazycell/commit/85afbd36d8a148e14cc53654b39ddb523980124d)) + +#### Improvements + +* Use UnsafeCell instead of RefCell ([3347a8e9](https://github.com/indiv0/lazycell/commit/3347a8e97d2215a47e25c1e2fc953e8052ad8eb6)) + + + + +## (2016-04-18) + + +#### Documentation + +* put types in between backticks ([607cf939](https://github.com/indiv0/lazycell/commit/607cf939b05e35001ba3070ec7a0b17b064e7be1)) + + + + +## v0.2.0 (2016-03-28) + + +#### Features + +* **lazycell:** + * add tests for `LazyCell` struct ([38f1313d](https://github.com/indiv0/lazycell/commit/38f1313d98542ca8c98b424edfa9ba9c3975f99e), closes [#30](https://github.com/indiv0/lazycell/issues/30)) + * remove unnecessary `Default` impl ([68c16d2d](https://github.com/indiv0/lazycell/commit/68c16d2df4e9d13d5298162c06edf918246fd758)) + +#### Documentation + +* **CHANGELOG:** removed unnecessary sections ([1cc0555d](https://github.com/indiv0/lazycell/commit/1cc0555d875898a01b0832ff967aed6b40e720eb)) +* **README:** add link to documentation ([c8dc33f0](https://github.com/indiv0/lazycell/commit/c8dc33f01f2c0dc187f59ee53a2b73081053012b), closes [#13](https://github.com/indiv0/lazycell/issues/13)) + + + + +## v0.1.0 (2016-03-16) + + +#### Features + +* **lib.rs:** implement Default trait for LazyCell ([150a6304](https://github.com/indiv0/LazyCell/commit/150a6304a230ee1de8424e49c447ec1b2d6578ce)) + + + + +## v0.0.1 (2016-03-16) + + +#### Bug Fixes + +* **Cargo.toml:** loosen restrictions on Clippy version ([84dd8f96](https://github.com/indiv0/LazyCell/commit/84dd8f960000294f9dad47d776a41b98ed812981)) + +#### Features + +* add initial implementation ([4b39764a](https://github.com/indiv0/LazyCell/commit/4b39764a575bcb701dbd8047b966f72720fd18a4)) +* add initial commit ([a80407a9](https://github.com/indiv0/LazyCell/commit/a80407a907ef7c9401f120104663172f6965521a)) + + + diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/Cargo.toml b/third_party/cargo/vendor/lazycell-1.2.1/Cargo.toml similarity index 51% rename from third_party/cargo/vendor/stable_deref_trait-1.1.1/Cargo.toml rename to third_party/cargo/vendor/lazycell-1.2.1/Cargo.toml index 0bbe977..faecd45 100644 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/Cargo.toml +++ b/third_party/cargo/vendor/lazycell-1.2.1/Cargo.toml @@ -11,17 +11,20 @@ # will likely look very different (and much more reasonable) [package] -name = "stable_deref_trait" -version = "1.1.1" -authors = ["Robert Grosse "] -description = "An unsafe marker trait for types like Box and Rc that dereference to a stable address even when moved, and hence can be used with libraries such as owning_ref and rental.\n" -documentation = "https://docs.rs/stable_deref_trait/1.1.1/stable_deref_trait" +name = "lazycell" +version = "1.2.1" +authors = ["Alex Crichton ", "Nikita Pekin "] +include = ["CHANGELOG.md", "Cargo.toml", "LICENSE-MIT", "LICENSE-APACHE", "README.md", "src/**/*.rs"] +description = "A library providing a lazily filled Cell struct" +documentation = "http://indiv0.github.io/lazycell/lazycell/" readme = "README.md" -categories = ["memory-management", "no-std"] +keywords = ["lazycell", "lazy", "cell", "library"] license = "MIT/Apache-2.0" -repository = "https://github.com/storyyeller/stable_deref_trait" +repository = "https://github.com/indiv0/lazycell" +[dependencies.clippy] +version = "0.0" +optional = true [features] -alloc = [] -default = ["std"] -std = [] +nightly = [] +nightly-testing = ["clippy", "nightly"] diff --git a/third_party/cargo/vendor/lock_api-0.1.5/LICENSE-APACHE b/third_party/cargo/vendor/lazycell-1.2.1/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/lock_api-0.1.5/LICENSE-APACHE rename to third_party/cargo/vendor/lazycell-1.2.1/LICENSE-APACHE diff --git a/third_party/cargo/vendor/lazycell-1.2.1/LICENSE-MIT b/third_party/cargo/vendor/lazycell-1.2.1/LICENSE-MIT new file mode 100644 index 0000000..b4cbb4b --- /dev/null +++ b/third_party/cargo/vendor/lazycell-1.2.1/LICENSE-MIT @@ -0,0 +1,26 @@ +Original work Copyright (c) 2014 The Rust Project Developers +Modified work Copyright (c) 2016-2018 Nikita Pekin and lazycell contributors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/lazycell-1.2.1/README.md b/third_party/cargo/vendor/lazycell-1.2.1/README.md new file mode 100644 index 0000000..4e1dd99 --- /dev/null +++ b/third_party/cargo/vendor/lazycell-1.2.1/README.md @@ -0,0 +1,72 @@ +# lazycell + + + + + + + + + +
Linuxtravis-badge
+ api-docs-badge + crates-io + license-badge + coveralls-badge +
+ +Rust library providing a lazily filled Cell. + +# Table of Contents + +* [Usage](#usage) +* [Contributing](#contributing) +* [Credits](#credits) +* [License](#license) + +## Usage + +Add the following to your `Cargo.toml`: + +```toml +[dependencies] +lazycell = "1.2" +``` + +And in your `lib.rs` or `main.rs`: + +```rust +extern crate lazycell; +``` + +See the [API docs][api-docs] for information on using the crate in your library. + +## Contributing + +Contributions are always welcome! +If you have an idea for something to add (code, documentation, tests, examples, +etc.) feel free to give it a shot. + +Please read [CONTRIBUTING.md][contributing] before you start contributing. + +## Credits + +The LazyCell library is based originally on work by The Rust Project Developers +for the project [crates.io][crates-io-repo]. + +The list of contributors to this project can be found at +[CONTRIBUTORS.md][contributors]. + +## License + +LazyCell is distributed under the terms of both the MIT license and the Apache +License (Version 2.0). + +See [LICENSE-APACHE][license-apache], and [LICENSE-MIT][license-mit] for details. + +[api-docs]: https://indiv0.github.io/lazycell/lazycell +[contributing]: https://github.com/indiv0/lazycell/blob/master/CONTRIBUTING.md "Contribution Guide" +[contributors]: https://github.com/indiv0/lazycell/blob/master/CONTRIBUTORS.md "List of Contributors" +[crates-io-repo]: https://github.com/rust-lang/crates.io "rust-lang/crates.io: Source code for crates.io" +[license-apache]: https://github.com/indiv0/lazycell/blob/master/LICENSE-APACHE "Apache-2.0 License" +[license-mit]: https://github.com/indiv0/lazycell/blob/master/LICENSE-MIT "MIT License" diff --git a/third_party/cargo/vendor/lazycell-1.2.1/src/lib.rs b/third_party/cargo/vendor/lazycell-1.2.1/src/lib.rs new file mode 100644 index 0000000..f7f8488 --- /dev/null +++ b/third_party/cargo/vendor/lazycell-1.2.1/src/lib.rs @@ -0,0 +1,649 @@ +// Original work Copyright (c) 2014 The Rust Project Developers +// Modified work Copyright (c) 2016-2018 Nikita Pekin and the lazycell contributors +// See the README.md file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(not(test), no_std)] + +#![deny(missing_docs)] +#![cfg_attr(feature = "nightly", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] + +//! This crate provides a `LazyCell` struct which acts as a lazily filled +//! `Cell`. +//! +//! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of +//! the entire object, but only of the borrows returned. A `LazyCell` is a +//! variation on `RefCell` which allows borrows to be tied to the lifetime of +//! the outer object. +//! +//! # Example +//! +//! The following example shows a quick example of the basic functionality of +//! `LazyCell`. +//! +//! ``` +//! use lazycell::LazyCell; +//! +//! let lazycell = LazyCell::new(); +//! +//! assert_eq!(lazycell.borrow(), None); +//! assert!(!lazycell.filled()); +//! lazycell.fill(1).ok(); +//! assert!(lazycell.filled()); +//! assert_eq!(lazycell.borrow(), Some(&1)); +//! assert_eq!(lazycell.into_inner(), Some(1)); +//! ``` +//! +//! `AtomicLazyCell` is a variant that uses an atomic variable to manage +//! coordination in a thread-safe fashion. The limitation of an `AtomicLazyCell` +//! is that after it is initialized, it can't be modified. + + +#[cfg(not(test))] +#[macro_use] +extern crate core as std; + +use std::cell::UnsafeCell; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A lazily filled `Cell`, with mutable contents. +/// +/// A `LazyCell` is completely frozen once filled, **unless** you have `&mut` +/// access to it, in which case `LazyCell::borrow_mut` may be used to mutate the +/// contents. +#[derive(Debug, Default)] +pub struct LazyCell { + inner: UnsafeCell>, +} + +impl LazyCell { + /// Creates a new, empty, `LazyCell`. + pub fn new() -> LazyCell { + LazyCell { inner: UnsafeCell::new(None) } + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, value: T) -> Result<(), T> { + let slot = unsafe { &mut *self.inner.get() }; + if slot.is_some() { + return Err(value); + } + *slot = Some(value); + + Ok(()) + } + + /// Put a value into this cell. + /// + /// Note that this function is infallible but requires `&mut self`. By + /// requiring `&mut self` we're guaranteed that no active borrows to this + /// cell can exist so we can always fill in the value. This may not always + /// be usable, however, as `&mut self` may not be possible to borrow. + /// + /// # Return value + /// + /// This function returns the previous value, if any. + pub fn replace(&mut self, value: T) -> Option { + mem::replace(unsafe { &mut *self.inner.get() }, Some(value)) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.borrow().is_some() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + unsafe { &*self.inner.get() }.as_ref() + } + + /// Borrows the contents of this lazy cell mutably for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow_mut(&mut self) -> Option<&mut T> { + unsafe { &mut *self.inner.get() }.as_mut() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// If the cell has not yet been filled, the cell is first filled using the + /// function provided. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn borrow_with T>(&self, f: F) -> &T { + if let Some(value) = self.borrow() { + return value; + } + let value = f(); + if self.fill(value).is_err() { + panic!("borrow_with: cell was filled by closure") + } + self.borrow().unwrap() + } + + /// Borrows the contents of this `LazyCell` mutably for the duration of the + /// cell itself. + /// + /// If the cell has not yet been filled, the cell is first filled using the + /// function provided. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn borrow_mut_with T>(&mut self, f: F) -> &mut T { + if !self.filled() { + let value = f(); + if self.fill(value).is_err() { + panic!("borrow_mut_with: cell was filled by closure") + } + } + + self.borrow_mut().unwrap() + } + + /// Same as `borrow_with`, but allows the initializing function to fail. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn try_borrow_with(&self, f: F) -> Result<&T, E> + where F: FnOnce() -> Result + { + if let Some(value) = self.borrow() { + return Ok(value); + } + let value = f()?; + if self.fill(value).is_err() { + panic!("try_borrow_with: cell was filled by closure") + } + Ok(self.borrow().unwrap()) + } + + /// Same as `borrow_mut_with`, but allows the initializing function to fail. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn try_borrow_mut_with(&mut self, f: F) -> Result<&mut T, E> + where F: FnOnce() -> Result + { + if self.filled() { + return Ok(self.borrow_mut().unwrap()); + } + let value = f()?; + if self.fill(value).is_err() { + panic!("try_borrow_mut_with: cell was filled by closure") + } + Ok(self.borrow_mut().unwrap()) + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe + // function. This unsafe can be removed when supporting Rust older than + // 1.25 is not needed. + #[allow(unused_unsafe)] + unsafe { self.inner.into_inner() } + } +} + +impl LazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + unsafe { *self.inner.get() } + } +} + +impl Clone for LazyCell { + /// Create a clone of this `LazyCell` + /// + /// If self has not been initialized, returns an uninitialized `LazyCell` + /// otherwise returns a `LazyCell` already initialized with a clone of the + /// contents of self. + fn clone(&self) -> LazyCell { + LazyCell { inner: UnsafeCell::new(self.borrow().map(Clone::clone) ) } + } +} + +// Tracks the AtomicLazyCell inner state +const NONE: usize = 0; +const LOCK: usize = 1; +const SOME: usize = 2; + +/// A lazily filled and thread-safe `Cell`, with frozen contents. +#[derive(Debug, Default)] +pub struct AtomicLazyCell { + inner: UnsafeCell>, + state: AtomicUsize, +} + +impl AtomicLazyCell { + /// An empty `AtomicLazyCell`. + pub const NONE: Self = Self { + inner: UnsafeCell::new(None), + state: AtomicUsize::new(NONE), + }; + + /// Creates a new, empty, `AtomicLazyCell`. + pub fn new() -> AtomicLazyCell { + Self::NONE + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, t: T) -> Result<(), T> { + if NONE != self.state.compare_and_swap(NONE, LOCK, Ordering::Acquire) { + return Err(t); + } + + unsafe { *self.inner.get() = Some(t) }; + + if LOCK != self.state.compare_and_swap(LOCK, SOME, Ordering::Release) { + panic!("unable to release lock"); + } + + Ok(()) + } + + /// Put a value into this cell. + /// + /// Note that this function is infallible but requires `&mut self`. By + /// requiring `&mut self` we're guaranteed that no active borrows to this + /// cell can exist so we can always fill in the value. This may not always + /// be usable, however, as `&mut self` may not be possible to borrow. + /// + /// # Return value + /// + /// This function returns the previous value, if any. + pub fn replace(&mut self, value: T) -> Option { + match mem::replace(self.state.get_mut(), SOME) { + NONE | SOME => {} + _ => panic!("cell in inconsistent state"), + } + mem::replace(unsafe { &mut *self.inner.get() }, Some(value)) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.state.load(Ordering::Acquire) == SOME + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { &*self.inner.get() }.as_ref(), + _ => None, + } + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe + // function. This unsafe can be removed when supporting Rust older than + // 1.25 is not needed. + #[allow(unused_unsafe)] + unsafe { self.inner.into_inner() } + } +} + +impl AtomicLazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { *self.inner.get() }, + _ => None, + } + } +} + +impl Clone for AtomicLazyCell { + /// Create a clone of this `AtomicLazyCell` + /// + /// If self has not been initialized, returns an uninitialized `AtomicLazyCell` + /// otherwise returns an `AtomicLazyCell` already initialized with a clone of the + /// contents of self. + fn clone(&self) -> AtomicLazyCell { + self.borrow().map_or( + Self::NONE, + |v| AtomicLazyCell { + inner: UnsafeCell::new(Some(v.clone())), + state: AtomicUsize::new(SOME), + } + ) + } +} + +unsafe impl Sync for AtomicLazyCell {} + +unsafe impl Send for AtomicLazyCell {} + +#[cfg(test)] +mod tests { + use super::{AtomicLazyCell, LazyCell}; + + #[test] + fn test_borrow_from_empty() { + let lazycell: LazyCell = LazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_fill_and_borrow() { + let lazycell = LazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_borrow_mut() { + let mut lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.borrow_mut(), Some(&mut 1)); + + *lazycell.borrow_mut().unwrap() = 2; + assert_eq!(lazycell.borrow_mut(), Some(&mut 2)); + + // official way to reset the cell + lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + } + + #[test] + fn test_already_filled_error() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.fill(1), Err(1)); + } + + #[test] + fn test_borrow_with() { + let lazycell = LazyCell::new(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_not_called_when_filled() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 2); + assert_eq!(&1, value); + } + + #[test] + #[should_panic] + fn test_borrow_with_sound_with_reentrancy() { + // Kudos to dbaupp for discovering this issue + // https://www.reddit.com/r/rust/comments/5vs9rt/lazycell_a_rust_library_providing_a_lazilyfilled/de527xm/ + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + lazycell.borrow_with(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Box::new(2) + }); + } + + #[test] + fn test_borrow_mut_with() { + let mut lazycell = LazyCell::new(); + + { + let value = lazycell.borrow_mut_with(|| 1); + assert_eq!(&mut 1, value); + *value = 2; + } + assert_eq!(&2, lazycell.borrow().unwrap()); + } + + #[test] + fn test_borrow_mut_with_already_filled() { + let mut lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_mut_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_mut_with_not_called_when_filled() { + let mut lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_mut_with(|| 2); + assert_eq!(&1, value); + } + + #[test] + fn test_try_borrow_with_ok() { + let lazycell = LazyCell::new(); + let result = lazycell.try_borrow_with::<(), _>(|| Ok(1)); + assert_eq!(result, Ok(&1)); + } + + #[test] + fn test_try_borrow_with_err() { + let lazycell = LazyCell::<()>::new(); + let result = lazycell.try_borrow_with(|| Err(1)); + assert_eq!(result, Err(1)); + } + + #[test] + fn test_try_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + let result = lazycell.try_borrow_with::<(), _>(|| unreachable!()); + assert_eq!(result, Ok(&1)); + } + + #[test] + #[should_panic] + fn test_try_borrow_with_sound_with_reentrancy() { + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + let _ = lazycell.try_borrow_with::<(), _>(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Ok(Box::new(2)) + }); + } + + #[test] + fn test_try_borrow_mut_with_ok() { + let mut lazycell = LazyCell::new(); + { + let result = lazycell.try_borrow_mut_with::<(), _>(|| Ok(1)); + assert_eq!(result, Ok(&mut 1)); + *result.unwrap() = 2; + } + assert_eq!(&mut 2, lazycell.borrow().unwrap()); + } + + #[test] + fn test_try_borrow_mut_with_err() { + let mut lazycell = LazyCell::<()>::new(); + let result = lazycell.try_borrow_mut_with(|| Err(1)); + assert_eq!(result, Err(1)); + } + + #[test] + fn test_try_borrow_mut_with_already_filled() { + let mut lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + let result = lazycell.try_borrow_mut_with::<(), _>(|| unreachable!()); + assert_eq!(result, Ok(&mut 1)); + } + + #[test] + fn test_into_inner() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_borrow_from_empty() { + let lazycell: AtomicLazyCell = AtomicLazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_atomic_fill_and_borrow() { + let lazycell = AtomicLazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_already_filled_panic() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(1, lazycell.fill(1).unwrap_err()); + } + + #[test] + fn test_atomic_into_inner() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } + + #[test] + fn normal_replace() { + let mut cell = LazyCell::new(); + assert_eq!(cell.fill(1), Ok(())); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(cell.replace(3), Some(2)); + assert_eq!(cell.borrow(), Some(&3)); + + let mut cell = LazyCell::new(); + assert_eq!(cell.replace(2), None); + } + + #[test] + fn atomic_replace() { + let mut cell = AtomicLazyCell::new(); + assert_eq!(cell.fill(1), Ok(())); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(cell.replace(3), Some(2)); + assert_eq!(cell.borrow(), Some(&3)); + } + + #[test] + fn clone() { + let mut cell = LazyCell::new(); + let clone1 = cell.clone(); + assert_eq!(clone1.borrow(), None); + assert_eq!(cell.fill(1), Ok(())); + let mut clone2 = cell.clone(); + assert_eq!(clone1.borrow(), None); + assert_eq!(clone2.borrow(), Some(&1)); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(clone1.borrow(), None); + assert_eq!(clone2.borrow(), Some(&1)); + assert_eq!(clone1.fill(3), Ok(())); + assert_eq!(clone2.replace(4), Some(1)); + assert_eq!(clone1.borrow(), Some(&3)); + assert_eq!(clone2.borrow(), Some(&4)); + assert_eq!(cell.borrow(), Some(&2)); + } + + #[test] + fn clone_atomic() { + let mut cell = AtomicLazyCell::new(); + let clone1 = cell.clone(); + assert_eq!(clone1.borrow(), None); + assert_eq!(cell.fill(1), Ok(())); + let mut clone2 = cell.clone(); + assert_eq!(clone1.borrow(), None); + assert_eq!(clone2.borrow(), Some(&1)); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(clone1.borrow(), None); + assert_eq!(clone2.borrow(), Some(&1)); + assert_eq!(clone1.fill(3), Ok(())); + assert_eq!(clone2.replace(4), Some(1)); + assert_eq!(clone1.borrow(), Some(&3)); + assert_eq!(clone2.borrow(), Some(&4)); + assert_eq!(cell.borrow(), Some(&2)); + } +} diff --git a/third_party/cargo/vendor/lock_api-0.1.5/.cargo-checksum.json b/third_party/cargo/vendor/lock_api-0.1.5/.cargo-checksum.json deleted file mode 100644 index b8be5a0..0000000 --- a/third_party/cargo/vendor/lock_api-0.1.5/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"ab2a7a96105e15de46900fb0da37edbab44e5513a9818672153dae44ed318f7e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","src/lib.rs":"4a16128f58e3380b22b26b137ee1096732995b7e401f3d227dd7b0738b6bd604","src/mutex.rs":"fee397f72325621812c5f78c7a6b9369ea7ec14e71bb0049678a50349519c0c7","src/remutex.rs":"ed76d7b93a56b6248d79676de2aaa66b607b64f1b773c9dd7326b8324e2bc71a","src/rwlock.rs":"5ab1aab614358cfdaf23e8ff8a0ac5e0c7656b777f385aca2e5422f0aa8f0985"},"package":"62ebf1391f6acad60e5c8b43706dde4582df75c06698ab44511d15016bc2442c"} \ No newline at end of file diff --git a/third_party/cargo/vendor/lock_api-0.3.3/.cargo-checksum.json b/third_party/cargo/vendor/lock_api-0.3.3/.cargo-checksum.json new file mode 100644 index 0000000..061fae8 --- /dev/null +++ b/third_party/cargo/vendor/lock_api-0.3.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"c82814c74f08e404a1207533d9f1e292ff743b90ced01a5c7808e52d2721ce82","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","src/lib.rs":"d9ed1f911f058d066ebfd024940da8a5c1ebbab6cfd65a633dfbc613573dd823","src/mutex.rs":"a2f5729761af0ad90596baca6e7ae1e3ae4495e67ebee167e7ad84bb9f4a649c","src/remutex.rs":"7ce5d47f9bdb1a7949ee9f12b0853b7690a8acb1f8eb643333ff05621210f6c8","src/rwlock.rs":"6004fed47262e84befb4817eca069f922a1cdbc207a2bbb5e55493e032bc85dd"},"package":"79b2de95ecb4691949fea4716ca53cdbcfccb2c612e19644a8bad05edcf9f47b"} \ No newline at end of file diff --git a/third_party/cargo/vendor/lock_api-0.3.3/BUILD b/third_party/cargo/vendor/lock_api-0.3.3/BUILD new file mode 100644 index 0000000..cd34108 --- /dev/null +++ b/third_party/cargo/vendor/lock_api-0.3.3/BUILD @@ -0,0 +1,43 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "Apache-2.0,MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "lock_api", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2018", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/scopeguard-1.1.0:scopeguard", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.3.3", + crate_features = [ + ], +) + diff --git a/third_party/cargo/vendor/lock_api-0.1.5/Cargo.toml b/third_party/cargo/vendor/lock_api-0.3.3/Cargo.toml similarity index 84% rename from third_party/cargo/vendor/lock_api-0.1.5/Cargo.toml rename to third_party/cargo/vendor/lock_api-0.3.3/Cargo.toml index ee39d85..68171b1 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/Cargo.toml +++ b/third_party/cargo/vendor/lock_api-0.3.3/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "lock_api" -version = "0.1.5" +version = "0.3.3" authors = ["Amanieu d'Antras "] description = "Wrappers to create fully-featured Mutex and RwLock types. Compatible with no_std." keywords = ["mutex", "rwlock", "lock", "no_std"] @@ -24,7 +25,12 @@ version = "0.4" optional = true [dependencies.scopeguard] -version = "0.3" +version = "1.0" +default-features = false + +[dependencies.serde] +version = "1.0.90" +optional = true default-features = false [features] diff --git a/third_party/cargo/vendor/metal-0.13.1/LICENSE-APACHE b/third_party/cargo/vendor/lock_api-0.3.3/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/LICENSE-APACHE rename to third_party/cargo/vendor/lock_api-0.3.3/LICENSE-APACHE diff --git a/third_party/cargo/vendor/lock_api-0.1.5/LICENSE-MIT b/third_party/cargo/vendor/lock_api-0.3.3/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/lock_api-0.1.5/LICENSE-MIT rename to third_party/cargo/vendor/lock_api-0.3.3/LICENSE-MIT diff --git a/third_party/cargo/vendor/lock_api-0.1.5/src/lib.rs b/third_party/cargo/vendor/lock_api-0.3.3/src/lib.rs similarity index 93% rename from third_party/cargo/vendor/lock_api-0.1.5/src/lib.rs rename to third_party/cargo/vendor/lock_api-0.3.3/src/lib.rs index 60271ed..d388d8a 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/src/lib.rs +++ b/third_party/cargo/vendor/lock_api-0.3.3/src/lib.rs @@ -28,14 +28,14 @@ //! //! ``` //! use lock_api::{RawMutex, Mutex, GuardSend}; -//! use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; +//! use std::sync::atomic::{AtomicBool, Ordering}; //! //! // 1. Define our raw lock type //! pub struct RawSpinlock(AtomicBool); //! //! // 2. Implement RawMutex for this type //! unsafe impl RawMutex for RawSpinlock { -//! const INIT: RawSpinlock = RawSpinlock(ATOMIC_BOOL_INIT); +//! const INIT: RawSpinlock = RawSpinlock(AtomicBool::new(false)); //! //! // A spinlock guard can be sent to another thread and unlocked there //! type GuardMarker = GuardSend; @@ -85,14 +85,12 @@ #![no_std] #![warn(missing_docs)] +#![warn(rust_2018_idioms)] #![cfg_attr(feature = "nightly", feature(const_fn))] #[macro_use] extern crate scopeguard; -#[cfg(feature = "owning_ref")] -extern crate owning_ref; - /// Marker type which indicates that the Guard type for a lock is `Send`. pub struct GuardSend(()); @@ -100,10 +98,10 @@ pub struct GuardSend(()); pub struct GuardNoSend(*mut ()); mod mutex; -pub use mutex::*; +pub use crate::mutex::*; mod remutex; -pub use remutex::*; +pub use crate::remutex::*; mod rwlock; -pub use rwlock::*; +pub use crate::rwlock::*; diff --git a/third_party/cargo/vendor/lock_api-0.1.5/src/mutex.rs b/third_party/cargo/vendor/lock_api-0.3.3/src/mutex.rs similarity index 82% rename from third_party/cargo/vendor/lock_api-0.1.5/src/mutex.rs rename to third_party/cargo/vendor/lock_api-0.3.3/src/mutex.rs index b9cf49b..116438e 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/src/mutex.rs +++ b/third_party/cargo/vendor/lock_api-0.3.3/src/mutex.rs @@ -14,6 +14,9 @@ use core::ops::{Deref, DerefMut}; #[cfg(feature = "owning_ref")] use owning_ref::StableAddress; +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + /// Basic operations for a mutex. /// /// Types implementing this trait can be used by `Mutex` to form a safe and @@ -25,6 +28,9 @@ use owning_ref::StableAddress; /// exclusive: a lock can't be acquired while the mutex is already locked. pub unsafe trait RawMutex { /// Initial value for an unlocked mutex. + // A “non-constant” const item is a legacy way to supply an initialized value to downstream + // static items. Can hopefully be replaced with `const fn new() -> Self` at some point. + #[allow(clippy::declare_interior_mutable_const)] const INIT: Self; /// Marker type which determines whether a lock guard should be `Send`. Use @@ -102,8 +108,8 @@ impl Mutex { #[inline] pub const fn new(val: T) -> Mutex { Mutex { - data: UnsafeCell::new(val), raw: R::INIT, + data: UnsafeCell::new(val), } } @@ -112,22 +118,24 @@ impl Mutex { #[inline] pub fn new(val: T) -> Mutex { Mutex { - data: UnsafeCell::new(val), raw: R::INIT, + data: UnsafeCell::new(val), } } /// Consumes this mutex, returning the underlying data. #[inline] - #[allow(unused_unsafe)] pub fn into_inner(self) -> T { - unsafe { self.data.into_inner() } + self.data.into_inner() } } impl Mutex { + /// # Safety + /// + /// The lock must be held when calling this method. #[inline] - fn guard(&self) -> MutexGuard { + unsafe fn guard(&self) -> MutexGuard<'_, R, T> { MutexGuard { mutex: self, marker: PhantomData, @@ -144,9 +152,10 @@ impl Mutex { /// Attempts to lock a mutex in the thread which already holds the lock will /// result in a deadlock. #[inline] - pub fn lock(&self) -> MutexGuard { + pub fn lock(&self) -> MutexGuard<'_, R, T> { self.raw.lock(); - self.guard() + // SAFETY: The lock is held, as required. + unsafe { self.guard() } } /// Attempts to acquire this lock. @@ -157,9 +166,10 @@ impl Mutex { /// /// This function does not block. #[inline] - pub fn try_lock(&self) -> Option> { + pub fn try_lock(&self) -> Option> { if self.raw.try_lock() { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -230,9 +240,10 @@ impl Mutex { /// `None` is returned. Otherwise, an RAII guard is returned. The lock will /// be unlocked when the guard is dropped. #[inline] - pub fn try_lock_for(&self, timeout: R::Duration) -> Option> { + pub fn try_lock_for(&self, timeout: R::Duration) -> Option> { if self.raw.try_lock_for(timeout) { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -244,9 +255,10 @@ impl Mutex { /// `None` is returned. Otherwise, an RAII guard is returned. The lock will /// be unlocked when the guard is dropped. #[inline] - pub fn try_lock_until(&self, timeout: R::Instant) -> Option> { + pub fn try_lock_until(&self, timeout: R::Instant) -> Option> { if self.raw.try_lock_until(timeout) { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -268,21 +280,61 @@ impl From for Mutex { } impl fmt::Debug for Mutex { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.try_lock() { Some(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(), - None => f.pad("Mutex { }"), + None => { + struct LockedPlaceholder; + impl fmt::Debug for LockedPlaceholder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } + } + + f.debug_struct("Mutex") + .field("data", &LockedPlaceholder) + .finish() + } } } } +// Copied and modified from serde +#[cfg(feature = "serde")] +impl Serialize for Mutex +where + R: RawMutex, + T: Serialize + ?Sized, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.lock().serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, R, T> Deserialize<'de> for Mutex +where + R: RawMutex, + T: Deserialize<'de> + ?Sized, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Mutex::new) + } +} + /// An RAII implementation of a "scoped lock" of a mutex. When this structure is /// dropped (falls out of scope), the lock will be unlocked. /// /// The data protected by the mutex can be accessed through this guard via its /// `Deref` and `DerefMut` implementations. -#[must_use] -pub struct MutexGuard<'a, R: RawMutex + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the Mutex will immediately unlock"] +pub struct MutexGuard<'a, R: RawMutex, T: ?Sized> { mutex: &'a Mutex, marker: PhantomData<(&'a mut T, R::GuardMarker)>, } @@ -318,14 +370,14 @@ impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> MutexGuard<'a, R, T> { } } - /// Attempts to make a new `MappedMutexGuard` for a component of the - /// locked data. The original guard is return if the closure returns `None`. + /// Attempts to make a new `MappedMutexGuard` for a component of the + /// locked data. The original guard is returned if the closure returns `None`. /// /// This operation cannot fail as the `MutexGuard` passed /// in already locked the mutex. /// /// This is an associated function that needs to be - /// used as `MutexGuard::map(...)`. A method would interfere with methods of + /// used as `MutexGuard::try_map(...)`. A method would interfere with methods of /// the same name on the contents of the locked data. #[inline] pub fn try_map(s: Self, f: F) -> Result, Self> @@ -381,7 +433,7 @@ impl<'a, R: RawMutexFair + 'a, T: ?Sized + 'a> MutexGuard<'a, R, T> { /// Temporarily unlocks the mutex to execute the given function. /// - /// The mutex is unlocked a fair unlock protocol. + /// The mutex is unlocked using a fair unlock protocol. /// /// This is safe because `&mut` guarantees that there exist no other /// references to the data protected by the mutex. @@ -428,6 +480,18 @@ impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> Drop for MutexGuard<'a, R, T> { } } +impl<'a, R: RawMutex + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for MutexGuard<'a, R, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawMutex + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display for MutexGuard<'a, R, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> StableAddress for MutexGuard<'a, R, T> {} @@ -438,8 +502,8 @@ unsafe impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> StableAddress for MutexGuard<' /// former doesn't support temporarily unlocking and re-locking, since that /// could introduce soundness issues if the locked object is modified by another /// thread. -#[must_use] -pub struct MappedMutexGuard<'a, R: RawMutex + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the Mutex will immediately unlock"] +pub struct MappedMutexGuard<'a, R: RawMutex, T: ?Sized> { raw: &'a R, data: *mut T, marker: PhantomData<&'a mut T>, @@ -447,10 +511,12 @@ pub struct MappedMutexGuard<'a, R: RawMutex + 'a, T: ?Sized + 'a> { unsafe impl<'a, R: RawMutex + Sync + 'a, T: ?Sized + Sync + 'a> Sync for MappedMutexGuard<'a, R, T> -{} +{ +} unsafe impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> Send for MappedMutexGuard<'a, R, T> where R::GuardMarker: Send -{} +{ +} impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> MappedMutexGuard<'a, R, T> { /// Makes a new `MappedMutexGuard` for a component of the locked data. @@ -476,14 +542,14 @@ impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> MappedMutexGuard<'a, R, T> { } } - /// Attempts to make a new `MappedMutexGuard` for a component of the - /// locked data. The original guard is return if the closure returns `None`. + /// Attempts to make a new `MappedMutexGuard` for a component of the + /// locked data. The original guard is returned if the closure returns `None`. /// /// This operation cannot fail as the `MappedMutexGuard` passed /// in already locked the mutex. /// /// This is an associated function that needs to be - /// used as `MappedMutexGuard::map(...)`. A method would interfere with methods of + /// used as `MappedMutexGuard::try_map(...)`. A method would interfere with methods of /// the same name on the contents of the locked data. #[inline] pub fn try_map(s: Self, f: F) -> Result, Self> @@ -546,5 +612,19 @@ impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> Drop for MappedMutexGuard<'a, R, T> { } } +impl<'a, R: RawMutex + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for MappedMutexGuard<'a, R, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawMutex + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for MappedMutexGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> StableAddress for MappedMutexGuard<'a, R, T> {} diff --git a/third_party/cargo/vendor/lock_api-0.1.5/src/remutex.rs b/third_party/cargo/vendor/lock_api-0.3.3/src/remutex.rs similarity index 81% rename from third_party/cargo/vendor/lock_api-0.1.5/src/remutex.rs rename to third_party/cargo/vendor/lock_api-0.3.3/src/remutex.rs index 3db9f51..4fd102a 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/src/remutex.rs +++ b/third_party/cargo/vendor/lock_api-0.3.3/src/remutex.rs @@ -5,18 +5,26 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use core::cell::{Cell, UnsafeCell}; -use core::fmt; -use core::marker::PhantomData; -use core::mem; -use core::ops::Deref; -use core::sync::atomic::{AtomicUsize, Ordering}; -use mutex::{RawMutex, RawMutexFair, RawMutexTimed}; -use GuardNoSend; +use crate::{ + mutex::{RawMutex, RawMutexFair, RawMutexTimed}, + GuardNoSend, +}; +use core::{ + cell::{Cell, UnsafeCell}, + fmt, + marker::PhantomData, + mem, + num::NonZeroUsize, + ops::Deref, + sync::atomic::{AtomicUsize, Ordering}, +}; #[cfg(feature = "owning_ref")] use owning_ref::StableAddress; +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + /// Helper trait which returns a non-zero thread ID. /// /// The simplest way to implement this trait is to return the address of a @@ -29,11 +37,14 @@ use owning_ref::StableAddress; /// re-used since that thread is no longer active. pub unsafe trait GetThreadId { /// Initial value. + // A “non-constant” const item is a legacy way to supply an initialized value to downstream + // static items. Can hopefully be replaced with `const fn new() -> Self` at some point. + #[allow(clippy::declare_interior_mutable_const)] const INIT: Self; /// Returns a non-zero thread ID which identifies the current thread of /// execution. - fn nonzero_thread_id(&self) -> usize; + fn nonzero_thread_id(&self) -> NonZeroUsize; } struct RawReentrantMutex { @@ -46,7 +57,7 @@ struct RawReentrantMutex { impl RawReentrantMutex { #[inline] fn lock_internal bool>(&self, try_lock: F) -> bool { - let id = self.get_thread_id.nonzero_thread_id(); + let id = self.get_thread_id.nonzero_thread_id().get(); if self.owner.load(Ordering::Relaxed) == id { self.lock_count.set( self.lock_count @@ -59,6 +70,7 @@ impl RawReentrantMutex { return false; } self.owner.store(id, Ordering::Relaxed); + debug_assert_eq!(self.lock_count.get(), 0); self.lock_count.set(1); } true @@ -80,11 +92,10 @@ impl RawReentrantMutex { #[inline] fn unlock(&self) { let lock_count = self.lock_count.get() - 1; + self.lock_count.set(lock_count); if lock_count == 0 { self.owner.store(0, Ordering::Relaxed); self.mutex.unlock(); - } else { - self.lock_count.set(lock_count); } } } @@ -93,11 +104,10 @@ impl RawReentrantMutex { #[inline] fn unlock_fair(&self) { let lock_count = self.lock_count.get() - 1; + self.lock_count.set(lock_count); if lock_count == 0 { self.owner.store(0, Ordering::Relaxed); self.mutex.unlock_fair(); - } else { - self.lock_count.set(lock_count); } } @@ -142,10 +152,12 @@ pub struct ReentrantMutex { unsafe impl Send for ReentrantMutex -{} +{ +} unsafe impl Sync for ReentrantMutex -{} +{ +} impl ReentrantMutex { /// Creates a new reentrant mutex in an unlocked state ready for use. @@ -180,15 +192,17 @@ impl ReentrantMutex { /// Consumes this mutex, returning the underlying data. #[inline] - #[allow(unused_unsafe)] pub fn into_inner(self) -> T { - unsafe { self.data.into_inner() } + self.data.into_inner() } } impl ReentrantMutex { + /// # Safety + /// + /// The lock must be held when calling this method. #[inline] - fn guard(&self) -> ReentrantMutexGuard { + unsafe fn guard(&self) -> ReentrantMutexGuard<'_, R, G, T> { ReentrantMutexGuard { remutex: &self, marker: PhantomData, @@ -206,9 +220,10 @@ impl ReentrantMutex { /// returned to allow scoped unlock of the lock. When the guard goes out of /// scope, the mutex will be unlocked. #[inline] - pub fn lock(&self) -> ReentrantMutexGuard { + pub fn lock(&self) -> ReentrantMutexGuard<'_, R, G, T> { self.raw.lock(); - self.guard() + // SAFETY: The lock is held, as required. + unsafe { self.guard() } } /// Attempts to acquire this lock. @@ -219,9 +234,10 @@ impl ReentrantMutex { /// /// This function does not block. #[inline] - pub fn try_lock(&self) -> Option> { + pub fn try_lock(&self) -> Option> { if self.raw.try_lock() { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -292,9 +308,10 @@ impl ReentrantMutex { /// `None` is returned. Otherwise, an RAII guard is returned. The lock will /// be unlocked when the guard is dropped. #[inline] - pub fn try_lock_for(&self, timeout: R::Duration) -> Option> { + pub fn try_lock_for(&self, timeout: R::Duration) -> Option> { if self.raw.try_lock_for(timeout) { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -306,9 +323,10 @@ impl ReentrantMutex { /// `None` is returned. Otherwise, an RAII guard is returned. The lock will /// be unlocked when the guard is dropped. #[inline] - pub fn try_lock_until(&self, timeout: R::Instant) -> Option> { + pub fn try_lock_until(&self, timeout: R::Instant) -> Option> { if self.raw.try_lock_until(timeout) { - Some(self.guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.guard() }) } else { None } @@ -330,31 +348,74 @@ impl From for ReentrantMutex { } impl fmt::Debug for ReentrantMutex { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.try_lock() { Some(guard) => f .debug_struct("ReentrantMutex") .field("data", &&*guard) .finish(), - None => f.pad("ReentrantMutex { }"), + None => { + struct LockedPlaceholder; + impl fmt::Debug for LockedPlaceholder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } + } + + f.debug_struct("ReentrantMutex") + .field("data", &LockedPlaceholder) + .finish() + } } } } +// Copied and modified from serde +#[cfg(feature = "serde")] +impl Serialize for ReentrantMutex +where + R: RawMutex, + G: GetThreadId, + T: Serialize + ?Sized, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.lock().serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, R, G, T> Deserialize<'de> for ReentrantMutex +where + R: RawMutex, + G: GetThreadId, + T: Deserialize<'de> + ?Sized, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(ReentrantMutex::new) + } +} + /// An RAII implementation of a "scoped lock" of a reentrant mutex. When this structure /// is dropped (falls out of scope), the lock will be unlocked. /// /// The data protected by the mutex can be accessed through this guard via its /// `Deref` implementation. -#[must_use] -pub struct ReentrantMutexGuard<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the ReentrantMutex will immediately unlock"] +pub struct ReentrantMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> { remutex: &'a ReentrantMutex, marker: PhantomData<(&'a T, GuardNoSend)>, } unsafe impl<'a, R: RawMutex + Sync + 'a, G: GetThreadId + Sync + 'a, T: ?Sized + Sync + 'a> Sync for ReentrantMutexGuard<'a, R, G, T> -{} +{ +} impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> ReentrantMutexGuard<'a, R, G, T> { /// Returns a reference to the original `ReentrantMutex` object. @@ -395,7 +456,10 @@ impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> ReentrantMutexGu /// used as `ReentrantMutexGuard::map(...)`. A method would interfere with methods of /// the same name on the contents of the locked data. #[inline] - pub fn try_map(s: Self, f: F) -> Result, Self> + pub fn try_map( + s: Self, + f: F, + ) -> Result, Self> where F: FnOnce(&mut T) -> Option<&mut U>, { @@ -494,10 +558,27 @@ impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> Drop } } +impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug + for ReentrantMutexGuard<'a, R, G, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for ReentrantMutexGuard<'a, R, G, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> StableAddress for ReentrantMutexGuard<'a, R, G, T> -{} +{ +} /// An RAII mutex guard returned by `ReentrantMutexGuard::map`, which can point to a /// subfield of the protected data. @@ -506,8 +587,8 @@ unsafe impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> StableAdd /// former doesn't support temporarily unlocking and re-locking, since that /// could introduce soundness issues if the locked object is modified by another /// thread. -#[must_use] -pub struct MappedReentrantMutexGuard<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the ReentrantMutex will immediately unlock"] +pub struct MappedReentrantMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> { raw: &'a RawReentrantMutex, data: *const T, marker: PhantomData<&'a T>, @@ -515,7 +596,8 @@ pub struct MappedReentrantMutexGuard<'a, R: RawMutex + 'a, G: GetThreadId + 'a, unsafe impl<'a, R: RawMutex + Sync + 'a, G: GetThreadId + Sync + 'a, T: ?Sized + Sync + 'a> Sync for MappedReentrantMutexGuard<'a, R, G, T> -{} +{ +} impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> MappedReentrantMutexGuard<'a, R, G, T> @@ -553,7 +635,10 @@ impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> /// used as `MappedReentrantMutexGuard::map(...)`. A method would interfere with methods of /// the same name on the contents of the locked data. #[inline] - pub fn try_map(s: Self, f: F) -> Result, Self> + pub fn try_map( + s: Self, + f: F, + ) -> Result, Self> where F: FnOnce(&T) -> Option<&U>, { @@ -612,7 +697,24 @@ impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> Drop } } +impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug + for MappedReentrantMutexGuard<'a, R, G, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for MappedReentrantMutexGuard<'a, R, G, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawMutex + 'a, G: GetThreadId + 'a, T: ?Sized + 'a> StableAddress for MappedReentrantMutexGuard<'a, R, G, T> -{} +{ +} diff --git a/third_party/cargo/vendor/lock_api-0.1.5/src/rwlock.rs b/third_party/cargo/vendor/lock_api-0.3.3/src/rwlock.rs similarity index 87% rename from third_party/cargo/vendor/lock_api-0.1.5/src/rwlock.rs rename to third_party/cargo/vendor/lock_api-0.3.3/src/rwlock.rs index 4edb917..0707e3c 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/src/rwlock.rs +++ b/third_party/cargo/vendor/lock_api-0.3.3/src/rwlock.rs @@ -14,6 +14,9 @@ use core::ops::{Deref, DerefMut}; #[cfg(feature = "owning_ref")] use owning_ref::StableAddress; +#[cfg(feature = "serde")] +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + /// Basic operations for a reader-writer lock. /// /// Types implementing this trait can be used by `RwLock` to form a safe and @@ -27,6 +30,9 @@ use owning_ref::StableAddress; /// exists. pub unsafe trait RawRwLock { /// Initial value for an unlocked `RwLock`. + // A “non-constant” const item is a legacy way to supply an initialized value to downstream + // static items. Can hopefully be replaced with `const fn new() -> Self` at some point. + #[allow(clippy::declare_interior_mutable_const)] const INIT: Self; /// Marker type which determines whether a lock guard should be `Send`. Use @@ -230,6 +236,35 @@ pub struct RwLock { data: UnsafeCell, } +// Copied and modified from serde +#[cfg(feature = "serde")] +impl Serialize for RwLock +where + R: RawRwLock, + T: Serialize + ?Sized, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + self.read().serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl<'de, R, T> Deserialize<'de> for RwLock +where + R: RawRwLock, + T: Deserialize<'de> + ?Sized, +{ + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(RwLock::new) + } +} + unsafe impl Send for RwLock {} unsafe impl Sync for RwLock {} @@ -263,16 +298,22 @@ impl RwLock { } impl RwLock { + /// # Safety + /// + /// The lock must be held when calling this method. #[inline] - fn read_guard(&self) -> RwLockReadGuard { + unsafe fn read_guard(&self) -> RwLockReadGuard<'_, R, T> { RwLockReadGuard { rwlock: self, marker: PhantomData, } } + /// # Safety + /// + /// The lock must be held when calling this method. #[inline] - fn write_guard(&self) -> RwLockWriteGuard { + unsafe fn write_guard(&self) -> RwLockWriteGuard<'_, R, T> { RwLockWriteGuard { rwlock: self, marker: PhantomData, @@ -292,9 +333,10 @@ impl RwLock { /// Returns an RAII guard which will release this thread's shared access /// once it is dropped. #[inline] - pub fn read(&self) -> RwLockReadGuard { + pub fn read(&self) -> RwLockReadGuard<'_, R, T> { self.raw.lock_shared(); - self.read_guard() + // SAFETY: The lock is held, as required. + unsafe { self.read_guard() } } /// Attempts to acquire this `RwLock` with shared read access. @@ -305,9 +347,10 @@ impl RwLock { /// /// This function does not block. #[inline] - pub fn try_read(&self) -> Option> { + pub fn try_read(&self) -> Option> { if self.raw.try_lock_shared() { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -322,9 +365,10 @@ impl RwLock { /// Returns an RAII guard which will drop the write access of this `RwLock` /// when dropped. #[inline] - pub fn write(&self) -> RwLockWriteGuard { + pub fn write(&self) -> RwLockWriteGuard<'_, R, T> { self.raw.lock_exclusive(); - self.write_guard() + // SAFETY: The lock is held, as required. + unsafe { self.write_guard() } } /// Attempts to lock this `RwLock` with exclusive write access. @@ -335,9 +379,10 @@ impl RwLock { /// /// This function does not block. #[inline] - pub fn try_write(&self) -> Option> { + pub fn try_write(&self) -> Option> { if self.raw.try_lock_exclusive() { - Some(self.write_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.write_guard() }) } else { None } @@ -441,9 +486,10 @@ impl RwLock { /// `None` is returned. Otherwise, an RAII guard is returned which will /// release the shared access when it is dropped. #[inline] - pub fn try_read_for(&self, timeout: R::Duration) -> Option> { + pub fn try_read_for(&self, timeout: R::Duration) -> Option> { if self.raw.try_lock_shared_for(timeout) { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -456,9 +502,10 @@ impl RwLock { /// `None` is returned. Otherwise, an RAII guard is returned which will /// release the shared access when it is dropped. #[inline] - pub fn try_read_until(&self, timeout: R::Instant) -> Option> { + pub fn try_read_until(&self, timeout: R::Instant) -> Option> { if self.raw.try_lock_shared_until(timeout) { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -471,9 +518,10 @@ impl RwLock { /// `None` is returned. Otherwise, an RAII guard is returned which will /// release the exclusive access when it is dropped. #[inline] - pub fn try_write_for(&self, timeout: R::Duration) -> Option> { + pub fn try_write_for(&self, timeout: R::Duration) -> Option> { if self.raw.try_lock_exclusive_for(timeout) { - Some(self.write_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.write_guard() }) } else { None } @@ -486,9 +534,10 @@ impl RwLock { /// `None` is returned. Otherwise, an RAII guard is returned which will /// release the exclusive access when it is dropped. #[inline] - pub fn try_write_until(&self, timeout: R::Instant) -> Option> { + pub fn try_write_until(&self, timeout: R::Instant) -> Option> { if self.raw.try_lock_exclusive_until(timeout) { - Some(self.write_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.write_guard() }) } else { None } @@ -512,9 +561,10 @@ impl RwLock { /// Returns an RAII guard which will release this thread's shared access /// once it is dropped. #[inline] - pub fn read_recursive(&self) -> RwLockReadGuard { + pub fn read_recursive(&self) -> RwLockReadGuard<'_, R, T> { self.raw.lock_shared_recursive(); - self.read_guard() + // SAFETY: The lock is held, as required. + unsafe { self.read_guard() } } /// Attempts to acquire this `RwLock` with shared read access. @@ -528,9 +578,10 @@ impl RwLock { /// /// This function does not block. #[inline] - pub fn try_read_recursive(&self) -> Option> { + pub fn try_read_recursive(&self) -> Option> { if self.raw.try_lock_shared_recursive() { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -549,9 +600,13 @@ impl RwLock { /// lock is held at the time of the call. See the documentation for /// `read_recursive` for details. #[inline] - pub fn try_read_recursive_for(&self, timeout: R::Duration) -> Option> { + pub fn try_read_recursive_for( + &self, + timeout: R::Duration, + ) -> Option> { if self.raw.try_lock_shared_recursive_for(timeout) { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -564,9 +619,13 @@ impl RwLock { /// `None` is returned. Otherwise, an RAII guard is returned which will /// release the shared access when it is dropped. #[inline] - pub fn try_read_recursive_until(&self, timeout: R::Instant) -> Option> { + pub fn try_read_recursive_until( + &self, + timeout: R::Instant, + ) -> Option> { if self.raw.try_lock_shared_recursive_until(timeout) { - Some(self.read_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.read_guard() }) } else { None } @@ -574,8 +633,11 @@ impl RwLock { } impl RwLock { + /// # Safety + /// + /// The lock must be held when calling this method. #[inline] - fn upgradable_guard(&self) -> RwLockUpgradableReadGuard { + unsafe fn upgradable_guard(&self) -> RwLockUpgradableReadGuard<'_, R, T> { RwLockUpgradableReadGuard { rwlock: self, marker: PhantomData, @@ -592,9 +654,10 @@ impl RwLock { /// Returns an RAII guard which will release this thread's shared access /// once it is dropped. #[inline] - pub fn upgradable_read(&self) -> RwLockUpgradableReadGuard { + pub fn upgradable_read(&self) -> RwLockUpgradableReadGuard<'_, R, T> { self.raw.lock_upgradable(); - self.upgradable_guard() + // SAFETY: The lock is held, as required. + unsafe { self.upgradable_guard() } } /// Attempts to acquire this `RwLock` with upgradable read access. @@ -605,9 +668,10 @@ impl RwLock { /// /// This function does not block. #[inline] - pub fn try_upgradable_read(&self) -> Option> { + pub fn try_upgradable_read(&self) -> Option> { if self.raw.try_lock_upgradable() { - Some(self.upgradable_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.upgradable_guard() }) } else { None } @@ -625,9 +689,10 @@ impl RwLock { pub fn try_upgradable_read_for( &self, timeout: R::Duration, - ) -> Option> { + ) -> Option> { if self.raw.try_lock_upgradable_for(timeout) { - Some(self.upgradable_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.upgradable_guard() }) } else { None } @@ -643,9 +708,10 @@ impl RwLock { pub fn try_upgradable_read_until( &self, timeout: R::Instant, - ) -> Option> { + ) -> Option> { if self.raw.try_lock_upgradable_until(timeout) { - Some(self.upgradable_guard()) + // SAFETY: The lock is held, as required. + Some(unsafe { self.upgradable_guard() }) } else { None } @@ -667,18 +733,29 @@ impl From for RwLock { } impl fmt::Debug for RwLock { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.try_read() { Some(guard) => f.debug_struct("RwLock").field("data", &&*guard).finish(), - None => f.pad("RwLock { }"), + None => { + struct LockedPlaceholder; + impl fmt::Debug for LockedPlaceholder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } + } + + f.debug_struct("RwLock") + .field("data", &LockedPlaceholder) + .finish() + } } } } /// RAII structure used to release the shared read access of a lock when /// dropped. -#[must_use] -pub struct RwLockReadGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the RwLock will immediately unlock"] +pub struct RwLockReadGuard<'a, R: RawRwLock, T: ?Sized> { rwlock: &'a RwLock, marker: PhantomData<(&'a T, R::GuardMarker)>, } @@ -819,13 +896,27 @@ impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for RwLockReadGuard<'a, R, T> { } } +impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for RwLockReadGuard<'a, R, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for RwLockReadGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for RwLockReadGuard<'a, R, T> {} /// RAII structure used to release the exclusive write access of a lock when /// dropped. -#[must_use] -pub struct RwLockWriteGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the RwLock will immediately unlock"] +pub struct RwLockWriteGuard<'a, R: RawRwLock, T: ?Sized> { rwlock: &'a RwLock, marker: PhantomData<(&'a mut T, R::GuardMarker)>, } @@ -1007,20 +1098,35 @@ impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for RwLockWriteGuard<'a, R, T> } } +impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug for RwLockWriteGuard<'a, R, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for RwLockWriteGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for RwLockWriteGuard<'a, R, T> {} /// RAII structure used to release the upgradable read access of a lock when /// dropped. -#[must_use] -pub struct RwLockUpgradableReadGuard<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the RwLock will immediately unlock"] +pub struct RwLockUpgradableReadGuard<'a, R: RawRwLockUpgrade, T: ?Sized> { rwlock: &'a RwLock, marker: PhantomData<(&'a T, R::GuardMarker)>, } unsafe impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + Sync + 'a> Sync for RwLockUpgradableReadGuard<'a, R, T> -{} +{ +} impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> RwLockUpgradableReadGuard<'a, R, T> { /// Returns a reference to the original reader-writer lock object. @@ -1196,10 +1302,27 @@ impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> Drop for RwLockUpgradableRead } } +impl<'a, R: RawRwLockUpgrade + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug + for RwLockUpgradableReadGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawRwLockUpgrade + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for RwLockUpgradableReadGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> StableAddress for RwLockUpgradableReadGuard<'a, R, T> -{} +{ +} /// An RAII read lock guard returned by `RwLockReadGuard::map`, which can point to a /// subfield of the protected data. @@ -1208,8 +1331,8 @@ unsafe impl<'a, R: RawRwLockUpgrade + 'a, T: ?Sized + 'a> StableAddress /// former doesn't support temporarily unlocking and re-locking, since that /// could introduce soundness issues if the locked object is modified by another /// thread. -#[must_use] -pub struct MappedRwLockReadGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the RwLock will immediately unlock"] +pub struct MappedRwLockReadGuard<'a, R: RawRwLock, T: ?Sized> { raw: &'a R, data: *const T, marker: PhantomData<&'a T>, @@ -1218,7 +1341,8 @@ pub struct MappedRwLockReadGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Sync + 'a> Sync for MappedRwLockReadGuard<'a, R, T> {} unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Send for MappedRwLockReadGuard<'a, R, T> where R::GuardMarker: Send -{} +{ +} impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> MappedRwLockReadGuard<'a, R, T> { /// Make a new `MappedRwLockReadGuard` for a component of the locked data. @@ -1307,10 +1431,27 @@ impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for MappedRwLockReadGuard<'a, R } } +impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug + for MappedRwLockReadGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for MappedRwLockReadGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for MappedRwLockReadGuard<'a, R, T> -{} +{ +} /// An RAII write lock guard returned by `RwLockWriteGuard::map`, which can point to a /// subfield of the protected data. @@ -1319,8 +1460,8 @@ unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress /// former doesn't support temporarily unlocking and re-locking, since that /// could introduce soundness issues if the locked object is modified by another /// thread. -#[must_use] -pub struct MappedRwLockWriteGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { +#[must_use = "if unused the RwLock will immediately unlock"] +pub struct MappedRwLockWriteGuard<'a, R: RawRwLock, T: ?Sized> { raw: &'a R, data: *mut T, marker: PhantomData<&'a mut T>, @@ -1328,10 +1469,12 @@ pub struct MappedRwLockWriteGuard<'a, R: RawRwLock + 'a, T: ?Sized + 'a> { unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + Sync + 'a> Sync for MappedRwLockWriteGuard<'a, R, T> -{} +{ +} unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Send for MappedRwLockWriteGuard<'a, R, T> where R::GuardMarker: Send -{} +{ +} impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> MappedRwLockWriteGuard<'a, R, T> { /// Make a new `MappedRwLockWriteGuard` for a component of the locked data. @@ -1392,6 +1535,10 @@ impl<'a, R: RawRwLockDowngrade + 'a, T: ?Sized + 'a> MappedRwLockWriteGuard<'a, /// Note that if there are any writers currently waiting to take the lock /// then other readers may not be able to acquire the lock even if it was /// downgraded. + #[deprecated( + since = "0.3.3", + note = "This function is unsound and will be removed in the future, see issue #198" + )] pub fn downgrade(s: Self) -> MappedRwLockReadGuard<'a, R, T> { s.raw.downgrade(); let raw = s.raw; @@ -1447,7 +1594,24 @@ impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> Drop for MappedRwLockWriteGuard<'a, } } +impl<'a, R: RawRwLock + 'a, T: fmt::Debug + ?Sized + 'a> fmt::Debug + for MappedRwLockWriteGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl<'a, R: RawRwLock + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display + for MappedRwLockWriteGuard<'a, R, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawRwLock + 'a, T: ?Sized + 'a> StableAddress for MappedRwLockWriteGuard<'a, R, T> -{} +{ +} diff --git a/third_party/cargo/vendor/memoffset-0.2.1/.cargo-checksum.json b/third_party/cargo/vendor/memoffset-0.2.1/.cargo-checksum.json deleted file mode 100644 index 43dbd48..0000000 --- a/third_party/cargo/vendor/memoffset-0.2.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"c48ab44d744586aab2bb02ff1288429679cced7cca191c0584982f9eb6edb6c7","LICENSE":"3234ac55816264ee7b6c7ee27efd61cf0a1fe775806870e3d9b4c41ea73c5cb1","README.md":"5b2de7b6eaa7f01720c0a58040264f1ba336fbd005d43284b55f82a826011d11","src/lib.rs":"f8cfb7f2f7e3b179de53d1bde8e814c51b5f66f638f1e744bc14cf9ae4148381","src/offset_of.rs":"1cf7c89bb7b05dee7241913596f107672289e14e8d3d404eecc8c97b302f2f12","src/span_of.rs":"513452dcb6e4c7d5354631973492561de83bed5aaa8306f82cc5828664962538"},"package":"0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"} \ No newline at end of file diff --git a/third_party/cargo/vendor/memoffset-0.2.1/README.md b/third_party/cargo/vendor/memoffset-0.2.1/README.md deleted file mode 100644 index 1725d7d..0000000 --- a/third_party/cargo/vendor/memoffset-0.2.1/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# memoffset # - -[![](http://meritbadge.herokuapp.com/memoffset)](https://crates.io/crates/memoffset) - -C-Like `offset_of` functionality for Rust structs. - -Introduces the following macros: - * `offset_of!` for obtaining the offset of a member of a struct. - * `span_of!` for obtaining the range that a field, or fields, span. - -`memoffset` works under `no_std` environments. - -## Usage ## -Add the following dependency to your `Cargo.toml`: - -```toml -[dependencies] -memoffset = "0.2" -``` - -Add the following lines at the top of your `main.rs` or `lib.rs` files. - -```rust -#[macro_use] -extern crate memoffset; -``` - -## Examples ## -```rust -#[repr(C, packed)] -struct Foo { - a: u32, - b: u32, - c: [u8; 5], - d: u32, -} - -assert_eq!(offset_of!(Foo, b), 4); -assert_eq!(offset_of!(Foo, c[3]), 11); - -assert_eq!(span_of!(Foo, a), 0..4); -assert_eq!(span_of!(Foo, a .. c), 0..8); -assert_eq!(span_of!(Foo, a .. c[1]), 0..9); -assert_eq!(span_of!(Foo, a ..= c[1]), 0..10); -assert_eq!(span_of!(Foo, ..= d), 0..14); -assert_eq!(span_of!(Foo, b ..), 4..17); -``` diff --git a/third_party/cargo/vendor/memoffset-0.2.1/src/lib.rs b/third_party/cargo/vendor/memoffset-0.2.1/src/lib.rs deleted file mode 100644 index 2738be4..0000000 --- a/third_party/cargo/vendor/memoffset-0.2.1/src/lib.rs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2017 Gilad Naaman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -//! A crate used for calculating offsets of struct members and their spans. -//! -//! Some of the funcationality of the crate makes no sense when used along with structs that -//! are not `#[repr(C, packed)]`, but it is up to the user to make sure that they are. -//! -//! ## Examples -//! ``` -//! #[macro_use] -//! extern crate memoffset; -//! -//! #[repr(C, packed)] -//! struct HelpMeIAmTrappedInAStructFactory { -//! help_me_before_they_: [u8; 15], -//! a: u32 -//! } -//! -//! fn main() { -//! assert_eq!(offset_of!(HelpMeIAmTrappedInAStructFactory, a), 15); -//! assert_eq!(span_of!(HelpMeIAmTrappedInAStructFactory, a), 15..19); -//! assert_eq!(span_of!(HelpMeIAmTrappedInAStructFactory, help_me_before_they_[2] .. a), 2..15); -//! } -//! ``` -//! -//! This functionality can be useful, for example, for checksum calculations: -//! -//! ```ignore -//! #[repr(C, packed)] -//! struct Message { -//! header: MessageHeader, -//! fragment_index: u32, -//! fragment_count: u32, -//! payload: [u8; 1024], -//! checksum: u16 -//! } -//! -//! let checksum_range = &raw[span_of!(Message, header..checksum)]; -//! let checksum = crc16(checksum_range); -//! ``` - -#![no_std] - -// This `use` statement enables the macros to use `$crate::mem`. -// Doing this enables this crate to function under both std and no-std crates. -#[doc(hidden)] -pub use core::mem; - -#[macro_use] -mod offset_of; -#[macro_use] -mod span_of; diff --git a/third_party/cargo/vendor/memoffset-0.2.1/src/offset_of.rs b/third_party/cargo/vendor/memoffset-0.2.1/src/offset_of.rs deleted file mode 100644 index 6148657..0000000 --- a/third_party/cargo/vendor/memoffset-0.2.1/src/offset_of.rs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2017 Gilad Naaman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -/// Calculates the offset of the specified field from the start of the struct. -/// This macro supports arbitrary amount of subscripts and recursive member-accesses. -/// -/// *Note*: This macro may not make much sense when used on structs that are not `#[repr(C, packed)]` -/// -/// ## Examples - Simple -/// ``` -/// #[macro_use] -/// extern crate memoffset; -/// -/// #[repr(C, packed)] -/// struct Foo { -/// a: u32, -/// b: u64, -/// c: [u8; 5] -/// } -/// -/// fn main() { -/// assert_eq!(offset_of!(Foo, a), 0); -/// assert_eq!(offset_of!(Foo, b), 4); -/// assert_eq!(offset_of!(Foo, c[2]), 14); -/// } -/// ``` -/// -/// ## Examples - Advanced -/// ``` -/// #[macro_use] -/// extern crate memoffset; -/// -/// #[repr(C, packed)] -/// struct UnnecessarilyComplicatedStruct { -/// member: [UnnecessarilyComplexStruct; 12] -/// } -/// -/// #[repr(C, packed)] -/// struct UnnecessarilyComplexStruct { -/// a: u32, -/// b: u64, -/// c: [u8; 5] -/// } -/// -/// -/// fn main() { -/// assert_eq!(offset_of!(UnnecessarilyComplicatedStruct, member[3].c[3]), 66); -/// } -/// ``` -#[macro_export] -macro_rules! offset_of { - ($father:ty, $($field:tt)+) => ({ - #[allow(unused_unsafe)] - let root: $father = unsafe { $crate::mem::uninitialized() }; - - let base = &root as *const _ as usize; - - // Future error: borrow of packed field requires unsafe function or block (error E0133) - #[allow(unused_unsafe)] - let member = unsafe { &root.$($field)* as *const _ as usize }; - - $crate::mem::forget(root); - - member - base - }); -} - -#[cfg(test)] -mod tests { - #[repr(C, packed)] - struct Foo { - a: u32, - b: [u8; 4], - c: i64, - } - - #[test] - fn offset_simple() { - assert_eq!(offset_of!(Foo, a), 0); - assert_eq!(offset_of!(Foo, b), 4); - assert_eq!(offset_of!(Foo, c), 8); - } - - #[test] - fn offset_index() { - assert_eq!(offset_of!(Foo, b[2]), 6); - } - - #[test] - #[should_panic] - fn offset_index_out_of_bounds() { - offset_of!(Foo, b[4]); - } - - #[test] - fn tuple_struct() { - #[repr(C, packed)] - struct Tup(i32, i32); - - assert_eq!(offset_of!(Tup, 0), 0); - } -} diff --git a/third_party/cargo/vendor/memoffset-0.2.1/src/span_of.rs b/third_party/cargo/vendor/memoffset-0.2.1/src/span_of.rs deleted file mode 100644 index fcb49ed..0000000 --- a/third_party/cargo/vendor/memoffset-0.2.1/src/span_of.rs +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright (c) 2017 Gilad Naaman -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. - -/// Produces a range instance representing the sub-slice containing the specified member. -/// -/// This macro provides 2 forms of differing functionalities. -/// -/// The first form is identical to the appearance of the `offset_of!` macro, -/// and just like `offset_of!`, it has no limit on the depth of fields / subscripts used. -/// -/// ```ignore -/// span_of!(Struct, member[index].field) -/// ``` -/// -/// The second form of `span_of!` returns a sub-slice which starts at one field, and ends at another. -/// The general pattern of this form is: -/// -/// ```ignore -/// // Exclusive -/// span_of!(Struct, member_a .. member_b) -/// // Inclusive -/// span_of!(Struct, member_a ..= member_b) -/// -/// // Open-ended ranges -/// span_of!(Struct, .. end) -/// span_of!(Struct, start ..) -/// ``` -/// -/// *Note*: -/// This macro uses recursion in order to resolve the range expressions, so there is a limit to the complexity of the expression. -/// In order to raise the limit, the compiler's recursion limit should be lifted. -/// -/// *Note*: -/// This macro may not make much sense when used on structs that are not `#[repr(C, packed)]` -/// -/// ## Examples -/// ``` -/// #[macro_use] -/// extern crate memoffset; -/// -/// #[repr(C, packed)] -/// struct Florp { -/// a: u32 -/// } -/// -/// #[repr(C, packed)] -/// struct Blarg { -/// x: u64, -/// y: [u8; 56], -/// z: Florp, -/// egg: [[u8; 4]; 4] -/// } -/// -/// fn main() { -/// assert_eq!(0..8, span_of!(Blarg, x)); -/// assert_eq!(64..68, span_of!(Blarg, z.a)); -/// assert_eq!(79..80, span_of!(Blarg, egg[2][3])); -/// -/// assert_eq!(8..64, span_of!(Blarg, y[0] .. z)); -/// assert_eq!(0..42, span_of!(Blarg, x .. y[34])); -/// assert_eq!(0..64, span_of!(Blarg, x ..= y)); -/// assert_eq!(58..68, span_of!(Blarg, y[50] ..= z)); -/// } -/// ``` -#[macro_export] -macro_rules! span_of { - (@helper $root:ident, [] ..=) => { - compile_error!("Expected a range, found '..='") - }; - (@helper $root:ident, [] ..) => { - compile_error!("Expected a range, found '..'") - }; - (@helper $root:ident, [] ..= $($field:tt)+) => { - (&$root as *const _ as usize, - &$root.$($field)* as *const _ as usize + $crate::mem::size_of_val(&$root.$($field)*)) - }; - (@helper $root:ident, [] .. $($field:tt)+) => { - (&$root as *const _ as usize, &$root.$($field)* as *const _ as usize) - }; - (@helper $root:ident, $(# $begin:tt)+ [] ..= $($end:tt)+) => { - (&$root.$($begin)* as *const _ as usize, - &$root.$($end)* as *const _ as usize + $crate::mem::size_of_val(&$root.$($end)*)) - }; - (@helper $root:ident, $(# $begin:tt)+ [] .. $($end:tt)+) => { - (&$root.$($begin)* as *const _ as usize, &$root.$($end)* as *const _ as usize) - }; - (@helper $root:ident, $(# $begin:tt)+ [] ..) => { - (&$root.$($begin)* as *const _ as usize, - &$root as *const _ as usize + $crate::mem::size_of_val(&$root)) - }; - (@helper $root:ident, $(# $begin:tt)+ [] ..=) => { - compile_error!( - "Found inclusive range to the end of a struct. Did you mean '..' instead of '..='?") - }; - (@helper $root:ident, $(# $begin:tt)+ []) => { - (&$root.$($begin)* as *const _ as usize, - &$root.$($begin)* as *const _ as usize + $crate::mem::size_of_val(&$root.$($begin)*)) - }; - (@helper $root:ident, $(# $begin:tt)+ [] $tt:tt $($rest:tt)*) => { - span_of!(@helper $root, $(#$begin)* #$tt [] $($rest)*) - }; - (@helper $root:ident, [] $tt:tt $($rest:tt)*) => { - span_of!(@helper $root, #$tt [] $($rest)*) - }; - - ($sty:ty, $($exp:tt)+) => ({ - unsafe { - let root: $sty = $crate::mem::uninitialized(); - let base = &root as *const _ as usize; - let (begin, end) = span_of!(@helper root, [] $($exp)*); - begin-base..end-base - } - }); -} - -#[cfg(test)] -mod tests { - use ::core::mem; - - #[repr(C, packed)] - struct Foo { - a: u32, - b: [u8; 4], - c: i64, - } - - #[test] - fn span_simple() { - assert_eq!(span_of!(Foo, a), 0..4); - assert_eq!(span_of!(Foo, b), 4..8); - assert_eq!(span_of!(Foo, c), 8..16); - } - - #[test] - fn span_index() { - assert_eq!(span_of!(Foo, b[1]), 5..6); - } - - #[test] - fn span_forms() { - #[repr(C, packed)] - struct Florp { - a: u32, - } - - #[repr(C, packed)] - struct Blarg { - x: u64, - y: [u8; 56], - z: Florp, - egg: [[u8; 4]; 4], - } - - // Love me some brute force - assert_eq!(0..8, span_of!(Blarg, x)); - assert_eq!(64..68, span_of!(Blarg, z.a)); - assert_eq!(79..80, span_of!(Blarg, egg[2][3])); - - assert_eq!(8..64, span_of!(Blarg, y[0]..z)); - assert_eq!(0..42, span_of!(Blarg, x..y[34])); - assert_eq!(0..64, span_of!(Blarg, x ..= y)); - assert_eq!(58..68, span_of!(Blarg, y[50] ..= z)); - } - - #[test] - fn ig_test() { - #[repr(C)] - struct Member { - foo: u32, - } - - #[repr(C)] - struct Test { - x: u64, - y: [u8; 56], - z: Member, - egg: [[u8; 4]; 4], - } - - assert_eq!(span_of!(Test, ..x), 0..0); - assert_eq!(span_of!(Test, ..=x), 0..8); - assert_eq!(span_of!(Test, ..y), 0..8); - assert_eq!(span_of!(Test, ..=y), 0..64); - assert_eq!(span_of!(Test, ..y[0]), 0..8); - assert_eq!(span_of!(Test, ..=y[0]), 0..9); - assert_eq!(span_of!(Test, ..z), 0..64); - assert_eq!(span_of!(Test, ..=z), 0..68); - assert_eq!(span_of!(Test, ..z.foo), 0..64); - assert_eq!(span_of!(Test, ..=z.foo), 0..68); - assert_eq!(span_of!(Test, ..egg), 0..68); - assert_eq!(span_of!(Test, ..=egg), 0..84); - assert_eq!(span_of!(Test, ..egg[0]), 0..68); - assert_eq!(span_of!(Test, ..=egg[0]), 0..72); - assert_eq!(span_of!(Test, ..egg[0][0]), 0..68); - assert_eq!(span_of!(Test, ..=egg[0][0]), 0..69); - assert_eq!( - span_of!(Test, x..), - offset_of!(Test, x)..mem::size_of::() - ); - assert_eq!( - span_of!(Test, y..), - offset_of!(Test, y)..mem::size_of::() - ); - assert_eq!( - span_of!(Test, y[0]..), - offset_of!(Test, y[0])..mem::size_of::() - ); - assert_eq!( - span_of!(Test, z..), - offset_of!(Test, z)..mem::size_of::() - ); - assert_eq!( - span_of!(Test, z.foo..), - offset_of!(Test, z.foo)..mem::size_of::() - ); - assert_eq!( - span_of!(Test, egg..), - offset_of!(Test, egg)..mem::size_of::() - ); - assert_eq!( - span_of!(Test, egg[0]..), - offset_of!(Test, egg[0])..mem::size_of::() - ); - assert_eq!( - span_of!(Test, egg[0][0]..), - offset_of!(Test, egg[0][0])..mem::size_of::() - ); - assert_eq!( - span_of!(Test, x..y), - offset_of!(Test, x)..offset_of!(Test, y) - ); - assert_eq!( - span_of!(Test, x..=y), - offset_of!(Test, x)..offset_of!(Test, y) + mem::size_of::<[u8; 56]>() - ); - assert_eq!( - span_of!(Test, x..y[4]), - offset_of!(Test, x)..offset_of!(Test, y[4]) - ); - assert_eq!( - span_of!(Test, x..=y[4]), - offset_of!(Test, x)..offset_of!(Test, y) + mem::size_of::<[u8; 5]>() - ); - assert_eq!( - span_of!(Test, x..z.foo), - offset_of!(Test, x)..offset_of!(Test, z.foo) - ); - assert_eq!( - span_of!(Test, x..=z.foo), - offset_of!(Test, x)..offset_of!(Test, z.foo) + mem::size_of::() - ); - assert_eq!( - span_of!(Test, egg[0][0]..egg[1][0]), - offset_of!(Test, egg[0][0])..offset_of!(Test, egg[1][0]) - ); - } -} diff --git a/third_party/cargo/vendor/metal-0.13.1/.cargo-checksum.json b/third_party/cargo/vendor/metal-0.13.1/.cargo-checksum.json deleted file mode 100644 index cd7cfad..0000000 --- a/third_party/cargo/vendor/metal-0.13.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"a0784f38460a934e9f25dea556eed763f01aedcfdc17dfbf8fe5a32e0eef3a2e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"4142280fb79a5646fa21e3092c4a118d9a38e77b1f2f64446f82049e064bdc09","bors.toml":"06ccf7395c5f6b9a0549ccb499b7e3d1b0a984d43a54861e82ca3c22c9d7e1ca","examples/argument-buffer/main.rs":"815c8a2f5f5f5551556b25c12ecca067e0e9e61559887ea55f6be37a97edcb83","examples/bind/main.rs":"08c3f486b38f1615f5353681d7dd7c3d13f67eaf5d81d84f8f575c0f19e0b88f","examples/caps/main.rs":"ad3390a5e44cdabe0419021f201b360090ca93769fb5566c8605d80609cc62f8","examples/compute/compute-argument-buffer.metal":"6530bbd6a0101d9db2893805436f5dc877959e81ea97a27014c0fc52fc9fa77b","examples/compute/compute-argument-buffer.rs":"ad7a157e6307544fe702eaebe6425e58bd1aa74c7845ca4f71f65adc4f453b64","examples/compute/default.metallib":"0f8579c77cf5d5f35023f1922b672081a23d625f199b0be0a68f81a0bfa95384","examples/compute/embedded-lib.rs":"1ab2031c37f59342774f6e9ba63809f1a0de991298fb3a709bd03054e4767085","examples/compute/main.rs":"ce9fb57e8d40bf3882f1be30f753ea00dc52e0261be1072e657e435047862e8a","examples/compute/shaders.metal":"f2b15551bb5247b88a3029c3d8ef37c6fa04a4a6cca9f90f069894ed6822b4bf","examples/library/main.rs":"7a976d0963c521690830f8a8642cb0fe8aa4a7ffba263119d26ed7f81f13adee","examples/reflection/main.rs":"3b9caa8a5fbc37e4bd94ea0eb7fdba71fd552c532d5b8dddd050427c8833acfc","examples/window/default.metallib":"f43d32e42cb6cbd50a5364dfb11ff17fda4b5cf2046e371d2e3ddc1d2008bb9e","examples/window/main.rs":"b91e8743b6aa25ffa40e1caff874cda5e5a1096002da225a19604707a71f4d37","examples/window/shaders.metal":"4c7ea146229caeb0df1d4feea13b927d27c1a6fe8fd0245ce84bf1975772434a","src/argument.rs":"b8b16aa374481ff415714d4bbbfc4b72a828a01f941f5a471cf61be84998abe5","src/buffer.rs":"63abe11180daff420cd93c5e1e4b23698c292f21ebfb161df3c4be44052be5ae","src/capturemanager.rs":"986f88aa497e344381b83a98d0927d0298a1d1e04fdd688330d960c1d1290c9e","src/commandbuffer.rs":"7d863679ab853ddd0baef3aba2585fae05693ce40a48acc15e21f2b0100777b4","src/commandqueue.rs":"f8aee21c3e7c68b66a12a2863312870fd8328e62ff11e9a5b317aee0b8b0cbce","src/constants.rs":"91c2271722b07e98a39ba71ef6c6bcf8a049f578e5c817a24b6d5919f052a48e","src/depthstencil.rs":"ed0ea2a22a44c947b42fc89744ba7201f11bc1945838db784f1f227f62bcb729","src/device.rs":"dc48e59361605bca5af1a668ec67d14344f372d3f6f5343c0ef37ab3497f9c7b","src/drawable.rs":"1b2d6288b13b5d688430b6321fbbcf314e95c92468a514f5c02c6481dc1caf05","src/encoder.rs":"4b0b261ce37a4598c3ef953ee63af6f047713fbb106978ed15328ef335390ad8","src/heap.rs":"75049467abad6292af6b0898e3d00feca424b13898dab7169f15cfccfa86f4fd","src/lib.rs":"b96f6d8b132cb1f631cab3143c008b4649726b0a42b46b53b9329e62b789bb54","src/library.rs":"50c97deb97fb0d2cee1364c7b1dd7f82eb90e9679a586ca09c6b74c1849748a8","src/pipeline/compute.rs":"ae67d1bceccd501f93da1b8f948bba468d0521cccdf3406e742baba9691db05d","src/pipeline/mod.rs":"4f9679202950b1ae95c8d97072c69139908f8104631a8933f19117365b3d16e6","src/pipeline/render.rs":"665ef126282751e3b1ae933054ac5df02c9c48022c030f8b45ee01f7288299f1","src/renderpass.rs":"f105a54184f794766d96e5af01b2707c9ac9a6570dc8778722c56900c11b4fe4","src/resource.rs":"31d7c809965bf11919270a45b40adcc08e52b6f63651a8f001abc01a4991d8a9","src/sampler.rs":"20efa4e9603fc725268038eaaded6ffa2e0e773d24ea0b0832a22153721cecf9","src/texture.rs":"ed59aade1377c984b2889eb5680182553eeb54b4e72714c87c43984c2c95abea","src/types.rs":"b55b6f9508d82df30ac2d5032498724704738977d66c6939c937708e2af4c503","src/vertexdescriptor.rs":"79dc44e8f1ee87510bef1fe157b16edce9ccbcf2635c3d36cd860bad92f164c2"},"package":"7de9c2b83c946ab01c9942928388f911d93486b97636d9927541345905fea65d"} \ No newline at end of file diff --git a/third_party/cargo/vendor/metal-0.13.1/src/constants.rs b/third_party/cargo/vendor/metal-0.13.1/src/constants.rs deleted file mode 100644 index 935c9cb..0000000 --- a/third_party/cargo/vendor/metal-0.13.1/src/constants.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2016 GFX developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -#[repr(u64)] -#[allow(non_camel_case_types)] -#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] -pub enum MTLPixelFormat { - Invalid = 0, - A8Unorm = 1, - R8Unorm = 10, - R8Unorm_sRGB = 11, - R8Snorm = 12, - R8Uint = 13, - R8Sint = 14, - R16Unorm = 20, - R16Snorm = 22, - R16Uint = 23, - R16Sint = 24, - R16Float = 25, - RG8Unorm = 30, - RG8Unorm_sRGB = 31, - RG8Snorm = 32, - RG8Uint = 33, - RG8Sint = 34, - B5G6R5Unorm = 40, - A1BGR5Unorm = 41, - ABGR4Unorm = 42, - BGR5A1Unorm = 43, - R32Uint = 53, - R32Sint = 54, - R32Float = 55, - RG16Unorm = 60, - RG16Snorm = 62, - RG16Uint = 63, - RG16Sint = 64, - RG16Float = 65, - RGBA8Unorm = 70, - RGBA8Unorm_sRGB = 71, - RGBA8Snorm = 72, - RGBA8Uint = 73, - RGBA8Sint = 74, - BGRA8Unorm = 80, - BGRA8Unorm_sRGB = 81, - RGB10A2Unorm = 90, - RGB10A2Uint = 91, - RG11B10Float = 92, - RGB9E5Float = 93, - BGR10A2Unorm = 94, - RG32Uint = 103, - RG32Sint = 104, - RG32Float = 105, - RGBA16Unorm = 110, - RGBA16Snorm = 112, - RGBA16Uint = 113, - RGBA16Sint = 114, - RGBA16Float = 115, - RGBA32Uint = 123, - RGBA32Sint = 124, - RGBA32Float = 125, - BC1_RGBA = 130, - BC1_RGBA_sRGB = 131, - BC2_RGBA = 132, - BC2_RGBA_sRGB = 133, - BC3_RGBA = 134, - BC3_RGBA_sRGB = 135, - BC4_RUnorm = 140, - BC4_RSnorm = 141, - BC5_RGUnorm = 142, - BC5_RGSnorm = 143, - BC6H_RGBFloat = 150, - BC6H_RGBUfloat = 151, - BC7_RGBAUnorm = 152, - BC7_RGBAUnorm_sRGB = 153, - PVRTC_RGB_2BPP = 160, - PVRTC_RGB_2BPP_sRGB = 161, - PVRTC_RGB_4BPP = 162, - PVRTC_RGB_4BPP_sRGB = 163, - PVRTC_RGBA_2BPP = 164, - PVRTC_RGBA_2BPP_sRGB = 165, - PVRTC_RGBA_4BPP = 166, - PVRTC_RGBA_4BPP_sRGB = 167, - EAC_R11Unorm = 170, - EAC_R11Snorm = 172, - EAC_RG11Unorm = 174, - EAC_RG11Snorm = 176, - EAC_RGBA8 = 178, - EAC_RGBA8_sRGB = 179, - ETC2_RGB8 = 180, - ETC2_RGB8_sRGB = 181, - ETC2_RGB8A1 = 182, - ETC2_RGB8A1_sRGB = 183, - ASTC_4x4_sRGB = 186, - ASTC_5x4_sRGB = 187, - ASTC_5x5_sRGB = 188, - ASTC_6x5_sRGB = 189, - ASTC_6x6_sRGB = 190, - ASTC_8x5_sRGB = 192, - ASTC_8x6_sRGB = 193, - ASTC_8x8_sRGB = 194, - ASTC_10x5_sRGB = 195, - ASTC_10x6_sRGB = 196, - ASTC_10x8_sRGB = 197, - ASTC_10x10_sRGB = 198, - ASTC_12x10_sRGB = 199, - ASTC_12x12_sRGB = 200, - ASTC_4x4_LDR = 204, - ASTC_5x4_LDR = 205, - ASTC_5x5_LDR = 206, - ASTC_6x5_LDR = 207, - ASTC_6x6_LDR = 208, - ASTC_8x5_LDR = 210, - ASTC_8x6_LDR = 211, - ASTC_8x8_LDR = 212, - ASTC_10x5_LDR = 213, - ASTC_10x6_LDR = 214, - ASTC_10x8_LDR = 215, - ASTC_10x10_LDR = 216, - ASTC_12x10_LDR = 217, - ASTC_12x12_LDR = 218, - GBGR422 = 240, - BGRG422 = 241, - Depth16Unorm = 250, - Depth32Float = 252, - Stencil8 = 253, - Depth24Unorm_Stencil8 = 255, - Depth32Float_Stencil8 = 260, - X32_Stencil8 = 261, - X24_Stencil8 = 262, - BGRA10_XR = 552, - BGRA10_XR_SRGB = 553, - BGR10_XR = 554, - BGR10_XR_SRGB = 555, -} diff --git a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/mod.rs b/third_party/cargo/vendor/metal-0.13.1/src/pipeline/mod.rs deleted file mode 100644 index 02548ad..0000000 --- a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/mod.rs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2017 GFX developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use super::*; - -mod compute; -mod render; - -pub use self::compute::*; -pub use self::render::*; diff --git a/third_party/cargo/vendor/metal-0.17.1/.cargo-checksum.json b/third_party/cargo/vendor/metal-0.17.1/.cargo-checksum.json new file mode 100644 index 0000000..f04eb97 --- /dev/null +++ b/third_party/cargo/vendor/metal-0.17.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"fb44ee4491846e8fa877e62609d545b5295522966b033c5461aeaf0fa247f328","Cargo.toml":"4918b09fd685edaf7c1400b715ad9a9c4f19c080fa073b56102071e54f8c5647","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"8961f19dddc0024f98c72d40689c8db0d317b0dfac1cfd6bfc9150d0fc9d4f95","bors.toml":"06ccf7395c5f6b9a0549ccb499b7e3d1b0a984d43a54861e82ca3c22c9d7e1ca","examples/argument-buffer/main.rs":"6634a20703e60e0c37a89333f4f65795f9d012f799b481a110612fd234dd8649","examples/bind/main.rs":"85b15b6edf2da657072ae9df14347cd1333182d74b511e88a5e6a2c1e865a430","examples/caps/main.rs":"145f5efc728232061d12f09ab954f738b6870921ee3f07744ee1450111c98ed8","examples/compute/compute-argument-buffer.metal":"6530bbd6a0101d9db2893805436f5dc877959e81ea97a27014c0fc52fc9fa77b","examples/compute/compute-argument-buffer.rs":"7ba732fdacf709d7075164bafd801fe025389d28620abb9979b3b75550771d32","examples/compute/default.metallib":"0f8579c77cf5d5f35023f1922b672081a23d625f199b0be0a68f81a0bfa95384","examples/compute/embedded-lib.rs":"faeee13d9c959f88c3950a693fb3bc57d61bc005209923964a5f7c2c196fb9ff","examples/compute/main.rs":"ee695accf6659c3cc0043b4067214edd16c484f30a5aef45d6a897a5f90c5e2b","examples/compute/shaders.metal":"f2b15551bb5247b88a3029c3d8ef37c6fa04a4a6cca9f90f069894ed6822b4bf","examples/library/main.rs":"a1420ec28a471f28a789b75b3ecf5abb699ed352b337747169914812fb98045a","examples/reflection/main.rs":"927902392a060e40a98f0d222cfa994bb60eee169fdcd550f0ecfc9e44872164","examples/window/default.metallib":"f43d32e42cb6cbd50a5364dfb11ff17fda4b5cf2046e371d2e3ddc1d2008bb9e","examples/window/main.rs":"bd264d90404d4955a8a119268c982346dd5a493415f2629d57e9d82820475fbc","examples/window/shaders.metal":"4c7ea146229caeb0df1d4feea13b927d27c1a6fe8fd0245ce84bf1975772434a","src/argument.rs":"f64e62439d67c02e47568ae91421033692dcec5abd174605c7b3abbcc0d3d9e4","src/buffer.rs":"960a8dd9375e7ce0783660baa0b15cea609dfe5018df9adc9bc18cea8a0a1b35","src/capturemanager.rs":"cc168fff60662f481a5580de2c1e5ff5a15a3248209a929b6a3d1caf8ad88913","src/commandbuffer.rs":"0dd0b34699b27e4891a0d2690ea01b69e3d40d66dabed023ccd1e7014fde8d0a","src/commandqueue.rs":"5b87621ae4495ae04a5de5ce980d0cde31b4bb0d1e31e932d34c49252240c9d9","src/constants.rs":"7be4d901da863f126d158d1042f5482a122fbcf760f7c225b0b1693a55f6bb4b","src/depthstencil.rs":"7f8fc0c9e9887ed0681fdec846e5e4a4830b69ea023d6506d567020ee7234408","src/device.rs":"4e8f6777aacb0089ea32d68b08fb5533494023ed1efe94c7480fcc78d161ed7a","src/drawable.rs":"03a8adb20da93839314586f0ec12bce139ece546a07e2f9ed60c89303fa52a82","src/encoder.rs":"d7acd5854a3048a466c3aa20bd8bf36f63ad721dd3ed1d222d6fd961a98e0964","src/heap.rs":"73d4082d29f31af58e3950c401da32aa8939c5fbdd2e587ef3dd977d30b79166","src/lib.rs":"e8396f361242ab37d2c791e6ee01f9cc149738635e8d854782d9b07e86dbc4c0","src/library.rs":"c8dad2294141f1d67e06fb3d2f9c407e48a7dc148c51dd52d5b5f0a86028a85a","src/pipeline/compute.rs":"b9f614a944d9d8517dd9806267a9f0efe337127e585d73ef6655398ea2658d90","src/pipeline/mod.rs":"6f6af08f4374e02c73d96923b6bcd3977ddd9393172b529c023381c2c4765e94","src/pipeline/render.rs":"d81e2b801801a6829650f8212ed5b99a203d48d23372f3d9c19166d4286dc837","src/renderpass.rs":"22f2b5a996c5c32896923f428b84350d51b83b1ee91cd889f96465137dfa2e04","src/resource.rs":"03ad88f2d67a7c4ceac4ae00781d56b269c048be55b5c40f0e136cd6986d907d","src/sampler.rs":"69b370d3b12dc12bbc4e9efba23c4a7ec8e401602cee9656c7030c6a68812411","src/texture.rs":"d8352033d26e1a254914b01444fbd996a17220b69009a36a89caa19a9a4c37c8","src/types.rs":"9b3f094f5d22b619bd1572b723bc23b9b5a766dc65eaa752bb3106db28ca18ea","src/vertexdescriptor.rs":"554c9171df839273f9572814064a8dfd90074772710dff079ad8f7f9908e1e9a"},"package":"f83c7dcc2038e12f68493fa3de44235df27b2497178e257185b4b5b5d028a1e4"} \ No newline at end of file diff --git a/third_party/cargo/vendor/metal-0.13.1/BUILD b/third_party/cargo/vendor/metal-0.17.1/BUILD similarity index 85% rename from third_party/cargo/vendor/metal-0.13.1/BUILD rename to third_party/cargo/vendor/metal-0.17.1/BUILD index b92cbcb..6549105 100644 --- a/third_party/cargo/vendor/metal-0.13.1/BUILD +++ b/third_party/cargo/vendor/metal-0.17.1/BUILD @@ -35,24 +35,21 @@ rust_library( name = "metal", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", "//third_party/cargo/vendor/block-0.1.6:block", - "//third_party/cargo/vendor/cocoa-0.18.5:cocoa", + "//third_party/cargo/vendor/cocoa-0.19.1:cocoa", "//third_party/cargo/vendor/core-graphics-0.17.3:core_graphics", "//third_party/cargo/vendor/foreign-types-0.3.2:foreign_types", - "//third_party/cargo/vendor/libc-0.2.67:libc", "//third_party/cargo/vendor/log-0.4.8:log", "//third_party/cargo/vendor/objc-0.2.7:objc", - "//third_party/cargo/vendor/objc-foundation-0.1.1:objc_foundation", - "//third_party/cargo/vendor/objc_id-0.1.1:objc_id", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.13.1", + version = "0.17.1", crate_features = [ "default", ], diff --git a/third_party/cargo/vendor/metal-0.17.1/Cargo.lock b/third_party/cargo/vendor/metal-0.17.1/Cargo.lock new file mode 100644 index 0000000..3391c68 --- /dev/null +++ b/third_party/cargo/vendor/metal-0.17.1/Cargo.lock @@ -0,0 +1,756 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "andrew" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rusttype 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)", + "xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "android_glue" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "approx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "arrayvec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "backtrace" +version = "0.3.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "backtrace-sys 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "backtrace-sys" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "bitflags" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "byteorder" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cc" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cocoa" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cocoa" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation-sys 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation-sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "core-graphics" +version = "0.17.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "dlib" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "downcast-rs" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "gcc" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "lazy_static" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.65" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libloading" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "line_drawing" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lock_api" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "log" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "memmap" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "metal" +version = "0.17.1" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "cocoa 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "sema 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "winit 0.19.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-traits" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "objc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "objc_exception 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "objc_exception" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ordered-float" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lock_api 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot_core 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "parking_lot_core" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "pkg-config" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "raw-window-handle" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "redox_syscall" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rustc-demangle" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rusttype" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rusttype 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rusttype" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "stb_truetype 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "same-file" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "scopeguard" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "sema" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "smallvec" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-client 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-protocols 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "stb_truetype" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "time" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unreachable" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "walkdir" +version = "2.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "same-file 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-client" +version = "0.21.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "downcast-rs 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-scanner 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-commons" +version = "0.21.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-protocols" +version = "0.21.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-client 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-scanner 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-scanner" +version = "0.21.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-sys" +version = "0.21.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-util" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winit" +version = "0.19.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "backtrace 0.3.40 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "cocoa 0.18.5 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "percent-encoding 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "raw-window-handle 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "smithay-client-toolkit 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-client 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "x11-dl 2.18.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "x11-dl" +version = "2.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", + "maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "pkg-config 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "xdg" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "xml-rs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "xml-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9b7f09f89872c2b6b29e319377b1fbe91c6f5947df19a25596e121cf19a7b35e" +"checksum android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "000444226fcff248f2bc4c7625be32c63caccfecc2723a2b9f78a7487a49c407" +"checksum approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" +"checksum arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" +"checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" +"checksum backtrace 0.3.40 (registry+https://github.com/rust-lang/crates.io-index)" = "924c76597f0d9ca25d762c25a4d369d51267536465dc5064bdf0eb073ed477ea" +"checksum backtrace-sys 0.1.32 (registry+https://github.com/rust-lang/crates.io-index)" = "5d6575f128516de27e3ce99689419835fce9643a9b215a14d2b5b685be018491" +"checksum bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d0c54bb8f454c567f21197eefcdbf5679d0bd99f2ddbe52e84c77061952e6789" +"checksum block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +"checksum byteorder 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8389c509ec62b9fe8eca58c502a0acaf017737355615243496cde4994f8fa4f9" +"checksum cc 1.0.46 (registry+https://github.com/rust-lang/crates.io-index)" = "0213d356d3c4ea2c18c40b037c3be23cd639825c18f25ee670ac7813beeef99c" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum cocoa 0.18.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1706996401131526e36b3b49f0c4d912639ce110996f3ca144d78946727bce54" +"checksum cocoa 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8cd20045e880893b4a8286d5639e9ade85fb1f6a14c291f882cf8cf2149d37d9" +"checksum core-foundation 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cc3532ec724375c7cb7ff0a097b714fde180bb1f6ed2ab27cfcd99ffca873cd2" +"checksum core-foundation-sys 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a3fb15cdbdd9cf8b82d97d0296bb5cd3631bba58d6e31650a002a8e7fb5721f9" +"checksum core-graphics 0.17.3 (registry+https://github.com/rust-lang/crates.io-index)" = "56790968ab1c8a1202a102e6de05fc6e1ec87da99e4e93e9a7d13efbfc1e95a9" +"checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" +"checksum downcast-rs 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "18df8ce4470c189d18aa926022da57544f31e154631eb4cfe796aea97051fe6c" +"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +"checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" +"checksum lazy_static 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "fb497c35d362b6a331cfd94956a07fc2c78a4604cdbee844a81170386b996dd3" +"checksum libc 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "e32a70cf75e5846d53a673923498228bbec6a8624708a9ea5645f075d6276122" +"checksum libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)" = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8" +"checksum libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3ad660d7cb8c5822cd83d10897b0f1f1526792737a179e73896152f85b88c2" +"checksum line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5cc7ad3d82c845bdb5dde34ffdcc7a5fb4d2996e1e1ee0f19c33bc80e15196b9" +"checksum lock_api 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f8912e782533a93a167888781b836336a6ca5da6175c05944c86cf28c31104dc" +"checksum log 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "61bd98ae7f7b754bc53dca7d44b604f733c6bba044ea6f41bc8d89272d8161d2" +"checksum malloc_buf 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +"checksum maybe-uninit 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" +"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +"checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" +"checksum num-traits 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "6ba9a427cfca2be13aa6f6403b0b7e7368fe982bfa16fccc450ce74c46cd9b32" +"checksum objc 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "31d20fd2b37e07cf5125be68357b588672e8cefe9a96f8c17a9d46053b3e590d" +"checksum objc_exception 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "098cd29a2fa3c230d3463ae069cecccc3fdfd64c0d2496ab5b96f82dab6a00dc" +"checksum ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "18869315e81473c951eb56ad5558bbc56978562d3ecfb87abb7a1e944cea4518" +"checksum parking_lot 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f842b1982eb6c2fe34036a4fbfb06dd185a3f5c8edfaacdf7d1ea10b07de6252" +"checksum parking_lot_core 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b876b1b9e7ac6e1a74a6da34d25c42e17e8862aa409cbbbdcfc8d86c6f3bc62b" +"checksum percent-encoding 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" +"checksum pkg-config 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)" = "110d5ee3593dbb73f56294327fe5668bcc997897097cbc76b51e7aed3f52452f" +"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" +"checksum rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "eba5f8cb59cc50ed56be8880a5c7b496bfd9bd26394e176bc67884094145c2c5" +"checksum raw-window-handle 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9db80d08d3ed847ce4fb3def46de0af4bfb6155bd09bd6eaf28b5ac72541c1f1" +"checksum redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "c214e91d3ecf43e9a4e41e578973adeb14b474f2bee858742d127af75a0112b1" +"checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" +"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +"checksum rusttype 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)" = "310942406a39981bed7e12b09182a221a29e0990f3e7e0c971f131922ed135d5" +"checksum rusttype 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6fa38506b5cbf2fb67f915e2725cb5012f1b9a785b0ab55c4733acda5f6554ef" +"checksum same-file 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "585e8ddcedc187886a30fa705c47985c3fa88d06624095856b36ca0b82ff4421" +"checksum scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" +"checksum sema 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "e3af15ff9b4a7d4bd2b21222c05154ee58260780a4d492c22de810f4f4187832" +"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +"checksum smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "26df3bb03ca5eac2e64192b723d51f56c1b1e0860e7c766281f4598f181acdc8" +"checksum smithay-client-toolkit 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2ccb8c57049b2a34d2cc2b203fa785020ba0129d31920ef0d317430adaf748fa" +"checksum stb_truetype 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "824210d6fb52cbc3ad2545270ead6860c7311aa5450642b078da4515937b6f7a" +"checksum time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "d825be0eb33fda1a7e68012d51e9c7f451dc1a69391e7fdc197060bb8c56667b" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9658c94fa8b940eab2250bd5a457f9c48b748420d71293b165c8cdbe2f55f71e" +"checksum wayland-client 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)" = "49963e5f9eeaf637bfcd1b9f0701c99fd5cd05225eb51035550d4272806f2713" +"checksum wayland-commons 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)" = "40c08896768b667e1df195d88a62a53a2d1351a1ed96188be79c196b35bb32ec" +"checksum wayland-protocols 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)" = "4afde2ea2a428eee6d7d2c8584fdbe8b82eee8b6c353e129a434cd6e07f42145" +"checksum wayland-scanner 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)" = "bf3828c568714507315ee425a9529edc4a4aa9901409e373e9e0027e7622b79e" +"checksum wayland-sys 0.21.13 (registry+https://github.com/rust-lang/crates.io-index)" = "520ab0fd578017a0ee2206623ba9ef4afe5e8f23ca7b42f6acfba2f4e66b1628" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum winit 0.19.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f99fce6bd9d143ea3690741af40c99c5b3510a6fd918e84a4e8e7bae25a7f4a9" +"checksum x11-dl 2.18.4 (registry+https://github.com/rust-lang/crates.io-index)" = "be65e1342a3baae65439cd03306778831a3d133b0d20243a7fb83fd5cf403c58" +"checksum xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d089681aa106a86fade1b0128fb5daf07d5867a509ab036d99988dec80429a57" +"checksum xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2" +"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" diff --git a/third_party/cargo/vendor/metal-0.13.1/Cargo.toml b/third_party/cargo/vendor/metal-0.17.1/Cargo.toml similarity index 86% rename from third_party/cargo/vendor/metal-0.13.1/Cargo.toml rename to third_party/cargo/vendor/metal-0.17.1/Cargo.toml index 7eb2691..cdc7dcc 100644 --- a/third_party/cargo/vendor/metal-0.13.1/Cargo.toml +++ b/third_party/cargo/vendor/metal-0.17.1/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "metal" -version = "0.13.1" +version = "0.17.1" authors = ["GFX Developers"] description = "Rust bindings for Metal" homepage = "https://github.com/gfx-rs/metal-rs" @@ -60,34 +61,25 @@ version = "1" version = "0.1.5" [dependencies.cocoa] -version = "0.18" +version = "0.19" [dependencies.core-graphics] -version = "0.17" +version = "0.17.3" [dependencies.foreign-types] version = "0.3" -[dependencies.libc] -version = "0.2" - [dependencies.log] version = "0.4" [dependencies.objc] -version = "0.2.3" +version = "0.2.4" features = ["objc_exception"] - -[dependencies.objc-foundation] -version = "0.1" - -[dependencies.objc_id] -version = "0.1" [dev-dependencies.sema] version = "0.1.4" [dev-dependencies.winit] -version = "0.17" +version = "0.19" [features] default = [] diff --git a/third_party/cargo/vendor/nodrop-0.1.14/LICENSE-APACHE b/third_party/cargo/vendor/metal-0.17.1/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/nodrop-0.1.14/LICENSE-APACHE rename to third_party/cargo/vendor/metal-0.17.1/LICENSE-APACHE diff --git a/third_party/cargo/vendor/crossbeam-epoch-0.6.1/LICENSE-MIT b/third_party/cargo/vendor/metal-0.17.1/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/crossbeam-epoch-0.6.1/LICENSE-MIT rename to third_party/cargo/vendor/metal-0.17.1/LICENSE-MIT diff --git a/third_party/cargo/vendor/metal-0.13.1/README.md b/third_party/cargo/vendor/metal-0.17.1/README.md similarity index 86% rename from third_party/cargo/vendor/metal-0.13.1/README.md rename to third_party/cargo/vendor/metal-0.17.1/README.md index 87a1e6b..2292314 100644 --- a/third_party/cargo/vendor/metal-0.13.1/README.md +++ b/third_party/cargo/vendor/metal-0.17.1/README.md @@ -1,5 +1,6 @@ # metal-rs [![Build Status](https://travis-ci.org/gfx-rs/metal-rs.svg?branch=master)](https://travis-ci.org/gfx-rs/metal-rs) +[![Crates.io](https://img.shields.io/crates/v/metal.svg?label=metal)](https://crates.io/crates/metal) Unsafe Rust bindings for the Metal 3D Graphics API. diff --git a/third_party/cargo/vendor/metal-0.13.1/bors.toml b/third_party/cargo/vendor/metal-0.17.1/bors.toml similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/bors.toml rename to third_party/cargo/vendor/metal-0.17.1/bors.toml diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/argument-buffer/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/argument-buffer/main.rs similarity index 85% rename from third_party/cargo/vendor/metal-0.13.1/examples/argument-buffer/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/argument-buffer/main.rs index 675c9e5..a4232c2 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/argument-buffer/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/argument-buffer/main.rs @@ -5,11 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; -extern crate objc_id; -extern crate objc_foundation; +#[macro_use] +extern crate objc; use metal::*; @@ -18,7 +15,7 @@ use cocoa::foundation::NSAutoreleasePool; fn main() { let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let desc1 = ArgumentDescriptor::new(); desc1.set_data_type(MTLDataType::Texture); @@ -34,12 +31,13 @@ fn main() { let sampler = { let descriptor = SamplerDescriptor::new(); + descriptor.set_support_argument_buffers(true); device.new_sampler(&descriptor) }; encoder.set_sampler_state(&sampler, 1); println!("{:?}", sampler); unsafe { - msg_send![pool, release]; + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/bind/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/bind/main.rs similarity index 83% rename from third_party/cargo/vendor/metal-0.13.1/examples/bind/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/bind/main.rs index 901098a..908aefc 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/bind/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/bind/main.rs @@ -5,11 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; -extern crate objc_id; -extern crate objc_foundation; +#[macro_use] +extern crate objc; use metal::*; @@ -18,7 +15,7 @@ use cocoa::foundation::NSAutoreleasePool; fn main() { let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let buffer = device.new_buffer(4, MTLResourceOptions::empty()); let sampler = { @@ -33,13 +30,13 @@ fn main() { encoder.set_buffers(2, &[Some(&buffer), None], &[4, 0]); encoder.set_sampler_states(1, &[Some(&sampler), None]); - + encoder.end_encoding(); cmd_buf.commit(); println!("Everything is bound"); unsafe { - msg_send![pool, release]; + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/caps/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/caps/main.rs similarity index 72% rename from third_party/cargo/vendor/metal-0.13.1/examples/caps/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/caps/main.rs index 452610c..7603095 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/caps/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/caps/main.rs @@ -5,24 +5,28 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; - use metal::*; fn main() { - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); #[cfg(feature = "private")] { println!("Vendor: {:?}", unsafe { device.vendor() }); println!("Family: {:?}", unsafe { device.family_name() }); } - println!("Max threads per threadgroup: {:?}", device.max_threads_per_threadgroup()); + println!( + "Max threads per threadgroup: {:?}", + device.max_threads_per_threadgroup() + ); #[cfg(target_os = "macos")] { println!("Integrated GPU: {:?}", device.is_low_power()); println!("Headless: {:?}", device.is_headless()); println!("D24S8: {:?}", device.d24_s8_supported()); } - println!("Indirect argument buffer: {:?}", device.argument_buffers_support()); + println!( + "Indirect argument buffer: {:?}", + device.argument_buffers_support() + ); } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/compute-argument-buffer.metal b/third_party/cargo/vendor/metal-0.17.1/examples/compute/compute-argument-buffer.metal similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/compute-argument-buffer.metal rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/compute-argument-buffer.metal diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/compute-argument-buffer.rs b/third_party/cargo/vendor/metal-0.17.1/examples/compute/compute-argument-buffer.rs similarity index 79% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/compute-argument-buffer.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/compute-argument-buffer.rs index 10589fd..b5e9d56 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/compute/compute-argument-buffer.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/compute/compute-argument-buffer.rs @@ -5,11 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; -extern crate objc_id; -extern crate objc_foundation; +#[macro_use] +extern crate objc; use metal::*; @@ -21,40 +18,42 @@ static LIBRARY_SRC: &str = include_str!("compute-argument-buffer.metal"); fn main() { let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let command_queue = device.new_command_queue(); let data = [ - 1u32, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, + 1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, ]; let buffer = device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, (data.len() * mem::size_of::()) as u64, - MTLResourceOptions::CPUCacheModeDefaultCache); + MTLResourceOptions::CPUCacheModeDefaultCache, + ); let sum = { let data = [0u32]; device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, (data.len() * mem::size_of::()) as u64, - MTLResourceOptions::CPUCacheModeDefaultCache) + MTLResourceOptions::CPUCacheModeDefaultCache, + ) }; let command_buffer = command_queue.new_command_buffer(); let encoder = command_buffer.new_compute_command_encoder(); - let library = device.new_library_with_source(LIBRARY_SRC, &CompileOptions::new()).unwrap(); + let library = device + .new_library_with_source(LIBRARY_SRC, &CompileOptions::new()) + .unwrap(); let kernel = library.get_function("sum", None).unwrap(); let argument_encoder = kernel.new_argument_encoder(0); let arg_buffer = device.new_buffer( argument_encoder.encoded_length(), - MTLResourceOptions::empty()); + MTLResourceOptions::empty(), + ); argument_encoder.set_argument_buffer(&arg_buffer, 0); argument_encoder.set_buffer(&buffer, 0, 0); argument_encoder.set_buffer(&sum, 0, 1); @@ -65,7 +64,8 @@ fn main() { let pipeline_state = device .new_compute_pipeline_state_with_function( pipeline_state_descriptor.compute_function().unwrap(), - ).unwrap(); + ) + .unwrap(); encoder.set_compute_pipeline_state(&pipeline_state); encoder.set_buffer(0, Some(&arg_buffer), 0); @@ -78,13 +78,13 @@ fn main() { let thread_group_count = MTLSize { width, height: 1, - depth: 1 + depth: 1, }; let thread_group_size = MTLSize { width: (data.len() as u64 + width) / width, height: 1, - depth: 1 + depth: 1, }; encoder.dispatch_thread_groups(thread_group_count, thread_group_size); @@ -96,6 +96,6 @@ fn main() { unsafe { assert_eq!(465, *ptr); - msg_send![pool, release]; + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/default.metallib b/third_party/cargo/vendor/metal-0.17.1/examples/compute/default.metallib similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/default.metallib rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/default.metallib diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/embedded-lib.rs b/third_party/cargo/vendor/metal-0.17.1/examples/compute/embedded-lib.rs similarity index 84% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/embedded-lib.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/embedded-lib.rs index ce93e69..ed6fcee 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/compute/embedded-lib.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/compute/embedded-lib.rs @@ -5,9 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; +#[macro_use] +extern crate objc; use metal::*; @@ -17,7 +16,7 @@ fn main() { let library_data = include_bytes!("default.metallib"); let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let library = device.new_library_with_data(&library_data[..]).unwrap(); let kernel = library.get_function("sum", None).unwrap(); @@ -27,6 +26,6 @@ fn main() { println!("OK"); unsafe { - msg_send![pool, release] + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/compute/main.rs similarity index 75% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/main.rs index c2c9ae1..07e1e66 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/compute/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/compute/main.rs @@ -5,11 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; -extern crate objc_id; -extern crate objc_foundation; +#[macro_use] +extern crate objc; use metal::*; @@ -19,36 +16,35 @@ use std::mem; fn main() { let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let command_queue = device.new_command_queue(); let data = [ - 1u32, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, + 1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, ]; let buffer = device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, (data.len() * mem::size_of::()) as u64, - MTLResourceOptions::CPUCacheModeDefaultCache); + MTLResourceOptions::CPUCacheModeDefaultCache, + ); let sum = { let data = [0u32]; device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, (data.len() * mem::size_of::()) as u64, - MTLResourceOptions::CPUCacheModeDefaultCache) + MTLResourceOptions::CPUCacheModeDefaultCache, + ) }; - let command_buffer = command_queue.new_command_buffer(); let encoder = command_buffer.new_compute_command_encoder(); - - let library = device.new_library_with_file("examples/compute/default.metallib").unwrap(); + let library = device + .new_library_with_file("examples/compute/default.metallib") + .unwrap(); let kernel = library.get_function("sum", None).unwrap(); let pipeline_state_descriptor = ComputePipelineDescriptor::new(); @@ -56,8 +52,9 @@ fn main() { let pipeline_state = device .new_compute_pipeline_state_with_function( - pipeline_state_descriptor.compute_function().unwrap() - ).unwrap(); + pipeline_state_descriptor.compute_function().unwrap(), + ) + .unwrap(); encoder.set_compute_pipeline_state(&pipeline_state); encoder.set_buffer(0, Some(&buffer), 0); @@ -68,13 +65,13 @@ fn main() { let thread_group_count = MTLSize { width, height: 1, - depth: 1 + depth: 1, }; let thread_group_size = MTLSize { width: (data.len() as u64 + width) / width, height: 1, - depth: 1 + depth: 1, }; encoder.dispatch_thread_groups(thread_group_count, thread_group_size); @@ -86,6 +83,6 @@ fn main() { unsafe { assert_eq!(465, *ptr); - msg_send![pool, release]; + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/compute/shaders.metal b/third_party/cargo/vendor/metal-0.17.1/examples/compute/shaders.metal similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/examples/compute/shaders.metal rename to third_party/cargo/vendor/metal-0.17.1/examples/compute/shaders.metal diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/library/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/library/main.rs similarity index 88% rename from third_party/cargo/vendor/metal-0.13.1/examples/library/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/library/main.rs index 6d14b68..7223db8 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/library/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/library/main.rs @@ -5,14 +5,12 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; - use metal::*; const PROGRAM: &'static str = ""; fn main() { - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let options = CompileOptions::new(); let _library = device.new_library_with_source(PROGRAM, &options); diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/reflection/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/reflection/main.rs similarity index 75% rename from third_party/cargo/vendor/metal-0.13.1/examples/reflection/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/reflection/main.rs index 705577f..41208d1 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/reflection/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/reflection/main.rs @@ -5,9 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate metal; -extern crate cocoa; -#[macro_use] extern crate objc; +#[macro_use] +extern crate objc; use metal::*; @@ -48,11 +47,14 @@ const PROGRAM: &'static str = " fn main() { let pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let options = CompileOptions::new(); let library = device.new_library_with_source(PROGRAM, &options).unwrap(); - let (vs, ps) = (library.get_function("vs", None).unwrap(), library.get_function("ps", None).unwrap()); + let (vs, ps) = ( + library.get_function("vs", None).unwrap(), + library.get_function("ps", None).unwrap(), + ); let vertex_desc = VertexDescriptor::new(); @@ -64,16 +66,18 @@ fn main() { println!("{:?}", desc); #[cfg(features = "private")] - let _reflection = unsafe { RenderPipelineReflection::new( - desc.serialize_vertex_data(), - desc.serialize_fragment_data(), - vertex_desc.serialize_descriptor(), - &device, - 0x8, - 0x0 - ) }; + let _reflection = unsafe { + RenderPipelineReflection::new( + desc.serialize_vertex_data(), + desc.serialize_fragment_data(), + vertex_desc.serialize_descriptor(), + &device, + 0x8, + 0x0, + ) + }; unsafe { - msg_send![pool, release]; + let () = msg_send![pool, release]; } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/window/default.metallib b/third_party/cargo/vendor/metal-0.17.1/examples/window/default.metallib similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/examples/window/default.metallib rename to third_party/cargo/vendor/metal-0.17.1/examples/window/default.metallib diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/window/main.rs b/third_party/cargo/vendor/metal-0.17.1/examples/window/main.rs similarity index 65% rename from third_party/cargo/vendor/metal-0.13.1/examples/window/main.rs rename to third_party/cargo/vendor/metal-0.17.1/examples/window/main.rs index c63fede..00e91a2 100644 --- a/third_party/cargo/vendor/metal-0.13.1/examples/window/main.rs +++ b/third_party/cargo/vendor/metal-0.17.1/examples/window/main.rs @@ -5,18 +5,12 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate cocoa; -extern crate core_graphics; -extern crate metal; -extern crate winit; -#[macro_use] extern crate objc; -extern crate objc_foundation; -extern crate block; -extern crate sema; +#[macro_use] +extern crate objc; +use cocoa::appkit::{NSView, NSWindow}; use cocoa::base::id as cocoa_id; -use cocoa::foundation::{NSRange, NSAutoreleasePool}; -use cocoa::appkit::{NSWindow, NSView}; +use cocoa::foundation::{NSAutoreleasePool, NSRange}; use core_graphics::geometry::CGSize; use objc::runtime::YES; @@ -27,7 +21,6 @@ use winit::os::macos::WindowExt; use std::mem; - fn prepare_pipeline_state<'a>(device: &DeviceRef, library: &LibraryRef) -> RenderPipelineState { let vert = library.get_function("triangle_vertex", None).unwrap(); let frag = library.get_function("triangle_fragment", None).unwrap(); @@ -35,9 +28,15 @@ fn prepare_pipeline_state<'a>(device: &DeviceRef, library: &LibraryRef) -> Rende let pipeline_state_descriptor = RenderPipelineDescriptor::new(); pipeline_state_descriptor.set_vertex_function(Some(&vert)); pipeline_state_descriptor.set_fragment_function(Some(&frag)); - pipeline_state_descriptor.color_attachments().object_at(0).unwrap().set_pixel_format(MTLPixelFormat::BGRA8Unorm); + pipeline_state_descriptor + .color_attachments() + .object_at(0) + .unwrap() + .set_pixel_format(MTLPixelFormat::BGRA8Unorm); - device.new_render_pipeline_state(&pipeline_state_descriptor).unwrap() + device + .new_render_pipeline_state(&pipeline_state_descriptor) + .unwrap() } fn prepare_render_pass_descriptor(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) { @@ -56,10 +55,11 @@ fn main() { let glutin_window = winit::WindowBuilder::new() .with_dimensions((800, 600).into()) .with_title("Metal".to_string()) - .build(&events_loop).unwrap(); + .build(&events_loop) + .unwrap(); let window: cocoa_id = unsafe { mem::transmute(glutin_window.get_nswindow()) }; - let device = Device::system_default(); + let device = Device::system_default().expect("no device found"); let layer = CoreAnimationLayer::new(); layer.set_device(&device); @@ -76,22 +76,23 @@ fn main() { let draw_size = glutin_window.get_inner_size().unwrap(); layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); - let library = device.new_library_with_file("examples/window/default.metallib").unwrap(); + let library = device + .new_library_with_file("examples/window/default.metallib") + .unwrap(); let pipeline_state = prepare_pipeline_state(&device, &library); let command_queue = device.new_command_queue(); //let nc: () = msg_send![command_queue.0, setExecutionEnabled:true]; let vbuf = { let vertex_data = [ - 0.0f32, 0.5, 1.0, 0.0, 0.0, - -0.5, -0.5, 0.0, 1.0, 0.0, - 0.5, 0.5, 0.0, 0.0, 1.0, + 0.0f32, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 1.0, ]; device.new_buffer_with_data( unsafe { mem::transmute(vertex_data.as_ptr()) }, (vertex_data.len() * mem::size_of::()) as u64, - MTLResourceOptions::CPUCacheModeDefaultCache) + MTLResourceOptions::CPUCacheModeDefaultCache, + ) }; let mut pool = unsafe { NSAutoreleasePool::new(cocoa::base::nil) }; @@ -99,11 +100,12 @@ fn main() { let mut running = true; while running { - events_loop.poll_events(|event| { - match event { - winit::Event::WindowEvent{ event: winit::WindowEvent::CloseRequested, .. } => running = false, - _ => () - } + events_loop.poll_events(|event| match event { + winit::Event::WindowEvent { + event: winit::WindowEvent::CloseRequested, + .. + } => running = false, + _ => (), }); if let Some(drawable) = layer.next_drawable() { @@ -111,7 +113,8 @@ fn main() { let _a = prepare_render_pass_descriptor(&render_pass_descriptor, drawable.texture()); let command_buffer = command_queue.new_command_buffer(); - let parallel_encoder = command_buffer.new_parallel_render_command_encoder(&render_pass_descriptor); + let parallel_encoder = + command_buffer.new_parallel_render_command_encoder(&render_pass_descriptor); let encoder = parallel_encoder.render_command_encoder(); encoder.set_render_pipeline_state(&pipeline_state); encoder.set_vertex_buffer(0, Some(&vbuf), 0); @@ -119,24 +122,48 @@ fn main() { encoder.end_encoding(); parallel_encoder.end_encoding(); - render_pass_descriptor.color_attachments().object_at(0).unwrap().set_load_action(MTLLoadAction::DontCare); + render_pass_descriptor + .color_attachments() + .object_at(0) + .unwrap() + .set_load_action(MTLLoadAction::DontCare); - let parallel_encoder = command_buffer.new_parallel_render_command_encoder(&render_pass_descriptor); + let parallel_encoder = + command_buffer.new_parallel_render_command_encoder(&render_pass_descriptor); let encoder = parallel_encoder.render_command_encoder(); - use std::mem; let p = vbuf.contents(); - let vertex_data: &[u8; 60] = unsafe { mem::transmute(&[ - 0.0f32, 0.5, 1.0, 0.0-r, 0.0, - -0.5, -0.5, 0.0, 1.0-r, 0.0, - 0.5, 0.5, 0.0, 0.0, 1.0+r, - ]) }; + let vertex_data: &[u8; 60] = unsafe { + mem::transmute(&[ + 0.0f32, + 0.5, + 1.0, + 0.0 - r, + 0.0, + -0.5, + -0.5, + 0.0, + 1.0 - r, + 0.0, + 0.5, + 0.5, + 0.0, + 0.0, + 1.0 + r, + ]) + }; use std::ptr; unsafe { - ptr::copy(vertex_data.as_ptr(), p as *mut u8, (vertex_data.len() * mem::size_of::()) as usize); + ptr::copy( + vertex_data.as_ptr(), + p as *mut u8, + (vertex_data.len() * mem::size_of::()) as usize, + ); } - vbuf.did_modify_range(NSRange::new(0 as u64, (vertex_data.len() * mem::size_of::()) as u64)); - + vbuf.did_modify_range(NSRange::new( + 0 as u64, + (vertex_data.len() * mem::size_of::()) as u64, + )); encoder.set_render_pipeline_state(&pipeline_state); encoder.set_vertex_buffer(0, Some(&vbuf), 0); @@ -149,8 +176,8 @@ fn main() { r += 0.01f32; //let _: () = msg_send![command_queue.0, _submitAvailableCommandBuffers]; - unsafe { - msg_send![pool, release]; + unsafe { + let () = msg_send![pool, release]; pool = NSAutoreleasePool::new(cocoa::base::nil); } } diff --git a/third_party/cargo/vendor/metal-0.13.1/examples/window/shaders.metal b/third_party/cargo/vendor/metal-0.17.1/examples/window/shaders.metal similarity index 100% rename from third_party/cargo/vendor/metal-0.13.1/examples/window/shaders.metal rename to third_party/cargo/vendor/metal-0.17.1/examples/window/shaders.metal diff --git a/third_party/cargo/vendor/metal-0.13.1/src/argument.rs b/third_party/cargo/vendor/metal-0.17.1/src/argument.rs similarity index 66% rename from third_party/cargo/vendor/metal-0.13.1/src/argument.rs rename to third_party/cargo/vendor/metal-0.17.1/src/argument.rs index a8eda98..6dda8ff 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/argument.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/argument.rs @@ -5,11 +5,10 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use ::{Array, MTLTextureType}; +use crate::{Array, MTLTextureType}; use cocoa::foundation::NSUInteger; -use objc::runtime::{YES, NO}; -use objc_foundation::{NSString, INSString}; +use objc::runtime::{NO, YES}; #[repr(u64)] #[allow(non_camel_case_types)] @@ -18,9 +17,9 @@ pub enum MTLDataType { None = 0, Struct = 1, - Array = 2, + Array = 2, - Float = 3, + Float = 3, Float2 = 4, Float3 = 5, Float4 = 6, @@ -37,7 +36,7 @@ pub enum MTLDataType { Float4x3 = 14, Float4x4 = 15, - Half = 16, + Half = 16, Half2 = 17, Half3 = 18, Half4 = 19, @@ -54,17 +53,17 @@ pub enum MTLDataType { Half4x3 = 27, Half4x4 = 28, - Int = 29, + Int = 29, Int2 = 30, Int3 = 31, Int4 = 32, - UInt = 33, + UInt = 33, UInt2 = 34, UInt3 = 35, UInt4 = 36, - Short = 37, + Short = 37, Short2 = 38, Short3 = 39, Short4 = 40, @@ -74,17 +73,17 @@ pub enum MTLDataType { UShort3 = 43, UShort4 = 44, - Char = 45, + Char = 45, Char2 = 46, Char3 = 47, Char4 = 48, - UChar = 49, + UChar = 49, UChar2 = 50, UChar3 = 51, UChar4 = 52, - Bool = 53, + Bool = 53, Bool2 = 54, Bool3 = 55, Bool4 = 56, @@ -124,9 +123,9 @@ pub enum MTLArgumentType { #[repr(u32)] #[allow(non_camel_case_types)] pub enum MTLArgumentAccess { - ReadOnly = 0, - ReadWrite = 1, - WriteOnly = 2, + ReadOnly = 0, + ReadWrite = 1, + WriteOnly = 2, } pub enum MTLStructMember {} @@ -140,33 +139,25 @@ foreign_obj_type! { impl StructMemberRef { pub fn name(&self) -> &str { unsafe { - let name: &NSString = msg_send![self, name]; - name.as_str() + let name = msg_send![self, name]; + crate::nsstring_as_str(name) } } pub fn offset(&self) -> NSUInteger { - unsafe { - msg_send![self, offset] - } + unsafe { msg_send![self, offset] } } pub fn data_type(&self) -> MTLDataType { - unsafe { - msg_send![self, dataType] - } + unsafe { msg_send![self, dataType] } } pub fn struct_type(&self) -> MTLStructType { - unsafe { - msg_send![self, structType] - } + unsafe { msg_send![self, structType] } } pub fn array_type(&self) -> MTLArrayType { - unsafe { - msg_send![self, arrayType] - } + unsafe { msg_send![self, arrayType] } } } @@ -180,17 +171,13 @@ foreign_obj_type! { impl StructTypeRef { pub fn members(&self) -> &Array { - unsafe { - msg_send![self, members] - } + unsafe { msg_send![self, members] } } pub fn member_from_name(&self, name: &str) -> Option<&StructMemberRef> { - let nsname = NSString::from_str(name); + let nsname = crate::nsstring_from_str(name); - unsafe { - msg_send![self, memberByName:nsname] - } + unsafe { msg_send![self, memberByName: nsname] } } } @@ -204,33 +191,23 @@ foreign_obj_type! { impl ArrayTypeRef { pub fn array_length(&self) -> NSUInteger { - unsafe { - msg_send![self, arrayLength] - } + unsafe { msg_send![self, arrayLength] } } pub fn stride(&self) -> NSUInteger { - unsafe { - msg_send![self, stride] - } + unsafe { msg_send![self, stride] } } pub fn element_type(&self) -> MTLDataType { - unsafe { - msg_send![self, elementType] - } + unsafe { msg_send![self, elementType] } } pub fn element_struct_type(&self) -> MTLStructType { - unsafe { - msg_send![self, elementStructType] - } + unsafe { msg_send![self, elementStructType] } } pub fn element_array_type(&self) -> MTLArrayType { - unsafe { - msg_send![self, elementArrayType] - } + unsafe { msg_send![self, elementArrayType] } } } @@ -245,27 +222,21 @@ foreign_obj_type! { impl ArgumentRef { pub fn name(&self) -> &str { unsafe { - let name: &NSString = msg_send![self, name]; - name.as_str() + let name = msg_send![self, name]; + crate::nsstring_as_str(name) } } pub fn type_(&self) -> MTLArgumentType { - unsafe { - msg_send![self, type] - } + unsafe { msg_send![self, type] } } pub fn access(&self) -> MTLArgumentAccess { - unsafe { - msg_send![self, access] - } + unsafe { msg_send![self, access] } } pub fn index(&self) -> NSUInteger { - unsafe { - msg_send![self, index] - } + unsafe { msg_send![self, index] } } pub fn is_active(&self) -> bool { @@ -273,57 +244,41 @@ impl ArgumentRef { match msg_send![self, isActive] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn buffer_alignment(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferAlignment] - } + unsafe { msg_send![self, bufferAlignment] } } pub fn buffer_data_size(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferDataSize] - } + unsafe { msg_send![self, bufferDataSize] } } pub fn buffer_data_type(&self) -> MTLDataType { - unsafe { - msg_send![self, bufferDataType] - } + unsafe { msg_send![self, bufferDataType] } } pub fn buffer_struct_type(&self) -> &StructTypeRef { - unsafe { - msg_send![self, bufferStructType] - } + unsafe { msg_send![self, bufferStructType] } } pub fn threadgroup_memory_alignment(&self) -> NSUInteger { - unsafe { - msg_send![self, threadgroupMemoryAlignment] - } + unsafe { msg_send![self, threadgroupMemoryAlignment] } } pub fn threadgroup_memory_data_size(&self) -> NSUInteger { - unsafe { - msg_send![self, threadgroupMemoryDataSize] - } + unsafe { msg_send![self, threadgroupMemoryDataSize] } } pub fn texture_type(&self) -> MTLTextureType { - unsafe { - msg_send![self, textureType] - } + unsafe { msg_send![self, textureType] } } pub fn texture_data_type(&self) -> MTLDataType { - unsafe { - msg_send![self, textureDataType] - } + unsafe { msg_send![self, textureDataType] } } } @@ -346,32 +301,22 @@ impl ArgumentDescriptor { impl ArgumentDescriptorRef { pub fn set_data_type(&self, ty: MTLDataType) { - unsafe { - msg_send![self, setDataType:ty] - } + unsafe { msg_send![self, setDataType: ty] } } pub fn set_index(&self, index: NSUInteger) { - unsafe { - msg_send![self, setIndex:index] - } + unsafe { msg_send![self, setIndex: index] } } pub fn set_access(&self, access: MTLArgumentAccess) { - unsafe { - msg_send![self, setAccess:access] - } + unsafe { msg_send![self, setAccess: access] } } pub fn set_array_length(&self, length: NSUInteger) { - unsafe { - msg_send![self, setArrayLength:length] - } + unsafe { msg_send![self, setArrayLength: length] } } pub fn set_texture_type(&self, ty: MTLTextureType) { - unsafe { - msg_send![self, setTextureType:ty] - } + unsafe { msg_send![self, setTextureType: ty] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/buffer.rs b/third_party/cargo/vendor/metal-0.17.1/src/buffer.rs similarity index 56% rename from third_party/cargo/vendor/metal-0.13.1/src/buffer.rs rename to third_party/cargo/vendor/metal-0.17.1/src/buffer.rs index ad7c0d0..4e5363c 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/buffer.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/buffer.rs @@ -18,27 +18,25 @@ foreign_obj_type! { type ParentType = ResourceRef; } - impl BufferRef { pub fn length(&self) -> u64 { - unsafe { - msg_send![self, length] - } + unsafe { msg_send![self, length] } } - pub fn contents(&self) -> *mut libc::c_void { - unsafe { - msg_send![self, contents] - } + pub fn contents(&self) -> *mut std::ffi::c_void { + unsafe { msg_send![self, contents] } } pub fn did_modify_range(&self, range: NSRange) { - unsafe { - msg_send![self, didModifyRange:range] - } + unsafe { msg_send![self, didModifyRange: range] } } - pub fn new_texture_from_contents(&self, descriptor: &TextureDescriptorRef, offset: u64, stride: u64) -> Texture { + pub fn new_texture_from_contents( + &self, + descriptor: &TextureDescriptorRef, + offset: u64, + stride: u64, + ) -> Texture { unsafe { msg_send![self, newTextureWithDescriptor:descriptor @@ -47,4 +45,18 @@ impl BufferRef { ] } } + + pub fn set_label(&self, name: &str) { + unsafe { + let name = crate::nsstring_from_str(name); + msg_send![self, setLabel:name] + } + } + + pub fn add_debug_marker(&self, name: &str, range: NSRange) { + unsafe { + let name = crate::nsstring_from_str(name); + msg_send![self, addDebugMarker:name range:range] + } + } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/capturemanager.rs b/third_party/cargo/vendor/metal-0.17.1/src/capturemanager.rs similarity index 81% rename from third_party/cargo/vendor/metal-0.13.1/src/capturemanager.rs rename to third_party/cargo/vendor/metal-0.17.1/src/capturemanager.rs index bf8b6f2..3fc5244 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/capturemanager.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/capturemanager.rs @@ -7,8 +7,6 @@ use super::*; -use objc_foundation::{INSString, NSString}; - pub enum MTLCaptureScope {} foreign_obj_type! { @@ -20,20 +18,20 @@ foreign_obj_type! { impl CaptureScopeRef { pub fn begin_scope(&self) { unsafe { - msg_send![self, beginScope]; + msg_send![self, beginScope] } } pub fn end_scope(&self) { unsafe { - msg_send![self, endScope]; + msg_send![self, endScope] } } pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } } @@ -56,14 +54,14 @@ impl CaptureManager { } impl CaptureManagerRef { - pub fn new_capture_scope_with_device(&self, device: &DeviceRef) -> &CaptureScopeRef { + pub fn new_capture_scope_with_device(&self, device: &DeviceRef) -> CaptureScope { unsafe { msg_send![self, newCaptureScopeWithDevice: device] } } pub fn new_capture_scope_with_command_queue( &self, command_queue: &CommandQueueRef, - ) -> &CaptureScopeRef { + ) -> CaptureScope { unsafe { msg_send![self, newCaptureScopeWithCommandQueue: command_queue] } } @@ -72,30 +70,30 @@ impl CaptureManagerRef { } pub fn set_default_capture_scope(&self, scope: &CaptureScopeRef) { - unsafe { msg_send![self, setDefaultCaptureScope:scope] } + unsafe { msg_send![self, setDefaultCaptureScope: scope] } } pub fn start_capture_with_device(&self, device: &DeviceRef) { unsafe { - msg_send![self, startCaptureWithDevice: device]; + msg_send![self, startCaptureWithDevice: device] } } pub fn start_capture_with_command_queue(&self, command_queue: &CommandQueueRef) { unsafe { - msg_send![self, startCaptureWithCommandQueue: command_queue]; + msg_send![self, startCaptureWithCommandQueue: command_queue] } } pub fn start_capture_with_scope(&self, scope: &CaptureScopeRef) { unsafe { - msg_send![self, startCaptureWithScope: scope]; + msg_send![self, startCaptureWithScope: scope] } } pub fn stop_capture(&self) { unsafe { - msg_send![self, stopCapture]; + msg_send![self, stopCapture] } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/commandbuffer.rs b/third_party/cargo/vendor/metal-0.17.1/src/commandbuffer.rs similarity index 54% rename from third_party/cargo/vendor/metal-0.13.1/src/commandbuffer.rs rename to third_party/cargo/vendor/metal-0.17.1/src/commandbuffer.rs index c933f04..ca278f3 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/commandbuffer.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/commandbuffer.rs @@ -7,7 +7,6 @@ use super::*; -use objc_foundation::{NSString, INSString}; use block::Block; #[repr(u32)] @@ -36,6 +35,13 @@ pub enum MTLCommandBufferError { DeviceRemoved = 11, } +#[repr(u32)] +#[allow(non_camel_case_types)] +pub enum MTLDispatchType { + Serial = 0, + Concurrent = 1, +} + type _MTLCommandBufferHandler = Block<(MTLCommandBuffer), ()>; pub enum MTLCommandBuffer {} @@ -49,75 +55,68 @@ foreign_obj_type! { impl CommandBufferRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel]; + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn enqueue(&self) { - unsafe { - msg_send![self, enqueue] - } + unsafe { msg_send![self, enqueue] } } pub fn commit(&self) { - unsafe { - msg_send![self, commit] - } + unsafe { msg_send![self, commit] } } pub fn status(&self) -> MTLCommandBufferStatus { - unsafe { - msg_send![self, status] - } + unsafe { msg_send![self, status] } } pub fn present_drawable(&self, drawable: &DrawableRef) { - unsafe { - msg_send![self, presentDrawable:drawable] - } + unsafe { msg_send![self, presentDrawable: drawable] } } pub fn wait_until_completed(&self) { - unsafe { - msg_send![self, waitUntilCompleted] - } + unsafe { msg_send![self, waitUntilCompleted] } } pub fn wait_until_scheduled(&self) { - unsafe { - msg_send![self, waitUntilScheduled] - } + unsafe { msg_send![self, waitUntilScheduled] } } pub fn new_blit_command_encoder(&self) -> &BlitCommandEncoderRef { - unsafe { - msg_send![self, blitCommandEncoder] - } + unsafe { msg_send![self, blitCommandEncoder] } } pub fn new_compute_command_encoder(&self) -> &ComputeCommandEncoderRef { - unsafe { - msg_send![self, computeCommandEncoder] - } + unsafe { msg_send![self, computeCommandEncoder] } } - pub fn new_render_command_encoder(&self, descriptor: &RenderPassDescriptorRef) -> &RenderCommandEncoderRef { - unsafe { - msg_send![self, renderCommandEncoderWithDescriptor:descriptor] - } + pub fn new_render_command_encoder( + &self, + descriptor: &RenderPassDescriptorRef, + ) -> &RenderCommandEncoderRef { + unsafe { msg_send![self, renderCommandEncoderWithDescriptor: descriptor] } } - pub fn new_parallel_render_command_encoder(&self, descriptor: &RenderPassDescriptorRef) -> &ParallelRenderCommandEncoderRef { - unsafe { - msg_send![self, parallelRenderCommandEncoderWithDescriptor:descriptor] - } + pub fn new_parallel_render_command_encoder( + &self, + descriptor: &RenderPassDescriptorRef, + ) -> &ParallelRenderCommandEncoderRef { + unsafe { msg_send![self, parallelRenderCommandEncoderWithDescriptor: descriptor] } + } + + pub fn compute_command_encoder_with_dispatch_type( + &self, + ty: MTLDispatchType, + ) -> &ComputeCommandEncoderRef { + unsafe { msg_send![self, computeCommandEncoderWithDispatchType: ty] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/commandqueue.rs b/third_party/cargo/vendor/metal-0.17.1/src/commandqueue.rs similarity index 65% rename from third_party/cargo/vendor/metal-0.13.1/src/commandqueue.rs rename to third_party/cargo/vendor/metal-0.17.1/src/commandqueue.rs index 1dd7c24..470d8db 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/commandqueue.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/commandqueue.rs @@ -7,8 +7,6 @@ use super::*; -use objc_foundation::{NSString, INSString}; - pub enum MTLCommandQueue {} foreign_obj_type! { @@ -20,33 +18,27 @@ foreign_obj_type! { impl CommandQueueRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn new_command_buffer(&self) -> &CommandBufferRef { - unsafe { - msg_send![self, commandBuffer] - } + unsafe { msg_send![self, commandBuffer] } } pub fn new_command_buffer_with_unretained_references(&self) -> &CommandBufferRef { - unsafe { - msg_send![self, commandBufferWithUnretainedReferences] - } + unsafe { msg_send![self, commandBufferWithUnretainedReferences] } } pub fn device(&self) -> &DeviceRef { - unsafe { - msg_send![self, device] - } + unsafe { msg_send![self, device] } } } diff --git a/third_party/cargo/vendor/metal-0.17.1/src/constants.rs b/third_party/cargo/vendor/metal-0.17.1/src/constants.rs new file mode 100644 index 0000000..b6765a0 --- /dev/null +++ b/third_party/cargo/vendor/metal-0.17.1/src/constants.rs @@ -0,0 +1,137 @@ +// Copyright 2016 GFX developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +#[repr(u64)] +#[allow(non_camel_case_types)] +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum MTLPixelFormat { + Invalid = 0, + A8Unorm = 1, + R8Unorm = 10, + R8Unorm_sRGB = 11, + R8Snorm = 12, + R8Uint = 13, + R8Sint = 14, + R16Unorm = 20, + R16Snorm = 22, + R16Uint = 23, + R16Sint = 24, + R16Float = 25, + RG8Unorm = 30, + RG8Unorm_sRGB = 31, + RG8Snorm = 32, + RG8Uint = 33, + RG8Sint = 34, + B5G6R5Unorm = 40, + A1BGR5Unorm = 41, + ABGR4Unorm = 42, + BGR5A1Unorm = 43, + R32Uint = 53, + R32Sint = 54, + R32Float = 55, + RG16Unorm = 60, + RG16Snorm = 62, + RG16Uint = 63, + RG16Sint = 64, + RG16Float = 65, + RGBA8Unorm = 70, + RGBA8Unorm_sRGB = 71, + RGBA8Snorm = 72, + RGBA8Uint = 73, + RGBA8Sint = 74, + BGRA8Unorm = 80, + BGRA8Unorm_sRGB = 81, + RGB10A2Unorm = 90, + RGB10A2Uint = 91, + RG11B10Float = 92, + RGB9E5Float = 93, + BGR10A2Unorm = 94, + RG32Uint = 103, + RG32Sint = 104, + RG32Float = 105, + RGBA16Unorm = 110, + RGBA16Snorm = 112, + RGBA16Uint = 113, + RGBA16Sint = 114, + RGBA16Float = 115, + RGBA32Uint = 123, + RGBA32Sint = 124, + RGBA32Float = 125, + BC1_RGBA = 130, + BC1_RGBA_sRGB = 131, + BC2_RGBA = 132, + BC2_RGBA_sRGB = 133, + BC3_RGBA = 134, + BC3_RGBA_sRGB = 135, + BC4_RUnorm = 140, + BC4_RSnorm = 141, + BC5_RGUnorm = 142, + BC5_RGSnorm = 143, + BC6H_RGBFloat = 150, + BC6H_RGBUfloat = 151, + BC7_RGBAUnorm = 152, + BC7_RGBAUnorm_sRGB = 153, + PVRTC_RGB_2BPP = 160, + PVRTC_RGB_2BPP_sRGB = 161, + PVRTC_RGB_4BPP = 162, + PVRTC_RGB_4BPP_sRGB = 163, + PVRTC_RGBA_2BPP = 164, + PVRTC_RGBA_2BPP_sRGB = 165, + PVRTC_RGBA_4BPP = 166, + PVRTC_RGBA_4BPP_sRGB = 167, + EAC_R11Unorm = 170, + EAC_R11Snorm = 172, + EAC_RG11Unorm = 174, + EAC_RG11Snorm = 176, + EAC_RGBA8 = 178, + EAC_RGBA8_sRGB = 179, + ETC2_RGB8 = 180, + ETC2_RGB8_sRGB = 181, + ETC2_RGB8A1 = 182, + ETC2_RGB8A1_sRGB = 183, + ASTC_4x4_sRGB = 186, + ASTC_5x4_sRGB = 187, + ASTC_5x5_sRGB = 188, + ASTC_6x5_sRGB = 189, + ASTC_6x6_sRGB = 190, + ASTC_8x5_sRGB = 192, + ASTC_8x6_sRGB = 193, + ASTC_8x8_sRGB = 194, + ASTC_10x5_sRGB = 195, + ASTC_10x6_sRGB = 196, + ASTC_10x8_sRGB = 197, + ASTC_10x10_sRGB = 198, + ASTC_12x10_sRGB = 199, + ASTC_12x12_sRGB = 200, + ASTC_4x4_LDR = 204, + ASTC_5x4_LDR = 205, + ASTC_5x5_LDR = 206, + ASTC_6x5_LDR = 207, + ASTC_6x6_LDR = 208, + ASTC_8x5_LDR = 210, + ASTC_8x6_LDR = 211, + ASTC_8x8_LDR = 212, + ASTC_10x5_LDR = 213, + ASTC_10x6_LDR = 214, + ASTC_10x8_LDR = 215, + ASTC_10x10_LDR = 216, + ASTC_12x10_LDR = 217, + ASTC_12x12_LDR = 218, + GBGR422 = 240, + BGRG422 = 241, + Depth16Unorm = 250, + Depth32Float = 252, + Stencil8 = 253, + Depth24Unorm_Stencil8 = 255, + Depth32Float_Stencil8 = 260, + X32_Stencil8 = 261, + X24_Stencil8 = 262, + BGRA10_XR = 552, + BGRA10_XR_SRGB = 553, + BGR10_XR = 554, + BGR10_XR_SRGB = 555, +} diff --git a/third_party/cargo/vendor/metal-0.13.1/src/depthstencil.rs b/third_party/cargo/vendor/metal-0.17.1/src/depthstencil.rs similarity index 67% rename from third_party/cargo/vendor/metal-0.13.1/src/depthstencil.rs rename to third_party/cargo/vendor/metal-0.17.1/src/depthstencil.rs index 42144b8..7f2fabf 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/depthstencil.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/depthstencil.rs @@ -5,7 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use objc::runtime::{YES, NO}; +use objc::runtime::{NO, YES}; #[repr(u64)] pub enum MTLCompareFunction { @@ -50,75 +50,51 @@ impl StencilDescriptor { impl StencilDescriptorRef { pub fn stencil_compare_function(&self) -> MTLCompareFunction { - unsafe { - msg_send![self, stencilCompareFunction] - } + unsafe { msg_send![self, stencilCompareFunction] } } pub fn set_stencil_compare_function(&self, func: MTLCompareFunction) { - unsafe { - msg_send![self, setStencilCompareFunction:func] - } + unsafe { msg_send![self, setStencilCompareFunction: func] } } pub fn stencil_failure_operation(&self) -> MTLStencilOperation { - unsafe { - msg_send![self, stencilFailureOperation] - } + unsafe { msg_send![self, stencilFailureOperation] } } pub fn set_stencil_failure_operation(&self, operation: MTLStencilOperation) { - unsafe { - msg_send![self, setStencilFailureOperation:operation] - } + unsafe { msg_send![self, setStencilFailureOperation: operation] } } pub fn depth_failure_operation(&self) -> MTLStencilOperation { - unsafe { - msg_send![self, depthFailureOperation] - } + unsafe { msg_send![self, depthFailureOperation] } } pub fn set_depth_failure_operation(&self, operation: MTLStencilOperation) { - unsafe { - msg_send![self, setDepthFailureOperation:operation] - } + unsafe { msg_send![self, setDepthFailureOperation: operation] } } pub fn depth_stencil_pass_operation(&self) -> MTLStencilOperation { - unsafe { - msg_send![self, depthStencilPassOperation] - } + unsafe { msg_send![self, depthStencilPassOperation] } } pub fn set_depth_stencil_pass_operation(&self, operation: MTLStencilOperation) { - unsafe { - msg_send![self, setDepthStencilPassOperation:operation] - } + unsafe { msg_send![self, setDepthStencilPassOperation: operation] } } pub fn read_mask(&self) -> u32 { - unsafe { - msg_send![self, readMask] - } + unsafe { msg_send![self, readMask] } } pub fn set_read_mask(&self, mask: u32) { - unsafe { - msg_send![self, setReadMask:mask] - } + unsafe { msg_send![self, setReadMask: mask] } } pub fn write_mask(&self) -> u32 { - unsafe { - msg_send![self, writeMask] - } + unsafe { msg_send![self, writeMask] } } pub fn set_write_mask(&self, mask: u32) { - unsafe { - msg_send![self, setWriteMask:mask] - } + unsafe { msg_send![self, setWriteMask: mask] } } } @@ -130,7 +106,6 @@ foreign_obj_type! { pub struct DepthStencilDescriptorRef; } - impl DepthStencilDescriptor { pub fn new() -> Self { unsafe { @@ -142,15 +117,11 @@ impl DepthStencilDescriptor { impl DepthStencilDescriptorRef { pub fn depth_compare_function(&self) -> MTLCompareFunction { - unsafe { - msg_send![self, depthCompareFunction] - } + unsafe { msg_send![self, depthCompareFunction] } } pub fn set_depth_compare_function(&self, func: MTLCompareFunction) { - unsafe { - msg_send![self, setDepthCompareFunction:func] - } + unsafe { msg_send![self, setDepthCompareFunction: func] } } pub fn depth_write_enabled(&self) -> bool { @@ -158,39 +129,29 @@ impl DepthStencilDescriptorRef { match msg_send![self, isDepthWriteEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_depth_write_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setDepthWriteEnabled:enabled] - } + unsafe { msg_send![self, setDepthWriteEnabled: enabled] } } pub fn front_face_stencil(&self) -> Option<&StencilDescriptorRef> { - unsafe { - msg_send![self, frontFaceStencil] - } + unsafe { msg_send![self, frontFaceStencil] } } pub fn set_front_face_stencil(&self, descriptor: Option<&StencilDescriptorRef>) { - unsafe { - msg_send![self, setFrontFaceStencil:descriptor] - } + unsafe { msg_send![self, setFrontFaceStencil: descriptor] } } pub fn back_face_stencil(&self) -> Option<&StencilDescriptorRef> { - unsafe { - msg_send![self, backFaceStencil] - } + unsafe { msg_send![self, backFaceStencil] } } pub fn set_back_face_stencil(&self, descriptor: Option<&StencilDescriptorRef>) { - unsafe { - msg_send![self, setBackFaceStencil:descriptor] - } + unsafe { msg_send![self, setBackFaceStencil: descriptor] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/device.rs b/third_party/cargo/vendor/metal-0.17.1/src/device.rs similarity index 77% rename from third_party/cargo/vendor/metal-0.13.1/src/device.rs rename to third_party/cargo/vendor/metal-0.17.1/src/device.rs index ea4a426..686747f 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/device.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/device.rs @@ -7,11 +7,9 @@ use block::{Block, ConcreteBlock}; use cocoa::base::id; -use cocoa::foundation::{NSUInteger}; +use cocoa::foundation::NSUInteger; use foreign_types::ForeignType; -use libc; -use objc::runtime::{Object, BOOL, YES, NO}; -use objc_foundation::{NSString, INSString}; +use objc::runtime::{Object, BOOL, NO, YES}; use super::*; @@ -19,7 +17,6 @@ use std::ffi::CStr; use std::path::Path; use std::ptr; - #[allow(non_camel_case_types)] #[repr(u64)] #[derive(Copy, Clone, Debug)] @@ -36,24 +33,25 @@ pub enum MTLFeatureSet { iOS_GPUFamily2_v4 = 9, iOS_GPUFamily3_v3 = 10, iOS_GPUFamily4_v1 = 11, - // iOS_GPUFamily1_v5 = 12, TODO: Uncomment when feature tables updated - // iOS_GPUFamily2_v5 = 13, - // iOS_GPUFamily3_v4 = 14, - // iOS_GPUFamily4_v2 = 15, - + iOS_GPUFamily1_v5 = 12, + iOS_GPUFamily2_v5 = 13, + iOS_GPUFamily3_v4 = 14, + iOS_GPUFamily4_v2 = 15, + iOS_GPUFamily5_v1 = 16, + tvOS_GPUFamily1_v1 = 30000, tvOS_GPUFamily1_v2 = 30001, tvOS_GPUFamily1_v3 = 30002, tvOS_GPUFamily2_v1 = 30003, - // tvOS_GPUFamily1_v4 = 30004, - // tvOS_GPUFamily2_v2 = 30005, + tvOS_GPUFamily1_v4 = 30004, + tvOS_GPUFamily2_v2 = 30005, macOS_GPUFamily1_v1 = 10000, macOS_GPUFamily1_v2 = 10001, //macOS_ReadWriteTextureTier2 = 10002, TODO: Uncomment when feature tables updated macOS_GPUFamily1_v3 = 10003, - //macOS_GPUFamily1_v4 = 10004, - //macOS_GPUFamily2_v1 = 10005, + macOS_GPUFamily1_v4 = 10004, + macOS_GPUFamily2_v1 = 10005, } bitflags! { @@ -70,7 +68,9 @@ bitflags! { #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum OS { - iOS, tvOS, macOS + iOS, + tvOS, + macOS, } const KB: u32 = 1024; @@ -91,6 +91,7 @@ impl MTLFeatureSet { } } + // returns the minor version on macos fn os_version(&self) -> u32 { use MTLFeatureSet::*; match self { @@ -98,60 +99,49 @@ impl MTLFeatureSet { iOS_GPUFamily1_v2 | iOS_GPUFamily2_v2 | iOS_GPUFamily3_v1 => 9, iOS_GPUFamily1_v3 | iOS_GPUFamily2_v3 | iOS_GPUFamily3_v2 => 10, iOS_GPUFamily1_v4 | iOS_GPUFamily2_v4 | iOS_GPUFamily3_v3 | iOS_GPUFamily4_v1 => 11, + iOS_GPUFamily1_v5 | iOS_GPUFamily2_v5 | iOS_GPUFamily3_v4 | iOS_GPUFamily4_v2 + | iOS_GPUFamily5_v1 => 12, tvOS_GPUFamily1_v1 => 9, tvOS_GPUFamily1_v2 => 10, tvOS_GPUFamily1_v3 | tvOS_GPUFamily2_v1 => 11, - macOS_GPUFamily1_v1 | macOS_GPUFamily1_v2 | macOS_GPUFamily1_v3 => 10, + tvOS_GPUFamily1_v4 | tvOS_GPUFamily2_v2 => 12, + macOS_GPUFamily1_v1 => 11, + macOS_GPUFamily1_v2 => 12, + macOS_GPUFamily1_v3 => 13, + macOS_GPUFamily1_v4 | macOS_GPUFamily2_v1 => 14, } } fn gpu_family(&self) -> u32 { use MTLFeatureSet::*; match self { - iOS_GPUFamily1_v1 - | iOS_GPUFamily1_v2 - | iOS_GPUFamily1_v3 - | iOS_GPUFamily1_v4 - | tvOS_GPUFamily1_v1 - | tvOS_GPUFamily1_v2 - | tvOS_GPUFamily1_v3 - | macOS_GPUFamily1_v1 - | macOS_GPUFamily1_v2 - | macOS_GPUFamily1_v3 => 1, - iOS_GPUFamily2_v1 - | iOS_GPUFamily2_v2 - | iOS_GPUFamily2_v3 - | iOS_GPUFamily2_v4 - | tvOS_GPUFamily2_v1 => 2, - iOS_GPUFamily3_v1 - | iOS_GPUFamily3_v2 - | iOS_GPUFamily3_v3 => 3, - iOS_GPUFamily4_v1 => 4, + iOS_GPUFamily1_v1 | iOS_GPUFamily1_v2 | iOS_GPUFamily1_v3 | iOS_GPUFamily1_v4 + | iOS_GPUFamily1_v5 | tvOS_GPUFamily1_v1 | tvOS_GPUFamily1_v2 | tvOS_GPUFamily1_v3 + | tvOS_GPUFamily1_v4 | macOS_GPUFamily1_v1 | macOS_GPUFamily1_v2 + | macOS_GPUFamily1_v3 | macOS_GPUFamily1_v4 => 1, + iOS_GPUFamily2_v1 | iOS_GPUFamily2_v2 | iOS_GPUFamily2_v3 | iOS_GPUFamily2_v4 + | iOS_GPUFamily2_v5 | tvOS_GPUFamily2_v1 | tvOS_GPUFamily2_v2 | macOS_GPUFamily2_v1 => { + 2 + } + iOS_GPUFamily3_v1 | iOS_GPUFamily3_v2 | iOS_GPUFamily3_v3 | iOS_GPUFamily3_v4 => 3, + iOS_GPUFamily4_v1 | iOS_GPUFamily4_v2 => 4, + iOS_GPUFamily5_v1 => 5, } } fn version(&self) -> u32 { use MTLFeatureSet::*; match self { - iOS_GPUFamily1_v1 - | iOS_GPUFamily2_v1 - | iOS_GPUFamily3_v1 - | iOS_GPUFamily4_v1 - | macOS_GPUFamily1_v1 - | tvOS_GPUFamily1_v1 - | tvOS_GPUFamily2_v1 => 1, - iOS_GPUFamily1_v2 - | iOS_GPUFamily2_v2 - | iOS_GPUFamily3_v2 - | macOS_GPUFamily1_v2 - | tvOS_GPUFamily1_v2 => 2, - iOS_GPUFamily1_v3 - | iOS_GPUFamily2_v3 - | iOS_GPUFamily3_v3 - | macOS_GPUFamily1_v3 + iOS_GPUFamily1_v1 | iOS_GPUFamily2_v1 | iOS_GPUFamily3_v1 | iOS_GPUFamily4_v1 + | iOS_GPUFamily5_v1 | macOS_GPUFamily1_v1 | macOS_GPUFamily2_v1 + | tvOS_GPUFamily1_v1 | tvOS_GPUFamily2_v1 => 1, + iOS_GPUFamily1_v2 | iOS_GPUFamily2_v2 | iOS_GPUFamily3_v2 | iOS_GPUFamily4_v2 + | macOS_GPUFamily1_v2 | tvOS_GPUFamily1_v2 | tvOS_GPUFamily2_v2 => 2, + iOS_GPUFamily1_v3 | iOS_GPUFamily2_v3 | iOS_GPUFamily3_v3 | macOS_GPUFamily1_v3 | tvOS_GPUFamily1_v3 => 3, - iOS_GPUFamily1_v4 - | iOS_GPUFamily2_v4 => 4, + iOS_GPUFamily1_v4 | iOS_GPUFamily2_v4 | iOS_GPUFamily3_v4 | tvOS_GPUFamily1_v4 + | macOS_GPUFamily1_v4 => 4, + iOS_GPUFamily1_v5 | iOS_GPUFamily2_v5 => 5, } } @@ -163,7 +153,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 2, OS::tvOS => true, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -188,7 +178,7 @@ impl MTLFeatureSet { } pub fn supports_linear_textures(&self) -> bool { - self.os() != OS::macOS || self.version() >= 3 + self.os() != OS::macOS || self.os_version() >= 13 } pub fn supports_bc_pixel_formats(&self) -> bool { @@ -240,14 +230,18 @@ impl MTLFeatureSet { } pub fn supports_layered_rendering(&self) -> bool { - self.os() == OS::macOS + match self.os() { + OS::iOS => self.gpu_family() >= 5, + OS::tvOS => false, + OS::macOS => true, + } } pub fn supports_tessellation(&self) -> bool { match self.os() { OS::iOS => self.gpu_family() >= 3 && self.os_version() >= 10, OS::tvOS => self.gpu_family() >= 2, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -255,7 +249,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -271,7 +265,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -279,7 +273,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 3 && self.os_version() >= 10, OS::tvOS => self.gpu_family() >= 2, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -287,7 +281,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 4, OS::tvOS => false, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -295,7 +289,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 3 && self.os_version() >= 10, OS::tvOS => self.gpu_family() >= 2, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -303,7 +297,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 3 && self.os_version() >= 11, OS::tvOS => self.gpu_family() >= 2, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -311,12 +305,12 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } pub fn supports_depth_16_pixel_format(&self) -> bool { - self.os() == OS::macOS && self.version() >= 2 + self.os() == OS::macOS && self.os_version() >= 12 } pub fn supports_extended_range_pixel_formats(&self) -> bool { @@ -331,7 +325,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 11, OS::tvOS => self.os_version() >= 11, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -339,7 +333,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 3 && self.os_version() >= 10, OS::tvOS => self.gpu_family() >= 2, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -347,7 +341,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -363,7 +357,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 3 || (self.gpu_family() >= 2 && self.version() >= 3), OS::tvOS => self.os_version() >= 10, - OS::macOS => false, + OS::macOS => self.gpu_family() >= 2, } } @@ -371,7 +365,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -379,7 +373,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -387,7 +381,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => false, + OS::macOS => self.os_version() >= 13, } } @@ -395,7 +389,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => false, + OS::macOS => self.os_version() >= 13, } } @@ -403,19 +397,19 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 10, OS::tvOS => self.os_version() >= 10, - OS::macOS => false, + OS::macOS => self.os_version() >= 13, } } pub fn supports_border_color(&self) -> bool { - self.os() == OS::macOS && self.version() >= 2 + self.os() == OS::macOS && self.os_version() >= 12 } pub fn supports_dual_source_blending(&self) -> bool { match self.os() { OS::iOS => self.os_version() >= 11, OS::tvOS => self.os_version() >= 11, - OS::macOS => self.version() >= 2, + OS::macOS => self.os_version() >= 12, } } @@ -423,7 +417,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 11, OS::tvOS => self.os_version() >= 11, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -431,7 +425,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 11, OS::tvOS => self.os_version() >= 11, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -439,7 +433,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.os_version() >= 11, OS::tvOS => self.os_version() >= 11, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -464,14 +458,18 @@ impl MTLFeatureSet { } pub fn supports_quad_scoped_permute_operations(&self) -> bool { - self.os() == OS::iOS && self.gpu_family() >= 4 + match self.os() { + OS::iOS => self.gpu_family() >= 4, + OS::tvOS => false, + OS::macOS => self.os_version() >= 13, + } } pub fn supports_raster_order_groups(&self) -> bool { match self.os() { OS::iOS => self.gpu_family() >= 4, OS::tvOS => false, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } @@ -479,16 +477,36 @@ impl MTLFeatureSet { match self.os() { OS::iOS => self.gpu_family() >= 4, OS::tvOS => false, - OS::macOS => self.version() >= 3, + OS::macOS => self.os_version() >= 13, } } pub fn supports_multiple_viewports(&self) -> bool { - self.os() == OS::macOS && self.version() >= 3 + match self.os() { + OS::iOS => self.gpu_family() >= 5, + OS::tvOS => false, + OS::macOS => self.os_version() >= 13, + } } pub fn supports_device_notifications(&self) -> bool { - self.os() == OS::macOS && self.version() >= 3 + self.os() == OS::macOS && self.os_version() >= 13 + } + + pub fn supports_stencil_feedback(&self) -> bool { + match self.os() { + OS::iOS => self.gpu_family() >= 5, + OS::tvOS => false, + OS::macOS => self.gpu_family() >= 2, + } + } + + pub fn supports_stencil_resolve(&self) -> bool { + match self.os() { + OS::iOS => self.gpu_family() >= 5, + OS::tvOS => false, + OS::macOS => self.gpu_family() >= 2, + } } pub fn max_vertex_attributes(&self) -> u32 { @@ -528,7 +546,7 @@ impl MTLFeatureSet { } pub fn max_threads_per_threadgroup(&self) -> u32 { - if self.os() == OS::macOS || self.gpu_family() == 4 { + if self.os() == OS::macOS || self.gpu_family() >= 4 { 1024 } else { 512 @@ -537,7 +555,14 @@ impl MTLFeatureSet { pub fn max_total_threadgroup_memory_allocation(&self) -> u32 { match (self.os(), self.gpu_family()) { - (OS::iOS, 4) => 32 * KB, + (OS::iOS, 5) => 64 * KB, + (OS::iOS, 4) => { + if self.os_version() >= 12 { + 64 * KB + } else { + 32 * KB + } + } (OS::iOS, 3) => 16 * KB, (OS::iOS, _) => 16 * KB - 32, (OS::tvOS, 1) => 16 * KB - 32, @@ -586,7 +611,7 @@ impl MTLFeatureSet { match self.os() { OS::iOS if self.os_version() >= 11 => 65536, OS::tvOS if self.os_version() >= 10 => 65536, - OS::macOS if self.version() >= 2 => 65536, + OS::macOS if self.os_version() >= 12 => 65536, _ => 0, } } @@ -594,6 +619,7 @@ impl MTLFeatureSet { pub fn max_tessellation_factor(&self) -> u32 { if self.supports_tessellation() { match self.os() { + OS::iOS if self.gpu_family() >= 5 => 64, OS::iOS => 16, OS::tvOS => 16, OS::macOS => 64, @@ -620,7 +646,7 @@ impl MTLFeatureSet { } pub fn max_buffer_length(&self) -> u32 { - if self.os() == OS::macOS && self.version() >= 2 { + if self.os() == OS::macOS && self.os_version() >= 12 { 1 * GB } else { 256 * MB @@ -637,7 +663,13 @@ impl MTLFeatureSet { pub fn max_1d_texture_size(&self) -> u32 { match (self.os(), self.gpu_family()) { - (OS::iOS, 1) | (OS::iOS, 2) => if self.version() <= 2 { 4096 } else { 8192 }, + (OS::iOS, 1) | (OS::iOS, 2) => { + if self.version() <= 2 { + 4096 + } else { + 8192 + } + } (OS::tvOS, 1) => 8192, _ => 16384, } @@ -645,7 +677,13 @@ impl MTLFeatureSet { pub fn max_2d_texture_size(&self) -> u32 { match (self.os(), self.gpu_family()) { - (OS::iOS, 1) | (OS::iOS, 2) => if self.version() <= 2 { 4096 } else { 8192 }, + (OS::iOS, 1) | (OS::iOS, 2) => { + if self.version() <= 2 { + 4096 + } else { + 8192 + } + } (OS::tvOS, 1) => 8192, _ => 16384, } @@ -653,7 +691,13 @@ impl MTLFeatureSet { pub fn max_cube_map_texture_size(&self) -> u32 { match (self.os(), self.gpu_family()) { - (OS::iOS, 1) | (OS::iOS, 2) => if self.version() <= 2 { 4096 } else { 8192 }, + (OS::iOS, 1) | (OS::iOS, 2) => { + if self.version() <= 2 { + 4096 + } else { + 8192 + } + } (OS::tvOS, 1) => 8192, _ => 16384, } @@ -679,18 +723,22 @@ impl MTLFeatureSet { /// the buffer alignment can be discovered via API query pub fn new_texture_buffer_alignment(&self) -> Option { match self.os() { - OS::iOS => if self.os_version() >= 11 { - None - } else if self.gpu_family() == 3 { - Some(16) - } else { - Some(64) - }, - OS::tvOS => if self.os_version() >= 11 { - None - } else { - Some(64) - }, + OS::iOS => { + if self.os_version() >= 11 { + None + } else if self.gpu_family() == 3 { + Some(16) + } else { + Some(64) + } + } + OS::tvOS => { + if self.os_version() >= 11 { + None + } else { + Some(64) + } + } OS::macOS => None, } } @@ -1293,8 +1341,9 @@ bitflags! { } #[link(name = "Metal", kind = "framework")] -extern { +extern "C" { fn MTLCreateSystemDefaultDevice() -> *mut MTLDevice; + #[cfg(not(target_os = "ios"))] fn MTLCopyAllDevices() -> *mut Object; //TODO: Array } @@ -1305,20 +1354,25 @@ type dispatch_queue_t = id; #[allow(non_camel_case_types)] type dispatch_block_t = *const Block<(), ()>; -#[cfg_attr(any(target_os = "macos", target_os = "ios"), - link(name = "System", kind = "dylib"))] -#[cfg_attr(not(any(target_os = "macos", target_os = "ios")), - link(name = "dispatch", kind = "dylib"))] +#[cfg_attr( + any(target_os = "macos", target_os = "ios"), + link(name = "System", kind = "dylib") +)] +#[cfg_attr( + not(any(target_os = "macos", target_os = "ios")), + link(name = "dispatch", kind = "dylib") +)] #[allow(improper_ctypes)] -extern { +extern "C" { static _dispatch_main_q: dispatch_queue_t; fn dispatch_data_create( - buffer: *const libc::c_void, - size: libc::size_t, + buffer: *const std::ffi::c_void, + size: crate::c_size_t, queue: dispatch_queue_t, - destructor: dispatch_block_t + destructor: dispatch_block_t, ) -> dispatch_data_t; + fn dispatch_release(object: dispatch_data_t); // actually dispatch_object_t } /*type MTLNewLibraryCompletionHandler = extern fn(library: id, error: id); @@ -1336,21 +1390,29 @@ foreign_obj_type! { } impl Device { - pub fn system_default() -> Self { - unsafe { Device(MTLCreateSystemDefaultDevice()) } + pub fn system_default() -> Option { + // `MTLCreateSystemDefaultDevice` may return null if Metal is not supported + unsafe { MTLCreateSystemDefaultDevice().as_mut().map(|x| Self(x)) } } - pub fn all() -> Vec { - if cfg!(target_os = "ios") { - vec![Device::system_default()] - } else { - unsafe { - let array = MTLCopyAllDevices(); - let count: NSUInteger = msg_send![array, count]; - (0 .. count) - .map(|i| msg_send![array, objectAtIndex: i]) - .collect() - } + pub fn all() -> Vec { + #[cfg(target_os = "ios")] + { + Self::system_default().into_iter().collect() + } + #[cfg(not(target_os = "ios"))] + unsafe { + let array = MTLCopyAllDevices(); + let count: NSUInteger = msg_send![array, count]; + let ret = (0..count) + .map(|i| msg_send![array, objectAtIndex: i]) + // The elements of this array are references---we convert them to owned references + // (which just means that we increment the reference count here, and it is + // decremented in the `Drop` impl for `Device`) + .map(|device: *mut Object| msg_send![device, retain]) + .collect(); + let () = msg_send![array, release]; + ret } } } @@ -1358,33 +1420,29 @@ impl Device { impl DeviceRef { pub fn name(&self) -> &str { unsafe { - let name: &NSString = msg_send![self, name]; - name.as_str() + let name = msg_send![self, name]; + crate::nsstring_as_str(name) } } #[cfg(feature = "private")] pub unsafe fn vendor(&self) -> &str { - let name: &NSString = msg_send![self, vendorName]; - name.as_str() + let name = msg_send![self, vendorName]; + crate::nsstring_as_str(name) } #[cfg(feature = "private")] pub unsafe fn family_name(&self) -> &str { - let name: &NSString = msg_send![self, familyName]; - name.as_str() + let name = msg_send![self, familyName]; + crate::nsstring_as_str(name) } pub fn registry_id(&self) -> u64 { - unsafe { - msg_send![self, registryID] - } + unsafe { msg_send![self, registryID] } } pub fn max_threads_per_threadgroup(&self) -> MTLSize { - unsafe { - msg_send![self, maxThreadsPerThreadgroup] - } + unsafe { msg_send![self, maxThreadsPerThreadgroup] } } pub fn is_low_power(&self) -> bool { @@ -1392,7 +1450,7 @@ impl DeviceRef { match msg_send![self, isLowPower] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } @@ -1402,7 +1460,7 @@ impl DeviceRef { match msg_send![self, isHeadless] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } @@ -1412,27 +1470,27 @@ impl DeviceRef { match msg_send![self, isRemovable] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn supports_feature_set(&self, feature: MTLFeatureSet) -> bool { unsafe { - match msg_send![self, supportsFeatureSet:feature] { + match msg_send![self, supportsFeatureSet: feature] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn supports_sample_count(&self, count: NSUInteger) -> bool { unsafe { - match msg_send![self, supportsTextureSampleCount:count] { + match msg_send![self, supportsTextureSampleCount: count] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } @@ -1442,32 +1500,33 @@ impl DeviceRef { match msg_send![self, isDepth24Stencil8PixelFormatSupported] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn new_command_queue(&self) -> CommandQueue { - unsafe { - msg_send![self, newCommandQueue] - } + unsafe { msg_send![self, newCommandQueue] } } - pub fn new_command_queue_with_max_command_buffer_count(&self, count: NSUInteger) -> CommandQueue { - unsafe { - msg_send![self, newCommandQueueWithMaxCommandBufferCount:count] - } + pub fn new_command_queue_with_max_command_buffer_count( + &self, + count: NSUInteger, + ) -> CommandQueue { + unsafe { msg_send![self, newCommandQueueWithMaxCommandBufferCount: count] } } pub fn new_default_library(&self) -> Library { - unsafe { - msg_send![self, newDefaultLibrary] - } + unsafe { msg_send![self, newDefaultLibrary] } } - pub fn new_library_with_source(&self, src: &str, options: &CompileOptionsRef) -> Result { - use cocoa::foundation::NSString as cocoa_NSString; + pub fn new_library_with_source( + &self, + src: &str, + options: &CompileOptionsRef, + ) -> Result { use cocoa::base::nil as cocoa_nil; + use cocoa::foundation::NSString as cocoa_NSString; unsafe { let source = cocoa_NSString::alloc(cocoa_nil).init_str(src); @@ -1475,12 +1534,13 @@ impl DeviceRef { let library: *mut MTLLibrary = msg_send![self, newLibraryWithSource:source options:options error:&mut err]; + let () = msg_send![source, release]; if !err.is_null() { let desc: *mut Object = msg_send![err, localizedDescription]; - let compile_error: *const libc::c_char = msg_send![desc, UTF8String]; + let compile_error: *const std::os::raw::c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); if library.is_null() { - msg_send![err, release]; + let () = msg_send![err, release]; return Err(message); } else { warn!("Shader warnings: {}", message); @@ -1493,15 +1553,15 @@ impl DeviceRef { } pub fn new_library_with_file>(&self, file: P) -> Result { - use cocoa::foundation::NSString as cocoa_NSString; use cocoa::base::nil as cocoa_nil; + use cocoa::foundation::NSString as cocoa_NSString; unsafe { - let filename = cocoa_NSString::alloc(cocoa_nil) - .init_str(file.as_ref().to_string_lossy().as_ref()); + let filename = + cocoa_NSString::alloc(cocoa_nil).init_str(file.as_ref().to_string_lossy().as_ref()); - let library: *mut MTLLibrary = try_objc!{ err => - msg_send![self, newLibraryWithFile:filename + let library: *mut MTLLibrary = try_objc! { err => + msg_send![self, newLibraryWithFile:filename.as_ref() error:&mut err] }; @@ -1513,26 +1573,31 @@ impl DeviceRef { unsafe { let destructor_block = ConcreteBlock::new(|| {}).copy(); let data = dispatch_data_create( - library_data.as_ptr() as *const libc::c_void, - library_data.len() as libc::size_t, + library_data.as_ptr() as *const std::ffi::c_void, + library_data.len() as crate::c_size_t, &_dispatch_main_q as *const _ as dispatch_queue_t, - &*destructor_block.deref() + &*destructor_block.deref(), ); let library: *mut MTLLibrary = try_objc! { err => msg_send![self, newLibraryWithData:data error:&mut err] }; - + dispatch_release(data); Ok(Library::from_ptr(library)) } } - pub fn new_render_pipeline_state_with_reflection(&self, descriptor: &RenderPipelineDescriptorRef, reflection: &RenderPipelineReflectionRef) -> Result { + pub fn new_render_pipeline_state_with_reflection( + &self, + descriptor: &RenderPipelineDescriptorRef, + reflection: &RenderPipelineReflectionRef, + ) -> Result { unsafe { - let reflection_options = MTLPipelineOption::ArgumentInfo | MTLPipelineOption::BufferTypeInfo; + let reflection_options = + MTLPipelineOption::ArgumentInfo | MTLPipelineOption::BufferTypeInfo; - let pipeline_state: *mut MTLRenderPipelineState = try_objc!{ err => + let pipeline_state: *mut MTLRenderPipelineState = try_objc! { err => msg_send![self, newRenderPipelineStateWithDescriptor:descriptor options:reflection_options reflection:reflection @@ -1543,9 +1608,12 @@ impl DeviceRef { } } - pub fn new_render_pipeline_state(&self, descriptor: &RenderPipelineDescriptorRef) -> Result { + pub fn new_render_pipeline_state( + &self, + descriptor: &RenderPipelineDescriptorRef, + ) -> Result { unsafe { - let pipeline_state: *mut MTLRenderPipelineState = try_objc!{ err => + let pipeline_state: *mut MTLRenderPipelineState = try_objc! { err => msg_send![self, newRenderPipelineStateWithDescriptor:descriptor error:&mut err] }; @@ -1554,9 +1622,12 @@ impl DeviceRef { } } - pub fn new_compute_pipeline_state_with_function(&self, function: &FunctionRef) -> Result { + pub fn new_compute_pipeline_state_with_function( + &self, + function: &FunctionRef, + ) -> Result { unsafe { - let pipeline_state: *mut MTLComputePipelineState = try_objc!{ err => + let pipeline_state: *mut MTLComputePipelineState = try_objc! { err => msg_send![self, newComputePipelineStateWithFunction:function error:&mut err] }; @@ -1565,9 +1636,11 @@ impl DeviceRef { } } - #[cfg(feature = "private")] - pub unsafe fn new_compute_pipeline_state(&self, descriptor: &ComputePipelineDescriptorRef) -> Result { - let pipeline_state: *mut MTLComputePipelineState = try_objc!{ err => + pub unsafe fn new_compute_pipeline_state( + &self, + descriptor: &ComputePipelineDescriptorRef, + ) -> Result { + let pipeline_state: *mut MTLComputePipelineState = try_objc! { err => msg_send![self, newComputePipelineStateWithDescriptor:descriptor error:&mut err] }; @@ -1582,7 +1655,12 @@ impl DeviceRef { } } - pub fn new_buffer_with_data(&self, bytes: *const libc::c_void, length: NSUInteger, options: MTLResourceOptions) -> Buffer { + pub fn new_buffer_with_data( + &self, + bytes: *const std::ffi::c_void, + length: NSUInteger, + options: MTLResourceOptions, + ) -> Buffer { unsafe { msg_send![self, newBufferWithBytes:bytes length:length @@ -1591,26 +1669,24 @@ impl DeviceRef { } pub fn new_texture(&self, descriptor: &TextureDescriptorRef) -> Texture { - unsafe { - msg_send![self, newTextureWithDescriptor:descriptor] - } + unsafe { msg_send![self, newTextureWithDescriptor: descriptor] } } pub fn new_sampler(&self, descriptor: &SamplerDescriptorRef) -> SamplerState { - unsafe { - msg_send![self, newSamplerStateWithDescriptor:descriptor] - } + unsafe { msg_send![self, newSamplerStateWithDescriptor: descriptor] } } - pub fn new_depth_stencil_state(&self, descriptor: &DepthStencilDescriptorRef) -> DepthStencilState { - unsafe { - msg_send![self, newDepthStencilStateWithDescriptor:descriptor] - } + pub fn new_depth_stencil_state( + &self, + descriptor: &DepthStencilDescriptorRef, + ) -> DepthStencilState { + unsafe { msg_send![self, newDepthStencilStateWithDescriptor: descriptor] } } pub fn argument_buffers_support(&self) -> Option { unsafe { - let has_arg_buffers: BOOL = msg_send![self, respondsToSelector: sel!(argumentBuffersSupport)]; + let has_arg_buffers: BOOL = + msg_send![self, respondsToSelector: sel!(argumentBuffersSupport)]; if has_arg_buffers == YES { Some(msg_send![self, argumentBuffersSupport]) } else { @@ -1619,33 +1695,47 @@ impl DeviceRef { } } - pub fn new_argument_encoder(&self, arguments: &ArrayRef) -> ArgumentEncoder { - unsafe { - msg_send![self, newArgumentEncoderWithArguments:arguments] - } + pub fn new_argument_encoder( + &self, + arguments: &ArrayRef, + ) -> ArgumentEncoder { + unsafe { msg_send![self, newArgumentEncoderWithArguments: arguments] } } pub fn new_heap(&self, descriptor: &HeapDescriptorRef) -> Heap { - unsafe { - msg_send![self, newHeapWithDescriptor: descriptor] - } + unsafe { msg_send![self, newHeapWithDescriptor: descriptor] } } - pub fn heap_buffer_size_and_align(&self, length: NSUInteger, options: MTLResourceOptions) -> MTLSizeAndAlign { - unsafe { - msg_send![self, heapBufferSizeAndAlignWithLength: length options: options] - } + pub fn heap_buffer_size_and_align( + &self, + length: NSUInteger, + options: MTLResourceOptions, + ) -> MTLSizeAndAlign { + unsafe { msg_send![self, heapBufferSizeAndAlignWithLength: length options: options] } } - pub fn heap_texture_size_and_align(&self, descriptor: &TextureDescriptorRef) -> MTLSizeAndAlign { - unsafe { - msg_send![self, heapTextureSizeAndAlignWithDescriptor: descriptor] - } + pub fn heap_texture_size_and_align( + &self, + descriptor: &TextureDescriptorRef, + ) -> MTLSizeAndAlign { + unsafe { msg_send![self, heapTextureSizeAndAlignWithDescriptor: descriptor] } } - pub fn minimum_linear_texture_alignment_for_pixel_format(&self, format: MTLPixelFormat) -> NSUInteger { - unsafe { - msg_send![self, minimumLinearTextureAlignmentForPixelFormat: format] - } + pub fn minimum_linear_texture_alignment_for_pixel_format( + &self, + format: MTLPixelFormat, + ) -> NSUInteger { + unsafe { msg_send![self, minimumLinearTextureAlignmentForPixelFormat: format] } + } + + pub fn minimum_texture_buffer_alignment_for_pixel_format( + &self, + format: MTLPixelFormat, + ) -> NSUInteger { + unsafe { msg_send![self, minimumTextureBufferAlignmentForPixelFormat: format] } + } + + pub fn max_argument_buffer_sampler_count(&self) -> NSUInteger { + unsafe { msg_send![self, maxArgumentBufferSamplerCount] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/drawable.rs b/third_party/cargo/vendor/metal-0.17.1/src/drawable.rs similarity index 88% rename from third_party/cargo/vendor/metal-0.13.1/src/drawable.rs rename to third_party/cargo/vendor/metal-0.17.1/src/drawable.rs index eec1936..0e6d837 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/drawable.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/drawable.rs @@ -13,11 +13,8 @@ foreign_obj_type! { pub struct DrawableRef; } - impl DrawableRef { pub fn present(&self) { - unsafe { - msg_send![self, present] - } + unsafe { msg_send![self, present] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/encoder.rs b/third_party/cargo/vendor/metal-0.17.1/src/encoder.rs similarity index 72% rename from third_party/cargo/vendor/metal-0.13.1/src/encoder.rs rename to third_party/cargo/vendor/metal-0.17.1/src/encoder.rs index 5ed74da..e607629 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/encoder.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/encoder.rs @@ -7,13 +7,10 @@ use super::*; -use cocoa::foundation::{NSRange, NSUInteger, NSInteger}; -use objc_foundation::{NSString, INSString}; +use cocoa::foundation::{NSInteger, NSRange, NSUInteger}; -use libc; use std::ops::Range; - #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum MTLPrimitiveType { @@ -27,8 +24,8 @@ pub enum MTLPrimitiveType { #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum MTLIndexType { - UInt16 = 0, - UInt32 = 1, + UInt16 = 0, + UInt32 = 1, } #[repr(u64)] @@ -83,7 +80,7 @@ pub struct MTLScissorRect { pub x: NSUInteger, pub y: NSUInteger, pub width: NSUInteger, - pub height: NSUInteger + pub height: NSUInteger, } #[repr(C)] @@ -103,7 +100,7 @@ pub struct MTLDrawPrimitivesIndirectArguments { pub vertexCount: u32, pub instanceCount: u32, pub vertexStart: u32, - pub baseInstance: u32 + pub baseInstance: u32, } #[repr(C)] @@ -113,7 +110,7 @@ pub struct MTLDrawIndexedPrimitivesIndirectArguments { pub instanceCount: u32, pub indexStart: u32, pub baseVertex: i32, - pub baseInstance: u32 + pub baseInstance: u32, } pub enum MTLCommandEncoder {} @@ -127,21 +124,21 @@ foreign_obj_type! { impl CommandEncoderRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel]; + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn end_encoding(&self) { unsafe { - msg_send![self, endEncoding]; + msg_send![self, endEncoding] } } } @@ -155,12 +152,9 @@ foreign_obj_type! { type ParentType = CommandEncoderRef; } - impl ParallelRenderCommandEncoderRef { pub fn render_command_encoder(&self) -> &RenderCommandEncoderRef { - unsafe { - msg_send![self, renderCommandEncoder] - } + unsafe { msg_send![self, renderCommandEncoder] } } } @@ -175,33 +169,23 @@ foreign_obj_type! { impl RenderCommandEncoderRef { pub fn set_render_pipeline_state(&self, pipeline_state: &RenderPipelineStateRef) { - unsafe { - msg_send![self, setRenderPipelineState:pipeline_state] - } + unsafe { msg_send![self, setRenderPipelineState: pipeline_state] } } pub fn set_viewport(&self, viewport: MTLViewport) { - unsafe { - msg_send![self, setViewport:viewport] - } + unsafe { msg_send![self, setViewport: viewport] } } pub fn set_front_facing_winding(&self, winding: MTLWinding) { - unsafe { - msg_send![self, setFrontFacingWinding:winding] - } + unsafe { msg_send![self, setFrontFacingWinding: winding] } } pub fn set_cull_mode(&self, mode: MTLCullMode) { - unsafe { - msg_send![self, setCullMode:mode] - } + unsafe { msg_send![self, setCullMode: mode] } } pub fn set_depth_clip_mode(&self, mode: MTLDepthClipMode) { - unsafe { - msg_send![self, setDepthClipMode:mode] - } + unsafe { msg_send![self, setDepthClipMode: mode] } } pub fn set_depth_bias(&self, bias: f32, scale: f32, clamp: f32) { @@ -213,15 +197,11 @@ impl RenderCommandEncoderRef { } pub fn set_scissor_rect(&self, rect: MTLScissorRect) { - unsafe { - msg_send![self, setScissorRect:rect] - } + unsafe { msg_send![self, setScissorRect: rect] } } pub fn set_triangle_fill_mode(&self, mode: MTLTriangleFillMode) { - unsafe { - msg_send![self, setTriangleFillMode:mode] - } + unsafe { msg_send![self, setTriangleFillMode: mode] } } pub fn set_blend_color(&self, red: f32, green: f32, blue: f32, alpha: f32) { @@ -234,15 +214,11 @@ impl RenderCommandEncoderRef { } pub fn set_depth_stencil_state(&self, depth_stencil_state: &DepthStencilStateRef) { - unsafe { - msg_send![self, setDepthStencilState:depth_stencil_state] - } + unsafe { msg_send![self, setDepthStencilState: depth_stencil_state] } } pub fn set_stencil_reference_value(&self, value: u32) { - unsafe { - msg_send![self, setStencilReferenceValue:value] - } + unsafe { msg_send![self, setStencilReferenceValue: value] } } pub fn set_stencil_front_back_reference_value(&self, front: u32, back: u32) { @@ -252,8 +228,7 @@ impl RenderCommandEncoderRef { } } - //TODO: change argument order - pub fn set_visibility_result_mode(&self, offset: NSUInteger, mode: MTLVisibilityResultMode) { + pub fn set_visibility_result_mode(&self, mode: MTLVisibilityResultMode, offset: NSUInteger) { unsafe { msg_send![self, setVisibilityResultMode:mode offset:offset] @@ -262,7 +237,12 @@ impl RenderCommandEncoderRef { // Specifying Resources for a Vertex Shader Function - pub fn set_vertex_bytes(&self, index: NSUInteger, length: NSUInteger, bytes: *const libc::c_void) { + pub fn set_vertex_bytes( + &self, + index: NSUInteger, + length: NSUInteger, + bytes: *const std::ffi::c_void, + ) { unsafe { msg_send![self, setVertexBytes:bytes @@ -272,7 +252,12 @@ impl RenderCommandEncoderRef { } } - pub fn set_vertex_buffer(&self, index: NSUInteger, buffer: Option<&BufferRef>, offset: NSUInteger) { + pub fn set_vertex_buffer( + &self, + index: NSUInteger, + buffer: Option<&BufferRef>, + offset: NSUInteger, + ) { unsafe { msg_send![self, setVertexBuffer:buffer @@ -282,7 +267,12 @@ impl RenderCommandEncoderRef { } } - pub fn set_vertex_buffers(&self, start_index: NSUInteger, data: &[Option<&BufferRef>], offsets: &[NSUInteger]) { + pub fn set_vertex_buffers( + &self, + start_index: NSUInteger, + data: &[Option<&BufferRef>], + offsets: &[NSUInteger], + ) { debug_assert_eq!(offsets.len(), data.len()); unsafe { msg_send![self, @@ -326,7 +316,11 @@ impl RenderCommandEncoderRef { } } - pub fn set_vertex_sampler_states(&self, start_index: NSUInteger, data: &[Option<&SamplerStateRef>]) { + pub fn set_vertex_sampler_states( + &self, + start_index: NSUInteger, + data: &[Option<&SamplerStateRef>], + ) { unsafe { msg_send![self, setVertexSamplerStates: data.as_ptr() @@ -339,7 +333,10 @@ impl RenderCommandEncoderRef { } pub fn set_vertex_sampler_state_with_lod( - &self, index: NSUInteger, sampler: Option<&SamplerStateRef>, lod_clamp: Range + &self, + index: NSUInteger, + sampler: Option<&SamplerStateRef>, + lod_clamp: Range, ) { unsafe { msg_send![self, @@ -353,7 +350,12 @@ impl RenderCommandEncoderRef { // Specifying Resources for a Fragment Shader Function - pub fn set_fragment_bytes(&self, index: NSUInteger, length: NSUInteger, bytes: *const libc::c_void) { + pub fn set_fragment_bytes( + &self, + index: NSUInteger, + length: NSUInteger, + bytes: *const std::ffi::c_void, + ) { unsafe { msg_send![self, setFragmentBytes:bytes @@ -363,7 +365,12 @@ impl RenderCommandEncoderRef { } } - pub fn set_fragment_buffer(&self, index: NSUInteger, buffer: Option<&BufferRef>, offset: NSUInteger) { + pub fn set_fragment_buffer( + &self, + index: NSUInteger, + buffer: Option<&BufferRef>, + offset: NSUInteger, + ) { unsafe { msg_send![self, setFragmentBuffer:buffer @@ -373,7 +380,12 @@ impl RenderCommandEncoderRef { } } - pub fn set_fragment_buffers(&self, start_index: NSUInteger, data: &[Option<&BufferRef>], offsets: &[NSUInteger]) { + pub fn set_fragment_buffers( + &self, + start_index: NSUInteger, + data: &[Option<&BufferRef>], + offsets: &[NSUInteger], + ) { debug_assert_eq!(offsets.len(), data.len()); unsafe { msg_send![self, @@ -415,7 +427,11 @@ impl RenderCommandEncoderRef { } } - pub fn set_fragment_sampler_states(&self, start_index: NSUInteger, data: &[Option<&SamplerStateRef>]) { + pub fn set_fragment_sampler_states( + &self, + start_index: NSUInteger, + data: &[Option<&SamplerStateRef>], + ) { unsafe { msg_send![self, setFragmentSamplerStates: data.as_ptr() @@ -428,7 +444,10 @@ impl RenderCommandEncoderRef { } pub fn set_fragment_sampler_state_with_lod( - &self, index: NSUInteger, sampler: Option<&SamplerStateRef>, lod_clamp: Range + &self, + index: NSUInteger, + sampler: Option<&SamplerStateRef>, + lod_clamp: Range, ) { unsafe { msg_send![self, @@ -443,7 +462,10 @@ impl RenderCommandEncoderRef { // Drawing Geometric Primitives pub fn draw_primitives( - &self, primitive_type: MTLPrimitiveType, vertex_start: NSUInteger, vertex_count: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + vertex_start: NSUInteger, + vertex_count: NSUInteger, ) { unsafe { msg_send![self, @@ -455,7 +477,11 @@ impl RenderCommandEncoderRef { } pub fn draw_primitives_instanced( - &self, primitive_type: MTLPrimitiveType, vertex_start: NSUInteger, vertex_count: NSUInteger, instance_count: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + vertex_start: NSUInteger, + vertex_count: NSUInteger, + instance_count: NSUInteger, ) { unsafe { msg_send![self, @@ -468,7 +494,12 @@ impl RenderCommandEncoderRef { } pub fn draw_primitives_instanced_base_instance( - &self, primitive_type: MTLPrimitiveType, vertex_start: NSUInteger, vertex_count: NSUInteger, instance_count: NSUInteger, base_instance: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + vertex_start: NSUInteger, + vertex_count: NSUInteger, + instance_count: NSUInteger, + base_instance: NSUInteger, ) { unsafe { msg_send![self, @@ -482,7 +513,10 @@ impl RenderCommandEncoderRef { } pub fn draw_primitives_indirect( - &self, primitive_type: MTLPrimitiveType, indirect_buffer: &BufferRef, indirect_buffer_offset: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + indirect_buffer: &BufferRef, + indirect_buffer_offset: NSUInteger, ) { unsafe { msg_send![self, @@ -494,7 +528,12 @@ impl RenderCommandEncoderRef { } pub fn draw_indexed_primitives( - &self, primitive_type: MTLPrimitiveType, index_count: NSUInteger, index_type: MTLIndexType, index_buffer: &BufferRef, index_buffer_offset: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + index_count: NSUInteger, + index_type: MTLIndexType, + index_buffer: &BufferRef, + index_buffer_offset: NSUInteger, ) { unsafe { msg_send![self, @@ -508,7 +547,13 @@ impl RenderCommandEncoderRef { } pub fn draw_indexed_primitives_instanced( - &self, primitive_type: MTLPrimitiveType, index_count: NSUInteger, index_type: MTLIndexType, index_buffer: &BufferRef, index_buffer_offset: NSUInteger, instance_count: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + index_count: NSUInteger, + index_type: MTLIndexType, + index_buffer: &BufferRef, + index_buffer_offset: NSUInteger, + instance_count: NSUInteger, ) { unsafe { msg_send![self, @@ -523,7 +568,15 @@ impl RenderCommandEncoderRef { } pub fn draw_indexed_primitives_instanced_base_instance( - &self, primitive_type: MTLPrimitiveType, index_count: NSUInteger, index_type: MTLIndexType, index_buffer: &BufferRef, index_buffer_offset: NSUInteger, instance_count: NSUInteger, base_vertex: NSInteger, base_instance: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + index_count: NSUInteger, + index_type: MTLIndexType, + index_buffer: &BufferRef, + index_buffer_offset: NSUInteger, + instance_count: NSUInteger, + base_vertex: NSInteger, + base_instance: NSUInteger, ) { unsafe { msg_send![self, @@ -540,7 +593,13 @@ impl RenderCommandEncoderRef { } pub fn draw_indexed_primitives_indirect( - &self, primitive_type: MTLPrimitiveType, index_type: MTLIndexType, index_buffer: &BufferRef, index_buffer_offset: NSUInteger, indirect_buffer: &BufferRef, indirect_buffer_offset: NSUInteger + &self, + primitive_type: MTLPrimitiveType, + index_type: MTLIndexType, + index_buffer: &BufferRef, + index_buffer_offset: NSUInteger, + indirect_buffer: &BufferRef, + indirect_buffer_offset: NSUInteger, ) { unsafe { msg_send![self, @@ -567,9 +626,7 @@ impl RenderCommandEncoderRef { } pub fn use_heap(&self, heap: &HeapRef) { - unsafe { - msg_send![self, useHeap:heap] - } + unsafe { msg_send![self, useHeap: heap] } } } @@ -584,14 +641,10 @@ foreign_obj_type! { impl BlitCommandEncoderRef { pub fn synchronize_resource(&self, resource: &ResourceRef) { - unsafe { - msg_send![self, synchronizeResource:resource] - } + unsafe { msg_send![self, synchronizeResource: resource] } } - pub fn fill_buffer(&self, - destination_buffer: &BufferRef, range: NSRange, value: u8, - ) { + pub fn fill_buffer(&self, destination_buffer: &BufferRef, range: NSRange, value: u8) { unsafe { msg_send![self, fillBuffer: destination_buffer @@ -601,9 +654,12 @@ impl BlitCommandEncoderRef { } } - pub fn copy_from_buffer(&self, - source_buffer: &BufferRef, source_offset: NSUInteger, - destination_buffer: &BufferRef, destination_offset: NSUInteger, + pub fn copy_from_buffer( + &self, + source_buffer: &BufferRef, + source_offset: NSUInteger, + destination_buffer: &BufferRef, + destination_offset: NSUInteger, size: NSUInteger, ) { unsafe { @@ -617,9 +673,17 @@ impl BlitCommandEncoderRef { } } - pub fn copy_from_texture(&self, - source_texture: &TextureRef, source_slice: NSUInteger, source_level: NSUInteger, source_origin: MTLOrigin, source_size: MTLSize, - destination_texture: &TextureRef, destination_slice: NSUInteger, destination_level: NSUInteger, destination_origin: MTLOrigin, + pub fn copy_from_texture( + &self, + source_texture: &TextureRef, + source_slice: NSUInteger, + source_level: NSUInteger, + source_origin: MTLOrigin, + source_size: MTLSize, + destination_texture: &TextureRef, + destination_slice: NSUInteger, + destination_level: NSUInteger, + destination_origin: MTLOrigin, ) { unsafe { msg_send![self, @@ -636,9 +700,17 @@ impl BlitCommandEncoderRef { } } - pub fn copy_from_buffer_to_texture(&self, - source_buffer: &BufferRef, source_offset: NSUInteger, source_bytes_per_row: NSUInteger, source_bytes_per_image: NSUInteger, source_size: MTLSize, - destination_texture: &TextureRef, destination_slice: NSUInteger, destination_level: NSUInteger, destination_origin: MTLOrigin, + pub fn copy_from_buffer_to_texture( + &self, + source_buffer: &BufferRef, + source_offset: NSUInteger, + source_bytes_per_row: NSUInteger, + source_bytes_per_image: NSUInteger, + source_size: MTLSize, + destination_texture: &TextureRef, + destination_slice: NSUInteger, + destination_level: NSUInteger, + destination_origin: MTLOrigin, options: MTLBlitOption, ) { unsafe { @@ -657,9 +729,17 @@ impl BlitCommandEncoderRef { } } - pub fn copy_from_texture_to_buffer(&self, - source_texture: &TextureRef, source_slice: NSUInteger, source_level: NSUInteger, source_origin: MTLOrigin, source_size: MTLSize, - destination_buffer: &BufferRef, destination_offset: NSUInteger, destination_bytes_per_row: NSUInteger, destination_bytes_per_image: NSUInteger, + pub fn copy_from_texture_to_buffer( + &self, + source_texture: &TextureRef, + source_slice: NSUInteger, + source_level: NSUInteger, + source_origin: MTLOrigin, + source_size: MTLSize, + destination_buffer: &BufferRef, + destination_offset: NSUInteger, + destination_bytes_per_row: NSUInteger, + destination_bytes_per_image: NSUInteger, options: MTLBlitOption, ) { unsafe { @@ -677,6 +757,44 @@ impl BlitCommandEncoderRef { ] } } + + pub fn optimize_contents_for_gpu_access(&self, texture: &TextureRef) { + unsafe { msg_send![self, optimizeContentsForGPUAccess: texture] } + } + + pub fn optimize_contents_for_gpu_access_slice_level( + &self, + texture: &TextureRef, + slice: NSUInteger, + level: NSUInteger, + ) { + unsafe { + msg_send![self, + optimizeContentsForGPUAccess: texture + slice: slice + level: level + ] + } + } + + pub fn optimize_contents_for_cpu_access(&self, texture: &TextureRef) { + unsafe { msg_send![self, optimizeContentsForCPUAccess: texture] } + } + + pub fn optimize_contents_for_cpu_access_slice_level( + &self, + texture: &TextureRef, + slice: NSUInteger, + level: NSUInteger, + ) { + unsafe { + msg_send![self, + optimizeContentsForCPUAccess: texture + slice: slice + level: level + ] + } + } } pub enum MTLComputeCommandEncoder {} @@ -690,18 +808,19 @@ foreign_obj_type! { impl ComputeCommandEncoderRef { pub fn set_compute_pipeline_state(&self, state: &ComputePipelineStateRef) { - unsafe { - msg_send![self, setComputePipelineState:state] - } + unsafe { msg_send![self, setComputePipelineState: state] } } pub fn set_buffer(&self, index: NSUInteger, buffer: Option<&BufferRef>, offset: NSUInteger) { - unsafe { - msg_send![self, setBuffer:buffer offset:offset atIndex:index] - } + unsafe { msg_send![self, setBuffer:buffer offset:offset atIndex:index] } } - pub fn set_buffers(&self, start_index: NSUInteger, data: &[Option<&BufferRef>], offsets: &[NSUInteger]) { + pub fn set_buffers( + &self, + start_index: NSUInteger, + data: &[Option<&BufferRef>], + offsets: &[NSUInteger], + ) { debug_assert_eq!(offsets.len(), data.len()); unsafe { msg_send![self, @@ -758,7 +877,10 @@ impl ComputeCommandEncoderRef { } pub fn set_sampler_state_with_lod( - &self, index: NSUInteger, sampler: Option<&SamplerStateRef>, lod_clamp: Range + &self, + index: NSUInteger, + sampler: Option<&SamplerStateRef>, + lod_clamp: Range, ) { unsafe { msg_send![self, @@ -770,7 +892,7 @@ impl ComputeCommandEncoderRef { } } - pub fn set_bytes(&self, index: NSUInteger, length: NSUInteger, bytes: *const libc::c_void) { + pub fn set_bytes(&self, index: NSUInteger, length: NSUInteger, bytes: *const std::ffi::c_void) { unsafe { msg_send![self, setBytes: bytes @@ -780,7 +902,11 @@ impl ComputeCommandEncoderRef { } } - pub fn dispatch_thread_groups(&self, thread_groups_count: MTLSize, threads_per_thread_group: MTLSize) { + pub fn dispatch_thread_groups( + &self, + thread_groups_count: MTLSize, + threads_per_thread_group: MTLSize, + ) { unsafe { msg_send![self, dispatchThreadgroups:thread_groups_count @@ -789,7 +915,12 @@ impl ComputeCommandEncoderRef { } } - pub fn dispatch_thread_groups_indirect(&self, buffer: &BufferRef, offset: NSUInteger, threads_per_thread_group: MTLSize) { + pub fn dispatch_thread_groups_indirect( + &self, + buffer: &BufferRef, + offset: NSUInteger, + threads_per_thread_group: MTLSize, + ) { unsafe { msg_send![self, dispatchThreadgroupsWithIndirectBuffer:buffer @@ -809,9 +940,7 @@ impl ComputeCommandEncoderRef { } pub fn use_heap(&self, heap: &HeapRef) { - unsafe { - msg_send![self, useHeap:heap] - } + unsafe { msg_send![self, useHeap: heap] } } } @@ -825,15 +954,11 @@ foreign_obj_type! { impl ArgumentEncoderRef { pub fn encoded_length(&self) -> NSUInteger { - unsafe { - msg_send![self, encodedLength] - } + unsafe { msg_send![self, encodedLength] } } pub fn alignment(&self) -> NSUInteger { - unsafe { - msg_send![self, alignment] - } + unsafe { msg_send![self, alignment] } } pub fn set_argument_buffer(&self, buffer: &BufferRef, offset: NSUInteger) { @@ -845,7 +970,12 @@ impl ArgumentEncoderRef { } } - pub fn set_argument_buffer_to_element(&self, buffer: &BufferRef, offset: NSUInteger, array_element: NSUInteger) { + pub fn set_argument_buffer_to_element( + &self, + buffer: &BufferRef, + offset: NSUInteger, + array_element: NSUInteger, + ) { unsafe { msg_send![self, setArgumentBuffer: buffer @@ -865,7 +995,12 @@ impl ArgumentEncoderRef { } } - pub fn set_buffers(&self, data: &[&BufferRef], offsets: &[NSUInteger], start_index: NSUInteger) { + pub fn set_buffers( + &self, + data: &[&BufferRef], + offsets: &[NSUInteger], + start_index: NSUInteger, + ) { assert_eq!(offsets.len(), data.len()); unsafe { msg_send![self, @@ -921,15 +1056,13 @@ impl ArgumentEncoderRef { } } - pub fn constant_data(&self, at_index: NSUInteger) -> *mut libc::c_void { - unsafe { - msg_send![self, constantDataAtIndex:at_index] - } + pub fn constant_data(&self, at_index: NSUInteger) -> *mut std::ffi::c_void { + unsafe { msg_send![self, constantDataAtIndex: at_index] } } pub fn new_argument_encoder_for_buffer(&self, index: NSUInteger) -> ArgumentEncoder { unsafe { - let ptr = msg_send![self, newArgumentEncoderForBufferAtIndex:index]; + let ptr = msg_send![self, newArgumentEncoderForBufferAtIndex: index]; ArgumentEncoder::from_ptr(ptr) } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/heap.rs b/third_party/cargo/vendor/metal-0.17.1/src/heap.rs similarity index 72% rename from third_party/cargo/vendor/metal-0.13.1/src/heap.rs rename to third_party/cargo/vendor/metal-0.17.1/src/heap.rs index 856b306..a18d790 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/heap.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/heap.rs @@ -19,39 +19,27 @@ foreign_obj_type! { impl HeapRef { pub fn cpu_cache_mode(&self) -> MTLCPUCacheMode { - unsafe { - msg_send![self, cpuCacheMode] - } + unsafe { msg_send![self, cpuCacheMode] } } pub fn storage_mode(&self) -> MTLStorageMode { - unsafe { - msg_send![self, storageMode] - } + unsafe { msg_send![self, storageMode] } } pub fn set_purgeable_state(&self, state: MTLPurgeableState) -> MTLPurgeableState { - unsafe { - msg_send![self, setPurgeableState:state] - } + unsafe { msg_send![self, setPurgeableState: state] } } pub fn size(&self) -> NSUInteger { - unsafe { - msg_send![self, size] - } + unsafe { msg_send![self, size] } } pub fn used_size(&self) -> NSUInteger { - unsafe { - msg_send![self, usedSize] - } + unsafe { msg_send![self, usedSize] } } pub fn max_available_size(&self, alignment: NSUInteger) -> NSUInteger { - unsafe { - msg_send![self, maxAvailableSizeWithAlignment: alignment] - } + unsafe { msg_send![self, maxAvailableSizeWithAlignment: alignment] } } pub fn new_buffer(&self, length: u64, options: MTLResourceOptions) -> Option { @@ -68,7 +56,7 @@ impl HeapRef { pub fn new_texture(&self, descriptor: &TextureDescriptorRef) -> Option { unsafe { - let ptr: *mut MTLTexture = msg_send![self, newTextureWithDescriptor:descriptor]; + let ptr: *mut MTLTexture = msg_send![self, newTextureWithDescriptor: descriptor]; if !ptr.is_null() { Some(Texture::from_ptr(ptr)) } else { @@ -97,38 +85,26 @@ impl HeapDescriptor { impl HeapDescriptorRef { pub fn cpu_cache_mode(&self) -> MTLCPUCacheMode { - unsafe { - msg_send![self, cpuCacheMode] - } + unsafe { msg_send![self, cpuCacheMode] } } pub fn set_cpu_cache_mode(&self, mode: MTLCPUCacheMode) { - unsafe { - msg_send![self, setCpuCacheMode:mode] - } + unsafe { msg_send![self, setCpuCacheMode: mode] } } pub fn storage_mode(&self) -> MTLStorageMode { - unsafe { - msg_send![self, storageMode] - } + unsafe { msg_send![self, storageMode] } } pub fn set_storage_mode(&self, mode: MTLStorageMode) { - unsafe { - msg_send![self, setStorageMode:mode] - } + unsafe { msg_send![self, setStorageMode: mode] } } pub fn size(&self) -> NSUInteger { - unsafe { - msg_send![self, size] - } + unsafe { msg_send![self, size] } } pub fn set_size(&self, size: NSUInteger) { - unsafe { - msg_send![self, setSize: size]; - } + unsafe { msg_send![self, setSize: size] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/lib.rs b/third_party/cargo/vendor/metal-0.17.1/src/lib.rs similarity index 69% rename from third_party/cargo/vendor/metal-0.13.1/src/lib.rs rename to third_party/cargo/vendor/metal-0.17.1/src/lib.rs index 28ff372..05b48df 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/lib.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/lib.rs @@ -8,30 +8,56 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] -extern crate cocoa; -extern crate core_graphics; #[macro_use] extern crate bitflags; -extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate objc; -extern crate objc_foundation; -extern crate objc_id; -extern crate block; #[macro_use] extern crate foreign_types; -use std::mem; -use std::marker::PhantomData; -use std::ops::Deref; use std::borrow::{Borrow, ToOwned}; +use std::marker::PhantomData; +use std::mem; +use std::ops::Deref; +use std::os::raw::c_void; -use objc::runtime::{Object, YES, NO}; use core_graphics::base::CGFloat; use core_graphics::geometry::CGSize; use foreign_types::ForeignType; +use objc::runtime::{Object, NO, YES}; +use cocoa::foundation::NSUInteger; + +fn nsstring_as_str(nsstr: &objc::runtime::Object) -> &str { + let bytes = unsafe { + let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String]; + bytes as *const u8 + }; + let len: NSUInteger = unsafe { msg_send![nsstr, length] }; + unsafe { + let bytes = std::slice::from_raw_parts(bytes, len as usize); + std::str::from_utf8(bytes).unwrap() + } +} + +fn nsstring_from_str(string: &str) -> *mut objc::runtime::Object { + const UTF8_ENCODING: usize = 4; + + let cls = class!(NSString); + let bytes = string.as_ptr() as *const c_void; + unsafe { + let obj: *mut objc::runtime::Object = msg_send![cls, alloc]; + let obj: *mut objc::runtime::Object = msg_send![ + obj, + initWithBytes:bytes + length:string.len() + encoding:UTF8_ENCODING + ]; + let _: *mut c_void = msg_send![obj, autorelease]; + obj + } +} macro_rules! foreign_obj_type { {type CType = $raw_ident:ident; @@ -59,8 +85,8 @@ macro_rules! foreign_obj_type { } => { foreign_type! { type CType = $raw_ident; - fn drop = ::obj_drop; - fn clone = ::obj_clone; + fn drop = crate::obj_drop; + fn clone = crate::obj_clone; pub struct $owned_ident; pub struct $ref_ident; } @@ -73,10 +99,8 @@ macro_rules! foreign_obj_type { impl ::std::fmt::Debug for $ref_ident { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { unsafe { - use ::objc_foundation::INSString; - // TODO: might leak, not 100% sure... - let string: &::objc_foundation::NSString = msg_send![self, debugDescription]; - write!(f, "{}", string.as_str()) + let string: *mut ::objc::runtime::Object = msg_send![self, debugDescription]; + write!(f, "{}", crate::nsstring_as_str(&*string)) } } } @@ -98,9 +122,9 @@ macro_rules! try_objc { let value = $body; if !$err_name.is_null() { let desc: *mut Object = msg_send![$err_name, localizedDescription]; - let compile_error: *const ::libc::c_char = msg_send![desc, UTF8String]; + let compile_error: *const std::os::raw::c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); - msg_send![$err_name, release]; + let () = msg_send![$err_name, release]; return Err(message); } value @@ -112,56 +136,63 @@ pub struct NSArray { _phantom: PhantomData, } -pub struct Array(*mut NSArray) where +pub struct Array(*mut NSArray) +where T: ForeignType + 'static, T::Ref: objc::Message + 'static; -pub struct ArrayRef(foreign_types::Opaque, PhantomData) where +pub struct ArrayRef(foreign_types::Opaque, PhantomData) +where T: ForeignType + 'static, T::Ref: objc::Message + 'static; -impl Drop for Array where +impl Drop for Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { fn drop(&mut self) { unsafe { - msg_send![self.0, release]; + let () = msg_send![self.0, release]; } } } -impl Clone for Array where +impl Clone for Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { fn clone(&self) -> Self { - unsafe { - Array(msg_send![self.0, retain]) - } + unsafe { Array(msg_send![self.0, retain]) } } } -unsafe impl objc::Message for NSArray where +unsafe impl objc::Message for NSArray +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, -{} -unsafe impl objc::Message for ArrayRef where +{ +} +unsafe impl objc::Message for ArrayRef +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, -{} +{ +} -impl Array where +impl Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, - { - pub fn from_slice(s: &[&T::Ref]) -> Self { +{ + pub fn from_slice<'a>(s: &[&T::Ref]) -> &'a ArrayRef { unsafe { let class = class!(NSArray); msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()] } } - - pub fn from_owned_slice(s: &[T]) -> Self { + + pub fn from_owned_slice<'a>(s: &[T]) -> &'a ArrayRef { unsafe { let class = class!(NSArray); msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()] @@ -169,7 +200,8 @@ impl Array where } } -impl foreign_types::ForeignType for Array where +impl foreign_types::ForeignType for Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { @@ -185,14 +217,16 @@ impl foreign_types::ForeignType for Array where } } -impl foreign_types::ForeignTypeRef for ArrayRef where +impl foreign_types::ForeignTypeRef for ArrayRef +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { type CType = NSArray; } -impl Deref for Array where +impl Deref for Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { @@ -203,7 +237,8 @@ impl Deref for Array where } } -impl Borrow> for Array where +impl Borrow> for Array +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { @@ -212,7 +247,8 @@ impl Borrow> for Array where } } -impl ToOwned for ArrayRef where +impl ToOwned for ArrayRef +where T: ForeignType + 'static, T::Ref: objc::Message + 'static, { @@ -234,9 +270,7 @@ foreign_obj_type! { impl CoreAnimationDrawableRef { pub fn texture(&self) -> &TextureRef { - unsafe { - msg_send![self, texture] - } + unsafe { msg_send![self, texture] } } } @@ -259,33 +293,23 @@ impl CoreAnimationLayer { impl CoreAnimationLayerRef { pub fn set_device(&self, device: &DeviceRef) { - unsafe { - msg_send![self, setDevice:device] - } + unsafe { msg_send![self, setDevice: device] } } pub fn pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, pixelFormat] - } + unsafe { msg_send![self, pixelFormat] } } pub fn set_pixel_format(&self, pixel_format: MTLPixelFormat) { - unsafe { - msg_send![self, setPixelFormat:pixel_format] - } + unsafe { msg_send![self, setPixelFormat: pixel_format] } } pub fn drawable_size(&self) -> CGSize { - unsafe { - msg_send![self, drawableSize] - } + unsafe { msg_send![self, drawableSize] } } pub fn set_drawable_size(&self, size: CGSize) { - unsafe { - msg_send![self, setDrawableSize:size] - } + unsafe { msg_send![self, setDrawableSize: size] } } pub fn presents_with_transaction(&self) -> bool { @@ -293,94 +317,85 @@ impl CoreAnimationLayerRef { match msg_send![self, presentsWithTransaction] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_presents_with_transaction(&self, transaction: bool) { - unsafe { - msg_send![self, setPresentsWithTransaction:transaction]; - } + unsafe { msg_send![self, setPresentsWithTransaction: transaction] } } pub fn set_edge_antialiasing_mask(&self, mask: u64) { - unsafe { - msg_send![self, setEdgeAntialiasingMask:mask] - } + unsafe { msg_send![self, setEdgeAntialiasingMask: mask] } } pub fn set_masks_to_bounds(&self, masks: bool) { - unsafe { - msg_send![self, setMasksToBounds:masks] - } + unsafe { msg_send![self, setMasksToBounds: masks] } } pub fn remove_all_animations(&self) { - unsafe { - msg_send![self, removeAllAnimations]; - } + unsafe { msg_send![self, removeAllAnimations] } } pub fn next_drawable(&self) -> Option<&CoreAnimationDrawableRef> { - unsafe { - msg_send![self, nextDrawable] - } + unsafe { msg_send![self, nextDrawable] } } pub fn set_contents_scale(&self, scale: CGFloat) { - unsafe { - msg_send![self, setContentsScale:scale]; - } + unsafe { msg_send![self, setContentsScale: scale] } } } -mod constants; -mod types; -mod device; -mod texture; -mod sampler; -mod resource; -mod drawable; -mod buffer; -mod renderpass; -mod commandqueue; -mod commandbuffer; -mod encoder; -mod pipeline; -mod library; mod argument; -mod vertexdescriptor; -mod depthstencil; -mod heap; +mod buffer; mod capturemanager; +mod commandbuffer; +mod commandqueue; +mod constants; +mod depthstencil; +mod device; +mod drawable; +mod encoder; +mod heap; +mod library; +mod pipeline; +mod renderpass; +mod resource; +mod sampler; +mod texture; +mod types; +mod vertexdescriptor; -pub use constants::*; -pub use types::*; -pub use device::*; -pub use texture::*; -pub use sampler::*; -pub use resource::*; -pub use drawable::*; -pub use buffer::*; -pub use renderpass::*; -pub use commandqueue::*; -pub use commandbuffer::*; -pub use encoder::*; -pub use pipeline::*; -pub use library::*; pub use argument::*; -pub use vertexdescriptor::*; -pub use depthstencil::*; -pub use heap::*; +pub use buffer::*; pub use capturemanager::*; +pub use commandbuffer::*; +pub use commandqueue::*; +pub use constants::*; +pub use depthstencil::*; +pub use device::*; +pub use drawable::*; +pub use encoder::*; +pub use heap::*; +pub use library::*; +pub use pipeline::*; +pub use renderpass::*; +pub use resource::*; +pub use sampler::*; +pub use texture::*; +pub use types::*; +pub use vertexdescriptor::*; #[inline] unsafe fn obj_drop(p: *mut T) { - msg_send![(p as *mut Object), release]; + msg_send![(p as *mut Object), release] } #[inline] unsafe fn obj_clone(p: *mut T) -> *mut T { msg_send![(p as *mut Object), retain] } + +#[allow(non_camel_case_types)] +type c_size_t = usize; diff --git a/third_party/cargo/vendor/metal-0.13.1/src/library.rs b/third_party/cargo/vendor/metal-0.17.1/src/library.rs similarity index 63% rename from third_party/cargo/vendor/metal-0.13.1/src/library.rs rename to third_party/cargo/vendor/metal-0.17.1/src/library.rs index 1e5c802..de4d7d6 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/library.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/library.rs @@ -7,10 +7,9 @@ use super::*; -use objc::runtime::{Object, YES, NO}; -use objc_foundation::{NSString, INSString, NSArray}; -use cocoa::foundation::{NSUInteger}; +use cocoa::foundation::NSUInteger; use foreign_types::ForeignType; +use objc::runtime::{Object, NO, YES}; use std::ffi::CStr; pub enum MTLVertexAttribute {} @@ -24,21 +23,17 @@ foreign_obj_type! { impl VertexAttributeRef { pub fn name(&self) -> &str { unsafe { - let name: &NSString = msg_send![self, name]; - name.as_str() + let name = msg_send![self, name]; + crate::nsstring_as_str(name) } } pub fn attribute_index(&self) -> u64 { - unsafe { - msg_send![self, attributeIndex] - } + unsafe { msg_send![self, attributeIndex] } } pub fn attribute_type(&self) -> MTLDataType { - unsafe { - msg_send![self, attributeType] - } + unsafe { msg_send![self, attributeType] } } pub fn is_active(&self) -> bool { @@ -46,11 +41,10 @@ impl VertexAttributeRef { match msg_send![self, isActive] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } - } #[repr(u64)] @@ -72,34 +66,28 @@ foreign_obj_type! { impl FunctionRef { pub fn name(&self) -> &str { unsafe { - let name: &NSString = msg_send![self, name]; - name.as_str() + let name = msg_send![self, name]; + crate::nsstring_as_str(name) } } pub fn function_type(&self) -> MTLFunctionType { - unsafe { - msg_send![self, functionType] - } + unsafe { msg_send![self, functionType] } } pub fn vertex_attributes(&self) -> &Array { - unsafe { - msg_send![self, vertexAttributes] - } + unsafe { msg_send![self, vertexAttributes] } } pub fn new_argument_encoder(&self, buffer_index: NSUInteger) -> ArgumentEncoder { unsafe { - let ptr = msg_send![self, newArgumentEncoderWithBufferIndex:buffer_index]; + let ptr = msg_send![self, newArgumentEncoderWithBufferIndex: buffer_index]; ArgumentEncoder::from_ptr(ptr) } } pub fn function_constants_dictionary(&self) -> *mut Object { - unsafe { - msg_send![self, functionConstantsDictionary] - } + unsafe { msg_send![self, functionConstantsDictionary] } } } @@ -111,6 +99,8 @@ pub enum MTLLanguageVersion { V1_1 = 0x10001, V1_2 = 0x10002, V2_0 = 0x20000, + V2_1 = 0x20001, + V2_2 = 0x20002, } pub enum MTLFunctionConstantValues {} @@ -131,7 +121,12 @@ impl FunctionConstantValues { } impl FunctionConstantValuesRef { - pub unsafe fn set_constant_value_at_index(&self, index: NSUInteger, ty: MTLDataType, value: *const std::os::raw::c_void) { + pub unsafe fn set_constant_value_at_index( + &self, + index: NSUInteger, + ty: MTLDataType, + value: *const std::os::raw::c_void, + ) { msg_send![self, setConstantValue:value type:ty atIndex:index] } } @@ -159,7 +154,7 @@ impl CompileOptionsRef { } pub unsafe fn set_preprocessor_defines(&self, defines: *mut Object) { - msg_send![self, setPreprocessorMacros:defines] + msg_send![self, setPreprocessorMacros: defines] } pub fn is_fast_math_enabled(&self) -> bool { @@ -167,37 +162,31 @@ impl CompileOptionsRef { match msg_send![self, fastMathEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_fast_math_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setFastMathEnabled:enabled] - } + unsafe { msg_send![self, setFastMathEnabled: enabled] } } pub fn language_version(&self) -> MTLLanguageVersion { - unsafe { - msg_send![self, languageVersion] - } + unsafe { msg_send![self, languageVersion] } } pub fn set_language_version(&self, version: MTLLanguageVersion) { - unsafe { - msg_send![self, setLanguageVersion:version] - } + unsafe { msg_send![self, setLanguageVersion: version] } } } #[repr(u64)] #[allow(non_camel_case_types)] pub enum MTLLibraryError { - Unsupported = 1, - Internal = 2, - CompileFailure = 3, - CompileWarning = 4, + Unsupported = 1, + Internal = 2, + CompileFailure = 3, + CompileWarning = 4, } pub enum MTLLibrary {} @@ -208,32 +197,36 @@ foreign_obj_type! { pub struct LibraryRef; } - impl LibraryRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } - pub fn get_function(&self, name: &str, constants: Option) -> Result { + pub fn get_function( + &self, + name: &str, + constants: Option, + ) -> Result { unsafe { - use cocoa::foundation::NSString as cocoa_NSString; - use cocoa::base::nil as cocoa_nil; - - let nsname = cocoa_NSString::alloc(cocoa_nil).init_str(name); + let nsname = crate::nsstring_from_str(name); let function: *mut MTLFunction = match constants { - Some(c) => try_objc!{ err => msg_send![self, newFunctionWithName:nsname constantValues:c error:&mut err] }, - None => msg_send![self, newFunctionWithName:nsname] + Some(c) => try_objc! { err => msg_send![self, + newFunctionWithName: nsname.as_ref() + constantValues: c.as_ref() + error: &mut err + ]}, + None => msg_send![self, newFunctionWithName: nsname.as_ref()], }; if !function.is_null() { @@ -244,9 +237,18 @@ impl LibraryRef { } } - pub fn function_names(&self) -> &NSArray { + pub fn function_names(&self) -> Vec { unsafe { - msg_send![self, functionNames] + let names: *mut Object = msg_send![self, functionNames]; + let count: NSUInteger = msg_send![names, count]; + let ret = (0..count) + .map(|i| { + let name = msg_send![names, objectAtIndex: i]; + nsstring_as_str(name).to_string() + }) + .collect(); + let () = msg_send![names, release]; + ret } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/compute.rs b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/compute.rs similarity index 63% rename from third_party/cargo/vendor/metal-0.13.1/src/pipeline/compute.rs rename to third_party/cargo/vendor/metal-0.17.1/src/pipeline/compute.rs index b2e53da..ccda527 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/compute.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/compute.rs @@ -8,8 +8,7 @@ use super::*; use cocoa::foundation::NSUInteger; -use objc::runtime::{YES, NO}; -use objc_foundation::{INSString, NSString}; +use objc::runtime::{NO, YES}; #[repr(u64)] #[allow(non_camel_case_types)] @@ -106,7 +105,7 @@ pub enum MTLStepFunction { ThreadPositionInGridXIndexed = 6, ThreadPositionInGridY = 7, ThreadPositionInGridYIndexed = 8, -} +} pub enum MTLComputePipelineDescriptor {} @@ -128,28 +127,24 @@ impl ComputePipelineDescriptor { impl ComputePipelineDescriptorRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn compute_function(&self) -> Option<&FunctionRef> { - unsafe { - msg_send![self, computeFunction] - } + unsafe { msg_send![self, computeFunction] } } pub fn set_compute_function(&self, function: Option<&FunctionRef>) { - unsafe { - msg_send![self, setComputeFunction:function] - } + unsafe { msg_send![self, setComputeFunction: function] } } pub fn thread_group_size_is_multiple_of_thread_execution_width(&self) -> bool { @@ -162,34 +157,32 @@ impl ComputePipelineDescriptorRef { } } - pub fn set_thread_group_size_is_multiple_of_thread_execution_width(&self, size_is_multiple_of_width: bool) { + pub fn set_thread_group_size_is_multiple_of_thread_execution_width( + &self, + size_is_multiple_of_width: bool, + ) { unsafe { - msg_send![self, setThreadGroupSizeIsMultipleOfThreadExecutionWidth:size_is_multiple_of_width] + msg_send![ + self, + setThreadGroupSizeIsMultipleOfThreadExecutionWidth: size_is_multiple_of_width + ] } } pub fn stage_input_descriptor(&self) -> Option<&StageInputOutputDescriptorRef> { - unsafe { - msg_send![self, stageInputDescriptor] - } + unsafe { msg_send![self, stageInputDescriptor] } } pub fn set_stage_input_descriptor(&self, descriptor: Option<&StageInputOutputDescriptorRef>) { - unsafe { - msg_send![self, setStageInputDescriptor:descriptor] - } + unsafe { msg_send![self, setStageInputDescriptor: descriptor] } } pub fn buffers(&self) -> Option<&PipelineBufferDescriptorArrayRef> { - unsafe { - msg_send![self, buffers] - } + unsafe { msg_send![self, buffers] } } pub fn reset(&self) { - unsafe { - msg_send![self, reset] - } + unsafe { msg_send![self, reset] } } } @@ -204,78 +197,28 @@ foreign_obj_type! { impl ComputePipelineStateRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn max_total_threads_per_group(&self) -> NSUInteger { - unsafe { - msg_send![self, maxTotalThreadsPerThreadgroup] - } + unsafe { msg_send![self, maxTotalThreadsPerThreadgroup] } } pub fn thread_execution_width(&self) -> NSUInteger { - unsafe { - msg_send![self, threadExecutionWidth] - } + unsafe { msg_send![self, threadExecutionWidth] } } pub fn static_threadgroup_memory_length(&self) -> NSUInteger { - unsafe { - msg_send![self, staticThreadgroupMemoryLength] - } - } -} - -pub enum MTLPipelineBufferDescriptorArray {} - -foreign_obj_type! { - type CType = MTLPipelineBufferDescriptorArray; - pub struct PipelineBufferDescriptorArray; - pub struct PipelineBufferDescriptorArrayRef; -} - -impl PipelineBufferDescriptorArrayRef { - pub fn object_at(&self, index: usize) -> Option<&PipelineBufferDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } - } - - pub fn set_object_at(&self, index: usize, buffer_desc: Option<&PipelineBufferDescriptorRef>) { - unsafe { - msg_send![self, setObject:buffer_desc atIndexedSubscript:index] - } - } -} - -pub enum MTLPipelineBufferDescriptor {} - -foreign_obj_type! { - type CType = MTLPipelineBufferDescriptor; - pub struct PipelineBufferDescriptor; - pub struct PipelineBufferDescriptorRef; -} - -impl PipelineBufferDescriptorRef { - pub fn mutability(&self) -> MTLMutability { - unsafe { - msg_send![self, mutability] - } - } - - pub fn set_mutability(&self, new_mutability: MTLMutability) { - unsafe { - msg_send![self, setMutability:new_mutability] - } + unsafe { msg_send![self, staticThreadgroupMemoryLength] } } } @@ -298,46 +241,32 @@ impl StageInputOutputDescriptor { impl StageInputOutputDescriptorRef { pub fn attributes(&self) -> Option<&AttributeDescriptorArrayRef> { - unsafe { - msg_send![self, attributes] - } + unsafe { msg_send![self, attributes] } } pub fn index_buffer_index(&self) -> NSUInteger { - unsafe { - msg_send![self, indexBufferIndex] - } + unsafe { msg_send![self, indexBufferIndex] } } pub fn set_index_buffer_index(&self, idx_buffer_idx: NSUInteger) { - unsafe { - msg_send![self, setIndexBufferIndex:idx_buffer_idx] - } + unsafe { msg_send![self, setIndexBufferIndex: idx_buffer_idx] } } pub fn index_type(&self) -> MTLIndexType { - unsafe { - msg_send![self, indexType] - } + unsafe { msg_send![self, indexType] } } pub fn set_index_type(&self, index_ty: MTLIndexType) { - unsafe { - msg_send![self, setIndexType:index_ty] - } + unsafe { msg_send![self, setIndexType: index_ty] } } pub fn layouts(&self) -> Option<&BufferLayoutDescriptorArrayRef> { - unsafe { - msg_send![self, layouts] - } + unsafe { msg_send![self, layouts] } } pub fn reset(&self) { - unsafe { - msg_send![self, reset] - } - } + unsafe { msg_send![self, reset] } + } } pub enum MTLAttributeDescriptorArray {} @@ -350,15 +279,11 @@ foreign_obj_type! { impl AttributeDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&AttributeDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } pub fn set_object_at(&self, index: usize, buffer_desc: Option<&AttributeDescriptorRef>) { - unsafe { - msg_send![self, setObject:buffer_desc atIndexedSubscript:index] - } + unsafe { msg_send![self, setObject:buffer_desc atIndexedSubscript:index] } } } @@ -372,39 +297,27 @@ foreign_obj_type! { impl AttributeDescriptorRef { pub fn buffer_index(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferIndex] - } + unsafe { msg_send![self, bufferIndex] } } pub fn set_buffer_index(&self, buffer_index: NSUInteger) { - unsafe { - msg_send![self, setBufferIndex:buffer_index] - } + unsafe { msg_send![self, setBufferIndex: buffer_index] } } pub fn format(&self) -> MTLAttributeFormat { - unsafe { - msg_send![self, format] - } + unsafe { msg_send![self, format] } } pub fn set_format(&self, format: MTLAttributeFormat) { - unsafe { - msg_send![self, setFormat:format] - } + unsafe { msg_send![self, setFormat: format] } } pub fn offset(&self) -> NSUInteger { - unsafe { - msg_send![self, offset] - } + unsafe { msg_send![self, offset] } } pub fn set_offset(&self, offset: NSUInteger) { - unsafe { - msg_send![self, setOffset:offset] - } + unsafe { msg_send![self, setOffset: offset] } } } @@ -418,15 +331,11 @@ foreign_obj_type! { impl BufferLayoutDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&BufferLayoutDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } pub fn set_object_at(&self, index: usize, buffer_desc: Option<&BufferLayoutDescriptorRef>) { - unsafe { - msg_send![self, setObject:buffer_desc atIndexedSubscript:index] - } + unsafe { msg_send![self, setObject:buffer_desc atIndexedSubscript:index] } } } @@ -440,38 +349,26 @@ foreign_obj_type! { impl BufferLayoutDescriptorRef { pub fn step_function(&self) -> MTLStepFunction { - unsafe { - msg_send![self, stepFunction] - } + unsafe { msg_send![self, stepFunction] } } pub fn set_step_function(&self, step_function: MTLStepFunction) { - unsafe { - msg_send![self, setStepFunction:step_function] - } + unsafe { msg_send![self, setStepFunction: step_function] } } pub fn step_rate(&self) -> NSUInteger { - unsafe { - msg_send![self, stepRate] - } + unsafe { msg_send![self, stepRate] } } pub fn set_step_rate(&self, step_rate: NSUInteger) { - unsafe { - msg_send![self, setStepRate:step_rate] - } + unsafe { msg_send![self, setStepRate: step_rate] } } pub fn stride(&self) -> NSUInteger { - unsafe { - msg_send![self, stride] - } + unsafe { msg_send![self, stride] } } pub fn set_stride(&self, stride: NSUInteger) { - unsafe { - msg_send![self, setStride:stride] - } + unsafe { msg_send![self, setStride: stride] } } } diff --git a/third_party/cargo/vendor/metal-0.17.1/src/pipeline/mod.rs b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/mod.rs new file mode 100644 index 0000000..4cde444 --- /dev/null +++ b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/mod.rs @@ -0,0 +1,50 @@ +// Copyright 2017 GFX developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use super::*; + +mod compute; +mod render; + +pub use self::compute::*; +pub use self::render::*; + +pub enum MTLPipelineBufferDescriptorArray {} + +foreign_obj_type! { + type CType = MTLPipelineBufferDescriptorArray; + pub struct PipelineBufferDescriptorArray; + pub struct PipelineBufferDescriptorArrayRef; +} + +impl PipelineBufferDescriptorArrayRef { + pub fn object_at(&self, index: usize) -> Option<&PipelineBufferDescriptorRef> { + unsafe { msg_send![self, objectAtIndexedSubscript: index] } + } + + pub fn set_object_at(&self, index: usize, buffer_desc: Option<&PipelineBufferDescriptorRef>) { + unsafe { msg_send![self, setObject:buffer_desc atIndexedSubscript:index] } + } +} + +pub enum MTLPipelineBufferDescriptor {} + +foreign_obj_type! { + type CType = MTLPipelineBufferDescriptor; + pub struct PipelineBufferDescriptor; + pub struct PipelineBufferDescriptorRef; +} + +impl PipelineBufferDescriptorRef { + pub fn mutability(&self) -> MTLMutability { + unsafe { msg_send![self, mutability] } + } + + pub fn set_mutability(&self, new_mutability: MTLMutability) { + unsafe { msg_send![self, setMutability: new_mutability] } + } +} diff --git a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/render.rs b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/render.rs similarity index 66% rename from third_party/cargo/vendor/metal-0.13.1/src/pipeline/render.rs rename to third_party/cargo/vendor/metal-0.17.1/src/pipeline/render.rs index f0ab852..a6d79bf 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/pipeline/render.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/pipeline/render.rs @@ -8,11 +8,7 @@ use super::*; use cocoa::foundation::NSUInteger; -use objc::runtime::{YES, NO}; -use objc_foundation::{INSString, NSString}; - -#[cfg(feature = "private")] -use libc; +use objc::runtime::{NO, YES}; #[repr(u64)] #[allow(non_camel_case_types)] @@ -79,15 +75,11 @@ foreign_obj_type! { impl RenderPipelineColorAttachmentDescriptorRef { pub fn pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, pixelFormat] - } + unsafe { msg_send![self, pixelFormat] } } pub fn set_pixel_format(&self, pixel_format: MTLPixelFormat) { - unsafe { - msg_send![self, setPixelFormat:pixel_format] - } + unsafe { msg_send![self, setPixelFormat: pixel_format] } } pub fn is_blending_enabled(&self) -> bool { @@ -95,99 +87,69 @@ impl RenderPipelineColorAttachmentDescriptorRef { match msg_send![self, isBlendingEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_blending_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setBlendingEnabled:enabled] - } + unsafe { msg_send![self, setBlendingEnabled: enabled] } } pub fn source_rgb_blend_factor(&self) -> MTLBlendFactor { - unsafe { - msg_send![self, sourceRGBBlendFactor] - } + unsafe { msg_send![self, sourceRGBBlendFactor] } } pub fn set_source_rgb_blend_factor(&self, blend_factor: MTLBlendFactor) { - unsafe { - msg_send![self, setSourceRGBBlendFactor:blend_factor] - } + unsafe { msg_send![self, setSourceRGBBlendFactor: blend_factor] } } pub fn destination_rgb_blend_factor(&self) -> MTLBlendFactor { - unsafe { - msg_send![self, destinationRGBBlendFactor] - } + unsafe { msg_send![self, destinationRGBBlendFactor] } } pub fn set_destination_rgb_blend_factor(&self, blend_factor: MTLBlendFactor) { - unsafe { - msg_send![self, setDestinationRGBBlendFactor:blend_factor] - } + unsafe { msg_send![self, setDestinationRGBBlendFactor: blend_factor] } } pub fn rgb_blend_operation(&self) -> MTLBlendOperation { - unsafe { - msg_send![self, rgbBlendOperation] - } + unsafe { msg_send![self, rgbBlendOperation] } } pub fn set_rgb_blend_operation(&self, blend_operation: MTLBlendOperation) { - unsafe { - msg_send![self, setRgbBlendOperation:blend_operation] - } + unsafe { msg_send![self, setRgbBlendOperation: blend_operation] } } pub fn source_alpha_blend_factor(&self) -> MTLBlendFactor { - unsafe { - msg_send![self, sourceAlphaBlendFactor] - } + unsafe { msg_send![self, sourceAlphaBlendFactor] } } pub fn set_source_alpha_blend_factor(&self, blend_factor: MTLBlendFactor) { - unsafe { - msg_send![self, setSourceAlphaBlendFactor:blend_factor] - } + unsafe { msg_send![self, setSourceAlphaBlendFactor: blend_factor] } } pub fn destination_alpha_blend_factor(&self) -> MTLBlendFactor { - unsafe { - msg_send![self, destinationAlphaBlendFactor] - } + unsafe { msg_send![self, destinationAlphaBlendFactor] } } pub fn set_destination_alpha_blend_factor(&self, blend_factor: MTLBlendFactor) { - unsafe { - msg_send![self, setDestinationAlphaBlendFactor:blend_factor] - } + unsafe { msg_send![self, setDestinationAlphaBlendFactor: blend_factor] } } pub fn alpha_blend_operation(&self) -> MTLBlendOperation { - unsafe { - msg_send![self, alphaBlendOperation] - } + unsafe { msg_send![self, alphaBlendOperation] } } pub fn set_alpha_blend_operation(&self, blend_operation: MTLBlendOperation) { - unsafe { - msg_send![self, setAlphaBlendOperation:blend_operation] - } + unsafe { msg_send![self, setAlphaBlendOperation: blend_operation] } } pub fn write_mask(&self) -> MTLColorWriteMask { - unsafe { - msg_send![self, writeMask] - } + unsafe { msg_send![self, writeMask] } } pub fn set_write_mask(&self, mask: MTLColorWriteMask) { - unsafe { - msg_send![self, setWriteMask:mask] - } + unsafe { msg_send![self, setWriteMask: mask] } } } @@ -201,10 +163,14 @@ foreign_obj_type! { impl RenderPipelineReflection { #[cfg(feature = "private")] - pub unsafe fn new(vertex_data: *mut libc::c_void, - fragment_data: *mut libc::c_void, vertex_desc: *mut libc::c_void, - device: &DeviceRef, options: u64, flags: u64) -> Self - { + pub unsafe fn new( + vertex_data: *mut std::ffi::c_void, + fragment_data: *mut std::ffi::c_void, + vertex_desc: *mut std::ffi::c_void, + device: &DeviceRef, + options: u64, + flags: u64, + ) -> Self { let class = class!(MTLRenderPipelineReflection); let this: RenderPipelineReflection = msg_send![class, alloc]; let this_alias: *mut Object = msg_send![this.as_ref(), initWithVertexData:vertex_data @@ -222,15 +188,11 @@ impl RenderPipelineReflection { impl RenderPipelineReflectionRef { pub fn fragment_arguments(&self) -> &Array { - unsafe { - msg_send![self, fragmentArguments] - } + unsafe { msg_send![self, fragmentArguments] } } pub fn vertex_arguments(&self) -> &Array { - unsafe { - msg_send![self, vertexArguments] - } + unsafe { msg_send![self, vertexArguments] } } } @@ -254,64 +216,48 @@ impl RenderPipelineDescriptor { impl RenderPipelineDescriptorRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn vertex_function(&self) -> Option<&FunctionRef> { - unsafe { - msg_send![self, vertexFunction] - } + unsafe { msg_send![self, vertexFunction] } } pub fn set_vertex_function(&self, function: Option<&FunctionRef>) { - unsafe { - msg_send![self, setVertexFunction:function] - } + unsafe { msg_send![self, setVertexFunction: function] } } pub fn fragment_function(&self) -> Option<&FunctionRef> { - unsafe { - msg_send![self, fragmentFunction] - } + unsafe { msg_send![self, fragmentFunction] } } pub fn set_fragment_function(&self, function: Option<&FunctionRef>) { - unsafe { - msg_send![self, setFragmentFunction:function] - } + unsafe { msg_send![self, setFragmentFunction: function] } } pub fn vertex_descriptor(&self) -> Option<&VertexDescriptorRef> { - unsafe { - msg_send![self, vertexDescriptor] - } + unsafe { msg_send![self, vertexDescriptor] } } pub fn set_vertex_descriptor(&self, descriptor: Option<&VertexDescriptorRef>) { - unsafe { - msg_send![self, setVertexDescriptor:descriptor] - } + unsafe { msg_send![self, setVertexDescriptor: descriptor] } } pub fn sample_count(&self) -> NSUInteger { - unsafe { - msg_send![self, sampleCount] - } + unsafe { msg_send![self, sampleCount] } } pub fn set_sample_count(&self, count: NSUInteger) { - unsafe { - msg_send![self, setSampleCount:count] - } + unsafe { msg_send![self, setSampleCount: count] } } pub fn is_alpha_to_coverage_enabled(&self) -> bool { @@ -319,15 +265,13 @@ impl RenderPipelineDescriptorRef { match msg_send![self, isAlphaToCoverageEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_alpha_to_coverage_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setAlphaToCoverageEnabled:enabled] - } + unsafe { msg_send![self, setAlphaToCoverageEnabled: enabled] } } pub fn is_alpha_to_one_enabled(&self) -> bool { @@ -335,15 +279,13 @@ impl RenderPipelineDescriptorRef { match msg_send![self, isAlphaToOneEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_alpha_to_one_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setAlphaToOneEnabled:enabled] - } + unsafe { msg_send![self, setAlphaToOneEnabled: enabled] } } pub fn is_rasterization_enabled(&self) -> bool { @@ -351,61 +293,45 @@ impl RenderPipelineDescriptorRef { match msg_send![self, isRasterizationEnabled] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } pub fn set_rasterization_enabled(&self, enabled: bool) { - unsafe { - msg_send![self, setRasterizationEnabled:enabled] - } + unsafe { msg_send![self, setRasterizationEnabled: enabled] } } pub fn color_attachments(&self) -> &RenderPipelineColorAttachmentDescriptorArrayRef { - unsafe { - msg_send![self, colorAttachments] - } + unsafe { msg_send![self, colorAttachments] } } pub fn depth_attachment_pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, depthAttachmentPixelFormat] - } + unsafe { msg_send![self, depthAttachmentPixelFormat] } } pub fn set_depth_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) { - unsafe { - msg_send![self, setDepthAttachmentPixelFormat:pixel_format] - } + unsafe { msg_send![self, setDepthAttachmentPixelFormat: pixel_format] } } pub fn stencil_attachment_pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, stencilAttachmentPixelFormat] - } + unsafe { msg_send![self, stencilAttachmentPixelFormat] } } pub fn set_stencil_attachment_pixel_format(&self, pixel_format: MTLPixelFormat) { - unsafe { - msg_send![self, setStencilAttachmentPixelFormat:pixel_format] - } + unsafe { msg_send![self, setStencilAttachmentPixelFormat: pixel_format] } } pub fn input_primitive_topology(&self) -> MTLPrimitiveTopologyClass { - unsafe { - msg_send![self, inputPrimitiveTopology] - } + unsafe { msg_send![self, inputPrimitiveTopology] } } pub fn set_input_primitive_topology(&self, topology: MTLPrimitiveTopologyClass) { - unsafe { - msg_send![self, setInputPrimitiveTopology:topology] - } + unsafe { msg_send![self, setInputPrimitiveTopology: topology] } } #[cfg(feature = "private")] - pub unsafe fn serialize_vertex_data(&self) -> *mut libc::c_void { + pub unsafe fn serialize_vertex_data(&self) -> *mut std::ffi::c_void { use std::ptr; let flags = 0; let err: *mut Object = ptr::null_mut(); @@ -414,9 +340,35 @@ impl RenderPipelineDescriptorRef { } #[cfg(feature = "private")] - pub unsafe fn serialize_fragment_data(&self) -> *mut libc::c_void { + pub unsafe fn serialize_fragment_data(&self) -> *mut std::ffi::c_void { msg_send![self, serializeFragmentData] } + + pub fn support_indirect_command_buffers(&self) -> bool { + unsafe { + match msg_send![self, supportIndirectCommandBuffers] { + YES => true, + NO => false, + _ => unreachable!(), + } + } + } + + pub fn set_support_indirect_command_buffers(&self, support: bool) { + unsafe { msg_send![self, setSupportIndirectCommandBuffers: support] } + } + + pub fn vertex_buffers(&self) -> Option<&PipelineBufferDescriptorArrayRef> { + unsafe { msg_send![self, vertexBuffers] } + } + + pub fn fragment_buffers(&self) -> Option<&PipelineBufferDescriptorArrayRef> { + unsafe { msg_send![self, fragmentBuffers] } + } + + pub fn reset(&self) { + unsafe { msg_send![self, reset] } + } } pub enum MTLRenderPipelineState {} @@ -430,15 +382,15 @@ foreign_obj_type! { impl RenderPipelineStateRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } } @@ -453,12 +405,14 @@ foreign_obj_type! { impl RenderPipelineColorAttachmentDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&RenderPipelineColorAttachmentDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } - pub fn set_object_at(&self, index: usize, attachment: Option<&RenderPipelineColorAttachmentDescriptorRef>) { + pub fn set_object_at( + &self, + index: usize, + attachment: Option<&RenderPipelineColorAttachmentDescriptorRef>, + ) { unsafe { msg_send![self, setObject:attachment atIndexedSubscript:index] diff --git a/third_party/cargo/vendor/metal-0.13.1/src/renderpass.rs b/third_party/cargo/vendor/metal-0.17.1/src/renderpass.rs similarity index 63% rename from third_party/cargo/vendor/metal-0.13.1/src/renderpass.rs rename to third_party/cargo/vendor/metal-0.17.1/src/renderpass.rs index 65dae31..dc96387 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/renderpass.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/renderpass.rs @@ -34,21 +34,28 @@ pub struct MTLClearColor { red: f64, green: f64, blue: f64, - alpha: f64 + alpha: f64, } impl MTLClearColor { #[inline] pub fn new(red: f64, green: f64, blue: f64, alpha: f64) -> Self { MTLClearColor { - red: red, - green: green, - blue: blue, - alpha: alpha + red, + green, + blue, + alpha, } } } +#[repr(u32)] +#[allow(non_camel_case_types)] +pub enum MTLMultisampleStencilResolveFilter { + Sample0 = 0, + DepthResolvedSample = 1, +} + pub enum MTLRenderPassAttachmentDescriptor {} foreign_obj_type! { @@ -59,123 +66,83 @@ foreign_obj_type! { impl RenderPassAttachmentDescriptorRef { pub fn texture(&self) -> Option<&TextureRef> { - unsafe { - msg_send![self, texture] - } + unsafe { msg_send![self, texture] } } pub fn set_texture(&self, texture: Option<&TextureRef>) { - unsafe { - msg_send![self, setTexture:texture]; - } + unsafe { msg_send![self, setTexture: texture] } } pub fn level(&self) -> NSUInteger { - unsafe { - msg_send![self, level] - } + unsafe { msg_send![self, level] } } pub fn set_level(&self, level: NSUInteger) { - unsafe { - msg_send![self, setLevel:level] - } + unsafe { msg_send![self, setLevel: level] } } pub fn slice(&self) -> NSUInteger { - unsafe { - msg_send![self, slice] - } + unsafe { msg_send![self, slice] } } pub fn set_slice(&self, slice: NSUInteger) { - unsafe { - msg_send![self, setSlice:slice] - } + unsafe { msg_send![self, setSlice: slice] } } pub fn depth_plane(&self) -> NSUInteger { - unsafe { - msg_send![self, depthPlane] - } + unsafe { msg_send![self, depthPlane] } } pub fn set_depth_plane(&self, depth_plane: NSUInteger) { - unsafe { - msg_send![self, setDepthPlane:depth_plane] - } + unsafe { msg_send![self, setDepthPlane: depth_plane] } } pub fn resolve_texture(&self) -> Option<&TextureRef> { - unsafe { - msg_send![self, resolveTexture] - } + unsafe { msg_send![self, resolveTexture] } } pub fn set_resolve_texture(&self, resolve_texture: Option<&TextureRef>) { - unsafe { - msg_send![self, setResolveTexture:resolve_texture] - } + unsafe { msg_send![self, setResolveTexture: resolve_texture] } } pub fn resolve_level(&self) -> NSUInteger { - unsafe { - msg_send![self, resolveLevel] - } + unsafe { msg_send![self, resolveLevel] } } pub fn set_resolve_level(&self, resolve_level: NSUInteger) { - unsafe { - msg_send![self, setResolveLevel:resolve_level] - } + unsafe { msg_send![self, setResolveLevel: resolve_level] } } pub fn resolve_slice(&self) -> NSUInteger { - unsafe { - msg_send![self, resolveSlice] - } + unsafe { msg_send![self, resolveSlice] } } pub fn set_resolve_slice(&self, resolve_slice: NSUInteger) { - unsafe { - msg_send![self, setResolveSlice:resolve_slice] - } + unsafe { msg_send![self, setResolveSlice: resolve_slice] } } pub fn resolve_depth_plane(&self) -> NSUInteger { - unsafe { - msg_send![self, resolveDepthPlane] - } + unsafe { msg_send![self, resolveDepthPlane] } } pub fn set_resolve_depth_plane(&self, resolve_depth_plane: NSUInteger) { - unsafe { - msg_send![self, setResolveDepthPlane:resolve_depth_plane] - } + unsafe { msg_send![self, setResolveDepthPlane: resolve_depth_plane] } } pub fn load_action(&self) -> MTLLoadAction { - unsafe { - msg_send![self, loadAction] - } + unsafe { msg_send![self, loadAction] } } pub fn set_load_action(&self, load_action: MTLLoadAction) { - unsafe { - msg_send![self, setLoadAction:load_action] - } + unsafe { msg_send![self, setLoadAction: load_action] } } pub fn store_action(&self) -> MTLStoreAction { - unsafe { - msg_send![self, storeAction] - } + unsafe { msg_send![self, storeAction] } } pub fn set_store_action(&self, store_action: MTLStoreAction) { - unsafe { - msg_send![self, setStoreAction:store_action] - } + unsafe { msg_send![self, setStoreAction: store_action] } } } @@ -199,15 +166,11 @@ impl RenderPassColorAttachmentDescriptor { impl RenderPassColorAttachmentDescriptorRef { pub fn clear_color(&self) -> MTLClearColor { - unsafe { - msg_send![self, clearColor] - } + unsafe { msg_send![self, clearColor] } } pub fn set_clear_color(&self, clear_color: MTLClearColor) { - unsafe { - msg_send![self, setClearColor:clear_color] - } + unsafe { msg_send![self, setClearColor: clear_color] } } } @@ -222,15 +185,11 @@ foreign_obj_type! { impl RenderPassDepthAttachmentDescriptorRef { pub fn clear_depth(&self) -> f64 { - unsafe { - msg_send![self, clearDepth] - } + unsafe { msg_send![self, clearDepth] } } pub fn set_clear_depth(&self, clear_depth: f64) { - unsafe { - msg_send![self, setClearDepth:clear_depth] - } + unsafe { msg_send![self, setClearDepth: clear_depth] } } } @@ -245,15 +204,22 @@ foreign_obj_type! { impl RenderPassStencilAttachmentDescriptorRef { pub fn clear_stencil(&self) -> u32 { - unsafe { - msg_send![self, clearStencil] - } + unsafe { msg_send![self, clearStencil] } } pub fn set_clear_stencil(&self, clear_stencil: u32) { - unsafe { - msg_send![self, setClearStencil:clear_stencil] - } + unsafe { msg_send![self, setClearStencil: clear_stencil] } + } + + pub fn stencil_resolve_filter(&self) -> MTLMultisampleStencilResolveFilter { + unsafe { msg_send![self, stencilResolveFilter] } + } + + pub fn set_stencil_resolve_filter( + &self, + stencil_resolve_filter: MTLMultisampleStencilResolveFilter, + ) { + unsafe { msg_send![self, setStencilResolveFilter: stencil_resolve_filter] } } } @@ -267,12 +233,14 @@ foreign_obj_type! { impl RenderPassColorAttachmentDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&RenderPassColorAttachmentDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } - pub fn set_object_at(&self, index: usize, attachment: Option<&RenderPassColorAttachmentDescriptorRef>) { + pub fn set_object_at( + &self, + index: usize, + attachment: Option<&RenderPassColorAttachmentDescriptorRef>, + ) { unsafe { msg_send![self, setObject:attachment atIndexedSubscript:index] @@ -299,56 +267,44 @@ impl RenderPassDescriptor { impl RenderPassDescriptorRef { pub fn color_attachments(&self) -> &RenderPassColorAttachmentDescriptorArrayRef { - unsafe { - msg_send![self, colorAttachments] - } + unsafe { msg_send![self, colorAttachments] } } pub fn depth_attachment(&self) -> Option<&RenderPassDepthAttachmentDescriptorRef> { - unsafe { - msg_send![self, depthAttachment] - } + unsafe { msg_send![self, depthAttachment] } } - pub fn set_depth_attachment(&self, depth_attachment: Option<&RenderPassDepthAttachmentDescriptorRef>) { - unsafe { - msg_send![self, setDepthAttachment:depth_attachment] - } + pub fn set_depth_attachment( + &self, + depth_attachment: Option<&RenderPassDepthAttachmentDescriptorRef>, + ) { + unsafe { msg_send![self, setDepthAttachment: depth_attachment] } } pub fn stencil_attachment(&self) -> Option<&RenderPassStencilAttachmentDescriptorRef> { - unsafe { - msg_send![self, stencilAttachment] - } + unsafe { msg_send![self, stencilAttachment] } } - pub fn set_stencil_attachment(&self, stencil_attachment: Option<&RenderPassStencilAttachmentDescriptorRef>) { - unsafe { - msg_send![self, setStencilAttachment:stencil_attachment] - } + pub fn set_stencil_attachment( + &self, + stencil_attachment: Option<&RenderPassStencilAttachmentDescriptorRef>, + ) { + unsafe { msg_send![self, setStencilAttachment: stencil_attachment] } } pub fn visibility_result_buffer(&self) -> Option<&BufferRef> { - unsafe { - msg_send![self, visibilityResultBuffer] - } + unsafe { msg_send![self, visibilityResultBuffer] } } pub fn set_visibility_result_buffer(&self, buffer: Option<&BufferRef>) { - unsafe { - msg_send![self, setVisibilityResultBuffer:buffer] - } + unsafe { msg_send![self, setVisibilityResultBuffer: buffer] } } pub fn render_target_array_length(&self) -> NSUInteger { - unsafe { - msg_send![self, renderTargetArrayLength] - } + unsafe { msg_send![self, renderTargetArrayLength] } } pub fn set_render_target_array_length(&self, length: NSUInteger) { - unsafe { - msg_send![self, setRenderTargetArrayLength:length] - } + unsafe { msg_send![self, setRenderTargetArrayLength: length] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/resource.rs b/third_party/cargo/vendor/metal-0.17.1/src/resource.rs similarity index 85% rename from third_party/cargo/vendor/metal-0.13.1/src/resource.rs rename to third_party/cargo/vendor/metal-0.17.1/src/resource.rs index d8a3c33..f8af9ab 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/resource.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/resource.rs @@ -6,7 +6,6 @@ // copied, modified, or distributed except according to those terms. use cocoa::foundation::NSUInteger; -use objc_foundation::{NSString, INSString}; #[repr(u64)] #[allow(non_camel_case_types)] @@ -30,7 +29,7 @@ pub enum MTLCPUCacheMode { #[allow(non_camel_case_types)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum MTLStorageMode { - Shared = 0, + Shared = 0, Managed = 1, Private = 2, Memoryless = 3, @@ -80,33 +79,27 @@ foreign_obj_type! { impl ResourceRef { pub fn label(&self) -> &str { unsafe { - let label: &NSString = msg_send![self, label]; - label.as_str() + let label = msg_send![self, label]; + crate::nsstring_as_str(label) } } pub fn set_label(&self, label: &str) { unsafe { - let nslabel = NSString::from_str(label); - msg_send![self, setLabel:nslabel] + let nslabel = crate::nsstring_from_str(label); + let () = msg_send![self, setLabel: nslabel]; } } pub fn cpu_cache_mode(&self) -> MTLCPUCacheMode { - unsafe { - msg_send![self, cpuCacheMode] - } + unsafe { msg_send![self, cpuCacheMode] } } pub fn storage_mode(&self) -> MTLStorageMode { - unsafe { - msg_send![self, storageMode] - } + unsafe { msg_send![self, storageMode] } } pub fn set_purgeable_state(&self, state: MTLPurgeableState) -> MTLPurgeableState { - unsafe { - msg_send![self, setPurgeableState:state] - } + unsafe { msg_send![self, setPurgeableState: state] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/sampler.rs b/third_party/cargo/vendor/metal-0.17.1/src/sampler.rs similarity index 67% rename from third_party/cargo/vendor/metal-0.13.1/src/sampler.rs rename to third_party/cargo/vendor/metal-0.17.1/src/sampler.rs index 1c073b0..d284b99 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/sampler.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/sampler.rs @@ -7,7 +7,7 @@ use cocoa::foundation::NSUInteger; -use depthstencil::MTLCompareFunction; +use crate::depthstencil::MTLCompareFunction; #[repr(u64)] #[derive(Copy, Clone)] @@ -32,7 +32,7 @@ pub enum MTLSamplerAddressMode { Repeat = 2, MirrorRepeat = 3, ClampToZero = 4, - ClampToBorderColor = 5 + ClampToBorderColor = 5, } #[repr(u64)] @@ -51,7 +51,6 @@ foreign_obj_type! { pub struct SamplerDescriptorRef; } - impl SamplerDescriptor { pub fn new() -> Self { unsafe { @@ -63,92 +62,64 @@ impl SamplerDescriptor { impl SamplerDescriptorRef { pub fn set_min_filter(&self, filter: MTLSamplerMinMagFilter) { - unsafe { - msg_send![self, setMinFilter:filter] - } + unsafe { msg_send![self, setMinFilter: filter] } } pub fn set_mag_filter(&self, filter: MTLSamplerMinMagFilter) { - unsafe { - msg_send![self, setMagFilter:filter] - } + unsafe { msg_send![self, setMagFilter: filter] } } pub fn set_mip_filter(&self, filter: MTLSamplerMipFilter) { - unsafe { - msg_send![self, setMipFilter:filter] - } + unsafe { msg_send![self, setMipFilter: filter] } } pub fn set_address_mode_s(&self, mode: MTLSamplerAddressMode) { - unsafe { - msg_send![self, setSAddressMode:mode] - } + unsafe { msg_send![self, setSAddressMode: mode] } } pub fn set_address_mode_t(&self, mode: MTLSamplerAddressMode) { - unsafe { - msg_send![self, setTAddressMode:mode] - } + unsafe { msg_send![self, setTAddressMode: mode] } } pub fn set_address_mode_r(&self, mode: MTLSamplerAddressMode) { - unsafe { - msg_send![self, setRAddressMode:mode] - } + unsafe { msg_send![self, setRAddressMode: mode] } } pub fn set_max_anisotropy(&self, anisotropy: NSUInteger) { - unsafe { - msg_send![self, setMaxAnisotropy:anisotropy] - } + unsafe { msg_send![self, setMaxAnisotropy: anisotropy] } } pub fn set_compare_function(&self, func: MTLCompareFunction) { - unsafe { - msg_send![self, setCompareFunction:func] - } + unsafe { msg_send![self, setCompareFunction: func] } } #[cfg(feature = "private")] pub unsafe fn set_lod_bias(&self, bias: f32) { - msg_send![self, setLodBias:bias] + msg_send![self, setLodBias: bias] } pub fn set_lod_min_clamp(&self, clamp: f32) { - unsafe { - msg_send![self, setLodMinClamp:clamp] - } + unsafe { msg_send![self, setLodMinClamp: clamp] } } pub fn set_lod_max_clamp(&self, clamp: f32) { - unsafe { - msg_send![self, setLodMaxClamp:clamp] - } + unsafe { msg_send![self, setLodMaxClamp: clamp] } } pub fn set_lod_average(&self, enable: bool) { - unsafe { - msg_send![self, setLodAverage:enable] - } + unsafe { msg_send![self, setLodAverage: enable] } } pub fn set_normalized_coordinates(&self, enable: bool) { - unsafe { - msg_send![self, setNormalizedCoordinates:enable] - } + unsafe { msg_send![self, setNormalizedCoordinates: enable] } } pub fn set_support_argument_buffers(&self, enable: bool) { - unsafe { - msg_send![self, setSupportArgumentBuffers:enable] - } + unsafe { msg_send![self, setSupportArgumentBuffers: enable] } } pub fn set_border_color(&self, color: MTLSamplerBorderColor) { - unsafe { - msg_send![self, setBorderColor:color] - } + unsafe { msg_send![self, setBorderColor: color] } } } diff --git a/third_party/cargo/vendor/metal-0.13.1/src/texture.rs b/third_party/cargo/vendor/metal-0.17.1/src/texture.rs similarity index 58% rename from third_party/cargo/vendor/metal-0.13.1/src/texture.rs rename to third_party/cargo/vendor/metal-0.17.1/src/texture.rs index ef0834c..ce0e549 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/texture.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/texture.rs @@ -7,10 +7,8 @@ use super::*; -use cocoa::foundation::{NSUInteger, NSRange}; -use objc::runtime::{YES, NO}; - -use libc; +use cocoa::foundation::{NSRange, NSUInteger}; +use objc::runtime::{NO, YES}; #[repr(u64)] #[allow(non_camel_case_types)] @@ -55,147 +53,99 @@ impl TextureDescriptor { impl TextureDescriptorRef { pub fn texture_type(&self) -> MTLTextureType { - unsafe { - msg_send![self, textureType] - } + unsafe { msg_send![self, textureType] } } pub fn set_texture_type(&self, texture_type: MTLTextureType) { - unsafe { - msg_send![self, setTextureType:texture_type] - } + unsafe { msg_send![self, setTextureType: texture_type] } } pub fn pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, pixelFormat] - } + unsafe { msg_send![self, pixelFormat] } } pub fn set_pixel_format(&self, pixel_format: MTLPixelFormat) { - unsafe { - msg_send![self, setPixelFormat:pixel_format] - } + unsafe { msg_send![self, setPixelFormat: pixel_format] } } pub fn width(&self) -> NSUInteger { - unsafe { - msg_send![self, width] - } + unsafe { msg_send![self, width] } } pub fn set_width(&self, width: NSUInteger) { - unsafe { - msg_send![self, setWidth:width] - } + unsafe { msg_send![self, setWidth: width] } } pub fn height(&self) -> NSUInteger { - unsafe { - msg_send![self, height] - } + unsafe { msg_send![self, height] } } pub fn set_height(&self, height: NSUInteger) { - unsafe { - msg_send![self, setHeight:height] - } + unsafe { msg_send![self, setHeight: height] } } pub fn depth(&self) -> NSUInteger { - unsafe { - msg_send![self, depth] - } + unsafe { msg_send![self, depth] } } pub fn set_depth(&self, depth: NSUInteger) { - unsafe { - msg_send![self, setDepth:depth] - } + unsafe { msg_send![self, setDepth: depth] } } pub fn mipmap_level_count(&self) -> NSUInteger { - unsafe { - msg_send![self, mipmapLevelCount] - } + unsafe { msg_send![self, mipmapLevelCount] } } pub fn set_mipmap_level_count(&self, count: NSUInteger) { - unsafe { - msg_send![self, setMipmapLevelCount:count] - } + unsafe { msg_send![self, setMipmapLevelCount: count] } } pub fn sample_count(&self) -> NSUInteger { - unsafe { - msg_send![self, sampleCount] - } + unsafe { msg_send![self, sampleCount] } } pub fn set_sample_count(&self, count: NSUInteger) { - unsafe { - msg_send![self, setSampleCount:count] - } + unsafe { msg_send![self, setSampleCount: count] } } pub fn array_length(&self) -> NSUInteger { - unsafe { - msg_send![self, arrayLength] - } + unsafe { msg_send![self, arrayLength] } } pub fn set_array_length(&self, length: NSUInteger) { - unsafe { - msg_send![self, setArrayLength:length] - } + unsafe { msg_send![self, setArrayLength: length] } } pub fn resource_options(&self) -> MTLResourceOptions { - unsafe { - msg_send![self, resourceOptions] - } + unsafe { msg_send![self, resourceOptions] } } pub fn set_resource_options(&self, options: MTLResourceOptions) { - unsafe { - msg_send![self, setResourceOptions:options] - } + unsafe { msg_send![self, setResourceOptions: options] } } pub fn cpu_cache_mode(&self) -> MTLCPUCacheMode { - unsafe { - msg_send![self, cpuCacheMode] - } + unsafe { msg_send![self, cpuCacheMode] } } pub fn set_cpu_cache_mode(&self, mode: MTLCPUCacheMode) { - unsafe { - msg_send![self, setCpuCacheMode:mode] - } + unsafe { msg_send![self, setCpuCacheMode: mode] } } pub fn storage_mode(&self) -> MTLStorageMode { - unsafe { - msg_send![self, storageMode] - } + unsafe { msg_send![self, storageMode] } } pub fn set_storage_mode(&self, mode: MTLStorageMode) { - unsafe { - msg_send![self, setStorageMode:mode] - } + unsafe { msg_send![self, setStorageMode: mode] } } pub fn usage(&self) -> MTLTextureUsage { - unsafe { - msg_send![self, usage] - } + unsafe { msg_send![self, usage] } } pub fn set_usage(&self, usage: MTLTextureUsage) { - unsafe { - msg_send![self, setUsage:usage] - } + unsafe { msg_send![self, setUsage: usage] } } } @@ -209,101 +159,69 @@ foreign_obj_type! { } impl TextureRef { - #[deprecated(since="0.13.0")] + #[deprecated(since = "0.13.0")] pub fn root_resource(&self) -> Option<&ResourceRef> { - unsafe { - msg_send![self, rootResource] - } + unsafe { msg_send![self, rootResource] } } pub fn parent_texture(&self) -> Option<&TextureRef> { - unsafe { - msg_send![self, parentTexture] - } + unsafe { msg_send![self, parentTexture] } } pub fn parent_relative_level(&self) -> NSUInteger { - unsafe { - msg_send![self, parentRelativeLevel] - } + unsafe { msg_send![self, parentRelativeLevel] } } pub fn parent_relative_slice(&self) -> NSUInteger { - unsafe { - msg_send![self, parentRelativeSlice] - } + unsafe { msg_send![self, parentRelativeSlice] } } pub fn buffer(&self) -> Option<&BufferRef> { - unsafe { - msg_send![self, buffer] - } + unsafe { msg_send![self, buffer] } } pub fn buffer_offset(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferOffset] - } + unsafe { msg_send![self, bufferOffset] } } pub fn buffer_stride(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferBytesPerRow] - } + unsafe { msg_send![self, bufferBytesPerRow] } } pub fn texture_type(&self) -> MTLTextureType { - unsafe { - msg_send![self, textureType] - } + unsafe { msg_send![self, textureType] } } pub fn pixel_format(&self) -> MTLPixelFormat { - unsafe { - msg_send![self, pixelFormat] - } + unsafe { msg_send![self, pixelFormat] } } pub fn width(&self) -> NSUInteger { - unsafe { - msg_send![self, width] - } + unsafe { msg_send![self, width] } } pub fn height(&self) -> NSUInteger { - unsafe { - msg_send![self, height] - } + unsafe { msg_send![self, height] } } pub fn depth(&self) -> NSUInteger { - unsafe { - msg_send![self, depth] - } + unsafe { msg_send![self, depth] } } pub fn mipmap_level_count(&self) -> NSUInteger { - unsafe { - msg_send![self, mipmapLevelCount] - } + unsafe { msg_send![self, mipmapLevelCount] } } pub fn sample_count(&self) -> NSUInteger { - unsafe { - msg_send![self, sampleCount] - } + unsafe { msg_send![self, sampleCount] } } pub fn array_length(&self) -> NSUInteger { - unsafe { - msg_send![self, arrayLength] - } + unsafe { msg_send![self, arrayLength] } } pub fn usage(&self) -> MTLTextureUsage { - unsafe { - msg_send![self, usage] - } + unsafe { msg_send![self, usage] } } pub fn framebuffer_only(&self) -> bool { @@ -311,12 +229,18 @@ impl TextureRef { match msg_send![self, framebufferOnly] { YES => true, NO => false, - _ => unreachable!() + _ => unreachable!(), } } } - pub fn get_bytes(&self, bytes: *mut libc::c_void, region: MTLRegion, mipmap_level: NSUInteger, stride: NSUInteger) { + pub fn get_bytes( + &self, + bytes: *mut std::ffi::c_void, + region: MTLRegion, + mipmap_level: NSUInteger, + stride: NSUInteger, + ) { unsafe { msg_send![self, getBytes:bytes bytesPerRow:stride @@ -325,7 +249,15 @@ impl TextureRef { } } - pub fn get_bytes_in_slice(&self, bytes: *mut libc::c_void, region: MTLRegion, mipmap_level: NSUInteger, stride: NSUInteger, image_stride: NSUInteger, slice: NSUInteger) { + pub fn get_bytes_in_slice( + &self, + bytes: *mut std::ffi::c_void, + region: MTLRegion, + mipmap_level: NSUInteger, + stride: NSUInteger, + image_stride: NSUInteger, + slice: NSUInteger, + ) { unsafe { msg_send![self, getBytes:bytes bytesPerRow:stride @@ -336,7 +268,13 @@ impl TextureRef { } } - pub fn replace_region(&self, region: MTLRegion, mipmap_level: NSUInteger, stride: NSUInteger, bytes: *const libc::c_void) { + pub fn replace_region( + &self, + region: MTLRegion, + mipmap_level: NSUInteger, + stride: NSUInteger, + bytes: *const std::ffi::c_void, + ) { unsafe { msg_send![self, replaceRegion:region mipmapLevel:mipmap_level @@ -345,7 +283,15 @@ impl TextureRef { } } - pub fn replace_region_in_slice(&self, region: MTLRegion, mipmap_level: NSUInteger, image_stride: NSUInteger, stride: NSUInteger, slice: NSUInteger, bytes: *const libc::c_void) { + pub fn replace_region_in_slice( + &self, + region: MTLRegion, + mipmap_level: NSUInteger, + image_stride: NSUInteger, + stride: NSUInteger, + slice: NSUInteger, + bytes: *const std::ffi::c_void, + ) { unsafe { msg_send![self, replaceRegion:region mipmapLevel:mipmap_level @@ -357,12 +303,16 @@ impl TextureRef { } pub fn new_texture_view(&self, pixel_format: MTLPixelFormat) -> Texture { - unsafe { - msg_send![self, newTextureViewWithPixelFormat:pixel_format] - } + unsafe { msg_send![self, newTextureViewWithPixelFormat: pixel_format] } } - pub fn new_texture_view_from_slice(&self, pixel_format: MTLPixelFormat, texture_type: MTLTextureType, mipmap_levels: NSRange, slices: NSRange) -> Texture { + pub fn new_texture_view_from_slice( + &self, + pixel_format: MTLPixelFormat, + texture_type: MTLTextureType, + mipmap_levels: NSRange, + slices: NSRange, + ) -> Texture { unsafe { msg_send![self, newTextureViewWithPixelFormat:pixel_format textureType:texture_type diff --git a/third_party/cargo/vendor/metal-0.13.1/src/types.rs b/third_party/cargo/vendor/metal-0.17.1/src/types.rs similarity index 77% rename from third_party/cargo/vendor/metal-0.13.1/src/types.rs rename to third_party/cargo/vendor/metal-0.17.1/src/types.rs index 6f4cf26..aa253b9 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/types.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/types.rs @@ -5,14 +5,14 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use cocoa::foundation::{NSUInteger}; +use cocoa::foundation::NSUInteger; #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct MTLOrigin { pub x: NSUInteger, pub y: NSUInteger, - pub z: NSUInteger + pub z: NSUInteger, } #[repr(C)] @@ -20,13 +20,19 @@ pub struct MTLOrigin { pub struct MTLSize { pub width: NSUInteger, pub height: NSUInteger, - pub depth: NSUInteger + pub depth: NSUInteger, } #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct MTLRegion { pub origin: MTLOrigin, - pub size: MTLSize + pub size: MTLSize, } +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct MTLSamplePosition { + pub x: f32, + pub y: f32, +} diff --git a/third_party/cargo/vendor/metal-0.13.1/src/vertexdescriptor.rs b/third_party/cargo/vendor/metal-0.17.1/src/vertexdescriptor.rs similarity index 79% rename from third_party/cargo/vendor/metal-0.13.1/src/vertexdescriptor.rs rename to third_party/cargo/vendor/metal-0.17.1/src/vertexdescriptor.rs index 49d0e23..2ff2c06 100644 --- a/third_party/cargo/vendor/metal-0.13.1/src/vertexdescriptor.rs +++ b/third_party/cargo/vendor/metal-0.17.1/src/vertexdescriptor.rs @@ -7,9 +7,6 @@ use cocoa::foundation::NSUInteger; -#[cfg(feature = "private")] -use libc; - #[repr(u64)] #[allow(non_camel_case_types)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -86,7 +83,7 @@ foreign_obj_type! { } impl VertexBufferLayoutDescriptor { - pub fn new () -> Self { + pub fn new() -> Self { unsafe { let class = class!(MTLVertexBufferLayoutDescriptor); msg_send![class, new] @@ -96,39 +93,27 @@ impl VertexBufferLayoutDescriptor { impl VertexBufferLayoutDescriptorRef { pub fn stride(&self) -> NSUInteger { - unsafe { - msg_send![self, stride] - } + unsafe { msg_send![self, stride] } } pub fn set_stride(&self, stride: NSUInteger) { - unsafe { - msg_send![self, setStride:stride] - } + unsafe { msg_send![self, setStride: stride] } } pub fn step_function(&self) -> MTLVertexStepFunction { - unsafe { - msg_send![self, stepFunction] - } + unsafe { msg_send![self, stepFunction] } } pub fn set_step_function(&self, func: MTLVertexStepFunction) { - unsafe { - msg_send![self, setStepFunction:func] - } + unsafe { msg_send![self, setStepFunction: func] } } pub fn step_rate(&self) -> NSUInteger { - unsafe { - msg_send![self, stepRate] - } + unsafe { msg_send![self, stepRate] } } pub fn set_step_rate(&self, step_rate: NSUInteger) { - unsafe { - msg_send![self, setStepRate:step_rate] - } + unsafe { msg_send![self, setStepRate: step_rate] } } } @@ -142,9 +127,7 @@ foreign_obj_type! { impl VertexBufferLayoutDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&VertexBufferLayoutDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } pub fn set_object_at(&self, index: usize, layout: Option<&VertexBufferLayoutDescriptorRef>) { @@ -174,39 +157,27 @@ impl VertexAttributeDescriptor { impl VertexAttributeDescriptorRef { pub fn format(&self) -> MTLVertexFormat { - unsafe { - msg_send![self, format] - } + unsafe { msg_send![self, format] } } pub fn set_format(&self, format: MTLVertexFormat) { - unsafe { - msg_send![self, setFormat:format] - } + unsafe { msg_send![self, setFormat: format] } } pub fn offset(&self) -> NSUInteger { - unsafe { - msg_send![self, offset] - } + unsafe { msg_send![self, offset] } } pub fn set_offset(&self, offset: NSUInteger) { - unsafe { - msg_send![self, setOffset:offset] - } + unsafe { msg_send![self, setOffset: offset] } } pub fn buffer_index(&self) -> NSUInteger { - unsafe { - msg_send![self, bufferIndex] - } + unsafe { msg_send![self, bufferIndex] } } pub fn set_buffer_index(&self, index: NSUInteger) { - unsafe { - msg_send![self, setBufferIndex:index] - } + unsafe { msg_send![self, setBufferIndex: index] } } } @@ -220,9 +191,7 @@ foreign_obj_type! { impl VertexAttributeDescriptorArrayRef { pub fn object_at(&self, index: usize) -> Option<&VertexAttributeDescriptorRef> { - unsafe { - msg_send![self, objectAtIndexedSubscript:index] - } + unsafe { msg_send![self, objectAtIndexedSubscript: index] } } pub fn set_object_at(&self, index: usize, attribute: Option<&VertexAttributeDescriptorRef>) { @@ -252,25 +221,19 @@ impl VertexDescriptor { impl VertexDescriptorRef { pub fn layouts(&self) -> &VertexBufferLayoutDescriptorArrayRef { - unsafe { - msg_send![self, layouts] - } + unsafe { msg_send![self, layouts] } } pub fn attributes(&self) -> &VertexAttributeDescriptorArrayRef { - unsafe { - msg_send![self, attributes] - } + unsafe { msg_send![self, attributes] } } #[cfg(feature = "private")] - pub unsafe fn serialize_descriptor(&self) -> *mut libc::c_void { + pub unsafe fn serialize_descriptor(&self) -> *mut std::ffi::c_void { msg_send![self, newSerializedDescriptor] } pub fn reset(&self) { - unsafe { - msg_send![self, reset] - } + unsafe { msg_send![self, reset] } } } diff --git a/third_party/cargo/vendor/mio-0.6.21/.cargo-checksum.json b/third_party/cargo/vendor/mio-0.6.21/.cargo-checksum.json new file mode 100644 index 0000000..9cfde5c --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"251757dda7b07df5b67d078c03941415d35b56f26995349fd2ee69ff0af16efe","Cargo.toml":"aef5f1abd28b0ef807250dc0b9c490aefc68fab85d633fd0384fa0545747eb89","LICENSE":"07919255c7e04793d8ea760d6c2ce32d19f9ff02bdbdde3ce90b1e1880929a9b","README.md":"eedc84973c97348ea27f93ac7d3232098438d4455c7eaedf6fcc7f105ac9f321","azure-pipelines.yml":"5054467a3d39887027cd680e27cbb9187347ff3f08546e9cafe4d95a1803d635","benches/bench_poll.rs":"dce8529e42e2e2497e91c7610ea2ef4b0dd72b114d329df17ddd90ffec1c04e6","ci/azure-cross-compile.yml":"16d9c0e770caf6a7f06f4bd6874ad244706b878c2822f8e78b7e647b6645fea4","ci/azure-deploy-docs.yml":"b87048ae366067ffe1fd869867927d27cc86b3d26866aa9223228bd1b528073e","ci/azure-install-rust.yml":"6ac24477b6d516823de794fc537c4484b6373d7f32b402e5afc02e5e6b272ae9","ci/azure-test-stable.yml":"86ec2f72251fa66c9954ae137c53d678df76cf66a28d24ab3bb232d01ed89570","src/channel.rs":"b16493a2b74334156e153b1f4143b0e98d43cd4d7bff0275066dfa575dde2402","src/deprecated/event_loop.rs":"ba931d256e6e57d5635c6cfc6e3a4add4551c87f16457d901b334a129f9cf41d","src/deprecated/handler.rs":"13cbc0c193f43a331e125e05d5eddf3712fe86e41a8721186d3672518ef8a9cc","src/deprecated/io.rs":"4948217ffeeba4f508cc89744da5d6af858b4ad7b4be23f927a00df93bdf2984","src/deprecated/mod.rs":"4310471b5a1313dbf53b492769a3031b15353eb269333b7c1a890bc2709def7c","src/deprecated/notify.rs":"8cb108387ebcfb75764e4dd2868d80eb00d793c4b7c867c08cd86ef10b91b023","src/deprecated/unix.rs":"76c832e7db8263395b576930186fe1a3c472589bed41810d445d89f0eed684eb","src/event_imp.rs":"f8cff47dedc52dab9c7cc2d707f2c2d86d7185f942f02ace4c60353cc6094035","src/io.rs":"9207ffc93ea744b09bc6872fa4d378d7c75640f9ac38b1fa67b940c7cb5d0ade","src/lazycell.rs":"871dbd89f6918a354c2ec2d2a8b89e4aa30754e7e3e8dfcf2f5a6071156e39cf","src/lib.rs":"e8ff126d978b128f93b57ddab0aa9230f414b11ce1a255e957151db3c8b69be3","src/net/mod.rs":"340c63a8efe9ee774b7bf8ed8c0f72fc7563e5c4b35f6a8b243f92d366e145a2","src/net/tcp.rs":"8b06dc8d2dd9fb7cd52db582fd7fe608b6a50cdf7ce18cf0abb9992956e95f6d","src/net/udp.rs":"8b5728924a07917d2845bbfb060cadb842b36a74d5372ac7707eb7f169a67d4d","src/poll.rs":"e76bb316deedbd9306f91ca8ab394d02b5676fa767746bd9770c5c9dff490426","src/sys/fuchsia/awakener.rs":"71a4a0083242457b0a96326c69c0f98b23dfdb97be96deb26ee02fa9d1dfb212","src/sys/fuchsia/eventedfd.rs":"bd8f43d2b61cdd6a5d0df9c0dc1cb43e1708140d01a05611055277ed55a33b63","src/sys/fuchsia/handles.rs":"161a69e8a8d7f71326a9c53bcb7685d0a81d184aba8e20da27c64aa27dfd56b2","src/sys/fuchsia/mod.rs":"9d80f1214abc93f48b6b6c12ce5b6cfaddbda592c8f3410564d0237228cae2d0","src/sys/fuchsia/net.rs":"50340191dd9cbe317bd6e6ae0170c03daa9141f15c96782b96484e3d8b8301b1","src/sys/fuchsia/ready.rs":"7e6bb7235c52ab4a2134d36cf982f6a4fd6e18050e737b40ee84c89a10a9faac","src/sys/fuchsia/selector.rs":"f3be7f8d683d43e4a8313246e4cacb9444549bf66ecb2234f0d0f53172043bf5","src/sys/mod.rs":"64bea046e4a9feb1f2e2fb8326452c1be8b9d56cf8794df0af4fbdf565204255","src/sys/unix/awakener.rs":"20a61d8f39b2f2abf4f166a3ed46fa0d79907ddf92758eaddb880c67321db56c","src/sys/unix/dlsym.rs":"559337d1f6c10e6c1172bd3908a9dcfa5a0828b53b04f7ca3a0d926afa85cd63","src/sys/unix/epoll.rs":"ea87ff5490616a8536878394201e8e3a1443746a7a3408a889c45d3cbd767f81","src/sys/unix/eventedfd.rs":"a0bd2096ab5acf42c48110f024bc8ea052ba62c707345c7db46fea7a494388df","src/sys/unix/io.rs":"a518f09020f821e87bcf9c2ecb4bf501d428619ddfd7b35a26629b614919b14c","src/sys/unix/kqueue.rs":"3bf9f9635a8607569e3176998b61d1801e5bb35a94588c827a0a954656eee3ea","src/sys/unix/mod.rs":"bb2bc586283c7a1cc0b739e4fd37ed3022602a562a2255f6c2fb2ac5d74bee17","src/sys/unix/ready.rs":"b77c8dba00cec1c8130c048879f7e8d294e488ca364f8a8e8ec474afe8045724","src/sys/unix/tcp.rs":"19d483762fc8c8a1cb182b2f2ead85534f99394cf605a14d5ed46db7f3354667","src/sys/unix/udp.rs":"bc2e8ad142b17797a7d038e720ff57ac9840eb5b2b26696c854180085ccd1873","src/sys/unix/uds.rs":"5223d4d35048019d175679686cc65a08baf027df0b2127428e2f322bbb533309","src/sys/unix/uio.rs":"3942a49548dd3a37e5fd6044a103d92e2635965ace1ab370be10c82245b41f66","src/sys/windows/awakener.rs":"2d3cdaf8b523675e2f64c5fd81e1197d5255384517b9753b718c5c47acf0cabd","src/sys/windows/buffer_pool.rs":"636f4b7510a507f9985987699ce8ec140b2ed852abb231443ee1486c80759eed","src/sys/windows/from_raw_arc.rs":"659dabdf5037546e3783aacc422992b4248b0ba2ddcce52b149d35bc723550e5","src/sys/windows/mod.rs":"afeec8cd4e3adeaf6ffe68b134ad1b4ba07faa3abae96f6f9a00bbc20ff5f2c5","src/sys/windows/selector.rs":"0137276cff457f84511e007bb9527f5e082ec04e898b8f8e0acd39fe65c00148","src/sys/windows/tcp.rs":"9942db351f91229d01a0b9f52dd6c9680050d3abcee9fbb6b4f2f14896dc2c58","src/sys/windows/udp.rs":"1ef869b660bcf89ea6498552474abf8f540946631e14d5b610ca31014cd9045f","src/timer.rs":"540d521c5b4a79f3b1c01296ef2e14e2e3743192f25180ee6e71e367692ce762","src/token.rs":"4a56f851709470df2eed803c57c68b0a4b12ea86fa1b8d2c999bec7a85d58ec0","src/udp.rs":"442e620f3ea0cf010497d3ad775debd585f28e79a025993d40471c8e6839dc98","test/benchmark.rs":"d655cd4a79b11555df4d46e929134d73f2e49e174a59f66b98904a6b9a2779e3","test/mod.rs":"15306dec0d939312ab36a181f609393d8cb1ebac4d048b8f0275fc056776074f","test/test_battery.rs":"a50e14eb3d2d914bdd1ddc8501a32fae757add51c1c5388350eb4a06b6456509","test/test_broken_pipe.rs":"1e8352a22a8b3fe170aa8bb942dc4a2ddd0fb5e69374733e6bcfa324481da648","test/test_close_on_drop.rs":"5ca1dece36ba37600d474d6e4da2495bb48946d37c17914bb682ffa8a4671702","test/test_custom_evented.rs":"f6dcfbfc5d7d44937e16bc333869f1fbd09f46c3c334135ca79df95b02415e27","test/test_double_register.rs":"f48b1b5aee68f0c3fef8895c8b9f2cf2446e670f3d0e7249ec300067df783617","test/test_echo_server.rs":"34d35e80029c03f276139a10320426ac0b95ff5d1d95d5cbc93474498adac31b","test/test_fuchsia_handles.rs":"1e4fc0920b4067a4ece7487067af4f6e3f18e8e55b0fd636ccc2d333f8ade70f","test/test_local_addr_ready.rs":"0a9cd42cb43b5afcc139b1def8278f2a24834e40f96c4ea69f05c4f3263f7c65","test/test_multicast.rs":"2a0ae0c99e80dddea3088fd639af22204d63f3bb2dad2bcdf1389ac97639d620","test/test_notify.rs":"3e730ae1c4eaf3453c6e46f514eb266ce119dec5543e46a2b5125a3d5eb5cd65","test/test_oneshot.rs":"3f618c167734b1ce4695691955fb01224c6abf0a1cc1e1db9e01248fb9edbd3c","test/test_poll.rs":"ad450ff65e9ab8108d424b3b8cf4c82847fb9927f12e749f0aee1228bd5db7da","test/test_poll_channel.rs":"8414e7d27e32bec5c8ea0341f4f2708eb64853cfb6d28689deb58d90b1619120","test/test_register_deregister.rs":"8fdbf48bbd5f2c84a2685fe4151189a157f148bd13781533e5a84f958a5baaf6","test/test_register_multiple_event_loops.rs":"e0f3115ef938ceed2eae47ea1630c7f440a860b69ab57b70507cf8062fc21eb9","test/test_reregister_without_poll.rs":"30ebba86b936bc283575f8f15237bd1f616ea09516bf34912a27ce6c7b5a5559","test/test_smoke.rs":"f1c4c52509537a76975354dbd9a91e16b14e53f8b30171c57ebf59ff4d935bcc","test/test_subprocess_pipe.rs":"324b68e1cb2d43bec204d41064f6873640cf61970718da3703506f0e5ebad31d","test/test_tcp.rs":"c69f7ffede13e2c9cb2b55490359fd8ec34e79c5797044e4a0051884ede1dc19","test/test_tcp_level.rs":"a76a8b854fe3e3245937c2e80acfb7a6ebb3442701179cd887365d1c27b4bd0d","test/test_tcp_shutdown.rs":"6f095fd7e0af26c61734509cc6e21d080d1f6484dcc3bdd8c954aca4f200f2b3","test/test_tick.rs":"2f3c90e03cac4bcbf70469b631e6ea64053342df3a5715bc30053771a7fdb6de","test/test_udp_level.rs":"c47b99cd614d5115fe59ed3afdbe56e0a4bf16884da7f03bab54ba4a513a3893","test/test_udp_socket.rs":"2c6a8242ea9435b366b70cdd47b318776d61995662e1d6a7077c74b026d8b6ad","test/test_uds_shutdown.rs":"9af7ac437084cb833d97cd9164d29003b45761c36ca0e2bc72bc9affd9590498","test/test_unix_echo_server.rs":"b70a474eceb9f8f320fed218be777b510c3ab8b74dd8959c381e41ed1dbe2929","test/test_unix_pass_fd.rs":"04d8911705047d11c745a2df1ffadff655c032250548e502df85d0b4490305a6","test/test_write_then_drop.rs":"00c91aef8f0b903f480bf0f55857659df6dc9a90f68a477264f62acb179b347f"},"package":"302dec22bcf6bae6dfb69c647187f4b4d0fb6f535521f7bc022430ce8e12008f"} \ No newline at end of file diff --git a/third_party/cargo/vendor/mio-0.6.21/BUILD b/third_party/cargo/vendor/mio-0.6.21/BUILD new file mode 100644 index 0000000..b6110da --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/BUILD @@ -0,0 +1,52 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + +# Unsupported target "bench_poll" with type "bench" omitted + +rust_library( + name = "mio", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", + "//third_party/cargo/vendor/iovec-0.1.4:iovec", + "//third_party/cargo/vendor/libc-0.2.67:libc", + "//third_party/cargo/vendor/log-0.4.8:log", + "//third_party/cargo/vendor/net2-0.2.33:net2", + "//third_party/cargo/vendor/slab-0.4.2:slab", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.6.21", + crate_features = [ + "default", + "with-deprecated", + ], +) + +# Unsupported target "test" with type "test" omitted diff --git a/third_party/cargo/vendor/mio-0.6.21/CHANGELOG.md b/third_party/cargo/vendor/mio-0.6.21/CHANGELOG.md new file mode 100644 index 0000000..556bd90 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/CHANGELOG.md @@ -0,0 +1,208 @@ +# 0.6.21 (November 27, 2019) + +### Fixed +- remove `=` dependency on `cfg-if`. + +# 0.6.20 (November 21, 2019) + +### Fixed +- Use default IOCP concurrency value (#1161). +- setting FD_CLOEXEC in pipe (#1095). + +# 0.6.19 (May 28, 2018) + +### Fixed +- Do not trigger HUP events on kqueue platforms (#958). + +# 0.6.18 (May 24, 2018) + +### Fixed +- Fix compilation on kqueue platforms with 32bit C long (#948). + +# 0.6.17 (May 15, 2018) + +### Fixed +- Don't report `RDHUP` as `HUP` (#939) +- Fix lazycell related compilation issues. +- Fix EPOLLPRI conflicting with READABLE +- Abort process on ref count overflows + +### Added +- Define PRI on all targets + +# 0.6.16 (September 5, 2018) + +* Add EPOLLPRI readiness to UnixReady on supported platforms (#867) +* Reduce spurious awaken calls (#875) + +# 0.6.15 (July 3, 2018) + +* Implement `Evented` for containers (#840). +* Fix android-aarch64 build (#850). + +# 0.6.14 (March 8, 2018) + +* Add `Poll::poll_interruptible` (#811) +* Add `Ready::all` and `usize` conversions (#825) + +# 0.6.13 (February 5, 2018) + +* Fix build on DragonFlyBSD. +* Add `TcpListener::from_std` that does not require the socket addr. +* Deprecate `TcpListener::from_listener` in favor of from_std. + +# 0.6.12 (January 5, 2018) + +* Add `TcpStream::peek` function (#773). +* Raise minimum Rust version to 1.18.0. +* `Poll`: retry select() when interrupted by a signal (#742). +* Deprecate `Events` index access (#713). +* Add `Events::clear` (#782). +* Add support for `lio_listio` (#780). + +# 0.6.11 (October 25, 2017) + +* Allow register to take empty interest (#640). +* Fix bug with TCP errors on windows (#725). +* Add TcpListener::accept_std (#733). +* Update IoVec to fix soundness bug -- includes behavior change. (#747). +* Minimum Rust version is now 1.14.0. +* Fix Android x86_64 build. +* Misc API & doc polish. + +# 0.6.10 (July 27, 2017) + +* Experimental support for Fuchsia +* Add `only_v6` option for UDP sockets +* Fix build on NetBSD +* Minimum Rust version is now 1.13.0 +* Assignment operators (e.g. `|=`) are now implemented for `Ready` + +# 0.6.9 (June 7, 2017) + +* More socket options are exposed through the TCP types, brought in through the + `net2` crate. + +# 0.6.8 (May 26, 2017) + +* Support Fuchia +* POSIX AIO support +* Fix memory leak caused by Register::new2 +* Windows: fix handling failed TCP connections +* Fix build on aarch64-linux-android +* Fix usage of `O_CLOEXEC` with `SETFL` + +# 0.6.7 (April 27, 2017) + +* Ignore EPIPE coming out of `kevent` +* Timer thread should exit when timer is dropped. + +# 0.6.6 (March 22, 2017) + +* Add send(), recv() and connect() to UDPSocket. +* Fix bug in custom readiness queue +* Move net types into `net` module + +# 0.6.5 (March 14, 2017) + +* Misc improvements to kqueue bindings +* Add official support for iOS, Android, BSD +* Reimplement custom readiness queue +* `Poll` is now `Sync` +* Officially deprecate non-core functionality (timers, channel, etc...) +* `Registration` now implements `Evented` +* Fix bug around error conditions with `connect` on windows. +* Use iovec crate for scatter / gather operations +* Only support readable and writable readiness on all platforms +* Expose additional readiness in a platform specific capacity + +# 0.6.4 (January 24, 2017) + +* Fix compilation on musl +* Add `TcpStream::from_stream` which converts a std TCP stream to Mio. + +# 0.6.3 (January 22, 2017) + +* Implement readv/writev for `TcpStream`, allowing vectored reads/writes to + work across platforms +* Remove `nix` dependency +* Implement `Display` and `Error` for some channel error types. +* Optimize TCP on Windows through `SetFileCompletionNotificationModes` + +# 0.6.2 (December 18, 2016) + +* Allow registration of custom handles on Windows (like `EventedFd` on Unix) +* Send only one byte for the awakener on Unix instead of four +* Fix a bug in the timer implementation which caused an infinite loop + +# 0.6.1 (October 30, 2016) + +* Update dependency of `libc` to 0.2.16 +* Fix channel `dec` logic +* Fix a timer bug around timeout cancellation +* Don't allocate buffers for TCP reads on Windows +* Touched up documentation in a few places +* Fix an infinite looping timer thread on OSX +* Fix compile on 32-bit OSX +* Fix compile on FreeBSD + +# 0.6.0 (September 2, 2016) + +* Shift primary API towards `Poll` +* `EventLoop` and types to `deprecated` mod. All contents of the + `deprecated` mod will be removed by Mio 1.0. +* Increase minimum supported Rust version to 1.9.0 +* Deprecate unix domain socket implementation in favor of using a + version external to Mio. For example: https://github.com/alexcrichton/mio-uds. +* Remove various types now included in `std` +* Updated TCP & UDP APIs to match the versions in `std` +* Enable implementing `Evented` for any type via `Registration` +* Rename `IoEvent` -> `Event` +* Access `Event` data via functions vs. public fields. +* Expose `Events` as a public type that is passed into `Poll` +* Use `std::time::Duration` for all APIs that require a time duration. +* Polled events are now retrieved via `Events` type. +* Implement `std::error::Error` for `TimerError` +* Relax `Send` bound on notify messages. +* Remove `Clone` impl for `Timeout` (future proof) +* Remove `mio::prelude` +* Remove `mio::util` +* Remove dependency on bytes + +# 0.5.0 (December 3, 2015) + +* Windows support (#239) +* NetBSD support (#306) +* Android support (#295) +* Don't re-export bytes types +* Renamed `EventLoop::register_opt` to `EventLoop::register` (#257) +* `EventLoopConfig` is now a builder instead of having public struct fields. It + is also no longer `Copy`. (#259) +* `TcpSocket` is no longer exported in the public API (#262) +* Integrate with net2. (#262) +* `TcpListener` now returns the remote peer address from `accept` as well (#275) +* The `UdpSocket::{send_to, recv_from}` methods are no longer generic over `Buf` + or `MutBuf` but instead take slices directly. The return types have also been + updated to return the number of bytes transferred. (#260) +* Fix bug with kqueue where an error on registration prevented the + changelist from getting flushed (#276) +* Support sending/receiving FDs over UNIX sockets (#291) +* Mio's socket types are permanently associated with an EventLoop (#308) +* Reduce unnecessary poll wakeups (#314) + + +# 0.4.1 (July 21, 2015) + +* [BUGFIX] Fix notify channel concurrency bug (#216) + +# 0.4.0 (July 16, 2015) + +* [BUGFIX] EventLoop::register requests all events, not just readable. +* [BUGFIX] Attempting to send a message to a shutdown event loop fails correctly. +* [FEATURE] Expose TCP shutdown +* [IMPROVEMENT] Coalesce readable & writable into `ready` event (#184) +* [IMPROVEMENT] Rename TryRead & TryWrite function names to avoid conflict with std. +* [IMPROVEMENT] Provide TCP and UDP types in Mio (path to windows #155) +* [IMPROVEMENT] Use clock_ticks crate instead of time (path to windows #155) +* [IMPROVEMENT] Move unix specific features into mio::unix module +* [IMPROVEMENT] TcpListener sets SO_REUSEADDR by default diff --git a/third_party/cargo/vendor/mio-0.6.21/Cargo.toml b/third_party/cargo/vendor/mio-0.6.21/Cargo.toml new file mode 100644 index 0000000..7281548 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/Cargo.toml @@ -0,0 +1,71 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "mio" +version = "0.6.21" +authors = ["Carl Lerche "] +exclude = [".gitignore", ".travis.yml", "deploy.sh"] +description = "Lightweight non-blocking IO" +homepage = "https://github.com/carllerche/mio" +documentation = "https://docs.rs/mio/0.6.21/mio/" +readme = "README.md" +keywords = ["io", "async", "non-blocking"] +categories = ["asynchronous"] +license = "MIT" +repository = "https://github.com/carllerche/mio" + +[[test]] +name = "test" +path = "test/mod.rs" +[dependencies.cfg-if] +version = "0.1.9" + +[dependencies.iovec] +version = "0.1.1" + +[dependencies.log] +version = "0.4" + +[dependencies.net2] +version = "0.2.29" + +[dependencies.slab] +version = "0.4.0" +[dev-dependencies.bytes] +version = "0.3.0" + +[dev-dependencies.env_logger] +version = "0.4.0" +default-features = false + +[dev-dependencies.tempdir] +version = "0.3.4" + +[features] +default = ["with-deprecated"] +with-deprecated = [] +[target."cfg(target_os = \"fuchsia\")".dependencies.fuchsia-zircon] +version = "0.3.2" + +[target."cfg(target_os = \"fuchsia\")".dependencies.fuchsia-zircon-sys] +version = "0.3.2" +[target."cfg(unix)".dependencies.libc] +version = "0.2.42" +[target."cfg(windows)".dependencies.kernel32-sys] +version = "0.2" + +[target."cfg(windows)".dependencies.miow] +version = "0.2.1" + +[target."cfg(windows)".dependencies.winapi] +version = "0.2.6" diff --git a/third_party/cargo/vendor/mio-0.6.21/LICENSE b/third_party/cargo/vendor/mio-0.6.21/LICENSE new file mode 100644 index 0000000..3516413 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Carl Lerche and other MIO contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/third_party/cargo/vendor/mio-0.6.21/README.md b/third_party/cargo/vendor/mio-0.6.21/README.md new file mode 100644 index 0000000..2a472bb --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/README.md @@ -0,0 +1,90 @@ +# Mio – Metal IO + +Mio is a lightweight I/O library for Rust with a focus on adding as little +overhead as possible over the OS abstractions. + +[![Crates.io][crates-badge]][crates-url] +[![MIT licensed][mit-badge]][mit-url] +[![Build Status][azure-badge]][azure-url] +[![Build Status][cirrus-badge]][cirrus-url] + +[crates-badge]: https://img.shields.io/crates/v/mio.svg +[crates-url]: https://crates.io/crates/mio +[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg +[mit-url]: LICENSE +[azure-badge]: https://dev.azure.com/tokio-rs/Tokio/_apis/build/status/tokio-rs.mio?branchName=master +[azure-url]: https://dev.azure.com/tokio-rs/Tokio/_build/latest?definitionId=2&branchName=master +[cirrus-badge]: https://api.cirrus-ci.com/github/carllerche/mio.svg +[cirrus-url]: https://cirrus-ci.com/github/carllerche/mio + +**API documentation** + +* [master](https://tokio-rs.github.io/mio/doc/mio/) +* [v0.6](https://docs.rs/mio/^0.6) + +This is a low level library, if you are looking for something easier to get +started with, see [Tokio](https://tokio.rs). + +## Usage + +To use `mio`, first add this to your `Cargo.toml`: + +```toml +[dependencies] +mio = "0.6" +``` + +Then, add this to your crate root: + +```rust +extern crate mio; +``` + +## Features + +* Non-blocking TCP, UDP. +* I/O event notification queue backed by epoll, kqueue, and IOCP. +* Zero allocations at runtime +* Platform specific extensions. + +## Non-goals + +The following are specifically omitted from Mio and are left to the user +or higher-level libraries. + +* File operations +* Thread pools / multi-threaded event loop +* Timers + +## Platforms + +Currently supported platforms: + +* Linux +* OS X +* Windows +* FreeBSD +* NetBSD +* Solaris +* Android +* iOS + +There are potentially others. If you find that Mio works on another +platform, submit a PR to update the list! + +## Community + +A group of Mio users hang out in the #mio channel on the Mozilla IRC +server (irc.mozilla.org). This can be a good place to go for questions. + +## Contributing + +Interested in getting involved? We would love to help you! For simple +bug fixes, just submit a PR with the fix and we can discuss the fix +directly in the PR. If the fix is more complex, start with an issue. + +If you want to propose an API change, create an issue to start a +discussion with the community. Also, feel free to talk with us in the +IRC channel. + +Finally, be kind. We support the [Rust Code of Conduct](https://www.rust-lang.org/conduct.html). diff --git a/third_party/cargo/vendor/mio-0.6.21/azure-pipelines.yml b/third_party/cargo/vendor/mio-0.6.21/azure-pipelines.yml new file mode 100644 index 0000000..444a67e --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/azure-pipelines.yml @@ -0,0 +1,50 @@ +trigger: ["master", "v0.6.x"] +pr: ["master", "v0.6.x"] + +jobs: +# Check formatting +# - template: ci/azure-rustfmt.yml +# parameters: +# name: rustfmt + +# Stable +- template: ci/azure-test-stable.yml + parameters: + name: stable + displayName: Test + cross: true + +# Nightly +- template: ci/azure-test-stable.yml + parameters: + name: nightly + displayName: Nightly + # Pin nightly to avoid being impacted by breakage + rust_version: nightly-2019-11-17 + benches: true + +# This represents the minimum Rust version supported by +# Mio. Updating this should be done in a dedicated PR. +# +# Tests are not run as tests may require newer versions of +# rust. +- template: ci/azure-test-stable.yml + parameters: + name: minrust + displayName: Min Rust + rust_version: 1.18.0 + cmd: check + cross: true + +- template: ci/azure-cross-compile.yml + parameters: + name: cross + +- template: ci/azure-deploy-docs.yml + parameters: + dependsOn: + # - rustfmt + - stable + - nightly + - minrust + - cross diff --git a/third_party/cargo/vendor/mio-0.6.21/benches/bench_poll.rs b/third_party/cargo/vendor/mio-0.6.21/benches/bench_poll.rs new file mode 100644 index 0000000..6b25b22 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/benches/bench_poll.rs @@ -0,0 +1,53 @@ +#![feature(test)] +#![allow(deprecated)] + +extern crate mio; +extern crate test; + +use mio::*; +use test::Bencher; +use std::sync::Arc; +use std::thread; + +#[bench] +fn bench_poll(bench: &mut Bencher) { + const NUM: usize = 10_000; + const THREADS: usize = 4; + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + + let mut registrations = vec![]; + let mut set_readiness = vec![]; + + for i in 0..NUM { + let (r, s) = Registration::new( + &poll, + Token(i), + Ready::readable(), + PollOpt::edge()); + + registrations.push(r); + set_readiness.push(s); + } + + let set_readiness = Arc::new(set_readiness); + + bench.iter(move || { + for mut i in 0..THREADS { + let set_readiness = set_readiness.clone(); + thread::spawn(move || { + while i < NUM { + set_readiness[i].set_readiness(Ready::readable()).unwrap(); + i += THREADS; + } + }); + } + + let mut n = 0; + + while n < NUM { + n += poll.poll(&mut events, None).unwrap(); + } + }) +} diff --git a/third_party/cargo/vendor/mio-0.6.21/ci/azure-cross-compile.yml b/third_party/cargo/vendor/mio-0.6.21/ci/azure-cross-compile.yml new file mode 100644 index 0000000..c7db94f --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/ci/azure-cross-compile.yml @@ -0,0 +1,56 @@ +parameters: + vmImage: ubuntu-16.04 + +jobs: +- job: ${{ parameters.name }} + displayName: Cross + strategy: + matrix: + iOS: + vmImage: macOS-10.13 + target: x86_64-apple-ios + + Android: + vmImage: ubuntu-16.04 + target: arm-linux-androideabi + + Android_64: + vmImage: ubuntu-16.04 + target: aarch64-linux-android + + NetBSD: + vmImage: ubuntu-16.04 + target: x86_64-unknown-netbsd + + Solaris: + vmImage: ubuntu-16.04 + target: x86_64-sun-solaris + + pool: + vmImage: $(vmImage) + + steps: + - template: azure-install-rust.yml + parameters: + rust_version: stable + + - script: rustup target add $(target) + displayName: "Add target" + + - script: cargo check --target $(target) + displayName: Check source + + - script: cargo check --tests --target $(target) + displayName: Check tests + + - script: cargo check --examples --target $(target) + displayName: Check examples + + - script: cargo check --target $(target) --no-default-features + displayName: Check source (no default features) + + - script: cargo check --tests --target $(target) --no-default-features + displayName: Check tests (no default features) + + - script: cargo check --examples --target $(target) --no-default-features + displayName: Check examples (no default features) diff --git a/third_party/cargo/vendor/mio-0.6.21/ci/azure-deploy-docs.yml b/third_party/cargo/vendor/mio-0.6.21/ci/azure-deploy-docs.yml new file mode 100644 index 0000000..2ff0f2a --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/ci/azure-deploy-docs.yml @@ -0,0 +1,39 @@ +parameters: + dependsOn: [] + +jobs: +- job: documentation + displayName: 'Deploy API Documentation' + condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master')) + pool: + vmImage: 'Ubuntu 16.04' + dependsOn: + - ${{ parameters.dependsOn }} + steps: + - template: azure-install-rust.yml + parameters: + rust_version: stable + - script: | + cargo doc --no-deps + cp -R target/doc '$(Build.BinariesDirectory)' + displayName: 'Generate Documentation' + - script: | + set -e + + git --version + ls -la + git init + git config user.name 'Deployment Bot (from Azure Pipelines)' + git config user.email 'deploy@tokio-rs.com' + git config --global credential.helper 'store --file ~/.my-credentials' + printf "protocol=https\nhost=github.com\nusername=carllerche\npassword=%s\n\n" "$GITHUB_TOKEN" | git credential-store --file ~/.my-credentials store + git remote add origin https://github.com/tokio-rs/mio + git checkout -b gh-pages + git add . + git commit -m 'Deploy Mio API documentation' + git push -f origin gh-pages + env: + GITHUB_TOKEN: $(githubPersonalToken) + workingDirectory: '$(Build.BinariesDirectory)' + displayName: 'Deploy Documentation' + diff --git a/third_party/cargo/vendor/mio-0.6.21/ci/azure-install-rust.yml b/third_party/cargo/vendor/mio-0.6.21/ci/azure-install-rust.yml new file mode 100644 index 0000000..43d806e --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/ci/azure-install-rust.yml @@ -0,0 +1,32 @@ +steps: + # Linux and macOS. + - script: | + set -e + curl https://sh.rustup.rs -sSf | sh -s -- -y --default-toolchain none + export PATH=$PATH:$HOME/.cargo/bin + rustup toolchain install $RUSTUP_TOOLCHAIN + rustup default $RUSTUP_TOOLCHAIN + echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin" + env: + RUSTUP_TOOLCHAIN: ${{parameters.rust_version}} + displayName: "Install rust (*nix)" + condition: not(eq(variables['Agent.OS'], 'Windows_NT')) + + # Windows. + - script: | + curl -sSf -o rustup-init.exe https://win.rustup.rs + rustup-init.exe -y --default-toolchain none + set PATH=%PATH%;%USERPROFILE%\.cargo\bin + rustup toolchain install %RUSTUP_TOOLCHAIN% + rustup default %RUSTUP_TOOLCHAIN% + echo "##vso[task.setvariable variable=PATH;]%PATH%;%USERPROFILE%\.cargo\bin" + env: + RUSTUP_TOOLCHAIN: ${{parameters.rust_version}} + displayName: "Install rust (windows)" + condition: eq(variables['Agent.OS'], 'Windows_NT') + + # All platforms. + - script: | + rustc -Vv + cargo -V + displayName: Query rust and cargo versions diff --git a/third_party/cargo/vendor/mio-0.6.21/ci/azure-test-stable.yml b/third_party/cargo/vendor/mio-0.6.21/ci/azure-test-stable.yml new file mode 100644 index 0000000..b0b9be1 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/ci/azure-test-stable.yml @@ -0,0 +1,45 @@ +parameters: + cmd: test + rust_version: stable + +jobs: +- job: ${{ parameters.name }} + displayName: ${{ parameters.displayName }} + strategy: + matrix: + Linux: + vmImage: ubuntu-16.04 + + ${{ if parameters.cross }}: + MacOS: + vmImage: macOS-10.13 + Windows: + vmImage: vs2017-win2016 + pool: + vmImage: $(vmImage) + + steps: + - template: azure-install-rust.yml + parameters: + rust_version: ${{ parameters.rust_version }} + + - script: | + cargo update + cargo update -p cfg-if --precise 0.1.9 + cargo ${{ parameters.cmd }} + displayName: cargo ${{ parameters.cmd }} + env: + CI: 'True' + + - script: cargo ${{ parameters.cmd }} --no-default-features + displayName: cargo ${{ parameters.cmd }} --no-default-features + env: + CI: 'True' + + - ${{ if eq(parameters.cmd, 'test') }}: + - script: cargo doc --no-deps + displayName: cargo doc --no-deps + + - ${{ if parameters.benches }}: + - script: cargo check --benches + displayName: Check benchmarks diff --git a/third_party/cargo/vendor/mio-0.6.21/src/channel.rs b/third_party/cargo/vendor/mio-0.6.21/src/channel.rs new file mode 100644 index 0000000..7077c51 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/channel.rs @@ -0,0 +1,390 @@ +//! Thread safe communication channel implementing `Evented` + +#![allow(unused_imports, deprecated, missing_debug_implementations)] + +use {io, Ready, Poll, PollOpt, Registration, SetReadiness, Token}; +use event::Evented; +use lazycell::{LazyCell, AtomicLazyCell}; +use std::any::Any; +use std::fmt; +use std::error; +use std::sync::{mpsc, Arc}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// Creates a new asynchronous channel, where the `Receiver` can be registered +/// with `Poll`. +pub fn channel() -> (Sender, Receiver) { + let (tx_ctl, rx_ctl) = ctl_pair(); + let (tx, rx) = mpsc::channel(); + + let tx = Sender { + tx, + ctl: tx_ctl, + }; + + let rx = Receiver { + rx, + ctl: rx_ctl, + }; + + (tx, rx) +} + +/// Creates a new synchronous, bounded channel where the `Receiver` can be +/// registered with `Poll`. +pub fn sync_channel(bound: usize) -> (SyncSender, Receiver) { + let (tx_ctl, rx_ctl) = ctl_pair(); + let (tx, rx) = mpsc::sync_channel(bound); + + let tx = SyncSender { + tx, + ctl: tx_ctl, + }; + + let rx = Receiver { + rx, + ctl: rx_ctl, + }; + + (tx, rx) +} + +pub fn ctl_pair() -> (SenderCtl, ReceiverCtl) { + let inner = Arc::new(Inner { + pending: AtomicUsize::new(0), + senders: AtomicUsize::new(1), + set_readiness: AtomicLazyCell::new(), + }); + + let tx = SenderCtl { + inner: inner.clone(), + }; + + let rx = ReceiverCtl { + registration: LazyCell::new(), + inner, + }; + + (tx, rx) +} + +/// Tracks messages sent on a channel in order to update readiness. +pub struct SenderCtl { + inner: Arc, +} + +/// Tracks messages received on a channel in order to track readiness. +pub struct ReceiverCtl { + registration: LazyCell, + inner: Arc, +} + +pub struct Sender { + tx: mpsc::Sender, + ctl: SenderCtl, +} + +pub struct SyncSender { + tx: mpsc::SyncSender, + ctl: SenderCtl, +} + +pub struct Receiver { + rx: mpsc::Receiver, + ctl: ReceiverCtl, +} + +pub enum SendError { + Io(io::Error), + Disconnected(T), +} + +pub enum TrySendError { + Io(io::Error), + Full(T), + Disconnected(T), +} + +struct Inner { + // The number of outstanding messages for the receiver to read + pending: AtomicUsize, + // The number of sender handles + senders: AtomicUsize, + // The set readiness handle + set_readiness: AtomicLazyCell, +} + +impl Sender { + pub fn send(&self, t: T) -> Result<(), SendError> { + self.tx.send(t) + .map_err(SendError::from) + .and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } +} + +impl Clone for Sender { + fn clone(&self) -> Sender { + Sender { + tx: self.tx.clone(), + ctl: self.ctl.clone(), + } + } +} + +impl SyncSender { + pub fn send(&self, t: T) -> Result<(), SendError> { + self.tx.send(t) + .map_err(From::from) + .and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } + + pub fn try_send(&self, t: T) -> Result<(), TrySendError> { + self.tx.try_send(t) + .map_err(From::from) + .and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } +} + +impl Clone for SyncSender { + fn clone(&self) -> SyncSender { + SyncSender { + tx: self.tx.clone(), + ctl: self.ctl.clone(), + } + } +} + +impl Receiver { + pub fn try_recv(&self) -> Result { + self.rx.try_recv().and_then(|res| { + let _ = self.ctl.dec(); + Ok(res) + }) + } +} + +impl Evented for Receiver { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.ctl.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.ctl.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.ctl.deregister(poll) + } +} + +/* + * + * ===== SenderCtl / ReceiverCtl ===== + * + */ + +impl SenderCtl { + /// Call to track that a message has been sent + pub fn inc(&self) -> io::Result<()> { + let cnt = self.inner.pending.fetch_add(1, Ordering::Acquire); + + if 0 == cnt { + // Toggle readiness to readable + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::readable())?; + } + } + + Ok(()) + } +} + +impl Clone for SenderCtl { + fn clone(&self) -> SenderCtl { + self.inner.senders.fetch_add(1, Ordering::Relaxed); + SenderCtl { inner: self.inner.clone() } + } +} + +impl Drop for SenderCtl { + fn drop(&mut self) { + if self.inner.senders.fetch_sub(1, Ordering::Release) == 1 { + let _ = self.inc(); + } + } +} + +impl ReceiverCtl { + pub fn dec(&self) -> io::Result<()> { + let first = self.inner.pending.load(Ordering::Acquire); + + if first == 1 { + // Unset readiness + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::empty())?; + } + } + + // Decrement + let second = self.inner.pending.fetch_sub(1, Ordering::AcqRel); + + if first == 1 && second > 1 { + // There are still pending messages. Since readiness was + // previously unset, it must be reset here + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::readable())?; + } + } + + Ok(()) + } +} + +impl Evented for ReceiverCtl { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + if self.registration.borrow().is_some() { + return Err(io::Error::new(io::ErrorKind::Other, "receiver already registered")); + } + + let (registration, set_readiness) = Registration::new(poll, token, interest, opts); + + + if self.inner.pending.load(Ordering::Relaxed) > 0 { + // TODO: Don't drop readiness + let _ = set_readiness.set_readiness(Ready::readable()); + } + + self.registration.fill(registration).expect("unexpected state encountered"); + self.inner.set_readiness.fill(set_readiness).expect("unexpected state encountered"); + + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + match self.registration.borrow() { + Some(registration) => registration.update(poll, token, interest, opts), + None => Err(io::Error::new(io::ErrorKind::Other, "receiver not registered")), + } + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + match self.registration.borrow() { + Some(registration) => registration.deregister(poll), + None => Err(io::Error::new(io::ErrorKind::Other, "receiver not registered")), + } + } +} + +/* + * + * ===== Error conversions ===== + * + */ + +impl From> for SendError { + fn from(src: mpsc::SendError) -> SendError { + SendError::Disconnected(src.0) + } +} + +impl From for SendError { + fn from(src: io::Error) -> SendError { + SendError::Io(src) + } +} + +impl From> for TrySendError { + fn from(src: mpsc::TrySendError) -> TrySendError { + match src { + mpsc::TrySendError::Full(v) => TrySendError::Full(v), + mpsc::TrySendError::Disconnected(v) => TrySendError::Disconnected(v), + } + } +} + +impl From> for TrySendError { + fn from(src: mpsc::SendError) -> TrySendError { + TrySendError::Disconnected(src.0) + } +} + +impl From for TrySendError { + fn from(src: io::Error) -> TrySendError { + TrySendError::Io(src) + } +} + +/* + * + * ===== Implement Error, Debug and Display for Errors ===== + * + */ + +impl error::Error for SendError { + fn description(&self) -> &str { + match *self { + SendError::Io(ref io_err) => io_err.description(), + SendError::Disconnected(..) => "Disconnected", + } + } +} + +impl error::Error for TrySendError { + fn description(&self) -> &str { + match *self { + TrySendError::Io(ref io_err) => io_err.description(), + TrySendError::Full(..) => "Full", + TrySendError::Disconnected(..) => "Disconnected", + } + } +} + +impl fmt::Debug for SendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_send_error(self, f) + } +} + +impl fmt::Display for SendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_send_error(self, f) + } +} + +impl fmt::Debug for TrySendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_try_send_error(self, f) + } +} + +impl fmt::Display for TrySendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_try_send_error(self, f) + } +} + +#[inline] +fn format_send_error(e: &SendError, f: &mut fmt::Formatter) -> fmt::Result { + match *e { + SendError::Io(ref io_err) => write!(f, "{}", io_err), + SendError::Disconnected(..) => write!(f, "Disconnected"), + } +} + +#[inline] +fn format_try_send_error(e: &TrySendError, f: &mut fmt::Formatter) -> fmt::Result { + match *e { + TrySendError::Io(ref io_err) => write!(f, "{}", io_err), + TrySendError::Full(..) => write!(f, "Full"), + TrySendError::Disconnected(..) => write!(f, "Disconnected"), + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/event_loop.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/event_loop.rs new file mode 100644 index 0000000..a4c4580 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/event_loop.rs @@ -0,0 +1,346 @@ +use {channel, Poll, Events, Token}; +use event::Evented; +use deprecated::{Handler, NotifyError}; +use event_imp::{Event, Ready, PollOpt}; +use timer::{self, Timer, Timeout}; +use std::{io, fmt, usize}; +use std::default::Default; +use std::time::Duration; + +#[derive(Debug, Default, Clone)] +pub struct EventLoopBuilder { + config: Config, +} + +/// `EventLoop` configuration details +#[derive(Clone, Debug)] +struct Config { + // == Notifications == + notify_capacity: usize, + messages_per_tick: usize, + + // == Timer == + timer_tick: Duration, + timer_wheel_size: usize, + timer_capacity: usize, +} + +impl Default for Config { + fn default() -> Config { + // Default EventLoop configuration values + Config { + notify_capacity: 4_096, + messages_per_tick: 256, + timer_tick: Duration::from_millis(100), + timer_wheel_size: 1_024, + timer_capacity: 65_536, + } + } +} + +impl EventLoopBuilder { + /// Construct a new `EventLoopBuilder` with the default configuration + /// values. + pub fn new() -> EventLoopBuilder { + EventLoopBuilder::default() + } + + /// Sets the maximum number of messages that can be buffered on the event + /// loop's notification channel before a send will fail. + /// + /// The default value for this is 4096. + pub fn notify_capacity(&mut self, capacity: usize) -> &mut Self { + self.config.notify_capacity = capacity; + self + } + + /// Sets the maximum number of messages that can be processed on any tick of + /// the event loop. + /// + /// The default value for this is 256. + pub fn messages_per_tick(&mut self, messages: usize) -> &mut Self { + self.config.messages_per_tick = messages; + self + } + + pub fn timer_tick(&mut self, val: Duration) -> &mut Self { + self.config.timer_tick = val; + self + } + + pub fn timer_wheel_size(&mut self, size: usize) -> &mut Self { + self.config.timer_wheel_size = size; + self + } + + pub fn timer_capacity(&mut self, cap: usize) -> &mut Self { + self.config.timer_capacity = cap; + self + } + + /// Constructs a new `EventLoop` using the configured values. The + /// `EventLoop` will not be running. + pub fn build(self) -> io::Result> { + EventLoop::configured(self.config) + } +} + +/// Single threaded IO event loop. +pub struct EventLoop { + run: bool, + poll: Poll, + events: Events, + timer: Timer, + notify_tx: channel::SyncSender, + notify_rx: channel::Receiver, + config: Config, +} + +// Token used to represent notifications +const NOTIFY: Token = Token(usize::MAX - 1); +const TIMER: Token = Token(usize::MAX - 2); + +impl EventLoop { + + /// Constructs a new `EventLoop` using the default configuration values. + /// The `EventLoop` will not be running. + pub fn new() -> io::Result> { + EventLoop::configured(Config::default()) + } + + fn configured(config: Config) -> io::Result> { + // Create the IO poller + let poll = Poll::new()?; + + let timer = timer::Builder::default() + .tick_duration(config.timer_tick) + .num_slots(config.timer_wheel_size) + .capacity(config.timer_capacity) + .build(); + + // Create cross thread notification queue + let (tx, rx) = channel::sync_channel(config.notify_capacity); + + // Register the notification wakeup FD with the IO poller + poll.register(&rx, NOTIFY, Ready::readable(), PollOpt::edge() | PollOpt::oneshot())?; + poll.register(&timer, TIMER, Ready::readable(), PollOpt::edge())?; + + Ok(EventLoop { + run: true, + poll, + timer, + notify_tx: tx, + notify_rx: rx, + config, + events: Events::with_capacity(1024), + }) + } + + /// Returns a sender that allows sending messages to the event loop in a + /// thread-safe way, waking up the event loop if needed. + /// + /// # Implementation Details + /// + /// Each [EventLoop](#) contains a lock-free queue with a pre-allocated + /// buffer size. The size can be changed by modifying + /// [EventLoopConfig.notify_capacity](struct.EventLoopConfig.html#method.notify_capacity). + /// When a message is sent to the EventLoop, it is first pushed on to the + /// queue. Then, if the EventLoop is currently running, an atomic flag is + /// set to indicate that the next loop iteration should be started without + /// waiting. + /// + /// If the loop is blocked waiting for IO events, then it is woken up. The + /// strategy for waking up the event loop is platform dependent. For + /// example, on a modern Linux OS, eventfd is used. On older OSes, a pipe + /// is used. + /// + /// The strategy of setting an atomic flag if the event loop is not already + /// sleeping allows avoiding an expensive wakeup operation if at all possible. + pub fn channel(&self) -> Sender { + Sender::new(self.notify_tx.clone()) + } + + /// Schedules a timeout after the requested time interval. When the + /// duration has been reached, + /// [Handler::timeout](trait.Handler.html#method.timeout) will be invoked + /// passing in the supplied token. + /// + /// Returns a handle to the timeout that can be used to cancel the timeout + /// using [#clear_timeout](#method.clear_timeout). + pub fn timeout(&mut self, token: H::Timeout, delay: Duration) -> timer::Result { + self.timer.set_timeout(delay, token) + } + + /// If the supplied timeout has not been triggered, cancel it such that it + /// will not be triggered in the future. + pub fn clear_timeout(&mut self, timeout: &Timeout) -> bool { + self.timer.cancel_timeout(&timeout).is_some() + } + + /// Tells the event loop to exit after it is done handling all events in the + /// current iteration. + pub fn shutdown(&mut self) { + self.run = false; + } + + /// Indicates whether the event loop is currently running. If it's not it has either + /// stopped or is scheduled to stop on the next tick. + pub fn is_running(&self) -> bool { + self.run + } + + /// Registers an IO handle with the event loop. + pub fn register(&mut self, io: &E, token: Token, interest: Ready, opt: PollOpt) -> io::Result<()> + where E: Evented + { + self.poll.register(io, token, interest, opt) + } + + /// Re-Registers an IO handle with the event loop. + pub fn reregister(&mut self, io: &E, token: Token, interest: Ready, opt: PollOpt) -> io::Result<()> + where E: Evented + { + self.poll.reregister(io, token, interest, opt) + } + + /// Keep spinning the event loop indefinitely, and notify the handler whenever + /// any of the registered handles are ready. + pub fn run(&mut self, handler: &mut H) -> io::Result<()> { + self.run = true; + + while self.run { + // Execute ticks as long as the event loop is running + self.run_once(handler, None)?; + } + + Ok(()) + } + + /// Deregisters an IO handle with the event loop. + /// + /// Both kqueue and epoll will automatically clear any pending events when closing a + /// file descriptor (socket). In that case, this method does not need to be called + /// prior to dropping a connection from the slab. + /// + /// Warning: kqueue effectively builds in deregister when using edge-triggered mode with + /// oneshot. Calling `deregister()` on the socket will cause a TcpStream error. + pub fn deregister(&mut self, io: &E) -> io::Result<()> where E: Evented { + self.poll.deregister(io) + } + + /// Spin the event loop once, with a given timeout (forever if `None`), + /// and notify the handler if any of the registered handles become ready + /// during that time. + pub fn run_once(&mut self, handler: &mut H, timeout: Option) -> io::Result<()> { + trace!("event loop tick"); + + // Check the registered IO handles for any new events. Each poll + // is for one second, so a shutdown request can last as long as + // one second before it takes effect. + let events = match self.io_poll(timeout) { + Ok(e) => e, + Err(err) => { + if err.kind() == io::ErrorKind::Interrupted { + handler.interrupted(self); + 0 + } else { + return Err(err); + } + } + }; + + self.io_process(handler, events); + handler.tick(self); + Ok(()) + } + + #[inline] + fn io_poll(&mut self, timeout: Option) -> io::Result { + self.poll.poll(&mut self.events, timeout) + } + + // Process IO events that have been previously polled + fn io_process(&mut self, handler: &mut H, cnt: usize) { + let mut i = 0; + + trace!("io_process(..); cnt={}; len={}", cnt, self.events.len()); + + // Iterate over the notifications. Each event provides the token + // it was registered with (which usually represents, at least, the + // handle that the event is about) as well as information about + // what kind of event occurred (readable, writable, signal, etc.) + while i < cnt { + let evt = self.events.get(i).unwrap(); + + trace!("event={:?}; idx={:?}", evt, i); + + match evt.token() { + NOTIFY => self.notify(handler), + TIMER => self.timer_process(handler), + _ => self.io_event(handler, evt) + } + + i += 1; + } + } + + fn io_event(&mut self, handler: &mut H, evt: Event) { + handler.ready(self, evt.token(), evt.readiness()); + } + + fn notify(&mut self, handler: &mut H) { + for _ in 0..self.config.messages_per_tick { + match self.notify_rx.try_recv() { + Ok(msg) => handler.notify(self, msg), + _ => break, + } + } + + // Re-register + let _ = self.poll.reregister(&self.notify_rx, NOTIFY, Ready::readable(), PollOpt::edge() | PollOpt::oneshot()); + } + + fn timer_process(&mut self, handler: &mut H) { + while let Some(t) = self.timer.poll() { + handler.timeout(self, t); + } + } +} + +impl fmt::Debug for EventLoop { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("EventLoop") + .field("run", &self.run) + .field("poll", &self.poll) + .field("config", &self.config) + .finish() + } +} + +/// Sends messages to the EventLoop from other threads. +pub struct Sender { + tx: channel::SyncSender +} + +impl fmt::Debug for Sender { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "Sender {{ ... }}") + } +} + +impl Clone for Sender { + fn clone(&self) -> Sender { + Sender { tx: self.tx.clone() } + } +} + +impl Sender { + fn new(tx: channel::SyncSender) -> Sender { + Sender { tx } + } + + pub fn send(&self, msg: M) -> Result<(), NotifyError> { + self.tx.try_send(msg)?; + Ok(()) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/handler.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/handler.rs new file mode 100644 index 0000000..db1bc31 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/handler.rs @@ -0,0 +1,37 @@ +use {Ready, Token}; +use deprecated::{EventLoop}; + +#[allow(unused_variables)] +pub trait Handler: Sized { + type Timeout; + type Message; + + /// Invoked when the socket represented by `token` is ready to be operated + /// on. `events` indicates the specific operations that are + /// ready to be performed. + /// + /// For example, when a TCP socket is ready to be read from, `events` will + /// have `readable` set. When the socket is ready to be written to, + /// `events` will have `writable` set. + /// + /// This function will only be invoked a single time per socket per event + /// loop tick. + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, events: Ready) { + } + + /// Invoked when a message has been received via the event loop's channel. + fn notify(&mut self, event_loop: &mut EventLoop, msg: Self::Message) { + } + + /// Invoked when a timeout has completed. + fn timeout(&mut self, event_loop: &mut EventLoop, timeout: Self::Timeout) { + } + + /// Invoked when `EventLoop` has been interrupted by a signal interrupt. + fn interrupted(&mut self, event_loop: &mut EventLoop) { + } + + /// Invoked at the end of an event loop tick. + fn tick(&mut self, event_loop: &mut EventLoop) { + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/io.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/io.rs new file mode 100644 index 0000000..16ff279 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/io.rs @@ -0,0 +1,28 @@ +use ::io::MapNonBlock; +use std::io::{self, Read, Write}; + +pub trait TryRead { + fn try_read(&mut self, buf: &mut [u8]) -> io::Result>; +} + +pub trait TryWrite { + fn try_write(&mut self, buf: &[u8]) -> io::Result>; +} + +impl TryRead for T { + fn try_read(&mut self, dst: &mut [u8]) -> io::Result> { + self.read(dst).map_non_block() + } +} + +impl TryWrite for T { + fn try_write(&mut self, src: &[u8]) -> io::Result> { + self.write(src).map_non_block() + } +} + +pub trait TryAccept { + type Output; + + fn accept(&self) -> io::Result>; +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/mod.rs new file mode 100644 index 0000000..124a2ee --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/mod.rs @@ -0,0 +1,36 @@ +#![allow(deprecated)] + +mod event_loop; +mod io; +mod handler; +mod notify; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub mod unix; + +pub use self::event_loop::{ + EventLoop, + EventLoopBuilder, + Sender, +}; +pub use self::io::{ + TryAccept, + TryRead, + TryWrite, +}; +pub use self::handler::{ + Handler, +}; +pub use self::notify::{ + NotifyError, +}; +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub use self::unix::{ + pipe, + PipeReader, + PipeWriter, + UnixListener, + UnixSocket, + UnixStream, + Shutdown, +}; diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/notify.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/notify.rs new file mode 100644 index 0000000..c8432d6 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/notify.rs @@ -0,0 +1,63 @@ +use {channel}; +use std::{fmt, io, error, any}; + +pub enum NotifyError { + Io(io::Error), + Full(T), + Closed(Option), +} + +impl fmt::Debug for NotifyError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + NotifyError::Io(ref e) => { + write!(fmt, "NotifyError::Io({:?})", e) + } + NotifyError::Full(..) => { + write!(fmt, "NotifyError::Full(..)") + } + NotifyError::Closed(..) => { + write!(fmt, "NotifyError::Closed(..)") + } + } + } +} + +impl fmt::Display for NotifyError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + NotifyError::Io(ref e) => { + write!(fmt, "IO error: {}", e) + } + NotifyError::Full(..) => write!(fmt, "Full"), + NotifyError::Closed(..) => write!(fmt, "Closed") + } + } +} + +impl error::Error for NotifyError { + fn description(&self) -> &str { + match *self { + NotifyError::Io(ref err) => err.description(), + NotifyError::Closed(..) => "The receiving end has hung up", + NotifyError::Full(..) => "Queue is full" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + NotifyError::Io(ref err) => Some(err), + _ => None + } + } +} + +impl From> for NotifyError { + fn from(src: channel::TrySendError) -> NotifyError { + match src { + channel::TrySendError::Io(e) => NotifyError::Io(e), + channel::TrySendError::Full(v) => NotifyError::Full(v), + channel::TrySendError::Disconnected(v) => NotifyError::Closed(Some(v)), + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/deprecated/unix.rs b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/unix.rs new file mode 100644 index 0000000..97c6a60 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/deprecated/unix.rs @@ -0,0 +1,420 @@ +use {io, sys, Ready, Poll, PollOpt, Token}; +use event::Evented; +use deprecated::TryAccept; +use io::MapNonBlock; +use std::io::{Read, Write}; +use std::path::Path; +pub use std::net::Shutdown; +use std::process; + +pub use sys::Io; + +#[derive(Debug)] +pub struct UnixSocket { + sys: sys::UnixSocket, +} + +impl UnixSocket { + /// Returns a new, unbound, non-blocking Unix domain socket + pub fn stream() -> io::Result { + sys::UnixSocket::stream() + .map(From::from) + } + + /// Connect the socket to the specified address + pub fn connect + ?Sized>(self, addr: &P) -> io::Result<(UnixStream, bool)> { + let complete = match self.sys.connect(addr) { + Ok(()) => true, + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => false, + Err(e) => return Err(e), + }; + Ok((From::from(self.sys), complete)) + } + + /// Bind the socket to the specified address + pub fn bind + ?Sized>(&self, addr: &P) -> io::Result<()> { + self.sys.bind(addr) + } + + /// Listen for incoming requests + pub fn listen(self, backlog: usize) -> io::Result { + self.sys.listen(backlog)?; + Ok(From::from(self.sys)) + } + + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone() + .map(From::from) + } +} + +impl Evented for UnixSocket { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl From for UnixSocket { + fn from(sys: sys::UnixSocket) -> UnixSocket { + UnixSocket { sys } + } +} + +/* + * + * ===== UnixStream ===== + * + */ + +#[derive(Debug)] +pub struct UnixStream { + sys: sys::UnixSocket, +} + +impl UnixStream { + pub fn connect + ?Sized>(path: &P) -> io::Result { + UnixSocket::stream() + .and_then(|sock| sock.connect(path)) + .map(|(sock, _)| sock) + } + + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone() + .map(From::from) + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result { + self.sys.shutdown(how).map(|_| 0) + } + + pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option)> { + self.sys.read_recv_fd(buf) + } + + pub fn try_read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result)>> { + self.read_recv_fd(buf).map_non_block() + } + + pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result { + self.sys.write_send_fd(buf, fd) + } + + pub fn try_write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result> { + self.write_send_fd(buf, fd).map_non_block() + } +} + +impl Read for UnixStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.sys.read(buf) + } +} + +impl Write for UnixStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.sys.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.sys.flush() + } +} + +impl Evented for UnixStream { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl From for UnixStream { + fn from(sys: sys::UnixSocket) -> UnixStream { + UnixStream { sys } + } +} + +/* + * + * ===== UnixListener ===== + * + */ + +#[derive(Debug)] +pub struct UnixListener { + sys: sys::UnixSocket, +} + +impl UnixListener { + pub fn bind + ?Sized>(addr: &P) -> io::Result { + UnixSocket::stream().and_then(|sock| { + sock.bind(addr)?; + sock.listen(256) + }) + } + + pub fn accept(&self) -> io::Result { + self.sys.accept().map(From::from) + } + + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone().map(From::from) + } +} + +impl Evented for UnixListener { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl TryAccept for UnixListener { + type Output = UnixStream; + + fn accept(&self) -> io::Result> { + UnixListener::accept(self).map_non_block() + } +} + +impl From for UnixListener { + fn from(sys: sys::UnixSocket) -> UnixListener { + UnixListener { sys } + } +} + +/* + * + * ===== Pipe ===== + * + */ + +pub fn pipe() -> io::Result<(PipeReader, PipeWriter)> { + let (rd, wr) = sys::pipe()?; + Ok((From::from(rd), From::from(wr))) +} + +#[derive(Debug)] +pub struct PipeReader { + io: Io, +} + +impl PipeReader { + pub fn from_stdout(stdout: process::ChildStdout) -> io::Result { + if let Err(e) = sys::set_nonblock(stdout.as_raw_fd()) { + return Err(e); + } + Ok(PipeReader::from(unsafe { Io::from_raw_fd(stdout.into_raw_fd()) })) + } + pub fn from_stderr(stderr: process::ChildStderr) -> io::Result { + if let Err(e) = sys::set_nonblock(stderr.as_raw_fd()) { + return Err(e); + } + Ok(PipeReader::from(unsafe { Io::from_raw_fd(stderr.into_raw_fd()) })) + } +} + +impl Read for PipeReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.io.read(buf) + } +} + +impl<'a> Read for &'a PipeReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + (&self.io).read(buf) + } +} + +impl Evented for PipeReader { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.io.deregister(poll) + } +} + +impl From for PipeReader { + fn from(io: Io) -> PipeReader { + PipeReader { io } + } +} + +#[derive(Debug)] +pub struct PipeWriter { + io: Io, +} + +impl PipeWriter { + pub fn from_stdin(stdin: process::ChildStdin) -> io::Result { + if let Err(e) = sys::set_nonblock(stdin.as_raw_fd()) { + return Err(e); + } + Ok(PipeWriter::from(unsafe { Io::from_raw_fd(stdin.into_raw_fd()) })) + } +} + +impl Write for PipeWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.io.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.io.flush() + } +} + +impl<'a> Write for &'a PipeWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + (&self.io).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.io).flush() + } +} + +impl Evented for PipeWriter { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.io.deregister(poll) + } +} + +impl From for PipeWriter { + fn from(io: Io) -> PipeWriter { + PipeWriter { io } + } +} + +/* + * + * ===== Conversions ===== + * + */ + +use std::os::unix::io::{RawFd, IntoRawFd, AsRawFd, FromRawFd}; + +impl IntoRawFd for UnixSocket { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +impl AsRawFd for UnixSocket { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +impl FromRawFd for UnixSocket { + unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket { + UnixSocket { sys: FromRawFd::from_raw_fd(fd) } + } +} + +impl IntoRawFd for UnixStream { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +impl AsRawFd for UnixStream { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +impl FromRawFd for UnixStream { + unsafe fn from_raw_fd(fd: RawFd) -> UnixStream { + UnixStream { sys: FromRawFd::from_raw_fd(fd) } + } +} + +impl IntoRawFd for UnixListener { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +impl AsRawFd for UnixListener { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +impl FromRawFd for UnixListener { + unsafe fn from_raw_fd(fd: RawFd) -> UnixListener { + UnixListener { sys: FromRawFd::from_raw_fd(fd) } + } +} + +impl IntoRawFd for PipeReader { + fn into_raw_fd(self) -> RawFd { + self.io.into_raw_fd() + } +} + +impl AsRawFd for PipeReader { + fn as_raw_fd(&self) -> RawFd { + self.io.as_raw_fd() + } +} + +impl FromRawFd for PipeReader { + unsafe fn from_raw_fd(fd: RawFd) -> PipeReader { + PipeReader { io: FromRawFd::from_raw_fd(fd) } + } +} + +impl IntoRawFd for PipeWriter { + fn into_raw_fd(self) -> RawFd { + self.io.into_raw_fd() + } +} + +impl AsRawFd for PipeWriter { + fn as_raw_fd(&self) -> RawFd { + self.io.as_raw_fd() + } +} + +impl FromRawFd for PipeWriter { + unsafe fn from_raw_fd(fd: RawFd) -> PipeWriter { + PipeWriter { io: FromRawFd::from_raw_fd(fd) } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/event_imp.rs b/third_party/cargo/vendor/mio-0.6.21/src/event_imp.rs new file mode 100644 index 0000000..f93e1fd --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/event_imp.rs @@ -0,0 +1,1164 @@ +use {Poll, Token}; +use std::{fmt, io, ops}; + +/// A value that may be registered with `Poll` +/// +/// Values that implement `Evented` can be registered with `Poll`. Users of Mio +/// should not use the `Evented` trait functions directly. Instead, the +/// equivalent functions on `Poll` should be used. +/// +/// See [`Poll`] for more details. +/// +/// # Implementing `Evented` +/// +/// There are two types of `Evented` values. +/// +/// * **System** handles, which are backed by sockets or other system handles. +/// These `Evented` handles will be monitored by the system selector. In this +/// case, an implementation of `Evented` delegates to a lower level handle. +/// +/// * **User** handles, which are driven entirely in user space using +/// [`Registration`] and [`SetReadiness`]. In this case, the implementer takes +/// responsibility for driving the readiness state changes. +/// +/// [`Poll`]: ../struct.Poll.html +/// [`Registration`]: ../struct.Registration.html +/// [`SetReadiness`]: ../struct.SetReadiness.html +/// +/// # Examples +/// +/// Implementing `Evented` on a struct containing a socket: +/// +/// ``` +/// use mio::{Ready, Poll, PollOpt, Token}; +/// use mio::event::Evented; +/// use mio::net::TcpStream; +/// +/// use std::io; +/// +/// pub struct MyEvented { +/// socket: TcpStream, +/// } +/// +/// impl Evented for MyEvented { +/// fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// // Delegate the `register` call to `socket` +/// self.socket.register(poll, token, interest, opts) +/// } +/// +/// fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// // Delegate the `reregister` call to `socket` +/// self.socket.reregister(poll, token, interest, opts) +/// } +/// +/// fn deregister(&self, poll: &Poll) -> io::Result<()> { +/// // Delegate the `deregister` call to `socket` +/// self.socket.deregister(poll) +/// } +/// } +/// ``` +/// +/// Implement `Evented` using [`Registration`] and [`SetReadiness`]. +/// +/// ``` +/// use mio::{Ready, Registration, Poll, PollOpt, Token}; +/// use mio::event::Evented; +/// +/// use std::io; +/// use std::time::Instant; +/// use std::thread; +/// +/// pub struct Deadline { +/// when: Instant, +/// registration: Registration, +/// } +/// +/// impl Deadline { +/// pub fn new(when: Instant) -> Deadline { +/// let (registration, set_readiness) = Registration::new2(); +/// +/// thread::spawn(move || { +/// let now = Instant::now(); +/// +/// if now < when { +/// thread::sleep(when - now); +/// } +/// +/// set_readiness.set_readiness(Ready::readable()); +/// }); +/// +/// Deadline { +/// when: when, +/// registration: registration, +/// } +/// } +/// +/// pub fn is_elapsed(&self) -> bool { +/// Instant::now() >= self.when +/// } +/// } +/// +/// impl Evented for Deadline { +/// fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// self.registration.register(poll, token, interest, opts) +/// } +/// +/// fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// self.registration.reregister(poll, token, interest, opts) +/// } +/// +/// fn deregister(&self, poll: &Poll) -> io::Result<()> { +/// self.registration.deregister(poll) +/// } +/// } +/// ``` +pub trait Evented { + /// Register `self` with the given `Poll` instance. + /// + /// This function should not be called directly. Use [`Poll::register`] + /// instead. Implementors should handle registration by either delegating + /// the call to another `Evented` type or creating a [`Registration`]. + /// + /// [`Poll::register`]: ../struct.Poll.html#method.register + /// [`Registration`]: ../struct.Registration.html + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>; + + /// Re-register `self` with the given `Poll` instance. + /// + /// This function should not be called directly. Use [`Poll::reregister`] + /// instead. Implementors should handle re-registration by either delegating + /// the call to another `Evented` type or calling + /// [`SetReadiness::set_readiness`]. + /// + /// [`Poll::reregister`]: ../struct.Poll.html#method.reregister + /// [`SetReadiness::set_readiness`]: ../struct.SetReadiness.html#method.set_readiness + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()>; + + /// Deregister `self` from the given `Poll` instance + /// + /// This function should not be called directly. Use [`Poll::deregister`] + /// instead. Implementors should handle deregistration by either delegating + /// the call to another `Evented` type or by dropping the [`Registration`] + /// associated with `self`. + /// + /// [`Poll::deregister`]: ../struct.Poll.html#method.deregister + /// [`Registration`]: ../struct.Registration.html + fn deregister(&self, poll: &Poll) -> io::Result<()>; +} + +impl Evented for Box { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.as_ref().deregister(poll) + } +} + +impl Evented for Box { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.as_ref().deregister(poll) + } +} + +impl Evented for ::std::sync::Arc { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.as_ref().reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.as_ref().deregister(poll) + } +} + +/// Options supplied when registering an `Evented` handle with `Poll` +/// +/// `PollOpt` values can be combined together using the various bitwise +/// operators. +/// +/// For high level documentation on polling and poll options, see [`Poll`]. +/// +/// # Examples +/// +/// ``` +/// use mio::PollOpt; +/// +/// let opts = PollOpt::edge() | PollOpt::oneshot(); +/// +/// assert!(opts.is_edge()); +/// assert!(opts.is_oneshot()); +/// assert!(!opts.is_level()); +/// ``` +/// +/// [`Poll`]: struct.Poll.html +#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)] +pub struct PollOpt(usize); + +impl PollOpt { + /// Return a `PollOpt` representing no set options. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::empty(); + /// + /// assert!(!opt.is_level()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn empty() -> PollOpt { + PollOpt(0) + } + + /// Return a `PollOpt` representing edge-triggered notifications. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::edge(); + /// + /// assert!(opt.is_edge()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn edge() -> PollOpt { + PollOpt(0b0001) + } + + /// Return a `PollOpt` representing level-triggered notifications. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::level(); + /// + /// assert!(opt.is_level()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn level() -> PollOpt { + PollOpt(0b0010) + } + + /// Return a `PollOpt` representing oneshot notifications. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::oneshot(); + /// + /// assert!(opt.is_oneshot()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn oneshot() -> PollOpt { + PollOpt(0b0100) + } + + #[deprecated(since = "0.6.5", note = "removed")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn urgent() -> PollOpt { + PollOpt(0b1000) + } + + #[deprecated(since = "0.6.5", note = "removed")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn all() -> PollOpt { + PollOpt::edge() | PollOpt::level() | PollOpt::oneshot() + } + + /// Returns true if the options include edge-triggered notifications. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::edge(); + /// + /// assert!(opt.is_edge()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_edge(&self) -> bool { + self.contains(PollOpt::edge()) + } + + /// Returns true if the options include level-triggered notifications. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::level(); + /// + /// assert!(opt.is_level()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_level(&self) -> bool { + self.contains(PollOpt::level()) + } + + /// Returns true if the options includes oneshot. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::oneshot(); + /// + /// assert!(opt.is_oneshot()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_oneshot(&self) -> bool { + self.contains(PollOpt::oneshot()) + } + + #[deprecated(since = "0.6.5", note = "removed")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[allow(deprecated)] + #[inline] + pub fn is_urgent(&self) -> bool { + self.contains(PollOpt::urgent()) + } + + #[deprecated(since = "0.6.5", note = "removed")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn bits(&self) -> usize { + self.0 + } + + /// Returns true if `self` is a superset of `other`. + /// + /// `other` may represent more than one option, in which case the function + /// only returns true if `self` contains all of the options specified in + /// `other`. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::oneshot(); + /// + /// assert!(opt.contains(PollOpt::oneshot())); + /// assert!(!opt.contains(PollOpt::edge())); + /// ``` + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::oneshot() | PollOpt::edge(); + /// + /// assert!(opt.contains(PollOpt::oneshot())); + /// assert!(opt.contains(PollOpt::edge())); + /// ``` + /// + /// ``` + /// use mio::PollOpt; + /// + /// let opt = PollOpt::oneshot() | PollOpt::edge(); + /// + /// assert!(!PollOpt::oneshot().contains(opt)); + /// assert!(opt.contains(opt)); + /// assert!((opt | PollOpt::level()).contains(opt)); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn contains(&self, other: PollOpt) -> bool { + (*self & other) == other + } + + /// Adds all options represented by `other` into `self`. + /// + /// This is equivalent to `*self = *self | other`. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let mut opt = PollOpt::empty(); + /// opt.insert(PollOpt::oneshot()); + /// + /// assert!(opt.is_oneshot()); + /// ``` + #[inline] + pub fn insert(&mut self, other: PollOpt) { + self.0 |= other.0; + } + + /// Removes all options represented by `other` from `self`. + /// + /// This is equivalent to `*self = *self & !other`. + /// + /// # Examples + /// + /// ``` + /// use mio::PollOpt; + /// + /// let mut opt = PollOpt::oneshot(); + /// opt.remove(PollOpt::oneshot()); + /// + /// assert!(!opt.is_oneshot()); + /// ``` + #[inline] + pub fn remove(&mut self, other: PollOpt) { + self.0 &= !other.0; + } +} + +impl ops::BitOr for PollOpt { + type Output = PollOpt; + + #[inline] + fn bitor(self, other: PollOpt) -> PollOpt { + PollOpt(self.0 | other.0) + } +} + +impl ops::BitXor for PollOpt { + type Output = PollOpt; + + #[inline] + fn bitxor(self, other: PollOpt) -> PollOpt { + PollOpt(self.0 ^ other.0) + } +} + +impl ops::BitAnd for PollOpt { + type Output = PollOpt; + + #[inline] + fn bitand(self, other: PollOpt) -> PollOpt { + PollOpt(self.0 & other.0) + } +} + +impl ops::Sub for PollOpt { + type Output = PollOpt; + + #[inline] + fn sub(self, other: PollOpt) -> PollOpt { + PollOpt(self.0 & !other.0) + } +} + +#[deprecated(since = "0.6.10", note = "removed")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +impl ops::Not for PollOpt { + type Output = PollOpt; + + #[inline] + fn not(self) -> PollOpt { + PollOpt(!self.0) + } +} + +impl fmt::Debug for PollOpt { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut one = false; + let flags = [ + (PollOpt::edge(), "Edge-Triggered"), + (PollOpt::level(), "Level-Triggered"), + (PollOpt::oneshot(), "OneShot")]; + + for &(flag, msg) in &flags { + if self.contains(flag) { + if one { write!(fmt, " | ")? } + write!(fmt, "{}", msg)?; + + one = true + } + } + + if !one { + fmt.write_str("(empty)")?; + } + + Ok(()) + } +} + +#[test] +fn test_debug_pollopt() { + assert_eq!("(empty)", format!("{:?}", PollOpt::empty())); + assert_eq!("Edge-Triggered", format!("{:?}", PollOpt::edge())); + assert_eq!("Level-Triggered", format!("{:?}", PollOpt::level())); + assert_eq!("OneShot", format!("{:?}", PollOpt::oneshot())); +} + +/// A set of readiness event kinds +/// +/// `Ready` is a set of operation descriptors indicating which kind of an +/// operation is ready to be performed. For example, `Ready::readable()` +/// indicates that the associated `Evented` handle is ready to perform a +/// `read` operation. +/// +/// This struct only represents portable event kinds. Since only readable and +/// writable events are guaranteed to be raised on all systems, those are the +/// only ones available via the `Ready` struct. There are also platform specific +/// extensions to `Ready`, i.e. `UnixReady`, which provide additional readiness +/// event kinds only available on unix platforms. +/// +/// `Ready` values can be combined together using the various bitwise operators. +/// +/// For high level documentation on polling and readiness, see [`Poll`]. +/// +/// # Examples +/// +/// ``` +/// use mio::Ready; +/// +/// let ready = Ready::readable() | Ready::writable(); +/// +/// assert!(ready.is_readable()); +/// assert!(ready.is_writable()); +/// ``` +/// +/// [`Poll`]: struct.Poll.html +/// [`readable`]: #method.readable +/// [`writable`]: #method.writable +/// [readiness]: struct.Poll.html#readiness-operations +#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)] +pub struct Ready(usize); + +const READABLE: usize = 0b00001; +const WRITABLE: usize = 0b00010; + +// These are deprecated and are moved into platform specific implementations. +const ERROR: usize = 0b00100; +const HUP: usize = 0b01000; + +impl Ready { + /// Returns the empty `Ready` set. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::empty(); + /// + /// assert!(!ready.is_readable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + pub fn empty() -> Ready { + Ready(0) + } + + #[deprecated(since = "0.6.5", note = "use Ready::empty instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn none() -> Ready { + Ready::empty() + } + + /// Returns a `Ready` representing readable readiness. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::readable(); + /// + /// assert!(ready.is_readable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn readable() -> Ready { + Ready(READABLE) + } + + /// Returns a `Ready` representing writable readiness. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::writable(); + /// + /// assert!(ready.is_writable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn writable() -> Ready { + Ready(WRITABLE) + } + + #[deprecated(since = "0.6.5", note = "use UnixReady instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn error() -> Ready { + Ready(ERROR) + } + + #[deprecated(since = "0.6.5", note = "use UnixReady instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn hup() -> Ready { + Ready(HUP) + } + + /// Returns a `Ready` representing readiness for all operations. + /// + /// This includes platform specific operations as well (`hup`, `aio`, + /// `error`, `lio`, `pri`). + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::all(); + /// + /// assert!(ready.is_readable()); + /// assert!(ready.is_writable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn all() -> Ready { + Ready(READABLE | WRITABLE | ::sys::READY_ALL) + } + + /// Returns true if `Ready` is the empty set + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::empty(); + /// assert!(ready.is_empty()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_empty(&self) -> bool { + *self == Ready::empty() + } + + #[deprecated(since = "0.6.5", note = "use Ready::is_empty instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn is_none(&self) -> bool { + self.is_empty() + } + + /// Returns true if the value includes readable readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::readable(); + /// + /// assert!(ready.is_readable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_readable(&self) -> bool { + self.contains(Ready::readable()) + } + + /// Returns true if the value includes writable readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::writable(); + /// + /// assert!(ready.is_writable()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn is_writable(&self) -> bool { + self.contains(Ready::writable()) + } + + #[deprecated(since = "0.6.5", note = "use UnixReady instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn is_error(&self) -> bool { + self.contains(Ready(ERROR)) + } + + #[deprecated(since = "0.6.5", note = "use UnixReady instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn is_hup(&self) -> bool { + self.contains(Ready(HUP)) + } + + /// Adds all readiness represented by `other` into `self`. + /// + /// This is equivalent to `*self = *self | other`. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let mut readiness = Ready::empty(); + /// readiness.insert(Ready::readable()); + /// + /// assert!(readiness.is_readable()); + /// ``` + #[inline] + pub fn insert>(&mut self, other: T) { + let other = other.into(); + self.0 |= other.0; + } + + /// Removes all options represented by `other` from `self`. + /// + /// This is equivalent to `*self = *self & !other`. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let mut readiness = Ready::readable(); + /// readiness.remove(Ready::readable()); + /// + /// assert!(!readiness.is_readable()); + /// ``` + #[inline] + pub fn remove>(&mut self, other: T) { + let other = other.into(); + self.0 &= !other.0; + } + + #[deprecated(since = "0.6.5", note = "removed")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + #[inline] + pub fn bits(&self) -> usize { + self.0 + } + + /// Returns true if `self` is a superset of `other`. + /// + /// `other` may represent more than one readiness operations, in which case + /// the function only returns true if `self` contains all readiness + /// specified in `other`. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let readiness = Ready::readable(); + /// + /// assert!(readiness.contains(Ready::readable())); + /// assert!(!readiness.contains(Ready::writable())); + /// ``` + /// + /// ``` + /// use mio::Ready; + /// + /// let readiness = Ready::readable() | Ready::writable(); + /// + /// assert!(readiness.contains(Ready::readable())); + /// assert!(readiness.contains(Ready::writable())); + /// ``` + /// + /// ``` + /// use mio::Ready; + /// + /// let readiness = Ready::readable() | Ready::writable(); + /// + /// assert!(!Ready::readable().contains(readiness)); + /// assert!(readiness.contains(readiness)); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + pub fn contains>(&self, other: T) -> bool { + let other = other.into(); + (*self & other) == other + } + + /// Create a `Ready` instance using the given `usize` representation. + /// + /// The `usize` representation must have been obtained from a call to + /// `Ready::as_usize`. + /// + /// The `usize` representation must be treated as opaque. There is no + /// guaranteed correlation between the returned value and platform defined + /// constants. Also, there is no guarantee that the `usize` representation + /// will remain constant across patch releases of Mio. + /// + /// This function is mainly provided to allow the caller to loa a + /// readiness value from an `AtomicUsize`. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::readable(); + /// let ready_usize = ready.as_usize(); + /// let ready2 = Ready::from_usize(ready_usize); + /// + /// assert_eq!(ready, ready2); + /// ``` + pub fn from_usize(val: usize) -> Ready { + Ready(val) + } + + /// Returns a `usize` representation of the `Ready` value. + /// + /// This `usize` representation must be treated as opaque. There is no + /// guaranteed correlation between the returned value and platform defined + /// constants. Also, there is no guarantee that the `usize` representation + /// will remain constant across patch releases of Mio. + /// + /// This function is mainly provided to allow the caller to store a + /// readiness value in an `AtomicUsize`. + /// + /// # Examples + /// + /// ``` + /// use mio::Ready; + /// + /// let ready = Ready::readable(); + /// let ready_usize = ready.as_usize(); + /// let ready2 = Ready::from_usize(ready_usize); + /// + /// assert_eq!(ready, ready2); + /// ``` + pub fn as_usize(&self) -> usize { + self.0 + } +} + +impl> ops::BitOr for Ready { + type Output = Ready; + + #[inline] + fn bitor(self, other: T) -> Ready { + Ready(self.0 | other.into().0) + } +} + +impl> ops::BitOrAssign for Ready { + #[inline] + fn bitor_assign(&mut self, other: T) { + self.0 |= other.into().0; + } +} + +impl> ops::BitXor for Ready { + type Output = Ready; + + #[inline] + fn bitxor(self, other: T) -> Ready { + Ready(self.0 ^ other.into().0) + } +} + +impl> ops::BitXorAssign for Ready { + #[inline] + fn bitxor_assign(&mut self, other: T) { + self.0 ^= other.into().0; + } +} + +impl> ops::BitAnd for Ready { + type Output = Ready; + + #[inline] + fn bitand(self, other: T) -> Ready { + Ready(self.0 & other.into().0) + } +} + +impl> ops::BitAndAssign for Ready { + #[inline] + fn bitand_assign(&mut self, other: T) { + self.0 &= other.into().0 + } +} + +impl> ops::Sub for Ready { + type Output = Ready; + + #[inline] + fn sub(self, other: T) -> Ready { + Ready(self.0 & !other.into().0) + } +} + +impl> ops::SubAssign for Ready { + #[inline] + fn sub_assign(&mut self, other: T) { + self.0 &= !other.into().0; + } +} + +#[deprecated(since = "0.6.10", note = "removed")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +impl ops::Not for Ready { + type Output = Ready; + + #[inline] + fn not(self) -> Ready { + Ready(!self.0) + } +} + +impl fmt::Debug for Ready { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut one = false; + let flags = [ + (Ready::readable(), "Readable"), + (Ready::writable(), "Writable"), + (Ready(ERROR), "Error"), + (Ready(HUP), "Hup")]; + + for &(flag, msg) in &flags { + if self.contains(flag) { + if one { write!(fmt, " | ")? } + write!(fmt, "{}", msg)?; + + one = true + } + } + + if !one { + fmt.write_str("(empty)")?; + } + + Ok(()) + } +} + +#[test] +fn test_debug_ready() { + assert_eq!("(empty)", format!("{:?}", Ready::empty())); + assert_eq!("Readable", format!("{:?}", Ready::readable())); + assert_eq!("Writable", format!("{:?}", Ready::writable())); +} + +/// An readiness event returned by [`Poll::poll`]. +/// +/// `Event` is a [readiness state] paired with a [`Token`]. It is returned by +/// [`Poll::poll`]. +/// +/// For more documentation on polling and events, see [`Poll`]. +/// +/// # Examples +/// +/// ``` +/// use mio::{Ready, Token}; +/// use mio::event::Event; +/// +/// let event = Event::new(Ready::readable() | Ready::writable(), Token(0)); +/// +/// assert_eq!(event.readiness(), Ready::readable() | Ready::writable()); +/// assert_eq!(event.token(), Token(0)); +/// ``` +/// +/// [`Poll::poll`]: ../struct.Poll.html#method.poll +/// [`Poll`]: ../struct.Poll.html +/// [readiness state]: ../struct.Ready.html +/// [`Token`]: ../struct.Token.html +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +pub struct Event { + kind: Ready, + token: Token +} + +impl Event { + /// Creates a new `Event` containing `readiness` and `token` + /// + /// # Examples + /// + /// ``` + /// use mio::{Ready, Token}; + /// use mio::event::Event; + /// + /// let event = Event::new(Ready::readable() | Ready::writable(), Token(0)); + /// + /// assert_eq!(event.readiness(), Ready::readable() | Ready::writable()); + /// assert_eq!(event.token(), Token(0)); + /// ``` + pub fn new(readiness: Ready, token: Token) -> Event { + Event { + kind: readiness, + token, + } + } + + /// Returns the event's readiness. + /// + /// # Examples + /// + /// ``` + /// use mio::{Ready, Token}; + /// use mio::event::Event; + /// + /// let event = Event::new(Ready::readable() | Ready::writable(), Token(0)); + /// + /// assert_eq!(event.readiness(), Ready::readable() | Ready::writable()); + /// ``` + pub fn readiness(&self) -> Ready { + self.kind + } + + #[deprecated(since = "0.6.5", note = "use Event::readiness()")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn kind(&self) -> Ready { + self.kind + } + + /// Returns the event's token. + /// + /// # Examples + /// + /// ``` + /// use mio::{Ready, Token}; + /// use mio::event::Event; + /// + /// let event = Event::new(Ready::readable() | Ready::writable(), Token(0)); + /// + /// assert_eq!(event.token(), Token(0)); + /// ``` + pub fn token(&self) -> Token { + self.token + } +} + +/* + * + * ===== Mio internal helpers ===== + * + */ + +pub fn ready_as_usize(events: Ready) -> usize { + events.0 +} + +pub fn opt_as_usize(opt: PollOpt) -> usize { + opt.0 +} + +pub fn ready_from_usize(events: usize) -> Ready { + Ready(events) +} + +pub fn opt_from_usize(opt: usize) -> PollOpt { + PollOpt(opt) +} + +// Used internally to mutate an `Event` in place +// Not used on all platforms +#[allow(dead_code)] +pub fn kind_mut(event: &mut Event) -> &mut Ready { + &mut event.kind +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/io.rs b/third_party/cargo/vendor/mio-0.6.21/src/io.rs new file mode 100644 index 0000000..2750013 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/io.rs @@ -0,0 +1,35 @@ +// Re-export the io::Result / Error types for convenience +pub use std::io::{Read, Write, Result, Error, ErrorKind}; + +// TODO: Delete this +/// A helper trait to provide the map_non_block function on Results. +pub trait MapNonBlock { + /// Maps a `Result` to a `Result>` by converting + /// operation-would-block errors into `Ok(None)`. + fn map_non_block(self) -> Result>; +} + +impl MapNonBlock for Result { + fn map_non_block(self) -> Result> { + use std::io::ErrorKind::WouldBlock; + + match self { + Ok(value) => Ok(Some(value)), + Err(err) => { + if let WouldBlock = err.kind() { + Ok(None) + } else { + Err(err) + } + } + } + } +} + +#[cfg(feature = "with-deprecated")] +pub mod deprecated { + /// Returns a std `WouldBlock` error without allocating + pub fn would_block() -> ::std::io::Error { + ::std::io::ErrorKind::WouldBlock.into() + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/lazycell.rs b/third_party/cargo/vendor/mio-0.6.21/src/lazycell.rs new file mode 100644 index 0000000..681fb2f --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/lazycell.rs @@ -0,0 +1,554 @@ +// Original work Copyright (c) 2014 The Rust Project Developers +// Modified work Copyright (c) 2016-2018 Nikita Pekin and the lazycell contributors +// See the README.md file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![deny(missing_docs)] +#![allow(unused)] + +//! This crate provides a `LazyCell` struct which acts as a lazily filled +//! `Cell`. +//! +//! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of +//! the entire object, but only of the borrows returned. A `LazyCell` is a +//! variation on `RefCell` which allows borrows to be tied to the lifetime of +//! the outer object. +//! +//! `AtomicLazyCell` is a variant that uses an atomic variable to manage +//! coordination in a thread-safe fashion. The limitation of an `AtomicLazyCell` +//! is that after it is initialized, it can't be modified. + +use std::cell::UnsafeCell; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A lazily filled `Cell`, with mutable contents. +/// +/// A `LazyCell` is completely frozen once filled, **unless** you have `&mut` +/// access to it, in which case `LazyCell::borrow_mut` may be used to mutate the +/// contents. +#[derive(Debug, Default)] +pub struct LazyCell { + inner: UnsafeCell>, +} + +impl LazyCell { + /// Creates a new, empty, `LazyCell`. + pub fn new() -> LazyCell { + LazyCell { inner: UnsafeCell::new(None) } + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, value: T) -> Result<(), T> { + let slot = unsafe { &mut *self.inner.get() }; + if slot.is_some() { + return Err(value); + } + *slot = Some(value); + + Ok(()) + } + + /// Put a value into this cell. + /// + /// Note that this function is infallible but requires `&mut self`. By + /// requiring `&mut self` we're guaranteed that no active borrows to this + /// cell can exist so we can always fill in the value. This may not always + /// be usable, however, as `&mut self` may not be possible to borrow. + /// + /// # Return value + /// + /// This function returns the previous value, if any. + pub fn replace(&mut self, value: T) -> Option { + mem::replace(unsafe { &mut *self.inner.get() }, Some(value)) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.borrow().is_some() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + unsafe { &*self.inner.get() }.as_ref() + } + + /// Borrows the contents of this lazy cell mutably for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow_mut(&mut self) -> Option<&mut T> { + unsafe { &mut *self.inner.get() }.as_mut() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// If the cell has not yet been filled, the cell is first filled using the + /// function provided. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn borrow_with T>(&self, f: F) -> &T { + if let Some(value) = self.borrow() { + return value; + } + let value = f(); + if self.fill(value).is_err() { + panic!("borrow_with: cell was filled by closure") + } + self.borrow().unwrap() + } + + /// Borrows the contents of this `LazyCell` mutably for the duration of the + /// cell itself. + /// + /// If the cell has not yet been filled, the cell is first filled using the + /// function provided. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn borrow_mut_with T>(&mut self, f: F) -> &mut T { + if !self.filled() { + let value = f(); + if self.fill(value).is_err() { + panic!("borrow_mut_with: cell was filled by closure") + } + } + + self.borrow_mut().unwrap() + } + + /// Same as `borrow_with`, but allows the initializing function to fail. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn try_borrow_with(&self, f: F) -> Result<&T, E> + where F: FnOnce() -> Result + { + if let Some(value) = self.borrow() { + return Ok(value); + } + let value = f()?; + if self.fill(value).is_err() { + panic!("try_borrow_with: cell was filled by closure") + } + Ok(self.borrow().unwrap()) + } + + /// Same as `borrow_mut_with`, but allows the initializing function to fail. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn try_borrow_mut_with(&mut self, f: F) -> Result<&mut T, E> + where F: FnOnce() -> Result + { + if self.filled() { + return Ok(self.borrow_mut().unwrap()); + } + let value = f()?; + if self.fill(value).is_err() { + panic!("try_borrow_mut_with: cell was filled by closure") + } + Ok(self.borrow_mut().unwrap()) + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe + // function. This unsafe can be removed when supporting Rust older than + // 1.25 is not needed. + #[allow(unused_unsafe)] + unsafe { self.inner.into_inner() } + } +} + +impl LazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + unsafe { *self.inner.get() } + } +} + +// Tracks the AtomicLazyCell inner state +const NONE: usize = 0; +const LOCK: usize = 1; +const SOME: usize = 2; + +/// A lazily filled and thread-safe `Cell`, with frozen contents. +#[derive(Debug, Default)] +pub struct AtomicLazyCell { + inner: UnsafeCell>, + state: AtomicUsize, +} + +impl AtomicLazyCell { + /// Creates a new, empty, `AtomicLazyCell`. + pub fn new() -> AtomicLazyCell { + Self { + inner: UnsafeCell::new(None), + state: AtomicUsize::new(NONE), + } + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, t: T) -> Result<(), T> { + if NONE != self.state.compare_and_swap(NONE, LOCK, Ordering::Acquire) { + return Err(t); + } + + unsafe { *self.inner.get() = Some(t) }; + + if LOCK != self.state.compare_and_swap(LOCK, SOME, Ordering::Release) { + panic!("unable to release lock"); + } + + Ok(()) + } + + /// Put a value into this cell. + /// + /// Note that this function is infallible but requires `&mut self`. By + /// requiring `&mut self` we're guaranteed that no active borrows to this + /// cell can exist so we can always fill in the value. This may not always + /// be usable, however, as `&mut self` may not be possible to borrow. + /// + /// # Return value + /// + /// This function returns the previous value, if any. + pub fn replace(&mut self, value: T) -> Option { + match mem::replace(self.state.get_mut(), SOME) { + NONE | SOME => {} + _ => panic!("cell in inconsistent state"), + } + mem::replace(unsafe { &mut *self.inner.get() }, Some(value)) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.state.load(Ordering::Acquire) == SOME + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { &*self.inner.get() }.as_ref(), + _ => None, + } + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + // Rust 1.25 changed UnsafeCell::into_inner() from unsafe to safe + // function. This unsafe can be removed when supporting Rust older than + // 1.25 is not needed. + #[allow(unused_unsafe)] + unsafe { self.inner.into_inner() } + } +} + +impl AtomicLazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { *self.inner.get() }, + _ => None, + } + } +} + +unsafe impl Sync for AtomicLazyCell {} + +unsafe impl Send for AtomicLazyCell {} + +#[cfg(test)] +mod tests { + use super::{AtomicLazyCell, LazyCell}; + + #[test] + fn test_borrow_from_empty() { + let lazycell: LazyCell = LazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_fill_and_borrow() { + let lazycell = LazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_borrow_mut() { + let mut lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.borrow_mut(), Some(&mut 1)); + + *lazycell.borrow_mut().unwrap() = 2; + assert_eq!(lazycell.borrow_mut(), Some(&mut 2)); + + // official way to reset the cell + lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + } + + #[test] + fn test_already_filled_error() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.fill(1), Err(1)); + } + + #[test] + fn test_borrow_with() { + let lazycell = LazyCell::new(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_not_called_when_filled() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 2); + assert_eq!(&1, value); + } + + #[test] + #[should_panic] + fn test_borrow_with_sound_with_reentrancy() { + // Kudos to dbaupp for discovering this issue + // https://www.reddit.com/r/rust/comments/5vs9rt/lazycell_a_rust_library_providing_a_lazilyfilled/de527xm/ + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + lazycell.borrow_with(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Box::new(2) + }); + } + + #[test] + fn test_borrow_mut_with() { + let mut lazycell = LazyCell::new(); + + { + let value = lazycell.borrow_mut_with(|| 1); + assert_eq!(&mut 1, value); + *value = 2; + } + assert_eq!(&2, lazycell.borrow().unwrap()); + } + + #[test] + fn test_borrow_mut_with_already_filled() { + let mut lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_mut_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_mut_with_not_called_when_filled() { + let mut lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_mut_with(|| 2); + assert_eq!(&1, value); + } + + #[test] + fn test_try_borrow_with_ok() { + let lazycell = LazyCell::new(); + let result = lazycell.try_borrow_with::<(), _>(|| Ok(1)); + assert_eq!(result, Ok(&1)); + } + + #[test] + fn test_try_borrow_with_err() { + let lazycell = LazyCell::<()>::new(); + let result = lazycell.try_borrow_with(|| Err(1)); + assert_eq!(result, Err(1)); + } + + #[test] + fn test_try_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + let result = lazycell.try_borrow_with::<(), _>(|| unreachable!()); + assert_eq!(result, Ok(&1)); + } + + #[test] + #[should_panic] + fn test_try_borrow_with_sound_with_reentrancy() { + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + let _ = lazycell.try_borrow_with::<(), _>(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Ok(Box::new(2)) + }); + } + + #[test] + fn test_try_borrow_mut_with_ok() { + let mut lazycell = LazyCell::new(); + { + let result = lazycell.try_borrow_mut_with::<(), _>(|| Ok(1)); + assert_eq!(result, Ok(&mut 1)); + *result.unwrap() = 2; + } + assert_eq!(&mut 2, lazycell.borrow().unwrap()); + } + + #[test] + fn test_try_borrow_mut_with_err() { + let mut lazycell = LazyCell::<()>::new(); + let result = lazycell.try_borrow_mut_with(|| Err(1)); + assert_eq!(result, Err(1)); + } + + #[test] + fn test_try_borrow_mut_with_already_filled() { + let mut lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + let result = lazycell.try_borrow_mut_with::<(), _>(|| unreachable!()); + assert_eq!(result, Ok(&mut 1)); + } + + #[test] + fn test_into_inner() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_borrow_from_empty() { + let lazycell: AtomicLazyCell = AtomicLazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_atomic_fill_and_borrow() { + let lazycell = AtomicLazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_already_filled_panic() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(1, lazycell.fill(1).unwrap_err()); + } + + #[test] + fn test_atomic_into_inner() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } + + #[test] + fn normal_replace() { + let mut cell = LazyCell::new(); + assert_eq!(cell.fill(1), Ok(())); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(cell.replace(3), Some(2)); + assert_eq!(cell.borrow(), Some(&3)); + + let mut cell = LazyCell::new(); + assert_eq!(cell.replace(2), None); + } + + #[test] + fn atomic_replace() { + let mut cell = AtomicLazyCell::new(); + assert_eq!(cell.fill(1), Ok(())); + assert_eq!(cell.replace(2), Some(1)); + assert_eq!(cell.replace(3), Some(2)); + assert_eq!(cell.borrow(), Some(&3)); + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/lib.rs b/third_party/cargo/vendor/mio-0.6.21/src/lib.rs new file mode 100644 index 0000000..1d2f500 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/lib.rs @@ -0,0 +1,311 @@ +#![doc(html_root_url = "https://docs.rs/mio/0.6.21")] +// Mio targets old versions of the Rust compiler. In order to do this, uses +// deprecated APIs. +#![allow(bare_trait_objects, deprecated, unknown_lints)] +#![deny(missing_docs, missing_debug_implementations)] +#![cfg_attr(test, deny(warnings))] + +// Many of mio's public methods violate this lint, but they can't be fixed +// without a breaking change. +#![cfg_attr(feature = "cargo-clippy", allow(clippy::trivially_copy_pass_by_ref))] + +//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event +//! notification, and other useful utilities for building high performance IO +//! apps. +//! +//! # Features +//! +//! * Non-blocking TCP, UDP +//! * I/O event notification queue backed by epoll, kqueue, and IOCP +//! * Zero allocations at runtime +//! * Platform specific extensions +//! +//! # Non-goals +//! +//! The following are specifically omitted from Mio and are left to the user or higher-level libraries. +//! +//! * File operations +//! * Thread pools / multi-threaded event loop +//! * Timers +//! +//! # Platforms +//! +//! Currently supported platforms: +//! +//! * Linux +//! * OS X +//! * Windows +//! * FreeBSD +//! * NetBSD +//! * Android +//! * iOS +//! +//! mio can handle interfacing with each of the event notification systems of the aforementioned platforms. The details of +//! their implementation are further discussed in [`Poll`]. +//! +//! # Usage +//! +//! Using mio starts by creating a [`Poll`], which reads events from the OS and +//! put them into [`Events`]. You can handle IO events from the OS with it. +//! +//! For more detail, see [`Poll`]. +//! +//! [`Poll`]: struct.Poll.html +//! [`Events`]: struct.Events.html +//! +//! # Example +//! +//! ``` +//! use mio::*; +//! use mio::net::{TcpListener, TcpStream}; +//! +//! // Setup some tokens to allow us to identify which event is +//! // for which socket. +//! const SERVER: Token = Token(0); +//! const CLIENT: Token = Token(1); +//! +//! let addr = "127.0.0.1:13265".parse().unwrap(); +//! +//! // Setup the server socket +//! let server = TcpListener::bind(&addr).unwrap(); +//! +//! // Create a poll instance +//! let poll = Poll::new().unwrap(); +//! +//! // Start listening for incoming connections +//! poll.register(&server, SERVER, Ready::readable(), +//! PollOpt::edge()).unwrap(); +//! +//! // Setup the client socket +//! let sock = TcpStream::connect(&addr).unwrap(); +//! +//! // Register the socket +//! poll.register(&sock, CLIENT, Ready::readable(), +//! PollOpt::edge()).unwrap(); +//! +//! // Create storage for events +//! let mut events = Events::with_capacity(1024); +//! +//! loop { +//! poll.poll(&mut events, None).unwrap(); +//! +//! for event in events.iter() { +//! match event.token() { +//! SERVER => { +//! // Accept and drop the socket immediately, this will close +//! // the socket and notify the client of the EOF. +//! let _ = server.accept(); +//! } +//! CLIENT => { +//! // The server just shuts down the socket, let's just exit +//! // from our event loop. +//! return; +//! } +//! _ => unreachable!(), +//! } +//! } +//! } +//! +//! ``` + +extern crate net2; +extern crate iovec; +extern crate slab; + +#[cfg(target_os = "fuchsia")] +extern crate fuchsia_zircon as zircon; +#[cfg(target_os = "fuchsia")] +extern crate fuchsia_zircon_sys as zircon_sys; + +#[cfg(unix)] +extern crate libc; + +#[cfg(windows)] +extern crate miow; + +#[cfg(windows)] +extern crate winapi; + +#[cfg(windows)] +extern crate kernel32; + +#[macro_use] +extern crate log; + +mod event_imp; +mod io; +mod poll; +mod sys; +mod token; +mod lazycell; + +pub mod net; + +#[deprecated(since = "0.6.5", note = "use mio-extras instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub mod channel; + +#[deprecated(since = "0.6.5", note = "use mio-extras instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub mod timer; + +#[deprecated(since = "0.6.5", note = "update to use `Poll`")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub mod deprecated; + +#[deprecated(since = "0.6.5", note = "use iovec crate directly")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub use iovec::IoVec; + +#[deprecated(since = "0.6.6", note = "use net module instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub mod tcp { + pub use net::{TcpListener, TcpStream}; + pub use std::net::Shutdown; +} + +#[deprecated(since = "0.6.6", note = "use net module instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub mod udp; + +pub use poll::{ + Poll, + Registration, + SetReadiness, +}; +pub use event_imp::{ + PollOpt, + Ready, +}; +pub use token::Token; + +pub mod event { + //! Readiness event types and utilities. + + pub use super::poll::{Events, Iter}; + pub use super::event_imp::{Event, Evented}; +} + +pub use event::{ + Events, +}; + +#[deprecated(since = "0.6.5", note = "use events:: instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub use event::{Event, Evented}; + +#[deprecated(since = "0.6.5", note = "use events::Iter instead")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub use poll::Iter as EventsIter; + +#[deprecated(since = "0.6.5", note = "std::io::Error can avoid the allocation now")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +pub use io::deprecated::would_block; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub mod unix { + //! Unix only extensions + pub use sys::{ + EventedFd, + }; + pub use sys::unix::UnixReady; +} + +#[cfg(target_os = "fuchsia")] +pub mod fuchsia { + //! Fuchsia-only extensions + //! + //! # Stability + //! + //! This module depends on the [magenta-sys crate](https://crates.io/crates/magenta-sys) + //! and so might introduce breaking changes, even on minor releases, + //! so long as that crate remains unstable. + pub use sys::{ + EventedHandle, + }; + pub use sys::fuchsia::{FuchsiaReady, zx_signals_t}; +} + +/// Windows-only extensions to the mio crate. +/// +/// Mio on windows is currently implemented with IOCP for a high-performance +/// implementation of asynchronous I/O. Mio then provides TCP and UDP as sample +/// bindings for the system to connect networking types to asynchronous I/O. On +/// Unix this scheme is then also extensible to all other file descriptors with +/// the `EventedFd` type, but on Windows no such analog is available. The +/// purpose of this module, however, is to similarly provide a mechanism for +/// foreign I/O types to get hooked up into the IOCP event loop. +/// +/// This module provides two types for interfacing with a custom IOCP handle: +/// +/// * `Binding` - this type is intended to govern binding with mio's `Poll` +/// type. Each I/O object should contain an instance of `Binding` that's +/// interfaced with for the implementation of the `Evented` trait. The +/// `register`, `reregister`, and `deregister` methods for the `Evented` trait +/// all have rough analogs with `Binding`. +/// +/// Note that this type **does not handle readiness**. That is, this type does +/// not handle whether sockets are readable/writable/etc. It's intended that +/// IOCP types will internally manage this state with a `SetReadiness` type +/// from the `poll` module. The `SetReadiness` is typically lazily created on +/// the first time that `Evented::register` is called and then stored in the +/// I/O object. +/// +/// Also note that for types which represent streams of bytes the mio +/// interface of *readiness* doesn't map directly to the Windows model of +/// *completion*. This means that types will have to perform internal +/// buffering to ensure that a readiness interface can be provided. For a +/// sample implementation see the TCP/UDP modules in mio itself. +/// +/// * `Overlapped` - this type is intended to be used as the concrete instances +/// of the `OVERLAPPED` type that most win32 methods expect. It's crucial, for +/// safety, that all asynchronous operations are initiated with an instance of +/// `Overlapped` and not another instantiation of `OVERLAPPED`. +/// +/// Mio's `Overlapped` type is created with a function pointer that receives +/// a `OVERLAPPED_ENTRY` type when called. This `OVERLAPPED_ENTRY` type is +/// defined in the `winapi` crate. Whenever a completion is posted to an IOCP +/// object the `OVERLAPPED` that was signaled will be interpreted as +/// `Overlapped` in the mio crate and this function pointer will be invoked. +/// Through this function pointer, and through the `OVERLAPPED` pointer, +/// implementations can handle management of I/O events. +/// +/// When put together these two types enable custom Windows handles to be +/// registered with mio's event loops. The `Binding` type is used to associate +/// handles and the `Overlapped` type is used to execute I/O operations. When +/// the I/O operations are completed a custom function pointer is called which +/// typically modifies a `SetReadiness` set by `Evented` methods which will get +/// later hooked into the mio event loop. +#[cfg(windows)] +pub mod windows { + + pub use sys::{Overlapped, Binding}; +} + +#[cfg(feature = "with-deprecated")] +mod convert { + use std::time::Duration; + + const NANOS_PER_MILLI: u32 = 1_000_000; + const MILLIS_PER_SEC: u64 = 1_000; + + /// Convert a `Duration` to milliseconds, rounding up and saturating at + /// `u64::MAX`. + /// + /// The saturating is fine because `u64::MAX` milliseconds are still many + /// million years. + pub fn millis(duration: Duration) -> u64 { + // Round up. + let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; + duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(u64::from(millis)) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/net/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/net/mod.rs new file mode 100644 index 0000000..53025c6 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/net/mod.rs @@ -0,0 +1,14 @@ +//! Networking primitives +//! +//! The types provided in this module are non-blocking by default and are +//! designed to be portable across all supported Mio platforms. As long as the +//! [portability guidelines] are followed, the behavior should be identical no +//! matter the target platform. +//! +//! [portability guidelines]: ../struct.Poll.html#portability + +mod tcp; +mod udp; + +pub use self::tcp::{TcpListener, TcpStream}; +pub use self::udp::UdpSocket; diff --git a/third_party/cargo/vendor/mio-0.6.21/src/net/tcp.rs b/third_party/cargo/vendor/mio-0.6.21/src/net/tcp.rs new file mode 100644 index 0000000..cc74ab9 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/net/tcp.rs @@ -0,0 +1,737 @@ +//! Primitives for working with TCP +//! +//! The types provided in this module are non-blocking by default and are +//! designed to be portable across all supported Mio platforms. As long as the +//! [portability guidelines] are followed, the behavior should be identical no +//! matter the target platform. +//! +/// [portability guidelines]: ../struct.Poll.html#portability + +use std::fmt; +use std::io::{Read, Write}; +use std::net::{self, SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr}; +use std::time::Duration; + +use net2::TcpBuilder; +use iovec::IoVec; + +use {io, sys, Ready, Poll, PollOpt, Token}; +use event::Evented; +use poll::SelectorId; + +/* + * + * ===== TcpStream ===== + * + */ + +/// A non-blocking TCP stream between a local socket and a remote socket. +/// +/// The socket will be closed when the value is dropped. +/// +/// # Examples +/// +/// ``` +/// # use std::net::TcpListener; +/// # use std::error::Error; +/// # +/// # fn try_main() -> Result<(), Box> { +/// # let _listener = TcpListener::bind("127.0.0.1:34254")?; +/// use mio::{Events, Ready, Poll, PollOpt, Token}; +/// use mio::net::TcpStream; +/// use std::time::Duration; +/// +/// let stream = TcpStream::connect(&"127.0.0.1:34254".parse()?)?; +/// +/// let poll = Poll::new()?; +/// let mut events = Events::with_capacity(128); +/// +/// // Register the socket with `Poll` +/// poll.register(&stream, Token(0), Ready::writable(), +/// PollOpt::edge())?; +/// +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// +/// // The socket might be ready at this point +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +pub struct TcpStream { + sys: sys::TcpStream, + selector_id: SelectorId, +} + +use std::net::Shutdown; + +// TODO: remove when fuchsia's set_nonblocking is fixed in libstd +#[cfg(target_os = "fuchsia")] +fn set_nonblocking(stream: &net::TcpStream) -> io::Result<()> { + sys::set_nonblock( + ::std::os::unix::io::AsRawFd::as_raw_fd(stream)) +} +#[cfg(not(target_os = "fuchsia"))] +fn set_nonblocking(stream: &net::TcpStream) -> io::Result<()> { + stream.set_nonblocking(true) +} + + +impl TcpStream { + /// Create a new TCP stream and issue a non-blocking connect to the + /// specified address. + /// + /// This convenience method is available and uses the system's default + /// options when creating a socket which is then connected. If fine-grained + /// control over the creation of the socket is desired, you can use + /// `net2::TcpBuilder` to configure a socket and then pass its socket to + /// `TcpStream::connect_stream` to transfer ownership into mio and schedule + /// the connect operation. + pub fn connect(addr: &SocketAddr) -> io::Result { + let sock = match *addr { + SocketAddr::V4(..) => TcpBuilder::new_v4(), + SocketAddr::V6(..) => TcpBuilder::new_v6(), + }?; + // Required on Windows for a future `connect_overlapped` operation to be + // executed successfully. + if cfg!(windows) { + sock.bind(&inaddr_any(addr))?; + } + TcpStream::connect_stream(sock.to_tcp_stream()?, addr) + } + + /// Creates a new `TcpStream` from the pending socket inside the given + /// `std::net::TcpBuilder`, connecting it to the address specified. + /// + /// This constructor allows configuring the socket before it's actually + /// connected, and this function will transfer ownership to the returned + /// `TcpStream` if successful. An unconnected `TcpStream` can be created + /// with the `net2::TcpBuilder` type (and also configured via that route). + /// + /// The platform specific behavior of this function looks like: + /// + /// * On Unix, the socket is placed into nonblocking mode and then a + /// `connect` call is issued. + /// + /// * On Windows, the address is stored internally and the connect operation + /// is issued when the returned `TcpStream` is registered with an event + /// loop. Note that on Windows you must `bind` a socket before it can be + /// connected, so if a custom `TcpBuilder` is used it should be bound + /// (perhaps to `INADDR_ANY`) before this method is called. + pub fn connect_stream(stream: net::TcpStream, + addr: &SocketAddr) -> io::Result { + Ok(TcpStream { + sys: sys::TcpStream::connect(stream, addr)?, + selector_id: SelectorId::new(), + }) + } + + /// Creates a new `TcpStream` from a standard `net::TcpStream`. + /// + /// This function is intended to be used to wrap a TCP stream from the + /// standard library in the mio equivalent. The conversion here will + /// automatically set `stream` to nonblocking and the returned object should + /// be ready to get associated with an event loop. + /// + /// Note that the TCP stream here will not have `connect` called on it, so + /// it should already be connected via some other means (be it manually, the + /// net2 crate, or the standard library). + pub fn from_stream(stream: net::TcpStream) -> io::Result { + set_nonblocking(&stream)?; + + Ok(TcpStream { + sys: sys::TcpStream::from_stream(stream), + selector_id: SelectorId::new(), + }) + } + + /// Returns the socket address of the remote peer of this TCP connection. + pub fn peer_addr(&self) -> io::Result { + self.sys.peer_addr() + } + + /// Returns the socket address of the local half of this TCP connection. + pub fn local_addr(&self) -> io::Result { + self.sys.local_addr() + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `TcpStream` is a reference to the same stream that this + /// object references. Both handles will read and write the same stream of + /// data, and options set on one stream will be propagated to the other + /// stream. + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone().map(|s| { + TcpStream { + sys: s, + selector_id: self.selector_id.clone(), + } + }) + } + + /// Shuts down the read, write, or both halves of this connection. + /// + /// This function will cause all pending and future I/O on the specified + /// portions to return immediately with an appropriate value (see the + /// documentation of `Shutdown`). + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + self.sys.shutdown(how) + } + + /// Sets the value of the `TCP_NODELAY` option on this socket. + /// + /// If set, this option disables the Nagle algorithm. This means that + /// segments are always sent as soon as possible, even if there is only a + /// small amount of data. When not set, data is buffered until there is a + /// sufficient amount to send out, thereby avoiding the frequent sending of + /// small packets. + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + self.sys.set_nodelay(nodelay) + } + + /// Gets the value of the `TCP_NODELAY` option on this socket. + /// + /// For more information about this option, see [`set_nodelay`][link]. + /// + /// [link]: #method.set_nodelay + pub fn nodelay(&self) -> io::Result { + self.sys.nodelay() + } + + /// Sets the value of the `SO_RCVBUF` option on this socket. + /// + /// Changes the size of the operating system's receive buffer associated + /// with the socket. + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + self.sys.set_recv_buffer_size(size) + } + + /// Gets the value of the `SO_RCVBUF` option on this socket. + /// + /// For more information about this option, see + /// [`set_recv_buffer_size`][link]. + /// + /// [link]: #method.set_recv_buffer_size + pub fn recv_buffer_size(&self) -> io::Result { + self.sys.recv_buffer_size() + } + + /// Sets the value of the `SO_SNDBUF` option on this socket. + /// + /// Changes the size of the operating system's send buffer associated with + /// the socket. + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + self.sys.set_send_buffer_size(size) + } + + /// Gets the value of the `SO_SNDBUF` option on this socket. + /// + /// For more information about this option, see + /// [`set_send_buffer_size`][link]. + /// + /// [link]: #method.set_send_buffer_size + pub fn send_buffer_size(&self) -> io::Result { + self.sys.send_buffer_size() + } + + /// Sets whether keepalive messages are enabled to be sent on this socket. + /// + /// On Unix, this option will set the `SO_KEEPALIVE` as well as the + /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). + /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. + /// + /// If `None` is specified then keepalive messages are disabled, otherwise + /// the duration specified will be the time to remain idle before sending a + /// TCP keepalive probe. + /// + /// Some platforms specify this value in seconds, so sub-second + /// specifications may be omitted. + pub fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { + self.sys.set_keepalive(keepalive) + } + + /// Returns whether keepalive messages are enabled on this socket, and if so + /// the duration of time between them. + /// + /// For more information about this option, see [`set_keepalive`][link]. + /// + /// [link]: #method.set_keepalive + pub fn keepalive(&self) -> io::Result> { + self.sys.keepalive() + } + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.sys.set_ttl(ttl) + } + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #method.set_ttl + pub fn ttl(&self) -> io::Result { + self.sys.ttl() + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// If this is set to `true` then the socket is restricted to sending and + /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications + /// can bind the same port at the same time. + /// + /// If this is set to `false` then the socket can be used to send and + /// receive packets from an IPv4-mapped IPv6 address. + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.sys.set_only_v6(only_v6) + } + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see [`set_only_v6`][link]. + /// + /// [link]: #method.set_only_v6 + pub fn only_v6(&self) -> io::Result { + self.sys.only_v6() + } + + /// Sets the value for the `SO_LINGER` option on this socket. + pub fn set_linger(&self, dur: Option) -> io::Result<()> { + self.sys.set_linger(dur) + } + + /// Gets the value of the `SO_LINGER` option on this socket. + /// + /// For more information about this option, see [`set_linger`][link]. + /// + /// [link]: #method.set_linger + pub fn linger(&self) -> io::Result> { + self.sys.linger() + } + + #[deprecated(since = "0.6.9", note = "use set_keepalive")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn set_keepalive_ms(&self, keepalive: Option) -> io::Result<()> { + self.set_keepalive(keepalive.map(|v| { + Duration::from_millis(u64::from(v)) + })) + } + + #[deprecated(since = "0.6.9", note = "use keepalive")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn keepalive_ms(&self) -> io::Result> { + self.keepalive().map(|v| { + v.map(|v| { + ::convert::millis(v) as u32 + }) + }) + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + self.sys.take_error() + } + + /// Receives data on the socket from the remote address to which it is + /// connected, without removing that data from the queue. On success, + /// returns the number of bytes peeked. + /// + /// Successive calls return the same data. This is accomplished by passing + /// `MSG_PEEK` as a flag to the underlying recv system call. + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.sys.peek(buf) + } + + /// Read in a list of buffers all at once. + /// + /// This operation will attempt to read bytes from this socket and place + /// them into the list of buffers provided. Note that each buffer is an + /// `IoVec` which can be created from a byte slice. + /// + /// The buffers provided will be filled in sequentially. A buffer will be + /// entirely filled up before the next is written to. + /// + /// The number of bytes read is returned, if successful, or an error is + /// returned otherwise. If no bytes are available to be read yet then + /// a "would block" error is returned. This operation does not block. + /// + /// On Unix this corresponds to the `readv` syscall. + pub fn read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result { + self.sys.readv(bufs) + } + + /// Write a list of buffers all at once. + /// + /// This operation will attempt to write a list of byte buffers to this + /// socket. Note that each buffer is an `IoVec` which can be created from a + /// byte slice. + /// + /// The buffers provided will be written sequentially. A buffer will be + /// entirely written before the next is written. + /// + /// The number of bytes written is returned, if successful, or an error is + /// returned otherwise. If the socket is not currently writable then a + /// "would block" error is returned. This operation does not block. + /// + /// On Unix this corresponds to the `writev` syscall. + pub fn write_bufs(&self, bufs: &[&IoVec]) -> io::Result { + self.sys.writev(bufs) + } +} + +fn inaddr_any(other: &SocketAddr) -> SocketAddr { + match *other { + SocketAddr::V4(..) => { + let any = Ipv4Addr::new(0, 0, 0, 0); + let addr = SocketAddrV4::new(any, 0); + SocketAddr::V4(addr) + } + SocketAddr::V6(..) => { + let any = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0); + let addr = SocketAddrV6::new(any, 0, 0, 0); + SocketAddr::V6(addr) + } + } +} + +impl Read for TcpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + (&self.sys).read(buf) + } +} + +impl<'a> Read for &'a TcpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + (&self.sys).read(buf) + } +} + +impl Write for TcpStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + (&self.sys).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.sys).flush() + } +} + +impl<'a> Write for &'a TcpStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + (&self.sys).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.sys).flush() + } +} + +impl Evented for TcpStream { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + self.selector_id.associate_selector(poll)?; + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.sys, f) + } +} + +/* + * + * ===== TcpListener ===== + * + */ + +/// A structure representing a socket server +/// +/// # Examples +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Ready, Poll, PollOpt, Token}; +/// use mio::net::TcpListener; +/// use std::time::Duration; +/// +/// let listener = TcpListener::bind(&"127.0.0.1:34255".parse()?)?; +/// +/// let poll = Poll::new()?; +/// let mut events = Events::with_capacity(128); +/// +/// // Register the socket with `Poll` +/// poll.register(&listener, Token(0), Ready::readable(), +/// PollOpt::edge())?; +/// +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// +/// // There may be a socket ready to be accepted +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +pub struct TcpListener { + sys: sys::TcpListener, + selector_id: SelectorId, +} + +impl TcpListener { + /// Convenience method to bind a new TCP listener to the specified address + /// to receive new connections. + /// + /// This function will take the following steps: + /// + /// 1. Create a new TCP socket. + /// 2. Set the `SO_REUSEADDR` option on the socket. + /// 3. Bind the socket to the specified address. + /// 4. Call `listen` on the socket to prepare it to receive new connections. + /// + /// If fine-grained control over the binding and listening process for a + /// socket is desired then the `net2::TcpBuilder` methods can be used in + /// combination with the `TcpListener::from_listener` method to transfer + /// ownership into mio. + pub fn bind(addr: &SocketAddr) -> io::Result { + // Create the socket + let sock = match *addr { + SocketAddr::V4(..) => TcpBuilder::new_v4(), + SocketAddr::V6(..) => TcpBuilder::new_v6(), + }?; + + // Set SO_REUSEADDR, but only on Unix (mirrors what libstd does) + if cfg!(unix) { + sock.reuse_address(true)?; + } + + // Bind the socket + sock.bind(addr)?; + + // listen + let listener = sock.listen(1024)?; + Ok(TcpListener { + sys: sys::TcpListener::new(listener)?, + selector_id: SelectorId::new(), + }) + } + + #[deprecated(since = "0.6.13", note = "use from_std instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn from_listener(listener: net::TcpListener, _: &SocketAddr) + -> io::Result { + TcpListener::from_std(listener) + } + + /// Creates a new `TcpListener` from an instance of a + /// `std::net::TcpListener` type. + /// + /// This function will set the `listener` provided into nonblocking mode on + /// Unix, and otherwise the stream will just be wrapped up in an mio stream + /// ready to accept new connections and become associated with an event + /// loop. + /// + /// The address provided must be the address that the listener is bound to. + pub fn from_std(listener: net::TcpListener) -> io::Result { + sys::TcpListener::new(listener).map(|s| { + TcpListener { + sys: s, + selector_id: SelectorId::new(), + } + }) + } + + /// Accepts a new `TcpStream`. + /// + /// This may return an `Err(e)` where `e.kind()` is + /// `io::ErrorKind::WouldBlock`. This means a stream may be ready at a later + /// point and one should wait for a notification before calling `accept` + /// again. + /// + /// If an accepted stream is returned, the remote address of the peer is + /// returned along with it. + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + let (s, a) = try!(self.accept_std()); + Ok((TcpStream::from_stream(s)?, a)) + } + + /// Accepts a new `std::net::TcpStream`. + /// + /// This method is the same as `accept`, except that it returns a TCP socket + /// *in blocking mode* which isn't bound to `mio`. This can be later then + /// converted to a `mio` type, if necessary. + pub fn accept_std(&self) -> io::Result<(net::TcpStream, SocketAddr)> { + self.sys.accept() + } + + /// Returns the local socket address of this listener. + pub fn local_addr(&self) -> io::Result { + self.sys.local_addr() + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `TcpListener` is a reference to the same socket that this + /// object references. Both handles can be used to accept incoming + /// connections and options set on one listener will affect the other. + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone().map(|s| { + TcpListener { + sys: s, + selector_id: self.selector_id.clone(), + } + }) + } + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.sys.set_ttl(ttl) + } + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #method.set_ttl + pub fn ttl(&self) -> io::Result { + self.sys.ttl() + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// If this is set to `true` then the socket is restricted to sending and + /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications + /// can bind the same port at the same time. + /// + /// If this is set to `false` then the socket can be used to send and + /// receive packets from an IPv4-mapped IPv6 address. + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.sys.set_only_v6(only_v6) + } + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see [`set_only_v6`][link]. + /// + /// [link]: #method.set_only_v6 + pub fn only_v6(&self) -> io::Result { + self.sys.only_v6() + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + self.sys.take_error() + } +} + +impl Evented for TcpListener { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + self.selector_id.associate_selector(poll)?; + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.sys, f) + } +} + +/* + * + * ===== UNIX ext ===== + * + */ + +#[cfg(all(unix, not(target_os = "fuchsia")))] +use std::os::unix::io::{IntoRawFd, AsRawFd, FromRawFd, RawFd}; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl IntoRawFd for TcpStream { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl AsRawFd for TcpStream { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl FromRawFd for TcpStream { + unsafe fn from_raw_fd(fd: RawFd) -> TcpStream { + TcpStream { + sys: FromRawFd::from_raw_fd(fd), + selector_id: SelectorId::new(), + } + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl IntoRawFd for TcpListener { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl AsRawFd for TcpListener { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl FromRawFd for TcpListener { + unsafe fn from_raw_fd(fd: RawFd) -> TcpListener { + TcpListener { + sys: FromRawFd::from_raw_fd(fd), + selector_id: SelectorId::new(), + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/net/udp.rs b/third_party/cargo/vendor/mio-0.6.21/src/net/udp.rs new file mode 100644 index 0000000..0d89511 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/net/udp.rs @@ -0,0 +1,645 @@ +//! Primitives for working with UDP +//! +//! The types provided in this module are non-blocking by default and are +//! designed to be portable across all supported Mio platforms. As long as the +//! [portability guidelines] are followed, the behavior should be identical no +//! matter the target platform. +//! +/// [portability guidelines]: ../struct.Poll.html#portability + +use {io, sys, Ready, Poll, PollOpt, Token}; +use event::Evented; +use poll::SelectorId; +use std::fmt; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +use iovec::IoVec; + +/// A User Datagram Protocol socket. +/// +/// This is an implementation of a bound UDP socket. This supports both IPv4 and +/// IPv6 addresses, and there is no corresponding notion of a server because UDP +/// is a datagram protocol. +/// +/// # Examples +/// +/// ``` +/// # use std::error::Error; +/// # +/// # fn try_main() -> Result<(), Box> { +/// // An Echo program: +/// // SENDER -> sends a message. +/// // ECHOER -> listens and prints the message received. +/// +/// use mio::net::UdpSocket; +/// use mio::{Events, Ready, Poll, PollOpt, Token}; +/// use std::time::Duration; +/// +/// const SENDER: Token = Token(0); +/// const ECHOER: Token = Token(1); +/// +/// // This operation will fail if the address is in use, so we select different ports for each +/// // socket. +/// let sender_socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; +/// let echoer_socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; +/// +/// // If we do not use connect here, SENDER and ECHOER would need to call send_to and recv_from +/// // respectively. +/// sender_socket.connect(echoer_socket.local_addr().unwrap())?; +/// +/// // We need a Poll to check if SENDER is ready to be written into, and if ECHOER is ready to be +/// // read from. +/// let poll = Poll::new()?; +/// +/// // We register our sockets here so that we can check if they are ready to be written/read. +/// poll.register(&sender_socket, SENDER, Ready::writable(), PollOpt::edge())?; +/// poll.register(&echoer_socket, ECHOER, Ready::readable(), PollOpt::edge())?; +/// +/// let msg_to_send = [9; 9]; +/// let mut buffer = [0; 9]; +/// +/// let mut events = Events::with_capacity(128); +/// loop { +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// for event in events.iter() { +/// match event.token() { +/// // Our SENDER is ready to be written into. +/// SENDER => { +/// let bytes_sent = sender_socket.send(&msg_to_send)?; +/// assert_eq!(bytes_sent, 9); +/// println!("sent {:?} -> {:?} bytes", msg_to_send, bytes_sent); +/// }, +/// // Our ECHOER is ready to be read from. +/// ECHOER => { +/// let num_recv = echoer_socket.recv(&mut buffer)?; +/// println!("echo {:?} -> {:?}", buffer, num_recv); +/// buffer = [0; 9]; +/// # return Ok(()); +/// } +/// _ => unreachable!() +/// } +/// } +/// } +/// # +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +pub struct UdpSocket { + sys: sys::UdpSocket, + selector_id: SelectorId, +} + +impl UdpSocket { + /// Creates a UDP socket from the given address. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// // We must bind it to an open address. + /// let socket = match UdpSocket::bind(&"127.0.0.1:0".parse()?) { + /// Ok(new_socket) => new_socket, + /// Err(fail) => { + /// // We panic! here, but you could try to bind it again on another address. + /// panic!("Failed to bind socket. {:?}", fail); + /// } + /// }; + /// + /// // Our socket was created, but we should not use it before checking it's readiness. + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn bind(addr: &SocketAddr) -> io::Result { + let socket = net::UdpSocket::bind(addr)?; + UdpSocket::from_socket(socket) + } + + /// Creates a new mio-wrapped socket from an underlying and bound std + /// socket. + /// + /// This function requires that `socket` has previously been bound to an + /// address to work correctly, and returns an I/O object which can be used + /// with mio to send/receive UDP messages. + /// + /// This can be used in conjunction with net2's `UdpBuilder` interface to + /// configure a socket before it's handed off to mio, such as setting + /// options like `reuse_address` or binding to multiple addresses. + pub fn from_socket(socket: net::UdpSocket) -> io::Result { + Ok(UdpSocket { + sys: sys::UdpSocket::new(socket)?, + selector_id: SelectorId::new(), + }) + } + + /// Returns the socket address that this socket was created from. + /// + /// # Examples + /// + // This assertion is almost, but not quite, universal. It fails on + // shared-IP FreeBSD jails. It's hard for mio to know whether we're jailed, + // so simply disable the test on FreeBSD. + #[cfg_attr(not(target_os = "freebsd"), doc = " ```")] + #[cfg_attr(target_os = "freebsd", doc = " ```no_run")] + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let addr = "127.0.0.1:0".parse()?; + /// let socket = UdpSocket::bind(&addr)?; + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn local_addr(&self) -> io::Result { + self.sys.local_addr() + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `UdpSocket` is a reference to the same socket that this + /// object references. Both handles will read and write the same port, and + /// options set on one socket will be propagated to the other. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// // We must bind it to an open address. + /// let socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// let cloned_socket = socket.try_clone()?; + /// + /// assert_eq!(socket.local_addr()?, cloned_socket.local_addr()?); + /// + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone() + .map(|s| { + UdpSocket { + sys: s, + selector_id: self.selector_id.clone(), + } + }) + } + + /// Sends data on the socket to the given address. On success, returns the + /// number of bytes written. + /// + /// Address type can be any implementor of `ToSocketAddrs` trait. See its + /// documentation for concrete examples. + /// + /// # Examples + /// + /// ```no_run + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// + /// // We must check if the socket is writable before calling send_to, + /// // or we could run into a WouldBlock error. + /// + /// let bytes_sent = socket.send_to(&[9; 9], &"127.0.0.1:11100".parse()?)?; + /// assert_eq!(bytes_sent, 9); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn send_to(&self, buf: &[u8], target: &SocketAddr) -> io::Result { + self.sys.send_to(buf, target) + } + + /// Receives data from the socket. On success, returns the number of bytes + /// read and the address from whence the data came. + /// + /// # Examples + /// + /// ```no_run + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// + /// // We must check if the socket is readable before calling recv_from, + /// // or we could run into a WouldBlock error. + /// + /// let mut buf = [0; 9]; + /// let (num_recv, from_addr) = socket.recv_from(&mut buf)?; + /// println!("Received {:?} -> {:?} bytes from {:?}", buf, num_recv, from_addr); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + self.sys.recv_from(buf) + } + + /// Sends data on the socket to the address previously bound via connect(). On success, + /// returns the number of bytes written. + pub fn send(&self, buf: &[u8]) -> io::Result { + self.sys.send(buf) + } + + /// Receives data from the socket previously bound with connect(). On success, returns + /// the number of bytes read. + pub fn recv(&self, buf: &mut [u8]) -> io::Result { + self.sys.recv(buf) + } + + /// Connects the UDP socket setting the default destination for `send()` + /// and limiting packets that are read via `recv` from the address specified + /// in `addr`. + pub fn connect(&self, addr: SocketAddr) -> io::Result<()> { + self.sys.connect(addr) + } + + /// Sets the value of the `SO_BROADCAST` option for this socket. + /// + /// When enabled, this socket is allowed to send packets to a broadcast + /// address. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let broadcast_socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// if broadcast_socket.broadcast()? == false { + /// broadcast_socket.set_broadcast(true)?; + /// } + /// + /// assert_eq!(broadcast_socket.broadcast()?, true); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { + self.sys.set_broadcast(on) + } + + /// Gets the value of the `SO_BROADCAST` option for this socket. + /// + /// For more information about this option, see + /// [`set_broadcast`][link]. + /// + /// [link]: #method.set_broadcast + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let broadcast_socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// assert_eq!(broadcast_socket.broadcast()?, false); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn broadcast(&self) -> io::Result { + self.sys.broadcast() + } + + /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// If enabled, multicast packets will be looped back to the local socket. + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> { + self.sys.set_multicast_loop_v4(on) + } + + /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v4`][link]. + /// + /// [link]: #method.set_multicast_loop_v4 + pub fn multicast_loop_v4(&self) -> io::Result { + self.sys.multicast_loop_v4() + } + + /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// Indicates the time-to-live value of outgoing multicast packets for + /// this socket. The default value is 1 which means that multicast packets + /// don't leave the local network unless explicitly requested. + /// + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> { + self.sys.set_multicast_ttl_v4(ttl) + } + + /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_ttl_v4`][link]. + /// + /// [link]: #method.set_multicast_ttl_v4 + pub fn multicast_ttl_v4(&self) -> io::Result { + self.sys.multicast_ttl_v4() + } + + /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// Controls whether this socket sees the multicast packets it sends itself. + /// Note that this may not have any affect on IPv4 sockets. + pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> { + self.sys.set_multicast_loop_v6(on) + } + + /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v6`][link]. + /// + /// [link]: #method.set_multicast_loop_v6 + pub fn multicast_loop_v6(&self) -> io::Result { + self.sys.multicast_loop_v6() + } + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// if socket.ttl()? < 255 { + /// socket.set_ttl(255)?; + /// } + /// + /// assert_eq!(socket.ttl()?, 255); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.sys.set_ttl(ttl) + } + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #method.set_ttl + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # + /// # fn try_main() -> Result<(), Box> { + /// use mio::net::UdpSocket; + /// + /// let socket = UdpSocket::bind(&"127.0.0.1:0".parse()?)?; + /// socket.set_ttl(255)?; + /// + /// assert_eq!(socket.ttl()?, 255); + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn ttl(&self) -> io::Result { + self.sys.ttl() + } + + /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// address of the local interface with which the system should join the + /// multicast group. If it's equal to `INADDR_ANY` then an appropriate + /// interface is chosen by the system. + pub fn join_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.sys.join_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// index of the interface to join/leave (or 0 to indicate any interface). + pub fn join_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.sys.join_multicast_v6(multiaddr, interface) + } + + /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v4`][link]. + /// + /// [link]: #method.join_multicast_v4 + pub fn leave_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.sys.leave_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v6`][link]. + /// + /// [link]: #method.join_multicast_v6 + pub fn leave_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.sys.leave_multicast_v6(multiaddr, interface) + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// If this is set to `true` then the socket is restricted to sending and + /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications + /// can bind the same port at the same time. + /// + /// If this is set to `false` then the socket can be used to send and + /// receive packets from an IPv4-mapped IPv6 address. + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.sys.set_only_v6(only_v6) + } + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see [`set_only_v6`][link]. + /// + /// [link]: #method.set_only_v6 + pub fn only_v6(&self) -> io::Result { + self.sys.only_v6() + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + self.sys.take_error() + } + + /// Receives a single datagram message socket previously bound with connect. + /// + /// This operation will attempt to read bytes from this socket and place + /// them into the list of buffers provided. Note that each buffer is an + /// `IoVec` which can be created from a byte slice. + /// + /// The buffers provided will be filled sequentially. A buffer will be + /// entirely filled up before the next is written to. + /// + /// The number of bytes read is returned, if successful, or an error is + /// returned otherwise. If no bytes are available to be read yet then + /// a [`WouldBlock`][link] error is returned. This operation does not block. + /// + /// On Unix this corresponds to the `readv` syscall. + /// + /// [link]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html#variant.WouldBlock + #[cfg(all(unix, not(target_os = "fuchsia")))] + pub fn recv_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result { + self.sys.readv(bufs) + } + + /// Sends data on the socket to the address previously bound via connect. + /// + /// This operation will attempt to send a list of byte buffers to this + /// socket in a single datagram. Note that each buffer is an `IoVec` + /// which can be created from a byte slice. + /// + /// The buffers provided will be written sequentially. A buffer will be + /// entirely written before the next is written. + /// + /// The number of bytes written is returned, if successful, or an error is + /// returned otherwise. If the socket is not currently writable then a + /// [`WouldBlock`][link] error is returned. This operation does not block. + /// + /// On Unix this corresponds to the `writev` syscall. + /// + /// [link]: https://doc.rust-lang.org/nightly/std/io/enum.ErrorKind.html#variant.WouldBlock + #[cfg(all(unix, not(target_os = "fuchsia")))] + pub fn send_bufs(&self, bufs: &[&IoVec]) -> io::Result { + self.sys.writev(bufs) + } +} + +impl Evented for UdpSocket { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.selector_id.associate_selector(poll)?; + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +impl fmt::Debug for UdpSocket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.sys, f) + } +} + +/* + * + * ===== UNIX ext ===== + * + */ + +#[cfg(all(unix, not(target_os = "fuchsia")))] +use std::os::unix::io::{IntoRawFd, AsRawFd, FromRawFd, RawFd}; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl IntoRawFd for UdpSocket { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl AsRawFd for UdpSocket { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl FromRawFd for UdpSocket { + unsafe fn from_raw_fd(fd: RawFd) -> UdpSocket { + UdpSocket { + sys: FromRawFd::from_raw_fd(fd), + selector_id: SelectorId::new(), + } + } +} + diff --git a/third_party/cargo/vendor/mio-0.6.21/src/poll.rs b/third_party/cargo/vendor/mio-0.6.21/src/poll.rs new file mode 100644 index 0000000..7985d45 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/poll.rs @@ -0,0 +1,2783 @@ +use {sys, Token}; +use event_imp::{self as event, Ready, Event, Evented, PollOpt}; +use std::{fmt, io, ptr, usize}; +use std::cell::UnsafeCell; +use std::{mem, ops, isize}; +#[cfg(all(unix, not(target_os = "fuchsia")))] +use std::os::unix::io::AsRawFd; +#[cfg(all(unix, not(target_os = "fuchsia")))] +use std::os::unix::io::RawFd; +use std::process; +use std::sync::{Arc, Mutex, Condvar}; +use std::sync::atomic::{AtomicUsize, AtomicPtr, AtomicBool}; +use std::sync::atomic::Ordering::{self, Acquire, Release, AcqRel, Relaxed, SeqCst}; +use std::time::{Duration, Instant}; + +// Poll is backed by two readiness queues. The first is a system readiness queue +// represented by `sys::Selector`. The system readiness queue handles events +// provided by the system, such as TCP and UDP. The second readiness queue is +// implemented in user space by `ReadinessQueue`. It provides a way to implement +// purely user space `Evented` types. +// +// `ReadinessQueue` is backed by a MPSC queue that supports reuse of linked +// list nodes. This significantly reduces the number of required allocations. +// Each `Registration` / `SetReadiness` pair allocates a single readiness node +// that is used for the lifetime of the registration. +// +// The readiness node also includes a single atomic variable, `state` that +// tracks most of the state associated with the registration. This includes the +// current readiness, interest, poll options, and internal state. When the node +// state is mutated, it is queued in the MPSC channel. A call to +// `ReadinessQueue::poll` will dequeue and process nodes. The node state can +// still be mutated while it is queued in the channel for processing. +// Intermediate state values do not matter as long as the final state is +// included in the call to `poll`. This is the eventually consistent nature of +// the readiness queue. +// +// The readiness node is ref counted using the `ref_count` field. On creation, +// the ref_count is initialized to 3: one `Registration` handle, one +// `SetReadiness` handle, and one for the readiness queue. Since the readiness queue +// doesn't *always* hold a handle to the node, we don't use the Arc type for +// managing ref counts (this is to avoid constantly incrementing and +// decrementing the ref count when pushing & popping from the queue). When the +// `Registration` handle is dropped, the `dropped` flag is set on the node, then +// the node is pushed into the registration queue. When Poll::poll pops the +// node, it sees the drop flag is set, and decrements it's ref count. +// +// The MPSC queue is a modified version of the intrusive MPSC node based queue +// described by 1024cores [1]. +// +// The first modification is that two markers are used instead of a single +// `stub`. The second marker is a `sleep_marker` which is used to signal to +// producers that the consumer is going to sleep. This sleep_marker is only used +// when the queue is empty, implying that the only node in the queue is +// `end_marker`. +// +// The second modification is an `until` argument passed to the dequeue +// function. When `poll` encounters a level-triggered node, the node will be +// immediately pushed back into the queue. In order to avoid an infinite loop, +// `poll` before pushing the node, the pointer is saved off and then passed +// again as the `until` argument. If the next node to pop is `until`, then +// `Dequeue::Empty` is returned. +// +// [1] http://www.1024cores.net/home/lock-free-algorithms/queues/intrusive-mpsc-node-based-queue + + +/// Polls for readiness events on all registered values. +/// +/// `Poll` allows a program to monitor a large number of `Evented` types, +/// waiting until one or more become "ready" for some class of operations; e.g. +/// reading and writing. An `Evented` type is considered ready if it is possible +/// to immediately perform a corresponding operation; e.g. [`read`] or +/// [`write`]. +/// +/// To use `Poll`, an `Evented` type must first be registered with the `Poll` +/// instance using the [`register`] method, supplying readiness interest. The +/// readiness interest tells `Poll` which specific operations on the handle to +/// monitor for readiness. A `Token` is also passed to the [`register`] +/// function. When `Poll` returns a readiness event, it will include this token. +/// This associates the event with the `Evented` handle that generated the +/// event. +/// +/// [`read`]: tcp/struct.TcpStream.html#method.read +/// [`write`]: tcp/struct.TcpStream.html#method.write +/// [`register`]: #method.register +/// +/// # Examples +/// +/// A basic example -- establishing a `TcpStream` connection. +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Poll, Ready, PollOpt, Token}; +/// use mio::net::TcpStream; +/// +/// use std::net::{TcpListener, SocketAddr}; +/// +/// // Bind a server socket to connect to. +/// let addr: SocketAddr = "127.0.0.1:0".parse()?; +/// let server = TcpListener::bind(&addr)?; +/// +/// // Construct a new `Poll` handle as well as the `Events` we'll store into +/// let poll = Poll::new()?; +/// let mut events = Events::with_capacity(1024); +/// +/// // Connect the stream +/// let stream = TcpStream::connect(&server.local_addr()?)?; +/// +/// // Register the stream with `Poll` +/// poll.register(&stream, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge())?; +/// +/// // Wait for the socket to become ready. This has to happens in a loop to +/// // handle spurious wakeups. +/// loop { +/// poll.poll(&mut events, None)?; +/// +/// for event in &events { +/// if event.token() == Token(0) && event.readiness().is_writable() { +/// // The socket connected (probably, it could still be a spurious +/// // wakeup) +/// return Ok(()); +/// } +/// } +/// } +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// # Edge-triggered and level-triggered +/// +/// An [`Evented`] registration may request edge-triggered events or +/// level-triggered events. This is done by setting `register`'s +/// [`PollOpt`] argument to either [`edge`] or [`level`]. +/// +/// The difference between the two can be described as follows. Supposed that +/// this scenario happens: +/// +/// 1. A [`TcpStream`] is registered with `Poll`. +/// 2. The socket receives 2kb of data. +/// 3. A call to [`Poll::poll`] returns the token associated with the socket +/// indicating readable readiness. +/// 4. 1kb is read from the socket. +/// 5. Another call to [`Poll::poll`] is made. +/// +/// If when the socket was registered with `Poll`, edge triggered events were +/// requested, then the call to [`Poll::poll`] done in step **5** will +/// (probably) hang despite there being another 1kb still present in the socket +/// read buffer. The reason for this is that edge-triggered mode delivers events +/// only when changes occur on the monitored [`Evented`]. So, in step *5* the +/// caller might end up waiting for some data that is already present inside the +/// socket buffer. +/// +/// With edge-triggered events, operations **must** be performed on the +/// `Evented` type until [`WouldBlock`] is returned. In other words, after +/// receiving an event indicating readiness for a certain operation, one should +/// assume that [`Poll::poll`] may never return another event for the same token +/// and readiness until the operation returns [`WouldBlock`]. +/// +/// By contrast, when level-triggered notifications was requested, each call to +/// [`Poll::poll`] will return an event for the socket as long as data remains +/// in the socket buffer. Generally, level-triggered events should be avoided if +/// high performance is a concern. +/// +/// Since even with edge-triggered events, multiple events can be generated upon +/// receipt of multiple chunks of data, the caller has the option to set the +/// [`oneshot`] flag. This tells `Poll` to disable the associated [`Evented`] +/// after the event is returned from [`Poll::poll`]. The subsequent calls to +/// [`Poll::poll`] will no longer include events for [`Evented`] handles that +/// are disabled even if the readiness state changes. The handle can be +/// re-enabled by calling [`reregister`]. When handles are disabled, internal +/// resources used to monitor the handle are maintained until the handle is +/// dropped or deregistered. This makes re-registering the handle a fast +/// operation. +/// +/// For example, in the following scenario: +/// +/// 1. A [`TcpStream`] is registered with `Poll`. +/// 2. The socket receives 2kb of data. +/// 3. A call to [`Poll::poll`] returns the token associated with the socket +/// indicating readable readiness. +/// 4. 2kb is read from the socket. +/// 5. Another call to read is issued and [`WouldBlock`] is returned +/// 6. The socket receives another 2kb of data. +/// 7. Another call to [`Poll::poll`] is made. +/// +/// Assuming the socket was registered with `Poll` with the [`edge`] and +/// [`oneshot`] options, then the call to [`Poll::poll`] in step 7 would block. This +/// is because, [`oneshot`] tells `Poll` to disable events for the socket after +/// returning an event. +/// +/// In order to receive the event for the data received in step 6, the socket +/// would need to be reregistered using [`reregister`]. +/// +/// [`PollOpt`]: struct.PollOpt.html +/// [`edge`]: struct.PollOpt.html#method.edge +/// [`level`]: struct.PollOpt.html#method.level +/// [`Poll::poll`]: struct.Poll.html#method.poll +/// [`WouldBlock`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.WouldBlock +/// [`Evented`]: event/trait.Evented.html +/// [`TcpStream`]: tcp/struct.TcpStream.html +/// [`reregister`]: #method.reregister +/// [`oneshot`]: struct.PollOpt.html#method.oneshot +/// +/// # Portability +/// +/// Using `Poll` provides a portable interface across supported platforms as +/// long as the caller takes the following into consideration: +/// +/// ### Spurious events +/// +/// [`Poll::poll`] may return readiness events even if the associated +/// [`Evented`] handle is not actually ready. Given the same code, this may +/// happen more on some platforms than others. It is important to never assume +/// that, just because a readiness notification was received, that the +/// associated operation will succeed as well. +/// +/// If operation fails with [`WouldBlock`], then the caller should not treat +/// this as an error, but instead should wait until another readiness event is +/// received. +/// +/// ### Draining readiness +/// +/// When using edge-triggered mode, once a readiness event is received, the +/// corresponding operation must be performed repeatedly until it returns +/// [`WouldBlock`]. Unless this is done, there is no guarantee that another +/// readiness event will be delivered, even if further data is received for the +/// [`Evented`] handle. +/// +/// For example, in the first scenario described above, after step 5, even if +/// the socket receives more data there is no guarantee that another readiness +/// event will be delivered. +/// +/// ### Readiness operations +/// +/// The only readiness operations that are guaranteed to be present on all +/// supported platforms are [`readable`] and [`writable`]. All other readiness +/// operations may have false negatives and as such should be considered +/// **hints**. This means that if a socket is registered with [`readable`], +/// [`error`], and [`hup`] interest, and either an error or hup is received, a +/// readiness event will be generated for the socket, but it **may** only +/// include `readable` readiness. Also note that, given the potential for +/// spurious events, receiving a readiness event with `hup` or `error` doesn't +/// actually mean that a `read` on the socket will return a result matching the +/// readiness event. +/// +/// In other words, portable programs that explicitly check for [`hup`] or +/// [`error`] readiness should be doing so as an **optimization** and always be +/// able to handle an error or HUP situation when performing the actual read +/// operation. +/// +/// [`readable`]: struct.Ready.html#method.readable +/// [`writable`]: struct.Ready.html#method.writable +/// [`error`]: unix/struct.UnixReady.html#method.error +/// [`hup`]: unix/struct.UnixReady.html#method.hup +/// +/// ### Registering handles +/// +/// Unless otherwise noted, it should be assumed that types implementing +/// [`Evented`] will never become ready unless they are registered with `Poll`. +/// +/// For example: +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Poll, Ready, PollOpt, Token}; +/// use mio::net::TcpStream; +/// use std::time::Duration; +/// use std::thread; +/// +/// let sock = TcpStream::connect(&"216.58.193.100:80".parse()?)?; +/// +/// thread::sleep(Duration::from_secs(1)); +/// +/// let poll = Poll::new()?; +/// +/// // The connect is not guaranteed to have started until it is registered at +/// // this point +/// poll.register(&sock, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge())?; +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// # Implementation notes +/// +/// `Poll` is backed by the selector provided by the operating system. +/// +/// | OS | Selector | +/// |------------|-----------| +/// | Linux | [epoll] | +/// | OS X, iOS | [kqueue] | +/// | Windows | [IOCP] | +/// | FreeBSD | [kqueue] | +/// | Android | [epoll] | +/// +/// On all supported platforms, socket operations are handled by using the +/// system selector. Platform specific extensions (e.g. [`EventedFd`]) allow +/// accessing other features provided by individual system selectors. For +/// example, Linux's [`signalfd`] feature can be used by registering the FD with +/// `Poll` via [`EventedFd`]. +/// +/// On all platforms except windows, a call to [`Poll::poll`] is mostly just a +/// direct call to the system selector. However, [IOCP] uses a completion model +/// instead of a readiness model. In this case, `Poll` must adapt the completion +/// model Mio's API. While non-trivial, the bridge layer is still quite +/// efficient. The most expensive part being calls to `read` and `write` require +/// data to be copied into an intermediate buffer before it is passed to the +/// kernel. +/// +/// Notifications generated by [`SetReadiness`] are handled by an internal +/// readiness queue. A single call to [`Poll::poll`] will collect events from +/// both from the system selector and the internal readiness queue. +/// +/// [epoll]: http://man7.org/linux/man-pages/man7/epoll.7.html +/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 +/// [IOCP]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365198(v=vs.85).aspx +/// [`signalfd`]: http://man7.org/linux/man-pages/man2/signalfd.2.html +/// [`EventedFd`]: unix/struct.EventedFd.html +/// [`SetReadiness`]: struct.SetReadiness.html +/// [`Poll::poll`]: struct.Poll.html#method.poll +pub struct Poll { + // Platform specific IO selector + selector: sys::Selector, + + // Custom readiness queue + readiness_queue: ReadinessQueue, + + // Use an atomic to first check if a full lock will be required. This is a + // fast-path check for single threaded cases avoiding the extra syscall + lock_state: AtomicUsize, + + // Sequences concurrent calls to `Poll::poll` + lock: Mutex<()>, + + // Wakeup the next waiter + condvar: Condvar, +} + +/// Handle to a user space `Poll` registration. +/// +/// `Registration` allows implementing [`Evented`] for types that cannot work +/// with the [system selector]. A `Registration` is always paired with a +/// `SetReadiness`, which allows updating the registration's readiness state. +/// When [`set_readiness`] is called and the `Registration` is associated with a +/// [`Poll`] instance, a readiness event will be created and eventually returned +/// by [`poll`]. +/// +/// A `Registration` / `SetReadiness` pair is created by calling +/// [`Registration::new2`]. At this point, the registration is not being +/// monitored by a [`Poll`] instance, so calls to `set_readiness` will not +/// result in any readiness notifications. +/// +/// `Registration` implements [`Evented`], so it can be used with [`Poll`] using +/// the same [`register`], [`reregister`], and [`deregister`] functions used +/// with TCP, UDP, etc... types. Once registered with [`Poll`], readiness state +/// changes result in readiness events being dispatched to the [`Poll`] instance +/// with which `Registration` is registered. +/// +/// **Note**, before using `Registration` be sure to read the +/// [`set_readiness`] documentation and the [portability] notes. The +/// guarantees offered by `Registration` may be weaker than expected. +/// +/// For high level documentation, see [`Poll`]. +/// +/// # Examples +/// +/// ``` +/// use mio::{Ready, Registration, Poll, PollOpt, Token}; +/// use mio::event::Evented; +/// +/// use std::io; +/// use std::time::Instant; +/// use std::thread; +/// +/// pub struct Deadline { +/// when: Instant, +/// registration: Registration, +/// } +/// +/// impl Deadline { +/// pub fn new(when: Instant) -> Deadline { +/// let (registration, set_readiness) = Registration::new2(); +/// +/// thread::spawn(move || { +/// let now = Instant::now(); +/// +/// if now < when { +/// thread::sleep(when - now); +/// } +/// +/// set_readiness.set_readiness(Ready::readable()); +/// }); +/// +/// Deadline { +/// when: when, +/// registration: registration, +/// } +/// } +/// +/// pub fn is_elapsed(&self) -> bool { +/// Instant::now() >= self.when +/// } +/// } +/// +/// impl Evented for Deadline { +/// fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// self.registration.register(poll, token, interest, opts) +/// } +/// +/// fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// self.registration.reregister(poll, token, interest, opts) +/// } +/// +/// fn deregister(&self, poll: &Poll) -> io::Result<()> { +/// poll.deregister(&self.registration) +/// } +/// } +/// ``` +/// +/// [system selector]: struct.Poll.html#implementation-notes +/// [`Poll`]: struct.Poll.html +/// [`Registration::new2`]: struct.Registration.html#method.new2 +/// [`Evented`]: event/trait.Evented.html +/// [`set_readiness`]: struct.SetReadiness.html#method.set_readiness +/// [`register`]: struct.Poll.html#method.register +/// [`reregister`]: struct.Poll.html#method.reregister +/// [`deregister`]: struct.Poll.html#method.deregister +/// [portability]: struct.Poll.html#portability +pub struct Registration { + inner: RegistrationInner, +} + +unsafe impl Send for Registration {} +unsafe impl Sync for Registration {} + +/// Updates the readiness state of the associated `Registration`. +/// +/// See [`Registration`] for more documentation on using `SetReadiness` and +/// [`Poll`] for high level polling documentation. +/// +/// [`Poll`]: struct.Poll.html +/// [`Registration`]: struct.Registration.html +#[derive(Clone)] +pub struct SetReadiness { + inner: RegistrationInner, +} + +unsafe impl Send for SetReadiness {} +unsafe impl Sync for SetReadiness {} + +/// Used to associate an IO type with a Selector +#[derive(Debug)] +pub struct SelectorId { + id: AtomicUsize, +} + +struct RegistrationInner { + // Unsafe pointer to the registration's node. The node is ref counted. This + // cannot "simply" be tracked by an Arc because `Poll::poll` has an implicit + // handle though it isn't stored anywhere. In other words, `Poll::poll` + // needs to decrement the ref count before the node is freed. + node: *mut ReadinessNode, +} + +#[derive(Clone)] +struct ReadinessQueue { + inner: Arc, +} + +unsafe impl Send for ReadinessQueue {} +unsafe impl Sync for ReadinessQueue {} + +struct ReadinessQueueInner { + // Used to wake up `Poll` when readiness is set in another thread. + awakener: sys::Awakener, + + // Head of the MPSC queue used to signal readiness to `Poll::poll`. + head_readiness: AtomicPtr, + + // Tail of the readiness queue. + // + // Only accessed by Poll::poll. Coordination will be handled by the poll fn + tail_readiness: UnsafeCell<*mut ReadinessNode>, + + // Fake readiness node used to punctuate the end of the readiness queue. + // Before attempting to read from the queue, this node is inserted in order + // to partition the queue between nodes that are "owned" by the dequeue end + // and nodes that will be pushed on by producers. + end_marker: Box, + + // Similar to `end_marker`, but this node signals to producers that `Poll` + // has gone to sleep and must be woken up. + sleep_marker: Box, + + // Similar to `end_marker`, but the node signals that the queue is closed. + // This happens when `ReadyQueue` is dropped and signals to producers that + // the nodes should no longer be pushed into the queue. + closed_marker: Box, +} + +/// Node shared by a `Registration` / `SetReadiness` pair as well as the node +/// queued into the MPSC channel. +struct ReadinessNode { + // Node state, see struct docs for `ReadinessState` + // + // This variable is the primary point of coordination between all the + // various threads concurrently accessing the node. + state: AtomicState, + + // The registration token cannot fit into the `state` variable, so it is + // broken out here. In order to atomically update both the state and token + // we have to jump through a few hoops. + // + // First, `state` includes `token_read_pos` and `token_write_pos`. These can + // either be 0, 1, or 2 which represent a token slot. `token_write_pos` is + // the token slot that contains the most up to date registration token. + // `token_read_pos` is the token slot that `poll` is currently reading from. + // + // When a call to `update` includes a different token than the one currently + // associated with the registration (token_write_pos), first an unused token + // slot is found. The unused slot is the one not represented by + // `token_read_pos` OR `token_write_pos`. The new token is written to this + // slot, then `state` is updated with the new `token_write_pos` value. This + // requires that there is only a *single* concurrent call to `update`. + // + // When `poll` reads a node state, it checks that `token_read_pos` matches + // `token_write_pos`. If they do not match, then it atomically updates + // `state` such that `token_read_pos` is set to `token_write_pos`. It will + // then read the token at the newly updated `token_read_pos`. + token_0: UnsafeCell, + token_1: UnsafeCell, + token_2: UnsafeCell, + + // Used when the node is queued in the readiness linked list. Accessing + // this field requires winning the "queue" lock + next_readiness: AtomicPtr, + + // Ensures that there is only one concurrent call to `update`. + // + // Each call to `update` will attempt to swap `update_lock` from `false` to + // `true`. If the CAS succeeds, the thread has obtained the update lock. If + // the CAS fails, then the `update` call returns immediately and the update + // is discarded. + update_lock: AtomicBool, + + // Pointer to Arc + readiness_queue: AtomicPtr<()>, + + // Tracks the number of `ReadyRef` pointers + ref_count: AtomicUsize, +} + +/// Stores the ReadinessNode state in an AtomicUsize. This wrapper around the +/// atomic variable handles encoding / decoding `ReadinessState` values. +struct AtomicState { + inner: AtomicUsize, +} + +const MASK_2: usize = 4 - 1; +const MASK_4: usize = 16 - 1; +const QUEUED_MASK: usize = 1 << QUEUED_SHIFT; +const DROPPED_MASK: usize = 1 << DROPPED_SHIFT; + +const READINESS_SHIFT: usize = 0; +const INTEREST_SHIFT: usize = 4; +const POLL_OPT_SHIFT: usize = 8; +const TOKEN_RD_SHIFT: usize = 12; +const TOKEN_WR_SHIFT: usize = 14; +const QUEUED_SHIFT: usize = 16; +const DROPPED_SHIFT: usize = 17; + +/// Tracks all state for a single `ReadinessNode`. The state is packed into a +/// `usize` variable from low to high bit as follows: +/// +/// 4 bits: Registration current readiness +/// 4 bits: Registration interest +/// 4 bits: Poll options +/// 2 bits: Token position currently being read from by `poll` +/// 2 bits: Token position last written to by `update` +/// 1 bit: Queued flag, set when node is being pushed into MPSC queue. +/// 1 bit: Dropped flag, set when all `Registration` handles have been dropped. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +struct ReadinessState(usize); + +/// Returned by `dequeue_node`. Represents the different states as described by +/// the queue documentation on 1024cores.net. +enum Dequeue { + Data(*mut ReadinessNode), + Empty, + Inconsistent, +} + +const AWAKEN: Token = Token(usize::MAX); +const MAX_REFCOUNT: usize = (isize::MAX) as usize; + +/* + * + * ===== Poll ===== + * + */ + +impl Poll { + /// Return a new `Poll` handle. + /// + /// This function will make a syscall to the operating system to create the + /// system selector. If this syscall fails, `Poll::new` will return with the + /// error. + /// + /// See [struct] level docs for more details. + /// + /// [struct]: struct.Poll.html + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Poll, Events}; + /// use std::time::Duration; + /// + /// let poll = match Poll::new() { + /// Ok(poll) => poll, + /// Err(e) => panic!("failed to create Poll instance; err={:?}", e), + /// }; + /// + /// // Create a structure to receive polled events + /// let mut events = Events::with_capacity(1024); + /// + /// // Wait for events, but none will be received because no `Evented` + /// // handles have been registered with this `Poll` instance. + /// let n = poll.poll(&mut events, Some(Duration::from_millis(500)))?; + /// assert_eq!(n, 0); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn new() -> io::Result { + is_send::(); + is_sync::(); + + let poll = Poll { + selector: sys::Selector::new()?, + readiness_queue: ReadinessQueue::new()?, + lock_state: AtomicUsize::new(0), + lock: Mutex::new(()), + condvar: Condvar::new(), + }; + + // Register the notification wakeup FD with the IO poller + poll.readiness_queue.inner.awakener.register(&poll, AWAKEN, Ready::readable(), PollOpt::edge())?; + + Ok(poll) + } + + /// Register an `Evented` handle with the `Poll` instance. + /// + /// Once registered, the `Poll` instance will monitor the `Evented` handle + /// for readiness state changes. When it notices a state change, it will + /// return a readiness event for the handle the next time [`poll`] is + /// called. + /// + /// See the [`struct`] docs for a high level overview. + /// + /// # Arguments + /// + /// `handle: &E: Evented`: This is the handle that the `Poll` instance + /// should monitor for readiness state changes. + /// + /// `token: Token`: The caller picks a token to associate with the socket. + /// When [`poll`] returns an event for the handle, this token is included. + /// This allows the caller to map the event to its handle. The token + /// associated with the `Evented` handle can be changed at any time by + /// calling [`reregister`]. + /// + /// `token` cannot be `Token(usize::MAX)` as it is reserved for internal + /// usage. + /// + /// See documentation on [`Token`] for an example showing how to pick + /// [`Token`] values. + /// + /// `interest: Ready`: Specifies which operations `Poll` should monitor for + /// readiness. `Poll` will only return readiness events for operations + /// specified by this argument. + /// + /// If a socket is registered with readable interest and the socket becomes + /// writable, no event will be returned from [`poll`]. + /// + /// The readiness interest for an `Evented` handle can be changed at any + /// time by calling [`reregister`]. + /// + /// `opts: PollOpt`: Specifies the registration options. The most common + /// options being [`level`] for level-triggered events, [`edge`] for + /// edge-triggered events, and [`oneshot`]. + /// + /// The registration options for an `Evented` handle can be changed at any + /// time by calling [`reregister`]. + /// + /// # Notes + /// + /// Unless otherwise specified, the caller should assume that once an + /// `Evented` handle is registered with a `Poll` instance, it is bound to + /// that `Poll` instance for the lifetime of the `Evented` handle. This + /// remains true even if the `Evented` handle is deregistered from the poll + /// instance using [`deregister`]. + /// + /// This function is **thread safe**. It can be called concurrently from + /// multiple threads. + /// + /// [`struct`]: # + /// [`reregister`]: #method.reregister + /// [`deregister`]: #method.deregister + /// [`poll`]: #method.poll + /// [`level`]: struct.PollOpt.html#method.level + /// [`edge`]: struct.PollOpt.html#method.edge + /// [`oneshot`]: struct.PollOpt.html#method.oneshot + /// [`Token`]: struct.Token.html + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Poll, Ready, PollOpt, Token}; + /// use mio::net::TcpStream; + /// use std::time::{Duration, Instant}; + /// + /// let poll = Poll::new()?; + /// let socket = TcpStream::connect(&"216.58.193.100:80".parse()?)?; + /// + /// // Register the socket with `poll` + /// poll.register(&socket, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge())?; + /// + /// let mut events = Events::with_capacity(1024); + /// let start = Instant::now(); + /// let timeout = Duration::from_millis(500); + /// + /// loop { + /// let elapsed = start.elapsed(); + /// + /// if elapsed >= timeout { + /// // Connection timed out + /// return Ok(()); + /// } + /// + /// let remaining = timeout - elapsed; + /// poll.poll(&mut events, Some(remaining))?; + /// + /// for event in &events { + /// if event.token() == Token(0) { + /// // Something (probably) happened on the socket. + /// return Ok(()); + /// } + /// } + /// } + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn register(&self, handle: &E, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> + where E: Evented + { + validate_args(token)?; + + /* + * Undefined behavior: + * - Reusing a token with a different `Evented` without deregistering + * (or closing) the original `Evented`. + */ + trace!("registering with poller"); + + // Register interests for this socket + handle.register(self, token, interest, opts)?; + + Ok(()) + } + + /// Re-register an `Evented` handle with the `Poll` instance. + /// + /// Re-registering an `Evented` handle allows changing the details of the + /// registration. Specifically, it allows updating the associated `token`, + /// `interest`, and `opts` specified in previous `register` and `reregister` + /// calls. + /// + /// The `reregister` arguments fully override the previous values. In other + /// words, if a socket is registered with [`readable`] interest and the call + /// to `reregister` specifies [`writable`], then read interest is no longer + /// requested for the handle. + /// + /// The `Evented` handle must have previously been registered with this + /// instance of `Poll` otherwise the call to `reregister` will return with + /// an error. + /// + /// `token` cannot be `Token(usize::MAX)` as it is reserved for internal + /// usage. + /// + /// See the [`register`] documentation for details about the function + /// arguments and see the [`struct`] docs for a high level overview of + /// polling. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Poll, Ready, PollOpt, Token}; + /// use mio::net::TcpStream; + /// + /// let poll = Poll::new()?; + /// let socket = TcpStream::connect(&"216.58.193.100:80".parse()?)?; + /// + /// // Register the socket with `poll`, requesting readable + /// poll.register(&socket, Token(0), Ready::readable(), PollOpt::edge())?; + /// + /// // Reregister the socket specifying a different token and write interest + /// // instead. `PollOpt::edge()` must be specified even though that value + /// // is not being changed. + /// poll.reregister(&socket, Token(2), Ready::writable(), PollOpt::edge())?; + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// + /// [`struct`]: # + /// [`register`]: #method.register + /// [`readable`]: struct.Ready.html#method.readable + /// [`writable`]: struct.Ready.html#method.writable + pub fn reregister(&self, handle: &E, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> + where E: Evented + { + validate_args(token)?; + + trace!("registering with poller"); + + // Register interests for this socket + handle.reregister(self, token, interest, opts)?; + + Ok(()) + } + + /// Deregister an `Evented` handle with the `Poll` instance. + /// + /// When an `Evented` handle is deregistered, the `Poll` instance will + /// no longer monitor it for readiness state changes. Unlike disabling + /// handles with oneshot, deregistering clears up any internal resources + /// needed to track the handle. + /// + /// A handle can be passed back to `register` after it has been + /// deregistered; however, it must be passed back to the **same** `Poll` + /// instance. + /// + /// `Evented` handles are automatically deregistered when they are dropped. + /// It is common to never need to explicitly call `deregister`. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Poll, Ready, PollOpt, Token}; + /// use mio::net::TcpStream; + /// use std::time::Duration; + /// + /// let poll = Poll::new()?; + /// let socket = TcpStream::connect(&"216.58.193.100:80".parse()?)?; + /// + /// // Register the socket with `poll` + /// poll.register(&socket, Token(0), Ready::readable(), PollOpt::edge())?; + /// + /// poll.deregister(&socket)?; + /// + /// let mut events = Events::with_capacity(1024); + /// + /// // Set a timeout because this poll should never receive any events. + /// let n = poll.poll(&mut events, Some(Duration::from_secs(1)))?; + /// assert_eq!(0, n); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn deregister(&self, handle: &E) -> io::Result<()> + where E: Evented + { + trace!("deregistering handle with poller"); + + // Deregister interests for this socket + handle.deregister(self)?; + + Ok(()) + } + + /// Wait for readiness events + /// + /// Blocks the current thread and waits for readiness events for any of the + /// `Evented` handles that have been registered with this `Poll` instance. + /// The function will block until either at least one readiness event has + /// been received or `timeout` has elapsed. A `timeout` of `None` means that + /// `poll` will block until a readiness event has been received. + /// + /// The supplied `events` will be cleared and newly received readiness events + /// will be pushed onto the end. At most `events.capacity()` events will be + /// returned. If there are further pending readiness events, they will be + /// returned on the next call to `poll`. + /// + /// A single call to `poll` may result in multiple readiness events being + /// returned for a single `Evented` handle. For example, if a TCP socket + /// becomes both readable and writable, it may be possible for a single + /// readiness event to be returned with both [`readable`] and [`writable`] + /// readiness **OR** two separate events may be returned, one with + /// [`readable`] set and one with [`writable`] set. + /// + /// Note that the `timeout` will be rounded up to the system clock + /// granularity (usually 1ms), and kernel scheduling delays mean that + /// the blocking interval may be overrun by a small amount. + /// + /// `poll` returns the number of readiness events that have been pushed into + /// `events` or `Err` when an error has been encountered with the system + /// selector. The value returned is deprecated and will be removed in 0.7.0. + /// Accessing the events by index is also deprecated. Events can be + /// inserted by other events triggering, thus making sequential access + /// problematic. Use the iterator API instead. See [`iter`]. + /// + /// See the [struct] level documentation for a higher level discussion of + /// polling. + /// + /// [`readable`]: struct.Ready.html#method.readable + /// [`writable`]: struct.Ready.html#method.writable + /// [struct]: # + /// [`iter`]: struct.Events.html#method.iter + /// + /// # Examples + /// + /// A basic example -- establishing a `TcpStream` connection. + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Poll, Ready, PollOpt, Token}; + /// use mio::net::TcpStream; + /// + /// use std::net::{TcpListener, SocketAddr}; + /// use std::thread; + /// + /// // Bind a server socket to connect to. + /// let addr: SocketAddr = "127.0.0.1:0".parse()?; + /// let server = TcpListener::bind(&addr)?; + /// let addr = server.local_addr()?.clone(); + /// + /// // Spawn a thread to accept the socket + /// thread::spawn(move || { + /// let _ = server.accept(); + /// }); + /// + /// // Construct a new `Poll` handle as well as the `Events` we'll store into + /// let poll = Poll::new()?; + /// let mut events = Events::with_capacity(1024); + /// + /// // Connect the stream + /// let stream = TcpStream::connect(&addr)?; + /// + /// // Register the stream with `Poll` + /// poll.register(&stream, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge())?; + /// + /// // Wait for the socket to become ready. This has to happens in a loop to + /// // handle spurious wakeups. + /// loop { + /// poll.poll(&mut events, None)?; + /// + /// for event in &events { + /// if event.token() == Token(0) && event.readiness().is_writable() { + /// // The socket connected (probably, it could still be a spurious + /// // wakeup) + /// return Ok(()); + /// } + /// } + /// } + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// + /// [struct]: # + pub fn poll(&self, events: &mut Events, timeout: Option) -> io::Result { + self.poll1(events, timeout, false) + } + + /// Like `poll`, but may be interrupted by a signal + /// + /// If `poll` is inturrupted while blocking, it will transparently retry the syscall. If you + /// want to handle signals yourself, however, use `poll_interruptible`. + pub fn poll_interruptible(&self, events: &mut Events, timeout: Option) -> io::Result { + self.poll1(events, timeout, true) + } + + fn poll1(&self, events: &mut Events, mut timeout: Option, interruptible: bool) -> io::Result { + let zero = Some(Duration::from_millis(0)); + + // At a high level, the synchronization strategy is to acquire access to + // the critical section by transitioning the atomic from unlocked -> + // locked. If the attempt fails, the thread will wait on the condition + // variable. + // + // # Some more detail + // + // The `lock_state` atomic usize combines: + // + // - locked flag, stored in the least significant bit + // - number of waiting threads, stored in the rest of the bits. + // + // When a thread transitions the locked flag from 0 -> 1, it has + // obtained access to the critical section. + // + // When entering `poll`, a compare-and-swap from 0 -> 1 is attempted. + // This is a fast path for the case when there are no concurrent calls + // to poll, which is very common. + // + // On failure, the mutex is locked, and the thread attempts to increment + // the number of waiting threads component of `lock_state`. If this is + // successfully done while the locked flag is set, then the thread can + // wait on the condition variable. + // + // When a thread exits the critical section, it unsets the locked flag. + // If there are any waiters, which is atomically determined while + // unsetting the locked flag, then the condvar is notified. + + let mut curr = self.lock_state.compare_and_swap(0, 1, SeqCst); + + if 0 != curr { + // Enter slower path + let mut lock = self.lock.lock().unwrap(); + let mut inc = false; + + loop { + if curr & 1 == 0 { + // The lock is currently free, attempt to grab it + let mut next = curr | 1; + + if inc { + // The waiter count has previously been incremented, so + // decrement it here + next -= 2; + } + + let actual = self.lock_state.compare_and_swap(curr, next, SeqCst); + + if actual != curr { + curr = actual; + continue; + } + + // Lock acquired, break from the loop + break; + } + + if timeout == zero { + if inc { + self.lock_state.fetch_sub(2, SeqCst); + } + + return Ok(0); + } + + // The lock is currently held, so wait for it to become + // free. If the waiter count hasn't been incremented yet, do + // so now + if !inc { + let next = curr.checked_add(2).expect("overflow"); + let actual = self.lock_state.compare_and_swap(curr, next, SeqCst); + + if actual != curr { + curr = actual; + continue; + } + + // Track that the waiter count has been incremented for + // this thread and fall through to the condvar waiting + inc = true; + } + + lock = match timeout { + Some(to) => { + let now = Instant::now(); + + // Wait to be notified + let (l, _) = self.condvar.wait_timeout(lock, to).unwrap(); + + // See how much time was elapsed in the wait + let elapsed = now.elapsed(); + + // Update `timeout` to reflect how much time is left to + // wait. + if elapsed >= to { + timeout = zero; + } else { + // Update the timeout + timeout = Some(to - elapsed); + } + + l + } + None => { + self.condvar.wait(lock).unwrap() + } + }; + + // Reload the state + curr = self.lock_state.load(SeqCst); + + // Try to lock again... + } + } + + let ret = self.poll2(events, timeout, interruptible); + + // Release the lock + if 1 != self.lock_state.fetch_and(!1, Release) { + // Acquire the mutex + let _lock = self.lock.lock().unwrap(); + + // There is at least one waiting thread, so notify one + self.condvar.notify_one(); + } + + ret + } + + #[inline] + #[cfg_attr(feature = "cargo-clippy", allow(clippy::if_same_then_else))] + fn poll2(&self, events: &mut Events, mut timeout: Option, interruptible: bool) -> io::Result { + // Compute the timeout value passed to the system selector. If the + // readiness queue has pending nodes, we still want to poll the system + // selector for new events, but we don't want to block the thread to + // wait for new events. + if timeout == Some(Duration::from_millis(0)) { + // If blocking is not requested, then there is no need to prepare + // the queue for sleep + // + // The sleep_marker should be removed by readiness_queue.poll(). + } else if self.readiness_queue.prepare_for_sleep() { + // The readiness queue is empty. The call to `prepare_for_sleep` + // inserts `sleep_marker` into the queue. This signals to any + // threads setting readiness that the `Poll::poll` is going to + // sleep, so the awakener should be used. + } else { + // The readiness queue is not empty, so do not block the thread. + timeout = Some(Duration::from_millis(0)); + } + + loop { + let now = Instant::now(); + // First get selector events + let res = self.selector.select(&mut events.inner, AWAKEN, timeout); + match res { + Ok(true) => { + // Some awakeners require reading from a FD. + self.readiness_queue.inner.awakener.cleanup(); + break; + } + Ok(false) => break, + Err(ref e) if e.kind() == io::ErrorKind::Interrupted && !interruptible => { + // Interrupted by a signal; update timeout if necessary and retry + if let Some(to) = timeout { + let elapsed = now.elapsed(); + if elapsed >= to { + break; + } else { + timeout = Some(to - elapsed); + } + } + } + Err(e) => return Err(e), + } + } + + // Poll custom event queue + self.readiness_queue.poll(&mut events.inner); + + // Return number of polled events + Ok(events.inner.len()) + } +} + +fn validate_args(token: Token) -> io::Result<()> { + if token == AWAKEN { + return Err(io::Error::new(io::ErrorKind::Other, "invalid token")); + } + + Ok(()) +} + +impl fmt::Debug for Poll { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Poll") + .finish() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl AsRawFd for Poll { + fn as_raw_fd(&self) -> RawFd { + self.selector.as_raw_fd() + } +} + +/// A collection of readiness events. +/// +/// `Events` is passed as an argument to [`Poll::poll`] and will be used to +/// receive any new readiness events received since the last poll. Usually, a +/// single `Events` instance is created at the same time as a [`Poll`] and +/// reused on each call to [`Poll::poll`]. +/// +/// See [`Poll`] for more documentation on polling. +/// +/// # Examples +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Poll}; +/// use std::time::Duration; +/// +/// let mut events = Events::with_capacity(1024); +/// let poll = Poll::new()?; +/// +/// assert_eq!(0, events.len()); +/// +/// // Register `Evented` handles with `poll` +/// +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// +/// for event in &events { +/// println!("event={:?}", event); +/// } +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// [`Poll::poll`]: struct.Poll.html#method.poll +/// [`Poll`]: struct.Poll.html +pub struct Events { + inner: sys::Events, +} + +/// [`Events`] iterator. +/// +/// This struct is created by the [`iter`] method on [`Events`]. +/// +/// # Examples +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Poll}; +/// use std::time::Duration; +/// +/// let mut events = Events::with_capacity(1024); +/// let poll = Poll::new()?; +/// +/// // Register handles with `poll` +/// +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// +/// for event in events.iter() { +/// println!("event={:?}", event); +/// } +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// [`Events`]: struct.Events.html +/// [`iter`]: struct.Events.html#method.iter +#[derive(Debug, Clone)] +pub struct Iter<'a> { + inner: &'a Events, + pos: usize, +} + +/// Owned [`Events`] iterator. +/// +/// This struct is created by the `into_iter` method on [`Events`]. +/// +/// # Examples +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Poll}; +/// use std::time::Duration; +/// +/// let mut events = Events::with_capacity(1024); +/// let poll = Poll::new()?; +/// +/// // Register handles with `poll` +/// +/// poll.poll(&mut events, Some(Duration::from_millis(100)))?; +/// +/// for event in events { +/// println!("event={:?}", event); +/// } +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// [`Events`]: struct.Events.html +#[derive(Debug)] +pub struct IntoIter { + inner: Events, + pos: usize, +} + +impl Events { + /// Return a new `Events` capable of holding up to `capacity` events. + /// + /// # Examples + /// + /// ``` + /// use mio::Events; + /// + /// let events = Events::with_capacity(1024); + /// + /// assert_eq!(1024, events.capacity()); + /// ``` + pub fn with_capacity(capacity: usize) -> Events { + Events { + inner: sys::Events::with_capacity(capacity), + } + } + + #[deprecated(since="0.6.10", note="Index access removed in favor of iterator only API.")] + #[doc(hidden)] + pub fn get(&self, idx: usize) -> Option { + self.inner.get(idx) + } + + #[doc(hidden)] + #[deprecated(since="0.6.10", note="Index access removed in favor of iterator only API.")] + pub fn len(&self) -> usize { + self.inner.len() + } + + /// Returns the number of `Event` values that `self` can hold. + /// + /// ``` + /// use mio::Events; + /// + /// let events = Events::with_capacity(1024); + /// + /// assert_eq!(1024, events.capacity()); + /// ``` + pub fn capacity(&self) -> usize { + self.inner.capacity() + } + + /// Returns `true` if `self` contains no `Event` values. + /// + /// # Examples + /// + /// ``` + /// use mio::Events; + /// + /// let events = Events::with_capacity(1024); + /// + /// assert!(events.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + /// Returns an iterator over the `Event` values. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Poll}; + /// use std::time::Duration; + /// + /// let mut events = Events::with_capacity(1024); + /// let poll = Poll::new()?; + /// + /// // Register handles with `poll` + /// + /// poll.poll(&mut events, Some(Duration::from_millis(100)))?; + /// + /// for event in events.iter() { + /// println!("event={:?}", event); + /// } + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn iter(&self) -> Iter { + Iter { + inner: self, + pos: 0 + } + } + + /// Clearing all `Event` values from container explicitly. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Poll}; + /// use std::time::Duration; + /// + /// let mut events = Events::with_capacity(1024); + /// let poll = Poll::new()?; + /// + /// // Register handles with `poll` + /// for _ in 0..2 { + /// events.clear(); + /// poll.poll(&mut events, Some(Duration::from_millis(100)))?; + /// + /// for event in events.iter() { + /// println!("event={:?}", event); + /// } + /// } + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn clear(&mut self) { + self.inner.clear(); + } +} + +impl<'a> IntoIterator for &'a Events { + type Item = Event; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a> Iterator for Iter<'a> { + type Item = Event; + + fn next(&mut self) -> Option { + let ret = self.inner.inner.get(self.pos); + self.pos += 1; + ret + } +} + +impl IntoIterator for Events { + type Item = Event; + type IntoIter = IntoIter; + + fn into_iter(self) -> Self::IntoIter { + IntoIter { + inner: self, + pos: 0, + } + } +} + +impl Iterator for IntoIter { + type Item = Event; + + fn next(&mut self) -> Option { + let ret = self.inner.inner.get(self.pos); + self.pos += 1; + ret + } +} + +impl fmt::Debug for Events { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Events") + .field("capacity", &self.capacity()) + .finish() + } +} + +// ===== Accessors for internal usage ===== + +pub fn selector(poll: &Poll) -> &sys::Selector { + &poll.selector +} + +/* + * + * ===== Registration ===== + * + */ + +// TODO: get rid of this, windows depends on it for now +#[allow(dead_code)] +pub fn new_registration(poll: &Poll, token: Token, ready: Ready, opt: PollOpt) + -> (Registration, SetReadiness) +{ + Registration::new_priv(poll, token, ready, opt) +} + +impl Registration { + /// Create and return a new `Registration` and the associated + /// `SetReadiness`. + /// + /// See [struct] documentation for more detail and [`Poll`] + /// for high level documentation on polling. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Ready, Registration, Poll, PollOpt, Token}; + /// use std::thread; + /// + /// let (registration, set_readiness) = Registration::new2(); + /// + /// thread::spawn(move || { + /// use std::time::Duration; + /// thread::sleep(Duration::from_millis(500)); + /// + /// set_readiness.set_readiness(Ready::readable()); + /// }); + /// + /// let poll = Poll::new()?; + /// poll.register(®istration, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge())?; + /// + /// let mut events = Events::with_capacity(256); + /// + /// loop { + /// poll.poll(&mut events, None); + /// + /// for event in &events { + /// if event.token() == Token(0) && event.readiness().is_readable() { + /// return Ok(()); + /// } + /// } + /// } + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// [struct]: # + /// [`Poll`]: struct.Poll.html + pub fn new2() -> (Registration, SetReadiness) { + // Allocate the registration node. The new node will have `ref_count` + // set to 2: one SetReadiness, one Registration. + let node = Box::into_raw(Box::new(ReadinessNode::new( + ptr::null_mut(), Token(0), Ready::empty(), PollOpt::empty(), 2))); + + let registration = Registration { + inner: RegistrationInner { + node, + }, + }; + + let set_readiness = SetReadiness { + inner: RegistrationInner { + node, + }, + }; + + (registration, set_readiness) + } + + #[deprecated(since = "0.6.5", note = "use `new2` instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn new(poll: &Poll, token: Token, interest: Ready, opt: PollOpt) + -> (Registration, SetReadiness) + { + Registration::new_priv(poll, token, interest, opt) + } + + // TODO: Get rid of this (windows depends on it for now) + fn new_priv(poll: &Poll, token: Token, interest: Ready, opt: PollOpt) + -> (Registration, SetReadiness) + { + is_send::(); + is_sync::(); + is_send::(); + is_sync::(); + + // Clone handle to the readiness queue, this bumps the ref count + let queue = poll.readiness_queue.inner.clone(); + + // Convert to a *mut () pointer + let queue: *mut () = unsafe { mem::transmute(queue) }; + + // Allocate the registration node. The new node will have `ref_count` + // set to 3: one SetReadiness, one Registration, and one Poll handle. + let node = Box::into_raw(Box::new(ReadinessNode::new( + queue, token, interest, opt, 3))); + + let registration = Registration { + inner: RegistrationInner { + node, + }, + }; + + let set_readiness = SetReadiness { + inner: RegistrationInner { + node, + }, + }; + + (registration, set_readiness) + } + + #[deprecated(since = "0.6.5", note = "use `Evented` impl")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn update(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.inner.update(poll, token, interest, opts) + } + + #[deprecated(since = "0.6.5", note = "use `Poll::deregister` instead")] + #[cfg(feature = "with-deprecated")] + #[doc(hidden)] + pub fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner.update(poll, Token(0), Ready::empty(), PollOpt::empty()) + } +} + +impl Evented for Registration { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.inner.update(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.inner.update(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner.update(poll, Token(0), Ready::empty(), PollOpt::empty()) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + // `flag_as_dropped` toggles the `dropped` flag and notifies + // `Poll::poll` to release its handle (which is just decrementing + // the ref count). + if self.inner.state.flag_as_dropped() { + // Can't do anything if the queuing fails + let _ = self.inner.enqueue_with_wakeup(); + } + } +} + +impl fmt::Debug for Registration { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Registration") + .finish() + } +} + +impl SetReadiness { + /// Returns the registration's current readiness. + /// + /// # Note + /// + /// There is no guarantee that `readiness` establishes any sort of memory + /// ordering. Any concurrent data access must be synchronized using another + /// strategy. + /// + /// # Examples + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Registration, Ready}; + /// + /// let (registration, set_readiness) = Registration::new2(); + /// + /// assert!(set_readiness.readiness().is_empty()); + /// + /// set_readiness.set_readiness(Ready::readable())?; + /// assert!(set_readiness.readiness().is_readable()); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn readiness(&self) -> Ready { + self.inner.readiness() + } + + /// Set the registration's readiness + /// + /// If the associated `Registration` is registered with a [`Poll`] instance + /// and has requested readiness events that include `ready`, then a future + /// call to [`Poll::poll`] will receive a readiness event representing the + /// readiness state change. + /// + /// # Note + /// + /// There is no guarantee that `readiness` establishes any sort of memory + /// ordering. Any concurrent data access must be synchronized using another + /// strategy. + /// + /// There is also no guarantee as to when the readiness event will be + /// delivered to poll. A best attempt will be made to make the delivery in a + /// "timely" fashion. For example, the following is **not** guaranteed to + /// work: + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Events, Registration, Ready, Poll, PollOpt, Token}; + /// + /// let poll = Poll::new()?; + /// let (registration, set_readiness) = Registration::new2(); + /// + /// poll.register(®istration, + /// Token(0), + /// Ready::readable(), + /// PollOpt::edge())?; + /// + /// // Set the readiness, then immediately poll to try to get the readiness + /// // event + /// set_readiness.set_readiness(Ready::readable())?; + /// + /// let mut events = Events::with_capacity(1024); + /// poll.poll(&mut events, None)?; + /// + /// // There is NO guarantee that the following will work. It is possible + /// // that the readiness event will be delivered at a later time. + /// let event = events.get(0).unwrap(); + /// assert_eq!(event.token(), Token(0)); + /// assert!(event.readiness().is_readable()); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// + /// # Examples + /// + /// A simple example, for a more elaborate example, see the [`Evented`] + /// documentation. + /// + /// ``` + /// # use std::error::Error; + /// # fn try_main() -> Result<(), Box> { + /// use mio::{Registration, Ready}; + /// + /// let (registration, set_readiness) = Registration::new2(); + /// + /// assert!(set_readiness.readiness().is_empty()); + /// + /// set_readiness.set_readiness(Ready::readable())?; + /// assert!(set_readiness.readiness().is_readable()); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// + /// [`Registration`]: struct.Registration.html + /// [`Evented`]: event/trait.Evented.html#examples + /// [`Poll`]: struct.Poll.html + /// [`Poll::poll`]: struct.Poll.html#method.poll + pub fn set_readiness(&self, ready: Ready) -> io::Result<()> { + self.inner.set_readiness(ready) + } +} + +impl fmt::Debug for SetReadiness { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("SetReadiness") + .finish() + } +} + +impl RegistrationInner { + /// Get the registration's readiness. + fn readiness(&self) -> Ready { + self.state.load(Relaxed).readiness() + } + + /// Set the registration's readiness. + /// + /// This function can be called concurrently by an arbitrary number of + /// SetReadiness handles. + fn set_readiness(&self, ready: Ready) -> io::Result<()> { + // Load the current atomic state. + let mut state = self.state.load(Acquire); + let mut next; + + loop { + next = state; + + if state.is_dropped() { + // Node is dropped, no more notifications + return Ok(()); + } + + // Update the readiness + next.set_readiness(ready); + + // If the readiness is not blank, try to obtain permission to + // push the node into the readiness queue. + if !next.effective_readiness().is_empty() { + next.set_queued(); + } + + let actual = self.state.compare_and_swap(state, next, AcqRel); + + if state == actual { + break; + } + + state = actual; + } + + if !state.is_queued() && next.is_queued() { + // We toggled the queued flag, making us responsible for queuing the + // node in the MPSC readiness queue. + self.enqueue_with_wakeup()?; + } + + Ok(()) + } + + /// Update the registration details associated with the node + fn update(&self, poll: &Poll, token: Token, interest: Ready, opt: PollOpt) -> io::Result<()> { + // First, ensure poll instances match + // + // Load the queue pointer, `Relaxed` is sufficient here as only the + // pointer is being operated on. The actual memory is guaranteed to be + // visible the `poll: &Poll` ref passed as an argument to the function. + let mut queue = self.readiness_queue.load(Relaxed); + let other: &*mut () = unsafe { + &*(&poll.readiness_queue.inner as *const _ as *const *mut ()) + }; + let other = *other; + + debug_assert!(mem::size_of::>() == mem::size_of::<*mut ()>()); + + if queue.is_null() { + // Attempt to set the queue pointer. `Release` ordering synchronizes + // with `Acquire` in `ensure_with_wakeup`. + let actual = self.readiness_queue.compare_and_swap( + queue, other, Release); + + if actual.is_null() { + // The CAS succeeded, this means that the node's ref count + // should be incremented to reflect that the `poll` function + // effectively owns the node as well. + // + // `Relaxed` ordering used for the same reason as in + // RegistrationInner::clone + self.ref_count.fetch_add(1, Relaxed); + + // Note that the `queue` reference stored in our + // `readiness_queue` field is intended to be a strong reference, + // so now that we've successfully claimed the reference we bump + // the refcount here. + // + // Down below in `release_node` when we deallocate this + // `RegistrationInner` is where we'll transmute this back to an + // arc and decrement the reference count. + mem::forget(poll.readiness_queue.clone()); + } else { + // The CAS failed, another thread set the queue pointer, so ensure + // that the pointer and `other` match + if actual != other { + return Err(io::Error::new(io::ErrorKind::Other, "registration handle associated with another `Poll` instance")); + } + } + + queue = other; + } else if queue != other { + return Err(io::Error::new(io::ErrorKind::Other, "registration handle associated with another `Poll` instance")); + } + + unsafe { + let actual = &poll.readiness_queue.inner as *const _ as *const usize; + debug_assert_eq!(queue as usize, *actual); + } + + // The `update_lock` atomic is used as a flag ensuring only a single + // thread concurrently enters the `update` critical section. Any + // concurrent calls to update are discarded. If coordinated updates are + // required, the Mio user is responsible for handling that. + // + // Acquire / Release ordering is used on `update_lock` to ensure that + // data access to the `token_*` variables are scoped to the critical + // section. + + // Acquire the update lock. + if self.update_lock.compare_and_swap(false, true, Acquire) { + // The lock is already held. Discard the update + return Ok(()); + } + + // Relaxed ordering is acceptable here as the only memory that needs to + // be visible as part of the update are the `token_*` variables, and + // ordering has already been handled by the `update_lock` access. + let mut state = self.state.load(Relaxed); + let mut next; + + // Read the current token, again this memory has been ordered by the + // acquire on `update_lock`. + let curr_token_pos = state.token_write_pos(); + let curr_token = unsafe { self::token(self, curr_token_pos) }; + + let mut next_token_pos = curr_token_pos; + + // If the `update` call is changing the token, then compute the next + // available token slot and write the token there. + // + // Note that this computation is happening *outside* of the + // compare-and-swap loop. The update lock ensures that only a single + // thread could be mutating the write_token_position, so the + // `next_token_pos` will never need to be recomputed even if + // `token_read_pos` concurrently changes. This is because + // `token_read_pos` can ONLY concurrently change to the current value of + // `token_write_pos`, so `next_token_pos` will always remain valid. + if token != curr_token { + next_token_pos = state.next_token_pos(); + + // Update the token + match next_token_pos { + 0 => unsafe { *self.token_0.get() = token }, + 1 => unsafe { *self.token_1.get() = token }, + 2 => unsafe { *self.token_2.get() = token }, + _ => unreachable!(), + } + } + + // Now enter the compare-and-swap loop + loop { + next = state; + + // The node is only dropped once all `Registration` handles are + // dropped. Only `Registration` can call `update`. + debug_assert!(!state.is_dropped()); + + // Update the write token position, this will also release the token + // to Poll::poll. + next.set_token_write_pos(next_token_pos); + + // Update readiness and poll opts + next.set_interest(interest); + next.set_poll_opt(opt); + + // If there is effective readiness, the node will need to be queued + // for processing. This exact behavior is still TBD, so we are + // conservative for now and always fire. + // + // See https://github.com/carllerche/mio/issues/535. + if !next.effective_readiness().is_empty() { + next.set_queued(); + } + + // compare-and-swap the state values. Only `Release` is needed here. + // The `Release` ensures that `Poll::poll` will see the token + // update and the update function doesn't care about any other + // memory visibility. + let actual = self.state.compare_and_swap(state, next, Release); + + if actual == state { + break; + } + + // CAS failed, but `curr_token_pos` should not have changed given + // that we still hold the update lock. + debug_assert_eq!(curr_token_pos, actual.token_write_pos()); + + state = actual; + } + + // Release the lock + self.update_lock.store(false, Release); + + if !state.is_queued() && next.is_queued() { + // We are responsible for enqueing the node. + enqueue_with_wakeup(queue, self)?; + } + + Ok(()) + } +} + +impl ops::Deref for RegistrationInner { + type Target = ReadinessNode; + + fn deref(&self) -> &ReadinessNode { + unsafe { &*self.node } + } +} + +impl Clone for RegistrationInner { + fn clone(&self) -> RegistrationInner { + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object. + // + // As explained in the [Boost documentation][1], Increasing the + // reference counter can always be done with memory_order_relaxed: New + // references to an object can only be formed from an existing + // reference, and passing an existing reference from one thread to + // another must already provide any required synchronization. + // + // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) + let old_size = self.ref_count.fetch_add(1, Relaxed); + + // However we need to guard against massive refcounts in case someone + // is `mem::forget`ing Arcs. If we don't do this the count can overflow + // and users will use-after free. We racily saturate to `isize::MAX` on + // the assumption that there aren't ~2 billion threads incrementing + // the reference count at once. This branch will never be taken in + // any realistic program. + // + // We abort because such a program is incredibly degenerate, and we + // don't care to support it. + if old_size & !MAX_REFCOUNT != 0 { + process::abort(); + } + + RegistrationInner { + node: self.node, + } + } +} + +impl Drop for RegistrationInner { + fn drop(&mut self) { + // Only handles releasing from `Registration` and `SetReadiness` + // handles. Poll has to call this itself. + release_node(self.node); + } +} + +/* + * + * ===== ReadinessQueue ===== + * + */ + +impl ReadinessQueue { + /// Create a new `ReadinessQueue`. + fn new() -> io::Result { + is_send::(); + is_sync::(); + + let end_marker = Box::new(ReadinessNode::marker()); + let sleep_marker = Box::new(ReadinessNode::marker()); + let closed_marker = Box::new(ReadinessNode::marker()); + + let ptr = &*end_marker as *const _ as *mut _; + + Ok(ReadinessQueue { + inner: Arc::new(ReadinessQueueInner { + awakener: sys::Awakener::new()?, + head_readiness: AtomicPtr::new(ptr), + tail_readiness: UnsafeCell::new(ptr), + end_marker, + sleep_marker, + closed_marker, + }) + }) + } + + /// Poll the queue for new events + fn poll(&self, dst: &mut sys::Events) { + // `until` is set with the first node that gets re-enqueued due to being + // set to have level-triggered notifications. This prevents an infinite + // loop where `Poll::poll` will keep dequeuing nodes it enqueues. + let mut until = ptr::null_mut(); + + if dst.len() == dst.capacity() { + // If `dst` is already full, the readiness queue won't be drained. + // This might result in `sleep_marker` staying in the queue and + // unecessary pipe writes occuring. + self.inner.clear_sleep_marker(); + } + + 'outer: + while dst.len() < dst.capacity() { + // Dequeue a node. If the queue is in an inconsistent state, then + // stop polling. `Poll::poll` will be called again shortly and enter + // a syscall, which should be enough to enable the other thread to + // finish the queuing process. + let ptr = match unsafe { self.inner.dequeue_node(until) } { + Dequeue::Empty | Dequeue::Inconsistent => break, + Dequeue::Data(ptr) => ptr, + }; + + let node = unsafe { &*ptr }; + + // Read the node state with Acquire ordering. This allows reading + // the token variables. + let mut state = node.state.load(Acquire); + let mut next; + let mut readiness; + let mut opt; + + loop { + // Build up any changes to the readiness node's state and + // attempt the CAS at the end + next = state; + + // Given that the node was just read from the queue, the + // `queued` flag should still be set. + debug_assert!(state.is_queued()); + + // The dropped flag means we need to release the node and + // perform no further processing on it. + if state.is_dropped() { + // Release the node and continue + release_node(ptr); + continue 'outer; + } + + // Process the node + readiness = state.effective_readiness(); + opt = state.poll_opt(); + + if opt.is_edge() { + // Mark the node as dequeued + next.set_dequeued(); + + if opt.is_oneshot() && !readiness.is_empty() { + next.disarm(); + } + } else if readiness.is_empty() { + next.set_dequeued(); + } + + // Ensure `token_read_pos` is set to `token_write_pos` so that + // we read the most up to date token value. + next.update_token_read_pos(); + + if state == next { + break; + } + + let actual = node.state.compare_and_swap(state, next, AcqRel); + + if actual == state { + break; + } + + state = actual; + } + + // If the queued flag is still set, then the node must be requeued. + // This typically happens when using level-triggered notifications. + if next.is_queued() { + if until.is_null() { + // We never want to see the node again + until = ptr; + } + + // Requeue the node + self.inner.enqueue_node(node); + } + + if !readiness.is_empty() { + // Get the token + let token = unsafe { token(node, next.token_read_pos()) }; + + // Push the event + dst.push_event(Event::new(readiness, token)); + } + } + } + + /// Prepare the queue for the `Poll::poll` thread to block in the system + /// selector. This involves changing `head_readiness` to `sleep_marker`. + /// Returns true if successful and `poll` can block. + fn prepare_for_sleep(&self) -> bool { + let end_marker = self.inner.end_marker(); + let sleep_marker = self.inner.sleep_marker(); + + let tail = unsafe { *self.inner.tail_readiness.get() }; + + // If the tail is currently set to the sleep_marker, then check if the + // head is as well. If it is, then the queue is currently ready to + // sleep. If it is not, then the queue is not empty and there should be + // no sleeping. + if tail == sleep_marker { + return self.inner.head_readiness.load(Acquire) == sleep_marker; + } + + // If the tail is not currently set to `end_marker`, then the queue is + // not empty. + if tail != end_marker { + return false; + } + + // The sleep marker is *not* currently in the readiness queue. + // + // The sleep marker is only inserted in this function. It is also only + // inserted in the tail position. This is guaranteed by first checking + // that the end marker is in the tail position, pushing the sleep marker + // after the end marker, then removing the end marker. + // + // Before inserting a node into the queue, the next pointer has to be + // set to null. Again, this is only safe to do when the node is not + // currently in the queue, but we already have ensured this. + self.inner.sleep_marker.next_readiness.store(ptr::null_mut(), Relaxed); + + let actual = self.inner.head_readiness.compare_and_swap( + end_marker, sleep_marker, AcqRel); + + debug_assert!(actual != sleep_marker); + + if actual != end_marker { + // The readiness queue is not empty + return false; + } + + // The current tail should be pointing to `end_marker` + debug_assert!(unsafe { *self.inner.tail_readiness.get() == end_marker }); + // The `end_marker` next pointer should be null + debug_assert!(self.inner.end_marker.next_readiness.load(Relaxed).is_null()); + + // Update tail pointer. + unsafe { *self.inner.tail_readiness.get() = sleep_marker; } + true + } +} + +impl Drop for ReadinessQueue { + fn drop(&mut self) { + // Close the queue by enqueuing the closed node + self.inner.enqueue_node(&*self.inner.closed_marker); + + loop { + // Free any nodes that happen to be left in the readiness queue + let ptr = match unsafe { self.inner.dequeue_node(ptr::null_mut()) } { + Dequeue::Empty => break, + Dequeue::Inconsistent => { + // This really shouldn't be possible as all other handles to + // `ReadinessQueueInner` are dropped, but handle this by + // spinning I guess? + continue; + } + Dequeue::Data(ptr) => ptr, + }; + + let node = unsafe { &*ptr }; + + let state = node.state.load(Acquire); + + debug_assert!(state.is_queued()); + + release_node(ptr); + } + } +} + +impl ReadinessQueueInner { + fn wakeup(&self) -> io::Result<()> { + self.awakener.wakeup() + } + + /// Prepend the given node to the head of the readiness queue. This is done + /// with relaxed ordering. Returns true if `Poll` needs to be woken up. + fn enqueue_node_with_wakeup(&self, node: &ReadinessNode) -> io::Result<()> { + if self.enqueue_node(node) { + self.wakeup()?; + } + + Ok(()) + } + + /// Push the node into the readiness queue + fn enqueue_node(&self, node: &ReadinessNode) -> bool { + // This is the 1024cores.net intrusive MPSC queue [1] "push" function. + let node_ptr = node as *const _ as *mut _; + + // Relaxed used as the ordering is "released" when swapping + // `head_readiness` + node.next_readiness.store(ptr::null_mut(), Relaxed); + + unsafe { + let mut prev = self.head_readiness.load(Acquire); + + loop { + if prev == self.closed_marker() { + debug_assert!(node_ptr != self.closed_marker()); + // debug_assert!(node_ptr != self.end_marker()); + debug_assert!(node_ptr != self.sleep_marker()); + + if node_ptr != self.end_marker() { + // The readiness queue is shutdown, but the enqueue flag was + // set. This means that we are responsible for decrementing + // the ready queue's ref count + debug_assert!(node.ref_count.load(Relaxed) >= 2); + release_node(node_ptr); + } + + return false; + } + + let act = self.head_readiness.compare_and_swap(prev, node_ptr, AcqRel); + + if prev == act { + break; + } + + prev = act; + } + + debug_assert!((*prev).next_readiness.load(Relaxed).is_null()); + + (*prev).next_readiness.store(node_ptr, Release); + + prev == self.sleep_marker() + } + } + + fn clear_sleep_marker(&self) { + let end_marker = self.end_marker(); + let sleep_marker = self.sleep_marker(); + + unsafe { + let tail = *self.tail_readiness.get(); + + if tail != self.sleep_marker() { + return; + } + + // The empty markeer is *not* currently in the readiness queue + // (since the sleep markeris). + self.end_marker.next_readiness.store(ptr::null_mut(), Relaxed); + + let actual = self.head_readiness.compare_and_swap( + sleep_marker, end_marker, AcqRel); + + debug_assert!(actual != end_marker); + + if actual != sleep_marker { + // The readiness queue is not empty, we cannot remove the sleep + // markeer + return; + } + + // Update the tail pointer. + *self.tail_readiness.get() = end_marker; + } + } + + /// Must only be called in `poll` or `drop` + unsafe fn dequeue_node(&self, until: *mut ReadinessNode) -> Dequeue { + // This is the 1024cores.net intrusive MPSC queue [1] "pop" function + // with the modifications mentioned at the top of the file. + let mut tail = *self.tail_readiness.get(); + let mut next = (*tail).next_readiness.load(Acquire); + + if tail == self.end_marker() || tail == self.sleep_marker() || tail == self.closed_marker() { + if next.is_null() { + // Make sure the sleep marker is removed (as we are no longer + // sleeping + self.clear_sleep_marker(); + + return Dequeue::Empty; + } + + *self.tail_readiness.get() = next; + tail = next; + next = (*next).next_readiness.load(Acquire); + } + + // Only need to check `until` at this point. `until` is either null, + // which will never match tail OR it is a node that was pushed by + // the current thread. This means that either: + // + // 1) The queue is inconsistent, which is handled explicitly + // 2) We encounter `until` at this point in dequeue + // 3) we will pop a different node + if tail == until { + return Dequeue::Empty; + } + + if !next.is_null() { + *self.tail_readiness.get() = next; + return Dequeue::Data(tail); + } + + if self.head_readiness.load(Acquire) != tail { + return Dequeue::Inconsistent; + } + + // Push the stub node + self.enqueue_node(&*self.end_marker); + + next = (*tail).next_readiness.load(Acquire); + + if !next.is_null() { + *self.tail_readiness.get() = next; + return Dequeue::Data(tail); + } + + Dequeue::Inconsistent + } + + fn end_marker(&self) -> *mut ReadinessNode { + &*self.end_marker as *const ReadinessNode as *mut ReadinessNode + } + + fn sleep_marker(&self) -> *mut ReadinessNode { + &*self.sleep_marker as *const ReadinessNode as *mut ReadinessNode + } + + fn closed_marker(&self) -> *mut ReadinessNode { + &*self.closed_marker as *const ReadinessNode as *mut ReadinessNode + } +} + +impl ReadinessNode { + /// Return a new `ReadinessNode`, initialized with a ref_count of 3. + fn new(queue: *mut (), + token: Token, + interest: Ready, + opt: PollOpt, + ref_count: usize) -> ReadinessNode + { + ReadinessNode { + state: AtomicState::new(interest, opt), + // Only the first token is set, the others are initialized to 0 + token_0: UnsafeCell::new(token), + token_1: UnsafeCell::new(Token(0)), + token_2: UnsafeCell::new(Token(0)), + next_readiness: AtomicPtr::new(ptr::null_mut()), + update_lock: AtomicBool::new(false), + readiness_queue: AtomicPtr::new(queue), + ref_count: AtomicUsize::new(ref_count), + } + } + + fn marker() -> ReadinessNode { + ReadinessNode { + state: AtomicState::new(Ready::empty(), PollOpt::empty()), + token_0: UnsafeCell::new(Token(0)), + token_1: UnsafeCell::new(Token(0)), + token_2: UnsafeCell::new(Token(0)), + next_readiness: AtomicPtr::new(ptr::null_mut()), + update_lock: AtomicBool::new(false), + readiness_queue: AtomicPtr::new(ptr::null_mut()), + ref_count: AtomicUsize::new(0), + } + } + + fn enqueue_with_wakeup(&self) -> io::Result<()> { + let queue = self.readiness_queue.load(Acquire); + + if queue.is_null() { + // Not associated with a queue, nothing to do + return Ok(()); + } + + enqueue_with_wakeup(queue, self) + } +} + +fn enqueue_with_wakeup(queue: *mut (), node: &ReadinessNode) -> io::Result<()> { + debug_assert!(!queue.is_null()); + // This is ugly... but we don't want to bump the ref count. + let queue: &Arc = unsafe { + &*(&queue as *const *mut () as *const Arc) + }; + queue.enqueue_node_with_wakeup(node) +} + +unsafe fn token(node: &ReadinessNode, pos: usize) -> Token { + match pos { + 0 => *node.token_0.get(), + 1 => *node.token_1.get(), + 2 => *node.token_2.get(), + _ => unreachable!(), + } +} + +fn release_node(ptr: *mut ReadinessNode) { + unsafe { + // `AcqRel` synchronizes with other `release_node` functions and ensures + // that the drop happens after any reads / writes on other threads. + if (*ptr).ref_count.fetch_sub(1, AcqRel) != 1 { + return; + } + + let node = Box::from_raw(ptr); + + // Decrement the readiness_queue Arc + let queue = node.readiness_queue.load(Acquire); + + if queue.is_null() { + return; + } + + let _: Arc = mem::transmute(queue); + } +} + +impl AtomicState { + fn new(interest: Ready, opt: PollOpt) -> AtomicState { + let state = ReadinessState::new(interest, opt); + + AtomicState { + inner: AtomicUsize::new(state.into()), + } + } + + /// Loads the current `ReadinessState` + fn load(&self, order: Ordering) -> ReadinessState { + self.inner.load(order).into() + } + + /// Stores a state if the current state is the same as `current`. + fn compare_and_swap(&self, current: ReadinessState, new: ReadinessState, order: Ordering) -> ReadinessState { + self.inner.compare_and_swap(current.into(), new.into(), order).into() + } + + // Returns `true` if the node should be queued + fn flag_as_dropped(&self) -> bool { + let prev: ReadinessState = self.inner.fetch_or(DROPPED_MASK | QUEUED_MASK, Release).into(); + // The flag should not have been previously set + debug_assert!(!prev.is_dropped()); + + !prev.is_queued() + } +} + +impl ReadinessState { + // Create a `ReadinessState` initialized with the provided arguments + #[inline] + fn new(interest: Ready, opt: PollOpt) -> ReadinessState { + let interest = event::ready_as_usize(interest); + let opt = event::opt_as_usize(opt); + + debug_assert!(interest <= MASK_4); + debug_assert!(opt <= MASK_4); + + let mut val = interest << INTEREST_SHIFT; + val |= opt << POLL_OPT_SHIFT; + + ReadinessState(val) + } + + #[inline] + fn get(self, mask: usize, shift: usize) -> usize{ + (self.0 >> shift) & mask + } + + #[inline] + fn set(&mut self, val: usize, mask: usize, shift: usize) { + self.0 = (self.0 & !(mask << shift)) | (val << shift) + } + + /// Get the readiness + #[inline] + fn readiness(self) -> Ready { + let v = self.get(MASK_4, READINESS_SHIFT); + event::ready_from_usize(v) + } + + #[inline] + fn effective_readiness(self) -> Ready { + self.readiness() & self.interest() + } + + /// Set the readiness + #[inline] + fn set_readiness(&mut self, v: Ready) { + self.set(event::ready_as_usize(v), MASK_4, READINESS_SHIFT); + } + + /// Get the interest + #[inline] + fn interest(self) -> Ready { + let v = self.get(MASK_4, INTEREST_SHIFT); + event::ready_from_usize(v) + } + + /// Set the interest + #[inline] + fn set_interest(&mut self, v: Ready) { + self.set(event::ready_as_usize(v), MASK_4, INTEREST_SHIFT); + } + + #[inline] + fn disarm(&mut self) { + self.set_interest(Ready::empty()); + } + + /// Get the poll options + #[inline] + fn poll_opt(self) -> PollOpt { + let v = self.get(MASK_4, POLL_OPT_SHIFT); + event::opt_from_usize(v) + } + + /// Set the poll options + #[inline] + fn set_poll_opt(&mut self, v: PollOpt) { + self.set(event::opt_as_usize(v), MASK_4, POLL_OPT_SHIFT); + } + + #[inline] + fn is_queued(self) -> bool { + self.0 & QUEUED_MASK == QUEUED_MASK + } + + /// Set the queued flag + #[inline] + fn set_queued(&mut self) { + // Dropped nodes should never be queued + debug_assert!(!self.is_dropped()); + self.0 |= QUEUED_MASK; + } + + #[inline] + fn set_dequeued(&mut self) { + debug_assert!(self.is_queued()); + self.0 &= !QUEUED_MASK + } + + #[inline] + fn is_dropped(self) -> bool { + self.0 & DROPPED_MASK == DROPPED_MASK + } + + #[inline] + fn token_read_pos(self) -> usize { + self.get(MASK_2, TOKEN_RD_SHIFT) + } + + #[inline] + fn token_write_pos(self) -> usize { + self.get(MASK_2, TOKEN_WR_SHIFT) + } + + #[inline] + fn next_token_pos(self) -> usize { + let rd = self.token_read_pos(); + let wr = self.token_write_pos(); + + match wr { + 0 => { + match rd { + 1 => 2, + 2 => 1, + 0 => 1, + _ => unreachable!(), + } + } + 1 => { + match rd { + 0 => 2, + 2 => 0, + 1 => 2, + _ => unreachable!(), + } + } + 2 => { + match rd { + 0 => 1, + 1 => 0, + 2 => 0, + _ => unreachable!(), + } + } + _ => unreachable!(), + } + } + + #[inline] + fn set_token_write_pos(&mut self, val: usize) { + self.set(val, MASK_2, TOKEN_WR_SHIFT); + } + + #[inline] + fn update_token_read_pos(&mut self) { + let val = self.token_write_pos(); + self.set(val, MASK_2, TOKEN_RD_SHIFT); + } +} + +impl From for usize { + fn from(src: ReadinessState) -> usize { + src.0 + } +} + +impl From for ReadinessState { + fn from(src: usize) -> ReadinessState { + ReadinessState(src) + } +} + +fn is_send() {} +fn is_sync() {} + +impl SelectorId { + pub fn new() -> SelectorId { + SelectorId { + id: AtomicUsize::new(0), + } + } + + pub fn associate_selector(&self, poll: &Poll) -> io::Result<()> { + let selector_id = self.id.load(Ordering::SeqCst); + + if selector_id != 0 && selector_id != poll.selector.id() { + Err(io::Error::new(io::ErrorKind::Other, "socket already registered")) + } else { + self.id.store(poll.selector.id(), Ordering::SeqCst); + Ok(()) + } + } +} + +impl Clone for SelectorId { + fn clone(&self) -> SelectorId { + SelectorId { + id: AtomicUsize::new(self.id.load(Ordering::SeqCst)), + } + } +} + +#[test] +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub fn as_raw_fd() { + let poll = Poll::new().unwrap(); + assert!(poll.as_raw_fd() > 0); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/awakener.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/awakener.rs new file mode 100644 index 0000000..19bc762 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/awakener.rs @@ -0,0 +1,73 @@ +use {io, poll, Evented, Ready, Poll, PollOpt, Token}; +use zircon; +use std::sync::{Arc, Mutex, Weak}; + +pub struct Awakener { + /// Token and weak reference to the port on which Awakener was registered. + /// + /// When `Awakener::wakeup` is called, these are used to send a wakeup message to the port. + inner: Mutex)>>, +} + +impl Awakener { + /// Create a new `Awakener`. + pub fn new() -> io::Result { + Ok(Awakener { + inner: Mutex::new(None) + }) + } + + /// Send a wakeup signal to the `Selector` on which the `Awakener` was registered. + pub fn wakeup(&self) -> io::Result<()> { + let inner_locked = self.inner.lock().unwrap(); + let &(token, ref weak_port) = + inner_locked.as_ref().expect("Called wakeup on unregistered awakener."); + + let port = weak_port.upgrade().expect("Tried to wakeup a closed port."); + + let status = 0; // arbitrary + let packet = zircon::Packet::from_user_packet( + token.0 as u64, status, zircon::UserPacket::from_u8_array([0; 32])); + + Ok(port.queue(&packet)?) + } + + pub fn cleanup(&self) {} +} + +impl Evented for Awakener { + fn register(&self, + poll: &Poll, + token: Token, + _events: Ready, + _opts: PollOpt) -> io::Result<()> + { + let mut inner_locked = self.inner.lock().unwrap(); + if inner_locked.is_some() { + panic!("Called register on already-registered Awakener."); + } + *inner_locked = Some((token, Arc::downgrade(poll::selector(poll).port()))); + + Ok(()) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + _events: Ready, + _opts: PollOpt) -> io::Result<()> + { + let mut inner_locked = self.inner.lock().unwrap(); + *inner_locked = Some((token, Arc::downgrade(poll::selector(poll).port()))); + + Ok(()) + } + + fn deregister(&self, _poll: &Poll) -> io::Result<()> + { + let mut inner_locked = self.inner.lock().unwrap(); + *inner_locked = None; + + Ok(()) + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/eventedfd.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/eventedfd.rs new file mode 100644 index 0000000..e23d0c4 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/eventedfd.rs @@ -0,0 +1,263 @@ +use {io, poll, Evented, Ready, Poll, PollOpt, Token}; +use libc; +use zircon; +use zircon::AsHandleRef; +use sys::fuchsia::{DontDrop, poll_opts_to_wait_async, sys}; +use std::mem; +use std::os::unix::io::RawFd; +use std::sync::{Arc, Mutex}; + +/// Properties of an `EventedFd`'s current registration +#[derive(Debug)] +pub struct EventedFdRegistration { + token: Token, + handle: DontDrop, + rereg_signals: Option<(zircon::Signals, zircon::WaitAsyncOpts)>, +} + +impl EventedFdRegistration { + unsafe fn new(token: Token, + raw_handle: sys::zx_handle_t, + rereg_signals: Option<(zircon::Signals, zircon::WaitAsyncOpts)>, + ) -> Self + { + EventedFdRegistration { + token: token, + handle: DontDrop::new(zircon::Handle::from_raw(raw_handle)), + rereg_signals: rereg_signals + } + } + + pub fn rereg_signals(&self) -> Option<(zircon::Signals, zircon::WaitAsyncOpts)> { + self.rereg_signals + } +} + +/// An event-ed file descriptor. The file descriptor is owned by this structure. +#[derive(Debug)] +pub struct EventedFdInner { + /// Properties of the current registration. + registration: Mutex>, + + /// Owned file descriptor. + /// + /// `fd` is closed on `Drop`, so modifying `fd` is a memory-unsafe operation. + fd: RawFd, + + /// Owned `fdio_t` pointer. + fdio: *const sys::fdio_t, +} + +impl EventedFdInner { + pub fn rereg_for_level(&self, port: &zircon::Port) { + let registration_opt = self.registration.lock().unwrap(); + if let Some(ref registration) = *registration_opt { + if let Some((rereg_signals, rereg_opts)) = registration.rereg_signals { + let _res = + registration + .handle.inner_ref() + .wait_async_handle( + port, + registration.token.0 as u64, + rereg_signals, + rereg_opts); + } + } + } + + pub fn registration(&self) -> &Mutex> { + &self.registration + } + + pub fn fdio(&self) -> &sys::fdio_t { + unsafe { &*self.fdio } + } +} + +impl Drop for EventedFdInner { + fn drop(&mut self) { + unsafe { + sys::__fdio_release(self.fdio); + let _ = libc::close(self.fd); + } + } +} + +// `EventedInner` must be manually declared `Send + Sync` because it contains a `RawFd` and a +// `*const sys::fdio_t`. These are only used to make thread-safe system calls, so accessing +// them is entirely thread-safe. +// +// Note: one minor exception to this are the calls to `libc::close` and `__fdio_release`, which +// happen on `Drop`. These accesses are safe because `drop` can only be called at most once from +// a single thread, and after it is called no other functions can be called on the `EventedFdInner`. +unsafe impl Sync for EventedFdInner {} +unsafe impl Send for EventedFdInner {} + +#[derive(Clone, Debug)] +pub struct EventedFd { + pub inner: Arc +} + +impl EventedFd { + pub unsafe fn new(fd: RawFd) -> Self { + let fdio = sys::__fdio_fd_to_io(fd); + assert!(fdio != ::std::ptr::null(), "FileDescriptor given to EventedFd must be valid."); + + EventedFd { + inner: Arc::new(EventedFdInner { + registration: Mutex::new(None), + fd: fd, + fdio: fdio, + }) + } + } + + fn handle_and_signals_for_events(&self, interest: Ready, opts: PollOpt) + -> (sys::zx_handle_t, zircon::Signals) + { + let epoll_events = ioevent_to_epoll(interest, opts); + + unsafe { + let mut raw_handle: sys::zx_handle_t = mem::uninitialized(); + let mut signals: sys::zx_signals_t = mem::uninitialized(); + sys::__fdio_wait_begin(self.inner.fdio, epoll_events, &mut raw_handle, &mut signals); + + (raw_handle, signals) + } + } + + fn register_with_lock( + &self, + registration: &mut Option, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + if registration.is_some() { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "Called register on an already registered file descriptor.")); + } + + let (raw_handle, signals) = self.handle_and_signals_for_events(interest, opts); + + let needs_rereg = opts.is_level() && !opts.is_oneshot(); + + // If we need to reregister, then each registration should be `oneshot` + let opts = opts | if needs_rereg { PollOpt::oneshot() } else { PollOpt::empty() }; + + let rereg_signals = if needs_rereg { + Some((signals, poll_opts_to_wait_async(opts))) + } else { + None + }; + + *registration = Some( + unsafe { EventedFdRegistration::new(token, raw_handle, rereg_signals) } + ); + + // We don't have ownership of the handle, so we can't drop it + let handle = DontDrop::new(unsafe { zircon::Handle::from_raw(raw_handle) }); + + let registered = poll::selector(poll) + .register_fd(handle.inner_ref(), self, token, signals, opts); + + if registered.is_err() { + *registration = None; + } + + registered + } + + fn deregister_with_lock( + &self, + registration: &mut Option, + poll: &Poll) -> io::Result<()> + { + let old_registration = if let Some(old_reg) = registration.take() { + old_reg + } else { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "Called rereregister on an unregistered file descriptor.")) + }; + + poll::selector(poll) + .deregister_fd(old_registration.handle.inner_ref(), old_registration.token) + } +} + +impl Evented for EventedFd { + fn register(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.register_with_lock( + &mut *self.inner.registration.lock().unwrap(), + poll, + token, + interest, + opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + // Take out the registration lock + let mut registration_lock = self.inner.registration.lock().unwrap(); + + // Deregister + self.deregister_with_lock(&mut *registration_lock, poll)?; + + self.register_with_lock( + &mut *registration_lock, + poll, + token, + interest, + opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + let mut registration_lock = self.inner.registration.lock().unwrap(); + self.deregister_with_lock(&mut *registration_lock, poll) + } +} + +fn ioevent_to_epoll(interest: Ready, opts: PollOpt) -> u32 { + use event_imp::ready_from_usize; + const HUP: usize = 0b01000; + + let mut kind = 0; + + if interest.is_readable() { + kind |= libc::EPOLLIN; + } + + if interest.is_writable() { + kind |= libc::EPOLLOUT; + } + + if interest.contains(ready_from_usize(HUP)) { + kind |= libc::EPOLLRDHUP; + } + + if opts.is_edge() { + kind |= libc::EPOLLET; + } + + if opts.is_oneshot() { + kind |= libc::EPOLLONESHOT; + } + + if opts.is_level() { + kind &= !libc::EPOLLET; + } + + kind as u32 +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/handles.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/handles.rs new file mode 100644 index 0000000..ae6f07f --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/handles.rs @@ -0,0 +1,78 @@ +use {io, poll, Evented, Ready, Poll, PollOpt, Token}; +use zircon_sys::zx_handle_t; +use std::sync::Mutex; + +/// Wrapper for registering a `HandleBase` type with mio. +#[derive(Debug)] +pub struct EventedHandle { + /// The handle to be registered. + handle: zx_handle_t, + + /// The current `Token` with which the handle is registered with mio. + token: Mutex>, +} + +impl EventedHandle { + /// Create a new `EventedHandle` which can be registered with mio + /// in order to receive event notifications. + /// + /// The underlying handle must not be dropped while the + /// `EventedHandle` still exists. + pub unsafe fn new(handle: zx_handle_t) -> Self { + EventedHandle { + handle: handle, + token: Mutex::new(None), + } + } + + /// Get the underlying handle being registered. + pub fn get_handle(&self) -> zx_handle_t { + self.handle + } +} + +impl Evented for EventedHandle { + fn register(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + let mut this_token = self.token.lock().unwrap(); + { + poll::selector(poll).register_handle(self.handle, token, interest, opts)?; + *this_token = Some(token); + } + Ok(()) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + let mut this_token = self.token.lock().unwrap(); + { + poll::selector(poll).deregister_handle(self.handle, token)?; + *this_token = None; + poll::selector(poll).register_handle(self.handle, token, interest, opts)?; + *this_token = Some(token); + } + Ok(()) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + let mut this_token = self.token.lock().unwrap(); + let token = if let Some(token) = *this_token { token } else { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "Attempted to deregister an unregistered handle.")) + }; + { + poll::selector(poll).deregister_handle(self.handle, token)?; + *this_token = None; + } + Ok(()) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/mod.rs new file mode 100644 index 0000000..10728fc --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/mod.rs @@ -0,0 +1,177 @@ +use {io, Ready, PollOpt}; +use libc; +use zircon; +use std::mem; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::ops::{Deref, DerefMut}; +use std::os::unix::io::RawFd; + +mod awakener; +mod handles; +mod eventedfd; +mod net; +mod ready; +mod selector; + +use self::eventedfd::{EventedFd, EventedFdInner}; +use self::ready::assert_fuchsia_ready_repr; + +pub use self::awakener::Awakener; +pub use self::handles::EventedHandle; +pub use self::net::{TcpListener, TcpStream, UdpSocket}; +pub use self::selector::{Events, Selector}; +pub use self::ready::{FuchsiaReady, zx_signals_t}; + +// Set non-blocking (workaround since the std version doesn't work in fuchsia) +// TODO: fix the std version and replace this +pub fn set_nonblock(fd: RawFd) -> io::Result<()> { + cvt(unsafe { libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK) }).map(|_| ()) +} + +/// Workaround until fuchsia's recv_from is fixed +unsafe fn recv_from(fd: RawFd, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + let flags = 0; + + let n = cvt( + libc::recv(fd, + buf.as_mut_ptr() as *mut libc::c_void, + buf.len(), + flags) + )?; + + // random address-- we don't use it + let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080); + Ok((n as usize, addr)) +} + +mod sys { + #![allow(non_camel_case_types)] + use std::os::unix::io::RawFd; + pub use zircon_sys::{zx_handle_t, zx_signals_t}; + + // 17 fn pointers we don't need for mio :) + pub type fdio_ops_t = [usize; 17]; + + pub type atomic_int_fast32_t = usize; // TODO: https://github.com/rust-lang/libc/issues/631 + + #[repr(C)] + pub struct fdio_t { + pub ops: *const fdio_ops_t, + pub magic: u32, + pub refcount: atomic_int_fast32_t, + pub dupcount: u32, + pub flags: u32, + } + + #[link(name="fdio")] + extern { + pub fn __fdio_fd_to_io(fd: RawFd) -> *const fdio_t; + pub fn __fdio_release(io: *const fdio_t); + + pub fn __fdio_wait_begin( + io: *const fdio_t, + events: u32, + handle_out: &mut zx_handle_t, + signals_out: &mut zx_signals_t, + ); + pub fn __fdio_wait_end( + io: *const fdio_t, + signals: zx_signals_t, + events_out: &mut u32, + ); + } +} + +fn epoll_event_to_ready(epoll: u32) -> Ready { + let epoll = epoll as i32; // casts the bits directly + let mut kind = Ready::empty(); + + if (epoll & libc::EPOLLIN) != 0 || (epoll & libc::EPOLLPRI) != 0 { + kind = kind | Ready::readable(); + } + + if (epoll & libc::EPOLLOUT) != 0 { + kind = kind | Ready::writable(); + } + + kind + + /* TODO: support? + // EPOLLHUP - Usually means a socket error happened + if (epoll & libc::EPOLLERR) != 0 { + kind = kind | UnixReady::error(); + } + + if (epoll & libc::EPOLLRDHUP) != 0 || (epoll & libc::EPOLLHUP) != 0 { + kind = kind | UnixReady::hup(); + } + */ +} + +fn poll_opts_to_wait_async(poll_opts: PollOpt) -> zircon::WaitAsyncOpts { + if poll_opts.is_oneshot() { + zircon::WaitAsyncOpts::Once + } else { + zircon::WaitAsyncOpts::Repeating + } +} + +trait IsMinusOne { + fn is_minus_one(&self) -> bool; +} + +impl IsMinusOne for i32 { + fn is_minus_one(&self) -> bool { *self == -1 } +} + +impl IsMinusOne for isize { + fn is_minus_one(&self) -> bool { *self == -1 } +} + +fn cvt(t: T) -> ::io::Result { + use std::io; + + if t.is_minus_one() { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +/// Utility type to prevent the type inside of it from being dropped. +#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +struct DontDrop(Option); + +impl DontDrop { + fn new(t: T) -> DontDrop { + DontDrop(Some(t)) + } + + fn inner_ref(&self) -> &T { + self.0.as_ref().unwrap() + } + + fn inner_mut(&mut self) -> &mut T { + self.0.as_mut().unwrap() + } +} + +impl Deref for DontDrop { + type Target = T; + fn deref(&self) -> &Self::Target { + self.inner_ref() + } +} + +impl DerefMut for DontDrop { + fn deref_mut(&mut self) -> &mut Self::Target { + self.inner_mut() + } +} + +impl Drop for DontDrop { + fn drop(&mut self) { + let inner = self.0.take(); + mem::forget(inner); + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/net.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/net.rs new file mode 100644 index 0000000..d43ad27 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/net.rs @@ -0,0 +1,444 @@ +use {io, Evented, Ready, Poll, PollOpt, Token}; +use iovec::IoVec; +use iovec::unix as iovec; +use libc; +use net2::TcpStreamExt; +#[allow(unused_imports)] // only here for Rust 1.8 +use net2::UdpSocketExt; +use sys::fuchsia::{recv_from, set_nonblock, EventedFd, DontDrop}; +use std::cmp; +use std::io::{Read, Write}; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::os::unix::io::AsRawFd; +use std::time::Duration; + +#[derive(Debug)] +pub struct TcpStream { + io: DontDrop, + evented_fd: EventedFd, +} + +impl TcpStream { + pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result { + try!(set_nonblock(stream.as_raw_fd())); + + let connected = stream.connect(addr); + match connected { + Ok(..) => {} + Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} + Err(e) => return Err(e), + } + + let evented_fd = unsafe { EventedFd::new(stream.as_raw_fd()) }; + + return Ok(TcpStream { + io: DontDrop::new(stream), + evented_fd: evented_fd, + }) + } + + pub fn from_stream(stream: net::TcpStream) -> TcpStream { + let evented_fd = unsafe { EventedFd::new(stream.as_raw_fd()) }; + + TcpStream { + io: DontDrop::new(stream), + evented_fd: evented_fd, + } + } + + pub fn peer_addr(&self) -> io::Result { + self.io.peer_addr() + } + + pub fn local_addr(&self) -> io::Result { + self.io.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.io.try_clone().map(|s| { + let evented_fd = unsafe { EventedFd::new(s.as_raw_fd()) }; + TcpStream { + io: DontDrop::new(s), + evented_fd: evented_fd, + } + }) + } + + pub fn shutdown(&self, how: net::Shutdown) -> io::Result<()> { + self.io.shutdown(how) + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + self.io.set_nodelay(nodelay) + } + + pub fn nodelay(&self) -> io::Result { + self.io.nodelay() + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + self.io.set_recv_buffer_size(size) + } + + pub fn recv_buffer_size(&self) -> io::Result { + self.io.recv_buffer_size() + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + self.io.set_send_buffer_size(size) + } + + pub fn send_buffer_size(&self) -> io::Result { + self.io.send_buffer_size() + } + + pub fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { + self.io.set_keepalive(keepalive) + } + + pub fn keepalive(&self) -> io::Result> { + self.io.keepalive() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.io.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.io.ttl() + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.io.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.io.only_v6() + } + + pub fn set_linger(&self, dur: Option) -> io::Result<()> { + self.io.set_linger(dur) + } + + pub fn linger(&self) -> io::Result> { + self.io.linger() + } + + pub fn take_error(&self) -> io::Result> { + self.io.take_error() + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.io.peek(buf) + } + + pub fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result { + unsafe { + let slice = iovec::as_os_slice_mut(bufs); + let len = cmp::min(::max_value() as usize, slice.len()); + let rc = libc::readv(self.io.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } + + pub fn writev(&self, bufs: &[&IoVec]) -> io::Result { + unsafe { + let slice = iovec::as_os_slice(bufs); + let len = cmp::min(::max_value() as usize, slice.len()); + let rc = libc::writev(self.io.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } +} + +impl<'a> Read for &'a TcpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.io.inner_ref().read(buf) + } +} + +impl<'a> Write for &'a TcpStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.io.inner_ref().write(buf) + } + fn flush(&mut self) -> io::Result<()> { + self.io.inner_ref().flush() + } +} + +impl Evented for TcpStream { + fn register(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.register(poll, token, interest, opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.evented_fd.deregister(poll) + } +} + +#[derive(Debug)] +pub struct TcpListener { + io: DontDrop, + evented_fd: EventedFd, +} + +impl TcpListener { + pub fn new(inner: net::TcpListener) -> io::Result { + set_nonblock(inner.as_raw_fd())?; + + let evented_fd = unsafe { EventedFd::new(inner.as_raw_fd()) }; + + Ok(TcpListener { + io: DontDrop::new(inner), + evented_fd: evented_fd, + }) + } + + pub fn local_addr(&self) -> io::Result { + self.io.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.io.try_clone().map(|io| { + let evented_fd = unsafe { EventedFd::new(io.as_raw_fd()) }; + TcpListener { + io: DontDrop::new(io), + evented_fd: evented_fd, + } + }) + } + + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + self.io.accept().and_then(|(s, a)| { + set_nonblock(s.as_raw_fd())?; + let evented_fd = unsafe { EventedFd::new(s.as_raw_fd()) }; + return Ok((TcpStream { + io: DontDrop::new(s), + evented_fd: evented_fd, + }, a)) + }) + } + + #[allow(deprecated)] + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.io.set_only_v6(only_v6) + } + + #[allow(deprecated)] + pub fn only_v6(&self) -> io::Result { + self.io.only_v6() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.io.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.io.ttl() + } + + pub fn take_error(&self) -> io::Result> { + self.io.take_error() + } +} + +impl Evented for TcpListener { + fn register(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.register(poll, token, interest, opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.evented_fd.deregister(poll) + } +} + +#[derive(Debug)] +pub struct UdpSocket { + io: DontDrop, + evented_fd: EventedFd, +} + +impl UdpSocket { + pub fn new(socket: net::UdpSocket) -> io::Result { + set_nonblock(socket.as_raw_fd())?; + + let evented_fd = unsafe { EventedFd::new(socket.as_raw_fd()) }; + + Ok(UdpSocket { + io: DontDrop::new(socket), + evented_fd: evented_fd, + }) + } + + pub fn local_addr(&self) -> io::Result { + self.io.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.io.try_clone().and_then(|io| { + UdpSocket::new(io) + }) + } + + pub fn send_to(&self, buf: &[u8], target: &SocketAddr) -> io::Result { + self.io.send_to(buf, target) + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + unsafe { recv_from(self.io.as_raw_fd(), buf) } + } + + pub fn send(&self, buf: &[u8]) -> io::Result { + self.io.send(buf) + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result { + self.io.recv(buf) + } + + pub fn connect(&self, addr: SocketAddr) + -> io::Result<()> { + self.io.connect(addr) + } + + pub fn broadcast(&self) -> io::Result { + self.io.broadcast() + } + + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { + self.io.set_broadcast(on) + } + + pub fn multicast_loop_v4(&self) -> io::Result { + self.io.multicast_loop_v4() + } + + pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> { + self.io.set_multicast_loop_v4(on) + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + self.io.multicast_ttl_v4() + } + + pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> { + self.io.set_multicast_ttl_v4(ttl) + } + + pub fn multicast_loop_v6(&self) -> io::Result { + self.io.multicast_loop_v6() + } + + pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> { + self.io.set_multicast_loop_v6(on) + } + + pub fn ttl(&self) -> io::Result { + self.io.ttl() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.io.set_ttl(ttl) + } + + pub fn join_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.io.join_multicast_v4(multiaddr, interface) + } + + pub fn join_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.io.join_multicast_v6(multiaddr, interface) + } + + pub fn leave_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.io.leave_multicast_v4(multiaddr, interface) + } + + pub fn leave_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.io.leave_multicast_v6(multiaddr, interface) + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.io.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.io.only_v6() + } + + + pub fn take_error(&self) -> io::Result> { + self.io.take_error() + } +} + +impl Evented for UdpSocket { + fn register(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.register(poll, token, interest, opts) + } + + fn reregister(&self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt) -> io::Result<()> + { + self.evented_fd.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.evented_fd.deregister(poll) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/ready.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/ready.rs new file mode 100644 index 0000000..97854f8 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/ready.rs @@ -0,0 +1,181 @@ +use event_imp::{Ready, ready_as_usize, ready_from_usize}; +pub use zircon_sys::{ + zx_signals_t, + ZX_OBJECT_READABLE, + ZX_OBJECT_WRITABLE, +}; +use std::ops; + +// The following impls are valid because Fuchsia and mio both represent +// "readable" as `1 << 0` and "writable" as `1 << 2`. +// We define this assertion here and call it from `Selector::new`, +// since `Selector:;new` is guaranteed to be called during a standard mio runtime, +// unlike the functions in this file. +#[inline] +pub fn assert_fuchsia_ready_repr() { + debug_assert!( + ZX_OBJECT_READABLE.bits() as usize == ready_as_usize(Ready::readable()), + "Zircon ZX_OBJECT_READABLE should have the same repr as Ready::readable()" + ); + debug_assert!( + ZX_OBJECT_WRITABLE.bits() as usize == ready_as_usize(Ready::writable()), + "Zircon ZX_OBJECT_WRITABLE should have the same repr as Ready::writable()" + ); +} + +/// Fuchsia specific extensions to `Ready` +/// +/// Provides additional readiness event kinds that are available on Fuchsia. +/// +/// Conversion traits are implemented between `Ready` and `FuchsiaReady`. +/// +/// For high level documentation on polling and readiness, see [`Poll`]. +/// +/// [`Poll`]: struct.Poll.html +#[derive(Debug, Copy, PartialEq, Eq, Clone, PartialOrd, Ord)] +pub struct FuchsiaReady(Ready); + +impl FuchsiaReady { + /// Returns the `FuchsiaReady` as raw zircon signals. + /// This function is just a more explicit, non-generic version of + /// `FuchsiaReady::into`. + #[inline] + pub fn into_zx_signals(self) -> zx_signals_t { + zx_signals_t::from_bits_truncate(ready_as_usize(self.0) as u32) + } +} + +impl Into for FuchsiaReady { + #[inline] + fn into(self) -> zx_signals_t { + self.into_zx_signals() + } +} + +impl From for FuchsiaReady { + #[inline] + fn from(src: zx_signals_t) -> Self { + FuchsiaReady(src.into()) + } +} + +impl From for Ready { + #[inline] + fn from(src: zx_signals_t) -> Self { + ready_from_usize(src.bits() as usize) + } +} + +impl From for FuchsiaReady { + #[inline] + fn from(src: Ready) -> FuchsiaReady { + FuchsiaReady(src) + } +} + +impl From for Ready { + #[inline] + fn from(src: FuchsiaReady) -> Ready { + src.0 + } +} + +impl ops::Deref for FuchsiaReady { + type Target = Ready; + + #[inline] + fn deref(&self) -> &Ready { + &self.0 + } +} + +impl ops::DerefMut for FuchsiaReady { + #[inline] + fn deref_mut(&mut self) -> &mut Ready { + &mut self.0 + } +} + +impl ops::BitOr for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitor(self, other: FuchsiaReady) -> FuchsiaReady { + (self.0 | other.0).into() + } +} + +impl ops::BitXor for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitxor(self, other: FuchsiaReady) -> FuchsiaReady { + (self.0 ^ other.0).into() + } +} + +impl ops::BitAnd for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitand(self, other: FuchsiaReady) -> FuchsiaReady { + (self.0 & other.0).into() + } +} + +impl ops::Sub for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn sub(self, other: FuchsiaReady) -> FuchsiaReady { + (self.0 & !other.0).into() + } +} + +#[deprecated(since = "0.6.10", note = "removed")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +impl ops::Not for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn not(self) -> FuchsiaReady { + (!self.0).into() + } +} + +impl ops::BitOr for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitor(self, other: zx_signals_t) -> FuchsiaReady { + self | FuchsiaReady::from(other) + } +} + +impl ops::BitXor for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitxor(self, other: zx_signals_t) -> FuchsiaReady { + self ^ FuchsiaReady::from(other) + } +} + +impl ops::BitAnd for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn bitand(self, other: zx_signals_t) -> FuchsiaReady { + self & FuchsiaReady::from(other) + } +} + +impl ops::Sub for FuchsiaReady { + type Output = FuchsiaReady; + + #[inline] + fn sub(self, other: zx_signals_t) -> FuchsiaReady { + self - FuchsiaReady::from(other) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/selector.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/selector.rs new file mode 100644 index 0000000..27226ac --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/fuchsia/selector.rs @@ -0,0 +1,353 @@ +use {io, Event, PollOpt, Ready, Token}; +use sys::fuchsia::{ + assert_fuchsia_ready_repr, + epoll_event_to_ready, + poll_opts_to_wait_async, + EventedFd, + EventedFdInner, + FuchsiaReady, +}; +use zircon; +use zircon::AsHandleRef; +use zircon_sys::zx_handle_t; +use std::collections::hash_map; +use std::fmt; +use std::mem; +use std::sync::atomic::{AtomicBool, AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; +use std::sync::{Arc, Mutex, Weak}; +use std::time::Duration; +use sys; + +/// The kind of registration-- file descriptor or handle. +/// +/// The last bit of a token is set to indicate the type of the registration. +#[derive(Copy, Clone, Eq, PartialEq)] +enum RegType { + Fd, + Handle, +} + +fn key_from_token_and_type(token: Token, reg_type: RegType) -> io::Result { + let key = token.0 as u64; + let msb = 1u64 << 63; + if (key & msb) != 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Most-significant bit of token must remain unset.")); + } + + Ok(match reg_type { + RegType::Fd => key, + RegType::Handle => key | msb, + }) +} + +fn token_and_type_from_key(key: u64) -> (Token, RegType) { + let msb = 1u64 << 63; + ( + Token((key & !msb) as usize), + if (key & msb) == 0 { + RegType::Fd + } else { + RegType::Handle + } + ) +} + +/// Each Selector has a globally unique(ish) ID associated with it. This ID +/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first +/// registered with the `Selector`. If a type that is previously associated with +/// a `Selector` attempts to register itself with a different `Selector`, the +/// operation will return with an error. This matches windows behavior. +static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; + +pub struct Selector { + id: usize, + + /// Zircon object on which the handles have been registered, and on which events occur + port: Arc, + + /// Whether or not `tokens_to_rereg` contains any elements. This is a best-effort attempt + /// used to prevent having to lock `tokens_to_rereg` when it is empty. + has_tokens_to_rereg: AtomicBool, + + /// List of `Token`s corresponding to registrations that need to be reregistered before the + /// next `port::wait`. This is necessary to provide level-triggered behavior for + /// `Async::repeating` registrations. + /// + /// When a level-triggered `Async::repeating` event is seen, its token is added to this list so + /// that it will be reregistered before the next `port::wait` call, making `port::wait` return + /// immediately if the signal was high during the reregistration. + /// + /// Note: when used at the same time, the `tokens_to_rereg` lock should be taken out _before_ + /// `token_to_fd`. + tokens_to_rereg: Mutex>, + + /// Map from tokens to weak references to `EventedFdInner`-- a structure describing a + /// file handle, its associated `fdio` object, and its current registration. + token_to_fd: Mutex>>, +} + +impl Selector { + pub fn new() -> io::Result { + // Assertion from fuchsia/ready.rs to make sure that FuchsiaReady's representation is + // compatible with Ready. + assert_fuchsia_ready_repr(); + + let port = Arc::new( + zircon::Port::create(zircon::PortOpts::Default)? + ); + + // offset by 1 to avoid choosing 0 as the id of a selector + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; + + let has_tokens_to_rereg = AtomicBool::new(false); + let tokens_to_rereg = Mutex::new(Vec::new()); + let token_to_fd = Mutex::new(hash_map::HashMap::new()); + + Ok(Selector { + id: id, + port: port, + has_tokens_to_rereg: has_tokens_to_rereg, + tokens_to_rereg: tokens_to_rereg, + token_to_fd: token_to_fd, + }) + } + + pub fn id(&self) -> usize { + self.id + } + + /// Returns a reference to the underlying port `Arc`. + pub fn port(&self) -> &Arc { &self.port } + + /// Reregisters all registrations pointed to by the `tokens_to_rereg` list + /// if `has_tokens_to_rereg`. + fn reregister_handles(&self) -> io::Result<()> { + // We use `Ordering::Acquire` to make sure that we see all `tokens_to_rereg` + // written before the store using `Ordering::Release`. + if self.has_tokens_to_rereg.load(Ordering::Acquire) { + let mut tokens = self.tokens_to_rereg.lock().unwrap(); + let token_to_fd = self.token_to_fd.lock().unwrap(); + for token in tokens.drain(0..) { + if let Some(eventedfd) = token_to_fd.get(&token) + .and_then(|h| h.upgrade()) { + eventedfd.rereg_for_level(&self.port); + } + } + self.has_tokens_to_rereg.store(false, Ordering::Release); + } + Ok(()) + } + + pub fn select(&self, + evts: &mut Events, + _awakener: Token, + timeout: Option) -> io::Result + { + evts.clear(); + + self.reregister_handles()?; + + let deadline = match timeout { + Some(duration) => { + let nanos = duration.as_secs().saturating_mul(1_000_000_000) + .saturating_add(duration.subsec_nanos() as u64); + + zircon::deadline_after(nanos) + } + None => zircon::ZX_TIME_INFINITE, + }; + + let packet = match self.port.wait(deadline) { + Ok(packet) => packet, + Err(zircon::Status::ErrTimedOut) => return Ok(false), + Err(e) => Err(e)?, + }; + + let observed_signals = match packet.contents() { + zircon::PacketContents::SignalOne(signal_packet) => { + signal_packet.observed() + } + zircon::PacketContents::SignalRep(signal_packet) => { + signal_packet.observed() + } + zircon::PacketContents::User(_user_packet) => { + // User packets are only ever sent by an Awakener + return Ok(true); + } + }; + + let key = packet.key(); + let (token, reg_type) = token_and_type_from_key(key); + + match reg_type { + RegType::Handle => { + // We can return immediately-- no lookup or registration necessary. + evts.events.push(Event::new(Ready::from(observed_signals), token)); + Ok(false) + }, + RegType::Fd => { + // Convert the signals to epoll events using __fdio_wait_end, + // and add to reregistration list if necessary. + let events: u32; + { + let handle = if let Some(handle) = + self.token_to_fd.lock().unwrap() + .get(&token) + .and_then(|h| h.upgrade()) { + handle + } else { + // This handle is apparently in the process of removal. + // It has been removed from the list, but port_cancel has not been called. + return Ok(false); + }; + + events = unsafe { + let mut events: u32 = mem::uninitialized(); + sys::fuchsia::sys::__fdio_wait_end(handle.fdio(), observed_signals, &mut events); + events + }; + + // If necessary, queue to be reregistered before next port_await + let needs_to_rereg = { + let registration_lock = handle.registration().lock().unwrap(); + + registration_lock + .as_ref() + .and_then(|r| r.rereg_signals()) + .is_some() + }; + + if needs_to_rereg { + let mut tokens_to_rereg_lock = self.tokens_to_rereg.lock().unwrap(); + tokens_to_rereg_lock.push(token); + // We use `Ordering::Release` to make sure that we see all `tokens_to_rereg` + // written before the store. + self.has_tokens_to_rereg.store(true, Ordering::Release); + } + } + + evts.events.push(Event::new(epoll_event_to_ready(events), token)); + Ok(false) + }, + } + } + + /// Register event interests for the given IO handle with the OS + pub fn register_fd(&self, + handle: &zircon::Handle, + fd: &EventedFd, + token: Token, + signals: zircon::Signals, + poll_opts: PollOpt) -> io::Result<()> + { + { + let mut token_to_fd = self.token_to_fd.lock().unwrap(); + match token_to_fd.entry(token) { + hash_map::Entry::Occupied(_) => + return Err(io::Error::new(io::ErrorKind::AlreadyExists, + "Attempted to register a filedescriptor on an existing token.")), + hash_map::Entry::Vacant(slot) => slot.insert(Arc::downgrade(&fd.inner)), + }; + } + + let wait_async_opts = poll_opts_to_wait_async(poll_opts); + + let wait_res = handle.wait_async_handle(&self.port, token.0 as u64, signals, wait_async_opts); + + if wait_res.is_err() { + self.token_to_fd.lock().unwrap().remove(&token); + } + + Ok(wait_res?) + } + + /// Deregister event interests for the given IO handle with the OS + pub fn deregister_fd(&self, handle: &zircon::Handle, token: Token) -> io::Result<()> { + self.token_to_fd.lock().unwrap().remove(&token); + + // We ignore NotFound errors since oneshots are automatically deregistered, + // but mio will attempt to deregister them manually. + self.port.cancel(&*handle, token.0 as u64) + .map_err(io::Error::from) + .or_else(|e| if e.kind() == io::ErrorKind::NotFound { + Ok(()) + } else { + Err(e) + }) + } + + pub fn register_handle(&self, + handle: zx_handle_t, + token: Token, + interests: Ready, + poll_opts: PollOpt) -> io::Result<()> + { + if poll_opts.is_level() && !poll_opts.is_oneshot() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "Repeated level-triggered events are not supported on Fuchsia handles.")); + } + + let temp_handle = unsafe { zircon::Handle::from_raw(handle) }; + + let res = temp_handle.wait_async_handle( + &self.port, + key_from_token_and_type(token, RegType::Handle)?, + FuchsiaReady::from(interests).into_zx_signals(), + poll_opts_to_wait_async(poll_opts)); + + mem::forget(temp_handle); + + Ok(res?) + } + + + pub fn deregister_handle(&self, handle: zx_handle_t, token: Token) -> io::Result<()> + { + let temp_handle = unsafe { zircon::Handle::from_raw(handle) }; + let res = self.port.cancel(&temp_handle, key_from_token_and_type(token, RegType::Handle)?); + + mem::forget(temp_handle); + + Ok(res?) + } +} + +pub struct Events { + events: Vec +} + +impl Events { + pub fn with_capacity(_u: usize) -> Events { + // The Fuchsia selector only handles one event at a time, + // so we ignore the default capacity and set it to one. + Events { events: Vec::with_capacity(1) } + } + pub fn len(&self) -> usize { + self.events.len() + } + pub fn capacity(&self) -> usize { + self.events.capacity() + } + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + pub fn get(&self, idx: usize) -> Option { + self.events.get(idx).map(|e| *e) + } + pub fn push_event(&mut self, event: Event) { + self.events.push(event) + } + pub fn clear(&mut self) { + self.events.events.drain(0..); + } +} + +impl fmt::Debug for Events { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Events") + .field("len", &self.len()) + .finish() + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/mod.rs new file mode 100644 index 0000000..8a1705d --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/mod.rs @@ -0,0 +1,56 @@ +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub use self::unix::{ + Awakener, + EventedFd, + Events, + Io, + Selector, + TcpStream, + TcpListener, + UdpSocket, + pipe, + set_nonblock, +}; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub use self::unix::READY_ALL; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +#[cfg(feature = "with-deprecated")] +pub use self::unix::UnixSocket; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +pub mod unix; + +#[cfg(windows)] +pub use self::windows::{ + Awakener, + Events, + Selector, + TcpStream, + TcpListener, + UdpSocket, + Overlapped, + Binding, +}; + +#[cfg(windows)] +mod windows; + +#[cfg(target_os = "fuchsia")] +pub use self::fuchsia::{ + Awakener, + Events, + EventedHandle, + Selector, + TcpStream, + TcpListener, + UdpSocket, + set_nonblock, +}; + +#[cfg(target_os = "fuchsia")] +pub mod fuchsia; + +#[cfg(not(all(unix, not(target_os = "fuchsia"))))] +pub const READY_ALL: usize = 0; diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/awakener.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/awakener.rs new file mode 100644 index 0000000..9cc367a --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/awakener.rs @@ -0,0 +1,74 @@ +pub use self::pipe::Awakener; + +/// Default awakener backed by a pipe +mod pipe { + use sys::unix; + use {io, Ready, Poll, PollOpt, Token}; + use event::Evented; + use std::io::{Read, Write}; + + /* + * + * ===== Awakener ===== + * + */ + + pub struct Awakener { + reader: unix::Io, + writer: unix::Io, + } + + impl Awakener { + pub fn new() -> io::Result { + let (rd, wr) = unix::pipe()?; + + Ok(Awakener { + reader: rd, + writer: wr, + }) + } + + pub fn wakeup(&self) -> io::Result<()> { + match (&self.writer).write(&[1]) { + Ok(_) => Ok(()), + Err(e) => { + if e.kind() == io::ErrorKind::WouldBlock { + Ok(()) + } else { + Err(e) + } + } + } + } + + pub fn cleanup(&self) { + let mut buf = [0; 128]; + + loop { + // Consume data until all bytes are purged + match (&self.reader).read(&mut buf) { + Ok(i) if i > 0 => {}, + _ => return, + } + } + } + + fn reader(&self) -> &unix::Io { + &self.reader + } + } + + impl Evented for Awakener { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.reader().register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.reader().reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.reader().deregister(poll) + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/dlsym.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/dlsym.rs new file mode 100644 index 0000000..e88c595 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/dlsym.rs @@ -0,0 +1,47 @@ +use std::marker; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use libc; + +macro_rules! dlsym { + (fn $name:ident($($t:ty),*) -> $ret:ty) => ( + #[allow(bad_style)] + static $name: ::sys::unix::dlsym::DlSym $ret> = + ::sys::unix::dlsym::DlSym { + name: concat!(stringify!($name), "\0"), + addr: ::std::sync::atomic::ATOMIC_USIZE_INIT, + _marker: ::std::marker::PhantomData, + }; + ) +} + +pub struct DlSym { + pub name: &'static str, + pub addr: AtomicUsize, + pub _marker: marker::PhantomData, +} + +impl DlSym { + pub fn get(&self) -> Option<&F> { + assert_eq!(mem::size_of::(), mem::size_of::()); + unsafe { + if self.addr.load(Ordering::SeqCst) == 0 { + self.addr.store(fetch(self.name), Ordering::SeqCst); + } + if self.addr.load(Ordering::SeqCst) == 1 { + None + } else { + mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr) + } + } + } +} + +unsafe fn fetch(name: &str) -> usize { + assert_eq!(name.as_bytes()[name.len() - 1], 0); + match libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize { + 0 => 1, + n => n, + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/epoll.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/epoll.rs new file mode 100644 index 0000000..03b0ebd --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/epoll.rs @@ -0,0 +1,260 @@ +#![allow(deprecated)] +use std::os::unix::io::AsRawFd; +use std::os::unix::io::RawFd; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::time::Duration; +use std::{cmp, i32}; + +use libc::{self, c_int}; +use libc::{EPOLLERR, EPOLLHUP, EPOLLONESHOT}; +use libc::{EPOLLET, EPOLLOUT, EPOLLIN, EPOLLPRI}; + +use {io, Ready, PollOpt, Token}; +use event_imp::Event; +use sys::unix::{cvt, UnixReady}; +use sys::unix::io::set_cloexec; + +/// Each Selector has a globally unique(ish) ID associated with it. This ID +/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first +/// registered with the `Selector`. If a type that is previously associated with +/// a `Selector` attempts to register itself with a different `Selector`, the +/// operation will return with an error. This matches windows behavior. +static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; + +#[derive(Debug)] +pub struct Selector { + id: usize, + epfd: RawFd, +} + +impl Selector { + pub fn new() -> io::Result { + let epfd = unsafe { + // Emulate `epoll_create` by using `epoll_create1` if it's available + // and otherwise falling back to `epoll_create` followed by a call to + // set the CLOEXEC flag. + dlsym!(fn epoll_create1(c_int) -> c_int); + + match epoll_create1.get() { + Some(epoll_create1_fn) => { + cvt(epoll_create1_fn(libc::EPOLL_CLOEXEC))? + } + None => { + let fd = cvt(libc::epoll_create(1024))?; + drop(set_cloexec(fd)); + fd + } + } + }; + + // offset by 1 to avoid choosing 0 as the id of a selector + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; + + Ok(Selector { + id: id, + epfd: epfd, + }) + } + + pub fn id(&self) -> usize { + self.id + } + + /// Wait for events from the OS + pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option) -> io::Result { + let timeout_ms = timeout + .map(|to| cmp::min(millis(to), i32::MAX as u64) as i32) + .unwrap_or(-1); + + // Wait for epoll events for at most timeout_ms milliseconds + evts.clear(); + unsafe { + let cnt = cvt(libc::epoll_wait(self.epfd, + evts.events.as_mut_ptr(), + evts.events.capacity() as i32, + timeout_ms))?; + let cnt = cnt as usize; + evts.events.set_len(cnt); + + for i in 0..cnt { + if evts.events[i].u64 as usize == awakener.into() { + evts.events.remove(i); + return Ok(true); + } + } + } + + Ok(false) + } + + /// Register event interests for the given IO handle with the OS + pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { + let mut info = libc::epoll_event { + events: ioevent_to_epoll(interests, opts), + u64: usize::from(token) as u64 + }; + + unsafe { + cvt(libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_ADD, fd, &mut info))?; + Ok(()) + } + } + + /// Register event interests for the given IO handle with the OS + pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { + let mut info = libc::epoll_event { + events: ioevent_to_epoll(interests, opts), + u64: usize::from(token) as u64 + }; + + unsafe { + cvt(libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_MOD, fd, &mut info))?; + Ok(()) + } + } + + /// Deregister event interests for the given IO handle with the OS + pub fn deregister(&self, fd: RawFd) -> io::Result<()> { + // The &info argument should be ignored by the system, + // but linux < 2.6.9 required it to be not null. + // For compatibility, we provide a dummy EpollEvent. + let mut info = libc::epoll_event { + events: 0, + u64: 0, + }; + + unsafe { + cvt(libc::epoll_ctl(self.epfd, libc::EPOLL_CTL_DEL, fd, &mut info))?; + Ok(()) + } + } +} + +fn ioevent_to_epoll(interest: Ready, opts: PollOpt) -> u32 { + let mut kind = 0; + + if interest.is_readable() { + kind |= EPOLLIN; + } + + if interest.is_writable() { + kind |= EPOLLOUT; + } + + if UnixReady::from(interest).is_priority() { + kind |= EPOLLPRI; + } + + if opts.is_edge() { + kind |= EPOLLET; + } + + if opts.is_oneshot() { + kind |= EPOLLONESHOT; + } + + if opts.is_level() { + kind &= !EPOLLET; + } + + kind as u32 +} + +impl AsRawFd for Selector { + fn as_raw_fd(&self) -> RawFd { + self.epfd + } +} + +impl Drop for Selector { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.epfd); + } + } +} + +pub struct Events { + events: Vec, +} + +impl Events { + pub fn with_capacity(u: usize) -> Events { + Events { + events: Vec::with_capacity(u) + } + } + + #[inline] + pub fn len(&self) -> usize { + self.events.len() + } + + #[inline] + pub fn capacity(&self) -> usize { + self.events.capacity() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + + #[inline] + pub fn get(&self, idx: usize) -> Option { + self.events.get(idx).map(|event| { + let epoll = event.events as c_int; + let mut kind = Ready::empty(); + + if (epoll & EPOLLIN) != 0 { + kind = kind | Ready::readable(); + } + + if (epoll & EPOLLPRI) != 0 { + kind = kind | Ready::readable() | UnixReady::priority(); + } + + if (epoll & EPOLLOUT) != 0 { + kind = kind | Ready::writable(); + } + + // EPOLLHUP - Usually means a socket error happened + if (epoll & EPOLLERR) != 0 { + kind = kind | UnixReady::error(); + } + + if (epoll & EPOLLHUP) != 0 { + kind = kind | UnixReady::hup(); + } + + let token = self.events[idx].u64; + + Event::new(kind, Token(token as usize)) + }) + } + + pub fn push_event(&mut self, event: Event) { + self.events.push(libc::epoll_event { + events: ioevent_to_epoll(event.readiness(), PollOpt::empty()), + u64: usize::from(event.token()) as u64 + }); + } + + pub fn clear(&mut self) { + unsafe { self.events.set_len(0); } + } +} + +const NANOS_PER_MILLI: u32 = 1_000_000; +const MILLIS_PER_SEC: u64 = 1_000; + +/// Convert a `Duration` to milliseconds, rounding up and saturating at +/// `u64::MAX`. +/// +/// The saturating is fine because `u64::MAX` milliseconds are still many +/// million years. +pub fn millis(duration: Duration) -> u64 { + // Round up. + let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; + duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64) +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/eventedfd.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/eventedfd.rs new file mode 100644 index 0000000..72586f6 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/eventedfd.rs @@ -0,0 +1,107 @@ +use {io, poll, Ready, Poll, PollOpt, Token}; +use event::Evented; +use std::os::unix::io::RawFd; + +/* + * + * ===== EventedFd ===== + * + */ + +#[derive(Debug)] + +/// Adapter for [`RawFd`] providing an [`Evented`] implementation. +/// +/// `EventedFd` enables registering any type with an FD with [`Poll`]. +/// +/// While only implementations for TCP and UDP are provided, Mio supports +/// registering any FD that can be registered with the underlying OS selector. +/// `EventedFd` provides the necessary bridge. +/// +/// Note that `EventedFd` takes a `&RawFd`. This is because `EventedFd` **does +/// not** take ownership of the FD. Specifically, it will not manage any +/// lifecycle related operations, such as closing the FD on drop. It is expected +/// that the `EventedFd` is constructed right before a call to +/// [`Poll::register`]. See the examples for more detail. +/// +/// # Examples +/// +/// Basic usage +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Ready, Poll, PollOpt, Token}; +/// use mio::unix::EventedFd; +/// +/// use std::os::unix::io::AsRawFd; +/// use std::net::TcpListener; +/// +/// // Bind a std listener +/// let listener = TcpListener::bind("127.0.0.1:0")?; +/// +/// let poll = Poll::new()?; +/// +/// // Register the listener +/// poll.register(&EventedFd(&listener.as_raw_fd()), +/// Token(0), Ready::readable(), PollOpt::edge())?; +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// Implementing [`Evented`] for a custom type backed by a [`RawFd`]. +/// +/// ``` +/// use mio::{Ready, Poll, PollOpt, Token}; +/// use mio::event::Evented; +/// use mio::unix::EventedFd; +/// +/// use std::os::unix::io::RawFd; +/// use std::io; +/// +/// pub struct MyIo { +/// fd: RawFd, +/// } +/// +/// impl Evented for MyIo { +/// fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// EventedFd(&self.fd).register(poll, token, interest, opts) +/// } +/// +/// fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) +/// -> io::Result<()> +/// { +/// EventedFd(&self.fd).reregister(poll, token, interest, opts) +/// } +/// +/// fn deregister(&self, poll: &Poll) -> io::Result<()> { +/// EventedFd(&self.fd).deregister(poll) +/// } +/// } +/// ``` +/// +/// [`RawFd`]: https://doc.rust-lang.org/std/os/unix/io/type.RawFd.html +/// [`Evented`]: ../event/trait.Evented.html +/// [`Poll`]: ../struct.Poll.html +/// [`Poll::register`]: ../struct.Poll.html#method.register +pub struct EventedFd<'a>(pub &'a RawFd); + +impl<'a> Evented for EventedFd<'a> { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + poll::selector(poll).register(*self.0, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + poll::selector(poll).reregister(*self.0, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + poll::selector(poll).deregister(*self.0) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/io.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/io.rs new file mode 100644 index 0000000..47a3a70 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/io.rs @@ -0,0 +1,107 @@ +use std::fs::File; +use std::io::{Read, Write}; +use std::os::unix::io::{IntoRawFd, AsRawFd, FromRawFd, RawFd}; + +use libc; + +use {io, Ready, Poll, PollOpt, Token}; +use event::Evented; +use unix::EventedFd; +use sys::unix::cvt; + +pub fn set_nonblock(fd: libc::c_int) -> io::Result<()> { + unsafe { + let flags = libc::fcntl(fd, libc::F_GETFL); + cvt(libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK)).map(|_|()) + } +} + +pub fn set_cloexec(fd: libc::c_int) -> io::Result<()> { + unsafe { + let flags = libc::fcntl(fd, libc::F_GETFD); + cvt(libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC)).map(|_| ()) + } +} + +/* + * + * ===== Basic IO type ===== + * + */ + +/// Manages a FD +#[derive(Debug)] +pub struct Io { + fd: File, +} + +impl Io { + /// Try to clone the FD + pub fn try_clone(&self) -> io::Result { + Ok(Io { fd: self.fd.try_clone()? }) + } +} + +impl FromRawFd for Io { + unsafe fn from_raw_fd(fd: RawFd) -> Io { + Io { fd: File::from_raw_fd(fd) } + } +} + +impl IntoRawFd for Io { + fn into_raw_fd(self) -> RawFd { + self.fd.into_raw_fd() + } +} + +impl AsRawFd for Io { + fn as_raw_fd(&self) -> RawFd { + self.fd.as_raw_fd() + } +} + +impl Evented for Io { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl Read for Io { + fn read(&mut self, dst: &mut [u8]) -> io::Result { + (&self.fd).read(dst) + } +} + +impl<'a> Read for &'a Io { + fn read(&mut self, dst: &mut [u8]) -> io::Result { + (&self.fd).read(dst) + } +} + +impl Write for Io { + fn write(&mut self, src: &[u8]) -> io::Result { + (&self.fd).write(src) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.fd).flush() + } +} + +impl<'a> Write for &'a Io { + fn write(&mut self, src: &[u8]) -> io::Result { + (&self.fd).write(src) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.fd).flush() + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/kqueue.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/kqueue.rs new file mode 100644 index 0000000..59c70e1 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/kqueue.rs @@ -0,0 +1,360 @@ +use std::{cmp, fmt, ptr}; +#[cfg(not(target_os = "netbsd"))] +use std::os::raw::{c_int, c_short}; +use std::os::unix::io::AsRawFd; +use std::os::unix::io::RawFd; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::time::Duration; + +use libc::{self, time_t}; + +use {io, Ready, PollOpt, Token}; +use event_imp::{self as event, Event}; +use sys::unix::{cvt, UnixReady}; +use sys::unix::io::set_cloexec; + +/// Each Selector has a globally unique(ish) ID associated with it. This ID +/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first +/// registered with the `Selector`. If a type that is previously associated with +/// a `Selector` attempts to register itself with a different `Selector`, the +/// operation will return with an error. This matches windows behavior. +static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; + +#[cfg(not(target_os = "netbsd"))] +type Filter = c_short; +#[cfg(not(target_os = "netbsd"))] +type UData = *mut ::libc::c_void; +#[cfg(not(target_os = "netbsd"))] +type Count = c_int; + +#[cfg(target_os = "netbsd")] +type Filter = u32; +#[cfg(target_os = "netbsd")] +type UData = ::libc::intptr_t; +#[cfg(target_os = "netbsd")] +type Count = usize; + +macro_rules! kevent { + ($id: expr, $filter: expr, $flags: expr, $data: expr) => { + libc::kevent { + ident: $id as ::libc::uintptr_t, + filter: $filter as Filter, + flags: $flags, + fflags: 0, + data: 0, + udata: $data as UData, + } + } +} + +pub struct Selector { + id: usize, + kq: RawFd, +} + +impl Selector { + pub fn new() -> io::Result { + // offset by 1 to avoid choosing 0 as the id of a selector + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; + let kq = unsafe { cvt(libc::kqueue())? }; + drop(set_cloexec(kq)); + + Ok(Selector { + id, + kq, + }) + } + + pub fn id(&self) -> usize { + self.id + } + + pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option) -> io::Result { + let timeout = timeout.map(|to| { + libc::timespec { + tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t, + // `Duration::subsec_nanos` is guaranteed to be less than one + // billion (the number of nanoseconds in a second), making the + // cast to i32 safe. The cast itself is needed for platforms + // where C's long is only 32 bits. + tv_nsec: libc::c_long::from(to.subsec_nanos() as i32), + } + }); + let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut()); + + evts.clear(); + unsafe { + let cnt = cvt(libc::kevent(self.kq, + ptr::null(), + 0, + evts.sys_events.0.as_mut_ptr(), + evts.sys_events.0.capacity() as Count, + timeout))?; + evts.sys_events.0.set_len(cnt as usize); + Ok(evts.coalesce(awakener)) + } + } + + pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { + trace!("registering; token={:?}; interests={:?}", token, interests); + + let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } | + if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } | + libc::EV_RECEIPT; + + unsafe { + let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE }; + let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE }; + let mut changes = [ + kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)), + kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)), + ]; + + cvt(libc::kevent(self.kq, + changes.as_ptr(), + changes.len() as Count, + changes.as_mut_ptr(), + changes.len() as Count, + ::std::ptr::null()))?; + + for change in changes.iter() { + debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR); + + // Test to see if an error happened + if change.data == 0 { + continue + } + + // Older versions of OSX (10.11 and 10.10 have been witnessed) + // can return EPIPE when registering a pipe file descriptor + // where the other end has already disappeared. For example code + // that creates a pipe, closes a file descriptor, and then + // registers the other end will see an EPIPE returned from + // `register`. + // + // It also turns out that kevent will still report events on the + // file descriptor, telling us that it's readable/hup at least + // after we've done this registration. As a result we just + // ignore `EPIPE` here instead of propagating it. + // + // More info can be found at carllerche/mio#582 + if change.data as i32 == libc::EPIPE && + change.filter == libc::EVFILT_WRITE as Filter { + continue + } + + // ignore ENOENT error for EV_DELETE + let orig_flags = if change.filter == libc::EVFILT_READ as Filter { r } else { w }; + if change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0 { + continue + } + + return Err(::std::io::Error::from_raw_os_error(change.data as i32)); + } + Ok(()) + } + } + + pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> { + // Just need to call register here since EV_ADD is a mod if already + // registered + self.register(fd, token, interests, opts) + } + + pub fn deregister(&self, fd: RawFd) -> io::Result<()> { + unsafe { + // EV_RECEIPT is a nice way to apply changes and get back per-event results while not + // draining the actual changes. + let filter = libc::EV_DELETE | libc::EV_RECEIPT; +#[cfg(not(target_os = "netbsd"))] + let mut changes = [ + kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()), + kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()), + ]; + +#[cfg(target_os = "netbsd")] + let mut changes = [ + kevent!(fd, libc::EVFILT_READ, filter, 0), + kevent!(fd, libc::EVFILT_WRITE, filter, 0), + ]; + + cvt(libc::kevent(self.kq, + changes.as_ptr(), + changes.len() as Count, + changes.as_mut_ptr(), + changes.len() as Count, + ::std::ptr::null())).map(|_| ())?; + + if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT { + return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); + } + for change in changes.iter() { + debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR); + if change.data != 0 && change.data as i32 != libc::ENOENT { + return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32)); + } + } + Ok(()) + } + } +} + +impl fmt::Debug for Selector { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Selector") + .field("id", &self.id) + .field("kq", &self.kq) + .finish() + } +} + +impl AsRawFd for Selector { + fn as_raw_fd(&self) -> RawFd { + self.kq + } +} + +impl Drop for Selector { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.kq); + } + } +} + +pub struct Events { + sys_events: KeventList, + events: Vec, + event_map: HashMap, +} + +struct KeventList(Vec); + +unsafe impl Send for KeventList {} +unsafe impl Sync for KeventList {} + +impl Events { + pub fn with_capacity(cap: usize) -> Events { + Events { + sys_events: KeventList(Vec::with_capacity(cap)), + events: Vec::with_capacity(cap), + event_map: HashMap::with_capacity(cap) + } + } + + #[inline] + pub fn len(&self) -> usize { + self.events.len() + } + + #[inline] + pub fn capacity(&self) -> usize { + self.events.capacity() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + + pub fn get(&self, idx: usize) -> Option { + self.events.get(idx).cloned() + } + + fn coalesce(&mut self, awakener: Token) -> bool { + let mut ret = false; + self.events.clear(); + self.event_map.clear(); + + for e in self.sys_events.0.iter() { + let token = Token(e.udata as usize); + let len = self.events.len(); + + if token == awakener { + // TODO: Should this return an error if event is an error. It + // is not critical as spurious wakeups are permitted. + ret = true; + continue; + } + + let idx = *self.event_map.entry(token) + .or_insert(len); + + if idx == len { + // New entry, insert the default + self.events.push(Event::new(Ready::empty(), token)); + + } + + if e.flags & libc::EV_ERROR != 0 { + event::kind_mut(&mut self.events[idx]).insert(*UnixReady::error()); + } + + if e.filter == libc::EVFILT_READ as Filter { + event::kind_mut(&mut self.events[idx]).insert(Ready::readable()); + } else if e.filter == libc::EVFILT_WRITE as Filter { + event::kind_mut(&mut self.events[idx]).insert(Ready::writable()); + } +#[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos"))] + { + if e.filter == libc::EVFILT_AIO { + event::kind_mut(&mut self.events[idx]).insert(UnixReady::aio()); + } + } +#[cfg(any(target_os = "freebsd"))] + { + if e.filter == libc::EVFILT_LIO { + event::kind_mut(&mut self.events[idx]).insert(UnixReady::lio()); + } + } + } + + ret + } + + pub fn push_event(&mut self, event: Event) { + self.events.push(event); + } + + pub fn clear(&mut self) { + self.sys_events.0.truncate(0); + self.events.truncate(0); + self.event_map.clear(); + } +} + +impl fmt::Debug for Events { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Events") + .field("len", &self.sys_events.0.len()) + .finish() + } +} + +#[test] +fn does_not_register_rw() { + use {Poll, Ready, PollOpt, Token}; + use unix::EventedFd; + + let kq = unsafe { libc::kqueue() }; + let kqf = EventedFd(&kq); + let poll = Poll::new().unwrap(); + + // registering kqueue fd will fail if write is requested (On anything but some versions of OS + // X) + poll.register(&kqf, Token(1234), Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); +} + +#[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos"))] +#[test] +fn test_coalesce_aio() { + let mut events = Events::with_capacity(1); + events.sys_events.0.push(kevent!(0x1234, libc::EVFILT_AIO, 0, 42)); + events.coalesce(Token(0)); + assert!(events.events[0].readiness() == UnixReady::aio().into()); + assert!(events.events[0].token() == Token(42)); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/mod.rs new file mode 100644 index 0000000..5bb8307 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/mod.rs @@ -0,0 +1,95 @@ +use libc::{self, c_int}; + +#[macro_use] +pub mod dlsym; + +#[cfg(any(target_os = "linux", target_os = "android", target_os = "solaris"))] +mod epoll; + +#[cfg(any(target_os = "linux", target_os = "android", target_os = "solaris"))] +pub use self::epoll::{Events, Selector}; + +#[cfg(any(target_os = "bitrig", target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos", + target_os = "netbsd", target_os = "openbsd"))] +mod kqueue; + +#[cfg(any(target_os = "bitrig", target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos", + target_os = "netbsd", target_os = "openbsd"))] +pub use self::kqueue::{Events, Selector}; + +mod awakener; +mod eventedfd; +mod io; +mod ready; +mod tcp; +mod udp; +mod uio; + +#[cfg(feature = "with-deprecated")] +mod uds; + +pub use self::awakener::Awakener; +pub use self::eventedfd::EventedFd; +pub use self::io::{Io, set_nonblock}; +pub use self::ready::{UnixReady, READY_ALL}; +pub use self::tcp::{TcpStream, TcpListener}; +pub use self::udp::UdpSocket; + +#[cfg(feature = "with-deprecated")] +pub use self::uds::UnixSocket; + +pub use iovec::IoVec; + +use std::os::unix::io::FromRawFd; + +pub fn pipe() -> ::io::Result<(Io, Io)> { + // Use pipe2 for atomically setting O_CLOEXEC if we can, but otherwise + // just fall back to using `pipe`. + dlsym!(fn pipe2(*mut c_int, c_int) -> c_int); + + let mut pipes = [0; 2]; + unsafe { + match pipe2.get() { + Some(pipe2_fn) => { + let flags = libc::O_NONBLOCK | libc::O_CLOEXEC; + cvt(pipe2_fn(pipes.as_mut_ptr(), flags))?; + Ok((Io::from_raw_fd(pipes[0]), Io::from_raw_fd(pipes[1]))) + } + None => { + cvt(libc::pipe(pipes.as_mut_ptr()))?; + // Ensure the pipe are closed if any of the system calls below + // fail. + let r = Io::from_raw_fd(pipes[0]); + let w = Io::from_raw_fd(pipes[1]); + cvt(libc::fcntl(pipes[0], libc::F_SETFD, libc::FD_CLOEXEC))?; + cvt(libc::fcntl(pipes[1], libc::F_SETFD, libc::FD_CLOEXEC))?; + cvt(libc::fcntl(pipes[0], libc::F_SETFL, libc::O_NONBLOCK))?; + cvt(libc::fcntl(pipes[1], libc::F_SETFL, libc::O_NONBLOCK))?; + Ok((r, w)) + } + } + } +} + +trait IsMinusOne { + fn is_minus_one(&self) -> bool; +} + +impl IsMinusOne for i32 { + fn is_minus_one(&self) -> bool { *self == -1 } +} +impl IsMinusOne for isize { + fn is_minus_one(&self) -> bool { *self == -1 } +} + +fn cvt(t: T) -> ::io::Result { + use std::io; + + if t.is_minus_one() { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/ready.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/ready.rs new file mode 100644 index 0000000..1780cea --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/ready.rs @@ -0,0 +1,499 @@ +use event_imp::{Ready, ready_as_usize, ready_from_usize}; + +use std::ops; +use std::fmt; + +/// Unix specific extensions to `Ready` +/// +/// Provides additional readiness event kinds that are available on unix +/// platforms. Unix platforms are able to provide readiness events for +/// additional socket events, such as HUP and error. +/// +/// HUP events occur when the remote end of a socket hangs up. In the TCP case, +/// this occurs when the remote end of a TCP socket shuts down writes. +/// +/// Error events occur when the socket enters an error state. In this case, the +/// socket will also receive a readable or writable event. Reading or writing to +/// the socket will result in an error. +/// +/// Conversion traits are implemented between `Ready` and `UnixReady`. See the +/// examples. +/// +/// For high level documentation on polling and readiness, see [`Poll`]. +/// +/// # Examples +/// +/// Most of the time, all that is needed is using bit operations +/// +/// ``` +/// use mio::Ready; +/// use mio::unix::UnixReady; +/// +/// let ready = Ready::readable() | UnixReady::hup(); +/// +/// assert!(ready.is_readable()); +/// assert!(UnixReady::from(ready).is_hup()); +/// ``` +/// +/// Basic conversion between ready types. +/// +/// ``` +/// use mio::Ready; +/// use mio::unix::UnixReady; +/// +/// // Start with a portable ready +/// let ready = Ready::readable(); +/// +/// // Convert to a unix ready, adding HUP +/// let mut unix_ready = UnixReady::from(ready) | UnixReady::hup(); +/// +/// unix_ready.insert(UnixReady::error()); +/// +/// // `unix_ready` maintains readable interest +/// assert!(unix_ready.is_readable()); +/// assert!(unix_ready.is_hup()); +/// assert!(unix_ready.is_error()); +/// +/// // Convert back to `Ready` +/// let ready = Ready::from(unix_ready); +/// +/// // Readable is maintained +/// assert!(ready.is_readable()); +/// ``` +/// +/// Registering readable and error interest on a socket +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Ready, Poll, PollOpt, Token}; +/// use mio::net::TcpStream; +/// use mio::unix::UnixReady; +/// +/// let addr = "216.58.193.68:80".parse()?; +/// let socket = TcpStream::connect(&addr)?; +/// +/// let poll = Poll::new()?; +/// +/// poll.register(&socket, +/// Token(0), +/// Ready::readable() | UnixReady::error(), +/// PollOpt::edge())?; +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// [`Poll`]: ../struct.Poll.html +/// [readiness]: struct.Poll.html#readiness-operations +#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)] +pub struct UnixReady(Ready); + +const ERROR: usize = 0b00_0100; +const HUP: usize = 0b00_1000; + +#[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos"))] +const AIO: usize = 0b01_0000; + +#[cfg(not(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos")))] +const AIO: usize = 0b00_0000; + +#[cfg(any(target_os = "freebsd"))] +const LIO: usize = 0b10_0000; + +#[cfg(not(any(target_os = "freebsd")))] +const LIO: usize = 0b00_0000; + +#[cfg(any(target_os = "linux", target_os = "android", target_os = "solaris"))] +const PRI: usize = 0b100_0000; + +#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "solaris")))] +const PRI: usize = 0; + +// Export to support `Ready::all` +pub const READY_ALL: usize = ERROR | HUP | AIO | LIO | PRI; + +#[test] +fn test_ready_all() { + let readable = Ready::readable().as_usize(); + let writable = Ready::writable().as_usize(); + + assert_eq!( + READY_ALL | readable | writable, + ERROR + HUP + AIO + LIO + PRI + readable + writable + ); + + // Issue #896. + #[cfg(any(target_os = "linux", target_os = "android", target_os = "solaris"))] + assert!(!Ready::from(UnixReady::priority()).is_writable()); +} + +impl UnixReady { + /// Returns a `Ready` representing AIO completion readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::aio(); + /// + /// assert!(ready.is_aio()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + #[inline] + #[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos"))] + pub fn aio() -> UnixReady { + UnixReady(ready_from_usize(AIO)) + } + + #[cfg(not(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos")))] + #[deprecated(since = "0.6.12", note = "this function is now platform specific")] + #[doc(hidden)] + pub fn aio() -> UnixReady { + UnixReady(Ready::empty()) + } + + /// Returns a `Ready` representing error readiness. + /// + /// **Note that only readable and writable readiness is guaranteed to be + /// supported on all platforms**. This means that `error` readiness + /// should be treated as a hint. For more details, see [readiness] in the + /// poll documentation. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::error(); + /// + /// assert!(ready.is_error()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + /// [readiness]: ../struct.Poll.html#readiness-operations + #[inline] + pub fn error() -> UnixReady { + UnixReady(ready_from_usize(ERROR)) + } + + /// Returns a `Ready` representing HUP readiness. + /// + /// A HUP (or hang-up) signifies that a stream socket **peer** closed the + /// connection, or shut down the writing half of the connection. + /// + /// **Note that only readable and writable readiness is guaranteed to be + /// supported on all platforms**. This means that `hup` readiness + /// should be treated as a hint. For more details, see [readiness] in the + /// poll documentation. It is also unclear if HUP readiness will remain in 0.7. See + /// [here][issue-941]. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::hup(); + /// + /// assert!(ready.is_hup()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + /// [readiness]: ../struct.Poll.html#readiness-operations + /// [issue-941]: https://github.com/tokio-rs/mio/issues/941 + #[inline] + pub fn hup() -> UnixReady { + UnixReady(ready_from_usize(HUP)) + } + + /// Returns a `Ready` representing LIO completion readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::lio(); + /// + /// assert!(ready.is_lio()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + #[cfg(any(target_os = "freebsd"))] + pub fn lio() -> UnixReady { + UnixReady(ready_from_usize(LIO)) + } + + /// Returns a `Ready` representing priority (`EPOLLPRI`) readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::priority(); + /// + /// assert!(ready.is_priority()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + #[cfg(any(target_os = "linux", + target_os = "android", target_os = "solaris"))] + pub fn priority() -> UnixReady { + UnixReady(ready_from_usize(PRI)) + } + + /// Returns true if `Ready` contains AIO readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::aio(); + /// + /// assert!(ready.is_aio()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + #[inline] + #[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos"))] + pub fn is_aio(&self) -> bool { + self.contains(ready_from_usize(AIO)) + } + + #[deprecated(since = "0.6.12", note = "this function is now platform specific")] + #[cfg(feature = "with-deprecated")] + #[cfg(not(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos")))] + #[doc(hidden)] + pub fn is_aio(&self) -> bool { + false + } + + /// Returns true if the value includes error readiness + /// + /// **Note that only readable and writable readiness is guaranteed to be + /// supported on all platforms**. This means that `error` readiness should + /// be treated as a hint. For more details, see [readiness] in the poll + /// documentation. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::error(); + /// + /// assert!(ready.is_error()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + /// [readiness]: ../struct.Poll.html#readiness-operations + #[inline] + pub fn is_error(&self) -> bool { + self.contains(ready_from_usize(ERROR)) + } + + /// Returns true if the value includes HUP readiness + /// + /// A HUP (or hang-up) signifies that a stream socket **peer** closed the + /// connection, or shut down the writing half of the connection. + /// + /// **Note that only readable and writable readiness is guaranteed to be + /// supported on all platforms**. This means that `hup` readiness + /// should be treated as a hint. For more details, see [readiness] in the + /// poll documentation. + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::hup(); + /// + /// assert!(ready.is_hup()); + /// ``` + /// + /// [`Poll`]: ../struct.Poll.html + /// [readiness]: ../struct.Poll.html#readiness-operations + #[inline] + pub fn is_hup(&self) -> bool { + self.contains(ready_from_usize(HUP)) + } + + /// Returns true if `Ready` contains LIO readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::lio(); + /// + /// assert!(ready.is_lio()); + /// ``` + #[inline] + #[cfg(any(target_os = "freebsd"))] + pub fn is_lio(&self) -> bool { + self.contains(ready_from_usize(LIO)) + } + + /// Returns true if `Ready` contains priority (`EPOLLPRI`) readiness + /// + /// See [`Poll`] for more documentation on polling. + /// + /// # Examples + /// + /// ``` + /// use mio::unix::UnixReady; + /// + /// let ready = UnixReady::priority(); + /// + /// assert!(ready.is_priority()); + /// ``` + /// + /// [`Poll`]: struct.Poll.html + #[inline] + #[cfg(any(target_os = "linux", + target_os = "android", target_os = "solaris"))] + pub fn is_priority(&self) -> bool { + self.contains(ready_from_usize(PRI)) + } +} + +impl From for UnixReady { + fn from(src: Ready) -> UnixReady { + UnixReady(src) + } +} + +impl From for Ready { + fn from(src: UnixReady) -> Ready { + src.0 + } +} + +impl ops::Deref for UnixReady { + type Target = Ready; + + fn deref(&self) -> &Ready { + &self.0 + } +} + +impl ops::DerefMut for UnixReady { + fn deref_mut(&mut self) -> &mut Ready { + &mut self.0 + } +} + +impl ops::BitOr for UnixReady { + type Output = UnixReady; + + #[inline] + fn bitor(self, other: UnixReady) -> UnixReady { + (self.0 | other.0).into() + } +} + +impl ops::BitXor for UnixReady { + type Output = UnixReady; + + #[inline] + fn bitxor(self, other: UnixReady) -> UnixReady { + (self.0 ^ other.0).into() + } +} + +impl ops::BitAnd for UnixReady { + type Output = UnixReady; + + #[inline] + fn bitand(self, other: UnixReady) -> UnixReady { + (self.0 & other.0).into() + } +} + +impl ops::Sub for UnixReady { + type Output = UnixReady; + + #[inline] + fn sub(self, other: UnixReady) -> UnixReady { + ready_from_usize(ready_as_usize(self.0) & !ready_as_usize(other.0)).into() + } +} + +#[deprecated(since = "0.6.10", note = "removed")] +#[cfg(feature = "with-deprecated")] +#[doc(hidden)] +impl ops::Not for UnixReady { + type Output = UnixReady; + + #[inline] + fn not(self) -> UnixReady { + (!self.0).into() + } +} + +impl fmt::Debug for UnixReady { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut one = false; + let flags = [ + (UnixReady(Ready::readable()), "Readable"), + (UnixReady(Ready::writable()), "Writable"), + (UnixReady::error(), "Error"), + (UnixReady::hup(), "Hup"), + #[allow(deprecated)] + (UnixReady::aio(), "Aio"), + #[cfg(any(target_os = "linux", + target_os = "android", target_os = "solaris"))] + (UnixReady::priority(), "Priority"), + ]; + + for &(flag, msg) in &flags { + if self.contains(flag) { + if one { write!(fmt, " | ")? } + write!(fmt, "{}", msg)?; + + one = true + } + } + + if !one { + fmt.write_str("(empty)")?; + } + + Ok(()) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/tcp.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/tcp.rs new file mode 100644 index 0000000..79c18c7 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/tcp.rs @@ -0,0 +1,286 @@ +use std::fmt; +use std::io::{Read, Write}; +use std::net::{self, SocketAddr}; +use std::os::unix::io::{RawFd, FromRawFd, IntoRawFd, AsRawFd}; +use std::time::Duration; + +use libc; +use net2::TcpStreamExt; +use iovec::IoVec; + +use {io, Ready, Poll, PollOpt, Token}; +use event::Evented; + +use sys::unix::eventedfd::EventedFd; +use sys::unix::io::set_nonblock; +use sys::unix::uio::VecIo; + +pub struct TcpStream { + inner: net::TcpStream, +} + +pub struct TcpListener { + inner: net::TcpListener, +} + +impl TcpStream { + pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result { + set_nonblock(stream.as_raw_fd())?; + + match stream.connect(addr) { + Ok(..) => {} + Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} + Err(e) => return Err(e), + } + + Ok(TcpStream { + inner: stream, + }) + } + + pub fn from_stream(stream: net::TcpStream) -> TcpStream { + TcpStream { + inner: stream, + } + } + + pub fn peer_addr(&self) -> io::Result { + self.inner.peer_addr() + } + + pub fn local_addr(&self) -> io::Result { + self.inner.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.inner.try_clone().map(|s| { + TcpStream { + inner: s, + } + }) + } + + pub fn shutdown(&self, how: net::Shutdown) -> io::Result<()> { + self.inner.shutdown(how) + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + self.inner.set_nodelay(nodelay) + } + + pub fn nodelay(&self) -> io::Result { + self.inner.nodelay() + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + self.inner.set_recv_buffer_size(size) + } + + pub fn recv_buffer_size(&self) -> io::Result { + self.inner.recv_buffer_size() + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + self.inner.set_send_buffer_size(size) + } + + pub fn send_buffer_size(&self) -> io::Result { + self.inner.send_buffer_size() + } + + pub fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { + self.inner.set_keepalive(keepalive) + } + + pub fn keepalive(&self) -> io::Result> { + self.inner.keepalive() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.inner.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.inner.ttl() + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.inner.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.inner.only_v6() + } + + pub fn set_linger(&self, dur: Option) -> io::Result<()> { + self.inner.set_linger(dur) + } + + pub fn linger(&self) -> io::Result> { + self.inner.linger() + } + + pub fn take_error(&self) -> io::Result> { + self.inner.take_error() + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + self.inner.peek(buf) + } + + pub fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result { + self.inner.readv(bufs) + } + + pub fn writev(&self, bufs: &[&IoVec]) -> io::Result { + self.inner.writev(bufs) + } +} + +impl<'a> Read for &'a TcpStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + (&self.inner).read(buf) + } +} + +impl<'a> Write for &'a TcpStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + (&self.inner).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.inner).flush() + } +} + +impl Evented for TcpStream { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.inner, f) + } +} + +impl FromRawFd for TcpStream { + unsafe fn from_raw_fd(fd: RawFd) -> TcpStream { + TcpStream { + inner: net::TcpStream::from_raw_fd(fd), + } + } +} + +impl IntoRawFd for TcpStream { + fn into_raw_fd(self) -> RawFd { + self.inner.into_raw_fd() + } +} + +impl AsRawFd for TcpStream { + fn as_raw_fd(&self) -> RawFd { + self.inner.as_raw_fd() + } +} + +impl TcpListener { + pub fn new(inner: net::TcpListener) -> io::Result { + set_nonblock(inner.as_raw_fd())?; + Ok(TcpListener { + inner, + }) + } + + pub fn local_addr(&self) -> io::Result { + self.inner.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.inner.try_clone().map(|s| { + TcpListener { + inner: s, + } + }) + } + + pub fn accept(&self) -> io::Result<(net::TcpStream, SocketAddr)> { + self.inner.accept() + } + + #[allow(deprecated)] + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.inner.set_only_v6(only_v6) + } + + #[allow(deprecated)] + pub fn only_v6(&self) -> io::Result { + self.inner.only_v6() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.inner.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.inner.ttl() + } + + pub fn take_error(&self) -> io::Result> { + self.inner.take_error() + } +} + +impl Evented for TcpListener { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.inner, f) + } +} + +impl FromRawFd for TcpListener { + unsafe fn from_raw_fd(fd: RawFd) -> TcpListener { + TcpListener { + inner: net::TcpListener::from_raw_fd(fd), + } + } +} + +impl IntoRawFd for TcpListener { + fn into_raw_fd(self) -> RawFd { + self.inner.into_raw_fd() + } +} + +impl AsRawFd for TcpListener { + fn as_raw_fd(&self) -> RawFd { + self.inner.as_raw_fd() + } +} + diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/udp.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/udp.rs new file mode 100644 index 0000000..c77a9d6 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/udp.rs @@ -0,0 +1,181 @@ +use {io, Ready, Poll, PollOpt, Token}; +use event::Evented; +use unix::EventedFd; +use sys::unix::uio::VecIo; +use std::fmt; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::os::unix::io::{RawFd, IntoRawFd, AsRawFd, FromRawFd}; + +#[allow(unused_imports)] // only here for Rust 1.8 +use net2::UdpSocketExt; +use iovec::IoVec; + +pub struct UdpSocket { + io: net::UdpSocket, +} + +impl UdpSocket { + pub fn new(socket: net::UdpSocket) -> io::Result { + socket.set_nonblocking(true)?; + Ok(UdpSocket { + io: socket, + }) + } + + pub fn local_addr(&self) -> io::Result { + self.io.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.io.try_clone().map(|io| { + UdpSocket { + io, + } + }) + } + + pub fn send_to(&self, buf: &[u8], target: &SocketAddr) -> io::Result { + self.io.send_to(buf, target) + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + self.io.recv_from(buf) + } + + pub fn send(&self, buf: &[u8]) -> io::Result { + self.io.send(buf) + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result { + self.io.recv(buf) + } + + pub fn connect(&self, addr: SocketAddr) + -> io::Result<()> { + self.io.connect(addr) + } + + pub fn broadcast(&self) -> io::Result { + self.io.broadcast() + } + + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { + self.io.set_broadcast(on) + } + + pub fn multicast_loop_v4(&self) -> io::Result { + self.io.multicast_loop_v4() + } + + pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> { + self.io.set_multicast_loop_v4(on) + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + self.io.multicast_ttl_v4() + } + + pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> { + self.io.set_multicast_ttl_v4(ttl) + } + + pub fn multicast_loop_v6(&self) -> io::Result { + self.io.multicast_loop_v6() + } + + pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> { + self.io.set_multicast_loop_v6(on) + } + + pub fn ttl(&self) -> io::Result { + self.io.ttl() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.io.set_ttl(ttl) + } + + pub fn join_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.io.join_multicast_v4(multiaddr, interface) + } + + pub fn join_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.io.join_multicast_v6(multiaddr, interface) + } + + pub fn leave_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.io.leave_multicast_v4(multiaddr, interface) + } + + pub fn leave_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.io.leave_multicast_v6(multiaddr, interface) + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.io.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.io.only_v6() + } + + pub fn take_error(&self) -> io::Result> { + self.io.take_error() + } + + pub fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result { + self.io.readv(bufs) + } + + pub fn writev(&self, bufs: &[&IoVec]) -> io::Result { + self.io.writev(bufs) + } +} + +impl Evented for UdpSocket { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + EventedFd(&self.as_raw_fd()).deregister(poll) + } +} + +impl fmt::Debug for UdpSocket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.io, f) + } +} + +impl FromRawFd for UdpSocket { + unsafe fn from_raw_fd(fd: RawFd) -> UdpSocket { + UdpSocket { + io: net::UdpSocket::from_raw_fd(fd), + } + } +} + +impl IntoRawFd for UdpSocket { + fn into_raw_fd(self) -> RawFd { + self.io.into_raw_fd() + } +} + +impl AsRawFd for UdpSocket { + fn as_raw_fd(&self) -> RawFd { + self.io.as_raw_fd() + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uds.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uds.rs new file mode 100644 index 0000000..1bf8c5d --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uds.rs @@ -0,0 +1,262 @@ +use std::io::{Read, Write}; +use std::mem; +use std::net::Shutdown; +use std::os::unix::prelude::*; +use std::path::Path; +use std::ptr; + +use libc; + +use {io, Ready, Poll, PollOpt, Token}; +use event::Evented; +use sys::unix::{cvt, Io}; +use sys::unix::io::{set_nonblock, set_cloexec}; + +trait MyInto { + fn my_into(self) -> T; +} + +impl MyInto for usize { + fn my_into(self) -> u32 { self as u32 } +} + +impl MyInto for usize { + fn my_into(self) -> usize { self } +} + +unsafe fn sockaddr_un(path: &Path) + -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { + let mut addr: libc::sockaddr_un = mem::zeroed(); + addr.sun_family = libc::AF_UNIX as libc::sa_family_t; + + let bytes = path.as_os_str().as_bytes(); + + if bytes.len() >= addr.sun_path.len() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN")) + } + for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { + *dst = *src as libc::c_char; + } + // null byte for pathname addresses is already there because we zeroed the + // struct + + let mut len = sun_path_offset() + bytes.len(); + match bytes.get(0) { + Some(&0) | None => {} + Some(_) => len += 1, + } + Ok((addr, len as libc::socklen_t)) +} + +fn sun_path_offset() -> usize { + unsafe { + // Work with an actual instance of the type since using a null pointer is UB + let addr: libc::sockaddr_un = mem::uninitialized(); + let base = &addr as *const _ as usize; + let path = &addr.sun_path as *const _ as usize; + path - base + } +} + +#[derive(Debug)] +pub struct UnixSocket { + io: Io, +} + +impl UnixSocket { + /// Returns a new, unbound, non-blocking Unix domain socket + pub fn stream() -> io::Result { + #[cfg(target_os = "linux")] + use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK}; + #[cfg(not(target_os = "linux"))] + const SOCK_CLOEXEC: libc::c_int = 0; + #[cfg(not(target_os = "linux"))] + const SOCK_NONBLOCK: libc::c_int = 0; + + unsafe { + if cfg!(target_os = "linux") { + let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK; + match cvt(libc::socket(libc::AF_UNIX, flags, 0)) { + Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)), + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} + Err(e) => return Err(e), + } + } + + let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?; + let fd = UnixSocket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + set_nonblock(fd.as_raw_fd())?; + Ok(fd) + } + } + + /// Connect the socket to the specified address + pub fn connect + ?Sized>(&self, addr: &P) -> io::Result<()> { + unsafe { + let (addr, len) = sockaddr_un(addr.as_ref())?; + cvt(libc::connect(self.as_raw_fd(), + &addr as *const _ as *const _, + len))?; + Ok(()) + } + } + + /// Listen for incoming requests + pub fn listen(&self, backlog: usize) -> io::Result<()> { + unsafe { + cvt(libc::listen(self.as_raw_fd(), backlog as i32))?; + Ok(()) + } + } + + pub fn accept(&self) -> io::Result { + unsafe { + let fd = cvt(libc::accept(self.as_raw_fd(), + ptr::null_mut(), + ptr::null_mut()))?; + let fd = Io::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + set_nonblock(fd.as_raw_fd())?; + Ok(UnixSocket { io: fd }) + } + } + + /// Bind the socket to the specified address + pub fn bind + ?Sized>(&self, addr: &P) -> io::Result<()> { + unsafe { + let (addr, len) = sockaddr_un(addr.as_ref())?; + cvt(libc::bind(self.as_raw_fd(), + &addr as *const _ as *const _, + len))?; + Ok(()) + } + } + + pub fn try_clone(&self) -> io::Result { + Ok(UnixSocket { io: self.io.try_clone()? }) + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Read => libc::SHUT_RD, + Shutdown::Write => libc::SHUT_WR, + Shutdown::Both => libc::SHUT_RDWR, + }; + unsafe { + cvt(libc::shutdown(self.as_raw_fd(), how))?; + Ok(()) + } + } + + pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option)> { + unsafe { + let mut iov = libc::iovec { + iov_base: buf.as_mut_ptr() as *mut _, + iov_len: buf.len(), + }; + struct Cmsg { + hdr: libc::cmsghdr, + data: [libc::c_int; 1], + } + let mut cmsg: Cmsg = mem::zeroed(); + let mut msg: libc::msghdr = mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = &mut cmsg as *mut _ as *mut _; + msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); + let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?; + + const SCM_RIGHTS: libc::c_int = 1; + + let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET && + cmsg.hdr.cmsg_type == SCM_RIGHTS { + Some(cmsg.data[0]) + } else { + None + }; + Ok((bytes as usize, fd)) + } + } + + pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result { + unsafe { + let mut iov = libc::iovec { + iov_base: buf.as_ptr() as *mut _, + iov_len: buf.len(), + }; + struct Cmsg { + hdr: libc::cmsghdr, + data: [libc::c_int; 1], + } + let mut cmsg: Cmsg = mem::zeroed(); + cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into(); + cmsg.hdr.cmsg_level = libc::SOL_SOCKET; + cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS + cmsg.data[0] = fd; + let mut msg: libc::msghdr = mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = &mut cmsg as *mut _ as *mut _; + msg.msg_controllen = mem::size_of_val(&cmsg).my_into(); + let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?; + Ok(bytes as usize) + } + } +} + +impl Read for UnixSocket { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.io.read(buf) + } +} + +impl Write for UnixSocket { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.io.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.io.flush() + } +} + +impl Evented for UnixSocket { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.io.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.io.deregister(poll) + } +} + + +impl From for UnixSocket { + fn from(io: Io) -> UnixSocket { + UnixSocket { io } + } +} + +impl FromRawFd for UnixSocket { + unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket { + UnixSocket { io: Io::from_raw_fd(fd) } + } +} + +impl IntoRawFd for UnixSocket { + fn into_raw_fd(self) -> RawFd { + self.io.into_raw_fd() + } +} + +impl AsRawFd for UnixSocket { + fn as_raw_fd(&self) -> RawFd { + self.io.as_raw_fd() + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uio.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uio.rs new file mode 100644 index 0000000..e38cd49 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/unix/uio.rs @@ -0,0 +1,44 @@ +use std::cmp; +use std::io; +use std::os::unix::io::AsRawFd; +use libc; +use iovec::IoVec; +use iovec::unix as iovec; + +pub trait VecIo { + fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result; + + fn writev(&self, bufs: &[&IoVec]) -> io::Result; +} + +impl VecIo for T { + fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result { + unsafe { + let slice = iovec::as_os_slice_mut(bufs); + let len = cmp::min(::max_value() as usize, slice.len()); + let rc = libc::readv(self.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } + + fn writev(&self, bufs: &[&IoVec]) -> io::Result { + unsafe { + let slice = iovec::as_os_slice(bufs); + let len = cmp::min(::max_value() as usize, slice.len()); + let rc = libc::writev(self.as_raw_fd(), + slice.as_ptr(), + len as libc::c_int); + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(rc as usize) + } + } + } +} \ No newline at end of file diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/awakener.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/awakener.rs new file mode 100644 index 0000000..c913bc9 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/awakener.rs @@ -0,0 +1,66 @@ +use std::sync::Mutex; + +use miow::iocp::CompletionStatus; +use {io, poll, Ready, Poll, PollOpt, Token}; +use event::Evented; +use sys::windows::Selector; + +pub struct Awakener { + inner: Mutex>, +} + +struct AwakenerInner { + token: Token, + selector: Selector, +} + +impl Awakener { + pub fn new() -> io::Result { + Ok(Awakener { + inner: Mutex::new(None), + }) + } + + pub fn wakeup(&self) -> io::Result<()> { + // Each wakeup notification has NULL as its `OVERLAPPED` pointer to + // indicate that it's from this awakener and not part of an I/O + // operation. This is specially recognized by the selector. + // + // If we haven't been registered with an event loop yet just silently + // succeed. + if let Some(inner) = self.inner.lock().unwrap().as_ref() { + let status = CompletionStatus::new(0, + usize::from(inner.token), + 0 as *mut _); + inner.selector.port().post(status)?; + } + Ok(()) + } + + pub fn cleanup(&self) { + // noop + } +} + +impl Evented for Awakener { + fn register(&self, poll: &Poll, token: Token, events: Ready, + opts: PollOpt) -> io::Result<()> { + assert_eq!(opts, PollOpt::edge()); + assert_eq!(events, Ready::readable()); + *self.inner.lock().unwrap() = Some(AwakenerInner { + selector: poll::selector(poll).clone_ref(), + token: token, + }); + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, events: Ready, + opts: PollOpt) -> io::Result<()> { + self.register(poll, token, events, opts) + } + + fn deregister(&self, _poll: &Poll) -> io::Result<()> { + *self.inner.lock().unwrap() = None; + Ok(()) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/buffer_pool.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/buffer_pool.rs new file mode 100644 index 0000000..8675459 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/buffer_pool.rs @@ -0,0 +1,20 @@ +pub struct BufferPool { + pool: Vec>, +} + +impl BufferPool { + pub fn new(cap: usize) -> BufferPool { + BufferPool { pool: Vec::with_capacity(cap) } + } + + pub fn get(&mut self, default_cap: usize) -> Vec { + self.pool.pop().unwrap_or_else(|| Vec::with_capacity(default_cap)) + } + + pub fn put(&mut self, mut buf: Vec) { + if self.pool.len() < self.pool.capacity(){ + unsafe { buf.set_len(0); } + self.pool.push(buf); + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/from_raw_arc.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/from_raw_arc.rs new file mode 100644 index 0000000..b6d38b2 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/from_raw_arc.rs @@ -0,0 +1,116 @@ +//! A "Manual Arc" which allows manually frobbing the reference count +//! +//! This module contains a copy of the `Arc` found in the standard library, +//! stripped down to the bare bones of what we actually need. The reason this is +//! done is for the ability to concretely know the memory layout of the `Inner` +//! structure of the arc pointer itself (e.g. `ArcInner` in the standard +//! library). +//! +//! We do some unsafe casting from `*mut OVERLAPPED` to a `FromRawArc` to +//! ensure that data lives for the length of an I/O operation, but this means +//! that we have to know the layouts of the structures involved. This +//! representation primarily guarantees that the data, `T` is at the front of +//! the inner pointer always. +//! +//! Note that we're missing out on some various optimizations implemented in the +//! standard library: +//! +//! * The size of `FromRawArc` is actually two words because of the drop flag +//! * The compiler doesn't understand that the pointer in `FromRawArc` is never +//! null, so Option> is not a nullable pointer. + +use std::ops::Deref; +use std::mem; +use std::sync::atomic::{self, AtomicUsize, Ordering}; + +pub struct FromRawArc { + _inner: *mut Inner, +} + +unsafe impl Send for FromRawArc { } +unsafe impl Sync for FromRawArc { } + +#[repr(C)] +struct Inner { + data: T, + cnt: AtomicUsize, +} + +impl FromRawArc { + pub fn new(data: T) -> FromRawArc { + let x = Box::new(Inner { + data: data, + cnt: AtomicUsize::new(1), + }); + FromRawArc { _inner: unsafe { mem::transmute(x) } } + } + + pub unsafe fn from_raw(ptr: *mut T) -> FromRawArc { + // Note that if we could use `mem::transmute` here to get a libstd Arc + // (guaranteed) then we could just use std::sync::Arc, but this is the + // crucial reason this currently exists. + FromRawArc { _inner: ptr as *mut Inner } + } +} + +impl Clone for FromRawArc { + fn clone(&self) -> FromRawArc { + // Atomic ordering of Relaxed lifted from libstd, but the general idea + // is that you need synchronization to communicate this increment to + // another thread, so this itself doesn't need to be synchronized. + unsafe { + (*self._inner).cnt.fetch_add(1, Ordering::Relaxed); + } + FromRawArc { _inner: self._inner } + } +} + +impl Deref for FromRawArc { + type Target = T; + + fn deref(&self) -> &T { + unsafe { &(*self._inner).data } + } +} + +impl Drop for FromRawArc { + fn drop(&mut self) { + unsafe { + // Atomic orderings lifted from the standard library + if (*self._inner).cnt.fetch_sub(1, Ordering::Release) != 1 { + return + } + atomic::fence(Ordering::Acquire); + drop(mem::transmute::<_, Box>(self._inner)); + } + } +} + +#[cfg(test)] +mod tests { + use super::FromRawArc; + + #[test] + fn smoke() { + let a = FromRawArc::new(1); + assert_eq!(*a, 1); + assert_eq!(*a.clone(), 1); + } + + #[test] + fn drops() { + struct A<'a>(&'a mut bool); + impl<'a> Drop for A<'a> { + fn drop(&mut self) { + *self.0 = true; + } + } + let mut a = false; + { + let a = FromRawArc::new(A(&mut a)); + let _ = a.clone(); + assert!(!*a.0); + } + assert!(a); + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/mod.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/mod.rs new file mode 100644 index 0000000..dad70b0 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/mod.rs @@ -0,0 +1,187 @@ +//! Implementation of mio for Windows using IOCP +//! +//! This module uses I/O Completion Ports (IOCP) on Windows to implement mio's +//! Unix epoll-like interface. Unfortunately these two I/O models are +//! fundamentally incompatible: +//! +//! * IOCP is a completion-based model where work is submitted to the kernel and +//! a program is notified later when the work finished. +//! * epoll is a readiness-based model where the kernel is queried as to what +//! work can be done, and afterwards the work is done. +//! +//! As a result, this implementation for Windows is much less "low level" than +//! the Unix implementation of mio. This design decision was intentional, +//! however. +//! +//! ## What is IOCP? +//! +//! The [official docs][docs] have a comprehensive explanation of what IOCP is, +//! but at a high level it requires the following operations to be executed to +//! perform some I/O: +//! +//! 1. A completion port is created +//! 2. An I/O handle and a token is registered with this completion port +//! 3. Some I/O is issued on the handle. This generally means that an API was +//! invoked with a zeroed `OVERLAPPED` structure. The API will immediately +//! return. +//! 4. After some time, the application queries the I/O port for completed +//! events. The port will returned a pointer to the `OVERLAPPED` along with +//! the token presented at registration time. +//! +//! Many I/O operations can be fired off before waiting on a port, and the port +//! will block execution of the calling thread until an I/O event has completed +//! (or a timeout has elapsed). +//! +//! Currently all of these low-level operations are housed in a separate `miow` +//! crate to provide a 0-cost abstraction over IOCP. This crate uses that to +//! implement all fiddly bits so there's very few actual Windows API calls or +//! `unsafe` blocks as a result. +//! +//! [docs]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365198%28v=vs.85%29.aspx +//! +//! ## Safety of IOCP +//! +//! Unfortunately for us, IOCP is pretty unsafe in terms of Rust lifetimes and +//! such. When an I/O operation is submitted to the kernel, it involves handing +//! the kernel a few pointers like a buffer to read/write, an `OVERLAPPED` +//! structure pointer, and perhaps some other buffers such as for socket +//! addresses. These pointers all have to remain valid **for the entire I/O +//! operation's duration**. +//! +//! There's no way to define a safe lifetime for these pointers/buffers over +//! the span of an I/O operation, so we're forced to add a layer of abstraction +//! (not 0-cost) to make these APIs safe. Currently this implementation +//! basically just boxes everything up on the heap to give it a stable address +//! and then keys off that most of the time. +//! +//! ## From completion to readiness +//! +//! Translating a completion-based model to a readiness-based model is also no +//! easy task, and a significant portion of this implementation is managing this +//! translation. The basic idea behind this implementation is to issue I/O +//! operations preemptively and then translate their completions to a "I'm +//! ready" event. +//! +//! For example, in the case of reading a `TcpSocket`, as soon as a socket is +//! connected (or registered after an accept) a read operation is executed. +//! While the read is in progress calls to `read` will return `WouldBlock`, and +//! once the read is completed we translate the completion notification into a +//! `readable` event. Once the internal buffer is drained (e.g. all data from it +//! has been read) a read operation is re-issued. +//! +//! Write operations are a little different from reads, and the current +//! implementation is to just schedule a write as soon as `write` is first +//! called. While that write operation is in progress all future calls to +//! `write` will return `WouldBlock`. Completion of the write then translates to +//! a `writable` event. Note that this will probably want to add some layer of +//! internal buffering in the future. +//! +//! ## Buffer Management +//! +//! As there's lots of I/O operations in flight at any one point in time, +//! there's lots of live buffers that need to be juggled around (e.g. this +//! implementation's own internal buffers). +//! +//! Currently all buffers are created for the I/O operation at hand and are then +//! discarded when it completes (this is listed as future work below). +//! +//! ## Callback Management +//! +//! When the main event loop receives a notification that an I/O operation has +//! completed, some work needs to be done to translate that to a set of events +//! or perhaps some more I/O needs to be scheduled. For example after a +//! `TcpStream` is connected it generates a writable event and also schedules a +//! read. +//! +//! To manage all this the `Selector` uses the `OVERLAPPED` pointer from the +//! completion status. The selector assumes that all `OVERLAPPED` pointers are +//! actually pointers to the interior of a `selector::Overlapped` which means +//! that right after the `OVERLAPPED` itself there's a function pointer. This +//! function pointer is given the completion status as well as another callback +//! to push events onto the selector. +//! +//! The callback for each I/O operation doesn't have any environment, so it +//! relies on memory layout and unsafe casting to translate an `OVERLAPPED` +//! pointer (or in this case a `selector::Overlapped` pointer) to a type of +//! `FromRawArc` (see module docs for why this type exists). +//! +//! ## Thread Safety +//! +//! Currently all of the I/O primitives make liberal use of `Arc` and `Mutex` +//! as an implementation detail. The main reason for this is to ensure that the +//! types are `Send` and `Sync`, but the implementations have not been stressed +//! in multithreaded situations yet. As a result, there are bound to be +//! functional surprises in using these concurrently. +//! +//! ## Future Work +//! +//! First up, let's take a look at unimplemented portions of this module: +//! +//! * The `PollOpt::level()` option is currently entirely unimplemented. +//! * Each `EventLoop` currently owns its completion port, but this prevents an +//! I/O handle from being added to multiple event loops (something that can be +//! done on Unix). Additionally, it hinders event loops moving across threads. +//! This should be solved by likely having a global `Selector` which all +//! others then communicate with. +//! * Although Unix sockets don't exist on Windows, there are named pipes and +//! those should likely be bound here in a similar fashion to `TcpStream`. +//! +//! Next up, there are a few performance improvements and optimizations that can +//! still be implemented +//! +//! * Buffer management right now is pretty bad, they're all just allocated +//! right before an I/O operation and discarded right after. There should at +//! least be some form of buffering buffers. +//! * No calls to `write` are internally buffered before being scheduled, which +//! means that writing performance is abysmal compared to Unix. There should +//! be some level of buffering of writes probably. + +use std::io; +use std::os::windows::prelude::*; + +use kernel32; +use winapi; + +mod awakener; +#[macro_use] +mod selector; +mod tcp; +mod udp; +mod from_raw_arc; +mod buffer_pool; + +pub use self::awakener::Awakener; +pub use self::selector::{Events, Selector, Overlapped, Binding}; +pub use self::tcp::{TcpStream, TcpListener}; +pub use self::udp::UdpSocket; + +#[derive(Copy, Clone)] +enum Family { + V4, V6, +} + +unsafe fn cancel(socket: &AsRawSocket, + overlapped: &Overlapped) -> io::Result<()> { + let handle = socket.as_raw_socket() as winapi::HANDLE; + let ret = kernel32::CancelIoEx(handle, overlapped.as_mut_ptr()); + if ret == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +unsafe fn no_notify_on_instant_completion(handle: winapi::HANDLE) -> io::Result<()> { + // TODO: move those to winapi + const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS: winapi::UCHAR = 1; + const FILE_SKIP_SET_EVENT_ON_HANDLE: winapi::UCHAR = 2; + + let flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS | FILE_SKIP_SET_EVENT_ON_HANDLE; + + let r = kernel32::SetFileCompletionNotificationModes(handle, flags); + if r == winapi::TRUE { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/selector.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/selector.rs new file mode 100644 index 0000000..5692084 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/selector.rs @@ -0,0 +1,534 @@ +#![allow(deprecated)] + +use std::{fmt, io}; +use std::cell::UnsafeCell; +use std::os::windows::prelude::*; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::time::Duration; + +use lazycell::AtomicLazyCell; + +use winapi::*; +use miow; +use miow::iocp::{CompletionPort, CompletionStatus}; + +use event_imp::{Event, Evented, Ready}; +use poll::{self, Poll}; +use sys::windows::buffer_pool::BufferPool; +use {Token, PollOpt}; + +/// Each Selector has a globally unique(ish) ID associated with it. This ID +/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first +/// registered with the `Selector`. If a type that is previously associated with +/// a `Selector` attempts to register itself with a different `Selector`, the +/// operation will return with an error. This matches windows behavior. +static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT; + +/// The guts of the Windows event loop, this is the struct which actually owns +/// a completion port. +/// +/// Internally this is just an `Arc`, and this allows handing out references to +/// the internals to I/O handles registered on this selector. This is +/// required to schedule I/O operations independently of being inside the event +/// loop (e.g. when a call to `write` is seen we're not "in the event loop"). +pub struct Selector { + inner: Arc, +} + +struct SelectorInner { + /// Unique identifier of the `Selector` + id: usize, + + /// The actual completion port that's used to manage all I/O + port: CompletionPort, + + /// A pool of buffers usable by this selector. + /// + /// Primitives will take buffers from this pool to perform I/O operations, + /// and once complete they'll be put back in. + buffers: Mutex, +} + +impl Selector { + pub fn new() -> io::Result { + // offset by 1 to avoid choosing 0 as the id of a selector + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1; + + CompletionPort::new(0).map(|cp| { + Selector { + inner: Arc::new(SelectorInner { + id: id, + port: cp, + buffers: Mutex::new(BufferPool::new(256)), + }), + } + }) + } + + pub fn select(&self, + events: &mut Events, + awakener: Token, + timeout: Option) -> io::Result { + trace!("select; timeout={:?}", timeout); + + // Clear out the previous list of I/O events and get some more! + events.clear(); + + trace!("polling IOCP"); + let n = match self.inner.port.get_many(&mut events.statuses, timeout) { + Ok(statuses) => statuses.len(), + Err(ref e) if e.raw_os_error() == Some(WAIT_TIMEOUT as i32) => 0, + Err(e) => return Err(e), + }; + + let mut ret = false; + for status in events.statuses[..n].iter() { + // This should only ever happen from the awakener, and we should + // only ever have one awakener right now, so assert as such. + if status.overlapped() as usize == 0 { + assert_eq!(status.token(), usize::from(awakener)); + ret = true; + continue; + } + + let callback = unsafe { + (*(status.overlapped() as *mut Overlapped)).callback + }; + + trace!("select; -> got overlapped"); + callback(status.entry()); + } + + trace!("returning"); + Ok(ret) + } + + /// Gets a reference to the underlying `CompletionPort` structure. + pub fn port(&self) -> &CompletionPort { + &self.inner.port + } + + /// Gets a new reference to this selector, although all underlying data + /// structures will refer to the same completion port. + pub fn clone_ref(&self) -> Selector { + Selector { inner: self.inner.clone() } + } + + /// Return the `Selector`'s identifier + pub fn id(&self) -> usize { + self.inner.id + } +} + +impl SelectorInner { + fn identical(&self, other: &SelectorInner) -> bool { + (self as *const SelectorInner) == (other as *const SelectorInner) + } +} + +// A registration is stored in each I/O object which keeps track of how it is +// associated with a `Selector` above. +// +// Once associated with a `Selector`, a registration can never be un-associated +// (due to IOCP requirements). This is actually implemented through the +// `poll::Registration` and `poll::SetReadiness` APIs to keep track of all the +// level/edge/filtering business. +/// A `Binding` is embedded in all I/O objects associated with a `Poll` +/// object. +/// +/// Each registration keeps track of which selector the I/O object is +/// associated with, ensuring that implementations of `Evented` can be +/// conformant for the various methods on Windows. +/// +/// If you're working with custom IOCP-enabled objects then you'll want to +/// ensure that one of these instances is stored in your object and used in the +/// implementation of `Evented`. +/// +/// For more information about how to use this see the `windows` module +/// documentation in this crate. +pub struct Binding { + selector: AtomicLazyCell>, +} + +impl Binding { + /// Creates a new blank binding ready to be inserted into an I/O + /// object. + /// + /// Won't actually do anything until associated with a `Poll` loop. + pub fn new() -> Binding { + Binding { selector: AtomicLazyCell::new() } + } + + /// Registers a new handle with the `Poll` specified, also assigning the + /// `token` specified. + /// + /// This function is intended to be used as part of `Evented::register` for + /// custom IOCP objects. It will add the specified handle to the internal + /// IOCP object with the provided `token`. All future events generated by + /// the handled provided will be received by the `Poll`'s internal IOCP + /// object. + /// + /// # Unsafety + /// + /// This function is unsafe as the `Poll` instance has assumptions about + /// what the `OVERLAPPED` pointer used for each I/O operation looks like. + /// Specifically they must all be instances of the `Overlapped` type in + /// this crate. More information about this can be found on the + /// `windows` module in this crate. + pub unsafe fn register_handle(&self, + handle: &AsRawHandle, + token: Token, + poll: &Poll) -> io::Result<()> { + let selector = poll::selector(poll); + + // Ignore errors, we'll see them on the next line. + drop(self.selector.fill(selector.inner.clone())); + self.check_same_selector(poll)?; + + selector.inner.port.add_handle(usize::from(token), handle) + } + + /// Same as `register_handle` but for sockets. + pub unsafe fn register_socket(&self, + handle: &AsRawSocket, + token: Token, + poll: &Poll) -> io::Result<()> { + let selector = poll::selector(poll); + drop(self.selector.fill(selector.inner.clone())); + self.check_same_selector(poll)?; + selector.inner.port.add_socket(usize::from(token), handle) + } + + /// Reregisters the handle provided from the `Poll` provided. + /// + /// This is intended to be used as part of `Evented::reregister` but note + /// that this function does not currently reregister the provided handle + /// with the `poll` specified. IOCP has a special binding for changing the + /// token which has not yet been implemented. Instead this function should + /// be used to assert that the call to `reregister` happened on the same + /// `Poll` that was passed into to `register`. + /// + /// Eventually, though, the provided `handle` will be re-assigned to have + /// the token `token` on the given `poll` assuming that it's been + /// previously registered with it. + /// + /// # Unsafety + /// + /// This function is unsafe for similar reasons to `register`. That is, + /// there may be pending I/O events and such which aren't handled correctly. + pub unsafe fn reregister_handle(&self, + _handle: &AsRawHandle, + _token: Token, + poll: &Poll) -> io::Result<()> { + self.check_same_selector(poll) + } + + /// Same as `reregister_handle`, but for sockets. + pub unsafe fn reregister_socket(&self, + _socket: &AsRawSocket, + _token: Token, + poll: &Poll) -> io::Result<()> { + self.check_same_selector(poll) + } + + /// Deregisters the handle provided from the `Poll` provided. + /// + /// This is intended to be used as part of `Evented::deregister` but note + /// that this function does not currently deregister the provided handle + /// from the `poll` specified. IOCP has a special binding for that which has + /// not yet been implemented. Instead this function should be used to assert + /// that the call to `deregister` happened on the same `Poll` that was + /// passed into to `register`. + /// + /// # Unsafety + /// + /// This function is unsafe for similar reasons to `register`. That is, + /// there may be pending I/O events and such which aren't handled correctly. + pub unsafe fn deregister_handle(&self, + _handle: &AsRawHandle, + poll: &Poll) -> io::Result<()> { + self.check_same_selector(poll) + } + + /// Same as `deregister_handle`, but for sockets. + pub unsafe fn deregister_socket(&self, + _socket: &AsRawSocket, + poll: &Poll) -> io::Result<()> { + self.check_same_selector(poll) + } + + fn check_same_selector(&self, poll: &Poll) -> io::Result<()> { + let selector = poll::selector(poll); + match self.selector.borrow() { + Some(prev) if prev.identical(&selector.inner) => Ok(()), + Some(_) | + None => Err(other("socket already registered")), + } + } +} + +impl fmt::Debug for Binding { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Binding") + .finish() + } +} + +/// Helper struct used for TCP and UDP which bundles a `binding` with a +/// `SetReadiness` handle. +pub struct ReadyBinding { + binding: Binding, + readiness: Option, +} + +impl ReadyBinding { + /// Creates a new blank binding ready to be inserted into an I/O object. + /// + /// Won't actually do anything until associated with an `Selector` loop. + pub fn new() -> ReadyBinding { + ReadyBinding { + binding: Binding::new(), + readiness: None, + } + } + + /// Returns whether this binding has been associated with a selector + /// yet. + pub fn registered(&self) -> bool { + self.readiness.is_some() + } + + /// Acquires a buffer with at least `size` capacity. + /// + /// If associated with a selector, this will attempt to pull a buffer from + /// that buffer pool. If not associated with a selector, this will allocate + /// a fresh buffer. + pub fn get_buffer(&self, size: usize) -> Vec { + match self.binding.selector.borrow() { + Some(i) => i.buffers.lock().unwrap().get(size), + None => Vec::with_capacity(size), + } + } + + /// Returns a buffer to this binding. + /// + /// If associated with a selector, this will push the buffer back into the + /// selector's pool of buffers. Otherwise this will just drop the buffer. + pub fn put_buffer(&self, buf: Vec) { + if let Some(i) = self.binding.selector.borrow() { + i.buffers.lock().unwrap().put(buf); + } + } + + /// Sets the readiness of this I/O object to a particular `set`. + /// + /// This is later used to fill out and respond to requests to `poll`. Note + /// that this is all implemented through the `SetReadiness` structure in the + /// `poll` module. + pub fn set_readiness(&self, set: Ready) { + if let Some(ref i) = self.readiness { + trace!("set readiness to {:?}", set); + i.set_readiness(set).expect("event loop disappeared?"); + } + } + + /// Queries what the current readiness of this I/O object is. + /// + /// This is what's being used to generate events returned by `poll`. + pub fn readiness(&self) -> Ready { + match self.readiness { + Some(ref i) => i.readiness(), + None => Ready::empty(), + } + } + + /// Implementation of the `Evented::register` function essentially. + /// + /// Returns an error if we're already registered with another event loop, + /// and otherwise just reassociates ourselves with the event loop to + /// possible change tokens. + pub fn register_socket(&mut self, + socket: &AsRawSocket, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt, + registration: &Mutex>) + -> io::Result<()> { + trace!("register {:?} {:?}", token, events); + unsafe { + self.binding.register_socket(socket, token, poll)?; + } + + let (r, s) = poll::new_registration(poll, token, events, opts); + self.readiness = Some(s); + *registration.lock().unwrap() = Some(r); + Ok(()) + } + + /// Implementation of `Evented::reregister` function. + pub fn reregister_socket(&mut self, + socket: &AsRawSocket, + poll: &Poll, + token: Token, + events: Ready, + opts: PollOpt, + registration: &Mutex>) + -> io::Result<()> { + trace!("reregister {:?} {:?}", token, events); + unsafe { + self.binding.reregister_socket(socket, token, poll)?; + } + + registration.lock().unwrap() + .as_mut().unwrap() + .reregister(poll, token, events, opts) + } + + /// Implementation of the `Evented::deregister` function. + /// + /// Doesn't allow registration with another event loop, just shuts down + /// readiness notifications and such. + pub fn deregister(&mut self, + socket: &AsRawSocket, + poll: &Poll, + registration: &Mutex>) + -> io::Result<()> { + trace!("deregistering"); + unsafe { + self.binding.deregister_socket(socket, poll)?; + } + + registration.lock().unwrap() + .as_ref().unwrap() + .deregister(poll) + } +} + +fn other(s: &str) -> io::Error { + io::Error::new(io::ErrorKind::Other, s) +} + +#[derive(Debug)] +pub struct Events { + /// Raw I/O event completions are filled in here by the call to `get_many` + /// on the completion port above. These are then processed to run callbacks + /// which figure out what to do after the event is done. + statuses: Box<[CompletionStatus]>, + + /// Literal events returned by `get` to the upwards `EventLoop`. This file + /// doesn't really modify this (except for the awakener), instead almost all + /// events are filled in by the `ReadinessQueue` from the `poll` module. + events: Vec, +} + +impl Events { + pub fn with_capacity(cap: usize) -> Events { + // Note that it's possible for the output `events` to grow beyond the + // capacity as it can also include deferred events, but that's certainly + // not the end of the world! + Events { + statuses: vec![CompletionStatus::zero(); cap].into_boxed_slice(), + events: Vec::with_capacity(cap), + } + } + + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + + pub fn len(&self) -> usize { + self.events.len() + } + + pub fn capacity(&self) -> usize { + self.events.capacity() + } + + pub fn get(&self, idx: usize) -> Option { + self.events.get(idx).map(|e| *e) + } + + pub fn push_event(&mut self, event: Event) { + self.events.push(event); + } + + pub fn clear(&mut self) { + self.events.truncate(0); + } +} + +macro_rules! overlapped2arc { + ($e:expr, $t:ty, $($field:ident).+) => ({ + let offset = offset_of!($t, $($field).+); + debug_assert!(offset < mem::size_of::<$t>()); + FromRawArc::from_raw(($e as usize - offset) as *mut $t) + }) +} + +macro_rules! offset_of { + ($t:ty, $($field:ident).+) => ( + &(*(0 as *const $t)).$($field).+ as *const _ as usize + ) +} + +// See sys::windows module docs for why this exists. +// +// The gist of it is that `Selector` assumes that all `OVERLAPPED` pointers are +// actually inside one of these structures so it can use the `Callback` stored +// right after it. +// +// We use repr(C) here to ensure that we can assume the overlapped pointer is +// at the start of the structure so we can just do a cast. +/// A wrapper around an internal instance over `miow::Overlapped` which is in +/// turn a wrapper around the Windows type `OVERLAPPED`. +/// +/// This type is required to be used for all IOCP operations on handles that are +/// registered with an event loop. The event loop will receive notifications +/// over `OVERLAPPED` pointers that have completed, and it will cast that +/// pointer to a pointer to this structure and invoke the associated callback. +#[repr(C)] +pub struct Overlapped { + inner: UnsafeCell, + callback: fn(&OVERLAPPED_ENTRY), +} + +impl Overlapped { + /// Creates a new `Overlapped` which will invoke the provided `cb` callback + /// whenever it's triggered. + /// + /// The returned `Overlapped` must be used as the `OVERLAPPED` passed to all + /// I/O operations that are registered with mio's event loop. When the I/O + /// operation associated with an `OVERLAPPED` pointer completes the event + /// loop will invoke the function pointer provided by `cb`. + pub fn new(cb: fn(&OVERLAPPED_ENTRY)) -> Overlapped { + Overlapped { + inner: UnsafeCell::new(miow::Overlapped::zero()), + callback: cb, + } + } + + /// Get the underlying `Overlapped` instance as a raw pointer. + /// + /// This can be useful when only a shared borrow is held and the overlapped + /// pointer needs to be passed down to winapi. + pub fn as_mut_ptr(&self) -> *mut OVERLAPPED { + unsafe { + (*self.inner.get()).raw() + } + } +} + +impl fmt::Debug for Overlapped { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Overlapped") + .finish() + } +} + +// Overlapped's APIs are marked as unsafe Overlapped's APIs are marked as +// unsafe as they must be used with caution to ensure thread safety. The +// structure itself is safe to send across threads. +unsafe impl Send for Overlapped {} +unsafe impl Sync for Overlapped {} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/tcp.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/tcp.rs new file mode 100644 index 0000000..f2ab39f --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/tcp.rs @@ -0,0 +1,851 @@ +use std::fmt; +use std::io::{self, Read, ErrorKind}; +use std::mem; +use std::net::{self, SocketAddr, Shutdown}; +use std::os::windows::prelude::*; +use std::sync::{Mutex, MutexGuard}; +use std::time::Duration; + +use miow::iocp::CompletionStatus; +use miow::net::*; +use net2::{TcpBuilder, TcpStreamExt as Net2TcpExt}; +use winapi::*; +use iovec::IoVec; + +use {poll, Ready, Poll, PollOpt, Token}; +use event::Evented; +use sys::windows::from_raw_arc::FromRawArc; +use sys::windows::selector::{Overlapped, ReadyBinding}; +use sys::windows::Family; + +pub struct TcpStream { + /// Separately stored implementation to ensure that the `Drop` + /// implementation on this type is only executed when it's actually dropped + /// (many clones of this `imp` are made). + imp: StreamImp, + registration: Mutex>, +} + +pub struct TcpListener { + imp: ListenerImp, + registration: Mutex>, +} + +#[derive(Clone)] +struct StreamImp { + /// A stable address and synchronized access for all internals. This serves + /// to ensure that all `Overlapped` pointers are valid for a long period of + /// time as well as allowing completion callbacks to have access to the + /// internals without having ownership. + /// + /// Note that the reference count also allows us "loan out" copies to + /// completion ports while I/O is running to guarantee that this stays alive + /// until the I/O completes. You'll notice a number of calls to + /// `mem::forget` below, and these only happen on successful scheduling of + /// I/O and are paired with `overlapped2arc!` macro invocations in the + /// completion callbacks (to have a decrement match the increment). + inner: FromRawArc, +} + +#[derive(Clone)] +struct ListenerImp { + inner: FromRawArc, +} + +struct StreamIo { + inner: Mutex, + read: Overlapped, // also used for connect + write: Overlapped, + socket: net::TcpStream, +} + +struct ListenerIo { + inner: Mutex, + accept: Overlapped, + family: Family, + socket: net::TcpListener, +} + +struct StreamInner { + iocp: ReadyBinding, + deferred_connect: Option, + read: State<(), ()>, + write: State<(Vec, usize), (Vec, usize)>, + /// whether we are instantly notified of success + /// (FILE_SKIP_COMPLETION_PORT_ON_SUCCESS, + /// without a roundtrip through the event loop) + instant_notify: bool, +} + +struct ListenerInner { + iocp: ReadyBinding, + accept: State, + accept_buf: AcceptAddrsBuf, + instant_notify: bool, +} + +enum State { + Empty, // no I/O operation in progress + Pending(T), // an I/O operation is in progress + Ready(U), // I/O has finished with this value + Error(io::Error), // there was an I/O error +} + +impl TcpStream { + fn new(socket: net::TcpStream, + deferred_connect: Option) -> TcpStream { + TcpStream { + registration: Mutex::new(None), + imp: StreamImp { + inner: FromRawArc::new(StreamIo { + read: Overlapped::new(read_done), + write: Overlapped::new(write_done), + socket: socket, + inner: Mutex::new(StreamInner { + iocp: ReadyBinding::new(), + deferred_connect: deferred_connect, + read: State::Empty, + write: State::Empty, + instant_notify: false, + }), + }), + }, + } + } + + pub fn connect(socket: net::TcpStream, addr: &SocketAddr) + -> io::Result { + socket.set_nonblocking(true)?; + Ok(TcpStream::new(socket, Some(*addr))) + } + + pub fn from_stream(stream: net::TcpStream) -> TcpStream { + TcpStream::new(stream, None) + } + + pub fn peer_addr(&self) -> io::Result { + self.imp.inner.socket.peer_addr() + } + + pub fn local_addr(&self) -> io::Result { + self.imp.inner.socket.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.imp.inner.socket.try_clone().map(|s| TcpStream::new(s, None)) + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + self.imp.inner.socket.shutdown(how) + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + self.imp.inner.socket.set_nodelay(nodelay) + } + + pub fn nodelay(&self) -> io::Result { + self.imp.inner.socket.nodelay() + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + self.imp.inner.socket.set_recv_buffer_size(size) + } + + pub fn recv_buffer_size(&self) -> io::Result { + self.imp.inner.socket.recv_buffer_size() + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + self.imp.inner.socket.set_send_buffer_size(size) + } + + pub fn send_buffer_size(&self) -> io::Result { + self.imp.inner.socket.send_buffer_size() + } + + pub fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { + self.imp.inner.socket.set_keepalive(keepalive) + } + + pub fn keepalive(&self) -> io::Result> { + self.imp.inner.socket.keepalive() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.imp.inner.socket.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.imp.inner.socket.ttl() + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.imp.inner.socket.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.imp.inner.socket.only_v6() + } + + pub fn set_linger(&self, dur: Option) -> io::Result<()> { + self.imp.inner.socket.set_linger(dur) + } + + pub fn linger(&self) -> io::Result> { + self.imp.inner.socket.linger() + } + + pub fn take_error(&self) -> io::Result> { + if let Some(e) = self.imp.inner.socket.take_error()? { + return Ok(Some(e)) + } + + // If the syscall didn't return anything then also check to see if we've + // squirreled away an error elsewhere for example as part of a connect + // operation. + // + // Typically this is used like so: + // + // 1. A `connect` is issued + // 2. Wait for the socket to be writable + // 3. Call `take_error` to see if the connect succeeded. + // + // Right now the `connect` operation finishes in `read_done` below and + // fill will in `State::Error` in the `read` slot if it fails, so we + // extract that here. + let mut me = self.inner(); + match mem::replace(&mut me.read, State::Empty) { + State::Error(e) => { + self.imp.schedule_read(&mut me); + Ok(Some(e)) + } + other => { + me.read = other; + Ok(None) + } + } + } + + fn inner(&self) -> MutexGuard { + self.imp.inner() + } + + fn before_read(&self) -> io::Result> { + let mut me = self.inner(); + + match me.read { + // Empty == we're not associated yet, and if we're pending then + // these are both cases where we return "would block" + State::Empty | + State::Pending(()) => return Err(io::ErrorKind::WouldBlock.into()), + + // If we got a delayed error as part of a `read_overlapped` below, + // return that here. Also schedule another read in case it was + // transient. + State::Error(_) => { + let e = match mem::replace(&mut me.read, State::Empty) { + State::Error(e) => e, + _ => panic!(), + }; + self.imp.schedule_read(&mut me); + return Err(e) + } + + // If we're ready for a read then some previous 0-byte read has + // completed. In that case the OS's socket buffer has something for + // us, so we just keep pulling out bytes while we can in the loop + // below. + State::Ready(()) => {} + } + + Ok(me) + } + + fn post_register(&self, interest: Ready, me: &mut StreamInner) { + if interest.is_readable() { + self.imp.schedule_read(me); + } + + // At least with epoll, if a socket is registered with an interest in + // writing and it's immediately writable then a writable event is + // generated immediately, so do so here. + if interest.is_writable() { + if let State::Empty = me.write { + self.imp.add_readiness(me, Ready::writable()); + } + } + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + match IoVec::from_bytes_mut(buf) { + Some(vec) => self.readv(&mut [vec]), + None => Ok(0), + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result { + let mut me = self.before_read()?; + + match (&self.imp.inner.socket).peek(buf) { + Ok(n) => Ok(n), + Err(e) => { + me.read = State::Empty; + self.imp.schedule_read(&mut me); + Err(e) + } + } + } + + pub fn readv(&self, bufs: &mut [&mut IoVec]) -> io::Result { + let mut me = self.before_read()?; + + // TODO: Does WSARecv work on a nonblocking sockets? We ideally want to + // call that instead of looping over all the buffers and calling + // `recv` on each buffer. I'm not sure though if an overlapped + // socket in nonblocking mode would work with that use case, + // however, so for now we just call `recv`. + + let mut amt = 0; + for buf in bufs { + match (&self.imp.inner.socket).read(buf) { + // If we did a partial read, then return what we've read so far + Ok(n) if n < buf.len() => return Ok(amt + n), + + // Otherwise filled this buffer entirely, so try to fill the + // next one as well. + Ok(n) => amt += n, + + // If we hit an error then things get tricky if we've already + // read some data. If the error is "would block" then we just + // return the data we've read so far while scheduling another + // 0-byte read. + // + // If we've read data and the error kind is not "would block", + // then we stash away the error to get returned later and return + // the data that we've read. + // + // Finally if we haven't actually read any data we just + // reschedule a 0-byte read to happen again and then return the + // error upwards. + Err(e) => { + if amt > 0 && e.kind() == io::ErrorKind::WouldBlock { + me.read = State::Empty; + self.imp.schedule_read(&mut me); + return Ok(amt) + } else if amt > 0 { + me.read = State::Error(e); + return Ok(amt) + } else { + me.read = State::Empty; + self.imp.schedule_read(&mut me); + return Err(e) + } + } + } + } + + Ok(amt) + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + match IoVec::from_bytes(buf) { + Some(vec) => self.writev(&[vec]), + None => Ok(0), + } + } + + pub fn writev(&self, bufs: &[&IoVec]) -> io::Result { + let mut me = self.inner(); + let me = &mut *me; + + match mem::replace(&mut me.write, State::Empty) { + State::Empty => {} + State::Error(e) => return Err(e), + other => { + me.write = other; + return Err(io::ErrorKind::WouldBlock.into()) + } + } + + if !me.iocp.registered() { + return Err(io::ErrorKind::WouldBlock.into()) + } + + if bufs.is_empty() { + return Ok(0) + } + + let len = bufs.iter().map(|b| b.len()).fold(0, |a, b| a + b); + let mut intermediate = me.iocp.get_buffer(len); + for buf in bufs { + intermediate.extend_from_slice(buf); + } + self.imp.schedule_write(intermediate, 0, me); + Ok(len) + } + + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } +} + +impl StreamImp { + fn inner(&self) -> MutexGuard { + self.inner.inner.lock().unwrap() + } + + fn schedule_connect(&self, addr: &SocketAddr) -> io::Result<()> { + unsafe { + trace!("scheduling a connect"); + self.inner.socket.connect_overlapped(addr, &[], self.inner.read.as_mut_ptr())?; + } + // see docs above on StreamImp.inner for rationale on forget + mem::forget(self.clone()); + Ok(()) + } + + /// Schedule a read to happen on this socket, enqueuing us to receive a + /// notification when a read is ready. + /// + /// Note that this does *not* work with a buffer. When reading a TCP stream + /// we actually read into a 0-byte buffer so Windows will send us a + /// notification when the socket is otherwise ready for reading. This allows + /// us to avoid buffer allocations for in-flight reads. + fn schedule_read(&self, me: &mut StreamInner) { + match me.read { + State::Empty => {} + State::Ready(_) | State::Error(_) => { + self.add_readiness(me, Ready::readable()); + return; + } + _ => return, + } + + me.iocp.set_readiness(me.iocp.readiness() - Ready::readable()); + + trace!("scheduling a read"); + let res = unsafe { + self.inner.socket.read_overlapped(&mut [], self.inner.read.as_mut_ptr()) + }; + match res { + // Note that `Ok(true)` means that this completed immediately and + // our socket is readable. This typically means that the caller of + // this function (likely `read` above) can try again as an + // optimization and return bytes quickly. + // + // Normally, though, although the read completed immediately + // there's still an IOCP completion packet enqueued that we're going + // to receive. + // + // You can configure this behavior (miow) with + // SetFileCompletionNotificationModes to indicate that `Ok(true)` + // does **not** enqueue a completion packet. (This is the case + // for me.instant_notify) + // + // Note that apparently libuv has scary code to work around bugs in + // `WSARecv` for UDP sockets apparently for handles which have had + // the `SetFileCompletionNotificationModes` function called on them, + // worth looking into! + Ok(Some(_)) if me.instant_notify => { + me.read = State::Ready(()); + self.add_readiness(me, Ready::readable()); + } + Ok(_) => { + // see docs above on StreamImp.inner for rationale on forget + me.read = State::Pending(()); + mem::forget(self.clone()); + } + Err(e) => { + me.read = State::Error(e); + self.add_readiness(me, Ready::readable()); + } + } + } + + /// Similar to `schedule_read`, except that this issues, well, writes. + /// + /// This function will continually attempt to write the entire contents of + /// the buffer `buf` until they have all been written. The `pos` argument is + /// the current offset within the buffer up to which the contents have + /// already been written. + /// + /// A new writable event (e.g. allowing another write) will only happen once + /// the buffer has been written completely (or hit an error). + fn schedule_write(&self, + buf: Vec, + mut pos: usize, + me: &mut StreamInner) { + + // About to write, clear any pending level triggered events + me.iocp.set_readiness(me.iocp.readiness() - Ready::writable()); + + loop { + trace!("scheduling a write of {} bytes", buf[pos..].len()); + let ret = unsafe { + self.inner.socket.write_overlapped(&buf[pos..], self.inner.write.as_mut_ptr()) + }; + match ret { + Ok(Some(transferred_bytes)) if me.instant_notify => { + trace!("done immediately with {} bytes", transferred_bytes); + if transferred_bytes == buf.len() - pos { + self.add_readiness(me, Ready::writable()); + me.write = State::Empty; + break; + } + pos += transferred_bytes; + } + Ok(_) => { + trace!("scheduled for later"); + // see docs above on StreamImp.inner for rationale on forget + me.write = State::Pending((buf, pos)); + mem::forget(self.clone()); + break; + } + Err(e) => { + trace!("write error: {}", e); + me.write = State::Error(e); + self.add_readiness(me, Ready::writable()); + me.iocp.put_buffer(buf); + break; + } + } + } + } + + /// Pushes an event for this socket onto the selector its registered for. + /// + /// When an event is generated on this socket, if it happened after the + /// socket was closed then we don't want to actually push the event onto our + /// selector as otherwise it's just a spurious notification. + fn add_readiness(&self, me: &mut StreamInner, set: Ready) { + me.iocp.set_readiness(set | me.iocp.readiness()); + } +} + +fn read_done(status: &OVERLAPPED_ENTRY) { + let status = CompletionStatus::from_entry(status); + let me2 = StreamImp { + inner: unsafe { overlapped2arc!(status.overlapped(), StreamIo, read) }, + }; + + let mut me = me2.inner(); + match mem::replace(&mut me.read, State::Empty) { + State::Pending(()) => { + trace!("finished a read: {}", status.bytes_transferred()); + assert_eq!(status.bytes_transferred(), 0); + me.read = State::Ready(()); + return me2.add_readiness(&mut me, Ready::readable()) + } + s => me.read = s, + } + + // If a read didn't complete, then the connect must have just finished. + trace!("finished a connect"); + + // By guarding with socket.result(), we ensure that a connection + // was successfully made before performing operations requiring a + // connected socket. + match unsafe { me2.inner.socket.result(status.overlapped()) } + .and_then(|_| me2.inner.socket.connect_complete()) + { + Ok(()) => { + me2.add_readiness(&mut me, Ready::writable()); + me2.schedule_read(&mut me); + } + Err(e) => { + me2.add_readiness(&mut me, Ready::readable() | Ready::writable()); + me.read = State::Error(e); + } + } +} + +fn write_done(status: &OVERLAPPED_ENTRY) { + let status = CompletionStatus::from_entry(status); + trace!("finished a write {}", status.bytes_transferred()); + let me2 = StreamImp { + inner: unsafe { overlapped2arc!(status.overlapped(), StreamIo, write) }, + }; + let mut me = me2.inner(); + let (buf, pos) = match mem::replace(&mut me.write, State::Empty) { + State::Pending(pair) => pair, + _ => unreachable!(), + }; + let new_pos = pos + (status.bytes_transferred() as usize); + if new_pos == buf.len() { + me2.add_readiness(&mut me, Ready::writable()); + } else { + me2.schedule_write(buf, new_pos, &mut me); + } +} + +impl Evented for TcpStream { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.register_socket(&self.imp.inner.socket, poll, token, + interest, opts, &self.registration)?; + + unsafe { + super::no_notify_on_instant_completion(self.imp.inner.socket.as_raw_socket() as HANDLE)?; + me.instant_notify = true; + } + + // If we were connected before being registered process that request + // here and go along our merry ways. Note that the callback for a + // successful connect will worry about generating writable/readable + // events and scheduling a new read. + if let Some(addr) = me.deferred_connect.take() { + return self.imp.schedule_connect(&addr).map(|_| ()) + } + self.post_register(interest, &mut me); + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.reregister_socket(&self.imp.inner.socket, poll, token, + interest, opts, &self.registration)?; + self.post_register(interest, &mut me); + Ok(()) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner().iocp.deregister(&self.imp.inner.socket, + poll, &self.registration) + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("TcpStream") + .finish() + } +} + +impl Drop for TcpStream { + fn drop(&mut self) { + // If we're still internally reading, we're no longer interested. Note + // though that we don't cancel any writes which may have been issued to + // preserve the same semantics as Unix. + // + // Note that "Empty" here may mean that a connect is pending, so we + // cancel even if that happens as well. + unsafe { + match self.inner().read { + State::Pending(_) | State::Empty => { + trace!("cancelling active TCP read"); + drop(super::cancel(&self.imp.inner.socket, + &self.imp.inner.read)); + } + State::Ready(_) | State::Error(_) => {} + } + } + } +} + +impl TcpListener { + pub fn new(socket: net::TcpListener) + -> io::Result { + let addr = socket.local_addr()?; + Ok(TcpListener::new_family(socket, match addr { + SocketAddr::V4(..) => Family::V4, + SocketAddr::V6(..) => Family::V6, + })) + } + + fn new_family(socket: net::TcpListener, family: Family) -> TcpListener { + TcpListener { + registration: Mutex::new(None), + imp: ListenerImp { + inner: FromRawArc::new(ListenerIo { + accept: Overlapped::new(accept_done), + family: family, + socket: socket, + inner: Mutex::new(ListenerInner { + iocp: ReadyBinding::new(), + accept: State::Empty, + accept_buf: AcceptAddrsBuf::new(), + instant_notify: false, + }), + }), + }, + } + } + + pub fn accept(&self) -> io::Result<(net::TcpStream, SocketAddr)> { + let mut me = self.inner(); + + let ret = match mem::replace(&mut me.accept, State::Empty) { + State::Empty => return Err(io::ErrorKind::WouldBlock.into()), + State::Pending(t) => { + me.accept = State::Pending(t); + return Err(io::ErrorKind::WouldBlock.into()); + } + State::Ready((s, a)) => Ok((s, a)), + State::Error(e) => Err(e), + }; + + self.imp.schedule_accept(&mut me); + + return ret + } + + pub fn local_addr(&self) -> io::Result { + self.imp.inner.socket.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.imp.inner.socket.try_clone().map(|s| { + TcpListener::new_family(s, self.imp.inner.family) + }) + } + + #[allow(deprecated)] + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.imp.inner.socket.set_only_v6(only_v6) + } + + #[allow(deprecated)] + pub fn only_v6(&self) -> io::Result { + self.imp.inner.socket.only_v6() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.imp.inner.socket.set_ttl(ttl) + } + + pub fn ttl(&self) -> io::Result { + self.imp.inner.socket.ttl() + } + + pub fn take_error(&self) -> io::Result> { + self.imp.inner.socket.take_error() + } + + fn inner(&self) -> MutexGuard { + self.imp.inner() + } +} + +impl ListenerImp { + fn inner(&self) -> MutexGuard { + self.inner.inner.lock().unwrap() + } + + fn schedule_accept(&self, me: &mut ListenerInner) { + match me.accept { + State::Empty => {} + _ => return + } + + me.iocp.set_readiness(me.iocp.readiness() - Ready::readable()); + + let res = match self.inner.family { + Family::V4 => TcpBuilder::new_v4(), + Family::V6 => TcpBuilder::new_v6(), + }.and_then(|builder| unsafe { + trace!("scheduling an accept"); + self.inner.socket.accept_overlapped(&builder, &mut me.accept_buf, + self.inner.accept.as_mut_ptr()) + }); + match res { + Ok((socket, _)) => { + // see docs above on StreamImp.inner for rationale on forget + me.accept = State::Pending(socket); + mem::forget(self.clone()); + } + Err(e) => { + me.accept = State::Error(e); + self.add_readiness(me, Ready::readable()); + } + } + } + + // See comments in StreamImp::push + fn add_readiness(&self, me: &mut ListenerInner, set: Ready) { + me.iocp.set_readiness(set | me.iocp.readiness()); + } +} + +fn accept_done(status: &OVERLAPPED_ENTRY) { + let status = CompletionStatus::from_entry(status); + let me2 = ListenerImp { + inner: unsafe { overlapped2arc!(status.overlapped(), ListenerIo, accept) }, + }; + + let mut me = me2.inner(); + let socket = match mem::replace(&mut me.accept, State::Empty) { + State::Pending(s) => s, + _ => unreachable!(), + }; + trace!("finished an accept"); + let result = me2.inner.socket.accept_complete(&socket).and_then(|()| { + me.accept_buf.parse(&me2.inner.socket) + }).and_then(|buf| { + buf.remote().ok_or_else(|| { + io::Error::new(ErrorKind::Other, "could not obtain remote address") + }) + }); + me.accept = match result { + Ok(remote_addr) => State::Ready((socket, remote_addr)), + Err(e) => State::Error(e), + }; + me2.add_readiness(&mut me, Ready::readable()); +} + +impl Evented for TcpListener { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.register_socket(&self.imp.inner.socket, poll, token, + interest, opts, &self.registration)?; + + unsafe { + super::no_notify_on_instant_completion(self.imp.inner.socket.as_raw_socket() as HANDLE)?; + me.instant_notify = true; + } + + self.imp.schedule_accept(&mut me); + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.reregister_socket(&self.imp.inner.socket, poll, token, + interest, opts, &self.registration)?; + self.imp.schedule_accept(&mut me); + Ok(()) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner().iocp.deregister(&self.imp.inner.socket, + poll, &self.registration) + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("TcpListener") + .finish() + } +} + +impl Drop for TcpListener { + fn drop(&mut self) { + // If we're still internally reading, we're no longer interested. + unsafe { + match self.inner().accept { + State::Pending(_) => { + trace!("cancelling active TCP accept"); + drop(super::cancel(&self.imp.inner.socket, + &self.imp.inner.accept)); + } + State::Empty | + State::Ready(_) | + State::Error(_) => {} + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/udp.rs b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/udp.rs new file mode 100644 index 0000000..4d3fc04 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/sys/windows/udp.rs @@ -0,0 +1,413 @@ +//! UDP for IOCP +//! +//! Note that most of this module is quite similar to the TCP module, so if +//! something seems odd you may also want to try the docs over there. + +use std::fmt; +use std::io::prelude::*; +use std::io; +use std::mem; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; +use std::sync::{Mutex, MutexGuard}; + +#[allow(unused_imports)] +use net2::{UdpBuilder, UdpSocketExt}; +use winapi::*; +use miow::iocp::CompletionStatus; +use miow::net::SocketAddrBuf; +use miow::net::UdpSocketExt as MiowUdpSocketExt; + +use {poll, Ready, Poll, PollOpt, Token}; +use event::Evented; +use sys::windows::from_raw_arc::FromRawArc; +use sys::windows::selector::{Overlapped, ReadyBinding}; + +pub struct UdpSocket { + imp: Imp, + registration: Mutex>, +} + +#[derive(Clone)] +struct Imp { + inner: FromRawArc, +} + +struct Io { + read: Overlapped, + write: Overlapped, + socket: net::UdpSocket, + inner: Mutex, +} + +struct Inner { + iocp: ReadyBinding, + read: State, Vec>, + write: State, (Vec, usize)>, + read_buf: SocketAddrBuf, +} + +enum State { + Empty, + Pending(T), + Ready(U), + Error(io::Error), +} + +impl UdpSocket { + pub fn new(socket: net::UdpSocket) -> io::Result { + Ok(UdpSocket { + registration: Mutex::new(None), + imp: Imp { + inner: FromRawArc::new(Io { + read: Overlapped::new(recv_done), + write: Overlapped::new(send_done), + socket: socket, + inner: Mutex::new(Inner { + iocp: ReadyBinding::new(), + read: State::Empty, + write: State::Empty, + read_buf: SocketAddrBuf::new(), + }), + }), + }, + }) + } + + pub fn local_addr(&self) -> io::Result { + self.imp.inner.socket.local_addr() + } + + pub fn try_clone(&self) -> io::Result { + self.imp.inner.socket.try_clone().and_then(UdpSocket::new) + } + + /// Note that unlike `TcpStream::write` this function will not attempt to + /// continue writing `buf` until its entirely written. + /// + /// TODO: This... may be wrong in the long run. We're reporting that we + /// successfully wrote all of the bytes in `buf` but it's possible + /// that we don't actually end up writing all of them! + pub fn send_to(&self, buf: &[u8], target: &SocketAddr) + -> io::Result { + let mut me = self.inner(); + let me = &mut *me; + + match me.write { + State::Empty => {} + _ => return Err(io::ErrorKind::WouldBlock.into()), + } + + if !me.iocp.registered() { + return Err(io::ErrorKind::WouldBlock.into()) + } + + let interest = me.iocp.readiness(); + me.iocp.set_readiness(interest - Ready::writable()); + + let mut owned_buf = me.iocp.get_buffer(64 * 1024); + let amt = owned_buf.write(buf)?; + unsafe { + trace!("scheduling a send"); + self.imp.inner.socket.send_to_overlapped(&owned_buf, target, + self.imp.inner.write.as_mut_ptr()) + }?; + me.write = State::Pending(owned_buf); + mem::forget(self.imp.clone()); + Ok(amt) + } + + /// Note that unlike `TcpStream::write` this function will not attempt to + /// continue writing `buf` until its entirely written. + /// + /// TODO: This... may be wrong in the long run. We're reporting that we + /// successfully wrote all of the bytes in `buf` but it's possible + /// that we don't actually end up writing all of them! + pub fn send(&self, buf: &[u8]) -> io::Result { + let mut me = self.inner(); + let me = &mut *me; + + match me.write { + State::Empty => {} + _ => return Err(io::ErrorKind::WouldBlock.into()), + } + + if !me.iocp.registered() { + return Err(io::ErrorKind::WouldBlock.into()) + } + + let interest = me.iocp.readiness(); + me.iocp.set_readiness(interest - Ready::writable()); + + let mut owned_buf = me.iocp.get_buffer(64 * 1024); + let amt = owned_buf.write(buf)?; + unsafe { + trace!("scheduling a send"); + self.imp.inner.socket.send_overlapped(&owned_buf, self.imp.inner.write.as_mut_ptr()) + + }?; + me.write = State::Pending(owned_buf); + mem::forget(self.imp.clone()); + Ok(amt) + } + + pub fn recv_from(&self, mut buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + let mut me = self.inner(); + match mem::replace(&mut me.read, State::Empty) { + State::Empty => Err(io::ErrorKind::WouldBlock.into()), + State::Pending(b) => { me.read = State::Pending(b); Err(io::ErrorKind::WouldBlock.into()) } + State::Ready(data) => { + // If we weren't provided enough space to receive the message + // then don't actually read any data, just return an error. + if buf.len() < data.len() { + me.read = State::Ready(data); + Err(io::Error::from_raw_os_error(WSAEMSGSIZE as i32)) + } else { + let r = if let Some(addr) = me.read_buf.to_socket_addr() { + buf.write(&data).unwrap(); + Ok((data.len(), addr)) + } else { + Err(io::Error::new(io::ErrorKind::Other, + "failed to parse socket address")) + }; + me.iocp.put_buffer(data); + self.imp.schedule_read_from(&mut me); + r + } + } + State::Error(e) => { + self.imp.schedule_read_from(&mut me); + Err(e) + } + } + } + + pub fn recv(&self, buf: &mut [u8]) + -> io::Result { + //Since recv_from can be used on connected sockets just call it and drop the address. + self.recv_from(buf).map(|(size,_)| size) + } + + pub fn connect(&self, addr: SocketAddr) -> io::Result<()> { + self.imp.inner.socket.connect(addr) + } + + pub fn broadcast(&self) -> io::Result { + self.imp.inner.socket.broadcast() + } + + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { + self.imp.inner.socket.set_broadcast(on) + } + + pub fn multicast_loop_v4(&self) -> io::Result { + self.imp.inner.socket.multicast_loop_v4() + } + + pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> { + self.imp.inner.socket.set_multicast_loop_v4(on) + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + self.imp.inner.socket.multicast_ttl_v4() + } + + pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> { + self.imp.inner.socket.set_multicast_ttl_v4(ttl) + } + + pub fn multicast_loop_v6(&self) -> io::Result { + self.imp.inner.socket.multicast_loop_v6() + } + + pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> { + self.imp.inner.socket.set_multicast_loop_v6(on) + } + + pub fn ttl(&self) -> io::Result { + self.imp.inner.socket.ttl() + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.imp.inner.socket.set_ttl(ttl) + } + + pub fn join_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.imp.inner.socket.join_multicast_v4(multiaddr, interface) + } + + pub fn join_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.imp.inner.socket.join_multicast_v6(multiaddr, interface) + } + + pub fn leave_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.imp.inner.socket.leave_multicast_v4(multiaddr, interface) + } + + pub fn leave_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.imp.inner.socket.leave_multicast_v6(multiaddr, interface) + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.imp.inner.socket.set_only_v6(only_v6) + } + + pub fn only_v6(&self) -> io::Result { + self.imp.inner.socket.only_v6() + } + + pub fn take_error(&self) -> io::Result> { + self.imp.inner.socket.take_error() + } + + fn inner(&self) -> MutexGuard { + self.imp.inner() + } + + fn post_register(&self, interest: Ready, me: &mut Inner) { + if interest.is_readable() { + //We use recv_from here since it is well specified for both + //connected and non-connected sockets and we can discard the address + //when calling recv(). + self.imp.schedule_read_from(me); + } + // See comments in TcpSocket::post_register for what's going on here + if interest.is_writable() { + if let State::Empty = me.write { + self.imp.add_readiness(me, Ready::writable()); + } + } + } +} + +impl Imp { + fn inner(&self) -> MutexGuard { + self.inner.inner.lock().unwrap() + } + + fn schedule_read_from(&self, me: &mut Inner) { + match me.read { + State::Empty => {} + _ => return, + } + + let interest = me.iocp.readiness(); + me.iocp.set_readiness(interest - Ready::readable()); + + let mut buf = me.iocp.get_buffer(64 * 1024); + let res = unsafe { + trace!("scheduling a read"); + let cap = buf.capacity(); + buf.set_len(cap); + self.inner.socket.recv_from_overlapped(&mut buf, &mut me.read_buf, + self.inner.read.as_mut_ptr()) + }; + match res { + Ok(_) => { + me.read = State::Pending(buf); + mem::forget(self.clone()); + } + Err(e) => { + me.read = State::Error(e); + self.add_readiness(me, Ready::readable()); + me.iocp.put_buffer(buf); + } + } + } + + // See comments in tcp::StreamImp::push + fn add_readiness(&self, me: &Inner, set: Ready) { + me.iocp.set_readiness(set | me.iocp.readiness()); + } +} + +impl Evented for UdpSocket { + fn register(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.register_socket(&self.imp.inner.socket, + poll, token, interest, opts, + &self.registration)?; + self.post_register(interest, &mut me); + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, + interest: Ready, opts: PollOpt) -> io::Result<()> { + let mut me = self.inner(); + me.iocp.reregister_socket(&self.imp.inner.socket, + poll, token, interest, + opts, &self.registration)?; + self.post_register(interest, &mut me); + Ok(()) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.inner().iocp.deregister(&self.imp.inner.socket, + poll, &self.registration) + } +} + +impl fmt::Debug for UdpSocket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("UdpSocket") + .finish() + } +} + +impl Drop for UdpSocket { + fn drop(&mut self) { + let inner = self.inner(); + + // If we're still internally reading, we're no longer interested. Note + // though that we don't cancel any writes which may have been issued to + // preserve the same semantics as Unix. + unsafe { + match inner.read { + State::Pending(_) => { + drop(super::cancel(&self.imp.inner.socket, + &self.imp.inner.read)); + } + State::Empty | + State::Ready(_) | + State::Error(_) => {} + } + } + } +} + +fn send_done(status: &OVERLAPPED_ENTRY) { + let status = CompletionStatus::from_entry(status); + trace!("finished a send {}", status.bytes_transferred()); + let me2 = Imp { + inner: unsafe { overlapped2arc!(status.overlapped(), Io, write) }, + }; + let mut me = me2.inner(); + me.write = State::Empty; + me2.add_readiness(&mut me, Ready::writable()); +} + +fn recv_done(status: &OVERLAPPED_ENTRY) { + let status = CompletionStatus::from_entry(status); + trace!("finished a recv {}", status.bytes_transferred()); + let me2 = Imp { + inner: unsafe { overlapped2arc!(status.overlapped(), Io, read) }, + }; + let mut me = me2.inner(); + let mut buf = match mem::replace(&mut me.read, State::Empty) { + State::Pending(buf) => buf, + _ => unreachable!(), + }; + unsafe { + buf.set_len(status.bytes_transferred() as usize); + } + me.read = State::Ready(buf); + me2.add_readiness(&mut me, Ready::readable()); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/timer.rs b/third_party/cargo/vendor/mio-0.6.21/src/timer.rs new file mode 100644 index 0000000..c591be5 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/timer.rs @@ -0,0 +1,516 @@ +//! Timer optimized for I/O related operations + +#![allow(deprecated, missing_debug_implementations)] + +use {convert, io, Ready, Poll, PollOpt, Registration, SetReadiness, Token}; +use event::Evented; +use lazycell::LazyCell; +use slab::Slab; +use std::{cmp, error, fmt, u64, usize, iter, thread}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +use self::TimerErrorKind::TimerOverflow; + +pub struct Timer { + // Size of each tick in milliseconds + tick_ms: u64, + // Slab of timeout entries + entries: Slab>, + // Timeout wheel. Each tick, the timer will look at the next slot for + // timeouts that match the current tick. + wheel: Vec, + // Tick 0's time instant + start: Instant, + // The current tick + tick: Tick, + // The next entry to possibly timeout + next: Token, + // Masks the target tick to get the slot + mask: u64, + // Set on registration with Poll + inner: LazyCell, +} + +pub struct Builder { + // Approximate duration of each tick + tick: Duration, + // Number of slots in the timer wheel + num_slots: usize, + // Max number of timeouts that can be in flight at a given time. + capacity: usize, +} + +#[derive(Clone, Debug)] +pub struct Timeout { + // Reference into the timer entry slab + token: Token, + // Tick that it should match up with + tick: u64, +} + +struct Inner { + registration: Registration, + set_readiness: SetReadiness, + wakeup_state: WakeupState, + wakeup_thread: thread::JoinHandle<()>, +} + +impl Drop for Inner { + fn drop(&mut self) { + // 1. Set wakeup state to TERMINATE_THREAD (https://github.com/carllerche/mio/blob/master/src/timer.rs#L451) + self.wakeup_state.store(TERMINATE_THREAD, Ordering::Release); + // 2. Wake him up + self.wakeup_thread.thread().unpark(); + } +} + +#[derive(Copy, Clone, Debug)] +struct WheelEntry { + next_tick: Tick, + head: Token, +} + +// Doubly linked list of timer entries. Allows for efficient insertion / +// removal of timeouts. +struct Entry { + state: T, + links: EntryLinks, +} + +#[derive(Copy, Clone)] +struct EntryLinks { + tick: Tick, + prev: Token, + next: Token +} + +type Tick = u64; + +const TICK_MAX: Tick = u64::MAX; + +// Manages communication with wakeup thread +type WakeupState = Arc; + +pub type Result = ::std::result::Result; +// TODO: remove +pub type TimerResult = Result; + + +/// Deprecated and unused. +#[derive(Debug)] +pub struct TimerError; + +/// Deprecated and unused. +#[derive(Debug)] +pub enum TimerErrorKind { + TimerOverflow, +} + +// TODO: Remove +pub type OldTimerResult = Result; + +const TERMINATE_THREAD: usize = 0; +const EMPTY: Token = Token(usize::MAX); + +impl Builder { + pub fn tick_duration(mut self, duration: Duration) -> Builder { + self.tick = duration; + self + } + + pub fn num_slots(mut self, num_slots: usize) -> Builder { + self.num_slots = num_slots; + self + } + + pub fn capacity(mut self, capacity: usize) -> Builder { + self.capacity = capacity; + self + } + + pub fn build(self) -> Timer { + Timer::new(convert::millis(self.tick), self.num_slots, self.capacity, Instant::now()) + } +} + +impl Default for Builder { + fn default() -> Builder { + Builder { + tick: Duration::from_millis(100), + num_slots: 256, + capacity: 65_536, + } + } +} + +impl Timer { + fn new(tick_ms: u64, num_slots: usize, capacity: usize, start: Instant) -> Timer { + let num_slots = num_slots.next_power_of_two(); + let capacity = capacity.next_power_of_two(); + let mask = (num_slots as u64) - 1; + let wheel = iter::repeat(WheelEntry { next_tick: TICK_MAX, head: EMPTY }) + .take(num_slots).collect(); + + Timer { + tick_ms, + entries: Slab::with_capacity(capacity), + wheel, + start, + tick: 0, + next: EMPTY, + mask, + inner: LazyCell::new(), + } + } + + pub fn set_timeout(&mut self, delay_from_now: Duration, state: T) -> Result { + let delay_from_start = self.start.elapsed() + delay_from_now; + self.set_timeout_at(delay_from_start, state) + } + + fn set_timeout_at(&mut self, delay_from_start: Duration, state: T) -> Result { + let mut tick = duration_to_tick(delay_from_start, self.tick_ms); + trace!("setting timeout; delay={:?}; tick={:?}; current-tick={:?}", delay_from_start, tick, self.tick); + + // Always target at least 1 tick in the future + if tick <= self.tick { + tick = self.tick + 1; + } + + self.insert(tick, state) + } + + fn insert(&mut self, tick: Tick, state: T) -> Result { + // Get the slot for the requested tick + let slot = (tick & self.mask) as usize; + let curr = self.wheel[slot]; + + // Insert the new entry + let entry = Entry::new(state, tick, curr.head); + let token = Token(self.entries.insert(entry)); + + if curr.head != EMPTY { + // If there was a previous entry, set its prev pointer to the new + // entry + self.entries[curr.head.into()].links.prev = token; + } + + // Update the head slot + self.wheel[slot] = WheelEntry { + next_tick: cmp::min(tick, curr.next_tick), + head: token, + }; + + self.schedule_readiness(tick); + + trace!("inserted timeout; slot={}; token={:?}", slot, token); + + // Return the new timeout + Ok(Timeout { + token, + tick + }) + } + + pub fn cancel_timeout(&mut self, timeout: &Timeout) -> Option { + let links = match self.entries.get(timeout.token.into()) { + Some(e) => e.links, + None => return None + }; + + // Sanity check + if links.tick != timeout.tick { + return None; + } + + self.unlink(&links, timeout.token); + Some(self.entries.remove(timeout.token.into()).state) + } + + pub fn poll(&mut self) -> Option { + let target_tick = current_tick(self.start, self.tick_ms); + self.poll_to(target_tick) + } + + fn poll_to(&mut self, mut target_tick: Tick) -> Option { + trace!("tick_to; target_tick={}; current_tick={}", target_tick, self.tick); + + if target_tick < self.tick { + target_tick = self.tick; + } + + while self.tick <= target_tick { + let curr = self.next; + + trace!("ticking; curr={:?}", curr); + + if curr == EMPTY { + self.tick += 1; + + let slot = self.slot_for(self.tick); + self.next = self.wheel[slot].head; + + // Handle the case when a slot has a single timeout which gets + // canceled before the timeout expires. In this case, the + // slot's head is EMPTY but there is a value for next_tick. Not + // resetting next_tick here causes the timer to get stuck in a + // loop. + if self.next == EMPTY { + self.wheel[slot].next_tick = TICK_MAX; + } + } else { + let slot = self.slot_for(self.tick); + + if curr == self.wheel[slot].head { + self.wheel[slot].next_tick = TICK_MAX; + } + + let links = self.entries[curr.into()].links; + + if links.tick <= self.tick { + trace!("triggering; token={:?}", curr); + + // Unlink will also advance self.next + self.unlink(&links, curr); + + // Remove and return the token + return Some(self.entries.remove(curr.into()).state); + } else { + let next_tick = self.wheel[slot].next_tick; + self.wheel[slot].next_tick = cmp::min(next_tick, links.tick); + self.next = links.next; + } + } + } + + // No more timeouts to poll + if let Some(inner) = self.inner.borrow() { + trace!("unsetting readiness"); + let _ = inner.set_readiness.set_readiness(Ready::empty()); + + if let Some(tick) = self.next_tick() { + self.schedule_readiness(tick); + } + } + + None + } + + fn unlink(&mut self, links: &EntryLinks, token: Token) { + trace!("unlinking timeout; slot={}; token={:?}", + self.slot_for(links.tick), token); + + if links.prev == EMPTY { + let slot = self.slot_for(links.tick); + self.wheel[slot].head = links.next; + } else { + self.entries[links.prev.into()].links.next = links.next; + } + + if links.next != EMPTY { + self.entries[links.next.into()].links.prev = links.prev; + + if token == self.next { + self.next = links.next; + } + } else if token == self.next { + self.next = EMPTY; + } + } + + fn schedule_readiness(&self, tick: Tick) { + if let Some(inner) = self.inner.borrow() { + // Coordinate setting readiness w/ the wakeup thread + let mut curr = inner.wakeup_state.load(Ordering::Acquire); + + loop { + if curr as Tick <= tick { + // Nothing to do, wakeup is already scheduled + return; + } + + // Attempt to move the wakeup time forward + trace!("advancing the wakeup time; target={}; curr={}", tick, curr); + let actual = inner.wakeup_state.compare_and_swap(curr, tick as usize, Ordering::Release); + + if actual == curr { + // Signal to the wakeup thread that the wakeup time has + // been changed. + trace!("unparking wakeup thread"); + inner.wakeup_thread.thread().unpark(); + return; + } + + curr = actual; + } + } + } + + // Next tick containing a timeout + fn next_tick(&self) -> Option { + if self.next != EMPTY { + let slot = self.slot_for(self.entries[self.next.into()].links.tick); + + if self.wheel[slot].next_tick == self.tick { + // There is data ready right now + return Some(self.tick); + } + } + + self.wheel.iter().map(|e| e.next_tick).min() + } + + fn slot_for(&self, tick: Tick) -> usize { + (self.mask & tick) as usize + } +} + +impl Default for Timer { + fn default() -> Timer { + Builder::default().build() + } +} + +impl Evented for Timer { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + if self.inner.borrow().is_some() { + return Err(io::Error::new(io::ErrorKind::Other, "timer already registered")); + } + + let (registration, set_readiness) = Registration::new(poll, token, interest, opts); + let wakeup_state = Arc::new(AtomicUsize::new(usize::MAX)); + let thread_handle = spawn_wakeup_thread( + wakeup_state.clone(), + set_readiness.clone(), + self.start, self.tick_ms); + + self.inner.fill(Inner { + registration, + set_readiness, + wakeup_state, + wakeup_thread: thread_handle, + }).expect("timer already registered"); + + if let Some(next_tick) = self.next_tick() { + self.schedule_readiness(next_tick); + } + + Ok(()) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + match self.inner.borrow() { + Some(inner) => inner.registration.update(poll, token, interest, opts), + None => Err(io::Error::new(io::ErrorKind::Other, "receiver not registered")), + } + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + match self.inner.borrow() { + Some(inner) => inner.registration.deregister(poll), + None => Err(io::Error::new(io::ErrorKind::Other, "receiver not registered")), + } + } +} + +impl fmt::Debug for Inner { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Inner") + .field("registration", &self.registration) + .field("wakeup_state", &self.wakeup_state.load(Ordering::Relaxed)) + .finish() + } +} + +fn spawn_wakeup_thread(state: WakeupState, set_readiness: SetReadiness, start: Instant, tick_ms: u64) -> thread::JoinHandle<()> { + thread::spawn(move || { + let mut sleep_until_tick = state.load(Ordering::Acquire) as Tick; + + loop { + if sleep_until_tick == TERMINATE_THREAD as Tick { + return; + } + + let now_tick = current_tick(start, tick_ms); + + trace!("wakeup thread: sleep_until_tick={:?}; now_tick={:?}", sleep_until_tick, now_tick); + + if now_tick < sleep_until_tick { + // Calling park_timeout with u64::MAX leads to undefined + // behavior in pthread, causing the park to return immediately + // and causing the thread to tightly spin. Instead of u64::MAX + // on large values, simply use a blocking park. + match tick_ms.checked_mul(sleep_until_tick - now_tick) { + Some(sleep_duration) => { + trace!("sleeping; tick_ms={}; now_tick={}; sleep_until_tick={}; duration={:?}", + tick_ms, now_tick, sleep_until_tick, sleep_duration); + thread::park_timeout(Duration::from_millis(sleep_duration)); + } + None => { + trace!("sleeping; tick_ms={}; now_tick={}; blocking sleep", + tick_ms, now_tick); + thread::park(); + } + } + sleep_until_tick = state.load(Ordering::Acquire) as Tick; + } else { + let actual = state.compare_and_swap(sleep_until_tick as usize, usize::MAX, Ordering::AcqRel) as Tick; + + if actual == sleep_until_tick { + trace!("setting readiness from wakeup thread"); + let _ = set_readiness.set_readiness(Ready::readable()); + sleep_until_tick = usize::MAX as Tick; + } else { + sleep_until_tick = actual as Tick; + } + } + } + }) +} + +fn duration_to_tick(elapsed: Duration, tick_ms: u64) -> Tick { + // Calculate tick rounding up to the closest one + let elapsed_ms = convert::millis(elapsed); + elapsed_ms.saturating_add(tick_ms / 2) / tick_ms +} + +fn current_tick(start: Instant, tick_ms: u64) -> Tick { + duration_to_tick(start.elapsed(), tick_ms) +} + +impl Entry { + fn new(state: T, tick: u64, next: Token) -> Entry { + Entry { + state, + links: EntryLinks { + tick, + prev: EMPTY, + next, + }, + } + } +} + +impl fmt::Display for TimerError { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + // `TimerError` will never be constructed. + unreachable!(); + } +} + +impl error::Error for TimerError { + fn description(&self) -> &str { + // `TimerError` will never be constructed. + unreachable!(); + } +} + +impl fmt::Display for TimerErrorKind { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + TimerOverflow => write!(fmt, "TimerOverflow"), + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/token.rs b/third_party/cargo/vendor/mio-0.6.21/src/token.rs new file mode 100644 index 0000000..09e4245 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/token.rs @@ -0,0 +1,153 @@ +/// Associates readiness notifications with [`Evented`] handles. +/// +/// `Token` is a wrapper around `usize` and is used as an argument to +/// [`Poll::register`] and [`Poll::reregister`]. +/// +/// See [`Poll`] for more documentation on polling. +/// +/// # Example +/// +/// Using `Token` to track which socket generated the notification. In this +/// example, `HashMap` is used, but usually something like [`slab`] is better. +/// +/// ``` +/// # use std::error::Error; +/// # fn try_main() -> Result<(), Box> { +/// use mio::{Events, Ready, Poll, PollOpt, Token}; +/// use mio::net::TcpListener; +/// +/// use std::thread; +/// use std::io::{self, Read}; +/// use std::collections::HashMap; +/// +/// // After this number of sockets is accepted, the server will shutdown. +/// const MAX_SOCKETS: usize = 32; +/// +/// // Pick a token that will not be used by any other socket and use that one +/// // for the listener. +/// const LISTENER: Token = Token(1024); +/// +/// // Used to store the sockets. +/// let mut sockets = HashMap::new(); +/// +/// // This is used to generate a unique token for a socket +/// let mut next_socket_index = 0; +/// +/// // The `Poll` instance +/// let poll = Poll::new()?; +/// +/// // Tcp listener +/// let listener = TcpListener::bind(&"127.0.0.1:0".parse()?)?; +/// +/// // Register the listener +/// poll.register(&listener, +/// LISTENER, +/// Ready::readable(), +/// PollOpt::edge())?; +/// +/// // Spawn a thread that will connect a bunch of sockets then close them +/// let addr = listener.local_addr()?; +/// thread::spawn(move || { +/// use std::net::TcpStream; +/// +/// // +1 here is to connect an extra socket to signal the socket to close +/// for _ in 0..(MAX_SOCKETS+1) { +/// // Connect then drop the socket +/// let _ = TcpStream::connect(&addr).unwrap(); +/// } +/// }); +/// +/// // Event storage +/// let mut events = Events::with_capacity(1024); +/// +/// // Read buffer, this will never actually get filled +/// let mut buf = [0; 256]; +/// +/// // The main event loop +/// loop { +/// // Wait for events +/// poll.poll(&mut events, None)?; +/// +/// for event in &events { +/// match event.token() { +/// LISTENER => { +/// // Perform operations in a loop until `WouldBlock` is +/// // encountered. +/// loop { +/// match listener.accept() { +/// Ok((socket, _)) => { +/// // Shutdown the server +/// if next_socket_index == MAX_SOCKETS { +/// return Ok(()); +/// } +/// +/// // Get the token for the socket +/// let token = Token(next_socket_index); +/// next_socket_index += 1; +/// +/// // Register the new socket w/ poll +/// poll.register(&socket, +/// token, +/// Ready::readable(), +/// PollOpt::edge())?; +/// +/// // Store the socket +/// sockets.insert(token, socket); +/// } +/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { +/// // Socket is not ready anymore, stop accepting +/// break; +/// } +/// e => panic!("err={:?}", e), // Unexpected error +/// } +/// } +/// } +/// token => { +/// // Always operate in a loop +/// loop { +/// match sockets.get_mut(&token).unwrap().read(&mut buf) { +/// Ok(0) => { +/// // Socket is closed, remove it from the map +/// sockets.remove(&token); +/// break; +/// } +/// // Data is not actually sent in this example +/// Ok(_) => unreachable!(), +/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { +/// // Socket is not ready anymore, stop reading +/// break; +/// } +/// e => panic!("err={:?}", e), // Unexpected error +/// } +/// } +/// } +/// } +/// } +/// } +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap(); +/// # } +/// ``` +/// +/// [`Evented`]: event/trait.Evented.html +/// [`Poll`]: struct.Poll.html +/// [`Poll::register`]: struct.Poll.html#method.register +/// [`Poll::reregister`]: struct.Poll.html#method.reregister +/// [`slab`]: https://crates.io/crates/slab +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Token(pub usize); + +impl From for Token { + fn from(val: usize) -> Token { + Token(val) + } +} + +impl From for usize { + fn from(val: Token) -> usize { + val.0 + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/src/udp.rs b/third_party/cargo/vendor/mio-0.6.21/src/udp.rs new file mode 100644 index 0000000..a71bd21 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/src/udp.rs @@ -0,0 +1,326 @@ +//! Primitives for working with UDP +//! +//! The types provided in this module are non-blocking by default and are +//! designed to be portable across all supported Mio platforms. As long as the +//! [portability guidelines] are followed, the behavior should be identical no +//! matter the target platform. +//! +//! [portability guidelines]: ../struct.Poll.html#portability + +#![allow(deprecated)] + +use {sys, Ready, Poll, PollOpt, Token}; +use io::{self, MapNonBlock}; +use event::Evented; +use poll::SelectorId; +use std::net::{self, Ipv4Addr, Ipv6Addr, SocketAddr}; + +/// A User Datagram Protocol socket. +/// +/// This is an implementation of a bound UDP socket. This supports both IPv4 and +/// IPv6 addresses, and there is no corresponding notion of a server because UDP +/// is a datagram protocol. +#[derive(Debug)] +pub struct UdpSocket { + sys: sys::UdpSocket, + selector_id: SelectorId, +} + +impl UdpSocket { + /// Creates a UDP socket from the given address. + pub fn bind(addr: &SocketAddr) -> io::Result { + let socket = net::UdpSocket::bind(addr)?; + UdpSocket::from_socket(socket) + } + + /// Creates a new mio-wrapped socket from an underlying and bound std + /// socket. + /// + /// This function requires that `socket` has previously been bound to an + /// address to work correctly, and returns an I/O object which can be used + /// with mio to send/receive UDP messages. + /// + /// This can be used in conjunction with net2's `UdpBuilder` interface to + /// configure a socket before it's handed off to mio, such as setting + /// options like `reuse_address` or binding to multiple addresses. + pub fn from_socket(socket: net::UdpSocket) -> io::Result { + Ok(UdpSocket { + sys: sys::UdpSocket::new(socket)?, + selector_id: SelectorId::new(), + }) + } + + /// Returns the socket address that this socket was created from. + pub fn local_addr(&self) -> io::Result { + self.sys.local_addr() + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `UdpSocket` is a reference to the same socket that this + /// object references. Both handles will read and write the same port, and + /// options set on one socket will be propagated to the other. + pub fn try_clone(&self) -> io::Result { + self.sys.try_clone() + .map(|s| { + UdpSocket { + sys: s, + selector_id: self.selector_id.clone(), + } + }) + } + + /// Sends data on the socket to the given address. On success, returns the + /// number of bytes written. + /// + /// Address type can be any implementor of `ToSocketAddrs` trait. See its + /// documentation for concrete examples. + pub fn send_to(&self, buf: &[u8], target: &SocketAddr) + -> io::Result> { + self.sys.send_to(buf, target).map_non_block() + } + + /// Receives data from the socket and stores data in the supplied buffer `buf`. On success, + /// returns the number of bytes read and the address from whence the data came. + /// + /// The function must be called with valid byte array `buf` of sufficient size to + /// hold the message bytes. If a message is too long to fit in the supplied buffer, + /// excess bytes may be discarded. + /// + /// The function does not read from `buf`, but is overwriting previous content of `buf`. + /// + /// Assuming the function has read `n` bytes, slicing `&buf[..n]` provides + /// efficient access with iterators and boundary checks. + pub fn recv_from(&self, buf: &mut [u8]) + -> io::Result> { + self.sys.recv_from(buf).map_non_block() + } + + /// Sends data on the socket to the address previously bound via connect(). On success, + /// returns the number of bytes written. + pub fn send(&self, buf: &[u8]) + -> io::Result> { + self.sys.send(buf).map_non_block() + } + + /// Receives data from the socket previously bound with connect() and stores data in + /// the supplied buffer `buf`. On success, returns the number of bytes read. + /// + /// The function must be called with valid byte array `buf` of sufficient size to + /// hold the message bytes. If a message is too long to fit in the supplied buffer, + /// excess bytes may be discarded. + /// + /// The function does not read from `buf`, but is overwriting previous content of `buf`. + /// + /// Assuming the function has read `n` bytes, slicing `&buf[..n]` provides + /// efficient access with iterators and boundary checks. + pub fn recv(&self, buf: &mut [u8]) + -> io::Result> { + self.sys.recv(buf).map_non_block() + } + + /// Connects the UDP socket setting the default destination for `send()` + /// and limiting packets that are read via `recv` from the address specified + /// in `addr`. + pub fn connect(&self, addr: SocketAddr) + -> io::Result<()> { + self.sys.connect(addr) + } + + /// Gets the value of the `SO_BROADCAST` option for this socket. + /// + /// For more information about this option, see + /// [`set_broadcast`][link]. + /// + /// [link]: #method.set_broadcast + pub fn broadcast(&self) -> io::Result { + self.sys.broadcast() + } + + /// Sets the value of the `SO_BROADCAST` option for this socket. + /// + /// When enabled, this socket is allowed to send packets to a broadcast + /// address. + pub fn set_broadcast(&self, on: bool) -> io::Result<()> { + self.sys.set_broadcast(on) + } + + /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v4`][link]. + /// + /// [link]: #method.set_multicast_loop_v4 + pub fn multicast_loop_v4(&self) -> io::Result { + self.sys.multicast_loop_v4() + } + + /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// If enabled, multicast packets will be looped back to the local socket. + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()> { + self.sys.set_multicast_loop_v4(on) + } + + /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_ttl_v4`][link]. + /// + /// [link]: #method.set_multicast_ttl_v4 + pub fn multicast_ttl_v4(&self) -> io::Result { + self.sys.multicast_ttl_v4() + } + + /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// Indicates the time-to-live value of outgoing multicast packets for + /// this socket. The default value is 1 which means that multicast packets + /// don't leave the local network unless explicitly requested. + /// + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> { + self.sys.set_multicast_ttl_v4(ttl) + } + + /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v6`][link]. + /// + /// [link]: #method.set_multicast_loop_v6 + pub fn multicast_loop_v6(&self) -> io::Result { + self.sys.multicast_loop_v6() + } + + /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// Controls whether this socket sees the multicast packets it sends itself. + /// Note that this may not have any affect on IPv4 sockets. + pub fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()> { + self.sys.set_multicast_loop_v6(on) + } + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #method.set_ttl + pub fn ttl(&self) -> io::Result { + self.sys.ttl() + } + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.sys.set_ttl(ttl) + } + + /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// address of the local interface with which the system should join the + /// multicast group. If it's equal to `INADDR_ANY` then an appropriate + /// interface is chosen by the system. + pub fn join_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.sys.join_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// index of the interface to join/leave (or 0 to indicate any interface). + pub fn join_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.sys.join_multicast_v6(multiaddr, interface) + } + + /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v4`][link]. + /// + /// [link]: #method.join_multicast_v4 + pub fn leave_multicast_v4(&self, + multiaddr: &Ipv4Addr, + interface: &Ipv4Addr) -> io::Result<()> { + self.sys.leave_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v6`][link]. + /// + /// [link]: #method.join_multicast_v6 + pub fn leave_multicast_v6(&self, + multiaddr: &Ipv6Addr, + interface: u32) -> io::Result<()> { + self.sys.leave_multicast_v6(multiaddr, interface) + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + self.sys.take_error() + } +} + +impl Evented for UdpSocket { + fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.selector_id.associate_selector(poll)?; + self.sys.register(poll, token, interest, opts) + } + + fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> { + self.sys.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.sys.deregister(poll) + } +} + +/* + * + * ===== UNIX ext ===== + * + */ + +#[cfg(all(unix, not(target_os = "fuchsia")))] +use std::os::unix::io::{IntoRawFd, AsRawFd, FromRawFd, RawFd}; + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl IntoRawFd for UdpSocket { + fn into_raw_fd(self) -> RawFd { + self.sys.into_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl AsRawFd for UdpSocket { + fn as_raw_fd(&self) -> RawFd { + self.sys.as_raw_fd() + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +impl FromRawFd for UdpSocket { + unsafe fn from_raw_fd(fd: RawFd) -> UdpSocket { + UdpSocket { + sys: FromRawFd::from_raw_fd(fd), + selector_id: SelectorId::new(), + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/benchmark.rs b/third_party/cargo/vendor/mio-0.6.21/test/benchmark.rs new file mode 100644 index 0000000..1e4fac5 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/benchmark.rs @@ -0,0 +1,80 @@ +use std::mem; +use mio::net::{AddressFamily, Inet, Inet6, SockAddr, InetAddr, IPv4Addr, SocketType, Dgram, Stream}; +use std::io::net::ip::IpAddr; +use native::NativeTaskBuilder; +use std::task::TaskBuilder; +use mio::os::{from_sockaddr}; +use time::Instant; +use std::vec::*; +use std::io::timer; + +mod nix { + pub use nix::c_int; + pub use nix::fcntl::{Fd, O_NONBLOCK, O_CLOEXEC}; + pub use nix::errno::{EWOULDBLOCK, EINPROGRESS}; + pub use nix::sys::socket::*; + pub use nix::unistd::*; + pub use nix::sys::epoll::*; +} + +fn timed(label: &str, f: ||) { + let start = Instant::now(); + f(); + let elapsed = start.elapsed(); + println!(" {}: {}", label, elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1_000_000_000.0); +} + +fn init(saddr: &str) -> (nix::Fd, nix::Fd) { + let optval = 1i; + let addr = SockAddr::parse(saddr.as_slice()).expect("could not parse InetAddr"); + let srvfd = nix::socket(nix::AF_INET, nix::SOCK_STREAM, nix::SOCK_CLOEXEC).unwrap(); + nix::setsockopt(srvfd, nix::SOL_SOCKET, nix::SO_REUSEADDR, &optval).unwrap(); + nix::bind(srvfd, &from_sockaddr(&addr)).unwrap(); + nix::listen(srvfd, 256u).unwrap(); + + let fd = nix::socket(nix::AF_INET, nix::SOCK_STREAM, nix::SOCK_CLOEXEC | nix::SOCK_NONBLOCK).unwrap(); + let res = nix::connect(fd, &from_sockaddr(&addr)); + let start = Instant::now(); + println!("connecting : {}", res); + + let clifd = nix::accept4(srvfd, nix::SOCK_CLOEXEC | nix::SOCK_NONBLOCK).unwrap(); + let elapsed = start.elapsed(); + println!("accepted : {} - {}", clifd, elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 / 1_000_000_000.0); + + (clifd, srvfd) +} + +#[test] +fn read_bench() { + let (clifd, srvfd) = init("10.10.1.5:11111"); + let mut buf = Vec::with_capacity(1600); + unsafe { buf.set_len(1600); } + timed("read", || { + let mut i = 0u; + while i < 10000000 { + let res = nix::read(clifd, buf.as_mut_slice()); + assert_eq!(res.unwrap_err().kind, nix::EWOULDBLOCK); + i = i + 1; + } + }); +} + +#[test] +fn epollctl_bench() { + let (clifd, srvfd) = init("10.10.1.5:22222"); + + let epfd = nix::epoll_create().unwrap(); + let info = nix::EpollEvent { events: nix::EPOLLIN | nix::EPOLLONESHOT | nix::EPOLLET, + data: 0u64 }; + + nix::epoll_ctl(epfd, nix::EpollCtlAdd, clifd, &info); + + timed("epoll_ctl", || { + let mut i = 0u; + while i < 10000000 { + nix::epoll_ctl(epfd, nix::EpollCtlMod, clifd, &info); + i = i + 1; + } + }); + +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/mod.rs b/third_party/cargo/vendor/mio-0.6.21/test/mod.rs new file mode 100644 index 0000000..e49034f --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/mod.rs @@ -0,0 +1,214 @@ +#![allow(deprecated)] + +extern crate mio; +extern crate bytes; +extern crate net2; + +#[macro_use] +extern crate log; +extern crate env_logger; +extern crate iovec; +extern crate slab; +extern crate tempdir; + +#[cfg(target_os = "fuchsia")] +extern crate fuchsia_zircon as zircon; + +pub use ports::localhost; + +mod test_custom_evented; +mod test_close_on_drop; +mod test_double_register; +mod test_echo_server; +mod test_local_addr_ready; +mod test_multicast; +mod test_oneshot; +mod test_poll; +mod test_register_deregister; +mod test_register_multiple_event_loops; +mod test_reregister_without_poll; +mod test_smoke; +mod test_tcp; +mod test_tcp_level; +mod test_tcp_shutdown; +mod test_udp_level; +mod test_udp_socket; +mod test_write_then_drop; + +#[cfg(feature = "with-deprecated")] +mod test_notify; +#[cfg(feature = "with-deprecated")] +mod test_poll_channel; +#[cfg(feature = "with-deprecated")] +mod test_tick; + +// The following tests are for deprecated features. Only run these tests on +// platforms that were supported from before the features were deprecated +#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] +#[cfg(feature = "with-deprecated")] +mod test_battery; + +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[cfg(feature = "with-deprecated")] +mod test_unix_echo_server; +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[cfg(feature = "with-deprecated")] +mod test_unix_pass_fd; +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[cfg(feature = "with-deprecated")] +mod test_uds_shutdown; +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[cfg(feature = "with-deprecated")] +mod test_subprocess_pipe; +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[cfg(feature = "with-deprecated")] +mod test_broken_pipe; + +#[cfg(any(target_os = "fuchsia"))] +mod test_fuchsia_handles; + +use bytes::{Buf, MutBuf}; +use std::io::{self, Read, Write}; +use std::time::Duration; +use mio::{Events, Poll}; +use mio::event::Event; + +pub trait TryRead { + fn try_read_buf(&mut self, buf: &mut B) -> io::Result> + where Self : Sized + { + // Reads the length of the slice supplied by buf.mut_bytes into the buffer + // This is not guaranteed to consume an entire datagram or segment. + // If your protocol is msg based (instead of continuous stream) you should + // ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo + // frames) + let res = self.try_read(unsafe { buf.mut_bytes() }); + + if let Ok(Some(cnt)) = res { + unsafe { buf.advance(cnt); } + } + + res + } + + fn try_read(&mut self, buf: &mut [u8]) -> io::Result>; +} + +pub trait TryWrite { + fn try_write_buf(&mut self, buf: &mut B) -> io::Result> + where Self : Sized + { + let res = self.try_write(buf.bytes()); + + if let Ok(Some(cnt)) = res { + buf.advance(cnt); + } + + res + } + + fn try_write(&mut self, buf: &[u8]) -> io::Result>; +} + +impl TryRead for T { + fn try_read(&mut self, dst: &mut [u8]) -> io::Result> { + self.read(dst).map_non_block() + } +} + +impl TryWrite for T { + fn try_write(&mut self, src: &[u8]) -> io::Result> { + self.write(src).map_non_block() + } +} + +/* + * + * ===== Helpers ===== + * + */ + +/// A helper trait to provide the map_non_block function on Results. +trait MapNonBlock { + /// Maps a `Result` to a `Result>` by converting + /// operation-would-block errors into `Ok(None)`. + fn map_non_block(self) -> io::Result>; +} + +impl MapNonBlock for io::Result { + fn map_non_block(self) -> io::Result> { + use std::io::ErrorKind::WouldBlock; + + match self { + Ok(value) => Ok(Some(value)), + Err(err) => { + if let WouldBlock = err.kind() { + Ok(None) + } else { + Err(err) + } + } + } + } +} + +mod ports { + use std::net::SocketAddr; + use std::str::FromStr; + use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; + use std::sync::atomic::Ordering::SeqCst; + + // Helper for getting a unique port for the task run + // TODO: Reuse ports to not spam the system + static mut NEXT_PORT: AtomicUsize = ATOMIC_USIZE_INIT; + const FIRST_PORT: usize = 18080; + + fn next_port() -> usize { + unsafe { + // If the atomic was never used, set it to the initial port + NEXT_PORT.compare_and_swap(0, FIRST_PORT, SeqCst); + + // Get and increment the port list + NEXT_PORT.fetch_add(1, SeqCst) + } + } + + pub fn localhost() -> SocketAddr { + let s = format!("127.0.0.1:{}", next_port()); + FromStr::from_str(&s).unwrap() + } +} + +pub fn sleep_ms(ms: u64) { + use std::thread; + thread::sleep(Duration::from_millis(ms)); +} + +pub fn expect_events(poll: &Poll, + event_buffer: &mut Events, + poll_try_count: usize, + mut expected: Vec) +{ + const MS: u64 = 1_000; + + for _ in 0..poll_try_count { + poll.poll(event_buffer, Some(Duration::from_millis(MS))).unwrap(); + for event in event_buffer.iter() { + let pos_opt = match expected.iter().position(|exp_event| { + (event.token() == exp_event.token()) && + event.readiness().contains(exp_event.readiness()) + }) { + Some(x) => Some(x), + None => None, + }; + if let Some(pos) = pos_opt { expected.remove(pos); } + } + + if expected.is_empty() { + break; + } + } + + assert!(expected.is_empty(), "The following expected events were not found: {:?}", expected); +} + diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_battery.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_battery.rs new file mode 100644 index 0000000..fa3aff0 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_battery.rs @@ -0,0 +1,269 @@ +use {localhost, sleep_ms, TryRead, TryWrite}; +use mio::*; +use mio::deprecated::{EventLoop, EventLoopBuilder, Handler}; +use mio::net::{TcpListener, TcpStream}; +use std::collections::LinkedList; +use slab::Slab; +use std::{io, thread}; +use std::time::Duration; + +// Don't touch the connection slab +const SERVER: Token = Token(10_000_000); +const CLIENT: Token = Token(10_000_001); + +#[cfg(windows)] +const N: usize = 10_000; +#[cfg(unix)] +const N: usize = 1_000_000; + +struct EchoConn { + sock: TcpStream, + token: Option, + count: usize, + buf: Vec +} + +impl EchoConn { + fn new(sock: TcpStream) -> EchoConn { + let mut ec = + EchoConn { + sock: sock, + token: None, + buf: Vec::with_capacity(22), + count: 0 + }; + unsafe { ec.buf.set_len(22) }; + ec + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + event_loop.reregister(&self.sock, self.token.unwrap(), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()) + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + loop { + match self.sock.try_read(&mut self.buf[..]) { + Ok(None) => { + break; + } + Ok(Some(_)) => { + self.count += 1; + if self.count % 10000 == 0 { + info!("Received {} messages", self.count); + } + if self.count == N { + event_loop.shutdown(); + } + } + Err(_) => { + break; + } + + }; + } + + event_loop.reregister(&self.sock, self.token.unwrap(), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct EchoServer { + sock: TcpListener, + conns: Slab +} + +impl EchoServer { + fn accept(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("server accepting socket"); + + let sock = self.sock.accept().unwrap().0; + let conn = EchoConn::new(sock,); + let tok = self.conns.insert(conn); + + // Register the connection + self.conns[tok].token = Some(Token(tok)); + event_loop.register(&self.conns[tok].sock, Token(tok), Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()) + .expect("could not register socket with event loop"); + + Ok(()) + } + + fn conn_readable(&mut self, event_loop: &mut EventLoop, + tok: Token) -> io::Result<()> { + debug!("server conn readable; tok={:?}", tok); + self.conn(tok).readable(event_loop) + } + + fn conn_writable(&mut self, event_loop: &mut EventLoop, + tok: Token) -> io::Result<()> { + debug!("server conn writable; tok={:?}", tok); + self.conn(tok).writable(event_loop) + } + + fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { + &mut self.conns[tok.into()] + } +} + +struct EchoClient { + sock: TcpStream, + backlog: LinkedList, + token: Token, + count: u32 +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl EchoClient { + fn new(sock: TcpStream, tok: Token) -> EchoClient { + + EchoClient { + sock: sock, + backlog: LinkedList::new(), + token: tok, + count: 0 + } + } + + fn readable(&mut self, _event_loop: &mut EventLoop) -> io::Result<()> { + Ok(()) + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket writable"); + + while self.backlog.len() > 0 { + match self.sock.try_write(self.backlog.front().unwrap().as_bytes()) { + Ok(None) => { + break; + } + Ok(Some(_)) => { + self.backlog.pop_front(); + self.count += 1; + if self.count % 10000 == 0 { + info!("Sent {} messages", self.count); + } + } + Err(e) => { debug!("not implemented; client err={:?}", e); break; } + } + } + if self.backlog.len() > 0 { + event_loop.reregister(&self.sock, self.token, Ready::writable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + } + + Ok(()) + } +} + +struct Echo { + server: EchoServer, + client: EchoClient, +} + +impl Echo { + fn new(srv: TcpListener, client: TcpStream) -> Echo { + Echo { + server: EchoServer { + sock: srv, + conns: Slab::with_capacity(128), + }, + client: EchoClient::new(client, CLIENT), + } + } +} + +impl Handler for Echo { + type Timeout = usize; + type Message = String; + + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, + events: Ready) { + + if events.is_readable() { + match token { + SERVER => self.server.accept(event_loop).unwrap(), + CLIENT => self.client.readable(event_loop).unwrap(), + i => self.server.conn_readable(event_loop, i).unwrap() + } + } + if events.is_writable() { + match token { + SERVER => panic!("received writable for token 0"), + CLIENT => self.client.writable(event_loop).unwrap(), + _ => self.server.conn_writable(event_loop, token).unwrap() + } + } + } + + fn notify(&mut self, event_loop: &mut EventLoop, msg: String) { + match self.client.sock.try_write(msg.as_bytes()) { + Ok(Some(n)) => { + self.client.count += 1; + if self.client.count % 10000 == 0 { + info!("Sent {} bytes: count {}", n, self.client.count); + } + }, + + _ => { + self.client.backlog.push_back(msg); + event_loop.reregister( + &self.client.sock, + self.client.token, + Ready::writable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + } + } + } +} + +#[test] +pub fn test_echo_server() { + debug!("Starting TEST_ECHO_SERVER"); + let mut b = EventLoopBuilder::new(); + b.notify_capacity(1_048_576) + .messages_per_tick(64) + .timer_tick(Duration::from_millis(100)) + .timer_wheel_size(1_024) + .timer_capacity(65_536); + + let mut event_loop = b.build().unwrap(); + + let addr = localhost(); + + let srv = TcpListener::bind(&addr).unwrap(); + + info!("listen for connections"); + event_loop.register(&srv, SERVER, Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let sock = TcpStream::connect(&addr).unwrap(); + + // Connect to the server + event_loop.register(&sock, CLIENT, Ready::writable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + let chan = event_loop.channel(); + + let go = move || { + let mut i = N; + + sleep_ms(1_000); + + let message = "THIS IS A TEST MESSAGE".to_string(); + while i > 0 { + chan.send(message.clone()).unwrap(); + i -= 1; + if i % 10000 == 0 { + info!("Enqueued {} messages", N - i); + } + } + }; + + let t = thread::spawn(go); + + // Start the event loop + event_loop.run(&mut Echo::new(srv, sock)).unwrap(); + t.join().unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_broken_pipe.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_broken_pipe.rs new file mode 100644 index 0000000..1cd0ca7 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_broken_pipe.rs @@ -0,0 +1,28 @@ +use mio::{Token, Ready, PollOpt}; +use mio::deprecated::{unix, EventLoop, Handler}; +use std::time::Duration; + +pub struct BrokenPipeHandler; + +impl Handler for BrokenPipeHandler { + type Timeout = (); + type Message = (); + fn ready(&mut self, _: &mut EventLoop, token: Token, _: Ready) { + if token == Token(1) { + panic!("Received ready() on a closed pipe."); + } + } +} + +#[test] +pub fn broken_pipe() { + let mut event_loop: EventLoop = EventLoop::new().unwrap(); + let (reader, _) = unix::pipe().unwrap(); + + event_loop.register(&reader, Token(1), Ready::all(), PollOpt::edge()) + .unwrap(); + + let mut handler = BrokenPipeHandler; + drop(reader); + event_loop.run_once(&mut handler, Some(Duration::from_millis(1000))).unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_close_on_drop.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_close_on_drop.rs new file mode 100644 index 0000000..6cd7d13 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_close_on_drop.rs @@ -0,0 +1,119 @@ +use {localhost, TryRead}; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use bytes::ByteBuf; +use mio::net::{TcpListener, TcpStream}; + +use self::TestState::{Initial, AfterRead}; + +const SERVER: Token = Token(0); +const CLIENT: Token = Token(1); + +#[derive(Debug, PartialEq)] +enum TestState { + Initial, + AfterRead, +} + +struct TestHandler { + srv: TcpListener, + cli: TcpStream, + state: TestState, + shutdown: bool, +} + +impl TestHandler { + fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { + TestHandler { + srv, + cli, + state: Initial, + shutdown: false, + } + } + + fn handle_read(&mut self, poll: &mut Poll, tok: Token, events: Ready) { + debug!("readable; tok={:?}; hint={:?}", tok, events); + + match tok { + SERVER => { + debug!("server connection ready for accept"); + let _ = self.srv.accept().unwrap(); + } + CLIENT => { + debug!("client readable"); + + match self.state { + Initial => { + let mut buf = [0; 4096]; + debug!("GOT={:?}", self.cli.try_read(&mut buf[..])); + self.state = AfterRead; + }, + AfterRead => {} + } + + let mut buf = ByteBuf::mut_with_capacity(1024); + + match self.cli.try_read_buf(&mut buf) { + Ok(Some(0)) => self.shutdown = true, + Ok(_) => panic!("the client socket should not be readable"), + Err(e) => panic!("Unexpected error {:?}", e) + } + } + _ => panic!("received unknown token {:?}", tok) + } + poll.reregister(&self.cli, CLIENT, Ready::readable(), PollOpt::edge()).unwrap(); + } + + fn handle_write(&mut self, poll: &mut Poll, tok: Token, _: Ready) { + match tok { + SERVER => panic!("received writable for token 0"), + CLIENT => { + debug!("client connected"); + poll.reregister(&self.cli, CLIENT, Ready::readable(), PollOpt::edge()).unwrap(); + } + _ => panic!("received unknown token {:?}", tok) + } + } +} + +#[test] +pub fn test_close_on_drop() { + let _ = ::env_logger::init(); + debug!("Starting TEST_CLOSE_ON_DROP"); + let mut poll = Poll::new().unwrap(); + + // The address to connect to - localhost + a unique port + let addr = localhost(); + + // == Create & setup server socket + let srv = TcpListener::bind(&addr).unwrap(); + + poll.register(&srv, SERVER, Ready::readable(), PollOpt::edge()).unwrap(); + + // == Create & setup client socket + let sock = TcpStream::connect(&addr).unwrap(); + + poll.register(&sock, CLIENT, Ready::writable(), PollOpt::edge()).unwrap(); + + // == Create storage for events + let mut events = Events::with_capacity(1024); + + // == Setup test handler + let mut handler = TestHandler::new(srv, sock); + + // == Run test + while !handler.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.readiness().is_readable() { + handler.handle_read(&mut poll, event.token(), event.readiness()); + } + + if event.readiness().is_writable() { + handler.handle_write(&mut poll, event.token(), event.readiness()); + } + } + } + assert!(handler.state == AfterRead, "actual={:?}", handler.state); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_custom_evented.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_custom_evented.rs new file mode 100644 index 0000000..08842fc --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_custom_evented.rs @@ -0,0 +1,394 @@ +use mio::{Events, Poll, PollOpt, Ready, Registration, SetReadiness, Token}; +use mio::event::Evented; +use std::time::Duration; + +#[test] +fn smoke() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(128); + + let (r, set) = Registration::new2(); + r.register(&poll, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + + let n = poll.poll(&mut events, Some(Duration::from_millis(0))).unwrap(); + assert_eq!(n, 0); + + set.set_readiness(Ready::readable()).unwrap(); + + let n = poll.poll(&mut events, Some(Duration::from_millis(0))).unwrap(); + assert_eq!(n, 1); + + assert_eq!(events.get(0).unwrap().token(), Token(0)); +} + +#[test] +fn set_readiness_before_register() { + use std::sync::{Arc, Barrier}; + use std::thread; + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(128); + + for _ in 0..5_000 { + let (r, set) = Registration::new2(); + + let b1 = Arc::new(Barrier::new(2)); + let b2 = b1.clone(); + + let th = thread::spawn(move || { + // set readiness before register + set.set_readiness(Ready::readable()).unwrap(); + + // run into barrier so both can pass + b2.wait(); + }); + + // wait for readiness + b1.wait(); + + // now register + poll.register(&r, Token(123), Ready::readable(), PollOpt::edge()).unwrap(); + + loop { + let n = poll.poll(&mut events, None).unwrap(); + + if n == 0 { + continue; + } + + assert_eq!(n, 1); + assert_eq!(events.get(0).unwrap().token(), Token(123)); + break; + } + + th.join().unwrap(); + } +} + +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))] +mod stress { + use mio::{Events, Poll, PollOpt, Ready, Registration, SetReadiness, Token}; + use mio::event::Evented; + use std::time::Duration; + + #[test] + fn single_threaded_poll() { + use std::sync::Arc; + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering::{Acquire, Release}; + use std::thread; + + const NUM_ATTEMPTS: usize = 30; + const NUM_ITERS: usize = 500; + const NUM_THREADS: usize = 4; + const NUM_REGISTRATIONS: usize = 128; + + for _ in 0..NUM_ATTEMPTS { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(NUM_REGISTRATIONS); + + let registrations: Vec<_> = (0..NUM_REGISTRATIONS).map(|i| { + let (r, s) = Registration::new2(); + r.register(&poll, Token(i), Ready::readable(), PollOpt::edge()).unwrap(); + (r, s) + }).collect(); + + let mut ready: Vec<_> = (0..NUM_REGISTRATIONS).map(|_| Ready::empty()).collect(); + + let remaining = Arc::new(AtomicUsize::new(NUM_THREADS)); + + for _ in 0..NUM_THREADS { + let remaining = remaining.clone(); + + let set_readiness: Vec = + registrations.iter().map(|r| r.1.clone()).collect(); + + thread::spawn(move || { + for _ in 0..NUM_ITERS { + for i in 0..NUM_REGISTRATIONS { + set_readiness[i].set_readiness(Ready::readable()).unwrap(); + set_readiness[i].set_readiness(Ready::empty()).unwrap(); + set_readiness[i].set_readiness(Ready::writable()).unwrap(); + set_readiness[i].set_readiness(Ready::readable() | Ready::writable()).unwrap(); + set_readiness[i].set_readiness(Ready::empty()).unwrap(); + } + } + + for i in 0..NUM_REGISTRATIONS { + set_readiness[i].set_readiness(Ready::readable()).unwrap(); + } + + remaining.fetch_sub(1, Release); + }); + } + + while remaining.load(Acquire) > 0 { + // Set interest + for (i, &(ref r, _)) in registrations.iter().enumerate() { + r.reregister(&poll, Token(i), Ready::writable(), PollOpt::edge()).unwrap(); + } + + poll.poll(&mut events, Some(Duration::from_millis(0))).unwrap(); + + for event in &events { + ready[event.token().0] = event.readiness(); + } + + // Update registration + // Set interest + for (i, &(ref r, _)) in registrations.iter().enumerate() { + r.reregister(&poll, Token(i), Ready::readable(), PollOpt::edge()).unwrap(); + } + } + + // Finall polls, repeat until readiness-queue empty + loop { + // Might not read all events from custom-event-queue at once, implementation dependend + poll.poll(&mut events, Some(Duration::from_millis(0))).unwrap(); + if events.is_empty() { + // no more events in readiness queue pending + break; + } + for event in &events { + ready[event.token().0] = event.readiness(); + } + } + + // Everything should be flagged as readable + for ready in ready { + assert_eq!(ready, Ready::readable()); + } + } + } + + #[test] + fn multi_threaded_poll() { + use std::sync::{Arc, Barrier}; + use std::sync::atomic::{AtomicUsize}; + use std::sync::atomic::Ordering::{Relaxed, SeqCst}; + use std::thread; + + const ENTRIES: usize = 10_000; + const PER_ENTRY: usize = 16; + const THREADS: usize = 4; + const NUM: usize = ENTRIES * PER_ENTRY; + + struct Entry { + #[allow(dead_code)] + registration: Registration, + set_readiness: SetReadiness, + num: AtomicUsize, + } + + impl Entry { + fn fire(&self) { + self.set_readiness.set_readiness(Ready::readable()).unwrap(); + } + } + + let poll = Arc::new(Poll::new().unwrap()); + let mut entries = vec![]; + + // Create entries + for i in 0..ENTRIES { + let (registration, set_readiness) = Registration::new2(); + registration.register(&poll, Token(i), Ready::readable(), PollOpt::edge()).unwrap(); + + entries.push(Entry { + registration, + set_readiness, + num: AtomicUsize::new(0), + }); + } + + let total = Arc::new(AtomicUsize::new(0)); + let entries = Arc::new(entries); + let barrier = Arc::new(Barrier::new(THREADS)); + + let mut threads = vec![]; + + for th in 0..THREADS { + let poll = poll.clone(); + let total = total.clone(); + let entries = entries.clone(); + let barrier = barrier.clone(); + + threads.push(thread::spawn(move || { + let mut events = Events::with_capacity(128); + + barrier.wait(); + + // Prime all the registrations + let mut i = th; + while i < ENTRIES { + entries[i].fire(); + i += THREADS; + } + + let mut n = 0; + + + while total.load(SeqCst) < NUM { + // A poll timeout is necessary here because there may be more + // than one threads blocked in `poll` when the final wakeup + // notification arrives (and only notifies one thread). + n += poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); + + let mut num_this_tick = 0; + + for event in &events { + let e = &entries[event.token().0]; + + let mut num = e.num.load(Relaxed); + + loop { + if num < PER_ENTRY { + let actual = e.num.compare_and_swap(num, num + 1, Relaxed); + + if actual == num { + num_this_tick += 1; + e.fire(); + break; + } + + num = actual; + } else { + break; + } + } + } + + total.fetch_add(num_this_tick, SeqCst); + } + + n + })); + } + + let _: Vec<_> = threads.into_iter() + .map(|th| th.join().unwrap()) + .collect(); + + for entry in entries.iter() { + assert_eq!(PER_ENTRY, entry.num.load(Relaxed)); + } + } + + #[test] + fn with_small_events_collection() { + const N: usize = 8; + const ITER: usize = 1_000; + + use std::sync::{Arc, Barrier}; + use std::sync::atomic::AtomicBool; + use std::sync::atomic::Ordering::{Acquire, Release}; + use std::thread; + + let poll = Poll::new().unwrap(); + let mut registrations = vec![]; + + let barrier = Arc::new(Barrier::new(N + 1)); + let done = Arc::new(AtomicBool::new(false)); + + for i in 0..N { + let (registration, set_readiness) = Registration::new2(); + poll.register(®istration, Token(i), Ready::readable(), PollOpt::edge()).unwrap(); + + registrations.push(registration); + + let barrier = barrier.clone(); + let done = done.clone(); + + thread::spawn(move || { + barrier.wait(); + + while !done.load(Acquire) { + set_readiness.set_readiness(Ready::readable()).unwrap(); + } + + // Set one last time + set_readiness.set_readiness(Ready::readable()).unwrap(); + }); + } + + let mut events = Events::with_capacity(4); + + barrier.wait(); + + for _ in 0..ITER { + poll.poll(&mut events, None).unwrap(); + } + + done.store(true, Release); + + let mut final_ready = vec![false; N]; + + + for _ in 0..5 { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + final_ready[event.token().0] = true; + } + + if final_ready.iter().all(|v| *v) { + return; + } + + thread::sleep(Duration::from_millis(10)); + } + + panic!("dead lock?"); + } +} + +#[test] +fn drop_registration_from_non_main_thread() { + use std::thread; + use std::sync::mpsc::channel; + + const THREADS: usize = 8; + const ITERS: usize = 50_000; + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut senders = Vec::with_capacity(THREADS); + let mut token_index = 0; + + // spawn threads, which will send messages to single receiver + for _ in 0..THREADS { + let (tx, rx) = channel::<(Registration, SetReadiness)>(); + senders.push(tx); + + thread::spawn(move || { + for (registration, set_readiness) in rx { + let _ = set_readiness.set_readiness(Ready::readable()); + drop(registration); + drop(set_readiness); + } + }); + } + + let mut index: usize = 0; + for _ in 0..ITERS { + let (registration, set_readiness) = Registration::new2(); + registration.register(&poll, Token(token_index), Ready::readable(), PollOpt::edge()).unwrap(); + let _ = senders[index].send((registration, set_readiness)); + + token_index += 1; + index += 1; + if index == THREADS { + index = 0; + + let (registration, set_readiness) = Registration::new2(); + registration.register(&poll, Token(token_index), Ready::readable(), PollOpt::edge()).unwrap(); + let _ = set_readiness.set_readiness(Ready::readable()); + drop(registration); + drop(set_readiness); + token_index += 1; + + thread::park_timeout(Duration::from_millis(0)); + let _ = poll.poll(&mut events, None).unwrap(); + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_double_register.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_double_register.rs new file mode 100644 index 0000000..c3d011c --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_double_register.rs @@ -0,0 +1,17 @@ +//! A smoke test for windows compatibility + +#[test] +#[cfg(any(target_os = "linux", target_os = "windows"))] +pub fn test_double_register() { + use mio::*; + use mio::net::TcpListener; + + let poll = Poll::new().unwrap(); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + assert!(poll.register(&l, Token(1), Ready::readable(), PollOpt::edge()).is_err()); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_echo_server.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_echo_server.rs new file mode 100644 index 0000000..e20ae98 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_echo_server.rs @@ -0,0 +1,303 @@ +use {localhost, TryRead, TryWrite}; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::net::{TcpListener, TcpStream}; +use bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf}; +use slab::Slab; +use std::io; + +const SERVER: Token = Token(10_000_000); +const CLIENT: Token = Token(10_000_001); + +struct EchoConn { + sock: TcpStream, + buf: Option, + mut_buf: Option, + token: Option, + interest: Ready +} + +impl EchoConn { + fn new(sock: TcpStream) -> EchoConn { + EchoConn { + sock, + buf: None, + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token: None, + interest: Ready::empty(), + } + } + + fn writable(&mut self, poll: &mut Poll) -> io::Result<()> { + let mut buf = self.buf.take().unwrap(); + + match self.sock.try_write_buf(&mut buf) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + + self.buf = Some(buf); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CONN : we wrote {} bytes!", r); + + self.mut_buf = Some(buf.flip()); + + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e), + } + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + poll.reregister(&self.sock, self.token.unwrap(), self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } + + fn readable(&mut self, poll: &mut Poll) -> io::Result<()> { + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CONN : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + debug!("CONN : we read {} bytes!", r); + + // prepare to provide this to writable + self.buf = Some(buf.flip()); + + self.interest.remove(Ready::readable()); + self.interest.insert(Ready::writable()); + } + Err(e) => { + debug!("not implemented; client err={:?}", e); + self.interest.remove(Ready::readable()); + } + + }; + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + poll.reregister(&self.sock, self.token.unwrap(), self.interest, + PollOpt::edge()) + } +} + +struct EchoServer { + sock: TcpListener, + conns: Slab +} + +impl EchoServer { + fn accept(&mut self, poll: &mut Poll) -> io::Result<()> { + debug!("server accepting socket"); + + let sock = self.sock.accept().unwrap().0; + let conn = EchoConn::new(sock,); + let tok = self.conns.insert(conn); + + // Register the connection + self.conns[tok].token = Some(Token(tok)); + poll.register(&self.conns[tok].sock, Token(tok), Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()) + .expect("could not register socket with event loop"); + + Ok(()) + } + + fn conn_readable(&mut self, poll: &mut Poll, + tok: Token) -> io::Result<()> { + debug!("server conn readable; tok={:?}", tok); + self.conn(tok).readable(poll) + } + + fn conn_writable(&mut self, poll: &mut Poll, + tok: Token) -> io::Result<()> { + debug!("server conn writable; tok={:?}", tok); + self.conn(tok).writable(poll) + } + + fn conn(&mut self, tok: Token) -> &mut EchoConn { + &mut self.conns[tok.into()] + } +} + +struct EchoClient { + sock: TcpStream, + msgs: Vec<&'static str>, + tx: SliceBuf<'static>, + rx: SliceBuf<'static>, + mut_buf: Option, + token: Token, + interest: Ready, + shutdown: bool, +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl EchoClient { + fn new(sock: TcpStream, token: Token, mut msgs: Vec<&'static str>) -> EchoClient { + let curr = msgs.remove(0); + + EchoClient { + sock, + msgs, + tx: SliceBuf::wrap(curr.as_bytes()), + rx: SliceBuf::wrap(curr.as_bytes()), + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token, + interest: Ready::empty(), + shutdown: false, + } + } + + fn readable(&mut self, poll: &mut Poll) -> io::Result<()> { + debug!("client socket readable"); + + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CLIENT : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + debug!("CLIENT : We read {} bytes!", r); + + // prepare for reading + let mut buf = buf.flip(); + + while buf.has_remaining() { + let actual = buf.read_byte().unwrap(); + let expect = self.rx.read_byte().unwrap(); + + assert!(actual == expect, "actual={}; expect={}", actual, expect); + } + + self.mut_buf = Some(buf.flip()); + + self.interest.remove(Ready::readable()); + + if !self.rx.has_remaining() { + self.next_msg(poll).unwrap(); + } + } + Err(e) => { + panic!("not implemented; client err={:?}", e); + } + }; + + if !self.interest.is_empty() { + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + poll.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot())?; + } + + Ok(()) + } + + fn writable(&mut self, poll: &mut Poll) -> io::Result<()> { + debug!("client socket writable"); + + match self.sock.try_write_buf(&mut self.tx) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CLIENT : we wrote {} bytes!", r); + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e) + } + + if self.interest.is_readable() || self.interest.is_writable() { + try!(poll.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot())); + } + + Ok(()) + } + + fn next_msg(&mut self, poll: &mut Poll) -> io::Result<()> { + if self.msgs.is_empty() { + self.shutdown = true; + return Ok(()); + } + + let curr = self.msgs.remove(0); + + debug!("client prepping next message"); + self.tx = SliceBuf::wrap(curr.as_bytes()); + self.rx = SliceBuf::wrap(curr.as_bytes()); + + self.interest.insert(Ready::writable()); + poll.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct Echo { + server: EchoServer, + client: EchoClient, +} + +impl Echo { + fn new(srv: TcpListener, client: TcpStream, msgs: Vec<&'static str>) -> Echo { + Echo { + server: EchoServer { + sock: srv, + conns: Slab::with_capacity(128) + }, + client: EchoClient::new(client, CLIENT, msgs) + } + } +} + +#[test] +pub fn test_echo_server() { + debug!("Starting TEST_ECHO_SERVER"); + let mut poll = Poll::new().unwrap(); + + let addr = localhost(); + let srv = TcpListener::bind(&addr).unwrap(); + + info!("listen for connections"); + poll.register(&srv, SERVER, Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let sock = TcpStream::connect(&addr).unwrap(); + + // Connect to the server + poll.register(&sock, CLIENT, Ready::writable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + // == Create storage for events + let mut events = Events::with_capacity(1024); + + let mut handler = Echo::new(srv, sock, vec!["foo", "bar"]); + + // Start the event loop + while !handler.client.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + debug!("ready {:?} {:?}", event.token(), event.readiness()); + if event.readiness().is_readable() { + match event.token() { + SERVER => handler.server.accept(&mut poll).unwrap(), + CLIENT => handler.client.readable(&mut poll).unwrap(), + i => handler.server.conn_readable(&mut poll, i).unwrap() + } + } + + if event.readiness().is_writable() { + match event.token() { + SERVER => panic!("received writable for token 0"), + CLIENT => handler.client.writable(&mut poll).unwrap(), + i => handler.server.conn_writable(&mut poll, i).unwrap() + }; + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_fuchsia_handles.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_fuchsia_handles.rs new file mode 100644 index 0000000..85a1432 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_fuchsia_handles.rs @@ -0,0 +1,30 @@ +use mio::*; +use mio::fuchsia::EventedHandle; +use zircon::{self, AsHandleRef}; +use std::time::Duration; + +const MS: u64 = 1_000; + +#[test] +pub fn test_fuchsia_channel() { + let poll = Poll::new().unwrap(); + let mut event_buffer = Events::with_capacity(1); + let event_buffer = &mut event_buffer; + + let (channel0, channel1) = zircon::Channel::create(zircon::ChannelOpts::Normal).unwrap(); + let channel1_evented = unsafe { EventedHandle::new(channel1.raw_handle()) }; + + poll.register(&channel1_evented, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + poll.poll(event_buffer, Some(Duration::from_millis(MS))).unwrap(); + assert_eq!(event_buffer.len(), 0); + + channel0.write(&[1, 2, 3], &mut vec![], 0).unwrap(); + + poll.poll(event_buffer, Some(Duration::from_millis(MS))).unwrap(); + let event = event_buffer.get(0).unwrap(); + assert_eq!(event.token(), Token(1)); + assert!(event.readiness().is_readable()); + + poll.deregister(&channel1_evented).unwrap(); +} \ No newline at end of file diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_local_addr_ready.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_local_addr_ready.rs new file mode 100644 index 0000000..2e97f52 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_local_addr_ready.rs @@ -0,0 +1,67 @@ +use {TryWrite}; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::net::{TcpListener, TcpStream}; + +const LISTEN: Token = Token(0); +const CLIENT: Token = Token(1); +const SERVER: Token = Token(2); + +struct MyHandler { + listener: TcpListener, + connected: TcpStream, + accepted: Option, + shutdown: bool, +} + +#[test] +fn local_addr_ready() { + let addr = "127.0.0.1:0".parse().unwrap(); + let server = TcpListener::bind(&addr).unwrap(); + let addr = server.local_addr().unwrap(); + + let poll = Poll::new().unwrap(); + poll.register(&server, LISTEN, Ready::readable(), + PollOpt::edge()).unwrap(); + + let sock = TcpStream::connect(&addr).unwrap(); + poll.register(&sock, CLIENT, Ready::readable(), + PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + + let mut handler = MyHandler { + listener: server, + connected: sock, + accepted: None, + shutdown: false, + }; + + while !handler.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + match event.token() { + LISTEN => { + let sock = handler.listener.accept().unwrap().0; + poll.register(&sock, + SERVER, + Ready::writable(), + PollOpt::edge()).unwrap(); + handler.accepted = Some(sock); + } + SERVER => { + handler.accepted.as_ref().unwrap().peer_addr().unwrap(); + handler.accepted.as_ref().unwrap().local_addr().unwrap(); + handler.accepted.as_mut().unwrap().try_write(&[1, 2, 3]).unwrap(); + handler.accepted = None; + } + CLIENT => { + handler.connected.peer_addr().unwrap(); + handler.connected.local_addr().unwrap(); + handler.shutdown = true; + } + _ => panic!("unexpected token"), + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_multicast.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_multicast.rs new file mode 100644 index 0000000..b73e0d5 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_multicast.rs @@ -0,0 +1,107 @@ +// TODO: This doesn't pass on android 64bit CI... +// Figure out why! +#![cfg(not(target_os = "android"))] + +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::net::UdpSocket; +use bytes::{Buf, MutBuf, RingBuf, SliceBuf}; +use std::str; +use std::net::IpAddr; +use localhost; + +const LISTENER: Token = Token(0); +const SENDER: Token = Token(1); + +pub struct UdpHandler { + tx: UdpSocket, + rx: UdpSocket, + msg: &'static str, + buf: SliceBuf<'static>, + rx_buf: RingBuf, + localhost: IpAddr, + shutdown: bool, +} + +impl UdpHandler { + fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler { + let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap(); + UdpHandler { + tx, + rx, + msg, + buf: SliceBuf::wrap(msg.as_bytes()), + rx_buf: RingBuf::new(1024), + localhost: sock.local_addr().unwrap().ip(), + shutdown: false, + } + } + + fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) { + if let LISTENER = token { + debug!("We are receiving a datagram now..."); + match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } { + Ok((cnt, addr)) => { + unsafe { MutBuf::advance(&mut self.rx_buf, cnt); } + assert_eq!(addr.ip(), self.localhost); + } + res => panic!("unexpected result: {:?}", res), + } + assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg); + self.shutdown = true; + } + } + + fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) { + if let SENDER = token { + let addr = self.rx.local_addr().unwrap(); + let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap(); + self.buf.advance(cnt); + } + } +} + +#[test] +pub fn test_multicast() { + drop(::env_logger::init()); + debug!("Starting TEST_UDP_CONNECTIONLESS"); + let mut poll = Poll::new().unwrap(); + + let addr = localhost(); + let any = "0.0.0.0:0".parse().unwrap(); + + let tx = UdpSocket::bind(&any).unwrap(); + let rx = UdpSocket::bind(&addr).unwrap(); + + info!("Joining group 227.1.1.100"); + let any = "0.0.0.0".parse().unwrap(); + rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap(); + + info!("Joining group 227.1.1.101"); + rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap(); + + info!("Registering SENDER"); + poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); + + info!("Registering LISTENER"); + poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + + let mut handler = UdpHandler::new(tx, rx, "hello world"); + + info!("Starting event loop to test with..."); + + while !handler.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.readiness().is_readable() { + handler.handle_read(&mut poll, event.token(), event.readiness()); + } + + if event.readiness().is_writable() { + handler.handle_write(&mut poll, event.token(), event.readiness()); + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_notify.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_notify.rs new file mode 100644 index 0000000..a6a8e51 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_notify.rs @@ -0,0 +1,192 @@ +use {localhost, sleep_ms}; +use mio::*; +use mio::deprecated::{EventLoop, EventLoopBuilder, Handler, Sender, NotifyError}; +use mio::net::TcpListener; +use std::thread; + +struct TestHandler { + sender: Sender, + notify: usize +} + +impl TestHandler { + fn new(sender: Sender) -> TestHandler { + TestHandler { + sender, + notify: 0 + } + } +} + +impl Handler for TestHandler { + type Timeout = usize; + type Message = String; + + fn notify(&mut self, event_loop: &mut EventLoop, msg: String) { + match self.notify { + 0 => { + assert!(msg == "First", "actual={}", msg); + self.sender.send("Second".to_string()).unwrap(); + } + 1 => { + assert!(msg == "Second", "actual={}", msg); + event_loop.shutdown(); + } + v => panic!("unexpected value for notify; val={}", v) + } + + self.notify += 1; + } +} + +#[test] +pub fn test_notify() { + debug!("Starting TEST_NOTIFY"); + let mut event_loop = EventLoop::new().unwrap(); + + let addr = localhost(); + + // Setup a server socket so that the event loop blocks + let srv = TcpListener::bind(&addr).unwrap(); + + event_loop.register(&srv, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + let sender = event_loop.channel(); + + thread::spawn(move || { + sleep_ms(1_000); + sender.send("First".to_string()).unwrap(); + }); + + let sender = event_loop.channel(); + let mut handler = TestHandler::new(sender); + + // Start the event loop + event_loop.run(&mut handler).unwrap(); + + assert!(handler.notify == 2, "actual={}", handler.notify); +} + +#[test] +pub fn test_notify_capacity() { + use std::sync::mpsc::*; + use std::thread; + + struct Capacity(Receiver); + + impl Handler for Capacity { + type Message = i32; + type Timeout = (); + + fn notify(&mut self, event_loop: &mut EventLoop, msg: i32) { + if msg == 1 { + self.0.recv().unwrap(); + } else if msg == 3 { + event_loop.shutdown(); + } + } + } + + let mut builder = EventLoopBuilder::new(); + builder.notify_capacity(1); + + let (tx, rx) = channel::(); + let mut event_loop = builder.build().unwrap(); + let notify = event_loop.channel(); + + let handle = thread::spawn(move || { + let mut handler = Capacity(rx); + event_loop.run(&mut handler).unwrap(); + }); + + assert!(notify.send(1).is_ok()); + + loop { + if notify.send(2).is_err() { + break; + } + } + + tx.send(1).unwrap(); + + loop { + if notify.send(3).is_ok() { + break; + } + } + + handle.join().unwrap(); +} + +#[test] +pub fn test_notify_drop() { + use std::sync::mpsc::{self,Sender}; + use std::thread; + + struct MessageDrop(Sender); + + impl Drop for MessageDrop { + fn drop(&mut self) { + self.0.send(0).unwrap(); + } + } + + struct DummyHandler; + + impl Handler for DummyHandler { + type Timeout = (); + type Message = MessageDrop; + + fn notify(&mut self, event_loop: &mut EventLoop, msg: MessageDrop) { + msg.0.send(1).unwrap(); + drop(msg); + // We stop after the first message + event_loop.shutdown(); + } + } + + let (tx_notif_1, rx_notif_1) = mpsc::channel(); + let (tx_notif_2, rx_notif_2) = mpsc::channel(); + let (tx_notif_3, _unused) = mpsc::channel(); + let (tx_exit_loop, rx_exit_loop) = mpsc::channel(); + let (tx_drop_loop, rx_drop_loop) = mpsc::channel(); + + let mut event_loop = EventLoop::new().unwrap(); + let notify = event_loop.channel(); + + let handle = thread::spawn(move || { + let mut handler = DummyHandler; + event_loop.run(&mut handler).unwrap(); + + // Confirmation we exited the loop + tx_exit_loop.send(()).unwrap(); + + // Order to drop the loop + rx_drop_loop.recv().unwrap(); + drop(event_loop); + }); + notify.send(MessageDrop(tx_notif_1)).unwrap(); + assert_eq!(rx_notif_1.recv().unwrap(), 1); // Response from the loop + assert_eq!(rx_notif_1.recv().unwrap(), 0); // Drop notification + + // We wait for the event loop to exit before sending the second notification + rx_exit_loop.recv().unwrap(); + notify.send(MessageDrop(tx_notif_2)).unwrap(); + + // We ensure the message is indeed stuck in the queue + sleep_ms(100); + assert!(rx_notif_2.try_recv().is_err()); + + // Give the order to drop the event loop + tx_drop_loop.send(()).unwrap(); + assert_eq!(rx_notif_2.recv().unwrap(), 0); // Drop notification + + // Check that sending a new notification will return an error + // We should also get our message back + match notify.send(MessageDrop(tx_notif_3)).unwrap_err() { + NotifyError::Closed(Some(..)) => {} + _ => panic!(), + } + + handle.join().unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_oneshot.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_oneshot.rs new file mode 100644 index 0000000..4dca219 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_oneshot.rs @@ -0,0 +1,64 @@ +use mio::*; +use mio::net::{TcpListener, TcpStream}; +use std::io::*; +use std::time::Duration; + +const MS: u64 = 1_000; + +#[test] +pub fn test_tcp_edge_oneshot() { + let _ = ::env_logger::init(); + + let mut poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::level()).unwrap(); + + // Connect a socket, we are going to write to it + let mut s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + poll.register(&s1, Token(1), Ready::writable(), PollOpt::level()).unwrap(); + + wait_for(&mut poll, &mut events, Token(0)); + + // Get pair + let (mut s2, _) = l.accept().unwrap(); + poll.register(&s2, Token(2), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + wait_for(&mut poll, &mut events, Token(1)); + + let res = s1.write(b"foo").unwrap(); + assert_eq!(3, res); + + let mut buf = [0; 1]; + + for byte in b"foo" { + wait_for(&mut poll, &mut events, Token(2)); + + assert_eq!(1, s2.read(&mut buf).unwrap()); + assert_eq!(*byte, buf[0]); + + poll.reregister(&s2, Token(2), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + if *byte == b'o' { + poll.reregister(&s2, Token(2), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + } + } +} + +fn wait_for(poll: &mut Poll, events: &mut Events, token: Token) { + loop { + poll.poll(events, Some(Duration::from_millis(MS))).unwrap(); + + let cnt = (0..events.len()).map(|i| events.get(i).unwrap()) + .filter(|e| e.token() == token) + .count(); + + assert!(cnt < 2, "token appeared multiple times in poll results; cnt={:}", cnt); + + if cnt == 1 { return }; + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_poll.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_poll.rs new file mode 100644 index 0000000..e259d89 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_poll.rs @@ -0,0 +1,18 @@ +use mio::*; +use std::time::Duration; + +#[test] +fn test_poll_closes_fd() { + for _ in 0..2000 { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(4); + let (registration, set_readiness) = Registration::new2(); + + poll.register(®istration, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + poll.poll(&mut events, Some(Duration::from_millis(0))).unwrap(); + + drop(poll); + drop(set_readiness); + drop(registration); + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_poll_channel.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_poll_channel.rs new file mode 100644 index 0000000..f7ce050 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_poll_channel.rs @@ -0,0 +1,285 @@ +use {expect_events, sleep_ms}; +use mio::{channel, Events, Poll, PollOpt, Ready, Token}; +use mio::event::Event; +use std::sync::mpsc::TryRecvError; +use std::thread; +use std::time::Duration; + +#[test] +pub fn test_poll_channel_edge() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::edge()).unwrap(); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(1, num); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Poll again and there should be no events + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Poll again, nothing + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push a value + tx.send("goodbye").unwrap(); + + // Have an event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(1, num); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Read the value + rx.try_recv().unwrap(); + + // Drop the sender half + drop(tx); + + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(1, num); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + match rx.try_recv() { + Err(TryRecvError::Disconnected) => {} + no => panic!("unexpected value {:?}", no), + } + +} + +#[test] +pub fn test_poll_channel_oneshot() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(1, num); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Poll again and there should be no events + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Poll again, nothing + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push a value + tx.send("goodbye").unwrap(); + + // Poll again, nothing + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Reregistering will re-trigger the notification + for _ in 0..3 { + poll.reregister(&rx, Token(123), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Have an event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(1, num); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + } + + // Get the value + assert_eq!("goodbye", rx.try_recv().unwrap()); + + poll.reregister(&rx, Token(123), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Have an event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + poll.reregister(&rx, Token(123), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Have an event + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_poll_channel_level() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::level()).unwrap(); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + for i in 0..5 { + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert!(1 == num, "actually got {} on iteration {}", num, i); + + let event = events.get(0).unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + } + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_poll_channel_writable() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::writable(), PollOpt::edge()).unwrap(); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_dropping_receive_before_poll() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::edge()).unwrap(); + + // Push the value + tx.send("hello").unwrap(); + + // Drop the receive end + drop(rx); + + // Wait, but nothing should happen + let num = poll.poll(&mut events, Some(Duration::from_millis(300))).unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_mixing_channel_with_socket() { + use mio::net::{TcpListener, TcpStream}; + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + poll.register(&rx, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + // Push a value onto the channel + tx.send("hello").unwrap(); + + // Connect a TCP socket + let s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + + // Register the socket + poll.register(&s1, Token(2), Ready::readable(), PollOpt::edge()).unwrap(); + + // Sleep a bit to ensure it arrives at dest + sleep_ms(250); + + expect_events(&poll, &mut events, 2, vec![ + Event::new(Ready::empty(), Token(0)), + Event::new(Ready::empty(), Token(1)), + ]); +} + +#[test] +pub fn test_sending_from_other_thread_while_polling() { + const ITERATIONS: usize = 20; + const THREADS: usize = 5; + + // Make sure to run multiple times + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + + for _ in 0..ITERATIONS { + let (tx, rx) = channel::channel(); + poll.register(&rx, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + + for _ in 0..THREADS { + let tx = tx.clone(); + + thread::spawn(move || { + sleep_ms(50); + tx.send("ping").unwrap(); + }); + } + + let mut recv = 0; + + while recv < THREADS { + let num = poll.poll(&mut events, None).unwrap(); + + if num != 0 { + assert_eq!(1, num); + assert_eq!(events.get(0).unwrap().token(), Token(0)); + + while let Ok(_) = rx.try_recv() { + recv += 1; + } + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_register_deregister.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_register_deregister.rs new file mode 100644 index 0000000..ae84a02 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_register_deregister.rs @@ -0,0 +1,123 @@ +use {expect_events, localhost, TryWrite}; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::event::Event; +use mio::net::{TcpListener, TcpStream}; +use bytes::SliceBuf; +use std::time::Duration; + +const SERVER: Token = Token(0); +const CLIENT: Token = Token(1); + +struct TestHandler { + server: TcpListener, + client: TcpStream, + state: usize, +} + +impl TestHandler { + fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { + TestHandler { + server: srv, + client: cli, + state: 0, + } + } + + fn handle_read(&mut self, poll: &mut Poll, token: Token) { + match token { + SERVER => { + trace!("handle_read; token=SERVER"); + let mut sock = self.server.accept().unwrap().0; + sock.try_write_buf(&mut SliceBuf::wrap(b"foobar")).unwrap(); + } + CLIENT => { + trace!("handle_read; token=CLIENT"); + assert!(self.state == 0, "unexpected state {}", self.state); + self.state = 1; + poll.reregister(&self.client, CLIENT, Ready::writable(), PollOpt::level()).unwrap(); + } + _ => panic!("unexpected token"), + } + } + + fn handle_write(&mut self, poll: &mut Poll, token: Token) { + debug!("handle_write; token={:?}; state={:?}", token, self.state); + + assert!(token == CLIENT, "unexpected token {:?}", token); + assert!(self.state == 1, "unexpected state {}", self.state); + + self.state = 2; + poll.deregister(&self.client).unwrap(); + poll.deregister(&self.server).unwrap(); + } +} + +#[test] +pub fn test_register_deregister() { + let _ = ::env_logger::init(); + + debug!("Starting TEST_REGISTER_DEREGISTER"); + let mut poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + + let addr = localhost(); + + let server = TcpListener::bind(&addr).unwrap(); + + info!("register server socket"); + poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap(); + + let client = TcpStream::connect(&addr).unwrap(); + + // Register client socket only as writable + poll.register(&client, CLIENT, Ready::readable(), PollOpt::level()).unwrap(); + + let mut handler = TestHandler::new(server, client); + + loop { + poll.poll(&mut events, None).unwrap(); + + if let Some(event) = events.get(0) { + if event.readiness().is_readable() { + handler.handle_read(&mut poll, event.token()); + } + + if event.readiness().is_writable() { + handler.handle_write(&mut poll, event.token()); + break; + } + } + } + + poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); + assert_eq!(events.len(), 0); +} + +#[test] +pub fn test_register_empty_interest() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let addr = localhost(); + + let sock = TcpListener::bind(&addr).unwrap(); + + poll.register(&sock, Token(0), Ready::empty(), PollOpt::edge()).unwrap(); + + let client = TcpStream::connect(&addr).unwrap(); + + // The connect is not guaranteed to have started until it is registered + // https://docs.rs/mio/0.6.10/mio/struct.Poll.html#registering-handles + poll.register(&client, Token(1), Ready::empty(), PollOpt::edge()).unwrap(); + + // sock is registered with empty interest, we should not receive any event + poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); + assert_eq!(events.len(), 0, "Received unexpected event: {:?}", events.get(0).unwrap()); + + // now sock is reregistered with readable, we should receive the pending event + poll.reregister(&sock, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + expect_events(&poll, &mut events, 2, vec![ + Event::new(Ready::readable(), Token(0)) + ]); + + poll.reregister(&sock, Token(0), Ready::empty(), PollOpt::edge()).unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_register_multiple_event_loops.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_register_multiple_event_loops.rs new file mode 100644 index 0000000..9204afa --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_register_multiple_event_loops.rs @@ -0,0 +1,63 @@ +use localhost; +use mio::*; +use mio::net::{TcpListener, TcpStream, UdpSocket}; +use std::io::ErrorKind; + +#[test] +fn test_tcp_register_multiple_event_loops() { + let addr = localhost(); + let listener = TcpListener::bind(&addr).unwrap(); + + let poll1 = Poll::new().unwrap(); + poll1.register(&listener, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + let poll2 = Poll::new().unwrap(); + + // Try registering the same socket with the initial one + let res = poll2.register(&listener, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); + + // Try cloning the socket and registering it again + let listener2 = listener.try_clone().unwrap(); + let res = poll2.register(&listener2, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); + + // Try the stream + let stream = TcpStream::connect(&addr).unwrap(); + + poll1.register(&stream, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + let res = poll2.register(&stream, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); + + // Try cloning the socket and registering it again + let stream2 = stream.try_clone().unwrap(); + let res = poll2.register(&stream2, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); +} + +#[test] +fn test_udp_register_multiple_event_loops() { + let addr = localhost(); + let socket = UdpSocket::bind(&addr).unwrap(); + + let poll1 = Poll::new().unwrap(); + poll1.register(&socket, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + let poll2 = Poll::new().unwrap(); + + // Try registering the same socket with the initial one + let res = poll2.register(&socket, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); + + // Try cloning the socket and registering it again + let socket2 = socket.try_clone().unwrap(); + let res = poll2.register(&socket2, Token(0), Ready::readable() | Ready::writable(), PollOpt::edge()); + assert!(res.is_err()); + assert_eq!(res.unwrap_err().kind(), ErrorKind::Other); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_reregister_without_poll.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_reregister_without_poll.rs new file mode 100644 index 0000000..45d5aca --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_reregister_without_poll.rs @@ -0,0 +1,28 @@ +use {sleep_ms}; +use mio::*; +use mio::net::{TcpListener, TcpStream}; +use std::time::Duration; + +const MS: u64 = 1_000; + +#[test] +pub fn test_reregister_different_without_poll() { + let mut events = Events::with_capacity(1024); + let poll = Poll::new().unwrap(); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + poll.register(&s1, Token(2), Ready::readable(), PollOpt::edge()).unwrap(); + + sleep_ms(MS); + + poll.reregister(&l, Token(0), Ready::writable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + poll.poll(&mut events, Some(Duration::from_millis(MS))).unwrap(); + assert_eq!(events.len(), 0); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_smoke.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_smoke.rs new file mode 100644 index 0000000..96f7d3c --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_smoke.rs @@ -0,0 +1,23 @@ +extern crate mio; + +use mio::{Events, Poll, Token, Ready, PollOpt}; +use mio::net::TcpListener; +use std::time::Duration; + +#[test] +fn run_once_with_nothing() { + let mut events = Events::with_capacity(1024); + let poll = Poll::new().unwrap(); + poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); +} + +#[test] +fn add_then_drop() { + let mut events = Events::with_capacity(1024); + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let poll = Poll::new().unwrap(); + poll.register(&l, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + drop(l); + poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); + +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_subprocess_pipe.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_subprocess_pipe.rs new file mode 100644 index 0000000..2bcf132 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_subprocess_pipe.rs @@ -0,0 +1,249 @@ +use {TryRead, TryWrite}; +use std::mem; +use mio::*; +use std::io; +use mio::deprecated::{EventLoop, Handler}; +use mio::deprecated::unix::{PipeReader, PipeWriter}; +use std::process::{Command, Stdio, Child}; + + +struct SubprocessClient { + stdin: Option, + stdout: Option, + stderr: Option, + stdin_token : Token, + stdout_token : Token, + stderr_token : Token, + output : Vec, + output_stderr : Vec, + input : Vec, + input_offset : usize, + buf : [u8; 65536], +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl SubprocessClient { + fn new(stdin: Option, stdout : Option, stderr : Option, data : &[u8]) -> SubprocessClient { + SubprocessClient { + stdin: stdin, + stdout: stdout, + stderr: stderr, + stdin_token : Token(0), + stdout_token : Token(1), + stderr_token : Token(2), + output : Vec::::new(), + output_stderr : Vec::::new(), + buf : [0; 65536], + input : data.to_vec(), + input_offset : 0, + } + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut eof = false; + match self.stdout { + None => unreachable!(), + Some (ref mut stdout) => match stdout.try_read(&mut self.buf[..]) { + Ok(None) => { + } + Ok(Some(r)) => { + if r == 0 { + eof = true; + } else { + self.output.extend(&self.buf[0..r]); + } + } + Err(e) => { + return Err(e); + } + } + }; + if eof { + drop(self.stdout.take()); + match self.stderr { + None => event_loop.shutdown(), + Some(_) => {}, + } + } + return Ok(()); + } + + fn readable_stderr(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut eof = false; + match self.stderr { + None => unreachable!(), + Some(ref mut stderr) => match stderr.try_read(&mut self.buf[..]) { + Ok(None) => { + } + Ok(Some(r)) => { + if r == 0 { + eof = true; + } else { + self.output_stderr.extend(&self.buf[0..r]); + } + } + Err(e) => { + return Err(e); + } + } + }; + if eof { + drop(self.stderr.take()); + match self.stdout { + None => event_loop.shutdown(), + Some(_) => {}, + } + } + return Ok(()); + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut ok = true; + match self.stdin { + None => unreachable!(), + Some(ref mut stdin) => match stdin.try_write(&(&self.input)[self.input_offset..]) { + Ok(None) => { + }, + Ok(Some(r)) => { + if r == 0 { + ok = false; + } else { + self.input_offset += r; + } + }, + Err(_) => { + ok = false; + }, + } + } + if self.input_offset == self.input.len() || !ok { + drop(self.stdin.take()); + match self.stderr { + None => match self.stdout { + None => event_loop.shutdown(), + Some(_) => {}, + }, + Some(_) => {}, + } + } + return Ok(()); + } + +} + +impl Handler for SubprocessClient { + type Timeout = usize; + type Message = (); + + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, + _: Ready) { + if token == self.stderr_token { + let _x = self.readable_stderr(event_loop); + } else { + let _x = self.readable(event_loop); + } + if token == self.stdin_token { + let _y = self.writable(event_loop); + } + } +} + + + + +const TEST_DATA : [u8; 1024 * 4096] = [42; 1024 * 4096]; +pub fn subprocess_communicate(mut process : Child, input : &[u8]) -> (Vec, Vec) { + let mut event_loop = EventLoop::::new().unwrap(); + let stdin : Option; + let stdin_exists : bool; + match process.stdin { + None => stdin_exists = false, + Some(_) => stdin_exists = true, + } + if stdin_exists { + match PipeWriter::from_stdin(process.stdin.take().unwrap()) { + Err(e) => panic!(e), + Ok(pipe) => stdin = Some(pipe), + } + } else { + stdin = None; + } + let stdout_exists : bool; + let stdout : Option; + match process.stdout { + None => stdout_exists = false, + Some(_) => stdout_exists = true, + } + if stdout_exists { + match PipeReader::from_stdout(process.stdout.take().unwrap()) { + Err(e) => panic!(e), + Ok(pipe) => stdout = Some(pipe), + } + } else { + stdout = None; + } + let stderr_exists : bool; + let stderr : Option; + match process.stderr { + None => stderr_exists = false, + Some(_) => stderr_exists = true, + } + if stderr_exists { + match PipeReader::from_stderr(process.stderr.take().unwrap()) { + Err(e) => panic!(e), + Ok(pipe) => stderr = Some(pipe), + } + } else { + stderr = None + } + + let mut subprocess = SubprocessClient::new(stdin, + stdout, + stderr, + input); + match subprocess.stdout { + Some(ref sub_stdout) => event_loop.register(sub_stdout, subprocess.stdout_token, Ready::readable(), + PollOpt::level()).unwrap(), + None => {}, + } + + match subprocess.stderr { + Some(ref sub_stderr) => event_loop.register(sub_stderr, subprocess.stderr_token, Ready::readable(), + PollOpt::level()).unwrap(), + None => {}, + } + + // Connect to the server + match subprocess.stdin { + Some (ref sub_stdin) => event_loop.register(sub_stdin, subprocess.stdin_token, Ready::writable(), + PollOpt::level()).unwrap(), + None => {}, + } + + // Start the event loop + event_loop.run(&mut subprocess).unwrap(); + let _ = process.wait(); + + let ret_stdout = mem::replace(&mut subprocess.output, Vec::::new()); + let ret_stderr = mem::replace(&mut subprocess.output_stderr, Vec::::new()); + return (ret_stdout, ret_stderr); +} + +#[test] +fn test_subprocess_pipe() { + let process = + Command::new("/bin/cat") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn().unwrap(); + let (ret_stdout, ret_stderr) = subprocess_communicate(process, &TEST_DATA[..]); + assert_eq!(TEST_DATA.len(), ret_stdout.len()); + assert_eq!(0usize, ret_stderr.len()); + let mut i : usize = 0; + for item in TEST_DATA.iter() { + assert_eq!(*item, ret_stdout[i]); + i += 1; + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_tcp.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp.rs new file mode 100644 index 0000000..ae569ac --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp.rs @@ -0,0 +1,660 @@ +use std::cmp; +use std::io::prelude::*; +use std::io; +use std::net; +use std::sync::mpsc::channel; +use std::thread; +use std::time::Duration; + +use net2::{self, TcpStreamExt}; + +use {TryRead, TryWrite}; +use mio::{Token, Ready, PollOpt, Poll, Events}; +use iovec::IoVec; +use mio::net::{TcpListener, TcpStream}; + +#[test] +fn accept() { + struct H { hit: bool, listener: TcpListener, shutdown: bool } + + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + net::TcpStream::connect(&addr).unwrap(); + }); + + let poll = Poll::new().unwrap(); + + poll.register(&l, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { hit: false, listener: l, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + h.hit = true; + assert_eq!(event.token(), Token(1)); + assert!(event.readiness().is_readable()); + assert!(h.listener.accept().is_ok()); + h.shutdown = true; + } + } + assert!(h.hit); + assert!(h.listener.accept().unwrap_err().kind() == io::ErrorKind::WouldBlock); + t.join().unwrap(); +} + +#[test] +fn connect() { + struct H { hit: u32, shutdown: bool } + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let (tx, rx) = channel(); + let (tx2, rx2) = channel(); + let t = thread::spawn(move || { + let s = l.accept().unwrap(); + rx.recv().unwrap(); + drop(s); + tx2.send(()).unwrap(); + }); + + let poll = Poll::new().unwrap(); + let s = TcpStream::connect(&addr).unwrap(); + + poll.register(&s, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { hit: 0, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + assert_eq!(event.token(), Token(1)); + match h.hit { + 0 => assert!(event.readiness().is_writable()), + 1 => assert!(event.readiness().is_readable()), + _ => panic!(), + } + h.hit += 1; + h.shutdown = true; + } + } + assert_eq!(h.hit, 1); + tx.send(()).unwrap(); + rx2.recv().unwrap(); + h.shutdown = false; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + assert_eq!(event.token(), Token(1)); + match h.hit { + 0 => assert!(event.readiness().is_writable()), + 1 => assert!(event.readiness().is_readable()), + _ => panic!(), + } + h.hit += 1; + h.shutdown = true; + } + } + assert_eq!(h.hit, 2); + t.join().unwrap(); +} + +#[test] +fn read() { + const N: usize = 16 * 1024 * 1024; + struct H { amt: usize, socket: TcpStream, shutdown: bool } + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let b = [0; 1024]; + let mut amt = 0; + while amt < N { + amt += s.write(&b).unwrap(); + } + }); + + let poll = Poll::new().unwrap(); + let s = TcpStream::connect(&addr).unwrap(); + + poll.register(&s, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { amt: 0, socket: s, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + assert_eq!(event.token(), Token(1)); + let mut b = [0; 1024]; + loop { + if let Some(amt) = h.socket.try_read(&mut b).unwrap() { + h.amt += amt; + } else { + break + } + if h.amt >= N { + h.shutdown = true; + break + } + } + } + } + t.join().unwrap(); +} + +#[test] +fn peek() { + const N: usize = 16 * 1024 * 1024; + struct H { amt: usize, socket: TcpStream, shutdown: bool } + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let b = [0; 1024]; + let mut amt = 0; + while amt < N { + amt += s.write(&b).unwrap(); + } + }); + + let poll = Poll::new().unwrap(); + let s = TcpStream::connect(&addr).unwrap(); + + poll.register(&s, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { amt: 0, socket: s, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + assert_eq!(event.token(), Token(1)); + let mut b = [0; 1024]; + match h.socket.peek(&mut b) { + Ok(_) => (), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + continue + }, + Err(e) => panic!("unexpected error: {:?}", e), + } + + loop { + if let Some(amt) = h.socket.try_read(&mut b).unwrap() { + h.amt += amt; + } else { + break + } + if h.amt >= N { + h.shutdown = true; + break + } + } + } + } + t.join().unwrap(); +} + +#[test] +fn read_bufs() { + const N: usize = 16 * 1024 * 1024; + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let b = [1; 1024]; + let mut amt = 0; + while amt < N { + amt += s.write(&b).unwrap(); + } + }); + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(128); + + let s = TcpStream::connect(&addr).unwrap(); + + poll.register(&s, Token(1), Ready::readable(), PollOpt::level()).unwrap(); + + let b1 = &mut [0; 10][..]; + let b2 = &mut [0; 383][..]; + let b3 = &mut [0; 28][..]; + let b4 = &mut [0; 8][..]; + let b5 = &mut [0; 128][..]; + let mut b: [&mut IoVec; 5] = [ + b1.into(), + b2.into(), + b3.into(), + b4.into(), + b5.into(), + ]; + + let mut so_far = 0; + loop { + for buf in b.iter_mut() { + for byte in buf.as_mut_bytes() { + *byte = 0; + } + } + + poll.poll(&mut events, None).unwrap(); + + match s.read_bufs(&mut b) { + Ok(0) => { + assert_eq!(so_far, N); + break + } + Ok(mut n) => { + so_far += n; + for buf in b.iter() { + let buf = buf.as_bytes(); + for byte in buf[..cmp::min(n, buf.len())].iter() { + assert_eq!(*byte, 1); + } + n = n.saturating_sub(buf.len()); + if n == 0 { + break + } + } + assert_eq!(n, 0); + } + Err(e) => assert_eq!(e.kind(), io::ErrorKind::WouldBlock), + } + } + + t.join().unwrap(); +} + +#[test] +fn write() { + const N: usize = 16 * 1024 * 1024; + struct H { amt: usize, socket: TcpStream, shutdown: bool } + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let mut b = [0; 1024]; + let mut amt = 0; + while amt < N { + amt += s.read(&mut b).unwrap(); + } + }); + + let poll = Poll::new().unwrap(); + let s = TcpStream::connect(&addr).unwrap(); + + poll.register(&s, Token(1), Ready::writable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { amt: 0, socket: s, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + assert_eq!(event.token(), Token(1)); + let b = [0; 1024]; + loop { + if let Some(amt) = h.socket.try_write(&b).unwrap() { + h.amt += amt; + } else { + break + } + if h.amt >= N { + h.shutdown = true; + break + } + } + } + } + t.join().unwrap(); +} + +#[test] +fn write_bufs() { + const N: usize = 16 * 1024 * 1024; + + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let mut b = [0; 1024]; + let mut amt = 0; + while amt < N { + for byte in b.iter_mut() { + *byte = 0; + } + let n = s.read(&mut b).unwrap(); + amt += n; + for byte in b[..n].iter() { + assert_eq!(*byte, 1); + } + } + }); + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(128); + let s = TcpStream::connect(&addr).unwrap(); + poll.register(&s, Token(1), Ready::writable(), PollOpt::level()).unwrap(); + + let b1 = &[1; 10][..]; + let b2 = &[1; 383][..]; + let b3 = &[1; 28][..]; + let b4 = &[1; 8][..]; + let b5 = &[1; 128][..]; + let b: [&IoVec; 5] = [ + b1.into(), + b2.into(), + b3.into(), + b4.into(), + b5.into(), + ]; + + let mut so_far = 0; + while so_far < N { + poll.poll(&mut events, None).unwrap(); + + match s.write_bufs(&b) { + Ok(n) => so_far += n, + Err(e) => assert_eq!(e.kind(), io::ErrorKind::WouldBlock), + } + } + + t.join().unwrap(); +} + +#[test] +fn connect_then_close() { + struct H { listener: TcpListener, shutdown: bool } + + let poll = Poll::new().unwrap(); + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let s = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + + poll.register(&l, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + poll.register(&s, Token(2), Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(128); + + let mut h = H { listener: l, shutdown: false }; + while !h.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.token() == Token(1) { + let s = h.listener.accept().unwrap().0; + poll.register(&s, Token(3), Ready::readable() | Ready::writable(), + PollOpt::edge()).unwrap(); + drop(s); + } else if event.token() == Token(2) { + h.shutdown = true; + } + } + } +} + +#[test] +fn listen_then_close() { + let poll = Poll::new().unwrap(); + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + poll.register(&l, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + drop(l); + + let mut events = Events::with_capacity(128); + + poll.poll(&mut events, Some(Duration::from_millis(100))).unwrap(); + + for event in &events { + if event.token() == Token(1) { + panic!("recieved ready() on a closed TcpListener") + } + } +} + +fn assert_send() { +} + +fn assert_sync() { +} + +#[test] +fn test_tcp_sockets_are_send() { + assert_send::(); + assert_send::(); + assert_sync::(); + assert_sync::(); +} + +#[test] +fn bind_twice_bad() { + let l1 = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let addr = l1.local_addr().unwrap(); + assert!(TcpListener::bind(&addr).is_err()); +} + +#[test] +fn multiple_writes_immediate_success() { + const N: usize = 16; + let l = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = l.local_addr().unwrap(); + + let t = thread::spawn(move || { + let mut s = l.accept().unwrap().0; + let mut b = [0; 1024]; + let mut amt = 0; + while amt < 1024*N { + for byte in b.iter_mut() { + *byte = 0; + } + let n = s.read(&mut b).unwrap(); + amt += n; + for byte in b[..n].iter() { + assert_eq!(*byte, 1); + } + } + }); + + let poll = Poll::new().unwrap(); + let mut s = TcpStream::connect(&addr).unwrap(); + poll.register(&s, Token(1), Ready::writable(), PollOpt::level()).unwrap(); + let mut events = Events::with_capacity(16); + + // Wait for our TCP stream to connect + 'outer: loop { + poll.poll(&mut events, None).unwrap(); + for event in events.iter() { + if event.token() == Token(1) && event.readiness().is_writable() { + break 'outer + } + } + } + + for _ in 0..N { + s.write_all(&[1; 1024]).unwrap(); + } + + t.join().unwrap(); +} + +#[test] +fn connection_reset_by_peer() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(16); + let mut buf = [0u8; 16]; + + // Create listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let addr = l.local_addr().unwrap(); + + // Connect client + let client = net2::TcpBuilder::new_v4().unwrap() + .to_tcp_stream().unwrap(); + + client.set_linger(Some(Duration::from_millis(0))).unwrap(); + client.connect(&addr).unwrap(); + + // Convert to Mio stream + let client = TcpStream::from_stream(client).unwrap(); + + // Register server + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + + // Register interest in the client + poll.register(&client, Token(1), Ready::readable() | Ready::writable(), PollOpt::edge()).unwrap(); + + // Wait for listener to be ready + let mut server; + 'outer: + loop { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.token() == Token(0) { + match l.accept() { + Ok((sock, _)) => { + server = sock; + break 'outer; + } + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => panic!("unexpected error {:?}", e), + } + } + } + } + + // Close the connection + drop(client); + + // Wait a moment + thread::sleep(Duration::from_millis(100)); + + // Register interest in the server socket + poll.register(&server, Token(3), Ready::readable(), PollOpt::edge()).unwrap(); + + + loop { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.token() == Token(3) { + assert!(event.readiness().is_readable()); + + match server.read(&mut buf) { + Ok(0) | + Err(_) => {}, + + Ok(x) => panic!("expected empty buffer but read {} bytes", x), + } + return; + } + } + } + +} + +#[test] +#[cfg_attr(target_os = "fuchsia", ignore)] +fn connect_error() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(16); + + // Pick a "random" port that shouldn't be in use. + let l = match TcpStream::connect(&"127.0.0.1:38381".parse().unwrap()) { + Ok(l) => l, + Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => { + // Connection failed synchronously. This is not a bug, but it + // unfortunately doesn't get us the code coverage we want. + return; + }, + Err(e) => panic!("TcpStream::connect unexpected error {:?}", e) + }; + + poll.register(&l, Token(0), Ready::writable(), PollOpt::edge()).unwrap(); + + 'outer: + loop { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.token() == Token(0) { + assert!(event.readiness().is_writable()); + break 'outer + } + } + } + + assert!(l.take_error().unwrap().is_some()); +} + +#[test] +fn write_error() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(16); + let (tx, rx) = channel(); + + let listener = net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let t = thread::spawn(move || { + let (conn, _addr) = listener.accept().unwrap(); + rx.recv().unwrap(); + drop(conn); + }); + + let mut s = TcpStream::connect(&addr).unwrap(); + poll.register(&s, + Token(0), + Ready::readable() | Ready::writable(), + PollOpt::edge()).unwrap(); + + let mut wait_writable = || { + 'outer: + loop { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.token() == Token(0) && event.readiness().is_writable() { + break 'outer + } + } + } + }; + + wait_writable(); + + tx.send(()).unwrap(); + t.join().unwrap(); + + let buf = [0; 1024]; + loop { + match s.write(&buf) { + Ok(_) => {} + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + wait_writable() + } + Err(e) => { + println!("good error: {}", e); + break + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_level.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_level.rs new file mode 100644 index 0000000..c384caa --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_level.rs @@ -0,0 +1,142 @@ +use {expect_events, sleep_ms, TryRead}; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::event::Event; +use mio::net::{TcpListener, TcpStream}; +use std::io::Write; +use std::time::Duration; + +const MS: u64 = 1_000; + +#[test] +pub fn test_tcp_listener_level_triggered() { + let poll = Poll::new().unwrap(); + let mut pevents = Events::with_capacity(1024); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::level()).unwrap(); + + let s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + poll.register(&s1, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + while filter(&pevents, Token(0)).is_empty() { + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + } + let events = filter(&pevents, Token(0)); + + assert_eq!(events.len(), 1); + assert_eq!(events[0], Event::new(Ready::readable(), Token(0))); + + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + let events = filter(&pevents, Token(0)); + assert_eq!(events.len(), 1); + assert_eq!(events[0], Event::new(Ready::readable(), Token(0))); + + // Accept the connection then test that the events stop + let _ = l.accept().unwrap(); + + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + let events = filter(&pevents, Token(0)); + assert!(events.is_empty(), "actual={:?}", events); + + let s3 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + poll.register(&s3, Token(2), Ready::readable(), PollOpt::edge()).unwrap(); + + while filter(&pevents, Token(0)).is_empty() { + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + } + let events = filter(&pevents, Token(0)); + + assert_eq!(events.len(), 1); + assert_eq!(events[0], Event::new(Ready::readable(), Token(0))); + + drop(l); + + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + let events = filter(&pevents, Token(0)); + assert!(events.is_empty()); +} + +#[test] +pub fn test_tcp_stream_level_triggered() { + drop(::env_logger::init()); + let poll = Poll::new().unwrap(); + let mut pevents = Events::with_capacity(1024); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge()).unwrap(); + + let mut s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + poll.register(&s1, Token(1), Ready::readable() | Ready::writable(), PollOpt::level()).unwrap(); + + // Sleep a bit to ensure it arrives at dest + sleep_ms(250); + + expect_events(&poll, &mut pevents, 2, vec![ + Event::new(Ready::readable(), Token(0)), + Event::new(Ready::writable(), Token(1)), + ]); + + // Server side of socket + let (mut s1_tx, _) = l.accept().unwrap(); + + // Sleep a bit to ensure it arrives at dest + sleep_ms(250); + + expect_events(&poll, &mut pevents, 2, vec![ + Event::new(Ready::writable(), Token(1)) + ]); + + // Register the socket + poll.register(&s1_tx, Token(123), Ready::readable(), PollOpt::edge()).unwrap(); + + debug!("writing some data ----------"); + + // Write some data + let res = s1_tx.write(b"hello world!"); + assert!(res.unwrap() > 0); + + // Sleep a bit to ensure it arrives at dest + sleep_ms(250); + + debug!("looking at rx end ----------"); + + // Poll rx end + expect_events(&poll, &mut pevents, 2, vec![ + Event::new(Ready::readable(), Token(1)) + ]); + + debug!("reading ----------"); + + // Reading the data should clear it + let mut res = vec![]; + while s1.try_read_buf(&mut res).unwrap().is_some() { + } + + assert_eq!(res, b"hello world!"); + + debug!("checking just read ----------"); + + expect_events(&poll, &mut pevents, 1, vec![ + Event::new(Ready::writable(), Token(1))]); + + // Closing the socket clears all active level events + drop(s1); + + debug!("checking everything is gone ----------"); + + poll.poll(&mut pevents, Some(Duration::from_millis(MS))).unwrap(); + let events = filter(&pevents, Token(1)); + assert!(events.is_empty()); +} + +fn filter(events: &Events, token: Token) -> Vec { + (0..events.len()).map(|i| events.get(i).unwrap()) + .filter(|e| e.token() == token) + .collect() +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_shutdown.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_shutdown.rs new file mode 100644 index 0000000..9363f83 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_tcp_shutdown.rs @@ -0,0 +1,248 @@ +use std::collections::HashMap; +use std::net::{self, Shutdown}; +use std::time::{Duration, Instant}; + +use mio::{Token, Ready, PollOpt, Poll, Events}; +use mio::event::{Evented, Event}; +use mio::net::TcpStream; + +struct TestPoll { + poll: Poll, + events: Events, + buf: HashMap, +} + +impl TestPoll { + fn new() -> TestPoll { + TestPoll { + poll: Poll::new().unwrap(), + events: Events::with_capacity(1024), + buf: HashMap::new(), + } + } + + fn register(&self, handle: &E, token: Token, interest: Ready, opts: PollOpt) + where E: Evented + { + self.poll.register(handle, token, interest, opts).unwrap(); + } + + fn wait_for(&mut self, token: Token, ready: Ready) -> Result<(), &'static str> { + let now = Instant::now(); + + loop { + if now.elapsed() > Duration::from_secs(1) { + return Err("not ready"); + } + + if let Some(curr) = self.buf.get(&token) { + if curr.contains(ready) { + break; + } + } + + self.poll.poll(&mut self.events, Some(Duration::from_millis(250))).unwrap(); + + for event in &self.events { + let curr = self.buf.entry(event.token()) + .or_insert(Ready::empty()); + + *curr |= event.readiness(); + } + } + + *self.buf.get_mut(&token).unwrap() -= ready; + Ok(()) + } + + fn check_idle(&mut self) -> Result<(), Event> { + self.poll.poll(&mut self.events, Some(Duration::from_millis(100))).unwrap(); + + if let Some(e) = self.events.iter().next() { + Err(e) + } else { + Ok(()) + } + } +} + +macro_rules! assert_ready { + ($poll:expr, $token:expr, $ready:expr) => {{ + match $poll.wait_for($token, $ready) { + Ok(_) => {} + Err(_) => panic!("not ready; token = {:?}; interest = {:?}", $token, $ready), + } + }} +} + +macro_rules! assert_not_ready { + ($poll:expr, $token:expr, $ready:expr) => {{ + match $poll.wait_for($token, $ready) { + Ok(_) => panic!("is ready; token = {:?}; interest = {:?}", $token, $ready), + Err(_) => {} + } + }} +} + +macro_rules! assert_hup_ready { + ($poll:expr) => { + #[cfg(unix)] + { + use mio::unix::UnixReady; + assert_ready!($poll, Token(0), Ready::from(UnixReady::hup())) + } + } +} + +macro_rules! assert_not_hup_ready { + ($poll:expr) => { + #[cfg(unix)] + { + use mio::unix::UnixReady; + assert_not_ready!($poll, Token(0), Ready::from(UnixReady::hup())) + } + } +} + +macro_rules! assert_idle { + ($poll:expr) => { + match $poll.check_idle() { + Ok(()) => {} + Err(e) => panic!("not idle; event = {:?}", e), + } + } +} + +// TODO: replace w/ assertive +// https://github.com/carllerche/assertive +macro_rules! assert_ok { + ($e:expr) => { + assert_ok!($e,) + }; + ($e:expr,) => {{ + use std::result::Result::*; + match $e { + Ok(v) => v, + Err(e) => panic!("assertion failed: error = {:?}", e), + } + }}; + ($e:expr, $($arg:tt)+) => {{ + use std::result::Result::*; + match $e { + Ok(v) => v, + Err(e) => panic!("assertion failed: error = {:?}: {}", e, format_args!($($arg)+)), + } + }}; +} + +#[test] +fn test_write_shutdown() { + use std::io::prelude::*; + + let mut poll = TestPoll::new(); + let mut buf = [0; 1024]; + + let listener = assert_ok!(net::TcpListener::bind("127.0.0.1:0")); + let addr = assert_ok!(listener.local_addr()); + + let mut client = assert_ok!(TcpStream::connect(&addr)); + poll.register(&client, + Token(0), + Ready::readable() | Ready::writable(), + PollOpt::edge()); + + let (socket, _) = assert_ok!(listener.accept()); + + assert_ready!(poll, Token(0), Ready::writable()); + + // Polling should not have any events + assert_idle!(poll); + + // Now, shutdown the write half of the socket. + assert_ok!(socket.shutdown(Shutdown::Write)); + + assert_ready!(poll, Token(0), Ready::readable()); + + assert_not_hup_ready!(poll); + + let n = assert_ok!(client.read(&mut buf)); + assert_eq!(n, 0); +} + +#[test] +fn test_graceful_shutdown() { + use std::io::prelude::*; + + let mut poll = TestPoll::new(); + let mut buf = [0; 1024]; + + let listener = assert_ok!(net::TcpListener::bind("127.0.0.1:0")); + let addr = assert_ok!(listener.local_addr()); + + let mut client = assert_ok!(TcpStream::connect(&addr)); + poll.register(&client, + Token(0), + Ready::readable() | Ready::writable(), + PollOpt::edge()); + + let (mut socket, _) = assert_ok!(listener.accept()); + + assert_ready!(poll, Token(0), Ready::writable()); + + // Polling should not have any events + assert_idle!(poll); + + // Now, shutdown the write half of the socket. + assert_ok!(client.shutdown(Shutdown::Write)); + + let n = assert_ok!(socket.read(&mut buf)); + assert_eq!(0, n); + drop(socket); + + assert_ready!(poll, Token(0), Ready::readable()); + #[cfg(not(any(target_os = "bitrig", target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos", + target_os = "netbsd", target_os = "openbsd")))] + assert_hup_ready!(poll); + + let mut buf = [0; 1024]; + let n = assert_ok!(client.read(&mut buf)); + assert_eq!(n, 0); +} + +#[test] +fn test_abrupt_shutdown() { + use net2::TcpStreamExt; + use std::io::Read; + + let mut poll = TestPoll::new(); + let mut buf = [0; 1024]; + + let listener = assert_ok!(net::TcpListener::bind("127.0.0.1:0")); + let addr = assert_ok!(listener.local_addr()); + + let mut client = assert_ok!(TcpStream::connect(&addr)); + poll.register(&client, + Token(0), + Ready::readable() | Ready::writable(), + PollOpt::edge()); + + let (socket, _) = assert_ok!(listener.accept()); + assert_ok!(socket.set_linger(Some(Duration::from_millis(0)))); + // assert_ok!(socket.set_linger(None)); + + // Wait to be connected + assert_ready!(poll, Token(0), Ready::writable()); + + drop(socket); + + #[cfg(not(any(target_os = "bitrig", target_os = "dragonfly", + target_os = "freebsd", target_os = "ios", target_os = "macos", + target_os = "netbsd", target_os = "openbsd")))] + assert_hup_ready!(poll); + assert_ready!(poll, Token(0), Ready::writable()); + assert_ready!(poll, Token(0), Ready::readable()); + + let res = client.read(&mut buf); + assert!(res.is_err(), "not err = {:?}", res); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_tick.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_tick.rs new file mode 100644 index 0000000..8c4cec9 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_tick.rs @@ -0,0 +1,64 @@ +use mio::*; +use mio::deprecated::{EventLoop, Handler}; +use mio::net::{TcpListener, TcpStream}; +use {sleep_ms}; + +struct TestHandler { + tick: usize, + state: usize, +} + +impl TestHandler { + fn new() -> TestHandler { + TestHandler { + tick: 0, + state: 0, + } + } +} + +impl Handler for TestHandler { + type Timeout = usize; + type Message = String; + + fn tick(&mut self, _event_loop: &mut EventLoop) { + debug!("Handler::tick()"); + self.tick += 1; + + assert_eq!(self.state, 1); + self.state = 0; + } + + fn ready(&mut self, _event_loop: &mut EventLoop, token: Token, events: Ready) { + debug!("READY: {:?} - {:?}", token, events); + if events.is_readable() { + debug!("Handler::ready() readable event"); + assert_eq!(token, Token(0)); + assert_eq!(self.state, 0); + self.state = 1; + } + } +} + +#[test] +pub fn test_tick() { + debug!("Starting TEST_TICK"); + let mut event_loop = EventLoop::new().expect("Couldn't make event loop"); + + let listener = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + event_loop.register(&listener, Token(0), Ready::readable(), PollOpt::level()).unwrap(); + + let client = TcpStream::connect(&listener.local_addr().unwrap()).unwrap(); + event_loop.register(&client, Token(1), Ready::readable(), PollOpt::edge()).unwrap(); + + sleep_ms(250); + + let mut handler = TestHandler::new(); + + for _ in 0..2 { + event_loop.run_once(&mut handler, None).unwrap(); + } + + assert!(handler.tick == 2, "actual={}", handler.tick); + assert!(handler.state == 0, "actual={}", handler.state); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_udp_level.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_udp_level.rs new file mode 100644 index 0000000..7e19d54 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_udp_level.rs @@ -0,0 +1,52 @@ +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::event::Event; +use mio::net::UdpSocket; +use {expect_events, sleep_ms}; + +#[test] +pub fn test_udp_level_triggered() { + let poll = Poll::new().unwrap(); + let poll = &poll; + let mut events = Events::with_capacity(1024); + let events = &mut events; + + // Create the listener + let tx = UdpSocket::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let rx = UdpSocket::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + poll.register(&tx, Token(0), Ready::readable() | Ready::writable(), PollOpt::level()).unwrap(); + poll.register(&rx, Token(1), Ready::readable() | Ready::writable(), PollOpt::level()).unwrap(); + + + for _ in 0..2 { + expect_events(poll, events, 2, vec![ + Event::new(Ready::writable(), Token(0)), + Event::new(Ready::writable(), Token(1)), + ]); + } + + tx.send_to(b"hello world!", &rx.local_addr().unwrap()).unwrap(); + + sleep_ms(250); + + for _ in 0..2 { + expect_events(poll, events, 2, vec![ + Event::new(Ready::readable() | Ready::writable(), Token(1)) + ]); + } + + let mut buf = [0; 200]; + while rx.recv_from(&mut buf).is_ok() {} + + for _ in 0..2 { + expect_events(poll, events, 4, vec![Event::new(Ready::writable(), Token(1))]); + } + + tx.send_to(b"hello world!", &rx.local_addr().unwrap()).unwrap(); + sleep_ms(250); + + expect_events(poll, events, 10, + vec![Event::new(Ready::readable() | Ready::writable(), Token(1))]); + + drop(rx); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_udp_socket.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_udp_socket.rs new file mode 100644 index 0000000..c331159 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_udp_socket.rs @@ -0,0 +1,252 @@ +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio::net::UdpSocket; +use bytes::{Buf, RingBuf, SliceBuf, MutBuf}; +use std::io::ErrorKind; +use std::str; +use std::time; +use localhost; +use iovec::IoVec; + +const LISTENER: Token = Token(0); +const SENDER: Token = Token(1); + +pub struct UdpHandlerSendRecv { + tx: UdpSocket, + rx: UdpSocket, + msg: &'static str, + buf: SliceBuf<'static>, + rx_buf: RingBuf, + connected: bool, + shutdown: bool, +} + +impl UdpHandlerSendRecv { + fn new(tx: UdpSocket, rx: UdpSocket, connected: bool, msg : &'static str) -> UdpHandlerSendRecv { + UdpHandlerSendRecv { + tx, + rx, + msg, + buf: SliceBuf::wrap(msg.as_bytes()), + rx_buf: RingBuf::new(1024), + connected, + shutdown: false, + } + } +} + +fn assert_send() { +} + +fn assert_sync() { +} + +#[cfg(test)] +fn test_send_recv_udp(tx: UdpSocket, rx: UdpSocket, connected: bool) { + debug!("Starting TEST_UDP_SOCKETS"); + let poll = Poll::new().unwrap(); + + assert_send::(); + assert_sync::(); + + // ensure that the sockets are non-blocking + let mut buf = [0; 128]; + assert_eq!(ErrorKind::WouldBlock, rx.recv_from(&mut buf).unwrap_err().kind()); + + info!("Registering SENDER"); + poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); + + info!("Registering LISTENER"); + poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + + info!("Starting event loop to test with..."); + let mut handler = UdpHandlerSendRecv::new(tx, rx, connected, "hello world"); + + while !handler.shutdown { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.readiness().is_readable() { + if let LISTENER = event.token() { + debug!("We are receiving a datagram now..."); + let cnt = unsafe { + if !handler.connected { + handler.rx.recv_from(handler.rx_buf.mut_bytes()).unwrap().0 + } else { + handler.rx.recv(handler.rx_buf.mut_bytes()).unwrap() + } + }; + + unsafe { MutBuf::advance(&mut handler.rx_buf, cnt); } + assert!(str::from_utf8(handler.rx_buf.bytes()).unwrap() == handler.msg); + handler.shutdown = true; + } + } + + if event.readiness().is_writable() { + if let SENDER = event.token() { + let cnt = if !handler.connected { + let addr = handler.rx.local_addr().unwrap(); + handler.tx.send_to(handler.buf.bytes(), &addr).unwrap() + } else { + handler.tx.send(handler.buf.bytes()).unwrap() + }; + + handler.buf.advance(cnt); + } + } + } + } +} + +/// Returns the sender and the receiver +fn connected_sockets() -> (UdpSocket, UdpSocket) { + let addr = localhost(); + let any = localhost(); + + let tx = UdpSocket::bind(&any).unwrap(); + let rx = UdpSocket::bind(&addr).unwrap(); + + let tx_addr = tx.local_addr().unwrap(); + let rx_addr = rx.local_addr().unwrap(); + + assert!(tx.connect(rx_addr).is_ok()); + assert!(rx.connect(tx_addr).is_ok()); + + (tx, rx) +} + +#[test] +pub fn test_udp_socket() { + let addr = localhost(); + let any = localhost(); + + let tx = UdpSocket::bind(&any).unwrap(); + let rx = UdpSocket::bind(&addr).unwrap(); + + test_send_recv_udp(tx, rx, false); +} + +#[test] +pub fn test_udp_socket_send_recv() { + let (tx, rx) = connected_sockets(); + + test_send_recv_udp(tx, rx, true); +} + +#[test] +pub fn test_udp_socket_discard() { + let addr = localhost(); + let any = localhost(); + let outside = localhost(); + + let tx = UdpSocket::bind(&any).unwrap(); + let rx = UdpSocket::bind(&addr).unwrap(); + let udp_outside = UdpSocket::bind(&outside).unwrap(); + + let tx_addr = tx.local_addr().unwrap(); + let rx_addr = rx.local_addr().unwrap(); + + assert!(tx.connect(rx_addr).is_ok()); + assert!(udp_outside.connect(rx_addr).is_ok()); + assert!(rx.connect(tx_addr).is_ok()); + + let poll = Poll::new().unwrap(); + + let r = udp_outside.send(b"hello world"); + assert!(r.is_ok() || r.unwrap_err().kind() == ErrorKind::WouldBlock); + + poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap(); + poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + + poll.poll(&mut events, Some(time::Duration::from_secs(5))).unwrap(); + + for event in &events { + if event.readiness().is_readable() { + if let LISTENER = event.token() { + assert!(false, "Expected to no receive a packet but got something") + } + } + } +} + +#[cfg(all(unix, not(target_os = "fuchsia")))] +#[test] +pub fn test_udp_socket_send_recv_bufs() { + let (tx, rx) = connected_sockets(); + + let poll = Poll::new().unwrap(); + + poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()) + .unwrap(); + + poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()) + .unwrap(); + + let mut events = Events::with_capacity(1024); + + let data = b"hello, world"; + let write_bufs: Vec<_> = vec![b"hello, " as &[u8], b"world"] + .into_iter() + .flat_map(IoVec::from_bytes) + .collect(); + let (a, b, c) = ( + &mut [0u8; 4] as &mut [u8], + &mut [0u8; 6] as &mut [u8], + &mut [0u8; 8] as &mut [u8], + ); + let mut read_bufs: Vec<_> = vec![a, b, c] + .into_iter() + .flat_map(IoVec::from_bytes_mut) + .collect(); + + let times = 5; + let mut rtimes = 0; + let mut wtimes = 0; + + 'outer: loop { + poll.poll(&mut events, None).unwrap(); + + for event in &events { + if event.readiness().is_readable() { + if let LISTENER = event.token() { + loop { + let cnt = match rx.recv_bufs(read_bufs.as_mut()) { + Ok(cnt) => cnt, + Err(ref e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => panic!("read error {}", e), + }; + assert_eq!(cnt, data.len()); + let res: Vec = read_bufs + .iter() + .flat_map(|buf| buf.iter()) + .cloned() + .collect(); + assert_eq!(&res[..cnt], &data[..cnt]); + rtimes += 1; + if rtimes == times { + break 'outer; + } + } + } + } + + if event.readiness().is_writable() { + if let SENDER = event.token() { + while wtimes < times { + let cnt = match tx.send_bufs(write_bufs.as_slice()) { + Ok(cnt) => cnt, + Err(ref e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => panic!("write error {}", e), + }; + assert_eq!(cnt, data.len()); + wtimes += 1; + } + } + } + } + } +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_uds_shutdown.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_uds_shutdown.rs new file mode 100644 index 0000000..bf96445 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_uds_shutdown.rs @@ -0,0 +1,300 @@ +use {TryRead, TryWrite}; +use mio::*; +use mio::deprecated::{EventLoop, Handler}; +use mio::deprecated::unix::*; +use bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf}; +use slab::Slab; +use std::io; +use std::path::PathBuf; +use tempdir::TempDir; + +const SERVER: Token = Token(10_000_000); +const CLIENT: Token = Token(10_000_001); + +struct EchoConn { + sock: UnixStream, + buf: Option, + mut_buf: Option, + token: Option, + interest: Ready +} + +impl EchoConn { + fn new(sock: UnixStream) -> EchoConn { + EchoConn { + sock: sock, + buf: None, + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token: None, + interest: Ready::hup() + } + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut buf = self.buf.take().unwrap(); + + match self.sock.try_write_buf(&mut buf) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + + self.buf = Some(buf); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CONN : we wrote {} bytes!", r); + + self.mut_buf = Some(buf.flip()); + + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + match self.sock.shutdown(Shutdown::Write) { + Err(e) => panic!(e), + _ => {}, + } + } + Err(e) => debug!("not implemented; client err={:?}", e), + } + + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CONN : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + debug!("CONN : we read {} bytes!", r); + + // prepare to provide this to writable + self.buf = Some(buf.flip()); + + self.interest.remove(Ready::readable()); + self.interest.insert(Ready::writable()); + } + Err(e) => { + debug!("not implemented; client err={:?}", e); + self.interest.remove(Ready::readable()); + } + + }; + + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, + PollOpt::edge()) + } +} + +struct EchoServer { + sock: UnixListener, + conns: Slab +} + +impl EchoServer { + fn accept(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("server accepting socket"); + + let sock = self.sock.accept().unwrap(); + let conn = EchoConn::new(sock,); + let tok = self.conns.insert(conn); + + // Register the connection + self.conns[tok].token = Some(Token(tok)); + event_loop.register(&self.conns[tok].sock, Token(tok), Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()) + .expect("could not register socket with event loop"); + + Ok(()) + } + + fn conn_readable(&mut self, event_loop: &mut EventLoop, + tok: Token) -> io::Result<()> { + debug!("server conn readable; tok={:?}", tok); + self.conn(tok).readable(event_loop) + } + + fn conn_writable(&mut self, event_loop: &mut EventLoop, + tok: Token) -> io::Result<()> { + debug!("server conn writable; tok={:?}", tok); + self.conn(tok).writable(event_loop) + } + + fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { + &mut self.conns[tok.into()] + } +} + +struct EchoClient { + sock: UnixStream, + msgs: Vec<&'static str>, + tx: SliceBuf<'static>, + rx: SliceBuf<'static>, + mut_buf: Option, + token: Token, + interest: Ready +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl EchoClient { + fn new(sock: UnixStream, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient { + let curr = msgs.remove(0); + + EchoClient { + sock: sock, + msgs: msgs, + tx: SliceBuf::wrap(curr.as_bytes()), + rx: SliceBuf::wrap(curr.as_bytes()), + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token: tok, + interest: Ready::none() + } + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket readable"); + + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CLIENT : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + if r == 0 { + self.interest.remove(Ready::readable()); + event_loop.shutdown(); + } else { + debug!("CLIENT : We read {} bytes!", r); + + // prepare for reading + let mut buf = buf.flip(); + + while buf.has_remaining() { + let actual = buf.read_byte().unwrap(); + let expect = self.rx.read_byte().unwrap(); + + assert!(actual == expect, "actual={}; expect={}", actual, expect); + } + + self.mut_buf = Some(buf.flip()); + if !self.rx.has_remaining() { + self.next_msg(event_loop).unwrap(); + } + } + } + Err(e) => { + panic!("not implemented; client err={:?}", e); + } + }; + + event_loop.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket writable"); + + match self.sock.try_write_buf(&mut self.tx) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CLIENT : we wrote {} bytes!", r); + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e) + } + + event_loop.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } + + fn next_msg(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + if self.msgs.is_empty() { + + return Ok(()); + } + + let curr = self.msgs.remove(0); + + debug!("client prepping next message"); + self.tx = SliceBuf::wrap(curr.as_bytes()); + self.rx = SliceBuf::wrap(curr.as_bytes()); + + self.interest.insert(Ready::writable()); + event_loop.reregister(&self.sock, self.token, self.interest, + PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct Echo { + server: EchoServer, + client: EchoClient, +} + +impl Echo { + fn new(srv: UnixListener, client: UnixStream, msgs: Vec<&'static str>) -> Echo { + Echo { + server: EchoServer { + sock: srv, + conns: Slab::with_capacity(128) + }, + client: EchoClient::new(client, CLIENT, msgs) + } + } +} + +impl Handler for Echo { + type Timeout = usize; + type Message = (); + + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, + events: Ready) { + debug!("ready {:?} {:?}", token, events); + if events.is_readable() { + match token { + SERVER => self.server.accept(event_loop).unwrap(), + CLIENT => self.client.readable(event_loop).unwrap(), + i => self.server.conn_readable(event_loop, i).unwrap() + } + } + + if events.is_writable() { + match token { + SERVER => panic!("received writable for token 0"), + CLIENT => self.client.writable(event_loop).unwrap(), + _ => self.server.conn_writable(event_loop, token).unwrap() + }; + } + } +} + +#[test] +pub fn test_echo_server() { + debug!("Starting TEST_ECHO_SERVER"); + let mut event_loop = EventLoop::new().unwrap(); + + let tmp_dir = TempDir::new("mio").unwrap(); + let addr = tmp_dir.path().join(&PathBuf::from("sock")); + + let srv = UnixListener::bind(&addr).unwrap(); + + event_loop.register(&srv, SERVER, Ready::readable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let sock = UnixStream::connect(&addr).unwrap(); + + // Connect to the server + event_loop.register(&sock, CLIENT, Ready::writable(), + PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Start the event loop + event_loop.run(&mut Echo::new(srv, sock, vec!["foo", "bar"])).unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_unix_echo_server.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_unix_echo_server.rs new file mode 100644 index 0000000..6531dea --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_unix_echo_server.rs @@ -0,0 +1,292 @@ +use {TryRead, TryWrite}; +use mio::*; +use mio::deprecated::{EventLoop, Handler}; +use mio::deprecated::unix::*; +use bytes::{Buf, ByteBuf, MutByteBuf, SliceBuf}; +use slab::Slab; +use std::path::PathBuf; +use std::io; +use tempdir::TempDir; + +const SERVER: Token = Token(10_000_000); +const CLIENT: Token = Token(10_000_001); + +struct EchoConn { + sock: UnixStream, + buf: Option, + mut_buf: Option, + token: Option, + interest: Ready, +} + +impl EchoConn { + fn new(sock: UnixStream) -> EchoConn { + EchoConn { + sock: sock, + buf: None, + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token: None, + interest: Ready::hup(), + } + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut buf = self.buf.take().unwrap(); + + match self.sock.try_write_buf(&mut buf) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + + self.buf = Some(buf); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CONN : we wrote {} bytes!", r); + + self.mut_buf = Some(buf.flip()); + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e), + } + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CONN : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + debug!("CONN : we read {} bytes!", r); + + // prepare to provide this to writable + self.buf = Some(buf.flip()); + + self.interest.remove(Ready::readable()); + self.interest.insert(Ready::writable()); + } + Err(e) => { + debug!("not implemented; client err={:?}", e); + self.interest.remove(Ready::readable()); + } + + }; + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct EchoServer { + sock: UnixListener, + conns: Slab +} + +impl EchoServer { + fn accept(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("server accepting socket"); + + let sock = self.sock.accept().unwrap(); + let conn = EchoConn::new(sock); + let tok = self.conns.insert(conn); + + // Register the connection + self.conns[tok].token = Some(Token(tok)); + event_loop.register(&self.conns[tok].sock, Token(tok), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()) + .expect("could not register socket with event loop"); + + Ok(()) + } + + fn conn_readable(&mut self, event_loop: &mut EventLoop, tok: Token) -> io::Result<()> { + debug!("server conn readable; tok={:?}", tok); + self.conn(tok).readable(event_loop) + } + + fn conn_writable(&mut self, event_loop: &mut EventLoop, tok: Token) -> io::Result<()> { + debug!("server conn writable; tok={:?}", tok); + self.conn(tok).writable(event_loop) + } + + fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { + &mut self.conns[tok.into()] + } +} + +struct EchoClient { + sock: UnixStream, + msgs: Vec<&'static str>, + tx: SliceBuf<'static>, + rx: SliceBuf<'static>, + mut_buf: Option, + token: Token, + interest: Ready, +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl EchoClient { + fn new(sock: UnixStream, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient { + let curr = msgs.remove(0); + + EchoClient { + sock: sock, + msgs: msgs, + tx: SliceBuf::wrap(curr.as_bytes()), + rx: SliceBuf::wrap(curr.as_bytes()), + mut_buf: Some(ByteBuf::mut_with_capacity(2048)), + token: tok, + interest: Ready::none(), + } + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket readable"); + + let mut buf = self.mut_buf.take().unwrap(); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + debug!("CLIENT : spurious read wakeup"); + self.mut_buf = Some(buf); + } + Ok(Some(r)) => { + debug!("CLIENT : We read {} bytes!", r); + + // prepare for reading + let mut buf = buf.flip(); + + debug!("CLIENT : buf = {:?} -- rx = {:?}", buf.bytes(), self.rx.bytes()); + while buf.has_remaining() { + let actual = buf.read_byte().unwrap(); + let expect = self.rx.read_byte().unwrap(); + + assert!(actual == expect, "actual={}; expect={}", actual, expect); + } + + self.mut_buf = Some(buf.flip()); + + self.interest.remove(Ready::readable()); + + if !self.rx.has_remaining() { + self.next_msg(event_loop).unwrap(); + } + } + Err(e) => { + panic!("not implemented; client err={:?}", e); + } + }; + + if !self.interest.is_none() { + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot())?; + } + + Ok(()) + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket writable"); + + match self.sock.try_write_buf(&mut self.tx) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CLIENT : we wrote {} bytes!", r); + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e) + } + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) + } + + fn next_msg(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + if self.msgs.is_empty() { + event_loop.shutdown(); + return Ok(()); + } + + let curr = self.msgs.remove(0); + + debug!("client prepping next message"); + self.tx = SliceBuf::wrap(curr.as_bytes()); + self.rx = SliceBuf::wrap(curr.as_bytes()); + + self.interest.insert(Ready::writable()); + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct Echo { + server: EchoServer, + client: EchoClient, +} + +impl Echo { + fn new(srv: UnixListener, client: UnixStream, msgs: Vec<&'static str>) -> Echo { + Echo { + server: EchoServer { + sock: srv, + conns: Slab::with_capacity(128) + }, + client: EchoClient::new(client, CLIENT, msgs) + } + } +} + +impl Handler for Echo { + type Timeout = usize; + type Message = (); + + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, events: Ready) { + if events.is_readable() { + match token { + SERVER => self.server.accept(event_loop).unwrap(), + CLIENT => self.client.readable(event_loop).unwrap(), + i => self.server.conn_readable(event_loop, i).unwrap() + }; + } + + if events.is_writable() { + match token { + SERVER => panic!("received writable for token 0"), + CLIENT => self.client.writable(event_loop).unwrap(), + _ => self.server.conn_writable(event_loop, token).unwrap() + }; + } + } +} + +#[test] +pub fn test_unix_echo_server() { + debug!("Starting TEST_UNIX_ECHO_SERVER"); + let mut event_loop = EventLoop::new().unwrap(); + + let tmp_dir = TempDir::new("mio").unwrap(); + let addr = tmp_dir.path().join(&PathBuf::from("sock")); + + let srv = UnixListener::bind(&addr).unwrap(); + + info!("listen for connections"); + event_loop.register(&srv, SERVER, Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let sock = UnixStream::connect(&addr).unwrap(); + + // Connect to the server + event_loop.register(&sock, CLIENT, Ready::writable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Start the event loop + event_loop.run(&mut Echo::new(srv, sock, vec!["foo", "bar"])).unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_unix_pass_fd.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_unix_pass_fd.rs new file mode 100644 index 0000000..a948bb2 --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_unix_pass_fd.rs @@ -0,0 +1,306 @@ +use {TryRead, TryWrite}; +use mio::*; +use mio::deprecated::{EventLoop, Handler}; +use mio::deprecated::unix::*; +use bytes::{Buf, ByteBuf, SliceBuf}; +use slab::Slab; +use std::path::PathBuf; +use std::io::{self, Read}; +use std::os::unix::io::{AsRawFd, FromRawFd}; +use tempdir::TempDir; + +const SERVER: Token = Token(10_000_000); +const CLIENT: Token = Token(10_000_001); + +struct EchoConn { + sock: UnixStream, + pipe_fd: Option, + token: Option, + interest: Ready, +} + +impl EchoConn { + fn new(sock: UnixStream) -> EchoConn { + EchoConn { + sock: sock, + pipe_fd: None, + token: None, + interest: Ready::hup(), + } + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let fd = self.pipe_fd.take().unwrap(); + + match self.sock.try_write_send_fd(b"x", fd.as_raw_fd()) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + + self.pipe_fd = Some(fd); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CONN : we wrote {} bytes!", r); + + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e), + } + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + let mut buf = ByteBuf::mut_with_capacity(2048); + + match self.sock.try_read_buf(&mut buf) { + Ok(None) => { + panic!("We just got readable, but were unable to read from the socket?"); + } + Ok(Some(r)) => { + debug!("CONN : we read {} bytes!", r); + self.interest.remove(Ready::readable()); + self.interest.insert(Ready::writable()); + } + Err(e) => { + debug!("not implemented; client err={:?}", e); + self.interest.remove(Ready::readable()); + } + + }; + + // create fd to pass back. Assume that the write will work + // without blocking, for simplicity -- we're only testing that + // the FD makes it through somehow + let (rd, mut wr) = pipe().unwrap(); + let mut buf = buf.flip(); + match wr.try_write_buf(&mut buf) { + Ok(None) => { + panic!("writing to our own pipe blocked :("); + } + Ok(Some(r)) => { + debug!("CONN: we wrote {} bytes to the FD", r); + } + Err(e) => { + panic!("not implemented; client err={:?}", e); + } + } + self.pipe_fd = Some(rd); + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token.unwrap(), self.interest, PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct EchoServer { + sock: UnixListener, + conns: Slab +} + +impl EchoServer { + fn accept(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("server accepting socket"); + + let sock = self.sock.accept().unwrap(); + let conn = EchoConn::new(sock); + let tok = self.conns.insert(conn); + + // Register the connection + self.conns[tok].token = Some(Token(tok)); + event_loop.register(&self.conns[tok].sock, Token(tok), Ready::readable(), PollOpt::edge() | PollOpt::oneshot()) + .expect("could not register socket with event loop"); + + Ok(()) + } + + fn conn_readable(&mut self, event_loop: &mut EventLoop, tok: Token) -> io::Result<()> { + debug!("server conn readable; tok={:?}", tok); + self.conn(tok).readable(event_loop) + } + + fn conn_writable(&mut self, event_loop: &mut EventLoop, tok: Token) -> io::Result<()> { + debug!("server conn writable; tok={:?}", tok); + self.conn(tok).writable(event_loop) + } + + fn conn<'a>(&'a mut self, tok: Token) -> &'a mut EchoConn { + &mut self.conns[tok.into()] + } +} + +struct EchoClient { + sock: UnixStream, + msgs: Vec<&'static str>, + tx: SliceBuf<'static>, + rx: SliceBuf<'static>, + token: Token, + interest: Ready, +} + + +// Sends a message and expects to receive the same exact message, one at a time +impl EchoClient { + fn new(sock: UnixStream, tok: Token, mut msgs: Vec<&'static str>) -> EchoClient { + let curr = msgs.remove(0); + + EchoClient { + sock: sock, + msgs: msgs, + tx: SliceBuf::wrap(curr.as_bytes()), + rx: SliceBuf::wrap(curr.as_bytes()), + token: tok, + interest: Ready::none(), + } + } + + fn readable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket readable"); + + let mut pipe: PipeReader; + let mut buf = [0; 256]; + + match self.sock.read_recv_fd(&mut buf) { + Ok((_, None)) => { + panic!("Did not receive passed file descriptor"); + } + Ok((r, Some(fd))) => { + assert_eq!(r, 1); + assert_eq!(b'x', buf[0]); + debug!("CLIENT : We read {} bytes!", r); + pipe = From::::from(unsafe { Io::from_raw_fd(fd) }); + } + Err(e) => { + panic!("not implemented; client err={:?}", e); + } + }; + + // read the data out of the FD itself + let n = match pipe.read(&mut buf) { + Ok(r) => { + debug!("CLIENT : We read {} bytes from the FD", r); + r + } + Err(e) => { + panic!("not implemented, client err={:?}", e); + } + }; + + for &actual in buf[0..n].iter() { + let expect = self.rx.read_byte().unwrap(); + assert!(actual == expect, "actual={}; expect={}", actual, expect); + } + + self.interest.remove(Ready::readable()); + + if !self.rx.has_remaining() { + self.next_msg(event_loop).unwrap(); + } + + if !self.interest.is_none() { + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot())?; + } + + Ok(()) + } + + fn writable(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + debug!("client socket writable"); + + match self.sock.try_write_buf(&mut self.tx) { + Ok(None) => { + debug!("client flushing buf; WOULDBLOCK"); + self.interest.insert(Ready::writable()); + } + Ok(Some(r)) => { + debug!("CLIENT : we wrote {} bytes!", r); + self.interest.insert(Ready::readable()); + self.interest.remove(Ready::writable()); + } + Err(e) => debug!("not implemented; client err={:?}", e) + } + + assert!(self.interest.is_readable() || self.interest.is_writable(), "actual={:?}", self.interest); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) + } + + fn next_msg(&mut self, event_loop: &mut EventLoop) -> io::Result<()> { + if self.msgs.is_empty() { + event_loop.shutdown(); + return Ok(()); + } + + let curr = self.msgs.remove(0); + + debug!("client prepping next message"); + self.tx = SliceBuf::wrap(curr.as_bytes()); + self.rx = SliceBuf::wrap(curr.as_bytes()); + + self.interest.insert(Ready::writable()); + event_loop.reregister(&self.sock, self.token, self.interest, PollOpt::edge() | PollOpt::oneshot()) + } +} + +struct Echo { + server: EchoServer, + client: EchoClient, +} + +impl Echo { + fn new(srv: UnixListener, client: UnixStream, msgs: Vec<&'static str>) -> Echo { + Echo { + server: EchoServer { + sock: srv, + conns: Slab::with_capacity(128) + }, + client: EchoClient::new(client, CLIENT, msgs) + } + } +} + +impl Handler for Echo { + type Timeout = usize; + type Message = (); + + fn ready(&mut self, event_loop: &mut EventLoop, token: Token, events: Ready) { + if events.is_readable() { + match token { + SERVER => self.server.accept(event_loop).unwrap(), + CLIENT => self.client.readable(event_loop).unwrap(), + i => self.server.conn_readable(event_loop, i).unwrap() + }; + } + + if events.is_writable() { + match token { + SERVER => panic!("received writable for token 0"), + CLIENT => self.client.writable(event_loop).unwrap(), + _ => self.server.conn_writable(event_loop, token).unwrap() + }; + } + } +} + +#[test] +pub fn test_unix_pass_fd() { + debug!("Starting TEST_UNIX_PASS_FD"); + let mut event_loop = EventLoop::new().unwrap(); + + let tmp_dir = TempDir::new("mio").unwrap(); + let addr = tmp_dir.path().join(&PathBuf::from("sock")); + + let srv = UnixListener::bind(&addr).unwrap(); + + info!("listen for connections"); + event_loop.register(&srv, SERVER, Ready::readable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + let sock = UnixStream::connect(&addr).unwrap(); + + // Connect to the server + event_loop.register(&sock, CLIENT, Ready::writable(), PollOpt::edge() | PollOpt::oneshot()).unwrap(); + + // Start the event loop + event_loop.run(&mut Echo::new(srv, sock, vec!["foo", "bar"])).unwrap(); +} diff --git a/third_party/cargo/vendor/mio-0.6.21/test/test_write_then_drop.rs b/third_party/cargo/vendor/mio-0.6.21/test/test_write_then_drop.rs new file mode 100644 index 0000000..971ffff --- /dev/null +++ b/third_party/cargo/vendor/mio-0.6.21/test/test_write_then_drop.rs @@ -0,0 +1,123 @@ +use std::io::{Write, Read}; + +use mio::event::Evented; +use mio::net::{TcpListener, TcpStream}; +use mio::{Poll, Events, Ready, PollOpt, Token}; + +#[test] +fn write_then_drop() { + drop(::env_logger::init()); + + let a = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let addr = a.local_addr().unwrap(); + let mut s = TcpStream::connect(&addr).unwrap(); + + let poll = Poll::new().unwrap(); + + a.register(&poll, + Token(1), + Ready::readable(), + PollOpt::edge()).unwrap(); + s.register(&poll, + Token(3), + Ready::empty(), + PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(1)); + + let mut s2 = a.accept().unwrap().0; + + s2.register(&poll, + Token(2), + Ready::writable(), + PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(2)); + + s2.write_all(&[1, 2, 3, 4]).unwrap(); + drop(s2); + + s.reregister(&poll, + Token(3), + Ready::readable(), + PollOpt::edge()).unwrap(); + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(3)); + + let mut buf = [0; 10]; + assert_eq!(s.read(&mut buf).unwrap(), 4); + assert_eq!(&buf[0..4], &[1, 2, 3, 4]); +} + +#[test] +fn write_then_deregister() { + drop(::env_logger::init()); + + let a = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + let addr = a.local_addr().unwrap(); + let mut s = TcpStream::connect(&addr).unwrap(); + + let poll = Poll::new().unwrap(); + + a.register(&poll, + Token(1), + Ready::readable(), + PollOpt::edge()).unwrap(); + s.register(&poll, + Token(3), + Ready::empty(), + PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(1)); + + let mut s2 = a.accept().unwrap().0; + + s2.register(&poll, + Token(2), + Ready::writable(), + PollOpt::edge()).unwrap(); + + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(2)); + + s2.write_all(&[1, 2, 3, 4]).unwrap(); + s2.deregister(&poll).unwrap(); + + s.reregister(&poll, + Token(3), + Ready::readable(), + PollOpt::edge()).unwrap(); + let mut events = Events::with_capacity(1024); + while events.is_empty() { + poll.poll(&mut events, None).unwrap(); + } + assert_eq!(events.len(), 1); + assert_eq!(events.get(0).unwrap().token(), Token(3)); + + let mut buf = [0; 10]; + assert_eq!(s.read(&mut buf).unwrap(), 4); + assert_eq!(&buf[0..4], &[1, 2, 3, 4]); +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/.cargo-checksum.json b/third_party/cargo/vendor/mio-extras-2.0.6/.cargo-checksum.json new file mode 100644 index 0000000..cb15205 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"499f8d84e8bee37198044301a5fdfe6a811dd19b62c2c771616185a7543b8334","Cargo.toml":"a4d1b4f5de2908b805a42b31472dfd5fee30a49dc4f575a174c581c7b57b25b7","LICENSE-APACHE":"406e5cbaa2ad1178c300cf28ac5258e8d0db0de4f061e78db559d30e6f38e25c","LICENSE-MIT":"8aa414e6c821efd8be6bade07368a5d9f51f5cc55718bc54e10a59eb826b8d58","README.md":"fa2642be7bd670014c5e25bafbee73b8be0667ddbd193c1cc344a71d7f59463f","src/channel.rs":"a9fb5bcf889b03766821011e94b30a351b80501523c4a9fe5c45796eae218968","src/lib.rs":"2ed1572d3255208681d017265df7f642eb4898b1c2dace91676935f55e03eb04","src/timer.rs":"a1e71e38ab983291557d534ce2454a0ba5872652f4e7c4161131ba5150ec8d57","test/mod.rs":"aa3afc2582f00e5e2a2e5b87d12eb9810b0eed3248b48abef7094fd8d02d9c41","test/test_poll_channel.rs":"508815e265ae44328fb3d7c98cdf210815a9946bde291dd896de81df0394de37","test/test_timer.rs":"d04b6f57e9a395ce190022c0158cc498805758101e9fdad18b63829eb9bb6510"},"package":"52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19"} \ No newline at end of file diff --git a/third_party/cargo/vendor/lock_api-0.1.5/BUILD b/third_party/cargo/vendor/mio-extras-2.0.6/BUILD similarity index 63% rename from third_party/cargo/vendor/lock_api-0.1.5/BUILD rename to third_party/cargo/vendor/mio-extras-2.0.6/BUILD index ab0e36b..0a3e1a5 100644 --- a/third_party/cargo/vendor/lock_api-0.1.5/BUILD +++ b/third_party/cargo/vendor/mio-extras-2.0.6/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "Apache-2.0,MIT" + "restricted", # "MIT OR Apache-2.0" ]) load( @@ -25,21 +25,23 @@ load( rust_library( - name = "lock_api", + name = "mio_extras", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/owning_ref-0.4.1:owning_ref", - "//third_party/cargo/vendor/scopeguard-0.3.3:scopeguard", + "//third_party/cargo/vendor/lazycell-1.2.1:lazycell", + "//third_party/cargo/vendor/log-0.4.8:log", + "//third_party/cargo/vendor/mio-0.6.21:mio", + "//third_party/cargo/vendor/slab-0.4.2:slab", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.1.5", + version = "2.0.6", crate_features = [ - "owning_ref", ], ) +# Unsupported target "test" with type "test" omitted diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/CHANGELOG.md b/third_party/cargo/vendor/mio-extras-2.0.6/CHANGELOG.md new file mode 100644 index 0000000..354b875 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/CHANGELOG.md @@ -0,0 +1,37 @@ +## 2.0.6 (7 Dec 2019) + +- fix license metadata in `Cargo.toml` (thanks @ignatenkobrain) + +## 2.0.5 (18 Jun 2018) + +- update `lazycell` from 0.6 -> 1.0 + +## 2.0.4 (7 Apr 2018) + +- Bump mio dependency (fixes minimal-versions build) + +## 2.0.3 (28 Dec 2017) + +- update `log` from 0.3 -> 0.4 + +## 2.0.2 + +- More docs tidying. + +## 2.0.1 + +- Another try at documenting the timer interface. + +## 2.0.0 + +- Remove channel implementation details from the API. Specifically, the + following are no longer public: + - `ctl_pair()` + - `SenderCtl` + - `ReceiverCtl` +- Document all APIs + +## 1.0.0 + +- Initial release. Essentially identical to + [mio-more](https://github.com/carllerche/mio-more). diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/Cargo.toml b/third_party/cargo/vendor/mio-extras-2.0.6/Cargo.toml new file mode 100644 index 0000000..d902a46 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/Cargo.toml @@ -0,0 +1,40 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "mio-extras" +version = "2.0.6" +authors = ["Carl Lerche ", "David Hotham"] +exclude = [".gitignore"] +description = "Extra components for use with Mio" +documentation = "https://docs.rs/mio-extras" +readme = "README.md" +keywords = ["io", "async", "non-blocking"] +categories = ["asynchronous"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/dimbleby/mio-extras" + +[[test]] +name = "test" +path = "test/mod.rs" +[dependencies.lazycell] +version = "1" + +[dependencies.log] +version = "0.4" + +[dependencies.mio] +version = "0.6.14" + +[dependencies.slab] +version = "0.4" diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-APACHE b/third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-APACHE similarity index 99% rename from third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-APACHE rename to third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-APACHE index 16fe87b..a6e8ded 100644 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-APACHE +++ b/third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-APACHE @@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work. same "printed page" as the copyright notice for easier identification within third-party archives. -Copyright [yyyy] [name of copyright owner] +Copyright 2017 Mio authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/LICENSE-MIT b/third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-MIT similarity index 96% rename from third_party/cargo/vendor/backtrace-sys-0.1.34/LICENSE-MIT rename to third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-MIT index 39e0ed6..4cf193e 100644 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/LICENSE-MIT +++ b/third_party/cargo/vendor/mio-extras-2.0.6/LICENSE-MIT @@ -1,4 +1,4 @@ -Copyright (c) 2014 Alex Crichton +Copyright (c) 2017 Mio authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/README.md b/third_party/cargo/vendor/mio-extras-2.0.6/README.md new file mode 100644 index 0000000..8ed136a --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/README.md @@ -0,0 +1,30 @@ +# mio-extras + +Extra components for use with [Mio](https://github.com/tokio-rs/mio): + +- a channel that implements `Evented` +- a timer that implements `Evented` + +[![Build Status](https://travis-ci.org/dimbleby/mio-extras.svg?branch=master)](https://travis-ci.org/dimbleby/mio-extras) +[![crates.io](http://meritbadge.herokuapp.com/mio-extras)](https://crates.io/crates/mio-extras) + +[Documentation](https://docs.rs/mio-extras). + +## History and maintenance + +This repository is forked from +[`mio-more`](https://github.com/carllerche/mio-more), which is unmaintained. + +I don't intend to do very much with this except for routine maintenance - bug +fixes, updating dependencies, and suchlike. + +However if you have some code that you think belongs here, then by all means +raise an issue or open a pull request. + +# License + +`mio-extras` is primarily distributed under the terms of both the MIT license +and the Apache License (Version 2.0), with portions covered by various BSD-like +licenses. + +See LICENSE-APACHE, and LICENSE-MIT for details. diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/src/channel.rs b/third_party/cargo/vendor/mio-extras-2.0.6/src/channel.rs new file mode 100644 index 0000000..561317e --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/src/channel.rs @@ -0,0 +1,431 @@ +//! Thread safe communication channel implementing `Evented` +use lazycell::{AtomicLazyCell, LazyCell}; +use mio::{Evented, Poll, PollOpt, Ready, Registration, SetReadiness, Token}; +use std::any::Any; +use std::error; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{mpsc, Arc}; +use std::{fmt, io}; + +/// Creates a new asynchronous channel, where the `Receiver` can be registered +/// with `Poll`. +pub fn channel() -> (Sender, Receiver) { + let (tx_ctl, rx_ctl) = ctl_pair(); + let (tx, rx) = mpsc::channel(); + + let tx = Sender { tx, ctl: tx_ctl }; + + let rx = Receiver { rx, ctl: rx_ctl }; + + (tx, rx) +} + +/// Creates a new synchronous, bounded channel where the `Receiver` can be +/// registered with `Poll`. +pub fn sync_channel(bound: usize) -> (SyncSender, Receiver) { + let (tx_ctl, rx_ctl) = ctl_pair(); + let (tx, rx) = mpsc::sync_channel(bound); + + let tx = SyncSender { tx, ctl: tx_ctl }; + + let rx = Receiver { rx, ctl: rx_ctl }; + + (tx, rx) +} + +fn ctl_pair() -> (SenderCtl, ReceiverCtl) { + let inner = Arc::new(Inner { + pending: AtomicUsize::new(0), + senders: AtomicUsize::new(1), + set_readiness: AtomicLazyCell::new(), + }); + + let tx = SenderCtl { + inner: Arc::clone(&inner), + }; + + let rx = ReceiverCtl { + registration: LazyCell::new(), + inner, + }; + + (tx, rx) +} + +/// Tracks messages sent on a channel in order to update readiness. +struct SenderCtl { + inner: Arc, +} + +/// Tracks messages received on a channel in order to track readiness. +struct ReceiverCtl { + registration: LazyCell, + inner: Arc, +} + +/// The sending half of a channel. +pub struct Sender { + tx: mpsc::Sender, + ctl: SenderCtl, +} + +/// The sending half of a synchronous channel. +pub struct SyncSender { + tx: mpsc::SyncSender, + ctl: SenderCtl, +} + +/// The receiving half of a channel. +pub struct Receiver { + rx: mpsc::Receiver, + ctl: ReceiverCtl, +} + +/// An error returned from the `Sender::send` or `SyncSender::send` function. +pub enum SendError { + /// An IO error. + Io(io::Error), + + /// The receiving half of the channel has disconnected. + Disconnected(T), +} + +/// An error returned from the `SyncSender::try_send` function. +pub enum TrySendError { + /// An IO error. + Io(io::Error), + + /// Data could not be sent because it would require the callee to block. + Full(T), + + /// The receiving half of the channel has disconnected. + Disconnected(T), +} + +struct Inner { + // The number of outstanding messages for the receiver to read + pending: AtomicUsize, + // The number of sender handles + senders: AtomicUsize, + // The set readiness handle + set_readiness: AtomicLazyCell, +} + +impl Sender { + /// Attempts to send a value on this channel, returning it back if it could not be sent. + pub fn send(&self, t: T) -> Result<(), SendError> { + self.tx.send(t).map_err(SendError::from).and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } +} + +impl Clone for Sender { + fn clone(&self) -> Sender { + Sender { + tx: self.tx.clone(), + ctl: self.ctl.clone(), + } + } +} + +impl SyncSender { + /// Sends a value on this synchronous channel. + /// + /// This function will *block* until space in the internal buffer becomes + /// available or a receiver is available to hand off the message to. + pub fn send(&self, t: T) -> Result<(), SendError> { + self.tx.send(t).map_err(From::from).and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } + + /// Attempts to send a value on this channel without blocking. + /// + /// This method differs from `send` by returning immediately if the channel's + /// buffer is full or no receiver is waiting to acquire some data. + pub fn try_send(&self, t: T) -> Result<(), TrySendError> { + self.tx.try_send(t).map_err(From::from).and_then(|_| { + self.ctl.inc()?; + Ok(()) + }) + } +} + +impl Clone for SyncSender { + fn clone(&self) -> SyncSender { + SyncSender { + tx: self.tx.clone(), + ctl: self.ctl.clone(), + } + } +} + +impl Receiver { + /// Attempts to return a pending value on this receiver without blocking. + pub fn try_recv(&self) -> Result { + self.rx.try_recv().and_then(|res| { + let _ = self.ctl.dec(); + Ok(res) + }) + } +} + +impl Evented for Receiver { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.ctl.register(poll, token, interest, opts) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + self.ctl.reregister(poll, token, interest, opts) + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + self.ctl.deregister(poll) + } +} + +/* + * + * ===== SenderCtl / ReceiverCtl ===== + * + */ + +impl SenderCtl { + /// Call to track that a message has been sent + fn inc(&self) -> io::Result<()> { + let cnt = self.inner.pending.fetch_add(1, Ordering::Acquire); + + if 0 == cnt { + // Toggle readiness to readable + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::readable())?; + } + } + + Ok(()) + } +} + +impl Clone for SenderCtl { + fn clone(&self) -> SenderCtl { + self.inner.senders.fetch_add(1, Ordering::Relaxed); + SenderCtl { + inner: Arc::clone(&self.inner), + } + } +} + +impl Drop for SenderCtl { + fn drop(&mut self) { + if self.inner.senders.fetch_sub(1, Ordering::Release) == 1 { + let _ = self.inc(); + } + } +} + +impl ReceiverCtl { + fn dec(&self) -> io::Result<()> { + let first = self.inner.pending.load(Ordering::Acquire); + + if first == 1 { + // Unset readiness + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::empty())?; + } + } + + // Decrement + let second = self.inner.pending.fetch_sub(1, Ordering::AcqRel); + + if first == 1 && second > 1 { + // There are still pending messages. Since readiness was + // previously unset, it must be reset here + if let Some(set_readiness) = self.inner.set_readiness.borrow() { + set_readiness.set_readiness(Ready::readable())?; + } + } + + Ok(()) + } +} + +impl Evented for ReceiverCtl { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + if self.registration.borrow().is_some() { + return Err(io::Error::new( + io::ErrorKind::Other, + "receiver already registered", + )); + } + + let (registration, set_readiness) = Registration::new2(); + poll.register(®istration, token, interest, opts)?; + + if self.inner.pending.load(Ordering::Relaxed) > 0 { + // TODO: Don't drop readiness + let _ = set_readiness.set_readiness(Ready::readable()); + } + + self.registration + .fill(registration) + .expect("unexpected state encountered"); + self.inner + .set_readiness + .fill(set_readiness) + .expect("unexpected state encountered"); + + Ok(()) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + match self.registration.borrow() { + Some(registration) => poll.reregister(registration, token, interest, opts), + None => Err(io::Error::new( + io::ErrorKind::Other, + "receiver not registered", + )), + } + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + match self.registration.borrow() { + Some(registration) => poll.deregister(registration), + None => Err(io::Error::new( + io::ErrorKind::Other, + "receiver not registered", + )), + } + } +} + +/* + * + * ===== Error conversions ===== + * + */ + +impl From> for SendError { + fn from(src: mpsc::SendError) -> SendError { + SendError::Disconnected(src.0) + } +} + +impl From for SendError { + fn from(src: io::Error) -> SendError { + SendError::Io(src) + } +} + +impl From> for TrySendError { + fn from(src: mpsc::TrySendError) -> TrySendError { + match src { + mpsc::TrySendError::Full(v) => TrySendError::Full(v), + mpsc::TrySendError::Disconnected(v) => TrySendError::Disconnected(v), + } + } +} + +impl From> for TrySendError { + fn from(src: mpsc::SendError) -> TrySendError { + TrySendError::Disconnected(src.0) + } +} + +impl From for TrySendError { + fn from(src: io::Error) -> TrySendError { + TrySendError::Io(src) + } +} + +/* + * + * ===== Implement Error, Debug and Display for Errors ===== + * + */ + +impl error::Error for SendError { + fn description(&self) -> &str { + match *self { + SendError::Io(ref io_err) => io_err.description(), + SendError::Disconnected(..) => "Disconnected", + } + } +} + +impl error::Error for TrySendError { + fn description(&self) -> &str { + match *self { + TrySendError::Io(ref io_err) => io_err.description(), + TrySendError::Full(..) => "Full", + TrySendError::Disconnected(..) => "Disconnected", + } + } +} + +impl fmt::Debug for SendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_send_error(self, f) + } +} + +impl fmt::Display for SendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_send_error(self, f) + } +} + +impl fmt::Debug for TrySendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_try_send_error(self, f) + } +} + +impl fmt::Display for TrySendError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_try_send_error(self, f) + } +} + +#[inline] +fn format_send_error(e: &SendError, f: &mut fmt::Formatter) -> fmt::Result { + match *e { + SendError::Io(ref io_err) => write!(f, "{}", io_err), + SendError::Disconnected(..) => write!(f, "Disconnected"), + } +} + +#[inline] +fn format_try_send_error(e: &TrySendError, f: &mut fmt::Formatter) -> fmt::Result { + match *e { + TrySendError::Io(ref io_err) => write!(f, "{}", io_err), + TrySendError::Full(..) => write!(f, "Full"), + TrySendError::Disconnected(..) => write!(f, "Disconnected"), + } +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/src/lib.rs b/third_party/cargo/vendor/mio-extras-2.0.6/src/lib.rs new file mode 100644 index 0000000..69a0005 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/src/lib.rs @@ -0,0 +1,33 @@ +//! Extra components for use with Mio. +#![deny(missing_docs)] +extern crate lazycell; +extern crate mio; +extern crate slab; + +#[macro_use] +extern crate log; + +pub mod channel; +pub mod timer; + +// Conversion utilities +mod convert { + use std::time::Duration; + + const NANOS_PER_MILLI: u32 = 1_000_000; + const MILLIS_PER_SEC: u64 = 1_000; + + /// Convert a `Duration` to milliseconds, rounding up and saturating at + /// `u64::MAX`. + /// + /// The saturating is fine because `u64::MAX` milliseconds are still many + /// million years. + pub fn millis(duration: Duration) -> u64 { + // Round up. + let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI; + duration + .as_secs() + .saturating_mul(MILLIS_PER_SEC) + .saturating_add(u64::from(millis)) + } +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/src/timer.rs b/third_party/cargo/vendor/mio-extras-2.0.6/src/timer.rs new file mode 100644 index 0000000..876026c --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/src/timer.rs @@ -0,0 +1,751 @@ +//! Timer optimized for I/O related operations +use crate::convert; +use lazycell::LazyCell; +use mio::{Evented, Poll, PollOpt, Ready, Registration, SetReadiness, Token}; +use slab::Slab; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use std::{cmp, fmt, io, iter, thread, u64, usize}; + +/// A timer. +/// +/// Typical usage goes like this: +/// +/// * register the timer with a `mio::Poll`. +/// * set a timeout, by calling `Timer::set_timeout`. Here you provide some +/// state to be associated with this timeout. +/// * poll the `Poll`, to learn when a timeout has occurred. +/// * retrieve state associated with the timeout by calling `Timer::poll`. +/// +/// You can omit use of the `Poll` altogether, if you like, and just poll the +/// `Timer` directly. +pub struct Timer { + // Size of each tick in milliseconds + tick_ms: u64, + // Slab of timeout entries + entries: Slab>, + // Timeout wheel. Each tick, the timer will look at the next slot for + // timeouts that match the current tick. + wheel: Vec, + // Tick 0's time instant + start: Instant, + // The current tick + tick: Tick, + // The next entry to possibly timeout + next: Token, + // Masks the target tick to get the slot + mask: u64, + // Set on registration with Poll + inner: LazyCell, +} + +/// Used to create a `Timer`. +pub struct Builder { + // Approximate duration of each tick + tick: Duration, + // Number of slots in the timer wheel + num_slots: usize, + // Max number of timeouts that can be in flight at a given time. + capacity: usize, +} + +/// A timeout, as returned by `Timer::set_timeout`. +/// +/// Use this as the argument to `Timer::cancel_timeout`, to cancel this timeout. +#[derive(Clone, Debug)] +pub struct Timeout { + // Reference into the timer entry slab + token: Token, + // Tick that it should match up with + tick: u64, +} + +struct Inner { + registration: Registration, + set_readiness: SetReadiness, + wakeup_state: WakeupState, + wakeup_thread: thread::JoinHandle<()>, +} + +impl Drop for Inner { + fn drop(&mut self) { + // 1. Set wakeup state to TERMINATE_THREAD + self.wakeup_state.store(TERMINATE_THREAD, Ordering::Release); + // 2. Wake him up + self.wakeup_thread.thread().unpark(); + } +} + +#[derive(Copy, Clone, Debug)] +struct WheelEntry { + next_tick: Tick, + head: Token, +} + +// Doubly linked list of timer entries. Allows for efficient insertion / +// removal of timeouts. +struct Entry { + state: T, + links: EntryLinks, +} + +#[derive(Copy, Clone)] +struct EntryLinks { + tick: Tick, + prev: Token, + next: Token, +} + +type Tick = u64; + +const TICK_MAX: Tick = u64::MAX; + +// Manages communication with wakeup thread +type WakeupState = Arc; + +const TERMINATE_THREAD: usize = 0; +const EMPTY: Token = Token(usize::MAX); + +impl Builder { + /// Set the tick duration. Default is 100ms. + pub fn tick_duration(mut self, duration: Duration) -> Builder { + self.tick = duration; + self + } + + /// Set the number of slots. Default is 256. + pub fn num_slots(mut self, num_slots: usize) -> Builder { + self.num_slots = num_slots; + self + } + + /// Set the capacity. Default is 65536. + pub fn capacity(mut self, capacity: usize) -> Builder { + self.capacity = capacity; + self + } + + /// Build a `Timer` with the parameters set on this `Builder`. + pub fn build(self) -> Timer { + Timer::new( + convert::millis(self.tick), + self.num_slots, + self.capacity, + Instant::now(), + ) + } +} + +impl Default for Builder { + fn default() -> Builder { + Builder { + tick: Duration::from_millis(100), + num_slots: 1 << 8, + capacity: 1 << 16, + } + } +} + +impl Timer { + fn new(tick_ms: u64, num_slots: usize, capacity: usize, start: Instant) -> Timer { + let num_slots = num_slots.next_power_of_two(); + let capacity = capacity.next_power_of_two(); + let mask = (num_slots as u64) - 1; + let wheel = iter::repeat(WheelEntry { + next_tick: TICK_MAX, + head: EMPTY, + }) + .take(num_slots) + .collect(); + + Timer { + tick_ms, + entries: Slab::with_capacity(capacity), + wheel, + start, + tick: 0, + next: EMPTY, + mask, + inner: LazyCell::new(), + } + } + + /// Set a timeout. + /// + /// When the timeout occurs, the given state becomes available via `poll`. + pub fn set_timeout(&mut self, delay_from_now: Duration, state: T) -> Timeout { + let delay_from_start = self.start.elapsed() + delay_from_now; + self.set_timeout_at(delay_from_start, state) + } + + fn set_timeout_at(&mut self, delay_from_start: Duration, state: T) -> Timeout { + let mut tick = duration_to_tick(delay_from_start, self.tick_ms); + trace!( + "setting timeout; delay={:?}; tick={:?}; current-tick={:?}", + delay_from_start, + tick, + self.tick + ); + + // Always target at least 1 tick in the future + if tick <= self.tick { + tick = self.tick + 1; + } + + self.insert(tick, state) + } + + fn insert(&mut self, tick: Tick, state: T) -> Timeout { + // Get the slot for the requested tick + let slot = (tick & self.mask) as usize; + let curr = self.wheel[slot]; + + // Insert the new entry + let entry = Entry::new(state, tick, curr.head); + let token = Token(self.entries.insert(entry)); + + if curr.head != EMPTY { + // If there was a previous entry, set its prev pointer to the new + // entry + self.entries[curr.head.into()].links.prev = token; + } + + // Update the head slot + self.wheel[slot] = WheelEntry { + next_tick: cmp::min(tick, curr.next_tick), + head: token, + }; + + self.schedule_readiness(tick); + + trace!("inserted timout; slot={}; token={:?}", slot, token); + + // Return the new timeout + Timeout { token, tick } + } + + /// Cancel a timeout. + /// + /// If the timeout has not yet occurred, the return value holds the + /// associated state. + pub fn cancel_timeout(&mut self, timeout: &Timeout) -> Option { + let links = match self.entries.get(timeout.token.into()) { + Some(e) => e.links, + None => return None, + }; + + // Sanity check + if links.tick != timeout.tick { + return None; + } + + self.unlink(&links, timeout.token); + Some(self.entries.remove(timeout.token.into()).state) + } + + /// Poll for an expired timer. + /// + /// The return value holds the state associated with the first expired + /// timer, if any. + pub fn poll(&mut self) -> Option { + let target_tick = current_tick(self.start, self.tick_ms); + self.poll_to(target_tick) + } + + fn poll_to(&mut self, mut target_tick: Tick) -> Option { + trace!( + "tick_to; target_tick={}; current_tick={}", + target_tick, + self.tick + ); + + if target_tick < self.tick { + target_tick = self.tick; + } + + while self.tick <= target_tick { + let curr = self.next; + + trace!("ticking; curr={:?}", curr); + + if curr == EMPTY { + self.tick += 1; + + let slot = self.slot_for(self.tick); + self.next = self.wheel[slot].head; + + // Handle the case when a slot has a single timeout which gets + // canceled before the timeout expires. In this case, the + // slot's head is EMPTY but there is a value for next_tick. Not + // resetting next_tick here causes the timer to get stuck in a + // loop. + if self.next == EMPTY { + self.wheel[slot].next_tick = TICK_MAX; + } + } else { + let slot = self.slot_for(self.tick); + + if curr == self.wheel[slot].head { + self.wheel[slot].next_tick = TICK_MAX; + } + + let links = self.entries[curr.into()].links; + + if links.tick <= self.tick { + trace!("triggering; token={:?}", curr); + + // Unlink will also advance self.next + self.unlink(&links, curr); + + // Remove and return the token + return Some(self.entries.remove(curr.into()).state); + } else { + let next_tick = self.wheel[slot].next_tick; + self.wheel[slot].next_tick = cmp::min(next_tick, links.tick); + self.next = links.next; + } + } + } + + // No more timeouts to poll + if let Some(inner) = self.inner.borrow() { + trace!("unsetting readiness"); + let _ = inner.set_readiness.set_readiness(Ready::empty()); + + if let Some(tick) = self.next_tick() { + self.schedule_readiness(tick); + } + } + + None + } + + fn unlink(&mut self, links: &EntryLinks, token: Token) { + trace!( + "unlinking timeout; slot={}; token={:?}", + self.slot_for(links.tick), + token + ); + + if links.prev == EMPTY { + let slot = self.slot_for(links.tick); + self.wheel[slot].head = links.next; + } else { + self.entries[links.prev.into()].links.next = links.next; + } + + if links.next != EMPTY { + self.entries[links.next.into()].links.prev = links.prev; + + if token == self.next { + self.next = links.next; + } + } else if token == self.next { + self.next = EMPTY; + } + } + + fn schedule_readiness(&self, tick: Tick) { + if let Some(inner) = self.inner.borrow() { + // Coordinate setting readiness w/ the wakeup thread + let mut curr = inner.wakeup_state.load(Ordering::Acquire); + + loop { + if curr as Tick <= tick { + // Nothing to do, wakeup is already scheduled + return; + } + + // Attempt to move the wakeup time forward + trace!("advancing the wakeup time; target={}; curr={}", tick, curr); + let actual = + inner + .wakeup_state + .compare_and_swap(curr, tick as usize, Ordering::Release); + + if actual == curr { + // Signal to the wakeup thread that the wakeup time has + // been changed. + trace!("unparking wakeup thread"); + inner.wakeup_thread.thread().unpark(); + return; + } + + curr = actual; + } + } + } + + // Next tick containing a timeout + fn next_tick(&self) -> Option { + if self.next != EMPTY { + let slot = self.slot_for(self.entries[self.next.into()].links.tick); + + if self.wheel[slot].next_tick == self.tick { + // There is data ready right now + return Some(self.tick); + } + } + + self.wheel.iter().map(|e| e.next_tick).min() + } + + fn slot_for(&self, tick: Tick) -> usize { + (self.mask & tick) as usize + } +} + +impl Default for Timer { + fn default() -> Timer { + Builder::default().build() + } +} + +impl Evented for Timer { + fn register( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + if self.inner.borrow().is_some() { + return Err(io::Error::new( + io::ErrorKind::Other, + "timer already registered", + )); + } + + let (registration, set_readiness) = Registration::new2(); + poll.register(®istration, token, interest, opts)?; + let wakeup_state = Arc::new(AtomicUsize::new(usize::MAX)); + let thread_handle = spawn_wakeup_thread( + Arc::clone(&wakeup_state), + set_readiness.clone(), + self.start, + self.tick_ms, + ); + + self.inner + .fill(Inner { + registration, + set_readiness, + wakeup_state, + wakeup_thread: thread_handle, + }) + .expect("timer already registered"); + + if let Some(next_tick) = self.next_tick() { + self.schedule_readiness(next_tick); + } + + Ok(()) + } + + fn reregister( + &self, + poll: &Poll, + token: Token, + interest: Ready, + opts: PollOpt, + ) -> io::Result<()> { + match self.inner.borrow() { + Some(inner) => poll.reregister(&inner.registration, token, interest, opts), + None => Err(io::Error::new( + io::ErrorKind::Other, + "receiver not registered", + )), + } + } + + fn deregister(&self, poll: &Poll) -> io::Result<()> { + match self.inner.borrow() { + Some(inner) => poll.deregister(&inner.registration), + None => Err(io::Error::new( + io::ErrorKind::Other, + "receiver not registered", + )), + } + } +} + +impl fmt::Debug for Inner { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Inner") + .field("registration", &self.registration) + .field("wakeup_state", &self.wakeup_state.load(Ordering::Relaxed)) + .finish() + } +} + +fn spawn_wakeup_thread( + state: WakeupState, + set_readiness: SetReadiness, + start: Instant, + tick_ms: u64, +) -> thread::JoinHandle<()> { + thread::spawn(move || { + let mut sleep_until_tick = state.load(Ordering::Acquire) as Tick; + + loop { + if sleep_until_tick == TERMINATE_THREAD as Tick { + return; + } + + let now_tick = current_tick(start, tick_ms); + + trace!( + "wakeup thread: sleep_until_tick={:?}; now_tick={:?}", + sleep_until_tick, + now_tick + ); + + if now_tick < sleep_until_tick { + // Calling park_timeout with u64::MAX leads to undefined + // behavior in pthread, causing the park to return immediately + // and causing the thread to tightly spin. Instead of u64::MAX + // on large values, simply use a blocking park. + match tick_ms.checked_mul(sleep_until_tick - now_tick) { + Some(sleep_duration) => { + trace!( + "sleeping; tick_ms={}; now_tick={}; sleep_until_tick={}; duration={:?}", + tick_ms, + now_tick, + sleep_until_tick, + sleep_duration + ); + thread::park_timeout(Duration::from_millis(sleep_duration)); + } + None => { + trace!( + "sleeping; tick_ms={}; now_tick={}; blocking sleep", + tick_ms, + now_tick + ); + thread::park(); + } + } + sleep_until_tick = state.load(Ordering::Acquire) as Tick; + } else { + let actual = + state.compare_and_swap(sleep_until_tick as usize, usize::MAX, Ordering::AcqRel) + as Tick; + + if actual == sleep_until_tick { + trace!("setting readiness from wakeup thread"); + let _ = set_readiness.set_readiness(Ready::readable()); + sleep_until_tick = usize::MAX as Tick; + } else { + sleep_until_tick = actual as Tick; + } + } + } + }) +} + +fn duration_to_tick(elapsed: Duration, tick_ms: u64) -> Tick { + // Calculate tick rounding up to the closest one + let elapsed_ms = convert::millis(elapsed); + elapsed_ms.saturating_add(tick_ms / 2) / tick_ms +} + +fn current_tick(start: Instant, tick_ms: u64) -> Tick { + duration_to_tick(start.elapsed(), tick_ms) +} + +impl Entry { + fn new(state: T, tick: u64, next: Token) -> Entry { + Entry { + state, + links: EntryLinks { + tick, + prev: EMPTY, + next, + }, + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + pub fn test_timeout_next_tick() { + let mut t = timer(); + let mut tick; + + t.set_timeout_at(Duration::from_millis(100), "a"); + + tick = ms_to_tick(&t, 50); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 100); + assert_eq!(Some("a"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 150); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 200); + assert_eq!(None, t.poll_to(tick)); + + assert_eq!(count(&t), 0); + } + + #[test] + pub fn test_clearing_timeout() { + let mut t = timer(); + let mut tick; + + let to = t.set_timeout_at(Duration::from_millis(100), "a"); + assert_eq!("a", t.cancel_timeout(&to).unwrap()); + + tick = ms_to_tick(&t, 100); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 200); + assert_eq!(None, t.poll_to(tick)); + + assert_eq!(count(&t), 0); + } + + #[test] + pub fn test_multiple_timeouts_same_tick() { + let mut t = timer(); + let mut tick; + + t.set_timeout_at(Duration::from_millis(100), "a"); + t.set_timeout_at(Duration::from_millis(100), "b"); + + let mut rcv = vec![]; + + tick = ms_to_tick(&t, 100); + rcv.push(t.poll_to(tick).unwrap()); + rcv.push(t.poll_to(tick).unwrap()); + + assert_eq!(None, t.poll_to(tick)); + + rcv.sort(); + assert!(rcv == ["a", "b"], "actual={:?}", rcv); + + tick = ms_to_tick(&t, 200); + assert_eq!(None, t.poll_to(tick)); + + assert_eq!(count(&t), 0); + } + + #[test] + pub fn test_multiple_timeouts_diff_tick() { + let mut t = timer(); + let mut tick; + + t.set_timeout_at(Duration::from_millis(110), "a"); + t.set_timeout_at(Duration::from_millis(220), "b"); + t.set_timeout_at(Duration::from_millis(230), "c"); + t.set_timeout_at(Duration::from_millis(440), "d"); + t.set_timeout_at(Duration::from_millis(560), "e"); + + tick = ms_to_tick(&t, 100); + assert_eq!(Some("a"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 200); + assert_eq!(Some("c"), t.poll_to(tick)); + assert_eq!(Some("b"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 300); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 400); + assert_eq!(Some("d"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 500); + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 600); + assert_eq!(Some("e"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + } + + #[test] + pub fn test_catching_up() { + let mut t = timer(); + + t.set_timeout_at(Duration::from_millis(110), "a"); + t.set_timeout_at(Duration::from_millis(220), "b"); + t.set_timeout_at(Duration::from_millis(230), "c"); + t.set_timeout_at(Duration::from_millis(440), "d"); + + let tick = ms_to_tick(&t, 600); + assert_eq!(Some("a"), t.poll_to(tick)); + assert_eq!(Some("c"), t.poll_to(tick)); + assert_eq!(Some("b"), t.poll_to(tick)); + assert_eq!(Some("d"), t.poll_to(tick)); + assert_eq!(None, t.poll_to(tick)); + } + + #[test] + pub fn test_timeout_hash_collision() { + let mut t = timer(); + let mut tick; + + t.set_timeout_at(Duration::from_millis(100), "a"); + t.set_timeout_at(Duration::from_millis(100 + TICK * SLOTS as u64), "b"); + + tick = ms_to_tick(&t, 100); + assert_eq!(Some("a"), t.poll_to(tick)); + assert_eq!(1, count(&t)); + + tick = ms_to_tick(&t, 200); + assert_eq!(None, t.poll_to(tick)); + assert_eq!(1, count(&t)); + + tick = ms_to_tick(&t, 100 + TICK * SLOTS as u64); + assert_eq!(Some("b"), t.poll_to(tick)); + assert_eq!(0, count(&t)); + } + + #[test] + pub fn test_clearing_timeout_between_triggers() { + let mut t = timer(); + let mut tick; + + let a = t.set_timeout_at(Duration::from_millis(100), "a"); + let _ = t.set_timeout_at(Duration::from_millis(100), "b"); + let _ = t.set_timeout_at(Duration::from_millis(200), "c"); + + tick = ms_to_tick(&t, 100); + assert_eq!(Some("b"), t.poll_to(tick)); + assert_eq!(2, count(&t)); + + t.cancel_timeout(&a); + assert_eq!(1, count(&t)); + + assert_eq!(None, t.poll_to(tick)); + + tick = ms_to_tick(&t, 200); + assert_eq!(Some("c"), t.poll_to(tick)); + assert_eq!(0, count(&t)); + } + + const TICK: u64 = 100; + const SLOTS: usize = 16; + const CAPACITY: usize = 32; + + fn count(timer: &Timer) -> usize { + timer.entries.len() + } + + fn timer() -> Timer<&'static str> { + Timer::new(TICK, SLOTS, CAPACITY, Instant::now()) + } + + fn ms_to_tick(timer: &Timer, ms: u64) -> u64 { + ms / timer.tick_ms + } +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/test/mod.rs b/third_party/cargo/vendor/mio-extras-2.0.6/test/mod.rs new file mode 100644 index 0000000..2170694 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/test/mod.rs @@ -0,0 +1,45 @@ +extern crate mio; +extern crate mio_extras; + +use mio::event::Event; +use mio::{Events, Poll}; +use std::time::Duration; + +mod test_poll_channel; +mod test_timer; + +pub fn expect_events( + poll: &Poll, + event_buffer: &mut Events, + poll_try_count: usize, + mut expected: Vec, +) { + const MS: u64 = 1_000; + + for _ in 0..poll_try_count { + poll.poll(event_buffer, Some(Duration::from_millis(MS))) + .unwrap(); + for event in event_buffer.iter() { + let pos_opt = match expected.iter().position(|exp_event| { + (event.token() == exp_event.token()) + && event.readiness().contains(exp_event.readiness()) + }) { + Some(x) => Some(x), + None => None, + }; + if let Some(pos) = pos_opt { + expected.remove(pos); + } + } + + if expected.is_empty() { + break; + } + } + + assert!( + expected.is_empty(), + "The following expected events were not found: {:?}", + expected + ); +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/test/test_poll_channel.rs b/third_party/cargo/vendor/mio-extras-2.0.6/test/test_poll_channel.rs new file mode 100644 index 0000000..7314f26 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/test/test_poll_channel.rs @@ -0,0 +1,362 @@ +use crate::expect_events; +use mio::event::Event; +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio_extras::channel; +use std::sync::mpsc::TryRecvError; +use std::thread; +use std::time::Duration; + +#[test] +pub fn test_poll_channel_edge() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::edge()) + .unwrap(); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(1, num); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Poll again and there should be no events + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Poll again, nothing + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push a value + tx.send("goodbye").unwrap(); + + // Have an event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(1, num); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Read the value + rx.try_recv().unwrap(); + + // Drop the sender half + drop(tx); + + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(1, num); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + match rx.try_recv() { + Err(TryRecvError::Disconnected) => {} + no => panic!("unexpected value {:?}", no), + } +} + +#[test] +pub fn test_poll_channel_oneshot() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register( + &rx, + Token(123), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(1, num); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + + // Poll again and there should be no events + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Poll again, nothing + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push a value + tx.send("goodbye").unwrap(); + + // Poll again, nothing + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Reregistering will re-trigger the notification + for _ in 0..3 { + poll.reregister( + &rx, + Token(123), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + // Have an event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(1, num); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + } + + // Get the value + assert_eq!("goodbye", rx.try_recv().unwrap()); + + poll.reregister( + &rx, + Token(123), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + // Have an event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + poll.reregister( + &rx, + Token(123), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + // Have an event + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_poll_channel_level() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::level()) + .unwrap(); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Polling will contain the event + for i in 0..5 { + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert!(1 == num, "actually got {} on iteration {}", num, i); + + let event = events.iter().next().unwrap(); + assert_eq!(event.token(), Token(123)); + assert_eq!(event.readiness(), Ready::readable()); + } + + // Read the value + assert_eq!("hello", rx.try_recv().unwrap()); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_poll_channel_writable() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::writable(), PollOpt::edge()) + .unwrap(); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); + + // Push the value + tx.send("hello").unwrap(); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_dropping_receive_before_poll() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + poll.register(&rx, Token(123), Ready::readable(), PollOpt::edge()) + .unwrap(); + + // Push the value + tx.send("hello").unwrap(); + + // Drop the receive end + drop(rx); + + // Wait, but nothing should happen + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(0, num); +} + +#[test] +pub fn test_mixing_channel_with_socket() { + use mio::net::{TcpListener, TcpStream}; + + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let (tx, rx) = channel::channel(); + + // Create the listener + let l = TcpListener::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(); + + // Register the listener with `Poll` + poll.register(&l, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + poll.register(&rx, Token(1), Ready::readable(), PollOpt::edge()) + .unwrap(); + + // Push a value onto the channel + tx.send("hello").unwrap(); + + // Connect a TCP socket + let s1 = TcpStream::connect(&l.local_addr().unwrap()).unwrap(); + + // Register the socket + poll.register(&s1, Token(2), Ready::readable(), PollOpt::edge()) + .unwrap(); + + // Sleep a bit to ensure it arrives at dest + thread::sleep(Duration::from_millis(250)); + + expect_events( + &poll, + &mut events, + 2, + vec![ + Event::new(Ready::empty(), Token(0)), + Event::new(Ready::empty(), Token(1)), + ], + ); +} + +#[test] +pub fn test_sending_from_other_thread_while_polling() { + const ITERATIONS: usize = 20; + const THREADS: usize = 5; + + // Make sure to run multiple times + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + + for _ in 0..ITERATIONS { + let (tx, rx) = channel::channel(); + poll.register(&rx, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + for _ in 0..THREADS { + let tx = tx.clone(); + + thread::spawn(move || { + thread::sleep(Duration::from_millis(50)); + tx.send("ping").unwrap(); + }); + } + + let mut recv = 0; + + while recv < THREADS { + let num = poll.poll(&mut events, None).unwrap(); + + if num != 0 { + assert_eq!(1, num); + assert_eq!(events.iter().next().unwrap().token(), Token(0)); + + while let Ok(_) = rx.try_recv() { + recv += 1; + } + } + } + } +} diff --git a/third_party/cargo/vendor/mio-extras-2.0.6/test/test_timer.rs b/third_party/cargo/vendor/mio-extras-2.0.6/test/test_timer.rs new file mode 100644 index 0000000..ac49833 --- /dev/null +++ b/third_party/cargo/vendor/mio-extras-2.0.6/test/test_timer.rs @@ -0,0 +1,308 @@ +use mio::{Events, Poll, PollOpt, Ready, Token}; +use mio_extras::timer::{self, Timer}; + +use std::thread; +use std::time::Duration; + +#[test] +fn test_basic_timer_without_poll() { + let mut timer = Timer::default(); + + // Set the timeout + timer.set_timeout(Duration::from_millis(200), "hello"); + + // Nothing when polled immediately + assert!(timer.poll().is_none()); + + // Wait for the timeout + thread::sleep(Duration::from_millis(250)); + + assert_eq!(Some("hello"), timer.poll()); + assert!(timer.poll().is_none()); +} + +#[test] +fn test_basic_timer_with_poll_edge_set_timeout_after_register() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + timer.set_timeout(Duration::from_millis(200), "hello"); + + let elapsed = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(200, elapsed), "actual={:?}", elapsed); + assert_eq!("hello", timer.poll().unwrap()); + assert_eq!(None, timer.poll()); +} + +#[test] +fn test_basic_timer_with_poll_edge_set_timeout_before_register() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + timer.set_timeout(Duration::from_millis(200), "hello"); + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + let elapsed = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(200, elapsed), "actual={:?}", elapsed); + assert_eq!("hello", timer.poll().unwrap()); + assert_eq!(None, timer.poll()); +} + +#[test] +fn test_setting_later_timeout_then_earlier_one() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + timer.set_timeout(Duration::from_millis(600), "hello"); + timer.set_timeout(Duration::from_millis(200), "world"); + + let elapsed = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(200, elapsed), "actual={:?}", elapsed); + assert_eq!("world", timer.poll().unwrap()); + assert_eq!(None, timer.poll()); + + let elapsed = self::elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(400, elapsed), "actual={:?}", elapsed); + assert_eq!("hello", timer.poll().unwrap()); + assert_eq!(None, timer.poll()); +} + +#[test] +fn test_timer_with_looping_wheel() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = timer::Builder::default().num_slots(2).build(); + + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + const TOKENS: &[&str] = &["hello", "world", "some", "thing"]; + + for (i, msg) in TOKENS.iter().enumerate() { + timer.set_timeout(Duration::from_millis(500 * (i as u64 + 1)), msg); + } + + for msg in TOKENS { + let elapsed = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!( + is_about(500, elapsed), + "actual={:?}; msg={:?}", + elapsed, + msg + ); + assert_eq!(Some(msg), timer.poll()); + assert_eq!(None, timer.poll()); + } +} + +#[test] +fn test_edge_without_polling() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + timer.set_timeout(Duration::from_millis(400), "hello"); + + let ms = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(400, ms), "actual={:?}", ms); + + let ms = elapsed(|| { + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(num, 0); + }); + + assert!(is_about(300, ms), "actual={:?}", ms); +} + +#[test] +fn test_level_triggered() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + poll.register(&timer, Token(0), Ready::readable(), PollOpt::level()) + .unwrap(); + + timer.set_timeout(Duration::from_millis(400), "hello"); + + let ms = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(400, ms), "actual={:?}", ms); + + let ms = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + assert_eq!(num, 1); + let event = events.iter().next().unwrap(); + assert_eq!(Token(0), event.token()); + assert_eq!(Ready::readable(), event.readiness()); + }); + + assert!(is_about(0, ms), "actual={:?}", ms); +} + +#[test] +fn test_edge_oneshot_triggered() { + let poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(1024); + let mut timer = Timer::default(); + + poll.register( + &timer, + Token(0), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + timer.set_timeout(Duration::from_millis(200), "hello"); + + let ms = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + assert_eq!(num, 1); + }); + + assert!(is_about(200, ms), "actual={:?}", ms); + + let ms = elapsed(|| { + let num = poll + .poll(&mut events, Some(Duration::from_millis(300))) + .unwrap(); + assert_eq!(num, 0); + }); + + assert!(is_about(300, ms), "actual={:?}", ms); + + poll.reregister( + &timer, + Token(0), + Ready::readable(), + PollOpt::edge() | PollOpt::oneshot(), + ) + .unwrap(); + + let ms = elapsed(|| { + let num = poll.poll(&mut events, None).unwrap(); + assert_eq!(num, 1); + }); + + assert!(is_about(0, ms)); +} + +#[test] +fn test_cancel_timeout() { + use std::time::Instant; + + let mut timer: Timer = Default::default(); + let timeout = timer.set_timeout(Duration::from_millis(200), 1); + timer.cancel_timeout(&timeout); + + let poll = Poll::new().unwrap(); + poll.register(&timer, Token(0), Ready::readable(), PollOpt::edge()) + .unwrap(); + + let mut events = Events::with_capacity(16); + + let now = Instant::now(); + let dur = Duration::from_millis(500); + let mut i = 0; + + while Instant::now() - now < dur { + if i > 10 { + panic!("iterated too many times"); + } + + i += 1; + + let elapsed = Instant::now() - now; + + poll.poll(&mut events, Some(dur - elapsed)).unwrap(); + + while let Some(_) = timer.poll() { + panic!("did not expect to receive timeout"); + } + } +} + +fn elapsed(mut f: F) -> u64 { + use std::time::Instant; + + let now = Instant::now(); + + f(); + + let elapsed = now.elapsed(); + elapsed.as_secs() * 1000 + u64::from(elapsed.subsec_millis()) +} + +fn is_about(expect: u64, val: u64) -> bool { + const WINDOW: i64 = 200; + + ((expect as i64) - (val as i64)).abs() <= WINDOW +} diff --git a/third_party/cargo/vendor/miow-0.2.1/.cargo-checksum.json b/third_party/cargo/vendor/miow-0.2.1/.cargo-checksum.json new file mode 100644 index 0000000..9e42c7d --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"7a72c6e4b9cce0cd1105ab0234e8b3caae6c1bd7af2c41eae39f031becfc5a37","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"05cefe09de4f980658e2868df1a220e3da5fd6ddb6d6c1eab1b5e6f5cb000879","appveyor.yml":"ffdfb9572a6362866bea6787a726b0d4e43f6bb6516f3a38ebdd561859531602","src/handle.rs":"ada6cf8482d49bc7be6d26adeb8ae47df9ff0a5637424474aa4a86ad699be63d","src/iocp.rs":"002fef559bbaf52ada0fcb7b94d6dbbaaedc94840b5870c186243e79120b7cfc","src/lib.rs":"0d30428e89c7a2be7e479148211360a56d6c6b3b5a86d5ee7254277484506efa","src/net.rs":"054b8772bf51acc80b74a261f2d759645332288e03c72e2bd05c555364fe05bf","src/overlapped.rs":"b3c7f7b45fd9b22090bd11563decb09e9c412db8757c0e7484cfaa9ec5e29b9c","src/pipe.rs":"97ef5d456d7e5a72af2c4509a8155bd45a2a755275524ce1cd2d79f44f264c65"},"package":"8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919"} \ No newline at end of file diff --git a/third_party/cargo/vendor/miow-0.2.1/BUILD b/third_party/cargo/vendor/miow-0.2.1/BUILD new file mode 100644 index 0000000..d79000d --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/BUILD @@ -0,0 +1,46 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT,Apache-2.0" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "miow", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/kernel32-sys-0.2.2:kernel32_sys", + "//third_party/cargo/vendor/net2-0.2.33:net2", + "//third_party/cargo/vendor/winapi-0.2.8:winapi", + "//third_party/cargo/vendor/ws2_32-sys-0.2.1:ws2_32_sys", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.2.1", + crate_features = [ + ], +) + diff --git a/third_party/cargo/vendor/miow-0.2.1/Cargo.toml b/third_party/cargo/vendor/miow-0.2.1/Cargo.toml new file mode 100644 index 0000000..6e42523 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "miow" +version = "0.2.1" +authors = ["Alex Crichton "] +license = "MIT/Apache-2.0" +readme = "README.md" +keywords = ["iocp", "windows", "io", "overlapped"] +repository = "https://github.com/alexcrichton/miow" +homepage = "https://github.com/alexcrichton/miow" +documentation = "https://docs.rs/miow/0.1/x86_64-pc-windows-msvc/miow/" +description = """ +A zero overhead I/O library for Windows, focusing on IOCP and Async I/O +abstractions. +""" + +[dependencies] +winapi = "0.2" +kernel32-sys = "0.2" +ws2_32-sys = "0.2" +net2 = { version = "0.2.5", default-features = false } + +[dev-dependencies] +rand = "0.3" diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/LICENSE-APACHE b/third_party/cargo/vendor/miow-0.2.1/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/num_cpus-1.12.0/LICENSE-APACHE rename to third_party/cargo/vendor/miow-0.2.1/LICENSE-APACHE diff --git a/third_party/cargo/vendor/backtrace-0.3.45/LICENSE-MIT b/third_party/cargo/vendor/miow-0.2.1/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/backtrace-0.3.45/LICENSE-MIT rename to third_party/cargo/vendor/miow-0.2.1/LICENSE-MIT diff --git a/third_party/cargo/vendor/miow-0.2.1/README.md b/third_party/cargo/vendor/miow-0.2.1/README.md new file mode 100644 index 0000000..947bd83 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/README.md @@ -0,0 +1,22 @@ +# miow + +[![Build status](https://ci.appveyor.com/api/projects/status/tc5lsxokjk86949l?svg=true)](https://ci.appveyor.com/project/alexcrichton/miow) + +[Documentation](https://docs.rs/miow/0.1/x86_64-pc-windows-msvc/miow/) + +A zero overhead Windows I/O library focusing on IOCP and other async I/O +features. + +```toml +# Cargo.toml +[dependencies] +miow = "0.1" +``` + +# License + +`miow` is primarily distributed under the terms of both the MIT license and +the Apache License (Version 2.0), with portions covered by various BSD-like +licenses. + +See LICENSE-APACHE, and LICENSE-MIT for details. diff --git a/third_party/cargo/vendor/miow-0.2.1/appveyor.yml b/third_party/cargo/vendor/miow-0.2.1/appveyor.yml new file mode 100644 index 0000000..2700e42 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/appveyor.yml @@ -0,0 +1,20 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu + GH_TOKEN: + secure: nHB4fVo+y/Aak+L0nYfrT8Rcs8OfUNm0F2xcIVFVYJ9ehf0CzvCmSMUvWguM0kKp + +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --target %TARGET% diff --git a/third_party/cargo/vendor/miow-0.2.1/src/handle.rs b/third_party/cargo/vendor/miow-0.2.1/src/handle.rs new file mode 100644 index 0000000..a2be11d --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/handle.rs @@ -0,0 +1,93 @@ +use std::io; +use std::cmp; + +use winapi::*; +use kernel32::*; + +#[derive(Debug)] +pub struct Handle(HANDLE); + +unsafe impl Send for Handle {} +unsafe impl Sync for Handle {} + +impl Handle { + pub fn new(handle: HANDLE) -> Handle { + Handle(handle) + } + + pub fn raw(&self) -> HANDLE { self.0 } + + pub fn into_raw(self) -> HANDLE { + use std::mem; + + let ret = self.0; + mem::forget(self); + ret + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + let mut bytes = 0; + let len = cmp::min(buf.len(), ::max_value() as usize) as DWORD; + try!(::cvt(unsafe { + WriteFile(self.0, buf.as_ptr() as *const _, len, &mut bytes, + 0 as *mut _) + })); + Ok(bytes as usize) + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + let mut bytes = 0; + let len = cmp::min(buf.len(), ::max_value() as usize) as DWORD; + try!(::cvt(unsafe { + ReadFile(self.0, buf.as_mut_ptr() as *mut _, len, &mut bytes, + 0 as *mut _) + })); + Ok(bytes as usize) + } + + pub unsafe fn read_overlapped(&self, buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let len = cmp::min(buf.len(), ::max_value() as usize) as DWORD; + let mut bytes = 0; + let res = ::cvt({ + ReadFile(self.0, + buf.as_mut_ptr() as *mut _, + len, + &mut bytes, + overlapped) + }); + match res { + Ok(_) => Ok(Some(bytes as usize)), + Err(ref e) if e.raw_os_error() == Some(ERROR_IO_PENDING as i32) + => Ok(None), + Err(e) => Err(e), + } + } + + pub unsafe fn write_overlapped(&self, buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let len = cmp::min(buf.len(), ::max_value() as usize) as DWORD; + let mut bytes = 0; + let res = ::cvt({ + WriteFile(self.0, + buf.as_ptr() as *const _, + len, + &mut bytes, + overlapped) + }); + match res { + Ok(_) => Ok(Some(bytes as usize)), + Err(ref e) if e.raw_os_error() == Some(ERROR_IO_PENDING as i32) + => Ok(None), + Err(e) => Err(e), + } + } +} + +impl Drop for Handle { + fn drop(&mut self) { + unsafe { CloseHandle(self.0) }; + } +} diff --git a/third_party/cargo/vendor/miow-0.2.1/src/iocp.rs b/third_party/cargo/vendor/miow-0.2.1/src/iocp.rs new file mode 100644 index 0000000..08b78d1 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/iocp.rs @@ -0,0 +1,313 @@ +//! Bindings to IOCP, I/O Completion Ports + +use std::cmp; +use std::io; +use std::mem; +use std::os::windows::io::*; +use std::time::Duration; + +use handle::Handle; +use winapi::*; +use kernel32::*; +use Overlapped; + +/// A handle to an Windows I/O Completion Port. +#[derive(Debug)] +pub struct CompletionPort { + handle: Handle, +} + +/// A status message received from an I/O completion port. +/// +/// These statuses can be created via the `new` or `empty` constructors and then +/// provided to a completion port, or they are read out of a completion port. +/// The fields of each status are read through its accessor methods. +#[derive(Clone, Copy, Debug)] +pub struct CompletionStatus(OVERLAPPED_ENTRY); + +unsafe impl Send for CompletionStatus {} +unsafe impl Sync for CompletionStatus {} + +impl CompletionPort { + /// Creates a new I/O completion port with the specified concurrency value. + /// + /// The number of threads given corresponds to the level of concurrency + /// allowed for threads associated with this port. Consult the Windows + /// documentation for more information about this value. + pub fn new(threads: u32) -> io::Result { + let ret = unsafe { + CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0 as *mut _, + 0, threads) + }; + if ret.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(CompletionPort { handle: Handle::new(ret) }) + } + } + + /// Associates a new `HANDLE` to this I/O completion port. + /// + /// This function will associate the given handle to this port with the + /// given `token` to be returned in status messages whenever it receives a + /// notification. + /// + /// Any object which is convertible to a `HANDLE` via the `AsRawHandle` + /// trait can be provided to this function, such as `std::fs::File` and + /// friends. + pub fn add_handle(&self, token: usize, + t: &T) -> io::Result<()> { + self._add(token, t.as_raw_handle()) + } + + /// Associates a new `SOCKET` to this I/O completion port. + /// + /// This function will associate the given socket to this port with the + /// given `token` to be returned in status messages whenever it receives a + /// notification. + /// + /// Any object which is convertible to a `SOCKET` via the `AsRawSocket` + /// trait can be provided to this function, such as `std::net::TcpStream` + /// and friends. + pub fn add_socket(&self, token: usize, + t: &T) -> io::Result<()> { + self._add(token, t.as_raw_socket() as HANDLE) + } + + fn _add(&self, token: usize, handle: HANDLE) -> io::Result<()> { + assert_eq!(mem::size_of_val(&token), mem::size_of::()); + let ret = unsafe { + CreateIoCompletionPort(handle, self.handle.raw(), + token as ULONG_PTR, 0) + }; + if ret.is_null() { + Err(io::Error::last_os_error()) + } else { + debug_assert_eq!(ret, self.handle.raw()); + Ok(()) + } + } + + /// Dequeue a completion status from this I/O completion port. + /// + /// This function will associate the calling thread with this completion + /// port and then wait for a status message to become available. The precise + /// semantics on when this function returns depends on the concurrency value + /// specified when the port was created. + /// + /// A timeout can optionally be specified to this function. If `None` is + /// provided this function will not time out, and otherwise it will time out + /// after the specified duration has passed. + /// + /// On success this will return the status message which was dequeued from + /// this completion port. + pub fn get(&self, timeout: Option) -> io::Result { + let mut bytes = 0; + let mut token = 0; + let mut overlapped = 0 as *mut _; + let timeout = ::dur2ms(timeout); + let ret = unsafe { + GetQueuedCompletionStatus(self.handle.raw(), + &mut bytes, + &mut token, + &mut overlapped, + timeout) + }; + ::cvt(ret).map(|_| { + CompletionStatus(OVERLAPPED_ENTRY { + dwNumberOfBytesTransferred: bytes, + lpCompletionKey: token, + lpOverlapped: overlapped, + Internal: 0, + }) + }) + } + + /// Dequeues a number of completion statuses from this I/O completion port. + /// + /// This function is the same as `get` except that it may return more than + /// one status. A buffer of "zero" statuses is provided (the contents are + /// not read) and then on success this function will return a sub-slice of + /// statuses which represent those which were dequeued from this port. This + /// function does not wait to fill up the entire list of statuses provided. + /// + /// Like with `get`, a timeout may be specified for this operation. + pub fn get_many<'a>(&self, + list: &'a mut [CompletionStatus], + timeout: Option) + -> io::Result<&'a mut [CompletionStatus]> + { + debug_assert_eq!(mem::size_of::(), + mem::size_of::()); + let mut removed = 0; + let timeout = ::dur2ms(timeout); + let len = cmp::min(list.len(), ::max_value() as usize) as ULONG; + let ret = unsafe { + GetQueuedCompletionStatusEx(self.handle.raw(), + list.as_ptr() as *mut _, + len, + &mut removed, + timeout, + FALSE) + }; + match ::cvt(ret) { + Ok(_) => Ok(&mut list[..removed as usize]), + Err(e) => Err(e), + } + } + + /// Posts a new completion status onto this I/O completion port. + /// + /// This function will post the given status, with custom parameters, to the + /// port. Threads blocked in `get` or `get_many` will eventually receive + /// this status. + pub fn post(&self, status: CompletionStatus) -> io::Result<()> { + let ret = unsafe { + PostQueuedCompletionStatus(self.handle.raw(), + status.0.dwNumberOfBytesTransferred, + status.0.lpCompletionKey, + status.0.lpOverlapped) + }; + ::cvt(ret).map(|_| ()) + } +} + +impl AsRawHandle for CompletionPort { + fn as_raw_handle(&self) -> HANDLE { + self.handle.raw() + } +} + +impl FromRawHandle for CompletionPort { + unsafe fn from_raw_handle(handle: HANDLE) -> CompletionPort { + CompletionPort { handle: Handle::new(handle) } + } +} + +impl IntoRawHandle for CompletionPort { + fn into_raw_handle(self) -> HANDLE { + self.handle.into_raw() + } +} + +impl CompletionStatus { + /// Creates a new completion status with the provided parameters. + /// + /// This function is useful when creating a status to send to a port with + /// the `post` method. The parameters are opaquely passed through and not + /// interpreted by the system at all. + pub fn new(bytes: u32, token: usize, overlapped: *mut Overlapped) + -> CompletionStatus { + assert_eq!(mem::size_of_val(&token), mem::size_of::()); + CompletionStatus(OVERLAPPED_ENTRY { + dwNumberOfBytesTransferred: bytes, + lpCompletionKey: token as ULONG_PTR, + lpOverlapped: overlapped as *mut _, + Internal: 0, + }) + } + + /// Creates a new borrowed completion status from the borrowed + /// `OVERLAPPED_ENTRY` argument provided. + /// + /// This method will wrap the `OVERLAPPED_ENTRY` in a `CompletionStatus`, + /// returning the wrapped structure. + pub fn from_entry(entry: &OVERLAPPED_ENTRY) -> &CompletionStatus { + unsafe { &*(entry as *const _ as *const _) } + } + + /// Creates a new "zero" completion status. + /// + /// This function is useful when creating a stack buffer or vector of + /// completion statuses to be passed to the `get_many` function. + pub fn zero() -> CompletionStatus { + CompletionStatus::new(0, 0, 0 as *mut _) + } + + /// Returns the number of bytes that were transferred for the I/O operation + /// associated with this completion status. + pub fn bytes_transferred(&self) -> u32 { + self.0.dwNumberOfBytesTransferred + } + + /// Returns the completion key value associated with the file handle whose + /// I/O operation has completed. + /// + /// A completion key is a per-handle key that is specified when it is added + /// to an I/O completion port via `add_handle` or `add_socket`. + pub fn token(&self) -> usize { + self.0.lpCompletionKey as usize + } + + /// Returns a pointer to the `Overlapped` structure that was specified when + /// the I/O operation was started. + pub fn overlapped(&self) -> *mut OVERLAPPED { + self.0.lpOverlapped + } + + /// Returns a pointer to the internal `OVERLAPPED_ENTRY` object. + pub fn entry(&self) -> &OVERLAPPED_ENTRY { + &self.0 + } +} + +#[cfg(test)] +mod tests { + use std::mem; + use std::time::Duration; + + use winapi::*; + + use iocp::{CompletionPort, CompletionStatus}; + + #[test] + fn is_send_sync() { + fn is_send_sync() {} + is_send_sync::(); + } + + #[test] + fn token_right_size() { + assert_eq!(mem::size_of::(), mem::size_of::()); + } + + #[test] + fn timeout() { + let c = CompletionPort::new(1).unwrap(); + let err = c.get(Some(Duration::from_millis(1))).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(WAIT_TIMEOUT as i32)); + } + + #[test] + fn get() { + let c = CompletionPort::new(1).unwrap(); + c.post(CompletionStatus::new(1, 2, 3 as *mut _)).unwrap(); + let s = c.get(None).unwrap(); + assert_eq!(s.bytes_transferred(), 1); + assert_eq!(s.token(), 2); + assert_eq!(s.overlapped(), 3 as *mut _); + } + + #[test] + fn get_many() { + let c = CompletionPort::new(1).unwrap(); + + c.post(CompletionStatus::new(1, 2, 3 as *mut _)).unwrap(); + c.post(CompletionStatus::new(4, 5, 6 as *mut _)).unwrap(); + + let mut s = vec![CompletionStatus::zero(); 4]; + { + let s = c.get_many(&mut s, None).unwrap(); + assert_eq!(s.len(), 2); + assert_eq!(s[0].bytes_transferred(), 1); + assert_eq!(s[0].token(), 2); + assert_eq!(s[0].overlapped(), 3 as *mut _); + assert_eq!(s[1].bytes_transferred(), 4); + assert_eq!(s[1].token(), 5); + assert_eq!(s[1].overlapped(), 6 as *mut _); + } + assert_eq!(s[2].bytes_transferred(), 0); + assert_eq!(s[2].token(), 0); + assert_eq!(s[2].overlapped(), 0 as *mut _); + } +} diff --git a/third_party/cargo/vendor/miow-0.2.1/src/lib.rs b/third_party/cargo/vendor/miow-0.2.1/src/lib.rs new file mode 100644 index 0000000..58643ff --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/lib.rs @@ -0,0 +1,57 @@ +//! A zero overhead Windows I/O library + +#![cfg(windows)] +#![deny(missing_docs)] +#![allow(bad_style)] +#![doc(html_root_url = "https://docs.rs/miow/0.1/x86_64-pc-windows-msvc/")] + +extern crate kernel32; +extern crate net2; +extern crate winapi; +extern crate ws2_32; + +#[cfg(test)] extern crate rand; + +use std::cmp; +use std::io; +use std::time::Duration; + +use winapi::*; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {:?}", stringify!($e), e), + }) +} + +mod handle; +mod overlapped; + +pub mod iocp; +pub mod net; +pub mod pipe; + +pub use overlapped::Overlapped; + +fn cvt(i: BOOL) -> io::Result { + if i == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(i) + } +} + +fn dur2ms(dur: Option) -> u32 { + let dur = match dur { + Some(dur) => dur, + None => return INFINITE, + }; + let ms = dur.as_secs().checked_mul(1_000); + let ms_extra = dur.subsec_nanos() / 1_000_000; + ms.and_then(|ms| { + ms.checked_add(ms_extra as u64) + }).map(|ms| { + cmp::min(u32::max_value() as u64, ms) as u32 + }).unwrap_or(INFINITE - 1) +} diff --git a/third_party/cargo/vendor/miow-0.2.1/src/net.rs b/third_party/cargo/vendor/miow-0.2.1/src/net.rs new file mode 100644 index 0000000..f3d1930 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/net.rs @@ -0,0 +1,1183 @@ +//! Extensions and types for the standard networking primitives. +//! +//! This module contains a number of extension traits for the types in +//! `std::net` for Windows-specific functionality. + +use std::cmp; +use std::io; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::net::{TcpStream, UdpSocket, SocketAddr, TcpListener}; +use std::net::{SocketAddrV4, Ipv4Addr, SocketAddrV6, Ipv6Addr}; +use std::os::windows::prelude::*; + +use net2::TcpBuilder; +use winapi::*; +use ws2_32::*; + +/// A type to represent a buffer in which a socket address will be stored. +/// +/// This type is used with the `recv_from_overlapped` function on the +/// `UdpSocketExt` trait to provide space for the overlapped I/O operation to +/// fill in the address upon completion. +#[derive(Clone, Copy)] +pub struct SocketAddrBuf { + buf: SOCKADDR_STORAGE, + len: c_int, +} + +/// A type to represent a buffer in which an accepted socket's address will be +/// stored. +/// +/// This type is used with the `accept_overlapped` method on the +/// `TcpListenerExt` trait to provide space for the overlapped I/O operation to +/// fill in the socket addresses upon completion. +#[repr(C)] +pub struct AcceptAddrsBuf { + // For AcceptEx we've got the restriction that the addresses passed in that + // buffer need to be at least 16 bytes more than the maximum address length + // for the protocol in question, so add some extra here and there + local: SOCKADDR_STORAGE, + _pad1: [u8; 16], + remote: SOCKADDR_STORAGE, + _pad2: [u8; 16], +} + +/// The parsed return value of `AcceptAddrsBuf`. +pub struct AcceptAddrs<'a> { + local: LPSOCKADDR, + local_len: c_int, + remote: LPSOCKADDR, + remote_len: c_int, + _data: &'a AcceptAddrsBuf, +} + +struct WsaExtension { + guid: GUID, + val: AtomicUsize, +} + +/// Additional methods for the `TcpStream` type in the standard library. +pub trait TcpStreamExt { + /// Execute an overlapped read I/O operation on this TCP stream. + /// + /// This function will issue an overlapped I/O read (via `WSARecv`) on this + /// socket. The provided buffer will be filled in when the operation + /// completes and the given `OVERLAPPED` instance is used to track the + /// overlapped operation. + /// + /// If the operation succeeds, `Ok(Some(n))` is returned indicating how + /// many bytes were read. If the operation returns an error indicating that + /// the I/O is currently pending, `Ok(None)` is returned. Otherwise, the + /// error associated with the operation is returned and no overlapped + /// operation is enqueued. + /// + /// The number of bytes read will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers are valid until the end of the I/O operation. The + /// kernel also requires that `overlapped` is unique for this I/O operation + /// and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn read_overlapped(&self, + buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Execute an overlapped write I/O operation on this TCP stream. + /// + /// This function will issue an overlapped I/O write (via `WSASend`) on this + /// socket. The provided buffer will be written when the operation completes + /// and the given `OVERLAPPED` instance is used to track the overlapped + /// operation. + /// + /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the + /// number of bytes that were written. If the operation returns an error + /// indicating that the I/O is currently pending, `Ok(None)` is returned. + /// Otherwise, the error associated with the operation is returned and no + /// overlapped operation is enqueued. + /// + /// The number of bytes written will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers are valid until the end of the I/O operation. The + /// kernel also requires that `overlapped` is unique for this I/O operation + /// and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn write_overlapped(&self, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Execute a connection operation for this socket. + /// + /// For more information about this method, see the + /// [`TcpBuilderExt::connect_overlapped`][link] documentation. + /// + /// [link]: trait.TcpBuilderExt.html#tymethod.connect_overlapped + unsafe fn connect_overlapped(&self, + addr: &SocketAddr, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Once a `connect_overlapped` has finished, this function needs to be + /// called to finish the connect operation. + /// + /// Currently this just calls `setsockopt` with `SO_UPDATE_CONNECT_CONTEXT` + /// to ensure that further functions like `getpeername` and `getsockname` + /// work correctly. + fn connect_complete(&self) -> io::Result<()>; + + /// Calls the `GetOverlappedResult` function to get the result of an + /// overlapped operation for this handle. + /// + /// This function takes the `OVERLAPPED` argument which must have been used + /// to initiate an overlapped I/O operation, and returns either the + /// successful number of bytes transferred during the operation or an error + /// if one occurred, along with the results of the `lpFlags` parameter of + /// the relevant operation, if applicable. + /// + /// # Unsafety + /// + /// This function is unsafe as `overlapped` must have previously been used + /// to execute an operation for this handle, and it must also be a valid + /// pointer to an `OVERLAPPED` instance. + /// + /// # Panics + /// + /// This function will panic + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)>; +} + +/// Additional methods for the `UdpSocket` type in the standard library. +pub trait UdpSocketExt { + /// Execute an overlapped receive I/O operation on this UDP socket. + /// + /// This function will issue an overlapped I/O read (via `WSARecvFrom`) on + /// this socket. The provided buffer will be filled in when the operation + /// completes, the source from where the data came from will be written to + /// `addr`, and the given `OVERLAPPED` instance is used to track the + /// overlapped operation. + /// + /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the + /// number of bytes that were read. If the operation returns an error + /// indicating that the I/O is currently pending, `Ok(None)` is returned. + /// Otherwise, the error associated with the operation is returned and no + /// overlapped operation is enqueued. + /// + /// The number of bytes read will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf`, + /// `addr`, and `overlapped` pointers are valid until the end of the I/O + /// operation. The kernel also requires that `overlapped` is unique for this + /// I/O operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn recv_from_overlapped(&self, + buf: &mut [u8], + addr: *mut SocketAddrBuf, + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Execute an overlapped receive I/O operation on this UDP socket. + /// + /// This function will issue an overlapped I/O read (via `WSARecv`) on + /// this socket. The provided buffer will be filled in when the operation + /// completes, the source from where the data came from will be written to + /// `addr`, and the given `OVERLAPPED` instance is used to track the + /// overlapped operation. + /// + /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the + /// number of bytes that were read. If the operation returns an error + /// indicating that the I/O is currently pending, `Ok(None)` is returned. + /// Otherwise, the error associated with the operation is returned and no + /// overlapped operation is enqueued. + /// + /// The number of bytes read will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf`, + /// and `overlapped` pointers are valid until the end of the I/O + /// operation. The kernel also requires that `overlapped` is unique for this + /// I/O operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn recv_overlapped(&self, + buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Execute an overlapped send I/O operation on this UDP socket. + /// + /// This function will issue an overlapped I/O write (via `WSASendTo`) on + /// this socket to the address specified by `addr`. The provided buffer will + /// be written when the operation completes and the given `OVERLAPPED` + /// instance is used to track the overlapped operation. + /// + /// If the operation succeeds, `Ok(Some(n0)` is returned where `n` byte + /// were written. If the operation returns an error indicating that the I/O + /// is currently pending, `Ok(None)` is returned. Otherwise, the error + /// associated with the operation is returned and no overlapped operation + /// is enqueued. + /// + /// The number of bytes written will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers are valid until the end of the I/O operation. The + /// kernel also requires that `overlapped` is unique for this I/O operation + /// and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn send_to_overlapped(&self, + buf: &[u8], + addr: &SocketAddr, + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Execute an overlapped send I/O operation on this UDP socket. + /// + /// This function will issue an overlapped I/O write (via `WSASend`) on + /// this socket to the address it was previously connected to. The provided + /// buffer will be written when the operation completes and the given `OVERLAPPED` + /// instance is used to track the overlapped operation. + /// + /// If the operation succeeds, `Ok(Some(n0)` is returned where `n` byte + /// were written. If the operation returns an error indicating that the I/O + /// is currently pending, `Ok(None)` is returned. Otherwise, the error + /// associated with the operation is returned and no overlapped operation + /// is enqueued. + /// + /// The number of bytes written will be returned as part of the completion + /// notification when the I/O finishes. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers are valid until the end of the I/O operation. The + /// kernel also requires that `overlapped` is unique for this I/O operation + /// and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that these two input + /// pointers are valid until the I/O operation is completed, typically via + /// completion ports and waiting to receive the completion notification on + /// the port. + unsafe fn send_overlapped(&self, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result>; + + /// Calls the `GetOverlappedResult` function to get the result of an + /// overlapped operation for this handle. + /// + /// This function takes the `OVERLAPPED` argument which must have been used + /// to initiate an overlapped I/O operation, and returns either the + /// successful number of bytes transferred during the operation or an error + /// if one occurred, along with the results of the `lpFlags` parameter of + /// the relevant operation, if applicable. + /// + /// # Unsafety + /// + /// This function is unsafe as `overlapped` must have previously been used + /// to execute an operation for this handle, and it must also be a valid + /// pointer to an `OVERLAPPED` instance. + /// + /// # Panics + /// + /// This function will panic + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)>; +} + +/// Additional methods for the `TcpBuilder` type in the `net2` library. +pub trait TcpBuilderExt { + /// Attempt to consume the internal socket in this builder by executing an + /// overlapped connect operation. + /// + /// This function will issue a connect operation to the address specified on + /// the underlying socket, flagging it as an overlapped operation which will + /// complete asynchronously. If successful this function will return the + /// corresponding TCP stream. + /// + /// The `buf` argument provided is an initial buffer of data that should be + /// sent after the connection is initiated. It's acceptable to + /// pass an empty slice here. + /// + /// This function will also return whether the connect immediately + /// succeeded or not. If `None` is returned then the I/O operation is still + /// pending and will complete at a later date, and if `Some(bytes)` is + /// returned then that many bytes were transferred. + /// + /// Note that to succeed this requires that the underlying socket has + /// previously been bound via a call to `bind` to a local address. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the + /// `overlapped` and `buf` pointers to be valid until the end of the I/O + /// operation. The kernel also requires that `overlapped` is unique for + /// this I/O operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that this pointer is + /// valid until the I/O operation is completed, typically via completion + /// ports and waiting to receive the completion notification on the port. + unsafe fn connect_overlapped(&self, + addr: &SocketAddr, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result<(TcpStream, Option)>; + + /// Calls the `GetOverlappedResult` function to get the result of an + /// overlapped operation for this handle. + /// + /// This function takes the `OVERLAPPED` argument which must have been used + /// to initiate an overlapped I/O operation, and returns either the + /// successful number of bytes transferred during the operation or an error + /// if one occurred, along with the results of the `lpFlags` parameter of + /// the relevant operation, if applicable. + /// + /// # Unsafety + /// + /// This function is unsafe as `overlapped` must have previously been used + /// to execute an operation for this handle, and it must also be a valid + /// pointer to an `OVERLAPPED` instance. + /// + /// # Panics + /// + /// This function will panic + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)>; +} + +/// Additional methods for the `TcpListener` type in the standard library. +pub trait TcpListenerExt { + /// Perform an accept operation on this listener, accepting a connection in + /// an overlapped fashion. + /// + /// This function will issue an I/O request to accept an incoming connection + /// with the specified overlapped instance. The `socket` provided must be a + /// configured but not bound or connected socket, and if successful this + /// will consume the internal socket of the builder to return a TCP stream. + /// + /// The `addrs` buffer provided will be filled in with the local and remote + /// addresses of the connection upon completion. + /// + /// If the accept succeeds immediately, `Ok(stream, true)` is returned. If + /// the connect indicates that the I/O is currently pending, `Ok(stream, + /// false)` is returned. Otherwise, the error associated with the operation + /// is returned and no overlapped operation is enqueued. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the + /// `addrs` and `overlapped` pointers are valid until the end of the I/O + /// operation. The kernel also requires that `overlapped` is unique for this + /// I/O operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that the pointers are + /// valid until the I/O operation is completed, typically via completion + /// ports and waiting to receive the completion notification on the port. + unsafe fn accept_overlapped(&self, + socket: &TcpBuilder, + addrs: &mut AcceptAddrsBuf, + overlapped: *mut OVERLAPPED) + -> io::Result<(TcpStream, bool)>; + + /// Once an `accept_overlapped` has finished, this function needs to be + /// called to finish the accept operation. + /// + /// Currently this just calls `setsockopt` with `SO_UPDATE_ACCEPT_CONTEXT` + /// to ensure that further functions like `getpeername` and `getsockname` + /// work correctly. + fn accept_complete(&self, socket: &TcpStream) -> io::Result<()>; + + /// Calls the `GetOverlappedResult` function to get the result of an + /// overlapped operation for this handle. + /// + /// This function takes the `OVERLAPPED` argument which must have been used + /// to initiate an overlapped I/O operation, and returns either the + /// successful number of bytes transferred during the operation or an error + /// if one occurred, along with the results of the `lpFlags` parameter of + /// the relevant operation, if applicable. + /// + /// # Unsafety + /// + /// This function is unsafe as `overlapped` must have previously been used + /// to execute an operation for this handle, and it must also be a valid + /// pointer to an `OVERLAPPED` instance. + /// + /// # Panics + /// + /// This function will panic + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)>; +} + +#[doc(hidden)] +trait NetInt { + fn from_be(i: Self) -> Self; + fn to_be(&self) -> Self; +} +macro_rules! doit { + ($($t:ident)*) => ($(impl NetInt for $t { + fn from_be(i: Self) -> Self { <$t>::from_be(i) } + fn to_be(&self) -> Self { <$t>::to_be(*self) } + })*) +} +doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + +// fn hton(i: I) -> I { i.to_be() } +fn ntoh(i: I) -> I { I::from_be(i) } + +fn last_err() -> io::Result> { + let err = unsafe { WSAGetLastError() }; + if err == WSA_IO_PENDING as i32 { + Ok(None) + } else { + Err(io::Error::from_raw_os_error(err)) + } +} + +fn cvt(i: c_int, size: DWORD) -> io::Result> { + if i == SOCKET_ERROR { + last_err() + } else { + Ok(Some(size as usize)) + } +} + +fn socket_addr_to_ptrs(addr: &SocketAddr) -> (*const SOCKADDR, c_int) { + match *addr { + SocketAddr::V4(ref a) => { + (a as *const _ as *const _, mem::size_of::() as c_int) + } + SocketAddr::V6(ref a) => { + (a as *const _ as *const _, mem::size_of::() as c_int) + } + } +} + +unsafe fn ptrs_to_socket_addr(ptr: *const SOCKADDR, + len: c_int) -> Option { + if (len as usize) < mem::size_of::() { + return None + } + match (*ptr).sa_family as i32 { + AF_INET if len as usize >= mem::size_of::() => { + let b = &*(ptr as *const SOCKADDR_IN); + let ip = ntoh(b.sin_addr.S_un); + let ip = Ipv4Addr::new((ip >> 24) as u8, + (ip >> 16) as u8, + (ip >> 8) as u8, + (ip >> 0) as u8); + Some(SocketAddr::V4(SocketAddrV4::new(ip, ntoh(b.sin_port)))) + } + AF_INET6 if len as usize >= mem::size_of::() => { + let b = &*(ptr as *const sockaddr_in6); + let arr = &b.sin6_addr.s6_addr; + let ip = Ipv6Addr::new( + ((arr[0] as u16) << 8) | (arr[1] as u16), + ((arr[2] as u16) << 8) | (arr[3] as u16), + ((arr[4] as u16) << 8) | (arr[5] as u16), + ((arr[6] as u16) << 8) | (arr[7] as u16), + ((arr[8] as u16) << 8) | (arr[9] as u16), + ((arr[10] as u16) << 8) | (arr[11] as u16), + ((arr[12] as u16) << 8) | (arr[13] as u16), + ((arr[14] as u16) << 8) | (arr[15] as u16)); + let addr = SocketAddrV6::new(ip, ntoh(b.sin6_port), + ntoh(b.sin6_flowinfo), + ntoh(b.sin6_scope_id)); + Some(SocketAddr::V6(addr)) + } + _ => None + } +} + +unsafe fn slice2buf(slice: &[u8]) -> WSABUF { + WSABUF { + len: cmp::min(slice.len(), ::max_value() as usize) as u_long, + buf: slice.as_ptr() as *mut _, + } +} + +unsafe fn result(socket: SOCKET, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)> { + let mut transferred = 0; + let mut flags = 0; + let r = WSAGetOverlappedResult(socket, + overlapped, + &mut transferred, + FALSE, + &mut flags); + if r == 0 { + Err(io::Error::last_os_error()) + } else { + Ok((transferred as usize, flags)) + } +} + +impl TcpStreamExt for TcpStream { + unsafe fn read_overlapped(&self, + buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let mut buf = slice2buf(buf); + let mut flags = 0; + let mut bytes_read: DWORD = 0; + let r = WSARecv(self.as_raw_socket(), &mut buf, 1, + &mut bytes_read, &mut flags, overlapped, None); + cvt(r, bytes_read) + } + + unsafe fn write_overlapped(&self, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let mut buf = slice2buf(buf); + let mut bytes_written = 0; + + // Note here that we capture the number of bytes written. The + // documentation on MSDN, however, states: + // + // > Use NULL for this parameter if the lpOverlapped parameter is not + // > NULL to avoid potentially erroneous results. This parameter can be + // > NULL only if the lpOverlapped parameter is not NULL. + // + // If we're not passing a null overlapped pointer here, then why are we + // then capturing the number of bytes! Well so it turns out that this is + // clearly faster to learn the bytes here rather than later calling + // `WSAGetOverlappedResult`, and in practice almost all implementations + // use this anyway [1]. + // + // As a result we use this to and report back the result. + // + // [1]: https://github.com/carllerche/mio/pull/520#issuecomment-273983823 + let r = WSASend(self.as_raw_socket(), &mut buf, 1, + &mut bytes_written, 0, overlapped, None); + cvt(r, bytes_written) + } + + unsafe fn connect_overlapped(&self, + addr: &SocketAddr, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + connect_overlapped(self.as_raw_socket(), addr, buf, overlapped) + } + + fn connect_complete(&self) -> io::Result<()> { + const SO_UPDATE_CONNECT_CONTEXT: c_int = 0x7010; + let result = unsafe { + setsockopt(self.as_raw_socket(), + SOL_SOCKET, + SO_UPDATE_CONNECT_CONTEXT, + 0 as *const _, + 0) + }; + if result == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)> { + result(self.as_raw_socket(), overlapped) + } +} + +unsafe fn connect_overlapped(socket: SOCKET, + addr: &SocketAddr, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + static CONNECTEX: WsaExtension = WsaExtension { + guid: GUID { + Data1: 0x25a207b9, + Data2: 0xddf3, + Data3: 0x4660, + Data4: [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e], + }, + val: ATOMIC_USIZE_INIT, + }; + type ConnectEx = unsafe extern "system" fn(SOCKET, *const SOCKADDR, + c_int, PVOID, DWORD, LPDWORD, + LPOVERLAPPED) -> BOOL; + + let ptr = try!(CONNECTEX.get(socket)); + assert!(ptr != 0); + let connect_ex = mem::transmute::<_, ConnectEx>(ptr); + + let (addr_buf, addr_len) = socket_addr_to_ptrs(addr); + let mut bytes_sent: DWORD = 0; + let r = connect_ex(socket, addr_buf, addr_len, + buf.as_ptr() as *mut _, + buf.len() as u32, + &mut bytes_sent, overlapped); + if r == TRUE { + Ok(Some(bytes_sent as usize)) + } else { + last_err() + } +} + +impl UdpSocketExt for UdpSocket { + unsafe fn recv_from_overlapped(&self, + buf: &mut [u8], + addr: *mut SocketAddrBuf, + overlapped: *mut OVERLAPPED) + -> io::Result> { + let mut buf = slice2buf(buf); + let mut flags = 0; + let mut received_bytes: DWORD = 0; + let r = WSARecvFrom(self.as_raw_socket(), &mut buf, 1, + &mut received_bytes, &mut flags, + &mut (*addr).buf as *mut _ as *mut _, + &mut (*addr).len, + overlapped, None); + cvt(r, received_bytes) + } + + unsafe fn recv_overlapped(&self, + buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let mut buf = slice2buf(buf); + let mut flags = 0; + let mut received_bytes: DWORD = 0; + let r = WSARecv(self.as_raw_socket(), &mut buf, 1, + &mut received_bytes, &mut flags, + overlapped, None); + cvt(r, received_bytes) + } + + unsafe fn send_to_overlapped(&self, + buf: &[u8], + addr: &SocketAddr, + overlapped: *mut OVERLAPPED) + -> io::Result> { + let (addr_buf, addr_len) = socket_addr_to_ptrs(addr); + let mut buf = slice2buf(buf); + let mut sent_bytes = 0; + let r = WSASendTo(self.as_raw_socket(), &mut buf, 1, + &mut sent_bytes, 0, + addr_buf as *const _, addr_len, + overlapped, None); + cvt(r, sent_bytes) + } + + unsafe fn send_overlapped(&self, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + let mut buf = slice2buf(buf); + let mut sent_bytes = 0; + let r = WSASend(self.as_raw_socket(), &mut buf, 1, + &mut sent_bytes, 0, + overlapped, None); + cvt(r, sent_bytes) + } + + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)> { + result(self.as_raw_socket(), overlapped) + } +} + +impl TcpBuilderExt for TcpBuilder { + unsafe fn connect_overlapped(&self, + addr: &SocketAddr, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result<(TcpStream, Option)> { + connect_overlapped(self.as_raw_socket(), addr, buf, overlapped).map(|s| { + (self.to_tcp_stream().unwrap(), s) + }) + } + + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)> { + result(self.as_raw_socket(), overlapped) + } +} + +impl TcpListenerExt for TcpListener { + unsafe fn accept_overlapped(&self, + socket: &TcpBuilder, + addrs: &mut AcceptAddrsBuf, + overlapped: *mut OVERLAPPED) + -> io::Result<(TcpStream, bool)> { + static ACCEPTEX: WsaExtension = WsaExtension { + guid: GUID { + Data1: 0xb5367df1, + Data2: 0xcbac, + Data3: 0x11cf, + Data4: [0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92], + }, + val: ATOMIC_USIZE_INIT, + }; + type AcceptEx = unsafe extern "system" fn(SOCKET, SOCKET, PVOID, + DWORD, DWORD, DWORD, LPDWORD, + LPOVERLAPPED) -> BOOL; + + let ptr = try!(ACCEPTEX.get(self.as_raw_socket())); + assert!(ptr != 0); + let accept_ex = mem::transmute::<_, AcceptEx>(ptr); + + let mut bytes = 0; + let (a, b, c, d) = (*addrs).args(); + let r = accept_ex(self.as_raw_socket(), socket.as_raw_socket(), + a, b, c, d, &mut bytes, overlapped); + let succeeded = if r == TRUE { + true + } else { + try!(last_err()); + false + }; + // NB: this unwrap() should be guaranteed to succeed, and this is an + // assert that it does indeed succeed. + Ok((socket.to_tcp_stream().unwrap(), succeeded)) + } + + fn accept_complete(&self, socket: &TcpStream) -> io::Result<()> { + const SO_UPDATE_ACCEPT_CONTEXT: c_int = 0x700B; + let me = self.as_raw_socket(); + let result = unsafe { + setsockopt(socket.as_raw_socket(), + SOL_SOCKET, + SO_UPDATE_ACCEPT_CONTEXT, + &me as *const _ as *const _, + mem::size_of_val(&me) as c_int) + }; + if result == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result<(usize, u32)> { + result(self.as_raw_socket(), overlapped) + } +} + +impl SocketAddrBuf { + /// Creates a new blank socket address buffer. + /// + /// This should be used before a call to `recv_from_overlapped` overlapped + /// to create an instance to pass down. + pub fn new() -> SocketAddrBuf { + SocketAddrBuf { + buf: unsafe { mem::zeroed() }, + len: mem::size_of::() as c_int, + } + } + + /// Parses this buffer to return a standard socket address. + /// + /// This function should be called after the buffer has been filled in with + /// a call to `recv_from_overlapped` being completed. It will interpret the + /// address filled in and return the standard socket address type. + /// + /// If an error is encountered then `None` is returned. + pub fn to_socket_addr(&self) -> Option { + unsafe { + ptrs_to_socket_addr(&self.buf as *const _ as *const _, self.len) + } + } +} + +static GETACCEPTEXSOCKADDRS: WsaExtension = WsaExtension { + guid: GUID { + Data1: 0xb5367df2, + Data2: 0xcbac, + Data3: 0x11cf, + Data4: [0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92], + }, + val: ATOMIC_USIZE_INIT, +}; +type GetAcceptExSockaddrs = unsafe extern "system" fn(PVOID, DWORD, DWORD, DWORD, + *mut LPSOCKADDR, LPINT, + *mut LPSOCKADDR, LPINT); + +impl AcceptAddrsBuf { + /// Creates a new blank buffer ready to be passed to a call to + /// `accept_overlapped`. + pub fn new() -> AcceptAddrsBuf { + unsafe { mem::zeroed() } + } + + /// Parses the data contained in this address buffer, returning the parsed + /// result if successful. + /// + /// This function can be called after a call to `accept_overlapped` has + /// succeeded to parse out the data that was written in. + pub fn parse(&self, socket: &TcpListener) -> io::Result { + let mut ret = AcceptAddrs { + local: 0 as *mut _, local_len: 0, + remote: 0 as *mut _, remote_len: 0, + _data: self, + }; + let ptr = try!(GETACCEPTEXSOCKADDRS.get(socket.as_raw_socket())); + assert!(ptr != 0); + unsafe { + let get_sockaddrs = mem::transmute::<_, GetAcceptExSockaddrs>(ptr); + let (a, b, c, d) = self.args(); + get_sockaddrs(a, b, c, d, + &mut ret.local, &mut ret.local_len, + &mut ret.remote, &mut ret.remote_len); + Ok(ret) + } + } + + fn args(&self) -> (PVOID, DWORD, DWORD, DWORD) { + let remote_offset = unsafe { + &(*(0 as *const AcceptAddrsBuf)).remote as *const _ as usize + }; + (self as *const _ as *mut _, 0, remote_offset as DWORD, + (mem::size_of_val(self) - remote_offset) as DWORD) + } +} + +impl<'a> AcceptAddrs<'a> { + /// Returns the local socket address contained in this buffer. + pub fn local(&self) -> Option { + unsafe { ptrs_to_socket_addr(self.local, self.local_len) } + } + + /// Returns the remote socket address contained in this buffer. + pub fn remote(&self) -> Option { + unsafe { ptrs_to_socket_addr(self.remote, self.remote_len) } + } +} + +impl WsaExtension { + fn get(&self, socket: SOCKET) -> io::Result { + let prev = self.val.load(Ordering::SeqCst); + if prev != 0 && !cfg!(debug_assertions) { + return Ok(prev) + } + let mut ret = 0 as usize; + let mut bytes = 0; + let r = unsafe { + WSAIoctl(socket, SIO_GET_EXTENSION_FUNCTION_POINTER, + &self.guid as *const _ as *mut _, + mem::size_of_val(&self.guid) as DWORD, + &mut ret as *mut _ as *mut _, + mem::size_of_val(&ret) as DWORD, + &mut bytes, + 0 as *mut _, None) + }; + cvt(r, 0).map(|_| { + debug_assert_eq!(bytes as usize, mem::size_of_val(&ret)); + debug_assert!(prev == 0 || prev == ret); + self.val.store(ret, Ordering::SeqCst); + ret + }) + + } +} + +#[cfg(test)] +mod tests { + use std::net::{TcpListener, UdpSocket, TcpStream, SocketAddr}; + use std::thread; + use std::io::prelude::*; + + use Overlapped; + use iocp::CompletionPort; + use net::{TcpStreamExt, UdpSocketExt, SocketAddrBuf}; + use net::{TcpBuilderExt, TcpListenerExt, AcceptAddrsBuf}; + use net2::TcpBuilder; + + fn each_ip(f: &mut FnMut(SocketAddr)) { + f(t!("127.0.0.1:0".parse())); + f(t!("[::1]:0".parse())); + } + + #[test] + fn tcp_read() { + each_ip(&mut |addr| { + let l = t!(TcpListener::bind(addr)); + let addr = t!(l.local_addr()); + let t = thread::spawn(move || { + let mut a = t!(l.accept()).0; + t!(a.write_all(&[1, 2, 3])); + }); + + let cp = t!(CompletionPort::new(1)); + let s = t!(TcpStream::connect(addr)); + t!(cp.add_socket(1, &s)); + + let mut b = [0; 10]; + let a = Overlapped::zero(); + unsafe { + t!(s.read_overlapped(&mut b, a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + assert_eq!(&b[0..3], &[1, 2, 3]); + + t!(t.join()); + }) + } + + #[test] + fn tcp_write() { + each_ip(&mut |addr| { + let l = t!(TcpListener::bind(addr)); + let addr = t!(l.local_addr()); + let t = thread::spawn(move || { + let mut a = t!(l.accept()).0; + let mut b = [0; 10]; + let n = t!(a.read(&mut b)); + assert_eq!(n, 3); + assert_eq!(&b[0..3], &[1, 2, 3]); + }); + + let cp = t!(CompletionPort::new(1)); + let s = t!(TcpStream::connect(addr)); + t!(cp.add_socket(1, &s)); + + let b = [1, 2, 3]; + let a = Overlapped::zero(); + unsafe { + t!(s.write_overlapped(&b, a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + + t!(t.join()); + }) + } + + #[test] + fn tcp_connect() { + each_ip(&mut |addr_template| { + let l = t!(TcpListener::bind(addr_template)); + let addr = t!(l.local_addr()); + let t = thread::spawn(move || { + t!(l.accept()); + }); + + let cp = t!(CompletionPort::new(1)); + let builder = match addr { + SocketAddr::V4(..) => t!(TcpBuilder::new_v4()), + SocketAddr::V6(..) => t!(TcpBuilder::new_v6()), + }; + t!(cp.add_socket(1, &builder)); + + let a = Overlapped::zero(); + t!(builder.bind(addr_template)); + let (s, _) = unsafe { + t!(builder.connect_overlapped(&addr, &[], a.raw())) + }; + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 0); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + t!(s.connect_complete()); + + t!(t.join()); + }) + } + + #[test] + fn udp_recv_from() { + each_ip(&mut |addr| { + let a = t!(UdpSocket::bind(addr)); + let b = t!(UdpSocket::bind(addr)); + let a_addr = t!(a.local_addr()); + let b_addr = t!(b.local_addr()); + let t = thread::spawn(move || { + t!(a.send_to(&[1, 2, 3], b_addr)); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_socket(1, &b)); + + let mut buf = [0; 10]; + let a = Overlapped::zero(); + let mut addr = SocketAddrBuf::new(); + unsafe { + t!(b.recv_from_overlapped(&mut buf, &mut addr, a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + assert_eq!(&buf[..3], &[1, 2, 3]); + assert_eq!(addr.to_socket_addr(), Some(a_addr)); + + t!(t.join()); + }) + } + + #[test] + fn udp_recv() { + each_ip(&mut |addr| { + let a = t!(UdpSocket::bind(addr)); + let b = t!(UdpSocket::bind(addr)); + let a_addr = t!(a.local_addr()); + let b_addr = t!(b.local_addr()); + assert!(b.connect(a_addr).is_ok()); + assert!(a.connect(b_addr).is_ok()); + let t = thread::spawn(move || { + t!(a.send_to(&[1, 2, 3], b_addr)); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_socket(1, &b)); + + let mut buf = [0; 10]; + let a = Overlapped::zero(); + unsafe { + t!(b.recv_overlapped(&mut buf, a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + assert_eq!(&buf[..3], &[1, 2, 3]); + + t!(t.join()); + }) + } + + #[test] + fn udp_send_to() { + each_ip(&mut |addr| { + let a = t!(UdpSocket::bind(addr)); + let b = t!(UdpSocket::bind(addr)); + let a_addr = t!(a.local_addr()); + let b_addr = t!(b.local_addr()); + let t = thread::spawn(move || { + let mut b = [0; 100]; + let (n, addr) = t!(a.recv_from(&mut b)); + assert_eq!(n, 3); + assert_eq!(addr, b_addr); + assert_eq!(&b[..3], &[1, 2, 3]); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_socket(1, &b)); + + let a = Overlapped::zero(); + unsafe { + t!(b.send_to_overlapped(&[1, 2, 3], &a_addr, a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + + t!(t.join()); + }) + } + + #[test] + fn udp_send() { + each_ip(&mut |addr| { + let a = t!(UdpSocket::bind(addr)); + let b = t!(UdpSocket::bind(addr)); + let a_addr = t!(a.local_addr()); + let b_addr = t!(b.local_addr()); + assert!(b.connect(a_addr).is_ok()); + assert!(a.connect(b_addr).is_ok()); + let t = thread::spawn(move || { + let mut b = [0; 100]; + let (n, addr) = t!(a.recv_from(&mut b)); + assert_eq!(n, 3); + assert_eq!(addr, b_addr); + assert_eq!(&b[..3], &[1, 2, 3]); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_socket(1, &b)); + + let a = Overlapped::zero(); + unsafe { + t!(b.send_overlapped(&[1, 2, 3], a.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + + t!(t.join()); + }) + } + + #[test] + fn tcp_accept() { + each_ip(&mut |addr_template| { + let l = t!(TcpListener::bind(addr_template)); + let addr = t!(l.local_addr()); + let t = thread::spawn(move || { + let socket = t!(TcpStream::connect(addr)); + (socket.local_addr().unwrap(), socket.peer_addr().unwrap()) + }); + + let cp = t!(CompletionPort::new(1)); + let builder = match addr { + SocketAddr::V4(..) => t!(TcpBuilder::new_v4()), + SocketAddr::V6(..) => t!(TcpBuilder::new_v6()), + }; + t!(cp.add_socket(1, &l)); + + let a = Overlapped::zero(); + let mut addrs = AcceptAddrsBuf::new(); + let (s, _) = unsafe { + t!(l.accept_overlapped(&builder, &mut addrs, a.raw())) + }; + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 0); + assert_eq!(status.token(), 1); + assert_eq!(status.overlapped(), a.raw()); + t!(l.accept_complete(&s)); + + let (remote, local) = t!(t.join()); + let addrs = addrs.parse(&l).unwrap(); + assert_eq!(addrs.local(), Some(local)); + assert_eq!(addrs.remote(), Some(remote)); + }) + } +} diff --git a/third_party/cargo/vendor/miow-0.2.1/src/overlapped.rs b/third_party/cargo/vendor/miow-0.2.1/src/overlapped.rs new file mode 100644 index 0000000..eade553 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/overlapped.rs @@ -0,0 +1,66 @@ +use std::mem; + +use winapi::*; + +/// A wrapper around `OVERLAPPED` to provide "rustic" accessors and +/// initializers. +#[derive(Debug)] +pub struct Overlapped(OVERLAPPED); + +unsafe impl Send for Overlapped {} +unsafe impl Sync for Overlapped {} + +impl Overlapped { + /// Creates a new zeroed out instance of an overlapped I/O tracking state. + /// + /// This is suitable for passing to methods which will then later get + /// notified via an I/O Completion Port. + pub fn zero() -> Overlapped { + Overlapped(unsafe { mem::zeroed() }) + } + + /// Creates a new `Overlapped` function pointer from the underlying + /// `OVERLAPPED`, wrapping in the "rusty" wrapper for working with + /// accessors. + /// + /// # Unsafety + /// + /// This function doesn't validate `ptr` nor the lifetime of the returned + /// pointer at all, it's recommended to use this method with extreme + /// caution. + pub unsafe fn from_raw<'a>(ptr: *mut OVERLAPPED) -> &'a mut Overlapped { + &mut *(ptr as *mut Overlapped) + } + + /// Gain access to the raw underlying data + pub fn raw(&self) -> *mut OVERLAPPED { + &self.0 as *const _ as *mut _ + } + + /// Sets the offset inside this overlapped structure. + /// + /// Note that for I/O operations in general this only has meaning for I/O + /// handles that are on a seeking device that supports the concept of an + /// offset. + pub fn set_offset(&mut self, offset: u64) { + self.0.Offset = offset as u32; + self.0.OffsetHigh = (offset >> 32) as u32; + } + + /// Reads the offset inside this overlapped structure. + pub fn offset(&self) -> u64 { + (self.0.Offset as u64) | ((self.0.OffsetHigh as u64) << 32) + } + + /// Sets the `hEvent` field of this structure. + /// + /// The event specified can be null. + pub fn set_event(&mut self, event: HANDLE) { + self.0.hEvent = event; + } + + /// Reads the `hEvent` field of this structure, may return null. + pub fn event(&self) -> HANDLE { + self.0.hEvent + } +} diff --git a/third_party/cargo/vendor/miow-0.2.1/src/pipe.rs b/third_party/cargo/vendor/miow-0.2.1/src/pipe.rs new file mode 100644 index 0000000..5d55c54 --- /dev/null +++ b/third_party/cargo/vendor/miow-0.2.1/src/pipe.rs @@ -0,0 +1,611 @@ +//! Named pipes + +use std::ffi::OsStr; +use std::fs::{OpenOptions, File}; +use std::io::prelude::*; +use std::io; +use std::os::windows::ffi::*; +use std::os::windows::io::*; +use std::time::Duration; + +use winapi::*; +use kernel32::*; +use handle::Handle; + +/// Readable half of an anonymous pipe. +#[derive(Debug)] +pub struct AnonRead(Handle); + +/// Writable half of an anonymous pipe. +#[derive(Debug)] +pub struct AnonWrite(Handle); + +/// A named pipe that can accept connections. +#[derive(Debug)] +pub struct NamedPipe(Handle); + +/// A builder structure for creating a new named pipe. +#[derive(Debug)] +pub struct NamedPipeBuilder { + name: Vec, + dwOpenMode: DWORD, + dwPipeMode: DWORD, + nMaxInstances: DWORD, + nOutBufferSize: DWORD, + nInBufferSize: DWORD, + nDefaultTimeOut: DWORD, +} + +/// Creates a new anonymous in-memory pipe, returning the read/write ends of the +/// pipe. +/// +/// The buffer size for this pipe may also be specified, but the system will +/// normally use this as a suggestion and it's not guaranteed that the buffer +/// will be precisely this size. +pub fn anonymous(buffer_size: u32) -> io::Result<(AnonRead, AnonWrite)> { + let mut read = 0 as HANDLE; + let mut write = 0 as HANDLE; + try!(::cvt(unsafe { + CreatePipe(&mut read, &mut write, 0 as *mut _, buffer_size) + })); + Ok((AnonRead(Handle::new(read)), AnonWrite(Handle::new(write)))) +} + +impl Read for AnonRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } +} +impl<'a> Read for &'a AnonRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } +} + +impl AsRawHandle for AnonRead { + fn as_raw_handle(&self) -> HANDLE { self.0.raw() } +} +impl FromRawHandle for AnonRead { + unsafe fn from_raw_handle(handle: HANDLE) -> AnonRead { + AnonRead(Handle::new(handle)) + } +} +impl IntoRawHandle for AnonRead { + fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } +} + +impl Write for AnonWrite { + fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn flush(&mut self) -> io::Result<()> { Ok(()) } +} +impl<'a> Write for &'a AnonWrite { + fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn flush(&mut self) -> io::Result<()> { Ok(()) } +} + +impl AsRawHandle for AnonWrite { + fn as_raw_handle(&self) -> HANDLE { self.0.raw() } +} +impl FromRawHandle for AnonWrite { + unsafe fn from_raw_handle(handle: HANDLE) -> AnonWrite { + AnonWrite(Handle::new(handle)) + } +} +impl IntoRawHandle for AnonWrite { + fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } +} + +/// A convenience function to connect to a named pipe. +/// +/// This function will block the calling process until it can connect to the +/// pipe server specified by `addr`. This will use `NamedPipe::wait` internally +/// to block until it can connect. +pub fn connect>(addr: A) -> io::Result { + _connect(addr.as_ref()) +} + +fn _connect(addr: &OsStr) -> io::Result { + let mut r = OpenOptions::new(); + let mut w = OpenOptions::new(); + let mut rw = OpenOptions::new(); + r.read(true); + w.write(true); + rw.read(true).write(true); + loop { + let res = rw.open(addr).or_else(|_| r.open(addr)) + .or_else(|_| w.open(addr)); + match res { + Ok(f) => return Ok(f), + Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY as i32) + => {} + Err(e) => return Err(e), + } + + try!(NamedPipe::wait(addr, Some(Duration::new(20, 0)))); + } +} + +impl NamedPipe { + /// Creates a new initial named pipe. + /// + /// This function is equivalent to: + /// + /// ``` + /// use miow::pipe::NamedPipeBuilder; + /// + /// # let addr = "foo"; + /// NamedPipeBuilder::new(addr) + /// .first(true) + /// .inbound(true) + /// .outbound(true) + /// .out_buffer_size(65536) + /// .in_buffer_size(65536) + /// .create(); + /// ``` + pub fn new>(addr: A) -> io::Result { + NamedPipeBuilder::new(addr).create() + } + + /// Waits until either a time-out interval elapses or an instance of the + /// specified named pipe is available for connection. + /// + /// If this function succeeds the process can create a `File` to connect to + /// the named pipe. + pub fn wait>(addr: A, timeout: Option) + -> io::Result<()> { + NamedPipe::_wait(addr.as_ref(), timeout) + } + + fn _wait(addr: &OsStr, timeout: Option) -> io::Result<()> { + let addr = addr.encode_wide().chain(Some(0)).collect::>(); + let timeout = ::dur2ms(timeout); + ::cvt(unsafe { + WaitNamedPipeW(addr.as_ptr(), timeout) + }).map(|_| ()) + } + + /// Connects this named pipe to a client, blocking until one becomes + /// available. + /// + /// This function will call the `ConnectNamedPipe` function to await for a + /// client to connect. This can be called immediately after the pipe is + /// created, or after it has been disconnected from a previous client. + pub fn connect(&self) -> io::Result<()> { + match ::cvt(unsafe { ConnectNamedPipe(self.0.raw(), 0 as *mut _) }) { + Ok(_) => Ok(()), + Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_CONNECTED as i32) + => Ok(()), + Err(e) => Err(e), + } + } + + /// Issue a connection request with the specified overlapped operation. + /// + /// This function will issue a request to connect a client to this server, + /// returning immediately after starting the overlapped operation. + /// + /// If this function immediately succeeds then `Ok(true)` is returned. If + /// the overlapped operation is enqueued and pending, then `Ok(false)` is + /// returned. Otherwise an error is returned indicating what went wrong. + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the + /// `overlapped` pointer is valid until the end of the I/O operation. The + /// kernel also requires that `overlapped` is unique for this I/O operation + /// and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that this pointer is + /// valid until the I/O operation is completed, typically via completion + /// ports and waiting to receive the completion notification on the port. + pub unsafe fn connect_overlapped(&self, overlapped: *mut OVERLAPPED) + -> io::Result { + match ::cvt(ConnectNamedPipe(self.0.raw(), overlapped)) { + Ok(_) => Ok(true), + Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_CONNECTED as i32) + => Ok(true), + Err(ref e) if e.raw_os_error() == Some(ERROR_IO_PENDING as i32) + => Ok(false), + Err(e) => Err(e), + } + } + + /// Disconnects this named pipe from any connected client. + pub fn disconnect(&self) -> io::Result<()> { + ::cvt(unsafe { + DisconnectNamedPipe(self.0.raw()) + }).map(|_| ()) + } + + /// Issues an overlapped read operation to occur on this pipe. + /// + /// This function will issue an asynchronous read to occur in an overlapped + /// fashion, returning immediately. The `buf` provided will be filled in + /// with data and the request is tracked by the `overlapped` function + /// provided. + /// + /// If the operation succeeds immediately, `Ok(Some(n))` is returned where + /// `n` is the number of bytes read. If an asynchronous operation is + /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred + /// it is returned. + /// + /// When this operation completes (or if it completes immediately), another + /// mechanism must be used to learn how many bytes were transferred (such as + /// looking at the filed in the IOCP status message). + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers to be valid until the end of the I/O operation. + /// The kernel also requires that `overlapped` is unique for this I/O + /// operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that the pointers are + /// valid until the I/O operation is completed, typically via completion + /// ports and waiting to receive the completion notification on the port. + pub unsafe fn read_overlapped(&self, + buf: &mut [u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + self.0.read_overlapped(buf, overlapped) + } + + /// Issues an overlapped write operation to occur on this pipe. + /// + /// This function will issue an asynchronous write to occur in an overlapped + /// fashion, returning immediately. The `buf` provided will be filled in + /// with data and the request is tracked by the `overlapped` function + /// provided. + /// + /// If the operation succeeds immediately, `Ok(Some(n))` is returned where + /// `n` is the number of bytes written. If an asynchronous operation is + /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred + /// it is returned. + /// + /// When this operation completes (or if it completes immediately), another + /// mechanism must be used to learn how many bytes were transferred (such as + /// looking at the filed in the IOCP status message). + /// + /// # Unsafety + /// + /// This function is unsafe because the kernel requires that the `buf` and + /// `overlapped` pointers to be valid until the end of the I/O operation. + /// The kernel also requires that `overlapped` is unique for this I/O + /// operation and is not in use for any other I/O. + /// + /// To safely use this function callers must ensure that the pointers are + /// valid until the I/O operation is completed, typically via completion + /// ports and waiting to receive the completion notification on the port. + pub unsafe fn write_overlapped(&self, + buf: &[u8], + overlapped: *mut OVERLAPPED) + -> io::Result> { + self.0.write_overlapped(buf, overlapped) + } + + /// Calls the `GetOverlappedResult` function to get the result of an + /// overlapped operation for this handle. + /// + /// This function takes the `OVERLAPPED` argument which must have been used + /// to initiate an overlapped I/O operation, and returns either the + /// successful number of bytes transferred during the operation or an error + /// if one occurred. + /// + /// # Unsafety + /// + /// This function is unsafe as `overlapped` must have previously been used + /// to execute an operation for this handle, and it must also be a valid + /// pointer to an `Overlapped` instance. + /// + /// # Panics + /// + /// This function will panic + pub unsafe fn result(&self, overlapped: *mut OVERLAPPED) + -> io::Result { + let mut transferred = 0; + let r = GetOverlappedResult(self.0.raw(), + overlapped, + &mut transferred, + FALSE); + if r == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(transferred as usize) + } + } +} + +impl Read for NamedPipe { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } +} +impl<'a> Read for &'a NamedPipe { + fn read(&mut self, buf: &mut [u8]) -> io::Result { self.0.read(buf) } +} + +impl Write for NamedPipe { + fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn flush(&mut self) -> io::Result<()> { + <&NamedPipe as Write>::flush(&mut &*self) + } +} +impl<'a> Write for &'a NamedPipe { + fn write(&mut self, buf: &[u8]) -> io::Result { self.0.write(buf) } + fn flush(&mut self) -> io::Result<()> { + ::cvt(unsafe { FlushFileBuffers(self.0.raw()) }).map(|_| ()) + } +} + +impl AsRawHandle for NamedPipe { + fn as_raw_handle(&self) -> HANDLE { self.0.raw() } +} +impl FromRawHandle for NamedPipe { + unsafe fn from_raw_handle(handle: HANDLE) -> NamedPipe { + NamedPipe(Handle::new(handle)) + } +} +impl IntoRawHandle for NamedPipe { + fn into_raw_handle(self) -> HANDLE { self.0.into_raw() } +} + +fn flag(slot: &mut DWORD, on: bool, val: DWORD) { + if on { + *slot |= val; + } else { + *slot &= !val; + } +} + +impl NamedPipeBuilder { + /// Creates a new named pipe builder with the default settings. + pub fn new>(addr: A) -> NamedPipeBuilder { + NamedPipeBuilder { + name: addr.as_ref().encode_wide().chain(Some(0)).collect(), + dwOpenMode: PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | + FILE_FLAG_OVERLAPPED, + dwPipeMode: PIPE_TYPE_BYTE, + nMaxInstances: PIPE_UNLIMITED_INSTANCES, + nOutBufferSize: 65536, + nInBufferSize: 65536, + nDefaultTimeOut: 0, + } + } + + /// Indicates whether data is allowed to flow from the client to the server. + pub fn inbound(&mut self, allowed: bool) -> &mut Self { + flag(&mut self.dwOpenMode, allowed, PIPE_ACCESS_INBOUND); + self + } + + /// Indicates whether data is allowed to flow from the server to the client. + pub fn outbound(&mut self, allowed: bool) -> &mut Self { + flag(&mut self.dwOpenMode, allowed, PIPE_ACCESS_OUTBOUND); + self + } + + /// Indicates that this pipe must be the first instance. + /// + /// If set to true, then creation will fail if there's already an instance + /// elsewhere. + pub fn first(&mut self, first: bool) -> &mut Self { + flag(&mut self.dwOpenMode, first, FILE_FLAG_FIRST_PIPE_INSTANCE); + self + } + + /// Indicates whether this server can accept remote clients or not. + pub fn accept_remote(&mut self, accept: bool) -> &mut Self { + flag(&mut self.dwPipeMode, !accept, PIPE_REJECT_REMOTE_CLIENTS); + self + } + + /// Specifies the maximum number of instances of the server pipe that are + /// allowed. + /// + /// The first instance of a pipe can specify this value. A value of 255 + /// indicates that there is no limit to the number of instances. + pub fn max_instances(&mut self, instances: u8) -> &mut Self { + self.nMaxInstances = instances as DWORD; + self + } + + /// Specifies the number of bytes to reserver for the output buffer + pub fn out_buffer_size(&mut self, buffer: u32) -> &mut Self { + self.nOutBufferSize = buffer as DWORD; + self + } + + /// Specifies the number of bytes to reserver for the input buffer + pub fn in_buffer_size(&mut self, buffer: u32) -> &mut Self { + self.nInBufferSize = buffer as DWORD; + self + } + + /// Using the options in this builder, attempt to create a new named pipe. + /// + /// This function will call the `CreateNamedPipe` function and return the + /// result. + pub fn create(&mut self) -> io::Result { + let h = unsafe { + CreateNamedPipeW(self.name.as_ptr(), + self.dwOpenMode, self.dwPipeMode, + self.nMaxInstances, self.nOutBufferSize, + self.nInBufferSize, self.nDefaultTimeOut, + 0 as *mut _) + }; + if h == INVALID_HANDLE_VALUE { + Err(io::Error::last_os_error()) + } else { + Ok(NamedPipe(Handle::new(h))) + } + } +} + +#[cfg(test)] +mod tests { + use std::fs::{File, OpenOptions}; + use std::io::prelude::*; + use std::sync::mpsc::channel; + use std::thread; + use std::time::Duration; + + use rand::{thread_rng, Rng}; + + use super::{anonymous, NamedPipe, NamedPipeBuilder}; + use iocp::CompletionPort; + use Overlapped; + + fn name() -> String { + let name = thread_rng().gen_ascii_chars().take(30).collect::(); + format!(r"\\.\pipe\{}", name) + } + + #[test] + fn anon() { + let (mut read, mut write) = t!(anonymous(256)); + assert_eq!(t!(write.write(&[1, 2, 3])), 3); + let mut b = [0; 10]; + assert_eq!(t!(read.read(&mut b)), 3); + assert_eq!(&b[..3], &[1, 2, 3]); + } + + #[test] + fn named_not_first() { + let name = name(); + let _a = t!(NamedPipe::new(&name)); + assert!(NamedPipe::new(&name).is_err()); + + t!(NamedPipeBuilder::new(&name).first(false).create()); + } + + #[test] + fn named_connect() { + let name = name(); + let a = t!(NamedPipe::new(&name)); + + let t = thread::spawn(move || { + t!(File::open(name)); + }); + + t!(a.connect()); + t!(a.disconnect()); + t!(t.join()); + } + + #[test] + fn named_wait() { + let name = name(); + let a = t!(NamedPipe::new(&name)); + + let (tx, rx) = channel(); + let t = thread::spawn(move || { + t!(NamedPipe::wait(&name, None)); + t!(File::open(&name)); + assert!(NamedPipe::wait(&name, Some(Duration::from_millis(1))).is_err()); + t!(tx.send(())); + }); + + t!(a.connect()); + t!(rx.recv()); + t!(a.disconnect()); + t!(t.join()); + } + + #[test] + fn named_connect_overlapped() { + let name = name(); + let a = t!(NamedPipe::new(&name)); + + let t = thread::spawn(move || { + t!(File::open(name)); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_handle(2, &a)); + + let over = Overlapped::zero(); + unsafe { + t!(a.connect_overlapped(over.raw())); + } + + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 0); + assert_eq!(status.token(), 2); + assert_eq!(status.overlapped(), over.raw()); + t!(t.join()); + } + + #[test] + fn named_read_write() { + let name = name(); + let mut a = t!(NamedPipe::new(&name)); + + let t = thread::spawn(move || { + let mut f = t!(OpenOptions::new().read(true).write(true).open(name)); + t!(f.write_all(&[1, 2, 3])); + let mut b = [0; 10]; + assert_eq!(t!(f.read(&mut b)), 3); + assert_eq!(&b[..3], &[1, 2, 3]); + }); + + t!(a.connect()); + let mut b = [0; 10]; + assert_eq!(t!(a.read(&mut b)), 3); + assert_eq!(&b[..3], &[1, 2, 3]); + t!(a.write_all(&[1, 2, 3])); + t!(a.flush()); + t!(a.disconnect()); + t!(t.join()); + } + + #[test] + fn named_read_overlapped() { + let name = name(); + let a = t!(NamedPipe::new(&name)); + + let t = thread::spawn(move || { + let mut f = t!(File::create(name)); + t!(f.write_all(&[1, 2, 3])); + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_handle(3, &a)); + t!(a.connect()); + + let mut b = [0; 10]; + let over = Overlapped::zero(); + unsafe { + t!(a.read_overlapped(&mut b, over.raw())); + } + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 3); + assert_eq!(status.overlapped(), over.raw()); + assert_eq!(&b[..3], &[1, 2, 3]); + + t!(t.join()); + } + + #[test] + fn named_write_overlapped() { + let name = name(); + let a = t!(NamedPipe::new(&name)); + + let t = thread::spawn(move || { + let mut f = t!(super::connect(name)); + let mut b = [0; 10]; + assert_eq!(t!(f.read(&mut b)), 3); + assert_eq!(&b[..3], &[1, 2, 3]) + }); + + let cp = t!(CompletionPort::new(1)); + t!(cp.add_handle(3, &a)); + t!(a.connect()); + + let over = Overlapped::zero(); + unsafe { + t!(a.write_overlapped(&[1, 2, 3], over.raw())); + } + + let status = t!(cp.get(None)); + assert_eq!(status.bytes_transferred(), 3); + assert_eq!(status.token(), 3); + assert_eq!(status.overlapped(), over.raw()); + + t!(t.join()); + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/.cargo-checksum.json b/third_party/cargo/vendor/net2-0.2.33/.cargo-checksum.json new file mode 100644 index 0000000..247941b --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"c18ec02a8566f054a27e18df2ac53856a74864fad952a41abda096c91caae106","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"c13834771aa1973a02dfbf99c282850ea1d6974269ebe9081cd2853a5ac59c93","appveyor.yml":"6e3173d907ccfa65e289c99042cb29d4a23b9d1f4ec5bf7afa6c0d65365bab54","src/ext.rs":"b9300ae246e9ac451889f146ece8bb6ed4a95482edf806373de5af759cd09360","src/lib.rs":"8d8a171090b75e86e7505921460fba072db0077942edd11c4a3c8a70e9164eef","src/socket.rs":"a033d04061d95c4fea3eb78ce25f147d3b669034681e4119d00bc78b817a8096","src/sys/redox/impls.rs":"90059116f0514bd44dbf282a3e8d7b192c99e1a78a34ebacb00f2d325ca0f8b0","src/sys/redox/mod.rs":"137013d409fd174fed0ceb3eceb2c17d15f34a3af70c7d237c06dd3a144affc1","src/sys/unix/impls.rs":"05f123226e8fe7559317d50864021650b2455d25d01a9aff1c65c01ae26cf4ef","src/sys/unix/mod.rs":"bb28a7275eac021132b01206d134802902d616c0be3e82100b45a3ff1eba4c02","src/sys/windows/impls.rs":"bee70b7cd45055c4eaa1967f7aad7ec46639de458c71ed6f3e97a2f7b2c49281","src/sys/windows/mod.rs":"0706f1587af0f693f75e8597e4196075a3f673c89727dd865447da306974bf35","src/tcp.rs":"0bebf5cca75714151de30c8f2d7697ca519c57da065e93ba81796bce04673f8d","src/udp.rs":"8af5a55a4ae5e4120ffe18dcc4dc24072e18da34bf3591a02b18653e5d3e8ac8","src/unix.rs":"fe9cdbd75ef2e1fafc128d1abb5f32500eaf0b674aa618d837e06ab1d0dc6687","src/utils.rs":"d31de5333a6fa2f5c99b64cc937be596888d9863264632e6bc6b36b30197fa5b","tests/all.rs":"12cb4616c842f655ece1b477664d41821f95b3051053da641b1d85026ee18274"},"package":"42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88"} \ No newline at end of file diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/BUILD b/third_party/cargo/vendor/net2-0.2.33/BUILD similarity index 76% rename from third_party/cargo/vendor/stable_deref_trait-1.1.1/BUILD rename to third_party/cargo/vendor/net2-0.2.33/BUILD index b9598cc..9fbb044 100644 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/BUILD +++ b/third_party/cargo/vendor/net2-0.2.33/BUILD @@ -23,22 +23,25 @@ load( ) +# Unsupported target "all" with type "test" omitted rust_library( - name = "stable_deref_trait", + name = "net2", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", srcs = glob(["**/*.rs"]), deps = [ + "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", + "//third_party/cargo/vendor/libc-0.2.67:libc", ], rustc_flags = [ "--cap-lints=allow", ], - version = "1.1.1", + version = "0.2.33", crate_features = [ "default", - "std", + "duration", ], ) diff --git a/third_party/cargo/vendor/net2-0.2.33/Cargo.toml b/third_party/cargo/vendor/net2-0.2.33/Cargo.toml new file mode 100644 index 0000000..40a6d8e --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/Cargo.toml @@ -0,0 +1,34 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g. crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "net2" +version = "0.2.33" +authors = ["Alex Crichton "] +description = "Extensions to the standard library's networking types as proposed in RFC 1158.\n" +homepage = "https://github.com/rust-lang-nursery/net2-rs" +documentation = "https://doc.rust-lang.org/net2-rs/" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang-nursery/net2-rs" +[dependencies.cfg-if] +version = "0.1" + +[features] +default = ["duration"] +duration = [] +nightly = [] +[target."cfg(any(target_os=\"redox\", unix))".dependencies.libc] +version = "0.2.42" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["handleapi", "winsock2", "ws2def", "ws2ipdef", "ws2tcpip"] diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/LICENSE-APACHE b/third_party/cargo/vendor/net2-0.2.33/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/parking_lot-0.6.4/LICENSE-APACHE rename to third_party/cargo/vendor/net2-0.2.33/LICENSE-APACHE diff --git a/third_party/cargo/vendor/rand-0.5.6/LICENSE-MIT b/third_party/cargo/vendor/net2-0.2.33/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/rand-0.5.6/LICENSE-MIT rename to third_party/cargo/vendor/net2-0.2.33/LICENSE-MIT diff --git a/third_party/cargo/vendor/net2-0.2.33/README.md b/third_party/cargo/vendor/net2-0.2.33/README.md new file mode 100644 index 0000000..6d8fc15 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/README.md @@ -0,0 +1,35 @@ +# net2 + +[![Build Status](https://travis-ci.org/rust-lang-nursery/net2-rs.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/net2-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/ns78f02jt2uvd2lp?svg=true)](https://ci.appveyor.com/project/alexcrichton/net2-rs) + +[Documentation](https://docs.rs/net2/0.2.32/net2/) + +Extensions to the standard library's networking types, proposed in [RFC +1158][rfc]. + + +[rfc]: https://github.com/alexcrichton/rfcs/blob/net2.1/text/0000-io-net-2.1.md + +```toml +# Cargo.toml +[dependencies] +net2 = "0.2" +``` + +# License + +This project 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. diff --git a/third_party/cargo/vendor/net2-0.2.33/appveyor.yml b/third_party/cargo/vendor/net2-0.2.33/appveyor.yml new file mode 100644 index 0000000..9b61baf --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/appveyor.yml @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose --features nightly --target %TARGET% diff --git a/third_party/cargo/vendor/net2-0.2.33/src/ext.rs b/third_party/cargo/vendor/net2-0.2.33/src/ext.rs new file mode 100644 index 0000000..38185d6 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/ext.rs @@ -0,0 +1,1501 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style, dead_code)] + +use std::io; +use std::mem; +use std::net::{TcpStream, TcpListener, UdpSocket, Ipv4Addr, Ipv6Addr}; +use std::net::ToSocketAddrs; + +use {TcpBuilder, UdpBuilder, FromInner}; +use sys; +use sys::c; +use socket; + +cfg_if! { + if #[cfg(any(target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris", + target_env = "uclibc"))] { + use libc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; + use libc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; + } else { + // ... + } +} + +use std::time::Duration; + +#[cfg(any(unix, target_os = "redox"))] use libc::*; +#[cfg(any(unix, target_os = "redox"))] use std::os::unix::prelude::*; +#[cfg(target_os = "redox")] pub type Socket = usize; +#[cfg(unix)] pub type Socket = c_int; +#[cfg(windows)] pub type Socket = SOCKET; +#[cfg(windows)] use std::os::windows::prelude::*; +#[cfg(windows)] use sys::c::*; + +#[cfg(windows)] const SIO_KEEPALIVE_VALS: DWORD = 0x98000004; +#[cfg(windows)] +#[repr(C)] +struct tcp_keepalive { + onoff: c_ulong, + keepalivetime: c_ulong, + keepaliveinterval: c_ulong, +} + +#[cfg(target_os = "redox")] fn v(opt: c_int) -> c_int { opt } +#[cfg(unix)] fn v(opt: c_int) -> c_int { opt } +#[cfg(windows)] fn v(opt: IPPROTO) -> c_int { opt as c_int } + +pub fn set_opt(sock: Socket, opt: c_int, val: c_int, + payload: T) -> io::Result<()> { + unsafe { + let payload = &payload as *const T as *const c_void; + #[cfg(target_os = "redox")] + let sock = sock as c_int; + try!(::cvt(setsockopt(sock, opt, val, payload as *const _, + mem::size_of::() as socklen_t))); + Ok(()) + } +} + +pub fn get_opt(sock: Socket, opt: c_int, val: c_int) -> io::Result { + unsafe { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::() as socklen_t; + #[cfg(target_os = "redox")] + let sock = sock as c_int; + try!(::cvt(getsockopt(sock, opt, val, + &mut slot as *mut _ as *mut _, + &mut len))); + assert_eq!(len as usize, mem::size_of::()); + Ok(slot) + } +} + +/// Extension methods for the standard [`TcpStream` type][link] in `std::net`. +/// +/// [link]: https://doc.rust-lang.org/std/net/struct.TcpStream.html +pub trait TcpStreamExt { + /// Sets the value of the `TCP_NODELAY` option on this socket. + /// + /// If set, this option disables the Nagle algorithm. This means that + /// segments are always sent as soon as possible, even if there is only a + /// small amount of data. When not set, data is buffered until there is a + /// sufficient amount to send out, thereby avoiding the frequent sending of + /// small packets. + fn set_nodelay(&self, nodelay: bool) -> io::Result<()>; + + /// Gets the value of the `TCP_NODELAY` option on this socket. + /// + /// For more information about this option, see [`set_nodelay`][link]. + /// + /// [link]: #tymethod.set_nodelay + fn nodelay(&self) -> io::Result; + + /// Sets the value of the `SO_RCVBUF` option on this socket. + /// + /// Changes the size of the operating system's receive buffer associated with the socket. + fn set_recv_buffer_size(&self, size: usize) -> io::Result<()>; + + /// Gets the value of the `SO_RCVBUF` option on this socket. + /// + /// For more information about this option, see [`set_recv_buffer_size`][link]. + /// + /// [link]: #tymethod.set_recv_buffer_size + fn recv_buffer_size(&self) -> io::Result; + + /// Sets the value of the `SO_SNDBUF` option on this socket. + /// + /// Changes the size of the operating system's send buffer associated with the socket. + fn set_send_buffer_size(&self, size: usize) -> io::Result<()>; + + /// Gets the value of the `SO_SNDBUF` option on this socket. + /// + /// For more information about this option, see [`set_send_buffer`][link]. + /// + /// [link]: #tymethod.set_send_buffer + fn send_buffer_size(&self) -> io::Result; + + /// Sets whether keepalive messages are enabled to be sent on this socket. + /// + /// On Unix, this option will set the `SO_KEEPALIVE` as well as the + /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). + /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. + /// + /// If `None` is specified then keepalive messages are disabled, otherwise + /// the number of milliseconds specified will be the time to remain idle + /// before sending a TCP keepalive probe. + /// + /// Some platforms specify this value in seconds, so sub-second millisecond + /// specifications may be omitted. + fn set_keepalive_ms(&self, keepalive: Option) -> io::Result<()>; + + /// Returns whether keepalive messages are enabled on this socket, and if so + /// the amount of milliseconds between them. + /// + /// For more information about this option, see [`set_keepalive_ms`][link]. + /// + /// [link]: #tymethod.set_keepalive_ms + fn keepalive_ms(&self) -> io::Result>; + + /// Sets whether keepalive messages are enabled to be sent on this socket. + /// + /// On Unix, this option will set the `SO_KEEPALIVE` as well as the + /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). + /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. + /// + /// If `None` is specified then keepalive messages are disabled, otherwise + /// the duration specified will be the time to remain idle before sending a + /// TCP keepalive probe. + /// + /// Some platforms specify this value in seconds, so sub-second + /// specifications may be omitted. + fn set_keepalive(&self, keepalive: Option) -> io::Result<()>; + + /// Returns whether keepalive messages are enabled on this socket, and if so + /// the duration of time between them. + /// + /// For more information about this option, see [`set_keepalive`][link]. + /// + /// [link]: #tymethod.set_keepalive + fn keepalive(&self) -> io::Result>; + + /// Sets the `SO_RCVTIMEO` option for this socket. + /// + /// This option specifies the timeout, in milliseconds, of how long calls to + /// this socket's `read` function will wait before returning a timeout. A + /// value of `None` means that no read timeout should be specified and + /// otherwise `Some` indicates the number of milliseconds for the timeout. + fn set_read_timeout_ms(&self, val: Option) -> io::Result<()>; + + /// Sets the `SO_RCVTIMEO` option for this socket. + /// + /// This option specifies the timeout of how long calls to this socket's + /// `read` function will wait before returning a timeout. A value of `None` + /// means that no read timeout should be specified and otherwise `Some` + /// indicates the number of duration of the timeout. + fn set_read_timeout(&self, val: Option) -> io::Result<()>; + + /// Gets the value of the `SO_RCVTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_read_timeout_ms`][link]. + /// + /// [link]: #tymethod.set_read_timeout_ms + fn read_timeout_ms(&self) -> io::Result>; + + /// Gets the value of the `SO_RCVTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_read_timeout`][link]. + /// + /// [link]: #tymethod.set_read_timeout + fn read_timeout(&self) -> io::Result>; + + /// Sets the `SO_SNDTIMEO` option for this socket. + /// + /// This option specifies the timeout, in milliseconds, of how long calls to + /// this socket's `write` function will wait before returning a timeout. A + /// value of `None` means that no read timeout should be specified and + /// otherwise `Some` indicates the number of milliseconds for the timeout. + fn set_write_timeout_ms(&self, val: Option) -> io::Result<()>; + + /// Sets the `SO_SNDTIMEO` option for this socket. + /// + /// This option specifies the timeout of how long calls to this socket's + /// `write` function will wait before returning a timeout. A value of `None` + /// means that no read timeout should be specified and otherwise `Some` + /// indicates the duration of the timeout. + fn set_write_timeout(&self, val: Option) -> io::Result<()>; + + /// Gets the value of the `SO_SNDTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_write_timeout_ms`][link]. + /// + /// [link]: #tymethod.set_write_timeout_ms + fn write_timeout_ms(&self) -> io::Result>; + + /// Gets the value of the `SO_SNDTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_write_timeout`][link]. + /// + /// [link]: #tymethod.set_write_timeout + fn write_timeout(&self) -> io::Result>; + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + fn set_ttl(&self, ttl: u32) -> io::Result<()>; + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #tymethod.set_ttl + fn ttl(&self) -> io::Result; + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// If this is set to `true` then the socket is restricted to sending and + /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications + /// can bind the same port at the same time. + /// + /// If this is set to `false` then the socket can be used to send and + /// receive packets from an IPv4-mapped IPv6 address. + fn set_only_v6(&self, only_v6: bool) -> io::Result<()>; + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see [`set_only_v6`][link]. + /// + /// [link]: #tymethod.set_only_v6 + fn only_v6(&self) -> io::Result; + + /// Executes a `connect` operation on this socket, establishing a connection + /// to the host specified by `addr`. + /// + /// Note that this normally does not need to be called on a `TcpStream`, + /// it's typically automatically done as part of a normal + /// `TcpStream::connect` function call or `TcpBuilder::connect` method call. + /// + /// This should only be necessary if an unconnected socket was extracted + /// from a `TcpBuilder` and then needs to be connected. + fn connect(&self, addr: T) -> io::Result<()>; + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + fn take_error(&self) -> io::Result>; + + /// Moves this TCP stream into or out of nonblocking mode. + /// + /// On Unix this corresponds to calling fcntl, and on Windows this + /// corresponds to calling ioctlsocket. + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>; + + /// Sets the linger duration of this socket by setting the SO_LINGER option + fn set_linger(&self, dur: Option) -> io::Result<()>; + + /// reads the linger duration for this socket by getting the SO_LINGER option + fn linger(&self) -> io::Result>; +} + +/// Extension methods for the standard [`TcpListener` type][link] in `std::net`. +/// +/// [link]: https://doc.rust-lang.org/std/net/struct.TcpListener.html +pub trait TcpListenerExt { + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This is the same as [`TcpStreamExt::set_ttl`][other]. + /// + /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl + fn set_ttl(&self, ttl: u32) -> io::Result<()>; + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_ttl`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_ttl + fn ttl(&self) -> io::Result; + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_only_v6`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6 + fn set_only_v6(&self, only_v6: bool) -> io::Result<()>; + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_only_v6`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6 + fn only_v6(&self) -> io::Result; + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + fn take_error(&self) -> io::Result>; + + /// Moves this TCP listener into or out of nonblocking mode. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_nonblocking`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_nonblocking + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>; + + /// Sets the linger duration of this socket by setting the SO_LINGER option + fn set_linger(&self, dur: Option) -> io::Result<()>; + + /// reads the linger duration for this socket by getting the SO_LINGER option + fn linger(&self) -> io::Result>; +} + +/// Extension methods for the standard [`UdpSocket` type][link] in `std::net`. +/// +/// [link]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html +pub trait UdpSocketExt { + /// Sets the value of the `SO_RCVBUF` option on this socket. + /// + /// Changes the size of the operating system's receive buffer associated with the socket. + fn set_recv_buffer_size(&self, size: usize) -> io::Result<()>; + + /// Gets the value of the `SO_RCVBUF` option on this socket. + /// + /// For more information about this option, see [`set_recv_buffer_size`][link]. + /// + /// [link]: #tymethod.set_recv_buffer_size + fn recv_buffer_size(&self) -> io::Result; + + /// Sets the value of the `SO_SNDBUF` option on this socket. + /// + /// Changes the size of the operating system's send buffer associated with the socket. + fn set_send_buffer_size(&self, size: usize) -> io::Result<()>; + + /// Gets the value of the `SO_SNDBUF` option on this socket. + /// + /// For more information about this option, see [`set_send_buffer`][link]. + /// + /// [link]: #tymethod.set_send_buffer + fn send_buffer_size(&self) -> io::Result; + + /// Sets the value of the `SO_BROADCAST` option for this socket. + /// + /// When enabled, this socket is allowed to send packets to a broadcast + /// address. + fn set_broadcast(&self, broadcast: bool) -> io::Result<()>; + + /// Gets the value of the `SO_BROADCAST` option for this socket. + /// + /// For more information about this option, see + /// [`set_broadcast`][link]. + /// + /// [link]: #tymethod.set_broadcast + fn broadcast(&self) -> io::Result; + + /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// If enabled, multicast packets will be looped back to the local socket. + /// Note that this may not have any affect on IPv6 sockets. + fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>; + + /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v4`][link]. + /// + /// [link]: #tymethod.set_multicast_loop_v4 + fn multicast_loop_v4(&self) -> io::Result; + + /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// Indicates the time-to-live value of outgoing multicast packets for + /// this socket. The default value is 1 which means that multicast packets + /// don't leave the local network unless explicitly requested. + /// + /// Note that this may not have any affect on IPv6 sockets. + fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>; + + /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_ttl_v4`][link]. + /// + /// [link]: #tymethod.set_multicast_ttl_v4 + fn multicast_ttl_v4(&self) -> io::Result; + + /// Sets the value of the `IPV6_MULTICAST_HOPS` option for this socket + fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()>; + + /// Gets the value of the `IPV6_MULTICAST_HOPS` option for this socket + fn multicast_hops_v6(&self) -> io::Result; + + /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// Controls whether this socket sees the multicast packets it sends itself. + /// Note that this may not have any affect on IPv4 sockets. + fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>; + + /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v6`][link]. + /// + /// [link]: #tymethod.set_multicast_loop_v6 + fn multicast_loop_v6(&self) -> io::Result; + + /// Sets the value of the `IP_MULTICAST_IF` option for this socket. + /// + /// Specifies the interface to use for routing multicast packets. + fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()>; + + /// Gets the value of the `IP_MULTICAST_IF` option for this socket. + /// + /// Returns the interface to use for routing multicast packets. + fn multicast_if_v4(&self) -> io::Result; + + + /// Sets the value of the `IPV6_MULTICAST_IF` option for this socket. + /// + /// Specifies the interface to use for routing multicast packets. + fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()>; + + /// Gets the value of the `IPV6_MULTICAST_IF` option for this socket. + /// + /// Returns the interface to use for routing multicast packets. + fn multicast_if_v6(&self) -> io::Result; + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This is the same as [`TcpStreamExt::set_ttl`][other]. + /// + /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl + fn set_ttl(&self, ttl: u32) -> io::Result<()>; + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_ttl`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_ttl + fn ttl(&self) -> io::Result; + + /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket. + /// + /// Specifies the hop limit for ipv6 unicast packets + fn set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()>; + + /// Gets the value of the `IPV6_UNICAST_HOPS` option for this socket. + /// + /// Specifies the hop limit for ipv6 unicast packets + fn unicast_hops_v6(&self) -> io::Result; + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_only_v6`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6 + fn set_only_v6(&self, only_v6: bool) -> io::Result<()>; + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_only_v6`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_only_v6 + fn only_v6(&self) -> io::Result; + + /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// address of the local interface with which the system should join the + /// multicast group. If it's equal to `INADDR_ANY` then an appropriate + /// interface is chosen by the system. + fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) + -> io::Result<()>; + + /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// index of the interface to join/leave (or 0 to indicate any interface). + fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) + -> io::Result<()>; + + /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v4`][link]. + /// + /// [link]: #tymethod.join_multicast_v4 + fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) + -> io::Result<()>; + + /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v6`][link]. + /// + /// [link]: #tymethod.join_multicast_v6 + fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) + -> io::Result<()>; + + /// Sets the `SO_RCVTIMEO` option for this socket. + /// + /// This option specifies the timeout, in milliseconds, of how long calls to + /// this socket's `read` function will wait before returning a timeout. A + /// value of `None` means that no read timeout should be specified and + /// otherwise `Some` indicates the number of milliseconds for the timeout. + fn set_read_timeout_ms(&self, val: Option) -> io::Result<()>; + + /// Sets the `SO_RCVTIMEO` option for this socket. + /// + /// This option specifies the timeout of how long calls to this socket's + /// `read` function will wait before returning a timeout. A value of `None` + /// means that no read timeout should be specified and otherwise `Some` + /// indicates the number of duration of the timeout. + fn set_read_timeout(&self, val: Option) -> io::Result<()>; + + /// Gets the value of the `SO_RCVTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_read_timeout_ms`][link]. + /// + /// [link]: #tymethod.set_read_timeout_ms + fn read_timeout_ms(&self) -> io::Result>; + + /// Gets the value of the `SO_RCVTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_read_timeout`][link]. + /// + /// [link]: #tymethod.set_read_timeout + fn read_timeout(&self) -> io::Result>; + + /// Sets the `SO_SNDTIMEO` option for this socket. + /// + /// This option specifies the timeout, in milliseconds, of how long calls to + /// this socket's `write` function will wait before returning a timeout. A + /// value of `None` means that no read timeout should be specified and + /// otherwise `Some` indicates the number of milliseconds for the timeout. + fn set_write_timeout_ms(&self, val: Option) -> io::Result<()>; + + /// Sets the `SO_SNDTIMEO` option for this socket. + /// + /// This option specifies the timeout of how long calls to this socket's + /// `write` function will wait before returning a timeout. A value of `None` + /// means that no read timeout should be specified and otherwise `Some` + /// indicates the duration of the timeout. + fn set_write_timeout(&self, val: Option) -> io::Result<()>; + + /// Gets the value of the `SO_SNDTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_write_timeout_ms`][link]. + /// + /// [link]: #tymethod.set_write_timeout_ms + fn write_timeout_ms(&self) -> io::Result>; + + /// Gets the value of the `SO_SNDTIMEO` option for this socket. + /// + /// For more information about this option, see [`set_write_timeout`][link]. + /// + /// [link]: #tymethod.set_write_timeout + fn write_timeout(&self) -> io::Result>; + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + fn take_error(&self) -> io::Result>; + + /// Connects this UDP socket to a remote address, allowing the `send` and + /// `recv` syscalls to be used to send data and also applies filters to only + /// receive data from the specified address. + fn connect(&self, addr: A) -> io::Result<()>; + + /// Sends data on the socket to the remote address to which it is connected. + /// + /// The `connect` method will connect this socket to a remote address. This + /// method will fail if the socket is not connected. + fn send(&self, buf: &[u8]) -> io::Result; + + /// Receives data on the socket from the remote address to which it is + /// connected. + /// + /// The `connect` method will connect this socket to a remote address. This + /// method will fail if the socket is not connected. + fn recv(&self, buf: &mut [u8]) -> io::Result; + + /// Moves this UDP socket into or out of nonblocking mode. + /// + /// For more information about this option, see + /// [`TcpStreamExt::set_nonblocking`][link]. + /// + /// [link]: trait.TcpStreamExt.html#tymethod.set_nonblocking + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()>; +} + +#[doc(hidden)] +pub trait AsSock { + fn as_sock(&self) -> Socket; +} + +#[cfg(target_os = "redox")] +impl AsSock for T { + fn as_sock(&self) -> Socket { self.as_raw_fd() } +} +#[cfg(unix)] +impl AsSock for T { + fn as_sock(&self) -> Socket { self.as_raw_fd() } +} +#[cfg(windows)] +impl AsSock for T { + fn as_sock(&self) -> Socket { self.as_raw_socket() as Socket } +} + +cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + use libc::TCP_KEEPALIVE as KEEPALIVE_OPTION; + } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd"))] { + use libc::SO_KEEPALIVE as KEEPALIVE_OPTION; + } else if #[cfg(unix)] { + use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; + } else if #[cfg(target_os = "redox")] { + use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; + } else { + // ... + } +} + +impl TcpStreamExt for TcpStream { + + fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + // TODO: casting usize to a c_int should be a checked cast + set_opt(self.as_sock(), SOL_SOCKET, SO_RCVBUF, size as c_int) + } + + fn recv_buffer_size(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_RCVBUF).map(int2usize) + } + + fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_SNDBUF, size as c_int) + } + + fn send_buffer_size(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_SNDBUF).map(int2usize) + } + + fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + set_opt(self.as_sock(), v(IPPROTO_TCP), TCP_NODELAY, + nodelay as c_int) + } + fn nodelay(&self) -> io::Result { + get_opt(self.as_sock(), v(IPPROTO_TCP), TCP_NODELAY) + .map(int2bool) + } + + fn set_keepalive(&self, keepalive: Option) -> io::Result<()> { + self.set_keepalive_ms(keepalive.map(dur2ms)) + } + + fn keepalive(&self) -> io::Result> { + self.keepalive_ms().map(|o| o.map(ms2dur)) + } + + #[cfg(target_os = "redox")] + fn set_keepalive_ms(&self, keepalive: Option) -> io::Result<()> { + try!(set_opt(self.as_sock(), SOL_SOCKET, SO_KEEPALIVE, + keepalive.is_some() as c_int)); + if let Some(dur) = keepalive { + try!(set_opt(self.as_sock(), v(IPPROTO_TCP), KEEPALIVE_OPTION, + (dur / 1000) as c_int)); + } + Ok(()) + } + + #[cfg(target_os = "redox")] + fn keepalive_ms(&self) -> io::Result> { + let keepalive = try!(get_opt::(self.as_sock(), SOL_SOCKET, + SO_KEEPALIVE)); + if keepalive == 0 { + return Ok(None) + } + let secs = try!(get_opt::(self.as_sock(), v(IPPROTO_TCP), + KEEPALIVE_OPTION)); + Ok(Some((secs as u32) * 1000)) + } + + #[cfg(unix)] + fn set_keepalive_ms(&self, keepalive: Option) -> io::Result<()> { + try!(set_opt(self.as_sock(), SOL_SOCKET, SO_KEEPALIVE, + keepalive.is_some() as c_int)); + if let Some(dur) = keepalive { + try!(set_opt(self.as_sock(), v(IPPROTO_TCP), KEEPALIVE_OPTION, + (dur / 1000) as c_int)); + } + Ok(()) + } + + #[cfg(unix)] + fn keepalive_ms(&self) -> io::Result> { + let keepalive = try!(get_opt::(self.as_sock(), SOL_SOCKET, + SO_KEEPALIVE)); + if keepalive == 0 { + return Ok(None) + } + let secs = try!(get_opt::(self.as_sock(), v(IPPROTO_TCP), + KEEPALIVE_OPTION)); + Ok(Some((secs as u32) * 1000)) + } + + #[cfg(windows)] + fn set_keepalive_ms(&self, keepalive: Option) -> io::Result<()> { + let ms = keepalive.unwrap_or(INFINITE); + let ka = tcp_keepalive { + onoff: keepalive.is_some() as c_ulong, + keepalivetime: ms as c_ulong, + keepaliveinterval: ms as c_ulong, + }; + unsafe { + ::cvt_win(WSAIoctl(self.as_sock(), + SIO_KEEPALIVE_VALS, + &ka as *const _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0, + 0 as *mut _, + 0 as *mut _, + None)).map(|_| ()) + } + } + + #[cfg(windows)] + fn keepalive_ms(&self) -> io::Result> { + let mut ka = tcp_keepalive { + onoff: 0, + keepalivetime: 0, + keepaliveinterval: 0, + }; + unsafe { + try!(::cvt_win(WSAIoctl(self.as_sock(), + SIO_KEEPALIVE_VALS, + 0 as *mut _, + 0, + &mut ka as *mut _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0 as *mut _, + None))); + } + Ok({ + if ka.onoff == 0 { + None + } else { + timeout2ms(ka.keepaliveinterval as DWORD) + } + }) + } + + fn set_read_timeout_ms(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_RCVTIMEO, + ms2timeout(dur)) + } + + fn read_timeout_ms(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_RCVTIMEO) + .map(timeout2ms) + } + + fn set_write_timeout_ms(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_SNDTIMEO, + ms2timeout(dur)) + } + + fn write_timeout_ms(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_SNDTIMEO) + .map(timeout2ms) + } + + fn set_read_timeout(&self, dur: Option) -> io::Result<()> { + self.set_read_timeout_ms(dur.map(dur2ms)) + } + + fn read_timeout(&self) -> io::Result> { + self.read_timeout_ms().map(|o| o.map(ms2dur)) + } + + fn set_write_timeout(&self, dur: Option) -> io::Result<()> { + self.set_write_timeout_ms(dur.map(dur2ms)) + } + + fn write_timeout(&self) -> io::Result> { + self.write_timeout_ms().map(|o| o.map(ms2dur)) + } + + fn set_ttl(&self, ttl: u32) -> io::Result<()> { + set_opt(self.as_sock(), IPPROTO_IP, IP_TTL, ttl as c_int) + } + + fn ttl(&self) -> io::Result { + get_opt::(self.as_sock(), IPPROTO_IP, IP_TTL) + .map(|b| b as u32) + } + + fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY, only_v6 as c_int) + } + + fn only_v6(&self) -> io::Result { + get_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY).map(int2bool) + } + + fn connect(&self, addr: T) -> io::Result<()> { + do_connect(self.as_sock(), addr) + } + + fn take_error(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_ERROR).map(int2err) + } + + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + set_nonblocking(self.as_sock(), nonblocking) + } + + fn set_linger(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_LINGER, dur2linger(dur)) + } + + fn linger(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_LINGER).map(linger2dur) + } +} + +#[cfg(any(target_os = "redox", unix))] +fn ms2timeout(dur: Option) -> timeval { + // TODO: be more rigorous + match dur { + Some(d) => timeval { + tv_sec: (d / 1000) as time_t, + tv_usec: (d % 1000) as suseconds_t, + }, + None => timeval { tv_sec: 0, tv_usec: 0 }, + } +} + +#[cfg(any(target_os = "redox", unix))] +fn timeout2ms(dur: timeval) -> Option { + if dur.tv_sec == 0 && dur.tv_usec == 0 { + None + } else { + Some(dur.tv_sec as u32 * 1000 + dur.tv_usec as u32 / 1000) + } +} + +#[cfg(windows)] +fn ms2timeout(dur: Option) -> DWORD { + dur.unwrap_or(0) +} + +#[cfg(windows)] +fn timeout2ms(dur: DWORD) -> Option { + if dur == 0 { + None + } else { + Some(dur) + } +} + +fn linger2dur(linger_opt: linger) -> Option { + if linger_opt.l_onoff == 0 { + None + } + else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +#[cfg(windows)] +fn dur2linger(dur: Option) -> linger { + match dur { + Some(d) => { + linger { + l_onoff: 1, + l_linger: d.as_secs() as u16, + } + }, + None => linger { l_onoff: 0, l_linger: 0 }, + } +} + +#[cfg(any(target_os = "redox", unix))] +fn dur2linger(dur: Option) -> linger { + match dur { + Some(d) => { + linger { + l_onoff: 1, + l_linger: d.as_secs() as c_int, + } + }, + None => linger { l_onoff: 0, l_linger: 0 }, + } +} + +fn ms2dur(ms: u32) -> Duration { + Duration::new((ms as u64) / 1000, (ms as u32) % 1000 * 1_000_000) +} + +fn dur2ms(dur: Duration) -> u32 { + (dur.as_secs() as u32 * 1000) + (dur.subsec_nanos() / 1_000_000) +} + +pub fn int2bool(n: c_int) -> bool { + if n == 0 {false} else {true} +} + +pub fn int2usize(n: c_int) -> usize { + // TODO: casting c_int to a usize should be a checked cast + n as usize +} + +pub fn int2err(n: c_int) -> Option { + if n == 0 { + None + } else { + Some(io::Error::from_raw_os_error(n as i32)) + } +} + +impl UdpSocketExt for UdpSocket { + + fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_RCVBUF, size as c_int) + } + + fn recv_buffer_size(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_RCVBUF).map(int2usize) + } + + fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_SNDBUF, size as c_int) + } + + fn send_buffer_size(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_SNDBUF).map(int2usize) + } + + fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_BROADCAST, + broadcast as c_int) + } + fn broadcast(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_BROADCAST) + .map(int2bool) + } + fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + set_opt(self.as_sock(), IPPROTO_IP, IP_MULTICAST_LOOP, + multicast_loop_v4 as c_int) + } + fn multicast_loop_v4(&self) -> io::Result { + get_opt(self.as_sock(), IPPROTO_IP, IP_MULTICAST_LOOP) + .map(int2bool) + } + + fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + set_opt(self.as_sock(), IPPROTO_IP, IP_MULTICAST_TTL, + multicast_ttl_v4 as c_int) + } + + fn multicast_ttl_v4(&self) -> io::Result { + get_opt::(self.as_sock(), IPPROTO_IP, IP_MULTICAST_TTL) + .map(|b| b as u32) + } + + fn set_multicast_hops_v6(&self, _hops: u32) -> io::Result<()> { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_HOPS, + _hops as c_int) + } + + fn multicast_hops_v6(&self) -> io::Result { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + get_opt::(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_HOPS) + .map(|b| b as u32) + } + + fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int) + } + fn multicast_loop_v6(&self) -> io::Result { + get_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_LOOP) + .map(int2bool) + } + + fn set_multicast_if_v4(&self, _interface: &Ipv4Addr) -> io::Result<()> { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + set_opt(self.as_sock(), IPPROTO_IP, IP_MULTICAST_IF, ip2in_addr(_interface)) + } + + fn multicast_if_v4(&self) -> io::Result { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + get_opt(self.as_sock(), IPPROTO_IP, IP_MULTICAST_IF).map(in_addr2ip) + } + + fn set_multicast_if_v6(&self, _interface: u32) -> io::Result<()> { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_IF, to_ipv6mr_interface(_interface)) + } + + fn multicast_if_v6(&self) -> io::Result { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + get_opt::(self.as_sock(), v(IPPROTO_IPV6), IPV6_MULTICAST_IF).map(|b| b as u32) + } + + fn set_ttl(&self, ttl: u32) -> io::Result<()> { + set_opt(self.as_sock(), IPPROTO_IP, IP_TTL, ttl as c_int) + } + + fn ttl(&self) -> io::Result { + get_opt::(self.as_sock(), IPPROTO_IP, IP_TTL) + .map(|b| b as u32) + } + + fn set_unicast_hops_v6(&self, _ttl: u32) -> io::Result<()> { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_UNICAST_HOPS, _ttl as c_int) + } + + fn unicast_hops_v6(&self) -> io::Result { + #[cfg(target_os = "redox")] + return Err(io::Error::new(io::ErrorKind::Other, "Not implemented yet")); + #[cfg(not(target_os = "redox"))] + get_opt::(self.as_sock(), IPPROTO_IP, IPV6_UNICAST_HOPS) + .map(|b| b as u32) + } + + fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY, only_v6 as c_int) + } + + fn only_v6(&self) -> io::Result { + get_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY).map(int2bool) + } + + fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) + -> io::Result<()> { + let mreq = ip_mreq { + imr_multiaddr: ip2in_addr(multiaddr), + imr_interface: ip2in_addr(interface), + }; + set_opt(self.as_sock(), IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) + } + + fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) + -> io::Result<()> { + let mreq = ipv6_mreq { + ipv6mr_multiaddr: ip2in6_addr(multiaddr), + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_ADD_MEMBERSHIP, + mreq) + } + + fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) + -> io::Result<()> { + let mreq = ip_mreq { + imr_multiaddr: ip2in_addr(multiaddr), + imr_interface: ip2in_addr(interface), + }; + set_opt(self.as_sock(), IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) + } + + fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) + -> io::Result<()> { + let mreq = ipv6_mreq { + ipv6mr_multiaddr: ip2in6_addr(multiaddr), + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_DROP_MEMBERSHIP, + mreq) + } + + fn set_read_timeout_ms(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_RCVTIMEO, + ms2timeout(dur)) + } + + fn read_timeout_ms(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_RCVTIMEO) + .map(timeout2ms) + } + + fn set_write_timeout_ms(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_SNDTIMEO, + ms2timeout(dur)) + } + + fn write_timeout_ms(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_SNDTIMEO) + .map(timeout2ms) + } + + fn set_read_timeout(&self, dur: Option) -> io::Result<()> { + self.set_read_timeout_ms(dur.map(dur2ms)) + } + + fn read_timeout(&self) -> io::Result> { + self.read_timeout_ms().map(|o| o.map(ms2dur)) + } + + fn set_write_timeout(&self, dur: Option) -> io::Result<()> { + self.set_write_timeout_ms(dur.map(dur2ms)) + } + + fn write_timeout(&self) -> io::Result> { + self.write_timeout_ms().map(|o| o.map(ms2dur)) + } + + fn take_error(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_ERROR).map(int2err) + } + + fn connect(&self, addr: A) -> io::Result<()> { + do_connect(self.as_sock(), addr) + } + + #[cfg(target_os = "redox")] + fn send(&self, buf: &[u8]) -> io::Result { + unsafe { + ::cvt(write(self.as_sock() as c_int, buf.as_ptr() as *const _, buf.len())).map(|n| n as usize) + } + } + + #[cfg(unix)] + fn send(&self, buf: &[u8]) -> io::Result { + unsafe { + ::cvt(send(self.as_sock() as c_int, buf.as_ptr() as *const _, buf.len(), 0)).map(|n| n as usize) + } + } + + #[cfg(windows)] + fn send(&self, buf: &[u8]) -> io::Result { + let len = ::std::cmp::min(buf.len(), c_int::max_value() as usize); + let buf = &buf[..len]; + unsafe { + ::cvt(send(self.as_sock(), buf.as_ptr() as *const _, len as c_int, 0)) + .map(|n| n as usize) + } + } + + #[cfg(target_os = "redox")] + fn recv(&self, buf: &mut [u8]) -> io::Result { + unsafe { + ::cvt(read(self.as_sock() as c_int, buf.as_mut_ptr() as *mut _, buf.len())) + .map(|n| n as usize) + } + } + + #[cfg(unix)] + fn recv(&self, buf: &mut [u8]) -> io::Result { + unsafe { + ::cvt(recv(self.as_sock(), buf.as_mut_ptr() as *mut _, buf.len(), 0)) + .map(|n| n as usize) + } + } + + #[cfg(windows)] + fn recv(&self, buf: &mut [u8]) -> io::Result { + let len = ::std::cmp::min(buf.len(), c_int::max_value() as usize); + let buf = &mut buf[..len]; + unsafe { + ::cvt(recv(self.as_sock(), buf.as_mut_ptr() as *mut _, buf.len() as c_int, 0)) + .map(|n| n as usize) + } + } + + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + set_nonblocking(self.as_sock(), nonblocking) + } +} + +fn do_connect(sock: Socket, addr: A) -> io::Result<()> { + let err = io::Error::new(io::ErrorKind::Other, + "no socket addresses resolved"); + let addrs = try!(addr.to_socket_addrs()); + let sys = sys::Socket::from_inner(sock); + let sock = socket::Socket::from_inner(sys); + let ret = addrs.fold(Err(err), |prev, addr| { + prev.or_else(|_| sock.connect(&addr)) + }); + mem::forget(sock); + return ret +} + +#[cfg(target_os = "redox")] +fn set_nonblocking(sock: Socket, nonblocking: bool) -> io::Result<()> { + let mut flags = ::cvt(unsafe { + fcntl(sock as c_int, F_GETFL) + })?; + if nonblocking { + flags |= O_NONBLOCK; + } else { + flags &= !O_NONBLOCK; + } + ::cvt(unsafe { + fcntl(sock as c_int, F_SETFL, flags) + }).and(Ok(())) +} + +#[cfg(unix)] +fn set_nonblocking(sock: Socket, nonblocking: bool) -> io::Result<()> { + let mut nonblocking = nonblocking as c_ulong; + ::cvt(unsafe { + ioctl(sock, FIONBIO, &mut nonblocking) + }).map(|_| ()) +} + +#[cfg(windows)] +fn set_nonblocking(sock: Socket, nonblocking: bool) -> io::Result<()> { + let mut nonblocking = nonblocking as c_ulong; + ::cvt(unsafe { + ioctlsocket(sock, FIONBIO as c_int, &mut nonblocking) + }).map(|_| ()) +} + +#[cfg(target_os = "redox")] +fn ip2in_addr(ip: &Ipv4Addr) -> in_addr { + let oct = ip.octets(); + in_addr { + s_addr: ::hton(((oct[0] as u32) << 24) | + ((oct[1] as u32) << 16) | + ((oct[2] as u32) << 8) | + ((oct[3] as u32) << 0)), + } +} + +#[cfg(unix)] +fn ip2in_addr(ip: &Ipv4Addr) -> in_addr { + let oct = ip.octets(); + in_addr { + s_addr: ::hton(((oct[0] as u32) << 24) | + ((oct[1] as u32) << 16) | + ((oct[2] as u32) << 8) | + ((oct[3] as u32) << 0)), + } +} + +#[cfg(windows)] +fn ip2in_addr(ip: &Ipv4Addr) -> in_addr { + let oct = ip.octets(); + unsafe { + let mut S_un: in_addr_S_un = mem::zeroed(); + *S_un.S_addr_mut() = ::hton(((oct[0] as u32) << 24) | + ((oct[1] as u32) << 16) | + ((oct[2] as u32) << 8) | + ((oct[3] as u32) << 0)); + in_addr { + S_un: S_un, + } + } +} + +fn in_addr2ip(ip: &in_addr) -> Ipv4Addr { + let h_addr = c::in_addr_to_u32(ip); + + let a: u8 = (h_addr >> 24) as u8; + let b: u8 = (h_addr >> 16) as u8; + let c: u8 = (h_addr >> 8) as u8; + let d: u8 = (h_addr >> 0) as u8; + + Ipv4Addr::new(a,b,c,d) +} + +#[cfg(target_os = "android")] +fn to_ipv6mr_interface(value: u32) -> c_int { + value as c_int +} + +#[cfg(not(target_os = "android"))] +fn to_ipv6mr_interface(value: u32) -> c_uint { + value as c_uint +} + +fn ip2in6_addr(ip: &Ipv6Addr) -> in6_addr { + let mut ret: in6_addr = unsafe { mem::zeroed() }; + let seg = ip.segments(); + let bytes = [ + (seg[0] >> 8) as u8, + (seg[0] >> 0) as u8, + (seg[1] >> 8) as u8, + (seg[1] >> 0) as u8, + (seg[2] >> 8) as u8, + (seg[2] >> 0) as u8, + (seg[3] >> 8) as u8, + (seg[3] >> 0) as u8, + (seg[4] >> 8) as u8, + (seg[4] >> 0) as u8, + (seg[5] >> 8) as u8, + (seg[5] >> 0) as u8, + (seg[6] >> 8) as u8, + (seg[6] >> 0) as u8, + (seg[7] >> 8) as u8, + (seg[7] >> 0) as u8, + ]; + #[cfg(windows)] unsafe { *ret.u.Byte_mut() = bytes; } + #[cfg(not(windows))] { ret.s6_addr = bytes; } + + return ret +} + +impl TcpListenerExt for TcpListener { + fn set_ttl(&self, ttl: u32) -> io::Result<()> { + set_opt(self.as_sock(), IPPROTO_IP, IP_TTL, ttl as c_int) + } + + fn ttl(&self) -> io::Result { + get_opt::(self.as_sock(), IPPROTO_IP, IP_TTL) + .map(|b| b as u32) + } + + fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY, only_v6 as c_int) + } + + fn only_v6(&self) -> io::Result { + get_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY).map(int2bool) + } + + fn take_error(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_ERROR).map(int2err) + } + + fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + set_nonblocking(self.as_sock(), nonblocking) + } + + fn set_linger(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_LINGER, dur2linger(dur)) + } + + fn linger(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_LINGER).map(linger2dur) + } +} + +impl TcpBuilder { + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This is the same as [`TcpStreamExt::set_ttl`][other]. + /// + /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl + pub fn ttl(&self, ttl: u32) -> io::Result<&Self> { + set_opt(self.as_sock(), IPPROTO_IP, IP_TTL, ttl as c_int) + .map(|()| self) + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// This is the same as [`TcpStreamExt::set_only_v6`][other]. + /// + /// [other]: trait.TcpStreamExt.html#tymethod.set_only_v6 + pub fn only_v6(&self, only_v6: bool) -> io::Result<&Self> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY, only_v6 as c_int) + .map(|()| self) + } + + /// Set value for the `SO_REUSEADDR` option on this socket. + /// + /// This indicates that futher calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + pub fn reuse_address(&self, reuse: bool) -> io::Result<&Self> { + set_opt(self.as_sock(), SOL_SOCKET, SO_REUSEADDR, + reuse as c_int).map(|()| self) + } + + /// Check the `SO_REUSEADDR` option on this socket. + pub fn get_reuse_address(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_REUSEADDR).map(int2bool) + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_ERROR).map(int2err) + } + + /// Sets the linger option for this socket + fn set_linger(&self, dur: Option) -> io::Result<()> { + set_opt(self.as_sock(), SOL_SOCKET, SO_LINGER, dur2linger(dur)) + } + + /// Gets the linger option for this socket + fn linger(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_LINGER).map(linger2dur) + } +} + +impl UdpBuilder { + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This is the same as [`TcpStreamExt::set_ttl`][other]. + /// + /// [other]: trait.TcpStreamExt.html#tymethod.set_ttl + pub fn ttl(&self, ttl: u32) -> io::Result<&Self> { + set_opt(self.as_sock(), IPPROTO_IP, IP_TTL, ttl as c_int) + .map(|()| self) + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// This is the same as [`TcpStream::only_v6`][other]. + /// + /// [other]: struct.TcpBuilder.html#method.only_v6 + pub fn only_v6(&self, only_v6: bool) -> io::Result<&Self> { + set_opt(self.as_sock(), v(IPPROTO_IPV6), IPV6_V6ONLY, only_v6 as c_int) + .map(|()| self) + } + + /// Set value for the `SO_REUSEADDR` option on this socket. + /// + /// This is the same as [`TcpBuilder::reuse_address`][other]. + /// + /// [other]: struct.TcpBuilder.html#method.reuse_address + pub fn reuse_address(&self, reuse: bool) -> io::Result<&Self> { + set_opt(self.as_sock(), SOL_SOCKET, SO_REUSEADDR, + reuse as c_int).map(|()| self) + } + + /// Check the `SO_REUSEADDR` option on this socket. + pub fn get_reuse_address(&self) -> io::Result { + get_opt(self.as_sock(), SOL_SOCKET, SO_REUSEADDR).map(int2bool) + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result> { + get_opt(self.as_sock(), SOL_SOCKET, SO_ERROR).map(int2err) + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/lib.rs b/third_party/cargo/vendor/net2-0.2.33/src/lib.rs new file mode 100644 index 0000000..d5a3378 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/lib.rs @@ -0,0 +1,122 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Extensions to `std::net` networking types. +//! +//! This crate implements a number of extensions to the standard `std::net` +//! networking types, hopefully being slated for inclusion into the standard +//! library in the future. The goal of this crate is to expose all sorts of +//! cross-platform and platform-specific configuration options of UDP/TCP +//! sockets. System APIs are wrapped with as thin a layer as possible instead of +//! bundling multiple actions into one API call. +//! +//! More information about the design of this crate can be found in the +//! [associated rfc][rfc] +//! +//! [rfc]: https://github.com/rust-lang/rfcs/pull/1158 +//! +//! # Examples +//! +//! ```no_run +//! use net2::TcpBuilder; +//! +//! let tcp = TcpBuilder::new_v4().unwrap(); +//! tcp.reuse_address(true).unwrap() +//! .only_v6(false).unwrap(); +//! +//! let mut stream = tcp.connect("127.0.0.1:80").unwrap(); +//! +//! // use `stream` as a TcpStream +//! ``` + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico", + html_root_url = "https://doc.rust-lang.org/net2-rs")] +#![deny(missing_docs, warnings)] + + +#[cfg(any(target_os="redox", unix))] extern crate libc; + +#[cfg(windows)] extern crate winapi; + +#[macro_use] extern crate cfg_if; + +use std::io; +use std::ops::Neg; +use std::net::{ToSocketAddrs, SocketAddr}; + +use utils::{One, NetInt}; + +mod tcp; +mod udp; +mod socket; +mod ext; +mod utils; + +#[cfg(target_os="redox")] #[path = "sys/redox/mod.rs"] mod sys; +#[cfg(unix)] #[path = "sys/unix/mod.rs"] mod sys; +#[cfg(windows)] #[path = "sys/windows/mod.rs"] mod sys; +#[cfg(all(unix, not(any(target_os = "solaris"))))] pub mod unix; + +pub use tcp::TcpBuilder; +pub use udp::UdpBuilder; +pub use ext::{TcpStreamExt, TcpListenerExt, UdpSocketExt}; + +fn one_addr(tsa: T) -> io::Result { + let mut addrs = try!(tsa.to_socket_addrs()); + let addr = match addrs.next() { + Some(addr) => addr, + None => return Err(io::Error::new(io::ErrorKind::Other, + "no socket addresses could be resolved")) + }; + if addrs.next().is_none() { + Ok(addr) + } else { + Err(io::Error::new(io::ErrorKind::Other, + "more than one address resolved")) + } +} + +fn cvt>(t: T) -> io::Result { + let one: T = T::one(); + if t == -one { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +#[cfg(windows)] +fn cvt_win(t: T) -> io::Result { + if t == T::zero() { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +fn hton(i: I) -> I { i.to_be() } + +fn ntoh(i: I) -> I { I::from_be(i) } + +trait AsInner { + type Inner; + fn as_inner(&self) -> &Self::Inner; +} + +trait FromInner { + type Inner; + fn from_inner(inner: Self::Inner) -> Self; +} + +trait IntoInner { + type Inner; + fn into_inner(self) -> Self::Inner; +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/socket.rs b/third_party/cargo/vendor/net2-0.2.33/src/socket.rs new file mode 100644 index 0000000..385ed2d --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/socket.rs @@ -0,0 +1,144 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::io; +use std::mem; +use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; +#[cfg(target_os = "redox")] +use libc::c_int; +#[cfg(unix)] +use libc::c_int; +#[cfg(windows)] +use winapi::ctypes::c_int; + +use sys; +use sys::c; + +pub struct Socket { + inner: sys::Socket, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int) -> io::Result { + Ok(Socket { inner: try!(sys::Socket::new(family, ty)) }) + } + + pub fn bind(&self, addr: &SocketAddr) -> io::Result<()> { + let (addr, len) = addr2raw(addr); + unsafe { + ::cvt(c::bind(self.inner.raw(), addr, len as c::socklen_t)).map(|_| ()) + } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { + ::cvt(c::listen(self.inner.raw(), backlog)).map(|_| ()) + } + } + + pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { + let (addr, len) = addr2raw(addr); + unsafe { + ::cvt(c::connect(self.inner.raw(), addr, len)).map(|_| ()) + } + } + + pub fn getsockname(&self) -> io::Result { + unsafe { + let mut storage: c::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c::socklen_t; + try!(::cvt(c::getsockname(self.inner.raw(), + &mut storage as *mut _ as *mut _, + &mut len))); + raw2addr(&storage, len) + } + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.raw().fmt(f) + } +} + +impl ::AsInner for Socket { + type Inner = sys::Socket; + fn as_inner(&self) -> &sys::Socket { &self.inner } +} + +impl ::FromInner for Socket { + type Inner = sys::Socket; + fn from_inner(sock: sys::Socket) -> Socket { + Socket { inner: sock } + } +} + +impl ::IntoInner for Socket { + type Inner = sys::Socket; + fn into_inner(self) -> sys::Socket { self.inner } +} + +fn addr2raw(addr: &SocketAddr) -> (*const c::sockaddr, c::socklen_t) { + match *addr { + SocketAddr::V4(ref a) => { + (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t) + } + SocketAddr::V6(ref a) => { + (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t) + } + } +} + +fn raw2addr(storage: &c::sockaddr_storage, len: c::socklen_t) -> io::Result { + match storage.ss_family as c_int { + c::AF_INET => { + unsafe { + assert!(len as usize >= mem::size_of::()); + let sa = storage as *const _ as *const c::sockaddr_in; + let bits = c::sockaddr_in_u32(&(*sa)); + let ip = Ipv4Addr::new((bits >> 24) as u8, + (bits >> 16) as u8, + (bits >> 8) as u8, + bits as u8); + Ok(SocketAddr::V4(SocketAddrV4::new(ip, ::ntoh((*sa).sin_port)))) + } + } + c::AF_INET6 => { + unsafe { + assert!(len as usize >= mem::size_of::()); + + let sa = storage as *const _ as *const c::sockaddr_in6; + #[cfg(windows)] let arr = (*sa).sin6_addr.u.Byte(); + #[cfg(not(windows))] let arr = (*sa).sin6_addr.s6_addr; + + let ip = Ipv6Addr::new( + (arr[0] as u16) << 8 | (arr[1] as u16), + (arr[2] as u16) << 8 | (arr[3] as u16), + (arr[4] as u16) << 8 | (arr[5] as u16), + (arr[6] as u16) << 8 | (arr[7] as u16), + (arr[8] as u16) << 8 | (arr[9] as u16), + (arr[10] as u16) << 8 | (arr[11] as u16), + (arr[12] as u16) << 8 | (arr[13] as u16), + (arr[14] as u16) << 8 | (arr[15] as u16), + ); + + #[cfg(windows)] let sin6_scope_id = *(*sa).u.sin6_scope_id(); + #[cfg(not(windows))] let sin6_scope_id = (*sa).sin6_scope_id; + + Ok(SocketAddr::V6(SocketAddrV6::new(ip, + ::ntoh((*sa).sin6_port), + (*sa).sin6_flowinfo, + sin6_scope_id))) + } + } + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid argument")), + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/impls.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/impls.rs new file mode 100644 index 0000000..388ec69 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/impls.rs @@ -0,0 +1,43 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::unix::io::{FromRawFd, AsRawFd}; + +use {TcpBuilder, UdpBuilder, FromInner, AsInner}; +use socket::Socket; +use sys; + +impl FromRawFd for TcpBuilder { + unsafe fn from_raw_fd(fd: usize) -> TcpBuilder { + let sock = sys::Socket::from_inner(fd); + TcpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawFd for TcpBuilder { + fn as_raw_fd(&self) -> usize { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() as usize + } +} + +impl FromRawFd for UdpBuilder { + unsafe fn from_raw_fd(fd: usize) -> UdpBuilder { + let sock = sys::Socket::from_inner(fd); + UdpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawFd for UdpBuilder { + fn as_raw_fd(&self) -> usize { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() as usize + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/mod.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/mod.rs new file mode 100644 index 0000000..9fd9b1f --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/redox/mod.rs @@ -0,0 +1,81 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +use std::io; +use std::mem; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::os::unix::io::FromRawFd; +use libc::{self, c_int}; + +mod impls; + +pub mod c { + pub use libc::*; + + pub fn sockaddr_in_u32(sa: &sockaddr_in) -> u32 { + ::ntoh((*sa).sin_addr.s_addr) + } + + pub fn in_addr_to_u32(addr: &in_addr) -> u32 { + ::ntoh(addr.s_addr) + } +} + +pub struct Socket { + fd: c_int, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int) -> io::Result { + unsafe { + let fd = ::cvt(libc::socket(family, ty, 0))?; + let mut flags = ::cvt(libc::fcntl(fd, libc::F_GETFD))?; + flags |= libc::O_CLOEXEC; + ::cvt(libc::fcntl(fd, libc::F_SETFD, flags))?; + Ok(Socket { fd: fd }) + } + } + + pub fn raw(&self) -> c_int { self.fd } + + fn into_fd(self) -> c_int { + let fd = self.fd; + mem::forget(self); + fd + } + + pub fn into_tcp_listener(self) -> TcpListener { + unsafe { TcpListener::from_raw_fd(self.into_fd() as usize) } + } + + pub fn into_tcp_stream(self) -> TcpStream { + unsafe { TcpStream::from_raw_fd(self.into_fd() as usize) } + } + + pub fn into_udp_socket(self) -> UdpSocket { + unsafe { UdpSocket::from_raw_fd(self.into_fd() as usize) } + } +} + +impl ::FromInner for Socket { + type Inner = usize; + fn from_inner(fd: usize) -> Socket { + Socket { fd: fd as c_int } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/impls.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/impls.rs new file mode 100644 index 0000000..95c2fb8 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/impls.rs @@ -0,0 +1,44 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::unix::io::{FromRawFd, AsRawFd}; +use libc::c_int; + +use {TcpBuilder, UdpBuilder, FromInner, AsInner}; +use socket::Socket; +use sys; + +impl FromRawFd for TcpBuilder { + unsafe fn from_raw_fd(fd: c_int) -> TcpBuilder { + let sock = sys::Socket::from_inner(fd); + TcpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawFd for TcpBuilder { + fn as_raw_fd(&self) -> c_int { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() + } +} + +impl FromRawFd for UdpBuilder { + unsafe fn from_raw_fd(fd: c_int) -> UdpBuilder { + let sock = sys::Socket::from_inner(fd); + UdpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawFd for UdpBuilder { + fn as_raw_fd(&self) -> c_int { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/mod.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/mod.rs new file mode 100644 index 0000000..e13f97c --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/unix/mod.rs @@ -0,0 +1,104 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +use std::io; +use std::mem; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::os::unix::io::FromRawFd; +use libc::{self, c_int}; +#[cfg(not(any(target_os = "solaris", target_os = "emscripten")))] +use libc::{ioctl, FIOCLEX}; + +mod impls; + +pub mod c { + pub use libc::*; + + pub fn sockaddr_in_u32(sa: &sockaddr_in) -> u32 { + ::ntoh((*sa).sin_addr.s_addr) + } + + pub fn in_addr_to_u32(addr: &in_addr) -> u32 { + ::ntoh(addr.s_addr) + } +} + +pub struct Socket { + fd: c_int, +} + +impl Socket { + #[cfg(not(any(target_os = "solaris", target_os = "emscripten")))] + pub fn new(family: c_int, ty: c_int) -> io::Result { + unsafe { + // Linux >2.6.26 overloads the type argument to accept SOCK_CLOEXEC, + // avoiding a race with another thread running fork/exec between + // socket() and ioctl() + #[cfg(any(target_os = "linux", target_os = "android"))] + match ::cvt(libc::socket(family, ty | libc::SOCK_CLOEXEC, 0)) { + Ok(fd) => return Ok(Socket { fd: fd }), + // Older versions of Linux return EINVAL; fall back to ioctl + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} + Err(e) => return Err(e), + } + + let fd = try!(::cvt(libc::socket(family, ty, 0))); + ioctl(fd, FIOCLEX); + Ok(Socket { fd: fd }) + } + } + + // ioctl(FIOCLEX) is not supported by Solaris/Illumos or emscripten, + // use fcntl(FD_CLOEXEC) instead + #[cfg(any(target_os = "solaris", target_os = "emscripten"))] + pub fn new(family: c_int, ty: c_int) -> io::Result { + unsafe { + let fd = try!(::cvt(libc::socket(family, ty, 0))); + libc::fcntl(fd, libc::FD_CLOEXEC); + Ok(Socket { fd: fd }) + } + } + + pub fn raw(&self) -> c_int { self.fd } + + fn into_fd(self) -> c_int { + let fd = self.fd; + mem::forget(self); + fd + } + + pub fn into_tcp_listener(self) -> TcpListener { + unsafe { TcpListener::from_raw_fd(self.into_fd()) } + } + + pub fn into_tcp_stream(self) -> TcpStream { + unsafe { TcpStream::from_raw_fd(self.into_fd()) } + } + + pub fn into_udp_socket(self) -> UdpSocket { + unsafe { UdpSocket::from_raw_fd(self.into_fd()) } + } +} + +impl ::FromInner for Socket { + type Inner = c_int; + fn from_inner(fd: c_int) -> Socket { + Socket { fd: fd } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/impls.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/impls.rs new file mode 100644 index 0000000..48e787c --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/impls.rs @@ -0,0 +1,44 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::windows::io::{FromRawSocket, RawSocket, AsRawSocket}; +use winapi::um::winsock2::SOCKET; + +use {TcpBuilder, UdpBuilder, FromInner, AsInner}; +use socket::Socket; +use sys; + +impl FromRawSocket for TcpBuilder { + unsafe fn from_raw_socket(fd: RawSocket) -> TcpBuilder { + let sock = sys::Socket::from_inner(fd as SOCKET); + TcpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawSocket for TcpBuilder { + fn as_raw_socket(&self) -> RawSocket { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() as RawSocket + } +} + +impl FromRawSocket for UdpBuilder { + unsafe fn from_raw_socket(fd: RawSocket) -> UdpBuilder { + let sock = sys::Socket::from_inner(fd as SOCKET); + UdpBuilder::from_inner(Socket::from_inner(sock)) + } +} + +impl AsRawSocket for UdpBuilder { + fn as_raw_socket(&self) -> RawSocket { + // TODO: this unwrap() is very bad + self.as_inner().borrow().as_ref().unwrap().as_inner().raw() as RawSocket + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/mod.rs b/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/mod.rs new file mode 100644 index 0000000..b2da96d --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/sys/windows/mod.rs @@ -0,0 +1,124 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +use std::io; +use std::mem; +use std::net::{TcpListener, TcpStream, UdpSocket}; +use std::os::windows::io::{RawSocket, FromRawSocket}; +use std::sync::{Once, ONCE_INIT}; + +const HANDLE_FLAG_INHERIT: DWORD = 0x00000001; + +pub mod c { + pub use winapi::ctypes::*; + pub use winapi::um::handleapi::*; + pub use winapi::um::winbase::*; + pub use winapi::um::winsock2::*; + pub use winapi::um::ws2tcpip::*; + + pub use winapi::shared::inaddr::*; + pub use winapi::shared::in6addr::*; + pub use winapi::shared::minwindef::*; + pub use winapi::shared::ntdef::*; + pub use winapi::shared::ws2def::*; + pub use winapi::shared::ws2def::{SOCK_STREAM, SOCK_DGRAM}; + pub use winapi::shared::ws2def::SOCKADDR as sockaddr; + pub use winapi::shared::ws2def::SOCKADDR_STORAGE as sockaddr_storage; + pub use winapi::shared::ws2def::SOCKADDR_IN as sockaddr_in; + pub use winapi::shared::ws2ipdef::*; + pub use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH as sockaddr_in6; + pub use winapi::shared::ws2ipdef::IP_MREQ as ip_mreq; + pub use winapi::shared::ws2ipdef::IPV6_MREQ as ipv6_mreq; + + pub fn sockaddr_in_u32(sa: &sockaddr_in) -> u32 { + ::ntoh(unsafe { *sa.sin_addr.S_un.S_addr() }) + } + + pub fn in_addr_to_u32(addr: &in_addr) -> u32 { + ::ntoh(unsafe { *addr.S_un.S_addr() }) + } +} + +use self::c::*; + +mod impls; + +fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| { + // Initialize winsock through the standard library by just creating a + // dummy socket. Whether this is successful or not we drop the result as + // libstd will be sure to have initialized winsock. + let _ = UdpSocket::bind("127.0.0.1:34254"); + }); +} + +pub struct Socket { + socket: SOCKET, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int) -> io::Result { + init(); + let socket = try!(unsafe { + match WSASocketW(family, ty, 0, 0 as *mut _, 0, + WSA_FLAG_OVERLAPPED) { + INVALID_SOCKET => Err(io::Error::last_os_error()), + n => Ok(Socket { socket: n }), + } + }); + try!(socket.set_no_inherit()); + Ok(socket) + } + + pub fn raw(&self) -> SOCKET { self.socket } + + fn into_socket(self) -> SOCKET { + let socket = self.socket; + mem::forget(self); + socket + } + + pub fn into_tcp_listener(self) -> TcpListener { + unsafe { TcpListener::from_raw_socket(self.into_socket() as RawSocket) } + } + + pub fn into_tcp_stream(self) -> TcpStream { + unsafe { TcpStream::from_raw_socket(self.into_socket() as RawSocket) } + } + + pub fn into_udp_socket(self) -> UdpSocket { + unsafe { UdpSocket::from_raw_socket(self.into_socket() as RawSocket) } + } + + fn set_no_inherit(&self) -> io::Result<()> { + ::cvt_win(unsafe { + SetHandleInformation(self.socket as HANDLE, HANDLE_FLAG_INHERIT, 0) + }).map(|_| ()) + } +} + +impl ::FromInner for Socket { + type Inner = SOCKET; + fn from_inner(socket: SOCKET) -> Socket { + Socket { socket: socket } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = closesocket(self.socket); + } + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/tcp.rs b/third_party/cargo/vendor/net2-0.2.33/src/tcp.rs new file mode 100644 index 0000000..5a535db --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/tcp.rs @@ -0,0 +1,161 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cell::RefCell; +use std::io; +use std::net::{SocketAddr, ToSocketAddrs, TcpListener, TcpStream}; +use std::fmt; + +use IntoInner; +use socket::Socket; +use sys::c; + +/// An "in progress" TCP socket which has not yet been connected or listened. +/// +/// Allows configuration of a socket before one of these operations is executed. +pub struct TcpBuilder { + socket: RefCell>, +} + +impl TcpBuilder { + /// Constructs a new TcpBuilder with the `AF_INET` domain, the `SOCK_STREAM` + /// type, and with a protocol argument of 0. + /// + /// Note that passing other kinds of flags or arguments can be done through + /// the `FromRaw{Fd,Socket}` implementation. + pub fn new_v4() -> io::Result { + Socket::new(c::AF_INET, c::SOCK_STREAM).map(::FromInner::from_inner) + } + + /// Constructs a new TcpBuilder with the `AF_INET6` domain, the `SOCK_STREAM` + /// type, and with a protocol argument of 0. + /// + /// Note that passing other kinds of flags or arguments can be done through + /// the `FromRaw{Fd,Socket}` implementation. + pub fn new_v6() -> io::Result { + Socket::new(c::AF_INET6, c::SOCK_STREAM).map(::FromInner::from_inner) + } + + /// Binds this socket to the specified address. + /// + /// This function directly corresponds to the bind(2) function on Windows + /// and Unix. + pub fn bind(&self, addr: T) -> io::Result<&TcpBuilder> + where T: ToSocketAddrs + { + self.with_socket(|sock| { + let addr = try!(::one_addr(addr)); + sock.bind(&addr) + }).map(|()| self) + } + + /// Mark a socket as ready to accept incoming connection requests using + /// accept() + /// + /// This function directly corresponds to the listen(2) function on Windows + /// and Unix. + /// + /// An error will be returned if `listen` or `connect` has already been + /// called on this builder. + pub fn listen(&self, backlog: i32) -> io::Result { + self.with_socket(|sock| { + sock.listen(backlog) + }).and_then(|()| { + self.to_tcp_listener() + }) + } + + /// Initiate a connection on this socket to the specified address. + /// + /// This function directly corresponds to the connect(2) function on Windows + /// and Unix. + /// + /// An error will be returned if `listen` or `connect` has already been + /// called on this builder. + pub fn connect(&self, addr: T) -> io::Result + where T: ToSocketAddrs + { + self.with_socket(|sock| { + let err = io::Error::new(io::ErrorKind::Other, + "no socket addresses resolved"); + try!(addr.to_socket_addrs()).fold(Err(err), |prev, addr| { + prev.or_else(|_| sock.connect(&addr)) + }) + }).and_then(|()| { + self.to_tcp_stream() + }) + } + + /// Converts this builder into a `TcpStream` + /// + /// This function will consume the internal socket and return it re-wrapped + /// as a `TcpStream`. An error will be returned if the internal socket has + /// already been consumed from a successful call to `connect`, `listen`, + /// etc. + pub fn to_tcp_stream(&self) -> io::Result { + self.socket.borrow_mut().take().map(|s| s.into_inner().into_tcp_stream()) + .ok_or(io::Error::new(io::ErrorKind::Other, + "socket has already been consumed")) + } + + /// Converts this builder into a `TcpListener` + /// + /// This function will consume the internal socket and return it re-wrapped + /// as a `TcpListener`. An error will be returned if the internal socket has + /// already been consumed from a successful call to `connect`, `listen`, + /// etc. + pub fn to_tcp_listener(&self) -> io::Result { + self.socket.borrow_mut().take() + .map(|s| s.into_inner().into_tcp_listener()) + .ok_or(io::Error::new(io::ErrorKind::Other, + "socket has already been consumed")) + } + + /// Returns the address of the local half of this TCP socket. + /// + /// An error will be returned if `listen` or `connect` has already been + /// called on this builder. + pub fn local_addr(&self) -> io::Result { + match *self.socket.borrow() { + Some(ref s) => s.getsockname(), + None => Err(io::Error::new(io::ErrorKind::Other, + "builder has already finished its socket")), + } + } + + fn with_socket(&self, f: F) -> io::Result<()> + where F: FnOnce(&Socket) -> io::Result<()> + { + match *self.socket.borrow() { + Some(ref s) => f(s), + None => Err(io::Error::new(io::ErrorKind::Other, + "builder has already finished its socket")), + } + } +} + +impl fmt::Debug for TcpBuilder { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "TcpBuilder {{ socket: {:?} }}", + self.socket.borrow().as_ref().unwrap()) + } +} + +impl ::AsInner for TcpBuilder { + type Inner = RefCell>; + fn as_inner(&self) -> &RefCell> { &self.socket } +} + +impl ::FromInner for TcpBuilder { + type Inner = Socket; + fn from_inner(sock: Socket) -> TcpBuilder { + TcpBuilder { socket: RefCell::new(Some(sock)) } + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/udp.rs b/third_party/cargo/vendor/net2-0.2.33/src/udp.rs new file mode 100644 index 0000000..d061ab5 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/udp.rs @@ -0,0 +1,89 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cell::RefCell; +use std::fmt; +use std::io; +use std::net::{ToSocketAddrs, UdpSocket}; + +use IntoInner; +use socket::Socket; +use sys::c; + +/// An "in progress" UDP socket which has not yet been connected. +/// +/// Allows configuration of a socket before the socket is connected. +pub struct UdpBuilder { + socket: RefCell>, +} + +impl UdpBuilder { + /// Constructs a new UdpBuilder with the `AF_INET` domain, the `SOCK_DGRAM` + /// type, and with a protocol argument of 0. + /// + /// Note that passing other kinds of flags or arguments can be done through + /// the `FromRaw{Fd,Socket}` implementation. + pub fn new_v4() -> io::Result { + Socket::new(c::AF_INET, c::SOCK_DGRAM).map(::FromInner::from_inner) + } + + /// Constructs a new UdpBuilder with the `AF_INET6` domain, the `SOCK_DGRAM` + /// type, and with a protocol argument of 0. + /// + /// Note that passing other kinds of flags or arguments can be done through + /// the `FromRaw{Fd,Socket}` implementation. + pub fn new_v6() -> io::Result { + Socket::new(c::AF_INET6, c::SOCK_DGRAM).map(::FromInner::from_inner) + } + + /// Binds this socket to the specified address. + /// + /// This function directly corresponds to the bind(2) function on Windows + /// and Unix. + pub fn bind(&self, addr: T) -> io::Result + where T: ToSocketAddrs + { + try!(self.with_socket(|sock| { + let addr = try!(::one_addr(addr)); + sock.bind(&addr) + })); + Ok(self.socket.borrow_mut().take().unwrap().into_inner().into_udp_socket()) + } + + fn with_socket(&self, f: F) -> io::Result<()> + where F: FnOnce(&Socket) -> io::Result<()> + { + match *self.socket.borrow() { + Some(ref s) => f(s), + None => Err(io::Error::new(io::ErrorKind::Other, + "builder has already finished its socket")), + } + } +} + +impl fmt::Debug for UdpBuilder { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "UdpBuilder {{ socket: {:?} }}", + self.socket.borrow().as_ref().unwrap()) + } +} + +impl ::AsInner for UdpBuilder { + type Inner = RefCell>; + fn as_inner(&self) -> &RefCell> { &self.socket } +} + +impl ::FromInner for UdpBuilder { + type Inner = Socket; + fn from_inner(sock: Socket) -> UdpBuilder { + UdpBuilder { socket: RefCell::new(Some(sock)) } + } +} + diff --git a/third_party/cargo/vendor/net2-0.2.33/src/unix.rs b/third_party/cargo/vendor/net2-0.2.33/src/unix.rs new file mode 100644 index 0000000..21dcb2a --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/unix.rs @@ -0,0 +1,57 @@ +//! Unix-specific extensions to the `std::net` types. + +use std::io; +use sys::c::{self, c_int}; + +use {TcpBuilder, UdpBuilder}; +use ext::{self, AsSock}; + +/// Unix-specific extensions for the `TcpBuilder` type in this library. +pub trait UnixTcpBuilderExt { + /// Set value for the `SO_REUSEPORT` option on this socket. + /// + /// This indicates that futher calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + fn reuse_port(&self, reuse: bool) -> io::Result<&Self>; + + /// Check the value of the `SO_REUSEPORT` option on this socket. + fn get_reuse_port(&self) -> io::Result; +} + +impl UnixTcpBuilderExt for TcpBuilder { + fn reuse_port(&self, reuse: bool) -> io::Result<&Self> { + ext::set_opt(self.as_sock(), c::SOL_SOCKET, c::SO_REUSEPORT, + reuse as c_int).map(|()| self) + } + + fn get_reuse_port(&self) -> io::Result { + ext::get_opt(self.as_sock(), c::SOL_SOCKET, c::SO_REUSEPORT) + .map(ext::int2bool) + } +} + +/// Unix-specific extensions for the `UdpBuilder` type in this library. +pub trait UnixUdpBuilderExt { + /// Set value for the `SO_REUSEPORT` option on this socket. + /// + /// This indicates that futher calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + fn reuse_port(&self, reuse: bool) -> io::Result<&Self>; + + /// Check the value of the `SO_REUSEPORT` option on this socket. + fn get_reuse_port(&self) -> io::Result; +} + +impl UnixUdpBuilderExt for UdpBuilder { + fn reuse_port(&self, reuse: bool) -> io::Result<&Self> { + ext::set_opt(self.as_sock(), c::SOL_SOCKET, c::SO_REUSEPORT, + reuse as c_int).map(|()| self) + } + + fn get_reuse_port(&self) -> io::Result { + ext::get_opt(self.as_sock(), c::SOL_SOCKET, c::SO_REUSEPORT) + .map(ext::int2bool) + } +} diff --git a/third_party/cargo/vendor/net2-0.2.33/src/utils.rs b/third_party/cargo/vendor/net2-0.2.33/src/utils.rs new file mode 100644 index 0000000..21fe9d6 --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/src/utils.rs @@ -0,0 +1,51 @@ +// Copyright 2015 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 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + + +#[doc(hidden)] +pub trait NetInt { + fn from_be(i: Self) -> Self; + fn to_be(&self) -> Self; +} +macro_rules! doit { + ($($t:ident)*) => ($(impl NetInt for $t { + fn from_be(i: Self) -> Self { <$t>::from_be(i) } + fn to_be(&self) -> Self { <$t>::to_be(*self) } + })*) +} +doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + +#[doc(hidden)] +pub trait One { + fn one() -> Self; +} + +macro_rules! one { + ($($t:ident)*) => ($( + impl One for $t { fn one() -> $t { 1 } } + )*) +} + +one! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + + +#[doc(hidden)] +pub trait Zero { + fn zero() -> Self; +} + +macro_rules! zero { + ($($t:ident)*) => ($( + impl Zero for $t { fn zero() -> $t { 0 } } + )*) +} + +zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + diff --git a/third_party/cargo/vendor/net2-0.2.33/tests/all.rs b/third_party/cargo/vendor/net2-0.2.33/tests/all.rs new file mode 100644 index 0000000..9413c0e --- /dev/null +++ b/third_party/cargo/vendor/net2-0.2.33/tests/all.rs @@ -0,0 +1,45 @@ +extern crate net2; + +use std::net::{TcpStream, IpAddr, Ipv4Addr, Ipv6Addr}; +use std::io::prelude::*; +use std::thread; + +use net2::TcpBuilder; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with: {}", stringify!($e), e), + }) +} + +#[test] +fn smoke_build_listener() { + let b = t!(TcpBuilder::new_v4()); + t!(b.bind("127.0.0.1:0")); + + let addr = t!(b.local_addr()); + assert_eq!(addr.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))); + + let listener = t!(b.listen(200)); + + let t = thread::spawn(move || { + let mut s = t!(listener.accept()).0; + let mut b = [0; 4]; + t!(s.read(&mut b)); + assert_eq!(b, [1, 2, 3, 0]); + }); + + let mut stream = t!(TcpStream::connect(&addr)); + t!(stream.write(&[1,2,3])); + t.join().unwrap(); +} + +#[test] +fn smoke_build_listener_v6() { + let b = t!(TcpBuilder::new_v6()); + t!(b.bind("::1:0")); + + let addr = t!(b.local_addr()); + assert_eq!(addr.ip(), IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1))); +} diff --git a/third_party/cargo/vendor/nodrop-0.1.14/.cargo-checksum.json b/third_party/cargo/vendor/nodrop-0.1.14/.cargo-checksum.json deleted file mode 100644 index 69622d2..0000000 --- a/third_party/cargo/vendor/nodrop-0.1.14/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"e43d9892df1d8d932b5f5d27f303f1a302b550b5a37b9b8fb1b107aa5273b8af","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0245ee104228a100ce5fceecf43e25faae450494d9173f43fd94c27d69fdac13","README.rst":"3a12c4caf645c40c7b9608c150c7e2bee50eafd114b802329f508a489d9e175b","src/lib.rs":"3e00173987c5fc462956c36f492426cbf0d900a2634c6b4e47580d6b142273ee"},"package":"72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"} \ No newline at end of file diff --git a/third_party/cargo/vendor/nodrop-0.1.14/Cargo.toml b/third_party/cargo/vendor/nodrop-0.1.14/Cargo.toml deleted file mode 100644 index 716eeda..0000000 --- a/third_party/cargo/vendor/nodrop-0.1.14/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "nodrop" -version = "0.1.14" -authors = ["bluss"] -description = "A wrapper type to inhibit drop (destructor).\n\n***Deprecated: Use ManuallyDrop or MaybeUninit instead!***\n" -documentation = "https://docs.rs/nodrop/" -keywords = [] -categories = ["rust-patterns"] -license = "MIT/Apache-2.0" -repository = "https://github.com/bluss/arrayvec" -[package.metadata.release] -no-dev-version = true -tag-name = "nodrop-{{version}}" -[dependencies.nodrop-union] -version = "0.1.8" -optional = true - -[features] -default = ["std"] -std = [] -use_needs_drop = [] -use_union = ["nodrop-union"] -[badges.maintenance] -status = "deprecated" diff --git a/third_party/cargo/vendor/nodrop-0.1.14/LICENSE-MIT b/third_party/cargo/vendor/nodrop-0.1.14/LICENSE-MIT deleted file mode 100644 index 2c8f27d..0000000 --- a/third_party/cargo/vendor/nodrop-0.1.14/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) Ulrik Sverdrup "bluss" 2015-2017 - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/nodrop-0.1.14/README.rst b/third_party/cargo/vendor/nodrop-0.1.14/README.rst deleted file mode 100644 index 3886ba6..0000000 --- a/third_party/cargo/vendor/nodrop-0.1.14/README.rst +++ /dev/null @@ -1,71 +0,0 @@ - -nodrop -====== - -Recent Changes (nodrop) ------------------------ - -- 0.1.14 - - - Mark nodrop deprecated - - With the release of arrayvec 0.5, nodrop is unused. - - With the release of Rust 1.36 and MaybeUninit, nodrop has no - purpose (but for older Rust releases). - -- 0.1.13 - - - Update to include license files in the crate by @ignatenkobrain - -- 0.1.12 - - - Remove dependency on crate odds. - -- 0.1.11 - - - Remove erronous assertion in test (#77) - -- 0.1.10 - - - Update for stable ``needs_drop`` (Rust 1.21, was nightly only) - -- 0.1.9 - - - Fix issue in recent nightly where ``repr(u8)`` did not work. Use - a better way to get rid of the enum layout optimization. - -- 0.1.8 - - - Add crate feature ``use_union`` that uses untagged unions to implement NoDrop. - Finally we have an implementation without hacks, without a runtime flag, - and without an actual ``Drop`` impl (which was needed to suppress drop). - The crate feature requires nightly and is unstable. - -- 0.1.7 - - - Remove crate feature ``no_drop_flag``, because it doesn't compile on nightly - anymore. Drop flags are gone anyway! - -- 0.1.6 - - - Add feature std, which you can opt out of to use ``no_std``. - -- 0.1.5 - - - Added crate feature ``use_needs_drop`` which is a nightly-only - optimization, which skips overwriting if the inner value does not need - drop. - -License -======= - -Dual-licensed to be compatible with the Rust project. - -Licensed under the Apache License, Version 2.0 -http://www.apache.org/licenses/LICENSE-2.0 or the MIT license -http://opensource.org/licenses/MIT, at your -option. This file may not be copied, modified, or distributed -except according to those terms. - - diff --git a/third_party/cargo/vendor/nodrop-0.1.14/src/lib.rs b/third_party/cargo/vendor/nodrop-0.1.14/src/lib.rs deleted file mode 100644 index a1a1547..0000000 --- a/third_party/cargo/vendor/nodrop-0.1.14/src/lib.rs +++ /dev/null @@ -1,189 +0,0 @@ -//! A wrapper type to inhibit drop (destructor). -//! -//! ***Deprecated: Use ManuallyDrop or MaybeUninit instead!*** -//! -//! The **nodrop** crate has the following cargo feature flags: -//! -//! - `std` -//! - Optional, enabled by default -//! - Use libstd -//! - `use_needs_drop` -//! - Optional -//! - Requires Rust 1.21 -//! - Use `needs_drop` to skip overwriting if not necessary -//! - `use_union` -//! - Optional -//! - Requires nightly channel -//! - Using untagged union, finally we have an implementation of `NoDrop` without hacks, -//! for example the fact that `NoDrop` never has a destructor anymore. -//! - -#![cfg_attr(not(any(test, feature="std")), no_std)] -#[cfg(not(any(test, feature="std")))] -extern crate core as std; - -#[cfg(feature = "use_union")] -extern crate nodrop_union as imp; - -pub use imp::NoDrop; - - -#[cfg(not(feature = "use_union"))] -mod imp { - use std::ptr; - use std::mem; - use std::ops::{Deref, DerefMut}; - - /// repr(u8) - Make sure the non-nullable pointer optimization does not occur! - #[repr(u8)] - enum Flag { - Alive(T), - // Dummy u8 field below, again to beat the enum layout opt - Dropped(u8), - } - - - /// A type holding **T** that will not call its destructor on drop - pub struct NoDrop(Flag); - - impl NoDrop { - /// Create a new **NoDrop**. - #[inline] - pub fn new(value: T) -> NoDrop { - NoDrop(Flag::Alive(value)) - } - - /// Extract the inner value. - /// - /// Once extracted, the value can of course drop again. - #[inline] - pub fn into_inner(mut self) -> T { - let inner = unsafe { - ptr::read(&mut *self) - }; - // skip Drop, so we don't even have to overwrite - mem::forget(self); - inner - } - } - - #[cfg(not(feature = "use_needs_drop"))] - #[inline] - fn needs_drop() -> bool { - true - } - - #[cfg(feature = "use_needs_drop")] - #[inline] - fn needs_drop() -> bool { - unsafe { - ::std::mem::needs_drop::() - } - } - - impl Drop for NoDrop { - fn drop(&mut self) { - if needs_drop::() { - // inhibit drop - unsafe { - ptr::write(&mut self.0, Flag::Dropped(0)); - } - } - } - } - - impl Deref for NoDrop { - type Target = T; - - // Use type invariant, always Flag::Alive. - #[inline] - fn deref(&self) -> &T { - match self.0 { - Flag::Alive(ref inner) => inner, - _ => unsafe { debug_assert_unreachable() } - } - } - } - - impl DerefMut for NoDrop { - // Use type invariant, always Flag::Alive. - #[inline] - fn deref_mut(&mut self) -> &mut T { - match self.0 { - Flag::Alive(ref mut inner) => inner, - _ => unsafe { debug_assert_unreachable() } - } - } - } - - #[cfg(test)] - #[test] - fn test_no_nonnullable_opt() { - // Make sure `Flag` does not apply the non-nullable pointer optimization - // as Option would do. - assert!(mem::size_of::>() > mem::size_of::<&i32>()); - assert!(mem::size_of::>>() > mem::size_of::>()); - } - - // copying this code saves us microcrate deps - #[inline] - unsafe fn debug_assert_unreachable() -> ! { - debug_assert!(false, "Reached unreachable section: this is a bug!"); - enum Void { } - match *(1 as *const Void) { } - } -} - -#[cfg(test)] -mod tests { - use super::NoDrop; - - #[test] - fn test_drop() { - use std::cell::Cell; - - let flag = &Cell::new(0); - - struct Bump<'a>(&'a Cell); - - impl<'a> Drop for Bump<'a> { - fn drop(&mut self) { - let n = self.0.get(); - self.0.set(n + 1); - } - } - - { - let _ = NoDrop::new([Bump(flag), Bump(flag)]); - } - assert_eq!(flag.get(), 0); - - // test something with the nullable pointer optimization - flag.set(0); - - { - let mut array = NoDrop::new(Vec::new()); - array.push(vec![Bump(flag)]); - array.push(vec![Bump(flag), Bump(flag)]); - array.push(vec![]); - array.push(vec![Bump(flag)]); - drop(array.pop()); - assert_eq!(flag.get(), 1); - drop(array.pop()); - assert_eq!(flag.get(), 1); - drop(array.pop()); - assert_eq!(flag.get(), 3); - } - - // last one didn't drop. - assert_eq!(flag.get(), 3); - - flag.set(0); - { - let array = NoDrop::new(Bump(flag)); - array.into_inner(); - assert_eq!(flag.get(), 1); - } - assert_eq!(flag.get(), 1); - } -} diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/.cargo-checksum.json b/third_party/cargo/vendor/num_cpus-1.12.0/.cargo-checksum.json deleted file mode 100644 index 88ed1f2..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"a2123abd3878019668c6afc950368eec5ef43340e6b3ac46b8ab0d8c453d484c","CONTRIBUTING.md":"2390961aab1bba026135338da1216b6cc828dfaeed9357d9c155c55a252d3efb","Cargo.toml":"fa31772b1643d482a785c1b78b581a377d408ffe9715c8b2d45d80f6c7d09f62","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0593d22d122d4bfec6407115e3907546312976f75473417aaa4c57ecd2095ae6","README.md":"12451d6905fe9cdac206410de8071b562e5ea936b6e55a19ac97982831a0fcdb","examples/values.rs":"46c833324b7339d359054c4f8e8284259e860df206c552c63b5893ade59c16a6","src/lib.rs":"f0f45c2b20071c0cd947da3664330d696c0d33ed50352e182ea2ff4792a663b9"},"package":"46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6"} \ No newline at end of file diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/CHANGELOG.md b/third_party/cargo/vendor/num_cpus-1.12.0/CHANGELOG.md deleted file mode 100644 index 5c433df..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/CHANGELOG.md +++ /dev/null @@ -1,125 +0,0 @@ -## v1.12.0 - -#### Fixes - -- fix `get` on OpenBSD to ignore offline CPUs -- implement `get_physical` on OpenBSD - -## v1.11.1 - -#### Fixes - -- Use `mem::zeroed` instead of `mem::uninitialized`. - -## v1.11.0 - -#### Features - -- add `hermit` target OS support -- removes `bitrig` support - -#### Fixes - -- fix `get_physical` count with AMD hyperthreading. - -## v1.10.1 - -#### Fixes - -- improve `haiku` CPU detection - -## v1.10.0 - -#### Features - -- add `illumos` target OS support -- add default fallback if target is unknown to `1` - -## v1.9.0 - -#### Features - -- add `sgx` target env support - -## v1.8.0 - -#### Features - -- add `wasm-unknown-unknown` target support - -## v1.7.0 - -#### Features - -- add `get_physical` support for macOS - -#### Fixes - -- use `_SC_NPROCESSORS_CONF` on Unix targets - -### v1.6.2 - -#### Fixes - -- revert 1.6.1 for now - -### v1.6.1 - -#### Fixes - -- fixes sometimes incorrect num on Android/ARM Linux (#45) - -## v1.6.0 - -#### Features - -- `get_physical` gains Windows support - -### v1.5.1 - -#### Fixes - -- fix `get` to return 1 if `sysconf(_SC_NPROCESSORS_ONLN)` failed - -## v1.5.0 - -#### Features - -- `get()` now checks `sched_affinity` on Linux - -## v1.4.0 - -#### Features - -- add `haiku` target support - -## v1.3.0 - -#### Features - -- add `redox` target support - -### v1.2.1 - -#### Fixes - -- fixes `get_physical` count (454ff1b) - -## v1.2.0 - -#### Features - -- add `emscripten` target support -- add `fuchsia` target support - -## v1.1.0 - -#### Features - -- added `get_physical` function to return number of physical CPUs found - -# v1.0.0 - -#### Features - -- `get` function returns number of CPUs (physical and virtual) of current platform diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/CONTRIBUTING.md b/third_party/cargo/vendor/num_cpus-1.12.0/CONTRIBUTING.md deleted file mode 100644 index 5685b08..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/CONTRIBUTING.md +++ /dev/null @@ -1,16 +0,0 @@ -# Contributing - -## License - -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 the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any -additional terms or conditions. diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/README.md b/third_party/cargo/vendor/num_cpus-1.12.0/README.md deleted file mode 100644 index a0bbe97..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# num_cpus - -[![crates.io](http://meritbadge.herokuapp.com/num_cpus)](https://crates.io/crates/num_cpus) -[![Travis CI Status](https://travis-ci.org/seanmonstar/num_cpus.svg?branch=master)](https://travis-ci.org/seanmonstar/num_cpus) -[![AppVeyor status](https://ci.appveyor.com/api/projects/status/qn8t6grhko5jwno6?svg=true)](https://ci.appveyor.com/project/seanmonstar/num-cpus) - -- [Documentation](https://docs.rs/num_cpus) -- [CHANGELOG](CHANGELOG.md) - -Count the number of CPUs on the current machine. - -## Usage - -Add to Cargo.toml: - -```toml -[dependencies] -num_cpus = "1.0" -``` - -In your `main.rs` or `lib.rs`: - -```rust -extern crate num_cpus; - -// count logical cores this process could try to use -let num = num_cpus::get(); -``` diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/examples/values.rs b/third_party/cargo/vendor/num_cpus-1.12.0/examples/values.rs deleted file mode 100644 index 041cfaf..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/examples/values.rs +++ /dev/null @@ -1,6 +0,0 @@ -extern crate num_cpus; - -fn main() { - println!("Logical CPUs: {}", num_cpus::get()); - println!("Physical CPUs: {}", num_cpus::get_physical()); -} diff --git a/third_party/cargo/vendor/num_cpus-1.12.0/src/lib.rs b/third_party/cargo/vendor/num_cpus-1.12.0/src/lib.rs deleted file mode 100644 index 807af39..0000000 --- a/third_party/cargo/vendor/num_cpus-1.12.0/src/lib.rs +++ /dev/null @@ -1,526 +0,0 @@ -//! A crate with utilities to determine the number of CPUs available on the -//! current system. -//! -//! Sometimes the CPU will exaggerate the number of CPUs it contains, because it can use -//! [processor tricks] to deliver increased performance when there are more threads. This -//! crate provides methods to get both the logical and physical numbers of cores. -//! -//! This information can be used as a guide to how many tasks can be run in parallel. -//! There are many properties of the system architecture that will affect parallelism, -//! for example memory access speeds (for all the caches and RAM) and the physical -//! architecture of the processor, so the number of CPUs should be used as a rough guide -//! only. -//! -//! -//! ## Examples -//! -//! Fetch the number of logical CPUs. -//! -//! ``` -//! let cpus = num_cpus::get(); -//! ``` -//! -//! See [`rayon::Threadpool`] for an example of where the number of CPUs could be -//! used when setting up parallel jobs (Where the threadpool example uses a fixed -//! number 8, it could use the number of CPUs). -//! -//! [processor tricks]: https://en.wikipedia.org/wiki/Simultaneous_multithreading -//! [`rayon::ThreadPool`]: https://docs.rs/rayon/1.*/rayon/struct.ThreadPool.html -#![cfg_attr(test, deny(warnings))] -#![deny(missing_docs)] -#![doc(html_root_url = "https://docs.rs/num_cpus/1.12.0")] -#![allow(non_snake_case)] - -#[cfg(not(windows))] -extern crate libc; - -#[cfg(target_os = "hermit")] -extern crate hermit_abi; - -#[cfg(test)] -#[macro_use] -extern crate doc_comment; - -#[cfg(test)] -doctest!("../README.md"); - -/// Returns the number of available CPUs of the current system. -/// -/// This function will get the number of logical cores. Sometimes this is different from the number -/// of physical cores (See [Simultaneous multithreading on Wikipedia][smt]). -/// -/// # Examples -/// -/// ``` -/// let cpus = num_cpus::get(); -/// if cpus > 1 { -/// println!("We are on a multicore system with {} CPUs", cpus); -/// } else { -/// println!("We are on a single core system"); -/// } -/// ``` -/// -/// # Note -/// -/// This will check [sched affinity] on Linux, showing a lower number of CPUs if the current -/// thread does not have access to all the computer's CPUs. -/// -/// [smt]: https://en.wikipedia.org/wiki/Simultaneous_multithreading -/// [sched affinity]: http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html -#[inline] -pub fn get() -> usize { - get_num_cpus() -} - -/// Returns the number of physical cores of the current system. -/// -/// # Note -/// -/// Physical count is supported only on Linux, mac OS and Windows platforms. -/// On other platforms, or if the physical count fails on supported platforms, -/// this function returns the same as [`get()`], which is the number of logical -/// CPUS. -/// -/// # Examples -/// -/// ``` -/// let logical_cpus = num_cpus::get(); -/// let physical_cpus = num_cpus::get_physical(); -/// if logical_cpus > physical_cpus { -/// println!("We have simultaneous multithreading with about {:.2} \ -/// logical cores to 1 physical core.", -/// (logical_cpus as f64) / (physical_cpus as f64)); -/// } else if logical_cpus == physical_cpus { -/// println!("Either we don't have simultaneous multithreading, or our \ -/// system doesn't support getting the number of physical CPUs."); -/// } else { -/// println!("We have less logical CPUs than physical CPUs, maybe we only have access to \ -/// some of the CPUs on our system."); -/// } -/// ``` -/// -/// [`get()`]: fn.get.html -#[inline] -pub fn get_physical() -> usize { - get_num_physical_cpus() -} - - -#[cfg(not(any(target_os = "linux", target_os = "windows", target_os="macos", target_os="openbsd")))] -#[inline] -fn get_num_physical_cpus() -> usize { - // Not implemented, fall back - get_num_cpus() -} - -#[cfg(target_os = "windows")] -fn get_num_physical_cpus() -> usize { - match get_num_physical_cpus_windows() { - Some(num) => num, - None => get_num_cpus() - } -} - -#[cfg(target_os = "windows")] -fn get_num_physical_cpus_windows() -> Option { - // Inspired by https://msdn.microsoft.com/en-us/library/ms683194 - - use std::ptr; - use std::mem; - - #[allow(non_upper_case_globals)] - const RelationProcessorCore: u32 = 0; - - #[repr(C)] - #[allow(non_camel_case_types)] - struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION { - mask: usize, - relationship: u32, - _unused: [u64; 2] - } - - extern "system" { - fn GetLogicalProcessorInformation( - info: *mut SYSTEM_LOGICAL_PROCESSOR_INFORMATION, - length: &mut u32 - ) -> u32; - } - - // First we need to determine how much space to reserve. - - // The required size of the buffer, in bytes. - let mut needed_size = 0; - - unsafe { - GetLogicalProcessorInformation(ptr::null_mut(), &mut needed_size); - } - - let struct_size = mem::size_of::() as u32; - - // Could be 0, or some other bogus size. - if needed_size == 0 || needed_size < struct_size || needed_size % struct_size != 0 { - return None; - } - - let count = needed_size / struct_size; - - // Allocate some memory where we will store the processor info. - let mut buf = Vec::with_capacity(count as usize); - - let result; - - unsafe { - result = GetLogicalProcessorInformation(buf.as_mut_ptr(), &mut needed_size); - } - - // Failed for any reason. - if result == 0 { - return None; - } - - let count = needed_size / struct_size; - - unsafe { - buf.set_len(count as usize); - } - - let phys_proc_count = buf.iter() - // Only interested in processor packages (physical processors.) - .filter(|proc_info| proc_info.relationship == RelationProcessorCore) - .count(); - - if phys_proc_count == 0 { - None - } else { - Some(phys_proc_count) - } -} - -#[cfg(target_os = "linux")] -fn get_num_physical_cpus() -> usize { - use std::collections::HashMap; - use std::fs::File; - use std::io::BufRead; - use std::io::BufReader; - - let file = match File::open("/proc/cpuinfo") { - Ok(val) => val, - Err(_) => return get_num_cpus(), - }; - let reader = BufReader::new(file); - let mut map = HashMap::new(); - let mut physid: u32 = 0; - let mut cores: usize = 0; - let mut chgcount = 0; - for line in reader.lines().filter_map(|result| result.ok()) { - let mut it = line.split(':'); - let (key, value) = match (it.next(), it.next()) { - (Some(key), Some(value)) => (key.trim(), value.trim()), - _ => continue, - }; - if key == "physical id" { - match value.parse() { - Ok(val) => physid = val, - Err(_) => break, - }; - chgcount += 1; - } - if key == "cpu cores" { - match value.parse() { - Ok(val) => cores = val, - Err(_) => break, - }; - chgcount += 1; - } - if chgcount == 2 { - map.insert(physid, cores); - chgcount = 0; - } - } - let count = map.into_iter().fold(0, |acc, (_, cores)| acc + cores); - - if count == 0 { - get_num_cpus() - } else { - count - } -} - -#[cfg(windows)] -fn get_num_cpus() -> usize { - #[repr(C)] - struct SYSTEM_INFO { - wProcessorArchitecture: u16, - wReserved: u16, - dwPageSize: u32, - lpMinimumApplicationAddress: *mut u8, - lpMaximumApplicationAddress: *mut u8, - dwActiveProcessorMask: *mut u8, - dwNumberOfProcessors: u32, - dwProcessorType: u32, - dwAllocationGranularity: u32, - wProcessorLevel: u16, - wProcessorRevision: u16, - } - - extern "system" { - fn GetSystemInfo(lpSystemInfo: *mut SYSTEM_INFO); - } - - unsafe { - let mut sysinfo: SYSTEM_INFO = std::mem::zeroed(); - GetSystemInfo(&mut sysinfo); - sysinfo.dwNumberOfProcessors as usize - } -} - -#[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - target_os = "netbsd"))] -fn get_num_cpus() -> usize { - use std::ptr; - - let mut cpus: libc::c_uint = 0; - let mut cpus_size = std::mem::size_of_val(&cpus); - - unsafe { - cpus = libc::sysconf(libc::_SC_NPROCESSORS_ONLN) as libc::c_uint; - } - if cpus < 1 { - let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; - unsafe { - libc::sysctl(mib.as_mut_ptr(), - 2, - &mut cpus as *mut _ as *mut _, - &mut cpus_size as *mut _ as *mut _, - ptr::null_mut(), - 0); - } - if cpus < 1 { - cpus = 1; - } - } - cpus as usize -} - -#[cfg(target_os = "openbsd")] -fn get_num_cpus() -> usize { - use std::ptr; - - let mut cpus: libc::c_uint = 0; - let mut cpus_size = std::mem::size_of_val(&cpus); - let mut mib = [libc::CTL_HW, libc::HW_NCPUONLINE, 0, 0]; - let rc: libc::c_int; - - unsafe { - rc = libc::sysctl(mib.as_mut_ptr(), - 2, - &mut cpus as *mut _ as *mut _, - &mut cpus_size as *mut _ as *mut _, - ptr::null_mut(), - 0); - } - if rc < 0 { - cpus = 1; - } - cpus as usize -} - -#[cfg(target_os = "openbsd")] -fn get_num_physical_cpus() -> usize { - use std::ptr; - - let mut cpus: libc::c_uint = 0; - let mut cpus_size = std::mem::size_of_val(&cpus); - let mut mib = [libc::CTL_HW, libc::HW_NCPU, 0, 0]; - let rc: libc::c_int; - - unsafe { - rc = libc::sysctl(mib.as_mut_ptr(), - 2, - &mut cpus as *mut _ as *mut _, - &mut cpus_size as *mut _ as *mut _, - ptr::null_mut(), - 0); - } - if rc < 0 { - cpus = 1; - } - cpus as usize -} - - -#[cfg(target_os = "macos")] -fn get_num_physical_cpus() -> usize { - use std::ffi::CStr; - use std::ptr; - - let mut cpus: i32 = 0; - let mut cpus_size = std::mem::size_of_val(&cpus); - - let sysctl_name = CStr::from_bytes_with_nul(b"hw.physicalcpu\0") - .expect("byte literal is missing NUL"); - - unsafe { - if 0 != libc::sysctlbyname(sysctl_name.as_ptr(), - &mut cpus as *mut _ as *mut _, - &mut cpus_size as *mut _ as *mut _, - ptr::null_mut(), - 0) { - return get_num_cpus(); - } - } - cpus as usize -} - -#[cfg(target_os = "linux")] -fn get_num_cpus() -> usize { - let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() }; - if unsafe { libc::sched_getaffinity(0, std::mem::size_of::(), &mut set) } == 0 { - let mut count: u32 = 0; - for i in 0..libc::CPU_SETSIZE as usize { - if unsafe { libc::CPU_ISSET(i, &set) } { - count += 1 - } - } - count as usize - } else { - let cpus = unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }; - if cpus < 1 { - 1 - } else { - cpus as usize - } - } -} - -#[cfg(any( - target_os = "nacl", - target_os = "macos", - target_os = "ios", - target_os = "android", - target_os = "solaris", - target_os = "illumos", - target_os = "fuchsia") -)] -fn get_num_cpus() -> usize { - // On ARM targets, processors could be turned off to save power. - // Use `_SC_NPROCESSORS_CONF` to get the real number. - #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] - const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_CONF; - #[cfg(not(any(target_arch = "arm", target_arch = "aarch64")))] - const CONF_NAME: libc::c_int = libc::_SC_NPROCESSORS_ONLN; - - let cpus = unsafe { libc::sysconf(CONF_NAME) }; - if cpus < 1 { - 1 - } else { - cpus as usize - } -} - -#[cfg(target_os = "haiku")] -fn get_num_cpus() -> usize { - use std::mem; - - #[allow(non_camel_case_types)] - type bigtime_t = i64; - #[allow(non_camel_case_types)] - type status_t = i32; - - #[repr(C)] - pub struct system_info { - pub boot_time: bigtime_t, - pub cpu_count: u32, - pub max_pages: u64, - pub used_pages: u64, - pub cached_pages: u64, - pub block_cache_pages: u64, - pub ignored_pages: u64, - pub needed_memory: u64, - pub free_memory: u64, - pub max_swap_pages: u64, - pub free_swap_pages: u64, - pub page_faults: u32, - pub max_sems: u32, - pub used_sems: u32, - pub max_ports: u32, - pub used_ports: u32, - pub max_threads: u32, - pub used_threads: u32, - pub max_teams: u32, - pub used_teams: u32, - pub kernel_name: [::std::os::raw::c_char; 256usize], - pub kernel_build_date: [::std::os::raw::c_char; 32usize], - pub kernel_build_time: [::std::os::raw::c_char; 32usize], - pub kernel_version: i64, - pub abi: u32, - } - - extern { - fn get_system_info(info: *mut system_info) -> status_t; - } - - let mut info: system_info = unsafe { mem::zeroed() }; - let status = unsafe { get_system_info(&mut info as *mut _) }; - if status == 0 { - info.cpu_count as usize - } else { - 1 - } -} - -#[cfg(target_os = "hermit")] -fn get_num_cpus() -> usize { - unsafe { hermit_abi::get_processor_count() } -} - -#[cfg(not(any( - target_os = "nacl", - target_os = "macos", - target_os = "ios", - target_os = "android", - target_os = "solaris", - target_os = "illumos", - target_os = "fuchsia", - target_os = "linux", - target_os = "openbsd", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "netbsd", - target_os = "haiku", - target_os = "hermit", - windows, -)))] -fn get_num_cpus() -> usize { - 1 -} - -#[cfg(test)] -mod tests { - fn env_var(name: &'static str) -> Option { - ::std::env::var(name).ok().map(|val| val.parse().unwrap()) - } - - #[test] - fn test_get() { - let num = super::get(); - if let Some(n) = env_var("NUM_CPUS_TEST_GET") { - assert_eq!(num, n); - } else { - assert!(num > 0); - assert!(num < 236_451); - } - } - - #[test] - fn test_get_physical() { - let num = super::get_physical(); - if let Some(n) = env_var("NUM_CPUS_TEST_GET_PHYSICAL") { - assert_eq!(num, n); - } else { - assert!(num > 0); - assert!(num < 236_451); - } - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/.cargo-checksum.json b/third_party/cargo/vendor/objc-foundation-0.1.1/.cargo-checksum.json deleted file mode 100644 index 5d7a412..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"27c851b122617cfbf263603bcf05d637aaddbc87c12c2e78f8f91675739928a8","examples/custom_class.rs":"44fab02b2eb974cbfd35e649872044457fa50c61148a13b02a71395fe6e44f3f","examples/example.rs":"1f05e488809d0356b3658ac2bce12def26ac9518f4774dc599a216ddc719cd65","src/array.rs":"c3b7038821a5ecb10b043152cfc1ab0520ef5f923ea77b1e6a1c54ddf4586d96","src/data.rs":"9ae4e7fe1bd92a40edd700f364ce60a18467387d360459e04e6933e6b6d20cfc","src/dictionary.rs":"b42dcb6f280211ef674f9018559eb768138f4a6a382410706278f2bcff3164b9","src/enumerator.rs":"62f77fb4ccc7b9306c0d6564589d25234368d88b63d319e813622846fe0e5f47","src/lib.rs":"f6dd421ba10b1a0e57fa10609ce2819ae491f63c08ee4b78a6884dcc5e742389","src/macros.rs":"7c03375b7efa17b2a58f9c9821a61581b4b6eaa1e0185f2468e6d5ded57aef59","src/object.rs":"c6deba06b351936ed2264cdb56755685cdf0b92e37fcf4f6ba56e6021cd00384","src/string.rs":"aeffa50feb90c50e11979780a67ced5c7458f8d164d668d271c0aaafe64d8025","src/value.rs":"ee8168e2b45a3094b08a604e84e2d80c38454bb8ffbb859a24baf04725894be1"},"package":"1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/Cargo.toml b/third_party/cargo/vendor/objc-foundation-0.1.1/Cargo.toml deleted file mode 100644 index 82562fc..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "objc-foundation" -version = "0.1.1" -authors = ["Steven Sheldon"] - -description = "Rust wrapper for Objective-C's Foundation framework." -keywords = ["objective-c", "osx", "ios", "cocoa", "uikit"] -repository = "http://github.com/SSheldon/rust-objc-foundation" -documentation = "http://ssheldon.github.io/rust-objc/objc_foundation/" -license = "MIT" - -exclude = [".gitignore"] - -[dependencies] -block = "0.1" -objc = "0.2" -objc_id = "0.1" diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/examples/custom_class.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/examples/custom_class.rs deleted file mode 100644 index 793e0bf..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/examples/custom_class.rs +++ /dev/null @@ -1,77 +0,0 @@ -#[macro_use] -extern crate objc; -extern crate objc_foundation; - -use std::sync::{Once, ONCE_INIT}; - -use objc::Message; -use objc::declare::ClassDecl; -use objc::runtime::{Class, Object, Sel}; -use objc_foundation::{INSObject, NSObject}; - -pub enum MYObject { } - -impl MYObject { - fn number(&self) -> u32 { - unsafe { - let obj = &*(self as *const _ as *const Object); - *obj.get_ivar("_number") - } - } - - fn set_number(&mut self, number: u32) { - unsafe { - let obj = &mut *(self as *mut _ as *mut Object); - obj.set_ivar("_number", number); - } - } -} - -unsafe impl Message for MYObject { } - -static MYOBJECT_REGISTER_CLASS: Once = ONCE_INIT; - -impl INSObject for MYObject { - fn class() -> &'static Class { - MYOBJECT_REGISTER_CLASS.call_once(|| { - let superclass = NSObject::class(); - let mut decl = ClassDecl::new("MYObject", superclass).unwrap(); - decl.add_ivar::("_number"); - - // Add ObjC methods for getting and setting the number - extern fn my_object_set_number(this: &mut Object, _cmd: Sel, number: u32) { - unsafe { this.set_ivar("_number", number); } - } - - extern fn my_object_get_number(this: &Object, _cmd: Sel) -> u32 { - unsafe { *this.get_ivar("_number") } - } - - unsafe { - let set_number: extern fn(&mut Object, Sel, u32) = my_object_set_number; - decl.add_method(sel!(setNumber:), set_number); - let get_number: extern fn(&Object, Sel) -> u32 = my_object_get_number; - decl.add_method(sel!(number), get_number); - } - - decl.register(); - }); - - Class::get("MYObject").unwrap() - } -} - -fn main() { - let mut obj = MYObject::new(); - - obj.set_number(7); - println!("Number: {}", unsafe { - let number: u32 = msg_send![obj, number]; - number - }); - - unsafe { - let _: () = msg_send![obj, setNumber:12u32]; - } - println!("Number: {}", obj.number()); -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/examples/example.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/examples/example.rs deleted file mode 100644 index 5338487..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/examples/example.rs +++ /dev/null @@ -1,38 +0,0 @@ -extern crate objc_foundation; - -use objc_foundation::{NSArray, NSDictionary, NSObject, NSString, - INSArray, INSCopying, INSDictionary, INSObject, INSString}; - -fn main() { - // Create and compare NSObjects - let obj = NSObject::new(); - println!("{:?} == {:?}? {:?}", obj, obj, obj == obj); - - let obj2 = NSObject::new(); - println!("{:?} == {:?}? {:?}", obj, obj2, obj == obj2); - - // Create an NSArray from a Vec - let objs = vec![obj, obj2]; - let array = NSArray::from_vec(objs); - for obj in array.object_enumerator() { - println!("{:?}", obj); - } - println!("{}", array.count()); - - // Turn the NSArray back into a Vec - let mut objs = NSArray::into_vec(array); - let obj = objs.pop().unwrap(); - - // Create an NSString from a str slice - let string = NSString::from_str("Hello, world!"); - println!("{}", string.as_str()); - let string2 = string.copy(); - println!("{}", string2.as_str()); - - // Create a dictionary mapping strings to objects - let keys = &[&*string]; - let vals = vec![obj]; - let dict = NSDictionary::from_keys_and_objects(keys, vals); - println!("{:?}", dict.object_for(&string)); - println!("{}", dict.count()); -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/array.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/array.rs deleted file mode 100644 index 0bc04d4..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/array.rs +++ /dev/null @@ -1,441 +0,0 @@ -use std::cmp::Ordering; -use std::marker::PhantomData; -use std::ops::{Index, Range}; - -use objc::runtime::{Class, Object}; -use objc_id::{Id, Owned, Ownership, Shared, ShareId}; - -use {INSCopying, INSFastEnumeration, INSMutableCopying, INSObject, NSEnumerator}; - -#[repr(isize)] -#[derive(Clone, Copy)] -pub enum NSComparisonResult { - Ascending = -1, - Same = 0, - Descending = 1, -} - -impl NSComparisonResult { - pub fn from_ordering(order: Ordering) -> NSComparisonResult { - match order { - Ordering::Less => NSComparisonResult::Ascending, - Ordering::Equal => NSComparisonResult::Same, - Ordering::Greater => NSComparisonResult::Descending, - } - } - - pub fn as_ordering(&self) -> Ordering { - match *self { - NSComparisonResult::Ascending => Ordering::Less, - NSComparisonResult::Same => Ordering::Equal, - NSComparisonResult::Descending => Ordering::Greater, - } - } -} - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct NSRange { - pub location: usize, - pub length: usize, -} - -impl NSRange { - pub fn from_range(range: Range) -> NSRange { - assert!(range.end >= range.start); - NSRange { location: range.start, length: range.end - range.start } - } - - pub fn as_range(&self) -> Range { - Range { start: self.location, end: self.location + self.length } - } -} - -unsafe fn from_refs(refs: &[&A::Item]) -> Id where A: INSArray { - let cls = A::class(); - let obj: *mut A = msg_send![cls, alloc]; - let obj: *mut A = msg_send![obj, initWithObjects:refs.as_ptr() - count:refs.len()]; - Id::from_retained_ptr(obj) -} - -pub trait INSArray : INSObject { - type Item: INSObject; - type Own: Ownership; - - fn count(&self) -> usize { - unsafe { - msg_send![self, count] - } - } - - fn object_at(&self, index: usize) -> &Self::Item { - unsafe { - let obj: *const Self::Item = msg_send![self, objectAtIndex:index]; - &*obj - } - } - - fn first_object(&self) -> Option<&Self::Item> { - unsafe { - let obj: *const Self::Item = msg_send![self, firstObject]; - if obj.is_null() { None } else { Some(&*obj) } - } - } - - fn last_object(&self) -> Option<&Self::Item> { - unsafe { - let obj: *const Self::Item = msg_send![self, lastObject]; - if obj.is_null() { None } else { Some(&*obj) } - } - } - - fn object_enumerator(&self) -> NSEnumerator { - unsafe { - let result: *mut Object = msg_send![self, objectEnumerator]; - NSEnumerator::from_ptr(result) - } - } - - fn from_vec(vec: Vec>) -> Id { - let refs: Vec<&Self::Item> = vec.iter().map(|obj| &**obj).collect(); - unsafe { - from_refs(&refs) - } - } - - fn objects_in_range(&self, range: Range) -> Vec<&Self::Item> { - let range = NSRange::from_range(range); - let mut vec = Vec::with_capacity(range.length); - unsafe { - let _: () = msg_send![self, getObjects:vec.as_ptr() range:range]; - vec.set_len(range.length); - } - vec - } - - fn to_vec(&self) -> Vec<&Self::Item> { - self.objects_in_range(0..self.count()) - } - - fn into_vec(array: Id) -> Vec> { - array.to_vec().into_iter().map(|obj| unsafe { - let obj_ptr: *const Self::Item = obj; - Id::from_ptr(obj_ptr as *mut Self::Item) - }).collect() - } - - fn mut_object_at(&mut self, index: usize) -> &mut Self::Item - where Self: INSArray { - unsafe { - let result: *mut Self::Item = msg_send![self, objectAtIndex:index]; - &mut *result - } - } - - fn shared_object_at(&self, index: usize) -> ShareId - where Self: INSArray { - let obj = self.object_at(index); - unsafe { - Id::from_ptr(obj as *const _ as *mut Self::Item) - } - } - - fn from_slice(slice: &[ShareId]) -> Id - where Self: INSArray { - let refs: Vec<&Self::Item> = slice.iter().map(|obj| &**obj).collect(); - unsafe { - from_refs(&refs) - } - } - - fn to_shared_vec(&self) -> Vec> - where Self: INSArray { - self.to_vec().into_iter().map(|obj| unsafe { - let obj_ptr: *const Self::Item = obj; - Id::from_ptr(obj_ptr as *mut Self::Item) - }).collect() - } -} - -pub struct NSArray { - item: PhantomData>, -} - -object_impl!(NSArray); - -impl INSObject for NSArray where T: INSObject, O: Ownership { - fn class() -> &'static Class { - Class::get("NSArray").unwrap() - } -} - -impl INSArray for NSArray where T: INSObject, O: Ownership { - type Item = T; - type Own = O; -} - -impl INSCopying for NSArray where T: INSObject { - type Output = NSSharedArray; -} - -impl INSMutableCopying for NSArray where T: INSObject { - type Output = NSMutableSharedArray; -} - -impl INSFastEnumeration for NSArray - where T: INSObject, O: Ownership { - type Item = T; -} - -impl Index for NSArray where T: INSObject, O: Ownership { - type Output = T; - - fn index(&self, index: usize) -> &T { - self.object_at(index) - } -} - -pub type NSSharedArray = NSArray; - -pub trait INSMutableArray : INSArray { - fn add_object(&mut self, obj: Id) { - unsafe { - let _: () = msg_send![self, addObject:&*obj]; - } - } - - fn insert_object_at(&mut self, index: usize, obj: Id) { - unsafe { - let _: () = msg_send![self, insertObject:&*obj atIndex:index]; - } - } - - fn replace_object_at(&mut self, index: usize, obj: Id) -> - Id { - let old_obj = unsafe { - let obj = self.object_at(index); - Id::from_ptr(obj as *const _ as *mut Self::Item) - }; - unsafe { - let _: () = msg_send![self, replaceObjectAtIndex:index - withObject:&*obj]; - } - old_obj - } - - fn remove_object_at(&mut self, index: usize) -> Id { - let obj = unsafe { - let obj = self.object_at(index); - Id::from_ptr(obj as *const _ as *mut Self::Item) - }; - unsafe { - let _: () = msg_send![self, removeObjectAtIndex:index]; - } - obj - } - - fn remove_last_object(&mut self) -> Id { - let obj = self.last_object().map(|obj| unsafe { - Id::from_ptr(obj as *const _ as *mut Self::Item) - }); - unsafe { - let _: () = msg_send![self, removeLastObject]; - } - // removeLastObject would have failed if the array is empty, - // so we know this won't be None - obj.unwrap() - } - - fn remove_all_objects(&mut self) { - unsafe { - let _: () = msg_send![self, removeAllObjects]; - } - } - - fn sort_by(&mut self, compare: F) - where F: FnMut(&Self::Item, &Self::Item) -> Ordering { - extern fn compare_with_closure(obj1: &T, obj2: &T, - compare: &mut F) -> NSComparisonResult - where F: FnMut(&T, &T) -> Ordering { - NSComparisonResult::from_ordering((*compare)(obj1, obj2)) - } - - let f: extern fn(&Self::Item, &Self::Item, &mut F) -> NSComparisonResult = - compare_with_closure; - let mut closure = compare; - unsafe { - let _: () = msg_send![self, sortUsingFunction:f - context:&mut closure]; - } - } -} - -pub struct NSMutableArray { - item: PhantomData>, -} - -object_impl!(NSMutableArray); - -impl INSObject for NSMutableArray where T: INSObject, O: Ownership { - fn class() -> &'static Class { - Class::get("NSMutableArray").unwrap() - } -} - -impl INSArray for NSMutableArray where T: INSObject, O: Ownership { - type Item = T; - type Own = O; -} - -impl INSMutableArray for NSMutableArray - where T: INSObject, O: Ownership { } - -impl INSCopying for NSMutableArray where T: INSObject { - type Output = NSSharedArray; -} - -impl INSMutableCopying for NSMutableArray where T: INSObject { - type Output = NSMutableSharedArray; -} - -impl INSFastEnumeration for NSMutableArray - where T: INSObject, O: Ownership { - type Item = T; -} - -impl Index for NSMutableArray - where T: INSObject, O: Ownership { - type Output = T; - - fn index(&self, index: usize) -> &T { - self.object_at(index) - } -} - -pub type NSMutableSharedArray = NSMutableArray; - -#[cfg(test)] -mod tests { - use objc_id::Id; - use {INSObject, INSString, NSObject, NSString}; - use super::{INSArray, INSMutableArray, NSArray, NSMutableArray}; - - fn sample_array(len: usize) -> Id> { - let mut vec = Vec::with_capacity(len); - for _ in 0..len { - vec.push(NSObject::new()); - } - NSArray::from_vec(vec) - } - - #[test] - fn test_count() { - let empty_array = NSArray::::new(); - assert!(empty_array.count() == 0); - - let array = sample_array(4); - assert!(array.count() == 4); - } - - #[test] - fn test_object_at() { - let array = sample_array(4); - assert!(array.object_at(0) != array.object_at(3)); - assert!(array.first_object().unwrap() == array.object_at(0)); - assert!(array.last_object().unwrap() == array.object_at(3)); - - let empty_array: Id> = INSObject::new(); - assert!(empty_array.first_object().is_none()); - assert!(empty_array.last_object().is_none()); - } - - #[test] - fn test_object_enumerator() { - let array = sample_array(4); - - assert!(array.object_enumerator().count() == 4); - assert!(array.object_enumerator() - .enumerate() - .all(|(i, obj)| obj == array.object_at(i))); - } - - #[test] - fn test_objects_in_range() { - let array = sample_array(4); - - let middle_objs = array.objects_in_range(1..3); - assert!(middle_objs.len() == 2); - assert!(middle_objs[0] == array.object_at(1)); - assert!(middle_objs[1] == array.object_at(2)); - - let empty_objs = array.objects_in_range(1..1); - assert!(empty_objs.len() == 0); - - let all_objs = array.objects_in_range(0..4); - assert!(all_objs.len() == 4); - } - - #[test] - fn test_into_vec() { - let array = sample_array(4); - - let vec = INSArray::into_vec(array); - assert!(vec.len() == 4); - } - - #[test] - fn test_add_object() { - let mut array = NSMutableArray::new(); - let obj = NSObject::new(); - array.add_object(obj); - - assert!(array.count() == 1); - assert!(array.object_at(0) == array.object_at(0)); - - let obj = NSObject::new(); - array.insert_object_at(0, obj); - assert!(array.count() == 2); - } - - #[test] - fn test_replace_object() { - let mut array = NSMutableArray::new(); - let obj = NSObject::new(); - array.add_object(obj); - - let obj = NSObject::new(); - let old_obj = array.replace_object_at(0, obj); - assert!(&*old_obj != array.object_at(0)); - } - - #[test] - fn test_remove_object() { - let mut array = NSMutableArray::new(); - for _ in 0..4 { - array.add_object(NSObject::new()); - } - - array.remove_object_at(1); - assert!(array.count() == 3); - - array.remove_last_object(); - assert!(array.count() == 2); - - array.remove_all_objects(); - assert!(array.count() == 0); - } - - #[test] - fn test_sort() { - let strings = vec![ - NSString::from_str("hello"), - NSString::from_str("hi"), - ]; - let mut strings = NSMutableArray::from_vec(strings); - - strings.sort_by(|s1, s2| s1.as_str().len().cmp(&s2.as_str().len())); - assert!(strings[0].as_str() == "hi"); - assert!(strings[1].as_str() == "hello"); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/data.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/data.rs deleted file mode 100644 index f49aa95..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/data.rs +++ /dev/null @@ -1,200 +0,0 @@ -use std::mem; -use std::ops::Range; -use std::os::raw::c_void; -use std::slice; - -use objc_id::Id; -use block::{Block, ConcreteBlock}; -use {INSObject, INSCopying, INSMutableCopying, NSRange}; - -pub trait INSData : INSObject { - fn len(&self) -> usize { - unsafe { - msg_send![self, length] - } - } - - fn bytes(&self) -> &[u8] { - let ptr: *const c_void = unsafe { msg_send![self, bytes] }; - // The bytes pointer may be null for length zero - let (ptr, len) = if ptr.is_null() { - (0x1 as *const u8, 0) - } else { - (ptr as *const u8, self.len()) - }; - unsafe { - slice::from_raw_parts(ptr, len) - } - } - - fn with_bytes(bytes: &[u8]) -> Id { - let cls = Self::class(); - unsafe { - let obj: *mut Self = msg_send![cls, alloc]; - let obj: *mut Self = msg_send![obj, initWithBytes:bytes.as_ptr() - length:bytes.len()]; - Id::from_retained_ptr(obj) - } - } - - fn from_vec(bytes: Vec) -> Id { - let capacity = bytes.capacity(); - let dealloc = ConcreteBlock::new(move |bytes: *mut c_void, len: usize| unsafe { - // Recreate the Vec and let it drop - let _ = Vec::from_raw_parts(bytes as *mut u8, len, capacity); - }); - let dealloc = dealloc.copy(); - let dealloc: &Block<(*mut c_void, usize), ()> = &dealloc; - - let mut bytes = bytes; - let cls = Self::class(); - unsafe { - let obj: *mut Self = msg_send![cls, alloc]; - let obj: *mut Self = msg_send![obj, initWithBytesNoCopy:bytes.as_mut_ptr() - length:bytes.len() - deallocator:dealloc]; - mem::forget(bytes); - Id::from_retained_ptr(obj) - } - } -} - -object_struct!(NSData); - -impl INSData for NSData { } - -impl INSCopying for NSData { - type Output = NSData; -} - -impl INSMutableCopying for NSData { - type Output = NSMutableData; -} - -pub trait INSMutableData : INSData { - fn bytes_mut(&mut self) -> &mut [u8] { - let ptr: *mut c_void = unsafe { msg_send![self, mutableBytes] }; - // The bytes pointer may be null for length zero - let (ptr, len) = if ptr.is_null() { - (0x1 as *mut u8, 0) - } else { - (ptr as *mut u8, self.len()) - }; - unsafe { - slice::from_raw_parts_mut(ptr, len) - } - } - - fn set_len(&mut self, len: usize) { - unsafe { - let _: () = msg_send![self, setLength:len]; - } - } - - fn append(&mut self, bytes: &[u8]) { - unsafe { - let _: () = msg_send![self, appendBytes:bytes.as_ptr() - length:bytes.len()]; - } - } - - fn replace_range(&mut self, range: Range, bytes: &[u8]) { - let range = NSRange::from_range(range); - unsafe { - let _: () = msg_send![self, replaceBytesInRange:range - withBytes:bytes.as_ptr() - length:bytes.len()]; - } - } - - fn set_bytes(&mut self, bytes: &[u8]) { - let len = self.len(); - self.replace_range(0..len, bytes); - } -} - -object_struct!(NSMutableData); - -impl INSData for NSMutableData { } - -impl INSMutableData for NSMutableData { } - -impl INSCopying for NSMutableData { - type Output = NSData; -} - -impl INSMutableCopying for NSMutableData { - type Output = NSMutableData; -} - -#[cfg(test)] -mod tests { - use INSObject; - use super::{INSData, INSMutableData, NSData, NSMutableData}; - - #[test] - fn test_bytes() { - let bytes = [3, 7, 16, 52, 112, 19]; - let data = NSData::with_bytes(&bytes); - assert!(data.len() == bytes.len()); - assert!(data.bytes() == bytes); - } - - #[test] - fn test_no_bytes() { - let data = NSData::new(); - assert!(Some(data.bytes()).is_some()); - } - - #[test] - fn test_bytes_mut() { - let mut data = NSMutableData::with_bytes(&[7, 16]); - data.bytes_mut()[0] = 3; - assert!(data.bytes() == [3, 16]); - } - - #[test] - fn test_set_len() { - let mut data = NSMutableData::with_bytes(&[7, 16]); - data.set_len(4); - assert!(data.len() == 4); - assert!(data.bytes() == [7, 16, 0, 0]); - - data.set_len(1); - assert!(data.len() == 1); - assert!(data.bytes() == [7]); - } - - #[test] - fn test_append() { - let mut data = NSMutableData::with_bytes(&[7, 16]); - data.append(&[3, 52]); - assert!(data.len() == 4); - assert!(data.bytes() == [7, 16, 3, 52]); - } - - #[test] - fn test_replace() { - let mut data = NSMutableData::with_bytes(&[7, 16]); - data.replace_range(0..0, &[3]); - assert!(data.bytes() == [3, 7, 16]); - - data.replace_range(1..2, &[52, 13]); - assert!(data.bytes() == [3, 52, 13, 16]); - - data.replace_range(2..4, &[6]); - assert!(data.bytes() == [3, 52, 6]); - - data.set_bytes(&[8, 17]); - assert!(data.bytes() == [8, 17]); - } - - #[test] - fn test_from_vec() { - let bytes = vec![3, 7, 16]; - let bytes_ptr = bytes.as_ptr(); - - let data = NSData::from_vec(bytes); - assert!(data.bytes().as_ptr() == bytes_ptr); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/dictionary.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/dictionary.rs deleted file mode 100644 index ea561a6..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/dictionary.rs +++ /dev/null @@ -1,230 +0,0 @@ -use std::cmp::min; -use std::marker::PhantomData; -use std::ops::Index; -use std::ptr; - -use objc::runtime::Class; -use objc_id::{Id, Owned, Ownership, ShareId}; - -use { - INSArray, INSFastEnumeration, INSCopying, INSObject, - NSArray, NSSharedArray, NSEnumerator, -}; - -unsafe fn from_refs(keys: &[&T], vals: &[&D::Value]) -> Id - where D: INSDictionary, T: INSCopying { - let cls = D::class(); - let count = min(keys.len(), vals.len()); - let obj: *mut D = msg_send![cls, alloc]; - let obj: *mut D = msg_send![obj, initWithObjects:vals.as_ptr() - forKeys:keys.as_ptr() - count:count]; - Id::from_retained_ptr(obj) -} - -pub trait INSDictionary : INSObject { - type Key: INSObject; - type Value: INSObject; - type Own: Ownership; - - fn count(&self) -> usize { - unsafe { - msg_send![self, count] - } - } - - fn object_for(&self, key: &Self::Key) -> Option<&Self::Value> { - unsafe { - let obj: *mut Self::Value = msg_send![self, objectForKey:key]; - if obj.is_null() { None } else { Some(&*obj) } - } - } - - fn keys(&self) -> Vec<&Self::Key> { - let len = self.count(); - let mut keys = Vec::with_capacity(len); - unsafe { - let _: () = msg_send![self, getObjects:ptr::null_mut::() - andKeys:keys.as_mut_ptr()]; - keys.set_len(len); - } - keys - } - - fn values(&self) -> Vec<&Self::Value> { - let len = self.count(); - let mut vals = Vec::with_capacity(len); - unsafe { - let _: () = msg_send![self, getObjects:vals.as_mut_ptr() - andKeys:ptr::null_mut::()]; - vals.set_len(len); - } - vals - } - - fn keys_and_objects(&self) -> (Vec<&Self::Key>, Vec<&Self::Value>) { - let len = self.count(); - let mut keys = Vec::with_capacity(len); - let mut objs = Vec::with_capacity(len); - unsafe { - let _: () = msg_send![self, getObjects:objs.as_mut_ptr() - andKeys:keys.as_mut_ptr()]; - keys.set_len(len); - objs.set_len(len); - } - (keys, objs) - } - - fn key_enumerator(&self) -> NSEnumerator { - unsafe { - let result = msg_send![self, keyEnumerator]; - NSEnumerator::from_ptr(result) - } - } - - fn object_enumerator(&self) -> NSEnumerator { - unsafe { - let result = msg_send![self, objectEnumerator]; - NSEnumerator::from_ptr(result) - } - } - - fn keys_array(&self) -> Id> { - unsafe { - let keys: *mut NSSharedArray = msg_send![self, allKeys]; - Id::from_ptr(keys) - } - } - - fn from_keys_and_objects(keys: &[&T], - vals: Vec>) -> Id - where T: INSCopying { - let vals_refs: Vec<&Self::Value> = vals.iter().map(|obj| &**obj).collect(); - unsafe { - from_refs(keys, &vals_refs) - } - } - - fn into_values_array(dict: Id) -> Id> { - unsafe { - let vals = msg_send![dict, allValues]; - Id::from_ptr(vals) - } - } -} - -pub struct NSDictionary { - key: PhantomData>, - obj: PhantomData>, -} - -object_impl!(NSDictionary); - -impl INSObject for NSDictionary where K: INSObject, V: INSObject { - fn class() -> &'static Class { - Class::get("NSDictionary").unwrap() - } -} - -impl INSDictionary for NSDictionary - where K: INSObject, V: INSObject { - type Key = K; - type Value = V; - type Own = Owned; -} - -impl INSFastEnumeration for NSDictionary - where K: INSObject, V: INSObject { - type Item = K; -} - -impl<'a, K, V> Index<&'a K> for NSDictionary where K: INSObject, V: INSObject { - type Output = V; - - fn index(&self, index: &K) -> &V { - self.object_for(index).unwrap() - } -} - -#[cfg(test)] -mod tests { - use objc_id::Id; - use {INSArray, INSObject, INSString, NSObject, NSString}; - use super::{INSDictionary, NSDictionary}; - - fn sample_dict(key: &str) -> Id> { - let string = NSString::from_str(key); - let obj = NSObject::new(); - NSDictionary::from_keys_and_objects(&[&*string], vec![obj]) - } - - #[test] - fn test_count() { - let dict = sample_dict("abcd"); - assert!(dict.count() == 1); - } - - #[test] - fn test_object_for() { - let dict = sample_dict("abcd"); - - let string = NSString::from_str("abcd"); - assert!(dict.object_for(&string).is_some()); - - let string = NSString::from_str("abcde"); - assert!(dict.object_for(&string).is_none()); - } - - #[test] - fn test_keys() { - let dict = sample_dict("abcd"); - let keys = dict.keys(); - - assert!(keys.len() == 1); - assert!(keys[0].as_str() == "abcd"); - } - - #[test] - fn test_values() { - let dict = sample_dict("abcd"); - let vals = dict.values(); - - assert!(vals.len() == 1); - } - - #[test] - fn test_keys_and_objects() { - let dict = sample_dict("abcd"); - let (keys, objs) = dict.keys_and_objects(); - - assert!(keys.len() == 1); - assert!(objs.len() == 1); - assert!(keys[0].as_str() == "abcd"); - assert!(objs[0] == dict.object_for(keys[0]).unwrap()); - } - - #[test] - fn test_key_enumerator() { - let dict = sample_dict("abcd"); - assert!(dict.key_enumerator().count() == 1); - assert!(dict.key_enumerator().next().unwrap().as_str() == "abcd"); - } - - #[test] - fn test_object_enumerator() { - let dict = sample_dict("abcd"); - assert!(dict.object_enumerator().count() == 1); - } - - #[test] - fn test_arrays() { - let dict = sample_dict("abcd"); - - let keys = dict.keys_array(); - assert!(keys.count() == 1); - assert!(keys.object_at(0).as_str() == "abcd"); - - let objs = INSDictionary::into_values_array(dict); - assert!(objs.count() == 1); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/enumerator.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/enumerator.rs deleted file mode 100644 index 9f2c081..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/enumerator.rs +++ /dev/null @@ -1,166 +0,0 @@ -use std::marker::PhantomData; -use std::mem; -use std::os::raw::c_ulong; -use std::ptr; -use std::slice; - -use objc::runtime::Object; -use objc_id::Id; - -use INSObject; - -pub struct NSEnumerator<'a, T> where T: INSObject { - id: Id, - item: PhantomData<&'a T>, -} - -impl<'a, T> NSEnumerator<'a, T> where T: INSObject { - pub unsafe fn from_ptr(ptr: *mut Object) -> NSEnumerator<'a, T> { - NSEnumerator { id: Id::from_ptr(ptr), item: PhantomData } - } -} - -impl<'a, T> Iterator for NSEnumerator<'a, T> where T: INSObject { - type Item = &'a T; - - fn next(&mut self) -> Option<&'a T> { - unsafe { - let obj: *mut T = msg_send![self.id, nextObject]; - if obj.is_null() { None } else { Some(&*obj) } - } - } -} - -pub trait INSFastEnumeration: INSObject { - type Item: INSObject; - - fn enumerator(&self) -> NSFastEnumerator { - NSFastEnumerator::new(self) - } -} - -#[repr(C)] -struct NSFastEnumerationState { - state: c_ulong, - items_ptr: *const *const T, - mutations_ptr: *mut c_ulong, - extra: [c_ulong; 5], -} - -fn enumerate<'a, 'b: 'a, C: INSFastEnumeration>(object: &'b C, - state: &mut NSFastEnumerationState, - buf: &'a mut [*const C::Item]) -> Option<&'a [*const C::Item]> { - let count: usize = unsafe { - // Reborrow state so that we don't move it - let state = &mut *state; - msg_send![object, countByEnumeratingWithState:state - objects:buf.as_mut_ptr() - count:buf.len()] - }; - - if count > 0 { - unsafe { Some(slice::from_raw_parts(state.items_ptr, count)) } - } else { - None - } -} - -const FAST_ENUM_BUF_SIZE: usize = 16; - -pub struct NSFastEnumerator<'a, C: 'a + INSFastEnumeration> { - object: &'a C, - - ptr: *const *const C::Item, - end: *const *const C::Item, - - state: NSFastEnumerationState, - buf: [*const C::Item; FAST_ENUM_BUF_SIZE], -} - -impl<'a, C: INSFastEnumeration> NSFastEnumerator<'a, C> { - fn new(object: &C) -> NSFastEnumerator { - NSFastEnumerator { - object: object, - - ptr: ptr::null(), - end: ptr::null(), - - state: unsafe { mem::zeroed() }, - buf: [ptr::null(); FAST_ENUM_BUF_SIZE], - } - } - - fn update_buf(&mut self) -> bool { - // If this isn't our first time enumerating, record the previous value - // from the mutations pointer. - let mutations = if !self.ptr.is_null() { - Some(unsafe { *self.state.mutations_ptr }) - } else { - None - }; - - let next_buf = enumerate(self.object, &mut self.state, &mut self.buf); - if let Some(buf) = next_buf { - // Check if the collection was mutated - if let Some(mutations) = mutations { - assert!(mutations == unsafe { *self.state.mutations_ptr }, - "Mutation detected during enumeration of object {:p}", - self.object); - } - - self.ptr = buf.as_ptr(); - self.end = unsafe { self.ptr.offset(buf.len() as isize) }; - true - } else { - self.ptr = ptr::null(); - self.end = ptr::null(); - false - } - } -} - -impl<'a, C: INSFastEnumeration> Iterator for NSFastEnumerator<'a, C> { - type Item = &'a C::Item; - - fn next(&mut self) -> Option<&'a C::Item> { - if self.ptr == self.end && !self.update_buf() { - None - } else { - unsafe { - let obj = *self.ptr; - self.ptr = self.ptr.offset(1); - Some(&*obj) - } - } - } -} - -#[cfg(test)] -mod tests { - use {INSArray, INSValue, NSArray, NSValue}; - use super::INSFastEnumeration; - - #[test] - fn test_enumerator() { - let vec = (0u32..4).map(NSValue::from_value).collect(); - let array = NSArray::from_vec(vec); - - let enumerator = array.object_enumerator(); - assert!(enumerator.count() == 4); - - let enumerator = array.object_enumerator(); - assert!(enumerator.enumerate().all(|(i, obj)| obj.value() == i as u32)); - } - - #[test] - fn test_fast_enumerator() { - let vec = (0u32..4).map(NSValue::from_value).collect(); - let array = NSArray::from_vec(vec); - - let enumerator = array.enumerator(); - assert!(enumerator.count() == 4); - - let enumerator = array.enumerator(); - assert!(enumerator.enumerate().all(|(i, obj)| obj.value() == i as u32)); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/lib.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/lib.rs deleted file mode 100644 index 65bbd01..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/lib.rs +++ /dev/null @@ -1,33 +0,0 @@ -#![crate_name = "objc_foundation"] -#![crate_type = "lib"] - -#[macro_use] -extern crate objc; -extern crate objc_id; -extern crate block; - -pub use self::array::{ - INSArray, INSMutableArray, - NSArray, NSComparisonResult, NSMutableArray, NSRange, - NSMutableSharedArray, NSSharedArray, -}; -pub use self::data::{INSData, INSMutableData, NSData, NSMutableData}; -pub use self::dictionary::{INSDictionary, NSDictionary}; -pub use self::enumerator::{INSFastEnumeration, NSEnumerator, NSFastEnumerator}; -pub use self::object::{INSObject, NSObject}; -pub use self::string::{INSCopying, INSMutableCopying, INSString, NSString}; -pub use self::value::{INSValue, NSValue}; - -#[link(name = "Foundation", kind = "framework")] -extern { } - -#[macro_use] -mod macros; - -mod array; -mod data; -mod dictionary; -mod enumerator; -mod object; -mod string; -mod value; diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/macros.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/macros.rs deleted file mode 100644 index cf06f2e..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/macros.rs +++ /dev/null @@ -1,55 +0,0 @@ -#[macro_export] -macro_rules! object_struct { - ($name:ident) => ( - pub struct $name { - _private: (), - } - - unsafe impl ::objc::Message for $name { } - - impl $crate::INSObject for $name { - fn class() -> &'static ::objc::runtime::Class { - let name = stringify!($name); - match ::objc::runtime::Class::get(name) { - Some(cls) => cls, - None => panic!("Class {} not found", name), - } - } - } - - impl ::std::cmp::PartialEq for $name { - fn eq(&self, other: &Self) -> bool { - use $crate::INSObject; - self.is_equal(other) - } - } - - impl ::std::cmp::Eq for $name { } - - impl ::std::hash::Hash for $name { - fn hash(&self, state: &mut H) where H: ::std::hash::Hasher { - use $crate::INSObject; - self.hash_code().hash(state); - } - } - - impl ::std::fmt::Debug for $name { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - use $crate::{INSObject, INSString}; - ::std::fmt::Debug::fmt(self.description().as_str(), f) - } - } - ); -} - -macro_rules! object_impl { - ($name:ident) => ( - object_impl!($name,); - ); - ($name:ident<$($t:ident),+>) => ( - object_impl!($name, $($t),+); - ); - ($name:ident, $($t:ident),*) => ( - unsafe impl<$($t),*> ::objc::Message for $name<$($t),*> { } - ); -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/object.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/object.rs deleted file mode 100644 index 2f11626..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/object.rs +++ /dev/null @@ -1,91 +0,0 @@ -use std::any::Any; - -use objc::Message; -use objc::runtime::{BOOL, Class, NO}; -use objc_id::{Id, ShareId}; - -use NSString; - -/* - The Sized bound is unfortunate; ideally, objc objects would not be - treated as Sized. However, rust won't allow casting a dynamically-sized type - pointer to an Object pointer, because dynamically-sized types can have fat - pointers (two words) instead of real pointers. - */ -pub trait INSObject : Any + Sized + Message { - fn class() -> &'static Class; - - fn hash_code(&self) -> usize { - unsafe { - msg_send![self, hash] - } - } - - fn is_equal(&self, other: &T) -> bool where T: INSObject { - let result: BOOL = unsafe { - msg_send![self, isEqual:other] - }; - result != NO - } - - fn description(&self) -> ShareId { - unsafe { - let result: *mut NSString = msg_send![self, description]; - Id::from_ptr(result) - } - } - - fn is_kind_of(&self, cls: &Class) -> bool { - let result: BOOL = unsafe { - msg_send![self, isKindOfClass:cls] - }; - result != NO - } - - fn new() -> Id { - let cls = Self::class(); - unsafe { - let obj: *mut Self = msg_send![cls, alloc]; - let obj: *mut Self = msg_send![obj, init]; - Id::from_retained_ptr(obj) - } - } -} - -object_struct!(NSObject); - -#[cfg(test)] -mod tests { - use {INSString, NSString}; - use super::{INSObject, NSObject}; - - #[test] - fn test_is_equal() { - let obj1 = NSObject::new(); - assert!(obj1.is_equal(&*obj1)); - - let obj2 = NSObject::new(); - assert!(!obj1.is_equal(&*obj2)); - } - - #[test] - fn test_hash_code() { - let obj = NSObject::new(); - assert!(obj.hash_code() == obj.hash_code()); - } - - #[test] - fn test_description() { - let obj = NSObject::new(); - let description = obj.description(); - let expected = format!("", &*obj); - assert!(description.as_str() == &*expected); - } - - #[test] - fn test_is_kind_of() { - let obj = NSObject::new(); - assert!(obj.is_kind_of(NSObject::class())); - assert!(!obj.is_kind_of(NSString::class())); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/string.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/string.rs deleted file mode 100644 index 2d21550..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/string.rs +++ /dev/null @@ -1,98 +0,0 @@ -use std::os::raw::c_char; -use std::slice; -use std::str; - -use objc_id::{Id, ShareId}; - -use INSObject; - -pub trait INSCopying : INSObject { - type Output: INSObject; - - fn copy(&self) -> ShareId { - unsafe { - let obj: *mut Self::Output = msg_send![self, copy]; - Id::from_retained_ptr(obj) - } - } -} - -pub trait INSMutableCopying : INSObject { - type Output: INSObject; - - fn mutable_copy(&self) -> Id { - unsafe { - let obj: *mut Self::Output = msg_send![self, mutableCopy]; - Id::from_retained_ptr(obj) - } - } -} - -const UTF8_ENCODING: usize = 4; - -pub trait INSString : INSObject { - fn len(&self) -> usize { - unsafe { - msg_send![self, lengthOfBytesUsingEncoding:UTF8_ENCODING] - } - } - - fn as_str(&self) -> &str { - let bytes = unsafe { - let bytes: *const c_char = msg_send![self, UTF8String]; - bytes as *const u8 - }; - let len = self.len(); - unsafe { - let bytes = slice::from_raw_parts(bytes, len); - str::from_utf8(bytes).unwrap() - } - } - - fn from_str(string: &str) -> Id { - let cls = Self::class(); - unsafe { - let obj: *mut Self = msg_send![cls, alloc]; - let obj: *mut Self = msg_send![obj, initWithBytes:string.as_ptr() - length:string.len() - encoding:UTF8_ENCODING]; - Id::from_retained_ptr(obj) - } - } -} - -object_struct!(NSString); - -impl INSString for NSString { } - -impl INSCopying for NSString { - type Output = NSString; -} - -#[cfg(test)] -mod tests { - use super::{INSCopying, INSString, NSString}; - - #[test] - fn test_utf8() { - let expected = "ประเทศไทย中华Việt Nam"; - let s = NSString::from_str(expected); - assert!(s.len() == expected.len()); - assert!(s.as_str() == expected); - } - - #[test] - fn test_interior_nul() { - let expected = "Hello\0World"; - let s = NSString::from_str(expected); - assert!(s.len() == expected.len()); - assert!(s.as_str() == expected); - } - - #[test] - fn test_copy() { - let s = NSString::from_str("Hello!"); - let copied = s.copy(); - assert!(copied.as_str() == s.as_str()); - } -} diff --git a/third_party/cargo/vendor/objc-foundation-0.1.1/src/value.rs b/third_party/cargo/vendor/objc-foundation-0.1.1/src/value.rs deleted file mode 100644 index 405afe1..0000000 --- a/third_party/cargo/vendor/objc-foundation-0.1.1/src/value.rs +++ /dev/null @@ -1,78 +0,0 @@ -use std::any::Any; -use std::ffi::{CStr, CString}; -use std::marker::PhantomData; -use std::mem; -use std::os::raw::c_char; -use std::str; - -use objc::{Encode, Encoding}; -use objc::runtime::Class; -use objc_id::Id; - -use {INSCopying, INSObject}; - -pub trait INSValue : INSObject { - type Value: 'static + Copy + Encode; - - fn value(&self) -> Self::Value { - assert!(Self::Value::encode() == self.encoding()); - unsafe { - let mut value = mem::uninitialized::(); - let _: () = msg_send![self, getValue:&mut value]; - value - } - } - - fn encoding(&self) -> Encoding { - unsafe { - let result: *const c_char = msg_send![self, objCType]; - let s = CStr::from_ptr(result); - let s = str::from_utf8(s.to_bytes()).unwrap(); - Encoding::from_str(s) - } - } - - fn from_value(value: Self::Value) -> Id { - let cls = Self::class(); - let encoding = CString::new(Self::Value::encode().as_str()).unwrap(); - unsafe { - let obj: *mut Self = msg_send![cls, alloc]; - let obj: *mut Self = msg_send![obj, initWithBytes:&value - objCType:encoding.as_ptr()]; - Id::from_retained_ptr(obj) - } - } -} - -pub struct NSValue { - value: PhantomData, -} - -object_impl!(NSValue); - -impl INSObject for NSValue where T: Any { - fn class() -> &'static Class { - Class::get("NSValue").unwrap() - } -} - -impl INSValue for NSValue where T: Any + Copy + Encode { - type Value = T; -} - -impl INSCopying for NSValue where T: Any { - type Output = NSValue; -} - -#[cfg(test)] -mod tests { - use objc::Encode; - use {INSValue, NSValue}; - - #[test] - fn test_value() { - let val = NSValue::from_value(13u32); - assert!(val.value() == 13); - assert!(u32::encode() == val.encoding()); - } -} diff --git a/third_party/cargo/vendor/objc_id-0.1.1/.cargo-checksum.json b/third_party/cargo/vendor/objc_id-0.1.1/.cargo-checksum.json deleted file mode 100644 index e10f9d7..0000000 --- a/third_party/cargo/vendor/objc_id-0.1.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"7d444ee847aa9b34cbe6cddeaf4001b28be86b28c2855e09c2e7fbfa797a66dd","README.md":"09ef009a08879a901c3bbfa2aeb35813e084d841b721905e5ae2d1cd84f6063c","src/id.rs":"d5034fbefbd59e18cacc00ee20dbab087e2b1cb7a47780789dc25efc83f7918b","src/lib.rs":"fdc6a052f18cc8d96f24848e107c73eac0ddf12882b69f6d40f09f4652c7fc73"},"package":"c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"} \ No newline at end of file diff --git a/third_party/cargo/vendor/objc_id-0.1.1/README.md b/third_party/cargo/vendor/objc_id-0.1.1/README.md deleted file mode 100644 index f1f362b..0000000 --- a/third_party/cargo/vendor/objc_id-0.1.1/README.md +++ /dev/null @@ -1,34 +0,0 @@ -Rust smart pointers for Objective-C reference counting. - -To ensure that Objective-C objects are retained and released -at the proper times, we can use the Id struct. - -To enforce aliasing rules, an `Id` can be either owned or shared; if it is -owned, meaning the `Id` is the only reference to the object, it can be mutably -dereferenced. An owned `Id` can be downgraded to a ShareId -which can be cloned to allow multiple references. - -Weak references may be created using the WeakId struct. - -``` rust -use objc::runtime::{Class, Object}; -use objc_id::{Id, WeakId}; - -let cls = Class::get("NSObject").unwrap(); -let obj: Id = unsafe { - Id::from_retained_ptr(msg_send![cls, new]) -}; -// obj will be released when it goes out of scope - -// share the object so we can clone it -let obj = obj.share(); -let another_ref = obj.clone(); -// dropping our other reference will decrement the retain count -drop(another_ref); - -let weak = WeakId::new(&obj); -assert!(weak.load().is_some()); -// After the object is deallocated, our weak pointer returns none -drop(obj); -assert!(weak.load().is_none()); -``` diff --git a/third_party/cargo/vendor/objc_id-0.1.1/src/id.rs b/third_party/cargo/vendor/objc_id-0.1.1/src/id.rs deleted file mode 100644 index b679f3b..0000000 --- a/third_party/cargo/vendor/objc_id-0.1.1/src/id.rs +++ /dev/null @@ -1,217 +0,0 @@ -use std::any::Any; -use std::fmt; -use std::hash; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; - -use objc::Message; -use objc::rc::{StrongPtr, WeakPtr}; -use objc::runtime::Object; - -/// A type used to mark that a struct owns the object(s) it contains, -/// so it has the sole references to them. -pub enum Owned { } -/// A type used to mark that the object(s) a struct contains are shared, -/// so there may be other references to them. -pub enum Shared { } - -/// A type that marks what type of ownership a struct has over the object(s) -/// it contains; specifically, either `Owned` or `Shared`. -pub trait Ownership: Any { } -impl Ownership for Owned { } -impl Ownership for Shared { } - -/// A pointer type for Objective-C's reference counted objects. -/// -/// The object of an `Id` is retained and sent a `release` message when -/// the `Id` is dropped. -/// -/// An `Id` may be either `Owned` or `Shared`, represented by the types `Id` -/// and `ShareId`, respectively. If owned, there are no other references to the -/// object and the `Id` can be mutably dereferenced. `ShareId`, however, can -/// only be immutably dereferenced because there may be other references to the -/// object, but a `ShareId` can be cloned to provide more references to the -/// object. An owned `Id` can be "downgraded" freely to a `ShareId`, but there -/// is no way to safely upgrade back. -pub struct Id { - ptr: StrongPtr, - item: PhantomData, - own: PhantomData, -} - -impl Id where T: Message, O: Ownership { - unsafe fn new(ptr: StrongPtr) -> Id { - Id { ptr: ptr, item: PhantomData, own: PhantomData } - } - - /// Constructs an `Id` from a pointer to an unretained object and - /// retains it. Panics if the pointer is null. - /// Unsafe because the pointer must be to a valid object and - /// the caller must ensure the ownership is correct. - pub unsafe fn from_ptr(ptr: *mut T) -> Id { - assert!(!ptr.is_null(), "Attempted to construct an Id from a null pointer"); - Id::new(StrongPtr::retain(ptr as *mut Object)) - } - - /// Constructs an `Id` from a pointer to a retained object; this won't - /// retain the pointer, so the caller must ensure the object has a +1 - /// retain count. Panics if the pointer is null. - /// Unsafe because the pointer must be to a valid object and - /// the caller must ensure the ownership is correct. - pub unsafe fn from_retained_ptr(ptr: *mut T) -> Id { - assert!(!ptr.is_null(), "Attempted to construct an Id from a null pointer"); - Id::new(StrongPtr::new(ptr as *mut Object)) - } -} - -impl Id where T: Message { - /// "Downgrade" an owned `Id` to a `ShareId`, allowing it to be cloned. - pub fn share(self) -> ShareId { - let Id { ptr, .. } = self; - unsafe { Id::new(ptr) } - } -} - -impl Clone for Id where T: Message { - fn clone(&self) -> ShareId { - unsafe { - Id::new(self.ptr.clone()) - } - } -} - -unsafe impl Sync for Id where T: Sync { } - -unsafe impl Send for Id where T: Send { } - -unsafe impl Send for Id where T: Sync { } - -impl Deref for Id { - type Target = T; - - fn deref(&self) -> &T { - unsafe { &*(*self.ptr as *mut T) } - } -} - -impl DerefMut for Id { - fn deref_mut(&mut self) -> &mut T { - unsafe { &mut *(*self.ptr as *mut T) } - } -} - -impl PartialEq for Id where T: PartialEq { - fn eq(&self, other: &Id) -> bool { - self.deref() == other.deref() - } - - fn ne(&self, other: &Id) -> bool { - self.deref() != other.deref() - } -} - -impl Eq for Id where T: Eq { } - -impl hash::Hash for Id where T: hash::Hash { - fn hash(&self, state: &mut H) where H: hash::Hasher { - self.deref().hash(state) - } -} - -impl fmt::Debug for Id where T: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.deref().fmt(f) - } -} - -impl fmt::Pointer for Id { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Pointer::fmt(&self.ptr, f) - } -} - -/// A convenient alias for a shared `Id`. -pub type ShareId = Id; - -/// A pointer type for a weak reference to an Objective-C reference counted -/// object. -pub struct WeakId { - ptr: WeakPtr, - item: PhantomData, -} - -impl WeakId where T: Message { - /// Construct a new `WeakId` referencing the given `ShareId`. - pub fn new(obj: &ShareId) -> WeakId { - WeakId { - ptr: obj.ptr.weak(), - item: PhantomData, - } - } - - /// Load a `ShareId` from the `WeakId` if the object still exists. - /// Returns `None` if the object has been deallocated. - pub fn load(&self) -> Option> { - let obj = self.ptr.load(); - if obj.is_null() { - None - } else { - Some(unsafe { Id::new(obj) }) - } - } -} - -unsafe impl Sync for WeakId where T: Sync { } - -unsafe impl Send for WeakId where T: Sync { } - -#[cfg(test)] -mod tests { - use objc::runtime::Object; - use super::{Id, ShareId, WeakId}; - - fn retain_count(obj: &Object) -> usize { - unsafe { msg_send![obj, retainCount] } - } - - #[test] - fn test_clone() { - let cls = class!(NSObject); - let obj: Id = unsafe { - let obj: *mut Object = msg_send![cls, alloc]; - let obj: *mut Object = msg_send![obj, init]; - Id::from_retained_ptr(obj) - }; - assert!(retain_count(&obj) == 1); - - let obj = obj.share(); - assert!(retain_count(&obj) == 1); - - let cloned = obj.clone(); - assert!(retain_count(&cloned) == 2); - assert!(retain_count(&obj) == 2); - - drop(obj); - assert!(retain_count(&cloned) == 1); - } - - #[test] - fn test_weak() { - let cls = class!(NSObject); - let obj: ShareId = unsafe { - let obj: *mut Object = msg_send![cls, alloc]; - let obj: *mut Object = msg_send![obj, init]; - Id::from_retained_ptr(obj) - }; - - let weak = WeakId::new(&obj); - let strong = weak.load().unwrap(); - let strong_ptr: *const Object = &*strong; - let obj_ptr: *const Object = &*obj; - assert!(strong_ptr == obj_ptr); - drop(strong); - - drop(obj); - assert!(weak.load().is_none()); - } -} diff --git a/third_party/cargo/vendor/objc_id-0.1.1/src/lib.rs b/third_party/cargo/vendor/objc_id-0.1.1/src/lib.rs deleted file mode 100644 index d03b354..0000000 --- a/third_party/cargo/vendor/objc_id-0.1.1/src/lib.rs +++ /dev/null @@ -1,47 +0,0 @@ -/*! -Rust smart pointers for Objective-C reference counting. - -To ensure that Objective-C objects are retained and released -at the proper times, we can use the [`Id`](struct.Id.html) struct. - -To enforce aliasing rules, an `Id` can be either owned or shared; if it is -owned, meaning the `Id` is the only reference to the object, it can be mutably -dereferenced. An owned `Id` can be downgraded to a [`ShareId`](type.ShareId.html) -which can be cloned to allow multiple references. - -Weak references may be created using the [`WeakId`](struct.WeakId.html) struct. - -``` -# #[macro_use] extern crate objc; -# extern crate objc_id; -use objc::runtime::{Class, Object}; -use objc_id::{Id, WeakId}; - -# fn main() { -let cls = Class::get("NSObject").unwrap(); -let obj: Id = unsafe { - Id::from_retained_ptr(msg_send![cls, new]) -}; -// obj will be released when it goes out of scope - -// share the object so we can clone it -let obj = obj.share(); -let another_ref = obj.clone(); -// dropping our other reference will decrement the retain count -drop(another_ref); - -let weak = WeakId::new(&obj); -assert!(weak.load().is_some()); -// After the object is deallocated, our weak pointer returns none -drop(obj); -assert!(weak.load().is_none()); -# } -``` -*/ - -#[macro_use] -extern crate objc; - -pub use id::{Id, Owned, Ownership, Shared, ShareId, WeakId}; - -mod id; diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/.cargo-checksum.json b/third_party/cargo/vendor/owning_ref-0.4.1/.cargo-checksum.json deleted file mode 100644 index 274171b..0000000 --- a/third_party/cargo/vendor/owning_ref-0.4.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"9a3880e4d5435ca03c0197c45d4ce6b6db6d3fb7eda855f297bafc2ec28af836","Cargo.toml":"91184e6b143ddf621fe7e6757fb28d8eb4c0e01f541fbd0dc440bf076ebfd20d","LICENSE":"90bc15ed094593083fd129fdd1a03607be80fe8839c5564616a5961ab7f7a194","README.md":"0dfea39ad1662ed0a61bb1453eafc207a53dfe577e7846c87d3a5161574fdb12","src/lib.rs":"2e423e210bf2e3ee5e4c426b9a3c9b7756fc434beff1ccf9afa48704e4ac993d"},"package":"6ff55baddef9e4ad00f88b6c743a2a8062d4c6ade126c2a528644b8e444d52ce"} \ No newline at end of file diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/CHANGELOG.md b/third_party/cargo/vendor/owning_ref-0.4.1/CHANGELOG.md deleted file mode 100644 index a5d24e8..0000000 --- a/third_party/cargo/vendor/owning_ref-0.4.1/CHANGELOG.md +++ /dev/null @@ -1,8 +0,0 @@ -# Changelog - -## [0.4.1] - 2020-02-27 -### Added -- `map_with_owner` (#51) - -### Changed -- Use dyn for trait objects (#53) diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/README.md b/third_party/cargo/vendor/owning_ref-0.4.1/README.md deleted file mode 100644 index ad32ac2..0000000 --- a/third_party/cargo/vendor/owning_ref-0.4.1/README.md +++ /dev/null @@ -1,64 +0,0 @@ -[![Build Status](https://travis-ci.org/Kimundi/owning-ref-rs.svg)](https://travis-ci.org/Kimundi/owning-ref-rs) -[![Crate](https://img.shields.io/crates/v/owning_ref.svg)](https://crates.io/crates/owning_ref) -[![Docs](https://docs.rs/owning_ref/badge.svg)](https://docs.rs/owning_ref) - -owning-ref-rs -============== - -A library for creating references that carry their owner with them. - -This can sometimes be useful because Rust borrowing rules normally prevent -moving a type that has been borrowed from. For example, this kind of code gets rejected: - -```rust -fn return_owned_and_referenced<'a>() -> (Vec, &'a [u8]) { - let v = vec![1, 2, 3, 4]; - let s = &v[1..3]; - (v, s) -} -``` - -This library enables this safe usage by keeping the owner and the reference -bundled together in a wrapper type that ensure that lifetime constraint: - -```rust -fn return_owned_and_referenced() -> OwningRef, [u8]> { - let v = vec![1, 2, 3, 4]; - let or = OwningRef::new(v); - let or = or.map(|v| &v[1..3]); - or -} -``` - -## Getting Started - -To get started, add the following to `Cargo.toml`. - -```toml -owning_ref = "0.4.1" -``` - -...and see the [docs](http://kimundi.github.io/owning-ref-rs/owning_ref/index.html) for how to use it. - - -## Example - -```rust -extern crate owning_ref; -use owning_ref::BoxRef; - -fn main() { - // Create an array owned by a Box. - let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>; - - // Transfer into a BoxRef. - let arr: BoxRef<[i32]> = BoxRef::new(arr); - assert_eq!(&*arr, &[1, 2, 3, 4]); - - // We can slice the array without losing ownership or changing type. - let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]); - assert_eq!(&*arr, &[2, 3]); - - // Also works for Arc, Rc, String and Vec! -} -``` diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/src/lib.rs b/third_party/cargo/vendor/owning_ref-0.4.1/src/lib.rs deleted file mode 100644 index fa2f15a..0000000 --- a/third_party/cargo/vendor/owning_ref-0.4.1/src/lib.rs +++ /dev/null @@ -1,2016 +0,0 @@ -#![warn(missing_docs)] - -/*! -# An owning reference. - -This crate provides the _owning reference_ types `OwningRef` and `OwningRefMut` -that enables it to bundle a reference together with the owner of the data it points to. -This allows moving and dropping of a `OwningRef` without needing to recreate the reference. - -This can sometimes be useful because Rust borrowing rules normally prevent -moving a type that has been moved from. For example, this kind of code gets rejected: - -```rust,ignore -fn return_owned_and_referenced<'a>() -> (Vec, &'a [u8]) { - let v = vec![1, 2, 3, 4]; - let s = &v[1..3]; - (v, s) -} -``` - -Even though, from a memory-layout point of view, this can be entirely safe -if the new location of the vector still lives longer than the lifetime `'a` -of the reference because the backing allocation of the vector does not change. - -This library enables this safe usage by keeping the owner and the reference -bundled together in a wrapper type that ensure that lifetime constraint: - -```rust -# extern crate owning_ref; -# use owning_ref::OwningRef; -# fn main() { -fn return_owned_and_referenced() -> OwningRef, [u8]> { - let v = vec![1, 2, 3, 4]; - let or = OwningRef::new(v); - let or = or.map(|v| &v[1..3]); - or -} -# } -``` - -It works by requiring owner types to dereference to stable memory locations -and preventing mutable access to root containers, which in practice requires heap allocation -as provided by `Box`, `Rc`, etc. - -Also provided are typedefs for common owner type combinations, -which allow for less verbose type signatures. For example, `BoxRef` instead of `OwningRef, T>`. - -The crate also provides the more advanced `OwningHandle` type, -which allows more freedom in bundling a dependent handle object -along with the data it depends on, at the cost of some unsafe needed in the API. -See the documentation around `OwningHandle` for more details. - -# Examples - -## Basics - -``` -extern crate owning_ref; -use owning_ref::BoxRef; - -fn main() { - // Create an array owned by a Box. - let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>; - - // Transfer into a BoxRef. - let arr: BoxRef<[i32]> = BoxRef::new(arr); - assert_eq!(&*arr, &[1, 2, 3, 4]); - - // We can slice the array without losing ownership or changing type. - let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]); - assert_eq!(&*arr, &[2, 3]); - - // Also works for Arc, Rc, String and Vec! -} -``` - -## Caching a reference to a struct field - -``` -extern crate owning_ref; -use owning_ref::BoxRef; - -fn main() { - struct Foo { - tag: u32, - x: u16, - y: u16, - z: u16, - } - let foo = Foo { tag: 1, x: 100, y: 200, z: 300 }; - - let or = BoxRef::new(Box::new(foo)).map(|foo| { - match foo.tag { - 0 => &foo.x, - 1 => &foo.y, - 2 => &foo.z, - _ => panic!(), - } - }); - - assert_eq!(*or, 200); -} -``` - -## Caching a reference to an entry in a vector - -``` -extern crate owning_ref; -use owning_ref::VecRef; - -fn main() { - let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]); - assert_eq!(*v, 4); -} -``` - -## Caching a subslice of a String - -``` -extern crate owning_ref; -use owning_ref::StringRef; - -fn main() { - let s = StringRef::new("hello world".to_owned()) - .map(|s| s.split(' ').nth(1).unwrap()); - - assert_eq!(&*s, "world"); -} -``` - -## Reference counted slices that share ownership of the backing storage - -``` -extern crate owning_ref; -use owning_ref::RcRef; -use std::rc::Rc; - -fn main() { - let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>); - assert_eq!(&*rc, &[1, 2, 3, 4]); - - let rc_a: RcRef<[i32]> = rc.clone().map(|s| &s[0..2]); - let rc_b = rc.clone().map(|s| &s[1..3]); - let rc_c = rc.clone().map(|s| &s[2..4]); - assert_eq!(&*rc_a, &[1, 2]); - assert_eq!(&*rc_b, &[2, 3]); - assert_eq!(&*rc_c, &[3, 4]); - - let rc_c_a = rc_c.clone().map(|s| &s[1]); - assert_eq!(&*rc_c_a, &4); -} -``` - -## Atomic reference counted slices that share ownership of the backing storage - -``` -extern crate owning_ref; -use owning_ref::ArcRef; -use std::sync::Arc; - -fn main() { - use std::thread; - - fn par_sum(rc: ArcRef<[i32]>) -> i32 { - if rc.len() == 0 { - return 0; - } else if rc.len() == 1 { - return rc[0]; - } - let mid = rc.len() / 2; - let left = rc.clone().map(|s| &s[..mid]); - let right = rc.map(|s| &s[mid..]); - - let left = thread::spawn(move || par_sum(left)); - let right = thread::spawn(move || par_sum(right)); - - left.join().unwrap() + right.join().unwrap() - } - - let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]); - let rc: ArcRef<[i32]> = rc.into(); - - assert_eq!(par_sum(rc), 10); -} -``` - -## References into RAII locks - -``` -extern crate owning_ref; -use owning_ref::RefRef; -use std::cell::{RefCell, Ref}; - -fn main() { - let refcell = RefCell::new((1, 2, 3, 4)); - // Also works with Mutex and RwLock - - let refref = { - let refref = RefRef::new(refcell.borrow()).map(|x| &x.3); - assert_eq!(*refref, 4); - - // We move the RAII lock and the reference to one of - // the subfields in the data it guards here: - refref - }; - - assert_eq!(*refref, 4); - - drop(refref); - - assert_eq!(*refcell.borrow(), (1, 2, 3, 4)); -} -``` - -## Mutable reference - -When the owned container implements `DerefMut`, it is also possible to make -a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`) - -``` -extern crate owning_ref; -use owning_ref::RefMutRefMut; -use std::cell::{RefCell, RefMut}; - -fn main() { - let refcell = RefCell::new((1, 2, 3, 4)); - - let mut refmut_refmut = { - let mut refmut_refmut = RefMutRefMut::new(refcell.borrow_mut()).map_mut(|x| &mut x.3); - assert_eq!(*refmut_refmut, 4); - *refmut_refmut *= 2; - - refmut_refmut - }; - - assert_eq!(*refmut_refmut, 8); - *refmut_refmut *= 2; - - drop(refmut_refmut); - - assert_eq!(*refcell.borrow(), (1, 2, 3, 16)); -} -``` -*/ - -extern crate stable_deref_trait; -pub use stable_deref_trait::{StableDeref as StableAddress, CloneStableDeref as CloneStableAddress}; - -/// An owning reference. -/// -/// This wraps an owner `O` and a reference `&T` pointing -/// at something reachable from `O::Target` while keeping -/// the ability to move `self` around. -/// -/// The owner is usually a pointer that points at some base type. -/// -/// For more details and examples, see the module and method docs. -pub struct OwningRef { - owner: O, - reference: *const T, -} - -/// An mutable owning reference. -/// -/// This wraps an owner `O` and a reference `&mut T` pointing -/// at something reachable from `O::Target` while keeping -/// the ability to move `self` around. -/// -/// The owner is usually a pointer that points at some base type. -/// -/// For more details and examples, see the module and method docs. -pub struct OwningRefMut { - owner: O, - reference: *mut T, -} - -/// Helper trait for an erased concrete type an owner dereferences to. -/// This is used in form of a trait object for keeping -/// something around to (virtually) call the destructor. -pub trait Erased {} -impl Erased for T {} - -/// Helper trait for erasing the concrete type of what an owner derferences to, -/// for example `Box -> Box`. This would be unneeded with -/// higher kinded types support in the language. -pub unsafe trait IntoErased<'a> { - /// Owner with the dereference type substituted to `Erased`. - type Erased; - /// Perform the type erasure. - fn into_erased(self) -> Self::Erased; -} - -///////////////////////////////////////////////////////////////////////////// -// OwningRef -///////////////////////////////////////////////////////////////////////////// - -impl OwningRef { - /// Creates a new owning reference from a owner - /// initialized to the direct dereference of it. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRef; - /// - /// fn main() { - /// let owning_ref = OwningRef::new(Box::new(42)); - /// assert_eq!(*owning_ref, 42); - /// } - /// ``` - pub fn new(o: O) -> Self - where O: StableAddress, - O: Deref, - { - OwningRef { - reference: &*o, - owner: o, - } - } - - /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait. - /// Instead, the caller is responsible to make the same promises as implementing the trait. - /// - /// This is useful for cases where coherence rules prevents implementing the trait - /// without adding a dependency to this crate in a third-party library. - pub unsafe fn new_assert_stable_address(o: O) -> Self - where O: Deref, - { - OwningRef { - reference: &*o, - owner: o, - } - } - - /// Converts `self` into a new owning reference that points at something reachable - /// from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRef; - /// - /// fn main() { - /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref = owning_ref.map(|array| &array[2]); - /// assert_eq!(*owning_ref, 3); - /// } - /// ``` - pub fn map(self, f: F) -> OwningRef - where O: StableAddress, - F: FnOnce(&T) -> &U - { - OwningRef { - reference: f(&self), - owner: self.owner, - } - } - - /// Converts `self` into a new owning reference that points at something reachable - /// from the previous one or from the owner itself. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U` or from the owner `O`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRef; - /// - /// fn main() { - /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); - /// let owning_ref = owning_ref.map(|array| &array[2]); - /// assert_eq!(*owning_ref, 3); - /// - /// // create a owning reference that points at the - /// // second element of the array from the owning ref that was pointing to the third - /// let owning_ref = owning_ref.map_with_owner(|array, _prev| &array[1]); - /// assert_eq!(*owning_ref, 2); - /// } - /// ``` - pub fn map_with_owner(self, f: F) -> OwningRef - where O: StableAddress, - F: for<'a> FnOnce(&'a O, &'a T) -> &'a U - { - OwningRef { - reference: f(&self.owner, &self), - owner: self.owner, - } - } - - /// Tries to convert `self` into a new owning reference that points - /// at something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRef; - /// - /// fn main() { - /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref = owning_ref.try_map(|array| { - /// if array[2] == 3 { Ok(&array[2]) } else { Err(()) } - /// }); - /// assert_eq!(*owning_ref.unwrap(), 3); - /// } - /// ``` - pub fn try_map(self, f: F) -> Result, E> - where O: StableAddress, - F: FnOnce(&T) -> Result<&U, E> - { - Ok(OwningRef { - reference: f(&self)?, - owner: self.owner, - }) - } - - /// Tries to convert `self` into a new owning reference that points - /// at something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRef; - /// - /// fn main() { - /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); - /// let owning_ref = owning_ref.map(|array| &array[2]); - /// - /// // create a owning reference that points at the - /// // second element of the array from the owning ref that was pointing to the third - /// let owning_ref = owning_ref.try_map_with_owner(|array, _prev| { - /// if array[1] == 2 { Ok(&array[1]) } else { Err(()) } - /// }); - /// assert_eq!(*owning_ref.unwrap(), 2); - /// } - /// ``` - pub fn try_map_with_owner(self, f: F) -> Result, E> - where O: StableAddress, - F: for<'a> FnOnce(&'a O, &'a T) -> Result<&'a U, E> - { - Ok(OwningRef { - reference: f(&self.owner, &self)?, - owner: self.owner, - }) - } - - /// Converts `self` into a new owning reference with a different owner type. - /// - /// The new owner type needs to still contain the original owner in some way - /// so that the reference into it remains valid. This function is marked unsafe - /// because the user needs to manually uphold this guarantee. - pub unsafe fn map_owner(self, f: F) -> OwningRef - where O: StableAddress, - P: StableAddress, - F: FnOnce(O) -> P - { - OwningRef { - reference: self.reference, - owner: f(self.owner), - } - } - - /// Converts `self` into a new owning reference where the owner is wrapped - /// in an additional `Box`. - /// - /// This can be used to safely erase the owner of any `OwningRef` - /// to a `OwningRef, T>`. - pub fn map_owner_box(self) -> OwningRef, T> { - OwningRef { - reference: self.reference, - owner: Box::new(self.owner), - } - } - - /// Erases the concrete base type of the owner with a trait object. - /// - /// This allows mixing of owned references with different owner base types. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::{OwningRef, Erased}; - /// - /// fn main() { - /// // NB: Using the concrete types here for explicitnes. - /// // For less verbose code type aliases like `BoxRef` are provided. - /// - /// let owning_ref_a: OwningRef, [i32; 4]> - /// = OwningRef::new(Box::new([1, 2, 3, 4])); - /// - /// let owning_ref_b: OwningRef>, Vec<(i32, bool)>> - /// = OwningRef::new(Box::new(vec![(0, false), (1, true)])); - /// - /// let owning_ref_a: OwningRef, i32> - /// = owning_ref_a.map(|a| &a[0]); - /// - /// let owning_ref_b: OwningRef>, i32> - /// = owning_ref_b.map(|a| &a[1].0); - /// - /// let owning_refs: [OwningRef, i32>; 2] - /// = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()]; - /// - /// assert_eq!(*owning_refs[0], 1); - /// assert_eq!(*owning_refs[1], 1); - /// } - /// ``` - pub fn erase_owner<'a>(self) -> OwningRef - where O: IntoErased<'a>, - { - OwningRef { - reference: self.reference, - owner: self.owner.into_erased(), - } - } - - // TODO: wrap_owner - - /// A reference to the underlying owner. - pub fn as_owner(&self) -> &O { - &self.owner - } - - /// Discards the reference and retrieves the owner. - pub fn into_owner(self) -> O { - self.owner - } -} - -impl OwningRefMut { - /// Creates a new owning reference from a owner - /// initialized to the direct dereference of it. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRefMut; - /// - /// fn main() { - /// let owning_ref_mut = OwningRefMut::new(Box::new(42)); - /// assert_eq!(*owning_ref_mut, 42); - /// } - /// ``` - pub fn new(mut o: O) -> Self - where O: StableAddress, - O: DerefMut, - { - OwningRefMut { - reference: &mut *o, - owner: o, - } - } - - /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait. - /// Instead, the caller is responsible to make the same promises as implementing the trait. - /// - /// This is useful for cases where coherence rules prevents implementing the trait - /// without adding a dependency to this crate in a third-party library. - pub unsafe fn new_assert_stable_address(mut o: O) -> Self - where O: DerefMut, - { - OwningRefMut { - reference: &mut *o, - owner: o, - } - } - - /// Converts `self` into a new _shared_ owning reference that points at - /// something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRefMut; - /// - /// fn main() { - /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref = owning_ref_mut.map(|array| &array[2]); - /// assert_eq!(*owning_ref, 3); - /// } - /// ``` - pub fn map(mut self, f: F) -> OwningRef - where O: StableAddress, - F: FnOnce(&mut T) -> &U - { - OwningRef { - reference: f(&mut self), - owner: self.owner, - } - } - - /// Converts `self` into a new _mutable_ owning reference that points at - /// something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRefMut; - /// - /// fn main() { - /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]); - /// assert_eq!(*owning_ref_mut, 3); - /// } - /// ``` - pub fn map_mut(mut self, f: F) -> OwningRefMut - where O: StableAddress, - F: FnOnce(&mut T) -> &mut U - { - OwningRefMut { - reference: f(&mut self), - owner: self.owner, - } - } - - /// Tries to convert `self` into a new _shared_ owning reference that points - /// at something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRefMut; - /// - /// fn main() { - /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref = owning_ref_mut.try_map(|array| { - /// if array[2] == 3 { Ok(&array[2]) } else { Err(()) } - /// }); - /// assert_eq!(*owning_ref.unwrap(), 3); - /// } - /// ``` - pub fn try_map(mut self, f: F) -> Result, E> - where O: StableAddress, - F: FnOnce(&mut T) -> Result<&U, E> - { - Ok(OwningRef { - reference: f(&mut self)?, - owner: self.owner, - }) - } - - /// Tries to convert `self` into a new _mutable_ owning reference that points - /// at something reachable from the previous one. - /// - /// This can be a reference to a field of `U`, something reachable from a field of - /// `U`, or even something unrelated with a `'static` lifetime. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::OwningRefMut; - /// - /// fn main() { - /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); - /// - /// // create a owning reference that points at the - /// // third element of the array. - /// let owning_ref_mut = owning_ref_mut.try_map_mut(|array| { - /// if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) } - /// }); - /// assert_eq!(*owning_ref_mut.unwrap(), 3); - /// } - /// ``` - pub fn try_map_mut(mut self, f: F) -> Result, E> - where O: StableAddress, - F: FnOnce(&mut T) -> Result<&mut U, E> - { - Ok(OwningRefMut { - reference: f(&mut self)?, - owner: self.owner, - }) - } - - /// Converts `self` into a new owning reference with a different owner type. - /// - /// The new owner type needs to still contain the original owner in some way - /// so that the reference into it remains valid. This function is marked unsafe - /// because the user needs to manually uphold this guarantee. - pub unsafe fn map_owner(self, f: F) -> OwningRefMut - where O: StableAddress, - P: StableAddress, - F: FnOnce(O) -> P - { - OwningRefMut { - reference: self.reference, - owner: f(self.owner), - } - } - - /// Converts `self` into a new owning reference where the owner is wrapped - /// in an additional `Box`. - /// - /// This can be used to safely erase the owner of any `OwningRefMut` - /// to a `OwningRefMut, T>`. - pub fn map_owner_box(self) -> OwningRefMut, T> { - OwningRefMut { - reference: self.reference, - owner: Box::new(self.owner), - } - } - - /// Erases the concrete base type of the owner with a trait object. - /// - /// This allows mixing of owned references with different owner base types. - /// - /// # Example - /// ``` - /// extern crate owning_ref; - /// use owning_ref::{OwningRefMut, Erased}; - /// - /// fn main() { - /// // NB: Using the concrete types here for explicitnes. - /// // For less verbose code type aliases like `BoxRef` are provided. - /// - /// let owning_ref_mut_a: OwningRefMut, [i32; 4]> - /// = OwningRefMut::new(Box::new([1, 2, 3, 4])); - /// - /// let owning_ref_mut_b: OwningRefMut>, Vec<(i32, bool)>> - /// = OwningRefMut::new(Box::new(vec![(0, false), (1, true)])); - /// - /// let owning_ref_mut_a: OwningRefMut, i32> - /// = owning_ref_mut_a.map_mut(|a| &mut a[0]); - /// - /// let owning_ref_mut_b: OwningRefMut>, i32> - /// = owning_ref_mut_b.map_mut(|a| &mut a[1].0); - /// - /// let owning_refs_mut: [OwningRefMut, i32>; 2] - /// = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()]; - /// - /// assert_eq!(*owning_refs_mut[0], 1); - /// assert_eq!(*owning_refs_mut[1], 1); - /// } - /// ``` - pub fn erase_owner<'a>(self) -> OwningRefMut - where O: IntoErased<'a>, - { - OwningRefMut { - reference: self.reference, - owner: self.owner.into_erased(), - } - } - - // TODO: wrap_owner - - /// A reference to the underlying owner. - pub fn as_owner(&self) -> &O { - &self.owner - } - - /// A mutable reference to the underlying owner. - pub fn as_owner_mut(&mut self) -> &mut O { - &mut self.owner - } - - /// Discards the reference and retrieves the owner. - pub fn into_owner(self) -> O { - self.owner - } -} - -///////////////////////////////////////////////////////////////////////////// -// OwningHandle -///////////////////////////////////////////////////////////////////////////// - -use std::ops::{Deref, DerefMut}; - -/// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows -/// consumers to pass around an owned object and a dependent reference, -/// `OwningHandle` contains an owned object and a dependent _object_. -/// -/// `OwningHandle` can encapsulate a `RefMut` along with its associated -/// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`. -/// However, the API is completely generic and there are no restrictions on -/// what types of owning and dependent objects may be used. -/// -/// `OwningHandle` is created by passing an owner object (which dereferences -/// to a stable address) along with a callback which receives a pointer to -/// that stable location. The callback may then dereference the pointer and -/// mint a dependent object, with the guarantee that the returned object will -/// not outlive the referent of the pointer. -/// -/// Since the callback needs to dereference a raw pointer, it requires `unsafe` -/// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is -/// implemented for common data structures. Types that implement `ToHandle` can -/// be wrapped into an `OwningHandle` without passing a callback. -pub struct OwningHandle - where O: StableAddress, H: Deref, -{ - handle: H, - _owner: O, -} - -impl Deref for OwningHandle - where O: StableAddress, H: Deref, -{ - type Target = H::Target; - fn deref(&self) -> &H::Target { - self.handle.deref() - } -} - -unsafe impl StableAddress for OwningHandle - where O: StableAddress, H: StableAddress, -{} - -impl DerefMut for OwningHandle - where O: StableAddress, H: DerefMut, -{ - fn deref_mut(&mut self) -> &mut H::Target { - self.handle.deref_mut() - } -} - -/// Trait to implement the conversion of owner to handle for common types. -pub trait ToHandle { - /// The type of handle to be encapsulated by the OwningHandle. - type Handle: Deref; - - /// Given an appropriately-long-lived pointer to ourselves, create a - /// handle to be encapsulated by the `OwningHandle`. - unsafe fn to_handle(x: *const Self) -> Self::Handle; -} - -/// Trait to implement the conversion of owner to mutable handle for common types. -pub trait ToHandleMut { - /// The type of handle to be encapsulated by the OwningHandle. - type HandleMut: DerefMut; - - /// Given an appropriately-long-lived pointer to ourselves, create a - /// mutable handle to be encapsulated by the `OwningHandle`. - unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut; -} - -impl OwningHandle - where O: StableAddress, O::Target: ToHandle, H: Deref, -{ - /// Create a new `OwningHandle` for a type that implements `ToHandle`. For types - /// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts - /// a callback to perform the conversion. - pub fn new(o: O) -> Self { - OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) }) - } -} - -impl OwningHandle - where O: StableAddress, O::Target: ToHandleMut, H: DerefMut, -{ - /// Create a new mutable `OwningHandle` for a type that implements `ToHandleMut`. - pub fn new_mut(o: O) -> Self { - OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) }) - } -} - -impl OwningHandle - where O: StableAddress, H: Deref, -{ - /// Create a new OwningHandle. The provided callback will be invoked with - /// a pointer to the object owned by `o`, and the returned value is stored - /// as the object to which this `OwningHandle` will forward `Deref` and - /// `DerefMut`. - pub fn new_with_fn(o: O, f: F) -> Self - where F: FnOnce(*const O::Target) -> H - { - let h: H; - { - h = f(o.deref() as *const O::Target); - } - - OwningHandle { - handle: h, - _owner: o, - } - } - - /// Create a new OwningHandle. The provided callback will be invoked with - /// a pointer to the object owned by `o`, and the returned value is stored - /// as the object to which this `OwningHandle` will forward `Deref` and - /// `DerefMut`. - pub fn try_new(o: O, f: F) -> Result - where F: FnOnce(*const O::Target) -> Result - { - let h: H; - { - h = f(o.deref() as *const O::Target)?; - } - - Ok(OwningHandle { - handle: h, - _owner: o, - }) - } - - /// A getter for the underlying owner. - pub fn as_owner(&self) -> &O { - &self._owner - } - - /// Discards the dependent object and returns the owner. - pub fn into_owner(self) -> O { - self._owner - } -} - -///////////////////////////////////////////////////////////////////////////// -// std traits -///////////////////////////////////////////////////////////////////////////// - -use std::convert::From; -use std::fmt::{self, Debug}; -use std::marker::{Send, Sync}; -use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering}; -use std::hash::{Hash, Hasher}; -use std::borrow::Borrow; - -impl Deref for OwningRef { - type Target = T; - - fn deref(&self) -> &T { - unsafe { - &*self.reference - } - } -} - -impl Deref for OwningRefMut { - type Target = T; - - fn deref(&self) -> &T { - unsafe { - &*self.reference - } - } -} - -impl DerefMut for OwningRefMut { - fn deref_mut(&mut self) -> &mut T { - unsafe { - &mut *self.reference - } - } -} - -unsafe impl StableAddress for OwningRef {} - -unsafe impl StableAddress for OwningRefMut {} - -impl AsRef for OwningRef { - fn as_ref(&self) -> &T { - &*self - } -} - -impl AsRef for OwningRefMut { - fn as_ref(&self) -> &T { - &*self - } -} - -impl AsMut for OwningRefMut { - fn as_mut(&mut self) -> &mut T { - &mut *self - } -} - -impl Borrow for OwningRef { - fn borrow(&self) -> &T { - &*self - } -} - -impl From for OwningRef - where O: StableAddress, - O: Deref, -{ - fn from(owner: O) -> Self { - OwningRef::new(owner) - } -} - -impl From for OwningRefMut - where O: StableAddress, - O: DerefMut -{ - fn from(owner: O) -> Self { - OwningRefMut::new(owner) - } -} - -impl From> for OwningRef - where O: StableAddress, - O: DerefMut -{ - fn from(other: OwningRefMut) -> Self { - OwningRef { - owner: other.owner, - reference: other.reference, - } - } -} - -// ^ FIXME: Is a Into impl for calling into_owner() possible as well? - -impl Debug for OwningRef - where O: Debug, - T: Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, - "OwningRef {{ owner: {:?}, reference: {:?} }}", - self.as_owner(), - &**self) - } -} - -impl Debug for OwningRefMut - where O: Debug, - T: Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, - "OwningRefMut {{ owner: {:?}, reference: {:?} }}", - self.as_owner(), - &**self) - } -} - -impl Clone for OwningRef - where O: CloneStableAddress, -{ - fn clone(&self) -> Self { - OwningRef { - owner: self.owner.clone(), - reference: self.reference, - } - } -} - -unsafe impl CloneStableAddress for OwningRef - where O: CloneStableAddress {} - -unsafe impl Send for OwningRef - where O: Send, for<'a> (&'a T): Send {} -unsafe impl Sync for OwningRef - where O: Sync, for<'a> (&'a T): Sync {} - -unsafe impl Send for OwningRefMut - where O: Send, for<'a> (&'a mut T): Send {} -unsafe impl Sync for OwningRefMut - where O: Sync, for<'a> (&'a mut T): Sync {} - -impl Debug for dyn Erased { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(f, "",) - } -} - -impl PartialEq for OwningRef where T: PartialEq { - fn eq(&self, other: &Self) -> bool { - (&*self as &T).eq(&*other as &T) - } -} - -impl Eq for OwningRef where T: Eq {} - -impl PartialOrd for OwningRef where T: PartialOrd { - fn partial_cmp(&self, other: &Self) -> Option { - (&*self as &T).partial_cmp(&*other as &T) - } -} - -impl Ord for OwningRef where T: Ord { - fn cmp(&self, other: &Self) -> Ordering { - (&*self as &T).cmp(&*other as &T) - } -} - -impl Hash for OwningRef where T: Hash { - fn hash(&self, state: &mut H) { - (&*self as &T).hash(state); - } -} - -impl PartialEq for OwningRefMut where T: PartialEq { - fn eq(&self, other: &Self) -> bool { - (&*self as &T).eq(&*other as &T) - } -} - -impl Eq for OwningRefMut where T: Eq {} - -impl PartialOrd for OwningRefMut where T: PartialOrd { - fn partial_cmp(&self, other: &Self) -> Option { - (&*self as &T).partial_cmp(&*other as &T) - } -} - -impl Ord for OwningRefMut where T: Ord { - fn cmp(&self, other: &Self) -> Ordering { - (&*self as &T).cmp(&*other as &T) - } -} - -impl Hash for OwningRefMut where T: Hash { - fn hash(&self, state: &mut H) { - (&*self as &T).hash(state); - } -} - -///////////////////////////////////////////////////////////////////////////// -// std types integration and convenience type defs -///////////////////////////////////////////////////////////////////////////// - -use std::boxed::Box; -use std::rc::Rc; -use std::sync::Arc; -use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; -use std::cell::{Ref, RefCell, RefMut}; - -impl ToHandle for RefCell { - type Handle = Ref<'static, T>; - unsafe fn to_handle(x: *const Self) -> Self::Handle { (*x).borrow() } -} - -impl ToHandleMut for RefCell { - type HandleMut = RefMut<'static, T>; - unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() } -} - -// NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision -// about which handle creation to use (i.e. read() vs try_read()) as well as -// what to do with error results. - -/// Typedef of a owning reference that uses a `Box` as the owner. -pub type BoxRef = OwningRef, U>; -/// Typedef of a owning reference that uses a `Vec` as the owner. -pub type VecRef = OwningRef, U>; -/// Typedef of a owning reference that uses a `String` as the owner. -pub type StringRef = OwningRef; - -/// Typedef of a owning reference that uses a `Rc` as the owner. -pub type RcRef = OwningRef, U>; -/// Typedef of a owning reference that uses a `Arc` as the owner. -pub type ArcRef = OwningRef, U>; - -/// Typedef of a owning reference that uses a `Ref` as the owner. -pub type RefRef<'a, T, U = T> = OwningRef, U>; -/// Typedef of a owning reference that uses a `RefMut` as the owner. -pub type RefMutRef<'a, T, U = T> = OwningRef, U>; -/// Typedef of a owning reference that uses a `MutexGuard` as the owner. -pub type MutexGuardRef<'a, T, U = T> = OwningRef, U>; -/// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner. -pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef, U>; -/// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner. -pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef, U>; - -/// Typedef of a mutable owning reference that uses a `Box` as the owner. -pub type BoxRefMut = OwningRefMut, U>; -/// Typedef of a mutable owning reference that uses a `Vec` as the owner. -pub type VecRefMut = OwningRefMut, U>; -/// Typedef of a mutable owning reference that uses a `String` as the owner. -pub type StringRefMut = OwningRefMut; - -/// Typedef of a mutable owning reference that uses a `RefMut` as the owner. -pub type RefMutRefMut<'a, T, U = T> = OwningRefMut, U>; -/// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner. -pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut, U>; -/// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner. -pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRefMut, U>; - -unsafe impl<'a, T: 'a> IntoErased<'a> for Box { - type Erased = Box; - fn into_erased(self) -> Self::Erased { - self - } -} -unsafe impl<'a, T: 'a> IntoErased<'a> for Rc { - type Erased = Rc; - fn into_erased(self) -> Self::Erased { - self - } -} -unsafe impl<'a, T: 'a> IntoErased<'a> for Arc { - type Erased = Arc; - fn into_erased(self) -> Self::Erased { - self - } -} - -/// Typedef of a owning reference that uses an erased `Box` as the owner. -pub type ErasedBoxRef = OwningRef, U>; -/// Typedef of a owning reference that uses an erased `Rc` as the owner. -pub type ErasedRcRef = OwningRef, U>; -/// Typedef of a owning reference that uses an erased `Arc` as the owner. -pub type ErasedArcRef = OwningRef, U>; - -/// Typedef of a mutable owning reference that uses an erased `Box` as the owner. -pub type ErasedBoxRefMut = OwningRefMut, U>; - -#[cfg(test)] -mod tests { - mod owning_ref { - use super::super::OwningRef; - use super::super::{RcRef, BoxRef, Erased, ErasedBoxRef}; - use std::cmp::{PartialEq, Ord, PartialOrd, Ordering}; - use std::hash::{Hash, Hasher}; - use std::collections::hash_map::DefaultHasher; - use std::collections::HashMap; - use std::rc::Rc; - - #[derive(Debug, PartialEq)] - struct Example(u32, String, [u8; 3]); - fn example() -> Example { - Example(42, "hello world".to_string(), [1, 2, 3]) - } - - #[test] - fn new_deref() { - let or: OwningRef, ()> = OwningRef::new(Box::new(())); - assert_eq!(&*or, &()); - } - - #[test] - fn into() { - let or: OwningRef, ()> = Box::new(()).into(); - assert_eq!(&*or, &()); - } - - #[test] - fn map_offset_ref() { - let or: BoxRef = Box::new(example()).into(); - let or: BoxRef<_, u32> = or.map(|x| &x.0); - assert_eq!(&*or, &42); - - let or: BoxRef = Box::new(example()).into(); - let or: BoxRef<_, u8> = or.map(|x| &x.2[1]); - assert_eq!(&*or, &2); - } - - #[test] - fn map_heap_ref() { - let or: BoxRef = Box::new(example()).into(); - let or: BoxRef<_, str> = or.map(|x| &x.1[..5]); - assert_eq!(&*or, "hello"); - } - - #[test] - fn map_static_ref() { - let or: BoxRef<()> = Box::new(()).into(); - let or: BoxRef<_, str> = or.map(|_| "hello"); - assert_eq!(&*or, "hello"); - } - - #[test] - fn map_chained() { - let or: BoxRef = Box::new(example().1).into(); - let or: BoxRef<_, str> = or.map(|x| &x[1..5]); - let or: BoxRef<_, str> = or.map(|x| &x[..2]); - assert_eq!(&*or, "el"); - } - - #[test] - fn map_chained_inference() { - let or = BoxRef::new(Box::new(example().1)) - .map(|x| &x[..5]) - .map(|x| &x[1..3]); - assert_eq!(&*or, "el"); - } - - #[test] - fn as_owner() { - let or: BoxRef = Box::new(example().1).into(); - let or = or.map(|x| &x[..5]); - assert_eq!(&*or, "hello"); - assert_eq!(&**or.as_owner(), "hello world"); - } - - #[test] - fn into_owner() { - let or: BoxRef = Box::new(example().1).into(); - let or = or.map(|x| &x[..5]); - assert_eq!(&*or, "hello"); - let s = *or.into_owner(); - assert_eq!(&s, "hello world"); - } - - #[test] - fn fmt_debug() { - let or: BoxRef = Box::new(example().1).into(); - let or = or.map(|x| &x[..5]); - let s = format!("{:?}", or); - assert_eq!(&s, "OwningRef { owner: \"hello world\", reference: \"hello\" }"); - } - - #[test] - fn erased_owner() { - let o1: BoxRef = BoxRef::new(Box::new(example())) - .map(|x| &x.1[..]); - - let o2: BoxRef = BoxRef::new(Box::new(example().1)) - .map(|x| &x[..]); - - let os: Vec> = vec![o1.erase_owner(), o2.erase_owner()]; - assert!(os.iter().all(|e| &e[..] == "hello world")); - } - - #[test] - fn non_static_erased_owner() { - let foo = [413, 612]; - let bar = &foo; - - // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure - // (see https://github.com/rust-lang/rust/issues/22340) - // So we use a function to identify the lifetimes instead. - fn borrow<'a>(a: &'a &[i32; 2]) -> &'a i32 { - &a[0] - } - - let o: BoxRef<&[i32; 2]> = Box::new(bar).into(); - let o: BoxRef<&[i32; 2], i32> = o.map(borrow); - let o: BoxRef = o.erase_owner(); - - assert_eq!(*o, 413); - } - - #[test] - fn raii_locks() { - use super::super::{RefRef, RefMutRef}; - use std::cell::RefCell; - use super::super::{MutexGuardRef, RwLockReadGuardRef, RwLockWriteGuardRef}; - use std::sync::{Mutex, RwLock}; - - { - let a = RefCell::new(1); - let a = { - let a = RefRef::new(a.borrow()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = RefCell::new(1); - let a = { - let a = RefMutRef::new(a.borrow_mut()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = Mutex::new(1); - let a = { - let a = MutexGuardRef::new(a.lock().unwrap()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = RwLock::new(1); - let a = { - let a = RwLockReadGuardRef::new(a.read().unwrap()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = RwLock::new(1); - let a = { - let a = RwLockWriteGuardRef::new(a.write().unwrap()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - } - - #[test] - fn eq() { - let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - assert_eq!(or1.eq(&or2), true); - } - - #[test] - fn cmp() { - let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice()); - assert_eq!(or1.cmp(&or2), Ordering::Less); - } - - #[test] - fn partial_cmp() { - let or1: BoxRef<[u8]> = BoxRef::new(vec![4, 5, 6].into_boxed_slice()); - let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater)); - } - - #[test] - fn hash() { - let mut h1 = DefaultHasher::new(); - let mut h2 = DefaultHasher::new(); - - let or1: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRef<[u8]> = BoxRef::new(vec![1, 2, 3].into_boxed_slice()); - - or1.hash(&mut h1); - or2.hash(&mut h2); - - assert_eq!(h1.finish(), h2.finish()); - } - - #[test] - fn borrow() { - let mut hash = HashMap::new(); - let key = RcRef::::new(Rc::new("foo-bar".to_string())).map(|s| &s[..]); - - hash.insert(key.clone().map(|s| &s[..3]), 42); - hash.insert(key.clone().map(|s| &s[4..]), 23); - - assert_eq!(hash.get("foo"), Some(&42)); - assert_eq!(hash.get("bar"), Some(&23)); - } - - #[test] - fn total_erase() { - let a: OwningRef, [u8]> - = OwningRef::new(vec![]).map(|x| &x[..]); - let b: OwningRef, [u8]> - = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]); - - let c: OwningRef>, [u8]> = unsafe {a.map_owner(Rc::new)}; - let d: OwningRef>, [u8]> = unsafe {b.map_owner(Rc::new)}; - - let e: OwningRef, [u8]> = c.erase_owner(); - let f: OwningRef, [u8]> = d.erase_owner(); - - let _g = e.clone(); - let _h = f.clone(); - } - - #[test] - fn total_erase_box() { - let a: OwningRef, [u8]> - = OwningRef::new(vec![]).map(|x| &x[..]); - let b: OwningRef, [u8]> - = OwningRef::new(vec![].into_boxed_slice()).map(|x| &x[..]); - - let c: OwningRef>, [u8]> = a.map_owner_box(); - let d: OwningRef>, [u8]> = b.map_owner_box(); - - let _e: OwningRef, [u8]> = c.erase_owner(); - let _f: OwningRef, [u8]> = d.erase_owner(); - } - - #[test] - fn try_map1() { - use std::any::Any; - - let x = Box::new(123_i32); - let y: Box = x; - - OwningRef::new(y).try_map(|x| x.downcast_ref::().ok_or(())).unwrap(); - } - - #[test] - fn try_map2() { - use std::any::Any; - - let x = Box::new(123_u32); - let y: Box = x; - - OwningRef::new(y).try_map(|x| x.downcast_ref::().ok_or(())).unwrap_err(); - } - - #[test] - fn map_with_owner() { - let owning_ref: BoxRef = Box::new(example()).into(); - let owning_ref = owning_ref.map(|owner| &owner.1); - - owning_ref.map_with_owner(|owner, ref_field| { - assert_eq!(owner.1, *ref_field); - ref_field - }); - } - - #[test] - fn try_map_with_owner_ok() { - let owning_ref: BoxRef = Box::new(example()).into(); - let owning_ref = owning_ref.map(|owner| &owner.1); - - owning_ref.try_map_with_owner(|owner, ref_field| { - assert_eq!(owner.1, *ref_field); - Ok(ref_field) as Result<_, ()> - }).unwrap(); - } - - #[test] - fn try_map_with_owner_err() { - let owning_ref: BoxRef = Box::new(example()).into(); - let owning_ref = owning_ref.map(|owner| &owner.1); - - owning_ref.try_map_with_owner(|owner, ref_field| { - assert_eq!(owner.1, *ref_field); - Err(()) as Result<&(), _> - }).unwrap_err(); - } - } - - mod owning_handle { - use super::super::OwningHandle; - use super::super::RcRef; - use std::rc::Rc; - use std::cell::RefCell; - use std::sync::Arc; - use std::sync::RwLock; - - #[test] - fn owning_handle() { - use std::cell::RefCell; - let cell = Rc::new(RefCell::new(2)); - let cell_ref = RcRef::new(cell); - let mut handle = OwningHandle::new_with_fn(cell_ref, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); - assert_eq!(*handle, 2); - *handle = 3; - assert_eq!(*handle, 3); - } - - #[test] - fn try_owning_handle_ok() { - use std::cell::RefCell; - let cell = Rc::new(RefCell::new(2)); - let cell_ref = RcRef::new(cell); - let mut handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| { - Ok(unsafe { - x.as_ref() - }.unwrap().borrow_mut()) - }).unwrap(); - assert_eq!(*handle, 2); - *handle = 3; - assert_eq!(*handle, 3); - } - - #[test] - fn try_owning_handle_err() { - use std::cell::RefCell; - let cell = Rc::new(RefCell::new(2)); - let cell_ref = RcRef::new(cell); - let handle = OwningHandle::try_new::<_, ()>(cell_ref, |x| { - if false { - return Ok(unsafe { - x.as_ref() - }.unwrap().borrow_mut()) - } - Err(()) - }); - assert!(handle.is_err()); - } - - #[test] - fn nested() { - use std::cell::RefCell; - use std::sync::{Arc, RwLock}; - - let result = { - let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString")))); - let curr = RcRef::new(complex); - let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); - let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap()); - assert_eq!(*curr, "someString"); - *curr = "someOtherString"; - curr - }; - assert_eq!(*result, "someOtherString"); - } - - #[test] - fn owning_handle_safe() { - use std::cell::RefCell; - let cell = Rc::new(RefCell::new(2)); - let cell_ref = RcRef::new(cell); - let handle = OwningHandle::new(cell_ref); - assert_eq!(*handle, 2); - } - - #[test] - fn owning_handle_mut_safe() { - use std::cell::RefCell; - let cell = Rc::new(RefCell::new(2)); - let cell_ref = RcRef::new(cell); - let mut handle = OwningHandle::new_mut(cell_ref); - assert_eq!(*handle, 2); - *handle = 3; - assert_eq!(*handle, 3); - } - - #[test] - fn owning_handle_safe_2() { - let result = { - let complex = Rc::new(RefCell::new(Arc::new(RwLock::new("someString")))); - let curr = RcRef::new(complex); - let curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().borrow_mut()); - let mut curr = OwningHandle::new_with_fn(curr, |x| unsafe { x.as_ref() }.unwrap().try_write().unwrap()); - assert_eq!(*curr, "someString"); - *curr = "someOtherString"; - curr - }; - assert_eq!(*result, "someOtherString"); - } - } - - mod owning_ref_mut { - use super::super::{OwningRefMut, BoxRefMut, Erased, ErasedBoxRefMut}; - use super::super::BoxRef; - use std::cmp::{PartialEq, Ord, PartialOrd, Ordering}; - use std::hash::{Hash, Hasher}; - use std::collections::hash_map::DefaultHasher; - use std::collections::HashMap; - - #[derive(Debug, PartialEq)] - struct Example(u32, String, [u8; 3]); - fn example() -> Example { - Example(42, "hello world".to_string(), [1, 2, 3]) - } - - #[test] - fn new_deref() { - let or: OwningRefMut, ()> = OwningRefMut::new(Box::new(())); - assert_eq!(&*or, &()); - } - - #[test] - fn new_deref_mut() { - let mut or: OwningRefMut, ()> = OwningRefMut::new(Box::new(())); - assert_eq!(&mut *or, &mut ()); - } - - #[test] - fn mutate() { - let mut or: OwningRefMut, usize> = OwningRefMut::new(Box::new(0)); - assert_eq!(&*or, &0); - *or = 1; - assert_eq!(&*or, &1); - } - - #[test] - fn into() { - let or: OwningRefMut, ()> = Box::new(()).into(); - assert_eq!(&*or, &()); - } - - #[test] - fn map_offset_ref() { - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRef<_, u32> = or.map(|x| &mut x.0); - assert_eq!(&*or, &42); - - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRef<_, u8> = or.map(|x| &mut x.2[1]); - assert_eq!(&*or, &2); - } - - #[test] - fn map_heap_ref() { - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRef<_, str> = or.map(|x| &mut x.1[..5]); - assert_eq!(&*or, "hello"); - } - - #[test] - fn map_static_ref() { - let or: BoxRefMut<()> = Box::new(()).into(); - let or: BoxRef<_, str> = or.map(|_| "hello"); - assert_eq!(&*or, "hello"); - } - - #[test] - fn map_mut_offset_ref() { - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRefMut<_, u32> = or.map_mut(|x| &mut x.0); - assert_eq!(&*or, &42); - - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRefMut<_, u8> = or.map_mut(|x| &mut x.2[1]); - assert_eq!(&*or, &2); - } - - #[test] - fn map_mut_heap_ref() { - let or: BoxRefMut = Box::new(example()).into(); - let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x.1[..5]); - assert_eq!(&*or, "hello"); - } - - #[test] - fn map_mut_static_ref() { - static mut MUT_S: [u8; 5] = *b"hello"; - - let mut_s: &'static mut [u8] = unsafe { &mut MUT_S }; - - let or: BoxRefMut<()> = Box::new(()).into(); - let or: BoxRefMut<_, [u8]> = or.map_mut(move |_| mut_s); - assert_eq!(&*or, b"hello"); - } - - #[test] - fn map_mut_chained() { - let or: BoxRefMut = Box::new(example().1).into(); - let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[1..5]); - let or: BoxRefMut<_, str> = or.map_mut(|x| &mut x[..2]); - assert_eq!(&*or, "el"); - } - - #[test] - fn map_chained_inference() { - let or = BoxRefMut::new(Box::new(example().1)) - .map_mut(|x| &mut x[..5]) - .map_mut(|x| &mut x[1..3]); - assert_eq!(&*or, "el"); - } - - #[test] - fn try_map_mut() { - let or: BoxRefMut = Box::new(example().1).into(); - let or: Result, ()> = or.try_map_mut(|x| Ok(&mut x[1..5])); - assert_eq!(&*or.unwrap(), "ello"); - - let or: BoxRefMut = Box::new(example().1).into(); - let or: Result, ()> = or.try_map_mut(|_| Err(())); - assert!(or.is_err()); - } - - #[test] - fn as_owner() { - let or: BoxRefMut = Box::new(example().1).into(); - let or = or.map_mut(|x| &mut x[..5]); - assert_eq!(&*or, "hello"); - assert_eq!(&**or.as_owner(), "hello world"); - } - - #[test] - fn into_owner() { - let or: BoxRefMut = Box::new(example().1).into(); - let or = or.map_mut(|x| &mut x[..5]); - assert_eq!(&*or, "hello"); - let s = *or.into_owner(); - assert_eq!(&s, "hello world"); - } - - #[test] - fn fmt_debug() { - let or: BoxRefMut = Box::new(example().1).into(); - let or = or.map_mut(|x| &mut x[..5]); - let s = format!("{:?}", or); - assert_eq!(&s, - "OwningRefMut { owner: \"hello world\", reference: \"hello\" }"); - } - - #[test] - fn erased_owner() { - let o1: BoxRefMut = BoxRefMut::new(Box::new(example())) - .map_mut(|x| &mut x.1[..]); - - let o2: BoxRefMut = BoxRefMut::new(Box::new(example().1)) - .map_mut(|x| &mut x[..]); - - let os: Vec> = vec![o1.erase_owner(), o2.erase_owner()]; - assert!(os.iter().all(|e| &e[..] == "hello world")); - } - - #[test] - fn non_static_erased_owner() { - let mut foo = [413, 612]; - let bar = &mut foo; - - // FIXME: lifetime inference fails us, and we can't easily define a lifetime for a closure - // (see https://github.com/rust-lang/rust/issues/22340) - // So we use a function to identify the lifetimes instead. - fn borrow<'a>(a: &'a mut &mut [i32; 2]) -> &'a mut i32 { - &mut a[0] - } - - let o: BoxRefMut<&mut [i32; 2]> = Box::new(bar).into(); - let o: BoxRefMut<&mut [i32; 2], i32> = o.map_mut(borrow); - let o: BoxRefMut = o.erase_owner(); - - assert_eq!(*o, 413); - } - - #[test] - fn raii_locks() { - use super::super::RefMutRefMut; - use std::cell::RefCell; - use super::super::{MutexGuardRefMut, RwLockWriteGuardRefMut}; - use std::sync::{Mutex, RwLock}; - - { - let a = RefCell::new(1); - let a = { - let a = RefMutRefMut::new(a.borrow_mut()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = Mutex::new(1); - let a = { - let a = MutexGuardRefMut::new(a.lock().unwrap()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - { - let a = RwLock::new(1); - let a = { - let a = RwLockWriteGuardRefMut::new(a.write().unwrap()); - assert_eq!(*a, 1); - a - }; - assert_eq!(*a, 1); - drop(a); - } - } - - #[test] - fn eq() { - let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - assert_eq!(or1.eq(&or2), true); - } - - #[test] - fn cmp() { - let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice()); - assert_eq!(or1.cmp(&or2), Ordering::Less); - } - - #[test] - fn partial_cmp() { - let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![4, 5, 6].into_boxed_slice()); - let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - assert_eq!(or1.partial_cmp(&or2), Some(Ordering::Greater)); - } - - #[test] - fn hash() { - let mut h1 = DefaultHasher::new(); - let mut h2 = DefaultHasher::new(); - - let or1: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - let or2: BoxRefMut<[u8]> = BoxRefMut::new(vec![1, 2, 3].into_boxed_slice()); - - or1.hash(&mut h1); - or2.hash(&mut h2); - - assert_eq!(h1.finish(), h2.finish()); - } - - #[test] - fn borrow() { - let mut hash = HashMap::new(); - let key1 = BoxRefMut::::new(Box::new("foo".to_string())).map(|s| &s[..]); - let key2 = BoxRefMut::::new(Box::new("bar".to_string())).map(|s| &s[..]); - - hash.insert(key1, 42); - hash.insert(key2, 23); - - assert_eq!(hash.get("foo"), Some(&42)); - assert_eq!(hash.get("bar"), Some(&23)); - } - - #[test] - fn total_erase() { - let a: OwningRefMut, [u8]> - = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]); - let b: OwningRefMut, [u8]> - = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]); - - let c: OwningRefMut>, [u8]> = unsafe {a.map_owner(Box::new)}; - let d: OwningRefMut>, [u8]> = unsafe {b.map_owner(Box::new)}; - - let _e: OwningRefMut, [u8]> = c.erase_owner(); - let _f: OwningRefMut, [u8]> = d.erase_owner(); - } - - #[test] - fn total_erase_box() { - let a: OwningRefMut, [u8]> - = OwningRefMut::new(vec![]).map_mut(|x| &mut x[..]); - let b: OwningRefMut, [u8]> - = OwningRefMut::new(vec![].into_boxed_slice()).map_mut(|x| &mut x[..]); - - let c: OwningRefMut>, [u8]> = a.map_owner_box(); - let d: OwningRefMut>, [u8]> = b.map_owner_box(); - - let _e: OwningRefMut, [u8]> = c.erase_owner(); - let _f: OwningRefMut, [u8]> = d.erase_owner(); - } - - #[test] - fn try_map1() { - use std::any::Any; - - let x = Box::new(123_i32); - let y: Box = x; - - OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::().ok_or(())).unwrap(); - } - - #[test] - fn try_map2() { - use std::any::Any; - - let x = Box::new(123_u32); - let y: Box = x; - - OwningRefMut::new(y).try_map_mut(|x| x.downcast_mut::().ok_or(())).unwrap_err(); - } - - #[test] - fn try_map3() { - use std::any::Any; - - let x = Box::new(123_i32); - let y: Box = x; - - OwningRefMut::new(y).try_map(|x| x.downcast_ref::().ok_or(())).unwrap(); - } - - #[test] - fn try_map4() { - use std::any::Any; - - let x = Box::new(123_u32); - let y: Box = x; - - OwningRefMut::new(y).try_map(|x| x.downcast_ref::().ok_or(())).unwrap_err(); - } - - #[test] - fn into_owning_ref() { - use super::super::BoxRef; - - let or: BoxRefMut<()> = Box::new(()).into(); - let or: BoxRef<()> = or.into(); - assert_eq!(&*or, &()); - } - - struct Foo { - u: u32, - } - struct Bar { - f: Foo, - } - - #[test] - fn ref_mut() { - use std::cell::RefCell; - - let a = RefCell::new(Bar { f: Foo { u: 42 } }); - let mut b = OwningRefMut::new(a.borrow_mut()); - assert_eq!(b.f.u, 42); - b.f.u = 43; - let mut c = b.map_mut(|x| &mut x.f); - assert_eq!(c.u, 43); - c.u = 44; - let mut d = c.map_mut(|x| &mut x.u); - assert_eq!(*d, 44); - *d = 45; - assert_eq!(*d, 45); - } - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.10.0/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot-0.10.0/.cargo-checksum.json new file mode 100644 index 0000000..83624a0 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot-0.10.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"67c50cb22d980c9320ccce5568ccaa89a58e8366ff6c1aafb90a0450034bb731","Cargo.toml":"1476f231995686093ade27b1da08c4fc6ed0c4cfbf3534589389e93e2bbe684e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"72b6b1ba1c29f8de15fb4ac65c482f32278e5402666a37d42054a8fd557387d0","appveyor.yml":"e2416e65e27442dd8e17c773deee1e45ee96157221bc81b03d9a6d25bfa570e2","src/condvar.rs":"56ca5fc69955f28a997133255547bb5d64074af6108f8036ea0273bab3e0fddd","src/deadlock.rs":"081dbf009539b113f67ad0a1abd7af889dad684a47aa1a7dc00ae91f08975ef6","src/elision.rs":"00f7af80021fd602879fb7205befb6ff941cd8dc932a5c0a534b430fefe421ea","src/lib.rs":"533f098d633a4a94367f2bb4e615a97ef2ab977c1ba55b01cd91dc5f91f2a294","src/mutex.rs":"ac145b5913cdc5690a146d7c3456f1cffa6cb454e994ac39de52c1ce97b78e55","src/once.rs":"a1c38a5d87077e3d112d57e065ee126a24ab19f04fba9cb1f2cb43bc82caf33c","src/raw_mutex.rs":"f3507478c34b49bd725dfaed6bf4847fc3aec28700960a7823af9e15b06b5e24","src/raw_rwlock.rs":"f8ce7c4f92299cf64cb6e7b69cd46d9ddefd1211535729b6455e82f7c4eb3eae","src/remutex.rs":"416d02e2195e04654ca2b0a8ebce2a10842da56f6910d9ed3b90948718de39d0","src/rwlock.rs":"54a3cb74644c88b425d2cd692117a35fe4ed8211ba73c975d6129297603ebf0e","src/util.rs":"37a2c8b5c9254df83e8f3a5cd831558c1045061a76c2571bdc4d78eb86e467f2"},"package":"92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/BUILD b/third_party/cargo/vendor/parking_lot-0.10.0/BUILD similarity index 79% rename from third_party/cargo/vendor/parking_lot-0.6.4/BUILD rename to third_party/cargo/vendor/parking_lot-0.10.0/BUILD index dc3baa1..77b42cd 100644 --- a/third_party/cargo/vendor/parking_lot-0.6.4/BUILD +++ b/third_party/cargo/vendor/parking_lot-0.10.0/BUILD @@ -28,19 +28,18 @@ rust_library( name = "parking_lot", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/lock_api-0.1.5:lock_api", - "//third_party/cargo/vendor/parking_lot_core-0.3.1:parking_lot_core", + "//third_party/cargo/vendor/lock_api-0.3.3:lock_api", + "//third_party/cargo/vendor/parking_lot_core-0.7.0:parking_lot_core", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.6.4", + version = "0.10.0", crate_features = [ "default", - "owning_ref", ], ) diff --git a/third_party/cargo/vendor/parking_lot-0.10.0/CHANGELOG.md b/third_party/cargo/vendor/parking_lot-0.10.0/CHANGELOG.md new file mode 100644 index 0000000..a681861 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot-0.10.0/CHANGELOG.md @@ -0,0 +1,104 @@ +## parking_lot 0.10.0, parking_lot_core 0.7.0, lock_api 0.3.2 (2019-11-25) + +- Upgrade smallvec dependency to 1.0 in parking_lot_core. +- Replace all usage of `mem::unitialized` with `mem::MaybeUninit`. +- The minimum required Rust version is bumped to 1.36. Because of the above two changes. +- Make methods on `WaitTimeoutResult` and `OnceState` take `self` by value instead of reference. + +## parking_lot_core 0.6.2 (2019-07-22) + +- Fixed compile error on Windows with old cfg_if version. (#164) + +## parking_lot_core 0.6.1 (2019-07-17) + +- Fixed Android build. (#163) + +## parking_lot 0.9.0, parking_lot_core 0.6.0, lock_api 0.3.1 (2019-07-14) + +- Re-export lock_api (0.3.1) from parking_lot (#150) +- Removed (non-dev) dependency on rand crate for fairness mechanism, by + including a simple xorshift PRNG in core (#144) +- Android now uses the futex-based ThreadParker. (#140) +- Fixed CloudABI ThreadParker. (#140) +- Fix race condition in lock_api::ReentrantMutex (da16c2c7) + +## lock_api 0.3.0 (2019-07-03, _yanked_) + +- Use NonZeroUsize in GetThreadId::nonzero_thread_id (#148) +- Debug assert lock_count in ReentrantMutex (#148) +- Tag as `unsafe` and document some internal methods (#148) +- This release was _yanked_ due to a regression in ReentrantMutex (da16c2c7) + +## parking_lot 0.8.1 (2019-07-03, _yanked_) + +- Re-export lock_api (0.3.0) from parking_lot (#150) +- This release was _yanked_ from crates.io due to unexpected breakage (#156) + +## parking_lot 0.8.0, parking_lot_core 0.5.0, lock_api 0.2.0 (2019-05-04) + +- Fix race conditions in deadlock detection. +- Support for more platforms by adding ThreadParker implementations for + Wasm, Redox, SGX and CloudABI. +- Drop support for older Rust. parking_lot now requires 1.31 and is a + Rust 2018 edition crate (#122). +- Disable the owning_ref feature by default. +- Fix was_last_thread value in the timeout callback of park() (#129). +- Support single byte Mutex/Once on stable Rust when compiler is at least + version 1.34. +- Make Condvar::new and Once::new const fns on stable Rust and remove + ONCE_INIT (#134). +- Add optional Serde support (#135). + +## parking_lot 0.7.1 (2019-01-01) + +- Fixed potential deadlock when upgrading a RwLock. +- Fixed overflow panic on very long timeouts (#111). + +## parking_lot 0.7.0, parking_lot_core 0.4.0 (2018-11-26) + +- Return if or how many threads were notified from `Condvar::notify_*` + +## parking_lot 0.6.3 (2018-07-18) + +- Export `RawMutex`, `RawRwLock` and `RawThreadId`. + +## parking_lot 0.6.2 (2018-06-18) + +- Enable `lock_api/nightly` feature from `parking_lot/nightly` (#79) + +## parking_lot 0.6.1 (2018-06-08) + +Added missing typedefs for mapped lock guards: + +- `MappedMutexGuard` +- `MappedReentrantMutexGuard` +- `MappedRwLockReadGuard` +- `MappedRwLockWriteGuard` + +## parking_lot 0.6.0 (2018-06-08) + +This release moves most of the code for type-safe `Mutex` and `RwLock` types +into a separate crate called `lock_api`. This new crate is compatible with +`no_std` and provides `Mutex` and `RwLock` type-safe wrapper types from a raw +mutex type which implements the `RawMutex` or `RawRwLock` trait. The API +provided by the wrapper types can be extended by implementing more traits on +the raw mutex type which provide more functionality (e.g. `RawMutexTimed`). See +the crate documentation for more details. + +There are also several major changes: + +- The minimum required Rust version is bumped to 1.26. +- All methods on `MutexGuard` (and other guard types) are no longer inherent + methods and must be called as `MutexGuard::method(self)`. This avoids + conflicts with methods from the inner type. +- `MutexGuard` (and other guard types) add the `unlocked` method which + temporarily unlocks a mutex, runs the given closure, and then re-locks the + mutex. +- `MutexGuard` (and other guard types) add the `bump` method which gives a + chance for other threads to acquire the mutex by temporarily unlocking it and + re-locking it. However this is optimized for the common case where there are + no threads waiting on the lock, in which case no unlocking is performed. +- `MutexGuard` (and other guard types) add the `map` method which returns a + `MappedMutexGuard` which holds only a subset of the original locked type. The + `MappedMutexGuard` type is identical to `MutexGuard` except that it does not + support the `unlocked` and `bump` methods, and can't be used with `CondVar`. diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/Cargo.toml b/third_party/cargo/vendor/parking_lot-0.10.0/Cargo.toml similarity index 80% rename from third_party/cargo/vendor/parking_lot-0.7.1/Cargo.toml rename to third_party/cargo/vendor/parking_lot-0.10.0/Cargo.toml index 19a73ca..ea2833f 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/Cargo.toml +++ b/third_party/cargo/vendor/parking_lot-0.10.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "parking_lot" -version = "0.7.1" +version = "0.10.0" authors = ["Amanieu d'Antras "] description = "More compact and efficient implementations of the standard synchronization primitives." readme = "README.md" @@ -21,15 +22,22 @@ categories = ["concurrency"] license = "Apache-2.0/MIT" repository = "https://github.com/Amanieu/parking_lot" [dependencies.lock_api] -version = "0.1" +version = "0.3.1" [dependencies.parking_lot_core] -version = "0.4" +version = "0.7.0" +[dev-dependencies.bincode] +version = "1.1.3" + +[dev-dependencies.lazy_static] +version = "1.0" + [dev-dependencies.rand] -version = "0.6" +version = "0.7" [features] deadlock_detection = ["parking_lot_core/deadlock_detection"] -default = ["owning_ref"] +default = [] nightly = ["parking_lot_core/nightly", "lock_api/nightly"] owning_ref = ["lock_api/owning_ref"] +serde = ["lock_api/serde"] diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/LICENSE-APACHE b/third_party/cargo/vendor/parking_lot-0.10.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/parking_lot-0.7.1/LICENSE-APACHE rename to third_party/cargo/vendor/parking_lot-0.10.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/LICENSE-MIT b/third_party/cargo/vendor/parking_lot-0.10.0/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/parking_lot-0.6.4/LICENSE-MIT rename to third_party/cargo/vendor/parking_lot-0.10.0/LICENSE-MIT diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/README.md b/third_party/cargo/vendor/parking_lot-0.10.0/README.md similarity index 90% rename from third_party/cargo/vendor/parking_lot-0.7.1/README.md rename to third_party/cargo/vendor/parking_lot-0.10.0/README.md index a8f339a..7705e67 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/README.md +++ b/third_party/cargo/vendor/parking_lot-0.10.0/README.md @@ -34,7 +34,7 @@ in the Rust standard library: parallelism. 2. Since they consist of just a single atomic variable, have constant initializers and don't need destructors, these primitives can be used as - `static` global variables. The standard library primitives require + `static` global variables. The standard library primitives require dynamic initialization and thus need to be lazily initialized with `lazy_static!`. 3. Uncontended lock acquisition and release is done through fast inline @@ -68,6 +68,9 @@ in the Rust standard library: can be enabled via the `deadlock_detection` feature. 17. `RwLock` supports atomically upgrading an "upgradable" read lock into a write lock. +18. Optional support for [serde](https://docs.serde.rs/serde/). Enable via the + feature `serde`. **NOTE!** this support is for `Mutex`, `ReentrantMutex`, + and `RwLock` only; `Condvar` and `Once` are not currently supported. ## The parking lot @@ -84,9 +87,8 @@ lock. There are a few restrictions when using this library on stable Rust: -- `Mutex` and `Once` will use 1 word of space instead of 1 byte. -- You will have to use `lazy_static!` to statically initialize `Mutex`, - `Condvar` and `RwLock` types instead of `const fn`. +- You will have to use `lazy_static!` or equivalent to statically initialize `Mutex` + and `RwLock` types. They use generics and can't be `const fn`s on stable yet. - `RwLock` will not be able to take advantage of hardware lock elision for readers, which improves performance when there are multiple readers. @@ -99,7 +101,7 @@ Add this to your `Cargo.toml`: ```toml [dependencies] -parking_lot = "0.6" +parking_lot = "0.10" ``` and this to your crate root: @@ -112,7 +114,7 @@ To enable nightly-only features, add this to your `Cargo.toml` instead: ```toml [dependencies] -parking_lot = {version = "0.6", features = ["nightly"]} +parking_lot = { version = "0.10", features = ["nightly"] } ``` The experimental deadlock detector can be enabled with the @@ -124,7 +126,7 @@ changes to the core API do not cause breaking changes for users of `parking_lot` ## Minimum Rust version -The current minimum required Rust version is 1.24. Any change to this is +The current minimum required Rust version is 1.36. Any change to this is considered a breaking change and will require a major version bump. ## License diff --git a/third_party/cargo/vendor/parking_lot-0.10.0/appveyor.yml b/third_party/cargo/vendor/parking_lot-0.10.0/appveyor.yml new file mode 100644 index 0000000..a7eb5cf --- /dev/null +++ b/third_party/cargo/vendor/parking_lot-0.10.0/appveyor.yml @@ -0,0 +1,59 @@ +environment: + TRAVIS_CARGO_NIGHTLY_FEATURE: nightly + RUST_TEST_THREADS: 1 + matrix: + - TARGET: x86_64-pc-windows-msvc + MSYSTEM: MINGW64 + CPU: x86_64 + TOOLCHAIN: nightly + FEATURES: nightly + - TARGET: i686-pc-windows-msvc + MSYSTEM: MINGW32 + CPU: i686 + TOOLCHAIN: nightly + FEATURES: nightly + - TARGET: x86_64-pc-windows-gnu + MSYSTEM: MINGW64 + CPU: x86_64 + TOOLCHAIN: nightly + FEATURES: nightly + - TARGET: i686-pc-windows-gnu + MSYSTEM: MINGW32 + CPU: i686 + TOOLCHAIN: nightly + FEATURES: nightly + - TARGET: x86_64-pc-windows-msvc + MSYSTEM: MINGW64 + CPU: x86_64 + TOOLCHAIN: 1.36.0 + - TARGET: i686-pc-windows-msvc + MSYSTEM: MINGW32 + CPU: i686 + TOOLCHAIN: 1.36.0 + - TARGET: x86_64-pc-windows-gnu + MSYSTEM: MINGW64 + CPU: x86_64 + TOOLCHAIN: 1.36.0 + - TARGET: i686-pc-windows-gnu + MSYSTEM: MINGW32 + CPU: i686 + TOOLCHAIN: 1.36.0 + +install: + - set PATH=C:\msys64\%MSYSTEM%\bin;c:\msys64\usr\bin;%PATH% + - pacman --noconfirm -Syu mingw-w64-%CPU%-make + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-host %TARGET% --default-toolchain %TOOLCHAIN% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - rustc -vV + - cargo -vV + +build_script: + - cargo build --features "%FEATURES%" + +test_script: + - cargo test --all --features "%FEATURES%" + - cargo doc --all + - cd benchmark + - cargo run --release --bin mutex -- 2 1 0 1 2 + - cargo run --release --bin rwlock -- 1 1 1 0 1 2 diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/condvar.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/condvar.rs similarity index 62% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/condvar.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/condvar.rs index cb85e88..149ec86 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/condvar.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/condvar.rs @@ -5,15 +5,16 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use deadlock; -use lock_api::RawMutex as RawMutexTrait; -use mutex::MutexGuard; +use crate::mutex::MutexGuard; +use crate::raw_mutex::{RawMutex, TOKEN_HANDOFF, TOKEN_NORMAL}; +use crate::{deadlock, util}; +use core::{ + fmt, ptr, + sync::atomic::{AtomicPtr, Ordering}, +}; +use lock_api::RawMutex as RawMutex_; use parking_lot_core::{self, ParkResult, RequeueOp, UnparkResult, DEFAULT_PARK_TOKEN}; -use raw_mutex::{RawMutex, TOKEN_HANDOFF, TOKEN_NORMAL}; -use std::sync::atomic::{AtomicPtr, Ordering}; use std::time::{Duration, Instant}; -use std::{fmt, ptr}; -use util; /// A type indicating whether a timed wait on a condition variable returned /// due to a time out or not. @@ -23,7 +24,7 @@ pub struct WaitTimeoutResult(bool); impl WaitTimeoutResult { /// Returns whether the wait was known to have timed out. #[inline] - pub fn timed_out(&self) -> bool { + pub fn timed_out(self) -> bool { self.0 } } @@ -77,9 +78,13 @@ impl WaitTimeoutResult { /// // wait for the thread to start up /// let &(ref lock, ref cvar) = &*pair; /// let mut started = lock.lock(); -/// while !*started { +/// if !*started { /// cvar.wait(&mut started); /// } +/// // Note that we used and if instead of a while loop above. This is only +/// // possible because parking_lot's Condvar will never spuriously wake up. +/// // This means that wait() will only return after notify_one or notify_all is +/// // called. /// ``` pub struct Condvar { state: AtomicPtr, @@ -88,7 +93,6 @@ pub struct Condvar { impl Condvar { /// Creates a new condition variable which is ready to be waited on and /// notified. - #[cfg(feature = "nightly")] #[inline] pub const fn new() -> Condvar { Condvar { @@ -96,16 +100,6 @@ impl Condvar { } } - /// Creates a new condition variable which is ready to be waited on and - /// notified. - #[cfg(not(feature = "nightly"))] - #[inline] - pub fn new() -> Condvar { - Condvar { - state: AtomicPtr::new(ptr::null_mut()), - } - } - /// Wakes up one blocked thread on this condvar. /// /// Returns whether a thread was woken up. @@ -141,7 +135,6 @@ impl Condvar { } #[cold] - #[inline(never)] fn notify_one_slow(&self, mutex: *mut RawMutex) -> bool { unsafe { // Unpark one thread and requeue the rest onto the mutex @@ -203,7 +196,6 @@ impl Condvar { } #[cold] - #[inline(never)] fn notify_all_slow(&self, mutex: *mut RawMutex) -> usize { unsafe { // Unpark one thread and requeue the rest onto the mutex @@ -263,7 +255,7 @@ impl Condvar { /// This function will panic if another thread is waiting on the `Condvar` /// with a different `Mutex` object. #[inline] - pub fn wait(&self, mutex_guard: &mut MutexGuard) { + pub fn wait(&self, mutex_guard: &mut MutexGuard<'_, T>) { self.wait_until_internal(unsafe { MutexGuard::mutex(mutex_guard).raw() }, None); } @@ -293,7 +285,7 @@ impl Condvar { #[inline] pub fn wait_until( &self, - mutex_guard: &mut MutexGuard, + mutex_guard: &mut MutexGuard<'_, T>, timeout: Instant, ) -> WaitTimeoutResult { self.wait_until_internal( @@ -397,7 +389,7 @@ impl Condvar { #[inline] pub fn wait_for( &self, - mutex_guard: &mut MutexGuard, + mutex_guard: &mut MutexGuard<'_, T>, timeout: Duration, ) -> WaitTimeoutResult { let deadline = util::to_deadline(timeout); @@ -413,18 +405,18 @@ impl Default for Condvar { } impl fmt::Debug for Condvar { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad("Condvar { .. }") } } #[cfg(test)] mod tests { + use crate::{Condvar, Mutex, MutexGuard}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; - use {Condvar, Mutex}; #[test] fn smoke() { @@ -626,7 +618,7 @@ mod tests { rx.recv().unwrap(); let _g = m.lock(); let _guard = PanicGuard(&*c); - let _ = c.wait(&mut m3.lock()); + c.wait(&mut m3.lock()); } #[test] @@ -668,10 +660,393 @@ mod tests { let mut g = m.lock(); while !c.notify_one() { // Wait for the thread to get into wait() - ::MutexGuard::bump(&mut g); + MutexGuard::bump(&mut g); } // The thread should have been requeued to the mutex, which we wake up now. drop(g); t.join().unwrap(); } + + #[test] + fn test_issue_129() { + let locks = Arc::new((Mutex::new(()), Condvar::new())); + + let (tx, rx) = channel(); + for _ in 0..4 { + let locks = locks.clone(); + let tx = tx.clone(); + thread::spawn(move || { + let mut guard = locks.0.lock(); + locks.1.wait(&mut guard); + locks.1.wait_for(&mut guard, Duration::from_millis(1)); + locks.1.notify_one(); + tx.send(()).unwrap(); + }); + } + + thread::sleep(Duration::from_millis(100)); + locks.1.notify_one(); + + for _ in 0..4 { + assert_eq!(rx.recv_timeout(Duration::from_millis(500)), Ok(())); + } + } +} + +/// This module contains an integration test that is heavily inspired from WebKit's own integration +/// tests for it's own Condvar. +#[cfg(test)] +mod webkit_queue_test { + use crate::{Condvar, Mutex, MutexGuard}; + use std::{collections::VecDeque, sync::Arc, thread, time::Duration}; + + #[derive(Clone, Copy)] + enum Timeout { + Bounded(Duration), + Forever, + } + + #[derive(Clone, Copy)] + enum NotifyStyle { + One, + All, + } + + struct Queue { + items: VecDeque, + should_continue: bool, + } + + impl Queue { + fn new() -> Self { + Self { + items: VecDeque::new(), + should_continue: true, + } + } + } + + fn wait( + condition: &Condvar, + lock: &mut MutexGuard<'_, T>, + predicate: impl Fn(&mut MutexGuard<'_, T>) -> bool, + timeout: &Timeout, + ) { + while !predicate(lock) { + match timeout { + Timeout::Forever => condition.wait(lock), + Timeout::Bounded(bound) => { + condition.wait_for(lock, *bound); + } + } + } + } + + fn notify(style: NotifyStyle, condition: &Condvar, should_notify: bool) { + match style { + NotifyStyle::One => { + condition.notify_one(); + } + NotifyStyle::All => { + if should_notify { + condition.notify_all(); + } + } + } + } + + fn run_queue_test( + num_producers: usize, + num_consumers: usize, + max_queue_size: usize, + messages_per_producer: usize, + notify_style: NotifyStyle, + timeout: Timeout, + delay: Duration, + ) { + let input_queue = Arc::new(Mutex::new(Queue::new())); + let empty_condition = Arc::new(Condvar::new()); + let full_condition = Arc::new(Condvar::new()); + + let output_vec = Arc::new(Mutex::new(vec![])); + + let consumers = (0..num_consumers) + .map(|_| { + consumer_thread( + input_queue.clone(), + empty_condition.clone(), + full_condition.clone(), + timeout, + notify_style, + output_vec.clone(), + max_queue_size, + ) + }) + .collect::>(); + let producers = (0..num_producers) + .map(|_| { + producer_thread( + messages_per_producer, + input_queue.clone(), + empty_condition.clone(), + full_condition.clone(), + timeout, + notify_style, + max_queue_size, + ) + }) + .collect::>(); + + thread::sleep(delay); + + for producer in producers.into_iter() { + producer.join().expect("Producer thread panicked"); + } + + { + let mut input_queue = input_queue.lock(); + input_queue.should_continue = false; + } + empty_condition.notify_all(); + + for consumer in consumers.into_iter() { + consumer.join().expect("Consumer thread panicked"); + } + + let mut output_vec = output_vec.lock(); + assert_eq!(output_vec.len(), num_producers * messages_per_producer); + output_vec.sort(); + for msg_idx in 0..messages_per_producer { + for producer_idx in 0..num_producers { + assert_eq!(msg_idx, output_vec[msg_idx * num_producers + producer_idx]); + } + } + } + + fn consumer_thread( + input_queue: Arc>, + empty_condition: Arc, + full_condition: Arc, + timeout: Timeout, + notify_style: NotifyStyle, + output_queue: Arc>>, + max_queue_size: usize, + ) -> thread::JoinHandle<()> { + thread::spawn(move || loop { + let (should_notify, result) = { + let mut queue = input_queue.lock(); + wait( + &*empty_condition, + &mut queue, + |state| -> bool { !state.items.is_empty() || !state.should_continue }, + &timeout, + ); + if queue.items.is_empty() && !queue.should_continue { + return; + } + let should_notify = queue.items.len() == max_queue_size; + let result = queue.items.pop_front(); + std::mem::drop(queue); + (should_notify, result) + }; + notify(notify_style, &*full_condition, should_notify); + + if let Some(result) = result { + output_queue.lock().push(result); + } + }) + } + + fn producer_thread( + num_messages: usize, + queue: Arc>, + empty_condition: Arc, + full_condition: Arc, + timeout: Timeout, + notify_style: NotifyStyle, + max_queue_size: usize, + ) -> thread::JoinHandle<()> { + thread::spawn(move || { + for message in 0..num_messages { + let should_notify = { + let mut queue = queue.lock(); + wait( + &*full_condition, + &mut queue, + |state| state.items.len() < max_queue_size, + &timeout, + ); + let should_notify = queue.items.is_empty(); + queue.items.push_back(message); + std::mem::drop(queue); + should_notify + }; + notify(notify_style, &*empty_condition, should_notify); + } + }) + } + + macro_rules! run_queue_tests { + ( $( $name:ident( + num_producers: $num_producers:expr, + num_consumers: $num_consumers:expr, + max_queue_size: $max_queue_size:expr, + messages_per_producer: $messages_per_producer:expr, + notification_style: $notification_style:expr, + timeout: $timeout:expr, + delay_seconds: $delay_seconds:expr); + )* ) => { + $(#[test] + fn $name() { + let delay = Duration::from_secs($delay_seconds); + run_queue_test( + $num_producers, + $num_consumers, + $max_queue_size, + $messages_per_producer, + $notification_style, + $timeout, + delay, + ); + })* + }; + } + + run_queue_tests! { + sanity_check_queue( + num_producers: 1, + num_consumers: 1, + max_queue_size: 1, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Bounded(Duration::from_secs(1)), + delay_seconds: 0 + ); + sanity_check_queue_timeout( + num_producers: 1, + num_consumers: 1, + max_queue_size: 1, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + new_test_without_timeout_5( + num_producers: 1, + num_consumers: 5, + max_queue_size: 1, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + one_producer_one_consumer_one_slot( + num_producers: 1, + num_consumers: 1, + max_queue_size: 1, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + one_producer_one_consumer_one_slot_timeout( + num_producers: 1, + num_consumers: 1, + max_queue_size: 1, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 1 + ); + one_producer_one_consumer_hundred_slots( + num_producers: 1, + num_consumers: 1, + max_queue_size: 100, + messages_per_producer: 1_000_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_one_consumer_one_slot( + num_producers: 10, + num_consumers: 1, + max_queue_size: 1, + messages_per_producer: 10000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_one_consumer_hundred_slots_notify_all( + num_producers: 10, + num_consumers: 1, + max_queue_size: 100, + messages_per_producer: 10000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_one_consumer_hundred_slots_notify_one( + num_producers: 10, + num_consumers: 1, + max_queue_size: 100, + messages_per_producer: 10000, + notification_style: NotifyStyle::One, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + one_producer_ten_consumers_one_slot( + num_producers: 1, + num_consumers: 10, + max_queue_size: 1, + messages_per_producer: 10000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + one_producer_ten_consumers_hundred_slots_notify_all( + num_producers: 1, + num_consumers: 10, + max_queue_size: 100, + messages_per_producer: 100_000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + one_producer_ten_consumers_hundred_slots_notify_one( + num_producers: 1, + num_consumers: 10, + max_queue_size: 100, + messages_per_producer: 100_000, + notification_style: NotifyStyle::One, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_ten_consumers_one_slot( + num_producers: 10, + num_consumers: 10, + max_queue_size: 1, + messages_per_producer: 50000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_ten_consumers_hundred_slots_notify_all( + num_producers: 10, + num_consumers: 10, + max_queue_size: 100, + messages_per_producer: 50000, + notification_style: NotifyStyle::All, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + ten_producers_ten_consumers_hundred_slots_notify_one( + num_producers: 10, + num_consumers: 10, + max_queue_size: 100, + messages_per_producer: 50000, + notification_style: NotifyStyle::One, + timeout: Timeout::Forever, + delay_seconds: 0 + ); + } } diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/deadlock.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/deadlock.rs similarity index 90% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/deadlock.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/deadlock.rs index ef7d619..810edf1 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/deadlock.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/deadlock.rs @@ -40,10 +40,15 @@ pub(crate) use parking_lot_core::deadlock::{acquire_resource, release_resource}; #[cfg(test)] #[cfg(feature = "deadlock_detection")] mod tests { + use crate::{Mutex, ReentrantMutex, RwLock}; use std::sync::{Arc, Barrier}; use std::thread::{self, sleep}; use std::time::Duration; - use {Mutex, ReentrantMutex, RwLock}; + + // We need to serialize these tests since deadlock detection uses global state + lazy_static::lazy_static! { + static ref DEADLOCK_DETECTION_LOCK: Mutex<()> = Mutex::new(()); + } fn check_deadlock() -> bool { use parking_lot_core::deadlock::check_deadlock; @@ -52,6 +57,8 @@ mod tests { #[test] fn test_mutex_deadlock() { + let _guard = DEADLOCK_DETECTION_LOCK.lock(); + let m1: Arc> = Default::default(); let m2: Arc> = Default::default(); let m3: Arc> = Default::default(); @@ -95,6 +102,8 @@ mod tests { #[test] fn test_mutex_deadlock_reentrant() { + let _guard = DEADLOCK_DETECTION_LOCK.lock(); + let m1: Arc> = Default::default(); assert!(!check_deadlock()); @@ -112,6 +121,8 @@ mod tests { #[test] fn test_remutex_deadlock() { + let _guard = DEADLOCK_DETECTION_LOCK.lock(); + let m1: Arc> = Default::default(); let m2: Arc> = Default::default(); let m3: Arc> = Default::default(); @@ -158,6 +169,8 @@ mod tests { #[test] fn test_rwlock_deadlock() { + let _guard = DEADLOCK_DETECTION_LOCK.lock(); + let m1: Arc> = Default::default(); let m2: Arc> = Default::default(); let m3: Arc> = Default::default(); @@ -199,8 +212,11 @@ mod tests { assert!(!check_deadlock()); } + #[cfg(rwlock_deadlock_detection_not_supported)] #[test] fn test_rwlock_deadlock_reentrant() { + let _guard = DEADLOCK_DETECTION_LOCK.lock(); + let m1: Arc> = Default::default(); assert!(!check_deadlock()); diff --git a/third_party/cargo/vendor/parking_lot-0.10.0/src/elision.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/elision.rs new file mode 100644 index 0000000..74ff5ff --- /dev/null +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/elision.rs @@ -0,0 +1,116 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use std::sync::atomic::AtomicUsize; + +// Extension trait to add lock elision primitives to atomic types +pub trait AtomicElisionExt { + type IntType; + + // Perform a compare_exchange and start a transaction + fn elision_compare_exchange_acquire( + &self, + current: Self::IntType, + new: Self::IntType, + ) -> Result; + + // Perform a fetch_sub and end a transaction + fn elision_fetch_sub_release(&self, val: Self::IntType) -> Self::IntType; +} + +// Indicates whether the target architecture supports lock elision +#[inline] +pub fn have_elision() -> bool { + cfg!(all( + feature = "nightly", + any(target_arch = "x86", target_arch = "x86_64"), + )) +} + +// This implementation is never actually called because it is guarded by +// have_elision(). +#[cfg(not(all(feature = "nightly", any(target_arch = "x86", target_arch = "x86_64"))))] +impl AtomicElisionExt for AtomicUsize { + type IntType = usize; + + #[inline] + fn elision_compare_exchange_acquire(&self, _: usize, _: usize) -> Result { + unreachable!(); + } + + #[inline] + fn elision_fetch_sub_release(&self, _: usize) -> usize { + unreachable!(); + } +} + +#[cfg(all(feature = "nightly", any(target_arch = "x86", target_arch = "x86_64")))] +impl AtomicElisionExt for AtomicUsize { + type IntType = usize; + + #[cfg(target_pointer_width = "32")] + #[inline] + fn elision_compare_exchange_acquire(&self, current: usize, new: usize) -> Result { + unsafe { + let prev: usize; + asm!("xacquire; lock; cmpxchgl $2, $1" + : "={eax}" (prev), "+*m" (self) + : "r" (new), "{eax}" (current) + : "memory" + : "volatile"); + if prev == current { + Ok(prev) + } else { + Err(prev) + } + } + } + #[cfg(target_pointer_width = "64")] + #[inline] + fn elision_compare_exchange_acquire(&self, current: usize, new: usize) -> Result { + unsafe { + let prev: usize; + asm!("xacquire; lock; cmpxchgq $2, $1" + : "={rax}" (prev), "+*m" (self) + : "r" (new), "{rax}" (current) + : "memory" + : "volatile"); + if prev == current { + Ok(prev) + } else { + Err(prev) + } + } + } + + #[cfg(target_pointer_width = "32")] + #[inline] + fn elision_fetch_sub_release(&self, val: usize) -> usize { + unsafe { + let prev: usize; + asm!("xrelease; lock; xaddl $2, $1" + : "=r" (prev), "+*m" (self) + : "0" (val.wrapping_neg()) + : "memory" + : "volatile"); + prev + } + } + #[cfg(target_pointer_width = "64")] + #[inline] + fn elision_fetch_sub_release(&self, val: usize) -> usize { + unsafe { + let prev: usize; + asm!("xrelease; lock; xaddq $2, $1" + : "=r" (prev), "+*m" (self) + : "0" (val.wrapping_neg()) + : "memory" + : "volatile"); + prev + } + } +} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/lib.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/lib.rs similarity index 66% rename from third_party/cargo/vendor/parking_lot-0.6.4/src/lib.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/lib.rs index f16b821..db0d6b3 100644 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/lib.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/lib.rs @@ -10,13 +10,9 @@ //! standard library. It also provides a `ReentrantMutex` type. #![warn(missing_docs)] -#![cfg_attr(feature = "nightly", feature(const_fn))] -#![cfg_attr(feature = "nightly", feature(integer_atomics))] +#![warn(rust_2018_idioms)] #![cfg_attr(feature = "nightly", feature(asm))] -extern crate lock_api; -extern crate parking_lot_core; - mod condvar; mod elision; mod mutex; @@ -32,13 +28,16 @@ pub mod deadlock; #[cfg(not(feature = "deadlock_detection"))] mod deadlock; -pub use condvar::{Condvar, WaitTimeoutResult}; -pub use mutex::{MappedMutexGuard, Mutex, MutexGuard}; -pub use once::{Once, OnceState, ONCE_INIT}; -pub use raw_mutex::RawMutex; -pub use raw_rwlock::RawRwLock; -pub use remutex::{MappedReentrantMutexGuard, RawThreadId, ReentrantMutex, ReentrantMutexGuard}; -pub use rwlock::{ +pub use self::condvar::{Condvar, WaitTimeoutResult}; +pub use self::mutex::{MappedMutexGuard, Mutex, MutexGuard}; +pub use self::once::{Once, OnceState}; +pub use self::raw_mutex::RawMutex; +pub use self::raw_rwlock::RawRwLock; +pub use self::remutex::{ + MappedReentrantMutexGuard, RawThreadId, ReentrantMutex, ReentrantMutexGuard, +}; +pub use self::rwlock::{ MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard, RwLockWriteGuard, }; +pub use ::lock_api; diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/mutex.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/mutex.rs similarity index 92% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/mutex.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/mutex.rs index 0e26570..82f1fe5 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/mutex.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/mutex.rs @@ -5,8 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use crate::raw_mutex::RawMutex; use lock_api; -use raw_mutex::RawMutex; /// A mutual exclusion primitive useful for protecting shared data /// @@ -69,7 +69,7 @@ use raw_mutex::RawMutex; /// /// let (tx, rx) = channel(); /// for _ in 0..10 { -/// let (data, tx) = (data.clone(), tx.clone()); +/// let (data, tx) = (Arc::clone(&data), tx.clone()); /// thread::spawn(move || { /// // The shared state can only be accessed once the lock is held. /// // Our non-atomic increment is safe because we're the only thread @@ -105,11 +105,14 @@ pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; #[cfg(test)] mod tests { + use crate::{Condvar, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; - use {Condvar, Mutex}; + + #[cfg(feature = "serde")] + use bincode::{deserialize, serialize}; struct Packet(Arc<(Mutex, Condvar)>); @@ -242,7 +245,7 @@ mod tests { fn test_mutex_arc_access_in_unwind() { let arc = Arc::new(Mutex::new(1)); let arc2 = arc.clone(); - let _ = thread::spawn(move || -> () { + let _ = thread::spawn(move || { struct Unwinder { i: Arc>, } @@ -284,16 +287,20 @@ mod tests { let mutex = Mutex::new(vec![0u8, 10]); assert_eq!(format!("{:?}", mutex), "Mutex { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", mutex), - "Mutex { - data: [ - 0, - 10 - ] -}" - ); let _lock = mutex.lock(); - assert_eq!(format!("{:?}", mutex), "Mutex { }"); + assert_eq!(format!("{:?}", mutex), "Mutex { data: }"); + } + + #[cfg(feature = "serde")] + #[test] + fn test_serde() { + let contents: Vec = vec![0, 1, 2]; + let mutex = Mutex::new(contents.clone()); + + let serialized = serialize(&mutex).unwrap(); + let deserialized: Mutex> = deserialize(&serialized).unwrap(); + + assert_eq!(*(mutex.lock()), *(deserialized.lock())); + assert_eq!(contents, *(deserialized.lock())); } } diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/once.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/once.rs similarity index 88% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/once.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/once.rs index 33b7572..f458c9c 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/once.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/once.rs @@ -5,26 +5,17 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use std::sync::atomic::{fence, Ordering}; -#[cfg(feature = "nightly")] -use std::sync::atomic::{AtomicU8, ATOMIC_U8_INIT}; -#[cfg(feature = "nightly")] -type U8 = u8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::AtomicUsize as AtomicU8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::ATOMIC_USIZE_INIT as ATOMIC_U8_INIT; -#[cfg(not(feature = "nightly"))] -type U8 = usize; +use crate::util::UncheckedOptionExt; +use core::{ + fmt, mem, + sync::atomic::{fence, AtomicU8, Ordering}, +}; use parking_lot_core::{self, SpinWait, DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; -use std::fmt; -use std::mem; -use util::UncheckedOptionExt; -const DONE_BIT: U8 = 1; -const POISON_BIT: U8 = 2; -const LOCKED_BIT: U8 = 4; -const PARKED_BIT: U8 = 8; +const DONE_BIT: u8 = 1; +const POISON_BIT: u8 = 2; +const LOCKED_BIT: u8 = 4; +const PARKED_BIT: u8 = 8; /// Current state of a `Once`. #[derive(Copy, Clone, Eq, PartialEq, Debug)] @@ -48,8 +39,8 @@ impl OnceState { /// Once an initialization routine for a `Once` has panicked it will forever /// indicate to future forced initialization routines that it is poisoned. #[inline] - pub fn poisoned(&self) -> bool { - match *self { + pub fn poisoned(self) -> bool { + match self { OnceState::Poisoned => true, _ => false, } @@ -58,8 +49,8 @@ impl OnceState { /// Returns whether the associated `Once` has successfully executed a /// closure. #[inline] - pub fn done(&self) -> bool { - match *self { + pub fn done(self) -> bool { + match self { OnceState::Done => true, _ => false, } @@ -81,9 +72,9 @@ impl OnceState { /// # Examples /// /// ``` -/// use parking_lot::{Once, ONCE_INIT}; +/// use parking_lot::Once; /// -/// static START: Once = ONCE_INIT; +/// static START: Once = Once::new(); /// /// START.call_once(|| { /// // run initialization here @@ -91,22 +82,11 @@ impl OnceState { /// ``` pub struct Once(AtomicU8); -/// Initialization value for static `Once` values. -pub const ONCE_INIT: Once = Once(ATOMIC_U8_INIT); - impl Once { /// Creates a new `Once` value. - #[cfg(feature = "nightly")] #[inline] pub const fn new() -> Once { - Once(ATOMIC_U8_INIT) - } - - /// Creates a new `Once` value. - #[cfg(not(feature = "nightly"))] - #[inline] - pub fn new() -> Once { - Once(ATOMIC_U8_INIT) + Once(AtomicU8::new(0)) } /// Returns the current state of this `Once`. @@ -141,10 +121,10 @@ impl Once { /// # Examples /// /// ``` - /// use parking_lot::{Once, ONCE_INIT}; + /// use parking_lot::Once; /// /// static mut VAL: usize = 0; - /// static INIT: Once = ONCE_INIT; + /// static INIT: Once = Once::new(); /// /// // Accessing a `static mut` is unsafe much of the time, but if we do so /// // in a synchronized fashion (e.g. write once or read all) then we're @@ -222,8 +202,7 @@ impl Once { // currently no way to take an `FnOnce` and call it via virtual dispatch // without some allocation overhead. #[cold] - #[inline(never)] - fn call_once_slow(&self, ignore_poison: bool, f: &mut FnMut(OnceState)) { + fn call_once_slow(&self, ignore_poison: bool, f: &mut dyn FnMut(OnceState)) { let mut spinwait = SpinWait::new(); let mut state = self.0.load(Ordering::Relaxed); loop { @@ -344,7 +323,7 @@ impl Default for Once { } impl fmt::Debug for Once { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Once") .field("state", &self.state()) .finish() @@ -353,15 +332,14 @@ impl fmt::Debug for Once { #[cfg(test)] mod tests { - #[cfg(feature = "nightly")] + use crate::Once; use std::panic; use std::sync::mpsc::channel; use std::thread; - use {Once, ONCE_INIT}; #[test] fn smoke_once() { - static O: Once = ONCE_INIT; + static O: Once = Once::new(); let mut a = 0; O.call_once(|| a += 1); assert_eq!(a, 1); @@ -371,7 +349,7 @@ mod tests { #[test] fn stampede_once() { - static O: Once = ONCE_INIT; + static O: Once = Once::new(); static mut RUN: bool = false; let (tx, rx) = channel(); @@ -405,10 +383,9 @@ mod tests { } } - #[cfg(feature = "nightly")] #[test] fn poison_bad() { - static O: Once = ONCE_INIT; + static O: Once = Once::new(); // poison the once let t = panic::catch_unwind(|| { @@ -434,10 +411,9 @@ mod tests { O.call_once(|| {}); } - #[cfg(feature = "nightly")] #[test] fn wait_for_force_to_finish() { - static O: Once = ONCE_INIT; + static O: Once = Once::new(); // poison the once let t = panic::catch_unwind(|| { @@ -475,14 +451,8 @@ mod tests { #[test] fn test_once_debug() { - static O: Once = ONCE_INIT; + static O: Once = Once::new(); assert_eq!(format!("{:?}", O), "Once { state: New }"); - assert_eq!( - format!("{:#?}", O), - "Once { - state: New -}" - ); } } diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/raw_mutex.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/raw_mutex.rs similarity index 58% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/raw_mutex.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/raw_mutex.rs index 4b5f762..ee39c3b 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/raw_mutex.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/raw_mutex.rs @@ -5,22 +5,14 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use std::sync::atomic::Ordering; -#[cfg(feature = "nightly")] -use std::sync::atomic::{AtomicU8, ATOMIC_U8_INIT}; -#[cfg(feature = "nightly")] -type U8 = u8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::AtomicUsize as AtomicU8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::ATOMIC_USIZE_INIT as ATOMIC_U8_INIT; -#[cfg(not(feature = "nightly"))] -type U8 = usize; -use deadlock; -use lock_api::{GuardNoSend, RawMutex as RawMutexTrait, RawMutexFair, RawMutexTimed}; +use crate::{deadlock, util}; +use core::{ + sync::atomic::{AtomicU8, Ordering}, + time::Duration, +}; +use lock_api::{GuardNoSend, RawMutex as RawMutex_}; use parking_lot_core::{self, ParkResult, SpinWait, UnparkResult, UnparkToken, DEFAULT_PARK_TOKEN}; -use std::time::{Duration, Instant}; -use util; +use std::time::Instant; // UnparkToken used to indicate that that the target thread should attempt to // lock the mutex again as soon as it is unparked. @@ -30,17 +22,42 @@ pub(crate) const TOKEN_NORMAL: UnparkToken = UnparkToken(0); // thread directly without unlocking it. pub(crate) const TOKEN_HANDOFF: UnparkToken = UnparkToken(1); -const LOCKED_BIT: U8 = 1; -const PARKED_BIT: U8 = 2; +/// This bit is set in the `state` of a `RawMutex` when that mutex is locked by some thread. +const LOCKED_BIT: u8 = 0b01; +/// This bit is set in the `state` of a `RawMutex` just before parking a thread. A thread is being +/// parked if it wants to lock the mutex, but it is currently being held by some other thread. +const PARKED_BIT: u8 = 0b10; /// Raw mutex type backed by the parking lot. pub struct RawMutex { + /// This atomic integer holds the current state of the mutex instance. Only the two lowest bits + /// are used. See `LOCKED_BIT` and `PARKED_BIT` for the bitmask for these bits. + /// + /// # State table: + /// + /// PARKED_BIT | LOCKED_BIT | Description + /// 0 | 0 | The mutex is not locked, nor is anyone waiting for it. + /// -----------+------------+------------------------------------------------------------------ + /// 0 | 1 | The mutex is locked by exactly one thread. No other thread is + /// | | waiting for it. + /// -----------+------------+------------------------------------------------------------------ + /// 1 | 0 | The mutex is not locked. One or more thread is parked or about to + /// | | park. At least one of the parked threads are just about to be + /// | | unparked, or a thread heading for parking might abort the park. + /// -----------+------------+------------------------------------------------------------------ + /// 1 | 1 | The mutex is locked by exactly one thread. One or more thread is + /// | | parked or about to park, waiting for the lock to become available. + /// | | In this state, PARKED_BIT is only ever cleared when a bucket lock + /// | | is held (i.e. in a parking_lot_core callback). This ensures that + /// | | we never end up in a situation where there are parked threads but + /// | | PARKED_BIT is not set (which would result in those threads + /// | | potentially never getting woken up). state: AtomicU8, } -unsafe impl RawMutexTrait for RawMutex { +unsafe impl lock_api::RawMutex for RawMutex { const INIT: RawMutex = RawMutex { - state: ATOMIC_U8_INIT, + state: AtomicU8::new(0), }; type GuardMarker = GuardNoSend; @@ -84,7 +101,7 @@ unsafe impl RawMutexTrait for RawMutex { unsafe { deadlock::release_resource(self as *const _ as usize) }; if self .state - .compare_exchange_weak(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) + .compare_exchange(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) .is_ok() { return; @@ -93,13 +110,13 @@ unsafe impl RawMutexTrait for RawMutex { } } -unsafe impl RawMutexFair for RawMutex { +unsafe impl lock_api::RawMutexFair for RawMutex { #[inline] fn unlock_fair(&self) { unsafe { deadlock::release_resource(self as *const _ as usize) }; if self .state - .compare_exchange_weak(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) + .compare_exchange(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) .is_ok() { return; @@ -115,7 +132,7 @@ unsafe impl RawMutexFair for RawMutex { } } -unsafe impl RawMutexTimed for RawMutex { +unsafe impl lock_api::RawMutexTimed for RawMutex { type Duration = Duration; type Instant = Instant; @@ -184,7 +201,6 @@ impl RawMutex { } #[cold] - #[inline(never)] fn lock_slow(&self, timeout: Option) -> bool { let mut spinwait = SpinWait::new(); let mut state = self.state.load(Ordering::Relaxed); @@ -223,37 +239,41 @@ impl RawMutex { } // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || self.state.load(Ordering::Relaxed) == LOCKED_BIT | PARKED_BIT; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( + let addr = self as *const _ as usize; + let validate = || self.state.load(Ordering::Relaxed) == LOCKED_BIT | PARKED_BIT; + let before_sleep = || {}; + let timed_out = |_, was_last_thread| { + // Clear the parked bit if we were the last parked thread + if was_last_thread { + self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); + } + }; + // SAFETY: + // * `addr` is an address we control. + // * `validate`/`timed_out` does not panic or call into any function of `parking_lot`. + // * `before_sleep` does not call `park`, nor does it panic. + match unsafe { + parking_lot_core::park( addr, validate, before_sleep, timed_out, DEFAULT_PARK_TOKEN, timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, + ) + } { + // The thread that unparked us passed the lock on to us + // directly without unlocking it. + ParkResult::Unparked(TOKEN_HANDOFF) => return true, - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), + // We were unparked normally, try acquiring the lock again + ParkResult::Unparked(_) => (), - // The validation function failed, try locking again - ParkResult::Invalid => (), + // The validation function failed, try locking again + ParkResult::Invalid => (), - // Timeout expired - ParkResult::TimedOut => return false, - } + // Timeout expired + ParkResult::TimedOut => return false, } // Loop back and try locking again @@ -263,48 +283,40 @@ impl RawMutex { } #[cold] - #[inline(never)] fn unlock_slow(&self, force_fair: bool) { - // Unlock directly if there are no parked threads - if self - .state - .compare_exchange(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - // Unpark one thread and leave the parked bit set if there might // still be parked threads on this address. - unsafe { - let addr = self as *const _ as usize; - let callback = |result: UnparkResult| { - // If we are using a fair unlock then we should keep the - // mutex locked and hand it off to the unparked thread. - if result.unparked_threads != 0 && (force_fair || result.be_fair) { - // Clear the parked bit if there are no more parked - // threads. - if !result.have_more_threads { - self.state.store(LOCKED_BIT, Ordering::Relaxed); - } - return TOKEN_HANDOFF; + let addr = self as *const _ as usize; + let callback = |result: UnparkResult| { + // If we are using a fair unlock then we should keep the + // mutex locked and hand it off to the unparked thread. + if result.unparked_threads != 0 && (force_fair || result.be_fair) { + // Clear the parked bit if there are no more parked + // threads. + if !result.have_more_threads { + self.state.store(LOCKED_BIT, Ordering::Relaxed); } + return TOKEN_HANDOFF; + } - // Clear the locked bit, and the parked bit as well if there - // are no more parked threads. - if result.have_more_threads { - self.state.store(PARKED_BIT, Ordering::Release); - } else { - self.state.store(0, Ordering::Release); - } - TOKEN_NORMAL - }; + // Clear the locked bit, and the parked bit as well if there + // are no more parked threads. + if result.have_more_threads { + self.state.store(PARKED_BIT, Ordering::Release); + } else { + self.state.store(0, Ordering::Release); + } + TOKEN_NORMAL + }; + // SAFETY: + // * `addr` is an address we control. + // * `callback` does not panic or call into any function of `parking_lot`. + unsafe { parking_lot_core::unpark_one(addr, callback); } } #[cold] - #[inline(never)] fn bump_slow(&self) { unsafe { deadlock::release_resource(self as *const _ as usize) }; self.unlock_slow(true); diff --git a/third_party/cargo/vendor/parking_lot-0.10.0/src/raw_rwlock.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/raw_rwlock.rs new file mode 100644 index 0000000..8c1ad11 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/raw_rwlock.rs @@ -0,0 +1,1137 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use crate::elision::{have_elision, AtomicElisionExt}; +use crate::raw_mutex::{TOKEN_HANDOFF, TOKEN_NORMAL}; +use crate::util; +use core::{ + cell::Cell, + sync::atomic::{AtomicUsize, Ordering}, +}; +use lock_api::{GuardNoSend, RawRwLock as RawRwLock_, RawRwLockUpgrade}; +use parking_lot_core::{ + self, deadlock, FilterOp, ParkResult, ParkToken, SpinWait, UnparkResult, UnparkToken, +}; +use std::time::{Duration, Instant}; + +// This reader-writer lock implementation is based on Boost's upgrade_mutex: +// https://github.com/boostorg/thread/blob/fc08c1fe2840baeeee143440fba31ef9e9a813c8/include/boost/thread/v2/shared_mutex.hpp#L432 +// +// This implementation uses 2 wait queues, one at key [addr] and one at key +// [addr + 1]. The primary queue is used for all new waiting threads, and the +// secondary queue is used by the thread which has acquired WRITER_BIT but is +// waiting for the remaining readers to exit the lock. +// +// This implementation is fair between readers and writers since it uses the +// order in which threads first started queuing to alternate between read phases +// and write phases. In particular is it not vulnerable to write starvation +// since readers will block if there is a pending writer. + +// There is at least one thread in the main queue. +const PARKED_BIT: usize = 0b0001; +// There is a parked thread holding WRITER_BIT. WRITER_BIT must be set. +const WRITER_PARKED_BIT: usize = 0b0010; +// A reader is holding an upgradable lock. The reader count must be non-zero and +// WRITER_BIT must not be set. +const UPGRADABLE_BIT: usize = 0b0100; +// If the reader count is zero: a writer is currently holding an exclusive lock. +// Otherwise: a writer is waiting for the remaining readers to exit the lock. +const WRITER_BIT: usize = 0b1000; +// Mask of bits used to count readers. +const READERS_MASK: usize = !0b1111; +// Base unit for counting readers. +const ONE_READER: usize = 0b10000; + +// Token indicating what type of lock a queued thread is trying to acquire +const TOKEN_SHARED: ParkToken = ParkToken(ONE_READER); +const TOKEN_EXCLUSIVE: ParkToken = ParkToken(WRITER_BIT); +const TOKEN_UPGRADABLE: ParkToken = ParkToken(ONE_READER | UPGRADABLE_BIT); + +/// Raw reader-writer lock type backed by the parking lot. +pub struct RawRwLock { + state: AtomicUsize, +} + +unsafe impl lock_api::RawRwLock for RawRwLock { + const INIT: RawRwLock = RawRwLock { + state: AtomicUsize::new(0), + }; + + type GuardMarker = GuardNoSend; + + #[inline] + fn lock_exclusive(&self) { + if self + .state + .compare_exchange_weak(0, WRITER_BIT, Ordering::Acquire, Ordering::Relaxed) + .is_err() + { + let result = self.lock_exclusive_slow(None); + debug_assert!(result); + } + self.deadlock_acquire(); + } + + #[inline] + fn try_lock_exclusive(&self) -> bool { + if self + .state + .compare_exchange(0, WRITER_BIT, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + self.deadlock_acquire(); + true + } else { + false + } + } + + #[inline] + fn unlock_exclusive(&self) { + self.deadlock_release(); + if self + .state + .compare_exchange(WRITER_BIT, 0, Ordering::Release, Ordering::Relaxed) + .is_ok() + { + return; + } + self.unlock_exclusive_slow(false); + } + + #[inline] + fn lock_shared(&self) { + if !self.try_lock_shared_fast(false) { + let result = self.lock_shared_slow(false, None); + debug_assert!(result); + } + self.deadlock_acquire(); + } + + #[inline] + fn try_lock_shared(&self) -> bool { + let result = if self.try_lock_shared_fast(false) { + true + } else { + self.try_lock_shared_slow(false) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn unlock_shared(&self) { + self.deadlock_release(); + let state = if have_elision() { + self.state.elision_fetch_sub_release(ONE_READER) + } else { + self.state.fetch_sub(ONE_READER, Ordering::Release) + }; + if state & (READERS_MASK | WRITER_PARKED_BIT) == (ONE_READER | WRITER_PARKED_BIT) { + self.unlock_shared_slow(); + } + } +} + +unsafe impl lock_api::RawRwLockFair for RawRwLock { + #[inline] + fn unlock_shared_fair(&self) { + // Shared unlocking is always fair in this implementation. + self.unlock_shared(); + } + + #[inline] + fn unlock_exclusive_fair(&self) { + self.deadlock_release(); + if self + .state + .compare_exchange(WRITER_BIT, 0, Ordering::Release, Ordering::Relaxed) + .is_ok() + { + return; + } + self.unlock_exclusive_slow(true); + } + + #[inline] + fn bump_shared(&self) { + if self.state.load(Ordering::Relaxed) & (READERS_MASK | WRITER_BIT) + == ONE_READER | WRITER_BIT + { + self.bump_shared_slow(); + } + } + + #[inline] + fn bump_exclusive(&self) { + if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { + self.bump_exclusive_slow(); + } + } +} + +unsafe impl lock_api::RawRwLockDowngrade for RawRwLock { + #[inline] + fn downgrade(&self) { + let state = self + .state + .fetch_add(ONE_READER - WRITER_BIT, Ordering::Release); + + // Wake up parked shared and upgradable threads if there are any + if state & PARKED_BIT != 0 { + self.downgrade_slow(); + } + } +} + +unsafe impl lock_api::RawRwLockTimed for RawRwLock { + type Duration = Duration; + type Instant = Instant; + + #[inline] + fn try_lock_shared_for(&self, timeout: Self::Duration) -> bool { + let result = if self.try_lock_shared_fast(false) { + true + } else { + self.lock_shared_slow(false, util::to_deadline(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_lock_shared_until(&self, timeout: Self::Instant) -> bool { + let result = if self.try_lock_shared_fast(false) { + true + } else { + self.lock_shared_slow(false, Some(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_lock_exclusive_for(&self, timeout: Duration) -> bool { + let result = if self + .state + .compare_exchange_weak(0, WRITER_BIT, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + true + } else { + self.lock_exclusive_slow(util::to_deadline(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_lock_exclusive_until(&self, timeout: Instant) -> bool { + let result = if self + .state + .compare_exchange_weak(0, WRITER_BIT, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + true + } else { + self.lock_exclusive_slow(Some(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } +} + +unsafe impl lock_api::RawRwLockRecursive for RawRwLock { + #[inline] + fn lock_shared_recursive(&self) { + if !self.try_lock_shared_fast(true) { + let result = self.lock_shared_slow(true, None); + debug_assert!(result); + } + self.deadlock_acquire(); + } + + #[inline] + fn try_lock_shared_recursive(&self) -> bool { + let result = if self.try_lock_shared_fast(true) { + true + } else { + self.try_lock_shared_slow(true) + }; + if result { + self.deadlock_acquire(); + } + result + } +} + +unsafe impl lock_api::RawRwLockRecursiveTimed for RawRwLock { + #[inline] + fn try_lock_shared_recursive_for(&self, timeout: Self::Duration) -> bool { + let result = if self.try_lock_shared_fast(true) { + true + } else { + self.lock_shared_slow(true, util::to_deadline(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_lock_shared_recursive_until(&self, timeout: Self::Instant) -> bool { + let result = if self.try_lock_shared_fast(true) { + true + } else { + self.lock_shared_slow(true, Some(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } +} + +unsafe impl lock_api::RawRwLockUpgrade for RawRwLock { + #[inline] + fn lock_upgradable(&self) { + if !self.try_lock_upgradable_fast() { + let result = self.lock_upgradable_slow(None); + debug_assert!(result); + } + self.deadlock_acquire(); + } + + #[inline] + fn try_lock_upgradable(&self) -> bool { + let result = if self.try_lock_upgradable_fast() { + true + } else { + self.try_lock_upgradable_slow() + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn unlock_upgradable(&self) { + self.deadlock_release(); + let state = self.state.load(Ordering::Relaxed); + if state & PARKED_BIT == 0 { + if self + .state + .compare_exchange_weak( + state, + state - (ONE_READER | UPGRADABLE_BIT), + Ordering::Release, + Ordering::Relaxed, + ) + .is_ok() + { + return; + } + } + self.unlock_upgradable_slow(false); + } + + #[inline] + fn upgrade(&self) { + let state = self.state.fetch_sub( + (ONE_READER | UPGRADABLE_BIT) - WRITER_BIT, + Ordering::Relaxed, + ); + if state & READERS_MASK != ONE_READER { + let result = self.upgrade_slow(None); + debug_assert!(result); + } + } + + #[inline] + fn try_upgrade(&self) -> bool { + if self + .state + .compare_exchange_weak( + ONE_READER | UPGRADABLE_BIT, + WRITER_BIT, + Ordering::Relaxed, + Ordering::Relaxed, + ) + .is_ok() + { + true + } else { + self.try_upgrade_slow() + } + } +} + +unsafe impl lock_api::RawRwLockUpgradeFair for RawRwLock { + #[inline] + fn unlock_upgradable_fair(&self) { + self.deadlock_release(); + let state = self.state.load(Ordering::Relaxed); + if state & PARKED_BIT == 0 { + if self + .state + .compare_exchange_weak( + state, + state - (ONE_READER | UPGRADABLE_BIT), + Ordering::Release, + Ordering::Relaxed, + ) + .is_ok() + { + return; + } + } + self.unlock_upgradable_slow(false); + } + + #[inline] + fn bump_upgradable(&self) { + if self.state.load(Ordering::Relaxed) == ONE_READER | UPGRADABLE_BIT | PARKED_BIT { + self.bump_upgradable_slow(); + } + } +} + +unsafe impl lock_api::RawRwLockUpgradeDowngrade for RawRwLock { + #[inline] + fn downgrade_upgradable(&self) { + let state = self.state.fetch_sub(UPGRADABLE_BIT, Ordering::Relaxed); + + // Wake up parked upgradable threads if there are any + if state & PARKED_BIT != 0 { + self.downgrade_slow(); + } + } + + #[inline] + fn downgrade_to_upgradable(&self) { + let state = self.state.fetch_add( + (ONE_READER | UPGRADABLE_BIT) - WRITER_BIT, + Ordering::Release, + ); + + // Wake up parked shared threads if there are any + if state & PARKED_BIT != 0 { + self.downgrade_to_upgradable_slow(); + } + } +} + +unsafe impl lock_api::RawRwLockUpgradeTimed for RawRwLock { + #[inline] + fn try_lock_upgradable_until(&self, timeout: Instant) -> bool { + let result = if self.try_lock_upgradable_fast() { + true + } else { + self.lock_upgradable_slow(Some(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_lock_upgradable_for(&self, timeout: Duration) -> bool { + let result = if self.try_lock_upgradable_fast() { + true + } else { + self.lock_upgradable_slow(util::to_deadline(timeout)) + }; + if result { + self.deadlock_acquire(); + } + result + } + + #[inline] + fn try_upgrade_until(&self, timeout: Instant) -> bool { + let state = self.state.fetch_sub( + (ONE_READER | UPGRADABLE_BIT) - WRITER_BIT, + Ordering::Relaxed, + ); + if state & READERS_MASK == ONE_READER { + true + } else { + self.upgrade_slow(Some(timeout)) + } + } + + #[inline] + fn try_upgrade_for(&self, timeout: Duration) -> bool { + let state = self.state.fetch_sub( + (ONE_READER | UPGRADABLE_BIT) - WRITER_BIT, + Ordering::Relaxed, + ); + if state & READERS_MASK == ONE_READER { + true + } else { + self.upgrade_slow(util::to_deadline(timeout)) + } + } +} + +impl RawRwLock { + #[inline(always)] + fn try_lock_shared_fast(&self, recursive: bool) -> bool { + let state = self.state.load(Ordering::Relaxed); + + // We can't allow grabbing a shared lock if there is a writer, even if + // the writer is still waiting for the remaining readers to exit. + if state & WRITER_BIT != 0 { + // To allow recursive locks, we make an exception and allow readers + // to skip ahead of a pending writer to avoid deadlocking, at the + // cost of breaking the fairness guarantees. + if !recursive || state & READERS_MASK == 0 { + return false; + } + } + + // Use hardware lock elision to avoid cache conflicts when multiple + // readers try to acquire the lock. We only do this if the lock is + // completely empty since elision handles conflicts poorly. + if have_elision() && state == 0 { + self.state + .elision_compare_exchange_acquire(0, ONE_READER) + .is_ok() + } else if let Some(new_state) = state.checked_add(ONE_READER) { + self.state + .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + } else { + false + } + } + + #[cold] + fn try_lock_shared_slow(&self, recursive: bool) -> bool { + let mut state = self.state.load(Ordering::Relaxed); + loop { + // This mirrors the condition in try_lock_shared_fast + if state & WRITER_BIT != 0 { + if !recursive || state & READERS_MASK == 0 { + return false; + } + } + if have_elision() && state == 0 { + match self.state.elision_compare_exchange_acquire(0, ONE_READER) { + Ok(_) => return true, + Err(x) => state = x, + } + } else { + match self.state.compare_exchange_weak( + state, + state + .checked_add(ONE_READER) + .expect("RwLock reader count overflow"), + Ordering::Acquire, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(x) => state = x, + } + } + } + } + + #[inline(always)] + fn try_lock_upgradable_fast(&self) -> bool { + let state = self.state.load(Ordering::Relaxed); + + // We can't grab an upgradable lock if there is already a writer or + // upgradable reader. + if state & (WRITER_BIT | UPGRADABLE_BIT) != 0 { + return false; + } + + if let Some(new_state) = state.checked_add(ONE_READER | UPGRADABLE_BIT) { + self.state + .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + } else { + false + } + } + + #[cold] + fn try_lock_upgradable_slow(&self) -> bool { + let mut state = self.state.load(Ordering::Relaxed); + loop { + // This mirrors the condition in try_lock_upgradable_fast + if state & (WRITER_BIT | UPGRADABLE_BIT) != 0 { + return false; + } + + match self.state.compare_exchange_weak( + state, + state + .checked_add(ONE_READER | UPGRADABLE_BIT) + .expect("RwLock reader count overflow"), + Ordering::Acquire, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(x) => state = x, + } + } + } + + #[cold] + fn lock_exclusive_slow(&self, timeout: Option) -> bool { + let try_lock = |state: &mut usize| { + loop { + if *state & (WRITER_BIT | UPGRADABLE_BIT) != 0 { + return false; + } + + // Grab WRITER_BIT if it isn't set, even if there are parked threads. + match self.state.compare_exchange_weak( + *state, + *state | WRITER_BIT, + Ordering::Acquire, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(x) => *state = x, + } + } + }; + + // Step 1: grab exclusive ownership of WRITER_BIT + let timed_out = !self.lock_common( + timeout, + TOKEN_EXCLUSIVE, + try_lock, + WRITER_BIT | UPGRADABLE_BIT, + ); + if timed_out { + return false; + } + + // Step 2: wait for all remaining readers to exit the lock. + self.wait_for_readers(timeout, 0) + } + + #[cold] + fn unlock_exclusive_slow(&self, force_fair: bool) { + // There are threads to unpark. Try to unpark as many as we can. + let callback = |mut new_state, result: UnparkResult| { + // If we are using a fair unlock then we should keep the + // rwlock locked and hand it off to the unparked threads. + if result.unparked_threads != 0 && (force_fair || result.be_fair) { + if result.have_more_threads { + new_state |= PARKED_BIT; + } + self.state.store(new_state, Ordering::Release); + TOKEN_HANDOFF + } else { + // Clear the parked bit if there are no more parked threads. + if result.have_more_threads { + self.state.store(PARKED_BIT, Ordering::Release); + } else { + self.state.store(0, Ordering::Release); + } + TOKEN_NORMAL + } + }; + // SAFETY: `callback` does not panic or call into any function of `parking_lot`. + unsafe { + self.wake_parked_threads(0, callback); + } + } + + #[cold] + fn lock_shared_slow(&self, recursive: bool, timeout: Option) -> bool { + let try_lock = |state: &mut usize| { + let mut spinwait_shared = SpinWait::new(); + loop { + // Use hardware lock elision to avoid cache conflicts when multiple + // readers try to acquire the lock. We only do this if the lock is + // completely empty since elision handles conflicts poorly. + if have_elision() && *state == 0 { + match self.state.elision_compare_exchange_acquire(0, ONE_READER) { + Ok(_) => return true, + Err(x) => *state = x, + } + } + + // This is the same condition as try_lock_shared_fast + if *state & WRITER_BIT != 0 { + if !recursive || *state & READERS_MASK == 0 { + return false; + } + } + + if self + .state + .compare_exchange_weak( + *state, + state + .checked_add(ONE_READER) + .expect("RwLock reader count overflow"), + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_ok() + { + return true; + } + + // If there is high contention on the reader count then we want + // to leave some time between attempts to acquire the lock to + // let other threads make progress. + spinwait_shared.spin_no_yield(); + *state = self.state.load(Ordering::Relaxed); + } + }; + self.lock_common(timeout, TOKEN_SHARED, try_lock, WRITER_BIT) + } + + #[cold] + fn unlock_shared_slow(&self) { + // At this point WRITER_PARKED_BIT is set and READER_MASK is empty. We + // just need to wake up a potentially sleeping pending writer. + // Using the 2nd key at addr + 1 + let addr = self as *const _ as usize + 1; + let callback = |_result: UnparkResult| { + // Clear the WRITER_PARKED_BIT here since there can only be one + // parked writer thread. + self.state.fetch_and(!WRITER_PARKED_BIT, Ordering::Relaxed); + TOKEN_NORMAL + }; + // SAFETY: + // * `addr` is an address we control. + // * `callback` does not panic or call into any function of `parking_lot`. + unsafe { + parking_lot_core::unpark_one(addr, callback); + } + } + + #[cold] + fn lock_upgradable_slow(&self, timeout: Option) -> bool { + let try_lock = |state: &mut usize| { + let mut spinwait_shared = SpinWait::new(); + loop { + if *state & (WRITER_BIT | UPGRADABLE_BIT) != 0 { + return false; + } + + if self + .state + .compare_exchange_weak( + *state, + state + .checked_add(ONE_READER | UPGRADABLE_BIT) + .expect("RwLock reader count overflow"), + Ordering::Acquire, + Ordering::Relaxed, + ) + .is_ok() + { + return true; + } + + // If there is high contention on the reader count then we want + // to leave some time between attempts to acquire the lock to + // let other threads make progress. + spinwait_shared.spin_no_yield(); + *state = self.state.load(Ordering::Relaxed); + } + }; + self.lock_common( + timeout, + TOKEN_UPGRADABLE, + try_lock, + WRITER_BIT | UPGRADABLE_BIT, + ) + } + + #[cold] + fn unlock_upgradable_slow(&self, force_fair: bool) { + // Just release the lock if there are no parked threads. + let mut state = self.state.load(Ordering::Relaxed); + while state & PARKED_BIT == 0 { + match self.state.compare_exchange_weak( + state, + state - (ONE_READER | UPGRADABLE_BIT), + Ordering::Release, + Ordering::Relaxed, + ) { + Ok(_) => return, + Err(x) => state = x, + } + } + + // There are threads to unpark. Try to unpark as many as we can. + let callback = |new_state, result: UnparkResult| { + // If we are using a fair unlock then we should keep the + // rwlock locked and hand it off to the unparked threads. + let mut state = self.state.load(Ordering::Relaxed); + if force_fair || result.be_fair { + // Fall back to normal unpark on overflow. Panicking is + // not allowed in parking_lot callbacks. + while let Some(mut new_state) = + (state - (ONE_READER | UPGRADABLE_BIT)).checked_add(new_state) + { + if result.have_more_threads { + new_state |= PARKED_BIT; + } else { + new_state &= !PARKED_BIT; + } + match self.state.compare_exchange_weak( + state, + new_state, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => return TOKEN_HANDOFF, + Err(x) => state = x, + } + } + } + + // Otherwise just release the upgradable lock and update PARKED_BIT. + loop { + let mut new_state = state - (ONE_READER | UPGRADABLE_BIT); + if result.have_more_threads { + new_state |= PARKED_BIT; + } else { + new_state &= !PARKED_BIT; + } + match self.state.compare_exchange_weak( + state, + new_state, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => return TOKEN_NORMAL, + Err(x) => state = x, + } + } + }; + // SAFETY: `callback` does not panic or call into any function of `parking_lot`. + unsafe { + self.wake_parked_threads(0, callback); + } + } + + #[cold] + fn try_upgrade_slow(&self) -> bool { + let mut state = self.state.load(Ordering::Relaxed); + loop { + if state & READERS_MASK != ONE_READER { + return false; + } + match self.state.compare_exchange_weak( + state, + state - (ONE_READER | UPGRADABLE_BIT) + WRITER_BIT, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => return true, + Err(x) => state = x, + } + } + } + + #[cold] + fn upgrade_slow(&self, timeout: Option) -> bool { + self.wait_for_readers(timeout, ONE_READER | UPGRADABLE_BIT) + } + + #[cold] + fn downgrade_slow(&self) { + // We only reach this point if PARKED_BIT is set. + let callback = |_, result: UnparkResult| { + // Clear the parked bit if there no more parked threads + if !result.have_more_threads { + self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); + } + TOKEN_NORMAL + }; + // SAFETY: `callback` does not panic or call into any function of `parking_lot`. + unsafe { + self.wake_parked_threads(ONE_READER, callback); + } + } + + #[cold] + fn downgrade_to_upgradable_slow(&self) { + // We only reach this point if PARKED_BIT is set. + let callback = |_, result: UnparkResult| { + // Clear the parked bit if there no more parked threads + if !result.have_more_threads { + self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); + } + TOKEN_NORMAL + }; + // SAFETY: `callback` does not panic or call into any function of `parking_lot`. + unsafe { + self.wake_parked_threads(ONE_READER | UPGRADABLE_BIT, callback); + } + } + + #[cold] + fn bump_shared_slow(&self) { + self.unlock_shared(); + self.lock_shared(); + } + + #[cold] + fn bump_exclusive_slow(&self) { + self.deadlock_release(); + self.unlock_exclusive_slow(true); + self.lock_exclusive(); + } + + #[cold] + fn bump_upgradable_slow(&self) { + self.deadlock_release(); + self.unlock_upgradable_slow(true); + self.lock_upgradable(); + } + + /// Common code for waking up parked threads after releasing WRITER_BIT or + /// UPGRADABLE_BIT. + /// + /// # Safety + /// + /// `callback` must uphold the requirements of the `callback` parameter to + /// `parking_lot_core::unpark_filter`. Meaning no panics or calls into any function in + /// `parking_lot`. + #[inline] + unsafe fn wake_parked_threads( + &self, + new_state: usize, + callback: impl FnOnce(usize, UnparkResult) -> UnparkToken, + ) { + // We must wake up at least one upgrader or writer if there is one, + // otherwise they may end up parked indefinitely since unlock_shared + // does not call wake_parked_threads. + let new_state = Cell::new(new_state); + let addr = self as *const _ as usize; + let filter = |ParkToken(token)| { + let s = new_state.get(); + + // If we are waking up a writer, don't wake anything else. + if s & WRITER_BIT != 0 { + return FilterOp::Stop; + } + + // Otherwise wake *all* readers and one upgrader/writer. + if token & (UPGRADABLE_BIT | WRITER_BIT) != 0 && s & UPGRADABLE_BIT != 0 { + // Skip writers and upgradable readers if we already have + // a writer/upgradable reader. + FilterOp::Skip + } else { + new_state.set(s + token); + FilterOp::Unpark + } + }; + let callback = |result| callback(new_state.get(), result); + // SAFETY: + // * `addr` is an address we control. + // * `filter` does not panic or call into any function of `parking_lot`. + // * `callback` safety responsibility is on caller + parking_lot_core::unpark_filter(addr, filter, callback); + } + + // Common code for waiting for readers to exit the lock after acquiring + // WRITER_BIT. + #[inline] + fn wait_for_readers(&self, timeout: Option, prev_value: usize) -> bool { + // At this point WRITER_BIT is already set, we just need to wait for the + // remaining readers to exit the lock. + let mut spinwait = SpinWait::new(); + let mut state = self.state.load(Ordering::Relaxed); + while state & READERS_MASK != 0 { + // Spin a few times to wait for readers to exit + if spinwait.spin() { + state = self.state.load(Ordering::Relaxed); + continue; + } + + // Set the parked bit + if state & WRITER_PARKED_BIT == 0 { + if let Err(x) = self.state.compare_exchange_weak( + state, + state | WRITER_PARKED_BIT, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + state = x; + continue; + } + } + + // Park our thread until we are woken up by an unlock + // Using the 2nd key at addr + 1 + let addr = self as *const _ as usize + 1; + let validate = || { + let state = self.state.load(Ordering::Relaxed); + state & READERS_MASK != 0 && state & WRITER_PARKED_BIT != 0 + }; + let before_sleep = || {}; + let timed_out = |_, _| {}; + // SAFETY: + // * `addr` is an address we control. + // * `validate`/`timed_out` does not panic or call into any function of `parking_lot`. + // * `before_sleep` does not call `park`, nor does it panic. + let park_result = unsafe { + parking_lot_core::park( + addr, + validate, + before_sleep, + timed_out, + TOKEN_EXCLUSIVE, + timeout, + ) + }; + match park_result { + // We still need to re-check the state if we are unparked + // since a previous writer timing-out could have allowed + // another reader to sneak in before we parked. + ParkResult::Unparked(_) | ParkResult::Invalid => { + state = self.state.load(Ordering::Relaxed); + continue; + } + + // Timeout expired + ParkResult::TimedOut => { + // We need to release WRITER_BIT and revert back to + // our previous value. We also wake up any threads that + // might be waiting on WRITER_BIT. + let state = self.state.fetch_add( + prev_value.wrapping_sub(WRITER_BIT | WRITER_PARKED_BIT), + Ordering::Relaxed, + ); + if state & PARKED_BIT != 0 { + let callback = |_, result: UnparkResult| { + // Clear the parked bit if there no more parked threads + if !result.have_more_threads { + self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); + } + TOKEN_NORMAL + }; + // SAFETY: `callback` does not panic or call any function of `parking_lot`. + unsafe { + self.wake_parked_threads(ONE_READER | UPGRADABLE_BIT, callback); + } + } + return false; + } + } + } + true + } + + /// Common code for acquiring a lock + #[inline] + fn lock_common( + &self, + timeout: Option, + token: ParkToken, + mut try_lock: impl FnMut(&mut usize) -> bool, + validate_flags: usize, + ) -> bool { + let mut spinwait = SpinWait::new(); + let mut state = self.state.load(Ordering::Relaxed); + loop { + // Attempt to grab the lock + if try_lock(&mut state) { + return true; + } + + // If there are no parked threads, try spinning a few times. + if state & (PARKED_BIT | WRITER_PARKED_BIT) == 0 && spinwait.spin() { + state = self.state.load(Ordering::Relaxed); + continue; + } + + // Set the parked bit + if state & PARKED_BIT == 0 { + if let Err(x) = self.state.compare_exchange_weak( + state, + state | PARKED_BIT, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + state = x; + continue; + } + } + + // Park our thread until we are woken up by an unlock + let addr = self as *const _ as usize; + let validate = || { + let state = self.state.load(Ordering::Relaxed); + state & PARKED_BIT != 0 && (state & validate_flags != 0) + }; + let before_sleep = || {}; + let timed_out = |_, was_last_thread| { + // Clear the parked bit if we were the last parked thread + if was_last_thread { + self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); + } + }; + + // SAFETY: + // * `addr` is an address we control. + // * `validate`/`timed_out` does not panic or call into any function of `parking_lot`. + // * `before_sleep` does not call `park`, nor does it panic. + let park_result = unsafe { + parking_lot_core::park(addr, validate, before_sleep, timed_out, token, timeout) + }; + match park_result { + // The thread that unparked us passed the lock on to us + // directly without unlocking it. + ParkResult::Unparked(TOKEN_HANDOFF) => return true, + + // We were unparked normally, try acquiring the lock again + ParkResult::Unparked(_) => (), + + // The validation function failed, try locking again + ParkResult::Invalid => (), + + // Timeout expired + ParkResult::TimedOut => return false, + } + + // Loop back and try locking again + spinwait.reset(); + state = self.state.load(Ordering::Relaxed); + } + } + + #[inline] + fn deadlock_acquire(&self) { + unsafe { deadlock::acquire_resource(self as *const _ as usize) }; + unsafe { deadlock::acquire_resource(self as *const _ as usize + 1) }; + } + + #[inline] + fn deadlock_release(&self) { + unsafe { deadlock::release_resource(self as *const _ as usize) }; + unsafe { deadlock::release_resource(self as *const _ as usize + 1) }; + } +} diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/remutex.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/remutex.rs similarity index 76% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/remutex.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/remutex.rs index aa40e14..6fdf107 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/remutex.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/remutex.rs @@ -5,8 +5,9 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use crate::raw_mutex::RawMutex; +use core::num::NonZeroUsize; use lock_api::{self, GetThreadId}; -use raw_mutex::RawMutex; /// Implementation of the `GetThreadId` trait for `lock_api::ReentrantMutex`. pub struct RawThreadId; @@ -14,11 +15,15 @@ pub struct RawThreadId; unsafe impl GetThreadId for RawThreadId { const INIT: RawThreadId = RawThreadId; - fn nonzero_thread_id(&self) -> usize { + fn nonzero_thread_id(&self) -> NonZeroUsize { // The address of a thread-local variable is guaranteed to be unique to the - // current thread, and is also guaranteed to be non-zero. - thread_local!(static KEY: u8 = unsafe { ::std::mem::uninitialized() }); - KEY.with(|x| x as *const _ as usize) + // current thread, and is also guaranteed to be non-zero. The variable has to have a + // non-zero size to guarantee it has a unique address for each thread. + thread_local!(static KEY: u8 = 0); + KEY.with(|x| { + NonZeroUsize::new(x as *const _ as usize) + .expect("thread-local variable address is null") + }) } } @@ -54,25 +59,28 @@ pub type MappedReentrantMutexGuard<'a, T> = #[cfg(test)] mod tests { + use crate::ReentrantMutex; use std::cell::RefCell; use std::sync::Arc; use std::thread; - use ReentrantMutex; + + #[cfg(feature = "serde")] + use bincode::{deserialize, serialize}; #[test] fn smoke() { - let m = ReentrantMutex::new(()); + let m = ReentrantMutex::new(2); { let a = m.lock(); { let b = m.lock(); { let c = m.lock(); - assert_eq!(*c, ()); + assert_eq!(*c, 2); } - assert_eq!(*b, ()); + assert_eq!(*b, 2); } - assert_eq!(*a, ()); + assert_eq!(*a, 2); } } @@ -113,14 +121,18 @@ mod tests { let mutex = ReentrantMutex::new(vec![0u8, 10]); assert_eq!(format!("{:?}", mutex), "ReentrantMutex { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", mutex), - "ReentrantMutex { - data: [ - 0, - 10 - ] -}" - ); + } + + #[cfg(feature = "serde")] + #[test] + fn test_serde() { + let contents: Vec = vec![0, 1, 2]; + let mutex = ReentrantMutex::new(contents.clone()); + + let serialized = serialize(&mutex).unwrap(); + let deserialized: ReentrantMutex> = deserialize(&serialized).unwrap(); + + assert_eq!(*(mutex.lock()), *(deserialized.lock())); + assert_eq!(contents, *(deserialized.lock())); } } diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/rwlock.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/rwlock.rs similarity index 94% rename from third_party/cargo/vendor/parking_lot-0.7.1/src/rwlock.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/rwlock.rs index f970924..776cec0 100644 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/rwlock.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/rwlock.rs @@ -5,8 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use crate::raw_rwlock::RawRwLock; use lock_api; -use raw_rwlock::RawRwLock; /// A reader-writer lock /// @@ -120,14 +120,16 @@ pub type RwLockUpgradableReadGuard<'a, T> = lock_api::RwLockUpgradableReadGuard< #[cfg(test)] mod tests { - extern crate rand; - use self::rand::Rng; + use crate::{RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard}; + use rand::Rng; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::channel; use std::sync::Arc; use std::thread; use std::time::Duration; - use {RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard}; + + #[cfg(feature = "serde")] + use bincode::{deserialize, serialize}; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); @@ -320,7 +322,7 @@ mod tests { fn test_rw_arc_access_in_unwind() { let arc = Arc::new(RwLock::new(1)); let arc2 = arc.clone(); - let _ = thread::spawn(move || -> () { + let _ = thread::spawn(move || { struct Unwinder { i: Arc>, } @@ -534,7 +536,15 @@ mod tests { thread::spawn(move || { let _lock = arc2.write(); }); - thread::sleep(Duration::from_millis(100)); + + if cfg!(not(all(target_env = "sgx", target_vendor = "fortanix"))) { + thread::sleep(Duration::from_millis(100)); + } else { + // FIXME: https://github.com/fortanix/rust-sgx/issues/31 + for _ in 0..100 { + thread::yield_now(); + } + } // A normal read would block here since there is a pending writer let _lock2 = arc.read_recursive(); @@ -545,17 +555,8 @@ mod tests { let x = RwLock::new(vec![0u8, 10]); assert_eq!(format!("{:?}", x), "RwLock { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", x), - "RwLock { - data: [ - 0, - 10 - ] -}" - ); let _lock = x.write(); - assert_eq!(format!("{:?}", x), "RwLock { }"); + assert_eq!(format!("{:?}", x), "RwLock { data: }"); } #[test] @@ -565,4 +566,17 @@ mod tests { let b = a.clone(); assert_eq!(Arc::strong_count(&b), 2); } + + #[cfg(feature = "serde")] + #[test] + fn test_serde() { + let contents: Vec = vec![0, 1, 2]; + let mutex = RwLock::new(contents.clone()); + + let serialized = serialize(&mutex).unwrap(); + let deserialized: RwLock> = deserialize(&serialized).unwrap(); + + assert_eq!(*(mutex.read()), *(deserialized.read())); + assert_eq!(contents, *(deserialized.read())); + } } diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/util.rs b/third_party/cargo/vendor/parking_lot-0.10.0/src/util.rs similarity index 75% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/src/util.rs rename to third_party/cargo/vendor/parking_lot-0.10.0/src/util.rs index c7dfd32..c5496fc 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/util.rs +++ b/third_party/cargo/vendor/parking_lot-0.10.0/src/util.rs @@ -5,6 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use std::time::{Duration, Instant}; + // Option::unchecked_unwrap pub trait UncheckedOptionExt { unsafe fn unchecked_unwrap(self) -> T; @@ -20,13 +22,17 @@ impl UncheckedOptionExt for Option { } } -// Equivalent to intrinsics::unreachable() in release mode +// hint::unreachable_unchecked() in release mode #[inline] unsafe fn unreachable() -> ! { if cfg!(debug_assertions) { unreachable!(); } else { - enum Void {} - match *(1 as *const Void) {} + core::hint::unreachable_unchecked() } } + +#[inline] +pub fn to_deadline(timeout: Duration) -> Option { + Instant::now().checked_add(timeout) +} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot-0.6.4/.cargo-checksum.json deleted file mode 100644 index 336edcf..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"e254fac6600c725edb746f31f41b1b2ceeb9cfc85f4f9a3e6af874c70b020823","Cargo.toml":"e5d073e0f98041047612bb2e226585f81fcb2d3eabef9579c9ce322f7708b38d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"a52cf38f796e7f12215662e8a3a23aa9802c170a09ecba0e4be766c88f95a9c5","appveyor.yml":"cb1d02316926d88e174976bfc6781194569ca27f386c50e3091d8e52587d30a2","src/condvar.rs":"ce127f75bad5c175abb8147aac4b5be78aabdb599c5f8f3aad77f6bc3705274d","src/deadlock.rs":"8916c2e2820bfd3a55860ddb9f1b907888406b68cdae2b7a2093c825d28f3b99","src/elision.rs":"89072fe0aca87d53abc0f56490ae77bcf9d77e28e291bd13e861b1924bbb079f","src/lib.rs":"3e259bf3421f10c3e920daca511a4880b2620145a1fcb070a37548835c4f429a","src/mutex.rs":"0ac3e654e4aa2c3078a6aa22c83428d604e7f3f8ed4c261c40d030d232ca7b64","src/once.rs":"606e0e88d6c1ff82b69bda56e7409ec3a1aefa66b45b7fa42b88cba07ae70598","src/raw_mutex.rs":"881e75a843d76399d01c4ae0f09cd23b93b137b5035a47bd7886505132e58165","src/raw_rwlock.rs":"2e3c13e80cd06be53118ae2bcc7bdec708dda8c139c371ee12885f48903cf69c","src/remutex.rs":"bad8022610344086010b0661998a416db4b458c222e671b67df03fc4795c0298","src/rwlock.rs":"fc826cbcf2d7862ecb184b657a82bb8794a9e26ac329c8f87b589fa09f15d245","src/util.rs":"2d07c0c010a857790ae2ed6a1215eeed8af76859e076797ea1ba8dec82169e84"},"package":"f0802bff09003b291ba756dc7e79313e51cc31667e94afbe847def490424cde5"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/CHANGELOG.md b/third_party/cargo/vendor/parking_lot-0.6.4/CHANGELOG.md deleted file mode 100644 index 20651aa..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/CHANGELOG.md +++ /dev/null @@ -1,48 +0,0 @@ -0.6.3 (2018-07-18) -================== - -- Export `RawMutex`, `RawRwLock` and `RawThreadId`. - -0.6.2 (2018-06-18) -================== - -- Enable `lock_api/nightly` feature from `parking_lot/nightly` (#79) - -0.6.1 (2018-06-08) -================== - -Added missing typedefs for mapped lock guards: - -- `MappedMutexGuard` -- `MappedReentrantMutexGuard` -- `MappedRwLockReadGuard` -- `MappedRwLockWriteGuard` - -0.6.0 (2018-06-08) -================== - -This release moves most of the code for type-safe `Mutex` and `RwLock` types -into a separate crate called `lock_api`. This new crate is compatible with -`no_std` and provides `Mutex` and `RwLock` type-safe wrapper types from a -raw mutex type which implements the `RawMutex` or `RawRwLock` trait. The API -provided by the wrapper types can be extended by implementing more traits on the -raw mutex type which provide more functionality (e.g. `RawMutexTimed`). See the -crate documentation for more details. - -There are also several major changes: - -- The minimum required Rust version is bumped to 1.26. -- All methods on `MutexGuard` (and other guard types) are no longer inherent - methods and must be called as `MutexGuard::method(self)`. This avoids - conflicts with methods from the inner type. -- `MutexGuard` (and other guard types) add the `unlocked` method which - temporarily unlocks a mutex, runs the given closure, and then re-locks the - mutex. -- `MutexGuard` (and other guard types) add the `bump` method which gives a - chance for other threads to acquire the mutex by temporarily unlocking it and - re-locking it. However this is optimized for the common case where there are - no threads waiting on the lock, in which case no unlocking is performed. -- `MutexGuard` (and other guard types) add the `map` method which returns a - `MappedMutexGuard` which holds only a subset of the original locked type. The - `MappedMutexGuard` type is identical to `MutexGuard` except that it does not - support the `unlocked` and `bump` methods, and can't be used with `CondVar`. diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/Cargo.toml b/third_party/cargo/vendor/parking_lot-0.6.4/Cargo.toml deleted file mode 100644 index 67765d1..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/Cargo.toml +++ /dev/null @@ -1,35 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "parking_lot" -version = "0.6.4" -authors = ["Amanieu d'Antras "] -description = "More compact and efficient implementations of the standard synchronization primitives." -readme = "README.md" -keywords = ["mutex", "condvar", "rwlock", "once", "thread"] -categories = ["concurrency"] -license = "Apache-2.0/MIT" -repository = "https://github.com/Amanieu/parking_lot" -[dependencies.lock_api] -version = "0.1" - -[dependencies.parking_lot_core] -version = "0.3" -[dev-dependencies.rand] -version = "0.5" - -[features] -deadlock_detection = ["parking_lot_core/deadlock_detection"] -default = ["owning_ref"] -nightly = ["parking_lot_core/nightly", "lock_api/nightly"] -owning_ref = ["lock_api/owning_ref"] diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/README.md b/third_party/cargo/vendor/parking_lot-0.6.4/README.md deleted file mode 100644 index 4e9204c..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/README.md +++ /dev/null @@ -1,138 +0,0 @@ -parking_lot -============ - -[![Build Status](https://travis-ci.org/Amanieu/parking_lot.svg?branch=master)](https://travis-ci.org/Amanieu/parking_lot) [![Build status](https://ci.appveyor.com/api/projects/status/wppcc32ttpud0a30/branch/master?svg=true)](https://ci.appveyor.com/project/Amanieu/parking-lot/branch/master) [![Crates.io](https://img.shields.io/crates/v/parking_lot.svg)](https://crates.io/crates/parking_lot) - -[Documentation (synchronization primitives)](https://docs.rs/parking_lot/) - -[Documentation (core parking lot API)](https://docs.rs/parking_lot_core/) - -[Documentation (type-safe lock API)](https://docs.rs/lock_api/) - -This library provides implementations of `Mutex`, `RwLock`, `Condvar` and -`Once` that are smaller, faster and more flexible than those in the Rust -standard library, as well as a `ReentrantMutex` type which supports recursive -locking. It also exposes a low-level API for creating your own efficient -synchronization primitives. - -When tested on x86_64 Linux, `parking_lot::Mutex` was found to be 1.5x -faster than `std::sync::Mutex` when uncontended, and up to 5x faster when -contended from multiple threads. The numbers for `RwLock` vary depending on -the number of reader and writer threads, but are almost always faster than -the standard library `RwLock`, and even up to 50x faster in some cases. - -## Features - -The primitives provided by this library have several advantages over those -in the Rust standard library: - -1. `Mutex` and `Once` only require 1 byte of storage space, while `Condvar` - and `RwLock` only require 1 word of storage space. On the other hand the - standard library primitives require a dynamically allocated `Box` to hold - OS-specific synchronization primitives. The small size of `Mutex` in - particular encourages the use of fine-grained locks to increase - parallelism. -2. Since they consist of just a single atomic variable, have constant - initializers and don't need destructors, these primitives can be used as - `static` global variables. The standard library primitives require - dynamic initialization and thus need to be lazily initialized with - `lazy_static!`. -3. Uncontended lock acquisition and release is done through fast inline - paths which only require a single atomic operation. -4. Microcontention (a contended lock with a short critical section) is - efficiently handled by spinning a few times while trying to acquire a - lock. -5. The locks are adaptive and will suspend a thread after a few failed spin - attempts. This makes the locks suitable for both long and short critical - sections. -6. `Condvar`, `RwLock` and `Once` work on Windows XP, unlike the standard - library versions of those types. -7. `RwLock` takes advantage of hardware lock elision on processors that - support it, which can lead to huge performance wins with many readers. -8. `RwLock` uses a task-fair locking policy, which avoids reader and writer - starvation, whereas the standard library version makes no guarantees. -9. `Condvar` is guaranteed not to produce spurious wakeups. A thread will - only be woken up if it timed out or it was woken up by a notification. -10. `Condvar::notify_all` will only wake up a single thread and requeue the - rest to wait on the associated `Mutex`. This avoids a thundering herd - problem where all threads try to acquire the lock at the same time. -11. `RwLock` supports atomically downgrading a write lock into a read lock. -12. `Mutex` and `RwLock` allow raw unlocking without a RAII guard object. -13. `Mutex<()>` and `RwLock<()>` allow raw locking without a RAII guard - object. -14. `Mutex` and `RwLock` support [eventual fairness](https://trac.webkit.org/changeset/203350) - which allows them to be fair on average without sacrificing performance. -15. A `ReentrantMutex` type which supports recursive locking. -16. An *experimental* deadlock detector that works for `Mutex`, - `RwLock` and `ReentrantMutex`. This feature is disabled by default and - can be enabled via the `deadlock_detection` feature. -17. `RwLock` supports atomically upgrading an "upgradable" read lock into a - write lock. - -## The parking lot - -To keep these primitives small, all thread queuing and suspending -functionality is offloaded to the *parking lot*. The idea behind this is -based on the Webkit [`WTF::ParkingLot`](https://webkit.org/blog/6161/locking-in-webkit/) -class, which essentially consists of a hash table mapping of lock addresses -to queues of parked (sleeping) threads. The Webkit parking lot was itself -inspired by Linux [futexes](http://man7.org/linux/man-pages/man2/futex.2.html), -but it is more powerful since it allows invoking callbacks while holding a queue -lock. - -## Nightly vs stable - -There are a few restrictions when using this library on stable Rust: - -- `Mutex` and `Once` will use 1 word of space instead of 1 byte. -- You will have to use `lazy_static!` to statically initialize `Mutex`, - `Condvar` and `RwLock` types instead of `const fn`. -- `RwLock` will not be able to take advantage of hardware lock elision for - readers, which improves performance when there are multiple readers. - -To enable nightly-only functionality, you need to enable the `nightly` feature -in Cargo (see below). - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -parking_lot = "0.6" -``` - -and this to your crate root: - -```rust -extern crate parking_lot; -``` - -To enable nightly-only features, add this to your `Cargo.toml` instead: - -```toml -[dependencies] -parking_lot = {version = "0.6", features = ["nightly"]} -``` - -The experimental deadlock detector can be enabled with the -`deadlock_detection` Cargo feature. - -The core parking lot API is provided by the `parking_lot_core` crate. It is -separate from the synchronization primitives in the `parking_lot` crate so that -changes to the core API do not cause breaking changes for users of `parking_lot`. - -## License - -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 the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any -additional terms or conditions. diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/appveyor.yml b/third_party/cargo/vendor/parking_lot-0.6.4/appveyor.yml deleted file mode 100644 index fef6b57..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/appveyor.yml +++ /dev/null @@ -1,29 +0,0 @@ -environment: - TRAVIS_CARGO_NIGHTLY_FEATURE: nightly - RUST_TEST_THREADS: 1 - matrix: - - TARGET: nightly-x86_64-pc-windows-msvc - - TARGET: nightly-i686-pc-windows-msvc - - TARGET: nightly-x86_64-pc-windows-gnu - - TARGET: nightly-i686-pc-windows-gnu - - TARGET: 1.24.0-x86_64-pc-windows-msvc - - TARGET: 1.24.0-i686-pc-windows-msvc - - TARGET: 1.24.0-x86_64-pc-windows-gnu - - TARGET: 1.24.0-i686-pc-windows-gnu - -install: - - SET PATH=C:\Python27;C:\Python27\Scripts;%PATH%;%APPDATA%\Python\Scripts - - pip install "travis-cargo<0.2" --user - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe" - - ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null - - ps: $env:PATH="$env:PATH;C:\rust\bin" - - rustc -vV - - cargo -vV - -build_script: - - travis-cargo build - -test_script: - - travis-cargo test - - travis-cargo test -- --features=deadlock_detection - - travis-cargo doc diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/condvar.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/condvar.rs deleted file mode 100644 index 89ddac7..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/condvar.rs +++ /dev/null @@ -1,533 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use deadlock; -use lock_api::RawMutex as RawMutexTrait; -use mutex::MutexGuard; -use parking_lot_core::{self, ParkResult, RequeueOp, UnparkResult, DEFAULT_PARK_TOKEN}; -use raw_mutex::{RawMutex, TOKEN_HANDOFF, TOKEN_NORMAL}; -use std::sync::atomic::{AtomicPtr, Ordering}; -use std::time::{Duration, Instant}; -use std::{fmt, ptr}; - -/// A type indicating whether a timed wait on a condition variable returned -/// due to a time out or not. -#[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub struct WaitTimeoutResult(bool); - -impl WaitTimeoutResult { - /// Returns whether the wait was known to have timed out. - #[inline] - pub fn timed_out(&self) -> bool { - self.0 - } -} - -/// A Condition Variable -/// -/// Condition variables represent the ability to block a thread such that it -/// consumes no CPU time while waiting for an event to occur. Condition -/// variables are typically associated with a boolean predicate (a condition) -/// and a mutex. The predicate is always verified inside of the mutex before -/// determining that thread must block. -/// -/// Note that this module places one additional restriction over the system -/// condition variables: each condvar can be used with only one mutex at a -/// time. Any attempt to use multiple mutexes on the same condition variable -/// simultaneously will result in a runtime panic. However it is possible to -/// switch to a different mutex if there are no threads currently waiting on -/// the condition variable. -/// -/// # Differences from the standard library `Condvar` -/// -/// - No spurious wakeups: A wait will only return a non-timeout result if it -/// was woken up by `notify_one` or `notify_all`. -/// - `Condvar::notify_all` will only wake up a single thread, the rest are -/// requeued to wait for the `Mutex` to be unlocked by the thread that was -/// woken up. -/// - Only requires 1 word of space, whereas the standard library boxes the -/// `Condvar` due to platform limitations. -/// - Can be statically constructed (requires the `const_fn` nightly feature). -/// - Does not require any drop glue when dropped. -/// - Inline fast path for the uncontended case. -/// -/// # Examples -/// -/// ``` -/// use parking_lot::{Mutex, Condvar}; -/// use std::sync::Arc; -/// use std::thread; -/// -/// let pair = Arc::new((Mutex::new(false), Condvar::new())); -/// let pair2 = pair.clone(); -/// -/// // Inside of our lock, spawn a new thread, and then wait for it to start -/// thread::spawn(move|| { -/// let &(ref lock, ref cvar) = &*pair2; -/// let mut started = lock.lock(); -/// *started = true; -/// cvar.notify_one(); -/// }); -/// -/// // wait for the thread to start up -/// let &(ref lock, ref cvar) = &*pair; -/// let mut started = lock.lock(); -/// while !*started { -/// cvar.wait(&mut started); -/// } -/// ``` -pub struct Condvar { - state: AtomicPtr, -} - -impl Condvar { - /// Creates a new condition variable which is ready to be waited on and - /// notified. - #[cfg(feature = "nightly")] - #[inline] - pub const fn new() -> Condvar { - Condvar { - state: AtomicPtr::new(ptr::null_mut()), - } - } - - /// Creates a new condition variable which is ready to be waited on and - /// notified. - #[cfg(not(feature = "nightly"))] - #[inline] - pub fn new() -> Condvar { - Condvar { - state: AtomicPtr::new(ptr::null_mut()), - } - } - - /// Wakes up one blocked thread on this condvar. - /// - /// If there is a blocked thread on this condition variable, then it will - /// be woken up from its call to `wait` or `wait_timeout`. Calls to - /// `notify_one` are not buffered in any way. - /// - /// To wake up all threads, see `notify_all()`. - #[inline] - pub fn notify_one(&self) { - // Nothing to do if there are no waiting threads - if self.state.load(Ordering::Relaxed).is_null() { - return; - } - - self.notify_one_slow(); - } - - #[cold] - #[inline(never)] - fn notify_one_slow(&self) { - unsafe { - // Unpark one thread - let addr = self as *const _ as usize; - let callback = |result: UnparkResult| { - // Clear our state if there are no more waiting threads - if !result.have_more_threads { - self.state.store(ptr::null_mut(), Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_one(addr, callback); - } - } - - /// Wakes up all blocked threads on this condvar. - /// - /// This method will ensure that any current waiters on the condition - /// variable are awoken. Calls to `notify_all()` are not buffered in any - /// way. - /// - /// To wake up only one thread, see `notify_one()`. - #[inline] - pub fn notify_all(&self) { - // Nothing to do if there are no waiting threads - let state = self.state.load(Ordering::Relaxed); - if state.is_null() { - return; - } - - self.notify_all_slow(state); - } - - #[cold] - #[inline(never)] - fn notify_all_slow(&self, mutex: *mut RawMutex) { - unsafe { - // Unpark one thread and requeue the rest onto the mutex - let from = self as *const _ as usize; - let to = mutex as usize; - let validate = || { - // Make sure that our atomic state still points to the same - // mutex. If not then it means that all threads on the current - // mutex were woken up and a new waiting thread switched to a - // different mutex. In that case we can get away with doing - // nothing. - if self.state.load(Ordering::Relaxed) != mutex { - return RequeueOp::Abort; - } - - // Clear our state since we are going to unpark or requeue all - // threads. - self.state.store(ptr::null_mut(), Ordering::Relaxed); - - // Unpark one thread if the mutex is unlocked, otherwise just - // requeue everything to the mutex. This is safe to do here - // since unlocking the mutex when the parked bit is set requires - // locking the queue. There is the possibility of a race if the - // mutex gets locked after we check, but that doesn't matter in - // this case. - if (*mutex).mark_parked_if_locked() { - RequeueOp::RequeueAll - } else { - RequeueOp::UnparkOneRequeueRest - } - }; - let callback = |op, result: UnparkResult| { - // If we requeued threads to the mutex, mark it as having - // parked threads. The RequeueAll case is already handled above. - if op == RequeueOp::UnparkOneRequeueRest && result.have_more_threads { - (*mutex).mark_parked(); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_requeue(from, to, validate, callback); - } - } - - /// Blocks the current thread until this condition variable receives a - /// notification. - /// - /// This function will atomically unlock the mutex specified (represented by - /// `mutex_guard`) and block the current thread. This means that any calls - /// to `notify_*()` which happen logically after the mutex is unlocked are - /// candidates to wake this thread up. When this function call returns, the - /// lock specified will have been re-acquired. - /// - /// # Panics - /// - /// This function will panic if another thread is waiting on the `Condvar` - /// with a different `Mutex` object. - #[inline] - pub fn wait(&self, mutex_guard: &mut MutexGuard) { - self.wait_until_internal(unsafe { MutexGuard::mutex(mutex_guard).raw() }, None); - } - - /// Waits on this condition variable for a notification, timing out after - /// the specified time instant. - /// - /// The semantics of this function are equivalent to `wait()` except that - /// the thread will be blocked roughly until `timeout` is reached. This - /// method should not be used for precise timing due to anomalies such as - /// preemption or platform differences that may not cause the maximum - /// amount of time waited to be precisely `timeout`. - /// - /// Note that the best effort is made to ensure that the time waited is - /// measured with a monotonic clock, and not affected by the changes made to - /// the system time. - /// - /// The returned `WaitTimeoutResult` value indicates if the timeout is - /// known to have elapsed. - /// - /// Like `wait`, the lock specified will be re-acquired when this function - /// returns, regardless of whether the timeout elapsed or not. - /// - /// # Panics - /// - /// This function will panic if another thread is waiting on the `Condvar` - /// with a different `Mutex` object. - #[inline] - pub fn wait_until( - &self, - mutex_guard: &mut MutexGuard, - timeout: Instant, - ) -> WaitTimeoutResult { - self.wait_until_internal( - unsafe { MutexGuard::mutex(mutex_guard).raw() }, - Some(timeout), - ) - } - - // This is a non-generic function to reduce the monomorphization cost of - // using `wait_until`. - fn wait_until_internal( - &self, - mutex: &RawMutex, - timeout: Option, - ) -> WaitTimeoutResult { - unsafe { - let result; - let mut bad_mutex = false; - let mut requeued = false; - { - let addr = self as *const _ as usize; - let lock_addr = mutex as *const _ as *mut _; - let validate = || { - // Ensure we don't use two different mutexes with the same - // Condvar at the same time. This is done while locked to - // avoid races with notify_one - let state = self.state.load(Ordering::Relaxed); - if state.is_null() { - self.state.store(lock_addr, Ordering::Relaxed); - } else if state != lock_addr { - bad_mutex = true; - return false; - } - true - }; - let before_sleep = || { - // Unlock the mutex before sleeping... - mutex.unlock(); - }; - let timed_out = |k, was_last_thread| { - // If we were requeued to a mutex, then we did not time out. - // We'll just park ourselves on the mutex again when we try - // to lock it later. - requeued = k != addr; - - // If we were the last thread on the queue then we need to - // clear our state. This is normally done by the - // notify_{one,all} functions when not timing out. - if !requeued && was_last_thread { - self.state.store(ptr::null_mut(), Ordering::Relaxed); - } - }; - result = parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - DEFAULT_PARK_TOKEN, - timeout, - ); - } - - // Panic if we tried to use multiple mutexes with a Condvar. Note - // that at this point the MutexGuard is still locked. It will be - // unlocked by the unwinding logic. - if bad_mutex { - panic!("attempted to use a condition variable with more than one mutex"); - } - - // ... and re-lock it once we are done sleeping - if result == ParkResult::Unparked(TOKEN_HANDOFF) { - deadlock::acquire_resource(mutex as *const _ as usize); - } else { - mutex.lock(); - } - - WaitTimeoutResult(!(result.is_unparked() || requeued)) - } - } - - /// Waits on this condition variable for a notification, timing out after a - /// specified duration. - /// - /// The semantics of this function are equivalent to `wait()` except that - /// the thread will be blocked for roughly no longer than `timeout`. This - /// method should not be used for precise timing due to anomalies such as - /// preemption or platform differences that may not cause the maximum - /// amount of time waited to be precisely `timeout`. - /// - /// Note that the best effort is made to ensure that the time waited is - /// measured with a monotonic clock, and not affected by the changes made to - /// the system time. - /// - /// The returned `WaitTimeoutResult` value indicates if the timeout is - /// known to have elapsed. - /// - /// Like `wait`, the lock specified will be re-acquired when this function - /// returns, regardless of whether the timeout elapsed or not. - #[inline] - pub fn wait_for( - &self, - guard: &mut MutexGuard, - timeout: Duration, - ) -> WaitTimeoutResult { - self.wait_until(guard, Instant::now() + timeout) - } -} - -impl Default for Condvar { - #[inline] - fn default() -> Condvar { - Condvar::new() - } -} - -impl fmt::Debug for Condvar { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.pad("Condvar { .. }") - } -} - -#[cfg(test)] -mod tests { - use std::sync::mpsc::channel; - use std::sync::Arc; - use std::thread; - use std::time::{Duration, Instant}; - use {Condvar, Mutex}; - - #[test] - fn smoke() { - let c = Condvar::new(); - c.notify_one(); - c.notify_all(); - } - - #[test] - fn notify_one() { - let m = Arc::new(Mutex::new(())); - let m2 = m.clone(); - let c = Arc::new(Condvar::new()); - let c2 = c.clone(); - - let mut g = m.lock(); - let _t = thread::spawn(move || { - let _g = m2.lock(); - c2.notify_one(); - }); - c.wait(&mut g); - } - - #[test] - fn notify_all() { - const N: usize = 10; - - let data = Arc::new((Mutex::new(0), Condvar::new())); - let (tx, rx) = channel(); - for _ in 0..N { - let data = data.clone(); - let tx = tx.clone(); - thread::spawn(move || { - let &(ref lock, ref cond) = &*data; - let mut cnt = lock.lock(); - *cnt += 1; - if *cnt == N { - tx.send(()).unwrap(); - } - while *cnt != 0 { - cond.wait(&mut cnt); - } - tx.send(()).unwrap(); - }); - } - drop(tx); - - let &(ref lock, ref cond) = &*data; - rx.recv().unwrap(); - let mut cnt = lock.lock(); - *cnt = 0; - cond.notify_all(); - drop(cnt); - - for _ in 0..N { - rx.recv().unwrap(); - } - } - - #[test] - fn wait_for() { - let m = Arc::new(Mutex::new(())); - let m2 = m.clone(); - let c = Arc::new(Condvar::new()); - let c2 = c.clone(); - - let mut g = m.lock(); - let no_timeout = c.wait_for(&mut g, Duration::from_millis(1)); - assert!(no_timeout.timed_out()); - let _t = thread::spawn(move || { - let _g = m2.lock(); - c2.notify_one(); - }); - let timeout_res = c.wait_for(&mut g, Duration::from_millis(u32::max_value() as u64)); - assert!(!timeout_res.timed_out()); - drop(g); - } - - #[test] - fn wait_until() { - let m = Arc::new(Mutex::new(())); - let m2 = m.clone(); - let c = Arc::new(Condvar::new()); - let c2 = c.clone(); - - let mut g = m.lock(); - let no_timeout = c.wait_until(&mut g, Instant::now() + Duration::from_millis(1)); - assert!(no_timeout.timed_out()); - let _t = thread::spawn(move || { - let _g = m2.lock(); - c2.notify_one(); - }); - let timeout_res = c.wait_until( - &mut g, - Instant::now() + Duration::from_millis(u32::max_value() as u64), - ); - assert!(!timeout_res.timed_out()); - drop(g); - } - - #[test] - #[should_panic] - fn two_mutexes() { - let m = Arc::new(Mutex::new(())); - let m2 = m.clone(); - let m3 = Arc::new(Mutex::new(())); - let c = Arc::new(Condvar::new()); - let c2 = c.clone(); - - // Make sure we don't leave the child thread dangling - struct PanicGuard<'a>(&'a Condvar); - impl<'a> Drop for PanicGuard<'a> { - fn drop(&mut self) { - self.0.notify_one(); - } - } - - let (tx, rx) = channel(); - let g = m.lock(); - let _t = thread::spawn(move || { - let mut g = m2.lock(); - tx.send(()).unwrap(); - c2.wait(&mut g); - }); - drop(g); - rx.recv().unwrap(); - let _g = m.lock(); - let _guard = PanicGuard(&*c); - let _ = c.wait(&mut m3.lock()); - } - - #[test] - fn two_mutexes_disjoint() { - let m = Arc::new(Mutex::new(())); - let m2 = m.clone(); - let m3 = Arc::new(Mutex::new(())); - let c = Arc::new(Condvar::new()); - let c2 = c.clone(); - - let mut g = m.lock(); - let _t = thread::spawn(move || { - let _g = m2.lock(); - c2.notify_one(); - }); - c.wait(&mut g); - drop(g); - - let _ = c.wait_for(&mut m3.lock(), Duration::from_millis(1)); - } - - #[test] - fn test_debug_condvar() { - let c = Condvar::new(); - assert_eq!(format!("{:?}", c), "Condvar { .. }"); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/deadlock.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/deadlock.rs deleted file mode 100644 index ef7d619..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/deadlock.rs +++ /dev/null @@ -1,218 +0,0 @@ -//! \[Experimental\] Deadlock detection -//! -//! This feature is optional and can be enabled via the `deadlock_detection` feature flag. -//! -//! # Example -//! -//! ``` -//! #[cfg(feature = "deadlock_detection")] -//! { // only for #[cfg] -//! use std::thread; -//! use std::time::Duration; -//! use parking_lot::deadlock; -//! -//! // Create a background thread which checks for deadlocks every 10s -//! thread::spawn(move || { -//! loop { -//! thread::sleep(Duration::from_secs(10)); -//! let deadlocks = deadlock::check_deadlock(); -//! if deadlocks.is_empty() { -//! continue; -//! } -//! -//! println!("{} deadlocks detected", deadlocks.len()); -//! for (i, threads) in deadlocks.iter().enumerate() { -//! println!("Deadlock #{}", i); -//! for t in threads { -//! println!("Thread Id {:#?}", t.thread_id()); -//! println!("{:#?}", t.backtrace()); -//! } -//! } -//! } -//! }); -//! } // only for #[cfg] -//! ``` - -#[cfg(feature = "deadlock_detection")] -pub use parking_lot_core::deadlock::check_deadlock; -pub(crate) use parking_lot_core::deadlock::{acquire_resource, release_resource}; - -#[cfg(test)] -#[cfg(feature = "deadlock_detection")] -mod tests { - use std::sync::{Arc, Barrier}; - use std::thread::{self, sleep}; - use std::time::Duration; - use {Mutex, ReentrantMutex, RwLock}; - - fn check_deadlock() -> bool { - use parking_lot_core::deadlock::check_deadlock; - !check_deadlock().is_empty() - } - - #[test] - fn test_mutex_deadlock() { - let m1: Arc> = Default::default(); - let m2: Arc> = Default::default(); - let m3: Arc> = Default::default(); - let b = Arc::new(Barrier::new(4)); - - let m1_ = m1.clone(); - let m2_ = m2.clone(); - let m3_ = m3.clone(); - let b1 = b.clone(); - let b2 = b.clone(); - let b3 = b.clone(); - - assert!(!check_deadlock()); - - let _t1 = thread::spawn(move || { - let _g = m1.lock(); - b1.wait(); - let _ = m2_.lock(); - }); - - let _t2 = thread::spawn(move || { - let _g = m2.lock(); - b2.wait(); - let _ = m3_.lock(); - }); - - let _t3 = thread::spawn(move || { - let _g = m3.lock(); - b3.wait(); - let _ = m1_.lock(); - }); - - assert!(!check_deadlock()); - - b.wait(); - sleep(Duration::from_millis(50)); - assert!(check_deadlock()); - - assert!(!check_deadlock()); - } - - #[test] - fn test_mutex_deadlock_reentrant() { - let m1: Arc> = Default::default(); - - assert!(!check_deadlock()); - - let _t1 = thread::spawn(move || { - let _g = m1.lock(); - let _ = m1.lock(); - }); - - sleep(Duration::from_millis(50)); - assert!(check_deadlock()); - - assert!(!check_deadlock()); - } - - #[test] - fn test_remutex_deadlock() { - let m1: Arc> = Default::default(); - let m2: Arc> = Default::default(); - let m3: Arc> = Default::default(); - let b = Arc::new(Barrier::new(4)); - - let m1_ = m1.clone(); - let m2_ = m2.clone(); - let m3_ = m3.clone(); - let b1 = b.clone(); - let b2 = b.clone(); - let b3 = b.clone(); - - assert!(!check_deadlock()); - - let _t1 = thread::spawn(move || { - let _g = m1.lock(); - let _g = m1.lock(); - b1.wait(); - let _ = m2_.lock(); - }); - - let _t2 = thread::spawn(move || { - let _g = m2.lock(); - let _g = m2.lock(); - b2.wait(); - let _ = m3_.lock(); - }); - - let _t3 = thread::spawn(move || { - let _g = m3.lock(); - let _g = m3.lock(); - b3.wait(); - let _ = m1_.lock(); - }); - - assert!(!check_deadlock()); - - b.wait(); - sleep(Duration::from_millis(50)); - assert!(check_deadlock()); - - assert!(!check_deadlock()); - } - - #[test] - fn test_rwlock_deadlock() { - let m1: Arc> = Default::default(); - let m2: Arc> = Default::default(); - let m3: Arc> = Default::default(); - let b = Arc::new(Barrier::new(4)); - - let m1_ = m1.clone(); - let m2_ = m2.clone(); - let m3_ = m3.clone(); - let b1 = b.clone(); - let b2 = b.clone(); - let b3 = b.clone(); - - assert!(!check_deadlock()); - - let _t1 = thread::spawn(move || { - let _g = m1.read(); - b1.wait(); - let _g = m2_.write(); - }); - - let _t2 = thread::spawn(move || { - let _g = m2.read(); - b2.wait(); - let _g = m3_.write(); - }); - - let _t3 = thread::spawn(move || { - let _g = m3.read(); - b3.wait(); - let _ = m1_.write(); - }); - - assert!(!check_deadlock()); - - b.wait(); - sleep(Duration::from_millis(50)); - assert!(check_deadlock()); - - assert!(!check_deadlock()); - } - - #[test] - fn test_rwlock_deadlock_reentrant() { - let m1: Arc> = Default::default(); - - assert!(!check_deadlock()); - - let _t1 = thread::spawn(move || { - let _g = m1.read(); - let _ = m1.write(); - }); - - sleep(Duration::from_millis(50)); - assert!(check_deadlock()); - - assert!(!check_deadlock()); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/elision.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/elision.rs deleted file mode 100644 index 23895b1..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/elision.rs +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::sync::atomic::AtomicUsize; - -// Extension trait to add lock elision primitives to atomic types -pub trait AtomicElisionExt { - type IntType; - - // Perform a compare_exchange and start a transaction - fn elision_acquire( - &self, - current: Self::IntType, - new: Self::IntType, - ) -> Result; - // Perform a compare_exchange and end a transaction - fn elision_release( - &self, - current: Self::IntType, - new: Self::IntType, - ) -> Result; -} - -// Indicates whether the target architecture supports lock elision -#[inline] -pub fn have_elision() -> bool { - cfg!(all( - feature = "nightly", - any(target_arch = "x86", target_arch = "x86_64"), - )) -} - -// This implementation is never actually called because it is guarded by -// have_elision(). -#[cfg(not(all(feature = "nightly", any(target_arch = "x86", target_arch = "x86_64"))))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, _: usize, _: usize) -> Result { - unreachable!(); - } - - #[inline] - fn elision_release(&self, _: usize, _: usize) -> Result { - unreachable!(); - } -} - -#[cfg(all(feature = "nightly", target_arch = "x86"))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgl $2, $1" - : "={eax}" (prev), "+*m" (self) - : "r" (new), "{eax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgl $2, $1" - : "={eax}" (prev), "+*m" (self) - : "r" (new), "{eax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} - -#[cfg(all(feature = "nightly", target_arch = "x86_64", target_pointer_width = "32"))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgl $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgl $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} - -#[cfg(all(feature = "nightly", target_arch = "x86_64", target_pointer_width = "64"))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgq $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgq $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/mutex.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/mutex.rs deleted file mode 100644 index d530400..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/mutex.rs +++ /dev/null @@ -1,298 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use lock_api; -use raw_mutex::RawMutex; - -/// A mutual exclusion primitive useful for protecting shared data -/// -/// This mutex will block threads waiting for the lock to become available. The -/// mutex can also be statically initialized or created via a `new` -/// constructor. Each mutex has a type parameter which represents the data that -/// it is protecting. The data can only be accessed through the RAII guards -/// returned from `lock` and `try_lock`, which guarantees that the data is only -/// ever accessed when the mutex is locked. -/// -/// # Fairness -/// -/// A typical unfair lock can often end up in a situation where a single thread -/// quickly acquires and releases the same mutex in succession, which can starve -/// other threads waiting to acquire the mutex. While this improves performance -/// because it doesn't force a context switch when a thread tries to re-acquire -/// a mutex it has just released, this can starve other threads. -/// -/// This mutex uses [eventual fairness](https://trac.webkit.org/changeset/203350) -/// to ensure that the lock will be fair on average without sacrificing -/// performance. This is done by forcing a fair unlock on average every 0.5ms, -/// which will force the lock to go to the next thread waiting for the mutex. -/// -/// Additionally, any critical section longer than 1ms will always use a fair -/// unlock, which has a negligible performance impact compared to the length of -/// the critical section. -/// -/// You can also force a fair unlock by calling `MutexGuard::unlock_fair` when -/// unlocking a mutex instead of simply dropping the `MutexGuard`. -/// -/// # Differences from the standard library `Mutex` -/// -/// - No poisoning, the lock is released normally on panic. -/// - Only requires 1 byte of space, whereas the standard library boxes the -/// `Mutex` due to platform limitations. -/// - Can be statically constructed (requires the `const_fn` nightly feature). -/// - Does not require any drop glue when dropped. -/// - Inline fast path for the uncontended case. -/// - Efficient handling of micro-contention using adaptive spinning. -/// - Allows raw locking & unlocking without a guard. -/// - Supports eventual fairness so that the mutex is fair on average. -/// - Optionally allows making the mutex fair by calling `MutexGuard::unlock_fair`. -/// -/// # Examples -/// -/// ``` -/// use std::sync::Arc; -/// use parking_lot::Mutex; -/// use std::thread; -/// use std::sync::mpsc::channel; -/// -/// const N: usize = 10; -/// -/// // Spawn a few threads to increment a shared variable (non-atomically), and -/// // let the main thread know once all increments are done. -/// // -/// // Here we're using an Arc to share memory among threads, and the data inside -/// // the Arc is protected with a mutex. -/// let data = Arc::new(Mutex::new(0)); -/// -/// let (tx, rx) = channel(); -/// for _ in 0..10 { -/// let (data, tx) = (data.clone(), tx.clone()); -/// thread::spawn(move || { -/// // The shared state can only be accessed once the lock is held. -/// // Our non-atomic increment is safe because we're the only thread -/// // which can access the shared state when the lock is held. -/// let mut data = data.lock(); -/// *data += 1; -/// if *data == N { -/// tx.send(()).unwrap(); -/// } -/// // the lock is unlocked here when `data` goes out of scope. -/// }); -/// } -/// -/// rx.recv().unwrap(); -/// ``` -pub type Mutex = lock_api::Mutex; - -/// An RAII implementation of a "scoped lock" of a mutex. When this structure is -/// dropped (falls out of scope), the lock will be unlocked. -/// -/// The data protected by the mutex can be accessed through this guard via its -/// `Deref` and `DerefMut` implementations. -pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>; - -/// An RAII mutex guard returned by `MutexGuard::map`, which can point to a -/// subfield of the protected data. -/// -/// The main difference between `MappedMutexGuard` and `MutexGuard` is that the -/// former doesn't support temporarily unlocking and re-locking, since that -/// could introduce soundness issues if the locked object is modified by another -/// thread. -pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; - -#[cfg(test)] -mod tests { - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::mpsc::channel; - use std::sync::Arc; - use std::thread; - use {Condvar, Mutex}; - - struct Packet(Arc<(Mutex, Condvar)>); - - #[derive(Eq, PartialEq, Debug)] - struct NonCopy(i32); - - unsafe impl Send for Packet {} - unsafe impl Sync for Packet {} - - #[test] - fn smoke() { - let m = Mutex::new(()); - drop(m.lock()); - drop(m.lock()); - } - - #[test] - fn lots_and_lots() { - const J: u32 = 1000; - const K: u32 = 3; - - let m = Arc::new(Mutex::new(0)); - - fn inc(m: &Mutex) { - for _ in 0..J { - *m.lock() += 1; - } - } - - let (tx, rx) = channel(); - for _ in 0..K { - let tx2 = tx.clone(); - let m2 = m.clone(); - thread::spawn(move || { - inc(&m2); - tx2.send(()).unwrap(); - }); - let tx2 = tx.clone(); - let m2 = m.clone(); - thread::spawn(move || { - inc(&m2); - tx2.send(()).unwrap(); - }); - } - - drop(tx); - for _ in 0..2 * K { - rx.recv().unwrap(); - } - assert_eq!(*m.lock(), J * K * 2); - } - - #[test] - fn try_lock() { - let m = Mutex::new(()); - *m.try_lock().unwrap() = (); - } - - #[test] - fn test_into_inner() { - let m = Mutex::new(NonCopy(10)); - assert_eq!(m.into_inner(), NonCopy(10)); - } - - #[test] - fn test_into_inner_drop() { - struct Foo(Arc); - impl Drop for Foo { - fn drop(&mut self) { - self.0.fetch_add(1, Ordering::SeqCst); - } - } - let num_drops = Arc::new(AtomicUsize::new(0)); - let m = Mutex::new(Foo(num_drops.clone())); - assert_eq!(num_drops.load(Ordering::SeqCst), 0); - { - let _inner = m.into_inner(); - assert_eq!(num_drops.load(Ordering::SeqCst), 0); - } - assert_eq!(num_drops.load(Ordering::SeqCst), 1); - } - - #[test] - fn test_get_mut() { - let mut m = Mutex::new(NonCopy(10)); - *m.get_mut() = NonCopy(20); - assert_eq!(m.into_inner(), NonCopy(20)); - } - - #[test] - fn test_mutex_arc_condvar() { - let packet = Packet(Arc::new((Mutex::new(false), Condvar::new()))); - let packet2 = Packet(packet.0.clone()); - let (tx, rx) = channel(); - let _t = thread::spawn(move || { - // wait until parent gets in - rx.recv().unwrap(); - let &(ref lock, ref cvar) = &*packet2.0; - let mut lock = lock.lock(); - *lock = true; - cvar.notify_one(); - }); - - let &(ref lock, ref cvar) = &*packet.0; - let mut lock = lock.lock(); - tx.send(()).unwrap(); - assert!(!*lock); - while !*lock { - cvar.wait(&mut lock); - } - } - - #[test] - fn test_mutex_arc_nested() { - // Tests nested mutexes and access - // to underlying data. - let arc = Arc::new(Mutex::new(1)); - let arc2 = Arc::new(Mutex::new(arc)); - let (tx, rx) = channel(); - let _t = thread::spawn(move || { - let lock = arc2.lock(); - let lock2 = lock.lock(); - assert_eq!(*lock2, 1); - tx.send(()).unwrap(); - }); - rx.recv().unwrap(); - } - - #[test] - fn test_mutex_arc_access_in_unwind() { - let arc = Arc::new(Mutex::new(1)); - let arc2 = arc.clone(); - let _ = thread::spawn(move || -> () { - struct Unwinder { - i: Arc>, - } - impl Drop for Unwinder { - fn drop(&mut self) { - *self.i.lock() += 1; - } - } - let _u = Unwinder { i: arc2 }; - panic!(); - }).join(); - let lock = arc.lock(); - assert_eq!(*lock, 2); - } - - #[test] - fn test_mutex_unsized() { - let mutex: &Mutex<[i32]> = &Mutex::new([1, 2, 3]); - { - let b = &mut *mutex.lock(); - b[0] = 4; - b[2] = 5; - } - let comp: &[i32] = &[4, 2, 5]; - assert_eq!(&*mutex.lock(), comp); - } - - #[test] - fn test_mutexguard_sync() { - fn sync(_: T) {} - - let mutex = Mutex::new(()); - sync(mutex.lock()); - } - - #[test] - fn test_mutex_debug() { - let mutex = Mutex::new(vec![0u8, 10]); - - assert_eq!(format!("{:?}", mutex), "Mutex { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", mutex), - "Mutex { - data: [ - 0, - 10 - ] -}" - ); - let _lock = mutex.lock(); - assert_eq!(format!("{:?}", mutex), "Mutex { }"); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/once.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/once.rs deleted file mode 100644 index f3e70be..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/once.rs +++ /dev/null @@ -1,488 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::sync::atomic::{fence, Ordering}; -#[cfg(feature = "nightly")] -use std::sync::atomic::{ATOMIC_U8_INIT, AtomicU8}; -#[cfg(feature = "nightly")] -type U8 = u8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::AtomicUsize as AtomicU8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::ATOMIC_USIZE_INIT as ATOMIC_U8_INIT; -#[cfg(not(feature = "nightly"))] -type U8 = usize; -use parking_lot_core::{self, SpinWait, DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; -use std::fmt; -use std::mem; -use util::UncheckedOptionExt; - -const DONE_BIT: U8 = 1; -const POISON_BIT: U8 = 2; -const LOCKED_BIT: U8 = 4; -const PARKED_BIT: U8 = 8; - -/// Current state of a `Once`. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum OnceState { - /// A closure has not been executed yet - New, - - /// A closure was executed but panicked. - Poisoned, - - /// A thread is currently executing a closure. - InProgress, - - /// A closure has completed sucessfully. - Done, -} - -impl OnceState { - /// Returns whether the associated `Once` has been poisoned. - /// - /// Once an initalization routine for a `Once` has panicked it will forever - /// indicate to future forced initialization routines that it is poisoned. - #[inline] - pub fn poisoned(&self) -> bool { - match *self { - OnceState::Poisoned => true, - _ => false, - } - } - - /// Returns whether the associated `Once` has successfullly executed a - /// closure. - #[inline] - pub fn done(&self) -> bool { - match *self { - OnceState::Done => true, - _ => false, - } - } -} - -/// A synchronization primitive which can be used to run a one-time -/// initialization. Useful for one-time initialization for globals, FFI or -/// related functionality. -/// -/// # Differences from the standard library `Once` -/// -/// - Only requires 1 byte of space, instead of 1 word. -/// - Not required to be `'static`. -/// - Relaxed memory barriers in the fast path, which can significantly improve -/// performance on some architectures. -/// - Efficient handling of micro-contention using adaptive spinning. -/// -/// # Examples -/// -/// ``` -/// use parking_lot::{Once, ONCE_INIT}; -/// -/// static START: Once = ONCE_INIT; -/// -/// START.call_once(|| { -/// // run initialization here -/// }); -/// ``` -pub struct Once(AtomicU8); - -/// Initialization value for static `Once` values. -pub const ONCE_INIT: Once = Once(ATOMIC_U8_INIT); - -impl Once { - /// Creates a new `Once` value. - #[cfg(feature = "nightly")] - #[inline] - pub const fn new() -> Once { - Once(ATOMIC_U8_INIT) - } - - /// Creates a new `Once` value. - #[cfg(not(feature = "nightly"))] - #[inline] - pub fn new() -> Once { - Once(ATOMIC_U8_INIT) - } - - /// Returns the current state of this `Once`. - #[inline] - pub fn state(&self) -> OnceState { - let state = self.0.load(Ordering::Acquire); - if state & DONE_BIT != 0 { - OnceState::Done - } else if state & LOCKED_BIT != 0 { - OnceState::InProgress - } else if state & POISON_BIT != 0 { - OnceState::Poisoned - } else { - OnceState::New - } - } - - /// Performs an initialization routine once and only once. The given closure - /// will be executed if this is the first time `call_once` has been called, - /// and otherwise the routine will *not* be invoked. - /// - /// This method will block the calling thread if another initialization - /// routine is currently running. - /// - /// When this function returns, it is guaranteed that some initialization - /// has run and completed (it may not be the closure specified). It is also - /// guaranteed that any memory writes performed by the executed closure can - /// be reliably observed by other threads at this point (there is a - /// happens-before relation between the closure and code executing after the - /// return). - /// - /// # Examples - /// - /// ``` - /// use parking_lot::{Once, ONCE_INIT}; - /// - /// static mut VAL: usize = 0; - /// static INIT: Once = ONCE_INIT; - /// - /// // Accessing a `static mut` is unsafe much of the time, but if we do so - /// // in a synchronized fashion (e.g. write once or read all) then we're - /// // good to go! - /// // - /// // This function will only call `expensive_computation` once, and will - /// // otherwise always return the value returned from the first invocation. - /// fn get_cached_val() -> usize { - /// unsafe { - /// INIT.call_once(|| { - /// VAL = expensive_computation(); - /// }); - /// VAL - /// } - /// } - /// - /// fn expensive_computation() -> usize { - /// // ... - /// # 2 - /// } - /// ``` - /// - /// # Panics - /// - /// The closure `f` will only be executed once if this is called - /// concurrently amongst many threads. If that closure panics, however, then - /// it will *poison* this `Once` instance, causing all future invocations of - /// `call_once` to also panic. - #[inline] - pub fn call_once(&self, f: F) - where - F: FnOnce(), - { - if self.0.load(Ordering::Acquire) == DONE_BIT { - return; - } - - let mut f = Some(f); - self.call_once_slow(false, &mut |_| unsafe { f.take().unchecked_unwrap()() }); - } - - /// Performs the same function as `call_once` except ignores poisoning. - /// - /// If this `Once` has been poisoned (some initialization panicked) then - /// this function will continue to attempt to call initialization functions - /// until one of them doesn't panic. - /// - /// The closure `f` is yielded a structure which can be used to query the - /// state of this `Once` (whether initialization has previously panicked or - /// not). - #[inline] - pub fn call_once_force(&self, f: F) - where - F: FnOnce(OnceState), - { - if self.0.load(Ordering::Acquire) == DONE_BIT { - return; - } - - let mut f = Some(f); - self.call_once_slow(true, &mut |state| unsafe { - f.take().unchecked_unwrap()(state) - }); - } - - // This is a non-generic function to reduce the monomorphization cost of - // using `call_once` (this isn't exactly a trivial or small implementation). - // - // Additionally, this is tagged with `#[cold]` as it should indeed be cold - // and it helps let LLVM know that calls to this function should be off the - // fast path. Essentially, this should help generate more straight line code - // in LLVM. - // - // Finally, this takes an `FnMut` instead of a `FnOnce` because there's - // currently no way to take an `FnOnce` and call it via virtual dispatch - // without some allocation overhead. - #[cold] - #[inline(never)] - fn call_once_slow(&self, ignore_poison: bool, f: &mut FnMut(OnceState)) { - let mut spinwait = SpinWait::new(); - let mut state = self.0.load(Ordering::Relaxed); - loop { - // If another thread called the closure, we're done - if state & DONE_BIT != 0 { - // An acquire fence is needed here since we didn't load the - // state with Ordering::Acquire. - fence(Ordering::Acquire); - return; - } - - // If the state has been poisoned and we aren't forcing, then panic - if state & POISON_BIT != 0 && !ignore_poison { - // Need the fence here as well for the same reason - fence(Ordering::Acquire); - panic!("Once instance has previously been poisoned"); - } - - // Grab the lock if it isn't locked, even if there is a queue on it. - // We also clear the poison bit since we are going to try running - // the closure again. - if state & LOCKED_BIT == 0 { - match self.0.compare_exchange_weak( - state, - (state | LOCKED_BIT) & !POISON_BIT, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => break, - Err(x) => state = x, - } - continue; - } - - // If there is no queue, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.0.load(Ordering::Relaxed); - continue; - } - - // Set the parked bit - if state & PARKED_BIT == 0 { - if let Err(x) = self.0.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - state = x; - continue; - } - } - - // Park our thread until we are woken up by the thread that owns the - // lock. - unsafe { - let addr = self as *const _ as usize; - let validate = || self.0.load(Ordering::Relaxed) == LOCKED_BIT | PARKED_BIT; - let before_sleep = || {}; - let timed_out = |_, _| unreachable!(); - parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - DEFAULT_PARK_TOKEN, - None, - ); - } - - // Loop back and check if the done bit was set - spinwait.reset(); - state = self.0.load(Ordering::Relaxed); - } - - struct PanicGuard<'a>(&'a Once); - impl<'a> Drop for PanicGuard<'a> { - fn drop(&mut self) { - // Mark the state as poisoned, unlock it and unpark all threads. - let once = self.0; - let state = once.0.swap(POISON_BIT, Ordering::Release); - if state & PARKED_BIT != 0 { - unsafe { - let addr = once as *const _ as usize; - parking_lot_core::unpark_all(addr, DEFAULT_UNPARK_TOKEN); - } - } - } - } - - // At this point we have the lock, so run the closure. Make sure we - // properly clean up if the closure panicks. - let guard = PanicGuard(self); - let once_state = if state & POISON_BIT != 0 { - OnceState::Poisoned - } else { - OnceState::New - }; - f(once_state); - mem::forget(guard); - - // Now unlock the state, set the done bit and unpark all threads - let state = self.0.swap(DONE_BIT, Ordering::Release); - if state & PARKED_BIT != 0 { - unsafe { - let addr = self as *const _ as usize; - parking_lot_core::unpark_all(addr, DEFAULT_UNPARK_TOKEN); - } - } - } -} - -impl Default for Once { - #[inline] - fn default() -> Once { - Once::new() - } -} - -impl fmt::Debug for Once { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Once") - .field("state", &self.state()) - .finish() - } -} - -#[cfg(test)] -mod tests { - #[cfg(feature = "nightly")] - use std::panic; - use std::sync::mpsc::channel; - use std::thread; - use {Once, ONCE_INIT}; - - #[test] - fn smoke_once() { - static O: Once = ONCE_INIT; - let mut a = 0; - O.call_once(|| a += 1); - assert_eq!(a, 1); - O.call_once(|| a += 1); - assert_eq!(a, 1); - } - - #[test] - fn stampede_once() { - static O: Once = ONCE_INIT; - static mut RUN: bool = false; - - let (tx, rx) = channel(); - for _ in 0..10 { - let tx = tx.clone(); - thread::spawn(move || { - for _ in 0..4 { - thread::yield_now() - } - unsafe { - O.call_once(|| { - assert!(!RUN); - RUN = true; - }); - assert!(RUN); - } - tx.send(()).unwrap(); - }); - } - - unsafe { - O.call_once(|| { - assert!(!RUN); - RUN = true; - }); - assert!(RUN); - } - - for _ in 0..10 { - rx.recv().unwrap(); - } - } - - #[cfg(feature = "nightly")] - #[test] - fn poison_bad() { - static O: Once = ONCE_INIT; - - // poison the once - let t = panic::catch_unwind(|| { - O.call_once(|| panic!()); - }); - assert!(t.is_err()); - - // poisoning propagates - let t = panic::catch_unwind(|| { - O.call_once(|| {}); - }); - assert!(t.is_err()); - - // we can subvert poisoning, however - let mut called = false; - O.call_once_force(|p| { - called = true; - assert!(p.poisoned()) - }); - assert!(called); - - // once any success happens, we stop propagating the poison - O.call_once(|| {}); - } - - #[cfg(feature = "nightly")] - #[test] - fn wait_for_force_to_finish() { - static O: Once = ONCE_INIT; - - // poison the once - let t = panic::catch_unwind(|| { - O.call_once(|| panic!()); - }); - assert!(t.is_err()); - - // make sure someone's waiting inside the once via a force - let (tx1, rx1) = channel(); - let (tx2, rx2) = channel(); - let t1 = thread::spawn(move || { - O.call_once_force(|p| { - assert!(p.poisoned()); - tx1.send(()).unwrap(); - rx2.recv().unwrap(); - }); - }); - - rx1.recv().unwrap(); - - // put another waiter on the once - let t2 = thread::spawn(|| { - let mut called = false; - O.call_once(|| { - called = true; - }); - assert!(!called); - }); - - tx2.send(()).unwrap(); - - assert!(t1.join().is_ok()); - assert!(t2.join().is_ok()); - } - - #[test] - fn test_once_debug() { - static O: Once = ONCE_INIT; - - assert_eq!(format!("{:?}", O), "Once { state: New }"); - assert_eq!( - format!("{:#?}", O), - "Once { - state: New -}" - ); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_mutex.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_mutex.rs deleted file mode 100644 index 1ba5581..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_mutex.rs +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::sync::atomic::Ordering; -#[cfg(feature = "nightly")] -use std::sync::atomic::{ATOMIC_U8_INIT, AtomicU8}; -#[cfg(feature = "nightly")] -type U8 = u8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::AtomicUsize as AtomicU8; -#[cfg(not(feature = "nightly"))] -use std::sync::atomic::ATOMIC_USIZE_INIT as ATOMIC_U8_INIT; -#[cfg(not(feature = "nightly"))] -type U8 = usize; -use deadlock; -use lock_api::{GuardNoSend, RawMutex as RawMutexTrait, RawMutexFair, RawMutexTimed}; -use parking_lot_core::{self, ParkResult, SpinWait, UnparkResult, UnparkToken, DEFAULT_PARK_TOKEN}; -use std::time::{Duration, Instant}; - -// UnparkToken used to indicate that that the target thread should attempt to -// lock the mutex again as soon as it is unparked. -pub(crate) const TOKEN_NORMAL: UnparkToken = UnparkToken(0); - -// UnparkToken used to indicate that the mutex is being handed off to the target -// thread directly without unlocking it. -pub(crate) const TOKEN_HANDOFF: UnparkToken = UnparkToken(1); - -const LOCKED_BIT: U8 = 1; -const PARKED_BIT: U8 = 2; - -/// Raw mutex type backed by the parking lot. -pub struct RawMutex { - state: AtomicU8, -} - -unsafe impl RawMutexTrait for RawMutex { - const INIT: RawMutex = RawMutex { - state: ATOMIC_U8_INIT, - }; - - type GuardMarker = GuardNoSend; - - #[inline] - fn lock(&self) { - if self - .state - .compare_exchange_weak(0, LOCKED_BIT, Ordering::Acquire, Ordering::Relaxed) - .is_err() - { - self.lock_slow(None); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if state & LOCKED_BIT != 0 { - return false; - } - match self.state.compare_exchange_weak( - state, - state | LOCKED_BIT, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - return true; - } - Err(x) => state = x, - } - } - } - - #[inline] - fn unlock(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_slow(false); - } -} - -unsafe impl RawMutexFair for RawMutex { - #[inline] - fn unlock_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_slow(true); - } - - #[inline] - fn bump(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_slow(); - } - } -} - -unsafe impl RawMutexTimed for RawMutex { - type Duration = Duration; - type Instant = Instant; - - #[inline] - fn try_lock_until(&self, timeout: Instant) -> bool { - let result = if self - .state - .compare_exchange_weak(0, LOCKED_BIT, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_slow(Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_for(&self, timeout: Duration) -> bool { - let result = if self - .state - .compare_exchange_weak(0, LOCKED_BIT, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_slow(Some(Instant::now() + timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -impl RawMutex { - // Used by Condvar when requeuing threads to us, must be called while - // holding the queue lock. - #[inline] - pub(crate) fn mark_parked_if_locked(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if state & LOCKED_BIT == 0 { - return false; - } - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - } - - // Used by Condvar when requeuing threads to us, must be called while - // holding the queue lock. - #[inline] - pub(crate) fn mark_parked(&self) { - self.state.fetch_or(PARKED_BIT, Ordering::Relaxed); - } - - #[cold] - #[inline(never)] - fn lock_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there is a queue on it - if state & LOCKED_BIT == 0 { - match self.state.compare_exchange_weak( - state, - state | LOCKED_BIT, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - continue; - } - - // If there is no queue, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Set the parked bit - if state & PARKED_BIT == 0 { - if let Err(x) = self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - state = x; - continue; - } - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || self.state.load(Ordering::Relaxed) == LOCKED_BIT | PARKED_BIT; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - DEFAULT_PARK_TOKEN, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - state = self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - fn unlock_slow(&self, force_fair: bool) { - // Unlock directly if there are no parked threads - if self - .state - .compare_exchange(LOCKED_BIT, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - - // Unpark one thread and leave the parked bit set if there might - // still be parked threads on this address. - unsafe { - let addr = self as *const _ as usize; - let callback = |result: UnparkResult| { - // If we are using a fair unlock then we should keep the - // mutex locked and hand it off to the unparked thread. - if result.unparked_threads != 0 && (force_fair || result.be_fair) { - // Clear the parked bit if there are no more parked - // threads. - if !result.have_more_threads { - self.state.store(LOCKED_BIT, Ordering::Relaxed); - } - return TOKEN_HANDOFF; - } - - // Clear the locked bit, and the parked bit as well if there - // are no more parked threads. - if result.have_more_threads { - self.state.store(PARKED_BIT, Ordering::Release); - } else { - self.state.store(0, Ordering::Release); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_one(addr, callback); - } - } - - #[cold] - #[inline(never)] - fn bump_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_slow(true); - self.lock(); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_rwlock.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_rwlock.rs deleted file mode 100644 index f59a6ac..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/raw_rwlock.rs +++ /dev/null @@ -1,1402 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use deadlock; -use elision::{have_elision, AtomicElisionExt}; -use lock_api::{ - GuardNoSend, RawRwLock as RawRwLockTrait, RawRwLockDowngrade, RawRwLockFair, - RawRwLockRecursive, RawRwLockRecursiveTimed, RawRwLockTimed, RawRwLockUpgrade, - RawRwLockUpgradeDowngrade, RawRwLockUpgradeFair, RawRwLockUpgradeTimed, -}; -use parking_lot_core::{self, FilterOp, ParkResult, ParkToken, SpinWait, UnparkResult}; -use raw_mutex::{TOKEN_HANDOFF, TOKEN_NORMAL}; -use std::cell::Cell; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; -use std::time::{Duration, Instant}; - -const PARKED_BIT: usize = 0b001; -const UPGRADING_BIT: usize = 0b010; -// A shared guard acquires a single guard resource -const SHARED_GUARD: usize = 0b100; -const GUARD_COUNT_MASK: usize = !(SHARED_GUARD - 1); -// An exclusive lock acquires all of guard resource (i.e. it is exclusive) -const EXCLUSIVE_GUARD: usize = GUARD_COUNT_MASK; -// An upgradable lock acquires just over half of the guard resource -// This should be (GUARD_COUNT_MASK + SHARED_GUARD) >> 1, however this might -// overflow, so we shift before adding (which is okay since the least -// significant bit is zero for both GUARD_COUNT_MASK and SHARED_GUARD) -const UPGRADABLE_GUARD: usize = (GUARD_COUNT_MASK >> 1) + (SHARED_GUARD >> 1); - -// Token indicating what type of lock queued threads are trying to acquire -const TOKEN_SHARED: ParkToken = ParkToken(SHARED_GUARD); -const TOKEN_EXCLUSIVE: ParkToken = ParkToken(EXCLUSIVE_GUARD); -const TOKEN_UPGRADABLE: ParkToken = ParkToken(UPGRADABLE_GUARD); -const TOKEN_UPGRADING: ParkToken = ParkToken((EXCLUSIVE_GUARD - UPGRADABLE_GUARD) | UPGRADING_BIT); - -/// Raw reader-writer lock type backed by the parking lot. -pub struct RawRwLock { - state: AtomicUsize, -} - -unsafe impl RawRwLockTrait for RawRwLock { - const INIT: RawRwLock = RawRwLock { - state: ATOMIC_USIZE_INIT, - }; - - type GuardMarker = GuardNoSend; - - #[inline] - fn lock_exclusive(&self) { - if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_err() - { - let result = self.lock_exclusive_slow(None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_exclusive(&self) -> bool { - if self - .state - .compare_exchange(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - true - } else { - false - } - } - - #[inline] - fn unlock_exclusive(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_exclusive_slow(false); - } - - #[inline] - fn lock_shared(&self) { - if !self.try_lock_shared_fast(false) { - let result = self.lock_shared_slow(false, None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_shared(&self) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.try_lock_shared_slow(false) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn unlock_shared(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - let state = self.state.load(Ordering::Relaxed); - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - { - if have_elision() { - if self - .state - .elision_release(state, state - SHARED_GUARD) - .is_ok() - { - return; - } - } else { - if self - .state - .compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) - .is_ok() - { - return; - } - } - } - self.unlock_shared_slow(false); - } -} - -unsafe impl RawRwLockFair for RawRwLock { - #[inline] - fn unlock_shared_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - let state = self.state.load(Ordering::Relaxed); - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - { - if have_elision() { - if self - .state - .elision_release(state, state - SHARED_GUARD) - .is_ok() - { - return; - } - } else { - if self - .state - .compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) - .is_ok() - { - return; - } - } - } - self.unlock_shared_slow(true); - } - - #[inline] - fn unlock_exclusive_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_exclusive_slow(true); - } - - #[inline] - fn bump_shared(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_shared_slow(); - } - } - - #[inline] - fn bump_exclusive(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_exclusive_slow(); - } - } -} - -unsafe impl RawRwLockDowngrade for RawRwLock { - #[inline] - fn downgrade(&self) { - let state = self - .state - .fetch_sub(EXCLUSIVE_GUARD - SHARED_GUARD, Ordering::Release); - - // Wake up parked shared and upgradable threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_slow(); - } - } -} - -unsafe impl RawRwLockTimed for RawRwLock { - type Duration = Duration; - type Instant = Instant; - - #[inline] - fn try_lock_shared_for(&self, timeout: Self::Duration) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.lock_shared_slow(false, Some(Instant::now() + timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_shared_until(&self, timeout: Self::Instant) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.lock_shared_slow(false, Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_exclusive_for(&self, timeout: Duration) -> bool { - let result = if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_exclusive_slow(Some(Instant::now() + timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_exclusive_until(&self, timeout: Instant) -> bool { - let result = if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_exclusive_slow(Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockRecursive for RawRwLock { - #[inline] - fn lock_shared_recursive(&self) { - if !self.try_lock_shared_fast(true) { - let result = self.lock_shared_slow(true, None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_shared_recursive(&self) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.try_lock_shared_slow(true) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockRecursiveTimed for RawRwLock { - #[inline] - fn try_lock_shared_recursive_for(&self, timeout: Self::Duration) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.lock_shared_slow(true, Some(Instant::now() + timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_shared_recursive_until(&self, timeout: Self::Instant) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.lock_shared_slow(true, Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockUpgrade for RawRwLock { - #[inline] - fn lock_upgradable(&self) { - if !self.try_lock_upgradable_fast() { - let result = self.lock_upgradable_slow(None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_upgradable(&self) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.try_lock_upgradable_slow() - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn unlock_upgradable(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(UPGRADABLE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_upgradable_slow(false); - } - - #[inline] - fn upgrade(&self) { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_err() - { - let result = self.upgrade_slow(None); - debug_assert!(result); - } - } - - fn try_upgrade(&self) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.try_upgrade_slow() - } - } -} - -unsafe impl RawRwLockUpgradeFair for RawRwLock { - #[inline] - fn unlock_upgradable_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(UPGRADABLE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_upgradable_slow(true); - } - - #[inline] - fn bump_upgradable(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_upgradable_slow(); - } - } -} - -unsafe impl RawRwLockUpgradeDowngrade for RawRwLock { - #[inline] - fn downgrade_upgradable(&self) { - let state = self - .state - .fetch_sub(UPGRADABLE_GUARD - SHARED_GUARD, Ordering::Relaxed); - - // Wake up parked shared and upgradable threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_upgradable_slow(state); - } - } - - #[inline] - fn downgrade_to_upgradable(&self) { - let state = self - .state - .fetch_sub(EXCLUSIVE_GUARD - UPGRADABLE_GUARD, Ordering::Release); - - // Wake up parked shared threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_to_upgradable_slow(); - } - } -} - -unsafe impl RawRwLockUpgradeTimed for RawRwLock { - #[inline] - fn try_lock_upgradable_until(&self, timeout: Instant) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.lock_upgradable_slow(Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_upgradable_for(&self, timeout: Duration) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.lock_upgradable_slow(Some(Instant::now() + timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_upgrade_until(&self, timeout: Instant) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.upgrade_slow(Some(timeout)) - } - } - - #[inline] - fn try_upgrade_for(&self, timeout: Duration) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.upgrade_slow(Some(Instant::now() + timeout)) - } - } -} - -impl RawRwLock { - #[inline(always)] - fn try_lock_shared_fast(&self, recursive: bool) -> bool { - let state = self.state.load(Ordering::Relaxed); - - // We can't allow grabbing a shared lock while there are parked threads - // since that could lead to writer starvation. - if !recursive && state & PARKED_BIT != 0 { - return false; - } - - // Use hardware lock elision to avoid cache conflicts when multiple - // readers try to acquire the lock. We only do this if the lock is - // completely empty since elision handles conflicts poorly. - if have_elision() && state == 0 { - self.state.elision_acquire(0, SHARED_GUARD).is_ok() - } else if let Some(new_state) = state.checked_add(SHARED_GUARD) { - self.state - .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - } else { - false - } - } - - #[inline(always)] - fn try_lock_upgradable_fast(&self) -> bool { - let state = self.state.load(Ordering::Relaxed); - - // We can't allow grabbing an upgradable lock while there are parked threads - // since that could lead to writer starvation. - if state & PARKED_BIT != 0 { - return false; - } - - if let Some(new_state) = state.checked_add(UPGRADABLE_GUARD) { - self.state - .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - } else { - false - } - } - - #[cold] - #[inline(never)] - fn lock_exclusive_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there are other - // threads parked. - if let Some(new_state) = state.checked_add(EXCLUSIVE_GUARD) { - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - continue; - } - - // If there are no parked threads and only one reader or writer, try - // spinning a few times. - if (state == EXCLUSIVE_GUARD || state == SHARED_GUARD || state == UPGRADABLE_GUARD) - && spinwait.spin() - { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // If the rwlock is free, abort the park and try to grab - // it immediately. - if state & GUARD_COUNT_MASK == 0 { - return false; - } - - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_EXCLUSIVE, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - state = self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - fn unlock_exclusive_slow(&self, force_fair: bool) { - // Unlock directly if there are no parked threads - if self - .state - .compare_exchange(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - }; - - // There are threads to unpark. We unpark threads up to the guard capacity. - let guard_count = Cell::new(0usize); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.get().checked_add(token) { - Some(new_guard_count) => { - guard_count.set(new_guard_count); - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // If we are using a fair unlock then we should keep the - // rwlock locked and hand it off to the unparked threads. - if result.unparked_threads != 0 && (force_fair || result.be_fair) { - // We need to set the guard count accordingly. - let mut new_state = guard_count.get(); - - if result.have_more_threads { - new_state |= PARKED_BIT; - } - - self.state.store(new_state, Ordering::Release); - TOKEN_HANDOFF - } else { - // Clear the parked bit if there are no more parked threads. - if result.have_more_threads { - self.state.store(PARKED_BIT, Ordering::Release); - } else { - self.state.store(0, Ordering::Release); - } - TOKEN_NORMAL - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_slow(&self) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = SHARED_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(new_guard_count) => { - guard_count = new_guard_count; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_to_upgradable_slow(&self) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = UPGRADABLE_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(new_guard_count) => { - guard_count = new_guard_count; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn lock_shared_slow(&self, recursive: bool, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut spinwait_shared = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - let mut unparked = false; - loop { - // Use hardware lock elision to avoid cache conflicts when multiple - // readers try to acquire the lock. We only do this if the lock is - // completely empty since elision handles conflicts poorly. - if have_elision() && state == 0 { - match self.state.elision_acquire(0, SHARED_GUARD) { - Ok(_) => return true, - Err(x) => state = x, - } - } - - // Grab the lock if there are no exclusive threads locked or - // waiting. However if we were unparked then we are allowed to grab - // the lock even if there are pending exclusive threads. - if unparked || recursive || state & PARKED_BIT == 0 { - if let Some(new_state) = state.checked_add(SHARED_GUARD) { - if self - .state - .compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_ok() - { - return true; - } - - // If there is high contention on the reader count then we want - // to leave some time between attempts to acquire the lock to - // let other threads make progress. - spinwait_shared.spin_no_yield(); - state = self.state.load(Ordering::Relaxed); - continue; - } else { - // We were unparked spuriously, reset unparked flag. - unparked = false; - } - } - - // If there are no parked threads, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // If the parked bit is not set then it means we are at - // the front of the queue. If there is space for another - // lock then we should abort the park and try acquiring - // the lock again. - if state & GUARD_COUNT_MASK != GUARD_COUNT_MASK { - return false; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_SHARED, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - spinwait_shared.reset(); - state = self.state.load(Ordering::Relaxed); - unparked = true; - } - } - - #[cold] - #[inline(never)] - fn try_lock_shared_slow(&self, recursive: bool) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if !recursive && state & PARKED_BIT != 0 { - return false; - } - if have_elision() && state == 0 { - match self.state.elision_acquire(0, SHARED_GUARD) { - Ok(_) => return true, - Err(x) => state = x, - } - } else { - match state.checked_add(SHARED_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - } - - #[cold] - #[inline(never)] - fn unlock_shared_slow(&self, force_fair: bool) { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Just release the lock if there are no parked thread or if we are - // not the last shared thread. - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - || (state & UPGRADING_BIT != 0 - && state & GUARD_COUNT_MASK != UPGRADABLE_GUARD + SHARED_GUARD) - { - match self.state.compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - continue; - } - - break; - } - - // There are threads to unpark. If there is a thread waiting to be - // upgraded, we find that thread and let it upgrade, otherwise we - // unpark threads up to the guard capacity. Note that there is a - // potential race condition here: another thread might grab a shared - // lock between now and when we actually release our lock. - let additional_guards = Cell::new(0usize); - let has_upgraded = Cell::new(if state & UPGRADING_BIT == 0 { - None - } else { - Some(false) - }); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - match has_upgraded.get() { - None => match additional_guards.get().checked_add(token) { - Some(x) => { - additional_guards.set(x); - FilterOp::Unpark - } - None => FilterOp::Stop, - }, - Some(false) => if token & UPGRADING_BIT != 0 { - additional_guards.set(token & !UPGRADING_BIT); - has_upgraded.set(Some(true)); - FilterOp::Unpark - } else { - FilterOp::Skip - }, - Some(true) => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Release our shared lock - let mut new_state = state - SHARED_GUARD; - - // Clear the parked bit if there are no more threads in - // the queue. - if !result.have_more_threads { - new_state &= !PARKED_BIT; - } - - // Clear the upgrading bit if we are upgrading a thread. - if let Some(true) = has_upgraded.get() { - new_state &= !UPGRADING_BIT; - } - - // Consider using fair unlocking. If we are, then we should set - // the state to the new value and tell the threads that we are - // handing the lock directly. - let token = if result.unparked_threads != 0 && (force_fair || result.be_fair) { - match new_state.checked_add(additional_guards.get()) { - Some(x) => { - new_state = x; - TOKEN_HANDOFF - } - None => TOKEN_NORMAL, - } - } else { - TOKEN_NORMAL - }; - - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return token, - Err(x) => state = x, - } - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn lock_upgradable_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut spinwait_shared = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - let mut unparked = false; - loop { - // Grab the lock if there are no exclusive or upgradable threads - // locked or waiting. However if we were unparked then we are - // allowed to grab the lock even if there are pending exclusive threads. - if unparked || state & PARKED_BIT == 0 { - if let Some(new_state) = state.checked_add(UPGRADABLE_GUARD) { - if self - .state - .compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_ok() - { - return true; - } - - // If there is high contention on the reader count then we want - // to leave some time between attempts to acquire the lock to - // let other threads make progress. - spinwait_shared.spin_no_yield(); - state = self.state.load(Ordering::Relaxed); - continue; - } else { - // We were unparked spuriously, reset unparked flag. - unparked = false; - } - } - - // If there are no parked threads, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // If the parked bit is not set then it means we are at - // the front of the queue. If there is space for an - // upgradable lock then we should abort the park and try - // acquiring the lock again. - if state & UPGRADABLE_GUARD != UPGRADABLE_GUARD { - return false; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_UPGRADABLE, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - spinwait_shared.reset(); - state = self.state.load(Ordering::Relaxed); - unparked = true; - } - } - - #[cold] - #[inline(never)] - fn try_lock_upgradable_slow(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if state & PARKED_BIT != 0 { - return false; - } - - match state.checked_add(UPGRADABLE_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - - #[cold] - #[inline(never)] - fn unlock_upgradable_slow(&self, force_fair: bool) { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Just release the lock if there are no parked threads. - if state & PARKED_BIT == 0 { - match self.state.compare_exchange_weak( - state, - state - UPGRADABLE_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - continue; - } - - break; - } - - // There are threads to unpark. We unpark threads up to the guard capacity. - let additional_guards = Cell::new(0usize); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - match additional_guards.get().checked_add(token) { - Some(x) => { - additional_guards.set(x); - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Release our upgradable lock - let mut new_state = state - UPGRADABLE_GUARD; - - // Clear the parked bit if there are no more threads in - // the queue - if !result.have_more_threads { - new_state &= !PARKED_BIT; - } - - // Consider using fair unlocking. If we are, then we should set - // the state to the new value and tell the threads that we are - // handing the lock directly. - let token = if result.unparked_threads != 0 && (force_fair || result.be_fair) { - match new_state.checked_add(additional_guards.get()) { - Some(x) => { - new_state = x; - TOKEN_HANDOFF - } - None => TOKEN_NORMAL, - } - } else { - TOKEN_NORMAL - }; - - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return token, - Err(x) => state = x, - } - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_upgradable_slow(&self, state: usize) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = (state & GUARD_COUNT_MASK) - UPGRADABLE_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(x) => { - guard_count = x; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn try_upgrade_slow(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - match state.checked_add(EXCLUSIVE_GUARD - SHARED_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - - #[cold] - #[inline(never)] - fn upgrade_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there are other - // threads parked. - if let Some(new_state) = state.checked_add(EXCLUSIVE_GUARD - UPGRADABLE_GUARD) { - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - continue; - } - - // If there are no parked threads and only one other reader, try - // spinning a few times. - if state == UPGRADABLE_GUARD | SHARED_GUARD && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // If the rwlock is free, abort the park and try to grab - // it immediately. - if state & GUARD_COUNT_MASK == UPGRADABLE_GUARD { - return false; - } - - // Set the upgrading and parked bits - match self.state.compare_exchange_weak( - state, - state | (UPGRADING_BIT | PARKED_BIT), - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the upgrading bit - let mut flags = UPGRADING_BIT; - - // Clear the parked bit if we were the last parked thread - if was_last_thread { - flags |= PARKED_BIT; - } - - self.state.fetch_and(!flags, Ordering::Relaxed); - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_UPGRADING, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - state = self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - fn bump_shared_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_shared_slow(true); - self.lock_shared(); - } - - #[cold] - #[inline(never)] - fn bump_exclusive_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_exclusive_slow(true); - self.lock_exclusive(); - } - - #[cold] - #[inline(never)] - fn bump_upgradable_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_upgradable_slow(true); - self.lock_upgradable(); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/remutex.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/remutex.rs deleted file mode 100644 index ba9e004..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/remutex.rs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use lock_api::{self, GetThreadId}; -use raw_mutex::RawMutex; - -/// Implementation of the `GetThreadId` trait for `lock_api::ReentrantMutex`. -pub struct RawThreadId; - -unsafe impl GetThreadId for RawThreadId { - const INIT: RawThreadId = RawThreadId; - - fn nonzero_thread_id(&self) -> usize { - // The address of a thread-local variable is guaranteed to be unique to the - // current thread, and is also guaranteed to be non-zero. - thread_local!(static KEY: u8 = unsafe { ::std::mem::uninitialized() }); - KEY.with(|x| x as *const _ as usize) - } -} - -/// A mutex which can be recursively locked by a single thread. -/// -/// This type is identical to `Mutex` except for the following points: -/// -/// - Locking multiple times from the same thread will work correctly instead of -/// deadlocking. -/// - `ReentrantMutexGuard` does not give mutable references to the locked data. -/// Use a `RefCell` if you need this. -/// -/// See [`Mutex`](struct.Mutex.html) for more details about the underlying mutex -/// primitive. -pub type ReentrantMutex = lock_api::ReentrantMutex; - -/// An RAII implementation of a "scoped lock" of a reentrant mutex. When this structure -/// is dropped (falls out of scope), the lock will be unlocked. -/// -/// The data protected by the mutex can be accessed through this guard via its -/// `Deref` implementation. -pub type ReentrantMutexGuard<'a, T> = - lock_api::ReentrantMutexGuard<'a, RawMutex, RawThreadId, T>; - -/// An RAII mutex guard returned by `ReentrantMutexGuard::map`, which can point to a -/// subfield of the protected data. -/// -/// The main difference between `MappedReentrantMutexGuard` and `ReentrantMutexGuard` is that the -/// former doesn't support temporarily unlocking and re-locking, since that -/// could introduce soundness issues if the locked object is modified by another -/// thread. -pub type MappedReentrantMutexGuard<'a, T> = - lock_api::MappedReentrantMutexGuard<'a, RawMutex, RawThreadId, T>; - -#[cfg(test)] -mod tests { - use std::cell::RefCell; - use std::sync::Arc; - use std::thread; - use ReentrantMutex; - - #[test] - fn smoke() { - let m = ReentrantMutex::new(()); - { - let a = m.lock(); - { - let b = m.lock(); - { - let c = m.lock(); - assert_eq!(*c, ()); - } - assert_eq!(*b, ()); - } - assert_eq!(*a, ()); - } - } - - #[test] - fn is_mutex() { - let m = Arc::new(ReentrantMutex::new(RefCell::new(0))); - let m2 = m.clone(); - let lock = m.lock(); - let child = thread::spawn(move || { - let lock = m2.lock(); - assert_eq!(*lock.borrow(), 4950); - }); - for i in 0..100 { - let lock = m.lock(); - *lock.borrow_mut() += i; - } - drop(lock); - child.join().unwrap(); - } - - #[test] - fn trylock_works() { - let m = Arc::new(ReentrantMutex::new(())); - let m2 = m.clone(); - let _lock = m.try_lock(); - let _lock2 = m.try_lock(); - thread::spawn(move || { - let lock = m2.try_lock(); - assert!(lock.is_none()); - }).join() - .unwrap(); - let _lock3 = m.try_lock(); - } - - #[test] - fn test_reentrant_mutex_debug() { - let mutex = ReentrantMutex::new(vec![0u8, 10]); - - assert_eq!(format!("{:?}", mutex), "ReentrantMutex { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", mutex), - "ReentrantMutex { - data: [ - 0, - 10 - ] -}" - ); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/rwlock.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/rwlock.rs deleted file mode 100644 index 5a1d0cb..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/rwlock.rs +++ /dev/null @@ -1,564 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use lock_api; -use raw_rwlock::RawRwLock; - -/// A reader-writer lock -/// -/// This type of lock allows a number of readers or at most one writer at any -/// point in time. The write portion of this lock typically allows modification -/// of the underlying data (exclusive access) and the read portion of this lock -/// typically allows for read-only access (shared access). -/// -/// This lock uses a task-fair locking policy which avoids both reader and -/// writer starvation. This means that readers trying to acquire the lock will -/// block even if the lock is unlocked when there are writers waiting to acquire -/// the lock. Because of this, attempts to recursively acquire a read lock -/// within a single thread may result in a deadlock. -/// -/// The type parameter `T` represents the data that this lock protects. It is -/// required that `T` satisfies `Send` to be shared across threads and `Sync` to -/// allow concurrent access through readers. The RAII guards returned from the -/// locking methods implement `Deref` (and `DerefMut` for the `write` methods) -/// to allow access to the contained of the lock. -/// -/// # Fairness -/// -/// A typical unfair lock can often end up in a situation where a single thread -/// quickly acquires and releases the same lock in succession, which can starve -/// other threads waiting to acquire the rwlock. While this improves performance -/// because it doesn't force a context switch when a thread tries to re-acquire -/// a rwlock it has just released, this can starve other threads. -/// -/// This rwlock uses [eventual fairness](https://trac.webkit.org/changeset/203350) -/// to ensure that the lock will be fair on average without sacrificing -/// performance. This is done by forcing a fair unlock on average every 0.5ms, -/// which will force the lock to go to the next thread waiting for the rwlock. -/// -/// Additionally, any critical section longer than 1ms will always use a fair -/// unlock, which has a negligible performance impact compared to the length of -/// the critical section. -/// -/// You can also force a fair unlock by calling `RwLockReadGuard::unlock_fair` -/// or `RwLockWriteGuard::unlock_fair` when unlocking a mutex instead of simply -/// dropping the guard. -/// -/// # Differences from the standard library `RwLock` -/// -/// - Supports atomically downgrading a write lock into a read lock. -/// - Task-fair locking policy instead of an unspecified platform default. -/// - No poisoning, the lock is released normally on panic. -/// - Only requires 1 word of space, whereas the standard library boxes the -/// `RwLock` due to platform limitations. -/// - Can be statically constructed (requires the `const_fn` nightly feature). -/// - Does not require any drop glue when dropped. -/// - Inline fast path for the uncontended case. -/// - Efficient handling of micro-contention using adaptive spinning. -/// - Allows raw locking & unlocking without a guard. -/// - Supports eventual fairness so that the rwlock is fair on average. -/// - Optionally allows making the rwlock fair by calling -/// `RwLockReadGuard::unlock_fair` and `RwLockWriteGuard::unlock_fair`. -/// -/// # Examples -/// -/// ``` -/// use parking_lot::RwLock; -/// -/// let lock = RwLock::new(5); -/// -/// // many reader locks can be held at once -/// { -/// let r1 = lock.read(); -/// let r2 = lock.read(); -/// assert_eq!(*r1, 5); -/// assert_eq!(*r2, 5); -/// } // read locks are dropped at this point -/// -/// // only one write lock may be held, however -/// { -/// let mut w = lock.write(); -/// *w += 1; -/// assert_eq!(*w, 6); -/// } // write lock is dropped here -/// ``` -pub type RwLock = lock_api::RwLock; - -/// RAII structure used to release the shared read access of a lock when -/// dropped. -pub type RwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, RawRwLock, T>; - -/// RAII structure used to release the exclusive write access of a lock when -/// dropped. -pub type RwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, RawRwLock, T>; - -/// An RAII read lock guard returned by `RwLockReadGuard::map`, which can point to a -/// subfield of the protected data. -/// -/// The main difference between `MappedRwLockReadGuard` and `RwLockReadGuard` is that the -/// former doesn't support temporarily unlocking and re-locking, since that -/// could introduce soundness issues if the locked object is modified by another -/// thread. -pub type MappedRwLockReadGuard<'a, T> = lock_api::MappedRwLockReadGuard<'a, RawRwLock, T>; - -/// An RAII write lock guard returned by `RwLockWriteGuard::map`, which can point to a -/// subfield of the protected data. -/// -/// The main difference between `MappedRwLockWriteGuard` and `RwLockWriteGuard` is that the -/// former doesn't support temporarily unlocking and re-locking, since that -/// could introduce soundness issues if the locked object is modified by another -/// thread. -pub type MappedRwLockWriteGuard<'a, T> = lock_api::MappedRwLockWriteGuard<'a, RawRwLock, T>; - -/// RAII structure used to release the upgradable read access of a lock when -/// dropped. -pub type RwLockUpgradableReadGuard<'a, T> = - lock_api::RwLockUpgradableReadGuard<'a, RawRwLock, T>; - -#[cfg(test)] -mod tests { - extern crate rand; - use self::rand::Rng; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::mpsc::channel; - use std::sync::Arc; - use std::thread; - use std::time::Duration; - use {RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard}; - - #[derive(Eq, PartialEq, Debug)] - struct NonCopy(i32); - - #[test] - fn smoke() { - let l = RwLock::new(()); - drop(l.read()); - drop(l.write()); - drop(l.upgradable_read()); - drop((l.read(), l.read())); - drop((l.read(), l.upgradable_read())); - drop(l.write()); - } - - #[test] - fn frob() { - const N: u32 = 10; - const M: u32 = 1000; - - let r = Arc::new(RwLock::new(())); - - let (tx, rx) = channel::<()>(); - for _ in 0..N { - let tx = tx.clone(); - let r = r.clone(); - thread::spawn(move || { - let mut rng = rand::thread_rng(); - for _ in 0..M { - if rng.gen_bool(1.0 / N as f64) { - drop(r.write()); - } else { - drop(r.read()); - } - } - drop(tx); - }); - } - drop(tx); - let _ = rx.recv(); - } - - #[test] - fn test_rw_arc_no_poison_wr() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _: Result<(), _> = thread::spawn(move || { - let _lock = arc2.write(); - panic!(); - }).join(); - let lock = arc.read(); - assert_eq!(*lock, 1); - } - - #[test] - fn test_rw_arc_no_poison_ww() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _: Result<(), _> = thread::spawn(move || { - let _lock = arc2.write(); - panic!(); - }).join(); - let lock = arc.write(); - assert_eq!(*lock, 1); - } - - #[test] - fn test_rw_arc_no_poison_rr() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _: Result<(), _> = thread::spawn(move || { - let _lock = arc2.read(); - panic!(); - }).join(); - let lock = arc.read(); - assert_eq!(*lock, 1); - } - - #[test] - fn test_rw_arc_no_poison_rw() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _: Result<(), _> = thread::spawn(move || { - let _lock = arc2.read(); - panic!() - }).join(); - let lock = arc.write(); - assert_eq!(*lock, 1); - } - - #[test] - fn test_ruw_arc() { - let arc = Arc::new(RwLock::new(0)); - let arc2 = arc.clone(); - let (tx, rx) = channel(); - - thread::spawn(move || { - for _ in 0..10 { - let mut lock = arc2.write(); - let tmp = *lock; - *lock = -1; - thread::yield_now(); - *lock = tmp + 1; - } - tx.send(()).unwrap(); - }); - - let mut children = Vec::new(); - - // Upgradable readers try to catch the writer in the act and also - // try to touch the value - for _ in 0..5 { - let arc3 = arc.clone(); - children.push(thread::spawn(move || { - let lock = arc3.upgradable_read(); - let tmp = *lock; - assert!(tmp >= 0); - thread::yield_now(); - let mut lock = RwLockUpgradableReadGuard::upgrade(lock); - assert_eq!(tmp, *lock); - *lock = -1; - thread::yield_now(); - *lock = tmp + 1; - })); - } - - // Readers try to catch the writers in the act - for _ in 0..5 { - let arc4 = arc.clone(); - children.push(thread::spawn(move || { - let lock = arc4.read(); - assert!(*lock >= 0); - })); - } - - // Wait for children to pass their asserts - for r in children { - assert!(r.join().is_ok()); - } - - // Wait for writer to finish - rx.recv().unwrap(); - let lock = arc.read(); - assert_eq!(*lock, 15); - } - - #[test] - fn test_rw_arc() { - let arc = Arc::new(RwLock::new(0)); - let arc2 = arc.clone(); - let (tx, rx) = channel(); - - thread::spawn(move || { - let mut lock = arc2.write(); - for _ in 0..10 { - let tmp = *lock; - *lock = -1; - thread::yield_now(); - *lock = tmp + 1; - } - tx.send(()).unwrap(); - }); - - // Readers try to catch the writer in the act - let mut children = Vec::new(); - for _ in 0..5 { - let arc3 = arc.clone(); - children.push(thread::spawn(move || { - let lock = arc3.read(); - assert!(*lock >= 0); - })); - } - - // Wait for children to pass their asserts - for r in children { - assert!(r.join().is_ok()); - } - - // Wait for writer to finish - rx.recv().unwrap(); - let lock = arc.read(); - assert_eq!(*lock, 10); - } - - #[test] - fn test_rw_arc_access_in_unwind() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _ = thread::spawn(move || -> () { - struct Unwinder { - i: Arc>, - } - impl Drop for Unwinder { - fn drop(&mut self) { - let mut lock = self.i.write(); - *lock += 1; - } - } - let _u = Unwinder { i: arc2 }; - panic!(); - }).join(); - let lock = arc.read(); - assert_eq!(*lock, 2); - } - - #[test] - fn test_rwlock_unsized() { - let rw: &RwLock<[i32]> = &RwLock::new([1, 2, 3]); - { - let b = &mut *rw.write(); - b[0] = 4; - b[2] = 5; - } - let comp: &[i32] = &[4, 2, 5]; - assert_eq!(&*rw.read(), comp); - } - - #[test] - fn test_rwlock_try_read() { - let lock = RwLock::new(0isize); - { - let read_guard = lock.read(); - - let read_result = lock.try_read(); - assert!( - read_result.is_some(), - "try_read should succeed while read_guard is in scope" - ); - - drop(read_guard); - } - { - let upgrade_guard = lock.upgradable_read(); - - let read_result = lock.try_read(); - assert!( - read_result.is_some(), - "try_read should succeed while upgrade_guard is in scope" - ); - - drop(upgrade_guard); - } - { - let write_guard = lock.write(); - - let read_result = lock.try_read(); - assert!( - read_result.is_none(), - "try_read should fail while write_guard is in scope" - ); - - drop(write_guard); - } - } - - #[test] - fn test_rwlock_try_write() { - let lock = RwLock::new(0isize); - { - let read_guard = lock.read(); - - let write_result = lock.try_write(); - assert!( - write_result.is_none(), - "try_write should fail while read_guard is in scope" - ); - - drop(read_guard); - } - { - let upgrade_guard = lock.upgradable_read(); - - let write_result = lock.try_write(); - assert!( - write_result.is_none(), - "try_write should fail while upgrade_guard is in scope" - ); - - drop(upgrade_guard); - } - { - let write_guard = lock.write(); - - let write_result = lock.try_write(); - assert!( - write_result.is_none(), - "try_write should fail while write_guard is in scope" - ); - - drop(write_guard); - } - } - - #[test] - fn test_rwlock_try_upgrade() { - let lock = RwLock::new(0isize); - { - let read_guard = lock.read(); - - let upgrade_result = lock.try_upgradable_read(); - assert!( - upgrade_result.is_some(), - "try_upgradable_read should succeed while read_guard is in scope" - ); - - drop(read_guard); - } - { - let upgrade_guard = lock.upgradable_read(); - - let upgrade_result = lock.try_upgradable_read(); - assert!( - upgrade_result.is_none(), - "try_upgradable_read should fail while upgrade_guard is in scope" - ); - - drop(upgrade_guard); - } - { - let write_guard = lock.write(); - - let upgrade_result = lock.try_upgradable_read(); - assert!( - upgrade_result.is_none(), - "try_upgradable should fail while write_guard is in scope" - ); - - drop(write_guard); - } - } - - #[test] - fn test_into_inner() { - let m = RwLock::new(NonCopy(10)); - assert_eq!(m.into_inner(), NonCopy(10)); - } - - #[test] - fn test_into_inner_drop() { - struct Foo(Arc); - impl Drop for Foo { - fn drop(&mut self) { - self.0.fetch_add(1, Ordering::SeqCst); - } - } - let num_drops = Arc::new(AtomicUsize::new(0)); - let m = RwLock::new(Foo(num_drops.clone())); - assert_eq!(num_drops.load(Ordering::SeqCst), 0); - { - let _inner = m.into_inner(); - assert_eq!(num_drops.load(Ordering::SeqCst), 0); - } - assert_eq!(num_drops.load(Ordering::SeqCst), 1); - } - - #[test] - fn test_get_mut() { - let mut m = RwLock::new(NonCopy(10)); - *m.get_mut() = NonCopy(20); - assert_eq!(m.into_inner(), NonCopy(20)); - } - - #[test] - fn test_rwlockguard_sync() { - fn sync(_: T) {} - - let rwlock = RwLock::new(()); - sync(rwlock.read()); - sync(rwlock.write()); - } - - #[test] - fn test_rwlock_downgrade() { - let x = Arc::new(RwLock::new(0)); - let mut handles = Vec::new(); - for _ in 0..8 { - let x = x.clone(); - handles.push(thread::spawn(move || { - for _ in 0..100 { - let mut writer = x.write(); - *writer += 1; - let cur_val = *writer; - let reader = RwLockWriteGuard::downgrade(writer); - assert_eq!(cur_val, *reader); - } - })); - } - for handle in handles { - handle.join().unwrap() - } - assert_eq!(*x.read(), 800); - } - - #[test] - fn test_rwlock_recursive() { - let arc = Arc::new(RwLock::new(1)); - let arc2 = arc.clone(); - let _lock1 = arc.read(); - thread::spawn(move || { - let _lock = arc2.write(); - }); - thread::sleep(Duration::from_millis(100)); - - // A normal read would block here since there is a pending writer - let _lock2 = arc.read_recursive(); - } - - #[test] - fn test_rwlock_debug() { - let x = RwLock::new(vec![0u8, 10]); - - assert_eq!(format!("{:?}", x), "RwLock { data: [0, 10] }"); - assert_eq!( - format!("{:#?}", x), - "RwLock { - data: [ - 0, - 10 - ] -}" - ); - let _lock = x.write(); - assert_eq!(format!("{:?}", x), "RwLock { }"); - } - - #[test] - fn test_clone() { - let rwlock = RwLock::new(Arc::new(1)); - let a = rwlock.read_recursive(); - let b = a.clone(); - assert_eq!(Arc::strong_count(&b), 2); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.6.4/src/util.rs b/third_party/cargo/vendor/parking_lot-0.6.4/src/util.rs deleted file mode 100644 index c7dfd32..0000000 --- a/third_party/cargo/vendor/parking_lot-0.6.4/src/util.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -// Option::unchecked_unwrap -pub trait UncheckedOptionExt { - unsafe fn unchecked_unwrap(self) -> T; -} - -impl UncheckedOptionExt for Option { - #[inline] - unsafe fn unchecked_unwrap(self) -> T { - match self { - Some(x) => x, - None => unreachable(), - } - } -} - -// Equivalent to intrinsics::unreachable() in release mode -#[inline] -unsafe fn unreachable() -> ! { - if cfg!(debug_assertions) { - unreachable!(); - } else { - enum Void {} - match *(1 as *const Void) {} - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot-0.7.1/.cargo-checksum.json deleted file mode 100644 index 57e8d3e..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"f9a9c82373818d32816c42e0f127f6f14a64d37925f02041c10c66a528e0d454","Cargo.toml":"5cc50b68f3a7a4a61c78fb216a7b5e3e7426d1e3e6f55149ec4d9e35a5e27e94","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"0840b0fe8613d0336800633c48bde4352f80a97a0e85910e1e0d2914d81109cc","appveyor.yml":"a0525637948083d463186164cddbfde87c2d371029ea538a35d2b2c7129a348f","src/condvar.rs":"24cb08be64fb45323a71c8a06de0d3ef7a991f76aca8911e4d39f105003a4dbc","src/deadlock.rs":"8916c2e2820bfd3a55860ddb9f1b907888406b68cdae2b7a2093c825d28f3b99","src/elision.rs":"f55cb93d29b20d8908cde523428fec32503224e7c9ca7bf1475475bc4c1f6202","src/lib.rs":"db6f074b1c35d60116c0b13b25cce6bb497bb680d340058bb942a1427c6b4d4e","src/mutex.rs":"637590d99bf310194171e4bc2d4f23c23e9a5cbf680f383873e2106cfd1e1390","src/once.rs":"02e92cf50e4d81cb9dfc459c9742d8bc2db72f53296f28b38fa81fa1eec0fea6","src/raw_mutex.rs":"ce66c9e9abc5d6f12a1969a369dc8374854e92a33114d6c068752ce36312a562","src/raw_rwlock.rs":"0c996433cf6445fcf3071b19fba1b7d96b0d039435afdb5c6eb5bed88a37f6c2","src/remutex.rs":"b75c9e98bb82e2dec607d3b4cee54daf60f91deea454d337f85416291a6ccc96","src/rwlock.rs":"946214fca407049d5b33cda41d146478f5884bd722bbc441085af7a887922618","src/util.rs":"b69018d1cb4f02c0c4ea068e51d4dbf8a1ae1a3996c3c911a309c3dd05a2c250"},"package":"ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/BUILD b/third_party/cargo/vendor/parking_lot-0.7.1/BUILD deleted file mode 100644 index 9d31b7a..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "Apache-2.0,MIT" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - - -rust_library( - name = "parking_lot", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2015", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/lock_api-0.1.5:lock_api", - "//third_party/cargo/vendor/parking_lot_core-0.4.0:parking_lot_core", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.7.1", - crate_features = [ - "default", - "owning_ref", - ], -) - diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/CHANGELOG.md b/third_party/cargo/vendor/parking_lot-0.7.1/CHANGELOG.md deleted file mode 100644 index ee87251..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/CHANGELOG.md +++ /dev/null @@ -1,59 +0,0 @@ -0.7.1 (2019-01-01) -================== - -- Fixed potential deadlock when upgrading a RwLock. -- Fixed overflow panic on very long timeouts (#111). - -0.7.0 (2018-11-20) -================== - -- Return if or how many threads were notified from `Condvar::notify_*` - -0.6.3 (2018-07-18) -================== - -- Export `RawMutex`, `RawRwLock` and `RawThreadId`. - -0.6.2 (2018-06-18) -================== - -- Enable `lock_api/nightly` feature from `parking_lot/nightly` (#79) - -0.6.1 (2018-06-08) -================== - -Added missing typedefs for mapped lock guards: - -- `MappedMutexGuard` -- `MappedReentrantMutexGuard` -- `MappedRwLockReadGuard` -- `MappedRwLockWriteGuard` - -0.6.0 (2018-06-08) -================== - -This release moves most of the code for type-safe `Mutex` and `RwLock` types -into a separate crate called `lock_api`. This new crate is compatible with -`no_std` and provides `Mutex` and `RwLock` type-safe wrapper types from a -raw mutex type which implements the `RawMutex` or `RawRwLock` trait. The API -provided by the wrapper types can be extended by implementing more traits on the -raw mutex type which provide more functionality (e.g. `RawMutexTimed`). See the -crate documentation for more details. - -There are also several major changes: - -- The minimum required Rust version is bumped to 1.26. -- All methods on `MutexGuard` (and other guard types) are no longer inherent - methods and must be called as `MutexGuard::method(self)`. This avoids - conflicts with methods from the inner type. -- `MutexGuard` (and other guard types) add the `unlocked` method which - temporarily unlocks a mutex, runs the given closure, and then re-locks the - mutex. -- `MutexGuard` (and other guard types) add the `bump` method which gives a - chance for other threads to acquire the mutex by temporarily unlocking it and - re-locking it. However this is optimized for the common case where there are - no threads waiting on the lock, in which case no unlocking is performed. -- `MutexGuard` (and other guard types) add the `map` method which returns a - `MappedMutexGuard` which holds only a subset of the original locked type. The - `MappedMutexGuard` type is identical to `MutexGuard` except that it does not - support the `unlocked` and `bump` methods, and can't be used with `CondVar`. diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/appveyor.yml b/third_party/cargo/vendor/parking_lot-0.7.1/appveyor.yml deleted file mode 100644 index 83498db..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/appveyor.yml +++ /dev/null @@ -1,29 +0,0 @@ -environment: - TRAVIS_CARGO_NIGHTLY_FEATURE: nightly - RUST_TEST_THREADS: 1 - matrix: - - TARGET: nightly-x86_64-pc-windows-msvc - - TARGET: nightly-i686-pc-windows-msvc - - TARGET: nightly-x86_64-pc-windows-gnu - - TARGET: nightly-i686-pc-windows-gnu - - TARGET: 1.24.0-x86_64-pc-windows-msvc - - TARGET: 1.24.0-i686-pc-windows-msvc - - TARGET: 1.24.0-x86_64-pc-windows-gnu - - TARGET: 1.24.0-i686-pc-windows-gnu - -install: - - SET PATH=C:\Python27;C:\Python27\Scripts;%PATH%;%APPDATA%\Python\Scripts - - pip install "travis-cargo<0.2" --user - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe" - - ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null - - ps: $env:PATH="$env:PATH;C:\rust\bin" - - rustc -vV - - cargo -vV - -build_script: - - travis-cargo build - -test_script: - - travis-cargo test - - travis-cargo --only nightly test -- --features=deadlock_detection - - travis-cargo doc diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/elision.rs b/third_party/cargo/vendor/parking_lot-0.7.1/src/elision.rs deleted file mode 100644 index b1201ee..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/elision.rs +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::sync::atomic::AtomicUsize; - -// Extension trait to add lock elision primitives to atomic types -pub trait AtomicElisionExt { - type IntType; - - // Perform a compare_exchange and start a transaction - fn elision_acquire( - &self, - current: Self::IntType, - new: Self::IntType, - ) -> Result; - // Perform a compare_exchange and end a transaction - fn elision_release( - &self, - current: Self::IntType, - new: Self::IntType, - ) -> Result; -} - -// Indicates whether the target architecture supports lock elision -#[inline] -pub fn have_elision() -> bool { - cfg!(all( - feature = "nightly", - any(target_arch = "x86", target_arch = "x86_64"), - )) -} - -// This implementation is never actually called because it is guarded by -// have_elision(). -#[cfg(not(all(feature = "nightly", any(target_arch = "x86", target_arch = "x86_64"))))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, _: usize, _: usize) -> Result { - unreachable!(); - } - - #[inline] - fn elision_release(&self, _: usize, _: usize) -> Result { - unreachable!(); - } -} - -#[cfg(all(feature = "nightly", target_arch = "x86"))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgl $2, $1" - : "={eax}" (prev), "+*m" (self) - : "r" (new), "{eax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgl $2, $1" - : "={eax}" (prev), "+*m" (self) - : "r" (new), "{eax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} - -#[cfg(all( - feature = "nightly", - target_arch = "x86_64", - target_pointer_width = "32" -))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgl $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgl $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} - -#[cfg(all( - feature = "nightly", - target_arch = "x86_64", - target_pointer_width = "64" -))] -impl AtomicElisionExt for AtomicUsize { - type IntType = usize; - - #[inline] - fn elision_acquire(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xacquire; lock; cmpxchgq $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } - - #[inline] - fn elision_release(&self, current: usize, new: usize) -> Result { - unsafe { - let prev: usize; - asm!("xrelease; lock; cmpxchgq $2, $1" - : "={rax}" (prev), "+*m" (self) - : "r" (new), "{rax}" (current) - : "memory" - : "volatile"); - if prev == current { - Ok(prev) - } else { - Err(prev) - } - } - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/lib.rs b/third_party/cargo/vendor/parking_lot-0.7.1/src/lib.rs deleted file mode 100644 index e8cd726..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/lib.rs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -//! This library provides implementations of `Mutex`, `RwLock`, `Condvar` and -//! `Once` that are smaller, faster and more flexible than those in the Rust -//! standard library. It also provides a `ReentrantMutex` type. - -#![warn(missing_docs)] -#![cfg_attr(feature = "nightly", feature(const_fn))] -#![cfg_attr(feature = "nightly", feature(integer_atomics))] -#![cfg_attr(feature = "nightly", feature(asm))] -#![cfg_attr(feature = "nightly", feature(time_checked_add))] - -extern crate lock_api; -extern crate parking_lot_core; - -mod condvar; -mod elision; -mod mutex; -mod once; -mod raw_mutex; -mod raw_rwlock; -mod remutex; -mod rwlock; -mod util; - -#[cfg(feature = "deadlock_detection")] -pub mod deadlock; -#[cfg(not(feature = "deadlock_detection"))] -mod deadlock; - -pub use condvar::{Condvar, WaitTimeoutResult}; -pub use mutex::{MappedMutexGuard, Mutex, MutexGuard}; -pub use once::{Once, OnceState, ONCE_INIT}; -pub use raw_mutex::RawMutex; -pub use raw_rwlock::RawRwLock; -pub use remutex::{MappedReentrantMutexGuard, RawThreadId, ReentrantMutex, ReentrantMutexGuard}; -pub use rwlock::{ - MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, - RwLockUpgradableReadGuard, RwLockWriteGuard, -}; diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/raw_rwlock.rs b/third_party/cargo/vendor/parking_lot-0.7.1/src/raw_rwlock.rs deleted file mode 100644 index de70066..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/raw_rwlock.rs +++ /dev/null @@ -1,1403 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use deadlock; -use elision::{have_elision, AtomicElisionExt}; -use lock_api::{ - GuardNoSend, RawRwLock as RawRwLockTrait, RawRwLockDowngrade, RawRwLockFair, - RawRwLockRecursive, RawRwLockRecursiveTimed, RawRwLockTimed, RawRwLockUpgrade, - RawRwLockUpgradeDowngrade, RawRwLockUpgradeFair, RawRwLockUpgradeTimed, -}; -use parking_lot_core::{self, FilterOp, ParkResult, ParkToken, SpinWait, UnparkResult}; -use raw_mutex::{TOKEN_HANDOFF, TOKEN_NORMAL}; -use std::cell::Cell; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; -use std::time::{Duration, Instant}; -use util; - -const PARKED_BIT: usize = 0b001; -const UPGRADING_BIT: usize = 0b010; -// A shared guard acquires a single guard resource -const SHARED_GUARD: usize = 0b100; -const GUARD_COUNT_MASK: usize = !(SHARED_GUARD - 1); -// An exclusive lock acquires all of guard resource (i.e. it is exclusive) -const EXCLUSIVE_GUARD: usize = GUARD_COUNT_MASK; -// An upgradable lock acquires just over half of the guard resource -// This should be (GUARD_COUNT_MASK + SHARED_GUARD) >> 1, however this might -// overflow, so we shift before adding (which is okay since the least -// significant bit is zero for both GUARD_COUNT_MASK and SHARED_GUARD) -const UPGRADABLE_GUARD: usize = (GUARD_COUNT_MASK >> 1) + (SHARED_GUARD >> 1); - -// Token indicating what type of lock queued threads are trying to acquire -const TOKEN_SHARED: ParkToken = ParkToken(SHARED_GUARD); -const TOKEN_EXCLUSIVE: ParkToken = ParkToken(EXCLUSIVE_GUARD); -const TOKEN_UPGRADABLE: ParkToken = ParkToken(UPGRADABLE_GUARD); -const TOKEN_UPGRADING: ParkToken = ParkToken((EXCLUSIVE_GUARD - UPGRADABLE_GUARD) | UPGRADING_BIT); - -/// Raw reader-writer lock type backed by the parking lot. -pub struct RawRwLock { - state: AtomicUsize, -} - -unsafe impl RawRwLockTrait for RawRwLock { - const INIT: RawRwLock = RawRwLock { - state: ATOMIC_USIZE_INIT, - }; - - type GuardMarker = GuardNoSend; - - #[inline] - fn lock_exclusive(&self) { - if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_err() - { - let result = self.lock_exclusive_slow(None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_exclusive(&self) -> bool { - if self - .state - .compare_exchange(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - true - } else { - false - } - } - - #[inline] - fn unlock_exclusive(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_exclusive_slow(false); - } - - #[inline] - fn lock_shared(&self) { - if !self.try_lock_shared_fast(false) { - let result = self.lock_shared_slow(false, None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_shared(&self) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.try_lock_shared_slow(false) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn unlock_shared(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - let state = self.state.load(Ordering::Relaxed); - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - { - if have_elision() { - if self - .state - .elision_release(state, state - SHARED_GUARD) - .is_ok() - { - return; - } - } else { - if self - .state - .compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) - .is_ok() - { - return; - } - } - } - self.unlock_shared_slow(false); - } -} - -unsafe impl RawRwLockFair for RawRwLock { - #[inline] - fn unlock_shared_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - let state = self.state.load(Ordering::Relaxed); - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - { - if have_elision() { - if self - .state - .elision_release(state, state - SHARED_GUARD) - .is_ok() - { - return; - } - } else { - if self - .state - .compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) - .is_ok() - { - return; - } - } - } - self.unlock_shared_slow(true); - } - - #[inline] - fn unlock_exclusive_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_exclusive_slow(true); - } - - #[inline] - fn bump_shared(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_shared_slow(); - } - } - - #[inline] - fn bump_exclusive(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_exclusive_slow(); - } - } -} - -unsafe impl RawRwLockDowngrade for RawRwLock { - #[inline] - fn downgrade(&self) { - let state = self - .state - .fetch_sub(EXCLUSIVE_GUARD - SHARED_GUARD, Ordering::Release); - - // Wake up parked shared and upgradable threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_slow(); - } - } -} - -unsafe impl RawRwLockTimed for RawRwLock { - type Duration = Duration; - type Instant = Instant; - - #[inline] - fn try_lock_shared_for(&self, timeout: Self::Duration) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.lock_shared_slow(false, util::to_deadline(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_shared_until(&self, timeout: Self::Instant) -> bool { - let result = if self.try_lock_shared_fast(false) { - true - } else { - self.lock_shared_slow(false, Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_exclusive_for(&self, timeout: Duration) -> bool { - let result = if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_exclusive_slow(util::to_deadline(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_exclusive_until(&self, timeout: Instant) -> bool { - let result = if self - .state - .compare_exchange_weak(0, EXCLUSIVE_GUARD, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - true - } else { - self.lock_exclusive_slow(Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockRecursive for RawRwLock { - #[inline] - fn lock_shared_recursive(&self) { - if !self.try_lock_shared_fast(true) { - let result = self.lock_shared_slow(true, None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_shared_recursive(&self) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.try_lock_shared_slow(true) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockRecursiveTimed for RawRwLock { - #[inline] - fn try_lock_shared_recursive_for(&self, timeout: Self::Duration) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.lock_shared_slow(true, util::to_deadline(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_shared_recursive_until(&self, timeout: Self::Instant) -> bool { - let result = if self.try_lock_shared_fast(true) { - true - } else { - self.lock_shared_slow(true, Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } -} - -unsafe impl RawRwLockUpgrade for RawRwLock { - #[inline] - fn lock_upgradable(&self) { - if !self.try_lock_upgradable_fast() { - let result = self.lock_upgradable_slow(None); - debug_assert!(result); - } - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - - #[inline] - fn try_lock_upgradable(&self) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.try_lock_upgradable_slow() - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn unlock_upgradable(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(UPGRADABLE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_upgradable_slow(false); - } - - #[inline] - fn upgrade(&self) { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_err() - { - let result = self.upgrade_slow(None); - debug_assert!(result); - } - } - - fn try_upgrade(&self) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.try_upgrade_slow() - } - } -} - -unsafe impl RawRwLockUpgradeFair for RawRwLock { - #[inline] - fn unlock_upgradable_fair(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - if self - .state - .compare_exchange_weak(UPGRADABLE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - self.unlock_upgradable_slow(true); - } - - #[inline] - fn bump_upgradable(&self) { - if self.state.load(Ordering::Relaxed) & PARKED_BIT != 0 { - self.bump_upgradable_slow(); - } - } -} - -unsafe impl RawRwLockUpgradeDowngrade for RawRwLock { - #[inline] - fn downgrade_upgradable(&self) { - let state = self - .state - .fetch_sub(UPGRADABLE_GUARD - SHARED_GUARD, Ordering::Relaxed); - - // Wake up parked shared and upgradable threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_upgradable_slow(state); - } - } - - #[inline] - fn downgrade_to_upgradable(&self) { - let state = self - .state - .fetch_sub(EXCLUSIVE_GUARD - UPGRADABLE_GUARD, Ordering::Release); - - // Wake up parked shared threads if there are any - if state & PARKED_BIT != 0 { - self.downgrade_to_upgradable_slow(); - } - } -} - -unsafe impl RawRwLockUpgradeTimed for RawRwLock { - #[inline] - fn try_lock_upgradable_until(&self, timeout: Instant) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.lock_upgradable_slow(Some(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_lock_upgradable_for(&self, timeout: Duration) -> bool { - let result = if self.try_lock_upgradable_fast() { - true - } else { - self.lock_upgradable_slow(util::to_deadline(timeout)) - }; - if result { - unsafe { deadlock::acquire_resource(self as *const _ as usize) }; - } - result - } - - #[inline] - fn try_upgrade_until(&self, timeout: Instant) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.upgrade_slow(Some(timeout)) - } - } - - #[inline] - fn try_upgrade_for(&self, timeout: Duration) -> bool { - if self - .state - .compare_exchange_weak( - UPGRADABLE_GUARD, - EXCLUSIVE_GUARD, - Ordering::Relaxed, - Ordering::Relaxed, - ) - .is_ok() - { - true - } else { - self.upgrade_slow(util::to_deadline(timeout)) - } - } -} - -impl RawRwLock { - #[inline(always)] - fn try_lock_shared_fast(&self, recursive: bool) -> bool { - let state = self.state.load(Ordering::Relaxed); - - // We can't allow grabbing a shared lock while there are parked threads - // since that could lead to writer starvation. - if !recursive && state & PARKED_BIT != 0 { - return false; - } - - // Use hardware lock elision to avoid cache conflicts when multiple - // readers try to acquire the lock. We only do this if the lock is - // completely empty since elision handles conflicts poorly. - if have_elision() && state == 0 { - self.state.elision_acquire(0, SHARED_GUARD).is_ok() - } else if let Some(new_state) = state.checked_add(SHARED_GUARD) { - self.state - .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - } else { - false - } - } - - #[inline(always)] - fn try_lock_upgradable_fast(&self) -> bool { - let state = self.state.load(Ordering::Relaxed); - - // We can't allow grabbing an upgradable lock while there are parked threads - // since that could lead to writer starvation. - if state & PARKED_BIT != 0 { - return false; - } - - if let Some(new_state) = state.checked_add(UPGRADABLE_GUARD) { - self.state - .compare_exchange_weak(state, new_state, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - } else { - false - } - } - - #[cold] - #[inline(never)] - fn lock_exclusive_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there are other - // threads parked. - if let Some(new_state) = state.checked_add(EXCLUSIVE_GUARD) { - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - continue; - } - - // If there are no parked threads and only one reader or writer, try - // spinning a few times. - if (state == EXCLUSIVE_GUARD || state == SHARED_GUARD || state == UPGRADABLE_GUARD) - && spinwait.spin() - { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // If the rwlock is free, abort the park and try to grab - // it immediately. - if state & GUARD_COUNT_MASK == 0 { - return false; - } - - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_EXCLUSIVE, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - state = self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - fn unlock_exclusive_slow(&self, force_fair: bool) { - // Unlock directly if there are no parked threads - if self - .state - .compare_exchange(EXCLUSIVE_GUARD, 0, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - }; - - // There are threads to unpark. We unpark threads up to the guard capacity. - let guard_count = Cell::new(0usize); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.get().checked_add(token) { - Some(new_guard_count) => { - guard_count.set(new_guard_count); - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // If we are using a fair unlock then we should keep the - // rwlock locked and hand it off to the unparked threads. - if result.unparked_threads != 0 && (force_fair || result.be_fair) { - // We need to set the guard count accordingly. - let mut new_state = guard_count.get(); - - if result.have_more_threads { - new_state |= PARKED_BIT; - } - - self.state.store(new_state, Ordering::Release); - TOKEN_HANDOFF - } else { - // Clear the parked bit if there are no more parked threads. - if result.have_more_threads { - self.state.store(PARKED_BIT, Ordering::Release); - } else { - self.state.store(0, Ordering::Release); - } - TOKEN_NORMAL - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_slow(&self) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = SHARED_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(new_guard_count) => { - guard_count = new_guard_count; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_to_upgradable_slow(&self) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = UPGRADABLE_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(new_guard_count) => { - guard_count = new_guard_count; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn lock_shared_slow(&self, recursive: bool, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut spinwait_shared = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - let mut unparked = false; - loop { - // Use hardware lock elision to avoid cache conflicts when multiple - // readers try to acquire the lock. We only do this if the lock is - // completely empty since elision handles conflicts poorly. - if have_elision() && state == 0 { - match self.state.elision_acquire(0, SHARED_GUARD) { - Ok(_) => return true, - Err(x) => state = x, - } - } - - // Grab the lock if there are no exclusive threads locked or - // waiting. However if we were unparked then we are allowed to grab - // the lock even if there are pending exclusive threads. - if unparked || recursive || state & PARKED_BIT == 0 { - if let Some(new_state) = state.checked_add(SHARED_GUARD) { - if self - .state - .compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_ok() - { - return true; - } - - // If there is high contention on the reader count then we want - // to leave some time between attempts to acquire the lock to - // let other threads make progress. - spinwait_shared.spin_no_yield(); - state = self.state.load(Ordering::Relaxed); - continue; - } else { - // We were unparked spuriously, reset unparked flag. - unparked = false; - } - } - - // If there are no parked threads, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // If the parked bit is not set then it means we are at - // the front of the queue. If there is space for another - // lock then we should abort the park and try acquiring - // the lock again. - if state & GUARD_COUNT_MASK != GUARD_COUNT_MASK { - return false; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_SHARED, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - spinwait_shared.reset(); - state = self.state.load(Ordering::Relaxed); - unparked = true; - } - } - - #[cold] - #[inline(never)] - fn try_lock_shared_slow(&self, recursive: bool) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if !recursive && state & PARKED_BIT != 0 { - return false; - } - if have_elision() && state == 0 { - match self.state.elision_acquire(0, SHARED_GUARD) { - Ok(_) => return true, - Err(x) => state = x, - } - } else { - match state.checked_add(SHARED_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - } - - #[cold] - #[inline(never)] - fn unlock_shared_slow(&self, force_fair: bool) { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Just release the lock if there are no parked thread or if we are - // not the last shared thread. - if state & PARKED_BIT == 0 - || (state & UPGRADING_BIT == 0 && state & GUARD_COUNT_MASK != SHARED_GUARD) - || (state & UPGRADING_BIT != 0 - && state & GUARD_COUNT_MASK != UPGRADABLE_GUARD + SHARED_GUARD) - { - match self.state.compare_exchange_weak( - state, - state - SHARED_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - continue; - } - - break; - } - - // There are threads to unpark. If there is a thread waiting to be - // upgraded, we find that thread and let it upgrade, otherwise we - // unpark threads up to the guard capacity. Note that there is a - // potential race condition here: another thread might grab a shared - // lock between now and when we actually release our lock. - let additional_guards = Cell::new(0usize); - let has_upgraded = Cell::new(false); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - // We need to check UPGRADING_BIT while holding the bucket lock, - // otherwise we might miss a thread trying to upgrade. - if self.state.load(Ordering::Relaxed) & UPGRADING_BIT == 0 { - match additional_guards.get().checked_add(token) { - Some(x) => { - additional_guards.set(x); - FilterOp::Unpark - } - None => FilterOp::Stop, - } - } else if has_upgraded.get() { - FilterOp::Stop - } else { - if token & UPGRADING_BIT != 0 { - additional_guards.set(token & !UPGRADING_BIT); - has_upgraded.set(true); - FilterOp::Unpark - } else { - FilterOp::Skip - } - } - }; - let callback = |result: UnparkResult| { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Release our shared lock - let mut new_state = state - SHARED_GUARD; - - // Clear the parked bit if there are no more threads in - // the queue. - if !result.have_more_threads { - new_state &= !PARKED_BIT; - } - - // Clear the upgrading bit if we are upgrading a thread. - if has_upgraded.get() { - new_state &= !UPGRADING_BIT; - } - - // Consider using fair unlocking. If we are, then we should set - // the state to the new value and tell the threads that we are - // handing the lock directly. - let token = if result.unparked_threads != 0 && (force_fair || result.be_fair) { - match new_state.checked_add(additional_guards.get()) { - Some(x) => { - new_state = x; - TOKEN_HANDOFF - } - None => TOKEN_NORMAL, - } - } else { - TOKEN_NORMAL - }; - - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return token, - Err(x) => state = x, - } - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn lock_upgradable_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut spinwait_shared = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - let mut unparked = false; - loop { - // Grab the lock if there are no exclusive or upgradable threads - // locked or waiting. However if we were unparked then we are - // allowed to grab the lock even if there are pending exclusive threads. - if unparked || state & PARKED_BIT == 0 { - if let Some(new_state) = state.checked_add(UPGRADABLE_GUARD) { - if self - .state - .compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) - .is_ok() - { - return true; - } - - // If there is high contention on the reader count then we want - // to leave some time between attempts to acquire the lock to - // let other threads make progress. - spinwait_shared.spin_no_yield(); - state = self.state.load(Ordering::Relaxed); - continue; - } else { - // We were unparked spuriously, reset unparked flag. - unparked = false; - } - } - - // If there are no parked threads, try spinning a few times - if state & PARKED_BIT == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Nothing to do if the parked bit is already set - if state & PARKED_BIT != 0 { - return true; - } - - // If the parked bit is not set then it means we are at - // the front of the queue. If there is space for an - // upgradable lock then we should abort the park and try - // acquiring the lock again. - if state & UPGRADABLE_GUARD != UPGRADABLE_GUARD { - return false; - } - - // Set the parked bit - match self.state.compare_exchange_weak( - state, - state | PARKED_BIT, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the parked bit if we were the last parked thread - if was_last_thread { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_UPGRADABLE, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - spinwait_shared.reset(); - state = self.state.load(Ordering::Relaxed); - unparked = true; - } - } - - #[cold] - #[inline(never)] - fn try_lock_upgradable_slow(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - if state & PARKED_BIT != 0 { - return false; - } - - match state.checked_add(UPGRADABLE_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - - #[cold] - #[inline(never)] - fn unlock_upgradable_slow(&self, force_fair: bool) { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Just release the lock if there are no parked threads. - if state & PARKED_BIT == 0 { - match self.state.compare_exchange_weak( - state, - state - UPGRADABLE_GUARD, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - continue; - } - - break; - } - - // There are threads to unpark. We unpark threads up to the guard capacity. - let additional_guards = Cell::new(0usize); - unsafe { - let addr = self as *const _ as usize; - let filter = |ParkToken(token)| -> FilterOp { - match additional_guards.get().checked_add(token) { - Some(x) => { - additional_guards.set(x); - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Release our upgradable lock - let mut new_state = state - UPGRADABLE_GUARD; - - // Clear the parked bit if there are no more threads in - // the queue - if !result.have_more_threads { - new_state &= !PARKED_BIT; - } - - // Consider using fair unlocking. If we are, then we should set - // the state to the new value and tell the threads that we are - // handing the lock directly. - let token = if result.unparked_threads != 0 && (force_fair || result.be_fair) { - match new_state.checked_add(additional_guards.get()) { - Some(x) => { - new_state = x; - TOKEN_HANDOFF - } - None => TOKEN_NORMAL, - } - } else { - TOKEN_NORMAL - }; - - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return token, - Err(x) => state = x, - } - } - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn downgrade_upgradable_slow(&self, state: usize) { - unsafe { - let addr = self as *const _ as usize; - let mut guard_count = (state & GUARD_COUNT_MASK) - UPGRADABLE_GUARD; - let filter = |ParkToken(token)| -> FilterOp { - match guard_count.checked_add(token) { - Some(x) => { - guard_count = x; - FilterOp::Unpark - } - None => FilterOp::Stop, - } - }; - let callback = |result: UnparkResult| { - // Clear the parked bit if there no more parked threads - if !result.have_more_threads { - self.state.fetch_and(!PARKED_BIT, Ordering::Relaxed); - } - TOKEN_NORMAL - }; - parking_lot_core::unpark_filter(addr, filter, callback); - } - } - - #[cold] - #[inline(never)] - fn try_upgrade_slow(&self) -> bool { - let mut state = self.state.load(Ordering::Relaxed); - loop { - match state.checked_add(EXCLUSIVE_GUARD - SHARED_GUARD) { - Some(new_state) => match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - }, - None => return false, - } - } - } - - #[cold] - #[inline(never)] - fn upgrade_slow(&self, timeout: Option) -> bool { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there are other - // threads parked. - if let Some(new_state) = state.checked_add(EXCLUSIVE_GUARD - UPGRADABLE_GUARD) { - match self.state.compare_exchange_weak( - state, - new_state, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - continue; - } - - // If there are no parked threads and only one other reader, try - // spinning a few times. - if state == UPGRADABLE_GUARD | SHARED_GUARD && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Park our thread until we are woken up by an unlock - unsafe { - let addr = self as *const _ as usize; - let validate = || { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // If the rwlock is free, abort the park and try to grab - // it immediately. - if state & GUARD_COUNT_MASK == UPGRADABLE_GUARD { - return false; - } - - // Set the upgrading and parked bits - match self.state.compare_exchange_weak( - state, - state | (UPGRADING_BIT | PARKED_BIT), - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => return true, - Err(x) => state = x, - } - } - }; - let before_sleep = || {}; - let timed_out = |_, was_last_thread| { - // Clear the upgrading bit - let mut flags = UPGRADING_BIT; - - // Clear the parked bit if we were the last parked thread - if was_last_thread { - flags |= PARKED_BIT; - } - - self.state.fetch_and(!flags, Ordering::Relaxed); - }; - match parking_lot_core::park( - addr, - validate, - before_sleep, - timed_out, - TOKEN_UPGRADING, - timeout, - ) { - // The thread that unparked us passed the lock on to us - // directly without unlocking it. - ParkResult::Unparked(TOKEN_HANDOFF) => return true, - - // We were unparked normally, try acquiring the lock again - ParkResult::Unparked(_) => (), - - // The validation function failed, try locking again - ParkResult::Invalid => (), - - // Timeout expired - ParkResult::TimedOut => return false, - } - } - - // Loop back and try locking again - spinwait.reset(); - state = self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - fn bump_shared_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_shared_slow(true); - self.lock_shared(); - } - - #[cold] - #[inline(never)] - fn bump_exclusive_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_exclusive_slow(true); - self.lock_exclusive(); - } - - #[cold] - #[inline(never)] - fn bump_upgradable_slow(&self) { - unsafe { deadlock::release_resource(self as *const _ as usize) }; - self.unlock_upgradable_slow(true); - self.lock_upgradable(); - } -} diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/src/util.rs b/third_party/cargo/vendor/parking_lot-0.7.1/src/util.rs deleted file mode 100644 index c05a539..0000000 --- a/third_party/cargo/vendor/parking_lot-0.7.1/src/util.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::time::{Duration, Instant}; - -// Option::unchecked_unwrap -pub trait UncheckedOptionExt { - unsafe fn unchecked_unwrap(self) -> T; -} - -impl UncheckedOptionExt for Option { - #[inline] - unsafe fn unchecked_unwrap(self) -> T { - match self { - Some(x) => x, - None => unreachable(), - } - } -} - -// Equivalent to intrinsics::unreachable() in release mode -#[inline] -unsafe fn unreachable() -> ! { - if cfg!(debug_assertions) { - unreachable!(); - } else { - enum Void {} - match *(1 as *const Void) {} - } -} - -#[inline] -pub fn to_deadline(timeout: Duration) -> Option { - #[cfg(feature = "nightly")] - let deadline = Instant::now().checked_add(timeout); - #[cfg(not(feature = "nightly"))] - let deadline = Some(Instant::now() + timeout); - - deadline -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot_core-0.3.1/.cargo-checksum.json deleted file mode 100644 index 6706d64..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"dc95a171db000a9243f985288bafad64342c5a669cfeb63a11776d0858e7c0a1","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","build.rs":"b4ca69501aa539f2d9a50a3188e93d69eb5ad0c38d5cd194df361a3f2f9a8b92","src/lib.rs":"9d5d80460481b44b8d9048b7319be33ac989250960c61b7c4528c0431f9ad36c","src/parking_lot.rs":"f7f597e768def124c78241a419ca2df965f0896b079e195a9d884d89cfbe9f17","src/spinwait.rs":"45a0f2a57177bc9759c0c2167f758ee220fba7cd8bdf1fbcd9c2b962fef9a1e5","src/thread_parker/generic.rs":"985966b1bdc763ada6d1fee800d19dd92611da4f84cfeef2d82763ffd2a499c3","src/thread_parker/linux.rs":"c41d08ab333972b67f20443f474ed25a1f171db0f87e227df4bdc504f6f9d897","src/thread_parker/unix.rs":"6364bcfeacfb3189bcebeddfccef1b9843d3c59d6d0f046827e62b33bcee30dd","src/thread_parker/windows/keyed_event.rs":"83d4bace5d2f17993071de28043e94f3b9673c887e01c72653b6fd24db260634","src/thread_parker/windows/mod.rs":"f31eed53f3e402477d80a70a7c6d474c01ba4c9ad952bbe562509448cd3cc1ad","src/thread_parker/windows/waitaddress.rs":"1a6eee8ab9131c746089e78b0aab900f23a5ed8ee6f2e789b8ec4d2232153ab8","src/util.rs":"2d07c0c010a857790ae2ed6a1215eeed8af76859e076797ea1ba8dec82169e84","src/word_lock.rs":"c4d50c0d37e6dd92fb078c80f84dc5b5c83bdf46baad34ed35af8730a345a2b5"},"package":"ad7f7e6ebdc79edff6fdcb87a55b620174f7a989e3eb31b65231f4af57f00b8c"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-MIT b/third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-MIT deleted file mode 100644 index 40b8817..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2016 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/build.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/build.rs deleted file mode 100644 index 8d745ee..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/build.rs +++ /dev/null @@ -1,8 +0,0 @@ -extern crate rustc_version; -use rustc_version::{version, Version}; - -fn main() { - if version().unwrap() >= Version::parse("1.26.0").unwrap() { - println!("cargo:rustc-cfg=has_localkey_try_with"); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/parking_lot.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/parking_lot.rs deleted file mode 100644 index 2d525a7..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/parking_lot.rs +++ /dev/null @@ -1,1391 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use rand::rngs::SmallRng; -use rand::{FromEntropy, Rng}; -use smallvec::SmallVec; -use std::cell::{Cell, UnsafeCell}; -use std::mem; -#[cfg(not(has_localkey_try_with))] -use std::panic; -use std::ptr; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; -use std::thread::LocalKey; -use std::time::{Duration, Instant}; -use thread_parker::ThreadParker; -use util::UncheckedOptionExt; -use word_lock::WordLock; - -static NUM_THREADS: AtomicUsize = ATOMIC_USIZE_INIT; -static HASHTABLE: AtomicUsize = ATOMIC_USIZE_INIT; - -// Even with 3x more buckets than threads, the memory overhead per thread is -// still only a few hundred bytes per thread. -const LOAD_FACTOR: usize = 3; - -struct HashTable { - // Hash buckets for the table - entries: Box<[Bucket]>, - - // Number of bits used for the hash function - hash_bits: u32, - - // Previous table. This is only kept to keep leak detectors happy. - _prev: *const HashTable, -} - -impl HashTable { - fn new(num_threads: usize, prev: *const HashTable) -> Box { - let new_size = (num_threads * LOAD_FACTOR).next_power_of_two(); - let hash_bits = 0usize.leading_zeros() - new_size.leading_zeros() - 1; - let bucket = Bucket { - mutex: WordLock::new(), - queue_head: Cell::new(ptr::null()), - queue_tail: Cell::new(ptr::null()), - fair_timeout: UnsafeCell::new(FairTimeout::new()), - _padding: unsafe { mem::uninitialized() }, - }; - Box::new(HashTable { - entries: vec![bucket; new_size].into_boxed_slice(), - hash_bits: hash_bits, - _prev: prev, - }) - } -} - -struct Bucket { - // Lock protecting the queue - mutex: WordLock, - - // Linked list of threads waiting on this bucket - queue_head: Cell<*const ThreadData>, - queue_tail: Cell<*const ThreadData>, - - // Next time at which point be_fair should be set - fair_timeout: UnsafeCell, - - // Padding to avoid false sharing between buckets. Ideally we would just - // align the bucket structure to 64 bytes, but Rust doesn't support that - // yet. - _padding: [u8; 64], -} - -// Implementation of Clone for Bucket, needed to make vec![] work -impl Clone for Bucket { - fn clone(&self) -> Bucket { - Bucket { - mutex: WordLock::new(), - queue_head: Cell::new(ptr::null()), - queue_tail: Cell::new(ptr::null()), - fair_timeout: UnsafeCell::new(FairTimeout::new()), - _padding: unsafe { mem::uninitialized() }, - } - } -} - -struct FairTimeout { - // Next time at which point be_fair should be set - timeout: Instant, - - // Random number generator for calculating the next timeout - rng: SmallRng, -} - -impl FairTimeout { - fn new() -> FairTimeout { - FairTimeout { - timeout: Instant::now(), - rng: SmallRng::from_entropy(), - } - } - - // Determine whether we should force a fair unlock, and update the timeout - fn should_timeout(&mut self) -> bool { - let now = Instant::now(); - if now > self.timeout { - self.timeout = now + Duration::new(0, self.rng.gen_range(0, 1000000)); - true - } else { - false - } - } -} - -struct ThreadData { - parker: ThreadParker, - - // Key that this thread is sleeping on. This may change if the thread is - // requeued to a different key. - key: AtomicUsize, - - // Linked list of parked threads in a bucket - next_in_queue: Cell<*const ThreadData>, - - // UnparkToken passed to this thread when it is unparked - unpark_token: Cell, - - // ParkToken value set by the thread when it was parked - park_token: Cell, - - // Is the thread parked with a timeout? - parked_with_timeout: Cell, - - // Extra data for deadlock detection - // TODO: once supported in stable replace with #[cfg...] & remove dummy struct/impl - #[allow(dead_code)] - deadlock_data: deadlock::DeadlockData, -} - -impl ThreadData { - fn new() -> ThreadData { - // Keep track of the total number of live ThreadData objects and resize - // the hash table accordingly. - let num_threads = NUM_THREADS.fetch_add(1, Ordering::Relaxed) + 1; - unsafe { - grow_hashtable(num_threads); - } - - ThreadData { - parker: ThreadParker::new(), - key: AtomicUsize::new(0), - next_in_queue: Cell::new(ptr::null()), - unpark_token: Cell::new(DEFAULT_UNPARK_TOKEN), - park_token: Cell::new(DEFAULT_PARK_TOKEN), - parked_with_timeout: Cell::new(false), - deadlock_data: deadlock::DeadlockData::new(), - } - } -} - -// Returns a ThreadData structure for the current thread -unsafe fn get_thread_data(local: &mut Option) -> &ThreadData { - // Try to read from thread-local storage, but return None if the TLS has - // already been destroyed. - #[cfg(has_localkey_try_with)] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - key.try_with(|x| x as *const ThreadData).ok() - } - #[cfg(not(has_localkey_try_with))] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - panic::catch_unwind(|| key.with(|x| x as *const ThreadData)).ok() - } - - // Unlike word_lock::ThreadData, parking_lot::ThreadData is always expensive - // to construct. Try to use a thread-local version if possible. - thread_local!(static THREAD_DATA: ThreadData = ThreadData::new()); - if let Some(tls) = try_get_tls(&THREAD_DATA) { - return &*tls; - } - - // Otherwise just create a ThreadData on the stack - *local = Some(ThreadData::new()); - local.as_ref().unwrap() -} - -impl Drop for ThreadData { - fn drop(&mut self) { - NUM_THREADS.fetch_sub(1, Ordering::Relaxed); - } -} - -// Get a pointer to the latest hash table, creating one if it doesn't exist yet. -unsafe fn get_hashtable() -> *const HashTable { - let mut table = HASHTABLE.load(Ordering::Acquire); - - // If there is no table, create one - if table == 0 { - let new_table = Box::into_raw(HashTable::new(LOAD_FACTOR, ptr::null())); - - // If this fails then it means some other thread created the hash - // table first. - match HASHTABLE.compare_exchange( - 0, - new_table as usize, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return new_table, - Err(x) => table = x, - } - - // Free the table we created - Box::from_raw(new_table); - } - - table as *const HashTable -} - -// Grow the hash table so that it is big enough for the given number of threads. -// This isn't performance-critical since it is only done when a ThreadData is -// created, which only happens once per thread. -unsafe fn grow_hashtable(num_threads: usize) { - // If there is no table, create one - if HASHTABLE.load(Ordering::Relaxed) == 0 { - let new_table = Box::into_raw(HashTable::new(num_threads, ptr::null())); - - // If this fails then it means some other thread created the hash - // table first. - if HASHTABLE - .compare_exchange(0, new_table as usize, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - - // Free the table we created - Box::from_raw(new_table); - } - - let mut old_table; - loop { - old_table = HASHTABLE.load(Ordering::Acquire) as *mut HashTable; - - // Check if we need to resize the existing table - if (*old_table).entries.len() >= LOAD_FACTOR * num_threads { - return; - } - - // Lock all buckets in the old table - for b in &(*old_table).entries[..] { - b.mutex.lock(); - } - - // Now check if our table is still the latest one. Another thread could - // have grown the hash table between us reading HASHTABLE and locking - // the buckets. - if HASHTABLE.load(Ordering::Relaxed) == old_table as usize { - break; - } - - // Unlock buckets and try again - for b in &(*old_table).entries[..] { - b.mutex.unlock(); - } - } - - // Create the new table - let new_table = HashTable::new(num_threads, old_table); - - // Move the entries from the old table to the new one - for b in &(*old_table).entries[..] { - let mut current = b.queue_head.get(); - while !current.is_null() { - let next = (*current).next_in_queue.get(); - let hash = hash((*current).key.load(Ordering::Relaxed), new_table.hash_bits); - if new_table.entries[hash].queue_tail.get().is_null() { - new_table.entries[hash].queue_head.set(current); - } else { - (*new_table.entries[hash].queue_tail.get()) - .next_in_queue - .set(current); - } - new_table.entries[hash].queue_tail.set(current); - (*current).next_in_queue.set(ptr::null()); - current = next; - } - } - - // Publish the new table. No races are possible at this point because - // any other thread trying to grow the hash table is blocked on the bucket - // locks in the old table. - HASHTABLE.store(Box::into_raw(new_table) as usize, Ordering::Release); - - // Unlock all buckets in the old table - for b in &(*old_table).entries[..] { - b.mutex.unlock(); - } -} - -// Hash function for addresses -#[cfg(target_pointer_width = "32")] -fn hash(key: usize, bits: u32) -> usize { - key.wrapping_mul(0x9E3779B9) >> (32 - bits) -} -#[cfg(target_pointer_width = "64")] -fn hash(key: usize, bits: u32) -> usize { - key.wrapping_mul(0x9E3779B97F4A7C15) >> (64 - bits) -} - -// Lock the bucket for the given key -unsafe fn lock_bucket<'a>(key: usize) -> &'a Bucket { - let mut bucket; - loop { - let hashtable = get_hashtable(); - - let hash = hash(key, (*hashtable).hash_bits); - bucket = &(*hashtable).entries[hash]; - - // Lock the bucket - bucket.mutex.lock(); - - // If no other thread has rehashed the table before we grabbed the lock - // then we are good to go! The lock we grabbed prevents any rehashes. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize { - return bucket; - } - - // Unlock the bucket and try again - bucket.mutex.unlock(); - } -} - -// Lock the bucket for the given key, but check that the key hasn't been changed -// in the meantime due to a requeue. -unsafe fn lock_bucket_checked<'a>(key: &AtomicUsize) -> (usize, &'a Bucket) { - let mut bucket; - loop { - let hashtable = get_hashtable(); - let current_key = key.load(Ordering::Relaxed); - - let hash = hash(current_key, (*hashtable).hash_bits); - bucket = &(*hashtable).entries[hash]; - - // Lock the bucket - bucket.mutex.lock(); - - // Check that both the hash table and key are correct while the bucket - // is locked. Note that the key can't change once we locked the proper - // bucket for it, so we just keep trying until we have the correct key. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize - && key.load(Ordering::Relaxed) == current_key - { - return (current_key, bucket); - } - - // Unlock the bucket and try again - bucket.mutex.unlock(); - } -} - -// Lock the two buckets for the given pair of keys -unsafe fn lock_bucket_pair<'a>(key1: usize, key2: usize) -> (&'a Bucket, &'a Bucket) { - let mut bucket1; - loop { - let hashtable = get_hashtable(); - - // Get the lowest bucket first - let hash1 = hash(key1, (*hashtable).hash_bits); - let hash2 = hash(key2, (*hashtable).hash_bits); - if hash1 <= hash2 { - bucket1 = &(*hashtable).entries[hash1]; - } else { - bucket1 = &(*hashtable).entries[hash2]; - } - - // Lock the first bucket - bucket1.mutex.lock(); - - // If no other thread has rehashed the table before we grabbed the lock - // then we are good to go! The lock we grabbed prevents any rehashes. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize { - // Now lock the second bucket and return the two buckets - if hash1 == hash2 { - return (bucket1, bucket1); - } else if hash1 < hash2 { - let bucket2 = &(*hashtable).entries[hash2]; - bucket2.mutex.lock(); - return (bucket1, bucket2); - } else { - let bucket2 = &(*hashtable).entries[hash1]; - bucket2.mutex.lock(); - return (bucket2, bucket1); - } - } - - // Unlock the bucket and try again - bucket1.mutex.unlock(); - } -} - -// Unlock a pair of buckets -unsafe fn unlock_bucket_pair(bucket1: &Bucket, bucket2: &Bucket) { - if bucket1 as *const _ == bucket2 as *const _ { - bucket1.mutex.unlock(); - } else if bucket1 as *const _ < bucket2 as *const _ { - bucket2.mutex.unlock(); - bucket1.mutex.unlock(); - } else { - bucket1.mutex.unlock(); - bucket2.mutex.unlock(); - } -} - -/// Result of a park operation. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum ParkResult { - /// We were unparked by another thread with the given token. - Unparked(UnparkToken), - - /// The validation callback returned false. - Invalid, - - /// The timeout expired. - TimedOut, -} - -impl ParkResult { - /// Returns true if we were unparked by another thread. - pub fn is_unparked(self) -> bool { - if let ParkResult::Unparked(_) = self { - true - } else { - false - } - } -} - -/// Result of an unpark operation. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub struct UnparkResult { - /// The number of threads that were unparked. - pub unparked_threads: usize, - - /// Whether there are any threads remaining in the queue. This only returns - /// true if a thread was unparked. - pub have_more_threads: bool, - - /// This is set to true on average once every 0.5ms for any given key. It - /// should be used to switch to a fair unlocking mechanism for a particular - /// unlock. - pub be_fair: bool, -} - -/// Operation that `unpark_requeue` should perform. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum RequeueOp { - /// Abort the operation without doing anything. - Abort, - - /// Unpark one thread and requeue the rest onto the target queue. - UnparkOneRequeueRest, - - /// Requeue all threads onto the target queue. - RequeueAll, -} - -/// Operation that `unpark_filter` should perform for each thread. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub enum FilterOp { - /// Unpark the thread and continue scanning the list of parked threads. - Unpark, - - /// Don't unpark the thread and continue scanning the list of parked threads. - Skip, - - /// Don't unpark the thread and stop scanning the list of parked threads. - Stop, -} - -/// A value which is passed from an unparker to a parked thread. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub struct UnparkToken(pub usize); - -/// A value associated with a parked thread which can be used by `unpark_filter`. -#[derive(Copy, Clone, Eq, PartialEq, Debug)] -pub struct ParkToken(pub usize); - -/// A default unpark token to use. -pub const DEFAULT_UNPARK_TOKEN: UnparkToken = UnparkToken(0); - -/// A default park token to use. -pub const DEFAULT_PARK_TOKEN: ParkToken = ParkToken(0); - -/// Parks the current thread in the queue associated with the given key. -/// -/// The `validate` function is called while the queue is locked and can abort -/// the operation by returning false. If `validate` returns true then the -/// current thread is appended to the queue and the queue is unlocked. -/// -/// The `before_sleep` function is called after the queue is unlocked but before -/// the thread is put to sleep. The thread will then sleep until it is unparked -/// or the given timeout is reached. -/// -/// The `timed_out` function is also called while the queue is locked, but only -/// if the timeout was reached. It is passed the key of the queue it was in when -/// it timed out, which may be different from the original key if -/// `unpark_requeue` was called. It is also passed a bool which indicates -/// whether it was the last thread in the queue. -/// -/// # Safety -/// -/// You should only call this function with an address that you control, since -/// you could otherwise interfere with the operation of other synchronization -/// primitives. -/// -/// The `validate` and `timed_out` functions are called while the queue is -/// locked and must not panic or call into any function in `parking_lot`. -/// -/// The `before_sleep` function is called outside the queue lock and is allowed -/// to call `unpark_one`, `unpark_all`, `unpark_requeue` or `unpark_filter`, but -/// it is not allowed to call `park` or panic. -#[inline] -pub unsafe fn park( - key: usize, - validate: V, - before_sleep: B, - timed_out: T, - park_token: ParkToken, - timeout: Option, -) -> ParkResult -where - V: FnOnce() -> bool, - B: FnOnce(), - T: FnOnce(usize, bool), -{ - let mut v = Some(validate); - let mut b = Some(before_sleep); - let mut t = Some(timed_out); - park_internal( - key, - &mut || v.take().unchecked_unwrap()(), - &mut || b.take().unchecked_unwrap()(), - &mut |key, was_last_thread| t.take().unchecked_unwrap()(key, was_last_thread), - park_token, - timeout, - ) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn park_internal( - key: usize, - validate: &mut FnMut() -> bool, - before_sleep: &mut FnMut(), - timed_out: &mut FnMut(usize, bool), - park_token: ParkToken, - timeout: Option, -) -> ParkResult { - // Grab our thread data, this also ensures that the hash table exists - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - - // Lock the bucket for the given key - let bucket = lock_bucket(key); - - // If the validation function fails, just return - if !validate() { - bucket.mutex.unlock(); - return ParkResult::Invalid; - } - - // Append our thread data to the queue and unlock the bucket - thread_data.parked_with_timeout.set(timeout.is_some()); - thread_data.next_in_queue.set(ptr::null()); - thread_data.key.store(key, Ordering::Relaxed); - thread_data.park_token.set(park_token); - thread_data.parker.prepare_park(); - if !bucket.queue_head.get().is_null() { - (*bucket.queue_tail.get()).next_in_queue.set(thread_data); - } else { - bucket.queue_head.set(thread_data); - } - bucket.queue_tail.set(thread_data); - bucket.mutex.unlock(); - - // Invoke the pre-sleep callback - before_sleep(); - - // Park our thread and determine whether we were woken up by an unpark or by - // our timeout. Note that this isn't precise: we can still be unparked since - // we are still in the queue. - let unparked = match timeout { - Some(timeout) => thread_data.parker.park_until(timeout), - None => { - thread_data.parker.park(); - // call deadlock detection on_unpark hook - deadlock::on_unpark(thread_data); - true - } - }; - - // If we were unparked, return now - if unparked { - return ParkResult::Unparked(thread_data.unpark_token.get()); - } - - // Lock our bucket again. Note that the hashtable may have been rehashed in - // the meantime. Our key may also have changed if we were requeued. - let (key, bucket) = lock_bucket_checked(&thread_data.key); - - // Now we need to check again if we were unparked or timed out. Unlike the - // last check this is precise because we hold the bucket lock. - if !thread_data.parker.timed_out() { - bucket.mutex.unlock(); - return ParkResult::Unparked(thread_data.unpark_token.get()); - } - - // We timed out, so we now need to remove our thread from the queue - let mut link = &bucket.queue_head; - let mut current = bucket.queue_head.get(); - let mut previous = ptr::null(); - while !current.is_null() { - if current == thread_data { - let next = (*current).next_in_queue.get(); - link.set(next); - let mut was_last_thread = true; - if bucket.queue_tail.get() == current { - bucket.queue_tail.set(previous); - } else { - // Scan the rest of the queue to see if there are any other - // entries with the given key. - let mut scan = next; - while !scan.is_null() { - if (*scan).key.load(Ordering::Relaxed) == key { - was_last_thread = false; - break; - } - scan = (*scan).next_in_queue.get(); - } - } - - // Callback to indicate that we timed out, and whether we were the - // last thread on the queue. - timed_out(key, was_last_thread); - break; - } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - } - - // There should be no way for our thread to have been removed from the queue - // if we timed out. - debug_assert!(!current.is_null()); - - // Unlock the bucket, we are done - bucket.mutex.unlock(); - ParkResult::TimedOut -} - -/// Unparks one thread from the queue associated with the given key. -/// -/// The `callback` function is called while the queue is locked and before the -/// target thread is woken up. The `UnparkResult` argument to the function -/// indicates whether a thread was found in the queue and whether this was the -/// last thread in the queue. This value is also returned by `unpark_one`. -/// -/// The `callback` function should return an `UnparkToken` value which will be -/// passed to the thread that is unparked. If no thread is unparked then the -/// returned value is ignored. -/// -/// # Safety -/// -/// You should only call this function with an address that you control, since -/// you could otherwise interfere with the operation of other synchronization -/// primitives. -/// -/// The `callback` function is called while the queue is locked and must not -/// panic or call into any function in `parking_lot`. -#[inline] -pub unsafe fn unpark_one(key: usize, callback: C) -> UnparkResult -where - C: FnOnce(UnparkResult) -> UnparkToken, -{ - let mut c = Some(callback); - unpark_one_internal(key, &mut |result| c.take().unchecked_unwrap()(result)) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_one_internal( - key: usize, - callback: &mut FnMut(UnparkResult) -> UnparkToken, -) -> UnparkResult { - // Lock the bucket for the given key - let bucket = lock_bucket(key); - - // Find a thread with a matching key and remove it from the queue - let mut link = &bucket.queue_head; - let mut current = bucket.queue_head.get(); - let mut previous = ptr::null(); - let mut result = UnparkResult { - unparked_threads: 0, - have_more_threads: false, - be_fair: false, - }; - while !current.is_null() { - if (*current).key.load(Ordering::Relaxed) == key { - // Remove the thread from the queue - let next = (*current).next_in_queue.get(); - link.set(next); - if bucket.queue_tail.get() == current { - bucket.queue_tail.set(previous); - } else { - // Scan the rest of the queue to see if there are any other - // entries with the given key. - let mut scan = next; - while !scan.is_null() { - if (*scan).key.load(Ordering::Relaxed) == key { - result.have_more_threads = true; - break; - } - scan = (*scan).next_in_queue.get(); - } - } - - // Invoke the callback before waking up the thread - result.unparked_threads = 1; - result.be_fair = (*bucket.fair_timeout.get()).should_timeout(); - let token = callback(result); - - // Set the token for the target thread - (*current).unpark_token.set(token); - - // This is a bit tricky: we first lock the ThreadParker to prevent - // the thread from exiting and freeing its ThreadData if its wait - // times out. Then we unlock the queue since we don't want to keep - // the queue locked while we perform a system call. Finally we wake - // up the parked thread. - let handle = (*current).parker.unpark_lock(); - bucket.mutex.unlock(); - handle.unpark(); - - return result; - } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - } - - // No threads with a matching key were found in the bucket - callback(result); - bucket.mutex.unlock(); - result -} - -/// Unparks all threads in the queue associated with the given key. -/// -/// The given `UnparkToken` is passed to all unparked threads. -/// -/// This function returns the number of threads that were unparked. -/// -/// # Safety -/// -/// You should only call this function with an address that you control, since -/// you could otherwise interfere with the operation of other synchronization -/// primitives. -pub unsafe fn unpark_all(key: usize, unpark_token: UnparkToken) -> usize { - // Lock the bucket for the given key - let bucket = lock_bucket(key); - - // Remove all threads with the given key in the bucket - let mut link = &bucket.queue_head; - let mut current = bucket.queue_head.get(); - let mut previous = ptr::null(); - let mut threads = SmallVec::<[_; 8]>::new(); - while !current.is_null() { - if (*current).key.load(Ordering::Relaxed) == key { - // Remove the thread from the queue - let next = (*current).next_in_queue.get(); - link.set(next); - if bucket.queue_tail.get() == current { - bucket.queue_tail.set(previous); - } - - // Set the token for the target thread - (*current).unpark_token.set(unpark_token); - - // Don't wake up threads while holding the queue lock. See comment - // in unpark_one. For now just record which threads we need to wake - // up. - threads.push((*current).parker.unpark_lock()); - current = next; - } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - } - - // Unlock the bucket - bucket.mutex.unlock(); - - // Now that we are outside the lock, wake up all the threads that we removed - // from the queue. - let num_threads = threads.len(); - for handle in threads.into_iter() { - handle.unpark(); - } - - num_threads -} - -/// Removes all threads from the queue associated with `key_from`, optionally -/// unparks the first one and requeues the rest onto the queue associated with -/// `key_to`. -/// -/// The `validate` function is called while both queues are locked and can abort -/// the operation by returning `RequeueOp::Abort`. It can also choose to -/// unpark the first thread in the source queue while moving the rest by -/// returning `RequeueOp::UnparkFirstRequeueRest`. Returning -/// `RequeueOp::RequeueAll` will move all threads to the destination queue. -/// -/// The `callback` function is also called while both queues are locked. It is -/// passed the `RequeueOp` returned by `validate` and an `UnparkResult` -/// indicating whether a thread was unparked and whether there are threads still -/// parked in the new queue. This `UnparkResult` value is also returned by -/// `unpark_requeue`. -/// -/// The `callback` function should return an `UnparkToken` value which will be -/// passed to the thread that is unparked. If no thread is unparked then the -/// returned value is ignored. -/// -/// # Safety -/// -/// You should only call this function with an address that you control, since -/// you could otherwise interfere with the operation of other synchronization -/// primitives. -/// -/// The `validate` and `callback` functions are called while the queue is locked -/// and must not panic or call into any function in `parking_lot`. -#[inline] -pub unsafe fn unpark_requeue( - key_from: usize, - key_to: usize, - validate: V, - callback: C, -) -> UnparkResult -where - V: FnOnce() -> RequeueOp, - C: FnOnce(RequeueOp, UnparkResult) -> UnparkToken, -{ - let mut v = Some(validate); - let mut c = Some(callback); - unpark_requeue_internal( - key_from, - key_to, - &mut || v.take().unchecked_unwrap()(), - &mut |op, r| c.take().unchecked_unwrap()(op, r), - ) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_requeue_internal( - key_from: usize, - key_to: usize, - validate: &mut FnMut() -> RequeueOp, - callback: &mut FnMut(RequeueOp, UnparkResult) -> UnparkToken, -) -> UnparkResult { - // Lock the two buckets for the given key - let (bucket_from, bucket_to) = lock_bucket_pair(key_from, key_to); - - // If the validation function fails, just return - let mut result = UnparkResult { - unparked_threads: 0, - have_more_threads: false, - be_fair: false, - }; - let op = validate(); - if op == RequeueOp::Abort { - unlock_bucket_pair(bucket_from, bucket_to); - return result; - } - - // Remove all threads with the given key in the source bucket - let mut link = &bucket_from.queue_head; - let mut current = bucket_from.queue_head.get(); - let mut previous = ptr::null(); - let mut requeue_threads: *const ThreadData = ptr::null(); - let mut requeue_threads_tail: *const ThreadData = ptr::null(); - let mut wakeup_thread = None; - while !current.is_null() { - if (*current).key.load(Ordering::Relaxed) == key_from { - // Remove the thread from the queue - let next = (*current).next_in_queue.get(); - link.set(next); - if bucket_from.queue_tail.get() == current { - bucket_from.queue_tail.set(previous); - } - - // Prepare the first thread for wakeup and requeue the rest. - if op == RequeueOp::UnparkOneRequeueRest && wakeup_thread.is_none() { - wakeup_thread = Some(current); - result.unparked_threads = 1; - } else { - if !requeue_threads.is_null() { - (*requeue_threads_tail).next_in_queue.set(current); - } else { - requeue_threads = current; - } - requeue_threads_tail = current; - (*current).key.store(key_to, Ordering::Relaxed); - result.have_more_threads = true; - } - current = next; - } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - } - - // Add the requeued threads to the destination bucket - if !requeue_threads.is_null() { - (*requeue_threads_tail).next_in_queue.set(ptr::null()); - if !bucket_to.queue_head.get().is_null() { - (*bucket_to.queue_tail.get()) - .next_in_queue - .set(requeue_threads); - } else { - bucket_to.queue_head.set(requeue_threads); - } - bucket_to.queue_tail.set(requeue_threads_tail); - } - - // Invoke the callback before waking up the thread - if result.unparked_threads != 0 { - result.be_fair = (*bucket_from.fair_timeout.get()).should_timeout(); - } - let token = callback(op, result); - - // See comment in unpark_one for why we mess with the locking - if let Some(wakeup_thread) = wakeup_thread { - (*wakeup_thread).unpark_token.set(token); - let handle = (*wakeup_thread).parker.unpark_lock(); - unlock_bucket_pair(bucket_from, bucket_to); - handle.unpark(); - } else { - unlock_bucket_pair(bucket_from, bucket_to); - } - - result -} - -/// Unparks a number of threads from the front of the queue associated with -/// `key` depending on the results of a filter function which inspects the -/// `ParkToken` associated with each thread. -/// -/// The `filter` function is called for each thread in the queue or until -/// `FilterOp::Stop` is returned. This function is passed the `ParkToken` -/// associated with a particular thread, which is unparked if `FilterOp::Unpark` -/// is returned. -/// -/// The `callback` function is also called while both queues are locked. It is -/// passed an `UnparkResult` indicating the number of threads that were unparked -/// and whether there are still parked threads in the queue. This `UnparkResult` -/// value is also returned by `unpark_filter`. -/// -/// The `callback` function should return an `UnparkToken` value which will be -/// passed to all threads that are unparked. If no thread is unparked then the -/// returned value is ignored. -/// -/// # Safety -/// -/// You should only call this function with an address that you control, since -/// you could otherwise interfere with the operation of other synchronization -/// primitives. -/// -/// The `filter` and `callback` functions are called while the queue is locked -/// and must not panic or call into any function in `parking_lot`. -#[inline] -pub unsafe fn unpark_filter(key: usize, mut filter: F, callback: C) -> UnparkResult -where - F: FnMut(ParkToken) -> FilterOp, - C: FnOnce(UnparkResult) -> UnparkToken, -{ - let mut c = Some(callback); - unpark_filter_internal(key, &mut filter, &mut |r| c.take().unchecked_unwrap()(r)) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_filter_internal( - key: usize, - filter: &mut FnMut(ParkToken) -> FilterOp, - callback: &mut FnMut(UnparkResult) -> UnparkToken, -) -> UnparkResult { - // Lock the bucket for the given key - let bucket = lock_bucket(key); - - // Go through the queue looking for threads with a matching key - let mut link = &bucket.queue_head; - let mut current = bucket.queue_head.get(); - let mut previous = ptr::null(); - let mut threads = SmallVec::<[_; 8]>::new(); - let mut result = UnparkResult { - unparked_threads: 0, - have_more_threads: false, - be_fair: false, - }; - while !current.is_null() { - if (*current).key.load(Ordering::Relaxed) == key { - // Call the filter function with the thread's ParkToken - let next = (*current).next_in_queue.get(); - match filter((*current).park_token.get()) { - FilterOp::Unpark => { - // Remove the thread from the queue - link.set(next); - if bucket.queue_tail.get() == current { - bucket.queue_tail.set(previous); - } - - // Add the thread to our list of threads to unpark - threads.push((current, None)); - - current = next; - } - FilterOp::Skip => { - result.have_more_threads = true; - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - FilterOp::Stop => { - result.have_more_threads = true; - break; - } - } - } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); - } - } - - // Invoke the callback before waking up the threads - result.unparked_threads = threads.len(); - if result.unparked_threads != 0 { - result.be_fair = (*bucket.fair_timeout.get()).should_timeout(); - } - let token = callback(result); - - // Pass the token to all threads that are going to be unparked and prepare - // them for unparking. - for t in threads.iter_mut() { - (*t.0).unpark_token.set(token); - t.1 = Some((*t.0).parker.unpark_lock()); - } - - bucket.mutex.unlock(); - - // Now that we are outside the lock, wake up all the threads that we removed - // from the queue. - for (_, handle) in threads.into_iter() { - handle.unchecked_unwrap().unpark(); - } - - result -} - -/// \[Experimental\] Deadlock detection -/// -/// Enabled via the `deadlock_detection` feature flag. -pub mod deadlock { - #[cfg(feature = "deadlock_detection")] - use super::deadlock_impl; - - #[cfg(feature = "deadlock_detection")] - pub(super) use super::deadlock_impl::DeadlockData; - - #[cfg(not(feature = "deadlock_detection"))] - pub(super) struct DeadlockData {} - - #[cfg(not(feature = "deadlock_detection"))] - impl DeadlockData { - pub(super) fn new() -> Self { - DeadlockData {} - } - } - - /// Acquire a resource identified by key in the deadlock detector - /// Noop if deadlock_detection feature isn't enabled. - /// Note: Call after the resource is acquired - #[inline] - pub unsafe fn acquire_resource(_key: usize) { - #[cfg(feature = "deadlock_detection")] - deadlock_impl::acquire_resource(_key); - } - - /// Release a resource identified by key in the deadlock detector. - /// Noop if deadlock_detection feature isn't enabled. - /// Note: Call before the resource is released - /// # Panics - /// Panics if the resource was already released or wasn't acquired in this thread. - #[inline] - pub unsafe fn release_resource(_key: usize) { - #[cfg(feature = "deadlock_detection")] - deadlock_impl::release_resource(_key); - } - - /// Returns all deadlocks detected *since* the last call. - /// Each cycle consist of a vector of `DeadlockedThread`. - #[cfg(feature = "deadlock_detection")] - #[inline] - pub fn check_deadlock() -> Vec> { - deadlock_impl::check_deadlock() - } - - #[inline] - pub(super) unsafe fn on_unpark(_td: &super::ThreadData) { - #[cfg(feature = "deadlock_detection")] - deadlock_impl::on_unpark(_td); - } -} - -#[cfg(feature = "deadlock_detection")] -mod deadlock_impl { - use super::{get_hashtable, get_thread_data, lock_bucket, ThreadData, NUM_THREADS}; - use backtrace::Backtrace; - use petgraph; - use petgraph::graphmap::DiGraphMap; - use std::cell::{Cell, UnsafeCell}; - use std::collections::HashSet; - use std::sync::atomic::Ordering; - use std::sync::mpsc; - use thread_id; - - /// Representation of a deadlocked thread - pub struct DeadlockedThread { - thread_id: usize, - backtrace: Backtrace, - } - - impl DeadlockedThread { - /// The system thread id - pub fn thread_id(&self) -> usize { - self.thread_id - } - - /// The thread backtrace - pub fn backtrace(&self) -> &Backtrace { - &self.backtrace - } - } - - pub struct DeadlockData { - // Currently owned resources (keys) - resources: UnsafeCell>, - - // Set when there's a pending callstack request - deadlocked: Cell, - - // Sender used to report the backtrace - backtrace_sender: UnsafeCell>>, - - // System thread id - thread_id: usize, - } - - impl DeadlockData { - pub fn new() -> Self { - DeadlockData { - resources: UnsafeCell::new(Vec::new()), - deadlocked: Cell::new(false), - backtrace_sender: UnsafeCell::new(None), - thread_id: thread_id::get(), - } - } - } - - pub(super) unsafe fn on_unpark(td: &ThreadData) { - if td.deadlock_data.deadlocked.get() { - let sender = (*td.deadlock_data.backtrace_sender.get()).take().unwrap(); - sender - .send(DeadlockedThread { - thread_id: td.deadlock_data.thread_id, - backtrace: Backtrace::new(), - }).unwrap(); - // make sure to close this sender - drop(sender); - - // park until the end of the time - td.parker.prepare_park(); - td.parker.park(); - unreachable!("unparked deadlocked thread!"); - } - } - - pub unsafe fn acquire_resource(key: usize) { - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - (*thread_data.deadlock_data.resources.get()).push(key); - } - - pub unsafe fn release_resource(key: usize) { - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - let resources = &mut (*thread_data.deadlock_data.resources.get()); - match resources.iter().rposition(|x| *x == key) { - Some(p) => resources.swap_remove(p), - None => panic!("key {} not found in thread resources", key), - }; - } - - pub fn check_deadlock() -> Vec> { - unsafe { - // fast pass - if check_wait_graph_fast() { - // double check - check_wait_graph_slow() - } else { - Vec::new() - } - } - } - - // Simple algorithm that builds a wait graph f the threads and the resources, - // then checks for the presence of cycles (deadlocks). - // This variant isn't precise as it doesn't lock the entire table before checking - unsafe fn check_wait_graph_fast() -> bool { - let table = get_hashtable(); - let thread_count = NUM_THREADS.load(Ordering::Relaxed); - let mut graph = DiGraphMap::::with_capacity(thread_count * 2, thread_count * 2); - - for b in &(*table).entries[..] { - b.mutex.lock(); - let mut current = b.queue_head.get(); - while !current.is_null() { - if !(*current).parked_with_timeout.get() - && !(*current).deadlock_data.deadlocked.get() - { - // .resources are waiting for their owner - for &resource in &(*(*current).deadlock_data.resources.get()) { - graph.add_edge(resource, current as usize, ()); - } - // owner waits for resource .key - graph.add_edge(current as usize, (*current).key.load(Ordering::Relaxed), ()); - } - current = (*current).next_in_queue.get(); - } - b.mutex.unlock(); - } - - petgraph::algo::is_cyclic_directed(&graph) - } - - #[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] - enum WaitGraphNode { - Thread(*const ThreadData), - Resource(usize), - } - - use self::WaitGraphNode::*; - - // Contrary to the _fast variant this locks the entrie table before looking for cycles. - // Returns all detected thread wait cycles. - // Note that once a cycle is reported it's never reported again. - unsafe fn check_wait_graph_slow() -> Vec> { - let mut table = get_hashtable(); - loop { - // Lock all buckets in the old table - for b in &(*table).entries[..] { - b.mutex.lock(); - } - - // Now check if our table is still the latest one. Another thread could - // have grown the hash table between us getting and locking the hash table. - let new_table = get_hashtable(); - if new_table == table { - break; - } - - // Unlock buckets and try again - for b in &(*table).entries[..] { - b.mutex.unlock(); - } - - table = new_table; - } - - let thread_count = NUM_THREADS.load(Ordering::Relaxed); - let mut graph = - DiGraphMap::::with_capacity(thread_count * 2, thread_count * 2); - - for b in &(*table).entries[..] { - let mut current = b.queue_head.get(); - while !current.is_null() { - if !(*current).parked_with_timeout.get() - && !(*current).deadlock_data.deadlocked.get() - { - // .resources are waiting for their owner - for &resource in &(*(*current).deadlock_data.resources.get()) { - graph.add_edge(Resource(resource), Thread(current), ()); - } - // owner waits for resource .key - graph.add_edge( - Thread(current), - Resource((*current).key.load(Ordering::Relaxed)), - (), - ); - } - current = (*current).next_in_queue.get(); - } - } - - for b in &(*table).entries[..] { - b.mutex.unlock(); - } - - // find cycles - let cycles = graph_cycles(&graph); - - let mut results = Vec::with_capacity(cycles.len()); - - for cycle in cycles { - let (sender, receiver) = mpsc::channel(); - for td in cycle { - let bucket = lock_bucket((*td).key.load(Ordering::Relaxed)); - (*td).deadlock_data.deadlocked.set(true); - *(*td).deadlock_data.backtrace_sender.get() = Some(sender.clone()); - let handle = (*td).parker.unpark_lock(); - bucket.mutex.unlock(); - // unpark the deadlocked thread! - // on unpark it'll notice the deadlocked flag and report back - handle.unpark(); - } - // make sure to drop our sender before collecting results - drop(sender); - results.push(receiver.iter().collect()); - } - - results - } - - // normalize a cycle to start with the "smallest" node - fn normalize_cycle(input: &[T]) -> Vec { - let min_pos = input - .iter() - .enumerate() - .min_by_key(|&(_, &t)| t) - .map(|(p, _)| p) - .unwrap_or(0); - input - .iter() - .cycle() - .skip(min_pos) - .take(input.len()) - .cloned() - .collect() - } - - // returns all thread cycles in the wait graph - fn graph_cycles(g: &DiGraphMap) -> Vec> { - use petgraph::visit::depth_first_search; - use petgraph::visit::DfsEvent; - use petgraph::visit::NodeIndexable; - - let mut cycles = HashSet::new(); - let mut path = Vec::with_capacity(g.node_bound()); - // start from threads to get the correct threads cycle - let threads = g - .nodes() - .filter(|n| if let &Thread(_) = n { true } else { false }); - - depth_first_search(g, threads, |e| match e { - DfsEvent::Discover(Thread(n), _) => path.push(n), - DfsEvent::Finish(Thread(_), _) => { - path.pop(); - } - DfsEvent::BackEdge(_, Thread(n)) => { - let from = path.iter().rposition(|&i| i == n).unwrap(); - cycles.insert(normalize_cycle(&path[from..])); - } - _ => (), - }); - - cycles.iter().cloned().collect() - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/spinwait.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/spinwait.rs deleted file mode 100644 index 4185026..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/spinwait.rs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -#[cfg(unix)] -use libc; -use std::sync::atomic::spin_loop_hint; -#[cfg(not(any(windows, unix)))] -use std::thread; -#[cfg(windows)] -use winapi; - -// Yields the rest of the current timeslice to the OS -#[cfg(windows)] -#[inline] -fn thread_yield() { - // Note that this is manually defined here rather than using the definition - // through `winapi`. The `winapi` definition comes from the `synchapi` - // header which enables the "synchronization.lib" library. It turns out, - // however that `Sleep` comes from `kernel32.dll` so this activation isn't - // necessary. - // - // This was originally identified in rust-lang/rust where on MinGW the - // libsynchronization.a library pulls in a dependency on a newer DLL not - // present in older versions of Windows. (see rust-lang/rust#49438) - // - // This is a bit of a hack for now and ideally we'd fix MinGW's own import - // libraries, but that'll probably take a lot longer than patching this here - // and avoiding the `synchapi` feature entirely. - extern "system" { - fn Sleep(a: winapi::shared::minwindef::DWORD); - } - unsafe { - // We don't use SwitchToThread here because it doesn't consider all - // threads in the system and the thread we are waiting for may not get - // selected. - Sleep(0); - } -} -#[cfg(unix)] -#[inline] -fn thread_yield() { - unsafe { - libc::sched_yield(); - } -} -#[cfg(not(any(windows, unix)))] -#[inline] -fn thread_yield() { - thread::yield_now(); -} - -// Wastes some CPU time for the given number of iterations, -// using a hint to indicate to the CPU that we are spinning. -#[inline] -fn cpu_relax(iterations: u32) { - for _ in 0..iterations { - spin_loop_hint() - } -} - -/// A counter used to perform exponential backoff in spin loops. -pub struct SpinWait { - counter: u32, -} - -impl SpinWait { - /// Creates a new `SpinWait`. - #[inline] - pub fn new() -> SpinWait { - SpinWait { counter: 0 } - } - - /// Resets a `SpinWait` to its initial state. - #[inline] - pub fn reset(&mut self) { - self.counter = 0; - } - - /// Spins until the sleep threshold has been reached. - /// - /// This function returns whether the sleep threshold has been reached, at - /// which point further spinning has diminishing returns and the thread - /// should be parked instead. - /// - /// The spin strategy will initially use a CPU-bound loop but will fall back - /// to yielding the CPU to the OS after a few iterations. - #[inline] - pub fn spin(&mut self) -> bool { - if self.counter >= 10 { - return false; - } - self.counter += 1; - if self.counter <= 3 { - cpu_relax(1 << self.counter); - } else { - thread_yield(); - } - true - } - - /// Spins without yielding the thread to the OS. - /// - /// Instead, the backoff is simply capped at a maximum value. This can be - /// used to improve throughput in `compare_exchange` loops that have high - /// contention. - #[inline] - pub fn spin_no_yield(&mut self) { - self.counter += 1; - if self.counter > 10 { - self.counter = 10; - } - cpu_relax(1 << self.counter); - } -} - -impl Default for SpinWait { - #[inline] - fn default() -> SpinWait { - SpinWait::new() - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/generic.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/generic.rs deleted file mode 100644 index d06406a..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/generic.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::cell::Cell; -use std::sync::{Condvar, Mutex, MutexGuard}; -use std::time::Instant; - -// Helper type for putting a thread to sleep until some other thread wakes it up -pub struct ThreadParker { - should_park: Cell, - mutex: Mutex<()>, - condvar: Condvar, -} - -impl ThreadParker { - pub fn new() -> ThreadParker { - ThreadParker { - should_park: Cell::new(false), - mutex: Mutex::new(()), - condvar: Condvar::new(), - } - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { - self.should_park.set(true); - } - - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { - // We need to grab the mutex here because another thread may be - // concurrently executing UnparkHandle::unpark, which is done without - // holding the queue lock. - let _lock = self.mutex.lock().unwrap(); - self.should_park.get() - } - - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { - let mut lock = self.mutex.lock().unwrap(); - while self.should_park.get() { - lock = self.condvar.wait(lock).unwrap(); - } - } - - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { - let mut lock = self.mutex.lock().unwrap(); - while self.should_park.get() { - let now = Instant::now(); - if timeout <= now { - return false; - } - let (new_lock, _) = self.condvar.wait_timeout(lock, timeout - now).unwrap(); - lock = new_lock; - } - true - } - - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { - UnparkHandle { - thread_parker: self, - _guard: self.mutex.lock().unwrap(), - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle<'a> { - thread_parker: *const ThreadParker, - _guard: MutexGuard<'a, ()>, -} - -impl<'a> UnparkHandle<'a> { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - (*self.thread_parker).should_park.set(false); - - // We notify while holding the lock here to avoid races with the target - // thread. In particular, the thread could exit after we unlock the - // mutex, which would make the condvar access invalid memory. - (*self.thread_parker).condvar.notify_one(); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/linux.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/linux.rs deleted file mode 100644 index 4a13d73..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/linux.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use libc; -use std::sync::atomic::{AtomicI32, Ordering}; -use std::time::Instant; - -const FUTEX_WAIT: i32 = 0; -const FUTEX_WAKE: i32 = 1; -const FUTEX_PRIVATE: i32 = 128; - -// x32 Linux uses a non-standard type for tv_nsec in timespec. -// See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 -#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] -#[allow(non_camel_case_types)] -type tv_nsec_t = i64; -#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] -#[allow(non_camel_case_types)] -type tv_nsec_t = libc::c_long; - -// Helper type for putting a thread to sleep until some other thread wakes it up -pub struct ThreadParker { - futex: AtomicI32, -} - -impl ThreadParker { - pub fn new() -> ThreadParker { - ThreadParker { - futex: AtomicI32::new(0), - } - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { - self.futex.store(1, Ordering::Relaxed); - } - - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { - self.futex.load(Ordering::Relaxed) != 0 - } - - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { - while self.futex.load(Ordering::Acquire) != 0 { - let r = libc::syscall( - libc::SYS_futex, - &self.futex, - FUTEX_WAIT | FUTEX_PRIVATE, - 1, - 0, - ); - debug_assert!(r == 0 || r == -1); - if r == -1 { - debug_assert!( - *libc::__errno_location() == libc::EINTR - || *libc::__errno_location() == libc::EAGAIN - ); - } - } - } - - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { - while self.futex.load(Ordering::Acquire) != 0 { - let now = Instant::now(); - if timeout <= now { - return false; - } - let diff = timeout - now; - if diff.as_secs() as libc::time_t as u64 != diff.as_secs() { - // Timeout overflowed, just sleep indefinitely - self.park(); - return true; - } - let ts = libc::timespec { - tv_sec: diff.as_secs() as libc::time_t, - tv_nsec: diff.subsec_nanos() as tv_nsec_t, - }; - let r = libc::syscall( - libc::SYS_futex, - &self.futex, - FUTEX_WAIT | FUTEX_PRIVATE, - 1, - &ts, - ); - debug_assert!(r == 0 || r == -1); - if r == -1 { - debug_assert!( - *libc::__errno_location() == libc::EINTR - || *libc::__errno_location() == libc::EAGAIN - || *libc::__errno_location() == libc::ETIMEDOUT - ); - } - } - true - } - - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { - // We don't need to lock anything, just clear the state - self.futex.store(0, Ordering::Release); - - UnparkHandle { futex: &self.futex } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle { - futex: *const AtomicI32, -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - // The thread data may have been freed at this point, but it doesn't - // matter since the syscall will just return EFAULT in that case. - let r = libc::syscall(libc::SYS_futex, self.futex, FUTEX_WAKE | FUTEX_PRIVATE, 1); - debug_assert!(r == 0 || r == 1 || r == -1); - if r == -1 { - debug_assert_eq!(*libc::__errno_location(), libc::EFAULT); - } - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/keyed_event.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/keyed_event.rs deleted file mode 100644 index 0e32fce..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/keyed_event.rs +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::mem; -use std::ptr; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -use winapi::shared::minwindef::{TRUE, ULONG}; -use winapi::shared::ntdef::NTSTATUS; -use winapi::shared::ntstatus::{STATUS_SUCCESS, STATUS_TIMEOUT}; -use winapi::um::handleapi::CloseHandle; -use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress}; -use winapi::um::winnt::{ACCESS_MASK, GENERIC_READ, GENERIC_WRITE, LPCSTR}; -use winapi::um::winnt::{BOOLEAN, HANDLE, LARGE_INTEGER, PHANDLE, PLARGE_INTEGER, PVOID}; - -const STATE_UNPARKED: usize = 0; -const STATE_PARKED: usize = 1; -const STATE_TIMED_OUT: usize = 2; - -#[allow(non_snake_case)] -pub struct KeyedEvent { - handle: HANDLE, - NtReleaseKeyedEvent: extern "system" fn( - EventHandle: HANDLE, - Key: PVOID, - Alertable: BOOLEAN, - Timeout: PLARGE_INTEGER, - ) -> NTSTATUS, - NtWaitForKeyedEvent: extern "system" fn( - EventHandle: HANDLE, - Key: PVOID, - Alertable: BOOLEAN, - Timeout: PLARGE_INTEGER, - ) -> NTSTATUS, -} - -impl KeyedEvent { - unsafe fn wait_for(&self, key: PVOID, timeout: PLARGE_INTEGER) -> NTSTATUS { - (self.NtWaitForKeyedEvent)(self.handle, key, 0, timeout) - } - - unsafe fn release(&self, key: PVOID) -> NTSTATUS { - (self.NtReleaseKeyedEvent)(self.handle, key, 0, ptr::null_mut()) - } - - #[allow(non_snake_case)] - pub unsafe fn create() -> Option { - let ntdll = GetModuleHandleA(b"ntdll.dll\0".as_ptr() as LPCSTR); - if ntdll.is_null() { - return None; - } - - let NtCreateKeyedEvent = GetProcAddress(ntdll, b"NtCreateKeyedEvent\0".as_ptr() as LPCSTR); - if NtCreateKeyedEvent.is_null() { - return None; - } - let NtReleaseKeyedEvent = - GetProcAddress(ntdll, b"NtReleaseKeyedEvent\0".as_ptr() as LPCSTR); - if NtReleaseKeyedEvent.is_null() { - return None; - } - let NtWaitForKeyedEvent = - GetProcAddress(ntdll, b"NtWaitForKeyedEvent\0".as_ptr() as LPCSTR); - if NtWaitForKeyedEvent.is_null() { - return None; - } - - let NtCreateKeyedEvent: extern "system" fn( - KeyedEventHandle: PHANDLE, - DesiredAccess: ACCESS_MASK, - ObjectAttributes: PVOID, - Flags: ULONG, - ) -> NTSTATUS = mem::transmute(NtCreateKeyedEvent); - let mut handle = mem::uninitialized(); - let status = NtCreateKeyedEvent( - &mut handle, - GENERIC_READ | GENERIC_WRITE, - ptr::null_mut(), - 0, - ); - if status != STATUS_SUCCESS { - return None; - } - - Some(KeyedEvent { - handle, - NtReleaseKeyedEvent: mem::transmute(NtReleaseKeyedEvent), - NtWaitForKeyedEvent: mem::transmute(NtWaitForKeyedEvent), - }) - } - - pub unsafe fn prepare_park(&'static self, key: &AtomicUsize) { - key.store(STATE_PARKED, Ordering::Relaxed); - } - - pub unsafe fn timed_out(&'static self, key: &AtomicUsize) -> bool { - key.load(Ordering::Relaxed) == STATE_TIMED_OUT - } - - pub unsafe fn park(&'static self, key: &AtomicUsize) { - let status = self.wait_for(key as *const _ as PVOID, ptr::null_mut()); - debug_assert_eq!(status, STATUS_SUCCESS); - } - - pub unsafe fn park_until(&'static self, key: &AtomicUsize, timeout: Instant) -> bool { - let now = Instant::now(); - if timeout <= now { - // If another thread unparked us, we need to call - // NtWaitForKeyedEvent otherwise that thread will stay stuck at - // NtReleaseKeyedEvent. - if key.swap(STATE_TIMED_OUT, Ordering::Relaxed) == STATE_UNPARKED { - self.park(key); - return true; - } - return false; - } - - // NT uses a timeout in units of 100ns. We use a negative value to - // indicate a relative timeout based on a monotonic clock. - let mut nt_timeout: LARGE_INTEGER = mem::zeroed(); - let diff = timeout - now; - let value = (diff.as_secs() as i64) - .checked_mul(-10000000) - .and_then(|x| x.checked_sub((diff.subsec_nanos() as i64 + 99) / 100)); - - match value { - Some(x) => *nt_timeout.QuadPart_mut() = x, - None => { - // Timeout overflowed, just sleep indefinitely - self.park(key); - return true; - } - }; - - let status = self.wait_for(key as *const _ as PVOID, &mut nt_timeout); - if status == STATUS_SUCCESS { - return true; - } - debug_assert_eq!(status, STATUS_TIMEOUT); - - // If another thread unparked us, we need to call NtWaitForKeyedEvent - // otherwise that thread will stay stuck at NtReleaseKeyedEvent. - if key.swap(STATE_TIMED_OUT, Ordering::Relaxed) == STATE_UNPARKED { - self.park(key); - return true; - } - false - } - - pub unsafe fn unpark_lock(&'static self, key: &AtomicUsize) -> UnparkHandle { - // If the state was STATE_PARKED then we need to wake up the thread - if key.swap(STATE_UNPARKED, Ordering::Relaxed) == STATE_PARKED { - UnparkHandle { - key: key, - keyed_event: self, - } - } else { - UnparkHandle { - key: ptr::null(), - keyed_event: self, - } - } - } -} - -impl Drop for KeyedEvent { - fn drop(&mut self) { - unsafe { - let ok = CloseHandle(self.handle); - debug_assert_eq!(ok, TRUE); - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle { - key: *const AtomicUsize, - keyed_event: &'static KeyedEvent, -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - if !self.key.is_null() { - let status = self.keyed_event.release(self.key as PVOID); - debug_assert_eq!(status, STATUS_SUCCESS); - } - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/waitaddress.rs b/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/waitaddress.rs deleted file mode 100644 index 1d9fca8..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/waitaddress.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -use winapi::shared::basetsd::SIZE_T; -use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE}; -use winapi::shared::winerror::ERROR_TIMEOUT; -use winapi::um::errhandlingapi::GetLastError; -use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress}; -use winapi::um::winbase::INFINITE; -use winapi::um::winnt::{LPCSTR, PVOID}; - -#[allow(non_snake_case)] -pub struct WaitAddress { - WaitOnAddress: extern "system" fn( - Address: PVOID, - CompareAddress: PVOID, - AddressSize: SIZE_T, - dwMilliseconds: DWORD, - ) -> BOOL, - WakeByAddressSingle: extern "system" fn(Address: PVOID), -} - -impl WaitAddress { - #[allow(non_snake_case)] - pub unsafe fn create() -> Option { - // MSDN claims that that WaitOnAddress and WakeByAddressSingle are - // located in kernel32.dll, but they are lying... - let synch_dll = GetModuleHandleA(b"api-ms-win-core-synch-l1-2-0.dll\0".as_ptr() as LPCSTR); - if synch_dll.is_null() { - return None; - } - - let WaitOnAddress = GetProcAddress(synch_dll, b"WaitOnAddress\0".as_ptr() as LPCSTR); - if WaitOnAddress.is_null() { - return None; - } - let WakeByAddressSingle = - GetProcAddress(synch_dll, b"WakeByAddressSingle\0".as_ptr() as LPCSTR); - if WakeByAddressSingle.is_null() { - return None; - } - Some(WaitAddress { - WaitOnAddress: mem::transmute(WaitOnAddress), - WakeByAddressSingle: mem::transmute(WakeByAddressSingle), - }) - } - - pub unsafe fn prepare_park(&'static self, key: &AtomicUsize) { - key.store(1, Ordering::Relaxed); - } - - pub unsafe fn timed_out(&'static self, key: &AtomicUsize) -> bool { - key.load(Ordering::Relaxed) != 0 - } - - pub unsafe fn park(&'static self, key: &AtomicUsize) { - while key.load(Ordering::Acquire) != 0 { - let cmp = 1usize; - let r = (self.WaitOnAddress)( - key as *const _ as PVOID, - &cmp as *const _ as PVOID, - mem::size_of::() as SIZE_T, - INFINITE, - ); - debug_assert!(r == TRUE); - } - } - - pub unsafe fn park_until(&'static self, key: &AtomicUsize, timeout: Instant) -> bool { - while key.load(Ordering::Acquire) != 0 { - let now = Instant::now(); - if timeout <= now { - return false; - } - let diff = timeout - now; - let timeout = diff - .as_secs() - .checked_mul(1000) - .and_then(|x| x.checked_add((diff.subsec_nanos() as u64 + 999999) / 1000000)) - .map(|ms| { - if ms > ::max_value() as u64 { - INFINITE - } else { - ms as DWORD - } - }).unwrap_or(INFINITE); - let cmp = 1usize; - let r = (self.WaitOnAddress)( - key as *const _ as PVOID, - &cmp as *const _ as PVOID, - mem::size_of::() as SIZE_T, - timeout, - ); - if r == FALSE { - debug_assert_eq!(GetLastError(), ERROR_TIMEOUT); - } - } - true - } - - pub unsafe fn unpark_lock(&'static self, key: &AtomicUsize) -> UnparkHandle { - // We don't need to lock anything, just clear the state - key.store(0, Ordering::Release); - - UnparkHandle { - key: key, - waitaddress: self, - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle { - key: *const AtomicUsize, - waitaddress: &'static WaitAddress, -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - (self.waitaddress.WakeByAddressSingle)(self.key as PVOID); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot_core-0.4.0/.cargo-checksum.json deleted file mode 100644 index 8cbf15c..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"b8af1f3d0946ea4db58f7fa34c19e38165eac9b070bb055e5888d55fa52e3007","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","build.rs":"b4ca69501aa539f2d9a50a3188e93d69eb5ad0c38d5cd194df361a3f2f9a8b92","src/lib.rs":"9d5d80460481b44b8d9048b7319be33ac989250960c61b7c4528c0431f9ad36c","src/parking_lot.rs":"70d621eed1e4a85d4e4f619d50fd11b12e3a4b7141d4400252d3ab071d665f8e","src/spinwait.rs":"45a0f2a57177bc9759c0c2167f758ee220fba7cd8bdf1fbcd9c2b962fef9a1e5","src/thread_parker/generic.rs":"985966b1bdc763ada6d1fee800d19dd92611da4f84cfeef2d82763ffd2a499c3","src/thread_parker/linux.rs":"c41d08ab333972b67f20443f474ed25a1f171db0f87e227df4bdc504f6f9d897","src/thread_parker/unix.rs":"6364bcfeacfb3189bcebeddfccef1b9843d3c59d6d0f046827e62b33bcee30dd","src/thread_parker/windows/keyed_event.rs":"83d4bace5d2f17993071de28043e94f3b9673c887e01c72653b6fd24db260634","src/thread_parker/windows/mod.rs":"f31eed53f3e402477d80a70a7c6d474c01ba4c9ad952bbe562509448cd3cc1ad","src/thread_parker/windows/waitaddress.rs":"1a6eee8ab9131c746089e78b0aab900f23a5ed8ee6f2e789b8ec4d2232153ab8","src/util.rs":"2d07c0c010a857790ae2ed6a1215eeed8af76859e076797ea1ba8dec82169e84","src/word_lock.rs":"c4d50c0d37e6dd92fb078c80f84dc5b5c83bdf46baad34ed35af8730a345a2b5"},"package":"94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/Cargo.toml b/third_party/cargo/vendor/parking_lot_core-0.4.0/Cargo.toml deleted file mode 100644 index 8a37925..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/Cargo.toml +++ /dev/null @@ -1,49 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "parking_lot_core" -version = "0.4.0" -authors = ["Amanieu d'Antras "] -description = "An advanced API for creating custom synchronization primitives." -keywords = ["mutex", "condvar", "rwlock", "once", "thread"] -categories = ["concurrency"] -license = "Apache-2.0/MIT" -repository = "https://github.com/Amanieu/parking_lot" -[dependencies.backtrace] -version = "0.3.2" -optional = true - -[dependencies.petgraph] -version = "0.4.5" -optional = true - -[dependencies.rand] -version = "0.6" - -[dependencies.smallvec] -version = "0.6" - -[dependencies.thread-id] -version = "3.2.0" -optional = true -[build-dependencies.rustc_version] -version = "0.2" - -[features] -deadlock_detection = ["petgraph", "thread-id", "backtrace"] -nightly = [] -[target."cfg(unix)".dependencies.libc] -version = "0.2.27" -[target."cfg(windows)".dependencies.winapi] -version = "0.3" -features = ["winnt", "ntstatus", "minwindef", "winerror", "winbase", "errhandlingapi", "handleapi"] diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-MIT b/third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-MIT deleted file mode 100644 index 40b8817..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2016 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/build.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/build.rs deleted file mode 100644 index 8d745ee..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/build.rs +++ /dev/null @@ -1,8 +0,0 @@ -extern crate rustc_version; -use rustc_version::{version, Version}; - -fn main() { - if version().unwrap() >= Version::parse("1.26.0").unwrap() { - println!("cargo:rustc-cfg=has_localkey_try_with"); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/lib.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/lib.rs deleted file mode 100644 index 338b63e..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/lib.rs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -//! This library exposes a low-level API for creating your own efficient -//! synchronization primitives. -//! -//! # The parking lot -//! -//! To keep synchronization primitives small, all thread queuing and suspending -//! functionality is offloaded to the *parking lot*. The idea behind this is based -//! on the Webkit [`WTF::ParkingLot`](https://webkit.org/blog/6161/locking-in-webkit/) -//! class, which essentially consists of a hash table mapping of lock addresses -//! to queues of parked (sleeping) threads. The Webkit parking lot was itself -//! inspired by Linux [futexes](http://man7.org/linux/man-pages/man2/futex.2.html), -//! but it is more powerful since it allows invoking callbacks while holding a -//! queue lock. -//! -//! There are two main operations that can be performed on the parking lot: -//! -//! - *Parking* refers to suspending the thread while simultaneously enqueuing it -//! on a queue keyed by some address. -//! - *Unparking* refers to dequeuing a thread from a queue keyed by some address -//! and resuming it. -//! -//! See the documentation of the individual functions for more details. -//! -//! # Building custom synchronization primitives -//! -//! Building custom synchronization primitives is very simple since the parking -//! lot takes care of all the hard parts for you. A simple example for a -//! custom primitive would be to integrate a `Mutex` inside another data type. -//! Since a mutex only requires 2 bits, it can share space with other data. -//! For example, one could create an `ArcMutex` type that combines the atomic -//! reference count and the two mutex bits in the same atomic word. - -#![warn(missing_docs)] -#![cfg_attr( - all(feature = "nightly", target_os = "linux"), - feature(integer_atomics) -)] - -extern crate rand; -extern crate smallvec; - -#[cfg(feature = "deadlock_detection")] -extern crate backtrace; -#[cfg(feature = "deadlock_detection")] -extern crate petgraph; -#[cfg(feature = "deadlock_detection")] -extern crate thread_id; - -#[cfg(unix)] -extern crate libc; - -#[cfg(windows)] -extern crate winapi; - -#[cfg(all(feature = "nightly", target_os = "linux"))] -#[path = "thread_parker/linux.rs"] -mod thread_parker; -#[cfg(all(unix, not(all(feature = "nightly", target_os = "linux"))))] -#[path = "thread_parker/unix.rs"] -mod thread_parker; -#[cfg(windows)] -#[path = "thread_parker/windows/mod.rs"] -mod thread_parker; -#[cfg(not(any(windows, unix)))] -#[path = "thread_parker/generic.rs"] -mod thread_parker; - -mod parking_lot; -mod spinwait; -mod util; -mod word_lock; - -pub use parking_lot::deadlock; -pub use parking_lot::{park, unpark_all, unpark_filter, unpark_one, unpark_requeue}; -pub use parking_lot::{FilterOp, ParkResult, ParkToken, RequeueOp, UnparkResult, UnparkToken}; -pub use parking_lot::{DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; -pub use spinwait::SpinWait; diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/generic.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/generic.rs deleted file mode 100644 index d06406a..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/generic.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::cell::Cell; -use std::sync::{Condvar, Mutex, MutexGuard}; -use std::time::Instant; - -// Helper type for putting a thread to sleep until some other thread wakes it up -pub struct ThreadParker { - should_park: Cell, - mutex: Mutex<()>, - condvar: Condvar, -} - -impl ThreadParker { - pub fn new() -> ThreadParker { - ThreadParker { - should_park: Cell::new(false), - mutex: Mutex::new(()), - condvar: Condvar::new(), - } - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { - self.should_park.set(true); - } - - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { - // We need to grab the mutex here because another thread may be - // concurrently executing UnparkHandle::unpark, which is done without - // holding the queue lock. - let _lock = self.mutex.lock().unwrap(); - self.should_park.get() - } - - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { - let mut lock = self.mutex.lock().unwrap(); - while self.should_park.get() { - lock = self.condvar.wait(lock).unwrap(); - } - } - - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { - let mut lock = self.mutex.lock().unwrap(); - while self.should_park.get() { - let now = Instant::now(); - if timeout <= now { - return false; - } - let (new_lock, _) = self.condvar.wait_timeout(lock, timeout - now).unwrap(); - lock = new_lock; - } - true - } - - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { - UnparkHandle { - thread_parker: self, - _guard: self.mutex.lock().unwrap(), - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle<'a> { - thread_parker: *const ThreadParker, - _guard: MutexGuard<'a, ()>, -} - -impl<'a> UnparkHandle<'a> { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - (*self.thread_parker).should_park.set(false); - - // We notify while holding the lock here to avoid races with the target - // thread. In particular, the thread could exit after we unlock the - // mutex, which would make the condvar access invalid memory. - (*self.thread_parker).condvar.notify_one(); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/unix.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/unix.rs deleted file mode 100644 index 169586b..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/unix.rs +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use libc; -use std::cell::{Cell, UnsafeCell}; -use std::mem; -#[cfg(any(target_os = "macos", target_os = "ios"))] -use std::ptr; -use std::time::{Duration, Instant}; - -// x32 Linux uses a non-standard type for tv_nsec in timespec. -// See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 -#[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] -#[allow(non_camel_case_types)] -type tv_nsec_t = i64; -#[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] -#[allow(non_camel_case_types)] -type tv_nsec_t = libc::c_long; - -// Helper type for putting a thread to sleep until some other thread wakes it up -pub struct ThreadParker { - should_park: Cell, - mutex: UnsafeCell, - condvar: UnsafeCell, - initialized: Cell, -} - -impl ThreadParker { - pub fn new() -> ThreadParker { - ThreadParker { - should_park: Cell::new(false), - mutex: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER), - condvar: UnsafeCell::new(libc::PTHREAD_COND_INITIALIZER), - initialized: Cell::new(false), - } - } - - // Initializes the condvar to use CLOCK_MONOTONIC instead of CLOCK_REALTIME. - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "android" - ))] - unsafe fn init(&self) {} - #[cfg(not(any( - target_os = "macos", - target_os = "ios", - target_os = "android" - )))] - unsafe fn init(&self) { - let mut attr: libc::pthread_condattr_t = mem::uninitialized(); - let r = libc::pthread_condattr_init(&mut attr); - debug_assert_eq!(r, 0); - let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC); - debug_assert_eq!(r, 0); - let r = libc::pthread_cond_init(self.condvar.get(), &attr); - debug_assert_eq!(r, 0); - let r = libc::pthread_condattr_destroy(&mut attr); - debug_assert_eq!(r, 0); - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { - self.should_park.set(true); - if !self.initialized.get() { - self.init(); - self.initialized.set(true); - } - } - - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { - // We need to grab the mutex here because another thread may be - // concurrently executing UnparkHandle::unpark, which is done without - // holding the queue lock. - let r = libc::pthread_mutex_lock(self.mutex.get()); - debug_assert_eq!(r, 0); - let should_park = self.should_park.get(); - let r = libc::pthread_mutex_unlock(self.mutex.get()); - debug_assert_eq!(r, 0); - should_park - } - - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { - let r = libc::pthread_mutex_lock(self.mutex.get()); - debug_assert_eq!(r, 0); - while self.should_park.get() { - let r = libc::pthread_cond_wait(self.condvar.get(), self.mutex.get()); - debug_assert_eq!(r, 0); - } - let r = libc::pthread_mutex_unlock(self.mutex.get()); - debug_assert_eq!(r, 0); - } - - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { - let r = libc::pthread_mutex_lock(self.mutex.get()); - debug_assert_eq!(r, 0); - while self.should_park.get() { - let now = Instant::now(); - if timeout <= now { - let r = libc::pthread_mutex_unlock(self.mutex.get()); - debug_assert_eq!(r, 0); - return false; - } - - if let Some(ts) = timeout_to_timespec(timeout - now) { - let r = libc::pthread_cond_timedwait(self.condvar.get(), self.mutex.get(), &ts); - if ts.tv_sec < 0 { - // On some systems, negative timeouts will return EINVAL. In - // that case we won't sleep and will just busy loop instead, - // which is the best we can do. - debug_assert!(r == 0 || r == libc::ETIMEDOUT || r == libc::EINVAL); - } else { - debug_assert!(r == 0 || r == libc::ETIMEDOUT); - } - } else { - // Timeout calculation overflowed, just sleep indefinitely - let r = libc::pthread_cond_wait(self.condvar.get(), self.mutex.get()); - debug_assert_eq!(r, 0); - } - } - let r = libc::pthread_mutex_unlock(self.mutex.get()); - debug_assert_eq!(r, 0); - true - } - - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { - let r = libc::pthread_mutex_lock(self.mutex.get()); - debug_assert_eq!(r, 0); - - UnparkHandle { - thread_parker: self, - } - } -} - -impl Drop for ThreadParker { - fn drop(&mut self) { - // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a - // mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER. - // Once it is used (locked/unlocked) or pthread_mutex_init() is called, - // this behaviour no longer occurs. The same applies to condvars. - unsafe { - let r = libc::pthread_mutex_destroy(self.mutex.get()); - if cfg!(target_os = "dragonfly") { - debug_assert!(r == 0 || r == libc::EINVAL); - } else { - debug_assert_eq!(r, 0); - } - let r = libc::pthread_cond_destroy(self.condvar.get()); - if cfg!(target_os = "dragonfly") { - debug_assert!(r == 0 || r == libc::EINVAL); - } else { - debug_assert_eq!(r, 0); - } - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle { - thread_parker: *const ThreadParker, -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - (*self.thread_parker).should_park.set(false); - - // We notify while holding the lock here to avoid races with the target - // thread. In particular, the thread could exit after we unlock the - // mutex, which would make the condvar access invalid memory. - let r = libc::pthread_cond_signal((*self.thread_parker).condvar.get()); - debug_assert_eq!(r, 0); - let r = libc::pthread_mutex_unlock((*self.thread_parker).mutex.get()); - debug_assert_eq!(r, 0); - } -} - -// Returns the current time on the clock used by pthread_cond_t as a timespec. -#[cfg(any(target_os = "macos", target_os = "ios"))] -unsafe fn timespec_now() -> libc::timespec { - let mut now: libc::timeval = mem::uninitialized(); - let r = libc::gettimeofday(&mut now, ptr::null_mut()); - debug_assert_eq!(r, 0); - libc::timespec { - tv_sec: now.tv_sec, - tv_nsec: now.tv_usec as tv_nsec_t * 1000, - } -} -#[cfg(not(any(target_os = "macos", target_os = "ios")))] -unsafe fn timespec_now() -> libc::timespec { - let mut now: libc::timespec = mem::uninitialized(); - let clock = if cfg!(target_os = "android") { - // Android doesn't support pthread_condattr_setclock, so we need to - // specify the timeout in CLOCK_REALTIME. - libc::CLOCK_REALTIME - } else { - libc::CLOCK_MONOTONIC - }; - let r = libc::clock_gettime(clock, &mut now); - debug_assert_eq!(r, 0); - now -} - -// Converts a relative timeout into an absolute timeout in the clock used by -// pthread_cond_t. -unsafe fn timeout_to_timespec(timeout: Duration) -> Option { - // Handle overflows early on - if timeout.as_secs() > libc::time_t::max_value() as u64 { - return None; - } - - let now = timespec_now(); - let mut nsec = now.tv_nsec + timeout.subsec_nanos() as tv_nsec_t; - let mut sec = now.tv_sec.checked_add(timeout.as_secs() as libc::time_t); - if nsec >= 1_000_000_000 { - nsec -= 1_000_000_000; - sec = sec.and_then(|sec| sec.checked_add(1)); - } - - sec.map(|sec| libc::timespec { - tv_nsec: nsec, - tv_sec: sec, - }) -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/mod.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/mod.rs deleted file mode 100644 index a91ab61..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/mod.rs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; -use std::time::Instant; - -mod keyed_event; -mod waitaddress; - -enum Backend { - KeyedEvent(keyed_event::KeyedEvent), - WaitAddress(waitaddress::WaitAddress), -} - -impl Backend { - unsafe fn get() -> &'static Backend { - static BACKEND: AtomicUsize = ATOMIC_USIZE_INIT; - - // Fast path: use the existing object - let backend = BACKEND.load(Ordering::Acquire); - if backend != 0 { - return &*(backend as *const Backend); - }; - - // Try to create a new Backend - let backend; - if let Some(waitaddress) = waitaddress::WaitAddress::create() { - backend = Backend::WaitAddress(waitaddress); - } else if let Some(keyed_event) = keyed_event::KeyedEvent::create() { - backend = Backend::KeyedEvent(keyed_event); - } else { - panic!( - "parking_lot requires either NT Keyed Events (WinXP+) or \ - WaitOnAddress/WakeByAddress (Win8+)" - ); - } - - // Try to create a new object - let backend = Box::into_raw(Box::new(backend)); - match BACKEND.compare_exchange(0, backend as usize, Ordering::Release, Ordering::Relaxed) { - Ok(_) => &*(backend as *const Backend), - Err(x) => { - // We lost the race, free our object and return the global one - Box::from_raw(backend); - &*(x as *const Backend) - } - } - } -} - -// Helper type for putting a thread to sleep until some other thread wakes it up -pub struct ThreadParker { - key: AtomicUsize, - backend: &'static Backend, -} - -impl ThreadParker { - pub fn new() -> ThreadParker { - // Initialize the backend here to ensure we don't get any panics - // later on, which could leave synchronization primitives in a broken - // state. - ThreadParker { - key: AtomicUsize::new(0), - backend: unsafe { Backend::get() }, - } - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { - match *self.backend { - Backend::KeyedEvent(ref x) => x.prepare_park(&self.key), - Backend::WaitAddress(ref x) => x.prepare_park(&self.key), - } - } - - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { - match *self.backend { - Backend::KeyedEvent(ref x) => x.timed_out(&self.key), - Backend::WaitAddress(ref x) => x.timed_out(&self.key), - } - } - - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { - match *self.backend { - Backend::KeyedEvent(ref x) => x.park(&self.key), - Backend::WaitAddress(ref x) => x.park(&self.key), - } - } - - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { - match *self.backend { - Backend::KeyedEvent(ref x) => x.park_until(&self.key, timeout), - Backend::WaitAddress(ref x) => x.park_until(&self.key, timeout), - } - } - - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { - match *self.backend { - Backend::KeyedEvent(ref x) => UnparkHandle::KeyedEvent(x.unpark_lock(&self.key)), - Backend::WaitAddress(ref x) => UnparkHandle::WaitAddress(x.unpark_lock(&self.key)), - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub enum UnparkHandle { - KeyedEvent(keyed_event::UnparkHandle), - WaitAddress(waitaddress::UnparkHandle), -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - match self { - UnparkHandle::KeyedEvent(x) => x.unpark(), - UnparkHandle::WaitAddress(x) => x.unpark(), - } - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/waitaddress.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/waitaddress.rs deleted file mode 100644 index 1d9fca8..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/waitaddress.rs +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -use winapi::shared::basetsd::SIZE_T; -use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE}; -use winapi::shared::winerror::ERROR_TIMEOUT; -use winapi::um::errhandlingapi::GetLastError; -use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress}; -use winapi::um::winbase::INFINITE; -use winapi::um::winnt::{LPCSTR, PVOID}; - -#[allow(non_snake_case)] -pub struct WaitAddress { - WaitOnAddress: extern "system" fn( - Address: PVOID, - CompareAddress: PVOID, - AddressSize: SIZE_T, - dwMilliseconds: DWORD, - ) -> BOOL, - WakeByAddressSingle: extern "system" fn(Address: PVOID), -} - -impl WaitAddress { - #[allow(non_snake_case)] - pub unsafe fn create() -> Option { - // MSDN claims that that WaitOnAddress and WakeByAddressSingle are - // located in kernel32.dll, but they are lying... - let synch_dll = GetModuleHandleA(b"api-ms-win-core-synch-l1-2-0.dll\0".as_ptr() as LPCSTR); - if synch_dll.is_null() { - return None; - } - - let WaitOnAddress = GetProcAddress(synch_dll, b"WaitOnAddress\0".as_ptr() as LPCSTR); - if WaitOnAddress.is_null() { - return None; - } - let WakeByAddressSingle = - GetProcAddress(synch_dll, b"WakeByAddressSingle\0".as_ptr() as LPCSTR); - if WakeByAddressSingle.is_null() { - return None; - } - Some(WaitAddress { - WaitOnAddress: mem::transmute(WaitOnAddress), - WakeByAddressSingle: mem::transmute(WakeByAddressSingle), - }) - } - - pub unsafe fn prepare_park(&'static self, key: &AtomicUsize) { - key.store(1, Ordering::Relaxed); - } - - pub unsafe fn timed_out(&'static self, key: &AtomicUsize) -> bool { - key.load(Ordering::Relaxed) != 0 - } - - pub unsafe fn park(&'static self, key: &AtomicUsize) { - while key.load(Ordering::Acquire) != 0 { - let cmp = 1usize; - let r = (self.WaitOnAddress)( - key as *const _ as PVOID, - &cmp as *const _ as PVOID, - mem::size_of::() as SIZE_T, - INFINITE, - ); - debug_assert!(r == TRUE); - } - } - - pub unsafe fn park_until(&'static self, key: &AtomicUsize, timeout: Instant) -> bool { - while key.load(Ordering::Acquire) != 0 { - let now = Instant::now(); - if timeout <= now { - return false; - } - let diff = timeout - now; - let timeout = diff - .as_secs() - .checked_mul(1000) - .and_then(|x| x.checked_add((diff.subsec_nanos() as u64 + 999999) / 1000000)) - .map(|ms| { - if ms > ::max_value() as u64 { - INFINITE - } else { - ms as DWORD - } - }).unwrap_or(INFINITE); - let cmp = 1usize; - let r = (self.WaitOnAddress)( - key as *const _ as PVOID, - &cmp as *const _ as PVOID, - mem::size_of::() as SIZE_T, - timeout, - ); - if r == FALSE { - debug_assert_eq!(GetLastError(), ERROR_TIMEOUT); - } - } - true - } - - pub unsafe fn unpark_lock(&'static self, key: &AtomicUsize) -> UnparkHandle { - // We don't need to lock anything, just clear the state - key.store(0, Ordering::Release); - - UnparkHandle { - key: key, - waitaddress: self, - } - } -} - -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. -pub struct UnparkHandle { - key: *const AtomicUsize, - waitaddress: &'static WaitAddress, -} - -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { - (self.waitaddress.WakeByAddressSingle)(self.key as PVOID); - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/word_lock.rs b/third_party/cargo/vendor/parking_lot_core-0.4.0/src/word_lock.rs deleted file mode 100644 index 7960568..0000000 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/word_lock.rs +++ /dev/null @@ -1,279 +0,0 @@ -// Copyright 2016 Amanieu d'Antras -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -use spinwait::SpinWait; -use std::cell::Cell; -use std::mem; -#[cfg(not(has_localkey_try_with))] -use std::panic; -use std::ptr; -use std::sync::atomic::{fence, AtomicUsize, Ordering}; -use std::thread::LocalKey; -use thread_parker::ThreadParker; - -struct ThreadData { - parker: ThreadParker, - - // Linked list of threads in the queue. The queue is split into two parts: - // the processed part and the unprocessed part. When new nodes are added to - // the list, they only have the next pointer set, and queue_tail is null. - // - // Nodes are processed with the queue lock held, which consists of setting - // the prev pointer for each node and setting the queue_tail pointer on the - // first processed node of the list. - // - // This setup allows nodes to be added to the queue without a lock, while - // still allowing O(1) removal of nodes from the processed part of the list. - // The only cost is the O(n) processing, but this only needs to be done - // once for each node, and therefore isn't too expensive. - queue_tail: Cell<*const ThreadData>, - prev: Cell<*const ThreadData>, - next: Cell<*const ThreadData>, -} - -impl ThreadData { - fn new() -> ThreadData { - ThreadData { - parker: ThreadParker::new(), - queue_tail: Cell::new(ptr::null()), - prev: Cell::new(ptr::null()), - next: Cell::new(ptr::null()), - } - } -} - -// Returns a ThreadData structure for the current thread -unsafe fn get_thread_data(local: &mut Option) -> &ThreadData { - // Try to read from thread-local storage, but return None if the TLS has - // already been destroyed. - #[cfg(has_localkey_try_with)] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - key.try_with(|x| x as *const ThreadData).ok() - } - #[cfg(not(has_localkey_try_with))] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - panic::catch_unwind(|| key.with(|x| x as *const ThreadData)).ok() - } - - // If ThreadData is expensive to construct, then we want to use a cached - // version in thread-local storage if possible. - if !cfg!(windows) && !cfg!(all(feature = "nightly", target_os = "linux")) { - thread_local!(static THREAD_DATA: ThreadData = ThreadData::new()); - if let Some(tls) = try_get_tls(&THREAD_DATA) { - return &*tls; - } - } - - // Otherwise just create a ThreadData on the stack - *local = Some(ThreadData::new()); - local.as_ref().unwrap() -} - -const LOCKED_BIT: usize = 1; -const QUEUE_LOCKED_BIT: usize = 2; -const QUEUE_MASK: usize = !3; - -// Word-sized lock that is used to implement the parking_lot API. Since this -// can't use parking_lot, it instead manages its own queue of waiting threads. -pub struct WordLock { - state: AtomicUsize, -} - -impl WordLock { - #[inline] - pub fn new() -> WordLock { - WordLock { - state: AtomicUsize::new(0), - } - } - - #[inline] - pub unsafe fn lock(&self) { - if self - .state - .compare_exchange_weak(0, LOCKED_BIT, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - return; - } - self.lock_slow(); - } - - #[inline] - pub unsafe fn unlock(&self) { - let state = self.state.fetch_sub(LOCKED_BIT, Ordering::Release); - if state & QUEUE_LOCKED_BIT != 0 || state & QUEUE_MASK == 0 { - return; - } - self.unlock_slow(); - } - - #[cold] - #[inline(never)] - unsafe fn lock_slow(&self) { - let mut spinwait = SpinWait::new(); - let mut state = self.state.load(Ordering::Relaxed); - loop { - // Grab the lock if it isn't locked, even if there is a queue on it - if state & LOCKED_BIT == 0 { - match self.state.compare_exchange_weak( - state, - state | LOCKED_BIT, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - continue; - } - - // If there is no queue, try spinning a few times - if state & QUEUE_MASK == 0 && spinwait.spin() { - state = self.state.load(Ordering::Relaxed); - continue; - } - - // Get our thread data and prepare it for parking - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - assert!(mem::align_of_val(thread_data) > !QUEUE_MASK); - thread_data.parker.prepare_park(); - - // Add our thread to the front of the queue - let queue_head = (state & QUEUE_MASK) as *const ThreadData; - if queue_head.is_null() { - thread_data.queue_tail.set(thread_data); - thread_data.prev.set(ptr::null()); - } else { - thread_data.queue_tail.set(ptr::null()); - thread_data.prev.set(ptr::null()); - thread_data.next.set(queue_head); - } - if let Err(x) = self.state.compare_exchange_weak( - state, - (state & !QUEUE_MASK) | thread_data as *const _ as usize, - Ordering::Release, - Ordering::Relaxed, - ) { - state = x; - continue; - } - - // Sleep until we are woken up by an unlock - thread_data.parker.park(); - - // Loop back and try locking again - spinwait.reset(); - self.state.load(Ordering::Relaxed); - } - } - - #[cold] - #[inline(never)] - unsafe fn unlock_slow(&self) { - let mut state = self.state.load(Ordering::Relaxed); - loop { - // We just unlocked the WordLock. Just check if there is a thread - // to wake up. If the queue is locked then another thread is already - // taking care of waking up a thread. - if state & QUEUE_LOCKED_BIT != 0 || state & QUEUE_MASK == 0 { - return; - } - - // Try to grab the queue lock - match self.state.compare_exchange_weak( - state, - state | QUEUE_LOCKED_BIT, - Ordering::Acquire, - Ordering::Relaxed, - ) { - Ok(_) => break, - Err(x) => state = x, - } - } - - // Now we have the queue lock and the queue is non-empty - 'outer: loop { - // First, we need to fill in the prev pointers for any newly added - // threads. We do this until we reach a node that we previously - // processed, which has a non-null queue_tail pointer. - let queue_head = (state & QUEUE_MASK) as *const ThreadData; - let mut queue_tail; - let mut current = queue_head; - loop { - queue_tail = (*current).queue_tail.get(); - if !queue_tail.is_null() { - break; - } - let next = (*current).next.get(); - (*next).prev.set(current); - current = next; - } - - // Set queue_tail on the queue head to indicate that the whole list - // has prev pointers set correctly. - (*queue_head).queue_tail.set(queue_tail); - - // If the WordLock is locked, then there is no point waking up a - // thread now. Instead we let the next unlocker take care of waking - // up a thread. - if state & LOCKED_BIT != 0 { - match self.state.compare_exchange_weak( - state, - state & !QUEUE_LOCKED_BIT, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return, - Err(x) => state = x, - } - - // Need an acquire fence before reading the new queue - fence(Ordering::Acquire); - continue; - } - - // Remove the last thread from the queue and unlock the queue - let new_tail = (*queue_tail).prev.get(); - if new_tail.is_null() { - loop { - match self.state.compare_exchange_weak( - state, - state & LOCKED_BIT, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => break, - Err(x) => state = x, - } - - // If the compare_exchange failed because a new thread was - // added to the queue then we need to re-scan the queue to - // find the previous element. - if state & QUEUE_MASK == 0 { - continue; - } else { - // Need an acquire fence before reading the new queue - fence(Ordering::Acquire); - continue 'outer; - } - } - } else { - (*queue_head).queue_tail.set(new_tail); - self.state.fetch_and(!QUEUE_LOCKED_BIT, Ordering::Release); - } - - // Finally, wake up the thread we removed from the queue. Note that - // we don't need to worry about any races here since the thread is - // guaranteed to be sleeping right now and we are the only one who - // can wake it up. - (*queue_tail).parker.unpark_lock().unpark(); - break; - } - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/.cargo-checksum.json b/third_party/cargo/vendor/parking_lot_core-0.7.0/.cargo-checksum.json new file mode 100644 index 0000000..cb5595b --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"3f1e8aa786fef106f002b12b25cb128fa1212ce04b2a2a98452ec1e83a662c4b","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","src/lib.rs":"058dddad16d91c8d0160fa2a78bb5f7c2f801f2fd9770fc387c5843395bf0379","src/parking_lot.rs":"13c1c9162933b0b3ed8b5237e03dfa66010e169070faead7a463ef9859bcb740","src/spinwait.rs":"d568d8a81f9144ec4c4a139dc934d7d04ee1656a4a221eb548742fe7aba09ab1","src/thread_parker/cloudabi.rs":"0668b50898c20e7267ac6cc977e7ad376a18958e2d07faeca8199794d873d2eb","src/thread_parker/generic.rs":"2f501c6e46fcff434ba9e13ae8859e66de3327f601ed92989b310124e4129ff4","src/thread_parker/linux.rs":"853fd22f51215d1f553ad6461ad3c92c4ec9c294e607e69ed5f53b2e8c7a11d7","src/thread_parker/mod.rs":"5bc2100d2f575608b5b76e626ca92ce3ba4830176ecc773c5594cda6ca0905e9","src/thread_parker/redox.rs":"081c76af1e24be12da45d8093e261c48d558342ac2ac64dc3f7dd95eaaa1bf11","src/thread_parker/sgx.rs":"3fd71a7066db58189f302d2344e4e425320f82c298ca482ca4318bae44ae37fd","src/thread_parker/unix.rs":"77e1f049207b7e89b22ef05e5134c7538b31fff99aa9660784136f96fec1845a","src/thread_parker/wasm.rs":"b4c9f9e9c1fd636b235a0e8e0227c954b1e7432d8394b58af77b348cdfa2141e","src/thread_parker/wasm_atomic.rs":"a1ab05981a833e72d8d353350ab2b95e6f833cd7224591e595ccdb3692968c23","src/thread_parker/windows/keyed_event.rs":"34fc4693e7afd69a5c426ae7face83b8363f114a44dece44197cd03861cfdded","src/thread_parker/windows/mod.rs":"7702ff9b72ac647ec998a9b205ace961a28839fcd94631fb750ca459e4804260","src/thread_parker/windows/waitaddress.rs":"06d994633006e237dc940f377432ea00cf1609e56096d69d46f7bb3b80eeb857","src/util.rs":"285e6133150645525f2ca1ece41f6d35bad4e7c5e08b42b20c99d2a97e04a974","src/word_lock.rs":"2c030aedb340ae8ca564365206452c298fe29986d005d6a40e808c9760f91c95"},"package":"7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1"} \ No newline at end of file diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/BUILD b/third_party/cargo/vendor/parking_lot_core-0.7.0/BUILD similarity index 76% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/BUILD rename to third_party/cargo/vendor/parking_lot_core-0.7.0/BUILD index fc7c6e2..2a120d1 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/BUILD +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/BUILD @@ -23,23 +23,22 @@ load( ) -# Unsupported target "build-script-build" with type "custom-build" omitted rust_library( name = "parking_lot_core", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ + "//third_party/cargo/vendor/cfg-if-0.1.10:cfg_if", "//third_party/cargo/vendor/libc-0.2.67:libc", - "//third_party/cargo/vendor/rand-0.5.6:rand", - "//third_party/cargo/vendor/smallvec-0.6.13:smallvec", + "//third_party/cargo/vendor/smallvec-1.2.0:smallvec", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.3.1", + version = "0.7.0", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/Cargo.toml b/third_party/cargo/vendor/parking_lot_core-0.7.0/Cargo.toml similarity index 80% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/Cargo.toml rename to third_party/cargo/vendor/parking_lot_core-0.7.0/Cargo.toml index b84475a..4da7eb7 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/Cargo.toml +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "parking_lot_core" -version = "0.3.1" +version = "0.7.0" authors = ["Amanieu d'Antras "] description = "An advanced API for creating custom synchronization primitives." keywords = ["mutex", "condvar", "rwlock", "once", "thread"] @@ -23,27 +24,29 @@ repository = "https://github.com/Amanieu/parking_lot" version = "0.3.2" optional = true +[dependencies.cfg-if] +version = "0.1.5" + [dependencies.petgraph] version = "0.4.5" optional = true -[dependencies.rand] -version = "0.5" - [dependencies.smallvec] -version = "0.6" +version = "1.0" [dependencies.thread-id] version = "3.2.0" optional = true -[build-dependencies.rustc_version] -version = "0.2" [features] deadlock_detection = ["petgraph", "thread-id", "backtrace"] nightly = [] +[target."cfg(target_os = \"cloudabi\")".dependencies.cloudabi] +version = "0.0.3" +[target."cfg(target_os = \"redox\")".dependencies.redox_syscall] +version = "0.1" [target."cfg(unix)".dependencies.libc] -version = "0.2.27" +version = "0.2.55" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["winnt", "ntstatus", "minwindef", "winerror", "winbase", "errhandlingapi", "handleapi"] diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-APACHE b/third_party/cargo/vendor/parking_lot_core-0.7.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/LICENSE-APACHE rename to third_party/cargo/vendor/parking_lot_core-0.7.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/parking_lot-0.7.1/LICENSE-MIT b/third_party/cargo/vendor/parking_lot_core-0.7.0/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/parking_lot-0.7.1/LICENSE-MIT rename to third_party/cargo/vendor/parking_lot_core-0.7.0/LICENSE-MIT diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/lib.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/lib.rs similarity index 66% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/src/lib.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/lib.rs index 338b63e..ba4cb1e 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/lib.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/lib.rs @@ -38,47 +38,34 @@ //! reference count and the two mutex bits in the same atomic word. #![warn(missing_docs)] +#![warn(rust_2018_idioms)] #![cfg_attr( - all(feature = "nightly", target_os = "linux"), - feature(integer_atomics) + all(target_env = "sgx", target_vendor = "fortanix"), + feature(sgx_platform) +)] +#![cfg_attr( + all( + feature = "nightly", + target_arch = "wasm32", + target_feature = "atomics" + ), + feature(stdsimd) +)] +#![cfg_attr( + all(feature = "nightly", target_os = "cloudabi",), + feature(thread_local) )] - -extern crate rand; -extern crate smallvec; - -#[cfg(feature = "deadlock_detection")] -extern crate backtrace; -#[cfg(feature = "deadlock_detection")] -extern crate petgraph; -#[cfg(feature = "deadlock_detection")] -extern crate thread_id; - -#[cfg(unix)] -extern crate libc; - -#[cfg(windows)] -extern crate winapi; - -#[cfg(all(feature = "nightly", target_os = "linux"))] -#[path = "thread_parker/linux.rs"] -mod thread_parker; -#[cfg(all(unix, not(all(feature = "nightly", target_os = "linux"))))] -#[path = "thread_parker/unix.rs"] -mod thread_parker; -#[cfg(windows)] -#[path = "thread_parker/windows/mod.rs"] -mod thread_parker; -#[cfg(not(any(windows, unix)))] -#[path = "thread_parker/generic.rs"] -mod thread_parker; mod parking_lot; mod spinwait; +mod thread_parker; mod util; mod word_lock; -pub use parking_lot::deadlock; -pub use parking_lot::{park, unpark_all, unpark_filter, unpark_one, unpark_requeue}; -pub use parking_lot::{FilterOp, ParkResult, ParkToken, RequeueOp, UnparkResult, UnparkToken}; -pub use parking_lot::{DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; -pub use spinwait::SpinWait; +pub use self::parking_lot::deadlock; +pub use self::parking_lot::{park, unpark_all, unpark_filter, unpark_one, unpark_requeue}; +pub use self::parking_lot::{ + FilterOp, ParkResult, ParkToken, RequeueOp, UnparkResult, UnparkToken, +}; +pub use self::parking_lot::{DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; +pub use self::spinwait::SpinWait; diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/parking_lot.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/parking_lot.rs similarity index 58% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/src/parking_lot.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/parking_lot.rs index 64acaf9..e91b665 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/parking_lot.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/parking_lot.rs @@ -5,23 +5,26 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use rand::rngs::SmallRng; -use rand::{FromEntropy, Rng}; +use crate::thread_parker::{ThreadParker, ThreadParkerT, UnparkHandleT}; +use crate::util::UncheckedOptionExt; +use crate::word_lock::WordLock; +use core::{ + cell::{Cell, UnsafeCell}, + ptr, + sync::atomic::{AtomicPtr, AtomicUsize, Ordering}, +}; use smallvec::SmallVec; -use std::cell::{Cell, UnsafeCell}; -use std::mem; -#[cfg(not(has_localkey_try_with))] -use std::panic; -use std::ptr; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; -use std::thread::LocalKey; use std::time::{Duration, Instant}; -use thread_parker::ThreadParker; -use util::UncheckedOptionExt; -use word_lock::WordLock; -static NUM_THREADS: AtomicUsize = ATOMIC_USIZE_INIT; -static HASHTABLE: AtomicUsize = ATOMIC_USIZE_INIT; +static NUM_THREADS: AtomicUsize = AtomicUsize::new(0); + +/// Holds the pointer to the currently active `HashTable`. +/// +/// # Safety +/// +/// Except for the initial value of null, it must always point to a valid `HashTable` instance. +/// Any `HashTable` this global static has ever pointed to must never be freed. +static HASHTABLE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); // Even with 3x more buckets than threads, the memory overhead per thread is // still only a few hundred bytes per thread. @@ -39,24 +42,27 @@ struct HashTable { } impl HashTable { + #[inline] fn new(num_threads: usize, prev: *const HashTable) -> Box { let new_size = (num_threads * LOAD_FACTOR).next_power_of_two(); let hash_bits = 0usize.leading_zeros() - new_size.leading_zeros() - 1; - let bucket = Bucket { - mutex: WordLock::new(), - queue_head: Cell::new(ptr::null()), - queue_tail: Cell::new(ptr::null()), - fair_timeout: UnsafeCell::new(FairTimeout::new()), - _padding: unsafe { mem::uninitialized() }, - }; + + let now = Instant::now(); + let mut entries = Vec::with_capacity(new_size); + for i in 0..new_size { + // We must ensure the seed is not zero + entries.push(Bucket::new(now, i as u32 + 1)); + } + Box::new(HashTable { - entries: vec![bucket; new_size].into_boxed_slice(), - hash_bits: hash_bits, + entries: entries.into_boxed_slice(), + hash_bits, _prev: prev, }) } } +#[repr(align(64))] struct Bucket { // Lock protecting the queue mutex: WordLock, @@ -67,22 +73,16 @@ struct Bucket { // Next time at which point be_fair should be set fair_timeout: UnsafeCell, - - // Padding to avoid false sharing between buckets. Ideally we would just - // align the bucket structure to 64 bytes, but Rust doesn't support that - // yet. - _padding: [u8; 64], } -// Implementation of Clone for Bucket, needed to make vec![] work -impl Clone for Bucket { - fn clone(&self) -> Bucket { - Bucket { +impl Bucket { + #[inline] + pub fn new(timeout: Instant, seed: u32) -> Self { + Self { mutex: WordLock::new(), queue_head: Cell::new(ptr::null()), queue_tail: Cell::new(ptr::null()), - fair_timeout: UnsafeCell::new(FairTimeout::new()), - _padding: unsafe { mem::uninitialized() }, + fair_timeout: UnsafeCell::new(FairTimeout::new(timeout, seed)), } } } @@ -91,28 +91,37 @@ struct FairTimeout { // Next time at which point be_fair should be set timeout: Instant, - // Random number generator for calculating the next timeout - rng: SmallRng, + // the PRNG state for calculating the next timeout + seed: u32, } impl FairTimeout { - fn new() -> FairTimeout { - FairTimeout { - timeout: Instant::now(), - rng: SmallRng::from_entropy(), - } + #[inline] + fn new(timeout: Instant, seed: u32) -> FairTimeout { + FairTimeout { timeout, seed } } // Determine whether we should force a fair unlock, and update the timeout + #[inline] fn should_timeout(&mut self) -> bool { let now = Instant::now(); if now > self.timeout { - self.timeout = now + Duration::new(0, self.rng.gen_range(0, 1000000)); + // Time between 0 and 1ms. + let nanos = self.gen_u32() % 1_000_000; + self.timeout = now + Duration::new(0, nanos); true } else { false } } + + // Pseudorandom number generator from the "Xorshift RNGs" paper by George Marsaglia. + fn gen_u32(&mut self) -> u32 { + self.seed ^= self.seed << 13; + self.seed ^= self.seed >> 17; + self.seed ^= self.seed << 5; + self.seed + } } struct ThreadData { @@ -135,8 +144,7 @@ struct ThreadData { parked_with_timeout: Cell, // Extra data for deadlock detection - // TODO: once supported in stable replace with #[cfg...] & remove dummy struct/impl - #[allow(dead_code)] + #[cfg(feature = "deadlock_detection")] deadlock_data: deadlock::DeadlockData, } @@ -145,9 +153,7 @@ impl ThreadData { // Keep track of the total number of live ThreadData objects and resize // the hash table accordingly. let num_threads = NUM_THREADS.fetch_add(1, Ordering::Relaxed) + 1; - unsafe { - grow_hashtable(num_threads); - } + grow_hashtable(num_threads); ThreadData { parker: ThreadParker::new(), @@ -156,34 +162,25 @@ impl ThreadData { unpark_token: Cell::new(DEFAULT_UNPARK_TOKEN), park_token: Cell::new(DEFAULT_PARK_TOKEN), parked_with_timeout: Cell::new(false), + #[cfg(feature = "deadlock_detection")] deadlock_data: deadlock::DeadlockData::new(), } } } -// Returns a ThreadData structure for the current thread -unsafe fn get_thread_data(local: &mut Option) -> &ThreadData { - // Try to read from thread-local storage, but return None if the TLS has - // already been destroyed. - #[cfg(has_localkey_try_with)] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - key.try_with(|x| x as *const ThreadData).ok() - } - #[cfg(not(has_localkey_try_with))] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - panic::catch_unwind(|| key.with(|x| x as *const ThreadData)).ok() - } - +// Invokes the given closure with a reference to the current thread `ThreadData`. +#[inline(always)] +fn with_thread_data(f: impl FnOnce(&ThreadData) -> T) -> T { // Unlike word_lock::ThreadData, parking_lot::ThreadData is always expensive - // to construct. Try to use a thread-local version if possible. + // to construct. Try to use a thread-local version if possible. Otherwise just + // create a ThreadData on the stack + let mut thread_data_storage = None; thread_local!(static THREAD_DATA: ThreadData = ThreadData::new()); - if let Some(tls) = try_get_tls(&THREAD_DATA) { - return &*tls; - } + let thread_data_ptr = THREAD_DATA + .try_with(|x| x as *const ThreadData) + .unwrap_or_else(|_| thread_data_storage.get_or_insert_with(ThreadData::new)); - // Otherwise just create a ThreadData on the stack - *local = Some(ThreadData::new()); - local.as_ref().unwrap() + f(unsafe { &*thread_data_ptr }) } impl Drop for ThreadData { @@ -192,157 +189,181 @@ impl Drop for ThreadData { } } -// Get a pointer to the latest hash table, creating one if it doesn't exist yet. -unsafe fn get_hashtable() -> *const HashTable { - let mut table = HASHTABLE.load(Ordering::Acquire); +/// Returns a reference to the latest hash table, creating one if it doesn't exist yet. +/// The reference is valid forever. However, the `HashTable` it references might become stale +/// at any point. Meaning it still exists, but it is not the instance in active use. +#[inline] +fn get_hashtable() -> &'static HashTable { + let table = HASHTABLE.load(Ordering::Acquire); // If there is no table, create one - if table == 0 { - let new_table = Box::into_raw(HashTable::new(LOAD_FACTOR, ptr::null())); - - // If this fails then it means some other thread created the hash - // table first. - match HASHTABLE.compare_exchange( - 0, - new_table as usize, - Ordering::Release, - Ordering::Relaxed, - ) { - Ok(_) => return new_table, - Err(x) => table = x, - } - - // Free the table we created - Box::from_raw(new_table); + if table.is_null() { + create_hashtable() + } else { + // SAFETY: when not null, `HASHTABLE` always points to a `HashTable` that is never freed. + unsafe { &*table } } +} - table as *const HashTable +/// Returns a reference to the latest hash table, creating one if it doesn't exist yet. +/// The reference is valid forever. However, the `HashTable` it references might become stale +/// at any point. Meaning it still exists, but it is not the instance in active use. +#[cold] +fn create_hashtable() -> &'static HashTable { + let new_table = Box::into_raw(HashTable::new(LOAD_FACTOR, ptr::null())); + + // If this fails then it means some other thread created the hash table first. + let table = match HASHTABLE.compare_exchange( + ptr::null_mut(), + new_table, + Ordering::Release, + Ordering::Relaxed, + ) { + Ok(_) => new_table, + Err(old_table) => { + // Free the table we created + // SAFETY: `new_table` is created from `Box::into_raw` above and only freed here. + unsafe { + Box::from_raw(new_table); + } + old_table + } + }; + // SAFETY: The `HashTable` behind `table` is never freed. It is either the table pointer we + // created here, or it is one loaded from `HASHTABLE`. + unsafe { &*table } } // Grow the hash table so that it is big enough for the given number of threads. // This isn't performance-critical since it is only done when a ThreadData is // created, which only happens once per thread. -unsafe fn grow_hashtable(num_threads: usize) { - // If there is no table, create one - if HASHTABLE.load(Ordering::Relaxed) == 0 { - let new_table = Box::into_raw(HashTable::new(num_threads, ptr::null())); - - // If this fails then it means some other thread created the hash - // table first. - if HASHTABLE - .compare_exchange(0, new_table as usize, Ordering::Release, Ordering::Relaxed) - .is_ok() - { - return; - } - - // Free the table we created - Box::from_raw(new_table); - } - - let mut old_table; - loop { - old_table = HASHTABLE.load(Ordering::Acquire) as *mut HashTable; +fn grow_hashtable(num_threads: usize) { + // Lock all buckets in the existing table and get a reference to it + let old_table = loop { + let table = get_hashtable(); // Check if we need to resize the existing table - if (*old_table).entries.len() >= LOAD_FACTOR * num_threads { + if table.entries.len() >= LOAD_FACTOR * num_threads { return; } // Lock all buckets in the old table - for b in &(*old_table).entries[..] { - b.mutex.lock(); + for bucket in &table.entries[..] { + bucket.mutex.lock(); } // Now check if our table is still the latest one. Another thread could // have grown the hash table between us reading HASHTABLE and locking // the buckets. - if HASHTABLE.load(Ordering::Relaxed) == old_table as usize { - break; + if HASHTABLE.load(Ordering::Relaxed) == table as *const _ as *mut _ { + break table; } // Unlock buckets and try again - for b in &(*old_table).entries[..] { - b.mutex.unlock(); + for bucket in &table.entries[..] { + // SAFETY: We hold the lock here, as required + unsafe { bucket.mutex.unlock() }; } - } + }; // Create the new table - let new_table = HashTable::new(num_threads, old_table); + let mut new_table = HashTable::new(num_threads, old_table); // Move the entries from the old table to the new one - for b in &(*old_table).entries[..] { - let mut current = b.queue_head.get(); - while !current.is_null() { - let next = (*current).next_in_queue.get(); - let hash = hash((*current).key.load(Ordering::Relaxed), new_table.hash_bits); - if new_table.entries[hash].queue_tail.get().is_null() { - new_table.entries[hash].queue_head.set(current); - } else { - (*new_table.entries[hash].queue_tail.get()) - .next_in_queue - .set(current); - } - new_table.entries[hash].queue_tail.set(current); - (*current).next_in_queue.set(ptr::null()); - current = next; - } + for bucket in &old_table.entries[..] { + // SAFETY: The park, unpark* and check_wait_graph_fast functions create only correct linked + // lists. All `ThreadData` instances in these lists will remain valid as long as they are + // present in the lists, meaning as long as their threads are parked. + unsafe { rehash_bucket_into(bucket, &mut new_table) }; } // Publish the new table. No races are possible at this point because // any other thread trying to grow the hash table is blocked on the bucket // locks in the old table. - HASHTABLE.store(Box::into_raw(new_table) as usize, Ordering::Release); + HASHTABLE.store(Box::into_raw(new_table), Ordering::Release); // Unlock all buckets in the old table - for b in &(*old_table).entries[..] { - b.mutex.unlock(); + for bucket in &old_table.entries[..] { + // SAFETY: We hold the lock here, as required + unsafe { bucket.mutex.unlock() }; + } +} + +/// Iterate through all `ThreadData` objects in the bucket and insert them into the given table +/// in the bucket their key correspond to for this table. +/// +/// # Safety +/// +/// The given `bucket` must have a correctly constructed linked list under `queue_head`, containing +/// `ThreadData` instances that must stay valid at least as long as the given `table` is in use. +/// +/// The given `table` must only contain buckets with correctly constructed linked lists. +unsafe fn rehash_bucket_into(bucket: &'static Bucket, table: &mut HashTable) { + let mut current: *const ThreadData = bucket.queue_head.get(); + while !current.is_null() { + let next = (*current).next_in_queue.get(); + let hash = hash((*current).key.load(Ordering::Relaxed), table.hash_bits); + if table.entries[hash].queue_tail.get().is_null() { + table.entries[hash].queue_head.set(current); + } else { + (*table.entries[hash].queue_tail.get()) + .next_in_queue + .set(current); + } + table.entries[hash].queue_tail.set(current); + (*current).next_in_queue.set(ptr::null()); + current = next; } } // Hash function for addresses #[cfg(target_pointer_width = "32")] +#[inline] fn hash(key: usize, bits: u32) -> usize { key.wrapping_mul(0x9E3779B9) >> (32 - bits) } #[cfg(target_pointer_width = "64")] +#[inline] fn hash(key: usize, bits: u32) -> usize { key.wrapping_mul(0x9E3779B97F4A7C15) >> (64 - bits) } -// Lock the bucket for the given key -unsafe fn lock_bucket<'a>(key: usize) -> &'a Bucket { - let mut bucket; +/// Locks the bucket for the given key and returns a reference to it. +/// The returned bucket must be unlocked again in order to not cause deadlocks. +#[inline] +fn lock_bucket(key: usize) -> &'static Bucket { loop { let hashtable = get_hashtable(); - let hash = hash(key, (*hashtable).hash_bits); - bucket = &(*hashtable).entries[hash]; + let hash = hash(key, hashtable.hash_bits); + let bucket = &hashtable.entries[hash]; // Lock the bucket bucket.mutex.lock(); // If no other thread has rehashed the table before we grabbed the lock // then we are good to go! The lock we grabbed prevents any rehashes. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize { + if HASHTABLE.load(Ordering::Relaxed) == hashtable as *const _ as *mut _ { return bucket; } // Unlock the bucket and try again - bucket.mutex.unlock(); + // SAFETY: We hold the lock here, as required + unsafe { bucket.mutex.unlock() }; } } -// Lock the bucket for the given key, but check that the key hasn't been changed -// in the meantime due to a requeue. -unsafe fn lock_bucket_checked<'a>(key: &AtomicUsize) -> (usize, &'a Bucket) { - let mut bucket; +/// Locks the bucket for the given key and returns a reference to it. But checks that the key +/// hasn't been changed in the meantime due to a requeue. +/// The returned bucket must be unlocked again in order to not cause deadlocks. +#[inline] +fn lock_bucket_checked(key: &AtomicUsize) -> (usize, &'static Bucket) { loop { let hashtable = get_hashtable(); let current_key = key.load(Ordering::Relaxed); - let hash = hash(current_key, (*hashtable).hash_bits); - bucket = &(*hashtable).entries[hash]; + let hash = hash(current_key, hashtable.hash_bits); + let bucket = &hashtable.entries[hash]; // Lock the bucket bucket.mutex.lock(); @@ -350,66 +371,73 @@ unsafe fn lock_bucket_checked<'a>(key: &AtomicUsize) -> (usize, &'a Bucket) { // Check that both the hash table and key are correct while the bucket // is locked. Note that the key can't change once we locked the proper // bucket for it, so we just keep trying until we have the correct key. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize + if HASHTABLE.load(Ordering::Relaxed) == hashtable as *const _ as *mut _ && key.load(Ordering::Relaxed) == current_key { return (current_key, bucket); } // Unlock the bucket and try again - bucket.mutex.unlock(); + // SAFETY: We hold the lock here, as required + unsafe { bucket.mutex.unlock() }; } } -// Lock the two buckets for the given pair of keys -unsafe fn lock_bucket_pair<'a>(key1: usize, key2: usize) -> (&'a Bucket, &'a Bucket) { - let mut bucket1; +/// Locks the two buckets for the given pair of keys and returns references to them. +/// The returned buckets must be unlocked again in order to not cause deadlocks. +/// +/// If both keys hash to the same value, both returned references will be to the same bucket. Be +/// careful to only unlock it once in this case, always use `unlock_bucket_pair`. +#[inline] +fn lock_bucket_pair(key1: usize, key2: usize) -> (&'static Bucket, &'static Bucket) { loop { let hashtable = get_hashtable(); - // Get the lowest bucket first - let hash1 = hash(key1, (*hashtable).hash_bits); - let hash2 = hash(key2, (*hashtable).hash_bits); - if hash1 <= hash2 { - bucket1 = &(*hashtable).entries[hash1]; + let hash1 = hash(key1, hashtable.hash_bits); + let hash2 = hash(key2, hashtable.hash_bits); + + // Get the bucket at the lowest hash/index first + let bucket1 = if hash1 <= hash2 { + &hashtable.entries[hash1] } else { - bucket1 = &(*hashtable).entries[hash2]; - } + &hashtable.entries[hash2] + }; // Lock the first bucket bucket1.mutex.lock(); // If no other thread has rehashed the table before we grabbed the lock // then we are good to go! The lock we grabbed prevents any rehashes. - if HASHTABLE.load(Ordering::Relaxed) == hashtable as usize { + if HASHTABLE.load(Ordering::Relaxed) == hashtable as *const _ as *mut _ { // Now lock the second bucket and return the two buckets if hash1 == hash2 { return (bucket1, bucket1); } else if hash1 < hash2 { - let bucket2 = &(*hashtable).entries[hash2]; + let bucket2 = &hashtable.entries[hash2]; bucket2.mutex.lock(); return (bucket1, bucket2); } else { - let bucket2 = &(*hashtable).entries[hash1]; + let bucket2 = &hashtable.entries[hash1]; bucket2.mutex.lock(); return (bucket2, bucket1); } } // Unlock the bucket and try again - bucket1.mutex.unlock(); + // SAFETY: We hold the lock here, as required + unsafe { bucket1.mutex.unlock() }; } } -// Unlock a pair of buckets +/// Unlock a pair of buckets +/// +/// # Safety +/// +/// Both buckets must be locked +#[inline] unsafe fn unlock_bucket_pair(bucket1: &Bucket, bucket2: &Bucket) { - if bucket1 as *const _ == bucket2 as *const _ { - bucket1.mutex.unlock(); - } else if bucket1 as *const _ < bucket2 as *const _ { - bucket2.mutex.unlock(); - bucket1.mutex.unlock(); - } else { - bucket1.mutex.unlock(); + bucket1.mutex.unlock(); + if !ptr::eq(bucket1, bucket2) { bucket2.mutex.unlock(); } } @@ -429,6 +457,7 @@ pub enum ParkResult { impl ParkResult { /// Returns true if we were unparked by another thread. + #[inline] pub fn is_unparked(self) -> bool { if let ParkResult::Unparked(_) = self { true @@ -535,142 +564,121 @@ pub const DEFAULT_PARK_TOKEN: ParkToken = ParkToken(0); /// to call `unpark_one`, `unpark_all`, `unpark_requeue` or `unpark_filter`, but /// it is not allowed to call `park` or panic. #[inline] -pub unsafe fn park( +pub unsafe fn park( key: usize, - validate: V, - before_sleep: B, - timed_out: T, - park_token: ParkToken, - timeout: Option, -) -> ParkResult -where - V: FnOnce() -> bool, - B: FnOnce(), - T: FnOnce(usize, bool), -{ - let mut v = Some(validate); - let mut b = Some(before_sleep); - let mut t = Some(timed_out); - park_internal( - key, - &mut || v.take().unchecked_unwrap()(), - &mut || b.take().unchecked_unwrap()(), - &mut |key, was_last_thread| t.take().unchecked_unwrap()(key, was_last_thread), - park_token, - timeout, - ) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn park_internal( - key: usize, - validate: &mut FnMut() -> bool, - before_sleep: &mut FnMut(), - timed_out: &mut FnMut(usize, bool), + validate: impl FnOnce() -> bool, + before_sleep: impl FnOnce(), + timed_out: impl FnOnce(usize, bool), park_token: ParkToken, timeout: Option, ) -> ParkResult { // Grab our thread data, this also ensures that the hash table exists - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); + with_thread_data(|thread_data| { + // Lock the bucket for the given key + let bucket = lock_bucket(key); - // Lock the bucket for the given key - let bucket = lock_bucket(key); - - // If the validation function fails, just return - if !validate() { - bucket.mutex.unlock(); - return ParkResult::Invalid; - } - - // Append our thread data to the queue and unlock the bucket - thread_data.parked_with_timeout.set(timeout.is_some()); - thread_data.next_in_queue.set(ptr::null()); - thread_data.key.store(key, Ordering::Relaxed); - thread_data.park_token.set(park_token); - thread_data.parker.prepare_park(); - if !bucket.queue_head.get().is_null() { - (*bucket.queue_tail.get()).next_in_queue.set(thread_data); - } else { - bucket.queue_head.set(thread_data); - } - bucket.queue_tail.set(thread_data); - bucket.mutex.unlock(); - - // Invoke the pre-sleep callback - before_sleep(); - - // Park our thread and determine whether we were woken up by an unpark or by - // our timeout. Note that this isn't precise: we can still be unparked since - // we are still in the queue. - let unparked = match timeout { - Some(timeout) => thread_data.parker.park_until(timeout), - None => { - thread_data.parker.park(); - // call deadlock detection on_unpark hook - deadlock::on_unpark(thread_data); - true + // If the validation function fails, just return + if !validate() { + // SAFETY: We hold the lock here, as required + bucket.mutex.unlock(); + return ParkResult::Invalid; } - }; - // If we were unparked, return now - if unparked { - return ParkResult::Unparked(thread_data.unpark_token.get()); - } - - // Lock our bucket again. Note that the hashtable may have been rehashed in - // the meantime. Our key may also have changed if we were requeued. - let (key, bucket) = lock_bucket_checked(&thread_data.key); - - // Now we need to check again if we were unparked or timed out. Unlike the - // last check this is precise because we hold the bucket lock. - if !thread_data.parker.timed_out() { - bucket.mutex.unlock(); - return ParkResult::Unparked(thread_data.unpark_token.get()); - } - - // We timed out, so we now need to remove our thread from the queue - let mut link = &bucket.queue_head; - let mut current = bucket.queue_head.get(); - let mut previous = ptr::null(); - while !current.is_null() { - if current == thread_data { - let next = (*current).next_in_queue.get(); - link.set(next); - let mut was_last_thread = true; - if bucket.queue_tail.get() == current { - bucket.queue_tail.set(previous); - } else { - // Scan the rest of the queue to see if there are any other - // entries with the given key. - let mut scan = next; - while !scan.is_null() { - if (*scan).key.load(Ordering::Relaxed) == key { - was_last_thread = false; - break; - } - scan = (*scan).next_in_queue.get(); - } - } - - // Callback to indicate that we timed out, and whether we were the - // last thread on the queue. - timed_out(key, was_last_thread); - break; + // Append our thread data to the queue and unlock the bucket + thread_data.parked_with_timeout.set(timeout.is_some()); + thread_data.next_in_queue.set(ptr::null()); + thread_data.key.store(key, Ordering::Relaxed); + thread_data.park_token.set(park_token); + thread_data.parker.prepare_park(); + if !bucket.queue_head.get().is_null() { + (*bucket.queue_tail.get()).next_in_queue.set(thread_data); } else { - link = &(*current).next_in_queue; - previous = current; - current = link.get(); + bucket.queue_head.set(thread_data); } - } + bucket.queue_tail.set(thread_data); + // SAFETY: We hold the lock here, as required + bucket.mutex.unlock(); - // There should be no way for our thread to have been removed from the queue - // if we timed out. - debug_assert!(!current.is_null()); + // Invoke the pre-sleep callback + before_sleep(); - // Unlock the bucket, we are done - bucket.mutex.unlock(); - ParkResult::TimedOut + // Park our thread and determine whether we were woken up by an unpark + // or by our timeout. Note that this isn't precise: we can still be + // unparked since we are still in the queue. + let unparked = match timeout { + Some(timeout) => thread_data.parker.park_until(timeout), + None => { + thread_data.parker.park(); + // call deadlock detection on_unpark hook + deadlock::on_unpark(thread_data); + true + } + }; + + // If we were unparked, return now + if unparked { + return ParkResult::Unparked(thread_data.unpark_token.get()); + } + + // Lock our bucket again. Note that the hashtable may have been rehashed in + // the meantime. Our key may also have changed if we were requeued. + let (key, bucket) = lock_bucket_checked(&thread_data.key); + + // Now we need to check again if we were unparked or timed out. Unlike the + // last check this is precise because we hold the bucket lock. + if !thread_data.parker.timed_out() { + // SAFETY: We hold the lock here, as required + bucket.mutex.unlock(); + return ParkResult::Unparked(thread_data.unpark_token.get()); + } + + // We timed out, so we now need to remove our thread from the queue + let mut link = &bucket.queue_head; + let mut current = bucket.queue_head.get(); + let mut previous = ptr::null(); + let mut was_last_thread = true; + while !current.is_null() { + if current == thread_data { + let next = (*current).next_in_queue.get(); + link.set(next); + if bucket.queue_tail.get() == current { + bucket.queue_tail.set(previous); + } else { + // Scan the rest of the queue to see if there are any other + // entries with the given key. + let mut scan = next; + while !scan.is_null() { + if (*scan).key.load(Ordering::Relaxed) == key { + was_last_thread = false; + break; + } + scan = (*scan).next_in_queue.get(); + } + } + + // Callback to indicate that we timed out, and whether we were the + // last thread on the queue. + timed_out(key, was_last_thread); + break; + } else { + if (*current).key.load(Ordering::Relaxed) == key { + was_last_thread = false; + } + link = &(*current).next_in_queue; + previous = current; + current = link.get(); + } + } + + // There should be no way for our thread to have been removed from the queue + // if we timed out. + debug_assert!(!current.is_null()); + + // Unlock the bucket, we are done + // SAFETY: We hold the lock here, as required + bucket.mutex.unlock(); + ParkResult::TimedOut + }) } /// Unparks one thread from the queue associated with the given key. @@ -693,18 +701,9 @@ unsafe fn park_internal( /// The `callback` function is called while the queue is locked and must not /// panic or call into any function in `parking_lot`. #[inline] -pub unsafe fn unpark_one(key: usize, callback: C) -> UnparkResult -where - C: FnOnce(UnparkResult) -> UnparkToken, -{ - let mut c = Some(callback); - unpark_one_internal(key, &mut |result| c.take().unchecked_unwrap()(result)) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_one_internal( +pub unsafe fn unpark_one( key: usize, - callback: &mut FnMut(UnparkResult) -> UnparkToken, + callback: impl FnOnce(UnparkResult) -> UnparkToken, ) -> UnparkResult { // Lock the bucket for the given key let bucket = lock_bucket(key); @@ -748,6 +747,7 @@ unsafe fn unpark_one_internal( // the queue locked while we perform a system call. Finally we wake // up the parked thread. let handle = (*current).parker.unpark_lock(); + // SAFETY: We hold the lock here, as required bucket.mutex.unlock(); handle.unpark(); @@ -761,6 +761,7 @@ unsafe fn unpark_one_internal( // No threads with a matching key were found in the bucket callback(result); + // SAFETY: We hold the lock here, as required bucket.mutex.unlock(); result } @@ -776,6 +777,7 @@ unsafe fn unpark_one_internal( /// You should only call this function with an address that you control, since /// you could otherwise interfere with the operation of other synchronization /// primitives. +#[inline] pub unsafe fn unpark_all(key: usize, unpark_token: UnparkToken) -> usize { // Lock the bucket for the given key let bucket = lock_bucket(key); @@ -810,6 +812,7 @@ pub unsafe fn unpark_all(key: usize, unpark_token: UnparkToken) -> usize { } // Unlock the bucket + // SAFETY: We hold the lock here, as required bucket.mutex.unlock(); // Now that we are outside the lock, wake up all the threads that we removed @@ -850,32 +853,11 @@ pub unsafe fn unpark_all(key: usize, unpark_token: UnparkToken) -> usize { /// The `validate` and `callback` functions are called while the queue is locked /// and must not panic or call into any function in `parking_lot`. #[inline] -pub unsafe fn unpark_requeue( +pub unsafe fn unpark_requeue( key_from: usize, key_to: usize, - validate: V, - callback: C, -) -> UnparkResult -where - V: FnOnce() -> RequeueOp, - C: FnOnce(RequeueOp, UnparkResult) -> UnparkToken, -{ - let mut v = Some(validate); - let mut c = Some(callback); - unpark_requeue_internal( - key_from, - key_to, - &mut || v.take().unchecked_unwrap()(), - &mut |op, r| c.take().unchecked_unwrap()(op, r), - ) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_requeue_internal( - key_from: usize, - key_to: usize, - validate: &mut FnMut() -> RequeueOp, - callback: &mut FnMut(RequeueOp, UnparkResult) -> UnparkToken, + validate: impl FnOnce() -> RequeueOp, + callback: impl FnOnce(RequeueOp, UnparkResult) -> UnparkToken, ) -> UnparkResult { // Lock the two buckets for the given key let (bucket_from, bucket_to) = lock_bucket_pair(key_from, key_to); @@ -884,6 +866,7 @@ unsafe fn unpark_requeue_internal( let mut result = UnparkResult::default(); let op = validate(); if op == RequeueOp::Abort { + // SAFETY: Both buckets are locked, as required. unlock_bucket_pair(bucket_from, bucket_to); return result; } @@ -964,9 +947,11 @@ unsafe fn unpark_requeue_internal( if let Some(wakeup_thread) = wakeup_thread { (*wakeup_thread).unpark_token.set(token); let handle = (*wakeup_thread).parker.unpark_lock(); + // SAFETY: Both buckets are locked, as required. unlock_bucket_pair(bucket_from, bucket_to); handle.unpark(); } else { + // SAFETY: Both buckets are locked, as required. unlock_bucket_pair(bucket_from, bucket_to); } @@ -1000,20 +985,10 @@ unsafe fn unpark_requeue_internal( /// The `filter` and `callback` functions are called while the queue is locked /// and must not panic or call into any function in `parking_lot`. #[inline] -pub unsafe fn unpark_filter(key: usize, mut filter: F, callback: C) -> UnparkResult -where - F: FnMut(ParkToken) -> FilterOp, - C: FnOnce(UnparkResult) -> UnparkToken, -{ - let mut c = Some(callback); - unpark_filter_internal(key, &mut filter, &mut |r| c.take().unchecked_unwrap()(r)) -} - -// Non-generic version to reduce monomorphization cost -unsafe fn unpark_filter_internal( +pub unsafe fn unpark_filter( key: usize, - filter: &mut FnMut(ParkToken) -> FilterOp, - callback: &mut FnMut(UnparkResult) -> UnparkToken, + mut filter: impl FnMut(ParkToken) -> FilterOp, + callback: impl FnOnce(UnparkResult) -> UnparkToken, ) -> UnparkResult { // Lock the bucket for the given key let bucket = lock_bucket(key); @@ -1073,6 +1048,7 @@ unsafe fn unpark_filter_internal( t.1 = Some((*t.0).parker.unpark_lock()); } + // SAFETY: We hold the lock here, as required bucket.mutex.unlock(); // Now that we are outside the lock, wake up all the threads that we removed @@ -1094,19 +1070,12 @@ pub mod deadlock { #[cfg(feature = "deadlock_detection")] pub(super) use super::deadlock_impl::DeadlockData; - #[cfg(not(feature = "deadlock_detection"))] - pub(super) struct DeadlockData {} - - #[cfg(not(feature = "deadlock_detection"))] - impl DeadlockData { - pub(super) fn new() -> Self { - DeadlockData {} - } - } - /// Acquire a resource identified by key in the deadlock detector /// Noop if deadlock_detection feature isn't enabled. - /// Note: Call after the resource is acquired + /// + /// # Safety + /// + /// Call after the resource is acquired #[inline] pub unsafe fn acquire_resource(_key: usize) { #[cfg(feature = "deadlock_detection")] @@ -1115,9 +1084,14 @@ pub mod deadlock { /// Release a resource identified by key in the deadlock detector. /// Noop if deadlock_detection feature isn't enabled. - /// Note: Call before the resource is released + /// /// # Panics + /// /// Panics if the resource was already released or wasn't acquired in this thread. + /// + /// # Safety + /// + /// Call before the resource is released #[inline] pub unsafe fn release_resource(_key: usize) { #[cfg(feature = "deadlock_detection")] @@ -1141,7 +1115,9 @@ pub mod deadlock { #[cfg(feature = "deadlock_detection")] mod deadlock_impl { - use super::{get_hashtable, get_thread_data, lock_bucket, ThreadData, NUM_THREADS}; + use super::{get_hashtable, lock_bucket, with_thread_data, ThreadData, NUM_THREADS}; + use crate::thread_parker::{ThreadParkerT, UnparkHandleT}; + use crate::word_lock::WordLock; use backtrace::Backtrace; use petgraph; use petgraph::graphmap::DiGraphMap; @@ -1214,19 +1190,19 @@ mod deadlock_impl { } pub unsafe fn acquire_resource(key: usize) { - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - (*thread_data.deadlock_data.resources.get()).push(key); + with_thread_data(|thread_data| { + (*thread_data.deadlock_data.resources.get()).push(key); + }); } pub unsafe fn release_resource(key: usize) { - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - let resources = &mut (*thread_data.deadlock_data.resources.get()); - match resources.iter().rposition(|x| *x == key) { - Some(p) => resources.swap_remove(p), - None => panic!("key {} not found in thread resources", key), - }; + with_thread_data(|thread_data| { + let resources = &mut (*thread_data.deadlock_data.resources.get()); + match resources.iter().rposition(|x| *x == key) { + Some(p) => resources.swap_remove(p), + None => panic!("key {} not found in thread resources", key), + }; + }); } pub fn check_deadlock() -> Vec> { @@ -1265,6 +1241,7 @@ mod deadlock_impl { } current = (*current).next_in_queue.get(); } + // SAFETY: We hold the lock here, as required b.mutex.unlock(); } @@ -1283,22 +1260,26 @@ mod deadlock_impl { // Returns all detected thread wait cycles. // Note that once a cycle is reported it's never reported again. unsafe fn check_wait_graph_slow() -> Vec> { + static DEADLOCK_DETECTION_LOCK: WordLock = WordLock::new(); + DEADLOCK_DETECTION_LOCK.lock(); + let mut table = get_hashtable(); loop { // Lock all buckets in the old table - for b in &(*table).entries[..] { + for b in &table.entries[..] { b.mutex.lock(); } // Now check if our table is still the latest one. Another thread could // have grown the hash table between us getting and locking the hash table. let new_table = get_hashtable(); - if new_table == table { + if new_table as *const _ == table as *const _ { break; } // Unlock buckets and try again - for b in &(*table).entries[..] { + for b in &table.entries[..] { + // SAFETY: We hold the lock here, as required b.mutex.unlock(); } @@ -1309,7 +1290,7 @@ mod deadlock_impl { let mut graph = DiGraphMap::::with_capacity(thread_count * 2, thread_count * 2); - for b in &(*table).entries[..] { + for b in &table.entries[..] { let mut current = b.queue_head.get(); while !current.is_null() { if !(*current).parked_with_timeout.get() @@ -1330,7 +1311,8 @@ mod deadlock_impl { } } - for b in &(*table).entries[..] { + for b in &table.entries[..] { + // SAFETY: We hold the lock here, as required b.mutex.unlock(); } @@ -1346,6 +1328,7 @@ mod deadlock_impl { (*td).deadlock_data.deadlocked.set(true); *(*td).deadlock_data.backtrace_sender.get() = Some(sender.clone()); let handle = (*td).parker.unpark_lock(); + // SAFETY: We hold the lock here, as required bucket.mutex.unlock(); // unpark the deadlocked thread! // on unpark it'll notice the deadlocked flag and report back @@ -1356,6 +1339,8 @@ mod deadlock_impl { results.push(receiver.iter().collect()); } + DEADLOCK_DETECTION_LOCK.unlock(); + results } @@ -1404,3 +1389,276 @@ mod deadlock_impl { cycles.iter().cloned().collect() } } + +#[cfg(test)] +mod tests { + use super::{ThreadData, DEFAULT_PARK_TOKEN, DEFAULT_UNPARK_TOKEN}; + use std::{ + ptr, + sync::{ + atomic::{AtomicIsize, AtomicPtr, AtomicUsize, Ordering}, + Arc, + }, + thread, + time::Duration, + }; + + /// Calls a closure for every `ThreadData` currently parked on a given key + fn for_each(key: usize, mut f: impl FnMut(&ThreadData)) { + let bucket = super::lock_bucket(key); + + let mut current: *const ThreadData = bucket.queue_head.get(); + while !current.is_null() { + let current_ref = unsafe { &*current }; + if current_ref.key.load(Ordering::Relaxed) == key { + f(current_ref); + } + current = current_ref.next_in_queue.get(); + } + + // SAFETY: We hold the lock here, as required + unsafe { bucket.mutex.unlock() }; + } + + macro_rules! test { + ( $( $name:ident( + repeats: $repeats:expr, + latches: $latches:expr, + delay: $delay:expr, + threads: $threads:expr, + single_unparks: $single_unparks:expr); + )* ) => { + $(#[test] + fn $name() { + let delay = Duration::from_micros($delay); + for _ in 0..$repeats { + run_parking_test($latches, delay, $threads, $single_unparks); + } + })* + }; + } + + test! { + unpark_all_one_fast( + repeats: 10000, latches: 1, delay: 0, threads: 1, single_unparks: 0 + ); + unpark_all_hundred_fast( + repeats: 100, latches: 1, delay: 0, threads: 100, single_unparks: 0 + ); + unpark_one_one_fast( + repeats: 1000, latches: 1, delay: 0, threads: 1, single_unparks: 1 + ); + unpark_one_hundred_fast( + repeats: 20, latches: 1, delay: 0, threads: 100, single_unparks: 100 + ); + unpark_one_fifty_then_fifty_all_fast( + repeats: 50, latches: 1, delay: 0, threads: 100, single_unparks: 50 + ); + unpark_all_one( + repeats: 100, latches: 1, delay: 10000, threads: 1, single_unparks: 0 + ); + unpark_all_hundred( + repeats: 100, latches: 1, delay: 10000, threads: 100, single_unparks: 0 + ); + unpark_one_one( + repeats: 10, latches: 1, delay: 10000, threads: 1, single_unparks: 1 + ); + unpark_one_fifty( + repeats: 1, latches: 1, delay: 10000, threads: 50, single_unparks: 50 + ); + unpark_one_fifty_then_fifty_all( + repeats: 2, latches: 1, delay: 10000, threads: 100, single_unparks: 50 + ); + hundred_unpark_all_one_fast( + repeats: 100, latches: 100, delay: 0, threads: 1, single_unparks: 0 + ); + hundred_unpark_all_one( + repeats: 1, latches: 100, delay: 10000, threads: 1, single_unparks: 0 + ); + } + + fn run_parking_test( + num_latches: usize, + delay: Duration, + num_threads: usize, + num_single_unparks: usize, + ) { + let mut tests = Vec::with_capacity(num_latches); + + for _ in 0..num_latches { + let test = Arc::new(SingleLatchTest::new(num_threads)); + let mut threads = Vec::with_capacity(num_threads); + for _ in 0..num_threads { + let test = test.clone(); + threads.push(thread::spawn(move || test.run())); + } + tests.push((test, threads)); + } + + for unpark_index in 0..num_single_unparks { + thread::sleep(delay); + for (test, _) in &tests { + test.unpark_one(unpark_index); + } + } + + for (test, threads) in tests { + test.finish(num_single_unparks); + for thread in threads { + thread.join().expect("Test thread panic"); + } + } + } + + struct SingleLatchTest { + semaphore: AtomicIsize, + num_awake: AtomicUsize, + /// Holds the pointer to the last *unprocessed* woken up thread. + last_awoken: AtomicPtr, + /// Total number of threads participating in this test. + num_threads: usize, + } + + impl SingleLatchTest { + pub fn new(num_threads: usize) -> Self { + Self { + // This implements a fair (FIFO) semaphore, and it starts out unavailable. + semaphore: AtomicIsize::new(0), + num_awake: AtomicUsize::new(0), + last_awoken: AtomicPtr::new(ptr::null_mut()), + num_threads, + } + } + + pub fn run(&self) { + // Get one slot from the semaphore + self.down(); + + // Report back to the test verification code that this thread woke up + let this_thread_ptr = super::with_thread_data(|t| t as *const _ as *mut _); + self.last_awoken.store(this_thread_ptr, Ordering::SeqCst); + self.num_awake.fetch_add(1, Ordering::SeqCst); + } + + pub fn unpark_one(&self, single_unpark_index: usize) { + // last_awoken should be null at all times except between self.up() and at the bottom + // of this method where it's reset to null again + assert!(self.last_awoken.load(Ordering::SeqCst).is_null()); + + let mut queue: Vec<*mut ThreadData> = Vec::with_capacity(self.num_threads); + for_each(self.semaphore_addr(), |thread_data| { + queue.push(thread_data as *const _ as *mut _); + }); + assert!(queue.len() <= self.num_threads - single_unpark_index); + + let num_awake_before_up = self.num_awake.load(Ordering::SeqCst); + + self.up(); + + // Wait for a parked thread to wake up and update num_awake + last_awoken. + while self.num_awake.load(Ordering::SeqCst) != num_awake_before_up + 1 { + thread::yield_now(); + } + + // At this point the other thread should have set last_awoken inside the run() method + let last_awoken = self.last_awoken.load(Ordering::SeqCst); + assert!(!last_awoken.is_null()); + if !queue.is_empty() && queue[0] != last_awoken { + panic!( + "Woke up wrong thread:\n\tqueue: {:?}\n\tlast awoken: {:?}", + queue, last_awoken + ); + } + self.last_awoken.store(ptr::null_mut(), Ordering::SeqCst); + } + + pub fn finish(&self, num_single_unparks: usize) { + // The amount of threads not unparked via unpark_one + let mut num_threads_left = self.num_threads.checked_sub(num_single_unparks).unwrap(); + + // Wake remaining threads up with unpark_all. Has to be in a loop, because there might + // still be threads that has not yet parked. + while num_threads_left > 0 { + let mut num_waiting_on_address = 0; + for_each(self.semaphore_addr(), |_thread_data| { + num_waiting_on_address += 1; + }); + assert!(num_waiting_on_address <= num_threads_left); + + let num_awake_before_unpark = self.num_awake.load(Ordering::SeqCst); + + let num_unparked = + unsafe { super::unpark_all(self.semaphore_addr(), DEFAULT_UNPARK_TOKEN) }; + assert!(num_unparked >= num_waiting_on_address); + assert!(num_unparked <= num_threads_left); + + // Wait for all unparked threads to wake up and update num_awake + last_awoken. + while self.num_awake.load(Ordering::SeqCst) + != num_awake_before_unpark + num_unparked + { + thread::yield_now() + } + + num_threads_left = num_threads_left.checked_sub(num_unparked).unwrap(); + } + // By now, all threads should have been woken up + assert_eq!(self.num_awake.load(Ordering::SeqCst), self.num_threads); + + // Make sure no thread is parked on our semaphore address + let mut num_waiting_on_address = 0; + for_each(self.semaphore_addr(), |_thread_data| { + num_waiting_on_address += 1; + }); + assert_eq!(num_waiting_on_address, 0); + } + + pub fn down(&self) { + let old_semaphore_value = self.semaphore.fetch_sub(1, Ordering::SeqCst); + + if old_semaphore_value > 0 { + // We acquired the semaphore. Done. + return; + } + + // We need to wait. + let validate = || true; + let before_sleep = || {}; + let timed_out = |_, _| {}; + unsafe { + super::park( + self.semaphore_addr(), + validate, + before_sleep, + timed_out, + DEFAULT_PARK_TOKEN, + None, + ); + } + } + + pub fn up(&self) { + let old_semaphore_value = self.semaphore.fetch_add(1, Ordering::SeqCst); + + // Check if anyone was waiting on the semaphore. If they were, then pass ownership to them. + if old_semaphore_value < 0 { + // We need to continue until we have actually unparked someone. It might be that + // the thread we want to pass ownership to has decremented the semaphore counter, + // but not yet parked. + loop { + match unsafe { + super::unpark_one(self.semaphore_addr(), |_| DEFAULT_UNPARK_TOKEN) + .unparked_threads + } { + 1 => break, + 0 => (), + i => panic!("Should not wake up {} threads", i), + } + } + } + } + + fn semaphore_addr(&self) -> usize { + &self.semaphore as *const _ as usize + } + } +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/spinwait.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/spinwait.rs similarity index 54% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/src/spinwait.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/spinwait.rs index 4185026..ad0327a 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/spinwait.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/spinwait.rs @@ -5,53 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -#[cfg(unix)] -use libc; +use crate::thread_parker; use std::sync::atomic::spin_loop_hint; -#[cfg(not(any(windows, unix)))] -use std::thread; -#[cfg(windows)] -use winapi; - -// Yields the rest of the current timeslice to the OS -#[cfg(windows)] -#[inline] -fn thread_yield() { - // Note that this is manually defined here rather than using the definition - // through `winapi`. The `winapi` definition comes from the `synchapi` - // header which enables the "synchronization.lib" library. It turns out, - // however that `Sleep` comes from `kernel32.dll` so this activation isn't - // necessary. - // - // This was originally identified in rust-lang/rust where on MinGW the - // libsynchronization.a library pulls in a dependency on a newer DLL not - // present in older versions of Windows. (see rust-lang/rust#49438) - // - // This is a bit of a hack for now and ideally we'd fix MinGW's own import - // libraries, but that'll probably take a lot longer than patching this here - // and avoiding the `synchapi` feature entirely. - extern "system" { - fn Sleep(a: winapi::shared::minwindef::DWORD); - } - unsafe { - // We don't use SwitchToThread here because it doesn't consider all - // threads in the system and the thread we are waiting for may not get - // selected. - Sleep(0); - } -} -#[cfg(unix)] -#[inline] -fn thread_yield() { - unsafe { - libc::sched_yield(); - } -} -#[cfg(not(any(windows, unix)))] -#[inline] -fn thread_yield() { - thread::yield_now(); -} // Wastes some CPU time for the given number of iterations, // using a hint to indicate to the CPU that we are spinning. @@ -63,6 +18,7 @@ fn cpu_relax(iterations: u32) { } /// A counter used to perform exponential backoff in spin loops. +#[derive(Default)] pub struct SpinWait { counter: u32, } @@ -70,8 +26,8 @@ pub struct SpinWait { impl SpinWait { /// Creates a new `SpinWait`. #[inline] - pub fn new() -> SpinWait { - SpinWait { counter: 0 } + pub fn new() -> Self { + Self::default() } /// Resets a `SpinWait` to its initial state. @@ -97,7 +53,7 @@ impl SpinWait { if self.counter <= 3 { cpu_relax(1 << self.counter); } else { - thread_yield(); + thread_parker::thread_yield(); } true } @@ -116,10 +72,3 @@ impl SpinWait { cpu_relax(1 << self.counter); } } - -impl Default for SpinWait { - #[inline] - fn default() -> SpinWait { - SpinWait::new() - } -} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/cloudabi.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/cloudabi.rs new file mode 100644 index 0000000..520cc72 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/cloudabi.rs @@ -0,0 +1,304 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use cloudabi as abi; +use core::{ + cell::Cell, + mem::{self, MaybeUninit}, + sync::atomic::{AtomicU32, Ordering}, +}; +use std::{convert::TryFrom, thread, time::Instant}; + +extern "C" { + #[thread_local] + static __pthread_thread_id: abi::tid; +} + +struct Lock { + lock: AtomicU32, +} + +impl Lock { + pub fn new() -> Self { + Lock { + lock: AtomicU32::new(abi::LOCK_UNLOCKED.0), + } + } + + /// # Safety + /// + /// See `Lock::lock`. + unsafe fn try_lock(&self) -> Option { + // Attempt to acquire the lock. + if let Err(old) = self.lock.compare_exchange( + abi::LOCK_UNLOCKED.0, + __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, + Ordering::Acquire, + Ordering::Relaxed, + ) { + // Failure. Crash upon recursive acquisition. + debug_assert_ne!( + old & !abi::LOCK_KERNEL_MANAGED.0, + __pthread_thread_id.0 | abi::LOCK_WRLOCKED.0, + "Attempted to recursive write-lock a lock", + ); + None + } else { + Some(LockGuard { lock: &self.lock }) + } + } + + /// # Safety + /// + /// This method is unsafe because the `LockGuard` has a raw pointer into this `Lock` + /// that it will access on drop to unlock the lock. So make sure the `LockGuard` goes + /// out of scope before the `Lock` it came from moves or goes out of scope. + pub unsafe fn lock(&self) -> LockGuard { + self.try_lock().unwrap_or_else(|| { + // Call into the kernel to acquire a write lock. + let subscription = abi::subscription { + type_: abi::eventtype::LOCK_WRLOCK, + union: abi::subscription_union { + lock: abi::subscription_lock { + lock: self.ptr(), + lock_scope: abi::scope::PRIVATE, + }, + }, + ..mem::zeroed() + }; + let mut event = MaybeUninit::::uninit(); + let mut nevents: usize = 0; + let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, &mut nevents); + debug_assert_eq!(ret, abi::errno::SUCCESS); + debug_assert_eq!(event.assume_init().error, abi::errno::SUCCESS); + + LockGuard { lock: &self.lock } + }) + } + + fn ptr(&self) -> *mut abi::lock { + &self.lock as *const AtomicU32 as *mut abi::lock + } +} + +struct LockGuard { + lock: *const AtomicU32, +} + +impl LockGuard { + fn ptr(&self) -> *mut abi::lock { + self.lock as *mut abi::lock + } +} + +impl Drop for LockGuard { + fn drop(&mut self) { + let lock = unsafe { &*self.lock }; + debug_assert_eq!( + lock.load(Ordering::Relaxed) & !abi::LOCK_KERNEL_MANAGED.0, + unsafe { __pthread_thread_id.0 } | abi::LOCK_WRLOCKED.0, + "This lock is not write-locked by this thread" + ); + + if !lock + .compare_exchange( + unsafe { __pthread_thread_id.0 } | abi::LOCK_WRLOCKED.0, + abi::LOCK_UNLOCKED.0, + Ordering::Release, + Ordering::Relaxed, + ) + .is_ok() + { + // Lock is managed by kernelspace. Call into the kernel + // to unblock waiting threads. + let ret = unsafe { abi::lock_unlock(self.lock as *mut abi::lock, abi::scope::PRIVATE) }; + debug_assert_eq!(ret, abi::errno::SUCCESS); + } + } +} + +struct Condvar { + condvar: AtomicU32, +} + +impl Condvar { + pub fn new() -> Self { + Condvar { + condvar: AtomicU32::new(abi::CONDVAR_HAS_NO_WAITERS.0), + } + } + + pub fn wait(&self, lock: &LockGuard) { + unsafe { + let subscription = abi::subscription { + type_: abi::eventtype::CONDVAR, + union: abi::subscription_union { + condvar: abi::subscription_condvar { + condvar: self.ptr(), + condvar_scope: abi::scope::PRIVATE, + lock: lock.ptr(), + lock_scope: abi::scope::PRIVATE, + }, + }, + ..mem::zeroed() + }; + let mut event = MaybeUninit::::uninit(); + let mut nevents: usize = 0; + + let ret = abi::poll(&subscription, event.as_mut_ptr(), 1, &mut nevents); + debug_assert_eq!(ret, abi::errno::SUCCESS); + debug_assert_eq!(event.assume_init().error, abi::errno::SUCCESS); + } + } + + /// Waits for a signal on the condvar. + /// Returns false if it times out before anyone notified us. + pub fn wait_timeout(&self, lock: &LockGuard, timeout: abi::timestamp) -> bool { + unsafe { + let subscriptions = [ + abi::subscription { + type_: abi::eventtype::CONDVAR, + union: abi::subscription_union { + condvar: abi::subscription_condvar { + condvar: self.ptr(), + condvar_scope: abi::scope::PRIVATE, + lock: lock.ptr(), + lock_scope: abi::scope::PRIVATE, + }, + }, + ..mem::zeroed() + }, + abi::subscription { + type_: abi::eventtype::CLOCK, + union: abi::subscription_union { + clock: abi::subscription_clock { + clock_id: abi::clockid::MONOTONIC, + timeout, + ..mem::zeroed() + }, + }, + ..mem::zeroed() + }, + ]; + let mut events = MaybeUninit::<[abi::event; 2]>::uninit(); + let mut nevents: usize = 0; + + let ret = abi::poll( + subscriptions.as_ptr(), + events.as_mut_ptr() as *mut _, + 2, + &mut nevents, + ); + debug_assert_eq!(ret, abi::errno::SUCCESS); + let events = events.assume_init(); + for i in 0..nevents { + debug_assert_eq!(events[i].error, abi::errno::SUCCESS); + if events[i].type_ == abi::eventtype::CONDVAR { + return true; + } + } + } + false + } + + pub fn notify(&self) { + let ret = unsafe { abi::condvar_signal(self.ptr(), abi::scope::PRIVATE, 1) }; + debug_assert_eq!(ret, abi::errno::SUCCESS); + } + + fn ptr(&self) -> *mut abi::condvar { + &self.condvar as *const AtomicU32 as *mut abi::condvar + } +} + +// Helper type for putting a thread to sleep until some other thread wakes it up +pub struct ThreadParker { + should_park: Cell, + lock: Lock, + condvar: Condvar, +} + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + fn new() -> ThreadParker { + ThreadParker { + should_park: Cell::new(false), + lock: Lock::new(), + condvar: Condvar::new(), + } + } + + unsafe fn prepare_park(&self) { + self.should_park.set(true); + } + + unsafe fn timed_out(&self) -> bool { + // We need to grab the lock here because another thread may be + // concurrently executing UnparkHandle::unpark, which is done without + // holding the queue lock. + let _guard = self.lock.lock(); + self.should_park.get() + } + + unsafe fn park(&self) { + let guard = self.lock.lock(); + while self.should_park.get() { + self.condvar.wait(&guard); + } + } + + unsafe fn park_until(&self, timeout: Instant) -> bool { + let guard = self.lock.lock(); + while self.should_park.get() { + if let Some(duration_left) = timeout.checked_duration_since(Instant::now()) { + if let Ok(nanos_left) = abi::timestamp::try_from(duration_left.as_nanos()) { + self.condvar.wait_timeout(&guard, nanos_left); + } else { + // remaining timeout overflows an abi::timestamp. Sleep indefinitely + self.condvar.wait(&guard); + } + } else { + // We timed out + return false; + } + } + true + } + + unsafe fn unpark_lock(&self) -> UnparkHandle { + let _lock_guard = self.lock.lock(); + + UnparkHandle { + thread_parker: self, + _lock_guard, + } + } +} + +pub struct UnparkHandle { + thread_parker: *const ThreadParker, + _lock_guard: LockGuard, +} + +impl super::UnparkHandleT for UnparkHandle { + unsafe fn unpark(self) { + (*self.thread_parker).should_park.set(false); + + // We notify while holding the lock here to avoid races with the target + // thread. In particular, the thread could exit after we unlock the + // mutex, which would make the condvar access invalid memory. + (*self.thread_parker).condvar.notify(); + } +} + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/generic.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/generic.rs new file mode 100644 index 0000000..3ee837a --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/generic.rs @@ -0,0 +1,77 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! A simple spin lock based thread parker. Used on platforms without better +//! parking facilities available. + +use core::sync::atomic::{spin_loop_hint, AtomicBool, Ordering}; +use std::{thread, time::Instant}; + +// Helper type for putting a thread to sleep until some other thread wakes it up +pub struct ThreadParker { + parked: AtomicBool, +} + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] + fn new() -> ThreadParker { + ThreadParker { + parked: AtomicBool::new(false), + } + } + + #[inline] + unsafe fn prepare_park(&self) { + self.parked.store(true, Ordering::Relaxed); + } + + #[inline] + unsafe fn timed_out(&self) -> bool { + self.parked.load(Ordering::Relaxed) != false + } + + #[inline] + unsafe fn park(&self) { + while self.parked.load(Ordering::Acquire) != false { + spin_loop_hint(); + } + } + + #[inline] + unsafe fn park_until(&self, timeout: Instant) -> bool { + while self.parked.load(Ordering::Acquire) != false { + if Instant::now() >= timeout { + return false; + } + spin_loop_hint(); + } + true + } + + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { + // We don't need to lock anything, just clear the state + self.parked.store(false, Ordering::Release); + UnparkHandle(()) + } +} + +pub struct UnparkHandle(()); + +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) {} +} + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/linux.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/linux.rs similarity index 50% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/linux.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/linux.rs index 4a13d73..04f66a7 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/linux.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/linux.rs @@ -5,13 +5,12 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use core::{ + ptr, + sync::atomic::{AtomicI32, Ordering}, +}; use libc; -use std::sync::atomic::{AtomicI32, Ordering}; -use std::time::Instant; - -const FUTEX_WAIT: i32 = 0; -const FUTEX_WAKE: i32 = 1; -const FUTEX_PRIVATE: i32 = 128; +use std::{thread, time::Instant}; // x32 Linux uses a non-standard type for tv_nsec in timespec. // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 @@ -22,54 +21,53 @@ type tv_nsec_t = i64; #[allow(non_camel_case_types)] type tv_nsec_t = libc::c_long; +fn errno() -> libc::c_int { + #[cfg(target_os = "linux")] + unsafe { + *libc::__errno_location() + } + #[cfg(target_os = "android")] + unsafe { + *libc::__errno() + } +} + // Helper type for putting a thread to sleep until some other thread wakes it up pub struct ThreadParker { futex: AtomicI32, } -impl ThreadParker { - pub fn new() -> ThreadParker { +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] + fn new() -> ThreadParker { ThreadParker { futex: AtomicI32::new(0), } } - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { + #[inline] + unsafe fn prepare_park(&self) { self.futex.store(1, Ordering::Relaxed); } - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { + #[inline] + unsafe fn timed_out(&self) -> bool { self.futex.load(Ordering::Relaxed) != 0 } - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { + #[inline] + unsafe fn park(&self) { while self.futex.load(Ordering::Acquire) != 0 { - let r = libc::syscall( - libc::SYS_futex, - &self.futex, - FUTEX_WAIT | FUTEX_PRIVATE, - 1, - 0, - ); - debug_assert!(r == 0 || r == -1); - if r == -1 { - debug_assert!( - *libc::__errno_location() == libc::EINTR - || *libc::__errno_location() == libc::EAGAIN - ); - } + self.futex_wait(None); } } - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { + #[inline] + unsafe fn park_until(&self, timeout: Instant) -> bool { while self.futex.load(Ordering::Acquire) != 0 { let now = Instant::now(); if timeout <= now { @@ -85,21 +83,7 @@ impl ThreadParker { tv_sec: diff.as_secs() as libc::time_t, tv_nsec: diff.subsec_nanos() as tv_nsec_t, }; - let r = libc::syscall( - libc::SYS_futex, - &self.futex, - FUTEX_WAIT | FUTEX_PRIVATE, - 1, - &ts, - ); - debug_assert!(r == 0 || r == -1); - if r == -1 { - debug_assert!( - *libc::__errno_location() == libc::EINTR - || *libc::__errno_location() == libc::EAGAIN - || *libc::__errno_location() == libc::ETIMEDOUT - ); - } + self.futex_wait(Some(ts)); } true } @@ -107,7 +91,8 @@ impl ThreadParker { // Locks the parker to prevent the target thread from exiting. This is // necessary to ensure that thread-local ThreadData objects remain valid. // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { // We don't need to lock anything, just clear the state self.futex.store(0, Ordering::Release); @@ -115,23 +100,56 @@ impl ThreadParker { } } -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. +impl ThreadParker { + #[inline] + fn futex_wait(&self, ts: Option) { + let ts_ptr = ts + .as_ref() + .map(|ts_ref| ts_ref as *const _) + .unwrap_or(ptr::null()); + let r = unsafe { + libc::syscall( + libc::SYS_futex, + &self.futex, + libc::FUTEX_WAIT | libc::FUTEX_PRIVATE_FLAG, + 1, + ts_ptr, + ) + }; + debug_assert!(r == 0 || r == -1); + if r == -1 { + debug_assert!( + errno() == libc::EINTR + || errno() == libc::EAGAIN + || (ts.is_some() && errno() == libc::ETIMEDOUT) + ); + } + } +} + pub struct UnparkHandle { futex: *const AtomicI32, } -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) { // The thread data may have been freed at this point, but it doesn't // matter since the syscall will just return EFAULT in that case. - let r = libc::syscall(libc::SYS_futex, self.futex, FUTEX_WAKE | FUTEX_PRIVATE, 1); + let r = libc::syscall( + libc::SYS_futex, + self.futex, + libc::FUTEX_WAKE | libc::FUTEX_PRIVATE_FLAG, + 1, + ); debug_assert!(r == 0 || r == 1 || r == -1); if r == -1 { - debug_assert_eq!(*libc::__errno_location(), libc::EFAULT); + debug_assert_eq!(errno(), libc::EFAULT); } } } + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/mod.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/mod.rs new file mode 100644 index 0000000..4c721c3 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/mod.rs @@ -0,0 +1,88 @@ +use cfg_if::cfg_if; +use std::time::Instant; + +/// Trait for the platform thread parker implementation. +/// +/// All unsafe methods are unsafe because the Unix thread parker is based on +/// pthread mutexes and condvars. Those primitives must not be moved and used +/// from any other memory address than the one they were located at when they +/// were initialized. As such, it's UB to call any unsafe method on +/// `ThreadParkerT` if the implementing instance has moved since the last +/// call to any of the unsafe methods. +pub trait ThreadParkerT { + type UnparkHandle: UnparkHandleT; + + const IS_CHEAP_TO_CONSTRUCT: bool; + + fn new() -> Self; + + /// Prepares the parker. This should be called before adding it to the queue. + unsafe fn prepare_park(&self); + + /// Checks if the park timed out. This should be called while holding the + /// queue lock after park_until has returned false. + unsafe fn timed_out(&self) -> bool; + + /// Parks the thread until it is unparked. This should be called after it has + /// been added to the queue, after unlocking the queue. + unsafe fn park(&self); + + /// Parks the thread until it is unparked or the timeout is reached. This + /// should be called after it has been added to the queue, after unlocking + /// the queue. Returns true if we were unparked and false if we timed out. + unsafe fn park_until(&self, timeout: Instant) -> bool; + + /// Locks the parker to prevent the target thread from exiting. This is + /// necessary to ensure that thread-local ThreadData objects remain valid. + /// This should be called while holding the queue lock. + unsafe fn unpark_lock(&self) -> Self::UnparkHandle; +} + +/// Handle for a thread that is about to be unparked. We need to mark the thread +/// as unparked while holding the queue lock, but we delay the actual unparking +/// until after the queue lock is released. +pub trait UnparkHandleT { + /// Wakes up the parked thread. This should be called after the queue lock is + /// released to avoid blocking the queue for too long. + /// + /// This method is unsafe for the same reason as the unsafe methods in + /// `ThreadParkerT`. + unsafe fn unpark(self); +} + +cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "android"))] { + #[path = "linux.rs"] + mod imp; + } else if #[cfg(unix)] { + #[path = "unix.rs"] + mod imp; + } else if #[cfg(windows)] { + #[path = "windows/mod.rs"] + mod imp; + } else if #[cfg(target_os = "redox")] { + #[path = "redox.rs"] + mod imp; + } else if #[cfg(all(target_env = "sgx", target_vendor = "fortanix"))] { + #[path = "sgx.rs"] + mod imp; + } else if #[cfg(all( + feature = "nightly", + target_arch = "wasm32", + target_feature = "atomics" + ))] { + #[path = "wasm_atomic.rs"] + mod imp; + } else if #[cfg(target_arch = "wasm32")] { + #[path = "wasm.rs"] + mod imp; + } else if #[cfg(all(feature = "nightly", target_os = "cloudabi"))] { + #[path = "cloudabi.rs"] + mod imp; + } else { + #[path = "generic.rs"] + mod imp; + } +} + +pub use self::imp::{thread_yield, ThreadParker, UnparkHandle}; diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/redox.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/redox.rs new file mode 100644 index 0000000..97ffc8a --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/redox.rs @@ -0,0 +1,138 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use core::{ + ptr, + sync::atomic::{AtomicI32, Ordering}, +}; +use std::{thread, time::Instant}; +use syscall::{ + call::futex, + data::TimeSpec, + error::{Error, EAGAIN, EFAULT, EINTR, ETIMEDOUT}, + flag::{FUTEX_WAIT, FUTEX_WAKE}, +}; + +const UNPARKED: i32 = 0; +const PARKED: i32 = 1; + +// Helper type for putting a thread to sleep until some other thread wakes it up +pub struct ThreadParker { + futex: AtomicI32, +} + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] + fn new() -> ThreadParker { + ThreadParker { + futex: AtomicI32::new(UNPARKED), + } + } + + #[inline] + unsafe fn prepare_park(&self) { + self.futex.store(PARKED, Ordering::Relaxed); + } + + #[inline] + unsafe fn timed_out(&self) -> bool { + self.futex.load(Ordering::Relaxed) != UNPARKED + } + + #[inline] + unsafe fn park(&self) { + while self.futex.load(Ordering::Acquire) != UNPARKED { + self.futex_wait(None); + } + } + + #[inline] + unsafe fn park_until(&self, timeout: Instant) -> bool { + while self.futex.load(Ordering::Acquire) != UNPARKED { + let now = Instant::now(); + if timeout <= now { + return false; + } + let diff = timeout - now; + if diff.as_secs() > i64::max_value() as u64 { + // Timeout overflowed, just sleep indefinitely + self.park(); + return true; + } + let ts = TimeSpec { + tv_sec: diff.as_secs() as i64, + tv_nsec: diff.subsec_nanos() as i32, + }; + self.futex_wait(Some(ts)); + } + true + } + + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { + // We don't need to lock anything, just clear the state + self.futex.store(UNPARKED, Ordering::Release); + + UnparkHandle { futex: self.ptr() } + } +} + +impl ThreadParker { + #[inline] + fn futex_wait(&self, ts: Option) { + let ts_ptr = ts + .as_ref() + .map(|ts_ref| ts_ref as *const _) + .unwrap_or(ptr::null()); + let r = unsafe { + futex( + self.ptr(), + FUTEX_WAIT, + PARKED, + ts_ptr as usize, + ptr::null_mut(), + ) + }; + match r { + Ok(r) => debug_assert_eq!(r, 0), + Err(Error { errno }) => { + debug_assert!(errno == EINTR || errno == EAGAIN || errno == ETIMEDOUT); + } + } + } + + #[inline] + fn ptr(&self) -> *mut i32 { + &self.futex as *const AtomicI32 as *mut i32 + } +} + +pub struct UnparkHandle { + futex: *mut i32, +} + +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) { + // The thread data may have been freed at this point, but it doesn't + // matter since the syscall will just return EFAULT in that case. + let r = futex(self.futex, FUTEX_WAKE, PARKED, 0, ptr::null_mut()); + match r { + Ok(num_woken) => debug_assert!(num_woken == 0 || num_woken == 1), + Err(Error { errno }) => debug_assert_eq!(errno, EFAULT), + } + } +} + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/sgx.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/sgx.rs new file mode 100644 index 0000000..56fc65a --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/sgx.rs @@ -0,0 +1,94 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use core::sync::atomic::{AtomicBool, Ordering}; +use std::{ + io, + os::fortanix_sgx::{ + thread::current as current_tcs, + usercalls::{ + self, + raw::{Tcs, EV_UNPARK, WAIT_INDEFINITE}, + }, + }, + thread, + time::Instant, +}; + +// Helper type for putting a thread to sleep until some other thread wakes it up +pub struct ThreadParker { + parked: AtomicBool, + tcs: Tcs, +} + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] + fn new() -> ThreadParker { + ThreadParker { + parked: AtomicBool::new(false), + tcs: current_tcs(), + } + } + + #[inline] + unsafe fn prepare_park(&self) { + self.parked.store(true, Ordering::Relaxed); + } + + #[inline] + unsafe fn timed_out(&self) -> bool { + self.parked.load(Ordering::Relaxed) + } + + #[inline] + unsafe fn park(&self) { + while self.parked.load(Ordering::Acquire) { + let result = usercalls::wait(EV_UNPARK, WAIT_INDEFINITE); + debug_assert_eq!(result.expect("wait returned error") & EV_UNPARK, EV_UNPARK); + } + } + + #[inline] + unsafe fn park_until(&self, _timeout: Instant) -> bool { + // FIXME: https://github.com/fortanix/rust-sgx/issues/31 + panic!("timeout not supported in SGX"); + } + + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { + // We don't need to lock anything, just clear the state + self.parked.store(false, Ordering::Release); + UnparkHandle(self.tcs) + } +} + +pub struct UnparkHandle(Tcs); + +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) { + let result = usercalls::send(EV_UNPARK, Some(self.0)); + if cfg!(debug_assertions) { + if let Err(error) = result { + // `InvalidInput` may be returned if the thread we send to has + // already been unparked and exited. + if error.kind() != io::ErrorKind::InvalidInput { + panic!("send returned an unexpected error: {:?}", error); + } + } + } + } +} + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/unix.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/unix.rs similarity index 71% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/unix.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/unix.rs index 169586b..e61ab62 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/unix.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/unix.rs @@ -5,12 +5,17 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use libc; -use std::cell::{Cell, UnsafeCell}; -use std::mem; #[cfg(any(target_os = "macos", target_os = "ios"))] -use std::ptr; -use std::time::{Duration, Instant}; +use core::ptr; +use core::{ + cell::{Cell, UnsafeCell}, + mem::MaybeUninit, +}; +use libc; +use std::{ + thread, + time::{Duration, Instant}, +}; // x32 Linux uses a non-standard type for tv_nsec in timespec. // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 @@ -29,8 +34,13 @@ pub struct ThreadParker { initialized: Cell, } -impl ThreadParker { - pub fn new() -> ThreadParker { +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = false; + + #[inline] + fn new() -> ThreadParker { ThreadParker { should_park: Cell::new(false), mutex: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER), @@ -39,32 +49,8 @@ impl ThreadParker { } } - // Initializes the condvar to use CLOCK_MONOTONIC instead of CLOCK_REALTIME. - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "android" - ))] - unsafe fn init(&self) {} - #[cfg(not(any( - target_os = "macos", - target_os = "ios", - target_os = "android" - )))] - unsafe fn init(&self) { - let mut attr: libc::pthread_condattr_t = mem::uninitialized(); - let r = libc::pthread_condattr_init(&mut attr); - debug_assert_eq!(r, 0); - let r = libc::pthread_condattr_setclock(&mut attr, libc::CLOCK_MONOTONIC); - debug_assert_eq!(r, 0); - let r = libc::pthread_cond_init(self.condvar.get(), &attr); - debug_assert_eq!(r, 0); - let r = libc::pthread_condattr_destroy(&mut attr); - debug_assert_eq!(r, 0); - } - - // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { + #[inline] + unsafe fn prepare_park(&self) { self.should_park.set(true); if !self.initialized.get() { self.init(); @@ -72,9 +58,8 @@ impl ThreadParker { } } - // Checks if the park timed out. This should be called while holding the - // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { + #[inline] + unsafe fn timed_out(&self) -> bool { // We need to grab the mutex here because another thread may be // concurrently executing UnparkHandle::unpark, which is done without // holding the queue lock. @@ -86,9 +71,8 @@ impl ThreadParker { should_park } - // Parks the thread until it is unparked. This should be called after it has - // been added to the queue, after unlocking the queue. - pub unsafe fn park(&self) { + #[inline] + unsafe fn park(&self) { let r = libc::pthread_mutex_lock(self.mutex.get()); debug_assert_eq!(r, 0); while self.should_park.get() { @@ -99,10 +83,8 @@ impl ThreadParker { debug_assert_eq!(r, 0); } - // Parks the thread until it is unparked or the timeout is reached. This - // should be called after it has been added to the queue, after unlocking - // the queue. Returns true if we were unparked and false if we timed out. - pub unsafe fn park_until(&self, timeout: Instant) -> bool { + #[inline] + unsafe fn park_until(&self, timeout: Instant) -> bool { let r = libc::pthread_mutex_lock(self.mutex.get()); debug_assert_eq!(r, 0); while self.should_park.get() { @@ -134,10 +116,8 @@ impl ThreadParker { true } - // Locks the parker to prevent the target thread from exiting. This is - // necessary to ensure that thread-local ThreadData objects remain valid. - // This should be called while holding the queue lock. - pub unsafe fn unpark_lock(&self) -> UnparkHandle { + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { let r = libc::pthread_mutex_lock(self.mutex.get()); debug_assert_eq!(r, 0); @@ -147,7 +127,30 @@ impl ThreadParker { } } +impl ThreadParker { + /// Initializes the condvar to use CLOCK_MONOTONIC instead of CLOCK_REALTIME. + #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))] + #[inline] + unsafe fn init(&self) {} + + /// Initializes the condvar to use CLOCK_MONOTONIC instead of CLOCK_REALTIME. + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] + #[inline] + unsafe fn init(&self) { + let mut attr = MaybeUninit::::uninit(); + let r = libc::pthread_condattr_init(attr.as_mut_ptr()); + debug_assert_eq!(r, 0); + let r = libc::pthread_condattr_setclock(attr.as_mut_ptr(), libc::CLOCK_MONOTONIC); + debug_assert_eq!(r, 0); + let r = libc::pthread_cond_init(self.condvar.get(), attr.as_ptr()); + debug_assert_eq!(r, 0); + let r = libc::pthread_condattr_destroy(attr.as_mut_ptr()); + debug_assert_eq!(r, 0); + } +} + impl Drop for ThreadParker { + #[inline] fn drop(&mut self) { // On DragonFly pthread_mutex_destroy() returns EINVAL if called on a // mutex that was just initialized with libc::PTHREAD_MUTEX_INITIALIZER. @@ -170,17 +173,13 @@ impl Drop for ThreadParker { } } -// Handle for a thread that is about to be unparked. We need to mark the thread -// as unparked while holding the queue lock, but we delay the actual unparking -// until after the queue lock is released. pub struct UnparkHandle { thread_parker: *const ThreadParker, } -impl UnparkHandle { - // Wakes up the parked thread. This should be called after the queue lock is - // released to avoid blocking the queue for too long. - pub unsafe fn unpark(self) { +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) { (*self.thread_parker).should_park.set(false); // We notify while holding the lock here to avoid races with the target @@ -195,18 +194,22 @@ impl UnparkHandle { // Returns the current time on the clock used by pthread_cond_t as a timespec. #[cfg(any(target_os = "macos", target_os = "ios"))] -unsafe fn timespec_now() -> libc::timespec { - let mut now: libc::timeval = mem::uninitialized(); - let r = libc::gettimeofday(&mut now, ptr::null_mut()); +#[inline] +fn timespec_now() -> libc::timespec { + let mut now = MaybeUninit::::uninit(); + let r = unsafe { libc::gettimeofday(now.as_mut_ptr(), ptr::null_mut()) }; debug_assert_eq!(r, 0); + // SAFETY: We know `libc::gettimeofday` has initialized the value. + let now = unsafe { now.assume_init() }; libc::timespec { tv_sec: now.tv_sec, tv_nsec: now.tv_usec as tv_nsec_t * 1000, } } #[cfg(not(any(target_os = "macos", target_os = "ios")))] -unsafe fn timespec_now() -> libc::timespec { - let mut now: libc::timespec = mem::uninitialized(); +#[inline] +fn timespec_now() -> libc::timespec { + let mut now = MaybeUninit::::uninit(); let clock = if cfg!(target_os = "android") { // Android doesn't support pthread_condattr_setclock, so we need to // specify the timeout in CLOCK_REALTIME. @@ -214,14 +217,16 @@ unsafe fn timespec_now() -> libc::timespec { } else { libc::CLOCK_MONOTONIC }; - let r = libc::clock_gettime(clock, &mut now); + let r = unsafe { libc::clock_gettime(clock, now.as_mut_ptr()) }; debug_assert_eq!(r, 0); - now + // SAFETY: We know `libc::clock_gettime` has initialized the value. + unsafe { now.assume_init() } } // Converts a relative timeout into an absolute timeout in the clock used by // pthread_cond_t. -unsafe fn timeout_to_timespec(timeout: Duration) -> Option { +#[inline] +fn timeout_to_timespec(timeout: Duration) -> Option { // Handle overflows early on if timeout.as_secs() > libc::time_t::max_value() as u64 { return None; @@ -240,3 +245,8 @@ unsafe fn timeout_to_timespec(timeout: Duration) -> Option { tv_sec: sec, }) } + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm.rs new file mode 100644 index 0000000..f91a218 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm.rs @@ -0,0 +1,53 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +//! The wasm platform can't park when atomic support is not available. +//! So this ThreadParker just panics on any attempt to park. + +use std::{thread, time::Instant}; + +pub struct ThreadParker(()); + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + fn new() -> ThreadParker { + ThreadParker(()) + } + + unsafe fn prepare_park(&self) { + panic!("Parking not supported on this platform"); + } + + unsafe fn timed_out(&self) -> bool { + panic!("Parking not supported on this platform"); + } + + unsafe fn park(&self) { + panic!("Parking not supported on this platform"); + } + + unsafe fn park_until(&self, _timeout: Instant) -> bool { + panic!("Parking not supported on this platform"); + } + + unsafe fn unpark_lock(&self) -> UnparkHandle { + panic!("Parking not supported on this platform"); + } +} + +pub struct UnparkHandle(()); + +impl super::UnparkHandleT for UnparkHandle { + unsafe fn unpark(self) {} +} + +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm_atomic.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm_atomic.rs new file mode 100644 index 0000000..37f3027 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/wasm_atomic.rs @@ -0,0 +1,96 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use core::{ + arch::wasm32, + sync::atomic::{AtomicI32, Ordering}, +}; +use std::{convert::TryFrom, thread, time::Instant}; + +// Helper type for putting a thread to sleep until some other thread wakes it up +pub struct ThreadParker { + parked: AtomicI32, +} + +const UNPARKED: i32 = 0; +const PARKED: i32 = 1; + +impl super::ThreadParkerT for ThreadParker { + type UnparkHandle = UnparkHandle; + + const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] + fn new() -> ThreadParker { + ThreadParker { + parked: AtomicI32::new(UNPARKED), + } + } + + #[inline] + unsafe fn prepare_park(&self) { + self.parked.store(PARKED, Ordering::Relaxed); + } + + #[inline] + unsafe fn timed_out(&self) -> bool { + self.parked.load(Ordering::Relaxed) == PARKED + } + + #[inline] + unsafe fn park(&self) { + while self.parked.load(Ordering::Acquire) == PARKED { + let r = unsafe { wasm32::i32_atomic_wait(self.ptr(), PARKED, -1) }; + // we should have either woken up (0) or got a not-equal due to a + // race (1). We should never time out (2) + debug_assert!(r == 0 || r == 1); + } + } + + #[inline] + unsafe fn park_until(&self, timeout: Instant) -> bool { + while self.parked.load(Ordering::Acquire) == PARKED { + if let Some(left) = timeout.checked_duration_since(Instant::now()) { + let nanos_left = i64::try_from(left.as_nanos()).unwrap_or(i64::max_value()); + let r = unsafe { wasm32::i32_atomic_wait(self.ptr(), PARKED, nanos_left) }; + debug_assert!(r == 0 || r == 1 || r == 2); + } else { + return false; + } + } + true + } + + #[inline] + unsafe fn unpark_lock(&self) -> UnparkHandle { + // We don't need to lock anything, just clear the state + self.parked.store(UNPARKED, Ordering::Release); + UnparkHandle(self.ptr()) + } +} + +impl ThreadParker { + #[inline] + fn ptr(&self) -> *mut i32 { + &self.parked as *const AtomicI32 as *mut i32 + } +} + +pub struct UnparkHandle(*mut i32); + +impl super::UnparkHandleT for UnparkHandle { + #[inline] + unsafe fn unpark(self) { + let num_notified = unsafe { wasm32::atomic_notify(self.0 as *mut i32, 1) }; + debug_assert!(num_notified == 0 || num_notified == 1); + } +} + +#[inline] +pub fn thread_yield() { + thread::yield_now(); +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/keyed_event.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/keyed_event.rs similarity index 64% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/keyed_event.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/keyed_event.rs index 0e32fce..7b516fe 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.4.0/src/thread_parker/windows/keyed_event.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/keyed_event.rs @@ -5,18 +5,29 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use std::mem; -use std::ptr; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::time::Instant; - -use winapi::shared::minwindef::{TRUE, ULONG}; -use winapi::shared::ntdef::NTSTATUS; -use winapi::shared::ntstatus::{STATUS_SUCCESS, STATUS_TIMEOUT}; -use winapi::um::handleapi::CloseHandle; -use winapi::um::libloaderapi::{GetModuleHandleA, GetProcAddress}; -use winapi::um::winnt::{ACCESS_MASK, GENERIC_READ, GENERIC_WRITE, LPCSTR}; -use winapi::um::winnt::{BOOLEAN, HANDLE, LARGE_INTEGER, PHANDLE, PLARGE_INTEGER, PVOID}; +use core::{ + mem::{self, MaybeUninit}, + ptr, +}; +use std::{ + sync::atomic::{AtomicUsize, Ordering}, + time::Instant, +}; +use winapi::{ + shared::{ + minwindef::{TRUE, ULONG}, + ntdef::NTSTATUS, + ntstatus::{STATUS_SUCCESS, STATUS_TIMEOUT}, + }, + um::{ + handleapi::CloseHandle, + libloaderapi::{GetModuleHandleA, GetProcAddress}, + winnt::{ + ACCESS_MASK, BOOLEAN, GENERIC_READ, GENERIC_WRITE, HANDLE, LARGE_INTEGER, LPCSTR, + PHANDLE, PLARGE_INTEGER, PVOID, + }, + }, +}; const STATE_UNPARKED: usize = 0; const STATE_PARKED: usize = 1; @@ -40,73 +51,82 @@ pub struct KeyedEvent { } impl KeyedEvent { + #[inline] unsafe fn wait_for(&self, key: PVOID, timeout: PLARGE_INTEGER) -> NTSTATUS { (self.NtWaitForKeyedEvent)(self.handle, key, 0, timeout) } + #[inline] unsafe fn release(&self, key: PVOID) -> NTSTATUS { (self.NtReleaseKeyedEvent)(self.handle, key, 0, ptr::null_mut()) } #[allow(non_snake_case)] - pub unsafe fn create() -> Option { - let ntdll = GetModuleHandleA(b"ntdll.dll\0".as_ptr() as LPCSTR); - if ntdll.is_null() { - return None; - } + pub fn create() -> Option { + unsafe { + let ntdll = GetModuleHandleA(b"ntdll.dll\0".as_ptr() as LPCSTR); + if ntdll.is_null() { + return None; + } - let NtCreateKeyedEvent = GetProcAddress(ntdll, b"NtCreateKeyedEvent\0".as_ptr() as LPCSTR); - if NtCreateKeyedEvent.is_null() { - return None; - } - let NtReleaseKeyedEvent = - GetProcAddress(ntdll, b"NtReleaseKeyedEvent\0".as_ptr() as LPCSTR); - if NtReleaseKeyedEvent.is_null() { - return None; - } - let NtWaitForKeyedEvent = - GetProcAddress(ntdll, b"NtWaitForKeyedEvent\0".as_ptr() as LPCSTR); - if NtWaitForKeyedEvent.is_null() { - return None; - } + let NtCreateKeyedEvent = + GetProcAddress(ntdll, b"NtCreateKeyedEvent\0".as_ptr() as LPCSTR); + if NtCreateKeyedEvent.is_null() { + return None; + } + let NtReleaseKeyedEvent = + GetProcAddress(ntdll, b"NtReleaseKeyedEvent\0".as_ptr() as LPCSTR); + if NtReleaseKeyedEvent.is_null() { + return None; + } + let NtWaitForKeyedEvent = + GetProcAddress(ntdll, b"NtWaitForKeyedEvent\0".as_ptr() as LPCSTR); + if NtWaitForKeyedEvent.is_null() { + return None; + } - let NtCreateKeyedEvent: extern "system" fn( - KeyedEventHandle: PHANDLE, - DesiredAccess: ACCESS_MASK, - ObjectAttributes: PVOID, - Flags: ULONG, - ) -> NTSTATUS = mem::transmute(NtCreateKeyedEvent); - let mut handle = mem::uninitialized(); - let status = NtCreateKeyedEvent( - &mut handle, - GENERIC_READ | GENERIC_WRITE, - ptr::null_mut(), - 0, - ); - if status != STATUS_SUCCESS { - return None; - } + let NtCreateKeyedEvent: extern "system" fn( + KeyedEventHandle: PHANDLE, + DesiredAccess: ACCESS_MASK, + ObjectAttributes: PVOID, + Flags: ULONG, + ) -> NTSTATUS = mem::transmute(NtCreateKeyedEvent); + let mut handle = MaybeUninit::uninit(); + let status = NtCreateKeyedEvent( + handle.as_mut_ptr(), + GENERIC_READ | GENERIC_WRITE, + ptr::null_mut(), + 0, + ); + if status != STATUS_SUCCESS { + return None; + } - Some(KeyedEvent { - handle, - NtReleaseKeyedEvent: mem::transmute(NtReleaseKeyedEvent), - NtWaitForKeyedEvent: mem::transmute(NtWaitForKeyedEvent), - }) + Some(KeyedEvent { + handle: handle.assume_init(), + NtReleaseKeyedEvent: mem::transmute(NtReleaseKeyedEvent), + NtWaitForKeyedEvent: mem::transmute(NtWaitForKeyedEvent), + }) + } } - pub unsafe fn prepare_park(&'static self, key: &AtomicUsize) { + #[inline] + pub fn prepare_park(&'static self, key: &AtomicUsize) { key.store(STATE_PARKED, Ordering::Relaxed); } - pub unsafe fn timed_out(&'static self, key: &AtomicUsize) -> bool { + #[inline] + pub fn timed_out(&'static self, key: &AtomicUsize) -> bool { key.load(Ordering::Relaxed) == STATE_TIMED_OUT } + #[inline] pub unsafe fn park(&'static self, key: &AtomicUsize) { let status = self.wait_for(key as *const _ as PVOID, ptr::null_mut()); debug_assert_eq!(status, STATUS_SUCCESS); } + #[inline] pub unsafe fn park_until(&'static self, key: &AtomicUsize, timeout: Instant) -> bool { let now = Instant::now(); if timeout <= now { @@ -152,6 +172,7 @@ impl KeyedEvent { false } + #[inline] pub unsafe fn unpark_lock(&'static self, key: &AtomicUsize) -> UnparkHandle { // If the state was STATE_PARKED then we need to wake up the thread if key.swap(STATE_UNPARKED, Ordering::Relaxed) == STATE_PARKED { @@ -169,6 +190,7 @@ impl KeyedEvent { } impl Drop for KeyedEvent { + #[inline] fn drop(&mut self) { unsafe { let ok = CloseHandle(self.handle); @@ -188,6 +210,7 @@ pub struct UnparkHandle { impl UnparkHandle { // Wakes up the parked thread. This should be called after the queue lock is // released to avoid blocking the queue for too long. + #[inline] pub unsafe fn unpark(self) { if !self.key.is_null() { let status = self.keyed_event.release(self.key as PVOID); diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/mod.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/mod.rs similarity index 63% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/mod.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/mod.rs index a91ab61..9db1652 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/thread_parker/windows/mod.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/mod.rs @@ -5,7 +5,10 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use core::{ + ptr, + sync::atomic::{AtomicPtr, AtomicUsize, Ordering}, +}; use std::time::Instant; mod keyed_event; @@ -16,16 +19,22 @@ enum Backend { WaitAddress(waitaddress::WaitAddress), } -impl Backend { - unsafe fn get() -> &'static Backend { - static BACKEND: AtomicUsize = ATOMIC_USIZE_INIT; +static BACKEND: AtomicPtr = AtomicPtr::new(ptr::null_mut()); +impl Backend { + #[inline] + fn get() -> &'static Backend { // Fast path: use the existing object - let backend = BACKEND.load(Ordering::Acquire); - if backend != 0 { - return &*(backend as *const Backend); + let backend_ptr = BACKEND.load(Ordering::Acquire); + if !backend_ptr.is_null() { + return unsafe { &*backend_ptr }; }; + Backend::create() + } + + #[cold] + fn create() -> &'static Backend { // Try to create a new Backend let backend; if let Some(waitaddress) = waitaddress::WaitAddress::create() { @@ -39,14 +48,21 @@ impl Backend { ); } - // Try to create a new object - let backend = Box::into_raw(Box::new(backend)); - match BACKEND.compare_exchange(0, backend as usize, Ordering::Release, Ordering::Relaxed) { - Ok(_) => &*(backend as *const Backend), - Err(x) => { - // We lost the race, free our object and return the global one - Box::from_raw(backend); - &*(x as *const Backend) + // Try to set our new Backend as the global one + let backend_ptr = Box::into_raw(Box::new(backend)); + match BACKEND.compare_exchange( + ptr::null_mut(), + backend_ptr, + Ordering::Release, + Ordering::Relaxed, + ) { + Ok(_) => unsafe { &*backend_ptr }, + Err(global_backend_ptr) => { + unsafe { + // We lost the race, free our object and return the global one + Box::from_raw(backend_ptr); + &*global_backend_ptr + } } } } @@ -59,18 +75,22 @@ pub struct ThreadParker { } impl ThreadParker { + pub const IS_CHEAP_TO_CONSTRUCT: bool = true; + + #[inline] pub fn new() -> ThreadParker { // Initialize the backend here to ensure we don't get any panics // later on, which could leave synchronization primitives in a broken // state. ThreadParker { key: AtomicUsize::new(0), - backend: unsafe { Backend::get() }, + backend: Backend::get(), } } // Prepares the parker. This should be called before adding it to the queue. - pub unsafe fn prepare_park(&self) { + #[inline] + pub fn prepare_park(&self) { match *self.backend { Backend::KeyedEvent(ref x) => x.prepare_park(&self.key), Backend::WaitAddress(ref x) => x.prepare_park(&self.key), @@ -79,7 +99,8 @@ impl ThreadParker { // Checks if the park timed out. This should be called while holding the // queue lock after park_until has returned false. - pub unsafe fn timed_out(&self) -> bool { + #[inline] + pub fn timed_out(&self) -> bool { match *self.backend { Backend::KeyedEvent(ref x) => x.timed_out(&self.key), Backend::WaitAddress(ref x) => x.timed_out(&self.key), @@ -88,6 +109,7 @@ impl ThreadParker { // Parks the thread until it is unparked. This should be called after it has // been added to the queue, after unlocking the queue. + #[inline] pub unsafe fn park(&self) { match *self.backend { Backend::KeyedEvent(ref x) => x.park(&self.key), @@ -98,6 +120,7 @@ impl ThreadParker { // Parks the thread until it is unparked or the timeout is reached. This // should be called after it has been added to the queue, after unlocking // the queue. Returns true if we were unparked and false if we timed out. + #[inline] pub unsafe fn park_until(&self, timeout: Instant) -> bool { match *self.backend { Backend::KeyedEvent(ref x) => x.park_until(&self.key, timeout), @@ -108,6 +131,7 @@ impl ThreadParker { // Locks the parker to prevent the target thread from exiting. This is // necessary to ensure that thread-local ThreadData objects remain valid. // This should be called while holding the queue lock. + #[inline] pub unsafe fn unpark_lock(&self) -> UnparkHandle { match *self.backend { Backend::KeyedEvent(ref x) => UnparkHandle::KeyedEvent(x.unpark_lock(&self.key)), @@ -127,6 +151,7 @@ pub enum UnparkHandle { impl UnparkHandle { // Wakes up the parked thread. This should be called after the queue lock is // released to avoid blocking the queue for too long. + #[inline] pub unsafe fn unpark(self) { match self { UnparkHandle::KeyedEvent(x) => x.unpark(), @@ -134,3 +159,30 @@ impl UnparkHandle { } } } + +// Yields the rest of the current timeslice to the OS +#[inline] +pub fn thread_yield() { + // Note that this is manually defined here rather than using the definition + // through `winapi`. The `winapi` definition comes from the `synchapi` + // header which enables the "synchronization.lib" library. It turns out, + // however that `Sleep` comes from `kernel32.dll` so this activation isn't + // necessary. + // + // This was originally identified in rust-lang/rust where on MinGW the + // libsynchronization.a library pulls in a dependency on a newer DLL not + // present in older versions of Windows. (see rust-lang/rust#49438) + // + // This is a bit of a hack for now and ideally we'd fix MinGW's own import + // libraries, but that'll probably take a lot longer than patching this here + // and avoiding the `synchapi` feature entirely. + extern "system" { + fn Sleep(a: winapi::shared::minwindef::DWORD); + } + unsafe { + // We don't use SwitchToThread here because it doesn't consider all + // threads in the system and the thread we are waiting for may not get + // selected. + Sleep(0); + } +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/waitaddress.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/waitaddress.rs new file mode 100644 index 0000000..0ec7804 --- /dev/null +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/thread_parker/windows/waitaddress.rs @@ -0,0 +1,149 @@ +// Copyright 2016 Amanieu d'Antras +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +use core::{ + mem, + sync::atomic::{AtomicUsize, Ordering}, +}; +use std::time::Instant; +use winapi::{ + shared::{ + basetsd::SIZE_T, + minwindef::{BOOL, DWORD, FALSE, TRUE}, + winerror::ERROR_TIMEOUT, + }, + um::{ + errhandlingapi::GetLastError, + libloaderapi::{GetModuleHandleA, GetProcAddress}, + winbase::INFINITE, + winnt::{LPCSTR, PVOID}, + }, +}; + +#[allow(non_snake_case)] +pub struct WaitAddress { + WaitOnAddress: extern "system" fn( + Address: PVOID, + CompareAddress: PVOID, + AddressSize: SIZE_T, + dwMilliseconds: DWORD, + ) -> BOOL, + WakeByAddressSingle: extern "system" fn(Address: PVOID), +} + +impl WaitAddress { + #[allow(non_snake_case)] + pub fn create() -> Option { + unsafe { + // MSDN claims that that WaitOnAddress and WakeByAddressSingle are + // located in kernel32.dll, but they are lying... + let synch_dll = + GetModuleHandleA(b"api-ms-win-core-synch-l1-2-0.dll\0".as_ptr() as LPCSTR); + if synch_dll.is_null() { + return None; + } + + let WaitOnAddress = GetProcAddress(synch_dll, b"WaitOnAddress\0".as_ptr() as LPCSTR); + if WaitOnAddress.is_null() { + return None; + } + let WakeByAddressSingle = + GetProcAddress(synch_dll, b"WakeByAddressSingle\0".as_ptr() as LPCSTR); + if WakeByAddressSingle.is_null() { + return None; + } + Some(WaitAddress { + WaitOnAddress: mem::transmute(WaitOnAddress), + WakeByAddressSingle: mem::transmute(WakeByAddressSingle), + }) + } + } + + #[inline] + pub fn prepare_park(&'static self, key: &AtomicUsize) { + key.store(1, Ordering::Relaxed); + } + + #[inline] + pub fn timed_out(&'static self, key: &AtomicUsize) -> bool { + key.load(Ordering::Relaxed) != 0 + } + + #[inline] + pub fn park(&'static self, key: &AtomicUsize) { + while key.load(Ordering::Acquire) != 0 { + let r = self.wait_on_address(key, INFINITE); + debug_assert!(r == TRUE); + } + } + + #[inline] + pub fn park_until(&'static self, key: &AtomicUsize, timeout: Instant) -> bool { + while key.load(Ordering::Acquire) != 0 { + let now = Instant::now(); + if timeout <= now { + return false; + } + let diff = timeout - now; + let timeout = diff + .as_secs() + .checked_mul(1000) + .and_then(|x| x.checked_add((diff.subsec_nanos() as u64 + 999999) / 1000000)) + .map(|ms| { + if ms > ::max_value() as u64 { + INFINITE + } else { + ms as DWORD + } + }) + .unwrap_or(INFINITE); + if self.wait_on_address(key, timeout) == FALSE { + debug_assert_eq!(unsafe { GetLastError() }, ERROR_TIMEOUT); + } + } + true + } + + #[inline] + pub fn unpark_lock(&'static self, key: &AtomicUsize) -> UnparkHandle { + // We don't need to lock anything, just clear the state + key.store(0, Ordering::Release); + + UnparkHandle { + key: key, + waitaddress: self, + } + } + + #[inline] + fn wait_on_address(&'static self, key: &AtomicUsize, timeout: DWORD) -> BOOL { + let cmp = 1usize; + (self.WaitOnAddress)( + key as *const _ as PVOID, + &cmp as *const _ as PVOID, + mem::size_of::() as SIZE_T, + timeout, + ) + } +} + +// Handle for a thread that is about to be unparked. We need to mark the thread +// as unparked while holding the queue lock, but we delay the actual unparking +// until after the queue lock is released. +pub struct UnparkHandle { + key: *const AtomicUsize, + waitaddress: &'static WaitAddress, +} + +impl UnparkHandle { + // Wakes up the parked thread. This should be called after the queue lock is + // released to avoid blocking the queue for too long. + #[inline] + pub fn unpark(self) { + (self.waitaddress.WakeByAddressSingle)(self.key as PVOID); + } +} diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/util.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/util.rs similarity index 86% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/src/util.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/util.rs index c7dfd32..d7aaa87 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/util.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/util.rs @@ -20,13 +20,12 @@ impl UncheckedOptionExt for Option { } } -// Equivalent to intrinsics::unreachable() in release mode +// hint::unreachable_unchecked() in release mode #[inline] unsafe fn unreachable() -> ! { if cfg!(debug_assertions) { unreachable!(); } else { - enum Void {} - match *(1 as *const Void) {} + core::hint::unreachable_unchecked() } } diff --git a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/word_lock.rs b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/word_lock.rs similarity index 61% rename from third_party/cargo/vendor/parking_lot_core-0.3.1/src/word_lock.rs rename to third_party/cargo/vendor/parking_lot_core-0.7.0/src/word_lock.rs index 7960568..450e985 100644 --- a/third_party/cargo/vendor/parking_lot_core-0.3.1/src/word_lock.rs +++ b/third_party/cargo/vendor/parking_lot_core-0.7.0/src/word_lock.rs @@ -5,15 +5,13 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use spinwait::SpinWait; -use std::cell::Cell; -use std::mem; -#[cfg(not(has_localkey_try_with))] -use std::panic; -use std::ptr; -use std::sync::atomic::{fence, AtomicUsize, Ordering}; -use std::thread::LocalKey; -use thread_parker::ThreadParker; +use crate::spinwait::SpinWait; +use crate::thread_parker::{ThreadParker, ThreadParkerT, UnparkHandleT}; +use core::{ + cell::Cell, + mem, ptr, + sync::atomic::{fence, AtomicUsize, Ordering}, +}; struct ThreadData { parker: ThreadParker, @@ -36,7 +34,9 @@ struct ThreadData { } impl ThreadData { + #[inline] fn new() -> ThreadData { + assert!(mem::align_of::() > !QUEUE_MASK); ThreadData { parker: ThreadParker::new(), queue_tail: Cell::new(ptr::null()), @@ -46,31 +46,25 @@ impl ThreadData { } } -// Returns a ThreadData structure for the current thread -unsafe fn get_thread_data(local: &mut Option) -> &ThreadData { - // Try to read from thread-local storage, but return None if the TLS has - // already been destroyed. - #[cfg(has_localkey_try_with)] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - key.try_with(|x| x as *const ThreadData).ok() - } - #[cfg(not(has_localkey_try_with))] - fn try_get_tls(key: &'static LocalKey) -> Option<*const ThreadData> { - panic::catch_unwind(|| key.with(|x| x as *const ThreadData)).ok() - } - +// Invokes the given closure with a reference to the current thread `ThreadData`. +#[inline] +fn with_thread_data(f: impl FnOnce(&ThreadData) -> T) -> T { + let mut thread_data_ptr = ptr::null(); // If ThreadData is expensive to construct, then we want to use a cached // version in thread-local storage if possible. - if !cfg!(windows) && !cfg!(all(feature = "nightly", target_os = "linux")) { + if !ThreadParker::IS_CHEAP_TO_CONSTRUCT { thread_local!(static THREAD_DATA: ThreadData = ThreadData::new()); - if let Some(tls) = try_get_tls(&THREAD_DATA) { - return &*tls; + if let Ok(tls_thread_data) = THREAD_DATA.try_with(|x| x as *const ThreadData) { + thread_data_ptr = tls_thread_data; } } - // Otherwise just create a ThreadData on the stack - *local = Some(ThreadData::new()); - local.as_ref().unwrap() + let mut thread_data_storage = None; + if thread_data_ptr.is_null() { + thread_data_ptr = thread_data_storage.get_or_insert_with(ThreadData::new); + } + + f(unsafe { &*thread_data_ptr }) } const LOCKED_BIT: usize = 1; @@ -84,15 +78,15 @@ pub struct WordLock { } impl WordLock { - #[inline] - pub fn new() -> WordLock { + /// Returns a new, unlocked, WordLock. + pub const fn new() -> Self { WordLock { state: AtomicUsize::new(0), } } #[inline] - pub unsafe fn lock(&self) { + pub fn lock(&self) { if self .state .compare_exchange_weak(0, LOCKED_BIT, Ordering::Acquire, Ordering::Relaxed) @@ -103,23 +97,23 @@ impl WordLock { self.lock_slow(); } + /// Must not be called on an already unlocked `WordLock`! #[inline] pub unsafe fn unlock(&self) { let state = self.state.fetch_sub(LOCKED_BIT, Ordering::Release); - if state & QUEUE_LOCKED_BIT != 0 || state & QUEUE_MASK == 0 { + if state.is_queue_locked() || state.queue_head().is_null() { return; } self.unlock_slow(); } #[cold] - #[inline(never)] - unsafe fn lock_slow(&self) { + fn lock_slow(&self) { let mut spinwait = SpinWait::new(); let mut state = self.state.load(Ordering::Relaxed); loop { // Grab the lock if it isn't locked, even if there is a queue on it - if state & LOCKED_BIT == 0 { + if !state.is_locked() { match self.state.compare_exchange_weak( state, state | LOCKED_BIT, @@ -133,55 +127,61 @@ impl WordLock { } // If there is no queue, try spinning a few times - if state & QUEUE_MASK == 0 && spinwait.spin() { + if state.queue_head().is_null() && spinwait.spin() { state = self.state.load(Ordering::Relaxed); continue; } // Get our thread data and prepare it for parking - let mut thread_data = None; - let thread_data = get_thread_data(&mut thread_data); - assert!(mem::align_of_val(thread_data) > !QUEUE_MASK); - thread_data.parker.prepare_park(); + state = with_thread_data(|thread_data| { + // The pthread implementation is still unsafe, so we need to surround `prepare_park` + // with `unsafe {}`. + #[allow(unused_unsafe)] + unsafe { + thread_data.parker.prepare_park(); + } - // Add our thread to the front of the queue - let queue_head = (state & QUEUE_MASK) as *const ThreadData; - if queue_head.is_null() { - thread_data.queue_tail.set(thread_data); - thread_data.prev.set(ptr::null()); - } else { - thread_data.queue_tail.set(ptr::null()); - thread_data.prev.set(ptr::null()); - thread_data.next.set(queue_head); - } - if let Err(x) = self.state.compare_exchange_weak( - state, - (state & !QUEUE_MASK) | thread_data as *const _ as usize, - Ordering::Release, - Ordering::Relaxed, - ) { - state = x; - continue; - } + // Add our thread to the front of the queue + let queue_head = state.queue_head(); + if queue_head.is_null() { + thread_data.queue_tail.set(thread_data); + thread_data.prev.set(ptr::null()); + } else { + thread_data.queue_tail.set(ptr::null()); + thread_data.prev.set(ptr::null()); + thread_data.next.set(queue_head); + } + if let Err(x) = self.state.compare_exchange_weak( + state, + state.with_queue_head(thread_data), + Ordering::Release, + Ordering::Relaxed, + ) { + return x; + } - // Sleep until we are woken up by an unlock - thread_data.parker.park(); + // Sleep until we are woken up by an unlock + // Ignoring unused unsafe, since it's only a few platforms where this is unsafe. + #[allow(unused_unsafe)] + unsafe { + thread_data.parker.park(); + } - // Loop back and try locking again - spinwait.reset(); - self.state.load(Ordering::Relaxed); + // Loop back and try locking again + spinwait.reset(); + self.state.load(Ordering::Relaxed) + }); } } #[cold] - #[inline(never)] - unsafe fn unlock_slow(&self) { + fn unlock_slow(&self) { let mut state = self.state.load(Ordering::Relaxed); loop { // We just unlocked the WordLock. Just check if there is a thread // to wake up. If the queue is locked then another thread is already // taking care of waking up a thread. - if state & QUEUE_LOCKED_BIT != 0 || state & QUEUE_MASK == 0 { + if state.is_queue_locked() || state.queue_head().is_null() { return; } @@ -202,27 +202,31 @@ impl WordLock { // First, we need to fill in the prev pointers for any newly added // threads. We do this until we reach a node that we previously // processed, which has a non-null queue_tail pointer. - let queue_head = (state & QUEUE_MASK) as *const ThreadData; + let queue_head = state.queue_head(); let mut queue_tail; let mut current = queue_head; loop { - queue_tail = (*current).queue_tail.get(); + queue_tail = unsafe { (*current).queue_tail.get() }; if !queue_tail.is_null() { break; } - let next = (*current).next.get(); - (*next).prev.set(current); - current = next; + unsafe { + let next = (*current).next.get(); + (*next).prev.set(current); + current = next; + } } // Set queue_tail on the queue head to indicate that the whole list // has prev pointers set correctly. - (*queue_head).queue_tail.set(queue_tail); + unsafe { + (*queue_head).queue_tail.set(queue_tail); + } // If the WordLock is locked, then there is no point waking up a // thread now. Instead we let the next unlocker take care of waking // up a thread. - if state & LOCKED_BIT != 0 { + if state.is_locked() { match self.state.compare_exchange_weak( state, state & !QUEUE_LOCKED_BIT, @@ -239,7 +243,7 @@ impl WordLock { } // Remove the last thread from the queue and unlock the queue - let new_tail = (*queue_tail).prev.get(); + let new_tail = unsafe { (*queue_tail).prev.get() }; if new_tail.is_null() { loop { match self.state.compare_exchange_weak( @@ -255,7 +259,7 @@ impl WordLock { // If the compare_exchange failed because a new thread was // added to the queue then we need to re-scan the queue to // find the previous element. - if state & QUEUE_MASK == 0 { + if state.queue_head().is_null() { continue; } else { // Need an acquire fence before reading the new queue @@ -264,7 +268,9 @@ impl WordLock { } } } else { - (*queue_head).queue_tail.set(new_tail); + unsafe { + (*queue_head).queue_tail.set(new_tail); + } self.state.fetch_and(!QUEUE_LOCKED_BIT, Ordering::Release); } @@ -272,8 +278,39 @@ impl WordLock { // we don't need to worry about any races here since the thread is // guaranteed to be sleeping right now and we are the only one who // can wake it up. - (*queue_tail).parker.unpark_lock().unpark(); + unsafe { + (*queue_tail).parker.unpark_lock().unpark(); + } break; } } } + +trait LockState { + fn is_locked(self) -> bool; + fn is_queue_locked(self) -> bool; + fn queue_head(self) -> *const ThreadData; + fn with_queue_head(self, thread_data: *const ThreadData) -> Self; +} + +impl LockState for usize { + #[inline] + fn is_locked(self) -> bool { + self & LOCKED_BIT != 0 + } + + #[inline] + fn is_queue_locked(self) -> bool { + self & QUEUE_LOCKED_BIT != 0 + } + + #[inline] + fn queue_head(self) -> *const ThreadData { + (self & QUEUE_MASK) as *const ThreadData + } + + #[inline] + fn with_queue_head(self, thread_data: *const ThreadData) -> Self { + (self & !QUEUE_MASK) | thread_data as *const _ as usize + } +} diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/.cargo-checksum.json b/third_party/cargo/vendor/percent-encoding-1.0.1/.cargo-checksum.json deleted file mode 100644 index 70eda28..0000000 --- a/third_party/cargo/vendor/percent-encoding-1.0.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"1e0b9724c150337dc13080547f26367d8a0d3a4050de38d5f16d2f3991e97637","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"20c7855c364d57ea4c97889a5e8d98470a9952dade37bd9248b9a54431670e5e","lib.rs":"d32a0b432c49053214a4aa51fd5e6b62215dea5a001f229a8ba1a17eb6be20f1"},"package":"31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"} \ No newline at end of file diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/lib.rs b/third_party/cargo/vendor/percent-encoding-1.0.1/lib.rs deleted file mode 100644 index 16d37ad..0000000 --- a/third_party/cargo/vendor/percent-encoding-1.0.1/lib.rs +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2013-2016 The rust-url developers. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! URLs use special chacters to indicate the parts of the request. For example, a forward slash -//! indicates a path. In order for that charcter to exist outside of a path separator, that -//! charcter would need to be encoded. -//! -//! Percent encoding replaces reserved charcters with the `%` escape charcter followed by hexidecimal -//! ASCII representaton. For non-ASCII charcters that are percent encoded, a UTF-8 byte sequence -//! becomes percent encoded. A simple example can be seen when the space literal is replaced with -//! `%20`. -//! -//! Percent encoding is further complicated by the fact that different parts of an URL have -//! different encoding requirements. In order to support the variety of encoding requirements, -//! `url::percent_encoding` includes different *encode sets*. -//! See [URL Standard](https://url.spec.whatwg.org/#percent-encoded-bytes) for details. -//! -//! This module provides some `*_ENCODE_SET` constants. -//! If a different set is required, it can be created with -//! the [`define_encode_set!`](../macro.define_encode_set!.html) macro. -//! -//! # Examples -//! -//! ``` -//! use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET}; -//! -//! assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F"); -//! ``` - -use std::ascii::AsciiExt; -use std::borrow::Cow; -use std::fmt; -use std::slice; -use std::str; - -/// Represents a set of characters / bytes that should be percent-encoded. -/// -/// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set). -/// -/// Different characters need to be encoded in different parts of an URL. -/// For example, a literal `?` question mark in an URL’s path would indicate -/// the start of the query string. -/// A question mark meant to be part of the path therefore needs to be percent-encoded. -/// In the query string however, a question mark does not have any special meaning -/// and does not need to be percent-encoded. -/// -/// A few sets are defined in this module. -/// Use the [`define_encode_set!`](../macro.define_encode_set!.html) macro to define different ones. -pub trait EncodeSet: Clone { - /// Called with UTF-8 bytes rather than code points. - /// Should return true for all non-ASCII bytes. - fn contains(&self, byte: u8) -> bool; -} - -/// Define a new struct -/// that implements the [`EncodeSet`](percent_encoding/trait.EncodeSet.html) trait, -/// for use in [`percent_decode()`](percent_encoding/fn.percent_encode.html) -/// and related functions. -/// -/// Parameters are characters to include in the set in addition to those of the base set. -/// See [encode sets specification](http://url.spec.whatwg.org/#simple-encode-set). -/// -/// Example -/// ======= -/// -/// ```rust -/// #[macro_use] extern crate percent_encoding; -/// use percent_encoding::{utf8_percent_encode, SIMPLE_ENCODE_SET}; -/// define_encode_set! { -/// /// This encode set is used in the URL parser for query strings. -/// pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'} -/// } -/// # fn main() { -/// assert_eq!(utf8_percent_encode("foo bar", QUERY_ENCODE_SET).collect::(), "foo%20bar"); -/// # } -/// ``` -#[macro_export] -macro_rules! define_encode_set { - ($(#[$attr: meta])* pub $name: ident = [$base_set: expr] | {$($ch: pat),*}) => { - $(#[$attr])* - #[derive(Copy, Clone, Debug)] - #[allow(non_camel_case_types)] - pub struct $name; - - impl $crate::EncodeSet for $name { - #[inline] - fn contains(&self, byte: u8) -> bool { - match byte as char { - $( - $ch => true, - )* - _ => $base_set.contains(byte) - } - } - } - } -} - -/// This encode set is used for the path of cannot-be-a-base URLs. -/// -/// All ASCII charcters less than hexidecimal 20 and greater than 7E are encoded. This includes -/// special charcters such as line feed, carriage return, NULL, etc. -#[derive(Copy, Clone, Debug)] -#[allow(non_camel_case_types)] -pub struct SIMPLE_ENCODE_SET; - -impl EncodeSet for SIMPLE_ENCODE_SET { - #[inline] - fn contains(&self, byte: u8) -> bool { - byte < 0x20 || byte > 0x7E - } -} - -define_encode_set! { - /// This encode set is used in the URL parser for query strings. - /// - /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html), - /// space, double quote ("), hash (#), and inequality qualifiers (<), (>) are encoded. - pub QUERY_ENCODE_SET = [SIMPLE_ENCODE_SET] | {' ', '"', '#', '<', '>'} -} - -define_encode_set! { - /// This encode set is used for path components. - /// - /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html), - /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`), - /// question mark (?), and curly brackets ({), (}) are encoded. - pub DEFAULT_ENCODE_SET = [QUERY_ENCODE_SET] | {'`', '?', '{', '}'} -} - -define_encode_set! { - /// This encode set is used for on '/'-separated path segment - /// - /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html), - /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`), - /// question mark (?), and curly brackets ({), (}), percent sign (%), forward slash (/) are - /// encoded. - pub PATH_SEGMENT_ENCODE_SET = [DEFAULT_ENCODE_SET] | {'%', '/'} -} - -define_encode_set! { - /// This encode set is used for username and password. - /// - /// Aside from special chacters defined in the [`SIMPLE_ENCODE_SET`](struct.SIMPLE_ENCODE_SET.html), - /// space, double quote ("), hash (#), inequality qualifiers (<), (>), backtick (`), - /// question mark (?), and curly brackets ({), (}), forward slash (/), colon (:), semi-colon (;), - /// equality (=), at (@), backslash (\\), square brackets ([), (]), caret (\^), and pipe (|) are - /// encoded. - pub USERINFO_ENCODE_SET = [DEFAULT_ENCODE_SET] | { - '/', ':', ';', '=', '@', '[', '\\', ']', '^', '|' - } -} - -/// Return the percent-encoding of the given bytes. -/// -/// This is unconditional, unlike `percent_encode()` which uses an encode set. -/// -/// # Examples -/// -/// ``` -/// use url::percent_encoding::percent_encode_byte; -/// -/// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::(), -/// "%66%6F%6F%20%62%61%72"); -/// ``` -pub fn percent_encode_byte(byte: u8) -> &'static str { - let index = usize::from(byte) * 3; - &"\ - %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\ - %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\ - %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\ - %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\ - %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\ - %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\ - %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\ - %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\ - %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\ - %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\ - %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\ - %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\ - %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\ - %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\ - %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\ - %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\ - "[index..index + 3] -} - -/// Percent-encode the given bytes with the given encode set. -/// -/// The encode set define which bytes (in addition to non-ASCII and controls) -/// need to be percent-encoded. -/// The choice of this set depends on context. -/// For example, `?` needs to be encoded in an URL path but not in a query string. -/// -/// The return value is an iterator of `&str` slices (so it has a `.collect::()` method) -/// that also implements `Display` and `Into>`. -/// The latter returns `Cow::Borrowed` when none of the bytes in `input` -/// are in the given encode set. -/// -/// # Examples -/// -/// ``` -/// use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET}; -/// -/// assert_eq!(percent_encode(b"foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F"); -/// ``` -#[inline] -pub fn percent_encode(input: &[u8], encode_set: E) -> PercentEncode { - PercentEncode { - bytes: input, - encode_set: encode_set, - } -} - -/// Percent-encode the UTF-8 encoding of the given string. -/// -/// See `percent_encode()` for how to use the return value. -/// -/// # Examples -/// -/// ``` -/// use url::percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET}; -/// -/// assert_eq!(utf8_percent_encode("foo bar?", DEFAULT_ENCODE_SET).to_string(), "foo%20bar%3F"); -/// ``` -#[inline] -pub fn utf8_percent_encode(input: &str, encode_set: E) -> PercentEncode { - percent_encode(input.as_bytes(), encode_set) -} - -/// The return type of `percent_encode()` and `utf8_percent_encode()`. -#[derive(Clone, Debug)] -pub struct PercentEncode<'a, E: EncodeSet> { - bytes: &'a [u8], - encode_set: E, -} - -impl<'a, E: EncodeSet> Iterator for PercentEncode<'a, E> { - type Item = &'a str; - - fn next(&mut self) -> Option<&'a str> { - if let Some((&first_byte, remaining)) = self.bytes.split_first() { - if self.encode_set.contains(first_byte) { - self.bytes = remaining; - Some(percent_encode_byte(first_byte)) - } else { - assert!(first_byte.is_ascii()); - for (i, &byte) in remaining.iter().enumerate() { - if self.encode_set.contains(byte) { - // 1 for first_byte + i for previous iterations of this loop - let (unchanged_slice, remaining) = self.bytes.split_at(1 + i); - self.bytes = remaining; - return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) }) - } else { - assert!(byte.is_ascii()); - } - } - let unchanged_slice = self.bytes; - self.bytes = &[][..]; - Some(unsafe { str::from_utf8_unchecked(unchanged_slice) }) - } - } else { - None - } - } - - fn size_hint(&self) -> (usize, Option) { - if self.bytes.is_empty() { - (0, Some(0)) - } else { - (1, Some(self.bytes.len())) - } - } -} - -impl<'a, E: EncodeSet> fmt::Display for PercentEncode<'a, E> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - for c in (*self).clone() { - formatter.write_str(c)? - } - Ok(()) - } -} - -impl<'a, E: EncodeSet> From> for Cow<'a, str> { - fn from(mut iter: PercentEncode<'a, E>) -> Self { - match iter.next() { - None => "".into(), - Some(first) => { - match iter.next() { - None => first.into(), - Some(second) => { - let mut string = first.to_owned(); - string.push_str(second); - string.extend(iter); - string.into() - } - } - } - } - } -} - -/// Percent-decode the given bytes. -/// -/// The return value is an iterator of decoded `u8` bytes -/// that also implements `Into>` -/// (which returns `Cow::Borrowed` when `input` contains no percent-encoded sequence) -/// and has `decode_utf8()` and `decode_utf8_lossy()` methods. -/// -/// # Examples -/// -/// ``` -/// use url::percent_encoding::percent_decode; -/// -/// assert_eq!(percent_decode(b"foo%20bar%3F").decode_utf8().unwrap(), "foo bar?"); -/// ``` -#[inline] -pub fn percent_decode(input: &[u8]) -> PercentDecode { - PercentDecode { - bytes: input.iter() - } -} - -/// The return type of `percent_decode()`. -#[derive(Clone, Debug)] -pub struct PercentDecode<'a> { - bytes: slice::Iter<'a, u8>, -} - -fn after_percent_sign(iter: &mut slice::Iter) -> Option { - let initial_iter = iter.clone(); - let h = iter.next().and_then(|&b| (b as char).to_digit(16)); - let l = iter.next().and_then(|&b| (b as char).to_digit(16)); - if let (Some(h), Some(l)) = (h, l) { - Some(h as u8 * 0x10 + l as u8) - } else { - *iter = initial_iter; - None - } -} - -impl<'a> Iterator for PercentDecode<'a> { - type Item = u8; - - fn next(&mut self) -> Option { - self.bytes.next().map(|&byte| { - if byte == b'%' { - after_percent_sign(&mut self.bytes).unwrap_or(byte) - } else { - byte - } - }) - } - - fn size_hint(&self) -> (usize, Option) { - let bytes = self.bytes.len(); - (bytes / 3, Some(bytes)) - } -} - -impl<'a> From> for Cow<'a, [u8]> { - fn from(iter: PercentDecode<'a>) -> Self { - match iter.if_any() { - Some(vec) => Cow::Owned(vec), - None => Cow::Borrowed(iter.bytes.as_slice()), - } - } -} - -impl<'a> PercentDecode<'a> { - /// If the percent-decoding is different from the input, return it as a new bytes vector. - pub fn if_any(&self) -> Option> { - let mut bytes_iter = self.bytes.clone(); - while bytes_iter.any(|&b| b == b'%') { - if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) { - let initial_bytes = self.bytes.as_slice(); - let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3; - let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned(); - decoded.push(decoded_byte); - decoded.extend(PercentDecode { - bytes: bytes_iter - }); - return Some(decoded) - } - } - // Nothing to decode - None - } - - /// Decode the result of percent-decoding as UTF-8. - /// - /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8. - pub fn decode_utf8(self) -> Result, str::Utf8Error> { - match self.clone().into() { - Cow::Borrowed(bytes) => { - match str::from_utf8(bytes) { - Ok(s) => Ok(s.into()), - Err(e) => Err(e), - } - } - Cow::Owned(bytes) => { - match String::from_utf8(bytes) { - Ok(s) => Ok(s.into()), - Err(e) => Err(e.utf8_error()), - } - } - } - } - - /// Decode the result of percent-decoding as UTF-8, lossily. - /// - /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD, - /// the replacement character. - pub fn decode_utf8_lossy(self) -> Cow<'a, str> { - decode_utf8_lossy(self.clone().into()) - } -} - -fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow { - match input { - Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes), - Cow::Owned(bytes) => { - let raw_utf8: *const [u8]; - match String::from_utf8_lossy(&bytes) { - Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(), - Cow::Owned(s) => return s.into(), - } - // from_utf8_lossy returned a borrow of `bytes` unchanged. - debug_assert!(raw_utf8 == &*bytes as *const [u8]); - // Reuse the existing `Vec` allocation. - unsafe { String::from_utf8_unchecked(bytes) }.into() - } - } -} - - diff --git a/third_party/cargo/vendor/percent-encoding-2.1.0/.cargo-checksum.json b/third_party/cargo/vendor/percent-encoding-2.1.0/.cargo-checksum.json new file mode 100644 index 0000000..7576f0f --- /dev/null +++ b/third_party/cargo/vendor/percent-encoding-2.1.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"dd59f4e6c033f011625ede444aa27fc8df4be53297af238b4f76d05144de5878","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"20c7855c364d57ea4c97889a5e8d98470a9952dade37bd9248b9a54431670e5e","lib.rs":"b9dd3a27fb0f56aebe3c4c411ea768a106a54e480ac08d9023c35bbba0bdcbdc"},"package":"d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e"} \ No newline at end of file diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/BUILD b/third_party/cargo/vendor/percent-encoding-2.1.0/BUILD similarity index 97% rename from third_party/cargo/vendor/percent-encoding-1.0.1/BUILD rename to third_party/cargo/vendor/percent-encoding-2.1.0/BUILD index f5a62c5..a7c30a9 100644 --- a/third_party/cargo/vendor/percent-encoding-1.0.1/BUILD +++ b/third_party/cargo/vendor/percent-encoding-2.1.0/BUILD @@ -35,7 +35,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "1.0.1", + version = "2.1.0", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/Cargo.toml b/third_party/cargo/vendor/percent-encoding-2.1.0/Cargo.toml similarity index 90% rename from third_party/cargo/vendor/percent-encoding-1.0.1/Cargo.toml rename to third_party/cargo/vendor/percent-encoding-2.1.0/Cargo.toml index bae0da0..b51d1d4 100644 --- a/third_party/cargo/vendor/percent-encoding-1.0.1/Cargo.toml +++ b/third_party/cargo/vendor/percent-encoding-2.1.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "percent-encoding" -version = "1.0.1" +version = "2.1.0" authors = ["The rust-url developers"] description = "Percent encoding and decoding" license = "MIT/Apache-2.0" @@ -21,4 +21,3 @@ repository = "https://github.com/servo/rust-url/" [lib] path = "lib.rs" test = false -doctest = false diff --git a/third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-APACHE b/third_party/cargo/vendor/percent-encoding-2.1.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/parking_lot_core-0.4.0/LICENSE-APACHE rename to third_party/cargo/vendor/percent-encoding-2.1.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/LICENSE-MIT b/third_party/cargo/vendor/percent-encoding-2.1.0/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/percent-encoding-1.0.1/LICENSE-MIT rename to third_party/cargo/vendor/percent-encoding-2.1.0/LICENSE-MIT diff --git a/third_party/cargo/vendor/percent-encoding-2.1.0/lib.rs b/third_party/cargo/vendor/percent-encoding-2.1.0/lib.rs new file mode 100644 index 0000000..27eaf67 --- /dev/null +++ b/third_party/cargo/vendor/percent-encoding-2.1.0/lib.rs @@ -0,0 +1,442 @@ +// Copyright 2013-2016 The rust-url developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! URLs use special chacters to indicate the parts of the request. +//! For example, a `?` question mark marks the end of a path and the start of a query string. +//! In order for that character to exist inside a path, it needs to be encoded differently. +//! +//! Percent encoding replaces reserved characters with the `%` escape character +//! followed by a byte value as two hexadecimal digits. +//! For example, an ASCII space is replaced with `%20`. +//! +//! When encoding, the set of characters that can (and should, for readability) be left alone +//! depends on the context. +//! The `?` question mark mentioned above is not a separator when used literally +//! inside of a query string, and therefore does not need to be encoded. +//! The [`AsciiSet`] parameter of [`percent_encode`] and [`utf8_percent_encode`] +//! lets callers configure this. +//! +//! This crate delibarately does not provide many different sets. +//! Users should consider in what context the encoded string will be used, +//! real relevant specifications, and define their own set. +//! This is done by using the `add` method of an existing set. +//! +//! # Examples +//! +//! ``` +//! use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS}; +//! +//! /// https://url.spec.whatwg.org/#fragment-percent-encode-set +//! const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); +//! +//! assert_eq!(utf8_percent_encode("foo ", FRAGMENT).to_string(), "foo%20%3Cbar%3E"); +//! ``` + +use std::borrow::Cow; +use std::fmt; +use std::slice; +use std::str; + +/// Represents a set of characters or bytes in the ASCII range. +/// +/// This used in [`percent_encode`] and [`utf8_percent_encode`]. +/// This is simlar to [percent-encode sets](https://url.spec.whatwg.org/#percent-encoded-bytes). +/// +/// Use the `add` method of an existing set to define a new set. For example: +/// +/// ``` +/// use percent_encoding::{AsciiSet, CONTROLS}; +/// +/// /// https://url.spec.whatwg.org/#fragment-percent-encode-set +/// const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); +/// ``` +pub struct AsciiSet { + mask: [Chunk; ASCII_RANGE_LEN / BITS_PER_CHUNK], +} + +type Chunk = u32; + +const ASCII_RANGE_LEN: usize = 0x80; + +const BITS_PER_CHUNK: usize = 8 * std::mem::size_of::(); + +impl AsciiSet { + /// Called with UTF-8 bytes rather than code points. + /// Not used for non-ASCII bytes. + const fn contains(&self, byte: u8) -> bool { + let chunk = self.mask[byte as usize / BITS_PER_CHUNK]; + let mask = 1 << (byte as usize % BITS_PER_CHUNK); + (chunk & mask) != 0 + } + + fn should_percent_encode(&self, byte: u8) -> bool { + !byte.is_ascii() || self.contains(byte) + } + + pub const fn add(&self, byte: u8) -> Self { + let mut mask = self.mask; + mask[byte as usize / BITS_PER_CHUNK] |= 1 << (byte as usize % BITS_PER_CHUNK); + AsciiSet { mask } + } + + pub const fn remove(&self, byte: u8) -> Self { + let mut mask = self.mask; + mask[byte as usize / BITS_PER_CHUNK] &= !(1 << (byte as usize % BITS_PER_CHUNK)); + AsciiSet { mask } + } +} + +/// The set of 0x00 to 0x1F (C0 controls), and 0x7F (DEL). +/// +/// Note that this includes the newline and tab characters, but not the space 0x20. +/// +/// +pub const CONTROLS: &AsciiSet = &AsciiSet { + mask: [ + !0_u32, // C0: 0x00 to 0x1F (32 bits set) + 0, + 0, + 1 << (0x7F_u32 % 32), // DEL: 0x7F (one bit set) + ], +}; + +macro_rules! static_assert { + ($( $bool: expr, )+) => { + fn _static_assert() { + $( + let _ = std::mem::transmute::<[u8; $bool as usize], u8>; + )+ + } + } +} + +static_assert! { + CONTROLS.contains(0x00), + CONTROLS.contains(0x1F), + !CONTROLS.contains(0x20), + !CONTROLS.contains(0x7E), + CONTROLS.contains(0x7F), +} + +/// Everything that is not an ASCII letter or digit. +/// +/// This is probably more eager than necessary in any context. +pub const NON_ALPHANUMERIC: &AsciiSet = &CONTROLS + .add(b' ') + .add(b'!') + .add(b'"') + .add(b'#') + .add(b'$') + .add(b'%') + .add(b'&') + .add(b'\'') + .add(b'(') + .add(b')') + .add(b'*') + .add(b'+') + .add(b',') + .add(b'-') + .add(b'.') + .add(b'/') + .add(b':') + .add(b';') + .add(b'<') + .add(b'=') + .add(b'>') + .add(b'?') + .add(b'@') + .add(b'[') + .add(b'\\') + .add(b']') + .add(b'^') + .add(b'_') + .add(b'`') + .add(b'{') + .add(b'|') + .add(b'}') + .add(b'~'); + +/// Return the percent-encoding of the given byte. +/// +/// This is unconditional, unlike `percent_encode()` which has an `AsciiSet` parameter. +/// +/// # Examples +/// +/// ``` +/// use percent_encoding::percent_encode_byte; +/// +/// assert_eq!("foo bar".bytes().map(percent_encode_byte).collect::(), +/// "%66%6F%6F%20%62%61%72"); +/// ``` +pub fn percent_encode_byte(byte: u8) -> &'static str { + let index = usize::from(byte) * 3; + &"\ + %00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F\ + %10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F\ + %20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F\ + %30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F\ + %40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F\ + %50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F\ + %60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F\ + %70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F\ + %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F\ + %90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F\ + %A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF\ + %B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF\ + %C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF\ + %D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF\ + %E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF\ + %F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF\ + "[index..index + 3] +} + +/// Percent-encode the given bytes with the given set. +/// +/// Non-ASCII bytes and bytes in `ascii_set` are encoded. +/// +/// The return type: +/// +/// * Implements `Iterator` and therefore has a `.collect::()` method, +/// * Implements `Display` and therefore has a `.to_string()` method, +/// * Implements `Into>` borrowing `input` when none of its bytes are encoded. +/// +/// # Examples +/// +/// ``` +/// use percent_encoding::{percent_encode, NON_ALPHANUMERIC}; +/// +/// assert_eq!(percent_encode(b"foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F"); +/// ``` +#[inline] +pub fn percent_encode<'a>(input: &'a [u8], ascii_set: &'static AsciiSet) -> PercentEncode<'a> { + PercentEncode { + bytes: input, + ascii_set, + } +} + +/// Percent-encode the UTF-8 encoding of the given string. +/// +/// See [`percent_encode`] regarding the return type. +/// +/// # Examples +/// +/// ``` +/// use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC}; +/// +/// assert_eq!(utf8_percent_encode("foo bar?", NON_ALPHANUMERIC).to_string(), "foo%20bar%3F"); +/// ``` +#[inline] +pub fn utf8_percent_encode<'a>(input: &'a str, ascii_set: &'static AsciiSet) -> PercentEncode<'a> { + percent_encode(input.as_bytes(), ascii_set) +} + +/// The return type of [`percent_encode`] and [`utf8_percent_encode`]. +#[derive(Clone)] +pub struct PercentEncode<'a> { + bytes: &'a [u8], + ascii_set: &'static AsciiSet, +} + +impl<'a> Iterator for PercentEncode<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option<&'a str> { + if let Some((&first_byte, remaining)) = self.bytes.split_first() { + if self.ascii_set.should_percent_encode(first_byte) { + self.bytes = remaining; + Some(percent_encode_byte(first_byte)) + } else { + for (i, &byte) in remaining.iter().enumerate() { + if self.ascii_set.should_percent_encode(byte) { + // 1 for first_byte + i for previous iterations of this loop + let (unchanged_slice, remaining) = self.bytes.split_at(1 + i); + self.bytes = remaining; + return Some(unsafe { str::from_utf8_unchecked(unchanged_slice) }); + } + } + let unchanged_slice = self.bytes; + self.bytes = &[][..]; + Some(unsafe { str::from_utf8_unchecked(unchanged_slice) }) + } + } else { + None + } + } + + fn size_hint(&self) -> (usize, Option) { + if self.bytes.is_empty() { + (0, Some(0)) + } else { + (1, Some(self.bytes.len())) + } + } +} + +impl<'a> fmt::Display for PercentEncode<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + for c in (*self).clone() { + formatter.write_str(c)? + } + Ok(()) + } +} + +impl<'a> From> for Cow<'a, str> { + fn from(mut iter: PercentEncode<'a>) -> Self { + match iter.next() { + None => "".into(), + Some(first) => match iter.next() { + None => first.into(), + Some(second) => { + let mut string = first.to_owned(); + string.push_str(second); + string.extend(iter); + string.into() + } + }, + } + } +} + +/// Percent-decode the given string. +/// +/// +/// +/// See [`percent_decode`] regarding the return type. +#[inline] +pub fn percent_decode_str(input: &str) -> PercentDecode { + percent_decode(input.as_bytes()) +} + +/// Percent-decode the given bytes. +/// +/// +/// +/// Any sequence of `%` followed by two hexadecimal digits is decoded. +/// The return type: +/// +/// * Implements `Into>` borrowing `input` when it contains no percent-encoded sequence, +/// * Implements `Iterator` and therefore has a `.collect::>()` method, +/// * Has `decode_utf8()` and `decode_utf8_lossy()` methods. +/// +/// # Examples +/// +/// ``` +/// use percent_encoding::percent_decode; +/// +/// assert_eq!(percent_decode(b"foo%20bar%3f").decode_utf8().unwrap(), "foo bar?"); +/// ``` +#[inline] +pub fn percent_decode(input: &[u8]) -> PercentDecode { + PercentDecode { + bytes: input.iter(), + } +} + +/// The return type of [`percent_decode`]. +#[derive(Clone, Debug)] +pub struct PercentDecode<'a> { + bytes: slice::Iter<'a, u8>, +} + +fn after_percent_sign(iter: &mut slice::Iter) -> Option { + let mut cloned_iter = iter.clone(); + let h = char::from(*cloned_iter.next()?).to_digit(16)?; + let l = char::from(*cloned_iter.next()?).to_digit(16)?; + *iter = cloned_iter; + Some(h as u8 * 0x10 + l as u8) +} + +impl<'a> Iterator for PercentDecode<'a> { + type Item = u8; + + fn next(&mut self) -> Option { + self.bytes.next().map(|&byte| { + if byte == b'%' { + after_percent_sign(&mut self.bytes).unwrap_or(byte) + } else { + byte + } + }) + } + + fn size_hint(&self) -> (usize, Option) { + let bytes = self.bytes.len(); + (bytes / 3, Some(bytes)) + } +} + +impl<'a> From> for Cow<'a, [u8]> { + fn from(iter: PercentDecode<'a>) -> Self { + match iter.if_any() { + Some(vec) => Cow::Owned(vec), + None => Cow::Borrowed(iter.bytes.as_slice()), + } + } +} + +impl<'a> PercentDecode<'a> { + /// If the percent-decoding is different from the input, return it as a new bytes vector. + fn if_any(&self) -> Option> { + let mut bytes_iter = self.bytes.clone(); + while bytes_iter.any(|&b| b == b'%') { + if let Some(decoded_byte) = after_percent_sign(&mut bytes_iter) { + let initial_bytes = self.bytes.as_slice(); + let unchanged_bytes_len = initial_bytes.len() - bytes_iter.len() - 3; + let mut decoded = initial_bytes[..unchanged_bytes_len].to_owned(); + decoded.push(decoded_byte); + decoded.extend(PercentDecode { bytes: bytes_iter }); + return Some(decoded); + } + } + // Nothing to decode + None + } + + /// Decode the result of percent-decoding as UTF-8. + /// + /// This is return `Err` when the percent-decoded bytes are not well-formed in UTF-8. + pub fn decode_utf8(self) -> Result, str::Utf8Error> { + match self.clone().into() { + Cow::Borrowed(bytes) => match str::from_utf8(bytes) { + Ok(s) => Ok(s.into()), + Err(e) => Err(e), + }, + Cow::Owned(bytes) => match String::from_utf8(bytes) { + Ok(s) => Ok(s.into()), + Err(e) => Err(e.utf8_error()), + }, + } + } + + /// Decode the result of percent-decoding as UTF-8, lossily. + /// + /// Invalid UTF-8 percent-encoded byte sequences will be replaced � U+FFFD, + /// the replacement character. + pub fn decode_utf8_lossy(self) -> Cow<'a, str> { + decode_utf8_lossy(self.clone().into()) + } +} + +fn decode_utf8_lossy(input: Cow<[u8]>) -> Cow { + match input { + Cow::Borrowed(bytes) => String::from_utf8_lossy(bytes), + Cow::Owned(bytes) => { + let raw_utf8: *const [u8]; + match String::from_utf8_lossy(&bytes) { + Cow::Borrowed(utf8) => raw_utf8 = utf8.as_bytes(), + Cow::Owned(s) => return s.into(), + } + // from_utf8_lossy returned a borrow of `bytes` unchanged. + debug_assert!(raw_utf8 == &*bytes as *const [u8]); + // Reuse the existing `Vec` allocation. + unsafe { String::from_utf8_unchecked(bytes) }.into() + } + } +} diff --git a/third_party/cargo/vendor/rand-0.5.6/.cargo-checksum.json b/third_party/cargo/vendor/rand-0.5.6/.cargo-checksum.json deleted file mode 100644 index a5c9a91..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"f5372c19151008367e30b37ced248ed2aac4ba74294204cf657070f54d405aac","CONTRIBUTING.md":"ce1d116f2991f195479a217ecad883e65812d739476ce313adbbed16425e9730","Cargo.toml":"226ebec959d588987fb0006d0ad708dd2a21a48ab70fd4581079a13c1a513203","LICENSE-APACHE":"aaff376532ea30a0cd5330b9502ad4a4c8bf769c539c87ffe78819d188a18ebf","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"2a9b60793f4b06217710ba574fb266850f64d265359c00d06ab05e0e3f4b7bb3","UPDATING.md":"995b503e4e25662c63df1710ca557e9688e1095644a4de80c6d19a2aa4281f2d","appveyor.yml":"e72b9bf8fa81ec7bc8939da12f51df6de946b93246542cf1f538ff1119497de6","benches/distributions.rs":"041c5adb223ee3a42bf6d5841e123ed1ea24838463bf88c29a5cb5a5dcfb320b","benches/generators.rs":"ef5e38c2462f9fb6dfeb7892061123b668826404a4546463bf34a8a939b39d1b","benches/misc.rs":"674e06347bc95cdd14588fefa673dbbc52d043b8e93d2bd56ee2fc9ad030d570","examples/monte-carlo.rs":"5b52e0dff8b2c29b2037c1f93f703e1c203d05b884640db99520137307fd9d6e","examples/monty-hall.rs":"d4873d567a606822dcb2be7e06517144f44d0d0ec39990751756b6265acaa88c","src/distributions/bernoulli.rs":"3a8dbab7dc97e6ad8d3225857dd6413e44a78d49ff870c25b1cd2c3bf7fdb6c3","src/distributions/binomial.rs":"38e46f348097920583707d86ec30522fb816355f216fd2a97fb427a5ed03c860","src/distributions/cauchy.rs":"a075e8e4d181bac25136a80f2af6cdc8b6d60c6d16df5b67a5181ea00ae3a34e","src/distributions/exponential.rs":"1702c7640d6027c49913d7e46b12c292646f9f4007ef74ba238c582de47014ee","src/distributions/float.rs":"0d0e79423d002a3187a7dec73e11e5acd9060590e71a3e39ca44375cafc687d4","src/distributions/gamma.rs":"8763faa2f6a244ea95d5af2b1e48ec8ddd1983eb4e170cf873c513fc8bc0746c","src/distributions/integer.rs":"a9c9edda09a457831c06e93ce94e7074af5bf97fd663a940b2f09ea21b1106a9","src/distributions/log_gamma.rs":"9f1fda43162c3f6184af15e9fabf3475de7e4e2e46412e7ae1480de1c7e5a68e","src/distributions/mod.rs":"3b7d190ce0d0c60fabac2902538116af27c5fa9291899287d281e2a16a8078bb","src/distributions/normal.rs":"987dc08c94e33f4f07e227d3b887d3cb522ddc6439bb93adcd0daf9b64097900","src/distributions/other.rs":"9962a738ed861d6c59e46272401290eca4237862127b3a143c7865616d9c1bed","src/distributions/pareto.rs":"ba207487d655295db7a566fec97ed636f0bcf4e50642138da553fd58e613cefe","src/distributions/poisson.rs":"3a44644936dea768ef83b45c9be86626356c67fc72f48f10d72111428ad77ddf","src/distributions/uniform.rs":"6cc7b9916e72a5807a9f7fdd90cb2944e9d175570758a507d6ce5779abda5a45","src/distributions/ziggurat_tables.rs":"4757d144fd1fc13fc0118e073f9ecf2a3cc94144a254a6633900705c3d9f7db3","src/lib.rs":"1560e7529869bc73603410a76a9d9c434953288d06c9743c4dd0d4f5d7438b94","src/prelude.rs":"a2f76c76bc2c7822bb4ce67ba13b076305b434a542aaa5f07b67f66f65e3e8cc","src/prng/chacha.rs":"f8659eb5beceb19e582f81050584007f6893b537da60e697fa04b1302a1e161f","src/prng/hc128.rs":"0b44d4877159ee82109fcd4415635db6baf27db1381598b0f18cecb7841c975c","src/prng/isaac.rs":"e8b9ee17f39c38b51fd2baeedc130979a81ff4b963a1016f57e78ffc16fb0d3f","src/prng/isaac64.rs":"32a1fee407b95349ff115e7bd9768214f953664124e577f62388a7bc5c129051","src/prng/isaac_array.rs":"9371fcd04f29aa21b10a6bba76949853d8a80b72fbb5c61ba9b0d9db8d6bbb3c","src/prng/mod.rs":"1055528c5755d280ef9e420615e69dde35f8267c7cf20d178b75145a722ad462","src/prng/xorshift.rs":"dacb87577d3faafe5a5333c7e4eae6cab5a9f23eef68069a9b7195dfd74a2901","src/rngs/adapter/mod.rs":"1f956553588693682d29be3a61385a6738d0c682719138a32460407aa626d5a3","src/rngs/adapter/read.rs":"72000e758119093ca090b281a5d2e76981e218175162c8502ceaff021b706198","src/rngs/adapter/reseeding.rs":"0b0ad2f47fba9d5aa787c7c2284d7f0dc9464830a63a3347a63270c011b1a1a5","src/rngs/entropy.rs":"8024dde0ae9fa5a87235c7fb09568c59f2a1fcab86324992192ed3e6c5eed7eb","src/rngs/jitter.rs":"24797e2fb6c7f2fa896b824591a74841fe1e5da980725161ab03882404ffd13a","src/rngs/mock.rs":"5ce40a4da78a623dd379035ccb2bc58e713508d0db0e89098dc362f7d7fbb4e3","src/rngs/mod.rs":"a6d2fba84dd76a96f43ba4a47b7ad067625f3acaeb3c532edbc82b9222f62a92","src/rngs/os.rs":"cf38bed5e8af7e1f1838cf8d3d5abf00702fc05aee34dd3e7d1b6ab8f1bafa2c","src/rngs/small.rs":"a6d51c0066e225bcab8a563b26a0f1b8a555ef1e3aca20210b6cd38513f08c8a","src/rngs/std.rs":"a38628a9bb2ed68daa9f9288380f274713f035b27f287e67a310c5bb4cb14f97","src/rngs/thread.rs":"645cfaa31458ad20d0bebc12a0f1aa4a6a3b00bcc6a446c5e232a14c6a396329","src/seq.rs":"124236e85d71c9cc7a8d065b45f0746cddc1a2af997d34abf664cfdab7354e81","tests/bool.rs":"b57dd7c6e597383f7f84a172cd29e85246475f2686159ca6aa61c52989f762ba","utils/ci/install.sh":"cbc29da047c6e516ff5d13731c8b07812fd40986e7b19b61a7c5deaf5d6ffdd0","utils/ci/script.sh":"309a982ecc8f5669cc1a9d0d67e0f743f3969f1a5a49e8285966ab5518767c43","utils/ziggurat_tables.py":"97d156574ad51465dd023ee63a3fbb52a5603963b09f3f30a50cdfd2bbf1a1e1"},"package":"c618c47cd3ebd209790115ab837de41425723956ad3ce2e6a7f09890947cacb9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/rand-0.5.6/BUILD b/third_party/cargo/vendor/rand-0.5.6/BUILD deleted file mode 100644 index 7433422..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/BUILD +++ /dev/null @@ -1,57 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "MIT,Apache-2.0" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - -# Unsupported target "bool" with type "test" omitted -# Unsupported target "distributions" with type "bench" omitted -# Unsupported target "generators" with type "bench" omitted -# Unsupported target "misc" with type "bench" omitted -# Unsupported target "monte-carlo" with type "example" omitted -# Unsupported target "monty-hall" with type "example" omitted - -rust_library( - name = "rand", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2015", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/libc-0.2.67:libc", - "//third_party/cargo/vendor/rand_core-0.3.1:rand_core", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.5.6", - crate_features = [ - "alloc", - "cloudabi", - "default", - "fuchsia-cprng", - "libc", - "std", - "winapi", - ], -) - diff --git a/third_party/cargo/vendor/rand-0.5.6/CHANGELOG.md b/third_party/cargo/vendor/rand-0.5.6/CHANGELOG.md deleted file mode 100644 index 4a09a5d..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/CHANGELOG.md +++ /dev/null @@ -1,422 +0,0 @@ -# Changelog -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -A [separate changelog is kept for rand_core](rand_core/CHANGELOG.md). - -You may also find the [Update Guide](UPDATING.md) useful. - - -## [0.5.6] - 2019-01-25 -### Platforms -- Fuchsia: Replaced fuchsia-zircon with fuchsia-cprng - - -## [0.5.5] - 2018-08-07 -### Documentation -- Fix links in documentation (#582) - - -## [0.5.4] - 2018-07-11 -### Platform support -- Make `OsRng` work via WASM/stdweb for WebWorkers - - -## [0.5.3] - 2018-06-26 -### Platform support -- OpenBSD, Bitrig: fix compilation (broken in 0.5.1) (#530) - - -## [0.5.2] - 2018-06-18 -### Platform support -- Hide `OsRng` and `JitterRng` on unsupported platforms (#512; fixes #503). - - -## [0.5.1] - 2018-06-08 - -### New distributions -- Added Cauchy distribution. (#474, #486) -- Added Pareto distribution. (#495) - -### Platform support and `OsRng` -- Remove blanket Unix implementation. (#484) -- Remove Wasm unimplemented stub. (#484) -- Dragonfly BSD: read from `/dev/random`. (#484) -- Bitrig: use `getentropy` like OpenBSD. (#484) -- Solaris: (untested) use `getrandom` if available, otherwise `/dev/random`. (#484) -- Emscripten, `stdweb`: split the read up in chunks. (#484) -- Emscripten, Haiku: don't do an extra blocking read from `/dev/random`. (#484) -- Linux, NetBSD, Solaris: read in blocking mode on first use in `fill_bytes`. (#484) -- Fuchsia, CloudABI: fix compilation (broken in Rand 0.5). (#484) - - -## [0.5.0] - 2018-05-21 - -### Crate features and organisation -- Minimum Rust version update: 1.22.0. (#239) -- Create a separate `rand_core` crate. (#288) -- Deprecate `rand_derive`. (#256) -- Add `prelude` (and module reorganisation). (#435) -- Add `log` feature. Logging is now available in `JitterRng`, `OsRng`, `EntropyRng` and `ReseedingRng`. (#246) -- Add `serde1` feature for some PRNGs. (#189) -- `stdweb` feature for `OsRng` support on WASM via stdweb. (#272, #336) - -### `Rng` trait -- Split `Rng` in `RngCore` and `Rng` extension trait. - `next_u32`, `next_u64` and `fill_bytes` are now part of `RngCore`. (#265) -- Add `Rng::sample`. (#256) -- Deprecate `Rng::gen_weighted_bool`. (#308) -- Add `Rng::gen_bool`. (#308) -- Remove `Rng::next_f32` and `Rng::next_f64`. (#273) -- Add optimized `Rng::fill` and `Rng::try_fill` methods. (#247) -- Deprecate `Rng::gen_iter`. (#286) -- Deprecate `Rng::gen_ascii_chars`. (#279) - -### `rand_core` crate -- `rand` now depends on new `rand_core` crate (#288) -- `RngCore` and `SeedableRng` are now part of `rand_core`. (#288) -- Add modules to help implementing RNGs `impl` and `le`. (#209, #228) -- Add `Error` and `ErrorKind`. (#225) -- Add `CryptoRng` marker trait. (#273) -- Add `BlockRngCore` trait. (#281) -- Add `BlockRng` and `BlockRng64` wrappers to help implementations. (#281, #325) -- Revise the `SeedableRng` trait. (#233) -- Remove default implementations for `RngCore::next_u64` and `RngCore::fill_bytes`. (#288) -- Add `RngCore::try_fill_bytes`. (#225) - -### Other traits and types -- Add `FromEntropy` trait. (#233, #375) -- Add `SmallRng` wrapper. (#296) -- Rewrite `ReseedingRng` to only work with `BlockRngCore` (substantial performance improvement). (#281) -- Deprecate `weak_rng`. Use `SmallRng` instead. (#296) -- Deprecate `AsciiGenerator`. (#279) - -### Random number generators -- Switch `StdRng` and `thread_rng` to HC-128. (#277) -- `StdRng` must now be created with `from_entropy` instead of `new` -- Change `thread_rng` reseeding threshold to 32 MiB. (#277) -- PRNGs no longer implement `Copy`. (#209) -- `Debug` implementations no longer show internals. (#209) -- Implement `Clone` for `ReseedingRng`, `JitterRng`, OsRng`. (#383, #384) -- Implement serialization for `XorShiftRng`, `IsaacRng` and `Isaac64Rng` under the `serde1` feature. (#189) -- Implement `BlockRngCore` for `ChaChaCore` and `Hc128Core`. (#281) -- All PRNGs are now portable across big- and little-endian architectures. (#209) -- `Isaac64Rng::next_u32` no longer throws away half the results. (#209) -- Add `IsaacRng::new_from_u64` and `Isaac64Rng::new_from_u64`. (#209) -- Add the HC-128 CSPRNG `Hc128Rng`. (#210) -- Change ChaCha20 to have 64-bit counter and 64-bit stream. (#349) -- Changes to `JitterRng` to get its size down from 2112 to 24 bytes. (#251) -- Various performance improvements to all PRNGs. - -### Platform support and `OsRng` -- Add support for CloudABI. (#224) -- Remove support for NaCl. (#225) -- WASM support for `OsRng` via stdweb, behind the `stdweb` feature. (#272, #336) -- Use `getrandom` on more platforms for Linux, and on Android. (#338) -- Use the `SecRandomCopyBytes` interface on macOS. (#322) -- On systems that do not have a syscall interface, only keep a single file descriptor open for `OsRng`. (#239) -- On Unix, first try a single read from `/dev/random`, then `/dev/urandom`. (#338) -- Better error handling and reporting in `OsRng` (using new error type). (#225) -- `OsRng` now uses non-blocking when available. (#225) -- Add `EntropyRng`, which provides `OsRng`, but has `JitterRng` as a fallback. (#235) - -### Distributions -- New `Distribution` trait. (#256) -- Add `Distribution::sample_iter` and `Rng::::sample_iter`. (#361) -- Deprecate `Rand`, `Sample` and `IndependentSample` traits. (#256) -- Add a `Standard` distribution (replaces most `Rand` implementations). (#256) -- Add `Binomial` and `Poisson` distributions. (#96) -- Add `Bernoulli` dsitribution. (#411) -- Add `Alphanumeric` distribution. (#279) -- Remove `Closed01` distribution, add `OpenClosed01`. (#274, #420) -- Rework `Range` type, making it possible to implement it for user types. (#274) -- Rename `Range` to `Uniform`. (#395) -- Add `Uniform::new_inclusive` for inclusive ranges. (#274) -- Use widening multiply method for much faster integer range reduction. (#274) -- `Standard` distribution for `char` uses `Uniform` internally. (#274) -- `Standard` distribution for `bool` uses sign test. (#274) -- Implement `Standard` distribution for `Wrapping`. (#436) -- Implement `Uniform` distribution for `Duration`. (#427) - - -## [0.4.3] - 2018-08-16 -### Fixed -- Use correct syscall number for PowerPC (#589) - - -## [0.4.2] - 2018-01-06 -### Changed -- Use `winapi` on Windows -- Update for Fuchsia OS -- Remove dev-dependency on `log` - - -## [0.4.1] - 2017-12-17 -### Added -- `no_std` support - - -## [0.4.0-pre.0] - 2017-12-11 -### Added -- `JitterRng` added as a high-quality alternative entropy source using the - system timer -- new `seq` module with `sample_iter`, `sample_slice`, etc. -- WASM support via dummy implementations (fail at run-time) -- Additional benchmarks, covering generators and new seq code - -### Changed -- `thread_rng` uses `JitterRng` if seeding from system time fails - (slower but more secure than previous method) - -### Deprecated - - `sample` function deprecated (replaced by `sample_iter`) - - -## [0.3.20] - 2018-01-06 -### Changed -- Remove dev-dependency on `log` -- Update `fuchsia-zircon` dependency to 0.3.2 - - -## [0.3.19] - 2017-12-27 -### Changed -- Require `log <= 0.3.8` for dev builds -- Update `fuchsia-zircon` dependency to 0.3 -- Fix broken links in docs (to unblock compiler docs testing CI) - - -## [0.3.18] - 2017-11-06 -### Changed -- `thread_rng` is seeded from the system time if `OsRng` fails -- `weak_rng` now uses `thread_rng` internally - - -## [0.3.17] - 2017-10-07 -### Changed - - Fuchsia: Magenta was renamed Zircon - -## [0.3.16] - 2017-07-27 -### Added -- Implement Debug for mote non-public types -- implement `Rand` for (i|u)i128 -- Support for Fuchsia - -### Changed -- Add inline attribute to SampleRange::construct_range. - This improves the benchmark for sample in 11% and for shuffle in 16%. -- Use `RtlGenRandom` instead of `CryptGenRandom` - - -## [0.3.15] - 2016-11-26 -### Added -- Add `Rng` trait method `choose_mut` -- Redox support - -### Changed -- Use `arc4rand` for `OsRng` on FreeBSD. -- Use `arc4random(3)` for `OsRng` on OpenBSD. - -### Fixed -- Fix filling buffers 4 GiB or larger with `OsRng::fill_bytes` on Windows - - -## [0.3.14] - 2016-02-13 -### Fixed -- Inline definitions from winapi/advapi32, wich decreases build times - - -## [0.3.13] - 2016-01-09 -### Fixed -- Compatible with Rust 1.7.0-nightly (needed some extra type annotations) - - -## [0.3.12] - 2015-11-09 -### Changed -- Replaced the methods in `next_f32` and `next_f64` with the technique described - Saito & Matsumoto at MCQMC'08. The new method should exhibit a slightly more - uniform distribution. -- Depend on libc 0.2 - -### Fixed -- Fix iterator protocol issue in `rand::sample` - - -## [0.3.11] - 2015-08-31 -### Added -- Implement `Rand` for arrays with n <= 32 - - -## [0.3.10] - 2015-08-17 -### Added -- Support for NaCl platforms - -### Changed -- Allow `Rng` to be `?Sized`, impl for `&mut R` and `Box` where `R: ?Sized + Rng` - - -## [0.3.9] - 2015-06-18 -### Changed -- Use `winapi` for Windows API things - -### Fixed -- Fixed test on stable/nightly -- Fix `getrandom` syscall number for aarch64-unknown-linux-gnu - - -## [0.3.8] - 2015-04-23 -### Changed -- `log` is a dev dependency - -### Fixed -- Fix race condition of atomics in `is_getrandom_available` - - -## [0.3.7] - 2015-04-03 -### Fixed -- Derive Copy/Clone changes - - -## [0.3.6] - 2015-04-02 -### Changed -- Move to stable Rust! - - -## [0.3.5] - 2015-04-01 -### Fixed -- Compatible with Rust master - - -## [0.3.4] - 2015-03-31 -### Added -- Implement Clone for `Weighted` - -### Fixed -- Compatible with Rust master - - -## [0.3.3] - 2015-03-26 -### Fixed -- Fix compile on Windows - - -## [0.3.2] - 2015-03-26 - - -## [0.3.1] - 2015-03-26 -### Fixed -- Fix compile on Windows - - -## [0.3.0] - 2015-03-25 -### Changed -- Update to use log version 0.3.x - - -## [0.2.1] - 2015-03-22 -### Fixed -- Compatible with Rust master -- Fixed iOS compilation - - -## [0.2.0] - 2015-03-06 -### Fixed -- Compatible with Rust master (move from `old_io` to `std::io`) - - -## [0.1.4] - 2015-03-04 -### Fixed -- Compatible with Rust master (use wrapping ops) - - -## [0.1.3] - 2015-02-20 -### Fixed -- Compatible with Rust master - -### Removed -- Removed Copy implementations from RNGs - - -## [0.1.2] - 2015-02-03 -### Added -- Imported functionality from `std::rand`, including: - - `StdRng`, `SeedableRng`, `TreadRng`, `weak_rng()` - - `ReaderRng`: A wrapper around any Reader to treat it as an RNG. -- Imported documentation from `std::rand` -- Imported tests from `std::rand` - - -## [0.1.1] - 2015-02-03 -### Added -- Migrate to a cargo-compatible directory structure. - -### Fixed -- Do not use entropy during `gen_weighted_bool(1)` - - -## [Rust 0.12.0] - 2014-10-09 -### Added -- Impl Rand for tuples of arity 11 and 12 -- Include ChaCha pseudorandom generator -- Add `next_f64` and `next_f32` to Rng -- Implement Clone for PRNGs - -### Changed -- Rename `TaskRng` to `ThreadRng` and `task_rng` to `thread_rng` (since a - runtime is removed from Rust). - -### Fixed -- Improved performance of ISAAC and ISAAC64 by 30% and 12 % respectively, by - informing the optimiser that indexing is never out-of-bounds. - -### Removed -- Removed the Deprecated `choose_option` - - -## [Rust 0.11.0] - 2014-07-02 -### Added -- document when to use `OSRng` in cryptographic context, and explain why we use `/dev/urandom` instead of `/dev/random` -- `Rng::gen_iter()` which will return an infinite stream of random values -- `Rng::gen_ascii_chars()` which will return an infinite stream of random ascii characters - -### Changed -- Now only depends on libcore! -- Remove `Rng.choose()`, rename `Rng.choose_option()` to `.choose()` -- Rename OSRng to OsRng -- The WeightedChoice structure is no longer built with a `Vec>`, - but rather a `&mut [Weighted]`. This means that the WeightedChoice - structure now has a lifetime associated with it. -- The `sample` method on `Rng` has been moved to a top-level function in the - `rand` module due to its dependence on `Vec`. - -### Removed -- `Rng::gen_vec()` was removed. Previous behavior can be regained with - `rng.gen_iter().take(n).collect()` -- `Rng::gen_ascii_str()` was removed. Previous behavior can be regained with - `rng.gen_ascii_chars().take(n).collect()` -- {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all - relied on being able to use an OSRng for seeding, but this is no longer - available in librand (where these types are defined). To retain the same - functionality, these types now implement the `Rand` trait so they can be - generated with a random seed from another random number generator. This allows - the stdlib to use an OSRng to create seeded instances of these RNGs. -- Rand implementations for `Box` and `@T` were removed. These seemed to be - pretty rare in the codebase, and it allows for librand to not depend on - liballoc. Additionally, other pointer types like Rc and Arc were not - supported. -- Remove a slew of old deprecated functions - - -## [Rust 0.10] - 2014-04-03 -### Changed -- replace `Rng.shuffle's` functionality with `.shuffle_mut` -- bubble up IO errors when creating an OSRng - -### Fixed -- Use `fill()` instead of `read()` -- Rewrite OsRng in Rust for windows - -## [0.10-pre] - 2014-03-02 -### Added -- Seperate `rand` out of the standard library diff --git a/third_party/cargo/vendor/rand-0.5.6/CONTRIBUTING.md b/third_party/cargo/vendor/rand-0.5.6/CONTRIBUTING.md deleted file mode 100644 index 37c1a9d..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/CONTRIBUTING.md +++ /dev/null @@ -1,93 +0,0 @@ -# Contributing to Rand - -Thank you for your interest in contributing to Rand! - -The following is a list of notes and tips for when you want to contribute to -Rand with a pull request. - -If you want to make major changes, it is usually best to open an issue to -discuss the idea first. - -Rand doesn't (yet) use rustfmt. It is best to follow the style of the -surrounding code, and try to keep an 80 character line limit. - - -## Documentation - -We especially welcome documentation PRs. - -As of Rust 1.25 there are differences in how stable and nightly render -documentation links. Make sure it works on stable, then nightly should be good -too. One Travis CI build checks for dead links using `cargo-deadlinks`. If you -want to run the check locally: -```sh -cargo install cargo-deadlinks -# It is recommended to remove left-over files from previous compilations -rm -rf /target/doc -cargo doc --no-deps -cargo deadlinks --dir target/doc -``` - -When making changes to code examples in the documentation, make sure they build -with: -```sh -cargo test --doc -``` - -A helpful command to rebuild documentation automatically on save (only works on -Linux): -``` -while inotifywait -r -e close_write src/ rand_core/; do cargo doc; done -``` - - -## Testing - -Rand already contains a number of unit tests, but could use more. Also the -existing ones could use clean-up. Any work on the tests is appreciated. - -Not every change or new bit of functionality requires tests, but if you can -think of a test that adds value, please add it. - -Depending on the code you change, test with one of: -```sh -cargo test -cargo test --package rand_core -# Test log, serde and 128-bit support -cargo test --features serde1,log,nightly -``` - -We want to be able to not only run the unit tests with `std` available, but also -without. Because `thread_rng()` and `FromEntropy` are not available without the -`std` feature, you may have to disable a new test with `#[cfg(feature="std")]`. -In other cases using `::test::rng` with a constant seed is a good option: -```rust -let mut rng = ::test::rng(528); // just pick some number -``` - -Only the unit tests should work in `no_std` mode, we don't want to complicate -the doc-tests. Run the tests with: -```sh -# Test no_std support -cargo test --lib --no-default-features -cargo test --package rand_core --no-default-features - -# Test no_std+alloc support; requires nightly -cargo test --lib --no-default-features --features alloc -``` - - -## Benchmarking - -A lot of code in Rand is performance-sensitive, most of it is expected to be -used in hot loops in some libraries/applications. If you change code in the -`rngs`, `prngs` or `distributions` modules, especially when you see an 'obvious -cleanup', make sure the benchmarks do not regress. It is nice to report the -benchmark results in the PR (or to report nothing's changed). - -```sh -# Benchmarks (requires nightly) -cargo bench -# Some benchmarks have a faster path with i128_support -cargo bench --features=nightly -``` diff --git a/third_party/cargo/vendor/rand-0.5.6/Cargo.toml b/third_party/cargo/vendor/rand-0.5.6/Cargo.toml deleted file mode 100644 index 32d6ef0..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/Cargo.toml +++ /dev/null @@ -1,72 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "rand" -version = "0.5.6" -authors = ["The Rust Project Developers"] -description = "Random number generators and other randomness functionality.\n" -homepage = "https://crates.io/crates/rand" -documentation = "https://docs.rs/rand" -readme = "README.md" -keywords = ["random", "rng"] -categories = ["algorithms", "no-std"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang-nursery/rand" -[package.metadata.docs.rs] -all-features = true -[dependencies.log] -version = "0.4" -optional = true - -[dependencies.rand_core] -version = "0.3" -default-features = false - -[dependencies.serde] -version = "1" -optional = true - -[dependencies.serde_derive] -version = "1" -optional = true -[dev-dependencies.bincode] -version = "1.0" - -[features] -alloc = ["rand_core/alloc"] -default = ["std"] -i128_support = [] -nightly = ["i128_support"] -serde1 = ["serde", "serde_derive", "rand_core/serde1"] -std = ["rand_core/std", "alloc", "libc", "winapi", "cloudabi", "fuchsia-cprng"] -[target."cfg(target_os = \"cloudabi\")".dependencies.cloudabi] -version = "0.0.3" -optional = true -[target."cfg(target_os = \"fuchsia\")".dependencies.fuchsia-cprng] -version = "0.1.0" -optional = true -[target."cfg(unix)".dependencies.libc] -version = "0.2" -optional = true -[target."cfg(windows)".dependencies.winapi] -version = "0.3" -features = ["minwindef", "ntsecapi", "profileapi", "winnt"] -optional = true -[target.wasm32-unknown-unknown.dependencies.stdweb] -version = "0.4" -optional = true -[badges.appveyor] -repository = "alexcrichton/rand" - -[badges.travis-ci] -repository = "rust-lang-nursery/rand" diff --git a/third_party/cargo/vendor/rand-0.5.6/LICENSE-APACHE b/third_party/cargo/vendor/rand-0.5.6/LICENSE-APACHE deleted file mode 100644 index 17d7468..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/cargo/vendor/rand-0.5.6/README.md b/third_party/cargo/vendor/rand-0.5.6/README.md deleted file mode 100644 index 75950ed..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/README.md +++ /dev/null @@ -1,143 +0,0 @@ -# Rand - -[![Build Status](https://travis-ci.org/rust-lang-nursery/rand.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/rand) -[![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-lang-nursery/rand?svg=true)](https://ci.appveyor.com/project/alexcrichton/rand) -[![Latest version](https://img.shields.io/crates/v/rand.svg)](https://crates.io/crates/rand) -[![Documentation](https://docs.rs/rand/badge.svg)](https://docs.rs/rand) -[![Minimum rustc version](https://img.shields.io/badge/rustc-1.22+-yellow.svg)](https://github.com/rust-lang-nursery/rand#rust-version-requirements) - -A Rust library for random number generation. - -Rand provides utilities to generate random numbers, to convert them to useful -types and distributions, and some randomness-related algorithms. - -The core random number generation traits of Rand live in the [rand_core]( -https://crates.io/crates/rand_core) crate; this crate is most useful when -implementing RNGs. - -API reference: -[master branch](https://rust-lang-nursery.github.io/rand/rand/index.html), -[by release](https://docs.rs/rand/0.5). - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -rand = "0.5" -``` - -and this to your crate root: - -```rust -extern crate rand; - -use rand::prelude::*; - -fn main() { - // basic usage with random(): - let x: u8 = random(); - println!("{}", x); - - let y = random::(); - println!("{}", y); - - if random() { // generates a boolean - println!("Heads!"); - } - - // normal usage needs both an RNG and a function to generate the appropriate - // type, range, distribution, etc. - let mut rng = thread_rng(); - if rng.gen() { // random bool - let x: f64 = rng.gen(); // random number in range [0, 1) - println!("x is: {}", x); - let ch = rng.gen::(); // Sometimes you need type annotation - println!("char is: {}", ch); - println!("Number from 0 to 9: {}", rng.gen_range(0, 10)); - } -} -``` - -## Functionality - -The Rand crate provides: - -- A convenient to use default RNG, `thread_rng`: an automatically seeded, - crypto-grade generator stored in thread-local memory. -- Pseudo-random number generators: `StdRng`, `SmallRng`, `prng` module. -- Functionality for seeding PRNGs: the `FromEntropy` trait, and as sources of - external randomness `EntropyRng`, `OsRng` and `JitterRng`. -- Most content from [`rand_core`](https://crates.io/crates/rand_core) - (re-exported): base random number generator traits and error-reporting types. -- 'Distributions' producing many different types of random values: - - A `Standard` distribution for integers, floats, and derived types including - tuples, arrays and `Option` - - Unbiased sampling from specified `Uniform` ranges. - - Sampling from exponential/normal/gamma distributions. - - Sampling from binomial/poisson distributions. - - `gen_bool` aka Bernoulli distribution. -- `seq`-uence related functionality: - - Sampling a subset of elements. - - Randomly shuffling a list. - - -## Versions - -Version 0.5 is the latest version and contains many breaking changes. -See [the Upgrade Guide](UPDATING.md) for guidance on updating from previous -versions. - -Version 0.4 was released in December 2017. It contains almost no breaking -changes since the 0.3 series. - -For more details, see the [changelog](CHANGELOG.md). - -### Rust version requirements - -The 0.5 release of Rand requires **Rustc version 1.22 or greater**. -Rand 0.4 and 0.3 (since approx. June 2017) require Rustc version 1.15 or -greater. Subsets of the Rand code may work with older Rust versions, but this -is not supported. - -Travis CI always has a build with a pinned version of Rustc matching the oldest -supported Rust release. The current policy is that this can be updated in any -Rand release if required, but the change must be noted in the changelog. - - -## Crate Features - -Rand is built with only the `std` feature enabled by default. The following -optional features are available: - -- `alloc` can be used instead of `std` to provide `Vec` and `Box`. -- `i128_support` enables support for generating `u128` and `i128` values. -- `log` enables some logging via the `log` crate. -- `nightly` enables all unstable features (`i128_support`). -- `serde1` enables serialization for some types, via Serde version 1. -- `stdweb` enables support for `OsRng` on `wasm-unknown-unknown` via `stdweb` - combined with `cargo-web`. - -`no_std` mode is activated by setting `default-features = false`; this removes -functionality depending on `std`: - -- `thread_rng()`, and `random()` are not available, as they require thread-local - storage and an entropy source. -- `OsRng` and `EntropyRng` are unavailable. -- `JitterRng` code is still present, but a nanosecond timer must be provided via - `JitterRng::new_with_timer` -- Since no external entropy is available, it is not possible to create - generators with fresh seeds using the `FromEntropy` trait (user must provide - a seed). -- Exponential, normal and gamma type distributions are unavailable since `exp` - and `log` functions are not provided in `core`. -- The `seq`-uence module is unavailable, as it requires `Vec`. - - -# License - -Rand is distributed under the terms of both the MIT license and the -Apache License (Version 2.0). - -See [LICENSE-APACHE](LICENSE-APACHE) and [LICENSE-MIT](LICENSE-MIT) for details. diff --git a/third_party/cargo/vendor/rand-0.5.6/UPDATING.md b/third_party/cargo/vendor/rand-0.5.6/UPDATING.md deleted file mode 100644 index 09321b7..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/UPDATING.md +++ /dev/null @@ -1,260 +0,0 @@ -# Update Guide - -This guide gives a few more details than the [changelog], in particular giving -guidance on how to use new features and migrate away from old ones. - -[changelog]: CHANGELOG.md - -## Rand 0.5 - -The 0.5 release has quite significant changes over the 0.4 release; as such, -it may be worth reading through the following coverage of breaking changes. -This release also contains many optimisations, which are not detailed below. - -### Crates - -We have a new crate: `rand_core`! This crate houses some important traits, -`RngCore`, `BlockRngCore`, `SeedableRng` and `CryptoRng`, the error types, as -well as two modules with helpers for implementations: `le` and `impls`. It is -recommended that implementations of generators use the `rand_core` crate while -other users use only the `rand` crate, which re-exports most parts of `rand_core`. - -The `rand_derive` crate has been deprecated due to very low usage and -deprecation of `Rand`. - -### Features - -Several new Cargo feature flags have been added: - -- `alloc`, used without `std`, allows use of `Box` and `Vec` -- `serde1` adds serialization support to some PRNGs -- `log` adds logging in a few places (primarily to `OsRng` and `JitterRng`) - -### `Rng` and friends (core traits) - -`Rng` trait has been split into two traits, a "back end" `RngCore` (implemented -by generators) and a "front end" `Rng` implementing all the convenient extension -methods. - -Implementations of generators must `impl RngCore` instead. Usage of `rand_core` -for implementations is encouraged; the `rand_core::{le, impls}` modules may -prove useful. - -Users of `Rng` *who don't need to implement it* won't need to make so many -changes; often users can forget about `RngCore` and only import `Rng`. Instead -of `RngCore::next_u32()` / `next_u64()` users should prefer `Rng::gen()`, and -instead of `RngCore::fill_bytes(dest)`, `Rng::fill(dest)` can be used. - -#### `Rng` / `RngCore` methods - -To allow error handling from fallible sources (e.g. `OsRng`), a new -`RngCore::try_fill_bytes` method has been added; for example `EntropyRng` uses -this mechanism to fall back to `JitterRng` if `OsRng` fails, and various -handlers produce better error messages. -As before, the other methods will panic on failure, but since these are usually -used with algorithmic generators which are usually infallible, this is -considered an appropriate compromise. - -A few methods from the old `Rng` have been removed or deprecated: - -- `next_f32` and `next_f64`; these are no longer implementable by generators; - use `gen` instead -- `gen_iter`; users may instead use standard iterators with closures: - `::std::iter::repeat(()).map(|()| rng.gen())` -- `gen_ascii_chars`; use `repeat` as above and `rng.sample(Alphanumeric)` -- `gen_weighted_bool(n)`; use `gen_bool(1.0 / n)` instead - -`Rng` has a few new methods: - -- `sample(distr)` is a shortcut for `distr.sample(rng)` for any `Distribution` -- `gen_bool(p)` generates a boolean with probability `p` of being true -- `fill` and `try_fill`, corresponding to `fill_bytes` and `try_fill_bytes` - respectively (i.e. the only difference is error handling); these can fill - and integer slice / array directly, and provide better performance - than `gen()` - -#### Constructing PRNGs - -##### New randomly-initialised PRNGs - -A new trait has been added: `FromEntropy`. This is automatically implemented for -any type supporting `SeedableRng`, and provides construction from fresh, strong -entropy: - -```rust -use rand::{ChaChaRng, FromEntropy}; - -let mut rng = ChaChaRng::from_entropy(); -``` - -##### Seeding PRNGs - -The `SeedableRng` trait has been modified to include the seed type via an -associated type (`SeedableRng::Seed`) instead of a template parameter -(`SeedableRng`). Additionally, all PRNGs now seed from a byte-array -(`[u8; N]` for some fixed N). This allows generic handling of PRNG seeding -which was not previously possible. - -PRNGs are no longer constructed from other PRNGs via `Rand` support / `gen()`, -but through `SeedableRng::from_rng`, which allows error handling and is -intentionally explicit. - -`SeedableRng::reseed` has been removed since it has no utility over `from_seed` -and its performance advantage is questionable. - -Implementations of `SeedableRng` may need to change their `Seed` type to a -byte-array; this restriction has been made to ensure portable handling of -Endianness. Helper functions are available in `rand_core::le` to read `u32` and -`u64` values from byte arrays. - -#### Block-based PRNGs - -rand_core has a new helper trait, `BlockRngCore`, and implementation, -`BlockRng`. These are for use by generators which generate a block of random -data at a time instead of word-sized values. Using this trait and implementation -has two advantages: optimised `RngCore` methods are provided, and the PRNG can -be used with `ReseedingRng` with very low overhead. - -#### Cryptographic RNGs - -A new trait has been added: `CryptoRng`. This is purely a marker trait to -indicate which generators should be suitable for cryptography, e.g. -`fn foo(rng: &mut R)`. *Suitability for cryptographic -use cannot be guaranteed.* - -### Error handling - -A new `Error` type has been added, designed explicitly for no-std compatibility, -simplicity, and enough flexibility for our uses (carrying a `cause` when -possible): -```rust -pub struct Error { - pub kind: ErrorKind, - pub msg: &'static str, - // some fields omitted -} -``` -The associated `ErrorKind` allows broad classification of errors into permanent, -unexpected, transient and not-yet-ready kinds. - -The following use the new error type: - -- `RngCore::try_fill_bytes` -- `Rng::try_fill` -- `OsRng::new` -- `JitterRng::new` - -### External generators - -We have a new generator, `EntropyRng`, which wraps `OsRng` and `JitterRng` -(preferring to use the former, but falling back to the latter if necessary). -This allows easy construction with fallback via `SeedableRng::from_rng`, -e.g. `IsaacRng::from_rng(EntropyRng::new())?`. This is equivalent to using -`FromEntropy` except for error handling. - -It is recommended to use `EntropyRng` over `OsRng` to avoid errors on platforms -with broken system generator, but it should be noted that the `JitterRng` -fallback is very slow. - -### PRNGs - -*Pseudo-Random Number Generators* (i.e. deterministic algorithmic generators) -have had a few changes since 0.4, and are now housed in the `prng` module -(old names remain temporarily available for compatibility; eventually these -generators will likely be housed outside the `rand` crate). - -All PRNGs now do not implement `Copy` to prevent accidental copying of the -generator's state (and thus repetitions of generated values). Explicit cloning -via `Clone` is still available. All PRNGs now have a custom implementation of -`Debug` which does not print any internal state; this helps avoid accidentally -leaking cryptographic generator state in log files. External PRNG -implementations are advised to follow this pattern (see also doc on `RngCore`). - -`SmallRng` has been added as a wrapper, currently around `XorShiftRng` (but -likely another algorithm soon). This is for uses where small state and fast -initialisation are important but cryptographic strength is not required. -(Actual performance of generation varies by benchmark; dependending on usage -this may or may not be the fastest algorithm, but will always be fast.) - -#### `ReseedingRng` - -The `ReseedingRng` wrapper has been signficantly altered to reduce overhead. -Unfortunately the new `ReseedingRng` is not compatible with all RNGs, but only -those using `BlockRngCore`. - -#### ISAAC PRNGs - -The `IsaacRng` and `Isaac64Rng` PRNGs now have an additional construction -method: `new_from_u64(seed)`. 64 bits of state is insufficient for cryptography -but may be of use in simulations and games. This will likely be superceeded by -a method to construct any PRNG from any hashable object in the future. - -#### HC-128 - -This is a new cryptographic generator, selected as one of the "stream ciphers -suitable for widespread adoption" by eSTREAM. This is now the default -cryptographic generator, used by `StdRng` and `thread_rng()`. - -### Helper functions/traits - -The `Rand` trait has been deprecated. Instead, users are encouraged to use -`Standard` which is a real distribution and supports the same sampling as -`Rand`. `Rng::gen()` now uses `Standard` and should work exactly as before. -See the documentation of the `distributions` module on how to implement -`Distribution` for `Standard` for user types `T` - -`weak_rng()` has been deprecated; use `SmallRng::from_entropy()` instead. - -### Distributions - -The `Sample` and `IndependentSample` traits have been replaced by a single -trait, `Distribution`. This is largely equivalent to `IndependentSample`, but -with `ind_sample` replaced by just `sample`. Support for mutable distributions -has been dropped; although it appears there may be a few genuine uses, these -are not used widely enough to justify the existance of two independent traits -or of having to provide mutable access to a distribution object. Both `Sample` -and `IndependentSample` are still available, but deprecated; they will be -removed in a future release. - -`Distribution::sample` (as well as several other functions) can now be called -directly on type-erased (unsized) RNGs. - -`RandSample` has been removed (see `Rand` deprecation and new `Standard` -distribution). - -The `Closed01` wrapper has been removed, but `OpenClosed01` has been added. - -#### Uniform distributions - -Two new distributions are available: - -- `Standard` produces uniformly-distributed samples for many different types, - and acts as a replacement for `Rand` -- `Alphanumeric` samples `char`s from the ranges `a-z A-Z 0-9` - -##### Ranges - -The `Range` distribution has been heavily adapted, and renamed to `Uniform`: - -- `Uniform::new(low, high)` remains (half open `[low, high)`) -- `Uniform::new_inclusive(low, high)` has been added, including `high` in the sample range -- `Uniform::sample_single(low, high, rng)` is a faster variant for single usage sampling from `[low, high)` - -`Uniform` can now be implemented for user-defined types; see the `uniform` module. - -#### Non-uniform distributions - -Two distributions have been added: - -- Poisson, modelling the number of events expected from a constant-rate - source within a fixed time interval (e.g. nuclear decay) -- Binomial, modelling the outcome of a fixed number of yes-no trials - -The sampling methods are based on those in "Numerical Recipes in C". - -##### Exponential and Normal distributions - -The main `Exp` and `Normal` distributions are unchanged, however the -"standard" versions, `Exp1` and `StandardNormal` are no longer wrapper types, -but full distributions. Instead of writing `let Exp1(x) = rng.gen();` you now -write `let x = rng.sample(Exp1);`. diff --git a/third_party/cargo/vendor/rand-0.5.6/appveyor.yml b/third_party/cargo/vendor/rand-0.5.6/appveyor.yml deleted file mode 100644 index 97d3ce6..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/appveyor.yml +++ /dev/null @@ -1,39 +0,0 @@ -environment: - - # At the time this was added AppVeyor was having troubles with checking - # revocation of SSL certificates of sites like static.rust-lang.org and what - # we think is crates.io. The libcurl HTTP client by default checks for - # revocation on Windows and according to a mailing list [1] this can be - # disabled. - # - # The `CARGO_HTTP_CHECK_REVOKE` env var here tells cargo to disable SSL - # revocation checking on Windows in libcurl. Note, though, that rustup, which - # we're using to download Rust here, also uses libcurl as the default backend. - # Unlike Cargo, however, rustup doesn't have a mechanism to disable revocation - # checking. To get rustup working we set `RUSTUP_USE_HYPER` which forces it to - # use the Hyper instead of libcurl backend. Both Hyper and libcurl use - # schannel on Windows but it appears that Hyper configures it slightly - # differently such that revocation checking isn't turned on by default. - # - # [1]: https://curl.haxx.se/mail/lib-2016-03/0202.html - RUSTUP_USE_HYPER: 1 - CARGO_HTTP_CHECK_REVOKE: false - - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host %TARGET% --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --all # cannot use --all and --features together - - cargo test --all --benches - - cargo test --features serde1,log,nightly - - cargo test --tests --no-default-features --features=alloc,serde1 - - cargo test --package rand_core --no-default-features --features=alloc,serde1 diff --git a/third_party/cargo/vendor/rand-0.5.6/benches/distributions.rs b/third_party/cargo/vendor/rand-0.5.6/benches/distributions.rs deleted file mode 100644 index fd6b5ae..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/benches/distributions.rs +++ /dev/null @@ -1,161 +0,0 @@ -#![feature(test)] -#![cfg_attr(all(feature="i128_support", feature="nightly"), allow(stable_features))] // stable since 2018-03-27 -#![cfg_attr(all(feature="i128_support", feature="nightly"), feature(i128_type, i128))] - -extern crate test; -extern crate rand; - -const RAND_BENCH_N: u64 = 1000; - -use std::mem::size_of; -use test::Bencher; - -use rand::{Rng, FromEntropy, XorShiftRng}; -use rand::distributions::*; - -macro_rules! distr_int { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0 as $ty; - for _ in 0..::RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum = accum.wrapping_add(x); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; - } - } -} - -macro_rules! distr_float { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0.0; - for _ in 0..::RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum += x; - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; - } - } -} - -macro_rules! distr { - ($fnn:ident, $ty:ty, $distr:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - let distr = $distr; - - b.iter(|| { - let mut accum = 0u32; - for _ in 0..::RAND_BENCH_N { - let x: $ty = distr.sample(&mut rng); - accum = accum.wrapping_add(x as u32); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; - } - } -} - -// uniform -distr_int!(distr_uniform_i8, i8, Uniform::new(20i8, 100)); -distr_int!(distr_uniform_i16, i16, Uniform::new(-500i16, 2000)); -distr_int!(distr_uniform_i32, i32, Uniform::new(-200_000_000i32, 800_000_000)); -distr_int!(distr_uniform_i64, i64, Uniform::new(3i64, 123_456_789_123)); -#[cfg(feature = "i128_support")] -distr_int!(distr_uniform_i128, i128, Uniform::new(-123_456_789_123i128, 123_456_789_123_456_789)); - -distr_float!(distr_uniform_f32, f32, Uniform::new(2.26f32, 2.319)); -distr_float!(distr_uniform_f64, f64, Uniform::new(2.26f64, 2.319)); - -// standard -distr_int!(distr_standard_i8, i8, Standard); -distr_int!(distr_standard_i16, i16, Standard); -distr_int!(distr_standard_i32, i32, Standard); -distr_int!(distr_standard_i64, i64, Standard); -#[cfg(feature = "i128_support")] -distr_int!(distr_standard_i128, i128, Standard); - -distr!(distr_standard_bool, bool, Standard); -distr!(distr_standard_alphanumeric, char, Alphanumeric); -distr!(distr_standard_codepoint, char, Standard); - -distr_float!(distr_standard_f32, f32, Standard); -distr_float!(distr_standard_f64, f64, Standard); -distr_float!(distr_open01_f32, f32, Open01); -distr_float!(distr_open01_f64, f64, Open01); -distr_float!(distr_openclosed01_f32, f32, OpenClosed01); -distr_float!(distr_openclosed01_f64, f64, OpenClosed01); - -// distributions -distr_float!(distr_exp, f64, Exp::new(1.23 * 4.56)); -distr_float!(distr_normal, f64, Normal::new(-1.23, 4.56)); -distr_float!(distr_log_normal, f64, LogNormal::new(-1.23, 4.56)); -distr_float!(distr_gamma_large_shape, f64, Gamma::new(10., 1.0)); -distr_float!(distr_gamma_small_shape, f64, Gamma::new(0.1, 1.0)); -distr_float!(distr_cauchy, f64, Cauchy::new(4.2, 6.9)); -distr_int!(distr_binomial, u64, Binomial::new(20, 0.7)); -distr_int!(distr_poisson, u64, Poisson::new(4.0)); -distr!(distr_bernoulli, bool, Bernoulli::new(0.18)); - - -// construct and sample from a range -macro_rules! gen_range_int { - ($fnn:ident, $ty:ident, $low:expr, $high:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - - b.iter(|| { - let mut high = $high; - let mut accum: $ty = 0; - for _ in 0..::RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen_range($low, high)); - // force recalculation of range each time - high = high.wrapping_add(1) & std::$ty::MAX; - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * ::RAND_BENCH_N; - } - } -} - -gen_range_int!(gen_range_i8, i8, -20i8, 100); -gen_range_int!(gen_range_i16, i16, -500i16, 2000); -gen_range_int!(gen_range_i32, i32, -200_000_000i32, 800_000_000); -gen_range_int!(gen_range_i64, i64, 3i64, 123_456_789_123); -#[cfg(feature = "i128_support")] -gen_range_int!(gen_range_i128, i128, -12345678901234i128, 123_456_789_123_456_789); - -#[bench] -fn dist_iter(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - let distr = Normal::new(-2.71828, 3.14159); - let mut iter = distr.sample_iter(&mut rng); - - b.iter(|| { - let mut accum = 0.0; - for _ in 0..::RAND_BENCH_N { - accum += iter.next().unwrap(); - } - accum - }); - b.bytes = size_of::() as u64 * ::RAND_BENCH_N; -} diff --git a/third_party/cargo/vendor/rand-0.5.6/benches/generators.rs b/third_party/cargo/vendor/rand-0.5.6/benches/generators.rs deleted file mode 100644 index 402a87b..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/benches/generators.rs +++ /dev/null @@ -1,176 +0,0 @@ -#![feature(test)] - -extern crate test; -extern crate rand; - -const RAND_BENCH_N: u64 = 1000; -const BYTES_LEN: usize = 1024; - -use std::mem::size_of; -use test::{black_box, Bencher}; - -use rand::prelude::*; -use rand::prng::{XorShiftRng, Hc128Rng, IsaacRng, Isaac64Rng, ChaChaRng}; -use rand::prng::hc128::Hc128Core; -use rand::rngs::adapter::ReseedingRng; -use rand::rngs::{OsRng, JitterRng, EntropyRng}; - -macro_rules! gen_bytes { - ($fnn:ident, $gen:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = $gen; - let mut buf = [0u8; BYTES_LEN]; - b.iter(|| { - for _ in 0..RAND_BENCH_N { - rng.fill_bytes(&mut buf); - black_box(buf); - } - }); - b.bytes = BYTES_LEN as u64 * RAND_BENCH_N; - } - } -} - -gen_bytes!(gen_bytes_xorshift, XorShiftRng::from_entropy()); -gen_bytes!(gen_bytes_chacha20, ChaChaRng::from_entropy()); -gen_bytes!(gen_bytes_hc128, Hc128Rng::from_entropy()); -gen_bytes!(gen_bytes_isaac, IsaacRng::from_entropy()); -gen_bytes!(gen_bytes_isaac64, Isaac64Rng::from_entropy()); -gen_bytes!(gen_bytes_std, StdRng::from_entropy()); -gen_bytes!(gen_bytes_small, SmallRng::from_entropy()); -gen_bytes!(gen_bytes_os, OsRng::new().unwrap()); - -macro_rules! gen_uint { - ($fnn:ident, $ty:ty, $gen:expr) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = $gen; - b.iter(|| { - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen::<$ty>()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -gen_uint!(gen_u32_xorshift, u32, XorShiftRng::from_entropy()); -gen_uint!(gen_u32_chacha20, u32, ChaChaRng::from_entropy()); -gen_uint!(gen_u32_hc128, u32, Hc128Rng::from_entropy()); -gen_uint!(gen_u32_isaac, u32, IsaacRng::from_entropy()); -gen_uint!(gen_u32_isaac64, u32, Isaac64Rng::from_entropy()); -gen_uint!(gen_u32_std, u32, StdRng::from_entropy()); -gen_uint!(gen_u32_small, u32, SmallRng::from_entropy()); -gen_uint!(gen_u32_os, u32, OsRng::new().unwrap()); - -gen_uint!(gen_u64_xorshift, u64, XorShiftRng::from_entropy()); -gen_uint!(gen_u64_chacha20, u64, ChaChaRng::from_entropy()); -gen_uint!(gen_u64_hc128, u64, Hc128Rng::from_entropy()); -gen_uint!(gen_u64_isaac, u64, IsaacRng::from_entropy()); -gen_uint!(gen_u64_isaac64, u64, Isaac64Rng::from_entropy()); -gen_uint!(gen_u64_std, u64, StdRng::from_entropy()); -gen_uint!(gen_u64_small, u64, SmallRng::from_entropy()); -gen_uint!(gen_u64_os, u64, OsRng::new().unwrap()); - -// Do not test JitterRng like the others by running it RAND_BENCH_N times per, -// measurement, because it is way too slow. Only run it once. -#[bench] -fn gen_u64_jitter(b: &mut Bencher) { - let mut rng = JitterRng::new().unwrap(); - b.iter(|| { - rng.gen::() - }); - b.bytes = size_of::() as u64; -} - -macro_rules! init_gen { - ($fnn:ident, $gen:ident) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = XorShiftRng::from_entropy(); - b.iter(|| { - let r2 = $gen::from_rng(&mut rng).unwrap(); - r2 - }); - } - } -} - -init_gen!(init_xorshift, XorShiftRng); -init_gen!(init_hc128, Hc128Rng); -init_gen!(init_isaac, IsaacRng); -init_gen!(init_isaac64, Isaac64Rng); -init_gen!(init_chacha, ChaChaRng); - -#[bench] -fn init_jitter(b: &mut Bencher) { - b.iter(|| { - JitterRng::new().unwrap() - }); -} - - -const RESEEDING_THRESHOLD: u64 = 1024*1024*1024; // something high enough to get - // deterministic measurements - -#[bench] -fn reseeding_hc128_bytes(b: &mut Bencher) { - let mut rng = ReseedingRng::new(Hc128Core::from_entropy(), - RESEEDING_THRESHOLD, - EntropyRng::new()); - let mut buf = [0u8; BYTES_LEN]; - b.iter(|| { - for _ in 0..RAND_BENCH_N { - rng.fill_bytes(&mut buf); - black_box(buf); - } - }); - b.bytes = BYTES_LEN as u64 * RAND_BENCH_N; -} - -macro_rules! reseeding_uint { - ($fnn:ident, $ty:ty) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = ReseedingRng::new(Hc128Core::from_entropy(), - RESEEDING_THRESHOLD, - EntropyRng::new()); - b.iter(|| { - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen::<$ty>()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -reseeding_uint!(reseeding_hc128_u32, u32); -reseeding_uint!(reseeding_hc128_u64, u64); - - -macro_rules! threadrng_uint { - ($fnn:ident, $ty:ty) => { - #[bench] - fn $fnn(b: &mut Bencher) { - let mut rng = thread_rng(); - b.iter(|| { - let mut accum: $ty = 0; - for _ in 0..RAND_BENCH_N { - accum = accum.wrapping_add(rng.gen::<$ty>()); - } - accum - }); - b.bytes = size_of::<$ty>() as u64 * RAND_BENCH_N; - } - } -} - -threadrng_uint!(thread_rng_u32, u32); -threadrng_uint!(thread_rng_u64, u64); diff --git a/third_party/cargo/vendor/rand-0.5.6/benches/misc.rs b/third_party/cargo/vendor/rand-0.5.6/benches/misc.rs deleted file mode 100644 index a1822a5..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/benches/misc.rs +++ /dev/null @@ -1,194 +0,0 @@ -#![feature(test)] - -extern crate test; -extern crate rand; - -const RAND_BENCH_N: u64 = 1000; - -use test::Bencher; - -use rand::prelude::*; -use rand::seq::*; - -#[bench] -fn misc_gen_bool_const(b: &mut Bencher) { - let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - for _ in 0..::RAND_BENCH_N { - accum ^= rng.gen_bool(0.18); - } - accum - }) -} - -#[bench] -fn misc_gen_bool_var(b: &mut Bencher) { - let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - let mut p = 0.18; - for _ in 0..::RAND_BENCH_N { - accum ^= rng.gen_bool(p); - p += 0.0001; - } - accum - }) -} - -#[bench] -fn misc_bernoulli_const(b: &mut Bencher) { - let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); - let d = rand::distributions::Bernoulli::new(0.18); - b.iter(|| { - // Can be evaluated at compile time. - let mut accum = true; - for _ in 0..::RAND_BENCH_N { - accum ^= rng.sample(d); - } - accum - }) -} - -#[bench] -fn misc_bernoulli_var(b: &mut Bencher) { - let mut rng = StdRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let mut accum = true; - let mut p = 0.18; - for _ in 0..::RAND_BENCH_N { - let d = rand::distributions::Bernoulli::new(p); - accum ^= rng.sample(d); - p += 0.0001; - } - accum - }) -} - -macro_rules! sample_binomial { - ($name:ident, $n:expr, $p:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - let (n, p) = ($n, $p); - b.iter(|| { - let d = rand::distributions::Binomial::new(n, p); - rng.sample(d) - }) - } - } -} - -sample_binomial!(misc_binomial_1, 1, 0.9); -sample_binomial!(misc_binomial_10, 10, 0.9); -sample_binomial!(misc_binomial_100, 100, 0.99); -sample_binomial!(misc_binomial_1000, 1000, 0.01); -sample_binomial!(misc_binomial_1e12, 1000_000_000_000, 0.2); - -#[bench] -fn misc_shuffle_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &mut [usize] = &mut [1; 100]; - b.iter(|| { - rng.shuffle(x); - x[0] - }) -} - -#[bench] -fn misc_sample_iter_10_of_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 100]; - b.iter(|| { - sample_iter(&mut rng, x, 10).unwrap_or_else(|e| e) - }) -} - -#[bench] -fn misc_sample_slice_10_of_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 100]; - b.iter(|| { - sample_slice(&mut rng, x, 10) - }) -} - -#[bench] -fn misc_sample_slice_ref_10_of_100(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - let x : &[usize] = &[1; 100]; - b.iter(|| { - sample_slice_ref(&mut rng, x, 10) - }) -} - -macro_rules! sample_indices { - ($name:ident, $amount:expr, $length:expr) => { - #[bench] - fn $name(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(thread_rng()).unwrap(); - b.iter(|| { - sample_indices(&mut rng, $length, $amount) - }) - } - } -} - -sample_indices!(misc_sample_indices_10_of_1k, 10, 1000); -sample_indices!(misc_sample_indices_50_of_1k, 50, 1000); -sample_indices!(misc_sample_indices_100_of_1k, 100, 1000); - -#[bench] -fn gen_1k_iter_repeat(b: &mut Bencher) { - use std::iter; - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let v: Vec = iter::repeat(()).map(|()| rng.gen()).take(128).collect(); - v - }); - b.bytes = 1024; -} - -#[bench] -#[allow(deprecated)] -fn gen_1k_gen_iter(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let v: Vec = rng.gen_iter().take(128).collect(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_sample_iter(b: &mut Bencher) { - use rand::distributions::{Distribution, Standard}; - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - let v: Vec = Standard.sample_iter(&mut rng).take(128).collect(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_gen_array(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - b.iter(|| { - // max supported array length is 32! - let v: [[u64; 32]; 4] = rng.gen(); - v - }); - b.bytes = 1024; -} - -#[bench] -fn gen_1k_fill(b: &mut Bencher) { - let mut rng = SmallRng::from_rng(&mut thread_rng()).unwrap(); - let mut buf = [0u64; 128]; - b.iter(|| { - rng.fill(&mut buf[..]); - buf - }); - b.bytes = 1024; -} diff --git a/third_party/cargo/vendor/rand-0.5.6/examples/monte-carlo.rs b/third_party/cargo/vendor/rand-0.5.6/examples/monte-carlo.rs deleted file mode 100644 index c18108a..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/examples/monte-carlo.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2013-2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! # Monte Carlo estimation of π -//! -//! Imagine that we have a square with sides of length 2 and a unit circle -//! (radius = 1), both centered at the origin. The areas are: -//! -//! ```text -//! area of circle = πr² = π * r * r = π -//! area of square = 2² = 4 -//! ``` -//! -//! The circle is entirely within the square, so if we sample many points -//! randomly from the square, roughly π / 4 of them should be inside the circle. -//! -//! We can use the above fact to estimate the value of π: pick many points in -//! the square at random, calculate the fraction that fall within the circle, -//! and multiply this fraction by 4. - -#![cfg(feature="std")] - - -extern crate rand; - -use rand::distributions::{Distribution, Uniform}; - -fn main() { - let range = Uniform::new(-1.0f64, 1.0); - let mut rng = rand::thread_rng(); - - let total = 1_000_000; - let mut in_circle = 0; - - for _ in 0..total { - let a = range.sample(&mut rng); - let b = range.sample(&mut rng); - if a*a + b*b <= 1.0 { - in_circle += 1; - } - } - - // prints something close to 3.14159... - println!("π is approximately {}", 4. * (in_circle as f64) / (total as f64)); -} diff --git a/third_party/cargo/vendor/rand-0.5.6/examples/monty-hall.rs b/third_party/cargo/vendor/rand-0.5.6/examples/monty-hall.rs deleted file mode 100644 index 3750f8f..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/examples/monty-hall.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2013-2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! ## Monty Hall Problem -//! -//! This is a simulation of the [Monty Hall Problem][]: -//! -//! > Suppose you're on a game show, and you're given the choice of three doors: -//! > Behind one door is a car; behind the others, goats. You pick a door, say -//! > No. 1, and the host, who knows what's behind the doors, opens another -//! > door, say No. 3, which has a goat. He then says to you, "Do you want to -//! > pick door No. 2?" Is it to your advantage to switch your choice? -//! -//! The rather unintuitive answer is that you will have a 2/3 chance of winning -//! if you switch and a 1/3 chance of winning if you don't, so it's better to -//! switch. -//! -//! This program will simulate the game show and with large enough simulation -//! steps it will indeed confirm that it is better to switch. -//! -//! [Monty Hall Problem]: https://en.wikipedia.org/wiki/Monty_Hall_problem - -#![cfg(feature="std")] - - -extern crate rand; - -use rand::Rng; -use rand::distributions::{Distribution, Uniform}; - -struct SimulationResult { - win: bool, - switch: bool, -} - -// Run a single simulation of the Monty Hall problem. -fn simulate(random_door: &Uniform, rng: &mut R) - -> SimulationResult { - let car = random_door.sample(rng); - - // This is our initial choice - let mut choice = random_door.sample(rng); - - // The game host opens a door - let open = game_host_open(car, choice, rng); - - // Shall we switch? - let switch = rng.gen(); - if switch { - choice = switch_door(choice, open); - } - - SimulationResult { win: choice == car, switch } -} - -// Returns the door the game host opens given our choice and knowledge of -// where the car is. The game host will never open the door with the car. -fn game_host_open(car: u32, choice: u32, rng: &mut R) -> u32 { - let choices = free_doors(&[car, choice]); - rand::seq::sample_slice(rng, &choices, 1)[0] -} - -// Returns the door we switch to, given our current choice and -// the open door. There will only be one valid door. -fn switch_door(choice: u32, open: u32) -> u32 { - free_doors(&[choice, open])[0] -} - -fn free_doors(blocked: &[u32]) -> Vec { - (0..3).filter(|x| !blocked.contains(x)).collect() -} - -fn main() { - // The estimation will be more accurate with more simulations - let num_simulations = 10000; - - let mut rng = rand::thread_rng(); - let random_door = Uniform::new(0u32, 3); - - let (mut switch_wins, mut switch_losses) = (0, 0); - let (mut keep_wins, mut keep_losses) = (0, 0); - - println!("Running {} simulations...", num_simulations); - for _ in 0..num_simulations { - let result = simulate(&random_door, &mut rng); - - match (result.win, result.switch) { - (true, true) => switch_wins += 1, - (true, false) => keep_wins += 1, - (false, true) => switch_losses += 1, - (false, false) => keep_losses += 1, - } - } - - let total_switches = switch_wins + switch_losses; - let total_keeps = keep_wins + keep_losses; - - println!("Switched door {} times with {} wins and {} losses", - total_switches, switch_wins, switch_losses); - - println!("Kept our choice {} times with {} wins and {} losses", - total_keeps, keep_wins, keep_losses); - - // With a large number of simulations, the values should converge to - // 0.667 and 0.333 respectively. - println!("Estimated chance to win if we switch: {}", - switch_wins as f32 / total_switches as f32); - println!("Estimated chance to win if we don't: {}", - keep_wins as f32 / total_keeps as f32); -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/bernoulli.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/bernoulli.rs deleted file mode 100644 index 2361fac..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/bernoulli.rs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! The Bernoulli distribution. - -use Rng; -use distributions::Distribution; - -/// The Bernoulli distribution. -/// -/// This is a special case of the Binomial distribution where `n = 1`. -/// -/// # Example -/// -/// ```rust -/// use rand::distributions::{Bernoulli, Distribution}; -/// -/// let d = Bernoulli::new(0.3); -/// let v = d.sample(&mut rand::thread_rng()); -/// println!("{} is from a Bernoulli distribution", v); -/// ``` -/// -/// # Precision -/// -/// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`), -/// so only probabilities that are multiples of 2-64 can be -/// represented. -#[derive(Clone, Copy, Debug)] -pub struct Bernoulli { - /// Probability of success, relative to the maximal integer. - p_int: u64, -} - -impl Bernoulli { - /// Construct a new `Bernoulli` with the given probability of success `p`. - /// - /// # Panics - /// - /// If `p < 0` or `p > 1`. - /// - /// # Precision - /// - /// For `p = 1.0`, the resulting distribution will always generate true. - /// For `p = 0.0`, the resulting distribution will always generate false. - /// - /// This method is accurate for any input `p` in the range `[0, 1]` which is - /// a multiple of 2-64. (Note that not all multiples of - /// 2-64 in `[0, 1]` can be represented as a `f64`.) - #[inline] - pub fn new(p: f64) -> Bernoulli { - assert!((p >= 0.0) & (p <= 1.0), "Bernoulli::new not called with 0 <= p <= 0"); - // Technically, this should be 2^64 or `u64::MAX + 1` because we compare - // using `<` when sampling. However, `u64::MAX` rounds to an `f64` - // larger than `u64::MAX` anyway. - const MAX_P_INT: f64 = ::core::u64::MAX as f64; - let p_int = if p < 1.0 { - (p * MAX_P_INT) as u64 - } else { - // Avoid overflow: `MAX_P_INT` cannot be represented as u64. - ::core::u64::MAX - }; - Bernoulli { p_int } - } -} - -impl Distribution for Bernoulli { - #[inline] - fn sample(&self, rng: &mut R) -> bool { - // Make sure to always return true for p = 1.0. - if self.p_int == ::core::u64::MAX { - return true; - } - let r: u64 = rng.gen(); - r < self.p_int - } -} - -#[cfg(test)] -mod test { - use Rng; - use distributions::Distribution; - use super::Bernoulli; - - #[test] - fn test_trivial() { - let mut r = ::test::rng(1); - let always_false = Bernoulli::new(0.0); - let always_true = Bernoulli::new(1.0); - for _ in 0..5 { - assert_eq!(r.sample::(&always_false), false); - assert_eq!(r.sample::(&always_true), true); - assert_eq!(Distribution::::sample(&always_false, &mut r), false); - assert_eq!(Distribution::::sample(&always_true, &mut r), true); - } - } - - #[test] - fn test_average() { - const P: f64 = 0.3; - let d = Bernoulli::new(P); - const N: u32 = 10_000_000; - - let mut sum: u32 = 0; - let mut rng = ::test::rng(2); - for _ in 0..N { - if d.sample(&mut rng) { - sum += 1; - } - } - let avg = (sum as f64) / (N as f64); - - assert!((avg - P).abs() < 1e-3); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/binomial.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/binomial.rs deleted file mode 100644 index 5eb03e3..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/binomial.rs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2016-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The binomial distribution. - -use Rng; -use distributions::{Distribution, Bernoulli, Cauchy}; -use distributions::log_gamma::log_gamma; - -/// The binomial distribution `Binomial(n, p)`. -/// -/// This distribution has density function: -/// `f(k) = n!/(k! (n-k)!) p^k (1-p)^(n-k)` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Binomial, Distribution}; -/// -/// let bin = Binomial::new(20, 0.3); -/// let v = bin.sample(&mut rand::thread_rng()); -/// println!("{} is from a binomial distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Binomial { - /// Number of trials. - n: u64, - /// Probability of success. - p: f64, -} - -impl Binomial { - /// Construct a new `Binomial` with the given shape parameters `n` (number - /// of trials) and `p` (probability of success). - /// - /// Panics if `p < 0` or `p > 1`. - pub fn new(n: u64, p: f64) -> Binomial { - assert!(p >= 0.0, "Binomial::new called with p < 0"); - assert!(p <= 1.0, "Binomial::new called with p > 1"); - Binomial { n, p } - } -} - -impl Distribution for Binomial { - fn sample(&self, rng: &mut R) -> u64 { - // Handle these values directly. - if self.p == 0.0 { - return 0; - } else if self.p == 1.0 { - return self.n; - } - - // For low n, it is faster to sample directly. For both methods, - // performance is independent of p. On Intel Haswell CPU this method - // appears to be faster for approx n < 300. - if self.n < 300 { - let mut result = 0; - let d = Bernoulli::new(self.p); - for _ in 0 .. self.n { - result += rng.sample(d) as u32; - } - return result as u64; - } - - // binomial distribution is symmetrical with respect to p -> 1-p, k -> n-k - // switch p so that it is less than 0.5 - this allows for lower expected values - // we will just invert the result at the end - let p = if self.p <= 0.5 { - self.p - } else { - 1.0 - self.p - }; - - // prepare some cached values - let float_n = self.n as f64; - let ln_fact_n = log_gamma(float_n + 1.0); - let pc = 1.0 - p; - let log_p = p.ln(); - let log_pc = pc.ln(); - let expected = self.n as f64 * p; - let sq = (expected * (2.0 * pc)).sqrt(); - - let mut lresult; - - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(0.0, 1.0); - loop { - let mut comp_dev: f64; - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - lresult = expected + sq * comp_dev; - // repeat the drawing until we are in the range of possible values - if lresult >= 0.0 && lresult < float_n + 1.0 { - break; - } - } - - // the result should be discrete - lresult = lresult.floor(); - - let log_binomial_dist = ln_fact_n - log_gamma(lresult+1.0) - - log_gamma(float_n - lresult + 1.0) + lresult*log_p + (float_n - lresult)*log_pc; - // this is the binomial probability divided by the comparison probability - // we will generate a uniform random value and if it is larger than this, - // we interpret it as a value falling out of the distribution and repeat - let comparison_coeff = (log_binomial_dist.exp() * sq) * (1.2 * (1.0 + comp_dev*comp_dev)); - - if comparison_coeff >= rng.gen() { - break; - } - } - - // invert the result for p < 0.5 - if p != self.p { - self.n - lresult as u64 - } else { - lresult as u64 - } - } -} - -#[cfg(test)] -mod test { - use Rng; - use distributions::Distribution; - use super::Binomial; - - fn test_binomial_mean_and_variance(n: u64, p: f64, rng: &mut R) { - let binomial = Binomial::new(n, p); - - let expected_mean = n as f64 * p; - let expected_variance = n as f64 * p * (1.0 - p); - - let mut results = [0.0; 1000]; - for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } - - let mean = results.iter().sum::() / results.len() as f64; - assert!((mean as f64 - expected_mean).abs() < expected_mean / 50.0); - - let variance = - results.iter().map(|x| (x - mean) * (x - mean)).sum::() - / results.len() as f64; - assert!((variance - expected_variance).abs() < expected_variance / 10.0); - } - - #[test] - fn test_binomial() { - let mut rng = ::test::rng(351); - test_binomial_mean_and_variance(150, 0.1, &mut rng); - test_binomial_mean_and_variance(70, 0.6, &mut rng); - test_binomial_mean_and_variance(40, 0.5, &mut rng); - test_binomial_mean_and_variance(20, 0.7, &mut rng); - test_binomial_mean_and_variance(20, 0.5, &mut rng); - } - - #[test] - fn test_binomial_end_points() { - let mut rng = ::test::rng(352); - assert_eq!(rng.sample(Binomial::new(20, 0.0)), 0); - assert_eq!(rng.sample(Binomial::new(20, 1.0)), 20); - } - - #[test] - #[should_panic] - fn test_binomial_invalid_lambda_neg() { - Binomial::new(20, -10.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/cauchy.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/cauchy.rs deleted file mode 100644 index 5ac55bd..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/cauchy.rs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2016-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Cauchy distribution. - -use Rng; -use distributions::Distribution; -use std::f64::consts::PI; - -/// The Cauchy distribution `Cauchy(median, scale)`. -/// -/// This distribution has a density function: -/// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))` -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Cauchy, Distribution}; -/// -/// let cau = Cauchy::new(2.0, 5.0); -/// let v = cau.sample(&mut rand::thread_rng()); -/// println!("{} is from a Cauchy(2, 5) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Cauchy { - median: f64, - scale: f64 -} - -impl Cauchy { - /// Construct a new `Cauchy` with the given shape parameters - /// `median` the peak location and `scale` the scale factor. - /// Panics if `scale <= 0`. - pub fn new(median: f64, scale: f64) -> Cauchy { - assert!(scale > 0.0, "Cauchy::new called with scale factor <= 0"); - Cauchy { - median, - scale - } - } -} - -impl Distribution for Cauchy { - fn sample(&self, rng: &mut R) -> f64 { - // sample from [0, 1) - let x = rng.gen::(); - // get standard cauchy random number - // note that π/2 is not exactly representable, even if x=0.5 the result is finite - let comp_dev = (PI * x).tan(); - // shift and scale according to parameters - let result = self.median + self.scale * comp_dev; - result - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Cauchy; - - fn median(mut numbers: &mut [f64]) -> f64 { - sort(&mut numbers); - let mid = numbers.len() / 2; - numbers[mid] - } - - fn sort(numbers: &mut [f64]) { - numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); - } - - #[test] - fn test_cauchy_median() { - let cauchy = Cauchy::new(10.0, 5.0); - let mut rng = ::test::rng(123); - let mut numbers: [f64; 1000] = [0.0; 1000]; - for i in 0..1000 { - numbers[i] = cauchy.sample(&mut rng); - } - let median = median(&mut numbers); - println!("Cauchy median: {}", median); - assert!((median - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - fn test_cauchy_mean() { - let cauchy = Cauchy::new(10.0, 5.0); - let mut rng = ::test::rng(123); - let mut sum = 0.0; - for _ in 0..1000 { - sum += cauchy.sample(&mut rng); - } - let mean = sum / 1000.0; - println!("Cauchy mean: {}", mean); - // for a Cauchy distribution the mean should not converge - assert!((mean - 10.0).abs() > 0.5); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_zero() { - Cauchy::new(0.0, 0.0); - } - - #[test] - #[should_panic] - fn test_cauchy_invalid_scale_neg() { - Cauchy::new(0.0, -10.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/exponential.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/exponential.rs deleted file mode 100644 index e8dbdc9..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/exponential.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The exponential distribution. - -use {Rng}; -use distributions::{ziggurat, ziggurat_tables, Distribution}; - -/// Samples floating-point numbers according to the exponential distribution, -/// with rate parameter `λ = 1`. This is equivalent to `Exp::new(1.0)` or -/// sampling with `-rng.gen::().ln()`, but faster. -/// -/// See `Exp` for the general exponential distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. The exact -/// description in the paper was adjusted to use tables for the exponential -/// distribution rather than normal. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Exp1; -/// -/// let val: f64 = SmallRng::from_entropy().sample(Exp1); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp1; - -// This could be done via `-rng.gen::().ln()` but that is slower. -impl Distribution for Exp1 { - #[inline] - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x).exp() - } - #[inline] - fn zero_case(rng: &mut R, _u: f64) -> f64 { - ziggurat_tables::ZIG_EXP_R - rng.gen::().ln() - } - - ziggurat(rng, false, - &ziggurat_tables::ZIG_EXP_X, - &ziggurat_tables::ZIG_EXP_F, - pdf, zero_case) - } -} - -/// The exponential distribution `Exp(lambda)`. -/// -/// This distribution has density function: `f(x) = lambda * exp(-lambda * x)` -/// for `x > 0`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Exp, Distribution}; -/// -/// let exp = Exp::new(2.0); -/// let v = exp.sample(&mut rand::thread_rng()); -/// println!("{} is from a Exp(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Exp { - /// `lambda` stored as `1/lambda`, since this is what we scale by. - lambda_inverse: f64 -} - -impl Exp { - /// Construct a new `Exp` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - #[inline] - pub fn new(lambda: f64) -> Exp { - assert!(lambda > 0.0, "Exp::new called with `lambda` <= 0"); - Exp { lambda_inverse: 1.0 / lambda } - } -} - -impl Distribution for Exp { - fn sample(&self, rng: &mut R) -> f64 { - let n: f64 = rng.sample(Exp1); - n * self.lambda_inverse - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Exp; - - #[test] - fn test_exp() { - let exp = Exp::new(10.0); - let mut rng = ::test::rng(221); - for _ in 0..1000 { - assert!(exp.sample(&mut rng) >= 0.0); - } - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_zero() { - Exp::new(0.0); - } - #[test] - #[should_panic] - fn test_exp_invalid_lambda_neg() { - Exp::new(-10.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/float.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/float.rs deleted file mode 100644 index 0058122..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/float.rs +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Basic floating-point number distributions - -use core::mem; -use Rng; -use distributions::{Distribution, Standard}; - -/// A distribution to sample floating point numbers uniformly in the half-open -/// interval `(0, 1]`, i.e. including 1 but not 0. -/// -/// All values that can be generated are of the form `n * ε/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`] -/// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::OpenClosed01; -/// -/// let val: f32 = thread_rng().sample(OpenClosed01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: struct.Standard.html -/// [`Open01`]: struct.Open01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct OpenClosed01; - -/// A distribution to sample floating point numbers uniformly in the open -/// interval `(0, 1)`, i.e. not including either endpoint. -/// -/// All values that can be generated are of the form `n * ε + ε/2`. For `f32` -/// the 22 most significant random bits of an `u32` are used, for `f64` 52 from -/// an `u64`. The conversion uses a transmute-based method. -/// -/// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`] -/// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary -/// ranges. -/// -/// # Example -/// ``` -/// use rand::{thread_rng, Rng}; -/// use rand::distributions::Open01; -/// -/// let val: f32 = thread_rng().sample(Open01); -/// println!("f32 from (0, 1): {}", val); -/// ``` -/// -/// [`Standard`]: struct.Standard.html -/// [`OpenClosed01`]: struct.OpenClosed01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct Open01; - - -pub(crate) trait IntoFloat { - type F; - - /// Helper method to combine the fraction and a contant exponent into a - /// float. - /// - /// Only the least significant bits of `self` may be set, 23 for `f32` and - /// 52 for `f64`. - /// The resulting value will fall in a range that depends on the exponent. - /// As an example the range with exponent 0 will be - /// [20..21), which is [1..2). - fn into_float_with_exponent(self, exponent: i32) -> Self::F; -} - -macro_rules! float_impls { - ($ty:ty, $uty:ty, $fraction_bits:expr, $exponent_bias:expr) => { - impl IntoFloat for $uty { - type F = $ty; - #[inline(always)] - fn into_float_with_exponent(self, exponent: i32) -> $ty { - // The exponent is encoded using an offset-binary representation - let exponent_bits = - (($exponent_bias + exponent) as $uty) << $fraction_bits; - unsafe { mem::transmute(self | exponent_bits) } - } - } - - impl Distribution<$ty> for Standard { - fn sample(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; [0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$ty>() * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $uty << precision) as $ty); - - let value: $uty = rng.gen(); - scale * (value >> (float_size - precision)) as $ty - } - } - - impl Distribution<$ty> for OpenClosed01 { - fn sample(&self, rng: &mut R) -> $ty { - // Multiply-based method; 24/53 random bits; (0, 1] interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - let float_size = mem::size_of::<$ty>() * 8; - let precision = $fraction_bits + 1; - let scale = 1.0 / ((1 as $uty << precision) as $ty); - - let value: $uty = rng.gen(); - let value = value >> (float_size - precision); - // Add 1 to shift up; will not overflow because of right-shift: - scale * (value + 1) as $ty - } - } - - impl Distribution<$ty> for Open01 { - fn sample(&self, rng: &mut R) -> $ty { - // Transmute-based method; 23/52 random bits; (0, 1) interval. - // We use the most significant bits because for simple RNGs - // those are usually more random. - const EPSILON: $ty = 1.0 / (1u64 << $fraction_bits) as $ty; - let float_size = mem::size_of::<$ty>() * 8; - - let value: $uty = rng.gen(); - let fraction = value >> (float_size - $fraction_bits); - fraction.into_float_with_exponent(0) - (1.0 - EPSILON / 2.0) - } - } - } -} -float_impls! { f32, u32, 23, 127 } -float_impls! { f64, u64, 52, 1023 } - - -#[cfg(test)] -mod tests { - use Rng; - use distributions::{Open01, OpenClosed01}; - use rngs::mock::StepRng; - - const EPSILON32: f32 = ::core::f32::EPSILON; - const EPSILON64: f64 = ::core::f64::EPSILON; - - #[test] - fn standard_fp_edge_cases() { - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.gen::(), 0.0); - assert_eq!(zeros.gen::(), 0.0); - - let mut one32 = StepRng::new(1 << 8, 0); - assert_eq!(one32.gen::(), EPSILON32 / 2.0); - - let mut one64 = StepRng::new(1 << 11, 0); - assert_eq!(one64.gen::(), EPSILON64 / 2.0); - - let mut max = StepRng::new(!0, 0); - assert_eq!(max.gen::(), 1.0 - EPSILON32 / 2.0); - assert_eq!(max.gen::(), 1.0 - EPSILON64 / 2.0); - } - - #[test] - fn openclosed01_edge_cases() { - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::(OpenClosed01), 0.0 + EPSILON32 / 2.0); - assert_eq!(zeros.sample::(OpenClosed01), 0.0 + EPSILON64 / 2.0); - - let mut one32 = StepRng::new(1 << 8, 0); - assert_eq!(one32.sample::(OpenClosed01), EPSILON32); - - let mut one64 = StepRng::new(1 << 11, 0); - assert_eq!(one64.sample::(OpenClosed01), EPSILON64); - - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::(OpenClosed01), 1.0); - assert_eq!(max.sample::(OpenClosed01), 1.0); - } - - #[test] - fn open01_edge_cases() { - let mut zeros = StepRng::new(0, 0); - assert_eq!(zeros.sample::(Open01), 0.0 + EPSILON32 / 2.0); - assert_eq!(zeros.sample::(Open01), 0.0 + EPSILON64 / 2.0); - - let mut one32 = StepRng::new(1 << 9, 0); - assert_eq!(one32.sample::(Open01), EPSILON32 / 2.0 * 3.0); - - let mut one64 = StepRng::new(1 << 12, 0); - assert_eq!(one64.sample::(Open01), EPSILON64 / 2.0 * 3.0); - - let mut max = StepRng::new(!0, 0); - assert_eq!(max.sample::(Open01), 1.0 - EPSILON32 / 2.0); - assert_eq!(max.sample::(Open01), 1.0 - EPSILON64 / 2.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/gamma.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/gamma.rs deleted file mode 100644 index f02cf3b..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/gamma.rs +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Gamma and derived distributions. - -use self::GammaRepr::*; -use self::ChiSquaredRepr::*; - -use Rng; -use distributions::normal::StandardNormal; -use distributions::{Distribution, Exp, Open01}; - -/// The Gamma distribution `Gamma(shape, scale)` distribution. -/// -/// The density function of this distribution is -/// -/// ```text -/// f(x) = x^(k - 1) * exp(-x / θ) / (Γ(k) * θ^k) -/// ``` -/// -/// where `Γ` is the Gamma function, `k` is the shape and `θ` is the -/// scale and both `k` and `θ` are strictly positive. -/// -/// The algorithm used is that described by Marsaglia & Tsang 2000[^1], -/// falling back to directly sampling from an Exponential for `shape -/// == 1`, and using the boosting technique described in that paper for -/// `shape < 1`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Gamma}; -/// -/// let gamma = Gamma::new(2.0, 5.0); -/// let v = gamma.sample(&mut rand::thread_rng()); -/// println!("{} is from a Gamma(2, 5) distribution", v); -/// ``` -/// -/// [^1]: George Marsaglia and Wai Wan Tsang. 2000. "A Simple Method for -/// Generating Gamma Variables" *ACM Trans. Math. Softw.* 26, 3 -/// (September 2000), 363-372. -/// DOI:[10.1145/358407.358414](https://doi.acm.org/10.1145/358407.358414) -#[derive(Clone, Copy, Debug)] -pub struct Gamma { - repr: GammaRepr, -} - -#[derive(Clone, Copy, Debug)] -enum GammaRepr { - Large(GammaLargeShape), - One(Exp), - Small(GammaSmallShape) -} - -// These two helpers could be made public, but saving the -// match-on-Gamma-enum branch from using them directly (e.g. if one -// knows that the shape is always > 1) doesn't appear to be much -// faster. - -/// Gamma distribution where the shape parameter is less than 1. -/// -/// Note, samples from this require a compulsory floating-point `pow` -/// call, which makes it significantly slower than sampling from a -/// gamma distribution where the shape parameter is greater than or -/// equal to 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaSmallShape { - inv_shape: f64, - large_shape: GammaLargeShape -} - -/// Gamma distribution where the shape parameter is larger than 1. -/// -/// See `Gamma` for sampling from a Gamma distribution with general -/// shape parameters. -#[derive(Clone, Copy, Debug)] -struct GammaLargeShape { - scale: f64, - c: f64, - d: f64 -} - -impl Gamma { - /// Construct an object representing the `Gamma(shape, scale)` - /// distribution. - /// - /// Panics if `shape <= 0` or `scale <= 0`. - #[inline] - pub fn new(shape: f64, scale: f64) -> Gamma { - assert!(shape > 0.0, "Gamma::new called with shape <= 0"); - assert!(scale > 0.0, "Gamma::new called with scale <= 0"); - - let repr = if shape == 1.0 { - One(Exp::new(1.0 / scale)) - } else if shape < 1.0 { - Small(GammaSmallShape::new_raw(shape, scale)) - } else { - Large(GammaLargeShape::new_raw(shape, scale)) - }; - Gamma { repr } - } -} - -impl GammaSmallShape { - fn new_raw(shape: f64, scale: f64) -> GammaSmallShape { - GammaSmallShape { - inv_shape: 1. / shape, - large_shape: GammaLargeShape::new_raw(shape + 1.0, scale) - } - } -} - -impl GammaLargeShape { - fn new_raw(shape: f64, scale: f64) -> GammaLargeShape { - let d = shape - 1. / 3.; - GammaLargeShape { - scale, - c: 1. / (9. * d).sqrt(), - d - } - } -} - -impl Distribution for Gamma { - fn sample(&self, rng: &mut R) -> f64 { - match self.repr { - Small(ref g) => g.sample(rng), - One(ref g) => g.sample(rng), - Large(ref g) => g.sample(rng), - } - } -} -impl Distribution for GammaSmallShape { - fn sample(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(Open01); - - self.large_shape.sample(rng) * u.powf(self.inv_shape) - } -} -impl Distribution for GammaLargeShape { - fn sample(&self, rng: &mut R) -> f64 { - loop { - let x = rng.sample(StandardNormal); - let v_cbrt = 1.0 + self.c * x; - if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 - continue - } - - let v = v_cbrt * v_cbrt * v_cbrt; - let u: f64 = rng.sample(Open01); - - let x_sqr = x * x; - if u < 1.0 - 0.0331 * x_sqr * x_sqr || - u.ln() < 0.5 * x_sqr + self.d * (1.0 - v + v.ln()) { - return self.d * v * self.scale - } - } - } -} - -/// The chi-squared distribution `χ²(k)`, where `k` is the degrees of -/// freedom. -/// -/// For `k > 0` integral, this distribution is the sum of the squares -/// of `k` independent standard normal random variables. For other -/// `k`, this uses the equivalent characterisation -/// `χ²(k) = Gamma(k/2, 2)`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{ChiSquared, Distribution}; -/// -/// let chi = ChiSquared::new(11.0); -/// let v = chi.sample(&mut rand::thread_rng()); -/// println!("{} is from a χ²(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct ChiSquared { - repr: ChiSquaredRepr, -} - -#[derive(Clone, Copy, Debug)] -enum ChiSquaredRepr { - // k == 1, Gamma(alpha, ..) is particularly slow for alpha < 1, - // e.g. when alpha = 1/2 as it would be for this case, so special- - // casing and using the definition of N(0,1)^2 is faster. - DoFExactlyOne, - DoFAnythingElse(Gamma), -} - -impl ChiSquared { - /// Create a new chi-squared distribution with degrees-of-freedom - /// `k`. Panics if `k < 0`. - pub fn new(k: f64) -> ChiSquared { - let repr = if k == 1.0 { - DoFExactlyOne - } else { - assert!(k > 0.0, "ChiSquared::new called with `k` < 0"); - DoFAnythingElse(Gamma::new(0.5 * k, 2.0)) - }; - ChiSquared { repr } - } -} -impl Distribution for ChiSquared { - fn sample(&self, rng: &mut R) -> f64 { - match self.repr { - DoFExactlyOne => { - // k == 1 => N(0,1)^2 - let norm = rng.sample(StandardNormal); - norm * norm - } - DoFAnythingElse(ref g) => g.sample(rng) - } - } -} - -/// The Fisher F distribution `F(m, n)`. -/// -/// This distribution is equivalent to the ratio of two normalised -/// chi-squared distributions, that is, `F(m,n) = (χ²(m)/m) / -/// (χ²(n)/n)`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{FisherF, Distribution}; -/// -/// let f = FisherF::new(2.0, 32.0); -/// let v = f.sample(&mut rand::thread_rng()); -/// println!("{} is from an F(2, 32) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct FisherF { - numer: ChiSquared, - denom: ChiSquared, - // denom_dof / numer_dof so that this can just be a straight - // multiplication, rather than a division. - dof_ratio: f64, -} - -impl FisherF { - /// Create a new `FisherF` distribution, with the given - /// parameter. Panics if either `m` or `n` are not positive. - pub fn new(m: f64, n: f64) -> FisherF { - assert!(m > 0.0, "FisherF::new called with `m < 0`"); - assert!(n > 0.0, "FisherF::new called with `n < 0`"); - - FisherF { - numer: ChiSquared::new(m), - denom: ChiSquared::new(n), - dof_ratio: n / m - } - } -} -impl Distribution for FisherF { - fn sample(&self, rng: &mut R) -> f64 { - self.numer.sample(rng) / self.denom.sample(rng) * self.dof_ratio - } -} - -/// The Student t distribution, `t(nu)`, where `nu` is the degrees of -/// freedom. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{StudentT, Distribution}; -/// -/// let t = StudentT::new(11.0); -/// let v = t.sample(&mut rand::thread_rng()); -/// println!("{} is from a t(11) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StudentT { - chi: ChiSquared, - dof: f64 -} - -impl StudentT { - /// Create a new Student t distribution with `n` degrees of - /// freedom. Panics if `n <= 0`. - pub fn new(n: f64) -> StudentT { - assert!(n > 0.0, "StudentT::new called with `n <= 0`"); - StudentT { - chi: ChiSquared::new(n), - dof: n - } - } -} -impl Distribution for StudentT { - fn sample(&self, rng: &mut R) -> f64 { - let norm = rng.sample(StandardNormal); - norm * (self.dof / self.chi.sample(rng)).sqrt() - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::{ChiSquared, StudentT, FisherF}; - - #[test] - fn test_chi_squared_one() { - let chi = ChiSquared::new(1.0); - let mut rng = ::test::rng(201); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_small() { - let chi = ChiSquared::new(0.5); - let mut rng = ::test::rng(202); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - fn test_chi_squared_large() { - let chi = ChiSquared::new(30.0); - let mut rng = ::test::rng(203); - for _ in 0..1000 { - chi.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_chi_squared_invalid_dof() { - ChiSquared::new(-1.0); - } - - #[test] - fn test_f() { - let f = FisherF::new(2.0, 32.0); - let mut rng = ::test::rng(204); - for _ in 0..1000 { - f.sample(&mut rng); - } - } - - #[test] - fn test_t() { - let t = StudentT::new(11.0); - let mut rng = ::test::rng(205); - for _ in 0..1000 { - t.sample(&mut rng); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/integer.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/integer.rs deleted file mode 100644 index a23ddd5..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/integer.rs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for integer types. - -use {Rng}; -use distributions::{Distribution, Standard}; - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u8 { - rng.next_u32() as u8 - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u16 { - rng.next_u32() as u16 - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u32 { - rng.next_u32() - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u64 { - rng.next_u64() - } -} - -#[cfg(feature = "i128_support")] -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> u128 { - // Use LE; we explicitly generate one value before the next. - let x = rng.next_u64() as u128; - let y = rng.next_u64() as u128; - (y << 64) | x - } -} - -impl Distribution for Standard { - #[inline] - #[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] - fn sample(&self, rng: &mut R) -> usize { - rng.next_u32() as usize - } - - #[inline] - #[cfg(target_pointer_width = "64")] - fn sample(&self, rng: &mut R) -> usize { - rng.next_u64() as usize - } -} - -macro_rules! impl_int_from_uint { - ($ty:ty, $uty:ty) => { - impl Distribution<$ty> for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> $ty { - rng.gen::<$uty>() as $ty - } - } - } -} - -impl_int_from_uint! { i8, u8 } -impl_int_from_uint! { i16, u16 } -impl_int_from_uint! { i32, u32 } -impl_int_from_uint! { i64, u64 } -#[cfg(feature = "i128_support")] impl_int_from_uint! { i128, u128 } -impl_int_from_uint! { isize, usize } - - -#[cfg(test)] -mod tests { - use Rng; - use distributions::{Standard}; - - #[test] - fn test_integers() { - let mut rng = ::test::rng(806); - - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - #[cfg(feature = "i128_support")] - rng.sample::(Standard); - - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - #[cfg(feature = "i128_support")] - rng.sample::(Standard); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/log_gamma.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/log_gamma.rs deleted file mode 100644 index f1fa383..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/log_gamma.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2016-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Calculates ln(gamma(x)) (natural logarithm of the gamma -/// function) using the Lanczos approximation. -/// -/// The approximation expresses the gamma function as: -/// `gamma(z+1) = sqrt(2*pi)*(z+g+0.5)^(z+0.5)*exp(-z-g-0.5)*Ag(z)` -/// `g` is an arbitrary constant; we use the approximation with `g=5`. -/// -/// Noting that `gamma(z+1) = z*gamma(z)` and applying `ln` to both sides: -/// `ln(gamma(z)) = (z+0.5)*ln(z+g+0.5)-(z+g+0.5) + ln(sqrt(2*pi)*Ag(z)/z)` -/// -/// `Ag(z)` is an infinite series with coefficients that can be calculated -/// ahead of time - we use just the first 6 terms, which is good enough -/// for most purposes. -pub fn log_gamma(x: f64) -> f64 { - // precalculated 6 coefficients for the first 6 terms of the series - let coefficients: [f64; 6] = [ - 76.18009172947146, - -86.50532032941677, - 24.01409824083091, - -1.231739572450155, - 0.1208650973866179e-2, - -0.5395239384953e-5, - ]; - - // (x+0.5)*ln(x+g+0.5)-(x+g+0.5) - let tmp = x + 5.5; - let log = (x + 0.5) * tmp.ln() - tmp; - - // the first few terms of the series for Ag(x) - let mut a = 1.000000000190015; - let mut denom = x; - for coeff in &coefficients { - denom += 1.0; - a += coeff / denom; - } - - // get everything together - // a is Ag(x) - // 2.5066... is sqrt(2pi) - log + (2.5066282746310005 * a / x).ln() -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/mod.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/mod.rs deleted file mode 100644 index 24dd3a3..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/mod.rs +++ /dev/null @@ -1,784 +0,0 @@ -// Copyright 2013-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Generating random samples from probability distributions. -//! -//! This module is the home of the [`Distribution`] trait and several of its -//! implementations. It is the workhorse behind some of the convenient -//! functionality of the [`Rng`] trait, including [`gen`], [`gen_range`] and -//! of course [`sample`]. -//! -//! Abstractly, a [probability distribution] describes the probability of -//! occurance of each value in its sample space. -//! -//! More concretely, an implementation of `Distribution` for type `X` is an -//! algorithm for choosing values from the sample space (a subset of `T`) -//! according to the distribution `X` represents, using an external source of -//! randomness (an RNG supplied to the `sample` function). -//! -//! A type `X` may implement `Distribution` for multiple types `T`. -//! Any type implementing [`Distribution`] is stateless (i.e. immutable), -//! but it may have internal parameters set at construction time (for example, -//! [`Uniform`] allows specification of its sample space as a range within `T`). -//! -//! -//! # The `Standard` distribution -//! -//! The [`Standard`] distribution is important to mention. This is the -//! distribution used by [`Rng::gen()`] and represents the "default" way to -//! produce a random value for many different types, including most primitive -//! types, tuples, arrays, and a few derived types. See the documentation of -//! [`Standard`] for more details. -//! -//! Implementing `Distribution` for [`Standard`] for user types `T` makes it -//! possible to generate type `T` with [`Rng::gen()`], and by extension also -//! with the [`random()`] function. -//! -//! -//! # Distribution to sample from a `Uniform` range -//! -//! The [`Uniform`] distribution is more flexible than [`Standard`], but also -//! more specialised: it supports fewer target types, but allows the sample -//! space to be specified as an arbitrary range within its target type `T`. -//! Both [`Standard`] and [`Uniform`] are in some sense uniform distributions. -//! -//! Values may be sampled from this distribution using [`Rng::gen_range`] or -//! by creating a distribution object with [`Uniform::new`], -//! [`Uniform::new_inclusive`] or `From`. When the range limits are not -//! known at compile time it is typically faster to reuse an existing -//! distribution object than to call [`Rng::gen_range`]. -//! -//! User types `T` may also implement `Distribution` for [`Uniform`], -//! although this is less straightforward than for [`Standard`] (see the -//! documentation in the [`uniform` module]. Doing so enables generation of -//! values of type `T` with [`Rng::gen_range`]. -//! -//! -//! # Other distributions -//! -//! There are surprisingly many ways to uniformly generate random floats. A -//! range between 0 and 1 is standard, but the exact bounds (open vs closed) -//! and accuracy differ. In addition to the [`Standard`] distribution Rand offers -//! [`Open01`] and [`OpenClosed01`]. See [Floating point implementation] for -//! more details. -//! -//! [`Alphanumeric`] is a simple distribution to sample random letters and -//! numbers of the `char` type; in contrast [`Standard`] may sample any valid -//! `char`. -//! -//! -//! # Non-uniform probability distributions -//! -//! Rand currently provides the following probability distributions: -//! -//! - Related to real-valued quantities that grow linearly -//! (e.g. errors, offsets): -//! - [`Normal`] distribution, and [`StandardNormal`] as a primitive -//! - [`Cauchy`] distribution -//! - Related to Bernoulli trials (yes/no events, with a given probability): -//! - [`Binomial`] distribution -//! - [`Bernoulli`] distribution, similar to [`Rng::gen_bool`]. -//! - Related to positive real-valued quantities that grow exponentially -//! (e.g. prices, incomes, populations): -//! - [`LogNormal`] distribution -//! - Related to the occurrence of independent events at a given rate: -//! - [`Poisson`] distribution -//! - [`Exp`]onential distribution, and [`Exp1`] as a primitive -//! - Gamma and derived distributions: -//! - [`Gamma`] distribution -//! - [`ChiSquared`] distribution -//! - [`StudentT`] distribution -//! - [`FisherF`] distribution -//! -//! -//! # Examples -//! -//! Sampling from a distribution: -//! -//! ``` -//! use rand::{thread_rng, Rng}; -//! use rand::distributions::Exp; -//! -//! let exp = Exp::new(2.0); -//! let v = thread_rng().sample(exp); -//! println!("{} is from an Exp(2) distribution", v); -//! ``` -//! -//! Implementing the [`Standard`] distribution for a user type: -//! -//! ``` -//! # #![allow(dead_code)] -//! use rand::Rng; -//! use rand::distributions::{Distribution, Standard}; -//! -//! struct MyF32 { -//! x: f32, -//! } -//! -//! impl Distribution for Standard { -//! fn sample(&self, rng: &mut R) -> MyF32 { -//! MyF32 { x: rng.gen() } -//! } -//! } -//! ``` -//! -//! -//! [probability distribution]: https://en.wikipedia.org/wiki/Probability_distribution -//! [`Distribution`]: trait.Distribution.html -//! [`gen_range`]: ../trait.Rng.html#method.gen_range -//! [`gen`]: ../trait.Rng.html#method.gen -//! [`sample`]: ../trait.Rng.html#method.sample -//! [`new_inclusive`]: struct.Uniform.html#method.new_inclusive -//! [`random()`]: ../fn.random.html -//! [`Rng::gen_bool`]: ../trait.Rng.html#method.gen_bool -//! [`Rng::gen_range`]: ../trait.Rng.html#method.gen_range -//! [`Rng::gen()`]: ../trait.Rng.html#method.gen -//! [`Rng`]: ../trait.Rng.html -//! [`uniform` module]: uniform/index.html -//! [Floating point implementation]: struct.Standard.html#floating-point-implementation -// distributions -//! [`Alphanumeric`]: struct.Alphanumeric.html -//! [`Bernoulli`]: struct.Bernoulli.html -//! [`Binomial`]: struct.Binomial.html -//! [`Cauchy`]: struct.Cauchy.html -//! [`ChiSquared`]: struct.ChiSquared.html -//! [`Exp`]: struct.Exp.html -//! [`Exp1`]: struct.Exp1.html -//! [`FisherF`]: struct.FisherF.html -//! [`Gamma`]: struct.Gamma.html -//! [`LogNormal`]: struct.LogNormal.html -//! [`Normal`]: struct.Normal.html -//! [`Open01`]: struct.Open01.html -//! [`OpenClosed01`]: struct.OpenClosed01.html -//! [`Pareto`]: struct.Pareto.html -//! [`Poisson`]: struct.Poisson.html -//! [`Standard`]: struct.Standard.html -//! [`StandardNormal`]: struct.StandardNormal.html -//! [`StudentT`]: struct.StudentT.html -//! [`Uniform`]: struct.Uniform.html -//! [`Uniform::new`]: struct.Uniform.html#method.new -//! [`Uniform::new_inclusive`]: struct.Uniform.html#method.new_inclusive - -use Rng; - -#[doc(inline)] pub use self::other::Alphanumeric; -#[doc(inline)] pub use self::uniform::Uniform; -#[doc(inline)] pub use self::float::{OpenClosed01, Open01}; -#[deprecated(since="0.5.0", note="use Uniform instead")] -pub use self::uniform::Uniform as Range; -#[cfg(feature="std")] -#[doc(inline)] pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT}; -#[cfg(feature="std")] -#[doc(inline)] pub use self::normal::{Normal, LogNormal, StandardNormal}; -#[cfg(feature="std")] -#[doc(inline)] pub use self::exponential::{Exp, Exp1}; -#[cfg(feature="std")] -#[doc(inline)] pub use self::pareto::Pareto; -#[cfg(feature = "std")] -#[doc(inline)] pub use self::poisson::Poisson; -#[cfg(feature = "std")] -#[doc(inline)] pub use self::binomial::Binomial; -#[doc(inline)] pub use self::bernoulli::Bernoulli; -#[cfg(feature = "std")] -#[doc(inline)] pub use self::cauchy::Cauchy; - -pub mod uniform; -#[cfg(feature="std")] -#[doc(hidden)] pub mod gamma; -#[cfg(feature="std")] -#[doc(hidden)] pub mod normal; -#[cfg(feature="std")] -#[doc(hidden)] pub mod exponential; -#[cfg(feature="std")] -#[doc(hidden)] pub mod pareto; -#[cfg(feature = "std")] -#[doc(hidden)] pub mod poisson; -#[cfg(feature = "std")] -#[doc(hidden)] pub mod binomial; -#[doc(hidden)] pub mod bernoulli; -#[cfg(feature = "std")] -#[doc(hidden)] pub mod cauchy; - -mod float; -mod integer; -#[cfg(feature="std")] -mod log_gamma; -mod other; -#[cfg(feature="std")] -mod ziggurat_tables; -#[cfg(feature="std")] -use distributions::float::IntoFloat; - -/// Types that can be used to create a random instance of `Support`. -#[deprecated(since="0.5.0", note="use Distribution instead")] -pub trait Sample { - /// Generate a random value of `Support`, using `rng` as the - /// source of randomness. - fn sample(&mut self, rng: &mut R) -> Support; -} - -/// `Sample`s that do not require keeping track of state. -/// -/// Since no state is recorded, each sample is (statistically) -/// independent of all others, assuming the `Rng` used has this -/// property. -#[allow(deprecated)] -#[deprecated(since="0.5.0", note="use Distribution instead")] -pub trait IndependentSample: Sample { - /// Generate a random value. - fn ind_sample(&self, &mut R) -> Support; -} - -/// DEPRECATED: Use `distributions::uniform` instead. -#[deprecated(since="0.5.0", note="use uniform instead")] -pub mod range { - pub use distributions::uniform::Uniform as Range; - pub use distributions::uniform::SampleUniform as SampleRange; -} - -#[allow(deprecated)] -mod impls { - use Rng; - use distributions::{Distribution, Sample, IndependentSample, - WeightedChoice}; - #[cfg(feature="std")] - use distributions::exponential::Exp; - #[cfg(feature="std")] - use distributions::gamma::{Gamma, ChiSquared, FisherF, StudentT}; - #[cfg(feature="std")] - use distributions::normal::{Normal, LogNormal}; - use distributions::range::{Range, SampleRange}; - - impl<'a, T: Clone> Sample for WeightedChoice<'a, T> { - fn sample(&mut self, rng: &mut R) -> T { - Distribution::sample(self, rng) - } - } - impl<'a, T: Clone> IndependentSample for WeightedChoice<'a, T> { - fn ind_sample(&self, rng: &mut R) -> T { - Distribution::sample(self, rng) - } - } - - impl Sample for Range { - fn sample(&mut self, rng: &mut R) -> T { - Distribution::sample(self, rng) - } - } - impl IndependentSample for Range { - fn ind_sample(&self, rng: &mut R) -> T { - Distribution::sample(self, rng) - } - } - - #[cfg(feature="std")] - macro_rules! impl_f64 { - ($($name: ident), *) => { - $( - impl Sample for $name { - fn sample(&mut self, rng: &mut R) -> f64 { - Distribution::sample(self, rng) - } - } - impl IndependentSample for $name { - fn ind_sample(&self, rng: &mut R) -> f64 { - Distribution::sample(self, rng) - } - } - )* - } - } - #[cfg(feature="std")] - impl_f64!(Exp, Gamma, ChiSquared, FisherF, StudentT, Normal, LogNormal); -} - -/// Types (distributions) that can be used to create a random instance of `T`. -/// -/// It is possible to sample from a distribution through both the -/// `Distribution` and [`Rng`] traits, via `distr.sample(&mut rng)` and -/// `rng.sample(distr)`. They also both offer the [`sample_iter`] method, which -/// produces an iterator that samples from the distribution. -/// -/// All implementations are expected to be immutable; this has the significant -/// advantage of not needing to consider thread safety, and for most -/// distributions efficient state-less sampling algorithms are available. -/// -/// [`Rng`]: ../trait.Rng.html -/// [`sample_iter`]: trait.Distribution.html#method.sample_iter -pub trait Distribution { - /// Generate a random value of `T`, using `rng` as the source of randomness. - fn sample(&self, rng: &mut R) -> T; - - /// Create an iterator that generates random values of `T`, using `rng` as - /// the source of randomness. - /// - /// # Example - /// - /// ``` - /// use rand::thread_rng; - /// use rand::distributions::{Distribution, Alphanumeric, Uniform, Standard}; - /// - /// let mut rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec = Standard.sample_iter(&mut rng).take(16).collect(); - /// - /// // String: - /// let s: String = Alphanumeric.sample_iter(&mut rng).take(7).collect(); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = die_range.sample_iter(&mut rng); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter<'a, R>(&'a self, rng: &'a mut R) -> DistIter<'a, Self, R, T> - where Self: Sized, R: Rng - { - DistIter { - distr: self, - rng: rng, - phantom: ::core::marker::PhantomData, - } - } -} - -impl<'a, T, D: Distribution> Distribution for &'a D { - fn sample(&self, rng: &mut R) -> T { - (*self).sample(rng) - } -} - - -/// An iterator that generates random values of `T` with distribution `D`, -/// using `R` as the source of randomness. -/// -/// This `struct` is created by the [`sample_iter`] method on [`Distribution`]. -/// See its documentation for more. -/// -/// [`Distribution`]: trait.Distribution.html -/// [`sample_iter`]: trait.Distribution.html#method.sample_iter -#[derive(Debug)] -pub struct DistIter<'a, D: 'a, R: 'a, T> { - distr: &'a D, - rng: &'a mut R, - phantom: ::core::marker::PhantomData, -} - -impl<'a, D, R, T> Iterator for DistIter<'a, D, R, T> - where D: Distribution, R: Rng + 'a -{ - type Item = T; - - #[inline(always)] - fn next(&mut self) -> Option { - Some(self.distr.sample(self.rng)) - } - - fn size_hint(&self) -> (usize, Option) { - (usize::max_value(), None) - } -} - - -/// A generic random value distribution, implemented for many primitive types. -/// Usually generates values with a numerically uniform distribution, and with a -/// range appropriate to the type. -/// -/// ## Built-in Implementations -/// -/// Assuming the provided `Rng` is well-behaved, these implementations -/// generate values with the following ranges and distributions: -/// -/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed -/// over all values of the type. -/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all -/// code points in the range `0...0x10_FFFF`, except for the range -/// `0xD800...0xDFFF` (the surrogate code points). This includes -/// unassigned/reserved code points. -/// * `bool`: Generates `false` or `true`, each with probability 0.5. -/// * Floating point types (`f32` and `f64`): Uniformly distributed in the -/// half-open range `[0, 1)`. See notes below. -/// * Wrapping integers (`Wrapping`), besides the type identical to their -/// normal integer variants. -/// -/// The following aggregate types also implement the distribution `Standard` as -/// long as their component types implement it: -/// -/// * Tuples and arrays: Each element of the tuple or array is generated -/// independently, using the `Standard` distribution recursively. -/// * `Option` where `Standard` is implemented for `T`: Returns `None` with -/// probability 0.5; otherwise generates a random `x: T` and returns `Some(x)`. -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Standard; -/// -/// let val: f32 = SmallRng::from_entropy().sample(Standard); -/// println!("f32 from [0, 1): {}", val); -/// ``` -/// -/// # Floating point implementation -/// The floating point implementations for `Standard` generate a random value in -/// the half-open interval `[0, 1)`, i.e. including 0 but not 1. -/// -/// All values that can be generated are of the form `n * ε/2`. For `f32` -/// the 23 most significant random bits of a `u32` are used and for `f64` the -/// 53 most significant bits of a `u64` are used. The conversion uses the -/// multiplicative method: `(rng.gen::<$uty>() >> N) as $ty * (ε/2)`. -/// -/// See also: [`Open01`] which samples from `(0, 1)`, [`OpenClosed01`] which -/// samples from `(0, 1]` and `Rng::gen_range(0, 1)` which also samples from -/// `[0, 1)`. Note that `Open01` and `gen_range` (which uses [`Uniform`]) use -/// transmute-based methods which yield 1 bit less precision but may perform -/// faster on some architectures (on modern Intel CPUs all methods have -/// approximately equal performance). -/// -/// [`Open01`]: struct.Open01.html -/// [`OpenClosed01`]: struct.OpenClosed01.html -/// [`Uniform`]: uniform/struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct Standard; - -#[allow(deprecated)] -impl ::Rand for T where Standard: Distribution { - fn rand(rng: &mut R) -> Self { - Standard.sample(rng) - } -} - - -/// A value with a particular weight for use with `WeightedChoice`. -#[derive(Copy, Clone, Debug)] -pub struct Weighted { - /// The numerical weight of this item - pub weight: u32, - /// The actual item which is being weighted - pub item: T, -} - -/// A distribution that selects from a finite collection of weighted items. -/// -/// Each item has an associated weight that influences how likely it -/// is to be chosen: higher weight is more likely. -/// -/// The `Clone` restriction is a limitation of the `Distribution` trait. -/// Note that `&T` is (cheaply) `Clone` for all `T`, as is `u32`, so one can -/// store references or indices into another vector. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Weighted, WeightedChoice, Distribution}; -/// -/// let mut items = vec!(Weighted { weight: 2, item: 'a' }, -/// Weighted { weight: 4, item: 'b' }, -/// Weighted { weight: 1, item: 'c' }); -/// let wc = WeightedChoice::new(&mut items); -/// let mut rng = rand::thread_rng(); -/// for _ in 0..16 { -/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice. -/// println!("{}", wc.sample(&mut rng)); -/// } -/// ``` -#[derive(Debug)] -pub struct WeightedChoice<'a, T:'a> { - items: &'a mut [Weighted], - weight_range: Uniform, -} - -impl<'a, T: Clone> WeightedChoice<'a, T> { - /// Create a new `WeightedChoice`. - /// - /// Panics if: - /// - /// - `items` is empty - /// - the total weight is 0 - /// - the total weight is larger than a `u32` can contain. - pub fn new(items: &'a mut [Weighted]) -> WeightedChoice<'a, T> { - // strictly speaking, this is subsumed by the total weight == 0 case - assert!(!items.is_empty(), "WeightedChoice::new called with no items"); - - let mut running_total: u32 = 0; - - // we convert the list from individual weights to cumulative - // weights so we can binary search. This *could* drop elements - // with weight == 0 as an optimisation. - for item in items.iter_mut() { - running_total = match running_total.checked_add(item.weight) { - Some(n) => n, - None => panic!("WeightedChoice::new called with a total weight \ - larger than a u32 can contain") - }; - - item.weight = running_total; - } - assert!(running_total != 0, "WeightedChoice::new called with a total weight of 0"); - - WeightedChoice { - items, - // we're likely to be generating numbers in this range - // relatively often, so might as well cache it - weight_range: Uniform::new(0, running_total) - } - } -} - -impl<'a, T: Clone> Distribution for WeightedChoice<'a, T> { - fn sample(&self, rng: &mut R) -> T { - // we want to find the first element that has cumulative - // weight > sample_weight, which we do by binary since the - // cumulative weights of self.items are sorted. - - // choose a weight in [0, total_weight) - let sample_weight = self.weight_range.sample(rng); - - // short circuit when it's the first item - if sample_weight < self.items[0].weight { - return self.items[0].item.clone(); - } - - let mut idx = 0; - let mut modifier = self.items.len(); - - // now we know that every possibility has an element to the - // left, so we can just search for the last element that has - // cumulative weight <= sample_weight, then the next one will - // be "it". (Note that this greatest element will never be the - // last element of the vector, since sample_weight is chosen - // in [0, total_weight) and the cumulative weight of the last - // one is exactly the total weight.) - while modifier > 1 { - let i = idx + modifier / 2; - if self.items[i].weight <= sample_weight { - // we're small, so look to the right, but allow this - // exact element still. - idx = i; - // we need the `/ 2` to round up otherwise we'll drop - // the trailing elements when `modifier` is odd. - modifier += 1; - } else { - // otherwise we're too big, so go left. (i.e. do - // nothing) - } - modifier /= 2; - } - self.items[idx + 1].item.clone() - } -} - -/// Sample a random number using the Ziggurat method (specifically the -/// ZIGNOR variant from Doornik 2005). Most of the arguments are -/// directly from the paper: -/// -/// * `rng`: source of randomness -/// * `symmetric`: whether this is a symmetric distribution, or one-sided with P(x < 0) = 0. -/// * `X`: the $x_i$ abscissae. -/// * `F`: precomputed values of the PDF at the $x_i$, (i.e. $f(x_i)$) -/// * `F_DIFF`: precomputed values of $f(x_i) - f(x_{i+1})$ -/// * `pdf`: the probability density function -/// * `zero_case`: manual sampling from the tail when we chose the -/// bottom box (i.e. i == 0) - -// the perf improvement (25-50%) is definitely worth the extra code -// size from force-inlining. -#[cfg(feature="std")] -#[inline(always)] -fn ziggurat( - rng: &mut R, - symmetric: bool, - x_tab: ziggurat_tables::ZigTable, - f_tab: ziggurat_tables::ZigTable, - mut pdf: P, - mut zero_case: Z) - -> f64 where P: FnMut(f64) -> f64, Z: FnMut(&mut R, f64) -> f64 { - loop { - // As an optimisation we re-implement the conversion to a f64. - // From the remaining 12 most significant bits we use 8 to construct `i`. - // This saves us generating a whole extra random number, while the added - // precision of using 64 bits for f64 does not buy us much. - let bits = rng.next_u64(); - let i = bits as usize & 0xff; - - let u = if symmetric { - // Convert to a value in the range [2,4) and substract to get [-1,1) - // We can't convert to an open range directly, that would require - // substracting `3.0 - EPSILON`, which is not representable. - // It is possible with an extra step, but an open range does not - // seem neccesary for the ziggurat algorithm anyway. - (bits >> 12).into_float_with_exponent(1) - 3.0 - } else { - // Convert to a value in the range [1,2) and substract to get (0,1) - (bits >> 12).into_float_with_exponent(0) - - (1.0 - ::core::f64::EPSILON / 2.0) - }; - let x = u * x_tab[i]; - - let test_x = if symmetric { x.abs() } else {x}; - - // algebraically equivalent to |u| < x_tab[i+1]/x_tab[i] (or u < x_tab[i+1]/x_tab[i]) - if test_x < x_tab[i + 1] { - return x; - } - if i == 0 { - return zero_case(rng, u); - } - // algebraically equivalent to f1 + DRanU()*(f0 - f1) < 1 - if f_tab[i + 1] + (f_tab[i] - f_tab[i + 1]) * rng.gen::() < pdf(x) { - return x; - } - } -} - -#[cfg(test)] -mod tests { - use Rng; - use rngs::mock::StepRng; - use super::{WeightedChoice, Weighted, Distribution}; - - #[test] - fn test_weighted_choice() { - // this makes assumptions about the internal implementation of - // WeightedChoice. It may fail when the implementation in - // `distributions::uniform::UniformInt` changes. - - macro_rules! t { - ($items:expr, $expected:expr) => {{ - let mut items = $items; - let mut total_weight = 0; - for item in &items { total_weight += item.weight; } - - let wc = WeightedChoice::new(&mut items); - let expected = $expected; - - // Use extremely large steps between the random numbers, because - // we test with small ranges and `UniformInt` is designed to prefer - // the most significant bits. - let mut rng = StepRng::new(0, !0 / (total_weight as u64)); - - for &val in expected.iter() { - assert_eq!(wc.sample(&mut rng), val) - } - }} - } - - t!([Weighted { weight: 1, item: 10}], [10]); - - // skip some - t!([Weighted { weight: 0, item: 20}, - Weighted { weight: 2, item: 21}, - Weighted { weight: 0, item: 22}, - Weighted { weight: 1, item: 23}], - [21, 21, 23]); - - // different weights - t!([Weighted { weight: 4, item: 30}, - Weighted { weight: 3, item: 31}], - [30, 31, 30, 31, 30, 31, 30]); - - // check that we're binary searching - // correctly with some vectors of odd - // length. - t!([Weighted { weight: 1, item: 40}, - Weighted { weight: 1, item: 41}, - Weighted { weight: 1, item: 42}, - Weighted { weight: 1, item: 43}, - Weighted { weight: 1, item: 44}], - [40, 41, 42, 43, 44]); - t!([Weighted { weight: 1, item: 50}, - Weighted { weight: 1, item: 51}, - Weighted { weight: 1, item: 52}, - Weighted { weight: 1, item: 53}, - Weighted { weight: 1, item: 54}, - Weighted { weight: 1, item: 55}, - Weighted { weight: 1, item: 56}], - [50, 54, 51, 55, 52, 56, 53]); - } - - #[test] - fn test_weighted_clone_initialization() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let clone = initial.clone(); - assert_eq!(initial.weight, clone.weight); - assert_eq!(initial.item, clone.item); - } - - #[test] #[should_panic] - fn test_weighted_clone_change_weight() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.weight = 5; - assert_eq!(initial.weight, clone.weight); - } - - #[test] #[should_panic] - fn test_weighted_clone_change_item() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.item = 5; - assert_eq!(initial.item, clone.item); - - } - - #[test] #[should_panic] - fn test_weighted_choice_no_items() { - WeightedChoice::::new(&mut []); - } - #[test] #[should_panic] - fn test_weighted_choice_zero_weight() { - WeightedChoice::new(&mut [Weighted { weight: 0, item: 0}, - Weighted { weight: 0, item: 1}]); - } - #[test] #[should_panic] - fn test_weighted_choice_weight_overflows() { - let x = ::core::u32::MAX / 2; // x + x + 2 is the overflow - WeightedChoice::new(&mut [Weighted { weight: x, item: 0 }, - Weighted { weight: 1, item: 1 }, - Weighted { weight: x, item: 2 }, - Weighted { weight: 1, item: 3 }]); - } - - #[test] #[allow(deprecated)] - fn test_backwards_compat_sample() { - use distributions::{Sample, IndependentSample}; - - struct Constant { val: T } - impl Sample for Constant { - fn sample(&mut self, _: &mut R) -> T { self.val } - } - impl IndependentSample for Constant { - fn ind_sample(&self, _: &mut R) -> T { self.val } - } - - let mut sampler = Constant{ val: 293 }; - assert_eq!(sampler.sample(&mut ::test::rng(233)), 293); - assert_eq!(sampler.ind_sample(&mut ::test::rng(234)), 293); - } - - #[cfg(feature="std")] - #[test] #[allow(deprecated)] - fn test_backwards_compat_exp() { - use distributions::{IndependentSample, Exp}; - let sampler = Exp::new(1.0); - sampler.ind_sample(&mut ::test::rng(235)); - } - - #[cfg(feature="std")] - #[test] - fn test_distributions_iter() { - use distributions::Normal; - let mut rng = ::test::rng(210); - let distr = Normal::new(10.0, 10.0); - let results: Vec<_> = distr.sample_iter(&mut rng).take(100).collect(); - println!("{:?}", results); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/normal.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/normal.rs deleted file mode 100644 index f053fb6..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/normal.rs +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The normal and derived distributions. - -use Rng; -use distributions::{ziggurat, ziggurat_tables, Distribution, Open01}; - -/// Samples floating-point numbers according to the normal distribution -/// `N(0, 1)` (a.k.a. a standard normal, or Gaussian). This is equivalent to -/// `Normal::new(0.0, 1.0)` but faster. -/// -/// See `Normal` for the general normal distribution. -/// -/// Implemented via the ZIGNOR variant[^1] of the Ziggurat method. -/// -/// [^1]: Jurgen A. Doornik (2005). [*An Improved Ziggurat Method to -/// Generate Normal Random Samples*]( -/// https://www.doornik.com/research/ziggurat.pdf). -/// Nuffield College, Oxford -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::StandardNormal; -/// -/// let val: f64 = SmallRng::from_entropy().sample(StandardNormal); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct StandardNormal; - -impl Distribution for StandardNormal { - fn sample(&self, rng: &mut R) -> f64 { - #[inline] - fn pdf(x: f64) -> f64 { - (-x*x/2.0).exp() - } - #[inline] - fn zero_case(rng: &mut R, u: f64) -> f64 { - // compute a random number in the tail by hand - - // strange initial conditions, because the loop is not - // do-while, so the condition should be true on the first - // run, they get overwritten anyway (0 < 1, so these are - // good). - let mut x = 1.0f64; - let mut y = 0.0f64; - - while -2.0 * y < x * x { - let x_: f64 = rng.sample(Open01); - let y_: f64 = rng.sample(Open01); - - x = x_.ln() / ziggurat_tables::ZIG_NORM_R; - y = y_.ln(); - } - - if u < 0.0 { x - ziggurat_tables::ZIG_NORM_R } else { ziggurat_tables::ZIG_NORM_R - x } - } - - ziggurat(rng, true, // this is symmetric - &ziggurat_tables::ZIG_NORM_X, - &ziggurat_tables::ZIG_NORM_F, - pdf, zero_case) - } -} - -/// The normal distribution `N(mean, std_dev**2)`. -/// -/// This uses the ZIGNOR variant of the Ziggurat method, see `StandardNormal` -/// for more details. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Normal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let normal = Normal::new(2.0, 3.0); -/// let v = normal.sample(&mut rand::thread_rng()); -/// println!("{} is from a N(2, 9) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Normal { - mean: f64, - std_dev: f64, -} - -impl Normal { - /// Construct a new `Normal` distribution with the given mean and - /// standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> Normal { - assert!(std_dev >= 0.0, "Normal::new called with `std_dev` < 0"); - Normal { - mean, - std_dev - } - } -} -impl Distribution for Normal { - fn sample(&self, rng: &mut R) -> f64 { - let n = rng.sample(StandardNormal); - self.mean + self.std_dev * n - } -} - - -/// The log-normal distribution `ln N(mean, std_dev**2)`. -/// -/// If `X` is log-normal distributed, then `ln(X)` is `N(mean, std_dev**2)` -/// distributed. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{LogNormal, Distribution}; -/// -/// // mean 2, standard deviation 3 -/// let log_normal = LogNormal::new(2.0, 3.0); -/// let v = log_normal.sample(&mut rand::thread_rng()); -/// println!("{} is from an ln N(2, 9) distribution", v) -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct LogNormal { - norm: Normal -} - -impl LogNormal { - /// Construct a new `LogNormal` distribution with the given mean - /// and standard deviation. - /// - /// # Panics - /// - /// Panics if `std_dev < 0`. - #[inline] - pub fn new(mean: f64, std_dev: f64) -> LogNormal { - assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); - LogNormal { norm: Normal::new(mean, std_dev) } - } -} -impl Distribution for LogNormal { - fn sample(&self, rng: &mut R) -> f64 { - self.norm.sample(rng).exp() - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::{Normal, LogNormal}; - - #[test] - fn test_normal() { - let norm = Normal::new(10.0, 10.0); - let mut rng = ::test::rng(210); - for _ in 0..1000 { - norm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_normal_invalid_sd() { - Normal::new(10.0, -1.0); - } - - - #[test] - fn test_log_normal() { - let lnorm = LogNormal::new(10.0, 10.0); - let mut rng = ::test::rng(211); - for _ in 0..1000 { - lnorm.sample(&mut rng); - } - } - #[test] - #[should_panic] - fn test_log_normal_invalid_sd() { - LogNormal::new(10.0, -1.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/other.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/other.rs deleted file mode 100644 index f23d2b8..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/other.rs +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of the `Standard` distribution for other built-in types. - -use core::char; -use core::num::Wrapping; - -use {Rng}; -use distributions::{Distribution, Standard, Uniform}; - -// ----- Sampling distributions ----- - -/// Sample a `char`, uniformly distributed over ASCII letters and numbers: -/// a-z, A-Z and 0-9. -/// -/// # Example -/// -/// ``` -/// use std::iter; -/// use rand::{Rng, thread_rng}; -/// use rand::distributions::Alphanumeric; -/// -/// let mut rng = thread_rng(); -/// let chars: String = iter::repeat(()) -/// .map(|()| rng.sample(Alphanumeric)) -/// .take(7) -/// .collect(); -/// println!("Random chars: {}", chars); -/// ``` -#[derive(Debug)] -pub struct Alphanumeric; - - -// ----- Implementations of distributions ----- - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> char { - let range = Uniform::new(0u32, 0x11_0000); - loop { - match char::from_u32(range.sample(rng)) { - Some(c) => return c, - // About 0.2% of numbers in the range 0..0x110000 are invalid - // codepoints (surrogates). - None => {} - } - } - } -} - -impl Distribution for Alphanumeric { - fn sample(&self, rng: &mut R) -> char { - const RANGE: u32 = 26 + 26 + 10; - const GEN_ASCII_STR_CHARSET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789"; - // We can pick from 62 characters. This is so close to a power of 2, 64, - // that we can do better than `Uniform`. Use a simple bitshift and - // rejection sampling. We do not use a bitmask, because for small RNGs - // the most significant bits are usually of higher quality. - loop { - let var = rng.next_u32() >> (32 - 6); - if var < RANGE { - return GEN_ASCII_STR_CHARSET[var as usize] as char - } - } - } -} - -impl Distribution for Standard { - #[inline] - fn sample(&self, rng: &mut R) -> bool { - // We can compare against an arbitrary bit of an u32 to get a bool. - // Because the least significant bits of a lower quality RNG can have - // simple patterns, we compare against the most significant bit. This is - // easiest done using a sign test. - (rng.next_u32() as i32) < 0 - } -} - -macro_rules! tuple_impl { - // use variables to indicate the arity of the tuple - ($($tyvar:ident),* ) => { - // the trailing commas are for the 1 tuple - impl< $( $tyvar ),* > - Distribution<( $( $tyvar ),* , )> - for Standard - where $( Standard: Distribution<$tyvar> ),* - { - #[inline] - fn sample(&self, _rng: &mut R) -> ( $( $tyvar ),* , ) { - ( - // use the $tyvar's to get the appropriate number of - // repeats (they're not actually needed) - $( - _rng.gen::<$tyvar>() - ),* - , - ) - } - } - } -} - -impl Distribution<()> for Standard { - #[inline] - fn sample(&self, _: &mut R) -> () { () } -} -tuple_impl!{A} -tuple_impl!{A, B} -tuple_impl!{A, B, C} -tuple_impl!{A, B, C, D} -tuple_impl!{A, B, C, D, E} -tuple_impl!{A, B, C, D, E, F} -tuple_impl!{A, B, C, D, E, F, G} -tuple_impl!{A, B, C, D, E, F, G, H} -tuple_impl!{A, B, C, D, E, F, G, H, I} -tuple_impl!{A, B, C, D, E, F, G, H, I, J} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} - -macro_rules! array_impl { - // recursive, given at least one type parameter: - {$n:expr, $t:ident, $($ts:ident,)*} => { - array_impl!{($n - 1), $($ts,)*} - - impl Distribution<[T; $n]> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, _rng: &mut R) -> [T; $n] { - [_rng.gen::<$t>(), $(_rng.gen::<$ts>()),*] - } - } - }; - // empty case: - {$n:expr,} => { - impl Distribution<[T; $n]> for Standard { - fn sample(&self, _rng: &mut R) -> [T; $n] { [] } - } - }; -} - -array_impl!{32, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T,} - -impl Distribution> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, rng: &mut R) -> Option { - // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 - if rng.gen::() { - Some(rng.gen()) - } else { - None - } - } -} - -impl Distribution> for Standard where Standard: Distribution { - #[inline] - fn sample(&self, rng: &mut R) -> Wrapping { - Wrapping(rng.gen()) - } -} - - -#[cfg(test)] -mod tests { - use {Rng, RngCore, Standard}; - use distributions::Alphanumeric; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::string::String; - - #[test] - fn test_misc() { - let rng: &mut RngCore = &mut ::test::rng(820); - - rng.sample::(Standard); - rng.sample::(Standard); - } - - #[cfg(feature="alloc")] - #[test] - fn test_chars() { - use core::iter; - let mut rng = ::test::rng(805); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let word: String = iter::repeat(()) - .map(|()| rng.gen::()).take(1000).collect(); - assert!(word.len() != 0); - } - - #[test] - fn test_alphanumeric() { - let mut rng = ::test::rng(806); - - // Test by generating a relatively large number of chars, so we also - // take the rejection sampling path. - let mut incorrect = false; - for _ in 0..100 { - let c = rng.sample(Alphanumeric); - incorrect |= !((c >= '0' && c <= '9') || - (c >= 'A' && c <= 'Z') || - (c >= 'a' && c <= 'z') ); - } - assert!(incorrect == false); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/pareto.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/pareto.rs deleted file mode 100644 index ba628e0..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/pareto.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Pareto distribution. - -use Rng; -use distributions::{Distribution, OpenClosed01}; - -/// Samples floating-point numbers according to the Pareto distribution -/// -/// # Example -/// ``` -/// use rand::prelude::*; -/// use rand::distributions::Pareto; -/// -/// let val: f64 = SmallRng::from_entropy().sample(Pareto::new(1., 2.)); -/// println!("{}", val); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Pareto { - scale: f64, - inv_neg_shape: f64, -} - -impl Pareto { - /// Construct a new Pareto distribution with given `scale` and `shape`. - /// - /// In the literature, `scale` is commonly written as xm or k and - /// `shape` is often written as α. - /// - /// # Panics - /// - /// `scale` and `shape` have to be non-zero and positive. - pub fn new(scale: f64, shape: f64) -> Pareto { - assert!((scale > 0.) & (shape > 0.)); - Pareto { scale, inv_neg_shape: -1.0 / shape } - } -} - -impl Distribution for Pareto { - fn sample(&self, rng: &mut R) -> f64 { - let u: f64 = rng.sample(OpenClosed01); - self.scale * u.powf(self.inv_neg_shape) - } -} - -#[cfg(test)] -mod tests { - use distributions::Distribution; - use super::Pareto; - - #[test] - #[should_panic] - fn invalid() { - Pareto::new(0., 0.); - } - - #[test] - fn sample() { - let scale = 1.0; - let shape = 2.0; - let d = Pareto::new(scale, shape); - let mut rng = ::test::rng(1); - for _ in 0..1000 { - let r = d.sample(&mut rng); - assert!(r >= scale); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/poisson.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/poisson.rs deleted file mode 100644 index bdecb77..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/poisson.rs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2016-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Poisson distribution. - -use Rng; -use distributions::{Distribution, Cauchy}; -use distributions::log_gamma::log_gamma; - -/// The Poisson distribution `Poisson(lambda)`. -/// -/// This distribution has a density function: -/// `f(k) = lambda^k * exp(-lambda) / k!` for `k >= 0`. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Poisson, Distribution}; -/// -/// let poi = Poisson::new(2.0); -/// let v = poi.sample(&mut rand::thread_rng()); -/// println!("{} is from a Poisson(2) distribution", v); -/// ``` -#[derive(Clone, Copy, Debug)] -pub struct Poisson { - lambda: f64, - // precalculated values - exp_lambda: f64, - log_lambda: f64, - sqrt_2lambda: f64, - magic_val: f64, -} - -impl Poisson { - /// Construct a new `Poisson` with the given shape parameter - /// `lambda`. Panics if `lambda <= 0`. - pub fn new(lambda: f64) -> Poisson { - assert!(lambda > 0.0, "Poisson::new called with lambda <= 0"); - let log_lambda = lambda.ln(); - Poisson { - lambda, - exp_lambda: (-lambda).exp(), - log_lambda, - sqrt_2lambda: (2.0 * lambda).sqrt(), - magic_val: lambda * log_lambda - log_gamma(1.0 + lambda), - } - } -} - -impl Distribution for Poisson { - fn sample(&self, rng: &mut R) -> u64 { - // using the algorithm from Numerical Recipes in C - - // for low expected values use the Knuth method - if self.lambda < 12.0 { - let mut result = 0; - let mut p = 1.0; - while p > self.exp_lambda { - p *= rng.gen::(); - result += 1; - } - result - 1 - } - // high expected values - rejection method - else { - let mut int_result: u64; - - // we use the Cauchy distribution as the comparison distribution - // f(x) ~ 1/(1+x^2) - let cauchy = Cauchy::new(0.0, 1.0); - - loop { - let mut result; - let mut comp_dev; - - loop { - // draw from the Cauchy distribution - comp_dev = rng.sample(cauchy); - // shift the peak of the comparison ditribution - result = self.sqrt_2lambda * comp_dev + self.lambda; - // repeat the drawing until we are in the range of possible values - if result >= 0.0 { - break; - } - } - // now the result is a random variable greater than 0 with Cauchy distribution - // the result should be an integer value - result = result.floor(); - int_result = result as u64; - - // this is the ratio of the Poisson distribution to the comparison distribution - // the magic value scales the distribution function to a range of approximately 0-1 - // since it is not exact, we multiply the ratio by 0.9 to avoid ratios greater than 1 - // this doesn't change the resulting distribution, only increases the rate of failed drawings - let check = 0.9 * (1.0 + comp_dev * comp_dev) - * (result * self.log_lambda - log_gamma(1.0 + result) - self.magic_val).exp(); - - // check with uniform random value - if below the threshold, we are within the target distribution - if rng.gen::() <= check { - break; - } - } - int_result - } - } -} - -#[cfg(test)] -mod test { - use distributions::Distribution; - use super::Poisson; - - #[test] - fn test_poisson_10() { - let poisson = Poisson::new(10.0); - let mut rng = ::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 10.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - fn test_poisson_15() { - // Take the 'high expected values' path - let poisson = Poisson::new(15.0); - let mut rng = ::test::rng(123); - let mut sum = 0; - for _ in 0..1000 { - sum += poisson.sample(&mut rng); - } - let avg = (sum as f64) / 1000.0; - println!("Poisson average: {}", avg); - assert!((avg - 15.0).abs() < 0.5); // not 100% certain, but probable enough - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_zero() { - Poisson::new(0.0); - } - - #[test] - #[should_panic] - fn test_poisson_invalid_lambda_neg() { - Poisson::new(-10.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/uniform.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/uniform.rs deleted file mode 100644 index 8fda031..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/uniform.rs +++ /dev/null @@ -1,856 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A distribution uniformly sampling numbers within a given range. -//! -//! [`Uniform`] is the standard distribution to sample uniformly from a range; -//! e.g. `Uniform::new_inclusive(1, 6)` can sample integers from 1 to 6, like a -//! standard die. [`Rng::gen_range`] supports any type supported by -//! [`Uniform`]. -//! -//! This distribution is provided with support for several primitive types -//! (all integer and floating-point types) as well as `std::time::Duration`, -//! and supports extension to user-defined types via a type-specific *back-end* -//! implementation. -//! -//! The types [`UniformInt`], [`UniformFloat`] and [`UniformDuration`] are the -//! back-ends supporting sampling from primitive integer and floating-point -//! ranges as well as from `std::time::Duration`; these types do not normally -//! need to be used directly (unless implementing a derived back-end). -//! -//! # Example usage -//! -//! ``` -//! use rand::{Rng, thread_rng}; -//! use rand::distributions::Uniform; -//! -//! let mut rng = thread_rng(); -//! let side = Uniform::new(-10.0, 10.0); -//! -//! // sample between 1 and 10 points -//! for _ in 0..rng.gen_range(1, 11) { -//! // sample a point from the square with sides -10 - 10 in two dimensions -//! let (x, y) = (rng.sample(side), rng.sample(side)); -//! println!("Point: {}, {}", x, y); -//! } -//! ``` -//! -//! # Extending `Uniform` to support a custom type -//! -//! To extend [`Uniform`] to support your own types, write a back-end which -//! implements the [`UniformSampler`] trait, then implement the [`SampleUniform`] -//! helper trait to "register" your back-end. See the `MyF32` example below. -//! -//! At a minimum, the back-end needs to store any parameters needed for sampling -//! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`. -//! Those methods should include an assert to check the range is valid (i.e. -//! `low < high`). The example below merely wraps another back-end. -//! -//! ``` -//! use rand::prelude::*; -//! use rand::distributions::uniform::{Uniform, SampleUniform, -//! UniformSampler, UniformFloat}; -//! -//! struct MyF32(f32); -//! -//! #[derive(Clone, Copy, Debug)] -//! struct UniformMyF32 { -//! inner: UniformFloat, -//! } -//! -//! impl UniformSampler for UniformMyF32 { -//! type X = MyF32; -//! fn new(low: Self::X, high: Self::X) -> Self { -//! UniformMyF32 { -//! inner: UniformFloat::::new(low.0, high.0), -//! } -//! } -//! fn new_inclusive(low: Self::X, high: Self::X) -> Self { -//! UniformSampler::new(low, high) -//! } -//! fn sample(&self, rng: &mut R) -> Self::X { -//! MyF32(self.inner.sample(rng)) -//! } -//! } -//! -//! impl SampleUniform for MyF32 { -//! type Sampler = UniformMyF32; -//! } -//! -//! let (low, high) = (MyF32(17.0f32), MyF32(22.0f32)); -//! let uniform = Uniform::new(low, high); -//! let x = uniform.sample(&mut thread_rng()); -//! ``` -//! -//! [`Uniform`]: struct.Uniform.html -//! [`Rng::gen_range`]: ../../trait.Rng.html#method.gen_range -//! [`SampleUniform`]: trait.SampleUniform.html -//! [`UniformSampler`]: trait.UniformSampler.html -//! [`UniformInt`]: struct.UniformInt.html -//! [`UniformFloat`]: struct.UniformFloat.html -//! [`UniformDuration`]: struct.UniformDuration.html - -#[cfg(feature = "std")] -use std::time::Duration; - -use Rng; -use distributions::Distribution; -use distributions::float::IntoFloat; - -/// Sample values uniformly between two bounds. -/// -/// [`Uniform::new`] and [`Uniform::new_inclusive`] construct a uniform -/// distribution sampling from the given range; these functions may do extra -/// work up front to make sampling of multiple values faster. -/// -/// When sampling from a constant range, many calculations can happen at -/// compile-time and all methods should be fast; for floating-point ranges and -/// the full range of integer types this should have comparable performance to -/// the `Standard` distribution. -/// -/// Steps are taken to avoid bias which might be present in naive -/// implementations; for example `rng.gen::() % 170` samples from the range -/// `[0, 169]` but is twice as likely to select numbers less than 85 than other -/// values. Further, the implementations here give more weight to the high-bits -/// generated by the RNG than the low bits, since with some RNGs the low-bits -/// are of lower quality than the high bits. -/// -/// Implementations should attempt to sample in `[low, high)` for -/// `Uniform::new(low, high)`, i.e., excluding `high`, but this may be very -/// difficult. All the primitive integer types satisfy this property, and the -/// float types normally satisfy it, but rounding may mean `high` can occur. -/// -/// # Example -/// -/// ``` -/// use rand::distributions::{Distribution, Uniform}; -/// -/// fn main() { -/// let between = Uniform::from(10..10000); -/// let mut rng = rand::thread_rng(); -/// let mut sum = 0; -/// for _ in 0..1000 { -/// sum += between.sample(&mut rng); -/// } -/// println!("{}", sum); -/// } -/// ``` -/// -/// [`Uniform::new`]: struct.Uniform.html#method.new -/// [`Uniform::new_inclusive`]: struct.Uniform.html#method.new_inclusive -/// [`new`]: struct.Uniform.html#method.new -/// [`new_inclusive`]: struct.Uniform.html#method.new_inclusive -#[derive(Clone, Copy, Debug)] -pub struct Uniform { - inner: X::Sampler, -} - -impl Uniform { - /// Create a new `Uniform` instance which samples uniformly from the half - /// open range `[low, high)` (excluding `high`). Panics if `low >= high`. - pub fn new(low: X, high: X) -> Uniform { - Uniform { inner: X::Sampler::new(low, high) } - } - - /// Create a new `Uniform` instance which samples uniformly from the closed - /// range `[low, high]` (inclusive). Panics if `low > high`. - pub fn new_inclusive(low: X, high: X) -> Uniform { - Uniform { inner: X::Sampler::new_inclusive(low, high) } - } -} - -impl Distribution for Uniform { - fn sample(&self, rng: &mut R) -> X { - self.inner.sample(rng) - } -} - -/// Helper trait for creating objects using the correct implementation of -/// [`UniformSampler`] for the sampling type. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [module documentation]: index.html -/// [`Uniform`]: struct.Uniform.html -pub trait SampleUniform: Sized { - /// The `UniformSampler` implementation supporting type `X`. - type Sampler: UniformSampler; -} - -/// Helper trait handling actual uniform sampling. -/// -/// See the [module documentation] on how to implement [`Uniform`] range -/// sampling for a custom type. -/// -/// Implementation of [`sample_single`] is optional, and is only useful when -/// the implementation can be faster than `Self::new(low, high).sample(rng)`. -/// -/// [module documentation]: index.html -/// [`Uniform`]: struct.Uniform.html -/// [`sample_single`]: trait.UniformSampler.html#method.sample_single -pub trait UniformSampler: Sized { - /// The type sampled by this implementation. - type X; - - /// Construct self, with inclusive lower bound and exclusive upper bound - /// `[low, high)`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new`, which asserts that `low < high` before calling this. - fn new(low: Self::X, high: Self::X) -> Self; - - /// Construct self, with inclusive bounds `[low, high]`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::new_inclusive`, which asserts that `low <= high` before - /// calling this. - fn new_inclusive(low: Self::X, high: Self::X) -> Self; - - /// Sample a value. - fn sample(&self, rng: &mut R) -> Self::X; - - /// Sample a single value uniformly from a range with inclusive lower bound - /// and exclusive upper bound `[low, high)`. - /// - /// Usually users should not call this directly but instead use - /// `Uniform::sample_single`, which asserts that `low < high` before calling - /// this. - /// - /// Via this method, implementations can provide a method optimized for - /// sampling only a single value from the specified range. The default - /// implementation simply calls `UniformSampler::new` then `sample` on the - /// result. - fn sample_single(low: Self::X, high: Self::X, rng: &mut R) - -> Self::X - { - let uniform: Self = UniformSampler::new(low, high); - uniform.sample(rng) - } -} - -impl From<::core::ops::Range> for Uniform { - fn from(r: ::core::ops::Range) -> Uniform { - Uniform::new(r.start, r.end) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -// What follows are all back-ends. - - -/// The back-end implementing [`UniformSampler`] for integer types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// For a closed range, the number of possible numbers we should generate is -/// `range = (high - low + 1)`. It is not possible to end up with a uniform -/// distribution if we map *all* the random integers that can be generated to -/// this range. We have to map integers from a `zone` that is a multiple of the -/// range. The rest of the integers, that cause a bias, are rejected. -/// -/// The problem with `range` is that to cover the full range of the type, it has -/// to store `unsigned_max + 1`, which can't be represented. But if the range -/// covers the full range of the type, no modulus is needed. A range of size 0 -/// can't exist, so we use that to represent this special case. Wrapping -/// arithmetic even makes representing `unsigned_max + 1` as 0 simple. -/// -/// We don't calculate `zone` directly, but first calculate the number of -/// integers to reject. To handle `unsigned_max + 1` not fitting in the type, -/// we use: -/// `ints_to_reject = (unsigned_max + 1) % range;` -/// `ints_to_reject = (unsigned_max - range + 1) % range;` -/// -/// The smallest integer PRNGs generate is `u32`. That is why for small integer -/// sizes (`i8`/`u8` and `i16`/`u16`) there is an optimization: don't pick the -/// largest zone that can fit in the small type, but pick the largest zone that -/// can fit in an `u32`. `ints_to_reject` is always less than half the size of -/// the small integer. This means the first bit of `zone` is always 1, and so -/// are all the other preceding bits of a larger integer. The easiest way to -/// grow the `zone` for the larger type is to simply sign extend it. -/// -/// An alternative to using a modulus is widening multiply: After a widening -/// multiply by `range`, the result is in the high word. Then comparing the low -/// word against `zone` makes sure our distribution is uniform. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`Uniform`]: struct.Uniform.html -#[derive(Clone, Copy, Debug)] -pub struct UniformInt { - low: X, - range: X, - zone: X, -} - -macro_rules! uniform_int_impl { - ($ty:ty, $signed:ty, $unsigned:ident, - $i_large:ident, $u_large:ident) => { - impl SampleUniform for $ty { - type Sampler = UniformInt<$ty>; - } - - impl UniformSampler for UniformInt<$ty> { - // We play free and fast with unsigned vs signed here - // (when $ty is signed), but that's fine, since the - // contract of this macro is for $ty and $unsigned to be - // "bit-equal", so casting between them is a no-op. - - type X = $ty; - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new(low: Self::X, high: Self::X) -> Self { - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformSampler::new_inclusive(low, high - 1) - } - - #[inline] // if the range is constant, this helps LLVM to do the - // calculations at compile-time. - fn new_inclusive(low: Self::X, high: Self::X) -> Self { - assert!(low <= high, - "Uniform::new_inclusive called with `low > high`"); - let unsigned_max = ::core::$unsigned::MAX; - - let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned; - let ints_to_reject = - if range > 0 { - (unsigned_max - range + 1) % range - } else { - 0 - }; - let zone = unsigned_max - ints_to_reject; - - UniformInt { - low: low, - // These are really $unsigned values, but store as $ty: - range: range as $ty, - zone: zone as $ty - } - } - - fn sample(&self, rng: &mut R) -> Self::X { - let range = self.range as $unsigned as $u_large; - if range > 0 { - // Grow `zone` to fit a type of at least 32 bits, by - // sign-extending it (the first bit is always 1, so are all - // the preceding bits of the larger type). - // For types that already have the right size, all the - // casting is a no-op. - let zone = self.zone as $signed as $i_large as $u_large; - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return self.low.wrapping_add(hi as $ty); - } - } - } else { - // Sample from the entire integer range. - rng.gen() - } - } - - fn sample_single(low: Self::X, - high: Self::X, - rng: &mut R) -> Self::X - { - assert!(low < high, - "Uniform::sample_single called with low >= high"); - let range = high.wrapping_sub(low) as $unsigned as $u_large; - let zone = - if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned { - // Using a modulus is faster than the approximation for - // i8 and i16. I suppose we trade the cost of one - // modulus for near-perfect branch prediction. - let unsigned_max: $u_large = ::core::$u_large::MAX; - let ints_to_reject = (unsigned_max - range + 1) % range; - unsigned_max - ints_to_reject - } else { - // conservative but fast approximation - range << range.leading_zeros() - }; - - loop { - let v: $u_large = rng.gen(); - let (hi, lo) = v.wmul(range); - if lo <= zone { - return low.wrapping_add(hi as $ty); - } - } - } - } - } -} - -uniform_int_impl! { i8, i8, u8, i32, u32 } -uniform_int_impl! { i16, i16, u16, i32, u32 } -uniform_int_impl! { i32, i32, u32, i32, u32 } -uniform_int_impl! { i64, i64, u64, i64, u64 } -#[cfg(feature = "i128_support")] -uniform_int_impl! { i128, i128, u128, u128, u128 } -uniform_int_impl! { isize, isize, usize, isize, usize } -uniform_int_impl! { u8, i8, u8, i32, u32 } -uniform_int_impl! { u16, i16, u16, i32, u32 } -uniform_int_impl! { u32, i32, u32, i32, u32 } -uniform_int_impl! { u64, i64, u64, i64, u64 } -uniform_int_impl! { usize, isize, usize, isize, usize } -#[cfg(feature = "i128_support")] -uniform_int_impl! { u128, u128, u128, i128, u128 } - - -trait WideningMultiply { - type Output; - - fn wmul(self, x: RHS) -> Self::Output; -} - -macro_rules! wmul_impl { - ($ty:ty, $wide:ty, $shift:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, x: $ty) -> Self::Output { - let tmp = (self as $wide) * (x as $wide); - ((tmp >> $shift) as $ty, tmp as $ty) - } - } - } -} -wmul_impl! { u8, u16, 8 } -wmul_impl! { u16, u32, 16 } -wmul_impl! { u32, u64, 32 } -#[cfg(feature = "i128_support")] -wmul_impl! { u64, u128, 64 } - -// This code is a translation of the __mulddi3 function in LLVM's -// compiler-rt. It is an optimised variant of the common method -// `(a + b) * (c + d) = ac + ad + bc + bd`. -// -// For some reason LLVM can optimise the C version very well, but -// keeps shuffeling registers in this Rust translation. -macro_rules! wmul_impl_large { - ($ty:ty, $half:expr) => { - impl WideningMultiply for $ty { - type Output = ($ty, $ty); - - #[inline(always)] - fn wmul(self, b: $ty) -> Self::Output { - const LOWER_MASK: $ty = !0 >> $half; - let mut low = (self & LOWER_MASK).wrapping_mul(b & LOWER_MASK); - let mut t = low >> $half; - low &= LOWER_MASK; - t += (self >> $half).wrapping_mul(b & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - let mut high = t >> $half; - t = low >> $half; - low &= LOWER_MASK; - t += (b >> $half).wrapping_mul(self & LOWER_MASK); - low += (t & LOWER_MASK) << $half; - high += t >> $half; - high += (self >> $half).wrapping_mul(b >> $half); - - (high, low) - } - } - } -} -#[cfg(not(feature = "i128_support"))] -wmul_impl_large! { u64, 32 } -#[cfg(feature = "i128_support")] -wmul_impl_large! { u128, 64 } - -macro_rules! wmul_impl_usize { - ($ty:ty) => { - impl WideningMultiply for usize { - type Output = (usize, usize); - - #[inline(always)] - fn wmul(self, x: usize) -> Self::Output { - let (high, low) = (self as $ty).wmul(x as $ty); - (high as usize, low as usize) - } - } - } -} -#[cfg(target_pointer_width = "32")] -wmul_impl_usize! { u32 } -#[cfg(target_pointer_width = "64")] -wmul_impl_usize! { u64 } - - - -/// The back-end implementing [`UniformSampler`] for floating-point types. -/// -/// Unless you are implementing [`UniformSampler`] for your own type, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// # Implementation notes -/// -/// Instead of generating a float in the `[0, 1)` range using [`Standard`], the -/// `UniformFloat` implementation converts the output of an PRNG itself. This -/// way one or two steps can be optimized out. -/// -/// The floats are first converted to a value in the `[1, 2)` interval using a -/// transmute-based method, and then mapped to the expected range with a -/// multiply and addition. Values produced this way have what equals 22 bits of -/// random digits for an `f32`, and 52 for an `f64`. -/// -/// Currently there is no difference between [`new`] and [`new_inclusive`], -/// because the boundaries of a floats range are a bit of a fuzzy concept due to -/// rounding errors. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`new`]: trait.UniformSampler.html#tymethod.new -/// [`new_inclusive`]: trait.UniformSampler.html#tymethod.new_inclusive -/// [`Uniform`]: struct.Uniform.html -/// [`Standard`]: ../struct.Standard.html -#[derive(Clone, Copy, Debug)] -pub struct UniformFloat { - scale: X, - offset: X, -} - -macro_rules! uniform_float_impl { - ($ty:ty, $bits_to_discard:expr, $next_u:ident) => { - impl SampleUniform for $ty { - type Sampler = UniformFloat<$ty>; - } - - impl UniformSampler for UniformFloat<$ty> { - type X = $ty; - - fn new(low: Self::X, high: Self::X) -> Self { - assert!(low < high, "Uniform::new called with `low >= high`"); - let scale = high - low; - let offset = low - scale; - UniformFloat { - scale: scale, - offset: offset, - } - } - - fn new_inclusive(low: Self::X, high: Self::X) -> Self { - assert!(low <= high, - "Uniform::new_inclusive called with `low > high`"); - let scale = high - low; - let offset = low - scale; - UniformFloat { - scale: scale, - offset: offset, - } - } - - fn sample(&self, rng: &mut R) -> Self::X { - // Generate a value in the range [1, 2) - let value1_2 = (rng.$next_u() >> $bits_to_discard) - .into_float_with_exponent(0); - // We don't use `f64::mul_add`, because it is not available with - // `no_std`. Furthermore, it is slower for some targets (but - // faster for others). However, the order of multiplication and - // addition is important, because on some platforms (e.g. ARM) - // it will be optimized to a single (non-FMA) instruction. - value1_2 * self.scale + self.offset - } - - fn sample_single(low: Self::X, - high: Self::X, - rng: &mut R) -> Self::X { - assert!(low < high, - "Uniform::sample_single called with low >= high"); - let scale = high - low; - let offset = low - scale; - // Generate a value in the range [1, 2) - let value1_2 = (rng.$next_u() >> $bits_to_discard) - .into_float_with_exponent(0); - // Doing multiply before addition allows some architectures to - // use a single instruction. - value1_2 * scale + offset - } - } - } -} - -uniform_float_impl! { f32, 32 - 23, next_u32 } -uniform_float_impl! { f64, 64 - 52, next_u64 } - - - -/// The back-end implementing [`UniformSampler`] for `Duration`. -/// -/// Unless you are implementing [`UniformSampler`] for your own types, this type -/// should not be used directly, use [`Uniform`] instead. -/// -/// [`UniformSampler`]: trait.UniformSampler.html -/// [`Uniform`]: struct.Uniform.html -#[cfg(feature = "std")] -#[derive(Clone, Copy, Debug)] -pub struct UniformDuration { - offset: Duration, - mode: UniformDurationMode, -} - -#[cfg(feature = "std")] -#[derive(Debug, Copy, Clone)] -enum UniformDurationMode { - Small { - nanos: Uniform, - }, - Large { - size: Duration, - secs: Uniform, - } -} - -#[cfg(feature = "std")] -impl SampleUniform for Duration { - type Sampler = UniformDuration; -} - -#[cfg(feature = "std")] -impl UniformSampler for UniformDuration { - type X = Duration; - - #[inline] - fn new(low: Duration, high: Duration) -> UniformDuration { - assert!(low < high, "Uniform::new called with `low >= high`"); - UniformDuration::new_inclusive(low, high - Duration::new(0, 1)) - } - - #[inline] - fn new_inclusive(low: Duration, high: Duration) -> UniformDuration { - assert!(low <= high, "Uniform::new_inclusive called with `low > high`"); - let size = high - low; - let nanos = size - .as_secs() - .checked_mul(1_000_000_000) - .and_then(|n| n.checked_add(size.subsec_nanos() as u64)); - - let mode = match nanos { - Some(nanos) => { - UniformDurationMode::Small { - nanos: Uniform::new_inclusive(0, nanos), - } - } - None => { - UniformDurationMode::Large { - size: size, - secs: Uniform::new_inclusive(0, size.as_secs()), - } - } - }; - - UniformDuration { - mode, - offset: low, - } - } - - #[inline] - fn sample(&self, rng: &mut R) -> Duration { - let d = match self.mode { - UniformDurationMode::Small { nanos } => { - let nanos = nanos.sample(rng); - Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32) - } - UniformDurationMode::Large { size, secs } => { - // constant folding means this is at least as fast as `gen_range` - let nano_range = Uniform::new(0, 1_000_000_000); - loop { - let d = Duration::new(secs.sample(rng), nano_range.sample(rng)); - if d <= size { - break d; - } - } - } - }; - - self.offset + d - } -} - -#[cfg(test)] -mod tests { - use Rng; - use distributions::uniform::{Uniform, UniformSampler, UniformFloat, SampleUniform}; - - #[should_panic] - #[test] - fn test_uniform_bad_limits_equal_int() { - Uniform::new(10, 10); - } - - #[should_panic] - #[test] - fn test_uniform_bad_limits_equal_float() { - Uniform::new(10., 10.); - } - - #[test] - fn test_uniform_good_limits_equal_int() { - let mut rng = ::test::rng(804); - let dist = Uniform::new_inclusive(10, 10); - for _ in 0..20 { - assert_eq!(rng.sample(dist), 10); - } - } - - #[test] - fn test_uniform_good_limits_equal_float() { - let mut rng = ::test::rng(805); - let dist = Uniform::new_inclusive(10., 10.); - for _ in 0..20 { - assert_eq!(rng.sample(dist), 10.); - } - } - - #[should_panic] - #[test] - fn test_uniform_bad_limits_flipped_int() { - Uniform::new(10, 5); - } - - #[should_panic] - #[test] - fn test_uniform_bad_limits_flipped_float() { - Uniform::new(10., 5.); - } - - #[test] - fn test_integers() { - let mut rng = ::test::rng(251); - macro_rules! t { - ($($ty:ident),*) => {{ - $( - let v: &[($ty, $ty)] = &[(0, 10), - (10, 127), - (::core::$ty::MIN, ::core::$ty::MAX)]; - for &(low, high) in v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!(low <= v && v < high); - } - - let my_uniform = Uniform::new_inclusive(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!(low <= v && v <= high); - } - - for _ in 0..1000 { - let v: $ty = rng.gen_range(low, high); - assert!(low <= v && v < high); - } - } - )* - }} - } - t!(i8, i16, i32, i64, isize, - u8, u16, u32, u64, usize); - #[cfg(feature = "i128_support")] - t!(i128, u128) - } - - #[test] - fn test_floats() { - let mut rng = ::test::rng(252); - macro_rules! t { - ($($ty:ty),*) => {{ - $( - let v: &[($ty, $ty)] = &[(0.0, 100.0), - (-1e35, -1e25), - (1e-35, 1e-25), - (-1e35, 1e35)]; - for &(low, high) in v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v: $ty = rng.sample(my_uniform); - assert!(low <= v && v < high); - } - } - )* - }} - } - - t!(f32, f64) - } - - #[test] - #[cfg(feature = "std")] - fn test_durations() { - use std::time::Duration; - - let mut rng = ::test::rng(253); - - let v = &[(Duration::new(10, 50000), Duration::new(100, 1234)), - (Duration::new(0, 100), Duration::new(1, 50)), - (Duration::new(0, 0), Duration::new(u64::max_value(), 999_999_999))]; - for &(low, high) in v.iter() { - let my_uniform = Uniform::new(low, high); - for _ in 0..1000 { - let v = rng.sample(my_uniform); - assert!(low <= v && v < high); - } - } - } - - #[test] - fn test_custom_uniform() { - #[derive(Clone, Copy, PartialEq, PartialOrd)] - struct MyF32 { - x: f32, - } - #[derive(Clone, Copy, Debug)] - struct UniformMyF32 { - inner: UniformFloat, - } - impl UniformSampler for UniformMyF32 { - type X = MyF32; - fn new(low: Self::X, high: Self::X) -> Self { - UniformMyF32 { - inner: UniformFloat::::new(low.x, high.x), - } - } - fn new_inclusive(low: Self::X, high: Self::X) -> Self { - UniformSampler::new(low, high) - } - fn sample(&self, rng: &mut R) -> Self::X { - MyF32 { x: self.inner.sample(rng) } - } - } - impl SampleUniform for MyF32 { - type Sampler = UniformMyF32; - } - - let (low, high) = (MyF32{ x: 17.0f32 }, MyF32{ x: 22.0f32 }); - let uniform = Uniform::new(low, high); - let mut rng = ::test::rng(804); - for _ in 0..100 { - let x: MyF32 = rng.sample(uniform); - assert!(low <= x && x < high); - } - } - - #[test] - fn test_uniform_from_std_range() { - let r = Uniform::from(2u32..7); - assert_eq!(r.inner.low, 2); - assert_eq!(r.inner.range, 5); - let r = Uniform::from(2.0f64..7.0); - assert_eq!(r.inner.offset, -3.0); - assert_eq!(r.inner.scale, 5.0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/distributions/ziggurat_tables.rs b/third_party/cargo/vendor/rand-0.5.6/src/distributions/ziggurat_tables.rs deleted file mode 100644 index 11a2172..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/distributions/ziggurat_tables.rs +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &'static [f64; 257]; -pub const ZIG_NORM_R: f64 = 3.654152885361008796; -pub static ZIG_NORM_X: [f64; 257] = - [3.910757959537090045, 3.654152885361008796, 3.449278298560964462, 3.320244733839166074, - 3.224575052047029100, 3.147889289517149969, 3.083526132001233044, 3.027837791768635434, - 2.978603279880844834, 2.934366867207854224, 2.894121053612348060, 2.857138730872132548, - 2.822877396825325125, 2.790921174000785765, 2.760944005278822555, 2.732685359042827056, - 2.705933656121858100, 2.680514643284522158, 2.656283037575502437, 2.633116393630324570, - 2.610910518487548515, 2.589575986706995181, 2.569035452680536569, 2.549221550323460761, - 2.530075232158516929, 2.511544441625342294, 2.493583041269680667, 2.476149939669143318, - 2.459208374333311298, 2.442725318198956774, 2.426670984935725972, 2.411018413899685520, - 2.395743119780480601, 2.380822795170626005, 2.366237056715818632, 2.351967227377659952, - 2.337996148795031370, 2.324308018869623016, 2.310888250599850036, 2.297723348901329565, - 2.284800802722946056, 2.272108990226823888, 2.259637095172217780, 2.247375032945807760, - 2.235313384928327984, 2.223443340090905718, 2.211756642882544366, 2.200245546609647995, - 2.188902771624720689, 2.177721467738641614, 2.166695180352645966, 2.155817819875063268, - 2.145083634046203613, 2.134487182844320152, 2.124023315687815661, 2.113687150684933957, - 2.103474055713146829, 2.093379631137050279, 2.083399693996551783, 2.073530263516978778, - 2.063767547809956415, 2.054107931648864849, 2.044547965215732788, 2.035084353727808715, - 2.025713947862032960, 2.016433734904371722, 2.007240830558684852, 1.998132471356564244, - 1.989106007615571325, 1.980158896898598364, 1.971288697931769640, 1.962493064942461896, - 1.953769742382734043, 1.945116560006753925, 1.936531428273758904, 1.928012334050718257, - 1.919557336591228847, 1.911164563769282232, 1.902832208548446369, 1.894558525668710081, - 1.886341828534776388, 1.878180486290977669, 1.870072921069236838, 1.862017605397632281, - 1.854013059758148119, 1.846057850283119750, 1.838150586580728607, 1.830289919680666566, - 1.822474540091783224, 1.814703175964167636, 1.806974591348693426, 1.799287584547580199, - 1.791640986550010028, 1.784033659547276329, 1.776464495522344977, 1.768932414909077933, - 1.761436365316706665, 1.753975320315455111, 1.746548278279492994, 1.739154261283669012, - 1.731792314050707216, 1.724461502945775715, 1.717160915015540690, 1.709889657069006086, - 1.702646854797613907, 1.695431651932238548, 1.688243209434858727, 1.681080704722823338, - 1.673943330923760353, 1.666830296159286684, 1.659740822855789499, 1.652674147080648526, - 1.645629517902360339, 1.638606196773111146, 1.631603456932422036, 1.624620582830568427, - 1.617656869570534228, 1.610711622367333673, 1.603784156023583041, 1.596873794420261339, - 1.589979870021648534, 1.583101723393471438, 1.576238702733332886, 1.569390163412534456, - 1.562555467528439657, 1.555733983466554893, 1.548925085471535512, 1.542128153226347553, - 1.535342571438843118, 1.528567729435024614, 1.521803020758293101, 1.515047842773992404, - 1.508301596278571965, 1.501563685112706548, 1.494833515777718391, 1.488110497054654369, - 1.481394039625375747, 1.474683555695025516, 1.467978458615230908, 1.461278162507407830, - 1.454582081885523293, 1.447889631277669675, 1.441200224845798017, 1.434513276002946425, - 1.427828197027290358, 1.421144398672323117, 1.414461289772464658, 1.407778276843371534, - 1.401094763676202559, 1.394410150925071257, 1.387723835686884621, 1.381035211072741964, - 1.374343665770030531, 1.367648583594317957, 1.360949343030101844, 1.354245316759430606, - 1.347535871177359290, 1.340820365893152122, 1.334098153216083604, 1.327368577624624679, - 1.320630975217730096, 1.313884673146868964, 1.307128989027353860, 1.300363230327433728, - 1.293586693733517645, 1.286798664489786415, 1.279998415710333237, 1.273185207661843732, - 1.266358287014688333, 1.259516886060144225, 1.252660221891297887, 1.245787495544997903, - 1.238897891102027415, 1.231990574742445110, 1.225064693752808020, 1.218119375481726552, - 1.211153726239911244, 1.204166830140560140, 1.197157747875585931, 1.190125515422801650, - 1.183069142678760732, 1.175987612011489825, 1.168879876726833800, 1.161744859441574240, - 1.154581450355851802, 1.147388505416733873, 1.140164844363995789, 1.132909248648336975, - 1.125620459211294389, 1.118297174115062909, 1.110938046009249502, 1.103541679420268151, - 1.096106627847603487, 1.088631390649514197, 1.081114409698889389, 1.073554065787871714, - 1.065948674757506653, 1.058296483326006454, 1.050595664586207123, 1.042844313139370538, - 1.035040439828605274, 1.027181966030751292, 1.019266717460529215, 1.011292417434978441, - 1.003256679539591412, 0.995156999629943084, 0.986990747093846266, 0.978755155288937750, - 0.970447311058864615, 0.962064143217605250, 0.953602409875572654, 0.945058684462571130, - 0.936429340280896860, 0.927710533396234771, 0.918898183643734989, 0.909987953490768997, - 0.900975224455174528, 0.891855070726792376, 0.882622229578910122, 0.873271068082494550, - 0.863795545546826915, 0.854189171001560554, 0.844444954902423661, 0.834555354079518752, - 0.824512208745288633, 0.814306670128064347, 0.803929116982664893, 0.793369058833152785, - 0.782615023299588763, 0.771654424216739354, 0.760473406422083165, 0.749056662009581653, - 0.737387211425838629, 0.725446140901303549, 0.713212285182022732, 0.700661841097584448, - 0.687767892786257717, 0.674499822827436479, 0.660822574234205984, 0.646695714884388928, - 0.632072236375024632, 0.616896989996235545, 0.601104617743940417, 0.584616766093722262, - 0.567338257040473026, 0.549151702313026790, 0.529909720646495108, 0.509423329585933393, - 0.487443966121754335, 0.463634336771763245, 0.437518402186662658, 0.408389134588000746, - 0.375121332850465727, 0.335737519180459465, 0.286174591747260509, 0.215241895913273806, - 0.000000000000000000]; -pub static ZIG_NORM_F: [f64; 257] = - [0.000477467764586655, 0.001260285930498598, 0.002609072746106363, 0.004037972593371872, - 0.005522403299264754, 0.007050875471392110, 0.008616582769422917, 0.010214971439731100, - 0.011842757857943104, 0.013497450601780807, 0.015177088307982072, 0.016880083152595839, - 0.018605121275783350, 0.020351096230109354, 0.022117062707379922, 0.023902203305873237, - 0.025705804008632656, 0.027527235669693315, 0.029365939758230111, 0.031221417192023690, - 0.033093219458688698, 0.034980941461833073, 0.036884215688691151, 0.038802707404656918, - 0.040736110656078753, 0.042684144916619378, 0.044646552251446536, 0.046623094902089664, - 0.048613553216035145, 0.050617723861121788, 0.052635418276973649, 0.054666461325077916, - 0.056710690106399467, 0.058767952921137984, 0.060838108349751806, 0.062921024437977854, - 0.065016577971470438, 0.067124653828023989, 0.069245144397250269, 0.071377949059141965, - 0.073522973714240991, 0.075680130359194964, 0.077849336702372207, 0.080030515814947509, - 0.082223595813495684, 0.084428509570654661, 0.086645194450867782, 0.088873592068594229, - 0.091113648066700734, 0.093365311913026619, 0.095628536713353335, 0.097903279039215627, - 0.100189498769172020, 0.102487158942306270, 0.104796225622867056, 0.107116667775072880, - 0.109448457147210021, 0.111791568164245583, 0.114145977828255210, 0.116511665626037014, - 0.118888613443345698, 0.121276805485235437, 0.123676228202051403, 0.126086870220650349, - 0.128508722280473636, 0.130941777174128166, 0.133386029692162844, 0.135841476571757352, - 0.138308116449064322, 0.140785949814968309, 0.143274978974047118, 0.145775208006537926, - 0.148286642733128721, 0.150809290682410169, 0.153343161060837674, 0.155888264725064563, - 0.158444614156520225, 0.161012223438117663, 0.163591108232982951, 0.166181285765110071, - 0.168782774801850333, 0.171395595638155623, 0.174019770082499359, 0.176655321444406654, - 0.179302274523530397, 0.181960655600216487, 0.184630492427504539, 0.187311814224516926, - 0.190004651671193070, 0.192709036904328807, 0.195425003514885592, 0.198152586546538112, - 0.200891822495431333, 0.203642749311121501, 0.206405406398679298, 0.209179834621935651, - 0.211966076307852941, 0.214764175252008499, 0.217574176725178370, 0.220396127481011589, - 0.223230075764789593, 0.226076071323264877, 0.228934165415577484, 0.231804410825248525, - 0.234686861873252689, 0.237581574432173676, 0.240488605941449107, 0.243408015423711988, - 0.246339863502238771, 0.249284212419516704, 0.252241126056943765, 0.255210669955677150, - 0.258192911338648023, 0.261187919133763713, 0.264195763998317568, 0.267216518344631837, - 0.270250256366959984, 0.273297054069675804, 0.276356989296781264, 0.279430141762765316, - 0.282516593084849388, 0.285616426816658109, 0.288729728483353931, 0.291856585618280984, - 0.294997087801162572, 0.298151326697901342, 0.301319396102034120, 0.304501391977896274, - 0.307697412505553769, 0.310907558127563710, 0.314131931597630143, 0.317370638031222396, - 0.320623784958230129, 0.323891482377732021, 0.327173842814958593, 0.330470981380537099, - 0.333783015832108509, 0.337110066638412809, 0.340452257045945450, 0.343809713148291340, - 0.347182563958251478, 0.350570941482881204, 0.353974980801569250, 0.357394820147290515, - 0.360830600991175754, 0.364282468130549597, 0.367750569780596226, 0.371235057669821344, - 0.374736087139491414, 0.378253817247238111, 0.381788410875031348, 0.385340034841733958, - 0.388908860020464597, 0.392495061461010764, 0.396098818517547080, 0.399720314981931668, - 0.403359739222868885, 0.407017284331247953, 0.410693148271983222, 0.414387534042706784, - 0.418100649839684591, 0.421832709231353298, 0.425583931339900579, 0.429354541031341519, - 0.433144769114574058, 0.436954852549929273, 0.440785034667769915, 0.444635565397727750, - 0.448506701509214067, 0.452398706863882505, 0.456311852680773566, 0.460246417814923481, - 0.464202689050278838, 0.468180961407822172, 0.472181538469883255, 0.476204732721683788, - 0.480250865911249714, 0.484320269428911598, 0.488413284707712059, 0.492530263646148658, - 0.496671569054796314, 0.500837575128482149, 0.505028667945828791, 0.509245245998136142, - 0.513487720749743026, 0.517756517232200619, 0.522052074674794864, 0.526374847174186700, - 0.530725304406193921, 0.535103932383019565, 0.539511234259544614, 0.543947731192649941, - 0.548413963257921133, 0.552910490428519918, 0.557437893621486324, 0.561996775817277916, - 0.566587763258951771, 0.571211506738074970, 0.575868682975210544, 0.580559996103683473, - 0.585286179266300333, 0.590047996335791969, 0.594846243770991268, 0.599681752622167719, - 0.604555390700549533, 0.609468064928895381, 0.614420723892076803, 0.619414360609039205, - 0.624450015550274240, 0.629528779928128279, 0.634651799290960050, 0.639820277456438991, - 0.645035480824251883, 0.650298743114294586, 0.655611470583224665, 0.660975147780241357, - 0.666391343912380640, 0.671861719900766374, 0.677388036222513090, 0.682972161648791376, - 0.688616083008527058, 0.694321916130032579, 0.700091918140490099, 0.705928501336797409, - 0.711834248882358467, 0.717811932634901395, 0.723864533472881599, 0.729995264565802437, - 0.736207598131266683, 0.742505296344636245, 0.748892447223726720, 0.755373506511754500, - 0.761953346841546475, 0.768637315803334831, 0.775431304986138326, 0.782341832659861902, - 0.789376143571198563, 0.796542330428254619, 0.803849483176389490, 0.811307874318219935, - 0.818929191609414797, 0.826726833952094231, 0.834716292992930375, 0.842915653118441077, - 0.851346258465123684, 0.860033621203008636, 0.869008688043793165, 0.878309655816146839, - 0.887984660763399880, 0.898095921906304051, 0.908726440060562912, 0.919991505048360247, - 0.932060075968990209, 0.945198953453078028, 0.959879091812415930, 0.977101701282731328, - 1.000000000000000000]; -pub const ZIG_EXP_R: f64 = 7.697117470131050077; -pub static ZIG_EXP_X: [f64; 257] = - [8.697117470131052741, 7.697117470131050077, 6.941033629377212577, 6.478378493832569696, - 6.144164665772472667, 5.882144315795399869, 5.666410167454033697, 5.482890627526062488, - 5.323090505754398016, 5.181487281301500047, 5.054288489981304089, 4.938777085901250530, - 4.832939741025112035, 4.735242996601741083, 4.644491885420085175, 4.559737061707351380, - 4.480211746528421912, 4.405287693473573185, 4.334443680317273007, 4.267242480277365857, - 4.203313713735184365, 4.142340865664051464, 4.084051310408297830, 4.028208544647936762, - 3.974606066673788796, 3.923062500135489739, 3.873417670399509127, 3.825529418522336744, - 3.779270992411667862, 3.734528894039797375, 3.691201090237418825, 3.649195515760853770, - 3.608428813128909507, 3.568825265648337020, 3.530315889129343354, 3.492837654774059608, - 3.456332821132760191, 3.420748357251119920, 3.386035442460300970, 3.352149030900109405, - 3.319047470970748037, 3.286692171599068679, 3.255047308570449882, 3.224079565286264160, - 3.193757903212240290, 3.164053358025972873, 3.134938858084440394, 3.106389062339824481, - 3.078380215254090224, 3.050890016615455114, 3.023897504455676621, 2.997382949516130601, - 2.971327759921089662, 2.945714394895045718, 2.920526286512740821, 2.895747768600141825, - 2.871364012015536371, 2.847360965635188812, 2.823725302450035279, 2.800444370250737780, - 2.777506146439756574, 2.754899196562344610, 2.732612636194700073, 2.710636095867928752, - 2.688959688741803689, 2.667573980773266573, 2.646469963151809157, 2.625639026797788489, - 2.605072938740835564, 2.584763820214140750, 2.564704126316905253, 2.544886627111869970, - 2.525304390037828028, 2.505950763528594027, 2.486819361740209455, 2.467904050297364815, - 2.449198932978249754, 2.430698339264419694, 2.412396812688870629, 2.394289099921457886, - 2.376370140536140596, 2.358635057409337321, 2.341079147703034380, 2.323697874390196372, - 2.306486858283579799, 2.289441870532269441, 2.272558825553154804, 2.255833774367219213, - 2.239262898312909034, 2.222842503111036816, 2.206569013257663858, 2.190438966723220027, - 2.174449009937774679, 2.158595893043885994, 2.142876465399842001, 2.127287671317368289, - 2.111826546019042183, 2.096490211801715020, 2.081275874393225145, 2.066180819490575526, - 2.051202409468584786, 2.036338080248769611, 2.021585338318926173, 2.006941757894518563, - 1.992404978213576650, 1.977972700957360441, 1.963642687789548313, 1.949412758007184943, - 1.935280786297051359, 1.921244700591528076, 1.907302480018387536, 1.893452152939308242, - 1.879691795072211180, 1.866019527692827973, 1.852433515911175554, 1.838931967018879954, - 1.825513128903519799, 1.812175288526390649, 1.798916770460290859, 1.785735935484126014, - 1.772631179231305643, 1.759600930889074766, 1.746643651946074405, 1.733757834985571566, - 1.720942002521935299, 1.708194705878057773, 1.695514524101537912, 1.682900062917553896, - 1.670349953716452118, 1.657862852574172763, 1.645437439303723659, 1.633072416535991334, - 1.620766508828257901, 1.608518461798858379, 1.596327041286483395, 1.584191032532688892, - 1.572109239386229707, 1.560080483527888084, 1.548103603714513499, 1.536177455041032092, - 1.524300908219226258, 1.512472848872117082, 1.500692176842816750, 1.488957805516746058, - 1.477268661156133867, 1.465623682245745352, 1.454021818848793446, 1.442462031972012504, - 1.430943292938879674, 1.419464582769983219, 1.408024891569535697, 1.396623217917042137, - 1.385258568263121992, 1.373929956328490576, 1.362636402505086775, 1.351376933258335189, - 1.340150580529504643, 1.328956381137116560, 1.317793376176324749, 1.306660610415174117, - 1.295557131686601027, 1.284481990275012642, 1.273434238296241139, 1.262412929069615330, - 1.251417116480852521, 1.240445854334406572, 1.229498195693849105, 1.218573192208790124, - 1.207669893426761121, 1.196787346088403092, 1.185924593404202199, 1.175080674310911677, - 1.164254622705678921, 1.153445466655774743, 1.142652227581672841, 1.131873919411078511, - 1.121109547701330200, 1.110358108727411031, 1.099618588532597308, 1.088889961938546813, - 1.078171191511372307, 1.067461226479967662, 1.056759001602551429, 1.046063435977044209, - 1.035373431790528542, 1.024687873002617211, 1.014005623957096480, 1.003325527915696735, - 0.992646405507275897, 0.981967053085062602, 0.971286240983903260, 0.960602711668666509, - 0.949915177764075969, 0.939222319955262286, 0.928522784747210395, 0.917815182070044311, - 0.907098082715690257, 0.896370015589889935, 0.885629464761751528, 0.874874866291025066, - 0.864104604811004484, 0.853317009842373353, 0.842510351810368485, 0.831682837734273206, - 0.820832606554411814, 0.809957724057418282, 0.799056177355487174, 0.788125868869492430, - 0.777164609759129710, 0.766170112735434672, 0.755139984181982249, 0.744071715500508102, - 0.732962673584365398, 0.721810090308756203, 0.710611050909655040, 0.699362481103231959, - 0.688061132773747808, 0.676703568029522584, 0.665286141392677943, 0.653804979847664947, - 0.642255960424536365, 0.630634684933490286, 0.618936451394876075, 0.607156221620300030, - 0.595288584291502887, 0.583327712748769489, 0.571267316532588332, 0.559100585511540626, - 0.546820125163310577, 0.534417881237165604, 0.521885051592135052, 0.509211982443654398, - 0.496388045518671162, 0.483401491653461857, 0.470239275082169006, 0.456886840931420235, - 0.443327866073552401, 0.429543940225410703, 0.415514169600356364, 0.401214678896277765, - 0.386617977941119573, 0.371692145329917234, 0.356399760258393816, 0.340696481064849122, - 0.324529117016909452, 0.307832954674932158, 0.290527955491230394, 0.272513185478464703, - 0.253658363385912022, 0.233790483059674731, 0.212671510630966620, 0.189958689622431842, - 0.165127622564187282, 0.137304980940012589, 0.104838507565818778, 0.063852163815001570, - 0.000000000000000000]; -pub static ZIG_EXP_F: [f64; 257] = - [0.000167066692307963, 0.000454134353841497, 0.000967269282327174, 0.001536299780301573, - 0.002145967743718907, 0.002788798793574076, 0.003460264777836904, 0.004157295120833797, - 0.004877655983542396, 0.005619642207205489, 0.006381905937319183, 0.007163353183634991, - 0.007963077438017043, 0.008780314985808977, 0.009614413642502212, 0.010464810181029981, - 0.011331013597834600, 0.012212592426255378, 0.013109164931254991, 0.014020391403181943, - 0.014945968011691148, 0.015885621839973156, 0.016839106826039941, 0.017806200410911355, - 0.018786700744696024, 0.019780424338009740, 0.020787204072578114, 0.021806887504283581, - 0.022839335406385240, 0.023884420511558174, 0.024942026419731787, 0.026012046645134221, - 0.027094383780955803, 0.028188948763978646, 0.029295660224637411, 0.030414443910466622, - 0.031545232172893622, 0.032687963508959555, 0.033842582150874358, 0.035009037697397431, - 0.036187284781931443, 0.037377282772959382, 0.038578995503074871, 0.039792391023374139, - 0.041017441380414840, 0.042254122413316254, 0.043502413568888197, 0.044762297732943289, - 0.046033761076175184, 0.047316792913181561, 0.048611385573379504, 0.049917534282706379, - 0.051235237055126281, 0.052564494593071685, 0.053905310196046080, 0.055257689676697030, - 0.056621641283742870, 0.057997175631200659, 0.059384305633420280, 0.060783046445479660, - 0.062193415408541036, 0.063615431999807376, 0.065049117786753805, 0.066494496385339816, - 0.067951593421936643, 0.069420436498728783, 0.070901055162371843, 0.072393480875708752, - 0.073897746992364746, 0.075413888734058410, 0.076941943170480517, 0.078481949201606435, - 0.080033947542319905, 0.081597980709237419, 0.083174093009632397, 0.084762330532368146, - 0.086362741140756927, 0.087975374467270231, 0.089600281910032886, 0.091237516631040197, - 0.092887133556043569, 0.094549189376055873, 0.096223742550432825, 0.097910853311492213, - 0.099610583670637132, 0.101322997425953631, 0.103048160171257702, 0.104786139306570145, - 0.106537004050001632, 0.108300825451033755, 0.110077676405185357, 0.111867631670056283, - 0.113670767882744286, 0.115487163578633506, 0.117316899211555525, 0.119160057175327641, - 0.121016721826674792, 0.122886979509545108, 0.124770918580830933, 0.126668629437510671, - 0.128580204545228199, 0.130505738468330773, 0.132445327901387494, 0.134399071702213602, - 0.136367070926428829, 0.138349428863580176, 0.140346251074862399, 0.142357645432472146, - 0.144383722160634720, 0.146424593878344889, 0.148480375643866735, 0.150551185001039839, - 0.152637142027442801, 0.154738369384468027, 0.156854992369365148, 0.158987138969314129, - 0.161134939917591952, 0.163298528751901734, 0.165478041874935922, 0.167673618617250081, - 0.169885401302527550, 0.172113535315319977, 0.174358169171353411, 0.176619454590494829, - 0.178897546572478278, 0.181192603475496261, 0.183504787097767436, 0.185834262762197083, - 0.188181199404254262, 0.190545769663195363, 0.192928149976771296, 0.195328520679563189, - 0.197747066105098818, 0.200183974691911210, 0.202639439093708962, 0.205113656293837654, - 0.207606827724221982, 0.210119159388988230, 0.212650861992978224, 0.215202151075378628, - 0.217773247148700472, 0.220364375843359439, 0.222975768058120111, 0.225607660116683956, - 0.228260293930716618, 0.230933917169627356, 0.233628783437433291, 0.236345152457059560, - 0.239083290262449094, 0.241843469398877131, 0.244625969131892024, 0.247431075665327543, - 0.250259082368862240, 0.253110290015629402, 0.255985007030415324, 0.258883549749016173, - 0.261806242689362922, 0.264753418835062149, 0.267725419932044739, 0.270722596799059967, - 0.273745309652802915, 0.276793928448517301, 0.279868833236972869, 0.282970414538780746, - 0.286099073737076826, 0.289255223489677693, 0.292439288161892630, 0.295651704281261252, - 0.298892921015581847, 0.302163400675693528, 0.305463619244590256, 0.308794066934560185, - 0.312155248774179606, 0.315547685227128949, 0.318971912844957239, 0.322428484956089223, - 0.325917972393556354, 0.329440964264136438, 0.332998068761809096, 0.336589914028677717, - 0.340217149066780189, 0.343880444704502575, 0.347580494621637148, 0.351318016437483449, - 0.355093752866787626, 0.358908472948750001, 0.362762973354817997, 0.366658079781514379, - 0.370594648435146223, 0.374573567615902381, 0.378595759409581067, 0.382662181496010056, - 0.386773829084137932, 0.390931736984797384, 0.395136981833290435, 0.399390684475231350, - 0.403694012530530555, 0.408048183152032673, 0.412454465997161457, 0.416914186433003209, - 0.421428728997616908, 0.425999541143034677, 0.430628137288459167, 0.435316103215636907, - 0.440065100842354173, 0.444876873414548846, 0.449753251162755330, 0.454696157474615836, - 0.459707615642138023, 0.464789756250426511, 0.469944825283960310, 0.475175193037377708, - 0.480483363930454543, 0.485871987341885248, 0.491343869594032867, 0.496901987241549881, - 0.502549501841348056, 0.508289776410643213, 0.514126393814748894, 0.520063177368233931, - 0.526104213983620062, 0.532253880263043655, 0.538516872002862246, 0.544898237672440056, - 0.551403416540641733, 0.558038282262587892, 0.564809192912400615, 0.571723048664826150, - 0.578787358602845359, 0.586010318477268366, 0.593400901691733762, 0.600968966365232560, - 0.608725382079622346, 0.616682180915207878, 0.624852738703666200, 0.633251994214366398, - 0.641896716427266423, 0.650805833414571433, 0.660000841079000145, 0.669506316731925177, - 0.679350572264765806, 0.689566496117078431, 0.700192655082788606, 0.711274760805076456, - 0.722867659593572465, 0.735038092431424039, 0.747868621985195658, 0.761463388849896838, - 0.775956852040116218, 0.791527636972496285, 0.808421651523009044, 0.826993296643051101, - 0.847785500623990496, 0.871704332381204705, 0.900469929925747703, 0.938143680862176477, - 1.000000000000000000]; diff --git a/third_party/cargo/vendor/rand-0.5.6/src/lib.rs b/third_party/cargo/vendor/rand-0.5.6/src/lib.rs deleted file mode 100644 index a1eb469..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/lib.rs +++ /dev/null @@ -1,1238 +0,0 @@ -// Copyright 2013-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Utilities for random number generation -//! -//! Rand provides utilities to generate random numbers, to convert them to -//! useful types and distributions, and some randomness-related algorithms. -//! -//! # Basic usage -//! -//! To get you started quickly, the easiest and highest-level way to get -//! a random value is to use [`random()`]. -//! -//! ``` -//! let x: u8 = rand::random(); -//! println!("{}", x); -//! -//! let y = rand::random::(); -//! println!("{}", y); -//! -//! if rand::random() { // generates a boolean -//! println!("Heads!"); -//! } -//! ``` -//! -//! This supports generating most common types but is not very flexible, thus -//! you probably want to learn a bit more about the Rand library. -//! -//! -//! # The two-step process to get a random value -//! -//! Generating random values is typically a two-step process: -//! -//! - get some *random data* (an integer or bit/byte sequence) from a random -//! number generator (RNG); -//! - use some function to transform that *data* into the type of value you want -//! (this function is an implementation of some *distribution* describing the -//! kind of value produced). -//! -//! Rand represents the first step with the [`RngCore`] trait and the second -//! step via a combination of the [`Rng`] extension trait and the -//! [`distributions` module]. -//! In practice you probably won't use [`RngCore`] directly unless you are -//! implementing a random number generator (RNG). -//! -//! There are many kinds of RNGs, with different trade-offs. You can read more -//! about them in the [`rngs` module] and even more in the [`prng` module], -//! however, often you can just use [`thread_rng()`]. This function -//! automatically initializes an RNG in thread-local memory, then returns a -//! reference to it. It is fast, good quality, and secure (unpredictable). -//! -//! To turn the output of the RNG into something usable, you usually want to use -//! the methods from the [`Rng`] trait. Some of the most useful methods are: -//! -//! - [`gen`] generates a random value appropriate for the type (just like -//! [`random()`]). For integers this is normally the full representable range -//! (e.g. from `0u32` to `std::u32::MAX`), for floats this is between 0 and 1, -//! and some other types are supported, including arrays and tuples. See the -//! [`Standard`] distribution which provides the implementations. -//! - [`gen_range`] samples from a specific range of values; this is like -//! [`gen`] but with specific upper and lower bounds. -//! - [`sample`] samples directly from some distribution. -//! -//! [`random()`] is defined using just the above: `thread_rng().gen()`. -//! -//! ## Distributions -//! -//! What are distributions, you ask? Specifying only the type and range of -//! values (known as the *sample space*) is not enough; samples must also have -//! a *probability distribution*, describing the relative probability of -//! sampling each value in that space. -//! -//! In many cases a *uniform* distribution is used, meaning roughly that each -//! value is equally likely (or for "continuous" types like floats, that each -//! equal-sized sub-range has the same probability of containing a sample). -//! [`gen`] and [`gen_range`] both use statistically uniform distributions. -//! -//! The [`distributions` module] provides implementations -//! of some other distributions, including Normal, Log-Normal and Exponential. -//! -//! It is worth noting that the functionality already mentioned is implemented -//! with distributions: [`gen`] samples values using the [`Standard`] -//! distribution, while [`gen_range`] uses [`Uniform`]. -//! -//! ## Importing (prelude) -//! -//! The most convenient way to import items from Rand is to use the [prelude]. -//! This includes the most important parts of Rand, but only those unlikely to -//! cause name conflicts. -//! -//! Note that Rand 0.5 has significantly changed the module organization and -//! contents relative to previous versions. Where possible old names have been -//! kept (but are hidden in the documentation), however these will be removed -//! in the future. We therefore recommend migrating to use the prelude or the -//! new module organization in your imports. -//! -//! -//! ## Examples -//! -//! ``` -//! use rand::prelude::*; -//! -//! // thread_rng is often the most convenient source of randomness: -//! let mut rng = thread_rng(); -//! -//! if rng.gen() { // random bool -//! let x: f64 = rng.gen(); // random number in range [0, 1) -//! println!("x is: {}", x); -//! let ch = rng.gen::(); // using type annotation -//! println!("char is: {}", ch); -//! println!("Number from 0 to 9: {}", rng.gen_range(0, 10)); -//! } -//! ``` -//! -//! -//! # More functionality -//! -//! The [`Rng`] trait includes a few more methods not mentioned above: -//! -//! - [`Rng::sample_iter`] allows iterating over values from a chosen -//! distribution. -//! - [`Rng::gen_bool`] generates boolean "events" with a given probability. -//! - [`Rng::fill`] and [`Rng::try_fill`] are fast alternatives to fill a slice -//! of integers. -//! - [`Rng::shuffle`] randomly shuffles elements in a slice. -//! - [`Rng::choose`] picks one element at random from a slice. -//! -//! For more slice/sequence related functionality, look in the [`seq` module]. -//! -//! There is also [`distributions::WeightedChoice`], which can be used to pick -//! elements at random with some probability. But it does not work well at the -//! moment and is going through a redesign. -//! -//! -//! # Error handling -//! -//! Error handling in Rand is a compromise between simplicity and necessity. -//! Most RNGs and sampling functions will never produce errors, and making these -//! able to handle errors would add significant overhead (to code complexity -//! and ergonomics of usage at least, and potentially also performance, -//! depending on the approach). -//! However, external RNGs can fail, and being able to handle this is important. -//! -//! It has therefore been decided that *most* methods should not return a -//! `Result` type, with as exceptions [`Rng::try_fill`], -//! [`RngCore::try_fill_bytes`], and [`SeedableRng::from_rng`]. -//! -//! Note that it is the RNG that panics when it fails but is not used through a -//! method that can report errors. Currently Rand contains only three RNGs that -//! can return an error (and thus may panic), and documents this property: -//! [`OsRng`], [`EntropyRng`] and [`ReadRng`]. Other RNGs, like [`ThreadRng`] -//! and [`StdRng`], can be used with all methods without concern. -//! -//! One further problem is that if Rand is unable to get any external randomness -//! when initializing an RNG with [`EntropyRng`], it will panic in -//! [`FromEntropy::from_entropy`], and notably in [`thread_rng()`]. Except by -//! compromising security, this problem is as unsolvable as running out of -//! memory. -//! -//! -//! # Distinction between Rand and `rand_core` -//! -//! The [`rand_core`] crate provides the necessary traits and functionality for -//! implementing RNGs; this includes the [`RngCore`] and [`SeedableRng`] traits -//! and the [`Error`] type. -//! Crates implementing RNGs should depend on [`rand_core`]. -//! -//! Applications and libraries consuming random values are encouraged to use the -//! Rand crate, which re-exports the common parts of [`rand_core`]. -//! -//! -//! # More examples -//! -//! For some inspiration, see the examples: -//! -//! - [Monte Carlo estimation of π]( -//! https://github.com/rust-lang-nursery/rand/blob/master/examples/monte-carlo.rs) -//! - [Monty Hall Problem]( -//! https://github.com/rust-lang-nursery/rand/blob/master/examples/monty-hall.rs) -//! -//! -//! [`distributions` module]: distributions/index.html -//! [`distributions::WeightedChoice`]: distributions/struct.WeightedChoice.html -//! [`FromEntropy::from_entropy`]: trait.FromEntropy.html#tymethod.from_entropy -//! [`EntropyRng`]: rngs/struct.EntropyRng.html -//! [`Error`]: struct.Error.html -//! [`gen_range`]: trait.Rng.html#method.gen_range -//! [`gen`]: trait.Rng.html#method.gen -//! [`OsRng`]: rngs/struct.OsRng.html -//! [prelude]: prelude/index.html -//! [`rand_core`]: https://crates.io/crates/rand_core -//! [`random()`]: fn.random.html -//! [`ReadRng`]: rngs/adapter/struct.ReadRng.html -//! [`Rng::choose`]: trait.Rng.html#method.choose -//! [`Rng::fill`]: trait.Rng.html#method.fill -//! [`Rng::gen_bool`]: trait.Rng.html#method.gen_bool -//! [`Rng::gen`]: trait.Rng.html#method.gen -//! [`Rng::sample_iter`]: trait.Rng.html#method.sample_iter -//! [`Rng::shuffle`]: trait.Rng.html#method.shuffle -//! [`RngCore`]: trait.RngCore.html -//! [`RngCore::try_fill_bytes`]: trait.RngCore.html#method.try_fill_bytes -//! [`rngs` module]: rngs/index.html -//! [`prng` module]: prng/index.html -//! [`Rng`]: trait.Rng.html -//! [`Rng::try_fill`]: trait.Rng.html#method.try_fill -//! [`sample`]: trait.Rng.html#method.sample -//! [`SeedableRng`]: trait.SeedableRng.html -//! [`SeedableRng::from_rng`]: trait.SeedableRng.html#method.from_rng -//! [`seq` module]: seq/index.html -//! [`SmallRng`]: rngs/struct.SmallRng.html -//! [`StdRng`]: rngs/struct.StdRng.html -//! [`thread_rng()`]: fn.thread_rng.html -//! [`ThreadRng`]: rngs/struct.ThreadRng.html -//! [`Standard`]: distributions/struct.Standard.html -//! [`Uniform`]: distributions/struct.Uniform.html - - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/rand/0.5.6")] - -#![deny(missing_docs)] -#![deny(missing_debug_implementations)] -#![doc(test(attr(allow(unused_variables), deny(warnings))))] - -#![cfg_attr(not(feature="std"), no_std)] -#![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))] -#![cfg_attr(all(feature="i128_support", feature="nightly"), allow(stable_features))] // stable since 2018-03-27 -#![cfg_attr(all(feature="i128_support", feature="nightly"), feature(i128_type, i128))] -#![cfg_attr(feature = "stdweb", recursion_limit="128")] - -#[cfg(feature="std")] extern crate std as core; -#[cfg(all(feature = "alloc", not(feature="std")))] extern crate alloc; - -#[cfg(test)] #[cfg(feature="serde1")] extern crate bincode; -#[cfg(feature="serde1")] extern crate serde; -#[cfg(feature="serde1")] #[macro_use] extern crate serde_derive; - -#[cfg(all(target_arch="wasm32", not(target_os="emscripten"), feature="stdweb"))] -#[macro_use] -extern crate stdweb; - -extern crate rand_core; - -#[cfg(feature = "log")] #[macro_use] extern crate log; -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! trace { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! debug { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! info { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! warn { ($($x:tt)*) => () } -#[allow(unused)] -#[cfg(not(feature = "log"))] macro_rules! error { ($($x:tt)*) => () } - - -// Re-exports from rand_core -pub use rand_core::{RngCore, CryptoRng, SeedableRng}; -pub use rand_core::{ErrorKind, Error}; - -// Public exports -#[cfg(feature="std")] pub use rngs::thread::thread_rng; - -// Public modules -pub mod distributions; -pub mod prelude; -pub mod prng; -pub mod rngs; -#[cfg(feature = "alloc")] pub mod seq; - -//////////////////////////////////////////////////////////////////////////////// -// Compatibility re-exports. Documentation is hidden; will be removed eventually. - -#[cfg(feature="std")] #[doc(hidden)] pub use rngs::adapter::read; -#[doc(hidden)] pub use rngs::adapter::ReseedingRng; - -#[allow(deprecated)] -#[cfg(feature="std")] #[doc(hidden)] pub use rngs::EntropyRng; - -#[allow(deprecated)] -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -#[doc(hidden)] -pub use rngs::OsRng; - -#[doc(hidden)] pub use prng::{ChaChaRng, IsaacRng, Isaac64Rng, XorShiftRng}; -#[doc(hidden)] pub use rngs::StdRng; - - -#[allow(deprecated)] -#[doc(hidden)] -pub mod jitter { - pub use rngs::{JitterRng, TimerError}; -} -#[allow(deprecated)] -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -#[doc(hidden)] -pub mod os { - pub use rngs::OsRng; -} -#[allow(deprecated)] -#[doc(hidden)] -pub mod chacha { - //! The ChaCha random number generator. - pub use prng::ChaChaRng; -} -#[doc(hidden)] -pub mod isaac { - //! The ISAAC random number generator. - pub use prng::{IsaacRng, Isaac64Rng}; -} - -#[cfg(feature="std")] #[doc(hidden)] pub use rngs::ThreadRng; - -//////////////////////////////////////////////////////////////////////////////// - - -use core::{marker, mem, slice}; -use distributions::{Distribution, Standard}; -use distributions::uniform::{SampleUniform, UniformSampler}; - - -/// A type that can be randomly generated using an [`Rng`]. -/// -/// This is merely an adapter around the [`Standard`] distribution for -/// convenience and backwards-compatibility. -/// -/// [`Rng`]: trait.Rng.html -/// [`Standard`]: distributions/struct.Standard.html -#[deprecated(since="0.5.0", note="replaced by distributions::Standard")] -pub trait Rand : Sized { - /// Generates a random instance of this type using the specified source of - /// randomness. - fn rand(rng: &mut R) -> Self; -} - -/// An automatically-implemented extension trait on [`RngCore`] providing high-level -/// generic methods for sampling values and other convenience methods. -/// -/// This is the primary trait to use when generating random values. -/// -/// # Generic usage -/// -/// The basic pattern is `fn foo(rng: &mut R)`. Some -/// things are worth noting here: -/// -/// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no -/// difference whether we use `R: Rng` or `R: RngCore`. -/// - The `+ ?Sized` un-bounding allows functions to be called directly on -/// type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without -/// this it would be necessary to write `foo(&mut r)`. -/// -/// An alternative pattern is possible: `fn foo(rng: R)`. This has some -/// trade-offs. It allows the argument to be consumed directly without a `&mut` -/// (which is how `from_rng(thread_rng())` works); also it still works directly -/// on references (including type-erased references). Unfortunately within the -/// function `foo` it is not known whether `rng` is a reference type or not, -/// hence many uses of `rng` require an extra reference, either explicitly -/// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the -/// optimiser can remove redundant references later. -/// -/// Example: -/// -/// ``` -/// # use rand::thread_rng; -/// use rand::Rng; -/// -/// fn foo(rng: &mut R) -> f32 { -/// rng.gen() -/// } -/// -/// # let v = foo(&mut thread_rng()); -/// ``` -/// -/// [`RngCore`]: trait.RngCore.html -pub trait Rng: RngCore { - /// Return a random value supporting the [`Standard`] distribution. - /// - /// [`Standard`]: distributions/struct.Standard.html - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let x: u32 = rng.gen(); - /// println!("{}", x); - /// println!("{:?}", rng.gen::<(f64, bool)>()); - /// ``` - #[inline] - fn gen(&mut self) -> T where Standard: Distribution { - Standard.sample(self) - } - - /// Generate a random value in the range [`low`, `high`), i.e. inclusive of - /// `low` and exclusive of `high`. - /// - /// This function is optimised for the case that only a single sample is - /// made from the given range. See also the [`Uniform`] distribution - /// type which may be faster if sampling from the same range repeatedly. - /// - /// # Panics - /// - /// Panics if `low >= high`. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let n: u32 = rng.gen_range(0, 10); - /// println!("{}", n); - /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64); - /// println!("{}", m); - /// ``` - /// - /// [`Uniform`]: distributions/uniform/struct.Uniform.html - fn gen_range(&mut self, low: T, high: T) -> T { - T::Sampler::sample_single(low, high, self) - } - - /// Sample a new value, using the given distribution. - /// - /// ### Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::Uniform; - /// - /// let mut rng = thread_rng(); - /// let x = rng.sample(Uniform::new(10u32, 15)); - /// // Type annotation requires two types, the type and distribution; the - /// // distribution can be inferred. - /// let y = rng.sample::(Uniform::new(10, 15)); - /// ``` - fn sample>(&mut self, distr: D) -> T { - distr.sample(self) - } - - /// Create an iterator that generates values using the given distribution. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// use rand::distributions::{Alphanumeric, Uniform, Standard}; - /// - /// let mut rng = thread_rng(); - /// - /// // Vec of 16 x f32: - /// let v: Vec = thread_rng().sample_iter(&Standard).take(16).collect(); - /// - /// // String: - /// let s: String = rng.sample_iter(&Alphanumeric).take(7).collect(); - /// - /// // Combined values - /// println!("{:?}", thread_rng().sample_iter(&Standard).take(5) - /// .collect::>()); - /// - /// // Dice-rolling: - /// let die_range = Uniform::new_inclusive(1, 6); - /// let mut roll_die = rng.sample_iter(&die_range); - /// while roll_die.next().unwrap() != 6 { - /// println!("Not a 6; rolling again!"); - /// } - /// ``` - fn sample_iter<'a, T, D: Distribution>(&'a mut self, distr: &'a D) - -> distributions::DistIter<'a, D, Self, T> where Self: Sized - { - distr.sample_iter(self) - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This uses [`fill_bytes`] internally which may handle some RNG errors - /// implicitly (e.g. waiting if the OS generator is not ready), but panics - /// on other errors. See also [`try_fill`] which returns errors. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut arr = [0i8; 20]; - /// thread_rng().fill(&mut arr[..]); - /// ``` - /// - /// [`fill_bytes`]: trait.RngCore.html#method.fill_bytes - /// [`try_fill`]: trait.Rng.html#method.try_fill - /// [`AsByteSliceMut`]: trait.AsByteSliceMut.html - fn fill(&mut self, dest: &mut T) { - self.fill_bytes(dest.as_byte_slice_mut()); - dest.to_le(); - } - - /// Fill `dest` entirely with random bytes (uniform value distribution), - /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices - /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.). - /// - /// On big-endian platforms this performs byte-swapping to ensure - /// portability of results from reproducible generators. - /// - /// This uses [`try_fill_bytes`] internally and forwards all RNG errors. In - /// some cases errors may be resolvable; see [`ErrorKind`] and - /// documentation for the RNG in use. If you do not plan to handle these - /// errors you may prefer to use [`fill`]. - /// - /// # Example - /// - /// ``` - /// # use rand::Error; - /// use rand::{thread_rng, Rng}; - /// - /// # fn try_inner() -> Result<(), Error> { - /// let mut arr = [0u64; 4]; - /// thread_rng().try_fill(&mut arr[..])?; - /// # Ok(()) - /// # } - /// - /// # try_inner().unwrap() - /// ``` - /// - /// [`ErrorKind`]: enum.ErrorKind.html - /// [`try_fill_bytes`]: trait.RngCore.html#method.try_fill_bytes - /// [`fill`]: trait.Rng.html#method.fill - /// [`AsByteSliceMut`]: trait.AsByteSliceMut.html - fn try_fill(&mut self, dest: &mut T) -> Result<(), Error> { - self.try_fill_bytes(dest.as_byte_slice_mut())?; - dest.to_le(); - Ok(()) - } - - /// Return a bool with a probability `p` of being true. - /// - /// This is a wrapper around [`distributions::Bernoulli`]. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// println!("{}", rng.gen_bool(1.0 / 3.0)); - /// ``` - /// - /// # Panics - /// - /// If `p` < 0 or `p` > 1. - /// - /// [`distributions::Bernoulli`]: distributions/bernoulli/struct.Bernoulli.html - #[inline] - fn gen_bool(&mut self, p: f64) -> bool { - let d = distributions::Bernoulli::new(p); - self.sample(d) - } - - /// Return a random element from `values`. - /// - /// Return `None` if `values` is empty. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let choices = [1, 2, 4, 8, 16, 32]; - /// let mut rng = thread_rng(); - /// println!("{:?}", rng.choose(&choices)); - /// assert_eq!(rng.choose(&choices[..0]), None); - /// ``` - fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { - if values.is_empty() { - None - } else { - Some(&values[self.gen_range(0, values.len())]) - } - } - - /// Return a mutable pointer to a random element from `values`. - /// - /// Return `None` if `values` is empty. - fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> { - if values.is_empty() { - None - } else { - let len = values.len(); - Some(&mut values[self.gen_range(0, len)]) - } - } - - /// Shuffle a mutable slice in place. - /// - /// This applies Durstenfeld's algorithm for the [Fisher–Yates shuffle]( - /// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm) - /// which produces an unbiased permutation. - /// - /// # Example - /// - /// ``` - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let mut y = [1, 2, 3]; - /// rng.shuffle(&mut y); - /// println!("{:?}", y); - /// rng.shuffle(&mut y); - /// println!("{:?}", y); - /// ``` - fn shuffle(&mut self, values: &mut [T]) { - let mut i = values.len(); - while i >= 2 { - // invariant: elements with index >= i have been locked in place. - i -= 1; - // lock element i in place. - values.swap(i, self.gen_range(0, i + 1)); - } - } - - /// Return an iterator that will yield an infinite number of randomly - /// generated items. - /// - /// # Example - /// - /// ``` - /// # #![allow(deprecated)] - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// let x = rng.gen_iter::().take(10).collect::>(); - /// println!("{:?}", x); - /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5) - /// .collect::>()); - /// ``` - #[allow(deprecated)] - #[deprecated(since="0.5.0", note="use Rng::sample_iter(&Standard) instead")] - fn gen_iter(&mut self) -> Generator where Standard: Distribution { - Generator { rng: self, _marker: marker::PhantomData } - } - - /// Return a bool with a 1 in n chance of true - /// - /// # Example - /// - /// ``` - /// # #![allow(deprecated)] - /// use rand::{thread_rng, Rng}; - /// - /// let mut rng = thread_rng(); - /// assert_eq!(rng.gen_weighted_bool(0), true); - /// assert_eq!(rng.gen_weighted_bool(1), true); - /// // Just like `rng.gen::()` a 50-50% chance, but using a slower - /// // method with different results. - /// println!("{}", rng.gen_weighted_bool(2)); - /// // First meaningful use of `gen_weighted_bool`. - /// println!("{}", rng.gen_weighted_bool(3)); - /// ``` - #[deprecated(since="0.5.0", note="use gen_bool instead")] - fn gen_weighted_bool(&mut self, n: u32) -> bool { - // Short-circuit after `n <= 1` to avoid panic in `gen_range` - n <= 1 || self.gen_range(0, n) == 0 - } - - /// Return an iterator of random characters from the set A-Z,a-z,0-9. - /// - /// # Example - /// - /// ``` - /// # #![allow(deprecated)] - /// use rand::{thread_rng, Rng}; - /// - /// let s: String = thread_rng().gen_ascii_chars().take(10).collect(); - /// println!("{}", s); - /// ``` - #[allow(deprecated)] - #[deprecated(since="0.5.0", note="use sample_iter(&Alphanumeric) instead")] - fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self> { - AsciiGenerator { rng: self } - } -} - -impl Rng for R {} - -/// Trait for casting types to byte slices -/// -/// This is used by the [`fill`] and [`try_fill`] methods. -/// -/// [`fill`]: trait.Rng.html#method.fill -/// [`try_fill`]: trait.Rng.html#method.try_fill -pub trait AsByteSliceMut { - /// Return a mutable reference to self as a byte slice - fn as_byte_slice_mut(&mut self) -> &mut [u8]; - - /// Call `to_le` on each element (i.e. byte-swap on Big Endian platforms). - fn to_le(&mut self); -} - -impl AsByteSliceMut for [u8] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self - } - - fn to_le(&mut self) {} -} - -macro_rules! impl_as_byte_slice { - ($t:ty) => { - impl AsByteSliceMut for [$t] { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - if self.len() == 0 { - unsafe { - // must not use null pointer - slice::from_raw_parts_mut(0x1 as *mut u8, 0) - } - } else { - unsafe { - slice::from_raw_parts_mut(&mut self[0] - as *mut $t - as *mut u8, - self.len() * mem::size_of::<$t>() - ) - } - } - } - - fn to_le(&mut self) { - for x in self { - *x = x.to_le(); - } - } - } - } -} - -impl_as_byte_slice!(u16); -impl_as_byte_slice!(u32); -impl_as_byte_slice!(u64); -#[cfg(feature="i128_support")] impl_as_byte_slice!(u128); -impl_as_byte_slice!(usize); -impl_as_byte_slice!(i8); -impl_as_byte_slice!(i16); -impl_as_byte_slice!(i32); -impl_as_byte_slice!(i64); -#[cfg(feature="i128_support")] impl_as_byte_slice!(i128); -impl_as_byte_slice!(isize); - -macro_rules! impl_as_byte_slice_arrays { - ($n:expr,) => {}; - ($n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!($n - 1, $($NN,)*); - - impl AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self[..].as_byte_slice_mut() - } - - fn to_le(&mut self) { - self[..].to_le() - } - } - }; - (!div $n:expr,) => {}; - (!div $n:expr, $N:ident, $($NN:ident,)*) => { - impl_as_byte_slice_arrays!(!div $n / 2, $($NN,)*); - - impl AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut { - fn as_byte_slice_mut(&mut self) -> &mut [u8] { - self[..].as_byte_slice_mut() - } - - fn to_le(&mut self) { - self[..].to_le() - } - } - }; -} -impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,); -impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,); - -/// Iterator which will generate a stream of random items. -/// -/// This iterator is created via the [`gen_iter`] method on [`Rng`]. -/// -/// [`gen_iter`]: trait.Rng.html#method.gen_iter -/// [`Rng`]: trait.Rng.html -#[derive(Debug)] -#[allow(deprecated)] -#[deprecated(since="0.5.0", note="use Rng::sample_iter instead")] -pub struct Generator { - rng: R, - _marker: marker::PhantomData T>, -} - -#[allow(deprecated)] -impl Iterator for Generator where Standard: Distribution { - type Item = T; - - fn next(&mut self) -> Option { - Some(self.rng.gen()) - } -} - -/// Iterator which will continuously generate random ascii characters. -/// -/// This iterator is created via the [`gen_ascii_chars`] method on [`Rng`]. -/// -/// [`gen_ascii_chars`]: trait.Rng.html#method.gen_ascii_chars -/// [`Rng`]: trait.Rng.html -#[derive(Debug)] -#[allow(deprecated)] -#[deprecated(since="0.5.0", note="use distributions::Alphanumeric instead")] -pub struct AsciiGenerator { - rng: R, -} - -#[allow(deprecated)] -impl Iterator for AsciiGenerator { - type Item = char; - - fn next(&mut self) -> Option { - const GEN_ASCII_STR_CHARSET: &[u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789"; - Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char) - } -} - - -/// A convenience extension to [`SeedableRng`] allowing construction from fresh -/// entropy. This trait is automatically implemented for any PRNG implementing -/// [`SeedableRng`] and is not intended to be implemented by users. -/// -/// This is equivalent to using `SeedableRng::from_rng(EntropyRng::new())` then -/// unwrapping the result. -/// -/// Since this is convenient and secure, it is the recommended way to create -/// PRNGs, though two alternatives may be considered: -/// -/// * Deterministic creation using [`SeedableRng::from_seed`] with a fixed seed -/// * Seeding from `thread_rng`: `SeedableRng::from_rng(thread_rng())?`; -/// this will usually be faster and should also be secure, but requires -/// trusting one extra component. -/// -/// ## Example -/// -/// ``` -/// use rand::{Rng, FromEntropy}; -/// use rand::rngs::StdRng; -/// -/// let mut rng = StdRng::from_entropy(); -/// println!("Random die roll: {}", rng.gen_range(1, 7)); -/// ``` -/// -/// [`EntropyRng`]: rngs/struct.EntropyRng.html -/// [`SeedableRng`]: trait.SeedableRng.html -/// [`SeedableRng::from_seed`]: trait.SeedableRng.html#tymethod.from_seed -#[cfg(feature="std")] -pub trait FromEntropy: SeedableRng { - /// Creates a new instance, automatically seeded with fresh entropy. - /// - /// Normally this will use `OsRng`, but if that fails `JitterRng` will be - /// used instead. Both should be suitable for cryptography. It is possible - /// that both entropy sources will fail though unlikely; failures would - /// almost certainly be platform limitations or build issues, i.e. most - /// applications targetting PC/mobile platforms should not need to worry - /// about this failing. - /// - /// # Panics - /// - /// If all entropy sources fail this will panic. If you need to handle - /// errors, use the following code, equivalent aside from error handling: - /// - /// ``` - /// # use rand::Error; - /// use rand::prelude::*; - /// use rand::rngs::EntropyRng; - /// - /// # fn try_inner() -> Result<(), Error> { - /// // This uses StdRng, but is valid for any R: SeedableRng - /// let mut rng = StdRng::from_rng(EntropyRng::new())?; - /// - /// println!("random number: {}", rng.gen_range(1, 10)); - /// # Ok(()) - /// # } - /// - /// # try_inner().unwrap() - /// ``` - fn from_entropy() -> Self; -} - -#[cfg(feature="std")] -impl FromEntropy for R { - fn from_entropy() -> R { - R::from_rng(EntropyRng::new()).unwrap_or_else(|err| - panic!("FromEntropy::from_entropy() failed: {}", err)) - } -} - - -/// DEPRECATED: use [`SmallRng`] instead. -/// -/// Create a weak random number generator with a default algorithm and seed. -/// -/// It returns the fastest `Rng` algorithm currently available in Rust without -/// consideration for cryptography or security. If you require a specifically -/// seeded `Rng` for consistency over time you should pick one algorithm and -/// create the `Rng` yourself. -/// -/// This will seed the generator with randomness from `thread_rng`. -/// -/// [`SmallRng`]: rngs/struct.SmallRng.html -#[deprecated(since="0.5.0", note="removed in favor of SmallRng")] -#[cfg(feature="std")] -pub fn weak_rng() -> XorShiftRng { - XorShiftRng::from_rng(thread_rng()).unwrap_or_else(|err| - panic!("weak_rng failed: {:?}", err)) -} - -/// Generates a random value using the thread-local random number generator. -/// -/// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for -/// documentation of the entropy source and [`Standard`] for documentation of -/// distributions and type-specific generation. -/// -/// # Examples -/// -/// ``` -/// let x = rand::random::(); -/// println!("{}", x); -/// -/// let y = rand::random::(); -/// println!("{}", y); -/// -/// if rand::random() { // generates a boolean -/// println!("Better lucky than good!"); -/// } -/// ``` -/// -/// If you're calling `random()` in a loop, caching the generator as in the -/// following example can increase performance. -/// -/// ``` -/// # #![allow(deprecated)] -/// use rand::Rng; -/// -/// let mut v = vec![1, 2, 3]; -/// -/// for x in v.iter_mut() { -/// *x = rand::random() -/// } -/// -/// // can be made faster by caching thread_rng -/// -/// let mut rng = rand::thread_rng(); -/// -/// for x in v.iter_mut() { -/// *x = rng.gen(); -/// } -/// ``` -/// -/// [`thread_rng`]: fn.thread_rng.html -/// [`Standard`]: distributions/struct.Standard.html -#[cfg(feature="std")] -#[inline] -pub fn random() -> T where Standard: Distribution { - thread_rng().gen() -} - -/// DEPRECATED: use `seq::sample_iter` instead. -/// -/// Randomly sample up to `amount` elements from a finite iterator. -/// The order of elements in the sample is not random. -/// -/// # Example -/// -/// ``` -/// # #![allow(deprecated)] -/// use rand::{thread_rng, sample}; -/// -/// let mut rng = thread_rng(); -/// let sample = sample(&mut rng, 1..100, 5); -/// println!("{:?}", sample); -/// ``` -#[cfg(feature="std")] -#[inline] -#[deprecated(since="0.4.0", note="renamed to seq::sample_iter")] -pub fn sample(rng: &mut R, iterable: I, amount: usize) -> Vec - where I: IntoIterator, - R: Rng, -{ - // the legacy sample didn't care whether amount was met - seq::sample_iter(rng, iterable, amount) - .unwrap_or_else(|e| e) -} - -#[cfg(test)] -mod test { - use rngs::mock::StepRng; - use super::*; - #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::boxed::Box; - - pub struct TestRng { inner: R } - - impl RngCore for TestRng { - fn next_u32(&mut self) -> u32 { - self.inner.next_u32() - } - fn next_u64(&mut self) -> u64 { - self.inner.next_u64() - } - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.inner.fill_bytes(dest) - } - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.inner.try_fill_bytes(dest) - } - } - - pub fn rng(seed: u64) -> TestRng { - TestRng { inner: StdRng::seed_from_u64(seed) } - } - - #[test] - fn test_fill_bytes_default() { - let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0); - - // check every remainder mod 8, both in small and big vectors. - let lengths = [0, 1, 2, 3, 4, 5, 6, 7, - 80, 81, 82, 83, 84, 85, 86, 87]; - for &n in lengths.iter() { - let mut buffer = [0u8; 87]; - let v = &mut buffer[0..n]; - r.fill_bytes(v); - - // use this to get nicer error messages. - for (i, &byte) in v.iter().enumerate() { - if byte == 0 { - panic!("byte {} of {} is zero", i, n) - } - } - } - } - - #[test] - fn test_fill() { - let x = 9041086907909331047; // a random u64 - let mut rng = StepRng::new(x, 0); - - // Convert to byte sequence and back to u64; byte-swap twice if BE. - let mut array = [0u64; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x, x]); - assert_eq!(rng.next_u64(), x); - - // Convert to bytes then u32 in LE order - let mut array = [0u32; 2]; - rng.fill(&mut array[..]); - assert_eq!(array, [x as u32, (x >> 32) as u32]); - assert_eq!(rng.next_u32(), x as u32); - } - - #[test] - fn test_fill_empty() { - let mut array = [0u32; 0]; - let mut rng = StepRng::new(0, 1); - rng.fill(&mut array); - rng.fill(&mut array[..]); - } - - #[test] - fn test_gen_range() { - let mut r = rng(101); - for _ in 0..1000 { - let a = r.gen_range(-3, 42); - assert!(a >= -3 && a < 42); - assert_eq!(r.gen_range(0, 1), 0); - assert_eq!(r.gen_range(-12, -11), -12); - } - - for _ in 0..1000 { - let a = r.gen_range(10, 42); - assert!(a >= 10 && a < 42); - assert_eq!(r.gen_range(0, 1), 0); - assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000); - } - - } - - #[test] - #[should_panic] - fn test_gen_range_panic_int() { - let mut r = rng(102); - r.gen_range(5, -2); - } - - #[test] - #[should_panic] - fn test_gen_range_panic_usize() { - let mut r = rng(103); - r.gen_range(5, 2); - } - - #[test] - #[allow(deprecated)] - fn test_gen_weighted_bool() { - let mut r = rng(104); - assert_eq!(r.gen_weighted_bool(0), true); - assert_eq!(r.gen_weighted_bool(1), true); - } - - #[test] - fn test_gen_bool() { - let mut r = rng(105); - for _ in 0..5 { - assert_eq!(r.gen_bool(0.0), false); - assert_eq!(r.gen_bool(1.0), true); - } - } - - #[test] - fn test_choose() { - let mut r = rng(107); - assert_eq!(r.choose(&[1, 1, 1]).map(|&x|x), Some(1)); - - let v: &[isize] = &[]; - assert_eq!(r.choose(v), None); - } - - #[test] - fn test_shuffle() { - let mut r = rng(108); - let empty: &mut [isize] = &mut []; - r.shuffle(empty); - let mut one = [1]; - r.shuffle(&mut one); - let b: &[_] = &[1]; - assert_eq!(one, b); - - let mut two = [1, 2]; - r.shuffle(&mut two); - assert!(two == [1, 2] || two == [2, 1]); - - let mut x = [1, 1, 1]; - r.shuffle(&mut x); - let b: &[_] = &[1, 1, 1]; - assert_eq!(x, b); - } - - #[test] - fn test_rng_trait_object() { - use distributions::{Distribution, Standard}; - let mut rng = rng(109); - let mut r = &mut rng as &mut RngCore; - r.next_u32(); - r.gen::(); - let mut v = [1, 1, 1]; - r.shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="alloc")] - fn test_rng_boxed_trait() { - use distributions::{Distribution, Standard}; - let rng = rng(110); - let mut r = Box::new(rng) as Box; - r.next_u32(); - r.gen::(); - let mut v = [1, 1, 1]; - r.shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!(r.gen_range(0, 1), 0); - let _c: u8 = Standard.sample(&mut r); - } - - #[test] - #[cfg(feature="std")] - fn test_random() { - // not sure how to test this aside from just getting some values - let _n : usize = random(); - let _f : f32 = random(); - let _o : Option> = random(); - let _many : ((), - (usize, - isize, - Option<(u32, (bool,))>), - (u8, i8, u16, i16, u32, i32, u64, i64), - (f32, (f64, (f64,)))) = random(); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prelude.rs b/third_party/cargo/vendor/rand-0.5.6/src/prelude.rs deleted file mode 100644 index 358c237..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prelude.rs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Convenience re-export of common members -//! -//! Like the standard library's prelude, this module simplifies importing of -//! common items. Unlike the standard prelude, the contents of this module must -//! be imported manually: -//! -//! ``` -//! use rand::prelude::*; -//! # let _ = StdRng::from_entropy(); -//! # let mut r = SmallRng::from_rng(thread_rng()).unwrap(); -//! # let _: f32 = r.gen(); -//! ``` - -#[doc(no_inline)] pub use distributions::Distribution; -#[doc(no_inline)] pub use rngs::{SmallRng, StdRng}; -#[doc(no_inline)] #[cfg(feature="std")] pub use rngs::ThreadRng; -#[doc(no_inline)] pub use {Rng, RngCore, CryptoRng, SeedableRng}; -#[doc(no_inline)] #[cfg(feature="std")] pub use {FromEntropy, random, thread_rng}; diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/chacha.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/chacha.rs deleted file mode 100644 index 2817f8f..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/chacha.rs +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://www.rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ChaCha random number generator. - -use core::fmt; -use rand_core::{CryptoRng, RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng}; - -const SEED_WORDS: usize = 8; // 8 words for the 256-bit key -const STATE_WORDS: usize = 16; - -/// A cryptographically secure random number generator that uses the ChaCha -/// algorithm. -/// -/// ChaCha is a stream cipher designed by Daniel J. Bernstein [^1], that we use -/// as an RNG. It is an improved variant of the Salsa20 cipher family, which was -/// selected as one of the "stream ciphers suitable for widespread adoption" by -/// eSTREAM [^2]. -/// -/// ChaCha uses add-rotate-xor (ARX) operations as its basis. These are safe -/// against timing attacks, although that is mostly a concern for ciphers and -/// not for RNGs. Also it is very suitable for SIMD implementation. -/// Here we do not provide a SIMD implementation yet, except for what is -/// provided by auto-vectorisation. -/// -/// With the ChaCha algorithm it is possible to choose the number of rounds the -/// core algorithm should run. The number of rounds is a tradeoff between -/// performance and security, where 8 rounds is the minimum potentially -/// secure configuration, and 20 rounds is widely used as a conservative choice. -/// We use 20 rounds in this implementation, but hope to allow type-level -/// configuration in the future. -/// -/// We use a 64-bit counter and 64-bit stream identifier as in Benstein's -/// implementation [^1] except that we use a stream identifier in place of a -/// nonce. A 64-bit counter over 64-byte (16 word) blocks allows 1 ZiB of output -/// before cycling, and the stream identifier allows 264 unique -/// streams of output per seed. Both counter and stream are initialized to zero -/// but may be set via [`set_word_pos`] and [`set_stream`]. -/// -/// The word layout is: -/// -/// ```text -/// constant constant constant constant -/// seed seed seed seed -/// seed seed seed seed -/// counter counter nonce nonce -/// ``` -/// -/// This implementation uses an output buffer of sixteen `u32` words, and uses -/// [`BlockRng`] to implement the [`RngCore`] methods. -/// -/// [^1]: D. J. Bernstein, [*ChaCha, a variant of Salsa20*]( -/// https://cr.yp.to/chacha.html) -/// -/// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( -/// http://www.ecrypt.eu.org/stream/) -/// -/// [`set_word_pos`]: #method.set_word_pos -/// [`set_stream`]: #method.set_stream -/// [`BlockRng`]: ../../../rand_core/block/struct.BlockRng.html -/// [`RngCore`]: ../../trait.RngCore.html -#[derive(Clone, Debug)] -pub struct ChaChaRng(BlockRng); - -impl RngCore for ChaChaRng { - #[inline] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - #[inline] - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for ChaChaRng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - ChaChaRng(BlockRng::::from_seed(seed)) - } - - fn from_rng(rng: R) -> Result { - BlockRng::::from_rng(rng).map(ChaChaRng) - } -} - -impl CryptoRng for ChaChaRng {} - -impl ChaChaRng { - /// Create an ChaCha random number generator using the default - /// fixed key of 8 zero words. - /// - /// # Examples - /// - /// ``` - /// # #![allow(deprecated)] - /// use rand::{RngCore, ChaChaRng}; - /// - /// let mut ra = ChaChaRng::new_unseeded(); - /// println!("{:?}", ra.next_u32()); - /// println!("{:?}", ra.next_u32()); - /// ``` - /// - /// Since this equivalent to a RNG with a fixed seed, repeated executions - /// of an unseeded RNG will produce the same result. This code sample will - /// consistently produce: - /// - /// - 2917185654 - /// - 2419978656 - #[deprecated(since="0.5.0", note="use the FromEntropy or SeedableRng trait")] - pub fn new_unseeded() -> ChaChaRng { - ChaChaRng::from_seed([0; SEED_WORDS*4]) - } - - /// Get the offset from the start of the stream, in 32-bit words. - /// - /// Since the generated blocks are 16 words (24) long and the - /// counter is 64-bits, the offset is a 68-bit number. Sub-word offsets are - /// not supported, hence the result can simply be multiplied by 4 to get a - /// byte-offset. - /// - /// Note: this function is currently only available when the `i128_support` - /// feature is enabled. In the future this will be enabled by default. - #[cfg(feature = "i128_support")] - pub fn get_word_pos(&self) -> u128 { - let mut c = (self.0.core.state[13] as u64) << 32 - | (self.0.core.state[12] as u64); - let mut index = self.0.index(); - // c is the end of the last block generated, unless index is at end - if index >= STATE_WORDS { - index = 0; - } else { - c = c.wrapping_sub(1); - } - ((c as u128) << 4) | (index as u128) - } - - /// Set the offset from the start of the stream, in 32-bit words. - /// - /// As with `get_word_pos`, we use a 68-bit number. Since the generator - /// simply cycles at the end of its period (1 ZiB), we ignore the upper - /// 60 bits. - /// - /// Note: this function is currently only available when the `i128_support` - /// feature is enabled. In the future this will be enabled by default. - #[cfg(feature = "i128_support")] - pub fn set_word_pos(&mut self, word_offset: u128) { - let index = (word_offset as usize) & 0xF; - let counter = (word_offset >> 4) as u64; - self.0.core.state[12] = counter as u32; - self.0.core.state[13] = (counter >> 32) as u32; - if index != 0 { - self.0.generate_and_set(index); // also increments counter - } else { - self.0.reset(); - } - } - - /// Set the stream number. - /// - /// This is initialized to zero; 264 unique streams of output - /// are available per seed/key. - /// - /// Note that in order to reproduce ChaCha output with a specific 64-bit - /// nonce, one can convert that nonce to a `u64` in little-endian fashion - /// and pass to this function. In theory a 96-bit nonce can be used by - /// passing the last 64-bits to this function and using the first 32-bits as - /// the most significant half of the 64-bit counter (which may be set - /// indirectly via `set_word_pos`), but this is not directly supported. - pub fn set_stream(&mut self, stream: u64) { - let index = self.0.index(); - self.0.core.state[14] = stream as u32; - self.0.core.state[15] = (stream >> 32) as u32; - if index < STATE_WORDS { - // we need to regenerate a partial result buffer - { - // reverse of counter adjustment in generate() - if self.0.core.state[12] == 0 { - self.0.core.state[13] = self.0.core.state[13].wrapping_sub(1); - } - self.0.core.state[12] = self.0.core.state[12].wrapping_sub(1); - } - self.0.generate_and_set(index); - } - } -} - -/// The core of `ChaChaRng`, used with `BlockRng`. -#[derive(Clone)] -pub struct ChaChaCore { - state: [u32; STATE_WORDS], -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for ChaChaCore { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "ChaChaCore {{}}") - } -} - -macro_rules! quarter_round{ - ($a: expr, $b: expr, $c: expr, $d: expr) => {{ - $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16); - $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12); - $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8); - $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7); - }} -} - -macro_rules! double_round{ - ($x: expr) => {{ - // Column round - quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); - quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); - quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); - quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); - // Diagonal round - quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); - quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); - quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); - quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); - }} -} - -impl BlockRngCore for ChaChaCore { - type Item = u32; - type Results = [u32; STATE_WORDS]; - - fn generate(&mut self, results: &mut Self::Results) { - // For some reason extracting this part into a separate function - // improves performance by 50%. - fn core(results: &mut [u32; STATE_WORDS], - state: &[u32; STATE_WORDS]) - { - let mut tmp = *state; - let rounds = 20; - for _ in 0..rounds / 2 { - double_round!(tmp); - } - for i in 0..STATE_WORDS { - results[i] = tmp[i].wrapping_add(state[i]); - } - } - - core(results, &self.state); - - // update 64-bit counter - self.state[12] = self.state[12].wrapping_add(1); - if self.state[12] != 0 { return; }; - self.state[13] = self.state[13].wrapping_add(1); - } -} - -impl SeedableRng for ChaChaCore { - type Seed = [u8; SEED_WORDS*4]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_le = [0u32; SEED_WORDS]; - le::read_u32_into(&seed, &mut seed_le); - Self { - state: [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574, // constants - seed_le[0], seed_le[1], seed_le[2], seed_le[3], // seed - seed_le[4], seed_le[5], seed_le[6], seed_le[7], // seed - 0, 0, 0, 0], // counter - } - } -} - -impl CryptoRng for ChaChaCore {} - -impl From for ChaChaRng { - fn from(core: ChaChaCore) -> Self { - ChaChaRng(BlockRng::new(core)) - } -} - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use super::ChaChaRng; - - #[test] - fn test_chacha_construction() { - let seed = [0,0,0,0,0,0,0,0, - 1,0,0,0,0,0,0,0, - 2,0,0,0,0,0,0,0, - 3,0,0,0,0,0,0,0]; - let mut rng1 = ChaChaRng::from_seed(seed); - assert_eq!(rng1.next_u32(), 137206642); - - let mut rng2 = ChaChaRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u32(), 1325750369); - } - - #[test] - fn test_chacha_true_values_a() { - // Test vectors 1 and 2 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, - 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, - 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, - 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2]; - assert_eq!(results, expected); - - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, - 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, - 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, - 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_true_values_b() { - // Test vector 3 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 1]; - let mut rng = ChaChaRng::from_seed(seed); - - // Skip block 0 - for _ in 0..16 { rng.next_u32(); } - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, - 0xe8252083, 0x60818b01, 0xf38422b8, 0x5aaa49c9, - 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, - 0x4436274e, 0x2561b3c8, 0xebdd4aa6, 0xa0136c00]; - assert_eq!(results, expected); - } - - #[test] - #[cfg(feature = "i128_support")] - fn test_chacha_true_values_c() { - // Test vector 4 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - let seed = [0, 0xff, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0]; - let expected = [0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, - 0xa78dea8f, 0x5e269039, 0xa1bebbc1, 0xcaf09aae, - 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, - 0x546ca624, 0x1bec45d5, 0x87f47473, 0x96f0992e]; - let expected_end = 3 * 16; - let mut results = [0u32; 16]; - - // Test block 2 by skipping block 0 and 1 - let mut rng1 = ChaChaRng::from_seed(seed); - for _ in 0..32 { rng1.next_u32(); } - for i in results.iter_mut() { *i = rng1.next_u32(); } - assert_eq!(results, expected); - assert_eq!(rng1.get_word_pos(), expected_end); - - // Test block 2 by using `set_word_pos` - let mut rng2 = ChaChaRng::from_seed(seed); - rng2.set_word_pos(2 * 16); - for i in results.iter_mut() { *i = rng2.next_u32(); } - assert_eq!(results, expected); - assert_eq!(rng2.get_word_pos(), expected_end); - - // Test skipping behaviour with other types - let mut buf = [0u8; 32]; - rng2.fill_bytes(&mut buf[..]); - assert_eq!(rng2.get_word_pos(), expected_end + 8); - rng2.fill_bytes(&mut buf[0..25]); - assert_eq!(rng2.get_word_pos(), expected_end + 15); - rng2.next_u64(); - assert_eq!(rng2.get_word_pos(), expected_end + 17); - rng2.next_u32(); - rng2.next_u64(); - assert_eq!(rng2.get_word_pos(), expected_end + 20); - rng2.fill_bytes(&mut buf[0..1]); - assert_eq!(rng2.get_word_pos(), expected_end + 21); - } - - #[test] - fn test_chacha_multiple_blocks() { - let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; - let mut rng = ChaChaRng::from_seed(seed); - - // Store the 17*i-th 32-bit word, - // i.e., the i-th word of the i-th 16-word block - let mut results = [0u32; 16]; - for i in results.iter_mut() { - *i = rng.next_u32(); - for _ in 0..16 { - rng.next_u32(); - } - } - let expected = [0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, - 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, - 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, - 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_true_bytes() { - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - let expected = [118, 184, 224, 173, 160, 241, 61, 144, - 64, 93, 106, 229, 83, 134, 189, 40, - 189, 210, 25, 184, 160, 141, 237, 26, - 168, 54, 239, 204, 139, 119, 13, 199]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_nonce() { - // Test vector 5 from - // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 - // Although we do not support setting a nonce, we try it here anyway so - // we can use this test vector. - let seed = [0u8; 32]; - let mut rng = ChaChaRng::from_seed(seed); - // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2 - rng.set_stream(2u64 << (24 + 32)); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, - 0x88228b1a, 0x96a4dfb3, 0x5b76ab72, 0xc727ee54, - 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, - 0x99c28f5f, 0x628314e8, 0x398a19fa, 0x6ded1b53]; - assert_eq!(results, expected); - } - - #[test] - fn test_chacha_clone_streams() { - let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; - let mut rng = ChaChaRng::from_seed(seed); - let mut clone = rng.clone(); - for _ in 0..16 { - assert_eq!(rng.next_u64(), clone.next_u64()); - } - - rng.set_stream(51); - for _ in 0..7 { - assert!(rng.next_u32() != clone.next_u32()); - } - clone.set_stream(51); // switch part way through block - for _ in 7..16 { - assert_eq!(rng.next_u32(), clone.next_u32()); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/hc128.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/hc128.rs deleted file mode 100644 index 5aa2d24..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/hc128.rs +++ /dev/null @@ -1,464 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://www.rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The HC-128 random number generator. - -use core::fmt; -use rand_core::{CryptoRng, RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng}; - -const SEED_WORDS: usize = 8; // 128 bit key followed by 128 bit iv - -/// A cryptographically secure random number generator that uses the HC-128 -/// algorithm. -/// -/// HC-128 is a stream cipher designed by Hongjun Wu[^1], that we use as an -/// RNG. It is selected as one of the "stream ciphers suitable for widespread -/// adoption" by eSTREAM[^2]. -/// -/// HC-128 is an array based RNG. In this it is similar to RC-4 and ISAAC before -/// it, but those have never been proven cryptographically secure (or have even -/// been significantly compromised, as in the case of RC-4[^5]). -/// -/// Because HC-128 works with simple indexing into a large array and with a few -/// operations that parallelize well, it has very good performance. The size of -/// the array it needs, 4kb, can however be a disadvantage. -/// -/// This implementation is not based on the version of HC-128 submitted to the -/// eSTREAM contest, but on a later version by the author with a few small -/// improvements from December 15, 2009[^3]. -/// -/// HC-128 has no known weaknesses that are easier to exploit than doing a -/// brute-force search of 2128. A very comprehensive analysis of the -/// current state of known attacks / weaknesses of HC-128 is given in *Some -/// Results On Analysis And Implementation Of HC-128 Stream Cipher*[^4]. -/// -/// The average cycle length is expected to be -/// 21024*32+10-1 = 232777. -/// We support seeding with a 256-bit array, which matches the 128-bit key -/// concatenated with a 128-bit IV from the stream cipher. -/// -/// This implementation uses an output buffer of sixteen `u32` words, and uses -/// [`BlockRng`] to implement the [`RngCore`] methods. -/// -/// ## References -/// [^1]: Hongjun Wu (2008). ["The Stream Cipher HC-128"]( -/// http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf). -/// *The eSTREAM Finalists*, LNCS 4986, pp. 39–47, Springer-Verlag. -/// -/// [^2]: [eSTREAM: the ECRYPT Stream Cipher Project]( -/// http://www.ecrypt.eu.org/stream/) -/// -/// [^3]: Hongjun Wu, [Stream Ciphers HC-128 and HC-256]( -/// https://www.ntu.edu.sg/home/wuhj/research/hc/index.html) -/// -/// [^4]: Shashwat Raizada (January 2015),["Some Results On Analysis And -/// Implementation Of HC-128 Stream Cipher"]( -/// http://library.isical.ac.in:8080/jspui/bitstream/123456789/6636/1/TH431.pdf). -/// -/// [^5]: Internet Engineering Task Force (February 2015), -/// ["Prohibiting RC4 Cipher Suites"](https://tools.ietf.org/html/rfc7465). -/// -/// [`BlockRng`]: ../../../rand_core/block/struct.BlockRng.html -/// [`RngCore`]: ../../trait.RngCore.html -#[derive(Clone, Debug)] -pub struct Hc128Rng(BlockRng); - -impl RngCore for Hc128Rng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Hc128Rng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - Hc128Rng(BlockRng::::from_seed(seed)) - } - - fn from_rng(rng: R) -> Result { - BlockRng::::from_rng(rng).map(Hc128Rng) - } -} - -impl CryptoRng for Hc128Rng {} - -/// The core of `Hc128Rng`, used with `BlockRng`. -#[derive(Clone)] -pub struct Hc128Core { - t: [u32; 1024], - counter1024: usize, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Hc128Core { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Hc128Core {{}}") - } -} - -impl BlockRngCore for Hc128Core { - type Item = u32; - type Results = [u32; 16]; - - fn generate(&mut self, results: &mut Self::Results) { - assert!(self.counter1024 % 16 == 0); - - let cc = self.counter1024 % 512; - let dd = (cc + 16) % 512; - let ee = cc.wrapping_sub(16) % 512; - - if self.counter1024 & 512 == 0 { - // P block - results[0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); - results[1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); - results[2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); - results[3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); - results[4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); - results[5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); - results[6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); - results[7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); - results[8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); - results[9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); - results[10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); - results[11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); - results[12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); - results[13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); - results[14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); - results[15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); - } else { - // Q block - results[0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); - results[1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); - results[2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); - results[3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); - results[4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); - results[5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); - results[6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); - results[7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); - results[8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); - results[9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); - results[10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); - results[11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); - results[12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); - results[13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); - results[14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); - results[15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); - } - self.counter1024 = self.counter1024.wrapping_add(16); - } -} - -impl Hc128Core { - // One step of HC-128, update P and generate 32 bits keystream - #[inline(always)] - fn step_p(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) - -> u32 - { - let (p, q) = self.t.split_at_mut(512); - // FIXME: it would be great if we the bounds checks here could be - // optimized out, and we would not need unsafe. - // This improves performance by about 7%. - unsafe { - let temp0 = p.get_unchecked(i511).rotate_right(23); - let temp1 = p.get_unchecked(i3).rotate_right(10); - let temp2 = p.get_unchecked(i10).rotate_right(8); - *p.get_unchecked_mut(i) = p.get_unchecked(i) - .wrapping_add(temp2) - .wrapping_add(temp0 ^ temp1); - let temp3 = { - // The h1 function in HC-128 - let a = *p.get_unchecked(i12) as u8; - let c = (p.get_unchecked(i12) >> 16) as u8; - q[a as usize].wrapping_add(q[256 + c as usize]) - }; - temp3 ^ p.get_unchecked(i) - } - } - - // One step of HC-128, update Q and generate 32 bits keystream - // Similar to `step_p`, but `p` and `q` are swapped, and the rotates are to - // the left instead of to the right. - #[inline(always)] - fn step_q(&mut self, i: usize, i511: usize, i3: usize, i10: usize, i12: usize) - -> u32 - { - let (p, q) = self.t.split_at_mut(512); - unsafe { - let temp0 = q.get_unchecked(i511).rotate_left(23); - let temp1 = q.get_unchecked(i3).rotate_left(10); - let temp2 = q.get_unchecked(i10).rotate_left(8); - *q.get_unchecked_mut(i) = q.get_unchecked(i) - .wrapping_add(temp2) - .wrapping_add(temp0 ^ temp1); - let temp3 = { - // The h2 function in HC-128 - let a = *q.get_unchecked(i12) as u8; - let c = (q.get_unchecked(i12) >> 16) as u8; - p[a as usize].wrapping_add(p[256 + c as usize]) - }; - temp3 ^ q.get_unchecked(i) - } - } - - fn sixteen_steps(&mut self) { - assert!(self.counter1024 % 16 == 0); - - let cc = self.counter1024 % 512; - let dd = (cc + 16) % 512; - let ee = cc.wrapping_sub(16) % 512; - - if self.counter1024 < 512 { - // P block - self.t[cc+0] = self.step_p(cc+0, cc+1, ee+13, ee+6, ee+4); - self.t[cc+1] = self.step_p(cc+1, cc+2, ee+14, ee+7, ee+5); - self.t[cc+2] = self.step_p(cc+2, cc+3, ee+15, ee+8, ee+6); - self.t[cc+3] = self.step_p(cc+3, cc+4, cc+0, ee+9, ee+7); - self.t[cc+4] = self.step_p(cc+4, cc+5, cc+1, ee+10, ee+8); - self.t[cc+5] = self.step_p(cc+5, cc+6, cc+2, ee+11, ee+9); - self.t[cc+6] = self.step_p(cc+6, cc+7, cc+3, ee+12, ee+10); - self.t[cc+7] = self.step_p(cc+7, cc+8, cc+4, ee+13, ee+11); - self.t[cc+8] = self.step_p(cc+8, cc+9, cc+5, ee+14, ee+12); - self.t[cc+9] = self.step_p(cc+9, cc+10, cc+6, ee+15, ee+13); - self.t[cc+10] = self.step_p(cc+10, cc+11, cc+7, cc+0, ee+14); - self.t[cc+11] = self.step_p(cc+11, cc+12, cc+8, cc+1, ee+15); - self.t[cc+12] = self.step_p(cc+12, cc+13, cc+9, cc+2, cc+0); - self.t[cc+13] = self.step_p(cc+13, cc+14, cc+10, cc+3, cc+1); - self.t[cc+14] = self.step_p(cc+14, cc+15, cc+11, cc+4, cc+2); - self.t[cc+15] = self.step_p(cc+15, dd+0, cc+12, cc+5, cc+3); - } else { - // Q block - self.t[cc+512+0] = self.step_q(cc+0, cc+1, ee+13, ee+6, ee+4); - self.t[cc+512+1] = self.step_q(cc+1, cc+2, ee+14, ee+7, ee+5); - self.t[cc+512+2] = self.step_q(cc+2, cc+3, ee+15, ee+8, ee+6); - self.t[cc+512+3] = self.step_q(cc+3, cc+4, cc+0, ee+9, ee+7); - self.t[cc+512+4] = self.step_q(cc+4, cc+5, cc+1, ee+10, ee+8); - self.t[cc+512+5] = self.step_q(cc+5, cc+6, cc+2, ee+11, ee+9); - self.t[cc+512+6] = self.step_q(cc+6, cc+7, cc+3, ee+12, ee+10); - self.t[cc+512+7] = self.step_q(cc+7, cc+8, cc+4, ee+13, ee+11); - self.t[cc+512+8] = self.step_q(cc+8, cc+9, cc+5, ee+14, ee+12); - self.t[cc+512+9] = self.step_q(cc+9, cc+10, cc+6, ee+15, ee+13); - self.t[cc+512+10] = self.step_q(cc+10, cc+11, cc+7, cc+0, ee+14); - self.t[cc+512+11] = self.step_q(cc+11, cc+12, cc+8, cc+1, ee+15); - self.t[cc+512+12] = self.step_q(cc+12, cc+13, cc+9, cc+2, cc+0); - self.t[cc+512+13] = self.step_q(cc+13, cc+14, cc+10, cc+3, cc+1); - self.t[cc+512+14] = self.step_q(cc+14, cc+15, cc+11, cc+4, cc+2); - self.t[cc+512+15] = self.step_q(cc+15, dd+0, cc+12, cc+5, cc+3); - } - self.counter1024 += 16; - } - - // Initialize an HC-128 random number generator. The seed has to be - // 256 bits in length (`[u32; 8]`), matching the 128 bit `key` followed by - // 128 bit `iv` when HC-128 where to be used as a stream cipher. - fn init(seed: [u32; SEED_WORDS]) -> Self { - #[inline] - fn f1(x: u32) -> u32 { - x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) - } - - #[inline] - fn f2(x: u32) -> u32 { - x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) - } - - let mut t = [0u32; 1024]; - - // Expand the key and iv into P and Q - let (key, iv) = seed.split_at(4); - t[..4].copy_from_slice(key); - t[4..8].copy_from_slice(key); - t[8..12].copy_from_slice(iv); - t[12..16].copy_from_slice(iv); - - // Generate the 256 intermediate values W[16] ... W[256+16-1], and - // copy the last 16 generated values to the start op P. - for i in 16..256+16 { - t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) - .wrapping_add(t[i-16]).wrapping_add(i as u32); - } - { - let (p1, p2) = t.split_at_mut(256); - p1[0..16].copy_from_slice(&p2[0..16]); - } - - // Generate both the P and Q tables - for i in 16..1024 { - t[i] = f2(t[i-2]).wrapping_add(t[i-7]).wrapping_add(f1(t[i-15])) - .wrapping_add(t[i-16]).wrapping_add(256 + i as u32); - } - - let mut core = Self { t, counter1024: 0 }; - - // run the cipher 1024 steps - for _ in 0..64 { core.sixteen_steps() }; - core.counter1024 = 0; - core - } -} - -impl SeedableRng for Hc128Core { - type Seed = [u8; SEED_WORDS*4]; - - /// Create an HC-128 random number generator with a seed. The seed has to be - /// 256 bits in length, matching the 128 bit `key` followed by 128 bit `iv` - /// when HC-128 where to be used as a stream cipher. - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; SEED_WORDS]; - le::read_u32_into(&seed, &mut seed_u32); - Self::init(seed_u32) - } -} - -impl CryptoRng for Hc128Core {} - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use super::Hc128Rng; - - #[test] - // Test vector 1 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_a() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x73150082, 0x3bfd03a0, 0xfb2fd77f, 0xaa63af0e, - 0xde122fc6, 0xa7dc29b6, 0x62a68527, 0x8b75ec68, - 0x9036db1e, 0x81896005, 0x00ade078, 0x491fbf9a, - 0x1cdc3013, 0x6c3d6e24, 0x90f664b2, 0x9cd57102]; - assert_eq!(results, expected); - } - - #[test] - // Test vector 2 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_b() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0xc01893d5, 0xb7dbe958, 0x8f65ec98, 0x64176604, - 0x36fc6724, 0xc82c6eec, 0x1b1c38a7, 0xc9b42a95, - 0x323ef123, 0x0a6a908b, 0xce757b68, 0x9f14f7bb, - 0xe4cde011, 0xaeb5173f, 0x89608c94, 0xb5cf46ca]; - assert_eq!(results, expected); - } - - #[test] - // Test vector 3 from the paper "The Stream Cipher HC-128" - fn test_hc128_true_values_c() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected = [0x518251a4, 0x04b4930a, 0xb02af931, 0x0639f032, - 0xbcb4a47a, 0x5722480b, 0x2bf99f72, 0xcdc0e566, - 0x310f0c56, 0xd3cc83e8, 0x663db8ef, 0x62dfe07f, - 0x593e1790, 0xc5ceaa9c, 0xab03806f, 0xc9a6e5a0]; - assert_eq!(results, expected); - } - - #[test] - fn test_hc128_true_values_u64() { - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - - let mut results = [0u64; 8]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [0x3bfd03a073150082, 0xaa63af0efb2fd77f, - 0xa7dc29b6de122fc6, 0x8b75ec6862a68527, - 0x818960059036db1e, 0x491fbf9a00ade078, - 0x6c3d6e241cdc3013, 0x9cd5710290f664b2]; - assert_eq!(results, expected); - - // The RNG operates in a P block of 512 results and next a Q block. - // After skipping 2*800 u32 results we end up somewhere in the Q block - // of the second round - for _ in 0..800 { rng.next_u64(); } - - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [0xd8c4d6ca84d0fc10, 0xf16a5d91dc66e8e7, - 0xd800de5bc37a8653, 0x7bae1f88c0dfbb4c, - 0x3bfe1f374e6d4d14, 0x424b55676be3fa06, - 0xe3a1e8758cbff579, 0x417f7198c5652bcd]; - assert_eq!(results, expected); - } - - #[test] - fn test_hc128_true_values_bytes() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng = Hc128Rng::from_seed(seed); - let expected = [0x31, 0xf9, 0x2a, 0xb0, 0x32, 0xf0, 0x39, 0x06, - 0x7a, 0xa4, 0xb4, 0xbc, 0x0b, 0x48, 0x22, 0x57, - 0x72, 0x9f, 0xf9, 0x2b, 0x66, 0xe5, 0xc0, 0xcd, - 0x56, 0x0c, 0x0f, 0x31, 0xe8, 0x83, 0xcc, 0xd3, - 0xef, 0xb8, 0x3d, 0x66, 0x7f, 0xe0, 0xdf, 0x62, - 0x90, 0x17, 0x3e, 0x59, 0x9c, 0xaa, 0xce, 0xc5, - 0x6f, 0x80, 0x03, 0xab, 0xa0, 0xe5, 0xa6, 0xc9, - 0x60, 0x95, 0x84, 0x7a, 0xa5, 0x68, 0x5a, 0x84, - 0xea, 0xd5, 0xf3, 0xea, 0x73, 0xa9, 0xad, 0x01, - 0x79, 0x7d, 0xbe, 0x9f, 0xea, 0xe3, 0xf9, 0x74, - 0x0e, 0xda, 0x2f, 0xa0, 0xe4, 0x7b, 0x4b, 0x1b, - 0xdd, 0x17, 0x69, 0x4a, 0xfe, 0x9f, 0x56, 0x95, - 0xad, 0x83, 0x6b, 0x9d, 0x60, 0xa1, 0x99, 0x96, - 0x90, 0x00, 0x66, 0x7f, 0xfa, 0x7e, 0x65, 0xe9, - 0xac, 0x8b, 0x92, 0x34, 0x77, 0xb4, 0x23, 0xd0, - 0xb9, 0xab, 0xb1, 0x47, 0x7d, 0x4a, 0x13, 0x0a]; - - // Pick a somewhat large buffer so we can test filling with the - // remainder from `state.results`, directly filling the buffer, and - // filling the remainder of the buffer. - let mut buffer = [0u8; 16*4*2]; - // Consume a value so that we have a remainder. - assert!(rng.next_u64() == 0x04b4930a518251a4); - rng.fill_bytes(&mut buffer); - - // [u8; 128] doesn't implement PartialEq - assert_eq!(buffer.len(), expected.len()); - for (b, e) in buffer.iter().zip(expected.iter()) { - assert_eq!(b, e); - } - } - - #[test] - fn test_hc128_clone() { - let seed = [0x55,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, // key - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; // iv - let mut rng1 = Hc128Rng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u32(), rng2.next_u32()); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac.rs deleted file mode 100644 index 99c80d6..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac.rs +++ /dev/null @@ -1,494 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ISAAC random number generator. - -use core::{fmt, slice}; -use core::num::Wrapping as w; -use rand_core::{RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng}; -use prng::isaac_array::IsaacArray; - -#[allow(non_camel_case_types)] -type w32 = w; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - -/// A random number generator that uses the ISAAC algorithm. -/// -/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are -/// the principal bitwise operations employed. It is the most advanced of a -/// series of array based random number generator designed by Robert Jenkins -/// in 1996[^1][^2]. -/// -/// ISAAC is notably fast and produces excellent quality random numbers for -/// non-cryptographic applications. -/// -/// In spite of being designed with cryptographic security in mind, ISAAC hasn't -/// been stringently cryptanalyzed and thus cryptographers do not not -/// consensually trust it to be secure. When looking for a secure RNG, prefer -/// [`Hc128Rng`] instead, which, like ISAAC, is an array-based RNG and one of -/// the stream-ciphers selected the by eSTREAM contest. -/// -/// In 2006 an improvement to ISAAC was suggested by Jean-Philippe Aumasson, -/// named ISAAC+[^3]. But because the specification is not complete, because -/// there is no good implementation, and because the suggested bias may not -/// exist, it is not implemented here. -/// -/// ## Overview of the ISAAC algorithm: -/// (in pseudo-code) -/// -/// ```text -/// Input: a, b, c, s[256] // state -/// Output: r[256] // results -/// -/// mix(a,i) = a ^ a << 13 if i = 0 mod 4 -/// a ^ a >> 6 if i = 1 mod 4 -/// a ^ a << 2 if i = 2 mod 4 -/// a ^ a >> 16 if i = 3 mod 4 -/// -/// c = c + 1 -/// b = b + c -/// -/// for i in 0..256 { -/// x = s_[i] -/// a = f(a,i) + s[i+128 mod 256] -/// y = a + b + s[x>>2 mod 256] -/// s[i] = y -/// b = x + s[y>>10 mod 256] -/// r[i] = b -/// } -/// ``` -/// -/// Numbers are generated in blocks of 256. This means the function above only -/// runs once every 256 times you ask for a next random number. In all other -/// circumstances the last element of the results array is returned. -/// -/// ISAAC therefore needs a lot of memory, relative to other non-crypto RNGs. -/// 2 * 256 * 4 = 2 kb to hold the state and results. -/// -/// This implementation uses [`BlockRng`] to implement the [`RngCore`] methods. -/// -/// ## References -/// [^1]: Bob Jenkins, [*ISAAC: A fast cryptographic random number generator*]( -/// http://burtleburtle.net/bob/rand/isaacafa.html) -/// -/// [^2]: Bob Jenkins, [*ISAAC and RC4*]( -/// http://burtleburtle.net/bob/rand/isaac.html) -/// -/// [^3]: Jean-Philippe Aumasson, [*On the pseudo-random generator ISAAC*]( -/// https://eprint.iacr.org/2006/438) -/// -/// [`Hc128Rng`]: ../hc128/struct.Hc128Rng.html -/// [`BlockRng`]: ../../../rand_core/block/struct.BlockRng.html -/// [`RngCore`]: ../../trait.RngCore.html -#[derive(Clone, Debug)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct IsaacRng(BlockRng); - -impl RngCore for IsaacRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for IsaacRng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - IsaacRng(BlockRng::::from_seed(seed)) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - fn seed_from_u64(seed: u64) -> Self { - IsaacRng(BlockRng::::seed_from_u64(seed)) - } - - fn from_rng(rng: S) -> Result { - BlockRng::::from_rng(rng).map(|rng| IsaacRng(rng)) - } -} - -impl IsaacRng { - /// Create an ISAAC random number generator using the default - /// fixed seed. - /// - /// DEPRECATED. `IsaacRng::new_from_u64(0)` will produce identical results. - #[deprecated(since="0.5.0", note="use the FromEntropy or SeedableRng trait")] - pub fn new_unseeded() -> Self { - Self::seed_from_u64(0) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] - pub fn new_from_u64(seed: u64) -> Self { - Self::seed_from_u64(seed) - } -} - -/// The core of `IsaacRng`, used with `BlockRng`. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct IsaacCore { - #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] - mem: [w32; RAND_SIZE], - a: w32, - b: w32, - c: w32, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for IsaacCore { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "IsaacCore {{}}") - } -} - -impl BlockRngCore for IsaacCore { - type Item = u32; - type Results = IsaacArray; - - /// Refills the output buffer, `results`. See also the pseudocode desciption - /// of the algorithm in the [`IsaacRng`] documentation. - /// - /// Optimisations used (similar to the reference implementation): - /// - /// - The loop is unrolled 4 times, once for every constant of mix(). - /// - The contents of the main loop are moved to a function `rngstep`, to - /// reduce code duplication. - /// - We use local variables for a and b, which helps with optimisations. - /// - We split the main loop in two, one that operates over 0..128 and one - /// over 128..256. This way we can optimise out the addition and modulus - /// from `s[i+128 mod 256]`. - /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the - /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer - /// arithmetic. - /// - We fill `results` backwards. The reference implementation reads values - /// from `results` in reverse. We read them in the normal direction, to - /// make `fill_bytes` a memcopy. To maintain compatibility we fill in - /// reverse. - /// - /// [`IsaacRng`]: struct.IsaacRng.html - fn generate(&mut self, results: &mut IsaacArray) { - self.c += w(1); - // abbreviations - let mut a = self.a; - let mut b = self.b + self.c; - const MIDPOINT: usize = RAND_SIZE / 2; - - #[inline] - fn ind(mem:&[w32; RAND_SIZE], v: w32, amount: usize) -> w32 { - let index = (v >> amount).0 as usize % RAND_SIZE; - mem[index] - } - - #[inline] - fn rngstep(mem: &mut [w32; RAND_SIZE], - results: &mut [u32; RAND_SIZE], - mix: w32, - a: &mut w32, - b: &mut w32, - base: usize, - m: usize, - m2: usize) { - let x = mem[base + m]; - *a = mix + mem[base + m2]; - let y = *a + *b + ind(&mem, x, 2); - mem[base + m] = y; - *b = x + ind(&mem, y, 2 + RAND_SIZE_LEN); - results[RAND_SIZE - 1 - base - m] = (*b).0; - } - - let mut m = 0; - let mut m2 = MIDPOINT; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); - } - - m = MIDPOINT; - m2 = 0; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, a ^ (a << 13), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 6 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 2 ), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 16), &mut a, &mut b, i + 3, m, m2); - } - - self.a = a; - self.b = b; - } -} - -impl IsaacCore { - /// Create a new ISAAC random number generator. - /// - /// The author Bob Jenkins describes how to best initialize ISAAC here: - /// - /// The answer is included here just in case: - /// - /// "No, you don't need a full 8192 bits of seed data. Normal key sizes will - /// do fine, and they should have their expected strength (eg a 40-bit key - /// will take as much time to brute force as 40-bit keys usually will). You - /// could fill the remainder with 0, but set the last array element to the - /// length of the key provided (to distinguish keys that differ only by - /// different amounts of 0 padding). You do still need to call `randinit()` - /// to make sure the initial state isn't uniform-looking." - /// "After publishing ISAAC, I wanted to limit the key to half the size of - /// `r[]`, and repeat it twice. That would have made it hard to provide a - /// key that sets the whole internal state to anything convenient. But I'd - /// already published it." - /// - /// And his answer to the question "For my code, would repeating the key - /// over and over to fill 256 integers be a better solution than - /// zero-filling, or would they essentially be the same?": - /// "If the seed is under 32 bytes, they're essentially the same, otherwise - /// repeating the seed would be stronger. randinit() takes a chunk of 32 - /// bytes, mixes it, and combines that with the next 32 bytes, et cetera. - /// Then loops over all the elements the same way a second time." - #[inline] - fn init(mut mem: [w32; RAND_SIZE], rounds: u32) -> Self { - fn mix(a: &mut w32, b: &mut w32, c: &mut w32, d: &mut w32, - e: &mut w32, f: &mut w32, g: &mut w32, h: &mut w32) { - *a ^= *b << 11; *d += *a; *b += *c; - *b ^= *c >> 2; *e += *b; *c += *d; - *c ^= *d << 8; *f += *c; *d += *e; - *d ^= *e >> 16; *g += *d; *e += *f; - *e ^= *f << 10; *h += *e; *f += *g; - *f ^= *g >> 4; *a += *f; *g += *h; - *g ^= *h << 8; *b += *g; *h += *a; - *h ^= *a >> 9; *c += *h; *a += *b; - } - - // These numbers are the result of initializing a...h with the - // fractional part of the golden ratio in binary (0x9e3779b9) - // and applying mix() 4 times. - let mut a = w(0x1367df5a); - let mut b = w(0x95d90059); - let mut c = w(0xc3163e4b); - let mut d = w(0x0f421ad8); - let mut e = w(0xd92a4a78); - let mut f = w(0xa51a3c49); - let mut g = w(0xc4efea1b); - let mut h = w(0x30609119); - - // Normally this should do two passes, to make all of the seed effect - // all of `mem` - for _ in 0..rounds { - for i in (0..RAND_SIZE/8).map(|i| i * 8) { - a += mem[i ]; b += mem[i+1]; - c += mem[i+2]; d += mem[i+3]; - e += mem[i+4]; f += mem[i+5]; - g += mem[i+6]; h += mem[i+7]; - mix(&mut a, &mut b, &mut c, &mut d, - &mut e, &mut f, &mut g, &mut h); - mem[i ] = a; mem[i+1] = b; - mem[i+2] = c; mem[i+3] = d; - mem[i+4] = e; mem[i+5] = f; - mem[i+6] = g; mem[i+7] = h; - } - } - - Self { mem, a: w(0), b: w(0), c: w(0) } - } -} - -impl SeedableRng for IsaacCore { - type Seed = [u8; 32]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; 8]; - le::read_u32_into(&seed, &mut seed_u32); - // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. - let mut seed_extended = [w(0); RAND_SIZE]; - for (x, y) in seed_extended.iter_mut().zip(seed_u32.iter()) { - *x = w(*y); - } - Self::init(seed_extended, 2) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - fn seed_from_u64(seed: u64) -> Self { - let mut key = [w(0); RAND_SIZE]; - key[0] = w(seed as u32); - key[1] = w((seed >> 32) as u32); - // Initialize with only one pass. - // A second pass does not improve the quality here, because all of the - // seed was already available in the first round. - // Not doing the second pass has the small advantage that if - // `seed == 0` this method produces exactly the same state as the - // reference implementation when used unseeded. - Self::init(key, 1) - } - - fn from_rng(mut rng: R) -> Result { - // Custom `from_rng` implementation that fills a seed with the same size - // as the entire state. - let mut seed = [w(0u32); RAND_SIZE]; - unsafe { - let ptr = seed.as_mut_ptr() as *mut u8; - - let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 4); - rng.try_fill_bytes(slice)?; - } - for i in seed.iter_mut() { - *i = w(i.0.to_le()); - } - - Ok(Self::init(seed, 2)) - } -} - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use super::IsaacRng; - - #[test] - fn test_isaac_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - assert_eq!(rng1.next_u32(), 2869442790); - - let mut rng2 = IsaacRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u32(), 3094074039); - } - - #[test] - fn test_isaac_true_values_32() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - let mut results = [0u32; 10]; - for i in results.iter_mut() { *i = rng1.next_u32(); } - let expected = [ - 2558573138, 873787463, 263499565, 2103644246, 3595684709, - 4203127393, 264982119, 2765226902, 2737944514, 3900253796]; - assert_eq!(results, expected); - - let seed = [57,48,0,0, 50,9,1,0, 49,212,0,0, 148,38,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng2 = IsaacRng::from_seed(seed); - // skip forward to the 10000th number - for _ in 0..10000 { rng2.next_u32(); } - - for i in results.iter_mut() { *i = rng2.next_u32(); } - let expected = [ - 3676831399, 3183332890, 2834741178, 3854698763, 2717568474, - 1576568959, 3507990155, 179069555, 141456972, 2478885421]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_true_values_64() { - // As above, using little-endian versions of above values - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - let mut results = [0u64; 5]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected = [ - 3752888579798383186, 9035083239252078381,18052294697452424037, - 11876559110374379111, 16751462502657800130]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_true_bytes() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - // Same as first values in test_isaac_true_values as bytes in LE order - let expected = [82, 186, 128, 152, 71, 240, 20, 52, - 45, 175, 180, 15, 86, 16, 99, 125, - 101, 203, 81, 214, 97, 162, 134, 250, - 103, 78, 203, 15, 150, 3, 210, 164]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_new_uninitialized() { - // Compare the results from initializing `IsaacRng` with - // `seed_from_u64(0)`, to make sure it is the same as the reference - // implementation when used uninitialized. - // Note: We only test the first 16 integers, not the full 256 of the - // first block. - let mut rng = IsaacRng::seed_from_u64(0); - let mut results = [0u32; 16]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected: [u32; 16] = [ - 0x71D71FD2, 0xB54ADAE7, 0xD4788559, 0xC36129FA, - 0x21DC1EA9, 0x3CB879CA, 0xD83B237F, 0xFA3CE5BD, - 0x8D048509, 0xD82E9489, 0xDB452848, 0xCA20E846, - 0x500F972E, 0x0EEFF940, 0x00D6B993, 0xBC12C17F]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac_clone() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = IsaacRng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u32(), rng2.next_u32()); - } - } - - #[test] - #[cfg(all(feature="serde1", feature="std"))] - fn test_isaac_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = IsaacRng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: IsaacRng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); - - for _ in 0..300 { // more than the 256 buffered results - assert_eq!(rng.next_u32(), deserialized.next_u32()); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac64.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac64.rs deleted file mode 100644 index fb3156d..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac64.rs +++ /dev/null @@ -1,491 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The ISAAC-64 random number generator. - -use core::{fmt, slice}; -use core::num::Wrapping as w; -use rand_core::{RngCore, SeedableRng, Error, le}; -use rand_core::block::{BlockRngCore, BlockRng64}; -use prng::isaac_array::IsaacArray; - -#[allow(non_camel_case_types)] -type w64 = w; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - -/// A random number generator that uses ISAAC-64, the 64-bit variant of the -/// ISAAC algorithm. -/// -/// ISAAC stands for "Indirection, Shift, Accumulate, Add, and Count" which are -/// the principal bitwise operations employed. It is the most advanced of a -/// series of array based random number generator designed by Robert Jenkins -/// in 1996[^1]. -/// -/// ISAAC-64 is mostly similar to ISAAC. Because it operates on 64-bit integers -/// instead of 32-bit, it uses twice as much memory to hold its state and -/// results. Also it uses different constants for shifts and indirect indexing, -/// optimized to give good results for 64bit arithmetic. -/// -/// ISAAC-64 is notably fast and produces excellent quality random numbers for -/// non-cryptographic applications. -/// -/// In spite of being designed with cryptographic security in mind, ISAAC hasn't -/// been stringently cryptanalyzed and thus cryptographers do not not -/// consensually trust it to be secure. When looking for a secure RNG, prefer -/// [`Hc128Rng`] instead, which, like ISAAC, is an array-based RNG and one of -/// the stream-ciphers selected the by eSTREAM contest. -/// -/// ## Overview of the ISAAC-64 algorithm: -/// (in pseudo-code) -/// -/// ```text -/// Input: a, b, c, s[256] // state -/// Output: r[256] // results -/// -/// mix(a,i) = !(a ^ a << 21) if i = 0 mod 4 -/// a ^ a >> 5 if i = 1 mod 4 -/// a ^ a << 12 if i = 2 mod 4 -/// a ^ a >> 33 if i = 3 mod 4 -/// -/// c = c + 1 -/// b = b + c -/// -/// for i in 0..256 { -/// x = s_[i] -/// a = mix(a,i) + s[i+128 mod 256] -/// y = a + b + s[x>>3 mod 256] -/// s[i] = y -/// b = x + s[y>>11 mod 256] -/// r[i] = b -/// } -/// ``` -/// -/// This implementation uses [`BlockRng64`] to implement the [`RngCore`] methods. -/// -/// See for more information the documentation of [`IsaacRng`]. -/// -/// [^1]: Bob Jenkins, [*ISAAC and RC4*]( -/// http://burtleburtle.net/bob/rand/isaac.html) -/// -/// [`IsaacRng`]: ../isaac/struct.IsaacRng.html -/// [`Hc128Rng`]: ../hc128/struct.Hc128Rng.html -/// [`BlockRng64`]: ../../../rand_core/block/struct.BlockRng64.html -/// [`RngCore`]: ../../trait.RngCore.html -#[derive(Clone, Debug)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Isaac64Rng(BlockRng64); - -impl RngCore for Isaac64Rng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for Isaac64Rng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - Isaac64Rng(BlockRng64::::from_seed(seed)) - } - - /// Create an ISAAC random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - fn seed_from_u64(seed: u64) -> Self { - Isaac64Rng(BlockRng64::::seed_from_u64(seed)) - } - - fn from_rng(rng: S) -> Result { - BlockRng64::::from_rng(rng).map(|rng| Isaac64Rng(rng)) - } -} - -impl Isaac64Rng { - /// Create a 64-bit ISAAC random number generator using the - /// default fixed seed. - /// - /// DEPRECATED. `Isaac64Rng::new_from_u64(0)` will produce identical results. - #[deprecated(since="0.5.0", note="use the FromEntropy or SeedableRng trait")] - pub fn new_unseeded() -> Self { - Self::seed_from_u64(0) - } - - /// Create an ISAAC-64 random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] - pub fn new_from_u64(seed: u64) -> Self { - Self::seed_from_u64(seed) - } -} - -/// The core of `Isaac64Rng`, used with `BlockRng`. -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct Isaac64Core { - #[cfg_attr(feature="serde1",serde(with="super::isaac_array::isaac_array_serde"))] - mem: [w64; RAND_SIZE], - a: w64, - b: w64, - c: w64, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for Isaac64Core { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Isaac64Core {{}}") - } -} - -impl BlockRngCore for Isaac64Core { - type Item = u64; - type Results = IsaacArray; - - /// Refills the output buffer, `results`. See also the pseudocode desciption - /// of the algorithm in the [`Isaac64Rng`] documentation. - /// - /// Optimisations used (similar to the reference implementation): - /// - /// - The loop is unrolled 4 times, once for every constant of mix(). - /// - The contents of the main loop are moved to a function `rngstep`, to - /// reduce code duplication. - /// - We use local variables for a and b, which helps with optimisations. - /// - We split the main loop in two, one that operates over 0..128 and one - /// over 128..256. This way we can optimise out the addition and modulus - /// from `s[i+128 mod 256]`. - /// - We maintain one index `i` and add `m` or `m2` as base (m2 for the - /// `s[i+128 mod 256]`), relying on the optimizer to turn it into pointer - /// arithmetic. - /// - We fill `results` backwards. The reference implementation reads values - /// from `results` in reverse. We read them in the normal direction, to - /// make `fill_bytes` a memcopy. To maintain compatibility we fill in - /// reverse. - /// - /// [`Isaac64Rng`]: struct.Isaac64Rng.html - fn generate(&mut self, results: &mut IsaacArray) { - self.c += w(1); - // abbreviations - let mut a = self.a; - let mut b = self.b + self.c; - const MIDPOINT: usize = RAND_SIZE / 2; - - #[inline] - fn ind(mem:&[w64; RAND_SIZE], v: w64, amount: usize) -> w64 { - let index = (v >> amount).0 as usize % RAND_SIZE; - mem[index] - } - - #[inline] - fn rngstep(mem: &mut [w64; RAND_SIZE], - results: &mut [u64; RAND_SIZE], - mix: w64, - a: &mut w64, - b: &mut w64, - base: usize, - m: usize, - m2: usize) { - let x = mem[base + m]; - *a = mix + mem[base + m2]; - let y = *a + *b + ind(&mem, x, 3); - mem[base + m] = y; - *b = x + ind(&mem, y, 3 + RAND_SIZE_LEN); - results[RAND_SIZE - 1 - base - m] = (*b).0; - } - - let mut m = 0; - let mut m2 = MIDPOINT; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); - } - - m = MIDPOINT; - m2 = 0; - for i in (0..MIDPOINT/4).map(|i| i * 4) { - rngstep(&mut self.mem, results, !(a ^ (a << 21)), &mut a, &mut b, i + 0, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 5 ), &mut a, &mut b, i + 1, m, m2); - rngstep(&mut self.mem, results, a ^ (a << 12), &mut a, &mut b, i + 2, m, m2); - rngstep(&mut self.mem, results, a ^ (a >> 33), &mut a, &mut b, i + 3, m, m2); - } - - self.a = a; - self.b = b; - } -} - -impl Isaac64Core { - /// Create a new ISAAC-64 random number generator. - fn init(mut mem: [w64; RAND_SIZE], rounds: u32) -> Self { - fn mix(a: &mut w64, b: &mut w64, c: &mut w64, d: &mut w64, - e: &mut w64, f: &mut w64, g: &mut w64, h: &mut w64) { - *a -= *e; *f ^= *h >> 9; *h += *a; - *b -= *f; *g ^= *a << 9; *a += *b; - *c -= *g; *h ^= *b >> 23; *b += *c; - *d -= *h; *a ^= *c << 15; *c += *d; - *e -= *a; *b ^= *d >> 14; *d += *e; - *f -= *b; *c ^= *e << 20; *e += *f; - *g -= *c; *d ^= *f >> 17; *f += *g; - *h -= *d; *e ^= *g << 14; *g += *h; - } - - // These numbers are the result of initializing a...h with the - // fractional part of the golden ratio in binary (0x9e3779b97f4a7c13) - // and applying mix() 4 times. - let mut a = w(0x647c4677a2884b7c); - let mut b = w(0xb9f8b322c73ac862); - let mut c = w(0x8c0ea5053d4712a0); - let mut d = w(0xb29b2e824a595524); - let mut e = w(0x82f053db8355e0ce); - let mut f = w(0x48fe4a0fa5a09315); - let mut g = w(0xae985bf2cbfc89ed); - let mut h = w(0x98f5704f6c44c0ab); - - // Normally this should do two passes, to make all of the seed effect - // all of `mem` - for _ in 0..rounds { - for i in (0..RAND_SIZE/8).map(|i| i * 8) { - a += mem[i ]; b += mem[i+1]; - c += mem[i+2]; d += mem[i+3]; - e += mem[i+4]; f += mem[i+5]; - g += mem[i+6]; h += mem[i+7]; - mix(&mut a, &mut b, &mut c, &mut d, - &mut e, &mut f, &mut g, &mut h); - mem[i ] = a; mem[i+1] = b; - mem[i+2] = c; mem[i+3] = d; - mem[i+4] = e; mem[i+5] = f; - mem[i+6] = g; mem[i+7] = h; - } - } - - Self { mem, a: w(0), b: w(0), c: w(0) } - } - - /// Create an ISAAC-64 random number generator using an `u64` as seed. - /// If `seed == 0` this will produce the same stream of random numbers as - /// the reference implementation when used unseeded. - #[deprecated(since="0.6.0", note="use SeedableRng::seed_from_u64 instead")] - pub fn new_from_u64(seed: u64) -> Self { - Self::seed_from_u64(seed) - } -} - -impl SeedableRng for Isaac64Core { - type Seed = [u8; 32]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u64 = [0u64; 4]; - le::read_u64_into(&seed, &mut seed_u64); - // Convert the seed to `Wrapping` and zero-extend to `RAND_SIZE`. - let mut seed_extended = [w(0); RAND_SIZE]; - for (x, y) in seed_extended.iter_mut().zip(seed_u64.iter()) { - *x = w(*y); - } - Self::init(seed_extended, 2) - } - - fn seed_from_u64(seed: u64) -> Self { - let mut key = [w(0); RAND_SIZE]; - key[0] = w(seed); - // Initialize with only one pass. - // A second pass does not improve the quality here, because all of the - // seed was already available in the first round. - // Not doing the second pass has the small advantage that if - // `seed == 0` this method produces exactly the same state as the - // reference implementation when used unseeded. - Self::init(key, 1) - } - - fn from_rng(mut rng: R) -> Result { - // Custom `from_rng` implementation that fills a seed with the same size - // as the entire state. - let mut seed = [w(0u64); RAND_SIZE]; - unsafe { - let ptr = seed.as_mut_ptr() as *mut u8; - let slice = slice::from_raw_parts_mut(ptr, RAND_SIZE * 8); - rng.try_fill_bytes(slice)?; - } - for i in seed.iter_mut() { - *i = w(i.0.to_le()); - } - - Ok(Self::init(seed, 2)) - } -} - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use super::Isaac64Rng; - - #[test] - fn test_isaac64_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - assert_eq!(rng1.next_u64(), 14964555543728284049); - - let mut rng2 = Isaac64Rng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u64(), 919595328260451758); - } - - #[test] - fn test_isaac64_true_values_64() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - let mut results = [0u64; 10]; - for i in results.iter_mut() { *i = rng1.next_u64(); } - let expected = [ - 15071495833797886820, 7720185633435529318, - 10836773366498097981, 5414053799617603544, - 12890513357046278984, 17001051845652595546, - 9240803642279356310, 12558996012687158051, - 14673053937227185542, 1677046725350116783]; - assert_eq!(results, expected); - - let seed = [57,48,0,0, 0,0,0,0, 50,9,1,0, 0,0,0,0, - 49,212,0,0, 0,0,0,0, 148,38,0,0, 0,0,0,0]; - let mut rng2 = Isaac64Rng::from_seed(seed); - // skip forward to the 10000th number - for _ in 0..10000 { rng2.next_u64(); } - - for i in results.iter_mut() { *i = rng2.next_u64(); } - let expected = [ - 18143823860592706164, 8491801882678285927, 2699425367717515619, - 17196852593171130876, 2606123525235546165, 15790932315217671084, - 596345674630742204, 9947027391921273664, 11788097613744130851, - 10391409374914919106]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_true_values_32() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - let mut results = [0u32; 12]; - for i in results.iter_mut() { *i = rng.next_u32(); } - // Subset of above values, as an LE u32 sequence - let expected = [ - 3477963620, 3509106075, - 687845478, 1797495790, - 227048253, 2523132918, - 4044335064, 1260557630, - 4079741768, 3001306521, - 69157722, 3958365844]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_true_values_mixed() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - // Test alternating between `next_u64` and `next_u32` works as expected. - // Values are the same as `test_isaac64_true_values` and - // `test_isaac64_true_values_32`. - assert_eq!(rng.next_u64(), 15071495833797886820); - assert_eq!(rng.next_u32(), 687845478); - assert_eq!(rng.next_u32(), 1797495790); - assert_eq!(rng.next_u64(), 10836773366498097981); - assert_eq!(rng.next_u32(), 4044335064); - // Skip one u32 - assert_eq!(rng.next_u64(), 12890513357046278984); - assert_eq!(rng.next_u32(), 69157722); - } - - #[test] - fn test_isaac64_true_bytes() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - // Same as first values in test_isaac64_true_values as bytes in LE order - let expected = [100, 131, 77, 207, 155, 181, 40, 209, - 102, 176, 255, 40, 238, 155, 35, 107, - 61, 123, 136, 13, 246, 243, 99, 150, - 216, 167, 15, 241, 62, 149, 34, 75]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_new_uninitialized() { - // Compare the results from initializing `IsaacRng` with - // `seed_from_u64(0)`, to make sure it is the same as the reference - // implementation when used uninitialized. - // Note: We only test the first 16 integers, not the full 256 of the - // first block. - let mut rng = Isaac64Rng::seed_from_u64(0); - let mut results = [0u64; 16]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 16] = [ - 0xF67DFBA498E4937C, 0x84A5066A9204F380, 0xFEE34BD5F5514DBB, - 0x4D1664739B8F80D6, 0x8607459AB52A14AA, 0x0E78BC5A98529E49, - 0xFE5332822AD13777, 0x556C27525E33D01A, 0x08643CA615F3149F, - 0xD0771FAF3CB04714, 0x30E86F68A37B008D, 0x3074EBC0488A3ADF, - 0x270645EA7A2790BC, 0x5601A0A8D3763C6A, 0x2F83071F53F325DD, - 0xB9090F3D42D2D2EA]; - assert_eq!(results, expected); - } - - #[test] - fn test_isaac64_clone() { - let seed = [1,0,0,0, 0,0,0,0, 23,0,0,0, 0,0,0,0, - 200,1,0,0, 0,0,0,0, 210,30,0,0, 0,0,0,0]; - let mut rng1 = Isaac64Rng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u64(), rng2.next_u64()); - } - } - - #[test] - #[cfg(all(feature="serde1", feature="std"))] - fn test_isaac64_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 57,48,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = Isaac64Rng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: Isaac64Rng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); - - for _ in 0..300 { // more than the 256 buffered results - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac_array.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac_array.rs deleted file mode 100644 index 3ebf828..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/isaac_array.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2017-2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! ISAAC helper functions for 256-element arrays. - -// Terrible workaround because arrays with more than 32 elements do not -// implement `AsRef`, `Default`, `Serialize`, `Deserialize`, or any other -// traits for that matter. - -#[cfg(feature="serde1")] use serde::{Serialize, Deserialize}; - -const RAND_SIZE_LEN: usize = 8; -const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - - -#[derive(Copy, Clone)] -#[allow(missing_debug_implementations)] -#[cfg_attr(feature="serde1", derive(Serialize, Deserialize))] -pub struct IsaacArray { - #[cfg_attr(feature="serde1",serde(with="isaac_array_serde"))] - #[cfg_attr(feature="serde1", serde(bound( - serialize = "T: Serialize", - deserialize = "T: Deserialize<'de> + Copy + Default")))] - inner: [T; RAND_SIZE] -} - -impl ::core::convert::AsRef<[T]> for IsaacArray { - #[inline(always)] - fn as_ref(&self) -> &[T] { - &self.inner[..] - } -} - -impl ::core::convert::AsMut<[T]> for IsaacArray { - #[inline(always)] - fn as_mut(&mut self) -> &mut [T] { - &mut self.inner[..] - } -} - -impl ::core::ops::Deref for IsaacArray { - type Target = [T; RAND_SIZE]; - #[inline(always)] - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl ::core::ops::DerefMut for IsaacArray { - #[inline(always)] - fn deref_mut(&mut self) -> &mut [T; RAND_SIZE] { - &mut self.inner - } -} - -impl ::core::default::Default for IsaacArray where T: Copy + Default { - fn default() -> IsaacArray { - IsaacArray { inner: [T::default(); RAND_SIZE] } - } -} - - -#[cfg(feature="serde1")] -pub(super) mod isaac_array_serde { - const RAND_SIZE_LEN: usize = 8; - const RAND_SIZE: usize = 1 << RAND_SIZE_LEN; - - use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use serde::de::{Visitor,SeqAccess}; - use serde::de; - - use core::fmt; - - pub fn serialize(arr: &[T;RAND_SIZE], ser: S) -> Result - where - T: Serialize, - S: Serializer - { - use serde::ser::SerializeTuple; - - let mut seq = ser.serialize_tuple(RAND_SIZE)?; - - for e in arr.iter() { - seq.serialize_element(&e)?; - } - - seq.end() - } - - #[inline] - pub fn deserialize<'de, T, D>(de: D) -> Result<[T;RAND_SIZE], D::Error> - where - T: Deserialize<'de>+Default+Copy, - D: Deserializer<'de>, - { - use core::marker::PhantomData; - struct ArrayVisitor { - _pd: PhantomData, - }; - impl<'de,T> Visitor<'de> for ArrayVisitor - where - T: Deserialize<'de>+Default+Copy - { - type Value = [T; RAND_SIZE]; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Isaac state array") - } - - #[inline] - fn visit_seq(self, mut seq: A) -> Result<[T; RAND_SIZE], A::Error> - where - A: SeqAccess<'de>, - { - let mut out = [Default::default();RAND_SIZE]; - - for i in 0..RAND_SIZE { - match seq.next_element()? { - Some(val) => out[i] = val, - None => return Err(de::Error::invalid_length(i, &self)), - }; - } - - Ok(out) - } - } - - de.deserialize_tuple(RAND_SIZE, ArrayVisitor{_pd: PhantomData}) - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/mod.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/mod.rs deleted file mode 100644 index 240b682..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/mod.rs +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Pseudo-random number generators. -//! -//! Pseudo-random number generators are algorithms to produce apparently random -//! numbers deterministically, and usually fairly quickly. See the documentation -//! of the [`rngs` module] for some introduction to PRNGs. -//! -//! As mentioned there, PRNGs fall in two broad categories: -//! -//! - [basic PRNGs], primarily designed for simulations -//! - [CSPRNGs], primarily designed for cryptography -//! -//! In simple terms, the basic PRNGs are often predictable; CSPRNGs should not -//! be predictable *when used correctly*. -//! -//! Contents of this documentation: -//! -//! 1. [The generators](#the-generators) -//! 1. [Performance and size](#performance) -//! 1. [Quality and cycle length](#quality) -//! 1. [Security](#security) -//! 1. [Extra features](#extra-features) -//! 1. [Further reading](#further-reading) -//! -//! -//! # The generators -//! -//! ## Basic pseudo-random number generators (PRNGs) -//! -//! The goal of regular, non-cryptographic PRNGs is usually to find a good -//! balance between simplicity, quality, memory usage and performance. These -//! algorithms are very important to Monte Carlo simulations, and also suitable -//! for several other problems such as randomized algorithms and games (except -//! where there is a risk of players predicting the next output value from -//! previous values, in which case a CSPRNG should be used). -//! -//! Currently Rand provides only one PRNG, and not a very good one at that: -//! -//! | name | full name | performance | memory | quality | period | features | -//! |------|-----------|-------------|--------|---------|--------|----------| -//! | [`XorShiftRng`] | Xorshift 32/128 | ★★★☆☆ | 16 bytes | ★☆☆☆☆ | `u32` * 2128 - 1 | — | -//! -// Quality stars [not rendered in documentation]: -// 5. reserved for crypto-level (e.g. ChaCha8, ISAAC) -// 4. good performance on TestU01 and PractRand, good theory -// (e.g. PCG, truncated Xorshift*) -// 3. good performance on TestU01 and PractRand, but "falling through the -// cracks" or insufficient theory (e.g. SFC, Xoshiro) -// 2. imperfect performance on tests or other limiting properties, but not -// terrible (e.g. Xoroshiro128+) -// 1. clear deficiencies in test results, cycle length, theory, or other -// properties (e.g. Xorshift) -// -// Performance stars [not rendered in documentation]: -// Meant to give an indication of relative performance. Roughly follows a log -// scale, based on the performance of `next_u64` on a current i5/i7: -// - 5. 8000 MB/s+ -// - 4. 4000 MB/s+ -// - 3. 2000 MB/s+ -// - 2. 1000 MB/s+ -// - 1. < 1000 MB/s -// -//! ## Cryptographically secure pseudo-random number generators (CSPRNGs) -//! -//! CSPRNGs have much higher requirements than basic PRNGs. The primary -//! consideration is security. Performance and simplicity are also important, -//! but in general CSPRNGs are more complex and slower than regular PRNGs. -//! Quality is no longer a concern, as it is a requirement for a -//! CSPRNG that the output is basically indistinguishable from true randomness -//! since any bias or correlation makes the output more predictable. -//! -//! There is a close relationship between CSPRNGs and cryptographic ciphers. -//! Any block cipher can be turned into a CSPRNG by encrypting a counter. Stream -//! ciphers are basically a CSPRNG and a combining operation, usually XOR. This -//! means that we can easily use any stream cipher as a CSPRNG. -//! -//! Rand currently provides two trustworthy CSPRNGs and two CSPRNG-like PRNGs: -//! -//! | name | full name | performance | initialization | memory | predictability | forward secrecy | -//! |------|-----------|--------------|--------------|----------|----------------|-------------------------| -//! | [`ChaChaRng`] | ChaCha20 | ★☆☆☆☆ | fast | 136 bytes | secure | no | -//! | [`Hc128Rng`] | HC-128 | ★★☆☆☆ | slow | 4176 bytes | secure | no | -//! | [`IsaacRng`] | ISAAC | ★★☆☆☆ | slow | 2072 bytes | unknown | unknown | -//! | [`Isaac64Rng`] | ISAAC-64 | ★★☆☆☆ | slow | 4136 bytes| unknown | unknown | -//! -//! It should be noted that the ISAAC generators are only included for -//! historical reasons, they have been with the Rust language since the very -//! beginning. They have good quality output and no attacks are known, but have -//! received little attention from cryptography experts. -//! -//! -//! # Performance -//! -//! First it has to be said most PRNGs are very fast, and will rarely be a -//! performance bottleneck. -//! -//! Performance of basic PRNGs is a bit of a subtle thing. It depends a lot on -//! the CPU architecture (32 vs. 64 bits), inlining, and also on the number of -//! available registers. This often causes the performance to be affected by -//! surrounding code due to inlining and other usage of registers. -//! -//! When choosing a PRNG for performance it is important to benchmark your own -//! application due to interactions between PRNGs and surrounding code and -//! dependence on the CPU architecture as well as the impact of the size of -//! data requested. Because of all this, we do not include performance numbers -//! here but merely a qualitative rating. -//! -//! CSPRNGs are a little different in that they typically generate a block of -//! output in a cache, and pull outputs from the cache. This allows them to have -//! good amortised performance, and reduces or completely removes the influence -//! of surrounding code on the CSPRNG performance. -//! -//! ### Worst-case performance -//! Because CSPRNGs usually produce a block of values into a cache, they have -//! poor worst case performance (in contrast to basic PRNGs, where the -//! performance is usually quite regular). -//! -//! ## State size -//! -//! Simple PRNGs often use very little memory, commonly only a few words, where -//! a *word* is usually either `u32` or `u64`. This is not true for all -//! non-cryptographic PRNGs however, for example the historically popular -//! Mersenne Twister MT19937 algorithm requires 2.5 kB of state. -//! -//! CSPRNGs typically require more memory; since the seed size is recommended -//! to be at least 192 bits and some more may be required for the algorithm, -//! 256 bits would be approximately the minimum secure size. In practice, -//! CSPRNGs tend to use quite a bit more, [`ChaChaRng`] is relatively small with -//! 136 bytes of state. -//! -//! ## Initialization time -//! -//! The time required to initialize new generators varies significantly. Many -//! simple PRNGs and even some cryptographic ones (including [`ChaChaRng`]) -//! only need to copy the seed value and some constants into their state, and -//! thus can be constructed very quickly. In contrast, CSPRNGs with large state -//! require an expensive key-expansion. -//! -//! # Quality -//! -//! Many basic PRNGs are not much more than a couple of bitwise and arithmetic -//! operations. Their simplicity gives good performance, but also means there -//! are small regularities hidden in the generated random number stream. -//! -//! How much do those hidden regularities matter? That is hard to say, and -//! depends on how the RNG gets used. If there happen to be correlations between -//! the random numbers and the algorithm they are used in, the results can be -//! wrong or misleading. -//! -//! A random number generator can be considered good if it gives the correct -//! results in as many applications as possible. The quality of PRNG -//! algorithms can be evaluated to some extend analytically, to determine the -//! cycle length and to rule out some correlations. Then there are empirical -//! test suites designed to test how well a PRNG performs on a wide range of -//! possible uses, the latest and most complete of which are [TestU01] and -//! [PractRand]. -//! -//! CSPRNGs tend to be more complex, and have an explicit requirement to be -//! unpredictable. This implies there must be no obvious correlations between -//! output values. -//! -//! ### Quality stars: -//! PRNGs with 3 stars or more should be good enough for any purpose. -//! 1 or 2 stars may be good enough for typical apps and games, but do not work -//! well with all algorithms. -//! -//! ## Period -//! -//! The *period* or *cycle length* of a PRNG is the number of values that can be -//! generated after which it starts repeating the same random number stream. -//! Many PRNGs have a fixed-size period, but for some only an expected average -//! cycle length can be given, where the exact length depends on the seed. -//! -//! On today's hardware, even a fast RNG with a cycle length of *only* -//! 264 can be used for centuries before cycling. Yet we recommend a -//! period of 2128 or more, which most modern PRNGs satisfy. -//! Alternatively a PRNG with shorter period but support for multiple streams -//! may be chosen. There are two reasons for this, as follows. -//! -//! If we see the entire period of an RNG as one long random number stream, -//! every independently seeded RNG returns a slice of that stream. When multiple -//! RNG are seeded randomly, there is an increasingly large chance to end up -//! with a partially overlapping slice of the stream. -//! -//! If the period of the RNG is 2128, and an application consumes -//! 248 values, it then takes about 232 random -//! initializations to have a chance of 1 in a million to repeat part of an -//! already used stream. This seems good enough for common usage of -//! non-cryptographic generators, hence the recommendation of at least -//! 2128. As an estimate, the chance of any overlap in a period of -//! size `p` with `n` independent seeds and `u` values used per seed is -//! approximately `1 - e^(-u * n^2 / (2 * p))`. -//! -//! Further, it is not recommended to use the full period of an RNG. Many -//! PRNGs have a property called *k-dimensional equidistribution*, meaning that -//! for values of some size (potentially larger than the output size), all -//! possible values are produced the same number of times over the generator's -//! period. This is not a property of true randomness. This is known as the -//! generalized birthday problem, see the [PCG paper] for a good explanation. -//! This results in a noticable bias on output after generating more values -//! than the square root of the period (after 264 values for a -//! period of 2128). -//! -//! -//! # Security -//! -//! ## Predictability -//! -//! From the context of any PRNG, one can ask the question *given some previous -//! output from the PRNG, is it possible to predict the next output value?* -//! This is an important property in any situation where there might be an -//! adversary. -//! -//! Regular PRNGs tend to be predictable, although with varying difficulty. In -//! some cases prediction is trivial, for example plain Xorshift outputs part of -//! its state without mutation, and prediction is as simple as seeding a new -//! Xorshift generator from four `u32` outputs. Other generators, like -//! [PCG](http://www.pcg-random.org/predictability.html) and truncated Xorshift* -//! are harder to predict, but not outside the realm of common mathematics and a -//! desktop PC. -//! -//! The basic security that CSPRNGs must provide is the infeasibility to predict -//! output. This requirement is formalized as the [next-bit test]; this is -//! roughly stated as: given the first *k* bits of a random sequence, the -//! sequence satisfies the next-bit test if there is no algorithm able to -//! predict the next bit using reasonable computing power. -//! -//! A further security that *some* CSPRNGs provide is forward secrecy: -//! in the event that the CSPRNGs state is revealed at some point, it must be -//! infeasible to reconstruct previous states or output. Note that many CSPRNGs -//! *do not* have forward secrecy in their usual formulations. -//! -//! As an outsider it is hard to get a good idea about the security of an -//! algorithm. People in the field of cryptography spend a lot of effort -//! analyzing existing designs, and what was once considered good may now turn -//! out to be weaker. Generally it is best to use algorithms well-analyzed by -//! experts, such as those recommended by NIST or ECRYPT. -//! -//! ## State and seeding -//! -//! It is worth noting that a CSPRNG's security relies absolutely on being -//! seeded with a secure random key. Should the key be known or guessable, all -//! output of the CSPRNG is easy to guess. This implies that the seed should -//! come from a trusted source; usually either the OS or another CSPRNG. Our -//! seeding helper trait, [`FromEntropy`], and the source it uses -//! ([`EntropyRng`]), should be secure. Additionally, [`ThreadRng`] is a CSPRNG, -//! thus it is acceptable to seed from this (although for security applications -//! fresh/external entropy should be preferred). -//! -//! Further, it should be obvious that the internal state of a CSPRNG must be -//! kept secret. With that in mind, our implementations do not provide direct -//! access to most of their internal state, and `Debug` implementations do not -//! print any internal state. This does not fully protect CSPRNG state; code -//! within the same process may read this memory (and we allow cloning and -//! serialisation of CSPRNGs for convenience). Further, a running process may be -//! forked by the operating system, which may leave both processes with a copy -//! of the same generator. -//! -//! ## Not a crypto library -//! -//! It should be emphasised that this is not a cryptography library; although -//! Rand does take some measures to provide secure random numbers, it does not -//! necessarily take all recommended measures. Further, cryptographic processes -//! such as encryption and authentication are complex and must be implemented -//! very carefully to avoid flaws and resist known attacks. It is therefore -//! recommended to use specialized libraries where possible, for example -//! [openssl], [ring] and the [RustCrypto libraries]. -//! -//! -//! # Extra features -//! -//! Some PRNGs may provide extra features, like: -//! -//! - Support for multiple streams, which can help with parallel tasks. -//! - The ability to jump or seek around in the random number stream; -//! with large periood this can be used as an alternative to streams. -//! -//! -//! # Further reading -//! -//! There is quite a lot that can be said about PRNGs. The [PCG paper] is a -//! very approachable explaining more concepts. -//! -//! A good paper about RNG quality is -//! ["Good random number generators are (not so) easy to find"]( -//! http://random.mat.sbg.ac.at/results/peter/A19final.pdf) by P. Hellekalek. -//! -//! -//! [`rngs` module]: ../rngs/index.html -//! [basic PRNGs]: #basic-pseudo-random-number-generators-prngs -//! [CSPRNGs]: #cryptographically-secure-pseudo-random-number-generators-csprngs -//! [`XorShiftRng`]: struct.XorShiftRng.html -//! [`ChaChaRng`]: chacha/struct.ChaChaRng.html -//! [`Hc128Rng`]: hc128/struct.Hc128Rng.html -//! [`IsaacRng`]: isaac/struct.IsaacRng.html -//! [`Isaac64Rng`]: isaac64/struct.Isaac64Rng.html -//! [`ThreadRng`]: ../rngs/struct.ThreadRng.html -//! [`FromEntropy`]: ../trait.FromEntropy.html -//! [`EntropyRng`]: ../rngs/struct.EntropyRng.html -//! [TestU01]: http://simul.iro.umontreal.ca/testu01/tu01.html -//! [PractRand]: http://pracrand.sourceforge.net/ -//! [PCG paper]: http://www.pcg-random.org/pdf/hmc-cs-2014-0905.pdf -//! [openssl]: https://crates.io/crates/openssl -//! [ring]: https://crates.io/crates/ring -//! [RustCrypto libraries]: https://github.com/RustCrypto -//! [next-bit test]: https://en.wikipedia.org/wiki/Next-bit_test - - -pub mod chacha; -pub mod hc128; -pub mod isaac; -pub mod isaac64; -mod xorshift; - -mod isaac_array; - -pub use self::chacha::ChaChaRng; -pub use self::hc128::Hc128Rng; -pub use self::isaac::IsaacRng; -pub use self::isaac64::Isaac64Rng; -pub use self::xorshift::XorShiftRng; diff --git a/third_party/cargo/vendor/rand-0.5.6/src/prng/xorshift.rs b/third_party/cargo/vendor/rand-0.5.6/src/prng/xorshift.rs deleted file mode 100644 index 90871f8..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/prng/xorshift.rs +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Xorshift generators - -use core::num::Wrapping as w; -use core::{fmt, slice}; -use rand_core::{RngCore, SeedableRng, Error, impls, le}; - -/// An Xorshift random number generator. -/// -/// The Xorshift[^1] algorithm is not suitable for cryptographic purposes -/// but is very fast. If you do not know for sure that it fits your -/// requirements, use a more secure one such as `IsaacRng` or `OsRng`. -/// -/// [^1]: Marsaglia, George (July 2003). -/// ["Xorshift RNGs"](https://www.jstatsoft.org/v08/i14/paper). -/// *Journal of Statistical Software*. Vol. 8 (Issue 14). -#[derive(Clone)] -#[cfg_attr(feature="serde1", derive(Serialize,Deserialize))] -pub struct XorShiftRng { - x: w, - y: w, - z: w, - w: w, -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for XorShiftRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "XorShiftRng {{}}") - } -} - -impl XorShiftRng { - /// Creates a new XorShiftRng instance which is not seeded. - /// - /// The initial values of this RNG are constants, so all generators created - /// by this function will yield the same stream of random numbers. It is - /// highly recommended that this is created through `SeedableRng` instead of - /// this function - #[deprecated(since="0.5.0", note="use the FromEntropy or SeedableRng trait")] - pub fn new_unseeded() -> XorShiftRng { - XorShiftRng { - x: w(0x193a6754), - y: w(0xa8a7d469), - z: w(0x97830e05), - w: w(0x113ba7bb), - } - } -} - -impl RngCore for XorShiftRng { - #[inline] - fn next_u32(&mut self) -> u32 { - let x = self.x; - let t = x ^ (x << 11); - self.x = self.y; - self.y = self.z; - self.z = self.w; - let w_ = self.w; - self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8)); - self.w.0 - } - - #[inline] - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_u32(self) - } - - #[inline] - fn fill_bytes(&mut self, dest: &mut [u8]) { - impls::fill_bytes_via_next(self, dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} - -impl SeedableRng for XorShiftRng { - type Seed = [u8; 16]; - - fn from_seed(seed: Self::Seed) -> Self { - let mut seed_u32 = [0u32; 4]; - le::read_u32_into(&seed, &mut seed_u32); - - // Xorshift cannot be seeded with 0 and we cannot return an Error, but - // also do not wish to panic (because a random seed can legitimately be - // 0); our only option is therefore to use a preset value. - if seed_u32.iter().all(|&x| x == 0) { - seed_u32 = [0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED, 0xBAD_5EED]; - } - - XorShiftRng { - x: w(seed_u32[0]), - y: w(seed_u32[1]), - z: w(seed_u32[2]), - w: w(seed_u32[3]), - } - } - - fn from_rng(mut rng: R) -> Result { - let mut seed_u32 = [0u32; 4]; - loop { - unsafe { - let ptr = seed_u32.as_mut_ptr() as *mut u8; - - let slice = slice::from_raw_parts_mut(ptr, 4 * 4); - rng.try_fill_bytes(slice)?; - } - if !seed_u32.iter().all(|&x| x == 0) { break; } - } - - Ok(XorShiftRng { - x: w(seed_u32[0]), - y: w(seed_u32[1]), - z: w(seed_u32[2]), - w: w(seed_u32[3]), - }) - } -} - -#[cfg(test)] -mod tests { - use {RngCore, SeedableRng}; - use super::XorShiftRng; - - #[test] - fn test_xorshift_construction() { - // Test that various construction techniques produce a working RNG. - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng1 = XorShiftRng::from_seed(seed); - assert_eq!(rng1.next_u64(), 4325440999699518727); - - let _rng2 = XorShiftRng::from_rng(rng1).unwrap(); - // Note: we cannot test the state of _rng2 because from_rng does not - // fix Endianness. This is allowed in the trait specification. - } - - #[test] - fn test_xorshift_true_values() { - let seed = [16,15,14,13, 12,11,10,9, 8,7,6,5, 4,3,2,1]; - let mut rng = XorShiftRng::from_seed(seed); - - let mut results = [0u32; 9]; - for i in results.iter_mut() { *i = rng.next_u32(); } - let expected: [u32; 9] = [ - 2081028795, 620940381, 269070770, 16943764, 854422573, 29242889, - 1550291885, 1227154591, 271695242]; - assert_eq!(results, expected); - - let mut results = [0u64; 9]; - for i in results.iter_mut() { *i = rng.next_u64(); } - let expected: [u64; 9] = [ - 9247529084182843387, 8321512596129439293, 14104136531997710878, - 6848554330849612046, 343577296533772213, 17828467390962600268, - 9847333257685787782, 7717352744383350108, 1133407547287910111]; - assert_eq!(results, expected); - - let mut results = [0u8; 32]; - rng.fill_bytes(&mut results); - let expected = [102, 57, 212, 16, 233, 130, 49, 183, - 158, 187, 44, 203, 63, 149, 45, 17, - 117, 129, 131, 160, 70, 121, 158, 155, - 224, 209, 192, 53, 10, 62, 57, 72]; - assert_eq!(results, expected); - } - - #[test] - fn test_xorshift_zero_seed() { - // Xorshift does not work with an all zero seed. - // Assert it does not panic. - let seed = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng = XorShiftRng::from_seed(seed); - let a = rng.next_u64(); - let b = rng.next_u64(); - assert!(a != 0); - assert!(b != a); - } - - #[test] - fn test_xorshift_clone() { - let seed = [1,2,3,4, 5,5,7,8, 8,7,6,5, 4,3,2,1]; - let mut rng1 = XorShiftRng::from_seed(seed); - let mut rng2 = rng1.clone(); - for _ in 0..16 { - assert_eq!(rng1.next_u64(), rng2.next_u64()); - } - } - - #[cfg(all(feature="serde1", feature="std"))] - #[test] - fn test_xorshift_serde() { - use bincode; - use std::io::{BufWriter, BufReader}; - - let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; - let mut rng = XorShiftRng::from_seed(seed); - - let buf: Vec = Vec::new(); - let mut buf = BufWriter::new(buf); - bincode::serialize_into(&mut buf, &rng).expect("Could not serialize"); - - let buf = buf.into_inner().unwrap(); - let mut read = BufReader::new(&buf[..]); - let mut deserialized: XorShiftRng = bincode::deserialize_from(&mut read).expect("Could not deserialize"); - - assert_eq!(rng.x, deserialized.x); - assert_eq!(rng.y, deserialized.y); - assert_eq!(rng.z, deserialized.z); - assert_eq!(rng.w, deserialized.w); - - for _ in 0..16 { - assert_eq!(rng.next_u64(), deserialized.next_u64()); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/mod.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/mod.rs deleted file mode 100644 index 9a3851a..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Wrappers / adapters forming RNGs - -#[cfg(feature="std")] #[doc(hidden)] pub mod read; -mod reseeding; - -#[cfg(feature="std")] pub use self::read::ReadRng; -pub use self::reseeding::ReseedingRng; diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/read.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/read.rs deleted file mode 100644 index de75f97..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/read.rs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around any Read to treat it as an RNG. - -use std::io::Read; - -use rand_core::{RngCore, Error, ErrorKind, impls}; - - -/// An RNG that reads random bytes straight from any type supporting -/// `std::io::Read`, for example files. -/// -/// This will work best with an infinite reader, but that is not required. -/// -/// This can be used with `/dev/urandom` on Unix but it is recommended to use -/// [`OsRng`] instead. -/// -/// # Panics -/// -/// `ReadRng` uses `std::io::read_exact`, which retries on interrupts. All other -/// errors from the underlying reader, including when it does not have enough -/// data, will only be reported through [`try_fill_bytes`]. The other -/// [`RngCore`] methods will panic in case of an error. -/// -/// # Example -/// -/// ``` -/// use rand::{read, Rng}; -/// -/// let data = vec![1, 2, 3, 4, 5, 6, 7, 8]; -/// let mut rng = read::ReadRng::new(&data[..]); -/// println!("{:x}", rng.gen::()); -/// ``` -/// -/// [`OsRng`]: ../struct.OsRng.html -/// [`RngCore`]: ../../trait.RngCore.html -/// [`try_fill_bytes`]: ../../trait.RngCore.html#method.tymethod.try_fill_bytes -#[derive(Debug)] -pub struct ReadRng { - reader: R -} - -impl ReadRng { - /// Create a new `ReadRng` from a `Read`. - pub fn new(r: R) -> ReadRng { - ReadRng { - reader: r - } - } -} - -impl RngCore for ReadRng { - fn next_u32(&mut self) -> u32 { - impls::next_u32_via_fill(self) - } - - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_fill(self) - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.try_fill_bytes(dest).unwrap_or_else(|err| - panic!("reading random bytes from Read implementation failed; error: {}", err)); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - if dest.len() == 0 { return Ok(()); } - // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. - self.reader.read_exact(dest).map_err(|err| { - match err.kind() { - ::std::io::ErrorKind::UnexpectedEof => Error::with_cause( - ErrorKind::Unavailable, - "not enough bytes available, reached end of source", err), - _ => Error::with_cause(ErrorKind::Unavailable, - "error reading from Read source", err) - } - }) - } -} - -#[cfg(test)] -mod test { - use super::ReadRng; - use {RngCore, ErrorKind}; - - #[test] - fn test_reader_rng_u64() { - // transmute from the target to avoid endianness concerns. - let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, - 0 , 0, 0, 0, 0, 0, 0, 2, - 0, 0, 0, 0, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u64(), 1_u64.to_be()); - assert_eq!(rng.next_u64(), 2_u64.to_be()); - assert_eq!(rng.next_u64(), 3_u64.to_be()); - } - - #[test] - fn test_reader_rng_u32() { - let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]; - let mut rng = ReadRng::new(&v[..]); - - assert_eq!(rng.next_u32(), 1_u32.to_be()); - assert_eq!(rng.next_u32(), 2_u32.to_be()); - assert_eq!(rng.next_u32(), 3_u32.to_be()); - } - - #[test] - fn test_reader_rng_fill_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 8]; - - let mut rng = ReadRng::new(&v[..]); - rng.fill_bytes(&mut w); - - assert!(v == w); - } - - #[test] - fn test_reader_rng_insufficient_bytes() { - let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; - let mut w = [0u8; 9]; - - let mut rng = ReadRng::new(&v[..]); - - assert!(rng.try_fill_bytes(&mut w).err().unwrap().kind == ErrorKind::Unavailable); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/reseeding.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/reseeding.rs deleted file mode 100644 index 7ec8de5..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/adapter/reseeding.rs +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A wrapper around another PRNG that reseeds it after it -//! generates a certain number of random bytes. - -use core::mem::size_of; - -use rand_core::{RngCore, CryptoRng, SeedableRng, Error, ErrorKind}; -use rand_core::block::{BlockRngCore, BlockRng}; - -/// A wrapper around any PRNG which reseeds the underlying PRNG after it has -/// generated a certain number of random bytes. -/// -/// When the RNG gets cloned, the clone is reseeded on first use. -/// -/// Reseeding is never strictly *necessary*. Cryptographic PRNGs don't have a -/// limited number of bytes they can output, or at least not a limit reachable -/// in any practical way. There is no such thing as 'running out of entropy'. -/// -/// Some small non-cryptographic PRNGs can have very small periods, for -/// example less than 264. Would reseeding help to ensure that you do -/// not wrap around at the end of the period? A period of 264 still -/// takes several centuries of CPU-years on current hardware. Reseeding will -/// actually make things worse, because the reseeded PRNG will just continue -/// somewhere else *in the same period*, with a high chance of overlapping with -/// previously used parts of it. -/// -/// # When should you use `ReseedingRng`? -/// -/// - Reseeding can be seen as some form of 'security in depth'. Even if in the -/// future a cryptographic weakness is found in the CSPRNG being used, -/// occasionally reseeding should make exploiting it much more difficult or -/// even impossible. -/// - It can be used as a poor man's cryptography (not recommended, just use a -/// good CSPRNG). Previous implementations of `thread_rng` for example used -/// `ReseedingRng` with the ISAAC RNG. That algorithm, although apparently -/// strong and with no known attack, does not come with any proof of security -/// and does not meet the current standards for a cryptographically secure -/// PRNG. By reseeding it frequently (every 32 kiB) it seems safe to assume -/// there is no attack that can operate on the tiny window between reseeds. -/// -/// # Error handling -/// -/// Although extremely unlikely, reseeding the wrapped PRNG can fail. -/// `ReseedingRng` will never panic but try to handle the error intelligently -/// through some combination of retrying and delaying reseeding until later. -/// If handling the source error fails `ReseedingRng` will continue generating -/// data from the wrapped PRNG without reseeding. -#[derive(Debug)] -pub struct ReseedingRng(BlockRng>) -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore; - -impl ReseedingRng -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingRng` with the given parameters. - /// - /// # Arguments - /// - /// * `rng`: the random number generator to use. - /// * `threshold`: the number of generated bytes after which to reseed the RNG. - /// * `reseeder`: the RNG to use for reseeding. - pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - ReseedingRng(BlockRng::new(ReseedingCore::new(rng, threshold, reseeder))) - } - - /// Reseed the internal PRNG. - pub fn reseed(&mut self) -> Result<(), Error> { - self.0.core.reseed() - } -} - -// TODO: this should be implemented for any type where the inner type -// implements RngCore, but we can't specify that because ReseedingCore is private -impl RngCore for ReseedingRng -where R: BlockRngCore + SeedableRng, - ::Results: AsRef<[u32]> + AsMut<[u32]> -{ - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl Clone for ReseedingRng -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingRng { - // Recreating `BlockRng` seems easier than cloning it and resetting - // the index. - ReseedingRng(BlockRng::new(self.0.core.clone())) - } -} - -impl CryptoRng for ReseedingRng -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - -#[derive(Debug)] -struct ReseedingCore { - inner: R, - reseeder: Rsdr, - threshold: i64, - bytes_until_reseed: i64, -} - -impl BlockRngCore for ReseedingCore -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - type Item = ::Item; - type Results = ::Results; - - fn generate(&mut self, results: &mut Self::Results) { - if self.bytes_until_reseed <= 0 { - // We get better performance by not calling only `auto_reseed` here - // and continuing with the rest of the function, but by directly - // returning from a non-inlined function. - return self.reseed_and_generate(results); - } - let num_bytes = results.as_ref().len() * size_of::(); - self.bytes_until_reseed -= num_bytes as i64; - self.inner.generate(results); - } -} - -impl ReseedingCore -where R: BlockRngCore + SeedableRng, - Rsdr: RngCore -{ - /// Create a new `ReseedingCore` with the given parameters. - /// - /// # Arguments - /// - /// * `rng`: the random number generator to use. - /// * `threshold`: the number of generated bytes after which to reseed the RNG. - /// * `reseeder`: the RNG to use for reseeding. - pub fn new(rng: R, threshold: u64, reseeder: Rsdr) -> Self { - assert!(threshold <= ::core::i64::MAX as u64); - ReseedingCore { - inner: rng, - reseeder, - threshold: threshold as i64, - bytes_until_reseed: threshold as i64, - } - } - - /// Reseed the internal PRNG. - fn reseed(&mut self) -> Result<(), Error> { - R::from_rng(&mut self.reseeder).map(|result| { - self.bytes_until_reseed = self.threshold; - self.inner = result - }) - } - - #[inline(never)] - fn reseed_and_generate(&mut self, - results: &mut ::Results) - { - trace!("Reseeding RNG after {} generated bytes", - self.threshold - self.bytes_until_reseed); - let threshold = if let Err(e) = self.reseed() { - let delay = match e.kind { - ErrorKind::Transient => 0, - kind @ _ if kind.should_retry() => self.threshold >> 8, - _ => self.threshold, - }; - warn!("Reseeding RNG delayed reseeding by {} bytes due to \ - error from source: {}", delay, e); - delay - } else { - self.threshold - }; - - let num_bytes = results.as_ref().len() * size_of::<::Item>(); - self.bytes_until_reseed = threshold - num_bytes as i64; - self.inner.generate(results); - } -} - -impl Clone for ReseedingCore -where R: BlockRngCore + SeedableRng + Clone, - Rsdr: RngCore + Clone -{ - fn clone(&self) -> ReseedingCore { - ReseedingCore { - inner: self.inner.clone(), - reseeder: self.reseeder.clone(), - threshold: self.threshold, - bytes_until_reseed: 0, // reseed clone on first use - } - } -} - -impl CryptoRng for ReseedingCore -where R: BlockRngCore + SeedableRng + CryptoRng, - Rsdr: RngCore + CryptoRng {} - -#[cfg(test)] -mod test { - use {Rng, SeedableRng}; - use prng::chacha::ChaChaCore; - use rngs::mock::StepRng; - use super::ReseedingRng; - - #[test] - fn test_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = ChaChaCore::from_rng(&mut zero).unwrap(); - let mut reseeding = ReseedingRng::new(rng, 32*4, zero); - - // Currently we only support for arrays up to length 32. - // TODO: cannot generate seq via Rng::gen because it uses different alg - let mut buf = [0u32; 32]; // Needs to be a multiple of the RNGs result - // size to test exactly. - reseeding.fill(&mut buf); - let seq = buf; - for _ in 0..10 { - reseeding.fill(&mut buf); - assert_eq!(buf, seq); - } - } - - #[test] - fn test_clone_reseeding() { - let mut zero = StepRng::new(0, 0); - let rng = ChaChaCore::from_rng(&mut zero).unwrap(); - let mut rng1 = ReseedingRng::new(rng, 32*4, zero); - - let first: u32 = rng1.gen(); - for _ in 0..10 { let _ = rng1.gen::(); } - - let mut rng2 = rng1.clone(); - assert_eq!(first, rng2.gen::()); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/entropy.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/entropy.rs deleted file mode 100644 index b8f4be7..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/entropy.rs +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Entropy generator, or wrapper around external generators - -use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; -#[allow(unused)] -use rngs; - -/// An interface returning random data from external source(s), provided -/// specifically for securely seeding algorithmic generators (PRNGs). -/// -/// Where possible, `EntropyRng` retrieves random data from the operating -/// system's interface for random numbers ([`OsRng`]); if that fails it will -/// fall back to the [`JitterRng`] entropy collector. In the latter case it will -/// still try to use [`OsRng`] on the next usage. -/// -/// If no secure source of entropy is available `EntropyRng` will panic on use; -/// i.e. it should never output predictable data. -/// -/// This is either a little slow ([`OsRng`] requires a system call) or extremely -/// slow ([`JitterRng`] must use significant CPU time to generate sufficient -/// jitter); for better performance it is common to seed a local PRNG from -/// external entropy then primarily use the local PRNG ([`thread_rng`] is -/// provided as a convenient, local, automatically-seeded CSPRNG). -/// -/// # Panics -/// -/// On most systems, like Windows, Linux, macOS and *BSD on common hardware, it -/// is highly unlikely for both [`OsRng`] and [`JitterRng`] to fail. But on -/// combinations like webassembly without Emscripten or stdweb both sources are -/// unavailable. If both sources fail, only [`try_fill_bytes`] is able to -/// report the error, and only the one from `OsRng`. The other [`RngCore`] -/// methods will panic in case of an error. -/// -/// [`OsRng`]: struct.OsRng.html -/// [`JitterRng`]: jitter/struct.JitterRng.html -/// [`thread_rng`]: ../fn.thread_rng.html -/// [`RngCore`]: ../trait.RngCore.html -/// [`try_fill_bytes`]: ../trait.RngCore.html#method.tymethod.try_fill_bytes -#[derive(Debug)] -pub struct EntropyRng { - source: Source, -} - -#[derive(Debug)] -enum Source { - Os(Os), - Custom(Custom), - Jitter(Jitter), - None, -} - -impl EntropyRng { - /// Create a new `EntropyRng`. - /// - /// This method will do no system calls or other initialization routines, - /// those are done on first use. This is done to make `new` infallible, - /// and `try_fill_bytes` the only place to report errors. - pub fn new() -> Self { - EntropyRng { source: Source::None } - } -} - -impl Default for EntropyRng { - fn default() -> Self { - EntropyRng::new() - } -} - -impl RngCore for EntropyRng { - fn next_u32(&mut self) -> u32 { - impls::next_u32_via_fill(self) - } - - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_fill(self) - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.try_fill_bytes(dest).unwrap_or_else(|err| - panic!("all entropy sources failed; first error: {}", err)) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let mut reported_error = None; - - if let Source::Os(ref mut os_rng) = self.source { - match os_rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: OsRng failed \ - [trying other entropy sources]: {}", err); - reported_error = Some(err); - }, - } - } else if Os::is_supported() { - match Os::new_and_fill(dest) { - Ok(os_rng) => { - debug!("EntropyRng: using OsRng"); - self.source = Source::Os(os_rng); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Source::Custom(ref mut rng) = self.source { - match rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: custom entropy source failed \ - [trying other entropy sources]: {}", err); - reported_error = Some(err); - }, - } - } else if Custom::is_supported() { - match Custom::new_and_fill(dest) { - Ok(custom) => { - debug!("EntropyRng: using custom entropy source"); - self.source = Source::Custom(custom); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Source::Jitter(ref mut jitter_rng) = self.source { - match jitter_rng.fill(dest) { - Ok(()) => return Ok(()), - Err(err) => { - warn!("EntropyRng: JitterRng failed: {}", err); - reported_error = Some(err); - }, - } - } else if Jitter::is_supported() { - match Jitter::new_and_fill(dest) { - Ok(jitter_rng) => { - debug!("EntropyRng: using JitterRng"); - self.source = Source::Jitter(jitter_rng); - return Ok(()); - }, - Err(err) => { reported_error = reported_error.or(Some(err)) }, - } - } - - if let Some(err) = reported_error { - Err(Error::with_cause(ErrorKind::Unavailable, - "All entropy sources failed", - err)) - } else { - Err(Error::new(ErrorKind::Unavailable, - "No entropy sources available")) - } - } -} - -impl CryptoRng for EntropyRng {} - - - -trait EntropySource { - fn new_and_fill(dest: &mut [u8]) -> Result - where Self: Sized; - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error>; - - fn is_supported() -> bool { true } -} - -#[allow(unused)] -#[derive(Clone, Debug)] -struct NoSource; - -#[allow(unused)] -impl EntropySource for NoSource { - fn new_and_fill(dest: &mut [u8]) -> Result { - Err(Error::new(ErrorKind::Unavailable, "Source not supported")) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - unreachable!() - } - - fn is_supported() -> bool { false } -} - - -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -#[derive(Clone, Debug)] -pub struct Os(rngs::OsRng); - -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -impl EntropySource for Os { - fn new_and_fill(dest: &mut [u8]) -> Result { - let mut rng = rngs::OsRng::new()?; - rng.try_fill_bytes(dest)?; - Ok(Os(rng)) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(not(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -))))] -type Os = NoSource; - - -type Custom = NoSource; - - -#[cfg(not(target_arch = "wasm32"))] -#[derive(Clone, Debug)] -pub struct Jitter(rngs::JitterRng); - -#[cfg(not(target_arch = "wasm32"))] -impl EntropySource for Jitter { - fn new_and_fill(dest: &mut [u8]) -> Result { - let mut rng = rngs::JitterRng::new()?; - rng.try_fill_bytes(dest)?; - Ok(Jitter(rng)) - } - - fn fill(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -#[cfg(target_arch = "wasm32")] -type Jitter = NoSource; - - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_entropy() { - let mut rng = EntropyRng::new(); - let n = (rng.next_u32() ^ rng.next_u32()).count_ones(); - assert!(n >= 2); // p(failure) approx 1e-7 - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/jitter.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/jitter.rs deleted file mode 100644 index 311682c..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/jitter.rs +++ /dev/null @@ -1,887 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -// -// Based on jitterentropy-library, http://www.chronox.de/jent.html. -// Copyright Stephan Mueller , 2014 - 2017. -// -// With permission from Stephan Mueller to relicense the Rust translation under -// the MIT license. - -//! Non-physical true random number generator based on timing jitter. - -// Note: the C implementation of `Jitterentropy` relies on being compiled -// without optimizations. This implementation goes through lengths to make the -// compiler not optimize out code which does influence timing jitter, but is -// technically dead code. - -use rand_core::{RngCore, CryptoRng, Error, ErrorKind, impls}; - -use core::{fmt, mem, ptr}; -#[cfg(all(feature="std", not(target_arch = "wasm32")))] -use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - -const MEMORY_BLOCKS: usize = 64; -const MEMORY_BLOCKSIZE: usize = 32; -const MEMORY_SIZE: usize = MEMORY_BLOCKS * MEMORY_BLOCKSIZE; - -/// A true random number generator based on jitter in the CPU execution time, -/// and jitter in memory access time. -/// -/// This is a true random number generator, as opposed to pseudo-random -/// generators. Random numbers generated by `JitterRng` can be seen as fresh -/// entropy. A consequence is that is orders of magnitude slower than [`OsRng`] -/// and PRNGs (about 103..106 slower). -/// -/// There are very few situations where using this RNG is appropriate. Only very -/// few applications require true entropy. A normal PRNG can be statistically -/// indistinguishable, and a cryptographic PRNG should also be as impossible to -/// predict. -/// -/// Use of `JitterRng` is recommended for initializing cryptographic PRNGs when -/// [`OsRng`] is not available. -/// -/// `JitterRng` can be used without the standard library, but not conveniently, -/// you must provide a high-precision timer and carefully have to follow the -/// instructions of [`new_with_timer`]. -/// -/// This implementation is based on -/// [Jitterentropy](http://www.chronox.de/jent.html) version 2.1.0. -/// -/// Note: There is no accurate timer available on Wasm platforms, to help -/// prevent fingerprinting or timing side-channel attacks. Therefore -/// [`JitterRng::new()`] is not available on Wasm. -/// -/// # Quality testing -/// -/// [`JitterRng::new()`] has build-in, but limited, quality testing, however -/// before using `JitterRng` on untested hardware, or after changes that could -/// effect how the code is optimized (such as a new LLVM version), it is -/// recommend to run the much more stringent -/// [NIST SP 800-90B Entropy Estimation Suite]( -/// https://github.com/usnistgov/SP800-90B_EntropyAssessment). -/// -/// Use the following code using [`timer_stats`] to collect the data: -/// -/// ```no_run -/// use rand::jitter::JitterRng; -/// # -/// # use std::error::Error; -/// # use std::fs::File; -/// # use std::io::Write; -/// # -/// # fn try_main() -> Result<(), Box> { -/// let mut rng = JitterRng::new()?; -/// -/// // 1_000_000 results are required for the -/// // NIST SP 800-90B Entropy Estimation Suite -/// const ROUNDS: usize = 1_000_000; -/// let mut deltas_variable: Vec = Vec::with_capacity(ROUNDS); -/// let mut deltas_minimal: Vec = Vec::with_capacity(ROUNDS); -/// -/// for _ in 0..ROUNDS { -/// deltas_variable.push(rng.timer_stats(true) as u8); -/// deltas_minimal.push(rng.timer_stats(false) as u8); -/// } -/// -/// // Write out after the statistics collection loop, to not disturb the -/// // test results. -/// File::create("jitter_rng_var.bin")?.write(&deltas_variable)?; -/// File::create("jitter_rng_min.bin")?.write(&deltas_minimal)?; -/// # -/// # Ok(()) -/// # } -/// # -/// # fn main() { -/// # try_main().unwrap(); -/// # } -/// ``` -/// -/// This will produce two files: `jitter_rng_var.bin` and `jitter_rng_min.bin`. -/// Run the Entropy Estimation Suite in three configurations, as outlined below. -/// Every run has two steps. One step to produce an estimation, another to -/// validate the estimation. -/// -/// 1. Estimate the expected amount of entropy that is at least available with -/// each round of the entropy collector. This number should be greater than -/// the amount estimated with `64 / test_timer()`. -/// ```sh -/// python noniid_main.py -v jitter_rng_var.bin 8 -/// restart.py -v jitter_rng_var.bin 8 -/// ``` -/// 2. Estimate the expected amount of entropy that is available in the last 4 -/// bits of the timer delta after running noice sources. Note that a value of -/// `3.70` is the minimum estimated entropy for true randomness. -/// ```sh -/// python noniid_main.py -v -u 4 jitter_rng_var.bin 4 -/// restart.py -v -u 4 jitter_rng_var.bin 4 -/// ``` -/// 3. Estimate the expected amount of entropy that is available to the entropy -/// collector if both noice sources only run their minimal number of times. -/// This measures the absolute worst-case, and gives a lower bound for the -/// available entropy. -/// ```sh -/// python noniid_main.py -v -u 4 jitter_rng_min.bin 4 -/// restart.py -v -u 4 jitter_rng_min.bin 4 -/// ``` -/// -/// [`OsRng`]: struct.OsRng.html -/// [`JitterRng::new()`]: struct.JitterRng.html#method.new -/// [`new_with_timer`]: struct.JitterRng.html#method.new_with_timer -/// [`timer_stats`]: struct.JitterRng.html#method.timer_stats -pub struct JitterRng { - data: u64, // Actual random number - // Number of rounds to run the entropy collector per 64 bits - rounds: u8, - // Timer used by `measure_jitter` - timer: fn() -> u64, - // Memory for the Memory Access noise source - mem_prev_index: u16, - // Make `next_u32` not waste 32 bits - data_half_used: bool, -} - -// Note: `JitterRng` maintains a small 64-bit entropy pool. With every -// `generate` 64 new bits should be integrated in the pool. If a round of -// `generate` were to collect less than the expected 64 bit, then the returned -// value, and the new state of the entropy pool, would be in some way related to -// the initial state. It is therefore better if the initial state of the entropy -// pool is different on each call to `generate`. This has a few implications: -// - `generate` should be called once before using `JitterRng` to produce the -// first usable value (this is done by default in `new`); -// - We do not zero the entropy pool after generating a result. The reference -// implementation also does not support zeroing, but recommends generating a -// new value without using it if you want to protect a previously generated -// 'secret' value from someone inspecting the memory; -// - Implementing `Clone` seems acceptable, as it would not cause the systematic -// bias a constant might cause. Only instead of one value that could be -// potentially related to the same initial state, there are now two. - -// Entropy collector state. -// These values are not necessary to preserve across runs. -struct EcState { - // Previous time stamp to determine the timer delta - prev_time: u64, - // Deltas used for the stuck test - last_delta: i32, - last_delta2: i32, - // Memory for the Memory Access noise source - mem: [u8; MEMORY_SIZE], -} - -impl EcState { - // Stuck test by checking the: - // - 1st derivation of the jitter measurement (time delta) - // - 2nd derivation of the jitter measurement (delta of time deltas) - // - 3rd derivation of the jitter measurement (delta of delta of time - // deltas) - // - // All values must always be non-zero. - // This test is a heuristic to see whether the last measurement holds - // entropy. - fn stuck(&mut self, current_delta: i32) -> bool { - let delta2 = self.last_delta - current_delta; - let delta3 = delta2 - self.last_delta2; - - self.last_delta = current_delta; - self.last_delta2 = delta2; - - current_delta == 0 || delta2 == 0 || delta3 == 0 - } -} - -// Custom Debug implementation that does not expose the internal state -impl fmt::Debug for JitterRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "JitterRng {{}}") - } -} - -impl Clone for JitterRng { - fn clone(&self) -> JitterRng { - JitterRng { - data: self.data, - rounds: self.rounds, - timer: self.timer, - mem_prev_index: self.mem_prev_index, - // The 32 bits that may still be unused from the previous round are - // for the original to use, not for the clone. - data_half_used: false, - } - } -} - -/// An error that can occur when [`JitterRng::test_timer`] fails. -/// -/// [`JitterRng::test_timer`]: struct.JitterRng.html#method.test_timer -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TimerError { - /// No timer available. - NoTimer, - /// Timer too coarse to use as an entropy source. - CoarseTimer, - /// Timer is not monotonically increasing. - NotMonotonic, - /// Variations of deltas of time too small. - TinyVariantions, - /// Too many stuck results (indicating no added entropy). - TooManyStuck, - #[doc(hidden)] - __Nonexhaustive, -} - -impl TimerError { - fn description(&self) -> &'static str { - match *self { - TimerError::NoTimer => "no timer available", - TimerError::CoarseTimer => "coarse timer", - TimerError::NotMonotonic => "timer not monotonic", - TimerError::TinyVariantions => "time delta variations too small", - TimerError::TooManyStuck => "too many stuck results", - TimerError::__Nonexhaustive => unreachable!(), - } - } -} - -impl fmt::Display for TimerError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.description()) - } -} - -#[cfg(feature="std")] -impl ::std::error::Error for TimerError { - fn description(&self) -> &str { - self.description() - } -} - -impl From for Error { - fn from(err: TimerError) -> Error { - // Timer check is already quite permissive of failures so we don't - // expect false-positive failures, i.e. any error is irrecoverable. - Error::with_cause(ErrorKind::Unavailable, - "timer jitter failed basic quality tests", err) - } -} - -// Initialise to zero; must be positive -#[cfg(all(feature="std", not(target_arch = "wasm32")))] -static JITTER_ROUNDS: AtomicUsize = ATOMIC_USIZE_INIT; - -impl JitterRng { - /// Create a new `JitterRng`. Makes use of `std::time` for a timer, or a - /// platform-specific function with higher accuracy if necessary and - /// available. - /// - /// During initialization CPU execution timing jitter is measured a few - /// hundred times. If this does not pass basic quality tests, an error is - /// returned. The test result is cached to make subsequent calls faster. - #[cfg(all(feature="std", not(target_arch = "wasm32")))] - pub fn new() -> Result { - let mut state = JitterRng::new_with_timer(platform::get_nstime); - let mut rounds = JITTER_ROUNDS.load(Ordering::Relaxed) as u8; - if rounds == 0 { - // No result yet: run test. - // This allows the timer test to run multiple times; we don't care. - rounds = state.test_timer()?; - JITTER_ROUNDS.store(rounds as usize, Ordering::Relaxed); - info!("JitterRng: using {} rounds per u64 output", rounds); - } - state.set_rounds(rounds); - - // Fill `data` with a non-zero value. - state.gen_entropy(); - Ok(state) - } - - /// Create a new `JitterRng`. - /// A custom timer can be supplied, making it possible to use `JitterRng` in - /// `no_std` environments. - /// - /// The timer must have nanosecond precision. - /// - /// This method is more low-level than `new()`. It is the responsibility of - /// the caller to run [`test_timer`] before using any numbers generated with - /// `JitterRng`, and optionally call [`set_rounds`]. Also it is important to - /// consume at least one `u64` before using the first result to initialize - /// the entropy collection pool. - /// - /// # Example - /// - /// ``` - /// # use rand::{Rng, Error}; - /// use rand::jitter::JitterRng; - /// - /// # fn try_inner() -> Result<(), Error> { - /// fn get_nstime() -> u64 { - /// use std::time::{SystemTime, UNIX_EPOCH}; - /// - /// let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - /// // The correct way to calculate the current time is - /// // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - /// // But this is faster, and the difference in terms of entropy is - /// // negligible (log2(10^9) == 29.9). - /// dur.as_secs() << 30 | dur.subsec_nanos() as u64 - /// } - /// - /// let mut rng = JitterRng::new_with_timer(get_nstime); - /// let rounds = rng.test_timer()?; - /// rng.set_rounds(rounds); // optional - /// let _ = rng.gen::(); - /// - /// // Ready for use - /// let v: u64 = rng.gen(); - /// # Ok(()) - /// # } - /// - /// # let _ = try_inner(); - /// ``` - /// - /// [`test_timer`]: struct.JitterRng.html#method.test_timer - /// [`set_rounds`]: struct.JitterRng.html#method.set_rounds - pub fn new_with_timer(timer: fn() -> u64) -> JitterRng { - JitterRng { - data: 0, - rounds: 64, - timer, - mem_prev_index: 0, - data_half_used: false, - } - } - - /// Configures how many rounds are used to generate each 64-bit value. - /// This must be greater than zero, and has a big impact on performance - /// and output quality. - /// - /// [`new_with_timer`] conservatively uses 64 rounds, but often less rounds - /// can be used. The `test_timer()` function returns the minimum number of - /// rounds required for full strength (platform dependent), so one may use - /// `rng.set_rounds(rng.test_timer()?);` or cache the value. - /// - /// [`new_with_timer`]: struct.JitterRng.html#method.new_with_timer - pub fn set_rounds(&mut self, rounds: u8) { - assert!(rounds > 0); - self.rounds = rounds; - } - - // Calculate a random loop count used for the next round of an entropy - // collection, based on bits from a fresh value from the timer. - // - // The timer is folded to produce a number that contains at most `n_bits` - // bits. - // - // Note: A constant should be added to the resulting random loop count to - // prevent loops that run 0 times. - #[inline(never)] - fn random_loop_cnt(&mut self, n_bits: u32) -> u32 { - let mut rounds = 0; - - let mut time = (self.timer)(); - // Mix with the current state of the random number balance the random - // loop counter a bit more. - time ^= self.data; - - // We fold the time value as much as possible to ensure that as many - // bits of the time stamp are included as possible. - let folds = (64 + n_bits - 1) / n_bits; - let mask = (1 << n_bits) - 1; - for _ in 0..folds { - rounds ^= time & mask; - time >>= n_bits; - } - - rounds as u32 - } - - // CPU jitter noise source - // Noise source based on the CPU execution time jitter - // - // This function injects the individual bits of the time value into the - // entropy pool using an LFSR. - // - // The code is deliberately inefficient with respect to the bit shifting. - // This function not only acts as folding operation, but this function's - // execution is used to measure the CPU execution time jitter. Any change to - // the loop in this function implies that careful retesting must be done. - #[inline(never)] - fn lfsr_time(&mut self, time: u64, var_rounds: bool) { - fn lfsr(mut data: u64, time: u64) -> u64{ - for i in 1..65 { - let mut tmp = time << (64 - i); - tmp >>= 64 - 1; - - // Fibonacci LSFR with polynomial of - // x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is - // primitive according to - // http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf - // (the shift values are the polynomial values minus one - // due to counting bits from 0 to 63). As the current - // position is always the LSB, the polynomial only needs - // to shift data in from the left without wrap. - data ^= tmp; - data ^= (data >> 63) & 1; - data ^= (data >> 60) & 1; - data ^= (data >> 55) & 1; - data ^= (data >> 30) & 1; - data ^= (data >> 27) & 1; - data ^= (data >> 22) & 1; - data = data.rotate_left(1); - } - data - } - - // Note: in the reference implementation only the last round effects - // `self.data`, all the other results are ignored. To make sure the - // other rounds are not optimised out, we first run all but the last - // round on a throw-away value instead of the real `self.data`. - let mut lfsr_loop_cnt = 0; - if var_rounds { lfsr_loop_cnt = self.random_loop_cnt(4) }; - - let mut throw_away: u64 = 0; - for _ in 0..lfsr_loop_cnt { - throw_away = lfsr(throw_away, time); - } - black_box(throw_away); - - self.data = lfsr(self.data, time); - } - - // Memory Access noise source - // This is a noise source based on variations in memory access times - // - // This function performs memory accesses which will add to the timing - // variations due to an unknown amount of CPU wait states that need to be - // added when accessing memory. The memory size should be larger than the L1 - // caches as outlined in the documentation and the associated testing. - // - // The L1 cache has a very high bandwidth, albeit its access rate is usually - // slower than accessing CPU registers. Therefore, L1 accesses only add - // minimal variations as the CPU has hardly to wait. Starting with L2, - // significant variations are added because L2 typically does not belong to - // the CPU any more and therefore a wider range of CPU wait states is - // necessary for accesses. L3 and real memory accesses have even a wider - // range of wait states. However, to reliably access either L3 or memory, - // the `self.mem` memory must be quite large which is usually not desirable. - #[inline(never)] - fn memaccess(&mut self, mem: &mut [u8; MEMORY_SIZE], var_rounds: bool) { - let mut acc_loop_cnt = 128; - if var_rounds { acc_loop_cnt += self.random_loop_cnt(4) }; - - let mut index = self.mem_prev_index as usize; - for _ in 0..acc_loop_cnt { - // Addition of memblocksize - 1 to index with wrap around logic to - // ensure that every memory location is hit evenly. - // The modulus also allows the compiler to remove the indexing - // bounds check. - index = (index + MEMORY_BLOCKSIZE - 1) % MEMORY_SIZE; - - // memory access: just add 1 to one byte - // memory access implies read from and write to memory location - mem[index] = mem[index].wrapping_add(1); - } - self.mem_prev_index = index as u16; - } - - // This is the heart of the entropy generation: calculate time deltas and - // use the CPU jitter in the time deltas. The jitter is injected into the - // entropy pool. - // - // Ensure that `ec.prev_time` is primed before using the output of this - // function. This can be done by calling this function and not using its - // result. - fn measure_jitter(&mut self, ec: &mut EcState) -> Option<()> { - // Invoke one noise source before time measurement to add variations - self.memaccess(&mut ec.mem, true); - - // Get time stamp and calculate time delta to previous - // invocation to measure the timing variations - let time = (self.timer)(); - // Note: wrapping_sub combined with a cast to `i64` generates a correct - // delta, even in the unlikely case this is a timer that is not strictly - // monotonic. - let current_delta = time.wrapping_sub(ec.prev_time) as i64 as i32; - ec.prev_time = time; - - // Call the next noise source which also injects the data - self.lfsr_time(current_delta as u64, true); - - // Check whether we have a stuck measurement (i.e. does the last - // measurement holds entropy?). - if ec.stuck(current_delta) { return None }; - - // Rotate the data buffer by a prime number (any odd number would - // do) to ensure that every bit position of the input time stamp - // has an even chance of being merged with a bit position in the - // entropy pool. We do not use one here as the adjacent bits in - // successive time deltas may have some form of dependency. The - // chosen value of 7 implies that the low 7 bits of the next - // time delta value is concatenated with the current time delta. - self.data = self.data.rotate_left(7); - - Some(()) - } - - // Shuffle the pool a bit by mixing some value with a bijective function - // (XOR) into the pool. - // - // The function generates a mixer value that depends on the bits set and - // the location of the set bits in the random number generated by the - // entropy source. Therefore, based on the generated random number, this - // mixer value can have 2^64 different values. That mixer value is - // initialized with the first two SHA-1 constants. After obtaining the - // mixer value, it is XORed into the random number. - // - // The mixer value is not assumed to contain any entropy. But due to the - // XOR operation, it can also not destroy any entropy present in the - // entropy pool. - #[inline(never)] - fn stir_pool(&mut self) { - // This constant is derived from the first two 32 bit initialization - // vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 - // The order does not really matter as we do not rely on the specific - // numbers. We just pick the SHA-1 constants as they have a good mix of - // bit set and unset. - const CONSTANT: u64 = 0x67452301efcdab89; - - // The start value of the mixer variable is derived from the third - // and fourth 32 bit initialization vector of SHA-1 as defined in - // FIPS 180-4 section 5.3.1 - let mut mixer = 0x98badcfe10325476; - - // This is a constant time function to prevent leaking timing - // information about the random number. - // The normal code is: - // ``` - // for i in 0..64 { - // if ((self.data >> i) & 1) == 1 { mixer ^= CONSTANT; } - // } - // ``` - // This is a bit fragile, as LLVM really wants to use branches here, and - // we rely on it to not recognise the opportunity. - for i in 0..64 { - let apply = (self.data >> i) & 1; - let mask = !apply.wrapping_sub(1); - mixer ^= CONSTANT & mask; - mixer = mixer.rotate_left(1); - } - - self.data ^= mixer; - } - - fn gen_entropy(&mut self) -> u64 { - trace!("JitterRng: collecting entropy"); - - // Prime `ec.prev_time`, and run the noice sources to make sure the - // first loop round collects the expected entropy. - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - let _ = self.measure_jitter(&mut ec); - - for _ in 0..self.rounds { - // If a stuck measurement is received, repeat measurement - // Note: we do not guard against an infinite loop, that would mean - // the timer suddenly became broken. - while self.measure_jitter(&mut ec).is_none() {} - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - self.stir_pool(); - self.data - } - - /// Basic quality tests on the timer, by measuring CPU timing jitter a few - /// hundred times. - /// - /// If succesful, this will return the estimated number of rounds necessary - /// to collect 64 bits of entropy. Otherwise a [`TimerError`] with the cause - /// of the failure will be returned. - /// - /// [`TimerError`]: enum.TimerError.html - pub fn test_timer(&mut self) -> Result { - debug!("JitterRng: testing timer ..."); - // We could add a check for system capabilities such as `clock_getres` - // or check for `CONFIG_X86_TSC`, but it does not make much sense as the - // following sanity checks verify that we have a high-resolution timer. - - let mut delta_sum = 0; - let mut old_delta = 0; - - let mut time_backwards = 0; - let mut count_mod = 0; - let mut count_stuck = 0; - - let mut ec = EcState { - prev_time: (self.timer)(), - last_delta: 0, - last_delta2: 0, - mem: [0; MEMORY_SIZE], - }; - - // TESTLOOPCOUNT needs some loops to identify edge systems. - // 100 is definitely too little. - const TESTLOOPCOUNT: u64 = 300; - const CLEARCACHE: u64 = 100; - - for i in 0..(CLEARCACHE + TESTLOOPCOUNT) { - // Measure time delta of core entropy collection logic - let time = (self.timer)(); - self.memaccess(&mut ec.mem, true); - self.lfsr_time(time, true); - let time2 = (self.timer)(); - - // Test whether timer works - if time == 0 || time2 == 0 { - return Err(TimerError::NoTimer); - } - let delta = time2.wrapping_sub(time) as i64 as i32; - - // Test whether timer is fine grained enough to provide delta even - // when called shortly after each other -- this implies that we also - // have a high resolution timer - if delta == 0 { - return Err(TimerError::CoarseTimer); - } - - // Up to here we did not modify any variable that will be - // evaluated later, but we already performed some work. Thus we - // already have had an impact on the caches, branch prediction, - // etc. with the goal to clear it to get the worst case - // measurements. - if i < CLEARCACHE { continue; } - - if ec.stuck(delta) { count_stuck += 1; } - - // Test whether we have an increasing timer. - if !(time2 > time) { time_backwards += 1; } - - // Count the number of times the counter increases in steps of 100ns - // or greater. - if (delta % 100) == 0 { count_mod += 1; } - - // Ensure that we have a varying delta timer which is necessary for - // the calculation of entropy -- perform this check only after the - // first loop is executed as we need to prime the old_delta value - delta_sum += (delta - old_delta).abs() as u64; - old_delta = delta; - } - - // Do a single read from `self.mem` to make sure the Memory Access noise - // source is not optimised out. - black_box(ec.mem[0]); - - // We allow the time to run backwards for up to three times. - // This can happen if the clock is being adjusted by NTP operations. - // If such an operation just happens to interfere with our test, it - // should not fail. The value of 3 should cover the NTP case being - // performed during our test run. - if time_backwards > 3 { - return Err(TimerError::NotMonotonic); - } - - // Test that the available amount of entropy per round does not get to - // low. We expect 1 bit of entropy per round as a reasonable minimum - // (although less is possible, it means the collector loop has to run - // much more often). - // `assert!(delta_average >= log2(1))` - // `assert!(delta_sum / TESTLOOPCOUNT >= 1)` - // `assert!(delta_sum >= TESTLOOPCOUNT)` - if delta_sum < TESTLOOPCOUNT { - return Err(TimerError::TinyVariantions); - } - - // Ensure that we have variations in the time stamp below 100 for at - // least 10% of all checks -- on some platforms, the counter increments - // in multiples of 100, but not always - if count_mod > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::CoarseTimer); - } - - // If we have more than 90% stuck results, then this Jitter RNG is - // likely to not work well. - if count_stuck > (TESTLOOPCOUNT * 9 / 10) { - return Err(TimerError::TooManyStuck); - } - - // Estimate the number of `measure_jitter` rounds necessary for 64 bits - // of entropy. - // - // We don't try very hard to come up with a good estimate of the - // available bits of entropy per round here for two reasons: - // 1. Simple estimates of the available bits (like Shannon entropy) are - // too optimistic. - // 2. Unless we want to waste a lot of time during intialization, there - // only a small number of samples are available. - // - // Therefore we use a very simple and conservative estimate: - // `let bits_of_entropy = log2(delta_average) / 2`. - // - // The number of rounds `measure_jitter` should run to collect 64 bits - // of entropy is `64 / bits_of_entropy`. - let delta_average = delta_sum / TESTLOOPCOUNT; - - if delta_average >= 16 { - let log2 = 64 - delta_average.leading_zeros(); - // Do something similar to roundup(64/(log2/2)): - Ok( ((64u32 * 2 + log2 - 1) / log2) as u8) - } else { - // For values < 16 the rounding error becomes too large, use a - // lookup table. - // Values 0 and 1 are invalid, and filtered out by the - // `delta_sum < TESTLOOPCOUNT` test above. - let log2_lookup = [0, 0, 128, 81, 64, 56, 50, 46, - 43, 41, 39, 38, 36, 35, 34, 33]; - Ok(log2_lookup[delta_average as usize]) - } - } - - /// Statistical test: return the timer delta of one normal run of the - /// `JitterRng` entropy collector. - /// - /// Setting `var_rounds` to `true` will execute the memory access and the - /// CPU jitter noice sources a variable amount of times (just like a real - /// `JitterRng` round). - /// - /// Setting `var_rounds` to `false` will execute the noice sources the - /// minimal number of times. This can be used to measure the minimum amount - /// of entropy one round of the entropy collector can collect in the worst - /// case. - /// - /// See [Quality testing](struct.JitterRng.html#quality-testing) on how to - /// use `timer_stats` to test the quality of `JitterRng`. - pub fn timer_stats(&mut self, var_rounds: bool) -> i64 { - let mut mem = [0; MEMORY_SIZE]; - - let time = (self.timer)(); - self.memaccess(&mut mem, var_rounds); - self.lfsr_time(time, var_rounds); - let time2 = (self.timer)(); - time2.wrapping_sub(time) as i64 - } -} - -#[cfg(feature="std")] -mod platform { - #[cfg(not(any(target_os = "macos", target_os = "ios", - target_os = "windows", - target_arch = "wasm32")))] - pub fn get_nstime() -> u64 { - use std::time::{SystemTime, UNIX_EPOCH}; - - let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); - // The correct way to calculate the current time is - // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64` - // But this is faster, and the difference in terms of entropy is - // negligible (log2(10^9) == 29.9). - dur.as_secs() << 30 | dur.subsec_nanos() as u64 - } - - #[cfg(any(target_os = "macos", target_os = "ios"))] - pub fn get_nstime() -> u64 { - extern crate libc; - // On Mac OS and iOS std::time::SystemTime only has 1000ns resolution. - // We use `mach_absolute_time` instead. This provides a CPU dependent - // unit, to get real nanoseconds the result should by multiplied by - // numer/denom from `mach_timebase_info`. - // But we are not interested in the exact nanoseconds, just entropy. So - // we use the raw result. - unsafe { libc::mach_absolute_time() } - } - - #[cfg(target_os = "windows")] - pub fn get_nstime() -> u64 { - extern crate winapi; - unsafe { - let mut t = super::mem::zeroed(); - winapi::um::profileapi::QueryPerformanceCounter(&mut t); - *t.QuadPart() as u64 - } - } -} - -// A function that is opaque to the optimizer to assist in avoiding dead-code -// elimination. Taken from `bencher`. -fn black_box(dummy: T) -> T { - unsafe { - let ret = ptr::read_volatile(&dummy); - mem::forget(dummy); - ret - } -} - -impl RngCore for JitterRng { - fn next_u32(&mut self) -> u32 { - // We want to use both parts of the generated entropy - if self.data_half_used { - self.data_half_used = false; - (self.data >> 32) as u32 - } else { - self.data = self.next_u64(); - self.data_half_used = true; - self.data as u32 - } - } - - fn next_u64(&mut self) -> u64 { - self.data_half_used = false; - self.gen_entropy() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - // Fill using `next_u32`. This is faster for filling small slices (four - // bytes or less), while the overhead is negligible. - // - // This is done especially for wrappers that implement `next_u32` - // themselves via `fill_bytes`. - impls::fill_bytes_via_next(self, dest) - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} - -impl CryptoRng for JitterRng {} - -#[cfg(test)] -mod test_jitter_init { - use jitter::JitterRng; - - #[cfg(all(feature="std", not(target_arch = "wasm32")))] - #[test] - fn test_jitter_init() { - use RngCore; - // Because this is a debug build, measurements here are not representive - // of the final release build. - // Don't fail this test if initializing `JitterRng` fails because of a - // bad timer (the timer from the standard library may not have enough - // accuracy on all platforms). - match JitterRng::new() { - Ok(ref mut rng) => { - // false positives are possible, but extremely unlikely - assert!(rng.next_u32() | rng.next_u32() != 0); - }, - Err(_) => {}, - } - } - - #[test] - fn test_jitter_bad_timer() { - fn bad_timer() -> u64 { 0 } - let mut rng = JitterRng::new_with_timer(bad_timer); - assert!(rng.test_timer().is_err()); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/mock.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/mock.rs deleted file mode 100644 index 812e4be..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/mock.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Mock random number generator - -use rand_core::{RngCore, Error, impls}; - -/// A simple implementation of `RngCore` for testing purposes. -/// -/// This generates an arithmetic sequence (i.e. adds a constant each step) -/// over a `u64` number, using wrapping arithmetic. If the increment is 0 -/// the generator yields a constant. -/// -/// ``` -/// use rand::Rng; -/// use rand::rngs::mock::StepRng; -/// -/// let mut my_rng = StepRng::new(2, 1); -/// let sample: [u64; 3] = my_rng.gen(); -/// assert_eq!(sample, [2, 3, 4]); -/// ``` -#[derive(Debug, Clone)] -pub struct StepRng { - v: u64, - a: u64, -} - -impl StepRng { - /// Create a `StepRng`, yielding an arithmetic sequence starting with - /// `initial` and incremented by `increment` each time. - pub fn new(initial: u64, increment: u64) -> Self { - StepRng { v: initial, a: increment } - } -} - -impl RngCore for StepRng { - fn next_u32(&mut self) -> u32 { - self.next_u64() as u32 - } - - fn next_u64(&mut self) -> u64 { - let result = self.v; - self.v = self.v.wrapping_add(self.a); - result - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - impls::fill_bytes_via_next(self, dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - Ok(self.fill_bytes(dest)) - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/mod.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/mod.rs deleted file mode 100644 index acc207d..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/mod.rs +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Random number generators and adapters for common usage: -//! -//! - [`ThreadRng`], a fast, secure, auto-seeded thread-local generator -//! - [`StdRng`] and [`SmallRng`], algorithms to cover typical usage -//! - [`EntropyRng`], [`OsRng`] and [`JitterRng`] as entropy sources -//! - [`mock::StepRng`] as a simple counter for tests -//! - [`adapter::ReadRng`] to read from a file/stream -//! -//! # Background — Random number generators (RNGs) -//! -//! Computers are inherently deterministic, so to get *random* numbers one -//! either has to use a hardware generator or collect bits of *entropy* from -//! various sources (e.g. event timestamps, or jitter). This is a relatively -//! slow and complicated operation. -//! -//! Generally the operating system will collect some entropy, remove bias, and -//! use that to seed its own PRNG; [`OsRng`] provides an interface to this. -//! [`JitterRng`] is an entropy collector included with Rand that measures -//! jitter in the CPU execution time, and jitter in memory access time. -//! [`EntropyRng`] is a wrapper that uses the best entropy source that is -//! available. -//! -//! ## Pseudo-random number generators -//! -//! What is commonly used instead of "true" random number renerators, are -//! *pseudo-random number generators* (PRNGs), deterministic algorithms that -//! produce an infinite stream of pseudo-random numbers from a small random -//! seed. PRNGs are faster, and have better provable properties. The numbers -//! produced can be statistically of very high quality and can be impossible to -//! predict. (They can also have obvious correlations and be trivial to predict; -//! quality varies.) -//! -//! There are two different types of PRNGs: those developed for simulations -//! and statistics, and those developed for use in cryptography; the latter are -//! called Cryptographically Secure PRNGs (CSPRNG or CPRNG). Both types can -//! have good statistical quality but the latter also have to be impossible to -//! predict, even after seeing many previous output values. Rand provides a good -//! default algorithm from each class: -//! -//! - [`SmallRng`] is a PRNG chosen for low memory usage, high performance and -//! good statistical quality. -//! The current algorithm (plain Xorshift) unfortunately performs -//! poorly in statistical quality test suites (TestU01 and PractRand) and will -//! be replaced in the next major release. -//! - [`StdRng`] is a CSPRNG chosen for good performance and trust of security -//! (based on reviews, maturity and usage). The current algorithm is HC-128, -//! which is one of the recommendations by ECRYPT's eSTREAM project. -//! -//! The above PRNGs do not cover all use-cases; more algorithms can be found in -//! the [`prng` module], as well as in several other crates. For example, you -//! may wish a CSPRNG with significantly lower memory usage than [`StdRng`] -//! while being less concerned about performance, in which case [`ChaChaRng`] -//! is a good choice. -//! -//! One complexity is that the internal state of a PRNG must change with every -//! generated number. For APIs this generally means a mutable reference to the -//! state of the PRNG has to be passed around. -//! -//! A solution is [`ThreadRng`]. This is a thread-local implementation of -//! [`StdRng`] with automatic seeding on first use. It is the best choice if you -//! "just" want a convenient, secure, fast random number source. Use via the -//! [`thread_rng`] function, which gets a reference to the current thread's -//! local instance. -//! -//! ## Seeding -//! -//! As mentioned above, PRNGs require a random seed in order to produce random -//! output. This is especially important for CSPRNGs, which are still -//! deterministic algorithms, thus can only be secure if their seed value is -//! also secure. To seed a PRNG, use one of: -//! -//! - [`FromEntropy::from_entropy`]; this is the most convenient way to seed -//! with fresh, secure random data. -//! - [`SeedableRng::from_rng`]; this allows seeding from another PRNG or -//! from an entropy source such as [`EntropyRng`]. -//! - [`SeedableRng::from_seed`]; this is mostly useful if you wish to be able -//! to reproduce the output sequence by using a fixed seed. (Don't use -//! [`StdRng`] or [`SmallRng`] in this case since different algorithms may be -//! used by future versions of Rand; use an algorithm from the -//! [`prng` module].) -//! -//! ## Conclusion -//! -//! - [`thread_rng`] is what you often want to use. -//! - If you want more control, flexibility, or better performance, use -//! [`StdRng`], [`SmallRng`] or an algorithm from the [`prng` module]. -//! - Use [`FromEntropy::from_entropy`] to seed new PRNGs. -//! - If you need reproducibility, use [`SeedableRng::from_seed`] combined with -//! a named PRNG. -//! -//! More information and notes on cryptographic security can be found -//! in the [`prng` module]. -//! -//! ## Examples -//! -//! Examples of seeding PRNGs: -//! -//! ``` -//! use rand::prelude::*; -//! # use rand::Error; -//! -//! // StdRng seeded securely by the OS or local entropy collector: -//! let mut rng = StdRng::from_entropy(); -//! # let v: u32 = rng.gen(); -//! -//! // SmallRng seeded from thread_rng: -//! # fn try_inner() -> Result<(), Error> { -//! let mut rng = SmallRng::from_rng(thread_rng())?; -//! # let v: u32 = rng.gen(); -//! # Ok(()) -//! # } -//! # try_inner().unwrap(); -//! -//! // SmallRng seeded by a constant, for deterministic results: -//! let seed = [1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16]; // byte array -//! let mut rng = SmallRng::from_seed(seed); -//! # let v: u32 = rng.gen(); -//! ``` -//! -//! -//! # Implementing custom RNGs -//! -//! If you want to implement custom RNG, see the [`rand_core`] crate. The RNG -//! will have to implement the [`RngCore`] trait, where the [`Rng`] trait is -//! build on top of. -//! -//! If the RNG needs seeding, also implement the [`SeedableRng`] trait. -//! -//! [`CryptoRng`] is a marker trait cryptographically secure PRNGs can -//! implement. -//! -//! -// This module: -//! [`ThreadRng`]: struct.ThreadRng.html -//! [`StdRng`]: struct.StdRng.html -//! [`SmallRng`]: struct.SmallRng.html -//! [`EntropyRng`]: struct.EntropyRng.html -//! [`OsRng`]: struct.OsRng.html -//! [`JitterRng`]: struct.JitterRng.html -// Other traits and functions: -//! [`rand_core`]: https://crates.io/crates/rand_core -//! [`prng` module]: ../prng/index.html -//! [`CryptoRng`]: ../trait.CryptoRng.html -//! [`FromEntropy`]: ../trait.FromEntropy.html -//! [`FromEntropy::from_entropy`]: ../trait.FromEntropy.html#tymethod.from_entropy -//! [`RngCore`]: ../trait.RngCore.html -//! [`Rng`]: ../trait.Rng.html -//! [`SeedableRng`]: ../trait.SeedableRng.html -//! [`SeedableRng::from_rng`]: ../trait.SeedableRng.html#tymethod.from_rng -//! [`SeedableRng::from_seed`]: ../trait.SeedableRng.html#tymethod.from_seed -//! [`thread_rng`]: ../fn.thread_rng.html -//! [`mock::StepRng`]: mock/struct.StepRng.html -//! [`adapter::ReadRng`]: adapter/struct.ReadRng.html -//! [`ChaChaRng`]: ../prng/chacha/struct.ChaChaRng.html - -pub mod adapter; - -#[cfg(feature="std")] mod entropy; -#[doc(hidden)] pub mod jitter; -pub mod mock; // Public so we don't export `StepRng` directly, making it a bit - // more clear it is intended for testing. -mod small; -mod std; -#[cfg(feature="std")] pub(crate) mod thread; - - -pub use self::jitter::{JitterRng, TimerError}; -#[cfg(feature="std")] pub use self::entropy::EntropyRng; - -pub use self::small::SmallRng; -pub use self::std::StdRng; -#[cfg(feature="std")] pub use self::thread::ThreadRng; - -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -mod os; - -#[cfg(all(feature="std", - any(target_os = "linux", target_os = "android", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten", - target_os = "solaris", - target_os = "cloudabi", - target_os = "macos", target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", target_os = "bitrig", - target_os = "redox", - target_os = "fuchsia", - windows, - all(target_arch = "wasm32", feature = "stdweb") -)))] -pub use self::os::OsRng; diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/os.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/os.rs deleted file mode 100644 index ecc5f32..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/os.rs +++ /dev/null @@ -1,1171 +0,0 @@ -// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Interface to the random number generator of the operating system. - -use std::fmt; -use rand_core::{CryptoRng, RngCore, Error, impls}; - -/// A random number generator that retrieves randomness straight from the -/// operating system. -/// -/// This is the preferred external source of entropy for most applications. -/// Commonly it is used to initialize a user-space RNG, which can then be used -/// to generate random values with much less overhead than `OsRng`. -/// -/// You may prefer to use [`EntropyRng`] instead of `OsRng`. It is unlikely, but -/// not entirely theoretical, for `OsRng` to fail. In such cases [`EntropyRng`] -/// falls back on a good alternative entropy source. -/// -/// `OsRng::new()` is guaranteed to be very cheap (after the first successful -/// call), and will never consume more than one file handle per process. -/// -/// # Platform sources -/// -/// | OS | interface -/// |------------------|--------------------------------------------------------- -/// | Linux, Android | [`getrandom`][1] system call if available, otherwise [`/dev/urandom`][2] after reading from `/dev/random` once -/// | Windows | [`RtlGenRandom`][3] -/// | macOS, iOS | [`SecRandomCopyBytes`][4] -/// | FreeBSD | [`kern.arandom`][5] -/// | OpenBSD, Bitrig | [`getentropy`][6] -/// | NetBSD | [`/dev/urandom`][7] after reading from `/dev/random` once -/// | Dragonfly BSD | [`/dev/random`][8] -/// | Solaris, illumos | [`getrandom`][9] system call if available, otherwise [`/dev/random`][10] -/// | Fuchsia OS | [`cprng_draw`][11] -/// | Redox | [`rand:`][12] -/// | CloudABI | [`random_get`][13] -/// | Haiku | `/dev/random` (identical to `/dev/urandom`) -/// | Web browsers | [`Crypto.getRandomValues`][14] (see [Support for WebAssembly and ams.js][14]) -/// | Node.js | [`crypto.randomBytes`][15] (see [Support for WebAssembly and ams.js][16]) -/// -/// Rand doesn't have a blanket implementation for all Unix-like operating -/// systems that reads from `/dev/urandom`. This ensures all supported operating -/// systems are using the recommended interface and respect maximum buffer -/// sizes. -/// -/// ## Support for WebAssembly and ams.js -/// -/// The three Emscripten targets `asmjs-unknown-emscripten`, -/// `wasm32-unknown-emscripten` and `wasm32-experimental-emscripten` use -/// Emscripten's emulation of `/dev/random` on web browsers and Node.js. -/// Unfortunately it falls back to the insecure `Math.random()` if a browser -/// doesn't support [`Crypto.getRandomValues`][12]. -/// -/// The bare Wasm target `wasm32-unknown-unknown` tries to call the javascript -/// methods directly, using `stdweb` in combination with `cargo-web`. -/// `wasm-bindgen` is not yet supported. -/// -/// ## Early boot -/// -/// It is possible that early in the boot process the OS hasn't had enough time -/// yet to collect entropy to securely seed its RNG, especially on virtual -/// machines. -/// -/// Some operating systems always block the thread until the RNG is securely -/// seeded. This can take anywhere from a few seconds to more than a minute. -/// Others make a best effort to use a seed from before the shutdown and don't -/// document much. -/// -/// A few, Linux, NetBSD and Solaris, offer a choice between blocking, and -/// getting an error. With `try_fill_bytes` we choose to get the error -/// ([`ErrorKind::NotReady`]), while the other methods use a blocking interface. -/// -/// On Linux (when the `genrandom` system call is not available) and on NetBSD -/// reading from `/dev/urandom` never blocks, even when the OS hasn't collected -/// enough entropy yet. As a countermeasure we try to do a single read from -/// `/dev/random` until we know the OS RNG is initialized (and store this in a -/// global static). -/// -/// # Panics -/// -/// `OsRng` is extremely unlikely to fail if `OsRng::new()`, and one read from -/// it, where succesfull. But in case it does fail, only [`try_fill_bytes`] is -/// able to report the cause. Depending on the error the other [`RngCore`] -/// methods will retry several times, and panic in case the error remains. -/// -/// [`EntropyRng`]: struct.EntropyRng.html -/// [`RngCore`]: ../trait.RngCore.html -/// [`try_fill_bytes`]: ../trait.RngCore.html#method.tymethod.try_fill_bytes -/// [`ErrorKind::NotReady`]: ../enum.ErrorKind.html#variant.NotReady -/// -/// [1]: http://man7.org/linux/man-pages/man2/getrandom.2.html -/// [2]: http://man7.org/linux/man-pages/man4/urandom.4.html -/// [3]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx -/// [4]: https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc -/// [5]: https://www.freebsd.org/cgi/man.cgi?query=random&sektion=4 -/// [6]: https://man.openbsd.org/getentropy.2 -/// [7]: http://netbsd.gw.com/cgi-bin/man-cgi?random+4+NetBSD-current -/// [8]: https://leaf.dragonflybsd.org/cgi/web-man?command=random§ion=4 -/// [9]: https://docs.oracle.com/cd/E88353_01/html/E37841/getrandom-2.html -/// [10]: https://docs.oracle.com/cd/E86824_01/html/E54777/random-7d.html -/// [11]: https://fuchsia.googlesource.com/zircon/+/HEAD/docs/syscalls/cprng_draw.md -/// [12]: https://github.com/redox-os/randd/blob/master/src/main.rs -/// [13]: https://github.com/NuxiNL/cloudabi/blob/v0.20/cloudabi.txt#L1826 -/// [14]: https://www.w3.org/TR/WebCryptoAPI/#Crypto-method-getRandomValues -/// [15]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback -/// [16]: #support-for-webassembly-and-amsjs - - -#[derive(Clone)] -pub struct OsRng(imp::OsRng); - -impl fmt::Debug for OsRng { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) - } -} - -impl OsRng { - /// Create a new `OsRng`. - pub fn new() -> Result { - imp::OsRng::new().map(OsRng) - } -} - -impl CryptoRng for OsRng {} - -impl RngCore for OsRng { - fn next_u32(&mut self) -> u32 { - impls::next_u32_via_fill(self) - } - - fn next_u64(&mut self) -> u64 { - impls::next_u64_via_fill(self) - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - use std::{time, thread}; - - // We cannot return Err(..), so we try to handle before panicking. - const MAX_RETRY_PERIOD: u32 = 10; // max 10s - const WAIT_DUR_MS: u32 = 100; // retry every 100ms - let wait_dur = time::Duration::from_millis(WAIT_DUR_MS as u64); - const RETRY_LIMIT: u32 = (MAX_RETRY_PERIOD * 1000) / WAIT_DUR_MS; - const TRANSIENT_RETRIES: u32 = 8; - let mut err_count = 0; - let mut error_logged = false; - - // Maybe block until the OS RNG is initialized - let mut read = 0; - if let Ok(n) = self.0.test_initialized(dest, true) { read = n }; - let dest = &mut dest[read..]; - - loop { - if let Err(e) = self.try_fill_bytes(dest) { - if err_count >= RETRY_LIMIT { - error!("OsRng failed too many times; last error: {}", e); - panic!("OsRng failed too many times; last error: {}", e); - } - - if e.kind.should_wait() { - if !error_logged { - warn!("OsRng failed; waiting up to {}s and retrying. Error: {}", - MAX_RETRY_PERIOD, e); - error_logged = true; - } - err_count += 1; - thread::sleep(wait_dur); - continue; - } else if e.kind.should_retry() { - if !error_logged { - warn!("OsRng failed; retrying up to {} times. Error: {}", - TRANSIENT_RETRIES, e); - error_logged = true; - } - err_count += (RETRY_LIMIT + TRANSIENT_RETRIES - 1) - / TRANSIENT_RETRIES; // round up - continue; - } else { - error!("OsRng failed: {}", e); - panic!("OsRng fatal error: {}", e); - } - } - - break; - } - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - // Some systems do not support reading 0 random bytes. - // (And why waste a system call?) - if dest.len() == 0 { return Ok(()); } - - let read = self.0.test_initialized(dest, false)?; - let dest = &mut dest[read..]; - - let max = self.0.max_chunk_size(); - if dest.len() <= max { - trace!("OsRng: reading {} bytes via {}", - dest.len(), self.0.method_str()); - } else { - trace!("OsRng: reading {} bytes via {} in {} chunks of {} bytes", - dest.len(), self.0.method_str(), (dest.len() + max) / max, max); - } - for slice in dest.chunks_mut(max) { - self.0.fill_chunk(slice)?; - } - Ok(()) - } -} - -trait OsRngImpl where Self: Sized { - // Create a new `OsRng` platform interface. - fn new() -> Result; - - // Fill a chunk with random bytes. - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error>; - - // Test whether the OS RNG is initialized. This method may not be possible - // to support cheaply (or at all) on all operating systems. - // - // If `blocking` is set, this will cause the OS the block execution until - // its RNG is initialized. - // - // Random values that are read while this are stored in `dest`, the amount - // of read bytes is returned. - fn test_initialized(&mut self, _dest: &mut [u8], _blocking: bool) - -> Result { Ok(0) } - - // Maximum chunk size supported. - fn max_chunk_size(&self) -> usize { ::core::usize::MAX } - - // Name of the OS interface (used for logging). - fn method_str(&self) -> &'static str; -} - - - - -// Helper functions to read from a random device such as `/dev/urandom`. -// -// All instances use a single internal file handle, to prevent possible -// exhaustion of file descriptors. -#[cfg(any(target_os = "linux", target_os = "android", - target_os = "netbsd", target_os = "dragonfly", - target_os = "solaris", target_os = "redox", - target_os = "haiku", target_os = "emscripten"))] -mod random_device { - use {Error, ErrorKind}; - use std::fs::File; - use std::io; - use std::io::Read; - use std::sync::{Once, Mutex, ONCE_INIT}; - - // TODO: remove outer Option when `Mutex::new(None)` is a constant expression - static mut READ_RNG_FILE: Option>> = None; - static READ_RNG_ONCE: Once = ONCE_INIT; - - #[allow(unused)] - pub fn open(path: &'static str, open_fn: F) -> Result<(), Error> - where F: Fn(&'static str) -> Result - { - READ_RNG_ONCE.call_once(|| { - unsafe { READ_RNG_FILE = Some(Mutex::new(None)) } - }); - - // We try opening the file outside the `call_once` fn because we cannot - // clone the error, thus we must retry on failure. - - let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; - let mut guard = mutex.lock().unwrap(); - if (*guard).is_none() { - info!("OsRng: opening random device {}", path); - let file = open_fn(path).map_err(map_err)?; - *guard = Some(file); - }; - Ok(()) - } - - pub fn read(dest: &mut [u8]) -> Result<(), Error> { - // We expect this function only to be used after `random_device::open` - // was succesful. Therefore we can assume that our memory was set with a - // valid object. - let mutex = unsafe { READ_RNG_FILE.as_ref().unwrap() }; - let mut guard = mutex.lock().unwrap(); - let file = (*guard).as_mut().unwrap(); - - // Use `std::io::read_exact`, which retries on `ErrorKind::Interrupted`. - file.read_exact(dest).map_err(|err| { - Error::with_cause(ErrorKind::Unavailable, - "error reading random device", err) - }) - - } - - pub fn map_err(err: io::Error) -> Error { - match err.kind() { - io::ErrorKind::Interrupted => - Error::new(ErrorKind::Transient, "interrupted"), - io::ErrorKind::WouldBlock => - Error::with_cause(ErrorKind::NotReady, - "OS RNG not yet seeded", err), - _ => Error::with_cause(ErrorKind::Unavailable, - "error while opening random device", err) - } - } -} - - -#[cfg(any(target_os = "linux", target_os = "android"))] -mod imp { - extern crate libc; - - use {Error, ErrorKind}; - use super::random_device; - use super::OsRngImpl; - - use std::io; - use std::io::Read; - use std::fs::{File, OpenOptions}; - use std::os::unix::fs::OpenOptionsExt; - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; - use std::sync::{Once, ONCE_INIT}; - - #[derive(Clone, Debug)] - pub struct OsRng { - method: OsRngMethod, - initialized: bool, - } - - #[derive(Clone, Debug)] - enum OsRngMethod { - GetRandom, - RandomDevice, - } - - impl OsRngImpl for OsRng { - fn new() -> Result { - if is_getrandom_available() { - return Ok(OsRng { method: OsRngMethod::GetRandom, - initialized: false }); - } - random_device::open("/dev/urandom", &|p| File::open(p))?; - Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) - } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - match self.method { - OsRngMethod::GetRandom => getrandom_try_fill(dest, false), - OsRngMethod::RandomDevice => random_device::read(dest), - } - } - - fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) - -> Result - { - static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; - if !self.initialized { - self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); - } - if self.initialized { return Ok(0); } - - let result = match self.method { - OsRngMethod::GetRandom => { - getrandom_try_fill(dest, blocking)?; - Ok(dest.len()) - } - OsRngMethod::RandomDevice => { - info!("OsRng: testing random device /dev/random"); - let mut file = OpenOptions::new() - .read(true) - .custom_flags(if blocking { 0 } else { libc::O_NONBLOCK }) - .open("/dev/random") - .map_err(random_device::map_err)?; - file.read(&mut dest[..1]).map_err(random_device::map_err)?; - Ok(1) - } - }; - OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); - self.initialized = true; - result - } - - fn method_str(&self) -> &'static str { - match self.method { - OsRngMethod::GetRandom => "getrandom", - OsRngMethod::RandomDevice => "/dev/urandom", - } - } - } - - #[cfg(target_arch = "x86_64")] - const NR_GETRANDOM: libc::c_long = 318; - #[cfg(target_arch = "x86")] - const NR_GETRANDOM: libc::c_long = 355; - #[cfg(target_arch = "arm")] - const NR_GETRANDOM: libc::c_long = 384; - #[cfg(target_arch = "aarch64")] - const NR_GETRANDOM: libc::c_long = 278; - #[cfg(target_arch = "s390x")] - const NR_GETRANDOM: libc::c_long = 349; - #[cfg(target_arch = "powerpc")] - const NR_GETRANDOM: libc::c_long = 359; - #[cfg(target_arch = "mips")] // old ABI - const NR_GETRANDOM: libc::c_long = 4353; - #[cfg(target_arch = "mips64")] - const NR_GETRANDOM: libc::c_long = 5313; - #[cfg(not(any(target_arch = "x86_64", target_arch = "x86", - target_arch = "arm", target_arch = "aarch64", - target_arch = "s390x", target_arch = "powerpc", - target_arch = "mips", target_arch = "mips64")))] - const NR_GETRANDOM: libc::c_long = 0; - - fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long { - extern "C" { - fn syscall(number: libc::c_long, ...) -> libc::c_long; - } - const GRND_NONBLOCK: libc::c_uint = 0x0001; - - if NR_GETRANDOM == 0 { return -1 }; - - unsafe { - syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), - if blocking { 0 } else { GRND_NONBLOCK }) - } - } - - fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { - let mut read = 0; - while read < dest.len() { - let result = getrandom(&mut dest[read..], blocking); - if result == -1 { - let err = io::Error::last_os_error(); - let kind = err.kind(); - if kind == io::ErrorKind::Interrupted { - continue; - } else if kind == io::ErrorKind::WouldBlock { - return Err(Error::with_cause( - ErrorKind::NotReady, - "getrandom not ready", - err, - )); - } else { - return Err(Error::with_cause( - ErrorKind::Unavailable, - "unexpected getrandom error", - err, - )); - } - } else { - read += result as usize; - } - } - Ok(()) - } - - fn is_getrandom_available() -> bool { - static CHECKER: Once = ONCE_INIT; - static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT; - - if NR_GETRANDOM == 0 { return false }; - - CHECKER.call_once(|| { - debug!("OsRng: testing getrandom"); - let mut buf: [u8; 0] = []; - let result = getrandom(&mut buf, false); - let available = if result == -1 { - let err = io::Error::last_os_error().raw_os_error(); - err != Some(libc::ENOSYS) - } else { - true - }; - AVAILABLE.store(available, Ordering::Relaxed); - info!("OsRng: using {}", if available { "getrandom" } else { "/dev/urandom" }); - }); - - AVAILABLE.load(Ordering::Relaxed) - } -} - - -#[cfg(target_os = "netbsd")] -mod imp { - use Error; - use super::random_device; - use super::OsRngImpl; - - use std::fs::File; - use std::io::Read; - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; - - #[derive(Clone, Debug)] - pub struct OsRng { initialized: bool } - - impl OsRngImpl for OsRng { - fn new() -> Result { - random_device::open("/dev/urandom", &|p| File::open(p))?; - Ok(OsRng { initialized: false }) - } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - random_device::read(dest) - } - - // Read a single byte from `/dev/random` to determine if the OS RNG is - // already seeded. NetBSD always blocks if not yet ready. - fn test_initialized(&mut self, dest: &mut [u8], _blocking: bool) - -> Result - { - static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; - if !self.initialized { - self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); - } - if self.initialized { return Ok(0); } - - info!("OsRng: testing random device /dev/random"); - let mut file = - File::open("/dev/random").map_err(random_device::map_err)?; - file.read(&mut dest[..1]).map_err(random_device::map_err)?; - - OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); - self.initialized = true; - Ok(1) - } - - fn method_str(&self) -> &'static str { "/dev/urandom" } - } -} - - -#[cfg(any(target_os = "dragonfly", - target_os = "haiku", - target_os = "emscripten"))] -mod imp { - use Error; - use super::random_device; - use super::OsRngImpl; - use std::fs::File; - - #[derive(Clone, Debug)] - pub struct OsRng(); - - impl OsRngImpl for OsRng { - fn new() -> Result { - random_device::open("/dev/random", &|p| File::open(p))?; - Ok(OsRng()) - } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - random_device::read(dest) - } - - #[cfg(target_os = "emscripten")] - fn max_chunk_size(&self) -> usize { - // `Crypto.getRandomValues` documents `dest` should be at most 65536 - // bytes. `crypto.randomBytes` documents: "To minimize threadpool - // task length variation, partition large randomBytes requests when - // doing so as part of fulfilling a client request. - 65536 - } - - fn method_str(&self) -> &'static str { "/dev/random" } - } -} - - -// Read from `/dev/random`, with chunks of limited size (1040 bytes). -// `/dev/random` uses the Hash_DRBG with SHA512 algorithm from NIST SP 800-90A. -// `/dev/urandom` uses the FIPS 186-2 algorithm, which is considered less -// secure. We choose to read from `/dev/random`. -// -// Since Solaris 11.3 the `getrandom` syscall is available. To make sure we can -// compile on both Solaris and on OpenSolaris derivatives, that do not have the -// function, we do a direct syscall instead of calling a library function. -// -// We have no way to differentiate between Solaris, illumos, SmartOS, etc. -#[cfg(target_os = "solaris")] -mod imp { - extern crate libc; - - use {Error, ErrorKind}; - use super::random_device; - use super::OsRngImpl; - - use std::io; - use std::io::Read; - use std::fs::{File, OpenOptions}; - use std::os::unix::fs::OpenOptionsExt; - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; - - #[derive(Clone, Debug)] - pub struct OsRng { - method: OsRngMethod, - initialized: bool, - } - - #[derive(Clone, Debug)] - enum OsRngMethod { - GetRandom, - RandomDevice, - } - - impl OsRngImpl for OsRng { - fn new() -> Result { - if is_getrandom_available() { - return Ok(OsRng { method: OsRngMethod::GetRandom, - initialized: false }); - } - let open = |p| OpenOptions::new() - .read(true) - .custom_flags(libc::O_NONBLOCK) - .open(p); - random_device::open("/dev/random", &open)?; - Ok(OsRng { method: OsRngMethod::RandomDevice, initialized: false }) - } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - match self.method { - OsRngMethod::GetRandom => getrandom_try_fill(dest, false), - OsRngMethod::RandomDevice => random_device::read(dest), - } - } - - fn test_initialized(&mut self, dest: &mut [u8], blocking: bool) - -> Result - { - static OS_RNG_INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT; - if !self.initialized { - self.initialized = OS_RNG_INITIALIZED.load(Ordering::Relaxed); - } - if self.initialized { return Ok(0); } - - let chunk_len = ::core::cmp::min(1024, dest.len()); - let dest = &mut dest[..chunk_len]; - - match self.method { - OsRngMethod::GetRandom => getrandom_try_fill(dest, blocking)?, - OsRngMethod::RandomDevice => { - if blocking { - info!("OsRng: testing random device /dev/random"); - // We already have a non-blocking handle, but now need a - // blocking one. Not much choice except opening it twice - let mut file = File::open("/dev/random") - .map_err(random_device::map_err)?; - file.read(dest).map_err(random_device::map_err)?; - } else { - self.fill_chunk(dest)?; - } - } - }; - OS_RNG_INITIALIZED.store(true, Ordering::Relaxed); - self.initialized = true; - Ok(chunk_len) - } - - fn max_chunk_size(&self) -> usize { - // The documentation says 1024 is the maximum for getrandom, but - // 1040 for /dev/random. - 1024 - } - - fn method_str(&self) -> &'static str { - match self.method { - OsRngMethod::GetRandom => "getrandom", - OsRngMethod::RandomDevice => "/dev/random", - } - } - } - - fn getrandom(buf: &mut [u8], blocking: bool) -> libc::c_long { - extern "C" { - fn syscall(number: libc::c_long, ...) -> libc::c_long; - } - - const SYS_GETRANDOM: libc::c_long = 143; - const GRND_NONBLOCK: libc::c_uint = 0x0001; - const GRND_RANDOM: libc::c_uint = 0x0002; - - unsafe { - syscall(SYS_GETRANDOM, buf.as_mut_ptr(), buf.len(), - if blocking { 0 } else { GRND_NONBLOCK } | GRND_RANDOM) - } - } - - fn getrandom_try_fill(dest: &mut [u8], blocking: bool) -> Result<(), Error> { - let result = getrandom(dest, blocking); - if result == -1 || result == 0 { - let err = io::Error::last_os_error(); - let kind = err.kind(); - if kind == io::ErrorKind::WouldBlock { - return Err(Error::with_cause( - ErrorKind::NotReady, - "getrandom not ready", - err, - )); - } else { - return Err(Error::with_cause( - ErrorKind::Unavailable, - "unexpected getrandom error", - err, - )); - } - } else if result != dest.len() as i64 { - return Err(Error::new(ErrorKind::Unavailable, - "unexpected getrandom error")); - } - Ok(()) - } - - fn is_getrandom_available() -> bool { - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; - use std::sync::{Once, ONCE_INIT}; - - static CHECKER: Once = ONCE_INIT; - static AVAILABLE: AtomicBool = ATOMIC_BOOL_INIT; - - CHECKER.call_once(|| { - debug!("OsRng: testing getrandom"); - let mut buf: [u8; 0] = []; - let result = getrandom(&mut buf, false); - let available = if result == -1 { - let err = io::Error::last_os_error().raw_os_error(); - err != Some(libc::ENOSYS) - } else { - true - }; - AVAILABLE.store(available, Ordering::Relaxed); - info!("OsRng: using {}", if available { "getrandom" } else { "/dev/random" }); - }); - - AVAILABLE.load(Ordering::Relaxed) - } -} - - -#[cfg(target_os = "cloudabi")] -mod imp { - extern crate cloudabi; - - use std::io; - use {Error, ErrorKind}; - use super::OsRngImpl; - - #[derive(Clone, Debug)] - pub struct OsRng; - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let errno = unsafe { cloudabi::random_get(dest) }; - if errno == cloudabi::errno::SUCCESS { - Ok(()) - } else { - // Cloudlibc provides its own `strerror` implementation so we - // can use `from_raw_os_error` here. - Err(Error::with_cause( - ErrorKind::Unavailable, - "random_get() system call failed", - io::Error::from_raw_os_error(errno as i32), - )) - } - } - - fn method_str(&self) -> &'static str { "cloudabi::random_get" } - } -} - - -#[cfg(any(target_os = "macos", target_os = "ios"))] -mod imp { - extern crate libc; - - use {Error, ErrorKind}; - use super::OsRngImpl; - - use std::io; - use self::libc::{c_int, size_t}; - - #[derive(Clone, Debug)] - pub struct OsRng; - - enum SecRandom {} - - #[allow(non_upper_case_globals)] - const kSecRandomDefault: *const SecRandom = 0 as *const SecRandom; - - #[link(name = "Security", kind = "framework")] - extern { - fn SecRandomCopyBytes(rnd: *const SecRandom, - count: size_t, bytes: *mut u8) -> c_int; - } - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let ret = unsafe { - SecRandomCopyBytes(kSecRandomDefault, - dest.len() as size_t, - dest.as_mut_ptr()) - }; - if ret == -1 { - Err(Error::with_cause( - ErrorKind::Unavailable, - "couldn't generate random bytes", - io::Error::last_os_error())) - } else { - Ok(()) - } - } - - fn method_str(&self) -> &'static str { "SecRandomCopyBytes" } - } -} - - -#[cfg(target_os = "freebsd")] -mod imp { - extern crate libc; - - use {Error, ErrorKind}; - use super::OsRngImpl; - - use std::ptr; - use std::io; - - #[derive(Clone, Debug)] - pub struct OsRng; - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let mib = [libc::CTL_KERN, libc::KERN_ARND]; - let mut len = dest.len(); - let ret = unsafe { - libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint, - dest.as_mut_ptr() as *mut _, &mut len, - ptr::null(), 0) - }; - if ret == -1 || len != dest.len() { - return Err(Error::with_cause( - ErrorKind::Unavailable, - "kern.arandom sysctl failed", - io::Error::last_os_error())); - } - Ok(()) - } - - fn max_chunk_size(&self) -> usize { 256 } - - fn method_str(&self) -> &'static str { "kern.arandom" } - } -} - - -#[cfg(any(target_os = "openbsd", target_os = "bitrig"))] -mod imp { - extern crate libc; - - use {Error, ErrorKind}; - use super::OsRngImpl; - - use std::io; - - #[derive(Clone, Debug)] - pub struct OsRng; - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let ret = unsafe { - libc::getentropy(dest.as_mut_ptr() as *mut libc::c_void, dest.len()) - }; - if ret == -1 { - return Err(Error::with_cause( - ErrorKind::Unavailable, - "getentropy failed", - io::Error::last_os_error())); - } - Ok(()) - } - - fn max_chunk_size(&self) -> usize { 256 } - - fn method_str(&self) -> &'static str { "getentropy" } - } -} - - -#[cfg(target_os = "redox")] -mod imp { - use Error; - use super::random_device; - use super::OsRngImpl; - use std::fs::File; - - #[derive(Clone, Debug)] - pub struct OsRng(); - - impl OsRngImpl for OsRng { - fn new() -> Result { - random_device::open("rand:", &|p| File::open(p))?; - Ok(OsRng()) - } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - random_device::read(dest) - } - - fn method_str(&self) -> &'static str { "'rand:'" } - } -} - - -#[cfg(target_os = "fuchsia")] -mod imp { - extern crate fuchsia_cprng; - - use Error; - use super::OsRngImpl; - - #[derive(Clone, Debug)] - pub struct OsRng; - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - fuchsia_cprng::cprng_draw(dest); - Ok(()) - } - - fn method_str(&self) -> &'static str { "cprng_draw" } - } -} - - -#[cfg(windows)] -mod imp { - extern crate winapi; - - use {Error, ErrorKind}; - use super::OsRngImpl; - - use std::io; - - use self::winapi::shared::minwindef::ULONG; - use self::winapi::um::ntsecapi::RtlGenRandom; - use self::winapi::um::winnt::PVOID; - - #[derive(Clone, Debug)] - pub struct OsRng; - - impl OsRngImpl for OsRng { - fn new() -> Result { Ok(OsRng) } - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - let ret = unsafe { - RtlGenRandom(dest.as_mut_ptr() as PVOID, dest.len() as ULONG) - }; - if ret == 0 { - return Err(Error::with_cause( - ErrorKind::Unavailable, - "couldn't generate random bytes", - io::Error::last_os_error())); - } - Ok(()) - } - - fn max_chunk_size(&self) -> usize { ::max_value() as usize } - - fn method_str(&self) -> &'static str { "RtlGenRandom" } - } -} - - -#[cfg(all(target_arch = "wasm32", - not(target_os = "emscripten"), - feature = "stdweb"))] -mod imp { - use std::mem; - use stdweb::unstable::TryInto; - use stdweb::web::error::Error as WebError; - use {Error, ErrorKind}; - use super::OsRngImpl; - - #[derive(Clone, Debug)] - enum OsRngMethod { - Browser, - Node - } - - #[derive(Clone, Debug)] - pub struct OsRng(OsRngMethod); - - impl OsRngImpl for OsRng { - fn new() -> Result { - let result = js! { - try { - if ( - typeof self === "object" && - typeof self.crypto === "object" && - typeof self.crypto.getRandomValues === "function" - ) { - return { success: true, ty: 1 }; - } - - if (typeof require("crypto").randomBytes === "function") { - return { success: true, ty: 2 }; - } - - return { success: false, error: new Error("not supported") }; - } catch(err) { - return { success: false, error: err }; - } - }; - - if js!{ return @{ result.as_ref() }.success } == true { - let ty = js!{ return @{ result }.ty }; - - if ty == 1 { Ok(OsRng(OsRngMethod::Browser)) } - else if ty == 2 { Ok(OsRng(OsRngMethod::Node)) } - else { unreachable!() } - } else { - let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); - Err(Error::with_cause(ErrorKind::Unavailable, "WASM Error", err)) - } - } - - - fn fill_chunk(&mut self, dest: &mut [u8]) -> Result<(), Error> { - assert_eq!(mem::size_of::(), 4); - - let len = dest.len() as u32; - let ptr = dest.as_mut_ptr() as i32; - - let result = match self.0 { - OsRngMethod::Browser => js! { - try { - let array = new Uint8Array(@{ len }); - self.crypto.getRandomValues(array); - HEAPU8.set(array, @{ ptr }); - - return { success: true }; - } catch(err) { - return { success: false, error: err }; - } - }, - OsRngMethod::Node => js! { - try { - let bytes = require("crypto").randomBytes(@{ len }); - HEAPU8.set(new Uint8Array(bytes), @{ ptr }); - - return { success: true }; - } catch(err) { - return { success: false, error: err }; - } - } - }; - - if js!{ return @{ result.as_ref() }.success } == true { - Ok(()) - } else { - let err: WebError = js!{ return @{ result }.error }.try_into().unwrap(); - Err(Error::with_cause(ErrorKind::Unexpected, "WASM Error", err)) - } - } - - fn max_chunk_size(&self) -> usize { 65536 } - - fn method_str(&self) -> &'static str { - match self.0 { - OsRngMethod::Browser => "Crypto.getRandomValues", - OsRngMethod::Node => "crypto.randomBytes", - } - } - } -} - - -#[cfg(test)] -mod test { - use RngCore; - use OsRng; - - #[test] - fn test_os_rng() { - let mut r = OsRng::new().unwrap(); - - r.next_u32(); - r.next_u64(); - - let mut v1 = [0u8; 1000]; - r.fill_bytes(&mut v1); - - let mut v2 = [0u8; 1000]; - r.fill_bytes(&mut v2); - - let mut n_diff_bits = 0; - for i in 0..v1.len() { - n_diff_bits += (v1[i] ^ v2[i]).count_ones(); - } - - // Check at least 1 bit per byte differs. p(failure) < 1e-1000 with random input. - assert!(n_diff_bits >= v1.len() as u32); - } - - #[test] - fn test_os_rng_empty() { - let mut r = OsRng::new().unwrap(); - - let mut empty = [0u8; 0]; - r.fill_bytes(&mut empty); - } - - #[test] - fn test_os_rng_huge() { - let mut r = OsRng::new().unwrap(); - - let mut huge = [0u8; 100_000]; - r.fill_bytes(&mut huge); - } - - #[cfg(not(any(target_arch = "wasm32", target_arch = "asmjs")))] - #[test] - fn test_os_rng_tasks() { - use std::sync::mpsc::channel; - use std::thread; - - let mut txs = vec!(); - for _ in 0..20 { - let (tx, rx) = channel(); - txs.push(tx); - - thread::spawn(move|| { - // wait until all the tasks are ready to go. - rx.recv().unwrap(); - - // deschedule to attempt to interleave things as much - // as possible (XXX: is this a good test?) - let mut r = OsRng::new().unwrap(); - thread::yield_now(); - let mut v = [0u8; 1000]; - - for _ in 0..100 { - r.next_u32(); - thread::yield_now(); - r.next_u64(); - thread::yield_now(); - r.fill_bytes(&mut v); - thread::yield_now(); - } - }); - } - - // start all the tasks - for tx in txs.iter() { - tx.send(()).unwrap(); - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/small.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/small.rs deleted file mode 100644 index effdbff..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/small.rs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A small fast RNG - -use {RngCore, SeedableRng, Error}; -use prng::XorShiftRng; - -/// An RNG recommended when small state, cheap initialization and good -/// performance are required. The PRNG algorithm in `SmallRng` is chosen to be -/// efficient on the current platform, **without consideration for cryptography -/// or security**. The size of its state is much smaller than for [`StdRng`]. -/// -/// Reproducibility of output from this generator is however not required, thus -/// future library versions may use a different internal generator with -/// different output. Further, this generator may not be portable and can -/// produce different output depending on the architecture. If you require -/// reproducible output, use a named RNG, for example [`XorShiftRng`]. -/// -/// The current algorithm used on all platforms is [Xorshift]. -/// -/// # Examples -/// -/// Initializing `SmallRng` with a random seed can be done using [`FromEntropy`]: -/// -/// ``` -/// # use rand::Rng; -/// use rand::FromEntropy; -/// use rand::rngs::SmallRng; -/// -/// // Create small, cheap to initialize and fast RNG with a random seed. -/// // The randomness is supplied by the operating system. -/// let mut small_rng = SmallRng::from_entropy(); -/// # let v: u32 = small_rng.gen(); -/// ``` -/// -/// When initializing a lot of `SmallRng`'s, using [`thread_rng`] can be more -/// efficient: -/// -/// ``` -/// use std::iter; -/// use rand::{SeedableRng, thread_rng}; -/// use rand::rngs::SmallRng; -/// -/// // Create a big, expensive to initialize and slower, but unpredictable RNG. -/// // This is cached and done only once per thread. -/// let mut thread_rng = thread_rng(); -/// // Create small, cheap to initialize and fast RNGs with random seeds. -/// // One can generally assume this won't fail. -/// let rngs: Vec = iter::repeat(()) -/// .map(|()| SmallRng::from_rng(&mut thread_rng).unwrap()) -/// .take(10) -/// .collect(); -/// ``` -/// -/// [`FromEntropy`]: ../trait.FromEntropy.html -/// [`StdRng`]: struct.StdRng.html -/// [`thread_rng`]: ../fn.thread_rng.html -/// [Xorshift]: ../prng/struct.XorShiftRng.html -/// [`XorShiftRng`]: ../prng/struct.XorShiftRng.html -#[derive(Clone, Debug)] -pub struct SmallRng(XorShiftRng); - -impl RngCore for SmallRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for SmallRng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - SmallRng(XorShiftRng::from_seed(seed)) - } - - fn from_rng(rng: R) -> Result { - XorShiftRng::from_rng(rng).map(SmallRng) - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/std.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/std.rs deleted file mode 100644 index 1451f76..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/std.rs +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The standard RNG - -use {RngCore, CryptoRng, Error, SeedableRng}; -use prng::Hc128Rng; - -/// The standard RNG. The PRNG algorithm in `StdRng` is chosen to be efficient -/// on the current platform, to be statistically strong and unpredictable -/// (meaning a cryptographically secure PRNG). -/// -/// The current algorithm used on all platforms is [HC-128]. -/// -/// Reproducibility of output from this generator is however not required, thus -/// future library versions may use a different internal generator with -/// different output. Further, this generator may not be portable and can -/// produce different output depending on the architecture. If you require -/// reproducible output, use a named RNG, for example [`ChaChaRng`]. -/// -/// [HC-128]: ../prng/hc128/struct.Hc128Rng.html -/// [`ChaChaRng`]: ../prng/chacha/struct.ChaChaRng.html -#[derive(Clone, Debug)] -pub struct StdRng(Hc128Rng); - -impl RngCore for StdRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - self.0.next_u32() - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - self.0.next_u64() - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - self.0.fill_bytes(dest); - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - self.0.try_fill_bytes(dest) - } -} - -impl SeedableRng for StdRng { - type Seed = ::Seed; - - fn from_seed(seed: Self::Seed) -> Self { - StdRng(Hc128Rng::from_seed(seed)) - } - - fn from_rng(rng: R) -> Result { - Hc128Rng::from_rng(rng).map(StdRng) - } -} - -impl CryptoRng for StdRng {} - - -#[cfg(test)] -mod test { - use {RngCore, SeedableRng}; - use rngs::StdRng; - - #[test] - fn test_stdrng_construction() { - let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0, - 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; - let mut rng1 = StdRng::from_seed(seed); - assert_eq!(rng1.next_u64(), 15759097995037006553); - - let mut rng2 = StdRng::from_rng(rng1).unwrap(); - assert_eq!(rng2.next_u64(), 6766915756997287454); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/rngs/thread.rs b/third_party/cargo/vendor/rand-0.5.6/src/rngs/thread.rs deleted file mode 100644 index 863b79d..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/rngs/thread.rs +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2017-2018 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Thread-local random number generator - -use std::cell::UnsafeCell; -use std::rc::Rc; - -use {RngCore, CryptoRng, SeedableRng, Error}; -use rngs::adapter::ReseedingRng; -use rngs::EntropyRng; -use prng::hc128::Hc128Core; - -// Rationale for using `UnsafeCell` in `ThreadRng`: -// -// Previously we used a `RefCell`, with an overhead of ~15%. There will only -// ever be one mutable reference to the interior of the `UnsafeCell`, because -// we only have such a reference inside `next_u32`, `next_u64`, etc. Within a -// single thread (which is the definition of `ThreadRng`), there will only ever -// be one of these methods active at a time. -// -// A possible scenario where there could be multiple mutable references is if -// `ThreadRng` is used inside `next_u32` and co. But the implementation is -// completely under our control. We just have to ensure none of them use -// `ThreadRng` internally, which is nonsensical anyway. We should also never run -// `ThreadRng` in destructors of its implementation, which is also nonsensical. -// -// The additional `Rc` is not strictly neccesary, and could be removed. For now -// it ensures `ThreadRng` stays `!Send` and `!Sync`, and implements `Clone`. - - -// Number of generated bytes after which to reseed `TreadRng`. -// -// The time it takes to reseed HC-128 is roughly equivalent to generating 7 KiB. -// We pick a treshold here that is large enough to not reduce the average -// performance too much, but also small enough to not make reseeding something -// that basically never happens. -const THREAD_RNG_RESEED_THRESHOLD: u64 = 32*1024*1024; // 32 MiB - -/// The type returned by [`thread_rng`], essentially just a reference to the -/// PRNG in thread-local memory. -/// -/// `ThreadRng` uses [`ReseedingRng`] wrapping the same PRNG as [`StdRng`], -/// which is reseeded after generating 32 MiB of random data. A single instance -/// is cached per thread and the returned `ThreadRng` is a reference to this -/// instance — hence `ThreadRng` is neither `Send` nor `Sync` but is safe to use -/// within a single thread. This RNG is seeded and reseeded via [`EntropyRng`] -/// as required. -/// -/// Note that the reseeding is done as an extra precaution against entropy -/// leaks and is in theory unnecessary — to predict `ThreadRng`'s output, an -/// attacker would have to either determine most of the RNG's seed or internal -/// state, or crack the algorithm used. -/// -/// Like [`StdRng`], `ThreadRng` is a cryptographically secure PRNG. The current -/// algorithm used is [HC-128], which is an array-based PRNG that trades memory -/// usage for better performance. This makes it similar to ISAAC, the algorithm -/// used in `ThreadRng` before rand 0.5. -/// -/// Cloning this handle just produces a new reference to the same thread-local -/// generator. -/// -/// [`thread_rng`]: ../fn.thread_rng.html -/// [`ReseedingRng`]: adapter/struct.ReseedingRng.html -/// [`StdRng`]: struct.StdRng.html -/// [`EntropyRng`]: struct.EntropyRng.html -/// [HC-128]: ../prng/hc128/struct.Hc128Rng.html -#[derive(Clone, Debug)] -pub struct ThreadRng { - rng: Rc>>, -} - -thread_local!( - static THREAD_RNG_KEY: Rc>> = { - let mut entropy_source = EntropyRng::new(); - let r = Hc128Core::from_rng(&mut entropy_source).unwrap_or_else(|err| - panic!("could not initialize thread_rng: {}", err)); - let rng = ReseedingRng::new(r, - THREAD_RNG_RESEED_THRESHOLD, - entropy_source); - Rc::new(UnsafeCell::new(rng)) - } -); - -/// Retrieve the lazily-initialized thread-local random number -/// generator, seeded by the system. Intended to be used in method -/// chaining style, e.g. `thread_rng().gen::()`, or cached locally, e.g. -/// `let mut rng = thread_rng();`. -/// -/// For more information see [`ThreadRng`]. -/// -/// [`ThreadRng`]: rngs/struct.ThreadRng.html -pub fn thread_rng() -> ThreadRng { - ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) } -} - -impl RngCore for ThreadRng { - #[inline(always)] - fn next_u32(&mut self) -> u32 { - unsafe { (*self.rng.get()).next_u32() } - } - - #[inline(always)] - fn next_u64(&mut self) -> u64 { - unsafe { (*self.rng.get()).next_u64() } - } - - fn fill_bytes(&mut self, dest: &mut [u8]) { - unsafe { (*self.rng.get()).fill_bytes(dest) } - } - - fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { - unsafe { (*self.rng.get()).try_fill_bytes(dest) } - } -} - -impl CryptoRng for ThreadRng {} - - -#[cfg(test)] -mod test { - #[test] - #[cfg(not(feature="stdweb"))] - fn test_thread_rng() { - use Rng; - let mut r = ::thread_rng(); - r.gen::(); - let mut v = [1, 1, 1]; - r.shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!(r.gen_range(0, 1), 0); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/src/seq.rs b/third_party/cargo/vendor/rand-0.5.6/src/seq.rs deleted file mode 100644 index 8c7ed47..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/src/seq.rs +++ /dev/null @@ -1,334 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Functions for randomly accessing and sampling sequences. - -use super::Rng; - -// This crate is only enabled when either std or alloc is available. -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::vec::Vec; -// BTreeMap is not as fast in tests, but better than nothing. -#[cfg(feature="std")] use std::collections::HashMap; -#[cfg(all(feature="alloc", not(feature="std")))] use alloc::collections::BTreeMap; - -/// Randomly sample `amount` elements from a finite iterator. -/// -/// The following can be returned: -/// -/// - `Ok`: `Vec` of `amount` non-repeating randomly sampled elements. The order is not random. -/// - `Err`: `Vec` of all the elements from `iterable` in sequential order. This happens when the -/// length of `iterable` was less than `amount`. This is considered an error since exactly -/// `amount` elements is typically expected. -/// -/// This implementation uses `O(len(iterable))` time and `O(amount)` memory. -/// -/// # Example -/// -/// ``` -/// use rand::{thread_rng, seq}; -/// -/// let mut rng = thread_rng(); -/// let sample = seq::sample_iter(&mut rng, 1..100, 5).unwrap(); -/// println!("{:?}", sample); -/// ``` -pub fn sample_iter(rng: &mut R, iterable: I, amount: usize) -> Result, Vec> - where I: IntoIterator, - R: Rng + ?Sized, -{ - let mut iter = iterable.into_iter(); - let mut reservoir = Vec::with_capacity(amount); - reservoir.extend(iter.by_ref().take(amount)); - - // Continue unless the iterator was exhausted - // - // note: this prevents iterators that "restart" from causing problems. - // If the iterator stops once, then so do we. - if reservoir.len() == amount { - for (i, elem) in iter.enumerate() { - let k = rng.gen_range(0, i + 1 + amount); - if let Some(spot) = reservoir.get_mut(k) { - *spot = elem; - } - } - Ok(reservoir) - } else { - // Don't hang onto extra memory. There is a corner case where - // `amount` was much less than `len(iterable)`. - reservoir.shrink_to_fit(); - Err(reservoir) - } -} - -/// Randomly sample exactly `amount` values from `slice`. -/// -/// The values are non-repeating and in random order. -/// -/// This implementation uses `O(amount)` time and memory. -/// -/// Panics if `amount > slice.len()` -/// -/// # Example -/// -/// ``` -/// use rand::{thread_rng, seq}; -/// -/// let mut rng = thread_rng(); -/// let values = vec![5, 6, 1, 3, 4, 6, 7]; -/// println!("{:?}", seq::sample_slice(&mut rng, &values, 3)); -/// ``` -pub fn sample_slice(rng: &mut R, slice: &[T], amount: usize) -> Vec - where R: Rng + ?Sized, - T: Clone -{ - let indices = sample_indices(rng, slice.len(), amount); - - let mut out = Vec::with_capacity(amount); - out.extend(indices.iter().map(|i| slice[*i].clone())); - out -} - -/// Randomly sample exactly `amount` references from `slice`. -/// -/// The references are non-repeating and in random order. -/// -/// This implementation uses `O(amount)` time and memory. -/// -/// Panics if `amount > slice.len()` -/// -/// # Example -/// -/// ``` -/// use rand::{thread_rng, seq}; -/// -/// let mut rng = thread_rng(); -/// let values = vec![5, 6, 1, 3, 4, 6, 7]; -/// println!("{:?}", seq::sample_slice_ref(&mut rng, &values, 3)); -/// ``` -pub fn sample_slice_ref<'a, R, T>(rng: &mut R, slice: &'a [T], amount: usize) -> Vec<&'a T> - where R: Rng + ?Sized -{ - let indices = sample_indices(rng, slice.len(), amount); - - let mut out = Vec::with_capacity(amount); - out.extend(indices.iter().map(|i| &slice[*i])); - out -} - -/// Randomly sample exactly `amount` indices from `0..length`. -/// -/// The values are non-repeating and in random order. -/// -/// This implementation uses `O(amount)` time and memory. -/// -/// This method is used internally by the slice sampling methods, but it can sometimes be useful to -/// have the indices themselves so this is provided as an alternative. -/// -/// Panics if `amount > length` -pub fn sample_indices(rng: &mut R, length: usize, amount: usize) -> Vec - where R: Rng + ?Sized, -{ - if amount > length { - panic!("`amount` must be less than or equal to `slice.len()`"); - } - - // We are going to have to allocate at least `amount` for the output no matter what. However, - // if we use the `cached` version we will have to allocate `amount` as a HashMap as well since - // it inserts an element for every loop. - // - // Therefore, if `amount >= length / 2` then inplace will be both faster and use less memory. - // In fact, benchmarks show the inplace version is faster for length up to about 20 times - // faster than amount. - // - // TODO: there is probably even more fine-tuning that can be done here since - // `HashMap::with_capacity(amount)` probably allocates more than `amount` in practice, - // and a trade off could probably be made between memory/cpu, since hashmap operations - // are slower than array index swapping. - if amount >= length / 20 { - sample_indices_inplace(rng, length, amount) - } else { - sample_indices_cache(rng, length, amount) - } -} - -/// Sample an amount of indices using an inplace partial fisher yates method. -/// -/// This allocates the entire `length` of indices and randomizes only the first `amount`. -/// It then truncates to `amount` and returns. -/// -/// This is better than using a `HashMap` "cache" when `amount >= length / 2` -/// since it does not require allocating an extra cache and is much faster. -fn sample_indices_inplace(rng: &mut R, length: usize, amount: usize) -> Vec - where R: Rng + ?Sized, -{ - debug_assert!(amount <= length); - let mut indices: Vec = Vec::with_capacity(length); - indices.extend(0..length); - for i in 0..amount { - let j: usize = rng.gen_range(i, length); - indices.swap(i, j); - } - indices.truncate(amount); - debug_assert_eq!(indices.len(), amount); - indices -} - - -/// This method performs a partial fisher-yates on a range of indices using a -/// `HashMap` as a cache to record potential collisions. -/// -/// The cache avoids allocating the entire `length` of values. This is especially useful when -/// `amount <<< length`, i.e. select 3 non-repeating from `1_000_000` -fn sample_indices_cache( - rng: &mut R, - length: usize, - amount: usize, -) -> Vec - where R: Rng + ?Sized, -{ - debug_assert!(amount <= length); - #[cfg(feature="std")] let mut cache = HashMap::with_capacity(amount); - #[cfg(not(feature="std"))] let mut cache = BTreeMap::new(); - let mut out = Vec::with_capacity(amount); - for i in 0..amount { - let j: usize = rng.gen_range(i, length); - - // equiv: let tmp = slice[i]; - let tmp = match cache.get(&i) { - Some(e) => *e, - None => i, - }; - - // equiv: slice[i] = slice[j]; - let x = match cache.get(&j) { - Some(x) => *x, - None => j, - }; - - // equiv: slice[j] = tmp; - cache.insert(j, tmp); - - // note that in the inplace version, slice[i] is automatically "returned" value - out.push(x); - } - debug_assert_eq!(out.len(), amount); - out -} - -#[cfg(test)] -mod test { - use super::*; - use {XorShiftRng, Rng, SeedableRng}; - #[cfg(not(feature="std"))] - use alloc::vec::Vec; - - #[test] - fn test_sample_iter() { - let min_val = 1; - let max_val = 100; - - let mut r = ::test::rng(401); - let vals = (min_val..max_val).collect::>(); - let small_sample = sample_iter(&mut r, vals.iter(), 5).unwrap(); - let large_sample = sample_iter(&mut r, vals.iter(), vals.len() + 5).unwrap_err(); - - assert_eq!(small_sample.len(), 5); - assert_eq!(large_sample.len(), vals.len()); - // no randomization happens when amount >= len - assert_eq!(large_sample, vals.iter().collect::>()); - - assert!(small_sample.iter().all(|e| { - **e >= min_val && **e <= max_val - })); - } - #[test] - fn test_sample_slice_boundaries() { - let empty: &[u8] = &[]; - - let mut r = ::test::rng(402); - - // sample 0 items - assert_eq!(&sample_slice(&mut r, empty, 0)[..], [0u8; 0]); - assert_eq!(&sample_slice(&mut r, &[42, 2, 42], 0)[..], [0u8; 0]); - - // sample 1 item - assert_eq!(&sample_slice(&mut r, &[42], 1)[..], [42]); - let v = sample_slice(&mut r, &[1, 42], 1)[0]; - assert!(v == 1 || v == 42); - - // sample "all" the items - let v = sample_slice(&mut r, &[42, 133], 2); - assert!(&v[..] == [42, 133] || v[..] == [133, 42]); - - assert_eq!(&sample_indices_inplace(&mut r, 0, 0)[..], [0usize; 0]); - assert_eq!(&sample_indices_inplace(&mut r, 1, 0)[..], [0usize; 0]); - assert_eq!(&sample_indices_inplace(&mut r, 1, 1)[..], [0]); - - assert_eq!(&sample_indices_cache(&mut r, 0, 0)[..], [0usize; 0]); - assert_eq!(&sample_indices_cache(&mut r, 1, 0)[..], [0usize; 0]); - assert_eq!(&sample_indices_cache(&mut r, 1, 1)[..], [0]); - - // Make sure lucky 777's aren't lucky - let slice = &[42, 777]; - let mut num_42 = 0; - let total = 1000; - for _ in 0..total { - let v = sample_slice(&mut r, slice, 1); - assert_eq!(v.len(), 1); - let v = v[0]; - assert!(v == 42 || v == 777); - if v == 42 { - num_42 += 1; - } - } - let ratio_42 = num_42 as f64 / 1000 as f64; - assert!(0.4 <= ratio_42 || ratio_42 <= 0.6, "{}", ratio_42); - } - - #[test] - fn test_sample_slice() { - let xor_rng = XorShiftRng::from_seed; - - let max_range = 100; - let mut r = ::test::rng(403); - - for length in 1usize..max_range { - let amount = r.gen_range(0, length); - let mut seed = [0u8; 16]; - r.fill(&mut seed); - - // assert that the two index methods give exactly the same result - let inplace = sample_indices_inplace( - &mut xor_rng(seed), length, amount); - let cache = sample_indices_cache( - &mut xor_rng(seed), length, amount); - assert_eq!(inplace, cache); - - // assert the basics work - let regular = sample_indices( - &mut xor_rng(seed), length, amount); - assert_eq!(regular.len(), amount); - assert!(regular.iter().all(|e| *e < length)); - assert_eq!(regular, inplace); - - // also test that sampling the slice works - let vec: Vec = (0..length).collect(); - { - let result = sample_slice(&mut xor_rng(seed), &vec, amount); - assert_eq!(result, regular); - } - - { - let result = sample_slice_ref(&mut xor_rng(seed), &vec, amount); - let expected = regular.iter().map(|v| v).collect::>(); - assert_eq!(result, expected); - } - } - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/tests/bool.rs b/third_party/cargo/vendor/rand-0.5.6/tests/bool.rs deleted file mode 100644 index c4208a0..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/tests/bool.rs +++ /dev/null @@ -1,23 +0,0 @@ -#![no_std] - -extern crate rand; - -use rand::SeedableRng; -use rand::rngs::SmallRng; -use rand::distributions::{Distribution, Bernoulli}; - -/// This test should make sure that we don't accidentally have undefined -/// behavior for large propabilties due to -/// https://github.com/rust-lang/rust/issues/10184. -/// Expressions like `1.0*(u64::MAX as f64) as u64` have to be avoided. -#[test] -fn large_probability() { - let p = 1. - ::core::f64::EPSILON / 2.; - assert!(p < 1.); - let d = Bernoulli::new(p); - let mut rng = SmallRng::from_seed( - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); - for _ in 0..10 { - assert!(d.sample(&mut rng), "extremely unlikely to fail by accident"); - } -} diff --git a/third_party/cargo/vendor/rand-0.5.6/utils/ci/install.sh b/third_party/cargo/vendor/rand-0.5.6/utils/ci/install.sh deleted file mode 100644 index 8e636e1..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/utils/ci/install.sh +++ /dev/null @@ -1,49 +0,0 @@ -# From https://github.com/japaric/trust - -set -ex - -main() { - local target= - if [ $TRAVIS_OS_NAME = linux ]; then - target=x86_64-unknown-linux-musl - sort=sort - else - target=x86_64-apple-darwin - sort=gsort # for `sort --sort-version`, from brew's coreutils. - fi - - # Builds for iOS are done on OSX, but require the specific target to be - # installed. - case $TARGET in - aarch64-apple-ios) - rustup target install aarch64-apple-ios - ;; - armv7-apple-ios) - rustup target install armv7-apple-ios - ;; - armv7s-apple-ios) - rustup target install armv7s-apple-ios - ;; - i386-apple-ios) - rustup target install i386-apple-ios - ;; - x86_64-apple-ios) - rustup target install x86_64-apple-ios - ;; - esac - - # This fetches latest stable release - local tag=$(git ls-remote --tags --refs --exit-code https://github.com/japaric/cross \ - | cut -d/ -f3 \ - | grep -E '^v[0.1.0-9.]+$' \ - | $sort --version-sort \ - | tail -n1) - curl -LSfs https://japaric.github.io/trust/install.sh | \ - sh -s -- \ - --force \ - --git japaric/cross \ - --tag $tag \ - --target $target -} - -main diff --git a/third_party/cargo/vendor/rand-0.5.6/utils/ci/script.sh b/third_party/cargo/vendor/rand-0.5.6/utils/ci/script.sh deleted file mode 100644 index 21188f3..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/utils/ci/script.sh +++ /dev/null @@ -1,29 +0,0 @@ -# Derived from https://github.com/japaric/trust - -set -ex - -main() { - if [ ! -z $DISABLE_TESTS ]; then # tests are disabled - cross build --no-default-features --target $TARGET --release - if [ -z $DISABLE_STD ]; then # std is enabled - cross build --features log,serde1 --target $TARGET - fi - return - fi - - if [ ! -z $NIGHTLY ]; then # have nightly Rust - cross test --tests --no-default-features --features alloc --target $TARGET - cross test --package rand_core --no-default-features --features alloc --target $TARGET - cross test --features serde1,log,nightly,alloc --target $TARGET - cross test --all --benches --target $TARGET - else # have stable Rust - cross test --tests --no-default-features --target $TARGET - cross test --package rand_core --no-default-features --target $TARGET - cross test --features serde1,log --target $TARGET - fi -} - -# we don't run the "test phase" when doing deploys -if [ -z $TRAVIS_TAG ]; then - main -fi diff --git a/third_party/cargo/vendor/rand-0.5.6/utils/ziggurat_tables.py b/third_party/cargo/vendor/rand-0.5.6/utils/ziggurat_tables.py deleted file mode 100755 index 9973b83..0000000 --- a/third_party/cargo/vendor/rand-0.5.6/utils/ziggurat_tables.py +++ /dev/null @@ -1,127 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2013 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# https://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -# This creates the tables used for distributions implemented using the -# ziggurat algorithm in `rand::distributions;`. They are -# (basically) the tables as used in the ZIGNOR variant (Doornik 2005). -# They are changed rarely, so the generated file should be checked in -# to git. -# -# It creates 3 tables: X as in the paper, F which is f(x_i), and -# F_DIFF which is f(x_i) - f(x_{i-1}). The latter two are just cached -# values which is not done in that paper (but is done in other -# variants). Note that the adZigR table is unnecessary because of -# algebra. -# -# It is designed to be compatible with Python 2 and 3. - -from math import exp, sqrt, log, floor -import random - -# The order should match the return value of `tables` -TABLE_NAMES = ['X', 'F'] - -# The actual length of the table is 1 more, to stop -# index-out-of-bounds errors. This should match the bitwise operation -# to find `i` in `zigurrat` in `libstd/rand/mod.rs`. Also the *_R and -# *_V constants below depend on this value. -TABLE_LEN = 256 - -# equivalent to `zigNorInit` in Doornik2005, but generalised to any -# distribution. r = dR, v = dV, f = probability density function, -# f_inv = inverse of f -def tables(r, v, f, f_inv): - # compute the x_i - xvec = [0]*(TABLE_LEN+1) - - xvec[0] = v / f(r) - xvec[1] = r - - for i in range(2, TABLE_LEN): - last = xvec[i-1] - xvec[i] = f_inv(v / last + f(last)) - - # cache the f's - fvec = [0]*(TABLE_LEN+1) - for i in range(TABLE_LEN+1): - fvec[i] = f(xvec[i]) - - return xvec, fvec - -# Distributions -# N(0, 1) -def norm_f(x): - return exp(-x*x/2.0) -def norm_f_inv(y): - return sqrt(-2.0*log(y)) - -NORM_R = 3.6541528853610088 -NORM_V = 0.00492867323399 - -NORM = tables(NORM_R, NORM_V, - norm_f, norm_f_inv) - -# Exp(1) -def exp_f(x): - return exp(-x) -def exp_f_inv(y): - return -log(y) - -EXP_R = 7.69711747013104972 -EXP_V = 0.0039496598225815571993 - -EXP = tables(EXP_R, EXP_V, - exp_f, exp_f_inv) - - -# Output the tables/constants/types - -def render_static(name, type, value): - # no space or - return 'pub static %s: %s =%s;\n' % (name, type, value) - -# static `name`: [`type`, .. `len(values)`] = -# [values[0], ..., values[3], -# values[4], ..., values[7], -# ... ]; -def render_table(name, values): - rows = [] - # 4 values on each row - for i in range(0, len(values), 4): - row = values[i:i+4] - rows.append(', '.join('%.18f' % f for f in row)) - - rendered = '\n [%s]' % ',\n '.join(rows) - return render_static(name, '[f64, .. %d]' % len(values), rendered) - - -with open('ziggurat_tables.rs', 'w') as f: - f.write('''// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// https://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Tables for distributions which are sampled using the ziggurat -// algorithm. Autogenerated by `ziggurat_tables.py`. - -pub type ZigTable = &\'static [f64, .. %d]; -''' % (TABLE_LEN + 1)) - for name, tables, r in [('NORM', NORM, NORM_R), - ('EXP', EXP, EXP_R)]: - f.write(render_static('ZIG_%s_R' % name, 'f64', ' %.18f' % r)) - for (tabname, table) in zip(TABLE_NAMES, tables): - f.write(render_table('ZIG_%s_%s' % (name, tabname), table)) diff --git a/third_party/cargo/vendor/rand_core-0.3.1/BUILD b/third_party/cargo/vendor/rand_core-0.3.1/BUILD index b687d4a..29da36d 100644 --- a/third_party/cargo/vendor/rand_core-0.3.1/BUILD +++ b/third_party/cargo/vendor/rand_core-0.3.1/BUILD @@ -38,8 +38,6 @@ rust_library( ], version = "0.3.1", crate_features = [ - "alloc", - "std", ], ) diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/.cargo-checksum.json b/third_party/cargo/vendor/raw-window-handle-0.3.3/.cargo-checksum.json new file mode 100644 index 0000000..b49bd85 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"05d00b9b9a88c7cdefa84f2e2ef96c0483f982140e48c420f175f3c165739711","Cargo.toml":"358a2ac9c8caf5c03d730b8534dc39938ca6cd53414b87c8292eef4e056daecf","LICENSE":"9c5a80639a57c1c945570e7ebbca0706305849ce3c098021325cca9db2f7acc4","README.md":"cab86df5186877302bfb6f90a49ae53af6141fc9588a4f6d7038658fdf10e7d0","appveyor.yml":"8d80a816ac9c301e7b91ff6797c1279462215b0b02169c0c0ceede261f788dca","rustfmt.toml":"a60f9a6656083027a16746999197d72aa6fd7f906969597cb99ce162177f1700","src/android.rs":"2e5c343443629aa5efaa013719e9e7bd45f67b3ed4094062ac55177184e390f3","src/ios.rs":"45cab84d5e6c0beff712e3889b587895245701fbe5396d0510b0d81396260986","src/lib.rs":"a53c6fa7c4afe037f05d14401effe891dd62ac378ea84235cfe6b43b918839e2","src/macos.rs":"e2ff627ce6f59f14a7669568695f03b7d8f9b7e94f0af7a5aa3b79ff61061ac8","src/unix.rs":"a07b02931d1b237ea1927dfd75000e38e2d7202c35714eba914bb8138686c5cb","src/web.rs":"a65e44fac0490085cdade5ac1b7e3d1e98172100e0f35096ec4a2940fe5095e2","src/windows.rs":"9358f459447b348f480638c36399c1ecfa2897fa3df905ead688862d118b60af"},"package":"0a441a7a6c80ad6473bd4b74ec1c9a4c951794285bf941c2126f607c72e48211"} \ No newline at end of file diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/BUILD b/third_party/cargo/vendor/raw-window-handle-0.3.3/BUILD new file mode 100644 index 0000000..26ae4a5 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/BUILD @@ -0,0 +1,43 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + + +rust_library( + name = "raw_window_handle", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2018", + srcs = glob(["**/*.rs"]), + deps = [ + "//third_party/cargo/vendor/libc-0.2.67:libc", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.3.3", + crate_features = [ + ], +) + diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/CHANGELOG.md b/third_party/cargo/vendor/raw-window-handle-0.3.3/CHANGELOG.md new file mode 100644 index 0000000..a76f393 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/CHANGELOG.md @@ -0,0 +1,39 @@ +# Unreleased + +# 0.3.3 (2019-12-1) + +* Add missing `Hash` implementation for `AndroidHandle`. + +# 0.3.2 (2019-11-29) + +* Add `Hash` implementation for `RawWindowHandle`. + +# 0.3.1 (2019-10-27) + +* Remove `RawWindowHandle`'s `HasRawWindowHandle` implementation, as it was unsound (see [#35](https://github.com/rust-windowing/raw-window-handle/issues/35)) +* Explicitly require that handles within `RawWindowHandle` be valid for the lifetime of the `HasRawWindowHandle` implementation that provided them. + +# 0.3.0 (2019-10-5) + +* **Breaking:** Rename `XLib.surface` to `XLib.window`, as that more accurately represents the underlying type. +* Implement `HasRawWindowHandle` for `RawWindowHandle` +* Add `HINSTANCE` field to `WindowsHandle`. + +# 0.2.0 (2019-09-26) + +* **Breaking:** Rename `X11` to `XLib`. +* Add XCB support. +* Add Web support. +* Add Android support. + +# 0.1.2 (2019-08-13) + +* Fix use of private `_non_exhaustive` field in platform handle structs preventing structs from getting initialized. + +# 0.1.1 (2019-08-13) + +* Flesh out Cargo.toml, adding crates.io info rendering tags. + +# 0.1.0 (2019-08-13) + +* Initial release. diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/Cargo.toml b/third_party/cargo/vendor/raw-window-handle-0.3.3/Cargo.toml new file mode 100644 index 0000000..f7247a3 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/Cargo.toml @@ -0,0 +1,36 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "raw-window-handle" +version = "0.3.3" +authors = ["Osspial "] +description = "Interoperability library for Rust Windowing applications." +documentation = "https://docs.rs/raw-window-handle" +readme = "README.md" +keywords = ["windowing"] +license = "MIT" +repository = "https://github.com/rust-windowing/raw-window-handle" +[package.metadata.docs.rs] +features = ["nightly-docs"] +[dependencies.libc] +version = "0.2" +features = [] + +[features] +nightly-docs = [] +[badges.appveyor] +repository = "rust-windowing/raw-window-handle" + +[badges.travis-ci] +repository = "rust-windowing/raw-window-handle" diff --git a/third_party/cargo/vendor/owning_ref-0.4.1/LICENSE b/third_party/cargo/vendor/raw-window-handle-0.3.3/LICENSE similarity index 94% rename from third_party/cargo/vendor/owning_ref-0.4.1/LICENSE rename to third_party/cargo/vendor/raw-window-handle-0.3.3/LICENSE index dff72d1..be95e0b 100644 --- a/third_party/cargo/vendor/owning_ref-0.4.1/LICENSE +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/LICENSE @@ -1,6 +1,6 @@ -The MIT License (MIT) +MIT License -Copyright (c) 2015 Marvin Löbel +Copyright (c) 2019 Osspial Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/README.md b/third_party/cargo/vendor/raw-window-handle-0.3.3/README.md new file mode 100644 index 0000000..e9d0052 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/README.md @@ -0,0 +1,7 @@ +# `raw-window-handle`: A common windowing interoperability library for Rust +[![Crates.io](https://img.shields.io/crates/v/raw-window-handle.svg?maxAge=2592000)](https://crates.io/crates/raw-window-handle) +[![Docs](https://docs.rs/raw-window-handle/badge.svg)](https://docs.rs/raw-window-handle) +[![Travis Build Status](https://travis-ci.org/rust-windowing/raw-window-handle.svg)](https://travis-ci.org/rust-windowing/raw-window-handle) +[![Appveyor Build Status](https://ci.appveyor.com/api/projects/status/iq3j85x0ruw5y205?svg=true)](https://ci.appveyor.com/project/Osspial/raw-window-handle) + +This library provides standard types for accessing a window's platform-specific raw window handle. This does not provide any utilities for creating and managing windows; instead, it provides a common interface that window creation libraries (e.g. Winit, SDL) can use to easily talk with graphics libraries (e.g. gfx-hal). diff --git a/third_party/cargo/vendor/winit-0.18.1/appveyor.yml b/third_party/cargo/vendor/raw-window-handle-0.3.3/appveyor.yml similarity index 85% rename from third_party/cargo/vendor/winit-0.18.1/appveyor.yml rename to third_party/cargo/vendor/raw-window-handle-0.3.3/appveyor.yml index 4722a5a..050795b 100644 --- a/third_party/cargo/vendor/winit-0.18.1/appveyor.yml +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/appveyor.yml @@ -20,5 +20,3 @@ build: false test_script: - cargo test --verbose - - cargo test --features serde --verbose - - cargo test --features icon_loading --verbose diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/rustfmt.toml b/third_party/cargo/vendor/raw-window-handle-0.3.3/rustfmt.toml new file mode 100644 index 0000000..34503e8 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/rustfmt.toml @@ -0,0 +1 @@ +use_field_init_shorthand=true diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/android.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/android.rs new file mode 100644 index 0000000..abf65dd --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/android.rs @@ -0,0 +1,31 @@ +use core::ptr; +use libc::c_void; + +/// Raw window handle for Android. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::android::AndroidHandle; +/// let handle = AndroidHandle { +/// /* fields */ +/// ..AndroidHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AndroidHandle { + /// A pointer to an ANativeWindow. + pub a_native_window: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl AndroidHandle { + pub fn empty() -> AndroidHandle { + #[allow(deprecated)] + AndroidHandle { + a_native_window: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/ios.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/ios.rs new file mode 100644 index 0000000..03820c2 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/ios.rs @@ -0,0 +1,34 @@ +use core::ptr; +use libc::c_void; + +/// Raw window handle for iOS. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::ios::IOSHandle; +/// let handle = IOSHandle { +/// /* fields */ +/// ..IOSHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct IOSHandle { + pub ui_window: *mut c_void, + pub ui_view: *mut c_void, + pub ui_view_controller: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl IOSHandle { + pub fn empty() -> IOSHandle { + #[allow(deprecated)] + IOSHandle { + ui_window: ptr::null_mut(), + ui_view: ptr::null_mut(), + ui_view_controller: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/lib.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/lib.rs new file mode 100644 index 0000000..6bd8072 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/lib.rs @@ -0,0 +1,194 @@ +//! Interoperability library for Rust Windowing applications. +//! +//! This library provides standard types for accessing a window's platform-specific raw window +//! handle. This does not provide any utilities for creating and managing windows; instead, it +//! provides a common interface that window creation libraries (e.g. Winit, SDL) can use to easily +//! talk with graphics libraries (e.g. gfx-hal). +//! +//! ## Platform handle initialization +//! +//! Each platform handle struct is purposefully non-exhaustive, so that additional fields may be +//! added without breaking backwards compatibility. Each struct provides an `empty` method that may +//! be used along with the struct update syntax to construct it. See each specific struct for +//! examples. +//! +#![cfg_attr(feature = "nightly-docs", feature(doc_cfg))] +#![no_std] + +#[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] +#[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] +pub mod android; +#[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] +#[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "ios"))] +pub mod ios; +#[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "macos")))] +#[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "macos"))] +pub mod macos; +#[cfg_attr( + feature = "nightly-docs", + doc(cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))) +)] +#[cfg_attr( + not(feature = "nightly-docs"), + cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )) +)] +pub mod unix; +#[cfg_attr(feature = "nightly-docs", doc(cfg(target_arch = "wasm32")))] +#[cfg_attr(not(feature = "nightly-docs"), cfg(target_arch = "wasm32"))] +pub mod web; +#[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "windows")))] +#[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "windows"))] +pub mod windows; + +mod platform { + #[cfg(target_os = "android")] + pub use crate::android::*; + #[cfg(target_os = "macos")] + pub use crate::macos::*; + #[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))] + pub use crate::unix::*; + #[cfg(target_os = "windows")] + pub use crate::windows::*; + // mod platform; + #[cfg(target_os = "ios")] + pub use crate::ios::*; + #[cfg(target_arch = "wasm32")] + pub use crate::web::*; +} + +/// Window that wraps around a raw window handle. +/// +/// # Safety guarantees +/// +/// Users can safely assume that non-`null`/`0` fields are valid handles, and it is up to the +/// implementer of this trait to ensure that condition is upheld. However, It is entirely valid +/// behavior for fields within each platform-specific `RawWindowHandle` variant to be `null` or +/// `0`, and appropriate checking should be done before the handle is used. +/// +/// Despite that qualification, implementers should still make a best-effort attempt to fill in all +/// available fields. If an implementation doesn't, and a downstream user needs the field, it should +/// try to derive the field from other fields the implementer *does* provide via whatever methods the +/// platform provides. +/// +/// The exact handles returned by `raw_window_handle` must remain consistent between multiple calls +/// to `raw_window_handle`, and must be valid for at least the lifetime of the `HasRawWindowHandle` +/// implementer. +pub unsafe trait HasRawWindowHandle { + fn raw_window_handle(&self) -> RawWindowHandle; +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum RawWindowHandle { + #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "ios")))] + #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "ios"))] + IOS(ios::IOSHandle), + + #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "macos")))] + #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "macos"))] + MacOS(macos::MacOSHandle), + + #[cfg_attr( + feature = "nightly-docs", + doc(cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))) + )] + #[cfg_attr( + not(feature = "nightly-docs"), + cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )) + )] + Xlib(unix::XlibHandle), + + #[cfg_attr( + feature = "nightly-docs", + doc(cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))) + )] + #[cfg_attr( + not(feature = "nightly-docs"), + cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )) + )] + Xcb(unix::XcbHandle), + + #[cfg_attr( + feature = "nightly-docs", + doc(cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + ))) + )] + #[cfg_attr( + not(feature = "nightly-docs"), + cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" + )) + )] + Wayland(unix::WaylandHandle), + + #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "windows")))] + #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "windows"))] + Windows(windows::WindowsHandle), + + #[cfg_attr(feature = "nightly-docs", doc(cfg(target_arch = "wasm32")))] + #[cfg_attr(not(feature = "nightly-docs"), cfg(target_arch = "wasm32"))] + Web(web::WebHandle), + + #[cfg_attr(feature = "nightly-docs", doc(cfg(target_os = "android")))] + #[cfg_attr(not(feature = "nightly-docs"), cfg(target_os = "android"))] + Android(android::AndroidHandle), + + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + __NonExhaustiveDoNotUse(seal::Seal), +} + +mod seal { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct Seal; +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/macos.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/macos.rs new file mode 100644 index 0000000..9e167c8 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/macos.rs @@ -0,0 +1,33 @@ +use core::ptr; +use libc::c_void; + +/// Raw window handle for macOS. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::macos::MacOSHandle; +/// let handle = MacOSHandle { +/// /* fields */ +/// ..MacOSHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct MacOSHandle { + pub ns_window: *mut c_void, + pub ns_view: *mut c_void, + // TODO: WHAT ABOUT ns_window_controller and ns_view_controller? + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl MacOSHandle { + pub fn empty() -> MacOSHandle { + #[allow(deprecated)] + MacOSHandle { + ns_window: ptr::null_mut(), + ns_view: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/unix.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/unix.rs new file mode 100644 index 0000000..be8d6f8 --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/unix.rs @@ -0,0 +1,98 @@ +use core::ptr; +use libc::{c_ulong, c_void}; + +/// Raw window handle for Xlib. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::unix::XlibHandle; +/// let handle = XlibHandle { +/// /* fields */ +/// ..XlibHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct XlibHandle { + /// An Xlib `Window`. + pub window: c_ulong, + /// A pointer to an Xlib `Display`. + pub display: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +/// Raw window handle for Xcb. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::unix::XcbHandle; +/// let handle = XcbHandle { +/// /* fields */ +/// ..XcbHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct XcbHandle { + /// An X11 `xcb_window_t`. + pub window: u32, // Based on xproto.h + /// A pointer to an X server `xcb_connection_t`. + pub connection: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +/// Raw window handle for Wayland. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::unix::WaylandHandle; +/// let handle = WaylandHandle { +/// /* fields */ +/// ..WaylandHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct WaylandHandle { + /// A pointer to a `wl_surface`. + pub surface: *mut c_void, + /// A pointer to a `wl_display`. + pub display: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl XlibHandle { + pub fn empty() -> XlibHandle { + #[allow(deprecated)] + XlibHandle { + window: 0, + display: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} + +impl XcbHandle { + pub fn empty() -> XcbHandle { + #[allow(deprecated)] + XcbHandle { + window: 0, + connection: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} + +impl WaylandHandle { + pub fn empty() -> WaylandHandle { + #[allow(deprecated)] + WaylandHandle { + surface: ptr::null_mut(), + display: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/web.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/web.rs new file mode 100644 index 0000000..846d78c --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/web.rs @@ -0,0 +1,33 @@ +/// Raw window handle for the web +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::web::WebHandle; +/// let handle = WebHandle { +/// /* fields */ +/// ..WebHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct WebHandle { + /// An ID value inserted into the data attributes of the canvas element as 'raw-handle' + /// + /// When accessing from JS, the attribute will automatically be called rawHandle + /// + /// Each canvas created by the windowing system should be assigned their own unique ID. + /// 0 should be reserved for invalid / null IDs. + pub id: u32, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl WebHandle { + pub fn empty() -> WebHandle { + #[allow(deprecated)] + WebHandle { + id: 0, + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/raw-window-handle-0.3.3/src/windows.rs b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/windows.rs new file mode 100644 index 0000000..365886e --- /dev/null +++ b/third_party/cargo/vendor/raw-window-handle-0.3.3/src/windows.rs @@ -0,0 +1,34 @@ +use core::ptr; +use libc::c_void; + +/// Raw window handle for Windows. +/// +/// ## Construction +/// ``` +/// # use raw_window_handle::windows::WindowsHandle; +/// let handle = WindowsHandle { +/// /* fields */ +/// ..WindowsHandle::empty() +/// }; +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct WindowsHandle { + /// A Win32 HWND handle. + pub hwnd: *mut c_void, + /// The HINSTANCE associated with this type's HWND. + pub hinstance: *mut c_void, + #[doc(hidden)] + #[deprecated = "This field is used to ensure that this struct is non-exhaustive, so that it may be extended in the future. Do not refer to this field."] + pub _non_exhaustive_do_not_use: crate::seal::Seal, +} + +impl WindowsHandle { + pub fn empty() -> WindowsHandle { + #[allow(deprecated)] + WindowsHandle { + hwnd: ptr::null_mut(), + hinstance: ptr::null_mut(), + _non_exhaustive_do_not_use: crate::seal::Seal, + } + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/.cargo-checksum.json b/third_party/cargo/vendor/redox_syscall-0.1.56/.cargo-checksum.json new file mode 100644 index 0000000..aa71729 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"6a30685e5679812735444beae8fbf0637c43cf65d8d7e74a9a44b7172899edd9","LICENSE":"efcfee7981ff72431fffb06925cad00a23dce079ed4354f61030ad5abdb78829","README.md":"9161f18ba7f69b4ca51e844aee8ffb8237513a468c5c3b1f3a5f989044f895ac","src/arch/aarch64.rs":"3c36537214f8e10331d42ce4c7ac57a472db49fed029193c31982279d08bdad5","src/arch/arm.rs":"44ed9097879fce0ebe85d29e25ba378fb3ee7fcd649b569207495ed601c42a1c","src/arch/nonredox.rs":"de54557f642218b34d451fc52fe3cff97e3e4307304ae02a678a900cab96cdb0","src/arch/x86.rs":"e72a7f653c25b1ea5595af7ce991fe0e5c96547e127fc67e4967d60abbe1d3bd","src/arch/x86_64.rs":"4b809fde77985b335b2f53057d0f13debeb3edae2bc3b18bcc7eb0af4b6d8aef","src/call.rs":"b5b53aab18bb91bfef88d82f1708d05e210a30cde141fce0031dad543d988391","src/data.rs":"84f8beb9d40b753a8c1713b922e99ed9913d35e959694b2c849351b1a92d87c9","src/error.rs":"d832a641ccb1baf10315e2e1ce59b12c30d605a526fc65a31f63bb3a92c3a2f7","src/flag.rs":"1e944be3b134d3776725529e2190e2d1548dd67a631838281b8c5bc829523dbe","src/io/dma.rs":"740cd441f844718a14f77c2fe292d29b7c468d686505810d8b3281f9528a6fe7","src/io/io.rs":"1bcb36d1867e9bab6a8186cd6928efe70ae2655e9f9d0dd3def20bc0fb6a82f6","src/io/mmio.rs":"b9fdb37d37a25a48106d60f1a977c541cb5162b20b12507c7dcd6eb3dff0a2c8","src/io/mod.rs":"4df12af3e82e6b5fe22112c9f51552112ee4811b7d1131d2a43d608d8d1cac09","src/io/pio.rs":"219fcd317d6c490a14794ec4db9de3e305c722dda720043c67076bda60632bb8","src/lib.rs":"907de02434902d35346f7e3b03be652a62e9def472cd1845eeca3da7a0c6bbea","src/number.rs":"4718baa58a0f3e6b9b66d1f328cb2a145e9b1f807654c3079a13b226c4085a29","src/scheme/generate.sh":"b022adacb74f2af1470e691341c37acc1582f428e9b8b6b9dccb790dde594b40","src/scheme/mod.rs":"2679272397bf0247e1a4695853465243ca02960feb4ced1124969f67ebd3e3ce","src/scheme/scheme.rs":"879728e4d4e7d8f3057df5a3a6af1636079135652594ee50ca1b665e876be595","src/scheme/scheme_block.rs":"a8ea17b1101548e9b36f6c9000f68fd5438a796069252f948bde7dda44088a7f","src/scheme/scheme_block_mut.rs":"8b881f84a54e2477967d43eb68dac7c578ff6451dba59eba0d517037b2ac4def","src/scheme/scheme_mut.rs":"30f9b0750437b7f55d5bb24da546fd4afcb3c27b0af06d5f681b8f1c4877e7b4","src/tests.rs":"b9d60e419f7e57bb942756e8011e19704cfd46fb6ec96ffa925fb7deb35c5d43"},"package":"2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84"} \ No newline at end of file diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/BUILD b/third_party/cargo/vendor/redox_syscall-0.1.56/BUILD new file mode 100644 index 0000000..e6a883b --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/BUILD @@ -0,0 +1,46 @@ +""" +cargo-raze crate build file. + +DO NOT EDIT! Replaced on runs of cargo-raze +""" +package(default_visibility = [ + # Public for visibility by "@raze__crate__version//" targets. + # + # Prefer access through "//third_party/cargo", which limits external + # visibility to explicit Cargo.toml dependencies. + "//visibility:public", +]) + +licenses([ + "notice", # "MIT" +]) + +load( + "@io_bazel_rules_rust//rust:rust.bzl", + "rust_library", + "rust_binary", + "rust_test", +) + + +alias( + name = "redox_syscall", + actual = ":syscall", +) + +rust_library( + name = "syscall", + crate_root = "src/lib.rs", + crate_type = "lib", + edition = "2015", + srcs = glob(["**/*.rs"]), + deps = [ + ], + rustc_flags = [ + "--cap-lints=allow", + ], + version = "0.1.56", + crate_features = [ + ], +) + diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/Cargo.toml b/third_party/cargo/vendor/redox_syscall-0.1.56/Cargo.toml new file mode 100644 index 0000000..459b06a --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/Cargo.toml @@ -0,0 +1,23 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "redox_syscall" +version = "0.1.56" +authors = ["Jeremy Soller "] +description = "A Rust library to access raw Redox system calls" +documentation = "https://docs.rs/redox_syscall" +license = "MIT" +repository = "https://gitlab.redox-os.org/redox-os/syscall" + +[lib] +name = "syscall" diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/LICENSE b/third_party/cargo/vendor/redox_syscall-0.1.56/LICENSE new file mode 100644 index 0000000..1292bb7 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2017 Redox OS Developers + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/README.md b/third_party/cargo/vendor/redox_syscall-0.1.56/README.md new file mode 100644 index 0000000..244c908 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/README.md @@ -0,0 +1,6 @@ +# syscall +[Redox OS](https://gitlab.redox-os.org/redox-os/redox)'s syscall API + +[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE) +[![crates.io](http://meritbadge.herokuapp.com/redox_syscall)](https://crates.io/crates/redox_syscall) +[![docs.rs](https://docs.rs/redox_syscall/badge.svg)](https://docs.rs/redox_syscall) diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/aarch64.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/aarch64.rs new file mode 100644 index 0000000..662f428 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/aarch64.rs @@ -0,0 +1,77 @@ +use super::error::{Error, Result}; + +pub unsafe fn syscall0(mut a: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a) + : "x0", "x8" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall1(mut a: usize, b: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b) + : "x0", "x8" + : "volatile"); + + Error::demux(a) +} + +// Clobbers all registers - special for clone +pub unsafe fn syscall1_clobber(mut a: usize, b: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b) + : "memory", + "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", + "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", + "x16", "x17","x18", "x19", "x20", "x21", "x22", "x23", + "x24", "x25", "x26", "x27", "x28", "x29", "x30" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall2(mut a: usize, b: usize, c: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b), "{x1}"(c) + : "x0", "x1", "x8" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall3(mut a: usize, b: usize, c: usize, d: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b), "{x1}"(c), "{x2}"(d) + : "x0", "x1", "x2", "x8" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall4(mut a: usize, b: usize, c: usize, d: usize, e: usize) -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b), "{x1}"(c), "{x2}"(d), "{x3}"(e) + : "x0", "x1", "x2", "x3", "x8" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall5(mut a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) + -> Result { + asm!("svc 0" + : "={x0}"(a) + : "{x8}"(a), "{x0}"(b), "{x1}"(c), "{x2}"(d), "{x3}"(e), "{x4}"(f) + : "x0", "x1", "x2", "x3", "x4", "x8" + : "volatile"); + + Error::demux(a) +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/arm.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/arm.rs new file mode 100644 index 0000000..e640f7e --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/arm.rs @@ -0,0 +1,73 @@ +use super::error::{Error, Result}; + +pub unsafe fn syscall0(mut a: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a) + : "memory" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall1(mut a: usize, b: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b) + : "memory" + : "volatile"); + + Error::demux(a) +} + +// Clobbers all registers - special for clone +pub unsafe fn syscall1_clobber(mut a: usize, b: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b) + : "memory", "r0", "r1", "r2", "r3", "r4" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall2(mut a: usize, b: usize, c: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b), "{r1}"(c) + : "memory" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall3(mut a: usize, b: usize, c: usize, d: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b), "{r1}"(c), "{r2}"(d) + : "memory" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall4(mut a: usize, b: usize, c: usize, d: usize, e: usize) -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b), "{r1}"(c), "{r2}"(d), "{r3}"(e) + : "memory" + : "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall5(mut a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) + -> Result { + asm!("swi $$0" + : "={r0}"(a) + : "{r7}"(a), "{r0}"(b), "{r1}"(c), "{r2}"(d), "{r3}"(e), "{r4}"(f) + : "memory" + : "volatile"); + + Error::demux(a) +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/nonredox.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/nonredox.rs new file mode 100644 index 0000000..c99d41a --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/nonredox.rs @@ -0,0 +1,31 @@ +use super::error::{Error, Result, ENOSYS}; + +pub unsafe fn syscall0(_a: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +pub unsafe fn syscall1(_a: usize, _b: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +// Clobbers all registers - special for clone +pub unsafe fn syscall1_clobber(_a: usize, _b: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +pub unsafe fn syscall2(_a: usize, _b: usize, _c: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +pub unsafe fn syscall3(_a: usize, _b: usize, _c: usize, _d: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +pub unsafe fn syscall4(_a: usize, _b: usize, _c: usize, _d: usize, _e: usize) -> Result { + Err(Error::new(ENOSYS)) +} + +pub unsafe fn syscall5(_a: usize, _b: usize, _c: usize, _d: usize, _e: usize, _f: usize) + -> Result { + Err(Error::new(ENOSYS)) +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86.rs new file mode 100644 index 0000000..0cd6409 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86.rs @@ -0,0 +1,73 @@ +use super::error::{Error, Result}; + +pub unsafe fn syscall0(mut a: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall1(mut a: usize, b: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +// Clobbers all registers - special for clone +pub unsafe fn syscall1_clobber(mut a: usize, b: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b) + : "memory", "ebx", "ecx", "edx", "esi", "edi" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall2(mut a: usize, b: usize, c: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b), "{ecx}"(c) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall3(mut a: usize, b: usize, c: usize, d: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall4(mut a: usize, b: usize, c: usize, d: usize, e: usize) -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d), "{esi}"(e) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall5(mut a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) + -> Result { + asm!("int 0x80" + : "={eax}"(a) + : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d), "{esi}"(e), "{edi}"(f) + : "memory" + : "intel", "volatile"); + + Error::demux(a) +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86_64.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86_64.rs new file mode 100644 index 0000000..76c3da1 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/arch/x86_64.rs @@ -0,0 +1,74 @@ +use super::error::{Error, Result}; + +pub unsafe fn syscall0(mut a: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall1(mut a: usize, b: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +// Clobbers all registers - special for clone +pub unsafe fn syscall1_clobber(mut a: usize, b: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b) + : "memory", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", + "r9", "r10", "r11", "r12", "r13", "r14", "r15" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall2(mut a: usize, b: usize, c: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b), "{rsi}"(c) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall3(mut a: usize, b: usize, c: usize, d: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b), "{rsi}"(c), "{rdx}"(d) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall4(mut a: usize, b: usize, c: usize, d: usize, e: usize) -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b), "{rsi}"(c), "{rdx}"(d), "{r10}"(e) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} + +pub unsafe fn syscall5(mut a: usize, b: usize, c: usize, d: usize, e: usize, f: usize) + -> Result { + asm!("syscall" + : "={rax}"(a) + : "{rax}"(a), "{rdi}"(b), "{rsi}"(c), "{rdx}"(d), "{r10}"(e), "{r8}"(f) + : "rcx", "r11", "memory" + : "intel", "volatile"); + + Error::demux(a) +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/call.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/call.rs new file mode 100644 index 0000000..8b56541 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/call.rs @@ -0,0 +1,393 @@ +use super::arch::*; +use super::data::{Map, SigAction, Stat, StatVfs, TimeSpec}; +use super::error::Result; +use super::number::*; + +use core::{mem, ptr}; + +// Signal restorer +extern "C" fn restorer() -> ! { + sigreturn().unwrap(); + unreachable!(); +} + +/// Set the end of the process's heap +/// +/// When `addr` is `0`, this function will return the current break. +/// +/// When `addr` is nonzero, this function will attempt to set the end of the process's +/// heap to `addr` and return the new program break. The new program break should be +/// checked by the allocator, it may not be exactly `addr`, as it may be aligned to a page +/// boundary. +/// +/// On error, `Err(ENOMEM)` will be returned indicating that no memory is available +pub unsafe fn brk(addr: usize) -> Result { + syscall1(SYS_BRK, addr) +} + +/// Change the process's working directory +/// +/// This function will attempt to set the process's working directory to `path`, which can be +/// either a relative, scheme relative, or absolute path. +/// +/// On success, `Ok(0)` will be returned. On error, one of the following errors will be returned. +/// +/// # Errors +/// +/// * `EACCES` - permission is denied for one of the components of `path`, or `path` +/// * `EFAULT` - `path` does not point to the process's addressible memory +/// * `EIO` - an I/O error occurred +/// * `ENOENT` - `path` does not exit +/// * `ENOTDIR` - `path` is not a directory +pub fn chdir>(path: T) -> Result { + unsafe { syscall2(SYS_CHDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } +} + +#[deprecated( + since = "0.1.55", + note = "use fchmod instead" +)] +pub fn chmod>(path: T, mode: usize) -> Result { + unsafe { syscall3(SYS_CHMOD, path.as_ref().as_ptr() as usize, path.as_ref().len(), mode) } +} + +/// Produce a fork of the current process, or a new process thread +pub unsafe fn clone(flags: usize) -> Result { + syscall1_clobber(SYS_CLONE, flags) +} + +/// Close a file +pub fn close(fd: usize) -> Result { + unsafe { syscall1(SYS_CLOSE, fd) } +} + +/// Get the current system time +pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result { + unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) } +} + +/// Copy and transform a file descriptor +pub fn dup(fd: usize, buf: &[u8]) -> Result { + unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) } +} + +/// Copy and transform a file descriptor +pub fn dup2(fd: usize, newfd: usize, buf: &[u8]) -> Result { + unsafe { syscall4(SYS_DUP2, fd, newfd, buf.as_ptr() as usize, buf.len()) } +} + +/// Exit the current process +pub fn exit(status: usize) -> Result { + unsafe { syscall1(SYS_EXIT, status) } +} + +/// Change file permissions +pub fn fchmod(fd: usize, mode: u16) -> Result { + unsafe { syscall2(SYS_FCHMOD, fd, mode as usize) } + +} + +/// Change file ownership +pub fn fchown(fd: usize, uid: u32, gid: u32) -> Result { + unsafe { syscall3(SYS_FCHOWN, fd, uid as usize, gid as usize) } + +} + +/// Change file descriptor flags +pub fn fcntl(fd: usize, cmd: usize, arg: usize) -> Result { + unsafe { syscall3(SYS_FCNTL, fd, cmd, arg) } +} + +/// Replace the current process with a new executable +pub fn fexec(fd: usize, args: &[[usize; 2]], vars: &[[usize; 2]]) -> Result { + unsafe { syscall5(SYS_FEXEC, fd, args.as_ptr() as usize, args.len(), vars.as_ptr() as usize, vars.len()) } +} + +/// Map a file into memory +pub unsafe fn fmap(fd: usize, map: &Map) -> Result { + syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::()) +} + +/// Unmap a memory-mapped file +pub unsafe fn funmap(addr: usize) -> Result { + syscall1(SYS_FUNMAP, addr) +} + +/// Retrieve the canonical path of a file +pub fn fpath(fd: usize, buf: &mut [u8]) -> Result { + unsafe { syscall3(SYS_FPATH, fd, buf.as_mut_ptr() as usize, buf.len()) } +} + +/// Rename a file +pub fn frename>(fd: usize, path: T) -> Result { + unsafe { syscall3(SYS_FRENAME, fd, path.as_ref().as_ptr() as usize, path.as_ref().len()) } +} + +/// Get metadata about a file +pub fn fstat(fd: usize, stat: &mut Stat) -> Result { + unsafe { syscall3(SYS_FSTAT, fd, stat as *mut Stat as usize, mem::size_of::()) } +} + +/// Get metadata about a filesystem +pub fn fstatvfs(fd: usize, stat: &mut StatVfs) -> Result { + unsafe { syscall3(SYS_FSTATVFS, fd, stat as *mut StatVfs as usize, mem::size_of::()) } +} + +/// Sync a file descriptor to its underlying medium +pub fn fsync(fd: usize) -> Result { + unsafe { syscall1(SYS_FSYNC, fd) } +} + +/// Truncate or extend a file to a specified length +pub fn ftruncate(fd: usize, len: usize) -> Result { + unsafe { syscall2(SYS_FTRUNCATE, fd, len) } +} + +// Change modify and/or access times +pub fn futimens(fd: usize, times: &[TimeSpec]) -> Result { + unsafe { syscall3(SYS_FUTIMENS, fd, times.as_ptr() as usize, times.len() * mem::size_of::()) } +} + +/// Fast userspace mutex +pub unsafe fn futex(addr: *mut i32, op: usize, val: i32, val2: usize, addr2: *mut i32) + -> Result { + syscall5(SYS_FUTEX, addr as usize, op, (val as isize) as usize, val2, addr2 as usize) +} + +/// Get the current working directory +pub fn getcwd(buf: &mut [u8]) -> Result { + unsafe { syscall2(SYS_GETCWD, buf.as_mut_ptr() as usize, buf.len()) } +} + +/// Get the effective group ID +pub fn getegid() -> Result { + unsafe { syscall0(SYS_GETEGID) } +} + +/// Get the effective namespace +pub fn getens() -> Result { + unsafe { syscall0(SYS_GETENS) } +} + +/// Get the effective user ID +pub fn geteuid() -> Result { + unsafe { syscall0(SYS_GETEUID) } +} + +/// Get the current group ID +pub fn getgid() -> Result { + unsafe { syscall0(SYS_GETGID) } +} + +/// Get the current namespace +pub fn getns() -> Result { + unsafe { syscall0(SYS_GETNS) } +} + +/// Get the current process ID +pub fn getpid() -> Result { + unsafe { syscall0(SYS_GETPID) } +} + +/// Get the process group ID +pub fn getpgid(pid: usize) -> Result { + unsafe { syscall1(SYS_GETPGID, pid) } +} + +/// Get the parent process ID +pub fn getppid() -> Result { + unsafe { syscall0(SYS_GETPPID) } +} + +/// Get the current user ID +pub fn getuid() -> Result { + unsafe { syscall0(SYS_GETUID) } +} + +/// Set the I/O privilege level +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +/// * `EINVAL` - `level > 3` +pub unsafe fn iopl(level: usize) -> Result { + syscall1(SYS_IOPL, level) +} + +/// Send a signal `sig` to the process identified by `pid` +pub fn kill(pid: usize, sig: usize) -> Result { + unsafe { syscall2(SYS_KILL, pid, sig) } +} + +/// Create a link to a file +pub unsafe fn link(old: *const u8, new: *const u8) -> Result { + syscall2(SYS_LINK, old as usize, new as usize) +} + +/// Seek to `offset` bytes in a file descriptor +pub fn lseek(fd: usize, offset: isize, whence: usize) -> Result { + unsafe { syscall3(SYS_LSEEK, fd, offset as usize, whence) } +} + +/// Make a new scheme namespace +pub fn mkns(schemes: &[[usize; 2]]) -> Result { + unsafe { syscall2(SYS_MKNS, schemes.as_ptr() as usize, schemes.len()) } +} + +/// Change mapping flags +pub unsafe fn mprotect(addr: usize, size: usize, flags: usize) -> Result { + syscall3(SYS_MPROTECT, addr, size, flags) +} + +/// Sleep for the time specified in `req` +pub fn nanosleep(req: &TimeSpec, rem: &mut TimeSpec) -> Result { + unsafe { syscall2(SYS_NANOSLEEP, req as *const TimeSpec as usize, + rem as *mut TimeSpec as usize) } +} + +/// Open a file +pub fn open>(path: T, flags: usize) -> Result { + unsafe { syscall3(SYS_OPEN, path.as_ref().as_ptr() as usize, path.as_ref().len(), flags) } +} + +/// Allocate pages, linearly in physical memory +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +/// * `ENOMEM` - the system has run out of available memory +pub unsafe fn physalloc(size: usize) -> Result { + syscall1(SYS_PHYSALLOC, size) +} + +/// Free physically allocated pages +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +pub unsafe fn physfree(physical_address: usize, size: usize) -> Result { + syscall2(SYS_PHYSFREE, physical_address, size) +} + +/// Map physical memory to virtual memory +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +pub unsafe fn physmap(physical_address: usize, size: usize, flags: usize) -> Result { + syscall3(SYS_PHYSMAP, physical_address, size, flags) +} + +/// Unmap previously mapped physical memory +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +/// * `EFAULT` - `virtual_address` has not been mapped +pub unsafe fn physunmap(virtual_address: usize) -> Result { + syscall1(SYS_PHYSUNMAP, virtual_address) +} + +/// Create a pair of file descriptors referencing the read and write ends of a pipe +pub fn pipe2(fds: &mut [usize; 2], flags: usize) -> Result { + unsafe { syscall2(SYS_PIPE2, fds.as_ptr() as usize, flags) } +} + +/// Read from a file descriptor into a buffer +pub fn read(fd: usize, buf: &mut [u8]) -> Result { + unsafe { syscall3(SYS_READ, fd, buf.as_mut_ptr() as usize, buf.len()) } +} + +/// Remove a directory +pub fn rmdir>(path: T) -> Result { + unsafe { syscall2(SYS_RMDIR, path.as_ref().as_ptr() as usize, path.as_ref().len()) } +} + +/// Set the process group ID +pub fn setpgid(pid: usize, pgid: usize) -> Result { + unsafe { syscall2(SYS_SETPGID, pid, pgid) } +} + +/// Set the current process group IDs +pub fn setregid(rgid: usize, egid: usize) -> Result { + unsafe { syscall2(SYS_SETREGID, rgid, egid) } +} + +/// Make a new scheme namespace +pub fn setrens(rns: usize, ens: usize) -> Result { + unsafe { syscall2(SYS_SETRENS, rns, ens) } +} + +/// Set the current process user IDs +pub fn setreuid(ruid: usize, euid: usize) -> Result { + unsafe { syscall2(SYS_SETREUID, ruid, euid) } +} + +/// Set up a signal handler +pub fn sigaction(sig: usize, act: Option<&SigAction>, oldact: Option<&mut SigAction>) -> Result { + unsafe { syscall4(SYS_SIGACTION, sig, + act.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, + oldact.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize, + restorer as usize) } +} + +/// Get and/or set signal masks +pub fn sigprocmask(how: usize, set: Option<&[u64; 2]>, oldset: Option<&mut [u64; 2]>) -> Result { + unsafe { syscall3(SYS_SIGPROCMASK, how, + set.map(|x| x as *const _).unwrap_or_else(ptr::null) as usize, + oldset.map(|x| x as *mut _).unwrap_or_else(ptr::null_mut) as usize) } +} + +// Return from signal handler +pub fn sigreturn() -> Result { + unsafe { syscall0(SYS_SIGRETURN) } +} + +/// Set the file mode creation mask +pub fn umask(mask: usize) -> Result { + unsafe { syscall1(SYS_UMASK, mask) } +} + +/// Remove a file +pub fn unlink>(path: T) -> Result { + unsafe { syscall2(SYS_UNLINK, path.as_ref().as_ptr() as usize, path.as_ref().len()) } +} + +/// Convert a virtual address to a physical one +/// +/// # Errors +/// +/// * `EPERM` - `uid != 0` +pub unsafe fn virttophys(virtual_address: usize) -> Result { + syscall1(SYS_VIRTTOPHYS, virtual_address) +} + +/// Check if a child process has exited or received a signal +pub fn waitpid(pid: usize, status: &mut usize, options: usize) -> Result { + unsafe { syscall3(SYS_WAITPID, pid, status as *mut usize as usize, options) } +} + +/// Write a buffer to a file descriptor +/// +/// The kernel will attempt to write the bytes in `buf` to the file descriptor `fd`, returning +/// either an `Err`, explained below, or `Ok(count)` where `count` is the number of bytes which +/// were written. +/// +/// # Errors +/// +/// * `EAGAIN` - the file descriptor was opened with `O_NONBLOCK` and writing would block +/// * `EBADF` - the file descriptor is not valid or is not open for writing +/// * `EFAULT` - `buf` does not point to the process's addressible memory +/// * `EIO` - an I/O error occurred +/// * `ENOSPC` - the device containing the file descriptor has no room for data +/// * `EPIPE` - the file descriptor refers to a pipe or socket whose reading end is closed +pub fn write(fd: usize, buf: &[u8]) -> Result { + unsafe { syscall3(SYS_WRITE, fd, buf.as_ptr() as usize, buf.len()) } +} + +/// Yield the process's time slice to the kernel +/// +/// This function will return Ok(0) on success +pub fn sched_yield() -> Result { + unsafe { syscall0(SYS_YIELD) } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/data.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/data.rs new file mode 100644 index 0000000..f2290e0 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/data.rs @@ -0,0 +1,309 @@ +use core::ops::{Deref, DerefMut}; +use core::{mem, slice}; + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct Event { + pub id: usize, + pub flags: usize, + pub data: usize +} + +impl Deref for Event { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const Event as *const u8, mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for Event { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut Event as *mut u8, mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct ITimerSpec { + pub it_interval: TimeSpec, + pub it_value: TimeSpec, +} + +impl Deref for ITimerSpec { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const ITimerSpec as *const u8, + mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for ITimerSpec { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut ITimerSpec as *mut u8, + mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct Map { + pub offset: usize, + pub size: usize, + pub flags: usize, +} + +impl Deref for Map { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const Map as *const u8, mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for Map { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut Map as *mut u8, mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct Packet { + pub id: u64, + pub pid: usize, + pub uid: u32, + pub gid: u32, + pub a: usize, + pub b: usize, + pub c: usize, + pub d: usize +} + +impl Deref for Packet { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const Packet as *const u8, mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for Packet { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut Packet as *mut u8, mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug)] +#[repr(C)] +pub struct SigAction { + pub sa_handler: extern "C" fn(usize), + pub sa_mask: [u64; 2], + pub sa_flags: usize, +} + +impl Default for SigAction { + fn default() -> Self { + Self { + sa_handler: unsafe { mem::transmute(0usize) }, + sa_mask: [0; 2], + sa_flags: 0, + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct Stat { + pub st_dev: u64, + pub st_ino: u64, + pub st_mode: u16, + pub st_nlink: u32, + pub st_uid: u32, + pub st_gid: u32, + pub st_size: u64, + pub st_blksize: u32, + pub st_blocks: u64, + pub st_mtime: u64, + pub st_mtime_nsec: u32, + pub st_atime: u64, + pub st_atime_nsec: u32, + pub st_ctime: u64, + pub st_ctime_nsec: u32, +} + +impl Deref for Stat { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const Stat as *const u8, + mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for Stat { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut Stat as *mut u8, + mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +pub struct StatVfs { + pub f_bsize: u32, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, +} + +impl Deref for StatVfs { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const StatVfs as *const u8, + mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for StatVfs { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut StatVfs as *mut u8, + mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq)] +#[repr(C)] +pub struct TimeSpec { + pub tv_sec: i64, + pub tv_nsec: i32, +} + +impl Deref for TimeSpec { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const TimeSpec as *const u8, + mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for TimeSpec { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut TimeSpec as *mut u8, + mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Copy, Clone, Debug, Default)] +#[repr(C)] +#[cfg(target_arch = "x86_64")] +pub struct IntRegisters { + pub r15: usize, + pub r14: usize, + pub r13: usize, + pub r12: usize, + pub rbp: usize, + pub rbx: usize, + pub r11: usize, + pub r10: usize, + pub r9: usize, + pub r8: usize, + pub rax: usize, + pub rcx: usize, + pub rdx: usize, + pub rsi: usize, + pub rdi: usize, + // pub orig_rax: usize, + pub rip: usize, + pub cs: usize, + pub eflags: usize, + pub rsp: usize, + pub ss: usize, + pub fs_base: usize, + pub gs_base: usize, + pub ds: usize, + pub es: usize, + pub fs: usize, + pub gs: usize +} + +impl Deref for IntRegisters { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const IntRegisters as *const u8, mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for IntRegisters { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut IntRegisters as *mut u8, mem::size_of::()) as &mut [u8] + } + } +} + +#[derive(Clone, Copy)] +#[repr(C)] +#[cfg(target_arch = "x86_64")] +pub struct FloatRegisters { + pub cwd: u16, + pub swd: u16, + pub ftw: u16, + pub fop: u16, + pub rip: u64, + pub rdp: u64, + pub mxcsr: u32, + pub mxcr_mask: u32, + pub st_space: [u32; 32], + pub xmm_space: [u32; 64] +} + +impl Default for FloatRegisters { + fn default() -> Self { + // xmm_space is not Default until const generics + unsafe { mem::zeroed() } + } +} + +impl Deref for FloatRegisters { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + slice::from_raw_parts(self as *const FloatRegisters as *const u8, mem::size_of::()) as &[u8] + } + } +} + +impl DerefMut for FloatRegisters { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + slice::from_raw_parts_mut(self as *mut FloatRegisters as *mut u8, mem::size_of::()) as &mut [u8] + } + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/error.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/error.rs new file mode 100644 index 0000000..fde4796 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/error.rs @@ -0,0 +1,311 @@ +use core::{fmt, result}; + +#[derive(Eq, PartialEq)] +pub struct Error { + pub errno: i32, +} + +pub type Result = result::Result; + +impl Error { + pub fn new(errno: i32) -> Error { + Error { errno: errno } + } + + pub fn mux(result: Result) -> usize { + match result { + Ok(value) => value, + Err(error) => -error.errno as usize, + } + } + + pub fn demux(value: usize) -> Result { + let errno = -(value as i32); + if errno >= 1 && errno < STR_ERROR.len() as i32 { + Err(Error::new(errno)) + } else { + Ok(value) + } + } + + pub fn text(&self) -> &'static str { + STR_ERROR.get(self.errno as usize).map(|&x| x).unwrap_or("Unknown Error") + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { + f.write_str(self.text()) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { + f.write_str(self.text()) + } +} + +pub const EPERM: i32 = 1; /* Operation not permitted */ +pub const ENOENT: i32 = 2; /* No such file or directory */ +pub const ESRCH: i32 = 3; /* No such process */ +pub const EINTR: i32 = 4; /* Interrupted system call */ +pub const EIO: i32 = 5; /* I/O error */ +pub const ENXIO: i32 = 6; /* No such device or address */ +pub const E2BIG: i32 = 7; /* Argument list too long */ +pub const ENOEXEC: i32 = 8; /* Exec format error */ +pub const EBADF: i32 = 9; /* Bad file number */ +pub const ECHILD: i32 = 10; /* No child processes */ +pub const EAGAIN: i32 = 11; /* Try again */ +pub const ENOMEM: i32 = 12; /* Out of memory */ +pub const EACCES: i32 = 13; /* Permission denied */ +pub const EFAULT: i32 = 14; /* Bad address */ +pub const ENOTBLK: i32 = 15; /* Block device required */ +pub const EBUSY: i32 = 16; /* Device or resource busy */ +pub const EEXIST: i32 = 17; /* File exists */ +pub const EXDEV: i32 = 18; /* Cross-device link */ +pub const ENODEV: i32 = 19; /* No such device */ +pub const ENOTDIR: i32 = 20; /* Not a directory */ +pub const EISDIR: i32 = 21; /* Is a directory */ +pub const EINVAL: i32 = 22; /* Invalid argument */ +pub const ENFILE: i32 = 23; /* File table overflow */ +pub const EMFILE: i32 = 24; /* Too many open files */ +pub const ENOTTY: i32 = 25; /* Not a typewriter */ +pub const ETXTBSY: i32 = 26; /* Text file busy */ +pub const EFBIG: i32 = 27; /* File too large */ +pub const ENOSPC: i32 = 28; /* No space left on device */ +pub const ESPIPE: i32 = 29; /* Illegal seek */ +pub const EROFS: i32 = 30; /* Read-only file system */ +pub const EMLINK: i32 = 31; /* Too many links */ +pub const EPIPE: i32 = 32; /* Broken pipe */ +pub const EDOM: i32 = 33; /* Math argument out of domain of func */ +pub const ERANGE: i32 = 34; /* Math result not representable */ +pub const EDEADLK: i32 = 35; /* Resource deadlock would occur */ +pub const ENAMETOOLONG: i32 = 36; /* File name too long */ +pub const ENOLCK: i32 = 37; /* No record locks available */ +pub const ENOSYS: i32 = 38; /* Function not implemented */ +pub const ENOTEMPTY: i32 = 39; /* Directory not empty */ +pub const ELOOP: i32 = 40; /* Too many symbolic links encountered */ +pub const EWOULDBLOCK: i32 = 41; /* Operation would block */ +pub const ENOMSG: i32 = 42; /* No message of desired type */ +pub const EIDRM: i32 = 43; /* Identifier removed */ +pub const ECHRNG: i32 = 44; /* Channel number out of range */ +pub const EL2NSYNC: i32 = 45; /* Level 2 not synchronized */ +pub const EL3HLT: i32 = 46; /* Level 3 halted */ +pub const EL3RST: i32 = 47; /* Level 3 reset */ +pub const ELNRNG: i32 = 48; /* Link number out of range */ +pub const EUNATCH: i32 = 49; /* Protocol driver not attached */ +pub const ENOCSI: i32 = 50; /* No CSI structure available */ +pub const EL2HLT: i32 = 51; /* Level 2 halted */ +pub const EBADE: i32 = 52; /* Invalid exchange */ +pub const EBADR: i32 = 53; /* Invalid request descriptor */ +pub const EXFULL: i32 = 54; /* Exchange full */ +pub const ENOANO: i32 = 55; /* No anode */ +pub const EBADRQC: i32 = 56; /* Invalid request code */ +pub const EBADSLT: i32 = 57; /* Invalid slot */ +pub const EDEADLOCK: i32 = 58; /* Resource deadlock would occur */ +pub const EBFONT: i32 = 59; /* Bad font file format */ +pub const ENOSTR: i32 = 60; /* Device not a stream */ +pub const ENODATA: i32 = 61; /* No data available */ +pub const ETIME: i32 = 62; /* Timer expired */ +pub const ENOSR: i32 = 63; /* Out of streams resources */ +pub const ENONET: i32 = 64; /* Machine is not on the network */ +pub const ENOPKG: i32 = 65; /* Package not installed */ +pub const EREMOTE: i32 = 66; /* Object is remote */ +pub const ENOLINK: i32 = 67; /* Link has been severed */ +pub const EADV: i32 = 68; /* Advertise error */ +pub const ESRMNT: i32 = 69; /* Srmount error */ +pub const ECOMM: i32 = 70; /* Communication error on send */ +pub const EPROTO: i32 = 71; /* Protocol error */ +pub const EMULTIHOP: i32 = 72; /* Multihop attempted */ +pub const EDOTDOT: i32 = 73; /* RFS specific error */ +pub const EBADMSG: i32 = 74; /* Not a data message */ +pub const EOVERFLOW: i32 = 75; /* Value too large for defined data type */ +pub const ENOTUNIQ: i32 = 76; /* Name not unique on network */ +pub const EBADFD: i32 = 77; /* File descriptor in bad state */ +pub const EREMCHG: i32 = 78; /* Remote address changed */ +pub const ELIBACC: i32 = 79; /* Can not access a needed shared library */ +pub const ELIBBAD: i32 = 80; /* Accessing a corrupted shared library */ +pub const ELIBSCN: i32 = 81; /* .lib section in a.out corrupted */ +pub const ELIBMAX: i32 = 82; /* Attempting to link in too many shared libraries */ +pub const ELIBEXEC: i32 = 83; /* Cannot exec a shared library directly */ +pub const EILSEQ: i32 = 84; /* Illegal byte sequence */ +pub const ERESTART: i32 = 85; /* Interrupted system call should be restarted */ +pub const ESTRPIPE: i32 = 86; /* Streams pipe error */ +pub const EUSERS: i32 = 87; /* Too many users */ +pub const ENOTSOCK: i32 = 88; /* Socket operation on non-socket */ +pub const EDESTADDRREQ: i32 = 89; /* Destination address required */ +pub const EMSGSIZE: i32 = 90; /* Message too long */ +pub const EPROTOTYPE: i32 = 91; /* Protocol wrong type for socket */ +pub const ENOPROTOOPT: i32 = 92; /* Protocol not available */ +pub const EPROTONOSUPPORT: i32 = 93; /* Protocol not supported */ +pub const ESOCKTNOSUPPORT: i32 = 94; /* Socket type not supported */ +pub const EOPNOTSUPP: i32 = 95; /* Operation not supported on transport endpoint */ +pub const EPFNOSUPPORT: i32 = 96; /* Protocol family not supported */ +pub const EAFNOSUPPORT: i32 = 97; /* Address family not supported by protocol */ +pub const EADDRINUSE: i32 = 98; /* Address already in use */ +pub const EADDRNOTAVAIL: i32 = 99; /* Cannot assign requested address */ +pub const ENETDOWN: i32 = 100; /* Network is down */ +pub const ENETUNREACH: i32 = 101; /* Network is unreachable */ +pub const ENETRESET: i32 = 102; /* Network dropped connection because of reset */ +pub const ECONNABORTED: i32 = 103; /* Software caused connection abort */ +pub const ECONNRESET: i32 = 104; /* Connection reset by peer */ +pub const ENOBUFS: i32 = 105; /* No buffer space available */ +pub const EISCONN: i32 = 106; /* Transport endpoint is already connected */ +pub const ENOTCONN: i32 = 107; /* Transport endpoint is not connected */ +pub const ESHUTDOWN: i32 = 108; /* Cannot send after transport endpoint shutdown */ +pub const ETOOMANYREFS: i32 = 109; /* Too many references: cannot splice */ +pub const ETIMEDOUT: i32 = 110; /* Connection timed out */ +pub const ECONNREFUSED: i32 = 111; /* Connection refused */ +pub const EHOSTDOWN: i32 = 112; /* Host is down */ +pub const EHOSTUNREACH: i32 = 113; /* No route to host */ +pub const EALREADY: i32 = 114; /* Operation already in progress */ +pub const EINPROGRESS: i32 = 115; /* Operation now in progress */ +pub const ESTALE: i32 = 116; /* Stale NFS file handle */ +pub const EUCLEAN: i32 = 117; /* Structure needs cleaning */ +pub const ENOTNAM: i32 = 118; /* Not a XENIX named type file */ +pub const ENAVAIL: i32 = 119; /* No XENIX semaphores available */ +pub const EISNAM: i32 = 120; /* Is a named type file */ +pub const EREMOTEIO: i32 = 121; /* Remote I/O error */ +pub const EDQUOT: i32 = 122; /* Quota exceeded */ +pub const ENOMEDIUM: i32 = 123; /* No medium found */ +pub const EMEDIUMTYPE: i32 = 124; /* Wrong medium type */ +pub const ECANCELED: i32 = 125; /* Operation Canceled */ +pub const ENOKEY: i32 = 126; /* Required key not available */ +pub const EKEYEXPIRED: i32 = 127; /* Key has expired */ +pub const EKEYREVOKED: i32 = 128; /* Key has been revoked */ +pub const EKEYREJECTED: i32 = 129; /* Key was rejected by service */ +pub const EOWNERDEAD: i32 = 130; /* Owner died */ +pub const ENOTRECOVERABLE: i32 = 131; /* State not recoverable */ + +pub static STR_ERROR: [&'static str; 132] = ["Success", + "Operation not permitted", + "No such file or directory", + "No such process", + "Interrupted system call", + "I/O error", + "No such device or address", + "Argument list too long", + "Exec format error", + "Bad file number", + "No child processes", + "Try again", + "Out of memory", + "Permission denied", + "Bad address", + "Block device required", + "Device or resource busy", + "File exists", + "Cross-device link", + "No such device", + "Not a directory", + "Is a directory", + "Invalid argument", + "File table overflow", + "Too many open files", + "Not a typewriter", + "Text file busy", + "File too large", + "No space left on device", + "Illegal seek", + "Read-only file system", + "Too many links", + "Broken pipe", + "Math argument out of domain of func", + "Math result not representable", + "Resource deadlock would occur", + "File name too long", + "No record locks available", + "Function not implemented", + "Directory not empty", + "Too many symbolic links encountered", + "Operation would block", + "No message of desired type", + "Identifier removed", + "Channel number out of range", + "Level 2 not synchronized", + "Level 3 halted", + "Level 3 reset", + "Link number out of range", + "Protocol driver not attached", + "No CSI structure available", + "Level 2 halted", + "Invalid exchange", + "Invalid request descriptor", + "Exchange full", + "No anode", + "Invalid request code", + "Invalid slot", + "Resource deadlock would occur", + "Bad font file format", + "Device not a stream", + "No data available", + "Timer expired", + "Out of streams resources", + "Machine is not on the network", + "Package not installed", + "Object is remote", + "Link has been severed", + "Advertise error", + "Srmount error", + "Communication error on send", + "Protocol error", + "Multihop attempted", + "RFS specific error", + "Not a data message", + "Value too large for defined data type", + "Name not unique on network", + "File descriptor in bad state", + "Remote address changed", + "Can not access a needed shared library", + "Accessing a corrupted shared library", + ".lib section in a.out corrupted", + "Attempting to link in too many shared libraries", + "Cannot exec a shared library directly", + "Illegal byte sequence", + "Interrupted system call should be restarted", + "Streams pipe error", + "Too many users", + "Socket operation on non-socket", + "Destination address required", + "Message too long", + "Protocol wrong type for socket", + "Protocol not available", + "Protocol not supported", + "Socket type not supported", + "Operation not supported on transport endpoint", + "Protocol family not supported", + "Address family not supported by protocol", + "Address already in use", + "Cannot assign requested address", + "Network is down", + "Network is unreachable", + "Network dropped connection because of reset", + "Software caused connection abort", + "Connection reset by peer", + "No buffer space available", + "Transport endpoint is already connected", + "Transport endpoint is not connected", + "Cannot send after transport endpoint shutdown", + "Too many references: cannot splice", + "Connection timed out", + "Connection refused", + "Host is down", + "No route to host", + "Operation already in progress", + "Operation now in progress", + "Stale NFS file handle", + "Structure needs cleaning", + "Not a XENIX named type file", + "No XENIX semaphores available", + "Is a named type file", + "Remote I/O error", + "Quota exceeded", + "No medium found", + "Wrong medium type", + "Operation Canceled", + "Required key not available", + "Key has expired", + "Key has been revoked", + "Key was rejected by service", + "Owner died", + "State not recoverable"]; diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/flag.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/flag.rs new file mode 100644 index 0000000..e6c4cbf --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/flag.rs @@ -0,0 +1,169 @@ +pub const CLONE_VM: usize = 0x100; +pub const CLONE_FS: usize = 0x200; +pub const CLONE_FILES: usize = 0x400; +pub const CLONE_SIGHAND: usize = 0x800; +pub const CLONE_VFORK: usize = 0x4000; +pub const CLONE_THREAD: usize = 0x10000; +pub const CLONE_STACK: usize = 0x1000_0000; + +pub const CLOCK_REALTIME: usize = 1; +pub const CLOCK_MONOTONIC: usize = 4; + +pub const EVENT_NONE: usize = 0; +pub const EVENT_READ: usize = 1; +pub const EVENT_WRITE: usize = 2; + +pub const F_DUPFD: usize = 0; +pub const F_GETFD: usize = 1; +pub const F_SETFD: usize = 2; +pub const F_GETFL: usize = 3; +pub const F_SETFL: usize = 4; + +pub const FUTEX_WAIT: usize = 0; +pub const FUTEX_WAKE: usize = 1; +pub const FUTEX_REQUEUE: usize = 2; + +pub const MAP_SHARED: usize = 0x0001; +pub const MAP_PRIVATE: usize = 0x0002; + +pub const MODE_TYPE: u16 = 0xF000; +pub const MODE_DIR: u16 = 0x4000; +pub const MODE_FILE: u16 = 0x8000; +pub const MODE_SYMLINK: u16 = 0xA000; +pub const MODE_FIFO: u16 = 0x1000; +pub const MODE_CHR: u16 = 0x2000; + +pub const MODE_PERM: u16 = 0x0FFF; +pub const MODE_SETUID: u16 = 0o4000; +pub const MODE_SETGID: u16 = 0o2000; + +pub const O_RDONLY: usize = 0x0001_0000; +pub const O_WRONLY: usize = 0x0002_0000; +pub const O_RDWR: usize = 0x0003_0000; +pub const O_NONBLOCK: usize = 0x0004_0000; +pub const O_APPEND: usize = 0x0008_0000; +pub const O_SHLOCK: usize = 0x0010_0000; +pub const O_EXLOCK: usize = 0x0020_0000; +pub const O_ASYNC: usize = 0x0040_0000; +pub const O_FSYNC: usize = 0x0080_0000; +pub const O_CLOEXEC: usize = 0x0100_0000; +pub const O_CREAT: usize = 0x0200_0000; +pub const O_TRUNC: usize = 0x0400_0000; +pub const O_EXCL: usize = 0x0800_0000; +pub const O_DIRECTORY: usize = 0x1000_0000; +pub const O_STAT: usize = 0x2000_0000; +pub const O_SYMLINK: usize = 0x4000_0000; +pub const O_NOFOLLOW: usize = 0x8000_0000; +pub const O_ACCMODE: usize = O_RDONLY | O_WRONLY | O_RDWR; + +pub const PHYSMAP_WRITE: usize = 0x0000_0001; +pub const PHYSMAP_WRITE_COMBINE: usize = 0x0000_0002; +pub const PHYSMAP_NO_CACHE: usize = 0x0000_0004; + +pub const PROT_NONE: usize = 0x0000_0000; +pub const PROT_EXEC: usize = 0x0001_0000; +pub const PROT_WRITE: usize = 0x0002_0000; +pub const PROT_READ: usize = 0x0004_0000; + +pub const PTRACE_CONT: u8 = 0b0000_0001; +pub const PTRACE_SINGLESTEP: u8 = 0b0000_0010; +pub const PTRACE_SYSCALL: u8 = 0b0000_0011; +pub const PTRACE_WAIT: u8 = 0b0000_0100; +pub const PTRACE_OPERATIONMASK: u8 = 0b0000_1111; +pub const PTRACE_SYSEMU: u8 = 0b0001_0000; + +pub const SEEK_SET: usize = 0; +pub const SEEK_CUR: usize = 1; +pub const SEEK_END: usize = 2; + +pub const SIGHUP: usize = 1; +pub const SIGINT: usize = 2; +pub const SIGQUIT: usize = 3; +pub const SIGILL: usize = 4; +pub const SIGTRAP: usize = 5; +pub const SIGABRT: usize = 6; +pub const SIGBUS: usize = 7; +pub const SIGFPE: usize = 8; +pub const SIGKILL: usize = 9; +pub const SIGUSR1: usize = 10; +pub const SIGSEGV: usize = 11; +pub const SIGUSR2: usize = 12; +pub const SIGPIPE: usize = 13; +pub const SIGALRM: usize = 14; +pub const SIGTERM: usize = 15; +pub const SIGSTKFLT: usize= 16; +pub const SIGCHLD: usize = 17; +pub const SIGCONT: usize = 18; +pub const SIGSTOP: usize = 19; +pub const SIGTSTP: usize = 20; +pub const SIGTTIN: usize = 21; +pub const SIGTTOU: usize = 22; +pub const SIGURG: usize = 23; +pub const SIGXCPU: usize = 24; +pub const SIGXFSZ: usize = 25; +pub const SIGVTALRM: usize= 26; +pub const SIGPROF: usize = 27; +pub const SIGWINCH: usize = 28; +pub const SIGIO: usize = 29; +pub const SIGPWR: usize = 30; +pub const SIGSYS: usize = 31; + +pub const SIG_DFL: usize = 0; +pub const SIG_IGN: usize = 1; + +pub const SIG_BLOCK: usize = 0; +pub const SIG_UNBLOCK: usize = 1; +pub const SIG_SETMASK: usize = 2; + +pub const SA_NOCLDSTOP: usize = 0x00000001; +pub const SA_NOCLDWAIT: usize = 0x00000002; +pub const SA_SIGINFO: usize = 0x00000004; +pub const SA_RESTORER: usize = 0x04000000; +pub const SA_ONSTACK: usize = 0x08000000; +pub const SA_RESTART: usize = 0x10000000; +pub const SA_NODEFER: usize = 0x40000000; +pub const SA_RESETHAND: usize = 0x80000000; + +pub const WNOHANG: usize = 0x01; +pub const WUNTRACED: usize = 0x02; +pub const WCONTINUED: usize = 0x08; + +/// True if status indicates the child is stopped. +pub fn wifstopped(status: usize) -> bool { + (status & 0xff) == 0x7f +} + +/// If wifstopped(status), the signal that stopped the child. +pub fn wstopsig(status: usize) -> usize { + (status >> 8) & 0xff +} + +/// True if status indicates the child continued after a stop. +pub fn wifcontinued(status: usize) -> bool { + status == 0xffff +} + +/// True if STATUS indicates termination by a signal. +pub fn wifsignaled(status: usize) -> bool { + ((status & 0x7f) + 1) as i8 >= 2 +} + +/// If wifsignaled(status), the terminating signal. +pub fn wtermsig(status: usize) -> usize { + status & 0x7f +} + +/// True if status indicates normal termination. +pub fn wifexited(status: usize) -> bool { + wtermsig(status) == 0 +} + +/// If wifexited(status), the exit status. +pub fn wexitstatus(status: usize) -> usize { + (status >> 8) & 0xff +} + +/// True if status indicates a core dump was created. +pub fn wcoredump(status: usize) -> bool { + (status & 0x80) != 0 +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/dma.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/dma.rs new file mode 100644 index 0000000..d5334b8 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/dma.rs @@ -0,0 +1,76 @@ +use core::{mem, ptr}; +use core::ops::{Deref, DerefMut}; + +use Result; + +struct PhysBox { + address: usize, + size: usize +} + +impl PhysBox { + fn new(size: usize) -> Result { + let address = unsafe { ::physalloc(size)? }; + Ok(PhysBox { + address: address, + size: size + }) + } +} + +impl Drop for PhysBox { + fn drop(&mut self) { + let _ = unsafe { ::physfree(self.address, self.size) }; + } +} + +pub struct Dma { + phys: PhysBox, + virt: *mut T +} + +impl Dma { + pub fn new(value: T) -> Result> { + let phys = PhysBox::new(mem::size_of::())?; + let virt = unsafe { ::physmap(phys.address, phys.size, ::PHYSMAP_WRITE)? } as *mut T; + unsafe { ptr::write(virt, value); } + Ok(Dma { + phys: phys, + virt: virt + }) + } + + pub fn zeroed() -> Result> { + let phys = PhysBox::new(mem::size_of::())?; + let virt = unsafe { ::physmap(phys.address, phys.size, ::PHYSMAP_WRITE)? } as *mut T; + unsafe { ptr::write_bytes(virt as *mut u8, 0, phys.size); } + Ok(Dma { + phys: phys, + virt: virt + }) + } + + pub fn physical(&self) -> usize { + self.phys.address + } +} + +impl Deref for Dma { + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.virt } + } +} + +impl DerefMut for Dma { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.virt } + } +} + +impl Drop for Dma { + fn drop(&mut self) { + unsafe { drop(ptr::read(self.virt)); } + let _ = unsafe { ::physunmap(self.virt as usize) }; + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/io.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/io.rs new file mode 100644 index 0000000..fb866b5 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/io.rs @@ -0,0 +1,67 @@ +use core::cmp::PartialEq; +use core::ops::{BitAnd, BitOr, Not}; + +pub trait Io { + type Value: Copy + PartialEq + BitAnd + BitOr + Not; + + fn read(&self) -> Self::Value; + fn write(&mut self, value: Self::Value); + + #[inline(always)] + fn readf(&self, flags: Self::Value) -> bool { + (self.read() & flags) as Self::Value == flags + } + + #[inline(always)] + fn writef(&mut self, flags: Self::Value, value: bool) { + let tmp: Self::Value = match value { + true => self.read() | flags, + false => self.read() & !flags, + }; + self.write(tmp); + } +} + +pub struct ReadOnly { + inner: I +} + +impl ReadOnly { + pub const fn new(inner: I) -> ReadOnly { + ReadOnly { + inner: inner + } + } + + #[inline(always)] + pub fn read(&self) -> I::Value { + self.inner.read() + } + + #[inline(always)] + pub fn readf(&self, flags: I::Value) -> bool { + self.inner.readf(flags) + } +} + +pub struct WriteOnly { + inner: I +} + +impl WriteOnly { + pub const fn new(inner: I) -> WriteOnly { + WriteOnly { + inner: inner + } + } + + #[inline(always)] + pub fn write(&mut self, value: I::Value) { + self.inner.write(value) + } + + #[inline(always)] + pub fn writef(&mut self, flags: I::Value, value: bool) { + self.inner.writef(flags, value) + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mmio.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mmio.rs new file mode 100644 index 0000000..b8e7727 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mmio.rs @@ -0,0 +1,31 @@ +use core::ptr::{read_volatile, write_volatile}; +use core::mem::uninitialized; +use core::ops::{BitAnd, BitOr, Not}; + +use super::io::Io; + +#[repr(packed)] +pub struct Mmio { + value: T, +} + +impl Mmio { + /// Create a new Mmio without initializing + pub fn new() -> Self { + Mmio { + value: unsafe { uninitialized() } + } + } +} + +impl Io for Mmio where T: Copy + PartialEq + BitAnd + BitOr + Not { + type Value = T; + + fn read(&self) -> T { + unsafe { read_volatile(&self.value) } + } + + fn write(&mut self, value: T) { + unsafe { write_volatile(&mut self.value, value) }; + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mod.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mod.rs new file mode 100644 index 0000000..a35456e --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/mod.rs @@ -0,0 +1,11 @@ +//! I/O functions + +pub use self::dma::*; +pub use self::io::*; +pub use self::mmio::*; +pub use self::pio::*; + +mod dma; +mod io; +mod mmio; +mod pio; diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/pio.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/pio.rs new file mode 100644 index 0000000..91ae310 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/io/pio.rs @@ -0,0 +1,89 @@ +use core::marker::PhantomData; + +use super::io::Io; + +/// Generic PIO +#[derive(Copy, Clone)] +pub struct Pio { + port: u16, + value: PhantomData, +} + +impl Pio { + /// Create a PIO from a given port + pub const fn new(port: u16) -> Self { + Pio:: { + port: port, + value: PhantomData, + } + } +} + +/// Read/Write for byte PIO +impl Io for Pio { + type Value = u8; + + /// Read + #[inline(always)] + fn read(&self) -> u8 { + let value: u8; + unsafe { + asm!("in $0, $1" : "={al}"(value) : "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + value + } + + /// Write + #[inline(always)] + fn write(&mut self, value: u8) { + unsafe { + asm!("out $1, $0" : : "{al}"(value), "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + } +} + +/// Read/Write for word PIO +impl Io for Pio { + type Value = u16; + + /// Read + #[inline(always)] + fn read(&self) -> u16 { + let value: u16; + unsafe { + asm!("in $0, $1" : "={ax}"(value) : "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + value + } + + /// Write + #[inline(always)] + fn write(&mut self, value: u16) { + unsafe { + asm!("out $1, $0" : : "{ax}"(value), "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + } +} + +/// Read/Write for doubleword PIO +impl Io for Pio { + type Value = u32; + + /// Read + #[inline(always)] + fn read(&self) -> u32 { + let value: u32; + unsafe { + asm!("in $0, $1" : "={eax}"(value) : "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + value + } + + /// Write + #[inline(always)] + fn write(&mut self, value: u32) { + unsafe { + asm!("out $1, $0" : : "{eax}"(value), "{dx}"(self.port) : "memory" : "intel", "volatile"); + } + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/lib.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/lib.rs new file mode 100644 index 0000000..6b8d130 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/lib.rs @@ -0,0 +1,59 @@ +#![feature(asm)] +#![feature(const_fn)] +#![cfg_attr(not(test), no_std)] + +#[cfg(test)] +extern crate core; + +pub use self::arch::*; +pub use self::call::*; +pub use self::data::*; +pub use self::error::*; +pub use self::flag::*; +pub use self::io::*; +pub use self::number::*; +pub use self::scheme::*; + +#[cfg(all(target_os = "redox", target_arch = "arm"))] +#[path="arch/arm.rs"] +mod arch; + +#[cfg(all(target_os = "redox", target_arch = "aarch64"))] +#[path="arch/aarch64.rs"] +mod arch; + +#[cfg(all(target_os = "redox", target_arch = "x86"))] +#[path="arch/x86.rs"] +mod arch; + +#[cfg(all(target_os = "redox", target_arch = "x86_64"))] +#[path="arch/x86_64.rs"] +mod arch; + +#[cfg(not(target_os = "redox"))] +#[path="arch/nonredox.rs"] +mod arch; + +/// Function definitions +pub mod call; + +/// Complex structures that are used for some system calls +pub mod data; + +/// All errors that can be generated by a system call +pub mod error; + +/// Flags used as an argument to many system calls +pub mod flag; + +/// Functions for low level hardware control +pub mod io; + +/// Call numbers used by each system call +pub mod number; + +/// A trait useful for scheme handlers +pub mod scheme; + +#[cfg(test)] +mod tests; diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/number.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/number.rs new file mode 100644 index 0000000..ec9acfa --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/number.rs @@ -0,0 +1,76 @@ +pub const SYS_CLASS: usize = 0xF000_0000; +pub const SYS_CLASS_PATH: usize=0x1000_0000; +pub const SYS_CLASS_FILE: usize=0x2000_0000; + +pub const SYS_ARG: usize = 0x0F00_0000; +pub const SYS_ARG_SLICE: usize =0x0100_0000; +pub const SYS_ARG_MSLICE: usize=0x0200_0000; +pub const SYS_ARG_PATH: usize = 0x0300_0000; + +pub const SYS_RET: usize = 0x00F0_0000; +pub const SYS_RET_FILE: usize = 0x0010_0000; + +pub const SYS_LINK: usize = SYS_CLASS_PATH | SYS_ARG_PATH | 9; +pub const SYS_OPEN: usize = SYS_CLASS_PATH | SYS_RET_FILE | 5; +pub const SYS_CHMOD: usize = SYS_CLASS_PATH | 15; +pub const SYS_RMDIR: usize = SYS_CLASS_PATH | 84; +pub const SYS_UNLINK: usize = SYS_CLASS_PATH | 10; + +pub const SYS_CLOSE: usize = SYS_CLASS_FILE | 6; +pub const SYS_DUP: usize = SYS_CLASS_FILE | SYS_RET_FILE | 41; +pub const SYS_DUP2: usize = SYS_CLASS_FILE | SYS_RET_FILE | 63; +pub const SYS_READ: usize = SYS_CLASS_FILE | SYS_ARG_MSLICE | 3; +pub const SYS_WRITE: usize = SYS_CLASS_FILE | SYS_ARG_SLICE | 4; +pub const SYS_LSEEK: usize = SYS_CLASS_FILE | 19; +pub const SYS_FCHMOD: usize = SYS_CLASS_FILE | 94; +pub const SYS_FCHOWN: usize = SYS_CLASS_FILE | 207; +pub const SYS_FCNTL: usize = SYS_CLASS_FILE | 55; +pub const SYS_FEVENT: usize = SYS_CLASS_FILE | 927; +pub const SYS_FEXEC: usize = SYS_CLASS_FILE | 11; +pub const SYS_FMAP: usize = SYS_CLASS_FILE | SYS_ARG_SLICE | 90; +pub const SYS_FUNMAP: usize = SYS_CLASS_FILE | 91; +pub const SYS_FPATH: usize = SYS_CLASS_FILE | SYS_ARG_MSLICE | 928; +pub const SYS_FRENAME: usize = SYS_CLASS_FILE | SYS_ARG_PATH | 38; +pub const SYS_FSTAT: usize = SYS_CLASS_FILE | SYS_ARG_MSLICE | 28; +pub const SYS_FSTATVFS: usize = SYS_CLASS_FILE | SYS_ARG_MSLICE | 100; +pub const SYS_FSYNC: usize = SYS_CLASS_FILE | 118; +pub const SYS_FTRUNCATE: usize =SYS_CLASS_FILE | 93; +pub const SYS_FUTIMENS: usize = SYS_CLASS_FILE | SYS_ARG_SLICE | 320; + +pub const SYS_BRK: usize = 45; +pub const SYS_CHDIR: usize = 12; +pub const SYS_CLOCK_GETTIME: usize = 265; +pub const SYS_CLONE: usize = 120; +pub const SYS_EXIT: usize = 1; +pub const SYS_FUTEX: usize = 240; +pub const SYS_GETCWD: usize = 183; +pub const SYS_GETEGID: usize = 202; +pub const SYS_GETENS: usize = 951; +pub const SYS_GETEUID: usize = 201; +pub const SYS_GETGID: usize = 200; +pub const SYS_GETNS: usize = 950; +pub const SYS_GETPID: usize = 20; +pub const SYS_GETPGID: usize = 132; +pub const SYS_GETPPID: usize = 64; +pub const SYS_GETUID: usize = 199; +pub const SYS_IOPL: usize = 110; +pub const SYS_KILL: usize = 37; +pub const SYS_MPROTECT: usize = 125; +pub const SYS_MKNS: usize = 984; +pub const SYS_NANOSLEEP: usize =162; +pub const SYS_PHYSALLOC: usize =945; +pub const SYS_PHYSFREE: usize = 946; +pub const SYS_PHYSMAP: usize = 947; +pub const SYS_PHYSUNMAP: usize =948; +pub const SYS_VIRTTOPHYS: usize=949; +pub const SYS_PIPE2: usize = 331; +pub const SYS_SETPGID: usize = 57; +pub const SYS_SETREGID: usize = 204; +pub const SYS_SETRENS: usize = 952; +pub const SYS_SETREUID: usize = 203; +pub const SYS_SIGACTION: usize =67; +pub const SYS_SIGPROCMASK:usize=126; +pub const SYS_SIGRETURN: usize =119; +pub const SYS_UMASK: usize = 60; +pub const SYS_WAITPID: usize = 7; +pub const SYS_YIELD: usize = 158; diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/generate.sh b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/generate.sh new file mode 100755 index 0000000..e5d11ae --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/generate.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +set -e + +echo "Generating SchemeMut from Scheme" +sed 's/trait Scheme/trait SchemeMut/' scheme.rs \ +| sed 's/\&self/\&mut self/g' \ +> scheme_mut.rs + +echo "Generating SchemeBlock from Scheme" +sed 's/trait Scheme/trait SchemeBlock/' scheme.rs \ +| sed 's/fn handle(\&self, packet: \&mut Packet)/fn handle(\&self, packet: \&Packet) -> Option/' \ +| sed 's/packet.a = Error::mux(res);/res.transpose().map(Error::mux)/' \ +| sed 's/Result/Result>/g' \ +> scheme_block.rs + +echo "Generating SchemeBlockMut from SchemeBlock" +sed 's/trait SchemeBlock/trait SchemeBlockMut/' scheme_block.rs \ +| sed 's/\&self/\&mut self/g' \ +> scheme_block_mut.rs diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/mod.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/mod.rs new file mode 100644 index 0000000..66f8fc7 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/mod.rs @@ -0,0 +1,9 @@ +pub use self::scheme::Scheme; +pub use self::scheme_mut::SchemeMut; +pub use self::scheme_block::SchemeBlock; +pub use self::scheme_block_mut::SchemeBlockMut; + +mod scheme; +mod scheme_mut; +mod scheme_block; +mod scheme_block_mut; diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme.rs new file mode 100644 index 0000000..c047e96 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme.rs @@ -0,0 +1,167 @@ +use core::{mem, slice}; + +use data::*; +use error::*; +use number::*; + +pub trait Scheme { + fn handle(&self, packet: &mut Packet) { + let res = match packet.a { + SYS_OPEN => self.open(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d, packet.uid, packet.gid), + SYS_CHMOD => self.chmod(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d as u16, packet.uid, packet.gid), + SYS_RMDIR => self.rmdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + SYS_UNLINK => self.unlink(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + + SYS_DUP => self.dup(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_READ => self.read(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_WRITE => self.write(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_LSEEK => self.seek(packet.b, packet.c, packet.d), + SYS_FCHMOD => self.fchmod(packet.b, packet.c as u16), + SYS_FCHOWN => self.fchown(packet.b, packet.c as u32, packet.d as u32), + SYS_FCNTL => self.fcntl(packet.b, packet.c, packet.d), + SYS_FEVENT => self.fevent(packet.b, packet.c), + SYS_FMAP => if packet.d >= mem::size_of::() { + self.fmap(packet.b, unsafe { &*(packet.c as *const Map) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FUNMAP => self.funmap(packet.b), + SYS_FPATH => self.fpath(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_FRENAME => self.frename(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }, packet.uid, packet.gid), + SYS_FSTAT => if packet.d >= mem::size_of::() { + self.fstat(packet.b, unsafe { &mut *(packet.c as *mut Stat) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSTATVFS => if packet.d >= mem::size_of::() { + self.fstatvfs(packet.b, unsafe { &mut *(packet.c as *mut StatVfs) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSYNC => self.fsync(packet.b), + SYS_FTRUNCATE => self.ftruncate(packet.b, packet.c), + SYS_FUTIMENS => if packet.d >= mem::size_of::() { + self.futimens(packet.b, unsafe { slice::from_raw_parts(packet.c as *const TimeSpec, packet.d / mem::size_of::()) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_CLOSE => self.close(packet.b), + _ => Err(Error::new(ENOSYS)) + }; + + packet.a = Error::mux(res); + } + + /* Scheme operations */ + + #[allow(unused_variables)] + fn open(&self, path: &[u8], flags: usize, uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn chmod(&self, path: &[u8], mode: u16, uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn rmdir(&self, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn unlink(&self, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + #[allow(unused_variables)] + fn dup(&self, old_id: usize, buf: &[u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn read(&self, id: usize, buf: &mut [u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&self, id: usize, buf: &[u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&self, id: usize, pos: usize, whence: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchmod(&self, id: usize, mode: u16) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchown(&self, id: usize, uid: u32, gid: u32) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fevent(&self, id: usize, flags: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fmap(&self, id: usize, map: &Map) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn funmap(&self, address: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fpath(&self, id: usize, buf: &mut [u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn frename(&self, id: usize, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstat(&self, id: usize, stat: &mut Stat) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstatvfs(&self, id: usize, stat: &mut StatVfs) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fsync(&self, id: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn ftruncate(&self, id: usize, len: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn futimens(&self, id: usize, times: &[TimeSpec]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn close(&self, id: usize) -> Result { + Err(Error::new(EBADF)) + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block.rs new file mode 100644 index 0000000..0407dde --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block.rs @@ -0,0 +1,167 @@ +use core::{mem, slice}; + +use data::*; +use error::*; +use number::*; + +pub trait SchemeBlock { + fn handle(&self, packet: &Packet) -> Option { + let res = match packet.a { + SYS_OPEN => self.open(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d, packet.uid, packet.gid), + SYS_CHMOD => self.chmod(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d as u16, packet.uid, packet.gid), + SYS_RMDIR => self.rmdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + SYS_UNLINK => self.unlink(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + + SYS_DUP => self.dup(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_READ => self.read(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_WRITE => self.write(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_LSEEK => self.seek(packet.b, packet.c, packet.d), + SYS_FCHMOD => self.fchmod(packet.b, packet.c as u16), + SYS_FCHOWN => self.fchown(packet.b, packet.c as u32, packet.d as u32), + SYS_FCNTL => self.fcntl(packet.b, packet.c, packet.d), + SYS_FEVENT => self.fevent(packet.b, packet.c), + SYS_FMAP => if packet.d >= mem::size_of::() { + self.fmap(packet.b, unsafe { &*(packet.c as *const Map) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FUNMAP => self.funmap(packet.b), + SYS_FPATH => self.fpath(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_FRENAME => self.frename(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }, packet.uid, packet.gid), + SYS_FSTAT => if packet.d >= mem::size_of::() { + self.fstat(packet.b, unsafe { &mut *(packet.c as *mut Stat) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSTATVFS => if packet.d >= mem::size_of::() { + self.fstatvfs(packet.b, unsafe { &mut *(packet.c as *mut StatVfs) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSYNC => self.fsync(packet.b), + SYS_FTRUNCATE => self.ftruncate(packet.b, packet.c), + SYS_FUTIMENS => if packet.d >= mem::size_of::() { + self.futimens(packet.b, unsafe { slice::from_raw_parts(packet.c as *const TimeSpec, packet.d / mem::size_of::()) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_CLOSE => self.close(packet.b), + _ => Err(Error::new(ENOSYS)) + }; + + res.transpose().map(Error::mux) + } + + /* Scheme operations */ + + #[allow(unused_variables)] + fn open(&self, path: &[u8], flags: usize, uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn chmod(&self, path: &[u8], mode: u16, uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn rmdir(&self, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn unlink(&self, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + #[allow(unused_variables)] + fn dup(&self, old_id: usize, buf: &[u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn read(&self, id: usize, buf: &mut [u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&self, id: usize, buf: &[u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&self, id: usize, pos: usize, whence: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchmod(&self, id: usize, mode: u16) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchown(&self, id: usize, uid: u32, gid: u32) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fcntl(&self, id: usize, cmd: usize, arg: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fevent(&self, id: usize, flags: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fmap(&self, id: usize, map: &Map) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn funmap(&self, address: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fpath(&self, id: usize, buf: &mut [u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn frename(&self, id: usize, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstat(&self, id: usize, stat: &mut Stat) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstatvfs(&self, id: usize, stat: &mut StatVfs) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fsync(&self, id: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn ftruncate(&self, id: usize, len: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn futimens(&self, id: usize, times: &[TimeSpec]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn close(&self, id: usize) -> Result> { + Err(Error::new(EBADF)) + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block_mut.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block_mut.rs new file mode 100644 index 0000000..411035f --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_block_mut.rs @@ -0,0 +1,167 @@ +use core::{mem, slice}; + +use data::*; +use error::*; +use number::*; + +pub trait SchemeBlockMut { + fn handle(&mut self, packet: &Packet) -> Option { + let res = match packet.a { + SYS_OPEN => self.open(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d, packet.uid, packet.gid), + SYS_CHMOD => self.chmod(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d as u16, packet.uid, packet.gid), + SYS_RMDIR => self.rmdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + SYS_UNLINK => self.unlink(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + + SYS_DUP => self.dup(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_READ => self.read(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_WRITE => self.write(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_LSEEK => self.seek(packet.b, packet.c, packet.d), + SYS_FCHMOD => self.fchmod(packet.b, packet.c as u16), + SYS_FCHOWN => self.fchown(packet.b, packet.c as u32, packet.d as u32), + SYS_FCNTL => self.fcntl(packet.b, packet.c, packet.d), + SYS_FEVENT => self.fevent(packet.b, packet.c), + SYS_FMAP => if packet.d >= mem::size_of::() { + self.fmap(packet.b, unsafe { &*(packet.c as *const Map) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FUNMAP => self.funmap(packet.b), + SYS_FPATH => self.fpath(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_FRENAME => self.frename(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }, packet.uid, packet.gid), + SYS_FSTAT => if packet.d >= mem::size_of::() { + self.fstat(packet.b, unsafe { &mut *(packet.c as *mut Stat) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSTATVFS => if packet.d >= mem::size_of::() { + self.fstatvfs(packet.b, unsafe { &mut *(packet.c as *mut StatVfs) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSYNC => self.fsync(packet.b), + SYS_FTRUNCATE => self.ftruncate(packet.b, packet.c), + SYS_FUTIMENS => if packet.d >= mem::size_of::() { + self.futimens(packet.b, unsafe { slice::from_raw_parts(packet.c as *const TimeSpec, packet.d / mem::size_of::()) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_CLOSE => self.close(packet.b), + _ => Err(Error::new(ENOSYS)) + }; + + res.transpose().map(Error::mux) + } + + /* Scheme operations */ + + #[allow(unused_variables)] + fn open(&mut self, path: &[u8], flags: usize, uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn chmod(&mut self, path: &[u8], mode: u16, uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn rmdir(&mut self, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn unlink(&mut self, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + #[allow(unused_variables)] + fn dup(&mut self, old_id: usize, buf: &[u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn read(&mut self, id: usize, buf: &mut [u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&mut self, id: usize, buf: &[u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchmod(&mut self, id: usize, mode: u16) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchown(&mut self, id: usize, uid: u32, gid: u32) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fcntl(&mut self, id: usize, cmd: usize, arg: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fevent(&mut self, id: usize, flags: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fmap(&mut self, id: usize, map: &Map) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn funmap(&mut self, address: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fpath(&mut self, id: usize, buf: &mut [u8]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn frename(&mut self, id: usize, path: &[u8], uid: u32, gid: u32) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstat(&mut self, id: usize, stat: &mut Stat) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstatvfs(&mut self, id: usize, stat: &mut StatVfs) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fsync(&mut self, id: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn ftruncate(&mut self, id: usize, len: usize) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn futimens(&mut self, id: usize, times: &[TimeSpec]) -> Result> { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn close(&mut self, id: usize) -> Result> { + Err(Error::new(EBADF)) + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_mut.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_mut.rs new file mode 100644 index 0000000..abd2e88 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/scheme/scheme_mut.rs @@ -0,0 +1,167 @@ +use core::{mem, slice}; + +use data::*; +use error::*; +use number::*; + +pub trait SchemeMut { + fn handle(&mut self, packet: &mut Packet) { + let res = match packet.a { + SYS_OPEN => self.open(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d, packet.uid, packet.gid), + SYS_CHMOD => self.chmod(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.d as u16, packet.uid, packet.gid), + SYS_RMDIR => self.rmdir(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + SYS_UNLINK => self.unlink(unsafe { slice::from_raw_parts(packet.b as *const u8, packet.c) }, packet.uid, packet.gid), + + SYS_DUP => self.dup(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_READ => self.read(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_WRITE => self.write(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }), + SYS_LSEEK => self.seek(packet.b, packet.c, packet.d), + SYS_FCHMOD => self.fchmod(packet.b, packet.c as u16), + SYS_FCHOWN => self.fchown(packet.b, packet.c as u32, packet.d as u32), + SYS_FCNTL => self.fcntl(packet.b, packet.c, packet.d), + SYS_FEVENT => self.fevent(packet.b, packet.c), + SYS_FMAP => if packet.d >= mem::size_of::() { + self.fmap(packet.b, unsafe { &*(packet.c as *const Map) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FUNMAP => self.funmap(packet.b), + SYS_FPATH => self.fpath(packet.b, unsafe { slice::from_raw_parts_mut(packet.c as *mut u8, packet.d) }), + SYS_FRENAME => self.frename(packet.b, unsafe { slice::from_raw_parts(packet.c as *const u8, packet.d) }, packet.uid, packet.gid), + SYS_FSTAT => if packet.d >= mem::size_of::() { + self.fstat(packet.b, unsafe { &mut *(packet.c as *mut Stat) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSTATVFS => if packet.d >= mem::size_of::() { + self.fstatvfs(packet.b, unsafe { &mut *(packet.c as *mut StatVfs) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_FSYNC => self.fsync(packet.b), + SYS_FTRUNCATE => self.ftruncate(packet.b, packet.c), + SYS_FUTIMENS => if packet.d >= mem::size_of::() { + self.futimens(packet.b, unsafe { slice::from_raw_parts(packet.c as *const TimeSpec, packet.d / mem::size_of::()) }) + } else { + Err(Error::new(EFAULT)) + }, + SYS_CLOSE => self.close(packet.b), + _ => Err(Error::new(ENOSYS)) + }; + + packet.a = Error::mux(res); + } + + /* Scheme operations */ + + #[allow(unused_variables)] + fn open(&mut self, path: &[u8], flags: usize, uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn chmod(&mut self, path: &[u8], mode: u16, uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn rmdir(&mut self, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + #[allow(unused_variables)] + fn unlink(&mut self, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(ENOENT)) + } + + /* Resource operations */ + #[allow(unused_variables)] + fn dup(&mut self, old_id: usize, buf: &[u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn read(&mut self, id: usize, buf: &mut [u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn write(&mut self, id: usize, buf: &[u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn seek(&mut self, id: usize, pos: usize, whence: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchmod(&mut self, id: usize, mode: u16) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fchown(&mut self, id: usize, uid: u32, gid: u32) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fcntl(&mut self, id: usize, cmd: usize, arg: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fevent(&mut self, id: usize, flags: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fmap(&mut self, id: usize, map: &Map) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn funmap(&mut self, address: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fpath(&mut self, id: usize, buf: &mut [u8]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn frename(&mut self, id: usize, path: &[u8], uid: u32, gid: u32) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstat(&mut self, id: usize, stat: &mut Stat) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fstatvfs(&mut self, id: usize, stat: &mut StatVfs) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn fsync(&mut self, id: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn ftruncate(&mut self, id: usize, len: usize) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn futimens(&mut self, id: usize, times: &[TimeSpec]) -> Result { + Err(Error::new(EBADF)) + } + + #[allow(unused_variables)] + fn close(&mut self, id: usize) -> Result { + Err(Error::new(EBADF)) + } +} diff --git a/third_party/cargo/vendor/redox_syscall-0.1.56/src/tests.rs b/third_party/cargo/vendor/redox_syscall-0.1.56/src/tests.rs new file mode 100644 index 0000000..cf89ec9 --- /dev/null +++ b/third_party/cargo/vendor/redox_syscall-0.1.56/src/tests.rs @@ -0,0 +1,129 @@ +#[test] +fn brk() { + unsafe { + let start = dbg!(crate::brk(0)).unwrap(); + let end = start + 4 * 1024 * 1024; + assert_eq!(dbg!(crate::brk(end)), Ok(end)); + } +} + +#[test] +fn chdir() { + //TODO: Verify CWD + assert_eq!(dbg!(crate::chdir("file:/")), Ok(0)); + assert_eq!(dbg!(crate::chdir("file:/root")), Ok(0)); +} + +//TODO: chmod + +#[test] +fn clone() { + let expected_status = 42; + let pid_res = unsafe { crate::clone(0) }; + if pid_res == Ok(0) { + crate::exit(expected_status).unwrap(); + panic!("failed to exit"); + } else { + let pid = dbg!(pid_res).unwrap(); + let mut status = 0; + assert_eq!(dbg!(crate::waitpid(pid, &mut status, 0)), Ok(pid)); + assert_eq!(dbg!(crate::wifexited(status)), true); + assert_eq!(dbg!(crate::wexitstatus(status)), expected_status); + } +} + +//TODO: close + +#[test] +fn clock_gettime() { + let mut tp = crate::TimeSpec::default(); + assert_eq!(dbg!( + crate::clock_gettime(crate::CLOCK_MONOTONIC, &mut tp) + ), Ok(0)); + assert_ne!(dbg!(tp), crate::TimeSpec::default()); + + tp = crate::TimeSpec::default(); + assert_eq!(dbg!( + crate::clock_gettime(crate::CLOCK_REALTIME, &mut tp) + ), Ok(0)); + assert_ne!(dbg!(tp), crate::TimeSpec::default()); +} + +//TODO: dup + +//TODO: dup2 + +//TODO: exit (handled by clone?) + +//TODO: fchmod + +//TODO: fcntl + +#[test] +fn fexec() { + let name = "/bin/ls"; + + let fd = dbg!( + crate::open(name, crate::O_RDONLY | crate::O_CLOEXEC) + ).unwrap(); + + let args = &[ + [name.as_ptr() as usize, name.len()] + ]; + + let vars = &[]; + + let pid_res = unsafe { crate::clone(0) }; + if pid_res == Ok(0) { + crate::fexec(fd, args, vars).unwrap(); + panic!("failed to fexec"); + } else { + assert_eq!(dbg!(crate::close(fd)), Ok(0)); + + let pid = dbg!(pid_res).unwrap(); + let mut status = 0; + assert_eq!(dbg!(crate::waitpid(pid, &mut status, 0)), Ok(pid)); + assert_eq!(dbg!(crate::wifexited(status)), true); + assert_eq!(dbg!(crate::wexitstatus(status)), 0); + } +} + +#[test] +fn fmap() { + use std::slice; + + let fd = dbg!( + crate::open( + "/tmp/syscall-tests-fmap", + crate::O_CREAT | crate::O_RDWR | crate::O_CLOEXEC + ) + ).unwrap(); + + let map = unsafe { + slice::from_raw_parts_mut( + dbg!( + crate::fmap(fd, &crate::Map { + offset: 0, + size: 128, + flags: crate::PROT_READ | crate::PROT_WRITE + }) + ).unwrap() as *mut u8, + 128 + ) + }; + + // Maps should be available after closing + assert_eq!(dbg!(crate::close(fd)), Ok(0)); + + for i in 0..128 { + map[i as usize] = i; + assert_eq!(map[i as usize], i); + } + + //TODO: add msync + unsafe { + assert_eq!(dbg!( + crate::funmap(map.as_mut_ptr() as usize) + ), Ok(0)); + } +} diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/.cargo-checksum.json b/third_party/cargo/vendor/rustc-demangle-0.1.16/.cargo-checksum.json deleted file mode 100644 index f041b63..0000000 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"ead05c6446fe945323775a2805e07aae6784238364fa07a84a72d38f7363c5d1","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"7bb7dbc6378a31b5b925a0cff628a69006c77a4cdf3533f7507b7c8fbe3492b0","src/legacy.rs":"3d469f6ba81129500a23b5975c9f099020c734bd26bb039d1030bf359d3d53fc","src/lib.rs":"4069dce717cdc52933b39991b401834b5aa5cd02fa2cffb78691397a97a467be","src/v0.rs":"9c4df16df15277abe500a539876e77907cda248da4822a921b708d6d4468ff4a"},"package":"4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783"} \ No newline at end of file diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/README.md b/third_party/cargo/vendor/rustc-demangle-0.1.16/README.md deleted file mode 100644 index 4b480b8..0000000 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# rustc-demangle - -Symbol demangling for Rust - -[![Build Status](https://travis-ci.org/alexcrichton/rustc-demangle.svg?branch=master)](https://travis-ci.org/alexcrichton/rustc-demangle) - -[Documentation](https://docs.rs/rustc-demangle) - -# License - -This project 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 rustc-demangle you, as defined in the Apache-2.0 license, shall -be dual licensed as above, without any additional terms or conditions. diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/legacy.rs b/third_party/cargo/vendor/rustc-demangle-0.1.16/src/legacy.rs deleted file mode 100644 index 5e30797..0000000 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/legacy.rs +++ /dev/null @@ -1,379 +0,0 @@ -use core::char; -use core::fmt; - -/// Representation of a demangled symbol name. -pub struct Demangle<'a> { - inner: &'a str, - /// The number of ::-separated elements in the original name. - elements: usize, -} - -/// De-mangles a Rust symbol into a more readable version -/// -/// All Rust symbols by default are mangled as they contain characters that -/// cannot be represented in all object files. The mangling mechanism is similar -/// to C++'s, but Rust has a few specifics to handle items like lifetimes in -/// symbols. -/// -/// This function will take a **mangled** symbol and return a value. When printed, -/// the de-mangled version will be written. If the symbol does not look like -/// a mangled symbol, the original value will be written instead. -/// -/// # Examples -/// -/// ``` -/// use rustc_demangle::demangle; -/// -/// assert_eq!(demangle("_ZN4testE").to_string(), "test"); -/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); -/// assert_eq!(demangle("foo").to_string(), "foo"); -/// ``` - -// All Rust symbols are in theory lists of "::"-separated identifiers. Some -// assemblers, however, can't handle these characters in symbol names. To get -// around this, we use C++-style mangling. The mangling method is: -// -// 1. Prefix the symbol with "_ZN" -// 2. For each element of the path, emit the length plus the element -// 3. End the path with "E" -// -// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". -// -// We're the ones printing our backtraces, so we can't rely on anything else to -// demangle our symbols. It's *much* nicer to look at demangled symbols, so -// this function is implemented to give us nice pretty output. -// -// Note that this demangler isn't quite as fancy as it could be. We have lots -// of other information in our symbols like hashes, version, type information, -// etc. Additionally, this doesn't handle glue symbols at all. -pub fn demangle(s: &str) -> Result<(Demangle, &str), ()> { - // First validate the symbol. If it doesn't look like anything we're - // expecting, we just print it literally. Note that we must handle non-Rust - // symbols because we could have any function in the backtrace. - let inner = if s.starts_with("_ZN") { - &s[3..] - } else if s.starts_with("ZN") { - // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" - // form too. - &s[2..] - } else if s.starts_with("__ZN") { - // On OSX, symbols are prefixed with an extra _ - &s[4..] - } else { - return Err(()); - }; - - // only work with ascii text - if inner.bytes().any(|c| c & 0x80 != 0) { - return Err(()); - } - - let mut elements = 0; - let mut chars = inner.chars(); - let mut c = try!(chars.next().ok_or(())); - while c != 'E' { - // Decode an identifier element's length. - if !c.is_digit(10) { - return Err(()); - } - let mut len = 0usize; - while let Some(d) = c.to_digit(10) { - len = try!(len.checked_mul(10) - .and_then(|len| len.checked_add(d as usize)) - .ok_or(())); - c = try!(chars.next().ok_or(())); - } - - // `c` already contains the first character of this identifier, skip it and - // all the other characters of this identifier, to reach the next element. - for _ in 0..len { - c = try!(chars.next().ok_or(())); - } - - elements += 1; - } - - Ok((Demangle { - inner: inner, - elements: elements, - }, chars.as_str())) -} - -// Rust hashes are hex digits with an `h` prepended. -fn is_rust_hash(s: &str) -> bool { - s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) -} - -impl<'a> fmt::Display for Demangle<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Alright, let's do this. - let mut inner = self.inner; - for element in 0..self.elements { - let mut rest = inner; - while rest.chars().next().unwrap().is_digit(10) { - rest = &rest[1..]; - } - let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); - inner = &rest[i..]; - rest = &rest[..i]; - // Skip printing the hash if alternate formatting - // was requested. - if f.alternate() && element+1 == self.elements && is_rust_hash(&rest) { - break; - } - if element != 0 { - try!(f.write_str("::")); - } - if rest.starts_with("_$") { - rest = &rest[1..]; - } - loop { - if rest.starts_with('.') { - if let Some('.') = rest[1..].chars().next() { - try!(f.write_str("::")); - rest = &rest[2..]; - } else { - try!(f.write_str(".")); - rest = &rest[1..]; - } - } else if rest.starts_with('$') { - let (escape, after_escape) = if let Some(end) = rest[1..].find('$') { - (&rest[1..end + 1], &rest[end + 2..]) - } else { - break; - }; - - // see src/librustc_codegen_utils/symbol_names/legacy.rs for these mappings - let unescaped = match escape { - "SP" => "@", - "BP" => "*", - "RF" => "&", - "LT" => "<", - "GT" => ">", - "LP" => "(", - "RP" => ")", - "C" => ",", - - _ => { - if escape.starts_with('u') { - let digits = &escape[1..]; - let all_lower_hex = digits.chars().all(|c| match c { - '0'...'9' | 'a'...'f' => true, - _ => false, - }); - let c = u32::from_str_radix(digits, 16).ok() - .and_then(char::from_u32); - if let (true, Some(c)) = (all_lower_hex, c) { - // FIXME(eddyb) do we need to filter out control codepoints? - if !c.is_control() { - try!(c.fmt(f)); - rest = after_escape; - continue; - } - } - } - break; - } - }; - try!(f.write_str(unescaped)); - rest = after_escape; - } else if let Some(i) = rest.find(|c| c == '$' || c == '.') { - try!(f.write_str(&rest[..i])); - rest = &rest[i..]; - } else { - break; - } - } - try!(f.write_str(rest)); - } - - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use std::prelude::v1::*; - - macro_rules! t { - ($a:expr, $b:expr) => (assert!(ok($a, $b))) - } - - macro_rules! t_err { - ($a:expr) => (assert!(ok_err($a))) - } - - macro_rules! t_nohash { - ($a:expr, $b:expr) => ({ - assert_eq!(format!("{:#}", ::demangle($a)), $b); - }) - } - - fn ok(sym: &str, expected: &str) -> bool { - match ::try_demangle(sym) { - Ok(s) => { - if s.to_string() == expected { - true - } else { - println!("\n{}\n!=\n{}\n", s, expected); - false - } - } - Err(_) => { - println!("error demangling"); - false - } - } - } - - fn ok_err(sym: &str) -> bool { - match ::try_demangle(sym) { - Ok(_) => { - println!("succeeded in demangling"); - false - } - Err(_) => ::demangle(sym).to_string() == sym, - } - } - - #[test] - fn demangle() { - t_err!("test"); - t!("_ZN4testE", "test"); - t_err!("_ZN4test"); - t!("_ZN4test1a2bcE", "test::a::bc"); - } - - #[test] - fn demangle_dollars() { - t!("_ZN4$RP$E", ")"); - t!("_ZN8$RF$testE", "&test"); - t!("_ZN8$BP$test4foobE", "*test::foob"); - t!("_ZN9$u20$test4foobE", " test::foob"); - t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); - } - - #[test] - fn demangle_many_dollars() { - t!("_ZN13test$u20$test4foobE", "test test::foob"); - t!("_ZN12test$BP$test4foobE", "test*test::foob"); - } - - - #[test] - fn demangle_osx() { - t!("__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011"); - t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", ">::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); - t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::::into_iter::h450e234d27262170"); - } - - #[test] - fn demangle_windows() { - t!("ZN4testE", "test"); - t!("ZN13test$u20$test4foobE", "test test::foob"); - t!("ZN12test$RF$test4foobE", "test&test::foob"); - } - - #[test] - fn demangle_elements_beginning_with_underscore() { - t!("_ZN13_$LT$test$GT$E", ""); - t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); - t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); - } - - #[test] - fn demangle_trait_impls() { - t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", - ">::bar"); - } - - #[test] - fn demangle_without_hash() { - let s = "_ZN3foo17h05af221e174051e9E"; - t!(s, "foo::h05af221e174051e9"); - t_nohash!(s, "foo"); - } - - #[test] - fn demangle_without_hash_edgecases() { - // One element, no hash. - t_nohash!("_ZN3fooE", "foo"); - // Two elements, no hash. - t_nohash!("_ZN3foo3barE", "foo::bar"); - // Longer-than-normal hash. - t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); - // Shorter-than-normal hash. - t_nohash!("_ZN3foo5h05afE", "foo"); - // Valid hash, but not at the end. - t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); - // Not a valid hash, missing the 'h'. - t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); - // Not a valid hash, has a non-hex-digit. - t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); - } - - #[test] - fn demangle_thinlto() { - // One element, no hash. - t!("_ZN3fooE.llvm.9D1C9369", "foo"); - t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); - t_nohash!("_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo"); - } - - #[test] - fn demangle_llvm_ir_branch_labels() { - t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice:: for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); - t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice:: for [T]>::index_mut.exit.i.i"); - } - - #[test] - fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { - t_err!("_ZN3fooE.llvm moocow"); - } - - #[test] - fn dont_panic() { - ::demangle("_ZN2222222222222222222222EE").to_string(); - ::demangle("_ZN5*70527e27.ll34csaғE").to_string(); - ::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); - ::demangle("\ - _ZN5~saäb4e\n\ - 2734cOsbE\n\ - 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ - ").to_string(); - } - - #[test] - fn invalid_no_chop() { - t_err!("_ZNfooE"); - } - - #[test] - fn handle_assoc_types() { - t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", " + 'a> as core::ops::function::FnOnce>::call_once::h69e8f44b3723e1ca"); - } - - #[test] - fn handle_bang() { - t!( - "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", - " as std::process::Termination>::report::hfc41d0da4a40b3e8" - ); - } - - #[test] - fn demangle_utf8_idents() { - t_nohash!( - "_ZN11utf8_idents157_$u10e1$$u10d0$$u10ed$$u10db$$u10d4$$u10da$$u10d0$$u10d3$_$u10d2$$u10d4$$u10db$$u10e0$$u10d8$$u10d4$$u10da$$u10d8$_$u10e1$$u10d0$$u10d3$$u10d8$$u10da$$u10d8$17h21634fd5714000aaE", - "utf8_idents::საჭმელად_გემრიელი_სადილი" - ); - } - - #[test] - fn demangle_issue_60925() { - t_nohash!( - "_ZN11issue_609253foo37Foo$LT$issue_60925..llv$u6d$..Foo$GT$3foo17h059a991a004536adE", - "issue_60925::foo::Foo::foo" - ); - } -} diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/lib.rs b/third_party/cargo/vendor/rustc-demangle-0.1.16/src/lib.rs deleted file mode 100644 index 19778d8..0000000 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/lib.rs +++ /dev/null @@ -1,373 +0,0 @@ -//! Demangle Rust compiler symbol names. -//! -//! This crate provides a `demangle` function which will return a `Demangle` -//! sentinel value that can be used to learn about the demangled version of a -//! symbol name. The demangled representation will be the same as the original -//! if it doesn't look like a mangled symbol name. -//! -//! `Demangle` can be formatted with the `Display` trait. The alternate -//! modifier (`#`) can be used to format the symbol name without the -//! trailing hash value. -//! -//! # Examples -//! -//! ``` -//! use rustc_demangle::demangle; -//! -//! assert_eq!(demangle("_ZN4testE").to_string(), "test"); -//! assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); -//! assert_eq!(demangle("foo").to_string(), "foo"); -//! // With hash -//! assert_eq!(format!("{}", demangle("_ZN3foo17h05af221e174051e9E")), "foo::h05af221e174051e9"); -//! // Without hash -//! assert_eq!(format!("{:#}", demangle("_ZN3foo17h05af221e174051e9E")), "foo"); -//! ``` - -#![no_std] -#![deny(missing_docs)] - -#[cfg(test)] -#[macro_use] -extern crate std; - -mod legacy; -mod v0; - -use core::fmt; - -/// Representation of a demangled symbol name. -pub struct Demangle<'a> { - style: Option>, - original: &'a str, - suffix: &'a str, -} - -enum DemangleStyle<'a> { - Legacy(legacy::Demangle<'a>), - V0(v0::Demangle<'a>), -} - -/// De-mangles a Rust symbol into a more readable version -/// -/// This function will take a **mangled** symbol and return a value. When printed, -/// the de-mangled version will be written. If the symbol does not look like -/// a mangled symbol, the original value will be written instead. -/// -/// # Examples -/// -/// ``` -/// use rustc_demangle::demangle; -/// -/// assert_eq!(demangle("_ZN4testE").to_string(), "test"); -/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); -/// assert_eq!(demangle("foo").to_string(), "foo"); -/// ``` -pub fn demangle(mut s: &str) -> Demangle { - // During ThinLTO LLVM may import and rename internal symbols, so strip out - // those endings first as they're one of the last manglings applied to symbol - // names. - let llvm = ".llvm."; - if let Some(i) = s.find(llvm) { - let candidate = &s[i + llvm.len()..]; - let all_hex = candidate.chars().all(|c| { - match c { - 'A' ... 'F' | '0' ... '9' | '@' => true, - _ => false, - } - }); - - if all_hex { - s = &s[..i]; - } - } - - let mut suffix = ""; - let mut style = match legacy::demangle(s) { - Ok((d, s)) => { - suffix = s; - Some(DemangleStyle::Legacy(d)) - } - Err(()) => match v0::demangle(s) { - Ok((d, s)) => { - suffix = s; - Some(DemangleStyle::V0(d)) - } - Err(v0::Invalid) => None, - }, - }; - - // Output like LLVM IR adds extra period-delimited words. See if - // we are in that case and save the trailing words if so. - if !suffix.is_empty() { - if suffix.starts_with(".") && is_symbol_like(suffix) { - // Keep the suffix. - } else { - // Reset the suffix and invalidate the demangling. - suffix = ""; - style = None; - } - } - - Demangle { - style: style, - original: s, - suffix: suffix, - } -} - -/// Error returned from the `try_demangle` function below when demangling fails. -#[derive(Debug, Clone)] -pub struct TryDemangleError { - _priv: (), -} - -/// The same as `demangle`, except return an `Err` if the string does not appear -/// to be a Rust symbol, rather than "demangling" the given string as a no-op. -/// -/// ``` -/// extern crate rustc_demangle; -/// -/// let not_a_rust_symbol = "la la la"; -/// -/// // The `try_demangle` function will reject strings which are not Rust symbols. -/// assert!(rustc_demangle::try_demangle(not_a_rust_symbol).is_err()); -/// -/// // While `demangle` will just pass the non-symbol through as a no-op. -/// assert_eq!(rustc_demangle::demangle(not_a_rust_symbol).as_str(), not_a_rust_symbol); -/// ``` -pub fn try_demangle(s: &str) -> Result { - let sym = demangle(s); - if sym.style.is_some() { - Ok(sym) - } else { - Err(TryDemangleError { _priv: () }) - } -} - -impl<'a> Demangle<'a> { - /// Returns the underlying string that's being demangled. - pub fn as_str(&self) -> &'a str { - self.original - } -} - -fn is_symbol_like(s: &str) -> bool { - s.chars().all(|c| { - // Once `char::is_ascii_punctuation` and `char::is_ascii_alphanumeric` - // have been stable for long enough, use those instead for clarity - is_ascii_alphanumeric(c) || is_ascii_punctuation(c) - }) -} - -// Copied from the documentation of `char::is_ascii_alphanumeric` -fn is_ascii_alphanumeric(c: char) -> bool { - match c { - '\u{0041}' ... '\u{005A}' | - '\u{0061}' ... '\u{007A}' | - '\u{0030}' ... '\u{0039}' => true, - _ => false, - } -} - -// Copied from the documentation of `char::is_ascii_punctuation` -fn is_ascii_punctuation(c: char) -> bool { - match c { - '\u{0021}' ... '\u{002F}' | - '\u{003A}' ... '\u{0040}' | - '\u{005B}' ... '\u{0060}' | - '\u{007B}' ... '\u{007E}' => true, - _ => false, - } -} - -impl<'a> fmt::Display for Demangle<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.style { - None => try!(f.write_str(self.original)), - Some(DemangleStyle::Legacy(ref d)) => { - try!(fmt::Display::fmt(d, f)) - } - Some(DemangleStyle::V0(ref d)) => { - try!(fmt::Display::fmt(d, f)) - } - } - f.write_str(self.suffix) - } -} - -impl<'a> fmt::Debug for Demangle<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -#[cfg(test)] -mod tests { - use std::prelude::v1::*; - - macro_rules! t { - ($a:expr, $b:expr) => (assert!(ok($a, $b))) - } - - macro_rules! t_err { - ($a:expr) => (assert!(ok_err($a))) - } - - macro_rules! t_nohash { - ($a:expr, $b:expr) => ({ - assert_eq!(format!("{:#}", super::demangle($a)), $b); - }) - } - - fn ok(sym: &str, expected: &str) -> bool { - match super::try_demangle(sym) { - Ok(s) => { - if s.to_string() == expected { - true - } else { - println!("\n{}\n!=\n{}\n", s, expected); - false - } - } - Err(_) => { - println!("error demangling"); - false - } - } - } - - fn ok_err(sym: &str) -> bool { - match super::try_demangle(sym) { - Ok(_) => { - println!("succeeded in demangling"); - false - } - Err(_) => super::demangle(sym).to_string() == sym, - } - } - - #[test] - fn demangle() { - t_err!("test"); - t!("_ZN4testE", "test"); - t_err!("_ZN4test"); - t!("_ZN4test1a2bcE", "test::a::bc"); - } - - #[test] - fn demangle_dollars() { - t!("_ZN4$RP$E", ")"); - t!("_ZN8$RF$testE", "&test"); - t!("_ZN8$BP$test4foobE", "*test::foob"); - t!("_ZN9$u20$test4foobE", " test::foob"); - t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); - } - - #[test] - fn demangle_many_dollars() { - t!("_ZN13test$u20$test4foobE", "test test::foob"); - t!("_ZN12test$BP$test4foobE", "test*test::foob"); - } - - - #[test] - fn demangle_osx() { - t!("__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011"); - t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", ">::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); - t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::::into_iter::h450e234d27262170"); - } - - #[test] - fn demangle_windows() { - t!("ZN4testE", "test"); - t!("ZN13test$u20$test4foobE", "test test::foob"); - t!("ZN12test$RF$test4foobE", "test&test::foob"); - } - - #[test] - fn demangle_elements_beginning_with_underscore() { - t!("_ZN13_$LT$test$GT$E", ""); - t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); - t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); - } - - #[test] - fn demangle_trait_impls() { - t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", - ">::bar"); - } - - #[test] - fn demangle_without_hash() { - let s = "_ZN3foo17h05af221e174051e9E"; - t!(s, "foo::h05af221e174051e9"); - t_nohash!(s, "foo"); - } - - #[test] - fn demangle_without_hash_edgecases() { - // One element, no hash. - t_nohash!("_ZN3fooE", "foo"); - // Two elements, no hash. - t_nohash!("_ZN3foo3barE", "foo::bar"); - // Longer-than-normal hash. - t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); - // Shorter-than-normal hash. - t_nohash!("_ZN3foo5h05afE", "foo"); - // Valid hash, but not at the end. - t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); - // Not a valid hash, missing the 'h'. - t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); - // Not a valid hash, has a non-hex-digit. - t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); - } - - #[test] - fn demangle_thinlto() { - // One element, no hash. - t!("_ZN3fooE.llvm.9D1C9369", "foo"); - t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); - t_nohash!("_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo"); - } - - #[test] - fn demangle_llvm_ir_branch_labels() { - t!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice:: for [T]>::index_mut::haf9727c2edfbc47b.exit.i.i"); - t_nohash!("_ZN4core5slice77_$LT$impl$u20$core..ops..index..IndexMut$LT$I$GT$$u20$for$u20$$u5b$T$u5d$$GT$9index_mut17haf9727c2edfbc47bE.exit.i.i", "core::slice:: for [T]>::index_mut.exit.i.i"); - } - - #[test] - fn demangle_ignores_suffix_that_doesnt_look_like_a_symbol() { - t_err!("_ZN3fooE.llvm moocow"); - } - - #[test] - fn dont_panic() { - super::demangle("_ZN2222222222222222222222EE").to_string(); - super::demangle("_ZN5*70527e27.ll34csaғE").to_string(); - super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); - super::demangle("\ - _ZN5~saäb4e\n\ - 2734cOsbE\n\ - 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ - ").to_string(); - } - - #[test] - fn invalid_no_chop() { - t_err!("_ZNfooE"); - } - - #[test] - fn handle_assoc_types() { - t!("_ZN151_$LT$alloc..boxed..Box$LT$alloc..boxed..FnBox$LT$A$C$$u20$Output$u3d$R$GT$$u20$$u2b$$u20$$u27$a$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once17h69e8f44b3723e1caE", " + 'a> as core::ops::function::FnOnce>::call_once::h69e8f44b3723e1ca"); - } - - #[test] - fn handle_bang() { - t!( - "_ZN88_$LT$core..result..Result$LT$$u21$$C$$u20$E$GT$$u20$as$u20$std..process..Termination$GT$6report17hfc41d0da4a40b3e8E", - " as std::process::Termination>::report::hfc41d0da4a40b3e8" - ); - } -} diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/v0.rs b/third_party/cargo/vendor/rustc-demangle-0.1.16/src/v0.rs deleted file mode 100644 index 7a6c6a2..0000000 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/src/v0.rs +++ /dev/null @@ -1,1084 +0,0 @@ -use core::char; -use core::fmt; -use core::fmt::Display; - -/// Representation of a demangled symbol name. -pub struct Demangle<'a> { - inner: &'a str, -} - -/// De-mangles a Rust symbol into a more readable version -/// -/// This function will take a **mangled** symbol and return a value. When printed, -/// the de-mangled version will be written. If the symbol does not look like -/// a mangled symbol, the original value will be written instead. -pub fn demangle(s: &str) -> Result<(Demangle, &str), Invalid> { - // First validate the symbol. If it doesn't look like anything we're - // expecting, we just print it literally. Note that we must handle non-Rust - // symbols because we could have any function in the backtrace. - let inner; - if s.len() > 2 && s.starts_with("_R") { - inner = &s[2..]; - } else if s.len() > 1 && s.starts_with("R") { - // On Windows, dbghelp strips leading underscores, so we accept "R..." - // form too. - inner = &s[1..]; - } else if s.len() > 3 && s.starts_with("__R") { - // On OSX, symbols are prefixed with an extra _ - inner = &s[3..]; - } else { - return Err(Invalid); - } - - // Paths always start with uppercase characters. - match inner.as_bytes()[0] { - b'A'...b'Z' => {} - _ => return Err(Invalid), - } - - // only work with ascii text - if inner.bytes().any(|c| c & 0x80 != 0) { - return Err(Invalid); - } - - // Verify that the symbol is indeed a valid path. - let mut parser = Parser { - sym: inner, - next: 0, - }; - try!(parser.skip_path()); - - // Instantiating crate (paths always start with uppercase characters). - match parser.sym.as_bytes().get(parser.next) { - Some(&b'A'...b'Z') => { - try!(parser.skip_path()); - } - _ => {} - } - - Ok((Demangle { - inner: inner, - }, &parser.sym[parser.next..])) -} - -impl<'s> Display for Demangle<'s> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut printer = Printer { - parser: Ok(Parser { - sym: self.inner, - next: 0, - }), - out: f, - bound_lifetime_depth: 0, - }; - printer.print_path(true) - } -} - -#[derive(PartialEq, Eq)] -pub struct Invalid; - -struct Ident<'s> { - /// ASCII part of the identifier. - ascii: &'s str, - /// Punycode insertion codes for Unicode codepoints, if any. - punycode: &'s str, -} - -const SMALL_PUNYCODE_LEN: usize = 128; - -impl<'s> Ident<'s> { - /// Attempt to decode punycode on the stack (allocation-free), - /// and pass the char slice to the closure, if successful. - /// This supports up to `SMALL_PUNYCODE_LEN` characters. - fn try_small_punycode_decode R, R>( - &self, - f: F, - ) -> Option { - let mut out = ['\0'; SMALL_PUNYCODE_LEN]; - let mut out_len = 0; - let r = self.punycode_decode(|i, c| { - // Check there's space left for another character. - try!(out.get(out_len).ok_or(())); - - // Move the characters after the insert position. - let mut j = out_len; - out_len += 1; - - while j > i { - out[j] = out[j - 1]; - j -= 1; - } - - // Insert the new character. - out[i] = c; - - Ok(()) - }); - if r.is_ok() { - Some(f(&out[..out_len])) - } else { - None - } - } - - /// Decode punycode as insertion positions and characters - /// and pass them to the closure, which can return `Err(())` - /// to stop the decoding process. - fn punycode_decode Result<(), ()>>( - &self, - mut insert: F, - ) -> Result<(), ()> { - let mut punycode_bytes = self.punycode.bytes().peekable(); - if punycode_bytes.peek().is_none() { - return Err(()); - } - - let mut len = 0; - - // Populate initial output from ASCII fragment. - for c in self.ascii.chars() { - try!(insert(len, c)); - len += 1; - } - - // Punycode parameters and initial state. - let base = 36; - let t_min = 1; - let t_max = 26; - let skew = 38; - let mut damp = 700; - let mut bias = 72; - let mut i: usize = 0; - let mut n: usize = 0x80; - - loop { - // Read one delta value. - let mut delta: usize = 0; - let mut w = 1; - let mut k: usize = 0; - loop { - use core::cmp::{min, max}; - - k += base; - let t = min(max(k.saturating_sub(bias), t_min), t_max); - - let d = match punycode_bytes.next() { - Some(d @ b'a'...b'z') => d - b'a', - Some(d @ b'0'...b'9') => 26 + (d - b'0'), - _ => return Err(()), - }; - let d = d as usize; - delta = try!(delta.checked_add( - try!(d.checked_mul(w).ok_or(())) - ).ok_or(())); - if d < t { - break; - } - w = try!(w.checked_mul(base - t).ok_or(())); - } - - // Compute the new insert position and character. - len += 1; - i = try!(i.checked_add(delta).ok_or(())); - n = try!(n.checked_add(i / len).ok_or(())); - i %= len; - - let n_u32 = n as u32; - let c = if n_u32 as usize == n { - try!(char::from_u32(n_u32).ok_or(())) - } else { - return Err(()); - }; - - // Insert the new character and increment the insert position. - try!(insert(i, c)); - i += 1; - - // If there are no more deltas, decoding is complete. - if punycode_bytes.peek().is_none() { - return Ok(()); - } - - // Perform bias adaptation. - delta /= damp; - damp = 2; - - delta += delta / len; - let mut k = 0; - while delta > ((base - t_min) * t_max) / 2 { - delta /= base - t_min; - k += base; - } - bias = k + ((base - t_min + 1) * delta) / (delta + skew); - } - } -} - -impl<'s> Display for Ident<'s> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.try_small_punycode_decode(|chars| { - for &c in chars { - try!(c.fmt(f)); - } - Ok(()) - }).unwrap_or_else(|| { - if !self.punycode.is_empty() { - try!(f.write_str("punycode{")); - - // Reconstruct a standard Punycode encoding, - // by using `-` as the separator. - if !self.ascii.is_empty() { - try!(f.write_str(self.ascii)); - try!(f.write_str("-")); - } - try!(f.write_str(self.punycode)); - - f.write_str("}") - } else { - f.write_str(self.ascii) - } - }) - } -} - -fn basic_type(tag: u8) -> Option<&'static str> { - Some(match tag { - b'b' => "bool", - b'c' => "char", - b'e' => "str", - b'u' => "()", - b'a' => "i8", - b's' => "i16", - b'l' => "i32", - b'x' => "i64", - b'n' => "i128", - b'i' => "isize", - b'h' => "u8", - b't' => "u16", - b'm' => "u32", - b'y' => "u64", - b'o' => "u128", - b'j' => "usize", - b'f' => "f32", - b'd' => "f64", - b'z' => "!", - b'p' => "_", - b'v' => "...", - - _ => return None, - }) -} - -struct Parser<'s> { - sym: &'s str, - next: usize, -} - -impl<'s> Parser<'s> { - fn peek(&self) -> Option { - self.sym.as_bytes().get(self.next).cloned() - } - - fn eat(&mut self, b: u8) -> bool { - if self.peek() == Some(b) { - self.next += 1; - true - } else { - false - } - } - - fn next(&mut self) -> Result { - let b = try!(self.peek().ok_or(Invalid)); - self.next += 1; - Ok(b) - } - - fn hex_nibbles(&mut self) -> Result<&'s str, Invalid> { - let start = self.next; - loop { - match try!(self.next()) { - b'0'...b'9' | b'a'...b'f' => {} - b'_' => break, - _ => return Err(Invalid), - } - } - Ok(&self.sym[start..self.next - 1]) - } - - fn digit_10(&mut self) -> Result { - let d = match self.peek() { - Some(d @ b'0'...b'9') => d - b'0', - _ => return Err(Invalid), - }; - self.next += 1; - Ok(d) - } - - fn digit_62(&mut self) -> Result { - let d = match self.peek() { - Some(d @ b'0'...b'9') => d - b'0', - Some(d @ b'a'...b'z') => 10 + (d - b'a'), - Some(d @ b'A'...b'Z') => 10 + 26 + (d - b'A'), - _ => return Err(Invalid), - }; - self.next += 1; - Ok(d) - } - - fn integer_62(&mut self) -> Result { - if self.eat(b'_') { - return Ok(0); - } - - let mut x: u64 = 0; - while !self.eat(b'_') { - let d = try!(self.digit_62()) as u64; - x = try!(x.checked_mul(62).ok_or(Invalid)); - x = try!(x.checked_add(d).ok_or(Invalid)); - } - x.checked_add(1).ok_or(Invalid) - } - - fn opt_integer_62(&mut self, tag: u8) -> Result { - if !self.eat(tag) { - return Ok(0); - } - try!(self.integer_62()).checked_add(1).ok_or(Invalid) - } - - fn disambiguator(&mut self) -> Result { - self.opt_integer_62(b's') - } - - fn namespace(&mut self) -> Result, Invalid> { - match try!(self.next()) { - // Special namespaces, like closures and shims. - ns @ b'A'...b'Z' => Ok(Some(ns as char)), - - // Implementation-specific/unspecified namespaces. - b'a'...b'z' => Ok(None), - - _ => Err(Invalid), - } - } - - fn backref(&mut self) -> Result, Invalid> { - let s_start = self.next - 1; - let i = try!(self.integer_62()); - if i >= s_start as u64 { - return Err(Invalid); - } - Ok(Parser { - sym: self.sym, - next: i as usize, - }) - } - - fn ident(&mut self) -> Result, Invalid> { - let is_punycode = self.eat(b'u'); - let mut len = try!(self.digit_10()) as usize; - if len != 0 { - loop { - match self.digit_10() { - Ok(d) => { - len = try!(len.checked_mul(10).ok_or(Invalid)); - len = try!(len.checked_add(d as usize).ok_or(Invalid)); - } - Err(Invalid) => break, - } - } - } - - // Skip past the optional `_` separator. - self.eat(b'_'); - - let start = self.next; - self.next = try!(self.next.checked_add(len).ok_or(Invalid)); - if self.next > self.sym.len() { - return Err(Invalid); - } - - let ident = &self.sym[start..self.next]; - - if is_punycode { - let ident = match ident.bytes().rposition(|b| b == b'_') { - Some(i) => Ident { - ascii: &ident[..i], - punycode: &ident[i + 1..], - }, - None => Ident { - ascii: "", - punycode: ident, - }, - }; - if ident.punycode.is_empty() { - return Err(Invalid); - } - Ok(ident) - } else { - Ok(Ident { - ascii: ident, - punycode: "", - }) - } - } - - fn skip_path(&mut self) -> Result<(), Invalid> { - match try!(self.next()) { - b'C' => { - try!(self.disambiguator()); - try!(self.ident()); - } - b'N' => { - try!(self.namespace()); - try!(self.skip_path()); - try!(self.disambiguator()); - try!(self.ident()); - } - b'M' => { - try!(self.disambiguator()); - try!(self.skip_path()); - try!(self.skip_type()); - } - b'X' => { - try!(self.disambiguator()); - try!(self.skip_path()); - try!(self.skip_type()); - try!(self.skip_path()); - } - b'Y' => { - try!(self.skip_type()); - try!(self.skip_path()); - } - b'I' => { - try!(self.skip_path()); - while !self.eat(b'E') { - try!(self.skip_generic_arg()); - } - } - b'B' => { - try!(self.backref()); - } - _ => return Err(Invalid), - } - Ok(()) - } - - fn skip_generic_arg(&mut self) -> Result<(), Invalid> { - if self.eat(b'L') { - try!(self.integer_62()); - Ok(()) - } else if self.eat(b'K') { - self.skip_const() - } else { - self.skip_type() - } - } - - fn skip_type(&mut self) -> Result<(), Invalid> { - match try!(self.next()) { - tag if basic_type(tag).is_some() => {} - - b'R' | b'Q' => { - if self.eat(b'L') { - try!(self.integer_62()); - } - try!(self.skip_type()); - } - b'P' | b'O' | b'S' => try!(self.skip_type()), - b'A' => { - try!(self.skip_type()); - try!(self.skip_const()); - } - b'T' => while !self.eat(b'E') { - try!(self.skip_type()); - }, - b'F' => { - let _binder = try!(self.opt_integer_62(b'G')); - let _is_unsafe = self.eat(b'U'); - if self.eat(b'K') { - let c_abi = self.eat(b'C'); - if !c_abi { - let abi = try!(self.ident()); - if abi.ascii.is_empty() || !abi.punycode.is_empty() { - return Err(Invalid); - } - } - } - while !self.eat(b'E') { - try!(self.skip_type()); - } - try!(self.skip_type()); - } - b'D' => { - let _binder = try!(self.opt_integer_62(b'G')); - while !self.eat(b'E') { - try!(self.skip_path()); - while self.eat(b'p') { - try!(self.ident()); - try!(self.skip_type()); - } - } - if !self.eat(b'L') { - return Err(Invalid); - } - try!(self.integer_62()); - } - b'B' => { - try!(self.backref()); - } - _ => { - // Go back to the tag, so `skip_path` also sees it. - self.next -= 1; - try!(self.skip_path()); - } - } - Ok(()) - } - - fn skip_const(&mut self) -> Result<(), Invalid> { - if self.eat(b'B') { - try!(self.backref()); - return Ok(()); - } - - match try!(self.next()) { - // Unsigned integer types. - b'h' | b't' | b'm' | b'y' | b'o' | b'j' => {} - - _ => return Err(Invalid), - } - - if self.eat(b'p') { - return Ok(()); - } - try!(self.hex_nibbles()); - Ok(()) - } -} - -struct Printer<'a, 'b: 'a, 's> { - parser: Result, Invalid>, - out: &'a mut fmt::Formatter<'b>, - bound_lifetime_depth: u32, -} - -/// Mark the parser as errored, print `?` and return early. -/// This allows callers to keep printing the approximate -/// syntax of the path/type/const, despite having errors. -/// E.g. `Vec<[(A, ?); ?]>` instead of `Vec<[(A, ?`. -macro_rules! invalid { - ($printer:ident) => {{ - $printer.parser = Err(Invalid); - return $printer.out.write_str("?"); - }} -} - -/// Call a parser method (if the parser hasn't errored yet), -/// and mark the parser as errored if it returns `Err(Invalid)`. -/// -/// If the parser errored, before or now, prints `?`, and -/// returns early the current function (see `invalid!` above). -macro_rules! parse { - ($printer:ident, $method:ident $(($($arg:expr),*))*) => { - match $printer.parser_mut().and_then(|p| p.$method($($($arg),*)*)) { - Ok(x) => x, - Err(Invalid) => invalid!($printer), - } - }; -} - -impl<'a, 'b, 's> Printer<'a, 'b, 's> { - fn parser_mut<'c>(&'c mut self) -> Result<&'c mut Parser<'s>, Invalid> { - self.parser.as_mut().map_err(|_| Invalid) - } - - /// Eat the given character from the parser, - /// returning `false` if the parser errored. - fn eat(&mut self, b: u8) -> bool { - self.parser_mut().map(|p| p.eat(b)) == Ok(true) - } - - /// Return a nested parser for a backref. - fn backref_printer<'c>(&'c mut self) -> Printer<'c, 'b, 's> { - Printer { - parser: self.parser_mut().and_then(|p| p.backref()), - out: self.out, - bound_lifetime_depth: self.bound_lifetime_depth, - } - } - - /// Print the lifetime according to the previously decoded index. - /// An index of `0` always refers to `'_`, but starting with `1`, - /// indices refer to late-bound lifetimes introduced by a binder. - fn print_lifetime_from_index(&mut self, lt: u64) -> fmt::Result { - try!(self.out.write_str("'")); - if lt == 0 { - return self.out.write_str("_"); - } - match (self.bound_lifetime_depth as u64).checked_sub(lt) { - Some(depth) => { - // Try to print lifetimes alphabetically first. - if depth < 26 { - let c = (b'a' + depth as u8) as char; - c.fmt(self.out) - } else { - // Use `'_123` after running out of letters. - try!(self.out.write_str("_")); - depth.fmt(self.out) - } - } - None => invalid!(self), - } - } - - /// Optionally enter a binder ('G') for late-bound lifetimes, - /// printing e.g. `for<'a, 'b> ` before calling the closure, - /// and make those lifetimes visible to it (via depth level). - fn in_binder(&mut self, f: F) -> fmt::Result - where F: FnOnce(&mut Self) -> fmt::Result, - { - let bound_lifetimes = parse!(self, opt_integer_62(b'G')); - - if bound_lifetimes > 0 { - try!(self.out.write_str("for<")); - for i in 0..bound_lifetimes { - if i > 0 { - try!(self.out.write_str(", ")); - } - self.bound_lifetime_depth += 1; - try!(self.print_lifetime_from_index(1)); - } - try!(self.out.write_str("> ")); - } - - let r = f(self); - - // Restore `bound_lifetime_depth` to the previous value. - self.bound_lifetime_depth -= bound_lifetimes as u32; - - r - } - - /// Print list elements using the given closure and separator, - /// until the end of the list ('E') is found, or the parser errors. - /// Returns the number of elements printed. - fn print_sep_list(&mut self, f: F, sep: &str) -> Result - where F: Fn(&mut Self) -> fmt::Result, - { - let mut i = 0; - while self.parser.is_ok() && !self.eat(b'E') { - if i > 0 { - try!(self.out.write_str(sep)); - } - try!(f(self)); - i += 1; - } - Ok(i) - } - - fn print_path(&mut self, in_value: bool) -> fmt::Result { - let tag = parse!(self, next); - match tag { - b'C' => { - let dis = parse!(self, disambiguator); - let name = parse!(self, ident); - - try!(name.fmt(self.out)); - if !self.out.alternate() { - try!(self.out.write_str("[")); - try!(fmt::LowerHex::fmt(&dis, self.out)); - try!(self.out.write_str("]")); - } - } - b'N' => { - let ns = parse!(self, namespace); - - try!(self.print_path(in_value)); - - let dis = parse!(self, disambiguator); - let name = parse!(self, ident); - - match ns { - // Special namespaces, like closures and shims. - Some(ns) => { - try!(self.out.write_str("::{")); - match ns { - 'C' => try!(self.out.write_str("closure")), - 'S' => try!(self.out.write_str("shim")), - _ => try!(ns.fmt(self.out)), - } - if !name.ascii.is_empty() || !name.punycode.is_empty() { - try!(self.out.write_str(":")); - try!(name.fmt(self.out)); - } - try!(self.out.write_str("#")); - try!(dis.fmt(self.out)); - try!(self.out.write_str("}")); - } - - // Implementation-specific/unspecified namespaces. - None => { - if !name.ascii.is_empty() || !name.punycode.is_empty() { - try!(self.out.write_str("::")); - try!(name.fmt(self.out)); - } - } - } - } - b'M' | b'X' | b'Y' => { - if tag != b'Y' { - // Ignore the `impl`'s own path. - parse!(self, disambiguator); - parse!(self, skip_path); - } - - try!(self.out.write_str("<")); - try!(self.print_type()); - if tag != b'M' { - try!(self.out.write_str(" as ")); - try!(self.print_path(false)); - } - try!(self.out.write_str(">")); - } - b'I' => { - try!(self.print_path(in_value)); - if in_value { - try!(self.out.write_str("::")); - } - try!(self.out.write_str("<")); - try!(self.print_sep_list(Self::print_generic_arg, ", ")); - try!(self.out.write_str(">")); - } - b'B' => { - try!(self.backref_printer().print_path(in_value)); - } - _ => invalid!(self), - } - Ok(()) - } - - fn print_generic_arg(&mut self) -> fmt::Result { - if self.eat(b'L') { - let lt = parse!(self, integer_62); - self.print_lifetime_from_index(lt) - } else if self.eat(b'K') { - self.print_const() - } else { - self.print_type() - } - } - - fn print_type(&mut self) -> fmt::Result { - let tag = parse!(self, next); - - match basic_type(tag) { - Some(ty) => return self.out.write_str(ty), - None => {} - } - - match tag { - b'R' | b'Q' => { - try!(self.out.write_str("&")); - if self.eat(b'L') { - let lt = parse!(self, integer_62); - if lt != 0 { - try!(self.print_lifetime_from_index(lt)); - try!(self.out.write_str(" ")); - } - } - if tag != b'R' { - try!(self.out.write_str("mut ")); - } - try!(self.print_type()); - } - - b'P' | b'O' => { - try!(self.out.write_str("*")); - if tag != b'P' { - try!(self.out.write_str("mut ")); - } else { - try!(self.out.write_str("const ")); - } - try!(self.print_type()); - } - - b'A' | b'S' => { - try!(self.out.write_str("[")); - try!(self.print_type()); - if tag == b'A' { - try!(self.out.write_str("; ")); - try!(self.print_const()); - } - try!(self.out.write_str("]")); - } - b'T' => { - try!(self.out.write_str("(")); - let count = try!(self.print_sep_list(Self::print_type, ", ")); - if count == 1 { - try!(self.out.write_str(",")); - } - try!(self.out.write_str(")")); - } - b'F' => try!(self.in_binder(|this| { - let is_unsafe = this.eat(b'U'); - let abi = if this.eat(b'K') { - if this.eat(b'C') { - Some("C") - } else { - let abi = parse!(this, ident); - if abi.ascii.is_empty() || !abi.punycode.is_empty() { - invalid!(this); - } - Some(abi.ascii) - } - } else { - None - }; - - if is_unsafe { - try!(this.out.write_str("unsafe ")); - } - - match abi { - Some(abi) => { - try!(this.out.write_str("extern \"")); - - // If the ABI had any `-`, they were replaced with `_`, - // so the parts between `_` have to be re-joined with `-`. - let mut parts = abi.split('_'); - try!(this.out.write_str(parts.next().unwrap())); - for part in parts { - try!(this.out.write_str("-")); - try!(this.out.write_str(part)); - } - - try!(this.out.write_str("\" ")); - } - None => {} - } - - try!(this.out.write_str("fn(")); - try!(this.print_sep_list(Self::print_type, ", ")); - try!(this.out.write_str(")")); - - if this.eat(b'u') { - // Skip printing the return type if it's 'u', i.e. `()`. - } else { - try!(this.out.write_str(" -> ")); - try!(this.print_type()); - } - - Ok(()) - })), - b'D' => { - try!(self.out.write_str("dyn ")); - try!(self.in_binder(|this| { - try!(this.print_sep_list(Self::print_dyn_trait, " + ")); - Ok(()) - })); - - if !self.eat(b'L') { - invalid!(self); - } - let lt = parse!(self, integer_62); - if lt != 0 { - try!(self.out.write_str(" + ")); - try!(self.print_lifetime_from_index(lt)); - } - } - b'B' => { - try!(self.backref_printer().print_type()); - } - _ => { - // Go back to the tag, so `print_path` also sees it. - let _ = self.parser_mut().map(|p| p.next -= 1); - try!(self.print_path(false)); - } - } - Ok(()) - } - - /// A trait in a trait object may have some "existential projections" - /// (i.e. associated type bindings) after it, which should be printed - /// in the `<...>` of the trait, e.g. `dyn Trait`. - /// To this end, this method will keep the `<...>` of an 'I' path - /// open, by omitting the `>`, and return `Ok(true)` in that case. - fn print_path_maybe_open_generics(&mut self) -> Result { - if self.eat(b'B') { - self.backref_printer().print_path_maybe_open_generics() - } else if self.eat(b'I') { - try!(self.print_path(false)); - try!(self.out.write_str("<")); - try!(self.print_sep_list(Self::print_generic_arg, ", ")); - Ok(true) - } else { - try!(self.print_path(false)); - Ok(false) - } - } - - fn print_dyn_trait(&mut self) -> fmt::Result { - let mut open = try!(self.print_path_maybe_open_generics()); - - while self.eat(b'p') { - if !open { - try!(self.out.write_str("<")); - open = true; - } else { - try!(self.out.write_str(", ")); - } - - let name = parse!(self, ident); - try!(name.fmt(self.out)); - try!(self.out.write_str(" = ")); - try!(self.print_type()); - } - - if open { - try!(self.out.write_str(">")); - } - - Ok(()) - } - - fn print_const(&mut self) -> fmt::Result { - if self.eat(b'B') { - return self.backref_printer().print_const(); - } - - let ty_tag = parse!(self, next); - let ty = match ty_tag { - // Unsigned integer types. - b'h' | b't' | b'm' | b'y' | b'o' | b'j' => { - basic_type(ty_tag).unwrap() - } - - _ => invalid!(self), - }; - - - if self.eat(b'p') { - try!(self.out.write_str("_")); - } else { - try!(self.print_const_uint()); - } - - if !self.out.alternate() { - try!(self.out.write_str(": ")); - try!(self.out.write_str(ty)); - } - - Ok(()) - } - - fn print_const_uint(&mut self) -> fmt::Result { - let hex = parse!(self, hex_nibbles); - - // Print anything that doesn't fit in `u64` verbatim. - if hex.len() > 16 { - try!(self.out.write_str("0x")); - return self.out.write_str(hex); - } - - let mut v = 0; - for c in hex.chars() { - v = (v << 4) | (c.to_digit(16).unwrap() as u64); - } - v.fmt(self.out) - } -} - -#[cfg(test)] -mod tests { - macro_rules! t_nohash { - ($a:expr, $b:expr) => ({ - assert_eq!(format!("{:#}", ::demangle($a)), $b); - }) - } - macro_rules! t_nohash_type { - ($a:expr, $b:expr) => ( - t_nohash!(concat!("_RMC0", $a), concat!("<", $b, ">")) - ) - } - - #[test] - fn demangle_crate_with_leading_digit() { - t_nohash!( - "_RNvC6_123foo3bar", - "123foo::bar" - ); - } - - #[test] - fn demangle_utf8_idents() { - t_nohash!( - "_RNqCs4fqI2P2rA04_11utf8_identsu30____7hkackfecea1cbdathfdh9hlq6y", - "utf8_idents::საჭმელად_გემრიელი_სადილი" - ); - } - - #[test] - fn demangle_closure() { - t_nohash!( - "_RNCNCNgCs6DXkGYLi8lr_2cc5spawn00B5_", - "cc::spawn::{closure#0}::{closure#0}" - ); - t_nohash!( - "_RNCINkXs25_NgCsbmNqQUJIY6D_4core5sliceINyB9_4IterhENuNgNoBb_4iter8iterator8Iterator9rpositionNCNgNpB9_6memchr7memrchrs_0E0Bb_", - " as core::iter::iterator::Iterator>::rposition::::{closure#0}" - ); - } - - #[test] - fn demangle_dyn_trait() { - t_nohash!( - "_RINbNbCskIICzLVDPPb_5alloc5alloc8box_freeDINbNiB4_5boxed5FnBoxuEp6OutputuEL_ECs1iopQbuBiw2_3std", - "alloc::alloc::box_free::>" - ); - } - - #[test] - fn demangle_const_generics() { - // NOTE(eddyb) this was hand-written, before rustc had working - // const generics support (but the mangling format did include them). - t_nohash_type!( - "INtC8arrayvec8ArrayVechKj7b_E", - "arrayvec::ArrayVec" - ); - } - - #[test] - fn demangle_exponential_explosion() { - // NOTE(eddyb) because of the prefix added by `t_nohash_type!` is - // 3 bytes long, `B2_` refers to the start of the type, not `B_`. - // 6 backrefs (`B8_E` through `B3_E`) result in 2^6 = 64 copies of `_`. - // Also, because the `p` (`_`) type is after all of the starts of the - // backrefs, it can be replaced with any other type, independently. - t_nohash_type!( - concat!("TTTTTT", "p", "B8_E", "B7_E", "B6_E", "B5_E", "B4_E", "B3_E"), - "((((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _)))), \ - ((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _))))), \ - (((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _)))), \ - ((((_, _), (_, _)), ((_, _), (_, _))), (((_, _), (_, _)), ((_, _), (_, _))))))" - ); - } - - #[test] - fn demangle_thinlto() { - t_nohash!("_RC3foo.llvm.9D1C9369", "foo"); - t_nohash!("_RC3foo.llvm.9D1C9369@@16", "foo"); - t_nohash!("_RNvC9backtrace3foo.llvm.A5310EB9", "backtrace::foo"); - } - - #[test] - fn demangle_extra_suffix() { - // From alexcrichton/rustc-demangle#27: - t_nohash!( - "_RNvNtNtNtNtCs92dm3009vxr_4rand4rngs7adapter9reseeding4fork23FORK_HANDLER_REGISTERED.0.0", - "rand::rngs::adapter::reseeding::fork::FORK_HANDLER_REGISTERED.0.0" - ); - } -} diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/.cargo-checksum.json b/third_party/cargo/vendor/rustc_version-0.2.3/.cargo-checksum.json deleted file mode 100644 index f86fe1c..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"80b9fb136c8c2945b4875b05b0f5a4b11e4722997e751f17d8d3f241d7c684db","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"c9a75f18b9ab2927829a208fc6aa2cf4e63b8420887ba29cdb265d6619ae82d5","README.md":"58bd14a1dfa1d828e6e99f35c3b7c2149d08e2d990d6ca93f92ab8ffb43275b7","src/errors.rs":"b28c2eeb1278fc3e8d68a64b177034faed67f6762335729d3a6d1e61be8fb034","src/lib.rs":"92a32673f77961724bc52b872781f06d22d166f06838c9582c5adae3c5214f51"},"package":"138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"} \ No newline at end of file diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/BUILD b/third_party/cargo/vendor/rustc_version-0.2.3/BUILD deleted file mode 100644 index 658bd75..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "MIT,Apache-2.0" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - - -rust_library( - name = "rustc_version", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2015", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/semver-0.9.0:semver", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.2.3", - crate_features = [ - ], -) - diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/Cargo.toml b/third_party/cargo/vendor/rustc_version-0.2.3/Cargo.toml deleted file mode 100644 index 3b252b8..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "rustc_version" -version = "0.2.3" -authors = ["Marvin Löbel "] -description = "A library for querying the version of a installed rustc compiler" -documentation = "https://docs.rs/rustc_version/" -readme = "README.md" -keywords = ["version", "rustc"] -license = "MIT/Apache-2.0" -repository = "https://github.com/Kimundi/rustc-version-rs" -[dependencies.semver] -version = "0.9" -[badges.travis-ci] -repository = "Kimundi/rustc-version-rs" diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-APACHE b/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-MIT b/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-MIT deleted file mode 100644 index 40b8817..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2016 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/README.md b/third_party/cargo/vendor/rustc_version-0.2.3/README.md deleted file mode 100644 index f491ca9..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/README.md +++ /dev/null @@ -1,75 +0,0 @@ -rustc-version-rs -============== - -A library for querying the version of a `rustc` compiler. - -This can be used by build scripts or other tools dealing with Rust sources -to make decisions based on the version of the compiler. - -[![Travis-CI Status](https://travis-ci.org/Kimundi/rustc-version-rs.png?branch=master)](https://travis-ci.org/Kimundi/rustc-version-rs) - -# Getting Started - -[rustc-version-rs is available on crates.io](https://crates.io/crates/rustc_version). -It is recommended to look there for the newest released version, as well as links to the newest builds of the docs. - -At the point of the last update of this README, the latest published version could be used like this: - -Add the following dependency to your Cargo manifest... - -```toml -[build-dependencies] -rustc_version = "0.2" -``` - -...and see the [docs](http://kimundi.github.io/rustc-version-rs/rustc_version/index.html) for how to use it. - -# Example - -```rust -// This could be a cargo build script - -extern crate rustc_version; -use rustc_version::{version, version_meta, Channel, Version}; - -fn main() { - // Assert we haven't travelled back in time - assert!(version().unwrap().major >= 1); - - // Set cfg flags depending on release channel - match version_meta().unwrap().channel { - Channel::Stable => { - println!("cargo:rustc-cfg=RUSTC_IS_STABLE"); - } - Channel::Beta => { - println!("cargo:rustc-cfg=RUSTC_IS_BETA"); - } - Channel::Nightly => { - println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY"); - } - Channel::Dev => { - println!("cargo:rustc-cfg=RUSTC_IS_DEV"); - } - } - - // Check for a minimum version - if version().unwrap() >= Version::parse("1.4.0").unwrap() { - println!("cargo:rustc-cfg=compiler_has_important_bugfix"); - } -} -``` - -## License - -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 the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any -additional terms or conditions. diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/src/errors.rs b/third_party/cargo/vendor/rustc_version-0.2.3/src/errors.rs deleted file mode 100644 index 54557b6..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/src/errors.rs +++ /dev/null @@ -1,79 +0,0 @@ -use std::{self, error, fmt, io, str}; -use semver::{self, Identifier}; - -/// The error type for this crate. -#[derive(Debug)] -pub enum Error { - /// An error ocurrend when executing the `rustc` command. - CouldNotExecuteCommand(io::Error), - /// The output of `rustc -vV` was not valid utf-8. - Utf8Error(str::Utf8Error), - /// The output of `rustc -vV` was not in the expected format. - UnexpectedVersionFormat, - /// An error ocurred in parsing a `VersionReq`. - ReqParseError(semver::ReqParseError), - /// An error ocurred in parsing the semver. - SemVerError(semver::SemVerError), - /// The pre-release tag is unknown. - UnknownPreReleaseTag(Identifier), -} -use Error::*; - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::error::Error; - match *self { - CouldNotExecuteCommand(ref e) => write!(f, "{}: {}", self.description(), e), - Utf8Error(_) => write!(f, "{}", self.description()), - UnexpectedVersionFormat => write!(f, "{}", self.description()), - ReqParseError(ref e) => write!(f, "{}: {}", self.description(), e), - SemVerError(ref e) => write!(f, "{}: {}", self.description(), e), - UnknownPreReleaseTag(ref i) => write!(f, "{}: {}", self.description(), i), - } - } -} - -impl error::Error for Error { - fn cause(&self) -> Option<&error::Error> { - match *self { - CouldNotExecuteCommand(ref e) => Some(e), - Utf8Error(ref e) => Some(e), - UnexpectedVersionFormat => None, - ReqParseError(ref e) => Some(e), - SemVerError(ref e) => Some(e), - UnknownPreReleaseTag(_) => None, - } - } - - fn description(&self) -> &str { - match *self { - CouldNotExecuteCommand(_) => "could not execute command", - Utf8Error(_) => "invalid UTF-8 output from `rustc -vV`", - UnexpectedVersionFormat => "unexpected `rustc -vV` format", - ReqParseError(_) => "error parsing version requirement", - SemVerError(_) => "error parsing version", - UnknownPreReleaseTag(_) => "unknown pre-release tag", - } - } -} - -macro_rules! impl_from { - ($($err_ty:ty => $variant:ident),* $(,)*) => { - $( - impl From<$err_ty> for Error { - fn from(e: $err_ty) -> Error { - Error::$variant(e) - } - } - )* - } -} - -impl_from! { - str::Utf8Error => Utf8Error, - semver::SemVerError => SemVerError, - semver::ReqParseError => ReqParseError, -} - -/// The result type for this crate. -pub type Result = std::result::Result; diff --git a/third_party/cargo/vendor/rustc_version-0.2.3/src/lib.rs b/third_party/cargo/vendor/rustc_version-0.2.3/src/lib.rs deleted file mode 100644 index c038288..0000000 --- a/third_party/cargo/vendor/rustc_version-0.2.3/src/lib.rs +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2016 rustc-version-rs developers -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![warn(missing_docs)] - -//! Simple library for getting the version information of a `rustc` -//! compiler. -//! -//! This can be used by build scripts or other tools dealing with Rust sources -//! to make decisions based on the version of the compiler. -//! -//! It calls `$RUSTC --version -v` and parses the output, falling -//! back to `rustc` if `$RUSTC` is not set. -//! -//! # Example -//! -//! ```rust -//! // This could be a cargo build script -//! -//! extern crate rustc_version; -//! use rustc_version::{version, version_meta, Channel, Version}; -//! -//! fn main() { -//! // Assert we haven't travelled back in time -//! assert!(version().unwrap().major >= 1); -//! -//! // Set cfg flags depending on release channel -//! match version_meta().unwrap().channel { -//! Channel::Stable => { -//! println!("cargo:rustc-cfg=RUSTC_IS_STABLE"); -//! } -//! Channel::Beta => { -//! println!("cargo:rustc-cfg=RUSTC_IS_BETA"); -//! } -//! Channel::Nightly => { -//! println!("cargo:rustc-cfg=RUSTC_IS_NIGHTLY"); -//! } -//! Channel::Dev => { -//! println!("cargo:rustc-cfg=RUSTC_IS_DEV"); -//! } -//! } -//! -//! // Check for a minimum version -//! if version().unwrap() >= Version::parse("1.4.0").unwrap() { -//! println!("cargo:rustc-cfg=compiler_has_important_bugfix"); -//! } -//! } -//! ``` - -extern crate semver; -use semver::Identifier; -use std::process::Command; -use std::{env, str}; -use std::ffi::OsString; - -// Convenience re-export to allow version comparison without needing to add -// semver crate. -pub use semver::Version; - -mod errors; -pub use errors::{Error, Result}; - -/// Release channel of the compiler. -#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] -pub enum Channel { - /// Development release channel - Dev, - /// Nightly release channel - Nightly, - /// Beta release channel - Beta, - /// Stable release channel - Stable, -} - -/// Rustc version plus metada like git short hash and build date. -#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] -pub struct VersionMeta { - /// Version of the compiler - pub semver: Version, - - /// Git short hash of the build of the compiler - pub commit_hash: Option, - - /// Commit date of the compiler - pub commit_date: Option, - - /// Build date of the compiler; this was removed between Rust 1.0.0 and 1.1.0. - pub build_date: Option, - - /// Release channel of the compiler - pub channel: Channel, - - /// Host target triple of the compiler - pub host: String, - - /// Short version string of the compiler - pub short_version_string: String, -} - -impl VersionMeta { - /// Returns the version metadata for `cmd`, which should be a `rustc` command. - pub fn for_command(cmd: Command) -> Result { - let mut cmd = cmd; - - let out = cmd.arg("-vV").output().map_err(Error::CouldNotExecuteCommand)?; - let out = str::from_utf8(&out.stdout)?; - - version_meta_for(out) - } -} - -/// Returns the `rustc` SemVer version. -pub fn version() -> Result { - Ok(version_meta()?.semver) -} - -/// Returns the `rustc` SemVer version and additional metadata -/// like the git short hash and build date. -pub fn version_meta() -> Result { - let cmd = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")); - - VersionMeta::for_command(Command::new(cmd)) -} - -/// Parses a "rustc -vV" output string and returns -/// the SemVer version and additional metadata -/// like the git short hash and build date. -pub fn version_meta_for(verbose_version_string: &str) -> Result { - let out: Vec<_> = verbose_version_string.lines().collect(); - - if !(out.len() >= 6 && out.len() <= 8) { - return Err(Error::UnexpectedVersionFormat); - } - - let short_version_string = out[0]; - - fn expect_prefix<'a>(line: &'a str, prefix: &str) -> Result<&'a str> { - if line.starts_with(prefix) { - Ok(&line[prefix.len()..]) - } else { - Err(Error::UnexpectedVersionFormat) - } - } - - let commit_hash = match expect_prefix(out[2], "commit-hash: ")? { - "unknown" => None, - hash => Some(hash.to_owned()), - }; - - let commit_date = match expect_prefix(out[3], "commit-date: ")? { - "unknown" => None, - hash => Some(hash.to_owned()), - }; - - // Handle that the build date may or may not be present. - let mut idx = 4; - let mut build_date = None; - if out[idx].starts_with("build-date") { - build_date = match expect_prefix(out[idx], "build-date: ")? { - "unknown" => None, - s => Some(s.to_owned()), - }; - idx += 1; - } - - let host = expect_prefix(out[idx], "host: ")?; - idx += 1; - let release = expect_prefix(out[idx], "release: ")?; - - let semver: Version = release.parse()?; - - let channel = if semver.pre.is_empty() { - Channel::Stable - } else { - match semver.pre[0] { - Identifier::AlphaNumeric(ref s) if s == "dev" => Channel::Dev, - Identifier::AlphaNumeric(ref s) if s == "beta" => Channel::Beta, - Identifier::AlphaNumeric(ref s) if s == "nightly" => Channel::Nightly, - ref x => return Err(Error::UnknownPreReleaseTag(x.clone())), - } - }; - - Ok(VersionMeta { - semver: semver, - commit_hash: commit_hash, - commit_date: commit_date, - build_date: build_date, - channel: channel, - host: host.into(), - short_version_string: short_version_string.into(), - }) -} - -#[test] -fn smoketest() { - let v = version().unwrap(); - assert!(v.major >= 1); - - let v = version_meta().unwrap(); - assert!(v.semver.major >= 1); - - assert!(version().unwrap() >= Version::parse("1.0.0").unwrap()); -} - -#[test] -fn parse_unexpected() { - let res = version_meta_for( -"rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) -binary: rustc -commit-hash: a59de37e99060162a2674e3ff45409ac73595c0e -commit-date: 2015-05-13 -rust-birthday: 2015-05-14 -host: x86_64-unknown-linux-gnu -release: 1.0.0"); - - assert!(match res { - Err(Error::UnexpectedVersionFormat) => true, - _ => false, - }); - -} - -#[test] -fn parse_1_0_0() { - let version = version_meta_for( -"rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14) -binary: rustc -commit-hash: a59de37e99060162a2674e3ff45409ac73595c0e -commit-date: 2015-05-13 -build-date: 2015-05-14 -host: x86_64-unknown-linux-gnu -release: 1.0.0").unwrap(); - - assert_eq!(version.semver, Version::parse("1.0.0").unwrap()); - assert_eq!(version.commit_hash, Some("a59de37e99060162a2674e3ff45409ac73595c0e".into())); - assert_eq!(version.commit_date, Some("2015-05-13".into())); - assert_eq!(version.build_date, Some("2015-05-14".into())); - assert_eq!(version.channel, Channel::Stable); - assert_eq!(version.host, "x86_64-unknown-linux-gnu"); - assert_eq!(version.short_version_string, "rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)"); -} - - -#[test] -fn parse_unknown() { - let version = version_meta_for( -"rustc 1.3.0 -binary: rustc -commit-hash: unknown -commit-date: unknown -host: x86_64-unknown-linux-gnu -release: 1.3.0").unwrap(); - - assert_eq!(version.semver, Version::parse("1.3.0").unwrap()); - assert_eq!(version.commit_hash, None); - assert_eq!(version.commit_date, None); - assert_eq!(version.channel, Channel::Stable); - assert_eq!(version.host, "x86_64-unknown-linux-gnu"); - assert_eq!(version.short_version_string, "rustc 1.3.0"); -} - -#[test] -fn parse_nightly() { - let version = version_meta_for( -"rustc 1.5.0-nightly (65d5c0833 2015-09-29) -binary: rustc -commit-hash: 65d5c083377645a115c4ac23a620d3581b9562b6 -commit-date: 2015-09-29 -host: x86_64-unknown-linux-gnu -release: 1.5.0-nightly").unwrap(); - - assert_eq!(version.semver, Version::parse("1.5.0-nightly").unwrap()); - assert_eq!(version.commit_hash, Some("65d5c083377645a115c4ac23a620d3581b9562b6".into())); - assert_eq!(version.commit_date, Some("2015-09-29".into())); - assert_eq!(version.channel, Channel::Nightly); - assert_eq!(version.host, "x86_64-unknown-linux-gnu"); - assert_eq!(version.short_version_string, "rustc 1.5.0-nightly (65d5c0833 2015-09-29)"); -} - -#[test] -fn parse_stable() { - let version = version_meta_for( -"rustc 1.3.0 (9a92aaf19 2015-09-15) -binary: rustc -commit-hash: 9a92aaf19a64603b02b4130fe52958cc12488900 -commit-date: 2015-09-15 -host: x86_64-unknown-linux-gnu -release: 1.3.0").unwrap(); - - assert_eq!(version.semver, Version::parse("1.3.0").unwrap()); - assert_eq!(version.commit_hash, Some("9a92aaf19a64603b02b4130fe52958cc12488900".into())); - assert_eq!(version.commit_date, Some("2015-09-15".into())); - assert_eq!(version.channel, Channel::Stable); - assert_eq!(version.host, "x86_64-unknown-linux-gnu"); - assert_eq!(version.short_version_string, "rustc 1.3.0 (9a92aaf19 2015-09-15)"); -} - -#[test] -fn parse_1_16_0_nightly() { - let version = version_meta_for( -"rustc 1.16.0-nightly (5d994d8b7 2017-01-05) -binary: rustc -commit-hash: 5d994d8b7e482e87467d4a521911477bd8284ce3 -commit-date: 2017-01-05 -host: x86_64-unknown-linux-gnu -release: 1.16.0-nightly -LLVM version: 3.9").unwrap(); - - assert_eq!(version.semver, Version::parse("1.16.0-nightly").unwrap()); - assert_eq!(version.commit_hash, Some("5d994d8b7e482e87467d4a521911477bd8284ce3".into())); - assert_eq!(version.commit_date, Some("2017-01-05".into())); - assert_eq!(version.channel, Channel::Nightly); - assert_eq!(version.host, "x86_64-unknown-linux-gnu"); - assert_eq!(version.short_version_string, "rustc 1.16.0-nightly (5d994d8b7 2017-01-05)"); -} - -/* -#[test] -fn version_matches_replacement() { - let f = |s1: &str, s2: &str| { - let a = Version::parse(s1).unwrap(); - let b = Version::parse(s2).unwrap(); - println!("{} <= {} : {}", s1, s2, a <= b); - }; - - println!(); - - f("1.5.0", "1.5.0"); - f("1.5.0-nightly", "1.5.0"); - f("1.5.0", "1.5.0-nightly"); - f("1.5.0-nightly", "1.5.0-nightly"); - - f("1.5.0", "1.6.0"); - f("1.5.0-nightly", "1.6.0"); - f("1.5.0", "1.6.0-nightly"); - f("1.5.0-nightly", "1.6.0-nightly"); - - panic!(); - -} -*/ diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/.cargo-checksum.json b/third_party/cargo/vendor/scopeguard-0.3.3/.cargo-checksum.json deleted file mode 100644 index 8657b29..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"015263d52db02d239b69b9e3f090c2902056a80b8625e37a83bf4af79def93f7","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"7b63ecd5f1902af1b63729947373683c32745c16a10e8e6292e2e2dcd7e90ae0","README.rst":"e53c8b52d8c641b866ebc169fed1d2b154af70296ddf5e087e454de03a7e6040","examples/readme.rs":"5a01391acf2acc52a7a2e0ba58dc8ded3e8cc57d54b45778af5e8ba577158f86","src/lib.rs":"230fd73e62f7d43cd65931c16ed0083d2d4bfcd899abcf5215728732e0e601df"},"package":"94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27"} \ No newline at end of file diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/Cargo.toml b/third_party/cargo/vendor/scopeguard-0.3.3/Cargo.toml deleted file mode 100644 index 4a0d52b..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "scopeguard" -version = "0.3.3" -authors = ["bluss"] -description = "A RAII scope guard that will run a given closure when it goes out of scope,\neven if the code between panics (assuming unwinding panic).\n\nDefines the macros `defer!` and `defer_on_unwind!`; the latter only runs\nif the scope is extited through unwinding on panic.\n" -documentation = "https://docs.rs/scopeguard/" -keywords = ["scope-guard", "defer", "panic"] -categories = ["rust-patterns"] -license = "MIT/Apache-2.0" -repository = "https://github.com/bluss/scopeguard" -[package.metadata.release] -no-dev-version = true - -[features] -default = ["use_std"] -use_std = [] diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-MIT b/third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-MIT deleted file mode 100644 index e69282e..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2015 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/README.rst b/third_party/cargo/vendor/scopeguard-0.3.3/README.rst deleted file mode 100644 index d4699ea..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/README.rst +++ /dev/null @@ -1,81 +0,0 @@ - -scopeguard -========== - -Rust crate for a convenient RAII scope guard that will run a given closure when -it goes out of scope, even if the code between panics (assuming unwinding panic). - -The `defer!` macro and `guard` are `no_std` compatible (require only core), -but the on unwinding strategy requires linking to `std`. - -Requires Rust 1.11. - - -Please read the `API documentation here`__ - -__ https://docs.rs/scopeguard/ - -|build_status|_ |crates|_ - -.. |build_status| image:: https://travis-ci.org/bluss/scopeguard.svg -.. _build_status: https://travis-ci.org/bluss/scopeguard - -.. |crates| image:: http://meritbadge.herokuapp.com/scopeguard -.. _crates: https://crates.io/crates/scopeguard - -How to use ----------- - -.. code:: rust - - #[macro_use(defer)] extern crate scopeguard; - - use scopeguard::guard; - - fn f() { - defer!(println!("Called at return or panic")); - panic!(); - } - - use std::fs::File; - use std::io::Write; - - fn g() { - let f = File::create("newfile.txt").unwrap(); - let mut file = guard(f, |f| { - // write file at return or panic - let _ = f.sync_all(); - }); - // Access the file through the scope guard itself - file.write(b"test me\n").unwrap(); - } - -Recent Changes --------------- - -- 0.3.3 - - - Use ``#[inline]`` on a few more functions by @stjepang (#14) - - Add examples to crate documentation - -- 0.3.2 - - - Add crate categories - -- 0.3.1 - - - Add ``defer_on_unwind!``, ``Strategy`` trait - - Rename ``Guard`` → ``ScopeGuard`` - - Add ``ScopeGuard::with_strategy``. - - ``ScopeGuard`` now implements ``Debug``. - - Require Rust 1.11 - -- 0.2.0 - - - Require Rust 1.6 - - Use `no_std` unconditionally - - No other changes - -- 0.1.2 - - - Add macro ``defer!()`` diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/examples/readme.rs b/third_party/cargo/vendor/scopeguard-0.3.3/examples/readme.rs deleted file mode 100644 index 904bc54..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/examples/readme.rs +++ /dev/null @@ -1,27 +0,0 @@ - -#[macro_use(defer)] extern crate scopeguard; - -use scopeguard::guard; - -fn f() { - defer!(println!("Called at return or panic")); - panic!(); -} - -use std::fs::File; -use std::io::Write; - -fn g() { - let f = File::create("newfile.txt").unwrap(); - let mut file = guard(f, |f| { - // write file at return or panic - let _ = f.sync_all(); - }); - // Access the file through the scope guard itself - file.write(b"test me\n").unwrap(); -} - -fn main() { - f(); - g(); -} diff --git a/third_party/cargo/vendor/scopeguard-0.3.3/src/lib.rs b/third_party/cargo/vendor/scopeguard-0.3.3/src/lib.rs deleted file mode 100644 index ff3929a..0000000 --- a/third_party/cargo/vendor/scopeguard-0.3.3/src/lib.rs +++ /dev/null @@ -1,409 +0,0 @@ -#![cfg_attr(not(any(test, feature = "use_std")), no_std)] - -//! A scope guard will run a given closure when it goes out of scope, -//! even if the code between panics. -//! (as long as panic doesn't abort) -//! -//! # Examples -//! -//! ## `defer!` -//! -//! Use the `defer` macro to run an operation at scope exit, -//! either regular scope exit or during unwinding from a panic. -//! -//! ``` -//! #[macro_use(defer)] extern crate scopeguard; -//! -//! use std::cell::Cell; -//! -//! fn main() { -//! // use a cell to observe drops during and after the scope guard is active -//! let drop_counter = Cell::new(0); -//! { -//! // Create a scope guard using `defer!` for the current scope -//! defer! {{ -//! drop_counter.set(1 + drop_counter.get()); -//! }}; -//! -//! // Do regular operations here in the meantime. -//! -//! // Just before scope exit: it hasn't run yet. -//! assert_eq!(drop_counter.get(), 0); -//! -//! // The following scope end is where the defer closure is called -//! } -//! assert_eq!(drop_counter.get(), 1); -//! } -//! ``` -//! -//! ## Scope Guard with Value -//! -//! If the scope guard closure needs to access an outer value that is also -//! mutated outside of the scope guard, then you may want to use the scope guard -//! with a value. The guard works like a smart pointer, so the inner value can -//! be accessed by reference or by mutable reference. -//! -//! ### 1. The guard owns a file -//! -//! In this example, the scope guard owns a file and ensures pending writes are -//! synced at scope exit. -//! -//! ``` -//! extern crate scopeguard; -//! -//! use std::fs::File; -//! use std::io::{self, Write}; -//! -//! fn try_main() -> io::Result<()> { -//! let f = File::create("newfile.txt")?; -//! let mut file = scopeguard::guard(f, |f| { -//! // ensure we flush file at return or panic -//! let _ = f.sync_all(); -//! }); -//! // Access the file through the scope guard itself -//! file.write(b"test me\n").map(|_| ()) -//! } -//! -//! fn main() { -//! try_main().unwrap(); -//! } -//! -//! ``` -//! -//! ### 2. The guard restores an invariant on scope exit -//! -//! ``` -//! extern crate scopeguard; -//! -//! use std::mem::ManuallyDrop; -//! use std::ptr; -//! -//! // This function, just for this example, takes the first element -//! // and inserts it into the assumed sorted tail of the vector. -//! // -//! // For optimization purposes we temporarily violate an invariant of the -//! // Vec, that it owns all of its elements. -//! // -//! // The safe approach is to use swap, which means two writes to memory, -//! // the optimization is to use a “hole” which uses only one write of memory -//! // for each position it moves. -//! // -//! // We *must* use a scope guard to run this code safely. We -//! // are running arbitrary user code (comparison operators) that may panic. -//! // The scope guard ensures we restore the invariant after successful -//! // exit or during unwinding from panic. -//! fn insertion_sort_first(v: &mut Vec) -//! where T: PartialOrd -//! { -//! struct Hole<'a, T: 'a> { -//! v: &'a mut Vec, -//! index: usize, -//! value: ManuallyDrop, -//! } -//! -//! unsafe { -//! // Create a moved-from location in the vector, a “hole”. -//! let value = ptr::read(&v[0]); -//! let mut hole = Hole { v: v, index: 0, value: ManuallyDrop::new(value) }; -//! -//! // Use a scope guard with a value. -//! // At scope exit, plug the hole so that the vector is fully -//! // initialized again. -//! // The scope guard owns the hole, but we can access it through the guard. -//! let mut hole_guard = scopeguard::guard(hole, |hole| { -//! // plug the hole in the vector with the value that was // taken out -//! let index = hole.index; -//! ptr::copy_nonoverlapping(&*hole.value, &mut hole.v[index], 1); -//! }); -//! -//! // run algorithm that moves the hole in the vector here -//! // move the hole until it's in a sorted position -//! for i in 1..hole_guard.v.len() { -//! if *hole_guard.value >= hole_guard.v[i] { -//! // move the element back and the hole forward -//! let index = hole_guard.index; -//! ptr::copy_nonoverlapping(&hole_guard.v[index + 1], &mut hole_guard.v[index], 1); -//! hole_guard.index += 1; -//! } else { -//! break; -//! } -//! } -//! -//! // When the scope exits here, the Vec becomes whole again! -//! } -//! } -//! -//! fn main() { -//! let string = String::from; -//! let mut data = vec![string("c"), string("a"), string("b"), string("d")]; -//! insertion_sort_first(&mut data); -//! assert_eq!(data, vec!["a", "b", "c", "d"]); -//! } -//! -//! ``` -//! -//! -//! # Crate features: -//! -//! - `use_std` -//! + Enabled by default. Enables the `OnUnwind` strategy. -//! + Disable to use `no_std`. - -#[cfg(not(any(test, feature = "use_std")))] -extern crate core as std; - -use std::fmt; -use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; - -pub trait Strategy { - /// Return `true` if the guard’s associated code should run - /// (in the context where this method is called). - fn should_run() -> bool; -} - -/// Always run on scope exit. -/// -/// “Always” run: on regular exit from a scope or on unwinding from a panic. -/// Can not run on abort, process exit, and other catastrophic events where -/// destructors don’t run. -#[derive(Debug)] -pub enum Always {} - -/// Run on scope exit through unwinding. -/// -/// Requires crate feature `use_std`. -#[cfg(feature = "use_std")] -#[derive(Debug)] -pub enum OnUnwind {} - -/// Run on regular scope exit, when not unwinding. -/// -/// Requires crate feature `use_std`. -#[cfg(feature = "use_std")] -#[derive(Debug)] -#[cfg(test)] -enum OnSuccess {} - -impl Strategy for Always { - #[inline(always)] - fn should_run() -> bool { true } -} - -#[cfg(feature = "use_std")] -impl Strategy for OnUnwind { - #[inline(always)] - fn should_run() -> bool { std::thread::panicking() } -} - -#[cfg(feature = "use_std")] -#[cfg(test)] -impl Strategy for OnSuccess { - #[inline(always)] - fn should_run() -> bool { !std::thread::panicking() } -} - -/// Macro to create a `ScopeGuard` (always run). -/// -/// The macro takes one expression `$e`, which is the body of a closure -/// that will run when the scope is exited. The expression can -/// be a whole block. -#[macro_export] -macro_rules! defer { - ($e:expr) => { - let _guard = $crate::guard((), |_| $e); - } -} - -/// Macro to create a `ScopeGuard` (run on successful scope exit). -/// -/// The macro takes one expression `$e`, which is the body of a closure -/// that will run when the scope is exited. The expression can -/// be a whole block. -/// -/// Requires crate feature `use_std`. -#[cfg(test)] -macro_rules! defer_on_success { - ($e:expr) => { - let _guard = $crate::guard_on_success((), |_| $e); - } -} - -/// Macro to create a `ScopeGuard` (run on unwinding from panic). -/// -/// The macro takes one expression `$e`, which is the body of a closure -/// that will run when the scope is exited. The expression can -/// be a whole block. -/// -/// Requires crate feature `use_std`. -#[macro_export] -macro_rules! defer_on_unwind { - ($e:expr) => { - let _guard = $crate::guard_on_unwind((), |_| $e); - } -} - -/// `ScopeGuard` is a scope guard that may own a protected value. -/// -/// If you place a guard in a local variable, the closure can -/// run regardless how you leave the scope — through regular return or panic -/// (except if panic or other code aborts; so as long as destructors run). -/// It is run only once. -/// -/// The `S` parameter for [`Strategy`](Strategy.t.html) determines if -/// the closure actually runs. -/// -/// The guard's closure will be called with a mut ref to the held value -/// in the destructor. It's called only once. -/// -/// The `ScopeGuard` implements `Deref` so that you can access the inner value. -pub struct ScopeGuard - where F: FnMut(&mut T) -{ - __dropfn: F, - __value: T, - strategy: PhantomData, -} -impl ScopeGuard - where F: FnMut(&mut T), - S: Strategy, -{ - /// Create a `ScopeGuard` that owns `v` (accessible through deref) and calls - /// `dropfn` when its destructor runs. - /// - /// The `Strategy` decides whether the scope guard's closure should run. - #[inline] - pub fn with_strategy(v: T, dropfn: F) -> ScopeGuard { - ScopeGuard { - __value: v, - __dropfn: dropfn, - strategy: PhantomData, - } - } -} - - -/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. -#[inline] -pub fn guard(v: T, dropfn: F) -> ScopeGuard - where F: FnMut(&mut T) -{ - ScopeGuard::with_strategy(v, dropfn) -} - -/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. -/// -/// Requires crate feature `use_std`. -#[cfg(feature = "use_std")] -#[cfg(test)] -#[inline] -fn guard_on_success(v: T, dropfn: F) -> ScopeGuard - where F: FnMut(&mut T) -{ - ScopeGuard::with_strategy(v, dropfn) -} - -/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. -/// -/// Requires crate feature `use_std`. -#[cfg(feature = "use_std")] -#[inline] -pub fn guard_on_unwind(v: T, dropfn: F) -> ScopeGuard - where F: FnMut(&mut T) -{ - ScopeGuard::with_strategy(v, dropfn) -} - -impl Deref for ScopeGuard - where F: FnMut(&mut T) -{ - type Target = T; - fn deref(&self) -> &T { - &self.__value - } - -} - -impl DerefMut for ScopeGuard - where F: FnMut(&mut T) -{ - fn deref_mut(&mut self) -> &mut T { - &mut self.__value - } -} - -impl Drop for ScopeGuard - where F: FnMut(&mut T) -{ - fn drop(&mut self) { - if S::should_run() { - (self.__dropfn)(&mut self.__value) - } - } -} - -impl fmt::Debug for ScopeGuard - where T: fmt::Debug, - F: FnMut(&mut T), - S: Strategy + fmt::Debug, -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("ScopeGuard") - .field("value", &self.__value) - .finish() - } -} - -#[cfg(test)] -mod tests { - use std::cell::Cell; - use std::panic::catch_unwind; - use std::panic::AssertUnwindSafe; - - #[test] - fn test_defer() { - let drops = Cell::new(0); - defer!(drops.set(1000)); - assert_eq!(drops.get(), 0); - } - - #[test] - fn test_defer_success_1() { - let drops = Cell::new(0); - { - defer_on_success!(drops.set(1)); - assert_eq!(drops.get(), 0); - } - assert_eq!(drops.get(), 1); - } - - #[test] - fn test_defer_success_2() { - let drops = Cell::new(0); - let _ = catch_unwind(AssertUnwindSafe(|| { - defer_on_success!(drops.set(1)); - panic!("failure") - })); - assert_eq!(drops.get(), 0); - } - - #[test] - fn test_defer_unwind_1() { - let drops = Cell::new(0); - let _ = catch_unwind(AssertUnwindSafe(|| { - defer_on_unwind!(drops.set(1)); - assert_eq!(drops.get(), 0); - panic!("failure") - })); - assert_eq!(drops.get(), 1); - } - - #[test] - fn test_defer_unwind_2() { - let drops = Cell::new(0); - { - defer_on_unwind!(drops.set(1)); - } - assert_eq!(drops.get(), 0); - } -} diff --git a/third_party/cargo/vendor/semver-0.9.0/.cargo-checksum.json b/third_party/cargo/vendor/semver-0.9.0/.cargo-checksum.json deleted file mode 100644 index 2f9af6e..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"a5b995796b5559de8975a6fee7166c9fda6c21b449ec90bef5f9baaeddd479a5","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"c780d8c3c802c5fe2c316127900385010c3e57f71c851eea9e8ed8495e2030dd","src/lib.rs":"cb1725a8bb90c1043f187c6ba504d0a9d07793e2f39f5205f926c58849311770","src/version.rs":"ffdf9c628597b889f149f3b2b1245b97c774eae1ce7030bd19235eabecaaede0","src/version_req.rs":"40d20720f5fdc0b3d9e398e64eb448a65987229bd322cab0fedf0cf1843f3bd8","tests/deprecation.rs":"b5ec79e19d61968d05b96b876c449e54d43cbd1762c6e63c23c3470f9db56292","tests/regression.rs":"180b699ad029b81e6135d42f0a8e6d782177bc29a41132f875ee6f8607a46b56","tests/serde.rs":"cdbbefc576ffcc814c30dad9598ab87a7fd9d14c5f42f1349e1db6afc72f8fed"},"package":"1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"} \ No newline at end of file diff --git a/third_party/cargo/vendor/semver-0.9.0/BUILD b/third_party/cargo/vendor/semver-0.9.0/BUILD deleted file mode 100644 index 1b98b77..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -""" -cargo-raze crate build file. - -DO NOT EDIT! Replaced on runs of cargo-raze -""" -package(default_visibility = [ - # Public for visibility by "@raze__crate__version//" targets. - # - # Prefer access through "//third_party/cargo", which limits external - # visibility to explicit Cargo.toml dependencies. - "//visibility:public", -]) - -licenses([ - "notice", # "MIT,Apache-2.0" -]) - -load( - "@io_bazel_rules_rust//rust:rust.bzl", - "rust_library", - "rust_binary", - "rust_test", -) - - -# Unsupported target "deprecation" with type "test" omitted -# Unsupported target "regression" with type "test" omitted - -rust_library( - name = "semver", - crate_root = "src/lib.rs", - crate_type = "lib", - edition = "2015", - srcs = glob(["**/*.rs"]), - deps = [ - "//third_party/cargo/vendor/semver-parser-0.7.0:semver_parser", - ], - rustc_flags = [ - "--cap-lints=allow", - ], - version = "0.9.0", - crate_features = [ - "default", - ], -) - -# Unsupported target "serde" with type "test" omitted diff --git a/third_party/cargo/vendor/semver-0.9.0/Cargo.toml b/third_party/cargo/vendor/semver-0.9.0/Cargo.toml deleted file mode 100644 index 7749f76..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/Cargo.toml +++ /dev/null @@ -1,45 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies -# -# If you believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "semver" -version = "0.9.0" -authors = ["Steve Klabnik ", "The Rust Project Developers"] -description = "Semantic version parsing and comparison.\n" -homepage = "https://docs.rs/crate/semver/" -documentation = "https://docs.rs/crate/semver/" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/steveklabnik/semver" -[dependencies.semver-parser] -version = "0.7.0" - -[dependencies.serde] -version = "1.0" -optional = true -[dev-dependencies.crates-index] -version = "0.5.0" - -[dev-dependencies.serde_json] -version = "1.0" - -[dev-dependencies.serde_derive] -version = "1.0" - -[dev-dependencies.tempdir] -version = "0.3.4" - -[features] -default = [] -ci = ["serde"] -[badges.travis-ci] -repository = "steveklabnik/semver" diff --git a/third_party/cargo/vendor/semver-0.9.0/LICENSE-MIT b/third_party/cargo/vendor/semver-0.9.0/LICENSE-MIT deleted file mode 100644 index 39d4bdb..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project Developers - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/third_party/cargo/vendor/semver-0.9.0/README.md b/third_party/cargo/vendor/semver-0.9.0/README.md deleted file mode 100644 index 2a5306d..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/README.md +++ /dev/null @@ -1,103 +0,0 @@ -semver -====== - -Semantic version parsing and comparison. - -[![Build Status](https://api.travis-ci.org/steveklabnik/semver.svg?branch=master)](https://travis-ci.org/steveklabnik/semver) - -[Documentation](https://steveklabnik.github.io/semver) - -Semantic versioning (see http://semver.org/) is a set of rules for -assigning version numbers. - -## SemVer and the Rust ecosystem - -Rust itself follows the SemVer specification, as does its standard libraries. The two are -not tied together. - -[Cargo](https://crates.io), Rust's package manager, uses SemVer to determine which versions of -packages you need installed. - -## Installation - -To use `semver`, add this to your `[dependencies]` section: - -```toml -semver = "0.7.0" -``` - -And this to your crate root: - -```rust -extern crate semver; -``` - -## Versions - -At its simplest, the `semver` crate allows you to construct `Version` objects using the `parse` -method: - -```rust -use semver::Version; - -assert!(Version::parse("1.2.3") == Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec!(), - build: vec!(), -})); -``` - -If you have multiple `Version`s, you can use the usual comparison operators to compare them: - -```rust -use semver::Version; - -assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); -assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); -``` - -## Requirements - -The `semver` crate also provides the ability to compare requirements, which are more complex -comparisons. - -For example, creating a requirement that only matches versions greater than or -equal to 1.0.0: - -```rust -use semver::Version; -use semver::VersionReq; - -let r = VersionReq::parse(">= 1.0.0").unwrap(); -let v = Version::parse("1.0.0").unwrap(); - -assert!(r.to_string() == ">= 1.0.0".to_string()); -assert!(r.matches(&v)) -``` - -It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at -https://www.npmjs.org/doc/misc/semver.html - -**Tilde requirements** specify a minimal version with some updates: - -```notrust -~1.2.3 := >=1.2.3 <1.3.0 -~1.2 := >=1.2.0 <1.3.0 -~1 := >=1.0.0 <2.0.0 -``` - -**Caret requirements** allow SemVer compatible updates to a specified version, -`0.x` and `0.x+1` are not considered compatible, but `1.x` and `1.x+1` are. - -`0.0.x` is not considered compatible with any other version. -Missing minor and patch versions are desugared to `0` but allow flexibility for that value. - -```notrust -^1.2.3 := >=1.2.3 <2.0.0 -^0.2.3 := >=0.2.3 <0.3.0 -^0.0.3 := >=0.0.3 <0.0.4 -^0.0 := >=0.0.0 <0.1.0 -^0 := >=0.0.0 <1.0.0 -``` diff --git a/third_party/cargo/vendor/semver-0.9.0/src/lib.rs b/third_party/cargo/vendor/semver-0.9.0/src/lib.rs deleted file mode 100644 index a38aae0..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/src/lib.rs +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2012-2013 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Semantic version parsing and comparison. -//! -//! Semantic versioning (see http://semver.org/) is a set of rules for -//! assigning version numbers. -//! -//! ## SemVer overview -//! -//! Given a version number MAJOR.MINOR.PATCH, increment the: -//! -//! 1. MAJOR version when you make incompatible API changes, -//! 2. MINOR version when you add functionality in a backwards-compatible -//! manner, and -//! 3. PATCH version when you make backwards-compatible bug fixes. -//! -//! Additional labels for pre-release and build metadata are available as -//! extensions to the MAJOR.MINOR.PATCH format. -//! -//! Any references to 'the spec' in this documentation refer to [version 2.0 of -//! the SemVer spec](http://semver.org/spec/v2.0.0.html). -//! -//! ## SemVer and the Rust ecosystem -//! -//! Rust itself follows the SemVer specification, as does its standard -//! libraries. The two are not tied together. -//! -//! [Cargo](http://crates.io), Rust's package manager, uses SemVer to determine -//! which versions of packages you need installed. -//! -//! ## Versions -//! -//! At its simplest, the `semver` crate allows you to construct `Version` -//! objects using the `parse` method: -//! -//! ```{rust} -//! use semver::Version; -//! -//! assert!(Version::parse("1.2.3") == Ok(Version { -//! major: 1, -//! minor: 2, -//! patch: 3, -//! pre: vec!(), -//! build: vec!(), -//! })); -//! ``` -//! -//! If you have multiple `Version`s, you can use the usual comparison operators -//! to compare them: -//! -//! ```{rust} -//! use semver::Version; -//! -//! assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); -//! assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); -//! ``` -//! -//! If you explicitly need to modify a Version, SemVer also allows you to -//! increment the major, minor, and patch numbers in accordance with the spec. -//! -//! Please note that in order to do this, you must use a mutable Version: -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut bugfix_release = Version::parse("1.0.0").unwrap(); -//! bugfix_release.increment_patch(); -//! -//! assert_eq!(Ok(bugfix_release), Version::parse("1.0.1")); -//! ``` -//! -//! When incrementing the minor version number, the patch number resets to zero -//! (in accordance with section 7 of the spec) -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut feature_release = Version::parse("1.4.6").unwrap(); -//! feature_release.increment_minor(); -//! -//! assert_eq!(Ok(feature_release), Version::parse("1.5.0")); -//! ``` -//! -//! Similarly, when incrementing the major version number, the patch and minor -//! numbers reset to zero (in accordance with section 8 of the spec) -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut chrome_release = Version::parse("41.5.5377").unwrap(); -//! chrome_release.increment_major(); -//! -//! assert_eq!(Ok(chrome_release), Version::parse("42.0.0")); -//! ``` -//! -//! ## Requirements -//! -//! The `semver` crate also provides the ability to compare requirements, which -//! are more complex comparisons. -//! -//! For example, creating a requirement that only matches versions greater than -//! or equal to 1.0.0: -//! -//! ```{rust} -//! # #![allow(unstable)] -//! use semver::Version; -//! use semver::VersionReq; -//! -//! let r = VersionReq::parse(">= 1.0.0").unwrap(); -//! let v = Version::parse("1.0.0").unwrap(); -//! -//! assert!(r.to_string() == ">= 1.0.0".to_string()); -//! assert!(r.matches(&v)) -//! ``` -//! -//! It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at -//! https://www.npmjs.org/doc/misc/semver.html -//! -//! **Tilde requirements** specify a minimal version with some updates: -//! -//! ```notrust -//! ~1.2.3 := >=1.2.3 <1.3.0 -//! ~1.2 := >=1.2.0 <1.3.0 -//! ~1 := >=1.0.0 <2.0.0 -//! ``` -//! -//! **Caret requirements** allow SemVer compatible updates to a specified -//! verion, `0.x` and `0.x+1` are not considered compatible, but `1.x` and -//! `1.x+1` are. -//! -//! `0.0.x` is not considered compatible with any other version. -//! Missing minor and patch versions are desugared to `0` but allow flexibility -//! for that value. -//! -//! ```notrust -//! ^1.2.3 := >=1.2.3 <2.0.0 -//! ^0.2.3 := >=0.2.3 <0.3.0 -//! ^0.0.3 := >=0.0.3 <0.0.4 -//! ^0.0 := >=0.0.0 <0.1.0 -//! ^0 := >=0.0.0 <1.0.0 -//! ``` -//! -//! **Wildcard requirements** allows parsing of version requirements of the -//! formats `*`, `x.*` and `x.y.*`. -//! -//! ```notrust -//! * := >=0.0.0 -//! 1.* := >=1.0.0 <2.0.0 -//! 1.2.* := >=1.2.0 <1.3.0 -//! ``` - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico")] -#![deny(missing_docs)] -#![cfg_attr(test, deny(warnings))] - -extern crate semver_parser; - -// Serialization and deserialization support for version numbers -#[cfg(feature = "serde")] -extern crate serde; - -// We take the common approach of keeping our own module system private, and -// just re-exporting the interface that we want. - -pub use version::{Version, Identifier, SemVerError}; -pub use version::Identifier::{Numeric, AlphaNumeric}; -pub use version_req::{VersionReq, ReqParseError}; - -// SemVer-compliant versions. -mod version; - -// advanced version comparisons -mod version_req; diff --git a/third_party/cargo/vendor/semver-0.9.0/src/version.rs b/third_party/cargo/vendor/semver-0.9.0/src/version.rs deleted file mode 100644 index 38de133..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/src/version.rs +++ /dev/null @@ -1,759 +0,0 @@ -// Copyright 2012-2013 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The `version` module gives you tools to create and compare SemVer-compliant -//! versions. - -use std::cmp::{self, Ordering}; -use std::fmt; -use std::hash; -use std::error::Error; - -use std::result; -use std::str; - -use semver_parser; - -#[cfg(feature = "serde")] -use serde::ser::{Serialize, Serializer}; -#[cfg(feature = "serde")] -use serde::de::{self, Deserialize, Deserializer, Visitor}; - -/// An identifier in the pre-release or build metadata. -/// -/// See sections 9 and 10 of the spec for more about pre-release identifers and -/// build metadata. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub enum Identifier { - /// An identifier that's solely numbers. - Numeric(u64), - /// An identifier with letters and numbers. - AlphaNumeric(String), -} - -impl From for Identifier { - fn from(other: semver_parser::version::Identifier) -> Identifier { - match other { - semver_parser::version::Identifier::Numeric(n) => Identifier::Numeric(n), - semver_parser::version::Identifier::AlphaNumeric(s) => Identifier::AlphaNumeric(s), - } - } -} - -impl fmt::Display for Identifier { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Identifier::Numeric(ref n) => fmt::Display::fmt(n, f), - Identifier::AlphaNumeric(ref s) => fmt::Display::fmt(s, f), - } - } -} - -#[cfg(feature = "serde")] -impl Serialize for Identifier { - fn serialize(&self, serializer: S) -> result::Result - where S: Serializer - { - // Serialize Identifier as a number or string. - match *self { - Identifier::Numeric(n) => serializer.serialize_u64(n), - Identifier::AlphaNumeric(ref s) => serializer.serialize_str(s), - } - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for Identifier { - fn deserialize(deserializer: D) -> result::Result - where D: Deserializer<'de> - { - struct IdentifierVisitor; - - // Deserialize Identifier from a number or string. - impl<'de> Visitor<'de> for IdentifierVisitor { - type Value = Identifier; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer pre-release or build identifier") - } - - fn visit_u64(self, numeric: u64) -> result::Result - where E: de::Error - { - Ok(Identifier::Numeric(numeric)) - } - - fn visit_str(self, alphanumeric: &str) -> result::Result - where E: de::Error - { - Ok(Identifier::AlphaNumeric(alphanumeric.to_owned())) - } - } - - deserializer.deserialize_any(IdentifierVisitor) - } -} - -/// Represents a version number conforming to the semantic versioning scheme. -#[derive(Clone, Eq, Debug)] -pub struct Version { - /// The major version, to be incremented on incompatible changes. - pub major: u64, - /// The minor version, to be incremented when functionality is added in a - /// backwards-compatible manner. - pub minor: u64, - /// The patch version, to be incremented when backwards-compatible bug - /// fixes are made. - pub patch: u64, - /// The pre-release version identifier, if one exists. - pub pre: Vec, - /// The build metadata, ignored when determining version precedence. - pub build: Vec, -} - -impl From for Version { - fn from(other: semver_parser::version::Version) -> Version { - Version { - major: other.major, - minor: other.minor, - patch: other.patch, - pre: other.pre.into_iter().map(From::from).collect(), - build: other.build.into_iter().map(From::from).collect(), - } - } -} - -#[cfg(feature = "serde")] -impl Serialize for Version { - fn serialize(&self, serializer: S) -> result::Result - where S: Serializer - { - // Serialize Version as a string. - serializer.collect_str(self) - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for Version { - fn deserialize(deserializer: D) -> result::Result - where D: Deserializer<'de> - { - struct VersionVisitor; - - // Deserialize Version from a string. - impl<'de> Visitor<'de> for VersionVisitor { - type Value = Version; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer version as a string") - } - - fn visit_str(self, v: &str) -> result::Result - where E: de::Error - { - Version::parse(v).map_err(de::Error::custom) - } - } - - deserializer.deserialize_str(VersionVisitor) - } -} - -/// An error type for this crate -/// -/// Currently, just a generic error. Will make this nicer later. -#[derive(Clone,PartialEq,Debug,PartialOrd)] -pub enum SemVerError { - /// An error ocurred while parsing. - ParseError(String), -} - -impl fmt::Display for SemVerError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &SemVerError::ParseError(ref m) => write!(f, "{}", m), - } - } -} - -impl Error for SemVerError { - fn description(&self) -> &str { - match self { - &SemVerError::ParseError(ref m) => m, - } - } -} - -/// A Result type for errors -pub type Result = result::Result; - -impl Version { - - /// Contructs the simple case without pre or build. - pub fn new(major: u64, minor: u64, patch: u64) -> Version { - Version { - major: major, - minor: minor, - patch: patch, - pre: Vec::new(), - build: Vec::new() - } - } - - /// Parse a string into a semver object. - pub fn parse(version: &str) -> Result { - let res = semver_parser::version::parse(version); - - match res { - // Convert plain String error into proper ParseError - Err(e) => Err(SemVerError::ParseError(e)), - Ok(v) => Ok(From::from(v)), - } - } - - /// Clears the build metadata - fn clear_metadata(&mut self) { - self.build = Vec::new(); - self.pre = Vec::new(); - } - - /// Increments the patch number for this Version (Must be mutable) - pub fn increment_patch(&mut self) { - self.patch += 1; - self.clear_metadata(); - } - - /// Increments the minor version number for this Version (Must be mutable) - /// - /// As instructed by section 7 of the spec, the patch number is reset to 0. - pub fn increment_minor(&mut self) { - self.minor += 1; - self.patch = 0; - self.clear_metadata(); - } - - /// Increments the major version number for this Version (Must be mutable) - /// - /// As instructed by section 8 of the spec, the minor and patch numbers are - /// reset to 0 - pub fn increment_major(&mut self) { - self.major += 1; - self.minor = 0; - self.patch = 0; - self.clear_metadata(); - } - - /// Checks to see if the current Version is in pre-release status - pub fn is_prerelease(&self) -> bool { - !self.pre.is_empty() - } -} - -impl str::FromStr for Version { - type Err = SemVerError; - - fn from_str(s: &str) -> Result { - Version::parse(s) - } -} - -impl fmt::Display for Version { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); - if !self.pre.is_empty() { - try!(write!(f, "-")); - for (i, x) in self.pre.iter().enumerate() { - if i != 0 { - try!(write!(f, ".")) - } - try!(write!(f, "{}", x)); - } - } - if !self.build.is_empty() { - try!(write!(f, "+")); - for (i, x) in self.build.iter().enumerate() { - if i != 0 { - try!(write!(f, ".")) - } - try!(write!(f, "{}", x)); - } - } - Ok(()) - } -} - -impl cmp::PartialEq for Version { - #[inline] - fn eq(&self, other: &Version) -> bool { - // We should ignore build metadata here, otherwise versions v1 and v2 - // can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which - // violate strict total ordering rules. - self.major == other.major && self.minor == other.minor && self.patch == other.patch && - self.pre == other.pre - } -} - -impl cmp::PartialOrd for Version { - fn partial_cmp(&self, other: &Version) -> Option { - Some(self.cmp(other)) - } -} - -impl cmp::Ord for Version { - fn cmp(&self, other: &Version) -> Ordering { - match self.major.cmp(&other.major) { - Ordering::Equal => {} - r => return r, - } - - match self.minor.cmp(&other.minor) { - Ordering::Equal => {} - r => return r, - } - - match self.patch.cmp(&other.patch) { - Ordering::Equal => {} - r => return r, - } - - // NB: semver spec says 0.0.0-pre < 0.0.0 - // but the version of ord defined for vec - // says that [] < [pre] so we alter it here - match (self.pre.len(), other.pre.len()) { - (0, 0) => Ordering::Equal, - (0, _) => Ordering::Greater, - (_, 0) => Ordering::Less, - (_, _) => self.pre.cmp(&other.pre), - } - } -} - -impl hash::Hash for Version { - fn hash(&self, into: &mut H) { - self.major.hash(into); - self.minor.hash(into); - self.patch.hash(into); - self.pre.hash(into); - } -} - -impl From<(u64,u64,u64)> for Version { - fn from(tuple: (u64,u64,u64)) -> Version { - let (major, minor, patch) = tuple; - Version::new(major, minor, patch) - } -} - -#[cfg(test)] -mod tests { - use std::result; - use super::Version; - use super::Identifier; - use super::SemVerError; - - #[test] - fn test_parse() { - fn parse_error(e: &str) -> result::Result { - return Err(SemVerError::ParseError(e.to_string())); - } - - assert_eq!(Version::parse(""), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse(" "), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse("1"), - parse_error("Expected dot")); - assert_eq!(Version::parse("1.2"), - parse_error("Expected dot")); - assert_eq!(Version::parse("1.2.3-"), - parse_error("Error parsing prerelease")); - assert_eq!(Version::parse("a.b.c"), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse("1.2.3 abc"), - parse_error("Extra junk after valid version: abc")); - - assert_eq!(Version::parse("1.2.3"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - - assert_eq!(Version::parse("1.2.3"), - Ok(Version::new(1,2,3))); - - assert_eq!(Version::parse(" 1.2.3 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!(Version::parse("1.2.3-alpha1"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(Version::parse(" 1.2.3-alpha1 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(Version::parse("1.2.3+build5"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse(" 1.2.3+build5 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse("1.2.3-alpha1+build5"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse(" 1.2.3-alpha1+build5 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::Numeric(1), - Identifier::AlphaNumeric(String::from("alpha1")), - Identifier::Numeric(9), - ], - build: vec![Identifier::AlphaNumeric(String::from("build5")), - Identifier::Numeric(7), - Identifier::AlphaNumeric(String::from("3aedf")), - ], - })); - assert_eq!(Version::parse("0.4.0-beta.1+0851523"), - Ok(Version { - major: 0, - minor: 4, - patch: 0, - pre: vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1), - ], - build: vec![Identifier::AlphaNumeric(String::from("0851523"))], - })); - - } - - #[test] - fn test_increment_patch() { - let mut buggy_release = Version::parse("0.1.0").unwrap(); - buggy_release.increment_patch(); - assert_eq!(buggy_release, Version::parse("0.1.1").unwrap()); - } - - #[test] - fn test_increment_minor() { - let mut feature_release = Version::parse("1.4.6").unwrap(); - feature_release.increment_minor(); - assert_eq!(feature_release, Version::parse("1.5.0").unwrap()); - } - - #[test] - fn test_increment_major() { - let mut chrome_release = Version::parse("46.1.246773").unwrap(); - chrome_release.increment_major(); - assert_eq!(chrome_release, Version::parse("47.0.0").unwrap()); - } - - #[test] - fn test_increment_keep_prerelease() { - let mut release = Version::parse("1.0.0-alpha").unwrap(); - release.increment_patch(); - - assert_eq!(release, Version::parse("1.0.1").unwrap()); - - release.increment_minor(); - - assert_eq!(release, Version::parse("1.1.0").unwrap()); - - release.increment_major(); - - assert_eq!(release, Version::parse("2.0.0").unwrap()); - } - - - #[test] - fn test_increment_clear_metadata() { - let mut release = Version::parse("1.0.0+4442").unwrap(); - release.increment_patch(); - - assert_eq!(release, Version::parse("1.0.1").unwrap()); - release = Version::parse("1.0.1+hello").unwrap(); - - release.increment_minor(); - - assert_eq!(release, Version::parse("1.1.0").unwrap()); - release = Version::parse("1.1.3747+hello").unwrap(); - - release.increment_major(); - - assert_eq!(release, Version::parse("2.0.0").unwrap()); - } - - #[test] - fn test_eq() { - assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3")); - assert_eq!(Version::parse("1.2.3-alpha1"), - Version::parse("1.2.3-alpha1")); - assert_eq!(Version::parse("1.2.3+build.42"), - Version::parse("1.2.3+build.42")); - assert_eq!(Version::parse("1.2.3-alpha1+42"), - Version::parse("1.2.3-alpha1+42")); - assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42")); - } - - #[test] - fn test_ne() { - assert!(Version::parse("0.0.0") != Version::parse("0.0.1")); - assert!(Version::parse("0.0.0") != Version::parse("0.1.0")); - assert!(Version::parse("0.0.0") != Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); - } - - #[test] - fn test_show() { - assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()), - "1.2.3".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()), - "1.2.3-alpha1".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()), - "1.2.3+build.42".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()), - "1.2.3-alpha1+42".to_string()); - } - - #[test] - fn test_to_string() { - assert_eq!(Version::parse("1.2.3").unwrap().to_string(), - "1.2.3".to_string()); - assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), - "1.2.3-alpha1".to_string()); - assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), - "1.2.3+build.42".to_string()); - assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), - "1.2.3-alpha1+42".to_string()); - } - - #[test] - fn test_lt() { - assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3")); - assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2")); - assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2"))); - assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42"))); - } - - #[test] - fn test_le() { - assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42")); - } - - #[test] - fn test_gt() { - assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1")); - assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2")); - assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2"))); - assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42"))); - } - - #[test] - fn test_ge() { - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42")); - } - - #[test] - fn test_prerelease_check() { - assert!(Version::parse("1.0.0").unwrap().is_prerelease() == false); - assert!(Version::parse("0.0.1").unwrap().is_prerelease() == false); - assert!(Version::parse("4.1.4-alpha").unwrap().is_prerelease()); - assert!(Version::parse("1.0.0-beta294296").unwrap().is_prerelease()); - } - - #[test] - fn test_spec_order() { - let vs = ["1.0.0-alpha", - "1.0.0-alpha.1", - "1.0.0-alpha.beta", - "1.0.0-beta", - "1.0.0-beta.2", - "1.0.0-beta.11", - "1.0.0-rc.1", - "1.0.0"]; - let mut i = 1; - while i < vs.len() { - let a = Version::parse(vs[i - 1]); - let b = Version::parse(vs[i]); - assert!(a < b, "nope {:?} < {:?}", a, b); - i += 1; - } - } - - #[test] - fn test_from_str() { - assert_eq!("1.2.3".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!(" 1.2.3 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!("1.2.3-alpha1".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(" 1.2.3-alpha1 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!("1.2.3+build5".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(" 1.2.3+build5 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!("1.2.3-alpha1+build5".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(" 1.2.3-alpha1+build5 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!("1.2.3-1.alpha1.9+build5.7.3aedf ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::Numeric(1), - Identifier::AlphaNumeric(String::from("alpha1")), - Identifier::Numeric(9), - ], - build: vec![Identifier::AlphaNumeric(String::from("build5")), - Identifier::Numeric(7), - Identifier::AlphaNumeric(String::from("3aedf")), - ], - })); - assert_eq!("0.4.0-beta.1+0851523".parse(), - Ok(Version { - major: 0, - minor: 4, - patch: 0, - pre: vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1), - ], - build: vec![Identifier::AlphaNumeric(String::from("0851523"))], - })); - - } - - #[test] - fn test_from_str_errors() { - fn parse_error(e: &str) -> result::Result { - return Err(SemVerError::ParseError(e.to_string())); - } - - assert_eq!("".parse(), parse_error("Error parsing major identifier")); - assert_eq!(" ".parse(), parse_error("Error parsing major identifier")); - assert_eq!("1".parse(), parse_error("Expected dot")); - assert_eq!("1.2".parse(), - parse_error("Expected dot")); - assert_eq!("1.2.3-".parse(), - parse_error("Error parsing prerelease")); - assert_eq!("a.b.c".parse(), - parse_error("Error parsing major identifier")); - assert_eq!("1.2.3 abc".parse(), - parse_error("Extra junk after valid version: abc")); - } -} diff --git a/third_party/cargo/vendor/semver-0.9.0/src/version_req.rs b/third_party/cargo/vendor/semver-0.9.0/src/version_req.rs deleted file mode 100644 index 6e6a542..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/src/version_req.rs +++ /dev/null @@ -1,895 +0,0 @@ -// Copyright 2012-2013 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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::error::Error; -use std::fmt; -use std::result; -use std::str; - -use Version; -use version::Identifier; -use semver_parser; - -#[cfg(feature = "serde")] -use serde::ser::{Serialize, Serializer}; -#[cfg(feature = "serde")] -use serde::de::{self, Deserialize, Deserializer, Visitor}; - -use self::Op::{Ex, Gt, GtEq, Lt, LtEq, Tilde, Compatible, Wildcard}; -use self::WildcardVersion::{Major, Minor, Patch}; -use self::ReqParseError::*; - -/// A `VersionReq` is a struct containing a list of predicates that can apply to ranges of version -/// numbers. Matching operations can then be done with the `VersionReq` against a particular -/// version to see if it satisfies some or all of the constraints. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct VersionReq { - predicates: Vec, -} - -impl From for VersionReq { - fn from(other: semver_parser::range::VersionReq) -> VersionReq { - VersionReq { predicates: other.predicates.into_iter().map(From::from).collect() } - } -} - -#[cfg(feature = "serde")] -impl Serialize for VersionReq { - fn serialize(&self, serializer: S) -> result::Result - where S: Serializer - { - // Serialize VersionReq as a string. - serializer.collect_str(self) - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for VersionReq { - fn deserialize(deserializer: D) -> result::Result - where D: Deserializer<'de> - { - struct VersionReqVisitor; - - /// Deserialize `VersionReq` from a string. - impl<'de> Visitor<'de> for VersionReqVisitor { - type Value = VersionReq; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer version requirement as a string") - } - - fn visit_str(self, v: &str) -> result::Result - where E: de::Error - { - VersionReq::parse(v).map_err(de::Error::custom) - } - } - - deserializer.deserialize_str(VersionReqVisitor) - } -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -enum WildcardVersion { - Major, - Minor, - Patch, -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -enum Op { - Ex, // Exact - Gt, // Greater than - GtEq, // Greater than or equal to - Lt, // Less than - LtEq, // Less than or equal to - Tilde, // e.g. ~1.0.0 - Compatible, // compatible by definition of semver, indicated by ^ - Wildcard(WildcardVersion), // x.y.*, x.*, * -} - -impl From for Op { - fn from(other: semver_parser::range::Op) -> Op { - use semver_parser::range; - match other { - range::Op::Ex => Op::Ex, - range::Op::Gt => Op::Gt, - range::Op::GtEq => Op::GtEq, - range::Op::Lt => Op::Lt, - range::Op::LtEq => Op::LtEq, - range::Op::Tilde => Op::Tilde, - range::Op::Compatible => Op::Compatible, - range::Op::Wildcard(version) => { - match version { - range::WildcardVersion::Major => Op::Wildcard(WildcardVersion::Major), - range::WildcardVersion::Minor => Op::Wildcard(WildcardVersion::Minor), - range::WildcardVersion::Patch => Op::Wildcard(WildcardVersion::Patch), - } - } - } - } -} - -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -struct Predicate { - op: Op, - major: u64, - minor: Option, - patch: Option, - pre: Vec, -} - -impl From for Predicate { - fn from(other: semver_parser::range::Predicate) -> Predicate { - Predicate { - op: From::from(other.op), - major: other.major, - minor: other.minor, - patch: other.patch, - pre: other.pre.into_iter().map(From::from).collect(), - } - } -} - -/// A `ReqParseError` is returned from methods which parse a string into a `VersionReq`. Each -/// enumeration is one of the possible errors that can occur. -#[derive(Clone, Debug, PartialEq)] -pub enum ReqParseError { - /// The given version requirement is invalid. - InvalidVersionRequirement, - /// You have already provided an operation, such as `=`, `~`, or `^`. Only use one. - OpAlreadySet, - /// The sigil you have written is not correct. - InvalidSigil, - /// All components of a version must be numeric. - VersionComponentsMustBeNumeric, - /// There was an error parsing an identifier. - InvalidIdentifier, - /// At least a major version is required. - MajorVersionRequired, - /// An unimplemented version requirement. - UnimplementedVersionRequirement, - /// This form of requirement is deprecated. - DeprecatedVersionRequirement(VersionReq), -} - -impl fmt::Display for ReqParseError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.description().fmt(f) - } -} - -impl Error for ReqParseError { - fn description(&self) -> &str { - match self { - &InvalidVersionRequirement => "the given version requirement is invalid", - &OpAlreadySet => { - "you have already provided an operation, such as =, ~, or ^; only use one" - }, - &InvalidSigil => "the sigil you have written is not correct", - &VersionComponentsMustBeNumeric => "version components must be numeric", - &InvalidIdentifier => "invalid identifier", - &MajorVersionRequired => "at least a major version number is required", - &UnimplementedVersionRequirement => { - "the given version requirement is not implemented, yet" - }, - &DeprecatedVersionRequirement(_) => "This requirement is deprecated", - } - } -} - -impl From for ReqParseError { - fn from(other: String) -> ReqParseError { - match &*other { - "Null is not a valid VersionReq" => ReqParseError::InvalidVersionRequirement, - "VersionReq did not parse properly." => ReqParseError::OpAlreadySet, - _ => ReqParseError::InvalidVersionRequirement, - } - } -} - -impl VersionReq { - /// `any()` is a factory method which creates a `VersionReq` with no constraints. In other - /// words, any version will match against it. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// - /// let anything = VersionReq::any(); - /// ``` - pub fn any() -> VersionReq { - VersionReq { predicates: vec![] } - } - - /// `parse()` is the main constructor of a `VersionReq`. It takes a string like `"^1.2.3"` - /// and turns it into a `VersionReq` that matches that particular constraint. - /// - /// A `Result` is returned which contains a `ReqParseError` if there was a problem parsing the - /// `VersionReq`. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// - /// let version = VersionReq::parse("=1.2.3"); - /// let version = VersionReq::parse(">1.2.3"); - /// let version = VersionReq::parse("<1.2.3"); - /// let version = VersionReq::parse("~1.2.3"); - /// let version = VersionReq::parse("^1.2.3"); - /// let version = VersionReq::parse("1.2.3"); // synonym for ^1.2.3 - /// let version = VersionReq::parse("<=1.2.3"); - /// let version = VersionReq::parse(">=1.2.3"); - /// ``` - /// - /// This example demonstrates error handling, and will panic. - /// - /// ```should-panic - /// use semver::VersionReq; - /// - /// let version = match VersionReq::parse("not a version") { - /// Ok(version) => version, - /// Err(e) => panic!("There was a problem parsing: {}", e), - /// } - /// ``` - pub fn parse(input: &str) -> Result { - let res = semver_parser::range::parse(input); - - if let Ok(v) = res { - return Ok(From::from(v)); - } - - return match VersionReq::parse_deprecated(input) { - Some(v) => { - Err(ReqParseError::DeprecatedVersionRequirement(v)) - } - None => Err(From::from(res.err().unwrap())), - } - } - - fn parse_deprecated(version: &str) -> Option { - return match version { - ".*" => Some(VersionReq::any()), - "0.1.0." => Some(VersionReq::parse("0.1.0").unwrap()), - "0.3.1.3" => Some(VersionReq::parse("0.3.13").unwrap()), - "0.2*" => Some(VersionReq::parse("0.2.*").unwrap()), - "*.0" => Some(VersionReq::any()), - _ => None, - } - } - - /// `exact()` is a factory method which creates a `VersionReq` with one exact constraint. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// use semver::Version; - /// - /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; - /// let exact = VersionReq::exact(&version); - /// ``` - pub fn exact(version: &Version) -> VersionReq { - VersionReq { predicates: vec![Predicate::exact(version)] } - } - - /// `matches()` matches a given `Version` against this `VersionReq`. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// use semver::Version; - /// - /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; - /// let exact = VersionReq::exact(&version); - /// - /// assert!(exact.matches(&version)); - /// ``` - pub fn matches(&self, version: &Version) -> bool { - // no predicates means anything matches - if self.predicates.is_empty() { - return true; - } - - self.predicates.iter().all(|p| p.matches(version)) && - self.predicates.iter().any(|p| p.pre_tag_is_compatible(version)) - } -} - -impl str::FromStr for VersionReq { - type Err = ReqParseError; - - fn from_str(s: &str) -> Result { - VersionReq::parse(s) - } -} - -impl Predicate { - fn exact(version: &Version) -> Predicate { - Predicate { - op: Ex, - major: version.major, - minor: Some(version.minor), - patch: Some(version.patch), - pre: version.pre.clone(), - } - } - - /// `matches()` takes a `Version` and determines if it matches this particular `Predicate`. - pub fn matches(&self, ver: &Version) -> bool { - match self.op { - Ex => self.is_exact(ver), - Gt => self.is_greater(ver), - GtEq => self.is_exact(ver) || self.is_greater(ver), - Lt => !self.is_exact(ver) && !self.is_greater(ver), - LtEq => !self.is_greater(ver), - Tilde => self.matches_tilde(ver), - Compatible => self.is_compatible(ver), - Wildcard(_) => self.matches_wildcard(ver), - } - } - - fn is_exact(&self, ver: &Version) -> bool { - if self.major != ver.major { - return false; - } - - match self.minor { - Some(minor) => { - if minor != ver.minor { - return false; - } - } - None => return true, - } - - match self.patch { - Some(patch) => { - if patch != ver.patch { - return false; - } - } - None => return true, - } - - if self.pre != ver.pre { - return false; - } - - true - } - - // https://docs.npmjs.com/misc/semver#prerelease-tags - fn pre_tag_is_compatible(&self, ver: &Version) -> bool { - // If a version has a prerelease tag (for example, 1.2.3-alpha.3) then it will - // only be - // allowed to satisfy comparator sets if at least one comparator with the same - // [major, - // minor, patch] tuple also has a prerelease tag. - !ver.is_prerelease() || - (self.major == ver.major && self.minor == Some(ver.minor) && - self.patch == Some(ver.patch) && !self.pre.is_empty()) - } - - fn is_greater(&self, ver: &Version) -> bool { - if self.major != ver.major { - return ver.major > self.major; - } - - match self.minor { - Some(minor) => { - if minor != ver.minor { - return ver.minor > minor; - } - } - None => return false, - } - - match self.patch { - Some(patch) => { - if patch != ver.patch { - return ver.patch > patch; - } - } - None => return false, - } - - if !self.pre.is_empty() { - return ver.pre.is_empty() || ver.pre > self.pre; - } - - false - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn matches_tilde(&self, ver: &Version) -> bool { - let minor = match self.minor { - Some(n) => n, - None => return self.major == ver.major, - }; - - match self.patch { - Some(patch) => { - self.major == ver.major && minor == ver.minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) - } - None => self.major == ver.major && minor == ver.minor, - } - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn is_compatible(&self, ver: &Version) -> bool { - if self.major != ver.major { - return false; - } - - let minor = match self.minor { - Some(n) => n, - None => return self.major == ver.major, - }; - - match self.patch { - Some(patch) => { - if self.major == 0 { - if minor == 0 { - ver.minor == minor && ver.patch == patch && self.pre_is_compatible(ver) - } else { - ver.minor == minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) - } - } else { - ver.minor > minor || - (ver.minor == minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver)))) - } - } - None => { - if self.major == 0 { - ver.minor == minor - } else { - ver.minor >= minor - } - } - } - } - - fn pre_is_compatible(&self, ver: &Version) -> bool { - ver.pre.is_empty() || ver.pre >= self.pre - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn matches_wildcard(&self, ver: &Version) -> bool { - match self.op { - Wildcard(Major) => true, - Wildcard(Minor) => self.major == ver.major, - Wildcard(Patch) => { - match self.minor { - Some(minor) => self.major == ver.major && minor == ver.minor, - None => { - // minor and patch version astericks mean match on major - self.major == ver.major - } - } - } - _ => false, // unreachable - } - } -} - -impl fmt::Display for VersionReq { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - if self.predicates.is_empty() { - try!(write!(fmt, "*")); - } else { - for (i, ref pred) in self.predicates.iter().enumerate() { - if i == 0 { - try!(write!(fmt, "{}", pred)); - } else { - try!(write!(fmt, ", {}", pred)); - } - } - } - - Ok(()) - } -} - -impl fmt::Display for Predicate { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match self.op { - Wildcard(Major) => try!(write!(fmt, "*")), - Wildcard(Minor) => try!(write!(fmt, "{}.*", self.major)), - Wildcard(Patch) => { - if let Some(minor) = self.minor { - try!(write!(fmt, "{}.{}.*", self.major, minor)) - } else { - try!(write!(fmt, "{}.*.*", self.major)) - } - } - _ => { - try!(write!(fmt, "{}{}", self.op, self.major)); - - match self.minor { - Some(v) => try!(write!(fmt, ".{}", v)), - None => (), - } - - match self.patch { - Some(v) => try!(write!(fmt, ".{}", v)), - None => (), - } - - if !self.pre.is_empty() { - try!(write!(fmt, "-")); - for (i, x) in self.pre.iter().enumerate() { - if i != 0 { - try!(write!(fmt, ".")) - } - try!(write!(fmt, "{}", x)); - } - } - } - } - - Ok(()) - } -} - -impl fmt::Display for Op { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { - Ex => try!(write!(fmt, "= ")), - Gt => try!(write!(fmt, "> ")), - GtEq => try!(write!(fmt, ">= ")), - Lt => try!(write!(fmt, "< ")), - LtEq => try!(write!(fmt, "<= ")), - Tilde => try!(write!(fmt, "~")), - Compatible => try!(write!(fmt, "^")), - // gets handled specially in Predicate::fmt - Wildcard(_) => try!(write!(fmt, "")), - } - Ok(()) - } -} - -#[cfg(test)] -mod test { - use super::{VersionReq, Op}; - use super::super::version::Version; - use std::hash::{Hash, Hasher}; - - fn req(s: &str) -> VersionReq { - VersionReq::parse(s).unwrap() - } - - fn version(s: &str) -> Version { - match Version::parse(s) { - Ok(v) => v, - Err(e) => panic!("`{}` is not a valid version. Reason: {:?}", s, e), - } - } - - fn assert_match(req: &VersionReq, vers: &[&str]) { - for ver in vers.iter() { - assert!(req.matches(&version(*ver)), "did not match {}", ver); - } - } - - fn assert_not_match(req: &VersionReq, vers: &[&str]) { - for ver in vers.iter() { - assert!(!req.matches(&version(*ver)), "matched {}", ver); - } - } - - fn calculate_hash(t: T) -> u64 { - use std::collections::hash_map::DefaultHasher; - - let mut s = DefaultHasher::new(); - t.hash(&mut s); - s.finish() - } - - #[test] - fn test_parsing_default() { - let r = req("1.0.0"); - - assert_eq!(r.to_string(), "^1.0.0".to_string()); - - assert_match(&r, &["1.0.0", "1.0.1"]); - assert_not_match(&r, &["0.9.9", "0.10.0", "0.1.0"]); - } - - #[test] - fn test_parsing_exact() { - let r = req("=1.0.0"); - - assert!(r.to_string() == "= 1.0.0".to_string()); - assert_eq!(r.to_string(), "= 1.0.0".to_string()); - - assert_match(&r, &["1.0.0"]); - assert_not_match(&r, &["1.0.1", "0.9.9", "0.10.0", "0.1.0", "1.0.0-pre"]); - - let r = req("=0.9.0"); - - assert_eq!(r.to_string(), "= 0.9.0".to_string()); - - assert_match(&r, &["0.9.0"]); - assert_not_match(&r, &["0.9.1", "1.9.0", "0.0.9"]); - - let r = req("=0.1.0-beta2.a"); - - assert_eq!(r.to_string(), "= 0.1.0-beta2.a".to_string()); - - assert_match(&r, &["0.1.0-beta2.a"]); - assert_not_match(&r, &["0.9.1", "0.1.0", "0.1.1-beta2.a", "0.1.0-beta2"]); - } - - #[test] - fn test_parse_metadata_see_issue_88_see_issue_88() { - for op in &[Op::Compatible, Op::Ex, Op::Gt, Op::GtEq, Op::Lt, Op::LtEq, Op::Tilde] { - req(&format!("{} 1.2.3+meta", op)); - } - } - - #[test] - pub fn test_parsing_greater_than() { - let r = req(">= 1.0.0"); - - assert_eq!(r.to_string(), ">= 1.0.0".to_string()); - - assert_match(&r, &["1.0.0", "2.0.0"]); - assert_not_match(&r, &["0.1.0", "0.0.1", "1.0.0-pre", "2.0.0-pre"]); - - let r = req(">= 2.1.0-alpha2"); - - assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha3", "2.1.0", "3.0.0"]); - assert_not_match(&r, - &["2.0.0", "2.1.0-alpha1", "2.0.0-alpha2", "3.0.0-alpha2"]); - } - - #[test] - pub fn test_parsing_less_than() { - let r = req("< 1.0.0"); - - assert_eq!(r.to_string(), "< 1.0.0".to_string()); - - assert_match(&r, &["0.1.0", "0.0.1"]); - assert_not_match(&r, &["1.0.0", "1.0.0-beta", "1.0.1", "0.9.9-alpha"]); - - let r = req("<= 2.1.0-alpha2"); - - assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha1", "2.0.0", "1.0.0"]); - assert_not_match(&r, - &["2.1.0", "2.2.0-alpha1", "2.0.0-alpha2", "1.0.0-alpha2"]); - } - - #[test] - pub fn test_multiple() { - let r = req("> 0.0.9, <= 2.5.3"); - assert_eq!(r.to_string(), "> 0.0.9, <= 2.5.3".to_string()); - assert_match(&r, &["0.0.10", "1.0.0", "2.5.3"]); - assert_not_match(&r, &["0.0.8", "2.5.4"]); - - let r = req("0.3.0, 0.4.0"); - assert_eq!(r.to_string(), "^0.3.0, ^0.4.0".to_string()); - assert_not_match(&r, &["0.0.8", "0.3.0", "0.4.0"]); - - let r = req("<= 0.2.0, >= 0.5.0"); - assert_eq!(r.to_string(), "<= 0.2.0, >= 0.5.0".to_string()); - assert_not_match(&r, &["0.0.8", "0.3.0", "0.5.1"]); - - let r = req("0.1.0, 0.1.4, 0.1.6"); - assert_eq!(r.to_string(), "^0.1.0, ^0.1.4, ^0.1.6".to_string()); - assert_match(&r, &["0.1.6", "0.1.9"]); - assert_not_match(&r, &["0.1.0", "0.1.4", "0.2.0"]); - - assert!(VersionReq::parse("> 0.1.0,").is_err()); - assert!(VersionReq::parse("> 0.3.0, ,").is_err()); - - let r = req(">=0.5.1-alpha3, <0.6"); - assert_eq!(r.to_string(), ">= 0.5.1-alpha3, < 0.6".to_string()); - assert_match(&r, - &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); - assert_not_match(&r, - &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre"]); - assert_not_match(&r, &["0.6.0", "0.6.0-pre"]); - } - - #[test] - pub fn test_parsing_tilde() { - let r = req("~1"); - assert_match(&r, &["1.0.0", "1.0.1", "1.1.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "0.0.9"]); - - let r = req("~1.2"); - assert_match(&r, &["1.2.0", "1.2.1"]); - assert_not_match(&r, &["1.1.1", "1.3.0", "0.0.9"]); - - let r = req("~1.2.2"); - assert_match(&r, &["1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.2.1", "1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - - let r = req("~1.2.3-beta.2"); - assert_match(&r, &["1.2.3", "1.2.4", "1.2.3-beta.2", "1.2.3-beta.4"]); - assert_not_match(&r, &["1.3.3", "1.1.4", "1.2.3-beta.1", "1.2.4-beta.2"]); - } - - #[test] - pub fn test_parsing_compatible() { - let r = req("^1"); - assert_match(&r, &["1.1.2", "1.1.0", "1.2.1", "1.0.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "0.1.4"]); - assert_not_match(&r, &["1.0.0-beta1", "0.1.0-alpha", "1.0.1-pre"]); - - let r = req("^1.1"); - assert_match(&r, &["1.1.2", "1.1.0", "1.2.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.0.1", "0.1.4"]); - - let r = req("^1.1.2"); - assert_match(&r, &["1.1.2", "1.1.4", "1.2.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); - assert_not_match(&r, &["1.1.2-alpha1", "1.1.3-alpha1", "2.9.0-alpha1"]); - - let r = req("^0.1.2"); - assert_match(&r, &["0.1.2", "0.1.4"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); - assert_not_match(&r, &["0.1.2-beta", "0.1.3-alpha", "0.2.0-pre"]); - - let r = req("^0.5.1-alpha3"); - assert_match(&r, - &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); - assert_not_match(&r, - &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre", "0.6.0"]); - - let r = req("^0.0.2"); - assert_match(&r, &["0.0.2"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1", "0.1.4"]); - - let r = req("^0.0"); - assert_match(&r, &["0.0.2", "0.0.0"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.1.4"]); - - let r = req("^0"); - assert_match(&r, &["0.9.1", "0.0.2", "0.0.0"]); - assert_not_match(&r, &["2.9.0", "1.1.1"]); - - let r = req("^1.4.2-beta.5"); - assert_match(&r, - &["1.4.2", "1.4.3", "1.4.2-beta.5", "1.4.2-beta.6", "1.4.2-c"]); - assert_not_match(&r, - &["0.9.9", "2.0.0", "1.4.2-alpha", "1.4.2-beta.4", "1.4.3-beta.5"]); - } - - #[test] - pub fn test_parsing_wildcard() { - let r = req(""); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("*"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("x"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("X"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - - let r = req("1.*"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - let r = req("1.x"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - let r = req("1.X"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - - let r = req("1.2.*"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - let r = req("1.2.x"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - let r = req("1.2.X"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - } - - #[test] - pub fn test_any() { - let r = VersionReq::any(); - assert_match(&r, &["0.0.1", "0.1.0", "1.0.0"]); - } - - #[test] - pub fn test_pre() { - let r = req("=2.1.1-really.0"); - assert_match(&r, &["2.1.1-really.0"]); - } - - // #[test] - // pub fn test_parse_errors() { - // assert_eq!(Err(InvalidVersionRequirement), VersionReq::parse("\0")); - // assert_eq!(Err(OpAlreadySet), VersionReq::parse(">= >= 0.0.2")); - // assert_eq!(Err(InvalidSigil), VersionReq::parse(">== 0.0.2")); - // assert_eq!(Err(VersionComponentsMustBeNumeric), - // VersionReq::parse("a.0.0")); - // assert_eq!(Err(InvalidIdentifier), VersionReq::parse("1.0.0-")); - // assert_eq!(Err(MajorVersionRequired), VersionReq::parse(">=")); - // } - - #[test] - pub fn test_from_str() { - assert_eq!("1.0.0".parse::().unwrap().to_string(), - "^1.0.0".to_string()); - assert_eq!("=1.0.0".parse::().unwrap().to_string(), - "= 1.0.0".to_string()); - assert_eq!("~1".parse::().unwrap().to_string(), - "~1".to_string()); - assert_eq!("~1.2".parse::().unwrap().to_string(), - "~1.2".to_string()); - assert_eq!("^1".parse::().unwrap().to_string(), - "^1".to_string()); - assert_eq!("^1.1".parse::().unwrap().to_string(), - "^1.1".to_string()); - assert_eq!("*".parse::().unwrap().to_string(), - "*".to_string()); - assert_eq!("1.*".parse::().unwrap().to_string(), - "1.*".to_string()); - assert_eq!("< 1.0.0".parse::().unwrap().to_string(), - "< 1.0.0".to_string()); - } - - // #[test] - // pub fn test_from_str_errors() { - // assert_eq!(Err(InvalidVersionRequirement), "\0".parse::()); - // assert_eq!(Err(OpAlreadySet), ">= >= 0.0.2".parse::()); - // assert_eq!(Err(InvalidSigil), ">== 0.0.2".parse::()); - // assert_eq!(Err(VersionComponentsMustBeNumeric), - // "a.0.0".parse::()); - // assert_eq!(Err(InvalidIdentifier), "1.0.0-".parse::()); - // assert_eq!(Err(MajorVersionRequired), ">=".parse::()); - // } - - #[test] - fn test_cargo3202() { - let v = "0.*.*".parse::().unwrap(); - assert_eq!("0.*.*", format!("{}", v.predicates[0])); - - let v = "0.0.*".parse::().unwrap(); - assert_eq!("0.0.*", format!("{}", v.predicates[0])); - - let r = req("0.*.*"); - assert_match(&r, &["0.5.0"]); - } - - #[test] - fn test_eq_hash() { - assert!(req("^1") == req("^1")); - assert!(calculate_hash(req("^1")) == calculate_hash(req("^1"))); - assert!(req("^1") != req("^2")); - } - - #[test] - fn test_ordering() { - assert!(req("=1") < req("*")); - assert!(req(">1") < req("*")); - assert!(req(">=1") < req("*")); - assert!(req("<1") < req("*")); - assert!(req("<=1") < req("*")); - assert!(req("~1") < req("*")); - assert!(req("^1") < req("*")); - assert!(req("*") == req("*")); - } -} diff --git a/third_party/cargo/vendor/semver-0.9.0/tests/deprecation.rs b/third_party/cargo/vendor/semver-0.9.0/tests/deprecation.rs deleted file mode 100644 index a5f533a..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/tests/deprecation.rs +++ /dev/null @@ -1,22 +0,0 @@ -extern crate semver; - -#[test] -fn test_regressions() { - use semver::VersionReq; - use semver::ReqParseError; - - let versions = vec![ - (".*", VersionReq::any()), - ("0.1.0.", VersionReq::parse("0.1.0").unwrap()), - ("0.3.1.3", VersionReq::parse("0.3.13").unwrap()), - ("0.2*", VersionReq::parse("0.2.*").unwrap()), - ("*.0", VersionReq::any()), - ]; - - for (version, requirement) in versions.into_iter() { - let parsed = VersionReq::parse(version); - let error = parsed.err().unwrap(); - - assert_eq!(ReqParseError::DeprecatedVersionRequirement(requirement), error); - } -} diff --git a/third_party/cargo/vendor/semver-0.9.0/tests/regression.rs b/third_party/cargo/vendor/semver-0.9.0/tests/regression.rs deleted file mode 100644 index ef568a7..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/tests/regression.rs +++ /dev/null @@ -1,25 +0,0 @@ -extern crate semver; -extern crate crates_index; -extern crate tempdir; - -// This test checks to see if every existing crate parses successfully. Important to not break the -// Rust universe! - -#[cfg(feature = "ci")] -#[test] -fn test_regressions() { - use tempdir::TempDir; - use crates_index::Index; - use semver::Version; - - let dir = TempDir::new("semver").unwrap(); - let index = Index::new(dir.into_path()); - index.clone().unwrap(); - - for krate in index.crates() { - for version in krate.versions() { - let v = version.version(); - assert!(Version::parse(v).is_ok(), "failed: {} ({})", version.name(), v); - } - } -} diff --git a/third_party/cargo/vendor/semver-0.9.0/tests/serde.rs b/third_party/cargo/vendor/semver-0.9.0/tests/serde.rs deleted file mode 100644 index bcb9264..0000000 --- a/third_party/cargo/vendor/semver-0.9.0/tests/serde.rs +++ /dev/null @@ -1,90 +0,0 @@ -#![cfg(feature = "serde")] - -#[macro_use] -extern crate serde_derive; - -extern crate semver; -extern crate serde_json; - -use semver::{Identifier, Version, VersionReq}; - -#[derive(Serialize, Deserialize, PartialEq, Debug)] -struct Identified { - name: String, - identifier: Identifier, -} - -#[derive(Serialize, Deserialize, PartialEq, Debug)] -struct Versioned { - name: String, - vers: Version, -} - -#[test] -fn serialize_identifier() { - let id = Identified { - name: "serde".to_owned(), - identifier: Identifier::Numeric(100), - }; - let j = serde_json::to_string(&id).unwrap(); - assert_eq!(j, r#"{"name":"serde","identifier":100}"#); - - let id = Identified { - name: "serde".to_owned(), - identifier: Identifier::AlphaNumeric("b100".to_owned()), - }; - let j = serde_json::to_string(&id).unwrap(); - assert_eq!(j, r#"{"name":"serde","identifier":"b100"}"#); -} - -#[test] -fn deserialize_identifier() { - let j = r#"{"name":"serde","identifier":100}"#; - let id = serde_json::from_str::(j).unwrap(); - let expected = Identified { - name: "serde".to_owned(), - identifier: Identifier::Numeric(100), - }; - assert_eq!(id, expected); - - let j = r#"{"name":"serde","identifier":"b100"}"#; - let id = serde_json::from_str::(j).unwrap(); - let expected = Identified { - name: "serde".to_owned(), - identifier: Identifier::AlphaNumeric("b100".to_owned()), - }; - assert_eq!(id, expected); -} - -#[test] -fn serialize_version() { - let v = Versioned { - name: "serde".to_owned(), - vers: Version::parse("1.0.0").unwrap(), - }; - let j = serde_json::to_string(&v).unwrap(); - assert_eq!(j, r#"{"name":"serde","vers":"1.0.0"}"#); -} - -#[test] -fn deserialize_version() { - let j = r#"{"name":"serde","vers":"1.0.0"}"#; - let v = serde_json::from_str::(j).unwrap(); - let expected = Versioned { - name: "serde".to_owned(), - vers: Version::parse("1.0.0").unwrap(), - }; - assert_eq!(v, expected); -} - -#[test] -fn serialize_versionreq() { - let v = VersionReq::exact(&Version::parse("1.0.0").unwrap()); - - assert_eq!(serde_json::to_string(&v).unwrap(), r#""= 1.0.0""#); -} - -#[test] -fn deserialize_versionreq() { - assert_eq!("1.0.0".parse::().unwrap(), serde_json::from_str(r#""1.0.0""#).unwrap()); -} diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/.cargo-checksum.json b/third_party/cargo/vendor/semver-parser-0.7.0/.cargo-checksum.json deleted file mode 100644 index 73575fe..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"67597114802114d2a7fdb457c1cf5f7e0c951b21e287c6a47b9a86b9028cf64d","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"d38feaa4f9468cd1e0ece22e0ad2eadfe6195a9a0a3843b7c722d5c7d81804fb","src/common.rs":"dc42336abd34e19ca9f732f33657e106f98dcc8c10d4c2564bc4f160cb31926e","src/lib.rs":"3ac8ef5a280344a25cb18ac386034c0fee8d64060fa14af5e25ed49f0cb2fd9e","src/range.rs":"3596f048d466d43887aff1e8c8c834476672a4627631ed35379c35466b5f02ec","src/recognize.rs":"9f16eda9fcd7d8af7eee4c3b89c611bd648040273fde6b35778f8a50b004c8b1","src/version.rs":"dbd91a4e4fd92a0aa9eb4f858ecbc1ecd680aa60572cc2ad2085e5c5c30e5b77"},"package":"388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"} \ No newline at end of file diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/Cargo.toml b/third_party/cargo/vendor/semver-parser-0.7.0/Cargo.toml deleted file mode 100644 index c2be878..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "semver-parser" -version = "0.7.0" -authors = ["Steve Klabnik "] -license = "MIT/Apache-2.0" -repository = "https://github.com/steveklabnik/semver-parser" -homepage = "https://github.com/steveklabnik/semver-parser" -documentation = "https://docs.rs/semver-parser" -description = """ -Parsing of the semver spec. -""" diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-APACHE b/third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/src/common.rs b/third_party/cargo/vendor/semver-parser-0.7.0/src/common.rs deleted file mode 100644 index 267b4d9..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/src/common.rs +++ /dev/null @@ -1,66 +0,0 @@ -use version::Identifier; -use recognize::{Recognize, Alt, OneOrMore, Inclusive, OneByte}; -use std::str::from_utf8; - -// by the time we get here, we know that it's all valid characters, so this doesn't need to return -// a result or anything -fn parse_meta(s: &str) -> Vec { - // Originally, I wanted to implement this method via calling parse, but parse is tolerant of - // leading zeroes, and we want anything with leading zeroes to be considered alphanumeric, not - // numeric. So the strategy is to check with a recognizer first, and then call parse once - // we've determined that it's a number without a leading zero. - s.split(".") - .map(|part| { - // another wrinkle: we made sure that any number starts with a - // non-zero. But there's a problem: an actual zero is a number, yet - // gets left out by this heuristic. So let's also check for the - // single, lone zero. - if is_alpha_numeric(part) { - Identifier::AlphaNumeric(part.to_string()) - } else { - // we can unwrap here because we know it is only digits due to the regex - Identifier::Numeric(part.parse().unwrap()) - } - }).collect() -} - -// parse optional metadata (preceded by the prefix character) -pub fn parse_optional_meta(s: &[u8], prefix_char: u8)-> Result<(Vec, usize), String> { - if let Some(len) = prefix_char.p(s) { - let start = len; - if let Some(len) = letters_numbers_dash_dot(&s[start..]) { - let end = start + len; - Ok((parse_meta(from_utf8(&s[start..end]).unwrap()), end)) - } else { - Err("Error parsing prerelease".to_string()) - } - } else { - Ok((Vec::new(), 0)) - } -} - -pub fn is_alpha_numeric(s: &str) -> bool { - if let Some((_val, len)) = numeric_identifier(s.as_bytes()) { - // Return true for number with leading zero - // Note: doing it this way also handily makes overflow fail over. - len != s.len() - } else { - true - } -} - -// Note: could plumb overflow error up to return value as Result -pub fn numeric_identifier(s: &[u8]) -> Option<(u64, usize)> { - if let Some(len) = Alt(b'0', OneOrMore(Inclusive(b'0'..b'9'))).p(s) { - from_utf8(&s[0..len]).unwrap().parse().ok().map(|val| (val, len)) - } else { - None - } -} - -pub fn letters_numbers_dash_dot(s: &[u8]) -> Option { - OneOrMore(OneByte(|c| c == b'-' || c == b'.' || - (b'0' <= c && c <= b'9') || - (b'a' <= c && c <= b'z') || - (b'A' <= c && c <= b'Z'))).p(s) -} diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/src/lib.rs b/third_party/cargo/vendor/semver-parser-0.7.0/src/lib.rs deleted file mode 100644 index 3b0d8f0..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/src/lib.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub mod version; -pub mod range; - -// for private stuff the two share -mod common; - -// for recognizer combinators -mod recognize; diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/src/range.rs b/third_party/cargo/vendor/semver-parser-0.7.0/src/range.rs deleted file mode 100644 index 858be9f..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/src/range.rs +++ /dev/null @@ -1,696 +0,0 @@ -use common::{self, numeric_identifier, letters_numbers_dash_dot}; -use version::Identifier; -use std::str::{FromStr, from_utf8}; -use recognize::*; - -#[derive(Debug)] -pub struct VersionReq { - pub predicates: Vec, -} - -#[derive(PartialEq,Debug)] -pub enum WildcardVersion { - Major, - Minor, - Patch, -} - -#[derive(PartialEq,Debug)] -pub enum Op { - Ex, // Exact - Gt, // Greater than - GtEq, // Greater than or equal to - Lt, // Less than - LtEq, // Less than or equal to - Tilde, // e.g. ~1.0.0 - Compatible, // compatible by definition of semver, indicated by ^ - Wildcard(WildcardVersion), // x.y.*, x.*, * -} - -impl FromStr for Op { - type Err = String; - - fn from_str(s: &str) -> Result { - match s { - "=" => Ok(Op::Ex), - ">" => Ok(Op::Gt), - ">=" => Ok(Op::GtEq), - "<" => Ok(Op::Lt), - "<=" => Ok(Op::LtEq), - "~" => Ok(Op::Tilde), - "^" => Ok(Op::Compatible), - _ => Err(String::from("Could not parse Op")), - } - } -} - -#[derive(PartialEq,Debug)] -pub struct Predicate { - pub op: Op, - pub major: u64, - pub minor: Option, - pub patch: Option, - pub pre: Vec, -} - -fn numeric_or_wild(s: &[u8]) -> Option<(Option, usize)> { - if let Some((val, len)) = numeric_identifier(s) { - Some((Some(val), len)) - } else if let Some(len) = OneOf(b"*xX").p(s) { - Some((None, len)) - } else { - None - } -} - -fn dot_numeric_or_wild(s: &[u8]) -> Option<(Option, usize)> { - b'.'.p(s).and_then(|len| - numeric_or_wild(&s[len..]).map(|(val, len2)| (val, len + len2)) - ) -} - -fn operation(s: &[u8]) -> Option<(Op, usize)> { - if let Some(len) = "=".p(s) { - Some((Op::Ex, len)) - } else if let Some(len) = ">=".p(s) { - Some((Op::GtEq, len)) - } else if let Some(len) = ">".p(s) { - Some((Op::Gt, len)) - } else if let Some(len) = "<=".p(s) { - Some((Op::LtEq, len)) - } else if let Some(len) = "<".p(s) { - Some((Op::Lt, len)) - } else if let Some(len) = "~".p(s) { - Some((Op::Tilde, len)) - } else if let Some(len) = "^".p(s) { - Some((Op::Compatible, len)) - } else { - None - } -} - -fn whitespace(s: &[u8]) -> Option { - ZeroOrMore(OneOf(b"\t\r\n ")).p(s) -} - -pub fn parse_predicate(range: &str) -> Result { - let s = range.trim().as_bytes(); - let mut i = 0; - let mut operation = if let Some((op, len)) = operation(&s[i..]) { - i += len; - op - } else { - // operations default to Compatible - Op::Compatible - }; - if let Some(len) = whitespace.p(&s[i..]) { - i += len; - } - let major = if let Some((major, len)) = numeric_identifier(&s[i..]) { - i += len; - major - } else { - return Err("Error parsing major version number: ".to_string()); - }; - let minor = if let Some((minor, len)) = dot_numeric_or_wild(&s[i..]) { - i += len; - if minor.is_none() { - operation = Op::Wildcard(WildcardVersion::Minor); - } - minor - } else { - None - }; - let patch = if let Some((patch, len)) = dot_numeric_or_wild(&s[i..]) { - i += len; - if patch.is_none() { - operation = Op::Wildcard(WildcardVersion::Patch); - } - patch - } else { - None - }; - let (pre, pre_len) = common::parse_optional_meta(&s[i..], b'-')?; - i += pre_len; - if let Some(len) = (b'+', letters_numbers_dash_dot).p(&s[i..]) { - i += len; - } - if i != s.len() { - return Err("Extra junk after valid predicate: ".to_string() + - from_utf8(&s[i..]).unwrap()); - } - Ok(Predicate { - op: operation, - major: major, - minor: minor, - patch: patch, - pre: pre, - }) -} - -pub fn parse(ranges: &str) -> Result { - // null is an error - if ranges == "\0" { - return Err(String::from("Null is not a valid VersionReq")); - } - - // an empty range is a major version wildcard - // so is a lone * or x of either capitalization - if (ranges == "") - || (ranges == "*") - || (ranges == "x") - || (ranges == "X") { - return Ok(VersionReq { - predicates: vec![Predicate { - op: Op::Wildcard(WildcardVersion::Major), - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }], - }); - } - - - let ranges = ranges.trim(); - - let predicates: Result, String> = ranges - .split(",") - .map(|range| { - parse_predicate(range) - }) - .collect(); - - let predicates = try!(predicates); - - if predicates.len() == 0 { - return Err(String::from("VersionReq did not parse properly")); - } - - Ok(VersionReq { - predicates: predicates, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use range; - use version::Identifier; - - #[test] - fn test_parsing_default() { - let r = range::parse("1.0.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 1, - minor: Some(0), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_exact_01() { - let r = range::parse("=1.0.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Ex, - major: 1, - minor: Some(0), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_exact_02() { - let r = range::parse("=0.9.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Ex, - major: 0, - minor: Some(9), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_exact_03() { - let r = range::parse("=0.1.0-beta2.a").unwrap(); - - assert_eq!(Predicate { - op: Op::Ex, - major: 0, - minor: Some(1), - patch: Some(0), - pre: vec![Identifier::AlphaNumeric(String::from("beta2")), - Identifier::AlphaNumeric(String::from("a"))], - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_greater_than() { - let r = range::parse("> 1.0.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Gt, - major: 1, - minor: Some(0), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_greater_than_01() { - let r = range::parse(">= 1.0.0").unwrap(); - - assert_eq!(Predicate { - op: Op::GtEq, - major: 1, - minor: Some(0), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_greater_than_02() { - let r = range::parse(">= 2.1.0-alpha2").unwrap(); - - assert_eq!(Predicate { - op: Op::GtEq, - major: 2, - minor: Some(1), - patch: Some(0), - pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_less_than() { - let r = range::parse("< 1.0.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Lt, - major: 1, - minor: Some(0), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_less_than_eq() { - let r = range::parse("<= 2.1.0-alpha2").unwrap(); - - assert_eq!(Predicate { - op: Op::LtEq, - major: 2, - minor: Some(1), - patch: Some(0), - pre: vec![Identifier::AlphaNumeric(String::from("alpha2"))], - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_tilde() { - let r = range::parse("~1").unwrap(); - - assert_eq!(Predicate { - op: Op::Tilde, - major: 1, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_parsing_compatible() { - let r = range::parse("^0").unwrap(); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_blank() { - let r = range::parse("").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Major), - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_wildcard() { - let r = range::parse("*").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Major), - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_x() { - let r = range::parse("x").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Major), - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_capital_x() { - let r = range::parse("X").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Major), - major: 0, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_minor_wildcard_star() { - let r = range::parse("1.*").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Minor), - major: 1, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_minor_wildcard_x() { - let r = range::parse("1.x").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Minor), - major: 1, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_minor_wildcard_capital_x() { - let r = range::parse("1.X").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Minor), - major: 1, - minor: None, - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_patch_wildcard_star() { - let r = range::parse("1.2.*").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Patch), - major: 1, - minor: Some(2), - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_patch_wildcard_x() { - let r = range::parse("1.2.x").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Patch), - major: 1, - minor: Some(2), - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - fn test_parsing_patch_wildcard_capital_x() { - let r = range::parse("1.2.X").unwrap(); - - assert_eq!(Predicate { - op: Op::Wildcard(WildcardVersion::Patch), - major: 1, - minor: Some(2), - patch: None, - pre: Vec::new(), - }, - r.predicates[0] - ); - } - - #[test] - pub fn test_multiple_01() { - let r = range::parse("> 0.0.9, <= 2.5.3").unwrap(); - - assert_eq!(Predicate { - op: Op::Gt, - major: 0, - minor: Some(0), - patch: Some(9), - pre: Vec::new(), - }, - r.predicates[0] - ); - - assert_eq!(Predicate { - op: Op::LtEq, - major: 2, - minor: Some(5), - patch: Some(3), - pre: Vec::new(), - }, - r.predicates[1] - ); - } - - #[test] - pub fn test_multiple_02() { - let r = range::parse("0.3.0, 0.4.0").unwrap(); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: Some(3), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: Some(4), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[1] - ); - } - - #[test] - pub fn test_multiple_03() { - let r = range::parse("<= 0.2.0, >= 0.5.0").unwrap(); - - assert_eq!(Predicate { - op: Op::LtEq, - major: 0, - minor: Some(2), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - - assert_eq!(Predicate { - op: Op::GtEq, - major: 0, - minor: Some(5), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[1] - ); - } - - #[test] - pub fn test_multiple_04() { - let r = range::parse("0.1.0, 0.1.4, 0.1.6").unwrap(); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: Some(1), - patch: Some(0), - pre: Vec::new(), - }, - r.predicates[0] - ); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: Some(1), - patch: Some(4), - pre: Vec::new(), - }, - r.predicates[1] - ); - - assert_eq!(Predicate { - op: Op::Compatible, - major: 0, - minor: Some(1), - patch: Some(6), - pre: Vec::new(), - }, - r.predicates[2] - ); - } - - #[test] - pub fn test_multiple_05() { - let r = range::parse(">=0.5.1-alpha3, <0.6").unwrap(); - - assert_eq!(Predicate { - op: Op::GtEq, - major: 0, - minor: Some(5), - patch: Some(1), - pre: vec![Identifier::AlphaNumeric(String::from("alpha3"))], - }, - r.predicates[0] - ); - - assert_eq!(Predicate { - op: Op::Lt, - major: 0, - minor: Some(6), - patch: None, - pre: Vec::new(), - }, - r.predicates[1] - ); - } - - #[test] - fn test_parse_build_metadata_with_predicate() { - assert_eq!(range::parse("^1.2.3+meta").unwrap().predicates[0].op, - Op::Compatible); - assert_eq!(range::parse("~1.2.3+meta").unwrap().predicates[0].op, - Op::Tilde); - assert_eq!(range::parse("=1.2.3+meta").unwrap().predicates[0].op, - Op::Ex); - assert_eq!(range::parse("<=1.2.3+meta").unwrap().predicates[0].op, - Op::LtEq); - assert_eq!(range::parse(">=1.2.3+meta").unwrap().predicates[0].op, - Op::GtEq); - assert_eq!(range::parse("<1.2.3+meta").unwrap().predicates[0].op, - Op::Lt); - assert_eq!(range::parse(">1.2.3+meta").unwrap().predicates[0].op, - Op::Gt); - } - - #[test] - pub fn test_parse_errors() { - assert!(range::parse("\0").is_err()); - assert!(range::parse(">= >= 0.0.2").is_err()); - assert!(range::parse(">== 0.0.2").is_err()); - assert!(range::parse("a.0.0").is_err()); - assert!(range::parse("1.0.0-").is_err()); - assert!(range::parse(">=").is_err()); - assert!(range::parse("> 0.1.0,").is_err()); - assert!(range::parse("> 0.3.0, ,").is_err()); - } - - #[test] - pub fn test_large_major_version() { - assert!(range::parse("18446744073709551617.0.0").is_err()); - } - - #[test] - pub fn test_large_minor_version() { - assert!(range::parse("0.18446744073709551617.0").is_err()); - } - - #[test] - pub fn test_large_patch_version() { - assert!(range::parse("0.0.18446744073709551617").is_err()); - } -} diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/src/recognize.rs b/third_party/cargo/vendor/semver-parser-0.7.0/src/recognize.rs deleted file mode 100644 index c0dd771..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/src/recognize.rs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2017 Google Inc. All rights reserved. -// -// Licensed under either of MIT or Apache License, Version 2.0, -// at your option. -// -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file or at -// https://opensource.org/licenses/MIT. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! Simple recognizer combinators. - -// This version is similar to a similar one in the "lang" module of -// xi-editor, but is stripped down to only the needed combinators. - -use std::ops; - -pub trait Recognize { - fn p(&self, s: &[u8]) -> Option; -} - -impl Option> Recognize for F { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - self(s) - } -} - -pub struct OneByte(pub F); - -impl bool> Recognize for OneByte { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - if s.is_empty() || !self.0(s[0]) { - None - } else { - Some(1) - } - } -} - -impl Recognize for u8 { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - OneByte(|b| b == *self).p(s) - } -} - -/// Use Inclusive(a..b) to indicate an inclusive range. When a...b syntax becomes -/// stable, we can get rid of this and switch to that. -pub struct Inclusive(pub T); - -impl Recognize for Inclusive> { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - OneByte(|x| x >= self.0.start && x <= self.0.end).p(s) - } -} - -impl<'a> Recognize for &'a [u8] { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - let len = self.len(); - if s.len() >= len && &s[..len] == *self { - Some(len) - } else { - None - } - } -} - -impl<'a> Recognize for &'a str { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - self.as_bytes().p(s) - } -} - -impl Recognize for (P1, P2) { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - self.0.p(s).and_then(|len1| - self.1.p(&s[len1..]).map(|len2| - len1 + len2)) - } -} - -/// Choice from two heterogeneous alternatives. -pub struct Alt(pub P1, pub P2); - -impl Recognize for Alt { - #[inline(always)] - fn p(&self, s: &[u8]) -> Option { - self.0.p(s).or_else(|| self.1.p(s)) - } -} - -/// Choice from a homogenous slice of parsers. -pub struct OneOf<'a, P: 'a>(pub &'a [P]); - -impl<'a, P: Recognize> Recognize for OneOf<'a, P> { - #[inline] - fn p(&self, s: &[u8]) -> Option { - for ref p in self.0 { - if let Some(len) = p.p(s) { - return Some(len); - } - } - None - } -} - -pub struct OneOrMore

(pub P); - -impl Recognize for OneOrMore

{ - #[inline] - fn p(&self, s: &[u8]) -> Option { - let mut i = 0; - let mut count = 0; - while let Some(len) = self.0.p(&s[i..]) { - i += len; - count += 1; - } - if count >= 1 { - Some(i) - } else { - None - } - } -} - -pub struct ZeroOrMore

(pub P); - -impl Recognize for ZeroOrMore

{ compute_allowed: bool, // If we're inside a render pass, contains the render pass and the subpass index. - render_pass: Option<(Box, u32)>, + render_pass: Option<(Box, u32)>, // True if we are a secondary command buffer. secondary_cb: bool, @@ -1259,6 +1259,28 @@ impl

AutoCommandBufferBuilder

{ Ok(self) } + /// Adds a command that executes all the commands in a vector. + /// + /// **This function is unsafe for now because safety checks and synchronization are not + /// implemented.** + // TODO: implement correctly + pub unsafe fn execute_commands_from_vec(mut self, command_buffers: Vec) + -> Result + where C: CommandBuffer + Send + Sync + 'static + { + { + let mut builder = self.inner.execute_commands(); + for cmd_buffer in command_buffers { + builder.add(cmd_buffer); + } + builder.submit()?; + } + + self.state_cacher.invalidate(); + + Ok(self) + } + /// Adds a command that writes the content of a buffer. /// /// This function is similar to the `memset` function in C. The `data` parameter is a number @@ -1393,12 +1415,24 @@ unsafe fn set_state

(destination: &mut SyncCommandBufferBuilder

, dynamic: & if let Some(ref scissors) = dynamic.scissors { destination.set_scissor(0, scissors.iter().cloned().collect::>().into_iter()); // TODO: don't collect } + + if let Some(compare_mask) = dynamic.compare_mask { + destination.set_stencil_compare_mask(compare_mask); + } + + if let Some(write_mask) = dynamic.write_mask { + destination.set_stencil_write_mask(write_mask); + } + + if let Some(reference) = dynamic.reference { + destination.set_stencil_reference(reference); + } } // Shortcut function to bind vertex buffers. unsafe fn vertex_buffers

(destination: &mut SyncCommandBufferBuilder

, state_cacher: &mut StateCacher, - vertex_buffers: Vec>) + vertex_buffers: Vec>) -> Result<(), SyncCommandBufferBuilderError> { let binding_range = { let mut compare = state_cacher.bind_vertex_buffers(); @@ -1494,7 +1528,7 @@ unsafe impl

CommandBuffer for AutoCommandBuffer

{ } #[inline] - fn lock_submit(&self, future: &GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError> { + fn lock_submit(&self, future: &dyn GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError> { match self.submit_state { SubmitState::OneTime { ref already_submitted } => { let was_already_submitted = already_submitted.swap(true, Ordering::SeqCst); @@ -1549,13 +1583,13 @@ unsafe impl

CommandBuffer for AutoCommandBuffer

{ #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { self.inner.check_buffer_access(buffer, exclusive, queue) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { self.inner @@ -1592,7 +1626,7 @@ macro_rules! err_gen { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { $( $name::$err(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/mod.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/mod.rs index 358ea77..f308758 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/mod.rs @@ -99,6 +99,7 @@ pub use self::traits::CommandBufferExecFuture; use pipeline::viewport::Scissor; use pipeline::viewport::Viewport; +use pipeline::depth_stencil::DynamicStencilValue; pub mod pool; pub mod submit; @@ -144,7 +145,10 @@ pub struct DynamicState { pub line_width: Option, pub viewports: Option>, pub scissors: Option>, - // TODO: missing fields + pub compare_mask: Option, + pub write_mask: Option, + pub reference: Option, + } impl DynamicState { @@ -154,6 +158,9 @@ impl DynamicState { line_width: None, viewports: None, scissors: None, + compare_mask: None, + write_mask: None, + reference: None } } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/standard.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/standard.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/standard.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/standard.rs index a3a6a13..a6c384c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/standard.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/standard.rs @@ -7,7 +7,7 @@ // notice may not be copied, modified, or distributed except // according to those terms. -use crossbeam::queue::MsQueue; +use crossbeam::queue::SegQueue; use fnv::FnvHashMap; use std::collections::hash_map::Entry; use std::marker::PhantomData; @@ -59,9 +59,9 @@ struct StandardCommandPoolPerThread { // The Vulkan pool of this thread. pool: Mutex, // List of existing primary command buffers that are available for reuse. - available_primary_command_buffers: MsQueue, + available_primary_command_buffers: SegQueue, // List of existing secondary command buffers that are available for reuse. - available_secondary_command_buffers: MsQueue, + available_secondary_command_buffers: SegQueue, } impl StandardCommandPool { @@ -105,8 +105,8 @@ unsafe impl CommandPool for Arc { UnsafeCommandPool::new(self.device.clone(), self.queue_family(), false, true)?; let pt = Arc::new(StandardCommandPoolPerThread { pool: Mutex::new(new_pool), - available_primary_command_buffers: MsQueue::new(), - available_secondary_command_buffers: MsQueue::new(), + available_primary_command_buffers: SegQueue::new(), + available_secondary_command_buffers: SegQueue::new(), }); entry.insert(Arc::downgrade(&pt)); @@ -126,7 +126,7 @@ unsafe impl CommandPool for Arc { }; for _ in 0 .. count as usize { - if let Some(cmd) = existing.try_pop() { + if let Ok(cmd) = existing.pop() { output.push(StandardCommandPoolBuilder { inner: StandardCommandPoolAlloc { cmd: ManuallyDrop::new(cmd), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/sys.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/sys.rs index 01e18eb..3a03c32 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/pool/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/pool/sys.rs @@ -11,7 +11,7 @@ use smallvec::SmallVec; use std::error; use std::fmt; use std::marker::PhantomData; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; use std::vec::IntoIter as VecIntoIter; @@ -93,12 +93,12 @@ impl UnsafeCommandPool { queueFamilyIndex: queue_family.id(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateCommandPool(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(UnsafeCommandPool { @@ -225,7 +225,7 @@ unsafe impl DeviceOwned for UnsafeCommandPool { unsafe impl VulkanObject for UnsafeCommandPool { type Object = vk::CommandPool; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_COMMAND_POOL; #[inline] fn internal_object(&self) -> vk::CommandPool { @@ -249,7 +249,7 @@ pub struct UnsafeCommandPoolAlloc(vk::CommandBuffer); unsafe impl VulkanObject for UnsafeCommandPoolAlloc { type Object = vk::CommandBuffer; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_COMMAND_BUFFER; #[inline] fn internal_object(&self) -> vk::CommandBuffer { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/state_cacher.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/state_cacher.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/state_cacher.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/state_cacher.rs index ce55c4a..f9afad0 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/state_cacher.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/state_cacher.rs @@ -108,6 +108,9 @@ impl StateCacher { cmp!(line_width); cmp!(viewports); cmp!(scissors); + cmp!(compare_mask); + cmp!(reference); + cmp!(write_mask); changed } @@ -363,7 +366,7 @@ mod tests { const EMPTY: [i32; 0] = []; let buf = - CpuAccessibleBuffer::from_data(device, BufferUsage::vertex_buffer(), EMPTY.iter()) + CpuAccessibleBuffer::from_data(device, BufferUsage::vertex_buffer(), false, EMPTY.iter()) .unwrap(); let mut cacher = StateCacher::new(); @@ -387,7 +390,7 @@ mod tests { const EMPTY: [i32; 0] = []; let buf = - CpuAccessibleBuffer::from_data(device, BufferUsage::vertex_buffer(), EMPTY.iter()) + CpuAccessibleBuffer::from_data(device, BufferUsage::vertex_buffer(), false, EMPTY.iter()) .unwrap(); let mut cacher = StateCacher::new(); @@ -420,15 +423,19 @@ mod tests { const EMPTY: [i32; 0] = []; let buf1 = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), + false, EMPTY.iter()) .unwrap(); let buf2 = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), + false, + EMPTY.iter()) + .unwrap(); + let buf3 = CpuAccessibleBuffer::from_data(device, + BufferUsage::vertex_buffer(), + false, EMPTY.iter()) .unwrap(); - let buf3 = - CpuAccessibleBuffer::from_data(device, BufferUsage::vertex_buffer(), EMPTY.iter()) - .unwrap(); let mut cacher = StateCacher::new(); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/bind_sparse.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/bind_sparse.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/bind_sparse.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/bind_sparse.rs index 441fe1a..bceec13 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/bind_sparse.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/bind_sparse.rs @@ -473,7 +473,7 @@ impl error::Error for SubmitBindSparseError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SubmitBindSparseError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_present.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_present.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_present.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_present.rs index 4a8b2d6..69e70bd 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_present.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_present.rs @@ -210,6 +210,10 @@ pub enum SubmitPresentError { /// The surface is no longer accessible and must be recreated. SurfaceLost, + /// The swapchain has lost or doesn't have fullscreen exclusivity possibly for + /// implementation-specific reasons outside of the application’s control. + FullscreenExclusiveLost, + /// The surface has changed in a way that makes the swapchain unusable. You must query the /// surface's new properties and recreate a new swapchain if you want to continue drawing. OutOfDate, @@ -223,11 +227,12 @@ impl error::Error for SubmitPresentError { SubmitPresentError::DeviceLost => "the connection to the device has been lost", SubmitPresentError::SurfaceLost => "the surface of this swapchain is no longer valid", SubmitPresentError::OutOfDate => "the swapchain needs to be recreated", + SubmitPresentError::FullscreenExclusiveLost => "the swapchain no longer has fullscreen exclusivity", } } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SubmitPresentError::OomError(ref err) => Some(err), _ => None, @@ -251,6 +256,7 @@ impl From for SubmitPresentError { Error::DeviceLost => SubmitPresentError::DeviceLost, Error::SurfaceLost => SubmitPresentError::SurfaceLost, Error::OutOfDate => SubmitPresentError::OutOfDate, + Error::FullscreenExclusiveLost => SubmitPresentError::FullscreenExclusiveLost, _ => panic!("unexpected error: {:?}", err), } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_submit.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_submit.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_submit.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_submit.rs index db0bd9f..0851a77 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/queue_submit.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/queue_submit.rs @@ -268,7 +268,7 @@ impl error::Error for SubmitCommandBufferError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SubmitCommandBufferError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/semaphores_wait.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/semaphores_wait.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/semaphores_wait.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/semaphores_wait.rs index 8b1a02b..585bf89 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/submit/semaphores_wait.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/submit/semaphores_wait.rs @@ -41,7 +41,7 @@ impl<'a> SubmitSemaphoresWaitBuilder<'a> { /// Merges this builder with another builder. #[inline] pub fn merge(&mut self, mut other: SubmitSemaphoresWaitBuilder<'a>) { - self.semaphores.extend(other.semaphores.drain()); + self.semaphores.extend(other.semaphores.drain(..)); } } @@ -50,7 +50,7 @@ impl<'a> Into> for SubmitSemaphoresWaitBuilder<'a fn into(mut self) -> SubmitCommandBufferBuilder<'a> { unsafe { let mut builder = SubmitCommandBufferBuilder::new(); - for sem in self.semaphores.drain() { + for sem in self.semaphores.drain(..) { builder.add_wait_semaphore(sem, PipelineStages { // TODO: correct stages ; hard @@ -68,7 +68,7 @@ impl<'a> Into> for SubmitSemaphoresWaitBuilder<'a> { fn into(mut self) -> SubmitPresentBuilder<'a> { unsafe { let mut builder = SubmitPresentBuilder::new(); - for sem in self.semaphores.drain() { + for sem in self.semaphores.drain(..) { builder.add_wait_semaphore(sem); } builder diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/base.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/base.rs similarity index 87% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/base.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/base.rs index 32f46b6..936a741 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/base.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/base.rs @@ -39,6 +39,7 @@ use sync::AccessError; use sync::AccessFlagBits; use sync::GpuFuture; use sync::PipelineStages; +use std::cell::RefCell; /// Wrapper around `UnsafeCommandBufferBuilder` that handles synchronization for you. /// @@ -183,7 +184,7 @@ struct Commands

{ latest_render_pass_enter: Option, // The actual list. - commands: Vec + Send + Sync>>, + commands: Vec + Send + Sync>>, } // Trait for single commands within the list of commands. @@ -196,15 +197,15 @@ pub trait Command

{ unsafe fn send(&mut self, out: &mut UnsafeCommandBufferBuilder

); // Turns this command into a `FinalCommand`. - fn into_final_command(self: Box) -> Box; + fn into_final_command(self: Box) -> Box; // Gives access to the `num`th buffer used by the command. - fn buffer(&self, _num: usize) -> &BufferAccess { + fn buffer(&self, _num: usize) -> &dyn BufferAccess { panic!() } // Gives access to the `num`th image used by the command. - fn image(&self, _num: usize) -> &ImageAccess { + fn image(&self, _num: usize) -> &dyn ImageAccess { panic!() } @@ -237,7 +238,7 @@ struct BuilderKey

{ // Same `Arc` as in the `SyncCommandBufferBuilder`. commands: Arc>>, // Index of the command that holds the resource within `commands`. - command_id: usize, + command_ids: RefCell>, // Type of the resource. resource_ty: KeyTy, // Index of the resource within the command. @@ -247,42 +248,50 @@ struct BuilderKey

{ impl

BuilderKey

{ // Turns this key used by the builder into a key used by the final command buffer. // Called when the command buffer is being built. - fn into_cb_key(self, final_commands: Arc>>>) + fn into_cb_key(self, final_commands: Arc>>>) -> CbKey<'static> { CbKey::Command { commands: final_commands, - command_id: self.command_id, + command_ids: self.command_ids.borrow().clone(), resource_ty: self.resource_ty, resource_index: self.resource_index, } } #[inline] - fn conflicts_buffer(&self, commands_lock: &Commands

, buf: &BufferAccess) -> bool { + fn conflicts_buffer(&self, commands_lock: &Commands

, buf: &dyn BufferAccess) -> bool { // TODO: put the conflicts_* methods directly on the Command trait to avoid an indirect call? match self.resource_ty { KeyTy::Buffer => { - let c = &commands_lock.commands[self.command_id]; - c.buffer(self.resource_index).conflicts_buffer(buf) + self.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + c.buffer(self.resource_index).conflicts_buffer(buf) + }) }, KeyTy::Image => { - let c = &commands_lock.commands[self.command_id]; - c.image(self.resource_index).conflicts_buffer(buf) + self.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + c.image(self.resource_index).conflicts_buffer(buf) + }) }, } } #[inline] - fn conflicts_image(&self, commands_lock: &Commands

, img: &ImageAccess) -> bool { + fn conflicts_image(&self, commands_lock: &Commands

, img: &dyn ImageAccess) -> bool { // TODO: put the conflicts_* methods directly on the Command trait to avoid an indirect call? match self.resource_ty { KeyTy::Buffer => { - let c = &commands_lock.commands[self.command_id]; - c.buffer(self.resource_index).conflicts_image(img) + self.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + c.buffer(self.resource_index).conflicts_image(img) + }) }, KeyTy::Image => { - let c = &commands_lock.commands[self.command_id]; - c.image(self.resource_index).conflicts_image(img) + self.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + c.image(self.resource_index).conflicts_image(img) + }) }, } } @@ -296,12 +305,16 @@ impl

PartialEq for BuilderKey

{ match other.resource_ty { KeyTy::Buffer => { - let c = &commands_lock.commands[other.command_id]; - self.conflicts_buffer(&commands_lock, c.buffer(other.resource_index)) + other.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + self.conflicts_buffer(&commands_lock, c.buffer(other.resource_index)) + }) }, KeyTy::Image => { - let c = &commands_lock.commands[other.command_id]; - self.conflicts_image(&commands_lock, c.image(other.resource_index)) + other.command_ids.borrow().iter().any(|command_id| { + let c = &commands_lock.commands[*command_id]; + self.conflicts_image(&commands_lock, c.image(other.resource_index)) + }) }, } } @@ -317,11 +330,11 @@ impl

Hash for BuilderKey

{ match self.resource_ty { KeyTy::Buffer => { - let c = &commands_lock.commands[self.command_id]; + let c = &commands_lock.commands[self.command_ids.borrow()[0]]; c.buffer(self.resource_index).conflict_key().hash(state) }, KeyTy::Image => { - let c = &commands_lock.commands[self.command_id]; + let c = &commands_lock.commands[self.command_ids.borrow()[0]]; c.image(self.resource_index).conflict_key().hash(state) }, } @@ -482,7 +495,7 @@ impl

SyncCommandBufferBuilder

{ let key = BuilderKey { commands: self.commands.clone(), - command_id: latest_command_id, + command_ids: RefCell::new(vec![latest_command_id]), resource_ty, resource_index, }; @@ -495,22 +508,21 @@ impl

SyncCommandBufferBuilder

{ Entry::Occupied(entry) => { // `collision_cmd_id` contains the ID of the command that we are potentially // colliding with. - let collision_cmd_id = entry.key().command_id; - debug_assert!(collision_cmd_id <= latest_command_id); + let collision_cmd_ids = entry.key().command_ids.borrow().clone(); + debug_assert!(collision_cmd_ids.iter().all(|id| *id <= latest_command_id)); let entry_key_resource_index = entry.key().resource_index; let entry_key_resource_ty = entry.key().resource_ty; - let entry = entry.into_mut(); // Find out if we have a collision with the pending commands. - if exclusive || entry.exclusive || entry.current_layout != start_layout { + if exclusive || entry.get().exclusive || entry.get().current_layout != start_layout { // Collision found between `latest_command_id` and `collision_cmd_id`. // We now want to modify the current pipeline barrier in order to handle the // collision. But since the pipeline barrier is going to be submitted before // the flushed commands, it would be a mistake if `collision_cmd_id` hasn't // been flushed yet. - if collision_cmd_id >= first_unflushed_cmd_id { + if collision_cmd_ids.iter().any(|command_id| *command_id >= first_unflushed_cmd_id) || entry.get().current_layout != start_layout { unsafe { // Flush the pending barrier. self.inner.pipeline_barrier(&self.pending_barrier); @@ -527,8 +539,9 @@ impl

SyncCommandBufferBuilder

{ } else { latest_command_id }; - if collision_cmd_id >= end { - let cmd1 = &commands_lock.commands[collision_cmd_id]; + + if let Some(collision_cmd_id) = collision_cmd_ids.iter().find(|command_id| **command_id >= end) { + let cmd1 = &commands_lock.commands[*collision_cmd_id]; let cmd2 = &commands_lock.commands[latest_command_id]; return Err(SyncCommandBufferBuilderError::Conflict { command1_name: cmd1.name(), @@ -537,7 +550,7 @@ impl

SyncCommandBufferBuilder

{ KeyTy::Image => cmd1.image_name(entry_key_resource_index), }, - command1_offset: collision_cmd_id, + command1_offset: *collision_cmd_id, command2_name: cmd2.name(), command2_param: match resource_ty { @@ -557,6 +570,9 @@ impl

SyncCommandBufferBuilder

{ } } + entry.key().command_ids.borrow_mut().push(latest_command_id); + let entry = entry.into_mut(); + // Modify the pipeline barrier to handle the collision. unsafe { let commands_lock = self.commands.lock().unwrap(); @@ -613,6 +629,7 @@ impl

SyncCommandBufferBuilder

{ // There is no collision. Simply merge the stages and accesses. // TODO: what about simplifying the newly-constructed stages/accesses? // this would simplify the job of the driver, but is it worth it? + let entry = entry.into_mut(); entry.stages = entry.stages | stages; entry.access = entry.access | access; } @@ -625,6 +642,7 @@ impl

SyncCommandBufferBuilder

{ let mut actually_exclusive = exclusive; let mut actual_start_layout = start_layout; + if !self.is_secondary && resource_ty == KeyTy::Image && start_layout != ImageLayout::Undefined && start_layout != ImageLayout::Preinitialized @@ -633,9 +651,11 @@ impl

SyncCommandBufferBuilder

{ let img = commands_lock.commands[latest_command_id].image(resource_index); let initial_layout_requirement = img.initial_layout_requirement(); - if initial_layout_requirement != start_layout { - actually_exclusive = true; - actual_start_layout = initial_layout_requirement; + // Checks if the image is initialized and transitions it + // if it isn't + let is_layout_initialized = img.is_layout_initialized(); + + if initial_layout_requirement != start_layout || !is_layout_initialized { // Note that we transition from `bottom_of_pipe`, which means that we // wait for all the previous commands to be entirely finished. This is @@ -648,6 +668,19 @@ impl

SyncCommandBufferBuilder

{ // suboptimal in some cases, in the general situation it will be ok. // unsafe { + let from_layout = if is_layout_initialized { + actually_exclusive = true; + initial_layout_requirement + } else { + if img.preinitialized_layout() { + ImageLayout::Preinitialized + } else { + ImageLayout::Undefined + } + }; + if initial_layout_requirement != start_layout { + actual_start_layout = initial_layout_requirement; + } let b = &mut self.pending_barrier; b.add_image_memory_barrier(img, 0 .. img.mipmap_levels(), @@ -661,8 +694,9 @@ impl

SyncCommandBufferBuilder

{ access, true, None, - initial_layout_requirement, + from_layout, start_layout); + img.layout_initialized(); } } } @@ -711,7 +745,7 @@ impl

SyncCommandBufferBuilder

{ continue; } - let img = commands_lock.commands[key.command_id].image(key.resource_index); + let img = commands_lock.commands[key.command_ids.borrow()[0]].image(key.resource_index); let requested_layout = img.final_layout_requirement(); if requested_layout == state.current_layout { continue; @@ -786,7 +820,7 @@ pub struct SyncCommandBuffer

{ // List of commands used by the command buffer. Used to hold the various resources that are // being used. Each element of `resources` has a copy of this `Arc`, but we need to keep one // here in case `resources` is empty. - commands: Arc>>>, + commands: Arc>>>, } // Usage of a resource in a finished command buffer. @@ -815,12 +849,12 @@ pub trait FinalCommand { fn name(&self) -> &'static str; // Gives access to the `num`th buffer used by the command. - fn buffer(&self, _num: usize) -> &BufferAccess { + fn buffer(&self, _num: usize) -> &dyn BufferAccess { panic!() } // Gives access to the `num`th image used by the command. - fn image(&self, _num: usize) -> &ImageAccess { + fn image(&self, _num: usize) -> &dyn ImageAccess { panic!() } @@ -855,9 +889,9 @@ enum CbKey<'a> { // The resource is held in the list of commands. Command { // Same `Arc` as in the `SyncCommandBufferBuilder`. - commands: Arc>>>, + commands: Arc>>>, // Index of the command that holds the resource within `commands`. - command_id: usize, + command_ids: Vec, // Type of the resource. resource_ty: KeyTy, // Index of the resource within the command. @@ -866,11 +900,11 @@ enum CbKey<'a> { // Temporary key that holds a reference to a buffer. Should never be stored in the list of // resources of `SyncCommandBuffer`. - BufferRef(&'a BufferAccess), + BufferRef(&'a dyn BufferAccess), // Temporary key that holds a reference to an image. Should never be stored in the list of // resources of `SyncCommandBuffer`. - ImageRef(&'a ImageAccess), + ImageRef(&'a dyn ImageAccess), } // The `CbKey::Command` variants implements `Send` and `Sync`, but the other two variants don't @@ -885,13 +919,13 @@ unsafe impl<'a> Sync for CbKey<'a> { impl<'a> CbKey<'a> { #[inline] - fn conflicts_buffer(&self, commands_lock: Option<&Vec>>, - buf: &BufferAccess) + fn conflicts_buffer(&self, commands_lock: Option<&Vec>>, + buf: &dyn BufferAccess) -> bool { match *self { CbKey::Command { ref commands, - command_id, + ref command_ids, resource_ty, resource_index, } => { @@ -905,12 +939,16 @@ impl<'a> CbKey<'a> { // TODO: put the conflicts_* methods directly on the FinalCommand trait to avoid an indirect call? match resource_ty { KeyTy::Buffer => { - let c = &commands_lock[command_id]; - c.buffer(resource_index).conflicts_buffer(buf) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + c.buffer(resource_index).conflicts_buffer(buf) + }) }, KeyTy::Image => { - let c = &commands_lock[command_id]; - c.image(resource_index).conflicts_buffer(buf) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + c.image(resource_index).conflicts_buffer(buf) + }) }, } }, @@ -921,13 +959,13 @@ impl<'a> CbKey<'a> { } #[inline] - fn conflicts_image(&self, commands_lock: Option<&Vec>>, - img: &ImageAccess) + fn conflicts_image(&self, commands_lock: Option<&Vec>>, + img: &dyn ImageAccess) -> bool { match *self { CbKey::Command { ref commands, - command_id, + ref command_ids, resource_ty, resource_index, } => { @@ -941,12 +979,16 @@ impl<'a> CbKey<'a> { // TODO: put the conflicts_* methods directly on the Command trait to avoid an indirect call? match resource_ty { KeyTy::Buffer => { - let c = &commands_lock[command_id]; - c.buffer(resource_index).conflicts_image(img) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + c.buffer(resource_index).conflicts_image(img) + }) }, KeyTy::Image => { - let c = &commands_lock[command_id]; - c.image(resource_index).conflicts_image(img) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + c.image(resource_index).conflicts_image(img) + }) }, } }, @@ -969,7 +1011,7 @@ impl<'a> PartialEq for CbKey<'a> { }, CbKey::Command { ref commands, - command_id, + ref command_ids, resource_ty, resource_index, } => { @@ -977,12 +1019,16 @@ impl<'a> PartialEq for CbKey<'a> { match resource_ty { KeyTy::Buffer => { - let c = &commands_lock[command_id]; - other.conflicts_buffer(Some(&commands_lock), c.buffer(resource_index)) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + other.conflicts_buffer(Some(&commands_lock), c.buffer(resource_index)) + }) }, KeyTy::Image => { - let c = &commands_lock[command_id]; - other.conflicts_image(Some(&commands_lock), c.image(resource_index)) + command_ids.iter().any(|command_id| { + let c = &commands_lock[*command_id]; + other.conflicts_image(Some(&commands_lock), c.image(resource_index)) + }) }, } }, @@ -999,7 +1045,7 @@ impl<'a> Hash for CbKey<'a> { match *self { CbKey::Command { ref commands, - command_id, + ref command_ids, resource_ty, resource_index, } => { @@ -1007,11 +1053,11 @@ impl<'a> Hash for CbKey<'a> { match resource_ty { KeyTy::Buffer => { - let c = &commands_lock[command_id]; + let c = &commands_lock[command_ids[0]]; c.buffer(resource_index).conflict_key().hash(state) }, KeyTy::Image => { - let c = &commands_lock[command_id]; + let c = &commands_lock[command_ids[0]]; c.image(resource_index).conflict_key().hash(state) }, } @@ -1034,7 +1080,7 @@ impl

SyncCommandBuffer

{ /// Tries to lock the resources used by the command buffer. /// /// > **Note**: You should call this in the implementation of the `CommandBuffer` trait. - pub fn lock_submit(&self, future: &GpuFuture, queue: &Queue) + pub fn lock_submit(&self, future: &dyn GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError> { let commands_lock = self.commands.lock().unwrap(); @@ -1047,21 +1093,21 @@ impl

SyncCommandBuffer

{ // Try locking resources. Updates `locked_resources` and `ret_value`, and break if an error // happens. for (key, entry) in self.resources.iter() { - let (command_id, resource_ty, resource_index) = match *key { + let (command_ids, resource_ty, resource_index) = match *key { CbKey::Command { - command_id, + ref command_ids, resource_ty, resource_index, .. } => { - (command_id, resource_ty, resource_index) + (command_ids, resource_ty, resource_index) }, _ => unreachable!(), }; match resource_ty { KeyTy::Buffer => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let buf = cmd.buffer(resource_index); // Because try_gpu_lock needs to be called first, @@ -1085,7 +1131,7 @@ impl

SyncCommandBuffer

{ error: err, command_name: cmd.name().into(), command_param: cmd.buffer_name(resource_index), - command_offset: command_id, + command_offset: command_ids[0], }); break; }, @@ -1095,7 +1141,7 @@ impl

SyncCommandBuffer

{ }, KeyTy::Image => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let img = cmd.image(resource_index); let prev_err = match future.check_image_access(img, entry.initial_layout, @@ -1117,7 +1163,7 @@ impl

SyncCommandBuffer

{ error: err, command_name: cmd.name().into(), command_param: cmd.image_name(resource_index), - command_offset: command_id, + command_offset: command_ids[0], }); break; }, @@ -1131,21 +1177,21 @@ impl

SyncCommandBuffer

{ // If we are going to return an error, we have to unlock all the resources we locked above. if let Err(_) = ret_value { for key in self.resources.keys().take(locked_resources) { - let (command_id, resource_ty, resource_index) = match *key { + let (command_ids, resource_ty, resource_index) = match *key { CbKey::Command { - command_id, + ref command_ids, resource_ty, resource_index, .. } => { - (command_id, resource_ty, resource_index) + (command_ids, resource_ty, resource_index) }, _ => unreachable!(), }; match resource_ty { KeyTy::Buffer => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let buf = cmd.buffer(resource_index); unsafe { buf.unlock(); @@ -1153,7 +1199,7 @@ impl

SyncCommandBuffer

{ }, KeyTy::Image => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let img = cmd.image(resource_index); unsafe { img.unlock(None); @@ -1180,26 +1226,26 @@ impl

SyncCommandBuffer

{ let commands_lock = self.commands.lock().unwrap(); for (key, val) in self.resources.iter() { - let (command_id, resource_ty, resource_index) = match *key { + let (command_ids, resource_ty, resource_index) = match *key { CbKey::Command { - command_id, + ref command_ids, resource_ty, resource_index, .. } => { - (command_id, resource_ty, resource_index) + (command_ids, resource_ty, resource_index) }, _ => unreachable!(), }; match resource_ty { KeyTy::Buffer => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let buf = cmd.buffer(resource_index); buf.unlock(); }, KeyTy::Image => { - let cmd = &commands_lock[command_id]; + let cmd = &commands_lock[command_ids[0]]; let img = cmd.image(resource_index); let trans = if val.final_layout != val.initial_layout { Some(val.final_layout) @@ -1217,7 +1263,7 @@ impl

SyncCommandBuffer

{ /// > **Note**: Suitable when implementing the `CommandBuffer` trait. #[inline] pub fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { // TODO: check the queue family @@ -1237,7 +1283,7 @@ impl

SyncCommandBuffer

{ /// > **Note**: Suitable when implementing the `CommandBuffer` trait. #[inline] pub fn check_image_access( - &self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) + &self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { // TODO: check the queue family diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/commands.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/commands.rs similarity index 90% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/commands.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/commands.rs index 655d3fe..cfa422c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/commands.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/commands.rs @@ -42,6 +42,8 @@ use pipeline::GraphicsPipelineAbstract; use pipeline::input_assembly::IndexType; use pipeline::viewport::Scissor; use pipeline::viewport::Viewport; +use pipeline::depth_stencil::DynamicStencilValue; +use pipeline::depth_stencil::StencilFaceFlags; use sampler::Filter; use sync::AccessFlagBits; use sync::Event; @@ -79,7 +81,7 @@ impl

SyncCommandBufferBuilder

{ self.clear_values.take().unwrap()); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(F); impl FinalCommand for Fin where F: FramebufferAbstract + Send + Sync + 'static @@ -87,7 +89,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdBeginRenderPass" } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { self.0.attached_image_view(num).unwrap().parent() } fn image_name(&self, num: usize) -> Cow<'static, str> { @@ -97,7 +99,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.framebuffer)) } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { self.framebuffer.attached_image_view(num).unwrap().parent() } @@ -159,7 +161,7 @@ impl

SyncCommandBufferBuilder

{ out.bind_index_buffer(&self.buffer, self.index_ty); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -167,7 +169,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdBindIndexBuffer" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -179,7 +181,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -227,7 +229,7 @@ impl

SyncCommandBufferBuilder

{ out.bind_pipeline_graphics(&self.pipeline); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(Gp); impl FinalCommand for Fin where Gp: Send + Sync + 'static @@ -263,7 +265,7 @@ impl

SyncCommandBufferBuilder

{ out.bind_pipeline_compute(&self.pipeline); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(Cp); impl FinalCommand for Fin where Cp: Send + Sync + 'static @@ -337,7 +339,7 @@ impl

SyncCommandBufferBuilder

{ self.regions.take().unwrap()); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(S, D); impl FinalCommand for Fin where S: ImageAccess + Send + Sync + 'static, @@ -346,7 +348,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdCopyImage" } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { if num == 0 { &self.0 } else if num == 1 { @@ -372,7 +374,7 @@ impl

SyncCommandBufferBuilder

{ self.destination.take().unwrap())) } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { if num == 0 { self.source.as_ref().unwrap() } else if num == 1 { @@ -469,7 +471,7 @@ impl

SyncCommandBufferBuilder

{ self.filter); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(S, D); impl FinalCommand for Fin where S: ImageAccess + Send + Sync + 'static, @@ -478,7 +480,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdBlitImage" } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { if num == 0 { &self.0 } else if num == 1 { @@ -504,7 +506,7 @@ impl

SyncCommandBufferBuilder

{ self.destination.take().unwrap())) } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { if num == 0 { self.source.as_ref().unwrap() } else if num == 1 { @@ -597,7 +599,7 @@ impl

SyncCommandBufferBuilder

{ self.regions.take().unwrap()); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(I); impl FinalCommand for Fin where I: ImageAccess + Send + Sync + 'static @@ -605,7 +607,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdClearColorImage" } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); &self.0 } @@ -619,7 +621,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.image.take().unwrap())) } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); self.image.as_ref().unwrap() } @@ -684,7 +686,7 @@ impl

SyncCommandBufferBuilder

{ self.regions.take().unwrap()); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(S, D); impl FinalCommand for Fin where S: BufferAccess + Send + Sync + 'static, @@ -693,7 +695,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdCopyBuffer" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { match num { 0 => &self.0, 1 => &self.1, @@ -714,7 +716,7 @@ impl

SyncCommandBufferBuilder

{ self.destination.take().unwrap())) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { match num { 0 => self.source.as_ref().unwrap(), 1 => self.destination.as_ref().unwrap(), @@ -800,7 +802,7 @@ impl

SyncCommandBufferBuilder

{ self.regions.take().unwrap()); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(S, D); impl FinalCommand for Fin where S: BufferAccess + Send + Sync + 'static, @@ -809,7 +811,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdCopyBufferToImage" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -817,7 +819,7 @@ impl

SyncCommandBufferBuilder

{ assert_eq!(num, 0); "source".into() } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); &self.1 } @@ -833,7 +835,7 @@ impl

SyncCommandBufferBuilder

{ self.destination.take().unwrap())) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); self.source.as_ref().unwrap() } @@ -843,7 +845,7 @@ impl

SyncCommandBufferBuilder

{ "source".into() } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); self.destination.as_ref().unwrap() } @@ -924,7 +926,7 @@ impl

SyncCommandBufferBuilder

{ self.regions.take().unwrap()); } - fn into_final_command(mut self: Box) -> Box { + fn into_final_command(mut self: Box) -> Box { struct Fin(S, D); impl FinalCommand for Fin where S: ImageAccess + Send + Sync + 'static, @@ -933,7 +935,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdCopyImageToBuffer" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.1 } @@ -941,7 +943,7 @@ impl

SyncCommandBufferBuilder

{ assert_eq!(num, 0); "destination".into() } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); &self.0 } @@ -957,7 +959,7 @@ impl

SyncCommandBufferBuilder

{ self.destination.take().unwrap())) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); self.destination.as_ref().unwrap() } @@ -967,7 +969,7 @@ impl

SyncCommandBufferBuilder

{ "destination".into() } - fn image(&self, num: usize) -> &ImageAccess { + fn image(&self, num: usize) -> &dyn ImageAccess { assert_eq!(num, 0); self.source.as_ref().unwrap() } @@ -1029,7 +1031,7 @@ impl

SyncCommandBufferBuilder

{ out.dispatch(self.dimensions); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdDispatch") } } @@ -1058,7 +1060,7 @@ impl

SyncCommandBufferBuilder

{ out.dispatch_indirect(&self.buffer); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -1066,7 +1068,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdDispatchIndirect" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -1078,7 +1080,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -1129,7 +1131,7 @@ impl

SyncCommandBufferBuilder

{ self.first_instance); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdDraw") } } @@ -1168,7 +1170,7 @@ impl

SyncCommandBufferBuilder

{ self.first_instance); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdDrawIndexed") } } @@ -1205,7 +1207,7 @@ impl

SyncCommandBufferBuilder

{ out.draw_indirect(&self.buffer, self.draw_count, self.stride); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -1213,7 +1215,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdDrawIndirect" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -1225,7 +1227,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -1280,7 +1282,7 @@ impl

SyncCommandBufferBuilder

{ out.draw_indexed_indirect(&self.buffer, self.draw_count, self.stride); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -1288,7 +1290,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdDrawIndexedIndirect" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -1300,7 +1302,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -1346,7 +1348,7 @@ impl

SyncCommandBufferBuilder

{ out.end_render_pass(); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdEndRenderPass") } } @@ -1387,7 +1389,7 @@ impl

SyncCommandBufferBuilder

{ out.fill_buffer(&self.buffer, self.data); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -1395,7 +1397,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdFillBuffer" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -1406,7 +1408,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -1449,7 +1451,7 @@ impl

SyncCommandBufferBuilder

{ out.next_subpass(self.subpass_contents); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdNextSubpass") } } @@ -1487,7 +1489,7 @@ impl

SyncCommandBufferBuilder

{ &self.data); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(Pl); impl FinalCommand for Fin where Pl: Send + Sync + 'static @@ -1534,7 +1536,7 @@ impl

SyncCommandBufferBuilder

{ out.reset_event(&self.event, self.stages); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(Arc); impl FinalCommand for Fin { fn name(&self) -> &'static str { @@ -1564,7 +1566,7 @@ impl

SyncCommandBufferBuilder

{ out.set_blend_constants(self.constants); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetBlendConstants") } } @@ -1590,7 +1592,7 @@ impl

SyncCommandBufferBuilder

{ out.set_depth_bias(self.constant_factor, self.clamp, self.slope_factor); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetDepthBias") } } @@ -1619,7 +1621,7 @@ impl

SyncCommandBufferBuilder

{ out.set_depth_bounds(self.min, self.max); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetDepthBounds") } } @@ -1644,7 +1646,7 @@ impl

SyncCommandBufferBuilder

{ out.set_event(&self.event, self.stages); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(Arc); impl FinalCommand for Fin { fn name(&self) -> &'static str { @@ -1674,7 +1676,7 @@ impl

SyncCommandBufferBuilder

{ out.set_line_width(self.line_width); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetLineWidth") } } @@ -1682,7 +1684,92 @@ impl

SyncCommandBufferBuilder

{ self.append_command(Cmd { line_width }); } - // TODO: stencil states + /// Calls `vkCmdSetStencilCompareMask` on the builder. + #[inline] + pub unsafe fn set_stencil_compare_mask(&mut self, compare_mask: DynamicStencilValue) { + + struct Cmd { + face_mask: StencilFaceFlags, + compare_mask: u32, + } + + impl

Command

for Cmd { + fn name(&self) -> &'static str { + "vkCmdSetStencilCompareMask" + } + + unsafe fn send(&mut self, out: &mut UnsafeCommandBufferBuilder

) { + out.set_stencil_compare_mask(self.face_mask, self.compare_mask); + } + + fn into_final_command(self: Box) -> Box { + Box::new("vkCmdSetStencilCompareMask") + } + } + + self.append_command(Cmd { + face_mask: compare_mask.face, + compare_mask: compare_mask.value, + }); + } + + /// Calls `vkCmdSetStencilReference` on the builder. + #[inline] + pub unsafe fn set_stencil_reference(&mut self, reference: DynamicStencilValue) { + + struct Cmd { + face_mask: StencilFaceFlags, + reference: u32, + } + + impl

Command

for Cmd { + fn name(&self) -> &'static str { + "vkCmdSetStencilReference" + } + + unsafe fn send(&mut self, out: &mut UnsafeCommandBufferBuilder

) { + out.set_stencil_reference(self.face_mask, self.reference); + } + + fn into_final_command(self: Box) -> Box { + Box::new("vkCmdSetStencilReference") + } + } + + self.append_command(Cmd { + face_mask: reference.face, + reference: reference.value, + }); + } + + /// Calls `vkCmdSetStencilWriteMask` on the builder. + #[inline] + pub unsafe fn set_stencil_write_mask(&mut self, write_mask: DynamicStencilValue) { + + struct Cmd { + face_mask: StencilFaceFlags, + write_mask: u32, + } + + impl

Command

for Cmd { + fn name(&self) -> &'static str { + "vkCmdSetStencilWriteMask" + } + + unsafe fn send(&mut self, out: &mut UnsafeCommandBufferBuilder

) { + out.set_stencil_write_mask(self.face_mask, self.write_mask); + } + + fn into_final_command(self: Box) -> Box { + Box::new("vkCmdSetStencilWriteMask") + } + } + + self.append_command(Cmd { + face_mask: write_mask.face, + write_mask: write_mask.value, + }); + } /// Calls `vkCmdSetScissor` on the builder. /// @@ -1707,15 +1794,15 @@ impl

SyncCommandBufferBuilder

{ out.set_scissor(self.first_scissor, self.scissors.take().unwrap()); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetScissor") } } self.append_command(Cmd { - first_scissor, - scissors: Some(scissors), - }); + first_scissor, + scissors: Some(scissors), + }); } /// Calls `vkCmdSetViewport` on the builder. @@ -1741,7 +1828,7 @@ impl

SyncCommandBufferBuilder

{ out.set_viewport(self.first_viewport, self.viewports.take().unwrap()); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { Box::new("vkCmdSetViewport") } } @@ -1775,7 +1862,7 @@ impl

SyncCommandBufferBuilder

{ out.update_buffer(&self.buffer, &self.data); } - fn into_final_command(self: Box) -> Box { + fn into_final_command(self: Box) -> Box { struct Fin(B); impl FinalCommand for Fin where B: BufferAccess + Send + Sync + 'static @@ -1783,7 +1870,7 @@ impl

SyncCommandBufferBuilder

{ fn name(&self) -> &'static str { "vkCmdUpdateBuffer" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.0 } @@ -1794,7 +1881,7 @@ impl

SyncCommandBufferBuilder

{ Box::new(Fin(self.buffer)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { assert_eq!(num, 0); &self.buffer } @@ -1824,7 +1911,7 @@ impl

SyncCommandBufferBuilder

{ pub struct SyncCommandBufferBuilderBindDescriptorSets<'b, P: 'b> { builder: &'b mut SyncCommandBufferBuilder

, - inner: SmallVec<[Box; 12]>, + inner: SmallVec<[Box; 12]>, } impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { @@ -1848,7 +1935,7 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { } struct Cmd { - inner: SmallVec<[Box; 12]>, + inner: SmallVec<[Box; 12]>, graphics: bool, pipeline_layout: Pl, first_binding: u32, @@ -1871,13 +1958,13 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { self.dynamic_offsets.take().unwrap()); } - fn into_final_command(self: Box) -> Box { - struct Fin(SmallVec<[Box; 12]>); + fn into_final_command(self: Box) -> Box { + struct Fin(SmallVec<[Box; 12]>); impl FinalCommand for Fin { fn name(&self) -> &'static str { "vkCmdBindDescriptorSets" } - fn buffer(&self, mut num: usize) -> &BufferAccess { + fn buffer(&self, mut num: usize) -> &dyn BufferAccess { for set in self.0.iter() { if let Some(buf) = set.buffer(num) { return buf.0; @@ -1898,7 +1985,7 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { } panic!() } - fn image(&self, mut num: usize) -> &ImageAccess { + fn image(&self, mut num: usize) -> &dyn ImageAccess { for set in self.0.iter() { if let Some(img) = set.image(num) { return img.0.parent(); @@ -1923,7 +2010,7 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { Box::new(Fin(self.inner)) } - fn buffer(&self, mut num: usize) -> &BufferAccess { + fn buffer(&self, mut num: usize) -> &dyn BufferAccess { for set in self.inner.iter() { if let Some(buf) = set.buffer(num) { return buf.0; @@ -1944,7 +2031,7 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { panic!() } - fn image(&self, mut num: usize) -> &ImageAccess { + fn image(&self, mut num: usize) -> &dyn ImageAccess { for set in self.inner.iter() { if let Some(img) = set.image(num) { return img.0.parent(); @@ -2054,7 +2141,7 @@ impl<'b, P> SyncCommandBufferBuilderBindDescriptorSets<'b, P> { pub struct SyncCommandBufferBuilderBindVertexBuffer<'a, P: 'a> { builder: &'a mut SyncCommandBufferBuilder

, inner: UnsafeCommandBufferBuilderBindVertexBuffer, - buffers: Vec>, + buffers: Vec>, } impl<'a, P> SyncCommandBufferBuilderBindVertexBuffer<'a, P> { @@ -2072,7 +2159,7 @@ impl<'a, P> SyncCommandBufferBuilderBindVertexBuffer<'a, P> { struct Cmd { first_binding: u32, inner: Option, - buffers: Vec>, + buffers: Vec>, } impl

Command

for Cmd { @@ -2084,13 +2171,13 @@ impl<'a, P> SyncCommandBufferBuilderBindVertexBuffer<'a, P> { out.bind_vertex_buffers(self.first_binding, self.inner.take().unwrap()); } - fn into_final_command(self: Box) -> Box { - struct Fin(Vec>); + fn into_final_command(self: Box) -> Box { + struct Fin(Vec>); impl FinalCommand for Fin { fn name(&self) -> &'static str { "vkCmdBindVertexBuffers" } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { &self.0[num] } fn buffer_name(&self, num: usize) -> Cow<'static, str> { @@ -2100,7 +2187,7 @@ impl<'a, P> SyncCommandBufferBuilderBindVertexBuffer<'a, P> { Box::new(Fin(self.buffers)) } - fn buffer(&self, num: usize) -> &BufferAccess { + fn buffer(&self, num: usize) -> &dyn BufferAccess { &self.buffers[num] } @@ -2143,7 +2230,7 @@ impl<'a, P> SyncCommandBufferBuilderBindVertexBuffer<'a, P> { pub struct SyncCommandBufferBuilderExecuteCommands<'a, P: 'a> { builder: &'a mut SyncCommandBufferBuilder

, inner: UnsafeCommandBufferBuilderExecuteCommands, - command_buffers: Vec>, + command_buffers: Vec>, } impl<'a, P> SyncCommandBufferBuilderExecuteCommands<'a, P> { @@ -2161,7 +2248,7 @@ impl<'a, P> SyncCommandBufferBuilderExecuteCommands<'a, P> { pub unsafe fn submit(self) -> Result<(), SyncCommandBufferBuilderError> { struct Cmd { inner: Option, - command_buffers: Vec>, + command_buffers: Vec>, } impl

Command

for Cmd { @@ -2173,8 +2260,8 @@ impl<'a, P> SyncCommandBufferBuilderExecuteCommands<'a, P> { out.execute_commands(self.inner.take().unwrap()); } - fn into_final_command(self: Box) -> Box { - struct Fin(Vec>); + fn into_final_command(self: Box) -> Box { + struct Fin(Vec>); impl FinalCommand for Fin { fn name(&self) -> &'static str { "vkCmdExecuteCommands" diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/tests.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/tests.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/tests.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/tests.rs index 12a237c..8645559 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/synced/tests.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/synced/tests.rs @@ -34,7 +34,7 @@ fn basic_conflict() { let pool = Device::standard_command_pool(&device, queue.family()); let mut sync = SyncCommandBufferBuilder::new(&pool, Kind::primary(), Flags::None).unwrap(); - let buf = CpuAccessibleBuffer::from_data(device, BufferUsage::all(), 0u32).unwrap(); + let buf = CpuAccessibleBuffer::from_data(device, BufferUsage::all(), false, 0u32).unwrap(); match sync.copy_buffer(buf.clone(), buf.clone(), iter::once((0, 0, 4))) { Err(SyncCommandBufferBuilderError::Conflict { .. }) => (), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/sys.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/sys.rs index 4d92afb..dff5fa8 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/sys.rs @@ -13,7 +13,6 @@ use std::mem; use std::ops::Range; use std::ptr; use std::sync::Arc; -use std::ffi::CStr; use OomError; use VulkanObject; @@ -47,6 +46,7 @@ use pipeline::GraphicsPipelineAbstract; use pipeline::input_assembly::IndexType; use pipeline::viewport::Scissor; use pipeline::viewport::Viewport; +use pipeline::depth_stencil::StencilFaceFlags; use query::QueryPipelineStatisticFlags; use query::UnsafeQueriesRange; use query::UnsafeQuery; @@ -55,6 +55,7 @@ use sync::AccessFlagBits; use sync::Event; use sync::PipelineStages; use vk; +use std::ffi::CStr; /// Determines the kind of command buffer that we want to create. #[derive(Debug, Clone)] @@ -1029,7 +1030,7 @@ impl

UnsafeCommandBufferBuilder

{ /// Calls `vkCmdCopyQueryPoolResults` on the builder. #[inline] pub unsafe fn copy_query_pool_results(&mut self, queries: UnsafeQueriesRange, - destination: &BufferAccess, stride: usize) { + destination: &dyn BufferAccess, stride: usize) { let destination = destination.inner(); debug_assert!(destination.offset < destination.buffer.size()); debug_assert!(destination.buffer.usage_transfer_destination()); @@ -1342,32 +1343,31 @@ impl

UnsafeCommandBufferBuilder

{ vk.CmdSetLineWidth(cmd, line_width); } - // TODO: missing enum for face_mask - /*/// Calls `vkCmdSetStencilCompareMask` on the builder. - #[inline] - pub unsafe fn set_stencil_compare_mask(&mut self, face_mask: , compare_mask: u32) { - let vk = self.device().pointers(); - let cmd = self.internal_object(); - vk.CmdSetStencilCompareMask(cmd, face_mask, compare_mask); - }*/ - // TODO: missing enum for face_mask - /*/// Calls `vkCmdSetStencilReference` on the builder. + /// Calls `vkCmdSetStencilCompareMask` on the builder. #[inline] - pub unsafe fn set_stencil_reference(&mut self, face_mask: , reference: u32) { + pub unsafe fn set_stencil_compare_mask(&mut self, face_mask: StencilFaceFlags, compare_mask: u32) { let vk = self.device().pointers(); let cmd = self.internal_object(); - vk.CmdSetStencilReference(cmd, face_mask, reference); - }*/ + vk.CmdSetStencilCompareMask(cmd, face_mask as u32, compare_mask); + } - // TODO: missing enum for face_mask - /*/// Calls `vkCmdSetStencilWriteMask` on the builder. + + /// Calls `vkCmdSetStencilReference` on the builder. #[inline] - pub unsafe fn set_stencil_write_mask(&mut self, face_mask: , write_mask: u32) { + pub unsafe fn set_stencil_reference(&mut self, face_mask: StencilFaceFlags, reference: u32) { let vk = self.device().pointers(); let cmd = self.internal_object(); - vk.CmdSetStencilWriteMask(cmd, face_mask, write_mask); - }*/ + vk.CmdSetStencilReference(cmd, face_mask as u32, reference); + } + + /// Calls `vkCmdSetStencilWriteMask` on the builder. + #[inline] + pub unsafe fn set_stencil_write_mask(&mut self, face_mask: StencilFaceFlags, write_mask: u32) { + let vk = self.device().pointers(); + let cmd = self.internal_object(); + vk.CmdSetStencilWriteMask(cmd, face_mask as u32, write_mask); + } /// Calls `vkCmdSetScissor` on the builder. /// @@ -1472,10 +1472,7 @@ impl

UnsafeCommandBufferBuilder

{ query.index()); } - /// Calls `vkCmdDebugMarkerBeginEXT` on the builder. - /// - /// # Panics - /// Requires the `VK_EXT_debug_marker` device extension to be loaded. + /// Calls `vkCmdBeginDebugUtilsLabelEXT` on the builder. /// /// # Safety /// The command pool that this command buffer was allocated from must support graphics or @@ -1484,36 +1481,28 @@ impl

UnsafeCommandBufferBuilder

{ pub unsafe fn debug_marker_begin(&mut self, name: &CStr, color: [f32; 4]) { let vk = self.device().pointers(); let cmd = self.internal_object(); - let info = vk::DebugMarkerMarkerInfoEXT { - sType: vk::STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT, + let info = vk::DebugUtilsLabelEXT { + sType: vk::STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, pNext: ptr::null(), - pMarkerName: name.as_ptr(), - color: color, + pLabelName: name.as_ptr(), + color, }; - vk.CmdDebugMarkerBeginEXT(cmd, &info); + vk.CmdBeginDebugUtilsLabelEXT(cmd, &info); } - /// Calls `vkCmdDebugMarkerEndEXT` on the builder. - /// - /// # Panics - /// Requires the `VK_EXT_debug_marker` device extension to be loaded. + /// Calls `vkCmdEndDebugUtilsLabelEXT` on the builder. /// /// # Safety - /// There must be an outstanding `vkCmdDebugMarkerBeginEXT` command prior to the - /// `vkCmdDebugMarkerEndEXT` on the queue that this command buffer is submitted to. If the - /// matching `vkCmdDebugMarkerBeginEXT` command was in a secondary command buffer, the - /// `vkCmdDebugMarkerEndEXT` must be in the same command buffer. + /// There must be an outstanding `vkCmdBeginDebugUtilsLabelEXT` command prior to the + /// `vkQueueEndDebugUtilsLabelEXT` on the queue tha `CommandBuffer` is submitted to. #[inline] pub unsafe fn debug_marker_end(&mut self) { let vk = self.device().pointers(); let cmd = self.internal_object(); - vk.CmdDebugMarkerEndEXT(cmd); + vk.CmdEndDebugUtilsLabelEXT(cmd); } - /// Calls `vkCmdDebugMarkerInsertEXT` on the builder. - /// - /// # Panics - /// Requires the `VK_EXT_debug_marker` device extension to be loaded. + /// Calls `vkCmdInsertDebugUtilsLabelEXT` on the builder. /// /// # Safety /// The command pool that this command buffer was allocated from must support graphics or @@ -1522,13 +1511,13 @@ impl

UnsafeCommandBufferBuilder

{ pub unsafe fn debug_marker_insert(&mut self, name: &CStr, color: [f32; 4]) { let vk = self.device().pointers(); let cmd = self.internal_object(); - let info = vk::DebugMarkerMarkerInfoEXT { - sType: vk::STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT, + let info = vk::DebugUtilsLabelEXT { + sType: vk::STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, pNext: ptr::null(), - pMarkerName: name.as_ptr(), - color: color, + pLabelName: name.as_ptr(), + color, }; - vk.CmdDebugMarkerInsertEXT(cmd, &info); + vk.CmdInsertDebugUtilsLabelEXT(cmd, &info); } } @@ -1542,7 +1531,7 @@ unsafe impl

DeviceOwned for UnsafeCommandBufferBuilder

{ unsafe impl

VulkanObject for UnsafeCommandBufferBuilder

{ type Object = vk::CommandBuffer; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_COMMAND_BUFFER; #[inline] fn internal_object(&self) -> vk::CommandBuffer { @@ -1952,7 +1941,7 @@ unsafe impl

DeviceOwned for UnsafeCommandBuffer

{ unsafe impl

VulkanObject for UnsafeCommandBuffer

{ type Object = vk::CommandBuffer; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_COMMAND_BUFFER; #[inline] fn internal_object(&self) -> vk::CommandBuffer { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/traits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/traits.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/traits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/traits.rs index 9c8f326..23d9216 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/traits.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/traits.rs @@ -54,7 +54,7 @@ pub unsafe trait CommandBuffer: DeviceOwned { /// the given queue, and if so locks it. /// /// If you call this function, then you should call `unlock` afterwards. - fn lock_submit(&self, future: &GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError>; + fn lock_submit(&self, future: &dyn GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError>; /// Unlocks the command buffer. Should be called once for each call to `lock_submit`. /// @@ -136,10 +136,10 @@ pub unsafe trait CommandBuffer: DeviceOwned { }) } - fn check_buffer_access(&self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + fn check_buffer_access(&self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError>; - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError>; @@ -158,7 +158,7 @@ unsafe impl CommandBuffer for T } #[inline] - fn lock_submit(&self, future: &GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError> { + fn lock_submit(&self, future: &dyn GpuFuture, queue: &Queue) -> Result<(), CommandBufferExecError> { (**self).lock_submit(future, queue) } @@ -169,13 +169,13 @@ unsafe impl CommandBuffer for T #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_buffer_access(buffer, exclusive, queue) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_image_access(image, layout, exclusive, queue) @@ -281,7 +281,7 @@ unsafe impl GpuFuture for CommandBufferExecFuture #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { match self.command_buffer .check_buffer_access(buffer, exclusive, queue) { @@ -294,7 +294,7 @@ unsafe impl GpuFuture for CommandBufferExecFuture } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { match self.command_buffer @@ -379,7 +379,7 @@ impl error::Error for CommandBufferExecError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { CommandBufferExecError::AccessError { ref error, .. } => Some(error), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/blit_image.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/blit_image.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/blit_image.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/blit_image.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/clear_color_image.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/clear_color_image.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/clear_color_image.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/clear_color_image.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_buffer.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_buffer.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_image.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_image.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_image.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_image.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_image_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_image_buffer.rs similarity index 77% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_image_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_image_buffer.rs index d1f2e57..a70d02d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/copy_image_buffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/copy_image_buffer.rs @@ -33,7 +33,6 @@ pub enum CheckCopyBufferImageTy { /// /// - Panics if the buffer and image were not created with `device`. /// -// TODO: handle compressed image formats pub fn check_copy_buffer_image(device: &Device, buffer: &B, image: &I, ty: CheckCopyBufferImageTy, image_offset: [u32; 3], image_size: [u32; 3], image_first_layer: u32, @@ -98,8 +97,7 @@ pub fn check_copy_buffer_image(device: &Device, buffer: &B, image: &I, image.format().ensure_accepts()?; { - let num_texels = image_size[0] * image_size[1] * image_size[2] * image_num_layers; - let required_len = num_texels as usize * image.format().rate() as usize; + let required_len = required_len_for_format(image.format(), image_size, image_num_layers); if required_len > buffer.len() { return Err(CheckCopyBufferImageError::BufferTooSmall { required_len: required_len, @@ -113,6 +111,39 @@ pub fn check_copy_buffer_image(device: &Device, buffer: &B, image: &I, Ok(()) } +/// Computes the minimum required len in elements for buffer with image data in specified +/// format of specified size. +fn required_len_for_format

(format: Format, image_size: [u32; 3], image_num_layers: u32) -> usize +where Format: AcceptsPixels

+{ + let (block_width, block_height) = format.block_dimensions(); + let num_blocks = (image_size[0] + block_width - 1) / block_width * ((image_size[1] + block_height - 1) / block_height) * image_size[2] * image_num_layers; + let required_len = num_blocks as usize * format.rate() as usize; + + return required_len; +} + +#[cfg(test)] +mod tests { + use crate::format::Format; + use command_buffer::validity::copy_image_buffer::required_len_for_format; + + #[test] + fn test_required_len_for_format() { + // issue #1292 + assert_eq!(required_len_for_format::(Format::BC1_RGBUnormBlock, [2048, 2048, 1], 1), 2097152); + // other test cases + assert_eq!(required_len_for_format::(Format::R8G8B8A8Unorm, [2048, 2048, 1], 1), 16777216); + assert_eq!(required_len_for_format::(Format::R4G4UnormPack8, [512, 512, 1], 1), 262144); + assert_eq!(required_len_for_format::(Format::R8G8B8Uscaled, [512, 512, 1], 1), 786432); + assert_eq!(required_len_for_format::(Format::R32G32Uint, [512, 512, 1], 1), 2097152); + assert_eq!(required_len_for_format::(Format::R32G32Uint, [512, 512, 1], 1), 524288); + assert_eq!(required_len_for_format::<[u32; 2]>(Format::R32G32Uint, [512, 512, 1], 1), 262144); + assert_eq!(required_len_for_format::(Format::ASTC_8x8UnormBlock, [512, 512, 1], 1), 65536); + assert_eq!(required_len_for_format::(Format::ASTC_12x12SrgbBlock, [512, 512, 1], 1), 29584); + } +} + /// Error that can happen from `check_copy_buffer_image`. #[derive(Debug, Copy, Clone)] pub enum CheckCopyBufferImageError { @@ -165,7 +196,7 @@ impl error::Error for CheckCopyBufferImageError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { CheckCopyBufferImageError::WrongPixelType(ref err) => { Some(err) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/descriptor_sets.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/descriptor_sets.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/descriptor_sets.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/descriptor_sets.rs index 4b5eed6..581a41c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/descriptor_sets.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/descriptor_sets.rs @@ -89,7 +89,7 @@ impl error::Error for CheckDescriptorSetsValidityError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { CheckDescriptorSetsValidityError::IncompatibleDescriptor { ref error, .. } => { Some(error) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/dispatch.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/dispatch.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/dispatch.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/dispatch.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/dynamic_state.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/dynamic_state.rs similarity index 69% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/dynamic_state.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/dynamic_state.rs index 843f88a..7761af1 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/dynamic_state.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/dynamic_state.rs @@ -71,7 +71,38 @@ pub fn check_dynamic_state_validity(pipeline: &Pl, state: &DynamicState) } } - // TODO: don't forget to implement the rest + if pipeline.has_dynamic_stencil_compare_mask() { + if let None = state.compare_mask { + return Err(CheckDynamicStateValidityError::CompareMaskMissing); + } + + } else { + if state.compare_mask.is_some() { + return Err(CheckDynamicStateValidityError::CompareMaskNotDynamic); + } + } + + if pipeline.has_dynamic_stencil_write_mask() { + if let None = state.write_mask { + return Err(CheckDynamicStateValidityError::WriteMaskMissing); + } + + } else { + if state.write_mask.is_some() { + return Err(CheckDynamicStateValidityError::WriteMaskNotDynamic); + } + } + + if pipeline.has_dynamic_stencil_reference() { + if let None = state.reference { + return Err(CheckDynamicStateValidityError::ReferenceMissing); + } + + } else { + if state.reference.is_some() { + return Err(CheckDynamicStateValidityError::ReferenceNotDynamic); + } + } Ok(()) } @@ -108,6 +139,18 @@ pub enum CheckDynamicStateValidityError { /// Number of scissors that were passed. obtained: usize, }, + /// Passed dynamic compare mask, while the pipeline doesn't have the compare mask set as dynamic. + CompareMaskNotDynamic, + /// The pipeline has dynamic compare mask, but no compare mask was passed. + CompareMaskMissing, + /// Passed dynamic write mask, while the pipeline doesn't have the write mask set as dynamic. + WriteMaskNotDynamic, + /// The pipeline has dynamic write mask, but no write mask was passed. + WriteMaskMissing, + /// Passed dynamic reference, while the pipeline doesn't have the reference set as dynamic. + ReferenceNotDynamic, + /// The pipeline has dynamic reference, but no reference was passed. + ReferenceMissing, } impl error::Error for CheckDynamicStateValidityError { @@ -144,6 +187,24 @@ impl error::Error for CheckDynamicStateValidityError { CheckDynamicStateValidityError::ScissorsCountMismatch { .. } => { "the number of dynamic scissors doesn't match the expected number of scissors" }, + CheckDynamicStateValidityError::CompareMaskNotDynamic => { + "passed dynamic compare mask, while the pipeline doesn't have compare mask set as dynamic" + }, + CheckDynamicStateValidityError::CompareMaskMissing => { + "the pipeline has dynamic compare mask, but no compare mask was passed" + }, + CheckDynamicStateValidityError::WriteMaskNotDynamic => { + "passed dynamic write mask, while the pipeline doesn't have write mask set as dynamic" + }, + CheckDynamicStateValidityError::WriteMaskMissing => { + "the pipeline has dynamic write mask, but no write mask was passed" + }, + CheckDynamicStateValidityError::ReferenceNotDynamic => { + "passed dynamic Reference, while the pipeline doesn't have reference set as dynamic" + }, + CheckDynamicStateValidityError::ReferenceMissing => { + "the pipeline has dynamic reference, but no reference was passed" + }, } } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/fill_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/fill_buffer.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/fill_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/fill_buffer.rs index 2648849..53c302a 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/fill_buffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/fill_buffer.rs @@ -78,7 +78,7 @@ mod tests { fn missing_usage() { let (device, queue) = gfx_dev_and_queue!(); let buffer = - CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), 0u32) + CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), false, 0u32) .unwrap(); match check_fill_buffer(&device, &buffer) { @@ -91,7 +91,7 @@ mod tests { fn wrong_device() { let (dev1, queue) = gfx_dev_and_queue!(); let (dev2, _) = gfx_dev_and_queue!(); - let buffer = CpuAccessibleBuffer::from_data(dev1, BufferUsage::all(), 0u32).unwrap(); + let buffer = CpuAccessibleBuffer::from_data(dev1, BufferUsage::all(), false, 0u32).unwrap(); assert_should_panic!({ let _ = check_fill_buffer(&dev2, &buffer); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/index_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/index_buffer.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/index_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/index_buffer.rs index 1978741..e09a914 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/index_buffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/index_buffer.rs @@ -96,6 +96,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); let buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::index_buffer(), + false, 0 .. 500u32) .unwrap(); @@ -112,6 +113,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); let buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::vertex_buffer(), + false, 0 .. 500u32) .unwrap(); @@ -126,7 +128,7 @@ mod tests { let (dev1, queue) = gfx_dev_and_queue!(); let (dev2, _) = gfx_dev_and_queue!(); - let buffer = CpuAccessibleBuffer::from_iter(dev1, BufferUsage::all(), 0 .. 500u32).unwrap(); + let buffer = CpuAccessibleBuffer::from_iter(dev1, BufferUsage::all(), false, 0 .. 500u32).unwrap(); assert_should_panic!({ let _ = check_index_buffer(&dev2, &buffer); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/push_constants.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/push_constants.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/push_constants.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/push_constants.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/update_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/update_buffer.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/update_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/update_buffer.rs index 6384643..4f3b79a 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/update_buffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/update_buffer.rs @@ -96,7 +96,7 @@ mod tests { fn missing_usage() { let (device, queue) = gfx_dev_and_queue!(); let buffer = - CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), 0u32) + CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::vertex_buffer(), false, 0u32) .unwrap(); match check_update_buffer(&device, &buffer, &0) { @@ -110,6 +110,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); let buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::transfer_destination(), + false, 0 .. 65536) .unwrap(); let data = (0 .. 65536).collect::>(); @@ -125,6 +126,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); let buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::transfer_destination(), + false, (0 .. 100000).map(|_| 0)) .unwrap(); let data = (0 .. 65536).map(|_| 0).collect::>(); @@ -140,6 +142,7 @@ mod tests { let (device, queue) = gfx_dev_and_queue!(); let buffer = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::transfer_destination(), + false, 0 .. 100) .unwrap(); let data = (0 .. 30).collect::>(); @@ -154,7 +157,7 @@ mod tests { fn wrong_device() { let (dev1, queue) = gfx_dev_and_queue!(); let (dev2, _) = gfx_dev_and_queue!(); - let buffer = CpuAccessibleBuffer::from_data(dev1, BufferUsage::all(), 0u32).unwrap(); + let buffer = CpuAccessibleBuffer::from_data(dev1, BufferUsage::all(), false, 0u32).unwrap(); assert_should_panic!({ let _ = check_update_buffer(&dev2, &buffer, &0); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/vertex_buffers.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/vertex_buffers.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/vertex_buffers.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/vertex_buffers.rs index 62980d0..ac96a1d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/validity/vertex_buffers.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/validity/vertex_buffers.rs @@ -46,7 +46,7 @@ pub fn check_vertex_buffers(pipeline: &P, vertex_buffers: V) /// Information returned if `check_vertex_buffer` succeeds. pub struct CheckVertexBuffer { /// The list of vertex buffers. - pub vertex_buffers: Vec>, + pub vertex_buffers: Vec>, /// Number of vertices available in the intersection of the buffers. pub vertex_count: u32, /// Number of instances available in the intersection of the buffers. diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor.rs index adaae6e..e3f7aca 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor.rs @@ -57,7 +57,7 @@ use vk; /// > will be checked when you create a pipeline layout, a descriptor set, or when you try to bind /// > a descriptor set. // TODO: add example -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub struct DescriptorDesc { /// Describes the content and layout of each array element of a descriptor. pub ty: DescriptorDescTy, @@ -78,7 +78,33 @@ impl DescriptorDesc { /// /// Returns true if `self` is the same descriptor as `other`, or if `self` is the same as /// `other` but with a larger array elements count and/or more shader stages. - // TODO: add example + /// + ///# Example + ///``` + ///use vulkano::descriptor::descriptor::DescriptorDesc; + ///use vulkano::descriptor::descriptor::DescriptorDescTy::*; + ///use vulkano::descriptor::descriptor::ShaderStages; + /// + ///let desc_super = DescriptorDesc{ ty: Sampler, array_count: 2, stages: ShaderStages{ + /// vertex: true, + /// tessellation_control: true, + /// tessellation_evaluation: true, + /// geometry: true, + /// fragment: true, + /// compute: true + ///}, readonly: false }; + ///let desc_sub = DescriptorDesc{ ty: Sampler, array_count: 1, stages: ShaderStages{ + /// vertex: true, + /// tessellation_control: false, + /// tessellation_evaluation: false, + /// geometry: false, + /// fragment: true, + /// compute: false + ///}, readonly: true }; + /// + ///assert_eq!(desc_super.is_superset_of(&desc_sub).unwrap(), ()); + /// + ///``` #[inline] pub fn is_superset_of(&self, other: &DescriptorDesc) -> Result<(), DescriptorDescSupersetError> { @@ -102,8 +128,43 @@ impl DescriptorDesc { /// Builds a `DescriptorDesc` that is the union of `self` and `other`, if possible. /// /// The returned value will be a superset of both `self` and `other`. + /// + ///# Example + ///``` + ///use vulkano::descriptor::descriptor::DescriptorDesc; + ///use vulkano::descriptor::descriptor::DescriptorDescTy::*; + ///use vulkano::descriptor::descriptor::ShaderStages; + /// + ///let desc_part1 = DescriptorDesc{ ty: Sampler, array_count: 2, stages: ShaderStages{ + /// vertex: true, + /// tessellation_control: true, + /// tessellation_evaluation: false, + /// geometry: true, + /// fragment: false, + /// compute: true + ///}, readonly: false }; + /// + ///let desc_part2 = DescriptorDesc{ ty: Sampler, array_count: 1, stages: ShaderStages{ + /// vertex: true, + /// tessellation_control: false, + /// tessellation_evaluation: true, + /// geometry: false, + /// fragment: true, + /// compute: true + ///}, readonly: true }; + /// + ///let desc_union = DescriptorDesc{ ty: Sampler, array_count: 2, stages: ShaderStages{ + /// vertex: true, + /// tessellation_control: true, + /// tessellation_evaluation: true, + /// geometry: true, + /// fragment: true, + /// compute: true + ///}, readonly: false }; + /// + ///assert_eq!(desc_part1.union(&desc_part2), Some(desc_union)); + ///``` // TODO: Result instead of Option - // TODO: add example #[inline] pub fn union(&self, other: &DescriptorDesc) -> Option { if self.ty != other.ty { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/collection.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/collection.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/collection.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/collection.rs index 3d23a57..03c917f 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/collection.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/collection.rs @@ -13,7 +13,7 @@ use descriptor::descriptor_set::DescriptorSetDesc; /// A collection of descriptor set objects. pub unsafe trait DescriptorSetsCollection { - fn into_vec(self) -> Vec>; + fn into_vec(self) -> Vec>; /// Returns the number of descriptors in the set. Includes possibly empty descriptors. /// @@ -30,7 +30,7 @@ pub unsafe trait DescriptorSetsCollection { unsafe impl DescriptorSetsCollection for () { #[inline] - fn into_vec(self) -> Vec> { + fn into_vec(self) -> Vec> { vec![] } @@ -49,7 +49,7 @@ unsafe impl DescriptorSetsCollection for T where T: DescriptorSet + Send + Sync + 'static { #[inline] - fn into_vec(self) -> Vec> { + fn into_vec(self) -> Vec> { vec![Box::new(self) as Box<_>] } @@ -74,7 +74,7 @@ unsafe impl DescriptorSetsCollection for Vec where T: DescriptorSet + Send + Sync + 'static { #[inline] - fn into_vec(self) -> Vec> { + fn into_vec(self) -> Vec> { let mut v = Vec::new(); for o in self { v.push(Box::new(o) as Box<_>); @@ -99,7 +99,7 @@ macro_rules! impl_collection { $(, $others: DescriptorSet + DescriptorSetDesc + Send + Sync + 'static)* { #[inline] - fn into_vec(self) -> Vec> { + fn into_vec(self) -> Vec> { #![allow(non_snake_case)] let ($first, $($others,)*) = self; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/fixed_size_pool.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/fixed_size_pool.rs similarity index 77% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/fixed_size_pool.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/fixed_size_pool.rs index 656a38a..7b6d6cb 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/fixed_size_pool.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/fixed_size_pool.rs @@ -8,9 +8,12 @@ // according to those terms. use crossbeam::queue::SegQueue; +use std::hash::Hash; +use std::hash::Hasher; use std::sync::Arc; use OomError; +use VulkanObject; use buffer::BufferAccess; use buffer::BufferViewRef; use descriptor::descriptor::DescriptorDesc; @@ -23,7 +26,6 @@ use descriptor::descriptor_set::UnsafeDescriptorPool; use descriptor::descriptor_set::UnsafeDescriptorSet; use descriptor::descriptor_set::UnsafeDescriptorSetLayout; use descriptor::descriptor_set::persistent::*; -use descriptor::pipeline_layout::PipelineLayoutAbstract; use device::Device; use device::DeviceOwned; use image::ImageViewAccess; @@ -36,33 +38,29 @@ use sampler::Sampler; /// /// # Example /// -/// At initialization, create a `FixedSizeDescriptorSetsPool`. The first parameter of the `new` -/// function can be a graphics pipeline, a compute pipeline, or anything that represents a pipeline -/// layout. +/// At initialization, create a `FixedSizeDescriptorSetsPool`. /// /// ```rust /// use vulkano::descriptor::descriptor_set::FixedSizeDescriptorSetsPool; +/// use vulkano::descriptor::pipeline_layout::PipelineLayoutAbstract; /// # use vulkano::pipeline::GraphicsPipelineAbstract; /// # use std::sync::Arc; /// # let graphics_pipeline: Arc = return; /// // use vulkano::pipeline::GraphicsPipelineAbstract; /// // let graphics_pipeline: Arc = ...; /// -/// let pool = FixedSizeDescriptorSetsPool::new(graphics_pipeline.clone(), 0); +/// let layout = graphics_pipeline.descriptor_set_layout(0).unwrap(); +/// let pool = FixedSizeDescriptorSetsPool::new(layout.clone()); /// ``` /// -/// You would then typically store the pool in a struct for later. Its type is -/// `FixedSizeDescriptorSetsPool` where `T` is the type of what was passed to `new()`. In the -/// example above, it would be `FixedSizeDescriptorSetsPool>`. -/// -/// Then whenever you need a descriptor set, call `pool.next()` to start the process of building -/// it. +/// You would then typically store the pool in a struct for later. Then whenever you need a +/// descriptor set, call `pool.next()` to start the process of building it. /// /// ```rust /// # use std::sync::Arc; /// # use vulkano::descriptor::descriptor_set::FixedSizeDescriptorSetsPool; /// # use vulkano::pipeline::GraphicsPipelineAbstract; -/// # let mut pool: FixedSizeDescriptorSetsPool> = return; +/// # let mut pool: FixedSizeDescriptorSetsPool = return; /// let descriptor_set = pool.next() /// //.add_buffer(...) /// //.add_sampled_image(...) @@ -73,34 +71,22 @@ use sampler::Sampler; /// the pool if you can't provide this. /// #[derive(Clone)] -pub struct FixedSizeDescriptorSetsPool { - pipeline_layout: L, - set_id: usize, - set_layout: Arc, +pub struct FixedSizeDescriptorSetsPool { + layout: Arc, // We hold a local implementation of the `DescriptorPool` trait for our own purpose. Since we // don't want to expose this trait impl in our API, we use a separate struct. pool: LocalPool, } -impl FixedSizeDescriptorSetsPool { +impl FixedSizeDescriptorSetsPool { /// Initializes a new pool. The pool is configured to allocate sets that corresponds to the /// parameters passed to this function. - pub fn new(layout: L, set_id: usize) -> FixedSizeDescriptorSetsPool - where L: PipelineLayoutAbstract + pub fn new(layout: Arc) -> FixedSizeDescriptorSetsPool { - assert!(layout.num_sets() > set_id); - let device = layout.device().clone(); - let set_layout = layout - .descriptor_set_layout(set_id) - .expect("Unable to get the descriptor set layout") - .clone(); - FixedSizeDescriptorSetsPool { - pipeline_layout: layout, - set_id, - set_layout, + layout, pool: LocalPool { device: device, next_capacity: 3, @@ -113,10 +99,9 @@ impl FixedSizeDescriptorSetsPool { /// /// The set will corresponds to the set layout that was passed to `new`. #[inline] - pub fn next(&mut self) -> FixedSizeDescriptorSetBuilder - where L: PipelineLayoutAbstract + Clone + pub fn next(&mut self) -> FixedSizeDescriptorSetBuilder<()> { - let inner = PersistentDescriptorSet::start(self.pipeline_layout.clone(), self.set_id); + let inner = PersistentDescriptorSet::start(self.layout.clone()); FixedSizeDescriptorSetBuilder { pool: self, @@ -126,13 +111,12 @@ impl FixedSizeDescriptorSetsPool { } /// A descriptor set created from a `FixedSizeDescriptorSetsPool`. -pub struct FixedSizeDescriptorSet { - inner: PersistentDescriptorSet, +pub struct FixedSizeDescriptorSet { + inner: PersistentDescriptorSet, } -unsafe impl DescriptorSet for FixedSizeDescriptorSet - where L: PipelineLayoutAbstract, - R: PersistentDescriptorSetResources +unsafe impl DescriptorSet for FixedSizeDescriptorSet + where R: PersistentDescriptorSetResources { #[inline] fn inner(&self) -> &UnsafeDescriptorSet { @@ -145,7 +129,7 @@ unsafe impl DescriptorSet for FixedSizeDescriptorSet } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { self.inner.buffer(index) } @@ -155,14 +139,12 @@ unsafe impl DescriptorSet for FixedSizeDescriptorSet } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { self.inner.image(index) } } -unsafe impl DescriptorSetDesc for FixedSizeDescriptorSet - where L: PipelineLayoutAbstract -{ +unsafe impl DescriptorSetDesc for FixedSizeDescriptorSet { #[inline] fn num_bindings(&self) -> usize { self.inner.num_bindings() @@ -174,15 +156,37 @@ unsafe impl DescriptorSetDesc for FixedSizeDescriptorSet } } -unsafe impl DeviceOwned for FixedSizeDescriptorSet - where L: DeviceOwned -{ +unsafe impl DeviceOwned for FixedSizeDescriptorSet { #[inline] fn device(&self) -> &Arc { self.inner.device() } } +impl PartialEq for FixedSizeDescriptorSet + where R: PersistentDescriptorSetResources +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner().internal_object() == other.inner().internal_object() && + self.device() == other.device() + } +} + +impl Eq for FixedSizeDescriptorSet + where R: PersistentDescriptorSetResources +{} + +impl Hash for FixedSizeDescriptorSet + where R: PersistentDescriptorSetResources +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().internal_object().hash(state); + self.device().hash(state); + } +} + // The fields of this struct can be considered as fields of the `FixedSizeDescriptorSet`. They are // in a separate struct because we don't want to expose the fact that we implement the // `DescriptorPool` trait. @@ -225,7 +229,7 @@ unsafe impl DescriptorPool for LocalPool { // Try to extract a descriptor from the current pool if any exist. // This is the most common case. if let Some(ref mut current_pool) = self.current_pool { - if let Some(already_existing_set) = current_pool.reserve.try_pop() { + if let Ok(already_existing_set) = current_pool.reserve.pop() { return Ok(LocalPoolAlloc { actual_alloc: Some(already_existing_set), pool: current_pool.clone(), @@ -300,21 +304,19 @@ impl Drop for LocalPoolAlloc { /// Prototype of a `FixedSizeDescriptorSet`. /// -/// The template parameter `L` is the pipeline layout to use, and the template parameter `R` is -/// an unspecified type that represents the list of resources. +/// The template parameter `R` is an unspecified type that represents the list of resources. /// /// See the docs of `FixedSizeDescriptorSetsPool` for an example. -pub struct FixedSizeDescriptorSetBuilder<'a, L: 'a, R> { - pool: &'a mut FixedSizeDescriptorSetsPool, - inner: PersistentDescriptorSetBuilder, +pub struct FixedSizeDescriptorSetBuilder<'a, R> { + pool: &'a mut FixedSizeDescriptorSetsPool, + inner: PersistentDescriptorSetBuilder, } -impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> - where L: PipelineLayoutAbstract +impl<'a, R> FixedSizeDescriptorSetBuilder<'a, R> { /// Builds a `FixedSizeDescriptorSet` from the builder. #[inline] - pub fn build(self) -> Result, PersistentDescriptorSetBuildError> { + pub fn build(self) -> Result, PersistentDescriptorSetBuildError> { let inner = self.inner.build_with_pool(&mut self.pool.pool)?; Ok(FixedSizeDescriptorSet { inner: inner }) } @@ -329,7 +331,7 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> #[inline] pub fn enter_array( self) - -> Result, PersistentDescriptorSetError> { + -> Result, PersistentDescriptorSetError> { Ok(FixedSizeDescriptorSetBuilderArray { pool: self.pool, inner: self.inner.enter_array()?, @@ -340,7 +342,7 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> #[inline] pub fn add_empty( self) - -> Result, PersistentDescriptorSetError> { + -> Result, PersistentDescriptorSetError> { Ok(FixedSizeDescriptorSetBuilder { pool: self.pool, inner: self.inner.add_empty()?, @@ -353,12 +355,11 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> /// /// # Panic /// - /// Panics if the buffer doesn't have the same device as the pipeline layout. + /// Panics if the buffer doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_buffer(self, buffer: T) -> Result)>, PersistentDescriptorSetError> @@ -376,10 +377,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> /// /// # Panic /// - /// Panics if the buffer view doesn't have the same device as the pipeline layout. + /// Panics if the buffer view doesn't have the same device as the descriptor set layout. /// pub fn add_buffer_view(self, view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferViewRef { Ok(FixedSizeDescriptorSetBuilder { @@ -394,12 +395,11 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> /// /// # Panic /// - /// Panics if the image view doesn't have the same device as the pipeline layout. + /// Panics if the image view doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_image(self, image_view: T) -> Result)>, PersistentDescriptorSetError> where T: ImageViewAccess @@ -416,11 +416,11 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> /// /// # Panic /// - /// Panics if the image view or the sampler doesn't have the same device as the pipeline layout. + /// Panics if the image view or the sampler doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_sampled_image(self, image_view: T, sampler: Arc) - -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> + -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> where T: ImageViewAccess { Ok(FixedSizeDescriptorSetBuilder { @@ -435,12 +435,11 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> /// /// # Panic /// - /// Panics if the sampler doesn't have the same device as the pipeline layout. + /// Panics if the sampler doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_sampler(self, sampler: Arc) -> Result, PersistentDescriptorSetError> { Ok(FixedSizeDescriptorSetBuilder { @@ -451,18 +450,17 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilder<'a, L, R> } /// Same as `FixedSizeDescriptorSetBuilder`, but we're in an array. -pub struct FixedSizeDescriptorSetBuilderArray<'a, L: 'a, R> { - pool: &'a mut FixedSizeDescriptorSetsPool, - inner: PersistentDescriptorSetBuilderArray, +pub struct FixedSizeDescriptorSetBuilderArray<'a, R> { + pool: &'a mut FixedSizeDescriptorSetsPool, + inner: PersistentDescriptorSetBuilderArray, } -impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> - where L: PipelineLayoutAbstract +impl<'a, R> FixedSizeDescriptorSetBuilderArray<'a, R> { /// Leaves the array. Call this once you added all the elements of the array. pub fn leave_array( self) - -> Result, PersistentDescriptorSetError> { + -> Result, PersistentDescriptorSetError> { Ok(FixedSizeDescriptorSetBuilder { pool: self.pool, inner: self.inner.leave_array()?, @@ -475,10 +473,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> /// /// # Panic /// - /// Panics if the buffer doesn't have the same device as the pipeline layout. + /// Panics if the buffer doesn't have the same device as the descriptor set layout. /// pub fn add_buffer(self, buffer: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferAccess { Ok(FixedSizeDescriptorSetBuilderArray { @@ -493,10 +491,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> /// /// # Panic /// - /// Panics if the buffer view doesn't have the same device as the pipeline layout. + /// Panics if the buffer view doesn't have the same device as the descriptor set layout. /// pub fn add_buffer_view(self, view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferViewRef { Ok(FixedSizeDescriptorSetBuilderArray { @@ -511,10 +509,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> /// /// # Panic /// - /// Panics if the image view doesn't have the same device as the pipeline layout. + /// Panics if the image view doesn't have the same device as the descriptor set layout. /// pub fn add_image(self, image_view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: ImageViewAccess { Ok(FixedSizeDescriptorSetBuilderArray { @@ -529,10 +527,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> /// /// # Panic /// - /// Panics if the image or the sampler doesn't have the same device as the pipeline layout. + /// Panics if the image or the sampler doesn't have the same device as the descriptor set layout. /// pub fn add_sampled_image(self, image_view: T, sampler: Arc) - -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> + -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> where T: ImageViewAccess { Ok(FixedSizeDescriptorSetBuilderArray { @@ -547,10 +545,10 @@ impl<'a, L, R> FixedSizeDescriptorSetBuilderArray<'a, L, R> /// /// # Panic /// - /// Panics if the sampler doesn't have the same device as the pipeline layout. + /// Panics if the sampler doesn't have the same device as the descriptor set layout. /// pub fn add_sampler(self, sampler: Arc) - -> Result, PersistentDescriptorSetError> + -> Result, PersistentDescriptorSetError> { Ok(FixedSizeDescriptorSetBuilderArray { pool: self.pool, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/mod.rs similarity index 86% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/mod.rs index 95ac51d..537d93d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/mod.rs @@ -35,8 +35,13 @@ //! - The `DescriptorSetsCollection` trait is implemented on collections of types that implement //! `DescriptorSet`. It is what you pass to the draw functions. +use std::hash::Hash; +use std::hash::Hasher; + use SafeDeref; +use VulkanObject; use buffer::BufferAccess; +use device::DeviceOwned; use descriptor::descriptor::DescriptorDesc; use image::ImageViewAccess; @@ -77,7 +82,7 @@ mod unsafe_layout; /// Trait for objects that contain a collection of resources that will be accessible by shaders. /// /// Objects of this type can be passed when submitting a draw command. -pub unsafe trait DescriptorSet: DescriptorSetDesc { +pub unsafe trait DescriptorSet: DescriptorSetDesc + DeviceOwned { /// Returns the inner `UnsafeDescriptorSet`. fn inner(&self) -> &UnsafeDescriptorSet; @@ -88,7 +93,7 @@ pub unsafe trait DescriptorSet: DescriptorSetDesc { /// returns the index of the descriptor that uses this buffer. /// /// The valid range is between 0 and `num_buffers()`. - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)>; + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)>; /// Returns the number of images within this descriptor set. fn num_images(&self) -> usize; @@ -97,7 +102,7 @@ pub unsafe trait DescriptorSet: DescriptorSetDesc { /// the index of the descriptor that uses this image. /// /// The valid range is between 0 and `num_images()`. - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)>; + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)>; } unsafe impl DescriptorSet for T @@ -115,7 +120,7 @@ unsafe impl DescriptorSet for T } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { (**self).buffer(index) } @@ -125,11 +130,29 @@ unsafe impl DescriptorSet for T } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { (**self).image(index) } } +impl PartialEq for dyn DescriptorSet + Send + Sync { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner().internal_object() == other.inner().internal_object() && + self.device() == other.device() + } +} + +impl Eq for dyn DescriptorSet + Send + Sync {} + +impl Hash for dyn DescriptorSet + Send + Sync { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().internal_object().hash(state); + self.device().hash(state); + } +} + /// Trait for objects that describe the layout of the descriptors of a set. pub unsafe trait DescriptorSetDesc { /// Returns the number of binding slots in the set. diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/persistent.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/persistent.rs similarity index 87% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/persistent.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/persistent.rs index b60d580..48b2fd9 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/persistent.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/persistent.rs @@ -9,6 +9,8 @@ use std::error; use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::sync::Arc; use OomError; @@ -29,7 +31,6 @@ use descriptor::descriptor_set::DescriptorWrite; use descriptor::descriptor_set::StdDescriptorPoolAlloc; use descriptor::descriptor_set::UnsafeDescriptorSet; use descriptor::descriptor_set::UnsafeDescriptorSetLayout; -use descriptor::pipeline_layout::PipelineLayoutAbstract; use device::Device; use device::DeviceOwned; use format::Format; @@ -54,31 +55,25 @@ use sampler::Sampler; /// /// # Example // TODO: -pub struct PersistentDescriptorSet { +pub struct PersistentDescriptorSet { inner: P, resources: R, - pipeline_layout: L, - set_id: usize, layout: Arc, } -impl PersistentDescriptorSet { +impl PersistentDescriptorSet<()> { /// Starts the process of building a `PersistentDescriptorSet`. Returns a builder. /// /// # Panic /// /// - Panics if the set id is out of range. /// - pub fn start(layout: L, set_id: usize) -> PersistentDescriptorSetBuilder - where L: PipelineLayoutAbstract + pub fn start(layout: Arc) -> PersistentDescriptorSetBuilder<()> { - assert!(layout.num_sets() > set_id); - - let cap = layout.num_bindings_in_set(set_id).unwrap_or(0); + let cap = layout.num_bindings(); PersistentDescriptorSetBuilder { layout: layout, - set_id: set_id, binding_id: 0, writes: Vec::with_capacity(cap), resources: (), @@ -86,9 +81,8 @@ impl PersistentDescriptorSet { } } -unsafe impl DescriptorSet for PersistentDescriptorSet - where L: PipelineLayoutAbstract, - P: DescriptorPoolAlloc, +unsafe impl DescriptorSet for PersistentDescriptorSet + where P: DescriptorPoolAlloc, R: PersistentDescriptorSetResources { #[inline] @@ -102,7 +96,7 @@ unsafe impl DescriptorSet for PersistentDescriptorSet } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { self.resources.buffer(index) } @@ -112,29 +106,25 @@ unsafe impl DescriptorSet for PersistentDescriptorSet } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { self.resources.image(index) } } -unsafe impl DescriptorSetDesc for PersistentDescriptorSet - where L: PipelineLayoutAbstract +unsafe impl DescriptorSetDesc for PersistentDescriptorSet { #[inline] fn num_bindings(&self) -> usize { - self.pipeline_layout - .num_bindings_in_set(self.set_id) - .unwrap() + self.layout.num_bindings() } #[inline] fn descriptor(&self, binding: usize) -> Option { - self.pipeline_layout.descriptor(self.set_id, binding) + self.layout.descriptor(binding) } } -unsafe impl DeviceOwned for PersistentDescriptorSet - where L: DeviceOwned +unsafe impl DeviceOwned for PersistentDescriptorSet { #[inline] fn device(&self) -> &Arc { @@ -142,17 +132,41 @@ unsafe impl DeviceOwned for PersistentDescriptorSet } } +impl PartialEq for PersistentDescriptorSet + where P: DescriptorPoolAlloc, + R: PersistentDescriptorSetResources +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner().internal_object() == other.inner().internal_object() && + self.device() == other.device() + } +} + +impl Eq for PersistentDescriptorSet + where P: DescriptorPoolAlloc, + R: PersistentDescriptorSetResources +{} + +impl Hash for PersistentDescriptorSet + where P: DescriptorPoolAlloc, + R: PersistentDescriptorSetResources +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().internal_object().hash(state); + self.device().hash(state); + } +} + /// Prototype of a `PersistentDescriptorSet`. /// -/// The template parameter `L` is the pipeline layout to use, and the template parameter `R` is -/// an unspecified type that represents the list of resources. +/// The template parameter `R` is an unspecified type that represents the list of resources. /// /// See the docs of `PersistentDescriptorSet` for an example. -pub struct PersistentDescriptorSetBuilder { - // The pipeline layout. - layout: L, - // Id of the set within the pipeline layout. - set_id: usize, +pub struct PersistentDescriptorSetBuilder { + // The descriptor set layout. + layout: Arc, // Binding currently being filled. binding_id: usize, // The writes to perform on a descriptor set in order to put the resources in it. @@ -164,13 +178,12 @@ pub struct PersistentDescriptorSetBuilder { // TODO: lots of checks are still missing, see the docs of // VkDescriptorImageInfo and VkWriteDescriptorSet -impl PersistentDescriptorSetBuilder - where L: PipelineLayoutAbstract +impl PersistentDescriptorSetBuilder { /// Builds a `PersistentDescriptorSet` from the builder. #[inline] pub fn build(self) - -> Result, + -> Result, PersistentDescriptorSetBuildError> { let mut pool = Device::standard_descriptor_pool(self.layout.device()); self.build_with_pool(&mut pool) @@ -180,17 +193,17 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the pool doesn't have the same device as the pipeline layout. + /// Panics if the pool doesn't have the same device as the descriptor set layout. /// pub fn build_with_pool

( self, pool: &mut P) - -> Result, PersistentDescriptorSetBuildError> + -> Result, PersistentDescriptorSetBuildError> where P: ?Sized + DescriptorPool { assert_eq!(self.layout.device().internal_object(), pool.device().internal_object()); - let expected_desc = self.layout.num_bindings_in_set(self.set_id).unwrap(); + let expected_desc = self.layout.num_bindings(); if expected_desc > self.binding_id { return Err(PersistentDescriptorSetBuildError::MissingDescriptors { @@ -201,13 +214,8 @@ impl PersistentDescriptorSetBuilder debug_assert_eq!(expected_desc, self.binding_id); - let set_layout = self.layout - .descriptor_set_layout(self.set_id) - .expect("Unable to get the descriptor set layout") - .clone(); - let set = unsafe { - let mut set = pool.alloc(&set_layout)?; + let mut set = pool.alloc(&self.layout)?; set.inner_mut() .write(pool.device(), self.writes.into_iter()); set @@ -216,9 +224,7 @@ impl PersistentDescriptorSetBuilder Ok(PersistentDescriptorSet { inner: set, resources: self.resources, - pipeline_layout: self.layout, - set_id: self.set_id, - layout: set_layout, + layout: self.layout, }) } @@ -232,8 +238,8 @@ impl PersistentDescriptorSetBuilder #[inline] pub fn enter_array( self) - -> Result, PersistentDescriptorSetError> { - let desc = match self.layout.descriptor(self.set_id, self.binding_id) { + -> Result, PersistentDescriptorSetError> { + let desc = match self.layout.descriptor(self.binding_id) { Some(d) => d, None => return Err(PersistentDescriptorSetError::EmptyExpected), }; @@ -249,8 +255,8 @@ impl PersistentDescriptorSetBuilder #[inline] pub fn add_empty( mut self) - -> Result, PersistentDescriptorSetError> { - match self.layout.descriptor(self.set_id, self.binding_id) { + -> Result, PersistentDescriptorSetError> { + match self.layout.descriptor(self.binding_id) { None => (), Some(desc) => return Err(PersistentDescriptorSetError::WrongDescriptorTy { expected: desc.ty.ty().unwrap(), @@ -267,12 +273,11 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the buffer doesn't have the same device as the pipeline layout. + /// Panics if the buffer doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_buffer(self, buffer: T) - -> Result Result)>, PersistentDescriptorSetError> where T: BufferAccess @@ -286,10 +291,10 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the buffer view doesn't have the same device as the pipeline layout. + /// Panics if the buffer view doesn't have the same device as the descriptor set layout. /// pub fn add_buffer_view(self, view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferViewRef { self.enter_array()?.add_buffer_view(view)?.leave_array() @@ -301,12 +306,11 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the image view doesn't have the same device as the pipeline layout. + /// Panics if the image view doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_image(self, image_view: T) - -> Result Result)>, PersistentDescriptorSetError> where T: ImageViewAccess @@ -320,11 +324,12 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the image view or the sampler doesn't have the same device as the pipeline layout. + /// Panics if the image view or the sampler doesn't have the same device as the descriptor set + /// layout. /// #[inline] pub fn add_sampled_image(self, image_view: T, sampler: Arc) - -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> + -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> where T: ImageViewAccess { self.enter_array()? @@ -338,12 +343,11 @@ impl PersistentDescriptorSetBuilder /// /// # Panic /// - /// Panics if the sampler doesn't have the same device as the pipeline layout. + /// Panics if the sampler doesn't have the same device as the descriptor set layout. /// #[inline] pub fn add_sampler(self, sampler: Arc) - -> Result Result, PersistentDescriptorSetError> { self.enter_array()?.add_sampler(sampler)?.leave_array() @@ -351,22 +355,21 @@ impl PersistentDescriptorSetBuilder } /// Same as `PersistentDescriptorSetBuilder`, but we're in an array. -pub struct PersistentDescriptorSetBuilderArray { +pub struct PersistentDescriptorSetBuilderArray { // The original builder. - builder: PersistentDescriptorSetBuilder, + builder: PersistentDescriptorSetBuilder, // Current array elements. array_element: usize, // Description of the descriptor. desc: DescriptorDesc, } -impl PersistentDescriptorSetBuilderArray - where L: PipelineLayoutAbstract +impl PersistentDescriptorSetBuilderArray { /// Leaves the array. Call this once you added all the elements of the array. pub fn leave_array( mut self) - -> Result, PersistentDescriptorSetError> { + -> Result, PersistentDescriptorSetError> { if self.desc.array_count > self.array_element as u32 { return Err(PersistentDescriptorSetError::MissingArrayElements { expected: self.desc.array_count, @@ -386,10 +389,10 @@ impl PersistentDescriptorSetBuilderArray /// /// # Panic /// - /// Panics if the buffer doesn't have the same device as the pipeline layout. + /// Panics if the buffer doesn't have the same device as the descriptor set layout. /// pub fn add_buffer(mut self, buffer: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferAccess { assert_eq!(self.builder.layout.device().internal_object(), @@ -450,7 +453,6 @@ impl PersistentDescriptorSetBuilderArray Ok(PersistentDescriptorSetBuilderArray { builder: PersistentDescriptorSetBuilder { layout: self.builder.layout, - set_id: self.builder.set_id, binding_id: self.builder.binding_id, writes: self.builder.writes, resources: (self.builder.resources, @@ -470,10 +472,10 @@ impl PersistentDescriptorSetBuilderArray /// /// # Panic /// - /// Panics if the buffer view doesn't have the same device as the pipeline layout. + /// Panics if the buffer view doesn't have the same device as the descriptor set layout. /// pub fn add_buffer_view(mut self, view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: BufferViewRef { assert_eq!(self.builder.layout.device().internal_object(), @@ -517,7 +519,6 @@ impl PersistentDescriptorSetBuilderArray Ok(PersistentDescriptorSetBuilderArray { builder: PersistentDescriptorSetBuilder { layout: self.builder.layout, - set_id: self.builder.set_id, binding_id: self.builder.binding_id, writes: self.builder.writes, resources: (self.builder.resources, @@ -537,10 +538,10 @@ impl PersistentDescriptorSetBuilderArray /// /// # Panic /// - /// Panics if the image view doesn't have the same device as the pipeline layout. + /// Panics if the image view doesn't have the same device as the descriptor set layout. /// pub fn add_image(mut self, image_view: T) - -> Result)>, PersistentDescriptorSetError> + -> Result)>, PersistentDescriptorSetError> where T: ImageViewAccess { assert_eq!(self.builder.layout.device().internal_object(), @@ -552,7 +553,7 @@ impl PersistentDescriptorSetBuilderArray let desc = match self.builder .layout - .descriptor(self.builder.set_id, self.builder.binding_id) { + .descriptor(self.builder.binding_id) { Some(d) => d, None => return Err(PersistentDescriptorSetError::EmptyExpected), }; @@ -623,7 +624,6 @@ impl PersistentDescriptorSetBuilderArray Ok(PersistentDescriptorSetBuilderArray { builder: PersistentDescriptorSetBuilder { layout: self.builder.layout, - set_id: self.builder.set_id, binding_id: self.builder.binding_id, writes: self.builder.writes, resources: (self.builder.resources, @@ -643,10 +643,10 @@ impl PersistentDescriptorSetBuilderArray /// /// # Panic /// - /// Panics if the image or the sampler doesn't have the same device as the pipeline layout. + /// Panics if the image or the sampler doesn't have the same device as the descriptor set layout. /// pub fn add_sampled_image(mut self, image_view: T, sampler: Arc) - -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> + -> Result), PersistentDescriptorSetSampler)>, PersistentDescriptorSetError> where T: ImageViewAccess { assert_eq!(self.builder.layout.device().internal_object(), @@ -660,7 +660,7 @@ impl PersistentDescriptorSetBuilderArray let desc = match self.builder .layout - .descriptor(self.builder.set_id, self.builder.binding_id) { + .descriptor(self.builder.binding_id) { Some(d) => d, None => return Err(PersistentDescriptorSetError::EmptyExpected), }; @@ -687,7 +687,6 @@ impl PersistentDescriptorSetBuilderArray Ok(PersistentDescriptorSetBuilderArray { builder: PersistentDescriptorSetBuilder { layout: self.builder.layout, - set_id: self.builder.set_id, binding_id: self.builder.binding_id, writes: self.builder.writes, resources: ((self.builder.resources, @@ -708,10 +707,10 @@ impl PersistentDescriptorSetBuilderArray /// /// # Panic /// - /// Panics if the sampler doesn't have the same device as the pipeline layout. + /// Panics if the sampler doesn't have the same device as the descriptor set layout. /// pub fn add_sampler(mut self, sampler: Arc) - -> Result, PersistentDescriptorSetError> + -> Result, PersistentDescriptorSetError> { assert_eq!(self.builder.layout.device().internal_object(), sampler.device().internal_object()); @@ -722,7 +721,7 @@ impl PersistentDescriptorSetBuilderArray let desc = match self.builder .layout - .descriptor(self.builder.set_id, self.builder.binding_id) { + .descriptor(self.builder.binding_id) { Some(d) => d, None => return Err(PersistentDescriptorSetError::EmptyExpected), }; @@ -743,7 +742,6 @@ impl PersistentDescriptorSetBuilderArray Ok(PersistentDescriptorSetBuilderArray { builder: PersistentDescriptorSetBuilder { layout: self.builder.layout, - set_id: self.builder.set_id, binding_id: self.builder.binding_id, writes: self.builder.writes, resources: (self.builder.resources, @@ -821,9 +819,9 @@ fn image_match_desc(image_view: &I, desc: &DescriptorImageDesc) pub unsafe trait PersistentDescriptorSetResources { fn num_buffers(&self) -> usize; - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)>; + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)>; fn num_images(&self) -> usize; - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)>; + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)>; } unsafe impl PersistentDescriptorSetResources for () { @@ -833,7 +831,7 @@ unsafe impl PersistentDescriptorSetResources for () { } #[inline] - fn buffer(&self, _: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, _: usize) -> Option<(&dyn BufferAccess, u32)> { None } @@ -843,7 +841,7 @@ unsafe impl PersistentDescriptorSetResources for () { } #[inline] - fn image(&self, _: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, _: usize) -> Option<(&dyn ImageViewAccess, u32)> { None } } @@ -864,7 +862,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { if let Some(buf) = self.0.buffer(index) { Some(buf) } else if index == self.0.num_buffers() { @@ -880,7 +878,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { self.0.image(index) } } @@ -903,7 +901,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { if let Some(buf) = self.0.buffer(index) { Some(buf) } else if index == self.0.num_buffers() { @@ -919,7 +917,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { self.0.image(index) } } @@ -940,7 +938,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { self.0.buffer(index) } @@ -950,7 +948,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorS } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { if let Some(img) = self.0.image(index) { Some(img) } else if index == self.0.num_images() { @@ -975,7 +973,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorSetS } #[inline] - fn buffer(&self, index: usize) -> Option<(&BufferAccess, u32)> { + fn buffer(&self, index: usize) -> Option<(&dyn BufferAccess, u32)> { self.0.buffer(index) } @@ -985,7 +983,7 @@ unsafe impl PersistentDescriptorSetResources for (R, PersistentDescriptorSetS } #[inline] - fn image(&self, index: usize) -> Option<(&ImageViewAccess, u32)> { + fn image(&self, index: usize) -> Option<(&dyn ImageViewAccess, u32)> { self.0.image(index) } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/std_pool.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/std_pool.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/std_pool.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/std_pool.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/sys.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/sys.rs index d81a863..6da3f7f 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/sys.rs @@ -11,7 +11,7 @@ use smallvec::SmallVec; use std::cmp; use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ops; use std::ptr; use std::sync::Arc; @@ -299,12 +299,12 @@ impl UnsafeDescriptorPool { pPoolSizes: pool_sizes.as_ptr(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateDescriptorPool(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(UnsafeDescriptorPool { @@ -732,7 +732,7 @@ impl UnsafeDescriptorSet { unsafe impl VulkanObject for UnsafeDescriptorSet { type Object = vk::DescriptorSet; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DESCRIPTOR_SET; #[inline] fn internal_object(&self) -> vk::DescriptorSet { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/unsafe_layout.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/unsafe_layout.rs similarity index 87% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/unsafe_layout.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/unsafe_layout.rs index dc23bc5..2c4c8ed 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/descriptor_set/unsafe_layout.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/descriptor_set/unsafe_layout.rs @@ -9,7 +9,7 @@ use smallvec::SmallVec; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -20,6 +20,7 @@ use vk; use descriptor::descriptor::DescriptorDesc; use descriptor::descriptor_set::DescriptorsCount; +use descriptor::descriptor_set::DescriptorSetDesc; use device::Device; use device::DeviceOwned; @@ -33,6 +34,8 @@ pub struct UnsafeDescriptorSetLayout { layout: vk::DescriptorSetLayout, // The device this layout belongs to. device: Arc, + // Descriptors. + descriptors: SmallVec<[Option; 32]>, // Number of descriptors. descriptors_count: DescriptorsCount, } @@ -47,10 +50,11 @@ impl UnsafeDescriptorSetLayout { -> Result where I: IntoIterator> { + let descriptors = descriptors.into_iter().collect::>(); let mut descriptors_count = DescriptorsCount::zero(); let bindings = descriptors - .into_iter() + .iter() .enumerate() .filter_map(|(binding, desc)| { let desc = match desc { @@ -85,18 +89,19 @@ impl UnsafeDescriptorSetLayout { pBindings: bindings.as_ptr(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); let vk = device.pointers(); check_errors(vk.CreateDescriptorSetLayout(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(UnsafeDescriptorSetLayout { layout: layout, device: device, + descriptors: descriptors, descriptors_count: descriptors_count, }) } @@ -108,6 +113,17 @@ impl UnsafeDescriptorSetLayout { } } +unsafe impl DescriptorSetDesc for UnsafeDescriptorSetLayout { + #[inline] + fn num_bindings(&self) -> usize { + self.descriptors.len() + } + #[inline] + fn descriptor(&self, binding: usize) -> Option { + self.descriptors.get(binding).cloned().unwrap_or(None) + } +} + unsafe impl DeviceOwned for UnsafeDescriptorSetLayout { #[inline] fn device(&self) -> &Arc { @@ -127,7 +143,7 @@ impl fmt::Debug for UnsafeDescriptorSetLayout { unsafe impl VulkanObject for UnsafeDescriptorSetLayout { type Object = vk::DescriptorSetLayout; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; #[inline] fn internal_object(&self) -> vk::DescriptorSetLayout { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/mod.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/mod.rs index 10322b4..5304070 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/mod.rs @@ -67,7 +67,7 @@ //! ## Creating a descriptor set //! //! ```ignore -//! // TODO: write example for: PersistentDescriptorSet::start(pipeline.clone(), 0).add_buffer(data_buffer.clone()) +//! // TODO: write example for: PersistentDescriptorSet::start(layout.clone()).add_buffer(data_buffer.clone()) //! ``` //! //! ## Passing the descriptor set when drawing diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/empty.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/empty.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/empty.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/empty.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/limits_check.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/limits_check.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/limits_check.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/limits_check.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/runtime_desc.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/runtime_desc.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/runtime_desc.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/runtime_desc.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/sys.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/sys.rs index 4da6e79..726f03b 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/sys.rs @@ -10,7 +10,7 @@ use smallvec::SmallVec; use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -144,12 +144,12 @@ impl PipelineLayout pPushConstantRanges: push_constants.as_ptr(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreatePipelineLayout(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(PipelineLayout { @@ -253,7 +253,7 @@ pub struct PipelineLayoutSys<'a>(&'a vk::PipelineLayout); unsafe impl<'a> VulkanObject for PipelineLayoutSys<'a> { type Object = vk::PipelineLayout; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE_LAYOUT; #[inline] fn internal_object(&self) -> vk::PipelineLayout { @@ -290,7 +290,7 @@ impl error::Error for PipelineLayoutCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { PipelineLayoutCreationError::OomError(ref err) => Some(err), PipelineLayoutCreationError::LimitsError(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/traits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/traits.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/traits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/traits.rs index d1cdc7a..537c4c0 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/traits.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/traits.rs @@ -255,7 +255,7 @@ impl error::Error for PipelineLayoutNotSupersetError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { PipelineLayoutNotSupersetError::IncompatibleDescriptors { ref error, .. } => { Some(error) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/tweaks.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/tweaks.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/tweaks.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/tweaks.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/union.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/union.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/descriptor/pipeline_layout/union.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/descriptor/pipeline_layout/union.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/device/extensions.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/device/extensions.rs similarity index 85% rename from third_party/cargo/vendor/vulkano-0.11.1/src/device/extensions.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/device/extensions.rs index c05909e..cd4376d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/device/extensions.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/device/extensions.rs @@ -34,12 +34,14 @@ macro_rules! device_extensions { let properties: Vec = unsafe { let mut num = 0; - try!(check_errors(vk.EnumerateDeviceExtensionProperties( - physical_device.internal_object(), ptr::null(), &mut num, ptr::null_mut()))); + check_errors(vk.EnumerateDeviceExtensionProperties( + physical_device.internal_object(), ptr::null(), &mut num, ptr::null_mut() + ))?; let mut properties = Vec::with_capacity(num as usize); - try!(check_errors(vk.EnumerateDeviceExtensionProperties( - physical_device.internal_object(), ptr::null(), &mut num, properties.as_mut_ptr()))); + check_errors(vk.EnumerateDeviceExtensionProperties( + physical_device.internal_object(), ptr::null(), &mut num, properties.as_mut_ptr() + ))?; properties.set_len(num as usize); properties }; @@ -63,12 +65,14 @@ macro_rules! device_extensions { let properties: Vec = unsafe { let mut num = 0; - try!(check_errors(vk.EnumerateDeviceExtensionProperties( - physical_device.internal_object(), ptr::null(), &mut num, ptr::null_mut()))); + check_errors(vk.EnumerateDeviceExtensionProperties( + physical_device.internal_object(), ptr::null(), &mut num, ptr::null_mut() + ))?; let mut properties = Vec::with_capacity(num as usize); - try!(check_errors(vk.EnumerateDeviceExtensionProperties( - physical_device.internal_object(), ptr::null(), &mut num, properties.as_mut_ptr()))); + check_errors(vk.EnumerateDeviceExtensionProperties( + physical_device.internal_object(), ptr::null(), &mut num, properties.as_mut_ptr() + ))?; properties.set_len(num as usize); properties }; @@ -109,7 +113,11 @@ device_extensions! { khr_get_memory_requirements2 => b"VK_KHR_get_memory_requirements2", khr_dedicated_allocation => b"VK_KHR_dedicated_allocation", khr_incremental_present => b"VK_KHR_incremental_present", - ext_debug_marker => b"VK_EXT_debug_marker", + khr_16bit_storage => b"VK_KHR_16bit_storage", + khr_storage_buffer_storage_class => b"VK_KHR_storage_buffer_storage_class", + ext_debug_utils => b"VK_EXT_debug_utils", + khr_multiview => b"VK_KHR_multiview", + ext_full_screen_exclusive => b"VK_EXT_full_screen_exclusive", } /// This helper type can only be instantiated inside this module. diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/device/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/device/mod.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/device/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/device/mod.rs index 876bda2..71e5c46 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/device/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/device/mod.rs @@ -96,7 +96,9 @@ use std::collections::hash_map::Entry; use std::error; use std::fmt; use std::hash::BuildHasherDefault; -use std::mem; +use std::hash::Hash; +use std::hash::Hasher; +use std::mem::MaybeUninit; use std::ops::Deref; use std::ptr; use std::sync::Arc; @@ -286,12 +288,12 @@ impl Device { pEnabledFeatures: &features, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk_i.CreateDevice(phys.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; // loading the function pointers of the newly-created device @@ -300,6 +302,13 @@ impl Device { *const _ }); + let mut active_queue_families: SmallVec<[u32; 8]> = SmallVec::new(); + for (queue_family, _) in output_queues.iter() { + if let None = active_queue_families.iter().find(|&&qf| qf == *queue_family) { + active_queue_families.push(*queue_family); + } + } + let device = Arc::new(Device { instance: phys.instance().clone(), @@ -315,7 +324,7 @@ impl Device { ..requested_features.clone() }, extensions: (&extensions).into(), - active_queue_families: output_queues.iter().map(|&(q, _)| q).collect(), + active_queue_families, allocation_count: Mutex::new(0), fence_pool: Mutex::new(Vec::new()), semaphore_pool: Mutex::new(Vec::new()), @@ -372,7 +381,7 @@ impl Device { // TODO: ^ #[inline] pub fn active_queue_families<'a>(&'a self) - -> Box> + 'a> { + -> Box> + 'a> { let physical_device = self.physical_device(); Box::new(self.active_queue_families .iter() @@ -473,7 +482,6 @@ impl Device { /// Assigns a human-readable name to `object` for debugging purposes. /// /// # Panics - /// * If the `VK_EXT_debug_marker` device extension is not loaded. /// * If `object` is not owned by this device. pub fn set_object_name(&self, object: &T, name: &CStr) -> Result<(), OomError> { assert!(object.device().internal_object() == self.internal_object()); @@ -482,20 +490,17 @@ impl Device { /// Assigns a human-readable name to `object` for debugging purposes. /// - /// # Panics - /// * If the `VK_EXT_debug_marker` device extension is not loaded. - /// /// # Safety /// `object` must be a Vulkan handle owned by this device, and its type must be accurately described by `ty`. - pub unsafe fn set_object_name_raw(&self, ty: vk::DebugReportObjectTypeEXT, object: u64, name: &CStr) -> Result<(), OomError> { - let info = vk::DebugMarkerObjectNameInfoEXT { - sType: vk::STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT, + pub unsafe fn set_object_name_raw(&self, ty: vk::ObjectType, object: u64, name: &CStr) -> Result<(), OomError> { + let info = vk::DebugUtilsObjectNameInfoEXT { + sType: vk::STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT, pNext: ptr::null(), objectType: ty, - object: object, - name: name.as_ptr(), + objectHandle: object, + pObjectName: name.as_ptr(), }; - check_errors(self.vk.DebugMarkerSetObjectNameEXT(self.device, &info))?; + check_errors(self.vk.SetDebugUtilsObjectNameEXT(self.device, &info))?; Ok(()) } } @@ -510,7 +515,7 @@ impl fmt::Debug for Device { unsafe impl VulkanObject for Device { type Object = vk::Device; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DEVICE; #[inline] fn internal_object(&self) -> vk::Device { @@ -536,6 +541,24 @@ impl Drop for Device { } } +impl PartialEq for Device { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.device == other.device && self.instance == other.instance + } +} + +impl Eq for Device {} + +impl Hash for Device { + #[inline] + fn hash(&self, state: &mut H) { + self.device.hash(state); + self.instance.hash(state); + } +} + + /// Implemented on objects that belong to a Vulkan device. /// /// # Safety @@ -582,13 +605,13 @@ impl Iterator for QueuesIter { self.next_queue += 1; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); self.device .vk - .GetDeviceQueue(self.device.device, family, id, &mut output); + .GetDeviceQueue(self.device.device, family, id, output.as_mut_ptr()); Some(Arc::new(Queue { - queue: Mutex::new(output), + queue: Mutex::new(output.assume_init()), device: self.device.clone(), family: family, id: id, @@ -740,6 +763,13 @@ impl Queue { } } +impl PartialEq for Queue { + fn eq(&self, other: &Self) -> bool { + self.is_same(other) + } +} + +impl Eq for Queue { } unsafe impl DeviceOwned for Queue { fn device(&self) -> &Arc { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/extensions.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/extensions.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/extensions.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/extensions.rs index 5b40e15..f27fc34 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/extensions.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/extensions.rs @@ -42,6 +42,17 @@ macro_rules! extensions { } } + /// Returns the union of this list and another list. + #[inline] + pub fn union(&self, other: &$sname) -> $sname { + $sname { + $( + $ext: self.$ext || other.$ext, + )* + _unbuildable: Unbuildable(()) + } + } + /// Returns the intersection of this list and another list. #[inline] pub fn intersection(&self, other: &$sname) -> $sname { @@ -68,15 +79,15 @@ macro_rules! extensions { impl fmt::Debug for $sname { #[allow(unused_assignments)] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "[")); + write!(f, "[")?; let mut first = true; $( if self.$ext { - if !first { try!(write!(f, ", ")); } + if !first { write!(f, ", ")? } else { first = false; } - try!(f.write_str(str::from_utf8($s).unwrap())); + f.write_str(str::from_utf8($s).unwrap())?; } )* @@ -182,7 +193,7 @@ impl error::Error for SupportedExtensionsError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SupportedExtensionsError::LoadingError(ref err) => Some(err), SupportedExtensionsError::OomError(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/features.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/features.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/features.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/features.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/format.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/format.rs similarity index 56% rename from third_party/cargo/vendor/vulkano-0.11.1/src/format.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/format.rs index 5026015..4c5346a 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/format.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/format.rs @@ -174,9 +174,9 @@ pub unsafe trait AcceptsPixels { } macro_rules! formats { - ($($name:ident => $vk:ident [$sz:expr] [$($f_ty:tt)*] {$($d_ty:tt)*},)+) => ( + ($($name:ident => $vk:ident [$bdim:expr] [$sz:expr] [$($f_ty:tt)*] {$($d_ty:tt)*},)+) => ( /// An enumeration of all the possible formats. - #[derive(Copy, Clone, Debug, PartialEq, Eq)] + #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[repr(u32)] #[allow(missing_docs)] #[allow(non_camel_case_types)] @@ -192,8 +192,9 @@ macro_rules! formats { .. other functions .. */ - /// Returns the size in bytes of an element of this format. Returns `None` if the - /// size is irrelevant (for example for compressed formats). + /// Returns the size in bytes of an element of this format. For block based formats + /// this will be the size of a single block. Returns `None` if the + /// size is irrelevant. #[inline] pub fn size(&self) -> Option { match *self { @@ -203,6 +204,17 @@ macro_rules! formats { } } + /// Returns (width, heigh) of the dimensions for block based formats. For + /// non block formats will return (1,1) + #[inline] + pub fn block_dimensions(&self) -> (u32, u32) { + match *self { + $( + Format::$name => $bdim, + )+ + } + } + /// Returns the `Format` corresponding to a Vulkan constant. pub(crate) fn from_vulkan_num(val: u32) -> Option { match val { @@ -420,190 +432,190 @@ macro_rules! formats { } formats! { - R4G4UnormPack8 => FORMAT_R4G4_UNORM_PACK8 [Some(1)] [float=2] {u8}, - R4G4B4A4UnormPack16 => FORMAT_R4G4B4A4_UNORM_PACK16 [Some(2)] [float=4] {u16}, - B4G4R4A4UnormPack16 => FORMAT_B4G4R4A4_UNORM_PACK16 [Some(2)] [float=4] {u16}, - R5G6B5UnormPack16 => FORMAT_R5G6B5_UNORM_PACK16 [Some(2)] [float=3] {u16}, - B5G6R5UnormPack16 => FORMAT_B5G6R5_UNORM_PACK16 [Some(2)] [float=3] {u16}, - R5G5B5A1UnormPack16 => FORMAT_R5G5B5A1_UNORM_PACK16 [Some(2)] [float=4] {u16}, - B5G5R5A1UnormPack16 => FORMAT_B5G5R5A1_UNORM_PACK16 [Some(2)] [float=4] {u16}, - A1R5G5B5UnormPack16 => FORMAT_A1R5G5B5_UNORM_PACK16 [Some(2)] [float=4] {u16}, - R8Unorm => FORMAT_R8_UNORM [Some(1)] [float=1] {u8}, - R8Snorm => FORMAT_R8_SNORM [Some(1)] [float=1] {i8}, - R8Uscaled => FORMAT_R8_USCALED [Some(1)] [float=1] {u8}, - R8Sscaled => FORMAT_R8_SSCALED [Some(1)] [float=1] {i8}, - R8Uint => FORMAT_R8_UINT [Some(1)] [uint=1] {u8}, - R8Sint => FORMAT_R8_SINT [Some(1)] [sint=1] {i8}, - R8Srgb => FORMAT_R8_SRGB [Some(1)] [float=1] {u8}, - R8G8Unorm => FORMAT_R8G8_UNORM [Some(2)] [float=2] {[u8; 2]}, - R8G8Snorm => FORMAT_R8G8_SNORM [Some(2)] [float=2] {[i8; 2]}, - R8G8Uscaled => FORMAT_R8G8_USCALED [Some(2)] [float=2] {[u8; 2]}, - R8G8Sscaled => FORMAT_R8G8_SSCALED [Some(2)] [float=2] {[i8; 2]}, - R8G8Uint => FORMAT_R8G8_UINT [Some(2)] [uint=2] {[u8; 2]}, - R8G8Sint => FORMAT_R8G8_SINT [Some(2)] [sint=2] {[i8; 2]}, - R8G8Srgb => FORMAT_R8G8_SRGB [Some(2)] [float=2] {[u8; 2]}, - R8G8B8Unorm => FORMAT_R8G8B8_UNORM [Some(3)] [float=3] {[u8; 3]}, - R8G8B8Snorm => FORMAT_R8G8B8_SNORM [Some(3)] [float=3] {[i8; 3]}, - R8G8B8Uscaled => FORMAT_R8G8B8_USCALED [Some(3)] [float=3] {[u8; 3]}, - R8G8B8Sscaled => FORMAT_R8G8B8_SSCALED [Some(3)] [float=3] {[i8; 3]}, - R8G8B8Uint => FORMAT_R8G8B8_UINT [Some(3)] [uint=3] {[u8; 3]}, - R8G8B8Sint => FORMAT_R8G8B8_SINT [Some(3)] [sint=3] {[i8; 3]}, - R8G8B8Srgb => FORMAT_R8G8B8_SRGB [Some(3)] [float=3] {[u8; 3]}, - B8G8R8Unorm => FORMAT_B8G8R8_UNORM [Some(3)] [float=3] {[u8; 3]}, - B8G8R8Snorm => FORMAT_B8G8R8_SNORM [Some(3)] [float=3] {[i8; 3]}, - B8G8R8Uscaled => FORMAT_B8G8R8_USCALED [Some(3)] [float=3] {[u8; 3]}, - B8G8R8Sscaled => FORMAT_B8G8R8_SSCALED [Some(3)] [float=3] {[i8; 3]}, - B8G8R8Uint => FORMAT_B8G8R8_UINT [Some(3)] [uint=3] {[u8; 3]}, - B8G8R8Sint => FORMAT_B8G8R8_SINT [Some(3)] [sint=3] {[i8; 3]}, - B8G8R8Srgb => FORMAT_B8G8R8_SRGB [Some(3)] [float=3] {[u8; 3]}, - R8G8B8A8Unorm => FORMAT_R8G8B8A8_UNORM [Some(4)] [float=4] {[u8; 4]}, - R8G8B8A8Snorm => FORMAT_R8G8B8A8_SNORM [Some(4)] [float=4] {[i8; 4]}, - R8G8B8A8Uscaled => FORMAT_R8G8B8A8_USCALED [Some(4)] [float=4] {[u8; 4]}, - R8G8B8A8Sscaled => FORMAT_R8G8B8A8_SSCALED [Some(4)] [float=4] {[i8; 4]}, - R8G8B8A8Uint => FORMAT_R8G8B8A8_UINT [Some(4)] [uint=4] {[u8; 4]}, - R8G8B8A8Sint => FORMAT_R8G8B8A8_SINT [Some(4)] [sint=4] {[i8; 4]}, - R8G8B8A8Srgb => FORMAT_R8G8B8A8_SRGB [Some(4)] [float=4] {[u8; 4]}, - B8G8R8A8Unorm => FORMAT_B8G8R8A8_UNORM [Some(4)] [float=4] {[u8; 4]}, - B8G8R8A8Snorm => FORMAT_B8G8R8A8_SNORM [Some(4)] [float=4] {[i8; 4]}, - B8G8R8A8Uscaled => FORMAT_B8G8R8A8_USCALED [Some(4)] [float=4] {[u8; 4]}, - B8G8R8A8Sscaled => FORMAT_B8G8R8A8_SSCALED [Some(4)] [float=4] {[i8; 4]}, - B8G8R8A8Uint => FORMAT_B8G8R8A8_UINT [Some(4)] [uint=4] {[u8; 4]}, - B8G8R8A8Sint => FORMAT_B8G8R8A8_SINT [Some(4)] [sint=4] {[i8; 4]}, - B8G8R8A8Srgb => FORMAT_B8G8R8A8_SRGB [Some(4)] [float=4] {[u8; 4]}, - A8B8G8R8UnormPack32 => FORMAT_A8B8G8R8_UNORM_PACK32 [Some(4)] [float=4] {[u8; 4]}, - A8B8G8R8SnormPack32 => FORMAT_A8B8G8R8_SNORM_PACK32 [Some(4)] [float=4] {[i8; 4]}, - A8B8G8R8UscaledPack32 => FORMAT_A8B8G8R8_USCALED_PACK32 [Some(4)] [float=4] {[u8; 4]}, - A8B8G8R8SscaledPack32 => FORMAT_A8B8G8R8_SSCALED_PACK32 [Some(4)] [float=4] {[i8; 4]}, - A8B8G8R8UintPack32 => FORMAT_A8B8G8R8_UINT_PACK32 [Some(4)] [uint=4] {[u8; 4]}, - A8B8G8R8SintPack32 => FORMAT_A8B8G8R8_SINT_PACK32 [Some(4)] [sint=4] {[i8; 4]}, - A8B8G8R8SrgbPack32 => FORMAT_A8B8G8R8_SRGB_PACK32 [Some(4)] [float=4] {[u8; 4]}, - A2R10G10B10UnormPack32 => FORMAT_A2R10G10B10_UNORM_PACK32 [Some(4)] [float=4] {u32}, - A2R10G10B10SnormPack32 => FORMAT_A2R10G10B10_SNORM_PACK32 [Some(4)] [float=4] {u32}, - A2R10G10B10UscaledPack32 => FORMAT_A2R10G10B10_USCALED_PACK32 [Some(4)] [float=4] {u32}, - A2R10G10B10SscaledPack32 => FORMAT_A2R10G10B10_SSCALED_PACK32 [Some(4)] [float=4] {u32}, - A2R10G10B10UintPack32 => FORMAT_A2R10G10B10_UINT_PACK32 [Some(4)] [uint=4] {u32}, - A2R10G10B10SintPack32 => FORMAT_A2R10G10B10_SINT_PACK32 [Some(4)] [sint=4] {u32}, - A2B10G10R10UnormPack32 => FORMAT_A2B10G10R10_UNORM_PACK32 [Some(4)] [float=4] {u32}, - A2B10G10R10SnormPack32 => FORMAT_A2B10G10R10_SNORM_PACK32 [Some(4)] [float=4] {u32}, - A2B10G10R10UscaledPack32 => FORMAT_A2B10G10R10_USCALED_PACK32 [Some(4)] [float=4] {u32}, - A2B10G10R10SscaledPack32 => FORMAT_A2B10G10R10_SSCALED_PACK32 [Some(4)] [float=4] {u32}, - A2B10G10R10UintPack32 => FORMAT_A2B10G10R10_UINT_PACK32 [Some(4)] [uint=4] {u32}, - A2B10G10R10SintPack32 => FORMAT_A2B10G10R10_SINT_PACK32 [Some(4)] [sint=4] {u32}, - R16Unorm => FORMAT_R16_UNORM [Some(2)] [float=1] {u16}, - R16Snorm => FORMAT_R16_SNORM [Some(2)] [float=1] {i16}, - R16Uscaled => FORMAT_R16_USCALED [Some(2)] [float=1] {u16}, - R16Sscaled => FORMAT_R16_SSCALED [Some(2)] [float=1] {i16}, - R16Uint => FORMAT_R16_UINT [Some(2)] [uint=1] {u16}, - R16Sint => FORMAT_R16_SINT [Some(2)] [sint=1] {i16}, - R16Sfloat => FORMAT_R16_SFLOAT [Some(2)] [float=1] {f16}, - R16G16Unorm => FORMAT_R16G16_UNORM [Some(4)] [float=2] {[u16; 2]}, - R16G16Snorm => FORMAT_R16G16_SNORM [Some(4)] [float=2] {[i16; 2]}, - R16G16Uscaled => FORMAT_R16G16_USCALED [Some(4)] [float=2] {[u16; 2]}, - R16G16Sscaled => FORMAT_R16G16_SSCALED [Some(4)] [float=2] {[i16; 2]}, - R16G16Uint => FORMAT_R16G16_UINT [Some(4)] [uint=2] {[u16; 2]}, - R16G16Sint => FORMAT_R16G16_SINT [Some(4)] [sint=2] {[i16; 2]}, - R16G16Sfloat => FORMAT_R16G16_SFLOAT [Some(4)] [float=2] {[f16; 2]}, - R16G16B16Unorm => FORMAT_R16G16B16_UNORM [Some(6)] [float=3] {[u16; 3]}, - R16G16B16Snorm => FORMAT_R16G16B16_SNORM [Some(6)] [float=3] {[i16; 3]}, - R16G16B16Uscaled => FORMAT_R16G16B16_USCALED [Some(6)] [float=3] {[u16; 3]}, - R16G16B16Sscaled => FORMAT_R16G16B16_SSCALED [Some(6)] [float=3] {[i16; 3]}, - R16G16B16Uint => FORMAT_R16G16B16_UINT [Some(6)] [uint=3] {[u16; 3]}, - R16G16B16Sint => FORMAT_R16G16B16_SINT [Some(6)] [sint=3] {[i16; 3]}, - R16G16B16Sfloat => FORMAT_R16G16B16_SFLOAT [Some(6)] [float=3] {[f16; 3]}, - R16G16B16A16Unorm => FORMAT_R16G16B16A16_UNORM [Some(8)] [float=4] {[u16; 4]}, - R16G16B16A16Snorm => FORMAT_R16G16B16A16_SNORM [Some(8)] [float=4] {[i16; 4]}, - R16G16B16A16Uscaled => FORMAT_R16G16B16A16_USCALED [Some(8)] [float=4] {[u16; 4]}, - R16G16B16A16Sscaled => FORMAT_R16G16B16A16_SSCALED [Some(8)] [float=4] {[i16; 4]}, - R16G16B16A16Uint => FORMAT_R16G16B16A16_UINT [Some(8)] [uint=4] {[u16; 4]}, - R16G16B16A16Sint => FORMAT_R16G16B16A16_SINT [Some(8)] [sint=4] {[i16; 4]}, - R16G16B16A16Sfloat => FORMAT_R16G16B16A16_SFLOAT [Some(8)] [float=4] {[f16; 4]}, - R32Uint => FORMAT_R32_UINT [Some(4)] [uint=1] {u32}, - R32Sint => FORMAT_R32_SINT [Some(4)] [sint=1] {i32}, - R32Sfloat => FORMAT_R32_SFLOAT [Some(4)] [float=1] {f32}, - R32G32Uint => FORMAT_R32G32_UINT [Some(8)] [uint=2] {[u32; 2]}, - R32G32Sint => FORMAT_R32G32_SINT [Some(8)] [sint=2] {[i32; 2]}, - R32G32Sfloat => FORMAT_R32G32_SFLOAT [Some(8)] [float=2] {[f32; 2]}, - R32G32B32Uint => FORMAT_R32G32B32_UINT [Some(12)] [uint=3] {[u32; 3]}, - R32G32B32Sint => FORMAT_R32G32B32_SINT [Some(12)] [sint=3] {[i32; 3]}, - R32G32B32Sfloat => FORMAT_R32G32B32_SFLOAT [Some(12)] [float=3] {[f32; 3]}, - R32G32B32A32Uint => FORMAT_R32G32B32A32_UINT [Some(16)] [uint=4] {[u32; 4]}, - R32G32B32A32Sint => FORMAT_R32G32B32A32_SINT [Some(16)] [sint=4] {[i32; 4]}, - R32G32B32A32Sfloat => FORMAT_R32G32B32A32_SFLOAT [Some(16)] [float=4] {[f32; 4]}, - R64Uint => FORMAT_R64_UINT [Some(8)] [uint=1] {u64}, - R64Sint => FORMAT_R64_SINT [Some(8)] [sint=1] {i64}, - R64Sfloat => FORMAT_R64_SFLOAT [Some(8)] [float=1] {f64}, - R64G64Uint => FORMAT_R64G64_UINT [Some(16)] [uint=2] {[u64; 2]}, - R64G64Sint => FORMAT_R64G64_SINT [Some(16)] [sint=2] {[i64; 2]}, - R64G64Sfloat => FORMAT_R64G64_SFLOAT [Some(16)] [float=2] {[f64; 2]}, - R64G64B64Uint => FORMAT_R64G64B64_UINT [Some(24)] [uint=3] {[u64; 3]}, - R64G64B64Sint => FORMAT_R64G64B64_SINT [Some(24)] [sint=3] {[i64; 3]}, - R64G64B64Sfloat => FORMAT_R64G64B64_SFLOAT [Some(24)] [float=3] {[f64; 3]}, - R64G64B64A64Uint => FORMAT_R64G64B64A64_UINT [Some(32)] [uint=4] {[u64; 4]}, - R64G64B64A64Sint => FORMAT_R64G64B64A64_SINT [Some(32)] [sint=4] {[i64; 4]}, - R64G64B64A64Sfloat => FORMAT_R64G64B64A64_SFLOAT [Some(32)] [float=4] {[f64; 4]}, - B10G11R11UfloatPack32 => FORMAT_B10G11R11_UFLOAT_PACK32 [Some(4)] [float=3] {u32}, - E5B9G9R9UfloatPack32 => FORMAT_E5B9G9R9_UFLOAT_PACK32 [Some(4)] [float=3] {u32}, - D16Unorm => FORMAT_D16_UNORM [Some(2)] [depth] {}, - X8_D24UnormPack32 => FORMAT_X8_D24_UNORM_PACK32 [Some(4)] [depth] {}, - D32Sfloat => FORMAT_D32_SFLOAT [Some(4)] [depth] {}, - S8Uint => FORMAT_S8_UINT [Some(1)] [stencil] {}, - D16Unorm_S8Uint => FORMAT_D16_UNORM_S8_UINT [None] [depthstencil] {}, - D24Unorm_S8Uint => FORMAT_D24_UNORM_S8_UINT [None] [depthstencil] {}, - D32Sfloat_S8Uint => FORMAT_D32_SFLOAT_S8_UINT [None] [depthstencil] {}, - BC1_RGBUnormBlock => FORMAT_BC1_RGB_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC1_RGBSrgbBlock => FORMAT_BC1_RGB_SRGB_BLOCK [None] [compressed=texture_compression_bc] {}, - BC1_RGBAUnormBlock => FORMAT_BC1_RGBA_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC1_RGBASrgbBlock => FORMAT_BC1_RGBA_SRGB_BLOCK [None] [compressed=texture_compression_bc] {}, - BC2UnormBlock => FORMAT_BC2_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC2SrgbBlock => FORMAT_BC2_SRGB_BLOCK [None] [compressed=texture_compression_bc] {}, - BC3UnormBlock => FORMAT_BC3_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC3SrgbBlock => FORMAT_BC3_SRGB_BLOCK [None] [compressed=texture_compression_bc] {}, - BC4UnormBlock => FORMAT_BC4_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC4SnormBlock => FORMAT_BC4_SNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC5UnormBlock => FORMAT_BC5_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC5SnormBlock => FORMAT_BC5_SNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC6HUfloatBlock => FORMAT_BC6H_UFLOAT_BLOCK [None] [compressed=texture_compression_bc] {}, - BC6HSfloatBlock => FORMAT_BC6H_SFLOAT_BLOCK [None] [compressed=texture_compression_bc] {}, - BC7UnormBlock => FORMAT_BC7_UNORM_BLOCK [None] [compressed=texture_compression_bc] {}, - BC7SrgbBlock => FORMAT_BC7_SRGB_BLOCK [None] [compressed=texture_compression_bc] {}, - ETC2_R8G8B8UnormBlock => FORMAT_ETC2_R8G8B8_UNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - ETC2_R8G8B8SrgbBlock => FORMAT_ETC2_R8G8B8_SRGB_BLOCK [None] [compressed=texture_compression_etc2] {}, - ETC2_R8G8B8A1UnormBlock => FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - ETC2_R8G8B8A1SrgbBlock => FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK [None] [compressed=texture_compression_etc2] {}, - ETC2_R8G8B8A8UnormBlock => FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - ETC2_R8G8B8A8SrgbBlock => FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK [None] [compressed=texture_compression_etc2] {}, - EAC_R11UnormBlock => FORMAT_EAC_R11_UNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - EAC_R11SnormBlock => FORMAT_EAC_R11_SNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - EAC_R11G11UnormBlock => FORMAT_EAC_R11G11_UNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - EAC_R11G11SnormBlock => FORMAT_EAC_R11G11_SNORM_BLOCK [None] [compressed=texture_compression_etc2] {}, - ASTC_4x4UnormBlock => FORMAT_ASTC_4x4_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_4x4SrgbBlock => FORMAT_ASTC_4x4_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_5x4UnormBlock => FORMAT_ASTC_5x4_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_5x4SrgbBlock => FORMAT_ASTC_5x4_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_5x5UnormBlock => FORMAT_ASTC_5x5_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_5x5SrgbBlock => FORMAT_ASTC_5x5_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_6x5UnormBlock => FORMAT_ASTC_6x5_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_6x5SrgbBlock => FORMAT_ASTC_6x5_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_6x6UnormBlock => FORMAT_ASTC_6x6_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_6x6SrgbBlock => FORMAT_ASTC_6x6_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x5UnormBlock => FORMAT_ASTC_8x5_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x5SrgbBlock => FORMAT_ASTC_8x5_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x6UnormBlock => FORMAT_ASTC_8x6_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x6SrgbBlock => FORMAT_ASTC_8x6_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x8UnormBlock => FORMAT_ASTC_8x8_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_8x8SrgbBlock => FORMAT_ASTC_8x8_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x5UnormBlock => FORMAT_ASTC_10x5_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x5SrgbBlock => FORMAT_ASTC_10x5_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x6UnormBlock => FORMAT_ASTC_10x6_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x6SrgbBlock => FORMAT_ASTC_10x6_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x8UnormBlock => FORMAT_ASTC_10x8_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x8SrgbBlock => FORMAT_ASTC_10x8_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x10UnormBlock => FORMAT_ASTC_10x10_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_10x10SrgbBlock => FORMAT_ASTC_10x10_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_12x10UnormBlock => FORMAT_ASTC_12x10_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_12x10SrgbBlock => FORMAT_ASTC_12x10_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_12x12UnormBlock => FORMAT_ASTC_12x12_UNORM_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, - ASTC_12x12SrgbBlock => FORMAT_ASTC_12x12_SRGB_BLOCK [None] [compressed=texture_compression_astc_ldr] {}, + R4G4UnormPack8 => FORMAT_R4G4_UNORM_PACK8 [(1, 1)] [Some(1)] [float=2] {u8}, + R4G4B4A4UnormPack16 => FORMAT_R4G4B4A4_UNORM_PACK16 [(1, 1)] [Some(2)] [float=4] {u16}, + B4G4R4A4UnormPack16 => FORMAT_B4G4R4A4_UNORM_PACK16 [(1, 1)] [Some(2)] [float=4] {u16}, + R5G6B5UnormPack16 => FORMAT_R5G6B5_UNORM_PACK16 [(1, 1)] [Some(2)] [float=3] {u16}, + B5G6R5UnormPack16 => FORMAT_B5G6R5_UNORM_PACK16 [(1, 1)] [Some(2)] [float=3] {u16}, + R5G5B5A1UnormPack16 => FORMAT_R5G5B5A1_UNORM_PACK16 [(1, 1)] [Some(2)] [float=4] {u16}, + B5G5R5A1UnormPack16 => FORMAT_B5G5R5A1_UNORM_PACK16 [(1, 1)] [Some(2)] [float=4] {u16}, + A1R5G5B5UnormPack16 => FORMAT_A1R5G5B5_UNORM_PACK16 [(1, 1)] [Some(2)] [float=4] {u16}, + R8Unorm => FORMAT_R8_UNORM [(1, 1)] [Some(1)] [float=1] {u8}, + R8Snorm => FORMAT_R8_SNORM [(1, 1)] [Some(1)] [float=1] {i8}, + R8Uscaled => FORMAT_R8_USCALED [(1, 1)] [Some(1)] [float=1] {u8}, + R8Sscaled => FORMAT_R8_SSCALED [(1, 1)] [Some(1)] [float=1] {i8}, + R8Uint => FORMAT_R8_UINT [(1, 1)] [Some(1)] [uint=1] {u8}, + R8Sint => FORMAT_R8_SINT [(1, 1)] [Some(1)] [sint=1] {i8}, + R8Srgb => FORMAT_R8_SRGB [(1, 1)] [Some(1)] [float=1] {u8}, + R8G8Unorm => FORMAT_R8G8_UNORM [(1, 1)] [Some(2)] [float=2] {[u8; 2]}, + R8G8Snorm => FORMAT_R8G8_SNORM [(1, 1)] [Some(2)] [float=2] {[i8; 2]}, + R8G8Uscaled => FORMAT_R8G8_USCALED [(1, 1)] [Some(2)] [float=2] {[u8; 2]}, + R8G8Sscaled => FORMAT_R8G8_SSCALED [(1, 1)] [Some(2)] [float=2] {[i8; 2]}, + R8G8Uint => FORMAT_R8G8_UINT [(1, 1)] [Some(2)] [uint=2] {[u8; 2]}, + R8G8Sint => FORMAT_R8G8_SINT [(1, 1)] [Some(2)] [sint=2] {[i8; 2]}, + R8G8Srgb => FORMAT_R8G8_SRGB [(1, 1)] [Some(2)] [float=2] {[u8; 2]}, + R8G8B8Unorm => FORMAT_R8G8B8_UNORM [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + R8G8B8Snorm => FORMAT_R8G8B8_SNORM [(1, 1)] [Some(3)] [float=3] {[i8; 3]}, + R8G8B8Uscaled => FORMAT_R8G8B8_USCALED [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + R8G8B8Sscaled => FORMAT_R8G8B8_SSCALED [(1, 1)] [Some(3)] [float=3] {[i8; 3]}, + R8G8B8Uint => FORMAT_R8G8B8_UINT [(1, 1)] [Some(3)] [uint=3] {[u8; 3]}, + R8G8B8Sint => FORMAT_R8G8B8_SINT [(1, 1)] [Some(3)] [sint=3] {[i8; 3]}, + R8G8B8Srgb => FORMAT_R8G8B8_SRGB [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + B8G8R8Unorm => FORMAT_B8G8R8_UNORM [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + B8G8R8Snorm => FORMAT_B8G8R8_SNORM [(1, 1)] [Some(3)] [float=3] {[i8; 3]}, + B8G8R8Uscaled => FORMAT_B8G8R8_USCALED [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + B8G8R8Sscaled => FORMAT_B8G8R8_SSCALED [(1, 1)] [Some(3)] [float=3] {[i8; 3]}, + B8G8R8Uint => FORMAT_B8G8R8_UINT [(1, 1)] [Some(3)] [uint=3] {[u8; 3]}, + B8G8R8Sint => FORMAT_B8G8R8_SINT [(1, 1)] [Some(3)] [sint=3] {[i8; 3]}, + B8G8R8Srgb => FORMAT_B8G8R8_SRGB [(1, 1)] [Some(3)] [float=3] {[u8; 3]}, + R8G8B8A8Unorm => FORMAT_R8G8B8A8_UNORM [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + R8G8B8A8Snorm => FORMAT_R8G8B8A8_SNORM [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + R8G8B8A8Uscaled => FORMAT_R8G8B8A8_USCALED [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + R8G8B8A8Sscaled => FORMAT_R8G8B8A8_SSCALED [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + R8G8B8A8Uint => FORMAT_R8G8B8A8_UINT [(1, 1)] [Some(4)] [uint=4] {[u8; 4]}, + R8G8B8A8Sint => FORMAT_R8G8B8A8_SINT [(1, 1)] [Some(4)] [sint=4] {[i8; 4]}, + R8G8B8A8Srgb => FORMAT_R8G8B8A8_SRGB [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + B8G8R8A8Unorm => FORMAT_B8G8R8A8_UNORM [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + B8G8R8A8Snorm => FORMAT_B8G8R8A8_SNORM [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + B8G8R8A8Uscaled => FORMAT_B8G8R8A8_USCALED [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + B8G8R8A8Sscaled => FORMAT_B8G8R8A8_SSCALED [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + B8G8R8A8Uint => FORMAT_B8G8R8A8_UINT [(1, 1)] [Some(4)] [uint=4] {[u8; 4]}, + B8G8R8A8Sint => FORMAT_B8G8R8A8_SINT [(1, 1)] [Some(4)] [sint=4] {[i8; 4]}, + B8G8R8A8Srgb => FORMAT_B8G8R8A8_SRGB [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + A8B8G8R8UnormPack32 => FORMAT_A8B8G8R8_UNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + A8B8G8R8SnormPack32 => FORMAT_A8B8G8R8_SNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + A8B8G8R8UscaledPack32 => FORMAT_A8B8G8R8_USCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + A8B8G8R8SscaledPack32 => FORMAT_A8B8G8R8_SSCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {[i8; 4]}, + A8B8G8R8UintPack32 => FORMAT_A8B8G8R8_UINT_PACK32 [(1, 1)] [Some(4)] [uint=4] {[u8; 4]}, + A8B8G8R8SintPack32 => FORMAT_A8B8G8R8_SINT_PACK32 [(1, 1)] [Some(4)] [sint=4] {[i8; 4]}, + A8B8G8R8SrgbPack32 => FORMAT_A8B8G8R8_SRGB_PACK32 [(1, 1)] [Some(4)] [float=4] {[u8; 4]}, + A2R10G10B10UnormPack32 => FORMAT_A2R10G10B10_UNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2R10G10B10SnormPack32 => FORMAT_A2R10G10B10_SNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2R10G10B10UscaledPack32 => FORMAT_A2R10G10B10_USCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2R10G10B10SscaledPack32 => FORMAT_A2R10G10B10_SSCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2R10G10B10UintPack32 => FORMAT_A2R10G10B10_UINT_PACK32 [(1, 1)] [Some(4)] [uint=4] {u32}, + A2R10G10B10SintPack32 => FORMAT_A2R10G10B10_SINT_PACK32 [(1, 1)] [Some(4)] [sint=4] {u32}, + A2B10G10R10UnormPack32 => FORMAT_A2B10G10R10_UNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2B10G10R10SnormPack32 => FORMAT_A2B10G10R10_SNORM_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2B10G10R10UscaledPack32 => FORMAT_A2B10G10R10_USCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2B10G10R10SscaledPack32 => FORMAT_A2B10G10R10_SSCALED_PACK32 [(1, 1)] [Some(4)] [float=4] {u32}, + A2B10G10R10UintPack32 => FORMAT_A2B10G10R10_UINT_PACK32 [(1, 1)] [Some(4)] [uint=4] {u32}, + A2B10G10R10SintPack32 => FORMAT_A2B10G10R10_SINT_PACK32 [(1, 1)] [Some(4)] [sint=4] {u32}, + R16Unorm => FORMAT_R16_UNORM [(1, 1)] [Some(2)] [float=1] {u16}, + R16Snorm => FORMAT_R16_SNORM [(1, 1)] [Some(2)] [float=1] {i16}, + R16Uscaled => FORMAT_R16_USCALED [(1, 1)] [Some(2)] [float=1] {u16}, + R16Sscaled => FORMAT_R16_SSCALED [(1, 1)] [Some(2)] [float=1] {i16}, + R16Uint => FORMAT_R16_UINT [(1, 1)] [Some(2)] [uint=1] {u16}, + R16Sint => FORMAT_R16_SINT [(1, 1)] [Some(2)] [sint=1] {i16}, + R16Sfloat => FORMAT_R16_SFLOAT [(1, 1)] [Some(2)] [float=1] {f16}, + R16G16Unorm => FORMAT_R16G16_UNORM [(1, 1)] [Some(4)] [float=2] {[u16; 2]}, + R16G16Snorm => FORMAT_R16G16_SNORM [(1, 1)] [Some(4)] [float=2] {[i16; 2]}, + R16G16Uscaled => FORMAT_R16G16_USCALED [(1, 1)] [Some(4)] [float=2] {[u16; 2]}, + R16G16Sscaled => FORMAT_R16G16_SSCALED [(1, 1)] [Some(4)] [float=2] {[i16; 2]}, + R16G16Uint => FORMAT_R16G16_UINT [(1, 1)] [Some(4)] [uint=2] {[u16; 2]}, + R16G16Sint => FORMAT_R16G16_SINT [(1, 1)] [Some(4)] [sint=2] {[i16; 2]}, + R16G16Sfloat => FORMAT_R16G16_SFLOAT [(1, 1)] [Some(4)] [float=2] {[f16; 2]}, + R16G16B16Unorm => FORMAT_R16G16B16_UNORM [(1, 1)] [Some(6)] [float=3] {[u16; 3]}, + R16G16B16Snorm => FORMAT_R16G16B16_SNORM [(1, 1)] [Some(6)] [float=3] {[i16; 3]}, + R16G16B16Uscaled => FORMAT_R16G16B16_USCALED [(1, 1)] [Some(6)] [float=3] {[u16; 3]}, + R16G16B16Sscaled => FORMAT_R16G16B16_SSCALED [(1, 1)] [Some(6)] [float=3] {[i16; 3]}, + R16G16B16Uint => FORMAT_R16G16B16_UINT [(1, 1)] [Some(6)] [uint=3] {[u16; 3]}, + R16G16B16Sint => FORMAT_R16G16B16_SINT [(1, 1)] [Some(6)] [sint=3] {[i16; 3]}, + R16G16B16Sfloat => FORMAT_R16G16B16_SFLOAT [(1, 1)] [Some(6)] [float=3] {[f16; 3]}, + R16G16B16A16Unorm => FORMAT_R16G16B16A16_UNORM [(1, 1)] [Some(8)] [float=4] {[u16; 4]}, + R16G16B16A16Snorm => FORMAT_R16G16B16A16_SNORM [(1, 1)] [Some(8)] [float=4] {[i16; 4]}, + R16G16B16A16Uscaled => FORMAT_R16G16B16A16_USCALED [(1, 1)] [Some(8)] [float=4] {[u16; 4]}, + R16G16B16A16Sscaled => FORMAT_R16G16B16A16_SSCALED [(1, 1)] [Some(8)] [float=4] {[i16; 4]}, + R16G16B16A16Uint => FORMAT_R16G16B16A16_UINT [(1, 1)] [Some(8)] [uint=4] {[u16; 4]}, + R16G16B16A16Sint => FORMAT_R16G16B16A16_SINT [(1, 1)] [Some(8)] [sint=4] {[i16; 4]}, + R16G16B16A16Sfloat => FORMAT_R16G16B16A16_SFLOAT [(1, 1)] [Some(8)] [float=4] {[f16; 4]}, + R32Uint => FORMAT_R32_UINT [(1, 1)] [Some(4)] [uint=1] {u32}, + R32Sint => FORMAT_R32_SINT [(1, 1)] [Some(4)] [sint=1] {i32}, + R32Sfloat => FORMAT_R32_SFLOAT [(1, 1)] [Some(4)] [float=1] {f32}, + R32G32Uint => FORMAT_R32G32_UINT [(1, 1)] [Some(8)] [uint=2] {[u32; 2]}, + R32G32Sint => FORMAT_R32G32_SINT [(1, 1)] [Some(8)] [sint=2] {[i32; 2]}, + R32G32Sfloat => FORMAT_R32G32_SFLOAT [(1, 1)] [Some(8)] [float=2] {[f32; 2]}, + R32G32B32Uint => FORMAT_R32G32B32_UINT [(1, 1)] [Some(12)] [uint=3] {[u32; 3]}, + R32G32B32Sint => FORMAT_R32G32B32_SINT [(1, 1)] [Some(12)] [sint=3] {[i32; 3]}, + R32G32B32Sfloat => FORMAT_R32G32B32_SFLOAT [(1, 1)] [Some(12)] [float=3] {[f32; 3]}, + R32G32B32A32Uint => FORMAT_R32G32B32A32_UINT [(1, 1)] [Some(16)] [uint=4] {[u32; 4]}, + R32G32B32A32Sint => FORMAT_R32G32B32A32_SINT [(1, 1)] [Some(16)] [sint=4] {[i32; 4]}, + R32G32B32A32Sfloat => FORMAT_R32G32B32A32_SFLOAT [(1, 1)] [Some(16)] [float=4] {[f32; 4]}, + R64Uint => FORMAT_R64_UINT [(1, 1)] [Some(8)] [uint=1] {u64}, + R64Sint => FORMAT_R64_SINT [(1, 1)] [Some(8)] [sint=1] {i64}, + R64Sfloat => FORMAT_R64_SFLOAT [(1, 1)] [Some(8)] [float=1] {f64}, + R64G64Uint => FORMAT_R64G64_UINT [(1, 1)] [Some(16)] [uint=2] {[u64; 2]}, + R64G64Sint => FORMAT_R64G64_SINT [(1, 1)] [Some(16)] [sint=2] {[i64; 2]}, + R64G64Sfloat => FORMAT_R64G64_SFLOAT [(1, 1)] [Some(16)] [float=2] {[f64; 2]}, + R64G64B64Uint => FORMAT_R64G64B64_UINT [(1, 1)] [Some(24)] [uint=3] {[u64; 3]}, + R64G64B64Sint => FORMAT_R64G64B64_SINT [(1, 1)] [Some(24)] [sint=3] {[i64; 3]}, + R64G64B64Sfloat => FORMAT_R64G64B64_SFLOAT [(1, 1)] [Some(24)] [float=3] {[f64; 3]}, + R64G64B64A64Uint => FORMAT_R64G64B64A64_UINT [(1, 1)] [Some(32)] [uint=4] {[u64; 4]}, + R64G64B64A64Sint => FORMAT_R64G64B64A64_SINT [(1, 1)] [Some(32)] [sint=4] {[i64; 4]}, + R64G64B64A64Sfloat => FORMAT_R64G64B64A64_SFLOAT [(1, 1)] [Some(32)] [float=4] {[f64; 4]}, + B10G11R11UfloatPack32 => FORMAT_B10G11R11_UFLOAT_PACK32 [(1, 1)] [Some(4)] [float=3] {u32}, + E5B9G9R9UfloatPack32 => FORMAT_E5B9G9R9_UFLOAT_PACK32 [(1, 1)] [Some(4)] [float=3] {u32}, + D16Unorm => FORMAT_D16_UNORM [(1, 1)] [Some(2)] [depth] {}, + X8_D24UnormPack32 => FORMAT_X8_D24_UNORM_PACK32 [(1, 1)] [Some(4)] [depth] {}, + D32Sfloat => FORMAT_D32_SFLOAT [(1, 1)] [Some(4)] [depth] {}, + S8Uint => FORMAT_S8_UINT [(1, 1)] [Some(1)] [stencil] {}, + D16Unorm_S8Uint => FORMAT_D16_UNORM_S8_UINT [(1, 1)] [None] [depthstencil] {}, + D24Unorm_S8Uint => FORMAT_D24_UNORM_S8_UINT [(1, 1)] [None] [depthstencil] {}, + D32Sfloat_S8Uint => FORMAT_D32_SFLOAT_S8_UINT [(1, 1)] [None] [depthstencil] {}, + BC1_RGBUnormBlock => FORMAT_BC1_RGB_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC1_RGBSrgbBlock => FORMAT_BC1_RGB_SRGB_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC1_RGBAUnormBlock => FORMAT_BC1_RGBA_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC1_RGBASrgbBlock => FORMAT_BC1_RGBA_SRGB_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC2UnormBlock => FORMAT_BC2_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC2SrgbBlock => FORMAT_BC2_SRGB_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC3UnormBlock => FORMAT_BC3_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC3SrgbBlock => FORMAT_BC3_SRGB_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC4UnormBlock => FORMAT_BC4_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC4SnormBlock => FORMAT_BC4_SNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_bc] {u8}, + BC5UnormBlock => FORMAT_BC5_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC5SnormBlock => FORMAT_BC5_SNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC6HUfloatBlock => FORMAT_BC6H_UFLOAT_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC6HSfloatBlock => FORMAT_BC6H_SFLOAT_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC7UnormBlock => FORMAT_BC7_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + BC7SrgbBlock => FORMAT_BC7_SRGB_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_bc] {u8}, + ETC2_R8G8B8UnormBlock => FORMAT_ETC2_R8G8B8_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + ETC2_R8G8B8SrgbBlock => FORMAT_ETC2_R8G8B8_SRGB_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + ETC2_R8G8B8A1UnormBlock => FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + ETC2_R8G8B8A1SrgbBlock => FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + ETC2_R8G8B8A8UnormBlock => FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_etc2] {u8}, + ETC2_R8G8B8A8SrgbBlock => FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_etc2] {u8}, + EAC_R11UnormBlock => FORMAT_EAC_R11_UNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + EAC_R11SnormBlock => FORMAT_EAC_R11_SNORM_BLOCK [(4, 4)] [Some(8)] [compressed=texture_compression_etc2] {u8}, + EAC_R11G11UnormBlock => FORMAT_EAC_R11G11_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_etc2] {u8}, + EAC_R11G11SnormBlock => FORMAT_EAC_R11G11_SNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_etc2] {u8}, + ASTC_4x4UnormBlock => FORMAT_ASTC_4x4_UNORM_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_4x4SrgbBlock => FORMAT_ASTC_4x4_SRGB_BLOCK [(4, 4)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_5x4UnormBlock => FORMAT_ASTC_5x4_UNORM_BLOCK [(5, 4)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_5x4SrgbBlock => FORMAT_ASTC_5x4_SRGB_BLOCK [(5, 4)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_5x5UnormBlock => FORMAT_ASTC_5x5_UNORM_BLOCK [(5, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_5x5SrgbBlock => FORMAT_ASTC_5x5_SRGB_BLOCK [(5, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_6x5UnormBlock => FORMAT_ASTC_6x5_UNORM_BLOCK [(6, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_6x5SrgbBlock => FORMAT_ASTC_6x5_SRGB_BLOCK [(6, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_6x6UnormBlock => FORMAT_ASTC_6x6_UNORM_BLOCK [(6, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_6x6SrgbBlock => FORMAT_ASTC_6x6_SRGB_BLOCK [(6, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x5UnormBlock => FORMAT_ASTC_8x5_UNORM_BLOCK [(8, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x5SrgbBlock => FORMAT_ASTC_8x5_SRGB_BLOCK [(8, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x6UnormBlock => FORMAT_ASTC_8x6_UNORM_BLOCK [(8, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x6SrgbBlock => FORMAT_ASTC_8x6_SRGB_BLOCK [(8, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x8UnormBlock => FORMAT_ASTC_8x8_UNORM_BLOCK [(8, 8)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_8x8SrgbBlock => FORMAT_ASTC_8x8_SRGB_BLOCK [(8, 8)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x5UnormBlock => FORMAT_ASTC_10x5_UNORM_BLOCK [(10, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x5SrgbBlock => FORMAT_ASTC_10x5_SRGB_BLOCK [(10, 5)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x6UnormBlock => FORMAT_ASTC_10x6_UNORM_BLOCK [(10, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x6SrgbBlock => FORMAT_ASTC_10x6_SRGB_BLOCK [(10, 6)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x8UnormBlock => FORMAT_ASTC_10x8_UNORM_BLOCK [(10, 8)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x8SrgbBlock => FORMAT_ASTC_10x8_SRGB_BLOCK [(10, 8)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x10UnormBlock => FORMAT_ASTC_10x10_UNORM_BLOCK [(10, 10)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_10x10SrgbBlock => FORMAT_ASTC_10x10_SRGB_BLOCK [(10, 10)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_12x10UnormBlock => FORMAT_ASTC_12x10_UNORM_BLOCK [(12, 10)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_12x10SrgbBlock => FORMAT_ASTC_12x10_SRGB_BLOCK [(12, 10)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_12x12UnormBlock => FORMAT_ASTC_12x12_UNORM_BLOCK [(12, 12)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, + ASTC_12x12SrgbBlock => FORMAT_ASTC_12x12_SRGB_BLOCK [(12, 12)] [Some(16)] [compressed=texture_compression_astc_ldr] {u8}, } pub unsafe trait FormatDesc { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/attachments_list.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/attachments_list.rs similarity index 77% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/attachments_list.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/attachments_list.rs index e0694fc..c82b188 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/attachments_list.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/attachments_list.rs @@ -18,7 +18,7 @@ use std::sync::Arc; pub unsafe trait AttachmentsList { fn num_attachments(&self) -> usize; - fn as_image_view_access(&self, index: usize) -> Option<&ImageViewAccess>; + fn as_image_view_access(&self, index: usize) -> Option<&dyn ImageViewAccess>; } unsafe impl AttachmentsList for T @@ -31,7 +31,7 @@ unsafe impl AttachmentsList for T } #[inline] - fn as_image_view_access(&self, index: usize) -> Option<&ImageViewAccess> { + fn as_image_view_access(&self, index: usize) -> Option<&dyn ImageViewAccess> { (**self).as_image_view_access(index) } } @@ -43,19 +43,19 @@ unsafe impl AttachmentsList for () { } #[inline] - fn as_image_view_access(&self, _: usize) -> Option<&ImageViewAccess> { + fn as_image_view_access(&self, _: usize) -> Option<&dyn ImageViewAccess> { None } } -unsafe impl AttachmentsList for Vec> { +unsafe impl AttachmentsList for Vec> { #[inline] fn num_attachments(&self) -> usize { self.len() } #[inline] - fn as_image_view_access(&self, index: usize) -> Option<&ImageViewAccess> { + fn as_image_view_access(&self, index: usize) -> Option<&dyn ImageViewAccess> { self.get(index).map(|v| &**v as &_) } } @@ -70,7 +70,7 @@ unsafe impl AttachmentsList for (A, B) } #[inline] - fn as_image_view_access(&self, index: usize) -> Option<&ImageViewAccess> { + fn as_image_view_access(&self, index: usize) -> Option<&dyn ImageViewAccess> { if index == self.0.num_attachments() { Some(&self.1) } else { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/compat_atch.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/compat_atch.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/compat_atch.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/compat_atch.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/desc.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/desc.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/desc.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/desc.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/empty.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/empty.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/empty.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/empty.rs index d985610..d2ca534 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/empty.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/empty.rs @@ -115,7 +115,7 @@ unsafe impl RenderPassDesc for EmptySinglePassRenderPassDesc { unsafe impl RenderPassDescClearValues> for EmptySinglePassRenderPassDesc { #[inline] - fn convert_clear_values(&self, values: Vec) -> Box> { + fn convert_clear_values(&self, values: Vec) -> Box> { assert!(values.is_empty()); // TODO: error instead Box::new(iter::empty()) } @@ -123,7 +123,7 @@ unsafe impl RenderPassDescClearValues> for EmptySinglePassRender unsafe impl RenderPassDescClearValues<()> for EmptySinglePassRenderPassDesc { #[inline] - fn convert_clear_values(&self, _: ()) -> Box> { + fn convert_clear_values(&self, _: ()) -> Box> { Box::new(iter::empty()) } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/framebuffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/framebuffer.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/framebuffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/framebuffer.rs index c734406..f0dd301 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/framebuffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/framebuffer.rs @@ -12,7 +12,7 @@ use std::cmp; use std::error; use std::fmt; use std::marker::PhantomData; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -241,7 +241,7 @@ impl FramebufferBuilder /// > **Note**: This is a very rare corner case and you shouldn't have to use this function /// > in most situations. #[inline] - pub fn boxed(self) -> FramebufferBuilder> + pub fn boxed(self) -> FramebufferBuilder> where A: 'static { FramebufferBuilder { @@ -305,12 +305,12 @@ impl FramebufferBuilder layers: dimensions[2], }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateFramebuffer(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Framebuffer { @@ -376,7 +376,7 @@ unsafe impl FramebufferAbstract for Framebuffer } #[inline] - fn attached_image_view(&self, index: usize) -> Option<&ImageViewAccess> { + fn attached_image_view(&self, index: usize) -> Option<&dyn ImageViewAccess> { self.resources.as_image_view_access(index) } } @@ -419,7 +419,7 @@ unsafe impl RenderPassDescClearValues for Framebuffer where Rp: RenderPassDescClearValues { #[inline] - fn convert_clear_values(&self, vals: C) -> Box> { + fn convert_clear_values(&self, vals: C) -> Box> { self.render_pass.convert_clear_values(vals) } } @@ -457,7 +457,7 @@ pub struct FramebufferSys<'a>(vk::Framebuffer, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for FramebufferSys<'a> { type Object = vk::Framebuffer; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_FRAMEBUFFER; #[inline] fn internal_object(&self) -> vk::Framebuffer { @@ -522,7 +522,7 @@ impl error::Error for FramebufferCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { FramebufferCreationError::OomError(ref err) => Some(err), FramebufferCreationError::IncompatibleAttachment(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/macros.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/macros.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/macros.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/macros.rs index 68cb34b..86ecc14 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/macros.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/macros.rs @@ -119,7 +119,7 @@ macro_rules! ordered_passes_renderpass { } unsafe impl RenderPassDescClearValues> for CustomRenderPassDesc { - fn convert_clear_values(&self, values: Vec) -> Box> { + fn convert_clear_values(&self, values: Vec) -> Box> { // FIXME: safety checks Box::new(values.into_iter()) } @@ -312,18 +312,6 @@ macro_rules! ordered_passes_renderpass { })* $(if $atch_name == num { - // If the clear OP is Clear or DontCare, default to the Undefined layout. - if initial_layout == Some(ImageLayout::DepthStencilAttachmentOptimal) || - initial_layout == Some(ImageLayout::ColorAttachmentOptimal) || - initial_layout == Some(ImageLayout::TransferDstOptimal) - { - if $crate::framebuffer::LoadOp::$load == $crate::framebuffer::LoadOp::Clear || - $crate::framebuffer::LoadOp::$load == $crate::framebuffer::LoadOp::DontCare - { - initial_layout = Some(ImageLayout::Undefined); - } - } - $(initial_layout = Some($init_layout);)* $(final_layout = Some($final_layout);)* })* diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/sys.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/sys.rs index d7d09c7..9a8ef6f 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/sys.rs @@ -11,7 +11,7 @@ use smallvec::SmallVec; use std::error; use std::fmt; use std::marker::PhantomData; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; use std::sync::Mutex; @@ -343,12 +343,12 @@ impl RenderPass }, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateRenderPass(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(RenderPass { @@ -387,9 +387,10 @@ impl RenderPass { unsafe { let vk = self.device.pointers(); - let mut out = mem::uninitialized(); - vk.GetRenderAreaGranularity(self.device.internal_object(), self.render_pass, &mut out); + let mut out = MaybeUninit::uninit(); + vk.GetRenderAreaGranularity(self.device.internal_object(), self.render_pass, out.as_mut_ptr()); + let out = out.assume_init(); debug_assert_ne!(out.width, 0); debug_assert_ne!(out.height, 0); let gran = [out.width, out.height]; @@ -446,7 +447,7 @@ unsafe impl RenderPassDescClearValues for RenderPass where D: RenderPassDescClearValues { #[inline] - fn convert_clear_values(&self, vals: C) -> Box> { + fn convert_clear_values(&self, vals: C) -> Box> { self.desc.convert_clear_values(vals) } } @@ -496,7 +497,7 @@ pub struct RenderPassSys<'a>(vk::RenderPass, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for RenderPassSys<'a> { type Object = vk::RenderPass; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_RENDER_PASS; #[inline] fn internal_object(&self) -> vk::RenderPass { @@ -525,7 +526,7 @@ impl error::Error for RenderPassCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { RenderPassCreationError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/traits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/traits.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/traits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/traits.rs index deb4ed0..b04ea03 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/framebuffer/traits.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/framebuffer/traits.rs @@ -31,7 +31,7 @@ pub unsafe trait FramebufferAbstract: RenderPassAbstract { /// Returns the attachment of the framebuffer with the given index. /// /// If the `index` is not between `0` and `num_attachments`, then `None` should be returned. - fn attached_image_view(&self, index: usize) -> Option<&ImageViewAccess>; + fn attached_image_view(&self, index: usize) -> Option<&dyn ImageViewAccess>; /// Returns the width of the framebuffer in pixels. #[inline] @@ -67,7 +67,7 @@ unsafe impl FramebufferAbstract for T } #[inline] - fn attached_image_view(&self, index: usize) -> Option<&ImageViewAccess> { + fn attached_image_view(&self, index: usize) -> Option<&dyn ImageViewAccess> { (**self).attached_image_view(index) } } @@ -134,7 +134,7 @@ pub unsafe trait RenderPassDescClearValues { /// that matches the attachment. /// // TODO: meh for boxing - fn convert_clear_values(&self, C) -> Box>; + fn convert_clear_values(&self, C) -> Box>; } unsafe impl RenderPassDescClearValues for T @@ -142,7 +142,7 @@ unsafe impl RenderPassDescClearValues for T T::Target: RenderPassDescClearValues { #[inline] - fn convert_clear_values(&self, vals: C) -> Box> { + fn convert_clear_values(&self, vals: C) -> Box> { (**self).convert_clear_values(vals) } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/attachment.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/attachment.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/attachment.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/attachment.rs index 7ee458f..eb266c7 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/attachment.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/attachment.rs @@ -7,6 +7,8 @@ // notice may not be copied, modified, or distributed except // according to those terms. +use std::hash::Hash; +use std::hash::Hasher; use std::iter::Empty; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -438,12 +440,12 @@ unsafe impl ImageAccess for AttachmentImage } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { false } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.conflict_key() == other.conflict_key() } @@ -497,6 +499,16 @@ unsafe impl ImageAccess for AttachmentImage let prev_val = self.gpu_lock.fetch_sub(1, Ordering::SeqCst); debug_assert!(prev_val >= 1); } + + #[inline] + unsafe fn layout_initialized(&self) { + self.initialized.store(true, Ordering::SeqCst); + } + + #[inline] + fn is_layout_initialized(&self) -> bool { + self.initialized.load(Ordering::SeqCst) + } } unsafe impl ImageClearValue for Arc> @@ -521,7 +533,7 @@ unsafe impl ImageViewAccess for AttachmentImage where F: 'static + Send + Sync { #[inline] - fn parent(&self) -> &ImageAccess { + fn parent(&self) -> &dyn ImageAccess { self } @@ -565,6 +577,28 @@ unsafe impl ImageViewAccess for AttachmentImage } } +impl PartialEq for AttachmentImage + where F: 'static + Send + Sync +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + ImageAccess::inner(self) == ImageAccess::inner(other) + } +} + +impl Eq for AttachmentImage + where F: 'static + Send + Sync +{} + +impl Hash for AttachmentImage + where F: 'static + Send + Sync +{ + #[inline] + fn hash(&self, state: &mut H) { + ImageAccess::inner(self).hash(state); + } +} + #[cfg(test)] mod tests { use super::AttachmentImage; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/immutable.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/immutable.rs similarity index 91% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/immutable.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/immutable.rs index 90e2ece..99860dd 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/immutable.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/immutable.rs @@ -8,6 +8,8 @@ // according to those terms. use smallvec::SmallVec; +use std::hash::Hash; +use std::hash::Hasher; use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; @@ -201,6 +203,7 @@ impl ImmutableImage { { let source = CpuAccessibleBuffer::from_iter(queue.device().clone(), BufferUsage::transfer_source(), + false, iter)?; ImmutableImage::from_buffer(source, dimensions, format, queue) } @@ -293,12 +296,12 @@ unsafe impl ImageAccess for ImmutableImage } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { false } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } @@ -351,7 +354,7 @@ unsafe impl ImageViewAccess for ImmutableImage where F: 'static + Send + Sync { #[inline] - fn parent(&self) -> &ImageAccess { + fn parent(&self) -> &dyn ImageAccess { self } @@ -391,6 +394,28 @@ unsafe impl ImageViewAccess for ImmutableImage } } +impl PartialEq for ImmutableImage + where F: 'static + Send + Sync +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + ImageAccess::inner(self) == ImageAccess::inner(other) + } +} + +impl Eq for ImmutableImage + where F: 'static + Send + Sync +{} + +impl Hash for ImmutableImage + where F: 'static + Send + Sync +{ + #[inline] + fn hash(&self, state: &mut H) { + ImageAccess::inner(self).hash(state); + } +} + unsafe impl ImageAccess for ImmutableImageInitialization where F: 'static + Send + Sync { @@ -410,12 +435,12 @@ unsafe impl ImageAccess for ImmutableImageInitialization } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { false } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } @@ -456,3 +481,25 @@ unsafe impl ImageAccess for ImmutableImageInitialization self.image.initialized.store(true, Ordering::Relaxed); } } + +impl PartialEq for ImmutableImageInitialization + where F: 'static + Send + Sync +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + ImageAccess::inner(self) == ImageAccess::inner(other) + } +} + +impl Eq for ImmutableImageInitialization + where F: 'static + Send + Sync +{} + +impl Hash for ImmutableImageInitialization + where F: 'static + Send + Sync +{ + #[inline] + fn hash(&self, state: &mut H) { + ImageAccess::inner(self).hash(state); + } +} diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/layout.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/layout.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/layout.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/layout.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/mod.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/mod.rs index c14f056..3bc9af9 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/mod.rs @@ -415,17 +415,11 @@ impl ImageDimensions { /// array_layers: 1, /// }; /// - /// assert_eq!(dims.max_mipmaps(), 7); + /// assert_eq!(dims.max_mipmaps(), 6); /// ``` /// - /// # Panic - /// - /// May panic if the dimensions are 0. - /// pub fn max_mipmaps(&self) -> u32 { - let max_dim = cmp::max(cmp::max(self.width(), self.height()), self.depth()); - let num_zeroes = 32 - (max_dim - 1).leading_zeros(); - num_zeroes + 1 + 32 - (self.width() | self.height() | self.depth()).leading_zeros() } /// Returns the dimensions of the `level`th mipmap level. If `level` is 0, then the dimensions @@ -447,19 +441,19 @@ impl ImageDimensions { /// /// assert_eq!(dims.mipmap_dimensions(0), Some(dims)); /// assert_eq!(dims.mipmap_dimensions(1), Some(ImageDimensions::Dim2d { - /// width: 512, + /// width: 481, /// height: 128, /// cubemap_compatible: false, /// array_layers: 1, /// })); /// assert_eq!(dims.mipmap_dimensions(6), Some(ImageDimensions::Dim2d { - /// width: 16, + /// width: 15, /// height: 4, /// cubemap_compatible: false, /// array_layers: 1, /// })); /// assert_eq!(dims.mipmap_dimensions(9), Some(ImageDimensions::Dim2d { - /// width: 2, + /// width: 1, /// height: 1, /// cubemap_compatible: false, /// array_layers: 1, @@ -489,7 +483,7 @@ impl ImageDimensions { debug_assert_ne!(width, 0); ImageDimensions::Dim1d { array_layers: array_layers, - width: (((width - 1) >> level) + 1).next_power_of_two(), + width: cmp::max(1, width >> level), } }, @@ -502,8 +496,8 @@ impl ImageDimensions { debug_assert_ne!(width, 0); debug_assert_ne!(height, 0); ImageDimensions::Dim2d { - width: (((width - 1) >> level) + 1).next_power_of_two(), - height: (((height - 1) >> level) + 1).next_power_of_two(), + width: cmp::max(1, width >> level), + height: cmp::max(1, height >> level), array_layers: array_layers, cubemap_compatible: cubemap_compatible, } @@ -517,9 +511,9 @@ impl ImageDimensions { debug_assert_ne!(width, 0); debug_assert_ne!(height, 0); ImageDimensions::Dim3d { - width: (((width - 1) >> level) + 1).next_power_of_two(), - height: (((height - 1) >> level) + 1).next_power_of_two(), - depth: (((depth - 1) >> level) + 1).next_power_of_two(), + width: cmp::max(1, width >> level), + height: cmp::max(1, height >> level), + depth: cmp::max(1, depth >> level), } }, }) @@ -546,7 +540,7 @@ mod tests { cubemap_compatible: false, array_layers: 1, }; - assert_eq!(dims.max_mipmaps(), 3); + assert_eq!(dims.max_mipmaps(), 2); let dims = ImageDimensions::Dim2d { width: 512, @@ -568,67 +562,61 @@ mod tests { assert_eq!(dims.mipmap_dimensions(0), Some(dims)); assert_eq!(dims.mipmap_dimensions(1), Some(ImageDimensions::Dim2d { - width: 256, - height: 128, + width: 141, + height: 87, cubemap_compatible: false, array_layers: 1, })); assert_eq!(dims.mipmap_dimensions(2), Some(ImageDimensions::Dim2d { - width: 128, - height: 64, + width: 70, + height: 43, cubemap_compatible: false, array_layers: 1, })); assert_eq!(dims.mipmap_dimensions(3), Some(ImageDimensions::Dim2d { - width: 64, - height: 32, + width: 35, + height: 21, cubemap_compatible: false, array_layers: 1, })); + assert_eq!(dims.mipmap_dimensions(4), Some(ImageDimensions::Dim2d { - width: 32, - height: 16, + width: 17, + height: 10, cubemap_compatible: false, array_layers: 1, })); assert_eq!(dims.mipmap_dimensions(5), Some(ImageDimensions::Dim2d { - width: 16, - height: 8, + width: 8, + height: 5, cubemap_compatible: false, array_layers: 1, })); assert_eq!(dims.mipmap_dimensions(6), - Some(ImageDimensions::Dim2d { - width: 8, - height: 4, - cubemap_compatible: false, - array_layers: 1, - })); - assert_eq!(dims.mipmap_dimensions(7), Some(ImageDimensions::Dim2d { width: 4, height: 2, cubemap_compatible: false, array_layers: 1, })); - assert_eq!(dims.mipmap_dimensions(8), + assert_eq!(dims.mipmap_dimensions(7), Some(ImageDimensions::Dim2d { width: 2, height: 1, cubemap_compatible: false, array_layers: 1, })); - assert_eq!(dims.mipmap_dimensions(9), + assert_eq!(dims.mipmap_dimensions(8), Some(ImageDimensions::Dim2d { width: 1, height: 1, cubemap_compatible: false, array_layers: 1, })); - assert_eq!(dims.mipmap_dimensions(10), None); + assert_eq!(dims.mipmap_dimensions(9), None); } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/storage.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/storage.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/storage.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/storage.rs index ef7aef3..97bf9eb 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/storage.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/storage.rs @@ -8,6 +8,8 @@ // according to those terms. use smallvec::SmallVec; +use std::hash::Hash; +use std::hash::Hasher; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; @@ -198,12 +200,12 @@ unsafe impl ImageAccess for StorageImage } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { false } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } @@ -268,7 +270,7 @@ unsafe impl ImageViewAccess for StorageImage A: MemoryPool { #[inline] - fn parent(&self) -> &ImageAccess { + fn parent(&self) -> &dyn ImageAccess { self } @@ -308,6 +310,31 @@ unsafe impl ImageViewAccess for StorageImage } } +impl PartialEq for StorageImage + where F: 'static + Send + Sync, + A: MemoryPool +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + ImageAccess::inner(self) == ImageAccess::inner(other) + } +} + +impl Eq for StorageImage + where F: 'static + Send + Sync, + A: MemoryPool +{} + +impl Hash for StorageImage + where F: 'static + Send + Sync, + A: MemoryPool +{ + #[inline] + fn hash(&self, state: &mut H) { + ImageAccess::inner(self).hash(state); + } +} + #[cfg(test)] mod tests { use super::StorageImage; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/swapchain.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/swapchain.rs similarity index 80% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/swapchain.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/swapchain.rs index f3c6169..0dec2a5 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/swapchain.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/swapchain.rs @@ -7,6 +7,8 @@ // notice may not be copied, modified, or distributed except // according to those terms. +use std::hash::Hash; +use std::hash::Hasher; use std::sync::Arc; use buffer::BufferAccess; @@ -82,6 +84,16 @@ impl SwapchainImage { fn my_image(&self) -> ImageInner { self.swapchain.raw_image(self.image_offset).unwrap() } + + #[inline] + fn layout_initialized(&self) { + self.swapchain.image_layout_initialized(self.image_offset); + } + + #[inline] + fn is_layout_initialized(&self) -> bool { + self.swapchain.is_image_layout_initialized(self.image_offset) + } } unsafe impl ImageAccess for SwapchainImage { @@ -101,12 +113,12 @@ unsafe impl ImageAccess for SwapchainImage { } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { false } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.my_image().image.key() == other.conflict_key() // TODO: } @@ -117,8 +129,22 @@ unsafe impl ImageAccess for SwapchainImage { #[inline] fn try_gpu_lock(&self, _: bool, _: ImageLayout) -> Result<(), AccessError> { - // Swapchain image are only accessible after being acquired. - Err(AccessError::SwapchainImageAcquireOnly) + if self.swapchain.is_fullscreen_exclusive() { + Ok(()) + } else { + // Swapchain image are only accessible after being acquired. + Err(AccessError::SwapchainImageAcquireOnly) + } + } + + #[inline] + unsafe fn layout_initialized(&self) { + self.layout_initialized(); + } + + #[inline] + fn is_layout_initialized(&self) -> bool{ + self.is_layout_initialized() } #[inline] @@ -147,7 +173,7 @@ unsafe impl ImageContent

for SwapchainImage { unsafe impl ImageViewAccess for SwapchainImage { #[inline] - fn parent(&self) -> &ImageAccess { + fn parent(&self) -> &dyn ImageAccess { self } @@ -190,3 +216,19 @@ unsafe impl ImageViewAccess for SwapchainImage { true } } + +impl PartialEq for SwapchainImage { + #[inline] + fn eq(&self, other: &Self) -> bool { + ImageAccess::inner(self) == ImageAccess::inner(other) + } +} + +impl Eq for SwapchainImage {} + +impl Hash for SwapchainImage { + #[inline] + fn hash(&self, state: &mut H) { + ImageAccess::inner(self).hash(state); + } +} diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/sys.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/sys.rs index b675c34..7689b93 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/sys.rs @@ -16,7 +16,10 @@ use smallvec::SmallVec; use std::error; use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::mem; +use std::mem::MaybeUninit; use std::ops::Range; use std::ptr; use std::sync::Arc; @@ -67,6 +70,7 @@ pub struct UnsafeImage { // `vkDestroyImage` is called only if `needs_destruction` is true. needs_destruction: bool, + preinitialized_layout: bool, } impl UnsafeImage { @@ -118,13 +122,13 @@ impl UnsafeImage { let format_features = { let physical_device = device.physical_device().internal_object(); - let mut output = mem::uninitialized(); - vk_i.GetPhysicalDeviceFormatProperties(physical_device, format as u32, &mut output); + let mut output = MaybeUninit::uninit(); + vk_i.GetPhysicalDeviceFormatProperties(physical_device, format as u32, output.as_mut_ptr()); let features = if linear_tiling { - output.linearTilingFeatures + output.assume_init().linearTilingFeatures } else { - output.optimalTilingFeatures + output.assume_init().optimalTilingFeatures }; if features == 0 { @@ -434,7 +438,7 @@ impl UnsafeImage { vk::IMAGE_TILING_OPTIMAL }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); let physical_device = device.physical_device().internal_object(); let r = vk_i.GetPhysicalDeviceImageFormatProperties(physical_device, format as u32, @@ -442,7 +446,7 @@ impl UnsafeImage { tiling, usage, 0, /* TODO */ - &mut output); + output.as_mut_ptr()); match check_errors(r) { Ok(_) => (), @@ -451,6 +455,8 @@ impl UnsafeImage { Err(err) => return Err(err.into()), } + let output = output.assume_init(); + if extent.width > output.maxExtent.width || extent.height > output.maxExtent.height || extent.depth > output.maxExtent.depth || mipmaps > output.maxMipLevels || @@ -489,12 +495,12 @@ impl UnsafeImage { }, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateImage(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; let mem_reqs = if device.loaded_extensions().khr_get_memory_requirements2 { @@ -508,8 +514,8 @@ impl UnsafeImage { Some(vk::MemoryDedicatedRequirementsKHR { sType: vk::STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR, pNext: ptr::null(), - prefersDedicatedAllocation: mem::uninitialized(), - requiresDedicatedAllocation: mem::uninitialized(), + prefersDedicatedAllocation: mem::zeroed(), + requiresDedicatedAllocation: mem::zeroed(), }) } else { None @@ -521,7 +527,7 @@ impl UnsafeImage { .as_mut() .map(|o| o as *mut vk::MemoryDedicatedRequirementsKHR) .unwrap_or(ptr::null_mut()) as *mut _, - memoryRequirements: mem::uninitialized(), + memoryRequirements: mem::zeroed(), }; vk.GetImageMemoryRequirements2KHR(device.internal_object(), &infos, &mut output); @@ -535,8 +541,9 @@ impl UnsafeImage { out } else { - let mut output: vk::MemoryRequirements = mem::uninitialized(); - vk.GetImageMemoryRequirements(device.internal_object(), image, &mut output); + let mut output: MaybeUninit = MaybeUninit::uninit(); + vk.GetImageMemoryRequirements(device.internal_object(), image, output.as_mut_ptr()); + let output = output.assume_init(); debug_assert!(output.memoryTypeBits != 0); MemoryRequirements::from_vulkan_reqs(output) }; @@ -551,6 +558,7 @@ impl UnsafeImage { mipmaps: mipmaps, format_features: format_features, needs_destruction: true, + preinitialized_layout, }; Ok((image, mem_reqs)) @@ -565,8 +573,8 @@ impl UnsafeImage { let vk_i = device.instance().pointers(); let physical_device = device.physical_device().internal_object(); - let mut output = mem::uninitialized(); - vk_i.GetPhysicalDeviceFormatProperties(physical_device, format as u32, &mut output); + let mut output = MaybeUninit::uninit(); + vk_i.GetPhysicalDeviceFormatProperties(physical_device, format as u32, output.as_mut_ptr()); // TODO: check that usage is correct in regard to `output`? @@ -578,8 +586,9 @@ impl UnsafeImage { dimensions: dimensions, samples: samples, mipmaps: mipmaps, - format_features: output.optimalTilingFeatures, + format_features: output.assume_init().optimalTilingFeatures, needs_destruction: false, // TODO: pass as parameter + preinitialized_layout: false, // TODO: Maybe this should be passed in? } } @@ -588,10 +597,12 @@ impl UnsafeImage { // We check for correctness in debug mode. debug_assert!({ - let mut mem_reqs = mem::uninitialized(); + let mut mem_reqs = MaybeUninit::uninit(); vk.GetImageMemoryRequirements(self.device.internal_object(), self.image, - &mut mem_reqs); + mem_reqs.as_mut_ptr()); + + let mem_reqs = mem_reqs.assume_init(); mem_reqs.size <= (memory.size() - offset) as u64 && (offset as u64 % mem_reqs.alignment) == 0 && mem_reqs.memoryTypeBits & (1 << memory.memory_type().id()) != 0 @@ -706,12 +717,13 @@ impl UnsafeImage { arrayLayer: 0, }; - let mut out = mem::uninitialized(); + let mut out = MaybeUninit::uninit(); vk.GetImageSubresourceLayout(self.device.internal_object(), self.image, &subresource, - &mut out); + out.as_mut_ptr()); + let out = out.assume_init(); LinearLayout { offset: out.offset as usize, size: out.size as usize, @@ -778,12 +790,17 @@ impl UnsafeImage { pub fn usage_input_attachment(&self) -> bool { (self.usage & vk::IMAGE_USAGE_INPUT_ATTACHMENT_BIT) != 0 } + + #[inline] + pub fn preinitialized_layout(&self) -> bool { + self.preinitialized_layout + } } unsafe impl VulkanObject for UnsafeImage { type Object = vk::Image; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_IMAGE; #[inline] fn internal_object(&self) -> vk::Image { @@ -812,6 +829,23 @@ impl Drop for UnsafeImage { } } +impl PartialEq for UnsafeImage { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.image == other.image && self.device == other.device + } +} + +impl Eq for UnsafeImage {} + +impl Hash for UnsafeImage { + #[inline] + fn hash(&self, state: &mut H) { + self.image.hash(state); + self.device.hash(state); + } +} + /// Error that can happen when creating an instance. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ImageCreationError { @@ -858,7 +892,7 @@ impl error::Error for ImageCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { ImageCreationError::AllocError(ref err) => Some(err), _ => None, @@ -995,12 +1029,12 @@ impl UnsafeImageView { }, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateImageView(image.device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(UnsafeImageView { @@ -1083,7 +1117,7 @@ impl UnsafeImageView { unsafe impl VulkanObject for UnsafeImageView { type Object = vk::ImageView; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_IMAGE_VIEW; #[inline] fn internal_object(&self) -> vk::ImageView { @@ -1108,6 +1142,23 @@ impl Drop for UnsafeImageView { } } +impl PartialEq for UnsafeImageView { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.view == other.view && self.device == other.device + } +} + +impl Eq for UnsafeImageView {} + +impl Hash for UnsafeImageView { + #[inline] + fn hash(&self, state: &mut H) { + self.view.hash(state); + self.device.hash(state); + } +} + #[cfg(test)] mod tests { use std::iter::Empty; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/traits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/traits.rs similarity index 83% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/traits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/traits.rs index 224aa5f..830ef5c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/image/traits.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/image/traits.rs @@ -7,6 +7,9 @@ // notice may not be copied, modified, or distributed except // according to those terms. +use std::hash::Hash; +use std::hash::Hasher; + use buffer::BufferAccess; use format::ClearValue; use format::Format; @@ -16,6 +19,7 @@ use format::PossibleFloatFormatDesc; use format::PossibleSintFormatDesc; use format::PossibleStencilFormatDesc; use format::PossibleUintFormatDesc; +use format::PossibleCompressedFormatDesc; use image::Dimensions; use image::ImageDimensions; use image::ImageLayout; @@ -41,7 +45,7 @@ pub unsafe trait ImageAccess { #[inline] fn has_color(&self) -> bool { let format = self.format(); - format.is_float() || format.is_uint() || format.is_sint() + format.is_float() || format.is_uint() || format.is_sint() || format.is_compressed() } /// Returns true if the image has a depth component. In other words, if it is a depth or a @@ -92,6 +96,27 @@ pub unsafe trait ImageAccess { self.inner().image.supports_blit_destination() } + /// When images are created their memory layout is initially `Undefined` or `Preinitialized`. + /// This method allows the image memory barrier creation process to signal when an image + /// has been transitioned out of its initial `Undefined` or `Preinitialized` state. This + /// allows vulkano to avoid creating unnecessary image memory barriers between future + /// uses of the image. + /// + /// ## Unsafe + /// + /// If a user calls this method outside of the intended context and signals that the layout + /// is no longer `Undefined` or `Preinitialized` when it is still in an `Undefined` or + /// `Preinitialized` state, this may result in the vulkan implementation attempting to use + /// an image in an invalid layout. The same problem must be considered by the implementer + /// of the method. + unsafe fn layout_initialized(&self) {} + + fn is_layout_initialized(&self) -> bool {false} + + unsafe fn preinitialized_layout(&self) -> bool { + self.inner().image.preinitialized_layout() + } + /// Returns the layout that the image has when it is first used in a primary command buffer. /// /// The first time you use an image in an `AutoCommandBufferBuilder`, vulkano will suppose that @@ -133,7 +158,7 @@ pub unsafe trait ImageAccess { /// /// Note that the function must be transitive. In other words if `conflicts(a, b)` is true and /// `conflicts(b, c)` is true, then `conflicts(a, c)` must be true as well. - fn conflicts_buffer(&self, other: &BufferAccess) -> bool; + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool; /// Returns true if an access to `self` potentially overlaps the same memory as an /// access to `other`. @@ -143,7 +168,7 @@ pub unsafe trait ImageAccess { /// /// Note that the function must be transitive. In other words if `conflicts(a, b)` is true and /// `conflicts(b, c)` is true, then `conflicts(a, c)` must be true as well. - fn conflicts_image(&self, other: &ImageAccess) -> bool; + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool; /// Returns a key that uniquely identifies the memory content of the image. /// Two ranges that potentially overlap in memory must return the same key. @@ -210,7 +235,7 @@ pub unsafe trait ImageAccess { } /// Inner information about an image. -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct ImageInner<'a> { /// The underlying image object. pub image: &'a UnsafeImage, @@ -248,12 +273,12 @@ unsafe impl ImageAccess for T } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { (**self).conflicts_buffer(other) } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { (**self).conflicts_image(other) } @@ -277,6 +302,32 @@ unsafe impl ImageAccess for T unsafe fn unlock(&self, transitioned_layout: Option) { (**self).unlock(transitioned_layout) } + + #[inline] + unsafe fn layout_initialized(&self) { + (**self).layout_initialized(); + } + + #[inline] + fn is_layout_initialized(&self) -> bool { + (**self).is_layout_initialized() + } +} + +impl PartialEq for dyn ImageAccess + Send + Sync { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() + } +} + +impl Eq for dyn ImageAccess + Send + Sync {} + +impl Hash for dyn ImageAccess + Send + Sync { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + } } /// Wraps around an object that implements `ImageAccess` and modifies the initial layout @@ -310,12 +361,12 @@ unsafe impl ImageAccess for ImageAccessFromUndefinedLayout } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.image.conflicts_buffer(other) } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.image.conflicts_image(other) } @@ -341,6 +392,28 @@ unsafe impl ImageAccess for ImageAccessFromUndefinedLayout } } +impl PartialEq for ImageAccessFromUndefinedLayout + where I: ImageAccess +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() + } +} + +impl Eq for ImageAccessFromUndefinedLayout + where I: ImageAccess +{} + +impl Hash for ImageAccessFromUndefinedLayout + where I: ImageAccess +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + } +} + /// Extension trait for images. Checks whether the value `T` can be used as a clear value for the /// given image. // TODO: isn't that for image views instead? @@ -355,7 +428,7 @@ pub unsafe trait ImageContent

: ImageAccess { /// Trait for types that represent the GPU can access an image view. pub unsafe trait ImageViewAccess { - fn parent(&self) -> &ImageAccess; + fn parent(&self) -> &dyn ImageAccess; /// Returns the dimensions of the image view. fn dimensions(&self) -> Dimensions; @@ -407,7 +480,7 @@ unsafe impl ImageViewAccess for T T::Target: ImageViewAccess { #[inline] - fn parent(&self) -> &ImageAccess { + fn parent(&self) -> &dyn ImageAccess { (**self).parent() } @@ -449,6 +522,22 @@ unsafe impl ImageViewAccess for T } } +impl PartialEq for dyn ImageViewAccess + Send + Sync { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() + } +} + +impl Eq for dyn ImageViewAccess + Send + Sync {} + +impl Hash for dyn ImageViewAccess + Send + Sync { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + } +} + pub unsafe trait AttachmentImageView: ImageViewAccess { fn accept(&self, initial_layout: ImageLayout, final_layout: ImageLayout) -> bool; } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/image/usage.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/image/usage.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/image/usage.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/image/usage.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/debug.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/debug.rs similarity index 53% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/debug.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/debug.rs index 8c41343..0d69f84 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/debug.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/debug.rs @@ -40,8 +40,8 @@ use std::error; use std::ffi::CStr; use std::fmt; -use std::mem; -use std::os::raw::{c_char, c_void}; +use std::mem::MaybeUninit; +use std::os::raw::c_void; use std::panic; use std::ptr; use std::sync::Arc; @@ -52,6 +52,7 @@ use Error; use VulkanObject; use check_errors; use vk; +use vk::{DebugUtilsMessengerCallbackDataEXT, Bool32}; /// Registration of a callback called by validation layers. /// @@ -60,19 +61,19 @@ use vk; to be called"] pub struct DebugCallback { instance: Arc, - debug_report_callback: vk::DebugReportCallbackEXT, - user_callback: Box>, + debug_report_callback: vk::DebugUtilsMessengerEXT, + user_callback: Box>, } impl DebugCallback { /// Initializes a debug callback. /// /// Panics generated by calling `user_callback` are ignored. - pub fn new(instance: &Arc, messages: MessageTypes, user_callback: F) + pub fn new(instance: &Arc, severity: MessageSeverity, ty: MessageType, user_callback: F) -> Result where F: Fn(&Message) + 'static + Send + panic::RefUnwindSafe { - if !instance.loaded_extensions().ext_debug_report { + if !instance.loaded_extensions().ext_debug_utils { return Err(DebugCallbackCreationError::MissingExtension); } @@ -80,32 +81,39 @@ impl DebugCallback { // that can't be cast to a `*const c_void`. let user_callback = Box::new(Box::new(user_callback) as Box<_>); - extern "system" fn callback(ty: vk::DebugReportFlagsEXT, _: vk::DebugReportObjectTypeEXT, - _: u64, _: usize, _: i32, layer_prefix: *const c_char, - description: *const c_char, user_data: *mut c_void) - -> u32 { + extern "system" fn callback( + severity: vk::DebugUtilsMessageSeverityFlagsEXT, + ty: vk::DebugUtilsMessageTypeFlagsEXT, + callback_data: *const + DebugUtilsMessengerCallbackDataEXT, + user_data: *mut c_void + ) -> Bool32 + { unsafe { - let user_callback = user_data as *mut Box as *const _; - let user_callback: &Box = &*user_callback; + let user_callback = user_data as *mut Box as *const _; + let user_callback: &Box = &*user_callback; - let layer_prefix = CStr::from_ptr(layer_prefix) + let layer_prefix = CStr::from_ptr((*callback_data).pMessageIdName) .to_str() .expect("debug callback message not utf-8"); - let description = CStr::from_ptr(description) + let description = CStr::from_ptr((*callback_data).pMessage) .to_str() .expect("debug callback message not utf-8"); let message = Message { - ty: MessageTypes { - information: (ty & vk::DEBUG_REPORT_INFORMATION_BIT_EXT) != 0, - warning: (ty & vk::DEBUG_REPORT_WARNING_BIT_EXT) != 0, - performance_warning: (ty & vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) != - 0, - error: (ty & vk::DEBUG_REPORT_ERROR_BIT_EXT) != 0, - debug: (ty & vk::DEBUG_REPORT_DEBUG_BIT_EXT) != 0, + severity: MessageSeverity { + information: (severity & vk::DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) != 0, + warning: (severity & vk::DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) != 0, + error: (severity & vk::DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0, + verbose: (severity & vk::DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) != 0, }, - layer_prefix: layer_prefix, - description: description, + ty: MessageType { + general: (ty & vk::DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) != 0, + validation: (ty & vk::DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) != 0, + performance: (ty & vk::DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) != 0, + }, + layer_prefix, + description, }; // Since we box the closure, the type system doesn't detect that the `UnwindSafe` @@ -118,49 +126,62 @@ impl DebugCallback { } } - let flags = { + let severity = { let mut flags = 0; - if messages.information { - flags |= vk::DEBUG_REPORT_INFORMATION_BIT_EXT; + if severity.information { + flags |= vk::DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT; } - if messages.warning { - flags |= vk::DEBUG_REPORT_WARNING_BIT_EXT; + if severity.warning { + flags |= vk::DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT; } - if messages.performance_warning { - flags |= vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; + if severity.error { + flags |= vk::DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; } - if messages.error { - flags |= vk::DEBUG_REPORT_ERROR_BIT_EXT; - } - if messages.debug { - flags |= vk::DEBUG_REPORT_DEBUG_BIT_EXT; + if severity.verbose { + flags |= vk::DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT; } flags }; - let infos = vk::DebugReportCallbackCreateInfoEXT { - sType: vk::STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, + let ty = { + let mut flags = 0; + if ty.general { + flags |= vk::DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT; + } + if ty.validation { + flags |= vk::DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT; + } + if ty.performance { + flags |= vk::DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + } + flags + }; + + let infos = vk::DebugUtilsMessengerCreateInfoEXT { + sType: vk::STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, pNext: ptr::null(), - flags: flags, - pfnCallback: callback, + flags: 0, + messageSeverity: severity, + messageType: ty, + pfnUserCallback: callback, pUserData: &*user_callback as &Box<_> as *const Box<_> as *const c_void as *mut _, }; let vk = instance.pointers(); let debug_report_callback = unsafe { - let mut output = mem::uninitialized(); - check_errors(vk.CreateDebugReportCallbackEXT(instance.internal_object(), + let mut output = MaybeUninit::uninit(); + check_errors(vk.CreateDebugUtilsMessengerEXT(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(DebugCallback { instance: instance.clone(), - debug_report_callback: debug_report_callback, - user_callback: user_callback, + debug_report_callback, + user_callback, }) } @@ -172,7 +193,7 @@ impl DebugCallback { -> Result where F: Fn(&Message) + Send + 'static + panic::RefUnwindSafe { - DebugCallback::new(instance, MessageTypes::errors_and_warnings(), user_callback) + DebugCallback::new(instance, MessageSeverity::errors_and_warnings(), MessageType::general(), user_callback) } } @@ -181,7 +202,7 @@ impl Drop for DebugCallback { fn drop(&mut self) { unsafe { let vk = self.instance.pointers(); - vk.DestroyDebugReportCallbackEXT(self.instance.internal_object(), + vk.DestroyDebugUtilsMessengerEXT(self.instance.internal_object(), self.debug_report_callback, ptr::null()); } @@ -190,60 +211,101 @@ impl Drop for DebugCallback { /// A message received by the callback. pub struct Message<'a> { - /// Type of message. - pub ty: MessageTypes, + /// Severity of message. + pub severity: MessageSeverity, + /// Type of message, + pub ty: MessageType, /// Prefix of the layer that reported this message. pub layer_prefix: &'a str, /// Description of the message. pub description: &'a str, } -/// Type of message. +/// Severity of message. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub struct MessageTypes { +pub struct MessageSeverity { /// An error that may cause undefined results, including an application crash. pub error: bool, /// An unexpected use. pub warning: bool, - /// A potential non-optimal use. - pub performance_warning: bool, /// An informational message that may be handy when debugging an application. pub information: bool, /// Diagnostic information from the loader and layers. - pub debug: bool, + pub verbose: bool, } -impl MessageTypes { - /// Builds a `MessageTypes` with all fields set to `false` expect `error`. +impl MessageSeverity { + /// Builds a `MessageSeverity` with all fields set to `false` expect `error`. #[inline] - pub fn errors() -> MessageTypes { - MessageTypes { + pub fn errors() -> MessageSeverity { + MessageSeverity { error: true, - ..MessageTypes::none() + ..MessageSeverity::none() } } - /// Builds a `MessageTypes` with all fields set to `false` expect `error`, `warning` + /// Builds a `MessageSeverity` with all fields set to `false` expect `error`, `warning` /// and `performance_warning`. #[inline] - pub fn errors_and_warnings() -> MessageTypes { - MessageTypes { + pub fn errors_and_warnings() -> MessageSeverity { + MessageSeverity { error: true, warning: true, - performance_warning: true, - ..MessageTypes::none() + ..MessageSeverity::none() } } - /// Builds a `MessageTypes` with all fields set to `false`. + /// Builds a `MessageSeverity` with all fields set to `false`. #[inline] - pub fn none() -> MessageTypes { - MessageTypes { + pub fn none() -> MessageSeverity { + MessageSeverity { error: false, warning: false, - performance_warning: false, information: false, - debug: false, + verbose: false, + } + } +} + +/// Type of message. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct MessageType { + /// Specifies that some general event has occurred. + pub general: bool, + /// Specifies that something has occurred during validation against the vulkan specification + pub validation: bool, + /// Specifies a potentially non-optimal use of Vulkan + pub performance: bool, +} + +impl MessageType { + /// Builds a `MessageType` with general field set to `true`. + #[inline] + pub fn general() -> MessageType { + MessageType { + general: true, + validation: false, + performance: false, + } + } + + /// Builds a `MessageType` with all fields set to `true`. + #[inline] + pub fn all() -> MessageType { + MessageType { + general: true, + validation: true, + performance: true, + } + } + + /// Builds a `MessageType` with all fields set to `false`. + #[inline] + pub fn none() -> MessageType { + MessageType { + general: false, + validation: false, + performance: false, } } } @@ -278,3 +340,21 @@ impl From for DebugCallbackCreationError { panic!("unexpected error: {:?}", err) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::thread; + #[test] + fn ensure_sendable() { + // It's useful to be able to initialize a DebugCallback on one thread + // and keep it alive on another thread. + let instance = instance!(); + let severity = MessageSeverity::none(); + let ty = MessageType::all(); + let callback = DebugCallback::new(&instance, severity, ty, |_| {}); + thread::spawn(move || { + let _ = callback; + }); + } +} diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/extensions.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/extensions.rs similarity index 90% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/extensions.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/extensions.rs index 06c89e3..d069dda 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/extensions.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/extensions.rs @@ -42,12 +42,14 @@ macro_rules! instance_extensions { let properties: Vec = unsafe { let mut num = 0; - try!(check_errors(entry_points.EnumerateInstanceExtensionProperties( - ptr::null(), &mut num, ptr::null_mut()))); + check_errors(entry_points.EnumerateInstanceExtensionProperties( + ptr::null(), &mut num, ptr::null_mut() + ))?; let mut properties = Vec::with_capacity(num as usize); - try!(check_errors(entry_points.EnumerateInstanceExtensionProperties( - ptr::null(), &mut num, properties.as_mut_ptr()))); + check_errors(entry_points.EnumerateInstanceExtensionProperties( + ptr::null(), &mut num, properties.as_mut_ptr() + ))?; properties.set_len(num as usize); properties }; @@ -91,12 +93,14 @@ macro_rules! instance_extensions { let properties: Vec = unsafe { let mut num = 0; - try!(check_errors(entry_points.EnumerateInstanceExtensionProperties( - ptr::null(), &mut num, ptr::null_mut()))); + check_errors(entry_points.EnumerateInstanceExtensionProperties( + ptr::null(), &mut num, ptr::null_mut() + ))?; let mut properties = Vec::with_capacity(num as usize); - try!(check_errors(entry_points.EnumerateInstanceExtensionProperties( - ptr::null(), &mut num, properties.as_mut_ptr()))); + check_errors(entry_points.EnumerateInstanceExtensionProperties( + ptr::null(), &mut num, properties.as_mut_ptr() + ))?; properties.set_len(num as usize); properties }; @@ -148,13 +152,14 @@ instance_extensions! { khr_wayland_surface => b"VK_KHR_wayland_surface", khr_android_surface => b"VK_KHR_android_surface", khr_win32_surface => b"VK_KHR_win32_surface", - ext_debug_report => b"VK_EXT_debug_report", + ext_debug_utils => b"VK_EXT_debug_utils", mvk_ios_surface => b"VK_MVK_ios_surface", mvk_macos_surface => b"VK_MVK_macos_surface", mvk_moltenvk => b"VK_MVK_moltenvk", // TODO: confirm that it's an instance extension nn_vi_surface => b"VK_NN_vi_surface", ext_swapchain_colorspace => b"VK_EXT_swapchain_colorspace", khr_get_physical_device_properties2 => b"VK_KHR_get_physical_device_properties2", + khr_get_surface_capabilities2 => b"VK_KHR_get_surface_capabilities2", } /// This helper type can only be instantiated inside this module. diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/instance.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/instance.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/instance.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/instance.rs index 0e93eff..69a667c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/instance.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/instance.rs @@ -13,11 +13,14 @@ use std::error; use std::ffi::CStr; use std::ffi::CString; use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::mem; use std::ops::Deref; use std::ptr; use std::slice; use std::sync::Arc; +use std::mem::MaybeUninit; use Error; use OomError; @@ -94,9 +97,9 @@ pub struct Instance { //alloc: Option>, physical_devices: Vec, vk: vk::InstancePointers, - extensions: InstanceExtensions, + extensions: RawInstanceExtensions, layers: SmallVec<[CString; 16]>, - function_pointers: OwnedOrRef>>, + function_pointers: OwnedOrRef>>, } // TODO: fix the underlying cause instead @@ -148,7 +151,7 @@ impl Instance { } /// Same as `new`, but allows specifying a loader where to load Vulkan from. - pub fn with_loader<'a, L, Ext>(loader: FunctionPointers>, + pub fn with_loader<'a, L, Ext>(loader: FunctionPointers>, app_infos: Option<&ApplicationInfo>, extensions: Ext, layers: L) -> Result, InstanceCreationError> where L: IntoIterator, @@ -167,7 +170,7 @@ impl Instance { fn new_inner(app_infos: Option<&ApplicationInfo>, extensions: RawInstanceExtensions, layers: SmallVec<[CString; 16]>, - function_pointers: OwnedOrRef>>) + function_pointers: OwnedOrRef>>) -> Result, InstanceCreationError> { // TODO: For now there are still buggy drivers that will segfault if you don't pass any // appinfos. Therefore for now we ensure that it can't be `None`. @@ -221,7 +224,7 @@ impl Instance { .unwrap_or(0), apiVersion: Version { major: 1, - minor: 0, + minor: 1, patch: 0, }.into_vulkan_version(), // TODO: }) @@ -243,7 +246,7 @@ impl Instance { // Creating the Vulkan instance. let instance = unsafe { - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); let infos = vk::InstanceCreateInfo { sType: vk::STRUCTURE_TYPE_INSTANCE_CREATE_INFO, pNext: ptr::null(), @@ -260,8 +263,8 @@ impl Instance { }; let entry_points = function_pointers.entry_points(); - check_errors(entry_points.CreateInstance(&infos, ptr::null(), &mut output))?; - output + check_errors(entry_points.CreateInstance(&infos, ptr::null(), output.as_mut_ptr()))?; + output.assume_init() }; // Loading the function pointers of the newly-created instance. @@ -282,12 +285,11 @@ impl Instance { devices }; - // TODO: should be Into - let extensions: InstanceExtensions = (&extensions).into(); + let vk_khr_get_physical_device_properties2 = CString::new(b"VK_KHR_get_physical_device_properties2".to_vec()).unwrap(); // Getting the properties of all physical devices. // If possible, we use VK_KHR_get_physical_device_properties2. - let physical_devices = if extensions.khr_get_physical_device_properties2 { + let physical_devices = if extensions.iter().any(|v| *v == vk_khr_get_physical_device_properties2) { Instance::init_physical_devices2(&vk, physical_devices, &extensions) } else { Instance::init_physical_devices(&vk, physical_devices) @@ -311,9 +313,9 @@ impl Instance { for device in physical_devices.into_iter() { let properties: vk::PhysicalDeviceProperties = unsafe { - let mut output = mem::uninitialized(); - vk.GetPhysicalDeviceProperties(device, &mut output); - output + let mut output = MaybeUninit::uninit(); + vk.GetPhysicalDeviceProperties(device, output.as_mut_ptr()); + output.assume_init() }; let queue_families = unsafe { @@ -327,15 +329,15 @@ impl Instance { }; let memory: vk::PhysicalDeviceMemoryProperties = unsafe { - let mut output = mem::uninitialized(); - vk.GetPhysicalDeviceMemoryProperties(device, &mut output); - output + let mut output = MaybeUninit::uninit(); + vk.GetPhysicalDeviceMemoryProperties(device, output.as_mut_ptr()); + output.assume_init() }; let available_features: vk::PhysicalDeviceFeatures = unsafe { - let mut output = mem::uninitialized(); - vk.GetPhysicalDeviceFeatures(device, &mut output); - output + let mut output = MaybeUninit::uninit(); + vk.GetPhysicalDeviceFeatures(device, output.as_mut_ptr()); + output.assume_init() }; output.push(PhysicalDeviceInfos { @@ -353,7 +355,7 @@ impl Instance { /// TODO: Query extension-specific physical device properties, once a new instance extension is supported. fn init_physical_devices2(vk: &vk::InstancePointers, physical_devices: Vec, - extensions: &InstanceExtensions) + extensions: &RawInstanceExtensions) -> Vec { let mut output = Vec::with_capacity(physical_devices.len()); @@ -362,7 +364,7 @@ impl Instance { let mut output = vk::PhysicalDeviceProperties2KHR { sType: vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR, pNext: ptr::null_mut(), - properties: mem::uninitialized(), + properties: mem::zeroed(), }; vk.GetPhysicalDeviceProperties2KHR(device, &mut output); @@ -378,7 +380,7 @@ impl Instance { vk::QueueFamilyProperties2KHR { sType: vk::STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR, pNext: ptr::null_mut(), - queueFamilyProperties: mem::uninitialized(), + queueFamilyProperties: mem::zeroed(), } }) .collect::>(); @@ -396,7 +398,7 @@ impl Instance { let mut output = vk::PhysicalDeviceMemoryProperties2KHR { sType: vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR, pNext: ptr::null_mut(), - memoryProperties: mem::uninitialized(), + memoryProperties: mem::zeroed(), }; vk.GetPhysicalDeviceMemoryProperties2KHR(device, &mut output); output.memoryProperties @@ -406,7 +408,7 @@ impl Instance { let mut output = vk::PhysicalDeviceFeatures2KHR { sType: vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR, pNext: ptr::null_mut(), - features: mem::uninitialized(), + features: mem::zeroed(), }; vk.GetPhysicalDeviceFeatures2KHR(device, &mut output); output.features @@ -449,10 +451,15 @@ impl Instance { /// /// let extensions = InstanceExtensions::supported_by_core().unwrap(); /// let instance = Instance::new(None, &extensions, None).unwrap(); - /// assert_eq!(instance.loaded_extensions(), &extensions); + /// assert_eq!(instance.loaded_extensions(), extensions); /// ``` #[inline] - pub fn loaded_extensions(&self) -> &InstanceExtensions { + pub fn loaded_extensions(&self) -> InstanceExtensions { + InstanceExtensions::from(&self.extensions) + } + + #[inline] + pub fn raw_loaded_extensions(&self) -> &RawInstanceExtensions { &self.extensions } @@ -474,7 +481,7 @@ impl fmt::Debug for Instance { unsafe impl VulkanObject for Instance { type Object = vk::Instance; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_INSTANCE; #[inline] fn internal_object(&self) -> vk::Instance { @@ -491,6 +498,22 @@ impl Drop for Instance { } } +impl PartialEq for Instance { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.instance == other.instance + } +} + +impl Eq for Instance {} + +impl Hash for Instance { + #[inline] + fn hash(&self, state: &mut H) { + self.instance.hash(state); + } +} + // Same as Cow but less annoying. enum OwnedOrRef { Owned(T), @@ -619,7 +642,7 @@ impl error::Error for InstanceCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { InstanceCreationError::LoadingError(ref err) => Some(err), InstanceCreationError::OomError(ref err) => Some(err), @@ -948,7 +971,7 @@ impl<'a> PhysicalDevice<'a> { unsafe impl<'a> VulkanObject for PhysicalDevice<'a> { type Object = vk::PhysicalDevice; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PHYSICAL_DEVICE; #[inline] fn internal_object(&self) -> vk::PhysicalDevice { @@ -1073,15 +1096,13 @@ impl<'a> QueueFamily<'a> { } /// Returns true if queues of this family can execute transfer operations. - /// - /// > **Note**: Queues that support graphics or compute operations also always support transfer - /// > operations. As of writing this, this function will always return true. The purpose of - /// > this function is to be future-proofed in case queues that don't support transfer - /// > operations are ever added to Vulkan. + /// > **Note**: While all queues that can perform graphics or compute operations can implicitly perform + /// > transfer operations, graphics & compute queues only optionally indicate support for tranfers. + /// > Many discrete cards will have one queue family that exclusively sets the VK_QUEUE_TRANSFER_BIT + /// > to indicate a special relationship with the DMA module and more efficient transfers. #[inline] - pub fn supports_transfers(&self) -> bool { - (self.flags() & vk::QUEUE_TRANSFER_BIT) != 0 || self.supports_graphics() || - self.supports_compute() + pub fn explicitly_supports_transfers(&self) -> bool { + (self.flags() & vk::QUEUE_TRANSFER_BIT) != 0 } /// Returns true if queues of this family can execute sparse resources binding operations. @@ -1097,6 +1118,14 @@ impl<'a> QueueFamily<'a> { } } +impl<'a> PartialEq for QueueFamily<'a> { + fn eq(&self, other: &Self) -> bool { + self.id == other.id && self.physical_device.internal_object() == other.physical_device.internal_object() + } +} + +impl<'a> Eq for QueueFamily<'a> { } + /// Iterator for all the queue families available on a physical device. #[derive(Debug, Clone)] pub struct QueueFamiliesIter<'a> { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/layers.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/layers.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/layers.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/layers.rs index f6e8e7a..e67a02a 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/layers.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/layers.rs @@ -180,7 +180,7 @@ impl error::Error for LayersListError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { LayersListError::LoadingError(ref err) => Some(err), LayersListError::OomError(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/limits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/limits.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/limits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/limits.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/loader.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/loader.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/loader.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/loader.rs index 80d7218..64b8f53 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/loader.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/loader.rs @@ -169,7 +169,7 @@ macro_rules! statically_linked_vulkan_loader { /// `lazy_static!`. The content of the lazy_static is then returned, or an error if we failed to /// load Vulkan. pub fn auto_loader() - -> Result<&'static FunctionPointers>, LoadingError> + -> Result<&'static FunctionPointers>, LoadingError> { #[cfg(target_os = "ios")] #[allow(non_snake_case)] @@ -179,7 +179,7 @@ pub fn auto_loader() } #[cfg(not(target_os = "ios"))] - fn def_loader_impl() -> Result, LoadingError> { + fn def_loader_impl() -> Result, LoadingError> { #[cfg(windows)] fn get_path() -> &'static Path { Path::new("vulkan-1.dll") @@ -203,7 +203,7 @@ pub fn auto_loader() } lazy_static! { - static ref DEFAULT_LOADER: Result>, LoadingError> = { + static ref DEFAULT_LOADER: Result>, LoadingError> = { def_loader_impl().map(FunctionPointers::new) }; } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/instance/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/instance/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/instance/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/instance/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/lib.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/lib.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/lib.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/lib.rs index 120e705..d2cf382 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/lib.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/lib.rs @@ -128,8 +128,8 @@ pub unsafe trait VulkanObject { /// The type of the object. type Object: VulkanHandle; - /// The `DebugReportObjectTypeEXT` of the internal Vulkan handle. - const TYPE: vk::DebugReportObjectTypeEXT; + /// The `ObjectType` of the internal Vulkan handle. + const TYPE: vk::ObjectType; /// Returns a reference to the object. fn internal_object(&self) -> Self::Object; @@ -220,6 +220,7 @@ pub(crate) enum Error { IncompatibleDisplay = vk::ERROR_INCOMPATIBLE_DISPLAY_KHR, ValidationFailed = vk::ERROR_VALIDATION_FAILED_EXT, OutOfPoolMemory = vk::ERROR_OUT_OF_POOL_MEMORY_KHR, + FullscreenExclusiveLost = vk::ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT, } /// Checks whether the result returned correctly. @@ -249,6 +250,7 @@ fn check_errors(result: vk::Result) -> Result { vk::ERROR_INCOMPATIBLE_DISPLAY_KHR => Err(Error::IncompatibleDisplay), vk::ERROR_VALIDATION_FAILED_EXT => Err(Error::ValidationFailed), vk::ERROR_OUT_OF_POOL_MEMORY_KHR => Err(Error::OutOfPoolMemory), + vk::ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT => Err(Error::FullscreenExclusiveLost), vk::ERROR_INVALID_SHADER_NV => panic!("Vulkan function returned \ VK_ERROR_INVALID_SHADER_NV"), c => unreachable!("Unexpected error code returned by Vulkan: {}", c), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/device_memory.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/device_memory.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/device_memory.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/device_memory.rs index ab9958a..9edea88 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/device_memory.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/device_memory.rs @@ -9,7 +9,7 @@ use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ops::Deref; use std::ops::DerefMut; use std::ops::Range; @@ -134,13 +134,13 @@ impl DeviceMemory { memoryTypeIndex: memory_type.id(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.AllocateMemory(device.internal_object(), &infos, ptr::null(), - &mut output))?; + output.as_mut_ptr()))?; *allocation_count += 1; - output + output.assume_init() }; Ok(DeviceMemory { @@ -176,14 +176,14 @@ impl DeviceMemory { let coherent = memory_type.is_host_coherent(); let ptr = unsafe { - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.MapMemory(device.internal_object(), mem.memory, 0, mem.size as vk::DeviceSize, 0, /* reserved flags */ - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(MappedDeviceMemory { @@ -229,7 +229,7 @@ impl fmt::Debug for DeviceMemory { unsafe impl VulkanObject for DeviceMemory { type Object = vk::DeviceMemory; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DEVICE_MEMORY; #[inline] fn internal_object(&self) -> vk::DeviceMemory { @@ -482,7 +482,7 @@ impl error::Error for DeviceMemoryAllocError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { DeviceMemoryAllocError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/host_visible.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/host_visible.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/host_visible.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/host_visible.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/non_host_visible.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/non_host_visible.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/non_host_visible.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/non_host_visible.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/pool.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/pool.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/memory/pool/pool.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/memory/pool/pool.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/blend.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/blend.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/blend.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/blend.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/cache.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/cache.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/cache.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/cache.rs index 8ef7fa2..e837557 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/cache.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/cache.rs @@ -23,7 +23,7 @@ //! on the disk, and [`with_data`](struct.PipelineCache.html#method.with_data) for how to reload it. //! -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -119,12 +119,12 @@ impl PipelineCache { .unwrap_or(ptr::null()), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreatePipelineCache(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(PipelineCache { @@ -219,7 +219,7 @@ impl PipelineCache { unsafe impl VulkanObject for PipelineCache { type Object = vk::PipelineCache; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE_CACHE; #[inline] fn internal_object(&self) -> vk::PipelineCache { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/compute_pipeline.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/compute_pipeline.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/compute_pipeline.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/compute_pipeline.rs index 2db5164..7679084 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/compute_pipeline.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/compute_pipeline.rs @@ -11,6 +11,7 @@ use std::error; use std::fmt; use std::marker::PhantomData; use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -138,14 +139,14 @@ impl ComputePipeline { basePipelineIndex: 0, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateComputePipelines(device.internal_object(), 0, 1, &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(ComputePipeline { @@ -212,7 +213,7 @@ pub struct ComputePipelineSys<'a>(vk::Pipeline, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for ComputePipelineSys<'a> { type Object = vk::Pipeline; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE; #[inline] fn internal_object(&self) -> vk::Pipeline { @@ -274,7 +275,7 @@ unsafe impl DeviceOwned for ComputePipeline { unsafe impl VulkanObject for ComputePipeline { type Object = vk::Pipeline; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE; #[inline] fn internal_object(&self) -> vk::Pipeline { @@ -316,7 +317,7 @@ impl error::Error for ComputePipelineCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { ComputePipelineCreationError::OomError(ref err) => Some(err), ComputePipelineCreationError::PipelineLayoutCreationError(ref err) => Some(err), @@ -378,6 +379,7 @@ mod tests { use descriptor::descriptor::DescriptorDescTy; use descriptor::descriptor::ShaderStages; use descriptor::descriptor_set::PersistentDescriptorSet; + use descriptor::pipeline_layout::PipelineLayoutAbstract; use descriptor::pipeline_layout::PipelineLayoutDesc; use descriptor::pipeline_layout::PipelineLayoutDescPcRange; use pipeline::ComputePipeline; @@ -967,9 +969,10 @@ mod tests { &SpecConsts { VALUE: 0x12345678 }) .unwrap()); - let data_buffer = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), 0) + let data_buffer = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), false, 0) .unwrap(); - let set = PersistentDescriptorSet::start(pipeline.clone(), 0) + let layout = pipeline.layout().descriptor_set_layout(0).unwrap(); + let set = PersistentDescriptorSet::start(layout.clone()) .add_buffer(data_buffer.clone()) .unwrap() .build() @@ -978,7 +981,7 @@ mod tests { let command_buffer = AutoCommandBufferBuilder::primary_one_time_submit(device.clone(), queue.family()) .unwrap() - .dispatch([1, 1, 1], pipeline, set, ()) + .dispatch([1, 1, 1], pipeline.clone(), set, ()) .unwrap() .build() .unwrap(); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/depth_stencil.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/depth_stencil.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/depth_stencil.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/depth_stencil.rs index e871100..e69558d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/depth_stencil.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/depth_stencil.rs @@ -172,6 +172,22 @@ pub enum StencilOp { DecrementAndWrap = vk::STENCIL_OP_DECREMENT_AND_WRAP, } +/// Enum to specify which stencil state to use +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[repr(u32)] +pub enum StencilFaceFlags { + StencilFaceFrontBit = vk::STENCIL_FACE_FRONT_BIT, + StencilFaceBackBit = vk::STENCIL_FACE_BACK_BIT, + StencilFrontAndBack = vk::STENCIL_FRONT_AND_BACK, +} + +/// Container for dynamic StencilFaceFlags and value +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct DynamicStencilValue { + pub face: StencilFaceFlags, + pub value: u32, +} + /// Allows you to ask the GPU to exclude fragments that are outside of a certain range. #[derive(Debug, Clone, PartialEq)] pub enum DepthBounds { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/builder.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/builder.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/builder.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/builder.rs index 970a52c..576cee7 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/builder.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/builder.rs @@ -13,6 +13,7 @@ use smallvec::SmallVec; use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; use std::u32; @@ -156,7 +157,7 @@ impl /// Builds the graphics pipeline, using an inferred a pipeline layout. // TODO: replace Box with a PipelineUnion struct without template params pub fn build(self, device: Arc) - -> Result, Rp>, + -> Result, Rp>, GraphicsPipelineCreationError> { self.with_auto_layout(device, &[]) } @@ -166,7 +167,7 @@ impl /// Configures the inferred layout for each descriptor `(set, binding)` in `dynamic_buffers` to accept dynamic /// buffers. pub fn with_auto_layout(self, device: Arc, dynamic_buffers: &[(usize, usize)]) - -> Result, Rp>, + -> Result, Rp>, GraphicsPipelineCreationError> { let pipeline_layout; @@ -1072,16 +1073,23 @@ impl basePipelineIndex: -1, // TODO: }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateGraphicsPipelines(device.internal_object(), 0, 1, &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; + // Some drivers return `VK_SUCCESS` but provide a null handle if they + // fail to create the pipeline (due to invalid shaders, etc) + // This check ensures that we don't create an invalid `GraphicsPipeline` instance + if pipeline == vk::NULL_HANDLE { + panic!("vkCreateGraphicsPipelines provided a NULL handle"); + } + let (render_pass, render_pass_subpass) = self.render_pass.take().unwrap().into(); Ok(GraphicsPipeline { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/creation_error.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/creation_error.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/creation_error.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/creation_error.rs index d6a1742..7d4f655 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/creation_error.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/creation_error.rs @@ -323,7 +323,7 @@ impl error::Error for GraphicsPipelineCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { GraphicsPipelineCreationError::OomError(ref err) => Some(err), GraphicsPipelineCreationError::IncompatiblePipelineLayout(ref err) => Some(err), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/mod.rs similarity index 88% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/mod.rs index ff28620..465719c 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/mod.rs @@ -8,6 +8,8 @@ // according to those terms. use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::marker::PhantomData; use std::ptr; use std::sync::Arc; @@ -74,6 +76,7 @@ pub struct GraphicsPipeline { num_viewports: u32, } +#[derive(PartialEq, Eq, Hash)] struct Inner { pipeline: vk::Pipeline, device: Arc, @@ -294,7 +297,7 @@ unsafe impl RenderPassDescClearValues for GraphicsPipeline { #[inline] - fn convert_clear_values(&self, vals: C) -> Box> { + fn convert_clear_values(&self, vals: C) -> Box> { self.render_pass.convert_clear_values(vals) } } @@ -302,7 +305,7 @@ unsafe impl RenderPassDescClearValues for GraphicsPipeline VulkanObject for GraphicsPipeline { type Object = vk::Pipeline; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE; #[inline] fn internal_object(&self) -> vk::Pipeline { @@ -324,7 +327,7 @@ impl Drop for Inner { /// object. /// When using this trait `AutoCommandBufferBuilder::draw*` calls will need the buffers to be /// wrapped in a `vec!()`. -pub unsafe trait GraphicsPipelineAbstract: PipelineLayoutAbstract + RenderPassAbstract + VertexSource>> { +pub unsafe trait GraphicsPipelineAbstract: PipelineLayoutAbstract + RenderPassAbstract + VertexSource>> + DeviceOwned { /// Returns an opaque object that represents the inside of the graphics pipeline. fn inner(&self) -> GraphicsPipelineSys; @@ -366,7 +369,7 @@ pub unsafe trait GraphicsPipelineAbstract: PipelineLayoutAbstract + RenderPassAb unsafe impl GraphicsPipelineAbstract for GraphicsPipeline where L: PipelineLayoutAbstract, Rp: RenderPassAbstract, - Mv: VertexSource>> + Mv: VertexSource>> { #[inline] fn inner(&self) -> GraphicsPipelineSys { @@ -474,6 +477,52 @@ unsafe impl GraphicsPipelineAbstract for T } } +impl PartialEq for GraphicsPipeline + where L: PipelineLayoutAbstract, + Rp: RenderPassAbstract, + Mv: VertexSource>> +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner == other.inner + } +} + +impl Eq for GraphicsPipeline + where L: PipelineLayoutAbstract, + Rp: RenderPassAbstract, + Mv: VertexSource>> +{} + +impl Hash for GraphicsPipeline + where L: PipelineLayoutAbstract, + Rp: RenderPassAbstract, + Mv: VertexSource>> +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner.hash(state); + } +} + +impl PartialEq for dyn GraphicsPipelineAbstract + Send + Sync { + #[inline] + fn eq(&self, other: &Self) -> bool { + GraphicsPipelineAbstract::inner(self).0 == GraphicsPipelineAbstract::inner(other).0 && + DeviceOwned::device(self) == DeviceOwned::device(other) + } +} + +impl Eq for dyn GraphicsPipelineAbstract + Send + Sync {} + +impl Hash for dyn GraphicsPipelineAbstract + Send + Sync { + #[inline] + fn hash(&self, state: &mut H) { + GraphicsPipelineAbstract::inner(self).0.hash(state); + DeviceOwned::device(self).hash(state); + } +} + /// Opaque object that represents the inside of the graphics pipeline. #[derive(Debug, Copy, Clone)] pub struct GraphicsPipelineSys<'a>(vk::Pipeline, PhantomData<&'a ()>); @@ -481,7 +530,7 @@ pub struct GraphicsPipelineSys<'a>(vk::Pipeline, PhantomData<&'a ()>); unsafe impl<'a> VulkanObject for GraphicsPipelineSys<'a> { type Object = vk::Pipeline; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_PIPELINE; #[inline] fn internal_object(&self) -> vk::Pipeline { @@ -507,7 +556,7 @@ unsafe impl VertexSource for GraphicsPipeline where Mv: VertexSource { #[inline] - fn decode(&self, s: S) -> (Vec>, usize, usize) { + fn decode(&self, s: S) -> (Vec>, usize, usize) { self.vertex_definition.decode(s) } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/tests.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/tests.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/graphics_pipeline/tests.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/graphics_pipeline/tests.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/input_assembly.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/input_assembly.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/input_assembly.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/input_assembly.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/multisample.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/multisample.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/multisample.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/multisample.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/raster.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/raster.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/raster.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/raster.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/shader.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/shader.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/shader.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/shader.rs index ec652db..3e6a81e 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/shader.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/shader.rs @@ -25,6 +25,7 @@ use std::iter; use std::iter::Empty as EmptyIter; use std::marker::PhantomData; use std::mem; +use std::mem::MaybeUninit; use std::ops::Range; use std::ptr; use std::sync::Arc; @@ -99,12 +100,12 @@ impl ShaderModule { }; let vk = device.pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateShaderModule(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(ShaderModule { @@ -166,7 +167,7 @@ impl ShaderModule { unsafe impl VulkanObject for ShaderModule { type Object = vk::ShaderModule; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_SHADER_MODULE; #[inline] fn internal_object(&self) -> vk::ShaderModule { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/bufferless.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/bufferless.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/bufferless.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/bufferless.rs index 4d718c7..277a925 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/bufferless.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/bufferless.rs @@ -33,14 +33,14 @@ pub struct BufferlessVertices { unsafe impl VertexSource for BufferlessDefinition { fn decode(&self, n: BufferlessVertices) - -> (Vec>, usize, usize) { + -> (Vec>, usize, usize) { (Vec::new(), n.vertices, n.instances) } } unsafe impl VertexSource> for BufferlessDefinition { fn decode<'l>(&self, _: Vec) - -> (Vec>, usize, usize) { + -> (Vec>, usize, usize) { panic!("bufferless drawing should not be supplied with buffers") } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/definition.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/definition.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/definition.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/definition.rs index 12fe672..24256e0 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/definition.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/definition.rs @@ -19,7 +19,7 @@ use vk; /// Trait for types that describe the definition of the vertex input used by a graphics pipeline. pub unsafe trait VertexDefinition - : VertexSource>> { + : VertexSource>> { /// Iterator that returns the offset, the stride (in bytes) and input rate of each buffer. type BuffersIter: ExactSizeIterator; /// Iterator that returns the attribute location, buffer id, and infos. @@ -114,7 +114,7 @@ pub unsafe trait VertexSource { // TODO: return error if problem // TODO: better than a Vec // TODO: return a struct instead - fn decode(&self, L) -> (Vec>, usize, usize); + fn decode(&self, L) -> (Vec>, usize, usize); } unsafe impl VertexSource for T @@ -122,7 +122,7 @@ unsafe impl VertexSource for T T::Target: VertexSource { #[inline] - fn decode(&self, list: L) -> (Vec>, usize, usize) { + fn decode(&self, list: L) -> (Vec>, usize, usize) { (**self).decode(list) } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/impl_vertex.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/impl_vertex.rs similarity index 86% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/impl_vertex.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/impl_vertex.rs index 0077a92..21bc592 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/impl_vertex.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/impl_vertex.rs @@ -10,7 +10,18 @@ use pipeline::vertex::VertexMemberTy; /// Implements the `Vertex` trait on a struct. -// TODO: add example +///# Example +/// +///``` +///#[derive(Default, Copy, Clone)] +///struct Vertex{ +/// position: [f32; 3], +/// color: [f32; 4] +///} +/// +///vulkano::impl_vertex!(Vertex, position, color); +/// +///``` #[macro_export] macro_rules! impl_vertex { ($out:ty $(, $member:ident)*) => ( @@ -27,20 +38,15 @@ macro_rules! impl_vertex { $( if name == stringify!($member) { - let (ty, array_size) = unsafe { - #[inline] fn f(_: &T) -> (VertexMemberTy, usize) - { T::format() } - let dummy: *const $out = ptr::null(); - f(&(&*dummy).$member) - }; + let dummy = <$out>::default(); + #[inline] fn f(_: &T) -> (VertexMemberTy, usize) { T::format() } + let (ty, array_size) = f(&dummy.$member); + + let dummy_ptr = (&dummy) as *const _; + let member_ptr = (&dummy.$member) as *const _; return Some(VertexMemberInfo { - offset: unsafe { - let dummy: *const $out = ptr::null(); - let member = (&(&*dummy).$member) as *const _; - member as usize - }, - + offset: member_ptr as usize - dummy_ptr as usize, ty: ty, array_size: array_size, }); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/instance_buffer.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/instance_buffer.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/instance_buffer.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/instance_buffer.rs index 70b4947..0b4e693 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/instance_buffer.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/instance_buffer.rs @@ -92,7 +92,7 @@ where } } -unsafe impl VertexSource>> +unsafe impl VertexSource>> for SingleInstanceBufferDefinition where V: Vertex, @@ -100,8 +100,8 @@ where #[inline] fn decode( &self, - mut source: Vec>, - ) -> (Vec>, usize, usize) { + mut source: Vec>, + ) -> (Vec>, usize, usize) { // FIXME: safety assert_eq!(source.len(), 1); let len = source[0].size() / mem::size_of::(); @@ -115,7 +115,7 @@ where V: Vertex, { #[inline] - fn decode(&self, source: B) -> (Vec>, usize, usize) { + fn decode(&self, source: B) -> (Vec>, usize, usize) { let len = source.len(); (vec![Box::new(source) as Box<_>], 1, len) } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/one_one.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/one_one.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/one_one.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/one_one.rs index ce00a44..d5512e9 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/one_one.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/one_one.rs @@ -93,14 +93,14 @@ unsafe impl VertexDefinition for OneVertexOneInstanceDefinition VertexSource>> +unsafe impl VertexSource>> for OneVertexOneInstanceDefinition where T: Vertex, U: Vertex { #[inline] - fn decode(&self, mut source: Vec>) - -> (Vec>, usize, usize) { + fn decode(&self, mut source: Vec>) + -> (Vec>, usize, usize) { // FIXME: safety assert_eq!(source.len(), 2); let len = source[0].size() / mem::size_of::(); @@ -118,7 +118,7 @@ unsafe impl<'a, T, U, Bt, Bu> VertexSource<(Bt, Bu)> for OneVertexOneInstanceDef Bu: TypedBufferAccess + Send + Sync + 'static { #[inline] - fn decode(&self, source: (Bt, Bu)) -> (Vec>, usize, usize) { + fn decode(&self, source: (Bt, Bu)) -> (Vec>, usize, usize) { let s1l = source.0.len(); let s2l = source.1.len(); (vec![Box::new(source.0) as Box<_>, Box::new(source.1) as Box<_>], s1l, s2l) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/single.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/single.rs similarity index 91% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/single.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/single.rs index e56ab26..b4ae0e1 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/single.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/single.rs @@ -85,12 +85,12 @@ unsafe impl VertexDefinition for SingleBufferDefinition } } -unsafe impl VertexSource>> for SingleBufferDefinition +unsafe impl VertexSource>> for SingleBufferDefinition where V: Vertex { #[inline] - fn decode(&self, mut source: Vec>) - -> (Vec>, usize, usize) { + fn decode(&self, mut source: Vec>) + -> (Vec>, usize, usize) { // FIXME: safety assert_eq!(source.len(), 1); let len = source[0].size() / mem::size_of::(); @@ -103,7 +103,7 @@ unsafe impl<'a, B, V> VertexSource for SingleBufferDefinition V: Vertex { #[inline] - fn decode(&self, source: B) -> (Vec>, usize, usize) { + fn decode(&self, source: B) -> (Vec>, usize, usize) { let len = source.len(); (vec![Box::new(source) as Box<_>], len, 1) } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/two.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/two.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/two.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/two.rs index 3c48eff..7881c31 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/two.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/two.rs @@ -93,13 +93,13 @@ unsafe impl VertexDefinition for TwoBuffersDefinition } } -unsafe impl VertexSource>> for TwoBuffersDefinition +unsafe impl VertexSource>> for TwoBuffersDefinition where T: Vertex, U: Vertex { #[inline] - fn decode(&self, source: Vec>) - -> (Vec>, usize, usize) { + fn decode(&self, source: Vec>) + -> (Vec>, usize, usize) { // FIXME: safety assert_eq!(source.len(), 2); let vertices = [ @@ -120,7 +120,7 @@ unsafe impl<'a, T, U, Bt, Bu> VertexSource<(Bt, Bu)> for TwoBuffersDefinition + Send + Sync + 'static { #[inline] - fn decode(&self, source: (Bt, Bu)) -> (Vec>, usize, usize) { + fn decode(&self, source: (Bt, Bu)) -> (Vec>, usize, usize) { let vertices = [source.0.len(), source.1.len()] .iter() .cloned() diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/vertex.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/vertex.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/vertex/vertex.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/vertex/vertex.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/viewport.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/viewport.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/pipeline/viewport.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/pipeline/viewport.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/query/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/query/mod.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/query/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/query/mod.rs index 8268356..0561e4d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/query/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/query/mod.rs @@ -15,7 +15,7 @@ use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -60,13 +60,13 @@ impl UnsafeQueryPool { pipelineStatistics: statistics, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); let vk = device.pointers(); check_errors(vk.CreateQueryPool(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(UnsafeQueryPool { @@ -114,7 +114,7 @@ impl UnsafeQueryPool { unsafe impl VulkanObject for UnsafeQueryPool { type Object = vk::QueryPool; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_QUERY_POOL; #[inline] fn internal_object(&self) -> vk::QueryPool { @@ -282,7 +282,7 @@ impl error::Error for QueryPoolCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { QueryPoolCreationError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sampler.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sampler.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sampler.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sampler.rs index 06c8ccb..d90c05e 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sampler.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sampler.rs @@ -64,7 +64,7 @@ use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -316,12 +316,12 @@ impl Sampler { unnormalizedCoordinates: vk::FALSE, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateSampler(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Sampler { @@ -403,12 +403,12 @@ impl Sampler { unnormalizedCoordinates: vk::TRUE, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateSampler(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Sampler { @@ -482,7 +482,7 @@ unsafe impl DeviceOwned for Sampler { unsafe impl VulkanObject for Sampler { type Object = vk::Sampler; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_SAMPLER; #[inline] fn internal_object(&self) -> vk::Sampler { @@ -699,7 +699,7 @@ impl error::Error for SamplerCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SamplerCreationError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/capabilities.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/capabilities.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/capabilities.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/capabilities.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/display.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/display.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/display.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/display.rs index 46a62d3..a614256 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/display.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/display.rs @@ -310,7 +310,7 @@ impl Display { unsafe impl VulkanObject for Display { type Object = vk::DisplayKHR; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DISPLAY_KHR; #[inline] fn internal_object(&self) -> vk::DisplayKHR { @@ -344,9 +344,9 @@ impl DisplayMode { }; let mut output = mem::uninitialized(); - try!(check_errors(vk.CreateDisplayModeKHR(display.device.internal_object(), + check_errors(vk.CreateDisplayModeKHR(display.device.internal_object(), display.display, &infos, ptr::null(), - &mut output))); + &mut output))?; output }; @@ -380,7 +380,7 @@ impl DisplayMode { unsafe impl VulkanObject for DisplayMode { type Object = vk::DisplayModeKHR; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_DISPLAY_MODE_KHR; #[inline] fn internal_object(&self) -> vk::DisplayModeKHR { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/mod.rs similarity index 94% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/mod.rs index baa38f9..22b9567 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/mod.rs @@ -165,19 +165,20 @@ //! # use vulkano::image::ImageUsage; //! # use vulkano::sync::SharingMode; //! # use vulkano::format::Format; -//! # use vulkano::swapchain::{Surface, Swapchain, SurfaceTransform, PresentMode, CompositeAlpha}; +//! # use vulkano::swapchain::{Surface, Swapchain, SurfaceTransform, PresentMode, CompositeAlpha, ColorSpace, FullscreenExclusive}; //! # fn create_swapchain( //! # device: Arc, surface: Arc>, present_queue: Arc, //! # buffers_count: u32, format: Format, dimensions: [u32; 2], -//! # surface_transform: SurfaceTransform, composite_alpha: CompositeAlpha, present_mode: PresentMode -//! # ) -> Result<(), Box> { +//! # surface_transform: SurfaceTransform, composite_alpha: CompositeAlpha, +//! # present_mode: PresentMode, fullscreen_exclusive: FullscreenExclusive +//! # ) -> Result<(), Box> { //! // The created swapchain will be used as a color attachment for rendering. //! let usage = ImageUsage { //! color_attachment: true, //! .. ImageUsage::none() //! }; //! -//! let sharing_mode = SharingMode::Exclusive(present_queue.family().id()); +//! let sharing_mode = SharingMode::Exclusive; //! //! // Create the swapchain and its buffers. //! let (swapchain, buffers) = Swapchain::new( @@ -203,10 +204,12 @@ //! composite_alpha, //! // How to present images. //! present_mode, +//! // How to handle fullscreen exclusivity +//! fullscreen_exclusive, //! // Clip the parts of the buffer which aren't visible. //! true, //! // No previous swapchain. -//! None +//! ColorSpace::SrgbNonLinear //! )?; //! //! # Ok(()) @@ -239,7 +242,7 @@ //! // let mut (swapchain, images) = Swapchain::new(...); //! loop { //! # let mut command_buffer: ::vulkano::command_buffer::AutoCommandBuffer<()> = return; -//! let (image_num, acquire_future) +//! let (image_num, suboptimal, acquire_future) //! = swapchain::acquire_next_image(swapchain.clone(), None).unwrap(); //! //! // The command_buffer contains the draw commands that modify the framebuffer @@ -262,7 +265,6 @@ //! rendering, you will need to *recreate* the swapchain by creating a new swapchain and passing //! as last parameter the old swapchain. //! -//! TODO: suboptimal stuff //! //! ``` //! use vulkano::swapchain; @@ -276,13 +278,13 @@ //! //! loop { //! if recreate_swapchain { -//! swapchain = swapchain.0.recreate_with_dimension([1024, 768]).unwrap(); +//! swapchain = swapchain.0.recreate_with_dimensions([1024, 768]).unwrap(); //! recreate_swapchain = false; //! } //! //! let (ref swapchain, ref _images) = swapchain; //! -//! let (index, acq_future) = match swapchain::acquire_next_image(swapchain.clone(), None) { +//! let (index, suboptimal, acq_future) = match swapchain::acquire_next_image(swapchain.clone(), None) { //! Ok(r) => r, //! Err(AcquireError::OutOfDate) => { recreate_swapchain = true; continue; }, //! Err(err) => panic!("{:?}", err) @@ -294,6 +296,10 @@ //! // .then_execute(...) //! .then_swapchain_present(queue.clone(), swapchain.clone(), index) //! .then_signal_fence_and_flush().unwrap(); // TODO: PresentError? +//! +//! if suboptimal { +//! recreate_swapchain = true; +//! } //! } //! ``` //! @@ -326,6 +332,8 @@ pub use self::swapchain::acquire_next_image; pub use self::swapchain::acquire_next_image_raw; pub use self::swapchain::present; pub use self::swapchain::present_incremental; +pub use self::swapchain::FullscreenExclusive; +pub use self::swapchain::FullscreenExclusiveError; mod capabilities; pub mod display; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/present_region.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/present_region.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/present_region.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/present_region.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/surface.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/surface.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/surface.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/surface.rs index bfb676c..20bfb24 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/surface.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/surface.rs @@ -9,7 +9,7 @@ use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::os::raw::c_ulong; use std::ptr; use std::sync::Arc; @@ -105,12 +105,12 @@ impl Surface { }, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateDisplayPlaneSurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -148,12 +148,12 @@ impl Surface { hwnd: hwnd as *mut _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateWin32SurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -190,12 +190,12 @@ impl Surface { window: window, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateXcbSurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -232,12 +232,12 @@ impl Surface { window: window, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateXlibSurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -275,12 +275,12 @@ impl Surface { surface: surface as *mut _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateWaylandSurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -314,12 +314,12 @@ impl Surface { window: window as *mut _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateAndroidSurfaceKHR(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -354,12 +354,12 @@ impl Surface { pView: view as *const _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateIOSSurfaceMVK(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -394,12 +394,12 @@ impl Surface { pView: view as *const _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateMacOSSurfaceMVK(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -433,12 +433,12 @@ impl Surface { window: window as *mut _, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateViSurfaceNN(instance.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Arc::new(Surface { @@ -455,14 +455,14 @@ impl Surface { unsafe { let vk = self.instance.pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.GetPhysicalDeviceSurfaceSupportKHR(queue .physical_device() .internal_object(), queue.id(), self.surface, - &mut output))?; - Ok(output != 0) + output.as_mut_ptr()))?; + Ok(output.assume_init() != 0) } } @@ -481,11 +481,11 @@ impl Surface { let vk = self.instance.pointers(); let caps = { - let mut out: vk::SurfaceCapabilitiesKHR = mem::uninitialized(); + let mut out: MaybeUninit = MaybeUninit::uninit(); check_errors(vk.GetPhysicalDeviceSurfaceCapabilitiesKHR(device.internal_object(), self.surface, - &mut out))?; - out + out.as_mut_ptr()))?; + out.assume_init() }; let formats = { @@ -578,7 +578,7 @@ unsafe impl SurfaceSwapchainLock for Surface { unsafe impl VulkanObject for Surface { type Object = vk::SurfaceKHR; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_SURFACE_KHR; #[inline] fn internal_object(&self) -> vk::SurfaceKHR { @@ -627,7 +627,7 @@ impl error::Error for SurfaceCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SurfaceCreationError::OomError(ref err) => Some(err), _ => None, @@ -681,7 +681,7 @@ impl error::Error for CapabilitiesError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { CapabilitiesError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/swapchain.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/swapchain.rs similarity index 72% rename from third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/swapchain.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/swapchain.rs index b6b6a73..e82fb94 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/swapchain/swapchain.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/swapchain/swapchain.rs @@ -9,6 +9,7 @@ use std::error; use std::fmt; +use std::mem::MaybeUninit; use std::mem; use std::ptr; use std::sync::Arc; @@ -21,6 +22,7 @@ use buffer::BufferAccess; use command_buffer::submit::SubmitAnyBuilder; use command_buffer::submit::SubmitPresentBuilder; use command_buffer::submit::SubmitSemaphoresWaitBuilder; +use command_buffer::submit::SubmitPresentError; use device::Device; use device::DeviceOwned; use device::Queue; @@ -58,6 +60,37 @@ use VulkanObject; use check_errors; use vk; +/// The way fullscreen exclusivity is handled. +#[derive(Copy,Clone,Debug,PartialEq,Eq)] +pub enum FullscreenExclusive { + /// Indicates that the driver should determine the appropriate full-screen method + /// by whatever means it deems appropriate. + Default, + /// Indicates that the driver may use full-screen exclusive mechanisms when available. + /// Such mechanisms may result in better performance and/or the availability of + /// different presentation capabilities, but may require a more disruptive transition + // during swapchain initialization, first presentation and/or destruction. + Allowed, + /// Indicates that the driver should avoid using full-screen mechanisms which rely + /// on disruptive transitions. + Disallowed, + /// Indicates the application will manage full-screen exclusive mode by using + /// `Swapchain::acquire_fullscreen_exclusive()` and + /// `Swapchain::release_fullscreen_exclusive()` functions. + AppControlled, +} + +impl FullscreenExclusive { + fn vk_sys_enum(&self) -> u32 { + match self { + &Self::Default => vk::FULL_SCREEN_EXCLUSIVE_DEFAUlT_EXT, + &Self::Allowed => vk::FULL_SCREEN_EXCLUSIVE_ALLOWED_EXT, + &Self::Disallowed => vk::FULL_SCREEN_EXCLUSIVE_DISALLOWED_EXT, + &Self::AppControlled => vk::FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT, + } + } +} + /// Tries to take ownership of an image in order to draw on it. /// /// The function returns the index of the image in the array of images that was returned @@ -66,12 +99,15 @@ use vk; /// /// If you try to draw on an image without acquiring it first, the execution will block. (TODO /// behavior may change). +/// +/// The second field in the tuple in the Ok result is a bool represent if the acquisition was +/// suboptimal. In this case the acquired image is still usable, but the swapchain should be +/// recreated as the Surface's properties no longer match the swapchain. pub fn acquire_next_image(swapchain: Arc>, timeout: Option) - -> Result<(usize, SwapchainAcquireFuture), AcquireError> { + -> Result<(usize, bool, SwapchainAcquireFuture), AcquireError> { let semaphore = Semaphore::from_pool(swapchain.device.clone())?; let fence = Fence::from_pool(swapchain.device.clone())?; - // TODO: propagate `suboptimal` to the user let AcquiredImage { id, suboptimal } = { // Check that this is not an old swapchain. From specs: // > swapchain must not have been replaced by being passed as the @@ -81,10 +117,16 @@ pub fn acquire_next_image(swapchain: Arc>, timeout: Option { transform: SurfaceTransform, alpha: CompositeAlpha, mode: PresentMode, + fullscreen_exclusive: FullscreenExclusive, + fullscreen_exclusive_held: AtomicBool, clipped: bool, } @@ -217,15 +261,43 @@ impl Swapchain { /// - Panics if the device and the surface don't belong to the same instance. /// - Panics if `usage` is empty. /// - // TODO: remove `old_swapchain` parameter and add another function `with_old_swapchain`. - // TODO: add `ColorSpace` parameter // TODO: isn't it unsafe to take the surface through an Arc when it comes to vulkano-win? #[inline] pub fn new( device: Arc, surface: Arc>, num_images: u32, format: F, dimensions: [u32; 2], layers: u32, usage: ImageUsage, sharing: S, - transform: SurfaceTransform, alpha: CompositeAlpha, mode: PresentMode, clipped: bool, - old_swapchain: Option<&Arc>>) + transform: SurfaceTransform, alpha: CompositeAlpha, mode: PresentMode, + fullscreen_exclusive: FullscreenExclusive, clipped: bool, color_space: ColorSpace) + -> Result<(Arc>, Vec>>), SwapchainCreationError> + where F: FormatDesc, + S: Into + { + Swapchain::new_inner(device, + surface, + num_images, + format.format(), + color_space, + Some(dimensions), + layers, + usage, + sharing.into(), + transform, + alpha, + mode, + fullscreen_exclusive, + clipped, + None) + } + + + /// Same as Swapchain::new but requires an old swapchain for the creation + #[inline] + pub fn with_old_swapchain( + device: Arc, surface: Arc>, num_images: u32, format: F, + dimensions: [u32; 2], layers: u32, usage: ImageUsage, sharing: S, + transform: SurfaceTransform, alpha: CompositeAlpha, mode: PresentMode, + fullscreen_exclusive: FullscreenExclusive, clipped: bool, color_space: ColorSpace, + old_swapchain: Arc>) -> Result<(Arc>, Vec>>), SwapchainCreationError> where F: FormatDesc, S: Into @@ -235,19 +307,40 @@ impl Swapchain { num_images, format.format(), ColorSpace::SrgbNonLinear, - dimensions, + Some(dimensions), layers, usage, sharing.into(), transform, alpha, mode, + fullscreen_exclusive, clipped, - old_swapchain.map(|s| &**s)) + Some(&*old_swapchain)) + } + + /// Recreates the swapchain with current dimensions of corresponding surface. + pub fn recreate(&self) + -> Result<(Arc>, Vec>>), SwapchainCreationError> { + Swapchain::new_inner(self.device.clone(), + self.surface.clone(), + self.num_images, + self.format, + self.color_space, + None, + self.layers, + self.usage, + self.sharing.clone(), + self.transform, + self.alpha, + self.mode, + self.fullscreen_exclusive, + self.clipped, + Some(self)) } /// Recreates the swapchain with new dimensions. - pub fn recreate_with_dimension( + pub fn recreate_with_dimensions( &self, dimensions: [u32; 2]) -> Result<(Arc>, Vec>>), SwapchainCreationError> { Swapchain::new_inner(self.device.clone(), @@ -255,21 +348,22 @@ impl Swapchain { self.num_images, self.format, self.color_space, - dimensions, + Some(dimensions), self.layers, self.usage, self.sharing.clone(), self.transform, self.alpha, self.mode, + self.fullscreen_exclusive, self.clipped, Some(self)) } fn new_inner(device: Arc, surface: Arc>, num_images: u32, format: Format, - color_space: ColorSpace, dimensions: [u32; 2], layers: u32, usage: ImageUsage, + color_space: ColorSpace, dimensions: Option<[u32; 2]>, layers: u32, usage: ImageUsage, sharing: SharingMode, transform: SurfaceTransform, alpha: CompositeAlpha, - mode: PresentMode, clipped: bool, old_swapchain: Option<&Swapchain>) + mode: PresentMode, fullscreen_exclusive: FullscreenExclusive, clipped: bool, old_swapchain: Option<&Swapchain>) -> Result<(Arc>, Vec>>), SwapchainCreationError> { assert_eq!(device.instance().internal_object(), surface.instance().internal_object()); @@ -291,18 +385,23 @@ impl Swapchain { { return Err(SwapchainCreationError::UnsupportedFormat); } - if dimensions[0] < capabilities.min_image_extent[0] { - return Err(SwapchainCreationError::UnsupportedDimensions); - } - if dimensions[1] < capabilities.min_image_extent[1] { - return Err(SwapchainCreationError::UnsupportedDimensions); - } - if dimensions[0] > capabilities.max_image_extent[0] { - return Err(SwapchainCreationError::UnsupportedDimensions); - } - if dimensions[1] > capabilities.max_image_extent[1] { - return Err(SwapchainCreationError::UnsupportedDimensions); - } + let dimensions = if let Some(dimensions) = dimensions { + if dimensions[0] < capabilities.min_image_extent[0] { + return Err(SwapchainCreationError::UnsupportedDimensions); + } + if dimensions[1] < capabilities.min_image_extent[1] { + return Err(SwapchainCreationError::UnsupportedDimensions); + } + if dimensions[0] > capabilities.max_image_extent[0] { + return Err(SwapchainCreationError::UnsupportedDimensions); + } + if dimensions[1] > capabilities.max_image_extent[1] { + return Err(SwapchainCreationError::UnsupportedDimensions); + } + dimensions + } else { + capabilities.current_extent.unwrap() + }; if layers < 1 || layers > capabilities.max_image_array_layers { return Err(SwapchainCreationError::UnsupportedArrayLayers); } @@ -337,9 +436,27 @@ impl Swapchain { } if !device.loaded_extensions().khr_swapchain { - return Err(SwapchainCreationError::MissingExtension); + return Err(SwapchainCreationError::MissingExtensionKHRSwapchain); } + let mut surface_full_screen_exclusive_info = None; + + if device.loaded_extensions().ext_full_screen_exclusive + && surface.instance().loaded_extensions().khr_get_physical_device_properties2 + && surface.instance().loaded_extensions().khr_get_surface_capabilities2 + { + surface_full_screen_exclusive_info = Some(vk::SurfaceFullScreenExclusiveInfoEXT { + sType: vk::STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_INFO_EXT, + pNext: ptr::null(), + fullScreenExclusive: fullscreen_exclusive.vk_sys_enum(), + }); + } + + let p_next = match surface_full_screen_exclusive_info.as_ref() { + Some(some) => unsafe { mem::transmute(some as *const _) }, + None => ptr::null(), + }; + // Required by the specs. assert_ne!(usage, ImageUsage::none()); @@ -365,7 +482,7 @@ impl Swapchain { let swapchain = unsafe { let (sh_mode, sh_count, sh_indices) = match sharing { - SharingMode::Exclusive(_) => (vk::SHARING_MODE_EXCLUSIVE, 0, ptr::null()), + SharingMode::Exclusive => (vk::SHARING_MODE_EXCLUSIVE, 0, ptr::null()), SharingMode::Concurrent(ref ids) => (vk::SHARING_MODE_CONCURRENT, ids.len() as u32, ids.as_ptr()), @@ -373,7 +490,7 @@ impl Swapchain { let infos = vk::SwapchainCreateInfoKHR { sType: vk::STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, - pNext: ptr::null(), + pNext: p_next, flags: 0, // reserved surface: surface.internal_object(), minImageCount: num_images, @@ -399,12 +516,12 @@ impl Swapchain { }, }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateSwapchainKHR(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; let image_handles = unsafe { @@ -448,6 +565,17 @@ impl Swapchain { }) .collect::>(); + let fullscreen_exclusive_held = old_swapchain + .as_ref() + .map(|old_swapchain| { + if old_swapchain.fullscreen_exclusive != FullscreenExclusive::AppControlled { + false + } else { + old_swapchain.fullscreen_exclusive_held.load(Ordering::SeqCst) + } + }) + .unwrap_or(false); + let swapchain = Arc::new(Swapchain { device: device.clone(), surface: surface.clone(), @@ -464,6 +592,8 @@ impl Swapchain { transform: transform, alpha: alpha, mode: mode, + fullscreen_exclusive, + fullscreen_exclusive_held: AtomicBool::new(fullscreen_exclusive_held), clipped: clipped, }); @@ -478,6 +608,11 @@ impl Swapchain { Ok((swapchain, swapchain_images)) } + /// Returns the saved Surface, from the Swapchain creation + pub fn surface(&self) -> &Arc>{ + &self.surface + } + /// Returns of the images that belong to this swapchain. #[inline] pub fn raw_image(&self, offset: usize) -> Option { @@ -555,12 +690,94 @@ impl Swapchain { pub fn clipped(&self) -> bool { self.clipped } + + /// Returns the value of 'fullscreen_exclusive` that was passed when creating the swapchain. + /// + /// See the documentation of `FullscreenExclusive` + #[inline] + pub fn fullscreen_exclusive(&self) -> FullscreenExclusive { + self.fullscreen_exclusive + } + + /// `FullscreenExclusive::AppControlled` must be the active fullscreen exclusivity mode. + /// Acquire fullscreen exclusivity until either the `release_fullscreen_exclusive` is + /// called, or if any of the the other `Swapchain` functions return `FullscreenExclusiveLost`. + /// Requires: `FullscreenExclusive::AppControlled` + pub fn acquire_fullscreen_exclusive(&self) -> Result<(), FullscreenExclusiveError> { + if self.fullscreen_exclusive != FullscreenExclusive::AppControlled { + return Err(FullscreenExclusiveError::NotAppControlled); + } + + if self.fullscreen_exclusive_held.swap(true, Ordering::SeqCst) { + return Err(FullscreenExclusiveError::DoubleAcquire); + } + + unsafe { + check_errors(self.device.pointers().AcquireFullScreenExclusiveModeEXT( + self.device.internal_object(), + self.swapchain + ))?; + } + + Ok(()) + } + + /// `FullscreenExclusive::AppControlled` must be the active fullscreen exclusivity mode. + /// Release fullscreen exclusivity. + pub fn release_fullscreen_exclusive(&self) -> Result<(), FullscreenExclusiveError> { + if self.fullscreen_exclusive != FullscreenExclusive::AppControlled { + return Err(FullscreenExclusiveError::NotAppControlled); + } + + if !self.fullscreen_exclusive_held.swap(false, Ordering::SeqCst) { + return Err(FullscreenExclusiveError::DoubleRelease); + } + + unsafe { + check_errors(self.device.pointers().ReleaseFullScreenExclusiveModeEXT( + self.device.internal_object(), + self.swapchain + ))?; + } + + Ok(()) + } + + /// `FullscreenExclusive::AppControlled` is not the active fullscreen exclusivity mode, + /// then this function will always return false. If true is returned the swapchain + /// is in `FullscreenExclusive::AppControlled` fullscreen exclusivity mode and exclusivity + /// is currently acquired. + pub fn is_fullscreen_exclusive(&self) -> bool { + if self.fullscreen_exclusive != FullscreenExclusive::AppControlled { + false + } else { + self.fullscreen_exclusive_held.load(Ordering::SeqCst) + } + } + + // This method is necessary to allow `SwapchainImage`s to signal when they have been + // transitioned out of their initial `undefined` image layout. + // + // See the `ImageAccess::layout_initialized` method documentation for more details. + pub(crate) fn image_layout_initialized(&self, image_offset: usize) { + let image_entry = self.images.get(image_offset); + if let Some(ref image_entry) = image_entry { + image_entry.undefined_layout.store(false, Ordering::SeqCst); + } + } + + pub(crate) fn is_image_layout_initialized(&self, image_offset: usize) -> bool { + let image_entry = self.images.get(image_offset); + if let Some(ref image_entry) = image_entry { + !image_entry.undefined_layout.load(Ordering::SeqCst) + } else { false } + } } unsafe impl VulkanObject for Swapchain { type Object = vk::SwapchainKHR; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_SWAPCHAIN_KHR; #[inline] fn internal_object(&self) -> vk::SwapchainKHR { @@ -606,7 +823,9 @@ pub enum SwapchainCreationError { /// The window is already in use by another API. NativeWindowInUse, /// The `VK_KHR_swapchain` extension was not enabled. - MissingExtension, + MissingExtensionKHRSwapchain, + /// The `VK_EXT_full_screen_exclusive` extension was not enabled. + MissingExtensionExtFullScreenExclusive, /// Surface mismatch between old and new swapchain. OldSwapchainSurfaceMismatch, /// The old swapchain has already been used to recreate another one. @@ -650,9 +869,12 @@ impl error::Error for SwapchainCreationError { SwapchainCreationError::NativeWindowInUse => { "the window is already in use by another API" }, - SwapchainCreationError::MissingExtension => { + SwapchainCreationError::MissingExtensionKHRSwapchain => { "the `VK_KHR_swapchain` extension was not enabled" }, + SwapchainCreationError::MissingExtensionExtFullScreenExclusive => { + "the `VK_EXT_full_screen_exclusive` extension was not enabled" + }, SwapchainCreationError::OldSwapchainSurfaceMismatch => { "surface mismatch between old and new swapchain" }, @@ -690,7 +912,7 @@ impl error::Error for SwapchainCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { SwapchainCreationError::OomError(ref err) => Some(err), _ => None, @@ -812,13 +1034,13 @@ unsafe impl GpuFuture for SwapchainAcquireFuture { #[inline] fn check_buffer_access( - &self, _: &BufferAccess, _: bool, _: &Queue) + &self, _: &dyn BufferAccess, _: bool, _: &Queue) -> Result, AccessCheckError> { Err(AccessCheckError::Unknown) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, _: bool, _: &Queue) + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, _: bool, _: &Queue) -> Result, AccessCheckError> { let swapchain_image = self.swapchain.raw_image(self.image_id).unwrap(); if swapchain_image.image.internal_object() != image.inner().image.internal_object() { @@ -854,30 +1076,96 @@ unsafe impl DeviceOwned for SwapchainAcquireFuture { impl Drop for SwapchainAcquireFuture { fn drop(&mut self) { - if !*self.finished.get_mut() { if let Some(ref fence) = self.fence { fence.wait(None).unwrap(); // TODO: handle error? self.semaphore = None; } - } else { - // We make sure that the fence is signalled. This also silences an error from the - // validation layers about using a fence whose state hasn't been checked (even though - // we know for sure that it must've been signalled). - debug_assert!({ - let dur = Some(Duration::new(0, 0)); - self.fence - .as_ref() - .map(|f| f.wait(dur).is_ok()) - .unwrap_or(true) - }); - } - // TODO: if this future is destroyed without being presented, then eventually acquiring // a new image will block forever ; difficulty: hard } } +/// Error that can happen when calling `Swapchain::acquire_fullscreen_exclusive` or `Swapchain::release_fullscreen_exclusive` +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +#[repr(u32)] +pub enum FullscreenExclusiveError { + /// Not enough memory. + OomError(OomError), + + /// Operation could not be completed for driver specific reasons. + InitializationFailed, + + /// The surface is no longer accessible and must be recreated. + SurfaceLost, + + /// Fullscreen exclusivity is already acquired. + DoubleAcquire, + + /// Fullscreen exclusivity is not current acquired. + DoubleRelease, + + /// Swapchain is not in fullscreen exclusive app controlled mode + NotAppControlled, +} + +impl fmt::Display for FullscreenExclusiveError { + #[inline] + fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!(fmt, "{}", error::Error::description(self)) + } +} + +impl From for FullscreenExclusiveError { + #[inline] + fn from(err: Error) -> FullscreenExclusiveError { + match err { + err @ Error::OutOfHostMemory => { + FullscreenExclusiveError::OomError(OomError::from(err)) + }, + err @ Error::OutOfDeviceMemory => { + FullscreenExclusiveError::OomError(OomError::from(err)) + }, + Error::SurfaceLost => { + FullscreenExclusiveError::SurfaceLost + }, + Error::InitializationFailed => { + FullscreenExclusiveError::InitializationFailed + }, + _ => panic!("unexpected error: {:?}", err), + } + } +} + +impl From for FullscreenExclusiveError { + #[inline] + fn from(err: OomError) -> FullscreenExclusiveError { + FullscreenExclusiveError::OomError(err) + } +} + +impl error::Error for FullscreenExclusiveError { + #[inline] + fn description(&self) -> &str { + match *self { + FullscreenExclusiveError::OomError(_) => "not enough memory", + FullscreenExclusiveError::SurfaceLost => "the surface of this swapchain is no longer valid", + FullscreenExclusiveError::InitializationFailed => "operation could not be completed for driver specific reasons", + FullscreenExclusiveError::DoubleAcquire => "fullscreen exclusivity is already acquired", + FullscreenExclusiveError::DoubleRelease => "fullscreen exclusivity is not acquired", + FullscreenExclusiveError::NotAppControlled => "swapchain is not in fullscreen exclusive app controlled mode" + } + } + + #[inline] + fn cause(&self) -> Option<&dyn error::Error> { + match *self { + FullscreenExclusiveError::OomError(ref err) => Some(err), + _ => None, + } + } +} + /// Error that can happen when calling `acquire_next_image`. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[repr(u32)] @@ -894,6 +1182,10 @@ pub enum AcquireError { /// The surface is no longer accessible and must be recreated. SurfaceLost, + /// The swapchain has lost or doesn't have fullscreen exclusivity possibly for + /// implementation-specific reasons outside of the application’s control. + FullscreenExclusiveLost, + /// The surface has changed in a way that makes the swapchain unusable. You must query the /// surface's new properties and recreate a new swapchain if you want to continue drawing. OutOfDate, @@ -908,11 +1200,12 @@ impl error::Error for AcquireError { AcquireError::Timeout => "no image is available for acquiring yet", AcquireError::SurfaceLost => "the surface of this swapchain is no longer valid", AcquireError::OutOfDate => "the swapchain needs to be recreated", + AcquireError::FullscreenExclusiveLost => "the swapchain no longer has fullscreen exclusivity", } } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { AcquireError::OomError(ref err) => Some(err), _ => None, @@ -943,6 +1236,7 @@ impl From for AcquireError { Error::DeviceLost => AcquireError::DeviceLost, Error::SurfaceLost => AcquireError::SurfaceLost, Error::OutOfDate => AcquireError::OutOfDate, + Error::FullscreenExclusiveLost => AcquireError::FullscreenExclusiveLost, _ => panic!("unexpected error: {:?}", err), } } @@ -1053,10 +1347,22 @@ unsafe impl GpuFuture for PresentFuture unsafe { // If `flushed` already contains `true`, then `build_submission` will return `Empty`. - match self.build_submission()? { + let build_submission_result = self.build_submission(); + + if let &Err(FlushError::FullscreenExclusiveLost) = &build_submission_result { + self.swapchain.fullscreen_exclusive_held.store(false, Ordering::SeqCst); + } + + match build_submission_result? { SubmitAnyBuilder::Empty => {}, SubmitAnyBuilder::QueuePresent(present) => { - present.submit(&self.queue)?; + let present_result = present.submit(&self.queue); + + if let &Err(SubmitPresentError::FullscreenExclusiveLost) = &present_result { + self.swapchain.fullscreen_exclusive_held.store(false, Ordering::SeqCst); + } + + present_result?; }, _ => unreachable!(), } @@ -1090,13 +1396,13 @@ unsafe impl GpuFuture for PresentFuture #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { self.previous.check_buffer_access(buffer, exclusive, queue) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { let swapchain_image = self.swapchain.raw_image(self.image_id).unwrap(); @@ -1170,15 +1476,16 @@ pub unsafe fn acquire_next_image_raw(swapchain: &Swapchain, timeout: Optio u64::max_value() }; - let mut out = mem::uninitialized(); + let mut out = MaybeUninit::uninit(); let r = check_errors(vk.AcquireNextImageKHR(swapchain.device.internal_object(), swapchain.swapchain, timeout_ns, semaphore.map(|s| s.internal_object()).unwrap_or(0), fence.map(|f| f.internal_object()).unwrap_or(0), - &mut out))?; + out.as_mut_ptr()))?; + let out = out.assume_init(); let (id, suboptimal) = match r { Success::Success => (out as usize, false), Success::Suboptimal => (out as usize, true), diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/event.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/event.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/event.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/event.rs index 4158aca..3c507ad 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/event.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/event.rs @@ -7,7 +7,7 @@ // notice may not be copied, modified, or distributed except // according to those terms. -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -78,13 +78,13 @@ impl Event { flags: 0, // reserved }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); let vk = device.pointers(); check_errors(vk.CreateEvent(device.internal_object(), &INFOS, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Event { @@ -164,7 +164,7 @@ unsafe impl DeviceOwned for Event { unsafe impl VulkanObject for Event { type Object = vk::Event; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_EVENT; #[inline] fn internal_object(&self) -> vk::Event { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/fence.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/fence.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/fence.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/fence.rs index 7b5a88c..5744ca0 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/fence.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/fence.rs @@ -10,7 +10,7 @@ use smallvec::SmallVec; use std::error; use std::fmt; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -107,12 +107,12 @@ impl Fence }; let vk = device.pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateFence(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Fence { @@ -307,7 +307,7 @@ unsafe impl VulkanObject for Fence { type Object = vk::Fence; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_FENCE; #[inline] fn internal_object(&self) -> vk::Fence { @@ -356,7 +356,7 @@ impl error::Error for FenceWaitError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { FenceWaitError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/fence_signal.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/fence_signal.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/fence_signal.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/fence_signal.rs index b6cd3d9..5527837 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/fence_signal.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/fence_signal.rs @@ -389,7 +389,7 @@ unsafe impl GpuFuture for FenceSignalFuture #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { let state = self.state.lock().unwrap(); if let Some(previous) = state.get_prev() { @@ -400,7 +400,7 @@ unsafe impl GpuFuture for FenceSignalFuture } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { let state = self.state.lock().unwrap(); @@ -491,13 +491,13 @@ unsafe impl GpuFuture for Arc> #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_buffer_access(buffer, exclusive, queue) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_image_access(image, layout, exclusive, queue) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/join.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/join.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/join.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/join.rs index 3c19d80..1b21195 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/join.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/join.rs @@ -86,10 +86,11 @@ unsafe impl GpuFuture for JoinFuture #[inline] unsafe fn build_submission(&self) -> Result { // TODO: review this function - let first = self.first.build_submission()?; let second = self.second.build_submission()?; + // In some cases below we have to submit previous command buffers already, this s done by flushing previous. + // Since the implementation should remember being flushed it's safe to call build_submission multiple times Ok(match (first, second) { (SubmitAnyBuilder::Empty, b) => b, (a, SubmitAnyBuilder::Empty) => a, @@ -98,27 +99,27 @@ unsafe impl GpuFuture for JoinFuture SubmitAnyBuilder::SemaphoresWait(a) }, (SubmitAnyBuilder::SemaphoresWait(a), SubmitAnyBuilder::CommandBuffer(b)) => { - b.submit(&self.second.queue().clone().unwrap())?; + self.second.flush()?; SubmitAnyBuilder::SemaphoresWait(a) }, (SubmitAnyBuilder::CommandBuffer(a), SubmitAnyBuilder::SemaphoresWait(b)) => { - a.submit(&self.first.queue().clone().unwrap())?; + self.first.flush()?; SubmitAnyBuilder::SemaphoresWait(b) }, (SubmitAnyBuilder::SemaphoresWait(a), SubmitAnyBuilder::QueuePresent(b)) => { - b.submit(&self.second.queue().clone().unwrap())?; + self.second.flush()?; SubmitAnyBuilder::SemaphoresWait(a) }, (SubmitAnyBuilder::QueuePresent(a), SubmitAnyBuilder::SemaphoresWait(b)) => { - a.submit(&self.first.queue().clone().unwrap())?; + self.first.flush()?; SubmitAnyBuilder::SemaphoresWait(b) }, (SubmitAnyBuilder::SemaphoresWait(a), SubmitAnyBuilder::BindSparse(b)) => { - b.submit(&self.second.queue().clone().unwrap())?; + self.second.flush()?; SubmitAnyBuilder::SemaphoresWait(a) }, (SubmitAnyBuilder::BindSparse(a), SubmitAnyBuilder::SemaphoresWait(b)) => { - a.submit(&self.first.queue().clone().unwrap())?; + self.first.flush()?; SubmitAnyBuilder::SemaphoresWait(b) }, (SubmitAnyBuilder::CommandBuffer(a), SubmitAnyBuilder::CommandBuffer(b)) => { @@ -127,8 +128,8 @@ unsafe impl GpuFuture for JoinFuture SubmitAnyBuilder::CommandBuffer(new) }, (SubmitAnyBuilder::QueuePresent(a), SubmitAnyBuilder::QueuePresent(b)) => { - a.submit(&self.first.queue().clone().unwrap())?; - b.submit(&self.second.queue().clone().unwrap())?; + self.first.flush()?; + self.second.flush()?; SubmitAnyBuilder::Empty }, (SubmitAnyBuilder::CommandBuffer(a), SubmitAnyBuilder::QueuePresent(b)) => { @@ -193,7 +194,7 @@ unsafe impl GpuFuture for JoinFuture #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { let first = self.first.check_buffer_access(buffer, exclusive, queue); let second = self.second.check_buffer_access(buffer, exclusive, queue); @@ -217,7 +218,7 @@ unsafe impl GpuFuture for JoinFuture } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { let first = self.first diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/mod.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/mod.rs index e4e9692..1afcf0f 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/mod.rs @@ -115,7 +115,7 @@ pub unsafe trait GpuFuture: DeviceOwned { /// /// > **Note**: Returning `Ok` means "access granted", while returning `Err` means /// > "don't know". Therefore returning `Err` is never unsafe. - fn check_buffer_access(&self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + fn check_buffer_access(&self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError>; /// Checks whether submitting something after this future grants access (exclusive or shared, @@ -132,7 +132,7 @@ pub unsafe trait GpuFuture: DeviceOwned { /// /// > **Note**: Keep in mind that changing the layout of an image also requires exclusive /// > access. - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError>; @@ -292,13 +292,13 @@ unsafe impl GpuFuture for Box #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_buffer_access(buffer, exclusive, queue) } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { (**self).check_image_access(image, layout, exclusive, queue) @@ -424,6 +424,10 @@ pub enum FlushError { /// surface's new properties and recreate a new swapchain if you want to continue drawing. OutOfDate, + /// The swapchain has lost or doesn't have fullscreen exclusivity possibly for + /// implementation-specific reasons outside of the application’s control. + FullscreenExclusiveLost, + /// The flush operation needed to block, but the timeout has elapsed. Timeout, } @@ -437,13 +441,14 @@ impl error::Error for FlushError { FlushError::DeviceLost => "the connection to the device has been lost", FlushError::SurfaceLost => "the surface of this swapchain is no longer valid", FlushError::OutOfDate => "the swapchain needs to be recreated", + FlushError::FullscreenExclusiveLost => "the swapchain no longer has fullscreen exclusivity", FlushError::Timeout => "the flush operation needed to block, but the timeout has \ elapsed", } } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { FlushError::AccessError(ref err) => Some(err), FlushError::OomError(ref err) => Some(err), @@ -474,6 +479,7 @@ impl From for FlushError { SubmitPresentError::DeviceLost => FlushError::DeviceLost, SubmitPresentError::SurfaceLost => FlushError::SurfaceLost, SubmitPresentError::OutOfDate => FlushError::OutOfDate, + SubmitPresentError::FullscreenExclusiveLost => FlushError::FullscreenExclusiveLost, } } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/now.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/now.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/now.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/now.rs index aa8bbb7..1c0fb26 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/now.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/now.rs @@ -64,13 +64,13 @@ unsafe impl GpuFuture for NowFuture { #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, _: bool, _: &Queue) + &self, buffer: &dyn BufferAccess, _: bool, _: &Queue) -> Result, AccessCheckError> { Err(AccessCheckError::Unknown) } #[inline] - fn check_image_access(&self, _: &ImageAccess, _: ImageLayout, _: bool, _: &Queue) + fn check_image_access(&self, _: &dyn ImageAccess, _: ImageLayout, _: bool, _: &Queue) -> Result, AccessCheckError> { Err(AccessCheckError::Unknown) } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/semaphore_signal.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/semaphore_signal.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/semaphore_signal.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/semaphore_signal.rs index bda4927..c9e104a 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/future/semaphore_signal.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/future/semaphore_signal.rs @@ -108,7 +108,7 @@ unsafe impl GpuFuture for SemaphoreSignalFuture unimplemented!() // TODO: how to do that? /*debug_assert_eq!(builder.num_signal_semaphores(), 0); builder.add_signal_semaphore(&self.semaphore); - try!(builder.submit(&queue));*/ + builder.submit(&queue)?;*/ }, SubmitAnyBuilder::QueuePresent(present) => { present.submit(&queue)?; @@ -143,7 +143,7 @@ unsafe impl GpuFuture for SemaphoreSignalFuture #[inline] fn check_buffer_access( - &self, buffer: &BufferAccess, exclusive: bool, queue: &Queue) + &self, buffer: &dyn BufferAccess, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { self.previous .check_buffer_access(buffer, exclusive, queue) @@ -151,7 +151,7 @@ unsafe impl GpuFuture for SemaphoreSignalFuture } #[inline] - fn check_image_access(&self, image: &ImageAccess, layout: ImageLayout, exclusive: bool, + fn check_image_access(&self, image: &dyn ImageAccess, layout: ImageLayout, exclusive: bool, queue: &Queue) -> Result, AccessCheckError> { self.previous diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/mod.rs similarity index 98% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/mod.rs index f231a98..ba65223 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/mod.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/mod.rs @@ -109,6 +109,7 @@ use std::sync::Arc; pub use self::event::Event; pub use self::fence::Fence; pub use self::fence::FenceWaitError; +pub use self::future::now; pub use self::future::AccessCheckError; pub use self::future::AccessError; pub use self::future::FenceSignalFuture; @@ -117,7 +118,6 @@ pub use self::future::GpuFuture; pub use self::future::JoinFuture; pub use self::future::NowFuture; pub use self::future::SemaphoreSignalFuture; -pub use self::future::now; pub use self::pipeline::AccessFlagBits; pub use self::pipeline::PipelineStages; pub use self::semaphore::Semaphore; @@ -137,7 +137,7 @@ mod semaphore; // TODO: remove pub enum SharingMode { /// The resource is used is only one queue family. - Exclusive(u32), + Exclusive, /// The resource is used in multiple queue families. Can be slower than `Exclusive`. Concurrent(Vec), // TODO: Vec is too expensive here } @@ -145,7 +145,7 @@ pub enum SharingMode { impl<'a> From<&'a Arc> for SharingMode { #[inline] fn from(queue: &'a Arc) -> SharingMode { - SharingMode::Exclusive(queue.family().id()) + SharingMode::Exclusive } } @@ -159,7 +159,8 @@ impl<'a> From<&'a [&'a Arc]> for SharingMode { /// Declares in which queue(s) a resource can be used. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Sharing - where I: Iterator +where + I: Iterator, { /// The resource is used is only one queue family. Exclusive, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/pipeline.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/pipeline.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/pipeline.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/pipeline.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/semaphore.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/semaphore.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/sync/semaphore.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/sync/semaphore.rs index b159531..77d2651 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/sync/semaphore.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/sync/semaphore.rs @@ -7,7 +7,7 @@ // notice may not be copied, modified, or distributed except // according to those terms. -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -74,12 +74,12 @@ impl Semaphore }; let vk = device.pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateSemaphore(device.internal_object(), &INFOS, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; Ok(Semaphore { @@ -102,7 +102,7 @@ unsafe impl VulkanObject for Semaphore { type Object = vk::Semaphore; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_SEMAPHORE; #[inline] fn internal_object(&self) -> vk::Semaphore { diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/tests.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/tests.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/tests.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/tests.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/version.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/version.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/version.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/version.rs diff --git a/third_party/cargo/vendor/vulkano-win-0.11.1/.cargo-checksum.json b/third_party/cargo/vendor/vulkano-win-0.11.1/.cargo-checksum.json deleted file mode 100644 index 66f8745..0000000 --- a/third_party/cargo/vendor/vulkano-win-0.11.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"165c8ee51ce7d4cc325b5c5bf43950419c58ce61fddff281f98f85ccd318aa79","src/lib.rs":"0768763d3cee8d98049a603efe7bdca49ca1442633979100a283b95ece6784c2"},"package":"07fffe247f37c8b051e8210ecfb6fe9a13bbb69e05ea61aceb1def5f709320ae"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vulkano-win-0.18.0/.cargo-checksum.json b/third_party/cargo/vendor/vulkano-win-0.18.0/.cargo-checksum.json new file mode 100644 index 0000000..847f48c --- /dev/null +++ b/third_party/cargo/vendor/vulkano-win-0.18.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"2812b64fa092eb0c8c14b846216fae07bc3f8c59feaa09703c8d7e5d887a5f20","src/lib.rs":"b39ca21c6ba7b967fe1844d300eb31e8153faf0b931680a1723f717bc9122f80"},"package":"bc7e4c74bbf33d0c6b9f7e98f47068c62dc65d6a0721c0cb4b05fe4776c9af80"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vulkano-win-0.11.1/BUILD b/third_party/cargo/vendor/vulkano-win-0.18.0/BUILD similarity index 81% rename from third_party/cargo/vendor/vulkano-win-0.11.1/BUILD rename to third_party/cargo/vendor/vulkano-win-0.18.0/BUILD index 7d36c45..b4288f9 100644 --- a/third_party/cargo/vendor/vulkano-win-0.11.1/BUILD +++ b/third_party/cargo/vendor/vulkano-win-0.18.0/BUILD @@ -28,16 +28,16 @@ rust_library( name = "vulkano_win", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/vulkano-0.11.1:vulkano", - "//third_party/cargo/vendor/winit-0.18.1:winit", + "//third_party/cargo/vendor/vulkano-0.18.0:vulkano", + "//third_party/cargo/vendor/winit-0.22.0:winit", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.11.1", + version = "0.18.0", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/vulkano-win-0.11.1/Cargo.toml b/third_party/cargo/vendor/vulkano-win-0.18.0/Cargo.toml similarity index 86% rename from third_party/cargo/vendor/vulkano-win-0.11.1/Cargo.toml rename to third_party/cargo/vendor/vulkano-win-0.18.0/Cargo.toml index 024b2b9..63b4f17 100644 --- a/third_party/cargo/vendor/vulkano-win-0.11.1/Cargo.toml +++ b/third_party/cargo/vendor/vulkano-win-0.18.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "vulkano-win" -version = "0.11.1" +version = "0.18.0" authors = ["Pierre Krieger ", "The vulkano contributors"] description = "Link between vulkano and winit" homepage = "https://vulkano.rs" @@ -22,15 +23,15 @@ categories = ["rendering::graphics-api"] license = "MIT/Apache-2.0" repository = "https://github.com/vulkano-rs/vulkano" [dependencies.vulkano] -version = "0.11.0" +version = "0.18.0" [dependencies.winit] -version = "0.18" +version = "0.22" [target."cfg(target_os = \"macos\")".dependencies.cocoa] -version = "0.18" +version = "0.20.0" [target."cfg(target_os = \"macos\")".dependencies.metal] -version = "0.13" +version = "0.17.0" [target."cfg(target_os = \"macos\")".dependencies.objc] -version = "0.2.2" +version = "0.2.7" diff --git a/third_party/cargo/vendor/vulkano-win-0.11.1/src/lib.rs b/third_party/cargo/vendor/vulkano-win-0.18.0/src/lib.rs similarity index 74% rename from third_party/cargo/vendor/vulkano-win-0.11.1/src/lib.rs rename to third_party/cargo/vendor/vulkano-win-0.18.0/src/lib.rs index fa209e6..f125948 100644 --- a/third_party/cargo/vendor/vulkano-win-0.11.1/src/lib.rs +++ b/third_party/cargo/vendor/vulkano-win-0.18.0/src/lib.rs @@ -1,15 +1,5 @@ #![doc(html_logo_url = "https://raw.githubusercontent.com/vulkano-rs/vulkano/master/logo.png")] -extern crate vulkano; -extern crate winit; - -#[cfg(target_os = "macos")] -extern crate objc; -#[cfg(target_os = "macos")] -extern crate cocoa; -#[cfg(target_os = "macos")] -extern crate metal; - use std::borrow::Borrow; use std::error; use std::fmt; @@ -22,8 +12,10 @@ use vulkano::instance::Instance; use vulkano::instance::InstanceExtensions; use vulkano::swapchain::Surface; use vulkano::swapchain::SurfaceCreationError; -use winit::{EventsLoop, WindowBuilder}; -use winit::CreationError as WindowCreationError; +use winit::window::Window; +use winit::window::WindowBuilder; +use winit::error::OsError as WindowCreationError; +use winit::event_loop::EventLoopWindowTarget; #[cfg(target_os = "macos")] use cocoa::appkit::{NSView, NSWindow}; @@ -47,6 +39,8 @@ pub fn required_extensions() -> InstanceExtensions { khr_win32_surface: true, mvk_ios_surface: true, mvk_macos_surface: true, + khr_get_physical_device_properties2: true, + khr_get_surface_capabilities2: true, ..InstanceExtensions::none() }; @@ -62,22 +56,22 @@ pub fn create_vk_surface( window: W, instance: Arc ) -> Result>, SurfaceCreationError> where - W: SafeBorrow, + W: SafeBorrow, { unsafe { winit_to_surface(instance, window) } } -pub trait VkSurfaceBuild { +pub trait VkSurfaceBuild { fn build_vk_surface( - self, events_loop: &EventsLoop, instance: Arc, - ) -> Result>, CreationError>; + self, event_loop: &EventLoopWindowTarget, instance: Arc, + ) -> Result>, CreationError>; } -impl VkSurfaceBuild for WindowBuilder { +impl VkSurfaceBuild for WindowBuilder { fn build_vk_surface( - self, events_loop: &EventsLoop, instance: Arc, - ) -> Result>, CreationError> { - let window = self.build(events_loop)?; + self, event_loop: &EventLoopWindowTarget, instance: Arc, + ) -> Result>, CreationError> { + let window = self.build(event_loop)?; Ok(create_vk_surface(window, instance)?) } } @@ -101,7 +95,7 @@ impl error::Error for CreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { CreationError::SurfaceCreationError(ref err) => Some(err), CreationError::WindowCreationError(ref err) => Some(err), @@ -131,21 +125,23 @@ impl From for CreationError { } #[cfg(target_os = "android")] -unsafe fn winit_to_surface>( +unsafe fn winit_to_surface>( instance: Arc, win: W, ) -> Result>, SurfaceCreationError> { - use winit::os::android::WindowExt; - Surface::from_anativewindow(instance, win.borrow().get_native_window(), win) + use winit::platform::android::WindowExtAndroid; + + Surface::from_anativewindow(instance, win.borrow().native_window(), win) } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] -unsafe fn winit_to_surface>( +unsafe fn winit_to_surface>( instance: Arc, win: W, ) -> Result>, SurfaceCreationError> { - use winit::os::unix::WindowExt; + use winit::platform::unix::WindowExtUnix; + match ( - win.borrow().get_wayland_display(), - win.borrow().get_wayland_surface(), + win.borrow().wayland_display(), + win.borrow().wayland_surface(), ) { (Some(display), Some(surface)) => Surface::from_wayland(instance, display, surface, win), _ => { @@ -154,15 +150,15 @@ unsafe fn winit_to_surface>( if instance.loaded_extensions().khr_xlib_surface { Surface::from_xlib( instance, - win.borrow().get_xlib_display().unwrap(), - win.borrow().get_xlib_window().unwrap() as _, + win.borrow().xlib_display().unwrap(), + win.borrow().xlib_window().unwrap() as _, win, ) } else { Surface::from_xcb( instance, - win.borrow().get_xcb_connection().unwrap(), - win.borrow().get_xlib_window().unwrap() as _, + win.borrow().xcb_connection().unwrap(), + win.borrow().xlib_window().unwrap() as _, win, ) } @@ -171,26 +167,26 @@ unsafe fn winit_to_surface>( } #[cfg(target_os = "windows")] -unsafe fn winit_to_surface>( +unsafe fn winit_to_surface>( instance: Arc, win: W, ) -> Result>, SurfaceCreationError> { - use winit::os::windows::WindowExt; + use winit::platform::windows::WindowExtWindows; + Surface::from_hwnd( instance, ptr::null() as *const (), // FIXME - win.borrow().get_hwnd(), + win.borrow().hwnd(), win, ) } #[cfg(target_os = "macos")] -unsafe fn winit_to_surface>( +unsafe fn winit_to_surface>( instance: Arc, win: W, ) -> Result>, SurfaceCreationError> { - use winit::os::macos::WindowExt; - - let wnd: cocoa_id = mem::transmute(win.borrow().get_nswindow()); + use winit::platform::macos::WindowExtMacOS ; + let wnd: cocoa_id = mem::transmute(win.borrow().ns_window()); let layer = CoreAnimationLayer::new(); layer.set_edge_antialiasing_mask(0); @@ -203,7 +199,7 @@ unsafe fn winit_to_surface>( view.setLayer(mem::transmute(layer.as_ref())); // Bombs here with out of memory view.setWantsLayer(YES); - Surface::from_macos_moltenvk(instance, win.borrow().get_nsview() as *const (), win) + Surface::from_macos_moltenvk(instance, win.borrow().ns_view() as *const (), win) } /// An alternative to `Borrow` with the requirement that all calls to diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/.cargo-checksum.json b/third_party/cargo/vendor/wayland-client-0.21.13/.cargo-checksum.json deleted file mode 100644 index 8b89c51..0000000 --- a/third_party/cargo/vendor/wayland-client-0.21.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"64fb60b860735f77016f3930484e3c50d831f4feea1d7936076cca19905ba7d5","build.rs":"9da6649c903a99185c755b9c501a1ebfcb147c0f89a9c0d20d2619bcb4b788ef","examples/dynamic_globals.rs":"7ec24e7fdee780915d15f2236cd6804fadf7b16b46d94d62b6a960a6a99c6a19","examples/list_globals.rs":"b05d691efa2b9a69680abba94601fc4063fb7c465228e098024336dfc652b194","examples/simple_window.rs":"7b50e4a6e535fb49698bfc142f0ff5ac090aabf97b542d19f9037f7ffc4e0629","src/cursor.rs":"0a19c067f19eb7d3472263482c5c14bd24c6690d1fa859b479678cfc53f76abc","src/display.rs":"d0ed902fa37c2938e7047176cb81f85b05d282a48aada8ac228323320e753d35","src/egl.rs":"a1ff24cbf247a1679dc716a617232565f5d83fa39c7854d690ab4aac9d8ac949","src/event_queue.rs":"44a78c83c30e1eefcb039610835d1f9d2e7e5d54d82cef81a1b1031a86b73dec","src/globals.rs":"2f724371a3d8d8dc2039111b817340f9bed5b89a913bfe3bacf67281d6401a47","src/lib.rs":"6f3340ab9808cea3bcde9c2c9a90c5dbe0424e6875c628ee97bf2fab208a4587","src/native_lib/display.rs":"9b4eddaa3c2f71b60b1f5f3e543ded75d2a8a7051d2de6694cec21beaa03691f","src/native_lib/event_queue.rs":"eef45cea3256ae186103ffdd51ef38c7fb2f07f016eea2f6584344a0b096770c","src/native_lib/mod.rs":"4c8412191bb696642f4dbb1df93eb74319188cb68ae514d8d3fc747f23db8d17","src/native_lib/proxy.rs":"1e35534c6fe34c5f720d8de33a88e226c5f273e6bdc524b7eab46a177c67b30c","src/proxy.rs":"60ee4344cc2a913a332bbd2433359d2aec024aa52ae1e3df47e2300f1ddd814f","src/rust_imp/connection.rs":"72fe83594cbb98356ccba77f091e50a6c039c9ca44538a5e11a7364a7668b8ee","src/rust_imp/display.rs":"0125c0463fe27d91b3d0f05f0d490087d1cac41c1682d410bcf45829787f00b3","src/rust_imp/mod.rs":"2d514130df7d76a39ce80483d05e411483fb0e81734db4f94eb56b9ca11f648b","src/rust_imp/proxy.rs":"2eab2f11ebaeba6d694dbaadaf850a099ec4f68205f1de627db0a60988918363","src/rust_imp/queues.rs":"514431bdbe0675e240eaacaf9654cf6aacc94f86f0847aea65b0bb334e8aa543","wayland.xml":"356cc470810e14fd4d209b0979b2260d83f3db5e6975dbcddd174193c9d84ec7"},"package":"49963e5f9eeaf637bfcd1b9f0701c99fd5cd05225eb51035550d4272806f2713"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/build.rs b/third_party/cargo/vendor/wayland-client-0.21.13/build.rs deleted file mode 100644 index 8c7bff5..0000000 --- a/third_party/cargo/vendor/wayland-client-0.21.13/build.rs +++ /dev/null @@ -1,20 +0,0 @@ -extern crate wayland_scanner; - -use std::env::var; -use std::path::Path; -use wayland_scanner::*; - -fn main() { - let protocol_file = "./wayland.xml"; - - let out_dir_str = var("OUT_DIR").unwrap(); - let out_dir = Path::new(&out_dir_str); - - if var("CARGO_FEATURE_NATIVE_LIB").ok().is_some() { - // generate the C code - generate_c_code(protocol_file, out_dir.join("wayland_c_api.rs"), Side::Client); - generate_c_interfaces(protocol_file, out_dir.join("wayland_c_interfaces.rs")); - } else { - generate_rust_code(protocol_file, out_dir.join("wayland_rust_api.rs"), Side::Client); - } -} diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/examples/dynamic_globals.rs b/third_party/cargo/vendor/wayland-client-0.21.13/examples/dynamic_globals.rs deleted file mode 100644 index 9921838..0000000 --- a/third_party/cargo/vendor/wayland-client-0.21.13/examples/dynamic_globals.rs +++ /dev/null @@ -1,109 +0,0 @@ -#[macro_use] -extern crate wayland_client; - -use wayland_client::{Display, GlobalManager}; - -use wayland_client::protocol::{wl_output, wl_seat}; - -// An example showcasing the capability of GlobalManager to handle -// dynamically created globals like wl_seat or wl_output, which can -// exist with multiplicity and created at any time - -fn main() { - let (display, mut event_queue) = Display::connect_to_env().unwrap(); - - // We create a GlobalManager with a callback, that will be - // advertised of any global creation or deletion - let _globals = GlobalManager::new_with_cb( - &display, - // This macro generates a callback for auto-creating the globals - // that interest us and calling our provided callbacks - global_filter!( - // Here we ask that all seats be automatically instantiated - // with version 1 when advertised, and provide a callback that - // will handle the created wl_seat to implement them - // - // NOTE: the type annotations are necessary because rustc's - // inference is apparently not smart enough - [wl_seat::WlSeat, 1, |seat: NewProxy<_>| { - let mut seat_name = None; - let mut caps = None; - seat.implement( - move |event, _| { - use wayland_client::protocol::wl_seat::Event; - match event { - Event::Name { name } => { - seat_name = Some(name); - } - Event::Capabilities { capabilities } => { - // We *should* have received the "name" event first - caps = Some(capabilities); - } - } - }, - (), - ) - }], - // Same thing with wl_output, but we require version 2 - [wl_output::WlOutput, 2, |output: NewProxy<_>| { - let mut name = "".to_owned(); - let mut modes = Vec::new(); - let mut scale = 1; - output.implement( - move |event, _| { - use wayland_client::protocol::wl_output::Event; - match event { - Event::Geometry { - x, - y, - physical_width, - physical_height, - subpixel, - make, - model, - transform, - } => { - println!("New output: \"{} ({})\"", make, model); - println!(" -> physical dimensions {}x{}", physical_width, physical_height); - println!(" -> location in the compositor space: ({}, {})", x, y); - println!(" -> transform: {:?}", transform); - println!(" -> subpixel orientation: {:?}", subpixel); - name = format!("{} ({})", make, model); - } - Event::Mode { - flags, - width, - height, - refresh, - } => { - modes.push((flags, width, height, refresh)); - } - Event::Scale { factor } => { - scale = factor; - } - Event::Done => { - println!("Modesetting information for output \"{}\"", name); - println!(" -> scaling factor: {}", scale); - println!(" -> mode list:"); - for &(f, w, h, r) in &modes { - println!( - " -> {}x{} @{}Hz (flags: [ {:?} ])", - w, - h, - (r as f32) / 1000.0, - f - ); - } - } - } - }, - (), - ) - }] - ), - ); - - event_queue.sync_roundtrip().unwrap(); - event_queue.sync_roundtrip().unwrap(); - event_queue.sync_roundtrip().unwrap(); -} diff --git a/third_party/cargo/vendor/wayland-client-0.23.6/.cargo-checksum.json b/third_party/cargo/vendor/wayland-client-0.23.6/.cargo-checksum.json new file mode 100644 index 0000000..8d6c126 --- /dev/null +++ b/third_party/cargo/vendor/wayland-client-0.23.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"2bb10aaa43e6b3e20c7fe335f58517c68c130849e0d77f84f37252facdfde9da","Cargo.toml":"9cb0ba64adcbe8c813bf58b2db3c1252689c534588ac842ed9c9804a70347672","build.rs":"b6b886ce8f337caf6acbe900961e0e7021e448b0ab8e241d95d91526e54807e7","examples/dynamic_globals.rs":"d782f7dcb853cc3606b9961d662e7d4ef768b7a26696ef66094a39a06b5cb4a5","examples/list_globals.rs":"b05d691efa2b9a69680abba94601fc4063fb7c465228e098024336dfc652b194","examples/simple_window.rs":"bbe0768f15559c289185dceef947a97b3edb8f5a3fe1c8984e660a52ba6a4173","src/cursor.rs":"ee3fe43cf9d52086b000377795cd11fca1460088ffb36a7c7cae98a1c89eed34","src/display.rs":"5da121e1b15dcb342e329c75cf4547f04a86f8adb237f7be5951d48a521a3186","src/egl.rs":"75595ba95ba0dfee649b35981dbe59d16964c28dd340b835ffb522612f961c63","src/event_queue.rs":"7480d07c6f0e141ec397afd70ef7f2ff80d06c593720d5db95041bb7cc3b3aed","src/globals.rs":"c7e7263b99bf7cddca1cbea9a2cab21bba043bef5c6fd2ec8326660523f0dc89","src/lib.rs":"161f718a11ca67412ff28d5a2f470c51624eb36f702f6e99f3d66696d4e70736","src/native_lib/display.rs":"16116283445437d781aec2f143b7151e32b1136a20ee4f471ed011dced80ee57","src/native_lib/event_queue.rs":"20dd8e2ccdcbc94cb5d0973b91e8d6a22ee3cbec3ce4f3230792ad99fb5c57f9","src/native_lib/mod.rs":"4c8412191bb696642f4dbb1df93eb74319188cb68ae514d8d3fc747f23db8d17","src/native_lib/proxy.rs":"119d028db2b80d49468abc251280f2e6c8e3aa6c3ba612c078450f0357112c3c","src/proxy.rs":"be526c2c2c38202eb234763d707da3a192e8a9adfe1e6d200e29647a8a4734c9","src/rust_imp/connection.rs":"854e522c43656573462b52fec92f8bfa34c90887f8d7855ead883aac3dead1be","src/rust_imp/display.rs":"84e373922c41779950389fe503cbdcb930d9a6aa1a3fa12824dd1b341157f9ca","src/rust_imp/mod.rs":"1ab0c9fd73c84e9e44ecc109c91986c5036936b8aef2e903b669e0d9243c1c1a","src/rust_imp/proxy.rs":"e91407f93e5ef593828687fa51720ca942fcac6256f1cb92ad4a92e2f1c43d90","src/rust_imp/queues.rs":"dc58ce9cd87f91e68e600109fa4ef08719ea6d509ca900bc220acfc50e2fc7a6","src/sinks.rs":"68e2702134a4e1ebae8ae6c60d3635d9b5bbec953202cd3e01350c0978f997ec","wayland.xml":"bdbb6e687de243860ef207a459f185661e5076ad74bc1849a2fe7d754e965ea7"},"package":"af1080ebe0efabcf12aef2132152f616038f2d7dcbbccf7b2d8c5270fe14bcda"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/BUILD b/third_party/cargo/vendor/wayland-client-0.23.6/BUILD similarity index 82% rename from third_party/cargo/vendor/wayland-client-0.21.13/BUILD rename to third_party/cargo/vendor/wayland-client-0.23.6/BUILD index e616c2d..82a50bc 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/BUILD +++ b/third_party/cargo/vendor/wayland-client-0.23.6/BUILD @@ -28,20 +28,22 @@ rust_binary( crate_root = "build.rs", edition = "2015", deps = [ - "//third_party/cargo/vendor/wayland-scanner-0.21.13:wayland_scanner", + "//third_party/cargo/vendor/wayland-scanner-0.23.6:wayland_scanner", ], rustc_flags = [ "--cap-lints=allow", ], crate_features = [ + "calloop", "cursor", "dlopen", "egl", + "eventloop", + "mio", "native_lib", - "wayland-sys", ], data = glob(["*"]), - version = "0.21.13", + version = "0.23.6", visibility = ["//visibility:private"], ) @@ -59,11 +61,13 @@ genrule( # See also: https://github.com/google/cargo-raze/pull/54 + " export TARGET='x86_64-unknown-linux-gnu';" + " export RUST_BACKTRACE=1;" + + " export CARGO_FEATURE_CALLOOP=1;" + " export CARGO_FEATURE_CURSOR=1;" + " export CARGO_FEATURE_DLOPEN=1;" + " export CARGO_FEATURE_EGL=1;" + + " export CARGO_FEATURE_EVENTLOOP=1;" + + " export CARGO_FEATURE_MIO=1;" + " export CARGO_FEATURE_NATIVE_LIB=1;" - + " export CARGO_FEATURE_WAYLAND_SYS=1;" + " export OUT_DIR=$$PWD/$$(dirname $@)/wayland_client_out_dir_outputs;" + " export BINARY_PATH=\"$$PWD/$(location :wayland_client_build_script)\";" + " export OUT_TAR=$$PWD/$@;" @@ -82,23 +86,27 @@ rust_library( srcs = glob(["**/*.rs"]), deps = [ "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", + "//third_party/cargo/vendor/calloop-0.4.4:calloop", "//third_party/cargo/vendor/downcast-rs-1.1.1:downcast_rs", "//third_party/cargo/vendor/libc-0.2.67:libc", + "//third_party/cargo/vendor/mio-0.6.21:mio", "//third_party/cargo/vendor/nix-0.14.1:nix", - "//third_party/cargo/vendor/wayland-commons-0.21.13:wayland_commons", - "//third_party/cargo/vendor/wayland-sys-0.21.13:wayland_sys", + "//third_party/cargo/vendor/wayland-commons-0.23.6:wayland_commons", + "//third_party/cargo/vendor/wayland-sys-0.23.6:wayland_sys", ], rustc_flags = [ "--cap-lints=allow", ], out_dir_tar = ":wayland_client_build_script_executor", - version = "0.21.13", + version = "0.23.6", crate_features = [ + "calloop", "cursor", "dlopen", "egl", + "eventloop", + "mio", "native_lib", - "wayland-sys", ], ) diff --git a/third_party/cargo/vendor/wayland-client-0.23.6/Cargo.lock b/third_party/cargo/vendor/wayland-client-0.23.6/Cargo.lock new file mode 100644 index 0000000..36b8241 --- /dev/null +++ b/third_party/cargo/vendor/wayland-client-0.23.6/Cargo.lock @@ -0,0 +1,429 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "byteorder" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "c2-chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ppv-lite86 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "calloop" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)", + "mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cc" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "dlib" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libloading 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "downcast-rs" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "getrandom" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "wasi 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "iovec" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "lazycell" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.62" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libloading" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "log" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "mio" +version = "0.6.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "mio-extras" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)", + "slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "miow" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "net2" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "getrandom 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_chacha 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_hc 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_chacha" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "c2-chacha 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "getrandom 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "remove_dir_all" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "slab" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "tempfile" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", + "remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "wasi" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "wayland-client" +version = "0.23.6" +dependencies = [ + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "calloop 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", + "downcast-rs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-scanner 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-commons" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-scanner" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "xml-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3d155346769a6855b86399e9bc3814ab343cd3d62c7e985113d46a0ec3c281fd" +"checksum byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" +"checksum c2-chacha 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7d64d04786e0f528460fc884753cf8dddcc466be308f6026f8e355c41a0e4101" +"checksum calloop 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "7aa2097be53a00de9e8fc349fea6d76221f398f5c4fa550d420669906962d160" +"checksum cc 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)" = "a61c7bce55cd2fae6ec8cb935ebd76256c2959a1f95790f6118a441c2cd5b406" +"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" +"checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" +"checksum downcast-rs 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b92dfd5c2f75260cbf750572f95d387e7ca0ba5e3fbe9e1a33f23025be020f" +"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +"checksum getrandom 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "473a1265acc8ff1e808cd0a1af8cee3c2ee5200916058a2ca113c29f2d903571" +"checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" +"checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" +"checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" +"checksum libloading 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b111a074963af1d37a139918ac6d49ad1d0d5e47f72fd55388619691a7d753" +"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +"checksum mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)" = "83f51996a3ed004ef184e16818edc51fadffe8e7ca68be67f9dee67d84d0ff23" +"checksum mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "46e73a04c2fa6250b8d802134d56d554a9ec2922bf977777c805ea5def61ce40" +"checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" +"checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" +"checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" +"checksum ppv-lite86 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e3cbf9f658cdb5000fcf6f362b8ea2ba154b9f146a61c7a20d647034c6b6561b" +"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum rand 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d47eab0e83d9693d40f825f86948aa16eff6750ead4bdffc4ab95b8b3a7f052c" +"checksum rand_chacha 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "03a2a90da8c7523f554344f921aa97283eadf6ac484a6d2a7d0212fa7f8d6853" +"checksum rand_core 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +"checksum rand_hc 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +"checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" +"checksum remove_dir_all 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "4a83fa3702a688b9359eccba92d153ac33fd2e8462f9e0e3fdf155239ea7792e" +"checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" +"checksum tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum wasi 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b89c3ce4ce14bdc6fb6beaf9ec7928ca331de5df7e5ea278375642a2f478570d" +"checksum wayland-commons 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "bb66b0d1a27c39bbce712b6372131c6e25149f03ffb0cd017cf8f7de8d66dbdb" +"checksum wayland-scanner 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93b02247366f395b9258054f964fe293ddd019c3237afba9be2ccbe9e1651c3d" +"checksum wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4" +"checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/Cargo.toml b/third_party/cargo/vendor/wayland-client-0.23.6/Cargo.toml similarity index 87% rename from third_party/cargo/vendor/wayland-client-0.21.13/Cargo.toml rename to third_party/cargo/vendor/wayland-client-0.23.6/Cargo.toml index c43ee4e..e936f56 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/Cargo.toml +++ b/third_party/cargo/vendor/wayland-client-0.23.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "wayland-client" -version = "0.21.13" +version = "0.23.6" authors = ["Victor Berger "] build = "build.rs" description = "Bindings to the standard C implementation of the wayland protocol, client side." @@ -42,25 +42,23 @@ optional = true version = "0.14.1" [dependencies.wayland-commons] -version = "0.21.13" +version = "0.23.6" [dependencies.wayland-sys] -version = "0.21.13" -features = ["client"] -optional = true +version = "0.23.6" [dev-dependencies.byteorder] version = "1.0" [dev-dependencies.tempfile] version = ">=2.0, <4.0" [build-dependencies.wayland-scanner] -version = "0.21.13" +version = "0.23.6" [features] cursor = ["wayland-sys/cursor", "native_lib"] dlopen = ["wayland-sys/dlopen", "native_lib"] egl = ["wayland-sys/egl", "native_lib"] eventloop = ["calloop", "mio"] -native_lib = ["wayland-sys", "wayland-commons/native_lib"] +native_lib = ["wayland-sys/client"] [badges.travis-ci] repository = "Smithay/wayland-rs" diff --git a/third_party/cargo/vendor/wayland-client-0.23.6/build.rs b/third_party/cargo/vendor/wayland-client-0.23.6/build.rs new file mode 100644 index 0000000..3f0d32c --- /dev/null +++ b/third_party/cargo/vendor/wayland-client-0.23.6/build.rs @@ -0,0 +1,20 @@ +extern crate wayland_scanner; + +use std::env::var; +use std::path::Path; +use wayland_scanner::*; + +fn main() { + let protocol_file = "./wayland.xml"; + + let out_dir_str = var("OUT_DIR").unwrap(); + let out_dir = Path::new(&out_dir_str); + + println!("cargo:rerun-if-changed={}", protocol_file); + generate_code_with_destructor_events( + protocol_file, + out_dir.join("wayland_api.rs"), + Side::Client, + &[("wl_callback", "done")], + ); +} diff --git a/third_party/cargo/vendor/wayland-client-0.23.6/examples/dynamic_globals.rs b/third_party/cargo/vendor/wayland-client-0.23.6/examples/dynamic_globals.rs new file mode 100644 index 0000000..97ad518 --- /dev/null +++ b/third_party/cargo/vendor/wayland-client-0.23.6/examples/dynamic_globals.rs @@ -0,0 +1,118 @@ +#[macro_use] +extern crate wayland_client; + +use wayland_client::{Display, GlobalManager}; + +use wayland_client::protocol::wl_output::{Mode, Subpixel, Transform, WlOutput}; +use wayland_client::protocol::{wl_output, wl_seat}; + +// An example showcasing the capability of GlobalManager to handle +// dynamically created globals like wl_seat or wl_output, which can +// exist with multiplicity and created at any time + +/// An event handler for wl_output. +/// +/// We will use it to implement the wl_output globals. +struct OutputHandler { + name: String, + modes: Vec<(Mode, i32, i32, i32)>, + scale: i32, +} + +impl wl_output::EventHandler for OutputHandler { + fn geometry( + &mut self, + _output: WlOutput, + x: i32, + y: i32, + physical_width: i32, + physical_height: i32, + subpixel: Subpixel, + make: String, + model: String, + transform: Transform, + ) { + println!("New output: \"{} ({})\"", make, model); + println!(" -> physical dimensions {}x{}", physical_width, physical_height); + println!(" -> location in the compositor space: ({}, {})", x, y); + println!(" -> transform: {:?}", transform); + println!(" -> subpixel orientation: {:?}", subpixel); + self.name = format!("{} ({})", make, model); + } + + fn mode(&mut self, _output: WlOutput, flags: Mode, width: i32, height: i32, refresh: i32) { + self.modes.push((flags, width, height, refresh)); + } + + fn scale(&mut self, _output: WlOutput, factor: i32) { + self.scale = factor; + } + + fn done(&mut self, _output: WlOutput) { + println!("Modesetting information for output \"{}\"", self.name); + println!(" -> scaling factor: {}", self.scale); + println!(" -> mode list:"); + for &(f, w, h, r) in &self.modes { + println!( + " -> {}x{} @{}Hz (flags: [ {:?} ])", + w, + h, + (r as f32) / 1000.0, + f + ); + } + } +} + +fn main() { + let (display, mut event_queue) = Display::connect_to_env().unwrap(); + + // We create a GlobalManager with a callback, that will be + // advertised of any global creation or deletion + let _globals = GlobalManager::new_with_cb( + &display, + // This macro generates a callback for auto-creating the globals + // that interest us and calling our provided callbacks + global_filter!( + // Here we ask that all seats be automatically instantiated + // with version 1 when advertised, and provide a callback that + // will handle the created wl_seat to implement them + // + // NOTE: the type annotations are necessary because rustc's + // inference is apparently not smart enough + [wl_seat::WlSeat, 1, |seat: NewProxy<_>| { + let mut seat_name = None; + let mut caps = None; + seat.implement_closure( + move |event, _| { + use wayland_client::protocol::wl_seat::Event; + match event { + Event::Name { name } => { + seat_name = Some(name); + } + Event::Capabilities { capabilities } => { + // We *should* have received the "name" event first + caps = Some(capabilities); + } + _ => {} + } + }, + (), + ) + }], + // Same thing with wl_output, but we require version 2 + [wl_output::WlOutput, 2, |output: NewProxy<_>| output.implement( + OutputHandler { + name: "".to_owned(), + modes: vec![], + scale: 1, + }, + () + )] + ), + ); + + event_queue.sync_roundtrip().unwrap(); + event_queue.sync_roundtrip().unwrap(); + event_queue.sync_roundtrip().unwrap(); +} diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/examples/list_globals.rs b/third_party/cargo/vendor/wayland-client-0.23.6/examples/list_globals.rs similarity index 100% rename from third_party/cargo/vendor/wayland-client-0.21.13/examples/list_globals.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/examples/list_globals.rs diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/examples/simple_window.rs b/third_party/cargo/vendor/wayland-client-0.23.6/examples/simple_window.rs similarity index 56% rename from third_party/cargo/vendor/wayland-client-0.21.13/examples/simple_window.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/examples/simple_window.rs index 2464c4c..e21a178 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/examples/simple_window.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/examples/simple_window.rs @@ -1,5 +1,6 @@ extern crate byteorder; extern crate tempfile; +#[macro_use(event_enum)] extern crate wayland_client; use std::cmp::min; @@ -8,14 +9,16 @@ use std::os::unix::io::AsRawFd; use byteorder::{NativeEndian, WriteBytesExt}; -use wayland_client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use wayland_client::protocol::wl_shell::RequestsTrait as ShellRequests; -use wayland_client::protocol::wl_shell_surface::RequestsTrait as ShellSurfaceRequests; -use wayland_client::protocol::wl_shm::RequestsTrait as ShmRequests; -use wayland_client::protocol::wl_shm_pool::RequestsTrait as PoolRequests; -use wayland_client::protocol::wl_surface::RequestsTrait as SurfaceRequests; -use wayland_client::protocol::{wl_compositor, wl_seat, wl_shell, wl_shell_surface, wl_shm}; -use wayland_client::{Display, GlobalManager, Proxy}; +use wayland_client::protocol::{wl_compositor, wl_keyboard, wl_pointer, wl_seat, wl_shell, wl_shm}; +use wayland_client::sinks::blocking_message_iterator; +use wayland_client::{Display, GlobalManager}; + +// declare an event enum containing the events we want to receive in the iterator +event_enum!( + Events | + Pointer => wl_pointer::WlPointer, + Keyboard => wl_keyboard::WlKeyboard +); fn main() { let (display, mut event_queue) = Display::connect_to_env().unwrap(); @@ -51,22 +54,22 @@ fn main() { // The compositor allows us to creates surfaces let compositor = globals - .instantiate_auto::(|comp| comp.implement(|_, _| {}, ())) + .instantiate_exact::(1, |comp| comp.implement_dummy()) .unwrap(); let surface = compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(|surface| surface.implement_dummy()) .unwrap(); // The SHM allows us to share memory with the server, and create buffers // on this shared memory to paint our surfaces let shm = globals - .instantiate_auto::(|shm| shm.implement(|_, _| {}, ())) + .instantiate_exact::(1, |shm| shm.implement_dummy()) .unwrap(); let pool = shm .create_pool( tmp.as_raw_fd(), // RawFd to the tempfile serving as shared memory (buf_x * buf_y * 4) as i32, // size in bytes of the shared memory (4 bytes per pixel) - |pool| pool.implement(|_, _| {}, ()), + |pool| pool.implement_dummy(), ) .unwrap(); let buffer = pool @@ -76,7 +79,7 @@ fn main() { buf_y as i32, // height of the buffer in pixels (buf_x * 4) as i32, // number of bytes between the beginning of two consecutive lines wl_shm::Format::Argb8888, // chosen encoding for the data - |buffer| buffer.implement(|_, _| {}, ()), + |buffer| buffer.implement_dummy(), ) .unwrap(); @@ -86,13 +89,13 @@ fn main() { // NOTE: the wl_shell interface is actually deprecated in favour of the xdg_shell // protocol, available in wayland-protocols. But this will do for this example. let shell = globals - .instantiate_auto::(|shell| shell.implement(|_, _| {}, ())) + .instantiate_exact::(1, |shell| shell.implement_dummy()) .unwrap(); let shell_surface = shell .get_shell_surface(&surface, |shellsurface| { - shellsurface.implement( - |event, shell_surface: Proxy| { - use wayland_client::protocol::wl_shell_surface::{Event, RequestsTrait}; + shellsurface.implement_closure( + |event, shell_surface| { + use wayland_client::protocol::wl_shell_surface::Event; // This ping/pong mechanism is used by the wayland server to detect // unresponsive applications if let Event::Ping { serial } = event { @@ -109,51 +112,37 @@ fn main() { surface.attach(Some(&buffer), 0, 0); surface.commit(); - // initialize a seat to retrieve pointer events + // initialize a seat to retrieve pointer & keyboard events + // + // we will dump them into a message iterator for easier handling + let (sink, msg_iter) = blocking_message_iterator(event_queue.get_token()); // to be handled properly this should be more dynamic, as more // than one seat can exist (and they can be created and destroyed // dynamically), however most "traditional" setups have a single // seat, so we'll keep it simple here let mut pointer_created = false; - globals.instantiate_auto::(|seat| { - seat.implement( - move |event, seat: Proxy| { + let mut keyboard_created = false; + globals.instantiate_exact::(1, |seat| { + seat.implement_closure( + move |event, seat| { // The capabilities of a seat are known at runtime and we retrieve // them via an events. 3 capabilities exists: pointer, keyboard, and touch // we are only interested in pointer here use wayland_client::protocol::wl_pointer::Event as PointerEvent; - use wayland_client::protocol::wl_seat::{ - Capability, Event as SeatEvent, RequestsTrait as SeatRequests, - }; + use wayland_client::protocol::wl_seat::{Capability, Event as SeatEvent}; if let SeatEvent::Capabilities { capabilities } = event { if !pointer_created && capabilities.contains(Capability::Pointer) { // create the pointer only once pointer_created = true; - seat.get_pointer(|pointer| { - pointer.implement( - |event, _| match event { - PointerEvent::Enter { - surface_x, surface_y, .. - } => { - println!("Pointer entered at ({}, {}).", surface_x, surface_y); - } - PointerEvent::Leave { .. } => { - println!("Pointer left."); - } - PointerEvent::Motion { - surface_x, surface_y, .. - } => { - println!("Pointer moved to ({}, {}).", surface_x, surface_y); - } - PointerEvent::Button { button, state, .. } => { - println!("Button {} was {:?}.", button, state); - } - _ => {} - }, - (), - ) - }); + seat.get_pointer(|pointer| pointer.implement(sink.clone(), ())) + .unwrap(); + } + if !keyboard_created && capabilities.contains(Capability::Keyboard) { + // create the keyboard only once + keyboard_created = false; + seat.get_keyboard(|keyboard| keyboard.implement(sink.clone(), ())) + .unwrap(); } } }, @@ -161,8 +150,42 @@ fn main() { ) }); - loop { - display.flush().unwrap(); - event_queue.dispatch().unwrap(); + // the main loop of our program + // + // the message iterator will block waiting for new events + for msg in msg_iter { + match msg { + Events::Pointer { event, .. } => match event { + wl_pointer::Event::Enter { + surface_x, surface_y, .. + } => { + println!("Pointer entered at ({}, {}).", surface_x, surface_y); + } + wl_pointer::Event::Leave { .. } => { + println!("Pointer left."); + } + wl_pointer::Event::Motion { + surface_x, surface_y, .. + } => { + println!("Pointer moved to ({}, {}).", surface_x, surface_y); + } + wl_pointer::Event::Button { button, state, .. } => { + println!("Button {} was {:?}.", button, state); + } + _ => {} + }, + Events::Keyboard { event, .. } => match event { + wl_keyboard::Event::Enter { .. } => { + println!("Gained keyboard focus."); + } + wl_keyboard::Event::Leave { .. } => { + println!("Lost keyboard focus."); + } + wl_keyboard::Event::Key { key, state, .. } => { + println!("Key with id {} was {:?}.", key, state); + } + _ => (), + }, + } } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/cursor.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/cursor.rs similarity index 72% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/cursor.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/cursor.rs index 3205eb7..7992100 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/cursor.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/cursor.rs @@ -2,17 +2,17 @@ //! //! This module contains bindings to the `libwayland-cursor.so` library. //! -//! These utilities allows you to load cursor images in order to match +//! These utilities allow you to load cursor images in order to match //! your cursors to the ones of the system. //! //! First of all, the function `load_theme` will allow you to load a //! `CursorTheme`, which represents the full cursor theme. //! -//! From this theme, you can load a specific `Cursor`, which can each -//! contain several images if the cursor is animated. It provides you -//! with the means of knowing which frame of the animation should be -//! displayed at which time, as well as handles to the buffers containing -//! these frames, to attach them to a wayland surface. +//! From this theme, you can load a specific `Cursor`, which can contain +//! several images if the cursor is animated. It also provides you with the +//! means of querying which frame of the animation should be displayed at +//! what time, as well as handles to the buffers containing these frames, to +//! attach them to a wayland surface. use protocol::wl_buffer::WlBuffer; use protocol::wl_shm::WlShm; @@ -24,9 +24,9 @@ use std::ptr; use wayland_sys::cursor::*; use Proxy; -/// Checks if the wayland-cursor lib is available and can be used +/// Checks if the wayland-cursor library is available and can be used /// -/// Trying to call any function of this module if the lib cannot +/// Trying to call any function of this module if the library cannot /// be used will result in a panic. pub fn is_available() -> bool { is_lib_available() @@ -39,21 +39,21 @@ pub struct CursorTheme { unsafe impl Send for CursorTheme {} -/// Attempts to load a cursor theme from given name. +/// Attempts to load a cursor theme. /// -/// If no name is given or the requested theme is not found, will -/// load the default theme. +/// If no name is given or the requested theme is not found, the default theme +/// will be loaded. /// /// Other arguments are the requested size for the cursor images (ex: 16) /// and a handle to the global `WlShm` object. /// -/// Panics: +/// # Panics /// -/// - If the `wayland-cursor` lib is not available (see `is_available()` function) -/// in this module. -/// - In case of memory allocation failure. -/// - If the theme name provided as argument contains an interior null -pub fn load_theme(name: Option<&str>, size: u32, shm: &Proxy) -> CursorTheme { +/// - Panics if the `wayland-cursor` lib is not available +/// (see `is_available()` function) in this module. +/// - Panics in case of memory allocation failure. +/// - Panics if `name` contains an interior null. +pub fn load_theme(name: Option<&str>, size: u32, shm: &WlShm) -> CursorTheme { let ptr = if let Some(theme) = name { let cstr = CString::new(theme).expect("Theme name contained an interior null."); unsafe { @@ -62,7 +62,7 @@ pub fn load_theme(name: Option<&str>, size: u32, shm: &Proxy) -> CursorTh wl_cursor_theme_load, cstr.as_ptr(), size as c_int, - shm.c_ptr() + shm.as_ref().c_ptr() ) } } else { @@ -72,7 +72,7 @@ pub fn load_theme(name: Option<&str>, size: u32, shm: &Proxy) -> CursorTh wl_cursor_theme_load, ptr::null(), size as c_int, - shm.c_ptr() + shm.as_ref().c_ptr() ) } }; @@ -83,10 +83,12 @@ pub fn load_theme(name: Option<&str>, size: u32, shm: &Proxy) -> CursorTh } impl CursorTheme { - /// Retrieve a cursor from the theme. + /// Retrieves a cursor from the theme. /// /// Returns `None` if this cursor is not provided by the theme. /// + /// # Panics + /// /// Panics if the name contains an interior null. pub fn get_cursor(&self, name: &str) -> Option { let cstr = CString::new(name).expect("Cursor name contained an interior null."); @@ -126,33 +128,30 @@ pub struct Cursor<'a> { unsafe impl<'a> Send for Cursor<'a> {} impl<'a> Cursor<'a> { - /// Retrieve the name of this cursor. + /// Returns the name of this cursor. pub fn name(&self) -> String { let name = unsafe { CStr::from_ptr((*self.cursor).name) }; name.to_string_lossy().into_owned() } - /// Retrieve the number of images contained in this - /// animated cursor + /// Returns the number of images contained in this animated cursor pub fn image_count(&self) -> usize { let count = unsafe { (*self.cursor).image_count }; count as usize } - /// Retrieve the image number of cursor animation. + /// Returns which frame of an animated cursor should be displayed at a given time. /// - /// Returns the image number of the animation that should be displayed - /// after a given amount of time since the beginning of the animation, - /// in milliseconds. + /// The time is given in milliseconds after the beginning of the animation. pub fn frame(&self, duration: u32) -> usize { let frame = unsafe { ffi_dispatch!(WAYLAND_CURSOR_HANDLE, wl_cursor_frame, self.cursor, duration) }; frame as usize } - /// Retrieve the image number and its duration. + /// Returns the frame number and its remaining duration. /// - /// Same as `frame()`, but also returns the number of milliseconds this - /// frame should still be displayed. + /// Same as `frame()`, but also returns the amount of milliseconds this + /// frame should continue to be displayed. pub fn frame_and_duration(&self, duration: u32) -> (usize, u32) { let mut out_duration = 0u32; let frame = unsafe { @@ -167,9 +166,9 @@ impl<'a> Cursor<'a> { (frame, out_duration) } - /// Retrieve a `CursorImageBuffer` containing the given image of an animation. + /// Returns a `CursorImageBuffer` containing the given image of an animation. /// - /// It can be used to be attached to a surface as a classic `WlBuffer`. + /// It can be attached to a surface as a classic `WlBuffer`. /// /// Returns `None` if the frame is out of bounds. /// @@ -182,17 +181,17 @@ impl<'a> Cursor<'a> { unsafe { let image = *(*self.cursor).images.offset(frame as isize); let ptr = ffi_dispatch!(WAYLAND_CURSOR_HANDLE, wl_cursor_image_get_buffer, image); - let buffer = Proxy::from_c_ptr(ptr); + let buffer = Proxy::from_c_ptr(ptr).into(); Some(CursorImageBuffer { _cursor: PhantomData, - buffer: buffer, + buffer, }) } } } - /// Retrieve the metadata associated with given frame of the animation. + /// Returns the metadata associated with a given frame of the animation. /// /// The tuple contains: `(width, height, hotspot_x, hotspot_y, delay)` /// @@ -215,20 +214,20 @@ impl<'a> Cursor<'a> { /// A buffer containing a cursor image. /// -/// You can access the `Proxy` via `Deref`. +/// You can access the `WlBuffer` via `Deref`. /// /// Note that this proxy will be considered as "unmanaged" by the crate, as such you should /// not try to act on it beyond assigning it to `wl_surface`s. pub struct CursorImageBuffer<'a> { _cursor: PhantomData<&'a Cursor<'a>>, - buffer: Proxy, + buffer: WlBuffer, } unsafe impl<'a> Send for CursorImageBuffer<'a> {} impl<'a> Deref for CursorImageBuffer<'a> { - type Target = Proxy; - fn deref(&self) -> &Proxy { + type Target = WlBuffer; + fn deref(&self) -> &WlBuffer { &self.buffer } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/display.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/display.rs similarity index 73% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/display.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/display.rs index 8ce88c7..f370412 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/display.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/display.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use nix::fcntl; -use {EventQueue, Proxy}; +use EventQueue; use imp::DisplayInner; @@ -53,13 +53,51 @@ impl ::std::fmt::Display for ConnectError { } } +/// A protocol error +/// +/// This kind of error is generated by the server if your client didn't respect +/// the protocol, after which the server will kill your connection. +/// +/// If the dispatching methods of `EventQueues` start to fail, you may want to +/// check `Display::protocol_error()` to see if a protocol error was generated. +#[derive(Clone, Debug)] +pub struct ProtocolError { + /// The error code associated with the error + /// + /// It should be interpreted as an instance of the `Error` enum of the + /// associated interface. + pub code: u32, + /// The id of the object that caused the error + pub object_id: u32, + /// The interface of the object that caused the error + pub object_interface: &'static str, + /// The message sent by the server describing the error + pub message: String, +} + +impl ::std::error::Error for ProtocolError { + fn description(&self) -> &str { + "Wayland protocol error" + } +} + +impl ::std::fmt::Display for ProtocolError { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { + write!( + f, + "Protocol error {} on object {}@{}: {}", + self.code, self.object_interface, self.object_id, self.message + ) + } +} + /// A connection to a wayland server /// -/// This object both represent the connection to the server, and as such -/// must be kept alive as long as you are connected, and contains the -/// primary `WlDisplay` wayland object, from which you can create all -/// your need objects. The inner `Proxy` can be accessed via -/// `Deref`. +/// This object both represent the connection to the server and contains the +/// primary `WlDisplay` wayland object. As such, it must be kept alive as long +/// as you are connected. You can access the contained `WlDisplay` via `Deref` +/// to create all the objects you need. +#[derive(Clone)] pub struct Display { pub(crate) inner: Arc, } @@ -70,8 +108,8 @@ impl Display { /// First of all, if the `WAYLAND_SOCKET` environment variable is set, it'll try to interpret /// it as a FD number to use /// - /// If the `WAYLAND_DISPLAY` variable is set, it will try to connect to the socket it points - /// to. Otherwise, it will default to `wayland-0`. + /// Otherwise, it will try to connect to the socket name defined in the `WAYLAND_DISPLAY` + /// environment variable, and error if it is not set. /// /// On success, you are given the `Display` object as well as the main `EventQueue` hosting /// the `WlDisplay` wayland object. @@ -101,7 +139,7 @@ impl Display { let mut socket_path = env::var_os("XDG_RUNTIME_DIR") .map(Into::::into) .ok_or(ConnectError::XdgRuntimeDirNotSet)?; - socket_path.push(env::var_os("WAYLAND_DISPLAY").unwrap_or_else(|| "wayland-0".into())); + socket_path.push(env::var_os("WAYLAND_DISPLAY").ok_or(ConnectError::NoCompositorListening)?); let socket = UnixStream::connect(socket_path).map_err(|_| ConnectError::NoCompositorListening)?; unsafe { Display::from_fd(socket.into_raw_fd()) } @@ -154,6 +192,20 @@ impl Display { EventQueue::new(evq_inner) } + /// Retrieve the last protocol error if any occured + /// + /// If your client does not respect some part of a protocol it is using, the server + /// will send a special "protocol error" event and kill your connection. This method + /// allows you to retrieve the contents of this event if it occured. + /// + /// If the dispatch methods of the `EventQueue` return an error, this is an indication + /// that a protocol error may have occured. Such errors are not recoverable, but this + /// method allows you to gracefully display them to the user, along with indications for + /// submitting a bug-report for example. + pub fn protocol_error(&self) -> Option { + self.inner.protocol_error() + } + #[cfg(feature = "native_lib")] /// Create a Display and Event Queue from an external display /// @@ -186,8 +238,8 @@ impl Display { } impl Deref for Display { - type Target = Proxy<::protocol::wl_display::WlDisplay>; - fn deref(&self) -> &Proxy<::protocol::wl_display::WlDisplay> { + type Target = ::protocol::wl_display::WlDisplay; + fn deref(&self) -> &::protocol::wl_display::WlDisplay { self.inner.get_proxy() } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/egl.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/egl.rs similarity index 93% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/egl.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/egl.rs index 23aaab2..5bf6975 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/egl.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/egl.rs @@ -11,7 +11,6 @@ use protocol::wl_surface::WlSurface; use std::os::raw::c_void; use wayland_sys::client::wl_proxy; use wayland_sys::egl::*; -use Proxy; /// Checks if the wayland-egl lib is available and can be used /// @@ -37,8 +36,8 @@ pub struct WlEglSurface { impl WlEglSurface { /// Create an EGL surface from a wayland surface - pub fn new(surface: &Proxy, width: i32, height: i32) -> WlEglSurface { - unsafe { WlEglSurface::new_from_raw(surface.c_ptr(), width, height) } + pub fn new(surface: &WlSurface, width: i32, height: i32) -> WlEglSurface { + unsafe { WlEglSurface::new_from_raw(surface.as_ref().c_ptr(), width, height) } } /// Create an EGL surface from a raw pointer to a wayland surface @@ -46,7 +45,7 @@ impl WlEglSurface { /// This function is unsafe because `surface` must be a valid wl_surface pointer pub unsafe fn new_from_raw(surface: *mut wl_proxy, width: i32, height: i32) -> WlEglSurface { let ptr = ffi_dispatch!(WAYLAND_EGL_HANDLE, wl_egl_window_create, surface, width, height); - WlEglSurface { ptr: ptr } + WlEglSurface { ptr } } /// Fetch current size of the EGL surface diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/event_queue.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/event_queue.rs similarity index 54% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/event_queue.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/event_queue.rs index 2228a7d..07f82c6 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/event_queue.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/event_queue.rs @@ -18,7 +18,11 @@ use imp::EventQueueInner; /// the queue are processed sequentially, and the appropriate implementation for each /// is invoked. When all messages have been processed these methods return. /// -/// Thus, a typical single-queue event loop for a simple wayland app can be: +/// There are two main ways to driving an event queue forward. The first way is the +/// simplest and generally sufficient for single-threaded apps that only process events +/// from wayland. It consists of using the `EventQueue::dispatch()` method, which will +/// take care of sending pending requests to the server, block until some events are +/// available, read them, and call the associated handlers: /// /// ```no_run /// # extern crate wayland_client; @@ -26,15 +30,71 @@ use imp::EventQueueInner; /// # fn main() { /// # let (display, mut event_queue) = Display::connect_to_env().unwrap(); /// loop { -/// display.flush().unwrap(); +/// // The dispatch() method returns once it has received some events to dispatch +/// // and have emptied the wayland socket from its pending messages, so it needs +/// // to be called in a loop. If this method returns an error, your connection to +/// // the wayland server is very likely dead. See its documentation for more details. /// event_queue.dispatch().expect("An error occurred during event dispatching!"); /// } /// # } /// ``` /// -/// See `EventQueue::prepare_read()` if you need more control about when the connection -/// socket is read. This will typically the case if you need to integrate other sources -/// of event into the event loop of your application. +/// The second way is more appropriate for apps that are either multithreaded (and need to process +/// wayland events from different threads conccurently) or need to react to events from different +/// sources and can't affort to just block on the wayland socket. It centers around three methods: +/// `Display::flush()`, `EventQueue::read_events()` and `EventQueue::dispatch_pending()`: +/// +/// ```no_run +/// # extern crate wayland_client; +/// # use wayland_client::Display; +/// # fn main() { +/// # let (display, mut event_queue) = Display::connect_to_env().unwrap(); +/// loop { +/// // The first method, called on the Display, is flush(). It writes all pending +/// // requests to the socket. Calling it ensures that the server will indeed +/// // receive your requests (so it can react to them). +/// if let Err(e) = display.flush() { +/// if e.kind() != ::std::io::ErrorKind::WouldBlock { +/// // if you are sending a realy large number of request, it might fill +/// // the internal buffers of the socket, in which case you should just +/// // retry flushing later. Other errors are a problem though. +/// eprintln!("Error while trying to flush the wayland socket: {:?}", e); +/// } +/// } +/// +/// // The second method will try to read events from the socket. It is done in two +/// // steps, first the read is prepared, and then it is actually executed. This allows +/// // lower contention when different threads are trying to trigger a read of events +/// // concurently +/// if let Some(guard) = event_queue.prepare_read() { +/// // prepare_read() returns None if there are already events pending in this +/// // event queue, in which case there is no need to try to read from the socket +/// if let Err(e) = guard.read_events() { +/// if e.kind() != ::std::io::ErrorKind::WouldBlock { +/// // if read_events() returns Err(WouldBlock), this just means that no new +/// // messages are available to be read +/// eprintln!("Error while trying to read from the wayland socket: {:?}", e); +/// } +/// } +/// } +/// +/// // Then, once events have been read from the socket and stored in the internal +/// // queues, they need to be dispatched to their handler. Note that while flush() +/// // and read_events() are global and will affect the whole connection, this last +/// // method will only affect the event queue it is being called on. This method +/// // cannot error unless there is a bug in the server or a previous read of events +/// // already errored. +/// event_queue.dispatch_pending().expect("Failed to dispatch all messages."); +/// +/// // Note that none of these methods are blocking, as such they should not be used +/// // as a loop as-is if there are no other sources of events your program is waiting on. +/// +/// // The wayland socket can also be integrated in a poll-like mechanism, using +/// // either the integration with calloop provided by the "eventloop" cargo feature, +/// // or the get_connection_fd() method. +/// } +/// # } +/// ``` pub struct EventQueue { // EventQueue is *not* Send pub(crate) inner: Rc, @@ -64,8 +124,8 @@ impl EventQueue { /// This process can insert events in the internal buffers of /// other event queues. /// - /// If an error is returned, your connection with the wayland - /// compositor is probably lost. + /// If an error is returned, your connection with the wayland compositor is probably lost. + /// You may want to check `Display::protocol_error()` to see if it was caused by a protocol error. pub fn dispatch(&mut self) -> io::Result { self.inner.dispatch() } @@ -76,8 +136,8 @@ impl EventQueue { /// Never blocks, if no events were pending, simply returns /// `Ok(0)`. /// - /// If an error is returned, your connection with the wayland - /// compositor is probably lost. + /// If an error is returned, your connection with the wayland compositor is probably lost. + /// You may want to check `Display::protocol_error()` to see if it was caused by a protocol error. pub fn dispatch_pending(&mut self) -> io::Result { self.inner.dispatch_pending() } @@ -91,6 +151,8 @@ impl EventQueue { /// Handlers are called as a consequence. /// /// On success returns the number of dispatched events. + /// If an error is returned, your connection with the wayland compositor is probably lost. + /// You may want to check `Display::protocol_error()` to see if it was caused by a protocol error. pub fn sync_roundtrip(&mut self) -> io::Result { self.inner.sync_roundtrip() } @@ -132,6 +194,14 @@ impl EventQueue { Err(()) => None, } } + + /// Retrieve the file descriptor associated with the wayland socket + /// + /// This FD should only be used to integrate into a polling mechanism, and should + /// never be directly read from or written to. + pub fn get_connection_fd(&self) -> ::std::os::unix::io::RawFd { + self.inner.get_connection_fd() + } } /// A guard over a read intention. diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/globals.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/globals.rs similarity index 65% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/globals.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/globals.rs index ed07efd..fb105fa 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/globals.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/globals.rs @@ -1,12 +1,11 @@ use std::sync::{Arc, Mutex}; -use protocol::wl_display::{self, RequestsTrait as DisplayRequests}; -use protocol::wl_registry::{self, RequestsTrait as RegistryRequests}; +use protocol::wl_display; +use protocol::wl_registry; use {Interface, NewProxy, Proxy}; struct Inner { list: Vec<(u32, String, u32)>, - callback: Box) + Send>, } /// An utility to manage global objects @@ -17,7 +16,7 @@ struct Inner { #[derive(Clone)] pub struct GlobalManager { inner: Arc>, - registry: Proxy, + registry: wl_registry::WlRegistry, } /// An error that occurred trying to bind a global @@ -67,16 +66,17 @@ pub enum GlobalEvent { impl GlobalManager { /// Create a global manager handling a registry - pub fn new(display: &Proxy) -> GlobalManager { - let inner = Arc::new(Mutex::new(Inner { - list: Vec::new(), - callback: Box::new(|_, _| {}), - })); + /// + /// In order to use `GlobalManager` from a different thread than the one `display` was created + /// on, wrap the `display` to an `EventQueue` on the appropriate thread using + /// `Proxy::make_wrapper()` before calling this function. + pub fn new(display: &wl_display::WlDisplay) -> GlobalManager { + let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .get_registry(|registry| { - registry.implement( + registry.implement_closure( move |msg, _proxy| { let mut inner = inner.lock().unwrap(); match msg { @@ -90,6 +90,7 @@ impl GlobalManager { wl_registry::Event::GlobalRemove { name } => { inner.list.retain(|&(n, _, _)| n != name); } + _ => {} } }, (), @@ -99,7 +100,7 @@ impl GlobalManager { GlobalManager { inner: inner_clone, - registry: registry, + registry, } } @@ -110,19 +111,20 @@ impl GlobalManager { /// /// This can be used if you want to handle specially certain globals, but want /// to use the default mechanism for the rest. - pub fn new_with_cb(display: &Proxy, callback: F) -> GlobalManager + /// + /// In order to use `GlobalManager` from a different thread than the one `display` was created + /// on, wrap the `display` to an `EventQueue` on the appropriate thread using + /// `Proxy::make_wrapper()` before calling this function. + pub fn new_with_cb(display: &wl_display::WlDisplay, mut callback: F) -> GlobalManager where - F: FnMut(GlobalEvent, Proxy) + Send + 'static, + F: FnMut(GlobalEvent, wl_registry::WlRegistry) + 'static, { - let inner = Arc::new(Mutex::new(Inner { - list: Vec::new(), - callback: Box::new(callback), - })); + let inner = Arc::new(Mutex::new(Inner { list: Vec::new() })); let inner_clone = inner.clone(); let registry = display .get_registry(|registry| { - registry.implement( + registry.implement_closure( move |msg, proxy| { let mut inner = inner.lock().unwrap(); let inner = &mut *inner; @@ -133,34 +135,35 @@ impl GlobalManager { version, } => { inner.list.push((name, interface.clone(), version)); - (inner.callback)( + callback( GlobalEvent::New { id: name, - interface: interface, - version: version, + interface, + version, }, proxy, - ); + ); } wl_registry::Event::GlobalRemove { name } => { if let Some((i, _)) = inner.list.iter().enumerate().find(|&(_, &(n, _, _))| n == name) - { - let (id, interface, _) = inner.list.swap_remove(i); - (inner.callback)( - GlobalEvent::Removed { - id: id, - interface: interface, - }, - proxy, - ); - } else { - panic!( - "Wayland protocol error: the server removed non-existing global \"{}\".", - name - ); - } - } + { + let (id, interface, _) = inner.list.swap_remove(i); + callback( + GlobalEvent::Removed { + id, + interface, + }, + proxy, + ); + } else { + panic!( + "Wayland protocol error: the server removed non-existing global \"{}\".", + name + ); + } + }, + _ => {} } }, (), @@ -170,39 +173,25 @@ impl GlobalManager { GlobalManager { inner: inner_clone, - registry: registry, + registry, } } - /// Instantiate a global with highest available version - /// - /// This method is only appropriate for globals that are expected to - /// not exist with multiplicity (such as `wl_compositor` or `wl_shm`), - /// as it will only bind a single one. - pub fn instantiate_auto(&self, implementor: F) -> Result, GlobalError> - where - F: FnOnce(NewProxy) -> Proxy, - { - let inner = self.inner.lock().unwrap(); - for &(id, ref interface, version) in &inner.list { - if interface == I::NAME { - return Ok(self.registry.bind(version, id, implementor).unwrap()); - } - } - Err(GlobalError::Missing) - } - /// Instantiate a global with a specific version /// - /// Like `instantiate_auto`, but will bind a specific version of - /// this global an not the highest available. - pub fn instantiate_exact( - &self, - version: u32, - implementor: F, - ) -> Result, GlobalError> + /// Meaning of requests and events can change depending on the object version you use, + /// as such unless you specifically want to support several versions of a protocol, it is + /// recommended to use this method with an hardcoded value for the version (the one you'll + /// use a as reference for your implementation). Notably you should *not* use `I::VERSION` + /// as a version, as this value can change when the protocol files are updated. + /// + /// This method is only appropriate for globals that are expected to + /// not exist with multiplicity (such as `wl_compositor` or `wl_shm`), + /// as it will always bind the first one that was advertized. + pub fn instantiate_exact(&self, version: u32, implementor: F) -> Result where - F: FnOnce(NewProxy) -> Proxy, + I: Interface + From>, + F: FnOnce(NewProxy) -> I, { let inner = self.inner.lock().unwrap(); for &(id, ref interface, server_version) in &inner.list { @@ -217,6 +206,45 @@ impl GlobalManager { Err(GlobalError::Missing) } + /// Instantiate a global from a version range + /// + /// If you want to support several versions of a particular global, this method allows you to + /// specify a range of versions that you accept. It'll bind the highest possible version that + /// is between `min_version` and `max_version` inclusive, and return an error if the highest + /// version supported by the compositor is lower than `min_version`. As for + /// `instantiate_exact`, you should not use `I::VERSION` here: the versions your code support + /// do not change when the protocol files are updated. + /// + /// When trying to support several versions of a protocol, you can check which version has + /// actually been used on any object using the `Proxy::version()` method. + /// + /// As `instantiate_exact`, it should only be used for singleton globals, for the same reasons. + pub fn instantiate_range( + &self, + min_version: u32, + max_version: u32, + implementor: F, + ) -> Result + where + I: Interface + From>, + F: FnOnce(NewProxy) -> I, + { + let inner = self.inner.lock().unwrap(); + for &(id, ref interface, version) in &inner.list { + if interface == I::NAME { + if version >= min_version { + return Ok(self + .registry + .bind(::std::cmp::min(version, max_version), id, implementor) + .unwrap()); + } else { + return Err(GlobalError::VersionTooLow(version)); + } + } + } + Err(GlobalError::Missing) + } + /// Retrieve the list of currently known globals pub fn list(&self) -> Vec<(u32, String, u32)> { self.inner.lock().unwrap().list.clone() @@ -230,7 +258,7 @@ impl GlobalManager { pub trait GlobalImplementor { /// A new global of given interface has been instantiated and you are /// supposed to provide an implementation for it. - fn new_global(&mut self, global: NewProxy) -> Proxy; + fn new_global(&mut self, global: NewProxy) -> I; /// A global was advertised but its version was lower than the minimal version /// you requested. /// @@ -240,9 +268,9 @@ pub trait GlobalImplementor { impl GlobalImplementor for F where - F: FnMut(NewProxy) -> Proxy, + F: FnMut(NewProxy) -> I, { - fn new_global(&mut self, global: NewProxy) -> Proxy { + fn new_global(&mut self, global: NewProxy) -> I { (*self)(global) } } @@ -265,13 +293,13 @@ where /// ```no_run /// # #[macro_use] extern crate wayland_client; /// use wayland_client::GlobalManager; -/// # use wayland_client::{Display, NewProxy, Proxy}; +/// # use wayland_client::{Display, NewProxy}; /// use wayland_client::protocol::{wl_output, wl_seat}; /// /// # fn main() { /// # let (display, mut event_queue) = Display::connect_to_env().unwrap(); -/// # let seat_implementor: fn(NewProxy<_>) -> Proxy<_> = unimplemented!(); -/// # let output_implementor: fn(NewProxy<_>) -> Proxy<_> = unimplemented!(); +/// # let seat_implementor: fn(NewProxy<_>) -> _ = unimplemented!(); +/// # let output_implementor: fn(NewProxy<_>) -> _ = unimplemented!(); /// let globals = GlobalManager::new_with_cb( /// &display, /// global_filter!( @@ -307,16 +335,16 @@ where macro_rules! global_filter { ($([$interface:ty, $version:expr, $callback:expr]),*) => { { - use $crate::protocol::wl_registry::{self, RequestsTrait}; - use $crate::{Proxy, GlobalEvent, NewProxy, Interface, GlobalImplementor}; - type Callback = Box) + Send>; + use $crate::protocol::wl_registry; + use $crate::{GlobalEvent, NewProxy, Interface, GlobalImplementor}; + type Callback = Box; let mut callbacks: Vec<(&'static str, Callback)> = Vec::new(); // Create the callback list $({ let mut cb = { $callback }; callbacks.push(( <$interface as Interface>::NAME, - Box::new(move |id, version, registry: Proxy| { + Box::new(move |id, version, registry: wl_registry::WlRegistry| { if version < $version { GlobalImplementor::<$interface>::error(&mut cb, version); } else { @@ -324,14 +352,15 @@ macro_rules! global_filter { version, id, |newp| GlobalImplementor::<$interface>::new_global(&mut cb, newp) - ); + ) + .expect("wl_registry died unexpectedly"); } }) as Box<_> )); })* // return the global closure - move |event: GlobalEvent, registry: Proxy| { + move |event: GlobalEvent, registry: wl_registry::WlRegistry| { if let GlobalEvent::New { id, interface, version } = event { for &mut (iface, ref mut cb) in &mut callbacks { if iface == interface { diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/lib.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/lib.rs similarity index 67% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/lib.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/lib.rs index ce6eca0..40995be 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/lib.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/lib.rs @@ -3,10 +3,10 @@ //! ## Overview //! //! This crate provides the interfaces and machinery to safely create -//! client applications for the wayland protocol. It is a rust wrapper +//! client applications for the Wayland protocol. It is a rust wrapper //! around the `libwayland-client.so` C library. //! -//! The wayland protocol revolves around the creation of various objects +//! The Wayland protocol revolves around the creation of various objects //! and the exchange of messages associated to these objects. The initial //! object is always the `Display`, that you get at initialization of the //! connection, exposed by this crate as `Display::connect_to_env()`. @@ -14,63 +14,63 @@ //! ## Protocol and messages handling model //! //! The protocol being bi-directional, you can send and receive messages. -//! Sending messages is done via methods of `Proxy<_>` objects, receiving -//! and handling them is done by providing implementations. +//! Sending messages is done via methods of Rust objects corresponding to the wayland protocol +//! objects, receiving and handling them is done by providing implementations. //! //! ### Proxies //! -//! Wayland protocol objects are represented in this crate by `Proxy` -//! objects, where `I` is a type representing the interface of the considered -//! object. And object's interface (think "class" in an object-oriented context) -//! defines which messages it can send and receive. +//! The underlying representation of Wayland protocol objects in this crate is `Proxy`, +//! where `I` is the type of the considered Rust object. An object's interface (think "class" +//! in an object-oriented context) defines which messages it can send and receive. //! -//! These proxies are used to send messages to the server (in the wayland context, -//! these are called "requests"). To do so, you need to import the appropriate -//! extension trait adding these methods. For example, to use a `Proxy`, -//! you need to import `protocol::wl_surface::RequestsTrait` from this crate. +//! These proxies are used to send messages to the server (in the Wayland context, +//! these are called "requests"). You usually don't use them directly, and instead call +//! methods on the Rust objects themselves, which invoke the appropriate `Proxy` methods. //! It is also possible to directly use the `Proxy::::send(..)` method, but //! this should only be done carefully: using it improperly can mess the protocol //! state and cause protocol errors, which are fatal to the connection (the server //! will kill you). //! -//! There is not a 1 to 1 mapping between `Proxy` instances and protocol -//! objects. Rather, you can think of `Proxy` as an `Rc`-like handle to a -//! wayland object. Multiple instances of it can exist referring to the same +//! There is not a 1 to 1 mapping between Rust object instances and protocol +//! objects. Rather, you can think of the Rust objects as `Rc`-like handles to a +//! Wayland object. Multiple instances of a Rust object can exist referring to the same //! protocol object. //! -//! Similarly, the lifetimes of the protocol objects and the `Proxy` are +//! Similarly, the lifetimes of the protocol objects and the Rust objects are //! not tightly tied. As protocol objects are created and destroyed by protocol //! messages, it can happen that an object gets destroyed while one or more -//! `Proxy` still refers to it. In such case, these proxies will be disabled -//! and their `alive()` method will start to return `false`. Trying to send messages -//! with them will also fail. +//! Rust objects still refer to it. In such case, these Rust objects will be disabled +//! and the `alive()` method on the underlying `Proxy` will start to return `false`. +//! Trying to send messages with them will also fail. //! //! ### Implementations //! -//! To receive and process messages from the server to you (in wayland context they are -//! called "events"), you need to provide an `Implementation` for each wayland object +//! To receive and process messages from the server to you (in Wayland context they are +//! called "events"), you need to provide an `Implementation` for each Wayland object //! created in the protocol session. Whenever a new protocol object is created, you will //! receive a `NewProxy` object. Providing an implementation via its `implement()` method -//! will turn it into a regular `Proxy` object. +//! will turn it into a regular Rust object. //! //! **All objects must be implemented**, even if it is an implementation doing nothing. //! Failure to do so (by dropping the `NewProxy` for example) can cause future fatal //! errors if the server tries to send an event to this object. //! -//! An implementation is just an `FnMut(I::Event, Proxy), where `I` is the interface of -//! the considered object. +//! An implementation is a struct implementing the `EventHandler` trait for the interface +//! of the considered object. Alternatively, an `FnMut(I::Event, I)` closure can be +//! used with the `implement_closure()` method, where `I` is the interface +//! of the considered object. //! //! ## Event Queues //! -//! The wayland client machinery provides the possibility to have one or more event queues -//! handling the processing of received messages. All wayland objects are associated to an +//! The Wayland client machinery provides the possibility to have one or more event queues +//! handling the processing of received messages. All Wayland objects are associated to an //! event queue, which controls when its events are dispatched. //! //! Events received from the server are stored in an internal buffer, and processed (by calling //! the appropriate implementations) when the associated event queue is dispatched. //! //! A default event queue is created at the same time as the initial `Display`, and by default -//! whenever a wayland object is created, it inherits the queue of its parent (the object that sent +//! whenever a Wayland object is created, it inherits the queue of its parent (the object that sent //! or receive the message that created the new object). It means that if you only plan to use the //! default event queue, you don't need to worry about assigning objects to their queues. //! @@ -80,7 +80,7 @@ //! //! ## Dynamic linking with `libwayland-client.so` //! -//! If you need to gracefully handle the case of a system on which wayland is not installed (by +//! If you need to gracefully handle the case of a system on which Wayland is not installed (by //! fallbacking to X11 for example), you can do so by activating the `dlopen` cargo feature. //! //! When this is done, the library will be loaded a runtime rather than directly linked. And trying @@ -94,7 +94,7 @@ //! - the `cursor` feature will try to load `libwayland-cursor.so`, a library helping with loading //! system themed cursor textures, to integrate your app in the system theme. //! - the `egl` feature will try to load `libwayland-egl.so`, a library allowing the creation of -//! OpenGL surface from wayland surfaces. +//! OpenGL surface from Wayland surfaces. //! //! Both of them will also be loaded at runtime if the `dlopen` feature was provided. See their //! respective submodules for details about their use. @@ -127,8 +127,7 @@ extern crate calloop; extern crate mio; extern crate wayland_commons; -#[cfg(feature = "native_lib")] -#[macro_use] +#[cfg_attr(feature = "native_lib", macro_use)] extern crate wayland_sys; mod display; @@ -136,11 +135,11 @@ mod event_queue; mod globals; mod proxy; -pub use display::{ConnectError, Display}; +pub use display::{ConnectError, Display, ProtocolError}; pub use event_queue::{EventQueue, QueueToken, ReadEventsGuard}; pub use globals::{GlobalError, GlobalEvent, GlobalImplementor, GlobalManager}; pub use imp::ProxyMap; -pub use proxy::{NewProxy, Proxy}; +pub use proxy::{HandledBy, NewProxy, Proxy}; #[cfg(feature = "cursor")] pub mod cursor; @@ -148,7 +147,10 @@ pub mod cursor; #[cfg(feature = "egl")] pub mod egl; -pub use wayland_commons::{AnonymousObject, Interface, MessageGroup, NoMessage}; +pub mod sinks; + +pub use anonymous_object::AnonymousObject; +pub use wayland_commons::{Interface, MessageGroup, NoMessage}; // rust implementation #[cfg(not(feature = "native_lib"))] @@ -159,49 +161,65 @@ mod imp; #[path = "native_lib/mod.rs"] mod imp; -#[cfg(feature = "native_lib")] /// C-associated types /// /// Required for plugging wayland-scanner generated protocols /// or interfacing with C code using wayland objects. pub mod sys { - pub use super::generated::c_interfaces as protocol_interfaces; pub use wayland_sys::{client, common}; } -/// Generated interfaces for the core wayland protocol pub mod protocol { - #[cfg(feature = "native_lib")] - pub use generated::c_api::*; - #[cfg(not(feature = "native_lib"))] - pub use generated::rust_api::*; -} - -mod generated { #![allow(dead_code, non_camel_case_types, unused_unsafe, unused_variables)] #![allow(non_upper_case_globals, non_snake_case, unused_imports)] #![allow(missing_docs)] + #![cfg_attr(feature = "cargo-clippy", allow(clippy))] - #[cfg(feature = "native_lib")] - pub mod c_interfaces { - include!(concat!(env!("OUT_DIR"), "/wayland_c_interfaces.rs")); + pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; + pub(crate) use wayland_commons::wire::{Argument, ArgumentType, Message, MessageDesc}; + pub(crate) use wayland_commons::{Interface, MessageGroup}; + pub(crate) use wayland_sys as sys; + pub(crate) use {AnonymousObject, HandledBy, NewProxy, Proxy, ProxyMap}; + include!(concat!(env!("OUT_DIR"), "/wayland_api.rs")); +} + +mod anonymous_object { + use super::{Interface, NoMessage, Proxy}; + + /// Anonymous interface + /// + /// A special Interface implementation representing an + /// handle to an object for which the interface is not known. + #[derive(Clone, Eq, PartialEq)] + pub struct AnonymousObject(Proxy); + + impl Interface for AnonymousObject { + type Request = NoMessage; + type Event = NoMessage; + const NAME: &'static str = ""; + const VERSION: u32 = 0; + fn c_interface() -> *const ::sys::common::wl_interface { + ::std::ptr::null() + } } - #[cfg(feature = "native_lib")] - pub mod c_api { - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::wire::{Argument, ArgumentType, Message, MessageDesc}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use wayland_sys as sys; - pub(crate) use {NewProxy, Proxy, ProxyMap}; - include!(concat!(env!("OUT_DIR"), "/wayland_c_api.rs")); + + impl AsRef> for AnonymousObject { + #[inline] + fn as_ref(&self) -> &Proxy { + &self.0 + } } - #[cfg(not(feature = "native_lib"))] - pub mod rust_api { - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::wire::{Argument, ArgumentType, Message, MessageDesc}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use {NewProxy, Proxy, ProxyMap}; - include!(concat!(env!("OUT_DIR"), "/wayland_rust_api.rs")); + impl From> for AnonymousObject { + #[inline] + fn from(proxy: Proxy) -> Self { + AnonymousObject(proxy) + } + } + impl From for Proxy { + #[inline] + fn from(value: AnonymousObject) -> Self { + value.0 + } } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/display.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/display.rs similarity index 67% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/display.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/display.rs index e64ec0f..c76e503 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/display.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/display.rs @@ -10,7 +10,7 @@ use {ConnectError, Proxy}; use super::EventQueueInner; pub(crate) struct DisplayInner { - proxy: Proxy, + proxy: WlDisplay, display: *mut wl_display, } @@ -23,7 +23,7 @@ unsafe fn make_display(ptr: *mut wl_display) -> Result<(Arc, Event } let display = Arc::new(DisplayInner { - proxy: Proxy::from_c_ptr(ptr as *mut _), + proxy: Proxy::from_c_ptr(ptr as *mut _).into(), display: ptr, }); @@ -63,10 +63,36 @@ impl DisplayInner { } } - pub(crate) fn get_proxy(&self) -> &Proxy { + pub(crate) fn get_proxy(&self) -> &WlDisplay { &self.proxy } + pub(crate) fn protocol_error(&self) -> Option<::ProtocolError> { + let ret = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_get_error, self.ptr()) }; + if ret == ::nix::errno::Errno::EPROTO as i32 { + let mut interface = ::std::ptr::null_mut(); + let mut id = 0; + let code = unsafe { + ffi_dispatch!( + WAYLAND_CLIENT_HANDLE, + wl_display_get_protocol_error, + self.ptr(), + &mut interface, + &mut id + ) + }; + let interface_name = unsafe { ::std::ffi::CStr::from_ptr((*interface).name) }; + Some(::ProtocolError { + code, + object_id: id, + object_interface: interface_name.to_str().unwrap_or(""), + message: String::new(), + }) + } else { + None + } + } + pub(crate) unsafe fn from_external(display_ptr: *mut wl_display) -> (Arc, EventQueueInner) { let evq_ptr = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_create_queue, display_ptr); @@ -78,7 +104,7 @@ impl DisplayInner { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_queue, wrapper_ptr, evq_ptr); let display = Arc::new(DisplayInner { - proxy: Proxy::from_c_display_wrapper(wrapper_ptr), + proxy: Proxy::from_c_display_wrapper(wrapper_ptr).into(), display: display_ptr, }); @@ -89,13 +115,13 @@ impl DisplayInner { impl Drop for DisplayInner { fn drop(&mut self) { - if self.proxy.c_ptr() == (self.display as *mut _) { + if self.proxy.as_ref().c_ptr() == (self.display as *mut _) { // disconnect only if we are owning this display unsafe { ffi_dispatch!( WAYLAND_CLIENT_HANDLE, wl_display_disconnect, - self.proxy.c_ptr() as *mut wl_display + self.proxy.as_ref().c_ptr() as *mut wl_display ); } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/event_queue.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/event_queue.rs similarity index 99% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/event_queue.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/event_queue.rs index b36a4cd..b8020d1 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/event_queue.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/event_queue.rs @@ -16,7 +16,6 @@ impl EventQueueInner { EventQueueInner { inner, wlevq } } - #[cfg(feature = "eventloop")] pub(crate) fn get_connection_fd(&self) -> ::std::os::unix::io::RawFd { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_get_fd, self.inner.ptr()) } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/mod.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/mod.rs similarity index 100% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/mod.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/mod.rs diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/proxy.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/proxy.rs similarity index 78% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/proxy.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/proxy.rs index fdf5e12..908e48b 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/native_lib/proxy.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/native_lib/proxy.rs @@ -1,6 +1,7 @@ use std::os::raw::{c_int, c_void}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::thread::{self, ThreadId}; use wayland_commons::utils::UserData; use wayland_commons::wire::ArgumentType; @@ -15,13 +16,15 @@ use wayland_sys::common::*; pub struct ProxyInternal { alive: AtomicBool, user_data: UserData, + queue_thread: ThreadId, } impl ProxyInternal { - pub fn new(user_data: UserData) -> ProxyInternal { + pub fn new(user_data: UserData, thread_id: ThreadId) -> ProxyInternal { ProxyInternal { alive: AtomicBool::new(true), user_data, + queue_thread: thread_id, } } } @@ -30,7 +33,7 @@ impl ProxyInternal { pub(crate) struct ProxyInner { internal: Option>, ptr: *mut wl_proxy, - is_wrapper: bool, + wrapping: Option, } unsafe impl Send for ProxyInner {} @@ -52,7 +55,13 @@ impl ProxyInner { if !self.is_alive() { return 0; } - unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr) as u32 } + let version = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr) as u32 }; + if version == 0 { + // For backcompat reasons the C libs return 0 as a version for the wl_display + // So override it + return 1; + } + version } pub(crate) fn id(&self) -> u32 { @@ -71,13 +80,6 @@ impl ProxyInner { } pub(crate) fn send(&self, msg: I::Request) { - if let Some(ref internal) = self.internal { - // object is managed - if !internal.alive.load(Ordering::Acquire) { - // don't send message to dead objects ! - return; - } - } let destructor = msg.is_destructor(); msg.as_raw_c_in(|opcode, args| unsafe { ffi_dispatch!( @@ -109,13 +111,6 @@ impl ProxyInner { I: Interface, J: Interface, { - if let Some(ref internal) = self.internal { - // object is managed - if !internal.alive.load(Ordering::Acquire) { - // don't send message to dead objects ! - return Err(()); - } - } let destructor = msg.is_destructor(); let opcode = msg.opcode(); @@ -129,7 +124,7 @@ impl ProxyInner { if let Some(o) = I::Request::child(opcode, 1, &()) { if !o.is_interface::() { - panic!("Trying to use 'send_constructor' with the wrong return type. Required interface {} but the message creates interface {}") + panic!("Trying to use 'send_constructor' with the wrong return type. Required interface {} but the message creates interface {}", J::NAME, o.interface) } } else { // there is no target interface in the protocol, this is a generic object-creating @@ -165,7 +160,12 @@ impl ProxyInner { } } - Ok(unsafe { NewProxyInner::from_c_ptr(ptr) }) + let mut newp = unsafe { NewProxyInner::from_c_ptr(ptr) }; + newp.queue_thread = self + .wrapping + .or_else(|| self.internal.as_ref().map(|int| int.queue_thread)) + .unwrap_or_else(|| thread::current().id()); + Ok(newp) } pub(crate) fn equals(&self, other: &ProxyInner) -> bool { @@ -193,29 +193,34 @@ impl ProxyInner { Ok(ProxyInner { internal: self.internal.clone(), ptr: wrapper_ptr, - is_wrapper: true, + wrapping: Some(thread::current().id()), // EventQueueInner is not Send, so we are necessarily on the right thread }) } pub(crate) fn child(&self) -> NewProxyInner { let ptr = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_create, self.ptr, I::c_interface()) }; - NewProxyInner { ptr: ptr } + let queue_thread = self + .wrapping + .or_else(|| self.internal.as_ref().map(|internal| internal.queue_thread)) + .unwrap_or_else(|| thread::current().id()); + NewProxyInner { ptr, queue_thread } } pub(crate) fn c_ptr(&self) -> *mut wl_proxy { self.ptr } - pub(crate) unsafe fn from_c_ptr(ptr: *mut wl_proxy) -> Self { + pub(crate) unsafe fn from_c_ptr>>(ptr: *mut wl_proxy) -> Self { if ptr.is_null() { return ProxyInner { internal: Some(Arc::new(ProxyInternal { alive: AtomicBool::new(false), user_data: UserData::empty(), + queue_thread: thread::current().id(), })), - ptr: ptr, - is_wrapper: false, + ptr, + wrapping: None, }; } @@ -231,9 +236,9 @@ impl ProxyInner { None }; ProxyInner { - internal: internal, - ptr: ptr, - is_wrapper: false, + internal, + ptr, + wrapping: None, } } @@ -241,7 +246,7 @@ impl ProxyInner { ProxyInner { internal: None, ptr: d, - is_wrapper: true, + wrapping: Some(thread::current().id()), } } @@ -250,27 +255,38 @@ impl ProxyInner { internal: Some(Arc::new(ProxyInternal { alive: AtomicBool::new(false), user_data: UserData::empty(), + queue_thread: self + .internal + .as_ref() + .map(|int| int.queue_thread) + .unwrap_or_else(|| thread::current().id()), })), ptr: ::std::ptr::null_mut(), - is_wrapper: false, + wrapping: None, } } } pub(crate) struct NewProxyInner { ptr: *mut wl_proxy, + queue_thread: ThreadId, } impl NewProxyInner { + pub(crate) fn is_queue_on_current_thread(&self) -> bool { + self.queue_thread == thread::current().id() + } + pub(crate) unsafe fn implement( self, implementation: F, user_data: UserData, ) -> ProxyInner where - F: FnMut(I::Event, Proxy) + 'static, + I: From>, + F: FnMut(I::Event, I) + 'static, { - let new_user_data = Box::new(ProxyUserData::new(implementation, user_data)); + let new_user_data = Box::new(ProxyUserData::new(implementation, user_data, self.queue_thread)); let internal = new_user_data.internal.clone(); ffi_dispatch!( @@ -285,7 +301,7 @@ impl NewProxyInner { ProxyInner { internal: Some(internal), ptr: self.ptr, - is_wrapper: false, + wrapping: None, } } @@ -294,22 +310,27 @@ impl NewProxyInner { } pub(crate) unsafe fn from_c_ptr(ptr: *mut wl_proxy) -> NewProxyInner { - NewProxyInner { ptr: ptr } + NewProxyInner { + ptr, + queue_thread: thread::current().id(), + } } } -struct ProxyUserData { +type BoxedCallback = Box::Event, I)>; + +struct ProxyUserData>> { internal: Arc, - implem: Option)>>, + implem: Option>, } -impl ProxyUserData { - fn new(implem: F, user_data: UserData) -> ProxyUserData +impl>> ProxyUserData { + fn new(implem: F, user_data: UserData, thread_id: ThreadId) -> ProxyUserData where - F: FnMut(I::Event, Proxy) + 'static, + F: FnMut(I::Event, I) + 'static, { ProxyUserData { - internal: Arc::new(ProxyInternal::new(user_data)), + internal: Arc::new(ProxyInternal::new(user_data, thread_id)), implem: Some(Box::new(implem)), } } @@ -323,7 +344,7 @@ unsafe extern "C" fn proxy_dispatcher( args: *const wl_argument, ) -> c_int where - I: Interface, + I: Interface + From>, { let proxy = proxy as *mut wl_proxy; @@ -334,7 +355,7 @@ where let msg = I::Event::from_raw_c(proxy as *mut _, opcode, args)?; let must_destroy = msg.is_destructor(); // create the proxy object - let proxy_obj = ::Proxy::::from_c_ptr(proxy); + let proxy_obj = ::Proxy::::from_c_ptr(proxy).into(); // retrieve the impl let user_data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, proxy); { @@ -355,7 +376,7 @@ where }); // check the return status match ret { - Ok(Ok(())) => return 0, + Ok(Ok(())) => 0, Ok(Err(())) => { eprintln!( "[wayland-client error] Attempted to dispatch unknown opcode {} for {}, aborting.", diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/proxy.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/proxy.rs similarity index 51% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/proxy.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/proxy.rs index 1534d47..979b1ce 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/proxy.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/proxy.rs @@ -1,7 +1,7 @@ +use super::AnonymousObject; use wayland_commons::utils::UserData; -use wayland_commons::{AnonymousObject, Interface}; +use wayland_commons::Interface; -#[cfg(feature = "native_lib")] use wayland_sys::client::*; use event_queue::QueueToken; @@ -20,9 +20,9 @@ use ProxyMap; /// tied to the lifetime of these handles, but rather to sending or /// receiving destroying messages. /// -/// These handles are notably used to send requests to the server. To do -/// you need to import the associated `RequestsTrait` trait from the module -/// of this interface. +/// These handles are notably used to send requests to the server. To do this +/// you need to convert them to the corresponding Rust object (using `.into()`) +/// and use methods on the Rust object. pub struct Proxy { _i: ::std::marker::PhantomData<&'static I>, pub(crate) inner: ProxyInner, @@ -57,12 +57,35 @@ impl Proxy { /// /// **Warning:** This method is mostly intended to be used by code generated /// by `wayland-scanner`, and you should probably never need to use it directly, - /// but rather use the appropriate `RequestsTrait` for your proxy. + /// but rather use the appropriate methods on the Rust object. /// /// This is the generic method to send requests. /// /// If your request needs to create an object, use `send_constructor`. pub fn send(&self, msg: I::Request) { + #[cfg(feature = "native_lib")] + { + if !self.is_external() && !self.is_alive() { + return; + } + } + #[cfg(not(feature = "native_lib"))] + { + if !self.is_alive() { + return; + } + } + if msg.since() > self.version() { + let opcode = msg.opcode() as usize; + panic!( + "Cannot send request {} which requires version >= {} on proxy {}@{} which is version {}.", + I::Request::MESSAGES[opcode].name, + msg.since(), + I::NAME, + self.id(), + self.version() + ); + } self.inner.send::(msg) } @@ -70,7 +93,7 @@ impl Proxy { /// /// **Warning:** This method is mostly intended to be used by code generated /// by `wayland-scanner`, and you should probably never need to use it directly, - /// but rather use the appropriate `RequestsTrait` for your proxy. + /// but rather use the appropriate methods on the Rust object. /// /// This is the generic method to send requests that create objects /// @@ -81,15 +104,30 @@ impl Proxy { msg: I::Request, implementor: F, version: Option, - ) -> Result, ()> + ) -> Result where - J: Interface, - F: FnOnce(NewProxy) -> Proxy, + J: Interface + From>, + F: FnOnce(NewProxy) -> J, { + if !self.is_alive() { + return Err(()); + } + if msg.since() > self.version() { + let opcode = msg.opcode() as usize; + panic!( + "Cannot send request {} which requires version >= {} on proxy {}@{} which is version {}.", + I::Request::MESSAGES[opcode].name, + msg.since(), + I::NAME, + self.id(), + self.version() + ); + } self.inner .send_constructor::(msg, version) .map(NewProxy::wrap) .map(implementor) + .map(Into::into) } /// Check if the object associated with this proxy is still alive @@ -137,7 +175,7 @@ impl Proxy { /// /// **Warning:** This method is mostly intended to be used by code generated /// by `wayland-scanner`, and you should probably never need to use it directly, - /// but rather use the appropriate `RequestsTrait` for your proxy. + /// but rather use the appropriate methods on the Rust object. /// /// This creates a new wayland object, considered as a /// child of this object. It will notably inherit its interface @@ -172,32 +210,45 @@ impl Proxy { /// all objects created as the result of its requests will be assigned to /// the queue associated to the provided token, rather than the queue of /// their parent. This does not change the queue of the proxy itself. - pub fn make_wrapper(&self, queue: &QueueToken) -> Result, ()> { + pub fn make_wrapper(&self, queue: &QueueToken) -> Result + where + I: From>, + { let inner = self.inner.make_wrapper(&queue.inner)?; Ok(Proxy { _i: ::std::marker::PhantomData, inner, - }) + } + .into()) } /// Create a placeholder object, to be used with `send_constructor` /// /// **Warning:** This method is mostly intended to be used by code generated /// by `wayland-scanner`, and you should probably never need to use it directly, - /// but rather use the appropriate `RequestsTrait` for your proxy. - pub fn child_placeholder(&self) -> Proxy { - Proxy::wrap(self.inner.child_placeholder()) + /// but rather use the appropriate methods on the Rust object. + pub fn child_placeholder>>(&self) -> J { + Proxy::wrap(self.inner.child_placeholder()).into() } } -#[cfg(feature = "native_lib")] impl Proxy { /// Check whether this proxy is managed by the library or not /// /// See `from_c_ptr` for details. + /// + /// NOTE: This method will panic if called while the `native_lib` feature is + /// not activated. pub fn is_external(&self) -> bool { - self.inner.is_external() + #[cfg(feature = "native_lib")] + { + self.inner.is_external() + } + #[cfg(not(feature = "native_lib"))] + { + panic!("[wayland-client] C interfacing methods can only be used with the `native_lib` cargo feature.") + } } /// Get a raw pointer to the underlying wayland object @@ -205,8 +256,18 @@ impl Proxy { /// Retrieve a pointer to the object from the `libwayland-client.so` library. /// You will mostly need it to interface with C libraries needing access /// to wayland objects (to initialize an opengl context for example). + /// + /// NOTE: This method will panic if called while the `native_lib` feature is + /// not activated. pub fn c_ptr(&self) -> *mut wl_proxy { - self.inner.c_ptr() + #[cfg(feature = "native_lib")] + { + self.inner.c_ptr() + } + #[cfg(not(feature = "native_lib"))] + { + panic!("[wayland-client] C interfacing methods can only be used with the `native_lib` cargo feature.") + } } /// Create a `Proxy` instance from a C pointer @@ -228,10 +289,23 @@ impl Proxy { /// /// In order to handle protocol races, invoking it with a NULL pointer will /// create an already-dead object. - pub unsafe fn from_c_ptr(ptr: *mut wl_proxy) -> Proxy { - Proxy { - _i: ::std::marker::PhantomData, - inner: ProxyInner::from_c_ptr::(ptr), + /// + /// NOTE: This method will panic if called while the `native_lib` feature is + /// not activated. + pub unsafe fn from_c_ptr(_ptr: *mut wl_proxy) -> Proxy + where + I: From>, + { + #[cfg(feature = "native_lib")] + { + Proxy { + _i: ::std::marker::PhantomData, + inner: ProxyInner::from_c_ptr::(_ptr), + } + } + #[cfg(not(feature = "native_lib"))] + { + panic!("[wayland-client] C interfacing methods can only be used with the `native_lib` cargo feature.") } } } @@ -254,7 +328,7 @@ impl Proxy<::protocol::wl_display::WlDisplay> { /// receive it as a `NewProxy`. You then have to provide an /// implementation for it, in order to process the incoming /// events it may receive. Once this done you will be able -/// to use it as a regular `Proxy`. +/// to use it as a regular Rust object. /// /// Implementations are structs implementing the appropriate /// variant of the `Implementation` trait. They can also be @@ -273,11 +347,97 @@ impl NewProxy { } } - /// Implement this proxy using given function and implementation data. - pub fn implement(self, implementation: F, user_data: UD) -> Proxy + /// Implement this proxy using the given handler and implementation data. + /// + /// The handler must be a struct implementing the `EventHandler` trait of the `I` interface. + /// + /// This must be called from the same thread as the one owning the event queue this + /// new proxy is attached to and will panic otherwise. A proxy by default inherits + /// the event queue of its parent object. + /// + /// If you don't want an object to inherits its parent queue, see `Proxy::make_wrapper`. + /// + /// If you want the user data to be accessed from other threads, + /// see `implement_user_data_threadsafe`. + pub fn implement(self, mut handler: T, user_data: UD) -> I where - F: FnMut(I::Event, Proxy) + Send + 'static, + T: 'static, + UD: 'static, + I: HandledBy + From>, + I::Event: MessageGroup, + { + let implementation = move |event, proxy: I| I::handle(&mut handler, event, proxy); + + self.implement_closure(implementation, user_data) + } + + /// Implement this proxy using the given implementation closure and implementation data. + /// + /// This must be called from the same thread as the one owning the event queue this + /// new proxy is attached to and will panic otherwise. A proxy by default inherits + /// the event queue of its parent object. + /// + /// If you don't want an object to inherits its parent queue, see `Proxy::make_wrapper`. + /// + /// If you want the user data to be accessed from other threads, + /// see `implement_closure_user_data_threadsafe`. + pub fn implement_closure(self, implementation: F, user_data: UD) -> I + where + F: FnMut(I::Event, I) + 'static, + UD: 'static, + I: From>, + I::Event: MessageGroup, + { + if !self.inner.is_queue_on_current_thread() { + panic!("Trying to implement a proxy with a non-Send implementation from an other thread than the one of its event queue."); + } + let inner = unsafe { + self.inner + .implement::(implementation, UserData::new(user_data)) + }; + Proxy { + _i: ::std::marker::PhantomData, + inner, + } + .into() + } + + /// Implement this proxy using a dummy handler which does nothing. + pub fn implement_dummy(self) -> I + where + I: From>, + I::Event: MessageGroup, + { + self.implement_closure_threadsafe(|_, _| (), ()) + } + + /// Implement this proxy using the given handler and implementation data. + /// + /// The handler must be a struct implementing the `EventHandler` trait of the `I` interface. + /// + /// This function allows you to implement a proxy from an other thread than the one where its + /// event queue is attach, but the implementation thus must be `Send`. + pub fn implement_threadsafe(self, mut handler: T, user_data: UD) -> I + where + T: Send + 'static, UD: Send + Sync + 'static, + I: HandledBy + From>, + I::Event: MessageGroup, + { + let implementation = move |event, proxy: I| I::handle(&mut handler, event, proxy); + + self.implement_closure_threadsafe(implementation, user_data) + } + + /// Implement this proxy using given closure and implementation data from any thread. + /// + /// This function allows you to implement a proxy from an other thread than the one where its + /// event queue is attach, but the implementation thus must be `Send`. + pub fn implement_closure_threadsafe(self, implementation: F, user_data: UD) -> I + where + F: FnMut(I::Event, I) + Send + 'static, + UD: Send + Sync + 'static, + I: From>, I::Event: MessageGroup, { let inner = unsafe { @@ -286,53 +446,55 @@ impl NewProxy { }; Proxy { _i: ::std::marker::PhantomData, - inner: inner, + inner, } + .into() } - /// Implement this proxy using given function and implementation data. + /// Implement this proxy using the given handler and implementation data. /// - /// This method allows the implementation to not be `Send`, but requires for - /// safety that you provide a token to the event queue this proxy will be implemented - /// on. This method will then ensure that this proxy is registered on this event queue, - /// so that it cannot be dispatched from an other thread. - /// - /// **Unsafety:** - /// - /// This call can be racy if the proxy is not already registered on this event queue and its - /// old queue is being dispatched from an other thread. - /// - /// To ensure safety, see `Proxy::make_wrapper`. - pub unsafe fn implement_nonsend( - self, - implementation: Impl, - user_data: UD, - queue: &QueueToken, - ) -> Proxy + /// This must be called from the same thread as the one owning the event queue this + /// new proxy is attached to and will panic otherwise. However the user data + /// may be accessed from other threads. + pub fn implement_user_data_threadsafe(self, mut handler: T, user_data: UD) -> I where - Impl: FnMut(I::Event, Proxy) + 'static, - UD: 'static, + T: 'static, + UD: Send + Sync + 'static, + I: HandledBy + From>, I::Event: MessageGroup, { - #[cfg(feature = "native_lib")] - { - queue.inner.assign_proxy(self.inner.c_ptr()); + let implementation = move |event, proxy: I| I::handle(&mut handler, event, proxy); + + self.implement_closure_user_data_threadsafe(implementation, user_data) + } + + /// Implement this proxy using the given closure and implementation data. + /// + /// This must be called from the same thread as the one owning the event queue this + /// new proxy is attached to and will panic otherwise. However the user data + /// may be accessed from other threads. + pub fn implement_closure_user_data_threadsafe(self, implementation: F, user_data: UD) -> I + where + F: FnMut(I::Event, I) + 'static, + UD: Send + Sync + 'static, + I: From>, + I::Event: MessageGroup, + { + if !self.inner.is_queue_on_current_thread() { + panic!("Trying to implement a proxy with a non-Send implementation from an other thread than the one of its event queue."); } - #[cfg(not(feature = "native_lib"))] - { - self.inner.assign_queue(&queue.inner); - } - let inner = self - .inner - .implement::(implementation, UserData::new(user_data)); + let inner = unsafe { + self.inner + .implement::(implementation, UserData::new_threadsafe(user_data)) + }; Proxy { _i: ::std::marker::PhantomData, - inner: inner, + inner, } + .into() } } -#[cfg(feature = "native_lib")] impl NewProxy { /// Get a raw pointer to the underlying wayland object /// @@ -342,8 +504,18 @@ impl NewProxy { /// /// Use this if you need to pass an unimplemented object to the C library /// you are interfacing with. + /// + /// NOTE: This method will panic if called while the `native_lib` feature is + /// not activated. pub fn c_ptr(&self) -> *mut wl_proxy { - self.inner.c_ptr() + #[cfg(feature = "native_lib")] + { + self.inner.c_ptr() + } + #[cfg(not(feature = "native_lib"))] + { + panic!("[wayland-client] C interfacing methods can only be used with the `native_lib` cargo feature.") + } } /// Create a `NewProxy` instance from a C pointer. @@ -352,10 +524,28 @@ impl NewProxy { /// can be safely implemented. As implementing it will overwrite any previously /// associated data or implementation, this can cause weird errors akin to /// memory corruption if it was not the case. - pub unsafe fn from_c_ptr(ptr: *mut wl_proxy) -> Self { - NewProxy { - _i: ::std::marker::PhantomData, - inner: NewProxyInner::from_c_ptr(ptr), + /// + /// NOTE: This method will panic if called while the `native_lib` feature is + /// not activated. + pub unsafe fn from_c_ptr(_ptr: *mut wl_proxy) -> Self { + #[cfg(feature = "native_lib")] + { + NewProxy { + _i: ::std::marker::PhantomData, + inner: NewProxyInner::from_c_ptr(_ptr), + } + } + #[cfg(not(feature = "native_lib"))] + { + panic!("[wayland-client] C interfacing methods can only be used with the `native_lib` cargo feature.") } } } + +/// Provides a callback function to handle events of the implementing interface via `T`. +/// +/// This trait is meant to be implemented automatically by code generated with `wayland-scanner`. +pub trait HandledBy: Interface + Sized { + /// Handles an event. + fn handle(handler: &mut T, event: Self::Event, proxy: Self); +} diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/connection.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/connection.rs similarity index 73% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/connection.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/connection.rs index 049fc29..8495b19 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/connection.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/connection.rs @@ -4,16 +4,18 @@ use std::sync::{Arc, Mutex}; use nix::Result as NixResult; -use wayland_commons::map::{Object, ObjectMap}; +use wayland_commons::map::{Object, ObjectMap, SERVER_ID_LIMIT}; use wayland_commons::socket::{BufferedSocket, Socket}; use wayland_commons::wire::{Argument, ArgumentType, Message, MessageParseError}; use super::proxy::ObjectMeta; use super::queues::QueueBuffer; +use ProtocolError; + #[derive(Clone, Debug)] pub(crate) enum Error { - Protocol, + Protocol(ProtocolError), Parse(MessageParseError), Nix(::nix::Error), } @@ -70,29 +72,15 @@ impl Connection { }, |msg| { let mut map = map.borrow_mut(); - let object = match map.find(msg.sender_id) { - Some(obj) => obj, - None => { - // this is a message sent to a destroyed object - // to avoid dying because of races, we just consume it into void - // closing any associated FDs - for a in msg.args { - if let Argument::Fd(fd) = a { - let _ = ::nix::unistd::close(fd); - } - } - // continue parsing to the next message - return true; - } - }; + let object = map.find(msg.sender_id); // create a new object if applicable - if let Some(child) = object.event_child(msg.opcode) { + if let Some((mut child, dead_parent)) = object.as_ref().and_then(|o| o.event_child(msg.opcode).map(|c| (c, o.meta.client_destroyed))) { let new_id = msg .args .iter() .flat_map(|a| { - if let &Argument::NewId(nid) = a { + if let Argument::NewId(nid) = *a { Some(nid) } else { None @@ -101,6 +89,15 @@ impl Connection { .next() .unwrap(); let child_interface = child.interface; + // if this ID belonged to a now destroyed server object, we can replace it + if new_id >= SERVER_ID_LIMIT && map.with(new_id, |obj| obj.meta.client_destroyed).unwrap_or(false) { + map.remove(new_id) + } + // if the parent object is already destroyed, the user will never see this + // object, so we set it as client_destroyed to ignore all future messages to it + if dead_parent { + child.meta.client_destroyed = true; + } if let Err(()) = map.insert_at(new_id, child) { eprintln!( "[wayland-client] Protocol error: server tried to create an object \"{}\" with invalid id \"{}\".", @@ -108,17 +105,37 @@ impl Connection { new_id ); // abort parsing, this is an unrecoverable error - *last_error = Some(Error::Protocol); + *last_error = Some(Error::Protocol(::ProtocolError { + code: 0, + object_id: 0, + object_interface: "", + message: format!("Protocol error: server tried to create an object \"{}\" with invalid id \"{}\".", child_interface, new_id) + })); return false; } } else { // debug assert: if this opcode does not define a child, then there should be no // NewId argument - debug_assert!(msg.args.iter().any(|a| a.get_type() == ArgumentType::NewId) == false); + debug_assert!(!msg.args.iter().any(|a| a.get_type() == ArgumentType::NewId)); } // send the message to the appropriate pending queue - object.meta.buffer.lock().unwrap().push_back(msg); + match object { + Some(Object { meta: ObjectMeta { client_destroyed: true, .. }, .. }) | None => { + // this is a message sent to a destroyed object + // to avoid dying because of races, we just consume it into void + // closing any associated FDs + for a in msg.args { + if let Argument::Fd(fd) = a { + let _ = ::nix::unistd::close(fd); + } + } + }, + Some(obj) => { + obj.meta.buffer.lock().unwrap().push_back(msg); + } + }; + // continue parsing true }, diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/display.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/display.rs similarity index 75% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/display.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/display.rs index 744a8e0..36054e1 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/display.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/display.rs @@ -7,15 +7,15 @@ use wayland_commons::utils::UserData; use protocol::wl_display::{self, WlDisplay}; -use {ConnectError, Proxy}; +use {ConnectError, ProtocolError, Proxy}; -use super::connection::Connection; +use super::connection::{Connection, Error as CxError}; use super::proxy::{NewProxyInner, ObjectMeta}; use super::EventQueueInner; pub(crate) struct DisplayInner { connection: Arc>, - proxy: Proxy, + proxy: WlDisplay, } impl DisplayInner { @@ -45,11 +45,16 @@ impl DisplayInner { eprintln!( "[wayland-client] Protocol error {} on object {}@{}: {}", code, - object_id.inner.object.interface, - object_id.id(), + object_id.as_ref().inner.object.interface, + object_id.as_ref().id(), message ); - *impl_last_error.lock().unwrap() = Some(super::connection::Error::Protocol); + *impl_last_error.lock().unwrap() = Some(CxError::Protocol(ProtocolError { + code, + object_id: object_id.as_ref().id(), + object_interface: object_id.as_ref().inner.object.interface, + message, + })); } wl_display::Event::DeleteId { id } => { // cleanup the map as appropriate @@ -64,6 +69,7 @@ impl DisplayInner { map.remove(id); } } + _ => {} }, UserData::empty(), ); @@ -71,7 +77,7 @@ impl DisplayInner { let default_event_queue = EventQueueInner::new(connection.clone(), None); let display = DisplayInner { - proxy: Proxy::wrap(display_proxy.make_wrapper(&default_event_queue).unwrap()), + proxy: Proxy::wrap(display_proxy.make_wrapper(&default_event_queue).unwrap()).into(), connection, }; @@ -90,7 +96,17 @@ impl DisplayInner { EventQueueInner::new(me.connection.clone(), None) } - pub(crate) fn get_proxy(&self) -> &Proxy { + pub(crate) fn get_proxy(&self) -> &WlDisplay { &self.proxy } + + pub(crate) fn protocol_error(&self) -> Option { + let cx = self.connection.lock().unwrap(); + let last_error = cx.last_error.lock().unwrap(); + if let Some(CxError::Protocol(ref e)) = *last_error { + Some(e.clone()) + } else { + None + } + } } diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/mod.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/mod.rs similarity index 77% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/mod.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/mod.rs index 6fec292..1d7c3a2 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/mod.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/mod.rs @@ -18,10 +18,10 @@ pub(crate) use self::display::DisplayInner; pub(crate) use self::proxy::{NewProxyInner, ProxyInner}; pub(crate) use self::queues::EventQueueInner; -/// A handle to the object map internal to the lib state +/// A handle to the object map internal to the library state /// -/// This type is only usable by code generated by `wayland-scanner`, and is -/// not instantiable directly. +/// This type is only used by code generated by `wayland-scanner`, and can not +/// be instantiated directly. pub struct ProxyMap { map: Arc>>, connection: Arc>, @@ -35,7 +35,7 @@ impl ProxyMap { ProxyMap { map, connection } } - /// Retrieve the Proxy corresponding to a given id + /// Returns the Proxy corresponding to a given id pub fn get(&mut self, id: u32) -> Option> { ProxyInner::from_id(id, self.map.clone(), self.connection.clone()).map(|object| { debug_assert!(I::NAME == "" || object.is_interface::()); @@ -43,7 +43,7 @@ impl ProxyMap { }) } - /// Create a new proxy for given id + /// Creates a new proxy for given id pub fn get_new(&mut self, id: u32) -> Option> { debug_assert!(self .map @@ -52,8 +52,7 @@ impl ProxyMap { .find(id) .map(|obj| obj.is_interface::()) .unwrap_or(true)); - NewProxyInner::from_id(id, self.map.clone(), self.connection.clone()) - .map(|object| NewProxy::wrap(object)) + NewProxyInner::from_id(id, self.map.clone(), self.connection.clone()).map(NewProxy::wrap) } } @@ -62,13 +61,13 @@ pub(crate) trait Dispatcher: Downcast + Send { } mod dispatcher_impl { - // this mod has for sole purpose to allow to silence these `dead_code` warnings... + // this mod has the sole purpose of silencing these `dead_code` warnings... #![allow(dead_code)] use super::Dispatcher; impl_downcast!(Dispatcher); } -pub(crate) struct ImplDispatcher) + 'static> { +pub(crate) struct ImplDispatcher>, F: FnMut(I::Event, I) + 'static> { _i: ::std::marker::PhantomData<&'static I>, implementation: F, } @@ -80,7 +79,8 @@ pub(crate) struct ImplDispatcher) + 's unsafe impl Send for ImplDispatcher where I: Interface, - F: FnMut(I::Event, Proxy) + 'static, + F: FnMut(I::Event, I) + 'static, + I: From>, I::Event: MessageGroup, { } @@ -88,17 +88,30 @@ where impl Dispatcher for ImplDispatcher where I: Interface, - F: FnMut(I::Event, Proxy) + 'static, + F: FnMut(I::Event, I) + 'static, + I: From>, I::Event: MessageGroup, { fn dispatch(&mut self, msg: Message, proxy: ProxyInner, map: &mut ProxyMap) -> Result<(), ()> { + let opcode = msg.opcode as usize; if ::std::env::var_os("WAYLAND_DEBUG").is_some() { - println!( + eprintln!( " <- {}@{}: {} {:?}", - proxy.object.interface, proxy.id, proxy.object.events[msg.opcode as usize].name, msg.args + proxy.object.interface, proxy.id, proxy.object.events[opcode].name, msg.args ); } let message = I::Event::from_raw(msg, map)?; + if message.since() > proxy.version() { + eprintln!( + "Received an event {} requiring version >= {} while proxy {}@{} is version {}.", + proxy.object.events[opcode].name, + message.since(), + proxy.object.interface, + proxy.id, + proxy.version() + ); + return Err(()); + } if message.is_destructor() { proxy.object.meta.alive.store(false, Ordering::Release); { @@ -114,9 +127,9 @@ where map.remove(proxy.id); } } - (self.implementation)(message, Proxy::::wrap(proxy.clone())); + (self.implementation)(message, Proxy::::wrap(proxy.clone()).into()); } else { - (self.implementation)(message, Proxy::::wrap(proxy)); + (self.implementation)(message, Proxy::::wrap(proxy).into()); } Ok(()) } @@ -125,7 +138,8 @@ where pub(crate) unsafe fn make_dispatcher(implementation: F) -> Arc> where I: Interface, - F: FnMut(I::Event, Proxy) + 'static, + F: FnMut(I::Event, I) + 'static, + I: From>, I::Event: MessageGroup, { Arc::new(Mutex::new(ImplDispatcher { diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/proxy.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/proxy.rs similarity index 90% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/proxy.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/proxy.rs index b2f76aa..6ade7a5 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/proxy.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/proxy.rs @@ -1,5 +1,6 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; +use std::thread::{self, ThreadId}; use wayland_commons::map::{Object, ObjectMap, ObjectMetadata}; use wayland_commons::utils::UserData; @@ -19,6 +20,7 @@ pub(crate) struct ObjectMeta { pub(crate) dispatcher: Arc>, pub(crate) server_destroyed: bool, pub(crate) client_destroyed: bool, + queue_thread: ThreadId, } impl ObjectMetadata for ObjectMeta { @@ -30,6 +32,7 @@ impl ObjectMetadata for ObjectMeta { dispatcher: super::default_dispatcher(), server_destroyed: false, client_destroyed: false, + queue_thread: self.queue_thread, } } } @@ -43,6 +46,7 @@ impl ObjectMeta { dispatcher: super::default_dispatcher(), server_destroyed: false, client_destroyed: false, + queue_thread: thread::current().id(), } } @@ -54,6 +58,7 @@ impl ObjectMeta { dispatcher: super::default_dispatcher(), server_destroyed: true, client_destroyed: true, + queue_thread: thread::current().id(), } } } @@ -111,13 +116,10 @@ impl ProxyInner { // thread is sending a message an accidentally sending that message // after ours if ours is a destructor let mut conn_lock = self.connection.lock().unwrap(); - if !self.is_alive() { - return; - } let destructor = msg.is_destructor(); let msg = msg.into_raw(self.id); if ::std::env::var_os("WAYLAND_DEBUG").is_some() { - println!( + eprintln!( " -> {}@{}: {} {:?}", I::NAME, self.id, @@ -126,7 +128,7 @@ impl ProxyInner { ); } // TODO: figure our if this can fail and still be recoverable ? - let _ = conn_lock.write_message(&msg).expect("Sending a message failed."); + conn_lock.write_message(&msg).expect("Sending a message failed."); if destructor { self.object.meta.alive.store(false, Ordering::Release); { @@ -157,13 +159,10 @@ impl ProxyInner { // grab the connection lock before anything else // this avoids the risk or races during object creation let mut conn_lock = self.connection.lock().unwrap(); - if !self.is_alive() { - return Err(()); - } let destructor = msg.is_destructor(); let mut msg = msg.into_raw(self.id); if ::std::env::var_os("WAYLAND_DEBUG").is_some() { - println!( + eprintln!( " -> {}@{}: {} {:?}", I::NAME, self.id, @@ -183,7 +182,7 @@ impl ProxyInner { if let Some(o) = I::Request::child(opcode, 1, &()) { if !o.is_interface::() { - panic!("Trying to use 'send_constructor' with the wrong return type. Required interface {} but the message creates interface {}") + panic!("Trying to use 'send_constructor' with the wrong return type. Required interface {} but the message creates interface {}", J::NAME, o.interface) } } else { // there is no target interface in the protocol, this is a generic object-creating @@ -191,8 +190,8 @@ impl ProxyInner { nid_idx += 2; } // insert the newly created object in the message - let newproxy = match &mut msg.args[nid_idx] { - &mut Argument::NewId(ref mut newid) => { + let newproxy = match msg.args[nid_idx] { + Argument::NewId(ref mut newid) => { let newp = match version { Some(v) => self.child_versioned::(v), None => self.child::(), @@ -203,7 +202,7 @@ impl ProxyInner { _ => unreachable!(), }; - let _ = conn_lock.write_message(&msg).expect("Sending a message failed."); + conn_lock.write_message(&msg).expect("Sending a message failed."); if destructor { self.object.meta.alive.store(false, Ordering::Release); { @@ -231,6 +230,8 @@ impl ProxyInner { pub(crate) fn make_wrapper(&self, queue: &EventQueueInner) -> Result { let mut wrapper = self.clone(); wrapper.object.meta.buffer = queue.buffer.clone(); + // EventQueueInner is not Send so we must be in the right thread + wrapper.object.meta.queue_thread = thread::current().id(); Ok(wrapper) } @@ -277,12 +278,13 @@ impl NewProxyInner { } } - /// Racy method, if called, must be called before any event to this object - /// is read from the socket, or it'll end up in the wrong queue... - pub(crate) unsafe fn assign_queue(&self, queue: &EventQueueInner) { - let _ = self.map.lock().unwrap().with(self.id, |obj| { - obj.meta.buffer = queue.buffer.clone(); - }); + pub(crate) fn is_queue_on_current_thread(&self) -> bool { + self.map + .lock() + .unwrap() + .find(self.id) + .map(|obj| obj.meta.queue_thread == thread::current().id()) + .unwrap_or(false) } // Invariants: Impl is either `Send` or we are on the same thread as the target event loop @@ -292,7 +294,8 @@ impl NewProxyInner { user_data: UserData, ) -> ProxyInner where - F: FnMut(I::Event, Proxy) + 'static, + F: FnMut(I::Event, I) + 'static, + I: From>, I::Event: MessageGroup, { let object = self.map.lock().unwrap().with(self.id, |obj| { diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/queues.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/queues.rs similarity index 79% rename from third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/queues.rs rename to third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/queues.rs index 2488704..0823702 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/src/rust_imp/queues.rs +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/rust_imp/queues.rs @@ -9,7 +9,7 @@ use nix::poll::{poll, PollFlags, PollFd}; use wayland_commons::map::ObjectMap; use wayland_commons::utils::UserData; -use wayland_commons::wire::Message; +use wayland_commons::wire::{Argument, Message}; use super::connection::{Connection, Error as CError}; use super::proxy::{ObjectMeta, ProxyInner}; @@ -41,7 +41,6 @@ impl EventQueueInner { } } - #[cfg(feature = "eventloop")] pub(crate) fn get_connection_fd(&self) -> ::std::os::unix::io::RawFd { self.connection.lock().unwrap().socket.get_socket().as_raw_fd() } @@ -96,7 +95,13 @@ impl EventQueueInner { Err(_) => unreachable!(), } - match self.read_events() { + let read_ret = self.read_events(); + + // even if read_events returned an error, it may have queued messages the need dispatching + // so we dispatch them + let dispatch_ret = self.dispatch_pending(); + + match read_ret { Ok(_) => (), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { // we waited for read readiness be then received a WouldBlock error @@ -107,7 +112,7 @@ impl EventQueueInner { Err(e) => return Err(e), } - self.dispatch_pending() + dispatch_ret } fn dispatch_buffer(&self, buffer: &mut VecDeque) -> io::Result { @@ -117,6 +122,29 @@ impl EventQueueInner { let id = msg.sender_id; if let Some(proxy) = ProxyInner::from_id(id, self.map.clone(), self.connection.clone()) { let object = proxy.object.clone(); + if object.meta.client_destroyed { + // This is a potential race, if we reach here it means that the proxy was + // destroyed by the user between this message was queued and now. To handle it + // correctly, we must close any FDs it contains, mark any child object as + // destroyed (but the server will never know about it, so the ids will be + // leaked) and discard the event. + for arg in msg.args { + match arg { + Argument::Fd(fd) => { + let _ = ::nix::unistd::close(fd); + } + Argument::NewId(id) => { + let mut map = self.map.lock().unwrap(); + map.with(id, |obj| { + obj.meta.client_destroyed = true; + }) + .unwrap(); + } + _ => {} + } + } + continue; + } let mut dispatcher = object.meta.dispatcher.lock().unwrap(); if let Err(()) = dispatcher.dispatch(msg, proxy, &mut proxymap) { return Err(io::Error::new( @@ -154,27 +182,31 @@ impl EventQueueInner { pub(crate) fn sync_roundtrip(&self) -> io::Result { use protocol::wl_callback::{Event as CbEvent, WlCallback}; - use protocol::wl_display::{RequestsTrait as DisplayRequests, WlDisplay}; + use protocol::wl_display::WlDisplay; use Proxy; // first retrieve the display and make a wrapper for it in this event queue - let display: Proxy = Proxy::wrap( + let display: WlDisplay = Proxy::wrap( ProxyInner::from_id(1, self.map.clone(), self.connection.clone()) .unwrap() .make_wrapper(self) .unwrap(), - ); + ) + .into(); let done = Rc::new(Cell::new(false)); let ret = display.sync(|np| { Proxy::wrap(unsafe { let done2 = done.clone(); np.inner.implement::( - move |CbEvent::Done { .. }, _| { - done2.set(true); + move |evt, _| { + if let CbEvent::Done { .. } = evt { + done2.set(true); + } }, UserData::empty(), ) }) + .into() }); if let Err(()) = ret { @@ -204,7 +236,7 @@ impl EventQueueInner { // TODO: integrate more properly with prepare read with a fence match self.connection.lock().unwrap().read_events() { Ok(n) => Ok(n as i32), - Err(CError::Protocol) => Err(::nix::errno::Errno::EPROTO.into()), + Err(CError::Protocol(_)) => Err(::nix::errno::Errno::EPROTO.into()), Err(CError::Parse(_)) => Err(::nix::errno::Errno::EPROTO.into()), Err(CError::Nix(::nix::Error::Sys(errno))) => Err(errno.into()), Err(CError::Nix(_)) => unreachable!(), diff --git a/third_party/cargo/vendor/wayland-client-0.23.6/src/sinks.rs b/third_party/cargo/vendor/wayland-client-0.23.6/src/sinks.rs new file mode 100644 index 0000000..d4f7614 --- /dev/null +++ b/third_party/cargo/vendor/wayland-client-0.23.6/src/sinks.rs @@ -0,0 +1,165 @@ +//! Message sinks +//! +//! The Wayland model naturally uses callbacks to handle the message you receive from the server. +//! However in some contexts, an iterator-based interface may be more practical to use, this is +//! what this module provides. +//! +//! The `message_iterator` function allows you to create a new message iterator. It is just a +//! regular MPSC, however its sending end (the `Sink`) can be directly used as an implementation +//! for Wayland objects. This just requires that `T: From<(I::Event, I)>` (where `I` is the +//! interface of the object you're trying to implement). The `event_enum!` macro is provided to +//! easily generate an appropriate type joining events from different interfaces into a single +//! iterator. +//! +//! The `blocking_message_iterator` function is very similar, except the created message iterator +//! will be linked to an event queue, and will block on it rather than returning `None`, and is +//! thus able to drive an event loop. + +use std::rc::Rc; + +use wayland_commons::Interface; + +use imp::EventQueueInner; +use {HandledBy, QueueToken}; + +pub use wayland_commons::sinks::{message_iterator, MsgIter, Sink}; + +impl HandledBy> for I +where + I: Interface, + M: From<(I::Event, I)>, +{ + fn handle(sink: &mut Sink, event: I::Event, proxy: I) { + sink.push((event, proxy)); + } +} + +/// A message iterator linked to an event queue +/// +/// Like a `MsgIter`, but it is linked with an event queue, and +/// will `dispatch()` and block instead of returning `None` if no +/// events are pending. +pub struct BlockingMsgIter { + evt_queue: Rc, + iter: MsgIter, +} + +impl Iterator for BlockingMsgIter { + type Item = T; + + fn next(&mut self) -> Option { + loop { + match self.iter.next() { + Some(msg) => return Some(msg), + None => { + self.evt_queue + .dispatch() + .expect("Connection to the wayland server lost."); + } + } + } + } +} + +/// Create a blokcing message iterator +/// +/// Contrarily to `message_iterator`, this one will block on the event queue +/// represented by the provided token rather than returning `None` if no event is available. +pub fn blocking_message_iterator(token: QueueToken) -> (Sink, BlockingMsgIter) { + let (sink, iter) = message_iterator(); + ( + sink, + BlockingMsgIter { + iter, + evt_queue: token.inner, + }, + ) +} + +/// Generate an enum joining several objects events +/// +/// This macro allows you to easily create a enum type for use with your message iterators. It is +/// used like so: +/// +/// ```ignore +/// event_enum!( +/// MyEnum | +/// Pointer => WlPointer, +/// Keyboard => WlKeyboard, +/// Surface => WlSurface +/// ); +/// ``` +/// +/// This will generate the following enum, unifying the events from each of the provided interface: +/// +/// ```ignore +/// pub enum MyEnum { +/// Pointer { event: WlPointer::Event, object: WlPointer }, +/// Keyboard { event: WlKeyboard::Event, object: WlKeyboard }, +/// Surface { event: WlSurface::Event, object: WlSurface } +/// } +/// ``` +/// +/// It will also generate the appropriate `From<_>` implementation so that a `Sink` can be +/// used as an implementation for `WlPointer`, `WlKeyboard` and `WlSurface`. +/// +/// If you want to add custom messages to the enum, the macro also supports it: +/// +/// ```ignore +/// event_enum!( +/// MyEnum | +/// Pointer => WlPointer, +/// Keyboard => WlKeyboard, +/// Surface => WlSurface | +/// MyMessage => SomeType, +/// OtherMessage => OtherType +/// ); +/// ``` +/// +/// will generate the following enum: +/// +/// ```ignore +/// pub enum MyEnum { +/// Pointer { event: WlPointer::Event, object: WlPointer }, +/// Keyboard { event: WlKeyboard::Event, object: WlKeyboard }, +/// Surface { event: WlSurface::Event, object: WlSurface }, +/// MyMessage(SomeType), +/// OtherMessage(OtherType) +/// } +/// ``` +/// +/// as well as implementations of `From` and `From`, so that these types can +/// directly be provided into a `Sink`. + +#[macro_export] +macro_rules! event_enum( + ($enu:ident | $($evt_name:ident => $iface:ty),*) => { + event_enum!($enu | $($evt_name => $iface),* | ); + }; + ($enu:ident | $($evt_name:ident => $iface:ty),* | $($name:ident => $value:ty),*) => { + pub enum $enu { + $( + $evt_name { event: <$iface as $crate::Interface>::Event, object: $iface }, + )* + $( + $name($value) + )* + } + + $( + impl From<(<$iface as $crate::Interface>::Event, $iface)> for $enu { + fn from((event, object): (<$iface as $crate::Interface>::Event, $iface)) -> $enu { + $enu::$evt_name { event, object } + } + } + )* + + $( + impl From<$value> for $enu { + fn from(value: $value) -> $enu { + $enu::$name(value) + } + } + )* + }; +); diff --git a/third_party/cargo/vendor/wayland-client-0.21.13/wayland.xml b/third_party/cargo/vendor/wayland-client-0.23.6/wayland.xml similarity index 93% rename from third_party/cargo/vendor/wayland-client-0.21.13/wayland.xml rename to third_party/cargo/vendor/wayland-client-0.23.6/wayland.xml index 3f2d967..141038b 100644 --- a/third_party/cargo/vendor/wayland-client-0.21.13/wayland.xml +++ b/third_party/cargo/vendor/wayland-client-0.23.6/wayland.xml @@ -57,6 +57,12 @@ This request creates a registry object that allows the client to list and bind the global objects available from the compositor. + + It should be noted that the server side resources consumed in + response to a get_registry request can only be released when the + client disconnects, not when the client side proxy is destroyed. + Therefore, clients should invoke get_registry as infrequently as + possible to avoid wasting memory. @@ -104,8 +110,8 @@ - The global registry object. The server has a number of global - objects that are available to all clients. These objects + The singleton global registry object. The server has a number of + global objects that are available to all clients. These objects typically represent an actual object in the server (for example, an input device) or they are singleton objects that provide extension functionality. @@ -129,7 +135,7 @@ Binds a new, client-created object to the server using the - specified name as the identifier. + specified name as the identifier. @@ -139,9 +145,9 @@ Notify the client of global objects. - The event notifies the client that a global object with - the given name is now available, and it implements the - given version of the given interface. + The event notifies the client that a global object with + the given name is now available, and it implements the + given version of the given interface. @@ -152,10 +158,10 @@ Notify the client of removed global objects. - This event notifies the client that the global identified - by name is no longer available. If the client bound to - the global using the bind request, the client should now - destroy that object. + This event notifies the client that the global identified + by name is no longer available. If the client bound to + the global using the bind request, the client should now + destroy that object. The object remains valid and requests to the object will be ignored until the client destroys it, to avoid races between @@ -226,7 +232,6 @@ so it is valid to destroy the pool immediately after creating a buffer from it. - @@ -252,14 +257,13 @@ created, but using the new size. This request can only be used to make the pool bigger. - - A global singleton object that provides support for shared + A singleton global object that provides support for shared memory. Clients can create wl_shm_pool objects using the create_pool @@ -287,7 +291,7 @@ formats are optional and may not be supported by the particular renderer in use. - The drm format codes match the #defines in drm_fourcc.h. + The drm format codes match the macros defined in drm_fourcc.h. The formats actually supported by the compositor will be reported by the format event. @@ -357,9 +361,8 @@ The pool can be used to create shared memory based buffer objects. The server will mmap size bytes of the passed file - descriptor, to use as backing memory for the pool. + descriptor, to use as backing memory for the pool. - @@ -449,7 +452,6 @@ wl_data_source.cancelled. Clients may still use this event in conjunction with wl_data_source.action for feedback. - @@ -487,7 +489,6 @@ Sent immediately after creating the wl_data_offer object. One event per offered mime type. - @@ -635,7 +636,6 @@ Used for feedback during drag-and-drop. - @@ -645,7 +645,6 @@ specified mime type over the passed file descriptor, then close it. - @@ -823,7 +822,6 @@ object will send out data_offer.offer events to describe the mime types it offers. - @@ -834,7 +832,6 @@ enter time is provided by the x and y arguments, in surface-local coordinates. - @@ -924,14 +921,14 @@ - Create a new data source. + Create a new data source. - Create a new data device for a given seat. + Create a new data device for a given seat. @@ -979,6 +976,9 @@ It allows clients to associate a wl_shell_surface with a basic surface. + + Note! This protocol is deprecated and not intended for production use. + For desktop-style user interfaces, use xdg_shell. @@ -1090,7 +1090,6 @@ The flags argument controls details of the transient behaviour. - @@ -1173,7 +1172,6 @@ corner of the surface relative to the upper left corner of the parent surface, in surface-local coordinates. - @@ -1260,7 +1258,6 @@ The width and height arguments specify the size of the window in surface-local coordinates. - @@ -1320,7 +1317,7 @@ - These errors can be emitted in response to wl_surface requests. + These errors can be emitted in response to wl_surface requests. @@ -1374,7 +1371,6 @@ If wl_surface.attach is sent with a NULL wl_buffer, the following wl_surface.commit will remove the surface content. - @@ -1405,7 +1401,6 @@ which uses buffer coordinates instead of surface coordinates, and is probably the preferred and intuitive way of doing this. - @@ -1447,7 +1442,6 @@ The callback_data passed in the callback is the current time, in milliseconds, with an undefined base. - @@ -1478,7 +1472,6 @@ destroyed immediately. A NULL wl_region causes the pending opaque region to be set to empty. - @@ -1508,7 +1501,6 @@ immediately. A NULL wl_region causes the input region to be set to infinite. - @@ -1661,7 +1653,6 @@ two requests separately and only transform from one to the other after receiving the wl_surface.commit. - @@ -1669,7 +1660,7 @@ - + A seat is a group of keyboards, pointer and touch devices. This object is published as a global during start up, or when such a @@ -1679,8 +1670,8 @@ - This is a bitmask of capabilities this seat has; if a member is - set, then it is present on the seat. + This is a bitmask of capabilities this seat has; if a member is + set, then it is present on the seat. @@ -1778,7 +1769,7 @@ - + The wl_pointer interface represents one or more input devices, such as mice, which control the pointer location and pointer_focus @@ -1828,7 +1819,6 @@ cursor ends, the current and pending input regions become undefined, and the wl_surface is unmapped. - @@ -1845,7 +1835,6 @@ is undefined and a client should respond to this event by setting an appropriate pointer image with the set_cursor request. - @@ -1870,7 +1859,6 @@ surface_x and surface_y are the location relative to the focused surface. - @@ -1878,7 +1866,7 @@ - Describes the physical state of a button that produced the button + Describes the physical state of a button that produced the button event. @@ -1891,10 +1879,17 @@ The location of the click is given by the last motion or enter event. - The time argument is a timestamp with millisecond - granularity, with an undefined base. - + The time argument is a timestamp with millisecond + granularity, with an undefined base. + The button is a button code as defined in the Linux kernel's + linux/input-event-codes.h header file, e.g. BTN_LEFT. + + Any 16-bit button code value is reserved for future additions to the + kernel's event code list. All other button codes above 0xFFFF are + currently undefined but may be used in future versions of this + protocol. + @@ -1928,7 +1923,6 @@ When applicable, a client can transform its content relative to the scroll distance. - @@ -2001,10 +1995,15 @@ finger. One example for this source is button-based scrolling where the vertical motion of a device is converted to scroll events while a button is held down. + + The "wheel tilt" axis source indicates that the actual device is a + wheel but the scroll event is not caused by a rotation but a + (usually sideways) tilt of the wheel. - + + @@ -2019,7 +2018,8 @@ wl_pointer.axis_source.finger, a wl_pointer.axis_stop event will be sent when the user lifts the finger off the device. - If the source is wl_pointer axis_source.wheel or + If the source is wl_pointer.axis_source.wheel, + wl_pointer.axis_source.wheel_tilt or wl_pointer.axis_source.continuous, a wl_pointer.axis_stop event may or may not be sent. Whether a compositor sends an axis_stop event for these sources is hardware-specific and implementation-dependent; @@ -2092,7 +2092,7 @@ - + The wl_keyboard interface represents one or more keyboards associated with a seat. @@ -2106,7 +2106,7 @@ + summary="libxkbcommon compatible; to determine the xkb keycode, clients must add 8 to the key event keycode"/> @@ -2152,10 +2152,9 @@ A key was pressed or released. - The time argument is a timestamp with millisecond - granularity, with an undefined base. + The time argument is a timestamp with millisecond + granularity, with an undefined base. - @@ -2167,7 +2166,6 @@ Notifies clients that the modifier and/or group state has changed, and it should update its local state. - @@ -2185,28 +2183,27 @@ - Informs the client about the keyboard's repeat rate and delay. + Informs the client about the keyboard's repeat rate and delay. - This event is sent as soon as the wl_keyboard object has been created, - and is guaranteed to be received by the client before any key press - event. + This event is sent as soon as the wl_keyboard object has been created, + and is guaranteed to be received by the client before any key press + event. - Negative values for either rate or delay are illegal. A rate of zero - will disable any repeating (regardless of the value of delay). + Negative values for either rate or delay are illegal. A rate of zero + will disable any repeating (regardless of the value of delay). - This event can be sent later on as well with a new value if necessary, - so clients should continue listening for the event past the creation - of wl_keyboard. + This event can be sent later on as well with a new value if necessary, + so clients should continue listening for the event past the creation + of wl_keyboard. - + summary="the rate of repeating keys in characters per second"/> + summary="delay in milliseconds since key down until repeating starts"/> - + The wl_touch interface represents a touchscreen associated with a seat. @@ -2256,7 +2253,14 @@ - Indicates the end of a contact point list. + Indicates the end of a set of events that logically belong together. + A client is expected to accumulate the data in all events within the + frame before proceeding. + + A wl_touch.frame terminates at least one event but otherwise no + guarantee is provided about the set of events within a frame. A client + must assume that any state not updated in a frame is unchanged from the + previously known state. @@ -2276,6 +2280,71 @@ + + + + + + Sent when a touchpoint has changed its shape. + + This event does not occur on its own. It is sent before a + wl_touch.frame event and carries the new shape information for + any previously reported, or new touch points of that frame. + + Other events describing the touch point such as wl_touch.down, + wl_touch.motion or wl_touch.orientation may be sent within the + same wl_touch.frame. A client should treat these events as a single + logical touch point update. The order of wl_touch.shape, + wl_touch.orientation and wl_touch.motion is not guaranteed. + A wl_touch.down event is guaranteed to occur before the first + wl_touch.shape event for this touch ID but both events may occur within + the same wl_touch.frame. + + A touchpoint shape is approximated by an ellipse through the major and + minor axis length. The major axis length describes the longer diameter + of the ellipse, while the minor axis length describes the shorter + diameter. Major and minor are orthogonal and both are specified in + surface-local coordinates. The center of the ellipse is always at the + touchpoint location as reported by wl_touch.down or wl_touch.move. + + This event is only sent by the compositor if the touch device supports + shape reports. The client has to make reasonable assumptions about the + shape if it did not receive this event. + + + + + + + + + Sent when a touchpoint has changed its orientation. + + This event does not occur on its own. It is sent before a + wl_touch.frame event and carries the new shape information for + any previously reported, or new touch points of that frame. + + Other events describing the touch point such as wl_touch.down, + wl_touch.motion or wl_touch.shape may be sent within the + same wl_touch.frame. A client should treat these events as a single + logical touch point update. The order of wl_touch.shape, + wl_touch.orientation and wl_touch.motion is not guaranteed. + A wl_touch.down event is guaranteed to occur before the first + wl_touch.orientation event for this touch ID but both events may occur + within the same wl_touch.frame. + + The orientation describes the clockwise angle of a touchpoint's major + axis to the positive surface y-axis and is normalized to the -180 to + +180 degree range. The granularity of orientation depends on the touch + device, some devices only support binary rotation values between 0 and + 90 degrees. + + This event is only sent by the compositor if the touch device supports + orientation reports. + + + + @@ -2315,7 +2384,6 @@ compositor will still be able to scan out directly from client surfaces. - @@ -2331,6 +2399,9 @@ The geometry event describes geometric properties of the output. The event is sent when binding to the output object and whenever any of the properties change. + + The physical size can be set to zero if it doesn't make sense for this + output (e.g. for projectors or virtual outputs). @@ -2372,10 +2443,10 @@ mode that was received with the current flag set. The size of a mode is given in physical hardware units of - the output device. This is not necessarily the same as - the output size in the global compositor space. For instance, - the output may be scaled, as described in wl_output.scale, - or transformed, as described in wl_output.transform. + the output device. This is not necessarily the same as + the output size in the global compositor space. For instance, + the output may be scaled, as described in wl_output.scale, + or transformed, as described in wl_output.transform. @@ -2387,20 +2458,20 @@ - This event is sent after all other properties have been - sent after binding to the output object and after any - other property changes done after that. This allows - changes to the output properties to be seen as - atomic, even if they happen via multiple events. + This event is sent after all other properties have been + sent after binding to the output object and after any + other property changes done after that. This allows + changes to the output properties to be seen as + atomic, even if they happen via multiple events. This event contains scaling geometry information - that is not in the geometry event. It may be sent after - binding the output object or if the output scale changes - later. If it is not sent, the client should assume a + that is not in the geometry event. It may be sent after + binding the output object or if the output scale changes + later. If it is not sent, the client should assume a scale of 1. A scale larger than 1 means that the compositor will @@ -2447,7 +2518,6 @@ Add the specified rectangle to the region. - @@ -2458,7 +2528,6 @@ Subtract the specified rectangle from the region. - @@ -2499,7 +2568,7 @@ + summary="the to-be sub-surface is invalid"/> @@ -2511,14 +2580,21 @@ The to-be sub-surface must not already have another role, and it must not have an existing wl_subsurface object. Otherwise a protocol error is raised. - + Adding sub-surfaces to a parent is a double-buffered operation on the + parent (see wl_surface.commit). The effect of adding a sub-surface + becomes visible on the next time the state of the parent surface is + applied. + + This request modifies the behaviour of wl_surface.commit request on + the sub-surface, see the documentation on wl_subsurface interface. + + summary="the new sub-surface object ID"/> + summary="the surface to be turned into a sub-surface"/> + summary="the parent surface"/> @@ -2581,13 +2657,13 @@ that was turned into a sub-surface with a wl_subcompositor.get_subsurface request. The wl_surface's association to the parent is deleted, and the wl_surface loses its role as - a sub-surface. The wl_surface is unmapped. + a sub-surface. The wl_surface is unmapped immediately. + summary="wl_surface is not a sibling or the parent"/> @@ -2609,7 +2685,6 @@ The initial position is 0, 0. - @@ -2632,9 +2707,8 @@ A new sub-surface is initially added as the top-most in the stack of its siblings and parent. - + summary="the reference surface"/> @@ -2642,9 +2716,8 @@ The sub-surface is placed just below the reference surface. See wl_subsurface.place_above. - + summary="the reference surface"/> diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/.cargo-checksum.json b/third_party/cargo/vendor/wayland-commons-0.21.13/.cargo-checksum.json deleted file mode 100644 index 78c8bbc..0000000 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"ab1744e0e86130ee3328269776f4f785429d1c29d80df12e12c1c93168f7231a","examples/manual_global_list.rs":"fac2187f3b1aa082bb3c8f2668054dcfffa4816e2e968d1718008926e0976cf7","src/lib.rs":"3be65d189d91786984e5843ab6e1e12ca974315c195026089c87426413cadc50","src/map.rs":"7c635519a8a9802ad8253d6283e3f64050df44794688f42f66040c888095e36c","src/socket.rs":"211262fad5942b73cf448d694351a455e4d39cfd365304edbfdec663fe161cc7","src/utils.rs":"c281feb8ed87037733e59c5bd681f2222d5c0a85e4158250e17b3dc0a12cee87","src/wire.rs":"679ff119cbb8de6ff0f37ec593abb5c4e1b42153ac60116e9c97c14efdb73867"},"package":"40c08896768b667e1df195d88a62a53a2d1351a1ed96188be79c196b35bb32ec"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-commons-0.23.6/.cargo-checksum.json b/third_party/cargo/vendor/wayland-commons-0.23.6/.cargo-checksum.json new file mode 100644 index 0000000..d554397 --- /dev/null +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"1c7ec70b5df066cc612964a769388dd7a9a5d10d8ef9a9b87dc3301193d5f797","Cargo.toml":"406f5a2de49f1f3163cb60667c98443fc1deab5d232f76ec5e321aa0ab4f1f44","examples/manual_global_list.rs":"fac2187f3b1aa082bb3c8f2668054dcfffa4816e2e968d1718008926e0976cf7","src/lib.rs":"09d8014665b70de6aa30efb6e656a4db7232a0c3a2d0b8b33376046dfdf88693","src/map.rs":"094923ddada4b8aa6818ddf58088e0a488dd036d932479eb329d5eb78963574d","src/sinks.rs":"f8685909e6d18ea2f19fcc19c0edb16234e44f1717090ba6fc6240025e2cc55c","src/socket.rs":"a31da7b38432f4ffa33020df0912a56cf16b68dc402dc9c8e255c1e15ed79ce5","src/utils.rs":"e3b41372f35c0bb18d00b8ca1edf3de571eea9b68deb12312cf22649dde6dc8d","src/wire.rs":"c2a826543150365a8fca53d4968020e2aba6b53f16c3070c2227579e32bd6d1a"},"package":"bb66b0d1a27c39bbce712b6372131c6e25149f03ffb0cd017cf8f7de8d66dbdb"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/BUILD b/third_party/cargo/vendor/wayland-commons-0.23.6/BUILD similarity index 86% rename from third_party/cargo/vendor/wayland-commons-0.21.13/BUILD rename to third_party/cargo/vendor/wayland-commons-0.23.6/BUILD index 5a47e42..aa4a86f 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/BUILD +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/BUILD @@ -33,15 +33,13 @@ rust_library( srcs = glob(["**/*.rs"]), deps = [ "//third_party/cargo/vendor/nix-0.14.1:nix", - "//third_party/cargo/vendor/wayland-sys-0.21.13:wayland_sys", + "//third_party/cargo/vendor/wayland-sys-0.23.6:wayland_sys", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.21.13", + version = "0.23.6", crate_features = [ - "native_lib", - "wayland-sys", ], ) diff --git a/third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.lock b/third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.lock new file mode 100644 index 0000000..dc87e3d --- /dev/null +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.lock @@ -0,0 +1,60 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bitflags" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cc" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.62" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "wayland-commons" +version = "0.23.6" +dependencies = [ + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3d155346769a6855b86399e9bc3814ab343cd3d62c7e985113d46a0ec3c281fd" +"checksum cc 1.0.42 (registry+https://github.com/rust-lang/crates.io-index)" = "a61c7bce55cd2fae6ec8cb935ebd76256c2959a1f95790f6118a441c2cd5b406" +"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" +"checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" +"checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4" diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/Cargo.toml b/third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.toml similarity index 87% rename from third_party/cargo/vendor/wayland-commons-0.21.13/Cargo.toml rename to third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.toml index bb2acec..1615ab3 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/Cargo.toml +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "wayland-commons" -version = "0.21.13" +version = "0.23.6" authors = ["Victor Berger "] description = "Common types and structures used by wayland-client and wayland-server." documentation = "https://smithay.github.io/wayland-rs/wayland_commons/" @@ -24,10 +24,6 @@ repository = "https://github.com/smithay/wayland-rs" version = "0.14.1" [dependencies.wayland-sys] -version = "0.21.13" -optional = true - -[features] -native_lib = ["wayland-sys"] +version = "0.23.6" [badges.travis-ci] repository = "Smithay/wayland-rs" diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/examples/manual_global_list.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/examples/manual_global_list.rs similarity index 100% rename from third_party/cargo/vendor/wayland-commons-0.21.13/examples/manual_global_list.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/examples/manual_global_list.rs diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/src/lib.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/lib.rs similarity index 85% rename from third_party/cargo/vendor/wayland-commons-0.21.13/src/lib.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/src/lib.rs index cf4c626..552c17f 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/src/lib.rs +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/lib.rs @@ -17,14 +17,12 @@ #[macro_use] extern crate nix; -#[cfg(feature = "native_lib")] extern crate wayland_sys; -#[cfg(feature = "native_lib")] use std::os::raw::c_void; -#[cfg(feature = "native_lib")] use wayland_sys::common as syscom; pub mod map; +pub mod sinks; pub mod socket; pub mod utils; pub mod wire; @@ -48,6 +46,8 @@ pub trait MessageGroup: Sized { /// /// If it is, once send or receive the associated object cannot be used any more. fn is_destructor(&self) -> bool; + /// The minimal object version for which this message exists + fn since(&self) -> u32; /// Retrieve the child `Object` associated with this message if any fn child( opcode: u16, @@ -58,11 +58,9 @@ pub trait MessageGroup: Sized { fn from_raw(msg: wire::Message, map: &mut Self::Map) -> Result; /// Turn this message into its raw representation fn into_raw(self, send_id: u32) -> wire::Message; - #[cfg(feature = "native_lib")] /// Construct a message of this group from its C representation unsafe fn from_raw_c(obj: *mut c_void, opcode: u32, args: *const syscom::wl_argument) -> Result; - #[cfg(feature = "native_lib")] /// Build a C representation of this message /// /// It can only be accessed from the provided closure, and this consumes @@ -88,32 +86,22 @@ pub trait Interface: 'static { /// Name of this interface const NAME: &'static str; /// Maximum supported version of this interface + /// + /// This is the maximum version supported by the protocol specification currently + /// used by this library, and should not be used as-is in your code, as a version + /// change can subtly change the behavior of some objects. + /// + /// Server are supposed to be able to handle all versions from 1 to the one they + /// advertise through the registry, and clients can choose any version among the + /// ones the server supports. const VERSION: u32; - #[cfg(feature = "native_lib")] /// Pointer to the C representation of this interface fn c_interface() -> *const ::syscom::wl_interface; } -/// Anonymous interface -/// -/// A special Interface implementation representing an -/// handle to an object for which the interface is not known. -pub struct AnonymousObject; - /// An empty enum representing a MessageGroup with no messages pub enum NoMessage {} -impl Interface for AnonymousObject { - type Request = NoMessage; - type Event = NoMessage; - const NAME: &'static str = ""; - const VERSION: u32 = 0; - #[cfg(feature = "native_lib")] - fn c_interface() -> *const ::syscom::wl_interface { - ::std::ptr::null() - } -} - #[cfg_attr(tarpaulin, skip)] impl MessageGroup for NoMessage { const MESSAGES: &'static [wire::MessageDesc] = &[]; @@ -124,6 +112,9 @@ impl MessageGroup for NoMessage { fn opcode(&self) -> u16 { match *self {} } + fn since(&self) -> u32 { + match *self {} + } fn child(_: u16, _: u32, _: &M) -> Option<::map::Object> { None } @@ -133,7 +124,6 @@ impl MessageGroup for NoMessage { fn into_raw(self, _: u32) -> wire::Message { match self {} } - #[cfg(feature = "native_lib")] unsafe fn from_raw_c( _obj: *mut c_void, _opcode: u32, @@ -141,7 +131,6 @@ impl MessageGroup for NoMessage { ) -> Result { Err(()) } - #[cfg(feature = "native_lib")] fn as_raw_c_in(self, _f: F) -> T where F: FnOnce(u32, &mut [syscom::wl_argument]) -> T, diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/src/map.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/map.rs similarity index 92% rename from third_party/cargo/vendor/wayland-commons-0.21.13/src/map.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/src/map.rs index 9dfc8d3..6f2124f 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/src/map.rs +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/map.rs @@ -3,7 +3,7 @@ use {Interface, MessageGroup, NoMessage}; /// Limit separating server-created from client-created objects IDs in the namespace -pub const SERVER_ID_LIMIT: u32 = 0xFF000000; +pub const SERVER_ID_LIMIT: u32 = 0xFF00_0000; /// A trait representing the metadata a wayland implementation /// may attach to an object. @@ -15,9 +15,7 @@ pub trait ObjectMetadata: Clone { } impl ObjectMetadata for () { - fn child(&self) -> () { - () - } + fn child(&self) {} } /// The representation of a protocol object @@ -46,10 +44,10 @@ impl Object { pub fn from_interface(version: u32, meta: Meta) -> Object { Object { interface: I::NAME, - version: version, + version, requests: I::Request::MESSAGES, events: I::Event::MESSAGES, - meta: meta, + meta, childs_from_events: childs_from::, childs_from_requests: childs_from::, } @@ -80,7 +78,7 @@ impl Object { version: 0, requests: &[], events: &[], - meta: meta, + meta, childs_from_events: childs_from::, childs_from_requests: childs_from::, } @@ -99,6 +97,7 @@ fn childs_from( /// /// Keeps track of which object id is associated to which /// interface object, and which is currently unused. +#[derive(Default)] pub struct ObjectMap { client_objects: Vec>>, server_objects: Vec>>, @@ -118,9 +117,9 @@ impl ObjectMap { if id >= SERVER_ID_LIMIT { self.server_objects .get((id - SERVER_ID_LIMIT) as usize) - .and_then(|x| x.clone()) + .and_then(Clone::clone) } else { - self.client_objects.get((id - 1) as usize).and_then(|x| x.clone()) + self.client_objects.get((id - 1) as usize).and_then(Clone::clone) } } @@ -132,10 +131,8 @@ impl ObjectMap { if let Some(place) = self.server_objects.get_mut((id - SERVER_ID_LIMIT) as usize) { *place = None; } - } else { - if let Some(place) = self.client_objects.get_mut((id - 1) as usize) { - *place = None; - } + } else if let Some(place) = self.client_objects.get_mut((id - 1) as usize) { + *place = None; } } @@ -170,12 +167,10 @@ impl ObjectMap { } else { Err(()) } + } else if let Some(&mut Some(ref mut obj)) = self.client_objects.get_mut((id - 1) as usize) { + Ok(f(obj)) } else { - if let Some(&mut Some(ref mut obj)) = self.client_objects.get_mut((id - 1) as usize) { - Ok(f(obj)) - } else { - Err(()) - } + Err(()) } } @@ -196,7 +191,7 @@ impl ObjectMap { // insert a new object in a store at the first free place fn insert_in(store: &mut Vec>>, object: Object) -> u32 { - match store.iter().position(|o| o.is_none()) { + match store.iter().position(Option::is_none) { Some(id) => { store[id] = Some(object); id as u32 diff --git a/third_party/cargo/vendor/wayland-commons-0.23.6/src/sinks.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/sinks.rs new file mode 100644 index 0000000..fbea43b --- /dev/null +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/sinks.rs @@ -0,0 +1,67 @@ +//! Message sinks +//! +//! This is a common implementation re-used by wayland-client and wayland-server. See +//! their respective documentation for their use. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::{Rc, Weak}; + +/// The sink end of an message iterator. +/// +/// This sink can be cloned and provided as implementation for wayland objects +/// as long as `T: From` or `T: From` (depending on whether +/// you are client-side or server-side). +pub struct Sink { + queue: Weak>>, +} + +impl Sink { + /// Push a new message to the associated message iterator + /// + /// If the iterator was dropped (and is thus no longer capable of + /// retrieving it), the message will be silently dropped instead. + pub fn push>(&self, msg: U) { + if let Some(queue) = self.queue.upgrade() { + queue.borrow_mut().push_back(msg.into()) + } + } +} + +impl Clone for Sink { + fn clone(&self) -> Sink { + Sink { + queue: self.queue.clone(), + } + } +} + +/// A message iterator +/// +/// It yields the various messages that have been pushed to it from its associated +/// sinks, in a MPSC fashion. +/// +/// It returning `None` via the `Iterator` trait only means that no message is +/// pending. It may start yielding new messages afterwards. It never blocks. +pub struct MsgIter { + queue: Rc>>, +} + +impl Iterator for MsgIter { + type Item = T; + + fn next(&mut self) -> Option { + self.queue.borrow_mut().pop_front() + } +} + +/// Create a new message iterator and an associated sink. +pub fn message_iterator() -> (Sink, MsgIter) { + let queue = Rc::new(RefCell::new(VecDeque::new())); + ( + Sink { + queue: Rc::downgrade(&queue), + }, + MsgIter { queue }, + ) +} diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/src/socket.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/socket.rs similarity index 98% rename from third_party/cargo/vendor/wayland-commons-0.21.13/src/socket.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/src/socket.rs index 450cd36..ecf42ed 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/src/socket.rs +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/socket.rs @@ -32,7 +32,7 @@ impl Socket { /// end may lose some data. pub fn send_msg(&self, bytes: &[u8], fds: &[RawFd]) -> NixResult<()> { let iov = [uio::IoVec::from_slice(bytes)]; - if fds.len() > 0 { + if !fds.is_empty() { let cmsgs = [socket::ControlMessage::ScmRights(fds)]; socket::sendmsg(self.fd, &iov, &cmsgs, socket::MsgFlags::MSG_DONTWAIT, None)?; } else { @@ -115,7 +115,7 @@ impl BufferedSocket { /// Wrap a Socket into a Buffered Socket pub fn new(socket: Socket) -> BufferedSocket { BufferedSocket { - socket: socket, + socket, in_data: Buffer::new(2 * MAX_BYTES_OUT / 4), // Incoming buffers are twice as big in order to be in_fds: Buffer::new(2 * MAX_FDS_OUT), // able to store leftover data if needed out_data: Buffer::new(MAX_BYTES_OUT / 4), @@ -142,6 +142,10 @@ impl BufferedSocket { let bytes = unsafe { ::std::slice::from_raw_parts(words.as_ptr() as *const u8, words.len() * 4) }; let fds = self.out_fds.get_contents(); self.socket.send_msg(bytes, fds)?; + for &fd in fds { + // once the fds are sent, we can close them + let _ = ::nix::unistd::close(fd); + } } self.out_data.clear(); self.out_fds.clear(); @@ -245,7 +249,7 @@ impl BufferedSocket { return Err(MessageParseError::MissingData); } let object_id = data[0]; - let opcode = (data[1] & 0x0000FFFF) as u16; + let opcode = (data[1] & 0x0000_FFFF) as u16; if let Some(sig) = signature(object_id, opcode) { match Message::from_raw(data, sig, fds) { Ok((msg, rest_data, rest_fds)) => { diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/src/utils.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/utils.rs similarity index 73% rename from third_party/cargo/vendor/wayland-commons-0.21.13/src/utils.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/src/utils.rs index a322a16..87c2946 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/src/utils.rs +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/utils.rs @@ -70,6 +70,28 @@ impl UserData { UserDataInner::Empty => None, } } + + /// Attempt to mutably access the wrapped user data + /// + /// Will return `None` if either: + /// + /// - The requested type `T` does not match the type used for construction + /// - This `UserData` has been created using the non-threadsafe variant and access + /// is attempted from an other thread than the one it was created on + pub fn get_mut(&mut self) -> Option<&mut T> { + match self.inner { + UserDataInner::ThreadSafe(ref mut val) => Any::downcast_mut::(&mut **val), + UserDataInner::NonThreadSafe(ref mut val, threadid) => { + // only give access if we are on the right thread + if threadid == thread::current().id() { + Any::downcast_mut::(&mut **val) + } else { + None + } + } + UserDataInner::Empty => None, + } + } } /// A storage able to store several values of `UserData` @@ -99,6 +121,19 @@ impl UserDataMap { None } + /// Attempt to mutably access the wrapped user data of a given type + /// + /// Will return `None` if no value of type `T` is stored in this `UserDataMap` + /// and accessible from this thread + pub fn get_mut(&mut self) -> Option<&mut T> { + for user_data in &mut self.list { + if let Some(val) = user_data.get_mut::() { + return Some(val); + } + } + None + } + /// Insert a value in the map if it is not already there /// /// This is the non-threadsafe variant, the type you insert don't have to be @@ -133,6 +168,12 @@ impl UserDataMap { } } +impl Default for UserDataMap { + fn default() -> UserDataMap { + UserDataMap::new() + } +} + mod list { /* * This is a lock-free append-only list, it is used as an implementation @@ -157,14 +198,14 @@ mod list { pub struct AppendList(AtomicPtr>); impl AppendList { - fn into_raw(ptr: NodePtr) -> *mut Node { + fn node_into_raw(ptr: NodePtr) -> *mut Node { match ptr { Some(b) => Box::into_raw(b), None => ptr::null_mut(), } } - unsafe fn from_raw(ptr: *mut Node) -> NodePtr { - if ptr == ptr::null_mut() { + unsafe fn node_from_raw(ptr: *mut Node) -> NodePtr { + if ptr.is_null() { None } else { Some(Box::from_raw(ptr)) @@ -172,7 +213,7 @@ mod list { } fn new_internal(ptr: NodePtr) -> Self { - AppendList(AtomicPtr::new(Self::into_raw(ptr))) + AppendList(AtomicPtr::new(Self::node_into_raw(ptr))) } pub fn new() -> Self { @@ -181,7 +222,7 @@ mod list { pub fn append(&self, value: T) { self.append_list(AppendList::new_internal(Some(Box::new(Node { - value: value, + value, next: AppendList::new(), })))); } @@ -211,6 +252,10 @@ mod list { pub fn iter(&self) -> AppendListIterator { AppendListIterator(&self.0) } + + pub fn iter_mut(&mut self) -> AppendListMutIterator { + AppendListMutIterator(&mut self.0) + } } impl<'a, T> IntoIterator for &'a AppendList { @@ -222,9 +267,18 @@ mod list { } } + impl<'a, T> IntoIterator for &'a mut AppendList { + type Item = &'a mut T; + type IntoIter = AppendListMutIterator<'a, T>; + + fn into_iter(self) -> AppendListMutIterator<'a, T> { + self.iter_mut() + } + } + impl Drop for AppendList { fn drop(&mut self) { - unsafe { Self::from_raw(mem::replace(self.0.get_mut(), ptr::null_mut())) }; + unsafe { Self::node_from_raw(mem::replace(self.0.get_mut(), ptr::null_mut())) }; } } @@ -246,6 +300,26 @@ mod list { } } } + + #[derive(Debug)] + pub struct AppendListMutIterator<'a, T: 'a>(&'a mut AtomicPtr>); + + impl<'a, T: 'a> Iterator for AppendListMutIterator<'a, T> { + type Item = &'a mut T; + + fn next(&mut self) -> Option<&'a mut T> { + let p = self.0.load(Ordering::Acquire); + if p.is_null() { + None + } else { + unsafe { + self.0 = &mut (*p).next.0; + Some(&mut (*p).value) + } + } + } + } + } #[cfg(test)] diff --git a/third_party/cargo/vendor/wayland-commons-0.21.13/src/wire.rs b/third_party/cargo/vendor/wayland-commons-0.23.6/src/wire.rs similarity index 97% rename from third_party/cargo/vendor/wayland-commons-0.21.13/src/wire.rs rename to third_party/cargo/vendor/wayland-commons-0.23.6/src/wire.rs index 1fd0018..39fe39c 100644 --- a/third_party/cargo/vendor/wayland-commons-0.21.13/src/wire.rs +++ b/third_party/cargo/vendor/wayland-commons-0.23.6/src/wire.rs @@ -153,7 +153,7 @@ impl Message { let orig_payload_len = payload.len(); let orig_fds_len = fds.len(); // Helper function to write a u32 or a RawFd to its buffer - fn write_buf<'a, T>(u: T, payload: &'a mut [T]) -> Result<&'a mut [T], MessageWriteError> { + fn write_buf(u: T, payload: &mut [T]) -> Result<&mut [T], MessageWriteError> { if let Some((head, tail)) = payload.split_first_mut() { *head = u; Ok(tail) @@ -225,7 +225,7 @@ impl Message { let wrote_size = (free_size - payload.len()) * 4; header[0] = self.sender_id; - header[1] = ((wrote_size as u32) << 16) | self.opcode as u32; + header[1] = ((wrote_size as u32) << 16) | u32::from(self.opcode); Ok((orig_payload_len - payload.len(), orig_fds_len - fds.len())) } @@ -262,7 +262,7 @@ impl Message { let sender_id = raw[0]; let word_2 = raw[1]; - let opcode = (word_2 & 0x0000FFFF) as u16; + let opcode = (word_2 & 0x0000_FFFF) as u16; let len = (word_2 >> 16) as usize / 4; if len < 2 || len > raw.len() { @@ -317,8 +317,8 @@ impl Message { .collect::, MessageParseError>>()?; let msg = Message { - sender_id: sender_id, - opcode: opcode, + sender_id, + opcode, args: arguments, }; Ok((msg, rest, fds)) @@ -342,12 +342,12 @@ pub fn dup_fd_cloexec(fd: RawFd) -> NixResult { match result { Ok(_) => { // setting the O_CLOEXEC worked - return Ok(newfd); + Ok(newfd) } Err(e) => { // something went wrong in F_GETFD or F_SETFD let _ = ::nix::unistd::close(newfd); - return Err(e); + Err(e) } } } diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/.cargo-checksum.json b/third_party/cargo/vendor/wayland-protocols-0.21.13/.cargo-checksum.json deleted file mode 100644 index ba4319d..0000000 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"35d0032ee41e41311ff8ee21897e51f57a380fc33262a5b6157990720877e359","build.rs":"a27ab53bc4390f9a5d6a0e8cda05c75f2ffdc7982bfd7459590af4c096a65dc9","protocols/COPYING":"f1a2b233e8a9a71c40f4aa885be08a0842ac85bb8588703c1dd7e6e6502e3124","protocols/Makefile.am":"34dc7d2f58b3198934c2970e59490aa580d185fa6919182185f0e1cbb6701681","protocols/README":"6235172d64cda3d4db3838d0097849d730e65d35c078ff8da731bdfdd22d4de1","protocols/autogen.sh":"fb26c092df7235733e756dfd869bdec34b8dd56ce7577b5028162c09c64004d8","protocols/configure.ac":"490c2460e2b559c9b700cd929c8bc30a84f4e53b82471b3fad30ae57f5225c11","protocols/m4/compat.m4":"9eba9db73f60337a674d58b9634c2706ea6d202d71c741c4008b5ff1458e6f3a","protocols/stable/presentation-time/README":"abed5978a4b5a05317382359aa1fdd4782be447894b9480a096e9110605a249c","protocols/stable/presentation-time/presentation-time.xml":"b3c6e755f8d5c9dcec771da23f99a6a2119cea3cc21acd78962a352d0d55e87e","protocols/stable/viewporter/README":"71e33de1e94da4a2e9b76f37edbf3dc8af3d4828c0165dba57751b2784f74110","protocols/stable/viewporter/viewporter.xml":"d5da5c61107c53062c7a73093bd72676a0d643fa04eb1867411126600a75fc54","protocols/stable/xdg-shell/README":"4981eb1b38b6c42ff5aa12ab3db46270650d364876fa82dbd05470529726f057","protocols/stable/xdg-shell/xdg-shell.xml":"8b7d47297ecde5f8cc557ae3bb7289a4c66ddde471c83698b697c867a2d59046","protocols/tests/scan.sh":"b219a2d2c5b7ffa52107cd31124a9909714472e31645a2278acd21decbeb14cd","protocols/unstable/fullscreen-shell/README":"fe3f21d4566d0b5aefc167649b2cb38f7b741a4e53f8c5d88b5dff05482bb098","protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml":"df718b7803ca72b3128e9b8d2eb5870810e677e3c1cd1d154194d03132dfb8e1","protocols/unstable/idle-inhibit/README":"98f814aa1ca5ba42ba9c9aed64e56381c9b8d7dd5dc5610d552830f8fa7787c6","protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml":"c2ac9f002c6669ca6c02eb9b587b8e9108e3ce6deab4a2de58b576f4f864ca38","protocols/unstable/input-method/README":"ea783a7a4180f5ee0efd5ed62e33a972fd1127636db44e0dd863e2dc46a7c27e","protocols/unstable/input-method/input-method-unstable-v1.xml":"e04464e22eee9ac67e21c3316c8bb47293656902c2f26b91ebdd8b40eeba03a0","protocols/unstable/input-timestamps/README":"ef92f7fba49eb9a31db2ea9f8c0577ce1f6f4ef57e499041a38d21501115e0e5","protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml":"92d9911f070407d470458f59ffdee5406ce3b6368270a93e6ecd9f4f71368bb0","protocols/unstable/keyboard-shortcuts-inhibit/README":"a2cd9366dca159c60a42c797c0305f81d4ff12f0064cb14ae1b78988ae1c17af","protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml":"9117d9e8ec02e9a3c3c55803b41e1227e76986f555f7c12eeb29f796fa63e69b","protocols/unstable/linux-dmabuf/README":"5ada0cec13f52f52430a98154c27cb405ccba4da291a1ab846251a0bf8a5dff0","protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml":"8eca77ac6c622df8c50c97b911d6f15b452d9ddf1a6b52c48131c702be80b655","protocols/unstable/linux-explicit-synchronization/README":"db6d7d851ae553ab96e601a20d9d33803a3974acfc6cf8434996c12c966b90a1","protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml":"9a2aaefd7155a4cb69ac391b675702ac1536581fbf1b722c4cb96d1eb61f7079","protocols/unstable/pointer-constraints/README":"29bcf3cfe32b5926a00daf02f7c8a5bb0b17a1a9d9bee5d049f0317a61f41a40","protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml":"b40a5fe19883efef0a274ef82dea47b6a8af4647af58950ab7c6da3058f3a949","protocols/unstable/pointer-gestures/README":"a0c8e7c53549c19489dd55c5f375a0a7c3bfddcceb808a43a973469f4878b2f8","protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml":"006323608b43a918cf6fcce3284975f40bac5d64a5ac79082bd277b40806907f","protocols/unstable/primary-selection/README":"3ae6bd7bab5c760106a055652626c0159a3c367f8ab64b0334048b7319b10811","protocols/unstable/primary-selection/primary-selection-unstable-v1.xml":"d568482ba84df6e531698b1f531810860995ca24d69495427fe43aee6017f52c","protocols/unstable/relative-pointer/README":"a5351dbb5ed63f2ee041024fb62795c7b6649cc98f4ce50239c1f1bfac36ffe2","protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml":"ab4930dd3084f732b6fdd12ee6dbd0a112a758ed8a57b170366391dbeb1a22ff","protocols/unstable/tablet/README":"f3806bd15b53446cea26c58f366b0382fd737362b257e4e60d26a574e128d0cd","protocols/unstable/tablet/tablet-unstable-v1.xml":"2816521e2716a98faa6f4f026527ec0912f8876136d58527ec3356553471fc6d","protocols/unstable/tablet/tablet-unstable-v2.xml":"c74d1aa4e44c9e2873f924707bcaf0becaaa77bf5de081cb7a4d8b06bebc2219","protocols/unstable/text-input/README":"d40c094a1f8bcbc0b0225d36acf1c5e5201d3cde87fea089991e9161f56ce846","protocols/unstable/text-input/text-input-unstable-v1.xml":"e65ec8126415e9ce992f806bbd2df0cd5efc6b07ce32aa96b2024abaa1240be5","protocols/unstable/text-input/text-input-unstable-v3.xml":"89ba8a5c5beb1a234f575cf6af477e47c70f28fdd5c21b9b2ab924762f0bc4e8","protocols/unstable/xdg-decoration/README":"8c53e37e9c192c01aba19a28def43ec9c60703acb64c85874e641c0f715e82ff","protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml":"4c52b8e737ade1a08da98d6d88329b8f76f2d3933732a5c13a454b5ea0e9ec03","protocols/unstable/xdg-foreign/README":"2d8c20c991a6e54748c84ffa8f81b153758fe58de39174c660f9422eba2ad1e7","protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml":"7727851ec43bf5897826248932d2e30a5a5b9257b6fab4afbb257d73adda088c","protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml":"bed5b5cf1483e216ab896c4fe86d296ea37a9283b31abf5e5b6fc82605f2e24f","protocols/unstable/xdg-output/README":"0220f9818bef87130c98acc8a571e78fe0c2ac26eff3a2f40c4cd48f542a2a0b","protocols/unstable/xdg-output/xdg-output-unstable-v1.xml":"bed7321b8325ba4c9c79936e1b89b713d7b822d54e3aeec5e7f20f03819534c8","protocols/unstable/xdg-shell/README":"a8a1af606073829cd2aef5a54f98455726999e71f8162dc55ec6ab647212a3b4","protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml":"864ab0ac02e89c6e6079a97876123cf6003b5a219d8dc0d5a0496d4bce7b5ffc","protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml":"15b9922317144e81aec6872ee0ed78d563efdba13ba88592bda71696120a41d2","protocols/unstable/xwayland-keyboard-grab/README":"5d888ca7848d68817843bfd0832da842ec70acc6466c776e80f6c128c225100e","protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml":"fcc1e24ec465c209de576f75bf87438b8339e4da42051a3f26b48916292c7c6f","protocols/wayland-protocols-uninstalled.pc.in":"9b1a4fa6257e150bd7e9ba93ee351f7b27612bd2b25b054478191e12b1a71fb2","protocols/wayland-protocols.pc.in":"07d52e8f3b5572437128b2524f593203afec230c6ff38d7ca51cffc4ef2221cb","src/lib.rs":"5d8dd68193c0036cea60c578af0a3fe563fe6df0975568fdf11626c673be3dca","src/protocol_macro.rs":"1b301f7b9a1dab5cce28c3a5993d50cd4a4cc966c86bd166e247256e37697e71","src/stable.rs":"d13c56aee42c9fac0944232ede57e9a3b0c8ecaba0e5ca15f0e5cb9f318a88b9","src/unstable.rs":"02dab0d16b86cb8f95090c3bdef295862a0bea340fbc8dd0bf345772c14100ba","src/wlr.rs":"f175fbff097213a28b0170f2d8cf761d0c988ff7d810db01a1462554d1857448","wlr-protocols/Makefile":"a1f4d578ab5566a812d393f945ad0675e7710cfe4ca6f74621868a194234d428","wlr-protocols/check.sh":"6d1f75568915d08bc7f6df0c3c0a234b0eee7b045a7fb8f21a0d2e46f691194f","wlr-protocols/unstable/wlr-data-control-unstable-v1.xml":"ed3489d0d41b58aba13dccf0de913f19d30ef850c56331d9abd0684fe89c0aff","wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml":"0653d993fb10163c45124bc3748717a59b49c6460fec9100282e17a38c6fc2f9","wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml":"0d724a81ad4ab059ce4fd500f6dcfb836ad1c72b174d116a82f1d0245b1fd160","wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml":"779ac19d63855f2211d9af735e0b2b9376b8ef070155ea9b8df64d2d9464d370","wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml":"6f56c6650302feb9456f54a9705cc9b3a93b265f593a95f40bad329dcb9cbf58","wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml":"f4228ad1a603c3eb6b22b5f1c8eb71e30c8fe8c3fadfad75fd7d5091fbadf672","wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml":"a273cbbbbc4860738eaf6aa7d9845fea5df9cd85204bfa8014937c716441cdba","wlr-protocols/wlr-protocols.pc.in":"1853341442197bf0310d76bf4172a9b491ecbd6358478cc3ee51ba01948d93c6"},"package":"4afde2ea2a428eee6d7d2c8584fdbe8b82eee8b6c353e129a434cd6e07f42145"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/build.rs b/third_party/cargo/vendor/wayland-protocols-0.21.13/build.rs deleted file mode 100644 index cd68b4e..0000000 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/build.rs +++ /dev/null @@ -1,126 +0,0 @@ -extern crate wayland_scanner; - -use std::env::var; -use std::path::Path; -use wayland_scanner::*; - -static STABLE_PROTOCOLS: &'static [&'static str] = &["presentation-time", "viewporter", "xdg-shell"]; - -static UNSTABLE_PROTOCOLS: &'static [(&'static str, &'static [&'static str])] = &[ - ("fullscreen-shell", &["v1"]), - ("idle-inhibit", &["v1"]), - ("input-method", &["v1"]), - ("input-timestamps", &["v1"]), - ("keyboard-shortcuts-inhibit", &["v1"]), - ("linux-dmabuf", &["v1"]), - ("linux-explicit-synchronization", &["v1"]), - ("pointer-constraints", &["v1"]), - ("pointer-gestures", &["v1"]), - ("primary-selection", &["v1"]), - ("relative-pointer", &["v1"]), - ("tablet", &["v1", "v2"]), - ("text-input", &["v1", "v3"]), - ("xdg-decoration", &["v1"]), - ("xdg-foreign", &["v1", "v2"]), - ("xdg-output", &["v1"]), - ("xdg-shell", &["v5", "v6"]), - ("xwayland-keyboard-grab", &["v1"]), -]; - -static WLR_UNSTABLE_PROTOCOLS: &'static [(&'static str, &'static [&'static str])] = &[ - ("wlr-data-control", &["v1"]), - ("wlr-export-dmabuf", &["v1"]), - ("wlr-foreign-toplevel-management", &["v1"]), - ("wlr-gamma-control", &["v1"]), - ("wlr-input-inhibitor", &["v1"]), - ("wlr-layer-shell", &["v1"]), - ("wlr-screencopy", &["v1"]), -]; - -fn generate_protocol(name: &str, protocol_file: &Path, out_dir: &Path, client: bool, server: bool) { - if var("CARGO_FEATURE_NATIVE_LIB").ok().is_some() { - generate_c_interfaces(&protocol_file, out_dir.join(&format!("{}_c_interfaces.rs", name))); - - if client { - generate_c_code( - &protocol_file, - out_dir.join(&format!("{}_c_client_api.rs", name)), - Side::Client, - ); - } - - if server { - generate_c_code( - &protocol_file, - out_dir.join(&format!("{}_c_server_api.rs", name)), - Side::Server, - ); - } - } else { - if client { - generate_rust_code( - &protocol_file, - out_dir.join(&format!("{}_rust_client_api.rs", name)), - Side::Client, - ); - } - - if server { - generate_rust_code( - &protocol_file, - out_dir.join(&format!("{}_rust_server_api.rs", name)), - Side::Server, - ); - } - } -} - -fn main() { - let out_dir_str = var("OUT_DIR").unwrap(); - let out_dir = Path::new(&out_dir_str); - - let client = var("CARGO_FEATURE_CLIENT").ok().is_some(); - let server = var("CARGO_FEATURE_SERVER").ok().is_some(); - - for name in STABLE_PROTOCOLS { - let file = format!("{name}/{name}.xml", name = name); - generate_protocol( - name, - &Path::new("./protocols/stable").join(&file), - out_dir, - client, - server, - ); - } - - if var("CARGO_FEATURE_UNSTABLE_PROTOCOLS").ok().is_some() { - for &(name, versions) in UNSTABLE_PROTOCOLS { - for version in versions { - let file = format!( - "{name}/{name}-unstable-{version}.xml", - name = name, - version = version - ); - generate_protocol( - &format!("{name}-{version}", name = name, version = version), - &Path::new("./protocols/unstable").join(file), - out_dir, - client, - server, - ); - } - } - for &(name, versions) in WLR_UNSTABLE_PROTOCOLS { - for version in versions { - let file = format!("{name}-unstable-{version}.xml", name = name, version = version); - generate_protocol( - &format!("{name}-{version}", name = name, version = version), - &Path::new("./wlr-protocols/unstable").join(file), - out_dir, - client, - server, - ); - } - } - } -} diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/protocol_macro.rs b/third_party/cargo/vendor/wayland-protocols-0.21.13/src/protocol_macro.rs deleted file mode 100644 index 0290987..0000000 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/protocol_macro.rs +++ /dev/null @@ -1,112 +0,0 @@ -#[macro_escape] -macro_rules! wayland_protocol( - ($name: expr, [$(($import: ident, $interface: ident)),*], [$(($prot_name:ident, $prot_import: ident, $prot_iface: ident)),*]) => { - #[cfg(feature = "client")] - pub use self::generated::client; - - #[cfg(feature = "server")] - pub use self::generated::server; - - #[cfg(all(feature = "native_lib", any(feature = "client", feature = "server")))] - pub use self::generated::c_interfaces; - - #[cfg(all(not(feature = "native_lib"), any(feature = "client", feature = "server")))] - mod generated { - #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)] - #![allow(non_upper_case_globals,non_snake_case,unused_imports)] - #![allow(missing_docs)] - - #[cfg(feature = "client")] - pub mod client { - //! Client-side API of this protocol - pub(crate) use wayland_client::{NewProxy, Proxy, ProxyMap}; - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; - pub(crate) use wayland_client::protocol::{$($import),*}; - $( - pub(crate) use ::$prot_name::client::$prot_import; - )* - include!(concat!(env!("OUT_DIR"), "/", $name, "_rust_client_api.rs")); - } - - #[cfg(feature = "server")] - pub mod server { - //! Server-side API of this protocol - pub(crate) use wayland_server::{NewResource, Resource, ResourceMap}; - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; - pub(crate) use wayland_server::protocol::{$($import),*}; - $( - pub(crate) use ::$prot_name::server::$prot_import; - )* - include!(concat!(env!("OUT_DIR"), "/", $name, "_rust_server_api.rs")); - } - } - - #[cfg(all(feature = "native_lib", any(feature = "client", feature = "server")))] - mod generated { - #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)] - #![allow(non_upper_case_globals,non_snake_case,unused_imports)] - #![allow(missing_docs)] - - pub mod c_interfaces { - //! C interfaces for this protocol - - // import client or server, both are the same anyway - #[cfg(feature = "client")] - pub use wayland_client::sys::protocol_interfaces::{$($interface),*}; - #[cfg(all(not(feature = "client"), feature = "server"))] - pub use wayland_server::sys::protocol_interfaces::{$($interface),*}; - $( - pub(crate) use ::$prot_name::c_interfaces::$prot_iface; - )* - include!(concat!(env!("OUT_DIR"), "/", $name, "_c_interfaces.rs")); - } - - #[cfg(feature = "client")] - pub mod client { - //! Client-side API of this protocol - pub(crate) use wayland_client::{NewProxy, Proxy, ProxyMap}; - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; - pub(crate) use wayland_sys as sys; - pub(crate) use wayland_client::protocol::{$($import),*}; - $( - pub(crate) use ::$prot_name::client::$prot_import; - )* - include!(concat!(env!("OUT_DIR"), "/", $name, "_c_client_api.rs")); - } - - #[cfg(feature = "server")] - pub mod server { - //! Server-side API of this protocol - pub(crate) use wayland_server::{NewResource, Resource, ResourceMap}; - pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; - pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup}; - pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; - pub(crate) use wayland_sys as sys; - pub(crate) use wayland_server::protocol::{$($import),*}; - $( - pub(crate) use ::$prot_name::server::$prot_import; - )* - include!(concat!(env!("OUT_DIR"), "/", $name, "_c_server_api.rs")); - } - } - } -); - -#[cfg(feature = "unstable_protocols")] -#[macro_escape] -macro_rules! wayland_protocol_versioned( - ($name: expr, [$($version: ident),*], $std_imports:tt, $prot_imports:tt) => { - $( - #[allow(missing_docs)] - pub mod $version { - wayland_protocol!(concat!($name, "-", stringify!($version)), $std_imports, $prot_imports); - } - )* - } -); diff --git a/third_party/cargo/vendor/wayland-protocols-0.23.6/.cargo-checksum.json b/third_party/cargo/vendor/wayland-protocols-0.23.6/.cargo-checksum.json new file mode 100644 index 0000000..a261331 --- /dev/null +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"d3508354285806207b6f73d21f96f9b0b0ad8beb2932a4e8b31b343a50530bd2","build.rs":"7a986f1fe15cfbe356804c33ff0ac947beecbb45f2d14dca1bb6303dded7608e","misc/gtk-primary-selection.xml":"e0a970c35af44a48817c7accc9270cafc80bc8a3bff9622a69ae0a815105aab1","protocols/COPYING":"f1a2b233e8a9a71c40f4aa885be08a0842ac85bb8588703c1dd7e6e6502e3124","protocols/Makefile.am":"34dc7d2f58b3198934c2970e59490aa580d185fa6919182185f0e1cbb6701681","protocols/README":"6235172d64cda3d4db3838d0097849d730e65d35c078ff8da731bdfdd22d4de1","protocols/autogen.sh":"fb26c092df7235733e756dfd869bdec34b8dd56ce7577b5028162c09c64004d8","protocols/configure.ac":"490c2460e2b559c9b700cd929c8bc30a84f4e53b82471b3fad30ae57f5225c11","protocols/m4/compat.m4":"9eba9db73f60337a674d58b9634c2706ea6d202d71c741c4008b5ff1458e6f3a","protocols/stable/presentation-time/README":"abed5978a4b5a05317382359aa1fdd4782be447894b9480a096e9110605a249c","protocols/stable/presentation-time/presentation-time.xml":"b3c6e755f8d5c9dcec771da23f99a6a2119cea3cc21acd78962a352d0d55e87e","protocols/stable/viewporter/README":"71e33de1e94da4a2e9b76f37edbf3dc8af3d4828c0165dba57751b2784f74110","protocols/stable/viewporter/viewporter.xml":"d5da5c61107c53062c7a73093bd72676a0d643fa04eb1867411126600a75fc54","protocols/stable/xdg-shell/README":"4981eb1b38b6c42ff5aa12ab3db46270650d364876fa82dbd05470529726f057","protocols/stable/xdg-shell/xdg-shell.xml":"8b7d47297ecde5f8cc557ae3bb7289a4c66ddde471c83698b697c867a2d59046","protocols/tests/scan.sh":"b219a2d2c5b7ffa52107cd31124a9909714472e31645a2278acd21decbeb14cd","protocols/unstable/fullscreen-shell/README":"fe3f21d4566d0b5aefc167649b2cb38f7b741a4e53f8c5d88b5dff05482bb098","protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml":"df718b7803ca72b3128e9b8d2eb5870810e677e3c1cd1d154194d03132dfb8e1","protocols/unstable/idle-inhibit/README":"98f814aa1ca5ba42ba9c9aed64e56381c9b8d7dd5dc5610d552830f8fa7787c6","protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml":"c2ac9f002c6669ca6c02eb9b587b8e9108e3ce6deab4a2de58b576f4f864ca38","protocols/unstable/input-method/README":"ea783a7a4180f5ee0efd5ed62e33a972fd1127636db44e0dd863e2dc46a7c27e","protocols/unstable/input-method/input-method-unstable-v1.xml":"e04464e22eee9ac67e21c3316c8bb47293656902c2f26b91ebdd8b40eeba03a0","protocols/unstable/input-timestamps/README":"ef92f7fba49eb9a31db2ea9f8c0577ce1f6f4ef57e499041a38d21501115e0e5","protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml":"92d9911f070407d470458f59ffdee5406ce3b6368270a93e6ecd9f4f71368bb0","protocols/unstable/keyboard-shortcuts-inhibit/README":"a2cd9366dca159c60a42c797c0305f81d4ff12f0064cb14ae1b78988ae1c17af","protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml":"9117d9e8ec02e9a3c3c55803b41e1227e76986f555f7c12eeb29f796fa63e69b","protocols/unstable/linux-dmabuf/README":"5ada0cec13f52f52430a98154c27cb405ccba4da291a1ab846251a0bf8a5dff0","protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml":"8eca77ac6c622df8c50c97b911d6f15b452d9ddf1a6b52c48131c702be80b655","protocols/unstable/linux-explicit-synchronization/README":"db6d7d851ae553ab96e601a20d9d33803a3974acfc6cf8434996c12c966b90a1","protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml":"9a2aaefd7155a4cb69ac391b675702ac1536581fbf1b722c4cb96d1eb61f7079","protocols/unstable/pointer-constraints/README":"29bcf3cfe32b5926a00daf02f7c8a5bb0b17a1a9d9bee5d049f0317a61f41a40","protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml":"b40a5fe19883efef0a274ef82dea47b6a8af4647af58950ab7c6da3058f3a949","protocols/unstable/pointer-gestures/README":"a0c8e7c53549c19489dd55c5f375a0a7c3bfddcceb808a43a973469f4878b2f8","protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml":"006323608b43a918cf6fcce3284975f40bac5d64a5ac79082bd277b40806907f","protocols/unstable/primary-selection/README":"3ae6bd7bab5c760106a055652626c0159a3c367f8ab64b0334048b7319b10811","protocols/unstable/primary-selection/primary-selection-unstable-v1.xml":"d568482ba84df6e531698b1f531810860995ca24d69495427fe43aee6017f52c","protocols/unstable/relative-pointer/README":"a5351dbb5ed63f2ee041024fb62795c7b6649cc98f4ce50239c1f1bfac36ffe2","protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml":"ab4930dd3084f732b6fdd12ee6dbd0a112a758ed8a57b170366391dbeb1a22ff","protocols/unstable/tablet/README":"f3806bd15b53446cea26c58f366b0382fd737362b257e4e60d26a574e128d0cd","protocols/unstable/tablet/tablet-unstable-v1.xml":"2816521e2716a98faa6f4f026527ec0912f8876136d58527ec3356553471fc6d","protocols/unstable/tablet/tablet-unstable-v2.xml":"c74d1aa4e44c9e2873f924707bcaf0becaaa77bf5de081cb7a4d8b06bebc2219","protocols/unstable/text-input/README":"d40c094a1f8bcbc0b0225d36acf1c5e5201d3cde87fea089991e9161f56ce846","protocols/unstable/text-input/text-input-unstable-v1.xml":"e65ec8126415e9ce992f806bbd2df0cd5efc6b07ce32aa96b2024abaa1240be5","protocols/unstable/text-input/text-input-unstable-v3.xml":"89ba8a5c5beb1a234f575cf6af477e47c70f28fdd5c21b9b2ab924762f0bc4e8","protocols/unstable/xdg-decoration/README":"8c53e37e9c192c01aba19a28def43ec9c60703acb64c85874e641c0f715e82ff","protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml":"4c52b8e737ade1a08da98d6d88329b8f76f2d3933732a5c13a454b5ea0e9ec03","protocols/unstable/xdg-foreign/README":"2d8c20c991a6e54748c84ffa8f81b153758fe58de39174c660f9422eba2ad1e7","protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml":"7727851ec43bf5897826248932d2e30a5a5b9257b6fab4afbb257d73adda088c","protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml":"bed5b5cf1483e216ab896c4fe86d296ea37a9283b31abf5e5b6fc82605f2e24f","protocols/unstable/xdg-output/README":"0220f9818bef87130c98acc8a571e78fe0c2ac26eff3a2f40c4cd48f542a2a0b","protocols/unstable/xdg-output/xdg-output-unstable-v1.xml":"bed7321b8325ba4c9c79936e1b89b713d7b822d54e3aeec5e7f20f03819534c8","protocols/unstable/xdg-shell/README":"a8a1af606073829cd2aef5a54f98455726999e71f8162dc55ec6ab647212a3b4","protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml":"864ab0ac02e89c6e6079a97876123cf6003b5a219d8dc0d5a0496d4bce7b5ffc","protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml":"15b9922317144e81aec6872ee0ed78d563efdba13ba88592bda71696120a41d2","protocols/unstable/xwayland-keyboard-grab/README":"5d888ca7848d68817843bfd0832da842ec70acc6466c776e80f6c128c225100e","protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml":"fcc1e24ec465c209de576f75bf87438b8339e4da42051a3f26b48916292c7c6f","protocols/wayland-protocols-uninstalled.pc.in":"9b1a4fa6257e150bd7e9ba93ee351f7b27612bd2b25b054478191e12b1a71fb2","protocols/wayland-protocols.pc.in":"07d52e8f3b5572437128b2524f593203afec230c6ff38d7ca51cffc4ef2221cb","src/lib.rs":"9556fa22a59822b4bcf38375a742923d49c3d1a19ac75682b15b10b2fd21db48","src/misc.rs":"9576645a890a200f14e6e7a7a1773a22084e6887c5e241c5ed866f6e3f76de7b","src/protocol_macro.rs":"0120cd17b1fac6ddda7fd7c1f506dea5e004c29f65692e72fed66ff956bcdec7","src/stable.rs":"87f46c01208f7e81599abc9cf5a43dce6ce2a20ae1f8cb5123094218bde67647","src/unstable.rs":"b689f8e99fafcaefb69f47eef813af905750f85b21fd42931ec037e1a8bc4b18","src/wlr.rs":"f175fbff097213a28b0170f2d8cf761d0c988ff7d810db01a1462554d1857448","wlr-protocols/Makefile":"a1f4d578ab5566a812d393f945ad0675e7710cfe4ca6f74621868a194234d428","wlr-protocols/check.sh":"6d1f75568915d08bc7f6df0c3c0a234b0eee7b045a7fb8f21a0d2e46f691194f","wlr-protocols/unstable/wlr-data-control-unstable-v1.xml":"5ac39552975b28d0ea42f636a79b7fc8e2d1fcfa31cbe173f549bd4b044ae2de","wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml":"0653d993fb10163c45124bc3748717a59b49c6460fec9100282e17a38c6fc2f9","wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml":"0d724a81ad4ab059ce4fd500f6dcfb836ad1c72b174d116a82f1d0245b1fd160","wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml":"779ac19d63855f2211d9af735e0b2b9376b8ef070155ea9b8df64d2d9464d370","wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml":"6f56c6650302feb9456f54a9705cc9b3a93b265f593a95f40bad329dcb9cbf58","wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml":"f4228ad1a603c3eb6b22b5f1c8eb71e30c8fe8c3fadfad75fd7d5091fbadf672","wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml":"a273cbbbbc4860738eaf6aa7d9845fea5df9cd85204bfa8014937c716441cdba","wlr-protocols/wlr-protocols.pc.in":"1853341442197bf0310d76bf4172a9b491ecbd6358478cc3ee51ba01948d93c6"},"package":"6cc286643656742777d55dc8e70d144fa4699e426ca8e9d4ef454f4bf15ffcf9"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/BUILD b/third_party/cargo/vendor/wayland-protocols-0.23.6/BUILD similarity index 79% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/BUILD rename to third_party/cargo/vendor/wayland-protocols-0.23.6/BUILD index d5e3ea3..6a53bfc 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/BUILD +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/BUILD @@ -28,21 +28,18 @@ rust_binary( crate_root = "build.rs", edition = "2015", deps = [ - "//third_party/cargo/vendor/wayland-scanner-0.21.13:wayland_scanner", + "//third_party/cargo/vendor/wayland-scanner-0.23.6:wayland_scanner", ], rustc_flags = [ "--cap-lints=allow", ], crate_features = [ "client", - "native_client", - "native_lib", "unstable_protocols", "wayland-client", - "wayland-sys", ], data = glob(["*"]), - version = "0.21.13", + version = "0.23.6", visibility = ["//visibility:private"], ) @@ -61,11 +58,8 @@ genrule( + " export TARGET='x86_64-unknown-linux-gnu';" + " export RUST_BACKTRACE=1;" + " export CARGO_FEATURE_CLIENT=1;" - + " export CARGO_FEATURE_NATIVE_CLIENT=1;" - + " export CARGO_FEATURE_NATIVE_LIB=1;" + " export CARGO_FEATURE_UNSTABLE_PROTOCOLS=1;" + " export CARGO_FEATURE_WAYLAND_CLIENT=1;" - + " export CARGO_FEATURE_WAYLAND_SYS=1;" + " export OUT_DIR=$$PWD/$$(dirname $@)/wayland_protocols_out_dir_outputs;" + " export BINARY_PATH=\"$$PWD/$(location :wayland_protocols_build_script)\";" + " export OUT_TAR=$$PWD/$@;" @@ -81,22 +75,18 @@ rust_library( srcs = glob(["**/*.rs"]), deps = [ "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", - "//third_party/cargo/vendor/wayland-client-0.21.13:wayland_client", - "//third_party/cargo/vendor/wayland-commons-0.21.13:wayland_commons", - "//third_party/cargo/vendor/wayland-sys-0.21.13:wayland_sys", + "//third_party/cargo/vendor/wayland-client-0.23.6:wayland_client", + "//third_party/cargo/vendor/wayland-commons-0.23.6:wayland_commons", ], rustc_flags = [ "--cap-lints=allow", ], out_dir_tar = ":wayland_protocols_build_script_executor", - version = "0.21.13", + version = "0.23.6", crate_features = [ "client", - "native_client", - "native_lib", "unstable_protocols", "wayland-client", - "wayland-sys", ], ) diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/Cargo.toml b/third_party/cargo/vendor/wayland-protocols-0.23.6/Cargo.toml similarity index 77% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/Cargo.toml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/Cargo.toml index 5d4efbd..edf71e2 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/Cargo.toml +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "wayland-protocols" -version = "0.21.13" +version = "0.23.6" authors = ["Victor Berger "] build = "build.rs" description = "Generated API for the officials wayland protocol extensions" @@ -27,27 +27,20 @@ all-features = true version = "1.0" [dependencies.wayland-client] -version = "0.21.13" +version = "0.23.6" optional = true [dependencies.wayland-commons] -version = "0.21.13" +version = "0.23.6" [dependencies.wayland-server] -version = "0.21.13" -optional = true - -[dependencies.wayland-sys] -version = "0.21.13" +version = "0.23.6" optional = true [build-dependencies.wayland-scanner] -version = "0.21.13" +version = "0.23.6" [features] client = ["wayland-client"] -native_client = ["client", "native_lib", "wayland-client/native_lib"] -native_lib = ["wayland-sys"] -native_server = ["server", "native_lib", "wayland-server/native_lib"] server = ["wayland-server"] unstable_protocols = [] [badges.travis-ci] diff --git a/third_party/cargo/vendor/wayland-protocols-0.23.6/build.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/build.rs new file mode 100644 index 0000000..c988ced --- /dev/null +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/build.rs @@ -0,0 +1,150 @@ +extern crate wayland_scanner; + +use std::env::var; +use std::path::Path; +use wayland_scanner::*; + +static STABLE_PROTOCOLS: &[(&str, &[(&str, &str)])] = &[ + ("presentation-time", &[]), + ("viewporter", &[]), + ("xdg-shell", &[]), +]; + +static UNSTABLE_PROTOCOLS: &[(&str, &[(&str, &[(&str, &str)])])] = &[ + ("fullscreen-shell", &[("v1", &[])]), + ("idle-inhibit", &[("v1", &[])]), + ("input-method", &[("v1", &[])]), + ("input-timestamps", &[("v1", &[])]), + ("keyboard-shortcuts-inhibit", &[("v1", &[])]), + ("linux-dmabuf", &[("v1", &[])]), + ( + "linux-explicit-synchronization", + &[( + "v1", + &[ + ("zwp_linux_buffer_release_v1", "fenced_release"), + ("zwp_linux_buffer_release_v1", "immediate_release"), + ], + )], + ), + ("pointer-constraints", &[("v1", &[])]), + ("pointer-gestures", &[("v1", &[])]), + ("primary-selection", &[("v1", &[])]), + ("relative-pointer", &[("v1", &[])]), + ("tablet", &[("v1", &[]), ("v2", &[])]), + ("text-input", &[("v1", &[]), ("v3", &[])]), + ("xdg-decoration", &[("v1", &[])]), + ("xdg-foreign", &[("v1", &[]), ("v2", &[])]), + ("xdg-output", &[("v1", &[])]), + ("xdg-shell", &[("v5", &[]), ("v6", &[])]), + ("xwayland-keyboard-grab", &[("v1", &[])]), +]; + +static WLR_UNSTABLE_PROTOCOLS: &[(&str, &[(&str, &[(&str, &str)])])] = &[ + ("wlr-data-control", &[("v1", &[])]), + ("wlr-export-dmabuf", &[("v1", &[])]), + ("wlr-foreign-toplevel-management", &[("v1", &[])]), + ("wlr-gamma-control", &[("v1", &[])]), + ("wlr-input-inhibitor", &[("v1", &[])]), + ("wlr-layer-shell", &[("v1", &[])]), + ("wlr-screencopy", &[("v1", &[])]), +]; + +static MISC_PROTOCOLS: &[(&str, &[(&str, &str)])] = &[("gtk-primary-selection", &[])]; + +fn generate_protocol( + name: &str, + protocol_file: &Path, + out_dir: &Path, + client: bool, + server: bool, + dest_events: &[(&str, &str)], +) { + println!("cargo:rerun-if-changed={}", protocol_file.display()); + + if client { + generate_code_with_destructor_events( + &protocol_file, + out_dir.join(&format!("{}_client_api.rs", name)), + Side::Client, + dest_events, + ); + } + if server { + generate_code_with_destructor_events( + &protocol_file, + out_dir.join(&format!("{}_server_api.rs", name)), + Side::Server, + dest_events, + ); + } +} + +fn main() { + println!("cargo:rerun-if-changed-env=CARGO_FEATURE_CLIENT"); + println!("cargo:rerun-if-changed-env=CARGO_FEATURE_SERVER"); + println!("cargo:rerun-if-changed-env=CARGO_FEATURE_UNSTABLE_PROTOCOLS"); + + let out_dir_str = var("OUT_DIR").unwrap(); + let out_dir = Path::new(&out_dir_str); + + let client = var("CARGO_FEATURE_CLIENT").ok().is_some(); + let server = var("CARGO_FEATURE_SERVER").ok().is_some(); + + for &(name, dest_events) in STABLE_PROTOCOLS { + let file = format!("{name}/{name}.xml", name = name); + generate_protocol( + name, + &Path::new("./protocols/stable").join(&file), + out_dir, + client, + server, + dest_events, + ); + } + + for &(name, dest_events) in MISC_PROTOCOLS { + let file = format!("{name}.xml", name = name); + generate_protocol( + name, + &Path::new("./misc").join(&file), + out_dir, + client, + server, + dest_events, + ); + } + + if var("CARGO_FEATURE_UNSTABLE_PROTOCOLS").ok().is_some() { + for &(name, versions) in UNSTABLE_PROTOCOLS { + for &(version, dest_events) in versions { + let file = format!( + "{name}/{name}-unstable-{version}.xml", + name = name, + version = version + ); + generate_protocol( + &format!("{name}-{version}", name = name, version = version), + &Path::new("./protocols/unstable").join(file), + out_dir, + client, + server, + dest_events, + ); + } + } + for &(name, versions) in WLR_UNSTABLE_PROTOCOLS { + for &(version, dest_events) in versions { + let file = format!("{name}-unstable-{version}.xml", name = name, version = version); + generate_protocol( + &format!("{name}-{version}", name = name, version = version), + &Path::new("./wlr-protocols/unstable").join(file), + out_dir, + client, + server, + dest_events, + ); + } + } + } +} diff --git a/third_party/cargo/vendor/wayland-protocols-0.23.6/misc/gtk-primary-selection.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/misc/gtk-primary-selection.xml new file mode 100644 index 0000000..02cab94 --- /dev/null +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/misc/gtk-primary-selection.xml @@ -0,0 +1,225 @@ + + + + Copyright © 2015, 2016 Red Hat + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol provides the ability to have a primary selection device to + match that of the X server. This primary selection is a shortcut to the + common clipboard selection, where text just needs to be selected in order + to allow copying it elsewhere. The de facto way to perform this action + is the middle mouse button, although it is not limited to this one. + + Clients wishing to honor primary selection should create a primary + selection source and set it as the selection through + wp_primary_selection_device.set_selection whenever the text selection + changes. In order to minimize calls in pointer-driven text selection, + it should happen only once after the operation finished. Similarly, + a NULL source should be set when text is unselected. + + wp_primary_selection_offer objects are first announced through the + wp_primary_selection_device.data_offer event. Immediately after this event, + the primary data offer will emit wp_primary_selection_offer.offer events + to let know of the mime types being offered. + + When the primary selection changes, the client with the keyboard focus + will receive wp_primary_selection_device.selection events. Only the client + with the keyboard focus will receive such events with a non-NULL + wp_primary_selection_offer. Across keyboard focus changes, previously + focused clients will receive wp_primary_selection_device.events with a + NULL wp_primary_selection_offer. + + In order to request the primary selection data, the client must pass + a recent serial pertaining to the press event that is triggering the + operation, if the compositor deems the serial valid and recent, the + wp_primary_selection_source.send event will happen in the other end + to let the transfer begin. The client owning the primary selection + should write the requested data, and close the file descriptor + immediately. + + If the primary selection owner client disappeared during the transfer, + the client reading the data will receive a + wp_primary_selection_device.selection event with a NULL + wp_primary_selection_offer, the client should take this as a hint + to finish the reads related to the no longer existing offer. + + The primary selection owner should be checking for errors during + writes, merely cancelling the ongoing transfer if any happened. + + + + + The primary selection device manager is a singleton global object that + provides access to the primary selection. It allows to create + wp_primary_selection_source objects, as well as retrieving the per-seat + wp_primary_selection_device objects. + + + + + Create a new primary selection source. + + + + + + + Create a new data device for a given seat. + + + + + + + + Destroy the primary selection device manager. + + + + + + + + Replaces the current selection. The previous owner of the primary selection + will receive a wp_primary_selection_source.cancelled event. + + To unset the selection, set the source to NULL. + + + + + + + + Introduces a new wp_primary_selection_offer object that may be used + to receive the current primary selection. Immediately following this + event, the new wp_primary_selection_offer object will send + wp_primary_selection_offer.offer events to describe the offered mime + types. + + + + + + + The wp_primary_selection_device.selection event is sent to notify the + client of a new primary selection. This event is sent after the + wp_primary_selection.data_offer event introducing this object, and after + the offer has announced its mimetypes through + wp_primary_selection_offer.offer. + + The data_offer is valid until a new offer or NULL is received + or until the client loses keyboard focus. The client must destroy the + previous selection data_offer, if any, upon receiving this event. + + + + + + + Destroy the primary selection device. + + + + + + + A wp_primary_selection_offer represents an offer to transfer the contents + of the primary selection clipboard to the client. Similar to + wl_data_offer, the offer also describes the mime types that the source + will transferthat the + data can be converted to and provides the mechanisms for transferring the + data directly to the client. + + + + + To transfer the contents of the primary selection clipboard, the client + issues this request and indicates the mime type that it wants to + receive. The transfer happens through the passed file descriptor + (typically created with the pipe system call). The source client writes + the data in the mime type representation requested and then closes the + file descriptor. + + The receiving client reads from the read end of the pipe until EOF and + closes its end, at which point the transfer is complete. + + + + + + + + Destroy the primary selection offer. + + + + + + Sent immediately after creating announcing the wp_primary_selection_offer + through wp_primary_selection_device.data_offer. One event is sent per + offered mime type. + + + + + + + + The source side of a wp_primary_selection_offer, it provides a way to + describe the offered data and respond to requests to transfer the + requested contents of the primary selection clipboard. + + + + + This request adds a mime type to the set of mime types advertised to + targets. Can be called several times to offer multiple types. + + + + + + + Destroy the primary selection source. + + + + + + Request for the current primary selection contents from the client. + Send the specified mime type over the passed file descriptor, then + close it. + + + + + + + + This primary selection source is no longer valid. The client should + clean up and destroy this primary selection source. + + + + diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/COPYING b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/COPYING similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/COPYING rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/COPYING diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/Makefile.am b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/Makefile.am similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/Makefile.am rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/Makefile.am diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/autogen.sh b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/autogen.sh similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/autogen.sh rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/autogen.sh diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/configure.ac b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/configure.ac similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/configure.ac rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/configure.ac diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/m4/compat.m4 b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/m4/compat.m4 similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/m4/compat.m4 rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/m4/compat.m4 diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/presentation-time/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/presentation-time/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/presentation-time/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/presentation-time/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/presentation-time/presentation-time.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/presentation-time/presentation-time.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/presentation-time/presentation-time.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/presentation-time/presentation-time.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/viewporter/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/viewporter/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/viewporter/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/viewporter/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/viewporter/viewporter.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/viewporter/viewporter.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/viewporter/viewporter.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/viewporter/viewporter.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/xdg-shell/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/xdg-shell/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/xdg-shell/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/xdg-shell/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/xdg-shell/xdg-shell.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/xdg-shell/xdg-shell.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/stable/xdg-shell/xdg-shell.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/stable/xdg-shell/xdg-shell.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/tests/scan.sh b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/tests/scan.sh similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/tests/scan.sh rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/tests/scan.sh diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/fullscreen-shell/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/fullscreen-shell/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/fullscreen-shell/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/fullscreen-shell/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/fullscreen-shell/fullscreen-shell-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/idle-inhibit/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/idle-inhibit/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/idle-inhibit/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/idle-inhibit/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-method/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-method/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-method/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-method/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-method/input-method-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-method/input-method-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-method/input-method-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-method/input-method-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-timestamps/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-timestamps/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-timestamps/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-timestamps/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/input-timestamps/input-timestamps-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/keyboard-shortcuts-inhibit/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/keyboard-shortcuts-inhibit/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/keyboard-shortcuts-inhibit/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/keyboard-shortcuts-inhibit/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-dmabuf/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-dmabuf/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-dmabuf/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-dmabuf/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-dmabuf/linux-dmabuf-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-explicit-synchronization/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-explicit-synchronization/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-explicit-synchronization/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-explicit-synchronization/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/linux-explicit-synchronization/linux-explicit-synchronization-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-constraints/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-constraints/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-constraints/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-constraints/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-gestures/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-gestures/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-gestures/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-gestures/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/primary-selection/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/primary-selection/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/primary-selection/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/primary-selection/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/primary-selection/primary-selection-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/primary-selection/primary-selection-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/primary-selection/primary-selection-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/primary-selection/primary-selection-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/relative-pointer/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/relative-pointer/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/relative-pointer/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/relative-pointer/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/relative-pointer/relative-pointer-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/tablet-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/tablet-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/tablet-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/tablet-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/tablet-unstable-v2.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/tablet-unstable-v2.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/tablet/tablet-unstable-v2.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/tablet/tablet-unstable-v2.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/text-input-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/text-input-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/text-input-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/text-input-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/text-input-unstable-v3.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/text-input-unstable-v3.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/text-input/text-input-unstable-v3.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/text-input/text-input-unstable-v3.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-decoration/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-decoration/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-decoration/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-decoration/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-output/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-output/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-output/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-output/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-output/xdg-output-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-output/xdg-output-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-output/xdg-output-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-output/xdg-output-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/xdg-shell-unstable-v5.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xdg-shell/xdg-shell-unstable-v6.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xwayland-keyboard-grab/README b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xwayland-keyboard-grab/README similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xwayland-keyboard-grab/README rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xwayland-keyboard-grab/README diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/unstable/xwayland-keyboard-grab/xwayland-keyboard-grab-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/wayland-protocols-uninstalled.pc.in b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/wayland-protocols-uninstalled.pc.in similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/wayland-protocols-uninstalled.pc.in rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/wayland-protocols-uninstalled.pc.in diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/wayland-protocols.pc.in b/third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/wayland-protocols.pc.in similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/protocols/wayland-protocols.pc.in rename to third_party/cargo/vendor/wayland-protocols-0.23.6/protocols/wayland-protocols.pc.in diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/lib.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/lib.rs similarity index 94% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/src/lib.rs rename to third_party/cargo/vendor/wayland-protocols-0.23.6/src/lib.rs index a8f2a2c..be6ae2a 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/lib.rs +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/lib.rs @@ -24,10 +24,6 @@ extern crate wayland_server; extern crate wayland_commons; -#[cfg(feature = "native_lib")] -#[macro_use] -extern crate wayland_sys; - #[macro_use] extern crate bitflags; @@ -37,6 +33,7 @@ mod protocol_macro; #[cfg(feature = "unstable_protocols")] pub mod unstable; +pub mod misc; pub mod wlr; mod stable; diff --git a/third_party/cargo/vendor/wayland-protocols-0.23.6/src/misc.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/misc.rs new file mode 100644 index 0000000..c10e46e --- /dev/null +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/misc.rs @@ -0,0 +1,64 @@ +//! Misc protocols +//! +//! This module contains protocols that are not clearly packaged by their maintainers, +//! often being implementation details of desktop environment, but can be used by external +//! tools for interoperability. +//! +//! Given they are not clearly packaged, the maintainers of this crate cannot guarantee +//! anything when it comes to them being up to date or the stability of their interface. +//! Pull requests for updating them will be welcomed, but we won't actively check if they +//! have received any updates. + +#![cfg_attr(rustfmt, rustfmt_skip)] + +pub mod gtk_primary_selection { + //! Gtk primary selection protocol + //! + //! This protocol provides the ability to have a primary selection device to + //! match that of the X server. This primary selection is a shortcut to the + //! common clipboard selection, where text just needs to be selected in order + //! to allow copying it elsewhere. The de facto way to perform this action + //! is the middle mouse button, although it is not limited to this one. + //! + //! Clients wishing to honor primary selection should create a primary + //! selection source and set it as the selection through + //! `wp_primary_selection_device.set_selection` whenever the text selection + //! changes. In order to minimize calls in pointer-driven text selection, + //! it should happen only once after the operation finished. Similarly, + //! a NULL source should be set when text is unselected. + //! + //! `wp_primary_selection_offer` objects are first announced through the + //! `wp_primary_selection_device.data_offer` event. Immediately after this event, + //! the primary data offer will emit `wp_primary_selection_offer.offer` events + //! to let know of the mime types being offered. + //! + //! When the primary selection changes, the client with the keyboard focus + //! will receive `wp_primary_selection_device.selection` events. Only the client + //! with the keyboard focus will receive such events with a non-NULL + //! `wp_primary_selection_offer`. Across keyboard focus changes, previously + //! focused clients will receive `wp_primary_selection_device.events` with a + //! NULL `wp_primary_selection_offer`. + //! + //! In order to request the primary selection data, the client must pass + //! a recent serial pertaining to the press event that is triggering the + //! operation, if the compositor deems the serial valid and recent, the + //! `wp_primary_selection_source.send` event will happen in the other end + //! to let the transfer begin. The client owning the primary selection + //! should write the requested data, and close the file descriptor + //! immediately. + //! + //! If the primary selection owner client disappeared during the transfer, + //! the client reading the data will receive a + //! `wp_primary_selection_device.selection` event with a NULL + //! `wp_primary_selection_offer`, the client should take this as a hint + //! to finish the reads related to the no longer existing offer. + //! + //! The primary selection owner should be checking for errors during + //! writes, merely cancelling the ongoing transfer if any happened. + + wayland_protocol!( + "gtk-primary-selection", + [(wl_seat, wl_seat_interface)], + [] + ); +} diff --git a/third_party/cargo/vendor/wayland-protocols-0.23.6/src/protocol_macro.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/protocol_macro.rs new file mode 100644 index 0000000..e0799e5 --- /dev/null +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/protocol_macro.rs @@ -0,0 +1,60 @@ +#[macro_escape] +macro_rules! wayland_protocol( + ($name: expr, [$(($import: ident, $interface: ident)),*], [$(($prot_name:ident, $prot_import: ident, $prot_iface: ident)),*]) => { + #[cfg(feature = "client")] + pub use self::generated::client; + + #[cfg(feature = "server")] + pub use self::generated::server; + + mod generated { + #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)] + #![allow(non_upper_case_globals,non_snake_case,unused_imports)] + #![allow(missing_docs)] + #![cfg_attr(feature = "cargo-clippy", allow(clippy))] + + #[cfg(feature = "client")] + pub mod client { + //! Client-side API of this protocol + pub(crate) use wayland_client::{NewProxy, Proxy, ProxyMap, HandledBy, AnonymousObject}; + pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; + pub(crate) use wayland_commons::{Interface, MessageGroup}; + pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; + pub(crate) use wayland_client::protocol::{$($import),*}; + pub(crate) use wayland_client::sys; + $( + pub(crate) use ::$prot_name::client::$prot_import; + )* + include!(concat!(env!("OUT_DIR"), "/", $name, "_client_api.rs")); + } + + #[cfg(feature = "server")] + pub mod server { + //! Server-side API of this protocol + pub(crate) use wayland_server::{AnonymousObject, NewResource, Resource, ResourceMap, HandledBy}; + pub(crate) use wayland_commons::map::{Object, ObjectMetadata}; + pub(crate) use wayland_commons::{Interface, MessageGroup}; + pub(crate) use wayland_commons::wire::{Argument, MessageDesc, ArgumentType, Message}; + pub(crate) use wayland_server::protocol::{$($import),*}; + pub(crate) use wayland_server::sys; + $( + pub(crate) use ::$prot_name::server::$prot_import; + )* + include!(concat!(env!("OUT_DIR"), "/", $name, "_server_api.rs")); + } + } + } +); + +#[cfg(feature = "unstable_protocols")] +#[macro_escape] +macro_rules! wayland_protocol_versioned( + ($name: expr, [$($version: ident),*], $std_imports:tt, $prot_imports:tt) => { + $( + #[allow(missing_docs)] + pub mod $version { + wayland_protocol!(concat!($name, "-", stringify!($version)), $std_imports, $prot_imports); + } + )* + } +); diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/stable.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/stable.rs similarity index 65% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/src/stable.rs rename to third_party/cargo/vendor/wayland-protocols-0.23.6/src/stable.rs index 89cc47b..55f4cd0 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/stable.rs +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/stable.rs @@ -3,7 +3,7 @@ pub mod presentation_time { //! Presentation time protocol //! - //! Allows precise feedback on presentation timing for example for smooth video playback. + //! Allows precise feedback on presentation timing, for example for smooth video playback. wayland_protocol!( "presentation-time", @@ -18,7 +18,7 @@ pub mod presentation_time { pub mod xdg_shell { //! XDG Shell protocol //! - //! Exposes the `xdg_wm_base` global, which deprecates and replace `wl_shell`. + //! Exposes the `xdg_wm_base` global, which deprecates and replaces `wl_shell`. wayland_protocol!( "xdg-shell", @@ -34,14 +34,8 @@ pub mod xdg_shell { pub mod viewporter { //! Viewporter protocol //! - //! Gives the capability to scale and crop surfaces, decorrelating the surface dimensions from - //! the size of the buffer. + //! Provides the capability of scaling and cropping surfaces, decorrelating the surface + //! dimensions from the size of the buffer. - wayland_protocol!( - "viewporter", - [ - (wl_surface, wl_surface_interface) - ], - [] - ); + wayland_protocol!("viewporter", [(wl_surface, wl_surface_interface)], []); } diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/unstable.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/unstable.rs similarity index 98% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/src/unstable.rs rename to third_party/cargo/vendor/wayland-protocols-0.23.6/src/unstable.rs index 95c5528..bfef674 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/unstable.rs +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/unstable.rs @@ -1,9 +1,11 @@ //! Unstable protocols from wayland-protocols //! //! The protocols described in this module are experimental and -//! backward incompatible changes may be made. Backward compatible -//! changes may be added together with the corresponding interface -//! version bump. +//! provide no guarantee of forward support. They may be abandonned +//! or never widely implemented. +//! +//! Backward compatible changes may be added together with the +//! corresponding interface version bump. //! //! Backward incompatible changes are done by bumping the version //! number in the protocol and interface names and resetting the diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/src/wlr.rs b/third_party/cargo/vendor/wayland-protocols-0.23.6/src/wlr.rs similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/src/wlr.rs rename to third_party/cargo/vendor/wayland-protocols-0.23.6/src/wlr.rs diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/Makefile b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/Makefile similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/Makefile rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/Makefile diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/check.sh b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/check.sh similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/check.sh rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/check.sh diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml similarity index 73% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml index a588755..75e8671 100644 --- a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml +++ b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-data-control-unstable-v1.xml @@ -2,6 +2,7 @@ Copyright © 2018 Simon Ser + Copyright © 2019 Ivan Molodetskikh Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted @@ -40,7 +41,7 @@ interface version number is reset. - + This interface is a manager that allows creating per-seat data device controls. @@ -70,7 +71,7 @@ - + This interface allows a client to manage a seat's selection. @@ -79,8 +80,14 @@ - All objects created by the device will still remain valid, until their - appropriate destroy request has been called. + This request asks the compositor to set the selection to the data from + the source on behalf of the client. + + The given source may not be used in any further set_selection or + set_primary_selection requests. Attempting to use a previously used + source is a protocol error. + + To unset the selection, set the source to NULL. @@ -95,20 +102,19 @@ The data_offer event introduces a new wlr_data_control_offer object, - which will subsequently be used in the wlr_data_control_device.selection - event. Immediately following the wlr_data_control_device.data_offer - event, the new data_offer object will send out - wlr_data_control_offer.offer events to describe the MIME types it - offers. - - This event replaces the previous data offer, which should be destroyed - by the client. + which will subsequently be used in either the + wlr_data_control_device.selection event (for the regular clipboard + selections) or the wlr_data_control_device.primary_selection event (for + the primary clipboard selections). Immediately following the + wlr_data_control_device.data_offer event, the new data_offer object + will send out wlr_data_control_offer.offer events to describe the MIME + types it offers. - + The selection event is sent out to notify the client of a new wlr_data_control_offer for the selection for this device. The wlr_data_control_device.data_offer and the wlr_data_control_offer.offer @@ -118,6 +124,9 @@ wlr_data_control_offer or NULL is received. The client must destroy the previous selection wlr_data_control_offer, if any, upon receiving this event. + + The first selection event is sent upon binding the + wlr_data_control_device object. @@ -129,6 +138,51 @@ the client. + + + + + + The primary_selection event is sent out to notify the client of a new + wlr_data_control_offer for the primary selection for this device. The + wlr_data_control_device.data_offer and the wlr_data_control_offer.offer + events are sent out immediately before this event to introduce the data + offer object. The primary_selection event is sent to a client when a + new primary selection is set. The wlr_data_control_offer is valid until + a new wlr_data_control_offer or NULL is received. The client must + destroy the previous primary selection wlr_data_control_offer, if any, + upon receiving this event. + + If the compositor supports primary selection, the first + primary_selection event is sent upon binding the + wlr_data_control_device object. + + + + + + + This request asks the compositor to set the primary selection to the + data from the source on behalf of the client. + + The given source may not be used in any further set_selection or + set_primary_selection requests. Attempting to use a previously used + source is a protocol error. + + To unset the primary selection, set the source to NULL. + + The compositor will ignore this request if it does not support primary + selection. + + + + + + + diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-export-dmabuf-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-foreign-toplevel-management-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-gamma-control-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-input-inhibitor-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-layer-shell-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/unstable/wlr-screencopy-unstable-v1.xml diff --git a/third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/wlr-protocols.pc.in b/third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/wlr-protocols.pc.in similarity index 100% rename from third_party/cargo/vendor/wayland-protocols-0.21.13/wlr-protocols/wlr-protocols.pc.in rename to third_party/cargo/vendor/wayland-protocols-0.23.6/wlr-protocols/wlr-protocols.pc.in diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/.cargo-checksum.json b/third_party/cargo/vendor/wayland-scanner-0.21.13/.cargo-checksum.json deleted file mode 100644 index 3d62316..0000000 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"a06188ab384389c22726dcdccd1d26abc6ffd93ed4cc0eca07de5e42a4c76247","src/c_code_gen.rs":"0db7cb379a56b3ca7774972e6d6c425c1c7048b9a98316e4129c526e9f85bfff","src/c_interface_gen.rs":"0f55a6df7b7c9cbec4a447f38f292ae9e6a7d880e8694bd0a433a4b16cb0bc3a","src/common_gen.rs":"d95bc9a97a63d7123e900d041d47b3b9149b44417b6c52c368e8eb97691f3e90","src/lib.rs":"e50f841cb2f308913fffea2c55f71ca22e9403d23df5e566691409f3dbaec222","src/parse.rs":"1defa09caf64ef3a6659bcf98e2881c12d1531e693b9bdb73f3cf0ba2c0ac254","src/protocol.rs":"7c0d1cda4de54aeb0cb5c45f506049055d7b3247f5b278401027ecdaace51059","src/rust_code_gen.rs":"7da53df062f4f4f0ad3aa4b46c45b0caeab0302ed3d7dcf4a9413c1aea569088","src/side.rs":"398d55c387cdacd6febc5029d211f87e2b1b3b0ddb65fa66f567815dffb0510b","src/util.rs":"44cf7c4d70bbee39a5fca39e284d6549d66ed22fa9b93c6c21fc9fe8d16edf82"},"package":"bf3828c568714507315ee425a9529edc4a4aa9901409e373e9e0027e7622b79e"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/rust_code_gen.rs b/third_party/cargo/vendor/wayland-scanner-0.21.13/src/rust_code_gen.rs deleted file mode 100644 index e9a7c43..0000000 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/rust_code_gen.rs +++ /dev/null @@ -1,114 +0,0 @@ -use proc_macro2::{Ident, Span, TokenStream}; - -use common_gen::*; -use protocol::*; -use util::*; -use Side; - -pub(crate) fn generate_protocol_client(protocol: Protocol) -> TokenStream { - let modules = protocol.interfaces.iter().map(|iface| { - let doc_attr = iface.description.as_ref().map(description_to_doc_attr); - let mod_name = Ident::new(&iface.name, Span::call_site()); - let iface_name = Ident::new(&snake_to_camel(&iface.name), Span::call_site()); - - let enums = &iface.enums; - let requests = gen_messagegroup( - &Ident::new("Request", Span::call_site()), - Side::Client, - false, - &iface.requests, - None, - ); - let events = gen_messagegroup( - &Ident::new("Event", Span::call_site()), - Side::Client, - true, - &iface.events, - None, - ); - let interface = gen_interface( - &iface_name, - &iface.name, - iface.version, - None, - ); - let client_methods = gen_client_methods(&iface_name, &iface.requests); - let sinces = gen_since_constants(&iface.requests, &iface.events); - - quote! { - #doc_attr - pub mod #mod_name { - use super::{ - Proxy, NewProxy, AnonymousObject, Interface, MessageGroup, MessageDesc, ArgumentType, Object, - Message, Argument, ObjectMetadata, - }; - - #(#enums)* - #requests - #events - #interface - #client_methods - #sinces - } - } - }); - - quote! { - #(#modules)* - } -} - -pub(crate) fn generate_protocol_server(protocol: Protocol) -> TokenStream { - let modules = protocol - .interfaces - .iter() - // display and registry are handled specially - .filter(|iface| iface.name != "wl_display" && iface.name != "wl_registry") - .map(|iface| { - let doc_attr = iface.description.as_ref().map(description_to_doc_attr); - let mod_name = Ident::new(&iface.name, Span::call_site()); - - let enums = &iface.enums; - let requests = gen_messagegroup( - &Ident::new("Request", Span::call_site()), - Side::Server, - true, - &iface.requests, - None, - ); - let events = gen_messagegroup( - &Ident::new("Event", Span::call_site()), - Side::Server, - false, - &iface.events, - None, - ); - let interface = gen_interface( - &Ident::new(&snake_to_camel(&iface.name), Span::call_site()), - &iface.name, - iface.version, - None, - ); - let sinces = gen_since_constants(&iface.requests, &iface.events); - - quote! { - #doc_attr - pub mod #mod_name { - use super::{ - Resource, NewResource, AnonymousObject, Interface, MessageGroup, MessageDesc, - ArgumentType, Object, Message, Argument, ObjectMetadata - }; - - #(#enums)* - #requests - #events - #interface - #sinces - } - } - }); - - quote! { - #(#modules)* - } -} diff --git a/third_party/cargo/vendor/wayland-scanner-0.23.6/.cargo-checksum.json b/third_party/cargo/vendor/wayland-scanner-0.23.6/.cargo-checksum.json new file mode 100644 index 0000000..ae32965 --- /dev/null +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"eb9b2f99157ccc6e7e13620ee6de307fa8608a1265fb9ce78769c234ad4c4896","src/c_code_gen.rs":"c69ffb34afa977a5dd9da369d92256d4ff6d407cba6c1ffe1509738e2b3fe6d0","src/c_interface_gen.rs":"fa8e864a0a07f6254fce4aa67b39ac5d391d2c60b6d21d4095c66f2258d6b3f5","src/common_gen.rs":"affa810601fe5bb27fcb6265653ada8fc2327f87f448b35948740103928a3f85","src/lib.rs":"7c8cd13d4f2f925795c0876dec84091437234d6401d159509e8cfc00a9cd6f38","src/parse.rs":"52329e177dd3e17e5d372ec4131ec618acf51c8729eb50964709bb8fea63323b","src/protocol.rs":"7c3402f1a52cf6dc9f1def460042a62002bc397af7fa71712cc3b9d2b541b6ee","src/side.rs":"5e398f59f987a41c09f818c369f6fffb560977d988b971d002d920c5af218137","src/util.rs":"98f876e4c3fa5030774853a50734545293ad66380b72818b3aa8f94502645b6a"},"package":"93b02247366f395b9258054f964fe293ddd019c3237afba9be2ccbe9e1651c3d"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/BUILD b/third_party/cargo/vendor/wayland-scanner-0.23.6/BUILD similarity index 97% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/BUILD rename to third_party/cargo/vendor/wayland-scanner-0.23.6/BUILD index 2f223f7..2af7290 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/BUILD +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/BUILD @@ -38,7 +38,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.21.13", + version = "0.23.6", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/Cargo.toml b/third_party/cargo/vendor/wayland-scanner-0.23.6/Cargo.toml similarity index 95% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/Cargo.toml rename to third_party/cargo/vendor/wayland-scanner-0.23.6/Cargo.toml index 32670f5..ea4881f 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/Cargo.toml +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "wayland-scanner" -version = "0.21.13" +version = "0.23.6" authors = ["Victor Berger "] description = "Wayland Scanner for generating rust APIs from XML wayland protocol files. Intented for use with wayland-sys. You should only need this crate if you are working on custom wayland protocol extensions. Look at the crate wayland-client for usable bindings." documentation = "https://smithay.github.io/wayland-rs/wayland_scanner/" diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_code_gen.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_code_gen.rs similarity index 83% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_code_gen.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_code_gen.rs index d466c36..114d94c 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_code_gen.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_code_gen.rs @@ -21,7 +21,13 @@ pub(crate) fn generate_protocol_client(protocol: Protocol) -> TokenStream { Side::Client, false, &iface.requests, - Some(messagegroup_c_addon(&ident, Side::Client, false, &iface.requests)), + Some(messagegroup_c_addon( + &ident, + &iface_name, + Side::Client, + false, + &iface.requests, + )), ); let ident = Ident::new("Event", Span::call_site()); @@ -30,7 +36,13 @@ pub(crate) fn generate_protocol_client(protocol: Protocol) -> TokenStream { Side::Client, true, &iface.events, - Some(messagegroup_c_addon(&ident, Side::Client, true, &iface.events)), + Some(messagegroup_c_addon( + &ident, + &iface_name, + Side::Client, + true, + &iface.events, + )), ); let interface = gen_interface( @@ -38,32 +50,42 @@ pub(crate) fn generate_protocol_client(protocol: Protocol) -> TokenStream { &iface.name, iface.version, Some(interface_c_addon(&iface.name)), + Side::Client, ); - let client_methods = gen_client_methods(&iface_name, &iface.requests); + let object_methods = gen_object_methods(&iface_name, &iface.requests, Side::Client); + let event_handler_trait = gen_event_handler_trait(&iface_name, &iface.events, Side::Client); let sinces = gen_since_constants(&iface.requests, &iface.events); + let c_interface = super::c_interface_gen::generate_interface(&iface); quote! { #doc_attr pub mod #mod_name { + use std::os::raw::c_char; use super::{ Proxy, NewProxy, AnonymousObject, Interface, MessageGroup, MessageDesc, ArgumentType, - Object, Message, Argument, ObjectMetadata + Object, Message, Argument, ObjectMetadata, HandledBy, types_null, NULLPTR }; - use super::sys::common::{wl_argument, wl_interface, wl_array}; + use super::sys::common::{wl_interface, wl_array, wl_argument, wl_message}; use super::sys::client::*; #(#enums)* #requests #events #interface - #client_methods + #object_methods + #event_handler_trait #sinces + #c_interface } } }); + let c_prefix = super::c_interface_gen::generate_interfaces_prefix(&protocol); + quote! { + #c_prefix + #(#modules)* } } @@ -77,6 +99,7 @@ pub(crate) fn generate_protocol_server(protocol: Protocol) -> TokenStream { .map(|iface| { let doc_attr = iface.description.as_ref().map(description_to_doc_attr); let mod_name = Ident::new(&iface.name, Span::call_site()); + let iface_name = Ident::new(&snake_to_camel(&iface.name), Span::call_site()); let enums = &iface.enums; @@ -86,7 +109,7 @@ pub(crate) fn generate_protocol_server(protocol: Protocol) -> TokenStream { Side::Server, true, &iface.requests, - Some(messagegroup_c_addon(&ident, Side::Server, true, &iface.requests)), + Some(messagegroup_c_addon(&ident, &iface_name, Side::Server, true, &iface.requests)), ); let ident = Ident::new("Event", Span::call_site()); @@ -95,7 +118,7 @@ pub(crate) fn generate_protocol_server(protocol: Protocol) -> TokenStream { Side::Server, false, &iface.events, - Some(messagegroup_c_addon(&ident, Side::Server, false, &iface.events)), + Some(messagegroup_c_addon(&ident, &iface_name, Side::Server, false, &iface.events)), ); let interface = gen_interface( @@ -103,34 +126,51 @@ pub(crate) fn generate_protocol_server(protocol: Protocol) -> TokenStream { &iface.name, iface.version, Some(interface_c_addon(&iface.name)), + Side::Server, ); + let object_methods = gen_object_methods(&iface_name, &iface.events, Side::Server); + let event_handler_trait = gen_event_handler_trait(&iface_name, &iface.requests, Side::Server); let sinces = gen_since_constants(&iface.requests, &iface.events); + let c_interface = super::c_interface_gen::generate_interface(&iface); quote! { #doc_attr pub mod #mod_name { + use std::os::raw::c_char; use super::{ Resource, NewResource, AnonymousObject, Interface, MessageGroup, MessageDesc, - ArgumentType, Object, Message, Argument, ObjectMetadata + ArgumentType, Object, Message, Argument, ObjectMetadata, HandledBy, types_null, NULLPTR }; - use super::sys::common::{wl_argument, wl_interface, wl_array}; + use super::sys::common::{wl_argument, wl_interface, wl_array, wl_message}; use super::sys::server::*; #(#enums)* #requests #events #interface + #object_methods + #event_handler_trait #sinces + #c_interface } } }); + let c_prefix = super::c_interface_gen::generate_interfaces_prefix(&protocol); + quote! { + #c_prefix #(#modules)* } } -fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Message]) -> TokenStream { +fn messagegroup_c_addon( + name: &Ident, + parent_iface: &Ident, + side: Side, + receiver: bool, + messages: &[Message], +) -> TokenStream { let from_raw_c_body = if receiver { let match_arms = messages .iter() @@ -145,7 +185,10 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me let len = Literal::usize_unsuffixed(msg.args.len()); let fields = msg.args.iter().enumerate().map(|(j, arg)| { - let field_name = Ident::new(&arg.name, Span::call_site()); + let field_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); let idx = Literal::usize_unsuffixed(j); let field_value = match arg.typ { @@ -206,11 +249,11 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me quote! { #object_name::::from_c_ptr( _args[#idx].o as *mut _, - ) + ).into() } } else { quote! { - #object_name::::from_c_ptr(_args[#idx].o as *mut _) + #object_name::::from_c_ptr(_args[#idx].o as *mut _).into() } }; @@ -238,28 +281,8 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me Side::Server => { quote! { { - let client = ffi_dispatch!( - WAYLAND_SERVER_HANDLE, - wl_resource_get_client, - obj as *mut _ - ); - let version = ffi_dispatch!( - WAYLAND_SERVER_HANDLE, - wl_resource_get_version, - obj as *mut _ - ); - let new_ptr = ffi_dispatch!( - WAYLAND_SERVER_HANDLE, - wl_resource_create, - client, - super::#iface_mod::#iface_type::c_interface(), - version, - _args[#idx].n - ); - - NewResource::::from_c_ptr( - new_ptr - ) + let me = Resource::<#parent_iface>::from_c_ptr(obj as *mut _); + me.make_child_for::(_args[#idx].n).unwrap() } } } @@ -324,10 +347,12 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me let pattern = if msg.args.is_empty() { quote!(#name::#msg_name) } else { - let fields = msg - .args - .iter() - .map(|arg| Ident::new(&arg.name, Span::call_site())); + let fields = msg.args.iter().map(|arg| { + Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ) + }); quote!(#name::#msg_name { #(#fields),* }) }; @@ -344,7 +369,10 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me let mut j = 0; let args_array_init_stmts = msg.args.iter().map(|arg| { let idx = Literal::usize_unsuffixed(j); - let arg_name = Ident::new(&arg.name, Span::call_site()); + let arg_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); let res = match arg.typ { Type::Uint => { @@ -419,20 +447,19 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me if arg.allow_null { quote! { _args_array[#idx].o = #arg_name - .map(|o| o.c_ptr() as *mut _) + .map(|o| o.as_ref().c_ptr() as *mut _) .unwrap_or(::std::ptr::null_mut()); } } else { quote! { - _args_array[#idx].o = #arg_name.c_ptr() as *mut _; + _args_array[#idx].o = #arg_name.as_ref().c_ptr() as *mut _; } } } Type::NewId => { if arg.interface.is_some() { quote! { - _args_array[#idx].o = #arg_name.c_ptr() as *mut _; - } + _args_array[#idx].o = #arg_name.as_ref().c_ptr() as *mut _; } } else { assert!( side != Side::Server, @@ -478,6 +505,7 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me quote! { match self { + #name::__nonexhaustive => unreachable!(), #(#match_arms,)* } } @@ -499,10 +527,10 @@ fn messagegroup_c_addon(name: &Ident, side: Side, receiver: bool, messages: &[Me } fn interface_c_addon(low_name: &str) -> TokenStream { - let mod_name = Ident::new(&format!("{}_interface", low_name), Span::call_site()); + let iface_name = Ident::new(&format!("{}_interface", low_name), Span::call_site()); quote! { fn c_interface() -> *const wl_interface { - unsafe { &super::super::c_interfaces::#mod_name } + unsafe { &#iface_name } } } } diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_interface_gen.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_interface_gen.rs similarity index 66% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_interface_gen.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_interface_gen.rs index 5cff8b5..86ecfa4 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/c_interface_gen.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/c_interface_gen.rs @@ -6,7 +6,7 @@ use proc_macro2::{Ident, Literal, Span, TokenStream}; use protocol::*; use util::null_terminated_byte_string_literal; -pub(crate) fn generate_interfaces(protocol: Protocol) -> TokenStream { +pub(crate) fn generate_interfaces_prefix(protocol: &Protocol) -> TokenStream { let longest_nulls = protocol.interfaces.iter().fold(0, |max, interface| { let request_longest_null = interface.requests.iter().fold(0, |max, request| { if request.all_null() { @@ -27,58 +27,56 @@ pub(crate) fn generate_interfaces(protocol: Protocol) -> TokenStream { let types_null_len = Literal::usize_unsuffixed(longest_nulls); - let nulls = repeat(quote!(NULLPTR as *const wl_interface)).take(longest_nulls); - - let interfaces = protocol.interfaces.iter().map(|interface| { - let requests = gen_messages(interface, &interface.requests, "requests"); - let events = gen_messages(interface, &interface.events, "events"); - - let interface_ident = Ident::new(&format!("{}_interface", interface.name), Span::call_site()); - let name_value = null_terminated_byte_string_literal(&interface.name); - let version_value = Literal::i32_unsuffixed(interface.version as i32); - let request_count_value = Literal::i32_unsuffixed(interface.requests.len() as i32); - let requests_value = if interface.requests.is_empty() { - quote!(NULLPTR as *const wl_message) - } else { - let requests_ident = Ident::new(&format!("{}_requests", interface.name), Span::call_site()); - quote!(unsafe { &#requests_ident as *const _ }) - }; - let event_count_value = Literal::i32_unsuffixed(interface.events.len() as i32); - let events_value = if interface.events.is_empty() { - quote!(NULLPTR as *const wl_message) - } else { - let events_ident = Ident::new(&format!("{}_events", interface.name), Span::call_site()); - quote!(unsafe { &#events_ident as *const _ }) - }; - - quote!( - #requests - #events - - pub static mut #interface_ident: wl_interface = wl_interface { - name: #name_value as *const u8 as *const c_char, - version: #version_value, - request_count: #request_count_value, - requests: #requests_value, - event_count: #event_count_value, - events: #events_value, - }; - ) - }); + let nulls = repeat(quote!(NULLPTR as *const sys::common::wl_interface)).take(longest_nulls); quote! { use std::os::raw::{c_char, c_void}; - use wayland_sys::common::*; const NULLPTR: *const c_void = 0 as *const c_void; - static mut types_null: [*const wl_interface; #types_null_len] = [ + static mut types_null: [*const sys::common::wl_interface; #types_null_len] = [ #(#nulls,)* ]; - - #(#interfaces)* } } +pub(crate) fn generate_interface(interface: &Interface) -> TokenStream { + let requests = gen_messages(interface, &interface.requests, "requests"); + let events = gen_messages(interface, &interface.events, "events"); + + let interface_ident = Ident::new(&format!("{}_interface", interface.name), Span::call_site()); + let name_value = null_terminated_byte_string_literal(&interface.name); + let version_value = Literal::i32_unsuffixed(interface.version as i32); + let request_count_value = Literal::i32_unsuffixed(interface.requests.len() as i32); + let requests_value = if interface.requests.is_empty() { + quote!(NULLPTR as *const wl_message) + } else { + let requests_ident = Ident::new(&format!("{}_requests", interface.name), Span::call_site()); + quote!(unsafe { &#requests_ident as *const _ }) + }; + let event_count_value = Literal::i32_unsuffixed(interface.events.len() as i32); + let events_value = if interface.events.is_empty() { + quote!(NULLPTR as *const wl_message) + } else { + let events_ident = Ident::new(&format!("{}_events", interface.name), Span::call_site()); + quote!(unsafe { &#events_ident as *const _ }) + }; + + quote!( + #requests + #events + + /// C representation of this interface, for interop + pub static mut #interface_ident: wl_interface = wl_interface { + name: #name_value as *const u8 as *const c_char, + version: #version_value, + request_count: #request_count_value, + requests: #requests_value, + event_count: #event_count_value, + events: #events_value, + }; + ) +} + fn gen_messages(interface: &Interface, messages: &[Message], which: &str) -> TokenStream { if messages.is_empty() { return TokenStream::new(); @@ -95,8 +93,9 @@ fn gen_messages(interface: &Interface, messages: &[Message], which: &str) -> Tok let array_len = Literal::usize_unsuffixed(msg.args.len()); let array_values = msg.args.iter().map(|arg| match (arg.typ, &arg.interface) { (Type::Object, &Some(ref inter)) | (Type::NewId, &Some(ref inter)) => { + let module = Ident::new(inter, Span::call_site()); let interface_ident = Ident::new(&format!("{}_interface", inter), Span::call_site()); - quote!(unsafe { &#interface_ident as *const wl_interface }) + quote!(unsafe { &super::#module::#interface_ident as *const wl_interface }) } _ => quote!(NULLPTR as *const wl_interface), }); @@ -136,6 +135,7 @@ fn gen_messages(interface: &Interface, messages: &[Message], which: &str) -> Tok quote! { #(#types_arrays)* + /// C-representation of the messages of this interface, for interop pub static mut #message_array_ident: [wl_message; #message_array_len] = [ #(#message_array_values,)* ]; diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/common_gen.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/common_gen.rs similarity index 68% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/common_gen.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/common_gen.rs index a82fdda..2a04311 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/common_gen.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/common_gen.rs @@ -2,6 +2,7 @@ #[allow(deprecated)] use std::ascii::AsciiExt; use std::iter; +use std::str; use proc_macro2::{Ident, Literal, Span, TokenStream}; use quote::ToTokens; @@ -11,11 +12,7 @@ use util::*; use Side; pub(crate) fn to_doc_attr(text: &str) -> TokenStream { - let text = text - .lines() - .map(|line| line.trim()) - .collect::>() - .join("\n"); + let text = text.lines().map(str::trim).collect::>().join("\n"); let text = text.trim(); quote!(#[doc = #text]) @@ -110,6 +107,8 @@ impl ToTokens for Enum { #[derive(Copy, Clone, Debug, PartialEq)] pub enum #ident { #(#variants,)* + #[doc(hidden)] + __nonexhaustive, } }; @@ -161,7 +160,7 @@ pub(crate) fn gen_since_constants(requests: &[Message], events: &[Message]) -> T let since = msg.since; quote! { /// The minimal object version supporting this request - pub const #cstname: u16 = #since; + pub const #cstname: u32 = #since; } }); let evt_constants = events.iter().map(|msg| { @@ -172,7 +171,7 @@ pub(crate) fn gen_since_constants(requests: &[Message], events: &[Message]) -> T let since = msg.since; quote! { /// The minimal object version supporting this event - pub const #cstname: u16 = #since; + pub const #cstname: u32 = #since; } }); @@ -210,7 +209,10 @@ pub(crate) fn gen_messagegroup( msg_name.into_token_stream() } else { let fields = msg.args.iter().map(|arg| { - let field_name = Ident::new(&arg.name, Span::call_site()); + let field_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); let field_type_inner = if let Some(ref enu) = arg.enum_ { dotted_to_relname(enu) } else { @@ -222,26 +224,38 @@ pub(crate) fn gen_messagegroup( Type::Array => quote!(Vec), Type::Fd => quote!(::std::os::unix::io::RawFd), Type::Object => { - let object_name = side.object_name(); if let Some(ref iface) = arg.interface { let iface_mod = Ident::new(&iface, Span::call_site()); let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site()); - quote!(#object_name) + quote!(super::#iface_mod::#iface_type) } else { - quote!(#object_name) + quote!(AnonymousObject) } } Type::NewId => { - let prefix = if receiver { "New" } else { "" }; - let object_name = - Ident::new(&format!("{}{}", prefix, side.object_name()), Span::call_site()); + let object_name = if receiver { + Some(Ident::new( + &format!("New{}", side.object_name()), + Span::call_site(), + )) + } else { + None + }; if let Some(ref iface) = arg.interface { let iface_mod = Ident::new(&iface, Span::call_site()); let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site()); - quote!(#object_name) + if let Some(object_name) = object_name { + quote!(#object_name) + } else { + quote!(super::#iface_mod::#iface_type) + } } else { // bind-like function - quote!((String, u32, #object_name)) + if let Some(object_name) = object_name { + quote!((String, u32, #object_name)) + } else { + quote!((String, u32, AnonymousObject)) + } } } Type::Destructor => panic!("An argument cannot have type \"destructor\"."), @@ -274,7 +288,7 @@ pub(crate) fn gen_messagegroup( let message_array_values = messages.iter().map(|msg| { let name_value = &msg.name; - let since_value = Literal::u16_unsuffixed(msg.since); + let since_value = Literal::u32_unsuffixed(msg.since); let signature_values = msg.args.iter().map(|arg| { let common_type = arg.typ.common_type(); quote!(super::ArgumentType::#common_type) @@ -322,9 +336,17 @@ pub(crate) fn gen_messagegroup( is_destructor_match_arms.push(quote!(_ => false)); } - let opcode_match_arms = message_match_patterns.enumerate().map(|(opcode, pattern)| { - let value = Literal::u16_unsuffixed(opcode as u16); - quote!(#pattern => #value) + let opcode_match_arms = message_match_patterns + .clone() + .enumerate() + .map(|(opcode, pattern)| { + let value = Literal::u16_unsuffixed(opcode as u16); + quote!(#pattern => #value) + }); + + let since_match_arms = messages.iter().zip(message_match_patterns).map(|(msg, pattern)| { + let since = Literal::u32_unsuffixed(msg.since as u32); + quote!(#pattern => #since) }); let child_match_arms = messages @@ -374,7 +396,10 @@ pub(crate) fn gen_messagegroup( quote!(Ok(#msg_type_qualified)) } else { let fields = msg.args.iter().map(|arg| { - let field_name = Ident::new(&arg.name, Span::call_site()); + let field_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); let some_code_path = match arg.typ { Type::Int => { if let Some(ref enu) = arg.enum_ { @@ -420,7 +445,7 @@ pub(crate) fn gen_messagegroup( } Type::Fd => quote!(val), Type::Object => { - let map_lookup = quote!(map.get(val).ok_or(())?); + let map_lookup = quote!(map.get(val).ok_or(())?.into()); if arg.allow_null { quote!(if val == 0 { None } else { Some(#map_lookup) }) } else { @@ -487,16 +512,21 @@ pub(crate) fn gen_messagegroup( let pattern = if msg.args.is_empty() { msg_type_qualified } else { - let fields = msg - .args - .iter() - .map(|arg| Ident::new(&arg.name, Span::call_site())); + let fields = msg.args.iter().map(|arg| { + Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ) + }); quote!(#msg_type_qualified { #(#fields),* }) }; let opcode_value = Literal::u16_unsuffixed(opcode as u16); let args_values = msg.args.iter().map(|arg| { - let arg_ident = Ident::new(&arg.name, Span::call_site()); + let arg_ident = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); match arg.typ { Type::Int => { if arg.enum_.is_some() { @@ -540,22 +570,22 @@ pub(crate) fn gen_messagegroup( Type::Fd => quote!(Argument::Fd(#arg_ident)), Type::NewId => { if arg.interface.is_some() { - quote!(Argument::NewId(#arg_ident.id())) + quote!(Argument::NewId(#arg_ident.as_ref().id())) } else { quote! { Argument::Str(unsafe { ::std::ffi::CString::from_vec_unchecked(#arg_ident.0.into()) }), Argument::Uint(#arg_ident.1), - Argument::NewId(#arg_ident.2.id()) + Argument::NewId(#arg_ident.2.as_ref().id()) } } } Type::Object => { if arg.allow_null { - quote!(Argument::Object(#arg_ident.map(|o| o.id()).unwrap_or(0))) + quote!(Argument::Object(#arg_ident.map(|o| o.as_ref().id()).unwrap_or(0))) } else { - quote!(Argument::Object(#arg_ident.id())) + quote!(Argument::Object(#arg_ident.as_ref().id())) } } Type::Destructor => panic!("An argument cannot have type Destructor"), @@ -573,6 +603,7 @@ pub(crate) fn gen_messagegroup( quote! { match self { + #name::__nonexhaustive => unreachable!(), #(#match_arms,)* } } @@ -581,6 +612,7 @@ pub(crate) fn gen_messagegroup( quote! { pub enum #name { #(#variants,)* + #[doc(hidden)] __nonexhaustive, } impl super::MessageGroup for #name { @@ -592,16 +624,25 @@ pub(crate) fn gen_messagegroup( fn is_destructor(&self) -> bool { match *self { + #name::__nonexhaustive => unreachable!(), #(#is_destructor_match_arms,)* } } fn opcode(&self) -> u16 { match *self { + #name::__nonexhaustive => unreachable!(), #(#opcode_match_arms,)* } } + fn since(&self) -> u32 { + match *self { + #name::__nonexhaustive => unreachable!(), + #(#since_match_arms,)* + } + } + fn child(opcode: u16, version: u32, meta: &Meta) -> Option> { match opcode { #(#child_match_arms,)* @@ -626,11 +667,35 @@ pub(crate) fn gen_interface( low_name: &str, version: u32, addon: Option, + side: Side, ) -> TokenStream { + let object_type = side.object_name(); let version_lit = Literal::u32_unsuffixed(version); quote! { - pub struct #name; + #[derive(Clone, Eq, PartialEq)] + pub struct #name(#object_type<#name>); + + impl AsRef<#object_type<#name>> for #name { + #[inline] + fn as_ref(&self) -> &#object_type { + &self.0 + } + } + + impl From<#object_type<#name>> for #name { + #[inline] + fn from(value: #object_type) -> Self { + #name(value) + } + } + + impl From<#name> for #object_type<#name> { + #[inline] + fn from(value: #name) -> Self { + value.0 + } + } impl Interface for #name { type Request = Request; @@ -643,9 +708,9 @@ pub(crate) fn gen_interface( } } -pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Option<&'a Arg>) { +pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message, side: Side) -> (TokenStream, Option<&'a Arg>) { let mut it = msg.args.iter().filter(|arg| arg.typ == Type::NewId); - let newid = it.next(); + let mut newid = it.next(); assert!( newid.is_none() || it.next().is_none(), "Request {}.{} returns more than one new_id", @@ -653,6 +718,11 @@ pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Op msg.name ); + // Serverside we don't deal with NewId arguments and treat them as objects. + if side == Side::Server { + newid = None; + } + let fn_name = Ident::new( &format!("{}{}", if is_keyword(&msg.name) { "_" } else { "" }, msg.name), Span::call_site(), @@ -663,7 +733,7 @@ pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Op let generics = if let Some(arg) = newid { if arg.interface.is_none() { args.push(quote!(version: u32)); - Some(quote!(T: Interface, F)) + Some(quote!(T: Interface + From>, F)) } else { Some(quote!(F)) } @@ -675,16 +745,20 @@ pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Op let arg_type_inner = if let Some(ref name) = arg.enum_ { dotted_to_relname(name) } else { - match arg.typ { + let mut typ = arg.typ; + if typ == Type::NewId && side == Side::Server { + typ = Type::Object; + } + match typ { Type::Object => arg .interface .as_ref() .map(|iface| { let iface_mod = Ident::new(iface, Span::call_site()); let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site()); - quote!(&Proxy) + quote!(&super::#iface_mod::#iface_type) }) - .unwrap_or(quote!(&Proxy)), + .unwrap_or(quote!(&super::AnonymousObject)), Type::NewId => { // client-side, the return-type handles that return None; @@ -718,17 +792,17 @@ pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Op let iface_type = Ident::new(&snake_to_camel(&iface), Span::call_site()); ( - quote!(Result, ()>), + quote!(Result), Some(quote! { where F: FnOnce( NewProxy, - ) -> Proxy + ) -> super::#iface_mod::#iface_type }), ) } None => ( - quote!(Result, ()>), - Some(quote!(where F: FnOnce(NewProxy) -> Proxy)), + quote!(Result), + Some(quote!(where F: FnOnce(NewProxy) -> T)), ), } } else { @@ -736,14 +810,22 @@ pub fn method_prototype<'a>(iname: &Ident, msg: &'a Message) -> (TokenStream, Op }; let prototype = quote! { - fn #fn_name#(<#generics>)*(&self, #(#args),*) -> #return_type #where_bounds + pub fn #fn_name#(<#generics>)*(&self, #(#args),*) -> #return_type #where_bounds }; (prototype, newid) } -pub(crate) fn gen_client_methods(name: &Ident, messages: &[Message]) -> TokenStream { - let methods = messages.iter().map(|msg| { +pub(crate) fn gen_object_methods(name: &Ident, messages: &[Message], side: Side) -> TokenStream { + let outgoing_message_type = Ident::new( + match side { + Side::Client => "Request", + Side::Server => "Event", + }, + Span::call_site(), + ); + + let method_impls = messages.iter().map(|msg| { let mut docs = String::new(); if let Some((ref short, ref long)) = msg.description { docs += &format!("{}\n\n{}\n", short, long); @@ -756,29 +838,28 @@ pub(crate) fn gen_client_methods(name: &Ident, messages: &[Message]) -> TokenStr } let doc_attr = to_doc_attr(&docs); - let (proto, _) = method_prototype(name, &msg); - quote! { - #doc_attr - #proto; - } - }); - - let method_impls = messages.iter().map(|msg| { let msg_name = Ident::new(&snake_to_camel(&msg.name), Span::call_site()); - let (proto, return_type) = method_prototype(name, &msg); + let (proto, return_type) = method_prototype(name, &msg, side); let msg_init = if msg.args.is_empty() { TokenStream::new() } else { let args = msg.args.iter().map(|arg| { - let arg_name = Ident::new(&arg.name, Span::call_site()); - let arg_value = match arg.typ { + let arg_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); + let mut typ = arg.typ; + if typ == Type::NewId && side == Side::Server { + typ = Type::Object; + } + let arg_value = match typ { Type::NewId => { if arg.interface.is_some() { - quote!(self.child_placeholder()) + quote!(self.0.child_placeholder()) } else { - quote!((T::NAME.into(), version, self.child_placeholder())) + quote!((T::NAME.into(), version, self.0.child_placeholder())) } } Type::Object => { @@ -799,29 +880,194 @@ pub(crate) fn gen_client_methods(name: &Ident, messages: &[Message]) -> TokenStr let send_stmt = match return_type { Some(ret_type) if ret_type.interface.is_none() => { - quote!(self.send_constructor(msg, implementor, Some(version))) + quote!(self.0.send_constructor(msg, implementor, Some(version))) } - Some(_) => quote!(self.send_constructor(msg, implementor, None)), + Some(_) => quote!(self.0.send_constructor(msg, implementor, None)), None => quote! { - self.send(msg); + self.0.send(msg); }, }; quote! { + #doc_attr #proto { - let msg = Request::#msg_name #msg_init; + let msg = #outgoing_message_type::#msg_name #msg_init; #send_stmt } } }); quote! { - pub trait RequestsTrait { - #(#methods)* - } - - impl RequestsTrait for Proxy<#name> { + impl #name { #(#method_impls)* } } } + +fn event_method_prototype(name: &Ident, msg: &Message, side: Side) -> TokenStream { + let method_name = Ident::new( + &format!("{}{}", if is_keyword(&msg.name) { "_" } else { "" }, msg.name), + Span::call_site(), + ); + + let method_args = msg.args.iter().map(|arg| { + let arg_name = Ident::new( + &format!( + "{}{}", + if is_keyword(&arg.name) || arg.name == "object" { + "_" + } else { + "" + }, + arg.name + ), + Span::call_site(), + ); + + let arg_type_inner = if let Some(ref enu) = arg.enum_ { + dotted_to_relname(enu) + } else { + match arg.typ { + Type::Uint => quote!(u32), + Type::Int => quote!(i32), + Type::Fixed => quote!(f64), + Type::String => quote!(String), + Type::Array => quote!(Vec), + Type::Fd => quote!(::std::os::unix::io::RawFd), + Type::Object => { + if let Some(ref iface) = arg.interface { + let iface_mod = Ident::new(&iface, Span::call_site()); + let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site()); + quote!(super::#iface_mod::#iface_type) + } else { + quote!(AnonymousObject) + } + } + Type::NewId => { + let object_name = Ident::new(&format!("New{}", side.object_name()), Span::call_site()); + + if let Some(ref iface) = arg.interface { + let iface_mod = Ident::new(&iface, Span::call_site()); + let iface_type = Ident::new(&snake_to_camel(iface), Span::call_site()); + quote!(#object_name) + } else { + // bind-like function + quote!((String, u32, #object_name)) + } + } + Type::Destructor => panic!("An argument cannot have type \"destructor\"."), + } + }; + + let field_type = if arg.allow_null { + quote!(Option<#arg_type_inner>) + } else { + arg_type_inner.into_token_stream() + }; + + quote! { + #arg_name: #field_type + } + }); + + quote! { + fn #method_name(&mut self, object: #name, #(#method_args),*) {} + } +} + +pub(crate) fn gen_event_handler_trait(iname: &Ident, messages: &[Message], side: Side) -> TokenStream { + let methods = messages.iter().map(|msg| { + let mut docs = String::new(); + if let Some((ref short, ref long)) = msg.description { + docs += &format!("{}\n\n{}\n", short, long); + } + if let Some(Type::Destructor) = msg.typ { + docs += "\nThis is a destructor, you cannot send requests to this object any longer once this method is called."; + } + if msg.since > 1 { + docs += &format!("\nOnly available since version {} of the interface.", msg.since); + } + + let doc_attr = to_doc_attr(&docs); + let proto = event_method_prototype(iname, &msg, side); + + quote! { + #doc_attr + #proto + } + }); + + let method_patterns = messages.iter().map(|msg| { + let msg_name = Ident::new(&snake_to_camel(&msg.name), Span::call_site()); + + let method_name = Ident::new( + &format!("{}{}", if is_keyword(&msg.name) { "_" } else { "" }, msg.name), + Span::call_site(), + ); + + let arg_names = msg + .args + .iter() + .map(|arg| { + let arg_name = Ident::new( + &format!("{}{}", if is_keyword(&arg.name) { "_" } else { "" }, arg.name), + Span::call_site(), + ); + + quote! { + #arg_name + } + }) + .collect::>(); + + let arg_names_2 = arg_names.clone(); + + match side { + Side::Client => quote! { + Event::#msg_name { #(#arg_names),* } => { + __handler.#method_name(__object, #(#arg_names_2),*) + } + }, + Side::Server => quote! { + Request::#msg_name { #(#arg_names),* } => { + __handler.#method_name(__object, #(#arg_names_2),*) + } + }, + } + }); + + match side { + Side::Client => quote! { + /// An interface for handling events. + pub trait EventHandler { + #(#methods)* + } + + impl HandledBy for #iname { + #[inline] + fn handle(__handler: &mut T, event: Event, __object: Self) { + match event { + #(#method_patterns)* + Event::__nonexhaustive => unreachable!(), + } + } + } + }, + Side::Server => quote! { + /// An interface for handling requests. + pub trait RequestHandler { + #(#methods)* + } + + impl HandledBy for #iname { + #[inline] + fn handle(__handler: &mut T, request: Request, __object: Self) { + match request { + #(#method_patterns)* + Request::__nonexhaustive => unreachable!(), + } + } + } + }, + } +} diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/lib.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/lib.rs similarity index 51% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/lib.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/lib.rs index 8e12c56..c0afd90 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/lib.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/lib.rs @@ -10,9 +10,8 @@ //! //! ## How to use this crate //! -//! This crate is to be used in a build script. It provides you two -//! functions, `generate_c_code` and `generate_c_interfaces`. They'll -//! allow you to generate the code to use with the `wayland_client` or +//! This crate is to be used in a build script. It provides the function `generate_code`. +//! It'll allow you to generate the code to use with the `wayland_client` or //! `wayland_server` crates for any XML wayland protocol file (NB: you don't //! need to do it for the core protocol, which is already included in both crates). //! @@ -30,7 +29,7 @@ //! use std::env::var; //! use std::path::Path; //! -//! use wayland_scanner::{Side, generate_c_code, generate_c_interfaces}; +//! use wayland_scanner::{Side, generate_code}; //! //! fn main() { //! // Location of the xml file, relative to the `Cargo.toml` @@ -40,17 +39,11 @@ //! let out_dir_str = var("OUT_DIR").unwrap(); //! let out_dir = Path::new(&out_dir_str); //! -//! generate_c_code( +//! generate_code( //! protocol_file, //! out_dir.join("my_protocol_api.rs"), //! Side::Client, // Replace by `Side::Server` for server-side code //! ); -//! -//! // interfaces are the same for client and server -//! generate_c_interfaces( -//! protocol_file, -//! out_dir.join("my_protocol_interfaces.rs") -//! ); //! } //! ``` //! @@ -76,12 +69,6 @@ //! #![allow(dead_code,non_camel_case_types,unused_unsafe,unused_variables)] //! #![allow(non_upper_case_globals,non_snake_case,unused_imports)] //! -//! pub mod interfaces { -//! // include the interfaces, they just need to be accessible to the generated code -//! // so this module is `pub` so that it can be imported by the other one. -//! include!(concat!(env!("OUT_DIR"), "/my_protocol_interfaces.rs")); -//! } -//! //! pub mod client { //! // If you protocol interacts with objects from other protocols, you'll need to import //! // their modules, like so: @@ -109,76 +96,17 @@ mod c_interface_gen; mod common_gen; mod parse; mod protocol; -mod rust_code_gen; mod side; mod util; pub use side::Side; fn load_xml>(prot: P) -> protocol::Protocol { - let pfile = File::open(prot.as_ref()).expect(&format!( - "Unable to open protocol file `{}`.", - prot.as_ref().display() - )); + let pfile = File::open(prot.as_ref()) + .unwrap_or_else(|_| panic!("Unable to open protocol file `{}`.", prot.as_ref().display())); parse::parse_stream(pfile) } -/// Generate the interfaces for a protocol -/// -/// See this crate's toplevel documentation for details. -/// -/// Args: -/// -/// - `protocol`: a path to the XML file describing the protocol, absolute or relative to -/// the build script using this function. -/// - `target`: the path of the file to store this interfaces in. -pub fn generate_c_interfaces, P2: AsRef>(protocol: P1, target: P2) { - let protocol = load_xml(protocol); - - { - let mut out = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(&target) - .unwrap(); - write!(&mut out, "{}", c_interface_gen::generate_interfaces(protocol)).unwrap(); - } - - let _ = Command::new("rustfmt").arg(target.as_ref()).status(); -} - -/// Generate the code for a protocol using the Rust implementation -/// -/// See this crate toplevel documentation for details. -/// -/// Args: -/// -/// - `protocol`: a path to the XML file describing the protocol, absolute or relative to -/// the build script using this function. -/// - `target`: the path of the file to store the code in. -/// - `side`: the side (client or server) to generate code for. -pub fn generate_rust_code, P2: AsRef>(prot: P1, target: P2, side: Side) { - let protocol = load_xml(prot); - - { - let mut out = OpenOptions::new() - .write(true) - .truncate(true) - .create(true) - .open(&target) - .unwrap(); - let output = match side { - Side::Client => rust_code_gen::generate_protocol_client(protocol), - Side::Server => rust_code_gen::generate_protocol_server(protocol), - }; - - write!(&mut out, "{}", output).unwrap(); - } - - let _ = Command::new("rustfmt").arg(target.as_ref()).status(); -} - /// Generate the code for a protocol using the C system libs /// /// See this crate toplevel documentation for details. @@ -189,8 +117,30 @@ pub fn generate_rust_code, P2: AsRef>(prot: P1, target: P2 /// the build script using this function. /// - `target`: the path of the file to store the code in. /// - `side`: the side (client or server) to generate code for. -pub fn generate_c_code, P2: AsRef>(prot: P1, target: P2, side: Side) { - let protocol = load_xml(prot); +pub fn generate_code, P2: AsRef>(prot: P1, target: P2, side: Side) { + generate_code_with_destructor_events(prot, target, side, &[]); +} + +/// Generate the code for a protocol with aditionnal destructor events +/// +/// Same as `generate_code`, but allows you to additionnaly specify some events +/// (in the format `("interface_name", "event_name")`) as being destructor, as this +/// information is not encoded in the protocol files. +pub fn generate_code_with_destructor_events, P2: AsRef>( + prot: P1, + target: P2, + side: Side, + events: &[(&str, &str)], +) { + let mut protocol = load_xml(prot); + + for interface in &mut protocol.interfaces { + for event in &mut interface.events { + if events.contains(&(&interface.name, &event.name)) { + event.typ = Some(::protocol::Type::Destructor); + } + } + } { let mut out = OpenOptions::new() @@ -211,20 +161,7 @@ pub fn generate_c_code, P2: AsRef>(prot: P1, target: P2, s let _ = Command::new("rustfmt").arg(target.as_ref()).status(); } -/// Generate the interfaces for a protocol from/to IO streams -/// -/// Like `generate_c_interfaces`, but takes IO Streams directly rather than filenames -/// -/// Args: -/// -/// - `protocol`: an object `Read`-able containing the XML protocol file -/// - `target`: a `Write`-able object to which the generated code will be outputted to -pub fn generate_c_interfaces_streams(protocol: P1, target: &mut P2) { - let protocol = parse::parse_stream(protocol); - write!(target, "{}", c_interface_gen::generate_interfaces(protocol)).unwrap(); -} - -/// Generate the code for a protocol from/to IO streams using the rust implementation +/// Generate the code for a protocol from/to IO streams /// /// Like `generate_code`, but takes IO Streams directly rather than filenames /// @@ -233,27 +170,31 @@ pub fn generate_c_interfaces_streams(protocol: P1, target: /// - `protocol`: an object `Read`-able containing the XML protocol file /// - `target`: a `Write`-able object to which the generated code will be outputted to /// - `side`: the side (client or server) to generate code for. -pub fn generate_rust_code_streams(protocol: P1, target: &mut P2, side: Side) { - let protocol = parse::parse_stream(protocol); - let output = match side { - Side::Client => rust_code_gen::generate_protocol_client(protocol), - Side::Server => rust_code_gen::generate_protocol_server(protocol), - }; - - write!(target, "{}", output).unwrap(); +pub fn generate_code_streams(protocol: P1, target: &mut P2, side: Side) { + generate_code_streams_with_destructor_events(protocol, target, side, &[]) } -/// Generate the code for a protocol from/to IO streams using the C system libs +/// Generate the code for a protocol from/to IO streams with aditionnal destructor events /// -/// Like `generate_code`, but takes IO Streams directly rather than filenames -/// -/// Args: -/// -/// - `protocol`: an object `Read`-able containing the XML protocol file -/// - `target`: a `Write`-able object to which the generated code will be outputted to -/// - `side`: the side (client or server) to generate code for. -pub fn generate_c_code_streams(protocol: P1, target: &mut P2, side: Side) { - let protocol = parse::parse_stream(protocol); +/// Same as `generate_code_streams`, but allows you to additionnaly specify some events +/// (in the format `("interface_name", "event_name")`) as being destructor, as this +/// information is not encoded in the protocol files. +pub fn generate_code_streams_with_destructor_events( + protocol: P1, + target: &mut P2, + side: Side, + events: &[(&str, &str)], +) { + let mut protocol = parse::parse_stream(protocol); + + for interface in &mut protocol.interfaces { + for event in &mut interface.events { + if events.contains(&(&interface.name, &event.name)) { + event.typ = Some(::protocol::Type::Destructor); + } + } + } + let output = match side { Side::Client => c_code_gen::generate_protocol_client(protocol), Side::Server => c_code_gen::generate_protocol_server(protocol), diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/parse.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/parse.rs similarity index 92% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/parse.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/parse.rs index 1b38356..ebcd70d 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/parse.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/parse.rs @@ -25,23 +25,7 @@ macro_rules! extract_end_tag( pub fn parse_stream(stream: S) -> Protocol { let mut reader = EventReader::new_with_config(stream, ParserConfig::new().trim_whitespace(true)); reader.next().expect("Could not read from event reader"); - let mut protocol = parse_protocol(reader); - - // yay, hardcoding things - if protocol.name == "wayland" { - // wl_callback has actually a destructor *event*, but the wayland specification - // format does not handle this. - // Luckily, wayland-scanner does, so we inject it - for interface in &mut protocol.interfaces { - if interface.name == "wl_callback" { - let done_event = &mut interface.events[0]; - assert!(done_event.name == "done"); - done_event.typ = Some(Type::Destructor); - } - } - } - - protocol + parse_protocol(reader) } fn parse_protocol(mut reader: EventReader) -> Protocol { @@ -124,9 +108,8 @@ fn parse_interface(reader: &mut EventReader, attrs: Vec(reader: &mut EventReader, attrs: Vec) -> (String, String) { let mut summary = String::new(); for attr in attrs { - match &attr.name.local_name[..] { - "summary" => summary = attr.value.split_whitespace().collect::>().join(" "), - _ => {} + if &attr.name.local_name[..] == "summary" { + summary = attr.value.split_whitespace().collect::>().join(" "); } } diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/protocol.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/protocol.rs similarity index 94% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/protocol.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/protocol.rs index c81eacd..e2ba96b 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/protocol.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/protocol.rs @@ -46,7 +46,7 @@ impl Interface { pub struct Message { pub name: String, pub typ: Option, - pub since: u16, + pub since: u32, pub description: Option<(String, String)>, pub args: Vec, pub type_index: usize, @@ -152,15 +152,15 @@ pub enum Type { } impl Type { - pub fn nullable(&self) -> bool { - match *self { + pub fn nullable(self) -> bool { + match self { Type::String | Type::Object | Type::NewId | Type::Array => true, _ => false, } } - pub fn rust_type(&self) -> TokenStream { - match *self { + pub fn rust_type(self) -> TokenStream { + match self { Type::Int => quote!(i32), Type::Uint => quote!(u32), Type::Fixed => quote!(f64), @@ -172,8 +172,8 @@ impl Type { } } - pub fn common_type(&self) -> TokenStream { - match *self { + pub fn common_type(self) -> TokenStream { + match self { Type::Int => quote!(Int), Type::Uint => quote!(Uint), Type::Fixed => quote!(Fixed), diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/side.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/side.rs similarity index 87% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/side.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/side.rs index c8ea7b5..2231c65 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/side.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/side.rs @@ -15,9 +15,9 @@ pub enum Side { } impl Side { - pub(crate) fn object_name(&self) -> Ident { + pub(crate) fn object_name(self) -> Ident { Ident::new( - match *self { + match self { Client => "Proxy", Server => "Resource", }, diff --git a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/util.rs b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/util.rs similarity index 84% rename from third_party/cargo/vendor/wayland-scanner-0.21.13/src/util.rs rename to third_party/cargo/vendor/wayland-scanner-0.23.6/src/util.rs index cb7bfcc..cc4b1b5 100644 --- a/third_party/cargo/vendor/wayland-scanner-0.21.13/src/util.rs +++ b/third_party/cargo/vendor/wayland-scanner-0.23.6/src/util.rs @@ -12,13 +12,20 @@ pub fn is_keyword(txt: &str) -> bool { | "let" | "loop" | "macro" | "match" | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub" | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct" | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" | "virtual" - | "where" | "while" | "yield" => true, + | "where" | "while" | "yield" | "__handler" | "__object" => true, + _ => false, + } +} + +pub fn is_camel_keyword(txt: &str) -> bool { + match txt { + "Self" => true, _ => false, } } pub fn snake_to_camel(input: &str) -> String { - input + let result = input .split('_') .flat_map(|s| { let mut first = true; @@ -31,7 +38,13 @@ pub fn snake_to_camel(input: &str) -> String { } }) }) - .collect() + .collect::(); + + if is_camel_keyword(&result) { + format!("_{}", &result) + } else { + result + } } pub fn dotted_to_relname(input: &str) -> TokenStream { diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/.cargo-checksum.json b/third_party/cargo/vendor/wayland-sys-0.21.13/.cargo-checksum.json deleted file mode 100644 index fbd7b4c..0000000 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"7cddc896d877462c39607c425bb316cf81b82a399220d1a588d8aa19f8b4274c","src/client.rs":"7dbbf4fb912bbec1c10432477481090d5a1b9ac9ebe9fa3b81c72d241242e2aa","src/common.rs":"774f90ec31abc6e068fe35d97a259025d55f565988a7f1f2d12c13ef0ae144ed","src/cursor.rs":"ceb17c70bda7afa6ab3c9bfcde9bfcea40428349fee8c6320fadf5ee06c5ebae","src/egl.rs":"97d58a5d7fbe31ef8f9db1149e20c60182852eb76568837a96147b5dc0ed9146","src/lib.rs":"1fed396945858ed84b56800b4dc3aee2ff2d3036d5bfc336becb05ce8d991e1f","src/server.rs":"7021ed5a52c6ddb23860fcf535c31fbd27907269df928bf90eb60bc24b757999"},"package":"520ab0fd578017a0ee2206623ba9ef4afe5e8f23ca7b42f6acfba2f4e66b1628"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-sys-0.23.6/.cargo-checksum.json b/third_party/cargo/vendor/wayland-sys-0.23.6/.cargo-checksum.json new file mode 100644 index 0000000..0397f87 --- /dev/null +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"12fdccbc58843615062c30fb3b08594b0d4fe98f47fd39fc50daa7d0d4fa9af7","src/client.rs":"6cc3f6002632a0fca3c2040b2c4f04d3f50da08d77b004c58e10f23b35418524","src/common.rs":"083fd5add5ec75306b27648aa02cf5adffda4669f464288fcd9369e296f8d9f8","src/cursor.rs":"ceb17c70bda7afa6ab3c9bfcde9bfcea40428349fee8c6320fadf5ee06c5ebae","src/egl.rs":"97d58a5d7fbe31ef8f9db1149e20c60182852eb76568837a96147b5dc0ed9146","src/lib.rs":"64105172e0ab8efa32a7863a5d8618686e85b7aa09b0476b7a628736b56cba81","src/server.rs":"55035701045608a383a16c91fc0c957a989c24a863268211812e81792db60991"},"package":"d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4"} \ No newline at end of file diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/BUILD b/third_party/cargo/vendor/wayland-sys-0.23.6/BUILD similarity index 95% rename from third_party/cargo/vendor/wayland-sys-0.21.13/BUILD rename to third_party/cargo/vendor/wayland-sys-0.23.6/BUILD index c1987d4..2992986 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/BUILD +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/BUILD @@ -37,10 +37,11 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.21.13", + version = "0.23.6", crate_features = [ "client", "cursor", + "dlib", "dlopen", "egl", "lazy_static", diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/Cargo.toml b/third_party/cargo/vendor/wayland-sys-0.23.6/Cargo.toml similarity index 88% rename from third_party/cargo/vendor/wayland-sys-0.21.13/Cargo.toml rename to third_party/cargo/vendor/wayland-sys-0.23.6/Cargo.toml index f0313c3..9fa5219 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/Cargo.toml +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "wayland-sys" -version = "0.21.13" +version = "0.23.6" authors = ["Victor Berger "] description = "FFI bindings to the various libwayland-*.so libraries. You should only need this crate if you are working on custom wayland protocol extensions. Look at the crate wayland-client for usable bindings." documentation = "https://smithay.github.io/wayland-rs/wayland_sys/" @@ -23,6 +23,7 @@ repository = "https://github.com/smithay/wayland-rs" all-features = true [dependencies.dlib] version = "0.4" +optional = true [dependencies.lazy_static] version = "1" @@ -33,10 +34,10 @@ version = "0.2" optional = true [features] -client = [] -cursor = [] +client = ["dlib"] +cursor = ["client"] dlopen = ["dlib/dlopen", "lazy_static"] -egl = [] -server = ["libc"] +egl = ["client"] +server = ["libc", "dlib"] [badges.travis-ci] repository = "Smithay/wayland-rs" diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/client.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/client.rs similarity index 95% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/client.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/client.rs index dfe22cc..5b1ed2a 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/src/client.rs +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/src/client.rs @@ -4,13 +4,16 @@ #![cfg_attr(rustfmt, rustfmt_skip)] +#[cfg(feature = "client")] use super::common::*; +#[cfg(feature = "client")] use std::os::raw::{c_char, c_int, c_void}; pub enum wl_proxy {} pub enum wl_display {} pub enum wl_event_queue {} +#[cfg(feature = "client")] external_library!(WaylandClient, "wayland-client", functions: // display creation and destruction @@ -80,7 +83,7 @@ external_library!(WaylandClient, "wayland-client", fn wl_proxy_marshal(*mut wl_proxy, u32) -> (), ); -#[cfg(feature = "dlopen")] +#[cfg(all(feature = "client", feature = "dlopen"))] lazy_static!( pub static ref WAYLAND_CLIENT_OPTION: Option = { // This is a workaround for Ubuntu 17.04, which doesn't have a bare symlink @@ -111,11 +114,11 @@ lazy_static!( }; ); -#[cfg(not(feature = "dlopen"))] +#[cfg(all(feature = "client", not(feature = "dlopen")))] pub fn is_lib_available() -> bool { true } -#[cfg(feature = "dlopen")] +#[cfg(all(feature = "client", feature = "dlopen"))] pub fn is_lib_available() -> bool { WAYLAND_CLIENT_OPTION.is_some() } diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/common.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/common.rs similarity index 98% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/common.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/common.rs index 7681d9b..eaac9e6 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/src/common.rs +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/src/common.rs @@ -37,7 +37,7 @@ pub struct wl_array { pub type wl_fixed_t = i32; pub fn wl_fixed_to_double(f: wl_fixed_t) -> f64 { - f as f64 / 256. + f64::from(f) / 256. } pub fn wl_fixed_from_double(d: f64) -> wl_fixed_t { diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/cursor.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/cursor.rs similarity index 100% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/cursor.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/cursor.rs diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/egl.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/egl.rs similarity index 100% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/egl.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/egl.rs diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/lib.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/lib.rs similarity index 78% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/lib.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/lib.rs index fbb65bc..9a16bbe 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/src/lib.rs +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/src/lib.rs @@ -1,14 +1,13 @@ //! FFI bindings to the wayland system libraries. //! -//! The names exported by this crate should *not* be used directly, but though -//! the `ffi_dispatch` macro like this: +//! The names exported by this crate should *not* be used directly, but through +//! the `ffi_dispatch` macro, like this: //! //! ```ignore //! ffi_dispatch!(HANDLE_NAME, func_name, arg1, arg2, arg3); //! ``` //! -//! Where `HANDLE_NAME` is the name of the handle generated if the cargo feature -//! `dlopen` is on. +//! Where `HANDLE_NAME` is the name of the handle generated if the cargo feature `dlopen` is on. //! //! For this to work, you must ensure every needed symbol is in scope (aka the static handle //! if `dlopen` is on, the extern function if not). The easiest way to do this is to glob import @@ -27,15 +26,15 @@ //! ``` //! //! Each module except `common` corresponds to a system library. They all define a function named -//! `is_lib_available()` which returns a boolean depending on whether the lib could be loaded. -//! They always return true if the feature `dlopen` is absent, as the lib is then directly linked. - +//! `is_lib_available()` which returns whether the library could be loaded. They always return true +//! if the feature `dlopen` is absent, as we link against the library directly in that case. #![allow(non_camel_case_types)] // If compiling with neither the `client` or `server` feature (non-sensical but // it's what happens when running `cargo test --all` from the workspace root), // dlib isn't actually used. This is not an issue, so don't warn about it. #[allow(unused_imports)] +#[cfg(any(feature = "client", feature = "server"))] #[macro_use] extern crate dlib; @@ -49,21 +48,18 @@ extern crate lazy_static; #[cfg(feature = "server")] extern crate libc; -/// Magic pointer for wayland objects managed by wayland-client or wayland-server +/// Magic static for wayland objects managed by wayland-client or wayland-server /// -/// This static serves no purpose other than existing, and thus providing a stable pointer -/// to something we know what it is. +/// This static serves no purpose other than existing at a stable address. /// /// It is used internally by wayland-client, wayland-server and wayland-scanner to ensure safety -/// regarding to wayland objects that are created by some other library. +/// regarding wayland objects that are created by other libraries. pub static RUST_MANAGED: u8 = 42; pub mod common; -#[cfg(feature = "client")] pub mod client; -#[cfg(feature = "server")] pub mod server; #[cfg(all(feature = "egl", feature = "client"))] diff --git a/third_party/cargo/vendor/wayland-sys-0.21.13/src/server.rs b/third_party/cargo/vendor/wayland-sys-0.23.6/src/server.rs similarity index 96% rename from third_party/cargo/vendor/wayland-sys-0.21.13/src/server.rs rename to third_party/cargo/vendor/wayland-sys-0.23.6/src/server.rs index 753f186..ace036f 100644 --- a/third_party/cargo/vendor/wayland-sys-0.21.13/src/server.rs +++ b/third_party/cargo/vendor/wayland-sys-0.23.6/src/server.rs @@ -5,8 +5,11 @@ #![cfg_attr(rustfmt, rustfmt_skip)] use super::common::*; +#[cfg(feature = "server")] use libc::{gid_t, pid_t, uid_t}; -use std::os::raw::{c_char, c_int, c_void}; +#[cfg(feature = "server")] +use std::os::raw::c_char; +use std::os::raw::{c_int, c_void}; pub enum wl_client {} pub enum wl_display {} @@ -36,6 +39,7 @@ pub struct wl_signal { pub listener_list: wl_list, } +#[cfg(feature = "server")] external_library!(WaylandServer, "wayland-server", functions: // wl_client @@ -138,7 +142,7 @@ external_library!(WaylandServer, "wayland-server", fn wl_resource_post_error(*mut wl_resource, u32, *const c_char) -> (), ); -#[cfg(feature = "dlopen")] +#[cfg(all(feature = "server", feature = "dlopen"))] lazy_static!( pub static ref WAYLAND_SERVER_OPTION: Option = { // This is a workaround for Ubuntu 17.04, which doesn't have a bare symlink @@ -169,16 +173,18 @@ lazy_static!( }; ); -#[cfg(not(feature = "dlopen"))] +#[cfg(all(feature = "server", not(feature = "dlopen")))] pub fn is_lib_available() -> bool { true } -#[cfg(feature = "dlopen")] +#[cfg(all(feature = "server", feature = "dlopen"))] pub fn is_lib_available() -> bool { WAYLAND_SERVER_OPTION.is_some() } +#[cfg(feature = "server")] pub mod signal { + #![cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))] #[cfg(not(feature = "dlopen"))] use super::{wl_list_init, wl_list_insert}; use super::{wl_listener, wl_notify_func_t, wl_signal}; @@ -191,7 +197,7 @@ pub mod signal { // TODO: Is this really not UB ? macro_rules! offset_of( ($ty:ty, $field:ident) => { - &(*(0 as *const $ty)).$field as *const _ as usize + &(*(ptr::null() as *const $ty)).$field as *const _ as usize } ); diff --git a/third_party/cargo/vendor/winapi-0.2.8/.cargo-checksum.json b/third_party/cargo/vendor/winapi-0.2.8/.cargo-checksum.json new file mode 100644 index 0000000..8723902 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"d15a0464554e57323507a2ff34925a2c592f3dffec9beb092c7ce985440f5bda","LICENSE.md":"fd232cfaeeff018cd3b9f22e0279b1c2237742999277596638800e967f6e4a29","src/activation.rs":"0e25834dfecd59391e2ecfdaa2e01bb5ac4d181778b47d0b9f67c56a6b2bd75f","src/audioclient.rs":"8c645d4ddb171620a527bcc14fa2904ff9aeb529262e68a0a9957d2ed77118be","src/audiosessiontypes.rs":"ba8cd1950cdab112861208ac1ecc35e656cbbe36e60c31315e547cfe47707685","src/basetsd.rs":"7b879d3164d5e6ec1b94d18a6b58f74a7f4e62fc279df32126e76c4f3138239d","src/bcrypt.rs":"05fe44190a37dd744bff8fc682f25a47c5f4239d417b213d18542aaa19b08b06","src/cfg.rs":"057ace203f04f8c09b6f68fefba7d3eb6644c46f2e44ca8f1364a8bc3bdd4970","src/cfgmgr32.rs":"714289f058283fc89fc79bbd4932bdbc0e9a88edd62a1787aac82c338f2dfb45","src/combaseapi.rs":"45458b1e0d918b237afd7e9581e2714b58ee009a91bbec45827694d1159a2e8b","src/commctrl.rs":"c0173aabd50f34a85c2523876fa0191d052d1d0c157f95ed228d98508806cc7d","src/commdlg.rs":"e75f64491eea54f651884eb3cc5353588c7fe54b086b43557d6d4917abbf95cd","src/corsym.rs":"301f937c7cb394675b2127a24595beef261d269d8f7cb45d6b4ac21a063985e3","src/d2d1.rs":"e7aa08883d85e2631f5327541e644b650ad009095daadef606bb06d9ac99afd3","src/d2dbasetypes.rs":"5a26048c997a580d8bb2a3512f1cb20dba411da99ffd6b23f4b0615ab9378058","src/d3d10shader.rs":"d6edf923fa8442be35b7f4ebebcd2e4bec4c3842ed5aee4bfd05c2de11edc4e0","src/d3d11.rs":"3f2f681357730df7ea954fb78903f0f0ad0bb3b577727307e751fd9598a4e837","src/d3d11shader.rs":"29612cc75ba238e2cd691fdcc01be9c79ca12b046e207d3cbfc5af23f04c4cb9","src/d3d12.rs":"906e512385e78756fe84f9a9622c510ce5a6daeb121127cf93f11af0f2fa3763","src/d3d12sdklayers.rs":"b50edb48a1c51bc7e3bf7176733c3dad4eb45a4e9747096e3b5a723052e130c8","src/d3d12shader.rs":"ff58932ef32c108348e41864f09ac6f909d641cac4f94c3e4f6c3dc4e5916521","src/d3d9.rs":"e01614130a4d68bb6e2a23f62ffb4d5016381e9026f8477aaca64851c8dcad53","src/d3d9caps.rs":"d4bcf91b7ae307388c91c19eacdb808506faea184b03178feee5c47959211b7b","src/d3d9types.rs":"1e10aae6297bc8dc083b111da496313ff19dcb9b88450e2637f8e98c0401519c","src/d3dcommon.rs":"f841b2e4df6dfccb9eb1955add24689db7b173780ec25e99b89097140a012152","src/d3dcompiler.rs":"02269410bd7f83f49391f852320ca0d76fd8d907ed22c68a003af65b3f5ab54a","src/dbghelp.rs":"c0ea5bcd04f414a696cd876439a7c4d6ee63627f4662705d189fd6e0412622f8","src/dcommon.rs":"8889ca66e2f89f1c275e5d6b7d6b203e7f25b4e7a262689b2ec6f04b9d1b5ae8","src/devpropdef.rs":"74948513ed623d3bdf1ea3fbf1f540b3e9e46efb9c1674ecccfe7f2fae5792f2","src/docobj.rs":"43e214d9d0c436a88ed2c620b8386e58e4d549ba9c8be51bf52291caf95e225d","src/dpapi.rs":"d44a1a6c9e52b34e8e87df1079b97081c646f07d0eee51f0d0cf66ae1c6fd58a","src/dsgetdc.rs":"5911c35ef3d80a5162fdbea6902f9b07033b746ff91bff2657a0971edb07bff2","src/dsound.rs":"53a5532d645e1b7995f0b4a0f0711fc66da8a27b7f8c87ce3d9e0882cfdca07c","src/dsrole.rs":"50b27a8afb11188ce24ab49620fe69ea21658148d8fd6076b8927175db5c1a9e","src/dwmapi.rs":"e65ca961eec0db275e211e04c59a8995c8c13d36ab08dc36ce197d9a4856266f","src/dwrite.rs":"f138d36e8b93778a7866cc755893b4da19cfd6ce42427139589a0bbaa294eb44","src/dxgi.rs":"5b6fcc5c665df1c0c6ed3de5d678a7bade1bb8ab1acbe952b784ce99fc817e53","src/dxgi1_2.rs":"6ba44755d715f2493236103fc5c24d7d45dff2e1fc3690aefbd4eb6c859dbc07","src/dxgi1_3.rs":"1f86a9db5fd45199fcc3ce56423e5fcf0c58df4001e2b50c5586d38ab820b78f","src/dxgi1_4.rs":"c578e6fcb82d535b20fc10232b75a7b9512d068919cc1e3f1c7cf55f3eb46460","src/dxgiformat.rs":"2e73df34f480b6ef3b5e21de0a520dacec91b00772e42786568fd162ca5e9aa6","src/dxgitype.rs":"204b8dae38c13a1dd8cd2ce6ca68851f743b416213d6db1cd0d96808bcbf7058","src/errhandlingapi.rs":"a70f9db3dd8ab60aba0daf39f12b527e54e312ca640e0b80d80c93ffdb6913c6","src/excpt.rs":"b07cf9ff0d23dd50c0776d048d0c579e401b7d729635f78998f85d35f33f05a4","src/fileapi.rs":"d31814c612bbd9372abbf6f8455fc2af89ac236c6b1855da10d66545e485ec57","src/gl.rs":"9429708bb97aeecb2c40030460ed0c3415fc0f2335c9513c68afa6157bd9b465","src/guiddef.rs":"86618dcd39c77048c7e453e6e86dafe90358eb7f97144f9672ae09e7b9855729","src/heapapi.rs":"21e420ba7641e507e8f2801d2b0ed25dbcb98e967924d711beb5cbfa8a5785e4","src/hidclass.rs":"a93380d35dc4d45807b10bbd69ee63eb8517b75989b68391685070a2fcfbefa1","src/hidpi.rs":"0b641fc119ac35761fe8e5eaed9a0781e9018598ea269d6cd386dbf5563ab9a0","src/hidsdi.rs":"50abb938ea8d0af90ccdea7ac3de4bc10fe42e34bc6a6d6eb4da1b330727da34","src/hidusage.rs":"44adc029bc89f0d4977b1295b7e998ddabf5283de66e1e33146bda8968d1d98b","src/hstring.rs":"51b3e63e3f1ed48f54c63c3e820e0563fb857b2743529d5f947f718d43425b89","src/http.rs":"ebb8b8db9e786e2683ad8b9a9066ef418df773ae7ce4d75f166cb5321f85f5a0","src/imm.rs":"b9277502f17f4cc6bde4f80f722ec1b976913355edbf162814ccfec2b3b080fd","src/inaddr.rs":"938143669da02c83a31d207be11e2176ed5219edf0e6f8f7a5534a5c6c3ce8d1","src/inspectable.rs":"b01f1814a233a77bf9f25c264747252c0464388c7d9c7302e5bde57502b8139b","src/ksmedia.rs":"acb96b1ea0cf3b5397f9037958093c6b4dbb54c4246516e57b9fed055e8e69c1","src/lib.rs":"8a7840b030f56883f68bdf90a1a04df8be2a5e2698a9ea86c73fac59c9f09b6e","src/libloaderapi.rs":"21a5d17c9f8ac4c006b515979964a8870f30710be4482083f45c6a41a16a36ce","src/lmaccess.rs":"712661c871569513334152bdcdf56c07776c560a22cd5b892a0f38e1957e28db","src/lmcons.rs":"3449aab4399cc36e7d7db551e384d82dfa4204178c4cfb9642f90645687fbc81","src/lmdfs.rs":"c351cdb2d10bf3a7c5ce7400dcdca41a792554e21e75fa9e5378ac18d8d3e4e7","src/lmerrlog.rs":"7937928544d27575e302c5e9c5e6803e9033e1f4d715e7ca29be202276d7d7a6","src/lmjoin.rs":"362cdc71f3f50099b862eff0733b3a57dd0f95cac15943135f794424f651b916","src/lsalookup.rs":"4aef1a95033444181f2b2b9df364ea165b0fdedb396c63e5d12db6b7398a3d5f","src/macros.rs":"5dacc570f226b6f1ad31d76a03675f0d182a3d578846920000fabb7cd92fc7f8","src/memoryapi.rs":"2273b8bfd7fc36dcf654c320826952ad502e8922a84174f8c1f7ed08aa555a04","src/minschannel.rs":"139828de63a0a4476de2bee454f5bca5e8a46cc29f1680339bb2804ee2d17322","src/minwinbase.rs":"6cd387a7f79e1a708bc48b5b27eaeaa7aadf0fff7a5e0a76cda0bdf3fa871863","src/minwindef.rs":"47ba4f2ec7789109ae339170715ed76288ae60ee57a4f06d5cc50a0e6855699f","src/mmdeviceapi.rs":"c8b7f7b6b78488d23ccba2b34e8765eac60ec9f08e19c96b377d957f65b1b6d1","src/mmreg.rs":"1621fad6eaa16d1e5ca95055fd11bf066b777b1343625f9fdc74e4d313d60dea","src/mmsystem.rs":"f6a2bff3bf80af1468de2c2a5f7ff2ced2b625adaf24f08f9b303965ed5ee371","src/mscat.rs":"9226a8e30546c4142e4fcdc716f8a15cc7c8081c9e875ec72ff9e8551f86f9a1","src/mssip.rs":"d7e2b91e358ff4986e700396d04f92aa1671aafada0d4889914a413177c091e1","src/nb30.rs":"dd85d7849111f04d33895835269929dc219e04de4373e91468eb053e3e0a5c52","src/ncrypt.rs":"29f168dcddeaa2cb231a7174cec672be83cca192ffc4632cead4c4a25189fb49","src/ntdef.rs":"3be66042d16a862f0fed8f48406b08c3091fbf92885a44efb7747f4a764d7de7","src/ntsecapi.rs":"dfb2cc7e23e8b20fa5ffd30ccecdb81b62d8ffeb68fdf99f93fb141ff4155afd","src/ntstatus.rs":"de6208f4e119a6405c1726433ea5e47a8b5f46b345f5809e9f580cce88360a79","src/oaidl.rs":"640c911e39888928baf77145cca34c1a768bfd759ec9709f70649a2946cb3246","src/objbase.rs":"7c9edb6a9ea72baddb15a6aec3602b3f9e7b1ce969dd655f440eae0ede1372e2","src/objidl.rs":"2a623b989f2a216edca3bd118eceff41267632839a3fd4410df9a7c126a87b64","src/objidlbase.rs":"3415a0bcd1b5b63ff48e17138ff87dae7c31eaeb323ae81f34b6712efade1d04","src/olectl.rs":"da2014c3d5858c5abff1635e1b8c8223333e7d22d28cac614aac3305a7f04ee4","src/pdh.rs":"eb01459c2acc456ecd204c6716d26027a6c77c2b4a9b698d3c922254fe2cc319","src/playsoundapi.rs":"7efddfc8601de565946c8c93074211c83b20866a1588e36e0518bba9864d0cf0","src/processsnapshot.rs":"df99a56280e6e41c5896341ffa1abe734f6c8662f4d7ea960cb97fb34c5b85d9","src/processthreadsapi.rs":"bf8edf8984ee97bc5054e68d02ec4633b5f15720602ab19c95d78e7d420c9cc8","src/propidl.rs":"88b5f176e4624063cadd8db95db52bf07cff421d73a8cfe319f992a9c99cd315","src/propsys.rs":"05c411639479f88e77383c585117a886f48ea7453260210db9f283e2cafdffbf","src/prsht.rs":"f862538c0010a51a02e5f24b3a44b54ba5993c32400b98a3b0558741ae7473a3","src/psapi.rs":"512523c5f8334c9ad221a73776c0ed2da93d8e2353dc4d2cee951ffa6ea7c163","src/qos.rs":"9ef6183b7c03b5b412f81f38ebb06048ff6266032bc236964dd994f173b82ec4","src/reason.rs":"c92aded3bbea859f110eed73b9b0fb40df6ac4a6ed6431ca69882b46b5ad5229","src/restrictederrorinfo.rs":"b8c53f4ae149ea806028cdafe699390a20202d72028b5f62836bcbf97720d133","src/roapi.rs":"dbbefb19f402a2aece66b500739b0a9e2c4d0133a8bc94d076510d5a67def175","src/roerrorapi.rs":"84a0a71a3f9ce67a577954ee5761cbd97d892eb5e7eb2c381f6bd29d4e1d4af7","src/rpc.rs":"e2293651222edf37f3ad3076adaae9033b25b06bd7b88ed7372585a4ae46c7d9","src/rpcdce.rs":"de77ca3c9b689ffaaf395a6882d3dfc3a1cec181efa6cb6075e605e4462bc3f6","src/sapi.rs":"05dbc1166b836251538c9e52a772fa584a1d0a1ad823e4336ab5e6cfefb96d57","src/schannel.rs":"e48926896227ffae5033bd634a7c71f5359d7a08b7b8c6e94e03864d87a37f8b","src/servprov.rs":"f086b4330162c7da711ea59d7023304a8fa2a53470b54d846ea1c11567703693","src/setupapi.rs":"4959862dd39597cd711022fcefbaf5c75b61410d57d04e9dbec2ddf7a2fa6f31","src/shellapi.rs":"ce3e3e7cd8aefe8068d6c51256827c0c3d51a449e4ab73e7125ea28d44dd6b6d","src/shellscalingapi.rs":"59c162b0215ff4b71b3535b6e142cca8cd99028031f47f0a6efb960c160a8776","src/shlguid.rs":"dcb7a1ada1b1b90f405e6dea8bcf1fc6994725b49a3165b7908670b2c31490e5","src/shlobj.rs":"53ff059ec6123001bed8f007c36e40812f83e4e04bd50b371319d10b4e38c36f","src/shobjidl.rs":"953d6ef4dc2a0d175d7133dc2f41255123ab8f778b22feaebd8ca1fa77356aa7","src/shtypes.rs":"ff785004e819bcfc521ab79327e58f98debab4e40c20412bbecdcee1b2801371","src/spapidef.rs":"9abe751425b6aaac7e4a7ea49f6d8e859f8f73164abd4d69b48e3e224d7de829","src/sql.rs":"004ed353b40bb4bceab55d6e8c33063a8eac992b076e47e6ead8303dbbc5b67f","src/sqltypes.rs":"0c5fa183c9f5b9e16e292de6a9afdf73f554730e651250856148ac04718803b8","src/sspi.rs":"dbd9d544abea4396983867ef4f7fbe2588673cc953dbeb74e7edc46503b16fa0","src/strmif.rs":"168040999cf99843cc1447988e46c56481a7a343ae41ab854db40ef566fa1119","src/subauth.rs":"183dd0df6436e9f0e859d62ca78e8ed42d4c1a5dc0690dcf22d42467fd2e0700","src/synchapi.rs":"cfce677c85377a340cb9307d9ac9eb06ffe9fd5e2ce08ed4a0390729e3a7d717","src/sysinfoapi.rs":"9a5579143263ce20d8c365b9874a0ae90ef28bc3295eab26ba3782efa48b464a","src/threadpoolapi.rs":"57876ea70b86d08663f7916ce076547f17596c26b8bf4dfafbad60e78264ff95","src/timezoneapi.rs":"5ccd80e6d16a858c56e20a7f3c5570e29777dab0fdfc057b6d2fb06463d56eb3","src/tlhelp32.rs":"c96ef7416bceab473463cc4ad98f037aeaac87bb7adf45cc16c281308537e82f","src/unknwnbase.rs":"2708c19491deb7364100025f3bb88a791c219551a65af70a776f8f3c5bf18b05","src/urlhist.rs":"8c8c0d0a613e59f68bf0e8cec061ea2126baa98d1479df4d07c8df5e41b50bc1","src/urlmon.rs":"0652e602ef2f5826360e5eab68bdf4f9365827a012c2c89289c54016ea001b74","src/usb.rs":"7e682ee819b237eabe796e604cff2434c450f724f4c86d919683eb7a5167c343","src/usbspec.rs":"d19671960838eb592cda4cd7c84c6f66cd9484f0904b5a28e1d8fd91e9c2c6af","src/usp10.rs":"baa2c1ef6ca5f064bc55b24f39c0553ede45a87b9183318572916fd4f1c679c6","src/vadefs.rs":"0e2f12fd1c521a943908669b2d10fceea409bac45242ec6e87c0e69706c1b3d0","src/vsbackup.rs":"af71cb851bd7eacde9d3e46a112497baef3ecebb472aae3c76c7faff804d33f9","src/vss.rs":"a626613810a69309b8f50d0a3bd75928d9de771c2287b6242487cb8cd55394a0","src/vsserror.rs":"f06b108d66ea9f06ad15d83b981117ed6a2a9cd218bb3bf53f13b0055acd9b2e","src/vswriter.rs":"8c4f5d27fa0883d187506538136cc610074941bb952afbe0984f7cb7c3c656f7","src/werapi.rs":"a2d692514ff3a61126971c5c2c5a7298c0f822559550a7f14501f8c96d1d951a","src/winbase.rs":"e224c40d827b1f1a9c74643c000f71e87ad18f749810cc611425af325c9472b8","src/wincon.rs":"402c5ebf80aa6ab1002935b7ddca17e8a243d0c714982054395862fe0ae40a04","src/wincred.rs":"e5fa987622dd880151ae190bb45daa666ffae3ae8e2da97407210afe01dd93d6","src/wincrypt.rs":"f7f8743b6a89d3f5e8b07405e43010bb3729aa8a8cf4546cc02705f802947ebc","src/windef.rs":"89fa9f5ab2909a4840f16979ebbc0afa2134abcb1d47cb7435b581f31b227658","src/windowscodecs.rs":"7c63bc4e2d0e7ce60c7bb13b93ef5aa12213f71a46845b6e034a9c224ef3eb3c","src/windowsx.rs":"414a9a841590f88804da3eb9ba55d583372a467cc50ab1ebdd7cfc653ce5f627","src/winerror.rs":"f3882eba4e299acbdedd548feb1ff89de958fb72d665bd6ba013b6a1f7596b52","src/winevt.rs":"64ae96f475ed98da7a84704d53d16caccbac2dbd525de0ef0f65fc58a6775ed1","src/wingdi.rs":"35aa9dd14b4b4c5a227ac3df0d312c19cbaede2d1388c26ad8eb910e80efeafd","src/winhttp.rs":"37769be104a2eb9efa70ffd74c8f38a09d9639cf575a677ad75d941e8d87cd58","src/winioctl.rs":"0f0efe0a41894a325b70428d04aeddec8dd7a87a91489a4e564a248e8498861b","src/winnetwk.rs":"d492c3d14a422f611166d39b895ddc6dd749ebc64a020bf3125af452494f91dd","src/winnls.rs":"90904d6adad70081a620165223fb4a71b64d747596c64d0df7de9511cd0f75c6","src/winnt.rs":"2c51ad0a065006010f1cfe7a3335274304e4747adc63f9798e1ca1f7091154a5","src/winreg.rs":"c687a5c6433daa13793815ef9af8befaedc9635be14eea0c618ad5334952dc31","src/winscard.rs":"78ab1d3ae22e486726740c343a4cc6268ca318de43f4b7d7ba51acbdf1b93936","src/winsmcrd.rs":"62be129c3d4cdea9dd31e769b587f071a94c347c8df71a43bb1eea18d52a60cc","src/winsock2.rs":"21dc0393f37f56c15c59d49a32861fb24c8f28d43ce26b56d958a174a5040a76","src/winspool.rs":"a3bd8e04f2db6118fe529bf52cb856a773cd8b816d197fc8edc8ac942578fd74","src/winstring.rs":"dc535f972d93be2fe067a5ca64edb45b6ad8e4549ecc0ce24486bd94555d5707","src/winsvc.rs":"7999f00b341f3e0e8701ea89f71986a6600650ff8cffdb1292e9f55d47bd0a3e","src/winusb.rs":"0ac355aa879a4aae501db04f1e8859dbef5e33fda9d46a7a12ef25e5524ec396","src/winusbio.rs":"8e2d64832999b59b2ea900396184c36d34cf94c97f31e15916c299213748a3e1","src/winuser.rs":"791bd8625812feccc8ec421489194d635c94cb4c4d754287a0caa54fa8f71c19","src/ws2def.rs":"0a1c7a69e4da8edc0584b0e3fb4ad1fa4aed621510b1bc1b0d104990577c6a38","src/ws2ipdef.rs":"c6a898cf25d187ad83e110af1e2286824868691a60818ecc44e68fa0bbbd4ff6","src/ws2spi.rs":"e63da700de55a317769230319eb9e4ec85cc0ac80b2baa076399367338b7ca0f","src/ws2tcpip.rs":"698084fd5d631a2ef236fe76001e7c44afd9b8958243e4ad4c098ac4beb4b352","src/wtypes.rs":"2689e8f442ccdc0b0e1ec82160a5cc3e80abf95dca82855ec595314062774a14","src/wtypesbase.rs":"f6dc0a8b09f3f003339c5dd366bdddb9dd671894be9dcf4a42058b226d2917a8","src/xinput.rs":"e15cd46bf18977481e22d609f8e0bb5508776902d7fa64477bb5b78596c0f67d"},"package":"167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"} \ No newline at end of file diff --git a/third_party/cargo/vendor/memoffset-0.2.1/BUILD b/third_party/cargo/vendor/winapi-0.2.8/BUILD similarity index 93% rename from third_party/cargo/vendor/memoffset-0.2.1/BUILD rename to third_party/cargo/vendor/winapi-0.2.8/BUILD index 563d580..34c274a 100644 --- a/third_party/cargo/vendor/memoffset-0.2.1/BUILD +++ b/third_party/cargo/vendor/winapi-0.2.8/BUILD @@ -25,7 +25,7 @@ load( rust_library( - name = "memoffset", + name = "winapi", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", @@ -35,7 +35,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.2.1", + version = "0.2.8", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/winapi-0.2.8/Cargo.toml b/third_party/cargo/vendor/winapi-0.2.8/Cargo.toml new file mode 100644 index 0000000..941a659 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/Cargo.toml @@ -0,0 +1,61 @@ +[package] +name = "winapi" +version = "0.2.8" +authors = ["Peter Atashian "] +description = "Types and constants for WinAPI bindings. See README for list of crates providing function bindings." +documentation = "https://retep998.github.io/doc/winapi/" +repository = "https://github.com/retep998/winapi-rs" +readme = "README.md" +keywords = ["windows", "ffi", "win32", "com", "directx"] +license = "MIT" +include = ["src/**/*", "Cargo.toml", "LICENSE.md"] + +[dev-dependencies] +advapi32-sys = { version = "0", path = "lib/advapi32" } +bcrypt-sys = { version = "0", path = "lib/bcrypt" } +comctl32-sys = { version = "0", path = "lib/comctl32" } +comdlg32-sys = { version = "0", path = "lib/comdlg32" } +credui-sys = { version = "0", path = "lib/credui" } +crypt32-sys = { version = "0", path = "lib/crypt32" } +d2d1-sys = { version = "0", path = "lib/d2d1" } +d3d11-sys = { version = "0", path = "lib/d3d11" } +d3d12-sys = { version = "0", path = "lib/d3d12" } +d3d9-sys = { version = "0", path = "lib/d3d9" } +d3dcompiler-sys = { version = "0", path = "lib/d3dcompiler" } +dbghelp-sys = { version = "0", path = "lib/dbghelp" } +dsound-sys = { version = "0", path = "lib/dsound" } +dwmapi-sys = { version = "0", path = "lib/dwmapi" } +dwrite-sys = { version = "0", path = "lib/dwrite" } +dxgi-sys = { version = "0", path = "lib/dxgi" } +dxguid-sys = { version = "0", path = "lib/dxguid" } +gdi32-sys = { version = "0", path = "lib/gdi32" } +hid-sys = { version = "0", path = "lib/hid" } +httpapi-sys = { version = "0", path = "lib/httpapi" } +kernel32-sys = { version = "0", path = "lib/kernel32" } +ktmw32-sys = { version = "0", path = "lib/ktmw32" } +mpr-sys = { version = "0", path = "lib/mpr" } +netapi32-sys = { version = "0", path = "lib/netapi32" } +odbc32-sys = { version = "0", path = "lib/odbc32" } +ole32-sys = { version = "0", path = "lib/ole32" } +oleaut32-sys = { version = "0", path = "lib/oleaut32" } +opengl32-sys = { version = "0", path = "lib/opengl32" } +pdh-sys = { version = "0", path = "lib/pdh" } +psapi-sys = { version = "0", path = "lib/psapi" } +runtimeobject-sys = { version = "0", path = "lib/runtimeobject" } +secur32-sys = { version = "0", path = "lib/secur32" } +setupapi-sys = { version = "0", path = "lib/setupapi" } +shell32-sys = { version = "0", path = "lib/shell32" } +shlwapi-sys = { version = "0", path = "lib/shlwapi" } +user32-sys = { version = "0", path = "lib/user32" } +userenv-sys = { version = "0", path = "lib/userenv" } +usp10-sys = { version = "0", path = "lib/usp10" } +uuid-sys = { version = "0", path = "lib/uuid" } +vssapi-sys = { version = "0", path = "lib/vssapi" } +wevtapi-sys = { version = "0", path = "lib/wevtapi" } +winhttp-sys = { version = "0", path = "lib/winhttp" } +winmm-sys = { version = "0", path = "lib/winmm" } +winscard-sys = { version = "0", path = "lib/winscard" } +winspool-sys = { version = "0", path = "lib/winspool" } +winusb-sys = { version = "0", path = "lib/winusb" } +ws2_32-sys = { version = "0", path = "lib/ws2_32" } +xinput-sys = { version = "0", path = "lib/xinput" } diff --git a/third_party/cargo/vendor/winapi-0.2.8/LICENSE.md b/third_party/cargo/vendor/winapi-0.2.8/LICENSE.md new file mode 100644 index 0000000..60d12ac --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Peter Atashian + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/activation.rs b/third_party/cargo/vendor/winapi-0.2.8/src/activation.rs new file mode 100644 index 0000000..f94f81b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/activation.rs @@ -0,0 +1,5 @@ +RIDL!( +interface IActivationFactory(IActivationFactoryVtbl): IInspectable(IInspectableVtbl) { + fn ActivateInstance(&mut self, instance: *mut *mut ::IInspectable) -> ::HRESULT +} +); \ No newline at end of file diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/audioclient.rs b/third_party/cargo/vendor/winapi-0.2.8/src/audioclient.rs new file mode 100644 index 0000000..5a5ee6a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/audioclient.rs @@ -0,0 +1,71 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//1627 +pub const AUDCLNT_E_NOT_INITIALIZED: ::HRESULT = AUDCLNT_ERR!(0x001); +pub const AUDCLNT_E_ALREADY_INITIALIZED: ::HRESULT = AUDCLNT_ERR!(0x002); +pub const AUDCLNT_E_WRONG_ENDPOINT_TYPE: ::HRESULT = AUDCLNT_ERR!(0x003); +pub const AUDCLNT_E_DEVICE_INVALIDATED: ::HRESULT = AUDCLNT_ERR!(0x004); +pub const AUDCLNT_E_NOT_STOPPED: ::HRESULT = AUDCLNT_ERR!(0x005); +pub const AUDCLNT_E_BUFFER_TOO_LARGE: ::HRESULT = AUDCLNT_ERR!(0x006); +pub const AUDCLNT_E_OUT_OF_ORDER: ::HRESULT = AUDCLNT_ERR!(0x007); +pub const AUDCLNT_E_UNSUPPORTED_FORMAT: ::HRESULT = AUDCLNT_ERR!(0x008); +pub const AUDCLNT_E_INVALID_SIZE: ::HRESULT = AUDCLNT_ERR!(0x009); +pub const AUDCLNT_E_DEVICE_IN_USE: ::HRESULT = AUDCLNT_ERR!(0x00a); +pub const AUDCLNT_E_BUFFER_OPERATION_PENDING: ::HRESULT = AUDCLNT_ERR!(0x00b); +pub const AUDCLNT_E_THREAD_NOT_REGISTERED: ::HRESULT = AUDCLNT_ERR!(0x00c); +pub const AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: ::HRESULT = AUDCLNT_ERR!(0x00e); +pub const AUDCLNT_E_ENDPOINT_CREATE_FAILED: ::HRESULT = AUDCLNT_ERR!(0x00f); +pub const AUDCLNT_E_SERVICE_NOT_RUNNING: ::HRESULT = AUDCLNT_ERR!(0x010); +pub const AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: ::HRESULT = AUDCLNT_ERR!(0x011); +pub const AUDCLNT_E_EXCLUSIVE_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x012); +pub const AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: ::HRESULT = AUDCLNT_ERR!(0x013); +pub const AUDCLNT_E_EVENTHANDLE_NOT_SET: ::HRESULT = AUDCLNT_ERR!(0x014); +pub const AUDCLNT_E_INCORRECT_BUFFER_SIZE: ::HRESULT = AUDCLNT_ERR!(0x015); +pub const AUDCLNT_E_BUFFER_SIZE_ERROR: ::HRESULT = AUDCLNT_ERR!(0x016); +pub const AUDCLNT_E_CPUUSAGE_EXCEEDED: ::HRESULT = AUDCLNT_ERR!(0x017); +pub const AUDCLNT_E_BUFFER_ERROR: ::HRESULT = AUDCLNT_ERR!(0x018); +pub const AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: ::HRESULT = AUDCLNT_ERR!(0x019); +pub const AUDCLNT_E_INVALID_DEVICE_PERIOD: ::HRESULT = AUDCLNT_ERR!(0x020); +pub const AUDCLNT_E_INVALID_STREAM_FLAG: ::HRESULT = AUDCLNT_ERR!(0x021); +pub const AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: ::HRESULT = AUDCLNT_ERR!(0x022); +pub const AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: ::HRESULT = AUDCLNT_ERR!(0x023); +pub const AUDCLNT_E_OFFLOAD_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x024); +pub const AUDCLNT_E_NONOFFLOAD_MODE_ONLY: ::HRESULT = AUDCLNT_ERR!(0x025); +pub const AUDCLNT_E_RESOURCES_INVALIDATED: ::HRESULT = AUDCLNT_ERR!(0x026); +pub const AUDCLNT_E_RAW_MODE_UNSUPPORTED: ::HRESULT = AUDCLNT_ERR!(0x027); +pub const AUDCLNT_S_BUFFER_EMPTY: ::SCODE = AUDCLNT_SUCCESS!(0x001); +pub const AUDCLNT_S_THREAD_ALREADY_REGISTERED: ::SCODE = AUDCLNT_SUCCESS!(0x002); +pub const AUDCLNT_S_POSITION_STALLED: ::SCODE = AUDCLNT_SUCCESS!(0x003); +DEFINE_GUID!(IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4c32, + 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2); +DEFINE_GUID!(IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, + 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2); +RIDL!{interface IAudioClient(IAudioClientVtbl): IUnknown(IUnknownVtbl) { + fn Initialize( + &mut self, ShareMode: ::AUDCLNT_SHAREMODE, StreamFlags: ::DWORD, + hnsBufferDuration: ::REFERENCE_TIME, hnsPeriodicity: ::REFERENCE_TIME, + pFormat: *const ::WAVEFORMATEX, AudioSessionGuid: ::LPCGUID + ) -> ::HRESULT, + fn GetBufferSize(&mut self, pNumBufferFrames: *mut ::UINT32) -> ::HRESULT, + fn GetStreamLatency(&mut self, phnsLatency: *mut ::REFERENCE_TIME) -> ::HRESULT, + fn GetCurrentPadding(&mut self, pNumPaddingFrames: *mut ::UINT32) -> ::HRESULT, + fn IsFormatSupported( + &mut self, ShareMode: ::AUDCLNT_SHAREMODE, pFormat: *const ::WAVEFORMATEX, + ppClosestMatch: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetMixFormat(&mut self, ppDeviceFormat: *mut *mut ::WAVEFORMATEX) -> ::HRESULT, + fn GetDevicePeriod( + &mut self, phnsDefaultDevicePeriod: *mut ::REFERENCE_TIME, + phnsMinimumDevicePeriod: *mut ::REFERENCE_TIME + ) -> ::HRESULT, + fn Start(&mut self) -> ::HRESULT, + fn Stop(&mut self) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn SetEventHandle(&mut self, eventHandle: ::HANDLE) -> ::HRESULT, + fn GetService(&mut self, riid: ::REFIID, ppv: *mut ::LPVOID) -> ::HRESULT +}} +RIDL!{interface IAudioRenderClient(IAudioRenderClientVtbl): IUnknown(IUnknownVtbl) { + fn GetBuffer(&mut self, NumFramesRequested: ::UINT32, ppData: *mut *mut ::BYTE) -> ::HRESULT, + fn ReleaseBuffer(&mut self, NumFramesWritten: ::UINT32, dwFlags: ::DWORD) -> ::HRESULT +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/audiosessiontypes.rs b/third_party/cargo/vendor/winapi-0.2.8/src/audiosessiontypes.rs new file mode 100644 index 0000000..796f17f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/audiosessiontypes.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +ENUM!{enum AUDCLNT_SHAREMODE { + AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_SHAREMODE_EXCLUSIVE, +}} +pub const AUDCLNT_STREAMFLAGS_CROSSPROCESS: ::DWORD = 0x00010000; +pub const AUDCLNT_STREAMFLAGS_LOOPBACK: ::DWORD = 0x00020000; +pub const AUDCLNT_STREAMFLAGS_EVENTCALLBACK: ::DWORD = 0x00040000; +pub const AUDCLNT_STREAMFLAGS_NOPERSIST: ::DWORD = 0x00080000; +pub const AUDCLNT_STREAMFLAGS_RATEADJUST: ::DWORD = 0x00100000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/basetsd.rs b/third_party/cargo/vendor/winapi-0.2.8/src/basetsd.rs new file mode 100644 index 0000000..6bf20fc --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/basetsd.rs @@ -0,0 +1,99 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Type definitions for the basic sized types. +#[cfg(target_arch = "x86")] +pub type POINTER_64_INT = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type POINTER_64_INT = ::__uint64; +pub type INT8 = ::c_schar; +pub type PINT8 = *mut ::c_schar; +pub type INT16 = ::c_short; +pub type PINT16 = *mut ::c_short; +pub type INT32 = ::c_int; +pub type PINT32 = *mut ::c_int; +pub type INT64 = ::__int64; +pub type PINT64 = *mut ::__int64; +pub type UINT8 = ::c_uchar; +pub type PUINT8 = *mut ::c_uchar; +pub type UINT16 = ::c_ushort; +pub type PUINT16 = *mut ::c_ushort; +pub type UINT32 = ::c_uint; +pub type PUINT32 = *mut ::c_uint; +pub type UINT64 = ::__uint64; +pub type PUINT64 = *mut ::__uint64; +pub type LONG32 = ::c_int; +pub type PLONG32 = *mut ::c_int; +pub type ULONG32 = ::c_uint; +pub type PULONG32 = *mut ::c_uint; +pub type DWORD32 = ::c_uint; +pub type PDWORD32 = *mut ::c_uint; +#[cfg(target_arch = "x86")] +pub type INT_PTR = ::c_int; +#[cfg(target_arch = "x86_64")] +pub type INT_PTR = ::__int64; +#[cfg(target_arch = "x86")] +pub type PINT_PTR = *mut ::c_int; +#[cfg(target_arch = "x86_64")] +pub type PINT_PTR = *mut ::__int64; +#[cfg(target_arch = "x86")] +pub type UINT_PTR = ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type UINT_PTR = ::__uint64; +#[cfg(target_arch = "x86")] +pub type PUINT_PTR = *mut ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type PUINT_PTR = *mut ::__uint64; +#[cfg(target_arch = "x86")] +pub type LONG_PTR = ::c_long; +#[cfg(target_arch = "x86_64")] +pub type LONG_PTR = ::__int64; +#[cfg(target_arch = "x86")] +pub type PLONG_PTR = *mut ::c_long; +#[cfg(target_arch = "x86_64")] +pub type PLONG_PTR = *mut ::__int64; +#[cfg(target_arch = "x86")] +pub type ULONG_PTR = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type ULONG_PTR = ::__uint64; +#[cfg(target_arch = "x86")] +pub type PULONG_PTR = *mut ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type PULONG_PTR = *mut ::__uint64; +#[cfg(target_arch = "x86_64")] +pub type SHANDLE_PTR = ::__int64; +#[cfg(target_arch = "x86_64")] +pub type HANDLE_PTR = ::__uint64; +#[cfg(target_arch = "x86_64")] +pub type UHALF_PTR = ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type PUHALF_PTR = *mut ::c_uint; +#[cfg(target_arch = "x86_64")] +pub type HALF_PTR = ::c_int; +#[cfg(target_arch = "x86_64")] +pub type PHALF_PTR = *mut ::c_int; +#[cfg(target_arch = "x86")] +pub type SHANDLE_PTR = ::c_long; +#[cfg(target_arch = "x86")] +pub type HANDLE_PTR = ::c_ulong; +#[cfg(target_arch = "x86")] +pub type UHALF_PTR = ::c_ushort; +#[cfg(target_arch = "x86")] +pub type PUHALF_PTR = *mut ::c_ushort; +#[cfg(target_arch = "x86")] +pub type HALF_PTR = ::c_short; +#[cfg(target_arch = "x86")] +pub type PHALF_PTR = *mut ::c_short; +pub type SIZE_T = ULONG_PTR; +pub type PSIZE_T = *mut ULONG_PTR; +pub type SSIZE_T = LONG_PTR; +pub type PSSIZE_T = *mut LONG_PTR; +pub type DWORD_PTR = ULONG_PTR; +pub type PDWORD_PTR = *mut ULONG_PTR; +pub type LONG64 = ::__int64; +pub type PLONG64 = *mut ::__int64; +pub type ULONG64 = ::__uint64; +pub type PULONG64 = *mut ::__uint64; +pub type DWORD64 = ::__uint64; +pub type PDWORD64 = *mut ::__uint64; +pub type KAFFINITY = ULONG_PTR; +pub type PKAFFINITY = *mut KAFFINITY; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/bcrypt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/bcrypt.rs new file mode 100644 index 0000000..ee818a5 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/bcrypt.rs @@ -0,0 +1,356 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Cryptographic Primitive API Prototypes and Definitions +pub const KDF_HASH_ALGORITHM: ::ULONG = 0x0; +pub const KDF_SECRET_PREPEND: ::ULONG = 0x1; +pub const KDF_SECRET_APPEND: ::ULONG = 0x2; +pub const KDF_HMAC_KEY: ::ULONG = 0x3; +pub const KDF_TLS_PRF_LABEL: ::ULONG = 0x4; +pub const KDF_TLS_PRF_SEED: ::ULONG = 0x5; +pub const KDF_SECRET_HANDLE: ::ULONG = 0x6; +pub const KDF_TLS_PRF_PROTOCOL: ::ULONG = 0x7; +pub const KDF_ALGORITHMID: ::ULONG = 0x8; +pub const KDF_PARTYUINFO: ::ULONG = 0x9; +pub const KDF_PARTYVINFO: ::ULONG = 0xA; +pub const KDF_SUPPPUBINFO: ::ULONG = 0xB; +pub const KDF_SUPPPRIVINFO: ::ULONG = 0xC; +pub const KDF_LABEL: ::ULONG = 0xD; +pub const KDF_CONTEXT: ::ULONG = 0xE; +pub const KDF_SALT: ::ULONG = 0xF; +pub const KDF_ITERATION_COUNT: ::ULONG = 0x10; +pub const KDF_GENERIC_PARAMETER: ::ULONG = 0x11; +pub const KDF_KEYBITLENGTH: ::ULONG = 0x12; +pub const KDF_USE_SECRET_AS_HMAC_KEY_FLAG: ::ULONG = 0x1; +STRUCT!{struct BCRYPT_KEY_LENGTHS_STRUCT { + dwMinLength: ::ULONG, + dwMaxLength: ::ULONG, + dwIncrement: ::ULONG, +}} +pub type BCRYPT_AUTH_TAG_LENGTHS_STRUCT = BCRYPT_KEY_LENGTHS_STRUCT; +STRUCT!{struct BCRYPT_OID { + cbOID: ::ULONG, + pbOID: ::PUCHAR, +}} +STRUCT!{struct BCRYPT_OID_LIST { + dwOIDCount: ::ULONG, + pOIDs: *mut BCRYPT_OID, +}} +STRUCT!{struct BCRYPT_PKCS1_PADDING_INFO { + pszAlgId: ::LPCWSTR, +}} +STRUCT!{struct BCRYPT_PSS_PADDING_INFO { + pszAlgId: ::LPCWSTR, + cbSalt: ::ULONG, +}} +STRUCT!{struct BCRYPT_OAEP_PADDING_INFO { + pszAlgId: ::LPCWSTR, + pbLabel: ::PUCHAR, + cbLabel: ::ULONG, +}} +pub const BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION: ::ULONG = 1; +pub const BCRYPT_AUTH_MODE_CHAIN_CALLS_FLAG: ::ULONG = 0x00000001; +pub const BCRYPT_AUTH_MODE_IN_PROGRESS_FLAG: ::ULONG = 0x00000002; +STRUCT!{struct BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO { + cbSize: ::ULONG, + dwInfoVersion: ::ULONG, + pbNonce: ::PUCHAR, + cbNonce: ::ULONG, + pbAuthData: ::PUCHAR, + cbAuthData: ::ULONG, + pbTag: ::PUCHAR, + cbTag: ::ULONG, + pbMacContext: ::PUCHAR, + cbMacContext: ::ULONG, + cbAAD: ::ULONG, + cbData: ::ULONGLONG, + dwFlags: ::ULONG, +}} +pub type PBCRYPT_AUTHENTICATED_CIPHER_MODE_INFO = *mut BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO; +pub const BCRYPT_PROV_DISPATCH: ::ULONG = 0x00000001; +pub const BCRYPT_BLOCK_PADDING: ::ULONG = 0x00000001; +pub const BCRYPT_PAD_NONE: ::ULONG = 0x00000001; +pub const BCRYPT_PAD_PKCS1: ::ULONG = 0x00000002; +pub const BCRYPT_PAD_OAEP: ::ULONG = 0x00000004; +pub const BCRYPT_PAD_PSS: ::ULONG = 0x00000008; +pub const BCRYPT_PAD_PKCS1_OPTIONAL_HASH_OID: ::ULONG = 0x00000010; +pub const BCRYPTBUFFER_VERSION: ::ULONG = 0; +STRUCT!{struct BCryptBuffer { + cbBuffer: ::ULONG, + BufferType: ::ULONG, + pvBuffer: ::PVOID, +}} +pub type PBCryptBuffer = *mut BCryptBuffer; +STRUCT!{struct BCryptBufferDesc { + ulVersion: ::ULONG, + cBuffers: ::ULONG, + pBuffers: PBCryptBuffer, +}} +pub type PBCryptBufferDesc = *mut BCryptBufferDesc; +//321 +pub type BCRYPT_HANDLE = ::PVOID; +pub type BCRYPT_ALG_HANDLE = ::PVOID; +pub type BCRYPT_KEY_HANDLE = ::PVOID; +pub type BCRYPT_HASH_HANDLE = ::PVOID; +pub type BCRYPT_SECRET_HANDLE = ::PVOID; +STRUCT!{struct BCRYPT_KEY_BLOB { + Magic: ::ULONG, +}} +pub const BCRYPT_RSAPUBLIC_MAGIC: ::ULONG = 0x31415352; +pub const BCRYPT_RSAPRIVATE_MAGIC: ::ULONG = 0x32415352; +STRUCT!{struct BCRYPT_RSAKEY_BLOB { + Magic: ::ULONG, + BitLength: ::ULONG, + cbPublicExp: ::ULONG, + cbModulus: ::ULONG, + cbPrime1: ::ULONG, + cbPrime2: ::ULONG, +}} +pub const BCRYPT_RSAFULLPRIVATE_MAGIC: ::ULONG = 0x33415352; +pub const BCRYPT_ECDH_PUBLIC_P256_MAGIC: ::ULONG = 0x314B4345; +pub const BCRYPT_ECDH_PRIVATE_P256_MAGIC: ::ULONG = 0x324B4345; +pub const BCRYPT_ECDH_PUBLIC_P384_MAGIC: ::ULONG = 0x334B4345; +pub const BCRYPT_ECDH_PRIVATE_P384_MAGIC: ::ULONG = 0x344B4345; +pub const BCRYPT_ECDH_PUBLIC_P521_MAGIC: ::ULONG = 0x354B4345; +pub const BCRYPT_ECDH_PRIVATE_P521_MAGIC: ::ULONG = 0x364B4345; +pub const BCRYPT_ECDSA_PUBLIC_P256_MAGIC: ::ULONG = 0x31534345; +pub const BCRYPT_ECDSA_PRIVATE_P256_MAGIC: ::ULONG = 0x32534345; +pub const BCRYPT_ECDSA_PUBLIC_P384_MAGIC: ::ULONG = 0x33534345; +pub const BCRYPT_ECDSA_PRIVATE_P384_MAGIC: ::ULONG = 0x34534345; +pub const BCRYPT_ECDSA_PUBLIC_P521_MAGIC: ::ULONG = 0x35534345; +pub const BCRYPT_ECDSA_PRIVATE_P521_MAGIC: ::ULONG = 0x36534345; +STRUCT!{struct BCRYPT_ECCKEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, +}} +pub type PBCRYPT_ECCKEY_BLOB = *mut BCRYPT_ECCKEY_BLOB; +pub const BCRYPT_DH_PUBLIC_MAGIC: ::ULONG = 0x42504844; +pub const BCRYPT_DH_PRIVATE_MAGIC: ::ULONG = 0x56504844; +STRUCT!{struct BCRYPT_DH_KEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, +}} +pub type PBCRYPT_DH_KEY_BLOB = *mut BCRYPT_DH_KEY_BLOB; +pub const BCRYPT_DH_PARAMETERS_MAGIC: ::ULONG = 0x4d504844; +STRUCT!{struct BCRYPT_DH_PARAMETER_HEADER { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, +}} +pub const BCRYPT_DSA_PUBLIC_MAGIC: ::ULONG = 0x42505344; +pub const BCRYPT_DSA_PRIVATE_MAGIC: ::ULONG = 0x56505344; +pub const BCRYPT_DSA_PUBLIC_MAGIC_V2: ::ULONG = 0x32425044; +pub const BCRYPT_DSA_PRIVATE_MAGIC_V2: ::ULONG = 0x32565044; +STRUCT!{struct BCRYPT_DSA_KEY_BLOB { + dwMagic: ::ULONG, + cbKey: ::ULONG, + Count: [::UCHAR; 4], + Seed: [::UCHAR; 20], + q: [::UCHAR; 20], +}} +pub type PBCRYPT_DSA_KEY_BLOB = *mut BCRYPT_DSA_KEY_BLOB; +ENUM!{enum HASHALGORITHM_ENUM { + DSA_HASH_ALGORITHM_SHA1, + DSA_HASH_ALGORITHM_SHA256, + DSA_HASH_ALGORITHM_SHA512, +}} +ENUM!{enum DSAFIPSVERSION_ENUM { + DSA_FIPS186_2, + DSA_FIPS186_3, +}} +STRUCT!{struct BCRYPT_DSA_KEY_BLOB_V2 { + dwMagic: ::ULONG, + cbKey: ::ULONG, + hashAlgorithm: HASHALGORITHM_ENUM, + standardVersion: DSAFIPSVERSION_ENUM, + cbSeedLength: ::ULONG, + cbGroupSize: ::ULONG, + Count: [::UCHAR; 4], +}} +pub type PBCRYPT_DSA_KEY_BLOB_V2 = *mut BCRYPT_DSA_KEY_BLOB_V2; +STRUCT!{struct BCRYPT_KEY_DATA_BLOB_HEADER { + dwMagic: ::ULONG, + dwVersion: ::ULONG, + cbKeyData: ::ULONG, +}} +pub type PBCRYPT_KEY_DATA_BLOB_HEADER = *mut BCRYPT_KEY_DATA_BLOB_HEADER; +pub const BCRYPT_KEY_DATA_BLOB_MAGIC: ::ULONG = 0x4d42444b; +pub const BCRYPT_KEY_DATA_BLOB_VERSION1: ::ULONG = 0x1; +pub const BCRYPT_DSA_PARAMETERS_MAGIC: ::ULONG = 0x4d505344; +pub const BCRYPT_DSA_PARAMETERS_MAGIC_V2: ::ULONG = 0x324d5044; +STRUCT!{struct BCRYPT_DSA_PARAMETER_HEADER { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, + Count: [::UCHAR; 4], + Seed: [::UCHAR; 20], + q: [::UCHAR; 20], +}} +STRUCT!{struct BCRYPT_DSA_PARAMETER_HEADER_V2 { + cbLength: ::ULONG, + dwMagic: ::ULONG, + cbKeyLength: ::ULONG, + hashAlgorithm: HASHALGORITHM_ENUM, + standardVersion: DSAFIPSVERSION_ENUM, + cbSeedLength: ::ULONG, + cbGroupSize: ::ULONG, + Count: [::UCHAR; 4], +}} +ENUM!{enum BCRYPT_HASH_OPERATION_TYPE { + BCRYPT_HASH_OPERATION_HASH_DATA = 1, + BCRYPT_HASH_OPERATION_FINISH_HASH = 2, +}} +STRUCT!{struct BCRYPT_MULTI_HASH_OPERATION { + iHash: ::ULONG, + hashOperation: BCRYPT_HASH_OPERATION_TYPE, + pbBuffer: ::PUCHAR, + cbBuffer: ::ULONG, +}} +ENUM!{enum BCRYPT_MULTI_OPERATION_TYPE { + BCRYPT_OPERATION_TYPE_HASH = 1, +}} +STRUCT!{struct BCRYPT_MULTI_OBJECT_LENGTH_STRUCT { + cbPerObject: ::ULONG, + cbPerElement: ::ULONG, +}} +pub const BCRYPT_CIPHER_INTERFACE: ::ULONG = 0x00000001; +pub const BCRYPT_HASH_INTERFACE: ::ULONG = 0x00000002; +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE: ::ULONG = 0x00000003; +pub const BCRYPT_SECRET_AGREEMENT_INTERFACE: ::ULONG = 0x00000004; +pub const BCRYPT_SIGNATURE_INTERFACE: ::ULONG = 0x00000005; +pub const BCRYPT_RNG_INTERFACE: ::ULONG = 0x00000006; +pub const BCRYPT_KEY_DERIVATION_INTERFACE: ::ULONG = 0x00000007; +pub const BCRYPT_ALG_HANDLE_HMAC_FLAG: ::ULONG = 0x00000008; +pub const BCRYPT_CAPI_AES_FLAG: ::ULONG = 0x00000010; +pub const BCRYPT_HASH_REUSABLE_FLAG: ::ULONG = 0x00000020; +pub const BCRYPT_BUFFERS_LOCKED_FLAG: ::ULONG = 0x00000040; +pub const BCRYPT_EXTENDED_KEYSIZE: ::ULONG = 0x00000080; +pub const BCRYPT_CIPHER_OPERATION: ::ULONG = 0x00000001; +pub const BCRYPT_HASH_OPERATION: ::ULONG = 0x00000002; +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_OPERATION: ::ULONG = 0x00000004; +pub const BCRYPT_SECRET_AGREEMENT_OPERATION: ::ULONG = 0x00000008; +pub const BCRYPT_SIGNATURE_OPERATION: ::ULONG = 0x00000010; +pub const BCRYPT_RNG_OPERATION: ::ULONG = 0x00000020; +pub const BCRYPT_KEY_DERIVATION_OPERATION: ::ULONG = 0x00000040; +STRUCT!{struct BCRYPT_ALGORITHM_IDENTIFIER { + pszName: ::LPWSTR, + dwClass: ::ULONG, + dwFlags: ::ULONG, +}} +STRUCT!{struct BCRYPT_PROVIDER_NAME { + pszProviderName: ::LPWSTR, +}} +pub const BCRYPT_PUBLIC_KEY_FLAG: ::ULONG = 0x00000001; +pub const BCRYPT_PRIVATE_KEY_FLAG: ::ULONG = 0x00000002; +pub const BCRYPT_RNG_USE_ENTROPY_IN_BUFFER: ::ULONG = 0x00000001; +pub const BCRYPT_USE_SYSTEM_PREFERRED_RNG: ::ULONG = 0x00000002; +STRUCT!{struct BCRYPT_INTERFACE_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, +}} +pub type PBCRYPT_INTERFACE_VERSION = *mut BCRYPT_INTERFACE_VERSION; +pub const BCRYPT_CIPHER_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_HASH_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_HASH_INTERFACE_MAJORVERSION_2: ::USHORT = 2; +pub const BCRYPT_HASH_INTERFACE_VERSION_2: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(BCRYPT_HASH_INTERFACE_MAJORVERSION_2, 0); +pub const BCRYPT_ASYMMETRIC_ENCRYPTION_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_SECRET_AGREEMENT_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_SIGNATURE_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const BCRYPT_RNG_INTERFACE_VERSION_1: BCRYPT_INTERFACE_VERSION = + BCRYPT_MAKE_INTERFACE_VERSION!(1, 0); +pub const CRYPT_MIN_DEPENDENCIES: ::ULONG = 0x00000001; +pub const CRYPT_PROCESS_ISOLATE: ::ULONG = 0x00010000; +pub const CRYPT_UM: ::ULONG = 0x00000001; +pub const CRYPT_KM: ::ULONG = 0x00000002; +pub const CRYPT_MM: ::ULONG = 0x00000003; +pub const CRYPT_ANY: ::ULONG = 0x00000004; +pub const CRYPT_OVERWRITE: ::ULONG = 0x00000001; +pub const CRYPT_LOCAL: ::ULONG = 0x00000001; +pub const CRYPT_DOMAIN: ::ULONG = 0x00000002; +pub const CRYPT_EXCLUSIVE: ::ULONG = 0x00000001; +pub const CRYPT_OVERRIDE: ::ULONG = 0x00010000; +pub const CRYPT_ALL_FUNCTIONS: ::ULONG = 0x00000001; +pub const CRYPT_ALL_PROVIDERS: ::ULONG = 0x00000002; +pub const CRYPT_PRIORITY_TOP: ::ULONG = 0x00000000; +pub const CRYPT_PRIORITY_BOTTOM: ::ULONG = 0xFFFFFFFF; +STRUCT!{struct CRYPT_INTERFACE_REG { + dwInterface: ::ULONG, + dwFlags: ::ULONG, + cFunctions: ::ULONG, + rgpszFunctions: *mut ::PWSTR, +}} +pub type PCRYPT_INTERFACE_REG = *mut CRYPT_INTERFACE_REG; +STRUCT!{struct CRYPT_IMAGE_REG { + pszImage: ::PWSTR, + cInterfaces: ::ULONG, + rgpInterfaces: *mut PCRYPT_INTERFACE_REG, +}} +pub type PCRYPT_IMAGE_REG = *mut CRYPT_IMAGE_REG; +STRUCT!{struct CRYPT_PROVIDER_REG { + cAliases: ::ULONG, + rgpszAliases: *mut ::PWSTR, + pUM: PCRYPT_IMAGE_REG, + pKM: PCRYPT_IMAGE_REG, +}} +pub type PCRYPT_PROVIDER_REG = *mut CRYPT_PROVIDER_REG; +STRUCT!{struct CRYPT_PROVIDERS { + cProviders: ::ULONG, + rgpszProviders: *mut ::PWSTR, +}} +pub type PCRYPT_PROVIDERS = *mut CRYPT_PROVIDERS; +STRUCT!{struct CRYPT_CONTEXT_CONFIG { + dwFlags: ::ULONG, + dwReserved: ::ULONG, +}} +pub type PCRYPT_CONTEXT_CONFIG = *mut CRYPT_CONTEXT_CONFIG; +STRUCT!{struct CRYPT_CONTEXT_FUNCTION_CONFIG { + dwFlags: ::ULONG, + dwReserved: ::ULONG, +}} +pub type PCRYPT_CONTEXT_FUNCTION_CONFIG = *mut CRYPT_CONTEXT_FUNCTION_CONFIG; +STRUCT!{struct CRYPT_CONTEXTS { + cContexts: ::ULONG, + rgpszContexts: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXTS = *mut CRYPT_CONTEXTS; +STRUCT!{struct CRYPT_CONTEXT_FUNCTIONS { + cFunctions: ::ULONG, + rgpszFunctions: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXT_FUNCTIONS = *mut CRYPT_CONTEXT_FUNCTIONS; +STRUCT!{struct CRYPT_CONTEXT_FUNCTION_PROVIDERS { + cProviders: ::ULONG, + rgpszProviders: *mut ::PWSTR, +}} +pub type PCRYPT_CONTEXT_FUNCTION_PROVIDERS = *mut CRYPT_CONTEXT_FUNCTION_PROVIDERS; +STRUCT!{struct CRYPT_PROPERTY_REF { + pszProperty: ::PWSTR, + cbValue: ::ULONG, + pbValue: ::PUCHAR, +}} +pub type PCRYPT_PROPERTY_REF = *mut CRYPT_PROPERTY_REF; +STRUCT!{struct CRYPT_IMAGE_REF { + pszImage: ::PWSTR, + dwFlags: ::ULONG, +}} +pub type PCRYPT_IMAGE_REF = *mut CRYPT_IMAGE_REF; +STRUCT!{struct CRYPT_PROVIDER_REF { + dwInterface: ::ULONG, + pszFunction: ::PWSTR, + pszProvider: ::PWSTR, + cProperties: ::ULONG, + rgpProperties: *mut PCRYPT_PROPERTY_REF, + pUM: PCRYPT_IMAGE_REF, + pKM: PCRYPT_IMAGE_REF, +}} +pub type PCRYPT_PROVIDER_REF = *mut CRYPT_PROVIDER_REF; +STRUCT!{struct CRYPT_PROVIDER_REFS { + cProviders: ::ULONG, + rgpProviders: *mut PCRYPT_PROVIDER_REF, +}} +pub type PCRYPT_PROVIDER_REFS = *mut CRYPT_PROVIDER_REFS; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/cfg.rs b/third_party/cargo/vendor/winapi-0.2.8/src/cfg.rs new file mode 100644 index 0000000..0720d32 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/cfg.rs @@ -0,0 +1,134 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! common Configuration Manager definitions for both user mode and kernel mode code +ENUM!{enum PNP_VETO_TYPE { + PNP_VetoTypeUnknown, + PNP_VetoLegacyDevice, + PNP_VetoPendingClose, + PNP_VetoWindowsApp, + PNP_VetoWindowsService, + PNP_VetoOutstandingOpen, + PNP_VetoDevice, + PNP_VetoDriver, + PNP_VetoIllegalDeviceRequest, + PNP_VetoInsufficientPower, + PNP_VetoNonDisableable, + PNP_VetoLegacyDriver, + PNP_VetoInsufficientRights, +}} +pub type PPNP_VETO_TYPE = *mut PNP_VETO_TYPE; +pub const CM_PROB_NOT_CONFIGURED: ::CONFIGRET = 0x00000001; +pub const CM_PROB_DEVLOADER_FAILED: ::CONFIGRET = 0x00000002; +pub const CM_PROB_OUT_OF_MEMORY: ::CONFIGRET = 0x00000003; +pub const CM_PROB_ENTRY_IS_WRONG_TYPE: ::CONFIGRET = 0x00000004; +pub const CM_PROB_LACKED_ARBITRATOR: ::CONFIGRET = 0x00000005; +pub const CM_PROB_BOOT_CONFIG_CONFLICT: ::CONFIGRET = 0x00000006; +pub const CM_PROB_FAILED_FILTER: ::CONFIGRET = 0x00000007; +pub const CM_PROB_DEVLOADER_NOT_FOUND: ::CONFIGRET = 0x00000008; +pub const CM_PROB_INVALID_DATA: ::CONFIGRET = 0x00000009; +pub const CM_PROB_FAILED_START: ::CONFIGRET = 0x0000000A; +pub const CM_PROB_LIAR: ::CONFIGRET = 0x0000000B; +pub const CM_PROB_NORMAL_CONFLICT: ::CONFIGRET = 0x0000000C; +pub const CM_PROB_NOT_VERIFIED: ::CONFIGRET = 0x0000000D; +pub const CM_PROB_NEED_RESTART: ::CONFIGRET = 0x0000000E; +pub const CM_PROB_REENUMERATION: ::CONFIGRET = 0x0000000F; +pub const CM_PROB_PARTIAL_LOG_CONF: ::CONFIGRET = 0x00000010; +pub const CM_PROB_UNKNOWN_RESOURCE: ::CONFIGRET = 0x00000011; +pub const CM_PROB_REINSTALL: ::CONFIGRET = 0x00000012; +pub const CM_PROB_REGISTRY: ::CONFIGRET = 0x00000013; +pub const CM_PROB_VXDLDR: ::CONFIGRET = 0x00000014; +pub const CM_PROB_WILL_BE_REMOVED: ::CONFIGRET = 0x00000015; +pub const CM_PROB_DISABLED: ::CONFIGRET = 0x00000016; +pub const CM_PROB_DEVLOADER_NOT_READY: ::CONFIGRET = 0x00000017; +pub const CM_PROB_DEVICE_NOT_THERE: ::CONFIGRET = 0x00000018; +pub const CM_PROB_MOVED: ::CONFIGRET = 0x00000019; +pub const CM_PROB_TOO_EARLY: ::CONFIGRET = 0x0000001A; +pub const CM_PROB_NO_VALID_LOG_CONF: ::CONFIGRET = 0x0000001B; +pub const CM_PROB_FAILED_INSTALL: ::CONFIGRET = 0x0000001C; +pub const CM_PROB_HARDWARE_DISABLED: ::CONFIGRET = 0x0000001D; +pub const CM_PROB_CANT_SHARE_IRQ: ::CONFIGRET = 0x0000001E; +pub const CM_PROB_FAILED_ADD: ::CONFIGRET = 0x0000001F; +pub const CM_PROB_DISABLED_SERVICE: ::CONFIGRET = 0x00000020; +pub const CM_PROB_TRANSLATION_FAILED: ::CONFIGRET = 0x00000021; +pub const CM_PROB_NO_SOFTCONFIG: ::CONFIGRET = 0x00000022; +pub const CM_PROB_BIOS_TABLE: ::CONFIGRET = 0x00000023; +pub const CM_PROB_IRQ_TRANSLATION_FAILED: ::CONFIGRET = 0x00000024; +pub const CM_PROB_FAILED_DRIVER_ENTRY: ::CONFIGRET = 0x00000025; +pub const CM_PROB_DRIVER_FAILED_PRIOR_UNLOAD: ::CONFIGRET = 0x00000026; +pub const CM_PROB_DRIVER_FAILED_LOAD: ::CONFIGRET = 0x00000027; +pub const CM_PROB_DRIVER_SERVICE_KEY_INVALID: ::CONFIGRET = 0x00000028; +pub const CM_PROB_LEGACY_SERVICE_NO_DEVICES: ::CONFIGRET = 0x00000029; +pub const CM_PROB_DUPLICATE_DEVICE: ::CONFIGRET = 0x0000002A; +pub const CM_PROB_FAILED_POST_START: ::CONFIGRET = 0x0000002B; +pub const CM_PROB_HALTED: ::CONFIGRET = 0x0000002C; +pub const CM_PROB_PHANTOM: ::CONFIGRET = 0x0000002D; +pub const CM_PROB_SYSTEM_SHUTDOWN: ::CONFIGRET = 0x0000002E; +pub const CM_PROB_HELD_FOR_EJECT: ::CONFIGRET = 0x0000002F; +pub const CM_PROB_DRIVER_BLOCKED: ::CONFIGRET = 0x00000030; +pub const CM_PROB_REGISTRY_TOO_LARGE: ::CONFIGRET = 0x00000031; +pub const CM_PROB_SETPROPERTIES_FAILED: ::CONFIGRET = 0x00000032; +pub const CM_PROB_WAITING_ON_DEPENDENCY: ::CONFIGRET = 0x00000033; +pub const CM_PROB_UNSIGNED_DRIVER: ::CONFIGRET = 0x00000034; +pub const CM_PROB_USED_BY_DEBUGGER: ::CONFIGRET = 0x00000035; +pub const NUM_CM_PROB_V1: ::CONFIGRET = 0x00000025; +pub const NUM_CM_PROB_V2: ::CONFIGRET = 0x00000032; +pub const NUM_CM_PROB_V3: ::CONFIGRET = 0x00000033; +pub const NUM_CM_PROB_V4: ::CONFIGRET = 0x00000034; +pub const NUM_CM_PROB_V5: ::CONFIGRET = 0x00000035; +pub const NUM_CM_PROB_V6: ::CONFIGRET = 0x00000036; +pub const DN_ROOT_ENUMERATED: ::CONFIGRET = 0x00000001; +pub const DN_DRIVER_LOADED: ::CONFIGRET = 0x00000002; +pub const DN_ENUM_LOADED: ::CONFIGRET = 0x00000004; +pub const DN_STARTED: ::CONFIGRET = 0x00000008; +pub const DN_MANUAL: ::CONFIGRET = 0x00000010; +pub const DN_NEED_TO_ENUM: ::CONFIGRET = 0x00000020; +pub const DN_NOT_FIRST_TIME: ::CONFIGRET = 0x00000040; +pub const DN_HARDWARE_ENUM: ::CONFIGRET = 0x00000080; +pub const DN_LIAR: ::CONFIGRET = 0x00000100; +pub const DN_HAS_MARK: ::CONFIGRET = 0x00000200; +pub const DN_HAS_PROBLEM: ::CONFIGRET = 0x00000400; +pub const DN_FILTERED: ::CONFIGRET = 0x00000800; +pub const DN_MOVED: ::CONFIGRET = 0x00001000; +pub const DN_DISABLEABLE: ::CONFIGRET = 0x00002000; +pub const DN_REMOVABLE: ::CONFIGRET = 0x00004000; +pub const DN_PRIVATE_PROBLEM: ::CONFIGRET = 0x00008000; +pub const DN_MF_PARENT: ::CONFIGRET = 0x00010000; +pub const DN_MF_CHILD: ::CONFIGRET = 0x00020000; +pub const DN_WILL_BE_REMOVED: ::CONFIGRET = 0x00040000; +pub const DN_NOT_FIRST_TIMEE: ::CONFIGRET = 0x00080000; +pub const DN_STOP_FREE_RES: ::CONFIGRET = 0x00100000; +pub const DN_REBAL_CANDIDATE: ::CONFIGRET = 0x00200000; +pub const DN_BAD_PARTIAL: ::CONFIGRET = 0x00400000; +pub const DN_NT_ENUMERATOR: ::CONFIGRET = 0x00800000; +pub const DN_NT_DRIVER: ::CONFIGRET = 0x01000000; +pub const DN_NEEDS_LOCKING: ::CONFIGRET = 0x02000000; +pub const DN_ARM_WAKEUP: ::CONFIGRET = 0x04000000; +pub const DN_APM_ENUMERATOR: ::CONFIGRET = 0x08000000; +pub const DN_APM_DRIVER: ::CONFIGRET = 0x10000000; +pub const DN_SILENT_INSTALL: ::CONFIGRET = 0x20000000; +pub const DN_NO_SHOW_IN_DM: ::CONFIGRET = 0x40000000; +pub const DN_BOOT_LOG_PROB: ::CONFIGRET = 0x80000000; +pub const DN_NEED_RESTART: ::CONFIGRET = DN_LIAR; +pub const DN_DRIVER_BLOCKED: ::CONFIGRET = DN_NOT_FIRST_TIME; +pub const DN_LEGACY_DRIVER: ::CONFIGRET = DN_MOVED; +pub const DN_CHILD_WITH_INVALID_ID: ::CONFIGRET = DN_HAS_MARK; +pub const DN_DEVICE_DISCONNECTED: ::CONFIGRET = DN_NEEDS_LOCKING; +pub const DN_CHANGEABLE_FLAGS: ::CONFIGRET = DN_NOT_FIRST_TIME + DN_HARDWARE_ENUM + DN_HAS_MARK + + DN_DISABLEABLE + DN_REMOVABLE + DN_MF_CHILD + DN_MF_PARENT + DN_NOT_FIRST_TIMEE + + DN_STOP_FREE_RES + DN_REBAL_CANDIDATE + DN_NT_ENUMERATOR + DN_NT_DRIVER + DN_SILENT_INSTALL + + DN_NO_SHOW_IN_DM; +pub const LCPRI_FORCECONFIG: ::PRIORITY = 0x00000000; +pub const LCPRI_BOOTCONFIG: ::PRIORITY = 0x00000001; +pub const LCPRI_DESIRED: ::PRIORITY = 0x00002000; +pub const LCPRI_NORMAL: ::PRIORITY = 0x00003000; +pub const LCPRI_LASTBESTCONFIG: ::PRIORITY = 0x00003FFF; +pub const LCPRI_SUBOPTIMAL: ::PRIORITY = 0x00005000; +pub const LCPRI_LASTSOFTCONFIG: ::PRIORITY = 0x00007FFF; +pub const LCPRI_RESTART: ::PRIORITY = 0x00008000; +pub const LCPRI_REBOOT: ::PRIORITY = 0x00009000; +pub const LCPRI_POWEROFF: ::PRIORITY = 0x0000A000; +pub const LCPRI_HARDRECONFIG: ::PRIORITY = 0x0000C000; +pub const LCPRI_HARDWIRED: ::PRIORITY = 0x0000E000; +pub const LCPRI_IMPOSSIBLE: ::PRIORITY = 0x0000F000; +pub const LCPRI_DISABLED: ::PRIORITY = 0x0000FFFF; +pub const MAX_LCPRI: ::PRIORITY = 0x0000FFFF; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/cfgmgr32.rs b/third_party/cargo/vendor/winapi-0.2.8/src/cfgmgr32.rs new file mode 100644 index 0000000..0305f1b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/cfgmgr32.rs @@ -0,0 +1,758 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! user APIs for the Configuration Manager +pub type PCVOID = *const ::VOID; +pub const MAX_DEVICE_ID_LEN: usize = 200; +pub const MAX_DEVNODE_ID_LEN: usize = MAX_DEVICE_ID_LEN; +pub const MAX_GUID_STRING_LEN: usize = 39; +pub const MAX_CLASS_NAME_LEN: usize = 32; +pub const MAX_PROFILE_LEN: usize = 80; +pub const MAX_CONFIG_VALUE: ::DWORD = 9999; +pub const MAX_INSTANCE_VALUE: ::DWORD = 9999; +pub const MAX_MEM_REGISTERS: ::DWORD = 9; +pub const MAX_IO_PORTS: ::DWORD = 20; +pub const MAX_IRQS: ::DWORD = 7; +pub const MAX_DMA_CHANNELS: ::DWORD = 7; +pub const DWORD_MAX: ::DWORD = 0xffffffff; +pub const DWORDLONG_MAX: ::DWORDLONG = 0xffffffffffffffff; +pub const CONFIGMG_VERSION: ::DWORD = 0x0400; +pub type RETURN_TYPE = ::DWORD; +pub type CONFIGRET = RETURN_TYPE; +pub type DEVNODE = ::DWORD; +pub type DEVINST = ::DWORD; +pub type PDEVNODE = *mut DEVNODE; +pub type PDEVINST = *mut DEVNODE; +pub type DEVNODEID_A = *mut ::CHAR; +pub type DEVINSTID_A = *mut ::CHAR; +pub type DEVNODEID_W = *mut ::WCHAR; +pub type DEVINSTID_W = *mut ::WCHAR; +pub type LOG_CONF = ::DWORD_PTR; +pub type PLOG_CONF = *mut LOG_CONF; +pub type RES_DES = ::DWORD_PTR; +pub type PRES_DES = *mut RES_DES; +pub type RESOURCEID = ::ULONG; +pub type PRESOURCEID = *mut RESOURCEID; +pub type PRIORITY = ::ULONG; +pub type PPRIORITY = *mut PRIORITY; +pub type RANGE_LIST = ::DWORD_PTR; +pub type PRANGE_LIST = *mut RANGE_LIST; +pub type RANGE_ELEMENT = ::DWORD_PTR; +pub type PRANGE_ELEMENT = *mut RANGE_ELEMENT; +pub type HMACHINE = ::HANDLE; +pub type PHMACHINE = *mut HMACHINE; +pub type CONFLICT_LIST = ::ULONG_PTR; +pub type PCONFLICT_LIST = *mut CONFLICT_LIST; +STRUCT!{nodebug struct CONFLICT_DETAILS_A { + CD_ulSize: ::ULONG, + CD_ulMask: ::ULONG, + CD_dnDevInst: DEVINST, + CD_rdResDes: RES_DES, + CD_ulFlags: ::ULONG, + CD_szDescription: [::CHAR; ::MAX_PATH], +}} +pub type PCONFLICT_DETAILS_A = *mut CONFLICT_DETAILS_A; +STRUCT!{nodebug struct CONFLICT_DETAILS_W { + CD_ulSize: ::ULONG, + CD_ulMask: ::ULONG, + CD_dnDevInst: DEVINST, + CD_rdResDes: RES_DES, + CD_ulFlags: ::ULONG, + CD_szDescription: [::WCHAR; ::MAX_PATH], +}} +pub type PCONFLICT_DETAILS_W = *mut CONFLICT_DETAILS_W; +pub const CM_CDMASK_DEVINST: ::ULONG = 0x00000001; +pub const CM_CDMASK_RESDES: ::ULONG = 0x00000002; +pub const CM_CDMASK_FLAGS: ::ULONG = 0x00000004; +pub const CM_CDMASK_DESCRIPTION: ::ULONG = 0x00000008; +pub const CM_CDMASK_VALID: ::ULONG = 0x0000000F; +pub const CM_CDFLAGS_DRIVER: ::ULONG = 0x00000001; +pub const CM_CDFLAGS_ROOT_OWNED: ::ULONG = 0x00000002; +pub const CM_CDFLAGS_RESERVED: ::ULONG = 0x00000004; +pub type REGDISPOSITION = ::ULONG; +pub const mMD_MemoryType: ::DWORD = 0x1; +pub const fMD_MemoryType: ::DWORD = mMD_MemoryType; +pub const fMD_ROM: ::DWORD = 0x0; +pub const fMD_RAM: ::DWORD = 0x1; +pub const mMD_32_24: ::DWORD = 0x2; +pub const fMD_32_24: ::DWORD = mMD_32_24; +pub const fMD_24: ::DWORD = 0x0; +pub const fMD_32: ::DWORD = 0x2; +pub const mMD_Prefetchable: ::DWORD = 0x4; +pub const fMD_Prefetchable: ::DWORD = mMD_Prefetchable; +pub const fMD_Pref: ::DWORD = mMD_Prefetchable; +pub const fMD_PrefetchDisallowed: ::DWORD = 0x0; +pub const fMD_PrefetchAllowed: ::DWORD = 0x4; +pub const mMD_Readable: ::DWORD = 0x8; +pub const fMD_Readable: ::DWORD = mMD_Readable; +pub const fMD_ReadAllowed: ::DWORD = 0x0; +pub const fMD_ReadDisallowed: ::DWORD = 0x8; +pub const mMD_CombinedWrite: ::DWORD = 0x10; +pub const fMD_CombinedWrite: ::DWORD = mMD_CombinedWrite; +pub const fMD_CombinedWriteDisallowed: ::DWORD = 0x0; +pub const fMD_CombinedWriteAllowed: ::DWORD = 0x10; +pub const mMD_Cacheable: ::DWORD = 0x20; +pub const fMD_NonCacheable: ::DWORD = 0x0; +pub const fMD_Cacheable: ::DWORD = 0x20; +pub const fMD_WINDOW_DECODE: ::DWORD = 0x40; +pub const fMD_MEMORY_BAR: ::DWORD = 0x80; +STRUCT!{struct MEM_RANGE { + MR_Align: ::DWORDLONG, + MR_nBytes: ::ULONG, + MR_Min: ::DWORDLONG, + MR_Max: ::DWORDLONG, + MR_Flags: ::DWORD, + MR_Reserved: ::DWORD, +}} +pub type PMEM_RANGE = *mut MEM_RANGE; +STRUCT!{struct MEM_DES { + MD_Count: ::DWORD, + MD_Type: ::DWORD, + MD_Alloc_Base: ::DWORDLONG, + MD_Alloc_End: ::DWORDLONG, + MD_Flags: ::DWORD, + MD_Reserved: ::DWORD, +}} +pub type PMEM_DES = *mut MEM_DES; +STRUCT!{struct MEM_RESOURCE { + MEM_Header: MEM_DES, + MEM_Data: [MEM_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PMEM_RESOURCE = *mut MEM_RESOURCE; +STRUCT!{struct MEM_LARGE_RANGE { + MLR_Align: ::DWORDLONG, + MLR_nBytes: ::ULONGLONG, + MLR_Min: ::DWORDLONG, + MLR_Max: ::DWORDLONG, + MLR_Flags: ::DWORD, + MLR_Reserved: ::DWORD, +}} +pub type PMEM_LARGE_RANGE = *mut MEM_LARGE_RANGE; +STRUCT!{struct MEM_LARGE_DES { + MLD_Count: ::DWORD, + MLD_Type: ::DWORD, + MLD_Alloc_Base: ::DWORDLONG, + MLD_Alloc_End: ::DWORDLONG, + MLD_Flags: ::DWORD, + MLD_Reserved: ::DWORD, +}} +pub type PMEM_LARGE_DES = *mut MEM_LARGE_DES; +STRUCT!{struct MEM_LARGE_RESOURCE { + MEM_LARGE_Header: MEM_LARGE_DES, + MEM_LARGE_Data: [MEM_LARGE_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PMEM_LARGE_RESOURCE = *mut MEM_LARGE_RESOURCE; +pub const fIOD_PortType: ::DWORD = 0x1; +pub const fIOD_Memory: ::DWORD = 0x0; +pub const fIOD_IO: ::DWORD = 0x1; +pub const fIOD_DECODE: ::DWORD = 0x00fc; +pub const fIOD_10_BIT_DECODE: ::DWORD = 0x0004; +pub const fIOD_12_BIT_DECODE: ::DWORD = 0x0008; +pub const fIOD_16_BIT_DECODE: ::DWORD = 0x0010; +pub const fIOD_POSITIVE_DECODE: ::DWORD = 0x0020; +pub const fIOD_PASSIVE_DECODE: ::DWORD = 0x0040; +pub const fIOD_WINDOW_DECODE: ::DWORD = 0x0080; +pub const fIOD_PORT_BAR: ::DWORD = 0x0100; +pub const IO_ALIAS_10_BIT_DECODE: ::DWORDLONG = 0x00000004; +pub const IO_ALIAS_12_BIT_DECODE: ::DWORDLONG = 0x00000010; +pub const IO_ALIAS_16_BIT_DECODE: ::DWORDLONG = 0x00000000; +pub const IO_ALIAS_POSITIVE_DECODE: ::DWORDLONG = 0x000000FF; +STRUCT!{struct IO_RANGE { + IOR_Align: ::DWORDLONG, + IOR_nPorts: ::DWORD, + IOR_Min: ::DWORDLONG, + IOR_Max: ::DWORDLONG, + IOR_RangeFlags: ::DWORD, + IOR_Alias: ::DWORDLONG, +}} +pub type PIO_RANGE = *mut IO_RANGE; +STRUCT!{struct IO_DES { + IOD_Count: ::DWORD, + IOD_Type: ::DWORD, + IOD_Alloc_Base: ::DWORDLONG, + IOD_Alloc_End: ::DWORDLONG, + IOD_DesFlags: ::DWORD, +}} +pub type PIO_DES = *mut IO_DES; +STRUCT!{struct IO_RESOURCE { + IO_Header: IO_DES, + IO_Data: [IO_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIO_RESOURCE = *mut IO_RESOURCE; +pub const mDD_Width: ::ULONG = 0x3; +pub const fDD_BYTE: ::ULONG = 0x0; +pub const fDD_WORD: ::ULONG = 0x1; +pub const fDD_DWORD: ::ULONG = 0x2; +pub const fDD_BYTE_AND_WORD: ::ULONG = 0x3; +pub const mDD_BusMaster: ::ULONG = 0x4; +pub const fDD_NoBusMaster: ::ULONG = 0x0; +pub const fDD_BusMaster: ::ULONG = 0x4; +pub const mDD_Type: ::ULONG = 0x18; +pub const fDD_TypeStandard: ::ULONG = 0x00; +pub const fDD_TypeA: ::ULONG = 0x08; +pub const fDD_TypeB: ::ULONG = 0x10; +pub const fDD_TypeF: ::ULONG = 0x18; +STRUCT!{struct DMA_RANGE { + DR_Min: ::ULONG, + DR_Max: ::ULONG, + DR_Flags: ::ULONG, +}} +pub type PDMA_RANGE = *mut DMA_RANGE; +STRUCT!{struct DMA_DES { + DD_Count: ::DWORD, + DD_Type: ::DWORD, + DD_Flags: ::DWORD, + DD_Alloc_Chan: ::ULONG, +}} +pub type PDMA_DES = *mut DMA_DES; +STRUCT!{struct DMA_RESOURCE { + DMA_Header: DMA_DES, + DMA_Data: [DMA_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PDMA_RESOURCE = *mut DMA_RESOURCE; +pub const mIRQD_Share: ::ULONG = 0x1; +pub const fIRQD_Exclusive: ::ULONG = 0x0; +pub const fIRQD_Share: ::ULONG = 0x1; +pub const fIRQD_Share_Bit: ::ULONG = 0; +pub const fIRQD_Level_Bit: ::ULONG = 1; +pub const mIRQD_Edge_Level: ::ULONG = 0x2; +pub const fIRQD_Level: ::ULONG = 0x0; +pub const fIRQD_Edge: ::ULONG = 0x2; +STRUCT!{struct IRQ_RANGE { + IRQR_Min: ::ULONG, + IRQR_Max: ::ULONG, + IRQR_Flags: ::ULONG, +}} +pub type PIRQ_RANGE = *mut IRQ_RANGE; +STRUCT!{struct IRQ_DES_32 { + IRQD_Count: ::DWORD, + IRQD_Type: ::DWORD, + IRQD_Flags: ::DWORD, + IRQD_Alloc_Num: ::ULONG, + IRQD_Affinity: ::ULONG32, +}} +pub type PIRQ_DES_32 = *mut IRQ_DES_32; +STRUCT!{struct IRQ_DES_64 { + IRQD_Count: ::DWORD, + IRQD_Type: ::DWORD, + IRQD_Flags: ::DWORD, + IRQD_Alloc_Num: ::ULONG, + IRQD_Affinity: ::ULONG64, +}} +pub type PIRQ_DES_64 = *mut IRQ_DES_64; +STRUCT!{struct IRQ_RESOURCE_32 { + IRQ_Header: IRQ_DES_32, + IRQ_Data: [IRQ_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIRQ_RESOURCE_32 = *mut IRQ_RESOURCE_32; +STRUCT!{struct IRQ_RESOURCE_64 { + IRQ_Header: IRQ_DES_64, + IRQ_Data: [IRQ_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PIRQ_RESOURCE_64 = *mut IRQ_RESOURCE_64; +STRUCT!{struct DEVPRIVATE_RANGE { + PR_Data1: ::DWORD, + PR_Data2: ::DWORD, + PR_Data3: ::DWORD, +}} +pub type PDEVPRIVATE_RANGE = *mut DEVPRIVATE_RANGE; +STRUCT!{struct DEVPRIVATE_DES { + PD_Count: ::DWORD, + PD_Type: ::DWORD, + PD_Data1: ::DWORD, + PD_Data2: ::DWORD, + PD_Data3: ::DWORD, + PD_Flags: ::DWORD, +}} +pub type PDEVPRIVATE_DES = *mut DEVPRIVATE_DES; +STRUCT!{struct DEVPRIVATE_RESOURCE { + PRV_Header: DEVPRIVATE_DES, + PRV_Data: [DEVPRIVATE_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PDEVPRIVATE_RESOURCE = *mut DEVPRIVATE_RESOURCE; +STRUCT!{struct CS_DES { + CSD_SignatureLength: ::DWORD, + CSD_LegacyDataOffset: ::DWORD, + CSD_LegacyDataSize: ::DWORD, + CSD_Flags: ::DWORD, + CSD_ClassGuid: ::GUID, + CSD_Signature: [::BYTE; ::ANYSIZE_ARRAY], +}} +pub type PCS_DES = *mut CS_DES; +STRUCT!{struct CS_RESOURCE { + CS_Header: CS_DES, +}} +pub type PCS_RESOURCE = *mut CS_RESOURCE; +pub const mPCD_IO_8_16: ::DWORD = 0x1; +pub const fPCD_IO_8: ::DWORD = 0x0; +pub const fPCD_IO_16: ::DWORD = 0x1; +pub const mPCD_MEM_8_16: ::DWORD = 0x2; +pub const fPCD_MEM_8: ::DWORD = 0x0; +pub const fPCD_MEM_16: ::DWORD = 0x2; +pub const mPCD_MEM_A_C: ::DWORD = 0xC; +pub const fPCD_MEM1_A: ::DWORD = 0x4; +pub const fPCD_MEM2_A: ::DWORD = 0x8; +pub const fPCD_IO_ZW_8: ::DWORD = 0x10; +pub const fPCD_IO_SRC_16: ::DWORD = 0x20; +pub const fPCD_IO_WS_16: ::DWORD = 0x40; +pub const mPCD_MEM_WS: ::DWORD = 0x300; +pub const fPCD_MEM_WS_ONE: ::DWORD = 0x100; +pub const fPCD_MEM_WS_TWO: ::DWORD = 0x200; +pub const fPCD_MEM_WS_THREE: ::DWORD = 0x300; +pub const fPCD_MEM_A: ::DWORD = 0x4; +pub const fPCD_ATTRIBUTES_PER_WINDOW: ::DWORD = 0x8000; +pub const fPCD_IO1_16: ::DWORD = 0x00010000; +pub const fPCD_IO1_ZW_8: ::DWORD = 0x00020000; +pub const fPCD_IO1_SRC_16: ::DWORD = 0x00040000; +pub const fPCD_IO1_WS_16: ::DWORD = 0x00080000; +pub const fPCD_IO2_16: ::DWORD = 0x00100000; +pub const fPCD_IO2_ZW_8: ::DWORD = 0x00200000; +pub const fPCD_IO2_SRC_16: ::DWORD = 0x00400000; +pub const fPCD_IO2_WS_16: ::DWORD = 0x00800000; +pub const mPCD_MEM1_WS: ::DWORD = 0x03000000; +pub const fPCD_MEM1_WS_TWO: ::DWORD = 0x02000000; +pub const fPCD_MEM1_WS_THREE: ::DWORD = 0x03000000; +pub const fPCD_MEM1_16: ::DWORD = 0x04000000; +pub const mPCD_MEM2_WS: ::DWORD = 0x30000000; +pub const fPCD_MEM2_WS_ONE: ::DWORD = 0x10000000; +pub const fPCD_MEM2_WS_TWO: ::DWORD = 0x20000000; +pub const fPCD_MEM2_WS_THREE: ::DWORD = 0x30000000; +pub const fPCD_MEM2_16: ::DWORD = 0x40000000; +pub const PCD_MAX_MEMORY: usize = 2; +pub const PCD_MAX_IO: usize = 2; +STRUCT!{struct PCCARD_DES { + PCD_Count: ::DWORD, + PCD_Type: ::DWORD, + PCD_Flags: ::DWORD, + PCD_ConfigIndex: ::BYTE, + PCD_Reserved: [::BYTE; 3], + PCD_MemoryCardBase1: ::DWORD, + PCD_MemoryCardBase2: ::DWORD, + PCD_MemoryCardBase: [::DWORD; PCD_MAX_MEMORY], + PCD_MemoryFlags: [::WORD; PCD_MAX_MEMORY], + PCD_IoFlags: [::BYTE; PCD_MAX_IO], +}} +pub type PPCCARD_DES = *mut PCCARD_DES; +STRUCT!{struct PCCARD_RESOURCE { + PcCard_Header: PCCARD_DES, +}} +pub type PPCCARD_RESOURCE = *mut PCCARD_RESOURCE; +pub const mPMF_AUDIO_ENABLE: ::DWORD = 0x8; +pub const fPMF_AUDIO_ENABLE: ::DWORD = 0x8; +STRUCT!{struct MFCARD_DES { + PMF_Count: ::DWORD, + PMF_Type: ::DWORD, + PMF_Flags: ::DWORD, + PMF_ConfigOptions: ::BYTE, + PMF_IoResourceIndex: ::BYTE, + PMF_Reserved: [::BYTE; 2], + PMF_ConfigRegisterBase: ::DWORD, +}} +pub type PMFCARD_DES = *mut MFCARD_DES; +STRUCT!{struct MFCARD_RESOURCE { + MfCard_Header: MFCARD_DES, +}} +pub type PMFCARD_RESOURCE = *mut MFCARD_RESOURCE; +STRUCT!{struct BUSNUMBER_RANGE { + BUSR_Min: ::ULONG, + BUSR_Max: ::ULONG, + BUSR_nBusNumbers: ::ULONG, + BUSR_Flags: ::ULONG, +}} +pub type PBUSNUMBER_RANGE = *mut BUSNUMBER_RANGE; +STRUCT!{struct BUSNUMBER_DES { + BUSD_Count: ::DWORD, + BUSD_Type: ::DWORD, + BUSD_Flags: ::DWORD, + BUSD_Alloc_Base: ::ULONG, + BUSD_Alloc_End: ::ULONG, +}} +pub type PBUSNUMBER_DES = *mut BUSNUMBER_DES; +STRUCT!{struct BUSNUMBER_RESOURCE { + BusNumber_Header: BUSNUMBER_DES, + BusNumber_Data: [BUSNUMBER_RANGE; ::ANYSIZE_ARRAY], +}} +pub type PBUSNUMBER_RESOURCE = *mut BUSNUMBER_RESOURCE; +STRUCT!{struct CONNECTION_DES { + COND_Type: ::DWORD, + COND_Flags: ::DWORD, + COND_Class: ::BYTE, + COND_ClassType: ::BYTE, + COND_Reserved1: ::BYTE, + COND_Reserved2: ::BYTE, + COND_Id: ::LARGE_INTEGER, +}} +pub type PCONNECTION_DES = *mut CONNECTION_DES; +STRUCT!{struct CONNECTION_RESOURCE { + Connection_Header: CONNECTION_DES, +}} +pub type PCONNECTION_RESOURCE = *mut CONNECTION_RESOURCE; +pub const CM_HWPI_NOT_DOCKABLE: ::DWORD = 0x00000000; +pub const CM_HWPI_UNDOCKED: ::DWORD = 0x00000001; +pub const CM_HWPI_DOCKED: ::DWORD = 0x00000002; +STRUCT!{nodebug struct HWPROFILEINFO_A { + HWPI_ulHWProfile: ::ULONG, + HWPI_szFriendlyName: [::CHAR; MAX_PROFILE_LEN], + HWPI_dwFlags: ::DWORD, +}} +pub type PHWPROFILEINFO_A = *mut HWPROFILEINFO_A; +STRUCT!{nodebug struct HWPROFILEINFO_W { + HWPI_ulHWProfile: ::ULONG, + HWPI_szFriendlyName: [::WCHAR; MAX_PROFILE_LEN], + HWPI_dwFlags: ::DWORD, +}} +pub type PHWPROFILEINFO_W = *mut HWPROFILEINFO_W; +pub const ResType_All: RESOURCEID = 0x00000000; +pub const ResType_None: RESOURCEID = 0x00000000; +pub const ResType_Mem: RESOURCEID = 0x00000001; +pub const ResType_IO: RESOURCEID = 0x00000002; +pub const ResType_DMA: RESOURCEID = 0x00000003; +pub const ResType_IRQ: RESOURCEID = 0x00000004; +pub const ResType_DoNotUse: RESOURCEID = 0x00000005; +pub const ResType_BusNumber: RESOURCEID = 0x00000006; +pub const ResType_MemLarge: RESOURCEID = 0x00000007; +pub const ResType_MAX: RESOURCEID = 0x00000007; +pub const ResType_Ignored_Bit: RESOURCEID = 0x00008000; +pub const ResType_ClassSpecific: RESOURCEID = 0x0000FFFF; +pub const ResType_Reserved: RESOURCEID = 0x00008000; +pub const ResType_DevicePrivate: RESOURCEID = 0x00008001; +pub const ResType_PcCardConfig: RESOURCEID = 0x00008002; +pub const ResType_MfCardConfig: RESOURCEID = 0x00008003; +pub const ResType_Connection: RESOURCEID = 0x00008004; +pub const CM_ADD_RANGE_ADDIFCONFLICT: ::ULONG = 0x00000000; +pub const CM_ADD_RANGE_DONOTADDIFCONFLICT: ::ULONG = 0x00000001; +pub const CM_ADD_RANGE_BITS: ::ULONG = 0x00000001; +pub const BASIC_LOG_CONF: ::ULONG = 0x00000000; +pub const FILTERED_LOG_CONF: ::ULONG = 0x00000001; +pub const ALLOC_LOG_CONF: ::ULONG = 0x00000002; +pub const BOOT_LOG_CONF: ::ULONG = 0x00000003; +pub const FORCED_LOG_CONF: ::ULONG = 0x00000004; +pub const OVERRIDE_LOG_CONF: ::ULONG = 0x00000005; +pub const NUM_LOG_CONF: ::ULONG = 0x00000006; +pub const LOG_CONF_BITS: ::ULONG = 0x00000007; +pub const PRIORITY_EQUAL_FIRST: ::ULONG = 0x00000008; +pub const PRIORITY_EQUAL_LAST: ::ULONG = 0x00000000; +pub const PRIORITY_BIT: ::ULONG = 0x00000008; +pub const RegDisposition_OpenAlways: REGDISPOSITION = 0x00000000; +pub const RegDisposition_OpenExisting: REGDISPOSITION = 0x00000001; +pub const RegDisposition_Bits: REGDISPOSITION = 0x00000001; +pub const CM_ADD_ID_HARDWARE: ::ULONG = 0x00000000; +pub const CM_ADD_ID_COMPATIBLE: ::ULONG = 0x00000001; +pub const CM_ADD_ID_BITS: ::ULONG = 0x00000001; +pub const CM_CREATE_DEVNODE_NORMAL: ::ULONG = 0x00000000; +pub const CM_CREATE_DEVNODE_NO_WAIT_INSTALL: ::ULONG = 0x00000001; +pub const CM_CREATE_DEVNODE_PHANTOM: ::ULONG = 0x00000002; +pub const CM_CREATE_DEVNODE_GENERATE_ID: ::ULONG = 0x00000004; +pub const CM_CREATE_DEVNODE_DO_NOT_INSTALL: ::ULONG = 0x00000008; +pub const CM_CREATE_DEVNODE_BITS: ::ULONG = 0x0000000F; +pub const CM_CREATE_DEVINST_NORMAL: ::ULONG = CM_CREATE_DEVNODE_NORMAL; +pub const CM_CREATE_DEVINST_NO_WAIT_INSTALL: ::ULONG = CM_CREATE_DEVNODE_NO_WAIT_INSTALL; +pub const CM_CREATE_DEVINST_PHANTOM: ::ULONG = CM_CREATE_DEVNODE_PHANTOM; +pub const CM_CREATE_DEVINST_GENERATE_ID: ::ULONG = CM_CREATE_DEVNODE_GENERATE_ID; +pub const CM_CREATE_DEVINST_DO_NOT_INSTALL: ::ULONG = CM_CREATE_DEVNODE_DO_NOT_INSTALL; +pub const CM_CREATE_DEVINST_BITS: ::ULONG = CM_CREATE_DEVNODE_BITS; +pub const CM_DELETE_CLASS_ONLY: ::ULONG = 0x00000000; +pub const CM_DELETE_CLASS_SUBKEYS: ::ULONG = 0x00000001; +pub const CM_DELETE_CLASS_INTERFACE: ::ULONG = 0x00000002; +pub const CM_DELETE_CLASS_BITS: ::ULONG = 0x00000003; +pub const CM_ENUMERATE_CLASSES_INSTALLER: ::ULONG = 0x00000000; +pub const CM_ENUMERATE_CLASSES_INTERFACE: ::ULONG = 0x00000001; +pub const CM_ENUMERATE_CLASSES_BITS: ::ULONG = 0x00000001; +pub const CM_DETECT_NEW_PROFILE: ::ULONG = 0x00000001; +pub const CM_DETECT_CRASHED: ::ULONG = 0x00000002; +pub const CM_DETECT_HWPROF_FIRST_BOOT: ::ULONG = 0x00000004; +pub const CM_DETECT_RUN: ::ULONG = 0x80000000; +pub const CM_DETECT_BITS: ::ULONG = 0x80000007; +pub const CM_DISABLE_POLITE: ::ULONG = 0x00000000; +pub const CM_DISABLE_ABSOLUTE: ::ULONG = 0x00000001; +pub const CM_DISABLE_HARDWARE: ::ULONG = 0x00000002; +pub const CM_DISABLE_UI_NOT_OK: ::ULONG = 0x00000004; +pub const CM_DISABLE_BITS: ::ULONG = 0x00000007; +pub const CM_GETIDLIST_FILTER_NONE: ::ULONG = 0x00000000; +pub const CM_GETIDLIST_FILTER_ENUMERATOR: ::ULONG = 0x00000001; +pub const CM_GETIDLIST_FILTER_SERVICE: ::ULONG = 0x00000002; +pub const CM_GETIDLIST_FILTER_EJECTRELATIONS: ::ULONG = 0x00000004; +pub const CM_GETIDLIST_FILTER_REMOVALRELATIONS: ::ULONG = 0x00000008; +pub const CM_GETIDLIST_FILTER_POWERRELATIONS: ::ULONG = 0x00000010; +pub const CM_GETIDLIST_FILTER_BUSRELATIONS: ::ULONG = 0x00000020; +pub const CM_GETIDLIST_DONOTGENERATE: ::ULONG = 0x10000040; +pub const CM_GETIDLIST_FILTER_TRANSPORTRELATIONS: ::ULONG = 0x00000080; +pub const CM_GETIDLIST_FILTER_PRESENT: ::ULONG = 0x00000100; +pub const CM_GETIDLIST_FILTER_CLASS: ::ULONG = 0x00000200; +pub const CM_GETIDLIST_FILTER_BITS: ::ULONG = 0x100003FF; +pub const CM_GET_DEVICE_INTERFACE_LIST_PRESENT: ::ULONG = 0x00000000; +pub const CM_GET_DEVICE_INTERFACE_LIST_ALL_DEVICES: ::ULONG = 0x00000001; +pub const CM_GET_DEVICE_INTERFACE_LIST_BITS: ::ULONG = 0x00000001; +pub const CM_DRP_DEVICEDESC: ::ULONG = 0x00000001; +pub const CM_DRP_HARDWAREID: ::ULONG = 0x00000002; +pub const CM_DRP_COMPATIBLEIDS: ::ULONG = 0x00000003; +pub const CM_DRP_UNUSED0: ::ULONG = 0x00000004; +pub const CM_DRP_SERVICE: ::ULONG = 0x00000005; +pub const CM_DRP_UNUSED1: ::ULONG = 0x00000006; +pub const CM_DRP_UNUSED2: ::ULONG = 0x00000007; +pub const CM_DRP_CLASS: ::ULONG = 0x00000008; +pub const CM_DRP_CLASSGUID: ::ULONG = 0x00000009; +pub const CM_DRP_DRIVER: ::ULONG = 0x0000000A; +pub const CM_DRP_CONFIGFLAGS: ::ULONG = 0x0000000B; +pub const CM_DRP_MFG: ::ULONG = 0x0000000C; +pub const CM_DRP_FRIENDLYNAME: ::ULONG = 0x0000000D; +pub const CM_DRP_LOCATION_INFORMATION: ::ULONG = 0x0000000E; +pub const CM_DRP_PHYSICAL_DEVICE_OBJECT_NAME: ::ULONG = 0x0000000F; +pub const CM_DRP_CAPABILITIES: ::ULONG = 0x00000010; +pub const CM_DRP_UI_NUMBER: ::ULONG = 0x00000011; +pub const CM_DRP_UPPERFILTERS: ::ULONG = 0x00000012; +pub const CM_CRP_UPPERFILTERS: ::ULONG = CM_DRP_UPPERFILTERS; +pub const CM_DRP_LOWERFILTERS: ::ULONG = 0x00000013; +pub const CM_CRP_LOWERFILTERS: ::ULONG = CM_DRP_LOWERFILTERS; +pub const CM_DRP_BUSTYPEGUID: ::ULONG = 0x00000014; +pub const CM_DRP_LEGACYBUSTYPE: ::ULONG = 0x00000015; +pub const CM_DRP_BUSNUMBER: ::ULONG = 0x00000016; +pub const CM_DRP_ENUMERATOR_NAME: ::ULONG = 0x00000017; +pub const CM_DRP_SECURITY: ::ULONG = 0x00000018; +pub const CM_CRP_SECURITY: ::ULONG = CM_DRP_SECURITY; +pub const CM_DRP_SECURITY_SDS: ::ULONG = 0x00000019; +pub const CM_CRP_SECURITY_SDS: ::ULONG = CM_DRP_SECURITY_SDS; +pub const CM_DRP_DEVTYPE: ::ULONG = 0x0000001A; +pub const CM_CRP_DEVTYPE: ::ULONG = CM_DRP_DEVTYPE; +pub const CM_DRP_EXCLUSIVE: ::ULONG = 0x0000001B; +pub const CM_CRP_EXCLUSIVE: ::ULONG = CM_DRP_EXCLUSIVE; +pub const CM_DRP_CHARACTERISTICS: ::ULONG = 0x0000001C; +pub const CM_CRP_CHARACTERISTICS: ::ULONG = CM_DRP_CHARACTERISTICS; +pub const CM_DRP_ADDRESS: ::ULONG = 0x0000001D; +pub const CM_DRP_UI_NUMBER_DESC_FORMAT: ::ULONG = 0x0000001E; +pub const CM_DRP_DEVICE_POWER_DATA: ::ULONG = 0x0000001F; +pub const CM_DRP_REMOVAL_POLICY: ::ULONG = 0x00000020; +pub const CM_DRP_REMOVAL_POLICY_HW_DEFAULT: ::ULONG = 0x00000021; +pub const CM_DRP_REMOVAL_POLICY_OVERRIDE: ::ULONG = 0x00000022; +pub const CM_DRP_INSTALL_STATE: ::ULONG = 0x00000023; +pub const CM_DRP_LOCATION_PATHS: ::ULONG = 0x00000024; +pub const CM_DRP_BASE_CONTAINERID: ::ULONG = 0x00000025; +pub const CM_DRP_MIN: ::ULONG = 0x00000001; +pub const CM_CRP_MIN: ::ULONG = CM_DRP_MIN; +pub const CM_DRP_MAX: ::ULONG = 0x00000025; +pub const CM_CRP_MAX: ::ULONG = CM_DRP_MAX; +pub const CM_DEVCAP_LOCKSUPPORTED: ::ULONG = 0x00000001; +pub const CM_DEVCAP_EJECTSUPPORTED: ::ULONG = 0x00000002; +pub const CM_DEVCAP_REMOVABLE: ::ULONG = 0x00000004; +pub const CM_DEVCAP_DOCKDEVICE: ::ULONG = 0x00000008; +pub const CM_DEVCAP_UNIQUEID: ::ULONG = 0x00000010; +pub const CM_DEVCAP_SILENTINSTALL: ::ULONG = 0x00000020; +pub const CM_DEVCAP_RAWDEVICEOK: ::ULONG = 0x00000040; +pub const CM_DEVCAP_SURPRISEREMOVALOK: ::ULONG = 0x00000080; +pub const CM_DEVCAP_HARDWAREDISABLED: ::ULONG = 0x00000100; +pub const CM_DEVCAP_NONDYNAMIC: ::ULONG = 0x00000200; +pub const CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL: ::ULONG = 1; +pub const CM_REMOVAL_POLICY_EXPECT_ORDERLY_REMOVAL: ::ULONG = 2; +pub const CM_REMOVAL_POLICY_EXPECT_SURPRISE_REMOVAL: ::ULONG = 3; +pub const CM_INSTALL_STATE_INSTALLED: ::ULONG = 0; +pub const CM_INSTALL_STATE_NEEDS_REINSTALL: ::ULONG = 1; +pub const CM_INSTALL_STATE_FAILED_INSTALL: ::ULONG = 2; +pub const CM_INSTALL_STATE_FINISH_INSTALL: ::ULONG = 3; +pub const CM_LOCATE_DEVNODE_NORMAL: ::ULONG = 0x00000000; +pub const CM_LOCATE_DEVNODE_PHANTOM: ::ULONG = 0x00000001; +pub const CM_LOCATE_DEVNODE_CANCELREMOVE: ::ULONG = 0x00000002; +pub const CM_LOCATE_DEVNODE_NOVALIDATION: ::ULONG = 0x00000004; +pub const CM_LOCATE_DEVNODE_BITS: ::ULONG = 0x00000007; +pub const CM_LOCATE_DEVINST_NORMAL: ::ULONG = CM_LOCATE_DEVNODE_NORMAL; +pub const CM_LOCATE_DEVINST_PHANTOM: ::ULONG = CM_LOCATE_DEVNODE_PHANTOM; +pub const CM_LOCATE_DEVINST_CANCELREMOVE: ::ULONG = CM_LOCATE_DEVNODE_CANCELREMOVE; +pub const CM_LOCATE_DEVINST_NOVALIDATION: ::ULONG = CM_LOCATE_DEVNODE_NOVALIDATION; +pub const CM_LOCATE_DEVINST_BITS: ::ULONG = CM_LOCATE_DEVNODE_BITS; +pub const CM_OPEN_CLASS_KEY_INSTALLER: ::ULONG = 0x00000000; +pub const CM_OPEN_CLASS_KEY_INTERFACE: ::ULONG = 0x00000001; +pub const CM_OPEN_CLASS_KEY_BITS: ::ULONG = 0x00000001; +pub const CM_REMOVE_UI_OK: ::ULONG = 0x00000000; +pub const CM_REMOVE_UI_NOT_OK: ::ULONG = 0x00000001; +pub const CM_REMOVE_NO_RESTART: ::ULONG = 0x00000002; +pub const CM_REMOVE_BITS: ::ULONG = 0x00000003; +pub const CM_QUERY_REMOVE_UI_OK: ::ULONG = CM_REMOVE_UI_OK; +pub const CM_QUERY_REMOVE_UI_NOT_OK: ::ULONG = CM_REMOVE_UI_NOT_OK; +pub const CM_QUERY_REMOVE_BITS: ::ULONG = CM_QUERY_REMOVE_UI_OK | CM_QUERY_REMOVE_UI_NOT_OK; +pub const CM_REENUMERATE_NORMAL: ::ULONG = 0x00000000; +pub const CM_REENUMERATE_SYNCHRONOUS: ::ULONG = 0x00000001; +pub const CM_REENUMERATE_RETRY_INSTALLATION: ::ULONG = 0x00000002; +pub const CM_REENUMERATE_ASYNCHRONOUS: ::ULONG = 0x00000004; +pub const CM_REENUMERATE_BITS: ::ULONG = 0x00000007; +pub const CM_REGISTER_DEVICE_DRIVER_STATIC: ::ULONG = 0x00000000; +pub const CM_REGISTER_DEVICE_DRIVER_DISABLEABLE: ::ULONG = 0x00000001; +pub const CM_REGISTER_DEVICE_DRIVER_REMOVABLE: ::ULONG = 0x00000002; +pub const CM_REGISTER_DEVICE_DRIVER_BITS: ::ULONG = 0x00000003; +pub const CM_REGISTRY_HARDWARE: ::ULONG = 0x00000000; +pub const CM_REGISTRY_SOFTWARE: ::ULONG = 0x00000001; +pub const CM_REGISTRY_USER: ::ULONG = 0x00000100; +pub const CM_REGISTRY_CONFIG: ::ULONG = 0x00000200; +pub const CM_REGISTRY_BITS: ::ULONG = 0x00000301; +pub const CM_SET_DEVNODE_PROBLEM_NORMAL: ::ULONG = 0x00000000; +pub const CM_SET_DEVNODE_PROBLEM_OVERRIDE: ::ULONG = 0x00000001; +pub const CM_SET_DEVNODE_PROBLEM_BITS: ::ULONG = 0x00000001; +pub const CM_SET_DEVINST_PROBLEM_NORMAL: ::ULONG = CM_SET_DEVNODE_PROBLEM_NORMAL; +pub const CM_SET_DEVINST_PROBLEM_OVERRIDE: ::ULONG = CM_SET_DEVNODE_PROBLEM_OVERRIDE; +pub const CM_SET_DEVINST_PROBLEM_BITS: ::ULONG = CM_SET_DEVNODE_PROBLEM_BITS; +pub const CM_SET_HW_PROF_FLAGS_UI_NOT_OK: ::ULONG = 0x00000001; +pub const CM_SET_HW_PROF_FLAGS_BITS: ::ULONG = 0x00000001; +pub const CM_SETUP_DEVNODE_READY: ::ULONG = 0x00000000; +pub const CM_SETUP_DEVINST_READY: ::ULONG = CM_SETUP_DEVNODE_READY; +pub const CM_SETUP_DOWNLOAD: ::ULONG = 0x00000001; +pub const CM_SETUP_WRITE_LOG_CONFS: ::ULONG = 0x00000002; +pub const CM_SETUP_PROP_CHANGE: ::ULONG = 0x00000003; +pub const CM_SETUP_DEVNODE_RESET: ::ULONG = 0x00000004; +pub const CM_SETUP_DEVINST_RESET: ::ULONG = CM_SETUP_DEVNODE_RESET; +pub const CM_SETUP_DEVNODE_CONFIG: ::ULONG = 0x00000005; +pub const CM_SETUP_DEVINST_CONFIG: ::ULONG = CM_SETUP_DEVNODE_CONFIG; +pub const CM_SETUP_DEVNODE_CONFIG_CLASS: ::ULONG = 0x00000006; +pub const CM_SETUP_DEVINST_CONFIG_CLASS: ::ULONG = CM_SETUP_DEVNODE_CONFIG_CLASS; +pub const CM_SETUP_DEVNODE_CONFIG_EXTENSIONS: ::ULONG = 0x00000007; +pub const CM_SETUP_DEVINST_CONFIG_EXTENSIONS: ::ULONG = CM_SETUP_DEVNODE_CONFIG_EXTENSIONS; +pub const CM_SETUP_BITS: ::ULONG = 0x00000007; +pub const CM_QUERY_ARBITRATOR_RAW: ::ULONG = 0x00000000; +pub const CM_QUERY_ARBITRATOR_TRANSLATED: ::ULONG = 0x00000001; +pub const CM_QUERY_ARBITRATOR_BITS: ::ULONG = 0x00000001; +pub const CM_CUSTOMDEVPROP_MERGE_MULTISZ: ::ULONG = 0x00000001; +pub const CM_CUSTOMDEVPROP_BITS: ::ULONG = 0x00000001; +pub const CM_NAME_ATTRIBUTE_NAME_RETRIEVED_FROM_DEVICE: ::ULONG = 0x1; +pub const CM_NAME_ATTRIBUTE_USER_ASSIGNED_NAME: ::ULONG = 0x2; +pub const CM_CLASS_PROPERTY_INSTALLER: ::ULONG = 0x00000000; +pub const CM_CLASS_PROPERTY_INTERFACE: ::ULONG = 0x00000001; +pub const CM_CLASS_PROPERTY_BITS: ::ULONG = 0x00000001; +DECLARE_HANDLE!(HCMNOTIFICATION, HCMNOTIFICATION__); +pub type PHCMNOTIFICATION = *mut HCMNOTIFICATION; +pub const CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES: ::ULONG = 0x00000001; +pub const CM_NOTIFY_FILTER_FLAG_ALL_DEVICE_INSTANCES: ::ULONG = 0x00000002; +pub const CM_NOTIFY_FILTER_VALID_FLAGS: ::ULONG = CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES + | CM_NOTIFY_FILTER_FLAG_ALL_DEVICE_INSTANCES; +ENUM!{enum CM_NOTIFY_FILTER_TYPE { + CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE = 0, + CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE, + CM_NOTIFY_FILTER_TYPE_DEVICEINSTANCE, + CM_NOTIFY_FILTER_TYPE_MAX, +}} +pub type PCM_NOTIFY_FILTER_TYPE = *mut CM_NOTIFY_FILTER_TYPE; +STRUCT!{struct CM_NOTIFY_FILTER_DeviceInterface { + ClassGuid: ::GUID, +}} +STRUCT!{struct CM_NOTIFY_FILTER_DeviceHandle { + hTarget: ::HANDLE, +}} +STRUCT!{nodebug struct CM_NOTIFY_FILTER_DeviceInstance { + InstanceId: [::WCHAR; MAX_DEVICE_ID_LEN], +}} +STRUCT!{nodebug struct CM_NOTIFY_FILTER { + cbSize: ::DWORD, + Flags: ::DWORD, + FilterType: CM_NOTIFY_FILTER_TYPE, + Reserved: ::DWORD, + u: [::BYTE; 400], +}} +UNION!(CM_NOTIFY_FILTER, u, DeviceInterface, DeviceInterface_mut, CM_NOTIFY_FILTER_DeviceInterface); +UNION!(CM_NOTIFY_FILTER, u, DeviceHandle, DeviceHandle_mut, CM_NOTIFY_FILTER_DeviceHandle); +UNION!(CM_NOTIFY_FILTER, u, DeviceInstance, DeviceInstance_mut, CM_NOTIFY_FILTER_DeviceInstance); +pub type PCM_NOTIFY_FILTER = *mut CM_NOTIFY_FILTER; +ENUM!{enum CM_NOTIFY_ACTION { + CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL = 0, + CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVE, + CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED, + CM_NOTIFY_ACTION_DEVICEREMOVEPENDING, + CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE, + CM_NOTIFY_ACTION_DEVICECUSTOMEVENT, + CM_NOTIFY_ACTION_DEVICEINSTANCEENUMERATED, + CM_NOTIFY_ACTION_DEVICEINSTANCESTARTED, + CM_NOTIFY_ACTION_DEVICEINSTANCEREMOVED, + CM_NOTIFY_ACTION_MAX, +}} +pub type PCM_NOTIFY_ACTION = *mut CM_NOTIFY_ACTION; +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceInterface { + ClassGuid: ::GUID, + SymbolicLink: [::WCHAR; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceHandle { + EventGuid: ::GUID, + NameOffset: ::LONG, + DataSize: ::DWORD, + Data: [::BYTE; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA_DeviceInstance { + InstanceId: [::WCHAR; ::ANYSIZE_ARRAY], +}} +STRUCT!{struct CM_NOTIFY_EVENT_DATA { + FilterType: CM_NOTIFY_FILTER_TYPE, + Reserved: ::DWORD, + u: [::BYTE; 25], +}} +UNION!( + CM_NOTIFY_EVENT_DATA, u, DeviceInterface, DeviceInterface_mut, + CM_NOTIFY_EVENT_DATA_DeviceInterface +); +UNION!(CM_NOTIFY_EVENT_DATA, u, DeviceHandle, DeviceHandle_mut, CM_NOTIFY_EVENT_DATA_DeviceHandle); +UNION!( + CM_NOTIFY_EVENT_DATA, u, DeviceInstance, DeviceInstance_mut, CM_NOTIFY_EVENT_DATA_DeviceInstance +); +pub type PCM_NOTIFY_EVENT_DATA = *mut CM_NOTIFY_EVENT_DATA; +pub type PCM_NOTIFY_CALLBACK = Option ::DWORD>; +pub const CR_SUCCESS: CONFIGRET = 0x00000000; +pub const CR_DEFAULT: CONFIGRET = 0x00000001; +pub const CR_OUT_OF_MEMORY: CONFIGRET = 0x00000002; +pub const CR_INVALID_POINTER: CONFIGRET = 0x00000003; +pub const CR_INVALID_FLAG: CONFIGRET = 0x00000004; +pub const CR_INVALID_DEVNODE: CONFIGRET = 0x00000005; +pub const CR_INVALID_DEVINST: CONFIGRET = CR_INVALID_DEVNODE; +pub const CR_INVALID_RES_DES: CONFIGRET = 0x00000006; +pub const CR_INVALID_LOG_CONF: CONFIGRET = 0x00000007; +pub const CR_INVALID_ARBITRATOR: CONFIGRET = 0x00000008; +pub const CR_INVALID_NODELIST: CONFIGRET = 0x00000009; +pub const CR_DEVNODE_HAS_REQS: CONFIGRET = 0x0000000A; +pub const CR_DEVINST_HAS_REQS: CONFIGRET = CR_DEVNODE_HAS_REQS; +pub const CR_INVALID_RESOURCEID: CONFIGRET = 0x0000000B; +pub const CR_DLVXD_NOT_FOUND: CONFIGRET = 0x0000000C; +pub const CR_NO_SUCH_DEVNODE: CONFIGRET = 0x0000000D; +pub const CR_NO_SUCH_DEVINST: CONFIGRET = CR_NO_SUCH_DEVNODE; +pub const CR_NO_MORE_LOG_CONF: CONFIGRET = 0x0000000E; +pub const CR_NO_MORE_RES_DES: CONFIGRET = 0x0000000F; +pub const CR_ALREADY_SUCH_DEVNODE: CONFIGRET = 0x00000010; +pub const CR_ALREADY_SUCH_DEVINST: CONFIGRET = CR_ALREADY_SUCH_DEVNODE; +pub const CR_INVALID_RANGE_LIST: CONFIGRET = 0x00000011; +pub const CR_INVALID_RANGE: CONFIGRET = 0x00000012; +pub const CR_FAILURE: CONFIGRET = 0x00000013; +pub const CR_NO_SUCH_LOGICAL_DEV: CONFIGRET = 0x00000014; +pub const CR_CREATE_BLOCKED: CONFIGRET = 0x00000015; +pub const CR_NOT_SYSTEM_VM: CONFIGRET = 0x00000016; +pub const CR_REMOVE_VETOED: CONFIGRET = 0x00000017; +pub const CR_APM_VETOED: CONFIGRET = 0x00000018; +pub const CR_INVALID_LOAD_TYPE: CONFIGRET = 0x00000019; +pub const CR_BUFFER_SMALL: CONFIGRET = 0x0000001A; +pub const CR_NO_ARBITRATOR: CONFIGRET = 0x0000001B; +pub const CR_NO_REGISTRY_HANDLE: CONFIGRET = 0x0000001C; +pub const CR_REGISTRY_ERROR: CONFIGRET = 0x0000001D; +pub const CR_INVALID_DEVICE_ID: CONFIGRET = 0x0000001E; +pub const CR_INVALID_DATA: CONFIGRET = 0x0000001F; +pub const CR_INVALID_API: CONFIGRET = 0x00000020; +pub const CR_DEVLOADER_NOT_READY: CONFIGRET = 0x00000021; +pub const CR_NEED_RESTART: CONFIGRET = 0x00000022; +pub const CR_NO_MORE_HW_PROFILES: CONFIGRET = 0x00000023; +pub const CR_DEVICE_NOT_THERE: CONFIGRET = 0x00000024; +pub const CR_NO_SUCH_VALUE: CONFIGRET = 0x00000025; +pub const CR_WRONG_TYPE: CONFIGRET = 0x00000026; +pub const CR_INVALID_PRIORITY: CONFIGRET = 0x00000027; +pub const CR_NOT_DISABLEABLE: CONFIGRET = 0x00000028; +pub const CR_FREE_RESOURCES: CONFIGRET = 0x00000029; +pub const CR_QUERY_VETOED: CONFIGRET = 0x0000002A; +pub const CR_CANT_SHARE_IRQ: CONFIGRET = 0x0000002B; +pub const CR_NO_DEPENDENT: CONFIGRET = 0x0000002C; +pub const CR_SAME_RESOURCES: CONFIGRET = 0x0000002D; +pub const CR_NO_SUCH_REGISTRY_KEY: CONFIGRET = 0x0000002E; +pub const CR_INVALID_MACHINENAME: CONFIGRET = 0x0000002F; +pub const CR_REMOTE_COMM_FAILURE: CONFIGRET = 0x00000030; +pub const CR_MACHINE_UNAVAILABLE: CONFIGRET = 0x00000031; +pub const CR_NO_CM_SERVICES: CONFIGRET = 0x00000032; +pub const CR_ACCESS_DENIED: CONFIGRET = 0x00000033; +pub const CR_CALL_NOT_IMPLEMENTED: CONFIGRET = 0x00000034; +pub const CR_INVALID_PROPERTY: CONFIGRET = 0x00000035; +pub const CR_DEVICE_INTERFACE_ACTIVE: CONFIGRET = 0x00000036; +pub const CR_NO_SUCH_DEVICE_INTERFACE: CONFIGRET = 0x00000037; +pub const CR_INVALID_REFERENCE_STRING: CONFIGRET = 0x00000038; +pub const CR_INVALID_CONFLICT_LIST: CONFIGRET = 0x00000039; +pub const CR_INVALID_INDEX: CONFIGRET = 0x0000003A; +pub const CR_INVALID_STRUCTURE_SIZE: CONFIGRET = 0x0000003B; +pub const NUM_CR_RESULTS: CONFIGRET = 0x0000003C; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/combaseapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/combaseapi.rs new file mode 100644 index 0000000..9233bc5 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/combaseapi.rs @@ -0,0 +1,17 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub const CLSCTX_INPROC_SERVER: DWORD = 0x1; +pub const CLSCTX_INPROC_HANDLER: DWORD = 0x2; +pub const CLSCTX_LOCAL_SERVER: DWORD = 0x4; +pub const CLSCTX_REMOTE_SERVER: DWORD = 0x10; +pub const CLSCTX_SERVER: DWORD = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | + CLSCTX_REMOTE_SERVER; +pub const CLSCTX_ALL: DWORD = CLSCTX_INPROC_HANDLER | CLSCTX_SERVER; +STRUCT!{struct ServerInformation { + dwServerPid: DWORD, + dwServerTid: DWORD, + ui64ServerAddress: UINT64, +}} +pub type PServerInformation = *mut ServerInformation; +DECLARE_HANDLE!(CO_MTA_USAGE_COOKIE, CO_MTA_USAGE_COOKIE__); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/commctrl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/commctrl.rs new file mode 100644 index 0000000..88513e1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/commctrl.rs @@ -0,0 +1,3578 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//138 +STRUCT!{struct INITCOMMONCONTROLSEX { + dwSize: ::DWORD, + dwICC: ::DWORD, +}} +pub type LPINITCOMMONCONTROLSEX = *mut INITCOMMONCONTROLSEX; +pub const ICC_LISTVIEW_CLASSES: ::DWORD = 0x1; +pub const ICC_TREEVIEW_CLASSES: ::DWORD = 0x2; +pub const ICC_BAR_CLASSES: ::DWORD = 0x4; +pub const ICC_TAB_CLASSES: ::DWORD = 0x8; +pub const ICC_UPDOWN_CLASS: ::DWORD = 0x10; +pub const ICC_PROGRESS_CLASS: ::DWORD = 0x20; +pub const ICC_HOTKEY_CLASS: ::DWORD = 0x40; +pub const ICC_ANIMATE_CLASS: ::DWORD = 0x80; +pub const ICC_WIN95_CLASSES: ::DWORD = 0xFF; +pub const ICC_DATE_CLASSES: ::DWORD = 0x100; +pub const ICC_USEREX_CLASSES: ::DWORD = 0x200; +pub const ICC_COOL_CLASSES: ::DWORD = 0x400; +pub const ICC_INTERNET_CLASSES: ::DWORD = 0x800; +pub const ICC_PAGESCROLLER_CLASS: ::DWORD = 0x1000; +pub const ICC_NATIVEFNTCTL_CLASS: ::DWORD = 0x2000; +pub const ICC_STANDARD_CLASSES: ::DWORD = 0x4000; +pub const ICC_LINK_CLASS: ::DWORD = 0x8000; +pub const ODT_HEADER: ::UINT = 100; +pub const ODT_TAB: ::UINT = 101; +pub const ODT_LISTVIEW: ::UINT = 102; +pub const LVM_FIRST: ::UINT = 0x1000; +pub const TV_FIRST: ::UINT = 0x1100; +pub const HDM_FIRST: ::UINT = 0x1200; +pub const TCM_FIRST: ::UINT = 0x1300; +pub const PGM_FIRST: ::UINT = 0x1400; +pub const ECM_FIRST: ::UINT = 0x1500; +pub const BCM_FIRST: ::UINT = 0x1600; +pub const CBM_FIRST: ::UINT = 0x1700; +pub const CCM_FIRST: ::UINT = 0x2000; +pub const CCM_LAST: ::UINT = CCM_FIRST + 0x200; +pub const CCM_SETBKCOLOR: ::UINT = CCM_FIRST + 1; +STRUCT!{struct COLORSCHEME { + dwSize: ::DWORD, + clrBtnHighlight: ::COLORREF, + clrBtnShadow: ::COLORREF, +}} +pub type LPCOLORSCHEME = *mut COLORSCHEME; +pub const CCM_SETCOLORSCHEME: ::UINT = CCM_FIRST + 2; +pub const CCM_GETCOLORSCHEME: ::UINT = CCM_FIRST + 3; +pub const CCM_GETDROPTARGET: ::UINT = CCM_FIRST + 4; +pub const CCM_SETUNICODEFORMAT: ::UINT = CCM_FIRST + 5; +pub const CCM_GETUNICODEFORMAT: ::UINT = CCM_FIRST + 6; +pub const CCM_SETVERSION: ::UINT = CCM_FIRST + 7; +pub const CCM_GETVERSION: ::UINT = CCM_FIRST + 8; +pub const CCM_SETNOTIFYWINDOW: ::UINT = CCM_FIRST + 9; +pub const CCM_SETWINDOWTHEME: ::UINT = CCM_FIRST + 0xb; +pub const CCM_DPISCALE: ::UINT = CCM_FIRST + 0xc; +pub const INFOTIPSIZE: ::c_int = 1024; +pub const NM_OUTOFMEMORY: ::UINT = (NM_FIRST as ::INT - 1) as ::UINT; +pub const NM_CLICK: ::UINT = (NM_FIRST as ::INT - 2) as ::UINT; +pub const NM_DBLCLK: ::UINT = (NM_FIRST as ::INT - 3) as ::UINT; +pub const NM_RETURN: ::UINT = (NM_FIRST as ::INT - 4) as ::UINT; +pub const NM_RCLICK: ::UINT = (NM_FIRST as ::INT - 5) as ::UINT; +pub const NM_RDBLCLK: ::UINT = (NM_FIRST as ::INT - 6) as ::UINT; +pub const NM_SETFOCUS: ::UINT = (NM_FIRST as ::INT - 7) as ::UINT; +pub const NM_KILLFOCUS: ::UINT = (NM_FIRST as ::INT - 8) as ::UINT; +pub const NM_CUSTOMDRAW: ::UINT = (NM_FIRST as ::INT - 12) as ::UINT; +pub const NM_HOVER: ::UINT = (NM_FIRST as ::INT - 13) as ::UINT; +pub const NM_NCHITTEST: ::UINT = (NM_FIRST as ::INT - 14) as ::UINT; +pub const NM_KEYDOWN: ::UINT = (NM_FIRST as ::INT - 15) as ::UINT; +pub const NM_RELEASEDCAPTURE: ::UINT = (NM_FIRST as ::INT - 16) as ::UINT; +pub const NM_SETCURSOR: ::UINT = (NM_FIRST as ::INT - 17) as ::UINT; +pub const NM_CHAR: ::UINT = (NM_FIRST as ::INT - 18) as ::UINT; +pub const NM_TOOLTIPSCREATED: ::UINT = (NM_FIRST as ::INT - 19) as ::UINT; +pub const NM_LDOWN: ::UINT = (NM_FIRST as ::INT - 20) as ::UINT; +pub const NM_RDOWN: ::UINT = (NM_FIRST as ::INT - 21) as ::UINT; +pub const NM_THEMECHANGED: ::UINT = (NM_FIRST as ::INT - 22) as ::UINT; +pub const NM_FONTCHANGED: ::UINT = (NM_FIRST as ::INT - 23) as ::UINT; +pub const NM_CUSTOMTEXT: ::UINT = (NM_FIRST as ::INT - 24) as ::UINT; +pub const NM_TVSTATEIMAGECHANGING: ::UINT = (NM_FIRST as ::INT - 24) as ::UINT; +STRUCT!{struct NMTOOLTIPSCREATED { + hdr: ::NMHDR, + hwndToolTips: ::HWND, +}} +pub type LPNMTOOLTIPSCREATED = *mut NMTOOLTIPSCREATED; +STRUCT!{struct NMMOUSE { + hdr : ::NMHDR, + dwItemSpec: ::DWORD_PTR, + dwItemData: ::DWORD_PTR, + pt: ::POINT, + dwHitInfo: ::LPARAM, +}} +pub type LPNMMOUSE = *mut NMMOUSE; +pub type NMCLICK = NMMOUSE; +pub type LPNMCLICK = LPNMMOUSE; +STRUCT!{struct NMOBJECTNOTIFY { + hdr: ::NMHDR, + iItem: ::c_int, + piid: *const ::IID, + pObject: *mut ::c_void, + hResult: ::HRESULT, + dwFlags: ::DWORD, +}} +pub type LPNMOBJECTNOTIFY = *mut NMOBJECTNOTIFY; +STRUCT!{struct NMKEY { + hdr: ::NMHDR, + nVKey: ::UINT, + uFlags: ::UINT, +}} +pub type LPNMKEY = *mut NMKEY; +STRUCT!{struct NMCHAR { + hdr: ::NMHDR, + ch: ::UINT, + dwItemPrev: ::DWORD, + dwItemNext: ::DWORD, +}} +pub type LPNMCHAR = *mut NMCHAR; +STRUCT!{struct NMCUSTOMTEXT { + hdr: ::NMHDR, + hDC: ::HDC, + lpString: ::LPCWSTR, + nCount: ::c_int, + lpRect: ::LPRECT, + uFormat: ::UINT, + fLink: ::BOOL, +}} +pub type LPNMCUSTOMTEXT = *mut NMCUSTOMTEXT; +pub const NM_FIRST: ::UINT = 0; +pub const NM_LAST: ::UINT = -99i32 as ::UINT; +pub const LVN_FIRST: ::UINT = -100i32 as ::UINT; +pub const LVN_LAST: ::UINT = -199i32 as ::UINT; +pub const HDN_FIRST: ::UINT = -300i32 as ::UINT; +pub const HDN_LAST: ::UINT = -399i32 as ::UINT; +pub const TVN_FIRST: ::UINT = -400i32 as ::UINT; +pub const TVN_LAST: ::UINT = -499i32 as ::UINT; +pub const TTN_FIRST: ::UINT = -520i32 as ::UINT; +pub const TTN_LAST: ::UINT = -549i32 as ::UINT; +pub const TCN_FIRST: ::UINT = -550i32 as ::UINT; +pub const TCN_LAST: ::UINT = -580i32 as ::UINT; +// pub const CDN_FIRST: ::UINT = 0 - 601; +// pub const CDN_LAST: ::UINT = 0 - 699; +pub const TBN_FIRST: ::UINT = -700i32 as ::UINT; +pub const TBN_LAST: ::UINT = -720i32 as ::UINT; +pub const UDN_FIRST: ::UINT = -721i32 as ::UINT; +pub const UDN_LAST: ::UINT = -729i32 as ::UINT; +pub const DTN_FIRST: ::UINT = -740i32 as ::UINT; +pub const DTN_LAST: ::UINT = -745i32 as ::UINT; +pub const MCN_FIRST: ::UINT = -746i32 as ::UINT; +pub const MCN_LAST: ::UINT = -752i32 as ::UINT; +pub const DTN_FIRST2: ::UINT = -753i32 as ::UINT; +pub const DTN_LAST2: ::UINT = -799i32 as ::UINT; +pub const CBEN_FIRST: ::UINT = -800i32 as ::UINT; +pub const CBEN_LAST: ::UINT = -830i32 as ::UINT; +pub const RBN_FIRST: ::UINT = -831i32 as ::UINT; +pub const RBN_LAST: ::UINT = -859i32 as ::UINT; +pub const IPN_FIRST: ::UINT = -860i32 as ::UINT; +pub const IPN_LAST: ::UINT = -879i32 as ::UINT; +pub const SBN_FIRST: ::UINT = -880i32 as ::UINT; +pub const SBN_LAST: ::UINT = -899i32 as ::UINT; +pub const PGN_FIRST: ::UINT = -900i32 as ::UINT; +pub const PGN_LAST: ::UINT = -950i32 as ::UINT; +pub const WMN_FIRST: ::UINT = -1000i32 as ::UINT; +pub const WMN_LAST: ::UINT = -1200i32 as ::UINT; +pub const BCN_FIRST: ::UINT = -1250i32 as ::UINT; +pub const BCN_LAST: ::UINT = -1350i32 as ::UINT; +pub const TRBN_FIRST: ::UINT = -1501i32 as ::UINT; +pub const TRBN_LAST: ::UINT = -1519i32 as ::UINT; +pub const CDRF_DODEFAULT: ::LRESULT = 0x00000000; +pub const CDRF_NEWFONT: ::LRESULT = 0x00000002; +pub const CDRF_SKIPDEFAULT: ::LRESULT = 0x00000004; +pub const CDRF_DOERASE: ::LRESULT = 0x00000008; +pub const CDRF_SKIPPOSTPAINT: ::LRESULT = 0x00000100; +pub const CDRF_NOTIFYPOSTPAINT: ::LRESULT = 0x00000010; +pub const CDRF_NOTIFYITEMDRAW: ::LRESULT = 0x00000020; +pub const CDRF_NOTIFYSUBITEMDRAW: ::LRESULT = 0x00000020; +pub const CDRF_NOTIFYPOSTERASE: ::LRESULT = 0x00000040; +pub const CDDS_PREPAINT: ::DWORD = 0x00000001; +pub const CDDS_POSTPAINT: ::DWORD = 0x00000002; +pub const CDDS_PREERASE: ::DWORD = 0x00000003; +pub const CDDS_POSTERASE: ::DWORD = 0x00000004; +pub const CDDS_ITEM: ::DWORD = 0x00010000; +pub const CDDS_ITEMPREPAINT: ::DWORD = CDDS_ITEM | CDDS_PREPAINT; +pub const CDDS_ITEMPOSTPAINT: ::DWORD = CDDS_ITEM | CDDS_POSTPAINT; +pub const CDDS_ITEMPREERASE: ::DWORD = CDDS_ITEM | CDDS_PREERASE; +pub const CDDS_ITEMPOSTERASE: ::DWORD = CDDS_ITEM | CDDS_POSTERASE; +pub const CDDS_SUBITEM: ::DWORD = 0x00020000; +pub const CDIS_SELECTED: ::UINT = 0x0001; +pub const CDIS_GRAYED: ::UINT = 0x0002; +pub const CDIS_DISABLED: ::UINT = 0x0004; +pub const CDIS_CHECKED: ::UINT = 0x0008; +pub const CDIS_FOCUS: ::UINT = 0x0010; +pub const CDIS_DEFAULT: ::UINT = 0x0020; +pub const CDIS_HOT: ::UINT = 0x0040; +pub const CDIS_MARKED: ::UINT = 0x0080; +pub const CDIS_INDETERMINATE: ::UINT = 0x0100; +pub const CDIS_SHOWKEYBOARDCUES: ::UINT = 0x0200; +pub const CDIS_NEARHOT: ::UINT = 0x0400; +pub const CDIS_OTHERSIDEHOT: ::UINT = 0x0800; +pub const CDIS_DROPHILITED: ::UINT = 0x1000; +STRUCT!{struct NMCUSTOMDRAW { + hdr: ::NMHDR, + dwDrawStage: ::DWORD, + hdc: ::HDC, + rc: ::RECT, + dwItemSpec: ::DWORD_PTR, + uItemState: ::UINT, + lItemlParam: ::LPARAM, +}} +pub type LPNMCUSTOMDRAW = *mut NMCUSTOMDRAW; +STRUCT!{struct NMTTCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + uDrawFlags: ::UINT, +}} +pub type LPNMTTCUSTOMDRAW = *mut NMTTCUSTOMDRAW; +STRUCT!{struct NMCUSTOMSPLITRECTINFO { + hdr: ::NMHDR, + rcClient: ::RECT, + rcButton: ::RECT, + rcSplit: ::RECT, +}} +pub type LPNMCUSTOMSPLITRECTINFO = *mut NMCUSTOMSPLITRECTINFO; +pub const NM_GETCUSTOMSPLITRECT: ::UINT = BCN_FIRST + 0x0003; +pub const CLR_NONE: ::DWORD = 0xFFFFFFFF; +pub const CLR_DEFAULT: ::DWORD = 0xFF000000; +pub enum IMAGELIST {} +pub type HIMAGELIST = *mut IMAGELIST; +STRUCT!{struct IMAGELISTDRAWPARAMS { + cbSize: ::DWORD, + himl: HIMAGELIST, + i: ::c_int, + hdcDst: ::HDC, + x: ::c_int, + y: ::c_int, + cx: ::c_int, + cy: ::c_int, + xBitmap: ::c_int, + yBitmap: ::c_int, + rgbBk: ::COLORREF, + rgbFg: ::COLORREF, + fStyle: ::UINT, + dwRop: ::DWORD, + fState: ::DWORD, + Frame: ::DWORD, + crEffect: ::COLORREF, +}} +pub type LPIMAGELISTDRAWPARAMS = *mut IMAGELISTDRAWPARAMS; +pub const ILC_MASK: ::UINT = 0x00000001; +pub const ILC_COLOR: ::UINT = 0x00000000; +pub const ILC_COLORDDB: ::UINT = 0x000000FE; +pub const ILC_COLOR4: ::UINT = 0x00000004; +pub const ILC_COLOR8: ::UINT = 0x00000008; +pub const ILC_COLOR16: ::UINT = 0x00000010; +pub const ILC_COLOR24: ::UINT = 0x00000018; +pub const ILC_COLOR32: ::UINT = 0x00000020; +pub const ILC_PALETTE: ::UINT = 0x00000800; +pub const ILC_MIRROR: ::UINT = 0x00002000; +pub const ILC_PERITEMMIRROR: ::UINT = 0x00008000; +pub const ILC_ORIGINALSIZE: ::UINT = 0x00010000; +pub const ILC_HIGHQUALITYSCALE: ::UINT = 0x00020000; +pub const ILD_NORMAL: ::UINT = 0x00000000; +pub const ILD_TRANSPARENT: ::UINT = 0x00000001; +pub const ILD_MASK: ::UINT = 0x00000010; +pub const ILD_IMAGE: ::UINT = 0x00000020; +pub const ILD_ROP: ::UINT = 0x00000040; +pub const ILD_BLEND25: ::UINT = 0x00000002; +pub const ILD_BLEND50: ::UINT = 0x00000004; +pub const ILD_OVERLAYMASK: ::UINT = 0x00000F00; +#[inline] #[allow(dead_code)] +pub fn INDEXTOOVERLAYMASK(i: ::UINT) -> ::UINT { i << 8 } +pub const ILD_PRESERVEALPHA: ::UINT = 0x00001000; +pub const ILD_SCALE: ::UINT = 0x00002000; +pub const ILD_DPISCALE: ::UINT = 0x00004000; +pub const ILD_ASYNC: ::UINT = 0x00008000; +pub const ILD_SELECTED: ::UINT = ILD_BLEND50; +pub const ILD_FOCUS: ::UINT = ILD_BLEND25; +pub const ILD_BLEND: ::UINT = ILD_BLEND50; +pub const CLR_HILIGHT: ::DWORD = CLR_DEFAULT; +pub const ILS_NORMAL: ::DWORD = 0x00000000; +pub const ILS_GLOW: ::DWORD = 0x00000001; +pub const ILS_SHADOW: ::DWORD = 0x00000002; +pub const ILS_SATURATE: ::DWORD = 0x00000004; +pub const ILS_ALPHA: ::DWORD = 0x00000008; +pub const HBITMAP_CALLBACK: ::HBITMAP = (0-1) as ::HBITMAP; +pub const ILCF_MOVE: ::UINT = 0x00000000; +pub const ILCF_SWAP: ::UINT = 0x00000001; +STRUCT!{struct IMAGEINFO { + hbmImage: ::HBITMAP, + hbmMask: ::HBITMAP, + Unused1: ::c_int, + Unused2: ::c_int, + rcImage: ::RECT, +}} +pub type LPIMAGEINFO = *mut IMAGEINFO; +pub const HDS_HORZ: ::DWORD = 0x0000; +pub const HDS_BUTTONS: ::DWORD = 0x0002; +pub const HDS_HOTTRACK: ::DWORD = 0x0004; +pub const HDS_HIDDEN: ::DWORD = 0x0008; +pub const HDS_DRAGDROP: ::DWORD = 0x0040; +pub const HDS_FULLDRAG: ::DWORD = 0x0080; +pub const HDS_FILTERBAR: ::DWORD = 0x0100; +pub const HDS_FLAT: ::DWORD = 0x0200; +pub const HDS_CHECKBOXES: ::DWORD = 0x0400; +pub const HDS_NOSIZING: ::DWORD = 0x0800; +pub const HDS_OVERFLOW: ::DWORD = 0x1000; +pub const HDFT_ISSTRING: ::UINT = 0x0000; +pub const HDFT_ISNUMBER: ::UINT = 0x0001; +pub const HDFT_ISDATE: ::UINT = 0x0002; +pub const HDFT_HASNOVALUE: ::UINT = 0x8000; +STRUCT!{struct HD_TEXTFILTERA { + pszText: ::LPSTR, + cchTextMax: ::INT, +}} +pub type LPHD_TEXTFILTERA = *mut HD_TEXTFILTERA; +STRUCT!{struct HD_TEXTFILTERW { + pszText: ::LPWSTR, + cchTextMax: ::INT, +}} +pub type LPHD_TEXTFILTERW = *mut HD_TEXTFILTERW; +STRUCT!{struct HDITEMA { + mask: ::UINT, + cxy: ::c_int, + pszText: ::LPSTR, + hbm: ::HBITMAP, + cchTextMax: ::c_int, + fmt: ::c_int, + lParam: ::LPARAM, + iImage: ::c_int, + iOrder: ::c_int, + _type: ::UINT, + pvFilter: *mut ::c_void, + state: ::UINT, +}} +pub type LPHDITEMA = *mut HDITEMA; +STRUCT!{struct HDITEMW { + mask: ::UINT, + cxy: ::c_int, + pszText: ::LPWSTR, + hbm: ::HBITMAP, + cchTextMax: ::c_int, + fmt: ::c_int, + lParam: ::LPARAM, + iImage: ::c_int, + iOrder: ::c_int, + _type: ::UINT, + pvFilter: *mut ::c_void, + state: ::UINT, +}} +pub type LPHDITEMW = *mut HDITEMW; +pub const HDI_WIDTH: ::UINT = 0x0001; +pub const HDI_HEIGHT: ::UINT = HDI_WIDTH; +pub const HDI_TEXT: ::UINT = 0x0002; +pub const HDI_FORMAT: ::UINT = 0x0004; +pub const HDI_LPARAM: ::UINT = 0x0008; +pub const HDI_BITMAP: ::UINT = 0x0010; +pub const HDI_IMAGE: ::UINT = 0x0020; +pub const HDI_DI_SETITEM: ::UINT = 0x0040; +pub const HDI_ORDER: ::UINT = 0x0080; +pub const HDI_FILTER: ::UINT = 0x0100; +pub const HDI_STATE: ::UINT = 0x0200; +pub const HDF_LEFT: ::c_int = 0x0000; +pub const HDF_RIGHT: ::c_int = 0x0001; +pub const HDF_CENTER: ::c_int = 0x0002; +pub const HDF_JUSTIFYMASK: ::c_int = 0x0003; +pub const HDF_RTLREADING: ::c_int = 0x0004; +pub const HDF_BITMAP: ::c_int = 0x2000; +pub const HDF_STRING: ::c_int = 0x4000; +pub const HDF_OWNERDRAW: ::c_int = 0x8000; +pub const HDF_IMAGE: ::c_int = 0x0800; +pub const HDF_BITMAP_ON_RIGHT: ::c_int = 0x1000; +pub const HDF_SORTUP: ::c_int = 0x0400; +pub const HDF_SORTDOWN: ::c_int = 0x0200; +pub const HDF_CHECKBOX: ::c_int = 0x0040; +pub const HDF_CHECKED: ::c_int = 0x0080; +pub const HDF_FIXEDWIDTH: ::c_int = 0x0100; +pub const HDF_SPLITBUTTON: ::c_int = 0x1000000; +pub const HDIS_FOCUSED: ::UINT = 0x00000001; +pub const HDM_GETITEMCOUNT: ::UINT = HDM_FIRST + 0; +pub const HDM_INSERTITEMA: ::UINT = HDM_FIRST + 1; +pub const HDM_INSERTITEMW: ::UINT = HDM_FIRST + 10; +pub const HDM_DELETEITEM: ::UINT = HDM_FIRST + 2; +pub const HDM_GETITEMA: ::UINT = HDM_FIRST + 3; +pub const HDM_GETITEMW: ::UINT = HDM_FIRST + 11; +pub const HDM_SETITEMA: ::UINT = HDM_FIRST + 4; +pub const HDM_SETITEMW: ::UINT = HDM_FIRST + 12; +STRUCT!{struct HDLAYOUT { + prc: *mut ::RECT, + pwpos: *mut ::WINDOWPOS, +}} +pub type LPHDLAYOUT = *mut HDLAYOUT; +pub const HDM_LAYOUT: ::UINT = HDM_FIRST + 5; +pub const HHT_NOWHERE: ::UINT = 0x0001; +pub const HHT_ONHEADER: ::UINT = 0x0002; +pub const HHT_ONDIVIDER: ::UINT = 0x0004; +pub const HHT_ONDIVOPEN: ::UINT = 0x0008; +pub const HHT_ONFILTER: ::UINT = 0x0010; +pub const HHT_ONFILTERBUTTON: ::UINT = 0x0020; +pub const HHT_ABOVE: ::UINT = 0x0100; +pub const HHT_BELOW: ::UINT = 0x0200; +pub const HHT_TORIGHT: ::UINT = 0x0400; +pub const HHT_TOLEFT: ::UINT = 0x0800; +pub const HHT_ONITEMSTATEICON: ::UINT = 0x1000; +pub const HHT_ONDROPDOWN: ::UINT = 0x2000; +pub const HHT_ONOVERFLOW: ::UINT = 0x4000; +STRUCT!{struct HDHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iItem: ::c_int, +}} +pub type LPHDHITTESTINFO = *mut HDHITTESTINFO; +pub const HDSIL_NORMAL: ::WPARAM = 0; +pub const HDSIL_STATE: ::WPARAM = 1; +pub const HDM_HITTEST: ::UINT = HDM_FIRST + 6; +pub const HDM_GETITEMRECT: ::UINT = HDM_FIRST + 7; +pub const HDM_SETIMAGELIST: ::UINT = HDM_FIRST + 8; +pub const HDM_GETIMAGELIST: ::UINT = HDM_FIRST + 9; +pub const HDM_ORDERTOINDEX: ::UINT = HDM_FIRST + 15; +pub const HDM_CREATEDRAGIMAGE: ::UINT = HDM_FIRST + 16; +pub const HDM_GETORDERARRAY: ::UINT = HDM_FIRST + 17; +pub const HDM_SETORDERARRAY: ::UINT = HDM_FIRST + 18; +pub const HDM_SETHOTDIVIDER: ::UINT = HDM_FIRST + 19; +pub const HDM_SETBITMAPMARGIN: ::UINT = HDM_FIRST + 20; +pub const HDM_GETBITMAPMARGIN: ::UINT = HDM_FIRST + 21; +pub const HDM_SETFILTERCHANGETIMEOUT: ::UINT = HDM_FIRST + 22; +pub const HDM_EDITFILTER: ::UINT = HDM_FIRST + 23; +pub const HDM_CLEARFILTER: ::UINT = HDM_FIRST + 24; +pub const HDM_GETITEMDROPDOWNRECT: ::UINT = HDM_FIRST + 25; +pub const HDM_GETOVERFLOWRECT: ::UINT = HDM_FIRST + 26; +pub const HDM_GETFOCUSEDITEM: ::UINT = HDM_FIRST + 27; +pub const HDM_SETFOCUSEDITEM: ::UINT = HDM_FIRST + 28; +pub const HDN_ITEMCHANGINGA: ::UINT = HDN_FIRST-0; +pub const HDN_ITEMCHANGINGW: ::UINT = HDN_FIRST-20; +pub const HDN_ITEMCHANGEDA: ::UINT = HDN_FIRST-1; +pub const HDN_ITEMCHANGEDW: ::UINT = HDN_FIRST-21; +pub const HDN_ITEMCLICKA: ::UINT = HDN_FIRST-2; +pub const HDN_ITEMCLICKW: ::UINT = HDN_FIRST-22; +pub const HDN_ITEMDBLCLICKA: ::UINT = HDN_FIRST-3; +pub const HDN_ITEMDBLCLICKW: ::UINT = HDN_FIRST-23; +pub const HDN_DIVIDERDBLCLICKA: ::UINT = HDN_FIRST-5; +pub const HDN_DIVIDERDBLCLICKW: ::UINT = HDN_FIRST-25; +pub const HDN_BEGINTRACKA: ::UINT = HDN_FIRST-6; +pub const HDN_BEGINTRACKW: ::UINT = HDN_FIRST-26; +pub const HDN_ENDTRACKA: ::UINT = HDN_FIRST-7; +pub const HDN_ENDTRACKW: ::UINT = HDN_FIRST-27; +pub const HDN_TRACKA: ::UINT = HDN_FIRST-8; +pub const HDN_TRACKW: ::UINT = HDN_FIRST-28; +pub const HDN_GETDISPINFOA: ::UINT = HDN_FIRST-9; +pub const HDN_GETDISPINFOW: ::UINT = HDN_FIRST-29; +pub const HDN_BEGINDRAG: ::UINT = HDN_FIRST-10; +pub const HDN_ENDDRAG: ::UINT = HDN_FIRST-11; +pub const HDN_FILTERCHANGE: ::UINT = HDN_FIRST-12; +pub const HDN_FILTERBTNCLICK: ::UINT = HDN_FIRST-13; +pub const HDN_BEGINFILTEREDIT: ::UINT = HDN_FIRST-14; +pub const HDN_ENDFILTEREDIT: ::UINT = HDN_FIRST-15; +pub const HDN_ITEMSTATEICONCLICK: ::UINT = HDN_FIRST-16; +pub const HDN_ITEMKEYDOWN: ::UINT = HDN_FIRST-17; +pub const HDN_DROPDOWN: ::UINT = HDN_FIRST-18; +pub const HDN_OVERFLOWCLICK: ::UINT = HDN_FIRST-19; +STRUCT!{struct NMHEADERA { + hdr: ::NMHDR, + iItem: ::c_int, + iButton: ::c_int, + pitem: *mut HDITEMA, +}} +pub type LPNMHEADERA = *mut NMHEADERA; +STRUCT!{struct NMHEADERW { + hdr: ::NMHDR, + iItem: ::c_int, + iButton: ::c_int, + pitem: *mut HDITEMW, +}} +pub type LPNMHEADERW = *mut NMHEADERW; +STRUCT!{struct NMHDDISPINFOW { + hdr: ::NMHDR, + iItem: ::c_int, + mask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMHDDISPINFOW = *mut NMHDDISPINFOW; +STRUCT!{struct NMHDDISPINFOA { + hdr: ::NMHDR, + iItem: ::c_int, + mask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMHDDISPINFOA = *mut NMHDDISPINFOA; +STRUCT!{struct NMHDFILTERBTNCLICK { + hdr: ::NMHDR, + iItem: ::INT, + rc: ::RECT, +}} +pub type LPNMHDFILTERBTNCLICK = *mut NMHDFILTERBTNCLICK; +#[cfg(target_arch="x86")] +STRUCT!{struct TBBUTTON { + iBitmap: ::c_int, + idCommand: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + bReserved: [::BYTE; 2], + dwData: ::DWORD_PTR, + iString: ::INT_PTR, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct TBBUTTON { + iBitmap: ::c_int, + idCommand: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + bReserved: [::BYTE; 6], + dwData: ::DWORD_PTR, + iString: ::INT_PTR, +}} +pub type PTBBUTTON = *mut TBBUTTON; +pub type LPTBBUTTON = *mut TBBUTTON; +pub type LPCTBBUTTON = *const TBBUTTON; +STRUCT!{struct COLORMAP { + from: ::COLORREF, + to: ::COLORREF, +}} +pub type LPCOLORMAP = *mut COLORMAP; +pub const CMB_MASKED: ::UINT = 0x02; +pub const TBSTATE_CHECKED: ::BYTE = 0x01; +pub const TBSTATE_PRESSED: ::BYTE = 0x02; +pub const TBSTATE_ENABLED: ::BYTE = 0x04; +pub const TBSTATE_HIDDEN: ::BYTE = 0x08; +pub const TBSTATE_INDETERMINATE: ::BYTE = 0x10; +pub const TBSTATE_WRAP: ::BYTE = 0x20; +pub const TBSTATE_ELLIPSES: ::BYTE = 0x40; +pub const TBSTATE_MARKED: ::BYTE = 0x80; +pub const TBSTYLE_BUTTON: ::DWORD = 0x0000; +pub const TBSTYLE_SEP: ::DWORD = 0x0001; +pub const TBSTYLE_CHECK: ::DWORD = 0x0002; +pub const TBSTYLE_GROUP: ::DWORD = 0x0004; +pub const TBSTYLE_CHECKGROUP: ::DWORD = TBSTYLE_GROUP | TBSTYLE_CHECK; +pub const TBSTYLE_DROPDOWN: ::DWORD = 0x0008; +pub const TBSTYLE_AUTOSIZE: ::DWORD = 0x0010; +pub const TBSTYLE_NOPREFIX: ::DWORD = 0x0020; +pub const TBSTYLE_TOOLTIPS: ::DWORD = 0x0100; +pub const TBSTYLE_WRAPABLE: ::DWORD = 0x0200; +pub const TBSTYLE_ALTDRAG: ::DWORD = 0x0400; +pub const TBSTYLE_FLAT: ::DWORD = 0x0800; +pub const TBSTYLE_LIST: ::DWORD = 0x1000; +pub const TBSTYLE_CUSTOMERASE: ::DWORD = 0x2000; +pub const TBSTYLE_REGISTERDROP: ::DWORD = 0x4000; +pub const TBSTYLE_TRANSPARENT: ::DWORD = 0x8000; +pub const TBSTYLE_EX_DRAWDDARROWS: ::DWORD = 0x00000001; +pub const BTNS_BUTTON: ::DWORD = TBSTYLE_BUTTON; +pub const BTNS_SEP: ::DWORD = TBSTYLE_SEP; +pub const BTNS_CHECK: ::DWORD = TBSTYLE_CHECK; +pub const BTNS_GROUP: ::DWORD = TBSTYLE_GROUP; +pub const BTNS_CHECKGROUP: ::DWORD = TBSTYLE_CHECKGROUP; +pub const BTNS_DROPDOWN: ::DWORD = TBSTYLE_DROPDOWN; +pub const BTNS_AUTOSIZE: ::DWORD = TBSTYLE_AUTOSIZE; +pub const BTNS_NOPREFIX: ::DWORD = TBSTYLE_NOPREFIX; +pub const BTNS_SHOWTEXT: ::DWORD = 0x0040; +pub const BTNS_WHOLEDROPDOWN: ::DWORD = 0x0080; +pub const TBSTYLE_EX_MIXEDBUTTONS: ::DWORD = 0x00000008; +pub const TBSTYLE_EX_HIDECLIPPEDBUTTONS: ::DWORD = 0x00000010; +pub const TBSTYLE_EX_MULTICOLUMN: ::DWORD = 0x00000002; +pub const TBSTYLE_EX_VERTICAL: ::DWORD = 0x00000004; +pub const TBSTYLE_EX_DOUBLEBUFFER: ::DWORD = 0x00000080; +STRUCT!{struct NMTBCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + hbrMonoDither: ::HBRUSH, + hbrLines: ::HBRUSH, + hpenLines: ::HPEN, + clrText: ::COLORREF, + clrMark: ::COLORREF, + clrTextHighlight: ::COLORREF, + clrBtnFace: ::COLORREF, + clrBtnHighlight: ::COLORREF, + clrHighlightHotTrack: ::COLORREF, + rcText: ::RECT, + nStringBkMode: ::c_int, + nHLStringBkMode: ::c_int, + iListGap: ::c_int, +}} +pub type LPNMTBCUSTOMDRAW = *mut NMTBCUSTOMDRAW; +pub const TBCDRF_NOEDGES: ::LRESULT = 0x00010000; +pub const TBCDRF_HILITEHOTTRACK: ::LRESULT = 0x00020000; +pub const TBCDRF_NOOFFSET: ::LRESULT = 0x00040000; +pub const TBCDRF_NOMARK: ::LRESULT = 0x00080000; +pub const TBCDRF_NOETCHEDEFFECT: ::LRESULT = 0x00100000; +pub const TBCDRF_BLENDICON: ::LRESULT = 0x00200000; +pub const TBCDRF_NOBACKGROUND: ::LRESULT = 0x00400000; +pub const TBCDRF_USECDCOLORS: ::LRESULT = 0x00800000; +pub const TB_ENABLEBUTTON: ::UINT = ::WM_USER + 1; +pub const TB_CHECKBUTTON: ::UINT = ::WM_USER + 2; +pub const TB_PRESSBUTTON: ::UINT = ::WM_USER + 3; +pub const TB_HIDEBUTTON: ::UINT = ::WM_USER + 4; +pub const TB_INDETERMINATE: ::UINT = ::WM_USER + 5; +pub const TB_MARKBUTTON: ::UINT = ::WM_USER + 6; +pub const TB_ISBUTTONENABLED: ::UINT = ::WM_USER + 9; +pub const TB_ISBUTTONCHECKED: ::UINT = ::WM_USER + 10; +pub const TB_ISBUTTONPRESSED: ::UINT = ::WM_USER + 11; +pub const TB_ISBUTTONHIDDEN: ::UINT = ::WM_USER + 12; +pub const TB_ISBUTTONINDETERMINATE : ::UINT = ::WM_USER + 13; +pub const TB_ISBUTTONHIGHLIGHTED: ::UINT = ::WM_USER + 14; +pub const TB_SETSTATE: ::UINT = ::WM_USER + 17; +pub const TB_GETSTATE: ::UINT = ::WM_USER + 18; +pub const TB_ADDBITMAP: ::UINT = ::WM_USER + 19; +STRUCT!{struct TBADDBITMAP { + hInst: ::HINSTANCE, + nID: ::UINT_PTR, +}} +pub type LPTBADDBITMAP = *mut TBADDBITMAP; +pub const HINST_COMMCTRL: ::HINSTANCE = (0 - 1) as ::HINSTANCE; +pub const IDB_STD_SMALL_COLOR: ::WPARAM = 0; +pub const IDB_STD_LARGE_COLOR: ::WPARAM = 1; +pub const IDB_VIEW_SMALL_COLOR: ::WPARAM = 4; +pub const IDB_VIEW_LARGE_COLOR: ::WPARAM = 5; +pub const IDB_HIST_SMALL_COLOR: ::WPARAM = 8; +pub const IDB_HIST_LARGE_COLOR: ::WPARAM = 9; +pub const IDB_HIST_NORMAL: ::WPARAM = 12; +pub const IDB_HIST_HOT: ::WPARAM = 13; +pub const IDB_HIST_DISABLED: ::WPARAM = 14; +pub const IDB_HIST_PRESSED: ::WPARAM = 15; +pub const STD_CUT: ::c_int = 0; +pub const STD_COPY: ::c_int = 1; +pub const STD_PASTE: ::c_int = 2; +pub const STD_UNDO: ::c_int = 3; +pub const STD_REDOW: ::c_int = 4; +pub const STD_DELETE: ::c_int = 5; +pub const STD_FILENEW: ::c_int = 6; +pub const STD_FILEOPEN: ::c_int = 7; +pub const STD_FILESAVE: ::c_int = 8; +pub const STD_PRINTPRE: ::c_int = 9; +pub const STD_PROPERTIES: ::c_int = 10; +pub const STD_HELP: ::c_int = 11; +pub const STD_FIND: ::c_int = 12; +pub const STD_REPLACE: ::c_int = 13; +pub const STD_PRINT: ::c_int = 14; +pub const VIEW_LARGEICONS: ::c_int = 0; +pub const VIEW_SMALLICONS: ::c_int = 1; +pub const VIEW_LIST: ::c_int = 2; +pub const VIEW_DETAILS: ::c_int = 3; +pub const VIEW_SORTNAME: ::c_int = 4; +pub const VIEW_SORTSIZE: ::c_int = 5; +pub const VIEW_SORTDATE: ::c_int = 6; +pub const VIEW_SORTTYPE: ::c_int = 7; +pub const VIEW_PARENTFOLDER: ::c_int = 8; +pub const VIEW_NETCONNECT: ::c_int = 9; +pub const VIEW_NETDISCONNECT: ::c_int = 10; +pub const VIEW_NEWFOLDER: ::c_int = 11; +pub const VIEW_VIEWMENU: ::c_int = 12; +pub const HIST_BACK: ::c_int = 0; +pub const HIST_FORWARD: ::c_int = 1; +pub const HIST_FAVORITES: ::c_int = 2; +pub const HIST_ADDTOFAVORITES: ::c_int = 3; +pub const HIST_VIEWTREE: ::c_int = 4; +pub const TB_ADDBUTTONSA: ::UINT = ::WM_USER + 20; +pub const TB_INSERTBUTTONA: ::UINT = ::WM_USER + 21; +pub const TB_DELETEBUTTON: ::UINT = ::WM_USER + 22; +pub const TB_GETBUTTON: ::UINT = ::WM_USER + 23; +pub const TB_BUTTONCOUNT: ::UINT = ::WM_USER + 24; +pub const TB_COMMANDTOINDEX: ::UINT = ::WM_USER + 25; +STRUCT!{struct TBSAVEPARAMSA { + hkr: ::HKEY, + pszSubKey: ::LPCSTR, + pszValueName: ::LPCSTR, +}} +pub type LPTBSAVEPARAMSA = *mut TBSAVEPARAMSA; +STRUCT!{struct TBSAVEPARAMSW { + hkr: ::HKEY, + pszSubKey: ::LPCWSTR, + pszValueName: ::LPCWSTR, +}} +pub type LPTBSAVEPARAMSW = *mut TBSAVEPARAMSW; +pub const TB_SAVERESTOREA: ::UINT = ::WM_USER + 26; +pub const TB_SAVERESTOREW: ::UINT = ::WM_USER + 76; +pub const TB_CUSTOMIZE: ::UINT = ::WM_USER + 27; +pub const TB_ADDSTRINGA: ::UINT = ::WM_USER + 28; +pub const TB_ADDSTRINGW: ::UINT = ::WM_USER + 77; +pub const TB_GETITEMRECT: ::UINT = ::WM_USER + 29; +pub const TB_BUTTONSTRUCTSIZE: ::UINT = ::WM_USER + 30; +pub const TB_SETBUTTONSIZE: ::UINT = ::WM_USER + 31; +pub const TB_SETBITMAPSIZE: ::UINT = ::WM_USER + 32; +pub const TB_AUTOSIZE: ::UINT = ::WM_USER + 33; +pub const TB_GETTOOLTIPS: ::UINT = ::WM_USER + 35; +pub const TB_SETTOOLTIPS: ::UINT = ::WM_USER + 36; +pub const TB_SETPARENT: ::UINT = ::WM_USER + 37; +pub const TB_SETROWS: ::UINT = ::WM_USER + 39; +pub const TB_GETROWS: ::UINT = ::WM_USER + 40; +pub const TB_SETCMDID: ::UINT = ::WM_USER + 42; +pub const TB_CHANGEBITMAP: ::UINT = ::WM_USER + 43; +pub const TB_GETBITMAP: ::UINT = ::WM_USER + 44; +pub const TB_GETBUTTONTEXTA: ::UINT = ::WM_USER + 45; +pub const TB_GETBUTTONTEXTW: ::UINT = ::WM_USER + 75; +pub const TB_REPLACEBITMAP: ::UINT = ::WM_USER + 46; +pub const TB_SETINDENT: ::UINT = ::WM_USER + 47; +pub const TB_SETIMAGELIST: ::UINT = ::WM_USER + 48; +pub const TB_GETIMAGELIST: ::UINT = ::WM_USER + 49; +pub const TB_LOADIMAGES: ::UINT = ::WM_USER + 50; +pub const TB_GETRECT: ::UINT = ::WM_USER + 51; +pub const TB_SETHOTIMAGELIST: ::UINT = ::WM_USER + 52; +pub const TB_GETHOTIMAGELIST: ::UINT = ::WM_USER + 53; +pub const TB_SETDISABLEDIMAGELIST: ::UINT = ::WM_USER + 54; +pub const TB_GETDISABLEDIMAGELIST: ::UINT = ::WM_USER + 55; +pub const TB_SETSTYLE: ::UINT = ::WM_USER + 56; +pub const TB_GETSTYLE: ::UINT = ::WM_USER + 57; +pub const TB_GETBUTTONSIZE: ::UINT = ::WM_USER + 58; +pub const TB_SETBUTTONWIDTH: ::UINT = ::WM_USER + 59; +pub const TB_SETMAXTEXTROWS: ::UINT = ::WM_USER + 60; +pub const TB_GETTEXTROWS: ::UINT = ::WM_USER + 61; +pub const TB_GETOBJECT: ::UINT = ::WM_USER + 62; +pub const TB_GETHOTITEM: ::UINT = ::WM_USER + 71; +pub const TB_SETHOTITEM: ::UINT = ::WM_USER + 72; +pub const TB_SETANCHORHIGHLIGHT: ::UINT = ::WM_USER + 73; +pub const TB_GETANCHORHIGHLIGHT: ::UINT = ::WM_USER + 74; +pub const TB_MAPACCELERATORA: ::UINT = ::WM_USER + 78; +STRUCT!{struct TBINSERTMARK { + iButton: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPTBINSERTMARK = *mut TBINSERTMARK; +pub const TBIMHT_AFTER: ::DWORD = 0x00000001; +pub const TBIMHT_BACKGROUND: ::DWORD = 0x00000002; +pub const TB_GETINSERTMARK: ::UINT = ::WM_USER + 79; +pub const TB_SETINSERTMARK: ::UINT = ::WM_USER + 80; +pub const TB_INSERTMARKHITTEST: ::UINT = ::WM_USER + 81; +pub const TB_MOVEBUTTON: ::UINT = ::WM_USER + 82; +pub const TB_GETMAXSIZE: ::UINT = ::WM_USER + 83; +pub const TB_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 84; +pub const TB_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 85; +pub const TB_GETPADDING: ::UINT = ::WM_USER + 86; +pub const TB_SETPADDING: ::UINT = ::WM_USER + 87; +pub const TB_SETINSERTMARKCOLOR: ::UINT = ::WM_USER + 88; +pub const TB_GETINSERTMARKCOLOR: ::UINT = ::WM_USER + 89; +pub const TB_SETCOLORSCHEME: ::UINT = CCM_SETCOLORSCHEME; +pub const TB_GETCOLORSCHEME: ::UINT = CCM_GETCOLORSCHEME; +pub const TB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TB_MAPACCELERATORW: ::UINT = ::WM_USER + 90; +STRUCT!{struct TBREPLACEBITMAP { + hInstOld: ::HINSTANCE, + nIDOld: ::UINT_PTR, + hInstNew: ::HINSTANCE, + nIDNew: ::UINT_PTR, + nButtons: ::c_int, +}} +pub type LPTBREPLACEBITMAP = *mut TBREPLACEBITMAP; +pub const TBBF_LARGE: ::DWORD = 0x0001; +pub const TB_GETBITMAPFLAGS: ::UINT = ::WM_USER + 41; +pub const TBIF_IMAGE: ::DWORD = 0x00000001; +pub const TBIF_TEXT: ::DWORD = 0x00000002; +pub const TBIF_STATE: ::DWORD = 0x00000004; +pub const TBIF_STYLE: ::DWORD = 0x00000008; +pub const TBIF_LPARAM: ::DWORD = 0x00000010; +pub const TBIF_COMMAND: ::DWORD = 0x00000020; +pub const TBIF_SIZE: ::DWORD = 0x00000040; +pub const TBIF_BYINDEX: ::DWORD = 0x80000000; +STRUCT!{struct TBBUTTONINFOA { + cbSize: ::UINT, + dwMask: ::DWORD, + idCommand: ::c_int, + iImage: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + cx: ::WORD, + lParam: ::DWORD_PTR, + pszText: ::LPSTR, + cchText: ::c_int, +}} +pub type LPTBBUTTONINFOA = *mut TBBUTTONINFOA; +STRUCT!{struct TBBUTTONINFOW { + cbSize: ::UINT, + dwMask: ::DWORD, + idCommand: ::c_int, + iImage: ::c_int, + fsState: ::BYTE, + fsStyle: ::BYTE, + cx: ::WORD, + lParam: ::DWORD_PTR, + pszText: ::LPWSTR, + cchText: ::c_int, +}} +pub type LPTBBUTTONINFOW = *mut TBBUTTONINFOW; +pub const TB_GETBUTTONINFOW: ::UINT = ::WM_USER + 63; +pub const TB_SETBUTTONINFOW: ::UINT = ::WM_USER + 64; +pub const TB_GETBUTTONINFOA: ::UINT = ::WM_USER + 65; +pub const TB_SETBUTTONINFOA: ::UINT = ::WM_USER + 66; +pub const TB_INSERTBUTTONW: ::UINT = ::WM_USER + 67; +pub const TB_ADDBUTTONSW: ::UINT = ::WM_USER + 68; +pub const TB_HITTEST: ::UINT = ::WM_USER + 69; +pub const TB_SETDRAWTEXTFLAGS: ::UINT = ::WM_USER + 70; +pub const TB_GETSTRINGW: ::UINT = ::WM_USER + 91; +pub const TB_GETSTRINGA: ::UINT = ::WM_USER + 92; +pub const TB_SETBOUNDINGSIZE: ::UINT = ::WM_USER + 93; +pub const TB_SETHOTITEM2: ::UINT = ::WM_USER + 94; +pub const TB_HASACCELERATOR: ::UINT = ::WM_USER + 95; +pub const TB_SETLISTGAP: ::UINT = ::WM_USER + 96; +pub const TB_GETIMAGELISTCOUNT: ::UINT = ::WM_USER + 98; +pub const TB_GETIDEALSIZE: ::UINT = ::WM_USER + 99; +pub const TBMF_PAD: ::DWORD = 0x00000001; +pub const TBMF_BARPAD: ::DWORD = 0x00000002; +pub const TBMF_BUTTONSPACING: ::DWORD = 0x00000004; +STRUCT!{struct TBMETRICS { + cbSize: ::UINT, + dwMask: ::DWORD, + cxPad: ::c_int, + cyPad: ::c_int, + cxBarPad: ::c_int, + cyBarPad: ::c_int, + cxButtonSpacing: ::c_int, + cyButtonSpacing: ::c_int, +}} +pub type LPTBMETRICS = *mut TBMETRICS; +pub const TB_GETMETRICS: ::UINT = ::WM_USER + 101; +pub const TB_SETMETRICS: ::UINT = ::WM_USER + 102; +pub const TB_GETITEMDROPDOWNRECT: ::UINT = ::WM_USER + 103; +pub const TB_SETPRESSEDIMAGELIST: ::UINT = ::WM_USER + 104; +pub const TB_GETPRESSEDIMAGELIST: ::UINT = ::WM_USER + 105; +pub const TB_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const TBN_GETBUTTONINFOA: ::UINT = TBN_FIRST - 0; +pub const TBN_BEGINDRAG: ::UINT = TBN_FIRST - 1; +pub const TBN_ENDDRAG: ::UINT = TBN_FIRST - 2; +pub const TBN_BEGINADJUST: ::UINT = TBN_FIRST - 3; +pub const TBN_ENDADJUST: ::UINT = TBN_FIRST - 4; +pub const TBN_RESET: ::UINT = TBN_FIRST - 5; +pub const TBN_QUERYINSERT: ::UINT = TBN_FIRST - 6; +pub const TBN_QUERYDELETE: ::UINT = TBN_FIRST - 7; +pub const TBN_TOOLBARCHANGE: ::UINT = TBN_FIRST - 8; +pub const TBN_CUSTHELP: ::UINT = TBN_FIRST - 9; +pub const TBN_DROPDOWN: ::UINT = TBN_FIRST - 10; +pub const TBN_GETOBJECT: ::UINT = TBN_FIRST - 12; +STRUCT!{struct NMTBHOTITEM { + hdr: ::NMHDR, + idOld: ::c_int, + idNew: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPNMTBHOTITEM = *mut NMTBHOTITEM; +pub const HICF_OTHER: ::DWORD = 0x00000000; +pub const HICF_MOUSE: ::DWORD = 0x00000001; +pub const HICF_ARROWKEYS: ::DWORD = 0x00000002; +pub const HICF_ACCELERATOR: ::DWORD = 0x00000004; +pub const HICF_DUPACCEL: ::DWORD = 0x00000008; +pub const HICF_ENTERING: ::DWORD = 0x00000010; +pub const HICF_LEAVING: ::DWORD = 0x00000020; +pub const HICF_RESELECT: ::DWORD = 0x00000040; +pub const HICF_LMOUSE: ::DWORD = 0x00000080; +pub const HICF_TOGGLEDROPDOWN: ::DWORD = 0x00000100; +pub const TBN_HOTITEMCHANGE: ::UINT = TBN_FIRST - 13; +pub const TBN_DRAGOUT: ::UINT = TBN_FIRST - 14; +pub const TBN_DELETINGBUTTON: ::UINT = TBN_FIRST - 15; +pub const TBN_GETDISPINFOA: ::UINT = TBN_FIRST - 16; +pub const TBN_GETDISPINFOW: ::UINT = TBN_FIRST - 17; +pub const TBN_GETINFOTIPA: ::UINT = TBN_FIRST - 18; +pub const TBN_GETINFOTIPW: ::UINT = TBN_FIRST - 19; +pub const TBN_GETBUTTONINFOW: ::UINT = TBN_FIRST - 20; +pub const TBN_RESTORE: ::UINT = TBN_FIRST - 21; +pub const TBN_SAVE: ::UINT = TBN_FIRST - 22; +pub const TBN_INITCUSTOMIZE: ::UINT = TBN_FIRST - 23; +pub const TBN_WRAPHOTITEM: ::UINT = TBN_FIRST - 24; +pub const TBN_DUPACCELERATOR: ::UINT = TBN_FIRST - 25; +pub const TBN_WRAPACCELERATOR: ::UINT = TBN_FIRST - 26; +pub const TBN_DRAGOVER: ::UINT = TBN_FIRST - 27; +pub const TBN_MAPACCELERATOR: ::UINT = TBN_FIRST - 28; +pub const TBNRF_HIDEHELP: ::LRESULT = 0x00000001; +pub const TBNRF_ENDCUSTOMIZE: ::LRESULT = 0x00000002; +STRUCT!{struct NMTBSAVE { + hdr: ::NMHDR, + pData: *mut ::DWORD, + pCurrent: *mut ::DWORD, + cbData: ::UINT, + iItem: ::c_int, + cButtons: ::c_int, + tbButton: TBBUTTON, +}} +pub type LPNMTBSAVE = *mut NMTBSAVE; +STRUCT!{struct NMTBRESTORE { + hdr: ::NMHDR, + pData: *mut ::DWORD, + pCurrent: *mut ::DWORD, + cbData: ::UINT, + iItem: ::c_int, + cButtons: ::c_int, + cbBytesPerRecord: ::c_int, + tbButton: TBBUTTON, +}} +pub type LPNMTBRESTORE = *mut NMTBRESTORE; +STRUCT!{struct NMTBGETINFOTIPA { + hdr: ::NMHDR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + lParal: ::LPARAM, +}} +pub type LPNMTBGETINFOTIPA = *mut NMTBGETINFOTIPA; +STRUCT!{struct NMTBGETINFOTIPW { + hdr: ::NMHDR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + lParal: ::LPARAM, +}} +pub type LPNMTBGETINFOTIPW = *mut NMTBGETINFOTIPW; +pub const TBNF_IMAGE: ::DWORD = 0x00000001; +pub const TBNF_TEXT: ::DWORD = 0x00000002; +pub const TBNF_DI_SETITEM: ::DWORD = 0x10000000; +STRUCT!{struct NMTBDISPINFOA { + hdr: ::NMHDR, + dwMask: ::DWORD, + idCommand: ::c_int, + lParam: ::DWORD_PTR, + iImage: ::c_int, + pszText: ::LPSTR, + cchText: ::c_int, +}} +pub type LPNMTBDISPINFOA = *mut NMTBDISPINFOA; +STRUCT!{struct NMTBDISPINFOW { + hdr: ::NMHDR, + dwMask: ::DWORD, + idCommand: ::c_int, + lParam: ::DWORD_PTR, + iImage: ::c_int, + pszText: ::LPWSTR, + cchText: ::c_int, +}} +pub type LPNMTBDISPINFOW = *mut NMTBDISPINFOW; +pub const TBDDRET_DEFAULT: ::LRESULT = 0; +pub const TBDDRET_NODEFAULT: ::LRESULT = 1; +pub const TBDDRET_TREATPRESSED: ::LRESULT = 2; +pub type TBNOTIFYA = NMTOOLBARA; +pub type TBNOTIFYW = NMTOOLBARW; +pub type LPTBNOTIFYA = LPNMTOOLBARA; +pub type LPTBNOTIFYW = LPNMTOOLBARW; +STRUCT!{struct NMTOOLBARA { + hdr: ::NMHDR, + iItem: ::c_int, + tbButton: TBBUTTON, + cchText: ::c_int, + pszText: ::LPSTR, + rcButton: ::RECT, +}} +pub type LPNMTOOLBARA = *mut NMTOOLBARA; +STRUCT!{struct NMTOOLBARW { + hdr: ::NMHDR, + iItem: ::c_int, + tbButton: TBBUTTON, + cchText: ::c_int, + pszText: ::LPWSTR, + rcButton: ::RECT, +}} +pub type LPNMTOOLBARW = *mut NMTOOLBARW; +pub const RBIM_IMAGELIST: ::UINT = 0x00000001; +pub const RBS_TOOLTIPS: ::DWORD = 0x00000100; +pub const RBS_VARHEIGHT: ::DWORD = 0x00000200; +pub const RBS_BANDBORDERS: ::DWORD = 0x00000400; +pub const RBS_FIXEDORDER: ::DWORD = 0x00000800; +pub const RBS_REGISTERDROP: ::DWORD = 0x00001000; +pub const RBS_AUTOSIZE: ::DWORD = 0x00002000; +pub const RBS_VERTICALGRIPPER: ::DWORD = 0x00004000; +pub const RBS_DBLCLKTOGGLE: ::DWORD = 0x00008000; +STRUCT!{struct REBARINFO { + cbSize: ::UINT, + fMask: ::UINT, + himl: HIMAGELIST, +}} +pub type LPREBARINFO = *mut REBARINFO; +pub const RBBS_BREAK: ::UINT = 0x00000001; +pub const RBBS_FIXEDSIZE: ::UINT = 0x00000002; +pub const RBBS_CHILDEDGE: ::UINT = 0x00000004; +pub const RBBS_HIDDEN: ::UINT = 0x00000008; +pub const RBBS_NOVERT: ::UINT = 0x00000010; +pub const RBBS_FIXEDBMP: ::UINT = 0x00000020; +pub const RBBS_VARIABLEHEIGHT: ::UINT = 0x00000040; +pub const RBBS_GRIPPERALWAYS: ::UINT = 0x00000080; +pub const RBBS_NOGRIPPER: ::UINT = 0x00000100; +pub const RBBS_USECHEVRON: ::UINT = 0x00000200; +pub const RBBS_HIDETITLE: ::UINT = 0x00000400; +pub const RBBS_TOPALIGN: ::UINT = 0x00000800; +pub const RBBIM_STYLE: ::UINT = 0x00000001; +pub const RBBIM_COLORS: ::UINT = 0x00000002; +pub const RBBIM_TEXT: ::UINT = 0x00000004; +pub const RBBIM_IMAGE: ::UINT = 0x00000008; +pub const RBBIM_CHILD: ::UINT = 0x00000010; +pub const RBBIM_CHILDSIZE: ::UINT = 0x00000020; +pub const RBBIM_SIZE: ::UINT = 0x00000040; +pub const RBBIM_BACKGROUND: ::UINT = 0x00000080; +pub const RBBIM_ID: ::UINT = 0x00000100; +pub const RBBIM_IDEALSIZE: ::UINT = 0x00000200; +pub const RBBIM_LPARAM: ::UINT = 0x00000400; +pub const RBBIM_HEADERSIZE: ::UINT = 0x00000800; +pub const RBBIM_CHEVRONLOCATION: ::UINT = 0x00001000; +pub const RBBIM_CHEVRONSTATE: ::UINT = 0x00002000; +STRUCT!{struct REBARBANDINFOA { + cbSize: ::UINT, + fMask: ::UINT, + fStyle: ::UINT, + clrFore: ::COLORREF, + clrBack: ::COLORREF, + lpText: ::LPSTR, + cch: ::UINT, + iImage: ::c_int, + hwndChild: ::HWND, + cxMinChild: ::UINT, + cyMinChild: ::UINT, + cx: ::UINT, + hbmBack: ::HBITMAP, + wID: ::UINT, + cyChild: ::UINT, + cyMaxChild: ::UINT, + cyIntegral: ::UINT, + cxIdeal: ::UINT, + lParam: ::LPARAM, + cxHeader: ::UINT, + rcChevronLocation: ::RECT, + uChevronState: ::UINT, +}} +pub type LPREBARBANDINFOA = *mut REBARBANDINFOA; +pub type LPCREBARBANDINFOA = *const REBARBANDINFOA; +STRUCT!{struct REBARBANDINFOW { + cbSize: ::UINT, + fMask: ::UINT, + fStyle: ::UINT, + clrFore: ::COLORREF, + clrBack: ::COLORREF, + lpText: ::LPWSTR, + cch: ::UINT, + iImage: ::c_int, + hwndChild: ::HWND, + cxMinChild: ::UINT, + cyMinChild: ::UINT, + cx: ::UINT, + hbmBack: ::HBITMAP, + wID: ::UINT, + cyChild: ::UINT, + cyMaxChild: ::UINT, + cyIntegral: ::UINT, + cxIdeal: ::UINT, + lParam: ::LPARAM, + cxHeader: ::UINT, + rcChevronLocation: ::RECT, + uChevronState: ::UINT, +}} +pub type LPREBARBANDINFOW = *mut REBARBANDINFOW; +pub type LPCREBARBANDINFOW = *const REBARBANDINFOW; +pub const RB_INSERTBANDA: ::UINT = ::WM_USER + 1; +pub const RB_DELETEBAND: ::UINT = ::WM_USER + 2; +pub const RB_GETBARINFO: ::UINT = ::WM_USER + 3; +pub const RB_SETBARINFO: ::UINT = ::WM_USER + 4; +pub const RB_SETBANDINFOA: ::UINT = ::WM_USER + 6; +pub const RB_SETPARENT: ::UINT = ::WM_USER + 7; +pub const RB_HITTEST: ::UINT = ::WM_USER + 8; +pub const RB_GETRECT: ::UINT = ::WM_USER + 9; +pub const RB_INSERTBANDW: ::UINT = ::WM_USER + 10; +pub const RB_SETBANDINFOW: ::UINT = ::WM_USER + 11; +pub const RB_GETBANDCOUNT: ::UINT = ::WM_USER + 12; +pub const RB_GETROWCOUNT: ::UINT = ::WM_USER + 13; +pub const RB_GETROWHEIGHT: ::UINT = ::WM_USER + 14; +pub const RB_IDTOINDEX: ::UINT = ::WM_USER + 16; +pub const RB_GETTOOLTIPS: ::UINT = ::WM_USER + 17; +pub const RB_SETTOOLTIPS: ::UINT = ::WM_USER + 18; +pub const RB_SETBKCOLOR: ::UINT = ::WM_USER + 19; +pub const RB_GETBKCOLOR: ::UINT = ::WM_USER + 20; +pub const RB_SETTEXTCOLOR: ::UINT = ::WM_USER + 21; +pub const RB_GETTEXTCOLOR: ::UINT = ::WM_USER + 22; +pub const RBSTR_CHANGERECT: ::WPARAM = 0x0001; +pub const RB_SIZETORECT: ::UINT = ::WM_USER + 23; +pub const RB_SETCOLORSCHEME: ::UINT = CCM_SETCOLORSCHEME; +pub const RB_GETCOLORSCHEME: ::UINT = CCM_GETCOLORSCHEME; +pub const RB_BEGINDRAG: ::UINT = ::WM_USER + 24; +pub const RB_ENDDRAG: ::UINT = ::WM_USER + 25; +pub const RB_DRAGMOVE: ::UINT = ::WM_USER + 26; +pub const RB_GETBARHEIGHT: ::UINT = ::WM_USER + 27; +pub const RB_GETBANDINFOW: ::UINT = ::WM_USER + 28; +pub const RB_GETBANDINFOA: ::UINT = ::WM_USER + 29; +pub const RB_MINIMIZEBAND: ::UINT = ::WM_USER + 30; +pub const RB_MAXIMIZEBAND: ::UINT = ::WM_USER + 31; +pub const RB_GETDROPTARGET: ::UINT = CCM_GETDROPTARGET; +pub const RB_GETBANDBORDERS: ::UINT = ::WM_USER + 34; +pub const RB_SHOWBAND: ::UINT = ::WM_USER + 35; +pub const RB_SETPALETTE: ::UINT = ::WM_USER + 37; +pub const RB_GETPALETTE: ::UINT = ::WM_USER + 38; +pub const RB_MOVEBAND: ::UINT = ::WM_USER + 39; +pub const RB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const RB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const RB_GETBANDMARGINS: ::UINT = ::WM_USER + 40; +pub const RB_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const RB_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 41; +pub const RB_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 42; +pub const RB_PUSHCHEVRON: ::UINT = ::WM_USER + 43; +pub const RB_SETBANDWIDTH: ::UINT = ::WM_USER + 44; +pub const RBN_HEIGHTCHANGE: ::UINT = RBN_FIRST - 0; +pub const RBN_GETOBJECT: ::UINT = RBN_FIRST - 1; +pub const RBN_LAYOUTCHANGED: ::UINT = RBN_FIRST - 2; +pub const RBN_AUTOSIZE: ::UINT = RBN_FIRST - 3; +pub const RBN_BEGINDRAG: ::UINT = RBN_FIRST - 4; +pub const RBN_ENDDRAG: ::UINT = RBN_FIRST - 5; +pub const RBN_DELETINGBAND: ::UINT = RBN_FIRST - 6; +pub const RBN_DELETEDBAND: ::UINT = RBN_FIRST - 7; +pub const RBN_CHILDSIZE: ::UINT = RBN_FIRST - 8; +pub const RBN_CHEVRONPUSHED: ::UINT = RBN_FIRST - 10; +pub const RBN_SPLITTERDRAG: ::UINT = RBN_FIRST - 11; +pub const RBN_MINMAX: ::UINT = RBN_FIRST - 21; +pub const RBN_AUTOBREAK: ::UINT = RBN_FIRST - 22; +STRUCT!{struct NMREBARCHILDSIZE { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + rcChild: ::RECT, + rcBand: ::RECT, +}} +pub type LPNMREBARCHILDSIZE = *mut NMREBARCHILDSIZE; +STRUCT!{struct NMREBAR { + hdr: ::NMHDR, + dwMask: ::DWORD, + uBand: ::UINT, + fStyle: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMREBAR = *mut NMREBAR; +pub const RBNM_ID: ::DWORD = 0x00000001; +pub const RBNM_STYLE: ::DWORD = 0x00000002; +pub const RBNM_LPARAM: ::DWORD = 0x00000004; +STRUCT!{struct NMRBAUTOSIZE { + hdr: ::NMHDR, + fChanged: ::BOOL, + rcTarget: ::RECT, + rcActual: ::RECT, +}} +pub type LPNMRBAUTOSIZE = *mut NMRBAUTOSIZE; +STRUCT!{struct NMREBARCHEVRON { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, + rc: ::RECT, + lParamNM: ::LPARAM, +}} +pub type LPNMREBARCHEVRON = *mut NMREBARCHEVRON; +STRUCT!{struct NMREBARSPLITTER { + hdr: ::NMHDR, + rcSizing: ::RECT, +}} +pub type LPNMREBARSPLITTER = *mut NMREBARSPLITTER; +pub const RBAB_AUTOSIZE: ::UINT = 0x0001; +pub const RBAB_ADDBAND: ::UINT = 0x0002; +STRUCT!{struct NMREBARAUTOBREAK { + hdr: ::NMHDR, + uBand: ::UINT, + wID: ::UINT, + lParam: ::LPARAM, + uMsg: ::UINT, + fStyleCurrent: ::UINT, + fAutoBreak: ::UINT, +}} +pub type LPNMREBARAUTOBREAK = *mut NMREBARAUTOBREAK; +pub const RBHT_NOWHERE: ::UINT = 0x0001; +pub const RBHT_CAPTION: ::UINT = 0x0002; +pub const RBHT_CLIENT: ::UINT = 0x0003; +pub const RBHT_GRABBER: ::UINT = 0x0004; +pub const RBHT_CHEVRON: ::UINT = 0x0008; +pub const RBHT_SPLITTER: ::UINT = 0x0010; +STRUCT!{struct RBHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iBand: ::c_int, +}} +pub type LPRBHITTESTINFO = *mut RBHITTESTINFO; +pub type LPTOOLINFOA = LPTTTOOLINFOA; +pub type LPTOOLINFOW = LPTTTOOLINFOW; +pub type TOOLINFOA = TTTOOLINFOA; +pub type TOOLINFOW = TTTOOLINFOW; +STRUCT!{struct TTTOOLINFOA { + cbSize: ::UINT, + uFlags: ::UINT, + hwnd: ::HWND, + uId: ::UINT_PTR, + rect: ::RECT, + hinst: ::HINSTANCE, + lpszText: ::LPSTR, + lParam: ::LPARAM, + lpReserved: *mut ::c_void, +}} +pub type PTTTOOLINFOA = *mut TTTOOLINFOA; +pub type LPTTTOOLINFOA = *mut TTTOOLINFOA; +STRUCT!{struct TTTOOLINFOW { + cbSize: ::UINT, + uFlags: ::UINT, + hwnd: ::HWND, + uId: ::UINT_PTR, + rect: ::RECT, + hinst: ::HINSTANCE, + lpszText: ::LPSTR, + lParam: ::LPARAM, + lpReserved: *mut ::c_void, +}} +pub type PTTTOOLINFOW = *mut TTTOOLINFOW; +pub type LPTTTOOLINFOW = *mut TTTOOLINFOW; +pub const TTS_ALWAYSTIP: ::DWORD = 0x01; +pub const TTS_NOPREFIX: ::DWORD = 0x02; +pub const TTS_NOANIMATE: ::DWORD = 0x10; +pub const TTS_NOFADE: ::DWORD = 0x20; +pub const TTS_BALLOON: ::DWORD = 0x40; +pub const TTS_CLOSE: ::DWORD = 0x80; +pub const TTS_USEVISUALSTYLE: ::DWORD = 0x100; +pub const TTF_IDISHWND: ::UINT = 0x0001; +pub const TTF_CENTERTIP: ::UINT = 0x0002; +pub const TTF_RTLREADING: ::UINT = 0x0004; +pub const TTF_SUBCLASS: ::UINT = 0x0010; +pub const TTF_TRACK: ::UINT = 0x0020; +pub const TTF_ABSOLUTE: ::UINT = 0x0080; +pub const TTF_TRANSPARENT: ::UINT = 0x0100; +pub const TTF_PARSELINKS: ::UINT = 0x1000; +pub const TTF_DI_SETITEM: ::UINT = 0x8000; +pub const TTDT_AUTOMATIC: ::WPARAM = 0; +pub const TTDT_RESHOW: ::WPARAM = 1; +pub const TTDT_AUTOPOP: ::WPARAM = 2; +pub const TTDT_INITIAL: ::WPARAM = 3; +pub const TTI_NONE: ::WPARAM = 0; +pub const TTI_INFO: ::WPARAM = 1; +pub const TTI_WARNING: ::WPARAM = 2; +pub const TTI_ERROR: ::WPARAM = 3; +pub const TTI_INFO_LARGE: ::WPARAM = 4; +pub const TTI_WARNING_LARGE: ::WPARAM = 5; +pub const TTI_ERROR_LARGE: ::WPARAM = 6; +pub const TTM_ACTIVATE: ::UINT = ::WM_USER + 1; +pub const TTM_SETDELAYTIME: ::UINT = ::WM_USER + 3; +pub const TTM_ADDTOOLA: ::UINT = ::WM_USER + 4; +pub const TTM_ADDTOOLW: ::UINT = ::WM_USER + 50; +pub const TTM_DELTOOLA: ::UINT = ::WM_USER + 5; +pub const TTM_DELTOOLW: ::UINT = ::WM_USER + 51; +pub const TTM_NEWTOOLRECTA: ::UINT = ::WM_USER + 6; +pub const TTM_NEWTOOLRECTW: ::UINT = ::WM_USER + 52; +pub const TTM_RELAYEVENT: ::UINT = ::WM_USER + 7; +pub const TTM_GETTOOLINFOA: ::UINT = ::WM_USER + 8; +pub const TTM_GETTOOLINFOW: ::UINT = ::WM_USER + 53; +pub const TTM_SETTOOLINFOA: ::UINT = ::WM_USER + 9; +pub const TTM_SETTOOLINFOW: ::UINT = ::WM_USER + 54; +pub const TTM_HITTESTA: ::UINT = ::WM_USER + 10; +pub const TTM_HITTESTW: ::UINT = ::WM_USER + 55; +pub const TTM_GETTEXTA: ::UINT = ::WM_USER + 11; +pub const TTM_GETTEXTW: ::UINT = ::WM_USER + 56; +pub const TTM_UPDATETIPTEXTA: ::UINT = ::WM_USER + 12; +pub const TTM_UPDATETIPTEXTW: ::UINT = ::WM_USER + 57; +pub const TTM_GETTOOLCOUNT: ::UINT = ::WM_USER + 13; +pub const TTM_ENUMTOOLSA: ::UINT = ::WM_USER + 14; +pub const TTM_ENUMTOOLSW: ::UINT = ::WM_USER + 58; +pub const TTM_GETCURRENTTOOLA: ::UINT = ::WM_USER + 15; +pub const TTM_GETCURRENTTOOLW: ::UINT = ::WM_USER + 59; +pub const TTM_WINDOWFROMPOINT: ::UINT = ::WM_USER + 16; +pub const TTM_TRACKACTIVATE: ::UINT = ::WM_USER + 17; +pub const TTM_TRACKPOSITION: ::UINT = ::WM_USER + 18; +pub const TTM_SETTIPBKCOLOR: ::UINT = ::WM_USER + 19; +pub const TTM_SETTIPTEXTCOLOR: ::UINT = ::WM_USER + 20; +pub const TTM_GETDELAYTIME: ::UINT = ::WM_USER + 21; +pub const TTM_GETTIPBKCOLOR: ::UINT = ::WM_USER + 22; +pub const TTM_GETTIPTEXTCOLOR: ::UINT = ::WM_USER + 23; +pub const TTM_SETMAXTIPWIDTH: ::UINT = ::WM_USER + 24; +pub const TTM_GETMAXTIPWIDTH: ::UINT = ::WM_USER + 25; +pub const TTM_SETMARGIN: ::UINT = ::WM_USER + 26; +pub const TTM_GETMARGIN: ::UINT = ::WM_USER + 27; +pub const TTM_POP: ::UINT = ::WM_USER + 28; +pub const TTM_UPDATE: ::UINT = ::WM_USER + 29; +pub const TTM_GETBUBBLESIZE: ::UINT = ::WM_USER + 30; +pub const TTM_ADJUSTRECT: ::UINT = ::WM_USER + 31; +pub const TTM_SETTITLEA: ::UINT = ::WM_USER + 32; +pub const TTM_SETTITLEW: ::UINT = ::WM_USER + 33; +pub const TTM_POPUP: ::UINT = ::WM_USER + 34; +pub const TTM_GETTITLE: ::UINT = ::WM_USER + 35; +STRUCT!{struct TTGETTITLE { + dwSize: ::DWORD, + uTitleBitmap: ::UINT, + cch: ::UINT, + pszTitle: *mut ::WCHAR, +}} +pub type LPTTGETTITLE = *mut TTGETTITLE; +pub const TTM_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub type LPHITTESTINFOW = LPTTHITTESTINFOW; +pub type LPHITTESTINFOA = LPTTHITTESTINFOA; +STRUCT!{struct TTHITTESTINFOA { + hwnd: ::HWND, + pt: ::POINT, + ti: TTTOOLINFOA, +}} +pub type LPTTHITTESTINFOA = *mut TTHITTESTINFOA; +STRUCT!{struct TTHITTESTINFOW { + hwnd: ::HWND, + pt: ::POINT, + ti: TTTOOLINFOW, +}} +pub type LPTTHITTESTINFOW = *mut TTHITTESTINFOW; +pub const TTN_GETDISPINFOA: ::UINT = TTN_FIRST - 0; +pub const TTN_GETDISPINFOW: ::UINT = TTN_FIRST - 10; +pub const TTN_SHOW: ::UINT = TTN_FIRST - 1; +pub const TTN_POP: ::UINT = TTN_FIRST - 2; +pub const TTN_LINKCLICK: ::UINT = TTN_FIRST - 3; +pub const TTN_NEEDTEXTA: ::UINT = TTN_GETDISPINFOA; +pub const TTN_NEEDTEXTW: ::UINT = TTN_GETDISPINFOW; +pub type TOOLTIPTEXTW = NMTTDISPINFOW; +pub type TOOLTIPTEXTA = NMTTDISPINFOA; +pub type LPTOOLTIPTEXTA = LPNMTTDISPINFOA; +pub type LPTOOLTIPTEXTW = LPNMTTDISPINFOW; +STRUCT!{nodebug struct NMTTDISPINFOA { + hdr: ::NMHDR, + lpszText: ::LPSTR, + szText: [::c_char; 80], + hinst: ::HINSTANCE, + uFlags: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMTTDISPINFOA = *mut NMTTDISPINFOA; +STRUCT!{nodebug struct NMTTDISPINFOW { + hdr: ::NMHDR, + lpszText: ::LPWSTR, + szText: [::WCHAR; 80], + hinst: ::HINSTANCE, + uFlags: ::UINT, + lParam: ::LPARAM, +}} +pub type LPNMTTDISPINFOW = *mut NMTTDISPINFOW; +pub const SBARS_SIZEGRIP: ::DWORD = 0x0100; +pub const SBARS_TOOLTIPS: ::DWORD = 0x0800; +pub const SBT_TOOLTIPS: ::DWORD = 0x0800; +pub const SB_SETTEXTA: ::UINT = ::WM_USER + 1; +pub const SB_SETTEXTW: ::UINT = ::WM_USER + 11; +pub const SB_GETTEXTA: ::UINT = ::WM_USER + 2; +pub const SB_GETTEXTW: ::UINT = ::WM_USER + 13; +pub const SB_GETTEXTLENGTHA: ::UINT = ::WM_USER + 3; +pub const SB_GETTEXTLENGTHW: ::UINT = ::WM_USER + 12; +pub const SB_SETPARTS: ::UINT = ::WM_USER + 4; +pub const SB_GETPARTS: ::UINT = ::WM_USER + 6; +pub const SB_GETBORDERS: ::UINT = ::WM_USER + 7; +pub const SB_SETMINHEIGHT: ::UINT = ::WM_USER + 8; +pub const SB_SIMPLE: ::UINT = ::WM_USER + 9; +pub const SB_GETRECT: ::UINT = ::WM_USER + 10; +pub const SB_ISSIMPLE: ::UINT = ::WM_USER + 14; +pub const SB_SETICON: ::UINT = ::WM_USER + 15; +pub const SB_SETTIPTEXTA: ::UINT = ::WM_USER + 16; +pub const SB_SETTIPTEXTW: ::UINT = ::WM_USER + 17; +pub const SB_GETTIPTEXTA: ::UINT = ::WM_USER + 18; +pub const SB_GETTIPTEXTW: ::UINT = ::WM_USER + 19; +pub const SB_GETICON: ::UINT = ::WM_USER + 20; +pub const SB_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const SB_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const SBT_OWNERDRAW: ::WPARAM = 0x1000; +pub const SBT_NOBORDERS: ::WPARAM = 0x0100; +pub const SBT_POPOUT: ::WPARAM = 0x0200; +pub const SBT_RTLREADING: ::WPARAM = 0x0400; +pub const SBT_NOTABPARSING: ::WPARAM = 0x0800; +pub const SB_SETBKCOLOR: ::UINT = CCM_SETBKCOLOR; +pub const SBN_SIMPLEMODECHANGE: ::UINT = SBN_FIRST - 0; +pub const SB_SIMPLEID: ::WPARAM = 0x00ff; +pub const TBS_AUTOTICKS: ::DWORD = 0x0001; +pub const TBS_VERT: ::DWORD = 0x0002; +pub const TBS_HORZ: ::DWORD = 0x0000; +pub const TBS_TOP: ::DWORD = 0x0004; +pub const TBS_BOTTOM: ::DWORD = 0x0000; +pub const TBS_LEFT: ::DWORD = 0x0004; +pub const TBS_RIGHT: ::DWORD = 0x0000; +pub const TBS_BOTH: ::DWORD = 0x0008; +pub const TBS_NOTICKS: ::DWORD = 0x0010; +pub const TBS_ENABLESELRANGE: ::DWORD = 0x0020; +pub const TBS_FIXEDLENGTH: ::DWORD = 0x0040; +pub const TBS_NOTHUMB: ::DWORD = 0x0080; +pub const TBS_TOOLTIPS: ::DWORD = 0x0100; +pub const TBS_REVERSED: ::DWORD = 0x0200; +pub const TBS_DOWNISLEFT: ::DWORD = 0x0400; +pub const TBS_NOTIFYBEFOREMOVE: ::DWORD = 0x0800; +pub const TBS_TRANSPARENTBKGND: ::DWORD = 0x1000; +pub const TBM_GETPOS: ::UINT = ::WM_USER; +pub const TBM_GETRANGEMIN: ::UINT = ::WM_USER + 1; +pub const TBM_GETRANGEMAX: ::UINT = ::WM_USER + 2; +pub const TBM_GETTIC: ::UINT = ::WM_USER + 3; +pub const TBM_SETTIC: ::UINT = ::WM_USER + 4; +pub const TBM_SETPOS: ::UINT = ::WM_USER + 5; +pub const TBM_SETRANGE: ::UINT = ::WM_USER + 6; +pub const TBM_SETRANGEMIN: ::UINT = ::WM_USER + 7; +pub const TBM_SETRANGEMAX: ::UINT = ::WM_USER + 8; +pub const TBM_CLEARTICS: ::UINT = ::WM_USER + 9; +pub const TBM_SETSEL: ::UINT = ::WM_USER + 10; +pub const TBM_SETSELSTART: ::UINT = ::WM_USER + 11; +pub const TBM_SETSELEND: ::UINT = ::WM_USER + 12; +pub const TBM_GETPTICS: ::UINT = ::WM_USER + 14; +pub const TBM_GETTICPOS: ::UINT = ::WM_USER + 15; +pub const TBM_GETNUMTICS: ::UINT = ::WM_USER + 16; +pub const TBM_GETSELSTART: ::UINT = ::WM_USER + 17; +pub const TBM_GETSELEND: ::UINT = ::WM_USER + 18; +pub const TBM_CLEARSEL: ::UINT = ::WM_USER + 19; +pub const TBM_SETTICFREQ: ::UINT = ::WM_USER + 20; +pub const TBM_SETPAGESIZE: ::UINT = ::WM_USER + 21; +pub const TBM_GETPAGESIZE: ::UINT = ::WM_USER + 22; +pub const TBM_SETLINESIZE: ::UINT = ::WM_USER + 23; +pub const TBM_GETLINESIZE: ::UINT = ::WM_USER + 24; +pub const TBM_GETTHUMBRECT: ::UINT = ::WM_USER + 25; +pub const TBM_GETCHANNELRECT: ::UINT = ::WM_USER + 26; +pub const TBM_SETTHUMBLENGTH: ::UINT = ::WM_USER + 27; +pub const TBM_GETTHUMBLENGTH: ::UINT = ::WM_USER + 28; +pub const TBM_SETTOOLTIPS: ::UINT = ::WM_USER + 29; +pub const TBM_GETTOOLTIPS: ::UINT = ::WM_USER + 30; +pub const TBM_SETTIPSIDE: ::UINT = ::WM_USER + 31; +pub const TBTS_TOP: ::WPARAM = 0; +pub const TBTS_LEFT: ::WPARAM = 1; +pub const TBTS_BOTTOM: ::WPARAM = 2; +pub const TBTS_RIGHT: ::WPARAM = 3; +pub const TBM_SETBUDDY: ::UINT = ::WM_USER + 32; +pub const TBM_GETBUDDY: ::UINT = ::WM_USER + 33; +pub const TBM_SETPOSNOTIFY: ::UINT = ::WM_USER + 34; +pub const TBM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TBM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TBCD_TICS: ::DWORD_PTR = 0x0001; +pub const TBCD_THUMB: ::DWORD_PTR = 0x0001; +pub const TBCD_CHANNEL: ::DWORD_PTR = 0x0001; +pub const TB_LINEUP: ::WPARAM = 0; +pub const TB_LINEDOWN: ::WPARAM = 1; +pub const TB_PAGEUP: ::WPARAM = 2; +pub const TB_PAGEDOWN: ::WPARAM = 3; +pub const TB_THUMBPOSITION: ::WPARAM = 4; +pub const TB_THUMBTRACK: ::WPARAM = 5; +pub const TB_TOP: ::WPARAM = 6; +pub const TB_BOTTOM: ::WPARAM = 7; +pub const TB_ENDTRACK: ::WPARAM = 8; +pub const TRBN_THUMBPOSCHANGING: ::UINT = TRBN_FIRST - 1; +STRUCT!{struct NMTRBTHUMBPOSCHANGING { + hdr: ::NMHDR, + dwPos: ::DWORD, + nReason: ::c_int, +}} +STRUCT!{struct DRAGLISTINFO { + uNotification: ::UINT, + hWnd: ::HWND, + ptCursor: ::POINT, +}} +pub type LPDRAGLISTINFO = *mut DRAGLISTINFO; +pub const DL_BEGINDRAG: ::UINT = ::WM_USER + 133; +pub const DL_DRAGGING: ::UINT = ::WM_USER + 134; +pub const DL_DROPPED: ::UINT = ::WM_USER + 135; +pub const DL_CANCELDRAG: ::UINT = ::WM_USER + 136; +pub const DL_CURSORSET: ::UINT = 0; +pub const DL_STOPCURSOR: ::UINT = 1; +pub const DL_COPYCURSOR: ::UINT = 2; +pub const DL_MOVECURSOR: ::UINT = 3; +STRUCT!{struct UDACCEL { + nSec: ::UINT, + nInc: ::UINT, +}} +pub type LPUDACCEL = *mut UDACCEL; +pub const UD_MAXVAL: ::c_short = 0x7fff; +pub const UD_MINVAL: ::c_short = 0 - UD_MAXVAL; +pub const UDS_WRAP: ::DWORD = 0x0001; +pub const UDS_SETBUDDYINT: ::DWORD = 0x0002; +pub const UDS_ALIGNRIGHT: ::DWORD = 0x0004; +pub const UDS_ALIGNLEFT: ::DWORD = 0x0008; +pub const UDS_AUTOBUDDY: ::DWORD = 0x0010; +pub const UDS_ARROWKEYS: ::DWORD = 0x0020; +pub const UDS_HORZ: ::DWORD = 0x0040; +pub const UDS_NOTHOUSANDS: ::DWORD = 0x0080; +pub const UDS_HOTTRACK: ::DWORD = 0x0100; +pub const UDM_SETRANGE: ::UINT = ::WM_USER + 101; +pub const UDM_GETRANGE: ::UINT = ::WM_USER + 102; +pub const UDM_SETPOS: ::UINT = ::WM_USER + 103; +pub const UDM_GETPOS: ::UINT = ::WM_USER + 104; +pub const UDM_SETBUDDY: ::UINT = ::WM_USER + 105; +pub const UDM_GETBUDDY: ::UINT = ::WM_USER + 106; +pub const UDM_SETACCEL: ::UINT = ::WM_USER + 107; +pub const UDM_GETACCEL: ::UINT = ::WM_USER + 108; +pub const UDM_SETBASE: ::UINT = ::WM_USER + 109; +pub const UDM_GETBASE: ::UINT = ::WM_USER + 110; +pub const UDM_SETRANGE32: ::UINT = ::WM_USER + 111; +pub const UDM_GETRANGE32: ::UINT = ::WM_USER + 112; +pub const UDM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const UDM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const UDM_SETPOS32: ::UINT = ::WM_USER + 113; +pub const UDM_GETPOS32: ::UINT = ::WM_USER + 114; +pub type NM_UPDOWN = NMUPDOWN; +pub type LPNM_UPDOWN = LPNMUPDOWN; +STRUCT!{struct NMUPDOWN { + hdr: ::NMHDR, + iPos: ::c_int, + iDelta: ::c_int, +}} +pub type LPNMUPDOWN = *mut NMUPDOWN; +pub const UDN_DELTAPOS: ::UINT = UDN_FIRST - 1; +pub const PBS_SMOOTH: ::DWORD = 0x01; +pub const PBS_VERTICAL: ::DWORD = 0x04; +pub const PBM_SETRANGE: ::UINT = ::WM_USER + 1; +pub const PBM_SETPOS: ::UINT = ::WM_USER + 2; +pub const PBM_DELTAPOS: ::UINT = ::WM_USER + 3; +pub const PBM_SETSTEP: ::UINT = ::WM_USER + 4; +pub const PBM_STEPIT: ::UINT = ::WM_USER + 5; +pub const PBM_SETRANGE32: ::UINT = ::WM_USER + 6; +STRUCT!{struct PBRANGE { + iLow: ::c_int, + iHigh: ::c_int, +}} +pub type LPPBRANGE = *mut PBRANGE; +pub const PBM_GETRANGE: ::UINT = ::WM_USER + 7; +pub const PBM_GETPOS: ::UINT = ::WM_USER + 8; +pub const PBM_SETBARCOLOR: ::UINT = ::WM_USER + 9; +pub const PBM_SETBKCOLOR: ::UINT = CCM_SETBKCOLOR; +pub const PBM_SETMARQUEE: ::UINT = ::WM_USER + 10; +pub const PBS_MARQUEE: ::DWORD = 0x08; +pub const PBS_SMOOTHREVERSE: ::DWORD = 0x10; +pub const PBM_GETSTEP: ::UINT = ::WM_USER + 13; +pub const PBM_GETBKCOLOR: ::UINT = ::WM_USER + 14; +pub const PBM_GETBARCOLOR: ::UINT = ::WM_USER + 15; +pub const PBM_SETSTATE: ::UINT = ::WM_USER + 16; +pub const PBM_GETSTATE: ::UINT = ::WM_USER + 17; +pub const PBST_NORMAL: ::c_int = 0x0001; +pub const PBST_ERROR: ::c_int = 0x0002; +pub const PBST_PAUSED: ::c_int = 0x0003; +pub const HOTKEYF_SHIFT: ::BYTE = 0x01; +pub const HOTKEYF_CONTROL: ::BYTE = 0x02; +pub const HOTKEYF_ALT: ::BYTE = 0x04; +pub const HOTKEYF_EXT: ::BYTE = 0x08; +pub const HKCOMB_NONE: ::WPARAM = 0x0001; +pub const HKCOMB_S: ::WPARAM = 0x0002; +pub const HKCOMB_C: ::WPARAM = 0x0004; +pub const HKCOMB_A: ::WPARAM = 0x0008; +pub const HKCOMB_SC: ::WPARAM = 0x0010; +pub const HKCOMB_SA: ::WPARAM = 0x0020; +pub const HKCOMB_CA: ::WPARAM = 0x0040; +pub const HKCOMB_SCA: ::WPARAM = 0x0080; +pub const HKM_SETHOTKEY: ::UINT = ::WM_USER + 1; +pub const HKM_GETHOTKEY: ::UINT = ::WM_USER + 2; +pub const HKM_SETRULES: ::UINT = ::WM_USER + 3; +pub const CCS_TOP: ::DWORD = 0x00000001; +pub const CCS_NOMOVEY: ::DWORD = 0x00000002; +pub const CCS_BOTTOM: ::DWORD = 0x00000003; +pub const CCS_NORESIZE: ::DWORD = 0x00000004; +pub const CCS_NOPARENTALIGN: ::DWORD = 0x00000008; +pub const CCS_ADJUSTABLE: ::DWORD = 0x00000020; +pub const CCS_NODIVIDER: ::DWORD = 0x00000040; +pub const CCS_VERT: ::DWORD = 0x00000080; +pub const CCS_LEFT: ::DWORD = CCS_VERT | CCS_TOP; +pub const CCS_RIGHT: ::DWORD = CCS_VERT | CCS_BOTTOM; +pub const CCS_NOMOVEX: ::DWORD = CCS_VERT | CCS_NOMOVEY; +pub const MAX_LINKID_TEXT: usize = 48; +pub const L_MAX_URL_LENGTH: usize = 2048 + 32 + 4; +pub const LWS_TRANSPARENT: ::DWORD = 0x0001; +pub const LWS_IGNORERETURN: ::DWORD = 0x0002; +pub const LWS_NOPREFIX: ::DWORD = 0x0004; +pub const LWS_USEVISUALSTYLE: ::DWORD = 0x0008; +pub const LWS_USECUSTOMTEXT: ::DWORD = 0x0010; +pub const LWS_RIGHT: ::DWORD = 0x0020; +pub const LIF_ITEMINDEX: ::UINT = 0x00000001; +pub const LIF_STATE: ::UINT = 0x00000002; +pub const LIF_ITEMID: ::UINT = 0x00000004; +pub const LIF_URL: ::UINT = 0x00000008; +pub const LIS_FOCUSED: ::UINT = 0x00000001; +pub const LIS_ENABLED: ::UINT = 0x00000002; +pub const LIS_VISITED: ::UINT = 0x00000004; +pub const LIS_HOTTRACK: ::UINT = 0x00000008; +pub const LIS_DEFAULTCOLORS: ::UINT = 0x00000010; +STRUCT!{nodebug struct LITEM { + mask: ::UINT, + iLink: ::c_int, + state: ::UINT, + stateMask: ::UINT, + szID: [::WCHAR; MAX_LINKID_TEXT], + szUrl: [::WCHAR; L_MAX_URL_LENGTH], +}} +pub type PLITEM = *mut LITEM; +STRUCT!{nodebug struct LHITTESTINFO { + pt: ::POINT, + item: LITEM, +}} +pub type PLHITTESTINFO = *mut LHITTESTINFO; +STRUCT!{nodebug struct NMLINK { + hdr: ::NMHDR, + item: LITEM, +}} +pub type PNMLINK = *mut NMLINK; +pub const LM_HITTEST: ::UINT = ::WM_USER + 0x300; +pub const LM_GETIDEALHEIGHT: ::UINT = ::WM_USER + 0x301; +pub const LM_SETITEM: ::UINT = ::WM_USER + 0x302; +pub const LM_GETITEM: ::UINT = ::WM_USER + 0x303; +pub const LM_GETIDEALSIZE: ::UINT = LM_GETIDEALHEIGHT; +pub const LVS_ICON: ::DWORD = 0x0000; +pub const LVS_REPORT: ::DWORD = 0x0001; +pub const LVS_SMALLICON: ::DWORD = 0x0002; +pub const LVS_LIST: ::DWORD = 0x0003; +pub const LVS_TYPEMASK: ::DWORD = 0x0003; +pub const LVS_SINGLESEL: ::DWORD = 0x0004; +pub const LVS_SHOWSELALWAYS: ::DWORD = 0x0008; +pub const LVS_SORTASCENDING: ::DWORD = 0x0010; +pub const LVS_SORTDESCENDING: ::DWORD = 0x0020; +pub const LVS_SHAREIMAGELISTS: ::DWORD = 0x0040; +pub const LVS_NOLABELWRAP: ::DWORD = 0x0080; +pub const LVS_AUTOARRANGE: ::DWORD = 0x0100; +pub const LVS_EDITLABELS: ::DWORD = 0x0200; +pub const LVS_OWNERDATA: ::DWORD = 0x1000; +pub const LVS_NOSCROLL: ::DWORD = 0x2000; +pub const LVS_TYPESTYLEMASK: ::DWORD = 0xfc00; +pub const LVS_ALIGNTOP: ::DWORD = 0x0000; +pub const LVS_ALIGNLEFT: ::DWORD = 0x0800; +pub const LVS_ALIGNMASK: ::DWORD = 0x0c00; +pub const LVS_OWNERDRAWFIXED: ::DWORD = 0x0400; +pub const LVS_NOCOLUMNHEADER: ::DWORD = 0x4000; +pub const LVS_NOSORTHEADER: ::DWORD = 0x8000; +pub const LVM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const LVM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const LVM_GETBKCOLOR: ::UINT = LVM_FIRST + 0; +pub const LVM_SETBKCOLOR: ::UINT = LVM_FIRST + 1; +pub const LVM_GETIMAGELIST: ::UINT = LVM_FIRST + 2; +pub const LVM_SETIMAGELIST: ::UINT = LVM_FIRST + 3; +pub const LVM_GETITEMCOUNT: ::UINT = LVM_FIRST + 4; +pub const LVSIL_NORMAL: ::c_int = 0; +pub const LVSIL_SMALL: ::c_int = 1; +pub const LVSIL_STATE: ::c_int = 2; +pub const LVSIL_GROUPHEADER: ::c_int = 3; +pub const LVIF_TEXT: ::UINT = 0x00000001; +pub const LVIF_IMAGE: ::UINT = 0x00000002; +pub const LVIF_PARAM: ::UINT = 0x00000004; +pub const LVIF_STATE: ::UINT = 0x00000008; +pub const LVIF_INDENT: ::UINT = 0x00000010; +pub const LVIF_NORECOMPUTE: ::UINT = 0x00000800; +pub const LVIF_GROUPID: ::UINT = 0x00000100; +pub const LVIF_COLUMNS: ::UINT = 0x00000200; +pub const LVIF_COLFMT: ::UINT = 0x00010000; +pub const LVIS_FOCUSED: ::UINT = 0x0001; +pub const LVIS_SELECTED: ::UINT = 0x0002; +pub const LVIS_CUT: ::UINT = 0x0004; +pub const LVIS_DROPHILITED: ::UINT = 0x0008; +pub const LVIS_GLOW: ::UINT = 0x0010; +pub const LVIS_ACTIVATING: ::UINT = 0x0020; +pub const LVIS_OVERLAYMASK: ::UINT = 0x0F00; +pub const LVIS_STATEIMAGEMASK: ::UINT = 0xF000; +#[inline] #[allow(dead_code)] +pub fn INDEXTOSTATEIMAGEMASK(i: ::UINT) -> ::UINT { i << 12 } +pub const I_INDENTCALLBACK: ::c_int = -1; +pub type LV_ITEMA = LVITEMA; +pub type LV_ITEMW = LVITEMW; +pub const I_GROUPIDCALLBACK: ::c_int = -1; +pub const I_GROUPIDNONE: ::c_int = -2; +STRUCT!{struct LVITEMA { + mask: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, + iIndent: ::c_int, + iGroupId: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, + iGroup: ::c_int, +}} +pub type LPLVITEMA = *mut LVITEMA; +STRUCT!{struct LVITEMW { + mask: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, + iIndent: ::c_int, + iGroupId: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, + iGroup: ::c_int, +}} +pub type LPLVITEMW = *mut LVITEMW; +pub const LPSTR_TEXTCALLBACKW: ::LPWSTR = (0 - 1) as ::LPWSTR; +pub const LPSTR_TEXTCALLBACKA: ::LPSTR = (0 - 1) as ::LPSTR; +pub const I_IMAGECALLBACK: ::c_int = -1; +pub const I_IMAGENONE: ::c_int = -2; +pub const I_COLUMNSCALLBACK: ::UINT = -1i32 as ::UINT; +pub const LVM_GETITEMA: ::UINT = LVM_FIRST + 5; +pub const LVM_GETITEMW: ::UINT = LVM_FIRST + 75; +pub const LVM_SETITEMA: ::UINT = LVM_FIRST + 6; +pub const LVM_SETITEMW: ::UINT = LVM_FIRST + 76; +pub const LVM_INSERTITEMA: ::UINT = LVM_FIRST + 7; +pub const LVM_INSERTITEMW: ::UINT = LVM_FIRST + 77; +pub const LVM_DELETEITEM: ::UINT = LVM_FIRST + 8; +pub const LVM_DELETEALLITEMS: ::UINT = LVM_FIRST + 9; +pub const LVM_GETCALLBACKMASK: ::UINT = LVM_FIRST + 10; +pub const LVM_SETCALLBACKMASK: ::UINT = LVM_FIRST + 11; +pub const LVM_GETNEXTITEM: ::UINT = LVM_FIRST + 12; +pub const LVNI_ALL: ::LPARAM = 0x0000; +pub const LVNI_FOCUSED: ::LPARAM = 0x0001; +pub const LVNI_SELECTED: ::LPARAM = 0x0002; +pub const LVNI_CUT: ::LPARAM = 0x0004; +pub const LVNI_DROPHILITED: ::LPARAM = 0x0008; +pub const LVNI_STATEMASK: ::LPARAM = LVNI_FOCUSED | LVNI_SELECTED | LVNI_CUT | LVNI_DROPHILITED; +pub const LVNI_VISIBLEORDER: ::LPARAM = 0x0010; +pub const LVNI_PREVIOUS: ::LPARAM = 0x0020; +pub const LVNI_VISIBLEONLY: ::LPARAM = 0x0040; +pub const LVNI_SAMEGROUPONLY: ::LPARAM = 0x0080; +pub const LVNI_ABOVE: ::LPARAM = 0x0100; +pub const LVNI_BELOW: ::LPARAM = 0x0200; +pub const LVNI_TOLEFT: ::LPARAM = 0x0400; +pub const LVNI_TORIGHT: ::LPARAM = 0x0800; +pub const LVNI_DIRECTIONMASK: ::LPARAM = LVNI_ABOVE | LVNI_BELOW | LVNI_TOLEFT | LVNI_TORIGHT; +pub const LVFI_PARAM: ::UINT = 0x0001; +pub const LVFI_STRING: ::UINT = 0x0002; +pub const LVFI_SUBSTRING: ::UINT = 0x0004; +pub const LVFI_PARTIAL: ::UINT = 0x0008; +pub const LVFI_WRAP: ::UINT = 0x0020; +pub const LVFI_NEARESTXY: ::UINT = 0x0040; +pub type LV_FINDINFOA = LVFINDINFOA; +pub type LV_FINDINFOW = LVFINDINFOW; +STRUCT!{struct LVFINDINFOA { + flags: ::UINT, + psz: ::LPCSTR, + lParam: ::LPARAM, + pt: ::POINT, + vkDirection: ::UINT, +}} +pub type LPLVFINDINFOA = *mut LVFINDINFOA; +STRUCT!{struct LVFINDINFOW { + flags: ::UINT, + psz: ::LPCWSTR, + lParam: ::LPARAM, + pt: ::POINT, + vkDirection: ::UINT, +}} +pub type LPLVFINDINFOW = *mut LVFINDINFOW; +pub const LVM_FINDITEMA: ::UINT = LVM_FIRST + 13; +pub const LVM_FINDITEMW: ::UINT = LVM_FIRST + 83; +pub const LVIR_BOUNDS: ::c_int = 0; +pub const LVIR_ICON: ::c_int = 1; +pub const LVIR_LABEL: ::c_int = 2; +pub const LVIR_SELECTBOUNDS: ::c_int = 3; +pub const LVM_GETITEMRECT: ::UINT = LVM_FIRST + 14; +pub const LVM_SETITEMPOSITION: ::UINT = LVM_FIRST + 15; +pub const LVM_GETITEMPOSITION: ::UINT = LVM_FIRST + 16; +pub const LVM_GETSTRINGWIDTHA: ::UINT = LVM_FIRST + 17; +pub const LVM_GETSTRINGWIDTHW: ::UINT = LVM_FIRST + 87; +pub const LVHT_NOWHERE: ::UINT = 0x00000001; +pub const LVHT_ONITEMICON: ::UINT = 0x00000002; +pub const LVHT_ONITEMLABEL: ::UINT = 0x00000004; +pub const LVHT_ONITEMSTATEICON: ::UINT = 0x00000008; +pub const LVHT_ONITEM: ::UINT = LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON; +pub const LVHT_ABOVE: ::UINT = 0x00000008; +pub const LVHT_BELOW: ::UINT = 0x00000010; +pub const LVHT_TORIGHT: ::UINT = 0x00000020; +pub const LVHT_TOLEFT: ::UINT = 0x00000040; +pub const LVHT_EX_GROUP_HEADER: ::UINT = 0x10000000; +pub const LVHT_EX_GROUP_FOOTER: ::UINT = 0x20000000; +pub const LVHT_EX_GROUP_COLLAPSE: ::UINT = 0x40000000; +pub const LVHT_EX_GROUP_BACKGROUND: ::UINT = 0x80000000; +pub const LVHT_EX_GROUP_STATEICON: ::UINT = 0x01000000; +pub const LVHT_EX_GROUP_SUBSETLINK: ::UINT = 0x02000000; +pub const LVHT_EX_GROUP: ::UINT = LVHT_EX_GROUP_BACKGROUND | LVHT_EX_GROUP_COLLAPSE + | LVHT_EX_GROUP_FOOTER | LVHT_EX_GROUP_HEADER | LVHT_EX_GROUP_STATEICON + | LVHT_EX_GROUP_SUBSETLINK; +pub const LVHT_EX_ONCONTENTS: ::UINT = 0x04000000; +pub const LVHT_EX_FOOTER: ::UINT = 0x08000000; +pub type LV_HITTESTINFO = LVHITTESTINFO; +STRUCT!{struct LVHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + iItem: ::c_int, + iSubItem: ::c_int, + iGroup: ::c_int, +}} +pub type LPLVHITTESTINFO = *mut LVHITTESTINFO; +pub const LVM_HITTEST: ::UINT = LVM_FIRST + 18; +pub const LVM_ENSUREVISIBLE: ::UINT = LVM_FIRST + 19; +pub const LVM_SCROLL: ::UINT = LVM_FIRST + 20; +pub const LVM_REDRAWITEMS: ::UINT = LVM_FIRST + 21; +pub const LVA_DEFAULT: ::WPARAM = 0x0000; +pub const LVA_ALIGNLEFT: ::WPARAM = 0x0001; +pub const LVA_ALIGNTOP: ::WPARAM = 0x0002; +pub const LVA_SNAPTOGRID: ::WPARAM = 0x0005; +pub const LVM_ARRANGE: ::UINT = LVM_FIRST + 22; +pub const LVM_EDITLABELA: ::UINT = LVM_FIRST + 23; +pub const LVM_EDITLABELW: ::UINT = LVM_FIRST + 118; +pub const LVM_GETEDITCONTROL: ::UINT = LVM_FIRST + 24; +pub type LV_COLUMNA = LVCOLUMNA; +pub type LV_COLUMNW = LVCOLUMNW; +STRUCT!{struct LVCOLUMNA { + mask: ::UINT, + fmt: ::c_int, + cx: ::c_int, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iSubItem: ::c_int, + iImage: ::c_int, + iOrder: ::c_int, + cxMin: ::c_int, + cxDefault: ::c_int, + cxIdeal: ::c_int, +}} +pub type LPLVCOLUMNA = *mut LVCOLUMNA; +STRUCT!{struct LVCOLUMNW { + mask: ::UINT, + fmt: ::c_int, + cx: ::c_int, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iSubItem: ::c_int, + iImage: ::c_int, + iOrder: ::c_int, + cxMin: ::c_int, + cxDefault: ::c_int, + cxIdeal: ::c_int, +}} +pub type LPLVCOLUMNW = *mut LVCOLUMNW; +pub const LVCF_FMT: ::UINT = 0x0001; +pub const LVCF_WIDTH: ::UINT = 0x0002; +pub const LVCF_TEXT: ::UINT = 0x0004; +pub const LVCF_SUBITEM: ::UINT = 0x0008; +pub const LVCF_IMAGE: ::UINT = 0x0010; +pub const LVCF_ORDER: ::UINT = 0x0020; +pub const LVCF_MINWIDTH: ::UINT = 0x0040; +pub const LVCF_DEFAULTWIDTH: ::UINT = 0x0080; +pub const LVCF_IDEALWIDTH: ::UINT = 0x0100; +pub const LVCFMT_LEFT: ::c_int = 0x0000; +pub const LVCFMT_RIGHT: ::c_int = 0x0001; +pub const LVCFMT_CENTER: ::c_int = 0x0002; +pub const LVCFMT_JUSTIFYMASK: ::c_int = 0x0003; +pub const LVCFMT_IMAGE: ::c_int = 0x0800; +pub const LVCFMT_BITMAP_ON_RIGHT: ::c_int = 0x1000; +pub const LVCFMT_COL_HAS_IMAGES: ::c_int = 0x8000; +pub const LVCFMT_FIXED_WIDTH: ::c_int = 0x00100; +pub const LVCFMT_NO_DPI_SCALE: ::c_int = 0x40000; +pub const LVCFMT_FIXED_RATIO: ::c_int = 0x80000; +pub const LVCFMT_LINE_BREAK: ::c_int = 0x100000; +pub const LVCFMT_FILL: ::c_int = 0x200000; +pub const LVCFMT_WRAP: ::c_int = 0x400000; +pub const LVCFMT_NO_TITLE: ::c_int = 0x800000; +pub const LVCFMT_TILE_PLACEMENTMASK: ::c_int = LVCFMT_LINE_BREAK | LVCFMT_FILL; +pub const LVCFMT_SPLITBUTTON: ::c_int = 0x1000000; +pub const LVM_GETCOLUMNA: ::UINT = LVM_FIRST + 25; +pub const LVM_GETCOLUMNW: ::UINT = LVM_FIRST + 95; +pub const LVM_SETCOLUMNA: ::UINT = LVM_FIRST + 26; +pub const LVM_SETCOLUMNW: ::UINT = LVM_FIRST + 96; +pub const LVM_INSERTCOLUMNA: ::UINT = LVM_FIRST + 27; +pub const LVM_INSERTCOLUMNW: ::UINT = LVM_FIRST + 97; +pub const LVM_DELETECOLUMN: ::UINT = LVM_FIRST + 28; +pub const LVM_GETCOLUMNWIDTH: ::UINT = LVM_FIRST + 29; +pub const LVM_SETCOLUMNWIDTH: ::UINT = LVM_FIRST + 30; +pub const LVM_GETHEADER: ::UINT = LVM_FIRST + 31; +pub const LVM_CREATEDRAGIMAGE: ::UINT = LVM_FIRST + 33; +pub const LVM_GETVIEWRECT: ::UINT = LVM_FIRST + 34; +pub const LVM_GETTEXTCOLOR: ::UINT = LVM_FIRST + 35; +pub const LVM_SETTEXTCOLOR: ::UINT = LVM_FIRST + 36; +pub const LVM_GETTEXTBKCOLOR: ::UINT = LVM_FIRST + 37; +pub const LVM_SETTEXTBKCOLOR: ::UINT = LVM_FIRST + 38; +pub const LVM_GETTOPINDEX: ::UINT = LVM_FIRST + 39; +pub const LVM_GETCOUNTPERPAGE: ::UINT = LVM_FIRST + 40; +pub const LVM_GETORIGIN: ::UINT = LVM_FIRST + 41; +pub const LVM_UPDATE: ::UINT = LVM_FIRST + 42; +pub const LVM_SETITEMSTATE: ::UINT = LVM_FIRST + 43; +pub const LVM_GETITEMSTATE: ::UINT = LVM_FIRST + 44; +pub const LVM_GETITEMTEXTA: ::UINT = LVM_FIRST + 45; +pub const LVM_GETITEMTEXTW: ::UINT = LVM_FIRST + 115; +pub const LVM_SETITEMTEXTA: ::UINT = LVM_FIRST + 46; +pub const LVM_SETITEMTEXTW: ::UINT = LVM_FIRST + 116; +pub const LVM_SETITEMCOUNT: ::UINT = LVM_FIRST + 47; +pub const LVM_SORTITEMS: ::UINT = LVM_FIRST + 48; +pub const LVM_SETITEMPOSITION32: ::UINT = LVM_FIRST + 49; +pub const LVM_GETSELECTEDCOUNT: ::UINT = LVM_FIRST + 50; +pub const LVM_GETITEMSPACING: ::UINT = LVM_FIRST + 51; +pub const LVM_GETISEARCHSTRINGA: ::UINT = LVM_FIRST + 52; +pub const LVM_GETISEARCHSTRINGW: ::UINT = LVM_FIRST + 117; +pub const LVM_SETICONSPACING: ::UINT = LVM_FIRST + 53; +pub const LVM_SETEXTENDEDLISTVIEWSTYLE: ::UINT = LVM_FIRST + 54; +pub const LVM_GETEXTENDEDLISTVIEWSTYLE: ::UINT = LVM_FIRST + 55; +pub const LVSICF_NOINVALIDATEALL: ::LPARAM = 0x00000001; +pub const LVSICF_NOSCROLL: ::LPARAM = 0x00000002; +pub const LVS_EX_GRIDLINES: ::DWORD = 0x00000001; +pub const LVS_EX_SUBITEMIMAGES: ::DWORD = 0x00000002; +pub const LVS_EX_CHECKBOXES: ::DWORD = 0x00000004; +pub const LVS_EX_TRACKSELECT: ::DWORD = 0x00000008; +pub const LVS_EX_HEADERDRAGDROP: ::DWORD = 0x00000010; +pub const LVS_EX_FULLROWSELECT: ::DWORD = 0x00000020; +pub const LVS_EX_ONECLICKACTIVATE: ::DWORD = 0x00000040; +pub const LVS_EX_TWOCLICKACTIVATE: ::DWORD = 0x00000080; +pub const LVS_EX_FLATSB: ::DWORD = 0x00000100; +pub const LVS_EX_REGIONAL: ::DWORD = 0x00000200; +pub const LVS_EX_INFOTIP: ::DWORD = 0x00000400; +pub const LVS_EX_UNDERLINEHOT: ::DWORD = 0x00000800; +pub const LVS_EX_UNDERLINECOLD: ::DWORD = 0x00001000; +pub const LVS_EX_MULTIWORKAREAS: ::DWORD = 0x00002000; +pub const LVS_EX_LABELTIP: ::DWORD = 0x00004000; +pub const LVS_EX_BORDERSELECT: ::DWORD = 0x00008000; +pub const LVS_EX_DOUBLEBUFFER: ::DWORD = 0x00010000; +pub const LVS_EX_HIDELABELS: ::DWORD = 0x00020000; +pub const LVS_EX_SINGLEROW: ::DWORD = 0x00040000; +pub const LVS_EX_SNAPTOGRID: ::DWORD = 0x00080000; +pub const LVS_EX_SIMPLESELECT: ::DWORD = 0x00100000; +pub const LVS_EX_JUSTIFYCOLUMNS: ::DWORD = 0x00200000; +pub const LVS_EX_TRANSPARENTBKGND: ::DWORD = 0x00400000; +pub const LVS_EX_TRANSPARENTSHADOWTEXT: ::DWORD = 0x00800000; +pub const LVS_EX_AUTOAUTOARRANGE: ::DWORD = 0x01000000; +pub const LVS_EX_HEADERINALLVIEWS: ::DWORD = 0x02000000; +pub const LVS_EX_AUTOCHECKSELECT: ::DWORD = 0x08000000; +pub const LVS_EX_AUTOSIZECOLUMNS: ::DWORD = 0x10000000; +pub const LVS_EX_COLUMNSNAPPOINTS: ::DWORD = 0x40000000; +pub const LVS_EX_COLUMNOVERFLOW: ::DWORD = 0x80000000; +pub const LVM_GETSUBITEMRECT: ::UINT = LVM_FIRST + 56; +pub const LVM_SUBITEMHITTEST: ::UINT = LVM_FIRST + 57; +pub const LVM_SETCOLUMNORDERARRAY: ::UINT = LVM_FIRST + 58; +pub const LVM_GETCOLUMNORDERARRAY: ::UINT = LVM_FIRST + 59; +pub const LVM_SETHOTITEM: ::UINT = LVM_FIRST + 60; +pub const LVM_GETHOTITEM: ::UINT = LVM_FIRST + 61; +pub const LVM_SETHOTCURSOR: ::UINT = LVM_FIRST + 62; +pub const LVM_GETHOTCURSOR: ::UINT = LVM_FIRST + 63; +pub const LVM_APPROXIMATEVIEWRECT: ::UINT = LVM_FIRST + 64; +pub const LV_MAX_WORKAREAS: ::WPARAM = 16; +pub const LVM_SETWORKAREAS: ::UINT = LVM_FIRST + 65; +pub const LVM_GETWORKAREAS: ::UINT = LVM_FIRST + 70; +pub const LVM_GETNUMBEROFWORKAREAS: ::UINT = LVM_FIRST + 73; +pub const LVM_GETSELECTIONMARK: ::UINT = LVM_FIRST + 66; +pub const LVM_SETSELECTIONMARK: ::UINT = LVM_FIRST + 67; +pub const LVM_SETHOVERTIME: ::UINT = LVM_FIRST + 71; +pub const LVM_GETHOVERTIME: ::UINT = LVM_FIRST + 72; +pub const LVM_SETTOOLTIPS: ::UINT = LVM_FIRST + 74; +pub const LVM_GETTOOLTIPS: ::UINT = LVM_FIRST + 78; +pub const LVM_SORTITEMSEX: ::UINT = LVM_FIRST + 81; +STRUCT!{struct LVBKIMAGEA { + ulFlags: ::ULONG, + hbm: ::HBITMAP, + pszImage: ::LPSTR, + cchImageMax: ::UINT, + xOffsetPercent: ::c_int, + yOffsetPercent: ::c_int, +}} +pub type LPLVBKIMAGEA = *mut LVBKIMAGEA; +STRUCT!{struct LVBKIMAGEW { + ulFlags: ::ULONG, + hbm: ::HBITMAP, + pszImage: ::LPWSTR, + cchImageMax: ::UINT, + xOffsetPercent: ::c_int, + yOffsetPercent: ::c_int, +}} +pub type LPLVBKIMAGEW = *mut LVBKIMAGEW; +pub const LVBKIF_SOURCE_NONE: ::ULONG = 0x00000000; +pub const LVBKIF_SOURCE_HBITMAP: ::ULONG = 0x00000001; +pub const LVBKIF_SOURCE_URL: ::ULONG = 0x00000002; +pub const LVBKIF_SOURCE_MASK: ::ULONG = 0x00000003; +pub const LVBKIF_STYLE_NORMAL: ::ULONG = 0x00000000; +pub const LVBKIF_STYLE_TILE: ::ULONG = 0x00000010; +pub const LVBKIF_STYLE_MASK: ::ULONG = 0x00000010; +pub const LVBKIF_FLAG_TILEOFFSET: ::ULONG = 0x00000100; +pub const LVBKIF_TYPE_WATERMARK: ::ULONG = 0x10000000; +pub const LVBKIF_FLAG_ALPHABLEND: ::ULONG = 0x20000000; +pub const LVM_SETBKIMAGEA: ::UINT = LVM_FIRST + 68; +pub const LVM_SETBKIMAGEW: ::UINT = LVM_FIRST + 138; +pub const LVM_GETBKIMAGEA: ::UINT = LVM_FIRST + 69; +pub const LVM_GETBKIMAGEW: ::UINT = LVM_FIRST + 139; +pub const LVM_SETSELECTEDCOLUMN: ::UINT = LVM_FIRST + 140; +pub const LV_VIEW_ICON: ::DWORD = 0x0000; +pub const LV_VIEW_DETAILS: ::DWORD = 0x0001; +pub const LV_VIEW_SMALLICON: ::DWORD = 0x0002; +pub const LV_VIEW_LIST: ::DWORD = 0x0003; +pub const LV_VIEW_TILE: ::DWORD = 0x0004; +pub const LV_VIEW_MAX: ::DWORD = 0x0004; +pub const LVM_SETVIEW: ::UINT = LVM_FIRST + 142; +pub const LVM_GETVIEW: ::UINT = LVM_FIRST + 143; +pub const LVGF_NONE: ::UINT = 0x00000000; +pub const LVGF_HEADER: ::UINT = 0x00000001; +pub const LVGF_FOOTER: ::UINT = 0x00000002; +pub const LVGF_STATE: ::UINT = 0x00000004; +pub const LVGF_ALIGN: ::UINT = 0x00000008; +pub const LVGF_GROUPID: ::UINT = 0x00000010; +pub const LVGF_SUBTITLE: ::UINT = 0x00000100; +pub const LVGF_TASK: ::UINT = 0x00000200; +pub const LVGF_DESCRIPTIONTOP: ::UINT = 0x00000400; +pub const LVGF_DESCRIPTIONBOTTOM: ::UINT = 0x00000800; +pub const LVGF_TITLEIMAGE: ::UINT = 0x00001000; +pub const LVGF_EXTENDEDIMAGE: ::UINT = 0x00002000; +pub const LVGF_ITEMS: ::UINT = 0x00004000; +pub const LVGF_SUBSET: ::UINT = 0x00008000; +pub const LVGF_SUBSETITEMS: ::UINT = 0x00010000; +pub const LVGS_NORMAL: ::UINT = 0x00000000; +pub const LVGS_COLLAPSED: ::UINT = 0x00000001; +pub const LVGS_HIDDEN: ::UINT = 0x00000002; +pub const LVGS_NOHEADER: ::UINT = 0x00000004; +pub const LVGS_COLLAPSIBLE: ::UINT = 0x00000008; +pub const LVGS_FOCUSED: ::UINT = 0x00000010; +pub const LVGS_SELECTED: ::UINT = 0x00000020; +pub const LVGS_SUBSETED: ::UINT = 0x00000040; +pub const LVGS_SUBSETLINKFOCUSED: ::UINT = 0x00000080; +pub const LVGA_HEADER_LEFT: ::UINT = 0x00000001; +pub const LVGA_HEADER_CENTER: ::UINT = 0x00000002; +pub const LVGA_HEADER_RIGHT: ::UINT = 0x00000004; +pub const LVGA_FOOTER_LEFT: ::UINT = 0x00000008; +pub const LVGA_FOOTER_CENTER: ::UINT = 0x00000010; +pub const LVGA_FOOTER_RIGHT: ::UINT = 0x00000020; +STRUCT!{struct LVGROUP { + cbSize: ::UINT, + mask: ::UINT, + pszHeader: ::LPWSTR, + cchHeader: ::c_int, + pszFooter: ::LPWSTR, + cchFooter: ::c_int, + iGroupId: ::c_int, + stateMask: ::UINT, + state: ::UINT, + uAlign: ::UINT, + pszSubtitle: ::LPWSTR, + cchSubtitle: ::UINT, + pszTask: ::LPWSTR, + cchTask: ::UINT, + pszDescriptionTop: ::LPWSTR, + cchDescriptionTop: ::UINT, + pszDescriptionBottom: ::LPWSTR, + cchDescriptionBottom: ::UINT, + iTitleImage: ::c_int, + iExtendedImage: ::c_int, + iFirstItem: ::c_int, + cItems: ::UINT, + pszSubsetTitle: ::LPWSTR, + cchSubsetTitle: ::UINT, +}} +pub type PLVGROUP = *mut LVGROUP; +pub const LVM_INSERTGROUP: ::UINT = LVM_FIRST + 145; +pub const LVM_SETGROUPINFO: ::UINT = LVM_FIRST + 147; +pub const LVM_GETGROUPINFO: ::UINT = LVM_FIRST + 149; +pub const LVM_REMOVEGROUP: ::UINT = LVM_FIRST + 150; +pub const LVM_MOVEGROUP: ::UINT = LVM_FIRST + 151; +pub const LVM_GETGROUPCOUNT: ::UINT = LVM_FIRST + 152; +pub const LVM_GETGROUPINFOBYINDEX: ::UINT = LVM_FIRST + 153; +pub const LVM_MOVEITEMTOGROUP: ::UINT = LVM_FIRST + 154; +pub const LVM_GETGROUPRECT: ::UINT = LVM_FIRST + 98; +pub const LVGGR_GROUP: ::LPARAM = 0; +pub const LVGGR_HEADER: ::LPARAM = 1; +pub const LVGGR_LABEL: ::LPARAM = 2; +pub const LVGGR_SUBSETLINK: ::LPARAM = 3; +pub const LVGMF_NONE: ::UINT = 0x00000000; +pub const LVGMF_BORDERSIZE: ::UINT = 0x00000001; +pub const LVGMF_BORDERCOLOR: ::UINT = 0x00000002; +pub const LVGMF_TEXTCOLOR: ::UINT = 0x00000004; +STRUCT!{struct LVGROUPMETRICS { + cbSize: ::UINT, + mask: ::UINT, + Left: ::UINT, + Top: ::UINT, + Right: ::UINT, + Bottom: ::UINT, + crLeft: ::COLORREF, + crTop: ::COLORREF, + crRight: ::COLORREF, + crBottom: ::COLORREF, + crHeader: ::COLORREF, + crFooter: ::COLORREF, +}} +pub type PLVGROUPMETRICS = *mut LVGROUPMETRICS; +pub const LVM_SETGROUPMETRICS: ::UINT = LVM_FIRST + 155; +pub const LVM_GETGROUPMETRICS: ::UINT = LVM_FIRST + 156; +pub const LVM_ENABLEGROUPVIEW: ::UINT = LVM_FIRST + 157; +pub const LVM_SORTGROUPS: ::UINT = LVM_FIRST + 158; +pub type PFNLVGROUPCOMPARE = Option ::c_int>; +STRUCT!{nodebug struct LVINSERTGROUPSORTED { + pfnGroupCompare: PFNLVGROUPCOMPARE, + pvData: *mut ::c_void, + lvGroup: LVGROUP, +}} +pub type PLVINSERTGROUPSORTED = *mut LVINSERTGROUPSORTED; +pub const LVM_INSERTGROUPSORTED: ::UINT = LVM_FIRST + 159; +pub const LVM_REMOVEALLGROUPS: ::UINT = LVM_FIRST + 160; +pub const LVM_HASGROUP: ::UINT = LVM_FIRST + 161; +pub const LVM_GETGROUPSTATE: ::UINT = LVM_FIRST + 92; +pub const LVM_GETFOCUSEDGROUP: ::UINT = LVM_FIRST + 93; +pub const LVTVIF_AUTOSIZE: ::DWORD = 0x00000000; +pub const LVTVIF_FIXEDWIDTH: ::DWORD = 0x00000001; +pub const LVTVIF_FIXEDHEIGHT: ::DWORD = 0x00000002; +pub const LVTVIF_FIXEDSIZE: ::DWORD = 0x00000003; +pub const LVTVIF_EXTENDED: ::DWORD = 0x00000004; +pub const LVTVIM_TILESIZE: ::DWORD = 0x00000001; +pub const LVTVIM_COLUMNS: ::DWORD = 0x00000002; +pub const LVTVIM_LABELMARGIN: ::DWORD = 0x00000004; +STRUCT!{struct LVTILEVIEWINFO { + cbSize: ::UINT, + dwMask: ::DWORD, + dwFlags: ::DWORD, + sizeTile: ::SIZE, + cLines: ::c_int, + rcLabelMargin: ::RECT, +}} +pub type PLVTILEVIEWINFO = *mut LVTILEVIEWINFO; +STRUCT!{struct LVTILEINFO { + cbSize: ::UINT, + iItem: ::c_int, + cColumns: ::UINT, + puColumns: ::PUINT, + piColFmt: *mut ::c_int, +}} +pub type PLVTILEINFO = *mut LVTILEINFO; +pub const LVM_SETTILEVIEWINFO: ::UINT = LVM_FIRST + 162; +pub const LVM_GETTILEVIEWINFO: ::UINT = LVM_FIRST + 163; +pub const LVM_SETTILEINFO: ::UINT = LVM_FIRST + 164; +pub const LVM_GETTILEINFO: ::UINT = LVM_FIRST + 165; +STRUCT!{struct LVINSERTMARK { + cbSize: ::UINT, + dwFlags: ::DWORD, + iItem: ::c_int, + dwReserved: ::DWORD, +}} +pub type LPLVINSERTMARK = *mut LVINSERTMARK; +pub const LVIM_AFTER: ::DWORD = 0x00000001; +pub const LVM_SETINSERTMARK: ::UINT = LVM_FIRST + 166; +pub const LVM_GETINSERTMARK: ::UINT = LVM_FIRST + 167; +pub const LVM_INSERTMARKHITTEST: ::UINT = LVM_FIRST + 168; +pub const LVM_GETINSERTMARKRECT: ::UINT = LVM_FIRST + 169; +pub const LVM_SETINSERTMARKCOLOR: ::UINT = LVM_FIRST + 170; +pub const LVM_GETINSERTMARKCOLOR: ::UINT = LVM_FIRST + 171; +STRUCT!{struct LVSETINFOTIP { + cbSize: ::UINT, + dwFlags: ::DWORD, + pszText: ::LPWSTR, + iItem: ::c_int, + iSubItem: ::c_int, +}} +pub type PLVSETINFOTIP = *mut LVSETINFOTIP; +pub const LVM_SETINFOTIP: ::UINT = LVM_FIRST + 173; +pub const LVM_GETSELECTEDCOLUMN: ::UINT = LVM_FIRST + 174; +pub const LVM_ISGROUPVIEWENABLED: ::UINT = LVM_FIRST + 175; +pub const LVM_GETOUTLINECOLOR: ::UINT = LVM_FIRST + 176; +pub const LVM_SETOUTLINECOLOR: ::UINT = LVM_FIRST + 177; +pub const LVM_CANCELEDITLABEL: ::UINT = LVM_FIRST + 179; +pub const LVM_MAPINDEXTOID: ::UINT = LVM_FIRST + 180; +pub const LVM_MAPIDTOINDEX: ::UINT = LVM_FIRST + 181; +pub const LVM_ISITEMVISIBLE: ::UINT = LVM_FIRST + 182; +pub const LVM_GETEMPTYTEXT: ::UINT = LVM_FIRST + 204; +pub const LVM_GETFOOTERRECT: ::UINT = LVM_FIRST + 205; +pub const LVFF_ITEMCOUNT: ::UINT = 0x00000001; +STRUCT!{struct LVFOOTERINFO { + mask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + cItems: ::UINT, +}} +pub type LPLVFOOTERINFO = *mut LVFOOTERINFO; +pub const LVM_GETFOOTERINFO: ::UINT = LVM_FIRST + 206; +pub const LVM_GETFOOTERITEMRECT: ::UINT = LVM_FIRST + 207; +pub const LVFIF_TEXT: ::UINT = 0x00000001; +pub const LVFIF_STATE: ::UINT = 0x00000002; +pub const LVFIS_FOCUSED: ::UINT = 0x0001; +STRUCT!{struct LVFOOTERITEM { + mask: ::UINT, + iItem: ::c_int, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + state: ::UINT, + stateMask: ::UINT, +}} +pub type LPLVFOOTERITEM = *mut LVFOOTERITEM; +pub const LVM_GETFOOTERITEM: ::UINT = LVM_FIRST + 208; +STRUCT!{struct LVITEMINDEX { + iItem: ::c_int, + iGroup: ::c_int, +}} +pub type PLVITEMINDEX = *mut LVITEMINDEX; +pub const LVM_GETITEMINDEXRECT: ::UINT = LVM_FIRST + 209; +pub const LVM_SETITEMINDEXSTATE: ::UINT = LVM_FIRST + 210; +pub const LVM_GETNEXTITEMINDEX: ::UINT = LVM_FIRST + 211; +pub type LPNM_LISTVIEW = LPNMLISTVIEW; +pub type NM_LISTVIEW = NMLISTVIEW; +STRUCT!{struct NMLISTVIEW { + hdr: ::NMHDR, + iItem: ::c_int, + iSubItem: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, + uChanged: ::UINT, + ptAction: ::POINT, + lParam: ::LPARAM, +}} +pub type LPNMLISTVIEW = *mut NMLISTVIEW; +STRUCT!{struct NMITEMACTIVATE { + hdr: ::NMHDR, + iItem: ::c_int, + iSubItem: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, + uChanged: ::UINT, + ptAction: ::POINT, + lParam: ::LPARAM, + uKeyFlags: ::UINT, +}} +pub type LPNMITEMACTIVATE = *mut NMITEMACTIVATE; +pub const LVKF_ALT: ::UINT = 0x0001; +pub const LVKF_CONTROL: ::UINT = 0x0002; +pub const LVKF_SHIFT: ::UINT = 0x0004; +STRUCT!{struct NMLVCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + clrText: ::COLORREF, + clrTextBk: ::COLORREF, + iSubItem: ::c_int, + dwItemType: ::DWORD, + clrFace: ::COLORREF, + iIconEffect: ::c_int, + iIconPhase: ::c_int, + iPartId: ::c_int, + iStateId: ::c_int, + rcText: ::RECT, + uAlign: ::UINT, +}} +pub type LPNMLVCUSTOMDRAW = *mut NMLVCUSTOMDRAW; +pub const LVCDI_ITEM: ::DWORD = 0x00000000; +pub const LVCDI_GROUP: ::DWORD = 0x00000001; +pub const LVCDI_ITEMSLIST: ::DWORD = 0x00000002; +pub const LVCDRF_NOSELECT: ::LRESULT = 0x00010000; +pub const LVCDRF_NOGROUPFRAME: ::LRESULT = 0x00020000; +STRUCT!{struct NMLVCACHEHINT { + hdr: ::NMHDR, + iFrom: ::c_int, + iTo: ::c_int, +}} +pub type LPNMLVCACHEHINT = *mut NMLVCACHEHINT; +pub type LPNM_CACHEHINT = LPNMLVCACHEHINT; +pub type PNM_CACHEHINT = LPNMLVCACHEHINT; +pub type NM_CACHEHINT = NMLVCACHEHINT; +STRUCT!{struct NMLVFINDITEMA { + hdr: ::NMHDR, + iStart: ::c_int, + lvfi: LVFINDINFOA, +}} +pub type LPNMLVFINDITEMA = *mut NMLVFINDITEMA; +STRUCT!{struct NMLVFINDITEMW { + hdr: ::NMHDR, + iStart: ::c_int, + lvfi: LVFINDINFOW, +}} +pub type LPNMLVFINDITEMW = *mut NMLVFINDITEMW; +pub type PNM_FINDITEMA = LPNMLVFINDITEMA; +pub type LPNM_FINDITEMA = LPNMLVFINDITEMA; +pub type NM_FINDITEMA = NMLVFINDITEMA; +pub type PNM_FINDITEMW = LPNMLVFINDITEMW; +pub type LPNM_FINDITEMW = LPNMLVFINDITEMW; +pub type NM_FINDITEMW = NMLVFINDITEMW; +STRUCT!{struct NMLVODSTATECHANGE { + hdr: ::NMHDR, + iFrom: ::c_int, + iTo: ::c_int, + uNewState: ::UINT, + uOldState: ::UINT, +}} +pub type LPNMLVODSTATECHANGE = *mut NMLVODSTATECHANGE; +pub type PNM_ODSTATECHANGE = LPNMLVODSTATECHANGE; +pub type LPNM_ODSTATECHANGE = LPNMLVODSTATECHANGE; +pub type NM_ODSTATECHANGE = NMLVODSTATECHANGE; +pub const LVN_ITEMCHANGING: ::UINT = LVN_FIRST - 0; +pub const LVN_ITEMCHANGED: ::UINT = LVN_FIRST - 1; +pub const LVN_INSERTITEM: ::UINT = LVN_FIRST - 2; +pub const LVN_DELETEITEM: ::UINT = LVN_FIRST - 3; +pub const LVN_DELETEALLITEMS: ::UINT = LVN_FIRST - 4; +pub const LVN_BEGINLABELEDITA: ::UINT = LVN_FIRST - 5; +pub const LVN_BEGINLABELEDITW: ::UINT = LVN_FIRST - 75; +pub const LVN_ENDLABELEDITA: ::UINT = LVN_FIRST - 6; +pub const LVN_ENDLABELEDITW: ::UINT = LVN_FIRST - 76; +pub const LVN_COLUMNCLICK: ::UINT = LVN_FIRST - 8; +pub const LVN_BEGINDRAG: ::UINT = LVN_FIRST - 9; +pub const LVN_BEGINRDRAG: ::UINT = LVN_FIRST - 11; +pub const LVN_ODCACHEHINT: ::UINT = LVN_FIRST - 13; +pub const LVN_ODFINDITEMA: ::UINT = LVN_FIRST - 52; +pub const LVN_ODFINDITEMW: ::UINT = LVN_FIRST - 79; +pub const LVN_ITEMACTIVATE: ::UINT = LVN_FIRST - 14; +pub const LVN_ODSTATECHANGED: ::UINT = LVN_FIRST - 15; +pub const LVN_HOTTRACK: ::UINT = LVN_FIRST - 21; +pub const LVN_GETDISPINFOA: ::UINT = LVN_FIRST - 50; +pub const LVN_GETDISPINFOW: ::UINT = LVN_FIRST - 77; +pub const LVN_SETDISPINFOA: ::UINT = LVN_FIRST - 51; +pub const LVN_SETDISPINFOW: ::UINT = LVN_FIRST - 78; +pub const LVIF_DI_SETITEM: ::UINT = 0x1000; +pub type LV_DISPINFOA = NMLVDISPINFOA; +pub type LV_DISPINFOW = NMLVDISPINFOW; +STRUCT!{struct NMLVDISPINFOA { + hdr: ::NMHDR, + item: LVITEMA, +}} +pub type LPNMLVDISPINFOA = *mut NMLVDISPINFOA; +STRUCT!{struct NMLVDISPINFOW { + hdr: ::NMHDR, + item: LVITEMW, +}} +pub type LPNMLVDISPINFOW = *mut NMLVDISPINFOW; +pub const LVN_KEYDOWN: ::UINT = LVN_FIRST - 55; +pub type LV_KEYDOWN = NMLVKEYDOWN; +STRUCT!{struct NMLVKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub type LPNMLVKEYDOWN = *mut NMLVKEYDOWN; +pub const LVN_MARQUEEBEGIN: ::UINT = LVN_FIRST - 56; +STRUCT!{nodebug struct NMLVLINK { + hdr: ::NMHDR, + link: LITEM, + iItem: ::c_int, + iSubItem: ::c_int, +}} +pub type PNMLVLINK = *mut NMLVLINK; +STRUCT!{struct NMLVGETINFOTIPA { + hdr: ::NMHDR, + dwFlags: ::DWORD, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + iSubItem: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMLVGETINFOTIPA = *mut NMLVGETINFOTIPA; +STRUCT!{struct NMLVGETINFOTIPW { + hdr: ::NMHDR, + dwFlags: ::DWORD, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iItem: ::c_int, + iSubItem: ::c_int, + lParam: ::LPARAM, +}} +pub type LPNMLVGETINFOTIPW = *mut NMLVGETINFOTIPW; +pub const LVGIT_UNFOLDED: ::DWORD = 0x0001; +pub const LVN_GETINFOTIPA: ::UINT = LVN_FIRST - 57; +pub const LVN_GETINFOTIPW: ::UINT = LVN_FIRST - 58; +pub const LVNSCH_DEFAULT: ::LPARAM = -1; +pub const LVNSCH_ERROR: ::LPARAM = -2; +pub const LVNSCH_IGNORE: ::LPARAM = -3; +pub const LVN_INCREMENTALSEARCHA: ::UINT = LVN_FIRST - 62; +pub const LVN_INCREMENTALSEARCHW: ::UINT = LVN_FIRST - 63; +pub const LVN_COLUMNDROPDOWN: ::UINT = LVN_FIRST - 64; +pub const LVN_COLUMNOVERFLOWCLICK: ::UINT = LVN_FIRST - 66; +STRUCT!{struct NMLVSCROLL { + hdr: ::NMHDR, + dx: ::c_int, + dy: ::c_int, +}} +pub type LPNMLVSCROLL = *mut NMLVSCROLL; +pub const LVN_BEGINSCROLL: ::UINT = LVN_FIRST - 80; +pub const LVN_ENDSCROLL: ::UINT = LVN_FIRST - 81; +pub const LVN_LINKCLICK: ::UINT = LVN_FIRST - 84; +pub const EMF_CENTERED: ::DWORD = 0x00000001; +STRUCT!{nodebug struct NMLVEMPTYMARKUP { + hdr: ::NMHDR, + dwFlags: ::DWORD, + szMarkup: [::WCHAR; L_MAX_URL_LENGTH], +}} +pub const LVN_GETEMPTYMARKUP: ::UINT = LVN_FIRST - 87; +pub const TVS_HASBUTTONS: ::DWORD = 0x0001; +pub const TVS_HASLINES: ::DWORD = 0x0002; +pub const TVS_LINESATROOT: ::DWORD = 0x0004; +pub const TVS_EDITLABELS: ::DWORD = 0x0008; +pub const TVS_DISABLEDRAGDROP: ::DWORD = 0x0010; +pub const TVS_SHOWSELALWAYS: ::DWORD = 0x0020; +pub const TVS_RTLREADING: ::DWORD = 0x0040; +pub const TVS_NOTOOLTIPS: ::DWORD = 0x0080; +pub const TVS_CHECKBOXES: ::DWORD = 0x0100; +pub const TVS_TRACKSELECT: ::DWORD = 0x0200; +pub const TVS_SINGLEEXPAND: ::DWORD = 0x0400; +pub const TVS_INFOTIP: ::DWORD = 0x0800; +pub const TVS_FULLROWSELECT: ::DWORD = 0x1000; +pub const TVS_NOSCROLL: ::DWORD = 0x2000; +pub const TVS_NONEVENHEIGHT: ::DWORD = 0x4000; +pub const TVS_NOHSCROLL: ::DWORD = 0x8000; +pub const TVS_EX_NOSINGLECOLLAPSE: ::DWORD = 0x0001; +pub const TVS_EX_MULTISELECT: ::DWORD = 0x0002; +pub const TVS_EX_DOUBLEBUFFER: ::DWORD = 0x0004; +pub const TVS_EX_NOINDENTSTATE: ::DWORD = 0x0008; +pub const TVS_EX_RICHTOOLTIP: ::DWORD = 0x0010; +pub const TVS_EX_AUTOHSCROLL: ::DWORD = 0x0020; +pub const TVS_EX_FADEINOUTEXPANDOS: ::DWORD = 0x0040; +pub const TVS_EX_PARTIALCHECKBOXES: ::DWORD = 0x0080; +pub const TVS_EX_EXCLUSIONCHECKBOXES: ::DWORD = 0x0100; +pub const TVS_EX_DIMMEDCHECKBOXES: ::DWORD = 0x0200; +pub const TVS_EX_DRAWIMAGEASYNC: ::DWORD = 0x0400; +pub enum TREEITEM {} +pub type HTREEITEM = *mut TREEITEM; +pub const TVIF_TEXT: ::UINT = 0x0001; +pub const TVIF_IMAGE: ::UINT = 0x0002; +pub const TVIF_PARAM: ::UINT = 0x0004; +pub const TVIF_STATE: ::UINT = 0x0008; +pub const TVIF_HANDLE: ::UINT = 0x0010; +pub const TVIF_SELECTEDIMAGE: ::UINT = 0x0020; +pub const TVIF_CHILDREN: ::UINT = 0x0040; +pub const TVIF_INTEGRAL: ::UINT = 0x0080; +pub const TVIF_STATEEX: ::UINT = 0x0100; +pub const TVIF_EXPANDEDIMAGE: ::UINT = 0x0200; +pub const TVIS_SELECTED: ::UINT = 0x0002; +pub const TVIS_CUT: ::UINT = 0x0004; +pub const TVIS_DROPHILITED: ::UINT = 0x0008; +pub const TVIS_BOLD: ::UINT = 0x0010; +pub const TVIS_EXPANDED: ::UINT = 0x0020; +pub const TVIS_EXPANDEDONCE: ::UINT = 0x0040; +pub const TVIS_EXPANDPARTIAL: ::UINT = 0x0080; +pub const TVIS_OVERLAYMASK: ::UINT = 0x0F00; +pub const TVIS_STATEIMAGEMASK: ::UINT = 0xF000; +pub const TVIS_USERMASK: ::UINT = 0xF000; +pub const TVIS_EX_FLAT: ::UINT = 0x0001; +pub const TVIS_EX_DISABLED: ::UINT = 0x0002; +pub const TVIS_EX_ALL: ::UINT = 0x0002; +STRUCT!{struct NMTVSTATEIMAGECHANGING { + hdr: ::NMHDR, + hti: HTREEITEM, + iOldStateImageIndex: ::c_int, + iNewStateImageIndex: ::c_int, +}} +pub type LPNMTVSTATEIMAGECHANGING = *mut NMTVSTATEIMAGECHANGING; +pub const I_CHILDRENCALLBACK: ::c_int = -1; +pub const I_CHILDRENAUTO: ::c_int = -2; +pub type LPTV_ITEMW = LPTVITEMW; +pub type LPTV_ITEMA = LPTVITEMA; +pub type TV_ITEMW = TVITEMW; +pub type TV_ITEMA = TVITEMA; +STRUCT!{struct TVITEMA { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTVITEMA = *mut TVITEMA; +STRUCT!{struct TVITEMW { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTVITEMW = *mut TVITEMW; +STRUCT!{struct TVITEMEXA { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, + iIntegral: ::c_int, + uStateEx: ::UINT, + hwnd: ::HWND, + iExpandedImage: ::c_int, + iReserved: ::c_int, +}} +pub type LPTVITEMEXA = *mut TVITEMEXA; +STRUCT!{struct TVITEMEXW { + mask: ::UINT, + hItem: HTREEITEM, + state: ::UINT, + stateMask: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + cChildren: ::c_int, + lParam: ::LPARAM, + iIntegral: ::c_int, + uStateEx: ::UINT, + hwnd: ::HWND, + iExpandedImage: ::c_int, + iReserved: ::c_int, +}} +pub type LPTVITEMEXW = *mut TVITEMEXW; +pub const TVI_ROOT: HTREEITEM = (0 - 0x10000) as HTREEITEM; +pub const TVI_FIRST: HTREEITEM = (0 - 0x0FFFF) as HTREEITEM; +pub const TVI_LAST: HTREEITEM = (0 - 0x0FFFE) as HTREEITEM; +pub const TVI_SORT: HTREEITEM = (0 - 0x0FFFD) as HTREEITEM; +pub type LPTV_INSERTSTRUCTA = LPTVINSERTSTRUCTA; +pub type LPTV_INSERTSTRUCTW = LPTVINSERTSTRUCTW; +pub type TV_INSERTSTRUCTA = TVINSERTSTRUCTA; +pub type TV_INSERTSTRUCTW = TVINSERTSTRUCTW; +STRUCT!{struct TVINSERTSTRUCTA { + hParent: HTREEITEM, + hInsertAfter: HTREEITEM, + itemex: TVITEMEXA, +}} +UNION!(TVINSERTSTRUCTA, itemex, item, item_mut, TV_ITEMA); +pub type LPTVINSERTSTRUCTA = *mut TVINSERTSTRUCTA; +STRUCT!{struct TVINSERTSTRUCTW { + hParent: HTREEITEM, + hInsertAfter: HTREEITEM, + itemex: TVITEMEXW, +}} +UNION!(TVINSERTSTRUCTW, itemex, item, item_mut, TV_ITEMW); +pub type LPTVINSERTSTRUCTW = *mut TVINSERTSTRUCTW; +pub const TVM_INSERTITEMA: ::UINT = TV_FIRST + 0; +pub const TVM_INSERTITEMW: ::UINT = TV_FIRST + 50; +pub const TVM_DELETEITEM: ::UINT = TV_FIRST + 1; +pub const TVM_EXPAND: ::UINT = TV_FIRST + 2; +pub const TVM_GETITEMRECT: ::UINT = TV_FIRST + 4; +pub const TVE_COLLAPSE: ::WPARAM = 0x0001; +pub const TVE_EXPAND: ::WPARAM = 0x0002; +pub const TVE_TOGGLE: ::WPARAM = 0x0003; +pub const TVE_EXPANDPARTIAL: ::WPARAM = 0x4000; +pub const TVE_COLLAPSERESET: ::WPARAM = 0x8000; +pub const TVM_GETCOUNT: ::UINT = TV_FIRST + 5; +pub const TVM_GETINDENT: ::UINT = TV_FIRST + 6; +pub const TVM_SETINDENT: ::UINT = TV_FIRST + 7; +pub const TVM_GETIMAGELIST: ::UINT = TV_FIRST + 8; +pub const TVM_SETIMAGELIST: ::UINT = TV_FIRST + 9; +pub const TVM_GETNEXTITEM: ::UINT = TV_FIRST + 10; +pub const TVSIL_NORMAL: ::WPARAM = 0; +pub const TVSIL_STATE: ::WPARAM = 2; +pub const TVGN_ROOT: ::WPARAM = 0x0000; +pub const TVGN_NEXT: ::WPARAM = 0x0001; +pub const TVGN_PREVIOUS: ::WPARAM = 0x0002; +pub const TVGN_PARENT: ::WPARAM = 0x0003; +pub const TVGN_CHILD: ::WPARAM = 0x0004; +pub const TVGN_FIRSTVISIBLE: ::WPARAM = 0x0005; +pub const TVGN_NEXTVISIBLE: ::WPARAM = 0x0006; +pub const TVGN_PREVIOUSVISIBLE: ::WPARAM = 0x0007; +pub const TVGN_DROPHILITE: ::WPARAM = 0x0008; +pub const TVGN_CARET: ::WPARAM = 0x0009; +pub const TVGN_LASTVISIBLE: ::WPARAM = 0x000A; +pub const TVGN_NEXTSELECTED: ::WPARAM = 0x000B; +pub const TVSI_NOSINGLEEXPAND: ::WPARAM = 0x8000; +pub const TVM_SELECTITEM: ::UINT = TV_FIRST + 11; +pub const TVM_GETITEMA: ::UINT = TV_FIRST + 12; +pub const TVM_GETITEMW: ::UINT = TV_FIRST + 62; +pub const TVM_SETITEMA: ::UINT = TV_FIRST + 13; +pub const TVM_SETITEMW: ::UINT = TV_FIRST + 63; +pub const TVM_EDITLABELA: ::UINT = TV_FIRST + 14; +pub const TVM_EDITLABELW: ::UINT = TV_FIRST + 65; +pub const TVM_GETEDITCONTROL: ::UINT = TV_FIRST + 15; +pub const TVM_GETVISIBLECOUNT: ::UINT = TV_FIRST + 16; +pub const TVM_HITTEST: ::UINT = TV_FIRST + 17; +pub type LPTV_HITTESTINFO = LPTVHITTESTINFO; +pub type TV_HITTESTINFO = TVHITTESTINFO; +STRUCT!{struct TVHITTESTINFO { + pt: ::POINT, + flags: ::UINT, + hItem: HTREEITEM, +}} +pub type LPTVHITTESTINFO = *mut TVHITTESTINFO; +pub const TVHT_NOWHERE: ::UINT = 0x0001; +pub const TVHT_ONITEMICON: ::UINT = 0x0002; +pub const TVHT_ONITEMLABEL: ::UINT = 0x0004; +pub const TVHT_ONITEM: ::UINT = TVHT_ONITEMICON | TVHT_ONITEMLABEL | TVHT_ONITEMSTATEICON; +pub const TVHT_ONITEMINDENT: ::UINT = 0x0008; +pub const TVHT_ONITEMBUTTON: ::UINT = 0x0010; +pub const TVHT_ONITEMRIGHT: ::UINT = 0x0020; +pub const TVHT_ONITEMSTATEICON: ::UINT = 0x0040; +pub const TVHT_ABOVE: ::UINT = 0x0100; +pub const TVHT_BELOW: ::UINT = 0x0200; +pub const TVHT_TORIGHT: ::UINT = 0x0400; +pub const TVHT_TOLEFT: ::UINT = 0x0800; +pub const TVM_CREATEDRAGIMAGE: ::UINT = TV_FIRST + 18; +pub const TVM_SORTCHILDREN: ::UINT = TV_FIRST + 19; +pub const TVM_ENSUREVISIBLE: ::UINT = TV_FIRST + 20; +pub const TVM_SORTCHILDRENCB: ::UINT = TV_FIRST + 21; +pub const TVM_ENDEDITLABELNOW: ::UINT = TV_FIRST + 22; +pub const TVM_GETISEARCHSTRINGA: ::UINT = TV_FIRST + 23; +pub const TVM_GETISEARCHSTRINGW: ::UINT = TV_FIRST + 64; +pub const TVM_SETTOOLTIPS: ::UINT = TV_FIRST + 24; +pub const TVM_GETTOOLTIPS: ::UINT = TV_FIRST + 25; +pub const TVM_SETINSERTMARK: ::UINT = TV_FIRST + 26; +pub const TVM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TVM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TVM_SETITEMHEIGHT: ::UINT = TV_FIRST + 27; +pub const TVM_GETITEMHEIGHT: ::UINT = TV_FIRST + 28; +pub const TVM_SETBKCOLOR: ::UINT = TV_FIRST + 29; +pub const TVM_SETTEXTCOLOR: ::UINT = TV_FIRST + 30; +pub const TVM_GETBKCOLOR: ::UINT = TV_FIRST + 31; +pub const TVM_GETTEXTCOLOR: ::UINT = TV_FIRST + 32; +pub const TVM_SETSCROLLTIME: ::UINT = TV_FIRST + 33; +pub const TVM_GETSCROLLTIME: ::UINT = TV_FIRST + 34; +pub const TVM_SETINSERTMARKCOLOR: ::UINT = TV_FIRST + 37; +pub const TVM_GETINSERTMARKCOLOR: ::UINT = TV_FIRST + 38; +pub const TVM_SETBORDER: ::UINT = TV_FIRST + 35; +pub const TVSBF_XBORDER: ::WPARAM = 0x00000001; +pub const TVSBF_YBORDER: ::WPARAM = 0x00000002; +pub const TVM_GETITEMSTATE: ::UINT = TV_FIRST + 39; +pub const TVM_SETLINECOLOR: ::UINT = TV_FIRST + 40; +pub const TVM_GETLINECOLOR: ::UINT = TV_FIRST + 41; +pub const TVM_MAPACCIDTOHTREEITEM: ::UINT = TV_FIRST + 42; +pub const TVM_MAPHTREEITEMTOACCID: ::UINT = TV_FIRST + 43; +pub const TVM_SETEXTENDEDSTYLE: ::UINT = TV_FIRST + 44; +pub const TVM_GETEXTENDEDSTYLE: ::UINT = TV_FIRST + 45; +pub const TVM_SETAUTOSCROLLINFO: ::UINT = TV_FIRST + 59; +pub const TVM_SETHOT: ::UINT = TV_FIRST + 58; +pub const TVM_GETSELECTEDCOUNT: ::UINT = TV_FIRST + 70; +pub const TVM_SHOWINFOTIP: ::UINT = TV_FIRST + 71; +ENUM!{enum TVITEMPART { + TVGIPR_BUTTON = 0x0001, +}} +STRUCT!{struct TVGETITEMPARTRECTINFO { + hti: HTREEITEM, + prc: *mut ::RECT, + partID: TVITEMPART, +}} +pub const TVM_GETITEMPARTRECT: ::UINT = TV_FIRST + 72; +pub type PFNTVCOMPARE = Option ::c_int>; +pub type LPTV_SORTCB = LPTVSORTCB; +pub type TV_SORTCB = TVSORTCB; +STRUCT!{nodebug struct TVSORTCB { + hParent: HTREEITEM, + lpfnCompare: PFNTVCOMPARE, + lParam: ::LPARAM, +}} +pub type LPTVSORTCB = *mut TVSORTCB; +pub type LPNM_TREEVIEWA = LPNMTREEVIEWA; +pub type LPNM_TREEVIEWW = LPNMTREEVIEWW; +pub type NM_TREEVIEWA = NMTREEVIEWA; +pub type NM_TREEVIEWW = NMTREEVIEWW; +STRUCT!{struct NMTREEVIEWA { + hdr: ::NMHDR, + action: ::UINT, + itemOld: TVITEMA, + itemNew: TVITEMA, + ptDrag: ::POINT, +}} +pub type LPNMTREEVIEWA = *mut NMTREEVIEWA; +STRUCT!{struct NMTREEVIEWW { + hdr: ::NMHDR, + action: ::UINT, + itemOld: TVITEMW, + itemNew: TVITEMW, + ptDrag: ::POINT, +}} +pub type LPNMTREEVIEWW = *mut NMTREEVIEWW; +pub const TVN_SELCHANGINGA: ::UINT = TVN_FIRST - 1; +pub const TVN_SELCHANGINGW: ::UINT = TVN_FIRST - 50; +pub const TVN_SELCHANGEDA: ::UINT = TVN_FIRST - 2; +pub const TVN_SELCHANGEDW: ::UINT = TVN_FIRST - 51; +pub const TVN_GETDISPINFOA: ::UINT = TVN_FIRST - 3; +pub const TVN_GETDISPINFOW: ::UINT = TVN_FIRST - 52; +pub const TVN_SETDISPINFOA: ::UINT = TVN_FIRST - 4; +pub const TVN_SETDISPINFOW: ::UINT = TVN_FIRST - 53; +pub const TVC_UNKNOWN: ::LPARAM = 0x0000; +pub const TVC_BYMOUSE: ::LPARAM = 0x0001; +pub const TVC_BYKEYBOARD: ::LPARAM = 0x0002; +pub const TVIF_DI_SETITEM: ::UINT = 0x1000; +pub type TV_DISPINFOA = NMTVDISPINFOA; +pub type TV_DISPINFOW = NMTVDISPINFOW; +STRUCT!{struct NMTVDISPINFOA { + hdr: ::NMHDR, + item: TVITEMA, +}} +pub type LPNMTVDISPINFOA = *mut NMTVDISPINFOA; +STRUCT!{struct NMTVDISPINFOW { + hdr: ::NMHDR, + item: TVITEMW, +}} +pub type LPNMTVDISPINFOW = *mut NMTVDISPINFOW; +STRUCT!{struct NMTVDISPINFOEXA { + hdr: ::NMHDR, + item: TVITEMEXA, +}} +pub type LPNMTVDISPINFOEXA = *mut NMTVDISPINFOEXA; +STRUCT!{struct NMTVDISPINFOEXW { + hdr: ::NMHDR, + item: TVITEMEXW, +}} +pub type LPNMTVDISPINFOEXW = *mut NMTVDISPINFOEXW; +pub type TV_DISPINFOEXA = NMTVDISPINFOEXA; +pub type TV_DISPINFOEXW = NMTVDISPINFOEXW; +pub const TVN_ITEMEXPANDINGA: ::UINT = TVN_FIRST - 5; +pub const TVN_ITEMEXPANDINGW: ::UINT = TVN_FIRST - 54; +pub const TVN_ITEMEXPANDEDA: ::UINT = TVN_FIRST - 6; +pub const TVN_ITEMEXPANDEDW: ::UINT = TVN_FIRST - 55; +pub const TVN_BEGINDRAGA: ::UINT = TVN_FIRST - 7; +pub const TVN_BEGINDRAGW: ::UINT = TVN_FIRST - 56; +pub const TVN_BEGINRDRAGA: ::UINT = TVN_FIRST - 8; +pub const TVN_BEGINRDRAGW: ::UINT = TVN_FIRST - 57; +pub const TVN_DELETEITEMA: ::UINT = TVN_FIRST - 9; +pub const TVN_DELETEITEMW: ::UINT = TVN_FIRST - 58; +pub const TVN_BEGINLABELEDITA: ::UINT = TVN_FIRST - 10; +pub const TVN_BEGINLABELEDITW: ::UINT = TVN_FIRST - 59; +pub const TVN_ENDLABELEDITA: ::UINT = TVN_FIRST - 11; +pub const TVN_ENDLABELEDITW: ::UINT = TVN_FIRST - 60; +pub const TVN_KEYDOWN: ::UINT = TVN_FIRST - 12; +pub const TVN_GETINFOTIPA: ::UINT = TVN_FIRST - 13; +pub const TVN_GETINFOTIPW: ::UINT = TVN_FIRST - 14; +pub const TVN_SINGLEEXPAND: ::UINT = TVN_FIRST - 15; +pub const TVN_ITEMCHANGINGA: ::UINT = TVN_FIRST - 16; +pub const TVN_ITEMCHANGINGW: ::UINT = TVN_FIRST - 17; +pub const TVN_ITEMCHANGEDA: ::UINT = TVN_FIRST - 18; +pub const TVN_ITEMCHANGEDW: ::UINT = TVN_FIRST - 19; +pub const TVN_ASYNCDRAW: ::UINT = TVN_FIRST - 20; +pub const TVNRET_DEFAULT: ::LRESULT = 0; +pub const TVNRET_SKIPOLD: ::LRESULT = 1; +pub const TVNRET_SKIPNEW: ::LRESULT = 2; +pub type TV_KEYDOWN = NMTVKEYDOWN; +STRUCT!{struct NMTVKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub type LPNMTVKEYDOWN = *mut NMTVKEYDOWN; +STRUCT!{struct NMTVCUSTOMDRAW { + nmcd: NMCUSTOMDRAW, + clrText: ::COLORREF, + clrTextBk: ::COLORREF, + iLevel: ::c_int, +}} +pub type LPNMTVCUSTOMDRAW = *mut NMTVCUSTOMDRAW; +STRUCT!{struct NMTVGETINFOTIPA { + hdr: ::NMHDR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + hItem: HTREEITEM, + lParam: ::LPARAM, +}} +pub type LPNMTVGETINFOTIPA = *mut NMTVGETINFOTIPA; +STRUCT!{struct NMTVGETINFOTIPW { + hdr: ::NMHDR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + hItem: HTREEITEM, + lParam: ::LPARAM, +}} +pub type LPNMTVGETINFOTIPW = *mut NMTVGETINFOTIPW; +pub const TVCDRF_NOIMAGES: ::LRESULT = 0x00010000; +STRUCT!{struct NMTVITEMCHANGE { + hdr: ::NMHDR, + uChanged: ::UINT, + hItem: HTREEITEM, + uStateNew: ::UINT, + uStateOld: ::UINT, + lParam: ::LPARAM, +}} +STRUCT!{struct NMTVASYNCDRAW { + hdr: ::NMHDR, + pimldp: *mut IMAGELISTDRAWPARAMS, + hr: ::HRESULT, + hItem: HTREEITEM, + lParam: ::LPARAM, + dwRetFlags: ::DWORD, + iRetImageIndex: ::c_int, +}} +pub const CBEIF_TEXT: ::UINT = 0x00000001; +pub const CBEIF_IMAGE: ::UINT = 0x00000002; +pub const CBEIF_SELECTEDIMAGE: ::UINT = 0x00000004; +pub const CBEIF_OVERLAY: ::UINT = 0x00000008; +pub const CBEIF_INDENT: ::UINT = 0x00000010; +pub const CBEIF_LPARAM: ::UINT = 0x00000020; +pub const CBEIF_DI_SETITEM: ::UINT = 0x10000000; +STRUCT!{struct COMBOBOXEXITEMA { + mask: ::UINT, + iItem: ::INT_PTR, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + iOverlay: ::c_int, + iIndent: ::c_int, + lParam: ::LPARAM, +}} +pub type PCOMBOBOXEXITEMA = *mut COMBOBOXEXITEMA; +pub type PCCOMBOBOXEXITEMA = *const COMBOBOXEXITEMA; +STRUCT!{struct COMBOBOXEXITEMW { + mask: ::UINT, + iItem: ::INT_PTR, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + iSelectedImage: ::c_int, + iOverlay: ::c_int, + iIndent: ::c_int, + lParam: ::LPARAM, +}} +pub type PCOMBOBOXEXITEMW = *mut COMBOBOXEXITEMW; +pub type PCCOMBOBOXEXITEMW = *const COMBOBOXEXITEMW; +pub const CBEM_INSERTITEMA: ::UINT = ::WM_USER + 1; +pub const CBEM_SETIMAGELIST: ::UINT = ::WM_USER + 2; +pub const CBEM_GETIMAGELIST: ::UINT = ::WM_USER + 3; +pub const CBEM_GETITEMA: ::UINT = ::WM_USER + 4; +pub const CBEM_SETITEMA: ::UINT = ::WM_USER + 5; +pub const CBEM_DELETEITEM: ::UINT = ::CB_DELETESTRING; +pub const CBEM_GETCOMBOCONTROL: ::UINT = ::WM_USER + 6; +pub const CBEM_GETEDITCONTROL: ::UINT = ::WM_USER + 7; +pub const CBEM_SETEXSTYLE: ::UINT = ::WM_USER + 8; +pub const CBEM_SETEXTENDEDSTYLE: ::UINT = ::WM_USER + 14; +pub const CBEM_GETEXSTYLE: ::UINT = ::WM_USER + 9; +pub const CBEM_GETEXTENDEDSTYLE: ::UINT = ::WM_USER + 9; +pub const CBEM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const CBEM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const CBEM_HASEDITCHANGED: ::UINT = ::WM_USER + 10; +pub const CBEM_INSERTITEMW: ::UINT = ::WM_USER + 11; +pub const CBEM_SETITEMW: ::UINT = ::WM_USER + 12; +pub const CBEM_GETITEMW: ::UINT = ::WM_USER + 13; +pub const CBEM_SETWINDOWTHEME: ::UINT = CCM_SETWINDOWTHEME; +pub const CBES_EX_NOEDITIMAGE: ::DWORD = 0x00000001; +pub const CBES_EX_NOEDITIMAGEINDENT: ::DWORD = 0x00000002; +pub const CBES_EX_PATHWORDBREAKPROC: ::DWORD = 0x00000004; +pub const CBES_EX_NOSIZELIMIT: ::DWORD = 0x00000008; +pub const CBES_EX_CASESENSITIVE: ::DWORD = 0x00000010; +pub const CBES_EX_TEXTENDELLIPSIS: ::DWORD = 0x00000020; +STRUCT!{struct NMCOMBOBOXEXA { + hdr: ::NMHDR, + ceItem: COMBOBOXEXITEMA, +}} +pub type PNMCOMBOBOXEXA = *mut NMCOMBOBOXEXA; +STRUCT!{struct NMCOMBOBOXEXW { + hdr: ::NMHDR, + ceItem: COMBOBOXEXITEMW, +}} +pub type PNMCOMBOBOXEXW = *mut NMCOMBOBOXEXW; +pub const CBEN_GETDISPINFOA: ::UINT = CBEN_FIRST - 0; +pub const CBEN_INSERTITEM: ::UINT = CBEN_FIRST - 1; +pub const CBEN_DELETEITEM: ::UINT = CBEN_FIRST - 2; +pub const CBEN_BEGINEDIT: ::UINT = CBEN_FIRST - 4; +pub const CBEN_ENDEDITA: ::UINT = CBEN_FIRST - 5; +pub const CBEN_ENDEDITW: ::UINT = CBEN_FIRST - 6; +pub const CBEN_GETDISPINFOW: ::UINT = CBEN_FIRST - 7; +pub const CBEN_DRAGBEGINA: ::UINT = CBEN_FIRST - 8; +pub const CBEN_DRAGBEGINW: ::UINT = CBEN_FIRST - 9; +pub const CBENF_KILLFOCUS: ::c_int = 1; +pub const CBENF_RETURN: ::c_int = 2; +pub const CBENF_ESCAPE: ::c_int = 3; +pub const CBENF_DROPDOWN: ::c_int = 4; +pub const CBEMAXSTRLEN: usize = 260; +STRUCT!{nodebug struct NMCBEDRAGBEGINW { + hdr: ::NMHDR, + iItemid: ::c_int, + szText: [::WCHAR; CBEMAXSTRLEN], +}} +pub type PNMCBEDRAGBEGINW = *mut NMCBEDRAGBEGINW; +pub type LPNMCBEDRAGBEGINW = *mut NMCBEDRAGBEGINW; +STRUCT!{nodebug struct NMCBEDRAGBEGINA { + hdr: ::NMHDR, + iItemid: ::c_int, + szText: [::c_char; CBEMAXSTRLEN], +}} +pub type PNMCBEDRAGBEGINA = *mut NMCBEDRAGBEGINA; +pub type LPNMCBEDRAGBEGINA = *mut NMCBEDRAGBEGINA; +STRUCT!{nodebug struct NMCBEENDEDITW { + hdr: ::NMHDR, + fChanged: ::BOOL, + iNewSelection: ::c_int, + szText: [::WCHAR; CBEMAXSTRLEN], + iWhy: ::c_int, +}} +pub type PNMCBEENDEDITW = *mut NMCBEENDEDITW; +pub type LPNMCBEENDEDITW = *mut NMCBEENDEDITW; +STRUCT!{nodebug struct NMCBEENDEDITA { + hdr: ::NMHDR, + fChanged: ::BOOL, + iNewSelection: ::c_int, + szText: [::c_char; CBEMAXSTRLEN], + iWhy: ::c_int, +}} +pub type PNMCBEENDEDITA = *mut NMCBEENDEDITA; +pub type LPNMCBEENDEDITA = *mut NMCBEENDEDITA; +pub const TCS_SCROLLOPPOSITE: ::DWORD = 0x0001; +pub const TCS_BOTTOM: ::DWORD = 0x0002; +pub const TCS_RIGHT: ::DWORD = 0x0002; +pub const TCS_MULTISELECT: ::DWORD = 0x0004; +pub const TCS_FLATBUTTONS: ::DWORD = 0x0008; +pub const TCS_FORCEICONLEFT: ::DWORD = 0x0010; +pub const TCS_FORCELABELLEFT: ::DWORD = 0x0020; +pub const TCS_HOTTRACK: ::DWORD = 0x0040; +pub const TCS_VERTICAL: ::DWORD = 0x0080; +pub const TCS_TABS: ::DWORD = 0x0000; +pub const TCS_BUTTONS: ::DWORD = 0x0100; +pub const TCS_SINGLELINE: ::DWORD = 0x0000; +pub const TCS_MULTILINE: ::DWORD = 0x0200; +pub const TCS_RIGHTJUSTIFY: ::DWORD = 0x0000; +pub const TCS_FIXEDWIDTH: ::DWORD = 0x0400; +pub const TCS_RAGGEDRIGHT: ::DWORD = 0x0800; +pub const TCS_FOCUSONBUTTONDOWN: ::DWORD = 0x1000; +pub const TCS_OWNERDRAWFIXED: ::DWORD = 0x2000; +pub const TCS_TOOLTIPS: ::DWORD = 0x4000; +pub const TCS_FOCUSNEVER: ::DWORD = 0x8000; +pub const TCS_EX_FLATSEPARATORS: ::DWORD = 0x00000001; +pub const TCS_EX_REGISTERDROP: ::DWORD = 0x00000002; +pub const TCM_GETIMAGELIST: ::UINT = TCM_FIRST + 2; +pub const TCM_SETIMAGELIST: ::UINT = TCM_FIRST + 3; +pub const TCM_GETITEMCOUNT: ::UINT = TCM_FIRST + 4; +pub const TCIF_TEXT: ::UINT = 0x0001; +pub const TCIF_IMAGE: ::UINT = 0x0002; +pub const TCIF_RTLREADING: ::UINT = 0x0004; +pub const TCIF_PARAM: ::UINT = 0x0008; +pub const TCIF_STATE: ::UINT = 0x0010; +pub const TCIS_BUTTONPRESSED: ::DWORD = 0x0001; +pub const TCIS_HIGHLIGHTED: ::DWORD = 0x0002; +pub type TC_ITEMHEADERA = TCITEMHEADERA; +pub type TC_ITEMHEADERW = TCITEMHEADERW; +STRUCT!{struct TCITEMHEADERA { + mask: ::UINT, + lpReserved1: ::UINT, + lpReserved2: ::UINT, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, +}} +pub type LPTCITEMHEADERA = *mut TCITEMHEADERA; +STRUCT!{struct TCITEMHEADERW { + mask: ::UINT, + lpReserved1: ::UINT, + lpReserved2: ::UINT, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, +}} +pub type LPTCITEMHEADERW = *mut TCITEMHEADERW; +pub type TC_ITEMA = TCITEMA; +pub type TC_ITEMW = TCITEMW; +STRUCT!{struct TCITEMA { + mask: ::UINT, + dwState: ::DWORD, + dwStateMask: ::DWORD, + pszText: ::LPSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTCITEMA = *mut TCITEMA; +STRUCT!{struct TCITEMW { + mask: ::UINT, + dwState: ::DWORD, + dwStateMask: ::DWORD, + pszText: ::LPWSTR, + cchTextMax: ::c_int, + iImage: ::c_int, + lParam: ::LPARAM, +}} +pub type LPTCITEMW = *mut TCITEMW; +pub const TCM_GETITEMA: ::UINT = TCM_FIRST + 5; +pub const TCM_GETITEMW: ::UINT = TCM_FIRST + 60; +pub const TCM_SETITEMA: ::UINT = TCM_FIRST + 6; +pub const TCM_SETITEMW: ::UINT = TCM_FIRST + 61; +pub const TCM_INSERTITEMA: ::UINT = TCM_FIRST + 7; +pub const TCM_INSERTITEMW: ::UINT = TCM_FIRST + 62; +pub const TCM_DELETEITEM: ::UINT = TCM_FIRST + 8; +pub const TCM_DELETEALLITEMS: ::UINT = TCM_FIRST + 9; +pub const TCM_GETITEMRECT: ::UINT = TCM_FIRST + 10; +pub const TCM_GETCURSEL: ::UINT = TCM_FIRST + 11; +pub const TCM_SETCURSEL: ::UINT = TCM_FIRST + 12; +pub const TCHT_NOWHERE: ::UINT = 0x0001; +pub const TCHT_ONITEMICON: ::UINT = 0x0002; +pub const TCHT_ONITEMLABEL: ::UINT = 0x0004; +pub const TCHT_ONITEM: ::UINT = TCHT_ONITEMICON | TCHT_ONITEMLABEL; +pub type LPTC_HITTESTINFO = LPTCHITTESTINFO; +pub type TC_HITTESTINFO = TCHITTESTINFO; +STRUCT!{struct TCHITTESTINFO { + pt: ::POINT, + flags: ::UINT, +}} +pub type LPTCHITTESTINFO = *mut TCHITTESTINFO; +pub const TCM_HITTEST: ::UINT = TCM_FIRST + 13; +pub const TCM_SETITEMEXTRA: ::UINT = TCM_FIRST + 14; +pub const TCM_ADJUSTRECT: ::UINT = TCM_FIRST + 40; +pub const TCM_SETITEMSIZE: ::UINT = TCM_FIRST + 41; +pub const TCM_REMOVEIMAGE: ::UINT = TCM_FIRST + 42; +pub const TCM_SETPADDING: ::UINT = TCM_FIRST + 43; +pub const TCM_GETROWCOUNT: ::UINT = TCM_FIRST + 44; +pub const TCM_GETTOOLTIPS: ::UINT = TCM_FIRST + 45; +pub const TCM_SETTOOLTIPS: ::UINT = TCM_FIRST + 46; +pub const TCM_GETCURFOCUS: ::UINT = TCM_FIRST + 47; +pub const TCM_SETCURFOCUS: ::UINT = TCM_FIRST + 48; +pub const TCM_SETMINTABWIDTH: ::UINT = TCM_FIRST + 49; +pub const TCM_DESELECTALL: ::UINT = TCM_FIRST + 50; +pub const TCM_HIGHLIGHTITEM: ::UINT = TCM_FIRST + 51; +pub const TCM_SETEXTENDEDSTYLE: ::UINT = TCM_FIRST + 52; +pub const TCM_GETEXTENDEDSTYLE: ::UINT = TCM_FIRST + 53; +pub const TCM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const TCM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const TCN_KEYDOWN: ::UINT = TCN_FIRST - 0; +pub type TC_KEYDOWN = NMTCKEYDOWN; +STRUCT!{struct NMTCKEYDOWN { + hdr: ::NMHDR, + wVKey: ::WORD, + flags: ::UINT, +}} +pub const TCN_SELCHANGE: ::UINT = TCN_FIRST - 1; +pub const TCN_SELCHANGING: ::UINT = TCN_FIRST - 2; +pub const TCN_GETOBJECT: ::UINT = TCN_FIRST - 3; +pub const TCN_FOCUSCHANGE: ::UINT = TCN_FIRST - 4; +pub const ACS_CENTER: ::DWORD = 0x0001; +pub const ACS_TRANSPARENT: ::DWORD = 0x0002; +pub const ACS_AUTOPLAY: ::DWORD = 0x0004; +pub const ACS_TIMER: ::DWORD = 0x0008; +pub const ACM_OPENA: ::UINT = ::WM_USER + 100; +pub const ACM_OPENW: ::UINT = ::WM_USER + 103; +pub const ACM_PLAY: ::UINT = ::WM_USER + 101; +pub const ACM_STOP: ::UINT = ::WM_USER + 102; +pub const ACM_ISPLAYING: ::UINT = ::WM_USER + 104; +pub const ACN_START: ::WPARAM = 1; +pub const ACN_STOP: ::WPARAM = 2; +pub type MONTHDAYSTATE = ::DWORD; +pub type LPMONTHDAYSTATE = *mut ::DWORD; +pub const MCM_FIRST: ::UINT = 0x1000; +pub const MCM_GETCURSEL: ::UINT = MCM_FIRST + 1; +pub const MCM_SETCURSEL: ::UINT = MCM_FIRST + 2; +pub const MCM_GETMAXSELCOUNT: ::UINT = MCM_FIRST + 3; +pub const MCM_SETMAXSELCOUNT: ::UINT = MCM_FIRST + 4; +pub const MCM_GETSELRANGE: ::UINT = MCM_FIRST + 5; +pub const MCM_SETSELRANGE: ::UINT = MCM_FIRST + 6; +pub const MCM_GETMONTHRANGE: ::UINT = MCM_FIRST + 7; +pub const MCM_SETDAYSTATE: ::UINT = MCM_FIRST + 8; +pub const MCM_GETMINREQRECT: ::UINT = MCM_FIRST + 9; +pub const MCM_SETCOLOR: ::UINT = MCM_FIRST + 10; +pub const MCM_GETCOLOR: ::UINT = MCM_FIRST + 11; +pub const MCM_SETTODAY: ::UINT = MCM_FIRST + 12; +pub const MCM_GETTODAY: ::UINT = MCM_FIRST + 13; +pub const MCM_HITTEST: ::UINT = MCM_FIRST + 14; +pub const MCSC_BACKGROUND: ::WPARAM = 0; +pub const MCSC_TEXT: ::WPARAM = 1; +pub const MCSC_TITLEBK: ::WPARAM = 2; +pub const MCSC_TITLETEXT: ::WPARAM = 3; +pub const MCSC_MONTHBK: ::WPARAM = 4; +pub const MCSC_TRAILINGTEXT: ::WPARAM = 5; +STRUCT!{struct MCHITTESTINFO { + cbSize: ::UINT, + pt: ::POINT, + uHit: ::UINT, + st: ::SYSTEMTIME, + rc: ::RECT, + iOffset: ::c_int, + iRow: ::c_int, + iCol: ::c_int, +}} +pub type PMCHITTESTINFO = *mut MCHITTESTINFO; +pub const MCHT_TITLE: ::UINT = 0x00010000; +pub const MCHT_CALENDAR: ::UINT = 0x00020000; +pub const MCHT_TODAYLINK: ::UINT = 0x00030000; +pub const MCHT_CALENDARCONTROL: ::UINT = 0x00100000; +pub const MCHT_NEXT: ::UINT = 0x01000000; +pub const MCHT_PREV: ::UINT = 0x02000000; +pub const MCHT_NOWHERE: ::UINT = 0x00000000; +pub const MCHT_TITLEBK: ::UINT = MCHT_TITLE; +pub const MCHT_TITLEMONTH: ::UINT = MCHT_TITLE | 0x0001; +pub const MCHT_TITLEYEAR: ::UINT = MCHT_TITLE | 0x0002; +pub const MCHT_TITLEBTNNEXT: ::UINT = MCHT_TITLE | MCHT_NEXT | 0x0003; +pub const MCHT_TITLEBTNPREV: ::UINT = MCHT_TITLE | MCHT_PREV | 0x0003; +pub const MCHT_CALENDARBK: ::UINT = MCHT_CALENDAR; +pub const MCHT_CALENDARDATE: ::UINT = MCHT_CALENDAR | 0x0001; +pub const MCHT_CALENDARDATENEXT: ::UINT = MCHT_CALENDARDATE | MCHT_NEXT; +pub const MCHT_CALENDARDATEPREV: ::UINT = MCHT_CALENDARDATE | MCHT_PREV; +pub const MCHT_CALENDARDAY: ::UINT = MCHT_CALENDAR | 0x0002; +pub const MCHT_CALENDARWEEKNUM: ::UINT = MCHT_CALENDAR | 0x0003; +pub const MCHT_CALENDARDATEMIN: ::UINT = MCHT_CALENDAR | 0x0004; +pub const MCHT_CALENDARDATEMAX: ::UINT = MCHT_CALENDAR | 0x0005; +pub const MCM_SETFIRSTDAYOFWEEK: ::UINT = MCM_FIRST + 15; +pub const MCM_GETFIRSTDAYOFWEEK: ::UINT = MCM_FIRST + 16; +pub const MCM_GETRANGE: ::UINT = MCM_FIRST + 17; +pub const MCM_SETRANGE: ::UINT = MCM_FIRST + 18; +pub const MCM_GETMONTHDELTA: ::UINT = MCM_FIRST + 19; +pub const MCM_SETMONTHDELTA: ::UINT = MCM_FIRST + 20; +pub const MCM_GETMAXTODAYWIDTH: ::UINT = MCM_FIRST + 21; +pub const MCM_SETUNICODEFORMAT: ::UINT = CCM_SETUNICODEFORMAT; +pub const MCM_GETUNICODEFORMAT: ::UINT = CCM_GETUNICODEFORMAT; +pub const MCM_GETCURRENTVIEW: ::UINT = MCM_FIRST + 22; +pub const MCM_GETCALENDARCOUNT: ::UINT = MCM_FIRST + 23; +pub const MCMV_MONTH: ::DWORD = 0; +pub const MCMV_YEAR: ::DWORD = 1; +pub const MCMV_DECADE: ::DWORD = 2; +pub const MCMV_CENTURY: ::DWORD = 3; +pub const MCMV_MAX: ::DWORD = MCMV_CENTURY; +pub const MCGIP_CALENDARCONTROL: ::DWORD = 0; +pub const MCGIP_NEXT: ::DWORD = 1; +pub const MCGIP_PREV: ::DWORD = 2; +pub const MCGIP_FOOTER: ::DWORD = 3; +pub const MCGIP_CALENDAR: ::DWORD = 4; +pub const MCGIP_CALENDARHEADER: ::DWORD = 5; +pub const MCGIP_CALENDARBODY: ::DWORD = 6; +pub const MCGIP_CALENDARROW: ::DWORD = 7; +pub const MCGIP_CALENDARCELL: ::DWORD = 8; +pub const MCGIF_DATE: ::DWORD = 0x00000001; +pub const MCGIF_RECT: ::DWORD = 0x00000002; +pub const MCGIF_NAME: ::DWORD = 0x00000004; +STRUCT!{struct MCGRIDINFO { + cbSize: ::UINT, + dwPart: ::DWORD, + dwFlags: ::DWORD, + iCalendar: ::c_int, + iRow: ::c_int, + iCol: ::c_int, + bSelected: ::BOOL, + stStart: ::SYSTEMTIME, + stEnd: ::SYSTEMTIME, + rc: ::RECT, + pszName: ::PWSTR, + cchName: ::size_t, +}} +pub type PMCGRIDINFO = *mut MCGRIDINFO; +pub const MCM_GETCALENDARGRIDINFO: ::UINT = MCM_FIRST + 24; +pub const MCM_GETCALID: ::UINT = MCM_FIRST + 27; +pub const MCM_SETCALID: ::UINT = MCM_FIRST + 28; +pub const MCM_SIZERECTTOMIN: ::UINT = MCM_FIRST + 29; +pub const MCM_SETCALENDARBORDER: ::UINT = MCM_FIRST + 30; +pub const MCM_GETCALENDARBORDER: ::UINT = MCM_FIRST + 31; +pub const MCM_SETCURRENTVIEW: ::UINT = MCM_FIRST + 32; +STRUCT!{struct NMSELCHANGE { + nmhdr: ::NMHDR, + stSelStart: ::SYSTEMTIME, + stSelEnd: ::SYSTEMTIME, +}} +pub type LPNMSELCHANGE = *mut NMSELCHANGE; +pub const MCN_SELCHANGE: ::UINT = MCN_FIRST - 3; +STRUCT!{struct NMDAYSTATE { + nmhdr: ::NMHDR, + stStart: ::SYSTEMTIME, + cDayState: ::c_int, + prgDayState: LPMONTHDAYSTATE, +}} +pub type LPNMDAYSTATE = *mut NMDAYSTATE; +pub const MCN_GETDAYSTATE: ::UINT = MCN_FIRST - 1; +pub type NMSELECT = NMSELCHANGE; +pub type LPNMSELECT = *mut NMSELCHANGE; +pub const MCN_SELECT: ::UINT = MCN_FIRST; +STRUCT!{struct NMVIEWCHANGE { + nmhdr: ::NMHDR, + dwOldView: ::DWORD, + dwNewView: ::DWORD, +}} +pub type LPNMVIEWCHANGE = *mut NMVIEWCHANGE; +pub const MCN_VIEWCHANGE: ::UINT = MCN_FIRST - 4; +pub const MCS_DAYSTATE: ::DWORD = 0x0001; +pub const MCS_MULTISELECT: ::DWORD = 0x0002; +pub const MCS_WEEKNUMBERS: ::DWORD = 0x0004; +pub const MCS_NOTODAYCIRCLE: ::DWORD = 0x0008; +pub const MCS_NOTODAY: ::DWORD = 0x0010; +pub const MCS_NOTRAILINGDATES: ::DWORD = 0x0040; +pub const MCS_SHORTDAYSOFWEEK: ::DWORD = 0x0080; +pub const MCS_NOSELCHANGEONNAV: ::DWORD = 0x0100; +pub const GMR_VISIBLE: ::DWORD = 0; +pub const GMR_DAYSTATE: ::DWORD = 1; +STRUCT!{struct DATETIMEPICKERINFO { + cbSize: ::UINT, + rcCheck: ::RECT, + stateCheck: ::DWORD, + rcButton: ::RECT, + stateButton: ::DWORD, + hwndEdit: ::HWND, + hwndUD: ::HWND, + hwndDropDown: ::HWND, +}} +pub type LPDATETIMEPICKERINFO = *mut DATETIMEPICKERINFO; +pub const DTM_FIRST: ::UINT = 0x1000; +pub const DTM_GETSYSTEMTIME: ::UINT = DTM_FIRST + 1; +pub const DTM_SETSYSTEMTIME: ::UINT = DTM_FIRST + 2; +pub const DTM_GETRANGE: ::UINT = DTM_FIRST + 3; +pub const DTM_SETRANGE: ::UINT = DTM_FIRST + 4; +pub const DTM_SETFORMATA: ::UINT = DTM_FIRST + 5; +pub const DTM_SETFORMATW: ::UINT = DTM_FIRST + 50; +pub const DTM_SETMCCOLOR: ::UINT = DTM_FIRST + 6; +pub const DTM_GETMCCOLOR: ::UINT = DTM_FIRST + 7; +pub const DTM_GETMONTHCAL: ::UINT = DTM_FIRST + 8; +pub const DTM_SETMCFONT: ::UINT = DTM_FIRST + 9; +pub const DTM_GETMCFONT: ::UINT = DTM_FIRST + 10; +pub const DTM_SETMCSTYLE: ::UINT = DTM_FIRST + 11; +pub const DTM_GETMCSTYLE: ::UINT = DTM_FIRST + 12; +pub const DTM_CLOSEMONTHCAL: ::UINT = DTM_FIRST + 13; +pub const DTM_GETDATETIMEPICKERINFO: ::UINT = DTM_FIRST + 14; +pub const DTM_GETIDEALSIZE: ::UINT = DTM_FIRST + 15; +pub const DTS_UPDOWN: ::DWORD = 0x0001; +pub const DTS_SHOWNONE: ::DWORD = 0x0002; +pub const DTS_SHORTDATEFORMAT: ::DWORD = 0x0000; +pub const DTS_LONGDATEFORMAT: ::DWORD = 0x0004; +pub const DTS_SHORTDATECENTURYFORMAT: ::DWORD = 0x000C; +pub const DTS_TIMEFORMAT: ::DWORD = 0x0009; +pub const DTS_APPCANPARSE: ::DWORD = 0x0010; +pub const DTS_RIGHTALIGN: ::DWORD = 0x0020; +pub const DTN_DATETIMECHANGE: ::UINT = DTN_FIRST2 - 6; +STRUCT!{struct NMDATETIMECHANGE { + nmhdr: ::NMHDR, + dwFlags: ::DWORD, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMECHANGE = *mut NMDATETIMECHANGE; +pub const DTN_USERSTRINGA: ::UINT = DTN_FIRST2 - 5; +pub const DTN_USERSTRINGW: ::UINT = DTN_FIRST - 5; +STRUCT!{struct NMDATETIMESTRINGA { + nmhdr: ::NMHDR, + pszUserString: ::LPCSTR, + st: ::SYSTEMTIME, + dwFlags: ::DWORD, +}} +pub type LPNMDATETIMESTRINGA = *mut NMDATETIMESTRINGA; +STRUCT!{struct NMDATETIMESTRINGW { + nmhdr: ::NMHDR, + pszUserString: ::LPCWSTR, + st: ::SYSTEMTIME, + dwFlags: ::DWORD, +}} +pub type LPNMDATETIMESTRINGW = *mut NMDATETIMESTRINGW; +pub const DTN_WMKEYDOWNA: ::UINT = DTN_FIRST2 - 4; +pub const DTN_WMKEYDOWNW: ::UINT = DTN_FIRST - 4; +STRUCT!{struct NMDATETIMEWMKEYDOWNA { + nmhdr: ::NMHDR, + nVirtKey: ::c_int, + pszFormat: ::LPCSTR, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMEWMKEYDOWNA = *mut NMDATETIMEWMKEYDOWNA; +STRUCT!{struct NMDATETIMEWMKEYDOWNW { + nmhdr: ::NMHDR, + nVirtKey: ::c_int, + pszFormat: ::LPCWSTR, + st: ::SYSTEMTIME, +}} +pub type LPNMDATETIMEWMKEYDOWNW = *mut NMDATETIMEWMKEYDOWNW; +pub const DTN_FORMATA: ::UINT = DTN_FIRST2 - 3; +pub const DTN_FORMATW: ::UINT = DTN_FIRST - 3; +STRUCT!{nodebug struct NMDATETIMEFORMATA { + nmhdr: ::NMHDR, + pszFormat: ::LPCSTR, + st: ::SYSTEMTIME, + pszDisplay: ::LPCSTR, + szDisplay: [::CHAR; 64], +}} +pub type LPNMDATETIMEFORMATA = *mut NMDATETIMEFORMATA; +STRUCT!{nodebug struct NMDATETIMEFORMATW { + nmhdr: ::NMHDR, + pszFormat: ::LPCWSTR, + st: ::SYSTEMTIME, + pszDisplay: ::LPCWSTR, + szDisplay: [::WCHAR; 64], +}} +pub type LPNMDATETIMEFORMATW = *mut NMDATETIMEFORMATW; +pub const DTN_FORMATQUERYA: ::UINT = DTN_FIRST2 - 2; +pub const DTN_FORMATQUERYW: ::UINT = DTN_FIRST - 2; +STRUCT!{struct NMDATETIMEFORMATQUERYA { + nmhdr: ::NMHDR, + pszFormat: ::LPCSTR, + szMax: ::SIZE, +}} +pub type LPNMDATETIMEFORMATQUERYA = *mut NMDATETIMEFORMATQUERYA; +STRUCT!{struct NMDATETIMEFORMATQUERYW { + nmhdr: ::NMHDR, + pszFormat: ::LPCWSTR, + szMax: ::SIZE, +}} +pub type LPNMDATETIMEFORMATQUERYW = *mut NMDATETIMEFORMATQUERYW; +pub const DTN_DROPDOWN: ::UINT = DTN_FIRST2 - 1; +pub const DTN_CLOSEUP: ::UINT = DTN_FIRST2; +pub const GDTR_MIN: ::WPARAM = 0x0001; +pub const GDTR_MAX: ::WPARAM = 0x0002; +pub const GDT_ERROR: ::LRESULT = -1; +pub const GDT_VALID: ::LRESULT = 0; +pub const GDT_NONE: ::LRESULT = 1; +pub const IPM_CLEARADDRESS: ::UINT = ::WM_USER + 100; +pub const IPM_SETADDRESS: ::UINT = ::WM_USER + 101; +pub const IPM_GETADDRESS: ::UINT = ::WM_USER + 102; +pub const IPM_SETRANGE: ::UINT = ::WM_USER + 103; +pub const IPM_SETFOCUS: ::UINT = ::WM_USER + 104; +pub const IPM_ISBLANK: ::UINT = ::WM_USER + 105; +pub const IPN_FIELDCHANGED: ::UINT = IPN_FIRST - 0; +STRUCT!{struct NMIPADDRESS { + hdr: ::NMHDR, + iField: ::c_int, + iValue: ::c_int, +}} +pub type LPNMIPADDRESS = *mut NMIPADDRESS; +#[inline] #[allow(dead_code)] +pub fn MAKEIPRANGE(low: ::BYTE, high: ::BYTE) -> ::LPARAM { + (high << 8 + low) as ::LPARAM +} +#[inline] #[allow(dead_code)] +pub fn MAKEIPADDRESS(b1: ::DWORD, b2: ::DWORD, b3: ::DWORD, b4: ::DWORD) -> ::LPARAM { + ((b1 << 24) + (b2 << 16) + (b3 << 8) + b4) as ::LPARAM +} +pub const PGS_VERT: ::DWORD = 0x00000000; +pub const PGS_HORZ: ::DWORD = 0x00000001; +pub const PGS_AUTOSCROLL: ::DWORD = 0x00000002; +pub const PGS_DRAGNDROP: ::DWORD = 0x00000004; +pub const PGF_INVISIBLE: ::DWORD = 0; +pub const PGF_NORMAL: ::DWORD = 1; +pub const PGF_GRAYED: ::DWORD = 2; +pub const PGF_DEPRESSED: ::DWORD = 4; +pub const PGF_HOT: ::DWORD = 8; +pub const PGB_TOPORLEFT: ::c_int = 0; +pub const PGB_BOTTOMORRIGHT: ::c_int = 1; +pub const PGM_SETCHILD: ::UINT = PGM_FIRST + 1; +pub const PGM_RECALCSIZE: ::UINT = PGM_FIRST + 2; +pub const PGM_FORWARDMOUSE: ::UINT = PGM_FIRST + 3; +pub const PGM_SETBKCOLOR: ::UINT = PGM_FIRST + 4; +pub const PGM_GETBKCOLOR: ::UINT = PGM_FIRST + 5; +pub const PGM_SETBORDER: ::UINT = PGM_FIRST + 6; +pub const PGM_GETBORDER: ::UINT = PGM_FIRST + 7; +pub const PGM_SETPOS: ::UINT = PGM_FIRST + 8; +pub const PGM_GETPOS: ::UINT = PGM_FIRST + 9; +pub const PGM_SETBUTTONSIZE: ::UINT = PGM_FIRST + 10; +pub const PGM_GETBUTTONSIZE: ::UINT = PGM_FIRST + 11; +pub const PGM_GETBUTTONSTATE: ::UINT = PGM_FIRST + 12; +pub const PGM_GETDROPTARGET: ::UINT = CCM_GETDROPTARGET; +pub const PGM_SETSCROLLINFO: ::UINT = PGM_FIRST + 13; +pub const PGN_SCROLL: ::UINT = PGN_FIRST - 1; +pub const PGF_SCROLLUP: ::c_int = 1; +pub const PGF_SCROLLDOWN: ::c_int = 2; +pub const PGF_SCROLLLEFT: ::c_int = 4; +pub const PGF_SCROLLRIGHT: ::c_int = 8; +pub const PGK_SHIFT: ::BOOL = 1; +pub const PGK_CONTROL: ::BOOL = 2; +pub const PGK_MENU: ::BOOL = 4; +STRUCT!{struct NMPGSCROLL { + hdr: ::NMHDR, + fwKeys: ::BOOL, + rcParent: ::RECT, + iDir: ::c_int, + iXpos: ::c_int, + iYpos: ::c_int, + iScroll: ::c_int, +}} +pub type LPNMPGSCROLL = *mut NMPGSCROLL; +pub const PGN_CALCSIZE: ::UINT = PGN_FIRST - 2; +pub const PGF_CALCWIDTH: ::DWORD = 1; +pub const PGF_CALCHEIGHT: ::DWORD = 2; +STRUCT!{struct NMPGCALCSIZE { + hdr: ::NMHDR, + dwFlag: ::DWORD, + iWidth: ::c_int, + iHeight: ::c_int, +}} +pub type LPNMPGCALCSIZE = *mut NMPGCALCSIZE; +pub const PGN_HOTITEMCHANGE: ::UINT = PGN_FIRST - 3; +STRUCT!{struct NMPGHOTITEM { + hdr: ::NMHDR, + idOld: ::c_int, + idNew: ::c_int, + dwFlags: ::DWORD, +}} +pub type LPNMPGHOTITEM = *mut NMPGHOTITEM; +pub const NFS_EDIT: ::DWORD = 0x0001; +pub const NFS_STATIC: ::DWORD = 0x0002; +pub const NFS_LISTCOMBO: ::DWORD = 0x0004; +pub const NFS_BUTTON: ::DWORD = 0x0008; +pub const NFS_ALL: ::DWORD = 0x0010; +pub const NFS_USEFONTASSOC: ::DWORD = 0x0020; +pub const BUTTON_IMAGELIST_ALIGN_LEFT: ::UINT = 0; +pub const BUTTON_IMAGELIST_ALIGN_RIGHT: ::UINT = 1; +pub const BUTTON_IMAGELIST_ALIGN_TOP: ::UINT = 2; +pub const BUTTON_IMAGELIST_ALIGN_BOTTOM: ::UINT = 3; +pub const BUTTON_IMAGELIST_ALIGN_CENTER: ::UINT = 4; +STRUCT!{struct BUTTON_IMAGELIST { + himl: HIMAGELIST, + margin: ::RECT, + uAlign: ::UINT, +}} +pub type PBUTTON_IMAGELIST = *mut BUTTON_IMAGELIST; +pub const BCM_GETIDEALSIZE: ::UINT = BCM_FIRST + 0x0001; +pub const BCM_SETIMAGELIST: ::UINT = BCM_FIRST + 0x0002; +pub const BCM_GETIMAGELIST: ::UINT = BCM_FIRST + 0x0003; +pub const BCM_SETTEXTMARGIN: ::UINT = BCM_FIRST + 0x0004; +pub const BCM_GETTEXTMARGIN: ::UINT = BCM_FIRST + 0x0005; +STRUCT!{struct NMBCHOTITEM { + hdr: ::NMHDR, + dwFlags: ::DWORD, +}} +pub type LPNMBCHOTITEM = *mut NMBCHOTITEM; +pub const BCN_HOTITEMCHANGE: ::UINT = BCN_FIRST + 0x0001; +pub const BS_SPLITBUTTON: ::UINT = 0x0000000C; +pub const BS_DEFSPLITBUTTON: ::UINT = 0x0000000D; +pub const BS_COMMANDLINK: ::UINT = 0x0000000E; +pub const BS_DEFCOMMANDLINK: ::UINT = 0x0000000F; +pub const BCSIF_GLYPH: ::UINT = 0x0001; +pub const BCSIF_IMAGE: ::UINT = 0x0002; +pub const BCSIF_STYLE: ::UINT = 0x0004; +pub const BCSIF_SIZE: ::UINT = 0x0008; +pub const BCSS_NOSPLIT: ::UINT = 0x0001; +pub const BCSS_STRETCH: ::UINT = 0x0002; +pub const BCSS_ALIGNLEFT: ::UINT = 0x0004; +pub const BCSS_IMAGE: ::UINT = 0x0008; +STRUCT!{struct BUTTON_SPLITINFO { + mask: ::UINT, + himlGlyph: HIMAGELIST, + uSplitStyle: ::UINT, + size: ::SIZE, +}} +pub type PBUTTON_SPLITINFO = *mut BUTTON_SPLITINFO; +pub const BCM_SETDROPDOWNSTATE: ::UINT = BCM_FIRST + 0x0006; +pub const BCM_SETSPLITINFO: ::UINT = BCM_FIRST + 0x0007; +pub const BCM_GETSPLITINFO: ::UINT = BCM_FIRST + 0x0008; +pub const BCM_SETNOTE: ::UINT = BCM_FIRST + 0x0009; +pub const BCM_GETNOTE: ::UINT = BCM_FIRST + 0x000A; +pub const BCM_GETNOTELENGTH: ::UINT = BCM_FIRST + 0x000B; +pub const BCM_SETSHIELD: ::UINT = BCM_FIRST + 0x000C; +pub const BCCL_NOGLYPH: HIMAGELIST = (0 - 1) as HIMAGELIST; +STRUCT!{struct NMBCDROPDOWN { + hdr: ::NMHDR, + rcButton: ::RECT, +}} +pub type LPNMBCDROPDOWN = *mut NMBCDROPDOWN; +pub const BCN_DROPDOWN: ::UINT = BCN_FIRST + 0x0002; +pub const EM_SETCUEBANNER: ::UINT = ECM_FIRST + 1; +pub const EM_GETCUEBANNER: ::UINT = ECM_FIRST + 2; +pub const EM_SHOWBALLOONTIP: ::UINT = ECM_FIRST + 3; +pub const EM_HIDEBALLOONTIP: ::UINT = ECM_FIRST + 4; +pub const EM_SETHILITE: ::UINT = ECM_FIRST + 5; +pub const EM_GETHILITE: ::UINT = ECM_FIRST + 6; +pub const EM_NOSETFOCUS: ::UINT = ECM_FIRST + 7; +pub const EM_TAKEFOCUS: ::UINT = ECM_FIRST + 8; +STRUCT!{struct EDITBALLOONTIP { + cbStruct: ::DWORD, + pszTitle: ::LPCWSTR, + pszText: ::LPCWSTR, + ttiIcon: ::INT, +}} +pub type PEDITBALLOONTIP = *mut EDITBALLOONTIP; +pub const CB_SETMINVISIBLE: ::UINT = CBM_FIRST + 1; +pub const CB_GETMINVISIBLE: ::UINT = CBM_FIRST + 2; +pub const CB_SETCUEBANNER: ::UINT = CBM_FIRST + 3; +pub const CB_GETCUEBANNER: ::UINT = CBM_FIRST + 4; +pub type PFTASKDIALOGCALLBACK = Option ::HRESULT>; +FLAGS!{enum TASKDIALOG_FLAGS { + TDF_ENABLE_HYPERLINKS = 0x0001, + TDF_USE_HICON_MAIN = 0x0002, + TDF_USE_HICON_FOOTER = 0x0004, + TDF_ALLOW_DIALOG_CANCELLATION = 0x0008, + TDF_USE_COMMAND_LINKS = 0x0010, + TDF_USE_COMMAND_LINKS_NO_ICON = 0x0020, + TDF_EXPAND_FOOTER_AREA = 0x0040, + TDF_EXPANDED_BY_DEFAULT = 0x0080, + TDF_VERIFICATION_FLAG_CHECKED = 0x0100, + TDF_SHOW_PROGRESS_BAR = 0x0200, + TDF_SHOW_MARQUEE_PROGRESS_BAR = 0x0400, + TDF_CALLBACK_TIMER = 0x0800, + TDF_POSITION_RELATIVE_TO_WINDOW = 0x1000, + TDF_RTL_LAYOUT = 0x2000, + TDF_NO_DEFAULT_RADIO_BUTTON = 0x4000, + TDF_CAN_BE_MINIMIZED = 0x8000, + TDF_NO_SET_FOREGROUND = 0x00010000, + TDF_SIZE_TO_CONTENT = 0x01000000, +}} +ENUM!{enum TASKDIALOG_MESSAGES { + TDM_NAVIGATE_PAGE = ::WM_USER + 101, + TDM_CLICK_BUTTON = ::WM_USER + 102, + TDM_SET_MARQUEE_PROGRESS_BAR = ::WM_USER + 103, + TDM_SET_PROGRESS_BAR_STATE = ::WM_USER + 104, + TDM_SET_PROGRESS_BAR_RANGE = ::WM_USER + 105, + TDM_SET_PROGRESS_BAR_POS = ::WM_USER + 106, + TDM_SET_PROGRESS_BAR_MARQUEE = ::WM_USER + 107, + TDM_SET_ELEMENT_TEXT = ::WM_USER + 108, + TDM_CLICK_RADIO_BUTTON = ::WM_USER + 110, + TDM_ENABLE_BUTTON = ::WM_USER + 111, + TDM_ENABLE_RADIO_BUTTON = ::WM_USER + 112, + TDM_CLICK_VERIFICATION = ::WM_USER + 113, + TDM_UPDATE_ELEMENT_TEXT = ::WM_USER + 114, + TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE = ::WM_USER + 115, + TDM_UPDATE_ICON = ::WM_USER + 116, +}} +ENUM!{enum TASKDIALOG_NOTIFICATIONS { + TDN_CREATED = 0, + TDN_NAVIGATED = 1, + TDN_BUTTON_CLICKED = 2, + TDN_HYPERLINK_CLICKED = 3, + TDN_TIMER = 4, + TDN_DESTROYED = 5, + TDN_RADIO_BUTTON_CLICKED = 6, + TDN_DIALOG_CONSTRUCTED = 7, + TDN_VERIFICATION_CLICKED = 8, + TDN_HELP = 9, + TDN_EXPANDO_BUTTON_CLICKED = 10, +}} +STRUCT!{struct TASKDIALOG_BUTTON { + nButtonID: ::c_int, + pszButtonText: ::PCWSTR, +}} +ENUM!{enum TASKDIALOG_ELEMENTS { + TDE_CONTENT, + TDE_EXPANDED_INFORMATION, + TDE_FOOTER, + TDE_MAIN_INSTRUCTION, +}} +ENUM!{enum TASKDIALOG_ICON_ELEMENTS { + TDIE_ICON_MAIN, + TDIE_ICON_FOOTER, +}} +FLAGS!{enum TASKDIALOG_COMMON_BUTTON_FLAGS { + TDCBF_OK_BUTTON = 0x0001, + TDCBF_YES_BUTTON = 0x0002, + TDCBF_NO_BUTTON = 0x0004, + TDCBF_CANCEL_BUTTON = 0x0008, + TDCBF_RETRY_BUTTON = 0x0010, + TDCBF_CLOSE_BUTTON = 0x0020, +}} +STRUCT!{nodebug struct TASKDIALOGCONFIG { + cbSize: ::UINT, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + dwFlags: TASKDIALOG_FLAGS, + dwCommonButtons: TASKDIALOG_COMMON_BUTTON_FLAGS, + pszWindowTitle: ::PCWSTR, + hMainIcon: ::HICON, + pszMainInstruction: ::PCWSTR, + pszContent: ::PCWSTR, + cButtons: ::UINT, + pButtons: *const TASKDIALOG_BUTTON, + nDefaultButton: ::c_int, + cRadioButtons: ::UINT, + pRadioButtons: *const TASKDIALOG_BUTTON, + nDefaultRadioButton: ::c_int, + pszVerificationText: ::PCWSTR, + pszExpandedInformation: ::PCWSTR, + pszExpandedControlText: ::PCWSTR, + pszCollapsedControlText: ::PCWSTR, + hFooterIcon: ::HICON, + pszFooter: ::PCWSTR, + pfCallback: PFTASKDIALOGCALLBACK, + lpCallbackData: ::LONG_PTR, + cxWidth: ::UINT, +}} +UNION!(TASKDIALOGCONFIG, hMainIcon, pszMainIcon, pszMainIcon_mut, ::PCWSTR); +UNION!(TASKDIALOGCONFIG, hFooterIcon, pszFooterIcon, pszFooterIcon_mut, ::PCWSTR); +pub const DA_LAST: ::c_int = 0x7FFFFFFF; +pub const DA_ERR: ::c_int = -1; +pub type PFNDAENUMCALLBACK = Option ::c_int>; +pub type PFNDAENUMCALLBACKCONST = Option ::c_int>; +pub type PFNDACOMPARE = Option ::c_int>; +pub type PFNDACOMPARECONST = Option ::c_int>; +pub enum DSA {} +pub type HDSA = *mut DSA; +pub const DSA_APPEND: ::c_int = DA_LAST; +pub const DSA_ERR: ::c_int = DA_ERR; +pub type PFNDSAENUMCALLBACK = PFNDAENUMCALLBACK; +pub type PFNDSAENUMCALLBACKCONST = PFNDAENUMCALLBACKCONST; +pub type PFNDSACOMPARE = PFNDACOMPARE; +pub type PFNDSACOMPARECONST = PFNDACOMPARECONST; +pub enum DPA {} +pub type HDPA = *mut DPA; +STRUCT!{struct DPASTREAMINFO { + iPos: ::c_int, + pvItem: *mut ::c_void, +}} +pub type PFNDPASTREAM = Option ::HRESULT>; +pub const DPAM_SORTED: ::DWORD = 0x00000001; +pub const DPAM_NORMAL: ::DWORD = 0x00000002; +pub const DPAM_UNION: ::DWORD = 0x00000004; +pub const DPAM_INTERSECT: ::DWORD = 0x00000008; +pub type PFNDPAMERGE = Option *mut ::c_void>; +pub type PFNDPAMERGECONST = Option *const ::c_void>; +pub const DPAMM_MERGE: ::UINT = 1; +pub const DPAMM_DELETE: ::UINT = 2; +pub const DPAMM_INSERT: ::UINT = 3; +pub const DPAS_SORTED: ::UINT = 0x0001; +pub const DPAS_INSERTBEFORE: ::UINT = 0x0002; +pub const DPAS_INSERTAFTER: ::UINT = 0x0004; +pub const DPA_APPEND: ::c_int = DA_LAST; +pub const DPA_ERR: ::c_int = DA_ERR; +pub type PFNDPAENUMCALLBACK = PFNDAENUMCALLBACK; +pub type PFNDPAENUMCALLBACKCONST = PFNDAENUMCALLBACKCONST; +pub type PFNDPACOMPARE = PFNDACOMPARE; +pub type PFNDPACOMPARECONST = PFNDACOMPARECONST; +pub const WSB_PROP_CYVSCROLL: ::UINT = 0x00000001; +pub const WSB_PROP_CXHSCROLL: ::UINT = 0x00000002; +pub const WSB_PROP_CYHSCROLL: ::UINT = 0x00000004; +pub const WSB_PROP_CXVSCROLL: ::UINT = 0x00000008; +pub const WSB_PROP_CXHTHUMB: ::UINT = 0x00000010; +pub const WSB_PROP_CYVTHUMB: ::UINT = 0x00000020; +pub const WSB_PROP_VBKGCOLOR: ::UINT = 0x00000040; +pub const WSB_PROP_HBKGCOLOR: ::UINT = 0x00000080; +pub const WSB_PROP_VSTYLE: ::UINT = 0x00000100; +pub const WSB_PROP_HSTYLE: ::UINT = 0x00000200; +pub const WSB_PROP_WINSTYLE: ::UINT = 0x00000400; +pub const WSB_PROP_PALETTE: ::UINT = 0x00000800; +pub const WSB_PROP_MASK: ::UINT = 0x00000FFF; +pub const FSB_FLAT_MODE: ::INT_PTR = 2; +pub const FSB_ENCARTA_MODE: ::INT_PTR = 1; +pub const FSB_REGULAR_MODE: ::INT_PTR = 0; +pub type SUBCLASSPROC = Option ::LRESULT>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/commdlg.rs b/third_party/cargo/vendor/winapi-0.2.8/src/commdlg.rs new file mode 100644 index 0000000..0eb3fd8 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/commdlg.rs @@ -0,0 +1,583 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! 32-Bit Common Dialog APIs +pub type LPOFNHOOKPROC = Option ::UINT_PTR>; +STRUCT!{nodebug struct OPENFILENAME_NT4A { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCSTR, + lpstrCustomFilter: ::LPSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCSTR, + lpstrTitle: ::LPCSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPOPENFILENAME_NT4A = *mut OPENFILENAME_NT4A; +STRUCT!{nodebug struct OPENFILENAME_NT4W { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCWSTR, + lpstrCustomFilter: ::LPWSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPWSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPWSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCWSTR, + lpstrTitle: ::LPCWSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCWSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPOPENFILENAME_NT4W = *mut OPENFILENAME_NT4W; +STRUCT!{nodebug struct OPENFILENAMEA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCSTR, + lpstrCustomFilter: ::LPSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCSTR, + lpstrTitle: ::LPCSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCSTR, + pvReserved: *mut ::c_void, + dwReserved: ::DWORD, + FlagsEx: ::DWORD, +}} +pub type LPOPENFILENAMEA = *mut OPENFILENAMEA; +STRUCT!{nodebug struct OPENFILENAMEW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpstrFilter: ::LPCWSTR, + lpstrCustomFilter: ::LPWSTR, + nMaxCustFilter: ::DWORD, + nFilterIndex: ::DWORD, + lpstrFile: ::LPWSTR, + nMaxFile: ::DWORD, + lpstrFileTitle: ::LPWSTR, + nMaxFileTitle: ::DWORD, + lpstrInitialDir: ::LPCWSTR, + lpstrTitle: ::LPCWSTR, + Flags: ::DWORD, + nFileOffset: ::WORD, + nFileExtension: ::WORD, + lpstrDefExt: ::LPCWSTR, + lCustData: ::LPARAM, + lpfnHook: LPOFNHOOKPROC, + lpTemplateName: ::LPCWSTR, + pvReserved: *mut ::c_void, + dwReserved: ::DWORD, + FlagsEx: ::DWORD, +}} +pub type LPOPENFILENAMEW = *mut OPENFILENAMEW; +pub const OFN_READONLY: ::DWORD = 0x00000001; +pub const OFN_OVERWRITEPROMPT: ::DWORD = 0x00000002; +pub const OFN_HIDEREADONLY: ::DWORD = 0x00000004; +pub const OFN_NOCHANGEDIR: ::DWORD = 0x00000008; +pub const OFN_SHOWHELP: ::DWORD = 0x00000010; +pub const OFN_ENABLEHOOK: ::DWORD = 0x00000020; +pub const OFN_ENABLETEMPLATE: ::DWORD = 0x00000040; +pub const OFN_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000080; +pub const OFN_NOVALIDATE: ::DWORD = 0x00000100; +pub const OFN_ALLOWMULTISELECT: ::DWORD = 0x00000200; +pub const OFN_EXTENSIONDIFFERENT: ::DWORD = 0x00000400; +pub const OFN_PATHMUSTEXIST: ::DWORD = 0x00000800; +pub const OFN_FILEMUSTEXIST: ::DWORD = 0x00001000; +pub const OFN_CREATEPROMPT: ::DWORD = 0x00002000; +pub const OFN_SHAREAWARE: ::DWORD = 0x00004000; +pub const OFN_NOREADONLYRETURN: ::DWORD = 0x00008000; +pub const OFN_NOTESTFILECREATE: ::DWORD = 0x00010000; +pub const OFN_NONETWORKBUTTON: ::DWORD = 0x00020000; +pub const OFN_NOLONGNAMES: ::DWORD = 0x00040000; +pub const OFN_EXPLORER: ::DWORD = 0x00080000; +pub const OFN_NODEREFERENCELINKS: ::DWORD = 0x00100000; +pub const OFN_LONGNAMES: ::DWORD = 0x00200000; +pub const OFN_ENABLEINCLUDENOTIFY: ::DWORD = 0x00400000; +pub const OFN_ENABLESIZING: ::DWORD = 0x00800000; +pub const OFN_DONTADDTORECENT: ::DWORD = 0x02000000; +pub const OFN_FORCESHOWHIDDEN: ::DWORD = 0x10000000; +pub const OFN_EX_NOPLACESBAR: ::DWORD = 0x00000001; +pub const OFN_SHAREFALLTHROUGH: ::UINT_PTR = 2; +pub const OFN_SHARENOWARN: ::UINT_PTR = 1; +pub const OFN_SHAREWARN: ::UINT_PTR = 0; +pub type LPCCHOOKPROC = Option ::UINT_PTR>; +STRUCT!{struct OFNOTIFYA { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEA, + pszFile: ::LPSTR, +}} +pub type LPOFNOTIFYA = *mut OFNOTIFYA; +STRUCT!{struct OFNOTIFYW { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEW, + pszFile: ::LPWSTR, +}} +pub type LPOFNOTIFYW = *mut OFNOTIFYW; +STRUCT!{struct OFNOTIFYEXA { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEA, + psf: ::LPVOID, + pidl: ::LPVOID, +}} +pub type LPOFNOTIFYEXA = *mut OFNOTIFYEXA; +STRUCT!{struct OFNOTIFYEXW { + hdr: ::NMHDR, + lpOFN: LPOPENFILENAMEW, + psf: ::LPVOID, + pidl: ::LPVOID, +}} +pub type LPOFNOTIFYEXW = *mut OFNOTIFYEXW; +pub const CDN_FIRST: ::UINT = -601i32 as ::UINT; +pub const CDN_LAST: ::UINT = -699i32 as ::UINT; +pub const CDN_INITDONE: ::UINT = CDN_FIRST - 0x0000; +pub const CDN_SELCHANGE: ::UINT = CDN_FIRST - 0x0001; +pub const CDN_FOLDERCHANGE: ::UINT = CDN_FIRST - 0x0002; +pub const CDN_SHAREVIOLATION: ::UINT = CDN_FIRST - 0x0003; +pub const CDN_HELP: ::UINT = CDN_FIRST - 0x0004; +pub const CDN_FILEOK: ::UINT = CDN_FIRST - 0x0005; +pub const CDN_TYPECHANGE: ::UINT = CDN_FIRST - 0x0006; +pub const CDN_INCLUDEITEM: ::UINT = CDN_FIRST - 0x0007; +pub const CDM_FIRST: ::UINT = ::WM_USER + 100; +pub const CDM_LAST: ::UINT = ::WM_USER + 200; +pub const CDM_GETSPEC: ::UINT = CDM_FIRST + 0x0000; +pub const CDM_GETFILEPATH: ::UINT = CDM_FIRST + 0x0001; +pub const CDM_GETFOLDERPATH: ::UINT = CDM_FIRST + 0x0002; +pub const CDM_GETFOLDERIDLIST: ::UINT = CDM_FIRST + 0x0003; +pub const CDM_SETCONTROLTEXT: ::UINT = CDM_FIRST + 0x0004; +pub const CDM_HIDECONTROL: ::UINT = CDM_FIRST + 0x0005; +pub const CDM_SETDEFEXT: ::UINT = CDM_FIRST + 0x0006; +STRUCT!{nodebug struct CHOOSECOLORA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HWND, + rgbResult: ::COLORREF, + lpCustColors: *mut ::COLORREF, + Flags: ::DWORD, + lCustData: ::LPARAM, + lpfnHook: LPCCHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPCHOOSECOLORA = *mut CHOOSECOLORA; +STRUCT!{nodebug struct CHOOSECOLORW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HWND, + rgbResult: ::COLORREF, + lpCustColors: *mut ::COLORREF, + Flags: ::DWORD, + lCustData: ::LPARAM, + lpfnHook: LPCCHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPCHOOSECOLORW = *mut CHOOSECOLORW; +pub const CC_RGBINIT: ::DWORD = 0x00000001; +pub const CC_FULLOPEN: ::DWORD = 0x00000002; +pub const CC_PREVENTFULLOPEN: ::DWORD = 0x00000004; +pub const CC_SHOWHELP: ::DWORD = 0x00000008; +pub const CC_ENABLEHOOK: ::DWORD = 0x00000010; +pub const CC_ENABLETEMPLATE: ::DWORD = 0x00000020; +pub const CC_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000040; +pub const CC_SOLIDCOLOR: ::DWORD = 0x00000080; +pub const CC_ANYCOLOR: ::DWORD = 0x00000100; +pub type LPFRHOOKPROC = Option ::UINT_PTR>; +STRUCT!{nodebug struct FINDREPLACEA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + Flags: ::DWORD, + lpstrFindWhat: ::LPSTR, + lpstrReplaceWith: ::LPSTR, + wFindWhatLen: ::WORD, + wReplaceWithLen: ::WORD, + lCustData: ::LPARAM, + lpfnHook: LPFRHOOKPROC, + lpTemplateName: ::LPCSTR, +}} +pub type LPFINDREPLACEA = *mut FINDREPLACEA; +STRUCT!{nodebug struct FINDREPLACEW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + Flags: ::DWORD, + lpstrFindWhat: ::LPWSTR, + lpstrReplaceWith: ::LPWSTR, + wFindWhatLen: ::WORD, + wReplaceWithLen: ::WORD, + lCustData: ::LPARAM, + lpfnHook: LPFRHOOKPROC, + lpTemplateName: ::LPCWSTR, +}} +pub type LPFINDREPLACEW = *mut FINDREPLACEW; +pub const FR_DOWN: ::DWORD = 0x00000001; +pub const FR_WHOLEWORD: ::DWORD = 0x00000002; +pub const FR_MATCHCASE: ::DWORD = 0x00000004; +pub const FR_FINDNEXT: ::DWORD = 0x00000008; +pub const FR_REPLACE: ::DWORD = 0x00000010; +pub const FR_REPLACEALL: ::DWORD = 0x00000020; +pub const FR_DIALOGTERM: ::DWORD = 0x00000040; +pub const FR_SHOWHELP: ::DWORD = 0x00000080; +pub const FR_ENABLEHOOK: ::DWORD = 0x00000100; +pub const FR_ENABLETEMPLATE: ::DWORD = 0x00000200; +pub const FR_NOUPDOWN: ::DWORD = 0x00000400; +pub const FR_NOMATCHCASE: ::DWORD = 0x00000800; +pub const FR_NOWHOLEWORD: ::DWORD = 0x00001000; +pub const FR_ENABLETEMPLATEHANDLE: ::DWORD = 0x00002000; +pub const FR_HIDEUPDOWN: ::DWORD = 0x00004000; +pub const FR_HIDEMATCHCASE: ::DWORD = 0x00008000; +pub const FR_HIDEWHOLEWORD: ::DWORD = 0x00010000; +pub const FR_RAW: ::DWORD = 0x00020000; +pub const FR_MATCHDIAC: ::DWORD = 0x20000000; +pub const FR_MATCHKASHIDA: ::DWORD = 0x40000000; +pub const FR_MATCHALEFHAMZA: ::DWORD = 0x80000000; +pub type LPCFHOOKPROC = Option ::UINT_PTR>; +STRUCT!{nodebug struct CHOOSEFONTA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDC: ::HDC, + lpLogFont: ::LPLOGFONTA, + iPointSize: ::INT, + Flags: ::DWORD, + rgbColors: ::COLORREF, + lCustData: ::LPARAM, + lpfnHook: LPCFHOOKPROC, + lpTemplateName: ::LPCSTR, + hInstance: ::HINSTANCE, + lpszStyle: ::LPSTR, + nFontType: ::WORD, + ___MISSING_ALIGNMENT__: ::WORD, + nSizeMin: ::INT, + nSizeMax: ::INT, +}} +pub type LPCHOOSEFONTA = *mut CHOOSEFONTA; +STRUCT!{nodebug struct CHOOSEFONTW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDC: ::HDC, + lpLogFont: ::LPLOGFONTW, + iPointSize: ::INT, + Flags: ::DWORD, + rgbColors: ::COLORREF, + lCustData: ::LPARAM, + lpfnHook: LPCFHOOKPROC, + lpTemplateName: ::LPCWSTR, + hInstance: ::HINSTANCE, + lpszStyle: ::LPWSTR, + nFontType: ::WORD, + ___MISSING_ALIGNMENT__: ::WORD, + nSizeMin: ::INT, + nSizeMax: ::INT, +}} +pub type LPCHOOSEFONTW = *mut CHOOSEFONTW; +pub const CF_SCREENFONTS: ::DWORD = 0x00000001; +pub const CF_PRINTERFONTS: ::DWORD = 0x00000002; +pub const CF_BOTH: ::DWORD = CF_SCREENFONTS | CF_PRINTERFONTS; +pub const CF_SHOWHELP: ::DWORD = 0x00000004; +pub const CF_ENABLEHOOK: ::DWORD = 0x00000008; +pub const CF_ENABLETEMPLATE: ::DWORD = 0x00000010; +pub const CF_ENABLETEMPLATEHANDLE: ::DWORD = 0x00000020; +pub const CF_INITTOLOGFONTSTRUCT: ::DWORD = 0x00000040; +pub const CF_USESTYLE: ::DWORD = 0x00000080; +pub const CF_EFFECTS: ::DWORD = 0x00000100; +pub const CF_APPLY: ::DWORD = 0x00000200; +pub const CF_ANSIONLY: ::DWORD = 0x00000400; +pub const CF_SCRIPTSONLY: ::DWORD = CF_ANSIONLY; +pub const CF_NOVECTORFONTS: ::DWORD = 0x00000800; +pub const CF_NOOEMFONTS: ::DWORD = CF_NOVECTORFONTS; +pub const CF_NOSIMULATIONS: ::DWORD = 0x00001000; +pub const CF_LIMITSIZE: ::DWORD = 0x00002000; +pub const CF_FIXEDPITCHONLY: ::DWORD = 0x00004000; +pub const CF_WYSIWYG: ::DWORD = 0x00008000; +pub const CF_FORCEFONTEXIST: ::DWORD = 0x00010000; +pub const CF_SCALABLEONLY: ::DWORD = 0x00020000; +pub const CF_TTONLY: ::DWORD = 0x00040000; +pub const CF_NOFACESEL: ::DWORD = 0x00080000; +pub const CF_NOSTYLESEL: ::DWORD = 0x00100000; +pub const CF_NOSIZESEL: ::DWORD = 0x00200000; +pub const CF_SELECTSCRIPT: ::DWORD = 0x00400000; +pub const CF_NOSCRIPTSEL: ::DWORD = 0x00800000; +pub const CF_NOVERTFONTS: ::DWORD = 0x01000000; +pub const CF_INACTIVEFONTS: ::DWORD = 0x02000000; +pub const SIMULATED_FONTTYPE: ::WORD = 0x8000; +pub const PRINTER_FONTTYPE: ::WORD = 0x4000; +pub const SCREEN_FONTTYPE: ::WORD = 0x2000; +pub const BOLD_FONTTYPE: ::WORD = 0x0100; +pub const ITALIC_FONTTYPE: ::WORD = 0x0200; +pub const REGULAR_FONTTYPE: ::WORD = 0x0400; +pub const PS_OPENTYPE_FONTTYPE: ::DWORD = 0x10000; +pub const TT_OPENTYPE_FONTTYPE: ::DWORD = 0x20000; +pub const TYPE1_FONTTYPE: ::DWORD = 0x40000; +pub const SYMBOL_FONTTYPE: ::DWORD = 0x80000; +pub const WM_CHOOSEFONT_GETLOGFONT: ::UINT = ::WM_USER + 1; +pub const WM_CHOOSEFONT_SETLOGFONT: ::UINT = ::WM_USER + 101; +pub const WM_CHOOSEFONT_SETFLAGS: ::UINT = ::WM_USER + 102; +pub const CD_LBSELNOITEMS: ::WORD = -1i16 as ::WORD; +pub const CD_LBSELCHANGE: ::WORD = 0; +pub const CD_LBSELSUB: ::WORD = 1; +pub const CD_LBSELADD: ::WORD = 2; +pub type LPPRINTHOOKPROC = Option ::UINT_PTR>; +pub type LPSETUPHOOKPROC = Option ::UINT_PTR>; +STRUCT!{nodebug struct PRINTDLGA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + nFromPage: ::WORD, + nToPage: ::WORD, + nMinPage: ::WORD, + nMaxPage: ::WORD, + nCopies: ::WORD, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPrintHook: LPPRINTHOOKPROC, + lpfnSetupHook: LPSETUPHOOKPROC, + lpPrintTemplateName: ::LPCSTR, + lpSetupTemplateName: ::LPCSTR, + hPrintTemplate: ::HGLOBAL, + hSetupTemplate: ::HGLOBAL, +}} +pub type LPPRINTDLGA = *mut PRINTDLGA; +STRUCT!{nodebug struct PRINTDLGW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + nFromPage: ::WORD, + nToPage: ::WORD, + nMinPage: ::WORD, + nMaxPage: ::WORD, + nCopies: ::WORD, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPrintHook: LPPRINTHOOKPROC, + lpfnSetupHook: LPSETUPHOOKPROC, + lpPrintTemplateName: ::LPCWSTR, + lpSetupTemplateName: ::LPCWSTR, + hPrintTemplate: ::HGLOBAL, + hSetupTemplate: ::HGLOBAL, +}} +pub type LPPRINTDLGW = *mut PRINTDLGW; +RIDL!( +interface IPrintDialogCallback(IPrintDialogCallbackVtbl) : IUnknown(IUnknownVtbl) { + fn InitDone(&mut self) -> ::HRESULT, + fn SelectionChange(&mut self) -> ::HRESULT, + fn HandleMessage( + &mut self, hDlg: ::HWND, uMsg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM, + pResult: *mut ::LRESULT + ) -> ::HRESULT +} +); +RIDL!( +interface IPrintDialogServices(IPrintDialogServicesVtbl) : IUnknown(IUnknownVtbl) { + fn GetCurrentDevMode(&mut self, pDevMode: ::LPDEVMODEW, pcbSize: *mut ::UINT) -> ::HRESULT, + fn GetCurrentPrinterName(&mut self, pPrinterName: ::LPWSTR, pcchSize: *mut ::UINT) -> ::HRESULT, + fn GetCurrentPortName(&mut self, pPortName: ::LPWSTR, pcchSize: *mut ::UINT) -> ::HRESULT +} +); +STRUCT!{struct PRINTPAGERANGE { + nFromPage: ::DWORD, + nToPage: ::DWORD, +}} +pub type LPPRINTPAGERANGE = *mut PRINTPAGERANGE; +pub type PCPRINTPAGERANGE = *const PRINTPAGERANGE; +STRUCT!{struct PRINTDLGEXA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + Flags2: ::DWORD, + ExclusionFlags: ::DWORD, + nPageRanges: ::DWORD, + nMaxPageRanges: ::DWORD, + lpPageRanges: LPPRINTPAGERANGE, + nMinPage: ::DWORD, + nMaxPage: ::DWORD, + nCopies: ::DWORD, + hInstance: ::HINSTANCE, + lpPrintTemplateName: ::LPCSTR, + lpCallback: ::LPUNKNOWN, + nPropertyPages: ::DWORD, + lphPropertyPages: *mut ::HPROPSHEETPAGE, + nStartPage: ::DWORD, + dwResultAction: ::DWORD, +}} +pub type LPPRINTDLGEXA = *mut PRINTDLGEXA; +STRUCT!{struct PRINTDLGEXW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + hDC: ::HDC, + Flags: ::DWORD, + Flags2: ::DWORD, + ExclusionFlags: ::DWORD, + nPageRanges: ::DWORD, + nMaxPageRanges: ::DWORD, + lpPageRanges: LPPRINTPAGERANGE, + nMinPage: ::DWORD, + nMaxPage: ::DWORD, + nCopies: ::DWORD, + hInstance: ::HINSTANCE, + lpPrintTemplateName: ::LPCWSTR, + lpCallback: ::LPUNKNOWN, + nPropertyPages: ::DWORD, + lphPropertyPages: *mut ::HPROPSHEETPAGE, + nStartPage: ::DWORD, + dwResultAction: ::DWORD, +}} +pub type LPPRINTDLGEXW = *mut PRINTDLGEXW; +pub const PD_ALLPAGES: ::DWORD = 0x00000000; +pub const PD_SELECTION: ::DWORD = 0x00000001; +pub const PD_PAGENUMS: ::DWORD = 0x00000002; +pub const PD_NOSELECTION: ::DWORD = 0x00000004; +pub const PD_NOPAGENUMS: ::DWORD = 0x00000008; +pub const PD_COLLATE: ::DWORD = 0x00000010; +pub const PD_PRINTTOFILE: ::DWORD = 0x00000020; +pub const PD_PRINTSETUP: ::DWORD = 0x00000040; +pub const PD_NOWARNING: ::DWORD = 0x00000080; +pub const PD_RETURNDC: ::DWORD = 0x00000100; +pub const PD_RETURNIC: ::DWORD = 0x00000200; +pub const PD_RETURNDEFAULT: ::DWORD = 0x00000400; +pub const PD_SHOWHELP: ::DWORD = 0x00000800; +pub const PD_ENABLEPRINTHOOK: ::DWORD = 0x00001000; +pub const PD_ENABLESETUPHOOK: ::DWORD = 0x00002000; +pub const PD_ENABLEPRINTTEMPLATE: ::DWORD = 0x00004000; +pub const PD_ENABLESETUPTEMPLATE: ::DWORD = 0x00008000; +pub const PD_ENABLEPRINTTEMPLATEHANDLE: ::DWORD = 0x00010000; +pub const PD_ENABLESETUPTEMPLATEHANDLE: ::DWORD = 0x00020000; +pub const PD_USEDEVMODECOPIES: ::DWORD = 0x00040000; +pub const PD_USEDEVMODECOPIESANDCOLLATE: ::DWORD = 0x00040000; +pub const PD_DISABLEPRINTTOFILE: ::DWORD = 0x00080000; +pub const PD_HIDEPRINTTOFILE: ::DWORD = 0x00100000; +pub const PD_NONETWORKBUTTON: ::DWORD = 0x00200000; +pub const PD_CURRENTPAGE: ::DWORD = 0x00400000; +pub const PD_NOCURRENTPAGE: ::DWORD = 0x00800000; +pub const PD_EXCLUSIONFLAGS: ::DWORD = 0x01000000; +pub const PD_USELARGETEMPLATE: ::DWORD = 0x10000000; +pub const PD_EXCL_COPIESANDCOLLATE: ::DWORD = ::DM_COPIES | ::DM_COLLATE; +pub const START_PAGE_GENERAL: ::DWORD = 0xffffffff; +pub const PD_RESULT_CANCEL: ::DWORD = 0; +pub const PD_RESULT_PRINT: ::DWORD = 1; +pub const PD_RESULT_APPLY: ::DWORD = 2; +STRUCT!{struct DEVNAMES { + wDriverOffset: ::WORD, + wDeviceOffset: ::WORD, + wOutputOffset: ::WORD, + wDefault: ::WORD, +}} +pub type LPDEVNAMES = *mut DEVNAMES; +pub type PCDEVNAMES = *const DEVNAMES; +pub const DN_DEFAULTPRN: ::WORD = 0x0001; +pub const WM_PSD_PAGESETUPDLG: ::UINT = ::WM_USER; +pub const WM_PSD_FULLPAGERECT: ::UINT = ::WM_USER + 1; +pub const WM_PSD_MINMARGINRECT: ::UINT = ::WM_USER + 2; +pub const WM_PSD_MARGINRECT: ::UINT = ::WM_USER + 3; +pub const WM_PSD_GREEKTEXTRECT: ::UINT = ::WM_USER + 4; +pub const WM_PSD_ENVSTAMPRECT: ::UINT = ::WM_USER + 5; +pub const WM_PSD_YAFULLPAGERECT: ::UINT = ::WM_USER + 6; +pub type LPPAGEPAINTHOOK = Option ::UINT_PTR>; +pub type LPPAGESETUPHOOK = Option ::UINT_PTR>; +STRUCT!{nodebug struct PAGESETUPDLGA { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + Flags: ::DWORD, + ptPaperSize: ::POINT, + rtMinMargin: ::RECT, + rtMargin: ::RECT, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPageSetupHook: LPPAGESETUPHOOK, + lpfnPagePaintHook: LPPAGEPAINTHOOK, + lpPageSetupTemplateName: ::LPCSTR, + hPageSetupTemplate: ::HGLOBAL, +}} +pub type LPPAGESETUPDLGA = *mut PAGESETUPDLGA; +STRUCT!{nodebug struct PAGESETUPDLGW { + lStructSize: ::DWORD, + hwndOwner: ::HWND, + hDevMode: ::HGLOBAL, + hDevNames: ::HGLOBAL, + Flags: ::DWORD, + ptPaperSize: ::POINT, + rtMinMargin: ::RECT, + rtMargin: ::RECT, + hInstance: ::HINSTANCE, + lCustData: ::LPARAM, + lpfnPageSetupHook: LPPAGESETUPHOOK, + lpfnPagePaintHook: LPPAGEPAINTHOOK, + lpPageSetupTemplateName: ::LPCWSTR, + hPageSetupTemplate: ::HGLOBAL, +}} +pub type LPPAGESETUPDLGW = *mut PAGESETUPDLGW; +pub const PSD_DEFAULTMINMARGINS: ::DWORD = 0x00000000; +pub const PSD_INWININIINTLMEASURE: ::DWORD = 0x00000000; +pub const PSD_MINMARGINS: ::DWORD = 0x00000001; +pub const PSD_MARGINS: ::DWORD = 0x00000002; +pub const PSD_INTHOUSANDTHSOFINCHES: ::DWORD = 0x00000004; +pub const PSD_INHUNDREDTHSOFMILLIMETERS: ::DWORD = 0x00000008; +pub const PSD_DISABLEMARGINS: ::DWORD = 0x00000010; +pub const PSD_DISABLEPRINTER: ::DWORD = 0x00000020; +pub const PSD_NOWARNING: ::DWORD = 0x00000080; +pub const PSD_DISABLEORIENTATION: ::DWORD = 0x00000100; +pub const PSD_RETURNDEFAULT: ::DWORD = 0x00000400; +pub const PSD_DISABLEPAPER: ::DWORD = 0x00000200; +pub const PSD_SHOWHELP: ::DWORD = 0x00000800; +pub const PSD_ENABLEPAGESETUPHOOK: ::DWORD = 0x00002000; +pub const PSD_ENABLEPAGESETUPTEMPLATE: ::DWORD = 0x00008000; +pub const PSD_ENABLEPAGESETUPTEMPLATEHANDLE: ::DWORD = 0x00020000; +pub const PSD_ENABLEPAGEPAINTHOOK: ::DWORD = 0x00040000; +pub const PSD_DISABLEPAGEPAINTING: ::DWORD = 0x00080000; +pub const PSD_NONETWORKBUTTON: ::DWORD = 0x00200000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/corsym.rs b/third_party/cargo/vendor/winapi-0.2.8/src/corsym.rs new file mode 100644 index 0000000..d036f07 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/corsym.rs @@ -0,0 +1,79 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Common Language Runtime Debugging Symbol Reader/Writer/Binder Interfaces +DEFINE_GUID!(CorSym_LanguageType_C, 0x63a08714, 0xfc37, 0x11d2, + 0x90, 0x4c, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageType_CPlusPlus, 0x3a12d0b7, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_CSharp, 0x3f5162f8, 0x07c6, 0x11d3, + 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageType_Basic, 0x3a12d0b8, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_Java, 0x3a12d0b4, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x0, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_Cobol, 0xaf046cd1, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_Pascal, 0xaf046cd2, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_ILAssembly, 0xaf046cd3, 0xd0e1, 0x11d2, + 0x97, 0x7c, 0x0, 0xa0, 0xc9, 0xb4, 0xd5, 0xc); +DEFINE_GUID!(CorSym_LanguageType_JScript, 0x3a12d0b6, 0xc26c, 0x11d0, + 0xb4, 0x42, 0x00, 0xa0, 0x24, 0x4a, 0x1d, 0xd2); +DEFINE_GUID!(CorSym_LanguageType_SMC, 0xd9b9f7b, 0x6611, 0x11d3, + 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd); +DEFINE_GUID!(CorSym_LanguageType_MCPlusPlus, 0x4b35fde8, 0x07c6, 0x11d3, + 0x90, 0x53, 0x0, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_LanguageVendor_Microsoft, 0x994b45c4, 0xe6e9, 0x11d2, + 0x90, 0x3f, 0x00, 0xc0, 0x4f, 0xa3, 0x02, 0xa1); +DEFINE_GUID!(CorSym_DocumentType_Text, 0x5a869d0b, 0x6611, 0x11d3, + 0xbd, 0x2a, 0x0, 0x0, 0xf8, 0x8, 0x49, 0xbd); +DEFINE_GUID!(CorSym_DocumentType_MC, 0xeb40cb65, 0x3c1f, 0x4352, + 0x9d, 0x7b, 0xba, 0xf, 0xc4, 0x7a, 0x9d, 0x77); +DEFINE_GUID!(CorSym_SourceHash_MD5, 0x406ea660, 0x64cf, 0x4c82, + 0xb6, 0xf0, 0x42, 0xd4, 0x81, 0x72, 0xa7, 0x99); +DEFINE_GUID!(CorSym_SourceHash_SHA1, 0xff1816ec, 0xaa5e, 0x4d10, + 0x87, 0xf7, 0x6f, 0x49, 0x63, 0x83, 0x34, 0x60); +ENUM!{enum CorSymAddrKind { + ADDR_IL_OFFSET = 1, + ADDR_NATIVE_RVA = 2, + ADDR_NATIVE_REGISTER = 3, + ADDR_NATIVE_REGREL = 4, + ADDR_NATIVE_OFFSET = 5, + ADDR_NATIVE_REGREG = 6, + ADDR_NATIVE_REGSTK = 7, + ADDR_NATIVE_STKREG = 8, + ADDR_BITFIELD = 9, + ADDR_NATIVE_ISECTOFFSET = 10, +}} +FLAGS!{enum CorSymVarFlag { + VAR_IS_COMP_GEN = 1, +}} +RIDL!( +interface ISymUnmanagedBinder(ISymUnmanagedBinderVtbl): IUnknown(IUnknownVtbl) { + fn GetReaderForFile( + &mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR, + pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT, + fn GetReaderFromStream( + &mut self, importer: *mut ::IUnknown, pstream: *mut ::IStream, + pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT +} +); +FLAGS!{enum CorSymSearchPolicyAttributes { + AllowRegistryAccess = 0x1, + AllowSymbolServerAccess = 0x2, + AllowOriginalPathAccess = 0x4, + AllowReferencePathAccess = 0x8, +}} +RIDL!( +interface ISymUnmanagedBinder2(ISymUnmanagedBinder2Vtbl): + ISymUnmanagedBinder(ISymUnmanagedBinderVtbl) { + fn GetReaderForFile2( + &mut self, importer: *mut ::IUnknown, fileName: *const ::WCHAR, searchPath: *const ::WCHAR, + searchPolicy: ::ULONG32, pRetVal: *mut *mut ISymUnmanagedReader + ) -> ::HRESULT +} +); +#[derive(Clone, Copy)] +pub struct ISymUnmanagedReader; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d2d1.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d2d1.rs new file mode 100644 index 0000000..1b1b039 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d2d1.rs @@ -0,0 +1,734 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of d2d1.h +// Types confirmed affected by the ABI issue: +// D2D1_SIZE_F, D2D1_SIZE_U, D2D1_COLOR_F, D2D1_PIXEL_FORMAT, +// D2D1_POINT_2F +pub const D2D1_DEFAULT_FLATTENING_TOLERANCE: ::FLOAT = 0.25; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_NEAREST_NEIGHBOR: ::DWORD = 0; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_LINEAR: ::DWORD = 1; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_CUBIC: ::DWORD = 2; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_MULTI_SAMPLE_LINEAR: ::DWORD = 3; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_ANISOTROPIC: ::DWORD = 4; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_HIGH_QUALITY_CUBIC: ::DWORD = 5; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_FANT: ::DWORD = 6; +pub const D2D1_INTERPOLATION_MODE_DEFINITION_MIPMAP_LINEAR: ::DWORD = 7; +ENUM!{enum D2D1_GAMMA { + D2D1_GAMMA_2_2 = 0, + D2D1_GAMMA_1_0 = 1, +}} +ENUM!{enum D2D1_OPACITY_MASK_CONTENT { + D2D1_OPACITY_MASK_CONTENT_GRAPHICS = 0, + D2D1_OPACITY_MASK_CONTENT_TEXT_NATURAL = 1, + D2D1_OPACITY_MASK_CONTENT_TEXT_GDI_COMPATIBLE = 2, +}} +ENUM!{enum D2D1_EXTEND_MODE { + D2D1_EXTEND_MODE_CLAMP = 0, + D2D1_EXTEND_MODE_WRAP = 1, + D2D1_EXTEND_MODE_MIRROR = 2, +}} +ENUM!{enum D2D1_ANTIALIAS_MODE { + D2D1_ANTIALIAS_MODE_PER_PRIMITIVE = 0, + D2D1_ANTIALIAS_MODE_ALIASED = 1, +}} +ENUM!{enum D2D1_TEXT_ANTIALIAS_MODE { + D2D1_TEXT_ANTIALIAS_MODE_DEFAULT = 0, + D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE = 1, + D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE = 2, + D2D1_TEXT_ANTIALIAS_MODE_ALIASED = 3, +}} +ENUM!{enum D2D1_BITMAP_INTERPOLATION_MODE { + D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR = + D2D1_INTERPOLATION_MODE_DEFINITION_NEAREST_NEIGHBOR, + D2D1_BITMAP_INTERPOLATION_MODE_LINEAR = + D2D1_INTERPOLATION_MODE_DEFINITION_LINEAR, +}} +FLAGS!{enum D2D1_DRAW_TEXT_OPTIONS { + D2D1_DRAW_TEXT_OPTIONS_NO_SNAP = 0x00000001, + D2D1_DRAW_TEXT_OPTIONS_CLIP = 0x00000002, + D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT = 0x00000004, + D2D1_DRAW_TEXT_OPTIONS_NONE = 0x00000000, +}} +pub type D2D1_POINT_2U = ::D2D_POINT_2U; +pub type D2D1_POINT_2F = ::D2D_POINT_2F; +pub type D2D1_RECT_F = ::D2D_RECT_F; +pub type D2D1_RECT_U = ::D2D_RECT_U; +pub type D2D1_SIZE_F = ::D2D_SIZE_F; +pub type D2D1_SIZE_U = ::D2D_SIZE_U; +pub type D2D1_COLOR_F = ::D2D_COLOR_F; +pub type D2D1_MATRIX_3X2_F = ::D2D_MATRIX_3X2_F; +pub type D2D1_TAG = ::UINT64; +STRUCT!{struct D2D1_BITMAP_PROPERTIES { + pixelFormat: ::D2D1_PIXEL_FORMAT, + dpiX: ::FLOAT, + dpiY: ::FLOAT, +}} +STRUCT!{struct D2D1_GRADIENT_STOP { + position: ::FLOAT, + color: D2D1_COLOR_F, +}} +STRUCT!{struct D2D1_BRUSH_PROPERTIES { + opacity: ::FLOAT, + transform: D2D1_MATRIX_3X2_F, +}} +STRUCT!{struct D2D1_BITMAP_BRUSH_PROPERTIES { + extendModeX: D2D1_EXTEND_MODE, + extendModeY: D2D1_EXTEND_MODE, + interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, +}} +STRUCT!{struct D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES { + startPoint: ::D2D1_POINT_2F, + endPoint: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES { + center: ::D2D1_POINT_2F, + gradientOriginOffset: ::D2D1_POINT_2F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +ENUM!{enum D2D1_ARC_SIZE { + D2D1_ARC_SIZE_SMALL = 0, + D2D1_ARC_SIZE_LARGE = 1, +}} +ENUM!{enum D2D1_CAP_STYLE { + D2D1_CAP_STYLE_FLAT = 0, + D2D1_CAP_STYLE_SQUARE = 1, + D2D1_CAP_STYLE_ROUND = 2, + D2D1_CAP_STYLE_TRIANGLE = 3, +}} +ENUM!{enum D2D1_DASH_STYLE { + D2D1_DASH_STYLE_SOLID = 0, + D2D1_DASH_STYLE_DASH = 1, + D2D1_DASH_STYLE_DOT = 2, + D2D1_DASH_STYLE_DASH_DOT = 3, + D2D1_DASH_STYLE_DASH_DOT_DOT = 4, + D2D1_DASH_STYLE_CUSTOM = 5, +}} +ENUM!{enum D2D1_LINE_JOIN { + D2D1_LINE_JOIN_MITER = 0, + D2D1_LINE_JOIN_BEVEL = 1, + D2D1_LINE_JOIN_ROUND = 2, + D2D1_LINE_JOIN_MITER_OR_BEVEL = 3, +}} +ENUM!{enum D2D1_COMBINE_MODE { + D2D1_COMBINE_MODE_UNION = 0, + D2D1_COMBINE_MODE_INTERSECT = 1, + D2D1_COMBINE_MODE_XOR = 2, + D2D1_COMBINE_MODE_EXCLUDE = 3, +}} +ENUM!{enum D2D1_GEOMETRY_RELATION { + D2D1_GEOMETRY_RELATION_UNKNOWN = 0, + D2D1_GEOMETRY_RELATION_DISJOINT = 1, + D2D1_GEOMETRY_RELATION_IS_CONTAINED = 2, + D2D1_GEOMETRY_RELATION_CONTAINS = 3, + D2D1_GEOMETRY_RELATION_OVERLAP = 4, +}} +ENUM!{enum D2D1_GEOMETRY_SIMPLIFICATION_OPTION { + D2D1_GEOMETRY_SIMPLIFICATION_OPTION_CUBICS_AND_LINES = 0, + D2D1_GEOMETRY_SIMPLIFICATION_OPTION_LINES = 1, +}} +ENUM!{enum D2D1_FIGURE_BEGIN { + D2D1_FIGURE_BEGIN_FILLED = 0, + D2D1_FIGURE_BEGIN_HOLLOW = 1, +}} +ENUM!{enum D2D1_FIGURE_END { + D2D1_FIGURE_END_OPEN = 0, + D2D1_FIGURE_END_CLOSED = 1, +}} +STRUCT!{struct D2D1_BEZIER_SEGMENT { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, + point3: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_TRIANGLE { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, + point3: ::D2D1_POINT_2F, +}} +FLAGS!{enum D2D1_PATH_SEGMENT { + D2D1_PATH_SEGMENT_NONE = 0x00000000, + D2D1_PATH_SEGMENT_FORCE_UNSTROKED = 0x00000001, + D2D1_PATH_SEGMENT_FORCE_ROUND_LINE_JOIN = 0x00000002, +}} +ENUM!{enum D2D1_SWEEP_DIRECTION { + D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE = 0, + D2D1_SWEEP_DIRECTION_CLOCKWISE = 1, +}} +ENUM!{enum D2D1_FILL_MODE { + D2D1_FILL_MODE_ALTERNATE = 0, + D2D1_FILL_MODE_WINDING = 1, +}} +STRUCT!{struct D2D1_ARC_SEGMENT { + point: ::D2D1_POINT_2F, + size: D2D1_SIZE_F, + rotationAngle: ::FLOAT, + sweepDirection: D2D1_SWEEP_DIRECTION, + arcSize: D2D1_ARC_SIZE, +}} +STRUCT!{struct D2D1_QUADRATIC_BEZIER_SEGMENT { + point1: ::D2D1_POINT_2F, + point2: ::D2D1_POINT_2F, +}} +STRUCT!{struct D2D1_ELLIPSE { + point: ::D2D1_POINT_2F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +STRUCT!{struct D2D1_ROUNDED_RECT { + rect: ::D2D1_RECT_F, + radiusX: ::FLOAT, + radiusY: ::FLOAT, +}} +STRUCT!{struct D2D1_STROKE_STYLE_PROPERTIES { + startCap: D2D1_CAP_STYLE, + endCap: D2D1_CAP_STYLE, + dashCap: D2D1_CAP_STYLE, + lineJoin: D2D1_LINE_JOIN, + miterLimit: ::FLOAT, + dashStyle: D2D1_DASH_STYLE, + dashOffset: ::FLOAT, +}} +FLAGS!{enum D2D1_LAYER_OPTIONS { + D2D1_LAYER_OPTIONS_NONE = 0x00000000, + D2D1_LAYER_OPTIONS_INITIALIZE_FOR_CLEARTYPE = 0x00000001, +}} +STRUCT!{struct D2D1_LAYER_PARAMETERS { + contentBounds: ::D2D1_RECT_F, + geometricMask: *mut ID2D1Geometry, + maskAntialiasMode: D2D1_ANTIALIAS_MODE, + maskTransform: D2D1_MATRIX_3X2_F, + opacity: ::FLOAT, + opacityBrush: *mut ID2D1Brush, + layerOptions: D2D1_LAYER_OPTIONS, +}} +ENUM!{enum D2D1_WINDOW_STATE { + D2D1_WINDOW_STATE_NONE = 0x0000000, + D2D1_WINDOW_STATE_OCCLUDED = 0x0000001, +}} +ENUM!{enum D2D1_RENDER_TARGET_TYPE { + D2D1_RENDER_TARGET_TYPE_DEFAULT = 0, + D2D1_RENDER_TARGET_TYPE_SOFTWARE = 1, + D2D1_RENDER_TARGET_TYPE_HARDWARE = 2, +}} +ENUM!{enum D2D1_FEATURE_LEVEL { + D2D1_FEATURE_LEVEL_DEFAULT = 0, + D2D1_FEATURE_LEVEL_9 = ::D3D_FEATURE_LEVEL_9_1.0, + D2D1_FEATURE_LEVEL_10 = ::D3D_FEATURE_LEVEL_10_0.0, +}} +FLAGS!{enum D2D1_RENDER_TARGET_USAGE { + D2D1_RENDER_TARGET_USAGE_NONE = 0x00000000, + D2D1_RENDER_TARGET_USAGE_FORCE_BITMAP_REMOTING = 0x00000001, + D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE = 0x00000002, +}} +FLAGS!{enum D2D1_PRESENT_OPTIONS { + D2D1_PRESENT_OPTIONS_NONE = 0x00000000, + D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS = 0x00000001, + D2D1_PRESENT_OPTIONS_IMMEDIATELY = 0x00000002, +}} +STRUCT!{struct D2D1_RENDER_TARGET_PROPERTIES { + _type: D2D1_RENDER_TARGET_TYPE, + pixelFormat: ::D2D1_PIXEL_FORMAT, + dpiX: ::FLOAT, + dpiY: ::FLOAT, + usage: D2D1_RENDER_TARGET_USAGE, + minLevel: D2D1_FEATURE_LEVEL, +}} +STRUCT!{struct D2D1_HWND_RENDER_TARGET_PROPERTIES { + hwnd: ::HWND, + pixelSize: D2D1_SIZE_U, + presentOptions: D2D1_PRESENT_OPTIONS, +}} +FLAGS!{enum D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS { + D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_NONE = 0x00000000, + D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS_GDI_COMPATIBLE = 0x00000001, +}} +STRUCT!{struct D2D1_DRAWING_STATE_DESCRIPTION { + antialiasMode: D2D1_ANTIALIAS_MODE, + textAntialiasMode: D2D1_TEXT_ANTIALIAS_MODE, + tag1: D2D1_TAG, + tag2: D2D1_TAG, + transform: D2D1_MATRIX_3X2_F, +}} +ENUM!{enum D2D1_DC_INITIALIZE_MODE { + D2D1_DC_INITIALIZE_MODE_COPY = 0, + D2D1_DC_INITIALIZE_MODE_CLEAR = 1, +}} +ENUM!{enum D2D1_DEBUG_LEVEL { + D2D1_DEBUG_LEVEL_NONE = 0, + D2D1_DEBUG_LEVEL_ERROR = 1, + D2D1_DEBUG_LEVEL_WARNING = 2, + D2D1_DEBUG_LEVEL_INFORMATION = 3, +}} +ENUM!{enum D2D1_FACTORY_TYPE { + D2D1_FACTORY_TYPE_SINGLE_THREADED = 0, + D2D1_FACTORY_TYPE_MULTI_THREADED = 1, +}} +STRUCT!{struct D2D1_FACTORY_OPTIONS { + debugLevel: D2D1_DEBUG_LEVEL, +}} +RIDL!( +interface ID2D1Resource(ID2D1ResourceVtbl): IUnknown(IUnknownVtbl) { + fn GetFactory(&mut self, factory: *mut *mut ID2D1Factory) -> () +}); +RIDL!( +interface ID2D1Image(ID2D1ImageVtbl): ID2D1Resource(ID2D1ResourceVtbl) { +}); +RIDL!( +interface ID2D1Bitmap(ID2D1BitmapVtbl): ID2D1Image(ID2D1ImageVtbl) { + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F, // FIXME: ABI issue + fn GetPixelSize(&mut self, ret: *mut D2D1_SIZE_U) -> *mut D2D1_SIZE_U, // FIXME: ABI issue + fn GetPixelFormat( + &mut self, ret: *mut ::D2D1_PIXEL_FORMAT + ) -> *mut ::D2D1_PIXEL_FORMAT, // FIXME: ABI issue + fn GetDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn CopyFromBitmap( + &mut self, destPoint: *const ::D2D1_POINT_2U, bitmap: *mut ID2D1Bitmap, + srcRect: *const ::D2D1_RECT_U + ) -> ::HRESULT, + fn CopyFromRenderTarget( + &mut self, destPoint: *const ::D2D1_POINT_2U, renderTarget: *mut ID2D1RenderTarget, + srcRect: *const ::D2D1_RECT_U + ) -> ::HRESULT, + fn CopyFromMemory( + &mut self, dstRect: *const ::D2D1_RECT_U, srcData: *const ::c_void, pitch: ::UINT32 + ) -> ::HRESULT +}); +RIDL!( +interface ID2D1GradientStopCollection(ID2D1GradientStopCollectionVtbl) + : ID2D1Resource(ID2D1ResourceVtbl) { + fn GetGradientStopCount(&mut self) -> ::UINT32, + fn GetGradientStops( + &mut self, gradientStops: *mut D2D1_GRADIENT_STOP, gradientStopsCount: ::UINT32 + ) -> (), + fn GetColorInterpolationGamma(&mut self) -> D2D1_GAMMA, + fn GetExtendMode(&mut self) -> D2D1_EXTEND_MODE +}); +RIDL!( +interface ID2D1Brush(ID2D1BrushVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn SetOpacity(&mut self, opacity: ::FLOAT) -> (), + fn SetTransform(&mut self, transform: *const D2D1_MATRIX_3X2_F) -> (), + fn GetOpacity(&mut self) -> ::FLOAT, + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> () +}); +RIDL!( +interface ID2D1BitmapBrush(ID2D1BitmapBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetExtendModeX(&mut self, extendModeX: D2D1_EXTEND_MODE) -> (), + fn SetExtendModeY(&mut self, extendModeY: D2D1_EXTEND_MODE) -> (), + fn SetInterpolationMode(&mut self, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE) -> (), + fn SetBitmap(&mut self, bitmap: *mut ID2D1Bitmap) -> (), + fn GetExtendModeX(&mut self) -> D2D1_EXTEND_MODE, + fn GetExtendModeY(&mut self) -> D2D1_EXTEND_MODE, + fn GetInterpolationMode(&mut self) -> D2D1_BITMAP_INTERPOLATION_MODE, + fn GetBitmap(&mut self, bitmap: *mut *mut ID2D1Bitmap) -> () +}); +RIDL!( +interface ID2D1SolidColorBrush(ID2D1SolidColorBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetColor(&mut self, color: *const D2D1_COLOR_F) -> (), + fn GetColor(&mut self, color: *mut D2D1_COLOR_F) -> *mut D2D1_COLOR_F +}); +RIDL!( +interface ID2D1LinearGradientBrush(ID2D1LinearGradientBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetStartPoint(&mut self, startPoint: ::D2D1_POINT_2F) -> (), + fn SetEndPoint(&mut self, endPoint: ::D2D1_POINT_2F) -> (), + fn GetStartPoint(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetEndPoint(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetGradientStopCollection( + &mut self, gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> () +}); +RIDL!( +interface ID2D1RadialGradientBrush(ID2D1RadialGradientBrushVtbl): ID2D1Brush(ID2D1BrushVtbl) { + fn SetCenter(&mut self, center: ::D2D1_POINT_2F) -> (), + fn SetGradientOriginOffset(&mut self, gradientOriginOffset: ::D2D1_POINT_2F) -> (), + fn SetRadiusX(&mut self, radiusX: ::FLOAT) -> (), + fn SetRadiusY(&mut self, radiusY: ::FLOAT) -> (), + fn GetCenter(&mut self, ret: *mut D2D1_POINT_2F) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetGradientOriginOffset( + &mut self, ret: *mut D2D1_POINT_2F + ) -> *mut D2D1_POINT_2F, // FIXME ABI issue + fn GetRadiusX(&mut self) -> ::FLOAT, + fn GetRadiusY(&mut self) -> ::FLOAT, + fn GetGradientStopCollection( + &mut self, gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> () +}); +RIDL!( +interface ID2D1StrokeStyle(ID2D1StrokeStyleVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetStartCap(&mut self) -> D2D1_CAP_STYLE, + fn GetEndCap(&mut self) -> D2D1_CAP_STYLE, + fn GetDashCap(&mut self) -> D2D1_CAP_STYLE, + fn GetMiterLimit(&mut self) -> ::FLOAT, + fn GetLineJoin(&mut self) -> D2D1_LINE_JOIN, + fn GetDashOffset(&mut self) -> ::FLOAT, + fn GetDashStyle(&mut self) -> D2D1_DASH_STYLE, + fn GetDashesCount(&mut self) -> ::UINT32, + fn GetDashes(&mut self, dashes: *mut ::FLOAT, dashesCount: ::UINT32) -> () +}); +RIDL!( +interface ID2D1Geometry(ID2D1GeometryVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetBounds( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, bounds: *mut ::D2D1_RECT_F + ) -> ::HRESULT, + fn GetWidenedBounds( + &mut self, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + bounds: *mut ::D2D1_RECT_F + ) -> ::HRESULT, + fn StrokeContainsPoint( + &mut self, point: ::D2D1_POINT_2F, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + contains: *mut ::BOOL + ) -> ::HRESULT, + fn FillContainsPoint( + &mut self, point: ::D2D1_POINT_2F, worldTransform: *const D2D1_MATRIX_3X2_F, + flatteningTolerance: ::FLOAT, contains: *mut ::BOOL + ) -> ::HRESULT, + fn CompareWithGeometry( + &mut self, inputGeometry: *mut ID2D1Geometry, + inputGeometryTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + relation: *mut D2D1_GEOMETRY_RELATION + ) -> ::HRESULT, + fn Simplify( + &mut self, simplificationOption: D2D1_GEOMETRY_SIMPLIFICATION_OPTION, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn Tessellate( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + tessellationSink: *mut ID2D1TessellationSink + ) -> ::HRESULT, + fn CombineWithGeometry( + &mut self, inputGeometry: *mut ID2D1Geometry, combineMode: D2D1_COMBINE_MODE, + inputGeometryTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn Outline( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT, + fn ComputeArea( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + area: *mut ::FLOAT + ) -> ::HRESULT, + fn ComputeLength( + &mut self, worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + length: *mut ::FLOAT + ) -> ::HRESULT, + fn ComputePointAtLength( + &mut self, length: ::FLOAT, worldTransform: *const D2D1_MATRIX_3X2_F, + flatteningTolerance: ::FLOAT, point: *mut ::D2D1_POINT_2F, + unitTangentVector: *mut ::D2D1_POINT_2F + ) -> ::HRESULT, + fn Widen( + &mut self, strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle, + worldTransform: *const D2D1_MATRIX_3X2_F, flatteningTolerance: ::FLOAT, + geometrySink: *mut ID2D1SimplifiedGeometrySink + ) -> ::HRESULT +}); +RIDL!( +interface ID2D1RectangleGeometry(ID2D1RectangleGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetRect(&mut self, rect: *mut ::D2D1_RECT_F) -> () +}); +RIDL!( +interface ID2D1RoundedRectangleGeometry(ID2D1RoundedRectangleGeometryVtbl) + : ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetRoundedRect(&mut self, roundedRect: *mut D2D1_ROUNDED_RECT) -> () +}); +RIDL!( +interface ID2D1EllipseGeometry(ID2D1EllipseGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetEllipse(&mut self, ellipse: *mut D2D1_ELLIPSE) -> () +}); +RIDL!( +interface ID2D1GeometryGroup(ID2D1GeometryGroupVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetFillMode(&mut self) -> D2D1_FILL_MODE, + fn GetSourceGeometryCount(&mut self) -> ::UINT32, + fn GetSourceGeometries( + &mut self, geometries: *mut *mut ID2D1Geometry, geometriesCount: ::UINT32 + ) -> () +}); +RIDL!( +interface ID2D1TransformedGeometry(ID2D1TransformedGeometryVtbl) + : ID2D1Geometry(ID2D1GeometryVtbl) { + fn GetSourceGeometry(&mut self, sourceGeometry: *mut *mut ID2D1Geometry) -> (), + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> () +}); +RIDL!( +interface ID2D1SimplifiedGeometrySink(ID2D1SimplifiedGeometrySinkVtbl): IUnknown(IUnknownVtbl) { + fn SetFillMode(&mut self, fillMode: D2D1_FILL_MODE) -> (), + fn SetSegmentFlags(&mut self, vertexFlags: D2D1_PATH_SEGMENT) -> (), + fn BeginFigure(&mut self, startPoint: ::D2D1_POINT_2F, figureBegin: D2D1_FIGURE_BEGIN) -> (), + fn AddLines(&mut self, points: *const ::D2D1_POINT_2F, pointsCount: ::UINT32) -> (), + fn AddBeziers(&mut self, beziers: *const D2D1_BEZIER_SEGMENT, beziersCount: ::UINT32) -> (), + fn EndFigure(&mut self, figureEnd: D2D1_FIGURE_END) -> (), + fn Close(&mut self) -> ::HRESULT +}); +RIDL!( +interface ID2D1GeometrySink(ID2D1GeometrySinkVtbl) + : ID2D1SimplifiedGeometrySink(ID2D1SimplifiedGeometrySinkVtbl) { + fn AddLine(&mut self, point: ::D2D1_POINT_2F) -> (), + fn AddBezier(&mut self, bezier: *const D2D1_BEZIER_SEGMENT) -> (), + fn AddQuadraticBezier(&mut self, bezier: *const D2D1_QUADRATIC_BEZIER_SEGMENT) -> (), + fn AddQuadraticBeziers( + &mut self, beziers: *const D2D1_QUADRATIC_BEZIER_SEGMENT, beziersCount: ::UINT32 + ) -> (), + fn AddArc(&mut self, arc: *const D2D1_ARC_SEGMENT) -> () +}); +RIDL!( +interface ID2D1TessellationSink(ID2D1TessellationSinkVtbl): IUnknown(IUnknownVtbl) { + fn AddTriangles(&mut self, triangles: *const D2D1_TRIANGLE, triangleCount: ::UINT32) -> (), + fn Close(&mut self) -> ::HRESULT +}); +RIDL!( +interface ID2D1PathGeometry(ID2D1PathGeometryVtbl): ID2D1Geometry(ID2D1GeometryVtbl) { + fn Open(&mut self, geometrySink: *mut *mut ID2D1GeometrySink) -> ::HRESULT, + fn Stream(&mut self, geometrySink: *mut ID2D1GeometrySink) -> ::HRESULT, + fn GetSegmentCount(&mut self, count: *mut ::UINT32) -> ::HRESULT, + fn GetFigureCount(&mut self, count: *mut ::UINT32) -> ::HRESULT +}); +RIDL!( +interface ID2D1Mesh(ID2D1MeshVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn Open(&mut self, tessellationSink: *mut *mut ID2D1TessellationSink) -> ::HRESULT +}); +RIDL!( +interface ID2D1Layer(ID2D1LayerVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F // FIXME: ABI issue +}); +RIDL!( +interface ID2D1DrawingStateBlock(ID2D1DrawingStateBlockVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn GetDescription(&mut self, stateDescription: *mut D2D1_DRAWING_STATE_DESCRIPTION) -> (), + fn SetDescription(&mut self, stateDescription: *const D2D1_DRAWING_STATE_DESCRIPTION) -> (), + fn SetTextRenderingParams( + &mut self, textRenderingParams: *mut ::IDWriteRenderingParams + ) -> (), + fn GetTextRenderingParams( + &mut self, textRenderingParams: *mut *mut ::IDWriteRenderingParams + ) -> () +}); +RIDL!( +interface ID2D1RenderTarget(ID2D1RenderTargetVtbl): ID2D1Resource(ID2D1ResourceVtbl) { + fn CreateBitmap( + &mut self, size: D2D1_SIZE_U, srcData: *const ::c_void, pitch: ::UINT32, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateBitmapFromWicBitmap( + &mut self, wicBitmapSource: *mut ::IWICBitmapSource, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateSharedBitmap( + &mut self, riid: ::REFIID, data: *const ::c_void, + bitmapProperties: *const D2D1_BITMAP_PROPERTIES, bitmap: *mut *mut ID2D1Bitmap + ) -> ::HRESULT, + fn CreateBitmapBrush( + &mut self, bitmap: *mut ID2D1Bitmap, + bitmapBrushProperties: *const D2D1_BITMAP_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, bitmapBrush: *mut *mut ID2D1BitmapBrush + ) -> ::HRESULT, + fn CreateSolidColorBrush( + &mut self, color: *const D2D1_COLOR_F, brushProperties: *const D2D1_BRUSH_PROPERTIES, + solidColorBrush: *mut *mut ID2D1SolidColorBrush + ) -> ::HRESULT, + fn CreateGradientStopCollection( + &mut self, gradientStops: *const D2D1_GRADIENT_STOP, gradientStopsCount: ::UINT32, + colorInterpolationGamma: D2D1_GAMMA, extendMode: D2D1_EXTEND_MODE, + gradientStopCollection: *mut *mut ID2D1GradientStopCollection + ) -> ::HRESULT, + fn CreateLinearGradientBrush( + &mut self, linearGradientBrushProperties: *const D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, + gradientStopCollection: *mut ID2D1GradientStopCollection, + linearGradientBrush: *mut *mut ID2D1LinearGradientBrush + ) -> ::HRESULT, + fn CreateRadialGradientBrush( + &mut self, radialGradientBrushProperties: *const D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES, + brushProperties: *const D2D1_BRUSH_PROPERTIES, + gradientStopCollection: *mut ID2D1GradientStopCollection, + radialGradientBrush: *mut *mut ID2D1RadialGradientBrush + ) -> ::HRESULT, + fn CreateCompatibleRenderTarget( + &mut self, desiredSize: *const D2D1_SIZE_F, desiredPixelSize: *const D2D1_SIZE_U, + desiredFormat: *const ::D2D1_PIXEL_FORMAT, options: D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS, + bitmapRenderTarget: *mut *mut ID2D1BitmapRenderTarget + ) -> ::HRESULT, + fn CreateLayer(&mut self, size: *const D2D1_SIZE_F, layer: *mut *mut ID2D1Layer) -> ::HRESULT, + fn CreateMesh(&mut self, mesh: *mut *mut ID2D1Mesh) -> ::HRESULT, + fn DrawLine( + &mut self, point0: ::D2D1_POINT_2F, point1: ::D2D1_POINT_2F, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStype: *mut ID2D1StrokeStyle + ) -> (), + fn DrawRectangle( + &mut self, rect: *const ::D2D1_RECT_F, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillRectangle( + &mut self, rect: *const ::D2D1_RECT_F, brush: *mut ID2D1Brush + ) -> (), + fn DrawRoundedRectangle( + &mut self, roundedRect: *const D2D1_ROUNDED_RECT, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillRoundedRectangle( + &mut self, roundedRect: *const D2D1_ROUNDED_RECT, brush: *mut ID2D1Brush + ) -> (), + fn DrawEllipse( + &mut self, ellipse: *const D2D1_ELLIPSE, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillEllipse( + &mut self, ellipse: *const D2D1_ELLIPSE, brush: *mut ID2D1Brush + ) -> (), + fn DrawGeometry( + &mut self, geometry: *mut ID2D1Geometry, brush: *mut ID2D1Brush, + strokeWidth: ::FLOAT, strokeStyle: *mut ID2D1StrokeStyle + ) -> (), + fn FillGeometry( + &mut self, geometry: *mut ID2D1Geometry, brush: *mut ID2D1Brush, + opacityBrush: *mut ID2D1Brush + ) -> (), + fn FillMesh( + &mut self, mesh: *mut ID2D1Mesh, brush: *const ID2D1Brush + ) -> (), + fn FillOpacityMask( + &mut self, opacityMask: *mut ID2D1Bitmap, brush: *mut ID2D1Brush, + content: D2D1_OPACITY_MASK_CONTENT, destinationRectangle: *const ::D2D1_RECT_F, + sourceRectangle: *const ::D2D1_RECT_F + ) -> (), + fn DrawBitmap( + &mut self, bitmap: *mut ID2D1Bitmap, destinationRectangle: *const ::D2D1_RECT_F, + opacity: ::FLOAT, interpolationMode: D2D1_BITMAP_INTERPOLATION_MODE, + sourceRectangle: *const ::D2D1_RECT_F + ) -> (), + fn DrawText( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut ::IDWriteTextFormat, layoutRect: *const ::D2D1_RECT_F, + defaultForegroundBrush: *mut ID2D1Brush, options: D2D1_DRAW_TEXT_OPTIONS, + measuringMode: ::DWRITE_MEASURING_MODE + ) -> (), + fn DrawTextLayout( + &mut self, origin: ::D2D1_POINT_2F, textLayout: *mut ::IDWriteTextLayout, + defaultForegroundBrush: *mut ID2D1Brush, options: D2D1_DRAW_TEXT_OPTIONS + ) -> (), + fn DrawGlyphRun( + &mut self, baselineOrigin: ::D2D1_POINT_2F, glyphRun: *const ::DWRITE_GLYPH_RUN, + foregroundBrush: *mut ID2D1Brush, measuringMode: ::DWRITE_MEASURING_MODE + ) -> (), + fn SetTransform(&mut self, transform: *const D2D1_MATRIX_3X2_F) -> (), + fn GetTransform(&mut self, transform: *mut D2D1_MATRIX_3X2_F) -> (), + fn SetAntialiasMode(&mut self, antialiasMode: D2D1_ANTIALIAS_MODE) -> (), + fn GetAntialiasMode(&mut self) -> D2D1_ANTIALIAS_MODE, + fn SetTextAntialiasMode(&mut self, textAntialiasMode: D2D1_TEXT_ANTIALIAS_MODE) -> (), + fn GetTextAntialiasMode(&mut self) -> D2D1_TEXT_ANTIALIAS_MODE, + fn SetTextRenderingParams( + &mut self, textRenderingParams: *mut ::IDWriteRenderingParams + ) -> (), + fn GetTextRenderingParams( + &mut self, textRenderingParams: *mut *mut ::IDWriteRenderingParams + ) -> (), + fn SetTags(&mut self, tag1: D2D1_TAG, tag2: D2D1_TAG) -> (), + fn GetTags(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> (), + fn PushLayer( + &mut self, layerParameters: *const D2D1_LAYER_PARAMETERS, layer: *mut ID2D1Layer + ) -> (), + fn PopLayer(&mut self) -> (), + fn Flush(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> ::HRESULT, + fn SaveDrawingState(&mut self, drawingStateBlock: *mut ID2D1DrawingStateBlock) -> (), + fn RestoreDrawingState(&mut self, drawingStateBlock: *mut ID2D1DrawingStateBlock) -> (), + fn PushAxisAlignedClip( + &mut self, clipRect: *const ::D2D1_RECT_F, antialiasMode: D2D1_ANTIALIAS_MODE + ) -> (), + fn PopAxisAlignedClip(&mut self) -> (), + fn Clear(&mut self, clearColor: *const D2D1_COLOR_F) -> (), + fn BeginDraw(&mut self) -> (), + fn EndDraw(&mut self, tag1: *mut D2D1_TAG, tag2: *mut D2D1_TAG) -> ::HRESULT, + fn GetPixelFormat( + &mut self, ret: *mut ::D2D1_PIXEL_FORMAT + ) -> *mut ::D2D1_PIXEL_FORMAT, // FIXME: ABI issue + fn SetDpi(&mut self, dpiX: ::FLOAT, dpiY: ::FLOAT) -> (), + fn GetDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn GetSize(&mut self, ret: *mut D2D1_SIZE_F) -> *mut D2D1_SIZE_F, // FIXME: ABI issue + fn GetPixelSize(&mut self, ret: *mut D2D1_SIZE_U) -> *mut D2D1_SIZE_U, // FIXME: ABI issue + fn GetMaximumBitmapSize(&mut self) -> ::UINT32, + fn IsSupported( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES + ) -> ::BOOL +}); +RIDL!( +interface ID2D1BitmapRenderTarget(ID2D1BitmapRenderTargetVtbl) + : ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn GetBitmap(&mut self, bitmap: *mut *mut ID2D1Bitmap) -> ::HRESULT +}); +RIDL!( +interface ID2D1HwndRenderTarget(ID2D1HwndRenderTargetVtbl) + : ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn CheckWindowState(&mut self) -> D2D1_WINDOW_STATE, + fn Resize(&mut self, pixelSize: *const D2D1_SIZE_U) -> ::HRESULT, + fn GetHwnd(&mut self) -> ::HWND +}); +RIDL!( +interface ID2D1GdiInteropRenderTarget(ID2D1GdiInteropRenderTargetVtbl): IUnknown(IUnknownVtbl) { + fn GetDC(&mut self, mode: D2D1_DC_INITIALIZE_MODE, hdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, update: *const ::RECT) -> ::HRESULT +}); +RIDL!( +interface ID2D1DCRenderTarget(ID2D1DCRenderTargetVtbl): ID2D1RenderTarget(ID2D1RenderTargetVtbl) { + fn BindDC(&mut self, hDC: ::HDC, pSubRect: *const ::RECT) -> ::HRESULT +}); +RIDL!( +interface ID2D1Factory(ID2D1FactoryVtbl): IUnknown(IUnknownVtbl) { + fn ReloadSystemMetrics(&mut self) -> ::HRESULT, + fn GetDesktopDpi(&mut self, dpiX: *mut ::FLOAT, dpiY: *mut ::FLOAT) -> (), + fn CreateRectangleGeometry( + &mut self, rectangle: *const ::D2D1_RECT_F, + rectangleGeometry: *mut *mut ID2D1RectangleGeometry + ) -> ::HRESULT, + fn CreateRoundedRectangleGeometry( + &mut self, roundedRectangle: *const D2D1_ROUNDED_RECT, + roundedRectangleGeometry: *mut *mut ID2D1RoundedRectangleGeometry + ) -> ::HRESULT, + fn CreateEllipseGeometry( + &mut self, ellipse: *const D2D1_ELLIPSE, + ellipseGeometry: *mut *mut ID2D1EllipseGeometry + ) -> ::HRESULT, + fn CreateGeometryGroup( + &mut self, fillMode: D2D1_FILL_MODE, geometries: *mut *mut ID2D1Geometry, + geometriesCount: ::UINT32, geometryGroup: *mut *mut ID2D1GeometryGroup + ) -> ::HRESULT, + fn CreateTransformedGeometry( + &mut self, sourceGeometry: *mut ID2D1Geometry, transform: *const D2D1_MATRIX_3X2_F, + transformedGeometry: *mut *mut ID2D1TransformedGeometry + ) -> ::HRESULT, + fn CreatePathGeometry( + &mut self, pathGeometry: *mut *mut ID2D1PathGeometry + ) -> ::HRESULT, + fn CreateStrokeStyle( + &mut self, strokeStyleProperties: *const D2D1_STROKE_STYLE_PROPERTIES, + dashes: *const ::FLOAT, dashesCount: ::UINT32, strokeStyle: *mut *mut ID2D1StrokeStyle + ) -> ::HRESULT, + fn CreateDrawingStateBlock( + &mut self, drawingStateDescription: *const D2D1_DRAWING_STATE_DESCRIPTION, + textRenderingParams: *mut ::IDWriteRenderingParams, + drawingStateBlock: *mut *mut ID2D1DrawingStateBlock + ) -> ::HRESULT, + fn CreateWicBitmapRenderTarget( + &mut self, target: *mut ::IWICBitmap, + renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + renderTarget: *mut *mut ID2D1RenderTarget + ) -> ::HRESULT, + fn CreateHwndRenderTarget( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + hwndRenderTargetProperties: *const D2D1_HWND_RENDER_TARGET_PROPERTIES, + hwndRenderTarget: *mut *mut ID2D1HwndRenderTarget + ) -> ::HRESULT, + fn CreateDxgiSurfaceRenderTarget( + &mut self, dxgiSurface: *mut ::IDXGISurface, + renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + renderTarget: *mut *mut ID2D1RenderTarget + ) -> ::HRESULT, + fn CreateDCRenderTarget( + &mut self, renderTargetProperties: *const D2D1_RENDER_TARGET_PROPERTIES, + dcRenderTarget: *mut *mut ID2D1DCRenderTarget + ) -> ::HRESULT +}); +DEFINE_GUID!( + UuidOfID2D1Factory, + 0x06152247, 0x6f50, 0x465a, 0x92, 0x45, 0x11, 0x8b, 0xfd, 0x3b, 0x60, 0x07 +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d2dbasetypes.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d2dbasetypes.rs new file mode 100644 index 0000000..45a5a14 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d2dbasetypes.rs @@ -0,0 +1,61 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of d2dbasetypes.h +STRUCT!{struct D2D_POINT_2U { + x: ::UINT32, + y: ::UINT32, +}} +STRUCT!{struct D2D_POINT_2F { + x: ::FLOAT, + y: ::FLOAT, +}} +pub type D2D_POINT_2L = ::POINT; +STRUCT!{struct D2D_VECTOR_2F { + x: ::FLOAT, + y: ::FLOAT, +}} +STRUCT!{struct D2D_VECTOR_3F { + x: ::FLOAT, + y: ::FLOAT, + z: ::FLOAT, +}} +STRUCT!{struct D2D_VECTOR_4F { + x: ::FLOAT, + y: ::FLOAT, + z: ::FLOAT, + w: ::FLOAT, +}} +STRUCT!{struct D2D_RECT_F { + left: ::FLOAT, + top: ::FLOAT, + right: ::FLOAT, + bottom: ::FLOAT, +}} +STRUCT!{struct D2D_RECT_U { + left: ::UINT32, + top: ::UINT32, + right: ::UINT32, + bottom: ::UINT32, +}} +pub type D2D_RECT_L = ::RECT; +STRUCT!{struct D2D_SIZE_F { + width: ::FLOAT, + height: ::FLOAT, +}} +STRUCT!{struct D2D_SIZE_U { + width: ::UINT32, + height: ::UINT32, +}} +pub type D2D_COLOR_F = ::D3DCOLORVALUE; +STRUCT!{struct D2D_MATRIX_3X2_F { + matrix: [[::FLOAT; 2]; 3], +}} +STRUCT!{struct D2D_MATRIX_4X3_F { + matrix: [[::FLOAT; 3]; 4], +}} +STRUCT!{struct D2D_MATRIX_4X4_F { + matrix: [[::FLOAT; 4]; 4], +}} +STRUCT!{struct D2D_MATRIX_5X4_F { + matrix: [[::FLOAT; 4]; 5], +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d10shader.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d10shader.rs new file mode 100644 index 0000000..4f64c5f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d10shader.rs @@ -0,0 +1,110 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub type D3D10_RESOURCE_RETURN_TYPE = D3D_RESOURCE_RETURN_TYPE; +pub type D3D10_CBUFFER_TYPE = D3D_CBUFFER_TYPE; +STRUCT!{struct D3D10_SHADER_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InputParameters: UINT, + OutputParameters: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + CutInstructionCount: UINT, + EmitInstructionCount: UINT, + GSOutputTopology: D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: UINT, +}} +STRUCT!{struct D3D10_SHADER_BUFFER_DESC { + Name: LPCSTR, + Type: D3D10_CBUFFER_TYPE, + Variables: UINT, + Size: UINT, + uFlags: UINT, +}} +STRUCT!{struct D3D10_SHADER_VARIABLE_DESC { + Name: LPCSTR, + StartOffset: UINT, + Size: UINT, + uFlags: UINT, + DefaultValue: LPVOID, +}} +STRUCT!{struct D3D10_SHADER_TYPE_DESC { + Class: D3D_SHADER_VARIABLE_CLASS, + Type: D3D_SHADER_VARIABLE_TYPE, + Rows: UINT, + Columns: UINT, + Elements: UINT, + Members: UINT, + Offset: UINT, +}} +STRUCT!{struct D3D10_SHADER_INPUT_BIND_DESC { + Name: LPCSTR, + Type: D3D_SHADER_INPUT_TYPE, + BindPoint: UINT, + BindCount: UINT, + uFlags: UINT, + ReturnType: D3D_RESOURCE_RETURN_TYPE, + Dimension: D3D_SRV_DIMENSION, + NumSamples: UINT, +}} +STRUCT!{struct D3D10_SIGNATURE_PARAMETER_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Register: UINT, + SystemValueType: D3D_NAME, + ComponentType: D3D_REGISTER_COMPONENT_TYPE, + Mask: BYTE, + ReadWriteMask: BYTE, +}} +RIDL!{interface ID3D10ShaderReflectionType(ID3D10ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_TYPE_DESC) -> HRESULT, + fn GetMemberTypeByIndex(&mut self, Index: UINT) -> *mut ID3D10ShaderReflectionType, + fn GetMemberTypeByName(&mut self, Name: LPCSTR) -> *mut ID3D10ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: UINT) -> LPCSTR +}} +RIDL!{interface ID3D10ShaderReflectionVariable(ID3D10ShaderReflectionVariableVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_VARIABLE_DESC) -> HRESULT, + fn GetType(&mut self) -> *mut ID3D10ShaderReflectionType +}} +RIDL!{interface ID3D10ShaderReflectionConstantBuffer(ID3D10ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_BUFFER_DESC) -> HRESULT, + fn GetVariableByIndex(&mut self, Index: UINT) -> *mut ID3D10ShaderReflectionVariable, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D10ShaderReflectionVariable +}} +RIDL!{interface ID3D10ShaderReflection(ID3D10ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D10_SHADER_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: UINT + ) -> *mut ID3D10ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D10ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D10_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D10_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D10_SIGNATURE_PARAMETER_DESC + ) -> HRESULT +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d11.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d11.rs new file mode 100644 index 0000000..4fed70c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d11.rs @@ -0,0 +1,2665 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +use super::*; +pub const D3D11_16BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xffff; +pub const D3D11_32BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xffffffff; +pub const D3D11_8BIT_INDEX_STRIP_CUT_VALUE: DWORD = 0xff; +pub const D3D11_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT: DWORD = 9; +pub const D3D11_CLIP_OR_CULL_DISTANCE_COUNT: DWORD = 8; +pub const D3D11_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT: DWORD = 2; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT: DWORD = 14; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT: DWORD = 15; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT: DWORD = 16; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT: DWORD = 15; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT: DWORD = 64; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT: DWORD = 128; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT: DWORD = 128; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_COUNT: DWORD = 16; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT: DWORD = 16; +pub const D3D11_COMMONSHADER_SUBROUTINE_NESTING_LIMIT: DWORD = 32; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_COUNT: DWORD = 4096; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_READS_PER_INST: DWORD = 3; +pub const D3D11_COMMONSHADER_TEMP_REGISTER_READ_PORTS: DWORD = 3; +pub const D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX: DWORD = 10; +pub const D3D11_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN: c_long = -10; +pub const D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE: c_long = -8; +pub const D3D11_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE: DWORD = 7; +pub const D3D11_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 256; +pub const D3D11_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP: DWORD = 64; +pub const D3D11_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 240; +pub const D3D11_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP: DWORD = 68; +pub const D3D11_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 224; +pub const D3D11_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP: DWORD = 72; +pub const D3D11_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 208; +pub const D3D11_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP: DWORD = 76; +pub const D3D11_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 192; +pub const D3D11_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP: DWORD = 84; +pub const D3D11_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 176; +pub const D3D11_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP: DWORD = 92; +pub const D3D11_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 160; +pub const D3D11_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP: DWORD = 100; +pub const D3D11_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 144; +pub const D3D11_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP: DWORD = 112; +pub const D3D11_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 128; +pub const D3D11_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP: DWORD = 128; +pub const D3D11_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 112; +pub const D3D11_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP: DWORD = 144; +pub const D3D11_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 96; +pub const D3D11_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP: DWORD = 168; +pub const D3D11_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 80; +pub const D3D11_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP: DWORD = 204; +pub const D3D11_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 64; +pub const D3D11_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP: DWORD = 256; +pub const D3D11_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 48; +pub const D3D11_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP: DWORD = 340; +pub const D3D11_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 32; +pub const D3D11_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP: DWORD = 512; +pub const D3D11_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: DWORD = 16; +pub const D3D11_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP: DWORD = 768; +pub const D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION: DWORD = 1; +pub const D3D11_CS_4_X_RAW_UAV_BYTE_ALIGNMENT: DWORD = 256; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP: DWORD = 768; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_X: DWORD = 768; +pub const D3D11_CS_4_X_THREAD_GROUP_MAX_Y: DWORD = 768; +pub const D3D11_CS_4_X_UAV_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION: DWORD = 65535; +pub const D3D11_CS_TGSM_REGISTER_COUNT: DWORD = 8192; +pub const D3D11_CS_TGSM_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_CS_TGSM_RESOURCE_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_CS_TGSM_RESOURCE_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_CS_THREADGROUPID_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADGROUPID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADIDINGROUP_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADIDINGROUP_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREADID_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_CS_THREADID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_X: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_Y: DWORD = 1024; +pub const D3D11_CS_THREAD_GROUP_MAX_Z: DWORD = 64; +pub const D3D11_CS_THREAD_GROUP_MIN_X: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MIN_Y: DWORD = 1; +pub const D3D11_CS_THREAD_GROUP_MIN_Z: DWORD = 1; +pub const D3D11_CS_THREAD_LOCAL_TEMP_REGISTER_POOL: DWORD = 16384; +pub const D3D11_DEFAULT_BLEND_FACTOR_ALPHA: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_BLUE: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_GREEN: FLOAT = 1.0; +pub const D3D11_DEFAULT_BLEND_FACTOR_RED: FLOAT = 1.0; +pub const D3D11_DEFAULT_BORDER_COLOR_COMPONENT: FLOAT = 0.0; +pub const D3D11_DEFAULT_DEPTH_BIAS: DWORD = 0; +pub const D3D11_DEFAULT_DEPTH_BIAS_CLAMP: FLOAT = 0.0; +pub const D3D11_DEFAULT_MAX_ANISOTROPY: DWORD = 16; +pub const D3D11_DEFAULT_MIP_LOD_BIAS: FLOAT = 0.0; +pub const D3D11_DEFAULT_RENDER_TARGET_ARRAY_INDEX: DWORD = 0; +pub const D3D11_DEFAULT_SAMPLE_MASK: DWORD = 0xffffffff; +pub const D3D11_DEFAULT_SCISSOR_ENDX: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_ENDY: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_STARTX: DWORD = 0; +pub const D3D11_DEFAULT_SCISSOR_STARTY: DWORD = 0; +pub const D3D11_DEFAULT_SLOPE_SCALED_DEPTH_BIAS: FLOAT = 0.0; +pub const D3D11_DEFAULT_STENCIL_READ_MASK: DWORD = 0xff; +pub const D3D11_DEFAULT_STENCIL_REFERENCE: DWORD = 0; +pub const D3D11_DEFAULT_STENCIL_WRITE_MASK: DWORD = 0xff; +pub const D3D11_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_HEIGHT: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_MAX_DEPTH: FLOAT = 0.0; +pub const D3D11_DEFAULT_VIEWPORT_MIN_DEPTH: FLOAT = 0.0; +pub const D3D11_DEFAULT_VIEWPORT_TOPLEFTX: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_TOPLEFTY: DWORD = 0; +pub const D3D11_DEFAULT_VIEWPORT_WIDTH: DWORD = 0; +pub const D3D11_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: DWORD = 3968; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS: DWORD = 3; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT: DWORD = 1; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_DS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_DS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_FLOAT16_FUSED_TOLERANCE_IN_ULP: FLOAT = 0.6; +pub const D3D11_FLOAT32_MAX: FLOAT = 3.402823466E+38; +pub const D3D11_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP: FLOAT = 0.6; +pub const D3D11_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR: FLOAT = 2.4; +pub const D3D11_FLOAT_TO_SRGB_EXPONENT_NUMERATOR: FLOAT = 1.0; +pub const D3D11_FLOAT_TO_SRGB_OFFSET: FLOAT = 0.055; +pub const D3D11_FLOAT_TO_SRGB_SCALE_1: FLOAT = 12.92; +pub const D3D11_FLOAT_TO_SRGB_SCALE_2: FLOAT = 1.055; +pub const D3D11_FLOAT_TO_SRGB_THRESHOLD: FLOAT = 0.0031308; +pub const D3D11_FTOI_INSTRUCTION_MAX_INPUT: FLOAT = 2147483647.999; +pub const D3D11_FTOI_INSTRUCTION_MIN_INPUT: FLOAT = -2147483648.999; +pub const D3D11_FTOU_INSTRUCTION_MAX_INPUT: FLOAT = 4294967295.999; +pub const D3D11_FTOU_INSTRUCTION_MIN_INPUT: FLOAT = 0.0; +pub const D3D11_GS_INPUT_INSTANCE_ID_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_INSTANCE_ID_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_COUNT: DWORD = 1; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_GS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_GS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_GS_INPUT_REGISTER_VERTICES: DWORD = 32; +pub const D3D11_GS_MAX_INSTANCE_COUNT: DWORD = 32; +pub const D3D11_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES: DWORD = 1024; +pub const D3D11_GS_OUTPUT_ELEMENTS: DWORD = 32; +pub const D3D11_GS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_GS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_CONTROL_POINT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_CONTROL_POINT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND: DWORD = 0xffffffff; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND: DWORD = 0xffffffff; +pub const D3D11_HS_MAXTESSFACTOR_LOWER_BOUND: FLOAT = 1.0; +pub const D3D11_HS_MAXTESSFACTOR_UPPER_BOUND: FLOAT = 64.0; +pub const D3D11_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: DWORD = 3968; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT: DWORD = 1; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS: DWORD = 128; +pub const D3D11_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: DWORD = 0; +pub const D3D11_IA_DEFAULT_PRIMITIVE_TOPOLOGY: DWORD = 0; +pub const D3D11_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: DWORD = 0; +pub const D3D11_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: DWORD = 1; +pub const D3D11_IA_INSTANCE_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_INTEGER_ARITHMETIC_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_PATCH_MAX_CONTROL_POINT_COUNT: DWORD = 32; +pub const D3D11_IA_PRIMITIVE_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_ID_BIT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: DWORD = 32; +pub const D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS: DWORD = 128; +pub const D3D11_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_INTEGER_DIVIDE_BY_ZERO_QUOTIENT: DWORD = 0xffffffff; +pub const D3D11_INTEGER_DIVIDE_BY_ZERO_REMAINDER: DWORD = 0xffffffff; +pub const D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL: DWORD = 0xffffffff; +pub const D3D11_KEEP_UNORDERED_ACCESS_VIEWS: DWORD = 0xffffffff; +pub const D3D11_LINEAR_GAMMA: FLOAT = 1.0; +pub const D3D11_MAJOR_VERSION: DWORD = 11; +pub const D3D11_MAX_BORDER_COLOR_COMPONENT: FLOAT = 1.0; +pub const D3D11_MAX_DEPTH: FLOAT = 1.0; +pub const D3D11_MAX_MAXANISOTROPY: DWORD = 16; +pub const D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT: DWORD = 32; +pub const D3D11_MAX_POSITION_VALUE: FLOAT = 3.402823466E+34; +pub const D3D11_MAX_TEXTURE_DIMENSION_2_TO_EXP: DWORD = 17; +pub const D3D11_MINOR_VERSION: DWORD = 0; +pub const D3D11_MIN_BORDER_COLOR_COMPONENT: FLOAT = 0.0; +pub const D3D11_MIN_DEPTH: FLOAT = 0.0; +pub const D3D11_MIN_MAXANISOTROPY: DWORD = 0; +pub const D3D11_MIP_LOD_BIAS_MAX: FLOAT = 15.99; +pub const D3D11_MIP_LOD_BIAS_MIN: FLOAT = -16.0; +pub const D3D11_MIP_LOD_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_MIP_LOD_RANGE_BIT_COUNT: DWORD = 8; +pub const D3D11_MULTISAMPLE_ANTIALIAS_LINE_WIDTH: FLOAT = 1.4; +pub const D3D11_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT: DWORD = 0; +pub const D3D11_PIXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 15; +pub const D3D11_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 16; +pub const D3D11_PS_CS_UAV_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_CS_UAV_REGISTER_COUNT: DWORD = 8; +pub const D3D11_PS_CS_UAV_REGISTER_READS_PER_INST: DWORD = 1; +pub const D3D11_PS_CS_UAV_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_PS_FRONTFACING_DEFAULT_VALUE: DWORD = 0xffffffff; +pub const D3D11_PS_FRONTFACING_FALSE_VALUE: DWORD = 0; +pub const D3D11_PS_FRONTFACING_TRUE_VALUE: DWORD = 0xffffffff; +pub const D3D11_PS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_PS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_PS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.0; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_DEPTH_REGISTER_COUNT: DWORD = 1; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENTS: DWORD = 1; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_MASK_REGISTER_COUNT: DWORD = 1; +pub const D3D11_PS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_PS_OUTPUT_REGISTER_COUNT: DWORD = 8; +pub const D3D11_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT: FLOAT = 0.5; +pub const D3D11_RAW_UAV_SRV_BYTE_ALIGNMENT: DWORD = 16; +pub const D3D11_REQ_BLEND_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP: DWORD = 27; +pub const D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT: DWORD = 4096; +pub const D3D11_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: DWORD = 32; +pub const D3D11_REQ_DRAW_VERTEX_COUNT_2_TO_EXP: DWORD = 32; +pub const D3D11_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT: DWORD = 1024; +pub const D3D11_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT: DWORD = 4096; +pub const D3D11_REQ_MAXANISOTROPY: DWORD = 16; +pub const D3D11_REQ_MIP_LEVELS: DWORD = 15; +pub const D3D11_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES: DWORD = 2048; +pub const D3D11_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH: DWORD = 16384; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM: DWORD = 128; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM: FLOAT = 0.25; +pub const D3D11_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM: DWORD = 2048; +pub const D3D11_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP: DWORD = 20; +pub const D3D11_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE: DWORD = 4096; +pub const D3D11_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURE1D_U_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION: DWORD = 16384; +pub const D3D11_REQ_TEXTURE3D_U_V_OR_W_DIMENSION: DWORD = 2048; +pub const D3D11_REQ_TEXTURECUBE_DIMENSION: DWORD = 16384; +pub const D3D11_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL: DWORD = 0; +pub const D3D11_SHADER_MAJOR_VERSION: DWORD = 5; +pub const D3D11_SHADER_MAX_INSTANCES: DWORD = 65535; +pub const D3D11_SHADER_MAX_INTERFACES: DWORD = 253; +pub const D3D11_SHADER_MAX_INTERFACE_CALL_SITES: DWORD = 4096; +pub const D3D11_SHADER_MAX_TYPES: DWORD = 65535; +pub const D3D11_SHADER_MINOR_VERSION: DWORD = 0; +pub const D3D11_SHIFT_INSTRUCTION_PAD_VALUE: DWORD = 0; +pub const D3D11_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT: DWORD = 5; +pub const D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT: DWORD = 8; +pub const D3D11_SO_BUFFER_MAX_STRIDE_IN_BYTES: DWORD = 2048; +pub const D3D11_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES: DWORD = 512; +pub const D3D11_SO_BUFFER_SLOT_COUNT: DWORD = 4; +pub const D3D11_SO_DDI_REGISTER_INDEX_DENOTING_GAP: DWORD = 0xffffffff; +pub const D3D11_SO_NO_RASTERIZED_STREAM: DWORD = 0xffffffff; +pub const D3D11_SO_OUTPUT_COMPONENT_COUNT: DWORD = 128; +pub const D3D11_SO_STREAM_COUNT: DWORD = 4; +pub const D3D11_SPEC_DATE_DAY: DWORD = 16; +pub const D3D11_SPEC_DATE_MONTH: DWORD = 05; +pub const D3D11_SPEC_DATE_YEAR: DWORD = 2011; +pub const D3D11_SPEC_VERSION: FLOAT = 1.07; +pub const D3D11_SRGB_GAMMA: FLOAT = 2.2; +pub const D3D11_SRGB_TO_FLOAT_DENOMINATOR_1: FLOAT = 12.92; +pub const D3D11_SRGB_TO_FLOAT_DENOMINATOR_2: FLOAT = 1.055; +pub const D3D11_SRGB_TO_FLOAT_EXPONENT: FLOAT = 2.4; +pub const D3D11_SRGB_TO_FLOAT_OFFSET: FLOAT = 0.055; +pub const D3D11_SRGB_TO_FLOAT_THRESHOLD: FLOAT = 0.04045; +pub const D3D11_SRGB_TO_FLOAT_TOLERANCE_IN_ULP: FLOAT = 0.5; +pub const D3D11_STANDARD_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_COMPONENT_BIT_COUNT_DOUBLED: DWORD = 64; +pub const D3D11_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE: DWORD = 4; +pub const D3D11_STANDARD_PIXEL_COMPONENT_COUNT: DWORD = 128; +pub const D3D11_STANDARD_PIXEL_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_VECTOR_SIZE: DWORD = 4; +pub const D3D11_STANDARD_VERTEX_ELEMENT_COUNT: DWORD = 32; +pub const D3D11_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT: DWORD = 64; +pub const D3D11_SUBPIXEL_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_SUBTEXEL_FRACTIONAL_BIT_COUNT: DWORD = 8; +pub const D3D11_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR: DWORD = 63; +pub const D3D11_TESSELLATOR_MAX_TESSELLATION_FACTOR: DWORD = 64; +pub const D3D11_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR: DWORD = 2; +pub const D3D11_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR: DWORD = 1; +pub const D3D11_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR: DWORD = 1; +pub const D3D11_TEXEL_ADDRESS_RANGE_BIT_COUNT: DWORD = 16; +pub const D3D11_UNBOUND_MEMORY_ACCESS_RESULT: DWORD = 0; +pub const D3D11_VIEWPORT_AND_SCISSORRECT_MAX_INDEX: DWORD = 15; +pub const D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE: DWORD = 16; +pub const D3D11_VIEWPORT_BOUNDS_MAX: DWORD = 32767; +pub const D3D11_VIEWPORT_BOUNDS_MIN: c_long = -32768; +pub const D3D11_VS_INPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_VS_INPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_VS_INPUT_REGISTER_READS_PER_INST: DWORD = 2; +pub const D3D11_VS_INPUT_REGISTER_READ_PORTS: DWORD = 1; +pub const D3D11_VS_OUTPUT_REGISTER_COMPONENTS: DWORD = 4; +pub const D3D11_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: DWORD = 32; +pub const D3D11_VS_OUTPUT_REGISTER_COUNT: DWORD = 32; +pub const D3D11_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT: DWORD = 10; +pub const D3D11_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: DWORD = 25; +pub const D3D11_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP: DWORD = 25; +pub const D3D11_1_UAV_SLOT_COUNT: DWORD = 64; +pub const D3D11_2_TILED_RESOURCE_TILE_SIZE_IN_BYTES: DWORD = 65536; +ENUM!{enum D3D11_INPUT_CLASSIFICATION { + D3D11_INPUT_PER_VERTEX_DATA = 0, + D3D11_INPUT_PER_INSTANCE_DATA = 1, +}} +pub const D3D11_APPEND_ALIGNED_ELEMENT: DWORD = 0xffffffff; +STRUCT!{struct D3D11_INPUT_ELEMENT_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Format: DXGI_FORMAT, + InputSlot: UINT, + AlignedByteOffset: UINT, + InputSlotClass: D3D11_INPUT_CLASSIFICATION, + InstanceDataStepRate: UINT, +}} +ENUM!{enum D3D11_FILL_MODE { + D3D11_FILL_WIREFRAME = 2, + D3D11_FILL_SOLID = 3, +}} +pub type D3D11_PRIMITIVE_TOPOLOGY = D3D_PRIMITIVE_TOPOLOGY; +pub type D3D11_PRIMITIVE = D3D_PRIMITIVE; +ENUM!{enum D3D11_CULL_MODE { + D3D11_CULL_NONE = 1, + D3D11_CULL_FRONT = 2, + D3D11_CULL_BACK = 3, +}} +STRUCT!{struct D3D11_SO_DECLARATION_ENTRY { + Stream: UINT, + SemanticName: LPCSTR, + SemanticIndex: UINT, + StartComponent: BYTE, + ComponentCount: BYTE, + OutputSlot: BYTE, +}} +STRUCT!{struct D3D11_VIEWPORT { + TopLeftX: FLOAT, + TopLeftY: FLOAT, + Width: FLOAT, + Height: FLOAT, + MinDepth: FLOAT, + MaxDepth: FLOAT, +}} +STRUCT!{struct D3D11_DRAW_INSTANCED_INDIRECT_ARGS { + VertexCountPerInstance: UINT, + InstanceCount: UINT, + StartVertexLocation: UINT, + StartInstanceLocation: UINT, +}} +STRUCT!{struct D3D11_DRAW_INDEXED_INSTANCED_INDIRECT_ARGS { + IndexCountPerInstance: UINT, + InstanceCount: UINT, + StartIndexLocation: UINT, + BaseVertexLocation: INT, + StartInstanceLocation: UINT, +}} +ENUM!{enum D3D11_RESOURCE_DIMENSION { + D3D11_RESOURCE_DIMENSION_UNKNOWN = 0, + D3D11_RESOURCE_DIMENSION_BUFFER = 1, + D3D11_RESOURCE_DIMENSION_TEXTURE1D = 2, + D3D11_RESOURCE_DIMENSION_TEXTURE2D = 3, + D3D11_RESOURCE_DIMENSION_TEXTURE3D = 4, +}} +pub type D3D11_SRV_DIMENSION = D3D_SRV_DIMENSION; +ENUM!{enum D3D11_DSV_DIMENSION { + D3D11_DSV_DIMENSION_UNKNOWN = 0, + D3D11_DSV_DIMENSION_TEXTURE1D = 1, + D3D11_DSV_DIMENSION_TEXTURE1DARRAY = 2, + D3D11_DSV_DIMENSION_TEXTURE2D = 3, + D3D11_DSV_DIMENSION_TEXTURE2DARRAY = 4, + D3D11_DSV_DIMENSION_TEXTURE2DMS = 5, + D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY = 6, +}} +ENUM!{enum D3D11_RTV_DIMENSION { + D3D11_RTV_DIMENSION_UNKNOWN = 0, + D3D11_RTV_DIMENSION_BUFFER = 1, + D3D11_RTV_DIMENSION_TEXTURE1D = 2, + D3D11_RTV_DIMENSION_TEXTURE1DARRAY = 3, + D3D11_RTV_DIMENSION_TEXTURE2D = 4, + D3D11_RTV_DIMENSION_TEXTURE2DARRAY = 5, + D3D11_RTV_DIMENSION_TEXTURE2DMS = 6, + D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D11_RTV_DIMENSION_TEXTURE3D = 8, +}} +ENUM!{enum D3D11_UAV_DIMENSION { + D3D11_UAV_DIMENSION_UNKNOWN = 0, + D3D11_UAV_DIMENSION_BUFFER = 1, + D3D11_UAV_DIMENSION_TEXTURE1D = 2, + D3D11_UAV_DIMENSION_TEXTURE1DARRAY = 3, + D3D11_UAV_DIMENSION_TEXTURE2D = 4, + D3D11_UAV_DIMENSION_TEXTURE2DARRAY = 5, + D3D11_UAV_DIMENSION_TEXTURE3D = 8, +}} +ENUM!{enum D3D11_USAGE { + D3D11_USAGE_DEFAULT = 0, + D3D11_USAGE_IMMUTABLE = 1, + D3D11_USAGE_DYNAMIC = 2, + D3D11_USAGE_STAGING = 3, +}} +FLAGS!{enum D3D11_BIND_FLAG { + D3D11_BIND_VERTEX_BUFFER = 0x1, + D3D11_BIND_INDEX_BUFFER = 0x2, + D3D11_BIND_CONSTANT_BUFFER = 0x4, + D3D11_BIND_SHADER_RESOURCE = 0x8, + D3D11_BIND_STREAM_OUTPUT = 0x10, + D3D11_BIND_RENDER_TARGET = 0x20, + D3D11_BIND_DEPTH_STENCIL = 0x40, + D3D11_BIND_UNORDERED_ACCESS = 0x80, + D3D11_BIND_DECODER = 0x200, + D3D11_BIND_VIDEO_ENCODER = 0x400, +}} +FLAGS!{enum D3D11_CPU_ACCESS_FLAG { + D3D11_CPU_ACCESS_WRITE = 0x10000, + D3D11_CPU_ACCESS_READ = 0x20000, +}} +FLAGS!{enum D3D11_RESOURCE_MISC_FLAG { + D3D11_RESOURCE_MISC_GENERATE_MIPS = 0x1, + D3D11_RESOURCE_MISC_SHARED = 0x2, + D3D11_RESOURCE_MISC_TEXTURECUBE = 0x4, + D3D11_RESOURCE_MISC_DRAWINDIRECT_ARGS = 0x10, + D3D11_RESOURCE_MISC_BUFFER_ALLOW_RAW_VIEWS = 0x20, + D3D11_RESOURCE_MISC_BUFFER_STRUCTURED = 0x40, + D3D11_RESOURCE_MISC_RESOURCE_CLAMP = 0x80, + D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX = 0x100, + D3D11_RESOURCE_MISC_GDI_COMPATIBLE = 0x200, + D3D11_RESOURCE_MISC_SHARED_NTHANDLE = 0x800, + D3D11_RESOURCE_MISC_RESTRICTED_CONTENT = 0x1000, + D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE = 0x2000, + D3D11_RESOURCE_MISC_RESTRICT_SHARED_RESOURCE_DRIVER = 0x4000, + D3D11_RESOURCE_MISC_GUARDED = 0x8000, + D3D11_RESOURCE_MISC_TILE_POOL = 0x20000, + D3D11_RESOURCE_MISC_TILED = 0x40000, + D3D11_RESOURCE_MISC_HW_PROTECTED = 0x80000, +}} +ENUM!{enum D3D11_MAP { + D3D11_MAP_READ = 1, + D3D11_MAP_WRITE = 2, + D3D11_MAP_READ_WRITE = 3, + D3D11_MAP_WRITE_DISCARD = 4, + D3D11_MAP_WRITE_NO_OVERWRITE = 5, +}} +FLAGS!{enum D3D11_MAP_FLAG { + D3D11_MAP_FLAG_DO_NOT_WAIT = 0x100000, +}} +FLAGS!{enum D3D11_RAISE_FLAG { + D3D11_RAISE_FLAG_DRIVER_INTERNAL_ERROR = 0x1, +}} +FLAGS!{enum D3D11_CLEAR_FLAG { + D3D11_CLEAR_DEPTH = 0x1, + D3D11_CLEAR_STENCIL = 0x2, +}} +pub type D3D11_RECT = RECT; +STRUCT!{struct D3D11_BOX { + left: UINT, + top: UINT, + front: UINT, + right: UINT, + bottom: UINT, + back: UINT, +}} +RIDL!{interface ID3D11DeviceChild(ID3D11DeviceChildVtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut ID3D11Device) -> (), + fn GetPrivateData( + &mut self, guid: REFGUID, pDataSize: *mut UINT, pData: *mut c_void + ) -> HRESULT, + fn SetPrivateData( + &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void + ) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT +}} +ENUM!{enum D3D11_COMPARISON_FUNC { + D3D11_COMPARISON_NEVER = 1, + D3D11_COMPARISON_LESS = 2, + D3D11_COMPARISON_EQUAL = 3, + D3D11_COMPARISON_LESS_EQUAL = 4, + D3D11_COMPARISON_GREATER = 5, + D3D11_COMPARISON_NOT_EQUAL = 6, + D3D11_COMPARISON_GREATER_EQUAL = 7, + D3D11_COMPARISON_ALWAYS = 8, +}} +ENUM!{enum D3D11_DEPTH_WRITE_MASK { + D3D11_DEPTH_WRITE_MASK_ZERO = 0, + D3D11_DEPTH_WRITE_MASK_ALL = 1, +}} +ENUM!{enum D3D11_STENCIL_OP { + D3D11_STENCIL_OP_KEEP = 1, + D3D11_STENCIL_OP_ZERO = 2, + D3D11_STENCIL_OP_REPLACE = 3, + D3D11_STENCIL_OP_INCR_SAT = 4, + D3D11_STENCIL_OP_DECR_SAT = 5, + D3D11_STENCIL_OP_INVERT = 6, + D3D11_STENCIL_OP_INCR = 7, + D3D11_STENCIL_OP_DECR = 8, +}} +STRUCT!{struct D3D11_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D11_STENCIL_OP, + StencilDepthFailOp: D3D11_STENCIL_OP, + StencilPassOp: D3D11_STENCIL_OP, + StencilFunc: D3D11_COMPARISON_FUNC, +}} +STRUCT!{struct D3D11_DEPTH_STENCIL_DESC { + DepthEnable: BOOL, + DepthWriteMask: D3D11_DEPTH_WRITE_MASK, + DepthFunc: D3D11_COMPARISON_FUNC, + StencilEnable: BOOL, + StencilReadMask: UINT8, + StencilWriteMask: UINT8, + FrontFace: D3D11_DEPTH_STENCILOP_DESC, + BackFace: D3D11_DEPTH_STENCILOP_DESC, +}} +RIDL!{interface ID3D11DepthStencilState(ID3D11DepthStencilStateVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_DEPTH_STENCIL_DESC) -> () +}} +ENUM!{enum D3D11_BLEND { + D3D11_BLEND_ZERO = 1, + D3D11_BLEND_ONE = 2, + D3D11_BLEND_SRC_COLOR = 3, + D3D11_BLEND_INV_SRC_COLOR = 4, + D3D11_BLEND_SRC_ALPHA = 5, + D3D11_BLEND_INV_SRC_ALPHA = 6, + D3D11_BLEND_DEST_ALPHA = 7, + D3D11_BLEND_INV_DEST_ALPHA = 8, + D3D11_BLEND_DEST_COLOR = 9, + D3D11_BLEND_INV_DEST_COLOR = 10, + D3D11_BLEND_SRC_ALPHA_SAT = 11, + D3D11_BLEND_BLEND_FACTOR = 14, + D3D11_BLEND_INV_BLEND_FACTOR = 15, + D3D11_BLEND_SRC1_COLOR = 16, + D3D11_BLEND_INV_SRC1_COLOR = 17, + D3D11_BLEND_SRC1_ALPHA = 18, + D3D11_BLEND_INV_SRC1_ALPHA = 19, +}} +ENUM!{enum D3D11_BLEND_OP { + D3D11_BLEND_OP_ADD = 1, + D3D11_BLEND_OP_SUBTRACT = 2, + D3D11_BLEND_OP_REV_SUBTRACT = 3, + D3D11_BLEND_OP_MIN = 4, + D3D11_BLEND_OP_MAX = 5, +}} +FLAGS!{enum D3D11_COLOR_WRITE_ENABLE { + D3D11_COLOR_WRITE_ENABLE_RED = 1, + D3D11_COLOR_WRITE_ENABLE_GREEN = 2, + D3D11_COLOR_WRITE_ENABLE_BLUE = 4, + D3D11_COLOR_WRITE_ENABLE_ALPHA = 8, + D3D11_COLOR_WRITE_ENABLE_ALL = D3D11_COLOR_WRITE_ENABLE_RED.0 | D3D11_COLOR_WRITE_ENABLE_GREEN.0 | + D3D11_COLOR_WRITE_ENABLE_BLUE.0 | D3D11_COLOR_WRITE_ENABLE_ALPHA.0, +}} +STRUCT!{struct D3D11_RENDER_TARGET_BLEND_DESC { + BlendEnable: BOOL, + SrcBlend: D3D11_BLEND, + DestBlend: D3D11_BLEND, + BlendOp: D3D11_BLEND_OP, + SrcBlendAlpha: D3D11_BLEND, + DestBlendAlpha: D3D11_BLEND, + BlendOpAlpha: D3D11_BLEND_OP, + RenderTargetWriteMask: UINT8, +}} +STRUCT!{struct D3D11_BLEND_DESC { + AlphaToCoverageEnable: BOOL, + IndependentBlendEnable: BOOL, + RenderTarget: [D3D11_RENDER_TARGET_BLEND_DESC; 8], +}} +RIDL!{interface ID3D11BlendState(ID3D11BlendStateVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_BLEND_DESC) -> () +}} +STRUCT!{struct D3D11_RASTERIZER_DESC { + FillMode: D3D11_FILL_MODE, + CullMode: D3D11_CULL_MODE, + FrontCounterClockwise: BOOL, + DepthBias: INT, + DepthBiasClamp: FLOAT, + SlopeScaledDepthBias: FLOAT, + DepthClipEnable: BOOL, + ScissorEnable: BOOL, + MultisampleEnable: BOOL, + AntialiasedLineEnable: BOOL, +}} +RIDL!{interface ID3D11RasterizerState(ID3D11RasterizerStateVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_RASTERIZER_DESC) -> () +}} +STRUCT!{struct D3D11_SUBRESOURCE_DATA { + pSysMem: *const c_void, + SysMemPitch: UINT, + SysMemSlicePitch: UINT, +}} +STRUCT!{struct D3D11_MAPPED_SUBRESOURCE { + pData: *mut c_void, + RowPitch: UINT, + DepthPitch: UINT, +}} +RIDL!{interface ID3D11Resource(ID3D11ResourceVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetType(&mut self, pResourceDimension: *mut D3D11_RESOURCE_DIMENSION) -> (), + fn SetEvictionPriority(&mut self, EvictionPriority: UINT) -> (), + fn GetEvictionPriority(&mut self) -> UINT +}} +STRUCT!{struct D3D11_BUFFER_DESC { + ByteWidth: UINT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, + StructureByteStride: UINT, +}} +RIDL!{interface ID3D11Buffer(ID3D11BufferVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_BUFFER_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE1D_DESC { + Width: UINT, + MipLevels: UINT, + ArraySize: UINT, + Format: DXGI_FORMAT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture1D(ID3D11Texture1DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE1D_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE2D_DESC { + Width: UINT, + Height: UINT, + MipLevels: UINT, + ArraySize: UINT, + Format: DXGI_FORMAT, + SampleDesc: DXGI_SAMPLE_DESC, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture2D(ID3D11Texture2DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE2D_DESC) -> () +}} +STRUCT!{struct D3D11_TEXTURE3D_DESC { + Width: UINT, + Height: UINT, + Depth: UINT, + MipLevels: UINT, + Format: DXGI_FORMAT, + Usage: D3D11_USAGE, + BindFlags: UINT, + CPUAccessFlags: UINT, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Texture3D(ID3D11Texture3DVtbl): ID3D11Resource(ID3D11ResourceVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_TEXTURE3D_DESC) -> () +}} +ENUM!{enum D3D11_TEXTURECUBE_FACE { + D3D11_TEXTURECUBE_FACE_POSITIVE_X = 0, + D3D11_TEXTURECUBE_FACE_NEGATIVE_X = 1, + D3D11_TEXTURECUBE_FACE_POSITIVE_Y = 2, + D3D11_TEXTURECUBE_FACE_NEGATIVE_Y = 3, + D3D11_TEXTURECUBE_FACE_POSITIVE_Z = 4, + D3D11_TEXTURECUBE_FACE_NEGATIVE_Z = 5, +}} +RIDL!{interface ID3D11View(ID3D11ViewVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetResource(&mut self, ppResource: *mut *mut ID3D11Resource) -> () +}} +STRUCT!{struct D3D11_BUFFER_SRV { + u1: UINT, + u2: UINT, +}} +UNION!{D3D11_BUFFER_SRV, u1, FirstElement, FirstElement_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u1, ElementOffset, ElementOffset_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u2, NumElements, NumElements_mut, UINT} +UNION!{D3D11_BUFFER_SRV, u2, ElementWidth, ElementWidth_mut, UINT} +FLAGS!{enum D3D11_BUFFEREX_SRV_FLAG { + D3D11_BUFFEREX_SRV_FLAG_RAW = 0x1, +}} +STRUCT!{struct D3D11_BUFFEREX_SRV { + FirstElement: UINT, + NumElements: UINT, + Flags: UINT, +}} +STRUCT!{struct D3D11_TEX1D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEXCUBE_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, +}} +STRUCT!{struct D3D11_TEXCUBE_ARRAY_SRV { + MostDetailedMip: UINT, + MipLevels: UINT, + First2DArrayFace: UINT, + NumCubes: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_SRV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_SRV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_SRV_DIMENSION, + u: [UINT; 4], +}} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, TextureCube, TextureCube_mut, D3D11_TEXCUBE_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, TextureCubeArray, TextureCubeArray_mut, + D3D11_TEXCUBE_ARRAY_SRV} +UNION!{D3D11_SHADER_RESOURCE_VIEW_DESC, u, BufferEx, BufferEx_mut, D3D11_BUFFEREX_SRV} +RIDL!{interface ID3D11ShaderResourceView(ID3D11ShaderResourceViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_RESOURCE_VIEW_DESC) -> () +}} +STRUCT!{struct D3D11_BUFFER_RTV { + u1: UINT, + u2: UINT, +}} +UNION!{D3D11_BUFFER_RTV, u1, FirstElement, FirstElement_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u1, ElementOffset, ElementOffset_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u2, NumElements, NumElements_mut, UINT} +UNION!{D3D11_BUFFER_RTV, u2, ElementWidth, ElementWidth_mut, UINT} +STRUCT!{struct D3D11_TEX1D_RTV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_RTV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_RTV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_RTV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_RTV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_RTV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_RTV { + MipSlice: UINT, + FirstWSlice: UINT, + WSize: UINT, +}} +STRUCT!{struct D3D11_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_RTV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture2DMSArray,Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_RTV} +UNION!{D3D11_RENDER_TARGET_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_RTV} +RIDL!{interface ID3D11RenderTargetView(ID3D11RenderTargetViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_RENDER_TARGET_VIEW_DESC) -> () +}} +STRUCT!{struct D3D11_TEX1D_DSV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_DSV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_DSV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_DSV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_DSV { + UnusedField_NothingToDefine: UINT, +}} +STRUCT!{struct D3D11_TEX2DMS_ARRAY_DSV { + FirstArraySlice: UINT, + ArraySize: UINT, +}} +FLAGS!{enum D3D11_DSV_FLAG{ + D3D11_DSV_READ_ONLY_DEPTH = 0x1, + D3D11_DSV_READ_ONLY_STENCIL = 0x2, +}} +STRUCT!{struct D3D11_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_DSV_DIMENSION, + Flags: UINT, + u: [UINT; 3], +}} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, D3D11_TEX2DMS_DSV} +UNION!{D3D11_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + D3D11_TEX2DMS_ARRAY_DSV} +RIDL!{interface ID3D11DepthStencilView(ID3D11DepthStencilViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_DEPTH_STENCIL_VIEW_DESC) -> () +}} +FLAGS!{enum D3D11_BUFFER_UAV_FLAG { + D3D11_BUFFER_UAV_FLAG_RAW = 0x1, + D3D11_BUFFER_UAV_FLAG_APPEND = 0x2, + D3D11_BUFFER_UAV_FLAG_COUNTER = 0x4, +}} +STRUCT!{struct D3D11_BUFFER_UAV { + FirstElement: UINT, + NumElements: UINT, + Flags: UINT, +}} +STRUCT!{struct D3D11_TEX1D_UAV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX1D_ARRAY_UAV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX2D_UAV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_UAV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_TEX3D_UAV { + MipSlice: UINT, + FirstWSlice: UINT, + WSize: UINT, +}} +STRUCT!{struct D3D11_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT, + ViewDimension: D3D11_UAV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Buffer, Buffer_mut, D3D11_BUFFER_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture1D, Texture1D_mut, D3D11_TEX1D_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + D3D11_TEX1D_ARRAY_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_UAV} +UNION!{D3D11_UNORDERED_ACCESS_VIEW_DESC, u, Texture3D, Texture3D_mut, D3D11_TEX3D_UAV} +RIDL!{interface ID3D11UnorderedAccessView(ID3D11UnorderedAccessViewVtbl): ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_UNORDERED_ACCESS_VIEW_DESC) -> () +}} +RIDL!{interface ID3D11VertexShader(ID3D11VertexShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11HullShader(ID3D11HullShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11DomainShader(ID3D11DomainShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11GeometryShader(ID3D11GeometryShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11PixelShader(ID3D11PixelShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11ComputeShader(ID3D11ComputeShaderVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +RIDL!{interface ID3D11InputLayout(ID3D11InputLayoutVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) {}} +ENUM!{enum D3D11_FILTER { + D3D11_FILTER_MIN_MAG_MIP_POINT = 0, + D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR = 0x1, + D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x4, + D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR = 0x5, + D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT = 0x10, + D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x11, + D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT = 0x14, + D3D11_FILTER_MIN_MAG_MIP_LINEAR = 0x15, + D3D11_FILTER_ANISOTROPIC = 0x55, + D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 0x80, + D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 0x81, + D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x84, + D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 0x85, + D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 0x90, + D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x91, + D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 0x94, + D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 0x95, + D3D11_FILTER_COMPARISON_ANISOTROPIC = 0xd5, + D3D11_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 0x100, + D3D11_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x101, + D3D11_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x104, + D3D11_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x105, + D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x110, + D3D11_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x111, + D3D11_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x114, + D3D11_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 0x115, + D3D11_FILTER_MINIMUM_ANISOTROPIC = 0x155, + D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 0x180, + D3D11_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 0x181, + D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 0x184, + D3D11_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 0x185, + D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 0x190, + D3D11_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 0x191, + D3D11_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 0x194, + D3D11_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 0x195, + D3D11_FILTER_MAXIMUM_ANISOTROPIC = 0x1d5, +}} +ENUM!{enum D3D11_FILTER_TYPE { + D3D11_FILTER_TYPE_POINT = 0, + D3D11_FILTER_TYPE_LINEAR = 1, +}} +ENUM!{enum D3D11_FILTER_REDUCTION_TYPE { + D3D11_FILTER_REDUCTION_TYPE_STANDARD = 0, + D3D11_FILTER_REDUCTION_TYPE_COMPARISON = 1, + D3D11_FILTER_REDUCTION_TYPE_MINIMUM = 2, + D3D11_FILTER_REDUCTION_TYPE_MAXIMUM = 3, +}} +pub const D3D11_FILTER_REDUCTION_TYPE_MASK: DWORD = 0x3; +pub const D3D11_FILTER_REDUCTION_TYPE_SHIFT: DWORD = 7; +pub const D3D11_FILTER_TYPE_MASK: DWORD = 0x3; +pub const D3D11_MIN_FILTER_SHIFT: DWORD = 4; +pub const D3D11_MAG_FILTER_SHIFT: DWORD = 2; +pub const D3D11_MIP_FILTER_SHIFT: DWORD = 0; +pub const D3D11_COMPARISON_FILTERING_BIT: DWORD = 0x80; +pub const D3D11_ANISOTROPIC_FILTERING_BIT: DWORD = 0x40; +ENUM!{enum D3D11_TEXTURE_ADDRESS_MODE { + D3D11_TEXTURE_ADDRESS_WRAP = 1, + D3D11_TEXTURE_ADDRESS_MIRROR = 2, + D3D11_TEXTURE_ADDRESS_CLAMP = 3, + D3D11_TEXTURE_ADDRESS_BORDER = 4, + D3D11_TEXTURE_ADDRESS_MIRROR_ONCE = 5, +}} +STRUCT!{struct D3D11_SAMPLER_DESC { + Filter: D3D11_FILTER, + AddressU: D3D11_TEXTURE_ADDRESS_MODE, + AddressV: D3D11_TEXTURE_ADDRESS_MODE, + AddressW: D3D11_TEXTURE_ADDRESS_MODE, + MipLODBias: FLOAT, + MaxAnisotropy: UINT, + ComparisonFunc: D3D11_COMPARISON_FUNC, + BorderColor: [FLOAT; 4], + MinLOD: FLOAT, + MaxLOD: FLOAT, +}} +RIDL!{interface ID3D11SamplerState(ID3D11SamplerStateVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SAMPLER_DESC) -> () +}} +FLAGS!{enum D3D11_FORMAT_SUPPORT { + D3D11_FORMAT_SUPPORT_BUFFER = 0x1, + D3D11_FORMAT_SUPPORT_IA_VERTEX_BUFFER = 0x2, + D3D11_FORMAT_SUPPORT_IA_INDEX_BUFFER = 0x4, + D3D11_FORMAT_SUPPORT_SO_BUFFER = 0x8, + D3D11_FORMAT_SUPPORT_TEXTURE1D = 0x10, + D3D11_FORMAT_SUPPORT_TEXTURE2D = 0x20, + D3D11_FORMAT_SUPPORT_TEXTURE3D = 0x40, + D3D11_FORMAT_SUPPORT_TEXTURECUBE = 0x80, + D3D11_FORMAT_SUPPORT_SHADER_LOAD = 0x100, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE = 0x200, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE_COMPARISON = 0x400, + D3D11_FORMAT_SUPPORT_SHADER_SAMPLE_MONO_TEXT = 0x800, + D3D11_FORMAT_SUPPORT_MIP = 0x1000, + D3D11_FORMAT_SUPPORT_MIP_AUTOGEN = 0x2000, + D3D11_FORMAT_SUPPORT_RENDER_TARGET = 0x4000, + D3D11_FORMAT_SUPPORT_BLENDABLE = 0x8000, + D3D11_FORMAT_SUPPORT_DEPTH_STENCIL = 0x10000, + D3D11_FORMAT_SUPPORT_CPU_LOCKABLE = 0x20000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE = 0x40000, + D3D11_FORMAT_SUPPORT_DISPLAY = 0x80000, + D3D11_FORMAT_SUPPORT_CAST_WITHIN_BIT_LAYOUT = 0x100000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET = 0x200000, + D3D11_FORMAT_SUPPORT_MULTISAMPLE_LOAD = 0x400000, + D3D11_FORMAT_SUPPORT_SHADER_GATHER = 0x800000, + D3D11_FORMAT_SUPPORT_BACK_BUFFER_CAST = 0x1000000, + D3D11_FORMAT_SUPPORT_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000, + D3D11_FORMAT_SUPPORT_SHADER_GATHER_COMPARISON = 0x4000000, + D3D11_FORMAT_SUPPORT_DECODER_OUTPUT = 0x8000000, + D3D11_FORMAT_SUPPORT_VIDEO_PROCESSOR_OUTPUT = 0x10000000, + D3D11_FORMAT_SUPPORT_VIDEO_PROCESSOR_INPUT = 0x20000000, + D3D11_FORMAT_SUPPORT_VIDEO_ENCODER = 0x40000000, +}} +FLAGS!{enum D3D11_FORMAT_SUPPORT2 { + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10, + D3D11_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20, + D3D11_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40, + D3D11_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80, + D3D11_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100, + D3D11_FORMAT_SUPPORT2_TILED = 0x200, + D3D11_FORMAT_SUPPORT2_SHAREABLE = 0x400, + D3D11_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000, +}} +RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDataSize(&mut self) -> UINT +}} +FLAGS!{enum D3D11_ASYNC_GETDATA_FLAG { + D3D11_ASYNC_GETDATA_DONOTFLUSH = 0x1, +}} +ENUM!{enum D3D11_QUERY { + D3D11_QUERY_EVENT = 0, + D3D11_QUERY_OCCLUSION = D3D11_QUERY_EVENT.0 + 1, + D3D11_QUERY_TIMESTAMP = D3D11_QUERY_OCCLUSION.0 + 1, + D3D11_QUERY_TIMESTAMP_DISJOINT = D3D11_QUERY_TIMESTAMP.0 + 1, + D3D11_QUERY_PIPELINE_STATISTICS = D3D11_QUERY_TIMESTAMP_DISJOINT.0 + 1, + D3D11_QUERY_OCCLUSION_PREDICATE = D3D11_QUERY_PIPELINE_STATISTICS.0 + 1, + D3D11_QUERY_SO_STATISTICS = D3D11_QUERY_OCCLUSION_PREDICATE.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE = D3D11_QUERY_SO_STATISTICS.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM0 = D3D11_QUERY_SO_OVERFLOW_PREDICATE.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0 = D3D11_QUERY_SO_STATISTICS_STREAM0.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM1 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM0.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1 = D3D11_QUERY_SO_STATISTICS_STREAM1.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM2 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM1.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2 = D3D11_QUERY_SO_STATISTICS_STREAM2.0 + 1, + D3D11_QUERY_SO_STATISTICS_STREAM3 = D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM2.0 + 1, + D3D11_QUERY_SO_OVERFLOW_PREDICATE_STREAM3 = D3D11_QUERY_SO_STATISTICS_STREAM3.0 + 1, +}} +FLAGS!{enum D3D11_QUERY_MISC_FLAG { + D3D11_QUERY_MISC_PREDICATEHINT = 0x1, +}} +STRUCT!{struct D3D11_QUERY_DESC { + Query: D3D11_QUERY, + MiscFlags: UINT, +}} +RIDL!{interface ID3D11Query(ID3D11QueryVtbl): ID3D11Asynchronous(ID3D11AsynchronousVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_QUERY_DESC) -> () +}} +RIDL!{interface ID3D11Predicate(ID3D11PredicateVtbl): ID3D11Query(ID3D11QueryVtbl) {}} +STRUCT!{struct D3D11_QUERY_DATA_TIMESTAMP_DISJOINT { + Frequency: UINT64, + Disjoint: BOOL, +}} +STRUCT!{struct D3D11_QUERY_DATA_PIPELINE_STATISTICS { + IAVertices: UINT64, + IAPrimitives: UINT64, + VSInvocations: UINT64, + GSInvocations: UINT64, + GSPrimitives: UINT64, + CInvocations: UINT64, + CPrimitives: UINT64, + PSInvocations: UINT64, + HSInvocations: UINT64, + DSInvocations: UINT64, + CSInvocations: UINT64, +}} +STRUCT!{struct D3D11_QUERY_DATA_SO_STATISTICS { + NumPrimitivesWritten: UINT64, + PrimitivesStorageNeeded: UINT64, +}} +FLAGS!{enum D3D11_COUNTER { + D3D11_COUNTER_DEVICE_DEPENDENT_0 = 0x40000000, +}} +ENUM!{enum D3D11_COUNTER_TYPE { + D3D11_COUNTER_TYPE_FLOAT32 = 0, + D3D11_COUNTER_TYPE_UINT16 = D3D11_COUNTER_TYPE_FLOAT32.0 + 1, + D3D11_COUNTER_TYPE_UINT32 = D3D11_COUNTER_TYPE_UINT16.0 + 1, + D3D11_COUNTER_TYPE_UINT64 = D3D11_COUNTER_TYPE_UINT32.0 + 1, +}} +STRUCT!{struct D3D11_COUNTER_DESC { + Counter: D3D11_COUNTER, + MiscFlags: UINT, +}} +STRUCT!{struct D3D11_COUNTER_INFO { + LastDeviceDependentCounter: D3D11_COUNTER, + NumSimultaneousCounters: UINT, + NumDetectableParallelUnits: UINT8, +}} +RIDL!{interface ID3D11Counter(ID3D11CounterVtbl): ID3D11Asynchronous(ID3D11AsynchronousVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_COUNTER_DESC) -> () +}} +ENUM!{enum D3D11_STANDARD_MULTISAMPLE_QUALITY_LEVELS { + D3D11_STANDARD_MULTISAMPLE_PATTERN = 0xffffffff, + D3D11_CENTER_MULTISAMPLE_PATTERN = 0xfffffffe, +}} +ENUM!{enum D3D11_DEVICE_CONTEXT_TYPE { + D3D11_DEVICE_CONTEXT_IMMEDIATE = 0, + D3D11_DEVICE_CONTEXT_DEFERRED = D3D11_DEVICE_CONTEXT_IMMEDIATE.0 + 1, +}} +STRUCT!{struct D3D11_CLASS_INSTANCE_DESC { + InstanceId: UINT, + InstanceIndex: UINT, + TypeId: UINT, + ConstantBuffer: UINT, + BaseConstantBufferOffset: UINT, + BaseTexture: UINT, + BaseSampler: UINT, + Created: BOOL, +}} +RIDL!{interface ID3D11ClassInstance(ID3D11ClassInstanceVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetClassLinkage(&mut self, ppLinkage: *mut *mut ID3D11ClassLinkage) -> (), + fn GetDesc(&mut self, pDesc: *mut D3D11_CLASS_INSTANCE_DESC) -> (), + fn GetInstanceName(&mut self, pInstanceName: LPSTR, pBufferLength: *mut SIZE_T) -> (), + fn GetTypeName(&mut self, pTypeName: LPSTR, pBufferLength: *mut SIZE_T) -> () +}} +RIDL!{interface ID3D11ClassLinkage(ID3D11ClassLinkageVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetClassInstance( + &mut self, GetClassInstance: LPCSTR, InstanceIndex: UINT, + ppInstance: *mut *mut ID3D11ClassInstance + ) -> HRESULT, + fn CreateClassInstance( + &mut self, pClassTypeName: LPCSTR, ConstantBufferOffset: UINT, ConstantVectorOffset: UINT, TextureOffset: UINT, SamplerOffset: UINT, ppInstance: *mut *mut ID3D11ClassInstance + ) -> HRESULT +}} +RIDL!{interface ID3D11CommandList(ID3D11CommandListVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetContextFlags(&mut self) -> UINT +}} +ENUM!{enum D3D11_FEATURE { + D3D11_FEATURE_THREADING = 0, + D3D11_FEATURE_DOUBLES = D3D11_FEATURE_THREADING.0 + 1, + D3D11_FEATURE_FORMAT_SUPPORT = D3D11_FEATURE_DOUBLES.0 + 1, + D3D11_FEATURE_FORMAT_SUPPORT2 = D3D11_FEATURE_FORMAT_SUPPORT.0 + 1, + D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS = D3D11_FEATURE_FORMAT_SUPPORT2.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS = D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS.0 + 1, + D3D11_FEATURE_ARCHITECTURE_INFO = D3D11_FEATURE_D3D11_OPTIONS.0 + 1, + D3D11_FEATURE_D3D9_OPTIONS = D3D11_FEATURE_ARCHITECTURE_INFO.0 + 1, + D3D11_FEATURE_SHADER_MIN_PRECISION_SUPPORT = D3D11_FEATURE_D3D9_OPTIONS.0 + 1, + D3D11_FEATURE_D3D9_SHADOW_SUPPORT = D3D11_FEATURE_SHADER_MIN_PRECISION_SUPPORT.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS1 = D3D11_FEATURE_D3D9_SHADOW_SUPPORT.0 + 1, + D3D11_FEATURE_D3D9_SIMPLE_INSTANCING_SUPPORT = D3D11_FEATURE_D3D11_OPTIONS1.0 + 1, + D3D11_FEATURE_MARKER_SUPPORT = D3D11_FEATURE_D3D9_SIMPLE_INSTANCING_SUPPORT.0 + 1, + D3D11_FEATURE_D3D9_OPTIONS1 = D3D11_FEATURE_MARKER_SUPPORT.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS2 = D3D11_FEATURE_D3D9_OPTIONS1.0 + 1, + D3D11_FEATURE_D3D11_OPTIONS3 = D3D11_FEATURE_D3D11_OPTIONS2.0 + 1, + D3D11_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = D3D11_FEATURE_D3D11_OPTIONS3.0 + 1, +}} +STRUCT!{struct D3D11_FEATURE_DATA_THREADING { + DriverConcurrentCreates: BOOL, + DriverCommandLists: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_DOUBLES { + DoublePrecisionFloatShaderOps: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_FORMAT_SUPPORT { + InFormat: DXGI_FORMAT, + OutFormatSupport: UINT, +}} +STRUCT!{struct D3D11_FEATURE_DATA_FORMAT_SUPPORT2 { + InFormat: DXGI_FORMAT, + OutFormatSupport2: UINT, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS { + ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS { + OutputMergerLogicOp: BOOL, + UAVOnlyRenderingForcedSampleCount: BOOL, + DiscardAPIsSeenByDriver: BOOL, + FlagsForUpdateAndCopySeenByDriver: BOOL, + ClearView: BOOL, + CopyWithOverlap: BOOL, + ConstantBufferPartialUpdate: BOOL, + ConstantBufferOffsetting: BOOL, + MapNoOverwriteOnDynamicConstantBuffer: BOOL, + MapNoOverwriteOnDynamicBufferSRV: BOOL, + MultisampleRTVWithForcedSampleCountOne: BOOL, + SAD4ShaderInstructions: BOOL, + ExtendedDoublesShaderInstructions: BOOL, + ExtendedResourceSharing: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_ARCHITECTURE_INFO { + TileBasedDeferredRenderer: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_OPTIONS { + FullNonPow2TextureSupport: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_SHADOW_SUPPORT { + SupportsDepthAsTextureWithLessEqualComparisonFilter: BOOL, +}} +FLAGS!{enum D3D11_SHADER_MIN_PRECISION_SUPPORT { + D3D11_SHADER_MIN_PRECISION_10_BIT = 0x1, + D3D11_SHADER_MIN_PRECISION_16_BIT = 0x2, +}} +STRUCT!{struct D3D11_FEATURE_DATA_SHADER_MIN_PRECISION_SUPPORT { + PixelShaderMinPrecision: UINT, + AllOtherShaderStagesMinPrecision: UINT, +}} +ENUM!{enum D3D11_TILED_RESOURCES_TIER { + D3D11_TILED_RESOURCES_NOT_SUPPORTED = 0, + D3D11_TILED_RESOURCES_TIER_1 = 1, + D3D11_TILED_RESOURCES_TIER_2 = 2, + D3D11_TILED_RESOURCES_TIER_3 = 3, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS1 { + TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, + MinMaxFiltering: BOOL, + ClearViewAlsoSupportsDepthOnlyFormats: BOOL, + MapOnDefaultBuffers: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_SIMPLE_INSTANCING_SUPPORT { + SimpleInstancingSupported: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_MARKER_SUPPORT { + Profile: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D9_OPTIONS1 { + FullNonPow2TextureSupported: BOOL, + DepthAsTextureWithLessEqualComparisonFilterSupported: BOOL, + SimpleInstancingSupported: BOOL, + TextureCubeFaceRenderTargetWithNonCubeDepthStencilSupported: BOOL, +}} +ENUM!{enum D3D11_CONSERVATIVE_RASTERIZATION_TIER { + D3D11_CONSERVATIVE_RASTERIZATION_NOT_SUPPORTED = 0, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, + D3D11_CONSERVATIVE_RASTERIZATION_TIER_3 = 3, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS2 { + PSSpecifiedStencilRefSupported: BOOL, + TypedUAVLoadAdditionalFormats: BOOL, + ROVsSupported: BOOL, + ConservativeRasterizationTier: D3D11_CONSERVATIVE_RASTERIZATION_TIER, + TiledResourcesTier: D3D11_TILED_RESOURCES_TIER, + MapOnDefaultTextures: BOOL, + StandardSwizzle: BOOL, + UnifiedMemoryArchitecture: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_D3D11_OPTIONS3 { + VPAndRTArrayIndexFromAnyShaderFeedingRasterizer: BOOL, +}} +STRUCT!{struct D3D11_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT { + MaxGPUVirtualAddressBitsPerResource: UINT, + MaxGPUVirtualAddressBitsPerProcess: UINT, +}} +RIDL!{interface ID3D11DeviceContext(ID3D11DeviceContextVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn VSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn PSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn PSSetShader( + &mut self, pPixelShader: *mut ID3D11PixelShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn PSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn VSSetShader( + &mut self, pVertexShader: *mut ID3D11VertexShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn DrawIndexed( + &mut self, IndexCount: UINT, StartIndexLocation: UINT, BaseVertexLocation: INT + ) -> (), + fn Draw(&mut self, VertexCount: UINT, StartVertexLocation: UINT) -> (), + fn Map( + &mut self, pResource: *mut ID3D11Resource, Subresource: UINT, MapType: D3D11_MAP, + MapFlags: UINT, pMappedResource: *mut D3D11_MAPPED_SUBRESOURCE + ) -> HRESULT, + fn Unmap(&mut self, pResource: *mut ID3D11Resource, Subresource: UINT) -> (), + fn PSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn IASetInputLayout(&mut self, pInputLayout: *mut ID3D11InputLayout) -> (), + fn IASetVertexBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppVertexBuffers: *const *mut ID3D11Buffer, + pStrides: *const UINT, pOffsets: *const UINT + ) -> (), + fn IASetIndexBuffer( + &mut self, pIndexBuffer: *mut ID3D11Buffer, Format: DXGI_FORMAT, Offset: UINT + ) -> (), + fn DrawIndexedInstanced( + &mut self, IndexCountPerInstance: UINT, InstanceCount: UINT, StartIndexLocation: UINT, + BaseVertexLocation: INT, StartInstanceLocation: UINT + ) -> (), + fn DrawInstanced( + &mut self, VertexCountPerInstance: UINT, InstanceCount: UINT, StartVertexLocation: UINT, + StartInstanceLocation: UINT + ) -> (), + fn GSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn GSSetShader( + &mut self, pShader: *mut ID3D11GeometryShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn IASetPrimitiveTopology(&mut self, Topology: D3D11_PRIMITIVE_TOPOLOGY) -> (), + fn VSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn VSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn Begin(&mut self, pAsync: *mut ID3D11Asynchronous) -> (), + fn End(&mut self, pAsync: *mut ID3D11Asynchronous) -> (), + fn GetData( + &mut self, pAsync: *mut ID3D11Asynchronous, pData: *mut c_void, DataSize: UINT, + GetDataFlags: UINT + ) -> HRESULT, + fn SetPredication( + &mut self, pPredicate: *mut ID3D11Predicate, PredicateValue: BOOL + ) -> (), + fn GSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn GSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn OMSetRenderTargets( + &mut self, NumViews: UINT, ppRenderTargetViews: *const *mut ID3D11RenderTargetView, + pDepthStencilView: *mut ID3D11DepthStencilView + ) -> (), + fn OMSetRenderTargetsAndUnorderedAccessViews( + &mut self, NumRTVs: UINT, ppRenderTargetViews: *const *mut ID3D11RenderTargetView, + pDepthStencilView: *mut ID3D11DepthStencilView, UAVStartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *const *mut ID3D11UnorderedAccessView, + pUAVInitialCounts: *const UINT + ) -> (), + fn OMSetBlendState( + &mut self, pBlendState: *mut ID3D11BlendState, BlendFactor: &[FLOAT; 4], SampleMask: UINT + ) -> (), + fn OMSetDepthStencilState( + &mut self, pDepthStencilState: *mut ID3D11DepthStencilState, StencilRef: UINT + ) -> (), + fn SOSetTargets( + &mut self, NumBuffers: UINT, ppSOTargets: *const *mut ID3D11Buffer, pOffsets: *const UINT + ) -> (), + fn DrawAuto(&mut self) -> (), + fn DrawIndexedInstancedIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn DrawInstancedIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn Dispatch( + &mut self, ThreadGroupCountX: UINT, ThreadGroupCountY: UINT, ThreadGroupCountZ: UINT + ) -> (), + fn DispatchIndirect( + &mut self, pBufferForArgs: *mut ID3D11Buffer, AlignedByteOffsetForArgs: UINT + ) -> (), + fn RSSetState(&mut self, pRasterizerState: *mut ID3D11RasterizerState) -> (), + fn RSSetViewports(&mut self, NumViewports: UINT, pViewports: *const D3D11_VIEWPORT) -> (), + fn RSSetScissorRects(&mut self, NumRects: UINT, pRects: *const D3D11_RECT) -> (), + fn CopySubresourceRegion( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, DstX: UINT, DstY: UINT, + DstZ: UINT, pSrcResource: *mut ID3D11Resource, SrcSubresource: UINT, + pSrcBox: *const D3D11_BOX + ) -> (), + fn CopyResource( + &mut self, pDstResource: *mut ID3D11Resource, pSrcResource: *mut ID3D11Resource + ) -> (), + fn UpdateSubresource( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, + pDstBox: *const D3D11_BOX, pSrcData: *const c_void, SrcRowPitch: UINT, SrcDepthPitch: UINT + ) -> (), + fn CopyStructureCount( + &mut self, pDstBuffer: *mut ID3D11Buffer, DstAlignedByteOffset: UINT, + pSrcView: *mut ID3D11UnorderedAccessView + ) -> (), + fn ClearRenderTargetView( + &mut self, pRenderTargetView: *mut ID3D11RenderTargetView, ColorRGBA: &[FLOAT; 4] + ) -> (), + fn ClearUnorderedAccessViewUint( + &mut self, pUnorderedAccessView: *mut ID3D11UnorderedAccessView, Values: &[UINT; 4] + ) -> (), + fn ClearUnorderedAccessViewFloat( + &mut self, pUnorderedAccessView: *mut ID3D11UnorderedAccessView, Values: &[FLOAT; 4] + ) -> (), + fn ClearDepthStencilView( + &mut self, pDepthStencilView: *mut ID3D11DepthStencilView, ClearFlags: UINT, Depth: FLOAT, + Stencil: UINT8 + ) -> (), + fn GenerateMips(&mut self, pShaderResourceView: *mut ID3D11ShaderResourceView) -> (), + fn SetResourceMinLOD(&mut self, pResource: *mut ID3D11Resource, MinLOD: FLOAT) -> (), + fn GetResourceMinLOD(&mut self, pResource: *mut ID3D11Resource) -> FLOAT, + fn ResolveSubresource( + &mut self, pDstResource: *mut ID3D11Resource, DstSubresource: UINT, + pSrcResource: *mut ID3D11Resource, SrcSubresource: UINT, Format: DXGI_FORMAT + ) -> (), + fn ExecuteCommandList( + &mut self, pCommandList: *mut ID3D11CommandList, + RestoreContextState: BOOL + ) -> (), + fn HSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn HSSetShader( + &mut self, pHullShader: *mut ID3D11HullShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn HSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn HSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn DSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn DSSetShader( + &mut self, pDomainShader: *mut ID3D11DomainShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn DSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn DSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn CSSetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *const *mut ID3D11ShaderResourceView + ) -> (), + fn CSSetUnorderedAccessViews( + &mut self, StartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *const *mut ID3D11UnorderedAccessView + ) -> (), + fn CSSetShader( + &mut self, pComputeShader: *mut ID3D11ComputeShader, + ppClassInstances: *const *mut ID3D11ClassInstance, NumClassInstances: UINT + ) -> (), + fn CSSetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *const *mut ID3D11SamplerState + ) -> (), + fn CSSetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *const *mut ID3D11Buffer + ) -> (), + fn VSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn PSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn PSGetShader( + &mut self, ppPixelShader: *mut *mut ID3D11PixelShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn PSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn VSGetShader( + &mut self, ppVertexShader: *mut *mut ID3D11VertexShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn PSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn IAGetInputLayout(&mut self, ppInputLayout: *mut *mut ID3D11InputLayout) -> (), + fn IAGetVertexBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppVertexBuffers: *mut *mut ID3D11Buffer, + pStrides: *mut UINT, pOffsets: *mut UINT + ) -> (), + fn IAGetIndexBuffer( + &mut self, pIndexBuffer: *mut *mut ID3D11Buffer, Format: *mut DXGI_FORMAT, + Offset: *mut UINT + ) -> (), + fn GSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn GSGetShader( + &mut self, ppGeometryShader: *mut *mut ID3D11GeometryShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn IAGetPrimitiveTopology(&mut self, pTopology: *mut D3D11_PRIMITIVE_TOPOLOGY) -> (), + fn VSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn VSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn GetPredication( + &mut self, ppPredicate: *mut *mut ID3D11Predicate, pPredicateValue: *mut BOOL + ) -> (), + fn GSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn GSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn OMGetRenderTargets( + &mut self, NumViews: UINT, ppRenderTargetViews: *mut *mut ID3D11RenderTargetView, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView + ) -> (), + fn OMGetRenderTargetsAndUnorderedAccessViews( + &mut self, NumRTVs: UINT, ppRenderTargetViews: *mut *mut ID3D11RenderTargetView, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView, UAVStartSlot: UINT, + ppUnorderedAccessViews: *mut *mut ID3D11UnorderedAccessView + ) -> (), + fn OMGetBlendState( + &mut self, ppBlendState: *mut *mut ID3D11BlendState, BlendFactor: &mut [FLOAT; 4], + pSampleMask: *mut UINT + ) -> (), + fn OMGetDepthStencilState( + &mut self, ppDepthStencilState: *mut *mut ID3D11DepthStencilState, pStencilRef: *mut UINT + ) -> (), + fn SOGetTargets(&mut self, NumBuffers: UINT, ppSOTargets: *mut *mut ID3D11Buffer) -> (), + fn RSGetState(&mut self, ppRasterizerState: *mut *mut ID3D11RasterizerState) -> (), + fn RSGetViewports(&mut self, pNumViewports: *mut UINT, pViewports: *mut D3D11_VIEWPORT) -> (), + fn RSGetScissorRects(&mut self, pNumRects: *mut UINT, pRects: *mut D3D11_RECT) -> (), + fn HSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn HSGetShader( + &mut self, ppHullShader: *mut *mut ID3D11HullShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn HSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn HSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn DSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn DSGetShader( + &mut self, ppDomainShader: *mut *mut ID3D11DomainShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn DSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn DSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn CSGetShaderResources( + &mut self, StartSlot: UINT, NumViews: UINT, + ppShaderResourceViews: *mut *mut ID3D11ShaderResourceView + ) -> (), + fn CSGetUnorderedAccessViews( + &mut self, StartSlot: UINT, NumUAVs: UINT, + ppUnorderedAccessViews: *mut *mut ID3D11UnorderedAccessView + ) -> (), + fn CSGetShader( + &mut self, ppComputeShader: *mut *mut ID3D11ComputeShader, + ppClassInstances: *mut *mut ID3D11ClassInstance, pNumClassInstances: *mut UINT + ) -> (), + fn CSGetSamplers( + &mut self, StartSlot: UINT, NumSamplers: UINT, ppSamplers: *mut *mut ID3D11SamplerState + ) -> (), + fn CSGetConstantBuffers( + &mut self, StartSlot: UINT, NumBuffers: UINT, ppConstantBuffers: *mut *mut ID3D11Buffer + ) -> (), + fn ClearState(&mut self) -> (), + fn Flush(&mut self) -> (), + fn GetType(&mut self) -> D3D11_DEVICE_CONTEXT_TYPE, + fn GetContextFlags(&mut self) -> UINT, + fn FinishCommandList( + &mut self, RestoreDeferredContextState: BOOL, ppCommandList: *mut *mut ID3D11CommandList + ) -> HRESULT +}} +STRUCT!{struct D3D11_VIDEO_DECODER_DESC { + Guid: GUID, + SampleWidth: UINT, + SampleHeight: UINT, + OutputFormat: DXGI_FORMAT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_CONFIG { + guidConfigBitstreamEncryption: GUID, + guidConfigMBcontrolEncryption: GUID, + guidConfigResidDiffEncryption: GUID, + ConfigBitstreamRaw: UINT, + ConfigMBcontrolRasterOrder: UINT, + ConfigResidDiffHost: UINT, + ConfigSpatialResid8: UINT, + ConfigResid8Subtraction: UINT, + ConfigSpatialHost8or9Clipping: UINT, + ConfigSpatialResidInterleaved: UINT, + ConfigIntraResidUnsigned: UINT, + ConfigResidDiffAccelerator: UINT, + ConfigHostInverseScan: UINT, + ConfigSpecificIDCT: UINT, + Config4GroupedCoefs: UINT, + ConfigMinRenderTargetBuffCount: USHORT, + ConfigDecoderSpecific: USHORT, +}} +ENUM!{enum D3D11_VIDEO_DECODER_BUFFER_TYPE { + D3D11_VIDEO_DECODER_BUFFER_PICTURE_PARAMETERS = 0, + D3D11_VIDEO_DECODER_BUFFER_MACROBLOCK_CONTROL = 1, + D3D11_VIDEO_DECODER_BUFFER_RESIDUAL_DIFFERENCE = 2, + D3D11_VIDEO_DECODER_BUFFER_DEBLOCKING_CONTROL = 3, + D3D11_VIDEO_DECODER_BUFFER_INVERSE_QUANTIZATION_MATRIX = 4, + D3D11_VIDEO_DECODER_BUFFER_SLICE_CONTROL = 5, + D3D11_VIDEO_DECODER_BUFFER_BITSTREAM = 6, + D3D11_VIDEO_DECODER_BUFFER_MOTION_VECTOR = 7, + D3D11_VIDEO_DECODER_BUFFER_FILM_GRAIN = 8, +}} +STRUCT!{struct D3D11_AES_CTR_IV { + IV: UINT64, + Count: UINT64, +}} +STRUCT!{struct D3D11_ENCRYPTED_BLOCK_INFO { + NumEncryptedBytesAtBeginning: UINT, + NumBytesInSkipPattern: UINT, + NumBytesInEncryptPattern: UINT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_BUFFER_DESC { + BufferType: D3D11_VIDEO_DECODER_BUFFER_TYPE, + BufferIndex: UINT, + DataOffset: UINT, + DataSize: UINT, + FirstMBaddress: UINT, + NumMBsInBuffer: UINT, + Width: UINT, + Height: UINT, + Stride: UINT, + ReservedBits: UINT, + pIV: *mut c_void, + IVSize: UINT, + PartialEncryption: BOOL, + EncryptedBlockInfo: D3D11_ENCRYPTED_BLOCK_INFO, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_EXTENSION { + Function: UINT, + pPrivateInputData: *mut c_void, + PrivateInputDataSize: UINT, + pPrivateOutputData: *mut c_void, + PrivateOutputDataSize: UINT, + ResourceCount: UINT, + ppResourceList: *mut *mut ID3D11Resource, +}} +RIDL!{interface ID3D11VideoDecoder(ID3D11VideoDecoderVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCreationParameters( + &mut self, pVideoDesc: *mut D3D11_VIDEO_DECODER_DESC, + pConfig: *mut D3D11_VIDEO_DECODER_CONFIG + ) -> HRESULT, + fn GetDriverHandle(&mut self, pDriverHandle: *mut HANDLE) -> HRESULT +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT { + D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_INPUT = 0x1, + D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT = 0x2, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_DEVICE_CAPS { + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_LINEAR_SPACE = 0x1, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_xvYCC = 0x2, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_RGB_RANGE_CONVERSION = 0x4, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_YCbCr_MATRIX_CONVERSION = 0x8, + D3D11_VIDEO_PROCESSOR_DEVICE_CAPS_NOMINAL_RANGE = 0x10, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FEATURE_CAPS { + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_FILL = 0x1, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_CONSTRICTION = 0x2, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_LUMA_KEY = 0x4, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_PALETTE = 0x8, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_LEGACY = 0x10, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_STEREO = 0x20, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ROTATION = 0x40, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_ALPHA_STREAM = 0x80, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_PIXEL_ASPECT_RATIO = 0x100, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_MIRROR = 0x200, + D3D11_VIDEO_PROCESSOR_FEATURE_CAPS_SHADER_USAGE = 0x400, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FILTER_CAPS { + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_BRIGHTNESS = 0x1, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_CONTRAST = 0x2, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_HUE = 0x4, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_SATURATION = 0x8, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_NOISE_REDUCTION = 0x10, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_EDGE_ENHANCEMENT = 0x20, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_ANAMORPHIC_SCALING = 0x40, + D3D11_VIDEO_PROCESSOR_FILTER_CAPS_STEREO_ADJUSTMENT = 0x80, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_FORMAT_CAPS { + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_INTERLACED = 0x1, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_PROCAMP = 0x2, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_RGB_LUMA_KEY = 0x4, + D3D11_VIDEO_PROCESSOR_FORMAT_CAPS_PALETTE_INTERLACED = 0x8, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS { + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_DENOISE = 0x1, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_DERINGING = 0x2, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_EDGE_ENHANCEMENT = 0x4, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_COLOR_CORRECTION = 0x8, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_FLESH_TONE_MAPPING = 0x10, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_IMAGE_STABILIZATION = 0x20, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_SUPER_RESOLUTION = 0x40, + D3D11_VIDEO_PROCESSOR_AUTO_STREAM_CAPS_ANAMORPHIC_SCALING = 0x80, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_STEREO_CAPS { + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_MONO_OFFSET = 0x1, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_ROW_INTERLEAVED = 0x2, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_COLUMN_INTERLEAVED = 0x4, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_CHECKERBOARD = 0x8, + D3D11_VIDEO_PROCESSOR_STEREO_CAPS_FLIP_MODE = 0x10, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CAPS { + DeviceCaps: UINT, + FeatureCaps: UINT, + FilterCaps: UINT, + InputFormatCaps: UINT, + AutoStreamCaps: UINT, + StereoCaps: UINT, + RateConversionCapsCount: UINT, + MaxInputStreams: UINT, + MaxStreamStates: UINT, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS { + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_BLEND = 0x1, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_BOB = 0x2, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_ADAPTIVE = 0x4, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_DEINTERLACE_MOTION_COMPENSATION = 0x8, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_INVERSE_TELECINE = 0x10, + D3D11_VIDEO_PROCESSOR_PROCESSOR_CAPS_FRAME_RATE_CONVERSION = 0x20, +}} +FLAGS!{enum D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS { + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_32 = 0x1, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_22 = 0x2, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_2224 = 0x4, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_2332 = 0x8, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_32322 = 0x10, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_55 = 0x20, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_64 = 0x40, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_87 = 0x80, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_222222222223 = 0x100, + D3D11_VIDEO_PROCESSOR_ITELECINE_CAPS_OTHER = 0x80000000, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS { + PastFrames: UINT, + FutureFrames: UINT, + ProcessorCaps: UINT, + ITelecineCaps: UINT, + CustomRateCount: UINT, +}} +FLAGS!{enum D3D11_CONTENT_PROTECTION_CAPS { + D3D11_CONTENT_PROTECTION_CAPS_SOFTWARE = 0x1, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE = 0x2, + D3D11_CONTENT_PROTECTION_CAPS_PROTECTION_ALWAYS_ON = 0x4, + D3D11_CONTENT_PROTECTION_CAPS_PARTIAL_DECRYPTION = 0x8, + D3D11_CONTENT_PROTECTION_CAPS_CONTENT_KEY = 0x10, + D3D11_CONTENT_PROTECTION_CAPS_FRESHEN_SESSION_KEY = 0x20, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPTED_READ_BACK = 0x40, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPTED_READ_BACK_KEY = 0x80, + D3D11_CONTENT_PROTECTION_CAPS_SEQUENTIAL_CTR_IV = 0x100, + D3D11_CONTENT_PROTECTION_CAPS_ENCRYPT_SLICEDATA_ONLY = 0x200, + D3D11_CONTENT_PROTECTION_CAPS_DECRYPTION_BLT = 0x400, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_PROTECT_UNCOMPRESSED = 0x800, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_PROTECTED_MEMORY_PAGEABLE = 0x1000, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_TEARDOWN = 0x2000, + D3D11_CONTENT_PROTECTION_CAPS_HARDWARE_DRM_COMMUNICATION = 0x4000, +}} +STRUCT!{struct D3D11_VIDEO_CONTENT_PROTECTION_CAPS { + Caps: UINT, + KeyExchangeTypeCount: UINT, + BlockAlignmentSize: UINT, + ProtectedMemorySize: ULONGLONG, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CUSTOM_RATE { + CustomRate: DXGI_RATIONAL, + OutputFrames: UINT, + InputInterlaced: BOOL, + InputFramesOrFields: UINT, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_FILTER { + D3D11_VIDEO_PROCESSOR_FILTER_BRIGHTNESS = 0, + D3D11_VIDEO_PROCESSOR_FILTER_CONTRAST = 1, + D3D11_VIDEO_PROCESSOR_FILTER_HUE = 2, + D3D11_VIDEO_PROCESSOR_FILTER_SATURATION = 3, + D3D11_VIDEO_PROCESSOR_FILTER_NOISE_REDUCTION = 4, + D3D11_VIDEO_PROCESSOR_FILTER_EDGE_ENHANCEMENT = 5, + D3D11_VIDEO_PROCESSOR_FILTER_ANAMORPHIC_SCALING = 6, + D3D11_VIDEO_PROCESSOR_FILTER_STEREO_ADJUSTMENT = 7, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_FILTER_RANGE { + Minimum: c_int, + Maximum: c_int, + Default: c_int, + Multiplier: c_float, +}} +ENUM!{enum D3D11_VIDEO_FRAME_FORMAT { + D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE = 0, + D3D11_VIDEO_FRAME_FORMAT_INTERLACED_TOP_FIELD_FIRST = 1, + D3D11_VIDEO_FRAME_FORMAT_INTERLACED_BOTTOM_FIELD_FIRST = 2, +}} +ENUM!{enum D3D11_VIDEO_USAGE { + D3D11_VIDEO_USAGE_PLAYBACK_NORMAL = 0, + D3D11_VIDEO_USAGE_OPTIMAL_SPEED = 1, + D3D11_VIDEO_USAGE_OPTIMAL_QUALITY = 2, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_CONTENT_DESC { + InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT, + InputFrameRate: DXGI_RATIONAL, + InputWidth: UINT, + InputHeight: UINT, + OutputFrameRate: DXGI_RATIONAL, + OutputWidth: UINT, + OutputHeight: UINT, + Usage: D3D11_VIDEO_USAGE, +}} +RIDL!{interface ID3D11VideoProcessorEnumerator(ID3D11VideoProcessorEnumeratorVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetVideoProcessorContentDesc( + &mut self, pContentDesc: *mut D3D11_VIDEO_PROCESSOR_CONTENT_DESC + ) -> HRESULT, + fn CheckVideoProcessorFormat(&mut self, Format: DXGI_FORMAT, pFlags: *mut UINT) -> HRESULT, + fn GetVideoProcessorCaps(&mut self, pCaps: *mut D3D11_VIDEO_PROCESSOR_CAPS) -> HRESULT, + fn GetVideoProcessorRateConversionCaps( + &mut self, TypeIndex: UINT, pCaps: *mut D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS + ) -> HRESULT, + fn GetVideoProcessorCustomRate( + &mut self, TypeIndex: UINT, CustomRateIndex: UINT, + pRate: *mut D3D11_VIDEO_PROCESSOR_CUSTOM_RATE + ) -> HRESULT, + fn GetVideoProcessorFilterRange( + &mut self, Filter: D3D11_VIDEO_PROCESSOR_FILTER, + Range: *mut D3D11_VIDEO_PROCESSOR_FILTER_RANGE + ) -> HRESULT +}} +STRUCT!{struct D3D11_VIDEO_COLOR_RGBA { + R: c_float, + G: c_float, + B: c_float, + A: c_float, +}} +STRUCT!{struct D3D11_VIDEO_COLOR_YCbCrA { + Y: c_float, + Cb: c_float, + Cr: c_float, + A: c_float, +}} +STRUCT!{struct D3D11_VIDEO_COLOR { + u: [c_float; 4], +}} +UNION!{D3D11_VIDEO_COLOR, u, YCbCr, YCbCr_mut, D3D11_VIDEO_COLOR_YCbCrA} +UNION!{D3D11_VIDEO_COLOR, u, RGBA, RGBA_mut, D3D11_VIDEO_COLOR_RGBA} +ENUM!{enum D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE { + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_UNDEFINED = 0, + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235 = 1, + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_0_255 = 2, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_COLOR_SPACE { + bitfield: UINT, +}} +BITFIELD!{D3D11_VIDEO_PROCESSOR_COLOR_SPACE bitfield: UINT [ + Usage set_Usage[0..1], + RGB_Range set_RGB_Range[1..2], + YCbCr_Matrix set_YCbCr_Matrix[2..3], + YCbCr_xvYCC set_YCbCr_xvYCC[3..4], + Nominal_Range set_Nominal_Range[4..6], +]} +ENUM!{enum D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE { + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_OPAQUE = 0, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_BACKGROUND = 1, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_DESTINATION = 2, + D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE_SOURCE_STREAM = 3, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_OUTPUT_RATE { + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_NORMAL = 0, + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_HALF = 1, + D3D11_VIDEO_PROCESSOR_OUTPUT_RATE_CUSTOM = 2, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_STEREO_FORMAT { + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_MONO = 0, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_HORIZONTAL = 1, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_VERTICAL = 2, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_SEPARATE = 3, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_MONO_OFFSET = 4, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_ROW_INTERLEAVED = 5, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_COLUMN_INTERLEAVED = 6, + D3D11_VIDEO_PROCESSOR_STEREO_FORMAT_CHECKERBOARD = 7, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE { + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_NONE = 0, + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_FRAME0 = 1, + D3D11_VIDEO_PROCESSOR_STEREO_FLIP_FRAME1 = 2, +}} +ENUM!{enum D3D11_VIDEO_PROCESSOR_ROTATION { + D3D11_VIDEO_PROCESSOR_ROTATION_IDENTITY = 0, + D3D11_VIDEO_PROCESSOR_ROTATION_90 = 1, + D3D11_VIDEO_PROCESSOR_ROTATION_180 = 2, + D3D11_VIDEO_PROCESSOR_ROTATION_270 = 3, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_STREAM { + Enable: BOOL, + OutputIndex: UINT, + InputFrameOrField: UINT, + PastFrames: UINT, + FutureFrames: UINT, + ppPastSurfaces: *mut *mut ID3D11VideoProcessorInputView, + pInputSurface: *mut ID3D11VideoProcessorInputView, + ppFutureSurfaces: *mut *mut ID3D11VideoProcessorInputView, + ppPastSurfacesRight: *mut *mut ID3D11VideoProcessorInputView, + pInputSurfaceRight: *mut ID3D11VideoProcessorInputView, + ppFutureSurfacesRight: *mut *mut ID3D11VideoProcessorInputView, +}} +RIDL!{interface ID3D11VideoProcessor(ID3D11VideoProcessorVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetContentDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_CONTENT_DESC) -> (), + fn GetRateConversionCaps( + &mut self, pCaps: *mut D3D11_VIDEO_PROCESSOR_RATE_CONVERSION_CAPS + ) -> () +}} +STRUCT!{struct D3D11_OMAC { + Omac: [BYTE; 16], +}} +ENUM!{enum D3D11_AUTHENTICATED_CHANNEL_TYPE { + D3D11_AUTHENTICATED_CHANNEL_D3D11 = 1, + D3D11_AUTHENTICATED_CHANNEL_DRIVER_SOFTWARE = 2, + D3D11_AUTHENTICATED_CHANNEL_DRIVER_HARDWARE = 3, +}} +RIDL!{interface ID3D11AuthenticatedChannel(ID3D11AuthenticatedChannelVtbl) + : ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut UINT) -> HRESULT, + fn GetCertificate(&mut self, CertificateSize: UINT, pCertificate: *mut BYTE) -> HRESULT, + fn GetChannelHandle(&mut self, pChannelHandle: *mut HANDLE) -> () +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_INPUT { + QueryType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT { + omac: D3D11_OMAC, + QueryType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, + ReturnCode: HRESULT, +}} +//FIXME bitfield +STRUCT!{struct D3D11_AUTHENTICATED_PROTECTION_FLAGS { + u: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_PROTECTION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ProtectionFlags: D3D11_AUTHENTICATED_PROTECTION_FLAGS, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CHANNEL_TYPE_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ChannelType: D3D11_AUTHENTICATED_CHANNEL_TYPE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_DEVICE_HANDLE_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CRYPTO_SESSION_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DecoderHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CRYPTO_SESSION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DecoderHandle: HANDLE, + CryptoSessionHandle: HANDLE, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + RestrictedSharedResourceProcessCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + ProcessIndex: UINT, +}} +ENUM!{enum D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE { + DD3D11_PROCESSIDTYPE_UNKNOWN = 0, + DD3D11_PROCESSIDTYPE_DWM = 1, + DD3D11_PROCESSIDTYPE_HANDLE = 2, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_RESTRICTED_SHARED_RESOURCE_PROCESS_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + ProcessIndex: UINT, + ProcessIdentifier: D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE, + ProcessHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_UNRESTRICTED_PROTECTED_SHARED_RESOURCE_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + UnrestrictedProtectedSharedResourceCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_COUNT_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDIndex: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_OUTPUT_ID_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + DeviceHandle: HANDLE, + CryptoSessionHandle: HANDLE, + OutputIDIndex: UINT, + OutputID: UINT64, +}} +ENUM!{enum D3D11_BUS_TYPE { + D3D11_BUS_TYPE_OTHER = 0, + D3D11_BUS_TYPE_PCI = 0x1, + D3D11_BUS_TYPE_PCIX = 0x2, + D3D11_BUS_TYPE_PCIEXPRESS = 0x3, + D3D11_BUS_TYPE_AGP = 0x4, + D3D11_BUS_IMPL_MODIFIER_INSIDE_OF_CHIPSET = 0x10000, + D3D11_BUS_IMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_CHIP = 0x20000, + D3D11_BUS_IMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_SOCKET = 0x30000, + D3D11_BUS_IMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR = 0x40000, + D3D11_BUS_IMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR_INSIDE_OF_NUAE = 0x50000, + D3D11_BUS_IMPL_MODIFIER_NON_STANDARD = 0x80000000, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACESSIBILITY_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + BusType: D3D11_BUS_TYPE, + AccessibleInContiguousBlocks: BOOL, + AccessibleInNonContiguousBlocks: BOOL, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_COUNT_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuidCount: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_INPUT { + Input: D3D11_AUTHENTICATED_QUERY_INPUT, + EncryptionGuidIndex: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_ACCESSIBILITY_ENCRYPTION_GUID_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuidIndex: UINT, + EncryptionGuid: GUID, +}} +STRUCT!{struct D3D11_AUTHENTICATED_QUERY_CURRENT_ACCESSIBILITY_ENCRYPTION_OUTPUT { + Output: D3D11_AUTHENTICATED_QUERY_OUTPUT, + EncryptionGuid: GUID, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_INPUT { + omac: D3D11_OMAC, + ConfigureType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_OUTPUT { + omac: D3D11_OMAC, + ConfigureType: GUID, + hChannel: HANDLE, + SequenceNumber: UINT, + ReturnCode: HRESULT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_INITIALIZE_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + StartSequenceQuery: UINT, + StartSequenceConfigure: UINT, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_PROTECTION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + Protections: D3D11_AUTHENTICATED_PROTECTION_FLAGS, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_CRYPTO_SESSION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + DecoderHandle: HANDLE, + CryptoSessionHandle: HANDLE, + DeviceHandle: HANDLE, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_SHARED_RESOURCE_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + ProcessType: D3D11_AUTHENTICATED_PROCESS_IDENTIFIER_TYPE, + ProcessHandle: HANDLE, + AllowAccess: BOOL, +}} +STRUCT!{struct D3D11_AUTHENTICATED_CONFIGURE_ACCESSIBLE_ENCRYPTION_INPUT { + Parameters: D3D11_AUTHENTICATED_CONFIGURE_INPUT, + EncryptionGuid: GUID, +}} +RIDL!{interface ID3D11CryptoSession(ID3D11CryptoSessionVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetCryptoType(&mut self, pCryptoType: *mut GUID) -> (), + fn GetDecoderProfile(&mut self, pDecoderProfile: *mut GUID) -> (), + fn GetCertificateSize(&mut self, pCertificateSize: *mut UINT) -> HRESULT, + fn GetCertificate(&mut self, CertificateSize: UINT, pCertificate: *mut BYTE) -> HRESULT, + fn GetCryptoSessionHandle(&mut self, pCertificate: *mut HANDLE) -> () +}} +ENUM!{enum D3D11_VDOV_DIMENSION { + D3D11_VDOV_DIMENSION_UNKNOWN = 0, + D3D11_VDOV_DIMENSION_TEXTURE2D = 1, +}} +STRUCT!{struct D3D11_TEX2D_VDOV { + ArraySlice: UINT, +}} +STRUCT!{struct D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC { + DecodeProfile: GUID, + ViewDimension: D3D11_VDOV_DIMENSION, + Texture2D: D3D11_TEX2D_VDOV, +}} +RIDL!{interface ID3D11VideoDecoderOutputView(ID3D11VideoDecoderOutputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC) -> () +}} +ENUM!{enum D3D11_VPIV_DIMENSION { + D3D11_VPIV_DIMENSION_UNKNOWN = 0, + D3D11_VPIV_DIMENSION_TEXTURE2D = 1, +}} +STRUCT!{struct D3D11_TEX2D_VPIV { + MipSlice: UINT, + ArraySlice: UINT, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { + FourCC: UINT, + ViewDimension: D3D11_VPIV_DIMENSION, + Texture2D: D3D11_TEX2D_VPIV, +}} +RIDL!{interface ID3D11VideoProcessorInputView(ID3D11VideoProcessorInputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC) -> () +}} +ENUM!{enum D3D11_VPOV_DIMENSION { + D3D11_VPOV_DIMENSION_UNKNOWN = 0, + D3D11_VPOV_DIMENSION_TEXTURE2D = 1, + D3D11_VPOV_DIMENSION_TEXTURE2DARRAY = 2, +}} +STRUCT!{struct D3D11_TEX2D_VPOV { + MipSlice: UINT, +}} +STRUCT!{struct D3D11_TEX2D_ARRAY_VPOV { + MipSlice: UINT, + FirstArraySlice: UINT, + ArraySize: UINT, +}} +STRUCT!{struct D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { + ViewDimension: D3D11_VPOV_DIMENSION, + u: [UINT; 3], +}} +UNION!{D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, u, Texture2D, Texture2D_mut, D3D11_TEX2D_VPOV} +UNION!{D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + D3D11_TEX2D_ARRAY_VPOV} +RIDL!{interface ID3D11VideoProcessorOutputView(ID3D11VideoProcessorOutputViewVtbl) + : ID3D11View(ID3D11ViewVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC) -> () +}} +RIDL!{interface ID3D11VideoContext(ID3D11VideoContextVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) { + fn GetDecoderBuffer( + &mut self, pDecoder: *mut ID3D11VideoDecoder, Type: D3D11_VIDEO_DECODER_BUFFER_TYPE, + pBufferSize: *mut UINT, ppBuffer: *mut *mut c_void + ) -> HRESULT, + fn ReleaseDecoderBuffer( + &mut self, pDecoder: *mut ID3D11VideoDecoder, Type: D3D11_VIDEO_DECODER_BUFFER_TYPE + ) -> HRESULT, + fn DecoderBeginFrame( + &mut self, pDecoder: *mut ID3D11VideoDecoder, pView: *mut ID3D11VideoDecoderOutputView, + ContentKeySize: UINT, pContentKey: *const c_void + ) -> HRESULT, + fn DecoderEndFrame(&mut self, pDecoder: *mut ID3D11VideoDecoder) -> HRESULT, + fn SubmitDecoderBuffers( + &mut self, pDecoder: *mut ID3D11VideoDecoder, NumBuffers: UINT, + pBufferDesc: *const D3D11_VIDEO_DECODER_BUFFER_DESC + ) -> HRESULT, + fn DecoderExtension( + &mut self, pDecoder: *mut ID3D11VideoDecoder, + pExtensionData: *const D3D11_VIDEO_DECODER_EXTENSION + ) -> HRESULT, + fn VideoProcessorSetOutputTargetRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL, pRect: *const RECT + ) -> (), + fn VideoProcessorSetOutputBackgroundColor( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, YCbCr: BOOL, pRect: *const RECT + ) -> (), + fn VideoProcessorSetOutputColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pColorSpace: *const D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> HRESULT, + fn VideoProcessorSetOutputAlphaFillMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + AlphaFillMode: D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE, StreamIndex: UINT + ) -> (), + fn VideoProcessorSetOutputConstriction( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL, Size: SIZE + ) -> (), + fn VideoProcessorSetOutputStereoMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enable: BOOL + ) -> (), + fn VideoProcessorSetOutputExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pExtensionGuid: *const GUID, + DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorGetOutputTargetRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, Enabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetOutputBackgroundColor( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pYCbCr: *mut BOOL, + pColor: *mut D3D11_VIDEO_COLOR + ) -> (), + fn VideoProcessorGetOutputColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pColorSpace: *mut D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorGetOutputAlphaFillMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pAlphaFillMode: *mut D3D11_VIDEO_PROCESSOR_ALPHA_FILL_MODE, pStreamIndex: *mut UINT + ) -> (), + fn VideoProcessorGetOutputConstriction( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pEnabled: *mut BOOL, + pSize: *mut SIZE + ) -> (), + fn VideoProcessorGetOutputStereoMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pEnabled: *mut BOOL + ) -> (), + fn VideoProcessorGetOutputExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, pExtensionGuid: *const GUID, + DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorSetStreamFrameFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + FrameFormat: D3D11_VIDEO_FRAME_FORMAT + ) -> (), + fn VideoProcessorSetStreamColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pColorSpace: *const D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorSetStreamOutputRate( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + OutputRate: D3D11_VIDEO_PROCESSOR_OUTPUT_RATE, RepeatFrame: BOOL, + pCustomRate: *const DXGI_RATIONAL + ) -> (), + fn VideoProcessorSetStreamSourceRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pRect: *const RECT + ) -> (), + fn VideoProcessorSetStreamDestRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pRect: *const RECT + ) -> (), + fn VideoProcessorSetStreamAlpha( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Alpha: FLOAT + ) -> (), + fn VideoProcessorSetStreamPalette( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Count: UINT, + pEntries: *const UINT + ) -> (), + fn VideoProcessorSetStreamPixelAspectRatio( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + pSourceAspectRatio: *const DXGI_RATIONAL, pDestinationAspectRatio: *const DXGI_RATIONAL + ) -> (), + fn VideoProcessorSetStreamLumaKey( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Lower: FLOAT, Upper: FLOAT + ) -> (), + fn VideoProcessorSetStreamStereoFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Format: D3D11_VIDEO_PROCESSOR_STEREO_FORMAT, LeftViewFrame0: BOOL, BaseViewFrame0: BOOL, + FlipMode: D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE + ) -> (), + fn VideoProcessorSetStreamAutoProcessingMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL + ) -> (), + fn VideoProcessorSetStreamFilter( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + Filter: D3D11_VIDEO_PROCESSOR_FILTER, Enable: BOOL, Level: c_int + ) -> (), + fn VideoProcessorSetStreamExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pExtensionGuid: *const GUID, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorGetStreamFrameFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pFrameFormat: *mut D3D11_VIDEO_FRAME_FORMAT + ) -> (), + fn VideoProcessorGetStreamColorSpace( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pColorSpace: *mut D3D11_VIDEO_PROCESSOR_COLOR_SPACE + ) -> (), + fn VideoProcessorGetStreamOutputRate( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pOutputRate: *mut D3D11_VIDEO_PROCESSOR_OUTPUT_RATE, pRepeatFrame: *mut BOOL, + pCustomRate: *mut DXGI_RATIONAL + ) -> (), + fn VideoProcessorGetStreamSourceRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetStreamDestRect( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pRect: *mut RECT + ) -> (), + fn VideoProcessorGetStreamAlpha( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pAlpha: *mut FLOAT + ) -> (), + fn VideoProcessorGetStreamPalette( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Count: UINT, + pEntries: *mut UINT + ) -> (), + fn VideoProcessorGetStreamPixelAspectRatio( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pSourceAspectRatio: *mut DXGI_RATIONAL, + pDestinationAspectRatio: *mut DXGI_RATIONAL + ) -> (), + fn VideoProcessorGetStreamLumaKey( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pLower: *mut FLOAT, pUpper: *mut FLOAT + ) -> (), + fn VideoProcessorGetStreamStereoFormat( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL, pFormat: *mut D3D11_VIDEO_PROCESSOR_STEREO_FORMAT, + pLeftViewFrame0: *mut BOOL, pBaseViewFrame0: *mut BOOL, + pFlipMode: *mut D3D11_VIDEO_PROCESSOR_STEREO_FLIP_MODE, MonoOffset: *mut c_int + ) -> (), + fn VideoProcessorGetStreamAutoProcessingMode( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnabled: *mut BOOL + ) -> (), + fn VideoProcessorGetStreamFilter( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + Filter: D3D11_VIDEO_PROCESSOR_FILTER, pEnabled: *mut BOOL, pLevel: *mut c_int + ) -> (), + fn VideoProcessorGetStreamExtension( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pExtensionGuid: *const GUID, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn VideoProcessorBlt( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, + pView: *mut ID3D11VideoProcessorOutputView, OutputFrame: UINT, StreamCount: UINT, + pStreams: *const D3D11_VIDEO_PROCESSOR_STREAM + ) -> HRESULT, + fn NegotiateCryptoSessionKeyExchange( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn EncryptionBlt( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, pSrcSurface: *mut ID3D11Texture2D, + pDstSurface: *mut ID3D11Texture2D, IVSize: UINT, pIV: *mut c_void + ) -> HRESULT, + fn DecryptionBlt( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, pSrcSurface: *mut ID3D11Texture2D, + pDstSurface: *mut ID3D11Texture2D, pEncryptedBlockInfo: *mut D3D11_ENCRYPTED_BLOCK_INFO, + ContentKeySize: UINT, pContentKey: *const c_void, IVSize: UINT, pIV: *mut c_void + ) -> HRESULT, + fn StartSessionKeyRefresh( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, RandomNumberSize: UINT, + pRandomNumber: *mut c_void + ) -> HRESULT, + fn FinishSessionKeyRefresh(&mut self, pCryptoSession: *mut ID3D11CryptoSession) -> HRESULT, + fn GetEncryptionBltKey( + &mut self, pCryptoSession: *mut ID3D11CryptoSession, KeySize: UINT, + pReadbackKey: *mut c_void + ) -> HRESULT, + fn NegotiateAuthenticatedChannelKeyExchange( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, DataSize: UINT, pData: *mut c_void + ) -> HRESULT, + fn QueryAuthenticatedChannel( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, InputSize: UINT, + pInput: *const c_void, OutputSize: UINT, pOutput: *mut c_void + ) -> HRESULT, + fn ConfigureAuthenticatedChannel( + &mut self, pChannel: *mut ID3D11AuthenticatedChannel, InputSize: UINT, + pInput: *const c_void, pOutput: *mut D3D11_AUTHENTICATED_CONFIGURE_OUTPUT + ) -> HRESULT, + fn VideoProcessorSetStreamRotation( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, Enable: BOOL, + Rotation: D3D11_VIDEO_PROCESSOR_ROTATION + ) -> HRESULT, + fn VideoProcessorGetStreamRotation( + &mut self, pVideoProcessor: *mut ID3D11VideoProcessor, StreamIndex: UINT, + pEnable: *mut BOOL, pRotation: *mut D3D11_VIDEO_PROCESSOR_ROTATION + ) -> HRESULT +}} +RIDL!{interface ID3D11VideoDevice(ID3D11VideoDeviceVtbl): IUnknown(IUnknownVtbl) { + fn CreateVideoDecoder( + &mut self, pVideoDesc: *const D3D11_VIDEO_DECODER_DESC, + pConfig: *const D3D11_VIDEO_DECODER_CONFIG, ppDecoder: *mut *mut ID3D11VideoDecoder + ) -> HRESULT, + fn CreateVideoProcessor( + &mut self, pEnum: *mut ID3D11VideoProcessorEnumerator, RateConversionIndex: UINT, + ppVideoProcessor: *mut *mut ID3D11VideoProcessor + ) -> HRESULT, + fn CreateAuthenticatedChannel( + &mut self, ChannelType: D3D11_AUTHENTICATED_CHANNEL_TYPE, + ppAuthenticatedChannel: *mut *mut ID3D11AuthenticatedChannel + ) -> HRESULT, + fn CreateCryptoSession( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, + pKeyExchangeType: *const GUID, ppCryptoSession: *mut *mut ID3D11CryptoSession + ) -> HRESULT, + fn CreateVideoDecoderOutputView( + &mut self, pResource: *mut ID3D11Resource, + pDesc: *const D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC, + ppVDOVView: *mut *mut ID3D11VideoDecoderOutputView + ) -> HRESULT, + fn CreateVideoProcessorInputView( + &mut self, pResource: *mut ID3D11Resource, pEnum: *mut ID3D11VideoProcessorEnumerator, + pDesc: *const D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, + ppVPIView: *mut *mut ID3D11VideoProcessorInputView + ) -> HRESULT, + fn CreateVideoProcessorOutputView( + &mut self, pResource: *mut ID3D11Resource, pEnum: *mut ID3D11VideoProcessorEnumerator, + pDesc: *const D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, + ppVPOView: *mut *mut ID3D11VideoProcessorOutputView + ) -> HRESULT, + fn CreateVideoProcessorEnumerator( + &mut self, pDesc: *const D3D11_VIDEO_PROCESSOR_CONTENT_DESC, + ppEnum: *mut *mut ID3D11VideoProcessorEnumerator + ) -> HRESULT, + fn GetVideoDecoderProfileCount(&mut self) -> UINT, + fn GetVideoDecoderProfile(&mut self, Index: UINT, pDecoderProfile: *mut GUID) -> HRESULT, + fn CheckVideoDecoderFormat( + &mut self, pDecoderProfile: *const GUID, Format: DXGI_FORMAT, pSupported: *mut BOOL + ) -> HRESULT, + fn GetVideoDecoderConfigCount( + &mut self, pDesc: *const D3D11_VIDEO_DECODER_DESC, pCount: *mut UINT + ) -> HRESULT, + fn GetVideoDecoderConfig( + &mut self, pDesc: *const D3D11_VIDEO_DECODER_DESC, Index: UINT, + pConfig: *mut D3D11_VIDEO_DECODER_CONFIG + ) -> HRESULT, + fn GetContentProtectionCaps( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, + pCaps: *mut D3D11_VIDEO_CONTENT_PROTECTION_CAPS + ) -> HRESULT, + fn CheckCryptoKeyExchange( + &mut self, pCryptoType: *const GUID, pDecoderProfile: *const GUID, Index: UINT, + pKeyExchangeType: *mut GUID + ) -> HRESULT, + fn SetPrivateData( &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT +}} +RIDL!{interface ID3D11Device(ID3D11DeviceVtbl): IUnknown(IUnknownVtbl) { + fn CreateBuffer( + &mut self, pDesc: *const D3D11_BUFFER_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppBuffer: *mut *mut ID3D11Buffer + ) -> HRESULT, + fn CreateTexture1D( + &mut self, pDesc: *const D3D11_TEXTURE1D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture1D: *mut *mut ID3D11Texture1D + ) -> HRESULT, + fn CreateTexture2D( + &mut self, pDesc: *const D3D11_TEXTURE2D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture2D: *mut *mut ID3D11Texture2D + ) -> HRESULT, + fn CreateTexture3D( + &mut self, pDesc: *const D3D11_TEXTURE3D_DESC, pInitialData: *const D3D11_SUBRESOURCE_DATA, + ppTexture3D: *mut *mut ID3D11Texture3D + ) -> HRESULT, + fn CreateShaderResourceView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_SHADER_RESOURCE_VIEW_DESC, + ppSRView: *mut *mut ID3D11ShaderResourceView + ) -> HRESULT, + fn CreateUnorderedAccessView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_UNORDERED_ACCESS_VIEW_DESC, + ppUAView: *mut *mut ID3D11UnorderedAccessView + ) -> HRESULT, + fn CreateRenderTargetView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_RENDER_TARGET_VIEW_DESC, + ppRTView: *mut *mut ID3D11RenderTargetView + ) -> HRESULT, + fn CreateDepthStencilView( + &mut self, pResource: *mut ID3D11Resource, pDesc: *const D3D11_DEPTH_STENCIL_VIEW_DESC, + ppDepthStencilView: *mut *mut ID3D11DepthStencilView + ) -> HRESULT, + fn CreateInputLayout( + &mut self, pInputElementDescs: *const D3D11_INPUT_ELEMENT_DESC, NumElements: UINT, + pShaderBytecodeWithInputSignature: *const c_void, BytecodeLength: SIZE_T, + ppInputLayout: *mut *mut ID3D11InputLayout + ) -> HRESULT, + fn CreateVertexShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppVertexShader: *mut *mut ID3D11VertexShader + ) -> HRESULT, + fn CreateGeometryShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppGeometryShader: *mut *mut ID3D11GeometryShader + ) -> HRESULT, + fn CreateGeometryShaderWithStreamOutput( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pSODeclaration: *const D3D11_SO_DECLARATION_ENTRY, NumEntries: UINT, + pBufferStrides: *const UINT, NumStrides: UINT, RasterizedStream: UINT, + pClassLinkage: *mut ID3D11ClassLinkage, ppGeometryShader: *mut *mut ID3D11GeometryShader + ) -> HRESULT, + fn CreatePixelShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppPixelShader: *mut *mut ID3D11PixelShader + ) -> HRESULT, + fn CreateHullShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppHullShader: *mut *mut ID3D11HullShader + ) -> HRESULT, + fn CreateDomainShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppDomainShader: *mut *mut ID3D11DomainShader + ) -> HRESULT, + fn CreateComputeShader( + &mut self, pShaderBytecode: *const c_void, BytecodeLength: SIZE_T, + pClassLinkage: *mut ID3D11ClassLinkage, ppComputeShader: *mut *mut ID3D11ComputeShader + ) -> HRESULT, + fn CreateClassLinkage(&mut self, ppLinkage: *mut *mut ID3D11ClassLinkage) -> HRESULT, + fn CreateBlendState( + &mut self, pBlendStateDesc: *const D3D11_BLEND_DESC, + ppBlendState: *mut *mut ID3D11BlendState + ) -> HRESULT, + fn CreateDepthStencilState( + &mut self, pDepthStencilDesc: *const D3D11_DEPTH_STENCIL_DESC, + ppDepthStencilState: *mut *mut ID3D11DepthStencilState + ) -> HRESULT, + fn CreateRasterizerState( + &mut self, pRasterizerDesc: *const D3D11_RASTERIZER_DESC, + ppRasterizerState: *mut *mut ID3D11RasterizerState + ) -> HRESULT, + fn CreateSamplerState( + &mut self, pSamplerDesc: *const D3D11_SAMPLER_DESC, + ppSamplerState: *mut *mut ID3D11SamplerState + ) -> HRESULT, + fn CreateQuery( + &mut self, pQueryDesc: *const D3D11_QUERY_DESC, ppQuery: *mut *mut ID3D11Query + ) -> HRESULT, + fn CreatePredicate( + &mut self, pPredicateDesc: *const D3D11_QUERY_DESC, ppPredicate: *mut *mut ID3D11Predicate + ) -> HRESULT, + fn CreateCounter( + &mut self, pCounterDesc: *const D3D11_COUNTER_DESC, ppCounter: *mut *mut ID3D11Counter + ) -> HRESULT, + fn CreateDeferredContext( + &mut self, ContextFlags: UINT, ppDeferredContext: *mut *mut ID3D11DeviceContext + ) -> HRESULT, + fn OpenSharedResource( + &mut self, hResource: HANDLE, ReturnedInterface: REFIID, ppResource: *mut *mut c_void + ) -> HRESULT, + fn CheckFormatSupport( + &mut self, Format: DXGI_FORMAT, pFormatSupport: *mut UINT + ) -> HRESULT, + fn CheckMultisampleQualityLevels( + &mut self, Format: DXGI_FORMAT, SampleCount: UINT, pNumQualityLevels: *mut UINT + ) -> HRESULT, + fn CheckCounterInfo(&mut self, pCounterInfo: *mut D3D11_COUNTER_INFO) -> (), + fn CheckCounter( + &mut self, pDesc: *const D3D11_COUNTER_DESC, pType: *mut D3D11_COUNTER_TYPE, + pActiveCounters: *mut UINT, szName: LPSTR, pNameLength: *mut UINT, szUnits: LPSTR, + pUnitsLength: *mut UINT, szDescription: LPSTR, pDescriptionLength: *mut UINT + ) -> HRESULT, + fn CheckFeatureSupport( + &mut self, Feature: D3D11_FEATURE, pFeatureSupportData: *mut c_void, + FeatureSupportDataSize: UINT + ) -> HRESULT, + fn GetPrivateData( + &mut self, guid: REFGUID, pDataSize: *mut UINT, pData: *mut c_void + ) -> HRESULT, + fn SetPrivateData( + &mut self, guid: REFGUID, DataSize: UINT, pData: *const c_void + ) -> HRESULT, + fn SetPrivateDataInterface(&mut self, guid: REFGUID, pData: *const IUnknown) -> HRESULT, + fn GetFeatureLevel(&mut self) -> D3D_FEATURE_LEVEL, + fn GetCreationFlags(&mut self) -> UINT, + fn GetDeviceRemovedReason(&mut self) -> HRESULT, + fn GetImmediateContext(&mut self, ppImmediateContext: *mut *mut ID3D11DeviceContext) -> (), + fn SetExceptionMode(&mut self, RaiseFlags: UINT) -> HRESULT, + fn GetExceptionMode(&mut self) -> UINT +}} +FLAGS!{enum D3D11_CREATE_DEVICE_FLAG { + D3D11_CREATE_DEVICE_SINGLETHREADED = 0x1, + D3D11_CREATE_DEVICE_DEBUG = 0x2, + D3D11_CREATE_DEVICE_SWITCH_TO_REF = 0x4, + D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS = 0x8, + D3D11_CREATE_DEVICE_BGRA_SUPPORT = 0x20, + D3D11_CREATE_DEVICE_DEBUGGABLE = 0x40, + D3D11_CREATE_DEVICE_PREVENT_ALTERING_LAYER_SETTINGS_FROM_REGISTRY = 0x80, + D3D11_CREATE_DEVICE_DISABLE_GPU_TIMEOUT = 0x100, + D3D11_CREATE_DEVICE_VIDEO_SUPPORT = 0x800, +}} +pub const D3D11_SDK_VERSION: DWORD = 7; + +pub fn D3D11CalcSubresource(MipSlice: ::UINT, ArraySlice: ::UINT, MipLevels: ::UINT) -> ::UINT { + MipSlice + ArraySlice * MipLevels +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d11shader.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d11shader.rs new file mode 100644 index 0000000..8328abe --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d11shader.rs @@ -0,0 +1,320 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +ENUM!{enum D3D11_SHADER_VERSION_TYPE { + D3D11_SHVER_PIXEL_SHADER = 0, + D3D11_SHVER_VERTEX_SHADER = 1, + D3D11_SHVER_GEOMETRY_SHADER = 2, + D3D11_SHVER_HULL_SHADER = 3, + D3D11_SHVER_DOMAIN_SHADER = 4, + D3D11_SHVER_COMPUTE_SHADER = 5, + D3D11_SHVER_RESERVED0 = 0xFFF0, +}} +pub const D3D_RETURN_PARAMETER_INDEX: c_int = -1; +pub type D3D11_RESOURCE_RETURN_TYPE = D3D_RESOURCE_RETURN_TYPE; +pub type D3D11_CBUFFER_TYPE = D3D_CBUFFER_TYPE; +STRUCT!{struct D3D11_SIGNATURE_PARAMETER_DESC { + SemanticName: LPCSTR, + SemanticIndex: UINT, + Register: UINT, + SystemValueType: D3D_NAME, + ComponentType: D3D_REGISTER_COMPONENT_TYPE, + Mask: BYTE, + ReadWriteMask: BYTE, + Stream: UINT, + MinPrecision: D3D_MIN_PRECISION, +}} +STRUCT!{struct D3D11_SHADER_BUFFER_DESC { + Name: LPCSTR, + Type: D3D_CBUFFER_TYPE, + Variables: UINT, + Size: UINT, + uFlags: UINT, +}} +STRUCT!{struct D3D11_SHADER_VARIABLE_DESC { + Name: LPCSTR, + StartOffset: UINT, + Size: UINT, + uFlags: UINT, + DefaultValue: LPVOID, + StartTexture: UINT, + TextureSize: UINT, + StartSampler: UINT, + SamplerSize: UINT, +}} +STRUCT!{struct D3D11_SHADER_TYPE_DESC { + Class: D3D_SHADER_VARIABLE_CLASS, + Type: D3D_SHADER_VARIABLE_TYPE, + Rows: UINT, + Columns: UINT, + Elements: UINT, + Members: UINT, + Offset: UINT, + Name: LPCSTR, +}} +pub type D3D11_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN; +pub type D3D11_TESSELLATOR_PARTITIONING = D3D_TESSELLATOR_PARTITIONING; +pub type D3D11_TESSELLATOR_OUTPUT_PRIMITIVE = D3D_TESSELLATOR_OUTPUT_PRIMITIVE; +STRUCT!{struct D3D11_SHADER_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InputParameters: UINT, + OutputParameters: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + CutInstructionCount: UINT, + EmitInstructionCount: UINT, + GSOutputTopology: D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: UINT, + InputPrimitive: D3D_PRIMITIVE, + PatchConstantParameters: UINT, + cGSInstanceCount: UINT, + cControlPoints: UINT, + HSOutputPrimitive: D3D_TESSELLATOR_OUTPUT_PRIMITIVE, + HSPartitioning: D3D_TESSELLATOR_PARTITIONING, + TessellatorDomain: D3D_TESSELLATOR_DOMAIN, + cBarrierInstructions: UINT, + cInterlockedInstructions: UINT, + cTextureStoreInstructions: UINT, +}} +STRUCT!{struct D3D11_SHADER_INPUT_BIND_DESC { + Name: LPCSTR, + Type: D3D_SHADER_INPUT_TYPE, + BindPoint: UINT, + BindCount: UINT, + uFlags: UINT, + ReturnType: D3D_RESOURCE_RETURN_TYPE, + Dimension: D3D_SRV_DIMENSION, + NumSamples: UINT, +}} +pub const D3D_SHADER_REQUIRES_DOUBLES: UINT64 = 0x00000001; +pub const D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL: UINT64 = 0x00000002; +pub const D3D_SHADER_REQUIRES_UAVS_AT_EVERY_STAGE: UINT64 = 0x00000004; +pub const D3D_SHADER_REQUIRES_64_UAVS: UINT64 = 0x00000008; +pub const D3D_SHADER_REQUIRES_MINIMUM_PRECISION: UINT64 = 0x00000010; +pub const D3D_SHADER_REQUIRES_11_1_DOUBLE_EXTENSIONS: UINT64 = 0x00000020; +pub const D3D_SHADER_REQUIRES_11_1_SHADER_EXTENSIONS: UINT64 = 0x00000040; +pub const D3D_SHADER_REQUIRES_LEVEL_9_COMPARISON_FILTERING: UINT64 = 0x00000080; +pub const D3D_SHADER_REQUIRES_TILED_RESOURCES: UINT64 = 0x00000100; +STRUCT!{struct D3D11_LIBRARY_DESC { + Creator: LPCSTR, + Flags: UINT, + FunctionCount: UINT, +}} +STRUCT!{struct D3D11_FUNCTION_DESC { + Version: UINT, + Creator: LPCSTR, + Flags: UINT, + ConstantBuffers: UINT, + BoundResources: UINT, + InstructionCount: UINT, + TempRegisterCount: UINT, + TempArrayCount: UINT, + DefCount: UINT, + DclCount: UINT, + TextureNormalInstructions: UINT, + TextureLoadInstructions: UINT, + TextureCompInstructions: UINT, + TextureBiasInstructions: UINT, + TextureGradientInstructions: UINT, + FloatInstructionCount: UINT, + IntInstructionCount: UINT, + UintInstructionCount: UINT, + StaticFlowControlCount: UINT, + DynamicFlowControlCount: UINT, + MacroInstructionCount: UINT, + ArrayInstructionCount: UINT, + MovInstructionCount: UINT, + MovcInstructionCount: UINT, + ConversionInstructionCount: UINT, + BitwiseInstructionCount: UINT, + MinFeatureLevel: D3D_FEATURE_LEVEL, + RequiredFeatureFlags: UINT64, + Name: LPCSTR, + FunctionParameterCount: INT, + HasReturn: BOOL, + Has10Level9VertexShader: BOOL, + Has10Level9PixelShader: BOOL, +}} +STRUCT!{struct D3D11_PARAMETER_DESC { + Name: LPCSTR, + SemanticName: LPCSTR, + Type: D3D_SHADER_VARIABLE_TYPE, + Class: D3D_SHADER_VARIABLE_CLASS, + Rows: UINT, + Columns: UINT, + InterpolationMode: D3D_INTERPOLATION_MODE, + Flags: D3D_PARAMETER_FLAGS, + FirstInRegister: UINT, + FirstInComponent: UINT, + FirstOutRegister: UINT, + FirstOutComponent: UINT, +}} +RIDL!{interface ID3D11ShaderReflectionType(ID3D11ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_TYPE_DESC) -> HRESULT, + fn GetMemberTypeByIndex(&mut self, Index: UINT) -> *mut ID3D11ShaderReflectionType, + fn GetMemberTypeByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: UINT) -> LPCSTR, + fn IsEqual(&mut self, pType: *mut ID3D11ShaderReflectionType) -> HRESULT, + fn GetSubType(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetBaseClass(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetNumInterfaces(&mut self) -> UINT, + fn GetInterfaceByIndex(&mut self, uIndex: UINT) -> *mut ID3D11ShaderReflectionType, + fn IsOfType(&mut self, pType: *mut ID3D11ShaderReflectionType) -> HRESULT, + fn ImplementsInterface(&mut self, pBase: *mut ID3D11ShaderReflectionType) -> HRESULT +}} +RIDL!{interface ID3D11ShaderReflectionVariable(ID3D11ShaderReflectionVariableVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_VARIABLE_DESC) -> HRESULT, + fn GetType(&mut self) -> *mut ID3D11ShaderReflectionType, + fn GetBuffer(&mut self) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetInterfaceSlot(&mut self, uArrayIndex: UINT) -> UINT +}} +RIDL!{interface ID3D11ShaderReflectionConstantBuffer(ID3D11ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_BUFFER_DESC) -> HRESULT, + fn GetVariableByIndex(&mut self, Index: UINT) -> *mut ID3D11ShaderReflectionVariable, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable +}} +RIDL!{interface ID3D11ShaderReflection(ID3D11ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_SHADER_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: UINT + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetPatchConstantParameterDesc( + &mut self, ParameterIndex: UINT, pDesc: *mut D3D11_SIGNATURE_PARAMETER_DESC + ) -> HRESULT, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: LPCSTR, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetMovInstructionCount(&mut self) -> UINT, + fn GetMovcInstructionCount(&mut self) -> UINT, + fn GetConversionInstructionCount(&mut self) -> UINT, + fn GetBitwiseInstructionCount(&mut self) -> UINT, + fn GetGSInputPrimitive(&mut self) -> D3D_PRIMITIVE, + fn IsSampleFrequencyShader(&mut self) -> BOOL, + fn GetNumInterfaceSlots(&mut self) -> UINT, + fn GetMinFeatureLevel(&mut self, pLevel: *mut D3D_FEATURE_LEVEL) -> HRESULT, + fn GetThreadGroupSize( + &mut self, pSizeX: *mut UINT, pSizeY: *mut UINT, pSizeZ: *mut UINT + ) -> UINT, + fn GetRequiresFlags(&mut self) -> UINT64 +}} +RIDL!{interface ID3D11LibraryReflection(ID3D11LibraryReflectionVtbl): IUnknown(IUnknownVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_LIBRARY_DESC) -> HRESULT, + fn GetFunctionByIndex(&mut self, FunctionIndex: INT) -> *mut ID3D11FunctionReflection +}} +RIDL!{interface ID3D11FunctionReflection(ID3D11FunctionReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_FUNCTION_DESC) -> HRESULT, + fn GetConstantBufferByIndex( + &mut self, BufferIndex: UINT + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: LPCSTR + ) -> *mut ID3D11ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: UINT, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetVariableByName(&mut self, Name: LPCSTR) -> *mut ID3D11ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: LPCSTR, pDesc: *mut D3D11_SHADER_INPUT_BIND_DESC + ) -> HRESULT, + fn GetFunctionParameter( + &mut self, ParameterIndex: INT + ) -> *mut ID3D11FunctionParameterReflection +}} +RIDL!{interface ID3D11FunctionParameterReflection(ID3D11FunctionParameterReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut D3D11_PARAMETER_DESC) -> HRESULT +}} +RIDL!{interface ID3D11Module(ID3D11ModuleVtbl): IUnknown(IUnknownVtbl) { + fn CreateInstance( + &mut self, pNamespace: LPCSTR, ppModuleInstance: *mut *mut ID3D11ModuleInstance + ) -> HRESULT +}} +RIDL!{interface ID3D11ModuleInstance(ID3D11ModuleInstanceVtbl): IUnknown(IUnknownVtbl) { + fn BindConstantBuffer(&mut self, uSrcSlot: UINT, uDstSlot: UINT, cbDstOffset: UINT) -> HRESULT, + fn BindConstantBufferByName( + &mut self, pName: LPCSTR, uDstSlot: UINT, cbDstOffset: UINT + ) -> HRESULT, + fn BindResource(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindResourceByName(&mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindSampler(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindSamplerByName(&mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindUnorderedAccessView(&mut self, uSrcSlot: UINT, uDstSlot: UINT, uCount: UINT) -> HRESULT, + fn BindUnorderedAccessViewByName( + &mut self, pName: LPCSTR, uDstSlot: UINT, uCount: UINT + ) -> HRESULT, + fn BindResourceAsUnorderedAccessView( + &mut self, uSrcSrvSlot: UINT, uDstUavSlot: UINT, uCount: UINT + ) -> HRESULT, + fn BindResourceAsUnorderedAccessViewByName( + &mut self, pSrvName: LPCSTR, uDstUavSlot: UINT, uCount: UINT + ) -> HRESULT +}} +RIDL!{interface ID3D11Linker(ID3D11LinkerVtbl): IUnknown(IUnknownVtbl) { + fn Link( + &mut self, pEntry: *mut ID3D11ModuleInstance, pEntryName: LPCSTR, pTargetName: LPCSTR, + uFlags: UINT, ppShaderBlob: *mut *mut ID3DBlob, ppErrorBuffer: *mut *mut ID3DBlob + ) -> HRESULT, + fn UseLibrary(&mut self, pLibraryMI: *mut ID3D11ModuleInstance) -> HRESULT, + fn AddClipPlaneFromCBuffer(&mut self, uCBufferSlot: UINT, uCBufferEntry: UINT) -> HRESULT +}} +RIDL!{interface ID3D11LinkingNode(ID3D11LinkingNodeVtbl): IUnknown(IUnknownVtbl) {}} +RIDL!{interface ID3D11FunctionLinkingGraph(ID3D11FunctionLinkingGraphVtbl): IUnknown(IUnknownVtbl) { + fn CreateModuleInstance( + &mut self, ppModuleInstance: *mut *mut ID3D11ModuleInstance, + ppErrorBuffer: *mut *mut ID3DBlob + ) -> HRESULT, + fn SetInputSignature( + &mut self, pInputParameters: *const D3D11_PARAMETER_DESC, cInputParameters: UINT, + ppInputNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn SetOutputSignature( + &mut self, pOutputParameters: *const D3D11_PARAMETER_DESC, cOutputParameters: UINT, + ppOutputNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn CallFunction( + &mut self, pModuleInstanceNamespace: LPCSTR, + pModuleWithFunctionPrototype: *mut ID3D11Module, pFunctionName: LPCSTR, + ppCallNode: *mut *mut ID3D11LinkingNode + ) -> HRESULT, + fn PassValue( + &mut self, pSrcNode: *mut ID3D11LinkingNode, SrcParameterIndex: INT, + pDstNode: *mut ID3D11LinkingNode, DstParameterIndex: INT + ) -> HRESULT, + fn PassValueWithSwizzle( + &mut self, pSrcNode: *mut ID3D11LinkingNode, SrcParameterIndex: INT, pSrcSwizzle: LPCSTR, + pDstNode: *mut ID3D11LinkingNode, DstParameterIndex: INT, pDstSwizzle: LPCSTR + ) -> HRESULT, + fn GetLastError(&mut self, ppErrorBuffer: *mut *mut ID3DBlob) -> HRESULT, + fn GenerateHlsl(&mut self, uFlags: UINT, ppBuffer: *mut *mut ID3DBlob) -> HRESULT +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d12.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12.rs new file mode 100644 index 0000000..ac6ae3b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12.rs @@ -0,0 +1,2324 @@ +// Copyright © 2015, Dmitry Roschin +// Licensed under the MIT License +pub const D3D12_16BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xffff; +pub const D3D12_32BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xffffffff; +pub const D3D12_8BIT_INDEX_STRIP_CUT_VALUE: ::UINT = 0xff; +pub const D3D12_ANISOTROPIC_FILTERING_BIT: ::UINT = 0x40; +pub const D3D12_APPEND_ALIGNED_ELEMENT: ::UINT = 0xffffffff; +pub const D3D12_ARRAY_AXIS_ADDRESS_RANGE_BIT_COUNT: ::UINT = 9; +pub const D3D12_CLIP_OR_CULL_DISTANCE_COUNT: ::UINT = 8; +pub const D3D12_CLIP_OR_CULL_DISTANCE_ELEMENT_COUNT: ::UINT = 2; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT: ::UINT = 14; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_HW_SLOT_COUNT: ::UINT = 15; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT: ::UINT = 16; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_COUNT: ::UINT = 15; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_CONSTANT_BUFFER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_FLOWCONTROL_NESTING_LIMIT: ::UINT = 64; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_CONSTANT_BUFFER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_IMMEDIATE_VALUE_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_COUNT: ::UINT = 128; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 128; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_COUNT: ::UINT = 16; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_COMMONSHADER_SAMPLER_SLOT_COUNT: ::UINT = 16; +pub const D3D12_COMMONSHADER_SUBROUTINE_NESTING_LIMIT: ::UINT = 32; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_COUNT: ::UINT = 4096; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_READS_PER_INST: ::UINT = 3; +pub const D3D12_COMMONSHADER_TEMP_REGISTER_READ_PORTS: ::UINT = 3; +pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MAX: ::UINT = 10; +pub const D3D12_COMMONSHADER_TEXCOORD_RANGE_REDUCTION_MIN: ::INT = -10; +pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_NEGATIVE: ::INT = -8; +pub const D3D12_COMMONSHADER_TEXEL_OFFSET_MAX_POSITIVE: ::UINT = 7; +pub const D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET00_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET00_MAX_NUM_THREADS_PER_GROUP: ::UINT = 64; +pub const D3D12_CS_4_X_BUCKET01_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 240; +pub const D3D12_CS_4_X_BUCKET01_MAX_NUM_THREADS_PER_GROUP: ::UINT = 68; +pub const D3D12_CS_4_X_BUCKET02_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 224; +pub const D3D12_CS_4_X_BUCKET02_MAX_NUM_THREADS_PER_GROUP: ::UINT = 72; +pub const D3D12_CS_4_X_BUCKET03_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 208; +pub const D3D12_CS_4_X_BUCKET03_MAX_NUM_THREADS_PER_GROUP: ::UINT = 76; +pub const D3D12_CS_4_X_BUCKET04_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 192; +pub const D3D12_CS_4_X_BUCKET04_MAX_NUM_THREADS_PER_GROUP: ::UINT = 84; +pub const D3D12_CS_4_X_BUCKET05_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 176; +pub const D3D12_CS_4_X_BUCKET05_MAX_NUM_THREADS_PER_GROUP: ::UINT = 92; +pub const D3D12_CS_4_X_BUCKET06_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 160; +pub const D3D12_CS_4_X_BUCKET06_MAX_NUM_THREADS_PER_GROUP: ::UINT = 100; +pub const D3D12_CS_4_X_BUCKET07_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 144; +pub const D3D12_CS_4_X_BUCKET07_MAX_NUM_THREADS_PER_GROUP: ::UINT = 112; +pub const D3D12_CS_4_X_BUCKET08_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 128; +pub const D3D12_CS_4_X_BUCKET08_MAX_NUM_THREADS_PER_GROUP: ::UINT = 128; +pub const D3D12_CS_4_X_BUCKET09_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 112; +pub const D3D12_CS_4_X_BUCKET09_MAX_NUM_THREADS_PER_GROUP: ::UINT = 144; +pub const D3D12_CS_4_X_BUCKET10_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 96; +pub const D3D12_CS_4_X_BUCKET10_MAX_NUM_THREADS_PER_GROUP: ::UINT = 168; +pub const D3D12_CS_4_X_BUCKET11_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 80; +pub const D3D12_CS_4_X_BUCKET11_MAX_NUM_THREADS_PER_GROUP: ::UINT = 204; +pub const D3D12_CS_4_X_BUCKET12_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 64; +pub const D3D12_CS_4_X_BUCKET12_MAX_NUM_THREADS_PER_GROUP: ::UINT = 256; +pub const D3D12_CS_4_X_BUCKET13_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 48; +pub const D3D12_CS_4_X_BUCKET13_MAX_NUM_THREADS_PER_GROUP: ::UINT = 340; +pub const D3D12_CS_4_X_BUCKET14_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 32; +pub const D3D12_CS_4_X_BUCKET14_MAX_NUM_THREADS_PER_GROUP: ::UINT = 512; +pub const D3D12_CS_4_X_BUCKET15_MAX_BYTES_TGSM_WRITABLE_PER_THREAD: ::UINT = 16; +pub const D3D12_CS_4_X_BUCKET15_MAX_NUM_THREADS_PER_GROUP: ::UINT = 768; +pub const D3D12_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION: ::UINT = 1; +pub const D3D12_CS_4_X_RAW_UAV_BYTE_ALIGNMENT: ::UINT = 256; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP: ::UINT = 768; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_X: ::UINT = 768; +pub const D3D12_CS_4_X_THREAD_GROUP_MAX_Y: ::UINT = 768; +pub const D3D12_CS_4_X_UAV_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION: ::UINT = 65535; +pub const D3D12_CS_TGSM_REGISTER_COUNT: ::UINT = 8192; +pub const D3D12_CS_TGSM_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_CS_TGSM_RESOURCE_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_CS_TGSM_RESOURCE_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_CS_THREADGROUPID_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADGROUPID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUPFLATTENED_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADIDINGROUP_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADIDINGROUP_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREADID_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_CS_THREADID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_X: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_Y: ::UINT = 1024; +pub const D3D12_CS_THREAD_GROUP_MAX_Z: ::UINT = 64; +pub const D3D12_CS_THREAD_GROUP_MIN_X: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MIN_Y: ::UINT = 1; +pub const D3D12_CS_THREAD_GROUP_MIN_Z: ::UINT = 1; +pub const D3D12_CS_THREAD_LOCAL_TEMP_REGISTER_POOL: ::UINT = 16384; +pub const D3D12_DEFAULT_BLEND_FACTOR_ALPHA: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_BLUE: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_GREEN: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BLEND_FACTOR_RED: ::FLOAT = 1.0; +pub const D3D12_DEFAULT_BORDER_COLOR_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_DEPTH_BIAS: ::UINT = 0; +pub const D3D12_DEFAULT_DEPTH_BIAS_CLAMP: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_MAX_ANISOTROPY: ::UINT = 16; +pub const D3D12_DEFAULT_MIP_LOD_BIAS: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 4194304; +pub const D3D12_DEFAULT_RENDER_TARGET_ARRAY_INDEX: ::UINT = 0; +pub const D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 65536; +pub const D3D12_DEFAULT_SAMPLE_MASK: ::UINT = 0xffffffff; +pub const D3D12_DEFAULT_SCISSOR_ENDX: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_ENDY: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_STARTX: ::UINT = 0; +pub const D3D12_DEFAULT_SCISSOR_STARTY: ::UINT = 0; +pub const D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_STENCIL_READ_MASK: ::UINT = 0xff; +pub const D3D12_DEFAULT_STENCIL_REFERENCE: ::UINT = 0; +pub const D3D12_DEFAULT_STENCIL_WRITE_MASK: ::UINT = 0xff; +pub const D3D12_DEFAULT_VIEWPORT_AND_SCISSORRECT_INDEX: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_HEIGHT: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_MAX_DEPTH: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_VIEWPORT_MIN_DEPTH: ::FLOAT = 0.0; +pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTX: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_TOPLEFTY: ::UINT = 0; +pub const D3D12_DEFAULT_VIEWPORT_WIDTH: ::UINT = 0; +pub const D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND: ::UINT = 0xffffffff; +pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xfffffff7; +pub const D3D12_DRIVER_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff0; +pub const D3D12_DS_INPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: ::UINT = 3968; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_CONTROL_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENTS: ::UINT = 3; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_DOMAIN_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_DS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_DS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_DS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_DS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_FILTER_REDUCTION_TYPE_MASK: ::UINT = 0x3; +pub const D3D12_FILTER_REDUCTION_TYPE_SHIFT: ::UINT = 7; +pub const D3D12_FILTER_TYPE_MASK: ::UINT = 0x3; +pub const D3D12_FLOAT16_FUSED_TOLERANCE_IN_ULP: ::DOUBLE = 0.6; +pub const D3D12_FLOAT32_MAX: ::FLOAT = 3.402823466e+38; +pub const D3D12_FLOAT32_TO_INTEGER_TOLERANCE_IN_ULP: ::FLOAT = 0.6; +pub const D3D12_FLOAT_TO_SRGB_EXPONENT_DENOMINATOR: ::FLOAT = 2.4; +pub const D3D12_FLOAT_TO_SRGB_EXPONENT_NUMERATOR: ::FLOAT = 1.0; +pub const D3D12_FLOAT_TO_SRGB_OFFSET: ::FLOAT = 0.055; +pub const D3D12_FLOAT_TO_SRGB_SCALE_1: ::FLOAT = 12.92; +pub const D3D12_FLOAT_TO_SRGB_SCALE_2: ::FLOAT = 1.055; +pub const D3D12_FLOAT_TO_SRGB_THRESHOLD: ::FLOAT = 0.0031308; +pub const D3D12_FTOI_INSTRUCTION_MAX_INPUT: ::FLOAT = 2147483647.999; +pub const D3D12_FTOI_INSTRUCTION_MIN_INPUT: ::FLOAT = -2147483648.999; +pub const D3D12_FTOU_INSTRUCTION_MAX_INPUT: ::FLOAT = 4294967295.999; +pub const D3D12_FTOU_INSTRUCTION_MIN_INPUT: ::FLOAT = 0.0; +pub const D3D12_GS_INPUT_INSTANCE_ID_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_INSTANCE_ID_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_PRIM_CONST_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_GS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_GS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_GS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_GS_INPUT_REGISTER_VERTICES: ::UINT = 32; +pub const D3D12_GS_MAX_INSTANCE_COUNT: ::UINT = 32; +pub const D3D12_GS_MAX_OUTPUT_VERTEX_COUNT_ACROSS_INSTANCES: ::UINT = 1024; +pub const D3D12_GS_OUTPUT_ELEMENTS: ::UINT = 32; +pub const D3D12_GS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_GS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_GS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_PHASE_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_PHASE_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_HS_CONTROL_POINT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_CONTROL_POINT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_CONTROL_POINT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_FORK_PHASE_INSTANCE_COUNT_UPPER_BOUND: ::UINT = 0xffffffff; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_FORK_INSTANCE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_JOIN_INSTANCE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_INPUT_PRIMITIVE_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_JOIN_PHASE_INSTANCE_COUNT_UPPER_BOUND: ::UINT = 0xffffffff; +pub const D3D12_HS_MAXTESSFACTOR_LOWER_BOUND: ::FLOAT = 1.0; +pub const D3D12_HS_MAXTESSFACTOR_UPPER_BOUND: ::FLOAT = 64.0; +pub const D3D12_HS_OUTPUT_CONTROL_POINTS_MAX_TOTAL_SCALARS: ::UINT = 3968; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_OUTPUT_CONTROL_POINT_ID_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_HS_OUTPUT_PATCH_CONSTANT_REGISTER_SCALAR_COMPONENTS: ::UINT = 128; +pub const D3D12_IA_DEFAULT_INDEX_BUFFER_OFFSET_IN_BYTES: ::UINT = 0; +pub const D3D12_IA_DEFAULT_PRIMITIVE_TOPOLOGY: ::UINT = 0; +pub const D3D12_IA_DEFAULT_VERTEX_BUFFER_OFFSET_IN_BYTES: ::UINT = 0; +pub const D3D12_IA_INDEX_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 1; +pub const D3D12_IA_INSTANCE_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_INTEGER_ARITHMETIC_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_PATCH_MAX_CONTROL_POINT_COUNT: ::UINT = 32; +pub const D3D12_IA_PRIMITIVE_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_ID_BIT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT: ::UINT = 32; +pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENTS_COMPONENTS: ::UINT = 128; +pub const D3D12_IA_VERTEX_INPUT_STRUCTURE_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_INTEGER_DIVIDE_BY_ZERO_QUOTIENT: ::UINT = 0xffffffff; +pub const D3D12_INTEGER_DIVIDE_BY_ZERO_REMAINDER: ::UINT = 0xffffffff; +pub const D3D12_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL: ::UINT = 0xffffffff; +pub const D3D12_KEEP_UNORDERED_ACCESS_VIEWS: ::UINT = 0xffffffff; +pub const D3D12_LINEAR_GAMMA: ::FLOAT = 1.0; +pub const D3D12_MAG_FILTER_SHIFT: ::UINT = 2; +pub const D3D12_MAJOR_VERSION: ::UINT = 12; +pub const D3D12_MAX_BORDER_COLOR_COMPONENT: ::FLOAT = 1.0; +pub const D3D12_MAX_DEPTH: ::FLOAT = 1.0; +pub const D3D12_MAX_LIVE_STATIC_SAMPLERS: ::UINT = 2032; +pub const D3D12_MAX_MAXANISOTROPY: ::UINT = 16; +pub const D3D12_MAX_MULTISAMPLE_SAMPLE_COUNT: ::UINT = 32; +pub const D3D12_MAX_POSITION_VALUE: ::FLOAT = 3.402823466e+34; +pub const D3D12_MAX_ROOT_COST: ::UINT = 64; +pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_1: ::UINT = 1000000; +pub const D3D12_MAX_SHADER_VISIBLE_DESCRIPTOR_HEAP_SIZE_TIER_2: ::UINT = 1000000; +pub const D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE: ::UINT = 2048; +pub const D3D12_MAX_TEXTURE_DIMENSION_2_TO_EXP: ::UINT = 17; +pub const D3D12_MINOR_VERSION: ::UINT = 0; +pub const D3D12_MIN_BORDER_COLOR_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_MIN_DEPTH: ::FLOAT = 0.0; +pub const D3D12_MIN_FILTER_SHIFT: ::UINT = 4; +pub const D3D12_MIN_MAXANISOTROPY: ::UINT = 0; +pub const D3D12_MIP_FILTER_SHIFT: ::UINT = 0; +pub const D3D12_MIP_LOD_BIAS_MAX: ::FLOAT = 15.99; +pub const D3D12_MIP_LOD_BIAS_MIN: ::FLOAT = -16.0; +pub const D3D12_MIP_LOD_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_MIP_LOD_RANGE_BIT_COUNT: ::UINT = 8; +pub const D3D12_MULTISAMPLE_ANTIALIAS_LINE_WIDTH: ::FLOAT = 1.4; +pub const D3D12_NONSAMPLE_FETCH_OUT_OF_RANGE_ACCESS_RESULT: ::UINT = 0; +pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xffffffff; +pub const D3D12_OS_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff8; +pub const D3D12_PACKED_TILE: ::UINT = 0xffffffff; +pub const D3D12_PIXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 15; +pub const D3D12_PRE_SCISSOR_PIXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 16; +pub const D3D12_PS_CS_UAV_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_CS_UAV_REGISTER_COUNT: ::UINT = 8; +pub const D3D12_PS_CS_UAV_REGISTER_READS_PER_INST: ::UINT = 1; +pub const D3D12_PS_CS_UAV_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_PS_FRONTFACING_DEFAULT_VALUE: ::UINT = 0xffffffff; +pub const D3D12_PS_FRONTFACING_FALSE_VALUE: ::UINT = 0; +pub const D3D12_PS_FRONTFACING_TRUE_VALUE: ::UINT = 0xffffffff; +pub const D3D12_PS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_PS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_PS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_PS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_PS_LEGACY_PIXEL_CENTER_FRACTIONAL_COMPONENT: ::FLOAT = 0.0; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_DEPTH_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENTS: ::UINT = 1; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_MASK_REGISTER_COUNT: ::UINT = 1; +pub const D3D12_PS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_PS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_PS_OUTPUT_REGISTER_COUNT: ::UINT = 8; +pub const D3D12_PS_PIXEL_CENTER_FRACTIONAL_COMPONENT: ::FLOAT = 0.5; +pub const D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT: ::UINT = 16; +pub const D3D12_REQ_BLEND_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP: ::UINT = 27; +pub const D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT: ::UINT = 4096; +pub const D3D12_REQ_DEPTH_STENCIL_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: ::UINT = 32; +pub const D3D12_REQ_DRAW_VERTEX_COUNT_2_TO_EXP: ::UINT = 32; +pub const D3D12_REQ_FILTERING_HW_ADDRESSABLE_RESOURCE_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_GS_INVOCATION_32BIT_OUTPUT_COMPONENT_LIMIT: ::UINT = 1024; +pub const D3D12_REQ_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT: ::UINT = 4096; +pub const D3D12_REQ_MAXANISOTROPY: ::UINT = 16; +pub const D3D12_REQ_MIP_LEVELS: ::UINT = 15; +pub const D3D12_REQ_MULTI_ELEMENT_STRUCTURE_SIZE_IN_BYTES: ::UINT = 2048; +pub const D3D12_REQ_RASTERIZER_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_RENDER_TO_BUFFER_WINDOW_WIDTH: ::UINT = 16384; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_A_TERM: ::UINT = 128; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_B_TERM: ::FLOAT = 0.25; +pub const D3D12_REQ_RESOURCE_SIZE_IN_MEGABYTES_EXPRESSION_C_TERM: ::UINT = 2048; +pub const D3D12_REQ_RESOURCE_VIEW_COUNT_PER_DEVICE_2_TO_EXP: ::UINT = 20; +pub const D3D12_REQ_SAMPLER_OBJECT_COUNT_PER_DEVICE: ::UINT = 4096; +pub const D3D12_REQ_SUBRESOURCES: ::UINT = 30720; +pub const D3D12_REQ_TEXTURE1D_ARRAY_AXIS_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURE1D_U_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION: ::UINT = 16384; +pub const D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION: ::UINT = 2048; +pub const D3D12_REQ_TEXTURECUBE_DIMENSION: ::UINT = 16384; +pub const D3D12_RESINFO_INSTRUCTION_MISSING_COMPONENT_RETVAL: ::UINT = 0; +pub const D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES: ::UINT = 0xffffffff; +pub const D3D12_SHADER_COMPONENT_MAPPING_MASK: ::UINT = 0x7; +pub const D3D12_SHADER_COMPONENT_MAPPING_SHIFT: ::UINT = 3; +pub const D3D12_SHADER_MAJOR_VERSION: ::UINT = 5; +pub const D3D12_SHADER_MAX_INSTANCES: ::UINT = 65535; +pub const D3D12_SHADER_MAX_INTERFACES: ::UINT = 253; +pub const D3D12_SHADER_MAX_INTERFACE_CALL_SITES: ::UINT = 4096; +pub const D3D12_SHADER_MAX_TYPES: ::UINT = 65535; +pub const D3D12_SHADER_MINOR_VERSION: ::UINT = 1; +pub const D3D12_SHIFT_INSTRUCTION_PAD_VALUE: ::UINT = 0; +pub const D3D12_SHIFT_INSTRUCTION_SHIFT_VALUE_BIT_COUNT: ::UINT = 5; +pub const D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT: ::UINT = 8; +pub const D3D12_SMALL_MSAA_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 65536; +pub const D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT: ::UINT = 4096; +pub const D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES: ::UINT = 2048; +pub const D3D12_SO_BUFFER_MAX_WRITE_WINDOW_IN_BYTES: ::UINT = 512; +pub const D3D12_SO_BUFFER_SLOT_COUNT: ::UINT = 4; +pub const D3D12_SO_DDI_REGISTER_INDEX_DENOTING_GAP: ::UINT = 0xffffffff; +pub const D3D12_SO_NO_RASTERIZED_STREAM: ::UINT = 0xffffffff; +pub const D3D12_SO_OUTPUT_COMPONENT_COUNT: ::UINT = 128; +pub const D3D12_SO_STREAM_COUNT: ::UINT = 4; +pub const D3D12_SPEC_DATE_DAY: ::UINT = 14; +pub const D3D12_SPEC_DATE_MONTH: ::UINT = 11; +pub const D3D12_SPEC_DATE_YEAR: ::UINT = 2014; +pub const D3D12_SPEC_VERSION: ::DOUBLE = 1.16; +pub const D3D12_SRGB_GAMMA: ::FLOAT = 2.2; +pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_1: ::FLOAT = 12.92; +pub const D3D12_SRGB_TO_FLOAT_DENOMINATOR_2: ::FLOAT = 1.055; +pub const D3D12_SRGB_TO_FLOAT_EXPONENT: ::FLOAT = 2.4; +pub const D3D12_SRGB_TO_FLOAT_OFFSET: ::FLOAT = 0.055; +pub const D3D12_SRGB_TO_FLOAT_THRESHOLD: ::FLOAT = 0.04045; +pub const D3D12_SRGB_TO_FLOAT_TOLERANCE_IN_ULP: ::FLOAT = 0.5; +pub const D3D12_STANDARD_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_COMPONENT_BIT_COUNT_DOUBLED: ::UINT = 64; +pub const D3D12_STANDARD_MAXIMUM_ELEMENT_ALIGNMENT_BYTE_MULTIPLE: ::UINT = 4; +pub const D3D12_STANDARD_PIXEL_COMPONENT_COUNT: ::UINT = 128; +pub const D3D12_STANDARD_PIXEL_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_VECTOR_SIZE: ::UINT = 4; +pub const D3D12_STANDARD_VERTEX_ELEMENT_COUNT: ::UINT = 32; +pub const D3D12_STANDARD_VERTEX_TOTAL_COMPONENT_COUNT: ::UINT = 64; +pub const D3D12_SUBPIXEL_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_SUBTEXEL_FRACTIONAL_BIT_COUNT: ::UINT = 8; +pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_END: ::UINT = 0xffffffff; +pub const D3D12_SYSTEM_RESERVED_REGISTER_SPACE_VALUES_START: ::UINT = 0xfffffff0; +pub const D3D12_TESSELLATOR_MAX_EVEN_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MAX_ISOLINE_DENSITY_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MAX_ODD_TESSELLATION_FACTOR: ::UINT = 63; +pub const D3D12_TESSELLATOR_MAX_TESSELLATION_FACTOR: ::UINT = 64; +pub const D3D12_TESSELLATOR_MIN_EVEN_TESSELLATION_FACTOR: ::UINT = 2; +pub const D3D12_TESSELLATOR_MIN_ISOLINE_DENSITY_TESSELLATION_FACTOR: ::UINT = 1; +pub const D3D12_TESSELLATOR_MIN_ODD_TESSELLATION_FACTOR: ::UINT = 1; +pub const D3D12_TEXEL_ADDRESS_RANGE_BIT_COUNT: ::UINT = 16; +pub const D3D12_TEXTURE_DATA_PITCH_ALIGNMENT: ::UINT = 256; +pub const D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT: ::UINT = 512; +pub const D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES: ::UINT = 65536; +pub const D3D12_UAV_COUNTER_PLACEMENT_ALIGNMENT: ::UINT = 4096; +pub const D3D12_UAV_SLOT_COUNT: ::UINT = 64; +pub const D3D12_UNBOUND_MEMORY_ACCESS_RESULT: ::UINT = 0; +pub const D3D12_VIEWPORT_AND_SCISSORRECT_MAX_INDEX: ::UINT = 15; +pub const D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE: ::UINT = 16; +pub const D3D12_VIEWPORT_BOUNDS_MAX: ::UINT = 32767; +pub const D3D12_VIEWPORT_BOUNDS_MIN: ::INT = -32768; +pub const D3D12_VS_INPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_VS_INPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_VS_INPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_VS_INPUT_REGISTER_READS_PER_INST: ::UINT = 2; +pub const D3D12_VS_INPUT_REGISTER_READ_PORTS: ::UINT = 1; +pub const D3D12_VS_OUTPUT_REGISTER_COMPONENTS: ::UINT = 4; +pub const D3D12_VS_OUTPUT_REGISTER_COMPONENT_BIT_COUNT: ::UINT = 32; +pub const D3D12_VS_OUTPUT_REGISTER_COUNT: ::UINT = 32; +pub const D3D12_WHQL_CONTEXT_COUNT_FOR_RESOURCE_LIMIT: ::UINT = 10; +pub const D3D12_WHQL_DRAWINDEXED_INDEX_COUNT_2_TO_EXP: ::UINT = 25; +pub const D3D12_WHQL_DRAW_VERTEX_COUNT_2_TO_EXP: ::UINT = 25; +pub type D3D12_GPU_VIRTUAL_ADDRESS = ::UINT64; +ENUM!{enum D3D12_COMMAND_LIST_TYPE { + D3D12_COMMAND_LIST_TYPE_DIRECT = 0, + D3D12_COMMAND_LIST_TYPE_BUNDLE = 1, + D3D12_COMMAND_LIST_TYPE_COMPUTE = 2, + D3D12_COMMAND_LIST_TYPE_COPY = 3, +}} +FLAGS!{enum D3D12_COMMAND_QUEUE_FLAGS { + D3D12_COMMAND_QUEUE_FLAG_NONE = 0x0, + D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT = 0x1, +}} +ENUM!{enum D3D12_COMMAND_QUEUE_PRIORITY { + D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0, + D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100, +}} +STRUCT!{struct D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE, + Priority: ::INT, + Flags: D3D12_COMMAND_QUEUE_FLAGS, + NodeMask: ::UINT, +}} +ENUM!{enum D3D12_PRIMITIVE_TOPOLOGY_TYPE { + D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED = 0, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT = 1, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE = 2, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE = 3, + D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH = 4, +}} +ENUM!{enum D3D12_INPUT_CLASSIFICATION { + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, + D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1, +}} +STRUCT!{struct D3D12_INPUT_ELEMENT_DESC { + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + Format: ::DXGI_FORMAT, + InputSlot: ::UINT, + AlignedByteOffset: ::UINT, + InputSlotClass: D3D12_INPUT_CLASSIFICATION, + InstanceDataStepRate: ::UINT, +}} +ENUM!{enum D3D12_FILL_MODE { + D3D12_FILL_MODE_WIREFRAME = 2, + D3D12_FILL_MODE_SOLID = 3, +}} +pub type D3D12_PRIMITIVE_TOPOLOGY = ::D3D_PRIMITIVE_TOPOLOGY; +pub type D3D12_PRIMITIVE = ::D3D_PRIMITIVE; +ENUM!{enum D3D12_CULL_MODE { + D3D12_CULL_MODE_NONE = 1, + D3D12_CULL_MODE_FRONT = 2, + D3D12_CULL_MODE_BACK = 3, +}} +STRUCT!{struct D3D12_SO_DECLARATION_ENTRY { + Stream: ::UINT, + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + StartComponent: ::BYTE, + ComponentCount: ::BYTE, + OutputSlot: ::BYTE, +}} +STRUCT!{struct D3D12_VIEWPORT { + TopLeftX: ::FLOAT, + TopLeftY: ::FLOAT, + Width: ::FLOAT, + Height: ::FLOAT, + MinDepth: ::FLOAT, + MaxDepth: ::FLOAT, +}} +pub type D3D12_RECT = ::RECT; +STRUCT!{struct D3D12_BOX { + left: ::UINT, + top: ::UINT, + front: ::UINT, + right: ::UINT, + bottom: ::UINT, + back: ::UINT, +}} +ENUM!{enum D3D12_COMPARISON_FUNC { + D3D12_COMPARISON_FUNC_NEVER = 1, + D3D12_COMPARISON_FUNC_LESS = 2, + D3D12_COMPARISON_FUNC_EQUAL = 3, + D3D12_COMPARISON_FUNC_LESS_EQUAL = 4, + D3D12_COMPARISON_FUNC_GREATER = 5, + D3D12_COMPARISON_FUNC_NOT_EQUAL = 6, + D3D12_COMPARISON_FUNC_GREATER_EQUAL = 7, + D3D12_COMPARISON_FUNC_ALWAYS = 8, +}} +ENUM!{enum D3D12_DEPTH_WRITE_MASK { + D3D12_DEPTH_WRITE_MASK_ZERO = 0, + D3D12_DEPTH_WRITE_MASK_ALL = 1, +}} +ENUM!{enum D3D12_STENCIL_OP { + D3D12_STENCIL_OP_KEEP = 1, + D3D12_STENCIL_OP_ZERO = 2, + D3D12_STENCIL_OP_REPLACE = 3, + D3D12_STENCIL_OP_INCR_SAT = 4, + D3D12_STENCIL_OP_DECR_SAT = 5, + D3D12_STENCIL_OP_INVERT = 6, + D3D12_STENCIL_OP_INCR = 7, + D3D12_STENCIL_OP_DECR = 8, +}} +STRUCT!{struct D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D12_STENCIL_OP, + StencilDepthFailOp: D3D12_STENCIL_OP, + StencilPassOp: D3D12_STENCIL_OP, + StencilFunc: D3D12_COMPARISON_FUNC, +}} +STRUCT!{struct D3D12_DEPTH_STENCIL_DESC { + DepthEnable: ::BOOL, + DepthWriteMask: D3D12_DEPTH_WRITE_MASK, + DepthFunc: D3D12_COMPARISON_FUNC, + StencilEnable: ::BOOL, + StencilReadMask: ::UINT8, + StencilWriteMask: ::UINT8, + FrontFace: D3D12_DEPTH_STENCILOP_DESC, + BackFace: D3D12_DEPTH_STENCILOP_DESC, +}} +ENUM!{enum D3D12_BLEND { + D3D12_BLEND_ZERO = 1, + D3D12_BLEND_ONE = 2, + D3D12_BLEND_SRC_COLOR = 3, + D3D12_BLEND_INV_SRC_COLOR = 4, + D3D12_BLEND_SRC_ALPHA = 5, + D3D12_BLEND_INV_SRC_ALPHA = 6, + D3D12_BLEND_DEST_ALPHA = 7, + D3D12_BLEND_INV_DEST_ALPHA = 8, + D3D12_BLEND_DEST_COLOR = 9, + D3D12_BLEND_INV_DEST_COLOR = 10, + D3D12_BLEND_SRC_ALPHA_SAT = 11, + D3D12_BLEND_BLEND_FACTOR = 14, + D3D12_BLEND_INV_BLEND_FACTOR = 15, + D3D12_BLEND_SRC1_COLOR = 16, + D3D12_BLEND_INV_SRC1_COLOR = 17, + D3D12_BLEND_SRC1_ALPHA = 18, + D3D12_BLEND_INV_SRC1_ALPHA = 19, +}} +ENUM!{enum D3D12_BLEND_OP { + D3D12_BLEND_OP_ADD = 1, + D3D12_BLEND_OP_SUBTRACT = 2, + D3D12_BLEND_OP_REV_SUBTRACT = 3, + D3D12_BLEND_OP_MIN = 4, + D3D12_BLEND_OP_MAX = 5, +}} +FLAGS!{enum D3D12_COLOR_WRITE_ENABLE { + D3D12_COLOR_WRITE_ENABLE_RED = 0x1, + D3D12_COLOR_WRITE_ENABLE_GREEN = 0x2, + D3D12_COLOR_WRITE_ENABLE_BLUE = 0x4, + D3D12_COLOR_WRITE_ENABLE_ALPHA = 0x8, + D3D12_COLOR_WRITE_ENABLE_ALL = 0xF, +}} +ENUM!{enum D3D12_LOGIC_OP { + D3D12_LOGIC_OP_CLEAR = 0, + D3D12_LOGIC_OP_SET = 1, + D3D12_LOGIC_OP_COPY = 2, + D3D12_LOGIC_OP_COPY_INVERTED = 3, + D3D12_LOGIC_OP_NOOP = 4, + D3D12_LOGIC_OP_INVERT = 5, + D3D12_LOGIC_OP_AND = 6, + D3D12_LOGIC_OP_NAND = 7, + D3D12_LOGIC_OP_OR = 8, + D3D12_LOGIC_OP_NOR = 9, + D3D12_LOGIC_OP_XOR = 10, + D3D12_LOGIC_OP_EQUIV = 11, + D3D12_LOGIC_OP_AND_REVERSE = 12, + D3D12_LOGIC_OP_AND_INVERTED = 13, + D3D12_LOGIC_OP_OR_REVERSE = 14, + D3D12_LOGIC_OP_OR_INVERTED = 15, +}} +STRUCT!{struct D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: ::BOOL, + LogicOpEnable: ::BOOL, + SrcBlend: D3D12_BLEND, + DestBlend: D3D12_BLEND, + BlendOp: D3D12_BLEND_OP, + SrcBlendAlpha: D3D12_BLEND, + DestBlendAlpha: D3D12_BLEND, + BlendOpAlpha: D3D12_BLEND_OP, + LogicOp: D3D12_LOGIC_OP, + RenderTargetWriteMask: ::UINT8, +}} +STRUCT!{struct D3D12_BLEND_DESC { + AlphaToCoverageEnable: ::BOOL, + IndependentBlendEnable: ::BOOL, + RenderTarget: [D3D12_RENDER_TARGET_BLEND_DESC; 8], +}} +ENUM!{enum D3D12_CONSERVATIVE_RASTERIZATION_MODE { + D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF = 0, + D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON = 1, +}} +STRUCT!{struct D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE, + CullMode: D3D12_CULL_MODE, + FrontCounterClockwise: ::BOOL, + DepthBias: ::INT, + DepthBiasClamp: ::FLOAT, + SlopeScaledDepthBias: ::FLOAT, + DepthClipEnable: ::BOOL, + MultisampleEnable: ::BOOL, + AntialiasedLineEnable: ::BOOL, + ForcedSampleCount: ::UINT, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE, +}} +RIDL!{interface ID3D12Object(ID3D12ObjectVtbl): IUnknown(IUnknownVtbl) { + fn GetPrivateData( + &mut self, guid: ::REFGUID, pDataSize: *mut ::UINT, pData: *mut ::c_void + ) -> ::HRESULT, + fn SetPrivateData( + &mut self, guid: ::REFGUID, DataSize: ::UINT, pData: *const ::c_void + ) -> ::HRESULT, + fn SetPrivateDataInterface( + &mut self, guid: ::REFGUID, pData: *const ::IUnknown + ) -> ::HRESULT, + fn SetName(&mut self, Name: ::LPCWSTR) -> ::HRESULT +}} +RIDL!{interface ID3D12DeviceChild(ID3D12DeviceChildVtbl): ID3D12Object(ID3D12ObjectVtbl) { + fn GetDevice( + &mut self, riid: ::REFGUID, ppvDevice: *mut *mut ::c_void + ) -> ::HRESULT +}} +RIDL!{interface ID3D12RootSignature(ID3D12RootSignatureVtbl): + ID3D12DeviceChild(ID3D12DeviceChildVtbl) { +}} +STRUCT!{struct D3D12_SHADER_BYTECODE { + pShaderBytecode: *const ::c_void, + BytecodeLength: ::SIZE_T, +}} +STRUCT!{struct D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: *const D3D12_SO_DECLARATION_ENTRY, + NumEntries: ::UINT, + pBufferStrides: *const ::UINT, + NumStrides: ::UINT, + RasterizedStream: ::UINT, +}} +STRUCT!{struct D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: *const D3D12_INPUT_ELEMENT_DESC, + NumElements: ::UINT, +}} +ENUM!{enum D3D12_INDEX_BUFFER_STRIP_CUT_VALUE { + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED = 0, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF = 1, + D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF = 2, +}} +STRUCT!{struct D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: *const ::c_void, + CachedBlobSizeInBytes: ::SIZE_T, +}} +FLAGS!{enum D3D12_PIPELINE_STATE_FLAGS { + D3D12_PIPELINE_STATE_FLAG_NONE = 0x0, + D3D12_PIPELINE_STATE_FLAG_TOOL_DEBUG = 0x1, +}} +STRUCT!{struct D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: *mut ID3D12RootSignature, + VS: D3D12_SHADER_BYTECODE, + PS: D3D12_SHADER_BYTECODE, + DS: D3D12_SHADER_BYTECODE, + HS: D3D12_SHADER_BYTECODE, + GS: D3D12_SHADER_BYTECODE, + StreamOutput: D3D12_STREAM_OUTPUT_DESC, + BlendState: D3D12_BLEND_DESC, + SampleMask: ::UINT, + RasterizerState: D3D12_RASTERIZER_DESC, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC, + InputLayout: D3D12_INPUT_LAYOUT_DESC, + IBStripCutValue: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + NumRenderTargets: ::UINT, + RTVFormats: [::DXGI_FORMAT; 8], + DSVFormat: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, + NodeMask: ::UINT, + CachedPSO: D3D12_CACHED_PIPELINE_STATE, + Flags: D3D12_PIPELINE_STATE_FLAGS, +}} +STRUCT!{struct D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: *mut ID3D12RootSignature, + CS: D3D12_SHADER_BYTECODE, + NodeMask: ::UINT, + CachedPSO: D3D12_CACHED_PIPELINE_STATE, + Flags: D3D12_PIPELINE_STATE_FLAGS, +}} +ENUM!{enum D3D12_FEATURE { + D3D12_FEATURE_D3D12_OPTIONS = 0, + D3D12_FEATURE_ARCHITECTURE = 1, + D3D12_FEATURE_FEATURE_LEVELS = 2, + D3D12_FEATURE_FORMAT_SUPPORT = 3, + D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS = 4, + D3D12_FEATURE_FORMAT_INFO = 5, + D3D12_FEATURE_GPU_VIRTUAL_ADDRESS_SUPPORT = 6, +}} +FLAGS!{enum D3D12_SHADER_MIN_PRECISION_SUPPORT { + D3D12_SHADER_MIN_PRECISION_SUPPORT_NONE = 0, + D3D12_SHADER_MIN_PRECISION_SUPPORT_10_BIT = 0x1, + D3D12_SHADER_MIN_PRECISION_SUPPORT_16_BIT = 0x2, +}} +ENUM!{enum D3D12_TILED_RESOURCES_TIER { + D3D12_TILED_RESOURCES_TIER_NOT_SUPPORTED = 0, + D3D12_TILED_RESOURCES_TIER_1 = 1, + D3D12_TILED_RESOURCES_TIER_2 = 2, + D3D12_TILED_RESOURCES_TIER_3 = 3, +}} +ENUM!{enum D3D12_RESOURCE_BINDING_TIER { + D3D12_RESOURCE_BINDING_TIER_1 = 1, + D3D12_RESOURCE_BINDING_TIER_2 = 2, + D3D12_RESOURCE_BINDING_TIER_3 = 3, +}} +ENUM!{enum D3D12_CONSERVATIVE_RASTERIZATION_TIER { + D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED = 0, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_1 = 1, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_2 = 2, + D3D12_CONSERVATIVE_RASTERIZATION_TIER_3 = 3, +}} +FLAGS!{enum D3D12_FORMAT_SUPPORT1 { + D3D12_FORMAT_SUPPORT1_NONE = 0x0, + D3D12_FORMAT_SUPPORT1_BUFFER = 0x1, + D3D12_FORMAT_SUPPORT1_IA_VERTEX_BUFFER = 0x2, + D3D12_FORMAT_SUPPORT1_IA_INDEX_BUFFER = 0x4, + D3D12_FORMAT_SUPPORT1_SO_BUFFER = 0x8, + D3D12_FORMAT_SUPPORT1_TEXTURE1D = 0x10, + D3D12_FORMAT_SUPPORT1_TEXTURE2D = 0x20, + D3D12_FORMAT_SUPPORT1_TEXTURE3D = 0x40, + D3D12_FORMAT_SUPPORT1_TEXTURECUBE = 0x80, + D3D12_FORMAT_SUPPORT1_SHADER_LOAD = 0x100, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE = 0x200, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_COMPARISON = 0x400, + D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE_MONO_TEXT = 0x800, + D3D12_FORMAT_SUPPORT1_MIP = 0x1000, + D3D12_FORMAT_SUPPORT1_RENDER_TARGET = 0x4000, + D3D12_FORMAT_SUPPORT1_BLENDABLE = 0x8000, + D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL = 0x10000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE = 0x40000, + D3D12_FORMAT_SUPPORT1_DISPLAY = 0x80000, + D3D12_FORMAT_SUPPORT1_CAST_WITHIN_BIT_LAYOUT = 0x100000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET = 0x200000, + D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD = 0x400000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER = 0x800000, + D3D12_FORMAT_SUPPORT1_BACK_BUFFER_CAST = 0x1000000, + D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW = 0x2000000, + D3D12_FORMAT_SUPPORT1_SHADER_GATHER_COMPARISON = 0x4000000, + D3D12_FORMAT_SUPPORT1_DECODER_OUTPUT = 0x8000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_OUTPUT = 0x10000000, + D3D12_FORMAT_SUPPORT1_VIDEO_PROCESSOR_INPUT = 0x20000000, + D3D12_FORMAT_SUPPORT1_VIDEO_ENCODER = 0x40000000, +}} +FLAGS!{enum D3D12_FORMAT_SUPPORT2 { + D3D12_FORMAT_SUPPORT2_NONE = 0x0, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_ADD = 0x1, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_BITWISE_OPS = 0x2, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_COMPARE_STORE_OR_COMPARE_EXCHANGE = 0x4, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_EXCHANGE = 0x8, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_SIGNED_MIN_OR_MAX = 0x10, + D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX = 0x20, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD = 0x40, + D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE = 0x80, + D3D12_FORMAT_SUPPORT2_OUTPUT_MERGER_LOGIC_OP = 0x100, + D3D12_FORMAT_SUPPORT2_TILED = 0x200, + D3D12_FORMAT_SUPPORT2_MULTIPLANE_OVERLAY = 0x4000, +}} +FLAGS!{enum D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS { + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE = 0x0, + D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_TILED_RESOURCE = 0x1, +}} +ENUM!{enum D3D12_CROSS_NODE_SHARING_TIER { + D3D12_CROSS_NODE_SHARING_TIER_NOT_SUPPORTED = 0, + D3D12_CROSS_NODE_SHARING_TIER_1_EMULATED = 1, + D3D12_CROSS_NODE_SHARING_TIER_1 = 2, + D3D12_CROSS_NODE_SHARING_TIER_2 = 3, +}} +ENUM!{enum D3D12_RESOURCE_HEAP_TIER { + D3D12_RESOURCE_HEAP_TIER_1 = 1, + D3D12_RESOURCE_HEAP_TIER_2 = 2, +}} +STRUCT!{struct D3D12_FEATURE_DATA_D3D12_OPTIONS { + DoublePrecisionFloatShaderOps: ::BOOL, + OutputMergerLogicOp: ::BOOL, + MinPrecisionSupport: D3D12_SHADER_MIN_PRECISION_SUPPORT, + TiledResourcesTier: D3D12_TILED_RESOURCES_TIER, + ResourceBindingTier: D3D12_RESOURCE_BINDING_TIER, + PSSpecifiedStencilRefSupported: ::BOOL, + TypedUAVLoadAdditionalFormats: ::BOOL, + ROVsSupported: ::BOOL, + ConservativeRasterizationTier: D3D12_CONSERVATIVE_RASTERIZATION_TIER, + MaxGPUVirtualAddressBitsPerResource: ::UINT, + StandardSwizzle64KBSupported: ::BOOL, + CrossNodeSharingTier: D3D12_CROSS_NODE_SHARING_TIER, + CrossAdapterRowMajorTextureSupported: ::BOOL, + VPAndRTArrayIndexFromAnyShaderFeedingRasterizerSupportedWithoutGSEmulation: ::BOOL, + ResourceHeapTier: D3D12_RESOURCE_HEAP_TIER, +}} + + + + + + + + + +FLAGS!{ enum D3D12_BUFFER_SRV_FLAGS { + D3D12_BUFFER_SRV_FLAG_NONE = 0x0, + D3D12_BUFFER_SRV_FLAG_RAW = 0x1, +}} + +FLAGS!{ enum D3D12_BUFFER_UAV_FLAGS { + D3D12_BUFFER_UAV_FLAG_NONE = 0x0, + D3D12_BUFFER_UAV_FLAG_RAW = 0x1, +}} + +FLAGS!{ enum D3D12_CLEAR_FLAGS { + D3D12_CLEAR_FLAG_DEPTH = 0x1, + D3D12_CLEAR_FLAG_STENCIL = 0x2, +}} + + +ENUM!{ enum D3D12_CPU_PAGE_PROPERTY { + D3D12_CPU_PAGE_PROPERTY_UNKNOWN = 0, + D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE = 1, + D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE = 2, + D3D12_CPU_PAGE_PROPERTY_WRITE_BACK = 3, +}} + + +FLAGS!{ enum D3D12_DESCRIPTOR_HEAP_FLAGS { + D3D12_DESCRIPTOR_HEAP_FLAG_NONE = 0x0, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE = 0x1, +}} + +ENUM!{ enum D3D12_DESCRIPTOR_HEAP_TYPE { + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV = 0, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER = 1, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV = 2, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV = 3, + D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES = 4, +}} + +ENUM!{ enum D3D12_DESCRIPTOR_RANGE_TYPE { + D3D12_DESCRIPTOR_RANGE_TYPE_SRV = 0, + D3D12_DESCRIPTOR_RANGE_TYPE_UAV = 1, + D3D12_DESCRIPTOR_RANGE_TYPE_CBV = 2, + D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER = 3, +}} + +ENUM!{ enum D3D12_DSV_DIMENSION { + D3D12_DSV_DIMENSION_UNKNOWN = 0, + D3D12_DSV_DIMENSION_TEXTURE1D = 1, + D3D12_DSV_DIMENSION_TEXTURE1DARRAY = 2, + D3D12_DSV_DIMENSION_TEXTURE2D = 3, + D3D12_DSV_DIMENSION_TEXTURE2DARRAY = 4, + D3D12_DSV_DIMENSION_TEXTURE2DMS = 5, + D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY = 6, +}} + +FLAGS!{ enum D3D12_DSV_FLAGS { + D3D12_DSV_FLAG_NONE = 0x0, + D3D12_DSV_FLAG_READ_ONLY_DEPTH = 0x1, + D3D12_DSV_FLAG_READ_ONLY_STENCIL = 0x2, +}} + + + +FLAGS!{ enum D3D12_FENCE_FLAGS { + D3D12_FENCE_FLAG_NONE = 0x0, + D3D12_FENCE_FLAG_SHARED = 0x1, + D3D12_FENCE_FLAG_SHARED_CROSS_ADAPTER = 0x2, +}} + + + +ENUM!{ enum D3D12_FILTER { + D3D12_FILTER_MIN_MAG_MIP_POINT = 0, + D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR = 1, + D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT = 4, + D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR = 5, + D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT = 16, + D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 17, + D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT = 20, + D3D12_FILTER_MIN_MAG_MIP_LINEAR = 21, + D3D12_FILTER_ANISOTROPIC = 85, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT = 128, + D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR = 129, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT = 132, + D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR = 133, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT = 144, + D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 145, + D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT = 148, + D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR = 149, + D3D12_FILTER_COMPARISON_ANISOTROPIC = 213, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_POINT = 256, + D3D12_FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR = 257, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 260, + D3D12_FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR = 261, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT = 272, + D3D12_FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 273, + D3D12_FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT = 276, + D3D12_FILTER_MINIMUM_MIN_MAG_MIP_LINEAR = 277, + D3D12_FILTER_MINIMUM_ANISOTROPIC = 341, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_POINT = 384, + D3D12_FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR = 385, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT = 388, + D3D12_FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR = 389, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT = 400, + D3D12_FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR = 401, + D3D12_FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT = 404, + D3D12_FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR = 405, + D3D12_FILTER_MAXIMUM_ANISOTROPIC = 469, +}} + +ENUM!{ enum D3D12_FILTER_REDUCTION_TYPE { + D3D12_FILTER_REDUCTION_TYPE_STANDARD = 0, + D3D12_FILTER_REDUCTION_TYPE_COMPARISON = 1, + D3D12_FILTER_REDUCTION_TYPE_MINIMUM = 2, + D3D12_FILTER_REDUCTION_TYPE_MAXIMUM = 3, +}} + +ENUM!{ enum D3D12_FILTER_TYPE { + D3D12_FILTER_TYPE_POINT = 0, + D3D12_FILTER_TYPE_LINEAR = 1, +}} + + + +FLAGS!{ enum D3D12_HEAP_FLAGS { + D3D12_HEAP_FLAG_NONE = 0x0, + D3D12_HEAP_FLAG_SHARED = 0x1, + D3D12_HEAP_FLAG_DENY_BUFFERS = 0x4, + D3D12_HEAP_FLAG_ALLOW_DISPLAY = 0x8, + D3D12_HEAP_FLAG_SHARED_CROSS_ADAPTER = 0x20, + D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES = 0x40, + D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES = 0x80, + D3D12_HEAP_FLAG_ALLOW_ALL_BUFFERS_AND_TEXTURES = 0x0, + D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS = 0xC0, + D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES = 0x44, + D3D12_HEAP_FLAG_ALLOW_ONLY_RT_DS_TEXTURES = 0x84, +}} + +ENUM!{ enum D3D12_HEAP_TYPE { + D3D12_HEAP_TYPE_DEFAULT = 1, + D3D12_HEAP_TYPE_UPLOAD = 2, + D3D12_HEAP_TYPE_READBACK = 3, + D3D12_HEAP_TYPE_CUSTOM = 4, +}} + + + +ENUM!{ enum D3D12_INDIRECT_ARGUMENT_TYPE { + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW = 0, + D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED = 1, + D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH = 2, + D3D12_INDIRECT_ARGUMENT_TYPE_VERTEX_BUFFER_VIEW = 3, + D3D12_INDIRECT_ARGUMENT_TYPE_INDEX_BUFFER_VIEW = 4, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT = 5, + D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT_BUFFER_VIEW = 6, + D3D12_INDIRECT_ARGUMENT_TYPE_SHADER_RESOURCE_VIEW = 7, + D3D12_INDIRECT_ARGUMENT_TYPE_UNORDERED_ACCESS_VIEW = 8, +}} + + + + + +ENUM!{ enum D3D12_MEMORY_POOL { + D3D12_MEMORY_POOL_UNKNOWN = 0, + D3D12_MEMORY_POOL_L0 = 1, + D3D12_MEMORY_POOL_L1 = 2, +}} + + + + +ENUM!{ enum D3D12_PREDICATION_OP { + D3D12_PREDICATION_OP_EQUAL_ZERO = 0, + D3D12_PREDICATION_OP_NOT_EQUAL_ZERO = 1, +}} + + + +ENUM!{ enum D3D12_QUERY_HEAP_TYPE { + D3D12_QUERY_HEAP_TYPE_OCCLUSION = 0, + D3D12_QUERY_HEAP_TYPE_TIMESTAMP = 1, + D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS = 2, + D3D12_QUERY_HEAP_TYPE_SO_STATISTICS = 3, +}} + +ENUM!{ enum D3D12_QUERY_TYPE { + D3D12_QUERY_TYPE_OCCLUSION = 0, + D3D12_QUERY_TYPE_BINARY_OCCLUSION = 1, + D3D12_QUERY_TYPE_TIMESTAMP = 2, + D3D12_QUERY_TYPE_PIPELINE_STATISTICS = 3, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM0 = 4, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM1 = 5, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM2 = 6, + D3D12_QUERY_TYPE_SO_STATISTICS_STREAM3 = 7, +}} + +FLAGS!{ enum D3D12_RESOURCE_BARRIER_FLAGS { + D3D12_RESOURCE_BARRIER_FLAG_NONE = 0x0, + D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY = 0x1, + D3D12_RESOURCE_BARRIER_FLAG_END_ONLY = 0x2, +}} + +ENUM!{ enum D3D12_RESOURCE_BARRIER_TYPE { + D3D12_RESOURCE_BARRIER_TYPE_TRANSITION = 0, + D3D12_RESOURCE_BARRIER_TYPE_ALIASING = 1, + D3D12_RESOURCE_BARRIER_TYPE_UAV = 2, +}} + + +ENUM!{ enum D3D12_RESOURCE_DIMENSION { + D3D12_RESOURCE_DIMENSION_UNKNOWN = 0, + D3D12_RESOURCE_DIMENSION_BUFFER = 1, + D3D12_RESOURCE_DIMENSION_TEXTURE1D = 2, + D3D12_RESOURCE_DIMENSION_TEXTURE2D = 3, + D3D12_RESOURCE_DIMENSION_TEXTURE3D = 4, +}} + +FLAGS!{ enum D3D12_RESOURCE_FLAGS { + D3D12_RESOURCE_FLAG_NONE = 0x0, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET = 0x1, + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL = 0x2, + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS = 0x4, + D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE = 0x8, + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER = 0x10, + D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS = 0x20, +}} + + +FLAGS!{ enum D3D12_RESOURCE_STATES { + D3D12_RESOURCE_STATE_COMMON = 0x0, + D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER = 0x1, + D3D12_RESOURCE_STATE_INDEX_BUFFER = 0x2, + D3D12_RESOURCE_STATE_RENDER_TARGET = 0x4, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS = 0x8, + D3D12_RESOURCE_STATE_DEPTH_WRITE = 0x10, + D3D12_RESOURCE_STATE_DEPTH_READ = 0x20, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE = 0x40, + D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE = 0x80, + D3D12_RESOURCE_STATE_STREAM_OUT = 0x100, + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT = 0x200, + D3D12_RESOURCE_STATE_COPY_DEST = 0x400, + D3D12_RESOURCE_STATE_COPY_SOURCE = 0x800, + D3D12_RESOURCE_STATE_RESOLVE_DEST = 0x1000, + D3D12_RESOURCE_STATE_RESOLVE_SOURCE = 0x2000, + D3D12_RESOURCE_STATE_GENERIC_READ = 0xAC3, + D3D12_RESOURCE_STATE_PRESENT = 0x0, + D3D12_RESOURCE_STATE_PREDICATION = 0x200, +}} + +ENUM!{ enum D3D12_ROOT_PARAMETER_TYPE { + D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE = 0, + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS = 1, + D3D12_ROOT_PARAMETER_TYPE_CBV = 2, + D3D12_ROOT_PARAMETER_TYPE_SRV = 3, + D3D12_ROOT_PARAMETER_TYPE_UAV = 4, +}} + +FLAGS!{ enum D3D12_ROOT_SIGNATURE_FLAGS { + D3D12_ROOT_SIGNATURE_FLAG_NONE = 0x0, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT = 0x1, + D3D12_ROOT_SIGNATURE_FLAG_DENY_VERTEX_SHADER_ROOT_ACCESS = 0x2, + D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS = 0x4, + D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS = 0x8, + D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS = 0x10, + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS = 0x20, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_STREAM_OUTPUT = 0x40, +}} + +ENUM!{ enum D3D12_RTV_DIMENSION { + D3D12_RTV_DIMENSION_UNKNOWN = 0, + D3D12_RTV_DIMENSION_BUFFER = 1, + D3D12_RTV_DIMENSION_TEXTURE1D = 2, + D3D12_RTV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_RTV_DIMENSION_TEXTURE2D = 4, + D3D12_RTV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_RTV_DIMENSION_TEXTURE2DMS = 6, + D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_RTV_DIMENSION_TEXTURE3D = 8, +}} + +ENUM!{ enum D3D12_SHADER_COMPONENT_MAPPING { + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0 = 0, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1 = 1, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_2 = 2, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3 = 3, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0 = 4, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1 = 5, +}} + + +ENUM!{ enum D3D12_SHADER_VISIBILITY { + D3D12_SHADER_VISIBILITY_ALL = 0, + D3D12_SHADER_VISIBILITY_VERTEX = 1, + D3D12_SHADER_VISIBILITY_HULL = 2, + D3D12_SHADER_VISIBILITY_DOMAIN = 3, + D3D12_SHADER_VISIBILITY_GEOMETRY = 4, + D3D12_SHADER_VISIBILITY_PIXEL = 5, +}} + +ENUM!{ enum D3D12_SRV_DIMENSION { + D3D12_SRV_DIMENSION_UNKNOWN = 0, + D3D12_SRV_DIMENSION_BUFFER = 1, + D3D12_SRV_DIMENSION_TEXTURE1D = 2, + D3D12_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_SRV_DIMENSION_TEXTURE2D = 4, + D3D12_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D12_SRV_DIMENSION_TEXTURE3D = 8, + D3D12_SRV_DIMENSION_TEXTURECUBE = 9, + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY = 10, +}} + +ENUM!{ enum D3D12_STATIC_BORDER_COLOR { + D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK = 0, + D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK = 1, + D3D12_STATIC_BORDER_COLOR_OPAQUE_WHITE = 2, +}} + + + +ENUM!{ enum D3D12_TEXTURE_ADDRESS_MODE { + D3D12_TEXTURE_ADDRESS_MODE_WRAP = 1, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR = 2, + D3D12_TEXTURE_ADDRESS_MODE_CLAMP = 3, + D3D12_TEXTURE_ADDRESS_MODE_BORDER = 4, + D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE = 5, +}} + +ENUM!{ enum D3D12_TEXTURE_COPY_TYPE { + D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX = 0, + D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT = 1, +}} + +ENUM!{ enum D3D12_TEXTURE_LAYOUT { + D3D12_TEXTURE_LAYOUT_UNKNOWN = 0, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR = 1, + D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE = 2, + D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE = 3, +}} + + +FLAGS!{ enum D3D12_TILE_COPY_FLAGS { + D3D12_TILE_COPY_FLAG_NONE = 0x0, + D3D12_TILE_COPY_FLAG_NO_HAZARD = 0x1, + D3D12_TILE_COPY_FLAG_LINEAR_BUFFER_TO_SWIZZLED_TILED_RESOURCE = 0x2, + D3D12_TILE_COPY_FLAG_SWIZZLED_TILED_RESOURCE_TO_LINEAR_BUFFER = 0x4, +}} + +FLAGS!{ enum D3D12_TILE_MAPPING_FLAGS { + D3D12_TILE_MAPPING_FLAG_NONE = 0x0, + D3D12_TILE_MAPPING_FLAG_NO_HAZARD = 0x1, +}} + +FLAGS!{ enum D3D12_TILE_RANGE_FLAGS { + D3D12_TILE_RANGE_FLAG_NONE = 0x0, + D3D12_TILE_RANGE_FLAG_NULL = 0x1, + D3D12_TILE_RANGE_FLAG_SKIP = 0x2, + D3D12_TILE_RANGE_FLAG_REUSE_SINGLE_TILE = 0x4, +}} + +ENUM!{ enum D3D12_UAV_DIMENSION { + D3D12_UAV_DIMENSION_UNKNOWN = 0, + D3D12_UAV_DIMENSION_BUFFER = 1, + D3D12_UAV_DIMENSION_TEXTURE1D = 2, + D3D12_UAV_DIMENSION_TEXTURE1DARRAY = 3, + D3D12_UAV_DIMENSION_TEXTURE2D = 4, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY = 5, + D3D12_UAV_DIMENSION_TEXTURE3D = 8, +}} + +ENUM!{ enum D3D_ROOT_SIGNATURE_VERSION { + D3D_ROOT_SIGNATURE_VERSION_1 = 1, +}} + + + + + +STRUCT!{struct D3D12_BUFFER_RTV { + FirstElement: ::UINT64, + NumElements: ::UINT, +}} + +STRUCT!{struct D3D12_BUFFER_SRV { + FirstElement: ::UINT64, + NumElements: ::UINT, + StructureByteStride: ::UINT, + Flags: ::D3D12_BUFFER_SRV_FLAGS, +}} + +STRUCT!{struct D3D12_BUFFER_UAV { + FirstElement: ::UINT64, + NumElements: ::UINT, + StructureByteStride: ::UINT, + CounterOffsetInBytes: ::UINT64, + Flags: ::D3D12_BUFFER_UAV_FLAGS, +}} + + + +STRUCT!{struct D3D12_CLEAR_VALUE { + Format: ::DXGI_FORMAT, + u: [::FLOAT; 4], +}} + +UNION!(D3D12_CLEAR_VALUE, u, DepthStencil, DepthStencil_mut, ::D3D12_DEPTH_STENCIL_VALUE); +UNION!(D3D12_CLEAR_VALUE, u, Color, Color_mut, [::FLOAT; 4]); + + + +STRUCT!{struct D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: ::UINT, + NumArgumentDescs: ::UINT, + pArgumentDescs: *const ::D3D12_INDIRECT_ARGUMENT_DESC, + NodeMask: ::UINT, +}} + + + +STRUCT!{struct D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, +}} + +STRUCT!{struct D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: ::SIZE_T, +}} + + + +STRUCT!{struct D3D12_DEPTH_STENCIL_VALUE { + Depth: ::FLOAT, + Stencil: ::UINT8, +}} + +STRUCT!{struct D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_DSV_DIMENSION, + Flags: ::D3D12_DSV_FLAGS, + u: ::D3D12_TEX1D_ARRAY_DSV, +}} + +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_DSV); +UNION!(D3D12_DEPTH_STENCIL_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_DSV); + +STRUCT!{struct D3D12_DESCRIPTOR_HEAP_DESC { + Type: ::D3D12_DESCRIPTOR_HEAP_TYPE, + NumDescriptors: ::UINT, + Flags: ::D3D12_DESCRIPTOR_HEAP_FLAGS, + NodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_DESCRIPTOR_RANGE { + RangeType: ::D3D12_DESCRIPTOR_RANGE_TYPE, + NumDescriptors: ::UINT, + BaseShaderRegister: ::UINT, + RegisterSpace: ::UINT, + OffsetInDescriptorsFromTableStart: ::UINT, +}} + +STRUCT!{struct D3D12_DISCARD_REGION { + NumRects: ::UINT, + pRects: *const ::D3D12_RECT, + FirstSubresource: ::UINT, + NumSubresources: ::UINT, +}} + +STRUCT!{struct D3D12_DISPATCH_ARGUMENTS { + ThreadGroupCountX: ::UINT, + ThreadGroupCountY: ::UINT, + ThreadGroupCountZ: ::UINT, +}} + +STRUCT!{struct D3D12_DRAW_ARGUMENTS { + VertexCountPerInstance: ::UINT, + InstanceCount: ::UINT, + StartVertexLocation: ::UINT, + StartInstanceLocation: ::UINT, +}} + +STRUCT!{struct D3D12_DRAW_INDEXED_ARGUMENTS { + IndexCountPerInstance: ::UINT, + InstanceCount: ::UINT, + StartIndexLocation: ::UINT, + BaseVertexLocation: ::INT, + StartInstanceLocation: ::UINT, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_ARCHITECTURE { + NodeIndex: ::UINT, + TileBasedRenderer: ::BOOL, + UMA: ::BOOL, + CacheCoherentUMA: ::BOOL, +}} + + +STRUCT!{struct D3D12_FEATURE_DATA_FEATURE_LEVELS { + NumFeatureLevels: ::UINT, + pFeatureLevelsRequested: *const ::D3D_FEATURE_LEVEL, + MaxSupportedFeatureLevel: ::D3D_FEATURE_LEVEL, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_FORMAT_INFO { + Format: ::DXGI_FORMAT, + PlaneCount: ::UINT8, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: ::DXGI_FORMAT, + Support1: ::D3D12_FORMAT_SUPPORT1, + Support2: ::D3D12_FORMAT_SUPPORT2, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_GPU_VIRTUAL_ADDRESS_SUPPORT { + MaxGPUVirtualAddressBitsPerResource: ::UINT, + MaxGPUVirtualAddressBitsPerProcess: ::UINT, +}} + +STRUCT!{struct D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS { + Format: ::DXGI_FORMAT, + SampleCount: ::UINT, + Flags: ::D3D12_MULTISAMPLE_QUALITY_LEVEL_FLAGS, + NumQualityLevels: ::UINT, +}} + +STRUCT!{struct D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: ::UINT64, +}} + + + +STRUCT!{struct D3D12_HEAP_DESC { + SizeInBytes: ::UINT64, + Properties: ::D3D12_HEAP_PROPERTIES, + Alignment: ::UINT64, + Flags: ::D3D12_HEAP_FLAGS, +}} + +STRUCT!{struct D3D12_HEAP_PROPERTIES { + Type: ::D3D12_HEAP_TYPE, + CPUPageProperty: ::D3D12_CPU_PAGE_PROPERTY, + MemoryPoolPreference: ::D3D12_MEMORY_POOL, + CreationNodeMask: ::UINT, + VisibleNodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_INDEX_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, + Format: ::DXGI_FORMAT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer { + Slot: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_Constant { + RootParameterIndex: ::UINT, + DestOffsetIn32BitValues: ::UINT, + Num32BitValuesToSet: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView { + RootParameterIndex: ::UINT, +}} + +STRUCT!{struct D3D12_INDIRECT_ARGUMENT_DESC { + Type: ::D3D12_INDIRECT_ARGUMENT_TYPE, + u: ::D3D12_INDIRECT_ARGUMENT_DESC_Constant, +}} + +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, UnorderedAccessView, UnorderedAccessView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_UnorderedAccessView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, ShaderResourceView, ShaderResourceView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_ShaderResourceView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, ConstantBufferView, ConstantBufferView_mut, + D3D12_INDIRECT_ARGUMENT_DESC_ConstantBufferView); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, Constant, Constant_mut, + D3D12_INDIRECT_ARGUMENT_DESC_Constant); +UNION!(D3D12_INDIRECT_ARGUMENT_DESC, u, VertexBuffer, VertexBuffer_mut, + D3D12_INDIRECT_ARGUMENT_DESC_VertexBuffer); + + + + +STRUCT!{struct D3D12_MEMCPY_DEST { + pData: *mut ::c_void, + RowPitch: ::SIZE_T, + SlicePitch: ::SIZE_T, +}} + +STRUCT!{struct D3D12_PACKED_MIP_INFO { + NumStandardMips: ::UINT8, + NumPackedMips: ::UINT8, + NumTilesForPackedMips: ::UINT, + StartTileIndexInOverallResource: ::UINT, +}} + +STRUCT!{struct D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: ::UINT64, + Footprint: ::D3D12_SUBRESOURCE_FOOTPRINT, +}} + +STRUCT!{struct D3D12_QUERY_DATA_PIPELINE_STATISTICS { + IAVertices: ::UINT64, + IAPrimitives: ::UINT64, + VSInvocations: ::UINT64, + GSInvocations: ::UINT64, + GSPrimitives: ::UINT64, + CInvocations: ::UINT64, + CPrimitives: ::UINT64, + PSInvocations: ::UINT64, + HSInvocations: ::UINT64, + DSInvocations: ::UINT64, + CSInvocations: ::UINT64, +}} + +STRUCT!{struct D3D12_QUERY_DATA_SO_STATISTICS { + NumPrimitivesWritten: ::UINT64, + PrimitivesStorageNeeded: ::UINT64, +}} + +STRUCT!{struct D3D12_QUERY_HEAP_DESC { + Type: ::D3D12_QUERY_HEAP_TYPE, + Count: ::UINT, + NodeMask: ::UINT, +}} + +STRUCT!{struct D3D12_RANGE { + Begin: ::SIZE_T, + End: ::SIZE_T, +}} + + + +STRUCT!{struct D3D12_RENDER_TARGET_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_RTV_DIMENSION, + u: ::D3D12_BUFFER_RTV, +}} + +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_RTV); +UNION!(D3D12_RENDER_TARGET_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_RTV); + +STRUCT!{struct D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: *mut ::ID3D12Resource, + pResourceAfter: *mut ::ID3D12Resource, +}} + +STRUCT!{struct D3D12_RESOURCE_ALLOCATION_INFO { + SizeInBytes: ::UINT64, + Alignment: ::UINT64, +}} + +STRUCT!{struct D3D12_RESOURCE_BARRIER { + Type: ::D3D12_RESOURCE_BARRIER_TYPE, + Flags: ::D3D12_RESOURCE_BARRIER_FLAGS, + u: ::D3D12_RESOURCE_TRANSITION_BARRIER, +}} + +UNION!(D3D12_RESOURCE_BARRIER, u, UAV, UAV_mut, ::D3D12_RESOURCE_UAV_BARRIER); +UNION!(D3D12_RESOURCE_BARRIER, u, Aliasing, Aliasing_mut, ::D3D12_RESOURCE_ALIASING_BARRIER); +UNION!(D3D12_RESOURCE_BARRIER, u, Transition, Transition_mut, ::D3D12_RESOURCE_TRANSITION_BARRIER); + +STRUCT!{struct D3D12_RESOURCE_DESC { + Dimension: ::D3D12_RESOURCE_DIMENSION, + Alignment: ::UINT64, + Width: ::UINT64, + Height: ::UINT, + DepthOrArraySize: ::UINT16, + MipLevels: ::UINT16, + Format: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, + Layout: ::D3D12_TEXTURE_LAYOUT, + Flags: ::D3D12_RESOURCE_FLAGS, +}} + +STRUCT!{struct D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: *mut ::ID3D12Resource, + Subresource: ::UINT, + StateBefore: ::D3D12_RESOURCE_STATES, + StateAfter: ::D3D12_RESOURCE_STATES, +}} + +STRUCT!{struct D3D12_RESOURCE_UAV_BARRIER { + pResource: *mut ::ID3D12Resource, +}} + +STRUCT!{struct D3D12_ROOT_CONSTANTS { + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, + Num32BitValues: ::UINT, +}} + +STRUCT!{struct D3D12_ROOT_DESCRIPTOR { + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, +}} + +STRUCT!{struct D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: ::UINT, + pDescriptorRanges: *const ::D3D12_DESCRIPTOR_RANGE, +}} + +#[cfg(target_pointer_width = "64")] +STRUCT!{struct D3D12_ROOT_PARAMETER { + ParameterType: ::D3D12_ROOT_PARAMETER_TYPE, + u: ::D3D12_ROOT_DESCRIPTOR_TABLE, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +#[cfg(target_pointer_width = "32")] +STRUCT!{struct D3D12_ROOT_PARAMETER { + ParameterType: ::D3D12_ROOT_PARAMETER_TYPE, + u: ::D3D12_ROOT_CONSTANTS, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +UNION!(D3D12_ROOT_PARAMETER, u, Descriptor, Descriptor_mut, ::D3D12_ROOT_DESCRIPTOR); +UNION!(D3D12_ROOT_PARAMETER, u, Constants, Constants_mut, ::D3D12_ROOT_CONSTANTS); +UNION!(D3D12_ROOT_PARAMETER, u, DescriptorTable, DescriptorTable_mut, + ::D3D12_ROOT_DESCRIPTOR_TABLE); + +STRUCT!{struct D3D12_ROOT_SIGNATURE_DESC { + NumParameters: ::UINT, + pParameters: *const ::D3D12_ROOT_PARAMETER, + NumStaticSamplers: ::UINT, + pStaticSamplers: *const ::D3D12_STATIC_SAMPLER_DESC, + Flags: ::D3D12_ROOT_SIGNATURE_FLAGS, +}} + +STRUCT!{struct D3D12_SAMPLER_DESC { + Filter: ::D3D12_FILTER, + AddressU: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressV: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressW: ::D3D12_TEXTURE_ADDRESS_MODE, + MipLODBias: ::FLOAT, + MaxAnisotropy: ::UINT, + ComparisonFunc: ::D3D12_COMPARISON_FUNC, + BorderColor: [::FLOAT; 4], + MinLOD: ::FLOAT, + MaxLOD: ::FLOAT, +}} + + + +STRUCT!{struct D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_SRV_DIMENSION, + Shader4ComponentMapping: ::UINT, + u: ::D3D12_BUFFER_SRV, +}} + +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, TextureCubeArray, TextureCubeArray_mut, + ::D3D12_TEXCUBE_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, TextureCube, TextureCube_mut, ::D3D12_TEXCUBE_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMSArray, Texture2DMSArray_mut, + ::D3D12_TEX2DMS_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DMS, Texture2DMS_mut, ::D3D12_TEX2DMS_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_SRV); +UNION!(D3D12_SHADER_RESOURCE_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_SRV); + + + +STRUCT!{struct D3D12_STATIC_SAMPLER_DESC { + Filter: ::D3D12_FILTER, + AddressU: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressV: ::D3D12_TEXTURE_ADDRESS_MODE, + AddressW: ::D3D12_TEXTURE_ADDRESS_MODE, + MipLODBias: ::FLOAT, + MaxAnisotropy: ::UINT, + ComparisonFunc: ::D3D12_COMPARISON_FUNC, + BorderColor: ::D3D12_STATIC_BORDER_COLOR, + MinLOD: ::FLOAT, + MaxLOD: ::FLOAT, + ShaderRegister: ::UINT, + RegisterSpace: ::UINT, + ShaderVisibility: ::D3D12_SHADER_VISIBILITY, +}} + +STRUCT!{struct D3D12_STREAM_OUTPUT_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT64, + BufferFilledSizeLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, +}} + + + +STRUCT!{struct D3D12_SUBRESOURCE_DATA { + pData: *const ::c_void, + RowPitch: ::LONG_PTR, + SlicePitch: ::LONG_PTR, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_FOOTPRINT { + Format: ::DXGI_FORMAT, + Width: ::UINT, + Height: ::UINT, + Depth: ::UINT, + RowPitch: ::UINT, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_INFO { + Offset: ::UINT64, + RowPitch: ::UINT, + DepthPitch: ::UINT, +}} + +STRUCT!{struct D3D12_SUBRESOURCE_TILING { + WidthInTiles: ::UINT, + HeightInTiles: ::UINT16, + DepthInTiles: ::UINT16, + StartTileIndexInOverallResource: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_DSV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_RTV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX1D_ARRAY_UAV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_DSV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_RTV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX1D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX1D_UAV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_DSV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_RTV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_ARRAY_SRV { + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_DSV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_RTV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2DMS_SRV { + UnusedField_NothingToDefine: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_DSV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_RTV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX2D_ARRAY_UAV { + MipSlice: ::UINT, + FirstArraySlice: ::UINT, + ArraySize: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_DSV { + MipSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_RTV { + MipSlice: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX2D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + PlaneSlice: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX2D_UAV { + MipSlice: ::UINT, + PlaneSlice: ::UINT, +}} + +STRUCT!{struct D3D12_TEX3D_RTV { + MipSlice: ::UINT, + FirstWSlice: ::UINT, + WSize: ::UINT, +}} + +STRUCT!{struct D3D12_TEX3D_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEX3D_UAV { + MipSlice: ::UINT, + FirstWSlice: ::UINT, + WSize: ::UINT, +}} + +STRUCT!{struct D3D12_TEXCUBE_ARRAY_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + First2DArrayFace: ::UINT, + NumCubes: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEXCUBE_SRV { + MostDetailedMip: ::UINT, + MipLevels: ::UINT, + ResourceMinLODClamp: ::FLOAT, +}} + +STRUCT!{struct D3D12_TEXTURE_COPY_LOCATION { + pResource: *mut ::ID3D12Resource, + Type: ::D3D12_TEXTURE_COPY_TYPE, + u: ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT, +}} + +UNION!(D3D12_TEXTURE_COPY_LOCATION, u, SubresourceIndex, SubresourceIndex_mut, ::UINT); +UNION!(D3D12_TEXTURE_COPY_LOCATION, u, PlacedFootprint, PlacedFootprint_mut, + ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT); + +STRUCT!{struct D3D12_TILED_RESOURCE_COORDINATE { + X: ::UINT, + Y: ::UINT, + Z: ::UINT, + Subresource: ::UINT, +}} + +STRUCT!{struct D3D12_TILE_REGION_SIZE { + NumTiles: ::UINT, + UseBox: ::BOOL, + Width: ::UINT, + Height: ::UINT16, + Depth: ::UINT16, +}} + +STRUCT!{struct D3D12_TILE_SHAPE { + WidthInTexels: ::UINT, + HeightInTexels: ::UINT, + DepthInTexels: ::UINT, +}} + +STRUCT!{struct D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: ::DXGI_FORMAT, + ViewDimension: ::D3D12_UAV_DIMENSION, + u: ::D3D12_BUFFER_UAV, +}} + +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture3D, Texture3D_mut, ::D3D12_TEX3D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture2DArray, Texture2DArray_mut, + ::D3D12_TEX2D_ARRAY_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture2D, Texture2D_mut, ::D3D12_TEX2D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture1DArray, Texture1DArray_mut, + ::D3D12_TEX1D_ARRAY_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Texture1D, Texture1D_mut, ::D3D12_TEX1D_UAV); +UNION!(D3D12_UNORDERED_ACCESS_VIEW_DESC, u, Buffer, Buffer_mut, ::D3D12_BUFFER_UAV); + +STRUCT!{struct D3D12_VERTEX_BUFFER_VIEW { + BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS, + SizeInBytes: ::UINT, + StrideInBytes: ::UINT, +}} + + + +RIDL!( +interface ID3D12CommandAllocator(ID3D12CommandAllocatorVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn Reset(&mut self) -> ::HRESULT +}); + +RIDL!( +interface ID3D12CommandList(ID3D12CommandListVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) { + fn GetType(&mut self) -> ::D3D12_COMMAND_LIST_TYPE +}); + +RIDL!( +interface ID3D12CommandQueue(ID3D12CommandQueueVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn UpdateTileMappings( + &mut self, pResource: *mut ::ID3D12Resource, NumResourceRegions: ::UINT, + pResourceRegionStartCoordinates: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pResourceRegionSizes: *const ::D3D12_TILE_REGION_SIZE, pHeap: *mut ::ID3D12Heap, + NumRanges: ::UINT, pRangeFlags: *const ::D3D12_TILE_RANGE_FLAGS, + pHeapRangeStartOffsets: *const ::UINT, pRangeTileCounts: *const ::UINT, + Flags: ::D3D12_TILE_MAPPING_FLAGS + ) -> (), + fn CopyTileMappings( + &mut self, pDstResource: *mut ::ID3D12Resource, + pDstRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pSrcResource: *mut ::ID3D12Resource, + pSrcRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pRegionSize: *const ::D3D12_TILE_REGION_SIZE, Flags: ::D3D12_TILE_MAPPING_FLAGS + ) -> (), + fn ExecuteCommandLists( + &mut self, NumCommandLists: ::UINT, ppCommandLists: *mut *mut ::ID3D12CommandList + ) -> (), + fn SetMarker( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn BeginEvent( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn EndEvent(&mut self) -> (), + fn Signal( + &mut self, pFence: *mut ::ID3D12Fence, Value: ::UINT64 + ) -> ::HRESULT, + fn Wait( + &mut self, pFence: *mut ::ID3D12Fence, Value: ::UINT64 + ) -> ::HRESULT, + fn GetTimestampFrequency(&mut self, pFrequency: *mut ::UINT64) -> ::HRESULT, + fn GetClockCalibration( + &mut self, pGpuTimestamp: *mut ::UINT64, pCpuTimestamp: *mut ::UINT64 + ) -> ::HRESULT, + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_COMMAND_QUEUE_DESC + ) -> *mut ::D3D12_COMMAND_QUEUE_DESC +}); + +RIDL!( +interface ID3D12CommandSignature(ID3D12CommandSignatureVtbl): ID3D12Pageable(ID3D12PageableVtbl) { +}); + +RIDL!( +interface ID3D12DescriptorHeap(ID3D12DescriptorHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_DESCRIPTOR_HEAP_DESC + ) -> *mut ::D3D12_DESCRIPTOR_HEAP_DESC, + fn GetCPUDescriptorHandleForHeapStart( + &mut self, __ret_val: *mut ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> *mut ::D3D12_CPU_DESCRIPTOR_HANDLE, + fn GetGPUDescriptorHandleForHeapStart( + &mut self, __ret_val: *mut ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> *mut ::D3D12_GPU_DESCRIPTOR_HANDLE +}); + + + +RIDL!( +interface ID3D12Device(ID3D12DeviceVtbl): ID3D12Object(ID3D12ObjectVtbl) { + fn GetNodeCount(&mut self) -> ::UINT, + fn CreateCommandQueue( + &mut self, pDesc: *const ::D3D12_COMMAND_QUEUE_DESC, riid: ::REFGUID, + ppCommandQueue: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateCommandAllocator( + &mut self, type_: ::D3D12_COMMAND_LIST_TYPE, riid: ::REFGUID, + ppCommandAllocator: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateGraphicsPipelineState( + &mut self, pDesc: *const ::D3D12_GRAPHICS_PIPELINE_STATE_DESC, riid: ::REFGUID, + ppPipelineState: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateComputePipelineState( + &mut self, pDesc: *const ::D3D12_COMPUTE_PIPELINE_STATE_DESC, riid: ::REFGUID, + ppPipelineState: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateCommandList( + &mut self, nodeMask: ::UINT, type_: ::D3D12_COMMAND_LIST_TYPE, + pCommandAllocator: *mut ::ID3D12CommandAllocator, + pInitialState: *mut ::ID3D12PipelineState, riid: ::REFGUID, + ppCommandList: *mut *mut ::c_void + ) -> ::HRESULT, + fn CheckFeatureSupport( + &mut self, Feature: ::D3D12_FEATURE, pFeatureSupportData: *mut ::c_void, + FeatureSupportDataSize: ::UINT + ) -> ::HRESULT, + fn CreateDescriptorHeap( + &mut self, pDescriptorHeapDesc: *const ::D3D12_DESCRIPTOR_HEAP_DESC, riid: ::REFGUID, + ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetDescriptorHandleIncrementSize( + &mut self, DescriptorHeapType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> ::UINT, + fn CreateRootSignature( + &mut self, nodeMask: ::UINT, pBlobWithRootSignature: *const ::c_void, + blobLengthInBytes: ::SIZE_T, riid: ::REFGUID, ppvRootSignature: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateConstantBufferView( + &mut self, pDesc: *const ::D3D12_CONSTANT_BUFFER_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateShaderResourceView( + &mut self, pResource: *mut ::ID3D12Resource, + pDesc: *const ::D3D12_SHADER_RESOURCE_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateUnorderedAccessView( + &mut self, pResource: *mut ::ID3D12Resource, pCounterResource: *mut ::ID3D12Resource, + pDesc: *const ::D3D12_UNORDERED_ACCESS_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateRenderTargetView( + &mut self, pResource: *mut ::ID3D12Resource, pDesc: *const ::D3D12_RENDER_TARGET_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateDepthStencilView( + &mut self, pResource: *mut ::ID3D12Resource, pDesc: *const ::D3D12_DEPTH_STENCIL_VIEW_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CreateSampler( + &mut self, pDesc: *const ::D3D12_SAMPLER_DESC, + DestDescriptor: ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn CopyDescriptors( + &mut self, NumDestDescriptorRanges: ::UINT, + pDestDescriptorRangeStarts: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + pDestDescriptorRangeSizes: *const ::UINT, NumSrcDescriptorRanges: ::UINT, + pSrcDescriptorRangeStarts: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + pSrcDescriptorRangeSizes: *const ::UINT, DescriptorHeapsType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> (), + fn CopyDescriptorsSimple( + &mut self, NumDescriptors: ::UINT, DestDescriptorRangeStart: ::D3D12_CPU_DESCRIPTOR_HANDLE, + SrcDescriptorRangeStart: ::D3D12_CPU_DESCRIPTOR_HANDLE, + DescriptorHeapsType: ::D3D12_DESCRIPTOR_HEAP_TYPE + ) -> (), + fn GetResourceAllocationInfo( + &mut self, visibleMask: ::UINT, numResourceDescs: ::UINT, + pResourceDescs: *const ::D3D12_RESOURCE_DESC, + __ret_val: *mut ::D3D12_RESOURCE_ALLOCATION_INFO + ) -> *mut ::D3D12_RESOURCE_ALLOCATION_INFO, + fn GetCustomHeapProperties( + &mut self, nodeMask: ::UINT, heapType: ::D3D12_HEAP_TYPE, + __ret_val: *mut ::D3D12_HEAP_PROPERTIES + ) -> *mut ::D3D12_HEAP_PROPERTIES, + fn CreateCommittedResource( + &mut self, pHeapProperties: *const ::D3D12_HEAP_PROPERTIES, HeapFlags: ::D3D12_HEAP_FLAGS, + pResourceDesc: *const ::D3D12_RESOURCE_DESC, InitialResourceState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riidResource: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateHeap( + &mut self, pDesc: *const ::D3D12_HEAP_DESC, riid: ::REFGUID, ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreatePlacedResource( + &mut self, pHeap: *mut ::ID3D12Heap, HeapOffset: ::UINT64, + pDesc: *const ::D3D12_RESOURCE_DESC, InitialState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riid: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateReservedResource( + &mut self, pDesc: *const ::D3D12_RESOURCE_DESC, InitialState: ::D3D12_RESOURCE_STATES, + pOptimizedClearValue: *const ::D3D12_CLEAR_VALUE, riid: ::REFGUID, + ppvResource: *mut *mut ::c_void + ) -> ::HRESULT, + fn CreateSharedHandle( + &mut self, pObject: *mut ::ID3D12DeviceChild, pAttributes: *const ::SECURITY_ATTRIBUTES, + Access: ::DWORD, Name: ::LPCWSTR, pHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn OpenSharedHandle( + &mut self, NTHandle: ::HANDLE, riid: ::REFGUID, ppvObj: *mut *mut ::c_void + ) -> ::HRESULT, + fn OpenSharedHandleByName( + &mut self, Name: ::LPCWSTR, Access: ::DWORD, pNTHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn MakeResident( + &mut self, NumObjects: ::UINT, ppObjects: *mut *mut ::ID3D12Pageable + ) -> ::HRESULT, + fn Evict( + &mut self, NumObjects: ::UINT, ppObjects: *mut *mut ::ID3D12Pageable + ) -> ::HRESULT, + fn CreateFence( + &mut self, InitialValue: ::UINT64, Flags: ::D3D12_FENCE_FLAGS, riid: ::REFGUID, + ppFence: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetDeviceRemovedReason(&mut self) -> ::HRESULT, + fn GetCopyableFootprints( + &mut self, pResourceDesc: *const ::D3D12_RESOURCE_DESC, FirstSubresource: ::UINT, + NumSubresources: ::UINT, BaseOffset: ::UINT64, + pLayouts: *mut ::D3D12_PLACED_SUBRESOURCE_FOOTPRINT, pNumRows: *mut ::UINT, + pRowSizeInBytes: *mut ::UINT64, pTotalBytes: *mut ::UINT64 + ) -> (), + fn CreateQueryHeap( + &mut self, pDesc: *const ::D3D12_QUERY_HEAP_DESC, riid: ::REFGUID, + ppvHeap: *mut *mut ::c_void + ) -> ::HRESULT, + fn SetStablePowerState(&mut self, Enable: ::BOOL) -> ::HRESULT, + fn CreateCommandSignature( + &mut self, pDesc: *const ::D3D12_COMMAND_SIGNATURE_DESC, + pRootSignature: *mut ::ID3D12RootSignature, riid: ::REFGUID, + ppvCommandSignature: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetResourceTiling( + &mut self, pTiledResource: *mut ::ID3D12Resource, pNumTilesForEntireResource: *mut ::UINT, + pPackedMipDesc: *mut ::D3D12_PACKED_MIP_INFO, + pStandardTileShapeForNonPackedMips: *mut ::D3D12_TILE_SHAPE, + pNumSubresourceTilings: *mut ::UINT, FirstSubresourceTilingToGet: ::UINT, + pSubresourceTilingsForNonPackedMips: *mut ::D3D12_SUBRESOURCE_TILING + ) -> (), + fn GetAdapterLuid(&mut self, __ret_val: *mut ::LUID) -> *mut ::LUID +}); + +RIDL!( +interface ID3D12Fence(ID3D12FenceVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetCompletedValue(&mut self) -> ::UINT64, + fn SetEventOnCompletion( + &mut self, Value: ::UINT64, hEvent: ::HANDLE + ) -> ::HRESULT, + fn Signal(&mut self, Value: ::UINT64) -> ::HRESULT +}); + +RIDL!( +interface ID3D12GraphicsCommandList(ID3D12GraphicsCommandListVtbl): ID3D12CommandList(ID3D12CommandListVtbl) { + fn Close(&mut self) -> ::HRESULT, + fn Reset( + &mut self, pAllocator: *mut ::ID3D12CommandAllocator, + pInitialState: *mut ::ID3D12PipelineState + ) -> ::HRESULT, + fn ClearState(&mut self, pPipelineState: *mut ::ID3D12PipelineState) -> (), + fn DrawInstanced( + &mut self, VertexCountPerInstance: ::UINT, InstanceCount: ::UINT, + StartVertexLocation: ::UINT, StartInstanceLocation: ::UINT + ) -> (), + fn DrawIndexedInstanced( + &mut self, IndexCountPerInstance: ::UINT, InstanceCount: ::UINT, + StartIndexLocation: ::UINT, BaseVertexLocation: ::INT, StartInstanceLocation: ::UINT + ) -> (), + fn Dispatch( + &mut self, ThreadGroupCountX: ::UINT, ThreadGroupCountY: ::UINT, ThreadGroupCountZ: ::UINT + ) -> (), + fn CopyBufferRegion( + &mut self, pDstBuffer: *mut ::ID3D12Resource, DstOffset: ::UINT64, + pSrcBuffer: *mut ::ID3D12Resource, SrcOffset: ::UINT64, NumBytes: ::UINT64 + ) -> (), + fn CopyTextureRegion( + &mut self, pDst: *const ::D3D12_TEXTURE_COPY_LOCATION, DstX: ::UINT, DstY: ::UINT, + DstZ: ::UINT, pSrc: *const ::D3D12_TEXTURE_COPY_LOCATION, pSrcBox: *const ::D3D12_BOX + ) -> (), + fn CopyResource( + &mut self, pDstResource: *mut ::ID3D12Resource, pSrcResource: *mut ::ID3D12Resource + ) -> (), + fn CopyTiles( + &mut self, pTiledResource: *mut ::ID3D12Resource, + pTileRegionStartCoordinate: *const ::D3D12_TILED_RESOURCE_COORDINATE, + pTileRegionSize: *const ::D3D12_TILE_REGION_SIZE, pBuffer: *mut ::ID3D12Resource, + BufferStartOffsetInBytes: ::UINT64, Flags: ::D3D12_TILE_COPY_FLAGS + ) -> (), + fn ResolveSubresource( + &mut self, pDstResource: *mut ::ID3D12Resource, DstSubresource: ::UINT, + pSrcResource: *mut ::ID3D12Resource, SrcSubresource: ::UINT, Format: ::DXGI_FORMAT + ) -> (), + fn IASetPrimitiveTopology( + &mut self, PrimitiveTopology: ::D3D12_PRIMITIVE_TOPOLOGY + ) -> (), + fn RSSetViewports( + &mut self, NumViewports: ::UINT, pViewports: *const ::D3D12_VIEWPORT + ) -> (), + fn RSSetScissorRects( + &mut self, NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn OMSetBlendFactor(&mut self, BlendFactor: *const [::FLOAT; 4]) -> (), + fn OMSetStencilRef(&mut self, StencilRef: ::UINT) -> (), + fn SetPipelineState( + &mut self, pPipelineState: *mut ::ID3D12PipelineState + ) -> (), + fn ResourceBarrier( + &mut self, NumBarriers: ::UINT, pBarriers: *const ::D3D12_RESOURCE_BARRIER + ) -> (), + fn ExecuteBundle( + &mut self, pCommandList: *mut ::ID3D12GraphicsCommandList + ) -> (), + fn SetDescriptorHeaps( + &mut self, NumDescriptorHeaps: ::UINT, ppDescriptorHeaps: *mut *mut ::ID3D12DescriptorHeap + ) -> (), + fn SetComputeRootSignature( + &mut self, pRootSignature: *mut ::ID3D12RootSignature + ) -> (), + fn SetGraphicsRootSignature( + &mut self, pRootSignature: *mut ::ID3D12RootSignature + ) -> (), + fn SetComputeRootDescriptorTable( + &mut self, RootParameterIndex: ::UINT, BaseDescriptor: ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> (), + fn SetGraphicsRootDescriptorTable( + &mut self, RootParameterIndex: ::UINT, BaseDescriptor: ::D3D12_GPU_DESCRIPTOR_HANDLE + ) -> (), + fn SetComputeRoot32BitConstant( + &mut self, RootParameterIndex: ::UINT, SrcData: ::UINT, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetGraphicsRoot32BitConstant( + &mut self, RootParameterIndex: ::UINT, SrcData: ::UINT, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetComputeRoot32BitConstants( + &mut self, RootParameterIndex: ::UINT, Num32BitValuesToSet: ::UINT, + pSrcData: *const ::c_void, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetGraphicsRoot32BitConstants( + &mut self, RootParameterIndex: ::UINT, Num32BitValuesToSet: ::UINT, + pSrcData: *const ::c_void, DestOffsetIn32BitValues: ::UINT + ) -> (), + fn SetComputeRootConstantBufferView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootConstantBufferView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetComputeRootShaderResourceView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootShaderResourceView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetComputeRootUnorderedAccessView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn SetGraphicsRootUnorderedAccessView( + &mut self, RootParameterIndex: ::UINT, BufferLocation: ::D3D12_GPU_VIRTUAL_ADDRESS + ) -> (), + fn IASetIndexBuffer( + &mut self, pView: *const ::D3D12_INDEX_BUFFER_VIEW + ) -> (), + fn IASetVertexBuffers( + &mut self, StartSlot: ::UINT, NumViews: ::UINT, pViews: *const ::D3D12_VERTEX_BUFFER_VIEW + ) -> (), + fn SOSetTargets( + &mut self, StartSlot: ::UINT, NumViews: ::UINT, + pViews: *const ::D3D12_STREAM_OUTPUT_BUFFER_VIEW + ) -> (), + fn OMSetRenderTargets( + &mut self, NumRenderTargetDescriptors: ::UINT, + pRenderTargetDescriptors: *const ::D3D12_CPU_DESCRIPTOR_HANDLE, + RTsSingleHandleToDescriptorRange: ::BOOL, + pDepthStencilDescriptor: *const ::D3D12_CPU_DESCRIPTOR_HANDLE + ) -> (), + fn ClearDepthStencilView( + &mut self, DepthStencilView: ::D3D12_CPU_DESCRIPTOR_HANDLE, + ClearFlags: ::D3D12_CLEAR_FLAGS, Depth: ::FLOAT, Stencil: ::UINT8, NumRects: ::UINT, + pRects: *const ::D3D12_RECT + ) -> (), + fn ClearRenderTargetView( + &mut self, RenderTargetView: ::D3D12_CPU_DESCRIPTOR_HANDLE, ColorRGBA: *const [::FLOAT; 4], + NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn ClearUnorderedAccessViewUint( + &mut self, ViewGPUHandleInCurrentHeap: ::D3D12_GPU_DESCRIPTOR_HANDLE, + ViewCPUHandle: ::D3D12_CPU_DESCRIPTOR_HANDLE, pResource: *mut ::ID3D12Resource, + Values: *const [::UINT; 4], NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn ClearUnorderedAccessViewFloat( + &mut self, ViewGPUHandleInCurrentHeap: ::D3D12_GPU_DESCRIPTOR_HANDLE, + ViewCPUHandle: ::D3D12_CPU_DESCRIPTOR_HANDLE, pResource: *mut ::ID3D12Resource, + Values: *const [::FLOAT; 4], NumRects: ::UINT, pRects: *const ::D3D12_RECT + ) -> (), + fn DiscardResource( + &mut self, pResource: *mut ::ID3D12Resource, pRegion: *const ::D3D12_DISCARD_REGION + ) -> (), + fn BeginQuery( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, Index: ::UINT + ) -> (), + fn EndQuery( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, Index: ::UINT + ) -> (), + fn ResolveQueryData( + &mut self, pQueryHeap: *mut ::ID3D12QueryHeap, Type: ::D3D12_QUERY_TYPE, + StartIndex: ::UINT, NumQueries: ::UINT, pDestinationBuffer: *mut ::ID3D12Resource, + AlignedDestinationBufferOffset: ::UINT64 + ) -> (), + fn SetPredication( + &mut self, pBuffer: *mut ::ID3D12Resource, AlignedBufferOffset: ::UINT64, + Operation: ::D3D12_PREDICATION_OP + ) -> (), + fn SetMarker( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn BeginEvent( + &mut self, Metadata: ::UINT, pData: *const ::c_void, Size: ::UINT + ) -> (), + fn EndEvent(&mut self) -> (), + fn ExecuteIndirect( + &mut self, pCommandSignature: *mut ::ID3D12CommandSignature, MaxCommandCount: ::UINT, + pArgumentBuffer: *mut ::ID3D12Resource, ArgumentBufferOffset: ::UINT64, + pCountBuffer: *mut ::ID3D12Resource, CountBufferOffset: ::UINT64 + ) -> () +}); + +RIDL!( +interface ID3D12Heap(ID3D12HeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_HEAP_DESC + ) -> *mut ::D3D12_HEAP_DESC +}); + + + +RIDL!( +interface ID3D12Pageable(ID3D12PageableVtbl): ID3D12DeviceChild(ID3D12DeviceChildVtbl) { +}); + +RIDL!( +interface ID3D12PipelineState(ID3D12PipelineStateVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn GetCachedBlob(&mut self, ppBlob: *mut *mut ::ID3DBlob) -> ::HRESULT +}); + +RIDL!( +interface ID3D12QueryHeap(ID3D12QueryHeapVtbl): ID3D12Pageable(ID3D12PageableVtbl) { +}); + +RIDL!( +interface ID3D12Resource(ID3D12ResourceVtbl): ID3D12Pageable(ID3D12PageableVtbl) { + fn Map( + &mut self, Subresource: ::UINT, pReadRange: *const ::D3D12_RANGE, + ppData: *mut *mut ::c_void + ) -> ::HRESULT, + fn Unmap( + &mut self, Subresource: ::UINT, pWrittenRange: *const ::D3D12_RANGE + ) -> (), + fn GetDesc( + &mut self, __ret_val: *mut ::D3D12_RESOURCE_DESC + ) -> *mut ::D3D12_RESOURCE_DESC, + fn GetGPUVirtualAddress(&mut self) -> ::D3D12_GPU_VIRTUAL_ADDRESS, + fn WriteToSubresource( + &mut self, DstSubresource: ::UINT, pDstBox: *const ::D3D12_BOX, pSrcData: *const ::c_void, + SrcRowPitch: ::UINT, SrcDepthPitch: ::UINT + ) -> ::HRESULT, + fn ReadFromSubresource( + &mut self, pDstData: *mut ::c_void, DstRowPitch: ::UINT, DstDepthPitch: ::UINT, + SrcSubresource: ::UINT, pSrcBox: *const ::D3D12_BOX + ) -> ::HRESULT, + fn GetHeapProperties( + &mut self, pHeapProperties: *mut ::D3D12_HEAP_PROPERTIES, + pHeapFlags: *mut ::D3D12_HEAP_FLAGS + ) -> ::HRESULT +}); + +RIDL!( +interface ID3D12RootSignatureDeserializer(ID3D12RootSignatureDeserializerVtbl): IUnknown(IUnknownVtbl) { + fn GetRootSignatureDesc(&mut self) -> *const ::D3D12_ROOT_SIGNATURE_DESC +}); + + + +pub type PFN_D3D12_CREATE_DEVICE = extern "system" fn (_ : *mut ::IUnknown, _ : ::D3D_FEATURE_LEVEL, _ : ::REFGUID, _ : *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_CREATE_ROOT_SIGNATURE_DESERIALIZER = extern "system" fn (pSrcData: ::LPCVOID, SrcDataSizeInBytes: ::SIZE_T, pRootSignatureDeserializerInterface: ::REFGUID, ppRootSignatureDeserializer: *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_GET_DEBUG_INTERFACE = extern "system" fn (_ : ::REFGUID, _ : *mut *mut ::c_void) -> ::HRESULT; +pub type PFN_D3D12_SERIALIZE_ROOT_SIGNATURE = extern "system" fn (pRootSignature: *const ::D3D12_ROOT_SIGNATURE_DESC, Version: ::D3D_ROOT_SIGNATURE_VERSION, ppBlob: *mut *mut ::ID3DBlob, ppErrorBlob: *mut *mut ::ID3DBlob) -> ::HRESULT; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d12sdklayers.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12sdklayers.rs new file mode 100644 index 0000000..f159886 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12sdklayers.rs @@ -0,0 +1,1063 @@ +// Copyright © 2015, Dmitry Roschin +// Licensed under the MIT License +RIDL!{interface ID3D12Debug(ID3D12DebugVtbl): IUnknown(IUnknownVtbl) { + fn EnableDebugLayer(&mut self) -> () +}} +FLAGS!{enum D3D12_DEBUG_FEATURE { + D3D12_DEBUG_FEATURE_NONE = 0, + D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DRAW = 0x1, + D3D12_DEBUG_FEATURE_TREAT_BUNDLE_AS_DISPATCH = 0x2, +}} +FLAGS!{enum D3D12_RLDO_FLAGS { + D3D12_RLDO_NONE = 0x0, + D3D12_RLDO_SUMMARY = 0x1, + D3D12_RLDO_DETAIL = 0x2, + D3D12_RLDO_IGNORE_INTERNAL = 0x4, +}} +RIDL!{interface ID3D12DebugDevice(ID3D12DebugDeviceVtbl): IUnknown(IUnknownVtbl) { + fn SetFeatureMask(&mut self, Mask: ::D3D12_DEBUG_FEATURE) -> ::HRESULT, + fn GetFeatureMask(&mut self) -> ::D3D12_DEBUG_FEATURE, + fn ReportLiveDeviceObjects(&mut self, Flags: ::D3D12_RLDO_FLAGS) -> ::HRESULT +}} +RIDL!{interface ID3D12DebugCommandQueue(ID3D12DebugCommandQueueVtbl): IUnknown(IUnknownVtbl) { + fn AssertResourceState( + &mut self, pResource: *mut ::ID3D12Resource, Subresource: ::UINT, State: ::UINT + ) -> ::BOOL +}} +RIDL!{interface ID3D12DebugCommandList(ID3D12DebugCommandListVtbl): IUnknown(IUnknownVtbl) { + fn AssertResourceState( + &mut self, pResource: *mut ::ID3D12Resource, Subresource: ::UINT, State: ::UINT + ) -> ::BOOL, + fn SetFeatureMask(&mut self, Mask: ::D3D12_DEBUG_FEATURE) -> ::HRESULT, + fn GetFeatureMask(&mut self) -> ::D3D12_DEBUG_FEATURE +}} +ENUM!{enum D3D12_MESSAGE_CATEGORY { + D3D12_MESSAGE_CATEGORY_APPLICATION_DEFINED = 0, + D3D12_MESSAGE_CATEGORY_MISCELLANEOUS = 1, + D3D12_MESSAGE_CATEGORY_INITIALIZATION = 2, + D3D12_MESSAGE_CATEGORY_CLEANUP = 3, + D3D12_MESSAGE_CATEGORY_COMPILATION = 4, + D3D12_MESSAGE_CATEGORY_STATE_CREATION = 5, + D3D12_MESSAGE_CATEGORY_STATE_SETTING = 6, + D3D12_MESSAGE_CATEGORY_STATE_GETTING = 7, + D3D12_MESSAGE_CATEGORY_RESOURCE_MANIPULATION = 8, + D3D12_MESSAGE_CATEGORY_EXECUTION = 9, + D3D12_MESSAGE_CATEGORY_SHADER = 10, +}} +ENUM!{enum D3D12_MESSAGE_SEVERITY { + D3D12_MESSAGE_SEVERITY_CORRUPTION = 0, + D3D12_MESSAGE_SEVERITY_ERROR = 1, + D3D12_MESSAGE_SEVERITY_WARNING = 2, + D3D12_MESSAGE_SEVERITY_INFO = 3, + D3D12_MESSAGE_SEVERITY_MESSAGE = 4, +}} +ENUM!{enum D3D12_MESSAGE_ID { + D3D12_MESSAGE_ID_UNKNOWN = 0, + D3D12_MESSAGE_ID_STRING_FROM_APPLICATION = 1, + D3D12_MESSAGE_ID_CORRUPTED_THIS = 2, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER1 = 3, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER2 = 4, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER3 = 5, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER4 = 6, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER5 = 7, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER6 = 8, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER7 = 9, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER8 = 10, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER9 = 11, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER10 = 12, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER11 = 13, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER12 = 14, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER13 = 15, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER14 = 16, + D3D12_MESSAGE_ID_CORRUPTED_PARAMETER15 = 17, + D3D12_MESSAGE_ID_CORRUPTED_MULTITHREADING = 18, + D3D12_MESSAGE_ID_MESSAGE_REPORTING_OUTOFMEMORY = 19, + D3D12_MESSAGE_ID_GETPRIVATEDATA_MOREDATA = 20, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFREEDATA = 21, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDIUNKNOWN = 22, + D3D12_MESSAGE_ID_SETPRIVATEDATA_INVALIDFLAGS = 23, + D3D12_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS = 24, + D3D12_MESSAGE_ID_SETPRIVATEDATA_OUTOFMEMORY = 25, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_UNRECOGNIZEDFORMAT = 26, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDESC = 27, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFORMAT = 28, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANESLICE = 29, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANESLICE = 30, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDIMENSIONS = 31, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDRESOURCE = 32, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDARG_RETURN = 33, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_OUTOFMEMORY_RETURN = 34, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNRECOGNIZEDFORMAT = 35, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_UNSUPPORTEDFORMAT = 36, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDESC = 37, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDFORMAT = 38, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANESLICE = 39, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANESLICE = 40, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDIMENSIONS = 41, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDRESOURCE = 42, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDARG_RETURN = 43, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_OUTOFMEMORY_RETURN = 44, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_UNRECOGNIZEDFORMAT = 45, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDESC = 46, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFORMAT = 47, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDDIMENSIONS = 48, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDRESOURCE = 49, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDARG_RETURN = 50, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_OUTOFMEMORY_RETURN = 51, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_OUTOFMEMORY = 52, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TOOMANYELEMENTS = 53, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDFORMAT = 54, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INCOMPATIBLEFORMAT = 55, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOT = 56, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDINPUTSLOTCLASS = 57, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_STEPRATESLOTCLASSMISMATCH = 58, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSLOTCLASSCHANGE = 59, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDSTEPRATECHANGE = 60, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_INVALIDALIGNMENT = 61, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_DUPLICATESEMANTIC = 62, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE = 63, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_NULLSEMANTIC = 64, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_MISSINGELEMENT = 65, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_OUTOFMEMORY = 66, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE = 67, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERTYPE = 68, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_OUTOFMEMORY = 69, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERBYTECODE = 70, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDSHADERTYPE = 71, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTOFMEMORY = 72, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERBYTECODE = 73, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSHADERTYPE = 74, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMENTRIES = 75, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSTREAMSTRIDEUNUSED = 76, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDDECL = 77, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_EXPECTEDDECL = 78, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_OUTPUTSLOT0EXPECTED = 79, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSLOT = 80, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_ONLYONEELEMENTPERSLOT = 81, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCOMPONENTCOUNT = 82, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTARTCOMPONENTANDCOMPONENTCOUNT = 83, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDGAPDEFINITION = 84, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_REPEATEDOUTPUT = 85, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDOUTPUTSTREAMSTRIDE = 86, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGSEMANTIC = 87, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MASKMISMATCH = 88, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_CANTHAVEONLYGAPS = 89, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DECLTOOCOMPLEX = 90, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_MISSINGOUTPUTSIGNATURE = 91, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_OUTOFMEMORY = 92, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE = 93, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERTYPE = 94, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFILLMODE = 95, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDCULLMODE = 96, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDDEPTHBIASCLAMP = 97, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDSLOPESCALEDDEPTHBIAS = 98, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_NULLDESC = 99, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHWRITEMASK = 100, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDDEPTHFUNC = 101, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFAILOP = 102, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILZFAILOP = 103, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILPASSOP = 104, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDFRONTFACESTENCILFUNC = 105, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFAILOP = 106, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILZFAILOP = 107, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILPASSOP = 108, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_INVALIDBACKFACESTENCILFUNC = 109, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILSTATE_NULLDESC = 110, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLEND = 111, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLEND = 112, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOP = 113, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDSRCBLENDALPHA = 114, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDDESTBLENDALPHA = 115, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDBLENDOPALPHA = 116, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDRENDERTARGETWRITEMASK = 117, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_NULLDESC = 118, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDFILTER = 119, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSU = 120, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSV = 121, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDADDRESSW = 122, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMIPLODBIAS = 123, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXANISOTROPY = 124, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDCOMPARISONFUNC = 125, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMINLOD = 126, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_INVALIDMAXLOD = 127, + D3D12_MESSAGE_ID_CREATESAMPLERSTATE_NULLDESC = 128, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNRECOGNIZED = 129, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNDEFINED = 130, + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_INVALIDVIEWPORT = 131, + D3D12_MESSAGE_ID_DEVICE_RSSETSCISSORRECTS_INVALIDSCISSOR = 132, + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_DENORMFLUSH = 133, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DENORMFLUSH = 134, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALID = 135, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCE = 136, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDDESTINATIONSTATE = 137, + D3D12_MESSAGE_ID_COPYRESOURCE_INVALIDSOURCESTATE = 138, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSUBRESOURCE = 139, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONBOX = 140, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_INVALIDDESTINATIONSTATE = 141, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_INVALID = 142, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_DESTINATION_SUBRESOURCE_INVALID = 143, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_INVALID = 144, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_SOURCE_SUBRESOURCE_INVALID = 145, + D3D12_MESSAGE_ID_DEVICE_RESOLVESUBRESOURCE_FORMAT_INVALID = 146, + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDMAPTYPE = 147, + D3D12_MESSAGE_ID_BUFFER_MAP_INVALIDFLAGS = 148, + D3D12_MESSAGE_ID_BUFFER_MAP_ALREADYMAPPED = 149, + D3D12_MESSAGE_ID_BUFFER_MAP_DEVICEREMOVED_RETURN = 150, + D3D12_MESSAGE_ID_BUFFER_UNMAP_NOTMAPPED = 151, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDMAPTYPE = 152, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDSUBRESOURCE = 153, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_INVALIDFLAGS = 154, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_ALREADYMAPPED = 155, + D3D12_MESSAGE_ID_TEXTURE1D_MAP_DEVICEREMOVED_RETURN = 156, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_INVALIDSUBRESOURCE = 157, + D3D12_MESSAGE_ID_TEXTURE1D_UNMAP_NOTMAPPED = 158, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDMAPTYPE = 159, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDSUBRESOURCE = 160, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_INVALIDFLAGS = 161, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_ALREADYMAPPED = 162, + D3D12_MESSAGE_ID_TEXTURE2D_MAP_DEVICEREMOVED_RETURN = 163, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_INVALIDSUBRESOURCE = 164, + D3D12_MESSAGE_ID_TEXTURE2D_UNMAP_NOTMAPPED = 165, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDMAPTYPE = 166, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDSUBRESOURCE = 167, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_INVALIDFLAGS = 168, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_ALREADYMAPPED = 169, + D3D12_MESSAGE_ID_TEXTURE3D_MAP_DEVICEREMOVED_RETURN = 170, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_INVALIDSUBRESOURCE = 171, + D3D12_MESSAGE_ID_TEXTURE3D_UNMAP_NOTMAPPED = 172, + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_DEPRECATED = 173, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_FORMAT_DEPRECATED = 174, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_UNRECOGNIZEDFLAGS = 175, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_INVALIDARG_RETURN = 176, + D3D12_MESSAGE_ID_SETEXCEPTIONMODE_DEVICEREMOVED_RETURN = 177, + D3D12_MESSAGE_ID_REF_SIMULATING_INFINITELY_FAST_HARDWARE = 178, + D3D12_MESSAGE_ID_REF_THREADING_MODE = 179, + D3D12_MESSAGE_ID_REF_UMDRIVER_EXCEPTION = 180, + D3D12_MESSAGE_ID_REF_KMDRIVER_EXCEPTION = 181, + D3D12_MESSAGE_ID_REF_HARDWARE_EXCEPTION = 182, + D3D12_MESSAGE_ID_REF_ACCESSING_INDEXABLE_TEMP_OUT_OF_RANGE = 183, + D3D12_MESSAGE_ID_REF_PROBLEM_PARSING_SHADER = 184, + D3D12_MESSAGE_ID_REF_OUT_OF_MEMORY = 185, + D3D12_MESSAGE_ID_REF_INFO = 186, + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEXPOS_OVERFLOW = 187, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXED_INDEXPOS_OVERFLOW = 188, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_VERTEXPOS_OVERFLOW = 189, + D3D12_MESSAGE_ID_DEVICE_DRAWINSTANCED_INSTANCEPOS_OVERFLOW = 190, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INSTANCEPOS_OVERFLOW = 191, + D3D12_MESSAGE_ID_DEVICE_DRAWINDEXEDINSTANCED_INDEXPOS_OVERFLOW = 192, + D3D12_MESSAGE_ID_DEVICE_DRAW_VERTEX_SHADER_NOT_SET = 193, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND = 194, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERINDEX = 195, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_COMPONENTTYPE = 196, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_REGISTERMASK = 197, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_SYSTEMVALUE = 198, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS = 199, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_NOT_SET = 200, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_ROOT_SIGNATURE_MISMATCH = 201, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_NOT_SET = 202, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INPUTLAYOUT_NOT_SET = 203, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_NOT_SET = 204, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_CONSTANT_BUFFER_TOO_SMALL = 205, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SAMPLER_NOT_SET = 206, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SHADERRESOURCEVIEW_NOT_SET = 207, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VIEW_DIMENSION_MISMATCH = 208, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_STRIDE_TOO_SMALL = 209, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_BUFFER_TOO_SMALL = 210, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_NOT_SET = 211, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_FORMAT_INVALID = 212, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_BUFFER_TOO_SMALL = 213, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_GS_INPUT_PRIMITIVE_MISMATCH = 214, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_RETURN_TYPE_MISMATCH = 215, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_POSITION_NOT_PRESENT = 216, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_NOT_SET = 217, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_BOUND_RESOURCE_MAPPED = 218, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INVALID_PRIMITIVETOPOLOGY = 219, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_OFFSET_UNALIGNED = 220, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_VERTEX_STRIDE_UNALIGNED = 221, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_INDEX_OFFSET_UNALIGNED = 222, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OUTPUT_STREAM_OFFSET_UNALIGNED = 223, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_LD_UNSUPPORTED = 224, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_UNSUPPORTED = 225, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_FORMAT_SAMPLE_C_UNSUPPORTED = 226, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RESOURCE_MULTISAMPLE_UNSUPPORTED = 227, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_TARGETS_BOUND_WITHOUT_SOURCE = 228, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_SO_STRIDE_LARGER_THAN_BUFFER = 229, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING = 230, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 = 231, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_AT_FAULT = 232, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_POSSIBLY_AT_FAULT = 233, + D3D12_MESSAGE_ID_DEVICE_REMOVAL_PROCESS_NOT_AT_FAULT = 234, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_INVALIDARG_RETURN = 235, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_OUTOFMEMORY_RETURN = 236, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BADINTERFACE_RETURN = 237, + D3D12_MESSAGE_ID_DEVICE_DRAW_VIEWPORT_NOT_SET = 238, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TRAILING_DIGIT_IN_SEMANTIC = 239, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_TRAILING_DIGIT_IN_SEMANTIC = 240, + D3D12_MESSAGE_ID_DEVICE_RSSETVIEWPORTS_DENORMFLUSH = 241, + D3D12_MESSAGE_ID_OMSETRENDERTARGETS_INVALIDVIEW = 242, + D3D12_MESSAGE_ID_DEVICE_SETTEXTFILTERSIZE_INVALIDDIMENSIONS = 243, + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLER_MISMATCH = 244, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_TYPE_MISMATCH = 245, + D3D12_MESSAGE_ID_BLENDSTATE_GETDESC_LEGACY = 246, + D3D12_MESSAGE_ID_SHADERRESOURCEVIEW_GETDESC_LEGACY = 247, + D3D12_MESSAGE_ID_DEVICE_DRAW_PS_OUTPUT_TYPE_MISMATCH = 248, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_FORMAT_GATHER_UNSUPPORTED = 249, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN = 250, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_STRIDE_TOO_LARGE = 251, + D3D12_MESSAGE_ID_DEVICE_IASETVERTEXBUFFERS_INVALIDRANGE = 252, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_EMPTY_LAYOUT = 253, + D3D12_MESSAGE_ID_DEVICE_DRAW_RESOURCE_SAMPLE_COUNT_MISMATCH = 254, + D3D12_MESSAGE_ID_LIVE_OBJECT_SUMMARY = 255, + D3D12_MESSAGE_ID_LIVE_BUFFER = 256, + D3D12_MESSAGE_ID_LIVE_TEXTURE1D = 257, + D3D12_MESSAGE_ID_LIVE_TEXTURE2D = 258, + D3D12_MESSAGE_ID_LIVE_TEXTURE3D = 259, + D3D12_MESSAGE_ID_LIVE_SHADERRESOURCEVIEW = 260, + D3D12_MESSAGE_ID_LIVE_RENDERTARGETVIEW = 261, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILVIEW = 262, + D3D12_MESSAGE_ID_LIVE_VERTEXSHADER = 263, + D3D12_MESSAGE_ID_LIVE_GEOMETRYSHADER = 264, + D3D12_MESSAGE_ID_LIVE_PIXELSHADER = 265, + D3D12_MESSAGE_ID_LIVE_INPUTLAYOUT = 266, + D3D12_MESSAGE_ID_LIVE_SAMPLER = 267, + D3D12_MESSAGE_ID_LIVE_BLENDSTATE = 268, + D3D12_MESSAGE_ID_LIVE_DEPTHSTENCILSTATE = 269, + D3D12_MESSAGE_ID_LIVE_RASTERIZERSTATE = 270, + D3D12_MESSAGE_ID_LIVE_QUERY = 271, + D3D12_MESSAGE_ID_LIVE_PREDICATE = 272, + D3D12_MESSAGE_ID_LIVE_COUNTER = 273, + D3D12_MESSAGE_ID_LIVE_DEVICE = 274, + D3D12_MESSAGE_ID_LIVE_SWAPCHAIN = 275, + D3D12_MESSAGE_ID_CREATEDEPTHSTENCILVIEW_INVALIDFLAGS = 276, + D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDCLASSLINKAGE = 277, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADER_INVALIDCLASSLINKAGE = 278, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTREAMS = 279, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAMTORASTERIZER = 280, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTREAMS = 281, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDCLASSLINKAGE = 282, + D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDCLASSLINKAGE = 283, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDSTREAM = 284, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDENTRIES = 285, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UNEXPECTEDSTRIDES = 286, + D3D12_MESSAGE_ID_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_INVALIDNUMSTRIDES = 287, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCALL = 288, + D3D12_MESSAGE_ID_CREATEHULLSHADER_OUTOFMEMORY = 289, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERBYTECODE = 290, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDSHADERTYPE = 291, + D3D12_MESSAGE_ID_CREATEHULLSHADER_INVALIDCLASSLINKAGE = 292, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCALL = 293, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_OUTOFMEMORY = 294, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERBYTECODE = 295, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDSHADERTYPE = 296, + D3D12_MESSAGE_ID_CREATEDOMAINSHADER_INVALIDCLASSLINKAGE = 297, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_XOR_DS_MISMATCH = 298, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_INVALID_ARG_BUFFER = 299, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_UNALIGNED = 300, + D3D12_MESSAGE_ID_DEVICE_DRAWINDIRECT_OFFSET_OVERFLOW = 301, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDMAPTYPE = 302, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDSUBRESOURCE = 303, + D3D12_MESSAGE_ID_RESOURCE_MAP_INVALIDFLAGS = 304, + D3D12_MESSAGE_ID_RESOURCE_MAP_ALREADYMAPPED = 305, + D3D12_MESSAGE_ID_RESOURCE_MAP_DEVICEREMOVED_RETURN = 306, + D3D12_MESSAGE_ID_RESOURCE_MAP_OUTOFMEMORY_RETURN = 307, + D3D12_MESSAGE_ID_RESOURCE_MAP_WITHOUT_INITIAL_DISCARD = 308, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_INVALIDSUBRESOURCE = 309, + D3D12_MESSAGE_ID_RESOURCE_UNMAP_NOTMAPPED = 310, + D3D12_MESSAGE_ID_DEVICE_DRAW_RASTERIZING_CONTROL_POINTS = 311, + D3D12_MESSAGE_ID_DEVICE_IASETPRIMITIVETOPOLOGY_TOPOLOGY_UNSUPPORTED = 312, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_SIGNATURE_MISMATCH = 313, + D3D12_MESSAGE_ID_DEVICE_DRAW_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH = 314, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_CONTROL_POINT_COUNT_MISMATCH = 315, + D3D12_MESSAGE_ID_DEVICE_DRAW_HS_DS_TESSELLATOR_DOMAIN_MISMATCH = 316, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_UNRECOGNIZED_FEATURE = 317, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_MISMATCHED_DATA_SIZE = 318, + D3D12_MESSAGE_ID_DEVICE_CHECKFEATURESUPPORT_INVALIDARG_RETURN = 319, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCALL = 320, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_OUTOFMEMORY = 321, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDSHADERBYTECODE = 322, + D3D12_MESSAGE_ID_CREATECOMPUTESHADER_INVALIDCLASSLINKAGE = 323, + D3D12_MESSAGE_ID_DEVICE_CSSETSHADERRESOURCES_VIEWS_EMPTY = 324, + D3D12_MESSAGE_ID_CSSETCONSTANTBUFFERS_INVALIDBUFFER = 325, + D3D12_MESSAGE_ID_DEVICE_CSSETCONSTANTBUFFERS_BUFFERS_EMPTY = 326, + D3D12_MESSAGE_ID_DEVICE_CSSETSAMPLERS_SAMPLERS_EMPTY = 327, + D3D12_MESSAGE_ID_DEVICE_CSGETSHADERRESOURCES_VIEWS_EMPTY = 328, + D3D12_MESSAGE_ID_DEVICE_CSGETCONSTANTBUFFERS_BUFFERS_EMPTY = 329, + D3D12_MESSAGE_ID_DEVICE_CSGETSAMPLERS_SAMPLERS_EMPTY = 330, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 331, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 332, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 333, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 334, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEFLOATOPSNOTSUPPORTED = 335, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEFLOATOPSNOTSUPPORTED = 336, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEFLOATOPSNOTSUPPORTED = 337, + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDSTRUCTURESTRIDE = 338, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDFLAGS = 339, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDRESOURCE = 340, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDESC = 341, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFORMAT = 342, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANESLICE = 343, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANESLICE = 344, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDIMENSIONS = 345, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_UNRECOGNIZEDFORMAT = 346, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_OVERLAPPING_OLD_SLOTS = 347, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_NO_OP = 348, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDARG_RETURN = 349, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_OUTOFMEMORY_RETURN = 350, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEW_DENORMFLUSH = 351, + D3D12_MESSAGE_ID_DEVICE_CSSETUNORDEREDACCESSS_VIEWS_EMPTY = 352, + D3D12_MESSAGE_ID_DEVICE_CSGETUNORDEREDACCESSS_VIEWS_EMPTY = 353, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDFLAGS = 354, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_INVALID_ARG_BUFFER = 355, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_UNALIGNED = 356, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_OFFSET_OVERFLOW = 357, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_DEPTH_READONLY = 358, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_STENCIL_READONLY = 359, + D3D12_MESSAGE_ID_CHECKFEATURESUPPORT_FORMAT_DEPRECATED = 360, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RETURN_TYPE_MISMATCH = 361, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET = 362, + D3D12_MESSAGE_ID_DEVICE_DRAW_UNORDEREDACCESSVIEW_RENDERTARGETVIEW_OVERLAP = 363, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_DIMENSION_MISMATCH = 364, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_APPEND_UNSUPPORTED = 365, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMICS_UNSUPPORTED = 366, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_STRUCTURE_STRIDE_MISMATCH = 367, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_BUFFER_TYPE_MISMATCH = 368, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_RAW_UNSUPPORTED = 369, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_LD_UNSUPPORTED = 370, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_FORMAT_STORE_UNSUPPORTED = 371, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_ADD_UNSUPPORTED = 372, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_BITWISE_OPS_UNSUPPORTED = 373, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_CMPSTORE_CMPEXCHANGE_UNSUPPORTED = 374, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_EXCHANGE_UNSUPPORTED = 375, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_SIGNED_MINMAX_UNSUPPORTED = 376, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_ATOMIC_UNSIGNED_MINMAX_UNSUPPORTED = 377, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_BOUND_RESOURCE_MAPPED = 378, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_OVERFLOW = 379, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_THREADGROUPCOUNT_ZERO = 380, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_STRUCTURE_STRIDE_MISMATCH = 381, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_BUFFER_TYPE_MISMATCH = 382, + D3D12_MESSAGE_ID_DEVICE_SHADERRESOURCEVIEW_RAW_UNSUPPORTED = 383, + D3D12_MESSAGE_ID_DEVICE_DISPATCH_UNSUPPORTED = 384, + D3D12_MESSAGE_ID_DEVICE_DISPATCHINDIRECT_UNSUPPORTED = 385, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDOFFSET = 386, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_LARGEOFFSET = 387, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDDESTINATIONSTATE = 388, + D3D12_MESSAGE_ID_COPYSTRUCTURECOUNT_INVALIDSOURCESTATE = 389, + D3D12_MESSAGE_ID_CHECKFORMATSUPPORT_FORMAT_NOT_SUPPORTED = 390, + D3D12_MESSAGE_ID_CLEARUNORDEREDACCESSVIEWFLOAT_INVALIDFORMAT = 391, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_COUNTER_UNSUPPORTED = 392, + D3D12_MESSAGE_ID_DEVICE_DRAW_PIXEL_SHADER_WITHOUT_RTV_OR_DSV = 393, + D3D12_MESSAGE_ID_SHADER_ABORT = 394, + D3D12_MESSAGE_ID_SHADER_MESSAGE = 395, + D3D12_MESSAGE_ID_SHADER_ERROR = 396, + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDRESOURCE = 397, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_INVALIDARG_RETURN = 398, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_OUTOFMEMORY_RETURN = 399, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_ACCESSDENIED_RETURN = 400, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALIDFORCEDSAMPLECOUNT = 401, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_USE_OF_FORCED_SAMPLE_COUNT = 402, + D3D12_MESSAGE_ID_CREATEBLENDSTATE_INVALIDLOGICOPS = 403, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDDARRAYWITHDECODER = 404, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDDARRAYWITHDECODER = 405, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDDARRAYWITHDECODER = 406, + D3D12_MESSAGE_ID_DEVICE_LOCKEDOUT_INTERFACE = 407, + D3D12_MESSAGE_ID_OFFERRESOURCES_INVALIDPRIORITY = 408, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDVIEW = 409, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 410, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_SHADEREXTENSIONSNOTSUPPORTED = 411, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 412, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_SHADEREXTENSIONSNOTSUPPORTED = 413, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 414, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_SHADEREXTENSIONSNOTSUPPORTED = 415, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 416, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_SHADEREXTENSIONSNOTSUPPORTED = 417, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_DOUBLEEXTENSIONSNOTSUPPORTED = 418, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_SHADEREXTENSIONSNOTSUPPORTED = 419, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 420, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_SHADEREXTENSIONSNOTSUPPORTED = 421, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_DOUBLEEXTENSIONSNOTSUPPORTED = 422, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_SHADEREXTENSIONSNOTSUPPORTED = 423, + D3D12_MESSAGE_ID_DEVICE_SHADER_LINKAGE_MINPRECISION = 424, + D3D12_MESSAGE_ID_DEVICE_CREATEVERTEXSHADER_UAVSNOTSUPPORTED = 425, + D3D12_MESSAGE_ID_DEVICE_CREATEHULLSHADER_UAVSNOTSUPPORTED = 426, + D3D12_MESSAGE_ID_DEVICE_CREATEDOMAINSHADER_UAVSNOTSUPPORTED = 427, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADER_UAVSNOTSUPPORTED = 428, + D3D12_MESSAGE_ID_DEVICE_CREATEGEOMETRYSHADERWITHSTREAMOUTPUT_UAVSNOTSUPPORTED = 429, + D3D12_MESSAGE_ID_DEVICE_CREATEPIXELSHADER_UAVSNOTSUPPORTED = 430, + D3D12_MESSAGE_ID_DEVICE_CREATECOMPUTESHADER_UAVSNOTSUPPORTED = 431, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_INVALIDOFFSET = 432, + D3D12_MESSAGE_ID_DEVICE_OMSETRENDERTARGETSANDUNORDEREDACCESSVIEWS_TOOMANYVIEWS = 433, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_NOTSUPPORTED = 434, + D3D12_MESSAGE_ID_SWAPDEVICECONTEXTSTATE_NOTSUPPORTED = 435, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_PREFERUPDATESUBRESOURCE1 = 436, + D3D12_MESSAGE_ID_GETDC_INACCESSIBLE = 437, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDRECT = 438, + D3D12_MESSAGE_ID_DEVICE_DRAW_SAMPLE_MASK_IGNORED_ON_FL9 = 439, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE1_NOT_SUPPORTED = 440, + D3D12_MESSAGE_ID_DEVICE_OPEN_SHARED_RESOURCE_BY_NAME_NOT_SUPPORTED = 441, + D3D12_MESSAGE_ID_ENQUEUESETEVENT_NOT_SUPPORTED = 442, + D3D12_MESSAGE_ID_OFFERRELEASE_NOT_SUPPORTED = 443, + D3D12_MESSAGE_ID_OFFERRESOURCES_INACCESSIBLE = 444, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSORINPUTVIEW_INVALIDMSAA = 445, + D3D12_MESSAGE_ID_CREATEVIDEOPROCESSOROUTPUTVIEW_INVALIDMSAA = 446, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_INVALIDSOURCERECT = 447, + D3D12_MESSAGE_ID_DEVICE_CLEARVIEW_EMPTYRECT = 448, + D3D12_MESSAGE_ID_UPDATESUBRESOURCE_EMPTYDESTBOX = 449, + D3D12_MESSAGE_ID_COPYSUBRESOURCEREGION_EMPTYSOURCEBOX = 450, + D3D12_MESSAGE_ID_DEVICE_DRAW_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS = 451, + D3D12_MESSAGE_ID_DEVICE_DRAW_DEPTHSTENCILVIEW_NOT_SET = 452, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET = 453, + D3D12_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET_DUE_TO_FLIP_PRESENT = 454, + D3D12_MESSAGE_ID_DEVICE_UNORDEREDACCESSVIEW_NOT_SET_DUE_TO_FLIP_PRESENT = 455, + D3D12_MESSAGE_ID_GETDATAFORNEWHARDWAREKEY_NULLPARAM = 456, + D3D12_MESSAGE_ID_CHECKCRYPTOSESSIONSTATUS_NULLPARAM = 457, + D3D12_MESSAGE_ID_SETEVENTONHARDWARECONTENTPROTECTIONTILT_NULLPARAM = 458, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_NULLPARAM = 459, + D3D12_MESSAGE_ID_GETVIDEODECODERCAPS_ZEROWIDTHHEIGHT = 460, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_NULLPARAM = 461, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE = 462, + D3D12_MESSAGE_ID_CHECKVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT = 463, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_NULLPARAM = 464, + D3D12_MESSAGE_ID_VIDEODECODERENABLEDOWNSAMPLING_UNSUPPORTED = 465, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_NULLPARAM = 466, + D3D12_MESSAGE_ID_VIDEODECODERUPDATEDOWNSAMPLING_UNSUPPORTED = 467, + D3D12_MESSAGE_ID_CHECKVIDEOPROCESSORFORMATCONVERSION_NULLPARAM = 468, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTCOLORSPACE1_NULLPARAM = 469, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTCOLORSPACE1_NULLPARAM = 470, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_NULLPARAM = 471, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMCOLORSPACE1_INVALIDSTREAM = 472, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_NULLPARAM = 473, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_INVALIDSTREAM = 474, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETSTREAMMIRROR_UNSUPPORTED = 475, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMCOLORSPACE1_NULLPARAM = 476, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETSTREAMMIRROR_NULLPARAM = 477, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_NULLPARAM = 478, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_INVALIDCOLORSPACE = 479, + D3D12_MESSAGE_ID_RECOMMENDVIDEODECODERDOWNSAMPLING_ZEROWIDTHHEIGHT = 480, + D3D12_MESSAGE_ID_VIDEOPROCESSORSETOUTPUTSHADERUSAGE_NULLPARAM = 481, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETOUTPUTSHADERUSAGE_NULLPARAM = 482, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_NULLPARAM = 483, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSTREAMCOUNT = 484, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_TARGETRECT = 485, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDSOURCERECT = 486, + D3D12_MESSAGE_ID_VIDEOPROCESSORGETBEHAVIORHINTS_INVALIDDESTRECT = 487, + D3D12_MESSAGE_ID_CREATEBUFFER_INVALIDUSAGE = 488, + D3D12_MESSAGE_ID_CREATETEXTURE1D_INVALIDUSAGE = 489, + D3D12_MESSAGE_ID_CREATETEXTURE2D_INVALIDUSAGE = 490, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_STEPRATE_NOT_1 = 491, + D3D12_MESSAGE_ID_CREATEINPUTLAYOUT_LEVEL9_INSTANCING_NOT_SUPPORTED = 492, + D3D12_MESSAGE_ID_UPDATETILEMAPPINGS_INVALID_PARAMETER = 493, + D3D12_MESSAGE_ID_COPYTILEMAPPINGS_INVALID_PARAMETER = 494, + D3D12_MESSAGE_ID_COPYTILES_INVALID_PARAMETER = 495, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_WARNING = 496, + D3D12_MESSAGE_ID_NULL_TILE_MAPPING_ACCESS_ERROR = 497, + D3D12_MESSAGE_ID_DIRTY_TILE_MAPPING_ACCESS = 498, + D3D12_MESSAGE_ID_DUPLICATE_TILE_MAPPINGS_IN_COVERED_AREA = 499, + D3D12_MESSAGE_ID_TILE_MAPPINGS_IN_COVERED_AREA_DUPLICATED_OUTSIDE = 500, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INCOMPATIBLE_RESOURCES = 501, + D3D12_MESSAGE_ID_TILE_MAPPINGS_SHARED_BETWEEN_INPUT_AND_OUTPUT = 502, + D3D12_MESSAGE_ID_CHECKMULTISAMPLEQUALITYLEVELS_INVALIDFLAGS = 503, + D3D12_MESSAGE_ID_GETRESOURCETILING_NONTILED_RESOURCE = 504, + D3D12_MESSAGE_ID_NEED_TO_CALL_TILEDRESOURCEBARRIER = 505, + D3D12_MESSAGE_ID_CREATEDEVICE_INVALIDARGS = 506, + D3D12_MESSAGE_ID_CREATEDEVICE_WARNING = 507, + D3D12_MESSAGE_ID_TILED_RESOURCE_TIER_1_BUFFER_TEXTURE_MISMATCH = 508, + D3D12_MESSAGE_ID_CREATE_CRYPTOSESSION = 509, + D3D12_MESSAGE_ID_CREATE_AUTHENTICATEDCHANNEL = 510, + D3D12_MESSAGE_ID_LIVE_CRYPTOSESSION = 511, + D3D12_MESSAGE_ID_LIVE_AUTHENTICATEDCHANNEL = 512, + D3D12_MESSAGE_ID_DESTROY_CRYPTOSESSION = 513, + D3D12_MESSAGE_ID_DESTROY_AUTHENTICATEDCHANNEL = 514, + D3D12_MESSAGE_ID_MAP_INVALID_SUBRESOURCE = 515, + D3D12_MESSAGE_ID_MAP_INVALID_TYPE = 516, + D3D12_MESSAGE_ID_MAP_UNSUPPORTED_TYPE = 517, + D3D12_MESSAGE_ID_UNMAP_INVALID_SUBRESOURCE = 518, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_TYPE = 519, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_NULL_POINTER = 520, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SUBRESOURCE = 521, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_RESERVED_BITS = 522, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISSING_BIND_FLAGS = 523, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MISMATCHING_MISC_FLAGS = 524, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_MATCHING_STATES = 525, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINATION = 526, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_BEFORE_AFTER_MISMATCH = 527, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_RESOURCE = 528, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_SAMPLE_COUNT = 529, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS = 530, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMBINED_FLAGS = 531, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAGS_FOR_FORMAT = 532, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_SPLIT_BARRIER = 533, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_END = 534, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_UNMATCHED_BEGIN = 535, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_FLAG = 536, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_COMMAND_LIST_TYPE = 537, + D3D12_MESSAGE_ID_INVALID_SUBRESOURCE_STATE = 538, + D3D12_MESSAGE_ID_INEFFICIENT_PRESENT = 539, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CONTENTION = 540, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET = 541, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_RESET_BUNDLE = 542, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_CANNOT_RESET = 543, + D3D12_MESSAGE_ID_COMMAND_LIST_OPEN = 544, + D3D12_MESSAGE_ID_QUERY_STATE_MISMATCH = 545, + D3D12_MESSAGE_ID_INVALID_BUNDLE_API = 546, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED = 547, + D3D12_MESSAGE_ID_COMMAND_LIST_CLOSED_WITH_INVALID_RESOURCE = 548, + D3D12_MESSAGE_ID_WRONG_COMMAND_ALLOCATOR_TYPE = 549, + D3D12_MESSAGE_ID_INVALID_INDIRECT_ARGUMENT_BUFFER = 550, + D3D12_MESSAGE_ID_COMPUTE_AND_GRAPHICS_PIPELINE = 551, + D3D12_MESSAGE_ID_COMMAND_ALLOCATOR_SYNC = 552, + D3D12_MESSAGE_ID_COMMAND_LIST_SYNC = 553, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_HEAP_INVALID = 554, + D3D12_MESSAGE_ID_CREATE_QUEUE_IMAGE_NOT_SUPPORTED = 555, + D3D12_MESSAGE_ID_CREATE_COMMAND_ALLOCATOR_IMAGE_NOT_SUPPORTED = 556, + D3D12_MESSAGE_ID_CREATE_COMMANDQUEUE = 557, + D3D12_MESSAGE_ID_CREATE_COMMANDALLOCATOR = 558, + D3D12_MESSAGE_ID_CREATE_PIPELINESTATE = 559, + D3D12_MESSAGE_ID_CREATE_COMMANDLIST12 = 560, + D3D12_MESSAGE_ID_CREATE_IMAGECOMMANDLIST = 561, + D3D12_MESSAGE_ID_CREATE_RESOURCE = 562, + D3D12_MESSAGE_ID_CREATE_DESCRIPTORHEAP = 563, + D3D12_MESSAGE_ID_CREATE_ROOTSIGNATURE = 564, + D3D12_MESSAGE_ID_CREATE_LIBRARY = 565, + D3D12_MESSAGE_ID_CREATE_HEAP = 566, + D3D12_MESSAGE_ID_CREATE_MONITOREDFENCE = 567, + D3D12_MESSAGE_ID_CREATE_QUERYHEAP = 568, + D3D12_MESSAGE_ID_CREATE_COMMANDSIGNATURE = 569, + D3D12_MESSAGE_ID_LIVE_COMMANDQUEUE = 570, + D3D12_MESSAGE_ID_LIVE_COMMANDALLOCATOR = 571, + D3D12_MESSAGE_ID_LIVE_PIPELINESTATE = 572, + D3D12_MESSAGE_ID_LIVE_COMMANDLIST12 = 573, + D3D12_MESSAGE_ID_LIVE_IMAGECOMMANDLIST = 574, + D3D12_MESSAGE_ID_LIVE_RESOURCE = 575, + D3D12_MESSAGE_ID_LIVE_DESCRIPTORHEAP = 576, + D3D12_MESSAGE_ID_LIVE_ROOTSIGNATURE = 577, + D3D12_MESSAGE_ID_LIVE_LIBRARY = 578, + D3D12_MESSAGE_ID_LIVE_HEAP = 579, + D3D12_MESSAGE_ID_LIVE_MONITOREDFENCE = 580, + D3D12_MESSAGE_ID_LIVE_QUERYHEAP = 581, + D3D12_MESSAGE_ID_LIVE_COMMANDSIGNATURE = 582, + D3D12_MESSAGE_ID_DESTROY_COMMANDQUEUE = 583, + D3D12_MESSAGE_ID_DESTROY_COMMANDALLOCATOR = 584, + D3D12_MESSAGE_ID_DESTROY_PIPELINESTATE = 585, + D3D12_MESSAGE_ID_DESTROY_COMMANDLIST12 = 586, + D3D12_MESSAGE_ID_DESTROY_IMAGECOMMANDLIST = 587, + D3D12_MESSAGE_ID_DESTROY_RESOURCE = 588, + D3D12_MESSAGE_ID_DESTROY_DESCRIPTORHEAP = 589, + D3D12_MESSAGE_ID_DESTROY_ROOTSIGNATURE = 590, + D3D12_MESSAGE_ID_DESTROY_LIBRARY = 591, + D3D12_MESSAGE_ID_DESTROY_HEAP = 592, + D3D12_MESSAGE_ID_DESTROY_MONITOREDFENCE = 593, + D3D12_MESSAGE_ID_DESTROY_QUERYHEAP = 594, + D3D12_MESSAGE_ID_DESTROY_COMMANDSIGNATURE = 595, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDHEAPTYPE = 596, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONS = 597, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDMISCFLAGS = 598, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMISCFLAGS = 599, + D3D12_MESSAGE_ID_CREATERESOURCE_LARGEALLOCATION = 600, + D3D12_MESSAGE_ID_CREATERESOURCE_SMALLALLOCATION = 601, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDARG_RETURN = 602, + D3D12_MESSAGE_ID_CREATERESOURCE_OUTOFMEMORY_RETURN = 603, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDESC = 604, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDINITIALSTATE = 605, + D3D12_MESSAGE_ID_RESOURCE_HAS_PENDING_INITIAL_DATA = 606, + D3D12_MESSAGE_ID_POSSIBLY_INVALID_SUBRESOURCE_STATE = 607, + D3D12_MESSAGE_ID_INVALID_USE_OF_NON_RESIDENT_RESOURCE = 608, + D3D12_MESSAGE_ID_POSSIBLE_INVALID_USE_OF_NON_RESIDENT_RESOURCE = 609, + D3D12_MESSAGE_ID_BUNDLE_PIPELINE_STATE_MISMATCH = 610, + D3D12_MESSAGE_ID_PRIMITIVE_TOPOLOGY_MISMATCH_PIPELINE_STATE = 611, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_PIPELINE_STATE = 612, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_PIPELINE_STATE = 613, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_PIPELINE_STATE = 614, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_PIPELINE_STATE = 615, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_PIPELINE_STATE = 616, + D3D12_MESSAGE_ID_RENDER_TARGET_NUMBER_MISMATCH_BUNDLE_PIPELINE_STATE = 617, + D3D12_MESSAGE_ID_RENDER_TARGET_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE = 618, + D3D12_MESSAGE_ID_RENDER_TARGET_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE = 619, + D3D12_MESSAGE_ID_DEPTH_STENCIL_FORMAT_MISMATCH_BUNDLE_PIPELINE_STATE = 620, + D3D12_MESSAGE_ID_DEPTH_STENCIL_SAMPLE_DESC_MISMATCH_BUNDLE_PIPELINE_STATE = 621, + D3D12_MESSAGE_ID_CREATESHADER_INVALIDBYTECODE = 622, + D3D12_MESSAGE_ID_CREATEHEAP_NULLDESC = 623, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDSIZE = 624, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDHEAPTYPE = 625, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES = 626, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMEMORYPOOL = 627, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDPROPERTIES = 628, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDALIGNMENT = 629, + D3D12_MESSAGE_ID_CREATEHEAP_UNRECOGNIZEDMISCFLAGS = 630, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDMISCFLAGS = 631, + D3D12_MESSAGE_ID_CREATEHEAP_INVALIDARG_RETURN = 632, + D3D12_MESSAGE_ID_CREATEHEAP_OUTOFMEMORY_RETURN = 633, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAPPROPERTIES = 634, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPTYPE = 635, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDCPUPAGEPROPERTIES = 636, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDMEMORYPOOL = 637, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPPROPERTIES = 638, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_UNRECOGNIZEDHEAPMISCFLAGS = 639, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDHEAPMISCFLAGS = 640, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_INVALIDARG_RETURN = 641, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_OUTOFMEMORY_RETURN = 642, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_UNRECOGNIZEDHEAPTYPE = 643, + D3D12_MESSAGE_ID_GETCUSTOMHEAPPROPERTIES_INVALIDHEAPTYPE = 644, + D3D12_MESSAGE_ID_CREATE_DESCRIPTOR_HEAP_INVALID_DESC = 645, + D3D12_MESSAGE_ID_INVALID_DESCRIPTOR_HANDLE = 646, + D3D12_MESSAGE_ID_CREATERASTERIZERSTATE_INVALID_CONSERVATIVERASTERMODE = 647, + D3D12_MESSAGE_ID_DEVICE_DRAW_INVALID_SYSTEMVALUE = 648, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_RESOURCE = 649, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_INVALID_DESC = 650, + D3D12_MESSAGE_ID_CREATE_CONSTANT_BUFFER_VIEW_LARGE_OFFSET = 651, + D3D12_MESSAGE_ID_CREATE_UNORDEREDACCESS_VIEW_INVALID_COUNTER_USAGE = 652, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_INVALID_RANGES = 653, + D3D12_MESSAGE_ID_COPY_DESCRIPTORS_WRITE_ONLY_DESCRIPTOR = 654, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RTV_FORMAT_NOT_UNKNOWN = 655, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_RENDER_TARGET_COUNT = 656, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VERTEX_SHADER_NOT_SET = 657, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INPUTLAYOUT_NOT_SET = 658, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_HS_DS_SIGNATURE_MISMATCH = 659, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERINDEX = 660, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_COMPONENTTYPE = 661, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_REGISTERMASK = 662, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SYSTEMVALUE = 663, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_NEVERWRITTEN_ALWAYSREADS = 664, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_MINPRECISION = 665, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND = 666, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_XOR_DS_MISMATCH = 667, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HULL_SHADER_INPUT_TOPOLOGY_MISMATCH = 668, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_CONTROL_POINT_COUNT_MISMATCH = 669, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_DS_TESSELLATOR_DOMAIN_MISMATCH = 670, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_CENTER_MULTISAMPLE_PATTERN = 671, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_USE_OF_FORCED_SAMPLE_COUNT = 672, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_PRIMITIVETOPOLOGY = 673, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SYSTEMVALUE = 674, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_DUAL_SOURCE_BLENDING_CAN_ONLY_HAVE_RENDER_TARGET_0 = 675, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_BLENDING = 676, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_OUTPUT_TYPE_MISMATCH = 677, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_OM_RENDER_TARGET_DOES_NOT_SUPPORT_LOGIC_OPS = 678, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_RENDERTARGETVIEW_NOT_SET = 679, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DEPTHSTENCILVIEW_NOT_SET = 680, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_INPUT_PRIMITIVE_MISMATCH = 681, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_POSITION_NOT_PRESENT = 682, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE_FLAGS = 683, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_INDEX_BUFFER_PROPERTIES = 684, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_INVALID_SAMPLE_DESC = 685, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_HS_ROOT_SIGNATURE_MISMATCH = 686, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_DS_ROOT_SIGNATURE_MISMATCH = 687, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_VS_ROOT_SIGNATURE_MISMATCH = 688, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_GS_ROOT_SIGNATURE_MISMATCH = 689, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_PS_ROOT_SIGNATURE_MISMATCH = 690, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_MISSING_ROOT_SIGNATURE = 691, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_OPEN_BUNDLE = 692, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_DESCRIPTOR_HEAP_MISMATCH = 693, + D3D12_MESSAGE_ID_EXECUTE_BUNDLE_TYPE = 694, + D3D12_MESSAGE_ID_DRAW_EMPTY_SCISSOR_RECTANGLE = 695, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_BLOB_NOT_FOUND = 696, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_DESERIALIZE_FAILED = 697, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_INVALID_CONFIGURATION = 698, + D3D12_MESSAGE_ID_CREATE_ROOT_SIGNATURE_NOT_SUPPORTED_ON_DEVICE = 699, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLRESOURCEPROPERTIES = 700, + D3D12_MESSAGE_ID_CREATERESOURCEANDHEAP_NULLHEAP = 701, + D3D12_MESSAGE_ID_GETRESOURCEALLOCATIONINFO_INVALIDRDESCS = 702, + D3D12_MESSAGE_ID_MAKERESIDENT_NULLOBJECTARRAY = 703, + D3D12_MESSAGE_ID_MAKERESIDENT_INVALIDOBJECT = 704, + D3D12_MESSAGE_ID_EVICT_NULLOBJECTARRAY = 705, + D3D12_MESSAGE_ID_EVICT_INVALIDOBJECT = 706, + D3D12_MESSAGE_ID_HEAPS_UNSUPPORTED = 707, + D3D12_MESSAGE_ID_SET_DESCRIPTOR_TABLE_INVALID = 708, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_INVALID = 709, + D3D12_MESSAGE_ID_SET_ROOT_CONSTANT_BUFFER_VIEW_INVALID = 710, + D3D12_MESSAGE_ID_SET_ROOT_SHADER_RESOURCE_VIEW_INVALID = 711, + D3D12_MESSAGE_ID_SET_ROOT_UNORDERED_ACCESS_VIEW_INVALID = 712, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID_DESC = 713, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_LARGE_OFFSET = 714, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID_DESC = 715, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_LARGE_OFFSET = 716, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID_DESC = 717, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDDIMENSIONALITY = 718, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDLAYOUT = 719, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDDIMENSIONALITY = 720, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDALIGNMENT = 721, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDMIPLEVELS = 722, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDSAMPLEDESC = 723, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDLAYOUT = 724, + D3D12_MESSAGE_ID_SET_INDEX_BUFFER_INVALID = 725, + D3D12_MESSAGE_ID_SET_VERTEX_BUFFERS_INVALID = 726, + D3D12_MESSAGE_ID_SET_STREAM_OUTPUT_BUFFERS_INVALID = 727, + D3D12_MESSAGE_ID_SET_RENDER_TARGETS_INVALID = 728, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_INVALID_PARAMETERS = 729, + D3D12_MESSAGE_ID_CREATEQUERY_HEAP_JPEG_NOT_SUPPORTED = 730, + D3D12_MESSAGE_ID_BEGIN_END_QUERY_INVALID_PARAMETERS = 731, + D3D12_MESSAGE_ID_CLOSE_COMMAND_LIST_OPEN_QUERY = 732, + D3D12_MESSAGE_ID_RESOLVE_QUERY_DATA_INVALID_PARAMETERS = 733, + D3D12_MESSAGE_ID_SET_PREDICATION_INVALID_PARAMETERS = 734, + D3D12_MESSAGE_ID_TIMESTAMPS_NOT_SUPPORTED = 735, + D3D12_MESSAGE_ID_UNSTABLE_POWER_STATE = 736, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDFORMAT = 737, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDFORMAT = 738, + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDSUBRESOURCERANGE = 739, + D3D12_MESSAGE_ID_GETCOPYABLELAYOUT_INVALIDBASEOFFSET = 740, + D3D12_MESSAGE_ID_RESOURCE_BARRIER_INVALID_HEAP = 741, + D3D12_MESSAGE_ID_CREATE_SAMPLER_INVALID = 742, + D3D12_MESSAGE_ID_CREATECOMMANDSIGNATURE_INVALID = 743, + D3D12_MESSAGE_ID_EXECUTE_INDIRECT_INVALID_PARAMETERS = 744, + D3D12_MESSAGE_ID_GETGPUVIRTUALADDRESS_INVALID_RESOURCE_DIMENSION = 745, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_INVALIDCONTEXTTYPE = 746, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_DECODENOTSUPPORTED = 747, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_ENCODENOTSUPPORTED = 748, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDPLANEINDEX = 749, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_INVALIDVIDEOPLANEINDEX = 750, + D3D12_MESSAGE_ID_CREATESHADERRESOURCEVIEW_AMBIGUOUSVIDEOPLANEINDEX = 751, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDPLANEINDEX = 752, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_INVALIDVIDEOPLANEINDEX = 753, + D3D12_MESSAGE_ID_CREATERENDERTARGETVIEW_AMBIGUOUSVIDEOPLANEINDEX = 754, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDPLANEINDEX = 755, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_INVALIDVIDEOPLANEINDEX = 756, + D3D12_MESSAGE_ID_CREATEUNORDEREDACCESSVIEW_AMBIGUOUSVIDEOPLANEINDEX = 757, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSCANDATAOFFSET = 758, + D3D12_MESSAGE_ID_JPEGDECODE_NOTSUPPORTED = 759, + D3D12_MESSAGE_ID_JPEGDECODE_DIMENSIONSTOOLARGE = 760, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOMPONENTS = 761, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDCOMPONENTS = 762, + D3D12_MESSAGE_ID_JPEGDECODE_DESTINATIONNOT2D = 763, + D3D12_MESSAGE_ID_JPEGDECODE_TILEDRESOURCESUNSUPPORTED = 764, + D3D12_MESSAGE_ID_JPEGDECODE_GUARDRECTSUNSUPPORTED = 765, + D3D12_MESSAGE_ID_JPEGDECODE_FORMATUNSUPPORTED = 766, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSUBRESOURCE = 767, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDMIPLEVEL = 768, + D3D12_MESSAGE_ID_JPEGDECODE_EMPTYDESTBOX = 769, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOT2D = 770, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXNOTSUB = 771, + D3D12_MESSAGE_ID_JPEGDECODE_DESTBOXESINTERSECT = 772, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEMISMATCH = 773, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEMISMATCH = 774, + D3D12_MESSAGE_ID_JPEGDECODE_XSUBSAMPLEODD = 775, + D3D12_MESSAGE_ID_JPEGDECODE_YSUBSAMPLEODD = 776, + D3D12_MESSAGE_ID_JPEGDECODE_UPSCALEUNSUPPORTED = 777, + D3D12_MESSAGE_ID_JPEGDECODE_TIER4DOWNSCALETOLARGE = 778, + D3D12_MESSAGE_ID_JPEGDECODE_TIER3DOWNSCALEUNSUPPORTED = 779, + D3D12_MESSAGE_ID_JPEGDECODE_CHROMASIZEMISMATCH = 780, + D3D12_MESSAGE_ID_JPEGDECODE_LUMACHROMASIZEMISMATCH = 781, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDNUMDESTINATIONS = 782, + D3D12_MESSAGE_ID_JPEGDECODE_SUBBOXUNSUPPORTED = 783, + D3D12_MESSAGE_ID_JPEGDECODE_1DESTUNSUPPORTEDFORMAT = 784, + D3D12_MESSAGE_ID_JPEGDECODE_3DESTUNSUPPORTEDFORMAT = 785, + D3D12_MESSAGE_ID_JPEGDECODE_SCALEUNSUPPORTED = 786, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDSOURCESIZE = 787, + D3D12_MESSAGE_ID_JPEGDECODE_INVALIDCOPYFLAGS = 788, + D3D12_MESSAGE_ID_JPEGDECODE_HAZARD = 789, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERUSAGE = 790, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDSRCBUFFERMISCFLAGS = 791, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPORTEDDSTTEXTUREUSAGE = 792, + D3D12_MESSAGE_ID_JPEGDECODE_BACKBUFFERNOTSUPPORTED = 793, + D3D12_MESSAGE_ID_JPEGDECODE_UNSUPPRTEDCOPYFLAGS = 794, + D3D12_MESSAGE_ID_JPEGENCODE_NOTSUPPORTED = 795, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSCANDATAOFFSET = 796, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDCOMPONENTS = 797, + D3D12_MESSAGE_ID_JPEGENCODE_SOURCENOT2D = 798, + D3D12_MESSAGE_ID_JPEGENCODE_TILEDRESOURCESUNSUPPORTED = 799, + D3D12_MESSAGE_ID_JPEGENCODE_GUARDRECTSUNSUPPORTED = 800, + D3D12_MESSAGE_ID_JPEGENCODE_XSUBSAMPLEMISMATCH = 801, + D3D12_MESSAGE_ID_JPEGENCODE_YSUBSAMPLEMISMATCH = 802, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDCOMPONENTS = 803, + D3D12_MESSAGE_ID_JPEGENCODE_FORMATUNSUPPORTED = 804, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDSUBRESOURCE = 805, + D3D12_MESSAGE_ID_JPEGENCODE_INVALIDMIPLEVEL = 806, + D3D12_MESSAGE_ID_JPEGENCODE_DIMENSIONSTOOLARGE = 807, + D3D12_MESSAGE_ID_JPEGENCODE_HAZARD = 808, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERUSAGE = 809, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDDSTBUFFERMISCFLAGS = 810, + D3D12_MESSAGE_ID_JPEGENCODE_UNSUPPORTEDSRCTEXTUREUSAGE = 811, + D3D12_MESSAGE_ID_JPEGENCODE_BACKBUFFERNOTSUPPORTED = 812, + D3D12_MESSAGE_ID_CREATEQUERYORPREDICATE_UNSUPPORTEDCONTEXTTTYPEFORQUERY = 813, + D3D12_MESSAGE_ID_FLUSH1_INVALIDCONTEXTTYPE = 814, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUE = 815, + D3D12_MESSAGE_ID_CREATERESOURCE_UNRECOGNIZEDCLEARVALUEFORMAT = 816, + D3D12_MESSAGE_ID_CREATERESOURCE_INVALIDCLEARVALUEFORMAT = 817, + D3D12_MESSAGE_ID_CREATERESOURCE_CLEARVALUEDENORMFLUSH = 818, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_INVALIDDEPTH = 819, + D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE = 820, + D3D12_MESSAGE_ID_CLEARDEPTHSTENCILVIEW_MISMATCHINGCLEARVALUE = 821, + D3D12_MESSAGE_ID_MAP_INVALIDHEAP = 822, + D3D12_MESSAGE_ID_UNMAP_INVALIDHEAP = 823, + D3D12_MESSAGE_ID_MAP_INVALIDRESOURCE = 824, + D3D12_MESSAGE_ID_UNMAP_INVALIDRESOURCE = 825, + D3D12_MESSAGE_ID_MAP_INVALIDSUBRESOURCE = 826, + D3D12_MESSAGE_ID_UNMAP_INVALIDSUBRESOURCE = 827, + D3D12_MESSAGE_ID_MAP_INVALIDRANGE = 828, + D3D12_MESSAGE_ID_UNMAP_INVALIDRANGE = 829, + D3D12_MESSAGE_ID_MAP_NULLRANGE = 830, + D3D12_MESSAGE_ID_UNMAP_NULLRANGE = 831, + D3D12_MESSAGE_ID_MAP_INVALIDDATAPOINTER = 832, + D3D12_MESSAGE_ID_MAP_INVALIDARG_RETURN = 833, + D3D12_MESSAGE_ID_MAP_OUTOFMEMORY_RETURN = 834, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_BUNDLENOTSUPPORTED = 835, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_COMMANDLISTMISMATCH = 836, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_OPENCOMMANDLIST = 837, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_FAILEDCOMMANDLIST = 838, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLDST = 839, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDDSTRESOURCEDIMENSION = 840, + D3D12_MESSAGE_ID_COPYBUFFERREGION_DSTRANGEOUTOFBOUNDS = 841, + D3D12_MESSAGE_ID_COPYBUFFERREGION_NULLSRC = 842, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDSRCRESOURCEDIMENSION = 843, + D3D12_MESSAGE_ID_COPYBUFFERREGION_SRCRANGEOUTOFBOUNDS = 844, + D3D12_MESSAGE_ID_COPYBUFFERREGION_INVALIDCOPYFLAGS = 845, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLDST = 846, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTTYPE = 847, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCEDIMENSION = 848, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCE = 849, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTSUBRESOURCE = 850, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTOFFSET = 851, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDDSTFORMAT = 852, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTFORMAT = 853, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDIMENSIONS = 854, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTROWPITCH = 855, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTPLACEMENT = 856, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTDSPLACEDFOOTPRINTFORMAT = 857, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_DSTREGIONOUTOFBOUNDS = 858, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_NULLSRC = 859, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCTYPE = 860, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCEDIMENSION = 861, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCRESOURCE = 862, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCSUBRESOURCE = 863, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCOFFSET = 864, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_UNRECOGNIZEDSRCFORMAT = 865, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCFORMAT = 866, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDIMENSIONS = 867, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCROWPITCH = 868, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCPLACEMENT = 869, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCDSPLACEDFOOTPRINTFORMAT = 870, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_SRCREGIONOUTOFBOUNDS = 871, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTCOORDINATES = 872, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDSRCBOX = 873, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_FORMATMISMATCH = 874, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_EMPTYBOX = 875, + D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDCOPYFLAGS = 876, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SUBRESOURCE_INDEX = 877, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_FORMAT = 878, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_RESOURCE_MISMATCH = 879, + D3D12_MESSAGE_ID_RESOLVESUBRESOURCE_INVALID_SAMPLE_COUNT = 880, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_INVALID_SHADER = 881, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_CS_ROOT_SIGNATURE_MISMATCH = 882, + D3D12_MESSAGE_ID_CREATECOMPUTEPIPELINESTATE_MISSING_ROOT_SIGNATURE = 883, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALIDCACHEDBLOB = 884, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBADAPTERMISMATCH = 885, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDRIVERVERSIONMISMATCH = 886, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBDESCMISMATCH = 887, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_CACHEDBLOBIGNORED = 888, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDHEAP = 889, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDRESOURCE = 890, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDBOX = 891, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_INVALIDSUBRESOURCE = 892, + D3D12_MESSAGE_ID_WRITETOSUBRESOURCE_EMPTYBOX = 893, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDHEAP = 894, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDRESOURCE = 895, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDBOX = 896, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_INVALIDSUBRESOURCE = 897, + D3D12_MESSAGE_ID_READFROMSUBRESOURCE_EMPTYBOX = 898, + D3D12_MESSAGE_ID_TOO_MANY_NODES_SPECIFIED = 899, + D3D12_MESSAGE_ID_INVALID_NODE_INDEX = 900, + D3D12_MESSAGE_ID_GETHEAPPROPERTIES_INVALIDRESOURCE = 901, + D3D12_MESSAGE_ID_NODE_MASK_MISMATCH = 902, + D3D12_MESSAGE_ID_COMMAND_LIST_OUTOFMEMORY = 903, + D3D12_MESSAGE_ID_COMMAND_LIST_MULTIPLE_SWAPCHAIN_BUFFER_REFERENCES = 904, + D3D12_MESSAGE_ID_COMMAND_LIST_TOO_MANY_SWAPCHAIN_REFERENCES = 905, + D3D12_MESSAGE_ID_COMMAND_QUEUE_TOO_MANY_SWAPCHAIN_REFERENCES = 906, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_WRONGSWAPCHAINBUFFERREFERENCE = 907, + D3D12_MESSAGE_ID_COMMAND_LIST_SETRENDERTARGETS_INVALIDNUMRENDERTARGETS = 908, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_TYPE = 909, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_FLAGS = 910, + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFLAGS = 911, + D3D12_MESSAGE_ID_CREATESHAREDRESOURCE_INVALIDFORMAT = 912, + D3D12_MESSAGE_ID_CREATESHAREDHEAP_INVALIDFLAGS = 913, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_UNRECOGNIZEDPROPERTIES = 914, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDSIZE = 915, + D3D12_MESSAGE_ID_REFLECTSHAREDPROPERTIES_INVALIDOBJECT = 916, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDOBJECT = 917, + D3D12_MESSAGE_ID_KEYEDMUTEX_INVALIDKEY = 918, + D3D12_MESSAGE_ID_KEYEDMUTEX_WRONGSTATE = 919, + D3D12_MESSAGE_ID_CREATE_QUEUE_INVALID_PRIORITY = 920, + D3D12_MESSAGE_ID_OBJECT_DELETED_WHILE_STILL_IN_USE = 921, + D3D12_MESSAGE_ID_CREATEPIPELINESTATE_INVALID_FLAGS = 922, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_HAS_NO_RESOURCE = 923, + D3D12_MESSAGE_ID_COMMAND_LIST_DRAW_RENDER_TARGET_DELETED = 924, + D3D12_MESSAGE_ID_CREATEGRAPHICSPIPELINESTATE_ALL_RENDER_TARGETS_HAVE_UNKNOWN_FORMAT = 925, + D3D12_MESSAGE_ID_HEAP_ADDRESS_RANGE_INTERSECTS_MULTIPLE_BUFFERS = 926, + D3D12_MESSAGE_ID_EXECUTECOMMANDLISTS_GPU_WRITTEN_READBACK_RESOURCE_MAPPED = 927, + D3D12_MESSAGE_ID_UNMAP_RANGE_NOT_NEEDED = 928, + D3D12_MESSAGE_ID_UNMAP_RANGE_NOT_EMPTY = 929, + D3D12_MESSAGE_ID_MAP_INVALID_NULLRANGE = 930, + D3D12_MESSAGE_ID_UNMAP_INVALID_NULLRANGE = 931, + D3D12_MESSAGE_ID_NO_GRAPHICS_API_SUPPORT = 932, + D3D12_MESSAGE_ID_NO_COMPUTE_API_SUPPORT = 933, + D3D12_MESSAGE_ID_D3D12_MESSAGES_END = 934, +}} +STRUCT!{struct D3D12_MESSAGE { + Category: D3D12_MESSAGE_CATEGORY, + Severity: D3D12_MESSAGE_SEVERITY, + ID: D3D12_MESSAGE_ID, + pDescription: *const ::c_char, + DescriptionByteLength: ::SIZE_T, +}} +STRUCT!{struct D3D12_INFO_QUEUE_FILTER_DESC { + NumCategories: ::UINT, + pCategoryList: *mut D3D12_MESSAGE_CATEGORY, + NumSeverities: ::UINT, + pSeverityList: *mut D3D12_MESSAGE_SEVERITY, + NumIDs: ::UINT, + pIDList: *mut D3D12_MESSAGE_ID, +}} +STRUCT!{struct D3D12_INFO_QUEUE_FILTER { + AllowList: D3D12_INFO_QUEUE_FILTER_DESC, + DenyList: D3D12_INFO_QUEUE_FILTER_DESC, +}} +pub const D3D12_INFO_QUEUE_DEFAULT_MESSAGE_COUNT_LIMIT: ::UINT = 1024; +RIDL!{interface ID3D12InfoQueue(ID3D12InfoQueueVtbl): IUnknown(IUnknownVtbl) { + fn SetMessageCountLimit(&mut self, MessageCountLimit: ::UINT64) -> ::HRESULT, + fn ClearStoredMessages(&mut self) -> (), + fn GetMessage( + &mut self, MessageIndex: ::UINT64, pMessage: *mut ::D3D12_MESSAGE, + pMessageByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn GetNumMessagesAllowedByStorageFilter(&mut self) -> ::UINT64, + fn GetNumMessagesDeniedByStorageFilter(&mut self) -> ::UINT64, + fn GetNumStoredMessages(&mut self) -> ::UINT64, + fn GetNumStoredMessagesAllowedByRetrievalFilter(&mut self) -> ::UINT64, + fn GetNumMessagesDiscardedByMessageCountLimit(&mut self) -> ::UINT64, + fn GetMessageCountLimit(&mut self) -> ::UINT64, + fn AddStorageFilterEntries(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn GetStorageFilter( + &mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER, pFilterByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn ClearStorageFilter(&mut self) -> (), + fn PushEmptyStorageFilter(&mut self) -> ::HRESULT, + fn PushCopyOfStorageFilter(&mut self) -> ::HRESULT, + fn PushStorageFilter(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn PopStorageFilter(&mut self) -> (), + fn GetStorageFilterStackSize(&mut self) -> ::UINT, + fn AddRetrievalFilterEntries(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn GetRetrievalFilter( + &mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER, pFilterByteLength: *mut ::SIZE_T + ) -> ::HRESULT, + fn ClearRetrievalFilter(&mut self) -> (), + fn PushEmptyRetrievalFilter(&mut self) -> ::HRESULT, + fn PushCopyOfRetrievalFilter(&mut self) -> ::HRESULT, + fn PushRetrievalFilter(&mut self, pFilter: *mut ::D3D12_INFO_QUEUE_FILTER) -> ::HRESULT, + fn PopRetrievalFilter(&mut self) -> (), + fn GetRetrievalFilterStackSize(&mut self) -> ::UINT, + fn AddMessage( + &mut self, Category: ::D3D12_MESSAGE_CATEGORY, Severity: ::D3D12_MESSAGE_SEVERITY, + ID: ::D3D12_MESSAGE_ID, pDescription: ::LPCSTR + ) -> ::HRESULT, + fn AddApplicationMessage( + &mut self, Severity: ::D3D12_MESSAGE_SEVERITY, pDescription: ::LPCSTR + ) -> ::HRESULT, + fn SetBreakOnCategory( + &mut self, Category: ::D3D12_MESSAGE_CATEGORY, bEnable: ::BOOL + ) -> ::HRESULT, + fn SetBreakOnSeverity( + &mut self, Severity: ::D3D12_MESSAGE_SEVERITY, bEnable: ::BOOL + ) -> ::HRESULT, + fn SetBreakOnID(&mut self, ID: ::D3D12_MESSAGE_ID, bEnable: ::BOOL) -> ::HRESULT, + fn GetBreakOnCategory(&mut self, Category: ::D3D12_MESSAGE_CATEGORY) -> ::BOOL, + fn GetBreakOnSeverity(&mut self, Severity: ::D3D12_MESSAGE_SEVERITY) -> ::BOOL, + fn GetBreakOnID(&mut self, ID: ::D3D12_MESSAGE_ID) -> ::BOOL, + fn SetMuteDebugOutput(&mut self, bMute: ::BOOL) -> (), + fn GetMuteDebugOutput(&mut self) -> ::BOOL +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d12shader.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12shader.rs new file mode 100644 index 0000000..bd210b2 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d12shader.rs @@ -0,0 +1,320 @@ +// Copyright © 2016; Dmitry Roschin +// Licensed under the MIT License +FLAGS!{ enum D3D12_SHADER_VERSION_TYPE { + D3D12_SHVER_PIXEL_SHADER = 0x0, + D3D12_SHVER_VERTEX_SHADER = 0x1, + D3D12_SHVER_GEOMETRY_SHADER = 0x2, + D3D12_SHVER_HULL_SHADER = 0x3, + D3D12_SHVER_DOMAIN_SHADER = 0x4, + D3D12_SHVER_COMPUTE_SHADER = 0x5, + D3D12_SHVER_RESERVED0 = 0xFFF0, +}} + +STRUCT!{struct D3D12_FUNCTION_DESC { + Version: ::UINT, + Creator: ::LPCSTR, + Flags: ::UINT, + ConstantBuffers: ::UINT, + BoundResources: ::UINT, + InstructionCount: ::UINT, + TempRegisterCount: ::UINT, + TempArrayCount: ::UINT, + DefCount: ::UINT, + DclCount: ::UINT, + TextureNormalInstructions: ::UINT, + TextureLoadInstructions: ::UINT, + TextureCompInstructions: ::UINT, + TextureBiasInstructions: ::UINT, + TextureGradientInstructions: ::UINT, + FloatInstructionCount: ::UINT, + IntInstructionCount: ::UINT, + UintInstructionCount: ::UINT, + StaticFlowControlCount: ::UINT, + DynamicFlowControlCount: ::UINT, + MacroInstructionCount: ::UINT, + ArrayInstructionCount: ::UINT, + MovInstructionCount: ::UINT, + MovcInstructionCount: ::UINT, + ConversionInstructionCount: ::UINT, + BitwiseInstructionCount: ::UINT, + MinFeatureLevel: ::D3D_FEATURE_LEVEL, + RequiredFeatureFlags: ::UINT64, + Name: ::LPCSTR, + FunctionParameterCount: ::INT, + HasReturn: ::BOOL, + Has10Level9VertexShader: ::BOOL, + Has10Level9PixelShader: ::BOOL, +}} + +STRUCT!{struct D3D12_LIBRARY_DESC { + Creator: ::LPCSTR, + Flags: ::UINT, + FunctionCount: ::UINT, +}} + +STRUCT!{struct D3D12_PARAMETER_DESC { + Name: ::LPCSTR, + SemanticName: ::LPCSTR, + Type: ::D3D_SHADER_VARIABLE_TYPE, + Class: ::D3D_SHADER_VARIABLE_CLASS, + Rows: ::UINT, + Columns: ::UINT, + InterpolationMode: ::D3D_INTERPOLATION_MODE, + Flags: ::D3D_PARAMETER_FLAGS, + FirstInRegister: ::UINT, + FirstInComponent: ::UINT, + FirstOutRegister: ::UINT, + FirstOutComponent: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_BUFFER_DESC { + Name: ::LPCSTR, + Type: ::D3D_CBUFFER_TYPE, + Variables: ::UINT, + Size: ::UINT, + uFlags: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_DESC { + Version: ::UINT, + Creator: ::LPCSTR, + Flags: ::UINT, + ConstantBuffers: ::UINT, + BoundResources: ::UINT, + InputParameters: ::UINT, + OutputParameters: ::UINT, + InstructionCount: ::UINT, + TempRegisterCount: ::UINT, + TempArrayCount: ::UINT, + DefCount: ::UINT, + DclCount: ::UINT, + TextureNormalInstructions: ::UINT, + TextureLoadInstructions: ::UINT, + TextureCompInstructions: ::UINT, + TextureBiasInstructions: ::UINT, + TextureGradientInstructions: ::UINT, + FloatInstructionCount: ::UINT, + IntInstructionCount: ::UINT, + UintInstructionCount: ::UINT, + StaticFlowControlCount: ::UINT, + DynamicFlowControlCount: ::UINT, + MacroInstructionCount: ::UINT, + ArrayInstructionCount: ::UINT, + CutInstructionCount: ::UINT, + EmitInstructionCount: ::UINT, + GSOutputTopology: ::D3D_PRIMITIVE_TOPOLOGY, + GSMaxOutputVertexCount: ::UINT, + InputPrimitive: ::D3D_PRIMITIVE, + PatchConstantParameters: ::UINT, + cGSInstanceCount: ::UINT, + cControlPoints: ::UINT, + HSOutputPrimitive: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE, + HSPartitioning: ::D3D_TESSELLATOR_PARTITIONING, + TessellatorDomain: ::D3D_TESSELLATOR_DOMAIN, + cBarrierInstructions: ::UINT, + cInterlockedInstructions: ::UINT, + cTextureStoreInstructions: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_INPUT_BIND_DESC { + Name: ::LPCSTR, + Type: ::D3D_SHADER_INPUT_TYPE, + BindPoint: ::UINT, + BindCount: ::UINT, + uFlags: ::UINT, + ReturnType: ::D3D_RESOURCE_RETURN_TYPE, + Dimension: ::D3D_SRV_DIMENSION, + NumSamples: ::UINT, + Space: ::UINT, + uID: ::UINT, +}} + +STRUCT!{struct D3D12_SHADER_TYPE_DESC { + Class: ::D3D_SHADER_VARIABLE_CLASS, + Type: ::D3D_SHADER_VARIABLE_TYPE, + Rows: ::UINT, + Columns: ::UINT, + Elements: ::UINT, + Members: ::UINT, + Offset: ::UINT, + Name: ::LPCSTR, +}} + +STRUCT!{struct D3D12_SHADER_VARIABLE_DESC { + Name: ::LPCSTR, + StartOffset: ::UINT, + Size: ::UINT, + uFlags: ::UINT, + DefaultValue: ::LPVOID, + StartTexture: ::UINT, + TextureSize: ::UINT, + StartSampler: ::UINT, + SamplerSize: ::UINT, +}} + +STRUCT!{struct D3D12_SIGNATURE_PARAMETER_DESC { + SemanticName: ::LPCSTR, + SemanticIndex: ::UINT, + Register: ::UINT, + SystemValueType: ::D3D_NAME, + ComponentType: ::D3D_REGISTER_COMPONENT_TYPE, + Mask: ::BYTE, + ReadWriteMask: ::BYTE, + Stream: ::UINT, + MinPrecision: ::D3D_MIN_PRECISION, +}} + +RIDL!( +interface ID3D12FunctionParameterReflection(ID3D12FunctionParameterReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_PARAMETER_DESC) -> ::HRESULT +}); + +RIDL!( +interface ID3D12FunctionReflection(ID3D12FunctionReflectionVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_FUNCTION_DESC) -> ::HRESULT, + fn GetConstantBufferByIndex( + &mut self, BufferIndex: ::UINT + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: ::UINT, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: ::LPCSTR, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetFunctionParameter( + &mut self, ParameterIndex: ::INT + ) -> *mut ::ID3D12FunctionParameterReflection +}); + +RIDL!( +interface ID3D12LibraryReflection(ID3D12LibraryReflectionVtbl): IUnknown(IUnknownVtbl) { + fn QueryInterface( + &mut self, iid: *const ::IID, ppv: *mut ::LPVOID + ) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG, + fn GetDesc(&mut self, pDesc: *mut ::D3D12_LIBRARY_DESC) -> ::HRESULT, + fn GetFunctionByIndex( + &mut self, FunctionIndex: ::INT + ) -> *mut ::ID3D12FunctionReflection +}); + +RIDL!( +interface ID3D12ShaderReflectionConstantBuffer(ID3D12ShaderReflectionConstantBufferVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_BUFFER_DESC) -> ::HRESULT, + fn GetVariableByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable +}); + +RIDL!( +interface ID3D12ShaderReflectionType(ID3D12ShaderReflectionTypeVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_TYPE_DESC) -> ::HRESULT, + fn GetMemberTypeByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionType, + fn GetMemberTypeByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionType, + fn GetMemberTypeName(&mut self, Index: ::UINT) -> ::LPCSTR, + fn IsEqual( + &mut self, pType: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT, + fn GetSubType(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetBaseClass(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetNumInterfaces(&mut self) -> ::UINT, + fn GetInterfaceByIndex( + &mut self, uIndex: ::UINT + ) -> *mut ::ID3D12ShaderReflectionType, + fn IsOfType( + &mut self, pType: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT, + fn ImplementsInterface( + &mut self, pBase: *mut ::ID3D12ShaderReflectionType + ) -> ::HRESULT +}); + +RIDL!( +interface ID3D12ShaderReflectionVariable(ID3D12ShaderReflectionVariableVtbl) { + fn GetDesc( + &mut self, pDesc: *mut ::D3D12_SHADER_VARIABLE_DESC + ) -> ::HRESULT, + fn GetType(&mut self) -> *mut ::ID3D12ShaderReflectionType, + fn GetBuffer(&mut self) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetInterfaceSlot(&mut self, uArrayIndex: ::UINT) -> ::UINT +}); + +RIDL!( +interface ID3D12ShaderReflection(ID3D12ShaderReflectionVtbl): IUnknown(IUnknownVtbl) { + fn QueryInterface( + &mut self, iid: *const ::IID, ppv: *mut ::LPVOID + ) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG, + fn GetDesc(&mut self, pDesc: *mut ::D3D12_SHADER_DESC) -> ::HRESULT, + fn GetConstantBufferByIndex( + &mut self, Index: ::UINT + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetConstantBufferByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionConstantBuffer, + fn GetResourceBindingDesc( + &mut self, ResourceIndex: ::UINT, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetInputParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetOutputParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetPatchConstantParameterDesc( + &mut self, ParameterIndex: ::UINT, pDesc: *mut ::D3D12_SIGNATURE_PARAMETER_DESC + ) -> ::HRESULT, + fn GetVariableByName( + &mut self, Name: ::LPCSTR + ) -> *mut ::ID3D12ShaderReflectionVariable, + fn GetResourceBindingDescByName( + &mut self, Name: ::LPCSTR, pDesc: *mut ::D3D12_SHADER_INPUT_BIND_DESC + ) -> ::HRESULT, + fn GetMovInstructionCount(&mut self) -> ::UINT, + fn GetMovcInstructionCount(&mut self) -> ::UINT, + fn GetConversionInstructionCount(&mut self) -> ::UINT, + fn GetBitwiseInstructionCount(&mut self) -> ::UINT, + fn GetGSInputPrimitive(&mut self) -> ::D3D_PRIMITIVE, + fn IsSampleFrequencyShader(&mut self) -> ::BOOL, + fn GetNumInterfaceSlots(&mut self) -> ::UINT, + fn GetMinFeatureLevel( + &mut self, pLevel: *mut ::D3D_FEATURE_LEVEL + ) -> ::HRESULT, + fn GetThreadGroupSize( + &mut self, pSizeX: *mut ::UINT, pSizeY: *mut ::UINT, pSizeZ: *mut ::UINT + ) -> ::UINT, + fn GetRequiresFlags(&mut self) -> ::UINT64 +}); + +pub type D3D12_CBUFFER_TYPE = ::D3D_CBUFFER_TYPE; +pub type D3D12_RESOURCE_RETURN_TYPE = ::D3D_RESOURCE_RETURN_TYPE; +pub type D3D12_TESSELLATOR_DOMAIN = ::D3D_TESSELLATOR_DOMAIN; +pub type D3D12_TESSELLATOR_OUTPUT_PRIMITIVE = ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE; +pub type D3D12_TESSELLATOR_PARTITIONING = ::D3D_TESSELLATOR_PARTITIONING; +pub type LPD3D12FUNCTIONPARAMETERREFLECTION = *mut ::ID3D12FunctionParameterReflection; +pub type LPD3D12FUNCTIONREFLECTION = *mut ::ID3D12FunctionReflection; +pub type LPD3D12LIBRARYREFLECTION = *mut ::ID3D12LibraryReflection; +pub type LPD3D12SHADERREFLECTION = *mut ::ID3D12ShaderReflection; +pub type LPD3D12SHADERREFLECTIONCONSTANTBUFFER = *mut ::ID3D12ShaderReflectionConstantBuffer; +pub type LPD3D12SHADERREFLECTIONTYPE = *mut ::ID3D12ShaderReflectionType; +pub type LPD3D12SHADERREFLECTIONVARIABLE = *mut ::ID3D12ShaderReflectionVariable; +pub const D3D_SHADER_REQUIRES_INNER_COVERAGE: ::UINT64 = 0x00000400; +pub const D3D_SHADER_REQUIRES_ROVS: ::UINT64 = 0x00001000; +pub const D3D_SHADER_REQUIRES_STENCIL_REF: ::UINT64 = 0x00000200; +pub const D3D_SHADER_REQUIRES_TYPED_UAV_LOAD_ADDITIONAL_FORMATS: ::UINT64 = 0x00000800; +pub const D3D_SHADER_REQUIRES_VIEWPORT_AND_RT_ARRAY_INDEX_FROM_ANY_SHADER_FEEDING_RASTERIZER: ::UINT64 = 0x00002000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d9.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9.rs new file mode 100644 index 0000000..26f9031 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9.rs @@ -0,0 +1,713 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License +//! Direct3D include file +pub const D3D_SDK_VERSION: ::DWORD = 32; +pub const D3D9b_SDK_VERSION: ::DWORD = 31; +RIDL!( +interface IDirect3D9(IDirect3D9Vtbl): IUnknown(IUnknownVtbl) { + fn RegisterSoftwareDevice(&mut self, pInitializeFunction: *mut ::VOID) -> ::HRESULT, + fn GetAdapterCount(&mut self) -> ::UINT, + fn GetAdapterIdentifier( + &mut self, Adapter: ::UINT, Flags: ::DWORD, pIdentifier: *mut ::D3DADAPTER_IDENTIFIER9 + ) -> ::HRESULT, + fn GetAdapterModeCount(&mut self, Adapter: ::UINT, Format: ::D3DFORMAT) -> ::UINT, + fn EnumAdapterModes( + &mut self, Adapter: ::UINT, Format: ::D3DFORMAT, Mode: ::UINT, pMode: *mut ::D3DDISPLAYMODE + ) -> ::HRESULT, + fn GetAdapterDisplayMode( + &mut self, Adapter: ::UINT, pMode: *mut ::D3DDISPLAYMODE + ) -> ::HRESULT, + fn CheckDeviceType( + &mut self, Adapter: ::UINT, DevType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + BackBufferFormat: ::D3DFORMAT, bWindowed: ::BOOL + ) -> ::HRESULT, + fn CheckDeviceFormat( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + Usage: ::DWORD, RType: ::D3DRESOURCETYPE, CheckFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn CheckDeviceMultiSampleType( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, SurfaceFormat: ::D3DFORMAT, + Windowed: ::BOOL, MultiSampleType: ::D3DMULTISAMPLE_TYPE, pQualityLevels: *mut ::DWORD + ) -> ::HRESULT, + fn CheckDepthStencilMatch( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, AdapterFormat: ::D3DFORMAT, + RenderTargetFormat: ::D3DFORMAT, DepthStencilFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn CheckDeviceFormatConversion( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, SourceFormat: ::D3DFORMAT, + TargetFormat: ::D3DFORMAT + ) -> ::HRESULT, + fn GetDeviceCaps( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, pCaps: *mut ::D3DCAPS9 + ) -> ::HRESULT, + fn GetAdapterMonitor(&mut self, Adapter: ::UINT) -> ::HMONITOR, + fn CreateDevice( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + ppReturnedDeviceInterface: *mut *mut IDirect3DDevice9 + ) -> ::HRESULT +} +); +pub type LPDIRECT3D9 = *mut IDirect3D9; +pub type PDIRECT3D9 = *mut IDirect3D9; +RIDL!( +interface IDirect3DDevice9(IDirect3DDevice9Vtbl): IUnknown(IUnknownVtbl) { + fn TestCooperativeLevel(&mut self) -> ::HRESULT, + fn GetAvailableTextureMem(&mut self) -> ::UINT, + fn EvictManagedResources(&mut self) -> ::HRESULT, + fn GetDirect3D(&mut self, ppD3D9: *mut *mut IDirect3D9) -> ::HRESULT, + fn GetDeviceCaps(&mut self, pCaps: *mut ::D3DCAPS9) -> ::HRESULT, + fn GetDisplayMode(&mut self, iSwapChain: ::UINT, pMode: *mut ::D3DDISPLAYMODE) -> ::HRESULT, + fn GetCreationParameters( + &mut self, pParameters: *mut ::D3DDEVICE_CREATION_PARAMETERS + ) -> ::HRESULT, + fn SetCursorProperties( + &mut self, XHotSpot: ::UINT, YHotSpot: ::UINT, pCursorBitmap: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn SetCursorPosition(&mut self, X: ::INT, Y: ::INT, Flags: ::DWORD) -> (), + fn ShowCursor(&mut self, bShow: ::BOOL) -> ::BOOL, + fn CreateAdditionalSwapChain( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pSwapChain: *mut *mut IDirect3DSwapChain9 + ) -> ::HRESULT, + fn GetSwapChain( + &mut self, iSwapChain: ::UINT, pSwapChain: *mut *mut IDirect3DSwapChain9 + ) -> ::HRESULT, + fn GetNumberOfSwapChains(&mut self) -> ::UINT, + fn Reset(&mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS) -> ::HRESULT, + fn Present( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA + ) -> ::HRESULT, + fn GetBackBuffer( + &mut self, iSwapChain: ::UINT, iBackBuffer: ::UINT, Type: ::D3DBACKBUFFER_TYPE, + ppBackBuffer: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRasterStatus( + &mut self, iSwapChain: ::UINT, pRasterStatus: *mut ::D3DRASTER_STATUS + ) -> ::HRESULT, + fn SetDialogBoxMode(&mut self, bEnableDialogs: ::BOOL) -> ::HRESULT, + fn SetGammaRamp( + &mut self, iSwapChain: ::UINT, Flags: ::DWORD, pRamp: *const ::D3DGAMMARAMP + ) -> (), + fn GetGammaRamp(&mut self, iSwapChain: ::UINT, pRamp: *mut ::D3DGAMMARAMP) -> (), + fn CreateTexture( + &mut self, Width: ::UINT, Height: ::UINT, Levels: ::UINT, Usage: ::DWORD, + Format: ::D3DFORMAT, Pool: ::D3DPOOL, ppTexture: *mut *mut IDirect3DTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateVolumeTexture( + &mut self, Width: ::UINT, Height: ::UINT, Depth: ::UINT, Levels: ::UINT, Usage: ::DWORD, + Format: ::D3DFORMAT, Pool: ::D3DPOOL, ppVolumeTexture: *mut *mut IDirect3DVolumeTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateCubeTexture( + &mut self, EdgeLength: ::UINT, Levels: ::UINT, Usage: ::DWORD, Format: ::D3DFORMAT, + Pool: ::D3DPOOL, ppCubeTexture: *mut *mut IDirect3DCubeTexture9, + pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateVertexBuffer( + &mut self, Length: ::UINT, Usage: ::DWORD, FVF: ::DWORD, Pool: ::D3DPOOL, + ppVertexBuffer: *mut *mut IDirect3DVertexBuffer9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateIndexBuffer( + &mut self, Length: ::UINT, Usage: ::DWORD, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppIndexBuffer: *mut *mut IDirect3DIndexBuffer9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateRenderTarget( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Lockable: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateDepthStencilSurface( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Discard: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn UpdateSurface( + &mut self, pSourceSurface: *mut IDirect3DSurface9, pSourceRect: *const ::RECT, + pDestinationSurface: *mut IDirect3DSurface9, pDestPoint: *const ::POINT + ) -> ::HRESULT, + fn UpdateTexture( + &mut self, pSourceTexture: *mut IDirect3DBaseTexture9, + pDestinationTexture: *mut IDirect3DBaseTexture9 + ) -> ::HRESULT, + fn GetRenderTargetData( + &mut self, pRenderTarget: *mut IDirect3DSurface9, pDestSurface: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetFrontBufferData( + &mut self, iSwapChain: ::UINT, pDestSurface: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn StretchRect( + &mut self, pSourceSurface: *mut IDirect3DSurface9, pSourceRect: *const ::RECT, + pDestSurface: *mut IDirect3DSurface9, pDestRect: *const ::RECT, + Filter: ::D3DTEXTUREFILTERTYPE + ) -> ::HRESULT, + fn ColorFill( + &mut self, pSurface: *mut IDirect3DSurface9, pRect: *const ::RECT, color: ::D3DCOLOR + ) -> ::HRESULT, + fn CreateOffscreenPlainSurface( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn SetRenderTarget( + &mut self, RenderTargetIndex: ::DWORD, pRenderTarget: *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRenderTarget( + &mut self, RenderTargetIndex: ::DWORD, ppRenderTarget: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn SetDepthStencilSurface(&mut self, pNewZStencil: *mut IDirect3DSurface9) -> ::HRESULT, + fn GetDepthStencilSurface( + &mut self, ppZStencilSurface: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn BeginScene(&mut self) -> ::HRESULT, + fn EndScene(&mut self) -> ::HRESULT, + fn Clear( + &mut self, Count: ::DWORD, pRects: *const ::D3DRECT, Flags: ::DWORD, Color: ::D3DCOLOR, + Z: ::FLOAT, Stencil: ::DWORD + ) -> ::HRESULT, + fn SetTransform( + &mut self, State: ::D3DTRANSFORMSTATETYPE, pMatrix: *const ::D3DMATRIX + ) -> ::HRESULT, + fn GetTransform( + &mut self, State: ::D3DTRANSFORMSTATETYPE, pMatrix: *mut ::D3DMATRIX + ) -> ::HRESULT, + fn MultiplyTransform( + &mut self, arg1: ::D3DTRANSFORMSTATETYPE, arg2: *const ::D3DMATRIX + ) -> ::HRESULT, + fn SetViewport(&mut self, pViewport: *const ::D3DVIEWPORT9) -> ::HRESULT, + fn GetViewport(&mut self, pViewport: *mut ::D3DVIEWPORT9) -> ::HRESULT, + fn SetMaterial(&mut self, pMaterial: *const ::D3DMATERIAL9) -> ::HRESULT, + fn GetMaterial(&mut self, pMaterial: *mut ::D3DMATERIAL9) -> ::HRESULT, + fn SetLight(&mut self, Index: ::DWORD, arg1: *const ::D3DLIGHT9) -> ::HRESULT, + fn GetLight(&mut self, Index: ::DWORD, arg1: *mut ::D3DLIGHT9) -> ::HRESULT, + fn LightEnable(&mut self, Index: ::DWORD, Enable: ::BOOL) -> ::HRESULT, + fn GetLightEnable(&mut self, Index: ::DWORD, pEnable: *mut ::BOOL) -> ::HRESULT, + fn SetClipPlane(&mut self, Index: ::DWORD, pPlane: *const ::FLOAT) -> ::HRESULT, + fn GetClipPlane(&mut self, Index: ::DWORD, pPlane: *mut ::FLOAT) -> ::HRESULT, + fn SetRenderState(&mut self, State: ::D3DRENDERSTATETYPE, Value: ::DWORD) -> ::HRESULT, + fn GetRenderState(&mut self, State: ::D3DRENDERSTATETYPE, pValue: *mut ::DWORD) -> ::HRESULT, + fn CreateStateBlock( + &mut self, Type: ::D3DSTATEBLOCKTYPE, ppSB: *mut *mut IDirect3DStateBlock9 + ) -> ::HRESULT, + fn BeginStateBlock(&mut self) -> ::HRESULT, + fn EndStateBlock(&mut self, ppSB: *mut *mut IDirect3DStateBlock9) -> ::HRESULT, + fn SetClipStatus(&mut self, pClipStatus: *const ::D3DCLIPSTATUS9) -> ::HRESULT, + fn GetClipStatus(&mut self, pClipStatus: *mut ::D3DCLIPSTATUS9) -> ::HRESULT, + fn GetTexture( + &mut self, Stage: ::DWORD, ppTexture: *mut *mut IDirect3DBaseTexture9 + ) -> ::HRESULT, + fn SetTexture(&mut self, Stage: ::DWORD, pTexture: *mut IDirect3DBaseTexture9) -> ::HRESULT, + fn GetTextureStageState( + &mut self, Stage: ::DWORD, Type: ::D3DTEXTURESTAGESTATETYPE, pValue: *mut ::DWORD + ) -> ::HRESULT, + fn SetTextureStageState( + &mut self, Stage: ::DWORD, Type: ::D3DTEXTURESTAGESTATETYPE, Value: ::DWORD + ) -> ::HRESULT, + fn GetSamplerState( + &mut self, Sampler: ::DWORD, Type: ::D3DSAMPLERSTATETYPE, pValue: *mut ::DWORD + ) -> ::HRESULT, + fn SetSamplerState( + &mut self, Sampler: ::DWORD, Type: ::D3DSAMPLERSTATETYPE, Value: ::DWORD + ) -> ::HRESULT, + fn ValidateDevice(&mut self, pNumPasses: *mut ::DWORD) -> ::HRESULT, + fn SetPaletteEntries( + &mut self, PaletteNumber: ::UINT, pEntries: *const ::PALETTEENTRY + ) -> ::HRESULT, + fn GetPaletteEntries( + &mut self, PaletteNumber: ::UINT, pEntries: *mut ::PALETTEENTRY + ) -> ::HRESULT, + fn SetCurrentTexturePalette(&mut self, PaletteNumber: ::UINT) -> ::HRESULT, + fn GetCurrentTexturePalette(&mut self, PaletteNumber: *mut ::UINT) -> ::HRESULT, + fn SetScissorRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn GetScissorRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn SetSoftwareVertexProcessing(&mut self, bSoftware: ::BOOL) -> ::HRESULT, + fn GetSoftwareVertexProcessing(&mut self) -> ::BOOL, + fn SetNPatchMode(&mut self, nSegments: ::FLOAT) -> ::HRESULT, + fn GetNPatchMode(&mut self) -> ::FLOAT, + fn DrawPrimitive( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, StartVertex: ::UINT, PrimitiveCount: ::UINT + ) -> ::HRESULT, + fn DrawIndexedPrimitive( + &mut self, arg1: ::D3DPRIMITIVETYPE, BaseVertexIndex: ::INT, MinVertexIndex: ::UINT, + NumVertices: ::UINT, startIndex: ::UINT, primCount: ::UINT + ) -> ::HRESULT, + fn DrawPrimitiveUP( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, PrimitiveCount: ::UINT, + pVertexStreamZeroData: *const ::VOID, VertexStreamZeroStride: ::UINT + ) -> ::HRESULT, + fn DrawIndexedPrimitiveUP( + &mut self, PrimitiveType: ::D3DPRIMITIVETYPE, MinVertexIndex: ::UINT, NumVertices: ::UINT, + PrimitiveCount: ::UINT, pIndexData: *const ::VOID, IndexDataFormat: ::D3DFORMAT, + pVertexStreamZeroData: *const ::VOID, VertexStreamZeroStride: ::UINT + ) -> ::HRESULT, + fn ProcessVertices( + &mut self, SrcStartIndex: ::UINT, DestIndex: ::UINT, VertexCount: ::UINT, + pDestBuffer: *mut IDirect3DVertexBuffer9, pVertexDecl: *mut IDirect3DVertexDeclaration9, + Flags: ::DWORD + ) -> ::HRESULT, + fn CreateVertexDeclaration( + &mut self, pVertexElements: *const ::D3DVERTEXELEMENT9, + ppDecl: *mut *mut IDirect3DVertexDeclaration9 + ) -> ::HRESULT, + fn SetVertexDeclaration(&mut self, pDecl: *mut IDirect3DVertexDeclaration9) -> ::HRESULT, + fn GetVertexDeclaration(&mut self, ppDecl: *mut *mut IDirect3DVertexDeclaration9) -> ::HRESULT, + fn SetFVF(&mut self, FVF: ::DWORD) -> ::HRESULT, + fn GetFVF(&mut self, pFVF: *mut ::DWORD) -> ::HRESULT, + fn CreateVertexShader( + &mut self, pFunction: *const ::DWORD, ppShader: *mut *mut IDirect3DVertexShader9 + ) -> ::HRESULT, + fn SetVertexShader(&mut self, pShader: *mut IDirect3DVertexShader9) -> ::HRESULT, + fn GetVertexShader(&mut self, ppShader: *mut *mut IDirect3DVertexShader9) -> ::HRESULT, + fn SetVertexShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *const ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn SetVertexShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *const ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn SetVertexShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *const ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn GetVertexShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn SetStreamSource( + &mut self, StreamNumber: ::UINT, pStreamData: *mut IDirect3DVertexBuffer9, + OffsetInBytes: ::UINT, Stride: ::UINT + ) -> ::HRESULT, + fn GetStreamSource( + &mut self, StreamNumber: ::UINT, ppStreamData: *mut *mut IDirect3DVertexBuffer9, + pOffsetInBytes: *mut ::UINT, pStride: *mut ::UINT + ) -> ::HRESULT, + fn SetStreamSourceFreq(&mut self, StreamNumber: ::UINT, Setting: ::UINT) -> ::HRESULT, + fn GetStreamSourceFreq(&mut self, StreamNumber: ::UINT, pSetting: *mut ::UINT) -> ::HRESULT, + fn SetIndices(&mut self, pIndexData: *mut IDirect3DIndexBuffer9) -> ::HRESULT, + fn GetIndices(&mut self, ppIndexData: *mut *mut IDirect3DIndexBuffer9) -> ::HRESULT, + fn CreatePixelShader( + &mut self, pFunction: *const ::DWORD, ppShader: *mut *mut IDirect3DPixelShader9 + ) -> ::HRESULT, + fn SetPixelShader(&mut self, pShader: *mut IDirect3DPixelShader9) -> ::HRESULT, + fn GetPixelShader(&mut self, ppShader: *mut *mut IDirect3DPixelShader9) -> ::HRESULT, + fn SetPixelShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *const ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantF( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::FLOAT, Vector4fCount: ::UINT + ) -> ::HRESULT, + fn SetPixelShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *const ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantI( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::INT, Vector4iCount: ::UINT + ) -> ::HRESULT, + fn SetPixelShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *const ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn GetPixelShaderConstantB( + &mut self, StartRegister: ::UINT, pConstantData: *mut ::BOOL, BoolCount: ::UINT + ) -> ::HRESULT, + fn DrawRectPatch( + &mut self, Handle: ::UINT, pNumSegs: *const ::FLOAT, + pRectPatchInfo: *const ::D3DRECTPATCH_INFO + ) -> ::HRESULT, + fn DrawTriPatch( + &mut self, Handle: ::UINT, pNumSegs: *const ::FLOAT, + pTriPatchInfo: *const ::D3DTRIPATCH_INFO + ) -> ::HRESULT, + fn DeletePatch(&mut self, Handle: ::UINT) -> ::HRESULT, + fn CreateQuery( + &mut self, Type: ::D3DQUERYTYPE, ppQuery: *mut *mut IDirect3DQuery9 + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9 = *mut IDirect3DDevice9; +pub type PDIRECT3DDEVICE9 = *mut IDirect3DDevice9; +RIDL!( +interface IDirect3DStateBlock9(IDirect3DStateBlock9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn Capture(&mut self) -> ::HRESULT, + fn Apply(&mut self) -> ::HRESULT +} +); +pub type LPDIRECT3DSTATEBLOCK9 = *mut IDirect3DStateBlock9; +pub type PDIRECT3DSTATEBLOCK9 = *mut IDirect3DStateBlock9; +RIDL!( +interface IDirect3DSwapChain9(IDirect3DSwapChain9Vtbl): IUnknown(IUnknownVtbl) { + fn Present( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA, dwFlags: ::DWORD + ) -> ::HRESULT, + fn GetFrontBufferData(&mut self, pDestSurface: *mut IDirect3DSurface9) -> ::HRESULT, + fn GetBackBuffer( + &mut self, iBackBuffer: ::UINT, Type: ::D3DBACKBUFFER_TYPE, + ppBackBuffer: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn GetRasterStatus(&mut self, pRasterStatus: *mut ::D3DRASTER_STATUS) -> ::HRESULT, + fn GetDisplayMode(&mut self, pMode: *mut ::D3DDISPLAYMODE) -> ::HRESULT, + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetPresentParameters( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS + ) -> ::HRESULT +} +); +pub type LPDIRECT3DSWAPCHAIN9 = *mut IDirect3DSwapChain9; +pub type PDIRECT3DSWAPCHAIN9 = *mut IDirect3DSwapChain9; +RIDL!( +interface IDirect3DResource9(IDirect3DResource9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn SetPrivateData( + &mut self, refguid: *const ::GUID, pData: *const ::VOID, SizeOfData: ::DWORD, + Flags: ::DWORD + ) -> ::HRESULT, + fn GetPrivateData( + &mut self, refguid: *const ::GUID, pData: *mut ::VOID, pSizeOfData: *mut ::DWORD + ) -> ::HRESULT, + fn FreePrivateData(&mut self, refguid: *const ::GUID) -> ::HRESULT, + fn SetPriority(&mut self, PriorityNew: ::DWORD) -> ::DWORD, + fn GetPriority(&mut self) -> ::DWORD, + fn PreLoad(&mut self) -> (), + fn GetType(&mut self) -> ::D3DRESOURCETYPE +} +); +pub type LPDIRECT3DRESOURCE9 = *mut IDirect3DResource9; +pub type PDIRECT3DRESOURCE9 = *mut IDirect3DResource9; +RIDL!( +interface IDirect3DVertexDeclaration9(IDirect3DVertexDeclaration9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetDeclaration( + &mut self, pElement: *mut ::D3DVERTEXELEMENT9, pNumElements: *mut ::UINT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXDECLARATION9 = *mut IDirect3DVertexDeclaration9; +pub type PDIRECT3DVERTEXDECLARATION9 = *mut IDirect3DVertexDeclaration9; +RIDL!( +interface IDirect3DVertexShader9(IDirect3DVertexShader9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetFunction(&mut self, arg1: *mut ::VOID, pSizeOfData: *mut ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXSHADER9 = *mut IDirect3DVertexShader9; +pub type PDIRECT3DVERTEXSHADER9 = *mut IDirect3DVertexShader9; +RIDL!( +interface IDirect3DPixelShader9(IDirect3DPixelShader9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetFunction(&mut self, arg1: *mut ::VOID, pSizeOfData: *mut ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DPIXELSHADER9 = *mut IDirect3DPixelShader9; +pub type PDIRECT3DPIXELSHADER9 = *mut IDirect3DPixelShader9; +RIDL!( +interface IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn SetLOD(&mut self, LODNew: ::DWORD) -> ::DWORD, + fn GetLOD(&mut self) -> ::DWORD, + fn GetLevelCount(&mut self) -> ::DWORD, + fn SetAutoGenFilterType(&mut self, FilterType: ::D3DTEXTUREFILTERTYPE) -> ::HRESULT, + fn GetAutoGenFilterType(&mut self) -> ::D3DTEXTUREFILTERTYPE, + fn GenerateMipSubLevels(&mut self) -> () +} +); +pub type LPDIRECT3DBASETEXTURE9 = *mut IDirect3DBaseTexture9; +pub type PDIRECT3DBASETEXTURE9 = *mut IDirect3DBaseTexture9; +RIDL!( +interface IDirect3DTexture9(IDirect3DTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn GetSurfaceLevel( + &mut self, Level: ::UINT, ppSurfaceLevel: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn LockRect( + &mut self, Level: ::UINT, pLockedRect: *mut ::D3DLOCKED_RECT, pRect: *const ::RECT, + Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self, Level: ::UINT) -> ::HRESULT, + fn AddDirtyRect(&mut self, pDirtyRect: *const ::RECT) -> ::HRESULT +} +); +pub type LPDIRECT3DTEXTURE9 = *mut IDirect3DTexture9; +pub type PDIRECT3DTEXTURE9 = *mut IDirect3DTexture9; +RIDL!( +interface IDirect3DVolumeTexture9(IDirect3DVolumeTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DVOLUME_DESC) -> ::HRESULT, + fn GetVolumeLevel( + &mut self, Level: ::UINT, ppVolumeLevel: *mut *mut IDirect3DVolume9 + ) -> ::HRESULT, + fn LockBox( + &mut self, Level: ::UINT, pLockedVolume: *mut ::D3DLOCKED_BOX, pBox: *const ::D3DBOX, + Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockBox(&mut self, Level: ::UINT) -> ::HRESULT, + fn AddDirtyBox(&mut self, pDirtyBox: *const ::D3DBOX) -> ::HRESULT +} +); +pub type LPDIRECT3DVOLUMETEXTURE9 = *mut IDirect3DVolumeTexture9; +pub type PDIRECT3DVOLUMETEXTURE9 = *mut IDirect3DVolumeTexture9; +RIDL!( +interface IDirect3DCubeTexture9(IDirect3DCubeTexture9Vtbl): IDirect3DBaseTexture9(IDirect3DBaseTexture9Vtbl) { + fn GetLevelDesc(&mut self, Level: ::UINT, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn GetCubeMapSurface( + &mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT, + ppCubeMapSurface: *mut *mut IDirect3DSurface9 + ) -> ::HRESULT, + fn LockRect( + &mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT, pLockedRect: *mut ::D3DLOCKED_RECT, + pRect: *const ::RECT, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self, FaceType: ::D3DCUBEMAP_FACES, Level: ::UINT) -> ::HRESULT, + fn AddDirtyRect( + &mut self, FaceType: ::D3DCUBEMAP_FACES, pDirtyRect: *const ::RECT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DCUBETEXTURE9 = *mut IDirect3DCubeTexture9; +pub type PDIRECT3DCUBETEXTURE9 = *mut IDirect3DCubeTexture9; +RIDL!( +interface IDirect3DVertexBuffer9(IDirect3DVertexBuffer9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn Lock( + &mut self, OffsetToLock: ::UINT, SizeToLock: ::UINT, ppbData: *mut *mut ::VOID, + Flags: ::DWORD + ) -> ::HRESULT, + fn Unlock(&mut self) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DVERTEXBUFFER_DESC) -> ::HRESULT +} +); +pub type LPDIRECT3DVERTEXBUFFER9 = *mut IDirect3DVertexBuffer9; +pub type PDIRECT3DVERTEXBUFFER9 = *mut IDirect3DVertexBuffer9; +RIDL!( +interface IDirect3DIndexBuffer9(IDirect3DIndexBuffer9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn Lock( + &mut self, OffsetToLock: ::UINT, SizeToLock: ::UINT, ppbData: *mut *mut ::VOID, + Flags: ::DWORD + ) -> ::HRESULT, + fn Unlock(&mut self) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DINDEXBUFFER_DESC) -> ::HRESULT +} +); +pub type LPDIRECT3DINDEXBUFFER9 = *mut IDirect3DIndexBuffer9; +pub type PDIRECT3DINDEXBUFFER9 = *mut IDirect3DIndexBuffer9; +RIDL!( +interface IDirect3DSurface9(IDirect3DSurface9Vtbl): IDirect3DResource9(IDirect3DResource9Vtbl) { + fn GetContainer(&mut self, riid: *const ::IID, ppContainer: *mut *mut ::VOID) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DSURFACE_DESC) -> ::HRESULT, + fn LockRect( + &mut self, pLockedRect: *mut ::D3DLOCKED_RECT, pRect: *const ::RECT, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockRect(&mut self) -> ::HRESULT, + fn GetDC(&mut self, phdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, hdc: ::HDC) -> ::HRESULT +} +); +pub type LPDIRECT3DSURFACE9 = *mut IDirect3DSurface9; +pub type PDIRECT3DSURFACE9 = *mut IDirect3DSurface9; +RIDL!( +interface IDirect3DVolume9(IDirect3DVolume9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn SetPrivateData( + &mut self, refguid: *const ::GUID, pData: *const ::VOID, SizeOfData: ::DWORD, + Flags: ::DWORD + ) -> ::HRESULT, + fn GetPrivateData( + &mut self, refguid: *const ::GUID, pData: *mut ::VOID, pSizeOfData: *mut ::DWORD + ) -> ::HRESULT, + fn FreePrivateData(&mut self, refguid: *const ::GUID) -> ::HRESULT, + fn GetContainer(&mut self, riid: *const ::IID, ppContainer: *mut *mut ::VOID) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut ::D3DVOLUME_DESC) -> ::HRESULT, + fn LockBox( + &mut self, pLockedVolume: *mut ::D3DLOCKED_BOX, pBox: *const ::D3DBOX, Flags: ::DWORD + ) -> ::HRESULT, + fn UnlockBox(&mut self) -> ::HRESULT +} +); +pub type LPDIRECT3DVOLUME9 = *mut IDirect3DVolume9; +pub type PDIRECT3DVOLUME9 = *mut IDirect3DVolume9; +RIDL!( +interface IDirect3DQuery9(IDirect3DQuery9Vtbl): IUnknown(IUnknownVtbl) { + fn GetDevice(&mut self, ppDevice: *mut *mut IDirect3DDevice9) -> ::HRESULT, + fn GetType(&mut self) -> ::D3DRESOURCETYPE, + fn GetDataSize(&mut self) -> ::DWORD, + fn Issue(&mut self, dwIssueFlags: ::DWORD) -> ::HRESULT, + fn GetData( + &mut self, pData: *mut ::VOID, dwSize: ::DWORD, dwGetDataFlags: ::DWORD + ) -> ::HRESULT +} +); +pub type LPDIRECT3DQUERY9 = *mut IDirect3DQuery9; +pub type PDIRECT3DQUERY9 = *mut IDirect3DQuery9; +pub const D3DCREATE_FPU_PRESERVE: ::DWORD = 0x2; +pub const D3DCREATE_MULTITHREADED: ::DWORD = 0x4; +pub const D3DCREATE_PUREDEVICE: ::DWORD = 0x10; +pub const D3DCREATE_SOFTWARE_VERTEXPROCESSING: ::DWORD = 0x20; +pub const D3DCREATE_HARDWARE_VERTEXPROCESSING: ::DWORD = 0x40; +pub const D3DCREATE_MIXED_VERTEXPROCESSING: ::DWORD = 0x80; +pub const D3DCREATE_DISABLE_DRIVER_MANAGEMENT: ::DWORD = 0x100; +pub const D3DCREATE_ADAPTERGROUP_DEVICE: ::DWORD = 0x200; +pub const D3DCREATE_DISABLE_DRIVER_MANAGEMENT_EX: ::DWORD = 0x400; +pub const D3DCREATE_NOWINDOWCHANGES: ::DWORD = 0x800; +pub const D3DCREATE_DISABLE_PSGP_THREADING: ::DWORD = 0x2000; +pub const D3DCREATE_ENABLE_PRESENTSTATS: ::DWORD = 0x4000; +pub const D3DCREATE_DISABLE_PRESENTSTATS: ::DWORD = 0x8000; +pub const D3DCREATE_SCREENSAVER: ::DWORD = 0x10000000; +pub const D3DADAPTER_DEFAULT: ::DWORD = 0; +RIDL!( +interface IDirect3D9Ex(IDirect3D9ExVtbl): IDirect3D9(IDirect3D9Vtbl) { + fn GetAdapterModeCountEx( + &mut self, Adapter: ::UINT, pFilter: *const ::D3DDISPLAYMODEFILTER + ) -> ::UINT, + fn EnumAdapterModesEx( + &mut self, Adapter: ::UINT, pFilter: *const ::D3DDISPLAYMODEFILTER, Mode: ::UINT, + pMode: *mut ::D3DDISPLAYMODEEX + ) -> ::HRESULT, + fn GetAdapterDisplayModeEx( + &mut self, Adapter: ::UINT, pMode: *mut ::D3DDISPLAYMODEEX, + pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT, + fn CreateDeviceEx( + &mut self, Adapter: ::UINT, DeviceType: ::D3DDEVTYPE, hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pFullscreenDisplayMode: *mut ::D3DDISPLAYMODEEX, + ppReturnedDeviceInterface: *mut *mut IDirect3DDevice9Ex + ) -> ::HRESULT, + fn GetAdapterLUID(&mut self, Adapter: ::UINT, pLUID: *mut ::LUID) -> ::HRESULT +} +); +pub type LPDIRECT3D9EX = *mut IDirect3D9Ex; +pub type PDIRECT3D9EX = *mut IDirect3D9Ex; +RIDL!( +interface IDirect3DDevice9Ex(IDirect3DDevice9ExVtbl): IDirect3DDevice9(IDirect3DDevice9Vtbl) { + fn SetConvolutionMonoKernel( + &mut self, width: ::UINT, height: ::UINT, rows: *mut ::FLOAT, columns: *mut ::FLOAT + ) -> ::HRESULT, + fn ComposeRects( + &mut self, pSrc: *mut IDirect3DSurface9, pDst: *mut IDirect3DSurface9, + pSrcRectDescs: *mut IDirect3DVertexBuffer9, NumRects: ::UINT, + pDstRectDescs: *mut IDirect3DVertexBuffer9, Operation: ::D3DCOMPOSERECTSOP, Xoffset: ::INT, + Yoffset: ::INT + ) -> ::HRESULT, + fn PresentEx( + &mut self, pSourceRect: *const ::RECT, pDestRect: *const ::RECT, + hDestWindowOverride: ::HWND, pDirtyRegion: *const ::RGNDATA, dwFlags: ::DWORD + ) -> ::HRESULT, + fn GetGPUThreadPriority(&mut self, pPriority: *mut ::INT) -> ::HRESULT, + fn SetGPUThreadPriority(&mut self, Priority: ::INT) -> ::HRESULT, + fn WaitForVBlank(&mut self, iSwapChain: ::UINT) -> ::HRESULT, + fn CheckResourceResidency( + &mut self, pResourceArray: *mut *mut IDirect3DResource9, NumResources: ::UINT32 + ) -> ::HRESULT, + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT, + fn CheckDeviceState(&mut self, hDestinationWindow: ::HWND) -> ::HRESULT, + fn CreateRenderTargetEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Lockable: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn CreateOffscreenPlainSurfaceEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, Pool: ::D3DPOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn CreateDepthStencilSurfaceEx( + &mut self, Width: ::UINT, Height: ::UINT, Format: ::D3DFORMAT, + MultiSample: ::D3DMULTISAMPLE_TYPE, MultisampleQuality: ::DWORD, Discard: ::BOOL, + ppSurface: *mut *mut IDirect3DSurface9, pSharedHandle: *mut ::HANDLE, Usage: ::DWORD + ) -> ::HRESULT, + fn ResetEx( + &mut self, pPresentationParameters: *mut ::D3DPRESENT_PARAMETERS, + pFullscreenDisplayMode: *mut ::D3DDISPLAYMODEEX + ) -> ::HRESULT, + fn GetDisplayModeEx( + &mut self, iSwapChain: ::UINT, pMode: *mut ::D3DDISPLAYMODEEX, + pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9EX = *mut IDirect3DDevice9Ex; +pub type PDIRECT3DDEVICE9EX = *mut IDirect3DDevice9Ex; +RIDL!( +interface IDirect3DSwapChain9Ex(IDirect3DSwapChain9ExVtbl): IDirect3DSwapChain9(IDirect3DSwapChain9Vtbl) { + fn GetLastPresentCount(&mut self, pLastPresentCount: *mut ::UINT) -> ::HRESULT, + fn GetPresentStats(&mut self, pPresentationStatistics: *mut ::D3DPRESENTSTATS) -> ::HRESULT, + fn GetDisplayModeEx( + &mut self, pMode: *mut ::D3DDISPLAYMODEEX, pRotation: *mut ::D3DDISPLAYROTATION + ) -> ::HRESULT +} +); +pub type LPDIRECT3DSWAPCHAIN9EX = *mut IDirect3DSwapChain9Ex; +pub type PDIRECT3DSWAPCHAIN9EX = *mut IDirect3DSwapChain9Ex; +RIDL!( +interface IDirect3D9ExOverlayExtension(IDirect3D9ExOverlayExtensionVtbl): IUnknown(IUnknownVtbl) { + fn CheckDeviceOverlayType( + &mut self, Adapter: ::UINT, DevType: ::D3DDEVTYPE, OverlayWidth: ::UINT, + OverlayHeight: ::UINT, OverlayFormat: ::D3DFORMAT, pDisplayMode: *mut ::D3DDISPLAYMODEEX, + DisplayRotation: ::D3DDISPLAYROTATION, pOverlayCaps: *mut ::D3DOVERLAYCAPS + ) -> ::HRESULT +} +); +pub type LPDIRECT3D9EXOVERLAYEXTENSION = *mut IDirect3D9ExOverlayExtension; +pub type PDIRECT3D9EXOVERLAYEXTENSION = *mut IDirect3D9ExOverlayExtension; +RIDL!( +interface IDirect3DDevice9Video(IDirect3DDevice9VideoVtbl): IUnknown(IUnknownVtbl) { + fn GetContentProtectionCaps( + &mut self, pCryptoType: *const ::GUID, pDecodeProfile: *const ::GUID, + pCaps: *mut ::D3DCONTENTPROTECTIONCAPS + ) -> ::HRESULT, + fn CreateAuthenticatedChannel( + &mut self, ChannelType: ::D3DAUTHENTICATEDCHANNELTYPE, + ppAuthenticatedChannel: *mut *mut IDirect3DAuthenticatedChannel9, + pChannelHandle: *mut ::HANDLE + ) -> ::HRESULT, + fn CreateCryptoSession( + &mut self, pCryptoType: *const ::GUID, pDecodeProfile: *const ::GUID, + ppCryptoSession: *mut *mut IDirect3DCryptoSession9, pCryptoHandle: *mut ::HANDLE + ) -> ::HRESULT +} +); +pub type LPDIRECT3DDEVICE9VIDEO = *mut IDirect3DDevice9Video; +pub type PDIRECT3DDEVICE9VIDEO = *mut IDirect3DDevice9Video; +RIDL!( +interface IDirect3DAuthenticatedChannel9(IDirect3DAuthenticatedChannel9Vtbl): IUnknown(IUnknownVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut ::UINT) -> ::HRESULT, + fn GetCertificate(&mut self, CertifacteSize: ::UINT, ppCertificate: *mut ::BYTE) -> ::HRESULT, + fn NegotiateKeyExchange(&mut self, DataSize: ::UINT, pData: *mut ::VOID) -> ::HRESULT, + fn Query( + &mut self, InputSize: ::UINT, pInput: *const ::VOID, OutputSize: ::UINT, + pOutput: *mut ::VOID + ) -> ::HRESULT, + fn Configure( + &mut self, InputSize: ::UINT, pInput: *const ::VOID, + pOutput: *mut ::D3DAUTHENTICATEDCHANNEL_CONFIGURE_OUTPUT + ) -> ::HRESULT +} +); +pub type LPDIRECT3DAUTHENTICATEDCHANNEL9 = *mut IDirect3DAuthenticatedChannel9; +pub type PDIRECT3DAUTHENTICATEDCHANNEL9 = *mut IDirect3DAuthenticatedChannel9; +RIDL!( +interface IDirect3DCryptoSession9(IDirect3DCryptoSession9Vtbl): IUnknown(IUnknownVtbl) { + fn GetCertificateSize(&mut self, pCertificateSize: *mut ::UINT) -> ::HRESULT, + fn GetCertificate(&mut self, CertifacteSize: ::UINT, ppCertificate: *mut ::BYTE) -> ::HRESULT, + fn NegotiateKeyExchange(&mut self, DataSize: ::UINT, pData: *mut ::VOID) -> ::HRESULT, + fn EncryptionBlt( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pDstSurface: *mut IDirect3DSurface9, + DstSurfaceSize: ::UINT, pIV: *mut ::VOID + ) -> ::HRESULT, + fn DecryptionBlt( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pDstSurface: *mut IDirect3DSurface9, + SrcSurfaceSize: ::UINT, pEncryptedBlockInfo: *mut ::D3DENCRYPTED_BLOCK_INFO, + pContentKey: *mut ::VOID, pIV: *mut ::VOID + ) -> ::HRESULT, + fn GetSurfacePitch( + &mut self, pSrcSurface: *mut IDirect3DSurface9, pSurfacePitch: *mut ::UINT + ) -> ::HRESULT, + fn StartSessionKeyRefresh( + &mut self, pRandomNumber: *mut ::VOID, RandomNumberSize: ::UINT + ) -> ::HRESULT, + fn FinishSessionKeyRefresh(&mut self) -> ::HRESULT, + fn GetEncryptionBltKey(&mut self, pReadbackKey: *mut ::VOID, KeySize: ::UINT) -> ::HRESULT +} +); +pub type LPDIRECT3DCRYPTOSESSION9 = *mut IDirect3DCryptoSession9; +pub type PDIRECT3DCRYPTOSESSION9 = *mut IDirect3DCryptoSession9; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d9caps.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9caps.rs new file mode 100644 index 0000000..74c877d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9caps.rs @@ -0,0 +1,349 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License +//! Direct3D capabilities include file +STRUCT!{struct D3DVSHADERCAPS2_0 { + Caps: ::DWORD, + DynamicFlowControlDepth: ::INT, + NumTemps: ::INT, + StaticFlowControlDepth: ::INT, +}} +pub const D3DVS20CAPS_PREDICATION: ::DWORD = 1 << 0; +pub const D3DVS20_MAX_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 24; +pub const D3DVS20_MIN_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DVS20_MAX_NUMTEMPS: ::DWORD = 32; +pub const D3DVS20_MIN_NUMTEMPS: ::DWORD = 12; +pub const D3DVS20_MAX_STATICFLOWCONTROLDEPTH: ::DWORD = 4; +pub const D3DVS20_MIN_STATICFLOWCONTROLDEPTH: ::DWORD = 1; +STRUCT!{struct D3DPSHADERCAPS2_0 { + Caps: ::DWORD, + DynamicFlowControlDepth: ::INT, + NumTemps: ::INT, + StaticFlowControlDepth: ::INT, + NumInstructionSlots: ::INT, +}} +pub const D3DPS20CAPS_ARBITRARYSWIZZLE: ::DWORD = 1 << 0; +pub const D3DPS20CAPS_GRADIENTINSTRUCTIONS: ::DWORD = 1 << 1; +pub const D3DPS20CAPS_PREDICATION: ::DWORD = 1 << 2; +pub const D3DPS20CAPS_NODEPENDENTREADLIMIT: ::DWORD = 1 << 3; +pub const D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT: ::DWORD = 1 << 4; +pub const D3DPS20_MAX_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 24; +pub const D3DPS20_MIN_DYNAMICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DPS20_MAX_NUMTEMPS: ::DWORD = 32; +pub const D3DPS20_MIN_NUMTEMPS: ::DWORD = 12; +pub const D3DPS20_MAX_STATICFLOWCONTROLDEPTH: ::DWORD = 4; +pub const D3DPS20_MIN_STATICFLOWCONTROLDEPTH: ::DWORD = 0; +pub const D3DPS20_MAX_NUMINSTRUCTIONSLOTS: ::DWORD = 512; +pub const D3DPS20_MIN_NUMINSTRUCTIONSLOTS: ::DWORD = 96; +pub const D3DMIN30SHADERINSTRUCTIONS: ::DWORD = 512; +pub const D3DMAX30SHADERINSTRUCTIONS: ::DWORD = 32768; +STRUCT!{struct D3DOVERLAYCAPS { + Caps: ::UINT, + MaxOverlayDisplayWidth: ::UINT, + MaxOverlayDisplayHeight: ::UINT, +}} +pub const D3DOVERLAYCAPS_FULLRANGERGB: ::DWORD = 0x00000001; +pub const D3DOVERLAYCAPS_LIMITEDRANGERGB: ::DWORD = 0x00000002; +pub const D3DOVERLAYCAPS_YCbCr_BT601: ::DWORD = 0x00000004; +pub const D3DOVERLAYCAPS_YCbCr_BT709: ::DWORD = 0x00000008; +pub const D3DOVERLAYCAPS_YCbCr_BT601_xvYCC: ::DWORD = 0x00000010; +pub const D3DOVERLAYCAPS_YCbCr_BT709_xvYCC: ::DWORD = 0x00000020; +pub const D3DOVERLAYCAPS_STRETCHX: ::DWORD = 0x00000040; +pub const D3DOVERLAYCAPS_STRETCHY: ::DWORD = 0x00000080; +STRUCT!{struct D3DCONTENTPROTECTIONCAPS { + Caps: ::DWORD, + KeyExchangeType: ::GUID, + BufferAlignmentStart: ::UINT, + BlockAlignmentSize: ::UINT, + ProtectedMemorySize: ::ULONGLONG, +}} +pub const D3DCPCAPS_SOFTWARE: ::DWORD = 0x00000001; +pub const D3DCPCAPS_HARDWARE: ::DWORD = 0x00000002; +pub const D3DCPCAPS_PROTECTIONALWAYSON: ::DWORD = 0x00000004; +pub const D3DCPCAPS_PARTIALDECRYPTION: ::DWORD = 0x00000008; +pub const D3DCPCAPS_CONTENTKEY: ::DWORD = 0x00000010; +pub const D3DCPCAPS_FRESHENSESSIONKEY: ::DWORD = 0x00000020; +pub const D3DCPCAPS_ENCRYPTEDREADBACK: ::DWORD = 0x00000040; +pub const D3DCPCAPS_ENCRYPTEDREADBACKKEY: ::DWORD = 0x00000080; +pub const D3DCPCAPS_SEQUENTIAL_CTR_IV: ::DWORD = 0x00000100; +pub const D3DCPCAPS_ENCRYPTSLICEDATAONLY: ::DWORD = 0x00000200; +STRUCT!{struct D3DCAPS9 { + DeviceType: ::D3DDEVTYPE, + AdapterOrdinal: ::UINT, + Caps: ::DWORD, + Caps2: ::DWORD, + Caps3: ::DWORD, + PresentationIntervals: ::DWORD, + CursorCaps: ::DWORD, + DevCaps: ::DWORD, + PrimitiveMiscCaps: ::DWORD, + RasterCaps: ::DWORD, + ZCmpCaps: ::DWORD, + SrcBlendCaps: ::DWORD, + DestBlendCaps: ::DWORD, + AlphaCmpCaps: ::DWORD, + ShadeCaps: ::DWORD, + TextureCaps: ::DWORD, + TextureFilterCaps: ::DWORD, + CubeTextureFilterCaps: ::DWORD, + VolumeTextureFilterCaps: ::DWORD, + TextureAddressCaps: ::DWORD, + VolumeTextureAddressCaps: ::DWORD, + LineCaps: ::DWORD, + MaxTextureWidth: ::DWORD, + MaxTextureHeight: ::DWORD, + MaxVolumeExtent: ::DWORD, + MaxTextureRepeat: ::DWORD, + MaxTextureAspectRatio: ::DWORD, + MaxAnisotropy: ::DWORD, + MaxVertexW: ::c_float, + GuardBandLeft: ::c_float, + GuardBandTop: ::c_float, + GuardBandRight: ::c_float, + GuardBandBottom: ::c_float, + ExtentsAdjust: ::c_float, + StencilCaps: ::DWORD, + FVFCaps: ::DWORD, + TextureOpCaps: ::DWORD, + MaxTextureBlendStages: ::DWORD, + MaxSimultaneousTextures: ::DWORD, + VertexProcessingCaps: ::DWORD, + MaxActiveLights: ::DWORD, + MaxUserClipPlanes: ::DWORD, + MaxVertexBlendMatrices: ::DWORD, + MaxVertexBlendMatrixIndex: ::DWORD, + MaxPointSize: ::c_float, + MaxPrimitiveCount: ::DWORD, + MaxVertexIndex: ::DWORD, + MaxStreams: ::DWORD, + MaxStreamStride: ::DWORD, + VertexShaderVersion: ::DWORD, + MaxVertexShaderConst: ::DWORD, + PixelShaderVersion: ::DWORD, + PixelShader1xMaxValue: ::c_float, + DevCaps2: ::DWORD, + MaxNpatchTessellationLevel: ::c_float, + Reserved5: ::DWORD, + MasterAdapterOrdinal: ::UINT, + AdapterOrdinalInGroup: ::UINT, + NumberOfAdaptersInGroup: ::UINT, + DeclTypes: ::DWORD, + NumSimultaneousRTs: ::DWORD, + StretchRectFilterCaps: ::DWORD, + VS20Caps: ::D3DVSHADERCAPS2_0, + PS20Caps: ::D3DPSHADERCAPS2_0, + VertexTextureFilterCaps: ::DWORD, + MaxVShaderInstructionsExecuted: ::DWORD, + MaxPShaderInstructionsExecuted: ::DWORD, + MaxVertexShader30InstructionSlots: ::DWORD, + MaxPixelShader30InstructionSlots: ::DWORD, +}} +pub const D3DCAPS_OVERLAY: ::DWORD = 0x00000800; +pub const D3DCAPS_READ_SCANLINE: ::DWORD = 0x00020000; +pub const D3DCAPS2_FULLSCREENGAMMA: ::DWORD = 0x00020000; +pub const D3DCAPS2_CANCALIBRATEGAMMA: ::DWORD = 0x00100000; +pub const D3DCAPS2_RESERVED: ::DWORD = 0x02000000; +pub const D3DCAPS2_CANMANAGERESOURCE: ::DWORD = 0x10000000; +pub const D3DCAPS2_DYNAMICTEXTURES: ::DWORD = 0x20000000; +pub const D3DCAPS2_CANAUTOGENMIPMAP: ::DWORD = 0x40000000; +pub const D3DCAPS2_CANSHARERESOURCE: ::DWORD = 0x80000000; +pub const D3DCAPS3_RESERVED: ::DWORD = 0x8000001f; +pub const D3DCAPS3_ALPHA_FULLSCREEN_FLIP_OR_DISCARD: ::DWORD = 0x00000020; +pub const D3DCAPS3_LINEAR_TO_SRGB_PRESENTATION: ::DWORD = 0x00000080; +pub const D3DCAPS3_COPY_TO_VIDMEM: ::DWORD = 0x00000100; +pub const D3DCAPS3_COPY_TO_SYSTEMMEM: ::DWORD = 0x00000200; +pub const D3DCAPS3_DXVAHD: ::DWORD = 0x00000400; +pub const D3DCAPS3_DXVAHD_LIMITED: ::DWORD = 0x00000800; +pub const D3DPRESENT_INTERVAL_DEFAULT: ::DWORD = 0x00000000; +pub const D3DPRESENT_INTERVAL_ONE: ::DWORD = 0x00000001; +pub const D3DPRESENT_INTERVAL_TWO: ::DWORD = 0x00000002; +pub const D3DPRESENT_INTERVAL_THREE: ::DWORD = 0x00000004; +pub const D3DPRESENT_INTERVAL_FOUR: ::DWORD = 0x00000008; +pub const D3DPRESENT_INTERVAL_IMMEDIATE: ::DWORD = 0x80000000; +pub const D3DCURSORCAPS_COLOR: ::DWORD = 0x00000001; +pub const D3DCURSORCAPS_LOWRES: ::DWORD = 0x00000002; +pub const D3DDEVCAPS_EXECUTESYSTEMMEMORY: ::DWORD = 0x00000010; +pub const D3DDEVCAPS_EXECUTEVIDEOMEMORY: ::DWORD = 0x00000020; +pub const D3DDEVCAPS_TLVERTEXSYSTEMMEMORY: ::DWORD = 0x00000040; +pub const D3DDEVCAPS_TLVERTEXVIDEOMEMORY: ::DWORD = 0x00000080; +pub const D3DDEVCAPS_TEXTURESYSTEMMEMORY: ::DWORD = 0x00000100; +pub const D3DDEVCAPS_TEXTUREVIDEOMEMORY: ::DWORD = 0x00000200; +pub const D3DDEVCAPS_DRAWPRIMTLVERTEX: ::DWORD = 0x00000400; +pub const D3DDEVCAPS_CANRENDERAFTERFLIP: ::DWORD = 0x00000800; +pub const D3DDEVCAPS_TEXTURENONLOCALVIDMEM: ::DWORD = 0x00001000; +pub const D3DDEVCAPS_DRAWPRIMITIVES2: ::DWORD = 0x00002000; +pub const D3DDEVCAPS_SEPARATETEXTUREMEMORIES: ::DWORD = 0x00004000; +pub const D3DDEVCAPS_DRAWPRIMITIVES2EX: ::DWORD = 0x00008000; +pub const D3DDEVCAPS_HWTRANSFORMANDLIGHT: ::DWORD = 0x00010000; +pub const D3DDEVCAPS_CANBLTSYSTONONLOCAL: ::DWORD = 0x00020000; +pub const D3DDEVCAPS_HWRASTERIZATION: ::DWORD = 0x00080000; +pub const D3DDEVCAPS_PUREDEVICE: ::DWORD = 0x00100000; +pub const D3DDEVCAPS_QUINTICRTPATCHES: ::DWORD = 0x00200000; +pub const D3DDEVCAPS_RTPATCHES: ::DWORD = 0x00400000; +pub const D3DDEVCAPS_RTPATCHHANDLEZERO: ::DWORD = 0x00800000; +pub const D3DDEVCAPS_NPATCHES: ::DWORD = 0x01000000; +pub const D3DPMISCCAPS_MASKZ: ::DWORD = 0x00000002; +pub const D3DPMISCCAPS_CULLNONE: ::DWORD = 0x00000010; +pub const D3DPMISCCAPS_CULLCW: ::DWORD = 0x00000020; +pub const D3DPMISCCAPS_CULLCCW: ::DWORD = 0x00000040; +pub const D3DPMISCCAPS_COLORWRITEENABLE: ::DWORD = 0x00000080; +pub const D3DPMISCCAPS_CLIPPLANESCALEDPOINTS: ::DWORD = 0x00000100; +pub const D3DPMISCCAPS_CLIPTLVERTS: ::DWORD = 0x00000200; +pub const D3DPMISCCAPS_TSSARGTEMP: ::DWORD = 0x00000400; +pub const D3DPMISCCAPS_BLENDOP: ::DWORD = 0x00000800; +pub const D3DPMISCCAPS_NULLREFERENCE: ::DWORD = 0x00001000; +pub const D3DPMISCCAPS_INDEPENDENTWRITEMASKS: ::DWORD = 0x00004000; +pub const D3DPMISCCAPS_PERSTAGECONSTANT: ::DWORD = 0x00008000; +pub const D3DPMISCCAPS_FOGANDSPECULARALPHA: ::DWORD = 0x00010000; +pub const D3DPMISCCAPS_SEPARATEALPHABLEND: ::DWORD = 0x00020000; +pub const D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS: ::DWORD = 0x00040000; +pub const D3DPMISCCAPS_MRTPOSTPIXELSHADERBLENDING: ::DWORD = 0x00080000; +pub const D3DPMISCCAPS_FOGVERTEXCLAMPED: ::DWORD = 0x00100000; +pub const D3DPMISCCAPS_POSTBLENDSRGBCONVERT: ::DWORD = 0x00200000; +pub const D3DLINECAPS_TEXTURE: ::DWORD = 0x00000001; +pub const D3DLINECAPS_ZTEST: ::DWORD = 0x00000002; +pub const D3DLINECAPS_BLEND: ::DWORD = 0x00000004; +pub const D3DLINECAPS_ALPHACMP: ::DWORD = 0x00000008; +pub const D3DLINECAPS_FOG: ::DWORD = 0x00000010; +pub const D3DLINECAPS_ANTIALIAS: ::DWORD = 0x00000020; +pub const D3DPRASTERCAPS_DITHER: ::DWORD = 0x00000001; +pub const D3DPRASTERCAPS_ZTEST: ::DWORD = 0x00000010; +pub const D3DPRASTERCAPS_FOGVERTEX: ::DWORD = 0x00000080; +pub const D3DPRASTERCAPS_FOGTABLE: ::DWORD = 0x00000100; +pub const D3DPRASTERCAPS_MIPMAPLODBIAS: ::DWORD = 0x00002000; +pub const D3DPRASTERCAPS_ZBUFFERLESSHSR: ::DWORD = 0x00008000; +pub const D3DPRASTERCAPS_FOGRANGE: ::DWORD = 0x00010000; +pub const D3DPRASTERCAPS_ANISOTROPY: ::DWORD = 0x00020000; +pub const D3DPRASTERCAPS_WBUFFER: ::DWORD = 0x00040000; +pub const D3DPRASTERCAPS_WFOG: ::DWORD = 0x00100000; +pub const D3DPRASTERCAPS_ZFOG: ::DWORD = 0x00200000; +pub const D3DPRASTERCAPS_COLORPERSPECTIVE: ::DWORD = 0x00400000; +pub const D3DPRASTERCAPS_SCISSORTEST: ::DWORD = 0x01000000; +pub const D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS: ::DWORD = 0x02000000; +pub const D3DPRASTERCAPS_DEPTHBIAS: ::DWORD = 0x04000000; +pub const D3DPRASTERCAPS_MULTISAMPLE_TOGGLE: ::DWORD = 0x08000000; +pub const D3DPCMPCAPS_NEVER: ::DWORD = 0x00000001; +pub const D3DPCMPCAPS_LESS: ::DWORD = 0x00000002; +pub const D3DPCMPCAPS_EQUAL: ::DWORD = 0x00000004; +pub const D3DPCMPCAPS_LESSEQUAL: ::DWORD = 0x00000008; +pub const D3DPCMPCAPS_GREATER: ::DWORD = 0x00000010; +pub const D3DPCMPCAPS_NOTEQUAL: ::DWORD = 0x00000020; +pub const D3DPCMPCAPS_GREATEREQUAL: ::DWORD = 0x00000040; +pub const D3DPCMPCAPS_ALWAYS: ::DWORD = 0x00000080; +pub const D3DPBLENDCAPS_ZERO: ::DWORD = 0x00000001; +pub const D3DPBLENDCAPS_ONE: ::DWORD = 0x00000002; +pub const D3DPBLENDCAPS_SRCCOLOR: ::DWORD = 0x00000004; +pub const D3DPBLENDCAPS_INVSRCCOLOR: ::DWORD = 0x00000008; +pub const D3DPBLENDCAPS_SRCALPHA: ::DWORD = 0x00000010; +pub const D3DPBLENDCAPS_INVSRCALPHA: ::DWORD = 0x00000020; +pub const D3DPBLENDCAPS_DESTALPHA: ::DWORD = 0x00000040; +pub const D3DPBLENDCAPS_INVDESTALPHA: ::DWORD = 0x00000080; +pub const D3DPBLENDCAPS_DESTCOLOR: ::DWORD = 0x00000100; +pub const D3DPBLENDCAPS_INVDESTCOLOR: ::DWORD = 0x00000200; +pub const D3DPBLENDCAPS_SRCALPHASAT: ::DWORD = 0x00000400; +pub const D3DPBLENDCAPS_BOTHSRCALPHA: ::DWORD = 0x00000800; +pub const D3DPBLENDCAPS_BOTHINVSRCALPHA: ::DWORD = 0x00001000; +pub const D3DPBLENDCAPS_BLENDFACTOR: ::DWORD = 0x00002000; +pub const D3DPBLENDCAPS_SRCCOLOR2: ::DWORD = 0x00004000; +pub const D3DPBLENDCAPS_INVSRCCOLOR2: ::DWORD = 0x00008000; +pub const D3DPSHADECAPS_COLORGOURAUDRGB: ::DWORD = 0x00000008; +pub const D3DPSHADECAPS_SPECULARGOURAUDRGB: ::DWORD = 0x00000200; +pub const D3DPSHADECAPS_ALPHAGOURAUDBLEND: ::DWORD = 0x00004000; +pub const D3DPSHADECAPS_FOGGOURAUD: ::DWORD = 0x00080000; +pub const D3DPTEXTURECAPS_PERSPECTIVE: ::DWORD = 0x00000001; +pub const D3DPTEXTURECAPS_POW2: ::DWORD = 0x00000002; +pub const D3DPTEXTURECAPS_ALPHA: ::DWORD = 0x00000004; +pub const D3DPTEXTURECAPS_SQUAREONLY: ::DWORD = 0x00000020; +pub const D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE: ::DWORD = 0x00000040; +pub const D3DPTEXTURECAPS_ALPHAPALETTE: ::DWORD = 0x00000080; +pub const D3DPTEXTURECAPS_NONPOW2CONDITIONAL: ::DWORD = 0x00000100; +pub const D3DPTEXTURECAPS_PROJECTED: ::DWORD = 0x00000400; +pub const D3DPTEXTURECAPS_CUBEMAP: ::DWORD = 0x00000800; +pub const D3DPTEXTURECAPS_VOLUMEMAP: ::DWORD = 0x00002000; +pub const D3DPTEXTURECAPS_MIPMAP: ::DWORD = 0x00004000; +pub const D3DPTEXTURECAPS_MIPVOLUMEMAP: ::DWORD = 0x00008000; +pub const D3DPTEXTURECAPS_MIPCUBEMAP: ::DWORD = 0x00010000; +pub const D3DPTEXTURECAPS_CUBEMAP_POW2: ::DWORD = 0x00020000; +pub const D3DPTEXTURECAPS_VOLUMEMAP_POW2: ::DWORD = 0x00040000; +pub const D3DPTEXTURECAPS_NOPROJECTEDBUMPENV: ::DWORD = 0x00200000; +pub const D3DPTFILTERCAPS_MINFPOINT: ::DWORD = 0x00000100; +pub const D3DPTFILTERCAPS_MINFLINEAR: ::DWORD = 0x00000200; +pub const D3DPTFILTERCAPS_MINFANISOTROPIC: ::DWORD = 0x00000400; +pub const D3DPTFILTERCAPS_MINFPYRAMIDALQUAD: ::DWORD = 0x00000800; +pub const D3DPTFILTERCAPS_MINFGAUSSIANQUAD: ::DWORD = 0x00001000; +pub const D3DPTFILTERCAPS_MIPFPOINT: ::DWORD = 0x00010000; +pub const D3DPTFILTERCAPS_MIPFLINEAR: ::DWORD = 0x00020000; +pub const D3DPTFILTERCAPS_CONVOLUTIONMONO: ::DWORD = 0x00040000; +pub const D3DPTFILTERCAPS_MAGFPOINT: ::DWORD = 0x01000000; +pub const D3DPTFILTERCAPS_MAGFLINEAR: ::DWORD = 0x02000000; +pub const D3DPTFILTERCAPS_MAGFANISOTROPIC: ::DWORD = 0x04000000; +pub const D3DPTFILTERCAPS_MAGFPYRAMIDALQUAD: ::DWORD = 0x08000000; +pub const D3DPTFILTERCAPS_MAGFGAUSSIANQUAD: ::DWORD = 0x10000000; +pub const D3DPTADDRESSCAPS_WRAP: ::DWORD = 0x00000001; +pub const D3DPTADDRESSCAPS_MIRROR: ::DWORD = 0x00000002; +pub const D3DPTADDRESSCAPS_CLAMP: ::DWORD = 0x00000004; +pub const D3DPTADDRESSCAPS_BORDER: ::DWORD = 0x00000008; +pub const D3DPTADDRESSCAPS_INDEPENDENTUV: ::DWORD = 0x00000010; +pub const D3DPTADDRESSCAPS_MIRRORONCE: ::DWORD = 0x00000020; +pub const D3DSTENCILCAPS_KEEP: ::DWORD = 0x00000001; +pub const D3DSTENCILCAPS_ZERO: ::DWORD = 0x00000002; +pub const D3DSTENCILCAPS_REPLACE: ::DWORD = 0x00000004; +pub const D3DSTENCILCAPS_INCRSAT: ::DWORD = 0x00000008; +pub const D3DSTENCILCAPS_DECRSAT: ::DWORD = 0x00000010; +pub const D3DSTENCILCAPS_INVERT: ::DWORD = 0x00000020; +pub const D3DSTENCILCAPS_INCR: ::DWORD = 0x00000040; +pub const D3DSTENCILCAPS_DECR: ::DWORD = 0x00000080; +pub const D3DSTENCILCAPS_TWOSIDED: ::DWORD = 0x00000100; +pub const D3DTEXOPCAPS_DISABLE: ::DWORD = 0x00000001; +pub const D3DTEXOPCAPS_SELECTARG1: ::DWORD = 0x00000002; +pub const D3DTEXOPCAPS_SELECTARG2: ::DWORD = 0x00000004; +pub const D3DTEXOPCAPS_MODULATE: ::DWORD = 0x00000008; +pub const D3DTEXOPCAPS_MODULATE2X: ::DWORD = 0x00000010; +pub const D3DTEXOPCAPS_MODULATE4X: ::DWORD = 0x00000020; +pub const D3DTEXOPCAPS_ADD: ::DWORD = 0x00000040; +pub const D3DTEXOPCAPS_ADDSIGNED: ::DWORD = 0x00000080; +pub const D3DTEXOPCAPS_ADDSIGNED2X: ::DWORD = 0x00000100; +pub const D3DTEXOPCAPS_SUBTRACT: ::DWORD = 0x00000200; +pub const D3DTEXOPCAPS_ADDSMOOTH: ::DWORD = 0x00000400; +pub const D3DTEXOPCAPS_BLENDDIFFUSEALPHA: ::DWORD = 0x00000800; +pub const D3DTEXOPCAPS_BLENDTEXTUREALPHA: ::DWORD = 0x00001000; +pub const D3DTEXOPCAPS_BLENDFACTORALPHA: ::DWORD = 0x00002000; +pub const D3DTEXOPCAPS_BLENDTEXTUREALPHAPM: ::DWORD = 0x00004000; +pub const D3DTEXOPCAPS_BLENDCURRENTALPHA: ::DWORD = 0x00008000; +pub const D3DTEXOPCAPS_PREMODULATE: ::DWORD = 0x00010000; +pub const D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR: ::DWORD = 0x00020000; +pub const D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA: ::DWORD = 0x00040000; +pub const D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR: ::DWORD = 0x00080000; +pub const D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA: ::DWORD = 0x00100000; +pub const D3DTEXOPCAPS_BUMPENVMAP: ::DWORD = 0x00200000; +pub const D3DTEXOPCAPS_BUMPENVMAPLUMINANCE: ::DWORD = 0x00400000; +pub const D3DTEXOPCAPS_DOTPRODUCT3: ::DWORD = 0x00800000; +pub const D3DTEXOPCAPS_MULTIPLYADD: ::DWORD = 0x01000000; +pub const D3DTEXOPCAPS_LERP: ::DWORD = 0x02000000; +pub const D3DFVFCAPS_TEXCOORDCOUNTMASK: ::DWORD = 0x0000ffff; +pub const D3DFVFCAPS_DONOTSTRIPELEMENTS: ::DWORD = 0x00080000; +pub const D3DFVFCAPS_PSIZE: ::DWORD = 0x00100000; +pub const D3DVTXPCAPS_TEXGEN: ::DWORD = 0x00000001; +pub const D3DVTXPCAPS_MATERIALSOURCE7: ::DWORD = 0x00000002; +pub const D3DVTXPCAPS_DIRECTIONALLIGHTS: ::DWORD = 0x00000008; +pub const D3DVTXPCAPS_POSITIONALLIGHTS: ::DWORD = 0x00000010; +pub const D3DVTXPCAPS_LOCALVIEWER: ::DWORD = 0x00000020; +pub const D3DVTXPCAPS_TWEENING: ::DWORD = 0x00000040; +pub const D3DVTXPCAPS_TEXGEN_SPHEREMAP: ::DWORD = 0x00000100; +pub const D3DVTXPCAPS_NO_TEXGEN_NONLOCALVIEWER: ::DWORD = 0x00000200; +pub const D3DDEVCAPS2_STREAMOFFSET: ::DWORD = 0x00000001; +pub const D3DDEVCAPS2_DMAPNPATCH: ::DWORD = 0x00000002; +pub const D3DDEVCAPS2_ADAPTIVETESSRTPATCH: ::DWORD = 0x00000004; +pub const D3DDEVCAPS2_ADAPTIVETESSNPATCH: ::DWORD = 0x00000008; +pub const D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES: ::DWORD = 0x00000010; +pub const D3DDEVCAPS2_PRESAMPLEDDMAPNPATCH: ::DWORD = 0x00000020; +pub const D3DDEVCAPS2_VERTEXELEMENTSCANSHARESTREAMOFFSET: ::DWORD = 0x00000040; +pub const D3DDTCAPS_UBYTE4: ::DWORD = 0x00000001; +pub const D3DDTCAPS_UBYTE4N: ::DWORD = 0x00000002; +pub const D3DDTCAPS_SHORT2N: ::DWORD = 0x00000004; +pub const D3DDTCAPS_SHORT4N: ::DWORD = 0x00000008; +pub const D3DDTCAPS_USHORT2N: ::DWORD = 0x00000010; +pub const D3DDTCAPS_USHORT4N: ::DWORD = 0x00000020; +pub const D3DDTCAPS_UDEC3: ::DWORD = 0x00000040; +pub const D3DDTCAPS_DEC3N: ::DWORD = 0x00000080; +pub const D3DDTCAPS_FLOAT16_2: ::DWORD = 0x00000100; +pub const D3DDTCAPS_FLOAT16_4: ::DWORD = 0x00000200; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3d9types.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9types.rs new file mode 100644 index 0000000..28d0bed --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3d9types.rs @@ -0,0 +1,1397 @@ +// Copyright © 2015, Corey Richardson +// Licensed under the MIT License +//! Direct3D capabilities include file +pub type D3DCOLOR = ::DWORD; +STRUCT!{struct D3DVECTOR { + x: ::c_float, + y: ::c_float, + z: ::c_float, +}} +STRUCT!{struct D3DCOLORVALUE { + r: ::c_float, + g: ::c_float, + b: ::c_float, + a: ::c_float, +}} +STRUCT!{struct D3DRECT { + x1: ::LONG, + y1: ::LONG, + x2: ::LONG, + y2: ::LONG, +}} +STRUCT!{struct D3DMATRIX { + m: [[::c_float; 4]; 4], +}} +STRUCT!{struct D3DVIEWPORT9 { + X: ::DWORD, + Y: ::DWORD, + Width: ::DWORD, + Height: ::DWORD, + MinZ: ::c_float, + MaxZ: ::c_float, +}} +pub const D3DMAXUSERCLIPPLANES: ::DWORD = 32; +pub const D3DCLIPPLANE0: ::DWORD = (1 << 0); +pub const D3DCLIPPLANE1: ::DWORD = (1 << 1); +pub const D3DCLIPPLANE2: ::DWORD = (1 << 2); +pub const D3DCLIPPLANE3: ::DWORD = (1 << 3); +pub const D3DCLIPPLANE4: ::DWORD = (1 << 4); +pub const D3DCLIPPLANE5: ::DWORD = (1 << 5); +pub const D3DCS_LEFT: ::DWORD = 0x00000001; +pub const D3DCS_RIGHT: ::DWORD = 0x00000002; +pub const D3DCS_TOP: ::DWORD = 0x00000004; +pub const D3DCS_BOTTOM: ::DWORD = 0x00000008; +pub const D3DCS_FRONT: ::DWORD = 0x00000010; +pub const D3DCS_BACK: ::DWORD = 0x00000020; +pub const D3DCS_PLANE0: ::DWORD = 0x00000040; +pub const D3DCS_PLANE1: ::DWORD = 0x00000080; +pub const D3DCS_PLANE2: ::DWORD = 0x00000100; +pub const D3DCS_PLANE3: ::DWORD = 0x00000200; +pub const D3DCS_PLANE4: ::DWORD = 0x00000400; +pub const D3DCS_PLANE5: ::DWORD = 0x00000800; +pub const D3DCS_ALL: ::DWORD = D3DCS_LEFT | D3DCS_RIGHT | D3DCS_TOP | D3DCS_BOTTOM | D3DCS_FRONT + | D3DCS_BACK | D3DCS_PLANE0 | D3DCS_PLANE1 | D3DCS_PLANE2 | D3DCS_PLANE3 | D3DCS_PLANE4 + | D3DCS_PLANE5; +STRUCT!{struct D3DCLIPSTATUS9 { + ClipUnion: ::DWORD, + ClipIntersection: ::DWORD, +}} +STRUCT!{struct D3DMATERIAL9 { + Diffuse: D3DCOLORVALUE, + Ambient: D3DCOLORVALUE, + Specular: D3DCOLORVALUE, + Emissive: D3DCOLORVALUE, + Power: ::c_float, +}} +ENUM!{enum D3DLIGHTTYPE { + D3DLIGHT_POINT = 1, + D3DLIGHT_SPOT = 2, + D3DLIGHT_DIRECTIONAL = 3, +}} +STRUCT!{struct D3DLIGHT9 { + Type: D3DLIGHTTYPE, + Diffuse: D3DCOLORVALUE, + Specular: D3DCOLORVALUE, + Ambient: D3DCOLORVALUE, + Position: D3DVECTOR, + Direction: D3DVECTOR, + Range: ::c_float, + Falloff: ::c_float, + Attenuation0: ::c_float, + Attenuation1: ::c_float, + Attenuation2: ::c_float, + Theta: ::c_float, + Phi: ::c_float, +}} +pub const D3DCLEAR_TARGET: ::DWORD = 0x1; +pub const D3DCLEAR_ZBUFFER: ::DWORD = 0x2; +pub const D3DCLEAR_STENCIL: ::DWORD = 0x4; +ENUM!{enum D3DSHADEMODE { + D3DSHADE_FLAT = 1, + D3DSHADE_GOURAUD = 2, + D3DSHADE_PHONG = 3, +}} +ENUM!{enum D3DFILLMODE { + D3DFILL_POINT = 1, + D3DFILL_WIREFRAME = 2, + D3DFILL_SOLID = 3, +}} +ENUM!{enum D3DBLEND { + D3DBLEND_ZERO = 1, + D3DBLEND_ONE = 2, + D3DBLEND_SRCCOLOR = 3, + D3DBLEND_INVSRCCOLOR = 4, + D3DBLEND_SRCALPHA = 5, + D3DBLEND_INVSRCALPHA = 6, + D3DBLEND_DESTALPHA = 7, + D3DBLEND_INVDESTALPHA = 8, + D3DBLEND_DESTCOLOR = 9, + D3DBLEND_INVDESTCOLOR = 10, + D3DBLEND_SRCALPHASAT = 11, + D3DBLEND_BOTHSRCALPHA = 12, + D3DBLEND_BOTHINVSRCALPHA = 13, + D3DBLEND_BLENDFACTOR = 14, + D3DBLEND_INVBLENDFACTOR = 15, +}} +ENUM!{enum D3DBLENDOP { + D3DBLENDOP_ADD = 1, + D3DBLENDOP_SUBTRACT = 2, + D3DBLENDOP_REVSUBTRACT = 3, + D3DBLENDOP_MIN = 4, + D3DBLENDOP_MAX = 5, +}} +ENUM!{enum D3DTEXTUREADDRESS { + D3DTADDRESS_WRAP = 1, + D3DTADDRESS_MIRROR = 2, + D3DTADDRESS_CLAMP = 3, + D3DTADDRESS_BORDER = 4, + D3DTADDRESS_MIRRORONCE = 5, +}} +ENUM!{enum D3DCULL { + D3DCULL_NONE = 1, + D3DCULL_CW = 2, + D3DCULL_CCW = 3, +}} +ENUM!{enum D3DCMPFUNC { + D3DCMP_NEVER = 1, + D3DCMP_LESS = 2, + D3DCMP_EQUAL = 3, + D3DCMP_LESSEQUAL = 4, + D3DCMP_GREATER = 5, + D3DCMP_NOTEQUAL = 6, + D3DCMP_GREATEREQUAL = 7, + D3DCMP_ALWAYS = 8, +}} +ENUM!{enum D3DSTENCILOP { + D3DSTENCILOP_KEEP = 1, + D3DSTENCILOP_ZERO = 2, + D3DSTENCILOP_REPLACE = 3, + D3DSTENCILOP_INCRSAT = 4, + D3DSTENCILOP_DECRSAT = 5, + D3DSTENCILOP_INVERT = 6, + D3DSTENCILOP_INCR = 7, + D3DSTENCILOP_DECR = 8, +}} +ENUM!{enum D3DFOGMODE { + D3DFOG_NONE = 0, + D3DFOG_EXP = 1, + D3DFOG_EXP2 = 2, + D3DFOG_LINEAR = 3, +}} +ENUM!{enum D3DZBUFFERTYPE { + D3DZB_FALSE = 0, + D3DZB_TRUE = 1, + D3DZB_USEW = 2, +}} +ENUM!{enum D3DPRIMITIVETYPE { + D3DPT_POINTLIST = 1, + D3DPT_LINELIST = 2, + D3DPT_LINESTRIP = 3, + D3DPT_TRIANGLELIST = 4, + D3DPT_TRIANGLESTRIP = 5, + D3DPT_TRIANGLEFAN = 6, +}} +ENUM!{enum D3DTRANSFORMSTATETYPE { + D3DTS_VIEW = 2, + D3DTS_PROJECTION = 3, + D3DTS_TEXTURE0 = 16, + D3DTS_TEXTURE1 = 17, + D3DTS_TEXTURE2 = 18, + D3DTS_TEXTURE3 = 19, + D3DTS_TEXTURE4 = 20, + D3DTS_TEXTURE5 = 21, + D3DTS_TEXTURE6 = 22, + D3DTS_TEXTURE7 = 23, +}} +ENUM!{enum D3DRENDERSTATETYPE { + D3DRS_ZENABLE = 7, + D3DRS_FILLMODE = 8, + D3DRS_SHADEMODE = 9, + D3DRS_ZWRITEENABLE = 14, + D3DRS_ALPHATESTENABLE = 15, + D3DRS_LASTPIXEL = 16, + D3DRS_SRCBLEND = 19, + D3DRS_DESTBLEND = 20, + D3DRS_CULLMODE = 22, + D3DRS_ZFUNC = 23, + D3DRS_ALPHAREF = 24, + D3DRS_ALPHAFUNC = 25, + D3DRS_DITHERENABLE = 26, + D3DRS_ALPHABLENDENABLE = 27, + D3DRS_FOGENABLE = 28, + D3DRS_SPECULARENABLE = 29, + D3DRS_FOGCOLOR = 34, + D3DRS_FOGTABLEMODE = 35, + D3DRS_FOGSTART = 36, + D3DRS_FOGEND = 37, + D3DRS_FOGDENSITY = 38, + D3DRS_RANGEFOGENABLE = 48, + D3DRS_STENCILENABLE = 52, + D3DRS_STENCILFAIL = 53, + D3DRS_STENCILZFAIL = 54, + D3DRS_STENCILPASS = 55, + D3DRS_STENCILFUNC = 56, + D3DRS_STENCILREF = 57, + D3DRS_STENCILMASK = 58, + D3DRS_STENCILWRITEMASK = 59, + D3DRS_TEXTUREFACTOR = 60, + D3DRS_WRAP0 = 128, + D3DRS_WRAP1 = 129, + D3DRS_WRAP2 = 130, + D3DRS_WRAP3 = 131, + D3DRS_WRAP4 = 132, + D3DRS_WRAP5 = 133, + D3DRS_WRAP6 = 134, + D3DRS_WRAP7 = 135, + D3DRS_CLIPPING = 136, + D3DRS_LIGHTING = 137, + D3DRS_AMBIENT = 139, + D3DRS_FOGVERTEXMODE = 140, + D3DRS_COLORVERTEX = 141, + D3DRS_LOCALVIEWER = 142, + D3DRS_NORMALIZENORMALS = 143, + D3DRS_DIFFUSEMATERIALSOURCE = 145, + D3DRS_SPECULARMATERIALSOURCE = 146, + D3DRS_AMBIENTMATERIALSOURCE = 147, + D3DRS_EMISSIVEMATERIALSOURCE = 148, + D3DRS_VERTEXBLEND = 151, + D3DRS_CLIPPLANEENABLE = 152, + D3DRS_POINTSIZE = 154, + D3DRS_POINTSIZE_MIN = 155, + D3DRS_POINTSPRITEENABLE = 156, + D3DRS_POINTSCALEENABLE = 157, + D3DRS_POINTSCALE_A = 158, + D3DRS_POINTSCALE_B = 159, + D3DRS_POINTSCALE_C = 160, + D3DRS_MULTISAMPLEANTIALIAS = 161, + D3DRS_MULTISAMPLEMASK = 162, + D3DRS_PATCHEDGESTYLE = 163, + D3DRS_DEBUGMONITORTOKEN = 165, + D3DRS_POINTSIZE_MAX = 166, + D3DRS_INDEXEDVERTEXBLENDENABLE = 167, + D3DRS_COLORWRITEENABLE = 168, + D3DRS_TWEENFACTOR = 170, + D3DRS_BLENDOP = 171, + D3DRS_POSITIONDEGREE = 172, + D3DRS_NORMALDEGREE = 173, + D3DRS_SCISSORTESTENABLE = 174, + D3DRS_SLOPESCALEDEPTHBIAS = 175, + D3DRS_ANTIALIASEDLINEENABLE = 176, + D3DRS_MINTESSELLATIONLEVEL = 178, + D3DRS_MAXTESSELLATIONLEVEL = 179, + D3DRS_ADAPTIVETESS_X = 180, + D3DRS_ADAPTIVETESS_Y = 181, + D3DRS_ADAPTIVETESS_Z = 182, + D3DRS_ADAPTIVETESS_W = 183, + D3DRS_ENABLEADAPTIVETESSELLATION = 184, + D3DRS_TWOSIDEDSTENCILMODE = 185, + D3DRS_CCW_STENCILFAIL = 186, + D3DRS_CCW_STENCILZFAIL = 187, + D3DRS_CCW_STENCILPASS = 188, + D3DRS_CCW_STENCILFUNC = 189, + D3DRS_COLORWRITEENABLE1 = 190, + D3DRS_COLORWRITEENABLE2 = 191, + D3DRS_COLORWRITEENABLE3 = 192, + D3DRS_BLENDFACTOR = 193, + D3DRS_SRGBWRITEENABLE = 194, + D3DRS_DEPTHBIAS = 195, + D3DRS_WRAP8 = 198, + D3DRS_WRAP9 = 199, + D3DRS_WRAP10 = 200, + D3DRS_WRAP11 = 201, + D3DRS_WRAP12 = 202, + D3DRS_WRAP13 = 203, + D3DRS_WRAP14 = 204, + D3DRS_WRAP15 = 205, + D3DRS_SEPARATEALPHABLENDENABLE = 206, + D3DRS_SRCBLENDALPHA = 207, + D3DRS_DESTBLENDALPHA = 208, + D3DRS_BLENDOPALPHA = 209, +}} +pub const D3D_MAX_SIMULTANEOUS_RENDERTARGETS: ::DWORD = 4; +ENUM!{enum D3DMATERIALCOLORSOURCE { + D3DMCS_MATERIAL = 0, + D3DMCS_COLOR1 = 1, + D3DMCS_COLOR2 = 2, +}} +pub const D3DRENDERSTATE_WRAPBIAS: ::DWORD = 128; +pub const D3DWRAP_U: ::DWORD = 0x00000001; +pub const D3DWRAP_V: ::DWORD = 0x00000002; +pub const D3DWRAP_W: ::DWORD = 0x00000004; +pub const D3DWRAPCOORD_0: ::DWORD = 0x00000001; +pub const D3DWRAPCOORD_1: ::DWORD = 0x00000002; +pub const D3DWRAPCOORD_2: ::DWORD = 0x00000004; +pub const D3DWRAPCOORD_3: ::DWORD = 0x00000008; +pub const D3DCOLORWRITEENABLE_RED: ::DWORD = 1 << 0; +pub const D3DCOLORWRITEENABLE_GREEN: ::DWORD = 1 << 1; +pub const D3DCOLORWRITEENABLE_BLUE: ::DWORD = 1 << 2; +pub const D3DCOLORWRITEENABLE_ALPHA: ::DWORD = 1 << 3; +ENUM!{enum D3DTEXTURESTAGESTATETYPE { + D3DTSS_COLOROP = 1, + D3DTSS_COLORARG1 = 2, + D3DTSS_COLORARG2 = 3, + D3DTSS_ALPHAOP = 4, + D3DTSS_ALPHAARG1 = 5, + D3DTSS_ALPHAARG2 = 6, + D3DTSS_BUMPENVMAT00 = 7, + D3DTSS_BUMPENVMAT01 = 8, + D3DTSS_BUMPENVMAT10 = 9, + D3DTSS_BUMPENVMAT11 = 10, + D3DTSS_TEXCOORDINDEX = 11, + D3DTSS_BUMPENVLSCALE = 22, + D3DTSS_BUMPENVLOFFSET = 23, + D3DTSS_TEXTURETRANSFORMFLAGS = 24, + D3DTSS_COLORARG0 = 26, + D3DTSS_ALPHAARG0 = 27, + D3DTSS_RESULTARG = 28, + D3DTSS_CONSTANT = 32, +}} +ENUM!{enum D3DSAMPLERSTATETYPE { + D3DSAMP_ADDRESSU = 1, + D3DSAMP_ADDRESSV = 2, + D3DSAMP_ADDRESSW = 3, + D3DSAMP_BORDERCOLOR = 4, + D3DSAMP_MAGFILTER = 5, + D3DSAMP_MINFILTER = 6, + D3DSAMP_MIPFILTER = 7, + D3DSAMP_MIPMAPLODBIAS = 8, + D3DSAMP_MAXMIPLEVEL = 9, + D3DSAMP_MAXANISOTROPY = 10, + D3DSAMP_SRGBTEXTURE = 11, + D3DSAMP_ELEMENTINDEX = 12, + D3DSAMP_DMAPOFFSET = 13, +}} +pub const D3DDMAPSAMPLER: ::DWORD = 256; +pub const D3DVERTEXTEXTURESAMPLER0: ::DWORD = D3DDMAPSAMPLER + 1; +pub const D3DVERTEXTEXTURESAMPLER1: ::DWORD = D3DDMAPSAMPLER + 2; +pub const D3DVERTEXTEXTURESAMPLER2: ::DWORD = D3DDMAPSAMPLER + 3; +pub const D3DVERTEXTEXTURESAMPLER3: ::DWORD = D3DDMAPSAMPLER + 4; +pub const D3DTSS_TCI_PASSTHRU: ::DWORD = 0x00000000; +pub const D3DTSS_TCI_CAMERASPACENORMAL: ::DWORD = 0x00010000; +pub const D3DTSS_TCI_CAMERASPACEPOSITION: ::DWORD = 0x00020000; +pub const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR: ::DWORD = 0x00030000; +pub const D3DTSS_TCI_SPHEREMAP: ::DWORD = 0x00040000; +ENUM!{enum D3DTEXTUREOP { + D3DTOP_DISABLE = 1, + D3DTOP_SELECTARG1 = 2, + D3DTOP_SELECTARG2 = 3, + D3DTOP_MODULATE = 4, + D3DTOP_MODULATE2X = 5, + D3DTOP_MODULATE4X = 6, + D3DTOP_ADD = 7, + D3DTOP_ADDSIGNED = 8, + D3DTOP_ADDSIGNED2X = 9, + D3DTOP_SUBTRACT = 10, + D3DTOP_ADDSMOOTH = 11, + D3DTOP_BLENDDIFFUSEALPHA = 12, + D3DTOP_BLENDTEXTUREALPHA = 13, + D3DTOP_BLENDFACTORALPHA = 14, + D3DTOP_BLENDTEXTUREALPHAPM = 15, + D3DTOP_BLENDCURRENTALPHA = 16, + D3DTOP_PREMODULATE = 17, + D3DTOP_MODULATEALPHA_ADDCOLOR = 18, + D3DTOP_MODULATECOLOR_ADDALPHA = 19, + D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20, + D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21, + D3DTOP_BUMPENVMAP = 22, + D3DTOP_BUMPENVMAPLUMINANCE = 23, + D3DTOP_DOTPRODUCT3 = 24, + D3DTOP_MULTIPLYADD = 25, + D3DTOP_LERP = 26, +}} +pub const D3DTA_SELECTMASK: ::DWORD = 0x0000000f; +pub const D3DTA_DIFFUSE: ::DWORD = 0x00000000; +pub const D3DTA_CURRENT: ::DWORD = 0x00000001; +pub const D3DTA_TEXTURE: ::DWORD = 0x00000002; +pub const D3DTA_TFACTOR: ::DWORD = 0x00000003; +pub const D3DTA_SPECULAR: ::DWORD = 0x00000004; +pub const D3DTA_TEMP: ::DWORD = 0x00000005; +pub const D3DTA_CONSTANT: ::DWORD = 0x00000006; +pub const D3DTA_COMPLEMENT: ::DWORD = 0x00000010; +pub const D3DTA_ALPHAREPLICATE: ::DWORD = 0x00000020; +ENUM!{enum D3DTEXTUREFILTERTYPE { + D3DTEXF_NONE = 0, + D3DTEXF_POINT = 1, + D3DTEXF_LINEAR = 2, + D3DTEXF_ANISOTROPIC = 3, + D3DTEXF_PYRAMIDALQUAD = 6, + D3DTEXF_GAUSSIANQUAD = 7, + D3DTEXF_CONVOLUTIONMONO = 8, +}} +pub const D3DPV_DONOTCOPYDATA: ::DWORD = 1 << 0; +pub const D3DFVF_RESERVED0: ::DWORD = 0x001; +pub const D3DFVF_POSITION_MASK: ::DWORD = 0x400E; +pub const D3DFVF_XYZ: ::DWORD = 0x002; +pub const D3DFVF_XYZRHW: ::DWORD = 0x004; +pub const D3DFVF_XYZB1: ::DWORD = 0x006; +pub const D3DFVF_XYZB2: ::DWORD = 0x008; +pub const D3DFVF_XYZB3: ::DWORD = 0x00a; +pub const D3DFVF_XYZB4: ::DWORD = 0x00c; +pub const D3DFVF_XYZB5: ::DWORD = 0x00e; +pub const D3DFVF_XYZW: ::DWORD = 0x4002; +pub const D3DFVF_NORMAL: ::DWORD = 0x010; +pub const D3DFVF_PSIZE: ::DWORD = 0x020; +pub const D3DFVF_DIFFUSE: ::DWORD = 0x040; +pub const D3DFVF_SPECULAR: ::DWORD = 0x080; +pub const D3DFVF_TEXCOUNT_MASK: ::DWORD = 0xf00; +pub const D3DFVF_TEXCOUNT_SHIFT: ::DWORD = 8; +pub const D3DFVF_TEX0: ::DWORD = 0x000; +pub const D3DFVF_TEX1: ::DWORD = 0x100; +pub const D3DFVF_TEX2: ::DWORD = 0x200; +pub const D3DFVF_TEX3: ::DWORD = 0x300; +pub const D3DFVF_TEX4: ::DWORD = 0x400; +pub const D3DFVF_TEX5: ::DWORD = 0x500; +pub const D3DFVF_TEX6: ::DWORD = 0x600; +pub const D3DFVF_TEX7: ::DWORD = 0x700; +pub const D3DFVF_TEX8: ::DWORD = 0x800; +pub const D3DFVF_LASTBETA_UBYTE4: ::DWORD = 0x1000; +pub const D3DFVF_LASTBETA_D3DCOLOR: ::DWORD = 0x8000; +pub const D3DFVF_RESERVED2: ::DWORD = 0x6000; +ENUM!{enum D3DDECLUSAGE { + D3DDECLUSAGE_POSITION = 0, + D3DDECLUSAGE_BLENDWEIGHT, + D3DDECLUSAGE_BLENDINDICES, + D3DDECLUSAGE_NORMAL, + D3DDECLUSAGE_PSIZE, + D3DDECLUSAGE_TEXCOORD, + D3DDECLUSAGE_TANGENT, + D3DDECLUSAGE_BINORMAL, + D3DDECLUSAGE_TESSFACTOR, + D3DDECLUSAGE_POSITIONT, + D3DDECLUSAGE_COLOR, + D3DDECLUSAGE_FOG, + D3DDECLUSAGE_DEPTH, + D3DDECLUSAGE_SAMPLE, +}} +pub const MAXD3DDECLUSAGE: D3DDECLUSAGE = D3DDECLUSAGE_SAMPLE; +pub const MAXD3DDECLUSAGEINDEX: ::DWORD = 15; +pub const MAXD3DDECLLENGTH: ::DWORD = 64; +ENUM!{enum D3DDECLMETHOD { + D3DDECLMETHOD_DEFAULT = 0, + D3DDECLMETHOD_PARTIALU, + D3DDECLMETHOD_PARTIALV, + D3DDECLMETHOD_CROSSUV, + D3DDECLMETHOD_UV, + D3DDECLMETHOD_LOOKUP, + D3DDECLMETHOD_LOOKUPPRESAMPLED, +}} +pub const MAXD3DDECLMETHOD: D3DDECLMETHOD = D3DDECLMETHOD_LOOKUPPRESAMPLED; +ENUM!{enum D3DDECLTYPE { + D3DDECLTYPE_FLOAT1 = 0, + D3DDECLTYPE_FLOAT2 = 1, + D3DDECLTYPE_FLOAT3 = 2, + D3DDECLTYPE_FLOAT4 = 3, + D3DDECLTYPE_D3DCOLOR = 4, + D3DDECLTYPE_UBYTE4 = 5, + D3DDECLTYPE_SHORT2 = 6, + D3DDECLTYPE_SHORT4 = 7, + D3DDECLTYPE_UBYTE4N = 8, + D3DDECLTYPE_SHORT2N = 9, + D3DDECLTYPE_SHORT4N = 10, + D3DDECLTYPE_USHORT2N = 11, + D3DDECLTYPE_USHORT4N = 12, + D3DDECLTYPE_UDEC3 = 13, + D3DDECLTYPE_DEC3N = 14, + D3DDECLTYPE_FLOAT16_2 = 15, + D3DDECLTYPE_FLOAT16_4 = 16, + D3DDECLTYPE_UNUSED = 17, +}} +pub const MAXD3DDECLTYPE: D3DDECLTYPE = D3DDECLTYPE_UNUSED; +STRUCT!{struct D3DVERTEXELEMENT9 { + Stream: ::WORD, + Offset: ::WORD, + Type: ::BYTE, + Method: ::BYTE, + Usage: ::BYTE, + UsageIndex: ::BYTE, +}} +pub type LPD3DVERTEXELEMENT9 = *mut D3DVERTEXELEMENT9; +pub const D3DDECL_END: D3DVERTEXELEMENT9 = D3DVERTEXELEMENT9 { + Stream: 0xFF, + Offset: 0, + Type: D3DDECLTYPE_UNUSED.0 as ::BYTE, + Method: 0, + Usage: 0, + UsageIndex: 0, +}; +pub const D3DDP_MAXTEXCOORD: ::DWORD = 8; +pub const D3DSTREAMSOURCE_INDEXEDDATA: ::DWORD = 1 << 30; +pub const D3DSTREAMSOURCE_INSTANCEDATA: ::DWORD = 2 << 30; +pub const D3DSI_OPCODE_MASK: ::DWORD = 0x0000FFFF; +pub const D3DSI_INSTLENGTH_MASK: ::DWORD = 0x0F000000; +pub const D3DSI_INSTLENGTH_SHIFT: ::DWORD = 24; +ENUM!{enum D3DSHADER_INSTRUCTION_OPCODE_TYPE { + D3DSIO_NOP = 0, + D3DSIO_MOV = 1, + D3DSIO_ADD = 2, + D3DSIO_SUB = 3, + D3DSIO_MAD = 4, + D3DSIO_MUL = 5, + D3DSIO_RCP = 6, + D3DSIO_RSQ = 7, + D3DSIO_DP3 = 8, + D3DSIO_DP4 = 9, + D3DSIO_MIN = 10, + D3DSIO_MAX = 11, + D3DSIO_SLT = 12, + D3DSIO_SGE = 13, + D3DSIO_EXP = 14, + D3DSIO_LOG = 15, + D3DSIO_LIT = 16, + D3DSIO_DST = 17, + D3DSIO_LRP = 18, + D3DSIO_FRC = 18, + D3DSIO_M4x4 = 20, + D3DSIO_M4x3 = 21, + D3DSIO_M3x4 = 22, + D3DSIO_M3x3 = 23, + D3DSIO_M3x2 = 24, + D3DSIO_CALL = 25, + D3DSIO_CALLNZ = 26, + D3DSIO_LOOP = 27, + D3DSIO_RET = 28, + D3DSIO_ENDLOOP = 29, + D3DSIO_LABEL = 30, + D3DSIO_DCL = 31, + D3DSIO_POW = 32, + D3DSIO_CRS = 33, + D3DSIO_SGN = 34, + D3DSIO_ABS = 35, + D3DSIO_NRM = 36, + D3DSIO_SINCOS = 37, + D3DSIO_REP = 38, + D3DSIO_ENDREP = 39, + D3DSIO_IF = 40, + D3DSIO_IFC = 41, + D3DSIO_ELSE = 42, + D3DSIO_ENDIF = 43, + D3DSIO_BREAK = 44, + D3DSIO_BREAKC = 45, + D3DSIO_MOVA = 46, + D3DSIO_DEFB = 47, + D3DSIO_DEFI = 48, + D3DSIO_TEXCOORD = 64, + D3DSIO_TEXKILL = 65, + D3DSIO_TEX = 66, + D3DSIO_TEXBEM = 67, + D3DSIO_TEXBEML = 68, + D3DSIO_TEXREG2AR = 69, + D3DSIO_TEXREG2GB = 70, + D3DSIO_TEXM3x2PAD = 71, + D3DSIO_TEXM3x2TEX = 72, + D3DSIO_TEXM3x3PAD = 73, + D3DSIO_TEXM3x3TEX = 74, + D3DSIO_RESERVED0 = 75, + D3DSIO_TEXM3x3SPEC = 76, + D3DSIO_TEXM3x3VSPEC = 77, + D3DSIO_EXPP = 78, + D3DSIO_LOGP = 79, + D3DSIO_CND = 80, + D3DSIO_DEF = 81, + D3DSIO_TEXREG2RGB = 82, + D3DSIO_TEXDP3TEX = 83, + D3DSIO_TEXM3x2DEPTH = 84, + D3DSIO_TEXDP3 = 85, + D3DSIO_TEXM3x3 = 86, + D3DSIO_TEXDEPTH = 87, + D3DSIO_CMP = 88, + D3DSIO_BEM = 89, + D3DSIO_DP2ADD = 90, + D3DSIO_DSX = 91, + D3DSIO_DSY = 92, + D3DSIO_TEXLDD = 93, + D3DSIO_SETP = 94, + D3DSIO_TEXLDL = 95, + D3DSIO_BREAKP = 96, + D3DSIO_PHASE = 0xFFFD, + D3DSIO_COMMENT = 0xFFFE, + D3DSIO_END = 0xFFFF, +}} +pub const D3DSI_COISSUE: ::DWORD = 0x40000000; +pub const D3DSP_OPCODESPECIFICCONTROL_MASK: ::DWORD = 0x00ff0000; +pub const D3DSP_OPCODESPECIFICCONTROL_SHIFT: ::DWORD = 16; +pub const D3DSI_TEXLD_PROJECT: ::DWORD = 0x01 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; +pub const D3DSI_TEXLD_BIAS: ::DWORD = 0x02 << D3DSP_OPCODESPECIFICCONTROL_SHIFT; +ENUM!{enum D3DSHADER_COMPARISON { + D3DSPC_RESERVED0 = 0, + D3DSPC_GT = 1, + D3DSPC_EQ = 2, + D3DSPC_GE = 3, + D3DSPC_LT = 4, + D3DSPC_NE = 5, + D3DSPC_LE = 6, + D3DSPC_RESERVED1 = 7, +}} +pub const D3DSHADER_COMPARISON_SHIFT: ::DWORD = D3DSP_OPCODESPECIFICCONTROL_SHIFT; +pub const D3DSHADER_COMPARISON_MASK: ::DWORD = 0x7 << D3DSHADER_COMPARISON_SHIFT; +pub const D3DSHADER_INSTRUCTION_PREDICATED: ::DWORD = 0x1 << 28; +pub const D3DSP_DCL_USAGE_SHIFT: ::DWORD = 0; +pub const D3DSP_DCL_USAGE_MASK: ::DWORD = 0x0000000f; +pub const D3DSP_DCL_USAGEINDEX_SHIFT: ::DWORD = 16; +pub const D3DSP_DCL_USAGEINDEX_MASK: ::DWORD = 0x000f0000; +pub const D3DSP_TEXTURETYPE_SHIFT: ::DWORD = 27; +pub const D3DSP_TEXTURETYPE_MASK: ::DWORD = 0x78000000; +ENUM!{enum D3DSAMPLER_TEXTURE_TYPE { + D3DSTT_UNKNOWN = 0 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_2D = 2 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_CUBE = 3 << D3DSP_TEXTURETYPE_SHIFT, + D3DSTT_VOLUME = 4 << D3DSP_TEXTURETYPE_SHIFT, +}} +pub const D3DSP_REGNUM_MASK: ::DWORD = 0x000007FF; +pub const D3DSP_WRITEMASK_0: ::DWORD = 0x00010000; +pub const D3DSP_WRITEMASK_1: ::DWORD = 0x00020000; +pub const D3DSP_WRITEMASK_2: ::DWORD = 0x00040000; +pub const D3DSP_WRITEMASK_3: ::DWORD = 0x00080000; +pub const D3DSP_WRITEMASK_ALL: ::DWORD = 0x000F0000; +pub const D3DSP_DSTMOD_SHIFT: ::DWORD = 20; +pub const D3DSP_DSTMOD_MASK: ::DWORD = 0x00F00000; +pub const D3DSPDM_NONE: ::DWORD = 0 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_SATURATE: ::DWORD = 1 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_PARTIALPRECISION: ::DWORD = 2 << D3DSP_DSTMOD_SHIFT; +pub const D3DSPDM_MSAMPCENTROID: ::DWORD = 4 << D3DSP_DSTMOD_SHIFT; +pub const D3DSP_DSTSHIFT_SHIFT: ::DWORD = 24; +pub const D3DSP_DSTSHIFT_MASK: ::DWORD = 0x0F000000; +pub const D3DSP_REGTYPE_SHIFT: ::DWORD = 28; +pub const D3DSP_REGTYPE_SHIFT2: ::DWORD = 8; +pub const D3DSP_REGTYPE_MASK: ::DWORD = 0x70000000; +pub const D3DSP_REGTYPE_MASK2: ::DWORD = 0x00001800; +ENUM!{enum D3DSHADER_PARAM_REGISTER_TYPE { + D3DSPR_TEMP = 0, + D3DSPR_INPUT = 1, + D3DSPR_CONST = 2, + D3DSPR_ADDR = 3, + D3DSPR_TEXTURE = 3, + D3DSPR_RASTOUT = 4, + D3DSPR_ATTROUT = 5, + D3DSPR_TEXCRDOUT = 6, + D3DSPR_OUTPUT = 6, + D3DSPR_CONSTINT = 7, + D3DSPR_COLOROUT = 8, + D3DSPR_DEPTHOUT = 9, + D3DSPR_SAMPLER = 10, + D3DSPR_CONST2 = 11, + D3DSPR_CONST3 = 12, + D3DSPR_CONST4 = 13, + D3DSPR_CONSTBOOL = 14, + D3DSPR_LOOP = 15, + D3DSPR_TEMPFLOAT16 = 16, + D3DSPR_MISCTYPE = 17, + D3DSPR_LABEL = 18, + D3DSPR_PREDICATE = 19, +}} +ENUM!{enum D3DSHADER_MISCTYPE_OFFSETS { + D3DSMO_POSITION = 0, + D3DSMO_FACE = 1, +}} +ENUM!{enum D3DVS_RASTOUT_OFFSETS { + D3DSRO_POSITION = 0, + D3DSRO_FOG, + D3DSRO_POINT_SIZE, +}} +pub const D3DVS_ADDRESSMODE_SHIFT: ::DWORD = 13; +pub const D3DVS_ADDRESSMODE_MASK: ::DWORD = 1 << D3DVS_ADDRESSMODE_SHIFT; +ENUM!{enum D3DVS_ADDRESSMODE_TYPE { + D3DVS_ADDRMODE_ABSOLUTE = 0 << D3DVS_ADDRESSMODE_SHIFT, + D3DVS_ADDRMODE_RELATIVE = 1 << D3DVS_ADDRESSMODE_SHIFT, +}} +pub const D3DSHADER_ADDRESSMODE_SHIFT: ::DWORD = 13; +pub const D3DSHADER_ADDRESSMODE_MASK: ::DWORD = 1 << D3DSHADER_ADDRESSMODE_SHIFT; +ENUM!{enum D3DSHADER_ADDRESSMODE_TYPE { + D3DSHADER_ADDRMODE_ABSOLUTE = 0 << D3DSHADER_ADDRESSMODE_SHIFT, + D3DSHADER_ADDRMODE_RELATIVE = 1 << D3DSHADER_ADDRESSMODE_SHIFT, +}} +pub const D3DVS_SWIZZLE_SHIFT: ::DWORD = 16; +pub const D3DVS_SWIZZLE_MASK: ::DWORD = 0x00FF0000; +pub const D3DVS_X_X: ::DWORD = 0 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_Y: ::DWORD = 1 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_Z: ::DWORD = 2 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_X_W: ::DWORD = 3 << D3DVS_SWIZZLE_SHIFT; +pub const D3DVS_Y_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Y_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 2); +pub const D3DVS_Z_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_Z_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 4); +pub const D3DVS_W_X: ::DWORD = 0 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_Y: ::DWORD = 1 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_Z: ::DWORD = 2 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_W_W: ::DWORD = 3 << (D3DVS_SWIZZLE_SHIFT + 6); +pub const D3DVS_NOSWIZZLE: ::DWORD = D3DVS_X_X | D3DVS_Y_Y | D3DVS_Z_Z | D3DVS_W_W; +pub const D3DSP_SWIZZLE_SHIFT: ::DWORD = 16; +pub const D3DSP_SWIZZLE_MASK: ::DWORD = 0x00FF0000; +pub const D3DSP_NOSWIZZLE: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATERED: ::DWORD = (0 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (0 << (D3DSP_SWIZZLE_SHIFT + 2)) | (0 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (0 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEGREEN: ::DWORD = (1 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | (1 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (1 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEBLUE: ::DWORD = (2 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (2 << (D3DSP_SWIZZLE_SHIFT + 2)) | (2 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (2 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_REPLICATEALPHA: ::DWORD = (3 << (D3DSP_SWIZZLE_SHIFT + 0)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 2)) | (3 << (D3DSP_SWIZZLE_SHIFT + 4)) + | (3 << (D3DSP_SWIZZLE_SHIFT + 6)); +pub const D3DSP_SRCMOD_SHIFT: ::DWORD = 24; +pub const D3DSP_SRCMOD_MASK: ::DWORD = 0x0F000000; +ENUM!{enum D3DSHADER_PARAM_SRCMOD_TYPE { + D3DSPSM_NONE = 0 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_NEG = 1 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_BIAS = 2 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_BIASNEG = 3 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_SIGN = 4 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_SIGNNEG = 5 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_COMP = 6 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_X2 = 7 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_X2NEG = 8 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_DZ = 9 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_DW = 10 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_ABS = 11 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_ABSNEG = 12 << D3DSP_SRCMOD_SHIFT, + D3DSPSM_NOT = 13 << D3DSP_SRCMOD_SHIFT, +}} +pub const D3DSP_MIN_PRECISION_SHIFT: ::DWORD = 14; +pub const D3DSP_MIN_PRECISION_MASK: ::DWORD = 0x0000C000; +ENUM!{enum D3DSHADER_MIN_PRECISION { + D3DMP_DEFAULT = 0, + D3DMP_16 = 1, + D3DMP_2_8 = 2, +}} +pub const D3DSI_COMMENTSIZE_SHIFT: ::DWORD = 16; +pub const D3DSI_COMMENTSIZE_MASK: ::DWORD = 0x7FFF0000; +pub const D3DPS_END: ::DWORD = 0x0000FFFF; +pub const D3DVS_END: ::DWORD = 0x0000FFFF; +ENUM!{enum D3DBASISTYPE { + D3DBASIS_BEZIER = 0, + D3DBASIS_BSPLINE = 1, + D3DBASIS_CATMULL_ROM = 2, +}} +ENUM!{enum D3DDEGREETYPE { + D3DDEGREE_LINEAR = 1, + D3DDEGREE_QUADRATIC = 2, + D3DDEGREE_CUBIC = 3, + D3DDEGREE_QUINTIC = 5, +}} +ENUM!{enum D3DPATCHEDGESTYLE { + D3DPATCHEDGE_DISCRETE = 0, + D3DPATCHEDGE_CONTINUOUS = 1, +}} +ENUM!{enum D3DSTATEBLOCKTYPE { + D3DSBT_ALL = 1, + D3DSBT_PIXELSTATE = 2, + D3DSBT_VERTEXSTATE = 3, +}} +FLAGS!{enum D3DVERTEXBLENDFLAGS { + D3DVBF_DISABLE = 0, + D3DVBF_1WEIGHTS = 1, + D3DVBF_2WEIGHTS = 2, + D3DVBF_3WEIGHTS = 3, + D3DVBF_TWEENING = 255, + D3DVBF_0WEIGHTS = 256, +}} +ENUM!{enum D3DTEXTURETRANSFORMFLAGS { + D3DTTFF_DISABLE = 0, + D3DTTFF_COUNT1 = 1, + D3DTTFF_COUNT2 = 2, + D3DTTFF_COUNT3 = 3, + D3DTTFF_COUNT4 = 4, + D3DTTFF_PROJECTED = 256, +}} +pub const D3DFVF_TEXTUREFORMAT2: ::DWORD = 0; +pub const D3DFVF_TEXTUREFORMAT1: ::DWORD = 3; +pub const D3DFVF_TEXTUREFORMAT3: ::DWORD = 1; +pub const D3DFVF_TEXTUREFORMAT4: ::DWORD = 2; +ENUM!{enum D3DDEVTYPE { + D3DDEVTYPE_HAL = 1, + D3DDEVTYPE_REF = 2, + D3DDEVTYPE_SW = 3, + D3DDEVTYPE_NULLREF = 4, +}} +ENUM!{enum D3DMULTISAMPLE_TYPE { + D3DMULTISAMPLE_NONE = 0, + D3DMULTISAMPLE_NONMASKABLE = 1, + D3DMULTISAMPLE_2_SAMPLES = 2, + D3DMULTISAMPLE_3_SAMPLES = 3, + D3DMULTISAMPLE_4_SAMPLES = 4, + D3DMULTISAMPLE_5_SAMPLES = 5, + D3DMULTISAMPLE_6_SAMPLES = 6, + D3DMULTISAMPLE_7_SAMPLES = 7, + D3DMULTISAMPLE_8_SAMPLES = 8, + D3DMULTISAMPLE_9_SAMPLES = 9, + D3DMULTISAMPLE_10_SAMPLES = 10, + D3DMULTISAMPLE_11_SAMPLES = 11, + D3DMULTISAMPLE_12_SAMPLES = 12, + D3DMULTISAMPLE_13_SAMPLES = 13, + D3DMULTISAMPLE_14_SAMPLES = 14, + D3DMULTISAMPLE_15_SAMPLES = 15, + D3DMULTISAMPLE_16_SAMPLES = 16, +}} +ENUM!{enum D3DFORMAT { + D3DFMT_UNKNOWN = 0, + D3DFMT_R8G8B8 = 20, + D3DFMT_A8R8G8B8 = 21, + D3DFMT_X8R8G8B8 = 22, + D3DFMT_R5G6B5 = 23, + D3DFMT_X1R5G5B5 = 24, + D3DFMT_A1R5G5B5 = 25, + D3DFMT_A4R4G4B4 = 26, + D3DFMT_R3G3B2 = 27, + D3DFMT_A8 = 28, + D3DFMT_A8R3G3B2 = 29, + D3DFMT_X4R4G4B4 = 30, + D3DFMT_A2B10G10R10 = 31, + D3DFMT_A8B8G8R8 = 32, + D3DFMT_X8B8G8R8 = 33, + D3DFMT_G16R16 = 34, + D3DFMT_A2R10G10B10 = 35, + D3DFMT_A16B16G16R16 = 36, + D3DFMT_A8P8 = 40, + D3DFMT_P8 = 41, + D3DFMT_L8 = 50, + D3DFMT_A8L8 = 51, + D3DFMT_A4L4 = 52, + D3DFMT_V8U8 = 60, + D3DFMT_L6V5U5 = 61, + D3DFMT_X8L8V8U8 = 62, + D3DFMT_Q8W8V8U8 = 63, + D3DFMT_V16U16 = 64, + D3DFMT_A2W10V10U10 = 67, + D3DFMT_UYVY = MAKEFOURCC!(b'U', b'Y', b'V', b'Y') as u32, + D3DFMT_R8G8_B8G8 = MAKEFOURCC!(b'R', b'G', b'B', b'G') as u32, + D3DFMT_YUY2 = MAKEFOURCC!(b'Y', b'U', b'Y', b'2') as u32, + D3DFMT_G8R8_G8B8 = MAKEFOURCC!(b'G', b'R', b'G', b'B') as u32, + D3DFMT_DXT1 = MAKEFOURCC!(b'D', b'X', b'T', b'1') as u32, + D3DFMT_DXT2 = MAKEFOURCC!(b'D', b'X', b'T', b'2') as u32, + D3DFMT_DXT3 = MAKEFOURCC!(b'D', b'X', b'T', b'3') as u32, + D3DFMT_DXT4 = MAKEFOURCC!(b'D', b'X', b'T', b'4') as u32, + D3DFMT_DXT5 = MAKEFOURCC!(b'D', b'X', b'T', b'5') as u32, + D3DFMT_D16_LOCKABLE = 70, + D3DFMT_D32 = 71, + D3DFMT_D15S1 = 73, + D3DFMT_D24S8 = 75, + D3DFMT_D24X8 = 77, + D3DFMT_D24X4S4 = 79, + D3DFMT_D16 = 80, + D3DFMT_D32F_LOCKABLE = 82, + D3DFMT_D24FS8 = 83, + D3DFMT_D32_LOCKABLE = 84, + D3DFMT_S8_LOCKABLE = 85, + D3DFMT_L16 = 81, + D3DFMT_VERTEXDATA = 100, + D3DFMT_INDEX16 = 101, + D3DFMT_INDEX32 = 102, + D3DFMT_Q16W16V16U16 = 110, + D3DFMT_MULTI2_ARGB8 = MAKEFOURCC!(b'M', b'E', b'T', b'1') as u32, + D3DFMT_R16F = 111, + D3DFMT_G16R16F = 112, + D3DFMT_A16B16G16R16F = 113, + D3DFMT_R32F = 114, + D3DFMT_G32R32F = 115, + D3DFMT_A32B32G32R32F = 116, + D3DFMT_CxV8U8 = 117, + D3DFMT_A1 = 118, + D3DFMT_A2B10G10R10_XR_BIAS = 119, + D3DFMT_BINARYBUFFER = 199, +}} +STRUCT!{struct D3DDISPLAYMODE { + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::UINT, + Format: D3DFORMAT, +}} +STRUCT!{struct D3DDEVICE_CREATION_PARAMETERS { + AdapterOrdinal: ::UINT, + DeviceType: D3DDEVTYPE, + hFocusWindow: ::HWND, + BehaviorFlags: ::DWORD, +}} +ENUM!{enum D3DSWAPEFFECT { + D3DSWAPEFFECT_DISCARD = 1, + D3DSWAPEFFECT_FLIP = 2, + D3DSWAPEFFECT_COPY = 3, + D3DSWAPEFFECT_OVERLAY = 4, + D3DSWAPEFFECT_FLIPEX = 5, +}} +ENUM!{enum D3DPOOL { + D3DPOOL_DEFAULT = 0, + D3DPOOL_MANAGED = 1, + D3DPOOL_SYSTEMMEM = 2, + D3DPOOL_SCRATCH = 3, +}} +pub const D3DPRESENT_RATE_DEFAULT: ::DWORD = 0x00000000; +STRUCT!{struct D3DPRESENT_PARAMETERS { + BackBufferWidth: ::UINT, + BackBufferHeight: ::UINT, + BackBufferFormat: D3DFORMAT, + BackBufferCount: ::UINT, + MultiSampleType: D3DMULTISAMPLE_TYPE, + MultiSampleQuality: ::DWORD, + SwapEffect: D3DSWAPEFFECT, + hDeviceWindow: ::HWND, + Windowed: ::BOOL, + EnableAutoDepthStencil: ::BOOL, + AutoDepthStencilFormat: D3DFORMAT, + Flags: ::DWORD, + FullScreen_RefreshRateInHz: ::UINT, + PresentationInterval: ::UINT, +}} +pub const D3DPRESENTFLAG_LOCKABLE_BACKBUFFER: ::DWORD = 0x00000001; +pub const D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL: ::DWORD = 0x00000002; +pub const D3DPRESENTFLAG_DEVICECLIP: ::DWORD = 0x00000004; +pub const D3DPRESENTFLAG_VIDEO: ::DWORD = 0x00000010; +pub const D3DPRESENTFLAG_NOAUTOROTATE: ::DWORD = 0x00000020; +pub const D3DPRESENTFLAG_UNPRUNEDMODE: ::DWORD = 0x00000040; +pub const D3DPRESENTFLAG_OVERLAY_LIMITEDRGB: ::DWORD = 0x00000080; +pub const D3DPRESENTFLAG_OVERLAY_YCbCr_BT709: ::DWORD = 0x00000100; +pub const D3DPRESENTFLAG_OVERLAY_YCbCr_xvYCC: ::DWORD = 0x00000200; +pub const D3DPRESENTFLAG_RESTRICTED_CONTENT: ::DWORD = 0x00000400; +pub const D3DPRESENTFLAG_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00000800; +STRUCT!{nodebug struct D3DGAMMARAMP { + red: [::WORD; 256], + green: [::WORD; 256], + blue: [::WORD; 256], +}} +ENUM!{enum D3DBACKBUFFER_TYPE { + D3DBACKBUFFER_TYPE_MONO = 0, + D3DBACKBUFFER_TYPE_LEFT = 1, + D3DBACKBUFFER_TYPE_RIGHT = 2, +}} +ENUM!{enum D3DRESOURCETYPE { + D3DRTYPE_SURFACE = 1, + D3DRTYPE_VOLUME = 2, + D3DRTYPE_TEXTURE = 3, + D3DRTYPE_VOLUMETEXTURE = 4, + D3DRTYPE_CUBETEXTURE = 5, + D3DRTYPE_VERTEXBUFFER = 6, + D3DRTYPE_INDEXBUFFER = 7, +}} +pub const D3DUSAGE_RENDERTARGET: ::DWORD = 0x00000001; +pub const D3DUSAGE_DEPTHSTENCIL: ::DWORD = 0x00000002; +pub const D3DUSAGE_DYNAMIC: ::DWORD = 0x00000200; +pub const D3DUSAGE_NONSECURE: ::DWORD = 0x00800000; +pub const D3DUSAGE_AUTOGENMIPMAP: ::DWORD = 0x00000400; +pub const D3DUSAGE_DMAP: ::DWORD = 0x00004000; +pub const D3DUSAGE_QUERY_LEGACYBUMPMAP: ::DWORD = 0x00008000; +pub const D3DUSAGE_QUERY_SRGBREAD: ::DWORD = 0x00010000; +pub const D3DUSAGE_QUERY_FILTER: ::DWORD = 0x00020000; +pub const D3DUSAGE_QUERY_SRGBWRITE: ::DWORD = 0x00040000; +pub const D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING: ::DWORD = 0x00080000; +pub const D3DUSAGE_QUERY_VERTEXTEXTURE: ::DWORD = 0x00100000; +pub const D3DUSAGE_QUERY_WRAPANDMIP: ::DWORD = 0x00200000; +pub const D3DUSAGE_WRITEONLY: ::DWORD = 0x00000008; +pub const D3DUSAGE_SOFTWAREPROCESSING: ::DWORD = 0x00000010; +pub const D3DUSAGE_DONOTCLIP: ::DWORD = 0x00000020; +pub const D3DUSAGE_POINTS: ::DWORD = 0x00000040; +pub const D3DUSAGE_RTPATCHES: ::DWORD = 0x00000080; +pub const D3DUSAGE_NPATCHES: ::DWORD = 0x00000100; +pub const D3DUSAGE_TEXTAPI: ::DWORD = 0x10000000; +pub const D3DUSAGE_RESTRICTED_CONTENT: ::DWORD = 0x00000800; +pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE: ::DWORD = 0x00002000; +pub const D3DUSAGE_RESTRICT_SHARED_RESOURCE_DRIVER: ::DWORD = 0x00001000; +ENUM!{enum D3DCUBEMAP_FACES { + D3DCUBEMAP_FACE_POSITIVE_X = 0, + D3DCUBEMAP_FACE_NEGATIVE_X = 1, + D3DCUBEMAP_FACE_POSITIVE_Y = 2, + D3DCUBEMAP_FACE_NEGATIVE_Y = 3, + D3DCUBEMAP_FACE_POSITIVE_Z = 4, + D3DCUBEMAP_FACE_NEGATIVE_Z = 5, +}} +pub const D3DLOCK_READONLY: ::DWORD = 0x00000010; +pub const D3DLOCK_DISCARD: ::DWORD = 0x00002000; +pub const D3DLOCK_NOOVERWRITE: ::DWORD = 0x00001000; +pub const D3DLOCK_NOSYSLOCK: ::DWORD = 0x00000800; +pub const D3DLOCK_DONOTWAIT: ::DWORD = 0x00004000; +pub const D3DLOCK_NO_DIRTY_UPDATE: ::DWORD = 0x00008000; +STRUCT!{struct D3DVERTEXBUFFER_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Size: ::UINT, + FVF: ::DWORD, +}} +STRUCT!{struct D3DINDEXBUFFER_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Size: ::UINT, +}} +STRUCT!{struct D3DSURFACE_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + MultiSampleType: D3DMULTISAMPLE_TYPE, + MultiSampleQuality: ::DWORD, + Width: ::UINT, + Height: ::UINT, +}} +STRUCT!{struct D3DVOLUME_DESC { + Format: D3DFORMAT, + Type: D3DRESOURCETYPE, + Usage: ::DWORD, + Pool: D3DPOOL, + Width: ::UINT, + Height: ::UINT, + Depth: ::UINT, +}} +STRUCT!{struct D3DLOCKED_RECT { + Pitch: ::INT, + pBits: *mut ::c_void, +}} +STRUCT!{struct D3DBOX { + Left: ::UINT, + Top: ::UINT, + Right: ::UINT, + Bottom: ::UINT, + Front: ::UINT, + Back: ::UINT, +}} +STRUCT!{struct D3DLOCKED_BOX { + RowPitch: ::INT, + SlicePitch: ::INT, + pBits: *mut ::c_void, +}} +STRUCT!{struct D3DRANGE { + Offset: ::UINT, + Size: ::UINT, +}} +STRUCT!{struct D3DRECTPATCH_INFO { + StartVertexOffsetWidth: ::UINT, + StartVertexOffsetHeight: ::UINT, + Width: ::UINT, + Height: ::UINT, + Stride: ::UINT, + Basis: D3DBASISTYPE, + Degree: D3DDEGREETYPE, +}} +STRUCT!{struct D3DTRIPATCH_INFO { + StartVertexOffset: ::UINT, + NumVertices: ::UINT, + Basis: D3DBASISTYPE, + Degree: D3DDEGREETYPE, +}} +pub const MAX_DEVICE_IDENTIFIER_STRING: usize = 512; +STRUCT!{nodebug struct D3DADAPTER_IDENTIFIER9 { + Driver: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], + Description: [::c_char; MAX_DEVICE_IDENTIFIER_STRING], + DeviceName: [::c_char; 32], + DriverVersion: ::LARGE_INTEGER, + VendorId: ::DWORD, + DeviceId: ::DWORD, + SubSysId: ::DWORD, + Revision: ::DWORD, + DeviceIdentifier: ::GUID, + WHQLLevel: ::DWORD, +}} +STRUCT!{struct D3DRASTER_STATUS { + InVBlank: ::BOOL, + ScanLine: ::UINT, +}} +ENUM!{enum D3DDEBUGMONITORTOKENS { + D3DDMT_ENABLE = 0, + D3DDMT_DISABLE = 1, +}} +ENUM!{enum D3DQUERYTYPE { + D3DQUERYTYPE_VCACHE = 4, + D3DQUERYTYPE_RESOURCEMANAGER = 5, + D3DQUERYTYPE_VERTEXSTATS = 6, + D3DQUERYTYPE_EVENT = 8, + D3DQUERYTYPE_OCCLUSION = 9, + D3DQUERYTYPE_TIMESTAMP = 10, + D3DQUERYTYPE_TIMESTAMPDISJOINT = 11, + D3DQUERYTYPE_TIMESTAMPFREQ = 12, + D3DQUERYTYPE_PIPELINETIMINGS = 13, + D3DQUERYTYPE_INTERFACETIMINGS = 14, + D3DQUERYTYPE_VERTEXTIMINGS = 15, + D3DQUERYTYPE_PIXELTIMINGS = 16, + D3DQUERYTYPE_BANDWIDTHTIMINGS = 17, + D3DQUERYTYPE_CACHEUTILIZATION = 18, + D3DQUERYTYPE_MEMORYPRESSURE = 19, +}} +pub const D3DISSUE_END: ::DWORD = 1 << 0; +pub const D3DISSUE_BEGIN: ::DWORD = 1 << 1; +pub const D3DGETDATA_FLUSH: ::DWORD = 1 << 0; +STRUCT!{struct D3DRESOURCESTATS { + bThrashing: ::BOOL, + ApproxBytesDownloaded: ::DWORD, + NumEvicts: ::DWORD, + NumVidCreates: ::DWORD, + LastPri: ::DWORD, + NumUsed: ::DWORD, + NumUsedInVidMem: ::DWORD, + WorkingSet: ::DWORD, + WorkingSetBytes: ::DWORD, + TotalManaged: ::DWORD, + TotalBytes: ::DWORD, +}} +pub const D3DRTYPECOUNT: usize = 8; +STRUCT!{struct D3DDEVINFO_RESOURCEMANAGER { + stats: [D3DRESOURCESTATS; 8 /*D3DRTYPECOUNT, rust bug?*/], +}} +pub type LPD3DDEVINFO_RESOURCEMANAGER = *mut D3DDEVINFO_RESOURCEMANAGER; +STRUCT!{struct D3DDEVINFO_D3DVERTEXSTATS { + NumRenderedTriangles: ::DWORD, + NumExtraClippingTriangles: ::DWORD, +}} +pub type LPD3DDEVINFO_D3DVERTEXSTATS = *mut D3DDEVINFO_D3DVERTEXSTATS; +STRUCT!{struct D3DDEVINFO_VCACHE { + Pattern: ::DWORD, + OptMethod: ::DWORD, + CacheSize: ::DWORD, + MagicNumber: ::DWORD, +}} +pub type LPD3DDEVINFO_VCACHE = *mut D3DDEVINFO_VCACHE; +STRUCT!{struct D3DDEVINFO_D3D9PIPELINETIMINGS { + VertexProcessingTimePercent: ::FLOAT, + PixelProcessingTimePercent: ::FLOAT, + OtherGPUProcessingTimePercent: ::FLOAT, + GPUIdleTimePercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9INTERFACETIMINGS { + WaitingForGPUToUseApplicationResourceTimePercent: ::FLOAT, + WaitingForGPUToAcceptMoreCommandsTimePercent: ::FLOAT, + WaitingForGPUToStayWithinLatencyTimePercent: ::FLOAT, + WaitingForGPUExclusiveResourceTimePercent: ::FLOAT, + WaitingForGPUOtherTimePercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9STAGETIMINGS { + MemoryProcessingPercent: ::FLOAT, + ComputationProcessingPercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9BANDWIDTHTIMINGS { + MaxBandwidthUtilized: ::FLOAT, + FrontEndUploadMemoryUtilizedPercent: ::FLOAT, + VertexRateUtilizedPercent: ::FLOAT, + TriangleSetupRateUtilizedPercent: ::FLOAT, + FillRateUtilizedPercent: ::FLOAT, +}} +STRUCT!{struct D3DDEVINFO_D3D9CACHEUTILIZATION { + TextureCacheHitRate: ::FLOAT, + PostTransformVertexCacheHitRate: ::FLOAT, +}} +STRUCT!{struct D3DMEMORYPRESSURE { + BytesEvictedFromProcess: ::UINT64, + SizeOfInefficientAllocation: ::UINT64, + LevelOfEfficiency: ::DWORD, +}} +ENUM!{enum D3DCOMPOSERECTSOP { + D3DCOMPOSERECTS_COPY = 1, + D3DCOMPOSERECTS_OR = 2, + D3DCOMPOSERECTS_AND = 3, + D3DCOMPOSERECTS_NEG = 4, +}} +STRUCT!{struct D3DCOMPOSERECTDESC { + X: ::USHORT, + Y: ::USHORT, + Width: ::USHORT, + Height: ::USHORT, +}} +STRUCT!{struct D3DCOMPOSERECTDESTINATION { + SrcRectIndex: ::USHORT, + Reserved: ::USHORT, + X: ::SHORT, + Y: ::SHORT, +}} +pub const D3DCOMPOSERECTS_MAXNUMRECTS: ::DWORD = 0xFFFF; +pub const D3DCONVOLUTIONMONO_MAXWIDTH: ::DWORD = 7; +pub const D3DCONVOLUTIONMONO_MAXHEIGHT: ::DWORD = D3DCONVOLUTIONMONO_MAXWIDTH; +pub const D3DFMT_A1_SURFACE_MAXWIDTH: ::DWORD = 8192; +pub const D3DFMT_A1_SURFACE_MAXHEIGHT: ::DWORD = 2048; +STRUCT!{struct D3DPRESENTSTATS { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, +}} +ENUM!{enum D3DSCANLINEORDERING { + D3DSCANLINEORDERING_UNKNOWN = 0, + D3DSCANLINEORDERING_PROGRESSIVE = 1, + D3DSCANLINEORDERING_INTERLACED = 2, +}} +STRUCT!{struct D3DDISPLAYMODEEX { + Size: ::UINT, + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::UINT, + Format: D3DFORMAT, + ScanLineOrdering: D3DSCANLINEORDERING, +}} +STRUCT!{struct D3DDISPLAYMODEFILTER { + Size: ::UINT, + Format: D3DFORMAT, + ScanLineOrdering: D3DSCANLINEORDERING, +}} +ENUM!{enum D3DDISPLAYROTATION { + D3DDISPLAYROTATION_IDENTITY = 1, + D3DDISPLAYROTATION_90 = 2, + D3DDISPLAYROTATION_180 = 3, + D3DDISPLAYROTATION_270 = 4, +}} +pub const D3D9_RESOURCE_PRIORITY_MINIMUM: ::DWORD = 0x28000000; +pub const D3D9_RESOURCE_PRIORITY_LOW: ::DWORD = 0x50000000; +pub const D3D9_RESOURCE_PRIORITY_NORMAL: ::DWORD = 0x78000000; +pub const D3D9_RESOURCE_PRIORITY_HIGH: ::DWORD = 0xa0000000; +pub const D3D9_RESOURCE_PRIORITY_MAXIMUM: ::DWORD = 0xc8000000; +pub const D3D_OMAC_SIZE: usize = 16; +STRUCT!{struct D3D_OMAC { + Omac: [::BYTE; D3D_OMAC_SIZE], +}} +ENUM!{enum D3DAUTHENTICATEDCHANNELTYPE { + D3DAUTHENTICATEDCHANNEL_D3D9 = 1, + D3DAUTHENTICATEDCHANNEL_DRIVER_SOFTWARE = 2, + D3DAUTHENTICATEDCHANNEL_DRIVER_HARDWARE = 3, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERY_INPUT { + QueryType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT { + omac: D3D_OMAC, + QueryType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, + ReturnCode: ::HRESULT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS { + Value: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYPROTECTION_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ProtectionFlags: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCHANNELTYPE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ChannelType: D3DAUTHENTICATEDCHANNELTYPE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYDEVICEHANDLE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DXVA2DecodeHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYCRYPTOSESSION_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DXVA2DecodeHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESSCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumRestrictedSharedResourceProcesses: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + ProcessIndex: ::UINT, +}} +ENUM!{enum D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE { + PROCESSIDTYPE_UNKNOWN = 0, + PROCESSIDTYPE_DWM = 1, + PROCESSIDTYPE_HANDLE = 2, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYRESTRICTEDSHAREDRESOURCEPROCESS_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + ProcessIndex: ::UINT, + ProcessIdentifer: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, + ProcessHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYUNRESTRICTEDPROTECTEDSHAREDRESOURCECOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumUnrestrictedProtectedSharedResources: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTIDCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + NumOutputIDs: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + OutputIDIndex: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYOUTPUTID_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + DeviceHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + OutputIDIndex: ::UINT, + OutputID: ::UINT64, +}} +FLAGS!{enum D3DBUSTYPE { + D3DBUSTYPE_OTHER = 0x00000000, + D3DBUSTYPE_PCI = 0x00000001, + D3DBUSTYPE_PCIX = 0x00000002, + D3DBUSTYPE_PCIEXPRESS = 0x00000003, + D3DBUSTYPE_AGP = 0x00000004, + D3DBUSIMPL_MODIFIER_INSIDE_OF_CHIPSET = 0x00010000, + MD3DBUSIMPL_ODIFIER_TRACKS_ON_MOTHER_BOARD_TO_CHIP = 0x00020000, + D3DBUSIMPL_MODIFIER_TRACKS_ON_MOTHER_BOARD_TO_SOCKET = 0x00030000, + D3DBUSIMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR = 0x00040000, + D3DBUSIMPL_MODIFIER_DAUGHTER_BOARD_CONNECTOR_INSIDE_OF_NUAE = 0x00050000, + D3DBUSIMPL_MODIFIER_NON_STANDARD = 0x80000000, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYINFOBUSTYPE_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + BusType: D3DBUSTYPE, + bAccessibleInContiguousBlocks: ::BOOL, + bAccessibleInNonContiguousBlocks: ::BOOL, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUIDCOUNT_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + NumEncryptionGuids: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_INPUT { + Input: D3DAUTHENTICATEDCHANNEL_QUERY_INPUT, + EncryptionGuidIndex: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYEVICTIONENCRYPTIONGUID_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + EncryptionGuidIndex: ::UINT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_QUERYUNCOMPRESSEDENCRYPTIONLEVEL_OUTPUT { + Output: D3DAUTHENTICATEDCHANNEL_QUERY_OUTPUT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT { + omac: D3D_OMAC, + ConfigureType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURE_OUTPUT { + omac: D3D_OMAC, + ConfigureType: ::GUID, + hChannel: ::HANDLE, + SequenceNumber: ::UINT, + ReturnCode: ::HRESULT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREINITIALIZE { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + StartSequenceQuery: ::UINT, + StartSequenceConfigure: ::UINT, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREPROTECTION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + Protections: D3DAUTHENTICATEDCHANNEL_PROTECTION_FLAGS, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURECRYPTOSESSION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + DXVA2DecodeHandle: ::HANDLE, + CryptoSessionHandle: ::HANDLE, + DeviceHandle: ::HANDLE, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGURESHAREDRESOURCE { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + ProcessIdentiferType: D3DAUTHENTICATEDCHANNEL_PROCESSIDENTIFIERTYPE, + ProcessHandle: ::HANDLE, + AllowAccess: ::BOOL, +}} +STRUCT!{struct D3DAUTHENTICATEDCHANNEL_CONFIGUREUNCOMPRESSEDENCRYPTION { + Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGURE_INPUT, + EncryptionGuid: ::GUID, +}} +STRUCT!{struct D3DENCRYPTED_BLOCK_INFO { + NumEncryptedBytesAtBeginning: ::UINT, + NumBytesInSkipPattern: ::UINT, + NumBytesInEncryptPattern: ::UINT, +}} +STRUCT!{struct D3DAES_CTR_IV { + IV: ::UINT64, + Count: ::UINT64, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3dcommon.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3dcommon.rs new file mode 100644 index 0000000..51a1b4e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3dcommon.rs @@ -0,0 +1,753 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of d3dcommon.h +ENUM!{enum D3D_DRIVER_TYPE { + D3D_DRIVER_TYPE_UNKNOWN, + D3D_DRIVER_TYPE_HARDWARE, + D3D_DRIVER_TYPE_REFERENCE, + D3D_DRIVER_TYPE_NULL, + D3D_DRIVER_TYPE_SOFTWARE, + D3D_DRIVER_TYPE_WARP, +}} +ENUM!{enum D3D_FEATURE_LEVEL { + D3D_FEATURE_LEVEL_9_1 = 0x9100, + D3D_FEATURE_LEVEL_9_2 = 0x9200, + D3D_FEATURE_LEVEL_9_3 = 0x9300, + D3D_FEATURE_LEVEL_10_0 = 0xa000, + D3D_FEATURE_LEVEL_10_1 = 0xa100, + D3D_FEATURE_LEVEL_11_0 = 0xb000, + D3D_FEATURE_LEVEL_11_1 = 0xb100, + D3D_FEATURE_LEVEL_12_0 = 0xc000, + D3D_FEATURE_LEVEL_12_1 = 0xc100, +}} +ENUM!{enum D3D_PRIMITIVE_TOPOLOGY { + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, + D3D_PRIMITIVE_TOPOLOGY_POINTLIST = 1, + D3D_PRIMITIVE_TOPOLOGY_LINELIST = 2, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, + D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, + D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, + D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, + D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, + D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, + D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, + D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, + D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, + D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, + D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, + D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, + D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, + D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, + D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, + D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, + D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, + D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, + D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, + D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, + D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, + D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, + D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, + D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, + D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, + D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, + D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, + D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, + D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, + D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, + D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, + D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, +}} +pub const D3D10_PRIMITIVE_TOPOLOGY_UNDEFINED: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; +pub const D3D10_PRIMITIVE_TOPOLOGY_POINTLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_POINTLIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; +pub const D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; +pub const D3D11_PRIMITIVE_TOPOLOGY_POINTLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_POINTLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; +pub const D3D11_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST; +pub const D3D11_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST: ::D3D_PRIMITIVE_TOPOLOGY = + D3D_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST; +ENUM!{enum D3D_PRIMITIVE { + D3D_PRIMITIVE_UNDEFINED = 0, + D3D_PRIMITIVE_POINT = 1, + D3D_PRIMITIVE_LINE = 2, + D3D_PRIMITIVE_TRIANGLE = 3, + D3D_PRIMITIVE_LINE_ADJ = 6, + D3D_PRIMITIVE_TRIANGLE_ADJ = 7, + D3D_PRIMITIVE_1_CONTROL_POINT_PATCH = 8, + D3D_PRIMITIVE_2_CONTROL_POINT_PATCH = 9, + D3D_PRIMITIVE_3_CONTROL_POINT_PATCH = 10, + D3D_PRIMITIVE_4_CONTROL_POINT_PATCH = 11, + D3D_PRIMITIVE_5_CONTROL_POINT_PATCH = 12, + D3D_PRIMITIVE_6_CONTROL_POINT_PATCH = 13, + D3D_PRIMITIVE_7_CONTROL_POINT_PATCH = 14, + D3D_PRIMITIVE_8_CONTROL_POINT_PATCH = 15, + D3D_PRIMITIVE_9_CONTROL_POINT_PATCH = 16, + D3D_PRIMITIVE_10_CONTROL_POINT_PATCH = 17, + D3D_PRIMITIVE_11_CONTROL_POINT_PATCH = 18, + D3D_PRIMITIVE_12_CONTROL_POINT_PATCH = 19, + D3D_PRIMITIVE_13_CONTROL_POINT_PATCH = 20, + D3D_PRIMITIVE_14_CONTROL_POINT_PATCH = 21, + D3D_PRIMITIVE_15_CONTROL_POINT_PATCH = 22, + D3D_PRIMITIVE_16_CONTROL_POINT_PATCH = 23, + D3D_PRIMITIVE_17_CONTROL_POINT_PATCH = 24, + D3D_PRIMITIVE_18_CONTROL_POINT_PATCH = 25, + D3D_PRIMITIVE_19_CONTROL_POINT_PATCH = 26, + D3D_PRIMITIVE_20_CONTROL_POINT_PATCH = 28, + D3D_PRIMITIVE_21_CONTROL_POINT_PATCH = 29, + D3D_PRIMITIVE_22_CONTROL_POINT_PATCH = 30, + D3D_PRIMITIVE_23_CONTROL_POINT_PATCH = 31, + D3D_PRIMITIVE_24_CONTROL_POINT_PATCH = 32, + D3D_PRIMITIVE_25_CONTROL_POINT_PATCH = 33, + D3D_PRIMITIVE_26_CONTROL_POINT_PATCH = 34, + D3D_PRIMITIVE_27_CONTROL_POINT_PATCH = 35, + D3D_PRIMITIVE_28_CONTROL_POINT_PATCH = 36, + D3D_PRIMITIVE_29_CONTROL_POINT_PATCH = 37, + D3D_PRIMITIVE_30_CONTROL_POINT_PATCH = 38, + D3D_PRIMITIVE_31_CONTROL_POINT_PATCH = 39, + D3D_PRIMITIVE_32_CONTROL_POINT_PATCH = 40, +}} +pub const D3D10_PRIMITIVE_UNDEFINED: ::D3D_PRIMITIVE = D3D_PRIMITIVE_UNDEFINED; +pub const D3D10_PRIMITIVE_POINT: ::D3D_PRIMITIVE = D3D_PRIMITIVE_POINT; +pub const D3D10_PRIMITIVE_LINE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE; +pub const D3D10_PRIMITIVE_TRIANGLE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE; +pub const D3D10_PRIMITIVE_LINE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE_ADJ; +pub const D3D10_PRIMITIVE_TRIANGLE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE_ADJ; +pub const D3D11_PRIMITIVE_UNDEFINED: ::D3D_PRIMITIVE = D3D_PRIMITIVE_UNDEFINED; +pub const D3D11_PRIMITIVE_POINT: ::D3D_PRIMITIVE = D3D_PRIMITIVE_POINT; +pub const D3D11_PRIMITIVE_LINE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE; +pub const D3D11_PRIMITIVE_TRIANGLE: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE; +pub const D3D11_PRIMITIVE_LINE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_LINE_ADJ; +pub const D3D11_PRIMITIVE_TRIANGLE_ADJ: ::D3D_PRIMITIVE = D3D_PRIMITIVE_TRIANGLE_ADJ; +pub const D3D11_PRIMITIVE_1_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_1_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_2_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_2_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_3_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_3_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_4_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_4_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_5_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_5_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_6_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_6_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_7_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_7_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_8_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_8_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_9_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_9_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_10_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_10_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_11_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_11_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_12_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_12_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_13_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_13_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_14_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_14_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_15_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_15_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_16_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_16_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_17_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_17_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_18_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_18_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_19_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_19_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_20_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_20_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_21_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_21_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_22_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_22_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_23_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_23_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_24_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_24_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_25_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_25_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_26_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_26_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_27_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_27_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_28_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_28_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_29_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_29_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_30_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_30_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_31_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_31_CONTROL_POINT_PATCH; +pub const D3D11_PRIMITIVE_32_CONTROL_POINT_PATCH: ::D3D_PRIMITIVE = + D3D_PRIMITIVE_32_CONTROL_POINT_PATCH; +ENUM!{enum D3D_SRV_DIMENSION { + D3D_SRV_DIMENSION_UNKNOWN = 0, + D3D_SRV_DIMENSION_BUFFER = 1, + D3D_SRV_DIMENSION_TEXTURE1D = 2, + D3D_SRV_DIMENSION_TEXTURE1DARRAY = 3, + D3D_SRV_DIMENSION_TEXTURE2D = 4, + D3D_SRV_DIMENSION_TEXTURE2DARRAY = 5, + D3D_SRV_DIMENSION_TEXTURE2DMS = 6, + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY = 7, + D3D_SRV_DIMENSION_TEXTURE3D = 8, + D3D_SRV_DIMENSION_TEXTURECUBE = 9, + D3D_SRV_DIMENSION_TEXTURECUBEARRAY = 10, + D3D_SRV_DIMENSION_BUFFEREX = 11, +}} +pub const D3D10_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D10_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D10_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D10_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D10_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D10_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D10_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D10_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D10_1_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D10_1_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D10_1_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D10_1_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D10_1_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D10_1_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D10_1_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D10_1_SRV_DIMENSION_TEXTURECUBEARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBEARRAY; +pub const D3D11_SRV_DIMENSION_UNKNOWN: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_UNKNOWN; +pub const D3D11_SRV_DIMENSION_BUFFER: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFER; +pub const D3D11_SRV_DIMENSION_TEXTURE1D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1D; +pub const D3D11_SRV_DIMENSION_TEXTURE1DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE1DARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE2D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2D; +pub const D3D11_SRV_DIMENSION_TEXTURE2DARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE2DMS: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMS; +pub const D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE2DMSARRAY; +pub const D3D11_SRV_DIMENSION_TEXTURE3D: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURE3D; +pub const D3D11_SRV_DIMENSION_TEXTURECUBE: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBE; +pub const D3D11_SRV_DIMENSION_TEXTURECUBEARRAY: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_TEXTURECUBEARRAY; +pub const D3D11_SRV_DIMENSION_BUFFEREX: ::D3D_SRV_DIMENSION = + D3D_SRV_DIMENSION_BUFFEREX; +STRUCT!{struct D3D_SHADER_MACRO { + Name: ::LPCSTR, + Definition: ::LPCSTR, +}} +pub type LPD3D_SHADER_MACRO = *mut D3D_SHADER_MACRO; +RIDL!( +interface ID3D10Blob(ID3D10BlobVtbl): IUnknown(IUnknownVtbl) { + fn GetBufferPointer(&mut self) -> ::LPVOID, + fn GetBufferSize(&mut self) -> ::SIZE_T +} +); +pub type LPD3D10BLOB = *mut ID3D10Blob; +pub type ID3DBlob = ID3D10Blob; +pub type LPD3DBLOB = *mut ID3DBlob; +ENUM!{enum D3D_INCLUDE_TYPE { + D3D_INCLUDE_LOCAL = 0, + D3D_INCLUDE_SYSTEM, +}} +pub const D3D10_INCLUDE_LOCAL: ::D3D_INCLUDE_TYPE = D3D_INCLUDE_LOCAL; +pub const D3D10_INCLUDE_SYSTEM: ::D3D_INCLUDE_TYPE = D3D_INCLUDE_SYSTEM; +RIDL!( +interface ID3DInclude(ID3DIncludeVtbl) { + fn Open( + &mut self, IncludeType: D3D_INCLUDE_TYPE, pFileName: ::LPCSTR, pParentData: ::LPCVOID, + ppData: *mut ::LPCVOID, pBytes: *mut ::UINT + ) -> ::HRESULT, + fn Close(&mut self, pData: ::LPCVOID) -> ::HRESULT +} +); +pub type LPD3DINCLUDE = *mut ID3DInclude; +ENUM!{enum D3D_SHADER_VARIABLE_CLASS { + D3D_SVC_SCALAR = 0, + D3D_SVC_VECTOR, + D3D_SVC_MATRIX_ROWS, + D3D_SVC_MATRIX_COLUMNS, + D3D_SVC_OBJECT, + D3D_SVC_STRUCT, + D3D_SVC_INTERFACE_CLASS, + D3D_SVC_INTERFACE_POINTER, +}} +pub const D3D10_SVC_SCALAR: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_SCALAR; +pub const D3D10_SVC_VECTOR: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_VECTOR; +pub const D3D10_SVC_MATRIX_ROWS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_MATRIX_ROWS; +pub const D3D10_SVC_MATRIX_COLUMNS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_MATRIX_COLUMNS; +pub const D3D10_SVC_OBJECT: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_OBJECT; +pub const D3D10_SVC_STRUCT: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_STRUCT; +pub const D3D11_SVC_INTERFACE_CLASS: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_INTERFACE_CLASS; +pub const D3D11_SVC_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_CLASS = D3D_SVC_INTERFACE_POINTER; +FLAGS!{enum D3D_SHADER_VARIABLE_FLAGS { + D3D_SVF_USERPACKED = 1, + D3D_SVF_USED = 2, + D3D_SVF_INTERFACE_POINTER = 4, + D3D_SVF_INTERFACE_PARAMETER = 8, +}} +pub const D3D10_SVF_USERPACKED: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_USERPACKED; +pub const D3D10_SVF_USED: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_USED; +pub const D3D11_SVF_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_INTERFACE_POINTER; +pub const D3D11_SVF_INTERFACE_PARAMETER: ::D3D_SHADER_VARIABLE_FLAGS = D3D_SVF_INTERFACE_PARAMETER; +ENUM!{enum D3D_SHADER_VARIABLE_TYPE { + D3D_SVT_VOID = 0, + D3D_SVT_BOOL = 1, + D3D_SVT_INT = 2, + D3D_SVT_FLOAT = 3, + D3D_SVT_STRING = 4, + D3D_SVT_TEXTURE = 5, + D3D_SVT_TEXTURE1D = 6, + D3D_SVT_TEXTURE2D = 7, + D3D_SVT_TEXTURE3D = 8, + D3D_SVT_TEXTURECUBE = 9, + D3D_SVT_SAMPLER = 10, + D3D_SVT_SAMPLER1D = 11, + D3D_SVT_SAMPLER2D = 12, + D3D_SVT_SAMPLER3D = 13, + D3D_SVT_SAMPLERCUBE = 14, + D3D_SVT_PIXELSHADER = 15, + D3D_SVT_VERTEXSHADER = 16, + D3D_SVT_PIXELFRAGMENT = 17, + D3D_SVT_VERTEXFRAGMENT = 18, + D3D_SVT_UINT = 19, + D3D_SVT_UINT8 = 20, + D3D_SVT_GEOMETRYSHADER = 21, + D3D_SVT_RASTERIZER = 22, + D3D_SVT_DEPTHSTENCIL = 23, + D3D_SVT_BLEND = 24, + D3D_SVT_BUFFER = 25, + D3D_SVT_CBUFFER = 26, + D3D_SVT_TBUFFER = 27, + D3D_SVT_TEXTURE1DARRAY = 28, + D3D_SVT_TEXTURE2DARRAY = 29, + D3D_SVT_RENDERTARGETVIEW = 30, + D3D_SVT_DEPTHSTENCILVIEW = 31, + D3D_SVT_TEXTURE2DMS = 32, + D3D_SVT_TEXTURE2DMSARRAY = 33, + D3D_SVT_TEXTURECUBEARRAY = 34, + D3D_SVT_HULLSHADER = 35, + D3D_SVT_DOMAINSHADER = 36, + D3D_SVT_INTERFACE_POINTER = 37, + D3D_SVT_COMPUTESHADER = 38, + D3D_SVT_DOUBLE = 39, + D3D_SVT_RWTEXTURE1D = 40, + D3D_SVT_RWTEXTURE1DARRAY = 41, + D3D_SVT_RWTEXTURE2D = 42, + D3D_SVT_RWTEXTURE2DARRAY = 43, + D3D_SVT_RWTEXTURE3D = 44, + D3D_SVT_RWBUFFER = 45, + D3D_SVT_BYTEADDRESS_BUFFER = 46, + D3D_SVT_RWBYTEADDRESS_BUFFER = 47, + D3D_SVT_STRUCTURED_BUFFER = 48, + D3D_SVT_RWSTRUCTURED_BUFFER = 49, + D3D_SVT_APPEND_STRUCTURED_BUFFER = 50, + D3D_SVT_CONSUME_STRUCTURED_BUFFER = 51, + D3D_SVT_MIN8FLOAT = 52, + D3D_SVT_MIN10FLOAT = 53, + D3D_SVT_MIN16FLOAT = 54, + D3D_SVT_MIN12INT = 55, + D3D_SVT_MIN16INT = 56, + D3D_SVT_MIN16UINT = 57, +}} +pub const D3D10_SVT_VOID: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VOID; +pub const D3D10_SVT_BOOL: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BOOL; +pub const D3D10_SVT_INT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_INT; +pub const D3D10_SVT_FLOAT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_FLOAT; +pub const D3D10_SVT_STRING: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_STRING; +pub const D3D10_SVT_TEXTURE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE; +pub const D3D10_SVT_TEXTURE1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE1D; +pub const D3D10_SVT_TEXTURE2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2D; +pub const D3D10_SVT_TEXTURE3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE3D; +pub const D3D10_SVT_TEXTURECUBE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURECUBE; +pub const D3D10_SVT_SAMPLER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER; +pub const D3D10_SVT_SAMPLER1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER1D; +pub const D3D10_SVT_SAMPLER2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER2D; +pub const D3D10_SVT_SAMPLER3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLER3D; +pub const D3D10_SVT_SAMPLERCUBE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_SAMPLERCUBE; +pub const D3D10_SVT_PIXELSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_PIXELSHADER; +pub const D3D10_SVT_VERTEXSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VERTEXSHADER; +pub const D3D10_SVT_PIXELFRAGMENT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_PIXELFRAGMENT; +pub const D3D10_SVT_VERTEXFRAGMENT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_VERTEXFRAGMENT; +pub const D3D10_SVT_UINT: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_UINT; +pub const D3D10_SVT_UINT8: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_UINT8; +pub const D3D10_SVT_GEOMETRYSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_GEOMETRYSHADER; +pub const D3D10_SVT_RASTERIZER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RASTERIZER; +pub const D3D10_SVT_DEPTHSTENCIL: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DEPTHSTENCIL; +pub const D3D10_SVT_BLEND: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BLEND; +pub const D3D10_SVT_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BUFFER; +pub const D3D10_SVT_CBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_CBUFFER; +pub const D3D10_SVT_TBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TBUFFER; +pub const D3D10_SVT_TEXTURE1DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE1DARRAY; +pub const D3D10_SVT_TEXTURE2DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DARRAY; +pub const D3D10_SVT_RENDERTARGETVIEW: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RENDERTARGETVIEW; +pub const D3D10_SVT_DEPTHSTENCILVIEW: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DEPTHSTENCILVIEW; +pub const D3D10_SVT_TEXTURE2DMS: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DMS; +pub const D3D10_SVT_TEXTURE2DMSARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURE2DMSARRAY; +pub const D3D10_SVT_TEXTURECUBEARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_TEXTURECUBEARRAY; +pub const D3D11_SVT_HULLSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_HULLSHADER; +pub const D3D11_SVT_DOMAINSHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DOMAINSHADER; +pub const D3D11_SVT_INTERFACE_POINTER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_INTERFACE_POINTER; +pub const D3D11_SVT_COMPUTESHADER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_COMPUTESHADER; +pub const D3D11_SVT_DOUBLE: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_DOUBLE; +pub const D3D11_SVT_RWTEXTURE1D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE1D; +pub const D3D11_SVT_RWTEXTURE1DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE1DARRAY; +pub const D3D11_SVT_RWTEXTURE2D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE2D; +pub const D3D11_SVT_RWTEXTURE2DARRAY: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE2DARRAY; +pub const D3D11_SVT_RWTEXTURE3D: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWTEXTURE3D; +pub const D3D11_SVT_RWBUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_RWBUFFER; +pub const D3D11_SVT_BYTEADDRESS_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = D3D_SVT_BYTEADDRESS_BUFFER; +pub const D3D11_SVT_RWBYTEADDRESS_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_RWBYTEADDRESS_BUFFER; +pub const D3D11_SVT_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_STRUCTURED_BUFFER; +pub const D3D11_SVT_RWSTRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_RWSTRUCTURED_BUFFER; +pub const D3D11_SVT_APPEND_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_APPEND_STRUCTURED_BUFFER; +pub const D3D11_SVT_CONSUME_STRUCTURED_BUFFER: ::D3D_SHADER_VARIABLE_TYPE = + D3D_SVT_CONSUME_STRUCTURED_BUFFER; +FLAGS!{enum D3D_SHADER_INPUT_FLAGS { + D3D_SIF_USERPACKED = 0x1, + D3D_SIF_COMPARISON_SAMPLER = 0x2, + D3D_SIF_TEXTURE_COMPONENT_0 = 0x4, + D3D_SIF_TEXTURE_COMPONENT_1 = 0x8, + D3D_SIF_TEXTURE_COMPONENTS = 0xc, + D3D_SIF_UNUSED = 0x10, +}} +pub const D3D10_SIF_USERPACKED: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_USERPACKED; +pub const D3D10_SIF_COMPARISON_SAMPLER: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_COMPARISON_SAMPLER; +pub const D3D10_SIF_TEXTURE_COMPONENT_0: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENT_0; +pub const D3D10_SIF_TEXTURE_COMPONENT_1: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENT_1; +pub const D3D10_SIF_TEXTURE_COMPONENTS: ::D3D_SHADER_INPUT_FLAGS = D3D_SIF_TEXTURE_COMPONENTS; +ENUM!{enum D3D_SHADER_INPUT_TYPE { + D3D_SIT_CBUFFER, + D3D_SIT_TBUFFER, + D3D_SIT_TEXTURE, + D3D_SIT_SAMPLER, + D3D_SIT_UAV_RWTYPED, + D3D_SIT_STRUCTURED, + D3D_SIT_UAV_RWSTRUCTURED, + D3D_SIT_BYTEADDRESS, + D3D_SIT_UAV_RWBYTEADDRESS, + D3D_SIT_UAV_APPEND_STRUCTURED, + D3D_SIT_UAV_CONSUME_STRUCTURED, + D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER, +}} +pub const D3D10_SIT_CBUFFER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_CBUFFER; +pub const D3D10_SIT_TBUFFER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_TBUFFER; +pub const D3D10_SIT_TEXTURE: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_TEXTURE; +pub const D3D10_SIT_SAMPLER: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_SAMPLER; +pub const D3D11_SIT_UAV_RWTYPED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWTYPED; +pub const D3D11_SIT_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_STRUCTURED; +pub const D3D11_SIT_UAV_RWSTRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWSTRUCTURED; +pub const D3D11_SIT_BYTEADDRESS: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_BYTEADDRESS; +pub const D3D11_SIT_UAV_RWBYTEADDRESS: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_RWBYTEADDRESS; +pub const D3D11_SIT_UAV_APPEND_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = D3D_SIT_UAV_APPEND_STRUCTURED; +pub const D3D11_SIT_UAV_CONSUME_STRUCTURED: ::D3D_SHADER_INPUT_TYPE = + D3D_SIT_UAV_CONSUME_STRUCTURED; +pub const D3D11_SIT_UAV_RWSTRUCTURED_WITH_COUNTER: ::D3D_SHADER_INPUT_TYPE = + D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER; +FLAGS!{enum D3D_SHADER_CBUFFER_FLAGS { + D3D_CBF_USERPACKED = 1, +}} +pub const D3D10_CBF_USERPACKED: ::D3D_SHADER_CBUFFER_FLAGS = D3D_CBF_USERPACKED; +ENUM!{enum D3D_CBUFFER_TYPE { + D3D_CT_CBUFFER, + D3D_CT_TBUFFER, + D3D_CT_INTERFACE_POINTERS, + D3D_CT_RESOURCE_BIND_INFO, +}} +pub const D3D10_CT_CBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_CBUFFER; +pub const D3D10_CT_TBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_TBUFFER; +pub const D3D11_CT_CBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_CBUFFER; +pub const D3D11_CT_TBUFFER: ::D3D_CBUFFER_TYPE = D3D_CT_TBUFFER; +pub const D3D11_CT_INTERFACE_POINTERS: ::D3D_CBUFFER_TYPE = D3D_CT_INTERFACE_POINTERS; +pub const D3D11_CT_RESOURCE_BIND_INFO: ::D3D_CBUFFER_TYPE = D3D_CT_RESOURCE_BIND_INFO; +ENUM!{enum D3D_NAME { + D3D_NAME_UNDEFINED = 0, + D3D_NAME_POSITION = 1, + D3D_NAME_CLIP_DISTANCE = 2, + D3D_NAME_CULL_DISTANCE = 3, + D3D_NAME_RENDER_TARGET_ARRAY_INDEX = 4, + D3D_NAME_VIEWPORT_ARRAY_INDEX = 5, + D3D_NAME_VERTEX_ID = 6, + D3D_NAME_PRIMITIVE_ID = 7, + D3D_NAME_INSTANCE_ID = 8, + D3D_NAME_IS_FRONT_FACE = 9, + D3D_NAME_SAMPLE_INDEX = 10, + D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR = 11, + D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR = 12, + D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR = 13, + D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 14, + D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 15, + D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 16, + D3D_NAME_TARGET = 64, + D3D_NAME_DEPTH = 65, + D3D_NAME_COVERAGE = 66, + D3D_NAME_DEPTH_GREATER_EQUAL = 67, + D3D_NAME_DEPTH_LESS_EQUAL = 68, +}} +pub const D3D10_NAME_UNDEFINED: D3D_NAME = D3D_NAME_UNDEFINED; +pub const D3D10_NAME_POSITION: D3D_NAME = D3D_NAME_POSITION; +pub const D3D10_NAME_CLIP_DISTANCE: D3D_NAME = D3D_NAME_CLIP_DISTANCE; +pub const D3D10_NAME_CULL_DISTANCE: D3D_NAME = D3D_NAME_CULL_DISTANCE; +pub const D3D10_NAME_RENDER_TARGET_ARRAY_INDEX: D3D_NAME = D3D_NAME_RENDER_TARGET_ARRAY_INDEX; +pub const D3D10_NAME_VIEWPORT_ARRAY_INDEX: D3D_NAME = D3D_NAME_VIEWPORT_ARRAY_INDEX; +pub const D3D10_NAME_VERTEX_ID: D3D_NAME = D3D_NAME_VERTEX_ID; +pub const D3D10_NAME_PRIMITIVE_ID: D3D_NAME = D3D_NAME_PRIMITIVE_ID; +pub const D3D10_NAME_INSTANCE_ID: D3D_NAME = D3D_NAME_INSTANCE_ID; +pub const D3D10_NAME_IS_FRONT_FACE: D3D_NAME = D3D_NAME_IS_FRONT_FACE; +pub const D3D10_NAME_SAMPLE_INDEX: D3D_NAME = D3D_NAME_SAMPLE_INDEX; +pub const D3D10_NAME_TARGET: D3D_NAME = D3D_NAME_TARGET; +pub const D3D10_NAME_DEPTH: D3D_NAME = D3D_NAME_DEPTH; +pub const D3D10_NAME_COVERAGE: D3D_NAME = D3D_NAME_COVERAGE; +pub const D3D11_NAME_FINAL_QUAD_EDGE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR; +pub const D3D11_NAME_FINAL_QUAD_INSIDE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR; +pub const D3D11_NAME_FINAL_TRI_EDGE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR; +pub const D3D11_NAME_FINAL_TRI_INSIDE_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR; +pub const D3D11_NAME_FINAL_LINE_DETAIL_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR; +pub const D3D11_NAME_FINAL_LINE_DENSITY_TESSFACTOR: D3D_NAME = D3D_NAME_FINAL_LINE_DENSITY_TESSFACTOR; +pub const D3D11_NAME_DEPTH_GREATER_EQUAL: D3D_NAME = D3D_NAME_DEPTH_GREATER_EQUAL; +pub const D3D11_NAME_DEPTH_LESS_EQUAL: D3D_NAME = D3D_NAME_DEPTH_LESS_EQUAL; +ENUM!{enum D3D_RESOURCE_RETURN_TYPE { + D3D_RETURN_TYPE_UNORM = 1, + D3D_RETURN_TYPE_SNORM = 2, + D3D_RETURN_TYPE_SINT = 3, + D3D_RETURN_TYPE_UINT = 4, + D3D_RETURN_TYPE_FLOAT = 5, + D3D_RETURN_TYPE_MIXED = 6, + D3D_RETURN_TYPE_DOUBLE = 7, + D3D_RETURN_TYPE_CONTINUED = 8, +}} +pub const D3D10_RETURN_TYPE_UNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UNORM; +pub const D3D10_RETURN_TYPE_SNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SNORM; +pub const D3D10_RETURN_TYPE_SINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SINT; +pub const D3D10_RETURN_TYPE_UINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UINT; +pub const D3D10_RETURN_TYPE_FLOAT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_FLOAT; +pub const D3D10_RETURN_TYPE_MIXED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_MIXED; +pub const D3D11_RETURN_TYPE_UNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UNORM; +pub const D3D11_RETURN_TYPE_SNORM: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SNORM; +pub const D3D11_RETURN_TYPE_SINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_SINT; +pub const D3D11_RETURN_TYPE_UINT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_UINT; +pub const D3D11_RETURN_TYPE_FLOAT: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_FLOAT; +pub const D3D11_RETURN_TYPE_MIXED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_MIXED; +pub const D3D11_RETURN_TYPE_DOUBLE: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_DOUBLE; +pub const D3D11_RETURN_TYPE_CONTINUED: ::D3D_RESOURCE_RETURN_TYPE = D3D_RETURN_TYPE_CONTINUED; +ENUM!{enum D3D_REGISTER_COMPONENT_TYPE { + D3D_REGISTER_COMPONENT_UNKNOWN = 0, + D3D_REGISTER_COMPONENT_UINT32 = 1, + D3D_REGISTER_COMPONENT_SINT32 = 2, + D3D_REGISTER_COMPONENT_FLOAT32 = 3, +}} +pub const D3D10_REGISTER_COMPONENT_UNKNOWN: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_UNKNOWN; +pub const D3D10_REGISTER_COMPONENT_UINT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_UINT32; +pub const D3D10_REGISTER_COMPONENT_SINT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_SINT32; +pub const D3D10_REGISTER_COMPONENT_FLOAT32: ::D3D_REGISTER_COMPONENT_TYPE = + D3D_REGISTER_COMPONENT_FLOAT32; +ENUM!{enum D3D_TESSELLATOR_DOMAIN { + D3D_TESSELLATOR_DOMAIN_UNDEFINED, + D3D_TESSELLATOR_DOMAIN_ISOLINE, + D3D_TESSELLATOR_DOMAIN_TRI, + D3D_TESSELLATOR_DOMAIN_QUAD, +}} +pub const D3D11_TESSELLATOR_DOMAIN_UNDEFINED: ::D3D_TESSELLATOR_DOMAIN = + D3D_TESSELLATOR_DOMAIN_UNDEFINED; +pub const D3D11_TESSELLATOR_DOMAIN_ISOLINE: ::D3D_TESSELLATOR_DOMAIN = + D3D_TESSELLATOR_DOMAIN_ISOLINE; +pub const D3D11_TESSELLATOR_DOMAIN_TRI: ::D3D_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN_TRI; +pub const D3D11_TESSELLATOR_DOMAIN_QUAD: ::D3D_TESSELLATOR_DOMAIN = D3D_TESSELLATOR_DOMAIN_QUAD; +ENUM!{enum D3D_TESSELLATOR_PARTITIONING { + D3D_TESSELLATOR_PARTITIONING_UNDEFINED, + D3D_TESSELLATOR_PARTITIONING_INTEGER, + D3D_TESSELLATOR_PARTITIONING_POW2, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD, + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN, +}} +pub const D3D11_TESSELLATOR_PARTITIONING_UNDEFINED: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_UNDEFINED; +pub const D3D11_TESSELLATOR_PARTITIONING_INTEGER: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_INTEGER; +pub const D3D11_TESSELLATOR_PARTITIONING_POW2: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_POW2; +pub const D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD; +pub const D3D11_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN: ::D3D_TESSELLATOR_PARTITIONING = + D3D_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN; +ENUM!{enum D3D_TESSELLATOR_OUTPUT_PRIMITIVE { + D3D_TESSELLATOR_OUTPUT_UNDEFINED, + D3D_TESSELLATOR_OUTPUT_POINT, + D3D_TESSELLATOR_OUTPUT_LINE, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW, + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW, +}} +pub const D3D11_TESSELLATOR_OUTPUT_UNDEFINED: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_UNDEFINED; +pub const D3D11_TESSELLATOR_OUTPUT_POINT: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_POINT; +pub const D3D11_TESSELLATOR_OUTPUT_LINE: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_LINE; +pub const D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CW: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CW; +pub const D3D11_TESSELLATOR_OUTPUT_TRIANGLE_CCW: ::D3D_TESSELLATOR_OUTPUT_PRIMITIVE = + D3D_TESSELLATOR_OUTPUT_TRIANGLE_CCW; +ENUM!{enum D3D_MIN_PRECISION { + D3D_MIN_PRECISION_DEFAULT, + D3D_MIN_PRECISION_FLOAT_16, + D3D_MIN_PRECISION_FLOAT_2_8, + D3D_MIN_PRECISION_RESERVED, + D3D_MIN_PRECISION_SINT_16, + D3D_MIN_PRECISION_UINT_16, + D3D_MIN_PRECISION_ANY_16 = 0xf0, + D3D_MIN_PRECISION_ANY_10 = 0xf1, +}} +ENUM!{enum D3D_INTERPOLATION_MODE { + D3D_INTERPOLATION_UNDEFINED, + D3D_INTERPOLATION_CONSTANT, + D3D_INTERPOLATION_LINEAR, + D3D_INTERPOLATION_LINEAR_CENTROID, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_CENTROID, + D3D_INTERPOLATION_LINEAR_SAMPLE, + D3D_INTERPOLATION_LINEAR_NOPERSPECTIVE_SAMPLE, +}} +FLAGS!{enum D3D_PARAMETER_FLAGS { + D3D_PF_NONE = 0, + D3D_PF_IN = 0x1, + D3D_PF_OUT = 0x2, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/d3dcompiler.rs b/third_party/cargo/vendor/winapi-0.2.8/src/d3dcompiler.rs new file mode 100644 index 0000000..6918888 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/d3dcompiler.rs @@ -0,0 +1,74 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub const D3DCOMPILER_DLL: &'static str = "d3dcompiler_47.dll"; +pub const D3D_COMPILER_VERSION: DWORD = 47; +pub const D3DCOMPILE_DEBUG: DWORD = 1 << 0; +pub const D3DCOMPILE_SKIP_VALIDATION: DWORD = 1 << 1; +pub const D3DCOMPILE_SKIP_OPTIMIZATION: DWORD = 1 << 2; +pub const D3DCOMPILE_PACK_MATRIX_ROW_MAJOR: DWORD = 1 << 3; +pub const D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR: DWORD = 1 << 4; +pub const D3DCOMPILE_PARTIAL_PRECISION: DWORD = 1 << 5; +pub const D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT: DWORD = 1 << 6; +pub const D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT: DWORD = 1 << 7; +pub const D3DCOMPILE_NO_PRESHADER: DWORD = 1 << 8; +pub const D3DCOMPILE_AVOID_FLOW_CONTROL: DWORD = 1 << 9; +pub const D3DCOMPILE_PREFER_FLOW_CONTROL: DWORD = 1 << 10; +pub const D3DCOMPILE_ENABLE_STRICTNESS: DWORD = 1 << 11; +pub const D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY: DWORD = 1 << 12; +pub const D3DCOMPILE_IEEE_STRICTNESS: DWORD = 1 << 13; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL0: DWORD = 1 << 14; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL1: DWORD = 0; +pub const D3DCOMPILE_OPTIMIZATION_LEVEL2: DWORD = (1 << 14) | (1 << 15); +pub const D3DCOMPILE_OPTIMIZATION_LEVEL3: DWORD = 1 << 15; +pub const D3DCOMPILE_RESERVED16: DWORD = 1 << 16; +pub const D3DCOMPILE_RESERVED17: DWORD = 1 << 17; +pub const D3DCOMPILE_WARNINGS_ARE_ERRORS: DWORD = 1 << 18; +pub const D3DCOMPILE_RESOURCES_MAY_ALIAS: DWORD = 1 << 19; +pub const D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES: DWORD = 1 << 20; +pub const D3DCOMPILE_ALL_RESOURCES_BOUND: DWORD = 1 << 21; +pub const D3DCOMPILE_EFFECT_CHILD_EFFECT: DWORD = 1 << 0; +pub const D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS: DWORD = 1 << 1; +pub const D3D_COMPILE_STANDARD_FILE_INCLUDE: *mut ID3DInclude = 1 as *mut ID3DInclude; +pub const D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS: DWORD = 0x00000001; +pub const D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS: DWORD = 0x00000002; +pub const D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH: DWORD = 0x00000004; +pub const D3D_DISASM_ENABLE_COLOR_CODE: DWORD = 0x00000001; +pub const D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS: DWORD = 0x00000002; +pub const D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING: DWORD = 0x00000004; +pub const D3D_DISASM_ENABLE_INSTRUCTION_CYCLE: DWORD = 0x00000008; +pub const D3D_DISASM_DISABLE_DEBUG_INFO: DWORD = 0x00000010; +pub const D3D_DISASM_ENABLE_INSTRUCTION_OFFSET: DWORD = 0x00000020; +pub const D3D_DISASM_INSTRUCTION_ONLY: DWORD = 0x00000040; +pub const D3D_DISASM_PRINT_HEX_LITERALS: DWORD = 0x00000080; +pub const D3D_GET_INST_OFFSETS_INCLUDE_NON_EXECUTABLE: DWORD = 0x00000001; +FLAGS!{enum D3DCOMPILER_STRIP_FLAGS { + D3DCOMPILER_STRIP_REFLECTION_DATA = 0x00000001, + D3DCOMPILER_STRIP_DEBUG_INFO = 0x00000002, + D3DCOMPILER_STRIP_TEST_BLOBS = 0x00000004, + D3DCOMPILER_STRIP_PRIVATE_DATA = 0x00000008, + D3DCOMPILER_STRIP_ROOT_SIGNATURE = 0x00000010, + D3DCOMPILER_STRIP_FORCE_DWORD = 0x7fffffff, +}} +ENUM!{enum D3D_BLOB_PART { + D3D_BLOB_INPUT_SIGNATURE_BLOB, + D3D_BLOB_OUTPUT_SIGNATURE_BLOB, + D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB, + D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB, + D3D_BLOB_ALL_SIGNATURE_BLOB, + D3D_BLOB_DEBUG_INFO, + D3D_BLOB_LEGACY_SHADER, + D3D_BLOB_XNA_PREPASS_SHADER, + D3D_BLOB_XNA_SHADER, + D3D_BLOB_PDB, + D3D_BLOB_PRIVATE_DATA, + D3D_BLOB_ROOT_SIGNATURE, + D3D_BLOB_TEST_ALTERNATE_SHADER = 0x8000, + D3D_BLOB_TEST_COMPILE_DETAILS, + D3D_BLOB_TEST_COMPILE_PERF, + D3D_BLOB_TEST_COMPILE_REPORT, +}} +STRUCT!{struct D3D_SHADER_DATA { + pBytecode: LPCVOID, + BytecodeLength: SIZE_T, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dbghelp.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dbghelp.rs new file mode 100644 index 0000000..8c20d72 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dbghelp.rs @@ -0,0 +1,340 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! DbgHelp include file +#[cfg(target_arch = "x86_64")] +STRUCT!{struct LOADED_IMAGE { + ModuleName: ::PSTR, + hFile: ::HANDLE, + MappedAddress: ::PUCHAR, + FileHeader: ::PIMAGE_NT_HEADERS64, + LastRvaSection: ::PIMAGE_SECTION_HEADER, + NumberOfSections: ::ULONG, + Sections: ::PIMAGE_SECTION_HEADER, + Characteristics: ::ULONG, + fSystemImage: ::BOOLEAN, + fDOSImage: ::BOOLEAN, + fReadOnly: ::BOOLEAN, + Version: ::UCHAR, + Links: ::LIST_ENTRY, + SizeOfImage: ::ULONG, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct LOADED_IMAGE { + ModuleName: ::PSTR, + hFile: ::HANDLE, + MappedAddress: ::PUCHAR, + FileHeader: ::PIMAGE_NT_HEADERS32, + LastRvaSection: ::PIMAGE_SECTION_HEADER, + NumberOfSections: ::ULONG, + Sections: ::PIMAGE_SECTION_HEADER, + Characteristics: ::ULONG, + fSystemImage: ::BOOLEAN, + fDOSImage: ::BOOLEAN, + fReadOnly: ::BOOLEAN, + Version: ::UCHAR, + Links: ::LIST_ENTRY, + SizeOfImage: ::ULONG, +}} +pub const MAX_SYM_NAME: usize = 2000; +pub const ERROR_IMAGE_NOT_STRIPPED: ::DWORD = 0x8800; +pub const ERROR_NO_DBG_POINTER: ::DWORD = 0x8801; +pub const ERROR_NO_PDB_POINTER: ::DWORD = 0x8802; +pub type PFIND_DEBUG_FILE_CALLBACK = Option ::BOOL>; +pub type PFIND_DEBUG_FILE_CALLBACKW = Option ::BOOL>; +pub type PFINDFILEINPATHCALLBACK = Option ::BOOL>; +pub type PFINDFILEINPATHCALLBACKW = Option ::BOOL>; +pub type PFIND_EXE_FILE_CALLBACK = Option ::BOOL>; +pub type PFIND_EXE_FILE_CALLBACKW = Option ::BOOL>; +#[cfg(target_arch = "x86")] +STRUCT!{struct IMAGE_DEBUG_INFORMATION { + List: ::LIST_ENTRY, + ReservedSize: ::DWORD, + ReservedMappedBase: ::PVOID, + ReservedMachine: ::USHORT, + ReservedCharacteristics: ::USHORT, + ReservedCheckSum: ::DWORD, + ImageBase: ::DWORD, + SizeOfImage: ::DWORD, + ReservedNumberOfSections: ::DWORD, + ReservedSections: ::PIMAGE_SECTION_HEADER, + ReservedExportedNamesSize: ::DWORD, + ReservedExportedNames: ::PSTR, + ReservedNumberOfFunctionTableEntries: ::DWORD, + ReservedFunctionTableEntries: ::PIMAGE_FUNCTION_ENTRY, + ReservedLowestFunctionStartingAddress: ::DWORD, + ReservedHighestFunctionEndingAddress: ::DWORD, + ReservedNumberOfFpoTableEntries: ::DWORD, + ReservedFpoTableEntries: ::PFPO_DATA, + SizeOfCoffSymbols: ::DWORD, + CoffSymbols: ::PIMAGE_COFF_SYMBOLS_HEADER, + ReservedSizeOfCodeViewSymbols: ::DWORD, + ReservedCodeViewSymbols: ::PVOID, + ImageFilePath: ::PSTR, + ImageFileName: ::PSTR, + ReservedDebugFilePath: ::PSTR, + ReservedTimeDateStamp: ::DWORD, + ReservedRomImage: ::BOOL, + ReservedDebugDirectory: ::PIMAGE_DEBUG_DIRECTORY, + ReservedNumberOfDebugDirectories: ::DWORD, + ReservedOriginalFunctionTableBaseAddress: ::DWORD, + Reserved: [::DWORD; 2], +}} +#[cfg(target_arch = "x86")] +pub type PIMAGE_DEBUG_INFORMATION = *mut IMAGE_DEBUG_INFORMATION; +pub type PENUMDIRTREE_CALLBACK = Option ::BOOL>; +pub type PENUMDIRTREE_CALLBACKW = Option ::BOOL>; +pub const UNDNAME_COMPLETE: ::DWORD = 0x0000; +pub const UNDNAME_NO_LEADING_UNDERSCORES: ::DWORD = 0x0001; +pub const UNDNAME_NO_MS_KEYWORDS: ::DWORD = 0x0002; +pub const UNDNAME_NO_FUNCTION_RETURNS: ::DWORD = 0x0004; +pub const UNDNAME_NO_ALLOCATION_MODEL: ::DWORD = 0x0008; +pub const UNDNAME_NO_ALLOCATION_LANGUAGE: ::DWORD = 0x0010; +pub const UNDNAME_NO_MS_THISTYPE: ::DWORD = 0x0020; +pub const UNDNAME_NO_CV_THISTYPE: ::DWORD = 0x0040; +pub const UNDNAME_NO_THISTYPE: ::DWORD = 0x0060; +pub const UNDNAME_NO_ACCESS_SPECIFIERS: ::DWORD = 0x0080; +pub const UNDNAME_NO_THROW_SIGNATURES: ::DWORD = 0x0100; +pub const UNDNAME_NO_MEMBER_TYPE: ::DWORD = 0x0200; +pub const UNDNAME_NO_RETURN_UDT_MODEL: ::DWORD = 0x0400; +pub const UNDNAME_32_BIT_DECODE: ::DWORD = 0x0800; +pub const UNDNAME_NAME_ONLY: ::DWORD = 0x1000; +pub const UNDNAME_NO_ARGUMENTS: ::DWORD = 0x2000; +pub const UNDNAME_NO_SPECIAL_SYMS: ::DWORD = 0x4000; +pub const DBHHEADER_DEBUGDIRS: ::DWORD = 0x1; +pub const DBHHEADER_CVMISC: ::DWORD = 0x2; +pub const DBHHEADER_PDBGUID: ::DWORD = 0x3; +STRUCT!{struct MODLOAD_DATA { + ssize: ::DWORD, + ssig: ::DWORD, + data: ::PVOID, + size: ::DWORD, + flags: ::DWORD, +}} +pub type PMODLOAD_DATA = *mut MODLOAD_DATA; +STRUCT!{struct MODLOAD_CVMISC { + oCV: ::DWORD, + cCV: ::size_t, + oMisc: ::DWORD, + cMisc: ::size_t, + dtImage: ::DWORD, + cImage: ::DWORD, +}} +pub type PMODLOAD_CVMISC = *mut MODLOAD_CVMISC; +STRUCT!{struct MODLOAD_PDBGUID_PDBAGE { + PdbGuid: ::GUID, + PdbAge: ::DWORD, +}} +pub type PMODLOAD_PDBGUID_PDBAGE = *mut MODLOAD_PDBGUID_PDBAGE; +ENUM!{enum ADDRESS_MODE { + AddrMode1616, + AddrMode1632, + AddrModeReal, + AddrModeFlat, +}} +STRUCT!{struct ADDRESS64 { + Offset: ::DWORD64, + Segment: ::WORD, + Mode: ::ADDRESS_MODE, +}} +pub type LPADDRESS64 = *mut ADDRESS64; +#[cfg(target_arch = "x86_64")] +pub type ADDRESS = ADDRESS64; +#[cfg(target_arch = "x86_64")] +pub type LPADDRESS = LPADDRESS64; +#[cfg(target_arch = "x86")] +STRUCT!{struct ADDRESS { + Offset: ::DWORD, + Segment: ::WORD, + Mode: ::ADDRESS_MODE, +}} +#[cfg(target_arch = "x86")] +pub type LPADDRESS = *mut ADDRESS; +STRUCT!{struct KDHELP64 { + Thread: ::DWORD64, + ThCallbackStack: ::DWORD, + ThCallbackBStore: ::DWORD, + NextCallback: ::DWORD, + FramePointer: ::DWORD, + KiCallUserMode: ::DWORD64, + KeUserCallbackDispatcher: ::DWORD64, + SystemRangeStart: ::DWORD64, + KiUserExceptionDispatcher: ::DWORD64, + StackBase: ::DWORD64, + StackLimit: ::DWORD64, + BuildVersion: ::DWORD, + Reserved0: ::DWORD, + Reserved1: [::DWORD64; 4], +}} +pub type PKDHELP64 = *mut KDHELP64; +#[cfg(target_arch = "x86_64")] +pub type KDHELP = KDHELP64; +#[cfg(target_arch = "x86_64")] +pub type PKDHELP = PKDHELP64; +#[cfg(target_arch = "x86")] +STRUCT!{struct KDHELP { + Thread: ::DWORD, + ThCallbackStack: ::DWORD, + NextCallback: ::DWORD, + FramePointer: ::DWORD, + KiCallUserMode: ::DWORD, + KeUserCallbackDispatcher: ::DWORD, + SystemRangeStart: ::DWORD, + ThCallbackBStore: ::DWORD, + KiUserExceptionDispatcher: ::DWORD, + StackBase: ::DWORD, + StackLimit: ::DWORD, + Reserved: [::DWORD; 5], +}} +#[cfg(target_arch = "x86")] +pub type PKDHELP = *mut KDHELP; +STRUCT!{struct STACKFRAME64 { + AddrPC: ::ADDRESS64, + AddrReturn: ::ADDRESS64, + AddrFrame: ::ADDRESS64, + AddrStack: ::ADDRESS64, + AddrBStore: ::ADDRESS64, + FuncTableEntry: ::PVOID, + Params: [::DWORD64; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD64; 3], + KdHelp: ::KDHELP64, +}} +pub type LPSTACKFRAME64 = *mut STACKFRAME64; +pub const INLINE_FRAME_CONTEXT_INIT: ::DWORD = 0; +pub const INLINE_FRAME_CONTEXT_IGNORE: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct STACKFRAME_EX { + AddrPC: ::ADDRESS64, + AddrReturn: ::ADDRESS64, + AddrFrame: ::ADDRESS64, + AddrStack: ::ADDRESS64, + AddrBStore: ::ADDRESS64, + FuncTableEntry: ::PVOID, + Params: [::DWORD64; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD64; 3], + KdHelp: ::KDHELP64, + StackFrameSize: ::DWORD, + InlineFrameContext: ::DWORD, +}} +pub type LPSTACKFRAME_EX = *mut STACKFRAME_EX; +#[cfg(target_arch = "x86_64")] +pub type STACKFRAME = STACKFRAME64; +#[cfg(target_arch = "x86_64")] +pub type LPSTACKFRAME = LPSTACKFRAME64; +#[cfg(target_arch = "x86")] +STRUCT!{struct STACKFRAME { + AddrPC: ::ADDRESS, + AddrReturn: ::ADDRESS, + AddrFrame: ::ADDRESS, + AddrStack: ::ADDRESS, + FuncTableEntry: ::PVOID, + Params: [::DWORD; 4], + Far: ::BOOL, + Virtual: ::BOOL, + Reserved: [::DWORD; 3], + KdHelp: ::KDHELP, + AddrBStore: ::ADDRESS, +}} +#[cfg(target_arch = "x86")] +pub type LPSTACKFRAME = *mut STACKFRAME; +pub type PREAD_PROCESS_MEMORY_ROUTINE64 = Option ::BOOL>; +pub type PFUNCTION_TABLE_ACCESS_ROUTINE64 = Option ::PVOID>; +pub type PGET_MODULE_BASE_ROUTINE64 = Option ::DWORD64>; +pub type PTRANSLATE_ADDRESS_ROUTINE64 = Option ::DWORD64>; +pub const SYM_STKWALK_DEFAULT: ::DWORD = 0x00000000; +pub const SYM_STKWALK_FORCE_FRAMEPTR: ::DWORD = 0x00000001; +#[cfg(target_arch = "x86_64")] +pub type PREAD_PROCESS_MEMORY_ROUTINE = PREAD_PROCESS_MEMORY_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PFUNCTION_TABLE_ACCESS_ROUTINE = PFUNCTION_TABLE_ACCESS_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PGET_MODULE_BASE_ROUTINE = PGET_MODULE_BASE_ROUTINE64; +#[cfg(target_arch = "x86_64")] +pub type PTRANSLATE_ADDRESS_ROUTINE = PTRANSLATE_ADDRESS_ROUTINE64; +#[cfg(target_arch = "x86")] +pub type PREAD_PROCESS_MEMORY_ROUTINE = Option ::BOOL>; +#[cfg(target_arch = "x86")] +pub type PFUNCTION_TABLE_ACCESS_ROUTINE = Option ::PVOID>; +#[cfg(target_arch = "x86")] +pub type PGET_MODULE_BASE_ROUTINE = Option ::DWORD>; +#[cfg(target_arch = "x86")] +pub type PTRANSLATE_ADDRESS_ROUTINE = Option ::DWORD>; +pub const API_VERSION_NUMBER: ::USHORT = 12; +STRUCT!{struct API_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, + Revision: ::USHORT, + Reserved: ::USHORT, +}} +pub type LPAPI_VERSION = *mut API_VERSION; +STRUCT!{struct SYMBOL_INFOW { + SizeOfStruct: ::ULONG, + TypeIndex: ::ULONG, + Reserved: [::ULONG64; 2], + Index: ::ULONG, + Size: ::ULONG, + ModBase: ::ULONG64, + Flags: ::ULONG, + Value: ::ULONG64, + Address: ::ULONG64, + Register: ::ULONG, + Scope: ::ULONG, + Tag: ::ULONG, + NameLen: ::ULONG, + MaxNameLen: ::ULONG, + Name: [::WCHAR; 1], +}} +pub type PSYMBOL_INFOW = *mut SYMBOL_INFOW; +STRUCT!{struct IMAGEHLP_SYMBOL64 { + SizeOfStruct: ::DWORD, + Address: ::DWORD64, + Size: ::DWORD, + Flags: ::DWORD, + MaxNameLength: ::DWORD, + Name: [::CHAR; 1], +}} +pub type PIMAGEHLP_SYMBOL64 = *mut IMAGEHLP_SYMBOL64; +STRUCT!{struct IMAGEHLP_LINEW64 { + SizeOfStruct: ::DWORD, + Key: ::PVOID, + LineNumber: ::DWORD, + FileName: ::PWSTR, + Address: ::DWORD64, +}} +pub type PIMAGEHLP_LINEW64 = *mut IMAGEHLP_LINEW64; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dcommon.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dcommon.rs new file mode 100644 index 0000000..2c220e3 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dcommon.rs @@ -0,0 +1,18 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of dcommon.h +ENUM!{enum DWRITE_MEASURING_MODE { + DWRITE_MEASURING_MODE_NATURAL = 0, + DWRITE_MEASURING_MODE_GDI_CLASSIC = 1, + DWRITE_MEASURING_MODE_GDI_NATURAL = 2, +}} +ENUM!{enum D2D1_ALPHA_MODE { + D2D1_ALPHA_MODE_UNKNOWN = 0, + D2D1_ALPHA_MODE_PREMULTIPLIED = 1, + D2D1_ALPHA_MODE_STRAIGHT = 2, + D2D1_ALPHA_MODE_IGNORE = 3, +}} +STRUCT!{struct D2D1_PIXEL_FORMAT { + format: ::DXGI_FORMAT, + alphaMode: D2D1_ALPHA_MODE, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/devpropdef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/devpropdef.rs new file mode 100644 index 0000000..3deca43 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/devpropdef.rs @@ -0,0 +1,71 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Defines property types and keys for the Plug and Play Device Property API +pub type DEVPROPTYPE = ::ULONG; +pub type PDEVPROPTYPE = *mut ::ULONG; +pub const DEVPROP_TYPEMOD_ARRAY: DEVPROPTYPE = 0x00001000; +pub const DEVPROP_TYPEMOD_LIST: DEVPROPTYPE = 0x00002000; +pub const DEVPROP_TYPE_EMPTY: DEVPROPTYPE = 0x00000000; +pub const DEVPROP_TYPE_NULL: DEVPROPTYPE = 0x00000001; +pub const DEVPROP_TYPE_SBYTE: DEVPROPTYPE = 0x00000002; +pub const DEVPROP_TYPE_BYTE: DEVPROPTYPE = 0x00000003; +pub const DEVPROP_TYPE_INT16: DEVPROPTYPE = 0x00000004; +pub const DEVPROP_TYPE_UINT16: DEVPROPTYPE = 0x00000005; +pub const DEVPROP_TYPE_INT32: DEVPROPTYPE = 0x00000006; +pub const DEVPROP_TYPE_UINT32: DEVPROPTYPE = 0x00000007; +pub const DEVPROP_TYPE_INT64: DEVPROPTYPE = 0x00000008; +pub const DEVPROP_TYPE_UINT64: DEVPROPTYPE = 0x00000009; +pub const DEVPROP_TYPE_FLOAT: DEVPROPTYPE = 0x0000000A; +pub const DEVPROP_TYPE_DOUBLE: DEVPROPTYPE = 0x0000000B; +pub const DEVPROP_TYPE_DECIMAL: DEVPROPTYPE = 0x0000000C; +pub const DEVPROP_TYPE_GUID: DEVPROPTYPE = 0x0000000D; +pub const DEVPROP_TYPE_CURRENCY: DEVPROPTYPE = 0x0000000E; +pub const DEVPROP_TYPE_DATE: DEVPROPTYPE = 0x0000000F; +pub const DEVPROP_TYPE_FILETIME: DEVPROPTYPE = 0x00000010; +pub const DEVPROP_TYPE_BOOLEAN: DEVPROPTYPE = 0x00000011; +pub const DEVPROP_TYPE_STRING: DEVPROPTYPE = 0x00000012; +pub const DEVPROP_TYPE_STRING_LIST: DEVPROPTYPE = DEVPROP_TYPE_STRING | DEVPROP_TYPEMOD_LIST; +pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR: DEVPROPTYPE = 0x00000013; +pub const DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING: DEVPROPTYPE = 0x00000014; +pub const DEVPROP_TYPE_DEVPROPKEY: DEVPROPTYPE = 0x00000015; +pub const DEVPROP_TYPE_DEVPROPTYPE: DEVPROPTYPE = 0x00000016; +pub const DEVPROP_TYPE_BINARY: DEVPROPTYPE = DEVPROP_TYPE_BYTE | DEVPROP_TYPEMOD_ARRAY; +pub const DEVPROP_TYPE_ERROR: DEVPROPTYPE = 0x00000017; +pub const DEVPROP_TYPE_NTSTATUS: DEVPROPTYPE = 0x00000018; +pub const DEVPROP_TYPE_STRING_INDIRECT: DEVPROPTYPE = 0x00000019; +pub const MAX_DEVPROP_TYPE: DEVPROPTYPE = 0x00000019; +pub const MAX_DEVPROP_TYPEMOD: DEVPROPTYPE = 0x00002000; +pub const DEVPROP_MASK_TYPE: DEVPROPTYPE = 0x00000FFF; +pub const DEVPROP_MASK_TYPEMOD: DEVPROPTYPE = 0x0000F000; +pub type DEVPROP_BOOLEAN = ::CHAR; +pub type PDEVPROP_BOOLEAN = *mut ::CHAR; +pub const DEVPROP_TRUE: DEVPROP_BOOLEAN = -1; +pub const DEVPROP_FALSE: DEVPROP_BOOLEAN = 0; +pub type DEVPROPGUID = ::GUID; +pub type PDEVPROPGUID = *mut ::GUID; +pub type DEVPROPID = ::ULONG; +pub type PDEVPROPID = *mut ::ULONG; +STRUCT!{struct DEVPROPKEY { + fmtid: DEVPROPGUID, + pid: DEVPROPID, +}} +pub type PDEVPROPKEY = *mut DEVPROPKEY; +ENUM!{enum DEVPROPSTORE { + DEVPROP_STORE_SYSTEM, + DEVPROP_STORE_USER, +}} +pub type PDEVPROPSTORE = *mut DEVPROPSTORE; +STRUCT!{struct DEVPROPCOMPKEY { + Key: DEVPROPKEY, + Store: DEVPROPSTORE, + LocaleName: ::PCWSTR, +}} +pub type PDEVPROPCOMPKEY = *mut DEVPROPCOMPKEY; +STRUCT!{struct DEVPROPERTY { + CompKey: DEVPROPCOMPKEY, + Type: DEVPROPTYPE, + BufferSize: ::ULONG, + Buffer: ::PVOID, +}} +pub type PDEVPROPERTY = *mut DEVPROPERTY; +pub const DEVPROPID_FIRST_USABLE: DEVPROPID = 2; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/docobj.rs b/third_party/cargo/vendor/winapi-0.2.8/src/docobj.rs new file mode 100644 index 0000000..3d5f904 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/docobj.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +STRUCT!{struct OLECMD { + cmdID: ::ULONG, + cmdf: ::DWORD, +}} +STRUCT!{struct OLECMDTEXT { + cmdtextf: ::DWORD, + cwActual: ::ULONG, + cwBuf: ::ULONG, + rgwz: [::wchar_t; 0], +}} +RIDL!{interface IOleCommandTarget(IOleCommandTargetVtbl): IUnknown(IUnknownVtbl) { + fn QueryStatus( + &mut self, pguidCmdGroup: *const ::GUID, cCmds: ::ULONG, prgCmds: *mut OLECMD, + pCmdText: *mut OLECMDTEXT + ) -> ::HRESULT, + fn Exec( + &mut self, pguidCmdGroup: *const :: GUID, nCmdID: ::DWORD, nCmdexecopt: ::DWORD, + pvaIn: *mut ::VARIANT, pvaOut: *mut ::VARIANT + ) -> ::HRESULT +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dpapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dpapi.rs new file mode 100644 index 0000000..c62e56f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dpapi.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Data Protection API Prototypes and Definitions +pub const szFORCE_KEY_PROTECTION: &'static str = "ForceKeyProtection"; +STRUCT!{struct CRYPTPROTECT_PROMPTSTRUCT { + cbSize: ::DWORD, + dwPromptFlags: ::DWORD, + hwndApp: ::HWND, + szPrompt: ::LPCWSTR, +}} +pub type PCRYPTPROTECT_PROMPTSTRUCT = *mut CRYPTPROTECT_PROMPTSTRUCT; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dsgetdc.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dsgetdc.rs new file mode 100644 index 0000000..09c81c0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dsgetdc.rs @@ -0,0 +1,113 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! This file contains structures, function prototypes, and definitions for the DsGetDcName API. +pub const DS_FORCE_REDISCOVERY: ::ULONG = 0x00000001; +pub const DS_DIRECTORY_SERVICE_REQUIRED: ::ULONG = 0x00000010; +pub const DS_DIRECTORY_SERVICE_PREFERRED: ::ULONG = 0x00000020; +pub const DS_GC_SERVER_REQUIRED: ::ULONG = 0x00000040; +pub const DS_PDC_REQUIRED: ::ULONG = 0x00000080; +pub const DS_BACKGROUND_ONLY: ::ULONG = 0x00000100; +pub const DS_IP_REQUIRED: ::ULONG = 0x00000200; +pub const DS_KDC_REQUIRED: ::ULONG = 0x00000400; +pub const DS_TIMESERV_REQUIRED: ::ULONG = 0x00000800; +pub const DS_WRITABLE_REQUIRED: ::ULONG = 0x00001000; +pub const DS_GOOD_TIMESERV_PREFERRED: ::ULONG = 0x00002000; +pub const DS_AVOID_SELF: ::ULONG = 0x00004000; +pub const DS_ONLY_LDAP_NEEDED: ::ULONG = 0x00008000; +pub const DS_IS_FLAT_NAME: ::ULONG = 0x00010000; +pub const DS_IS_DNS_NAME: ::ULONG = 0x00020000; +pub const DS_TRY_NEXTCLOSEST_SITE: ::ULONG = 0x00040000; +pub const DS_DIRECTORY_SERVICE_6_REQUIRED: ::ULONG = 0x00080000; +pub const DS_WEB_SERVICE_REQUIRED: ::ULONG = 0x00100000; +pub const DS_DIRECTORY_SERVICE_8_REQUIRED: ::ULONG = 0x00200000; +pub const DS_DIRECTORY_SERVICE_9_REQUIRED: ::ULONG = 0x00400000; +pub const DS_RETURN_DNS_NAME: ::ULONG = 0x40000000; +pub const DS_RETURN_FLAT_NAME: ::ULONG = 0x80000000; +pub const DSGETDC_VALID_FLAGS: ::ULONG = DS_FORCE_REDISCOVERY | DS_DIRECTORY_SERVICE_REQUIRED + | DS_DIRECTORY_SERVICE_PREFERRED | DS_GC_SERVER_REQUIRED | DS_PDC_REQUIRED | DS_BACKGROUND_ONLY + | DS_IP_REQUIRED | DS_KDC_REQUIRED | DS_TIMESERV_REQUIRED | DS_WRITABLE_REQUIRED + | DS_GOOD_TIMESERV_PREFERRED | DS_AVOID_SELF | DS_ONLY_LDAP_NEEDED | DS_IS_FLAT_NAME + | DS_IS_DNS_NAME | DS_TRY_NEXTCLOSEST_SITE | DS_DIRECTORY_SERVICE_6_REQUIRED + | DS_DIRECTORY_SERVICE_8_REQUIRED | DS_DIRECTORY_SERVICE_9_REQUIRED | DS_WEB_SERVICE_REQUIRED + | DS_RETURN_FLAT_NAME | DS_RETURN_DNS_NAME; +STRUCT!{struct DOMAIN_CONTROLLER_INFOA { + DomainControllerName: ::LPSTR, + DomainControllerAddress: ::LPSTR, + DomainControllerAddressType: ::ULONG, + DomainGuid: ::GUID, + DomainName: ::LPSTR, + DnsForestName: ::LPSTR, + Flags: ::ULONG, + DcSiteName: ::LPSTR, + ClientSiteName: ::LPSTR, +}} +pub type PDOMAIN_CONTROLLER_INFOA = *mut DOMAIN_CONTROLLER_INFOA; +STRUCT!{struct DOMAIN_CONTROLLER_INFOW { + DomainControllerName: ::LPWSTR, + DomainControllerAddress: ::LPWSTR, + DomainControllerAddressType: ::ULONG, + DomainGuid: ::GUID, + DomainName: ::LPWSTR, + DnsForestName: ::LPWSTR, + Flags: ::ULONG, + DcSiteName: ::LPWSTR, + ClientSiteName: ::LPWSTR, +}} +pub type PDOMAIN_CONTROLLER_INFOW = *mut DOMAIN_CONTROLLER_INFOW; +pub const DS_INET_ADDRESS: ::ULONG = 1; +pub const DS_NETBIOS_ADDRESS: ::ULONG = 2; +pub const DS_PDC_FLAG: ::ULONG = 0x00000001; +pub const DS_GC_FLAG: ::ULONG = 0x00000004; +pub const DS_LDAP_FLAG: ::ULONG = 0x00000008; +pub const DS_DS_FLAG: ::ULONG = 0x00000010; +pub const DS_KDC_FLAG: ::ULONG = 0x00000020; +pub const DS_TIMESERV_FLAG: ::ULONG = 0x00000040; +pub const DS_CLOSEST_FLAG: ::ULONG = 0x00000080; +pub const DS_WRITABLE_FLAG: ::ULONG = 0x00000100; +pub const DS_GOOD_TIMESERV_FLAG: ::ULONG = 0x00000200; +pub const DS_NDNC_FLAG: ::ULONG = 0x00000400; +pub const DS_SELECT_SECRET_DOMAIN_6_FLAG: ::ULONG = 0x00000800; +pub const DS_FULL_SECRET_DOMAIN_6_FLAG: ::ULONG = 0x00001000; +pub const DS_WS_FLAG: ::ULONG = 0x00002000; +pub const DS_DS_8_FLAG: ::ULONG = 0x00004000; +pub const DS_DS_9_FLAG: ::ULONG = 0x00008000; +pub const DS_PING_FLAGS: ::ULONG = 0x000FFFFF; +pub const DS_DNS_CONTROLLER_FLAG: ::ULONG = 0x20000000; +pub const DS_DNS_DOMAIN_FLAG: ::ULONG = 0x40000000; +pub const DS_DNS_FOREST_FLAG: ::ULONG = 0x80000000; +pub const DS_DOMAIN_IN_FOREST: ::ULONG = 0x0001; +pub const DS_DOMAIN_DIRECT_OUTBOUND: ::ULONG = 0x0002; +pub const DS_DOMAIN_TREE_ROOT: ::ULONG = 0x0004; +pub const DS_DOMAIN_PRIMARY: ::ULONG = 0x0008; +pub const DS_DOMAIN_NATIVE_MODE: ::ULONG = 0x0010; +pub const DS_DOMAIN_DIRECT_INBOUND: ::ULONG = 0x0020; +pub const DS_DOMAIN_VALID_FLAGS: ::ULONG = DS_DOMAIN_IN_FOREST | DS_DOMAIN_DIRECT_OUTBOUND + | DS_DOMAIN_TREE_ROOT | DS_DOMAIN_PRIMARY | DS_DOMAIN_NATIVE_MODE | DS_DOMAIN_DIRECT_INBOUND; +STRUCT!{struct DS_DOMAIN_TRUSTSW { + NetbiosDomainName: ::LPWSTR, + DnsDomainName: ::LPWSTR, + Flags: ::ULONG, + ParentIndex: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + DomainSid: ::PSID, + DomainGuid: ::GUID, +}} +pub type PDS_DOMAIN_TRUSTSW = *mut DS_DOMAIN_TRUSTSW; +STRUCT!{struct DS_DOMAIN_TRUSTSA { + NetbiosDomainName: ::LPSTR, + DnsDomainName: ::LPSTR, + Flags: ::ULONG, + ParentIndex: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + DomainSid: ::PSID, + DomainGuid: ::GUID, +}} +pub type PDS_DOMAIN_TRUSTSA = *mut DS_DOMAIN_TRUSTSA; +pub const DS_ONLY_DO_SITE_NAME: ::ULONG = 0x01; +pub const DS_NOTIFY_AFTER_SITE_RECORDS: ::ULONG = 0x02; +pub const DS_OPEN_VALID_OPTION_FLAGS: ::ULONG = DS_ONLY_DO_SITE_NAME + | DS_NOTIFY_AFTER_SITE_RECORDS; +pub const DS_OPEN_VALID_FLAGS: ::ULONG = DS_FORCE_REDISCOVERY | DS_ONLY_LDAP_NEEDED + | DS_KDC_REQUIRED | DS_PDC_REQUIRED | DS_GC_SERVER_REQUIRED | DS_WRITABLE_REQUIRED; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dsound.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dsound.rs new file mode 100644 index 0000000..e8f167f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dsound.rs @@ -0,0 +1,132 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! DSound procedure declarations, constant definitions and macros +STRUCT!{struct DSCAPS { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwMinSecondarySampleRate: ::DWORD, + dwMaxSecondarySampleRate: ::DWORD, + dwPrimaryBuffers: ::DWORD, + dwMaxHwMixingAllBuffers: ::DWORD, + dwMaxHwMixingStaticBuffers: ::DWORD, + dwMaxHwMixingStreamingBuffers: ::DWORD, + dwFreeHwMixingAllBuffers: ::DWORD, + dwFreeHwMixingStaticBuffers: ::DWORD, + dwFreeHwMixingStreamingBuffers: ::DWORD, + dwMaxHw3DAllBuffers: ::DWORD, + dwMaxHw3DStaticBuffers: ::DWORD, + dwMaxHw3DStreamingBuffers: ::DWORD, + dwFreeHw3DAllBuffers: ::DWORD, + dwFreeHw3DStaticBuffers: ::DWORD, + dwFreeHw3DStreamingBuffers: ::DWORD, + dwTotalHwMemBytes: ::DWORD, + dwFreeHwMemBytes: ::DWORD, + dwMaxContigFreeHwMemBytes: ::DWORD, + dwUnlockTransferRateHwBuffers: ::DWORD, + dwPlayCpuOverheadSwBuffers: ::DWORD, + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +pub type LPDSCAPS = *mut DSCAPS; +STRUCT!{struct DSBCAPS { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwBufferBytes: ::DWORD, + dwUnlockTransferRate: ::DWORD, + dwPlayCpuOverhead: ::DWORD, +}} +pub type LPDSBCAPS = *mut DSBCAPS; +STRUCT!{struct DSBUFFERDESC { + dwSize: ::DWORD, + dwFlags: ::DWORD, + dwBufferBytes: ::DWORD, + dwReserved: ::DWORD, + lpwfxFormat: ::LPWAVEFORMATEX, + guid3DAlgorithm: ::GUID, +}} +pub type LPCDSBUFFERDESC = *const DSBUFFERDESC; +RIDL!( +interface IDirectSoundBuffer(IDirectSoundBufferVtbl): IUnknown(IUnknownVtbl) { + fn GetCaps(&mut self, pDSBufferCaps: ::LPDSBCAPS) -> ::HRESULT, + fn GetCurrentPosition( + &mut self, pdwCurrentPlayCursor: ::LPDWORD, pdwCurrentWriteCursor: ::LPDWORD + ) -> ::HRESULT, + fn GetFormat( + &mut self, pwfxFormat: ::LPWAVEFORMATEX, dwSizeAllocated: ::DWORD, + pdwSizeWritten: ::LPDWORD + ) -> ::HRESULT, + fn GetVolume(&mut self, plVolume: ::LPLONG) -> ::HRESULT, + fn GetPan(&mut self, plPan: ::LPLONG) -> ::HRESULT, + fn GetFrequency(&mut self, pdwFrequency: ::LPDWORD) -> ::HRESULT, + fn GetStatus(&mut self, pdwStatus: ::LPDWORD) -> ::HRESULT, + fn Initialize( + &mut self, pDirectSound: ::LPDIRECTSOUND, pcDSBufferDesc: ::LPCDSBUFFERDESC + ) -> ::HRESULT, + fn Lock( + &mut self, dwOffset: ::DWORD, dwBytes: ::DWORD, ppvAudioPtr1: *mut ::LPVOID, + pdwAudioBytes1: ::LPDWORD, ppvAudioPtr2: *mut ::LPVOID, pdwAudioBytes2: ::LPDWORD, + dwFlags: ::DWORD + ) -> ::HRESULT, + fn Play(&mut self, dwReserved1: ::DWORD, dwPriority: ::DWORD, dwFlags: ::DWORD) -> ::HRESULT, + fn SetCurrentPosition(&mut self, dwNewPosition: ::DWORD) -> ::HRESULT, + fn SetFormat(&mut self, pcfxFormat: ::LPCWAVEFORMATEX) -> ::HRESULT, + fn SetVolume(&mut self, lVolume: ::LONG) -> ::HRESULT, + fn SetPan(&mut self, lPan: ::LONG) -> ::HRESULT, + fn SetFrequency(&mut self, dwFrequency: ::DWORD) -> ::HRESULT, + fn Stop(&mut self) -> ::HRESULT, + fn Unlock( + &mut self, pvAudioPtr1: ::LPVOID, dwAudioBytes1: ::DWORD, pvAudioPtr2: ::LPVOID, + dwAudioBytes2: ::DWORD + ) -> ::HRESULT, + fn Restore(&mut self) -> ::HRESULT +} +); +pub type LPDIRECTSOUNDBUFFER = *mut IDirectSoundBuffer; +RIDL!( +interface IDirectSound(IDirectSoundVtbl): IUnknown(IUnknownVtbl) +{ + fn CreateSoundBuffer( + &mut self, pcDSBufferDesc: ::LPCDSBUFFERDESC, ppDSBuffer: *mut ::LPDIRECTSOUNDBUFFER, + pUnkOuter: ::LPUNKNOWN + ) -> ::HRESULT, + fn GetCaps(&mut self, pDSCaps: ::LPDSCAPS) -> ::HRESULT, + fn DuplicateSoundBuffer( + &mut self, pDSBufferOriginal: LPDIRECTSOUNDBUFFER, + ppDSBufferDuplicate: *mut ::LPDIRECTSOUNDBUFFER + ) -> ::HRESULT, + fn SetCooperativeLevel(&mut self, hWnd: ::HWND, dwLevel: ::DWORD) -> ::HRESULT, + fn Compact(&mut self) -> ::HRESULT, + fn GetSpeakerConfig(&mut self, pdwSpeakerConfig: ::LPDWORD) -> ::HRESULT, + fn SetSpeakerConfig(&mut self, dwSpeakerConfig: ::DWORD) -> ::HRESULT, + fn Initialize(&mut self, pcGuidDevice: ::LPCGUID) -> ::HRESULT +} +); +pub type LPDIRECTSOUND = *mut IDirectSound; +pub const DS_OK: ::HRESULT = ::S_OK; +pub const DSERR_GENERIC: ::HRESULT = ::E_FAIL; +pub const DSSCL_NORMAL: ::DWORD = 0x00000001; +pub const DSSCL_PRIORITY: ::DWORD = 0x00000002; +pub const DSSCL_EXCLUSIVE: ::DWORD = 0x00000003; +pub const DSSCL_WRITEPRIMARY: ::DWORD = 0x00000004; +pub const DSBCAPS_PRIMARYBUFFER: ::DWORD = 0x00000001; +pub const DSBCAPS_STATIC: ::DWORD = 0x00000002; +pub const DSBCAPS_LOCHARDWARE: ::DWORD = 0x00000004; +pub const DSBCAPS_LOCSOFTWARE: ::DWORD = 0x00000008; +pub const DSBCAPS_CTRL3D: ::DWORD = 0x00000010; +pub const DSBCAPS_CTRLFREQUENCY: ::DWORD = 0x00000020; +pub const DSBCAPS_CTRLPAN: ::DWORD = 0x00000040; +pub const DSBCAPS_CTRLVOLUME: ::DWORD = 0x00000080; +pub const DSBCAPS_CTRLPOSITIONNOTIFY: ::DWORD = 0x00000100; +pub const DSBCAPS_CTRLFX: ::DWORD = 0x00000200; +pub const DSBCAPS_STICKYFOCUS: ::DWORD = 0x00004000; +pub const DSBCAPS_GLOBALFOCUS: ::DWORD = 0x00008000; +pub const DSBCAPS_GETCURRENTPOSITION2: ::DWORD = 0x00010000; +pub const DSBCAPS_MUTE3DATMAXDISTANCE: ::DWORD = 0x00020000; +pub const DSBCAPS_LOCDEFER: ::DWORD = 0x00040000; +pub const DSBCAPS_TRUEPLAYPOSITION: ::DWORD = 0x00080000; +pub const DSBPLAY_LOOPING: ::DWORD = 0x00000001; +pub const DSBPLAY_LOCHARDWARE: ::DWORD = 0x00000002; +pub const DSBPLAY_LOCSOFTWARE: ::DWORD = 0x00000004; +pub const DSBPLAY_TERMINATEBY_TIME: ::DWORD = 0x00000008; +pub const DSBPLAY_TERMINATEBY_DISTANCE: ::DWORD = 0x000000010; +pub const DSBPLAY_TERMINATEBY_PRIORITY: ::DWORD = 0x000000020; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dsrole.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dsrole.rs new file mode 100644 index 0000000..f9cf81c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dsrole.rs @@ -0,0 +1,50 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Contains public interfaces to query the network roles of workstations, servers, and DCs +ENUM!{enum DSROLE_MACHINE_ROLE { + DsRole_RoleStandaloneWorkstation, + DsRole_RoleMemberWorkstation, + DsRole_RoleStandaloneServer, + DsRole_RoleMemberServer, + DsRole_RoleBackupDomainController, + DsRole_RolePrimaryDomainController, +}} +ENUM!{enum DSROLE_SERVER_STATE { + DsRoleServerUnknown = 0, + DsRoleServerPrimary, + DsRoleServerBackup, +}} +pub type PDSROLE_SERVER_STATE = *mut DSROLE_SERVER_STATE; +ENUM!{enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL { + DsRolePrimaryDomainInfoBasic = 1, + DsRoleUpgradeStatus, + DsRoleOperationState, +}} +pub const DSROLE_PRIMARY_DS_RUNNING: ::ULONG = 0x00000001; +pub const DSROLE_PRIMARY_DS_MIXED_MODE: ::ULONG = 0x00000002; +pub const DSROLE_UPGRADE_IN_PROGRESS: ::ULONG = 0x00000004; +pub const DSROLE_PRIMARY_DS_READONLY: ::ULONG = 0x00000008; +pub const DSROLE_PRIMARY_DOMAIN_GUID_PRESENT: ::ULONG = 0x01000000; +STRUCT!{struct DSROLE_PRIMARY_DOMAIN_INFO_BASIC { + MachineRole: DSROLE_MACHINE_ROLE, + Flags: ::ULONG, + DomainNameFlat: ::LPWSTR, + DomainNameDns: ::LPWSTR, + DomainForestName: ::LPWSTR, + DomainGuid: ::GUID, +}} +pub type PDSROLE_PRIMARY_DOMAIN_INFO_BASIC = *mut DSROLE_PRIMARY_DOMAIN_INFO_BASIC; +STRUCT!{struct DSROLE_UPGRADE_STATUS_INFO { + OperationState: ::ULONG, + PreviousServerState: DSROLE_SERVER_STATE, +}} +pub type PDSROLE_UPGRADE_STATUS_INFO = *mut DSROLE_UPGRADE_STATUS_INFO; +ENUM!{enum DSROLE_OPERATION_STATE { + DsRoleOperationIdle = 0, + DsRoleOperationActive, + DsRoleOperationNeedReboot, +}} +STRUCT!{struct DSROLE_OPERATION_STATE_INFO { + OperationState: DSROLE_OPERATION_STATE, +}} +pub type PDSROLE_OPERATION_STATE_INFO = *mut DSROLE_OPERATION_STATE_INFO; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dwmapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dwmapi.rs new file mode 100644 index 0000000..f95e8f1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dwmapi.rs @@ -0,0 +1,9 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Procedure declarations, constant definitions, and macros for the NLS component. +STRUCT!{struct DWM_BLURBEHIND { + dwFlags: ::DWORD, + fEnable: ::BOOL, + hRgnBlur: ::HRGN, + fTransitionOnMaximized: ::BOOL, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dwrite.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dwrite.rs new file mode 100644 index 0000000..09bbf0d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dwrite.rs @@ -0,0 +1,1038 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! DirectX Typography Services public API definitions. +ENUM!{enum DWRITE_FONT_FILE_TYPE { + DWRITE_FONT_FILE_TYPE_UNKNOWN, + DWRITE_FONT_FILE_TYPE_CFF, + DWRITE_FONT_FILE_TYPE_TRUETYPE, + DWRITE_FONT_FILE_TYPE_TRUETYPE_COLLECTION, + DWRITE_FONT_FILE_TYPE_TYPE1_PFM, + DWRITE_FONT_FILE_TYPE_TYPE1_PFB, + DWRITE_FONT_FILE_TYPE_VECTOR, + DWRITE_FONT_FILE_TYPE_BITMAP, +}} +ENUM!{enum DWRITE_FONT_FACE_TYPE { + DWRITE_FONT_FACE_TYPE_CFF, + DWRITE_FONT_FACE_TYPE_TRUETYPE, + DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION, + DWRITE_FONT_FACE_TYPE_TYPE1, + DWRITE_FONT_FACE_TYPE_VECTOR, + DWRITE_FONT_FACE_TYPE_BITMAP, + DWRITE_FONT_FACE_TYPE_UNKNOWN, + DWRITE_FONT_FACE_TYPE_RAW_CFF, +}} +FLAGS!{enum DWRITE_FONT_SIMULATIONS { + DWRITE_FONT_SIMULATIONS_NONE = 0x0000, + DWRITE_FONT_SIMULATIONS_BOLD = 0x0001, + DWRITE_FONT_SIMULATIONS_OBLIQUE = 0x0002, +}} +ENUM!{enum DWRITE_FONT_WEIGHT { + DWRITE_FONT_WEIGHT_THIN = 100, + DWRITE_FONT_WEIGHT_EXTRA_LIGHT = 200, + DWRITE_FONT_WEIGHT_ULTRA_LIGHT = 200, + DWRITE_FONT_WEIGHT_LIGHT = 300, + DWRITE_FONT_WEIGHT_SEMI_LIGHT = 350, + DWRITE_FONT_WEIGHT_NORMAL = 400, + DWRITE_FONT_WEIGHT_REGULAR = 400, + DWRITE_FONT_WEIGHT_MEDIUM = 500, + DWRITE_FONT_WEIGHT_DEMI_BOLD = 600, + DWRITE_FONT_WEIGHT_SEMI_BOLD = 600, + DWRITE_FONT_WEIGHT_BOLD = 700, + DWRITE_FONT_WEIGHT_EXTRA_BOLD = 800, + DWRITE_FONT_WEIGHT_ULTRA_BOLD = 800, + DWRITE_FONT_WEIGHT_BLACK = 900, + DWRITE_FONT_WEIGHT_HEAVY = 900, + DWRITE_FONT_WEIGHT_EXTRA_BLACK = 950, + DWRITE_FONT_WEIGHT_ULTRA_BLACK = 950, +}} +ENUM!{enum DWRITE_FONT_STRETCH { + DWRITE_FONT_STRETCH_UNDEFINED = 0, + DWRITE_FONT_STRETCH_ULTRA_CONDENSED = 1, + DWRITE_FONT_STRETCH_EXTRA_CONDENSED = 2, + DWRITE_FONT_STRETCH_CONDENSED = 3, + DWRITE_FONT_STRETCH_SEMI_CONDENSED = 4, + DWRITE_FONT_STRETCH_NORMAL = 5, + DWRITE_FONT_STRETCH_MEDIUM = 5, + DWRITE_FONT_STRETCH_SEMI_EXPANDED = 6, + DWRITE_FONT_STRETCH_EXPANDED = 7, + DWRITE_FONT_STRETCH_EXTRA_EXPANDED = 8, + DWRITE_FONT_STRETCH_ULTRA_EXPANDED = 9, +}} +ENUM!{enum DWRITE_FONT_STYLE { + DWRITE_FONT_STYLE_NORMAL, + DWRITE_FONT_STYLE_OBLIQUE, + DWRITE_FONT_STYLE_ITALIC, +}} +ENUM!{enum DWRITE_INFORMATIONAL_STRING_ID { + DWRITE_INFORMATIONAL_STRING_NONE, + DWRITE_INFORMATIONAL_STRING_COPYRIGHT_NOTICE, + DWRITE_INFORMATIONAL_STRING_VERSION_STRINGS, + DWRITE_INFORMATIONAL_STRING_TRADEMARK, + DWRITE_INFORMATIONAL_STRING_MANUFACTURER, + DWRITE_INFORMATIONAL_STRING_DESIGNER, + DWRITE_INFORMATIONAL_STRING_DESIGNER_URL, + DWRITE_INFORMATIONAL_STRING_DESCRIPTION, + DWRITE_INFORMATIONAL_STRING_FONT_VENDOR_URL, + DWRITE_INFORMATIONAL_STRING_LICENSE_DESCRIPTION, + DWRITE_INFORMATIONAL_STRING_LICENSE_INFO_URL, + DWRITE_INFORMATIONAL_STRING_WIN32_FAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_WIN32_SUBFAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_PREFERRED_FAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_PREFERRED_SUBFAMILY_NAMES, + DWRITE_INFORMATIONAL_STRING_SAMPLE_TEXT, + DWRITE_INFORMATIONAL_STRING_FULL_NAME, + DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME, + DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_CID_NAME, + DWRITE_INFORMATIONAL_STRING_WWS_FAMILY_NAME, + DWRITE_INFORMATIONAL_STRING_DESIGN_SCRIPT_LANGUAGE_TAG, + DWRITE_INFORMATIONAL_STRING_SUPPORTED_SCRIPT_LANGUAGE_TAG, +}} +STRUCT!{struct DWRITE_FONT_METRICS { + designUnitsPerEm: ::UINT16, + ascent: ::UINT16, + descent: ::UINT16, + lineGap: ::INT16, + capHeight: ::UINT16, + xHeight: ::UINT16, + underlinePosition: ::INT16, + underlineThickness: ::UINT16, + strikethroughPosition: ::INT16, + strikethroughThickness: ::UINT16, +}} +STRUCT!{struct DWRITE_GLYPH_METRICS { + leftSideBearing: ::INT32, + advanceWidth: ::UINT32, + rightSideBearing: ::INT32, + topSideBearing: ::INT32, + advanceHeight: ::UINT32, + bottomSideBearing: ::INT32, + verticalOriginY: ::INT32, +}} +STRUCT!{struct DWRITE_GLYPH_OFFSET { + advanceOffset: ::FLOAT, + ascenderOffset: ::FLOAT, +}} +ENUM!{enum DWRITE_FACTORY_TYPE { + DWRITE_FACTORY_TYPE_SHARED, + DWRITE_FACTORY_TYPE_ISOLATED, +}} +#[inline] +pub fn DWRITE_MAKE_OPENTYPE_TAG(a: u8, b: u8, c: u8, d: u8) -> u32 { + ((d as u32) << 24) | ((c as u32) << 16) | ((b as u32) << 8) | (a as u32) +} +RIDL!{interface IDWriteFontFileLoader(IDWriteFontFileLoaderVtbl): IUnknown(IUnknownVtbl) { + fn CreateStreamFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + fontFileStream: *mut *mut IDWriteFontFileStream + ) -> ::HRESULT +}} +RIDL!{interface IDWriteLocalFontFileLoader(IDWriteLocalFontFileLoaderVtbl): + IDWriteFontFileLoader(IDWriteFontFileLoaderVtbl) { + fn GetFilePathLengthFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + filePathLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetFilePathFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + filePath: *mut ::WCHAR, + filePathSize: ::UINT32 + ) -> ::HRESULT, + fn GetLastWriteTimeFromKey( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + lastWriteTime: *mut ::FILETIME + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFileStream(IDWriteFontFileStreamVtbl): IUnknown(IUnknownVtbl) { + fn ReadFileFragment( + &mut self, fragmentStart: *mut *const ::c_void, fileOffset: ::UINT64, + fragmentSize: ::UINT64, fragmentContext: *mut *mut ::c_void + ) -> ::HRESULT, + fn ReleaseFileFragment(&mut self, fragmentContext: *mut ::c_void) -> (), + fn GetFileSize(&mut self, fileSize: *mut ::UINT64) -> ::HRESULT, + fn GetLastWriteTime(&mut self, lastWriteTime: *mut ::UINT64) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFile(IDWriteFontFileVtbl): IUnknown(IUnknownVtbl) { + fn GetReferenceKey( + &mut self, fontFileReferenceKey: *mut *const ::c_void, + fontFileReferenceKeySize: *mut ::UINT32 + ) -> ::HRESULT, + fn GetLoader(&mut self, fontFileLoader: *mut *mut IDWriteFontFileLoader) -> ::HRESULT, + fn Analyze( + &mut self, isSupportedFontType: *mut ::BOOL, fontFileType: *mut DWRITE_FONT_FILE_TYPE, + fontFaceType: *mut DWRITE_FONT_FACE_TYPE, numberOfFaces: *mut ::UINT32 + ) -> ::HRESULT +}} +ENUM!{enum DWRITE_PIXEL_GEOMETRY { + DWRITE_PIXEL_GEOMETRY_FLAT, + DWRITE_PIXEL_GEOMETRY_RGB, + DWRITE_PIXEL_GEOMETRY_BGR, +}} +ENUM!{enum DWRITE_RENDERING_MODE { + DWRITE_RENDERING_MODE_DEFAULT, + DWRITE_RENDERING_MODE_ALIASED, + DWRITE_RENDERING_MODE_GDI_CLASSIC, + DWRITE_RENDERING_MODE_GDI_NATURAL, + DWRITE_RENDERING_MODE_NATURAL, + DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC, + DWRITE_RENDERING_MODE_OUTLINE, + DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC = DWRITE_RENDERING_MODE_GDI_CLASSIC.0, + DWRITE_RENDERING_MODE_CLEARTYPE_GDI_NATURAL = DWRITE_RENDERING_MODE_GDI_NATURAL.0, + DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL = DWRITE_RENDERING_MODE_NATURAL.0, + DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC.0, +}} +STRUCT!{struct DWRITE_MATRIX { + m11: ::FLOAT, + m12: ::FLOAT, + m21: ::FLOAT, + m22: ::FLOAT, + dx: ::FLOAT, + dy: ::FLOAT, +}} +RIDL!{interface IDWriteRenderingParams(IDWriteRenderingParamsVtbl): IUnknown(IUnknownVtbl) { + fn GetGamma(&mut self) -> ::FLOAT, + fn GetEnhancedContrast(&mut self) -> ::FLOAT, + fn GetClearTypeLevel(&mut self) -> ::FLOAT, + fn GetPixelGeometry(&mut self) -> DWRITE_PIXEL_GEOMETRY, + fn GetRenderingMode(&mut self) -> DWRITE_RENDERING_MODE +}} +pub type IDWriteGeometrySink = ::ID2D1SimplifiedGeometrySink; +RIDL!{interface IDWriteFontFace(IDWriteFontFaceVtbl): IUnknown(IUnknownVtbl) { + fn GetType(&mut self) -> DWRITE_FONT_FACE_TYPE, + fn GetFiles( + &mut self, numberOfFiles: *mut ::UINT32, fontFiles: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn GetIndex(&mut self) -> ::UINT32, + fn GetSimulations(&mut self) -> DWRITE_FONT_SIMULATIONS, + fn IsSymbolFont(&mut self) -> ::BOOL, + fn GetMetrics(&mut self, fontFaceMetrics: *mut DWRITE_FONT_METRICS) -> (), + fn GetGlyphCount(&mut self) -> ::UINT16, + fn GetDesignGlyphMetrics( + &mut self, glyphIndices: *const ::UINT16, glyphCount: ::UINT32, + glyphMetrics: *mut DWRITE_GLYPH_METRICS, isSideways: ::BOOL + ) -> ::HRESULT, + fn GetGlyphIndices( + &mut self, codePoints: *const ::UINT32, codePointCount: ::UINT32, + glyphIndices: *mut ::UINT16 + ) -> ::HRESULT, + fn TryGetFontTable( + &mut self, openTypeTableTag: ::UINT32, tableData: *mut *const ::c_void, + tableSize: *mut ::UINT32, tableContext: *mut *mut ::c_void, exists: *mut ::BOOL + ) -> ::HRESULT, + fn ReleaseFontTable( + &mut self, tableContext: *mut ::c_void + ) -> ::HRESULT, + fn GetGlyphRunOutline( + &mut self, emSize: ::FLOAT, glyphIndices: *const ::UINT16, glyphAdvances: *const ::FLOAT, + glyphOffsets: *const DWRITE_GLYPH_OFFSET, glyphCount: ::UINT32, isSideways: ::BOOL, + isRightToLeft: ::BOOL, geometrySink: *mut IDWriteGeometrySink + ) -> ::HRESULT, + fn GetRecommendedRenderingMode( + &mut self, emSize: ::FLOAT, pixelsPerDip: ::FLOAT, measuringMode: ::DWRITE_MEASURING_MODE, + renderingParams: *mut IDWriteRenderingParams, renderingMode: *mut DWRITE_RENDERING_MODE + ) -> ::HRESULT, + fn GetGdiCompatibleMetrics( + &mut self, emSize: ::FLOAT, pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, + fontFaceMetrics: *mut DWRITE_FONT_METRICS + ) -> ::HRESULT, + fn GetGdiCompatibleGlyphMetrics( + &mut self, enSize: ::FLOAT, pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, + useGdiNatrual: ::BOOL, glyphIndices: *const ::UINT16, glyphCount: ::UINT32, + glyphMetrics: *mut DWRITE_GLYPH_METRICS, isSideways: ::BOOL + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontCollectionLoader(IDWriteFontCollectionLoaderVtbl): + IUnknown(IUnknownVtbl) { + fn CreateEnumeratorFromKey( + &mut self, factory: *mut IDWriteFactory, collectionKey: *const ::c_void, + collectionKeySize: ::UINT32, fontFileEnumerator: *mut *mut IDWriteFontFileEnumerator + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFileEnumerator(IDWriteFontFileEnumeratorVtbl): IUnknown(IUnknownVtbl) { + fn MoveNext(&mut self, hasCurrentFile: *mut ::BOOL) -> ::HRESULT, + fn GetCurrentFontFile(&mut self, fontFile: *mut *mut IDWriteFontFile) -> ::HRESULT +}} +RIDL!{interface IDWriteLocalizedStrings(IDWriteLocalizedStringsVtbl): IUnknown(IUnknownVtbl) { + fn GetCount(&mut self) -> ::UINT32, + fn FindLocaleName( + &mut self, localeName: *const ::WCHAR, index: *mut ::UINT32, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetLocaleNameLength(&mut self, index: ::UINT32, length: *mut ::UINT32) -> ::HRESULT, + fn GetLocaleName( + &mut self, index: ::UINT32, localeName: *mut ::WCHAR, size: ::UINT32 + ) -> ::HRESULT, + fn GetStringLength(&mut self, index: ::UINT32, length: *mut ::UINT32) -> ::HRESULT, + fn GetString( + &mut self, index: ::UINT32, stringBuffer: *mut ::WCHAR, size: ::UINT32 + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontCollection(IDWriteFontCollectionVtbl): IUnknown(IUnknownVtbl) { + fn GetFontFamilyCount(&mut self) -> ::UINT32, + fn GetFontFamily( + &mut self, index: ::UINT32, fontFamily: *mut *mut IDWriteFontFamily + ) -> ::HRESULT, + fn FindFamilyName( + &mut self, familyName: *const ::WCHAR, index: *mut ::UINT32, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetFontFromFontFace( + &mut self, fontFace: *mut IDWriteFontFace, font: *mut *mut IDWriteFont + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFontList(IDWriteFontListVtbl): IUnknown(IUnknownVtbl) { + fn GetFontCollection(&mut self, fontCollection: *mut *mut IDWriteFontCollection) -> ::HRESULT, + fn GetFontCount(&mut self) -> ::UINT32, + fn GetFont(&mut self, index: ::UINT32, font: *mut *mut IDWriteFont) -> ::HRESULT +}} +RIDL!{interface IDWriteFontFamily(IDWriteFontFamilyVtbl): IDWriteFontList(IDWriteFontListVtbl) { + fn GetFamilyNames(&mut self, names: *mut *mut IDWriteLocalizedStrings) -> ::HRESULT, + fn GetFirstMatchingFont( + &mut self, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, + style: DWRITE_FONT_STYLE, matchingFont: *mut *mut IDWriteFont + ) -> ::HRESULT, + fn GetMatchingFonts( + &mut self, weight: DWRITE_FONT_WEIGHT, stretch: DWRITE_FONT_STRETCH, + style: DWRITE_FONT_STYLE, matchingFonts: *mut *mut IDWriteFontList + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFont(IDWriteFontVtbl): IUnknown(IUnknownVtbl) { + fn GetFontFamily(&mut self, fontFamily: *mut *mut IDWriteFontFamily) -> ::HRESULT, + fn GetWeight(&mut self) -> DWRITE_FONT_WEIGHT, + fn GetStretch(&mut self) -> DWRITE_FONT_STRETCH, + fn GetStyle(&mut self) -> DWRITE_FONT_STYLE, + fn IsSymbolFont(&mut self) -> ::BOOL, + fn GetFaceNames(&mut self, names: *mut *mut IDWriteLocalizedStrings) -> ::HRESULT, + fn GetInformationalStrings( + &mut self, informationalStringId: DWRITE_INFORMATIONAL_STRING_ID, + informationalStrings: *mut *mut IDWriteLocalizedStrings, exists: *mut ::BOOL + ) -> ::HRESULT, + fn GetSimulations(&mut self) -> DWRITE_FONT_SIMULATIONS, + fn GetMetrics(&mut self, fontMetrics: *mut DWRITE_FONT_METRICS) -> (), + fn HasCharacter(&mut self, unicodeValue: ::UINT32, exists: *mut ::BOOL) -> ::HRESULT, + fn CreateFontFace(&mut self, fontFace: *mut *mut IDWriteFontFace) -> ::HRESULT +}} +ENUM!{enum DWRITE_READING_DIRECTION { + DWRITE_READING_DIRECTION_LEFT_TO_RIGHT = 0, + DWRITE_READING_DIRECTION_RIGHT_TO_LEFT = 1, + DWRITE_READING_DIRECTION_TOP_TO_BOTTOM = 2, + DWRITE_READING_DIRECTION_BOTTOM_TO_TOP = 3, +}} +ENUM!{enum DWRITE_FLOW_DIRECTION { + DWRITE_FLOW_DIRECTION_TOP_TO_BOTTOM = 0, + DWRITE_FLOW_DIRECTION_BOTTOM_TO_TOP = 1, + DWRITE_FLOW_DIRECTION_LEFT_TO_RIGHT = 2, + DWRITE_FLOW_DIRECTION_RIGHT_TO_LEFT = 3, +}} +ENUM!{enum DWRITE_TEXT_ALIGNMENT { + DWRITE_TEXT_ALIGNMENT_LEADING, + DWRITE_TEXT_ALIGNMENT_TRAILING, + DWRITE_TEXT_ALIGNMENT_CENTER, + DWRITE_TEXT_ALIGNMENT_JUSTIFIED, +}} +ENUM!{enum DWRITE_PARAGRAPH_ALIGNMENT { + DWRITE_PARAGRAPH_ALIGNMENT_NEAR, + DWRITE_PARAGRAPH_ALIGNMENT_FAR, + DWRITE_PARAGRAPH_ALIGNMENT_CENTER, +}} +ENUM!{enum DWRITE_WORD_WRAPPING { + DWRITE_WORD_WRAPPING_WRAP = 0, + DWRITE_WORD_WRAPPING_NO_WRAP = 1, + DWRITE_WORD_WRAPPING_EMERGENCY_BREAK = 2, + DWRITE_WORD_WRAPPING_WHOLE_WORD = 3, + DWRITE_WORD_WRAPPING_CHARACTER = 4, +}} +ENUM!{enum DWRITE_LINE_SPACING_METHOD { + DWRITE_LINE_SPACING_METHOD_DEFAULT, + DWRITE_LINE_SPACING_METHOD_UNIFORM, + DWRITE_LINE_SPACING_METHOD_PROPORTIONAL, +}} +ENUM!{enum DWRITE_TRIMMING_GRANULARITY { + DWRITE_TRIMMING_GRANULARITY_NONE, + DWRITE_TRIMMING_GRANULARITY_CHARACTER, + DWRITE_TRIMMING_GRANULARITY_WORD, +}} +ENUM!{enum DWRITE_FONT_FEATURE_TAG { + DWRITE_FONT_FEATURE_TAG_ALTERNATIVE_FRACTIONS = 0x63726661, // 'afrc' + DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS_FROM_CAPITALS = 0x63703263, // 'c2pc' + DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS_FROM_CAPITALS = 0x63733263, // 'c2sc' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_ALTERNATES = 0x746c6163, // 'calt' + DWRITE_FONT_FEATURE_TAG_CASE_SENSITIVE_FORMS = 0x65736163, // 'case' + DWRITE_FONT_FEATURE_TAG_GLYPH_COMPOSITION_DECOMPOSITION = 0x706d6363, // 'ccmp' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_LIGATURES = 0x67696c63, // 'clig' + DWRITE_FONT_FEATURE_TAG_CAPITAL_SPACING = 0x70737063, // 'cpsp' + DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_SWASH = 0x68777363, // 'cswh' + DWRITE_FONT_FEATURE_TAG_CURSIVE_POSITIONING = 0x73727563, // 'curs' + DWRITE_FONT_FEATURE_TAG_DEFAULT = 0x746c6664, // 'dflt' + DWRITE_FONT_FEATURE_TAG_DISCRETIONARY_LIGATURES = 0x67696c64, // 'dlig' + DWRITE_FONT_FEATURE_TAG_EXPERT_FORMS = 0x74707865, // 'expt' + DWRITE_FONT_FEATURE_TAG_FRACTIONS = 0x63617266, // 'frac' + DWRITE_FONT_FEATURE_TAG_FULL_WIDTH = 0x64697766, // 'fwid' + DWRITE_FONT_FEATURE_TAG_HALF_FORMS = 0x666c6168, // 'half' + DWRITE_FONT_FEATURE_TAG_HALANT_FORMS = 0x6e6c6168, // 'haln' + DWRITE_FONT_FEATURE_TAG_ALTERNATE_HALF_WIDTH = 0x746c6168, // 'halt' + DWRITE_FONT_FEATURE_TAG_HISTORICAL_FORMS = 0x74736968, // 'hist' + DWRITE_FONT_FEATURE_TAG_HORIZONTAL_KANA_ALTERNATES = 0x616e6b68, // 'hkna' + DWRITE_FONT_FEATURE_TAG_HISTORICAL_LIGATURES = 0x67696c68, // 'hlig' + DWRITE_FONT_FEATURE_TAG_HALF_WIDTH = 0x64697768, // 'hwid' + DWRITE_FONT_FEATURE_TAG_HOJO_KANJI_FORMS = 0x6f6a6f68, // 'hojo' + DWRITE_FONT_FEATURE_TAG_JIS04_FORMS = 0x3430706a, // 'jp04' + DWRITE_FONT_FEATURE_TAG_JIS78_FORMS = 0x3837706a, // 'jp78' + DWRITE_FONT_FEATURE_TAG_JIS83_FORMS = 0x3338706a, // 'jp83' + DWRITE_FONT_FEATURE_TAG_JIS90_FORMS = 0x3039706a, // 'jp90' + DWRITE_FONT_FEATURE_TAG_KERNING = 0x6e72656b, // 'kern' + DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES = 0x6167696c, // 'liga' + DWRITE_FONT_FEATURE_TAG_LINING_FIGURES = 0x6d756e6c, // 'lnum' + DWRITE_FONT_FEATURE_TAG_LOCALIZED_FORMS = 0x6c636f6c, // 'locl' + DWRITE_FONT_FEATURE_TAG_MARK_POSITIONING = 0x6b72616d, // 'mark' + DWRITE_FONT_FEATURE_TAG_MATHEMATICAL_GREEK = 0x6b72676d, // 'mgrk' + DWRITE_FONT_FEATURE_TAG_MARK_TO_MARK_POSITIONING = 0x6b6d6b6d, // 'mkmk' + DWRITE_FONT_FEATURE_TAG_ALTERNATE_ANNOTATION_FORMS = 0x746c616e, // 'nalt' + DWRITE_FONT_FEATURE_TAG_NLC_KANJI_FORMS = 0x6b636c6e, // 'nlck' + DWRITE_FONT_FEATURE_TAG_OLD_STYLE_FIGURES = 0x6d756e6f, // 'onum' + DWRITE_FONT_FEATURE_TAG_ORDINALS = 0x6e64726f, // 'ordn' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_ALTERNATE_WIDTH = 0x746c6170, // 'palt' + DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS = 0x70616370, // 'pcap' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_FIGURES = 0x6d756e70, // 'pnum' + DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_WIDTHS = 0x64697770, // 'pwid' + DWRITE_FONT_FEATURE_TAG_QUARTER_WIDTHS = 0x64697771, // 'qwid' + DWRITE_FONT_FEATURE_TAG_REQUIRED_LIGATURES = 0x67696c72, // 'rlig' + DWRITE_FONT_FEATURE_TAG_RUBY_NOTATION_FORMS = 0x79627572, // 'ruby' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_ALTERNATES = 0x746c6173, // 'salt' + DWRITE_FONT_FEATURE_TAG_SCIENTIFIC_INFERIORS = 0x666e6973, // 'sinf' + DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS = 0x70636d73, // 'smcp' + DWRITE_FONT_FEATURE_TAG_SIMPLIFIED_FORMS = 0x6c706d73, // 'smpl' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_1 = 0x31307373, // 'ss01' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_2 = 0x32307373, // 'ss02' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_3 = 0x33307373, // 'ss03' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_4 = 0x34307373, // 'ss04' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_5 = 0x35307373, // 'ss05' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_6 = 0x36307373, // 'ss06' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_7 = 0x37307373, // 'ss07' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_8 = 0x38307373, // 'ss08' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_9 = 0x39307373, // 'ss09' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_10 = 0x30317373, // 'ss10' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_11 = 0x31317373, // 'ss11' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_12 = 0x32317373, // 'ss12' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_13 = 0x33317373, // 'ss13' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_14 = 0x34317373, // 'ss14' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_15 = 0x35317373, // 'ss15' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_16 = 0x36317373, // 'ss16' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_17 = 0x37317373, // 'ss17' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_18 = 0x38317373, // 'ss18' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_19 = 0x39317373, // 'ss19' + DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_20 = 0x30327373, // 'ss20' + DWRITE_FONT_FEATURE_TAG_SUBSCRIPT = 0x73627573, // 'subs' + DWRITE_FONT_FEATURE_TAG_SUPERSCRIPT = 0x73707573, // 'sups' + DWRITE_FONT_FEATURE_TAG_SWASH = 0x68737773, // 'swsh' + DWRITE_FONT_FEATURE_TAG_TITLING = 0x6c746974, // 'titl' + DWRITE_FONT_FEATURE_TAG_TRADITIONAL_NAME_FORMS = 0x6d616e74, // 'tnam' + DWRITE_FONT_FEATURE_TAG_TABULAR_FIGURES = 0x6d756e74, // 'tnum' + DWRITE_FONT_FEATURE_TAG_TRADITIONAL_FORMS = 0x64617274, // 'trad' + DWRITE_FONT_FEATURE_TAG_THIRD_WIDTHS = 0x64697774, // 'twid' + DWRITE_FONT_FEATURE_TAG_UNICASE = 0x63696e75, // 'unic' + DWRITE_FONT_FEATURE_TAG_VERTICAL_WRITING = 0x74726576, // 'vert' + DWRITE_FONT_FEATURE_TAG_VERTICAL_ALTERNATES_AND_ROTATION = 0x32747276, // 'vrt2' + DWRITE_FONT_FEATURE_TAG_SLASHED_ZERO = 0x6f72657a, // 'zero' +}} +STRUCT!{struct DWRITE_TEXT_RANGE { + startPosition: ::UINT32, + length: ::UINT32, +}} +STRUCT!{struct DWRITE_FONT_FEATURE { + nameTag: DWRITE_FONT_FEATURE_TAG, + parameter: ::UINT32, +}} +STRUCT!{struct DWRITE_TYPOGRAPHIC_FEATURES { + features: *mut DWRITE_FONT_FEATURE, + featureCount: ::UINT32, +}} +STRUCT!{struct DWRITE_TRIMMING { + granularity: DWRITE_TRIMMING_GRANULARITY, + delimiter: ::UINT32, + delimiterCount: ::UINT32, +}} +RIDL!{interface IDWriteTextFormat(IDWriteTextFormatVtbl): IUnknown(IUnknownVtbl) { + fn SetTextAlignment(&mut self, textAlignment: DWRITE_TEXT_ALIGNMENT) -> ::HRESULT, + fn SetParagraphAlignment( + &mut self, paragraphAlignment: DWRITE_PARAGRAPH_ALIGNMENT + ) -> ::HRESULT, + fn SetWordWrapping(&mut self, wordWrapping: DWRITE_WORD_WRAPPING) -> ::HRESULT, + fn SetReadingDirection(&mut self, readingDirection: DWRITE_READING_DIRECTION) -> ::HRESULT, + fn SetFlowDirection(&mut self, flowDirection: DWRITE_FLOW_DIRECTION) -> ::HRESULT, + fn SetIncrementalTabStop(&mut self, incrementalTabStop: ::FLOAT) -> ::HRESULT, + fn SetTrimming( + &mut self, trimmingOptions: *const DWRITE_TRIMMING, trimmingSign: *mut IDWriteInlineObject + ) -> ::HRESULT, + fn SetLineSpacing( + &mut self, lineSpacingMethod: DWRITE_LINE_SPACING_METHOD, lineSpacing: ::FLOAT, + baseLine: ::FLOAT + ) -> ::HRESULT, + fn GetTextAlignment(&mut self) -> DWRITE_TEXT_ALIGNMENT, + fn GetParagraphAlignment(&mut self) -> DWRITE_PARAGRAPH_ALIGNMENT, + fn GetWordWrapping(&mut self) -> DWRITE_WORD_WRAPPING, + fn GetReadingDirection(&mut self) -> DWRITE_READING_DIRECTION, + fn GetFlowDirection(&mut self) -> DWRITE_FLOW_DIRECTION, + fn GetIncrementalTabStop(&mut self) -> ::FLOAT, + fn GetTrimming( + &mut self, trimmingOptions: *mut DWRITE_TRIMMING, + trimmingSign: *mut *mut IDWriteInlineObject + ) -> ::HRESULT, + fn GetLineSpacing( + &mut self, lineSpacingMethod: *mut DWRITE_LINE_SPACING_METHOD, lineSpacing: *mut ::FLOAT, + baseline: *mut ::FLOAT + ) -> ::HRESULT, + fn GetFontCollection(&mut self, fontCollection: *mut *mut IDWriteFontCollection) -> ::HRESULT, + fn GetFontFamilyNameLength(&mut self) -> ::UINT32, + fn GetFontFamilyName(&mut self, fontFamilyName: *mut ::WCHAR, nameSize: ::UINT32) -> ::HRESULT, + fn GetFontWeight(&mut self) -> DWRITE_FONT_WEIGHT, + fn GetFontStyle(&mut self) -> DWRITE_FONT_STYLE, + fn GetFontStretch(&mut self) -> DWRITE_FONT_STRETCH, + fn GetFontSize(&mut self) -> ::FLOAT, + fn GetLocaleNameLength(&mut self) -> ::UINT32, + fn GetLocaleName(&mut self, localeName: *mut ::WCHAR, nameSize: ::UINT32) -> ::HRESULT +}} +RIDL!{interface IDWriteTypography(IDWriteTypographyVtbl): IUnknown(IUnknownVtbl) { + fn AddFontFeature(&mut self, fontFeature: DWRITE_FONT_FEATURE) -> ::HRESULT, + fn GetFontFeatureCount(&mut self) -> ::UINT32, + fn GetFontFeature( + &mut self, fontFeatureIndex: ::UINT32, fontFeature: *mut DWRITE_FONT_FEATURE + ) -> ::HRESULT +}} +FLAGS!{enum DWRITE_SCRIPT_SHAPES { + DWRITE_SCRIPT_SHAPES_DEFAULT = 0, + DWRITE_SCRIPT_SHAPES_NO_VISUAL = 1, +}} +STRUCT!{struct DWRITE_SCRIPT_ANALYSIS { + script: ::UINT16, + shapes: DWRITE_SCRIPT_SHAPES, +}} +ENUM!{enum DWRITE_BREAK_CONDITION { + DWRITE_BREAK_CONDITION_NEUTRAL, + DWRITE_BREAK_CONDITION_CAN_BREAK, + DWRITE_BREAK_CONDITION_MAY_NOT_BREAK, + DWRITE_BREAK_CONDITION_MUST_BREAK, +}} +STRUCT!{struct DWRITE_LINE_BREAKPOINT { + bit_fields: ::UINT8, +}} +BITFIELD!{DWRITE_LINE_BREAKPOINT bit_fields: ::UINT8 [ + breakConditionBefore set_breakConditionBefore[0..2], + breakConditionAfter set_breakConditionAfter[2..4], + isWhitespace set_isWhitespace[4..5], + isSoftHyphen set_isSoftHyphen[5..6], + padding set_padding[6..8], +]} +ENUM!{enum DWRITE_NUMBER_SUBSTITUTION_METHOD { + DWRITE_NUMBER_SUBSTITUTION_METHOD_FROM_CULTURE, + DWRITE_NUMBER_SUBSTITUTION_METHOD_CONTEXTUAL, + DWRITE_NUMBER_SUBSTITUTION_METHOD_NONE, + DWRITE_NUMBER_SUBSTITUTION_METHOD_NATIONAL, + DWRITE_NUMBER_SUBSTITUTION_METHOD_TRADITIONAL, +}} +RIDL!{interface IDWriteNumberSubstitution(IDWriteNumberSubstitutionVtbl): IUnknown(IUnknownVtbl) { +}} +STRUCT!{struct DWRITE_SHAPING_TEXT_PROPERTIES { + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_SHAPING_TEXT_PROPERTIES bit_fields: ::UINT16 [ + isShapedAlone set_isShapedAlone[0..1], + reserved set_reserved[1..16], +]} +STRUCT!{struct DWRITE_SHAPING_GLYPH_PROPERTIES { + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_SHAPING_GLYPH_PROPERTIES bit_fields: ::UINT16 [ + justification set_justification[0..4], + isClusterStart set_isClusterStart[4..5], + isDiacritic set_isDiacritic[5..6], + isZeroWidthSpace set_isZeroWidthSpace[6..7], + reserved set_reserved[7..16], +]} +RIDL!{interface IDWriteTextAnalysisSource(IDWriteTextAnalysisSourceVtbl): IUnknown(IUnknownVtbl) { + fn GetTextAtPosition( + &mut self, textPosition: ::UINT32, textString: *mut *const ::WCHAR, + textLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetTextBeforePosition( + &mut self, textPosition: ::UINT32, textString: *mut *const ::WCHAR, + textLength: *mut ::UINT32 + ) -> ::HRESULT, + fn GetParagraphReadingDirection(&mut self) -> DWRITE_READING_DIRECTION, + fn GetLocaleName( + &mut self, textPosition: ::UINT32, textLength: *mut ::UINT32, + localeName: *mut *const ::WCHAR + ) -> ::HRESULT, + fn GetNumberSubstitution( + &mut self, textPosition: ::UINT32, textLength: *mut ::UINT32, + numberSubstitution: *mut *mut IDWriteNumberSubstitution + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextAnalysisSink(IDWriteTextAnalysisSinkVtbl): IUnknown(IUnknownVtbl) { + fn SetScriptAnalysis( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS + ) -> ::HRESULT, + fn SetLineBreakpoints( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + lineBreakpoints: *const DWRITE_LINE_BREAKPOINT + ) -> ::HRESULT, + fn SetBidiLevel( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, explicitLevel: ::UINT8, + resolvedLevel: ::UINT8 + ) -> ::HRESULT, + fn SetNumberSubstitution( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, + numberSubstitution: *mut IDWriteNumberSubstitution + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextAnalyzer(IDWriteTextAnalyzerVtbl): IUnknown(IUnknownVtbl) { + fn AnalyzeScript( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeBidi( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeNumberSubstitution( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn AnalyzeLineBreakpoints( + &mut self, analysisSource: *mut IDWriteTextAnalysisSource, textPosition: ::UINT32, + textLength: ::UINT32, analysisSink: *mut IDWriteTextAnalysisSink + ) -> ::HRESULT, + fn GetGlyphs( + &mut self, textString: *const ::WCHAR, textLength: ::UINT32, + fontFace: *mut IDWriteFontFace, isSideways: ::BOOL, isRightToLeft: ::BOOL, + scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, localeName: *const ::WCHAR, + numberSubstitution: *mut IDWriteNumberSubstitution, + features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, featureRangeLengths: *const ::UINT32, + featureRanges: ::UINT32, maxGlyphCount: ::UINT32, clusterMap: *mut ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, glyphIndices: *mut ::UINT16, + glyphProps: *mut DWRITE_SHAPING_GLYPH_PROPERTIES, actualGlyphCount: *mut ::UINT32 + ) -> ::HRESULT, + fn GetGlyphPlacements( + &mut self, textString: *const ::WCHAR, clusterMap: *const ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, textLength: ::UINT32, + glyphIndices: *const ::UINT16, glyphProps: *const DWRITE_SHAPING_GLYPH_PROPERTIES, + glyphCount: ::UINT32, fontFace: *mut IDWriteFontFace, fontEmSize: ::FLOAT, + isSideways: ::BOOL, isRightToLeft: ::BOOL, scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, + localeName: *const ::WCHAR, features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, + featureRangeLengths: *const ::UINT32, featureRanges: ::UINT32, glyphAdvances: *mut ::FLOAT, + glyphOffsets: *mut DWRITE_GLYPH_OFFSET + ) -> ::HRESULT, + fn GetGdiCompatibleGlyphPlacements( + &mut self, textString: *const ::WCHAR, clusterMap: *const ::UINT16, + textProps: *mut DWRITE_SHAPING_TEXT_PROPERTIES, textLength: ::UINT32, + glyphIndices: *const ::UINT16, glyphProps: *const DWRITE_SHAPING_GLYPH_PROPERTIES, + glyphCount: ::UINT32, fontFace: *mut IDWriteFontFace, fontEmSize: ::FLOAT, + pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, useGdiNatrual: ::BOOL, + isSideways: ::BOOL, isRightToLeft: ::BOOL, scriptAnalysis: *const DWRITE_SCRIPT_ANALYSIS, + localeName: *const ::WCHAR, features: *mut *const DWRITE_TYPOGRAPHIC_FEATURES, + featureRangeLengths: *const ::UINT32, featureRanges: ::UINT32, glyphAdvances: *mut ::FLOAT, + glyphOffsets: *mut DWRITE_GLYPH_OFFSET + ) -> ::HRESULT +}} +STRUCT!{struct DWRITE_GLYPH_RUN { + fontFace: *mut IDWriteFontFace, + fontEmSize: ::FLOAT, + glyphCount: ::UINT32, + glyphIndices: *const ::UINT16, + glyphAdvances: *const ::FLOAT, + glyphOffsets: *const DWRITE_GLYPH_OFFSET, + isSideways: ::BOOL, + bidiLevel: ::UINT32, +}} +STRUCT!{struct DWRITE_GLYPH_RUN_DESCRIPTION { + localeName: *const ::WCHAR, + string: *const ::WCHAR, + stringLength: ::UINT32, + clusterMap: *const ::UINT16, + textPosition: ::UINT32, +}} +STRUCT!{struct DWRITE_UNDERLINE { + width: ::FLOAT, + thickness: ::FLOAT, + offset: ::FLOAT, + runHeight: ::FLOAT, + readingDirection: DWRITE_READING_DIRECTION, + flowDirection: DWRITE_FLOW_DIRECTION, + localeName: *const ::WCHAR, + measuringMode: ::DWRITE_MEASURING_MODE, +}} +STRUCT!{struct DWRITE_STRIKETHROUGH { + width: ::FLOAT, + thickness: ::FLOAT, + offset: ::FLOAT, + readingDirection: DWRITE_READING_DIRECTION, + flowDirection: DWRITE_FLOW_DIRECTION, + localeName: *const ::WCHAR, + measuringMode: ::DWRITE_MEASURING_MODE, +}} +STRUCT!{struct DWRITE_LINE_METRICS { + length: ::UINT32, + trailingWhitespaceLength: ::UINT32, + newlineLength: ::UINT32, + height: ::FLOAT, + baseline: ::FLOAT, + isTrimmed: ::BOOL, +}} +STRUCT!{struct DWRITE_CLUSTER_METRICS { + width: ::FLOAT, + length: ::UINT16, + bit_fields: ::UINT16, +}} +BITFIELD!{DWRITE_CLUSTER_METRICS bit_fields: ::UINT16 [ + canWrapLineAfter set_canWrapLineAfter[0..1], + isWhitespace set_isWhitespace[1..2], + isNewline set_isNewline[2..3], + isSoftHyphen set_isSoftHyphen[3..4], + isRightToLeft set_isRightToLeft[4..5], + padding set_padding[5..16], +]} +STRUCT!{struct DWRITE_TEXT_METRICS { + left: ::FLOAT, + top: ::FLOAT, + width: ::FLOAT, + widthIncludingTrailingWhitespace: ::FLOAT, + height: ::FLOAT, + layoutWidth: ::FLOAT, + layoutHeight: ::FLOAT, + maxBidiReorderingDepth: ::UINT32, + lineCount: ::UINT32, +}} +STRUCT!{struct DWRITE_INLINE_OBJECT_METRICS { + width: ::FLOAT, + height: ::FLOAT, + baseline: ::FLOAT, + supportsSideways: ::BOOL, +}} +STRUCT!{struct DWRITE_OVERHANG_METRICS { + left: ::FLOAT, + top: ::FLOAT, + right: ::FLOAT, + bottom: ::FLOAT, +}} +STRUCT!{struct DWRITE_HIT_TEST_METRICS { + textPosition: ::UINT32, + length: ::UINT32, + left: ::FLOAT, + top: ::FLOAT, + width: ::FLOAT, + height: ::FLOAT, + bidiLevel: ::UINT32, + isText: ::BOOL, + isTrimmed: ::BOOL, +}} +RIDL!{interface IDWriteInlineObject(IDWriteInlineObjectVtbl): IUnknown(IUnknownVtbl) { + fn Draw( + &mut self, clientDrawingContext: *mut ::c_void, renderer: *mut IDWriteTextRenderer, + originX: ::FLOAT, originY: ::FLOAT, isSideways: ::BOOL, isRightToLeft: ::BOOL, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn GetMetrics(&mut self, metrics: *mut DWRITE_INLINE_OBJECT_METRICS) -> ::HRESULT, + fn GetOverhangMetrics(&mut self, overhangs: *mut DWRITE_OVERHANG_METRICS) -> ::HRESULT, + fn GetBreakConditions( + &mut self, breakConditionBefore: *mut DWRITE_BREAK_CONDITION, + breakConditionAfter: *mut DWRITE_BREAK_CONDITION + ) -> ::HRESULT +}} +RIDL!{interface IDWritePixelSnapping(IDWritePixelSnappingVtbl): IUnknown(IUnknownVtbl) { + fn IsPixelSnappingDisabled( + &mut self, clientDrawingContext: *mut ::c_void, isDisabled: *mut ::BOOL + ) -> ::HRESULT, + fn GetCurrentTransform( + &mut self, clientDrawingContext: *mut ::c_void, transform: *mut DWRITE_MATRIX + ) -> ::HRESULT, + fn GetPixelsPerDip( + &mut self, clientDrawingContext: *mut ::c_void, pixelsPerDip: *mut ::FLOAT + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextRenderer(IDWriteTextRendererVtbl): + IDWritePixelSnapping(IDWritePixelSnappingVtbl) { + fn DrawGlyphRun( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, measuringMode: ::DWRITE_MEASURING_MODE, + glyphRun: *const DWRITE_GLYPH_RUN, + glyphRunDescription: *const DWRITE_GLYPH_RUN_DESCRIPTION, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawUnderline( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, underline: *const DWRITE_UNDERLINE, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawStrikethrough( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, strikethrough: *const DWRITE_STRIKETHROUGH, + clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT, + fn DrawInlineObject( + &mut self, clientDrawingContext: *mut ::c_void, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, inlineObject: *mut IDWriteInlineObject, + isSideways: ::BOOL, isRightToLeft: ::BOOL, clientDrawingEffect: *mut ::IUnknown + ) -> ::HRESULT +}} +RIDL!{interface IDWriteTextLayout(IDWriteTextLayoutVtbl): + IDWriteTextFormat(IDWriteTextFormatVtbl) { + fn SetMaxWidth(&mut self, maxWidth: ::FLOAT) -> ::HRESULT, + fn SetMaxHeight(&mut self, maxHeight: ::FLOAT) -> ::HRESULT, + fn SetFontCollection( + &mut self, fontCollection: *mut IDWriteFontCollection, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontFamilyName( + &mut self, fontFamilyName: *const ::WCHAR, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontWeight( + &mut self, fontWeight: DWRITE_FONT_WEIGHT, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontStyle( + &mut self, fontStyle: DWRITE_FONT_STYLE, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontStretch( + &mut self, fontStretch: DWRITE_FONT_STRETCH, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetFontSize(&mut self, fontSize: ::FLOAT, textRange: DWRITE_TEXT_RANGE) -> ::HRESULT, + fn SetUnderline(&mut self, hasUnderline: ::BOOL, textRange: DWRITE_TEXT_RANGE) -> ::HRESULT, + fn SetStrikethrough( + &mut self, hasStrikethrough: ::BOOL, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetDrawingEffect( + &mut self, drawingEffect: *mut ::IUnknown, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetInlineObject( + &mut self, inlineObject: *mut IDWriteInlineObject, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetTypography( + &mut self, typography: *mut IDWriteTypography, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn SetLocaleName( + &mut self, localeName: *const ::WCHAR, textRange: DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetMaxWidth(&mut self) -> ::FLOAT, + fn GetMaxHeight(&mut self) -> ::FLOAT, + fn GetFontCollection( + &mut self, currentPosition: ::UINT32, fontCollection: *mut *mut IDWriteFontCollection, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontFamilyNameLength( + &mut self, currentPosition: ::UINT32, nameLength: *mut ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontFamilyName( + &mut self, currentPosition: ::UINT32, fontFamilyName: *mut ::WCHAR, + nameSize: ::UINT32, textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontWeight( + &mut self, currentPosition: ::UINT32, fontWeight: *mut DWRITE_FONT_WEIGHT, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontStyle( + &mut self, currentPosition: ::UINT32, fontStyle: *mut DWRITE_FONT_STYLE, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontStretch( + &mut self, currentPosition: ::UINT32, fontStretch: *mut DWRITE_FONT_STRETCH, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetFontSize( + &mut self, currentPosition: ::UINT32, fontSize: *mut ::FLOAT, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetUnderline( + &mut self, currentPosition: ::UINT32, hasUnderline: *mut ::BOOL, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetStrikethrough( + &mut self, currentPosition: ::UINT32, hasStrikethrough: *mut ::BOOL, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetDrawingEffect( + &mut self, currentPosition: ::UINT32, drawingEffect: *mut *mut ::IUnknown, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetInlineObject( + &mut self, currentPosition: ::UINT32, inlineObject: *mut *mut IDWriteInlineObject, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetTypography( + &mut self, currentPosition: ::UINT32, typography: *mut *mut IDWriteTypography, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetLocaleNameLength( + &mut self, currentPosition: ::UINT32, nameLength: *mut ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn GetLocaleName( + &mut self, currentPosition: ::UINT32, localeName: *mut ::WCHAR, nameSize: ::UINT32, + textRange: *mut DWRITE_TEXT_RANGE + ) -> ::HRESULT, + fn Draw( + &mut self, clientDrawingContext: *mut ::c_void, renderer: *mut IDWriteTextRenderer, + originX: ::FLOAT, originY: ::FLOAT + ) -> ::HRESULT, + fn GetLineMetrics( + &mut self, lineMetrics: *mut DWRITE_LINE_METRICS, maxLineCount: ::UINT32, + actualLineCount: *mut ::UINT32 + ) -> ::HRESULT, + fn GetMetrics(&mut self, textMetrics: *mut DWRITE_TEXT_METRICS) -> ::HRESULT, + fn GetOverhangMetrics(&mut self, overhangs: *mut DWRITE_OVERHANG_METRICS) -> ::HRESULT, + fn GetClusterMetrics( + &mut self, clusterMetrics: *mut DWRITE_CLUSTER_METRICS, maxClusterCount: ::UINT32, + actualClusterCount: *mut ::UINT32 + ) -> ::HRESULT, + fn DetermineMinWidth(&mut self, minWidth: *mut ::FLOAT) -> ::HRESULT, + fn HitTestPoint( + &mut self, pointX: ::FLOAT, pointY: ::FLOAT, isTrailingHit: *mut ::BOOL, + isInside: *mut ::BOOL, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS + ) -> ::HRESULT, + fn HitTestTextPosition( + &mut self, textPosition: ::UINT32, isTrailingHit: ::BOOL, pointX: *mut ::FLOAT, + pointY: *mut ::FLOAT, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS + ) -> ::HRESULT, + fn HitTestTextRange( + &mut self, textPosition: ::UINT32, textLength: ::UINT32, originX: ::FLOAT, + originY: ::FLOAT, hitTestMetrics: *mut DWRITE_HIT_TEST_METRICS, + maxHitTestMetricsCount: ::UINT32, actualHitTestMetricsCount: *mut ::UINT32 + ) -> ::HRESULT +}} +RIDL!{interface IDWriteBitmapRenderTarget(IDWriteBitmapRenderTargetVtbl): IUnknown(IUnknownVtbl) { + fn DrawGlyphRun( + &mut self, baselineOriginX: ::FLOAT, baselineOriginY: ::FLOAT, + measuringMode: ::DWRITE_MEASURING_MODE, glyphRun: *const ::DWRITE_GLYPH_RUN, + renderingParams: *mut IDWriteRenderingParams, textColor: ::COLORREF, + blackBoxRect: *mut ::RECT + ) -> ::HRESULT, + fn GetMemoryDC(&mut self) -> ::HDC, + fn GetPixelsPerDip(&mut self) -> ::FLOAT, + fn SetPixelsPerDip(&mut self, pixelsPerDip: ::FLOAT) -> ::HRESULT, + fn GetCurrentTransform(&mut self, transform: *mut DWRITE_MATRIX) -> ::HRESULT, + fn SetCurrentTransform(&mut self, transform: *const DWRITE_MATRIX) -> ::HRESULT, + fn GetSize(&mut self, size: *mut ::SIZE) -> ::HRESULT, + fn Resize(&mut self, width: ::UINT32, height: ::UINT32) -> ::HRESULT +}} +RIDL!{interface IDWriteGdiInterop(IDWriteGdiInteropVtbl): IUnknown(IUnknownVtbl) { + fn CreateFontFromLOGFONT( + &mut self, logFont: *const ::LOGFONTW, font: *mut *mut IDWriteFont + ) -> ::HRESULT, + fn ConvertFontToLOGFONT( + &mut self, font: *mut IDWriteFont, logFont: *mut ::LOGFONTW, isSystemFont: *mut ::BOOL + ) -> ::HRESULT, + fn ConvertFontFaceToLOGFONT( + &mut self, font: *mut IDWriteFontFace, logFont: *mut ::LOGFONTW + ) -> ::HRESULT, + fn CreateFontFaceFromHdc( + &mut self, hdc: ::HDC, fontFace: *mut *mut IDWriteFontFace + ) -> ::HRESULT, + fn CreateBitmapRenderTarget( + &mut self, hdc: ::HDC, width: ::UINT32, height: ::UINT32, + renderTarget: *mut *mut IDWriteBitmapRenderTarget + ) -> ::HRESULT +}} +ENUM!{enum DWRITE_TEXTURE_TYPE { + DWRITE_TEXTURE_ALIASED_1x1 = 0, + DWRITE_TEXTURE_CLEARTYPE_3x1 = 1, +}} +pub const DWRITE_ALPHA_MAX: ::BYTE = 255; +RIDL!{interface IDWriteGlyphRunAnalysis(IDWriteGlyphRunAnalysisVtbl): IUnknown(IUnknownVtbl) { + fn GetAlphaTextureBounds( + &mut self, textureType: DWRITE_TEXTURE_TYPE, textureBounds: *mut ::RECT + ) -> ::HRESULT, + fn CreateAlphaTexture( + &mut self, textureType: DWRITE_TEXTURE_TYPE, textureBounds: *const ::RECT, + alphaValues: *mut ::BYTE, bufferSize: ::UINT32 + ) -> ::HRESULT, + fn GetAlphaBlendParams( + &mut self, renderingParams: *mut IDWriteRenderingParams, blendGamma: *mut ::FLOAT, + blendEnhancedContrast: *mut ::FLOAT, blendClearTypeLevel: *mut ::FLOAT + ) -> ::HRESULT +}} +RIDL!{interface IDWriteFactory(IDWriteFactoryVtbl): IUnknown(IUnknownVtbl) { + fn GetSystemFontCollection( + &mut self, fontCollection: *mut *mut IDWriteFontCollection, checkForUpdates: ::BOOL + ) -> ::HRESULT, + fn CreateCustomFontCollection( + &mut self, collectionLoader: *mut IDWriteFontCollectionLoader, + collectionKey: *const ::c_void, collectionKeySize: ::UINT32, + fontCollection: *mut *mut IDWriteFontCollection + ) -> ::HRESULT, + fn RegisterFontCollectionLoader( + &mut self, fontCollectionLoader: *mut IDWriteFontCollectionLoader + ) -> ::HRESULT, + fn UnregisterFontCollectionLoader( + &mut self, fontCollectionLoader: *mut IDWriteFontCollectionLoader + ) -> ::HRESULT, + fn CreateFontFileReference( + &mut self, filePath: *const ::WCHAR, lastWriteTime: *const ::FILETIME, + fontFile: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn CreateCustomFontFileReference( + &mut self, fontFileReferenceKey: *const ::c_void, fontFileReferenceKeySize: ::UINT32, + fontFileLoader: *mut IDWriteFontFileLoader, fontFile: *mut *mut IDWriteFontFile + ) -> ::HRESULT, + fn CreateFontFace( + &mut self, fontFaceType: DWRITE_FONT_FACE_TYPE, numberOfFiles: ::UINT32, + fontFiles: *const *mut IDWriteFontFile, faceIndex: ::UINT32, + fontFaceSimulationFlags: DWRITE_FONT_SIMULATIONS, fontFace: *mut *mut IDWriteFontFace + ) -> ::HRESULT, + fn CreateRenderingParams( + &mut self, renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn CreateMonitorRenderingParams( + &mut self, monitor: ::HMONITOR, renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn CreateCustomRenderingParams( + &mut self, gamma: ::FLOAT, enhancedContrast: ::FLOAT, clearTypeLevel: ::FLOAT, + pixelGeometry: DWRITE_PIXEL_GEOMETRY, renderingMode: DWRITE_RENDERING_MODE, + renderingParams: *mut *mut IDWriteRenderingParams + ) -> ::HRESULT, + fn RegisterFontFileLoader( + &mut self, fontFileLoader: *mut IDWriteFontFileLoader + ) -> ::HRESULT, + fn UnregisterFontFileLoader( + &mut self, fontFileLoader: *mut IDWriteFontFileLoader + ) -> ::HRESULT, + fn CreateTextFormat( + &mut self, fontFamilyName: *const ::WCHAR, fontCollection: *mut IDWriteFontCollection, + fontWeight: DWRITE_FONT_WEIGHT, fontStyle: DWRITE_FONT_STYLE, + fontStretch: DWRITE_FONT_STRETCH, fontSize: ::FLOAT, localeName: *const ::WCHAR, + textFormat: *mut *mut IDWriteTextFormat + ) -> ::HRESULT, + fn CreateTypography(&mut self, typography: *mut *mut IDWriteTypography) -> ::HRESULT, + fn GetGdiInterop(&mut self, gdiInterop: *mut *mut IDWriteGdiInterop) -> ::HRESULT, + fn CreateTextLayout( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut IDWriteTextFormat, maxWidth: ::FLOAT, maxHeight: ::FLOAT, + textLayout: *mut *mut IDWriteTextLayout + ) -> ::HRESULT, + fn CreateGdiCompatibleTextLayout( + &mut self, string: *const ::WCHAR, stringLength: ::UINT32, + textFormat: *mut IDWriteTextFormat, layoutWidth: ::FLOAT, layoutHeight: ::FLOAT, + pixelsPerDip: ::FLOAT, transform: *const DWRITE_MATRIX, useGdiNatrual: ::BOOL, + textLayout: *mut *mut IDWriteTextLayout + ) -> ::HRESULT, + fn CreateEllipsisTrimmingSign( + &mut self, textFormat: *mut IDWriteTextFormat, trimmingSign: *mut *mut IDWriteInlineObject + ) -> ::HRESULT, + fn CreateTextAnalyzer(&mut self, textAnalyzer: *mut *mut IDWriteTextAnalyzer) -> ::HRESULT, + fn CreateNumberSubstitution( + &mut self, substitutionMethod: DWRITE_NUMBER_SUBSTITUTION_METHOD, + localeName: *const ::WCHAR, ignoreUserOverride: ::BOOL, + numberSubstitution: *mut *mut IDWriteNumberSubstitution + ) -> ::HRESULT, + fn CreateGlyphRunAnalysis( + &mut self, glyphRun: *const DWRITE_GLYPH_RUN, pixelsPerDip: ::FLOAT, + transform: *const DWRITE_MATRIX, renderingMode: DWRITE_RENDERING_MODE, + measuringMode: ::DWRITE_MEASURING_MODE, baselineOriginX: ::FLOAT, + baselineOriginY: ::FLOAT, glyphRunAnalysis: *mut *mut IDWriteGlyphRunAnalysis + ) -> ::HRESULT +}} +pub const FACILITY_DWRITE: ::HRESULT = 0x898; +pub const DWRITE_ERR_BASE: ::HRESULT = 0x5000; +#[inline] +pub fn MAKE_DWRITE_HR(severity: ::HRESULT, code: ::HRESULT) -> ::HRESULT { + ::MAKE_HRESULT(severity, FACILITY_DWRITE, DWRITE_ERR_BASE + code) +} +#[inline] +pub fn MAKE_DWRITE_HR_ERR(code: ::HRESULT) -> ::HRESULT { + MAKE_DWRITE_HR(::SEVERITY_ERROR, code) +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi.rs new file mode 100644 index 0000000..c818215 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi.rs @@ -0,0 +1,240 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of dxgi.h +STRUCT!{struct DXGI_FRAME_STATISTICS { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, +}} +STRUCT!{struct DXGI_MAPPED_RECT { + Pitch: ::INT, + pBits: *mut ::BYTE, +}} +STRUCT!{nodebug struct DXGI_ADAPTER_DESC { + Description: [::WCHAR; 128], + VectorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, +}} +STRUCT!{nodebug struct DXGI_OUTPUT_DESC { + DeviceName: [::WCHAR; 32], + DesktopCoordinates: ::RECT, + AttachedToDesktop: ::BOOL, + Rotation: ::DXGI_MODE_ROTATION, + Monitor: ::HMONITOR, +}} +STRUCT!{struct DXGI_SHARED_RESOURCE { + Handle: ::HANDLE, +}} +pub const DXGI_RESOURCE_PRIORITY_MINIMUM: ::DWORD = 0x28000000; +pub const DXGI_RESOURCE_PRIORITY_LOW: ::DWORD = 0x50000000; +pub const DXGI_RESOURCE_PRIORITY_NORMAL: ::DWORD = 0x78000000; +pub const DXGI_RESOURCE_PRIORITY_HIGH: ::DWORD = 0xa0000000; +pub const DXGI_RESOURCE_PRIORITY_MAXIMUM: ::DWORD = 0xc8000000; +ENUM!{enum DXGI_RESIDENCY { + DXGI_RESIDENCY_FULLY_RESIDENT = 1, + DXGI_RESIDENCY_RESIDENT_IN_SHARED_MEMORY = 2, + DXGI_RESIDENCY_EVICTED_TO_DISK = 3, +}} +STRUCT!{struct DXGI_SURFACE_DESC { + Width: ::UINT, + Height: ::UINT, + Format: ::DXGI_FORMAT, + SampleDesc: ::DXGI_SAMPLE_DESC, +}} +ENUM!{enum DXGI_SWAP_EFFECT { + DXGI_SWAP_EFFECT_DISCARD = 0, + DXGI_SWAP_EFFECT_SEQUENTIAL = 1, + DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL = 3, +}} +FLAGS!{enum DXGI_SWAP_CHAIN_FLAG { + DXGI_SWAP_CHAIN_FLAG_NONPREROTATED = 1, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH = 2, + DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE = 4, + DXGI_SWAP_CHAIN_FLAG_RESTRICTED_CONTENT = 8, + DXGI_SWAP_CHAIN_FLAG_RESTRICT_SHARED_RESOURCE_DRIVER = 16, + DXGI_SWAP_CHAIN_FLAG_DISPLAY_ONLY = 32, + DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT = 64, + DXGI_SWAP_CHAIN_FLAG_FOREGROUND_LAYER = 128, + DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO = 256, + DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO = 512, +}} +STRUCT!{struct DXGI_SWAP_CHAIN_DESC { + BufferDesc: ::DXGI_MODE_DESC, + SampleDesc: ::DXGI_SAMPLE_DESC, + BufferUsage: ::DXGI_USAGE, + BufferCount: ::UINT, + OutputWindow: ::HWND, + Windowed: ::BOOL, + SwapEffect: DXGI_SWAP_EFFECT, + Flags: ::UINT, +}} +RIDL!( +interface IDXGIObject(IDXGIObjectVtbl): IUnknown(IUnknownVtbl) { + fn SetPrivateData( + &mut self, Name: ::REFGUID, DataSize: ::UINT, pData: *const ::c_void + ) -> ::HRESULT, + fn SetPrivateDataInterface(&mut self, Name: ::REFGUID, pUnknown: *const ::IUnknown) -> ::HRESULT, + fn GetPrivateData( + &mut self, Name: ::REFGUID, pDataSize: *mut ::UINT, pData: *mut ::c_void + ) -> ::HRESULT, + fn GetParent( + &mut self, riid: ::REFIID, ppParent: *mut *mut ::c_void + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDevice(&mut self, riid: ::REFIID, ppDevice: *mut *mut ::c_void) -> ::HRESULT +}); +RIDL!( +interface IDXGIResource(IDXGIResourceVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn GetSharedHandle(&mut self, pSharedHandle: *mut ::HANDLE) -> ::HRESULT, + fn GetUsage(&mut self, pUsage: *mut ::DXGI_USAGE) -> ::HRESULT, + fn SetEvictionPriority(&mut self, EvictionPriority: ::UINT) -> ::HRESULT, + fn GetEvictionPriority(&mut self, pEvictionPriority: *mut ::UINT) -> ::HRESULT +}); +RIDL!( +interface IDXGIKeyedMutex(IDXGIKeyedMutexVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn AcquireSync(&mut self, Key: ::UINT64, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn ReleaseSync(&mut self, Key: ::UINT64) -> ::HRESULT +}); +RIDL!( +interface IDXGISurface(IDXGISurfaceVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut DXGI_SURFACE_DESC) -> ::HRESULT, + fn Map(&mut self, pLockedRect: *mut DXGI_MAPPED_RECT, MapFlags: ::UINT) -> ::HRESULT, + fn Unmap(&mut self) -> ::HRESULT +}); +RIDL!( +interface IDXGISurface1(IDXGISurface1Vtbl): IDXGISurface(IDXGISurfaceVtbl) { + fn GetDC(&mut self, Discard: ::BOOL, phdc: *mut ::HDC) -> ::HRESULT, + fn ReleaseDC(&mut self, pDirtyRect: *mut ::RECT) -> ::HRESULT +}); +RIDL!( +interface IDXGIAdapter(IDXGIAdapterVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn EnumOutputs(&mut self, Output: ::UINT, ppOutput: *mut *mut IDXGIOutput) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut DXGI_ADAPTER_DESC) -> ::HRESULT, + fn CheckInterfaceSupport( + &mut self, InterfaceName: ::REFGUID, pUMDVersion: *mut ::LARGE_INTEGER + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIOutput(IDXGIOutputVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut DXGI_OUTPUT_DESC) -> ::HRESULT, + fn GetDisplayModeList( + &mut self, EnumFormat: ::DXGI_FORMAT, Flags: ::UINT, pNumModes: *mut ::UINT, + pDesc: *mut ::DXGI_MODE_DESC + ) -> ::HRESULT, + fn FindClosestMatchingMode( + &mut self, pModeToMatch: *const ::DXGI_MODE_DESC, pClosestMatch: *mut ::DXGI_MODE_DESC, + pConcernedDevice: *mut ::IUnknown + ) -> ::HRESULT, + fn WaitForVBlank(&mut self) -> ::HRESULT, + fn TakeOwnership(&mut self, pDevice: *mut ::IUnknown, Exclusive: ::BOOL) -> ::HRESULT, + fn ReleaseOwnership(&mut self) -> (), + fn GetGammaControlCapabilities( + &mut self, pGammaCaps: *mut ::DXGI_GAMMA_CONTROL_CAPABILITIES + ) -> ::HRESULT, + fn SetGammaControl(&mut self, pArray: *const ::DXGI_GAMMA_CONTROL) -> ::HRESULT, + fn GetGammaControl(&mut self, pArray: *mut ::DXGI_GAMMA_CONTROL) -> ::HRESULT, + fn SetDisplaySurface(&mut self, pScanoutSurface: *mut IDXGISurface) -> ::HRESULT, + fn GetDisplaySurfaceData(&mut self, pDestination: *mut IDXGISurface) -> ::HRESULT, + fn GetFrameStatistics(&mut self, pStats: *mut DXGI_FRAME_STATISTICS) -> ::HRESULT +}); +pub const DXGI_MAX_SWAP_CHAIN_BUFFERS: ::DWORD = 16; +pub const DXGI_PRESENT_TEST: ::DWORD = 0x00000001; +pub const DXGI_PRESENT_DO_NOT_SEQUENCE: ::DWORD = 0x00000002; +pub const DXGI_PRESENT_RESTART: ::DWORD = 0x00000004; +pub const DXGI_PRESENT_DO_NOT_WAIT: ::DWORD = 0x00000008; +pub const DXGI_PRESENT_STEREO_PREFER_RIGHT: ::DWORD = 0x00000010; +pub const DXGI_PRESENT_STEREO_TEMPORARY_MONO: ::DWORD = 0x00000020; +pub const DXGI_PRESENT_RESTRICT_TO_OUTPUT: ::DWORD = 0x00000040; +pub const DXGI_PRESENT_USE_DURATION: ::DWORD = 0x00000100; +RIDL!( +interface IDXGISwapChain(IDXGISwapChainVtbl): IDXGIDeviceSubObject(IDXGIDeviceSubObjectVtbl) { + fn Present(&mut self, SyncInterval: ::UINT, Flags: ::UINT) -> ::HRESULT, + fn GetBuffer( + &mut self, Buffer: ::UINT, riid: ::REFIID, ppSurface: *mut *mut ::c_void + ) -> ::HRESULT, + fn SetFullscreenState(&mut self, Fullscreen: ::BOOL, pTarget: *mut IDXGIOutput) -> ::HRESULT, + fn GetFullscreenState( + &mut self, pFullscreen: *mut ::BOOL, ppTarget: *mut *mut IDXGIOutput + ) -> ::HRESULT, + fn GetDesc(&mut self, pDesc: *mut DXGI_SWAP_CHAIN_DESC) -> ::HRESULT, + fn ResizeBuffers( + &mut self, BufferCount: ::UINT, Width: ::UINT, Height: ::UINT, NewFormat: ::DXGI_FORMAT, + SwapChainFlags: ::UINT + ) -> ::HRESULT, + fn ResizeTarget(&mut self, pNewTargetParameters: *const ::DXGI_MODE_DESC) -> ::HRESULT, + fn GetContainingOutput(&mut self, ppOutput: *mut *mut IDXGIOutput) -> ::HRESULT, + fn GetFrameStatistics(&mut self, pStats: *mut DXGI_FRAME_STATISTICS) -> ::HRESULT, + fn GetLastPresentCount(&mut self, pLastPresentCount: *mut ::UINT) -> ::HRESULT +}); +RIDL!( +interface IDXGIFactory(IDXGIFactoryVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn EnumAdapters(&mut self, Adapter: ::UINT, ppAdapter: *mut *mut IDXGIAdapter) -> ::HRESULT, + fn MakeWindowAssociation(&mut self, WindowHandle: ::HWND, Flags: ::UINT) -> ::HRESULT, + fn GetWindowAssociation(&mut self, pWindowHandle: *mut ::HWND) -> ::HRESULT, + fn CreateSwapChain( + &mut self, pDevice: *mut ::IUnknown, pDesc: *mut DXGI_SWAP_CHAIN_DESC, + ppSwapChain: *mut *mut IDXGISwapChain + ) -> ::HRESULT, + fn CreateSoftwareAdapter( + &mut self, Module: ::HMODULE, ppAdapter: *mut *mut IDXGIAdapter + ) -> ::HRESULT +}); +RIDL!( +interface IDXGIDevice(IDXGIDeviceVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetAdapter(&mut self, pAdapter: *mut *mut IDXGIAdapter) -> ::HRESULT, + fn CreateSurface( + &mut self, pDesc: *const DXGI_SURFACE_DESC, NumSurfaces: ::UINT, Usage: ::DXGI_USAGE, + pSharedResource: *const DXGI_SHARED_RESOURCE, ppSurface: *mut *mut IDXGISurface + ) -> ::HRESULT, + fn QueryResourceResidency( + &mut self, ppResources: *const *mut ::IUnknown, pResidencyStatus: *mut DXGI_RESIDENCY, + NumResources: ::UINT + ) -> ::HRESULT, + fn SetGPUThreadPriority(&mut self, Priority: ::INT) -> ::HRESULT, + fn GetGPUThreadPriority(&mut self, pPriority: *mut ::INT) -> ::HRESULT +}); +ENUM!{enum DXGI_ADAPTER_FLAG { + DXGI_ADAPTER_FLAG_NONE, + DXGI_ADAPTER_FLAG_REMOTE, + DXGI_ADAPTER_FLAG_SOFTWARE, +}} +STRUCT!{nodebug struct DXGI_ADAPTER_DESC1 { + Description: [::WCHAR; 128], + VendorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, + Flags: ::UINT, +}} +STRUCT!{struct DXGI_DISPLAY_COLOR_SPACE { + PrimaryCoordinates: [[::FLOAT; 2]; 8], + WhitePoints: [[::FLOAT; 2]; 16], +}} +RIDL!( +interface IDXGIFactory1(IDXGIFactory1Vtbl): IDXGIFactory(IDXGIFactoryVtbl) { + fn EnumAdapters1(&mut self, Adapter: ::UINT, ppAdapter: *mut *mut IDXGIAdapter1) -> ::HRESULT, + fn IsCurrent(&mut self) -> ::BOOL +}); +RIDL!( +interface IDXGIAdapter1(IDXGIAdapter1Vtbl): IDXGIAdapter(IDXGIAdapterVtbl) { + fn GetDesc1(&mut self, pDesc: *mut DXGI_ADAPTER_DESC1) -> ::HRESULT +}); +RIDL!( +interface IDXGIDevice1(IDXGIDevice1Vtbl): IDXGIDevice(IDXGIDeviceVtbl) { + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT +}); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_2.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_2.rs new file mode 100644 index 0000000..4208274 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_2.rs @@ -0,0 +1,288 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License +//! Mappings for the contents of dxgi1_2.h + +ENUM!{ enum DXGI_ALPHA_MODE { + DXGI_ALPHA_MODE_UNSPECIFIED = 0, + DXGI_ALPHA_MODE_PREMULTIPLIED = 1, + DXGI_ALPHA_MODE_STRAIGHT = 2, + DXGI_ALPHA_MODE_IGNORE = 3, + DXGI_ALPHA_MODE_FORCE_DWORD = 0xFFFFFFFF, +}} + +ENUM!{ enum DXGI_COMPUTE_PREEMPTION_GRANULARITY { + DXGI_COMPUTE_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_COMPUTE_PREEMPTION_DISPATCH_BOUNDARY = 1, + DXGI_COMPUTE_PREEMPTION_THREAD_GROUP_BOUNDARY = 2, + DXGI_COMPUTE_PREEMPTION_THREAD_BOUNDARY = 3, + DXGI_COMPUTE_PREEMPTION_INSTRUCTION_BOUNDARY = 4, +}} + +ENUM!{ enum DXGI_GRAPHICS_PREEMPTION_GRANULARITY { + DXGI_GRAPHICS_PREEMPTION_DMA_BUFFER_BOUNDARY = 0, + DXGI_GRAPHICS_PREEMPTION_PRIMITIVE_BOUNDARY = 1, + DXGI_GRAPHICS_PREEMPTION_TRIANGLE_BOUNDARY = 2, + DXGI_GRAPHICS_PREEMPTION_PIXEL_BOUNDARY = 3, + DXGI_GRAPHICS_PREEMPTION_INSTRUCTION_BOUNDARY = 4, +}} + +ENUM!{ enum DXGI_OUTDUPL_POINTER_SHAPE_TYPE { + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME = 1, + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR = 2, + DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MASKED_COLOR = 4, +}} + +ENUM!{ enum DXGI_SCALING { + DXGI_SCALING_STRETCH = 0, + DXGI_SCALING_NONE = 1, + DXGI_SCALING_ASPECT_RATIO_STRETCH = 2, +}} + +ENUM!{ enum _DXGI_OFFER_RESOURCE_PRIORITY { + DXGI_OFFER_RESOURCE_PRIORITY_LOW = 1, + DXGI_OFFER_RESOURCE_PRIORITY_NORMAL = 2, + DXGI_OFFER_RESOURCE_PRIORITY_HIGH = 3, +}} + +STRUCT!{nodebug struct DXGI_ADAPTER_DESC2 { + Description: [::WCHAR; 128], + VendorId: ::UINT, + DeviceId: ::UINT, + SubSysId: ::UINT, + Revision: ::UINT, + DedicatedVideoMemory: ::SIZE_T, + DedicatedSystemMemory: ::SIZE_T, + SharedSystemMemory: ::SIZE_T, + AdapterLuid: ::LUID, + Flags: ::UINT, + GraphicsPreemptionGranularity: ::DXGI_GRAPHICS_PREEMPTION_GRANULARITY, + ComputePreemptionGranularity: ::DXGI_COMPUTE_PREEMPTION_GRANULARITY, +}} + +STRUCT!{struct DXGI_MODE_DESC1 { + Width: ::UINT, + Height: ::UINT, + RefreshRate: ::DXGI_RATIONAL, + Format: ::DXGI_FORMAT, + ScanlineOrdering: ::DXGI_MODE_SCANLINE_ORDER, + Scaling: ::DXGI_MODE_SCALING, + Stereo: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_DESC { + ModeDesc: ::DXGI_MODE_DESC, + Rotation: ::DXGI_MODE_ROTATION, + DesktopImageInSystemMemory: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_FRAME_INFO { + LastPresentTime: ::LARGE_INTEGER, + LastMouseUpdateTime: ::LARGE_INTEGER, + AccumulatedFrames: ::UINT, + RectsCoalesced: ::BOOL, + ProtectedContentMaskedOut: ::BOOL, + PointerPosition: ::DXGI_OUTDUPL_POINTER_POSITION, + TotalMetadataBufferSize: ::UINT, + PointerShapeBufferSize: ::UINT, +}} + +STRUCT!{struct DXGI_OUTDUPL_MOVE_RECT { + SourcePoint: ::POINT, + DestinationRect: ::RECT, +}} + +STRUCT!{struct DXGI_OUTDUPL_POINTER_POSITION { + Position: ::POINT, + Visible: ::BOOL, +}} + +STRUCT!{struct DXGI_OUTDUPL_POINTER_SHAPE_INFO { + Type: ::UINT, + Width: ::UINT, + Height: ::UINT, + Pitch: ::UINT, + HotSpot: ::POINT, +}} + +STRUCT!{struct DXGI_PRESENT_PARAMETERS { + DirtyRectsCount: ::UINT, + pDirtyRects: *mut ::RECT, + pScrollRect: *mut ::RECT, + pScrollOffset: *mut ::POINT, +}} + +STRUCT!{struct DXGI_SWAP_CHAIN_DESC1 { + Width: ::UINT, + Height: ::UINT, + Format: ::DXGI_FORMAT, + Stereo: ::BOOL, + SampleDesc: ::DXGI_SAMPLE_DESC, + BufferUsage: ::DXGI_USAGE, + BufferCount: ::UINT, + Scaling: ::DXGI_SCALING, + SwapEffect: ::DXGI_SWAP_EFFECT, + AlphaMode: ::DXGI_ALPHA_MODE, + Flags: ::UINT, +}} + +STRUCT!{struct DXGI_SWAP_CHAIN_FULLSCREEN_DESC { + RefreshRate: ::DXGI_RATIONAL, + ScanlineOrdering: ::DXGI_MODE_SCANLINE_ORDER, + Scaling: ::DXGI_MODE_SCALING, + Windowed: ::BOOL, +}} + +RIDL!( +interface IDXGIAdapter2(IDXGIAdapter2Vtbl): IDXGIAdapter1(IDXGIAdapter1Vtbl) { + fn GetDesc2(&mut self, pDesc: *mut ::DXGI_ADAPTER_DESC2) -> ::HRESULT +}); + +RIDL!( +interface IDXGIDevice2(IDXGIDevice2Vtbl): IDXGIDevice1(IDXGIDevice1Vtbl) { + fn OfferResources( + &mut self, NumResources: ::UINT, ppResources: *mut *mut ::IDXGIResource, + Priority: ::DXGI_OFFER_RESOURCE_PRIORITY + ) -> ::HRESULT, + fn ReclaimResources( + &mut self, NumResources: ::UINT, ppResources: *mut *mut ::IDXGIResource, + pDiscarded: *mut ::BOOL + ) -> ::HRESULT, + fn EnqueueSetEvent(&mut self, hEvent: ::HANDLE) -> ::HRESULT +}); + +RIDL!( +interface IDXGIDisplayControl(IDXGIDisplayControlVtbl): IUnknown(IUnknownVtbl) { + fn IsStereoEnabled(&mut self) -> ::BOOL, + fn SetStereoEnabled(&mut self, enabled: ::BOOL) -> () +}); + +RIDL!( +interface IDXGIFactory2(IDXGIFactory2Vtbl): IDXGIFactory1(IDXGIFactory1Vtbl) { + fn IsWindowedStereoEnabled(&mut self) -> ::BOOL, + fn CreateSwapChainForHwnd( + &mut self, pDevice: *mut ::IUnknown, hWnd: ::HWND, pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, + pFullscreenDesc: *const ::DXGI_SWAP_CHAIN_FULLSCREEN_DESC, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn CreateSwapChainForCoreWindow( + &mut self, pDevice: *mut ::IUnknown, pWindow: *mut ::IUnknown, + pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: *mut ::IDXGIOutput, + ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn GetSharedResourceAdapterLuid( + &mut self, hResource: ::HANDLE, pLuid: *mut ::LUID + ) -> ::HRESULT, + fn RegisterStereoStatusWindow( + &mut self, WindowHandle: ::HWND, wMsg: ::UINT, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn RegisterStereoStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterStereoStatus(&mut self, dwCookie: ::DWORD) -> (), + fn RegisterOcclusionStatusWindow( + &mut self, WindowHandle: ::HWND, wMsg: ::UINT, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn RegisterOcclusionStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterOcclusionStatus(&mut self, dwCookie: ::DWORD) -> (), + fn CreateSwapChainForComposition( + &mut self, pDevice: *mut ::IUnknown, pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput1(IDXGIOutput1Vtbl): IDXGIOutput(IDXGIOutputVtbl) { + fn GetDisplayModeList1( + &mut self, EnumFormat: ::DXGI_FORMAT, Flags: ::UINT, pNumModes: *mut ::UINT, + pDesc: *mut ::DXGI_MODE_DESC1 + ) -> ::HRESULT, + fn FindClosestMatchingMode1( + &mut self, pModeToMatch: *const ::DXGI_MODE_DESC1, pClosestMatch: *mut ::DXGI_MODE_DESC1, + pConcernedDevice: *mut ::IUnknown + ) -> ::HRESULT, + fn GetDisplaySurfaceData1( + &mut self, pDestination: *mut ::IDXGIResource + ) -> ::HRESULT, + fn DuplicateOutput( + &mut self, pDevice: *mut ::IUnknown, + ppOutputDuplication: *mut *mut ::IDXGIOutputDuplication + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutputDuplication(IDXGIOutputDuplicationVtbl): IDXGIObject(IDXGIObjectVtbl) { + fn GetDesc(&mut self, pDesc: *mut ::DXGI_OUTDUPL_DESC) -> (), + fn AcquireNextFrame( + &mut self, TimeoutInMilliseconds: ::UINT, pFrameInfo: *mut ::DXGI_OUTDUPL_FRAME_INFO, + ppDesktopResource: *mut *mut ::IDXGIResource + ) -> ::HRESULT, + fn GetFrameDirtyRects( + &mut self, DirtyRectsBufferSize: ::UINT, pDirtyRectsBuffer: *mut ::RECT, + pDirtyRectsBufferSizeRequired: *mut ::UINT + ) -> ::HRESULT, + fn GetFrameMoveRects( + &mut self, MoveRectsBufferSize: ::UINT, pMoveRectBuffer: *mut ::DXGI_OUTDUPL_MOVE_RECT, + pMoveRectsBufferSizeRequired: *mut ::UINT + ) -> ::HRESULT, + fn GetFramePointerShape( + &mut self, PointerShapeBufferSize: ::UINT, pPointerShapeBuffer: *mut ::c_void, + pPointerShapeBufferSizeRequired: *mut ::UINT, + pPointerShapeInfo: *mut ::DXGI_OUTDUPL_POINTER_SHAPE_INFO + ) -> ::HRESULT, + fn MapDesktopSurface( + &mut self, pLockedRect: *mut ::DXGI_MAPPED_RECT + ) -> ::HRESULT, + fn UnMapDesktopSurface(&mut self) -> ::HRESULT, + fn ReleaseFrame(&mut self) -> ::HRESULT +}); + +RIDL!( +interface IDXGIResource1(IDXGIResource1Vtbl): IDXGIResource(IDXGIResourceVtbl) { + fn CreateSubresourceSurface( + &mut self, index: ::UINT, ppSurface: *mut *mut ::IDXGISurface2 + ) -> ::HRESULT, + fn CreateSharedHandle( + &mut self, pAttributes: *const ::SECURITY_ATTRIBUTES, dwAccess: ::DWORD, lpName: ::LPCWSTR, + pHandle: *mut ::HANDLE + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISurface2(IDXGISurface2Vtbl): IDXGISurface1(IDXGISurface1Vtbl) { + fn GetResource( + &mut self, riid: ::REFGUID, ppParentResource: *mut *mut ::c_void, + pSubresourceIndex: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain1(IDXGISwapChain1Vtbl): IDXGISwapChain(IDXGISwapChainVtbl) { + fn GetDesc1(&mut self, pDesc: *mut ::DXGI_SWAP_CHAIN_DESC1) -> ::HRESULT, + fn GetFullscreenDesc( + &mut self, pDesc: *mut ::DXGI_SWAP_CHAIN_FULLSCREEN_DESC + ) -> ::HRESULT, + fn GetHwnd(&mut self, pHwnd: *mut ::HWND) -> ::HRESULT, + fn GetCoreWindow( + &mut self, refiid: ::REFGUID, ppUnk: *mut *mut ::c_void + ) -> ::HRESULT, + fn Present1( + &mut self, SyncInterval: ::UINT, PresentFlags: ::UINT, + pPresentParameters: *const ::DXGI_PRESENT_PARAMETERS + ) -> ::HRESULT, + fn IsTemporaryMonoSupported(&mut self) -> ::BOOL, + fn GetRestrictToOutput( + &mut self, ppRestrictToOutput: *mut *mut ::IDXGIOutput + ) -> ::HRESULT, + fn SetBackgroundColor(&mut self, pColor: *const ::DXGI_RGBA) -> ::HRESULT, + fn GetBackgroundColor(&mut self, pColor: *mut ::DXGI_RGBA) -> ::HRESULT, + fn SetRotation(&mut self, Rotation: ::DXGI_MODE_ROTATION) -> ::HRESULT, + fn GetRotation(&mut self, pRotation: *mut ::DXGI_MODE_ROTATION) -> ::HRESULT +}); + +pub type DXGI_OFFER_RESOURCE_PRIORITY = ::_DXGI_OFFER_RESOURCE_PRIORITY; +pub const DXGI_ENUM_MODES_DISABLED_STEREO: ::UINT = 8; +pub const DXGI_ENUM_MODES_STEREO: ::UINT = 4; +pub const DXGI_SHARED_RESOURCE_READ: ::UINT = 0x80000000; +pub const DXGI_SHARED_RESOURCE_WRITE: ::UINT = 1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_3.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_3.rs new file mode 100644 index 0000000..71acf98 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_3.rs @@ -0,0 +1,131 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License +//! Mappings for the contents of dxgi1_3.h + +ENUM!{ enum DXGI_FRAME_PRESENTATION_MODE { + DXGI_FRAME_PRESENTATION_MODE_COMPOSED = 0, + DXGI_FRAME_PRESENTATION_MODE_OVERLAY = 1, + DXGI_FRAME_PRESENTATION_MODE_NONE = 2, + DXGI_FRAME_PRESENTATION_MODE_COMPOSITION_FAILURE = 3, +}} + +FLAGS!{ enum DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS { + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_NOMINAL_RANGE = 0x1, + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_BT709 = 0x2, + DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAG_xvYCC = 0x4, +}} + +FLAGS!{ enum DXGI_OVERLAY_SUPPORT_FLAG { + DXGI_OVERLAY_SUPPORT_FLAG_DIRECT = 0x1, + DXGI_OVERLAY_SUPPORT_FLAG_SCALING = 0x2, +}} + +STRUCT!{struct DXGI_DECODE_SWAP_CHAIN_DESC { + Flags: ::UINT, +}} + +STRUCT!{struct DXGI_FRAME_STATISTICS_MEDIA { + PresentCount: ::UINT, + PresentRefreshCount: ::UINT, + SyncRefreshCount: ::UINT, + SyncQPCTime: ::LARGE_INTEGER, + SyncGPUTime: ::LARGE_INTEGER, + CompositionMode: ::DXGI_FRAME_PRESENTATION_MODE, + ApprovedPresentDuration: ::UINT, +}} + +STRUCT!{struct DXGI_MATRIX_3X2_F { + _11: ::FLOAT, + _12: ::FLOAT, + _21: ::FLOAT, + _22: ::FLOAT, + _31: ::FLOAT, + _32: ::FLOAT, +}} + +RIDL!( +interface IDXGIDecodeSwapChain(IDXGIDecodeSwapChainVtbl): IUnknown(IUnknownVtbl) { + fn PresentBuffer( + &mut self, BufferToPresent: ::UINT, SyncInterval: ::UINT, Flags: ::UINT + ) -> ::HRESULT, + fn SetSourceRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn SetTargetRect(&mut self, pRect: *const ::RECT) -> ::HRESULT, + fn SetDestSize(&mut self, Width: ::UINT, Height: ::UINT) -> ::HRESULT, + fn GetSourceRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn GetTargetRect(&mut self, pRect: *mut ::RECT) -> ::HRESULT, + fn GetDestSize( + &mut self, pWidth: *mut ::UINT, pHeight: *mut ::UINT + ) -> ::HRESULT, + fn SetColorSpace( + &mut self, ColorSpace: ::DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS + ) -> ::HRESULT, + fn GetColorSpace(&mut self) -> ::DXGI_MULTIPLANE_OVERLAY_YCbCr_FLAGS +}); + +RIDL!( +interface IDXGIDevice3(IDXGIDevice3Vtbl): IDXGIDevice2(IDXGIDevice2Vtbl) { + fn Trim(&mut self) -> () +}); + +RIDL!( +interface IDXGIFactory3(IDXGIFactory3Vtbl): IDXGIFactory2(IDXGIFactory2Vtbl) { + fn GetCreationFlags(&mut self) -> ::UINT +}); + +RIDL!( +interface IDXGIFactoryMedia(IDXGIFactoryMediaVtbl): IUnknown(IUnknownVtbl) { + fn CreateSwapChainForCompositionSurfaceHandle( + &mut self, pDevice: *mut ::IUnknown, hSurface: ::HANDLE, + pDesc: *const ::DXGI_SWAP_CHAIN_DESC1, pRestrictToOutput: *mut ::IDXGIOutput, + ppSwapChain: *mut *mut ::IDXGISwapChain1 + ) -> ::HRESULT, + fn CreateDecodeSwapChainForCompositionSurfaceHandle( + &mut self, pDevice: *mut ::IUnknown, hSurface: ::HANDLE, + pDesc: *mut ::DXGI_DECODE_SWAP_CHAIN_DESC, pYuvDecodeBuffers: *mut ::IDXGIResource, + pRestrictToOutput: *mut ::IDXGIOutput, ppSwapChain: *mut *mut ::IDXGIDecodeSwapChain + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput2(IDXGIOutput2Vtbl): IDXGIOutput1(IDXGIOutput1Vtbl) { + fn SupportsOverlays(&mut self) -> ::BOOL +}); + +RIDL!( +interface IDXGIOutput3(IDXGIOutput3Vtbl): IDXGIOutput2(IDXGIOutput2Vtbl) { + fn CheckOverlaySupport( + &mut self, EnumFormat: ::DXGI_FORMAT, pConcernedDevice: *mut ::IUnknown, + pFlags: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain2(IDXGISwapChain2Vtbl): IDXGISwapChain1(IDXGISwapChain1Vtbl) { + fn SetSourceSize(&mut self, Width: ::UINT, Height: ::UINT) -> ::HRESULT, + fn GetSourceSize( + &mut self, pWidth: *mut ::UINT, pHeight: *mut ::UINT + ) -> ::HRESULT, + fn SetMaximumFrameLatency(&mut self, MaxLatency: ::UINT) -> ::HRESULT, + fn GetMaximumFrameLatency(&mut self, pMaxLatency: *mut ::UINT) -> ::HRESULT, + fn GetFrameLatencyWaitableObject(&mut self) -> ::HANDLE, + fn SetMatrixTransform( + &mut self, pMatrix: *const ::DXGI_MATRIX_3X2_F + ) -> ::HRESULT, + fn GetMatrixTransform( + &mut self, pMatrix: *mut ::DXGI_MATRIX_3X2_F + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChainMedia(IDXGISwapChainMediaVtbl): IUnknown(IUnknownVtbl) { + fn GetFrameStatisticsMedia( + &mut self, pStats: *mut ::DXGI_FRAME_STATISTICS_MEDIA + ) -> ::HRESULT, + fn SetPresentDuration(&mut self, Duration: ::UINT) -> ::HRESULT, + fn CheckPresentDurationSupport( + &mut self, DesiredPresentDuration: ::UINT, pClosestSmallerPresentDuration: *mut ::UINT, + pClosestLargerPresentDuration: *mut ::UINT + ) -> ::HRESULT +}); + +pub const DXGI_CREATE_FACTORY_DEBUG: ::UINT = 0x1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_4.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_4.rs new file mode 100644 index 0000000..cbca18f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgi1_4.rs @@ -0,0 +1,82 @@ +// Copyright © 2015; Dmitry Roschin +// Licensed under the MIT License +//! Mappings for the contents of dxgi1_4.h + +ENUM!{ enum DXGI_MEMORY_SEGMENT_GROUP { + DXGI_MEMORY_SEGMENT_GROUP_LOCAL = 0, + DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL = 1, +}} + +FLAGS!{ enum DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG { + DXGI_OVERLAY_COLOR_SPACE_SUPPORT_FLAG_PRESENT = 0x1, +}} + +FLAGS!{ enum DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG { + DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_PRESENT = 0x1, + DXGI_SWAP_CHAIN_COLOR_SPACE_SUPPORT_FLAG_OVERLAY_PRESENT = 0x2, +}} + +STRUCT!{struct DXGI_QUERY_VIDEO_MEMORY_INFO { + Budget: ::UINT64, + CurrentUsage: ::UINT64, + AvailableForReservation: ::UINT64, + CurrentReservation: ::UINT64, +}} + +RIDL!( +interface IDXGIAdapter3(IDXGIAdapter3Vtbl): IDXGIAdapter2(IDXGIAdapter2Vtbl) { + fn RegisterHardwareContentProtectionTeardownStatusEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterHardwareContentProtectionTeardownStatus( + &mut self, dwCookie: ::DWORD + ) -> (), + fn QueryVideoMemoryInfo( + &mut self, NodeIndex: ::UINT, MemorySegmentGroup: ::DXGI_MEMORY_SEGMENT_GROUP, + pVideoMemoryInfo: *mut ::DXGI_QUERY_VIDEO_MEMORY_INFO + ) -> ::HRESULT, + fn SetVideoMemoryReservation( + &mut self, NodeIndex: ::UINT, MemorySegmentGroup: ::DXGI_MEMORY_SEGMENT_GROUP, + Reservation: ::UINT64 + ) -> ::HRESULT, + fn RegisterVideoMemoryBudgetChangeNotificationEvent( + &mut self, hEvent: ::HANDLE, pdwCookie: *mut ::DWORD + ) -> ::HRESULT, + fn UnregisterVideoMemoryBudgetChangeNotification( + &mut self, dwCookie: ::DWORD + ) -> () +}); + +RIDL!( +interface IDXGIFactory4(IDXGIFactory4Vtbl): IDXGIFactory3(IDXGIFactory3Vtbl) { + fn EnumAdapterByLuid( + &mut self, AdapterLuid: ::LUID, riid: ::REFGUID, ppvAdapter: *mut *mut ::c_void + ) -> ::HRESULT, + fn EnumWarpAdapter( + &mut self, riid: ::REFGUID, ppvAdapter: *mut *mut ::c_void + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGIOutput4(IDXGIOutput4Vtbl): IDXGIOutput3(IDXGIOutput3Vtbl) { + fn CheckOverlayColorSpaceSupport( + &mut self, Format: ::DXGI_FORMAT, ColorSpace: ::DXGI_COLOR_SPACE_TYPE, + pConcernedDevice: *mut ::IUnknown, pFlags: *mut ::UINT + ) -> ::HRESULT +}); + +RIDL!( +interface IDXGISwapChain3(IDXGISwapChain3Vtbl): IDXGISwapChain2(IDXGISwapChain2Vtbl) { + fn GetCurrentBackBufferIndex(&mut self) -> ::UINT, + fn CheckColorSpaceSupport( + &mut self, ColorSpace: ::DXGI_COLOR_SPACE_TYPE, pColorSpaceSupport: *mut ::UINT + ) -> ::HRESULT, + fn SetColorSpace1( + &mut self, ColorSpace: ::DXGI_COLOR_SPACE_TYPE + ) -> ::HRESULT, + fn ResizeBuffers1( + &mut self, BufferCount: ::UINT, Width: ::UINT, Height: ::UINT, Format: ::DXGI_FORMAT, + SwapChainFlags: ::UINT, pCreationNodeMask: *const ::UINT, + ppPresentQueue: *mut *mut ::IUnknown + ) -> ::HRESULT +}); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgiformat.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgiformat.rs new file mode 100644 index 0000000..3e46fc2 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgiformat.rs @@ -0,0 +1,124 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of dxgiformat.h +ENUM!{enum DXGI_FORMAT { + DXGI_FORMAT_UNKNOWN = 0, + DXGI_FORMAT_R32G32B32A32_TYPELESS = 1, + DXGI_FORMAT_R32G32B32A32_FLOAT = 2, + DXGI_FORMAT_R32G32B32A32_UINT = 3, + DXGI_FORMAT_R32G32B32A32_SINT = 4, + DXGI_FORMAT_R32G32B32_TYPELESS = 5, + DXGI_FORMAT_R32G32B32_FLOAT = 6, + DXGI_FORMAT_R32G32B32_UINT = 7, + DXGI_FORMAT_R32G32B32_SINT = 8, + DXGI_FORMAT_R16G16B16A16_TYPELESS = 9, + DXGI_FORMAT_R16G16B16A16_FLOAT = 10, + DXGI_FORMAT_R16G16B16A16_UNORM = 11, + DXGI_FORMAT_R16G16B16A16_UINT = 12, + DXGI_FORMAT_R16G16B16A16_SNORM = 13, + DXGI_FORMAT_R16G16B16A16_SINT = 14, + DXGI_FORMAT_R32G32_TYPELESS = 15, + DXGI_FORMAT_R32G32_FLOAT = 16, + DXGI_FORMAT_R32G32_UINT = 17, + DXGI_FORMAT_R32G32_SINT = 18, + DXGI_FORMAT_R32G8X24_TYPELESS = 19, + DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20, + DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22, + DXGI_FORMAT_R10G10B10A2_TYPELESS = 23, + DXGI_FORMAT_R10G10B10A2_UNORM = 24, + DXGI_FORMAT_R10G10B10A2_UINT = 25, + DXGI_FORMAT_R11G11B10_FLOAT = 26, + DXGI_FORMAT_R8G8B8A8_TYPELESS = 27, + DXGI_FORMAT_R8G8B8A8_UNORM = 28, + DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29, + DXGI_FORMAT_R8G8B8A8_UINT = 30, + DXGI_FORMAT_R8G8B8A8_SNORM = 31, + DXGI_FORMAT_R8G8B8A8_SINT = 32, + DXGI_FORMAT_R16G16_TYPELESS = 33, + DXGI_FORMAT_R16G16_FLOAT = 34, + DXGI_FORMAT_R16G16_UNORM = 35, + DXGI_FORMAT_R16G16_UINT = 36, + DXGI_FORMAT_R16G16_SNORM = 37, + DXGI_FORMAT_R16G16_SINT = 38, + DXGI_FORMAT_R32_TYPELESS = 39, + DXGI_FORMAT_D32_FLOAT = 40, + DXGI_FORMAT_R32_FLOAT = 41, + DXGI_FORMAT_R32_UINT = 42, + DXGI_FORMAT_R32_SINT = 43, + DXGI_FORMAT_R24G8_TYPELESS = 44, + DXGI_FORMAT_D24_UNORM_S8_UINT = 45, + DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46, + DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47, + DXGI_FORMAT_R8G8_TYPELESS = 48, + DXGI_FORMAT_R8G8_UNORM = 49, + DXGI_FORMAT_R8G8_UINT = 50, + DXGI_FORMAT_R8G8_SNORM = 51, + DXGI_FORMAT_R8G8_SINT = 52, + DXGI_FORMAT_R16_TYPELESS = 53, + DXGI_FORMAT_R16_FLOAT = 54, + DXGI_FORMAT_D16_UNORM = 55, + DXGI_FORMAT_R16_UNORM = 56, + DXGI_FORMAT_R16_UINT = 57, + DXGI_FORMAT_R16_SNORM = 58, + DXGI_FORMAT_R16_SINT = 59, + DXGI_FORMAT_R8_TYPELESS = 60, + DXGI_FORMAT_R8_UNORM = 61, + DXGI_FORMAT_R8_UINT = 62, + DXGI_FORMAT_R8_SNORM = 63, + DXGI_FORMAT_R8_SINT = 64, + DXGI_FORMAT_A8_UNORM = 65, + DXGI_FORMAT_R1_UNORM = 66, + DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67, + DXGI_FORMAT_R8G8_B8G8_UNORM = 68, + DXGI_FORMAT_G8R8_G8B8_UNORM = 69, + DXGI_FORMAT_BC1_TYPELESS = 70, + DXGI_FORMAT_BC1_UNORM = 71, + DXGI_FORMAT_BC1_UNORM_SRGB = 72, + DXGI_FORMAT_BC2_TYPELESS = 73, + DXGI_FORMAT_BC2_UNORM = 74, + DXGI_FORMAT_BC2_UNORM_SRGB = 75, + DXGI_FORMAT_BC3_TYPELESS = 76, + DXGI_FORMAT_BC3_UNORM = 77, + DXGI_FORMAT_BC3_UNORM_SRGB = 78, + DXGI_FORMAT_BC4_TYPELESS = 79, + DXGI_FORMAT_BC4_UNORM = 80, + DXGI_FORMAT_BC4_SNORM = 81, + DXGI_FORMAT_BC5_TYPELESS = 82, + DXGI_FORMAT_BC5_UNORM = 83, + DXGI_FORMAT_BC5_SNORM = 84, + DXGI_FORMAT_B5G6R5_UNORM = 85, + DXGI_FORMAT_B5G5R5A1_UNORM = 86, + DXGI_FORMAT_B8G8R8A8_UNORM = 87, + DXGI_FORMAT_B8G8R8X8_UNORM = 88, + DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, + DXGI_FORMAT_B8G8R8A8_TYPELESS = 90, + DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91, + DXGI_FORMAT_B8G8R8X8_TYPELESS = 92, + DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93, + DXGI_FORMAT_BC6H_TYPELESS = 94, + DXGI_FORMAT_BC6H_UF16 = 95, + DXGI_FORMAT_BC6H_SF16 = 96, + DXGI_FORMAT_BC7_TYPELESS = 97, + DXGI_FORMAT_BC7_UNORM = 98, + DXGI_FORMAT_BC7_UNORM_SRGB = 99, + DXGI_FORMAT_AYUV = 100, + DXGI_FORMAT_Y410 = 101, + DXGI_FORMAT_Y416 = 102, + DXGI_FORMAT_NV12 = 103, + DXGI_FORMAT_P010 = 104, + DXGI_FORMAT_P016 = 105, + DXGI_FORMAT_420_OPAQUE = 106, + DXGI_FORMAT_YUY2 = 107, + DXGI_FORMAT_Y210 = 108, + DXGI_FORMAT_Y216 = 109, + DXGI_FORMAT_NV11 = 110, + DXGI_FORMAT_AI44 = 111, + DXGI_FORMAT_IA44 = 112, + DXGI_FORMAT_P8 = 113, + DXGI_FORMAT_A8P8 = 114, + DXGI_FORMAT_B4G4R4A4_UNORM = 115, + DXGI_FORMAT_P208 = 130, + DXGI_FORMAT_V208 = 131, + DXGI_FORMAT_V408 = 132, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/dxgitype.rs b/third_party/cargo/vendor/winapi-0.2.8/src/dxgitype.rs new file mode 100644 index 0000000..6c9a2f5 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/dxgitype.rs @@ -0,0 +1,86 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of dxgitype.h +pub const DXGI_CPU_ACCESS_NONE: ::DWORD = 0; +pub const DXGI_CPU_ACCESS_DYNAMIC: ::DWORD = 1; +pub const DXGI_CPU_ACCESS_READ_WRITE: ::DWORD = 2; +pub const DXGI_CPU_ACCESS_SCRATCH: ::DWORD = 3; +pub const DXGI_CPU_ACCESS_FIELD: ::DWORD = 15; +FLAGS!{enum DXGI_USAGE { + DXGI_USAGE_SHADER_INPUT = 1 << (0 + 4), + DXGI_USAGE_RENDER_TARGET_OUTPUT = 1 << (1 + 4), + DXGI_USAGE_BACK_BUFFER = 1 << (2 + 4), + DXGI_USAGE_SHARED = 1 << (3 + 4), + DXGI_USAGE_READ_ONLY = 1 << (4 + 4), + DXGI_USAGE_DISCARD_ON_PRESENT = 1 << (5 + 4), + DXGI_USAGE_UNORDERED_ACCESS = 1 << (6 + 4), +}} +STRUCT!{struct DXGI_RGB { + Red: f32, + Green: f32, + Blue: f32, +}} +pub type DXGI_RGBA = ::D3DCOLORVALUE; +STRUCT!{nodebug struct DXGI_GAMMA_CONTROL { + Scale: DXGI_RGB, + Offset: DXGI_RGB, + GammaCurve: [DXGI_RGB; 1025], +}} +STRUCT!{nodebug struct DXGI_GAMMA_CONTROL_CAPABILITIES { + ScaleAndOffsetSupported: ::BOOL, + MaxConvertedValue: f32, + MinConvertedValue: f32, + NumGammaControlPoints: ::UINT, + ControlPointPositions: [f32; 1025], +}} +STRUCT!{struct DXGI_RATIONAL { + Numerator: ::UINT, + Denominator: ::UINT, +}} +ENUM!{enum DXGI_MODE_SCANLINE_ORDER { + DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED, + DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE, + DXGI_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST, + DXGI_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST, +}} +ENUM!{enum DXGI_MODE_SCALING { + DXGI_MODE_SCALING_UNSPECIFIED, + DXGI_MODE_SCALING_CENTERED, + DXGI_MODE_SCALING_STRETCHED, +}} +ENUM!{enum DXGI_MODE_ROTATION { + DXGI_MODE_ROTATION_UNSPECIFIED, + DXGI_MODE_ROTATION_IDENTITY, + DXGI_MODE_ROTATION_ROTATE90, + DXGI_MODE_ROTATION_ROTATE180, + DXGI_MODE_ROTATION_ROTATE270, +}} +STRUCT!{struct DXGI_MODE_DESC { + Width: ::UINT, + Height: ::UINT, + RefreshRate: DXGI_RATIONAL, + Format: ::DXGI_FORMAT, + ScanlineOrdering: DXGI_MODE_SCANLINE_ORDER, + Scaling: DXGI_MODE_SCALING, +}} +STRUCT!{struct DXGI_SAMPLE_DESC { + Count: ::UINT, + Quality: ::UINT, +}} +ENUM!{enum DXGI_COLOR_SPACE_TYPE { + DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709 = 0x0, + DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 = 0x1, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P709 = 0x2, + DXGI_COLOR_SPACE_RGB_STUDIO_G22_NONE_P2020 = 0x3, + DXGI_COLOR_SPACE_RESERVED = 0x4, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_NONE_P709_X601 = 0x5, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P601 = 0x6, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P601 = 0x7, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709 = 0x8, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709 = 0x9, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P2020 = 0xA, + DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P2020 = 0xB, + DXGI_COLOR_SPACE_CUSTOM = 0xFFFFFFFF, +}} +pub const DXGI_CENTER_MULTISAMPLE_QUALITY_PATTERN: ::UINT = 0xfffffffe; +pub const DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN: ::UINT = 0xffffffff; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/errhandlingapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/errhandlingapi.rs new file mode 100644 index 0000000..fbdde40 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/errhandlingapi.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-errorhandling-l1 +pub type PTOP_LEVEL_EXCEPTION_FILTER = Option ::LONG>; +pub type LPTOP_LEVEL_EXCEPTION_FILTER = PTOP_LEVEL_EXCEPTION_FILTER; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/excpt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/excpt.rs new file mode 100644 index 0000000..53ea3ff --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/excpt.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +ENUM!{enum EXCEPTION_DISPOSITION { + ExceptionContinueExecution = 0, + ExceptionContinueSearch = 1, + ExceptionNestedException = 2, + ExceptionCollidedUnwind = 3, +}} +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _EXCEPTION_RECORD; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _CONTEXT; +#[cfg(target_arch = "x86_64")] #[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct _DISPATCHER_CONTEXT; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/fileapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/fileapi.rs new file mode 100644 index 0000000..764a7f6 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/fileapi.rs @@ -0,0 +1,152 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-file-l1 +pub const CREATE_NEW: ::DWORD = 1; +pub const CREATE_ALWAYS: ::DWORD = 2; +pub const OPEN_EXISTING: ::DWORD = 3; +pub const OPEN_ALWAYS: ::DWORD = 4; +pub const TRUNCATE_EXISTING: ::DWORD = 5; +pub const INVALID_FILE_SIZE: ::DWORD = 0xFFFFFFFF; +pub const INVALID_SET_FILE_POINTER: ::DWORD = 0xFFFFFFFF; +pub const INVALID_FILE_ATTRIBUTES: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct WIN32_FILE_ATTRIBUTE_DATA { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, +}} +pub type LPWIN32_FILE_ATTRIBUTE_DATA = *mut WIN32_FILE_ATTRIBUTE_DATA; +STRUCT!{struct BY_HANDLE_FILE_INFORMATION { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + dwVolumeSerialNumber: ::DWORD, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + nNumberOfLinks: ::DWORD, + nFileIndexHigh: ::DWORD, + nFileIndexLow: ::DWORD, +}} +pub type PBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; +pub type LPBY_HANDLE_FILE_INFORMATION = *mut BY_HANDLE_FILE_INFORMATION; +STRUCT!{struct CREATEFILE2_EXTENDED_PARAMETERS { + dwSize: ::DWORD, + dwFileAttributes: ::DWORD, + dwFileFlags: ::DWORD, + dwSecurityQosFlags: ::DWORD, + lpSecurityAttributes: ::LPSECURITY_ATTRIBUTES, + hTemplateFile: ::HANDLE, +}} +pub type PCREATEFILE2_EXTENDED_PARAMETERS = *mut CREATEFILE2_EXTENDED_PARAMETERS; +pub type LPCREATEFILE2_EXTENDED_PARAMETERS = *mut CREATEFILE2_EXTENDED_PARAMETERS; +ENUM!{enum PRIORITY_HINT { + IoPriorityHintVeryLow = 0, + IoPriorityHintLow = 1, + IoPriorityHintNormal = 2, + MaximumIoPriorityHintType = 3, +}} +STRUCT!{struct FILE_BASIC_INFO { + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + FileAttributes: ::DWORD, +}} +STRUCT!{struct FILE_STANDARD_INFO { + AllocationSize: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + NumberOfLinks: ::DWORD, + DeletePending: ::BOOLEAN, + Directory: ::BOOLEAN, +}} +STRUCT!{struct FILE_NAME_INFO { + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_RENAME_INFO { + ReplaceIfExists: ::BOOL, + RootDirectory: ::HANDLE, + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_DISPOSITION_INFO { + DeleteFile: ::BOOL, +}} +STRUCT!{struct FILE_ALLOCATION_INFO { + AllocationSize: ::LARGE_INTEGER, +}} +STRUCT!{struct FILE_END_OF_FILE_INFO { + EndOfFile: ::LARGE_INTEGER, +}} +STRUCT!{struct FILE_STREAM_INFO { + NextEntryOffset: ::DWORD, + StreamNameLength: ::DWORD, + StreamSize: ::DWORD, + StreamAllocationSize: ::DWORD, + StreamName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_COMPRESSION_INFO { + CompressedFileSize: ::LARGE_INTEGER, + CompressionFormat: ::WORD, + CompressionUnitShift: ::UCHAR, + ChunkShift: ::UCHAR, + ClusterShift: ::UCHAR, + Reserved: [::UCHAR; 3], +}} +STRUCT!{struct FILE_ATTRIBUTE_TAG_INFO { + NextEntryOffset: ::DWORD, + ReparseTag: ::DWORD, +}} +STRUCT!{struct FILE_ID_BOTH_DIR_INFO { + NextEntryOffset: ::DWORD, + FileIndex: ::DWORD, + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + AllocationSize: ::LARGE_INTEGER, + FileAttributes: ::DWORD, + FileNameLength: ::DWORD, + EaSize: ::DWORD, + ShortNameLength: ::CCHAR, + ShortName: [::WCHAR; 12], + FileId: ::LARGE_INTEGER, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_IO_PRIORITY_HINT_INFO { + PriorityHint: ::PRIORITY_HINT, +}} +STRUCT!{struct FILE_FULL_DIR_INFO { + NextEntryOffset: ::ULONG, + FileIndex: ::ULONG, + CreationTime: ::LARGE_INTEGER, + LastAccessTime: ::LARGE_INTEGER, + LastWriteTime: ::LARGE_INTEGER, + ChangeTime: ::LARGE_INTEGER, + EndOfFile: ::LARGE_INTEGER, + AllocationSize: ::LARGE_INTEGER, + FileAttributes: ::ULONG, + FileNameLength: ::ULONG, + EaSize: ::ULONG, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_STORAGE_INFO { + LogicalBytesPerSector: ::ULONG, + PhysicalBytesPerSectorForAtomicity: ::ULONG, + PhysicalBytesPerSectorForPerformance: ::ULONG, + FileSystemEffectivePhysicalBytesPerSectorForAtomicity: ::ULONG, + Flags: ::ULONG, + ByteOffsetForSectorAlignment: ::ULONG, + ByteOffsetForPartitionAlignment: ::ULONG, +}} +STRUCT!{struct FILE_ALIGNMENT_INFO { + AlignmentRequirement: ::ULONG, +}} +STRUCT!{struct FILE_ID_INFO { + VolumeSerialNumber: ::ULONGLONG, + FileId: ::FILE_ID_128, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/gl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/gl.rs new file mode 100644 index 0000000..006c37e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/gl.rs @@ -0,0 +1,35 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//48 +pub type GLenum = ::c_uint; +pub type GLboolean = ::c_uchar; +pub type GLbitfield = ::c_uint; +pub type GLbyte = ::c_schar; +pub type GLshort = ::c_short; +pub type GLint = ::c_int; +pub type GLsizei = ::c_int; +pub type GLubyte = ::c_uchar; +pub type GLushort = ::c_ushort; +pub type GLuint = ::c_uint; +pub type GLfloat = ::c_float; +pub type GLclampf = ::c_float; +pub type GLdouble = ::c_double; +pub type GLclampd = ::c_double; +pub type GLvoid = ::c_void; +//63 +//68 +//AccumOp +pub const GL_ACCUM: GLenum = 0x0100; +pub const GL_LOAD: GLenum = 0x0101; +pub const GL_RETURN: GLenum = 0x0102; +pub const GL_MULT: GLenum = 0x0103; +pub const GL_ADD: GLenum = 0x0104; +//AlphaFunction +pub const GL_NEVER: GLenum = 0x0200; +pub const GL_LESS: GLenum = 0x0201; +pub const GL_EQUAL: GLenum = 0x0202; +pub const GL_LEQUAL: GLenum = 0x0203; +pub const GL_GREATER: GLenum = 0x0204; +pub const GL_NOTEQUAL: GLenum = 0x0205; +pub const GL_GEQUAL: GLenum = 0x0206; +pub const GL_ALWAYS: GLenum = 0x0207; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/guiddef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/guiddef.rs new file mode 100644 index 0000000..8b436cd --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/guiddef.rs @@ -0,0 +1,20 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +STRUCT!{struct GUID { + Data1: ::c_ulong, + Data2: ::c_ushort, + Data3: ::c_ushort, + Data4: [::c_uchar; 8], +}} +pub type LPGUID = *mut GUID; +pub type LPCGUID = *const GUID; +pub type IID = GUID; +pub type LPIID = *mut IID; +pub type CLSID = GUID; +pub type LPCLSID = *mut CLSID; +pub type FMTID = GUID; +pub type LPFMTID = *mut FMTID; +pub type REFGUID = *const GUID; +pub type REFIID = *const IID; +pub type REFCLSID = *const IID; +pub type REFFMTID = *const IID; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/heapapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/heapapi.rs new file mode 100644 index 0000000..6f631c5 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/heapapi.rs @@ -0,0 +1,12 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-heap-l1 +STRUCT!{struct HEAP_SUMMARY { + cb: ::DWORD, + cbAllocated: ::SIZE_T, + cbCommitted: ::SIZE_T, + cbReserved: ::SIZE_T, + cbMaxReserve: ::SIZE_T, +}} +pub type PHEAP_SUMMARY = *mut HEAP_SUMMARY; +pub type LPHEAP_SUMMARY = PHEAP_SUMMARY; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/hidclass.rs b/third_party/cargo/vendor/winapi-0.2.8/src/hidclass.rs new file mode 100644 index 0000000..0851d5f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/hidclass.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License +DEFINE_GUID!{GUID_DEVINTERFACE_HID, 0x4D1E55B2, 0xF16F, 0x11CF, + 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} +pub const GUID_CLASS_INPUT: ::GUID = GUID_DEVINTERFACE_HID; +DEFINE_GUID!{GUID_HID_INTERFACE_NOTIFY, 0x2c4e2e88, 0x25e6, 0x4c33, 0x88, 0x2f, 0x3d, 0x82, 0xe6, 0x07, 0x36, 0x81} +DEFINE_GUID!{GUID_HID_INTERFACE_HIDPARSE, 0xf5c315a5, 0x69ac, 0x4bc2, 0x92, 0x79, 0xd0, 0xb6, 0x45, 0x76, 0xf4, 0x4b} +// FIXME devpropkey stuff +pub const HID_REVISION: ::DWORD = 0x00000001; +pub const IOCTL_HID_GET_DRIVER_CONFIG: ::DWORD = HID_BUFFER_CTL_CODE!(100); +pub const IOCTL_HID_SET_DRIVER_CONFIG: ::DWORD = HID_BUFFER_CTL_CODE!(101); +pub const IOCTL_HID_GET_POLL_FREQUENCY_MSEC: ::DWORD = HID_BUFFER_CTL_CODE!(102); +pub const IOCTL_HID_SET_POLL_FREQUENCY_MSEC: ::DWORD = HID_BUFFER_CTL_CODE!(103); +pub const IOCTL_GET_NUM_DEVICE_INPUT_BUFFERS: ::DWORD = HID_BUFFER_CTL_CODE!(104); +pub const IOCTL_SET_NUM_DEVICE_INPUT_BUFFERS: ::DWORD = HID_BUFFER_CTL_CODE!(105); +pub const IOCTL_HID_GET_COLLECTION_INFORMATION: ::DWORD = HID_BUFFER_CTL_CODE!(106); +pub const IOCTL_HID_ENABLE_WAKE_ON_SX: ::DWORD = HID_BUFFER_CTL_CODE!(107); +pub const IOCTL_HID_SET_S0_IDLE_TIMEOUT: ::DWORD = HID_BUFFER_CTL_CODE!(108); +pub const IOCTL_HID_GET_COLLECTION_DESCRIPTOR: ::DWORD = HID_CTL_CODE!(100); +pub const IOCTL_HID_FLUSH_QUEUE: ::DWORD = HID_CTL_CODE!(101); +pub const IOCTL_HID_SET_FEATURE: ::DWORD = HID_IN_CTL_CODE!(100); +pub const IOCTL_HID_SET_OUTPUT_REPORT: ::DWORD = HID_IN_CTL_CODE!(101); +pub const IOCTL_HID_GET_FEATURE: ::DWORD = HID_OUT_CTL_CODE!(100); +pub const IOCTL_GET_PHYSICAL_DESCRIPTOR: ::DWORD = HID_OUT_CTL_CODE!(102); +pub const IOCTL_HID_GET_HARDWARE_ID: ::DWORD = HID_OUT_CTL_CODE!(103); +pub const IOCTL_HID_GET_INPUT_REPORT: ::DWORD = HID_OUT_CTL_CODE!(104); +pub const IOCTL_HID_GET_OUTPUT_REPORT: ::DWORD = HID_OUT_CTL_CODE!(105); +pub const IOCTL_HID_GET_MANUFACTURER_STRING: ::DWORD = HID_OUT_CTL_CODE!(110); +pub const IOCTL_HID_GET_PRODUCT_STRING: ::DWORD = HID_OUT_CTL_CODE!(111); +pub const IOCTL_HID_GET_SERIALNUMBER_STRING: ::DWORD = HID_OUT_CTL_CODE!(112); +pub const IOCTL_HID_GET_INDEXED_STRING: ::DWORD = HID_OUT_CTL_CODE!(120); +pub const IOCTL_HID_GET_MS_GENRE_DESCRIPTOR: ::DWORD = HID_OUT_CTL_CODE!(121); +pub const IOCTL_HID_ENABLE_SECURE_READ: ::DWORD = HID_CTL_CODE!(130); +pub const IOCTL_HID_DISABLE_SECURE_READ: ::DWORD = HID_CTL_CODE!(131); +pub const IOCTL_HID_DEVICERESET_NOTIFICATION: ::DWORD = HID_CTL_CODE!(140); +STRUCT!{struct HID_XFER_PACKET { + reportBuffer: ::PUCHAR, + reportBufferLen: ::ULONG, + reportId: ::UCHAR, +}} +pub type PHID_XFER_PACKET = *mut HID_XFER_PACKET; +//FIXME Stuff for NT_INCLUDED +STRUCT!{struct HID_COLLECTION_INFORMATION { + DescriptorSize: ::ULONG, + Polled: ::BOOLEAN, + Reserved1: [::UCHAR; 1], + VendorID: ::USHORT, + ProductID: ::USHORT, + VersionNumber: ::USHORT, +}} +pub type PHID_COLLECTION_INFORMATION = *mut HID_COLLECTION_INFORMATION; +STRUCT!{struct HID_DRIVER_CONFIG { + Size: ::ULONG, + RingBufferSize: ::ULONG, +}} +pub type PHID_DRIVER_CONFIG = *mut HID_DRIVER_CONFIG; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/hidpi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/hidpi.rs new file mode 100644 index 0000000..b2321ea --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/hidpi.rs @@ -0,0 +1,182 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License +pub const HIDP_LINK_COLLECTION_ROOT: ::USHORT = -1i16 as u16; +pub const HIDP_LINK_COLLECTION_UNSPECIFIED: ::USHORT = 0; +ENUM!{enum HIDP_REPORT_TYPE { + HidP_Input, + HidP_Output, + HidP_Feature, +}} +STRUCT!{struct USAGE_AND_PAGE { + Usage: ::USAGE, + UsagePage: ::USAGE, +}} +pub type PUSAGE_AND_PAGE = *mut USAGE_AND_PAGE; +STRUCT!{struct HIDP_BUTTON_CAPS { + UsagePage: ::USAGE, + ReportID: ::UCHAR, + IsAlias: ::BOOLEAN, + BitField: ::USHORT, + LinkCollection: ::USHORT, + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + IsRange: ::BOOLEAN, + IsStringRange: ::BOOLEAN, + IsDesignatorRange: ::BOOLEAN, + IsAbsolute: ::BOOLEAN, + Reserved: [::ULONG; 10], + S_un: [u16; 8], +}} +UNION!{HIDP_BUTTON_CAPS, S_un, Range, Range_mut, HIDP_RANGE_STRUCT} +UNION!{HIDP_BUTTON_CAPS, S_un, NotRange, NotRange_mut, HIDP_NOTRANGE_STRUCT} +pub type PHIDP_BUTTON_CAPS = *mut HIDP_BUTTON_CAPS; +STRUCT!{struct HIDP_RANGE_STRUCT { + UsageMin: ::USAGE, + UsageMax: ::USAGE, + StringMin: ::USHORT, + StringMax: ::USHORT, + DesignatorMin: ::USHORT, + DesignatorMax: ::USHORT, + DataIndexMin: ::USHORT, + DataIndexMax: ::USHORT, +}} +STRUCT!{struct HIDP_NOTRANGE_STRUCT { + Usage: ::USAGE, + Reserved1: ::USAGE, + StringIndex: ::USHORT, + Reserved2: ::USHORT, + DesignatorIndex: ::USHORT, + Reserved3: ::USHORT, + DataIndex: ::USHORT, + Reserved4: ::USHORT, +}} +STRUCT!{struct HIDP_VALUE_CAPS { + UsagePage: ::USAGE, + ReportID: ::UCHAR, + IsAlias: ::BOOLEAN, + BitField: ::USHORT, + LinkCollection: ::USHORT, + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + IsRange: ::BOOLEAN, + IsStringRange: ::BOOLEAN, + IsDesignatorRange: ::BOOLEAN, + IsAbsolute: ::BOOLEAN, + HasNull: ::BOOLEAN, + Reserved: ::UCHAR, + BitSize: ::USHORT, + ReportCount: ::USHORT, + Reserved2: [::USHORT; 5], + UnitsExp: ::ULONG, + Units: ::ULONG, + LogicalMin: ::LONG, + LogicalMax: ::LONG, + PhysicalMin: ::LONG, + PhysicalMax: ::LONG, + S_un: [u16; 8], +}} +UNION!{HIDP_VALUE_CAPS, S_un, Range, Range_mut, HIDP_RANGE_STRUCT} +UNION!{HIDP_VALUE_CAPS, S_un, NotRange, NotRange_mut, HIDP_NOTRANGE_STRUCT} +pub type PHIDP_VALUE_CAPS = *mut HIDP_VALUE_CAPS; +STRUCT!{struct HIDP_LINK_COLLECTION_NODE { + LinkUsage: ::USAGE, + LinkUsagePage: ::USAGE, + Parent: ::USHORT, + NumberOfChildren: ::USHORT, + NextSibling: ::USHORT, + FirstChild: ::USHORT, + bit_fields: ::ULONG, + UserContext: ::PVOID, +}} +BITFIELD!{HIDP_LINK_COLLECTION_NODE bit_fields: ::ULONG [ + CollectionType set_CollectionType[0..8], + IsAlias set_IsAlias[8..9], +]} +pub type PHIDP_LINK_COLLECTION_NODE = *mut HIDP_LINK_COLLECTION_NODE; +pub type PHIDP_REPORT_DESCRIPTOR = ::PUCHAR; +pub enum HIDP_PREPARSED_DATA{} +pub type PHIDP_PREPARSED_DATA = *mut HIDP_PREPARSED_DATA; +STRUCT!{struct HIDP_CAPS { + Usage: ::USAGE, + UsagePage: ::USAGE, + InputReportByteLength: ::USHORT, + OutputReportByteLength: ::USHORT, + FeatureReportByteLength: ::USHORT, + Reserved: [::USHORT; 17], + NumberLinkCollectionNodes: ::USHORT, + NumberInputButtonCaps: ::USHORT, + NumberInputValueCaps: ::USHORT, + NumberInputDataIndices: ::USHORT, + NumberOutputButtonCaps: ::USHORT, + NumberOutputValueCaps: ::USHORT, + NumberOutputDataIndices: ::USHORT, + NumberFeatureButtonCaps: ::USHORT, + NumberFeatureValueCaps: ::USHORT, + NumberFeatureDataIndices: ::USHORT, +}} +pub type PHIDP_CAPS = *mut HIDP_CAPS; +STRUCT!{struct HIDP_DATA { + DataIndex: ::USHORT, + Reserved: ::USHORT, + S_un: [u32; 1], +}} +UNION!{HIDP_DATA, S_un, RawValue, RawValue_mut, ::ULONG} +UNION!{HIDP_DATA, S_un, On, On_mut, ::BOOLEAN} +pub type PHIDP_DATA = *mut HIDP_DATA; +STRUCT!{struct HIDP_UNKNOWN_TOKEN { + Token: ::UCHAR, + Reserved: [::UCHAR; 3], + BitField: ::ULONG, +}} +pub type PHIDP_UNKNOWN_TOKEN = *mut HIDP_UNKNOWN_TOKEN; +STRUCT!{struct HIDP_EXTENDED_ATTRIBUTES { + NumGlobalUnknowns: ::UCHAR, + Reserved: [::UCHAR; 3], + GlobalUnknowns: PHIDP_UNKNOWN_TOKEN, + Data: [::ULONG; 1], +}} +pub type PHIDP_EXTENDED_ATTRIBUTES = *mut HIDP_EXTENDED_ATTRIBUTES; +ENUM!{enum HIDP_KEYBOARD_DIRECTION { + HidP_Keyboard_Break, + HidP_Keyboard_Make, +}} +STRUCT!{struct HIDP_KEYBOARD_MODIFIER_STATE { + ul: ::ULONG, +}} +BITFIELD!{HIDP_KEYBOARD_MODIFIER_STATE ul: ::ULONG [ + LeftControl set_LeftControl[0..1], + LeftShift set_LeftShift[1..2], + LeftAlt set_LeftAlt[2..3], + LeftGUI set_LeftGUI[3..4], + RightControl set_RightControl[4..5], + RightShift set_RightShift[5..6], + RightAlt set_RightAlt[6..7], + RigthGUI set_RigthGUI[7..8], + CapsLock set_CapsLock[8..9], + ScollLock set_ScollLock[9..10], + NumLock set_NumLock[10..11], +]} +pub type PHIDP_KEYBOARD_MODIFIER_STATE = *mut HIDP_KEYBOARD_MODIFIER_STATE; +pub type PHIDP_INSERT_SCANCODES = Option ::BOOLEAN>; +pub const HIDP_STATUS_SUCCESS: ::NTSTATUS = HIDP_ERROR_CODES!(0x0, 0); +pub const HIDP_STATUS_NULL: ::NTSTATUS = HIDP_ERROR_CODES!(0x8, 1); +pub const HIDP_STATUS_INVALID_PREPARSED_DATA: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 1); +pub const HIDP_STATUS_INVALID_REPORT_TYPE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 2); +pub const HIDP_STATUS_INVALID_REPORT_LENGTH: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 3); +pub const HIDP_STATUS_USAGE_NOT_FOUND: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 4); +pub const HIDP_STATUS_VALUE_OUT_OF_RANGE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 5); +pub const HIDP_STATUS_BAD_LOG_PHY_VALUES: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 6); +pub const HIDP_STATUS_BUFFER_TOO_SMALL: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 7); +pub const HIDP_STATUS_INTERNAL_ERROR: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 8); +pub const HIDP_STATUS_I8042_TRANS_UNKNOWN: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 9); +pub const HIDP_STATUS_INCOMPATIBLE_REPORT_ID: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xA); +pub const HIDP_STATUS_NOT_VALUE_ARRAY: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xB); +pub const HIDP_STATUS_IS_VALUE_ARRAY: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xC); +pub const HIDP_STATUS_DATA_INDEX_NOT_FOUND: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xD); +pub const HIDP_STATUS_DATA_INDEX_OUT_OF_RANGE: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xE); +pub const HIDP_STATUS_BUTTON_NOT_PRESSED: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0xF); +pub const HIDP_STATUS_REPORT_DOES_NOT_EXIST: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0x10); +pub const HIDP_STATUS_NOT_IMPLEMENTED: ::NTSTATUS = HIDP_ERROR_CODES!(0xC, 0x20); +pub const HIDP_STATUS_I8242_TRANS_UNKNOWN: ::NTSTATUS = HIDP_STATUS_I8042_TRANS_UNKNOWN; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/hidsdi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/hidsdi.rs new file mode 100644 index 0000000..1b421f0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/hidsdi.rs @@ -0,0 +1,15 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License +STRUCT!{struct HIDD_CONFIGURATION { + cookie: ::PVOID, + size: ::ULONG, + RingBufferSize: ::ULONG, +}} +pub type PHIDD_CONFIGURATION = *mut HIDD_CONFIGURATION; +STRUCT!{struct HIDD_ATTRIBUTES { + Size: ::ULONG, + VendorID: ::USHORT, + ProductID: ::USHORT, + VersionNumber: ::USHORT, +}} +pub type PHIDD_ATTRIBUTES = *mut HIDD_ATTRIBUTES; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/hidusage.rs b/third_party/cargo/vendor/winapi-0.2.8/src/hidusage.rs new file mode 100644 index 0000000..4d76509 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/hidusage.rs @@ -0,0 +1,270 @@ +// Copyright © 2015, Peter Atashian and Alex Daniel Jones +// Licensed under the MIT License +pub type USAGE = ::USHORT; +pub type PUSAGE = *mut USAGE; +pub const HID_USAGE_PAGE_UNDEFINED: ::USAGE = 0x00; +pub const HID_USAGE_PAGE_GENERIC: ::USAGE = 0x01; +pub const HID_USAGE_PAGE_SIMULATION: ::USAGE = 0x02; +pub const HID_USAGE_PAGE_VR: ::USAGE = 0x03; +pub const HID_USAGE_PAGE_SPORT: ::USAGE = 0x04; +pub const HID_USAGE_PAGE_GAME: ::USAGE = 0x05; +pub const HID_USAGE_PAGE_KEYBOARD: ::USAGE = 0x07; +pub const HID_USAGE_PAGE_LED: ::USAGE = 0x08; +pub const HID_USAGE_PAGE_BUTTON: ::USAGE = 0x09; +pub const HID_USAGE_PAGE_ORDINAL: ::USAGE = 0x0A; +pub const HID_USAGE_PAGE_TELEPHONY: ::USAGE = 0x0B; +pub const HID_USAGE_PAGE_CONSUMER: ::USAGE = 0x0C; +pub const HID_USAGE_PAGE_DIGITIZER: ::USAGE = 0x0D; +pub const HID_USAGE_PAGE_UNICODE: ::USAGE = 0x10; +pub const HID_USAGE_PAGE_ALPHANUMERIC: ::USAGE = 0x14; +pub const HID_USAGE_PAGE_SENSOR: ::USAGE = 0x20; +pub const HID_USAGE_PAGE_BARCODE_SCANNER: ::USAGE = 0x8C; +pub const HID_USAGE_PAGE_WEIGHING_DEVICE: ::USAGE = 0x8D; +pub const HID_USAGE_PAGE_MAGNETIC_STRIPE_READER: ::USAGE = 0x8E; +pub const HID_USAGE_PAGE_CAMERA_CONTROL: ::USAGE = 0x90; +pub const HID_USAGE_PAGE_MICROSOFT_BLUETOOTH_HANDSFREE: ::USAGE = 0xFFF3; +pub const HID_USAGE_PAGE_VENDOR_DEFINED_BEGIN: ::USAGE = 0xFF00; +pub const HID_USAGE_PAGE_VENDOR_DEFINED_END: ::USAGE = 0xFFFF; +pub const HID_USAGE_GENERIC_POINTER: ::USAGE = 0x01; +pub const HID_USAGE_GENERIC_MOUSE: ::USAGE = 0x02; +pub const HID_USAGE_GENERIC_JOYSTICK: ::USAGE = 0x04; +pub const HID_USAGE_GENERIC_GAMEPAD: ::USAGE = 0x05; +pub const HID_USAGE_GENERIC_KEYBOARD: ::USAGE = 0x06; +pub const HID_USAGE_GENERIC_KEYPAD: ::USAGE = 0x07; +pub const HID_USAGE_GENERIC_PORTABLE_DEVICE_CONTROL: ::USAGE = 0x0D; +pub const HID_USAGE_GENERIC_SYSTEM_CTL: ::USAGE = 0x80; +pub const HID_USAGE_GENERIC_X: ::USAGE = 0x30; +pub const HID_USAGE_GENERIC_Y: ::USAGE = 0x31; +pub const HID_USAGE_GENERIC_Z: ::USAGE = 0x32; +pub const HID_USAGE_GENERIC_RX: ::USAGE = 0x33; +pub const HID_USAGE_GENERIC_RY: ::USAGE = 0x34; +pub const HID_USAGE_GENERIC_RZ: ::USAGE = 0x35; +pub const HID_USAGE_GENERIC_SLIDER: ::USAGE = 0x36; +pub const HID_USAGE_GENERIC_DIAL: ::USAGE = 0x37; +pub const HID_USAGE_GENERIC_WHEEL: ::USAGE = 0x38; +pub const HID_USAGE_GENERIC_HATSWITCH: ::USAGE = 0x39; +pub const HID_USAGE_GENERIC_COUNTED_BUFFER: ::USAGE = 0x3A; +pub const HID_USAGE_GENERIC_BYTE_COUNT: ::USAGE = 0x3B; +pub const HID_USAGE_GENERIC_MOTION_WAKEUP: ::USAGE = 0x3C; +pub const HID_USAGE_GENERIC_VX: ::USAGE = 0x40; +pub const HID_USAGE_GENERIC_VY: ::USAGE = 0x41; +pub const HID_USAGE_GENERIC_VZ: ::USAGE = 0x42; +pub const HID_USAGE_GENERIC_VBRX: ::USAGE = 0x43; +pub const HID_USAGE_GENERIC_VBRY: ::USAGE = 0x44; +pub const HID_USAGE_GENERIC_VBRZ: ::USAGE = 0x45; +pub const HID_USAGE_GENERIC_VNO: ::USAGE = 0x46; +pub const HID_USAGE_GENERIC_RESOLUTION_MULTIPLIER: ::USAGE = 0x48; +pub const HID_USAGE_GENERIC_SYSCTL_POWER: ::USAGE = 0x81; +pub const HID_USAGE_GENERIC_SYSCTL_SLEEP: ::USAGE = 0x82; +pub const HID_USAGE_GENERIC_SYSCTL_WAKE: ::USAGE = 0x83; +pub const HID_USAGE_GENERIC_SYSCTL_CONTEXT_MENU: ::USAGE = 0x84; +pub const HID_USAGE_GENERIC_SYSCTL_MAIN_MENU: ::USAGE = 0x85; +pub const HID_USAGE_GENERIC_SYSCTL_APP_MENU: ::USAGE = 0x86; +pub const HID_USAGE_GENERIC_SYSCTL_HELP_MENU: ::USAGE = 0x87; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_EXIT: ::USAGE = 0x88; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_SELECT: ::USAGE = 0x89; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_RIGHT: ::USAGE = 0x8A; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_LEFT: ::USAGE = 0x8B; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_UP: ::USAGE = 0x8C; +pub const HID_USAGE_GENERIC_SYSCTL_MENU_DOWN: ::USAGE = 0x8D; +pub const HID_USAGE_GENERIC_SYSTEM_DISPLAY_ROTATION_LOCK_BUTTON: ::USAGE = 0xC9; +pub const HID_USAGE_GENERIC_SYSTEM_DISPLAY_ROTATION_LOCK_SLIDER_SWITCH: ::USAGE = 0xCA; +pub const HID_USAGE_GENERIC_CONTROL_ENABLE: ::USAGE = 0xCB; +pub const HID_USAGE_SIMULATION_RUDDER: ::USAGE = 0xBA; +pub const HID_USAGE_SIMULATION_THROTTLE: ::USAGE = 0xBB; +pub const HID_USAGE_KEYBOARD_NOEVENT: ::USAGE = 0x00; +pub const HID_USAGE_KEYBOARD_ROLLOVER: ::USAGE = 0x01; +pub const HID_USAGE_KEYBOARD_POSTFAIL: ::USAGE = 0x02; +pub const HID_USAGE_KEYBOARD_UNDEFINED: ::USAGE = 0x03; +pub const HID_USAGE_KEYBOARD_aA: ::USAGE = 0x04; +pub const HID_USAGE_KEYBOARD_zZ: ::USAGE = 0x1D; +pub const HID_USAGE_KEYBOARD_ONE: ::USAGE = 0x1E; +pub const HID_USAGE_KEYBOARD_ZERO: ::USAGE = 0x27; +pub const HID_USAGE_KEYBOARD_LCTRL: ::USAGE = 0xE0; +pub const HID_USAGE_KEYBOARD_LSHFT: ::USAGE = 0xE1; +pub const HID_USAGE_KEYBOARD_LALT: ::USAGE = 0xE2; +pub const HID_USAGE_KEYBOARD_LGUI: ::USAGE = 0xE3; +pub const HID_USAGE_KEYBOARD_RCTRL: ::USAGE = 0xE4; +pub const HID_USAGE_KEYBOARD_RSHFT: ::USAGE = 0xE5; +pub const HID_USAGE_KEYBOARD_RALT: ::USAGE = 0xE6; +pub const HID_USAGE_KEYBOARD_RGUI: ::USAGE = 0xE7; +pub const HID_USAGE_KEYBOARD_SCROLL_LOCK: ::USAGE = 0x47; +pub const HID_USAGE_KEYBOARD_NUM_LOCK: ::USAGE = 0x53; +pub const HID_USAGE_KEYBOARD_CAPS_LOCK: ::USAGE = 0x39; +pub const HID_USAGE_KEYBOARD_F1: ::USAGE = 0x3A; +pub const HID_USAGE_KEYBOARD_F2: ::USAGE = 0x3B; +pub const HID_USAGE_KEYBOARD_F3: ::USAGE = 0x3C; +pub const HID_USAGE_KEYBOARD_F4: ::USAGE = 0x3D; +pub const HID_USAGE_KEYBOARD_F5: ::USAGE = 0x3E; +pub const HID_USAGE_KEYBOARD_F6: ::USAGE = 0x3F; +pub const HID_USAGE_KEYBOARD_F7: ::USAGE = 0x40; +pub const HID_USAGE_KEYBOARD_F8: ::USAGE = 0x41; +pub const HID_USAGE_KEYBOARD_F9: ::USAGE = 0x42; +pub const HID_USAGE_KEYBOARD_F10: ::USAGE = 0x43; +pub const HID_USAGE_KEYBOARD_F11: ::USAGE = 0x44; +pub const HID_USAGE_KEYBOARD_F12: ::USAGE = 0x45; +pub const HID_USAGE_KEYBOARD_F13: ::USAGE = 0x68; +pub const HID_USAGE_KEYBOARD_F14: ::USAGE = 0x69; +pub const HID_USAGE_KEYBOARD_F15: ::USAGE = 0x6A; +pub const HID_USAGE_KEYBOARD_F16: ::USAGE = 0x6B; +pub const HID_USAGE_KEYBOARD_F17: ::USAGE = 0x6C; +pub const HID_USAGE_KEYBOARD_F18: ::USAGE = 0x6D; +pub const HID_USAGE_KEYBOARD_F19: ::USAGE = 0x6E; +pub const HID_USAGE_KEYBOARD_F20: ::USAGE = 0x6F; +pub const HID_USAGE_KEYBOARD_F21: ::USAGE = 0x70; +pub const HID_USAGE_KEYBOARD_F22: ::USAGE = 0x71; +pub const HID_USAGE_KEYBOARD_F23: ::USAGE = 0x72; +pub const HID_USAGE_KEYBOARD_F24: ::USAGE = 0x73; +pub const HID_USAGE_KEYBOARD_RETURN: ::USAGE = 0x28; +pub const HID_USAGE_KEYBOARD_ESCAPE: ::USAGE = 0x29; +pub const HID_USAGE_KEYBOARD_DELETE: ::USAGE = 0x2A; +pub const HID_USAGE_KEYBOARD_PRINT_SCREEN: ::USAGE = 0x46; +pub const HID_USAGE_KEYBOARD_DELETE_FORWARD: ::USAGE = 0x4C; +pub const HID_USAGE_LED_NUM_LOCK: ::USAGE = 0x01; +pub const HID_USAGE_LED_CAPS_LOCK: ::USAGE = 0x02; +pub const HID_USAGE_LED_SCROLL_LOCK: ::USAGE = 0x03; +pub const HID_USAGE_LED_COMPOSE: ::USAGE = 0x04; +pub const HID_USAGE_LED_KANA: ::USAGE = 0x05; +pub const HID_USAGE_LED_POWER: ::USAGE = 0x06; +pub const HID_USAGE_LED_SHIFT: ::USAGE = 0x07; +pub const HID_USAGE_LED_DO_NOT_DISTURB: ::USAGE = 0x08; +pub const HID_USAGE_LED_MUTE: ::USAGE = 0x09; +pub const HID_USAGE_LED_TONE_ENABLE: ::USAGE = 0x0A; +pub const HID_USAGE_LED_HIGH_CUT_FILTER: ::USAGE = 0x0B; +pub const HID_USAGE_LED_LOW_CUT_FILTER: ::USAGE = 0x0C; +pub const HID_USAGE_LED_EQUALIZER_ENABLE: ::USAGE = 0x0D; +pub const HID_USAGE_LED_SOUND_FIELD_ON: ::USAGE = 0x0E; +pub const HID_USAGE_LED_SURROUND_FIELD_ON: ::USAGE = 0x0F; +pub const HID_USAGE_LED_REPEAT: ::USAGE = 0x10; +pub const HID_USAGE_LED_STEREO: ::USAGE = 0x11; +pub const HID_USAGE_LED_SAMPLING_RATE_DETECT: ::USAGE = 0x12; +pub const HID_USAGE_LED_SPINNING: ::USAGE = 0x13; +pub const HID_USAGE_LED_CAV: ::USAGE = 0x14; +pub const HID_USAGE_LED_CLV: ::USAGE = 0x15; +pub const HID_USAGE_LED_RECORDING_FORMAT_DET: ::USAGE = 0x16; +pub const HID_USAGE_LED_OFF_HOOK: ::USAGE = 0x17; +pub const HID_USAGE_LED_RING: ::USAGE = 0x18; +pub const HID_USAGE_LED_MESSAGE_WAITING: ::USAGE = 0x19; +pub const HID_USAGE_LED_DATA_MODE: ::USAGE = 0x1A; +pub const HID_USAGE_LED_BATTERY_OPERATION: ::USAGE = 0x1B; +pub const HID_USAGE_LED_BATTERY_OK: ::USAGE = 0x1C; +pub const HID_USAGE_LED_BATTERY_LOW: ::USAGE = 0x1D; +pub const HID_USAGE_LED_SPEAKER: ::USAGE = 0x1E; +pub const HID_USAGE_LED_HEAD_SET: ::USAGE = 0x1F; +pub const HID_USAGE_LED_HOLD: ::USAGE = 0x20; +pub const HID_USAGE_LED_MICROPHONE: ::USAGE = 0x21; +pub const HID_USAGE_LED_COVERAGE: ::USAGE = 0x22; +pub const HID_USAGE_LED_NIGHT_MODE: ::USAGE = 0x23; +pub const HID_USAGE_LED_SEND_CALLS: ::USAGE = 0x24; +pub const HID_USAGE_LED_CALL_PICKUP: ::USAGE = 0x25; +pub const HID_USAGE_LED_CONFERENCE: ::USAGE = 0x26; +pub const HID_USAGE_LED_STAND_BY: ::USAGE = 0x27; +pub const HID_USAGE_LED_CAMERA_ON: ::USAGE = 0x28; +pub const HID_USAGE_LED_CAMERA_OFF: ::USAGE = 0x29; +pub const HID_USAGE_LED_ON_LINE: ::USAGE = 0x2A; +pub const HID_USAGE_LED_OFF_LINE: ::USAGE = 0x2B; +pub const HID_USAGE_LED_BUSY: ::USAGE = 0x2C; +pub const HID_USAGE_LED_READY: ::USAGE = 0x2D; +pub const HID_USAGE_LED_PAPER_OUT: ::USAGE = 0x2E; +pub const HID_USAGE_LED_PAPER_JAM: ::USAGE = 0x2F; +pub const HID_USAGE_LED_REMOTE: ::USAGE = 0x30; +pub const HID_USAGE_LED_FORWARD: ::USAGE = 0x31; +pub const HID_USAGE_LED_REVERSE: ::USAGE = 0x32; +pub const HID_USAGE_LED_STOP: ::USAGE = 0x33; +pub const HID_USAGE_LED_REWIND: ::USAGE = 0x34; +pub const HID_USAGE_LED_FAST_FORWARD: ::USAGE = 0x35; +pub const HID_USAGE_LED_PLAY: ::USAGE = 0x36; +pub const HID_USAGE_LED_PAUSE: ::USAGE = 0x37; +pub const HID_USAGE_LED_RECORD: ::USAGE = 0x38; +pub const HID_USAGE_LED_ERROR: ::USAGE = 0x39; +pub const HID_USAGE_LED_SELECTED_INDICATOR: ::USAGE = 0x3A; +pub const HID_USAGE_LED_IN_USE_INDICATOR: ::USAGE = 0x3B; +pub const HID_USAGE_LED_MULTI_MODE_INDICATOR: ::USAGE = 0x3C; +pub const HID_USAGE_LED_INDICATOR_ON: ::USAGE = 0x3D; +pub const HID_USAGE_LED_INDICATOR_FLASH: ::USAGE = 0x3E; +pub const HID_USAGE_LED_INDICATOR_SLOW_BLINK: ::USAGE = 0x3F; +pub const HID_USAGE_LED_INDICATOR_FAST_BLINK: ::USAGE = 0x40; +pub const HID_USAGE_LED_INDICATOR_OFF: ::USAGE = 0x41; +pub const HID_USAGE_LED_FLASH_ON_TIME: ::USAGE = 0x42; +pub const HID_USAGE_LED_SLOW_BLINK_ON_TIME: ::USAGE = 0x43; +pub const HID_USAGE_LED_SLOW_BLINK_OFF_TIME: ::USAGE = 0x44; +pub const HID_USAGE_LED_FAST_BLINK_ON_TIME: ::USAGE = 0x45; +pub const HID_USAGE_LED_FAST_BLINK_OFF_TIME: ::USAGE = 0x46; +pub const HID_USAGE_LED_INDICATOR_COLOR: ::USAGE = 0x47; +pub const HID_USAGE_LED_RED: ::USAGE = 0x48; +pub const HID_USAGE_LED_GREEN: ::USAGE = 0x49; +pub const HID_USAGE_LED_AMBER: ::USAGE = 0x4A; +pub const HID_USAGE_LED_GENERIC_INDICATOR: ::USAGE = 0x4B; +pub const HID_USAGE_TELEPHONY_PHONE: ::USAGE = 0x01; +pub const HID_USAGE_TELEPHONY_ANSWERING_MACHINE: ::USAGE = 0x02; +pub const HID_USAGE_TELEPHONY_MESSAGE_CONTROLS: ::USAGE = 0x03; +pub const HID_USAGE_TELEPHONY_HANDSET: ::USAGE = 0x04; +pub const HID_USAGE_TELEPHONY_HEADSET: ::USAGE = 0x05; +pub const HID_USAGE_TELEPHONY_KEYPAD: ::USAGE = 0x06; +pub const HID_USAGE_TELEPHONY_PROGRAMMABLE_BUTTON: ::USAGE = 0x07; +pub const HID_USAGE_TELEPHONY_REDIAL: ::USAGE = 0x24; +pub const HID_USAGE_TELEPHONY_TRANSFER: ::USAGE = 0x25; +pub const HID_USAGE_TELEPHONY_DROP: ::USAGE = 0x26; +pub const HID_USAGE_TELEPHONY_LINE: ::USAGE = 0x2A; +pub const HID_USAGE_TELEPHONY_RING_ENABLE: ::USAGE = 0x2D; +pub const HID_USAGE_TELEPHONY_SEND: ::USAGE = 0x31; +pub const HID_USAGE_TELEPHONY_KEYPAD_0: ::USAGE = 0xB0; +pub const HID_USAGE_TELEPHONY_KEYPAD_D: ::USAGE = 0xBF; +pub const HID_USAGE_TELEPHONY_HOST_AVAILABLE: ::USAGE = 0xF1; +pub const HID_USAGE_CONSUMERCTRL: ::USAGE = 0x01; +pub const HID_USAGE_CONSUMER_CHANNEL_INCREMENT: ::USAGE = 0x9C; +pub const HID_USAGE_CONSUMER_CHANNEL_DECREMENT: ::USAGE = 0x9D; +pub const HID_USAGE_CONSUMER_PLAY: ::USAGE = 0xB0; +pub const HID_USAGE_CONSUMER_PAUSE: ::USAGE = 0xB1; +pub const HID_USAGE_CONSUMER_RECORD: ::USAGE = 0xB2; +pub const HID_USAGE_CONSUMER_FAST_FORWARD: ::USAGE = 0xB3; +pub const HID_USAGE_CONSUMER_REWIND: ::USAGE = 0xB4; +pub const HID_USAGE_CONSUMER_SCAN_NEXT_TRACK: ::USAGE = 0xB5; +pub const HID_USAGE_CONSUMER_SCAN_PREV_TRACK: ::USAGE = 0xB6; +pub const HID_USAGE_CONSUMER_STOP: ::USAGE = 0xB7; +pub const HID_USAGE_CONSUMER_PLAY_PAUSE: ::USAGE = 0xCD; +pub const HID_USAGE_CONSUMER_VOLUME: ::USAGE = 0xE0; +pub const HID_USAGE_CONSUMER_BALANCE: ::USAGE = 0xE1; +pub const HID_USAGE_CONSUMER_MUTE: ::USAGE = 0xE2; +pub const HID_USAGE_CONSUMER_BASS: ::USAGE = 0xE3; +pub const HID_USAGE_CONSUMER_TREBLE: ::USAGE = 0xE4; +pub const HID_USAGE_CONSUMER_BASS_BOOST: ::USAGE = 0xE5; +pub const HID_USAGE_CONSUMER_SURROUND_MODE: ::USAGE = 0xE6; +pub const HID_USAGE_CONSUMER_LOUDNESS: ::USAGE = 0xE7; +pub const HID_USAGE_CONSUMER_MPX: ::USAGE = 0xE8; +pub const HID_USAGE_CONSUMER_VOLUME_INCREMENT: ::USAGE = 0xE9; +pub const HID_USAGE_CONSUMER_VOLUME_DECREMENT: ::USAGE = 0xEA; +pub const HID_USAGE_CONSUMER_BASS_INCREMENT: ::USAGE = 0x152; +pub const HID_USAGE_CONSUMER_BASS_DECREMENT: ::USAGE = 0x153; +pub const HID_USAGE_CONSUMER_TREBLE_INCREMENT: ::USAGE = 0x154; +pub const HID_USAGE_CONSUMER_TREBLE_DECREMENT: ::USAGE = 0x155; +pub const HID_USAGE_CONSUMER_AL_CONFIGURATION: ::USAGE = 0x183; +pub const HID_USAGE_CONSUMER_AL_EMAIL: ::USAGE = 0x18A; +pub const HID_USAGE_CONSUMER_AL_CALCULATOR: ::USAGE = 0x192; +pub const HID_USAGE_CONSUMER_AL_BROWSER: ::USAGE = 0x194; +pub const HID_USAGE_CONSUMER_AC_SEARCH: ::USAGE = 0x221; +pub const HID_USAGE_CONSUMER_AC_GOTO: ::USAGE = 0x222; +pub const HID_USAGE_CONSUMER_AC_HOME: ::USAGE = 0x223; +pub const HID_USAGE_CONSUMER_AC_BACK: ::USAGE = 0x224; +pub const HID_USAGE_CONSUMER_AC_FORWARD: ::USAGE = 0x225; +pub const HID_USAGE_CONSUMER_AC_STOP: ::USAGE = 0x226; +pub const HID_USAGE_CONSUMER_AC_REFRESH: ::USAGE = 0x227; +pub const HID_USAGE_CONSUMER_AC_PREVIOUS: ::USAGE = 0x228; +pub const HID_USAGE_CONSUMER_AC_NEXT: ::USAGE = 0x229; +pub const HID_USAGE_CONSUMER_AC_BOOKMARKS: ::USAGE = 0x22A; +pub const HID_USAGE_CONSUMER_AC_PAN: ::USAGE = 0x238; +pub const HID_USAGE_CONSUMER_EXTENDED_KEYBOARD_ATTRIBUTES_COLLECTION: ::USAGE = 0x2C0; +pub const HID_USAGE_CONSUMER_KEYBOARD_FORM_FACTOR: ::USAGE = 0x2C1; +pub const HID_USAGE_CONSUMER_KEYBOARD_KEY_TYPE: ::USAGE = 0x2C2; +pub const HID_USAGE_CONSUMER_KEYBOARD_PHYSICAL_LAYOUT: ::USAGE = 0x2C3; +pub const HID_USAGE_CONSUMER_VENDOR_SPECIFIC_KEYBOARD_PHYSICAL_LAYOUT: ::USAGE = 0x2C4; +pub const HID_USAGE_CONSUMER_KEYBOARD_IETF_LANGUAGE_TAG_INDEX: ::USAGE = 0x2C5; +pub const HID_USAGE_CONSUMER_IMPLEMENTED_KEYBOARD_INPUT_ASSIST_CONTROLS: ::USAGE = 0x2C6; +pub const HID_USAGE_DIGITIZER_PEN: ::USAGE = 0x02; +pub const HID_USAGE_DIGITIZER_IN_RANGE: ::USAGE = 0x32; +pub const HID_USAGE_DIGITIZER_TIP_SWITCH: ::USAGE = 0x42; +pub const HID_USAGE_DIGITIZER_BARREL_SWITCH: ::USAGE = 0x44; +pub const HID_USAGE_CAMERA_AUTO_FOCUS: ::USAGE = 0x20; +pub const HID_USAGE_CAMERA_SHUTTER: ::USAGE = 0x21; +pub const HID_USAGE_MS_BTH_HF_DIALNUMBER: ::USAGE = 0x21; +pub const HID_USAGE_MS_BTH_HF_DIALMEMORY: ::USAGE = 0x22; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/hstring.rs b/third_party/cargo/vendor/winapi-0.2.8/src/hstring.rs new file mode 100644 index 0000000..01cfc6d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/hstring.rs @@ -0,0 +1,16 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This interface definition contains typedefs for Windows Runtime data types. +DECLARE_HANDLE!(HSTRING, HSTRING__); +#[cfg(target_arch = "x86_64")] +STRUCT!{struct HSTRING_HEADER { + Reserved: [::PVOID; 0], // For alignment + Reserved2: [::c_char; 24], +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct HSTRING_HEADER { + Reserved: [::PVOID; 0], // For alignment + Reserved2: [::c_char; 20], +}} +UNION!(HSTRING_HEADER, Reserved2, Reserved1, Reserved1_mut, ::PVOID); +DECLARE_HANDLE!(HSTRING_BUFFER, HSTRING_BUFFER__); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/http.rs b/third_party/cargo/vendor/winapi-0.2.8/src/http.rs new file mode 100644 index 0000000..b0020f9 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/http.rs @@ -0,0 +1,828 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! HTTP API specification +pub const HTTP_INITIALIZE_SERVER: ::ULONG = 0x00000001; +pub const HTTP_INITIALIZE_CONFIG: ::ULONG = 0x00000002; +pub const HTTP_DEMAND_CBT: ::ULONG = 0x00000004; +ENUM!{enum HTTP_SERVER_PROPERTY { + HttpServerAuthenticationProperty, + HttpServerLoggingProperty, + HttpServerQosProperty, + HttpServerTimeoutsProperty, + HttpServerQueueLengthProperty, + HttpServerStateProperty, + HttpServer503VerbosityProperty, + HttpServerBindingProperty, + HttpServerExtendedAuthenticationProperty, + HttpServerListenEndpointProperty, + HttpServerChannelBindProperty, + HttpServerProtectionLevelProperty, +}} +pub type PHTTP_SERVER_PROPERTY = *mut HTTP_SERVER_PROPERTY; +STRUCT!{struct HTTP_PROPERTY_FLAGS { + BitFields: ::ULONG, +}} +BITFIELD!(HTTP_PROPERTY_FLAGS BitFields: ::ULONG [ + Present set_Present[0..1], +]); +pub type PHTTP_PROPERTY_FLAGS = *mut HTTP_PROPERTY_FLAGS; +ENUM!{enum HTTP_ENABLED_STATE { + HttpEnabledStateActive, + HttpEnabledStateInactive, +}} +pub type PHTTP_ENABLED_STATE = *mut HTTP_ENABLED_STATE; +STRUCT!{struct HTTP_STATE_INFO { + Flags: HTTP_PROPERTY_FLAGS, + State: HTTP_ENABLED_STATE, +}} +pub type PHTTP_STATE_INFO = *mut HTTP_STATE_INFO; +ENUM!{enum HTTP_503_RESPONSE_VERBOSITY { + Http503ResponseVerbosityBasic, + Http503ResponseVerbosityLimited, + Http503ResponseVerbosityFull, +}} +pub type PHTTP_503_RESPONSE_VERBOSITY = *mut HTTP_503_RESPONSE_VERBOSITY; +ENUM!{enum HTTP_QOS_SETTING_TYPE { + HttpQosSettingTypeBandwidth, + HttpQosSettingTypeConnectionLimit, + HttpQosSettingTypeFlowRate, +}} +pub type PHTTP_QOS_SETTING_TYPE = *mut HTTP_QOS_SETTING_TYPE; +STRUCT!{struct HTTP_QOS_SETTING_INFO { + QosType: HTTP_QOS_SETTING_TYPE, + QosSetting: ::PVOID, +}} +pub type PHTTP_QOS_SETTING_INFO = *mut HTTP_QOS_SETTING_INFO; +STRUCT!{struct HTTP_CONNECTION_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxConnections: ::ULONG, +}} +pub type PHTTP_CONNECTION_LIMIT_INFO = *mut HTTP_CONNECTION_LIMIT_INFO; +STRUCT!{struct HTTP_BANDWIDTH_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxBandwidth: ::ULONG, +}} +pub type PHTTP_BANDWIDTH_LIMIT_INFO = *mut HTTP_BANDWIDTH_LIMIT_INFO; +STRUCT!{struct HTTP_FLOWRATE_INFO { + Flags: HTTP_PROPERTY_FLAGS, + MaxBandwidth: ::ULONG, + MaxPeakBandwidth: ::ULONG, + BurstSize: ::ULONG, +}} +pub type PHTTP_FLOWRATE_INFO = *mut HTTP_FLOWRATE_INFO; +pub const HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE: ::ULONG = 1024; +pub const HTTP_LIMIT_INFINITE: ::ULONG = !0; +ENUM!{enum HTTP_SERVICE_CONFIG_TIMEOUT_KEY { + IdleConnectionTimeout = 0, + HeaderWaitTimeout, +}} +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_KEY = *mut HTTP_SERVICE_CONFIG_TIMEOUT_KEY; +pub type HTTP_SERVICE_CONFIG_TIMEOUT_PARAM = ::USHORT; +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_PARAM = *mut ::USHORT; +STRUCT!{struct HTTP_SERVICE_CONFIG_TIMEOUT_SET { + KeyDesc: HTTP_SERVICE_CONFIG_TIMEOUT_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_TIMEOUT_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_TIMEOUT_SET = *mut HTTP_SERVICE_CONFIG_TIMEOUT_SET; +STRUCT!{struct HTTP_TIMEOUT_LIMIT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + EntityBody: ::USHORT, + DrainEntityBody: ::USHORT, + RequestQueue: ::USHORT, + IdleConnection: ::USHORT, + HeaderWait: ::USHORT, + MinSendRate: ::ULONG, +}} +pub type PHTTP_TIMEOUT_LIMIT_INFO = *mut HTTP_TIMEOUT_LIMIT_INFO; +STRUCT!{struct HTTP_LISTEN_ENDPOINT_INFO { + Flags: HTTP_PROPERTY_FLAGS, + EnableSharing: ::BOOLEAN, +}} +pub type PHTTP_LISTEN_ENDPOINT_INFO = *mut HTTP_LISTEN_ENDPOINT_INFO; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS { + DomainNameLength: ::USHORT, + DomainName: ::PWSTR, + RealmLength: ::USHORT, + Realm: ::PWSTR, +}} +pub type PHTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS = *mut HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS { + RealmLength: ::USHORT, + Realm: ::PWSTR, +}} +pub type PHTTP_SERVER_AUTHENTICATION_BASIC_PARAMS = *mut HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS; +pub const HTTP_AUTH_ENABLE_BASIC: ::ULONG = 0x00000001; +pub const HTTP_AUTH_ENABLE_DIGEST: ::ULONG = 0x00000002; +pub const HTTP_AUTH_ENABLE_NTLM: ::ULONG = 0x00000004; +pub const HTTP_AUTH_ENABLE_NEGOTIATE: ::ULONG = 0x00000008; +pub const HTTP_AUTH_ENABLE_KERBEROS: ::ULONG = 0x00000010; +pub const HTTP_AUTH_ENABLE_ALL: ::ULONG = HTTP_AUTH_ENABLE_BASIC | HTTP_AUTH_ENABLE_DIGEST | + HTTP_AUTH_ENABLE_NTLM | HTTP_AUTH_ENABLE_NEGOTIATE | HTTP_AUTH_ENABLE_KERBEROS; +pub const HTTP_AUTH_EX_FLAG_ENABLE_KERBEROS_CREDENTIAL_CACHING: ::UCHAR = 0x01; +pub const HTTP_AUTH_EX_FLAG_CAPTURE_CREDENTIAL: ::UCHAR = 0x02; +STRUCT!{struct HTTP_SERVER_AUTHENTICATION_INFO { + Flags: HTTP_PROPERTY_FLAGS, + AuthSchemes: ::ULONG, + ReceiveMutualAuth: ::BOOLEAN, + ReceiveContextHandle: ::BOOLEAN, + DisableNTLMCredentialCaching: ::BOOLEAN, + ExFlags: ::UCHAR, + DigestParams: HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS, + BasicParams: HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS, +}} +pub type PHTTP_SERVER_AUTHENTICATION_INFO = *mut HTTP_SERVER_AUTHENTICATION_INFO; +ENUM!{enum HTTP_SERVICE_BINDING_TYPE { + HttpServiceBindingTypeNone = 0, + HttpServiceBindingTypeW, + HttpServiceBindingTypeA, +}} +STRUCT!{struct HTTP_SERVICE_BINDING_BASE { + Type: HTTP_SERVICE_BINDING_TYPE, +}} +pub type PHTTP_SERVICE_BINDING_BASE = *mut HTTP_SERVICE_BINDING_BASE; +STRUCT!{struct HTTP_SERVICE_BINDING_A { + Base: HTTP_SERVICE_BINDING_BASE, + Buffer: ::PCHAR, + BufferSize: ::ULONG, +}} +pub type PHTTP_SERVICE_BINDING_A = *mut HTTP_SERVICE_BINDING_A; +STRUCT!{struct HTTP_SERVICE_BINDING_W { + Base: HTTP_SERVICE_BINDING_BASE, + Buffer: ::PWCHAR, + BufferSize: ::ULONG, +}} +pub type PHTTP_SERVICE_BINDING_W = *mut HTTP_SERVICE_BINDING_W; +ENUM!{enum HTTP_AUTHENTICATION_HARDENING_LEVELS { + HttpAuthenticationHardeningLegacy = 0, + HttpAuthenticationHardeningMedium, + HttpAuthenticationHardeningStrict, +}} +pub const HTTP_CHANNEL_BIND_PROXY: ::ULONG = 0x1; +pub const HTTP_CHANNEL_BIND_PROXY_COHOSTING: ::ULONG = 0x20; +pub const HTTP_CHANNEL_BIND_NO_SERVICE_NAME_CHECK: ::ULONG = 0x2; +pub const HTTP_CHANNEL_BIND_DOTLESS_SERVICE: ::ULONG = 0x4; +pub const HTTP_CHANNEL_BIND_SECURE_CHANNEL_TOKEN: ::ULONG = 0x8; +pub const HTTP_CHANNEL_BIND_CLIENT_SERVICE: ::ULONG = 0x10; +STRUCT!{struct HTTP_CHANNEL_BIND_INFO { + Hardening: HTTP_AUTHENTICATION_HARDENING_LEVELS, + Flags: ::ULONG, + ServiceNames: *mut PHTTP_SERVICE_BINDING_BASE, + NumberOfServiceNames: ::ULONG, +}} +pub type PHTTP_CHANNEL_BIND_INFO = *mut HTTP_CHANNEL_BIND_INFO; +STRUCT!{struct HTTP_REQUEST_CHANNEL_BIND_STATUS { + ServiceName: PHTTP_SERVICE_BINDING_BASE, + ChannelToken: ::PUCHAR, + ChannelTokenSize: ::ULONG, + Flags: ::ULONG, +}} +pub type PHTTP_REQUEST_CHANNEL_BIND_STATUS = *mut HTTP_REQUEST_CHANNEL_BIND_STATUS; +pub const HTTP_LOG_FIELD_DATE: ::ULONG = 0x00000001; +pub const HTTP_LOG_FIELD_TIME: ::ULONG = 0x00000002; +pub const HTTP_LOG_FIELD_CLIENT_IP: ::ULONG = 0x00000004; +pub const HTTP_LOG_FIELD_USER_NAME: ::ULONG = 0x00000008; +pub const HTTP_LOG_FIELD_SITE_NAME: ::ULONG = 0x00000010; +pub const HTTP_LOG_FIELD_COMPUTER_NAME: ::ULONG = 0x00000020; +pub const HTTP_LOG_FIELD_SERVER_IP: ::ULONG = 0x00000040; +pub const HTTP_LOG_FIELD_METHOD: ::ULONG = 0x00000080; +pub const HTTP_LOG_FIELD_URI_STEM: ::ULONG = 0x00000100; +pub const HTTP_LOG_FIELD_URI_QUERY: ::ULONG = 0x00000200; +pub const HTTP_LOG_FIELD_STATUS: ::ULONG = 0x00000400; +pub const HTTP_LOG_FIELD_WIN32_STATUS: ::ULONG = 0x00000800; +pub const HTTP_LOG_FIELD_BYTES_SENT: ::ULONG = 0x00001000; +pub const HTTP_LOG_FIELD_BYTES_RECV: ::ULONG = 0x00002000; +pub const HTTP_LOG_FIELD_TIME_TAKEN: ::ULONG = 0x00004000; +pub const HTTP_LOG_FIELD_SERVER_PORT: ::ULONG = 0x00008000; +pub const HTTP_LOG_FIELD_USER_AGENT: ::ULONG = 0x00010000; +pub const HTTP_LOG_FIELD_COOKIE: ::ULONG = 0x00020000; +pub const HTTP_LOG_FIELD_REFERER: ::ULONG = 0x00040000; +pub const HTTP_LOG_FIELD_VERSION: ::ULONG = 0x00080000; +pub const HTTP_LOG_FIELD_HOST: ::ULONG = 0x00100000; +pub const HTTP_LOG_FIELD_SUB_STATUS: ::ULONG = 0x00200000; +pub const HTTP_LOG_FIELD_CLIENT_PORT: ::ULONG = 0x00400000; +pub const HTTP_LOG_FIELD_URI: ::ULONG = 0x00800000; +pub const HTTP_LOG_FIELD_SITE_ID: ::ULONG = 0x01000000; +pub const HTTP_LOG_FIELD_REASON: ::ULONG = 0x02000000; +pub const HTTP_LOG_FIELD_QUEUE_NAME: ::ULONG = 0x04000000; +ENUM!{enum HTTP_LOGGING_TYPE { + HttpLoggingTypeW3C, + HttpLoggingTypeIIS, + HttpLoggingTypeNCSA, + HttpLoggingTypeRaw, +}} +ENUM!{enum HTTP_LOGGING_ROLLOVER_TYPE { + HttpLoggingRolloverSize, + HttpLoggingRolloverDaily, + HttpLoggingRolloverWeekly, + HttpLoggingRolloverMonthly, + HttpLoggingRolloverHourly, +}} +pub const HTTP_MIN_ALLOWED_LOG_FILE_ROLLOVER_SIZE: ::ULONG = (1 * 1024 * 1024) as ::ULONG; +pub const HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER: ::ULONG = 0x00000001; +pub const HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION: ::ULONG = 0x00000002; +pub const HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY: ::ULONG = 0x00000004; +pub const HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY: ::ULONG = 0x00000008; +STRUCT!{struct HTTP_LOGGING_INFO { + Flags: HTTP_PROPERTY_FLAGS, + LoggingFlags: ::ULONG, + SoftwareName: ::PCWSTR, + SoftwareNameLength: ::USHORT, + DirectoryNameLength: ::USHORT, + DirectoryName: ::PCWSTR, + Format: HTTP_LOGGING_TYPE, + Fields: ::ULONG, + pExtFields: ::PVOID, + NumOfExtFields: ::USHORT, + MaxRecordSize: ::USHORT, + RolloverType: HTTP_LOGGING_ROLLOVER_TYPE, + RolloverSize: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PHTTP_LOGGING_INFO = *mut HTTP_LOGGING_INFO; +STRUCT!{struct HTTP_BINDING_INFO { + Flags: HTTP_PROPERTY_FLAGS, + RequestQueueHandle: ::HANDLE, +}} +pub type PHTTP_BINDING_INFO = *mut HTTP_BINDING_INFO; +ENUM!{enum HTTP_PROTECTION_LEVEL_TYPE { + HttpProtectionLevelUnrestricted, + HttpProtectionLevelEdgeRestricted, + HttpProtectionLevelRestricted, +}} +pub type PHTTP_PROTECTION_LEVEL_TYPE = *mut HTTP_PROTECTION_LEVEL_TYPE; +STRUCT!{struct HTTP_PROTECTION_LEVEL_INFO { + Flags: HTTP_PROPERTY_FLAGS, + Level: HTTP_PROTECTION_LEVEL_TYPE, +}} +pub type PHTTP_PROTECTION_LEVEL_INFO = *mut HTTP_PROTECTION_LEVEL_INFO; +pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING: ::ULONG = 0x00000001; +pub const HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER: ::ULONG = 0x00000002; +pub const HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY: ::ULONG = 0x00000001; +pub const HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY: ::ULONG = 0x00000002; +pub const HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER: ::ULONG = 0x00000001; +pub const HTTP_SEND_RESPONSE_FLAG_DISCONNECT: ::ULONG = 0x00000001; +pub const HTTP_SEND_RESPONSE_FLAG_MORE_DATA: ::ULONG = 0x00000002; +pub const HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA: ::ULONG = 0x00000004; +pub const HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING: ::ULONG = 0x00000008; +pub const HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES: ::ULONG = 0x00000020; +pub const HTTP_SEND_RESPONSE_FLAG_OPAQUE: ::ULONG = 0x00000040; +pub const HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE: ::ULONG = 0x00000001; +pub type HTTP_OPAQUE_ID = ::ULONGLONG; +pub type PHTTP_OPAQUE_ID = *mut ::ULONGLONG; +pub type HTTP_REQUEST_ID = HTTP_OPAQUE_ID; +pub type PHTTP_REQUEST_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_CONNECTION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_CONNECTION_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_RAW_CONNECTION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_RAW_CONNECTION_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_URL_GROUP_ID = HTTP_OPAQUE_ID; +pub type PHTTP_URL_GROUP_ID = *mut HTTP_OPAQUE_ID; +pub type HTTP_SERVER_SESSION_ID = HTTP_OPAQUE_ID; +pub type PHTTP_SERVER_SESSION_ID = *mut HTTP_OPAQUE_ID; +pub const HTTP_BYTE_RANGE_TO_EOF: ::ULONGLONG = !0; +STRUCT!{struct HTTP_BYTE_RANGE { + StartingOffset: ::ULARGE_INTEGER, + Length: ::ULARGE_INTEGER, +}} +pub type PHTTP_BYTE_RANGE = *mut HTTP_BYTE_RANGE; +STRUCT!{struct HTTP_VERSION { + MajorVersion: ::USHORT, + MinorVersion: ::USHORT, +}} +pub type PHTTP_VERSION = *mut HTTP_VERSION; +pub const HTTP_VERSION_UNKNOWN: HTTP_VERSION = HTTP_VERSION { MajorVersion: 0, MinorVersion: 0 }; +pub const HTTP_VERSION_0_9: HTTP_VERSION = HTTP_VERSION { MajorVersion: 0, MinorVersion: 9 }; +pub const HTTP_VERSION_1_0: HTTP_VERSION = HTTP_VERSION { MajorVersion: 1, MinorVersion: 0 }; +pub const HTTP_VERSION_1_1: HTTP_VERSION = HTTP_VERSION { MajorVersion: 1, MinorVersion: 1 }; +#[inline] #[allow(dead_code)] +pub fn HTTP_SET_VERSION(mut version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) { + version.MajorVersion = major; + version.MinorVersion = minor; +} +#[inline] #[allow(dead_code)] +pub fn HTTP_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion == major && version.MinorVersion == minor +} +#[inline] #[allow(dead_code)] +pub fn HTTP_GREATER_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion > major || (version.MajorVersion == major && version.MinorVersion > minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_LESS_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.MajorVersion < major || (version.MajorVersion == major && version.MinorVersion < minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_NOT_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_EQUAL_VERSION(version, major, minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_GREATER_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_LESS_VERSION(version, major, minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTP_LESS_EQUAL_VERSION(version: HTTP_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + !HTTP_GREATER_VERSION(version, major, minor) +} +ENUM!{enum HTTP_VERB { + HttpVerbUnparsed, + HttpVerbUnknown, + HttpVerbInvalid, + HttpVerbOPTIONS, + HttpVerbGET, + HttpVerbHEAD, + HttpVerbPOST, + HttpVerbPUT, + HttpVerbDELETE, + HttpVerbTRACE, + HttpVerbCONNECT, + HttpVerbTRACK, + HttpVerbMOVE, + HttpVerbCOPY, + HttpVerbPROPFIND, + HttpVerbPROPPATCH, + HttpVerbMKCOL, + HttpVerbLOCK, + HttpVerbUNLOCK, + HttpVerbSEARCH, + HttpVerbMaximum, +}} +pub type PHTTP_VERB = *mut HTTP_VERB; +ENUM!{enum HTTP_HEADER_ID { + HttpHeaderCacheControl = 0, + HttpHeaderConnection = 1, + HttpHeaderDate = 2, + HttpHeaderKeepAlive = 3, + HttpHeaderPragma = 4, + HttpHeaderTrailer = 5, + HttpHeaderTransferEncoding = 6, + HttpHeaderUpgrade = 7, + HttpHeaderVia = 8, + HttpHeaderWarning = 9, + HttpHeaderAllow = 10, + HttpHeaderContentLength = 11, + HttpHeaderContentType = 12, + HttpHeaderContentEncoding = 13, + HttpHeaderContentLanguage = 14, + HttpHeaderContentLocation = 15, + HttpHeaderContentMd5 = 16, + HttpHeaderContentRange = 17, + HttpHeaderExpires = 18, + HttpHeaderLastModified = 19, + HttpHeaderAccept = 20, + HttpHeaderAcceptCharset = 21, + HttpHeaderAcceptEncoding = 22, + HttpHeaderAcceptLanguage = 23, + HttpHeaderAuthorization = 24, + HttpHeaderCookie = 25, + HttpHeaderExpect = 26, + HttpHeaderFrom = 27, + HttpHeaderHost = 28, + HttpHeaderIfMatch = 29, + HttpHeaderIfModifiedSince = 30, + HttpHeaderIfNoneMatch = 31, + HttpHeaderIfRange = 32, + HttpHeaderIfUnmodifiedSince = 33, + HttpHeaderMaxForwards = 34, + HttpHeaderProxyAuthorization = 35, + HttpHeaderReferer = 36, + HttpHeaderRange = 37, + HttpHeaderTe = 38, + HttpHeaderTranslate = 39, + HttpHeaderUserAgent = 40, + HttpHeaderRequestMaximum = 41, + HttpHeaderAcceptRanges = 20, + HttpHeaderAge = 21, + HttpHeaderEtag = 22, + HttpHeaderLocation = 23, + HttpHeaderProxyAuthenticate = 24, + HttpHeaderRetryAfter = 25, + HttpHeaderServer = 26, + HttpHeaderSetCookie = 27, + HttpHeaderVary = 28, + HttpHeaderWwwAuthenticate = 29, + HttpHeaderResponseMaximum = 30, + HttpHeaderMaximum = 41, +}} +pub type PHTTP_HEADER_ID = *mut HTTP_HEADER_ID; +STRUCT!{struct HTTP_KNOWN_HEADER { + RawValueLength: ::USHORT, + pRawValue: ::PCSTR, +}} +pub type PHTTP_KNOWN_HEADER = *mut HTTP_KNOWN_HEADER; +STRUCT!{struct HTTP_UNKNOWN_HEADER { + NameLength: ::USHORT, + RawValueLength: ::USHORT, + pName: ::PCSTR, + pRawValue: ::PCSTR, +}} +pub type PHTTP_UNKNOWN_HEADER = *mut HTTP_UNKNOWN_HEADER; +ENUM!{enum HTTP_LOG_DATA_TYPE { + HttpLogDataTypeFields = 0, +}} +pub type PHTTP_LOG_DATA_TYPE = *mut HTTP_LOG_DATA_TYPE; +STRUCT!{struct HTTP_LOG_DATA { + Type: HTTP_LOG_DATA_TYPE, +}} +pub type PHTTP_LOG_DATA = *mut HTTP_LOG_DATA; +STRUCT!{struct HTTP_LOG_FIELDS_DATA { + Base: HTTP_LOG_DATA, + UserNameLength: ::USHORT, + UriStemLength: ::USHORT, + ClientIpLength: ::USHORT, + ServerNameLength: ::USHORT, + ServiceNameLength: ::USHORT, + ServerIpLength: ::USHORT, + MethodLength: ::USHORT, + UriQueryLength: ::USHORT, + HostLength: ::USHORT, + UserAgentLength: ::USHORT, + CookieLength: ::USHORT, + ReferrerLength: ::USHORT, + UserName: ::PWCHAR, + UriStem: ::PWCHAR, + ClientIp: ::PCHAR, + ServerName: ::PCHAR, + ServiceName: ::PCHAR, + ServerIp: ::PCHAR, + Method: ::PCHAR, + UriQuery: ::PCHAR, + Host: ::PCHAR, + UserAgent: ::PCHAR, + Cookie: ::PCHAR, + Referrer: ::PCHAR, + ServerPort: ::USHORT, + ProtocolStatus: ::USHORT, + Win32Status: ::ULONG, + MethodNum: HTTP_VERB, + SubStatus: ::USHORT, +}} +pub type PHTTP_LOG_FIELDS_DATA = *mut HTTP_LOG_FIELDS_DATA; +ENUM!{enum HTTP_DATA_CHUNK_TYPE { + HttpDataChunkFromMemory, + HttpDataChunkFromFileHandle, + HttpDataChunkFromFragmentCache, + HttpDataChunkFromFragmentCacheEx, + HttpDataChunkMaximum, +}} +pub type PHTTP_DATA_CHUNK_TYPE = *mut HTTP_DATA_CHUNK_TYPE; +STRUCT!{struct HTTP_DATA_CHUNK_FromMemory { + pBuffer: ::PVOID, + BufferLength: ::ULONG, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFileHandle { + ByteRange: HTTP_BYTE_RANGE, + FileHandle: ::HANDLE, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFragmentCache { + FragmentNameLength: ::USHORT, + pFragmentName: ::PCWSTR, +}} +STRUCT!{struct HTTP_DATA_CHUNK_FromFragmentCacheEx { + ByteRange: HTTP_BYTE_RANGE, + pFragmentName: ::PCWSTR, +}} +STRUCT!{struct HTTP_DATA_CHUNK { + DataChunkType: HTTP_DATA_CHUNK_TYPE, + FromFileHandle: HTTP_DATA_CHUNK_FromFileHandle, +}} +UNION!(HTTP_DATA_CHUNK, FromFileHandle, FromMemory, FromMemory_mut, HTTP_DATA_CHUNK_FromMemory); +UNION!( + HTTP_DATA_CHUNK, FromFileHandle, FromFragmentCache, FromFragmentCache_mut, + HTTP_DATA_CHUNK_FromFragmentCache +); +UNION!( + HTTP_DATA_CHUNK, FromFileHandle, FromFragmentCacheEx, FromFragmentCacheEx_mut, + HTTP_DATA_CHUNK_FromFragmentCacheEx +); +pub type PHTTP_DATA_CHUNK = *mut HTTP_DATA_CHUNK; +STRUCT!{nodebug struct HTTP_REQUEST_HEADERS { + UnknownHeaderCount: ::USHORT, + pUnknownHeaders: PHTTP_UNKNOWN_HEADER, + TrailerCount: ::USHORT, + pTrailers: PHTTP_UNKNOWN_HEADER, + KnownHeaders: [HTTP_KNOWN_HEADER; 41], // FIXME HttpHeaderRequestMaximum +}} +pub type PHTTP_REQUEST_HEADERS = *mut HTTP_REQUEST_HEADERS; +STRUCT!{nodebug struct HTTP_RESPONSE_HEADERS { + UnknownHeaderCount: ::USHORT, + pUnknownHeaders: PHTTP_UNKNOWN_HEADER, + TrailerCount: ::USHORT, + pTrailers: PHTTP_UNKNOWN_HEADER, + KnownHeaders: [HTTP_KNOWN_HEADER; 30], // FIXME HttpHeaderResponseMaximum +}} +pub type PHTTP_RESPONSE_HEADERS = *mut HTTP_RESPONSE_HEADERS; +STRUCT!{struct HTTP_TRANSPORT_ADDRESS { + pRemoteAddress: ::PSOCKADDR, + pLocalAddress: ::PSOCKADDR, +}} +pub type PHTTP_TRANSPORT_ADDRESS = *mut HTTP_TRANSPORT_ADDRESS; +STRUCT!{struct HTTP_COOKED_URL { + FullUrlLength: ::USHORT, + HostLength: ::USHORT, + AbsPathLength: ::USHORT, + QueryStringLength: ::USHORT, + pFullUrl: ::PCWSTR, + pHost: ::PCWSTR, + pAbsPath: ::PCWSTR, + pQueryString: ::PCWSTR, +}} +pub type PHTTP_COOKED_URL = *mut HTTP_COOKED_URL; +pub type HTTP_URL_CONTEXT = ::ULONGLONG; +pub const HTTP_URL_FLAG_REMOVE_ALL: ::ULONG = 0x00000001; +ENUM!{enum HTTP_AUTH_STATUS { + HttpAuthStatusSuccess, + HttpAuthStatusNotAuthenticated, + HttpAuthStatusFailure, +}} +pub type PHTTP_AUTH_STATUS = *mut HTTP_AUTH_STATUS; +ENUM!{enum HTTP_REQUEST_AUTH_TYPE { + HttpRequestAuthTypeNone = 0, + HttpRequestAuthTypeBasic, + HttpRequestAuthTypeDigest, + HttpRequestAuthTypeNTLM, + HttpRequestAuthTypeNegotiate, + HttpRequestAuthTypeKerberos, +}} +pub type PHTTP_REQUEST_AUTH_TYPE = *mut HTTP_REQUEST_AUTH_TYPE; +STRUCT!{struct HTTP_SSL_CLIENT_CERT_INFO { + CertFlags: ::ULONG, + CertEncodedSize: ::ULONG, + pCertEncoded: ::PUCHAR, + Token: ::HANDLE, + CertDeniedByMapper: ::BOOLEAN, +}} +pub type PHTTP_SSL_CLIENT_CERT_INFO = *mut HTTP_SSL_CLIENT_CERT_INFO; +pub const HTTP_RECEIVE_SECURE_CHANNEL_TOKEN: ::ULONG = 0x1; +STRUCT!{struct HTTP_SSL_INFO { + ServerCertKeySize: ::USHORT, + ConnectionKeySize: ::USHORT, + ServerCertIssuerSize: ::ULONG, + ServerCertSubjectSize: ::ULONG, + pServerCertIssuer: ::PCSTR, + pServerCertSubject: ::PCSTR, + pClientCertInfo: PHTTP_SSL_CLIENT_CERT_INFO, + SslClientCertNegotiated: ::ULONG, +}} +pub type PHTTP_SSL_INFO = *mut HTTP_SSL_INFO; +ENUM!{enum HTTP_REQUEST_INFO_TYPE { + HttpRequestInfoTypeAuth, + HttpRequestInfoTypeChannelBind, +}} +STRUCT!{struct HTTP_REQUEST_INFO { + InfoType: HTTP_REQUEST_INFO_TYPE, + InfoLength: ::ULONG, + pInfo: ::PVOID, +}} +pub type PHTTP_REQUEST_INFO = *mut HTTP_REQUEST_INFO; +pub const HTTP_REQUEST_AUTH_FLAG_TOKEN_FOR_CACHED_CRED: ::ULONG = 0x00000001; +STRUCT!{struct HTTP_REQUEST_AUTH_INFO { + AuthStatus: HTTP_AUTH_STATUS, + SecStatus: ::SECURITY_STATUS, + Flags: ::ULONG, + AuthType: HTTP_REQUEST_AUTH_TYPE, + AccessToken: ::HANDLE, + ContextAttributes: ::ULONG, + PackedContextLength: ::ULONG, + PackedContextType: ::ULONG, + PackedContext: ::PVOID, + MutualAuthDataLength: ::ULONG, + pMutualAuthData: ::PCHAR, + PackageNameLength: ::USHORT, + pPackageName: ::PWSTR, +}} +pub type PHTTP_REQUEST_AUTH_INFO = *mut HTTP_REQUEST_AUTH_INFO; +STRUCT!{nodebug struct HTTP_REQUEST_V1 { + Flags: ::ULONG, + ConnectionId: HTTP_CONNECTION_ID, + RequestId: HTTP_REQUEST_ID, + UrlContext: HTTP_URL_CONTEXT, + Version: HTTP_VERSION, + Verb: HTTP_VERB, + UnknownVerbLength: ::USHORT, + RawUrlLength: ::USHORT, + pUnknownVerb: ::PCSTR, + pRawUrl: ::PCSTR, + CookedUrl: HTTP_COOKED_URL, + Address: HTTP_TRANSPORT_ADDRESS, + Headers: HTTP_REQUEST_HEADERS, + BytesReceived: ::ULONGLONG, + EntityChunkCount: ::USHORT, + pEntityChunks: PHTTP_DATA_CHUNK, + RawConnectionId: HTTP_RAW_CONNECTION_ID, + pSslInfo: PHTTP_SSL_INFO, +}} +pub type PHTTP_REQUEST_V1 = *mut HTTP_REQUEST_V1; +STRUCT!{nodebug struct HTTP_REQUEST_V2 { + Base: HTTP_REQUEST_V1, + RequestInfoCount: ::USHORT, + pRequestInfo: PHTTP_REQUEST_INFO, +}} +pub type PHTTP_REQUEST_V2 = *mut HTTP_REQUEST_V2; +pub type HTTP_REQUEST = HTTP_REQUEST_V2; +pub type PHTTP_REQUEST = *mut HTTP_REQUEST; +pub const HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS: ::ULONG = 0x00000001; +pub const HTTP_REQUEST_FLAG_IP_ROUTED: ::ULONG = 0x00000002; +STRUCT!{nodebug struct HTTP_RESPONSE_V1 { + Flags: ::ULONG, + Version: HTTP_VERSION, + StatusCode: ::USHORT, + ReasonLength: ::USHORT, + pReason: ::PCSTR, + Headers: HTTP_RESPONSE_HEADERS, + EntityChunkCount: ::USHORT, + pEntityChunks: PHTTP_DATA_CHUNK, +}} +pub type PHTTP_RESPONSE_V1 = *mut HTTP_RESPONSE_V1; +pub const HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE: ::ULONG = 0x00000001; +ENUM!{enum HTTP_RESPONSE_INFO_TYPE { + HttpResponseInfoTypeMultipleKnownHeaders, + HttpResponseInfoTypeAuthenticationProperty, + HttpResponseInfoTypeQoSProperty, + HttpResponseInfoTypeChannelBind, +}} +pub type PHTTP_RESPONSE_INFO_TYPE = *mut HTTP_RESPONSE_INFO_TYPE; +STRUCT!{struct HTTP_RESPONSE_INFO { + Type: HTTP_RESPONSE_INFO_TYPE, + Length: ::ULONG, + pInfo: ::PVOID, +}} +pub type PHTTP_RESPONSE_INFO = *mut HTTP_RESPONSE_INFO; +pub const HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER: ::ULONG = 0x00000001; +STRUCT!{struct HTTP_MULTIPLE_KNOWN_HEADERS { + HeaderId: HTTP_HEADER_ID, + Flags: ::ULONG, + KnownHeaderCount: ::USHORT, + KnownHeaders: PHTTP_KNOWN_HEADER, +}} +pub type PHTTP_MULTIPLE_KNOWN_HEADERS = *mut HTTP_MULTIPLE_KNOWN_HEADERS; +STRUCT!{nodebug struct HTTP_RESPONSE_V2 { + Base: HTTP_RESPONSE_V1, + ResponseInfoCount: ::USHORT, + pResponseInfo: PHTTP_RESPONSE_INFO, +}} +pub type PHTTP_RESPONSE_V2 = *mut HTTP_RESPONSE_V2; +pub type HTTP_RESPONSE = HTTP_RESPONSE_V2; +pub type PHTTP_RESPONSE = *mut HTTP_RESPONSE; +STRUCT!{struct HTTPAPI_VERSION { + HttpApiMajorVersion: ::USHORT, + HttpApiMinorVersion: ::USHORT, +}} +pub type PHTTPAPI_VERSION = *mut HTTPAPI_VERSION; +pub const HTTPAPI_VERSION_2: HTTPAPI_VERSION = HTTPAPI_VERSION { + HttpApiMajorVersion: 2, HttpApiMinorVersion: 0, +}; +pub const HTTPAPI_VERSION_1: HTTPAPI_VERSION = HTTPAPI_VERSION { + HttpApiMajorVersion: 1, HttpApiMinorVersion: 0, +}; +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_EQUAL_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion == major && version.HttpApiMinorVersion == minor +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_GREATER_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion > major || + (version.HttpApiMajorVersion == major && version.HttpApiMinorVersion > minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_LESS_VERSION(version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT) -> bool { + version.HttpApiMajorVersion < major || + (version.HttpApiMajorVersion == major && version.HttpApiMinorVersion < minor) +} +#[inline] #[allow(dead_code)] +pub fn HTTPAPI_VERSION_GREATER_OR_EQUAL( + version: HTTPAPI_VERSION, major: ::USHORT, minor: ::USHORT +) -> bool { + !HTTPAPI_LESS_VERSION(version, major, minor) +} +ENUM!{enum HTTP_CACHE_POLICY_TYPE { + HttpCachePolicyNocache, + HttpCachePolicyUserInvalidates, + HttpCachePolicyTimeToLive, + HttpCachePolicyMaximum, +}} +pub type PHTTP_CACHE_POLICY_TYPE = *mut HTTP_CACHE_POLICY_TYPE; +STRUCT!{struct HTTP_CACHE_POLICY { + Policy: HTTP_CACHE_POLICY_TYPE, + SecondsToLive: ::ULONG, +}} +pub type PHTTP_CACHE_POLICY = *mut HTTP_CACHE_POLICY; +ENUM!{enum HTTP_SERVICE_CONFIG_ID { + HttpServiceConfigIPListenList, + HttpServiceConfigSSLCertInfo, + HttpServiceConfigUrlAclInfo, + HttpServiceConfigTimeout, + HttpServiceConfigCache, + HttpServiceConfigSslSniCertInfo, + HttpServiceConfigSslCcsCertInfo, + HttpServiceConfigMax, +}} +pub type PHTTP_SERVICE_CONFIG_ID = *mut HTTP_SERVICE_CONFIG_ID; +ENUM!{enum HTTP_SERVICE_CONFIG_QUERY_TYPE { + HttpServiceConfigQueryExact, + HttpServiceConfigQueryNext, + HttpServiceConfigQueryMax, +}} +pub type PHTTP_SERVICE_CONFIG_QUERY_TYPE = *mut HTTP_SERVICE_CONFIG_QUERY_TYPE; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_KEY { + pIpPort: ::PSOCKADDR, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_KEY = *mut HTTP_SERVICE_CONFIG_SSL_KEY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_KEY { + IpPort: ::SOCKADDR_STORAGE, + Host: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_KEY = *mut HTTP_SERVICE_CONFIG_SSL_SNI_KEY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_KEY { + LocalAddress: ::SOCKADDR_STORAGE, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_KEY = *mut HTTP_SERVICE_CONFIG_SSL_CCS_KEY; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_PARAM { + SslHashLength: ::ULONG, + pSslHash: ::PVOID, + AppId: ::GUID, + pSslCertStoreName: ::PWSTR, + DefaultCertCheckMode: ::DWORD, + DefaultRevocationFreshnessTime: ::DWORD, + DefaultRevocationUrlRetrievalTimeout: ::DWORD, + pDefaultSslCtlIdentifier: ::PWSTR, + pDefaultSslCtlStoreName: ::PWSTR, + DefaultFlags: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_PARAM = *mut HTTP_SERVICE_CONFIG_SSL_PARAM; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_USE_DS_MAPPER: ::DWORD = 0x00000001; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT: ::DWORD = 0x00000002; +pub const HTTP_SERVICE_CONFIG_SSL_FLAG_NO_RAW_FILTER: ::DWORD = 0x00000004; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SET = *mut HTTP_SERVICE_CONFIG_SSL_SET; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_SET = *mut HTTP_SERVICE_CONFIG_SSL_SNI_SET; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_SET { + KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_SSL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_SET = *mut HTTP_SERVICE_CONFIG_SSL_CCS_SET; +STRUCT!{struct HTTP_SERVICE_CONFIG_SSL_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_QUERY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_SNI_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_SNI_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_SNI_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_SNI_QUERY; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_SSL_CCS_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_SSL_CCS_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_SSL_CCS_QUERY = *mut HTTP_SERVICE_CONFIG_SSL_CCS_QUERY; +STRUCT!{struct HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM { + AddrLength: ::USHORT, + pAddress: ::PSOCKADDR, +}} +pub type PHTTP_SERVICE_CONFIG_IP_LISTEN_PARAM = *mut HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM; +STRUCT!{nodebug struct HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY { + AddrCount: ::ULONG, + AddrList: [::SOCKADDR_STORAGE; ::ANYSIZE_ARRAY], +}} +pub type PHTTP_SERVICE_CONFIG_IP_LISTEN_QUERY = *mut HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_KEY { + pUrlPrefix: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_KEY = *mut HTTP_SERVICE_CONFIG_URLACL_KEY; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_PARAM { + pStringSecurityDescriptor: ::PWSTR, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_PARAM = *mut HTTP_SERVICE_CONFIG_URLACL_PARAM; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_SET { + KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_URLACL_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_SET = *mut HTTP_SERVICE_CONFIG_URLACL_SET; +STRUCT!{struct HTTP_SERVICE_CONFIG_URLACL_QUERY { + QueryDesc: HTTP_SERVICE_CONFIG_QUERY_TYPE, + KeyDesc: HTTP_SERVICE_CONFIG_URLACL_KEY, + dwToken: ::DWORD, +}} +pub type PHTTP_SERVICE_CONFIG_URLACL_QUERY = *mut HTTP_SERVICE_CONFIG_URLACL_QUERY; +ENUM!{enum HTTP_SERVICE_CONFIG_CACHE_KEY { + MaxCacheResponseSize = 0, + CacheRangeChunkSize, +}} +pub type PHTTP_SERVICE_CONFIG_CACHE_KEY = *mut HTTP_SERVICE_CONFIG_CACHE_KEY; +pub type HTTP_SERVICE_CONFIG_CACHE_PARAM = ::ULONG; +pub type PHTTP_SERVICE_CONFIG_CACHE_PARAM = *mut ::ULONG; +STRUCT!{struct HTTP_SERVICE_CONFIG_CACHE_SET { + KeyDesc: HTTP_SERVICE_CONFIG_CACHE_KEY, + ParamDesc: HTTP_SERVICE_CONFIG_CACHE_PARAM, +}} +pub type PHTTP_SERVICE_CONFIG_CACHE_SET = *mut HTTP_SERVICE_CONFIG_CACHE_SET; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/imm.rs b/third_party/cargo/vendor/winapi-0.2.8/src/imm.rs new file mode 100644 index 0000000..cadf6cf --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/imm.rs @@ -0,0 +1,3 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub type LPUINT = *mut ::c_uint; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/inaddr.rs b/third_party/cargo/vendor/winapi-0.2.8/src/inaddr.rs new file mode 100644 index 0000000..f89e9ba --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/inaddr.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! IPv4 Internet address +STRUCT!{struct in_addr_S_un_b { + s_b1: ::UCHAR, + s_b2: ::UCHAR, + s_b3: ::UCHAR, + s_b4: ::UCHAR, +}} +STRUCT!{struct in_addr_S_un_w { + s_w1: ::USHORT, + s_w2: ::USHORT, +}} +STRUCT!{struct in_addr { + S_un: ::ULONG, +}} +UNION!(in_addr, S_un, S_un_b, S_un_b_mut, in_addr_S_un_b); +UNION!(in_addr, S_un, S_un_w, S_un_w_mut, in_addr_S_un_w); +UNION!(in_addr, S_un, S_addr, S_addr_mut, ::ULONG); +pub type IN_ADDR = in_addr; +pub type PIN_ADDR = *mut in_addr; +pub type LPIN_ADDR = *mut in_addr; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/inspectable.rs b/third_party/cargo/vendor/winapi-0.2.8/src/inspectable.rs new file mode 100644 index 0000000..36575e1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/inspectable.rs @@ -0,0 +1,15 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub type LPINSPECTABLE = *mut IInspectable; +ENUM!{enum TrustLevel { + BaseTrust = 0, + PartialTrust, + FullTrust, +}} +RIDL!( +interface IInspectable(IInspectableVtbl): IUnknown(IUnknownVtbl) { + fn GetIids(&mut self, iidCount: *mut ::ULONG, iids: *mut *mut ::IID) -> ::HRESULT, + fn GetRuntimeClassName(&mut self, className: *mut ::HSTRING) -> ::HRESULT, + fn GetTrustLevel(&mut self, trustLevel: *mut TrustLevel) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ksmedia.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ksmedia.rs new file mode 100644 index 0000000..8ef2700 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ksmedia.rs @@ -0,0 +1,18 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ANALOG, 0x6DBA3190, 0x67BD, 0x11CF, + 0xA0, 0xF7, 0x00, 0x20, 0xAF, 0xD1, 0x56, 0xE4); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_DRM, 0x00000009, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ALAW, 0x00000006, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_MULAW, 0x00000007, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_ADPCM, 0x00000002, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); +DEFINE_GUID!(KSDATAFORMAT_SUBTYPE_MPEG, 0x00000050, 0x0000, 0x0010, + 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lib.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lib.rs new file mode 100644 index 0000000..0e99f81 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lib.rs @@ -0,0 +1,368 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Types and constants for WinAPI bindings. +#![allow(bad_style)] +#![warn(trivial_casts, trivial_numeric_casts)] +#![warn(unused_qualifications, unused)] +#![cfg(windows)] +//------------------------------------------------------------------------------------------------- +// Imports +//------------------------------------------------------------------------------------------------- +pub use std::os::raw::{ + c_void, + c_char, + c_schar, + c_uchar, + c_short, + c_ushort, + c_int, + c_uint, + c_long, + c_ulong, + c_longlong, + c_ulonglong, + c_float, + c_double, +}; +pub use activation::*; +pub use audioclient::*; +pub use audiosessiontypes::*; +pub use basetsd::*; +pub use bcrypt::*; +pub use cfg::*; +pub use cfgmgr32::*; +pub use combaseapi::*; +pub use commctrl::*; +pub use commdlg::*; +pub use corsym::*; +pub use d2d1::*; +pub use d2dbasetypes::*; +pub use d3d9::*; +pub use d3d9caps::*; +pub use d3d9types::*; +pub use d3d11::*; +pub use d3d10shader::*; +pub use d3d11shader::*; +pub use d3d12::*; +pub use d3d12sdklayers::*; +pub use d3d12shader::*; +pub use d3dcommon::*; +pub use d3dcompiler::*; +pub use dbghelp::*; +pub use dcommon::*; +pub use devpropdef::*; +pub use docobj::*; +pub use dpapi::*; +pub use dsgetdc::*; +pub use dsound::*; +pub use dsrole::*; +pub use dwmapi::*; +pub use dwrite::*; +pub use dxgi::*; +pub use dxgi1_2::*; +pub use dxgi1_3::*; +pub use dxgi1_4::*; +pub use dxgiformat::*; +pub use dxgitype::*; +pub use errhandlingapi::*; +pub use excpt::*; +pub use fileapi::*; +pub use gl::*; +pub use guiddef::*; +pub use heapapi::*; +pub use hidclass::*; +pub use hidpi::*; +pub use hidsdi::*; +pub use hidusage::*; +pub use hstring::*; +pub use http::*; +pub use imm::*; +pub use inaddr::*; +pub use inspectable::*; +pub use ksmedia::*; +pub use libloaderapi::*; +pub use lmaccess::*; +pub use lmcons::*; +pub use lmdfs::*; +pub use lmerrlog::*; +pub use lmjoin::*; +pub use lsalookup::*; +pub use memoryapi::*; +pub use minschannel::*; +pub use minwinbase::*; +pub use minwindef::*; +pub use mmdeviceapi::*; +pub use mmreg::*; +pub use mmsystem::*; +pub use mscat::*; +pub use mssip::*; +pub use nb30::*; +pub use ncrypt::*; +pub use ntdef::*; +pub use ntsecapi::*; +pub use ntstatus::*; +pub use oaidl::*; +pub use objbase::*; +pub use objidl::*; +pub use objidlbase::*; +pub use olectl::*; +pub use pdh::*; +pub use playsoundapi::*; +pub use processsnapshot::*; +pub use processthreadsapi::*; +pub use propidl::*; +pub use propsys::*; +pub use prsht::*; +pub use psapi::*; +pub use qos::*; +pub use reason::*; +pub use restrictederrorinfo::*; +pub use roapi::*; +pub use roerrorapi::*; +pub use rpc::*; +pub use rpcdce::*; +pub use sapi::*; +pub use schannel::*; +pub use servprov::*; +pub use setupapi::*; +pub use shellapi::*; +pub use shellscalingapi::*; +pub use shlguid::*; +pub use shlobj::*; +pub use shobjidl::*; +pub use shtypes::*; +pub use spapidef::*; +pub use sqltypes::*; +pub use sspi::*; +pub use strmif::*; +pub use subauth::*; +pub use synchapi::*; +pub use sysinfoapi::*; +pub use threadpoolapi::*; +pub use timezoneapi::*; +pub use tlhelp32::*; +pub use unknwnbase::*; +pub use urlhist::*; +pub use urlmon::*; +pub use usb::*; +pub use usbspec::*; +pub use usp10::*; +pub use vadefs::*; +pub use vsbackup::*; +pub use vss::*; +pub use vsserror::*; +pub use vswriter::*; +pub use werapi::*; +pub use winbase::*; +pub use wincon::*; +pub use wincred::*; +pub use wincrypt::*; +pub use windowsx::*; +pub use windef::*; +pub use windowscodecs::*; +pub use winerror::*; +pub use winevt::*; +pub use wingdi::*; +pub use winhttp::*; +pub use winioctl::*; +pub use winnetwk::*; +pub use winnls::*; +pub use winnt::*; +pub use winreg::*; +pub use winscard::*; +pub use winsmcrd::*; +pub use winsock2::*; +pub use winspool::*; +pub use winstring::*; +pub use winsvc::*; +pub use winusb::*; +pub use winusbio::*; +pub use winuser::*; +pub use ws2def::*; +pub use ws2ipdef::*; +pub use ws2spi::*; +pub use ws2tcpip::*; +pub use wtypes::*; +pub use wtypesbase::*; +pub use xinput::*; +//------------------------------------------------------------------------------------------------- +// Modules +//------------------------------------------------------------------------------------------------- +#[macro_use] mod macros; +pub mod activation; +pub mod audioclient; +pub mod audiosessiontypes; +pub mod basetsd; +pub mod bcrypt; +pub mod cfg; +pub mod cfgmgr32; +pub mod combaseapi; +pub mod commctrl; +pub mod commdlg; +pub mod corsym; +pub mod d2d1; +pub mod d2dbasetypes; +pub mod d3d9; +pub mod d3d9caps; +pub mod d3d9types; +pub mod d3d11; +pub mod d3d10shader; +pub mod d3d11shader; +pub mod d3d12; +pub mod d3d12sdklayers; +pub mod d3d12shader; +pub mod d3dcommon; +pub mod d3dcompiler; +pub mod dbghelp; +pub mod dcommon; +pub mod devpropdef; +pub mod docobj; +pub mod dpapi; +pub mod dsgetdc; +pub mod dsound; +pub mod dsrole; +pub mod dwmapi; +pub mod dwrite; +pub mod dxgi; +pub mod dxgi1_2; +pub mod dxgi1_3; +pub mod dxgi1_4; +pub mod dxgiformat; +pub mod dxgitype; +pub mod errhandlingapi; +pub mod excpt; +pub mod fileapi; +pub mod gl; +pub mod guiddef; +pub mod heapapi; +pub mod hidclass; +pub mod hidpi; +pub mod hidsdi; +pub mod hidusage; +pub mod hstring; +pub mod http; +pub mod imm; +pub mod inaddr; +pub mod inspectable; +pub mod ksmedia; +pub mod libloaderapi; +pub mod lmaccess; +pub mod lmcons; +pub mod lmdfs; +pub mod lmerrlog; +pub mod lmjoin; +pub mod lsalookup; +pub mod memoryapi; +pub mod minschannel; +pub mod minwinbase; +pub mod minwindef; +pub mod mmdeviceapi; +pub mod mmreg; +pub mod mmsystem; +pub mod mscat; +pub mod mssip; +pub mod nb30; +pub mod ncrypt; +pub mod ntdef; +pub mod ntsecapi; +pub mod ntstatus; +pub mod oaidl; +pub mod objbase; +pub mod objidl; +pub mod objidlbase; +pub mod olectl; +pub mod pdh; +pub mod playsoundapi; +pub mod processsnapshot; +pub mod processthreadsapi; +pub mod propidl; +pub mod propsys; +pub mod prsht; +pub mod psapi; +pub mod qos; +pub mod reason; +pub mod restrictederrorinfo; +pub mod roapi; +pub mod roerrorapi; +pub mod rpc; +pub mod rpcdce; +pub mod sapi; +pub mod schannel; +pub mod servprov; +pub mod setupapi; +pub mod shellapi; +pub mod shellscalingapi; +pub mod shlguid; +pub mod shlobj; +pub mod shobjidl; +pub mod shtypes; +pub mod spapidef; +pub mod sqltypes; +pub mod sspi; +pub mod strmif; +pub mod subauth; +pub mod synchapi; +pub mod sysinfoapi; +pub mod threadpoolapi; +pub mod timezoneapi; +pub mod tlhelp32; +pub mod unknwnbase; +pub mod urlhist; +pub mod urlmon; +pub mod usb; +pub mod usbspec; +pub mod usp10; +pub mod vadefs; +pub mod vsbackup; +pub mod vss; +pub mod vsserror; +pub mod vswriter; +pub mod werapi; +pub mod winbase; +pub mod wincon; +pub mod wincred; +pub mod wincrypt; +pub mod windef; +pub mod windowscodecs; +pub mod windowsx; +pub mod winerror; +pub mod winevt; +pub mod wingdi; +pub mod winhttp; +pub mod winioctl; +pub mod winnetwk; +pub mod winnls; +pub mod winnt; +pub mod winreg; +pub mod winscard; +pub mod winsmcrd; +pub mod winsock2; +pub mod winspool; +pub mod winstring; +pub mod winsvc; +pub mod winusb; +pub mod winusbio; +pub mod winuser; +pub mod ws2def; +pub mod ws2ipdef; +pub mod ws2spi; +pub mod ws2tcpip; +pub mod wtypes; +pub mod wtypesbase; +pub mod xinput; +//------------------------------------------------------------------------------------------------- +// Primitive types not provided by std +//------------------------------------------------------------------------------------------------- +pub type __int8 = i8; +pub type __uint8 = u8; +pub type __int16 = i16; +pub type __uint16 = u16; +pub type __int32 = i32; +pub type __uint32 = u32; +pub type __int64 = i64; +pub type __uint64 = u64; +pub type wchar_t = c_ushort; +#[cfg(target_arch = "x86")] +pub type size_t = c_uint; +#[cfg(target_arch = "x86_64")] +pub type size_t = __uint64; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/libloaderapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/libloaderapi.rs new file mode 100644 index 0000000..9b47b0a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/libloaderapi.rs @@ -0,0 +1,23 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-libraryloader-l1 +pub type DLL_DIRECTORY_COOKIE = ::PVOID; +pub type PDLL_DIRECTORY_COOKIE = *mut ::PVOID; +pub type ENUMRESLANGPROCA = Option ::BOOL>; +pub type ENUMRESLANGPROCW = Option ::BOOL>; +pub type ENUMRESNAMEPROCA = Option ::BOOL>; +pub type ENUMRESNAMEPROCW = Option ::BOOL>; +pub type ENUMRESTYPEPROCA = Option ::BOOL>; +pub type ENUMRESTYPEPROCW = Option ::BOOL>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lmaccess.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lmaccess.rs new file mode 100644 index 0000000..2768f8c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lmaccess.rs @@ -0,0 +1,853 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// This file contains structures, function prototypes, and definitions +// for the NetUser, NetUserModals, NetGroup, NetAccess, and NetLogon API. +STRUCT!{struct USER_INFO_0 { + usri0_name: ::LPWSTR, +}} +pub type PUSER_INFO_0 = *mut USER_INFO_0; +pub type LPUSER_INFO_0 = *mut USER_INFO_0; +STRUCT!{struct USER_INFO_1 { + usri1_name: ::LPWSTR, + usri1_password: ::LPWSTR, + usri1_password_age: ::DWORD, + usri1_priv: ::DWORD, + usri1_home_dir: ::LPWSTR, + usri1_comment: ::LPWSTR, + usri1_flags: ::DWORD, + usri1_script_path: ::LPWSTR, +}} +pub type PUSER_INFO_1 = *mut USER_INFO_1; +pub type LPUSER_INFO_1 = *mut USER_INFO_1; +STRUCT!{struct USER_INFO_2 { + usri2_name: ::LPWSTR, + usri2_password: ::LPWSTR, + usri2_password_age: ::DWORD, + usri2_priv: ::DWORD, + usri2_home_dir: ::LPWSTR, + usri2_comment: ::LPWSTR, + usri2_flags: ::DWORD, + usri2_script_path: ::LPWSTR, + usri2_auth_flags: ::DWORD, + usri2_full_name: ::LPWSTR, + usri2_usr_comment: ::LPWSTR, + usri2_parms: ::LPWSTR, + usri2_workstations: ::LPWSTR, + usri2_last_logon: ::DWORD, + usri2_last_logoff: ::DWORD, + usri2_acct_expires: ::DWORD, + usri2_max_storage: ::DWORD, + usri2_units_per_week: ::DWORD, + usri2_logon_hours: ::PBYTE, + usri2_bad_pw_count: ::DWORD, + usri2_num_logons: ::DWORD, + usri2_logon_server: ::LPWSTR, + usri2_country_code: ::DWORD, + usri2_code_page: ::DWORD, +}} +pub type PUSER_INFO_2 = *mut USER_INFO_2; +pub type LPUSER_INFO_2 = *mut USER_INFO_2; +STRUCT!{struct USER_INFO_3 { + usri3_name: ::LPWSTR, + usri3_password: ::LPWSTR, + usri3_password_age: ::DWORD, + usri3_priv: ::DWORD, + usri3_home_dir: ::LPWSTR, + usri3_comment: ::LPWSTR, + usri3_flags: ::DWORD, + usri3_script_path: ::LPWSTR, + usri3_auth_flags: ::DWORD, + usri3_full_name: ::LPWSTR, + usri3_usr_comment: ::LPWSTR, + usri3_parms: ::LPWSTR, + usri3_workstations: ::LPWSTR, + usri3_last_logon: ::DWORD, + usri3_last_logoff: ::DWORD, + usri3_acct_expires: ::DWORD, + usri3_max_storage: ::DWORD, + usri3_units_per_week: ::DWORD, + usri3_logon_hours: ::PBYTE, + usri3_bad_pw_count: ::DWORD, + usri3_num_logons: ::DWORD, + usri3_logon_server: ::LPWSTR, + usri3_country_code: ::DWORD, + usri3_code_page: ::DWORD, + usri3_user_id: ::DWORD, + usri3_primary_group_id: ::DWORD, + usri3_profile: ::LPWSTR, + usri3_home_dir_drive: ::LPWSTR, + usri3_password_expired: ::DWORD, +}} +pub type PUSER_INFO_3 = *mut USER_INFO_3; +pub type LPUSER_INFO_3 = *mut USER_INFO_3; +STRUCT!{struct USER_INFO_4 { + usri4_name: ::LPWSTR, + usri4_password: ::LPWSTR, + usri4_password_age: ::DWORD, + usri4_priv: ::DWORD, + usri4_home_dir: ::LPWSTR, + usri4_comment: ::LPWSTR, + usri4_flags: ::DWORD, + usri4_script_path: ::LPWSTR, + usri4_auth_flags: ::DWORD, + usri4_full_name: ::LPWSTR, + usri4_usr_comment: ::LPWSTR, + usri4_parms: ::LPWSTR, + usri4_workstations: ::LPWSTR, + usri4_last_logon: ::DWORD, + usri4_last_logoff: ::DWORD, + usri4_acct_expires: ::DWORD, + usri4_max_storage: ::DWORD, + usri4_units_per_week: ::DWORD, + usri4_logon_hours: ::PBYTE, + usri4_bad_pw_count: ::DWORD, + usri4_num_logons: ::DWORD, + usri4_logon_server: ::LPWSTR, + usri4_country_code: ::DWORD, + usri4_code_page: ::DWORD, + usri4_user_sid: ::PSID, + usri4_primary_group_id: ::DWORD, + usri4_profile: ::LPWSTR, + usri4_home_dir_drive: ::LPWSTR, + usri4_password_expired: ::DWORD, +}} +pub type PUSER_INFO_4 = *mut USER_INFO_4; +pub type LPUSER_INFO_4 = *mut USER_INFO_4; +STRUCT!{struct USER_INFO_10 { + usri10_name: ::LPWSTR, + usri10_comment: ::LPWSTR, + usri10_usr_comment: ::LPWSTR, + usri10_full_name: ::LPWSTR, +}} +pub type PUSER_INFO_10 = *mut USER_INFO_10; +pub type LPUSER_INFO_10 = *mut USER_INFO_10; +STRUCT!{struct USER_INFO_11 { + usri11_name: ::LPWSTR, + usri11_comment: ::LPWSTR, + usri11_usr_comment: ::LPWSTR, + usri11_full_name: ::LPWSTR, + usri11_priv: ::DWORD, + usri11_auth_flags: ::DWORD, + usri11_password_age: ::DWORD, + usri11_home_dir: ::LPWSTR, + usri11_parms: ::LPWSTR, + usri11_last_logon: ::DWORD, + usri11_last_logoff: ::DWORD, + usri11_bad_pw_count: ::DWORD, + usri11_num_logons: ::DWORD, + usri11_logon_server: ::LPWSTR, + usri11_country_code: ::DWORD, + usri11_workstations: ::LPWSTR, + usri11_max_storage: ::DWORD, + usri11_units_per_week: ::DWORD, + usri11_logon_hours: ::PBYTE, + usri11_code_page: ::DWORD, +}} +pub type PUSER_INFO_11 = *mut USER_INFO_11; +pub type LPUSER_INFO_11 = *mut USER_INFO_11; +STRUCT!{struct USER_INFO_20 { + usri20_name: ::LPWSTR, + usri20_full_name: ::LPWSTR, + usri20_comment: ::LPWSTR, + usri20_flags: ::DWORD, + usri20_user_id: ::DWORD, +}} +pub type PUSER_INFO_20 = *mut USER_INFO_20; +pub type LPUSER_INFO_20 = *mut USER_INFO_20; +STRUCT!{struct USER_INFO_21 { + usri21_password: [::BYTE; ::ENCRYPTED_PWLEN], +}} +pub type PUSER_INFO_21 = *mut USER_INFO_21; +pub type LPUSER_INFO_21 = *mut USER_INFO_21; +STRUCT!{struct USER_INFO_22 { + usri22_name: ::LPWSTR, + usri22_password: [::BYTE; ::ENCRYPTED_PWLEN], + usri22_password_age: ::DWORD, + usri22_priv: ::DWORD, + usri22_home_dir: ::LPWSTR, + usri22_comment: ::LPWSTR, + usri22_flags: ::DWORD, + usri22_script_path: ::LPWSTR, + usri22_auth_flags: ::DWORD, + usri22_full_name: ::LPWSTR, + usri22_usr_comment: ::LPWSTR, + usri22_parms: ::LPWSTR, + usri22_workstations: ::LPWSTR, + usri22_last_logon: ::DWORD, + usri22_last_logoff: ::DWORD, + usri22_acct_expires: ::DWORD, + usri22_max_storage: ::DWORD, + usri22_units_per_week: ::DWORD, + usri22_logon_hours: ::PBYTE, + usri22_bad_pw_count: ::DWORD, + usri22_num_logons: ::DWORD, + usri22_logon_server: ::LPWSTR, + usri22_country_code: ::DWORD, + usri22_code_page: ::DWORD, +}} +pub type PUSER_INFO_22 = *mut USER_INFO_22; +pub type LPUSER_INFO_22 = *mut USER_INFO_22; +STRUCT!{struct USER_INFO_23 { + usri23_name: ::LPWSTR, + usri23_full_name: ::LPWSTR, + usri23_comment: ::LPWSTR, + usri23_flags: ::DWORD, + usri23_user_sid: ::PSID, +}} +pub type PUSER_INFO_23 = *mut USER_INFO_23; +pub type LPUSER_INFO_23 = *mut USER_INFO_23; +STRUCT!{struct USER_INFO_24 { + usri24_internet_identity: ::BOOL, + usri24_flags: ::DWORD, + usri24_internet_provider_name: ::LPWSTR, + usri24_internet_principal_name: ::LPWSTR, + usri24_user_sid: ::PSID, +}} +pub type PUSER_INFO_24 = *mut USER_INFO_24; +pub type LPUSER_INFO_24 = *mut USER_INFO_24; +STRUCT!{struct USER_INFO_1003 { + usri1003_password: ::LPWSTR, +}} +pub type PUSER_INFO_1003 = *mut USER_INFO_1003; +pub type LPUSER_INFO_1003 = *mut USER_INFO_1003; +STRUCT!{struct USER_INFO_1005 { + usri1005_priv: ::DWORD, +}} +pub type PUSER_INFO_1005 = *mut USER_INFO_1005; +pub type LPUSER_INFO_1005 = *mut USER_INFO_1005; +STRUCT!{struct USER_INFO_1006 { + usri1006_home_dir: ::LPWSTR, +}} +pub type PUSER_INFO_1006 = *mut USER_INFO_1006; +pub type LPUSER_INFO_1006 = *mut USER_INFO_1006; +STRUCT!{struct USER_INFO_1007 { + usri1007_comment: ::LPWSTR, +}} +pub type PUSER_INFO_1007 = *mut USER_INFO_1007; +pub type LPUSER_INFO_1007 = *mut USER_INFO_1007; +STRUCT!{struct USER_INFO_1008 { + usri1008_flags: ::DWORD, +}} +pub type PUSER_INFO_1008 = *mut USER_INFO_1008; +pub type LPUSER_INFO_1008 = *mut USER_INFO_1008; +STRUCT!{struct USER_INFO_1009 { + usri1009_script_path: ::LPWSTR, +}} +pub type PUSER_INFO_1009 = *mut USER_INFO_1009; +pub type LPUSER_INFO_1009 = *mut USER_INFO_1009; +STRUCT!{struct USER_INFO_1010 { + usri1010_auth_flags: ::DWORD, +}} +pub type PUSER_INFO_1010 = *mut USER_INFO_1010; +pub type LPUSER_INFO_1010 = *mut USER_INFO_1010; +STRUCT!{struct USER_INFO_1011 { + usri1011_full_name: ::LPWSTR, +}} +pub type PUSER_INFO_1011 = *mut USER_INFO_1011; +pub type LPUSER_INFO_1011 = *mut USER_INFO_1011; +STRUCT!{struct USER_INFO_1012 { + usri1012_usr_comment: ::LPWSTR, +}} +pub type PUSER_INFO_1012 = *mut USER_INFO_1012; +pub type LPUSER_INFO_1012 = *mut USER_INFO_1012; +STRUCT!{struct USER_INFO_1013 { + usri1013_parms: ::LPWSTR, +}} +pub type PUSER_INFO_1013 = *mut USER_INFO_1013; +pub type LPUSER_INFO_1013 = *mut USER_INFO_1013; +STRUCT!{struct USER_INFO_1014 { + usri1014_workstations: ::LPWSTR, +}} +pub type PUSER_INFO_1014 = *mut USER_INFO_1014; +pub type LPUSER_INFO_1014 = *mut USER_INFO_1014; +STRUCT!{struct USER_INFO_1017 { + usri1017_acct_expires: ::DWORD, +}} +pub type PUSER_INFO_1017 = *mut USER_INFO_1017; +pub type LPUSER_INFO_1017 = *mut USER_INFO_1017; +STRUCT!{struct USER_INFO_1018 { + usri1018_max_storage: ::DWORD, +}} +pub type PUSER_INFO_1018 = *mut USER_INFO_1018; +pub type LPUSER_INFO_1018 = *mut USER_INFO_1018; +STRUCT!{struct USER_INFO_1020 { + usri1020_units_per_week: ::DWORD, + usri1020_logon_hours: ::LPBYTE, +}} +pub type PUSER_INFO_1020 = *mut USER_INFO_1020; +pub type LPUSER_INFO_1020 = *mut USER_INFO_1020; +STRUCT!{struct USER_INFO_1023 { + usri1023_logon_server: ::LPWSTR, +}} +pub type PUSER_INFO_1023 = *mut USER_INFO_1023; +pub type LPUSER_INFO_1023 = *mut USER_INFO_1023; +STRUCT!{struct USER_INFO_1024 { + usri1024_country_code: ::DWORD, +}} +pub type PUSER_INFO_1024 = *mut USER_INFO_1024; +pub type LPUSER_INFO_1024 = *mut USER_INFO_1024; +STRUCT!{struct USER_INFO_1025 { + usri1025_code_page: ::DWORD, +}} +pub type PUSER_INFO_1025 = *mut USER_INFO_1025; +pub type LPUSER_INFO_1025 = *mut USER_INFO_1025; +STRUCT!{struct USER_INFO_1051 { + usri1051_primary_group_id: ::DWORD, +}} +pub type PUSER_INFO_1051 = *mut USER_INFO_1051; +pub type LPUSER_INFO_1051 = *mut USER_INFO_1051; +STRUCT!{struct USER_INFO_1052 { + usri1052_profile: ::LPWSTR, +}} +pub type PUSER_INFO_1052 = *mut USER_INFO_1052; +pub type LPUSER_INFO_1052 = *mut USER_INFO_1052; +STRUCT!{struct USER_INFO_1053 { + usri1053_home_dir_drive: ::LPWSTR, +}} +pub type PUSER_INFO_1053 = *mut USER_INFO_1053; +pub type LPUSER_INFO_1053 = *mut USER_INFO_1053; +STRUCT!{struct USER_MODALS_INFO_0 { + usrmod0_min_passwd_len: ::DWORD, + usrmod0_max_passwd_age: ::DWORD, + usrmod0_min_passwd_age: ::DWORD, + usrmod0_force_logoff: ::DWORD, + usrmod0_password_hist_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_0 = *mut USER_MODALS_INFO_0; +pub type LPUSER_MODALS_INFO_0 = *mut USER_MODALS_INFO_0; +STRUCT!{struct USER_MODALS_INFO_1 { + usrmod1_role: ::DWORD, + usrmod1_primary: ::LPWSTR, +}} +pub type PUSER_MODALS_INFO_1 = *mut USER_MODALS_INFO_1; +pub type LPUSER_MODALS_INFO_1 = *mut USER_MODALS_INFO_1; +STRUCT!{struct USER_MODALS_INFO_2 { + usrmod2_domain_name: ::LPWSTR, + usrmod2_domain_id: ::PSID, +}} +pub type PUSER_MODALS_INFO_2 = *mut USER_MODALS_INFO_2; +pub type LPUSER_MODALS_INFO_2 = *mut USER_MODALS_INFO_2; +STRUCT!{struct USER_MODALS_INFO_3 { + usrmod3_lockout_duration: ::DWORD, + usrmod3_lockout_observation_window: ::DWORD, + usrmod3_lockout_threshold: ::DWORD, +}} +pub type PUSER_MODALS_INFO_3 = *mut USER_MODALS_INFO_3; +pub type LPUSER_MODALS_INFO_3 = *mut USER_MODALS_INFO_3; +STRUCT!{struct USER_MODALS_INFO_1001 { + usrmod1001_min_passwd_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1001 = *mut USER_MODALS_INFO_1001; +pub type LPUSER_MODALS_INFO_1001 = *mut USER_MODALS_INFO_1001; +STRUCT!{struct USER_MODALS_INFO_1002 { + usrmod1002_max_passwd_age: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1002 = *mut USER_MODALS_INFO_1002; +pub type LPUSER_MODALS_INFO_1002 = *mut USER_MODALS_INFO_1002; +STRUCT!{struct USER_MODALS_INFO_1003 { + usrmod1003_min_passwd_age: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1003 = *mut USER_MODALS_INFO_1003; +pub type LPUSER_MODALS_INFO_1003 = *mut USER_MODALS_INFO_1003; +STRUCT!{struct USER_MODALS_INFO_1004 { + usrmod1004_force_logoff: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1004 = *mut USER_MODALS_INFO_1004; +pub type LPUSER_MODALS_INFO_1004 = *mut USER_MODALS_INFO_1004; +STRUCT!{struct USER_MODALS_INFO_1005 { + usrmod1005_password_hist_len: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1005 = *mut USER_MODALS_INFO_1005; +pub type LPUSER_MODALS_INFO_1005 = *mut USER_MODALS_INFO_1005; +STRUCT!{struct USER_MODALS_INFO_1006 { + usrmod1006_role: ::DWORD, +}} +pub type PUSER_MODALS_INFO_1006 = *mut USER_MODALS_INFO_1006; +pub type LPUSER_MODALS_INFO_1006 = *mut USER_MODALS_INFO_1006; +STRUCT!{struct USER_MODALS_INFO_1007 { + usrmod1007_primary: ::LPWSTR, +}} +pub type PUSER_MODALS_INFO_1007 = *mut USER_MODALS_INFO_1007; +pub type LPUSER_MODALS_INFO_1007 = *mut USER_MODALS_INFO_1007; +pub const UF_SCRIPT: ::DWORD = 0x0001; +pub const UF_ACCOUNTDISABLE: ::DWORD = 0x0002; +pub const UF_HOMEDIR_REQUIRED: ::DWORD = 0x0008; +pub const UF_LOCKOUT: ::DWORD = 0x0010; +pub const UF_PASSWD_NOTREQD: ::DWORD = 0x0020; +pub const UF_PASSWD_CANT_CHANGE: ::DWORD = 0x0040; +pub const UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: ::DWORD = 0x0080; +pub const UF_TEMP_DUPLICATE_ACCOUNT: ::DWORD = 0x0100; +pub const UF_NORMAL_ACCOUNT: ::DWORD = 0x0200; +pub const UF_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 0x0800; +pub const UF_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 0x1000; +pub const UF_SERVER_TRUST_ACCOUNT: ::DWORD = 0x2000; +pub const UF_MACHINE_ACCOUNT_MASK: ::DWORD = UF_INTERDOMAIN_TRUST_ACCOUNT + | UF_WORKSTATION_TRUST_ACCOUNT | UF_SERVER_TRUST_ACCOUNT; +pub const UF_ACCOUNT_TYPE_MASK: ::DWORD = UF_TEMP_DUPLICATE_ACCOUNT | UF_NORMAL_ACCOUNT + | UF_INTERDOMAIN_TRUST_ACCOUNT | UF_WORKSTATION_TRUST_ACCOUNT | UF_SERVER_TRUST_ACCOUNT; +pub const UF_DONT_EXPIRE_PASSWD: ::DWORD = 0x10000; +pub const UF_MNS_LOGON_ACCOUNT: ::DWORD = 0x20000; +pub const UF_SMARTCARD_REQUIRED: ::DWORD = 0x40000; +pub const UF_TRUSTED_FOR_DELEGATION: ::DWORD = 0x80000; +pub const UF_NOT_DELEGATED: ::DWORD = 0x100000; +pub const UF_USE_DES_KEY_ONLY: ::DWORD = 0x200000; +pub const UF_DONT_REQUIRE_PREAUTH: ::DWORD = 0x400000; +pub const UF_PASSWORD_EXPIRED: ::DWORD = 0x800000; +pub const UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: ::DWORD = 0x1000000; +pub const UF_NO_AUTH_DATA_REQUIRED: ::DWORD = 0x2000000; +pub const UF_PARTIAL_SECRETS_ACCOUNT: ::DWORD = 0x4000000; +pub const UF_USE_AES_KEYS: ::DWORD = 0x8000000; +pub const UF_SETTABLE_BITS: ::DWORD = UF_SCRIPT | UF_ACCOUNTDISABLE | UF_LOCKOUT + | UF_HOMEDIR_REQUIRED | UF_PASSWD_NOTREQD | UF_PASSWD_CANT_CHANGE | UF_ACCOUNT_TYPE_MASK + | UF_DONT_EXPIRE_PASSWD | UF_MNS_LOGON_ACCOUNT | UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED + | UF_SMARTCARD_REQUIRED | UF_TRUSTED_FOR_DELEGATION | UF_NOT_DELEGATED | UF_USE_DES_KEY_ONLY + | UF_DONT_REQUIRE_PREAUTH | UF_PASSWORD_EXPIRED | UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION + | UF_NO_AUTH_DATA_REQUIRED | UF_USE_AES_KEYS | UF_PARTIAL_SECRETS_ACCOUNT; +pub const FILTER_TEMP_DUPLICATE_ACCOUNT: ::DWORD = 0x0001; +pub const FILTER_NORMAL_ACCOUNT: ::DWORD = 0x0002; +pub const FILTER_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 0x0008; +pub const FILTER_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 0x0010; +pub const FILTER_SERVER_TRUST_ACCOUNT: ::DWORD = 0x0020; +pub const LG_INCLUDE_INDIRECT: ::DWORD = 0x0001; +pub const AF_OP_PRINT: ::DWORD = 0x1; +pub const AF_OP_COMM: ::DWORD = 0x2; +pub const AF_OP_SERVER: ::DWORD = 0x4; +pub const AF_OP_ACCOUNTS: ::DWORD = 0x8; +pub const AF_SETTABLE_BITS: ::DWORD = AF_OP_PRINT | AF_OP_COMM | AF_OP_SERVER | AF_OP_ACCOUNTS; +pub const UAS_ROLE_STANDALONE: ::DWORD = 0; +pub const UAS_ROLE_MEMBER: ::DWORD = 1; +pub const UAS_ROLE_BACKUP: ::DWORD = 2; +pub const UAS_ROLE_PRIMARY: ::DWORD = 3; +pub const USER_NAME_PARMNUM: ::DWORD = 1; +pub const USER_PASSWORD_PARMNUM: ::DWORD = 3; +pub const USER_PASSWORD_AGE_PARMNUM: ::DWORD = 4; +pub const USER_PRIV_PARMNUM: ::DWORD = 5; +pub const USER_HOME_DIR_PARMNUM: ::DWORD = 6; +pub const USER_COMMENT_PARMNUM: ::DWORD = 7; +pub const USER_FLAGS_PARMNUM: ::DWORD = 8; +pub const USER_SCRIPT_PATH_PARMNUM: ::DWORD = 9; +pub const USER_AUTH_FLAGS_PARMNUM: ::DWORD = 10; +pub const USER_FULL_NAME_PARMNUM: ::DWORD = 11; +pub const USER_USR_COMMENT_PARMNUM: ::DWORD = 12; +pub const USER_PARMS_PARMNUM: ::DWORD = 13; +pub const USER_WORKSTATIONS_PARMNUM: ::DWORD = 14; +pub const USER_LAST_LOGON_PARMNUM: ::DWORD = 15; +pub const USER_LAST_LOGOFF_PARMNUM: ::DWORD = 16; +pub const USER_ACCT_EXPIRES_PARMNUM: ::DWORD = 17; +pub const USER_MAX_STORAGE_PARMNUM: ::DWORD = 18; +pub const USER_UNITS_PER_WEEK_PARMNUM: ::DWORD = 19; +pub const USER_LOGON_HOURS_PARMNUM: ::DWORD = 20; +pub const USER_PAD_PW_COUNT_PARMNUM: ::DWORD = 21; +pub const USER_NUM_LOGONS_PARMNUM: ::DWORD = 22; +pub const USER_LOGON_SERVER_PARMNUM: ::DWORD = 23; +pub const USER_COUNTRY_CODE_PARMNUM: ::DWORD = 24; +pub const USER_CODE_PAGE_PARMNUM: ::DWORD = 25; +pub const USER_PRIMARY_GROUP_PARMNUM: ::DWORD = 51; +pub const USER_PROFILE: ::DWORD = 52; +pub const USER_PROFILE_PARMNUM: ::DWORD = 52; +pub const USER_HOME_DIR_DRIVE_PARMNUM: ::DWORD = 53; +pub const USER_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_NAME_PARMNUM; +pub const USER_PASSWORD_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_PARMNUM; +pub const USER_PASSWORD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_AGE_PARMNUM; +pub const USER_PRIV_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PRIV_PARMNUM; +pub const USER_HOME_DIR_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_PARMNUM; +pub const USER_COMMENT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_COMMENT_PARMNUM; +pub const USER_FLAGS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_FLAGS_PARMNUM; +pub const USER_SCRIPT_PATH_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_SCRIPT_PATH_PARMNUM; +pub const USER_AUTH_FLAGS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_AUTH_FLAGS_PARMNUM; +pub const USER_FULL_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_FULL_NAME_PARMNUM; +pub const USER_USR_COMMENT_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_USR_COMMENT_PARMNUM; +pub const USER_PARMS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_PARMS_PARMNUM; +pub const USER_WORKSTATIONS_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_WORKSTATIONS_PARMNUM; +pub const USER_LAST_LOGON_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGON_PARMNUM; +pub const USER_LAST_LOGOFF_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGOFF_PARMNUM; +pub const USER_ACCT_EXPIRES_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_ACCT_EXPIRES_PARMNUM; +pub const USER_MAX_STORAGE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_MAX_STORAGE_PARMNUM; +pub const USER_UNITS_PER_WEEK_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_UNITS_PER_WEEK_PARMNUM; +pub const USER_LOGON_HOURS_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LOGON_HOURS_PARMNUM; +pub const USER_PAD_PW_COUNT_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PAD_PW_COUNT_PARMNUM; +pub const USER_NUM_LOGONS_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_NUM_LOGONS_PARMNUM; +pub const USER_LOGON_SERVER_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_LOGON_SERVER_PARMNUM; +pub const USER_COUNTRY_CODE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_COUNTRY_CODE_PARMNUM; +pub const USER_CODE_PAGE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + USER_CODE_PAGE_PARMNUM; +pub const USER_PRIMARY_GROUP_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_PRIMARY_GROUP_PARMNUM; +pub const USER_HOME_DIR_DRIVE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_DRIVE_PARMNUM; +pub const TIMEQ_FOREVER: ::DWORD = -1i32 as ::DWORD; +pub const USER_MAXSTORAGE_UNLIMITED: ::DWORD = -1i32 as ::DWORD; +pub const USER_NO_LOGOFF: ::DWORD = -1i32 as ::DWORD; +pub const UNITS_PER_DAY: ::DWORD = 24; +pub const UNITS_PER_WEEK: ::DWORD = UNITS_PER_DAY * 7; +pub const USER_PRIV_MASK: ::DWORD = 0x3; +pub const USER_PRIV_GUEST: ::DWORD = 0; +pub const USER_PRIV_USER: ::DWORD = 1; +pub const USER_PRIV_ADMIN: ::DWORD = 2; +pub const MAX_PASSWD_LEN: ::DWORD = ::PWLEN; +pub const DEF_MIN_PWLEN: ::DWORD = 6; +pub const DEF_PWUNIQUENESS: ::DWORD = 5; +pub const DEF_MAX_PWHIST: ::DWORD = 8; +pub const DEF_MAX_PWAGE: ::DWORD = TIMEQ_FOREVER; +pub const DEF_MIN_PWAGE: ::DWORD = 0; +pub const DEF_FORCE_LOGOFF: ::DWORD = 0xffffffff; +pub const DEF_MAX_BADPW: ::DWORD = 0; +pub const ONE_DAY: ::DWORD = 1 * 24 * 3600; +pub const VALIDATED_LOGON: ::DWORD = 0; +pub const PASSWORD_EXPIRED: ::DWORD = 2; +pub const NON_VALIDATED_LOGON: ::DWORD = 3; +pub const VALID_LOGOFF: ::DWORD = 1; +pub const MODALS_MIN_PASSWD_LEN_PARMNUM: ::DWORD = 1; +pub const MODALS_MAX_PASSWD_AGE_PARMNUM: ::DWORD = 2; +pub const MODALS_MIN_PASSWD_AGE_PARMNUM: ::DWORD = 3; +pub const MODALS_FORCE_LOGOFF_PARMNUM: ::DWORD = 4; +pub const MODALS_PASSWD_HIST_LEN_PARMNUM: ::DWORD = 5; +pub const MODALS_ROLE_PARMNUM: ::DWORD = 6; +pub const MODALS_PRIMARY_PARMNUM: ::DWORD = 7; +pub const MODALS_DOMAIN_NAME_PARMNUM: ::DWORD = 8; +pub const MODALS_DOMAIN_ID_PARMNUM: ::DWORD = 9; +pub const MODALS_LOCKOUT_DURATION_PARMNUM: ::DWORD = 10; +pub const MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM: ::DWORD = 11; +pub const MODALS_LOCKOUT_THRESHOLD_PARMNUM: ::DWORD = 12; +pub const MODALS_MIN_PASSWD_LEN_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_LEN_PARMNUM; +pub const MODALS_MAX_PASSWD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MAX_PASSWD_AGE_PARMNUM; +pub const MODALS_MIN_PASSWD_AGE_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_AGE_PARMNUM; +pub const MODALS_FORCE_LOGOFF_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_FORCE_LOGOFF_PARMNUM; +pub const MODALS_PASSWD_HIST_LEN_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_PASSWD_HIST_LEN_PARMNUM; +pub const MODALS_ROLE_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_ROLE_PARMNUM; +pub const MODALS_PRIMARY_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_PRIMARY_PARMNUM; +pub const MODALS_DOMAIN_NAME_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_NAME_PARMNUM; +pub const MODALS_DOMAIN_ID_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_ID_PARMNUM; +STRUCT!{struct GROUP_INFO_0 { + grpi0_name: ::LPWSTR, +}} +pub type PGROUP_INFO_0 = *mut GROUP_INFO_0; +pub type LPGROUP_INFO_0 = *mut GROUP_INFO_0; +STRUCT!{struct GROUP_INFO_1 { + grpi1_name: ::LPWSTR, + grpi1_comment: ::LPWSTR, +}} +pub type PGROUP_INFO_1 = *mut GROUP_INFO_1; +pub type LPGROUP_INFO_1 = *mut GROUP_INFO_1; +STRUCT!{struct GROUP_INFO_2 { + grpi2_name: ::LPWSTR, + grpi2_comment: ::LPWSTR, + grpi2_group_id: ::DWORD, + grpi2_attributes: ::DWORD, +}} +pub type PGROUP_INFO_2 = *mut GROUP_INFO_2; +STRUCT!{struct GROUP_INFO_3 { + grpi3_name: ::LPWSTR, + grpi3_comment: ::LPWSTR, + grpi3_group_sid: ::PSID, + grpi3_attributes: ::DWORD, +}} +pub type PGROUP_INFO_3 = *mut GROUP_INFO_3; +STRUCT!{struct GROUP_INFO_1002 { + grpi1002_comment: ::LPWSTR, +}} +pub type PGROUP_INFO_1002 = *mut GROUP_INFO_1002; +pub type LPGROUP_INFO_1002 = *mut GROUP_INFO_1002; +STRUCT!{struct GROUP_INFO_1005 { + grpi1005_attributes: ::DWORD, +}} +pub type PGROUP_INFO_1005 = *mut GROUP_INFO_1005; +pub type LPGROUP_INFO_1005 = *mut GROUP_INFO_1005; +STRUCT!{struct GROUP_USERS_INFO_0 { + grui0_name: ::LPWSTR, +}} +pub type PGROUP_USERS_INFO_0 = *mut GROUP_USERS_INFO_0; +pub type LPGROUP_USERS_INFO_0 = *mut GROUP_USERS_INFO_0; +STRUCT!{struct GROUP_USERS_INFO_1 { + grui1_name: ::LPWSTR, + grui1_attributes: ::DWORD, +}} +pub type PGROUP_USERS_INFO_1 = *mut GROUP_USERS_INFO_1; +pub type LPGROUP_USERS_INFO_1 = *mut GROUP_USERS_INFO_1; +pub const GROUPIDMASK: ::DWORD = 0x8000; +pub const GROUP_SPECIALGRP_USERS: &'static str = "USERS"; +pub const GROUP_SPECIALGRP_ADMINS: &'static str = "ADMINS"; +pub const GROUP_SPECIALGRP_GUESTS: &'static str = "GUESTS"; +pub const GROUP_SPECIALGRP_LOCAL: &'static str = "LOCAL"; +pub const GROUP_ALL_PARMNUM: ::DWORD = 0; +pub const GROUP_NAME_PARMNUM: ::DWORD = 1; +pub const GROUP_COMMENT_PARMNUM: ::DWORD = 2; +pub const GROUP_ATTRIBUTES_PARMNUM: ::DWORD = 3; +pub const GROUP_ALL_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_ALL_PARMNUM; +pub const GROUP_NAME_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_NAME_PARMNUM; +pub const GROUP_COMMENT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_COMMENT_PARMNUM; +pub const GROUP_ATTRIBUTES_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + GROUP_ATTRIBUTES_PARMNUM; +STRUCT!{struct LOCALGROUP_INFO_0 { + lgrpi0_name: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_0 = *mut LOCALGROUP_INFO_0; +pub type LPLOCALGROUP_INFO_0 = *mut LOCALGROUP_INFO_0; +STRUCT!{struct LOCALGROUP_INFO_1 { + lgrpi1_name: ::LPWSTR, + lgrpi1_comment: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_1 = *mut LOCALGROUP_INFO_1; +pub type LPLOCALGROUP_INFO_1 = *mut LOCALGROUP_INFO_1; +STRUCT!{struct LOCALGROUP_INFO_1002 { + lgrpi1002_comment: ::LPWSTR, +}} +pub type PLOCALGROUP_INFO_1002 = *mut LOCALGROUP_INFO_1002; +pub type LPLOCALGROUP_INFO_1002 = *mut LOCALGROUP_INFO_1002; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_0 { + lgrmi0_sid: ::PSID, +}} +pub type PLOCALGROUP_MEMBERS_INFO_0 = *mut LOCALGROUP_MEMBERS_INFO_0; +pub type LPLOCALGROUP_MEMBERS_INFO_0 = *mut LOCALGROUP_MEMBERS_INFO_0; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_1 { + lgrmi1_sid: ::PSID, + lgrmi1_sidusage: ::SID_NAME_USE, + lgrmi1_name: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_1 = *mut LOCALGROUP_MEMBERS_INFO_1; +pub type LPLOCALGROUP_MEMBERS_INFO_1 = *mut LOCALGROUP_MEMBERS_INFO_1; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_2 { + lgrmi2_sid: ::PSID, + lgrmi2_sidusage: ::SID_NAME_USE, + lgrmi2_domainandname: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_2 = *mut LOCALGROUP_MEMBERS_INFO_2; +pub type LPLOCALGROUP_MEMBERS_INFO_2 = *mut LOCALGROUP_MEMBERS_INFO_2; +STRUCT!{struct LOCALGROUP_MEMBERS_INFO_3 { + lgrmi3_domainandname: ::LPWSTR, +}} +pub type PLOCALGROUP_MEMBERS_INFO_3 = *mut LOCALGROUP_MEMBERS_INFO_3; +pub type LPLOCALGROUP_MEMBERS_INFO_3 = *mut LOCALGROUP_MEMBERS_INFO_3; +STRUCT!{struct LOCALGROUP_USERS_INFO_0 { + lgrui0_name: ::LPWSTR, +}} +pub type PLOCALGROUP_USERS_INFO_0 = *mut LOCALGROUP_USERS_INFO_0; +pub type LPLOCALGROUP_USERS_INFO_0 = *mut LOCALGROUP_USERS_INFO_0; +pub const LOCALGROUP_NAME_PARMNUM: ::DWORD = 1; +pub const LOCALGROUP_COMMENT_PARMNUM: ::DWORD = 2; +STRUCT!{struct NET_DISPLAY_USER { + usri1_name: ::LPWSTR, + usri1_comment: ::LPWSTR, + usri1_flags: ::DWORD, + usri1_full_name: ::LPWSTR, + usri1_user_id: ::DWORD, + usri1_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_USER = *mut NET_DISPLAY_USER; +STRUCT!{struct NET_DISPLAY_MACHINE { + usri2_name: ::LPWSTR, + usri2_comment: ::LPWSTR, + usri2_flags: ::DWORD, + usri2_user_id: ::DWORD, + usri2_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_MACHINE = *mut NET_DISPLAY_MACHINE; +STRUCT!{struct NET_DISPLAY_GROUP { + usri3_name: ::LPWSTR, + usri3_comment: ::LPWSTR, + grpi3_group_id: ::DWORD, + grpi3_attributes: ::DWORD, + grpi3_next_index: ::DWORD, +}} +pub type PNET_DISPLAY_GROUP = *mut NET_DISPLAY_GROUP; +STRUCT!{struct ACCESS_INFO_0 { + acc0_resource_name: ::LPWSTR, +}} +pub type PACCESS_INFO_0 = *mut ACCESS_INFO_0; +pub type LPACCESS_INFO_0 = *mut ACCESS_INFO_0; +STRUCT!{struct ACCESS_INFO_1 { + acc1_resource_name: ::LPWSTR, + acc1_attr: ::DWORD, + acc1_count: ::DWORD, +}} +pub type PACCESS_INFO_1 = *mut ACCESS_INFO_1; +pub type LPACCESS_INFO_1 = *mut ACCESS_INFO_1; +STRUCT!{struct ACCESS_INFO_1002 { + acc1002_attr: ::DWORD, +}} +pub type PACCESS_INFO_1002 = *mut ACCESS_INFO_1002; +pub type LPACCESS_INFO_1002 = *mut ACCESS_INFO_1002; +STRUCT!{struct ACCESS_LIST { + acl_ugname: ::LPWSTR, + acl_access: ::DWORD, +}} +pub type PACCESS_LIST = *mut ACCESS_LIST; +pub type LPACCESS_LIST = *mut ACCESS_LIST; +pub const ACCESS_NONE: ::DWORD = 0; +pub const ACCESS_ALL: ::DWORD = ACCESS_READ | ACCESS_WRITE | ACCESS_CREATE | ACCESS_EXEC + | ACCESS_DELETE | ACCESS_ATRIB | ACCESS_PERM; +pub const ACCESS_READ: ::DWORD = 0x01; +pub const ACCESS_WRITE: ::DWORD = 0x02; +pub const ACCESS_CREATE: ::DWORD = 0x04; +pub const ACCESS_EXEC: ::DWORD = 0x08; +pub const ACCESS_DELETE: ::DWORD = 0x10; +pub const ACCESS_ATRIB: ::DWORD = 0x20; +pub const ACCESS_PERM: ::DWORD = 0x40; +pub const ACCESS_GROUP: ::DWORD = 0x8000; +pub const ACCESS_AUDIT: ::DWORD = 0x1; +pub const ACCESS_SUCCESS_OPEN: ::DWORD = 0x10; +pub const ACCESS_SUCCESS_WRITE: ::DWORD = 0x20; +pub const ACCESS_SUCCESS_DELETE: ::DWORD = 0x40; +pub const ACCESS_SUCCESS_ACL: ::DWORD = 0x80; +pub const ACCESS_SUCCESS_MASK: ::DWORD = 0xF0; +pub const ACCESS_FAIL_OPEN: ::DWORD = 0x100; +pub const ACCESS_FAIL_WRITE: ::DWORD = 0x200; +pub const ACCESS_FAIL_DELETE: ::DWORD = 0x400; +pub const ACCESS_FAIL_ACL: ::DWORD = 0x800; +pub const ACCESS_FAIL_MASK: ::DWORD = 0xF00; +pub const ACCESS_FAIL_SHIFT: ::DWORD = 4; +pub const ACCESS_RESOURCE_NAME_PARMNUM: ::DWORD = 1; +pub const ACCESS_ATTR_PARMNUM: ::DWORD = 2; +pub const ACCESS_COUNT_PARMNUM: ::DWORD = 3; +pub const ACCESS_ACCESS_LIST_PARMNUM: ::DWORD = 4; +pub const ACCESS_RESOURCE_NAME_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + ACCESS_RESOURCE_NAME_PARMNUM; +pub const ACCESS_ATTR_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + ACCESS_ATTR_PARMNUM; +pub const ACCESS_COUNT_INFOLEVEL: ::DWORD = ::PARMNUM_BASE_INFOLEVEL + ACCESS_COUNT_PARMNUM; +pub const ACCESS_ACCESS_LIST_INFOLEVEL: ::DWORD = + ::PARMNUM_BASE_INFOLEVEL + ACCESS_ACCESS_LIST_PARMNUM; +ENUM!{enum NET_VALIDATE_PASSWORD_TYPE { + NetValidateAuthentication = 1, + NetValidatePasswordChange, + NetValidatePasswordReset, +}} +pub type PNET_VALIDATE_PASSWORD_TYPE = *mut NET_VALIDATE_PASSWORD_TYPE; +STRUCT!{struct NET_VALIDATE_PASSWORD_HASH { + Length: ::ULONG, + Hash: ::LPBYTE, +}} +pub type PNET_VALIDATE_PASSWORD_HASH = *mut NET_VALIDATE_PASSWORD_HASH; +pub const NET_VALIDATE_PASSWORD_LAST_SET: ::ULONG = 0x00000001; +pub const NET_VALIDATE_BAD_PASSWORD_TIME: ::ULONG = 0x00000002; +pub const NET_VALIDATE_LOCKOUT_TIME: ::ULONG = 0x00000004; +pub const NET_VALIDATE_BAD_PASSWORD_COUNT: ::ULONG = 0x00000008; +pub const NET_VALIDATE_PASSWORD_HISTORY_LENGTH: ::ULONG = 0x00000010; +pub const NET_VALIDATE_PASSWORD_HISTORY: ::ULONG = 0x00000020; +STRUCT!{struct NET_VALIDATE_PERSISTED_FIELDS { + PresentFields: ::ULONG, + PasswordLastSet: ::FILETIME, + BadPasswordTime: ::FILETIME, + LockoutTime: ::FILETIME, + BadPasswordCount: ::ULONG, + PasswordHistoryLength: ::ULONG, + PasswordHistory: PNET_VALIDATE_PASSWORD_HASH, +}} +pub type PNET_VALIDATE_PERSISTED_FIELDS = *mut NET_VALIDATE_PERSISTED_FIELDS; +STRUCT!{struct NET_VALIDATE_OUTPUT_ARG { + ChangedPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ValidationStatus: ::NET_API_STATUS, +}} +pub type PNET_VALIDATE_OUTPUT_ARG = *mut NET_VALIDATE_OUTPUT_ARG; +STRUCT!{struct NET_VALIDATE_AUTHENTICATION_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + PasswordMatched: ::BOOLEAN, +}} +pub type PNET_VALIDATE_AUTHENTICATION_INPUT_ARG = *mut NET_VALIDATE_AUTHENTICATION_INPUT_ARG; +STRUCT!{struct NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ClearPassword: ::LPWSTR, + UserAccountName: ::LPWSTR, + HashedPassword: NET_VALIDATE_PASSWORD_HASH, + PasswordMatch: ::BOOLEAN, +}} +pub type PNET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG = *mut NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG; +STRUCT!{struct NET_VALIDATE_PASSWORD_RESET_INPUT_ARG { + InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, + ClearPassword: ::LPWSTR, + UserAccountName: ::LPWSTR, + HashedPassword: NET_VALIDATE_PASSWORD_HASH, + PasswordMustChangeAtNextLogon: ::BOOLEAN, + ClearLockout: ::BOOLEAN, +}} +pub type PNET_VALIDATE_PASSWORD_RESET_INPUT_ARG = *mut NET_VALIDATE_PASSWORD_RESET_INPUT_ARG; +pub const NETLOGON_CONTROL_QUERY: ::DWORD = 1; +pub const NETLOGON_CONTROL_REPLICATE: ::DWORD = 2; +pub const NETLOGON_CONTROL_SYNCHRONIZE: ::DWORD = 3; +pub const NETLOGON_CONTROL_PDC_REPLICATE: ::DWORD = 4; +pub const NETLOGON_CONTROL_REDISCOVER: ::DWORD = 5; +pub const NETLOGON_CONTROL_TC_QUERY: ::DWORD = 6; +pub const NETLOGON_CONTROL_TRANSPORT_NOTIFY: ::DWORD = 7; +pub const NETLOGON_CONTROL_FIND_USER: ::DWORD = 8; +pub const NETLOGON_CONTROL_CHANGE_PASSWORD: ::DWORD = 9; +pub const NETLOGON_CONTROL_TC_VERIFY: ::DWORD = 10; +pub const NETLOGON_CONTROL_FORCE_DNS_REG: ::DWORD = 11; +pub const NETLOGON_CONTROL_QUERY_DNS_REG: ::DWORD = 12; +pub const NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL: ::DWORD = 0xFFFB; +pub const NETLOGON_CONTROL_BACKUP_CHANGE_LOG: ::DWORD = 0xFFFC; +pub const NETLOGON_CONTROL_TRUNCATE_LOG: ::DWORD = 0xFFFD; +pub const NETLOGON_CONTROL_SET_DBFLAG: ::DWORD = 0xFFFE; +pub const NETLOGON_CONTROL_BREAKPOINT: ::DWORD = 0xFFFF; +STRUCT!{struct NETLOGON_INFO_1 { + netlog1_flags: ::DWORD, + netlog1_pdc_connection_status: ::NET_API_STATUS, +}} +pub type PNETLOGON_INFO_1 = *mut NETLOGON_INFO_1; +STRUCT!{struct NETLOGON_INFO_2 { + netlog2_flags: ::DWORD, + netlog2_pdc_connection_status: ::NET_API_STATUS, + netlog2_trusted_dc_name: ::LPWSTR, + netlog2_tc_connection_status: ::NET_API_STATUS, +}} +pub type PNETLOGON_INFO_2 = *mut NETLOGON_INFO_2; +STRUCT!{struct NETLOGON_INFO_3 { + netlog3_flags: ::DWORD, + netlog3_logon_attempts: ::DWORD, + netlog3_reserved1: ::DWORD, + netlog3_reserved2: ::DWORD, + netlog3_reserved3: ::DWORD, + netlog3_reserved4: ::DWORD, + netlog3_reserved5: ::DWORD, +}} +pub type PNETLOGON_INFO_3 = *mut NETLOGON_INFO_3; +STRUCT!{struct NETLOGON_INFO_4 { + netlog4_trusted_dc_name: ::LPWSTR, + netlog4_trusted_domain_name: ::LPWSTR, +}} +pub type PNETLOGON_INFO_4 = *mut NETLOGON_INFO_4; +pub const NETLOGON_REPLICATION_NEEDED: ::DWORD = 0x01; +pub const NETLOGON_REPLICATION_IN_PROGRESS: ::DWORD = 0x02; +pub const NETLOGON_FULL_SYNC_REPLICATION: ::DWORD = 0x04; +pub const NETLOGON_REDO_NEEDED: ::DWORD = 0x08; +pub const NETLOGON_HAS_IP: ::DWORD = 0x10; +pub const NETLOGON_HAS_TIMESERV: ::DWORD = 0x20; +pub const NETLOGON_DNS_UPDATE_FAILURE: ::DWORD = 0x40; +pub const NETLOGON_VERIFY_STATUS_RETURNED: ::DWORD = 0x80; +DEFINE_GUID!(ServiceAccountPasswordGUID, 0x262E99C9, 0x6160, 0x4871, + 0xAC, 0xEC, 0x4E, 0x61, 0x73, 0x6B, 0x6F, 0x21); +pub const SERVICE_ACCOUNT_FLAG_LINK_TO_HOST_ONLY: ::DWORD = 0x00000001; +pub const SERVICE_ACCOUNT_FLAG_ADD_AGAINST_RODC: ::DWORD = 0x00000002; +pub const SERVICE_ACCOUNT_FLAG_UNLINK_FROM_HOST_ONLY: ::DWORD = 0x00000001; +pub const SERVICE_ACCOUNT_FLAG_REMOVE_OFFLINE: ::DWORD = 0x00000002; +ENUM!{enum MSA_INFO_LEVEL { + MsaInfoLevel0 = 0, + MsaInfoLevelMax, +}} +pub type PMSA_INFO_LEVEL = *mut MSA_INFO_LEVEL; +ENUM!{enum MSA_INFO_STATE { + MsaInfoNotExist = 1, + MsaInfoNotService, + MsaInfoCannotInstall, + MsaInfoCanInstall, + MsaInfoInstalled, +}} +pub type PMSA_INFO_STATE = *mut MSA_INFO_STATE; +STRUCT!{struct MSA_INFO_0 { + State: MSA_INFO_STATE, +}} +pub type PMSA_INFO_0 = *mut MSA_INFO_0; +pub type LPMSA_INFO_0 = *mut MSA_INFO_0; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lmcons.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lmcons.rs new file mode 100644 index 0000000..267db8b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lmcons.rs @@ -0,0 +1,55 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This file contains constants used throughout the LAN Manager API header files. +pub const CNLEN: ::DWORD = 15; +pub const LM20_CNLEN: ::DWORD = 15; +pub const DNLEN: ::DWORD = CNLEN; +pub const LM20_DNLEN: ::DWORD = LM20_CNLEN; +pub const UNCLEN: ::DWORD = CNLEN + 2; +pub const LM20_UNCLEN: ::DWORD = LM20_CNLEN + 2; +pub const NNLEN: ::DWORD = 80; +pub const LM20_NNLEN: ::DWORD = 12; +pub const RMLEN: ::DWORD = UNCLEN + 1 + NNLEN; +pub const LM20_RMLEN: ::DWORD = LM20_UNCLEN + 1 + LM20_NNLEN; +pub const SNLEN: ::DWORD = 80; +pub const LM20_SNLEN: ::DWORD = 15; +pub const STXTLEN: ::DWORD = 256; +pub const LM20_STXTLEN: ::DWORD = 63; +pub const PATHLEN: ::DWORD = 256; +pub const LM20_PATHLEN: ::DWORD = 256; +pub const DEVLEN: ::DWORD = 80; +pub const LM20_DEVLEN: ::DWORD = 8; +pub const EVLEN: ::DWORD = 16; +pub const UNLEN: ::DWORD = 256; +pub const LM20_UNLEN: ::DWORD = 20; +pub const GNLEN: ::DWORD = UNLEN; +pub const LM20_GNLEN: ::DWORD = LM20_UNLEN; +pub const PWLEN: ::DWORD = 256; +pub const LM20_PWLEN: ::DWORD = 14; +pub const SHPWLEN: ::DWORD = 8; +pub const CLTYPE_LEN: ::DWORD = 12; +pub const MAXCOMMENTSZ: ::DWORD = 256; +pub const LM20_MAXCOMMENTSZ: ::DWORD = 48; +pub const QNLEN: ::DWORD = NNLEN; +pub const LM20_QNLEN: ::DWORD = LM20_NNLEN; +pub const ALERTSZ: ::DWORD = 128; +pub const MAXDEVENTRIES: ::DWORD = 4 * 8; // FIXME: sizeof(int) instead of 4 +pub const NETBIOS_NAME_LEN: ::DWORD = 16; +pub const MAX_PREFERRED_LENGTH: ::DWORD = -1i32 as ::DWORD; +pub const CRYPT_KEY_LEN: ::DWORD = 7; +pub const CRYPT_TXT_LEN: ::DWORD = 8; +pub const ENCRYPTED_PWLEN: usize = 16; +pub const SESSION_PWLEN: ::DWORD = 24; +pub const SESSION_CRYPT_KLEN: ::DWORD = 21; +pub const PARM_ERROR_UNKNOWN: ::DWORD = -1i32 as ::DWORD; +pub const PARM_ERROR_NONE: ::DWORD = 0; +pub const PARMNUM_BASE_INFOLEVEL: ::DWORD = 1000; +pub type LMSTR = ::LPWSTR; +pub type LMCSTR = ::LPCWSTR; +pub type NET_API_STATUS = ::DWORD; +pub type API_RET_TYPE = NET_API_STATUS; +pub const PLATFORM_ID_DOS: ::DWORD = 300; +pub const PLATFORM_ID_OS2: ::DWORD = 400; +pub const PLATFORM_ID_NT: ::DWORD = 500; +pub const PLATFORM_ID_OSF: ::DWORD = 600; +pub const PLATFORM_ID_VMS: ::DWORD = 700; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lmdfs.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lmdfs.rs new file mode 100644 index 0000000..b74c647 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lmdfs.rs @@ -0,0 +1,311 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// This file contains structures, function prototypes, and definitions for the NetDfs API +pub const DFS_VOLUME_STATES: ::DWORD = 0xF; +pub const DFS_VOLUME_STATE_OK: ::DWORD = 1; +pub const DFS_VOLUME_STATE_INCONSISTENT: ::DWORD = 2; +pub const DFS_VOLUME_STATE_OFFLINE: ::DWORD = 3; +pub const DFS_VOLUME_STATE_ONLINE: ::DWORD = 4; +pub const DFS_VOLUME_STATE_RESYNCHRONIZE: ::DWORD = 0x10; +pub const DFS_VOLUME_STATE_STANDBY: ::DWORD = 0x20; +pub const DFS_VOLUME_STATE_FORCE_SYNC: ::DWORD = 0x40; +pub const DFS_VOLUME_FLAVORS: ::DWORD = 0x0300; +pub const DFS_VOLUME_FLAVOR_UNUSED1: ::DWORD = 0x0000; +pub const DFS_VOLUME_FLAVOR_STANDALONE: ::DWORD = 0x0100; +pub const DFS_VOLUME_FLAVOR_AD_BLOB: ::DWORD = 0x0200; +pub const DFS_STORAGE_FLAVOR_UNUSED2: ::DWORD = 0x0300; +pub const DFS_STORAGE_STATES: ::ULONG = 0xF; +pub const DFS_STORAGE_STATE_OFFLINE: ::ULONG = 1; +pub const DFS_STORAGE_STATE_ONLINE: ::ULONG = 2; +pub const DFS_STORAGE_STATE_ACTIVE: ::ULONG = 4; +ENUM!{enum DFS_TARGET_PRIORITY_CLASS { + DfsInvalidPriorityClass = -1i32 as u32, + DfsSiteCostNormalPriorityClass = 0, + DfsGlobalHighPriorityClass, + DfsSiteCostHighPriorityClass, + DfsSiteCostLowPriorityClass, + DfsGlobalLowPriorityClass, +}} +STRUCT!{struct DFS_TARGET_PRIORITY { + TargetPriorityClass: DFS_TARGET_PRIORITY_CLASS, + TargetPriorityRank: ::USHORT, + Reserved: ::USHORT, +}} +pub type PDFS_TARGET_PRIORITY = *mut DFS_TARGET_PRIORITY; +STRUCT!{struct DFS_INFO_1 { + EntryPath: ::LPWSTR, +}} +pub type PDFS_INFO_1 = *mut DFS_INFO_1; +pub type LPDFS_INFO_1 = *mut DFS_INFO_1; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_1_32 { + EntryPath: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_1_32 = *mut DFS_INFO_1_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_1_32 = *mut DFS_INFO_1_32; +STRUCT!{struct DFS_INFO_2 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_2 = *mut DFS_INFO_2; +pub type LPDFS_INFO_2 = *mut DFS_INFO_2; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_2_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + NumberOfStorages: ::DWORD, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_2_32 = *mut DFS_INFO_2_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_2_32 = *mut DFS_INFO_2_32; +STRUCT!{struct DFS_STORAGE_INFO { + State: ::ULONG, + ServerName: ::LPWSTR, + ShareName: ::LPWSTR, +}} +pub type PDFS_STORAGE_INFO = *mut DFS_STORAGE_INFO; +pub type LPDFS_STORAGE_INFO = *mut DFS_STORAGE_INFO; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_STORAGE_INFO_0_32 { + State: ::ULONG, + ServerName: ::ULONG, + ShareName: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_STORAGE_INFO_0_32 = *mut DFS_STORAGE_INFO_0_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_STORAGE_INFO_0_32 = *mut DFS_STORAGE_INFO_0_32; +STRUCT!{struct DFS_STORAGE_INFO_1 { + State: ::ULONG, + ServerName: ::LPWSTR, + ShareName: ::LPWSTR, + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_STORAGE_INFO_1 = *mut DFS_STORAGE_INFO_1; +pub type LPDFS_STORAGE_INFO_1 = *mut DFS_STORAGE_INFO_1; +STRUCT!{struct DFS_INFO_3 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_3 = *mut DFS_INFO_3; +pub type LPDFS_INFO_3 = *mut DFS_INFO_3; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_3_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + NumberOfStorages: ::DWORD, + Storage: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_3_32 = *mut DFS_INFO_3_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_3_32 = *mut DFS_INFO_3_32; +STRUCT!{struct DFS_INFO_4 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_4 = *mut DFS_INFO_4; +pub type LPDFS_INFO_4 = *mut DFS_INFO_4; +#[cfg(target_arch="x86_64")] STRUCT!{struct DFS_INFO_4_32 { + EntryPath: ::ULONG, + Comment: ::ULONG, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + NumberOfStorages: ::DWORD, + Storage: ::ULONG, +}} +#[cfg(target_arch="x86_64")] +pub type PDFS_INFO_4_32 = *mut DFS_INFO_4_32; +#[cfg(target_arch="x86_64")] +pub type LPDFS_INFO_4_32 = *mut DFS_INFO_4_32; +STRUCT!{struct DFS_INFO_5 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_5 = *mut DFS_INFO_5; +pub type LPDFS_INFO_5 = *mut DFS_INFO_5; +STRUCT!{struct DFS_INFO_6 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_6 = *mut DFS_INFO_6; +pub type LPDFS_INFO_6 = *mut DFS_INFO_6; +STRUCT!{struct DFS_INFO_7 { + GenerationGuid: ::GUID, +}} +pub type PDFS_INFO_7 = *mut DFS_INFO_7; +pub type LPDFS_INFO_7 = *mut DFS_INFO_7; +STRUCT!{struct DFS_INFO_8 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, + NumberOfStorages: ::DWORD, +}} +pub type PDFS_INFO_8 = *mut DFS_INFO_8; +pub type LPDFS_INFO_8 = *mut DFS_INFO_8; +STRUCT!{struct DFS_INFO_9 { + EntryPath: ::LPWSTR, + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + Guid: ::GUID, + PropertyFlags: ::ULONG, + MetadataSize: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, + NumberOfStorages: ::DWORD, + Storage: LPDFS_STORAGE_INFO, +}} +pub type PDFS_INFO_9 = *mut DFS_INFO_9; +pub type LPDFS_INFO_9 = *mut DFS_INFO_9; +pub const DFS_PROPERTY_FLAG_INSITE_REFERRALS: ::ULONG = 0x00000001; +pub const DFS_PROPERTY_FLAG_ROOT_SCALABILITY: ::ULONG = 0x00000002; +pub const DFS_PROPERTY_FLAG_SITE_COSTING: ::ULONG = 0x00000004; +pub const DFS_PROPERTY_FLAG_TARGET_FAILBACK: ::ULONG = 0x00000008; +pub const DFS_PROPERTY_FLAG_CLUSTER_ENABLED: ::ULONG = 0x00000010; +pub const DFS_PROPERTY_FLAG_ABDE: ::ULONG = 0x00000020; +pub const DFS_VALID_PROPERTY_FLAGS: ::ULONG = DFS_PROPERTY_FLAG_INSITE_REFERRALS + | DFS_PROPERTY_FLAG_ROOT_SCALABILITY | DFS_PROPERTY_FLAG_SITE_COSTING + | DFS_PROPERTY_FLAG_TARGET_FAILBACK | DFS_PROPERTY_FLAG_CLUSTER_ENABLED + | DFS_PROPERTY_FLAG_ABDE; +STRUCT!{struct DFS_INFO_50 { + NamespaceMajorVersion: ::ULONG, + NamespaceMinorVersion: ::ULONG, + NamespaceCapabilities: ::ULONGLONG, +}} +pub type PDFS_INFO_50 = *mut DFS_INFO_50; +pub type LPDFS_INFO_50 = *mut DFS_INFO_50; +STRUCT!{struct DFS_INFO_100 { + Comment: ::LPWSTR, +}} +pub type PDFS_INFO_100 = *mut DFS_INFO_100; +pub type LPDFS_INFO_100 = *mut DFS_INFO_100; +STRUCT!{struct DFS_INFO_101 { + State: ::DWORD, +}} +pub type PDFS_INFO_101 = *mut DFS_INFO_101; +pub type LPDFS_INFO_101 = *mut DFS_INFO_101; +STRUCT!{struct DFS_INFO_102 { + Timeout: ::ULONG, +}} +pub type PDFS_INFO_102 = *mut DFS_INFO_102; +pub type LPDFS_INFO_102 = *mut DFS_INFO_102; +STRUCT!{struct DFS_INFO_103 { + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, +}} +pub type PDFS_INFO_103 = *mut DFS_INFO_103; +pub type LPDFS_INFO_103 = *mut DFS_INFO_103; +STRUCT!{struct DFS_INFO_104 { + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_INFO_104 = *mut DFS_INFO_104; +pub type LPDFS_INFO_104 = *mut DFS_INFO_104; +STRUCT!{struct DFS_INFO_105 { + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, +}} +pub type PDFS_INFO_105 = *mut DFS_INFO_105; +pub type LPDFS_INFO_105 = *mut DFS_INFO_105; +STRUCT!{struct DFS_INFO_106 { + State: ::DWORD, + TargetPriority: DFS_TARGET_PRIORITY, +}} +pub type PDFS_INFO_106 = *mut DFS_INFO_106; +pub type LPDFS_INFO_106 = *mut DFS_INFO_106; +STRUCT!{struct DFS_INFO_107 { + Comment: ::LPWSTR, + State: ::DWORD, + Timeout: ::ULONG, + PropertyFlagMask: ::ULONG, + PropertyFlags: ::ULONG, + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PDFS_INFO_107 = *mut DFS_INFO_107; +pub type LPDFS_INFO_107 = *mut DFS_INFO_107; +STRUCT!{struct DFS_INFO_150 { + SdLengthReserved: ::ULONG, + pSecurityDescriptor: ::PSECURITY_DESCRIPTOR, +}} +pub type PDFS_INFO_150 = *mut DFS_INFO_150; +pub type LPDFS_INFO_150 = *mut DFS_INFO_150; +STRUCT!{struct DFS_INFO_200 { + FtDfsName: ::LPWSTR, +}} +pub type PDFS_INFO_200 = *mut DFS_INFO_200; +pub type LPDFS_INFO_200 = *mut DFS_INFO_200; +STRUCT!{struct DFS_INFO_300 { + Flags: ::DWORD, + DfsName: ::LPWSTR, +}} +pub type PDFS_INFO_300 = *mut DFS_INFO_300; +pub type LPDFS_INFO_300 = *mut DFS_INFO_300; +pub const DFS_ADD_VOLUME: ::DWORD = 1; +pub const DFS_RESTORE_VOLUME: ::DWORD = 2; +pub const NET_DFS_SETDC_FLAGS: ::DWORD = 0x00000000; +pub const NET_DFS_SETDC_TIMEOUT: ::DWORD = 0x00000001; +pub const NET_DFS_SETDC_INITPKT: ::DWORD = 0x00000002; +STRUCT!{struct DFS_SITENAME_INFO { + SiteFlags: ::ULONG, + SiteName: ::LPWSTR, +}} +pub type PDFS_SITENAME_INFO = *mut DFS_SITENAME_INFO; +pub type LPDFS_SITENAME_INFO = *mut DFS_SITENAME_INFO; +pub const DFS_SITE_PRIMARY: ::ULONG = 0x1; +STRUCT!{struct DFS_SITELIST_INFO { + cSites: ::ULONG, + Site: [DFS_SITENAME_INFO; 1], +}} +pub type PDFS_SITELIST_INFO = *mut DFS_SITELIST_INFO; +pub type LPDFS_SITELIST_INFO = *mut DFS_SITELIST_INFO; +ENUM!{enum DFS_NAMESPACE_VERSION_ORIGIN { + DFS_NAMESPACE_VERSION_ORIGIN_COMBINED = 0, + DFS_NAMESPACE_VERSION_ORIGIN_SERVER, + DFS_NAMESPACE_VERSION_ORIGIN_DOMAIN, +}} +pub type PDFS_NAMESPACE_VERSION_ORIGIN = *mut DFS_NAMESPACE_VERSION_ORIGIN; +pub const DFS_NAMESPACE_CAPABILITY_ABDE: ::ULONGLONG = 0x0000000000000001; +STRUCT!{struct DFS_SUPPORTED_NAMESPACE_VERSION_INFO { + DomainDfsMajorVersion: ::ULONG, + DomainDfsMinorVersion: ::ULONG, + DomainDfsCapabilities: ::ULONGLONG, + StandaloneDfsMajorVersion: ::ULONG, + StandaloneDfsMinorVersion: ::ULONG, + StandaloneDfsCapabilities: ::ULONGLONG, +}} +pub type PDFS_SUPPORTED_NAMESPACE_VERSION_INFO = *mut DFS_SUPPORTED_NAMESPACE_VERSION_INFO; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lmerrlog.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lmerrlog.rs new file mode 100644 index 0000000..ebbe3b0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lmerrlog.rs @@ -0,0 +1,263 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +STRUCT!{struct ERROR_LOG { + el_len: ::DWORD, + el_reserved: ::DWORD, + el_time: ::DWORD, + el_error: ::DWORD, + el_name: ::LPWSTR, + el_text: ::LPWSTR, + el_data: ::LPBYTE, + el_data_size: ::DWORD, + el_nstrings: ::DWORD, +}} +pub type PERROR_LOG = *mut ERROR_LOG; +pub type LPERROR_LOG = *mut ERROR_LOG; +STRUCT!{struct HLOG { + time: ::DWORD, + last_flags: ::DWORD, + offset: ::DWORD, + rec_offset: ::DWORD, +}} +pub type PHLOG = *mut HLOG; +pub type LPHLOG = *mut HLOG; +pub const LOGFLAGS_FORWARD: ::DWORD = 0; +pub const LOGFLAGS_BACKWARD: ::DWORD = 0x1; +pub const LOGFLAGS_SEEK: ::DWORD = 0x2; +pub const ERRLOG_BASE: ::DWORD = 3100; +pub const NELOG_Internal_Error: ::DWORD = ERRLOG_BASE + 0; +pub const NELOG_Resource_Shortage: ::DWORD = ERRLOG_BASE + 1; +pub const NELOG_Unable_To_Lock_Segment: ::DWORD = ERRLOG_BASE + 2; +pub const NELOG_Unable_To_Unlock_Segment: ::DWORD = ERRLOG_BASE + 3; +pub const NELOG_Uninstall_Service: ::DWORD = ERRLOG_BASE + 4; +pub const NELOG_Init_Exec_Fail: ::DWORD = ERRLOG_BASE + 5; +pub const NELOG_Ncb_Error: ::DWORD = ERRLOG_BASE + 6; +pub const NELOG_Net_Not_Started: ::DWORD = ERRLOG_BASE + 7; +pub const NELOG_Ioctl_Error: ::DWORD = ERRLOG_BASE + 8; +pub const NELOG_System_Semaphore: ::DWORD = ERRLOG_BASE + 9; +pub const NELOG_Init_OpenCreate_Err: ::DWORD = ERRLOG_BASE + 10; +pub const NELOG_NetBios: ::DWORD = ERRLOG_BASE + 11; +pub const NELOG_SMB_Illegal: ::DWORD = ERRLOG_BASE + 12; +pub const NELOG_Service_Fail: ::DWORD = ERRLOG_BASE + 13; +pub const NELOG_Entries_Lost: ::DWORD = ERRLOG_BASE + 14; +pub const NELOG_Init_Seg_Overflow: ::DWORD = ERRLOG_BASE + 20; +pub const NELOG_Srv_No_Mem_Grow: ::DWORD = ERRLOG_BASE + 21; +pub const NELOG_Access_File_Bad: ::DWORD = ERRLOG_BASE + 22; +pub const NELOG_Srvnet_Not_Started: ::DWORD = ERRLOG_BASE + 23; +pub const NELOG_Init_Chardev_Err: ::DWORD = ERRLOG_BASE + 24; +pub const NELOG_Remote_API: ::DWORD = ERRLOG_BASE + 25; +pub const NELOG_Ncb_TooManyErr: ::DWORD = ERRLOG_BASE + 26; +pub const NELOG_Mailslot_err: ::DWORD = ERRLOG_BASE + 27; +pub const NELOG_ReleaseMem_Alert: ::DWORD = ERRLOG_BASE + 28; +pub const NELOG_AT_cannot_write: ::DWORD = ERRLOG_BASE + 29; +pub const NELOG_Cant_Make_Msg_File: ::DWORD = ERRLOG_BASE + 30; +pub const NELOG_Exec_Netservr_NoMem: ::DWORD = ERRLOG_BASE + 31; +pub const NELOG_Server_Lock_Failure: ::DWORD = ERRLOG_BASE + 32; +pub const NELOG_Msg_Shutdown: ::DWORD = ERRLOG_BASE + 40; +pub const NELOG_Msg_Sem_Shutdown: ::DWORD = ERRLOG_BASE + 41; +pub const NELOG_Msg_Log_Err: ::DWORD = ERRLOG_BASE + 50; +pub const NELOG_VIO_POPUP_ERR: ::DWORD = ERRLOG_BASE + 51; +pub const NELOG_Msg_Unexpected_SMB_Type: ::DWORD = ERRLOG_BASE + 52; +pub const NELOG_Wksta_Infoseg: ::DWORD = ERRLOG_BASE + 60; +pub const NELOG_Wksta_Compname: ::DWORD = ERRLOG_BASE + 61; +pub const NELOG_Wksta_BiosThreadFailure: ::DWORD = ERRLOG_BASE + 62; +pub const NELOG_Wksta_IniSeg: ::DWORD = ERRLOG_BASE + 63; +pub const NELOG_Wksta_HostTab_Full: ::DWORD = ERRLOG_BASE + 64; +pub const NELOG_Wksta_Bad_Mailslot_SMB: ::DWORD = ERRLOG_BASE + 65; +pub const NELOG_Wksta_UASInit: ::DWORD = ERRLOG_BASE + 66; +pub const NELOG_Wksta_SSIRelogon: ::DWORD = ERRLOG_BASE + 67; +pub const NELOG_Build_Name: ::DWORD = ERRLOG_BASE + 70; +pub const NELOG_Name_Expansion: ::DWORD = ERRLOG_BASE + 71; +pub const NELOG_Message_Send: ::DWORD = ERRLOG_BASE + 72; +pub const NELOG_Mail_Slt_Err: ::DWORD = ERRLOG_BASE + 73; +pub const NELOG_AT_cannot_read: ::DWORD = ERRLOG_BASE + 74; +pub const NELOG_AT_sched_err: ::DWORD = ERRLOG_BASE + 75; +pub const NELOG_AT_schedule_file_created: ::DWORD = ERRLOG_BASE + 76; +pub const NELOG_Srvnet_NB_Open: ::DWORD = ERRLOG_BASE + 77; +pub const NELOG_AT_Exec_Err: ::DWORD = ERRLOG_BASE + 78; +pub const NELOG_Lazy_Write_Err: ::DWORD = ERRLOG_BASE + 80; +pub const NELOG_HotFix: ::DWORD = ERRLOG_BASE + 81; +pub const NELOG_HardErr_From_Server: ::DWORD = ERRLOG_BASE + 82; +pub const NELOG_LocalSecFail1: ::DWORD = ERRLOG_BASE + 83; +pub const NELOG_LocalSecFail2: ::DWORD = ERRLOG_BASE + 84; +pub const NELOG_LocalSecFail3: ::DWORD = ERRLOG_BASE + 85; +pub const NELOG_LocalSecGeneralFail: ::DWORD = ERRLOG_BASE + 86; +pub const NELOG_NetWkSta_Internal_Error: ::DWORD = ERRLOG_BASE + 90; +pub const NELOG_NetWkSta_No_Resource: ::DWORD = ERRLOG_BASE + 91; +pub const NELOG_NetWkSta_SMB_Err: ::DWORD = ERRLOG_BASE + 92; +pub const NELOG_NetWkSta_VC_Err: ::DWORD = ERRLOG_BASE + 93; +pub const NELOG_NetWkSta_Stuck_VC_Err: ::DWORD = ERRLOG_BASE + 94; +pub const NELOG_NetWkSta_NCB_Err: ::DWORD = ERRLOG_BASE + 95; +pub const NELOG_NetWkSta_Write_Behind_Err: ::DWORD = ERRLOG_BASE + 96; +pub const NELOG_NetWkSta_Reset_Err: ::DWORD = ERRLOG_BASE + 97; +pub const NELOG_NetWkSta_Too_Many: ::DWORD = ERRLOG_BASE + 98; +pub const NELOG_Srv_Thread_Failure: ::DWORD = ERRLOG_BASE + 104; +pub const NELOG_Srv_Close_Failure: ::DWORD = ERRLOG_BASE + 105; +pub const NELOG_ReplUserCurDir: ::DWORD = ERRLOG_BASE + 106; +pub const NELOG_ReplCannotMasterDir: ::DWORD = ERRLOG_BASE + 107; +pub const NELOG_ReplUpdateError: ::DWORD = ERRLOG_BASE + 108; +pub const NELOG_ReplLostMaster: ::DWORD = ERRLOG_BASE + 109; +pub const NELOG_NetlogonAuthDCFail: ::DWORD = ERRLOG_BASE + 110; +pub const NELOG_ReplLogonFailed: ::DWORD = ERRLOG_BASE + 111; +pub const NELOG_ReplNetErr: ::DWORD = ERRLOG_BASE + 112; +pub const NELOG_ReplMaxFiles: ::DWORD = ERRLOG_BASE + 113; +pub const NELOG_ReplMaxTreeDepth: ::DWORD = ERRLOG_BASE + 114; +pub const NELOG_ReplBadMsg: ::DWORD = ERRLOG_BASE + 115; +pub const NELOG_ReplSysErr: ::DWORD = ERRLOG_BASE + 116; +pub const NELOG_ReplUserLoged: ::DWORD = ERRLOG_BASE + 117; +pub const NELOG_ReplBadImport: ::DWORD = ERRLOG_BASE + 118; +pub const NELOG_ReplBadExport: ::DWORD = ERRLOG_BASE + 119; +pub const NELOG_ReplSignalFileErr: ::DWORD = ERRLOG_BASE + 120; +pub const NELOG_DiskFT: ::DWORD = ERRLOG_BASE + 121; +pub const NELOG_ReplAccessDenied: ::DWORD = ERRLOG_BASE + 122; +pub const NELOG_NetlogonFailedPrimary: ::DWORD = ERRLOG_BASE + 123; +pub const NELOG_NetlogonPasswdSetFailed: ::DWORD = ERRLOG_BASE + 124; +pub const NELOG_NetlogonTrackingError: ::DWORD = ERRLOG_BASE + 125; +pub const NELOG_NetlogonSyncError: ::DWORD = ERRLOG_BASE + 126; +pub const NELOG_NetlogonRequireSignOrSealError: ::DWORD = ERRLOG_BASE + 127; +pub const NELOG_UPS_PowerOut: ::DWORD = ERRLOG_BASE + 130; +pub const NELOG_UPS_Shutdown: ::DWORD = ERRLOG_BASE + 131; +pub const NELOG_UPS_CmdFileError: ::DWORD = ERRLOG_BASE + 132; +pub const NELOG_UPS_CannotOpenDriver: ::DWORD = ERRLOG_BASE+133; +pub const NELOG_UPS_PowerBack: ::DWORD = ERRLOG_BASE + 134; +pub const NELOG_UPS_CmdFileConfig: ::DWORD = ERRLOG_BASE + 135; +pub const NELOG_UPS_CmdFileExec: ::DWORD = ERRLOG_BASE + 136; +pub const NELOG_Missing_Parameter: ::DWORD = ERRLOG_BASE + 150; +pub const NELOG_Invalid_Config_Line: ::DWORD = ERRLOG_BASE + 151; +pub const NELOG_Invalid_Config_File: ::DWORD = ERRLOG_BASE + 152; +pub const NELOG_File_Changed: ::DWORD = ERRLOG_BASE + 153; +pub const NELOG_Files_Dont_Fit: ::DWORD = ERRLOG_BASE + 154; +pub const NELOG_Wrong_DLL_Version: ::DWORD = ERRLOG_BASE + 155; +pub const NELOG_Error_in_DLL: ::DWORD = ERRLOG_BASE + 156; +pub const NELOG_System_Error: ::DWORD = ERRLOG_BASE + 157; +pub const NELOG_FT_ErrLog_Too_Large: ::DWORD = ERRLOG_BASE + 158; +pub const NELOG_FT_Update_In_Progress: ::DWORD = ERRLOG_BASE + 159; +pub const NELOG_Joined_Domain: ::DWORD = ERRLOG_BASE + 160; +pub const NELOG_Joined_Workgroup: ::DWORD = ERRLOG_BASE + 161; +pub const NELOG_OEM_Code: ::DWORD = ERRLOG_BASE + 199; +pub const ERRLOG2_BASE: ::DWORD = 5700; +pub const NELOG_NetlogonSSIInitError: ::DWORD = ERRLOG2_BASE + 0; +pub const NELOG_NetlogonFailedToUpdateTrustList: ::DWORD = ERRLOG2_BASE + 1; +pub const NELOG_NetlogonFailedToAddRpcInterface: ::DWORD = ERRLOG2_BASE + 2; +pub const NELOG_NetlogonFailedToReadMailslot: ::DWORD = ERRLOG2_BASE + 3; +pub const NELOG_NetlogonFailedToRegisterSC: ::DWORD = ERRLOG2_BASE + 4; +pub const NELOG_NetlogonChangeLogCorrupt: ::DWORD = ERRLOG2_BASE + 5; +pub const NELOG_NetlogonFailedToCreateShare: ::DWORD = ERRLOG2_BASE + 6; +pub const NELOG_NetlogonDownLevelLogonFailed: ::DWORD = ERRLOG2_BASE + 7; +pub const NELOG_NetlogonDownLevelLogoffFailed: ::DWORD = ERRLOG2_BASE + 8; +pub const NELOG_NetlogonNTLogonFailed: ::DWORD = ERRLOG2_BASE + 9; +pub const NELOG_NetlogonNTLogoffFailed: ::DWORD = ERRLOG2_BASE + 10; +pub const NELOG_NetlogonPartialSyncCallSuccess: ::DWORD = ERRLOG2_BASE + 11; +pub const NELOG_NetlogonPartialSyncCallFailed: ::DWORD = ERRLOG2_BASE + 12; +pub const NELOG_NetlogonFullSyncCallSuccess: ::DWORD = ERRLOG2_BASE + 13; +pub const NELOG_NetlogonFullSyncCallFailed: ::DWORD = ERRLOG2_BASE + 14; +pub const NELOG_NetlogonPartialSyncSuccess: ::DWORD = ERRLOG2_BASE + 15; +pub const NELOG_NetlogonPartialSyncFailed: ::DWORD = ERRLOG2_BASE + 16; +pub const NELOG_NetlogonFullSyncSuccess: ::DWORD = ERRLOG2_BASE + 17; +pub const NELOG_NetlogonFullSyncFailed: ::DWORD = ERRLOG2_BASE + 18; +pub const NELOG_NetlogonAuthNoDomainController: ::DWORD = ERRLOG2_BASE + 19; +pub const NELOG_NetlogonAuthNoTrustLsaSecret: ::DWORD = ERRLOG2_BASE + 20; +pub const NELOG_NetlogonAuthNoTrustSamAccount: ::DWORD = ERRLOG2_BASE + 21; +pub const NELOG_NetlogonServerAuthFailed: ::DWORD = ERRLOG2_BASE + 22; +pub const NELOG_NetlogonServerAuthNoTrustSamAccount: ::DWORD = ERRLOG2_BASE + 23; +pub const NELOG_FailedToRegisterSC: ::DWORD = ERRLOG2_BASE + 24; +pub const NELOG_FailedToSetServiceStatus: ::DWORD = ERRLOG2_BASE + 25; +pub const NELOG_FailedToGetComputerName: ::DWORD = ERRLOG2_BASE + 26; +pub const NELOG_DriverNotLoaded: ::DWORD = ERRLOG2_BASE + 27; +pub const NELOG_NoTranportLoaded: ::DWORD = ERRLOG2_BASE + 28; +pub const NELOG_NetlogonFailedDomainDelta: ::DWORD = ERRLOG2_BASE + 29; +pub const NELOG_NetlogonFailedGlobalGroupDelta: ::DWORD = ERRLOG2_BASE + 30; +pub const NELOG_NetlogonFailedLocalGroupDelta: ::DWORD = ERRLOG2_BASE + 31; +pub const NELOG_NetlogonFailedUserDelta: ::DWORD = ERRLOG2_BASE + 32; +pub const NELOG_NetlogonFailedPolicyDelta: ::DWORD = ERRLOG2_BASE + 33; +pub const NELOG_NetlogonFailedTrustedDomainDelta: ::DWORD = ERRLOG2_BASE + 34; +pub const NELOG_NetlogonFailedAccountDelta: ::DWORD = ERRLOG2_BASE + 35; +pub const NELOG_NetlogonFailedSecretDelta: ::DWORD = ERRLOG2_BASE + 36; +pub const NELOG_NetlogonSystemError: ::DWORD = ERRLOG2_BASE + 37; +pub const NELOG_NetlogonDuplicateMachineAccounts: ::DWORD = ERRLOG2_BASE + 38; +pub const NELOG_NetlogonTooManyGlobalGroups: ::DWORD = ERRLOG2_BASE + 39; +pub const NELOG_NetlogonBrowserDriver: ::DWORD = ERRLOG2_BASE + 40; +pub const NELOG_NetlogonAddNameFailure: ::DWORD = ERRLOG2_BASE + 41; +pub const NELOG_RplMessages: ::DWORD = ERRLOG2_BASE + 42; +pub const NELOG_RplXnsBoot: ::DWORD = ERRLOG2_BASE + 43; +pub const NELOG_RplSystem: ::DWORD = ERRLOG2_BASE + 44; +pub const NELOG_RplWkstaTimeout: ::DWORD = ERRLOG2_BASE + 45; +pub const NELOG_RplWkstaFileOpen: ::DWORD = ERRLOG2_BASE + 46; +pub const NELOG_RplWkstaFileRead: ::DWORD = ERRLOG2_BASE + 47; +pub const NELOG_RplWkstaMemory: ::DWORD = ERRLOG2_BASE + 48; +pub const NELOG_RplWkstaFileChecksum: ::DWORD = ERRLOG2_BASE + 49; +pub const NELOG_RplWkstaFileLineCount: ::DWORD = ERRLOG2_BASE + 50; +pub const NELOG_RplWkstaBbcFile: ::DWORD = ERRLOG2_BASE + 51; +pub const NELOG_RplWkstaFileSize: ::DWORD = ERRLOG2_BASE + 52; +pub const NELOG_RplWkstaInternal: ::DWORD = ERRLOG2_BASE + 53; +pub const NELOG_RplWkstaWrongVersion: ::DWORD = ERRLOG2_BASE + 54; +pub const NELOG_RplWkstaNetwork: ::DWORD = ERRLOG2_BASE + 55; +pub const NELOG_RplAdapterResource: ::DWORD = ERRLOG2_BASE + 56; +pub const NELOG_RplFileCopy: ::DWORD = ERRLOG2_BASE + 57; +pub const NELOG_RplFileDelete: ::DWORD = ERRLOG2_BASE + 58; +pub const NELOG_RplFilePerms: ::DWORD = ERRLOG2_BASE + 59; +pub const NELOG_RplCheckConfigs: ::DWORD = ERRLOG2_BASE + 60; +pub const NELOG_RplCreateProfiles: ::DWORD = ERRLOG2_BASE + 61; +pub const NELOG_RplRegistry: ::DWORD = ERRLOG2_BASE + 62; +pub const NELOG_RplReplaceRPLDISK: ::DWORD = ERRLOG2_BASE + 63; +pub const NELOG_RplCheckSecurity: ::DWORD = ERRLOG2_BASE + 64; +pub const NELOG_RplBackupDatabase: ::DWORD = ERRLOG2_BASE + 65; +pub const NELOG_RplInitDatabase: ::DWORD = ERRLOG2_BASE + 66; +pub const NELOG_RplRestoreDatabaseFailure: ::DWORD = ERRLOG2_BASE + 67; +pub const NELOG_RplRestoreDatabaseSuccess: ::DWORD = ERRLOG2_BASE + 68; +pub const NELOG_RplInitRestoredDatabase: ::DWORD = ERRLOG2_BASE + 69; +pub const NELOG_NetlogonSessionTypeWrong: ::DWORD = ERRLOG2_BASE + 70; +pub const NELOG_RplUpgradeDBTo40: ::DWORD = ERRLOG2_BASE + 71; +pub const NELOG_NetlogonLanmanBdcsNotAllowed: ::DWORD = ERRLOG2_BASE + 72; +pub const NELOG_NetlogonNoDynamicDns: ::DWORD = ERRLOG2_BASE + 73; +pub const NELOG_NetlogonDynamicDnsRegisterFailure: ::DWORD = ERRLOG2_BASE + 74; +pub const NELOG_NetlogonDynamicDnsDeregisterFailure: ::DWORD = ERRLOG2_BASE + 75; +pub const NELOG_NetlogonFailedFileCreate: ::DWORD = ERRLOG2_BASE + 76; +pub const NELOG_NetlogonGetSubnetToSite: ::DWORD = ERRLOG2_BASE + 77; +pub const NELOG_NetlogonNoSiteForClient: ::DWORD = ERRLOG2_BASE + 78; +pub const NELOG_NetlogonBadSiteName: ::DWORD = ERRLOG2_BASE + 79; +pub const NELOG_NetlogonBadSubnetName: ::DWORD = ERRLOG2_BASE + 80; +pub const NELOG_NetlogonDynamicDnsServerFailure: ::DWORD = ERRLOG2_BASE + 81; +pub const NELOG_NetlogonDynamicDnsFailure: ::DWORD = ERRLOG2_BASE + 82; +pub const NELOG_NetlogonRpcCallCancelled: ::DWORD = ERRLOG2_BASE + 83; +pub const NELOG_NetlogonDcSiteCovered: ::DWORD = ERRLOG2_BASE + 84; +pub const NELOG_NetlogonDcSiteNotCovered: ::DWORD = ERRLOG2_BASE + 85; +pub const NELOG_NetlogonGcSiteCovered: ::DWORD = ERRLOG2_BASE + 86; +pub const NELOG_NetlogonGcSiteNotCovered: ::DWORD = ERRLOG2_BASE + 87; +pub const NELOG_NetlogonFailedSpnUpdate: ::DWORD = ERRLOG2_BASE + 88; +pub const NELOG_NetlogonFailedDnsHostNameUpdate: ::DWORD = ERRLOG2_BASE + 89; +pub const NELOG_NetlogonAuthNoUplevelDomainController: ::DWORD = ERRLOG2_BASE + 90; +pub const NELOG_NetlogonAuthDomainDowngraded: ::DWORD = ERRLOG2_BASE + 91; +pub const NELOG_NetlogonNdncSiteCovered: ::DWORD = ERRLOG2_BASE + 92; +pub const NELOG_NetlogonNdncSiteNotCovered: ::DWORD = ERRLOG2_BASE + 93; +pub const NELOG_NetlogonDcOldSiteCovered: ::DWORD = ERRLOG2_BASE + 94; +pub const NELOG_NetlogonDcSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 95; +pub const NELOG_NetlogonGcOldSiteCovered: ::DWORD = ERRLOG2_BASE + 96; +pub const NELOG_NetlogonGcSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 97; +pub const NELOG_NetlogonNdncOldSiteCovered: ::DWORD = ERRLOG2_BASE + 98; +pub const NELOG_NetlogonNdncSiteNotCoveredAuto: ::DWORD = ERRLOG2_BASE + 99; +pub const NELOG_NetlogonSpnMultipleSamAccountNames: ::DWORD = ERRLOG2_BASE + 100; +pub const NELOG_NetlogonSpnCrackNamesFailure: ::DWORD = ERRLOG2_BASE + 101; +pub const NELOG_NetlogonNoAddressToSiteMapping: ::DWORD = ERRLOG2_BASE + 102; +pub const NELOG_NetlogonInvalidGenericParameterValue: ::DWORD = ERRLOG2_BASE + 103; +pub const NELOG_NetlogonInvalidDwordParameterValue: ::DWORD = ERRLOG2_BASE + 104; +pub const NELOG_NetlogonServerAuthFailedNoAccount: ::DWORD = ERRLOG2_BASE + 105; +pub const NELOG_NetlogonNoDynamicDnsManual: ::DWORD = ERRLOG2_BASE + 106; +pub const NELOG_NetlogonNoSiteForClients: ::DWORD = ERRLOG2_BASE + 107; +pub const NELOG_NetlogonDnsDeregAborted: ::DWORD = ERRLOG2_BASE + 108; +pub const NELOG_NetlogonRpcPortRequestFailure: ::DWORD = ERRLOG2_BASE + 109; +pub const NELOG_NetlogonPartialSiteMappingForClients: ::DWORD = ERRLOG2_BASE + 110; +pub const NELOG_NetlogonRemoteDynamicDnsRegisterFailure: ::DWORD = ERRLOG2_BASE + 111; +pub const NELOG_NetlogonRemoteDynamicDnsDeregisterFailure: ::DWORD = ERRLOG2_BASE + 112; +pub const NELOG_NetlogonRejectedRemoteDynamicDnsRegister: ::DWORD = ERRLOG2_BASE + 113; +pub const NELOG_NetlogonRejectedRemoteDynamicDnsDeregister: ::DWORD = ERRLOG2_BASE + 114; +pub const NELOG_NetlogonRemoteDynamicDnsUpdateRequestFailure: ::DWORD = ERRLOG2_BASE + 115; +pub const NELOG_NetlogonUserValidationReqInitialTimeOut: ::DWORD = ERRLOG2_BASE + 116; +pub const NELOG_NetlogonUserValidationReqRecurringTimeOut: ::DWORD = ERRLOG2_BASE + 117; +pub const NELOG_NetlogonUserValidationReqWaitInitialWarning: ::DWORD = ERRLOG2_BASE + 118; +pub const NELOG_NetlogonUserValidationReqWaitRecurringWarning: ::DWORD = ERRLOG2_BASE + 119; +pub const NELOG_NetlogonFailedToAddAuthzRpcInterface: ::DWORD = ERRLOG2_BASE + 120; +pub const NELOG_NetLogonFailedToInitializeAuthzRm: ::DWORD = ERRLOG2_BASE + 121; +pub const NELOG_NetLogonFailedToInitializeRPCSD: ::DWORD = ERRLOG2_BASE + 122; +pub const NELOG_NetlogonMachinePasswdSetSucceeded: ::DWORD = ERRLOG2_BASE + 123; +pub const NELOG_NetlogonMsaPasswdSetSucceeded: ::DWORD = ERRLOG2_BASE + 124; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lmjoin.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lmjoin.rs new file mode 100644 index 0000000..12b8a10 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lmjoin.rs @@ -0,0 +1,80 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// Definitions and prototypes for the Net setup apis +ENUM!{enum NETSETUP_NAME_TYPE { + NetSetupUnknown = 0, + NetSetupMachine, + NetSetupWorkgroup, + NetSetupDomain, + NetSetupNonExistentDomain, + NetSetupDnsMachine, +}} +pub type PNETSETUP_NAME_TYPE = *mut NETSETUP_NAME_TYPE; +ENUM!{enum NETSETUP_JOIN_STATUS { + NetSetupUnknownStatus = 0, + NetSetupUnjoined, + NetSetupWorkgroupName, + NetSetupDomainName, +}} +pub type PNETSETUP_JOIN_STATUS = *mut NETSETUP_JOIN_STATUS; +pub const NETSETUP_JOIN_DOMAIN: ::DWORD = 0x00000001; +pub const NETSETUP_ACCT_CREATE: ::DWORD = 0x00000002; +pub const NETSETUP_ACCT_DELETE: ::DWORD = 0x00000004; +pub const NETSETUP_WIN9X_UPGRADE: ::DWORD = 0x00000010; +pub const NETSETUP_DOMAIN_JOIN_IF_JOINED: ::DWORD = 0x00000020; +pub const NETSETUP_JOIN_UNSECURE: ::DWORD = 0x00000040; +pub const NETSETUP_MACHINE_PWD_PASSED: ::DWORD = 0x00000080; +pub const NETSETUP_DEFER_SPN_SET: ::DWORD = 0x00000100; +pub const NETSETUP_JOIN_DC_ACCOUNT: ::DWORD = 0x00000200; +pub const NETSETUP_JOIN_WITH_NEW_NAME: ::DWORD = 0x00000400; +pub const NETSETUP_JOIN_READONLY: ::DWORD = 0x00000800; +pub const NETSETUP_DNS_NAME_CHANGES_ONLY: ::DWORD = 0x00001000; +pub const NETSETUP_INSTALL_INVOCATION: ::DWORD = 0x00040000; +pub const NETSETUP_AMBIGUOUS_DC: ::DWORD = 0x00001000; +pub const NETSETUP_NO_NETLOGON_CACHE: ::DWORD = 0x00002000; +pub const NETSETUP_DONT_CONTROL_SERVICES: ::DWORD = 0x00004000; +pub const NETSETUP_SET_MACHINE_NAME: ::DWORD = 0x00008000; +pub const NETSETUP_FORCE_SPN_SET: ::DWORD = 0x00010000; +pub const NETSETUP_NO_ACCT_REUSE: ::DWORD = 0x00020000; +pub const NETSETUP_ALT_SAMACCOUNTNAME: ::DWORD = 0x00020000; +pub const NETSETUP_IGNORE_UNSUPPORTED_FLAGS: ::DWORD = 0x10000000; +pub const NETSETUP_VALID_UNJOIN_FLAGS: ::DWORD = NETSETUP_ACCT_DELETE + | NETSETUP_IGNORE_UNSUPPORTED_FLAGS | NETSETUP_JOIN_DC_ACCOUNT; +pub const NETSETUP_PROCESS_OFFLINE_FLAGS: ::DWORD = NETSETUP_JOIN_DOMAIN + | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_WITH_NEW_NAME | NETSETUP_DONT_CONTROL_SERVICES + | NETSETUP_MACHINE_PWD_PASSED; +pub const NETSETUP_PROVISION_DOWNLEVEL_PRIV_SUPPORT: ::DWORD = 0x00000001; +pub const NETSETUP_PROVISION_REUSE_ACCOUNT: ::DWORD = 0x00000002; +pub const NETSETUP_PROVISION_USE_DEFAULT_PASSWORD: ::DWORD = 0x00000004; +pub const NETSETUP_PROVISION_SKIP_ACCOUNT_SEARCH: ::DWORD = 0x00000008; +pub const NETSETUP_PROVISION_ROOT_CA_CERTS: ::DWORD = 0x00000010; +pub const NETSETUP_PROVISION_PERSISTENTSITE: ::DWORD = 0x00000020; +pub const NETSETUP_PROVISION_ONLINE_CALLER: ::DWORD = 0x40000000; +pub const NETSETUP_PROVISION_CHECK_PWD_ONLY: ::DWORD = 0x80000000; +pub const NETSETUP_PROVISIONING_PARAMS_WIN8_VERSION: ::DWORD = 0x00000001; +pub const NETSETUP_PROVISIONING_PARAMS_CURRENT_VERSION: ::DWORD = 0x00000002; +STRUCT!{struct NETSETUP_PROVISIONING_PARAMS { + dwVersion: ::DWORD, + lpDomain: ::LPCWSTR, + lpHostName: ::LPCWSTR, + lpMachineAccountOU: ::LPCWSTR, + lpDcName: ::LPCWSTR, + dwProvisionOptions: ::DWORD, + aCertTemplateNames: *mut ::LPCWSTR, + cCertTemplateNames: ::DWORD, + aMachinePolicyNames: *mut ::LPCWSTR, + cMachinePolicyNames: ::DWORD, + aMachinePolicyPaths: *mut ::LPCWSTR, + cMachinePolicyPaths: ::DWORD, + lpNetbiosName: ::LPWSTR, + lpSiteName: ::LPWSTR, + lpPrimaryDNSDomain: ::LPWSTR, +}} +pub type PNETSETUP_PROVISIONING_PARAMS = *mut NETSETUP_PROVISIONING_PARAMS; +ENUM!{enum NET_COMPUTER_NAME_TYPE { + NetPrimaryComputerName, + NetAlternateComputerNames, + NetAllComputerNames, + NetComputerNameTypeMax, +}} +pub type PNET_COMPUTER_NAME_TYPE = *mut NET_COMPUTER_NAME_TYPE; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/lsalookup.rs b/third_party/cargo/vendor/winapi-0.2.8/src/lsalookup.rs new file mode 100644 index 0000000..039d72a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/lsalookup.rs @@ -0,0 +1,69 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! LSA Policy Lookup API +STRUCT!{struct LSA_UNICODE_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PWSTR, +}} +pub type PLSA_UNICODE_STRING = *mut LSA_UNICODE_STRING; +STRUCT!{struct LSA_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PCHAR, +}} +pub type PLSA_STRING = *mut LSA_STRING; +STRUCT!{struct LSA_OBJECT_ATTRIBUTES { + Length: ::ULONG, + RootDirectory: ::HANDLE, + ObjectName: PLSA_UNICODE_STRING, + Attributes: ::ULONG, + SecurityDescriptor: ::PVOID, + SecurityQualityOfService: ::PVOID, +}} +pub type PLSA_OBJECT_ATTRIBUTES = *mut LSA_OBJECT_ATTRIBUTES; +STRUCT!{struct LSA_TRUST_INFORMATION { + Name: LSA_UNICODE_STRING, + Sid: ::PSID, +}} +pub type PLSA_TRUST_INFORMATION = *mut LSA_TRUST_INFORMATION; +STRUCT!{struct LSA_REFERENCED_DOMAIN_LIST { + Entries: ::ULONG, + Domains: PLSA_TRUST_INFORMATION, +}} +pub type PLSA_REFERENCED_DOMAIN_LIST = *mut LSA_REFERENCED_DOMAIN_LIST; +STRUCT!{struct LSA_TRANSLATED_SID2 { + Use: ::SID_NAME_USE, + Sid: ::PSID, + DomainIndex: ::LONG, + Flags: ::ULONG, +}} +pub type PLSA_TRANSLATED_SID2 = *mut LSA_TRANSLATED_SID2; +STRUCT!{struct LSA_TRANSLATED_NAME { + Use: ::SID_NAME_USE, + Name: LSA_UNICODE_STRING, + DomainIndex: ::LONG, +}} +pub type PLSA_TRANSLATED_NAME = *mut LSA_TRANSLATED_NAME; +STRUCT!{struct POLICY_ACCOUNT_DOMAIN_INFO { + DomainName: LSA_UNICODE_STRING, + DomainSid: ::PSID, +}} +pub type PPOLICY_ACCOUNT_DOMAIN_INFO = *mut POLICY_ACCOUNT_DOMAIN_INFO; +STRUCT!{struct POLICY_DNS_DOMAIN_INFO { + Name: LSA_UNICODE_STRING, + DnsDomainName: LSA_UNICODE_STRING, + DnsForestName: LSA_UNICODE_STRING, + DomainGuid: ::GUID, + Sid: ::PSID, +}} +pub type PPOLICY_DNS_DOMAIN_INFO = *mut POLICY_DNS_DOMAIN_INFO; +pub const LOOKUP_VIEW_LOCAL_INFORMATION: ::ACCESS_MASK = 0x00000001; +pub const LOOKUP_TRANSLATE_NAMES: ::ACCESS_MASK = 0x00000800; +ENUM!{enum LSA_LOOKUP_DOMAIN_INFO_CLASS { + AccountDomainInformation = 5, + DnsDomainInformation = 12, +}} +pub type PLSA_LOOKUP_DOMAIN_INFO_CLASS = *mut LSA_LOOKUP_DOMAIN_INFO_CLASS; +pub type LSA_LOOKUP_HANDLE = ::PVOID; +pub type PLSA_LOOKUP_HANDLE = *mut ::PVOID; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/macros.rs b/third_party/cargo/vendor/winapi-0.2.8/src/macros.rs new file mode 100644 index 0000000..0bbd6aa --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/macros.rs @@ -0,0 +1,270 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Macros to make things easier to define +macro_rules! DECLARE_HANDLE { + ($name:ident, $inner:ident) => { + #[allow(missing_copy_implementations)] pub enum $inner { } + pub type $name = *mut $inner; + }; +} +macro_rules! MAKE_HRESULT { + ($sev:expr, $fac:expr, $code:expr) => { + ($sev << 31) | ($fac << 16) | $code + } +} +macro_rules! MAKE_SCODE { + ($sev:expr, $fac:expr, $code:expr) => { + ($sev << 31) | ($fac << 16) | $code + } +} +macro_rules! HIDP_ERROR_CODES { + ($sev:expr, $code:expr) => { + ($sev << 28) | (::FACILITY_HID_ERROR_CODE << 16) | $code + } +} +macro_rules! MAKEFOURCC { + ($a:expr, $b:expr, $c:expr, $d:expr) => { + ($a as i32) | (($b as i32) << 8) | (($c as i32) << 16) | (($d as i32) << 24) + } +} +#[macro_export] +macro_rules! DEFINE_GUID { + ( + $name:ident, $l:expr, $w1:expr, $w2:expr, $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, + $b6:expr, $b7:expr, $b8:expr + ) => { + pub const $name: $crate::GUID = $crate::GUID { + Data1: $l, + Data2: $w1, + Data3: $w2, + Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + }; + } +} +macro_rules! CTL_CODE { + ($DeviceType:expr, $Function:expr, $Method:expr, $Access:expr) => { + ($DeviceType << 16) | ($Access << 14) | ($Function << 2) | $Method + } +} +macro_rules! HID_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_NEITHER, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_BUFFER_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_BUFFERED, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_IN_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_IN_DIRECT, ::FILE_ANY_ACCESS) + } +} +macro_rules! HID_OUT_CTL_CODE { + ($id:expr) => { + CTL_CODE!(::FILE_DEVICE_KEYBOARD, $id, ::METHOD_OUT_DIRECT, ::FILE_ANY_ACCESS) + } +} +macro_rules! AUDCLNT_ERR { + ($n:expr) => { + MAKE_HRESULT!(::SEVERITY_ERROR, ::FACILITY_AUDCLNT, $n) + }; +} +macro_rules! AUDCLNT_SUCCESS { + ($n:expr) => { + MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_AUDCLNT, $n) + }; +} +macro_rules! BCRYPT_MAKE_INTERFACE_VERSION { + ($major:expr, $minor:expr) => { + ::BCRYPT_INTERFACE_VERSION { MajorVersion: $major, MinorVersion: $minor } + } +} +#[macro_export] +macro_rules! RIDL { + (interface $interface:ident ($vtbl:ident) + {$( + fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty + ),+} + ) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + $(pub $method: unsafe extern "system" fn( + This: *mut $interface + $(,$p: $t)* + ) -> $rtr),+ + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl $interface { + #[inline] + $(pub unsafe fn $method(&mut self $(,$p: $t)*) -> $rtr { + ((*self.lpVtbl).$method)(self $(,$p)*) + })+ + } + }; + (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) { + }) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + pub parent: $crate::$pvtbl + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl ::std::ops::Deref for $interface { + type Target = $crate::$pinterface; + #[inline] + fn deref(&self) -> &$crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + impl ::std::ops::DerefMut for $interface { + #[inline] + fn deref_mut(&mut self) -> &mut $crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + }; + (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) + {$( + fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty + ),+} + ) => { + #[repr(C)] #[allow(missing_copy_implementations)] + pub struct $vtbl { + pub parent: $crate::$pvtbl + $(,pub $method: unsafe extern "system" fn( + This: *mut $interface + $(,$p: $t)* + ) -> $rtr)+ + } + #[repr(C)] #[derive(Debug)] #[allow(missing_copy_implementations)] + pub struct $interface { + pub lpVtbl: *const $vtbl + } + impl $interface { + #[inline] + $(pub unsafe fn $method(&mut self $(,$p: $t)*) -> $rtr { + ((*self.lpVtbl).$method)(self $(,$p)*) + })+ + } + impl ::std::ops::Deref for $interface { + type Target = $crate::$pinterface; + #[inline] + fn deref(&self) -> &$crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + impl ::std::ops::DerefMut for $interface { + #[inline] + fn deref_mut(&mut self) -> &mut $crate::$pinterface { + unsafe { ::std::mem::transmute(self) } + } + } + }; +} +macro_rules! UNION { + ($base:ident, $field:ident, $variant:ident, $variantmut:ident, $fieldtype:ty) => { + impl $base { + #[inline] + pub unsafe fn $variant(&self) -> &$fieldtype { + ::std::mem::transmute(&self.$field) + } + #[inline] + pub unsafe fn $variantmut(&mut self) -> &mut $fieldtype { + ::std::mem::transmute(&mut self.$field) + } + } + } +} +macro_rules! BITFIELD { + ($base:ident $field:ident: $fieldtype:ty [ + $($thing:ident $set_thing:ident[$r:expr],)+ + ]) => { + impl $base {$( + #[inline] + pub fn $thing(&self) -> $fieldtype { + let size = ::std::mem::size_of::<$fieldtype>() * 8; + self.$field << (size - $r.end) >> (size - $r.end + $r.start) + } + #[inline] + pub fn $set_thing(&mut self, val: $fieldtype) { + let mask = ((1 << ($r.end - $r.start)) - 1) << $r.start; + self.$field &= !mask; + self.$field |= (val << $r.start) & mask; + } + )+} + } +} +#[macro_export] +macro_rules! ENUM { + {enum $name:ident { $($variant:ident = $value:expr,)+ }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + $(pub const $variant: $name = $name($value);)+ + }; + {enum $name:ident { $variant:ident = $value:expr, $($rest:tt)* }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + pub const $variant: $name = $name($value); + ENUM!{@gen $name, $variant, $($rest)*} + }; + {enum $name:ident { $variant:ident, $($rest:tt)* }} => { + ENUM!{enum $name { $variant = 0, $($rest)* }} + }; + {@gen $name:ident, $base:ident,} => {}; + {@gen $name:ident, $base:ident, $variant:ident = $value:expr, $($rest:tt)*} => { + pub const $variant: $name = $name($value); + ENUM!{@gen $name, $variant, $($rest)*} + }; + {@gen $name:ident, $base:ident, $variant:ident, $($rest:tt)*} => { + pub const $variant: $name = $name($base.0 + 1u32); + ENUM!{@gen $name, $variant, $($rest)*} + }; +} +macro_rules! FLAGS { + {enum $name:ident { $($variant:ident = $value:expr,)+ }} => { + #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + pub struct $name(pub u32); + $(pub const $variant: $name = $name($value);)+ + impl ::std::ops::BitAnd<$name> for $name { + type Output = $name; + fn bitand(self, o: $name) -> $name { $name(self.0 & o.0) } + } + impl ::std::ops::BitOr<$name> for $name { + type Output = $name; + fn bitor(self, o: $name) -> $name { $name(self.0 | o.0) } + } + impl ::std::ops::BitXor<$name> for $name { + type Output = $name; + fn bitxor(self, o: $name) -> $name { $name(self.0 ^ o.0) } + } + impl ::std::ops::Not for $name { + type Output = $name; + fn not(self) -> $name { $name(!self.0) } + } + } +} +macro_rules! STRUCT { + {$(#[$attrs:meta])* nodebug struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { + #[repr(C)] $(#[$attrs])* + pub struct $name { + $(pub $field: $ftype,)+ + } + impl Copy for $name {} + impl Clone for $name { fn clone(&self) -> $name { *self } } + }; + {$(#[$attrs:meta])* struct $name:ident { $($field:ident: $ftype:ty,)+ }} => { + #[repr(C)] #[derive(Debug)] $(#[$attrs])* + pub struct $name { + $(pub $field: $ftype,)+ + } + impl Copy for $name {} + impl Clone for $name { fn clone(&self) -> $name { *self } } + }; +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/memoryapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/memoryapi.rs new file mode 100644 index 0000000..30cefea --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/memoryapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-memory-l1-1-0 +pub const FILE_MAP_WRITE: ::DWORD = ::SECTION_MAP_WRITE; +pub const FILE_MAP_READ: ::DWORD = ::SECTION_MAP_READ; +pub const FILE_MAP_ALL_ACCESS: ::DWORD = ::SECTION_ALL_ACCESS; +pub const FILE_MAP_EXECUTE: ::DWORD = ::SECTION_MAP_EXECUTE_EXPLICIT; +pub const FILE_MAP_COPY: ::DWORD = 0x00000001; +pub const FILE_MAP_RESERVE: ::DWORD = 0x80000000; +ENUM!{enum MEMORY_RESOURCE_NOTIFICATION_TYPE { + LowMemoryResourceNotification, + HighMemoryResourceNotification, +}} +STRUCT!{struct WIN32_MEMORY_RANGE_ENTRY { + VirtualAddress: ::PVOID, + NumberOfBytes: ::SIZE_T, +}} +pub type PWIN32_MEMORY_RANGE_ENTRY = *mut WIN32_MEMORY_RANGE_ENTRY; +pub type PBAD_MEMORY_CALLBACK_ROUTINE = Option; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/minschannel.rs b/third_party/cargo/vendor/winapi-0.2.8/src/minschannel.rs new file mode 100644 index 0000000..828f1be --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/minschannel.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Public Definitions for MIN SCHANNEL Security Provider + +pub const SECPKG_ATTR_ISSUER_LIST: ::DWORD = 0x50; +pub const SECPKG_ATTR_REMOTE_CRED: ::DWORD = 0x51; +pub const SECPKG_ATTR_LOCAL_CRED: ::DWORD = 0x52; +pub const SECPKG_ATTR_REMOTE_CERT_CONTEXT: ::DWORD = 0x53; +pub const SECPKG_ATTR_LOCAL_CERT_CONTEXT: ::DWORD = 0x54; +pub const SECPKG_ATTR_ROOT_STORE: ::DWORD = 0x55; +pub const SECPKG_ATTR_SUPPORTED_ALGS: ::DWORD = 0x56; +pub const SECPKG_ATTR_CIPHER_STRENGTHS: ::DWORD = 0x57; +pub const SECPKG_ATTR_SUPPORTED_PROTOCOLS: ::DWORD = 0x58; +pub const SECPKG_ATTR_ISSUER_LIST_EX: ::DWORD = 0x59; +pub const SECPKG_ATTR_CONNECTION_INFO: ::DWORD = 0x5a; +pub const SECPKG_ATTR_EAP_KEY_BLOCK: ::DWORD = 0x5b; +pub const SECPKG_ATTR_MAPPED_CRED_ATTR: ::DWORD = 0x5c; +pub const SECPKG_ATTR_SESSION_INFO: ::DWORD = 0x5d; +pub const SECPKG_ATTR_APP_DATA: ::DWORD = 0x5e; +pub const SECPKG_ATTR_REMOTE_CERTIFICATES: ::DWORD = 0x5F; +pub const SECPKG_ATTR_CLIENT_CERT_POLICY: ::DWORD = 0x60; +pub const SECPKG_ATTR_CC_POLICY_RESULT: ::DWORD = 0x61; +pub const SECPKG_ATTR_USE_NCRYPT: ::DWORD = 0x62; +pub const SECPKG_ATTR_LOCAL_CERT_INFO: ::DWORD = 0x63; +pub const SECPKG_ATTR_CIPHER_INFO: ::DWORD = 0x64; +pub const SECPKG_ATTR_EAP_PRF_INFO: ::DWORD = 0x65; +pub const SECPKG_ATTR_SUPPORTED_SIGNATURES: ::DWORD = 0x66; +pub const SECPKG_ATTR_REMOTE_CERT_CHAIN: ::DWORD = 0x67; +pub const SECPKG_ATTR_UI_INFO: ::DWORD = 0x68; +pub const SECPKG_ATTR_EARLY_START: ::DWORD = 0x69; + +STRUCT!{struct SecPkgCred_SupportedAlgs { + cSupportedAlgs: ::DWORD, + palgSupportedAlgs: ::ALG_ID, +}} + +STRUCT!{struct SecPkgCred_CipherStrengths { + dwMinimumCipherStrength: ::DWORD, + dwMaximumCipherStrength: ::DWORD, +}} + +STRUCT!{struct SecPkgCred_SupportedProtocols { + grbitProtocol: ::DWORD, +}} + +STRUCT!{struct SecPkgCred_ClientCertPolicy { + dwFlags: ::DWORD, + guidPolicyId: ::GUID, + dwCertFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + fCheckRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + fOmitUsageCheck: ::BOOL, + pwszSslCtlStoreName: ::LPWSTR, + pwszSslCtlIdentifier: ::LPWSTR, +}} \ No newline at end of file diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/minwinbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/minwinbase.rs new file mode 100644 index 0000000..f6317fa --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/minwinbase.rs @@ -0,0 +1,253 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This module defines the 32-Bit Windows Base APIs +STRUCT!{struct SECURITY_ATTRIBUTES { + nLength: ::DWORD, + lpSecurityDescriptor: ::LPVOID, + bInheritHandle: ::BOOL, +}} +pub type PSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; +pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; +STRUCT!{struct OVERLAPPED { + Internal: ::ULONG_PTR, + InternalHigh: ::ULONG_PTR, + Offset: ::DWORD, + OffsetHigh: ::DWORD, + hEvent: ::HANDLE, +}} +UNION!(OVERLAPPED, Offset, Pointer, Pointer_mut, ::PVOID); +pub type LPOVERLAPPED = *mut OVERLAPPED; +STRUCT!{struct OVERLAPPED_ENTRY { + lpCompletionKey: ::ULONG_PTR, + lpOverlapped: LPOVERLAPPED, + Internal: ::ULONG_PTR, + dwNumberOfBytesTransferred: ::DWORD, +}} +pub type LPOVERLAPPED_ENTRY = *mut OVERLAPPED_ENTRY; +STRUCT!{struct SYSTEMTIME { + wYear: ::WORD, + wMonth: ::WORD, + wDayOfWeek: ::WORD, + wDay: ::WORD, + wHour: ::WORD, + wMinute: ::WORD, + wSecond: ::WORD, + wMilliseconds: ::WORD, +}} +pub type PSYSTEMTIME = *mut SYSTEMTIME; +pub type LPSYSTEMTIME = *mut SYSTEMTIME; +STRUCT!{nodebug struct WIN32_FIND_DATAA { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + dwReserved0: ::DWORD, + dwReserved1: ::DWORD, + cFileName: [::CHAR; ::MAX_PATH], + cAlternateFileName: [::CHAR; 14], +}} +pub type PWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; +pub type LPWIN32_FIND_DATAA = *mut WIN32_FIND_DATAA; +STRUCT!{nodebug struct WIN32_FIND_DATAW { + dwFileAttributes: ::DWORD, + ftCreationTime: ::FILETIME, + ftLastAccessTime: ::FILETIME, + ftLastWriteTime: ::FILETIME, + nFileSizeHigh: ::DWORD, + nFileSizeLow: ::DWORD, + dwReserved0: ::DWORD, + dwReserved1: ::DWORD, + cFileName: [::WCHAR; ::MAX_PATH], + cAlternateFileName: [::WCHAR; 14], +}} +pub type PWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; +pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; +ENUM!{enum FINDEX_INFO_LEVELS { + FindExInfoStandard, + FindExInfoBasic, + FindExInfoMaxInfoLevel, +}} +pub const FIND_FIRST_EX_CASE_SENSITIVE: ::DWORD = 0x00000001; +pub const FIND_FIRST_EX_LARGE_FETCH: ::DWORD = 0x00000002; +ENUM!{enum FINDEX_SEARCH_OPS { + FindExSearchNameMatch, + FindExSearchLimitToDirectories, + FindExSearchLimitToDevices, + FindExSearchMaxSearchOp, +}} +ENUM!{enum GET_FILEEX_INFO_LEVELS { + GetFileExInfoStandard, + GetFileExMaxInfoLevel, +}} +ENUM!{enum FILE_INFO_BY_HANDLE_CLASS { + FileBasicInfo, + FileStandardInfo, + FileNameInfo, + FileRenameInfo, + FileDispositionInfo, + FileAllocationInfo, + FileEndOfFileInfo, + FileStreamInfo, + FileCompressionInfo, + FileAttributeTagInfo, + FileIdBothDirectoryInfo, + FileIdBothDirectoryRestartInfo, + FileIoPriorityHintInfo, + FileRemoteProtocolInfo, + FileFullDirectoryInfo, + FileFullDirectoryRestartInfo, + FileStorageInfo, + FileAlignmentInfo, + FileIdInfo, + FileIdExtdDirectoryInfo, + FileIdExtdDirectoryRestartInfo, + MaximumFileInfoByHandleClass, +}} +pub type PFILE_INFO_BY_HANDLE_CLASS = *mut FILE_INFO_BY_HANDLE_CLASS; +pub type CRITICAL_SECTION = ::RTL_CRITICAL_SECTION; +pub type PCRITICAL_SECTION = ::PRTL_CRITICAL_SECTION; +pub type LPCRITICAL_SECTION = ::PRTL_CRITICAL_SECTION; +pub type CRITICAL_SECTION_DEBUG = ::RTL_CRITICAL_SECTION_DEBUG; +pub type PCRITICAL_SECTION_DEBUG = ::PRTL_CRITICAL_SECTION_DEBUG; +pub type LPCRITICAL_SECTION_DEBUG = ::PRTL_CRITICAL_SECTION_DEBUG; +pub type LPOVERLAPPED_COMPLETION_ROUTINE = Option; +pub const LOCKFILE_FAIL_IMMEDIATELY: ::DWORD = 0x00000001; +pub const LOCKFILE_EXCLUSIVE_LOCK: ::DWORD = 0x00000002; +STRUCT!{struct PROCESS_HEAP_ENTRY_Block { + hMem: ::HANDLE, + dwReserved: [::DWORD; 3], +}} +STRUCT!{struct PROCESS_HEAP_ENTRY_Region { + dwCommittedSize: ::DWORD, + dwUnCommittedSize: ::DWORD, + lpFirstBlock: ::LPVOID, + lpLastBlock: ::LPVOID, +}} +STRUCT!{struct PROCESS_HEAP_ENTRY { + lpData: ::PVOID, + cbData: ::DWORD, + cbOverhead: ::BYTE, + iRegionIndex: ::BYTE, + wFlags: ::WORD, + Region: PROCESS_HEAP_ENTRY_Region, +}} +UNION!(PROCESS_HEAP_ENTRY, Region, Block, Block_mut, PROCESS_HEAP_ENTRY_Block); +pub type LPPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; +pub type PPROCESS_HEAP_ENTRY = *mut PROCESS_HEAP_ENTRY; +pub const PROCESS_HEAP_REGION: ::WORD = 0x0001; +pub const PROCESS_HEAP_UNCOMMITTED_RANGE: ::WORD = 0x0002; +pub const PROCESS_HEAP_ENTRY_BUSY: ::WORD = 0x0004; +pub const PROCESS_HEAP_SEG_ALLOC: ::WORD = 0x0008; +pub const PROCESS_HEAP_ENTRY_MOVEABLE: ::WORD = 0x0010; +pub const PROCESS_HEAP_ENTRY_DDESHARE: ::WORD = 0x0020; +pub type PTHREAD_START_ROUTINE = Option ::DWORD>; +pub type LPTHREAD_START_ROUTINE = PTHREAD_START_ROUTINE; +pub type LPCONTEXT = ::PCONTEXT; +STRUCT!{struct REASON_CONTEXT_Detailed { + LocalizedReasonModule: ::HMODULE, + LocalizedReasonId: ::ULONG, + ReasonStringCount: ::ULONG, + ReasonStrings: *mut ::LPWSTR, +}} +STRUCT!{struct REASON_CONTEXT { + Version: ::ULONG, + Flags: ::DWORD, + Reason: REASON_CONTEXT_Detailed, +}} +UNION!(REASON_CONTEXT, Reason, SimpleReasonString, SimpleReasonString_mut, ::LPWSTR); +pub type PREASON_CONTEXT = *mut REASON_CONTEXT; +pub const EXCEPTION_DEBUG_EVENT: ::DWORD = 1; +pub const CREATE_THREAD_DEBUG_EVENT: ::DWORD = 2; +pub const CREATE_PROCESS_DEBUG_EVENT: ::DWORD = 3; +pub const EXIT_THREAD_DEBUG_EVENT: ::DWORD = 4; +pub const EXIT_PROCESS_DEBUG_EVENT: ::DWORD = 5; +pub const LOAD_DLL_DEBUG_EVENT: ::DWORD = 6; +pub const UNLOAD_DLL_DEBUG_EVENT: ::DWORD = 7; +pub const OUTPUT_DEBUG_STRING_EVENT: ::DWORD = 8; +pub const RIP_EVENT: ::DWORD = 9; +STRUCT!{struct EXCEPTION_DEBUG_INFO { + ExceptionRecord: ::EXCEPTION_RECORD, + dwFirstChance: ::DWORD, +}} +pub type LPEXCEPTION_DEBUG_INFO = *mut EXCEPTION_DEBUG_INFO; +STRUCT!{nodebug struct CREATE_THREAD_DEBUG_INFO { + hThread: ::HANDLE, + lpThreadLocalBase: ::LPVOID, + lpStartAddress: LPTHREAD_START_ROUTINE, +}} +pub type LPCREATE_THREAD_DEBUG_INFO = *mut CREATE_THREAD_DEBUG_INFO; +STRUCT!{nodebug struct CREATE_PROCESS_DEBUG_INFO { + hFile: ::HANDLE, + hProcess: ::HANDLE, + hThread: ::HANDLE, + lpBaseOfImage: ::LPVOID, + dwDebugInfoFileOffset: ::DWORD, + nDebugInfoSize: ::DWORD, + lpThreadLocalBase: ::LPVOID, + lpStartAddress: LPTHREAD_START_ROUTINE, + lpImageName: ::LPVOID, + fUnicode: ::WORD, +}} +pub type LPCREATE_PROCESS_DEBUG_INFO = *mut CREATE_PROCESS_DEBUG_INFO; +STRUCT!{struct EXIT_THREAD_DEBUG_INFO { + dwExitCode: ::DWORD, +}} +pub type LPEXIT_THREAD_DEBUG_INFO = *mut EXIT_THREAD_DEBUG_INFO; +STRUCT!{struct EXIT_PROCESS_DEBUG_INFO { + dwExitCode: ::DWORD, +}} +pub type LPEXIT_PROCESS_DEBUG_INFO = *mut EXIT_PROCESS_DEBUG_INFO; +STRUCT!{struct LOAD_DLL_DEBUG_INFO { + hFile: ::HANDLE, + lpBaseOfDll: ::LPVOID, + dwDebugInfoFileOffset: ::DWORD, + nDebugInfoSize: ::DWORD, + lpImageName: ::LPVOID, + fUnicode: ::WORD, +}} +pub type LPLOAD_DLL_DEBUG_INFO = *mut LOAD_DLL_DEBUG_INFO; +STRUCT!{struct UNLOAD_DLL_DEBUG_INFO { + lpBaseOfDll: ::LPVOID, +}} +pub type LPUNLOAD_DLL_DEBUG_INFO = *mut UNLOAD_DLL_DEBUG_INFO; +STRUCT!{struct OUTPUT_DEBUG_STRING_INFO { + lpDebugStringData: ::LPSTR, + fUnicode: ::WORD, + nDebugStringLength: ::WORD, +}} +pub type LPOUTPUT_DEBUG_STRING_INFO = *mut OUTPUT_DEBUG_STRING_INFO; +STRUCT!{struct RIP_INFO { + dwError: ::DWORD, + dwType: ::DWORD, +}} +pub type LPRIP_INFO = *mut RIP_INFO; +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct DEBUG_EVENT { + dwDebugEventCode: ::DWORD, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, + u: [u8; 160], +}} +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct DEBUG_EVENT { + dwDebugEventCode: ::DWORD, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, + u: [u8; 84], +}} +UNION!(DEBUG_EVENT, u, Exception, Exception_mut, EXCEPTION_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, CreateThread, CreateThread_mut, CREATE_THREAD_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, CreateProcessInfo, CreateProcessInfo_mut, CREATE_PROCESS_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, ExitThread, ExitThread_mut, EXIT_THREAD_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, ExitProcess, ExitProcess_mut, EXIT_PROCESS_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, LoadDll, LoadDll_mut, LOAD_DLL_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, UnloadDll, UnloadDll_mut, UNLOAD_DLL_DEBUG_INFO); +UNION!(DEBUG_EVENT, u, DebugString, DebugString_mut, OUTPUT_DEBUG_STRING_INFO); +UNION!(DEBUG_EVENT, u, RipInfo, RipInfo_mut, RIP_INFO); +pub type LPDEBUG_EVENT = *mut DEBUG_EVENT; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/minwindef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/minwindef.rs new file mode 100644 index 0000000..a5ed017 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/minwindef.rs @@ -0,0 +1,89 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Basic Windows Type Definitions for minwin partition +pub type ULONG = ::c_ulong; +pub type PULONG = *mut ULONG; +pub type USHORT = ::c_ushort; +pub type PUSHORT = *mut USHORT; +pub type UCHAR = ::c_uchar; +pub type PUCHAR = *mut UCHAR; +pub type PSZ = *mut ::c_char; +pub const MAX_PATH: usize = 260; +pub const FALSE: BOOL = 0; +pub const TRUE: BOOL = 1; +pub type DWORD = ::c_ulong; +pub type BOOL = ::c_int; +pub type BYTE = ::c_uchar; +pub type WORD = ::c_ushort; +pub type FLOAT = ::c_float; +pub type PFLOAT = *mut FLOAT; +pub type PBOOL = *mut BOOL; +pub type LPBOOL = *mut BOOL; +pub type PBYTE = *mut BYTE; +pub type LPBYTE = *mut BYTE; +pub type PINT = *mut ::c_int; +pub type LPINT = *mut ::c_int; +pub type PWORD = *mut WORD; +pub type LPWORD = *mut WORD; +pub type LPLONG = *mut ::c_long; +pub type PDWORD = *mut DWORD; +pub type LPDWORD = *mut DWORD; +pub type LPVOID = *mut ::c_void; +pub type LPCVOID = *const ::c_void; +pub type INT = ::c_int; +pub type UINT = ::c_uint; +pub type PUINT = *mut ::c_uint; +pub type WPARAM = ::UINT_PTR; +pub type LPARAM = ::LONG_PTR; +pub type LRESULT = ::LONG_PTR; +pub fn MAKEWORD(a: BYTE, b: BYTE) -> WORD { + (a as WORD) | ((b as WORD) << 8) +} +pub fn MAKELONG(a: WORD, b: WORD) -> ::LONG { + ((a as DWORD) | ((b as DWORD) << 16)) as ::LONG +} +pub fn LOWORD(l: DWORD) -> WORD { + (l & 0xffff) as WORD +} +pub fn HIWORD(l: DWORD) -> WORD { + ((l >> 16) & 0xffff) as WORD +} +pub fn LOBYTE(l: WORD) -> BYTE { + (l & 0xff) as BYTE +} +pub fn HIBYTE(l: WORD) -> BYTE { + ((l >> 8) & 0xff) as BYTE +} +pub type SPHANDLE = *mut ::HANDLE; +pub type LPHANDLE = *mut ::HANDLE; +pub type HGLOBAL = ::HANDLE; +pub type HLOCAL = ::HANDLE; +pub type GLOBALHANDLE = ::HANDLE; +pub type LOCALHANDLE = ::HANDLE; +/// Pointer to probably a function with unknown type signature. +pub type FARPROC = *const ::c_void; +/// Pointer to probably a function with unknown type signature. +pub type NEARPROC = *const ::c_void; +/// Pointer to probably a function with unknown type signature. +pub type PROC = *const ::c_void; +pub type ATOM = WORD; +DECLARE_HANDLE!(HKEY, HKEY__); +pub type PHKEY = *mut HKEY; +DECLARE_HANDLE!(HMETAFILE, HMETAFILE__); +DECLARE_HANDLE!(HINSTANCE, HINSTANCE__); +pub type HMODULE = HINSTANCE; +DECLARE_HANDLE!(HRGN, HRGN__); +DECLARE_HANDLE!(HRSRC, HRSRC__); +DECLARE_HANDLE!(HSPRITE, HSPRITE__); +DECLARE_HANDLE!(HLSURF, HLSURF__); +DECLARE_HANDLE!(HSTR, HSTR__); +DECLARE_HANDLE!(HTASK, HTASK__); +DECLARE_HANDLE!(HWINSTA, HWINSTA__); +DECLARE_HANDLE!(HKL, HKL__); +pub type HFILE = ::c_int; +STRUCT!{struct FILETIME { + dwLowDateTime: DWORD, + dwHighDateTime: DWORD, +}} +pub type PFILETIME = *mut FILETIME; +pub type LPFILETIME = *mut FILETIME; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/mmdeviceapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/mmdeviceapi.rs new file mode 100644 index 0000000..9fc85a7 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/mmdeviceapi.rs @@ -0,0 +1,63 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +pub const DEVICE_STATE_ACTIVE: ::DWORD = 0x00000001; +pub const DEVICE_STATE_DISABLED: ::DWORD = 0x00000002; +pub const DEVICE_STATE_NOTPRESENT: ::DWORD = 0x00000004; +pub const DEVICE_STATE_UNPLUGGED: ::DWORD = 0x00000008; +pub const DEVICE_STATEMASK_ALL: ::DWORD = 0x0000000F; +ENUM!{enum EDataFlow { + eRender, + eCapture, + eAll, + EDataFlow_enum_count, +}} +ENUM!{enum ERole { + eConsole, + eMultimedia, + eCommunications, + ERole_enum_count, +}} +DEFINE_GUID!(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, + 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E); +DEFINE_GUID!(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, + 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6); +RIDL!( +interface IMMDevice(IMMDeviceVtbl): IUnknown(IUnknownVtbl) { + fn Activate( + &mut self, iid: ::REFIID, dwClsCtx: ::DWORD, pActivationParams: *mut ::PROPVARIANT, + ppInterface: *mut ::LPVOID + ) -> ::HRESULT, + fn OpenPropertyStore( + &mut self, stgmAccess: ::DWORD, ppProperties: *mut *mut ::IPropertyStore + ) -> ::HRESULT, + fn GetId(&mut self, ppstrId: *mut ::LPWSTR) -> ::HRESULT, + fn GetState(&mut self, pdwState: *mut ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface IMMDeviceEnumerator(IMMDeviceEnumeratorVtbl): IUnknown(IUnknownVtbl) { + fn EnumAudioEndpoints( + &mut self, dataFlow: EDataFlow, dwStateMask: ::DWORD, + ppDevices: *mut *mut IMMDeviceCollection + ) -> ::HRESULT, + fn GetDefaultAudioEndpoint( + &mut self, dataFlow: EDataFlow, role: ERole, ppEndpoint: *mut *mut IMMDevice + ) -> ::HRESULT, + fn GetDevice(&mut self, pwstrId: ::LPCWSTR, ppDevices: *mut *mut IMMDevice) -> ::HRESULT, + fn RegisterEndpointNotificationCallback( + &mut self, pClient: *mut IMMNotificationClient + ) -> ::HRESULT, + fn UnregisterEndpointNotificationCallback( + &mut self, pClient: *mut IMMNotificationClient + ) -> ::HRESULT +} +); +RIDL!( +interface IMMDeviceCollection(IMMDeviceCollectionVtbl): IUnknown(IUnknownVtbl) { + fn GetCount(&mut self, pcDevices: *const ::UINT) -> ::HRESULT, + fn Item(&mut self, nDevice: ::UINT, ppDevice: *mut *mut IMMDevice) -> ::HRESULT +} +); +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMMNotificationClient; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/mmreg.rs b/third_party/cargo/vendor/winapi-0.2.8/src/mmreg.rs new file mode 100644 index 0000000..826d96d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/mmreg.rs @@ -0,0 +1,304 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub const WAVE_FORMAT_UNKNOWN: ::WORD = 0x0000; +pub const WAVE_FORMAT_PCM: ::WORD = 0x0001; +pub const WAVE_FORMAT_ADPCM: ::WORD = 0x0002; +pub const WAVE_FORMAT_IEEE_FLOAT: ::WORD = 0x0003; +pub const WAVE_FORMAT_VSELP: ::WORD = 0x0004; +pub const WAVE_FORMAT_IBM_CVSD: ::WORD = 0x0005; +pub const WAVE_FORMAT_ALAW: ::WORD = 0x0006; +pub const WAVE_FORMAT_MULAW: ::WORD = 0x0007; +pub const WAVE_FORMAT_DTS: ::WORD = 0x0008; +pub const WAVE_FORMAT_DRM: ::WORD = 0x0009; +pub const WAVE_FORMAT_WMAVOICE9: ::WORD = 0x000A; +pub const WAVE_FORMAT_WMAVOICE10: ::WORD = 0x000B; +pub const WAVE_FORMAT_OKI_ADPCM: ::WORD = 0x0010; +pub const WAVE_FORMAT_DVI_ADPCM: ::WORD = 0x0011; +pub const WAVE_FORMAT_IMA_ADPCM: ::WORD = WAVE_FORMAT_DVI_ADPCM; +pub const WAVE_FORMAT_MEDIASPACE_ADPCM: ::WORD = 0x0012; +pub const WAVE_FORMAT_SIERRA_ADPCM: ::WORD = 0x0013; +pub const WAVE_FORMAT_G723_ADPCM: ::WORD = 0x0014; +pub const WAVE_FORMAT_DIGISTD: ::WORD = 0x0015; +pub const WAVE_FORMAT_DIGIFIX: ::WORD = 0x0016; +pub const WAVE_FORMAT_DIALOGIC_OKI_ADPCM: ::WORD = 0x0017; +pub const WAVE_FORMAT_MEDIAVISION_ADPCM: ::WORD = 0x0018; +pub const WAVE_FORMAT_CU_CODEC: ::WORD = 0x0019; +pub const WAVE_FORMAT_HP_DYN_VOICE: ::WORD = 0x001A; +pub const WAVE_FORMAT_YAMAHA_ADPCM: ::WORD = 0x0020; +pub const WAVE_FORMAT_SONARC: ::WORD = 0x0021; +pub const WAVE_FORMAT_DSPGROUP_TRUESPEECH: ::WORD = 0x0022; +pub const WAVE_FORMAT_ECHOSC1: ::WORD = 0x0023; +pub const WAVE_FORMAT_AUDIOFILE_AF36: ::WORD = 0x0024; +pub const WAVE_FORMAT_APTX: ::WORD = 0x0025; +pub const WAVE_FORMAT_AUDIOFILE_AF10: ::WORD = 0x0026; +pub const WAVE_FORMAT_PROSODY_1612: ::WORD = 0x0027; +pub const WAVE_FORMAT_LRC: ::WORD = 0x0028; +pub const WAVE_FORMAT_DOLBY_AC2: ::WORD = 0x0030; +pub const WAVE_FORMAT_GSM610: ::WORD = 0x0031; +pub const WAVE_FORMAT_MSNAUDIO: ::WORD = 0x0032; +pub const WAVE_FORMAT_ANTEX_ADPCME: ::WORD = 0x0033; +pub const WAVE_FORMAT_CONTROL_RES_VQLPC: ::WORD = 0x0034; +pub const WAVE_FORMAT_DIGIREAL: ::WORD = 0x0035; +pub const WAVE_FORMAT_DIGIADPCM: ::WORD = 0x0036; +pub const WAVE_FORMAT_CONTROL_RES_CR10: ::WORD = 0x0037; +pub const WAVE_FORMAT_NMS_VBXADPCM: ::WORD = 0x0038; +pub const WAVE_FORMAT_CS_IMAADPCM: ::WORD = 0x0039; +pub const WAVE_FORMAT_ECHOSC3: ::WORD = 0x003A; +pub const WAVE_FORMAT_ROCKWELL_ADPCM: ::WORD = 0x003B; +pub const WAVE_FORMAT_ROCKWELL_DIGITALK: ::WORD = 0x003C; +pub const WAVE_FORMAT_XEBEC: ::WORD = 0x003D; +pub const WAVE_FORMAT_G721_ADPCM: ::WORD = 0x0040; +pub const WAVE_FORMAT_G728_CELP: ::WORD = 0x0041; +pub const WAVE_FORMAT_MSG723: ::WORD = 0x0042; +pub const WAVE_FORMAT_INTEL_G723_1: ::WORD = 0x0043; +pub const WAVE_FORMAT_INTEL_G729: ::WORD = 0x0044; +pub const WAVE_FORMAT_SHARP_G726: ::WORD = 0x0045; +pub const WAVE_FORMAT_MPEG: ::WORD = 0x0050; +pub const WAVE_FORMAT_RT24: ::WORD = 0x0052; +pub const WAVE_FORMAT_PAC: ::WORD = 0x0053; +pub const WAVE_FORMAT_MPEGLAYER3: ::WORD = 0x0055; +pub const WAVE_FORMAT_LUCENT_G723: ::WORD = 0x0059; +pub const WAVE_FORMAT_CIRRUS: ::WORD = 0x0060; +pub const WAVE_FORMAT_ESPCM: ::WORD = 0x0061; +pub const WAVE_FORMAT_VOXWARE: ::WORD = 0x0062; +pub const WAVE_FORMAT_CANOPUS_ATRAC: ::WORD = 0x0063; +pub const WAVE_FORMAT_G726_ADPCM: ::WORD = 0x0064; +pub const WAVE_FORMAT_G722_ADPCM: ::WORD = 0x0065; +pub const WAVE_FORMAT_DSAT: ::WORD = 0x0066; +pub const WAVE_FORMAT_DSAT_DISPLAY: ::WORD = 0x0067; +pub const WAVE_FORMAT_VOXWARE_BYTE_ALIGNED: ::WORD = 0x0069; +pub const WAVE_FORMAT_VOXWARE_AC8: ::WORD = 0x0070; +pub const WAVE_FORMAT_VOXWARE_AC10: ::WORD = 0x0071; +pub const WAVE_FORMAT_VOXWARE_AC16: ::WORD = 0x0072; +pub const WAVE_FORMAT_VOXWARE_AC20: ::WORD = 0x0073; +pub const WAVE_FORMAT_VOXWARE_RT24: ::WORD = 0x0074; +pub const WAVE_FORMAT_VOXWARE_RT29: ::WORD = 0x0075; +pub const WAVE_FORMAT_VOXWARE_RT29HW: ::WORD = 0x0076; +pub const WAVE_FORMAT_VOXWARE_VR12: ::WORD = 0x0077; +pub const WAVE_FORMAT_VOXWARE_VR18: ::WORD = 0x0078; +pub const WAVE_FORMAT_VOXWARE_TQ40: ::WORD = 0x0079; +pub const WAVE_FORMAT_VOXWARE_SC3: ::WORD = 0x007A; +pub const WAVE_FORMAT_VOXWARE_SC3_1: ::WORD = 0x007B; +pub const WAVE_FORMAT_SOFTSOUND: ::WORD = 0x0080; +pub const WAVE_FORMAT_VOXWARE_TQ60: ::WORD = 0x0081; +pub const WAVE_FORMAT_MSRT24: ::WORD = 0x0082; +pub const WAVE_FORMAT_G729A: ::WORD = 0x0083; +pub const WAVE_FORMAT_MVI_MVI2: ::WORD = 0x0084; +pub const WAVE_FORMAT_DF_G726: ::WORD = 0x0085; +pub const WAVE_FORMAT_DF_GSM610: ::WORD = 0x0086; +pub const WAVE_FORMAT_ISIAUDIO: ::WORD = 0x0088; +pub const WAVE_FORMAT_ONLIVE: ::WORD = 0x0089; +pub const WAVE_FORMAT_MULTITUDE_FT_SX20: ::WORD = 0x008A; +pub const WAVE_FORMAT_INFOCOM_ITS_G721_ADPCM: ::WORD = 0x008B; +pub const WAVE_FORMAT_CONVEDIA_G729: ::WORD = 0x008C; +pub const WAVE_FORMAT_CONGRUENCY: ::WORD = 0x008D; +pub const WAVE_FORMAT_SBC24: ::WORD = 0x0091; +pub const WAVE_FORMAT_DOLBY_AC3_SPDIF: ::WORD = 0x0092; +pub const WAVE_FORMAT_MEDIASONIC_G723: ::WORD = 0x0093; +pub const WAVE_FORMAT_PROSODY_8KBPS: ::WORD = 0x0094; +pub const WAVE_FORMAT_ZYXEL_ADPCM: ::WORD = 0x0097; +pub const WAVE_FORMAT_PHILIPS_LPCBB: ::WORD = 0x0098; +pub const WAVE_FORMAT_PACKED: ::WORD = 0x0099; +pub const WAVE_FORMAT_MALDEN_PHONYTALK: ::WORD = 0x00A0; +pub const WAVE_FORMAT_RACAL_RECORDER_GSM: ::WORD = 0x00A1; +pub const WAVE_FORMAT_RACAL_RECORDER_G720_A: ::WORD = 0x00A2; +pub const WAVE_FORMAT_RACAL_RECORDER_G723_1: ::WORD = 0x00A3; +pub const WAVE_FORMAT_RACAL_RECORDER_TETRA_ACELP: ::WORD = 0x00A4; +pub const WAVE_FORMAT_NEC_AAC: ::WORD = 0x00B0; +pub const WAVE_FORMAT_RAW_AAC1: ::WORD = 0x00FF; +pub const WAVE_FORMAT_RHETOREX_ADPCM: ::WORD = 0x0100; +pub const WAVE_FORMAT_IRAT: ::WORD = 0x0101; +pub const WAVE_FORMAT_VIVO_G723: ::WORD = 0x0111; +pub const WAVE_FORMAT_VIVO_SIREN: ::WORD = 0x0112; +pub const WAVE_FORMAT_PHILIPS_CELP: ::WORD = 0x0120; +pub const WAVE_FORMAT_PHILIPS_GRUNDIG: ::WORD = 0x0121; +pub const WAVE_FORMAT_DIGITAL_G723: ::WORD = 0x0123; +pub const WAVE_FORMAT_SANYO_LD_ADPCM: ::WORD = 0x0125; +pub const WAVE_FORMAT_SIPROLAB_ACEPLNET: ::WORD = 0x0130; +pub const WAVE_FORMAT_SIPROLAB_ACELP4800: ::WORD = 0x0131; +pub const WAVE_FORMAT_SIPROLAB_ACELP8V3: ::WORD = 0x0132; +pub const WAVE_FORMAT_SIPROLAB_G729: ::WORD = 0x0133; +pub const WAVE_FORMAT_SIPROLAB_G729A: ::WORD = 0x0134; +pub const WAVE_FORMAT_SIPROLAB_KELVIN: ::WORD = 0x0135; +pub const WAVE_FORMAT_VOICEAGE_AMR: ::WORD = 0x0136; +pub const WAVE_FORMAT_G726ADPCM: ::WORD = 0x0140; +pub const WAVE_FORMAT_DICTAPHONE_CELP68: ::WORD = 0x0141; +pub const WAVE_FORMAT_DICTAPHONE_CELP54: ::WORD = 0x0142; +pub const WAVE_FORMAT_QUALCOMM_PUREVOICE: ::WORD = 0x0150; +pub const WAVE_FORMAT_QUALCOMM_HALFRATE: ::WORD = 0x0151; +pub const WAVE_FORMAT_TUBGSM: ::WORD = 0x0155; +pub const WAVE_FORMAT_MSAUDIO1: ::WORD = 0x0160; +pub const WAVE_FORMAT_WMAUDIO2: ::WORD = 0x0161; +pub const WAVE_FORMAT_WMAUDIO3: ::WORD = 0x0162; +pub const WAVE_FORMAT_WMAUDIO_LOSSLESS: ::WORD = 0x0163; +pub const WAVE_FORMAT_WMASPDIF: ::WORD = 0x0164; +pub const WAVE_FORMAT_UNISYS_NAP_ADPCM: ::WORD = 0x0170; +pub const WAVE_FORMAT_UNISYS_NAP_ULAW: ::WORD = 0x0171; +pub const WAVE_FORMAT_UNISYS_NAP_ALAW: ::WORD = 0x0172; +pub const WAVE_FORMAT_UNISYS_NAP_16K: ::WORD = 0x0173; +pub const WAVE_FORMAT_SYCOM_ACM_SYC008: ::WORD = 0x0174; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_G726L: ::WORD = 0x0175; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_CELP54: ::WORD = 0x0176; +pub const WAVE_FORMAT_SYCOM_ACM_SYC701_CELP68: ::WORD = 0x0177; +pub const WAVE_FORMAT_KNOWLEDGE_ADVENTURE_ADPCM: ::WORD = 0x0178; +pub const WAVE_FORMAT_FRAUNHOFER_IIS_MPEG2_AAC: ::WORD = 0x0180; +pub const WAVE_FORMAT_DTS_DS: ::WORD = 0x0190; +pub const WAVE_FORMAT_CREATIVE_ADPCM: ::WORD = 0x0200; +pub const WAVE_FORMAT_CREATIVE_FASTSPEECH8: ::WORD = 0x0202; +pub const WAVE_FORMAT_CREATIVE_FASTSPEECH10: ::WORD = 0x0203; +pub const WAVE_FORMAT_UHER_ADPCM: ::WORD = 0x0210; +pub const WAVE_FORMAT_ULEAD_DV_AUDIO: ::WORD = 0x0215; +pub const WAVE_FORMAT_ULEAD_DV_AUDIO_1: ::WORD = 0x0216; +pub const WAVE_FORMAT_QUARTERDECK: ::WORD = 0x0220; +pub const WAVE_FORMAT_ILINK_VC: ::WORD = 0x0230; +pub const WAVE_FORMAT_RAW_SPORT: ::WORD = 0x0240; +pub const WAVE_FORMAT_ESST_AC3: ::WORD = 0x0241; +pub const WAVE_FORMAT_GENERIC_PASSTHRU: ::WORD = 0x0249; +pub const WAVE_FORMAT_IPI_HSX: ::WORD = 0x0250; +pub const WAVE_FORMAT_IPI_RPELP: ::WORD = 0x0251; +pub const WAVE_FORMAT_CS2: ::WORD = 0x0260; +pub const WAVE_FORMAT_SONY_SCX: ::WORD = 0x0270; +pub const WAVE_FORMAT_SONY_SCY: ::WORD = 0x0271; +pub const WAVE_FORMAT_SONY_ATRAC3: ::WORD = 0x0272; +pub const WAVE_FORMAT_SONY_SPC: ::WORD = 0x0273; +pub const WAVE_FORMAT_TELUM_AUDIO: ::WORD = 0x0280; +pub const WAVE_FORMAT_TELUM_IA_AUDIO: ::WORD = 0x0281; +pub const WAVE_FORMAT_NORCOM_VOICE_SYSTEMS_ADPCM: ::WORD = 0x0285; +pub const WAVE_FORMAT_FM_TOWNS_SND: ::WORD = 0x0300; +pub const WAVE_FORMAT_MICRONAS: ::WORD = 0x0350; +pub const WAVE_FORMAT_MICRONAS_CELP833: ::WORD = 0x0351; +pub const WAVE_FORMAT_BTV_DIGITAL: ::WORD = 0x0400; +pub const WAVE_FORMAT_INTEL_MUSIC_CODER: ::WORD = 0x0401; +pub const WAVE_FORMAT_INDEO_AUDIO: ::WORD = 0x0402; +pub const WAVE_FORMAT_QDESIGN_MUSIC: ::WORD = 0x0450; +pub const WAVE_FORMAT_ON2_VP7_AUDIO: ::WORD = 0x0500; +pub const WAVE_FORMAT_ON2_VP6_AUDIO: ::WORD = 0x0501; +pub const WAVE_FORMAT_VME_VMPCM: ::WORD = 0x0680; +pub const WAVE_FORMAT_TPC: ::WORD = 0x0681; +pub const WAVE_FORMAT_LIGHTWAVE_LOSSLESS: ::WORD = 0x08AE; +pub const WAVE_FORMAT_OLIGSM: ::WORD = 0x1000; +pub const WAVE_FORMAT_OLIADPCM: ::WORD = 0x1001; +pub const WAVE_FORMAT_OLICELP: ::WORD = 0x1002; +pub const WAVE_FORMAT_OLISBC: ::WORD = 0x1003; +pub const WAVE_FORMAT_OLIOPR: ::WORD = 0x1004; +pub const WAVE_FORMAT_LH_CODEC: ::WORD = 0x1100; +pub const WAVE_FORMAT_LH_CODEC_CELP: ::WORD = 0x1101; +pub const WAVE_FORMAT_LH_CODEC_SBC8: ::WORD = 0x1102; +pub const WAVE_FORMAT_LH_CODEC_SBC12: ::WORD = 0x1103; +pub const WAVE_FORMAT_LH_CODEC_SBC16: ::WORD = 0x1104; +pub const WAVE_FORMAT_NORRIS: ::WORD = 0x1400; +pub const WAVE_FORMAT_ISIAUDIO_2: ::WORD = 0x1401; +pub const WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS: ::WORD = 0x1500; +pub const WAVE_FORMAT_MPEG_ADTS_AAC: ::WORD = 0x1600; +pub const WAVE_FORMAT_MPEG_RAW_AAC: ::WORD = 0x1601; +pub const WAVE_FORMAT_MPEG_LOAS: ::WORD = 0x1602; +pub const WAVE_FORMAT_NOKIA_MPEG_ADTS_AAC: ::WORD = 0x1608; +pub const WAVE_FORMAT_NOKIA_MPEG_RAW_AAC: ::WORD = 0x1609; +pub const WAVE_FORMAT_VODAFONE_MPEG_ADTS_AAC: ::WORD = 0x160A; +pub const WAVE_FORMAT_VODAFONE_MPEG_RAW_AAC: ::WORD = 0x160B; +pub const WAVE_FORMAT_MPEG_HEAAC: ::WORD = 0x1610; +pub const WAVE_FORMAT_VOXWARE_RT24_SPEECH: ::WORD = 0x181C; +pub const WAVE_FORMAT_SONICFOUNDRY_LOSSLESS: ::WORD = 0x1971; +pub const WAVE_FORMAT_INNINGS_TELECOM_ADPCM: ::WORD = 0x1979; +pub const WAVE_FORMAT_LUCENT_SX8300P: ::WORD = 0x1C07; +pub const WAVE_FORMAT_LUCENT_SX5363S: ::WORD = 0x1C0C; +pub const WAVE_FORMAT_CUSEEME: ::WORD = 0x1F03; +pub const WAVE_FORMAT_NTCSOFT_ALF2CM_ACM: ::WORD = 0x1FC4; +pub const WAVE_FORMAT_DVM: ::WORD = 0x2000; +pub const WAVE_FORMAT_DTS2: ::WORD = 0x2001; +pub const WAVE_FORMAT_MAKEAVIS: ::WORD = 0x3313; +pub const WAVE_FORMAT_DIVIO_MPEG4_AAC: ::WORD = 0x4143; +pub const WAVE_FORMAT_NOKIA_ADAPTIVE_MULTIRATE: ::WORD = 0x4201; +pub const WAVE_FORMAT_DIVIO_G726: ::WORD = 0x4243; +pub const WAVE_FORMAT_LEAD_SPEECH: ::WORD = 0x434C; +pub const WAVE_FORMAT_LEAD_VORBIS: ::WORD = 0x564C; +pub const WAVE_FORMAT_WAVPACK_AUDIO: ::WORD = 0x5756; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_1: ::WORD = 0x674F; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_2: ::WORD = 0x6750; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_3: ::WORD = 0x6751; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_1_PLUS: ::WORD = 0x676F; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_2_PLUS: ::WORD = 0x6770; +pub const WAVE_FORMAT_OGG_VORBIS_MODE_3_PLUS: ::WORD = 0x6771; +pub const WAVE_FORMAT_3COM_NBX: ::WORD = 0x7000; +pub const WAVE_FORMAT_FAAD_AAC: ::WORD = 0x706D; +pub const WAVE_FORMAT_AMR_NB: ::WORD = 0x7361; +pub const WAVE_FORMAT_AMR_WB: ::WORD = 0x7362; +pub const WAVE_FORMAT_AMR_WP: ::WORD = 0x7363; +pub const WAVE_FORMAT_GSM_AMR_CBR: ::WORD = 0x7A21; +pub const WAVE_FORMAT_GSM_AMR_VBR_SID: ::WORD = 0x7A22; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_G723_1: ::WORD = 0xA100; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_AVQSBC: ::WORD = 0xA101; +pub const WAVE_FORMAT_COMVERSE_INFOSYS_SBC: ::WORD = 0xA102; +pub const WAVE_FORMAT_SYMBOL_G729_A: ::WORD = 0xA103; +pub const WAVE_FORMAT_VOICEAGE_AMR_WB: ::WORD = 0xA104; +pub const WAVE_FORMAT_INGENIENT_G726: ::WORD = 0xA105; +pub const WAVE_FORMAT_MPEG4_AAC: ::WORD = 0xA106; +pub const WAVE_FORMAT_ENCORE_G726: ::WORD = 0xA107; +pub const WAVE_FORMAT_ZOLL_ASAO: ::WORD = 0xA108; +pub const WAVE_FORMAT_SPEEX_VOICE: ::WORD = 0xA109; +pub const WAVE_FORMAT_VIANIX_MASC: ::WORD = 0xA10A; +pub const WAVE_FORMAT_WM9_SPECTRUM_ANALYZER: ::WORD = 0xA10B; +pub const WAVE_FORMAT_WMF_SPECTRUM_ANAYZER: ::WORD = 0xA10C; +pub const WAVE_FORMAT_GSM_610: ::WORD = 0xA10D; +pub const WAVE_FORMAT_GSM_620: ::WORD = 0xA10E; +pub const WAVE_FORMAT_GSM_660: ::WORD = 0xA10F; +pub const WAVE_FORMAT_GSM_690: ::WORD = 0xA110; +pub const WAVE_FORMAT_GSM_ADAPTIVE_MULTIRATE_WB: ::WORD = 0xA111; +pub const WAVE_FORMAT_POLYCOM_G722: ::WORD = 0xA112; +pub const WAVE_FORMAT_POLYCOM_G728: ::WORD = 0xA113; +pub const WAVE_FORMAT_POLYCOM_G729_A: ::WORD = 0xA114; +pub const WAVE_FORMAT_POLYCOM_SIREN: ::WORD = 0xA115; +pub const WAVE_FORMAT_GLOBAL_IP_ILBC: ::WORD = 0xA116; +pub const WAVE_FORMAT_RADIOTIME_TIME_SHIFT_RADIO: ::WORD = 0xA117; +pub const WAVE_FORMAT_NICE_ACA: ::WORD = 0xA118; +pub const WAVE_FORMAT_NICE_ADPCM: ::WORD = 0xA119; +pub const WAVE_FORMAT_VOCORD_G721: ::WORD = 0xA11A; +pub const WAVE_FORMAT_VOCORD_G726: ::WORD = 0xA11B; +pub const WAVE_FORMAT_VOCORD_G722_1: ::WORD = 0xA11C; +pub const WAVE_FORMAT_VOCORD_G728: ::WORD = 0xA11D; +pub const WAVE_FORMAT_VOCORD_G729: ::WORD = 0xA11E; +pub const WAVE_FORMAT_VOCORD_G729_A: ::WORD = 0xA11F; +pub const WAVE_FORMAT_VOCORD_G723_1: ::WORD = 0xA120; +pub const WAVE_FORMAT_VOCORD_LBC: ::WORD = 0xA121; +pub const WAVE_FORMAT_NICE_G728: ::WORD = 0xA122; +pub const WAVE_FORMAT_FRACE_TELECOM_G729: ::WORD = 0xA123; +pub const WAVE_FORMAT_CODIAN: ::WORD = 0xA124; +pub const WAVE_FORMAT_FLAC: ::WORD = 0xF1AC; +pub const WAVE_FORMAT_EXTENSIBLE: ::WORD = 0xFFFE; +pub const WAVE_FORMAT_DEVELOPMENT: ::WORD = 0xFFFF; +//2557 +pub const SPEAKER_FRONT_LEFT: ::DWORD = 0x1; +pub const SPEAKER_FRONT_RIGHT: ::DWORD = 0x2; +pub const SPEAKER_FRONT_CENTER: ::DWORD = 0x4; +pub const SPEAKER_LOW_FREQUENCY: ::DWORD = 0x8; +pub const SPEAKER_BACK_LEFT: ::DWORD = 0x10; +pub const SPEAKER_BACK_RIGHT: ::DWORD = 0x20; +pub const SPEAKER_FRONT_LEFT_OF_CENTER: ::DWORD = 0x40; +pub const SPEAKER_FRONT_RIGHT_OF_CENTER: ::DWORD = 0x80; +pub const SPEAKER_BACK_CENTER: ::DWORD = 0x100; +pub const SPEAKER_SIDE_LEFT: ::DWORD = 0x200; +pub const SPEAKER_SIDE_RIGHT: ::DWORD = 0x400; +pub const SPEAKER_TOP_CENTER: ::DWORD = 0x800; +pub const SPEAKER_TOP_FRONT_LEFT: ::DWORD = 0x1000; +pub const SPEAKER_TOP_FRONT_CENTER: ::DWORD = 0x2000; +pub const SPEAKER_TOP_FRONT_RIGHT: ::DWORD = 0x4000; +pub const SPEAKER_TOP_BACK_LEFT: ::DWORD = 0x8000; +pub const SPEAKER_TOP_BACK_CENTER: ::DWORD = 0x10000; +pub const SPEAKER_TOP_BACK_RIGHT: ::DWORD = 0x20000; +pub const SPEAKER_RESERVED: ::DWORD = 0x7FFC0000; +pub const SPEAKER_ALL: ::DWORD = 0x80000000; +STRUCT!{#[repr(packed)] struct WAVEFORMATEX { + wFormatTag: ::WORD, + nChannels: ::WORD, + nSamplesPerSec: ::DWORD, + nAvgBytesPerSec: ::DWORD, + nBlockAlign: ::WORD, + wBitsPerSample: ::WORD, + cbSize: ::WORD, +}} +STRUCT!{#[repr(packed)] struct WAVEFORMATEXTENSIBLE { + Format: ::WAVEFORMATEX, + Samples: ::WORD, + dwChannelMask: ::DWORD, + SubFormat: ::GUID, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/mmsystem.rs b/third_party/cargo/vendor/winapi-0.2.8/src/mmsystem.rs new file mode 100644 index 0000000..c579eda --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/mmsystem.rs @@ -0,0 +1,259 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! MM procedure declarations, constant definitions and macros +//109 (Win 7 SDK) +pub type MMVERSION = ::UINT; +pub type MMRESULT = ::UINT; +STRUCT!{struct MMTIME { + wType: ::UINT, + u: MMTIME_u, +}} +pub type PMMTIME = *mut MMTIME; +pub type NPMMTIME = *mut MMTIME; +pub type LPMMTIME = *mut MMTIME; +STRUCT!{struct MMTIME_u { + data: [u8; 8], +}} +UNION!(MMTIME_u, data, ms, ms_mut, ::DWORD); +UNION!(MMTIME_u, data, sample, sample_mut, ::DWORD); +UNION!(MMTIME_u, data, cb, cb_mut, ::DWORD); +UNION!(MMTIME_u, data, ticks, ticks_mut, ::DWORD); +UNION!(MMTIME_u, data, smpte, smpte_mut, MMTIME_smpte); +UNION!(MMTIME_u, data, midi, midi_mut, MMTIME_midi); +STRUCT!{struct MMTIME_smpte { + hour: ::BYTE, + min: ::BYTE, + sec: ::BYTE, + frame: ::BYTE, + fps: ::BYTE, + dummy: ::BYTE, + pad: [::BYTE; 2], +}} +STRUCT!{struct MMTIME_midi { + songptrpos: ::DWORD, +}} +pub const TIME_MS: ::UINT = 0x0001; +pub const TIME_SAMPLES: ::UINT = 0x0002; +pub const TIME_BYTES: ::UINT = 0x0004; +pub const TIME_SMPTE: ::UINT = 0x0008; +pub const TIME_MIDI: ::UINT = 0x0010; +pub const TIME_TICKS: ::UINT = 0x0020; +pub const MM_JOY1MOVE: ::UINT = 0x3A0; +pub const MM_JOY2MOVE: ::UINT = 0x3A1; +pub const MM_JOY1ZMOVE: ::UINT = 0x3A2; +pub const MM_JOY2ZMOVE: ::UINT = 0x3A3; +pub const MM_JOY1BUTTONDOWN: ::UINT = 0x3B5; +pub const MM_JOY2BUTTONDOWN: ::UINT = 0x3B6; +pub const MM_JOY1BUTTONUP: ::UINT = 0x3B7; +pub const MM_JOY2BUTTONUP: ::UINT = 0x3B8; +pub const MM_MCINOTIFY: ::UINT = 0x3B9; +pub const MM_WOM_OPEN: ::UINT = 0x3BB; +pub const MM_WOM_CLOSE: ::UINT = 0x3BC; +pub const MM_WOM_DONE: ::UINT = 0x3BD; +pub const MM_WIM_OPEN: ::UINT = 0x3BE; +pub const MM_WIM_CLOSE: ::UINT = 0x3BF; +pub const MM_WIM_DATA: ::UINT = 0x3C0; +pub const MM_MIM_OPEN: ::UINT = 0x3C1; +pub const MM_MIM_CLOSE: ::UINT = 0x3C2; +pub const MM_MIM_DATA: ::UINT = 0x3C3; +pub const MM_MIM_LONGDATA: ::UINT = 0x3C4; +pub const MM_MIM_ERROR: ::UINT = 0x3C5; +pub const MM_MIM_LONGERROR: ::UINT = 0x3C6; +pub const MM_MOM_OPEN: ::UINT = 0x3C7; +pub const MM_MOM_CLOSE: ::UINT = 0x3C8; +pub const MM_MOM_DONE: ::UINT = 0x3C9; +pub const MMSYSERR_BASE: MMRESULT = 0; +pub const WAVERR_BASE: MMRESULT = 32; +pub const MIDIERR_BASE: MMRESULT = 64; +pub const TIMERR_BASE: MMRESULT = 96; +pub const JOYERR_BASE: MMRESULT = 160; +pub const MCIERR_BASE: MMRESULT = 256; +pub const MIXERR_BASE: MMRESULT = 1024; +pub const MMSYSERR_NOERROR: MMRESULT = 0; +pub const MMSYSERR_ERROR: MMRESULT = MMSYSERR_BASE + 1; +pub const MMSYSERR_BADDEVICEID: MMRESULT = MMSYSERR_BASE + 2; +pub const MMSYSERR_NOTENABLED: MMRESULT = MMSYSERR_BASE + 3; +pub const MMSYSERR_ALLOCATED: MMRESULT = MMSYSERR_BASE + 4; +pub const MMSYSERR_INVALHANDLE: MMRESULT = MMSYSERR_BASE + 5; +pub const MMSYSERR_NODRIVER: MMRESULT = MMSYSERR_BASE + 6; +pub const MMSYSERR_NOMEM: MMRESULT = MMSYSERR_BASE + 7; +pub const MMSYSERR_NOTSUPPORTED: MMRESULT = MMSYSERR_BASE + 8; +pub const MMSYSERR_BADERRNUM: MMRESULT = MMSYSERR_BASE + 9; +pub const MMSYSERR_INVALFLAG: MMRESULT = MMSYSERR_BASE + 10; +pub const MMSYSERR_INVALPARAM: MMRESULT = MMSYSERR_BASE + 11; +pub const MMSYSERR_HANDLEBUSY: MMRESULT = MMSYSERR_BASE + 12; +pub const MMSYSERR_INVALIDALIAS: MMRESULT = MMSYSERR_BASE + 13; +pub const MMSYSERR_BADDB: MMRESULT = MMSYSERR_BASE + 14; +pub const MMSYSERR_KEYNOTFOUND: MMRESULT = MMSYSERR_BASE + 15; +pub const MMSYSERR_READERROR: MMRESULT = MMSYSERR_BASE + 16; +pub const MMSYSERR_WRITEERROR: MMRESULT = MMSYSERR_BASE + 17; +pub const MMSYSERR_DELETEERROR: MMRESULT = MMSYSERR_BASE + 18; +pub const MMSYSERR_VALNOTFOUND: MMRESULT = MMSYSERR_BASE + 19; +pub const MMSYSERR_NODRIVERCB: MMRESULT = MMSYSERR_BASE + 20; +pub const MMSYSERR_MOREDATA: MMRESULT = MMSYSERR_BASE + 21; +pub const MMSYSERR_LASTERROR: MMRESULT = MMSYSERR_BASE + 21; +pub const MIDIERR_UNPREPARED: MMRESULT = MIDIERR_BASE + 0; +pub const MIDIERR_STILLPLAYING: MMRESULT = MIDIERR_BASE + 1; +pub const MIDIERR_NOMAP: MMRESULT = MIDIERR_BASE + 2; +pub const MIDIERR_NOTREADY: MMRESULT = MIDIERR_BASE + 3; +pub const MIDIERR_NODEVICE: MMRESULT = MIDIERR_BASE + 4; +pub const MIDIERR_INVALIDSETUP: MMRESULT = MIDIERR_BASE + 5; +pub const MIDIERR_BADOPENMODE: MMRESULT = MIDIERR_BASE + 6; +pub const MIDIERR_DONT_CONTINUE: MMRESULT = MIDIERR_BASE + 7; +pub const MIDIERR_LASTERROR: MMRESULT = MIDIERR_BASE + 7; +pub const CALLBACK_TYPEMASK: ::DWORD = 0x00070000; +pub const CALLBACK_NULL: ::DWORD = 0x00000000; +pub const CALLBACK_WINDOW: ::DWORD = 0x00010000; +pub const CALLBACK_TASK: ::DWORD = 0x00020000; +pub const CALLBACK_FUNCTION: ::DWORD = 0x00030000; +pub const CALLBACK_THREAD: ::DWORD = CALLBACK_TASK; +pub const CALLBACK_EVENT: ::DWORD = 0x00050000; +//497 (Win 7 SDK) +pub const WAVERR_BADFORMAT: MMRESULT = WAVERR_BASE + 0; +pub const WAVERR_STILLPLAYING: MMRESULT = WAVERR_BASE + 1; +pub const WAVERR_UNPREPARED: MMRESULT = WAVERR_BASE + 2; +pub const WAVERR_SYNC: MMRESULT = WAVERR_BASE + 3; +pub const WAVERR_LASTERROR: MMRESULT = WAVERR_BASE + 3; +DECLARE_HANDLE!(HWAVEIN, HWAVEIN__); +DECLARE_HANDLE!(HWAVEOUT, HWAVEOUT__); +pub type LPHWAVEIN = *mut HWAVEIN; +pub type LPHWAVEOUT = *mut HWAVEOUT; +pub const WOM_OPEN: ::UINT = MM_WOM_OPEN; +pub const WOM_CLOSE: ::UINT = MM_WOM_CLOSE; +pub const WOM_DONE: ::UINT = MM_WOM_DONE; +pub const WIM_OPEN: ::UINT = MM_WIM_OPEN; +pub const WIM_CLOSE: ::UINT = MM_WIM_CLOSE; +pub const WIM_DATA: ::UINT = MM_WIM_DATA; +pub const WAVE_MAPPER: ::UINT = 0xFFFFFFFF; +pub const WAVE_FORMAT_QUERY: ::DWORD = 0x0001; +pub const WAVE_ALLOWSYNC: ::DWORD = 0x0002; +pub const WAVE_MAPPED: ::DWORD = 0x0004; +pub const WAVE_FORMAT_DIRECT: ::DWORD = 0x0008; +pub const WAVE_FORMAT_DIRECT_QUERY: ::DWORD = WAVE_FORMAT_QUERY | WAVE_FORMAT_DIRECT; +pub const WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE: ::DWORD = 0x0010; +STRUCT!{struct WAVEHDR { + lpData: ::LPSTR, + dwBufferLength: ::DWORD, + dwBytesRecorded: ::DWORD, + dwUser: ::DWORD_PTR, + dwFlags: ::DWORD, + dwLoops: ::DWORD, + lpNext: *mut WAVEHDR, + reserved: ::DWORD_PTR, +}} +pub type PWAVEHDR = *mut WAVEHDR; +pub type NPWAVEHDR = *mut WAVEHDR; +pub type LPWAVEHDR = *mut WAVEHDR; +STRUCT!{struct WAVEOUTCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwFormats: ::DWORD, + wChannels: ::WORD, + wReserved1: ::WORD, + dwSupport: ::DWORD, +}} +pub type PWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +pub type NPWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +pub type LPWAVEOUTCAPSW = *mut WAVEOUTCAPSW; +STRUCT!{struct WAVEINCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwFormats: ::DWORD, + wChannels: ::WORD, + wReserved1: ::WORD, +}} +pub type PWAVEINCAPSW = *mut WAVEINCAPSW; +pub type NPWAVEINCAPSW = *mut WAVEINCAPSW; +pub type LPWAVEINCAPSW = *mut WAVEINCAPSW; +pub const WAVE_INVALIDFORMAT: ::DWORD = 0x00000000; +pub const WAVE_FORMAT_1M08: ::DWORD = 0x00000001; +pub const WAVE_FORMAT_1S08: ::DWORD = 0x00000002; +pub const WAVE_FORMAT_1M16: ::DWORD = 0x00000004; +pub const WAVE_FORMAT_1S16: ::DWORD = 0x00000008; +pub const WAVE_FORMAT_2M08: ::DWORD = 0x00000010; +pub const WAVE_FORMAT_2S08: ::DWORD = 0x00000020; +pub const WAVE_FORMAT_2M16: ::DWORD = 0x00000040; +pub const WAVE_FORMAT_2S16: ::DWORD = 0x00000080; +pub const WAVE_FORMAT_4M08: ::DWORD = 0x00000100; +pub const WAVE_FORMAT_4S08: ::DWORD = 0x00000200; +pub const WAVE_FORMAT_4M16: ::DWORD = 0x00000400; +pub const WAVE_FORMAT_4S16: ::DWORD = 0x00000800; +pub const WAVE_FORMAT_44M08: ::DWORD = 0x00000100; +pub const WAVE_FORMAT_44S08: ::DWORD = 0x00000200; +pub const WAVE_FORMAT_44M16: ::DWORD = 0x00000400; +pub const WAVE_FORMAT_44S16: ::DWORD = 0x00000800; +pub const WAVE_FORMAT_48M08: ::DWORD = 0x00001000; +pub const WAVE_FORMAT_48S08: ::DWORD = 0x00002000; +pub const WAVE_FORMAT_48M16: ::DWORD = 0x00004000; +pub const WAVE_FORMAT_48S16: ::DWORD = 0x00008000; +pub const WAVE_FORMAT_96M08: ::DWORD = 0x00010000; +pub const WAVE_FORMAT_96S08: ::DWORD = 0x00020000; +pub const WAVE_FORMAT_96M16: ::DWORD = 0x00040000; +pub const WAVE_FORMAT_96S16: ::DWORD = 0x00080000; +//782 (Win 7 SDK) +pub type PWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type NPWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type LPWAVEFORMATEX = *mut ::WAVEFORMATEX; +pub type LPCWAVEFORMATEX = *const ::WAVEFORMATEX; +//2170 (Win 7 SDK) +pub const TIMERR_NOERROR: ::MMRESULT = 0; +pub const TIMERR_NOCANDO: ::MMRESULT = TIMERR_BASE + 1; +pub const TIMERR_STRUCT: ::MMRESULT = TIMERR_BASE + 33; +//2198 (Win 7 SDK) +STRUCT!{struct TIMECAPS { + wPeriodMin: ::UINT, + wPeriodMax: ::UINT, +}} +pub type PTIMECAPS = *mut TIMECAPS; +pub type NPTIMECAPS = *mut TIMECAPS; +pub type LPTIMECAPS = *mut TIMECAPS; +STRUCT!{struct MIDIHDR { + lpData: ::LPSTR, + dwBufferLength: ::DWORD, + dwBytesRecorded: ::DWORD, + dwUser: ::DWORD_PTR, + dwFlags: ::DWORD, + lpNext: *mut MIDIHDR, + reserved: ::DWORD_PTR, + dwOffset: ::DWORD, + dwReserved: [::DWORD_PTR; 4], +}} +pub type PMIDIHDR = *mut MIDIHDR; +pub type NPMIDIHDR = *mut MIDIHDR; +pub type LPMIDIHDR = *mut MIDIHDR; +STRUCT!{struct MIDIINCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: MMVERSION, + szPname: [::WCHAR; 32], + dwSupport: ::DWORD, +}} +pub type PMIDIINCAPSW = *mut MIDIINCAPSW; +pub type NPMIDIINCAPSW = *mut MIDIINCAPSW; +pub type LPMIDIINCAPSW = *mut MIDIINCAPSW; +STRUCT!{struct MIDIOUTCAPSW { + wMid: ::WORD, + wPid: ::WORD, + vDriverVersion: ::MMVERSION, + szPname: [::WCHAR; 32], + wTechnology: ::WORD, + wVoices: ::WORD, + wNotes: ::WORD, + wChannelMask: ::WORD, + dwSupport: ::DWORD, +}} +pub type PMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +pub type NPMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +pub type LPMIDIOUTCAPSW = *mut MIDIOUTCAPSW; +DECLARE_HANDLE!(HMIDIIN, HMIDIIN__); +DECLARE_HANDLE!(HMIDIOUT, HMIDIOUT__); +pub type LPHMIDIIN = *mut HMIDIIN; +pub type LPHMIDIOUT = *mut HMIDIOUT; +DECLARE_HANDLE!(HMIDISTRM, HMIDISTRM__); +DECLARE_HANDLE!(HMIDI, HMIDI__); +pub type LPHMIDISTRM = *mut HMIDISTRM; +pub type LPHMIDI = *mut HMIDI; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/mscat.rs b/third_party/cargo/vendor/winapi-0.2.8/src/mscat.rs new file mode 100644 index 0000000..cc159de --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/mscat.rs @@ -0,0 +1,28 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Microsoft Internet Security Catalog API Prototypes and Definitions +STRUCT!{struct CRYPTCATSTORE { + cbStruct: ::DWORD, + dwPublicVersion: ::DWORD, + pwszP7File: ::LPWSTR, + hProv: ::HCRYPTPROV, + dwEncodingType: ::DWORD, + fdwStoreFlags: ::DWORD, + hReserved: ::HANDLE, + hAttrs: ::HANDLE, + hCryptMsg: ::HCRYPTMSG, + hSorted: ::HANDLE, +}} +STRUCT!{struct CRYPTCATMEMBER { + cbStruct: ::DWORD, + pwszReferenceTag: ::LPWSTR, + pwszFileName: ::LPWSTR, + gSubjectType: ::GUID, + fdwMemberFlags: ::DWORD, + pIndirectData: *mut ::SIP_INDIRECT_DATA, + dwCertVersion: ::DWORD, + dwReserved: ::DWORD, + hReserved: ::HANDLE, + sEncodedIndirectData: ::CRYPT_ATTR_BLOB, + sEncodedMemberInfo: ::CRYPT_ATTR_BLOB, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/mssip.rs b/third_party/cargo/vendor/winapi-0.2.8/src/mssip.rs new file mode 100644 index 0000000..5eeaa7e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/mssip.rs @@ -0,0 +1,103 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Microsoft SIP Provider Prototypes and Definitions +STRUCT!{struct SIP_SUBJECTINFO { + cbSize: ::DWORD, + pgSubjectType: *mut ::GUID, + hFile: ::HANDLE, + pwsFileName: ::LPCWSTR, + pwsDisplayName: ::LPCWSTR, + dwReserved1: ::DWORD, + dwIntVersion: ::DWORD, + hProv: ::HCRYPTPROV, + DigestAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + dwFlags: ::DWORD, + dwEncodingType: ::DWORD, + dwReserved2: ::DWORD, + fdwCAPISettings: ::DWORD, + fdwSecuritySettings: ::DWORD, + dwIndex: ::DWORD, + dwUnionChoice: ::DWORD, + psFlat: *mut MS_ADDINFO_FLAT, + pClientData: ::LPVOID, +}} +UNION!(SIP_SUBJECTINFO, psFlat, psCatMember, psCatMember_mut, *mut MS_ADDINFO_CATALOGMEMBER); +UNION!(SIP_SUBJECTINFO, psFlat, psBlob, psBlob_mut, *mut MS_ADDINFO_BLOB); +pub type LPSIP_SUBJECTINFO = *mut SIP_SUBJECTINFO; +STRUCT!{struct MS_ADDINFO_FLAT { + cbStruct: ::DWORD, + pIndirectData: *mut SIP_INDIRECT_DATA, +}} +pub type PMS_ADDINFO_FLAT = *mut MS_ADDINFO_FLAT; +STRUCT!{struct MS_ADDINFO_CATALOGMEMBER { + cbStruct: ::DWORD, + pStore: *mut ::CRYPTCATSTORE, + pMember: *mut ::CRYPTCATMEMBER, +}} +pub type PMS_ADDINFO_CATALOGMEMBER = *mut MS_ADDINFO_CATALOGMEMBER; +STRUCT!{struct MS_ADDINFO_BLOB { + cbStruct: ::DWORD, + cbMemObject: ::DWORD, + pbMemObject: *mut ::BYTE, + cbMemSignedMsg: ::DWORD, + pbMemSignedMsg: *mut ::BYTE, +}} +pub type PMS_ADDINFO_BLOB = *mut MS_ADDINFO_BLOB; +STRUCT!{struct SIP_INDIRECT_DATA { + Data: ::CRYPT_ATTRIBUTE_TYPE_VALUE, + DigestAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + Digest: ::CRYPT_HASH_BLOB, +}} +pub type PSIP_INDIRECT_DATA = *mut SIP_INDIRECT_DATA; +STRUCT!{struct SIP_ADD_NEWPROVIDER { + cbStruct: ::DWORD, + pgSubject: *mut ::GUID, + pwszDLLFileName: *mut ::WCHAR, + pwszMagicNumber: *mut ::WCHAR, + pwszIsFunctionName: *mut ::WCHAR, + pwszGetFuncName: *mut ::WCHAR, + pwszPutFuncName: *mut ::WCHAR, + pwszCreateFuncName: *mut ::WCHAR, + pwszVerifyFuncName: *mut ::WCHAR, + pwszRemoveFuncName: *mut ::WCHAR, + pwszIsFunctionNameFmt2: *mut ::WCHAR, + pwszGetCapFuncName: ::PWSTR, +}} +pub type PSIP_ADD_NEWPROVIDER = *mut SIP_ADD_NEWPROVIDER; +STRUCT!{struct SIP_CAP_SET_V3 { + cbSize: ::DWORD, + dwVersion: ::DWORD, + isMultiSign: ::BOOL, + dwFlags: ::DWORD, +}} +UNION!(SIP_CAP_SET_V3, dwFlags, dwReserved, dwReserved_mut, ::DWORD); +pub type PSIP_CAP_SET_V3 = *mut SIP_CAP_SET_V3; +pub type SIP_CAP_SET = PSIP_CAP_SET_V3; +pub type pCryptSIPGetSignedDataMsg = Option ::BOOL>; +pub type pCryptSIPPutSignedDataMsg = Option ::BOOL>; +pub type pCryptSIPCreateIndirectData = Option ::BOOL>; +pub type pCryptSIPVerifyIndirectData = Option ::BOOL>; +pub type pCryptSIPRemoveSignedDataMsg = Option ::BOOL>; +STRUCT!{nodebug struct SIP_DISPATCH_INFO { + cbSize: ::DWORD, + hSIP: ::HANDLE, + pfGet: pCryptSIPGetSignedDataMsg, + pfPut: pCryptSIPPutSignedDataMsg, + pfCreate: pCryptSIPCreateIndirectData, + pfVerify: pCryptSIPVerifyIndirectData, + pfRemove: pCryptSIPRemoveSignedDataMsg, +}} +pub type LPSIP_DISPATCH_INFO = *mut SIP_DISPATCH_INFO; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/nb30.rs b/third_party/cargo/vendor/winapi-0.2.8/src/nb30.rs new file mode 100644 index 0000000..26e9dea --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/nb30.rs @@ -0,0 +1,200 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// This module contains the definitions for portable NetBIOS 3.0 support. +pub const NCBNAMSZ: usize = 16; +pub const MAX_LANA: usize = 254; +pub type PFPOST = Option; +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct NCB { + ncb_command: ::UCHAR, + ncb_retcode: ::UCHAR, + ncb_lsn: ::UCHAR, + ncb_num: ::UCHAR, + ncb_buffer: ::PUCHAR, + ncb_length: ::WORD, + ncb_callname: [::UCHAR; NCBNAMSZ], + ncb_name: [::UCHAR; NCBNAMSZ], + ncb_rto: ::UCHAR, + ncb_sto: ::UCHAR, + ncb_post: PFPOST, + ncb_lana_num: ::UCHAR, + ncb_cmd_cplt: ::UCHAR, + ncb_reserve: [::UCHAR; 18], + ncb_event: ::HANDLE, +}} +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct NCB { + ncb_command: ::UCHAR, + ncb_retcode: ::UCHAR, + ncb_lsn: ::UCHAR, + ncb_num: ::UCHAR, + ncb_buffer: ::PUCHAR, + ncb_length: ::WORD, + ncb_callname: [::UCHAR; NCBNAMSZ], + ncb_name: [::UCHAR; NCBNAMSZ], + ncb_rto: ::UCHAR, + ncb_sto: ::UCHAR, + ncb_post: PFPOST, + ncb_lana_num: ::UCHAR, + ncb_cmd_cplt: ::UCHAR, + ncb_reserve: [::UCHAR; 10], + ncb_event: ::HANDLE, +}} +pub type PNCB = *mut NCB; +STRUCT!{struct ADAPTER_STATUS { + adapter_address: [::UCHAR; 6], + rev_major: ::UCHAR, + reserved0: ::UCHAR, + adapter_type: ::UCHAR, + rev_minor: ::UCHAR, + duration: ::WORD, + frmr_recv: ::WORD, + frmr_xmit: ::WORD, + iframe_recv_err: ::WORD, + xmit_aborts: ::WORD, + xmit_success: ::DWORD, + recv_success: ::DWORD, + iframe_xmit_err: ::WORD, + recv_buff_unavail: ::WORD, + t1_timeouts: ::WORD, + ti_timeouts: ::WORD, + reserved1: ::DWORD, + free_ncbs: ::WORD, + max_cfg_ncbs: ::WORD, + max_ncbs: ::WORD, + xmit_buf_unavail: ::WORD, + max_dgram_size: ::WORD, + pending_sess: ::WORD, + max_cfg_sess: ::WORD, + max_sess: ::WORD, + max_sess_pkt_size: ::WORD, + name_count: ::WORD, +}} +pub type PADAPTER_STATUS = *mut ADAPTER_STATUS; +STRUCT!{struct NAME_BUFFER { + name: [::UCHAR; NCBNAMSZ], + name_num: ::UCHAR, + name_flags: ::UCHAR, +}} +pub type PNAME_BUFFER = *mut NAME_BUFFER; +pub const NAME_FLAGS_MASK: ::UCHAR = 0x87; +pub const GROUP_NAME: ::UCHAR = 0x80; +pub const UNIQUE_NAME: ::UCHAR = 0x00; +pub const REGISTERING: ::UCHAR = 0x00; +pub const REGISTERED: ::UCHAR = 0x04; +pub const DEREGISTERED: ::UCHAR = 0x05; +pub const DUPLICATE: ::UCHAR = 0x06; +pub const DUPLICATE_DEREG: ::UCHAR = 0x07; +STRUCT!{struct SESSION_HEADER { + sess_name: ::UCHAR, + num_sess: ::UCHAR, + rcv_dg_outstanding: ::UCHAR, + rcv_any_outstanding: ::UCHAR, +}} +pub type PSESSION_HEADER = *mut SESSION_HEADER; +STRUCT!{struct SESSION_BUFFER { + lsn: ::UCHAR, + state: ::UCHAR, + local_name: [::UCHAR; NCBNAMSZ], + remote_name: [::UCHAR; NCBNAMSZ], + rcvs_outstanding: ::UCHAR, + sends_outstanding: ::UCHAR, +}} +pub type PSESSION_BUFFER = *mut SESSION_BUFFER; +pub const LISTEN_OUTSTANDING: ::UCHAR = 0x01; +pub const CALL_PENDING: ::UCHAR = 0x02; +pub const SESSION_ESTABLISHED: ::UCHAR = 0x03; +pub const HANGUP_PENDING: ::UCHAR = 0x04; +pub const HANGUP_COMPLETE: ::UCHAR = 0x05; +pub const SESSION_ABORTED: ::UCHAR = 0x06; +STRUCT!{nodebug struct LANA_ENUM { + length: ::UCHAR, + lana: [::UCHAR; MAX_LANA + 1], +}} +pub type PLANA_ENUM = *mut LANA_ENUM; +STRUCT!{struct FIND_NAME_HEADER { + node_count: ::WORD, + reserved: ::UCHAR, + unique_group: ::UCHAR, +}} +pub type PFIND_NAME_HEADER = *mut FIND_NAME_HEADER; +STRUCT!{struct FIND_NAME_BUFFER { + length: ::UCHAR, + access_control: ::UCHAR, + frame_control: ::UCHAR, + destination_addr: [::UCHAR; 6], + source_addr: [::UCHAR; 6], + routing_info: [::UCHAR; 18], +}} +pub type PFIND_NAME_BUFFER = *mut FIND_NAME_BUFFER; +STRUCT!{struct ACTION_HEADER { + transport_id: ::ULONG, + action_code: ::USHORT, + reserved: ::USHORT, +}} +pub type PACTION_HEADER = *mut ACTION_HEADER; +pub const NCBCALL: ::UCHAR = 0x10; +pub const NCBLISTEN: ::UCHAR = 0x11; +pub const NCBHANGUP: ::UCHAR = 0x12; +pub const NCBSEND: ::UCHAR = 0x14; +pub const NCBRECV: ::UCHAR = 0x15; +pub const NCBRECVANY: ::UCHAR = 0x16; +pub const NCBCHAINSEND: ::UCHAR = 0x17; +pub const NCBDGSEND: ::UCHAR = 0x20; +pub const NCBDGRECV: ::UCHAR = 0x21; +pub const NCBDGSENDBC: ::UCHAR = 0x22; +pub const NCBADDNAME: ::UCHAR = 0x30; +pub const NCBDELNAME: ::UCHAR = 0x31; +pub const NCBRESET: ::UCHAR = 0x32; +pub const NCBASTAT: ::UCHAR = 0x33; +pub const NCBSSTAT: ::UCHAR = 0x34; +pub const NCBCANCEL: ::UCHAR = 0x35; +pub const NCBADDGRNAME: ::UCHAR = 0x36; +pub const NCBENUM: ::UCHAR = 0x37; +pub const NCBUNLINK: ::UCHAR = 0x70; +pub const NCBSENDNA: ::UCHAR = 0x71; +pub const NCBCHAINSENDNA: ::UCHAR = 0x72; +pub const NCBLANSTALERT: ::UCHAR = 0x73; +pub const NCBACTION: ::UCHAR = 0x77; +pub const NCBFINDNAME: ::UCHAR = 0x78; +pub const NCBTRACE: ::UCHAR = 0x79; +pub const ASYNCH: ::UCHAR = 0x80; +pub const NRC_GOODRET: ::UCHAR = 0x00; +pub const NRC_BUFLEN: ::UCHAR = 0x01; +pub const NRC_ILLCMD: ::UCHAR = 0x03; +pub const NRC_CMDTMO: ::UCHAR = 0x05; +pub const NRC_INCOMP: ::UCHAR = 0x06; +pub const NRC_BADDR: ::UCHAR = 0x07; +pub const NRC_SNUMOUT: ::UCHAR = 0x08; +pub const NRC_NORES: ::UCHAR = 0x09; +pub const NRC_SCLOSED: ::UCHAR = 0x0a; +pub const NRC_CMDCAN: ::UCHAR = 0x0b; +pub const NRC_DUPNAME: ::UCHAR = 0x0d; +pub const NRC_NAMTFUL: ::UCHAR = 0x0e; +pub const NRC_ACTSES: ::UCHAR = 0x0f; +pub const NRC_LOCTFUL: ::UCHAR = 0x11; +pub const NRC_REMTFUL: ::UCHAR = 0x12; +pub const NRC_ILLNN: ::UCHAR = 0x13; +pub const NRC_NOCALL: ::UCHAR = 0x14; +pub const NRC_NOWILD: ::UCHAR = 0x15; +pub const NRC_INUSE: ::UCHAR = 0x16; +pub const NRC_NAMERR: ::UCHAR = 0x17; +pub const NRC_SABORT: ::UCHAR = 0x18; +pub const NRC_NAMCONF: ::UCHAR = 0x19; +pub const NRC_IFBUSY: ::UCHAR = 0x21; +pub const NRC_TOOMANY: ::UCHAR = 0x22; +pub const NRC_BRIDGE: ::UCHAR = 0x23; +pub const NRC_CANOCCR: ::UCHAR = 0x24; +pub const NRC_CANCEL: ::UCHAR = 0x26; +pub const NRC_DUPENV: ::UCHAR = 0x30; +pub const NRC_ENVNOTDEF: ::UCHAR = 0x34; +pub const NRC_OSRESNOTAV: ::UCHAR = 0x35; +pub const NRC_MAXAPPS: ::UCHAR = 0x36; +pub const NRC_NOSAPS: ::UCHAR = 0x37; +pub const NRC_NORESOURCES: ::UCHAR = 0x38; +pub const NRC_INVADDRESS: ::UCHAR = 0x39; +pub const NRC_INVDDID: ::UCHAR = 0x3B; +pub const NRC_LOCKFAIL: ::UCHAR = 0x3C; +pub const NRC_OPENERR: ::UCHAR = 0x3f; +pub const NRC_SYSTEM: ::UCHAR = 0x40; +pub const NRC_PENDING: ::UCHAR = 0xff; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ncrypt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ncrypt.rs new file mode 100644 index 0000000..e730141 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ncrypt.rs @@ -0,0 +1,9 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Cryptographic API Prototypes and Definitions +//191 +pub type NCRYPT_HANDLE = ::ULONG_PTR; +pub type NCRYPT_PROV_HANDLE = ::ULONG_PTR; +pub type NCRYPT_KEY_HANDLE = ::ULONG_PTR; +pub type NCRYPT_HASH_HANDLE = ::ULONG_PTR; +pub type NCRYPT_SECRET_HANDLE = ::ULONG_PTR; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ntdef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ntdef.rs new file mode 100644 index 0000000..2e6f14b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ntdef.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Type definitions for the basic types. +//909 +pub type NTSTATUS = ::LONG; +pub type PNTSTATUS = *mut NTSTATUS; +pub type PCNTSTATUS = *const NTSTATUS; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ntsecapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ntsecapi.rs new file mode 100644 index 0000000..893ea9e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ntsecapi.rs @@ -0,0 +1,1589 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! This module defines the Local Security Authority APIs. +DEFINE_GUID!(Audit_System_SecurityStateChange, 0x0cce9210, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_SecuritySubsystemExtension, 0x0cce9211, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_Integrity, 0x0cce9212, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_IPSecDriverEvents, 0x0cce9213, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System_Others, 0x0cce9214, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Logon, 0x0cce9215, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Logoff, 0x0cce9216, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_AccountLockout, 0x0cce9217, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecMainMode, 0x0cce9218, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecQuickMode, 0x0cce9219, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_IPSecUserMode, 0x0cce921a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_SpecialLogon, 0x0cce921b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Others, 0x0cce921c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FileSystem, 0x0cce921d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Registry, 0x0cce921e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Kernel, 0x0cce921f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Sam, 0x0cce9220, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_CertificationServices, 0x0cce9221, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_ApplicationGenerated, 0x0cce9222, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Handle, 0x0cce9223, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Share, 0x0cce9224, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FirewallPacketDrops, 0x0cce9225, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_FirewallConnection, 0x0cce9226, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_Other, 0x0cce9227, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_Sensitive, 0x0cce9228, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_NonSensitive, 0x0cce9229, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse_Others, 0x0cce922a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_ProcessCreation, 0x0cce922b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_ProcessTermination, 0x0cce922c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_DpapiActivity, 0x0cce922d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking_RpcCall, 0x0cce922e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuditPolicy, 0x0cce922f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuthenticationPolicy, 0x0cce9230, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_AuthorizationPolicy, 0x0cce9231, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_MpsscvRulePolicy, 0x0cce9232, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_WfpIPSecPolicy, 0x0cce9233, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange_Others, 0x0cce9234, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_UserAccount, 0x0cce9235, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_ComputerAccount, 0x0cce9236, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_SecurityGroup, 0x0cce9237, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_DistributionGroup, 0x0cce9238, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_ApplicationGroup, 0x0cce9239, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement_Others, 0x0cce923a, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DSAccess_DSAccess, 0x0cce923b, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DsAccess_AdAuditChanges, 0x0cce923c, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Ds_Replication, 0x0cce923d, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Ds_DetailedReplication, 0x0cce923e, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_CredentialValidation, 0x0cce923f, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_Kerberos, 0x0cce9240, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_Others, 0x0cce9241, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon_KerbCredentialValidation, 0x0cce9242, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_NPS, 0x0cce9243, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_DetailedFileShare, 0x0cce9244, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_RemovableStorage, 0x0cce9245, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess_CbacStaging, 0x0cce9246, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon_Claims, 0x0cce9247, 0x69ae, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_System, 0x69979848, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_Logon, 0x69979849, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_ObjectAccess, 0x6997984a, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PrivilegeUse, 0x6997984b, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DetailedTracking, 0x6997984c, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_PolicyChange, 0x6997984d, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountManagement, 0x6997984e, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_DirectoryServiceAccess, 0x6997984f, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +DEFINE_GUID!(Audit_AccountLogon, 0x69979850, 0x797a, 0x11d9, + 0xbe, 0xd3, 0x50, 0x50, 0x54, 0x50, 0x30, 0x30); +ENUM!{enum POLICY_AUDIT_EVENT_TYPE { + AuditCategorySystem = 0, + AuditCategoryLogon, + AuditCategoryObjectAccess, + AuditCategoryPrivilegeUse, + AuditCategoryDetailedTracking, + AuditCategoryPolicyChange, + AuditCategoryAccountManagement, + AuditCategoryDirectoryServiceAccess, + AuditCategoryAccountLogon, +}} +pub type PPOLICY_AUDIT_EVENT_TYPE = *mut POLICY_AUDIT_EVENT_TYPE; +pub const POLICY_AUDIT_EVENT_UNCHANGED: POLICY_AUDIT_EVENT_OPTIONS = 0x00000000; +pub const POLICY_AUDIT_EVENT_SUCCESS: POLICY_AUDIT_EVENT_OPTIONS = 0x00000001; +pub const POLICY_AUDIT_EVENT_FAILURE: POLICY_AUDIT_EVENT_OPTIONS = 0x00000002; +pub const POLICY_AUDIT_EVENT_NONE: POLICY_AUDIT_EVENT_OPTIONS = 0x00000004; +pub const POLICY_AUDIT_EVENT_MASK: POLICY_AUDIT_EVENT_OPTIONS = POLICY_AUDIT_EVENT_SUCCESS + | POLICY_AUDIT_EVENT_FAILURE | POLICY_AUDIT_EVENT_UNCHANGED | POLICY_AUDIT_EVENT_NONE; +pub const POLICY_VIEW_LOCAL_INFORMATION: ::ACCESS_MASK = 0x00000001; +pub const POLICY_VIEW_AUDIT_INFORMATION: ::ACCESS_MASK = 0x00000002; +pub const POLICY_GET_PRIVATE_INFORMATION: ::ACCESS_MASK = 0x00000004; +pub const POLICY_TRUST_ADMIN: ::ACCESS_MASK = 0x00000008; +pub const POLICY_CREATE_ACCOUNT: ::ACCESS_MASK = 0x00000010; +pub const POLICY_CREATE_SECRET: ::ACCESS_MASK = 0x00000020; +pub const POLICY_CREATE_PRIVILEGE: ::ACCESS_MASK = 0x00000040; +pub const POLICY_SET_DEFAULT_QUOTA_LIMITS: ::ACCESS_MASK = 0x00000080; +pub const POLICY_SET_AUDIT_REQUIREMENTS: ::ACCESS_MASK = 0x00000100; +pub const POLICY_AUDIT_LOG_ADMIN: ::ACCESS_MASK = 0x00000200; +pub const POLICY_SERVER_ADMIN: ::ACCESS_MASK = 0x00000400; +pub const POLICY_LOOKUP_NAMES: ::ACCESS_MASK = 0x00000800; +pub const POLICY_NOTIFICATION: ::ACCESS_MASK = 0x00001000; +pub const POLICY_ALL_ACCESS: ::ACCESS_MASK = ::STANDARD_RIGHTS_REQUIRED + | POLICY_VIEW_LOCAL_INFORMATION | POLICY_VIEW_AUDIT_INFORMATION + | POLICY_GET_PRIVATE_INFORMATION | POLICY_TRUST_ADMIN | POLICY_CREATE_ACCOUNT + | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE | POLICY_SET_DEFAULT_QUOTA_LIMITS + | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN | POLICY_SERVER_ADMIN + | POLICY_LOOKUP_NAMES; +pub const POLICY_READ: ::ACCESS_MASK = ::STANDARD_RIGHTS_READ | POLICY_VIEW_AUDIT_INFORMATION + | POLICY_GET_PRIVATE_INFORMATION; +pub const POLICY_WRITE: ::ACCESS_MASK = ::STANDARD_RIGHTS_WRITE | POLICY_TRUST_ADMIN + | POLICY_CREATE_ACCOUNT | POLICY_CREATE_SECRET | POLICY_CREATE_PRIVILEGE + | POLICY_SET_DEFAULT_QUOTA_LIMITS | POLICY_SET_AUDIT_REQUIREMENTS | POLICY_AUDIT_LOG_ADMIN + | POLICY_SERVER_ADMIN; +pub const POLICY_EXECUTE: ::ACCESS_MASK = ::STANDARD_RIGHTS_EXECUTE + | POLICY_VIEW_LOCAL_INFORMATION | POLICY_LOOKUP_NAMES; +STRUCT!{struct LSA_TRANSLATED_SID { + Use: ::SID_NAME_USE, + RelativeId: ::ULONG, + DomainIndex: ::LONG, +}} +pub type PLSA_TRANSLATED_SID = *mut LSA_TRANSLATED_SID; +ENUM!{enum POLICY_LSA_SERVER_ROLE { + PolicyServerRoleBackup = 2, + PolicyServerRolePrimary, +}} +pub type PPOLICY_LSA_SERVER_ROLE = *mut POLICY_LSA_SERVER_ROLE; +pub type POLICY_AUDIT_EVENT_OPTIONS = ::ULONG; +pub type PPOLICY_AUDIT_EVENT_OPTIONS = *mut ::ULONG; +ENUM!{enum POLICY_INFORMATION_CLASS { + PolicyAuditLogInformation = 1, + PolicyAuditEventsInformation, + PolicyPrimaryDomainInformation, + PolicyPdAccountInformation, + PolicyAccountDomainInformation, + PolicyLsaServerRoleInformation, + PolicyReplicaSourceInformation, + PolicyDefaultQuotaInformation, + PolicyModificationInformation, + PolicyAuditFullSetInformation, + PolicyAuditFullQueryInformation, + PolicyDnsDomainInformation, + PolicyDnsDomainInformationInt, + PolicyLocalAccountDomainInformation, + PolicyLastEntry, +}} +pub type PPOLICY_INFORMATION_CLASS = *mut POLICY_INFORMATION_CLASS; +STRUCT!{struct POLICY_AUDIT_LOG_INFO { + AuditLogPercentFull: ::ULONG, + MaximumLogSize: ::ULONG, + AuditRetentionPeriod: ::LARGE_INTEGER, + AuditLogFullShutdownInProgress: ::BOOLEAN, + TimeToShutdown: ::LARGE_INTEGER, + NextAuditRecordId: ::ULONG, +}} +pub type PPOLICY_AUDIT_LOG_INFO = *mut POLICY_AUDIT_LOG_INFO; +STRUCT!{struct POLICY_AUDIT_EVENTS_INFO { + AuditingMode: ::BOOLEAN, + EventAuditingOptions: PPOLICY_AUDIT_EVENT_OPTIONS, + MaximumAuditEventCount: ::ULONG, +}} +pub type PPOLICY_AUDIT_EVENTS_INFO = *mut POLICY_AUDIT_EVENTS_INFO; +STRUCT!{struct POLICY_AUDIT_SUBCATEGORIES_INFO { + MaximumSubCategoryCount: ::ULONG, + EventAuditingOptions: PPOLICY_AUDIT_EVENT_OPTIONS, +}} +pub type PPOLICY_AUDIT_SUBCATEGORIES_INFO = *mut POLICY_AUDIT_SUBCATEGORIES_INFO; +STRUCT!{struct POLICY_AUDIT_CATEGORIES_INFO { + MaximumSubCategoryCount: ::ULONG, + SubCategoriesInfo: PPOLICY_AUDIT_SUBCATEGORIES_INFO, +}} +pub type PPOLICY_AUDIT_CATEGORIES_INFO = *mut POLICY_AUDIT_CATEGORIES_INFO; +pub const PER_USER_POLICY_UNCHANGED: ::ULONG = 0x00; +pub const PER_USER_AUDIT_SUCCESS_INCLUDE: ::ULONG = 0x01; +pub const PER_USER_AUDIT_SUCCESS_EXCLUDE: ::ULONG = 0x02; +pub const PER_USER_AUDIT_FAILURE_INCLUDE: ::ULONG = 0x04; +pub const PER_USER_AUDIT_FAILURE_EXCLUDE: ::ULONG = 0x08; +pub const PER_USER_AUDIT_NONE: ::ULONG = 0x10; +pub const VALID_PER_USER_AUDIT_POLICY_FLAG: ::ULONG = PER_USER_AUDIT_SUCCESS_INCLUDE + | PER_USER_AUDIT_SUCCESS_EXCLUDE | PER_USER_AUDIT_FAILURE_INCLUDE + | PER_USER_AUDIT_FAILURE_EXCLUDE | PER_USER_AUDIT_NONE; +STRUCT!{struct POLICY_PRIMARY_DOMAIN_INFO { + Name: ::LSA_UNICODE_STRING, + Sid: ::PSID, +}} +pub type PPOLICY_PRIMARY_DOMAIN_INFO = *mut POLICY_PRIMARY_DOMAIN_INFO; +STRUCT!{struct POLICY_PD_ACCOUNT_INFO { + Name: ::LSA_UNICODE_STRING, +}} +pub type PPOLICY_PD_ACCOUNT_INFO = *mut POLICY_PD_ACCOUNT_INFO; +STRUCT!{struct POLICY_LSA_SERVER_ROLE_INFO { + LsaServerRole: POLICY_LSA_SERVER_ROLE, +}} +pub type PPOLICY_LSA_SERVER_ROLE_INFO = *mut POLICY_LSA_SERVER_ROLE_INFO; +STRUCT!{struct POLICY_REPLICA_SOURCE_INFO { + ReplicaSource: ::LSA_UNICODE_STRING, + ReplicaAccountName: ::LSA_UNICODE_STRING, +}} +pub type PPOLICY_REPLICA_SOURCE_INFO = *mut POLICY_REPLICA_SOURCE_INFO; +STRUCT!{struct POLICY_DEFAULT_QUOTA_INFO { + QuotaLimits: ::QUOTA_LIMITS, +}} +pub type PPOLICY_DEFAULT_QUOTA_INFO = *mut POLICY_DEFAULT_QUOTA_INFO; +STRUCT!{struct POLICY_MODIFICATION_INFO { + ModifiedId: ::LARGE_INTEGER, + DatabaseCreationTime: ::LARGE_INTEGER, +}} +pub type PPOLICY_MODIFICATION_INFO = *mut POLICY_MODIFICATION_INFO; +STRUCT!{struct POLICY_AUDIT_FULL_SET_INFO { + ShutDownOnFull: ::BOOLEAN, +}} +pub type PPOLICY_AUDIT_FULL_SET_INFO = *mut POLICY_AUDIT_FULL_SET_INFO; +STRUCT!{struct POLICY_AUDIT_FULL_QUERY_INFO { + ShutDownOnFull: ::BOOLEAN, + LogIsFull: ::BOOLEAN, +}} +pub type PPOLICY_AUDIT_FULL_QUERY_INFO = *mut POLICY_AUDIT_FULL_QUERY_INFO; +ENUM!{enum POLICY_DOMAIN_INFORMATION_CLASS { + PolicyDomainEfsInformation = 2, + PolicyDomainKerberosTicketInformation, +}} +pub type PPOLICY_DOMAIN_INFORMATION_CLASS = *mut POLICY_DOMAIN_INFORMATION_CLASS; +STRUCT!{struct POLICY_DOMAIN_EFS_INFO { + InfoLength: ::ULONG, + EfsBlob: ::PUCHAR, +}} +pub type PPOLICY_DOMAIN_EFS_INFO = *mut POLICY_DOMAIN_EFS_INFO; +STRUCT!{struct POLICY_DOMAIN_KERBEROS_TICKET_INFO { + AuthenticationOptions: ::ULONG, + MaxServiceTicketAge: ::LARGE_INTEGER, + MaxTicketAge: ::LARGE_INTEGER, + MaxRenewAge: ::LARGE_INTEGER, + MaxClockSkew: ::LARGE_INTEGER, + Reserved: ::LARGE_INTEGER, +}} +pub type PPOLICY_DOMAIN_KERBEROS_TICKET_INFO = *mut POLICY_DOMAIN_KERBEROS_TICKET_INFO; +ENUM!{enum POLICY_NOTIFICATION_INFORMATION_CLASS { + PolicyNotifyAuditEventsInformation = 1, + PolicyNotifyAccountDomainInformation, + PolicyNotifyServerRoleInformation, + PolicyNotifyDnsDomainInformation, + PolicyNotifyDomainEfsInformation, + PolicyNotifyDomainKerberosTicketInformation, + PolicyNotifyMachineAccountPasswordInformation, + PolicyNotifyGlobalSaclInformation, + PolicyNotifyMax, +}} +pub type PPOLICY_NOTIFICATION_INFORMATION_CLASS = *mut POLICY_NOTIFICATION_INFORMATION_CLASS; +pub type LSA_HANDLE = ::PVOID; +pub type PLSA_HANDLE = *mut ::PVOID; +ENUM!{enum TRUSTED_INFORMATION_CLASS { + TrustedDomainNameInformation = 1, + TrustedControllersInformation, + TrustedPosixOffsetInformation, + TrustedPasswordInformation, + TrustedDomainInformationBasic, + TrustedDomainInformationEx, + TrustedDomainAuthInformation, + TrustedDomainFullInformation, + TrustedDomainAuthInformationInternal, + TrustedDomainFullInformationInternal, + TrustedDomainInformationEx2Internal, + TrustedDomainFullInformation2Internal, + TrustedDomainSupportedEncryptionTypes, +}} +pub type PTRUSTED_INFORMATION_CLASS = *mut TRUSTED_INFORMATION_CLASS; +STRUCT!{struct TRUSTED_DOMAIN_NAME_INFO { + Name: ::LSA_UNICODE_STRING, +}} +pub type PTRUSTED_DOMAIN_NAME_INFO = *mut TRUSTED_DOMAIN_NAME_INFO; +STRUCT!{struct TRUSTED_CONTROLLERS_INFO { + Entries: ::ULONG, + Names: ::PLSA_UNICODE_STRING, +}} +pub type PTRUSTED_CONTROLLERS_INFO = *mut TRUSTED_CONTROLLERS_INFO; +STRUCT!{struct TRUSTED_POSIX_OFFSET_INFO { + Offset: ::ULONG, +}} +pub type PTRUSTED_POSIX_OFFSET_INFO = *mut TRUSTED_POSIX_OFFSET_INFO; +STRUCT!{struct TRUSTED_PASSWORD_INFO { + Password: ::LSA_UNICODE_STRING, + OldPassword: ::LSA_UNICODE_STRING, +}} +pub type PTRUSTED_PASSWORD_INFO = *mut TRUSTED_PASSWORD_INFO; +pub type TRUSTED_DOMAIN_INFORMATION_BASIC = ::LSA_TRUST_INFORMATION; +pub type PTRUSTED_DOMAIN_INFORMATION_BASIC = ::PLSA_TRUST_INFORMATION; +pub const TRUST_DIRECTION_DISABLED: ::ULONG = 0x00000000; +pub const TRUST_DIRECTION_INBOUND: ::ULONG = 0x00000001; +pub const TRUST_DIRECTION_OUTBOUND: ::ULONG = 0x00000002; +pub const TRUST_DIRECTION_BIDIRECTIONAL: ::ULONG = TRUST_DIRECTION_INBOUND + | TRUST_DIRECTION_OUTBOUND; +pub const TRUST_TYPE_DOWNLEVEL: ::ULONG = 0x00000001; +pub const TRUST_TYPE_UPLEVEL: ::ULONG = 0x00000002; +pub const TRUST_TYPE_MIT: ::ULONG = 0x00000003; +pub const TRUST_ATTRIBUTE_NON_TRANSITIVE: ::ULONG = 0x00000001; +pub const TRUST_ATTRIBUTE_UPLEVEL_ONLY: ::ULONG = 0x00000002; +pub const TRUST_ATTRIBUTE_QUARANTINED_DOMAIN: ::ULONG = 0x00000004; +pub const TRUST_ATTRIBUTE_FOREST_TRANSITIVE: ::ULONG = 0x00000008; +pub const TRUST_ATTRIBUTE_CROSS_ORGANIZATION: ::ULONG = 0x00000010; +pub const TRUST_ATTRIBUTE_WITHIN_FOREST: ::ULONG = 0x00000020; +pub const TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL: ::ULONG = 0x00000040; +pub const TRUST_ATTRIBUTE_TRUST_USES_RC4_ENCRYPTION: ::ULONG = 0x00000080; +pub const TRUST_ATTRIBUTE_TRUST_USES_AES_KEYS: ::ULONG = 0x00000100; +pub const TRUST_ATTRIBUTE_CROSS_ORGANIZATION_NO_TGT_DELEGATION: ::ULONG = 0x00000200; +pub const TRUST_ATTRIBUTES_VALID: ::ULONG = 0xFF03FFFF; +pub const TRUST_ATTRIBUTES_USER: ::ULONG = 0xFF000000; +STRUCT!{struct TRUSTED_DOMAIN_INFORMATION_EX { + Name: ::LSA_UNICODE_STRING, + FlatName: ::LSA_UNICODE_STRING, + Sid: ::PSID, + TrustDirection: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, +}} +pub type PTRUSTED_DOMAIN_INFORMATION_EX = *mut TRUSTED_DOMAIN_INFORMATION_EX; +STRUCT!{struct TRUSTED_DOMAIN_INFORMATION_EX2 { + Name: ::LSA_UNICODE_STRING, + FlatName: ::LSA_UNICODE_STRING, + Sid: ::PSID, + TrustDirection: ::ULONG, + TrustType: ::ULONG, + TrustAttributes: ::ULONG, + ForestTrustLength: ::ULONG, + ForestTrustInfo: ::PUCHAR, +}} +pub type PTRUSTED_DOMAIN_INFORMATION_EX2 = *mut TRUSTED_DOMAIN_INFORMATION_EX2; +pub const TRUST_AUTH_TYPE_NONE: ::ULONG = 0; +pub const TRUST_AUTH_TYPE_NT4OWF: ::ULONG = 1; +pub const TRUST_AUTH_TYPE_CLEAR: ::ULONG = 2; +pub const TRUST_AUTH_TYPE_VERSION: ::ULONG = 3; +STRUCT!{struct LSA_AUTH_INFORMATION { + LastUpdateTime: ::LARGE_INTEGER, + AuthType: ::ULONG, + AuthInfoLength: ::ULONG, + AuthInfo: ::PUCHAR, +}} +pub type PLSA_AUTH_INFORMATION = *mut LSA_AUTH_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_AUTH_INFORMATION { + IncomingAuthInfos: ::ULONG, + IncomingAuthenticationInformation: PLSA_AUTH_INFORMATION, + IncomingPreviousAuthenticationInformation: PLSA_AUTH_INFORMATION, + OutgoingAuthInfos: ::ULONG, + OutgoingAuthenticationInformation: PLSA_AUTH_INFORMATION, + OutgoingPreviousAuthenticationInformation: PLSA_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_AUTH_INFORMATION = *mut TRUSTED_DOMAIN_AUTH_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_FULL_INFORMATION { + Information: TRUSTED_DOMAIN_INFORMATION_EX, + PosixOffset: TRUSTED_POSIX_OFFSET_INFO, + AuthInformation: TRUSTED_DOMAIN_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_FULL_INFORMATION = *mut TRUSTED_DOMAIN_FULL_INFORMATION; +STRUCT!{struct TRUSTED_DOMAIN_FULL_INFORMATION2 { + Information: TRUSTED_DOMAIN_INFORMATION_EX2, + PosixOffset: TRUSTED_POSIX_OFFSET_INFO, + AuthInformation: TRUSTED_DOMAIN_AUTH_INFORMATION, +}} +pub type PTRUSTED_DOMAIN_FULL_INFORMATION2 = *mut TRUSTED_DOMAIN_FULL_INFORMATION2; +STRUCT!{struct TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES { + SupportedEncryptionTypes: ::ULONG, +}} +pub type PTRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES = + *mut TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES; +ENUM!{enum LSA_FOREST_TRUST_RECORD_TYPE { + ForestTrustTopLevelName, + ForestTrustTopLevelNameEx, + ForestTrustDomainInfo, + ForestTrustRecordTypeLast, // = ForestTrustDomainInfo, +}} +pub const LSA_FTRECORD_DISABLED_REASONS: ::ULONG = 0x0000FFFF; +pub const LSA_TLN_DISABLED_NEW: ::ULONG = 0x00000001; +pub const LSA_TLN_DISABLED_ADMIN: ::ULONG = 0x00000002; +pub const LSA_TLN_DISABLED_CONFLICT: ::ULONG = 0x00000004; +pub const LSA_SID_DISABLED_ADMIN: ::ULONG = 0x00000001; +pub const LSA_SID_DISABLED_CONFLICT: ::ULONG = 0x00000002; +pub const LSA_NB_DISABLED_ADMIN: ::ULONG = 0x00000004; +pub const LSA_NB_DISABLED_CONFLICT: ::ULONG = 0x00000008; +STRUCT!{struct LSA_FOREST_TRUST_DOMAIN_INFO { + Sid: ::PSID, + DnsName: ::LSA_UNICODE_STRING, + NetbiosName: ::LSA_UNICODE_STRING, +}} +pub type PLSA_FOREST_TRUST_DOMAIN_INFO = *mut LSA_FOREST_TRUST_DOMAIN_INFO; +pub const MAX_FOREST_TRUST_BINARY_DATA_SIZE: ::ULONG = 128 * 1024; +STRUCT!{struct LSA_FOREST_TRUST_BINARY_DATA { + Length: ::ULONG, + Buffer: ::PUCHAR, +}} +pub type PLSA_FOREST_TRUST_BINARY_DATA = *mut LSA_FOREST_TRUST_BINARY_DATA; +STRUCT!{struct LSA_FOREST_TRUST_RECORD_ForestTrustData { + DomainInfo: LSA_FOREST_TRUST_DOMAIN_INFO, +}} +UNION!( + LSA_FOREST_TRUST_RECORD_ForestTrustData, DomainInfo, TopLevelName, TopLevelName_mut, + ::LSA_UNICODE_STRING +); +UNION!( + LSA_FOREST_TRUST_RECORD_ForestTrustData, DomainInfo, Data, Data_mut, + LSA_FOREST_TRUST_BINARY_DATA +); +STRUCT!{struct LSA_FOREST_TRUST_RECORD { + Flags: ::ULONG, + ForestTrustType: LSA_FOREST_TRUST_RECORD_TYPE, + Time: ::LARGE_INTEGER, + ForestTrustData: LSA_FOREST_TRUST_RECORD_ForestTrustData, +}} +pub type PLSA_FOREST_TRUST_RECORD = *mut LSA_FOREST_TRUST_RECORD; +pub const MAX_RECORDS_IN_FOREST_TRUST_INFO: ::ULONG = 4000; +STRUCT!{struct LSA_FOREST_TRUST_INFORMATION { + RecordCount: ::ULONG, + Entries: *mut PLSA_FOREST_TRUST_RECORD, +}} +pub type PLSA_FOREST_TRUST_INFORMATION = *mut LSA_FOREST_TRUST_INFORMATION; +ENUM!{enum LSA_FOREST_TRUST_COLLISION_RECORD_TYPE { + CollisionTdo, + CollisionXref, + CollisionOther, +}} +STRUCT!{struct LSA_FOREST_TRUST_COLLISION_RECORD { + Index: ::ULONG, + Type: LSA_FOREST_TRUST_COLLISION_RECORD_TYPE, + Flags: ::ULONG, + Name: ::LSA_UNICODE_STRING, +}} +pub type PLSA_FOREST_TRUST_COLLISION_RECORD = *mut LSA_FOREST_TRUST_COLLISION_RECORD; +STRUCT!{struct LSA_FOREST_TRUST_COLLISION_INFORMATION { + RecordCount: ::ULONG, + Entries: *mut PLSA_FOREST_TRUST_COLLISION_RECORD, +}} +pub type PLSA_FOREST_TRUST_COLLISION_INFORMATION = *mut LSA_FOREST_TRUST_COLLISION_INFORMATION; +pub type LSA_ENUMERATION_HANDLE = ::ULONG; +pub type PLSA_ENUMERATION_HANDLE = *mut ::ULONG; +STRUCT!{struct LSA_ENUMERATION_INFORMATION { + Sid: ::PSID, +}} +pub type PLSA_ENUMERATION_INFORMATION = *mut LSA_ENUMERATION_INFORMATION; +STRUCT!{struct LSA_LAST_INTER_LOGON_INFO { + LastSuccessfulLogon: ::LARGE_INTEGER, + LastFailedLogon: ::LARGE_INTEGER, + FailedAttemptCountSinceLastSuccessfulLogon: ::ULONG, +}} +pub type PLSA_LAST_INTER_LOGON_INFO = *mut LSA_LAST_INTER_LOGON_INFO; +STRUCT!{struct SECURITY_LOGON_SESSION_DATA { + Size: ::ULONG, + LogonId: ::LUID, + UserName: ::LSA_UNICODE_STRING, + LogonDomain: ::LSA_UNICODE_STRING, + AuthenticationPackage: ::LSA_UNICODE_STRING, + LogonType: ::ULONG, + Session: ::ULONG, + Sid: ::PSID, + LogonTime: ::LARGE_INTEGER, + LogonServer: ::LSA_UNICODE_STRING, + DnsDomainName: ::LSA_UNICODE_STRING, + Upn: ::LSA_UNICODE_STRING, + UserFlags: ::ULONG, + LastLogonInfo: LSA_LAST_INTER_LOGON_INFO, + LogonScript: ::LSA_UNICODE_STRING, + ProfilePath: ::LSA_UNICODE_STRING, + HomeDirectory: ::LSA_UNICODE_STRING, + HomeDirectoryDrive: ::LSA_UNICODE_STRING, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, +}} +pub type PSECURITY_LOGON_SESSION_DATA = *mut SECURITY_LOGON_SESSION_DATA; +pub const CENTRAL_ACCESS_POLICY_OWNER_RIGHTS_PRESENT_FLAG: ::ULONG = 0x00000001; +pub const CENTRAL_ACCESS_POLICY_STAGED_OWNER_RIGHTS_PRESENT_FLAG: ::ULONG = 0x00000100; +pub const CENTRAL_ACCESS_POLICY_STAGED_FLAG: ::ULONG = 0x00010000; +pub const CENTRAL_ACCESS_POLICY_VALID_FLAG_MASK: ::ULONG = + CENTRAL_ACCESS_POLICY_OWNER_RIGHTS_PRESENT_FLAG + | CENTRAL_ACCESS_POLICY_STAGED_OWNER_RIGHTS_PRESENT_FLAG | CENTRAL_ACCESS_POLICY_STAGED_FLAG; +pub const LSASETCAPS_RELOAD_FLAG: ::ULONG = 0x00000001; +pub const LSASETCAPS_VALID_FLAG_MASK: ::ULONG = LSASETCAPS_RELOAD_FLAG; +STRUCT!{struct CENTRAL_ACCESS_POLICY_ENTRY { + Name: ::LSA_UNICODE_STRING, + Description: ::LSA_UNICODE_STRING, + ChangeId: ::LSA_UNICODE_STRING, + LengthAppliesTo: ::ULONG, + AppliesTo: ::PUCHAR, + LengthSD: ::ULONG, + SD: ::PSECURITY_DESCRIPTOR, + LengthStagedSD: ::ULONG, + StagedSD: ::PSECURITY_DESCRIPTOR, + Flags: ::ULONG, +}} +pub type PCENTRAL_ACCESS_POLICY_ENTRY = *mut CENTRAL_ACCESS_POLICY_ENTRY; +pub type PCCENTRAL_ACCESS_POLICY_ENTRY = *const CENTRAL_ACCESS_POLICY_ENTRY; +STRUCT!{struct CENTRAL_ACCESS_POLICY { + CAPID: ::PSID, + Name: ::LSA_UNICODE_STRING, + Description: ::LSA_UNICODE_STRING, + ChangeId: ::LSA_UNICODE_STRING, + Flags: ::ULONG, + CAPECount: ::ULONG, + CAPEs: *mut PCENTRAL_ACCESS_POLICY_ENTRY, +}} +pub type PCENTRAL_ACCESS_POLICY = *mut CENTRAL_ACCESS_POLICY; +pub type PCCENTRAL_ACCESS_POLICY = *const CENTRAL_ACCESS_POLICY; +ENUM!{enum NEGOTIATE_MESSAGES { + NegEnumPackagePrefixes = 0, + NegGetCallerName = 1, + NegTransferCredentials = 2, + NegCallPackageMax, +}} +pub const NEGOTIATE_MAX_PREFIX: usize = 32; +STRUCT!{struct NEGOTIATE_PACKAGE_PREFIX { + PackageId: ::ULONG_PTR, + PackageDataA: ::PVOID, + PackageDataW: ::PVOID, + PrefixLen: ::ULONG_PTR, + Prefix: [::UCHAR; NEGOTIATE_MAX_PREFIX], +}} +pub type PNEGOTIATE_PACKAGE_PREFIX = *mut NEGOTIATE_PACKAGE_PREFIX; +STRUCT!{struct NEGOTIATE_PACKAGE_PREFIXES { + MessageType: ::ULONG, + PrefixCount: ::ULONG, + Offset: ::ULONG, + Pad: ::ULONG, +}} +pub type PNEGOTIATE_PACKAGE_PREFIXES = *mut NEGOTIATE_PACKAGE_PREFIXES; +STRUCT!{struct NEGOTIATE_CALLER_NAME_REQUEST { + MessageType: ::ULONG, + LogonId: ::LUID, +}} +pub type PNEGOTIATE_CALLER_NAME_REQUEST = *mut NEGOTIATE_CALLER_NAME_REQUEST; +STRUCT!{struct NEGOTIATE_CALLER_NAME_RESPONSE { + MessageType: ::ULONG, + CallerName: ::PWSTR, +}} +pub type PNEGOTIATE_CALLER_NAME_RESPONSE = *mut NEGOTIATE_CALLER_NAME_RESPONSE; +STRUCT!{struct DOMAIN_PASSWORD_INFORMATION { + MinPasswordLength: ::USHORT, + PasswordHistoryLength: ::USHORT, + PasswordProperties: ::ULONG, + MaxPasswordAge: ::LARGE_INTEGER, + MinPasswordAge: ::LARGE_INTEGER, +}} +pub type PDOMAIN_PASSWORD_INFORMATION = *mut DOMAIN_PASSWORD_INFORMATION; +pub const DOMAIN_PASSWORD_COMPLEX: ::ULONG = 0x00000001; +pub const DOMAIN_PASSWORD_NO_ANON_CHANGE: ::ULONG = 0x00000002; +pub const DOMAIN_PASSWORD_NO_CLEAR_CHANGE: ::ULONG = 0x00000004; +pub const DOMAIN_LOCKOUT_ADMINS: ::ULONG = 0x00000008; +pub const DOMAIN_PASSWORD_STORE_CLEARTEXT: ::ULONG = 0x00000010; +pub const DOMAIN_REFUSE_PASSWORD_CHANGE: ::ULONG = 0x00000020; +pub const DOMAIN_NO_LM_OWF_CHANGE: ::ULONG = 0x00000040; +pub type PSAM_PASSWORD_NOTIFICATION_ROUTINE = Option ::NTSTATUS>; +pub type PSAM_INIT_NOTIFICATION_ROUTINE = Option ::BOOLEAN>; +pub type PSAM_PASSWORD_FILTER_ROUTINE = Option ::BOOLEAN>; +ENUM!{enum MSV1_0_LOGON_SUBMIT_TYPE { + MsV1_0InteractiveLogon = 2, + MsV1_0Lm20Logon, + MsV1_0NetworkLogon, + MsV1_0SubAuthLogon, + MsV1_0WorkstationUnlockLogon = 7, + MsV1_0S4ULogon = 12, + MsV1_0VirtualLogon = 82, + MsV1_0NoElevationLogon = 83, + MsV1_0LuidLogon = 84, +}} +pub type PMSV1_0_LOGON_SUBMIT_TYPE = *mut MSV1_0_LOGON_SUBMIT_TYPE; +ENUM!{enum MSV1_0_PROFILE_BUFFER_TYPE { + MsV1_0InteractiveProfile = 2, + MsV1_0Lm20LogonProfile, + MsV1_0SmartCardProfile, +}} +pub type PMSV1_0_PROFILE_BUFFER_TYPE = *mut MSV1_0_PROFILE_BUFFER_TYPE; +STRUCT!{struct MSV1_0_INTERACTIVE_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PMSV1_0_INTERACTIVE_LOGON = *mut MSV1_0_INTERACTIVE_LOGON; +STRUCT!{struct MSV1_0_INTERACTIVE_PROFILE { + MessageType: MSV1_0_PROFILE_BUFFER_TYPE, + LogonCount: ::USHORT, + BadPasswordCount: ::USHORT, + LogonTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + LogonScript: ::UNICODE_STRING, + HomeDirectory: ::UNICODE_STRING, + FullName: ::UNICODE_STRING, + ProfilePath: ::UNICODE_STRING, + HomeDirectoryDrive: ::UNICODE_STRING, + LogonServer: ::UNICODE_STRING, + UserFlags: ::ULONG, +}} +pub type PMSV1_0_INTERACTIVE_PROFILE = *mut MSV1_0_INTERACTIVE_PROFILE; +pub const MSV1_0_CHALLENGE_LENGTH: usize = 8; +pub const MSV1_0_USER_SESSION_KEY_LENGTH: usize = 16; +pub const MSV1_0_LANMAN_SESSION_KEY_LENGTH: usize = 8; +pub const MSV1_0_CLEARTEXT_PASSWORD_ALLOWED: ::ULONG = 0x02; +pub const MSV1_0_UPDATE_LOGON_STATISTICS: ::ULONG = 0x04; +pub const MSV1_0_RETURN_USER_PARAMETERS: ::ULONG = 0x08; +pub const MSV1_0_DONT_TRY_GUEST_ACCOUNT: ::ULONG = 0x10; +pub const MSV1_0_ALLOW_SERVER_TRUST_ACCOUNT: ::ULONG = 0x20; +pub const MSV1_0_RETURN_PASSWORD_EXPIRY: ::ULONG = 0x40; +pub const MSV1_0_USE_CLIENT_CHALLENGE: ::ULONG = 0x80; +pub const MSV1_0_TRY_GUEST_ACCOUNT_ONLY: ::ULONG = 0x100; +pub const MSV1_0_RETURN_PROFILE_PATH: ::ULONG = 0x200; +pub const MSV1_0_TRY_SPECIFIED_DOMAIN_ONLY: ::ULONG = 0x400; +pub const MSV1_0_ALLOW_WORKSTATION_TRUST_ACCOUNT: ::ULONG = 0x800; +pub const MSV1_0_DISABLE_PERSONAL_FALLBACK: ::ULONG = 0x00001000; +pub const MSV1_0_ALLOW_FORCE_GUEST: ::ULONG = 0x00002000; +pub const MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED: ::ULONG = 0x00004000; +pub const MSV1_0_USE_DOMAIN_FOR_ROUTING_ONLY: ::ULONG = 0x00008000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_EX: ::ULONG = 0x00100000; +pub const MSV1_0_ALLOW_MSVCHAPV2: ::ULONG = 0x00010000; +pub const MSV1_0_S4U2SELF: ::ULONG = 0x00020000; +pub const MSV1_0_CHECK_LOGONHOURS_FOR_S4U: ::ULONG = 0x00040000; +pub const MSV1_0_INTERNET_DOMAIN: ::ULONG = 0x00080000; +pub const MSV1_0_SUBAUTHENTICATION_DLL: ::ULONG = 0xFF000000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_SHIFT: ::ULONG = 24; +pub const MSV1_0_MNS_LOGON: ::ULONG = 0x01000000; +pub const MSV1_0_SUBAUTHENTICATION_DLL_RAS: ::ULONG = 2; +pub const MSV1_0_SUBAUTHENTICATION_DLL_IIS: ::ULONG = 132; +STRUCT!{struct MSV1_0_LM20_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Workstation: ::UNICODE_STRING, + ChallengeToClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + CaseSensitiveChallengeResponse: ::STRING, + CaseInsensitiveChallengeResponse: ::STRING, + ParameterControl: ::ULONG, +}} +pub type PMSV1_0_LM20_LOGON = *mut MSV1_0_LM20_LOGON; +STRUCT!{struct MSV1_0_SUBAUTH_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Workstation: ::UNICODE_STRING, + ChallengeToClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + AuthenticationInfo1: ::STRING, + AuthenticationInfo2: ::STRING, + ParameterControl: ::ULONG, + SubAuthPackageId: ::ULONG, +}} +pub type PMSV1_0_SUBAUTH_LOGON = *mut MSV1_0_SUBAUTH_LOGON; +STRUCT!{struct MSV1_0_S4U_LOGON { + MessageType: MSV1_0_LOGON_SUBMIT_TYPE, + MSV1_0_LOGON_SUBMIT_TYPE: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, +}} +pub type PMSV1_0_S4U_LOGON = *mut MSV1_0_S4U_LOGON; +pub const LOGON_GUEST: ::ULONG = 0x01; +pub const LOGON_NOENCRYPTION: ::ULONG = 0x02; +pub const LOGON_CACHED_ACCOUNT: ::ULONG = 0x04; +pub const LOGON_USED_LM_PASSWORD: ::ULONG = 0x08; +pub const LOGON_EXTRA_SIDS: ::ULONG = 0x20; +pub const LOGON_SUBAUTH_SESSION_KEY: ::ULONG = 0x40; +pub const LOGON_SERVER_TRUST_ACCOUNT: ::ULONG = 0x80; +pub const LOGON_NTLMV2_ENABLED: ::ULONG = 0x100; +pub const LOGON_RESOURCE_GROUPS: ::ULONG = 0x200; +pub const LOGON_PROFILE_PATH_RETURNED: ::ULONG = 0x400; +pub const LOGON_NT_V2: ::ULONG = 0x800; +pub const LOGON_LM_V2: ::ULONG = 0x1000; +pub const LOGON_NTLM_V2: ::ULONG = 0x2000; +pub const LOGON_OPTIMIZED: ::ULONG = 0x4000; +pub const LOGON_WINLOGON: ::ULONG = 0x8000; +pub const LOGON_PKINIT: ::ULONG = 0x10000; +pub const LOGON_NO_OPTIMIZED: ::ULONG = 0x20000; +pub const LOGON_NO_ELEVATION: ::ULONG = 0x40000; +pub const LOGON_MANAGED_SERVICE: ::ULONG = 0x80000; +pub const LOGON_GRACE_LOGON: ::ULONG = 0x01000000; +STRUCT!{struct MSV1_0_LM20_LOGON_PROFILE { + MessageType: MSV1_0_PROFILE_BUFFER_TYPE, + KickOffTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + UserFlags: ::ULONG, + UserSessionKey: [::UCHAR; MSV1_0_USER_SESSION_KEY_LENGTH], + LogonDomainName: ::UNICODE_STRING, + LanmanSessionKey: [::UCHAR; MSV1_0_LANMAN_SESSION_KEY_LENGTH], + LogonServer: ::UNICODE_STRING, + UserParameters: ::UNICODE_STRING, +}} +pub type PMSV1_0_LM20_LOGON_PROFILE = *mut MSV1_0_LM20_LOGON_PROFILE; +pub const MSV1_0_OWF_PASSWORD_LENGTH: usize = 16; +STRUCT!{struct MSV1_0_SUPPLEMENTAL_CREDENTIAL { + Version: ::ULONG, + Flags: ::ULONG, + LmPassword: [::UCHAR; MSV1_0_OWF_PASSWORD_LENGTH], + NtPassword: [::UCHAR; MSV1_0_OWF_PASSWORD_LENGTH], +}} +pub type PMSV1_0_SUPPLEMENTAL_CREDENTIAL = *mut MSV1_0_SUPPLEMENTAL_CREDENTIAL; +pub const MSV1_0_NTLM3_RESPONSE_LENGTH: usize = 16; +pub const MSV1_0_NTLM3_OWF_LENGTH: usize = 16; +STRUCT!{struct MSV1_0_NTLM3_RESPONSE { + Response: [::UCHAR; MSV1_0_NTLM3_RESPONSE_LENGTH], + RespType: ::UCHAR, + HiRespType: ::UCHAR, + Flags: ::USHORT, + MsgWord: ::ULONG, + TimeStamp: ::ULONGLONG, + ChallengeFromClient: [::UCHAR; MSV1_0_CHALLENGE_LENGTH], + AvPairsOff: ::ULONG, + Buffer: [::UCHAR; 1], +}} +pub type PMSV1_0_NTLM3_RESPONSE = *mut MSV1_0_NTLM3_RESPONSE; +ENUM!{enum MSV1_0_AVID { + MsvAvEOL, + MsvAvNbComputerName, + MsvAvNbDomainName, + MsvAvDnsComputerName, + MsvAvDnsDomainName, + MsvAvDnsTreeName, + MsvAvFlags, + MsvAvTimestamp, + MsvAvRestrictions, + MsvAvTargetName, + MsvAvChannelBindings, +}} +STRUCT!{struct MSV1_0_AV_PAIR { + AvId: ::USHORT, + AvLen: ::USHORT, +}} +pub type PMSV1_0_AV_PAIR = *mut MSV1_0_AV_PAIR; +ENUM!{enum MSV1_0_PROTOCOL_MESSAGE_TYPE { + MsV1_0Lm20ChallengeRequest = 0, + MsV1_0Lm20GetChallengeResponse, + MsV1_0EnumerateUsers, + MsV1_0GetUserInfo, + MsV1_0ReLogonUsers, + MsV1_0ChangePassword, + MsV1_0ChangeCachedPassword, + MsV1_0GenericPassthrough, + MsV1_0CacheLogon, + MsV1_0SubAuth, + MsV1_0DeriveCredential, + MsV1_0CacheLookup, + MsV1_0SetProcessOption, + MsV1_0ConfigLocalAliases, + MsV1_0ClearCachedCredentials, + MsV1_0LookupToken, + MsV1_0ValidateAuth, + MsV1_0CacheLookupEx, + MsV1_0GetCredentialKey, + MsV1_0SetThreadOption, +}} +pub type PMSV1_0_PROTOCOL_MESSAGE_TYPE = *mut MSV1_0_PROTOCOL_MESSAGE_TYPE; +STRUCT!{struct MSV1_0_CHANGEPASSWORD_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + OldPassword: ::UNICODE_STRING, + NewPassword: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, +}} +pub type PMSV1_0_CHANGEPASSWORD_REQUEST = *mut MSV1_0_CHANGEPASSWORD_REQUEST; +STRUCT!{struct MSV1_0_CHANGEPASSWORD_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + PasswordInfoValid: ::BOOLEAN, + DomainPasswordInfo: DOMAIN_PASSWORD_INFORMATION, +}} +pub type PMSV1_0_CHANGEPASSWORD_RESPONSE = *mut MSV1_0_CHANGEPASSWORD_RESPONSE; +STRUCT!{struct MSV1_0_PASSTHROUGH_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + PackageName: ::UNICODE_STRING, + DataLength: ::ULONG, + LogonData: ::PUCHAR, + Pad: ::ULONG, +}} +pub type PMSV1_0_PASSTHROUGH_REQUEST = *mut MSV1_0_PASSTHROUGH_REQUEST; +STRUCT!{struct MSV1_0_PASSTHROUGH_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + Pad: ::ULONG, + DataLength: ::ULONG, + ValidationData: ::PUCHAR, +}} +pub type PMSV1_0_PASSTHROUGH_RESPONSE = *mut MSV1_0_PASSTHROUGH_RESPONSE; +STRUCT!{struct MSV1_0_SUBAUTH_REQUEST { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + SubAuthPackageId: ::ULONG, + SubAuthInfoLength: ::ULONG, + SubAuthSubmitBuffer: ::PUCHAR, +}} +pub type PMSV1_0_SUBAUTH_REQUEST = *mut MSV1_0_SUBAUTH_REQUEST; +STRUCT!{struct MSV1_0_SUBAUTH_RESPONSE { + MessageType: MSV1_0_PROTOCOL_MESSAGE_TYPE, + SubAuthInfoLength: ::ULONG, + SubAuthReturnBuffer: ::PUCHAR, +}} +pub type PMSV1_0_SUBAUTH_RESPONSE = *mut MSV1_0_SUBAUTH_RESPONSE; +pub const RTL_ENCRYPT_MEMORY_SIZE: ::ULONG = 8; +pub const RTL_ENCRYPT_OPTION_CROSS_PROCESS: ::ULONG = 0x01; +pub const RTL_ENCRYPT_OPTION_SAME_LOGON: ::ULONG = 0x02; +pub const KERB_ETYPE_NULL: ::LONG = 0; +pub const KERB_ETYPE_DES_CBC_CRC: ::LONG = 1; +pub const KERB_ETYPE_DES_CBC_MD4: ::LONG = 2; +pub const KERB_ETYPE_DES_CBC_MD5: ::LONG = 3; +pub const KERB_ETYPE_AES128_CTS_HMAC_SHA1_96: ::LONG = 17; +pub const KERB_ETYPE_AES256_CTS_HMAC_SHA1_96: ::LONG = 18; +pub const KERB_ETYPE_RC4_MD4: ::LONG = -128; +pub const KERB_ETYPE_RC4_PLAIN2: ::LONG = -129; +pub const KERB_ETYPE_RC4_LM: ::LONG = -130; +pub const KERB_ETYPE_RC4_SHA: ::LONG = -131; +pub const KERB_ETYPE_DES_PLAIN: ::LONG = -132; +pub const KERB_ETYPE_RC4_HMAC_OLD: ::LONG = -133; +pub const KERB_ETYPE_RC4_PLAIN_OLD: ::LONG = -134; +pub const KERB_ETYPE_RC4_HMAC_OLD_EXP: ::LONG = -135; +pub const KERB_ETYPE_RC4_PLAIN_OLD_EXP: ::LONG = -136; +pub const KERB_ETYPE_RC4_PLAIN: ::LONG = -140; +pub const KERB_ETYPE_RC4_PLAIN_EXP: ::LONG = -141; +pub const KERB_ETYPE_AES128_CTS_HMAC_SHA1_96_PLAIN: ::LONG = -148; +pub const KERB_ETYPE_AES256_CTS_HMAC_SHA1_96_PLAIN: ::LONG = -149; +pub const KERB_ETYPE_DSA_SHA1_CMS: ::LONG = 9; +pub const KERB_ETYPE_RSA_MD5_CMS: ::LONG = 10; +pub const KERB_ETYPE_RSA_SHA1_CMS: ::LONG = 11; +pub const KERB_ETYPE_RC2_CBC_ENV: ::LONG = 12; +pub const KERB_ETYPE_RSA_ENV: ::LONG = 13; +pub const KERB_ETYPE_RSA_ES_OEAP_ENV: ::LONG = 14; +pub const KERB_ETYPE_DES_EDE3_CBC_ENV: ::LONG = 15; +pub const KERB_ETYPE_DSA_SIGN: ::LONG = 8; +pub const KERB_ETYPE_RSA_PRIV: ::LONG = 9; +pub const KERB_ETYPE_RSA_PUB: ::LONG = 10; +pub const KERB_ETYPE_RSA_PUB_MD5: ::LONG = 11; +pub const KERB_ETYPE_RSA_PUB_SHA1: ::LONG = 12; +pub const KERB_ETYPE_PKCS7_PUB: ::LONG = 13; +pub const KERB_ETYPE_DES3_CBC_MD5: ::LONG = 5; +pub const KERB_ETYPE_DES3_CBC_SHA1: ::LONG = 7; +pub const KERB_ETYPE_DES3_CBC_SHA1_KD: ::LONG = 16; +pub const KERB_ETYPE_DES_CBC_MD5_NT: ::LONG = 20; +pub const KERB_ETYPE_RC4_HMAC_NT: ::LONG = 23; +pub const KERB_ETYPE_RC4_HMAC_NT_EXP: ::LONG = 24; +pub const KERB_CHECKSUM_NONE: ::LONG = 0; +pub const KERB_CHECKSUM_CRC32: ::LONG = 1; +pub const KERB_CHECKSUM_MD4: ::LONG = 2; +pub const KERB_CHECKSUM_KRB_DES_MAC: ::LONG = 4; +pub const KERB_CHECKSUM_KRB_DES_MAC_K: ::LONG = 5; +pub const KERB_CHECKSUM_MD5: ::LONG = 7; +pub const KERB_CHECKSUM_MD5_DES: ::LONG = 8; +pub const KERB_CHECKSUM_SHA1_NEW: ::LONG = 14; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES128: ::LONG = 15; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES256: ::LONG = 16; +pub const KERB_CHECKSUM_LM: ::LONG = -130; +pub const KERB_CHECKSUM_SHA1: ::LONG = -131; +pub const KERB_CHECKSUM_REAL_CRC32: ::LONG = -132; +pub const KERB_CHECKSUM_DES_MAC: ::LONG = -133; +pub const KERB_CHECKSUM_DES_MAC_MD5: ::LONG = -134; +pub const KERB_CHECKSUM_MD25: ::LONG = -135; +pub const KERB_CHECKSUM_RC4_MD5: ::LONG = -136; +pub const KERB_CHECKSUM_MD5_HMAC: ::LONG = -137; +pub const KERB_CHECKSUM_HMAC_MD5: ::LONG = -138; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES128_Ki: ::LONG = -150; +pub const KERB_CHECKSUM_HMAC_SHA1_96_AES256_Ki: ::LONG = -151; +pub const KERB_TICKET_FLAGS_reserved: ::ULONG = 0x80000000; +pub const KERB_TICKET_FLAGS_forwardable: ::ULONG = 0x40000000; +pub const KERB_TICKET_FLAGS_forwarded: ::ULONG = 0x20000000; +pub const KERB_TICKET_FLAGS_proxiable: ::ULONG = 0x10000000; +pub const KERB_TICKET_FLAGS_proxy: ::ULONG = 0x08000000; +pub const KERB_TICKET_FLAGS_may_postdate: ::ULONG = 0x04000000; +pub const KERB_TICKET_FLAGS_postdated: ::ULONG = 0x02000000; +pub const KERB_TICKET_FLAGS_invalid: ::ULONG = 0x01000000; +pub const KERB_TICKET_FLAGS_renewable: ::ULONG = 0x00800000; +pub const KERB_TICKET_FLAGS_initial: ::ULONG = 0x00400000; +pub const KERB_TICKET_FLAGS_pre_authent: ::ULONG = 0x00200000; +pub const KERB_TICKET_FLAGS_hw_authent: ::ULONG = 0x00100000; +pub const KERB_TICKET_FLAGS_ok_as_delegate: ::ULONG = 0x00040000; +pub const KERB_TICKET_FLAGS_name_canonicalize: ::ULONG = 0x00010000; +pub const KERB_TICKET_FLAGS_cname_in_pa_data: ::ULONG = 0x00040000; +pub const KERB_TICKET_FLAGS_enc_pa_rep: ::ULONG = 0x00010000; +pub const KERB_TICKET_FLAGS_reserved1: ::ULONG = 0x00000001; +pub const KRB_NT_UNKNOWN: ::LONG = 0; +pub const KRB_NT_PRINCIPAL: ::LONG = 1; +pub const KRB_NT_PRINCIPAL_AND_ID: ::LONG = -131; +pub const KRB_NT_SRV_INST: ::LONG = 2; +pub const KRB_NT_SRV_INST_AND_ID: ::LONG = -132; +pub const KRB_NT_SRV_HST: ::LONG = 3; +pub const KRB_NT_SRV_XHST: ::LONG = 4; +pub const KRB_NT_UID: ::LONG = 5; +pub const KRB_NT_ENTERPRISE_PRINCIPAL: ::LONG = 10; +pub const KRB_NT_WELLKNOWN: ::LONG = 11; +pub const KRB_NT_ENT_PRINCIPAL_AND_ID: ::LONG = -130; +pub const KRB_NT_MS_PRINCIPAL: ::LONG = -128; +pub const KRB_NT_MS_PRINCIPAL_AND_ID: ::LONG = -129; +pub const KRB_NT_MS_BRANCH_ID: ::LONG = -133; +pub const KRB_NT_X500_PRINCIPAL: ::LONG = 6; +pub const KERB_WRAP_NO_ENCRYPT: ::ULONG = 0x80000001; +ENUM!{enum KERB_LOGON_SUBMIT_TYPE { + KerbInteractiveLogon = 2, + KerbSmartCardLogon = 6, + KerbWorkstationUnlockLogon = 7, + KerbSmartCardUnlockLogon = 8, + KerbProxyLogon = 9, + KerbTicketLogon = 10, + KerbTicketUnlockLogon = 11, + KerbS4ULogon = 12, + KerbCertificateLogon = 13, + KerbCertificateS4ULogon = 14, + KerbCertificateUnlockLogon = 15, + KerbNoElevationLogon = 83, + KerbLuidLogon = 84, +}} +pub type PKERB_LOGON_SUBMIT_TYPE = *mut KERB_LOGON_SUBMIT_TYPE; +STRUCT!{struct KERB_INTERACTIVE_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + LogonDomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PKERB_INTERACTIVE_LOGON = *mut KERB_INTERACTIVE_LOGON; +STRUCT!{struct KERB_INTERACTIVE_UNLOCK_LOGON { + Logon: KERB_INTERACTIVE_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_INTERACTIVE_UNLOCK_LOGON = *mut KERB_INTERACTIVE_UNLOCK_LOGON; +STRUCT!{struct KERB_SMART_CARD_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Pin: ::UNICODE_STRING, + CspDataLength: ::ULONG, + CspData: ::PUCHAR, +}} +pub type PKERB_SMART_CARD_LOGON = *mut KERB_SMART_CARD_LOGON; +STRUCT!{struct KERB_SMART_CARD_UNLOCK_LOGON { + Logon: KERB_SMART_CARD_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_SMART_CARD_UNLOCK_LOGON = *mut KERB_SMART_CARD_UNLOCK_LOGON; +pub const KERB_CERTIFICATE_LOGON_FLAG_CHECK_DUPLICATES: ::ULONG = 0x1; +pub const KERB_CERTIFICATE_LOGON_FLAG_USE_CERTIFICATE_INFO: ::ULONG = 0x2; +STRUCT!{struct KERB_CERTIFICATE_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + DomainName: ::UNICODE_STRING, + UserName: ::UNICODE_STRING, + Pin: ::UNICODE_STRING, + Flags: ::ULONG, + CspDataLength: ::ULONG, + CspData: ::PUCHAR, +}} +pub type PKERB_CERTIFICATE_LOGON = *mut KERB_CERTIFICATE_LOGON; +STRUCT!{struct KERB_CERTIFICATE_UNLOCK_LOGON { + Logon: KERB_CERTIFICATE_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_CERTIFICATE_UNLOCK_LOGON = *mut KERB_CERTIFICATE_UNLOCK_LOGON; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_DUPLICATES: ::ULONG = 0x1; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS: ::ULONG = 0x2; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_FAIL_IF_NT_AUTH_POLICY_REQUIRED: ::ULONG = 0x4; +pub const KERB_CERTIFICATE_S4U_LOGON_FLAG_IDENTIFY: ::ULONG = 0x8; +STRUCT!{struct KERB_CERTIFICATE_S4U_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + CertificateLength: ::ULONG, + Certificate: ::PUCHAR, +}} +pub type PKERB_CERTIFICATE_S4U_LOGON = *mut KERB_CERTIFICATE_S4U_LOGON; +STRUCT!{struct KERB_TICKET_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + ServiceTicketLength: ::ULONG, + TicketGrantingTicketLength: ::ULONG, + ServiceTicket: ::PUCHAR, + TicketGrantingTicket: ::PUCHAR, +}} +pub type PKERB_TICKET_LOGON = *mut KERB_TICKET_LOGON; +STRUCT!{struct KERB_TICKET_UNLOCK_LOGON { + Logon: KERB_TICKET_LOGON, + LogonId: ::LUID, +}} +pub type PKERB_TICKET_UNLOCK_LOGON = *mut KERB_TICKET_UNLOCK_LOGON; +pub const KERB_S4U_LOGON_FLAG_CHECK_LOGONHOURS: ::ULONG = 0x2; +pub const KERB_S4U_LOGON_FLAG_IDENTIFY: ::ULONG = 0x8; +STRUCT!{struct KERB_S4U_LOGON { + MessageType: KERB_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + ClientUpn: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, +}} +pub type PKERB_S4U_LOGON = *mut KERB_S4U_LOGON; +ENUM!{enum KERB_PROFILE_BUFFER_TYPE { + KerbInteractiveProfile = 2, + KerbSmartCardProfile = 4, + KerbTicketProfile = 6, +}} +pub type PKERB_PROFILE_BUFFER_TYPE = *mut KERB_PROFILE_BUFFER_TYPE; +STRUCT!{struct KERB_INTERACTIVE_PROFILE { + MessageType: KERB_PROFILE_BUFFER_TYPE, + LogonCount: ::USHORT, + BadPasswordCount: ::USHORT, + LogonTime: ::LARGE_INTEGER, + LogoffTime: ::LARGE_INTEGER, + KickOffTime: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + LogonScript: ::UNICODE_STRING, + HomeDirectory: ::UNICODE_STRING, + FullName: ::UNICODE_STRING, + ProfilePath: ::UNICODE_STRING, + HomeDirectoryDrive: ::UNICODE_STRING, + LogonServer: ::UNICODE_STRING, + UserFlags: ::ULONG, +}} +pub type PKERB_INTERACTIVE_PROFILE = *mut KERB_INTERACTIVE_PROFILE; +STRUCT!{struct KERB_SMART_CARD_PROFILE { + Profile: KERB_INTERACTIVE_PROFILE, + CertificateSize: ::ULONG, + CertificateData: ::PUCHAR, +}} +pub type PKERB_SMART_CARD_PROFILE = *mut KERB_SMART_CARD_PROFILE; +STRUCT!{struct KERB_CRYPTO_KEY { + KeyType: ::LONG, + Length: ::ULONG, + Value: ::PUCHAR, +}} +pub type PKERB_CRYPTO_KEY = *mut KERB_CRYPTO_KEY; +STRUCT!{struct KERB_CRYPTO_KEY32 { + KeyType: ::LONG, + Length: ::ULONG, + Offset: ::ULONG, +}} +pub type PKERB_CRYPTO_KEY32 = *mut KERB_CRYPTO_KEY32; +STRUCT!{struct KERB_TICKET_PROFILE { + Profile: KERB_INTERACTIVE_PROFILE, + SessionKey: KERB_CRYPTO_KEY, +}} +pub type PKERB_TICKET_PROFILE = *mut KERB_TICKET_PROFILE; +ENUM!{enum KERB_PROTOCOL_MESSAGE_TYPE { + KerbDebugRequestMessage = 0, + KerbQueryTicketCacheMessage, + KerbChangeMachinePasswordMessage, + KerbVerifyPacMessage, + KerbRetrieveTicketMessage, + KerbUpdateAddressesMessage, + KerbPurgeTicketCacheMessage, + KerbChangePasswordMessage, + KerbRetrieveEncodedTicketMessage, + KerbDecryptDataMessage, + KerbAddBindingCacheEntryMessage, + KerbSetPasswordMessage, + KerbSetPasswordExMessage, + KerbVerifyCredentialsMessage, + KerbQueryTicketCacheExMessage, + KerbPurgeTicketCacheExMessage, + KerbRefreshSmartcardCredentialsMessage, + KerbAddExtraCredentialsMessage, + KerbQuerySupplementalCredentialsMessage, + KerbTransferCredentialsMessage, + KerbQueryTicketCacheEx2Message, + KerbSubmitTicketMessage, + KerbAddExtraCredentialsExMessage, + KerbQueryKdcProxyCacheMessage, + KerbPurgeKdcProxyCacheMessage, + KerbQueryTicketCacheEx3Message, + KerbCleanupMachinePkinitCredsMessage, + KerbAddBindingCacheEntryExMessage, + KerbQueryBindingCacheMessage, + KerbPurgeBindingCacheMessage, + KerbPinKdcMessage, + KerbUnpinAllKdcsMessage, + KerbQueryDomainExtendedPoliciesMessage, + KerbQueryS4U2ProxyCacheMessage, +}} +pub type PKERB_PROTOCOL_MESSAGE_TYPE = *mut KERB_PROTOCOL_MESSAGE_TYPE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_TKT_CACHE_REQUEST = *mut KERB_QUERY_TKT_CACHE_REQUEST; +STRUCT!{struct KERB_TICKET_CACHE_INFO { + ServerName: ::UNICODE_STRING, + RealmName: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO = *mut KERB_TICKET_CACHE_INFO; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO_EX = *mut KERB_TICKET_CACHE_INFO_EX; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX2 { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, + SessionKeyType: ::ULONG, + BranchId: ::ULONG, +}} +pub type PKERB_TICKET_CACHE_INFO_EX2 = *mut KERB_TICKET_CACHE_INFO_EX2; +STRUCT!{struct KERB_TICKET_CACHE_INFO_EX3 { + ClientName: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ServerName: ::UNICODE_STRING, + ServerRealm: ::UNICODE_STRING, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewTime: ::LARGE_INTEGER, + EncryptionType: ::LONG, + TicketFlags: ::ULONG, + SessionKeyType: ::ULONG, + BranchId: ::ULONG, + CacheFlags: ::ULONG, + KdcCalled: ::UNICODE_STRING, +}} +pub type PKERB_TICKET_CACHE_INFO_EX3 = *mut KERB_TICKET_CACHE_INFO_EX3; +STRUCT!{struct KERB_QUERY_TKT_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_RESPONSE = *mut KERB_QUERY_TKT_CACHE_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX2_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX2; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX2_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX2_RESPONSE; +STRUCT!{struct KERB_QUERY_TKT_CACHE_EX3_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfTickets: ::ULONG, + Tickets: [KERB_TICKET_CACHE_INFO_EX3; ::ANYSIZE_ARRAY], +}} +pub type PKERB_QUERY_TKT_CACHE_EX3_RESPONSE = *mut KERB_QUERY_TKT_CACHE_EX3_RESPONSE; +pub const KERB_USE_DEFAULT_TICKET_FLAGS: ::ULONG = 0x0; +pub const KERB_RETRIEVE_TICKET_DEFAULT: ::ULONG = 0x0; +pub const KERB_RETRIEVE_TICKET_DONT_USE_CACHE: ::ULONG = 0x1; +pub const KERB_RETRIEVE_TICKET_USE_CACHE_ONLY: ::ULONG = 0x2; +pub const KERB_RETRIEVE_TICKET_USE_CREDHANDLE: ::ULONG = 0x4; +pub const KERB_RETRIEVE_TICKET_AS_KERB_CRED: ::ULONG = 0x8; +pub const KERB_RETRIEVE_TICKET_WITH_SEC_CRED: ::ULONG = 0x10; +pub const KERB_RETRIEVE_TICKET_CACHE_TICKET: ::ULONG = 0x20; +pub const KERB_RETRIEVE_TICKET_MAX_LIFETIME: ::ULONG = 0x40; +STRUCT!{struct KERB_AUTH_DATA { + Type: ::ULONG, + Length: ::ULONG, + Data: ::PUCHAR, +}} +pub type PKERB_AUTH_DATA = *mut KERB_AUTH_DATA; +STRUCT!{struct KERB_NET_ADDRESS { + Family: ::ULONG, + Length: ::ULONG, + Address: ::PUCHAR, +}} +pub type PKERB_NET_ADDRESS = *mut KERB_NET_ADDRESS; +STRUCT!{struct KERB_NET_ADDRESSES { + Number: ::ULONG, + Addresses: [KERB_NET_ADDRESS; ::ANYSIZE_ARRAY], +}} +pub type PKERB_NET_ADDRESSES = *mut KERB_NET_ADDRESSES; +STRUCT!{struct KERB_EXTERNAL_NAME { + NameType: ::SHORT, + NameCount: ::USHORT, + Names: [::UNICODE_STRING; ::ANYSIZE_ARRAY], +}} +pub type PKERB_EXTERNAL_NAME = *mut KERB_EXTERNAL_NAME; +STRUCT!{struct KERB_EXTERNAL_TICKET { + ServiceName: PKERB_EXTERNAL_NAME, + TargetName: PKERB_EXTERNAL_NAME, + ClientName: PKERB_EXTERNAL_NAME, + DomainName: ::UNICODE_STRING, + TargetDomainName: ::UNICODE_STRING, + AltTargetDomainName: ::UNICODE_STRING, + SessionKey: KERB_CRYPTO_KEY, + TicketFlags: ::ULONG, + Flags: ::ULONG, + KeyExpirationTime: ::LARGE_INTEGER, + StartTime: ::LARGE_INTEGER, + EndTime: ::LARGE_INTEGER, + RenewUntil: ::LARGE_INTEGER, + TimeSkew: ::LARGE_INTEGER, + EncodedTicketSize: ::ULONG, + EncodedTicket: ::PUCHAR, +}} +pub type PKERB_EXTERNAL_TICKET = *mut KERB_EXTERNAL_TICKET; +STRUCT!{struct KERB_RETRIEVE_TKT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + TargetName: ::UNICODE_STRING, + TicketFlags: ::ULONG, + CacheOptions: ::ULONG, + EncryptionType: ::LONG, + CredentialsHandle: ::SecHandle, +}} +pub type PKERB_RETRIEVE_TKT_REQUEST = *mut KERB_RETRIEVE_TKT_REQUEST; +STRUCT!{struct KERB_RETRIEVE_TKT_RESPONSE { + Ticket: KERB_EXTERNAL_TICKET, +}} +pub type PKERB_RETRIEVE_TKT_RESPONSE = *mut KERB_RETRIEVE_TKT_RESPONSE; +STRUCT!{struct KERB_PURGE_TKT_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + ServerName: ::UNICODE_STRING, + RealmName: ::UNICODE_STRING, +}} +pub type PKERB_PURGE_TKT_CACHE_REQUEST = *mut KERB_PURGE_TKT_CACHE_REQUEST; +pub const KERB_PURGE_ALL_TICKETS: ::ULONG = 1; +STRUCT!{struct KERB_PURGE_TKT_CACHE_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + TicketTemplate: KERB_TICKET_CACHE_INFO_EX, +}} +pub type PKERB_PURGE_TKT_CACHE_EX_REQUEST = *mut KERB_PURGE_TKT_CACHE_EX_REQUEST; +STRUCT!{struct KERB_SUBMIT_TKT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + Key: KERB_CRYPTO_KEY32, + KerbCredSize: ::ULONG, + KerbCredOffset: ::ULONG, +}} +pub type PKERB_SUBMIT_TKT_REQUEST = *mut KERB_SUBMIT_TKT_REQUEST; +STRUCT!{struct KERB_QUERY_KDC_PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_KDC_PROXY_CACHE_REQUEST = *mut KERB_QUERY_KDC_PROXY_CACHE_REQUEST; +STRUCT!{struct KDC_PROXY_CACHE_ENTRY_DATA { + SinceLastUsed: ::ULONG64, + DomainName: ::UNICODE_STRING, + ProxyServerName: ::UNICODE_STRING, + ProxyServerVdir: ::UNICODE_STRING, + ProxyServerPort: ::USHORT, + LogonId: ::LUID, + CredUserName: ::UNICODE_STRING, + CredDomainName: ::UNICODE_STRING, + GlobalCache: ::BOOLEAN, +}} +pub type PKDC_PROXY_CACHE_ENTRY_DATA = *mut KDC_PROXY_CACHE_ENTRY_DATA; +STRUCT!{struct KERB_QUERY_KDC_PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfEntries: ::ULONG, + Entries: PKDC_PROXY_CACHE_ENTRY_DATA, +}} +pub type PKERB_QUERY_KDC_PROXY_CACHE_RESPONSE = *mut KERB_QUERY_KDC_PROXY_CACHE_RESPONSE; +STRUCT!{struct KERB_PURGE_KDC_PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_PURGE_KDC_PROXY_CACHE_REQUEST = *mut KERB_PURGE_KDC_PROXY_CACHE_REQUEST; +STRUCT!{struct KERB_PURGE_KDC_PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfPurged: ::ULONG, +}} +pub type PKERB_PURGE_KDC_PROXY_CACHE_RESPONSE = *mut KERB_PURGE_KDC_PROXY_CACHE_RESPONSE; +pub const KERB_S4U2PROXY_CACHE_ENTRY_INFO_FLAG_NEGATIVE: ::ULONG = 0x1; +STRUCT!{struct KERB_S4U2PROXY_CACHE_ENTRY_INFO { + ServerName: ::UNICODE_STRING, + Flags: ::ULONG, + LastStatus: ::NTSTATUS, + Expiry: ::LARGE_INTEGER, +}} +pub type PKERB_S4U2PROXY_CACHE_ENTRY_INFO = *mut KERB_S4U2PROXY_CACHE_ENTRY_INFO; +pub const KERB_S4U2PROXY_CRED_FLAG_NEGATIVE: ::ULONG = 0x1; +STRUCT!{struct KERB_S4U2PROXY_CRED { + UserName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + Flags: ::ULONG, + LastStatus: ::NTSTATUS, + Expiry: ::LARGE_INTEGER, + CountOfEntries: ::ULONG, + Entries: PKERB_S4U2PROXY_CACHE_ENTRY_INFO, +}} +pub type PKERB_S4U2PROXY_CRED = *mut KERB_S4U2PROXY_CRED; +STRUCT!{struct KERB_QUERY_S4U2PROXY_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + LogonId: ::LUID, +}} +pub type PKERB_QUERY_S4U2PROXY_CACHE_REQUEST = *mut KERB_QUERY_S4U2PROXY_CACHE_REQUEST; +STRUCT!{struct KERB_QUERY_S4U2PROXY_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfCreds: ::ULONG, + Creds: PKERB_S4U2PROXY_CRED, +}} +pub type PKERB_QUERY_S4U2PROXY_CACHE_RESPONSE = *mut KERB_QUERY_S4U2PROXY_CACHE_RESPONSE; +STRUCT!{struct KERB_CHANGEPASSWORD_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + OldPassword: ::UNICODE_STRING, + NewPassword: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, +}} +pub type PKERB_CHANGEPASSWORD_REQUEST = *mut KERB_CHANGEPASSWORD_REQUEST; +STRUCT!{struct KERB_SETPASSWORD_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + CredentialsHandle: ::SecHandle, + Flags: ::ULONG, + DomainName: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, +}} +pub type PKERB_SETPASSWORD_REQUEST = *mut KERB_SETPASSWORD_REQUEST; +STRUCT!{struct KERB_SETPASSWORD_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + CredentialsHandle: ::SecHandle, + Flags: ::ULONG, + AccountRealm: ::UNICODE_STRING, + AccountName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, + ClientRealm: ::UNICODE_STRING, + ClientName: ::UNICODE_STRING, + Impersonating: ::BOOLEAN, + KdcAddress: ::UNICODE_STRING, + KdcAddressType: ::ULONG, +}} +pub type PKERB_SETPASSWORD_EX_REQUEST = *mut KERB_SETPASSWORD_EX_REQUEST; +pub const DS_UNKNOWN_ADDRESS_TYPE: ::ULONG = 0; +pub const KERB_SETPASS_USE_LOGONID: ::ULONG = 1; +pub const KERB_SETPASS_USE_CREDHANDLE: ::ULONG = 2; +STRUCT!{struct KERB_DECRYPT_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, + Flags: ::ULONG, + CryptoType: ::LONG, + KeyUsage: ::LONG, + Key: KERB_CRYPTO_KEY, + EncryptedDataSize: ::ULONG, + InitialVectorSize: ::ULONG, + InitialVector: ::PUCHAR, + EncryptedData: ::PUCHAR, +}} +pub type PKERB_DECRYPT_REQUEST = *mut KERB_DECRYPT_REQUEST; +pub const KERB_DECRYPT_FLAG_DEFAULT_KEY: ::ULONG = 0x00000001; +STRUCT!{struct KERB_DECRYPT_RESPONSE { + DecryptedData: [::UCHAR; ::ANYSIZE_ARRAY], +}} +pub type PKERB_DECRYPT_RESPONSE = *mut KERB_DECRYPT_RESPONSE; +STRUCT!{struct KERB_ADD_BINDING_CACHE_ENTRY_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, +}} +pub type PKERB_ADD_BINDING_CACHE_ENTRY_REQUEST = *mut KERB_ADD_BINDING_CACHE_ENTRY_REQUEST; +STRUCT!{struct KERB_REFRESH_SCCRED_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CredentialBlob: ::UNICODE_STRING, + LogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_REFRESH_SCCRED_REQUEST = *mut KERB_REFRESH_SCCRED_REQUEST; +pub const KERB_REFRESH_SCCRED_RELEASE: ::ULONG = 0x0; +pub const KERB_REFRESH_SCCRED_GETTGT: ::ULONG = 0x1; +STRUCT!{struct KERB_ADD_CREDENTIALS_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + UserName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + Password: ::UNICODE_STRING, + LogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_ADD_CREDENTIALS_REQUEST = *mut KERB_ADD_CREDENTIALS_REQUEST; +pub const KERB_REQUEST_ADD_CREDENTIAL: ::ULONG = 1; +pub const KERB_REQUEST_REPLACE_CREDENTIAL: ::ULONG = 2; +pub const KERB_REQUEST_REMOVE_CREDENTIAL: ::ULONG = 4; +STRUCT!{struct KERB_ADD_CREDENTIALS_REQUEST_EX { + Credentials: KERB_ADD_CREDENTIALS_REQUEST, + PrincipalNameCount: ::ULONG, + PrincipalNames: [::UNICODE_STRING; ::ANYSIZE_ARRAY], +}} +pub type PKERB_ADD_CREDENTIALS_REQUEST_EX = *mut KERB_ADD_CREDENTIALS_REQUEST_EX; +STRUCT!{struct KERB_TRANSFER_CRED_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + OriginLogonId: ::LUID, + DestinationLogonId: ::LUID, + Flags: ::ULONG, +}} +pub type PKERB_TRANSFER_CRED_REQUEST = *mut KERB_TRANSFER_CRED_REQUEST; +pub const KERB_TRANSFER_CRED_WITH_TICKETS: ::ULONG = 0x1; +pub const KERB_TRANSFER_CRED_CLEANUP_CREDENTIALS: ::ULONG = 0x2; +STRUCT!{struct KERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + LogonId: ::LUID, +}} +pub type PKERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST = + *mut KERB_CLEANUP_MACHINE_PKINIT_CREDS_REQUEST; +STRUCT!{struct KERB_BINDING_CACHE_ENTRY_DATA { + DiscoveryTime: ::ULONG64, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, + Flags: ::ULONG, + DcFlags: ::ULONG, + CacheFlags: ::ULONG, + KdcName: ::UNICODE_STRING, +}} +pub type PKERB_BINDING_CACHE_ENTRY_DATA = *mut KERB_BINDING_CACHE_ENTRY_DATA; +STRUCT!{struct KERB_QUERY_BINDING_CACHE_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + CountOfEntries: ::ULONG, + Entries: PKERB_BINDING_CACHE_ENTRY_DATA, +}} +pub type PKERB_QUERY_BINDING_CACHE_RESPONSE = *mut KERB_QUERY_BINDING_CACHE_RESPONSE; +STRUCT!{struct KERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + RealmName: ::UNICODE_STRING, + KdcAddress: ::UNICODE_STRING, + AddressType: ::ULONG, + DcFlags: ::ULONG, +}} +pub type PKERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST = *mut KERB_ADD_BINDING_CACHE_ENTRY_EX_REQUEST; +STRUCT!{struct KERB_QUERY_BINDING_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, +}} +pub type PKERB_QUERY_BINDING_CACHE_REQUEST = *mut KERB_QUERY_BINDING_CACHE_REQUEST; +STRUCT!{struct KERB_PURGE_BINDING_CACHE_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, +}} +pub type PKERB_PURGE_BINDING_CACHE_REQUEST = *mut KERB_PURGE_BINDING_CACHE_REQUEST; +STRUCT!{struct KERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + DomainName: ::UNICODE_STRING, +}} +pub type PKERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST = + *mut KERB_QUERY_DOMAIN_EXTENDED_POLICIES_REQUEST; +STRUCT!{struct KERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE { + MessageType: KERB_PROTOCOL_MESSAGE_TYPE, + Flags: ::ULONG, + ExtendedPolicies: ::ULONG, + DsFlags: ::ULONG, +}} +pub type PKERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE = + *mut KERB_QUERY_DOMAIN_EXTENDED_POLICIES_RESPONSE; +ENUM!{enum KERB_CERTIFICATE_INFO_TYPE { + CertHashInfo = 1, +}} +pub type PKERB_CERTIFICATE_INFO_TYPE = *mut KERB_CERTIFICATE_INFO_TYPE; +STRUCT!{struct KERB_CERTIFICATE_HASHINFO { + StoreNameLength: ::USHORT, + HashLength: ::USHORT, +}} +pub type PKERB_CERTIFICATE_HASHINFO = *mut KERB_CERTIFICATE_HASHINFO; +STRUCT!{struct KERB_CERTIFICATE_INFO { + CertInfoSize: ::ULONG, + InfoType: ::ULONG, +}} +pub type PKERB_CERTIFICATE_INFO = *mut KERB_CERTIFICATE_INFO; +STRUCT!{struct POLICY_AUDIT_SID_ARRAY { + UsersCount: ::ULONG, + UserSidArray: *mut ::PSID, +}} +pub type PPOLICY_AUDIT_SID_ARRAY = *mut POLICY_AUDIT_SID_ARRAY; +STRUCT!{struct AUDIT_POLICY_INFORMATION { + AuditSubCategoryGuid: ::GUID, + AuditingInformation: ::ULONG, + AuditCategoryGuid: ::GUID, +}} +pub type PAUDIT_POLICY_INFORMATION = *mut AUDIT_POLICY_INFORMATION; +pub type LPAUDIT_POLICY_INFORMATION = PAUDIT_POLICY_INFORMATION; +pub type PCAUDIT_POLICY_INFORMATION = *const AUDIT_POLICY_INFORMATION; +pub const AUDIT_SET_SYSTEM_POLICY: ::ULONG = 0x0001; +pub const AUDIT_QUERY_SYSTEM_POLICY: ::ULONG = 0x0002; +pub const AUDIT_SET_USER_POLICY: ::ULONG = 0x0004; +pub const AUDIT_QUERY_USER_POLICY: ::ULONG = 0x0008; +pub const AUDIT_ENUMERATE_USERS: ::ULONG = 0x0010; +pub const AUDIT_SET_MISC_POLICY: ::ULONG = 0x0020; +pub const AUDIT_QUERY_MISC_POLICY: ::ULONG = 0x0040; +pub const AUDIT_GENERIC_ALL: ::ULONG = ::STANDARD_RIGHTS_REQUIRED | AUDIT_SET_SYSTEM_POLICY + | AUDIT_QUERY_SYSTEM_POLICY | AUDIT_SET_USER_POLICY | AUDIT_QUERY_USER_POLICY + | AUDIT_ENUMERATE_USERS | AUDIT_SET_MISC_POLICY | AUDIT_QUERY_MISC_POLICY; +pub const AUDIT_GENERIC_READ: ::ULONG = ::STANDARD_RIGHTS_READ | AUDIT_QUERY_SYSTEM_POLICY + | AUDIT_QUERY_USER_POLICY | AUDIT_ENUMERATE_USERS | AUDIT_QUERY_MISC_POLICY; +pub const AUDIT_GENERIC_WRITE: ::ULONG = ::STANDARD_RIGHTS_WRITE | AUDIT_SET_USER_POLICY + | AUDIT_SET_MISC_POLICY | AUDIT_SET_SYSTEM_POLICY; +pub const AUDIT_GENERIC_EXECUTE: ::ULONG = ::STANDARD_RIGHTS_EXECUTE; +STRUCT!{struct PKU2U_CERT_BLOB { + CertOffset: ::ULONG, + CertLength: ::USHORT, +}} +pub type PPKU2U_CERT_BLOB = *mut PKU2U_CERT_BLOB; +pub const PKU2U_CREDUI_CONTEXT_VERSION: ::ULONG64 = 0x4154414454524543; +STRUCT!{struct PKU2U_CREDUI_CONTEXT { + Version: ::ULONG64, + cbHeaderLength: ::USHORT, + cbStructureLength: ::ULONG, + CertArrayCount: ::USHORT, + CertArrayOffset: ::ULONG, +}} +pub type PPKU2U_CREDUI_CONTEXT = *mut PKU2U_CREDUI_CONTEXT; +ENUM!{enum PKU2U_LOGON_SUBMIT_TYPE { + Pku2uCertificateS4ULogon = 14, +}} +pub type PPKU2U_LOGON_SUBMIT_TYPE = *mut PKU2U_LOGON_SUBMIT_TYPE; +STRUCT!{struct PKU2U_CERTIFICATE_S4U_LOGON { + MessageType: PKU2U_LOGON_SUBMIT_TYPE, + Flags: ::ULONG, + UserPrincipalName: ::UNICODE_STRING, + DomainName: ::UNICODE_STRING, + CertificateLength: ::ULONG, + Certificate: ::PUCHAR, +}} +pub type PPKU2U_CERTIFICATE_S4U_LOGON = *mut PKU2U_CERTIFICATE_S4U_LOGON; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ntstatus.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ntstatus.rs new file mode 100644 index 0000000..4662235 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ntstatus.rs @@ -0,0 +1,2474 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Constant definitions for the NTSTATUS values. +pub const STATUS_WAIT_0: ::NTSTATUS = 0x00000000; +pub const FACILITY_VSM: ::NTSTATUS = 0x45; +pub const FACILITY_VOLSNAP: ::NTSTATUS = 0x50; +pub const FACILITY_VOLMGR: ::NTSTATUS = 0x38; +pub const FACILITY_VIRTUALIZATION: ::NTSTATUS = 0x37; +pub const FACILITY_VIDEO: ::NTSTATUS = 0x1B; +pub const FACILITY_USB_ERROR_CODE: ::NTSTATUS = 0x10; +pub const FACILITY_TRANSACTION: ::NTSTATUS = 0x19; +pub const FACILITY_TPM: ::NTSTATUS = 0x29; +pub const FACILITY_TERMINAL_SERVER: ::NTSTATUS = 0xA; +pub const FACILITY_SXS_ERROR_CODE: ::NTSTATUS = 0x15; +pub const FACILITY_NTSSPI: ::NTSTATUS = 0x9; +pub const FACILITY_SPACES: ::NTSTATUS = 0xE7; +pub const FACILITY_SMB: ::NTSTATUS = 0x5D; +pub const FACILITY_SYSTEM_INTEGRITY: ::NTSTATUS = 0xE9; +pub const FACILITY_SHARED_VHDX: ::NTSTATUS = 0x5C; +pub const FACILITY_SECUREBOOT: ::NTSTATUS = 0x43; +pub const FACILITY_SECURITY_CORE: ::NTSTATUS = 0xE8; +pub const FACILITY_SDBUS: ::NTSTATUS = 0x51; +pub const FACILITY_RTPM: ::NTSTATUS = 0x2A; +pub const FACILITY_RPC_STUBS: ::NTSTATUS = 0x3; +pub const FACILITY_RPC_RUNTIME: ::NTSTATUS = 0x2; +pub const FACILITY_RESUME_KEY_FILTER: ::NTSTATUS = 0x40; +pub const FACILITY_RDBSS: ::NTSTATUS = 0x41; +pub const FACILITY_NTWIN32: ::NTSTATUS = 0x7; +pub const FACILITY_WIN32K_NTUSER: ::NTSTATUS = 0x3E; +pub const FACILITY_WIN32K_NTGDI: ::NTSTATUS = 0x3F; +pub const FACILITY_NDIS_ERROR_CODE: ::NTSTATUS = 0x23; +pub const FACILTIY_MUI_ERROR_CODE: ::NTSTATUS = 0xB; +pub const FACILITY_MONITOR: ::NTSTATUS = 0x1D; +pub const FACILITY_MAXIMUM_VALUE: ::NTSTATUS = 0xEB; +pub const FACILITY_LICENSING: ::NTSTATUS = 0xEA; +pub const FACILITY_IPSEC: ::NTSTATUS = 0x36; +pub const FACILITY_IO_ERROR_CODE: ::NTSTATUS = 0x4; +pub const FACILITY_INTERIX: ::NTSTATUS = 0x99; +pub const FACILITY_HYPERVISOR: ::NTSTATUS = 0x35; +pub const FACILITY_HID_ERROR_CODE: ::NTSTATUS = 0x11; +pub const FACILITY_GRAPHICS_KERNEL: ::NTSTATUS = 0x1E; +pub const FACILITY_FWP_ERROR_CODE: ::NTSTATUS = 0x22; +pub const FACILITY_FVE_ERROR_CODE: ::NTSTATUS = 0x21; +pub const FACILITY_FIREWIRE_ERROR_CODE: ::NTSTATUS = 0x12; +pub const FACILITY_FILTER_MANAGER: ::NTSTATUS = 0x1C; +pub const FACILITY_DRIVER_FRAMEWORK: ::NTSTATUS = 0x20; +pub const FACILITY_DEBUGGER: ::NTSTATUS = 0x1; +pub const FACILITY_COMMONLOG: ::NTSTATUS = 0x1A; +pub const FACILITY_CODCLASS_ERROR_CODE: ::NTSTATUS = 0x6; +pub const FACILITY_CLUSTER_ERROR_CODE: ::NTSTATUS = 0x13; +pub const FACILITY_NTCERT: ::NTSTATUS = 0x8; +pub const FACILITY_BTH_ATT: ::NTSTATUS = 0x42; +pub const FACILITY_BCD_ERROR_CODE: ::NTSTATUS = 0x39; +pub const FACILITY_AUDIO_KERNEL: ::NTSTATUS = 0x44; +pub const FACILITY_ACPI_ERROR_CODE: ::NTSTATUS = 0x14; +pub const STATUS_SEVERITY_WARNING: ::NTSTATUS = 0x2; +pub const STATUS_SEVERITY_SUCCESS: ::NTSTATUS = 0x0; +pub const STATUS_SEVERITY_INFORMATIONAL: ::NTSTATUS = 0x1; +pub const STATUS_SEVERITY_ERROR: ::NTSTATUS = 0x3; +pub const STATUS_SUCCESS: ::NTSTATUS = 0x00000000; +pub const STATUS_WAIT_1: ::NTSTATUS = 0x00000001; +pub const STATUS_WAIT_2: ::NTSTATUS = 0x00000002; +pub const STATUS_WAIT_3: ::NTSTATUS = 0x00000003; +pub const STATUS_WAIT_63: ::NTSTATUS = 0x0000003F; +pub const STATUS_ABANDONED: ::NTSTATUS = 0x00000080; +pub const STATUS_ABANDONED_WAIT_0: ::NTSTATUS = 0x00000080; +pub const STATUS_ABANDONED_WAIT_63: ::NTSTATUS = 0x000000BF; +pub const STATUS_USER_APC: ::NTSTATUS = 0x000000C0; +pub const STATUS_KERNEL_APC: ::NTSTATUS = 0x00000100; +pub const STATUS_ALERTED: ::NTSTATUS = 0x00000101; +pub const STATUS_TIMEOUT: ::NTSTATUS = 0x00000102; +pub const STATUS_PENDING: ::NTSTATUS = 0x00000103; +pub const STATUS_REPARSE: ::NTSTATUS = 0x00000104; +pub const STATUS_MORE_ENTRIES: ::NTSTATUS = 0x00000105; +pub const STATUS_NOT_ALL_ASSIGNED: ::NTSTATUS = 0x00000106; +pub const STATUS_SOME_NOT_MAPPED: ::NTSTATUS = 0x00000107; +pub const STATUS_OPLOCK_BREAK_IN_PROGRESS: ::NTSTATUS = 0x00000108; +pub const STATUS_VOLUME_MOUNTED: ::NTSTATUS = 0x00000109; +pub const STATUS_RXACT_COMMITTED: ::NTSTATUS = 0x0000010A; +pub const STATUS_NOTIFY_CLEANUP: ::NTSTATUS = 0x0000010B; +pub const STATUS_NOTIFY_ENUM_DIR: ::NTSTATUS = 0x0000010C; +pub const STATUS_NO_QUOTAS_FOR_ACCOUNT: ::NTSTATUS = 0x0000010D; +pub const STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED: ::NTSTATUS = 0x0000010E; +pub const STATUS_PAGE_FAULT_TRANSITION: ::NTSTATUS = 0x00000110; +pub const STATUS_PAGE_FAULT_DEMAND_ZERO: ::NTSTATUS = 0x00000111; +pub const STATUS_PAGE_FAULT_COPY_ON_WRITE: ::NTSTATUS = 0x00000112; +pub const STATUS_PAGE_FAULT_GUARD_PAGE: ::NTSTATUS = 0x00000113; +pub const STATUS_PAGE_FAULT_PAGING_FILE: ::NTSTATUS = 0x00000114; +pub const STATUS_CACHE_PAGE_LOCKED: ::NTSTATUS = 0x00000115; +pub const STATUS_CRASH_DUMP: ::NTSTATUS = 0x00000116; +pub const STATUS_BUFFER_ALL_ZEROS: ::NTSTATUS = 0x00000117; +pub const STATUS_REPARSE_OBJECT: ::NTSTATUS = 0x00000118; +pub const STATUS_RESOURCE_REQUIREMENTS_CHANGED: ::NTSTATUS = 0x00000119; +pub const STATUS_TRANSLATION_COMPLETE: ::NTSTATUS = 0x00000120; +pub const STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY: ::NTSTATUS = 0x00000121; +pub const STATUS_NOTHING_TO_TERMINATE: ::NTSTATUS = 0x00000122; +pub const STATUS_PROCESS_NOT_IN_JOB: ::NTSTATUS = 0x00000123; +pub const STATUS_PROCESS_IN_JOB: ::NTSTATUS = 0x00000124; +pub const STATUS_VOLSNAP_HIBERNATE_READY: ::NTSTATUS = 0x00000125; +pub const STATUS_FSFILTER_OP_COMPLETED_SUCCESSFULLY: ::NTSTATUS = 0x00000126; +pub const STATUS_INTERRUPT_VECTOR_ALREADY_CONNECTED: ::NTSTATUS = 0x00000127; +pub const STATUS_INTERRUPT_STILL_CONNECTED: ::NTSTATUS = 0x00000128; +pub const STATUS_PROCESS_CLONED: ::NTSTATUS = 0x00000129; +pub const STATUS_FILE_LOCKED_WITH_ONLY_READERS: ::NTSTATUS = 0x0000012A; +pub const STATUS_FILE_LOCKED_WITH_WRITERS: ::NTSTATUS = 0x0000012B; +pub const STATUS_VALID_IMAGE_HASH: ::NTSTATUS = 0x0000012C; +pub const STATUS_VALID_CATALOG_HASH: ::NTSTATUS = 0x0000012D; +pub const STATUS_VALID_STRONG_CODE_HASH: ::NTSTATUS = 0x0000012E; +pub const STATUS_RESOURCEMANAGER_READ_ONLY: ::NTSTATUS = 0x00000202; +pub const STATUS_RING_PREVIOUSLY_EMPTY: ::NTSTATUS = 0x00000210; +pub const STATUS_RING_PREVIOUSLY_FULL: ::NTSTATUS = 0x00000211; +pub const STATUS_RING_PREVIOUSLY_ABOVE_QUOTA: ::NTSTATUS = 0x00000212; +pub const STATUS_RING_NEWLY_EMPTY: ::NTSTATUS = 0x00000213; +pub const STATUS_RING_SIGNAL_OPPOSITE_ENDPOINT: ::NTSTATUS = 0x00000214; +pub const STATUS_OPLOCK_SWITCHED_TO_NEW_HANDLE: ::NTSTATUS = 0x00000215; +pub const STATUS_OPLOCK_HANDLE_CLOSED: ::NTSTATUS = 0x00000216; +pub const STATUS_WAIT_FOR_OPLOCK: ::NTSTATUS = 0x00000367; +pub const DBG_EXCEPTION_HANDLED: ::NTSTATUS = 0x00010001; +pub const DBG_CONTINUE: ::NTSTATUS = 0x00010002; +pub const STATUS_FLT_IO_COMPLETE: ::NTSTATUS = 0x001C0001; +pub const STATUS_OBJECT_NAME_EXISTS: ::NTSTATUS = 0x40000000; +pub const STATUS_THREAD_WAS_SUSPENDED: ::NTSTATUS = 0x40000001; +pub const STATUS_WORKING_SET_LIMIT_RANGE: ::NTSTATUS = 0x40000002; +pub const STATUS_IMAGE_NOT_AT_BASE: ::NTSTATUS = 0x40000003; +pub const STATUS_RXACT_STATE_CREATED: ::NTSTATUS = 0x40000004; +pub const STATUS_SEGMENT_NOTIFICATION: ::NTSTATUS = 0x40000005; +pub const STATUS_LOCAL_USER_SESSION_KEY: ::NTSTATUS = 0x40000006; +pub const STATUS_BAD_CURRENT_DIRECTORY: ::NTSTATUS = 0x40000007; +pub const STATUS_SERIAL_MORE_WRITES: ::NTSTATUS = 0x40000008; +pub const STATUS_REGISTRY_RECOVERED: ::NTSTATUS = 0x40000009; +pub const STATUS_FT_READ_RECOVERY_FROM_BACKUP: ::NTSTATUS = 0x4000000A; +pub const STATUS_FT_WRITE_RECOVERY: ::NTSTATUS = 0x4000000B; +pub const STATUS_SERIAL_COUNTER_TIMEOUT: ::NTSTATUS = 0x4000000C; +pub const STATUS_NULL_LM_PASSWORD: ::NTSTATUS = 0x4000000D; +pub const STATUS_IMAGE_MACHINE_TYPE_MISMATCH: ::NTSTATUS = 0x4000000E; +pub const STATUS_RECEIVE_PARTIAL: ::NTSTATUS = 0x4000000F; +pub const STATUS_RECEIVE_EXPEDITED: ::NTSTATUS = 0x40000010; +pub const STATUS_RECEIVE_PARTIAL_EXPEDITED: ::NTSTATUS = 0x40000011; +pub const STATUS_EVENT_DONE: ::NTSTATUS = 0x40000012; +pub const STATUS_EVENT_PENDING: ::NTSTATUS = 0x40000013; +pub const STATUS_CHECKING_FILE_SYSTEM: ::NTSTATUS = 0x40000014; +pub const STATUS_FATAL_APP_EXIT: ::NTSTATUS = 0x40000015; +pub const STATUS_PREDEFINED_HANDLE: ::NTSTATUS = 0x40000016; +pub const STATUS_WAS_UNLOCKED: ::NTSTATUS = 0x40000017; +pub const STATUS_SERVICE_NOTIFICATION: ::NTSTATUS = 0x40000018; +pub const STATUS_WAS_LOCKED: ::NTSTATUS = 0x40000019; +pub const STATUS_LOG_HARD_ERROR: ::NTSTATUS = 0x4000001A; +pub const STATUS_ALREADY_WIN32: ::NTSTATUS = 0x4000001B; +pub const STATUS_WX86_UNSIMULATE: ::NTSTATUS = 0x4000001C; +pub const STATUS_WX86_CONTINUE: ::NTSTATUS = 0x4000001D; +pub const STATUS_WX86_SINGLE_STEP: ::NTSTATUS = 0x4000001E; +pub const STATUS_WX86_BREAKPOINT: ::NTSTATUS = 0x4000001F; +pub const STATUS_WX86_EXCEPTION_CONTINUE: ::NTSTATUS = 0x40000020; +pub const STATUS_WX86_EXCEPTION_LASTCHANCE: ::NTSTATUS = 0x40000021; +pub const STATUS_WX86_EXCEPTION_CHAIN: ::NTSTATUS = 0x40000022; +pub const STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE: ::NTSTATUS = 0x40000023; +pub const STATUS_NO_YIELD_PERFORMED: ::NTSTATUS = 0x40000024; +pub const STATUS_TIMER_RESUME_IGNORED: ::NTSTATUS = 0x40000025; +pub const STATUS_ARBITRATION_UNHANDLED: ::NTSTATUS = 0x40000026; +pub const STATUS_CARDBUS_NOT_SUPPORTED: ::NTSTATUS = 0x40000027; +pub const STATUS_WX86_CREATEWX86TIB: ::NTSTATUS = 0x40000028; +pub const STATUS_MP_PROCESSOR_MISMATCH: ::NTSTATUS = 0x40000029; +pub const STATUS_HIBERNATED: ::NTSTATUS = 0x4000002A; +pub const STATUS_RESUME_HIBERNATION: ::NTSTATUS = 0x4000002B; +pub const STATUS_FIRMWARE_UPDATED: ::NTSTATUS = 0x4000002C; +pub const STATUS_DRIVERS_LEAKING_LOCKED_PAGES: ::NTSTATUS = 0x4000002D; +pub const STATUS_MESSAGE_RETRIEVED: ::NTSTATUS = 0x4000002E; +pub const STATUS_SYSTEM_POWERSTATE_TRANSITION: ::NTSTATUS = 0x4000002F; +pub const STATUS_ALPC_CHECK_COMPLETION_LIST: ::NTSTATUS = 0x40000030; +pub const STATUS_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: ::NTSTATUS = 0x40000031; +pub const STATUS_ACCESS_AUDIT_BY_POLICY: ::NTSTATUS = 0x40000032; +pub const STATUS_ABANDON_HIBERFILE: ::NTSTATUS = 0x40000033; +pub const STATUS_BIZRULES_NOT_ENABLED: ::NTSTATUS = 0x40000034; +pub const STATUS_FT_READ_FROM_COPY: ::NTSTATUS = 0x40000035; +pub const STATUS_IMAGE_AT_DIFFERENT_BASE: ::NTSTATUS = 0x40000036; +pub const DBG_REPLY_LATER: ::NTSTATUS = 0x40010001; +pub const DBG_UNABLE_TO_PROVIDE_HANDLE: ::NTSTATUS = 0x40010002; +pub const DBG_TERMINATE_THREAD: ::NTSTATUS = 0x40010003; +pub const DBG_TERMINATE_PROCESS: ::NTSTATUS = 0x40010004; +pub const DBG_CONTROL_C: ::NTSTATUS = 0x40010005; +pub const DBG_PRINTEXCEPTION_C: ::NTSTATUS = 0x40010006; +pub const DBG_RIPEXCEPTION: ::NTSTATUS = 0x40010007; +pub const DBG_CONTROL_BREAK: ::NTSTATUS = 0x40010008; +pub const DBG_COMMAND_EXCEPTION: ::NTSTATUS = 0x40010009; +pub const DBG_PRINTEXCEPTION_WIDE_C: ::NTSTATUS = 0x4001000A; +pub const STATUS_HEURISTIC_DAMAGE_POSSIBLE: ::NTSTATUS = 0x40190001; +pub const STATUS_GUARD_PAGE_VIOLATION: ::NTSTATUS = 0x80000001u32 as i32; +pub const STATUS_DATATYPE_MISALIGNMENT: ::NTSTATUS = 0x80000002u32 as i32; +pub const STATUS_BREAKPOINT: ::NTSTATUS = 0x80000003u32 as i32; +pub const STATUS_SINGLE_STEP: ::NTSTATUS = 0x80000004u32 as i32; +pub const STATUS_BUFFER_OVERFLOW: ::NTSTATUS = 0x80000005u32 as i32; +pub const STATUS_NO_MORE_FILES: ::NTSTATUS = 0x80000006u32 as i32; +pub const STATUS_WAKE_SYSTEM_DEBUGGER: ::NTSTATUS = 0x80000007u32 as i32; +pub const STATUS_HANDLES_CLOSED: ::NTSTATUS = 0x8000000Au32 as i32; +pub const STATUS_NO_INHERITANCE: ::NTSTATUS = 0x8000000Bu32 as i32; +pub const STATUS_GUID_SUBSTITUTION_MADE: ::NTSTATUS = 0x8000000Cu32 as i32; +pub const STATUS_PARTIAL_COPY: ::NTSTATUS = 0x8000000Du32 as i32; +pub const STATUS_DEVICE_PAPER_EMPTY: ::NTSTATUS = 0x8000000Eu32 as i32; +pub const STATUS_DEVICE_POWERED_OFF: ::NTSTATUS = 0x8000000Fu32 as i32; +pub const STATUS_DEVICE_OFF_LINE: ::NTSTATUS = 0x80000010u32 as i32; +pub const STATUS_DEVICE_BUSY: ::NTSTATUS = 0x80000011u32 as i32; +pub const STATUS_NO_MORE_EAS: ::NTSTATUS = 0x80000012u32 as i32; +pub const STATUS_INVALID_EA_NAME: ::NTSTATUS = 0x80000013u32 as i32; +pub const STATUS_EA_LIST_INCONSISTENT: ::NTSTATUS = 0x80000014u32 as i32; +pub const STATUS_INVALID_EA_FLAG: ::NTSTATUS = 0x80000015u32 as i32; +pub const STATUS_VERIFY_REQUIRED: ::NTSTATUS = 0x80000016u32 as i32; +pub const STATUS_EXTRANEOUS_INFORMATION: ::NTSTATUS = 0x80000017u32 as i32; +pub const STATUS_RXACT_COMMIT_NECESSARY: ::NTSTATUS = 0x80000018u32 as i32; +pub const STATUS_NO_MORE_ENTRIES: ::NTSTATUS = 0x8000001Au32 as i32; +pub const STATUS_FILEMARK_DETECTED: ::NTSTATUS = 0x8000001Bu32 as i32; +pub const STATUS_MEDIA_CHANGED: ::NTSTATUS = 0x8000001Cu32 as i32; +pub const STATUS_BUS_RESET: ::NTSTATUS = 0x8000001Du32 as i32; +pub const STATUS_END_OF_MEDIA: ::NTSTATUS = 0x8000001Eu32 as i32; +pub const STATUS_BEGINNING_OF_MEDIA: ::NTSTATUS = 0x8000001Fu32 as i32; +pub const STATUS_MEDIA_CHECK: ::NTSTATUS = 0x80000020u32 as i32; +pub const STATUS_SETMARK_DETECTED: ::NTSTATUS = 0x80000021u32 as i32; +pub const STATUS_NO_DATA_DETECTED: ::NTSTATUS = 0x80000022u32 as i32; +pub const STATUS_REDIRECTOR_HAS_OPEN_HANDLES: ::NTSTATUS = 0x80000023u32 as i32; +pub const STATUS_SERVER_HAS_OPEN_HANDLES: ::NTSTATUS = 0x80000024u32 as i32; +pub const STATUS_ALREADY_DISCONNECTED: ::NTSTATUS = 0x80000025u32 as i32; +pub const STATUS_LONGJUMP: ::NTSTATUS = 0x80000026u32 as i32; +pub const STATUS_CLEANER_CARTRIDGE_INSTALLED: ::NTSTATUS = 0x80000027u32 as i32; +pub const STATUS_PLUGPLAY_QUERY_VETOED: ::NTSTATUS = 0x80000028u32 as i32; +pub const STATUS_UNWIND_CONSOLIDATE: ::NTSTATUS = 0x80000029u32 as i32; +pub const STATUS_REGISTRY_HIVE_RECOVERED: ::NTSTATUS = 0x8000002Au32 as i32; +pub const STATUS_DLL_MIGHT_BE_INSECURE: ::NTSTATUS = 0x8000002Bu32 as i32; +pub const STATUS_DLL_MIGHT_BE_INCOMPATIBLE: ::NTSTATUS = 0x8000002Cu32 as i32; +pub const STATUS_STOPPED_ON_SYMLINK: ::NTSTATUS = 0x8000002Du32 as i32; +pub const STATUS_CANNOT_GRANT_REQUESTED_OPLOCK: ::NTSTATUS = 0x8000002Eu32 as i32; +pub const STATUS_NO_ACE_CONDITION: ::NTSTATUS = 0x8000002Fu32 as i32; +pub const STATUS_DEVICE_SUPPORT_IN_PROGRESS: ::NTSTATUS = 0x80000030u32 as i32; +pub const STATUS_DEVICE_POWER_CYCLE_REQUIRED: ::NTSTATUS = 0x80000031u32 as i32; +pub const DBG_EXCEPTION_NOT_HANDLED: ::NTSTATUS = 0x80010001u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_UP: ::NTSTATUS = 0x80130001u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_DOWN: ::NTSTATUS = 0x80130002u32 as i32; +pub const STATUS_CLUSTER_NETWORK_ALREADY_ONLINE: ::NTSTATUS = 0x80130003u32 as i32; +pub const STATUS_CLUSTER_NETWORK_ALREADY_OFFLINE: ::NTSTATUS = 0x80130004u32 as i32; +pub const STATUS_CLUSTER_NODE_ALREADY_MEMBER: ::NTSTATUS = 0x80130005u32 as i32; +pub const STATUS_FLT_BUFFER_TOO_SMALL: ::NTSTATUS = 0x801C0001u32 as i32; +pub const STATUS_FVE_PARTIAL_METADATA: ::NTSTATUS = 0x80210001u32 as i32; +pub const STATUS_FVE_TRANSIENT_STATE: ::NTSTATUS = 0x80210002u32 as i32; +pub const STATUS_UNSUCCESSFUL: ::NTSTATUS = 0xC0000001u32 as i32; +pub const STATUS_NOT_IMPLEMENTED: ::NTSTATUS = 0xC0000002u32 as i32; +pub const STATUS_INVALID_INFO_CLASS: ::NTSTATUS = 0xC0000003u32 as i32; +pub const STATUS_INFO_LENGTH_MISMATCH: ::NTSTATUS = 0xC0000004u32 as i32; +pub const STATUS_ACCESS_VIOLATION: ::NTSTATUS = 0xC0000005u32 as i32; +pub const STATUS_IN_PAGE_ERROR: ::NTSTATUS = 0xC0000006u32 as i32; +pub const STATUS_PAGEFILE_QUOTA: ::NTSTATUS = 0xC0000007u32 as i32; +pub const STATUS_INVALID_HANDLE: ::NTSTATUS = 0xC0000008u32 as i32; +pub const STATUS_BAD_INITIAL_STACK: ::NTSTATUS = 0xC0000009u32 as i32; +pub const STATUS_BAD_INITIAL_PC: ::NTSTATUS = 0xC000000Au32 as i32; +pub const STATUS_INVALID_CID: ::NTSTATUS = 0xC000000Bu32 as i32; +pub const STATUS_TIMER_NOT_CANCELED: ::NTSTATUS = 0xC000000Cu32 as i32; +pub const STATUS_INVALID_PARAMETER: ::NTSTATUS = 0xC000000Du32 as i32; +pub const STATUS_NO_SUCH_DEVICE: ::NTSTATUS = 0xC000000Eu32 as i32; +pub const STATUS_NO_SUCH_FILE: ::NTSTATUS = 0xC000000Fu32 as i32; +pub const STATUS_INVALID_DEVICE_REQUEST: ::NTSTATUS = 0xC0000010u32 as i32; +pub const STATUS_END_OF_FILE: ::NTSTATUS = 0xC0000011u32 as i32; +pub const STATUS_WRONG_VOLUME: ::NTSTATUS = 0xC0000012u32 as i32; +pub const STATUS_NO_MEDIA_IN_DEVICE: ::NTSTATUS = 0xC0000013u32 as i32; +pub const STATUS_UNRECOGNIZED_MEDIA: ::NTSTATUS = 0xC0000014u32 as i32; +pub const STATUS_NONEXISTENT_SECTOR: ::NTSTATUS = 0xC0000015u32 as i32; +pub const STATUS_MORE_PROCESSING_REQUIRED: ::NTSTATUS = 0xC0000016u32 as i32; +pub const STATUS_NO_MEMORY: ::NTSTATUS = 0xC0000017u32 as i32; +pub const STATUS_CONFLICTING_ADDRESSES: ::NTSTATUS = 0xC0000018u32 as i32; +pub const STATUS_NOT_MAPPED_VIEW: ::NTSTATUS = 0xC0000019u32 as i32; +pub const STATUS_UNABLE_TO_FREE_VM: ::NTSTATUS = 0xC000001Au32 as i32; +pub const STATUS_UNABLE_TO_DELETE_SECTION: ::NTSTATUS = 0xC000001Bu32 as i32; +pub const STATUS_INVALID_SYSTEM_SERVICE: ::NTSTATUS = 0xC000001Cu32 as i32; +pub const STATUS_ILLEGAL_INSTRUCTION: ::NTSTATUS = 0xC000001Du32 as i32; +pub const STATUS_INVALID_LOCK_SEQUENCE: ::NTSTATUS = 0xC000001Eu32 as i32; +pub const STATUS_INVALID_VIEW_SIZE: ::NTSTATUS = 0xC000001Fu32 as i32; +pub const STATUS_INVALID_FILE_FOR_SECTION: ::NTSTATUS = 0xC0000020u32 as i32; +pub const STATUS_ALREADY_COMMITTED: ::NTSTATUS = 0xC0000021u32 as i32; +pub const STATUS_ACCESS_DENIED: ::NTSTATUS = 0xC0000022u32 as i32; +pub const STATUS_BUFFER_TOO_SMALL: ::NTSTATUS = 0xC0000023u32 as i32; +pub const STATUS_OBJECT_TYPE_MISMATCH: ::NTSTATUS = 0xC0000024u32 as i32; +pub const STATUS_NONCONTINUABLE_EXCEPTION: ::NTSTATUS = 0xC0000025u32 as i32; +pub const STATUS_INVALID_DISPOSITION: ::NTSTATUS = 0xC0000026u32 as i32; +pub const STATUS_UNWIND: ::NTSTATUS = 0xC0000027u32 as i32; +pub const STATUS_BAD_STACK: ::NTSTATUS = 0xC0000028u32 as i32; +pub const STATUS_INVALID_UNWIND_TARGET: ::NTSTATUS = 0xC0000029u32 as i32; +pub const STATUS_NOT_LOCKED: ::NTSTATUS = 0xC000002Au32 as i32; +pub const STATUS_PARITY_ERROR: ::NTSTATUS = 0xC000002Bu32 as i32; +pub const STATUS_UNABLE_TO_DECOMMIT_VM: ::NTSTATUS = 0xC000002Cu32 as i32; +pub const STATUS_NOT_COMMITTED: ::NTSTATUS = 0xC000002Du32 as i32; +pub const STATUS_INVALID_PORT_ATTRIBUTES: ::NTSTATUS = 0xC000002Eu32 as i32; +pub const STATUS_PORT_MESSAGE_TOO_LONG: ::NTSTATUS = 0xC000002Fu32 as i32; +pub const STATUS_INVALID_PARAMETER_MIX: ::NTSTATUS = 0xC0000030u32 as i32; +pub const STATUS_INVALID_QUOTA_LOWER: ::NTSTATUS = 0xC0000031u32 as i32; +pub const STATUS_DISK_CORRUPT_ERROR: ::NTSTATUS = 0xC0000032u32 as i32; +pub const STATUS_OBJECT_NAME_INVALID: ::NTSTATUS = 0xC0000033u32 as i32; +pub const STATUS_OBJECT_NAME_NOT_FOUND: ::NTSTATUS = 0xC0000034u32 as i32; +pub const STATUS_OBJECT_NAME_COLLISION: ::NTSTATUS = 0xC0000035u32 as i32; +pub const STATUS_PORT_DO_NOT_DISTURB: ::NTSTATUS = 0xC0000036u32 as i32; +pub const STATUS_PORT_DISCONNECTED: ::NTSTATUS = 0xC0000037u32 as i32; +pub const STATUS_DEVICE_ALREADY_ATTACHED: ::NTSTATUS = 0xC0000038u32 as i32; +pub const STATUS_OBJECT_PATH_INVALID: ::NTSTATUS = 0xC0000039u32 as i32; +pub const STATUS_OBJECT_PATH_NOT_FOUND: ::NTSTATUS = 0xC000003Au32 as i32; +pub const STATUS_OBJECT_PATH_SYNTAX_BAD: ::NTSTATUS = 0xC000003Bu32 as i32; +pub const STATUS_DATA_OVERRUN: ::NTSTATUS = 0xC000003Cu32 as i32; +pub const STATUS_DATA_LATE_ERROR: ::NTSTATUS = 0xC000003Du32 as i32; +pub const STATUS_DATA_ERROR: ::NTSTATUS = 0xC000003Eu32 as i32; +pub const STATUS_CRC_ERROR: ::NTSTATUS = 0xC000003Fu32 as i32; +pub const STATUS_SECTION_TOO_BIG: ::NTSTATUS = 0xC0000040u32 as i32; +pub const STATUS_PORT_CONNECTION_REFUSED: ::NTSTATUS = 0xC0000041u32 as i32; +pub const STATUS_INVALID_PORT_HANDLE: ::NTSTATUS = 0xC0000042u32 as i32; +pub const STATUS_SHARING_VIOLATION: ::NTSTATUS = 0xC0000043u32 as i32; +pub const STATUS_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000044u32 as i32; +pub const STATUS_INVALID_PAGE_PROTECTION: ::NTSTATUS = 0xC0000045u32 as i32; +pub const STATUS_MUTANT_NOT_OWNED: ::NTSTATUS = 0xC0000046u32 as i32; +pub const STATUS_SEMAPHORE_LIMIT_EXCEEDED: ::NTSTATUS = 0xC0000047u32 as i32; +pub const STATUS_PORT_ALREADY_SET: ::NTSTATUS = 0xC0000048u32 as i32; +pub const STATUS_SECTION_NOT_IMAGE: ::NTSTATUS = 0xC0000049u32 as i32; +pub const STATUS_SUSPEND_COUNT_EXCEEDED: ::NTSTATUS = 0xC000004Au32 as i32; +pub const STATUS_THREAD_IS_TERMINATING: ::NTSTATUS = 0xC000004Bu32 as i32; +pub const STATUS_BAD_WORKING_SET_LIMIT: ::NTSTATUS = 0xC000004Cu32 as i32; +pub const STATUS_INCOMPATIBLE_FILE_MAP: ::NTSTATUS = 0xC000004Du32 as i32; +pub const STATUS_SECTION_PROTECTION: ::NTSTATUS = 0xC000004Eu32 as i32; +pub const STATUS_EAS_NOT_SUPPORTED: ::NTSTATUS = 0xC000004Fu32 as i32; +pub const STATUS_EA_TOO_LARGE: ::NTSTATUS = 0xC0000050u32 as i32; +pub const STATUS_NONEXISTENT_EA_ENTRY: ::NTSTATUS = 0xC0000051u32 as i32; +pub const STATUS_NO_EAS_ON_FILE: ::NTSTATUS = 0xC0000052u32 as i32; +pub const STATUS_EA_CORRUPT_ERROR: ::NTSTATUS = 0xC0000053u32 as i32; +pub const STATUS_FILE_LOCK_CONFLICT: ::NTSTATUS = 0xC0000054u32 as i32; +pub const STATUS_LOCK_NOT_GRANTED: ::NTSTATUS = 0xC0000055u32 as i32; +pub const STATUS_DELETE_PENDING: ::NTSTATUS = 0xC0000056u32 as i32; +pub const STATUS_CTL_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC0000057u32 as i32; +pub const STATUS_UNKNOWN_REVISION: ::NTSTATUS = 0xC0000058u32 as i32; +pub const STATUS_REVISION_MISMATCH: ::NTSTATUS = 0xC0000059u32 as i32; +pub const STATUS_INVALID_OWNER: ::NTSTATUS = 0xC000005Au32 as i32; +pub const STATUS_INVALID_PRIMARY_GROUP: ::NTSTATUS = 0xC000005Bu32 as i32; +pub const STATUS_NO_IMPERSONATION_TOKEN: ::NTSTATUS = 0xC000005Cu32 as i32; +pub const STATUS_CANT_DISABLE_MANDATORY: ::NTSTATUS = 0xC000005Du32 as i32; +pub const STATUS_NO_LOGON_SERVERS: ::NTSTATUS = 0xC000005Eu32 as i32; +pub const STATUS_NO_SUCH_LOGON_SESSION: ::NTSTATUS = 0xC000005Fu32 as i32; +pub const STATUS_NO_SUCH_PRIVILEGE: ::NTSTATUS = 0xC0000060u32 as i32; +pub const STATUS_PRIVILEGE_NOT_HELD: ::NTSTATUS = 0xC0000061u32 as i32; +pub const STATUS_INVALID_ACCOUNT_NAME: ::NTSTATUS = 0xC0000062u32 as i32; +pub const STATUS_USER_EXISTS: ::NTSTATUS = 0xC0000063u32 as i32; +pub const STATUS_NO_SUCH_USER: ::NTSTATUS = 0xC0000064u32 as i32; +pub const STATUS_GROUP_EXISTS: ::NTSTATUS = 0xC0000065u32 as i32; +pub const STATUS_NO_SUCH_GROUP: ::NTSTATUS = 0xC0000066u32 as i32; +pub const STATUS_MEMBER_IN_GROUP: ::NTSTATUS = 0xC0000067u32 as i32; +pub const STATUS_MEMBER_NOT_IN_GROUP: ::NTSTATUS = 0xC0000068u32 as i32; +pub const STATUS_LAST_ADMIN: ::NTSTATUS = 0xC0000069u32 as i32; +pub const STATUS_WRONG_PASSWORD: ::NTSTATUS = 0xC000006Au32 as i32; +pub const STATUS_ILL_FORMED_PASSWORD: ::NTSTATUS = 0xC000006Bu32 as i32; +pub const STATUS_PASSWORD_RESTRICTION: ::NTSTATUS = 0xC000006Cu32 as i32; +pub const STATUS_LOGON_FAILURE: ::NTSTATUS = 0xC000006Du32 as i32; +pub const STATUS_ACCOUNT_RESTRICTION: ::NTSTATUS = 0xC000006Eu32 as i32; +pub const STATUS_INVALID_LOGON_HOURS: ::NTSTATUS = 0xC000006Fu32 as i32; +pub const STATUS_INVALID_WORKSTATION: ::NTSTATUS = 0xC0000070u32 as i32; +pub const STATUS_PASSWORD_EXPIRED: ::NTSTATUS = 0xC0000071u32 as i32; +pub const STATUS_ACCOUNT_DISABLED: ::NTSTATUS = 0xC0000072u32 as i32; +pub const STATUS_NONE_MAPPED: ::NTSTATUS = 0xC0000073u32 as i32; +pub const STATUS_TOO_MANY_LUIDS_REQUESTED: ::NTSTATUS = 0xC0000074u32 as i32; +pub const STATUS_LUIDS_EXHAUSTED: ::NTSTATUS = 0xC0000075u32 as i32; +pub const STATUS_INVALID_SUB_AUTHORITY: ::NTSTATUS = 0xC0000076u32 as i32; +pub const STATUS_INVALID_ACL: ::NTSTATUS = 0xC0000077u32 as i32; +pub const STATUS_INVALID_SID: ::NTSTATUS = 0xC0000078u32 as i32; +pub const STATUS_INVALID_SECURITY_DESCR: ::NTSTATUS = 0xC0000079u32 as i32; +pub const STATUS_PROCEDURE_NOT_FOUND: ::NTSTATUS = 0xC000007Au32 as i32; +pub const STATUS_INVALID_IMAGE_FORMAT: ::NTSTATUS = 0xC000007Bu32 as i32; +pub const STATUS_NO_TOKEN: ::NTSTATUS = 0xC000007Cu32 as i32; +pub const STATUS_BAD_INHERITANCE_ACL: ::NTSTATUS = 0xC000007Du32 as i32; +pub const STATUS_RANGE_NOT_LOCKED: ::NTSTATUS = 0xC000007Eu32 as i32; +pub const STATUS_DISK_FULL: ::NTSTATUS = 0xC000007Fu32 as i32; +pub const STATUS_SERVER_DISABLED: ::NTSTATUS = 0xC0000080u32 as i32; +pub const STATUS_SERVER_NOT_DISABLED: ::NTSTATUS = 0xC0000081u32 as i32; +pub const STATUS_TOO_MANY_GUIDS_REQUESTED: ::NTSTATUS = 0xC0000082u32 as i32; +pub const STATUS_GUIDS_EXHAUSTED: ::NTSTATUS = 0xC0000083u32 as i32; +pub const STATUS_INVALID_ID_AUTHORITY: ::NTSTATUS = 0xC0000084u32 as i32; +pub const STATUS_AGENTS_EXHAUSTED: ::NTSTATUS = 0xC0000085u32 as i32; +pub const STATUS_INVALID_VOLUME_LABEL: ::NTSTATUS = 0xC0000086u32 as i32; +pub const STATUS_SECTION_NOT_EXTENDED: ::NTSTATUS = 0xC0000087u32 as i32; +pub const STATUS_NOT_MAPPED_DATA: ::NTSTATUS = 0xC0000088u32 as i32; +pub const STATUS_RESOURCE_DATA_NOT_FOUND: ::NTSTATUS = 0xC0000089u32 as i32; +pub const STATUS_RESOURCE_TYPE_NOT_FOUND: ::NTSTATUS = 0xC000008Au32 as i32; +pub const STATUS_RESOURCE_NAME_NOT_FOUND: ::NTSTATUS = 0xC000008Bu32 as i32; +pub const STATUS_ARRAY_BOUNDS_EXCEEDED: ::NTSTATUS = 0xC000008Cu32 as i32; +pub const STATUS_FLOAT_DENORMAL_OPERAND: ::NTSTATUS = 0xC000008Du32 as i32; +pub const STATUS_FLOAT_DIVIDE_BY_ZERO: ::NTSTATUS = 0xC000008Eu32 as i32; +pub const STATUS_FLOAT_INEXACT_RESULT: ::NTSTATUS = 0xC000008Fu32 as i32; +pub const STATUS_FLOAT_INVALID_OPERATION: ::NTSTATUS = 0xC0000090u32 as i32; +pub const STATUS_FLOAT_OVERFLOW: ::NTSTATUS = 0xC0000091u32 as i32; +pub const STATUS_FLOAT_STACK_CHECK: ::NTSTATUS = 0xC0000092u32 as i32; +pub const STATUS_FLOAT_UNDERFLOW: ::NTSTATUS = 0xC0000093u32 as i32; +pub const STATUS_INTEGER_DIVIDE_BY_ZERO: ::NTSTATUS = 0xC0000094u32 as i32; +pub const STATUS_INTEGER_OVERFLOW: ::NTSTATUS = 0xC0000095u32 as i32; +pub const STATUS_PRIVILEGED_INSTRUCTION: ::NTSTATUS = 0xC0000096u32 as i32; +pub const STATUS_TOO_MANY_PAGING_FILES: ::NTSTATUS = 0xC0000097u32 as i32; +pub const STATUS_FILE_INVALID: ::NTSTATUS = 0xC0000098u32 as i32; +pub const STATUS_ALLOTTED_SPACE_EXCEEDED: ::NTSTATUS = 0xC0000099u32 as i32; +pub const STATUS_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC000009Au32 as i32; +pub const STATUS_DFS_EXIT_PATH_FOUND: ::NTSTATUS = 0xC000009Bu32 as i32; +pub const STATUS_DEVICE_DATA_ERROR: ::NTSTATUS = 0xC000009Cu32 as i32; +pub const STATUS_DEVICE_NOT_CONNECTED: ::NTSTATUS = 0xC000009Du32 as i32; +pub const STATUS_DEVICE_POWER_FAILURE: ::NTSTATUS = 0xC000009Eu32 as i32; +pub const STATUS_FREE_VM_NOT_AT_BASE: ::NTSTATUS = 0xC000009Fu32 as i32; +pub const STATUS_MEMORY_NOT_ALLOCATED: ::NTSTATUS = 0xC00000A0u32 as i32; +pub const STATUS_WORKING_SET_QUOTA: ::NTSTATUS = 0xC00000A1u32 as i32; +pub const STATUS_MEDIA_WRITE_PROTECTED: ::NTSTATUS = 0xC00000A2u32 as i32; +pub const STATUS_DEVICE_NOT_READY: ::NTSTATUS = 0xC00000A3u32 as i32; +pub const STATUS_INVALID_GROUP_ATTRIBUTES: ::NTSTATUS = 0xC00000A4u32 as i32; +pub const STATUS_BAD_IMPERSONATION_LEVEL: ::NTSTATUS = 0xC00000A5u32 as i32; +pub const STATUS_CANT_OPEN_ANONYMOUS: ::NTSTATUS = 0xC00000A6u32 as i32; +pub const STATUS_BAD_VALIDATION_CLASS: ::NTSTATUS = 0xC00000A7u32 as i32; +pub const STATUS_BAD_TOKEN_TYPE: ::NTSTATUS = 0xC00000A8u32 as i32; +pub const STATUS_BAD_MASTER_BOOT_RECORD: ::NTSTATUS = 0xC00000A9u32 as i32; +pub const STATUS_INSTRUCTION_MISALIGNMENT: ::NTSTATUS = 0xC00000AAu32 as i32; +pub const STATUS_INSTANCE_NOT_AVAILABLE: ::NTSTATUS = 0xC00000ABu32 as i32; +pub const STATUS_PIPE_NOT_AVAILABLE: ::NTSTATUS = 0xC00000ACu32 as i32; +pub const STATUS_INVALID_PIPE_STATE: ::NTSTATUS = 0xC00000ADu32 as i32; +pub const STATUS_PIPE_BUSY: ::NTSTATUS = 0xC00000AEu32 as i32; +pub const STATUS_ILLEGAL_FUNCTION: ::NTSTATUS = 0xC00000AFu32 as i32; +pub const STATUS_PIPE_DISCONNECTED: ::NTSTATUS = 0xC00000B0u32 as i32; +pub const STATUS_PIPE_CLOSING: ::NTSTATUS = 0xC00000B1u32 as i32; +pub const STATUS_PIPE_CONNECTED: ::NTSTATUS = 0xC00000B2u32 as i32; +pub const STATUS_PIPE_LISTENING: ::NTSTATUS = 0xC00000B3u32 as i32; +pub const STATUS_INVALID_READ_MODE: ::NTSTATUS = 0xC00000B4u32 as i32; +pub const STATUS_IO_TIMEOUT: ::NTSTATUS = 0xC00000B5u32 as i32; +pub const STATUS_FILE_FORCED_CLOSED: ::NTSTATUS = 0xC00000B6u32 as i32; +pub const STATUS_PROFILING_NOT_STARTED: ::NTSTATUS = 0xC00000B7u32 as i32; +pub const STATUS_PROFILING_NOT_STOPPED: ::NTSTATUS = 0xC00000B8u32 as i32; +pub const STATUS_COULD_NOT_INTERPRET: ::NTSTATUS = 0xC00000B9u32 as i32; +pub const STATUS_FILE_IS_A_DIRECTORY: ::NTSTATUS = 0xC00000BAu32 as i32; +pub const STATUS_NOT_SUPPORTED: ::NTSTATUS = 0xC00000BBu32 as i32; +pub const STATUS_REMOTE_NOT_LISTENING: ::NTSTATUS = 0xC00000BCu32 as i32; +pub const STATUS_DUPLICATE_NAME: ::NTSTATUS = 0xC00000BDu32 as i32; +pub const STATUS_BAD_NETWORK_PATH: ::NTSTATUS = 0xC00000BEu32 as i32; +pub const STATUS_NETWORK_BUSY: ::NTSTATUS = 0xC00000BFu32 as i32; +pub const STATUS_DEVICE_DOES_NOT_EXIST: ::NTSTATUS = 0xC00000C0u32 as i32; +pub const STATUS_TOO_MANY_COMMANDS: ::NTSTATUS = 0xC00000C1u32 as i32; +pub const STATUS_ADAPTER_HARDWARE_ERROR: ::NTSTATUS = 0xC00000C2u32 as i32; +pub const STATUS_INVALID_NETWORK_RESPONSE: ::NTSTATUS = 0xC00000C3u32 as i32; +pub const STATUS_UNEXPECTED_NETWORK_ERROR: ::NTSTATUS = 0xC00000C4u32 as i32; +pub const STATUS_BAD_REMOTE_ADAPTER: ::NTSTATUS = 0xC00000C5u32 as i32; +pub const STATUS_PRINT_QUEUE_FULL: ::NTSTATUS = 0xC00000C6u32 as i32; +pub const STATUS_NO_SPOOL_SPACE: ::NTSTATUS = 0xC00000C7u32 as i32; +pub const STATUS_PRINT_CANCELLED: ::NTSTATUS = 0xC00000C8u32 as i32; +pub const STATUS_NETWORK_NAME_DELETED: ::NTSTATUS = 0xC00000C9u32 as i32; +pub const STATUS_NETWORK_ACCESS_DENIED: ::NTSTATUS = 0xC00000CAu32 as i32; +pub const STATUS_BAD_DEVICE_TYPE: ::NTSTATUS = 0xC00000CBu32 as i32; +pub const STATUS_BAD_NETWORK_NAME: ::NTSTATUS = 0xC00000CCu32 as i32; +pub const STATUS_TOO_MANY_NAMES: ::NTSTATUS = 0xC00000CDu32 as i32; +pub const STATUS_TOO_MANY_SESSIONS: ::NTSTATUS = 0xC00000CEu32 as i32; +pub const STATUS_SHARING_PAUSED: ::NTSTATUS = 0xC00000CFu32 as i32; +pub const STATUS_REQUEST_NOT_ACCEPTED: ::NTSTATUS = 0xC00000D0u32 as i32; +pub const STATUS_REDIRECTOR_PAUSED: ::NTSTATUS = 0xC00000D1u32 as i32; +pub const STATUS_NET_WRITE_FAULT: ::NTSTATUS = 0xC00000D2u32 as i32; +pub const STATUS_PROFILING_AT_LIMIT: ::NTSTATUS = 0xC00000D3u32 as i32; +pub const STATUS_NOT_SAME_DEVICE: ::NTSTATUS = 0xC00000D4u32 as i32; +pub const STATUS_FILE_RENAMED: ::NTSTATUS = 0xC00000D5u32 as i32; +pub const STATUS_VIRTUAL_CIRCUIT_CLOSED: ::NTSTATUS = 0xC00000D6u32 as i32; +pub const STATUS_NO_SECURITY_ON_OBJECT: ::NTSTATUS = 0xC00000D7u32 as i32; +pub const STATUS_CANT_WAIT: ::NTSTATUS = 0xC00000D8u32 as i32; +pub const STATUS_PIPE_EMPTY: ::NTSTATUS = 0xC00000D9u32 as i32; +pub const STATUS_CANT_ACCESS_DOMAIN_INFO: ::NTSTATUS = 0xC00000DAu32 as i32; +pub const STATUS_CANT_TERMINATE_SELF: ::NTSTATUS = 0xC00000DBu32 as i32; +pub const STATUS_INVALID_SERVER_STATE: ::NTSTATUS = 0xC00000DCu32 as i32; +pub const STATUS_INVALID_DOMAIN_STATE: ::NTSTATUS = 0xC00000DDu32 as i32; +pub const STATUS_INVALID_DOMAIN_ROLE: ::NTSTATUS = 0xC00000DEu32 as i32; +pub const STATUS_NO_SUCH_DOMAIN: ::NTSTATUS = 0xC00000DFu32 as i32; +pub const STATUS_DOMAIN_EXISTS: ::NTSTATUS = 0xC00000E0u32 as i32; +pub const STATUS_DOMAIN_LIMIT_EXCEEDED: ::NTSTATUS = 0xC00000E1u32 as i32; +pub const STATUS_OPLOCK_NOT_GRANTED: ::NTSTATUS = 0xC00000E2u32 as i32; +pub const STATUS_INVALID_OPLOCK_PROTOCOL: ::NTSTATUS = 0xC00000E3u32 as i32; +pub const STATUS_INTERNAL_DB_CORRUPTION: ::NTSTATUS = 0xC00000E4u32 as i32; +pub const STATUS_INTERNAL_ERROR: ::NTSTATUS = 0xC00000E5u32 as i32; +pub const STATUS_GENERIC_NOT_MAPPED: ::NTSTATUS = 0xC00000E6u32 as i32; +pub const STATUS_BAD_DESCRIPTOR_FORMAT: ::NTSTATUS = 0xC00000E7u32 as i32; +pub const STATUS_INVALID_USER_BUFFER: ::NTSTATUS = 0xC00000E8u32 as i32; +pub const STATUS_UNEXPECTED_IO_ERROR: ::NTSTATUS = 0xC00000E9u32 as i32; +pub const STATUS_UNEXPECTED_MM_CREATE_ERR: ::NTSTATUS = 0xC00000EAu32 as i32; +pub const STATUS_UNEXPECTED_MM_MAP_ERROR: ::NTSTATUS = 0xC00000EBu32 as i32; +pub const STATUS_UNEXPECTED_MM_EXTEND_ERR: ::NTSTATUS = 0xC00000ECu32 as i32; +pub const STATUS_NOT_LOGON_PROCESS: ::NTSTATUS = 0xC00000EDu32 as i32; +pub const STATUS_LOGON_SESSION_EXISTS: ::NTSTATUS = 0xC00000EEu32 as i32; +pub const STATUS_INVALID_PARAMETER_1: ::NTSTATUS = 0xC00000EFu32 as i32; +pub const STATUS_INVALID_PARAMETER_2: ::NTSTATUS = 0xC00000F0u32 as i32; +pub const STATUS_INVALID_PARAMETER_3: ::NTSTATUS = 0xC00000F1u32 as i32; +pub const STATUS_INVALID_PARAMETER_4: ::NTSTATUS = 0xC00000F2u32 as i32; +pub const STATUS_INVALID_PARAMETER_5: ::NTSTATUS = 0xC00000F3u32 as i32; +pub const STATUS_INVALID_PARAMETER_6: ::NTSTATUS = 0xC00000F4u32 as i32; +pub const STATUS_INVALID_PARAMETER_7: ::NTSTATUS = 0xC00000F5u32 as i32; +pub const STATUS_INVALID_PARAMETER_8: ::NTSTATUS = 0xC00000F6u32 as i32; +pub const STATUS_INVALID_PARAMETER_9: ::NTSTATUS = 0xC00000F7u32 as i32; +pub const STATUS_INVALID_PARAMETER_10: ::NTSTATUS = 0xC00000F8u32 as i32; +pub const STATUS_INVALID_PARAMETER_11: ::NTSTATUS = 0xC00000F9u32 as i32; +pub const STATUS_INVALID_PARAMETER_12: ::NTSTATUS = 0xC00000FAu32 as i32; +pub const STATUS_REDIRECTOR_NOT_STARTED: ::NTSTATUS = 0xC00000FBu32 as i32; +pub const STATUS_REDIRECTOR_STARTED: ::NTSTATUS = 0xC00000FCu32 as i32; +pub const STATUS_STACK_OVERFLOW: ::NTSTATUS = 0xC00000FDu32 as i32; +pub const STATUS_NO_SUCH_PACKAGE: ::NTSTATUS = 0xC00000FEu32 as i32; +pub const STATUS_BAD_FUNCTION_TABLE: ::NTSTATUS = 0xC00000FFu32 as i32; +pub const STATUS_VARIABLE_NOT_FOUND: ::NTSTATUS = 0xC0000100u32 as i32; +pub const STATUS_DIRECTORY_NOT_EMPTY: ::NTSTATUS = 0xC0000101u32 as i32; +pub const STATUS_FILE_CORRUPT_ERROR: ::NTSTATUS = 0xC0000102u32 as i32; +pub const STATUS_NOT_A_DIRECTORY: ::NTSTATUS = 0xC0000103u32 as i32; +pub const STATUS_BAD_LOGON_SESSION_STATE: ::NTSTATUS = 0xC0000104u32 as i32; +pub const STATUS_LOGON_SESSION_COLLISION: ::NTSTATUS = 0xC0000105u32 as i32; +pub const STATUS_NAME_TOO_LONG: ::NTSTATUS = 0xC0000106u32 as i32; +pub const STATUS_FILES_OPEN: ::NTSTATUS = 0xC0000107u32 as i32; +pub const STATUS_CONNECTION_IN_USE: ::NTSTATUS = 0xC0000108u32 as i32; +pub const STATUS_MESSAGE_NOT_FOUND: ::NTSTATUS = 0xC0000109u32 as i32; +pub const STATUS_PROCESS_IS_TERMINATING: ::NTSTATUS = 0xC000010Au32 as i32; +pub const STATUS_INVALID_LOGON_TYPE: ::NTSTATUS = 0xC000010Bu32 as i32; +pub const STATUS_NO_GUID_TRANSLATION: ::NTSTATUS = 0xC000010Cu32 as i32; +pub const STATUS_CANNOT_IMPERSONATE: ::NTSTATUS = 0xC000010Du32 as i32; +pub const STATUS_IMAGE_ALREADY_LOADED: ::NTSTATUS = 0xC000010Eu32 as i32; +pub const STATUS_ABIOS_NOT_PRESENT: ::NTSTATUS = 0xC000010Fu32 as i32; +pub const STATUS_ABIOS_LID_NOT_EXIST: ::NTSTATUS = 0xC0000110u32 as i32; +pub const STATUS_ABIOS_LID_ALREADY_OWNED: ::NTSTATUS = 0xC0000111u32 as i32; +pub const STATUS_ABIOS_NOT_LID_OWNER: ::NTSTATUS = 0xC0000112u32 as i32; +pub const STATUS_ABIOS_INVALID_COMMAND: ::NTSTATUS = 0xC0000113u32 as i32; +pub const STATUS_ABIOS_INVALID_LID: ::NTSTATUS = 0xC0000114u32 as i32; +pub const STATUS_ABIOS_SELECTOR_NOT_AVAILABLE: ::NTSTATUS = 0xC0000115u32 as i32; +pub const STATUS_ABIOS_INVALID_SELECTOR: ::NTSTATUS = 0xC0000116u32 as i32; +pub const STATUS_NO_LDT: ::NTSTATUS = 0xC0000117u32 as i32; +pub const STATUS_INVALID_LDT_SIZE: ::NTSTATUS = 0xC0000118u32 as i32; +pub const STATUS_INVALID_LDT_OFFSET: ::NTSTATUS = 0xC0000119u32 as i32; +pub const STATUS_INVALID_LDT_DESCRIPTOR: ::NTSTATUS = 0xC000011Au32 as i32; +pub const STATUS_INVALID_IMAGE_NE_FORMAT: ::NTSTATUS = 0xC000011Bu32 as i32; +pub const STATUS_RXACT_INVALID_STATE: ::NTSTATUS = 0xC000011Cu32 as i32; +pub const STATUS_RXACT_COMMIT_FAILURE: ::NTSTATUS = 0xC000011Du32 as i32; +pub const STATUS_MAPPED_FILE_SIZE_ZERO: ::NTSTATUS = 0xC000011Eu32 as i32; +pub const STATUS_TOO_MANY_OPENED_FILES: ::NTSTATUS = 0xC000011Fu32 as i32; +pub const STATUS_CANCELLED: ::NTSTATUS = 0xC0000120u32 as i32; +pub const STATUS_CANNOT_DELETE: ::NTSTATUS = 0xC0000121u32 as i32; +pub const STATUS_INVALID_COMPUTER_NAME: ::NTSTATUS = 0xC0000122u32 as i32; +pub const STATUS_FILE_DELETED: ::NTSTATUS = 0xC0000123u32 as i32; +pub const STATUS_SPECIAL_ACCOUNT: ::NTSTATUS = 0xC0000124u32 as i32; +pub const STATUS_SPECIAL_GROUP: ::NTSTATUS = 0xC0000125u32 as i32; +pub const STATUS_SPECIAL_USER: ::NTSTATUS = 0xC0000126u32 as i32; +pub const STATUS_MEMBERS_PRIMARY_GROUP: ::NTSTATUS = 0xC0000127u32 as i32; +pub const STATUS_FILE_CLOSED: ::NTSTATUS = 0xC0000128u32 as i32; +pub const STATUS_TOO_MANY_THREADS: ::NTSTATUS = 0xC0000129u32 as i32; +pub const STATUS_THREAD_NOT_IN_PROCESS: ::NTSTATUS = 0xC000012Au32 as i32; +pub const STATUS_TOKEN_ALREADY_IN_USE: ::NTSTATUS = 0xC000012Bu32 as i32; +pub const STATUS_PAGEFILE_QUOTA_EXCEEDED: ::NTSTATUS = 0xC000012Cu32 as i32; +pub const STATUS_COMMITMENT_LIMIT: ::NTSTATUS = 0xC000012Du32 as i32; +pub const STATUS_INVALID_IMAGE_LE_FORMAT: ::NTSTATUS = 0xC000012Eu32 as i32; +pub const STATUS_INVALID_IMAGE_NOT_MZ: ::NTSTATUS = 0xC000012Fu32 as i32; +pub const STATUS_INVALID_IMAGE_PROTECT: ::NTSTATUS = 0xC0000130u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_16: ::NTSTATUS = 0xC0000131u32 as i32; +pub const STATUS_LOGON_SERVER_CONFLICT: ::NTSTATUS = 0xC0000132u32 as i32; +pub const STATUS_TIME_DIFFERENCE_AT_DC: ::NTSTATUS = 0xC0000133u32 as i32; +pub const STATUS_SYNCHRONIZATION_REQUIRED: ::NTSTATUS = 0xC0000134u32 as i32; +pub const STATUS_DLL_NOT_FOUND: ::NTSTATUS = 0xC0000135u32 as i32; +pub const STATUS_OPEN_FAILED: ::NTSTATUS = 0xC0000136u32 as i32; +pub const STATUS_IO_PRIVILEGE_FAILED: ::NTSTATUS = 0xC0000137u32 as i32; +pub const STATUS_ORDINAL_NOT_FOUND: ::NTSTATUS = 0xC0000138u32 as i32; +pub const STATUS_ENTRYPOINT_NOT_FOUND: ::NTSTATUS = 0xC0000139u32 as i32; +pub const STATUS_CONTROL_C_EXIT: ::NTSTATUS = 0xC000013Au32 as i32; +pub const STATUS_LOCAL_DISCONNECT: ::NTSTATUS = 0xC000013Bu32 as i32; +pub const STATUS_REMOTE_DISCONNECT: ::NTSTATUS = 0xC000013Cu32 as i32; +pub const STATUS_REMOTE_RESOURCES: ::NTSTATUS = 0xC000013Du32 as i32; +pub const STATUS_LINK_FAILED: ::NTSTATUS = 0xC000013Eu32 as i32; +pub const STATUS_LINK_TIMEOUT: ::NTSTATUS = 0xC000013Fu32 as i32; +pub const STATUS_INVALID_CONNECTION: ::NTSTATUS = 0xC0000140u32 as i32; +pub const STATUS_INVALID_ADDRESS: ::NTSTATUS = 0xC0000141u32 as i32; +pub const STATUS_DLL_INIT_FAILED: ::NTSTATUS = 0xC0000142u32 as i32; +pub const STATUS_MISSING_SYSTEMFILE: ::NTSTATUS = 0xC0000143u32 as i32; +pub const STATUS_UNHANDLED_EXCEPTION: ::NTSTATUS = 0xC0000144u32 as i32; +pub const STATUS_APP_INIT_FAILURE: ::NTSTATUS = 0xC0000145u32 as i32; +pub const STATUS_PAGEFILE_CREATE_FAILED: ::NTSTATUS = 0xC0000146u32 as i32; +pub const STATUS_NO_PAGEFILE: ::NTSTATUS = 0xC0000147u32 as i32; +pub const STATUS_INVALID_LEVEL: ::NTSTATUS = 0xC0000148u32 as i32; +pub const STATUS_WRONG_PASSWORD_CORE: ::NTSTATUS = 0xC0000149u32 as i32; +pub const STATUS_ILLEGAL_FLOAT_CONTEXT: ::NTSTATUS = 0xC000014Au32 as i32; +pub const STATUS_PIPE_BROKEN: ::NTSTATUS = 0xC000014Bu32 as i32; +pub const STATUS_REGISTRY_CORRUPT: ::NTSTATUS = 0xC000014Cu32 as i32; +pub const STATUS_REGISTRY_IO_FAILED: ::NTSTATUS = 0xC000014Du32 as i32; +pub const STATUS_NO_EVENT_PAIR: ::NTSTATUS = 0xC000014Eu32 as i32; +pub const STATUS_UNRECOGNIZED_VOLUME: ::NTSTATUS = 0xC000014Fu32 as i32; +pub const STATUS_SERIAL_NO_DEVICE_INITED: ::NTSTATUS = 0xC0000150u32 as i32; +pub const STATUS_NO_SUCH_ALIAS: ::NTSTATUS = 0xC0000151u32 as i32; +pub const STATUS_MEMBER_NOT_IN_ALIAS: ::NTSTATUS = 0xC0000152u32 as i32; +pub const STATUS_MEMBER_IN_ALIAS: ::NTSTATUS = 0xC0000153u32 as i32; +pub const STATUS_ALIAS_EXISTS: ::NTSTATUS = 0xC0000154u32 as i32; +pub const STATUS_LOGON_NOT_GRANTED: ::NTSTATUS = 0xC0000155u32 as i32; +pub const STATUS_TOO_MANY_SECRETS: ::NTSTATUS = 0xC0000156u32 as i32; +pub const STATUS_SECRET_TOO_LONG: ::NTSTATUS = 0xC0000157u32 as i32; +pub const STATUS_INTERNAL_DB_ERROR: ::NTSTATUS = 0xC0000158u32 as i32; +pub const STATUS_FULLSCREEN_MODE: ::NTSTATUS = 0xC0000159u32 as i32; +pub const STATUS_TOO_MANY_CONTEXT_IDS: ::NTSTATUS = 0xC000015Au32 as i32; +pub const STATUS_LOGON_TYPE_NOT_GRANTED: ::NTSTATUS = 0xC000015Bu32 as i32; +pub const STATUS_NOT_REGISTRY_FILE: ::NTSTATUS = 0xC000015Cu32 as i32; +pub const STATUS_NT_CROSS_ENCRYPTION_REQUIRED: ::NTSTATUS = 0xC000015Du32 as i32; +pub const STATUS_DOMAIN_CTRLR_CONFIG_ERROR: ::NTSTATUS = 0xC000015Eu32 as i32; +pub const STATUS_FT_MISSING_MEMBER: ::NTSTATUS = 0xC000015Fu32 as i32; +pub const STATUS_ILL_FORMED_SERVICE_ENTRY: ::NTSTATUS = 0xC0000160u32 as i32; +pub const STATUS_ILLEGAL_CHARACTER: ::NTSTATUS = 0xC0000161u32 as i32; +pub const STATUS_UNMAPPABLE_CHARACTER: ::NTSTATUS = 0xC0000162u32 as i32; +pub const STATUS_UNDEFINED_CHARACTER: ::NTSTATUS = 0xC0000163u32 as i32; +pub const STATUS_FLOPPY_VOLUME: ::NTSTATUS = 0xC0000164u32 as i32; +pub const STATUS_FLOPPY_ID_MARK_NOT_FOUND: ::NTSTATUS = 0xC0000165u32 as i32; +pub const STATUS_FLOPPY_WRONG_CYLINDER: ::NTSTATUS = 0xC0000166u32 as i32; +pub const STATUS_FLOPPY_UNKNOWN_ERROR: ::NTSTATUS = 0xC0000167u32 as i32; +pub const STATUS_FLOPPY_BAD_REGISTERS: ::NTSTATUS = 0xC0000168u32 as i32; +pub const STATUS_DISK_RECALIBRATE_FAILED: ::NTSTATUS = 0xC0000169u32 as i32; +pub const STATUS_DISK_OPERATION_FAILED: ::NTSTATUS = 0xC000016Au32 as i32; +pub const STATUS_DISK_RESET_FAILED: ::NTSTATUS = 0xC000016Bu32 as i32; +pub const STATUS_SHARED_IRQ_BUSY: ::NTSTATUS = 0xC000016Cu32 as i32; +pub const STATUS_FT_ORPHANING: ::NTSTATUS = 0xC000016Du32 as i32; +pub const STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT: ::NTSTATUS = 0xC000016Eu32 as i32; +pub const STATUS_PARTITION_FAILURE: ::NTSTATUS = 0xC0000172u32 as i32; +pub const STATUS_INVALID_BLOCK_LENGTH: ::NTSTATUS = 0xC0000173u32 as i32; +pub const STATUS_DEVICE_NOT_PARTITIONED: ::NTSTATUS = 0xC0000174u32 as i32; +pub const STATUS_UNABLE_TO_LOCK_MEDIA: ::NTSTATUS = 0xC0000175u32 as i32; +pub const STATUS_UNABLE_TO_UNLOAD_MEDIA: ::NTSTATUS = 0xC0000176u32 as i32; +pub const STATUS_EOM_OVERFLOW: ::NTSTATUS = 0xC0000177u32 as i32; +pub const STATUS_NO_MEDIA: ::NTSTATUS = 0xC0000178u32 as i32; +pub const STATUS_NO_SUCH_MEMBER: ::NTSTATUS = 0xC000017Au32 as i32; +pub const STATUS_INVALID_MEMBER: ::NTSTATUS = 0xC000017Bu32 as i32; +pub const STATUS_KEY_DELETED: ::NTSTATUS = 0xC000017Cu32 as i32; +pub const STATUS_NO_LOG_SPACE: ::NTSTATUS = 0xC000017Du32 as i32; +pub const STATUS_TOO_MANY_SIDS: ::NTSTATUS = 0xC000017Eu32 as i32; +pub const STATUS_LM_CROSS_ENCRYPTION_REQUIRED: ::NTSTATUS = 0xC000017Fu32 as i32; +pub const STATUS_KEY_HAS_CHILDREN: ::NTSTATUS = 0xC0000180u32 as i32; +pub const STATUS_CHILD_MUST_BE_VOLATILE: ::NTSTATUS = 0xC0000181u32 as i32; +pub const STATUS_DEVICE_CONFIGURATION_ERROR: ::NTSTATUS = 0xC0000182u32 as i32; +pub const STATUS_DRIVER_INTERNAL_ERROR: ::NTSTATUS = 0xC0000183u32 as i32; +pub const STATUS_INVALID_DEVICE_STATE: ::NTSTATUS = 0xC0000184u32 as i32; +pub const STATUS_IO_DEVICE_ERROR: ::NTSTATUS = 0xC0000185u32 as i32; +pub const STATUS_DEVICE_PROTOCOL_ERROR: ::NTSTATUS = 0xC0000186u32 as i32; +pub const STATUS_BACKUP_CONTROLLER: ::NTSTATUS = 0xC0000187u32 as i32; +pub const STATUS_LOG_FILE_FULL: ::NTSTATUS = 0xC0000188u32 as i32; +pub const STATUS_TOO_LATE: ::NTSTATUS = 0xC0000189u32 as i32; +pub const STATUS_NO_TRUST_LSA_SECRET: ::NTSTATUS = 0xC000018Au32 as i32; +pub const STATUS_NO_TRUST_SAM_ACCOUNT: ::NTSTATUS = 0xC000018Bu32 as i32; +pub const STATUS_TRUSTED_DOMAIN_FAILURE: ::NTSTATUS = 0xC000018Cu32 as i32; +pub const STATUS_TRUSTED_RELATIONSHIP_FAILURE: ::NTSTATUS = 0xC000018Du32 as i32; +pub const STATUS_EVENTLOG_FILE_CORRUPT: ::NTSTATUS = 0xC000018Eu32 as i32; +pub const STATUS_EVENTLOG_CANT_START: ::NTSTATUS = 0xC000018Fu32 as i32; +pub const STATUS_TRUST_FAILURE: ::NTSTATUS = 0xC0000190u32 as i32; +pub const STATUS_MUTANT_LIMIT_EXCEEDED: ::NTSTATUS = 0xC0000191u32 as i32; +pub const STATUS_NETLOGON_NOT_STARTED: ::NTSTATUS = 0xC0000192u32 as i32; +pub const STATUS_ACCOUNT_EXPIRED: ::NTSTATUS = 0xC0000193u32 as i32; +pub const STATUS_POSSIBLE_DEADLOCK: ::NTSTATUS = 0xC0000194u32 as i32; +pub const STATUS_NETWORK_CREDENTIAL_CONFLICT: ::NTSTATUS = 0xC0000195u32 as i32; +pub const STATUS_REMOTE_SESSION_LIMIT: ::NTSTATUS = 0xC0000196u32 as i32; +pub const STATUS_EVENTLOG_FILE_CHANGED: ::NTSTATUS = 0xC0000197u32 as i32; +pub const STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: ::NTSTATUS = 0xC0000198u32 as i32; +pub const STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT: ::NTSTATUS = 0xC0000199u32 as i32; +pub const STATUS_NOLOGON_SERVER_TRUST_ACCOUNT: ::NTSTATUS = 0xC000019Au32 as i32; +pub const STATUS_DOMAIN_TRUST_INCONSISTENT: ::NTSTATUS = 0xC000019Bu32 as i32; +pub const STATUS_FS_DRIVER_REQUIRED: ::NTSTATUS = 0xC000019Cu32 as i32; +pub const STATUS_IMAGE_ALREADY_LOADED_AS_DLL: ::NTSTATUS = 0xC000019Du32 as i32; +pub const STATUS_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: ::NTSTATUS = 0xC000019Eu32 as i32; +pub const STATUS_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: ::NTSTATUS = 0xC000019Fu32 as i32; +pub const STATUS_SECURITY_STREAM_IS_INCONSISTENT: ::NTSTATUS = 0xC00001A0u32 as i32; +pub const STATUS_INVALID_LOCK_RANGE: ::NTSTATUS = 0xC00001A1u32 as i32; +pub const STATUS_INVALID_ACE_CONDITION: ::NTSTATUS = 0xC00001A2u32 as i32; +pub const STATUS_IMAGE_SUBSYSTEM_NOT_PRESENT: ::NTSTATUS = 0xC00001A3u32 as i32; +pub const STATUS_NOTIFICATION_GUID_ALREADY_DEFINED: ::NTSTATUS = 0xC00001A4u32 as i32; +pub const STATUS_INVALID_EXCEPTION_HANDLER: ::NTSTATUS = 0xC00001A5u32 as i32; +pub const STATUS_DUPLICATE_PRIVILEGES: ::NTSTATUS = 0xC00001A6u32 as i32; +pub const STATUS_NOT_ALLOWED_ON_SYSTEM_FILE: ::NTSTATUS = 0xC00001A7u32 as i32; +pub const STATUS_REPAIR_NEEDED: ::NTSTATUS = 0xC00001A8u32 as i32; +pub const STATUS_QUOTA_NOT_ENABLED: ::NTSTATUS = 0xC00001A9u32 as i32; +pub const STATUS_NO_APPLICATION_PACKAGE: ::NTSTATUS = 0xC00001AAu32 as i32; +pub const STATUS_FILE_METADATA_OPTIMIZATION_IN_PROGRESS: ::NTSTATUS = 0xC00001ABu32 as i32; +pub const STATUS_NOT_SAME_OBJECT: ::NTSTATUS = 0xC00001ACu32 as i32; +pub const STATUS_FATAL_MEMORY_EXHAUSTION: ::NTSTATUS = 0xC00001ADu32 as i32; +pub const STATUS_ERROR_PROCESS_NOT_IN_JOB: ::NTSTATUS = 0xC00001AEu32 as i32; +pub const STATUS_NETWORK_OPEN_RESTRICTION: ::NTSTATUS = 0xC0000201u32 as i32; +pub const STATUS_NO_USER_SESSION_KEY: ::NTSTATUS = 0xC0000202u32 as i32; +pub const STATUS_USER_SESSION_DELETED: ::NTSTATUS = 0xC0000203u32 as i32; +pub const STATUS_RESOURCE_LANG_NOT_FOUND: ::NTSTATUS = 0xC0000204u32 as i32; +pub const STATUS_INSUFF_SERVER_RESOURCES: ::NTSTATUS = 0xC0000205u32 as i32; +pub const STATUS_INVALID_BUFFER_SIZE: ::NTSTATUS = 0xC0000206u32 as i32; +pub const STATUS_INVALID_ADDRESS_COMPONENT: ::NTSTATUS = 0xC0000207u32 as i32; +pub const STATUS_INVALID_ADDRESS_WILDCARD: ::NTSTATUS = 0xC0000208u32 as i32; +pub const STATUS_TOO_MANY_ADDRESSES: ::NTSTATUS = 0xC0000209u32 as i32; +pub const STATUS_ADDRESS_ALREADY_EXISTS: ::NTSTATUS = 0xC000020Au32 as i32; +pub const STATUS_ADDRESS_CLOSED: ::NTSTATUS = 0xC000020Bu32 as i32; +pub const STATUS_CONNECTION_DISCONNECTED: ::NTSTATUS = 0xC000020Cu32 as i32; +pub const STATUS_CONNECTION_RESET: ::NTSTATUS = 0xC000020Du32 as i32; +pub const STATUS_TOO_MANY_NODES: ::NTSTATUS = 0xC000020Eu32 as i32; +pub const STATUS_TRANSACTION_ABORTED: ::NTSTATUS = 0xC000020Fu32 as i32; +pub const STATUS_TRANSACTION_TIMED_OUT: ::NTSTATUS = 0xC0000210u32 as i32; +pub const STATUS_TRANSACTION_NO_RELEASE: ::NTSTATUS = 0xC0000211u32 as i32; +pub const STATUS_TRANSACTION_NO_MATCH: ::NTSTATUS = 0xC0000212u32 as i32; +pub const STATUS_TRANSACTION_RESPONDED: ::NTSTATUS = 0xC0000213u32 as i32; +pub const STATUS_TRANSACTION_INVALID_ID: ::NTSTATUS = 0xC0000214u32 as i32; +pub const STATUS_TRANSACTION_INVALID_TYPE: ::NTSTATUS = 0xC0000215u32 as i32; +pub const STATUS_NOT_SERVER_SESSION: ::NTSTATUS = 0xC0000216u32 as i32; +pub const STATUS_NOT_CLIENT_SESSION: ::NTSTATUS = 0xC0000217u32 as i32; +pub const STATUS_CANNOT_LOAD_REGISTRY_FILE: ::NTSTATUS = 0xC0000218u32 as i32; +pub const STATUS_DEBUG_ATTACH_FAILED: ::NTSTATUS = 0xC0000219u32 as i32; +pub const STATUS_SYSTEM_PROCESS_TERMINATED: ::NTSTATUS = 0xC000021Au32 as i32; +pub const STATUS_DATA_NOT_ACCEPTED: ::NTSTATUS = 0xC000021Bu32 as i32; +pub const STATUS_NO_BROWSER_SERVERS_FOUND: ::NTSTATUS = 0xC000021Cu32 as i32; +pub const STATUS_VDM_HARD_ERROR: ::NTSTATUS = 0xC000021Du32 as i32; +pub const STATUS_DRIVER_CANCEL_TIMEOUT: ::NTSTATUS = 0xC000021Eu32 as i32; +pub const STATUS_REPLY_MESSAGE_MISMATCH: ::NTSTATUS = 0xC000021Fu32 as i32; +pub const STATUS_MAPPED_ALIGNMENT: ::NTSTATUS = 0xC0000220u32 as i32; +pub const STATUS_IMAGE_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC0000221u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA: ::NTSTATUS = 0xC0000222u32 as i32; +pub const STATUS_CLIENT_SERVER_PARAMETERS_INVALID: ::NTSTATUS = 0xC0000223u32 as i32; +pub const STATUS_PASSWORD_MUST_CHANGE: ::NTSTATUS = 0xC0000224u32 as i32; +pub const STATUS_NOT_FOUND: ::NTSTATUS = 0xC0000225u32 as i32; +pub const STATUS_NOT_TINY_STREAM: ::NTSTATUS = 0xC0000226u32 as i32; +pub const STATUS_RECOVERY_FAILURE: ::NTSTATUS = 0xC0000227u32 as i32; +pub const STATUS_STACK_OVERFLOW_READ: ::NTSTATUS = 0xC0000228u32 as i32; +pub const STATUS_FAIL_CHECK: ::NTSTATUS = 0xC0000229u32 as i32; +pub const STATUS_DUPLICATE_OBJECTID: ::NTSTATUS = 0xC000022Au32 as i32; +pub const STATUS_OBJECTID_EXISTS: ::NTSTATUS = 0xC000022Bu32 as i32; +pub const STATUS_CONVERT_TO_LARGE: ::NTSTATUS = 0xC000022Cu32 as i32; +pub const STATUS_RETRY: ::NTSTATUS = 0xC000022Du32 as i32; +pub const STATUS_FOUND_OUT_OF_SCOPE: ::NTSTATUS = 0xC000022Eu32 as i32; +pub const STATUS_ALLOCATE_BUCKET: ::NTSTATUS = 0xC000022Fu32 as i32; +pub const STATUS_PROPSET_NOT_FOUND: ::NTSTATUS = 0xC0000230u32 as i32; +pub const STATUS_MARSHALL_OVERFLOW: ::NTSTATUS = 0xC0000231u32 as i32; +pub const STATUS_INVALID_VARIANT: ::NTSTATUS = 0xC0000232u32 as i32; +pub const STATUS_DOMAIN_CONTROLLER_NOT_FOUND: ::NTSTATUS = 0xC0000233u32 as i32; +pub const STATUS_ACCOUNT_LOCKED_OUT: ::NTSTATUS = 0xC0000234u32 as i32; +pub const STATUS_HANDLE_NOT_CLOSABLE: ::NTSTATUS = 0xC0000235u32 as i32; +pub const STATUS_CONNECTION_REFUSED: ::NTSTATUS = 0xC0000236u32 as i32; +pub const STATUS_GRACEFUL_DISCONNECT: ::NTSTATUS = 0xC0000237u32 as i32; +pub const STATUS_ADDRESS_ALREADY_ASSOCIATED: ::NTSTATUS = 0xC0000238u32 as i32; +pub const STATUS_ADDRESS_NOT_ASSOCIATED: ::NTSTATUS = 0xC0000239u32 as i32; +pub const STATUS_CONNECTION_INVALID: ::NTSTATUS = 0xC000023Au32 as i32; +pub const STATUS_CONNECTION_ACTIVE: ::NTSTATUS = 0xC000023Bu32 as i32; +pub const STATUS_NETWORK_UNREACHABLE: ::NTSTATUS = 0xC000023Cu32 as i32; +pub const STATUS_HOST_UNREACHABLE: ::NTSTATUS = 0xC000023Du32 as i32; +pub const STATUS_PROTOCOL_UNREACHABLE: ::NTSTATUS = 0xC000023Eu32 as i32; +pub const STATUS_PORT_UNREACHABLE: ::NTSTATUS = 0xC000023Fu32 as i32; +pub const STATUS_REQUEST_ABORTED: ::NTSTATUS = 0xC0000240u32 as i32; +pub const STATUS_CONNECTION_ABORTED: ::NTSTATUS = 0xC0000241u32 as i32; +pub const STATUS_BAD_COMPRESSION_BUFFER: ::NTSTATUS = 0xC0000242u32 as i32; +pub const STATUS_USER_MAPPED_FILE: ::NTSTATUS = 0xC0000243u32 as i32; +pub const STATUS_AUDIT_FAILED: ::NTSTATUS = 0xC0000244u32 as i32; +pub const STATUS_TIMER_RESOLUTION_NOT_SET: ::NTSTATUS = 0xC0000245u32 as i32; +pub const STATUS_CONNECTION_COUNT_LIMIT: ::NTSTATUS = 0xC0000246u32 as i32; +pub const STATUS_LOGIN_TIME_RESTRICTION: ::NTSTATUS = 0xC0000247u32 as i32; +pub const STATUS_LOGIN_WKSTA_RESTRICTION: ::NTSTATUS = 0xC0000248u32 as i32; +pub const STATUS_IMAGE_MP_UP_MISMATCH: ::NTSTATUS = 0xC0000249u32 as i32; +pub const STATUS_INSUFFICIENT_LOGON_INFO: ::NTSTATUS = 0xC0000250u32 as i32; +pub const STATUS_BAD_DLL_ENTRYPOINT: ::NTSTATUS = 0xC0000251u32 as i32; +pub const STATUS_BAD_SERVICE_ENTRYPOINT: ::NTSTATUS = 0xC0000252u32 as i32; +pub const STATUS_LPC_REPLY_LOST: ::NTSTATUS = 0xC0000253u32 as i32; +pub const STATUS_IP_ADDRESS_CONFLICT1: ::NTSTATUS = 0xC0000254u32 as i32; +pub const STATUS_IP_ADDRESS_CONFLICT2: ::NTSTATUS = 0xC0000255u32 as i32; +pub const STATUS_REGISTRY_QUOTA_LIMIT: ::NTSTATUS = 0xC0000256u32 as i32; +pub const STATUS_PATH_NOT_COVERED: ::NTSTATUS = 0xC0000257u32 as i32; +pub const STATUS_NO_CALLBACK_ACTIVE: ::NTSTATUS = 0xC0000258u32 as i32; +pub const STATUS_LICENSE_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000259u32 as i32; +pub const STATUS_PWD_TOO_SHORT: ::NTSTATUS = 0xC000025Au32 as i32; +pub const STATUS_PWD_TOO_RECENT: ::NTSTATUS = 0xC000025Bu32 as i32; +pub const STATUS_PWD_HISTORY_CONFLICT: ::NTSTATUS = 0xC000025Cu32 as i32; +pub const STATUS_PLUGPLAY_NO_DEVICE: ::NTSTATUS = 0xC000025Eu32 as i32; +pub const STATUS_UNSUPPORTED_COMPRESSION: ::NTSTATUS = 0xC000025Fu32 as i32; +pub const STATUS_INVALID_HW_PROFILE: ::NTSTATUS = 0xC0000260u32 as i32; +pub const STATUS_INVALID_PLUGPLAY_DEVICE_PATH: ::NTSTATUS = 0xC0000261u32 as i32; +pub const STATUS_DRIVER_ORDINAL_NOT_FOUND: ::NTSTATUS = 0xC0000262u32 as i32; +pub const STATUS_DRIVER_ENTRYPOINT_NOT_FOUND: ::NTSTATUS = 0xC0000263u32 as i32; +pub const STATUS_RESOURCE_NOT_OWNED: ::NTSTATUS = 0xC0000264u32 as i32; +pub const STATUS_TOO_MANY_LINKS: ::NTSTATUS = 0xC0000265u32 as i32; +pub const STATUS_QUOTA_LIST_INCONSISTENT: ::NTSTATUS = 0xC0000266u32 as i32; +pub const STATUS_FILE_IS_OFFLINE: ::NTSTATUS = 0xC0000267u32 as i32; +pub const STATUS_EVALUATION_EXPIRATION: ::NTSTATUS = 0xC0000268u32 as i32; +pub const STATUS_ILLEGAL_DLL_RELOCATION: ::NTSTATUS = 0xC0000269u32 as i32; +pub const STATUS_LICENSE_VIOLATION: ::NTSTATUS = 0xC000026Au32 as i32; +pub const STATUS_DLL_INIT_FAILED_LOGOFF: ::NTSTATUS = 0xC000026Bu32 as i32; +pub const STATUS_DRIVER_UNABLE_TO_LOAD: ::NTSTATUS = 0xC000026Cu32 as i32; +pub const STATUS_DFS_UNAVAILABLE: ::NTSTATUS = 0xC000026Du32 as i32; +pub const STATUS_VOLUME_DISMOUNTED: ::NTSTATUS = 0xC000026Eu32 as i32; +pub const STATUS_WX86_INTERNAL_ERROR: ::NTSTATUS = 0xC000026Fu32 as i32; +pub const STATUS_WX86_FLOAT_STACK_CHECK: ::NTSTATUS = 0xC0000270u32 as i32; +pub const STATUS_VALIDATE_CONTINUE: ::NTSTATUS = 0xC0000271u32 as i32; +pub const STATUS_NO_MATCH: ::NTSTATUS = 0xC0000272u32 as i32; +pub const STATUS_NO_MORE_MATCHES: ::NTSTATUS = 0xC0000273u32 as i32; +pub const STATUS_NOT_A_REPARSE_POINT: ::NTSTATUS = 0xC0000275u32 as i32; +pub const STATUS_IO_REPARSE_TAG_INVALID: ::NTSTATUS = 0xC0000276u32 as i32; +pub const STATUS_IO_REPARSE_TAG_MISMATCH: ::NTSTATUS = 0xC0000277u32 as i32; +pub const STATUS_IO_REPARSE_DATA_INVALID: ::NTSTATUS = 0xC0000278u32 as i32; +pub const STATUS_IO_REPARSE_TAG_NOT_HANDLED: ::NTSTATUS = 0xC0000279u32 as i32; +pub const STATUS_PWD_TOO_LONG: ::NTSTATUS = 0xC000027Au32 as i32; +pub const STATUS_STOWED_EXCEPTION: ::NTSTATUS = 0xC000027Bu32 as i32; +pub const STATUS_REPARSE_POINT_NOT_RESOLVED: ::NTSTATUS = 0xC0000280u32 as i32; +pub const STATUS_DIRECTORY_IS_A_REPARSE_POINT: ::NTSTATUS = 0xC0000281u32 as i32; +pub const STATUS_RANGE_LIST_CONFLICT: ::NTSTATUS = 0xC0000282u32 as i32; +pub const STATUS_SOURCE_ELEMENT_EMPTY: ::NTSTATUS = 0xC0000283u32 as i32; +pub const STATUS_DESTINATION_ELEMENT_FULL: ::NTSTATUS = 0xC0000284u32 as i32; +pub const STATUS_ILLEGAL_ELEMENT_ADDRESS: ::NTSTATUS = 0xC0000285u32 as i32; +pub const STATUS_MAGAZINE_NOT_PRESENT: ::NTSTATUS = 0xC0000286u32 as i32; +pub const STATUS_REINITIALIZATION_NEEDED: ::NTSTATUS = 0xC0000287u32 as i32; +pub const STATUS_DEVICE_REQUIRES_CLEANING: ::NTSTATUS = 0x80000288u32 as i32; +pub const STATUS_DEVICE_DOOR_OPEN: ::NTSTATUS = 0x80000289u32 as i32; +pub const STATUS_ENCRYPTION_FAILED: ::NTSTATUS = 0xC000028Au32 as i32; +pub const STATUS_DECRYPTION_FAILED: ::NTSTATUS = 0xC000028Bu32 as i32; +pub const STATUS_RANGE_NOT_FOUND: ::NTSTATUS = 0xC000028Cu32 as i32; +pub const STATUS_NO_RECOVERY_POLICY: ::NTSTATUS = 0xC000028Du32 as i32; +pub const STATUS_NO_EFS: ::NTSTATUS = 0xC000028Eu32 as i32; +pub const STATUS_WRONG_EFS: ::NTSTATUS = 0xC000028Fu32 as i32; +pub const STATUS_NO_USER_KEYS: ::NTSTATUS = 0xC0000290u32 as i32; +pub const STATUS_FILE_NOT_ENCRYPTED: ::NTSTATUS = 0xC0000291u32 as i32; +pub const STATUS_NOT_EXPORT_FORMAT: ::NTSTATUS = 0xC0000292u32 as i32; +pub const STATUS_FILE_ENCRYPTED: ::NTSTATUS = 0xC0000293u32 as i32; +pub const STATUS_WAKE_SYSTEM: ::NTSTATUS = 0x40000294; +pub const STATUS_WMI_GUID_NOT_FOUND: ::NTSTATUS = 0xC0000295u32 as i32; +pub const STATUS_WMI_INSTANCE_NOT_FOUND: ::NTSTATUS = 0xC0000296u32 as i32; +pub const STATUS_WMI_ITEMID_NOT_FOUND: ::NTSTATUS = 0xC0000297u32 as i32; +pub const STATUS_WMI_TRY_AGAIN: ::NTSTATUS = 0xC0000298u32 as i32; +pub const STATUS_SHARED_POLICY: ::NTSTATUS = 0xC0000299u32 as i32; +pub const STATUS_POLICY_OBJECT_NOT_FOUND: ::NTSTATUS = 0xC000029Au32 as i32; +pub const STATUS_POLICY_ONLY_IN_DS: ::NTSTATUS = 0xC000029Bu32 as i32; +pub const STATUS_VOLUME_NOT_UPGRADED: ::NTSTATUS = 0xC000029Cu32 as i32; +pub const STATUS_REMOTE_STORAGE_NOT_ACTIVE: ::NTSTATUS = 0xC000029Du32 as i32; +pub const STATUS_REMOTE_STORAGE_MEDIA_ERROR: ::NTSTATUS = 0xC000029Eu32 as i32; +pub const STATUS_NO_TRACKING_SERVICE: ::NTSTATUS = 0xC000029Fu32 as i32; +pub const STATUS_SERVER_SID_MISMATCH: ::NTSTATUS = 0xC00002A0u32 as i32; +pub const STATUS_DS_NO_ATTRIBUTE_OR_VALUE: ::NTSTATUS = 0xC00002A1u32 as i32; +pub const STATUS_DS_INVALID_ATTRIBUTE_SYNTAX: ::NTSTATUS = 0xC00002A2u32 as i32; +pub const STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED: ::NTSTATUS = 0xC00002A3u32 as i32; +pub const STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS: ::NTSTATUS = 0xC00002A4u32 as i32; +pub const STATUS_DS_BUSY: ::NTSTATUS = 0xC00002A5u32 as i32; +pub const STATUS_DS_UNAVAILABLE: ::NTSTATUS = 0xC00002A6u32 as i32; +pub const STATUS_DS_NO_RIDS_ALLOCATED: ::NTSTATUS = 0xC00002A7u32 as i32; +pub const STATUS_DS_NO_MORE_RIDS: ::NTSTATUS = 0xC00002A8u32 as i32; +pub const STATUS_DS_INCORRECT_ROLE_OWNER: ::NTSTATUS = 0xC00002A9u32 as i32; +pub const STATUS_DS_RIDMGR_INIT_ERROR: ::NTSTATUS = 0xC00002AAu32 as i32; +pub const STATUS_DS_OBJ_CLASS_VIOLATION: ::NTSTATUS = 0xC00002ABu32 as i32; +pub const STATUS_DS_CANT_ON_NON_LEAF: ::NTSTATUS = 0xC00002ACu32 as i32; +pub const STATUS_DS_CANT_ON_RDN: ::NTSTATUS = 0xC00002ADu32 as i32; +pub const STATUS_DS_CANT_MOD_OBJ_CLASS: ::NTSTATUS = 0xC00002AEu32 as i32; +pub const STATUS_DS_CROSS_DOM_MOVE_FAILED: ::NTSTATUS = 0xC00002AFu32 as i32; +pub const STATUS_DS_GC_NOT_AVAILABLE: ::NTSTATUS = 0xC00002B0u32 as i32; +pub const STATUS_DIRECTORY_SERVICE_REQUIRED: ::NTSTATUS = 0xC00002B1u32 as i32; +pub const STATUS_REPARSE_ATTRIBUTE_CONFLICT: ::NTSTATUS = 0xC00002B2u32 as i32; +pub const STATUS_CANT_ENABLE_DENY_ONLY: ::NTSTATUS = 0xC00002B3u32 as i32; +pub const STATUS_FLOAT_MULTIPLE_FAULTS: ::NTSTATUS = 0xC00002B4u32 as i32; +pub const STATUS_FLOAT_MULTIPLE_TRAPS: ::NTSTATUS = 0xC00002B5u32 as i32; +pub const STATUS_DEVICE_REMOVED: ::NTSTATUS = 0xC00002B6u32 as i32; +pub const STATUS_JOURNAL_DELETE_IN_PROGRESS: ::NTSTATUS = 0xC00002B7u32 as i32; +pub const STATUS_JOURNAL_NOT_ACTIVE: ::NTSTATUS = 0xC00002B8u32 as i32; +pub const STATUS_NOINTERFACE: ::NTSTATUS = 0xC00002B9u32 as i32; +pub const STATUS_DS_RIDMGR_DISABLED: ::NTSTATUS = 0xC00002BAu32 as i32; +pub const STATUS_DS_ADMIN_LIMIT_EXCEEDED: ::NTSTATUS = 0xC00002C1u32 as i32; +pub const STATUS_DRIVER_FAILED_SLEEP: ::NTSTATUS = 0xC00002C2u32 as i32; +pub const STATUS_MUTUAL_AUTHENTICATION_FAILED: ::NTSTATUS = 0xC00002C3u32 as i32; +pub const STATUS_CORRUPT_SYSTEM_FILE: ::NTSTATUS = 0xC00002C4u32 as i32; +pub const STATUS_DATATYPE_MISALIGNMENT_ERROR: ::NTSTATUS = 0xC00002C5u32 as i32; +pub const STATUS_WMI_READ_ONLY: ::NTSTATUS = 0xC00002C6u32 as i32; +pub const STATUS_WMI_SET_FAILURE: ::NTSTATUS = 0xC00002C7u32 as i32; +pub const STATUS_COMMITMENT_MINIMUM: ::NTSTATUS = 0xC00002C8u32 as i32; +pub const STATUS_REG_NAT_CONSUMPTION: ::NTSTATUS = 0xC00002C9u32 as i32; +pub const STATUS_TRANSPORT_FULL: ::NTSTATUS = 0xC00002CAu32 as i32; +pub const STATUS_DS_SAM_INIT_FAILURE: ::NTSTATUS = 0xC00002CBu32 as i32; +pub const STATUS_ONLY_IF_CONNECTED: ::NTSTATUS = 0xC00002CCu32 as i32; +pub const STATUS_DS_SENSITIVE_GROUP_VIOLATION: ::NTSTATUS = 0xC00002CDu32 as i32; +pub const STATUS_PNP_RESTART_ENUMERATION: ::NTSTATUS = 0xC00002CEu32 as i32; +pub const STATUS_JOURNAL_ENTRY_DELETED: ::NTSTATUS = 0xC00002CFu32 as i32; +pub const STATUS_DS_CANT_MOD_PRIMARYGROUPID: ::NTSTATUS = 0xC00002D0u32 as i32; +pub const STATUS_SYSTEM_IMAGE_BAD_SIGNATURE: ::NTSTATUS = 0xC00002D1u32 as i32; +pub const STATUS_PNP_REBOOT_REQUIRED: ::NTSTATUS = 0xC00002D2u32 as i32; +pub const STATUS_POWER_STATE_INVALID: ::NTSTATUS = 0xC00002D3u32 as i32; +pub const STATUS_DS_INVALID_GROUP_TYPE: ::NTSTATUS = 0xC00002D4u32 as i32; +pub const STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: ::NTSTATUS = 0xC00002D5u32 as i32; +pub const STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: ::NTSTATUS = 0xC00002D6u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: ::NTSTATUS = 0xC00002D7u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: ::NTSTATUS = 0xC00002D8u32 as i32; +pub const STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: ::NTSTATUS = 0xC00002D9u32 as i32; +pub const STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: ::NTSTATUS = 0xC00002DAu32 as i32; +pub const STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: ::NTSTATUS = 0xC00002DBu32 as i32; +pub const STATUS_DS_HAVE_PRIMARY_MEMBERS: ::NTSTATUS = 0xC00002DCu32 as i32; +pub const STATUS_WMI_NOT_SUPPORTED: ::NTSTATUS = 0xC00002DDu32 as i32; +pub const STATUS_INSUFFICIENT_POWER: ::NTSTATUS = 0xC00002DEu32 as i32; +pub const STATUS_SAM_NEED_BOOTKEY_PASSWORD: ::NTSTATUS = 0xC00002DFu32 as i32; +pub const STATUS_SAM_NEED_BOOTKEY_FLOPPY: ::NTSTATUS = 0xC00002E0u32 as i32; +pub const STATUS_DS_CANT_START: ::NTSTATUS = 0xC00002E1u32 as i32; +pub const STATUS_DS_INIT_FAILURE: ::NTSTATUS = 0xC00002E2u32 as i32; +pub const STATUS_SAM_INIT_FAILURE: ::NTSTATUS = 0xC00002E3u32 as i32; +pub const STATUS_DS_GC_REQUIRED: ::NTSTATUS = 0xC00002E4u32 as i32; +pub const STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: ::NTSTATUS = 0xC00002E5u32 as i32; +pub const STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS: ::NTSTATUS = 0xC00002E6u32 as i32; +pub const STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: ::NTSTATUS = 0xC00002E7u32 as i32; +pub const STATUS_MULTIPLE_FAULT_VIOLATION: ::NTSTATUS = 0xC00002E8u32 as i32; +pub const STATUS_CURRENT_DOMAIN_NOT_ALLOWED: ::NTSTATUS = 0xC00002E9u32 as i32; +pub const STATUS_CANNOT_MAKE: ::NTSTATUS = 0xC00002EAu32 as i32; +pub const STATUS_SYSTEM_SHUTDOWN: ::NTSTATUS = 0xC00002EBu32 as i32; +pub const STATUS_DS_INIT_FAILURE_CONSOLE: ::NTSTATUS = 0xC00002ECu32 as i32; +pub const STATUS_DS_SAM_INIT_FAILURE_CONSOLE: ::NTSTATUS = 0xC00002EDu32 as i32; +pub const STATUS_UNFINISHED_CONTEXT_DELETED: ::NTSTATUS = 0xC00002EEu32 as i32; +pub const STATUS_NO_TGT_REPLY: ::NTSTATUS = 0xC00002EFu32 as i32; +pub const STATUS_OBJECTID_NOT_FOUND: ::NTSTATUS = 0xC00002F0u32 as i32; +pub const STATUS_NO_IP_ADDRESSES: ::NTSTATUS = 0xC00002F1u32 as i32; +pub const STATUS_WRONG_CREDENTIAL_HANDLE: ::NTSTATUS = 0xC00002F2u32 as i32; +pub const STATUS_CRYPTO_SYSTEM_INVALID: ::NTSTATUS = 0xC00002F3u32 as i32; +pub const STATUS_MAX_REFERRALS_EXCEEDED: ::NTSTATUS = 0xC00002F4u32 as i32; +pub const STATUS_MUST_BE_KDC: ::NTSTATUS = 0xC00002F5u32 as i32; +pub const STATUS_STRONG_CRYPTO_NOT_SUPPORTED: ::NTSTATUS = 0xC00002F6u32 as i32; +pub const STATUS_TOO_MANY_PRINCIPALS: ::NTSTATUS = 0xC00002F7u32 as i32; +pub const STATUS_NO_PA_DATA: ::NTSTATUS = 0xC00002F8u32 as i32; +pub const STATUS_PKINIT_NAME_MISMATCH: ::NTSTATUS = 0xC00002F9u32 as i32; +pub const STATUS_SMARTCARD_LOGON_REQUIRED: ::NTSTATUS = 0xC00002FAu32 as i32; +pub const STATUS_KDC_INVALID_REQUEST: ::NTSTATUS = 0xC00002FBu32 as i32; +pub const STATUS_KDC_UNABLE_TO_REFER: ::NTSTATUS = 0xC00002FCu32 as i32; +pub const STATUS_KDC_UNKNOWN_ETYPE: ::NTSTATUS = 0xC00002FDu32 as i32; +pub const STATUS_SHUTDOWN_IN_PROGRESS: ::NTSTATUS = 0xC00002FEu32 as i32; +pub const STATUS_SERVER_SHUTDOWN_IN_PROGRESS: ::NTSTATUS = 0xC00002FFu32 as i32; +pub const STATUS_NOT_SUPPORTED_ON_SBS: ::NTSTATUS = 0xC0000300u32 as i32; +pub const STATUS_WMI_GUID_DISCONNECTED: ::NTSTATUS = 0xC0000301u32 as i32; +pub const STATUS_WMI_ALREADY_DISABLED: ::NTSTATUS = 0xC0000302u32 as i32; +pub const STATUS_WMI_ALREADY_ENABLED: ::NTSTATUS = 0xC0000303u32 as i32; +pub const STATUS_MFT_TOO_FRAGMENTED: ::NTSTATUS = 0xC0000304u32 as i32; +pub const STATUS_COPY_PROTECTION_FAILURE: ::NTSTATUS = 0xC0000305u32 as i32; +pub const STATUS_CSS_AUTHENTICATION_FAILURE: ::NTSTATUS = 0xC0000306u32 as i32; +pub const STATUS_CSS_KEY_NOT_PRESENT: ::NTSTATUS = 0xC0000307u32 as i32; +pub const STATUS_CSS_KEY_NOT_ESTABLISHED: ::NTSTATUS = 0xC0000308u32 as i32; +pub const STATUS_CSS_SCRAMBLED_SECTOR: ::NTSTATUS = 0xC0000309u32 as i32; +pub const STATUS_CSS_REGION_MISMATCH: ::NTSTATUS = 0xC000030Au32 as i32; +pub const STATUS_CSS_RESETS_EXHAUSTED: ::NTSTATUS = 0xC000030Bu32 as i32; +pub const STATUS_PASSWORD_CHANGE_REQUIRED: ::NTSTATUS = 0xC000030Cu32 as i32; +pub const STATUS_PKINIT_FAILURE: ::NTSTATUS = 0xC0000320u32 as i32; +pub const STATUS_SMARTCARD_SUBSYSTEM_FAILURE: ::NTSTATUS = 0xC0000321u32 as i32; +pub const STATUS_NO_KERB_KEY: ::NTSTATUS = 0xC0000322u32 as i32; +pub const STATUS_HOST_DOWN: ::NTSTATUS = 0xC0000350u32 as i32; +pub const STATUS_UNSUPPORTED_PREAUTH: ::NTSTATUS = 0xC0000351u32 as i32; +pub const STATUS_EFS_ALG_BLOB_TOO_BIG: ::NTSTATUS = 0xC0000352u32 as i32; +pub const STATUS_PORT_NOT_SET: ::NTSTATUS = 0xC0000353u32 as i32; +pub const STATUS_DEBUGGER_INACTIVE: ::NTSTATUS = 0xC0000354u32 as i32; +pub const STATUS_DS_VERSION_CHECK_FAILURE: ::NTSTATUS = 0xC0000355u32 as i32; +pub const STATUS_AUDITING_DISABLED: ::NTSTATUS = 0xC0000356u32 as i32; +pub const STATUS_PRENT4_MACHINE_ACCOUNT: ::NTSTATUS = 0xC0000357u32 as i32; +pub const STATUS_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: ::NTSTATUS = 0xC0000358u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_32: ::NTSTATUS = 0xC0000359u32 as i32; +pub const STATUS_INVALID_IMAGE_WIN_64: ::NTSTATUS = 0xC000035Au32 as i32; +pub const STATUS_BAD_BINDINGS: ::NTSTATUS = 0xC000035Bu32 as i32; +pub const STATUS_NETWORK_SESSION_EXPIRED: ::NTSTATUS = 0xC000035Cu32 as i32; +pub const STATUS_APPHELP_BLOCK: ::NTSTATUS = 0xC000035Du32 as i32; +pub const STATUS_ALL_SIDS_FILTERED: ::NTSTATUS = 0xC000035Eu32 as i32; +pub const STATUS_NOT_SAFE_MODE_DRIVER: ::NTSTATUS = 0xC000035Fu32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_DEFAULT: ::NTSTATUS = 0xC0000361u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_PATH: ::NTSTATUS = 0xC0000362u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_PUBLISHER: ::NTSTATUS = 0xC0000363u32 as i32; +pub const STATUS_ACCESS_DISABLED_BY_POLICY_OTHER: ::NTSTATUS = 0xC0000364u32 as i32; +pub const STATUS_FAILED_DRIVER_ENTRY: ::NTSTATUS = 0xC0000365u32 as i32; +pub const STATUS_DEVICE_ENUMERATION_ERROR: ::NTSTATUS = 0xC0000366u32 as i32; +pub const STATUS_MOUNT_POINT_NOT_RESOLVED: ::NTSTATUS = 0xC0000368u32 as i32; +pub const STATUS_INVALID_DEVICE_OBJECT_PARAMETER: ::NTSTATUS = 0xC0000369u32 as i32; +pub const STATUS_MCA_OCCURED: ::NTSTATUS = 0xC000036Au32 as i32; +pub const STATUS_DRIVER_BLOCKED_CRITICAL: ::NTSTATUS = 0xC000036Bu32 as i32; +pub const STATUS_DRIVER_BLOCKED: ::NTSTATUS = 0xC000036Cu32 as i32; +pub const STATUS_DRIVER_DATABASE_ERROR: ::NTSTATUS = 0xC000036Du32 as i32; +pub const STATUS_SYSTEM_HIVE_TOO_LARGE: ::NTSTATUS = 0xC000036Eu32 as i32; +pub const STATUS_INVALID_IMPORT_OF_NON_DLL: ::NTSTATUS = 0xC000036Fu32 as i32; +pub const STATUS_DS_SHUTTING_DOWN: ::NTSTATUS = 0x40000370; +pub const STATUS_NO_SECRETS: ::NTSTATUS = 0xC0000371u32 as i32; +pub const STATUS_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: ::NTSTATUS = 0xC0000372u32 as i32; +pub const STATUS_FAILED_STACK_SWITCH: ::NTSTATUS = 0xC0000373u32 as i32; +pub const STATUS_HEAP_CORRUPTION: ::NTSTATUS = 0xC0000374u32 as i32; +pub const STATUS_SMARTCARD_WRONG_PIN: ::NTSTATUS = 0xC0000380u32 as i32; +pub const STATUS_SMARTCARD_CARD_BLOCKED: ::NTSTATUS = 0xC0000381u32 as i32; +pub const STATUS_SMARTCARD_CARD_NOT_AUTHENTICATED: ::NTSTATUS = 0xC0000382u32 as i32; +pub const STATUS_SMARTCARD_NO_CARD: ::NTSTATUS = 0xC0000383u32 as i32; +pub const STATUS_SMARTCARD_NO_KEY_CONTAINER: ::NTSTATUS = 0xC0000384u32 as i32; +pub const STATUS_SMARTCARD_NO_CERTIFICATE: ::NTSTATUS = 0xC0000385u32 as i32; +pub const STATUS_SMARTCARD_NO_KEYSET: ::NTSTATUS = 0xC0000386u32 as i32; +pub const STATUS_SMARTCARD_IO_ERROR: ::NTSTATUS = 0xC0000387u32 as i32; +pub const STATUS_DOWNGRADE_DETECTED: ::NTSTATUS = 0xC0000388u32 as i32; +pub const STATUS_SMARTCARD_CERT_REVOKED: ::NTSTATUS = 0xC0000389u32 as i32; +pub const STATUS_ISSUING_CA_UNTRUSTED: ::NTSTATUS = 0xC000038Au32 as i32; +pub const STATUS_REVOCATION_OFFLINE_C: ::NTSTATUS = 0xC000038Bu32 as i32; +pub const STATUS_PKINIT_CLIENT_FAILURE: ::NTSTATUS = 0xC000038Cu32 as i32; +pub const STATUS_SMARTCARD_CERT_EXPIRED: ::NTSTATUS = 0xC000038Du32 as i32; +pub const STATUS_DRIVER_FAILED_PRIOR_UNLOAD: ::NTSTATUS = 0xC000038Eu32 as i32; +pub const STATUS_SMARTCARD_SILENT_CONTEXT: ::NTSTATUS = 0xC000038Fu32 as i32; +pub const STATUS_PER_USER_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000401u32 as i32; +pub const STATUS_ALL_USER_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000402u32 as i32; +pub const STATUS_USER_DELETE_TRUST_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000403u32 as i32; +pub const STATUS_DS_NAME_NOT_UNIQUE: ::NTSTATUS = 0xC0000404u32 as i32; +pub const STATUS_DS_DUPLICATE_ID_FOUND: ::NTSTATUS = 0xC0000405u32 as i32; +pub const STATUS_DS_GROUP_CONVERSION_ERROR: ::NTSTATUS = 0xC0000406u32 as i32; +pub const STATUS_VOLSNAP_PREPARE_HIBERNATE: ::NTSTATUS = 0xC0000407u32 as i32; +pub const STATUS_USER2USER_REQUIRED: ::NTSTATUS = 0xC0000408u32 as i32; +pub const STATUS_STACK_BUFFER_OVERRUN: ::NTSTATUS = 0xC0000409u32 as i32; +pub const STATUS_NO_S4U_PROT_SUPPORT: ::NTSTATUS = 0xC000040Au32 as i32; +pub const STATUS_CROSSREALM_DELEGATION_FAILURE: ::NTSTATUS = 0xC000040Bu32 as i32; +pub const STATUS_REVOCATION_OFFLINE_KDC: ::NTSTATUS = 0xC000040Cu32 as i32; +pub const STATUS_ISSUING_CA_UNTRUSTED_KDC: ::NTSTATUS = 0xC000040Du32 as i32; +pub const STATUS_KDC_CERT_EXPIRED: ::NTSTATUS = 0xC000040Eu32 as i32; +pub const STATUS_KDC_CERT_REVOKED: ::NTSTATUS = 0xC000040Fu32 as i32; +pub const STATUS_PARAMETER_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000410u32 as i32; +pub const STATUS_HIBERNATION_FAILURE: ::NTSTATUS = 0xC0000411u32 as i32; +pub const STATUS_DELAY_LOAD_FAILED: ::NTSTATUS = 0xC0000412u32 as i32; +pub const STATUS_AUTHENTICATION_FIREWALL_FAILED: ::NTSTATUS = 0xC0000413u32 as i32; +pub const STATUS_VDM_DISALLOWED: ::NTSTATUS = 0xC0000414u32 as i32; +pub const STATUS_HUNG_DISPLAY_DRIVER_THREAD: ::NTSTATUS = 0xC0000415u32 as i32; +pub const STATUS_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: ::NTSTATUS = 0xC0000416u32 as i32; +pub const STATUS_INVALID_CRUNTIME_PARAMETER: ::NTSTATUS = 0xC0000417u32 as i32; +pub const STATUS_NTLM_BLOCKED: ::NTSTATUS = 0xC0000418u32 as i32; +pub const STATUS_DS_SRC_SID_EXISTS_IN_FOREST: ::NTSTATUS = 0xC0000419u32 as i32; +pub const STATUS_DS_DOMAIN_NAME_EXISTS_IN_FOREST: ::NTSTATUS = 0xC000041Au32 as i32; +pub const STATUS_DS_FLAT_NAME_EXISTS_IN_FOREST: ::NTSTATUS = 0xC000041Bu32 as i32; +pub const STATUS_INVALID_USER_PRINCIPAL_NAME: ::NTSTATUS = 0xC000041Cu32 as i32; +pub const STATUS_FATAL_USER_CALLBACK_EXCEPTION: ::NTSTATUS = 0xC000041Du32 as i32; +pub const STATUS_ASSERTION_FAILURE: ::NTSTATUS = 0xC0000420u32 as i32; +pub const STATUS_VERIFIER_STOP: ::NTSTATUS = 0xC0000421u32 as i32; +pub const STATUS_CALLBACK_POP_STACK: ::NTSTATUS = 0xC0000423u32 as i32; +pub const STATUS_INCOMPATIBLE_DRIVER_BLOCKED: ::NTSTATUS = 0xC0000424u32 as i32; +pub const STATUS_HIVE_UNLOADED: ::NTSTATUS = 0xC0000425u32 as i32; +pub const STATUS_COMPRESSION_DISABLED: ::NTSTATUS = 0xC0000426u32 as i32; +pub const STATUS_FILE_SYSTEM_LIMITATION: ::NTSTATUS = 0xC0000427u32 as i32; +pub const STATUS_INVALID_IMAGE_HASH: ::NTSTATUS = 0xC0000428u32 as i32; +pub const STATUS_NOT_CAPABLE: ::NTSTATUS = 0xC0000429u32 as i32; +pub const STATUS_REQUEST_OUT_OF_SEQUENCE: ::NTSTATUS = 0xC000042Au32 as i32; +pub const STATUS_IMPLEMENTATION_LIMIT: ::NTSTATUS = 0xC000042Bu32 as i32; +pub const STATUS_ELEVATION_REQUIRED: ::NTSTATUS = 0xC000042Cu32 as i32; +pub const STATUS_NO_SECURITY_CONTEXT: ::NTSTATUS = 0xC000042Du32 as i32; +pub const STATUS_PKU2U_CERT_FAILURE: ::NTSTATUS = 0xC000042Fu32 as i32; +pub const STATUS_BEYOND_VDL: ::NTSTATUS = 0xC0000432u32 as i32; +pub const STATUS_ENCOUNTERED_WRITE_IN_PROGRESS: ::NTSTATUS = 0xC0000433u32 as i32; +pub const STATUS_PTE_CHANGED: ::NTSTATUS = 0xC0000434u32 as i32; +pub const STATUS_PURGE_FAILED: ::NTSTATUS = 0xC0000435u32 as i32; +pub const STATUS_CRED_REQUIRES_CONFIRMATION: ::NTSTATUS = 0xC0000440u32 as i32; +pub const STATUS_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: ::NTSTATUS = 0xC0000441u32 as i32; +pub const STATUS_CS_ENCRYPTION_UNSUPPORTED_SERVER: ::NTSTATUS = 0xC0000442u32 as i32; +pub const STATUS_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: ::NTSTATUS = 0xC0000443u32 as i32; +pub const STATUS_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: ::NTSTATUS = 0xC0000444u32 as i32; +pub const STATUS_CS_ENCRYPTION_FILE_NOT_CSE: ::NTSTATUS = 0xC0000445u32 as i32; +pub const STATUS_INVALID_LABEL: ::NTSTATUS = 0xC0000446u32 as i32; +pub const STATUS_DRIVER_PROCESS_TERMINATED: ::NTSTATUS = 0xC0000450u32 as i32; +pub const STATUS_AMBIGUOUS_SYSTEM_DEVICE: ::NTSTATUS = 0xC0000451u32 as i32; +pub const STATUS_SYSTEM_DEVICE_NOT_FOUND: ::NTSTATUS = 0xC0000452u32 as i32; +pub const STATUS_RESTART_BOOT_APPLICATION: ::NTSTATUS = 0xC0000453u32 as i32; +pub const STATUS_INSUFFICIENT_NVRAM_RESOURCES: ::NTSTATUS = 0xC0000454u32 as i32; +pub const STATUS_INVALID_SESSION: ::NTSTATUS = 0xC0000455u32 as i32; +pub const STATUS_THREAD_ALREADY_IN_SESSION: ::NTSTATUS = 0xC0000456u32 as i32; +pub const STATUS_THREAD_NOT_IN_SESSION: ::NTSTATUS = 0xC0000457u32 as i32; +pub const STATUS_INVALID_WEIGHT: ::NTSTATUS = 0xC0000458u32 as i32; +pub const STATUS_REQUEST_PAUSED: ::NTSTATUS = 0xC0000459u32 as i32; +pub const STATUS_NO_RANGES_PROCESSED: ::NTSTATUS = 0xC0000460u32 as i32; +pub const STATUS_DISK_RESOURCES_EXHAUSTED: ::NTSTATUS = 0xC0000461u32 as i32; +pub const STATUS_NEEDS_REMEDIATION: ::NTSTATUS = 0xC0000462u32 as i32; +pub const STATUS_DEVICE_FEATURE_NOT_SUPPORTED: ::NTSTATUS = 0xC0000463u32 as i32; +pub const STATUS_DEVICE_UNREACHABLE: ::NTSTATUS = 0xC0000464u32 as i32; +pub const STATUS_INVALID_TOKEN: ::NTSTATUS = 0xC0000465u32 as i32; +pub const STATUS_SERVER_UNAVAILABLE: ::NTSTATUS = 0xC0000466u32 as i32; +pub const STATUS_FILE_NOT_AVAILABLE: ::NTSTATUS = 0xC0000467u32 as i32; +pub const STATUS_DEVICE_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC0000468u32 as i32; +pub const STATUS_PACKAGE_UPDATING: ::NTSTATUS = 0xC0000469u32 as i32; +pub const STATUS_NOT_READ_FROM_COPY: ::NTSTATUS = 0xC000046Au32 as i32; +pub const STATUS_FT_WRITE_FAILURE: ::NTSTATUS = 0xC000046Bu32 as i32; +pub const STATUS_FT_DI_SCAN_REQUIRED: ::NTSTATUS = 0xC000046Cu32 as i32; +pub const STATUS_OBJECT_NOT_EXTERNALLY_BACKED: ::NTSTATUS = 0xC000046Du32 as i32; +pub const STATUS_EXTERNAL_BACKING_PROVIDER_UNKNOWN: ::NTSTATUS = 0xC000046Eu32 as i32; +pub const STATUS_COMPRESSION_NOT_BENEFICIAL: ::NTSTATUS = 0xC000046Fu32 as i32; +pub const STATUS_DATA_CHECKSUM_ERROR: ::NTSTATUS = 0xC0000470u32 as i32; +pub const STATUS_INTERMIXED_KERNEL_EA_OPERATION: ::NTSTATUS = 0xC0000471u32 as i32; +pub const STATUS_TRIM_READ_ZERO_NOT_SUPPORTED: ::NTSTATUS = 0xC0000472u32 as i32; +pub const STATUS_TOO_MANY_SEGMENT_DESCRIPTORS: ::NTSTATUS = 0xC0000473u32 as i32; +pub const STATUS_INVALID_OFFSET_ALIGNMENT: ::NTSTATUS = 0xC0000474u32 as i32; +pub const STATUS_INVALID_FIELD_IN_PARAMETER_LIST: ::NTSTATUS = 0xC0000475u32 as i32; +pub const STATUS_OPERATION_IN_PROGRESS: ::NTSTATUS = 0xC0000476u32 as i32; +pub const STATUS_INVALID_INITIATOR_TARGET_PATH: ::NTSTATUS = 0xC0000477u32 as i32; +pub const STATUS_SCRUB_DATA_DISABLED: ::NTSTATUS = 0xC0000478u32 as i32; +pub const STATUS_NOT_REDUNDANT_STORAGE: ::NTSTATUS = 0xC0000479u32 as i32; +pub const STATUS_RESIDENT_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Au32 as i32; +pub const STATUS_COMPRESSED_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Bu32 as i32; +pub const STATUS_DIRECTORY_NOT_SUPPORTED: ::NTSTATUS = 0xC000047Cu32 as i32; +pub const STATUS_IO_OPERATION_TIMEOUT: ::NTSTATUS = 0xC000047Du32 as i32; +pub const STATUS_SYSTEM_NEEDS_REMEDIATION: ::NTSTATUS = 0xC000047Eu32 as i32; +pub const STATUS_APPX_INTEGRITY_FAILURE_CLR_NGEN: ::NTSTATUS = 0xC000047Fu32 as i32; +pub const STATUS_SHARE_UNAVAILABLE: ::NTSTATUS = 0xC0000480u32 as i32; +pub const STATUS_APISET_NOT_HOSTED: ::NTSTATUS = 0xC0000481u32 as i32; +pub const STATUS_APISET_NOT_PRESENT: ::NTSTATUS = 0xC0000482u32 as i32; +pub const STATUS_DEVICE_HARDWARE_ERROR: ::NTSTATUS = 0xC0000483u32 as i32; +pub const STATUS_FIRMWARE_SLOT_INVALID: ::NTSTATUS = 0xC0000484u32 as i32; +pub const STATUS_FIRMWARE_IMAGE_INVALID: ::NTSTATUS = 0xC0000485u32 as i32; +pub const STATUS_STORAGE_TOPOLOGY_ID_MISMATCH: ::NTSTATUS = 0xC0000486u32 as i32; +pub const STATUS_WIM_NOT_BOOTABLE: ::NTSTATUS = 0xC0000487u32 as i32; +pub const STATUS_BLOCKED_BY_PARENTAL_CONTROLS: ::NTSTATUS = 0xC0000488u32 as i32; +pub const STATUS_NEEDS_REGISTRATION: ::NTSTATUS = 0xC0000489u32 as i32; +pub const STATUS_QUOTA_ACTIVITY: ::NTSTATUS = 0xC000048Au32 as i32; +pub const STATUS_INVALID_TASK_NAME: ::NTSTATUS = 0xC0000500u32 as i32; +pub const STATUS_INVALID_TASK_INDEX: ::NTSTATUS = 0xC0000501u32 as i32; +pub const STATUS_THREAD_ALREADY_IN_TASK: ::NTSTATUS = 0xC0000502u32 as i32; +pub const STATUS_CALLBACK_BYPASS: ::NTSTATUS = 0xC0000503u32 as i32; +pub const STATUS_UNDEFINED_SCOPE: ::NTSTATUS = 0xC0000504u32 as i32; +pub const STATUS_INVALID_CAP: ::NTSTATUS = 0xC0000505u32 as i32; +pub const STATUS_NOT_GUI_PROCESS: ::NTSTATUS = 0xC0000506u32 as i32; +pub const STATUS_DEVICE_HUNG: ::NTSTATUS = 0xC0000507u32 as i32; +pub const STATUS_FAIL_FAST_EXCEPTION: ::NTSTATUS = 0xC0000602u32 as i32; +pub const STATUS_IMAGE_CERT_REVOKED: ::NTSTATUS = 0xC0000603u32 as i32; +pub const STATUS_DYNAMIC_CODE_BLOCKED: ::NTSTATUS = 0xC0000604u32 as i32; +pub const STATUS_IMAGE_CERT_EXPIRED: ::NTSTATUS = 0xC0000605u32 as i32; +pub const STATUS_PORT_CLOSED: ::NTSTATUS = 0xC0000700u32 as i32; +pub const STATUS_MESSAGE_LOST: ::NTSTATUS = 0xC0000701u32 as i32; +pub const STATUS_INVALID_MESSAGE: ::NTSTATUS = 0xC0000702u32 as i32; +pub const STATUS_REQUEST_CANCELED: ::NTSTATUS = 0xC0000703u32 as i32; +pub const STATUS_RECURSIVE_DISPATCH: ::NTSTATUS = 0xC0000704u32 as i32; +pub const STATUS_LPC_RECEIVE_BUFFER_EXPECTED: ::NTSTATUS = 0xC0000705u32 as i32; +pub const STATUS_LPC_INVALID_CONNECTION_USAGE: ::NTSTATUS = 0xC0000706u32 as i32; +pub const STATUS_LPC_REQUESTS_NOT_ALLOWED: ::NTSTATUS = 0xC0000707u32 as i32; +pub const STATUS_RESOURCE_IN_USE: ::NTSTATUS = 0xC0000708u32 as i32; +pub const STATUS_HARDWARE_MEMORY_ERROR: ::NTSTATUS = 0xC0000709u32 as i32; +pub const STATUS_THREADPOOL_HANDLE_EXCEPTION: ::NTSTATUS = 0xC000070Au32 as i32; +pub const STATUS_THREADPOOL_SET_EVENT_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Bu32 as i32; +pub const STATUS_THREADPOOL_RELEASE_SEMAPHORE_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Cu32 as i32; +pub const STATUS_THREADPOOL_RELEASE_MUTEX_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Du32 as i32; +pub const STATUS_THREADPOOL_FREE_LIBRARY_ON_COMPLETION_FAILED: ::NTSTATUS = 0xC000070Eu32 as i32; +pub const STATUS_THREADPOOL_RELEASED_DURING_OPERATION: ::NTSTATUS = 0xC000070Fu32 as i32; +pub const STATUS_CALLBACK_RETURNED_WHILE_IMPERSONATING: ::NTSTATUS = 0xC0000710u32 as i32; +pub const STATUS_APC_RETURNED_WHILE_IMPERSONATING: ::NTSTATUS = 0xC0000711u32 as i32; +pub const STATUS_PROCESS_IS_PROTECTED: ::NTSTATUS = 0xC0000712u32 as i32; +pub const STATUS_MCA_EXCEPTION: ::NTSTATUS = 0xC0000713u32 as i32; +pub const STATUS_CERTIFICATE_MAPPING_NOT_UNIQUE: ::NTSTATUS = 0xC0000714u32 as i32; +pub const STATUS_SYMLINK_CLASS_DISABLED: ::NTSTATUS = 0xC0000715u32 as i32; +pub const STATUS_INVALID_IDN_NORMALIZATION: ::NTSTATUS = 0xC0000716u32 as i32; +pub const STATUS_NO_UNICODE_TRANSLATION: ::NTSTATUS = 0xC0000717u32 as i32; +pub const STATUS_ALREADY_REGISTERED: ::NTSTATUS = 0xC0000718u32 as i32; +pub const STATUS_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0000719u32 as i32; +pub const STATUS_PORT_ALREADY_HAS_COMPLETION_LIST: ::NTSTATUS = 0xC000071Au32 as i32; +pub const STATUS_CALLBACK_RETURNED_THREAD_PRIORITY: ::NTSTATUS = 0xC000071Bu32 as i32; +pub const STATUS_INVALID_THREAD: ::NTSTATUS = 0xC000071Cu32 as i32; +pub const STATUS_CALLBACK_RETURNED_TRANSACTION: ::NTSTATUS = 0xC000071Du32 as i32; +pub const STATUS_CALLBACK_RETURNED_LDR_LOCK: ::NTSTATUS = 0xC000071Eu32 as i32; +pub const STATUS_CALLBACK_RETURNED_LANG: ::NTSTATUS = 0xC000071Fu32 as i32; +pub const STATUS_CALLBACK_RETURNED_PRI_BACK: ::NTSTATUS = 0xC0000720u32 as i32; +pub const STATUS_CALLBACK_RETURNED_THREAD_AFFINITY: ::NTSTATUS = 0xC0000721u32 as i32; +pub const STATUS_DISK_REPAIR_DISABLED: ::NTSTATUS = 0xC0000800u32 as i32; +pub const STATUS_DS_DOMAIN_RENAME_IN_PROGRESS: ::NTSTATUS = 0xC0000801u32 as i32; +pub const STATUS_DISK_QUOTA_EXCEEDED: ::NTSTATUS = 0xC0000802u32 as i32; +pub const STATUS_DATA_LOST_REPAIR: ::NTSTATUS = 0x80000803u32 as i32; +pub const STATUS_CONTENT_BLOCKED: ::NTSTATUS = 0xC0000804u32 as i32; +pub const STATUS_BAD_CLUSTERS: ::NTSTATUS = 0xC0000805u32 as i32; +pub const STATUS_VOLUME_DIRTY: ::NTSTATUS = 0xC0000806u32 as i32; +pub const STATUS_DISK_REPAIR_REDIRECTED: ::NTSTATUS = 0x40000807; +pub const STATUS_DISK_REPAIR_UNSUCCESSFUL: ::NTSTATUS = 0xC0000808u32 as i32; +pub const STATUS_CORRUPT_LOG_OVERFULL: ::NTSTATUS = 0xC0000809u32 as i32; +pub const STATUS_CORRUPT_LOG_CORRUPTED: ::NTSTATUS = 0xC000080Au32 as i32; +pub const STATUS_CORRUPT_LOG_UNAVAILABLE: ::NTSTATUS = 0xC000080Bu32 as i32; +pub const STATUS_CORRUPT_LOG_DELETED_FULL: ::NTSTATUS = 0xC000080Cu32 as i32; +pub const STATUS_CORRUPT_LOG_CLEARED: ::NTSTATUS = 0xC000080Du32 as i32; +pub const STATUS_ORPHAN_NAME_EXHAUSTED: ::NTSTATUS = 0xC000080Eu32 as i32; +pub const STATUS_PROACTIVE_SCAN_IN_PROGRESS: ::NTSTATUS = 0xC000080Fu32 as i32; +pub const STATUS_ENCRYPTED_IO_NOT_POSSIBLE: ::NTSTATUS = 0xC0000810u32 as i32; +pub const STATUS_CORRUPT_LOG_UPLEVEL_RECORDS: ::NTSTATUS = 0xC0000811u32 as i32; +pub const STATUS_FILE_CHECKED_OUT: ::NTSTATUS = 0xC0000901u32 as i32; +pub const STATUS_CHECKOUT_REQUIRED: ::NTSTATUS = 0xC0000902u32 as i32; +pub const STATUS_BAD_FILE_TYPE: ::NTSTATUS = 0xC0000903u32 as i32; +pub const STATUS_FILE_TOO_LARGE: ::NTSTATUS = 0xC0000904u32 as i32; +pub const STATUS_FORMS_AUTH_REQUIRED: ::NTSTATUS = 0xC0000905u32 as i32; +pub const STATUS_VIRUS_INFECTED: ::NTSTATUS = 0xC0000906u32 as i32; +pub const STATUS_VIRUS_DELETED: ::NTSTATUS = 0xC0000907u32 as i32; +pub const STATUS_BAD_MCFG_TABLE: ::NTSTATUS = 0xC0000908u32 as i32; +pub const STATUS_CANNOT_BREAK_OPLOCK: ::NTSTATUS = 0xC0000909u32 as i32; +pub const STATUS_BAD_KEY: ::NTSTATUS = 0xC000090Au32 as i32; +pub const STATUS_BAD_DATA: ::NTSTATUS = 0xC000090Bu32 as i32; +pub const STATUS_NO_KEY: ::NTSTATUS = 0xC000090Cu32 as i32; +pub const STATUS_FILE_HANDLE_REVOKED: ::NTSTATUS = 0xC0000910u32 as i32; +pub const STATUS_WOW_ASSERTION: ::NTSTATUS = 0xC0009898u32 as i32; +pub const STATUS_INVALID_SIGNATURE: ::NTSTATUS = 0xC000A000u32 as i32; +pub const STATUS_HMAC_NOT_SUPPORTED: ::NTSTATUS = 0xC000A001u32 as i32; +pub const STATUS_AUTH_TAG_MISMATCH: ::NTSTATUS = 0xC000A002u32 as i32; +pub const STATUS_INVALID_STATE_TRANSITION: ::NTSTATUS = 0xC000A003u32 as i32; +pub const STATUS_INVALID_KERNEL_INFO_VERSION: ::NTSTATUS = 0xC000A004u32 as i32; +pub const STATUS_INVALID_PEP_INFO_VERSION: ::NTSTATUS = 0xC000A005u32 as i32; +pub const STATUS_HANDLE_REVOKED: ::NTSTATUS = 0xC000A006u32 as i32; +pub const STATUS_IPSEC_QUEUE_OVERFLOW: ::NTSTATUS = 0xC000A010u32 as i32; +pub const STATUS_ND_QUEUE_OVERFLOW: ::NTSTATUS = 0xC000A011u32 as i32; +pub const STATUS_HOPLIMIT_EXCEEDED: ::NTSTATUS = 0xC000A012u32 as i32; +pub const STATUS_PROTOCOL_NOT_SUPPORTED: ::NTSTATUS = 0xC000A013u32 as i32; +pub const STATUS_FASTPATH_REJECTED: ::NTSTATUS = 0xC000A014u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: ::NTSTATUS = 0xC000A080u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: ::NTSTATUS = 0xC000A081u32 as i32; +pub const STATUS_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: ::NTSTATUS = 0xC000A082u32 as i32; +pub const STATUS_XML_PARSE_ERROR: ::NTSTATUS = 0xC000A083u32 as i32; +pub const STATUS_XMLDSIG_ERROR: ::NTSTATUS = 0xC000A084u32 as i32; +pub const STATUS_WRONG_COMPARTMENT: ::NTSTATUS = 0xC000A085u32 as i32; +pub const STATUS_AUTHIP_FAILURE: ::NTSTATUS = 0xC000A086u32 as i32; +pub const STATUS_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: ::NTSTATUS = 0xC000A087u32 as i32; +pub const STATUS_DS_OID_NOT_FOUND: ::NTSTATUS = 0xC000A088u32 as i32; +pub const STATUS_INCORRECT_ACCOUNT_TYPE: ::NTSTATUS = 0xC000A089u32 as i32; +pub const STATUS_HASH_NOT_SUPPORTED: ::NTSTATUS = 0xC000A100u32 as i32; +pub const STATUS_HASH_NOT_PRESENT: ::NTSTATUS = 0xC000A101u32 as i32; +pub const STATUS_SECONDARY_IC_PROVIDER_NOT_REGISTERED: ::NTSTATUS = 0xC000A121u32 as i32; +pub const STATUS_GPIO_CLIENT_INFORMATION_INVALID: ::NTSTATUS = 0xC000A122u32 as i32; +pub const STATUS_GPIO_VERSION_NOT_SUPPORTED: ::NTSTATUS = 0xC000A123u32 as i32; +pub const STATUS_GPIO_INVALID_REGISTRATION_PACKET: ::NTSTATUS = 0xC000A124u32 as i32; +pub const STATUS_GPIO_OPERATION_DENIED: ::NTSTATUS = 0xC000A125u32 as i32; +pub const STATUS_GPIO_INCOMPATIBLE_CONNECT_MODE: ::NTSTATUS = 0xC000A126u32 as i32; +pub const STATUS_GPIO_INTERRUPT_ALREADY_UNMASKED: ::NTSTATUS = 0x8000A127u32 as i32; +pub const STATUS_CANNOT_SWITCH_RUNLEVEL: ::NTSTATUS = 0xC000A141u32 as i32; +pub const STATUS_INVALID_RUNLEVEL_SETTING: ::NTSTATUS = 0xC000A142u32 as i32; +pub const STATUS_RUNLEVEL_SWITCH_TIMEOUT: ::NTSTATUS = 0xC000A143u32 as i32; +pub const STATUS_SERVICES_FAILED_AUTOSTART: ::NTSTATUS = 0x4000A144; +pub const STATUS_RUNLEVEL_SWITCH_AGENT_TIMEOUT: ::NTSTATUS = 0xC000A145u32 as i32; +pub const STATUS_RUNLEVEL_SWITCH_IN_PROGRESS: ::NTSTATUS = 0xC000A146u32 as i32; +pub const STATUS_NOT_APPCONTAINER: ::NTSTATUS = 0xC000A200u32 as i32; +pub const STATUS_NOT_SUPPORTED_IN_APPCONTAINER: ::NTSTATUS = 0xC000A201u32 as i32; +pub const STATUS_INVALID_PACKAGE_SID_LENGTH: ::NTSTATUS = 0xC000A202u32 as i32; +pub const STATUS_APP_DATA_NOT_FOUND: ::NTSTATUS = 0xC000A281u32 as i32; +pub const STATUS_APP_DATA_EXPIRED: ::NTSTATUS = 0xC000A282u32 as i32; +pub const STATUS_APP_DATA_CORRUPT: ::NTSTATUS = 0xC000A283u32 as i32; +pub const STATUS_APP_DATA_LIMIT_EXCEEDED: ::NTSTATUS = 0xC000A284u32 as i32; +pub const STATUS_APP_DATA_REBOOT_REQUIRED: ::NTSTATUS = 0xC000A285u32 as i32; +pub const STATUS_OFFLOAD_READ_FLT_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A1u32 as i32; +pub const STATUS_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A2u32 as i32; +pub const STATUS_OFFLOAD_READ_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A3u32 as i32; +pub const STATUS_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: ::NTSTATUS = 0xC000A2A4u32 as i32; +pub const DBG_NO_STATE_CHANGE: ::NTSTATUS = 0xC0010001u32 as i32; +pub const DBG_APP_NOT_IDLE: ::NTSTATUS = 0xC0010002u32 as i32; +pub const RPC_NT_INVALID_STRING_BINDING: ::NTSTATUS = 0xC0020001u32 as i32; +pub const RPC_NT_WRONG_KIND_OF_BINDING: ::NTSTATUS = 0xC0020002u32 as i32; +pub const RPC_NT_INVALID_BINDING: ::NTSTATUS = 0xC0020003u32 as i32; +pub const RPC_NT_PROTSEQ_NOT_SUPPORTED: ::NTSTATUS = 0xC0020004u32 as i32; +pub const RPC_NT_INVALID_RPC_PROTSEQ: ::NTSTATUS = 0xC0020005u32 as i32; +pub const RPC_NT_INVALID_STRING_UUID: ::NTSTATUS = 0xC0020006u32 as i32; +pub const RPC_NT_INVALID_ENDPOINT_FORMAT: ::NTSTATUS = 0xC0020007u32 as i32; +pub const RPC_NT_INVALID_NET_ADDR: ::NTSTATUS = 0xC0020008u32 as i32; +pub const RPC_NT_NO_ENDPOINT_FOUND: ::NTSTATUS = 0xC0020009u32 as i32; +pub const RPC_NT_INVALID_TIMEOUT: ::NTSTATUS = 0xC002000Au32 as i32; +pub const RPC_NT_OBJECT_NOT_FOUND: ::NTSTATUS = 0xC002000Bu32 as i32; +pub const RPC_NT_ALREADY_REGISTERED: ::NTSTATUS = 0xC002000Cu32 as i32; +pub const RPC_NT_TYPE_ALREADY_REGISTERED: ::NTSTATUS = 0xC002000Du32 as i32; +pub const RPC_NT_ALREADY_LISTENING: ::NTSTATUS = 0xC002000Eu32 as i32; +pub const RPC_NT_NO_PROTSEQS_REGISTERED: ::NTSTATUS = 0xC002000Fu32 as i32; +pub const RPC_NT_NOT_LISTENING: ::NTSTATUS = 0xC0020010u32 as i32; +pub const RPC_NT_UNKNOWN_MGR_TYPE: ::NTSTATUS = 0xC0020011u32 as i32; +pub const RPC_NT_UNKNOWN_IF: ::NTSTATUS = 0xC0020012u32 as i32; +pub const RPC_NT_NO_BINDINGS: ::NTSTATUS = 0xC0020013u32 as i32; +pub const RPC_NT_NO_PROTSEQS: ::NTSTATUS = 0xC0020014u32 as i32; +pub const RPC_NT_CANT_CREATE_ENDPOINT: ::NTSTATUS = 0xC0020015u32 as i32; +pub const RPC_NT_OUT_OF_RESOURCES: ::NTSTATUS = 0xC0020016u32 as i32; +pub const RPC_NT_SERVER_UNAVAILABLE: ::NTSTATUS = 0xC0020017u32 as i32; +pub const RPC_NT_SERVER_TOO_BUSY: ::NTSTATUS = 0xC0020018u32 as i32; +pub const RPC_NT_INVALID_NETWORK_OPTIONS: ::NTSTATUS = 0xC0020019u32 as i32; +pub const RPC_NT_NO_CALL_ACTIVE: ::NTSTATUS = 0xC002001Au32 as i32; +pub const RPC_NT_CALL_FAILED: ::NTSTATUS = 0xC002001Bu32 as i32; +pub const RPC_NT_CALL_FAILED_DNE: ::NTSTATUS = 0xC002001Cu32 as i32; +pub const RPC_NT_PROTOCOL_ERROR: ::NTSTATUS = 0xC002001Du32 as i32; +pub const RPC_NT_UNSUPPORTED_TRANS_SYN: ::NTSTATUS = 0xC002001Fu32 as i32; +pub const RPC_NT_UNSUPPORTED_TYPE: ::NTSTATUS = 0xC0020021u32 as i32; +pub const RPC_NT_INVALID_TAG: ::NTSTATUS = 0xC0020022u32 as i32; +pub const RPC_NT_INVALID_BOUND: ::NTSTATUS = 0xC0020023u32 as i32; +pub const RPC_NT_NO_ENTRY_NAME: ::NTSTATUS = 0xC0020024u32 as i32; +pub const RPC_NT_INVALID_NAME_SYNTAX: ::NTSTATUS = 0xC0020025u32 as i32; +pub const RPC_NT_UNSUPPORTED_NAME_SYNTAX: ::NTSTATUS = 0xC0020026u32 as i32; +pub const RPC_NT_UUID_NO_ADDRESS: ::NTSTATUS = 0xC0020028u32 as i32; +pub const RPC_NT_DUPLICATE_ENDPOINT: ::NTSTATUS = 0xC0020029u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_TYPE: ::NTSTATUS = 0xC002002Au32 as i32; +pub const RPC_NT_MAX_CALLS_TOO_SMALL: ::NTSTATUS = 0xC002002Bu32 as i32; +pub const RPC_NT_STRING_TOO_LONG: ::NTSTATUS = 0xC002002Cu32 as i32; +pub const RPC_NT_PROTSEQ_NOT_FOUND: ::NTSTATUS = 0xC002002Du32 as i32; +pub const RPC_NT_PROCNUM_OUT_OF_RANGE: ::NTSTATUS = 0xC002002Eu32 as i32; +pub const RPC_NT_BINDING_HAS_NO_AUTH: ::NTSTATUS = 0xC002002Fu32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_SERVICE: ::NTSTATUS = 0xC0020030u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHN_LEVEL: ::NTSTATUS = 0xC0020031u32 as i32; +pub const RPC_NT_INVALID_AUTH_IDENTITY: ::NTSTATUS = 0xC0020032u32 as i32; +pub const RPC_NT_UNKNOWN_AUTHZ_SERVICE: ::NTSTATUS = 0xC0020033u32 as i32; +pub const EPT_NT_INVALID_ENTRY: ::NTSTATUS = 0xC0020034u32 as i32; +pub const EPT_NT_CANT_PERFORM_OP: ::NTSTATUS = 0xC0020035u32 as i32; +pub const EPT_NT_NOT_REGISTERED: ::NTSTATUS = 0xC0020036u32 as i32; +pub const RPC_NT_NOTHING_TO_EXPORT: ::NTSTATUS = 0xC0020037u32 as i32; +pub const RPC_NT_INCOMPLETE_NAME: ::NTSTATUS = 0xC0020038u32 as i32; +pub const RPC_NT_INVALID_VERS_OPTION: ::NTSTATUS = 0xC0020039u32 as i32; +pub const RPC_NT_NO_MORE_MEMBERS: ::NTSTATUS = 0xC002003Au32 as i32; +pub const RPC_NT_NOT_ALL_OBJS_UNEXPORTED: ::NTSTATUS = 0xC002003Bu32 as i32; +pub const RPC_NT_INTERFACE_NOT_FOUND: ::NTSTATUS = 0xC002003Cu32 as i32; +pub const RPC_NT_ENTRY_ALREADY_EXISTS: ::NTSTATUS = 0xC002003Du32 as i32; +pub const RPC_NT_ENTRY_NOT_FOUND: ::NTSTATUS = 0xC002003Eu32 as i32; +pub const RPC_NT_NAME_SERVICE_UNAVAILABLE: ::NTSTATUS = 0xC002003Fu32 as i32; +pub const RPC_NT_INVALID_NAF_ID: ::NTSTATUS = 0xC0020040u32 as i32; +pub const RPC_NT_CANNOT_SUPPORT: ::NTSTATUS = 0xC0020041u32 as i32; +pub const RPC_NT_NO_CONTEXT_AVAILABLE: ::NTSTATUS = 0xC0020042u32 as i32; +pub const RPC_NT_INTERNAL_ERROR: ::NTSTATUS = 0xC0020043u32 as i32; +pub const RPC_NT_ZERO_DIVIDE: ::NTSTATUS = 0xC0020044u32 as i32; +pub const RPC_NT_ADDRESS_ERROR: ::NTSTATUS = 0xC0020045u32 as i32; +pub const RPC_NT_FP_DIV_ZERO: ::NTSTATUS = 0xC0020046u32 as i32; +pub const RPC_NT_FP_UNDERFLOW: ::NTSTATUS = 0xC0020047u32 as i32; +pub const RPC_NT_FP_OVERFLOW: ::NTSTATUS = 0xC0020048u32 as i32; +pub const RPC_NT_NO_MORE_ENTRIES: ::NTSTATUS = 0xC0030001u32 as i32; +pub const RPC_NT_SS_CHAR_TRANS_OPEN_FAIL: ::NTSTATUS = 0xC0030002u32 as i32; +pub const RPC_NT_SS_CHAR_TRANS_SHORT_FILE: ::NTSTATUS = 0xC0030003u32 as i32; +pub const RPC_NT_SS_IN_NULL_CONTEXT: ::NTSTATUS = 0xC0030004u32 as i32; +pub const RPC_NT_SS_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0030005u32 as i32; +pub const RPC_NT_SS_CONTEXT_DAMAGED: ::NTSTATUS = 0xC0030006u32 as i32; +pub const RPC_NT_SS_HANDLES_MISMATCH: ::NTSTATUS = 0xC0030007u32 as i32; +pub const RPC_NT_SS_CANNOT_GET_CALL_HANDLE: ::NTSTATUS = 0xC0030008u32 as i32; +pub const RPC_NT_NULL_REF_POINTER: ::NTSTATUS = 0xC0030009u32 as i32; +pub const RPC_NT_ENUM_VALUE_OUT_OF_RANGE: ::NTSTATUS = 0xC003000Au32 as i32; +pub const RPC_NT_BYTE_COUNT_TOO_SMALL: ::NTSTATUS = 0xC003000Bu32 as i32; +pub const RPC_NT_BAD_STUB_DATA: ::NTSTATUS = 0xC003000Cu32 as i32; +pub const RPC_NT_CALL_IN_PROGRESS: ::NTSTATUS = 0xC0020049u32 as i32; +pub const RPC_NT_NO_MORE_BINDINGS: ::NTSTATUS = 0xC002004Au32 as i32; +pub const RPC_NT_GROUP_MEMBER_NOT_FOUND: ::NTSTATUS = 0xC002004Bu32 as i32; +pub const EPT_NT_CANT_CREATE: ::NTSTATUS = 0xC002004Cu32 as i32; +pub const RPC_NT_INVALID_OBJECT: ::NTSTATUS = 0xC002004Du32 as i32; +pub const RPC_NT_NO_INTERFACES: ::NTSTATUS = 0xC002004Fu32 as i32; +pub const RPC_NT_CALL_CANCELLED: ::NTSTATUS = 0xC0020050u32 as i32; +pub const RPC_NT_BINDING_INCOMPLETE: ::NTSTATUS = 0xC0020051u32 as i32; +pub const RPC_NT_COMM_FAILURE: ::NTSTATUS = 0xC0020052u32 as i32; +pub const RPC_NT_UNSUPPORTED_AUTHN_LEVEL: ::NTSTATUS = 0xC0020053u32 as i32; +pub const RPC_NT_NO_PRINC_NAME: ::NTSTATUS = 0xC0020054u32 as i32; +pub const RPC_NT_NOT_RPC_ERROR: ::NTSTATUS = 0xC0020055u32 as i32; +pub const RPC_NT_UUID_LOCAL_ONLY: ::NTSTATUS = 0x40020056; +pub const RPC_NT_SEC_PKG_ERROR: ::NTSTATUS = 0xC0020057u32 as i32; +pub const RPC_NT_NOT_CANCELLED: ::NTSTATUS = 0xC0020058u32 as i32; +pub const RPC_NT_INVALID_ES_ACTION: ::NTSTATUS = 0xC0030059u32 as i32; +pub const RPC_NT_WRONG_ES_VERSION: ::NTSTATUS = 0xC003005Au32 as i32; +pub const RPC_NT_WRONG_STUB_VERSION: ::NTSTATUS = 0xC003005Bu32 as i32; +pub const RPC_NT_INVALID_PIPE_OBJECT: ::NTSTATUS = 0xC003005Cu32 as i32; +pub const RPC_NT_INVALID_PIPE_OPERATION: ::NTSTATUS = 0xC003005Du32 as i32; +pub const RPC_NT_WRONG_PIPE_VERSION: ::NTSTATUS = 0xC003005Eu32 as i32; +pub const RPC_NT_PIPE_CLOSED: ::NTSTATUS = 0xC003005Fu32 as i32; +pub const RPC_NT_PIPE_DISCIPLINE_ERROR: ::NTSTATUS = 0xC0030060u32 as i32; +pub const RPC_NT_PIPE_EMPTY: ::NTSTATUS = 0xC0030061u32 as i32; +pub const RPC_NT_INVALID_ASYNC_HANDLE: ::NTSTATUS = 0xC0020062u32 as i32; +pub const RPC_NT_INVALID_ASYNC_CALL: ::NTSTATUS = 0xC0020063u32 as i32; +pub const RPC_NT_PROXY_ACCESS_DENIED: ::NTSTATUS = 0xC0020064u32 as i32; +pub const RPC_NT_COOKIE_AUTH_FAILED: ::NTSTATUS = 0xC0020065u32 as i32; +pub const RPC_NT_SEND_INCOMPLETE: ::NTSTATUS = 0x400200AF; +pub const STATUS_ACPI_INVALID_OPCODE: ::NTSTATUS = 0xC0140001u32 as i32; +pub const STATUS_ACPI_STACK_OVERFLOW: ::NTSTATUS = 0xC0140002u32 as i32; +pub const STATUS_ACPI_ASSERT_FAILED: ::NTSTATUS = 0xC0140003u32 as i32; +pub const STATUS_ACPI_INVALID_INDEX: ::NTSTATUS = 0xC0140004u32 as i32; +pub const STATUS_ACPI_INVALID_ARGUMENT: ::NTSTATUS = 0xC0140005u32 as i32; +pub const STATUS_ACPI_FATAL: ::NTSTATUS = 0xC0140006u32 as i32; +pub const STATUS_ACPI_INVALID_SUPERNAME: ::NTSTATUS = 0xC0140007u32 as i32; +pub const STATUS_ACPI_INVALID_ARGTYPE: ::NTSTATUS = 0xC0140008u32 as i32; +pub const STATUS_ACPI_INVALID_OBJTYPE: ::NTSTATUS = 0xC0140009u32 as i32; +pub const STATUS_ACPI_INVALID_TARGETTYPE: ::NTSTATUS = 0xC014000Au32 as i32; +pub const STATUS_ACPI_INCORRECT_ARGUMENT_COUNT: ::NTSTATUS = 0xC014000Bu32 as i32; +pub const STATUS_ACPI_ADDRESS_NOT_MAPPED: ::NTSTATUS = 0xC014000Cu32 as i32; +pub const STATUS_ACPI_INVALID_EVENTTYPE: ::NTSTATUS = 0xC014000Du32 as i32; +pub const STATUS_ACPI_HANDLER_COLLISION: ::NTSTATUS = 0xC014000Eu32 as i32; +pub const STATUS_ACPI_INVALID_DATA: ::NTSTATUS = 0xC014000Fu32 as i32; +pub const STATUS_ACPI_INVALID_REGION: ::NTSTATUS = 0xC0140010u32 as i32; +pub const STATUS_ACPI_INVALID_ACCESS_SIZE: ::NTSTATUS = 0xC0140011u32 as i32; +pub const STATUS_ACPI_ACQUIRE_GLOBAL_LOCK: ::NTSTATUS = 0xC0140012u32 as i32; +pub const STATUS_ACPI_ALREADY_INITIALIZED: ::NTSTATUS = 0xC0140013u32 as i32; +pub const STATUS_ACPI_NOT_INITIALIZED: ::NTSTATUS = 0xC0140014u32 as i32; +pub const STATUS_ACPI_INVALID_MUTEX_LEVEL: ::NTSTATUS = 0xC0140015u32 as i32; +pub const STATUS_ACPI_MUTEX_NOT_OWNED: ::NTSTATUS = 0xC0140016u32 as i32; +pub const STATUS_ACPI_MUTEX_NOT_OWNER: ::NTSTATUS = 0xC0140017u32 as i32; +pub const STATUS_ACPI_RS_ACCESS: ::NTSTATUS = 0xC0140018u32 as i32; +pub const STATUS_ACPI_INVALID_TABLE: ::NTSTATUS = 0xC0140019u32 as i32; +pub const STATUS_ACPI_REG_HANDLER_FAILED: ::NTSTATUS = 0xC0140020u32 as i32; +pub const STATUS_ACPI_POWER_REQUEST_FAILED: ::NTSTATUS = 0xC0140021u32 as i32; +pub const STATUS_CTX_WINSTATION_NAME_INVALID: ::NTSTATUS = 0xC00A0001u32 as i32; +pub const STATUS_CTX_INVALID_PD: ::NTSTATUS = 0xC00A0002u32 as i32; +pub const STATUS_CTX_PD_NOT_FOUND: ::NTSTATUS = 0xC00A0003u32 as i32; +pub const STATUS_CTX_CDM_CONNECT: ::NTSTATUS = 0x400A0004; +pub const STATUS_CTX_CDM_DISCONNECT: ::NTSTATUS = 0x400A0005; +pub const STATUS_CTX_CLOSE_PENDING: ::NTSTATUS = 0xC00A0006u32 as i32; +pub const STATUS_CTX_NO_OUTBUF: ::NTSTATUS = 0xC00A0007u32 as i32; +pub const STATUS_CTX_MODEM_INF_NOT_FOUND: ::NTSTATUS = 0xC00A0008u32 as i32; +pub const STATUS_CTX_INVALID_MODEMNAME: ::NTSTATUS = 0xC00A0009u32 as i32; +pub const STATUS_CTX_RESPONSE_ERROR: ::NTSTATUS = 0xC00A000Au32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_TIMEOUT: ::NTSTATUS = 0xC00A000Bu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_NO_CARRIER: ::NTSTATUS = 0xC00A000Cu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE: ::NTSTATUS = 0xC00A000Du32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_BUSY: ::NTSTATUS = 0xC00A000Eu32 as i32; +pub const STATUS_CTX_MODEM_RESPONSE_VOICE: ::NTSTATUS = 0xC00A000Fu32 as i32; +pub const STATUS_CTX_TD_ERROR: ::NTSTATUS = 0xC00A0010u32 as i32; +pub const STATUS_CTX_LICENSE_CLIENT_INVALID: ::NTSTATUS = 0xC00A0012u32 as i32; +pub const STATUS_CTX_LICENSE_NOT_AVAILABLE: ::NTSTATUS = 0xC00A0013u32 as i32; +pub const STATUS_CTX_LICENSE_EXPIRED: ::NTSTATUS = 0xC00A0014u32 as i32; +pub const STATUS_CTX_WINSTATION_NOT_FOUND: ::NTSTATUS = 0xC00A0015u32 as i32; +pub const STATUS_CTX_WINSTATION_NAME_COLLISION: ::NTSTATUS = 0xC00A0016u32 as i32; +pub const STATUS_CTX_WINSTATION_BUSY: ::NTSTATUS = 0xC00A0017u32 as i32; +pub const STATUS_CTX_BAD_VIDEO_MODE: ::NTSTATUS = 0xC00A0018u32 as i32; +pub const STATUS_CTX_GRAPHICS_INVALID: ::NTSTATUS = 0xC00A0022u32 as i32; +pub const STATUS_CTX_NOT_CONSOLE: ::NTSTATUS = 0xC00A0024u32 as i32; +pub const STATUS_CTX_CLIENT_QUERY_TIMEOUT: ::NTSTATUS = 0xC00A0026u32 as i32; +pub const STATUS_CTX_CONSOLE_DISCONNECT: ::NTSTATUS = 0xC00A0027u32 as i32; +pub const STATUS_CTX_CONSOLE_CONNECT: ::NTSTATUS = 0xC00A0028u32 as i32; +pub const STATUS_CTX_SHADOW_DENIED: ::NTSTATUS = 0xC00A002Au32 as i32; +pub const STATUS_CTX_WINSTATION_ACCESS_DENIED: ::NTSTATUS = 0xC00A002Bu32 as i32; +pub const STATUS_CTX_INVALID_WD: ::NTSTATUS = 0xC00A002Eu32 as i32; +pub const STATUS_CTX_WD_NOT_FOUND: ::NTSTATUS = 0xC00A002Fu32 as i32; +pub const STATUS_CTX_SHADOW_INVALID: ::NTSTATUS = 0xC00A0030u32 as i32; +pub const STATUS_CTX_SHADOW_DISABLED: ::NTSTATUS = 0xC00A0031u32 as i32; +pub const STATUS_RDP_PROTOCOL_ERROR: ::NTSTATUS = 0xC00A0032u32 as i32; +pub const STATUS_CTX_CLIENT_LICENSE_NOT_SET: ::NTSTATUS = 0xC00A0033u32 as i32; +pub const STATUS_CTX_CLIENT_LICENSE_IN_USE: ::NTSTATUS = 0xC00A0034u32 as i32; +pub const STATUS_CTX_SHADOW_ENDED_BY_MODE_CHANGE: ::NTSTATUS = 0xC00A0035u32 as i32; +pub const STATUS_CTX_SHADOW_NOT_RUNNING: ::NTSTATUS = 0xC00A0036u32 as i32; +pub const STATUS_CTX_LOGON_DISABLED: ::NTSTATUS = 0xC00A0037u32 as i32; +pub const STATUS_CTX_SECURITY_LAYER_ERROR: ::NTSTATUS = 0xC00A0038u32 as i32; +pub const STATUS_TS_INCOMPATIBLE_SESSIONS: ::NTSTATUS = 0xC00A0039u32 as i32; +pub const STATUS_TS_VIDEO_SUBSYSTEM_ERROR: ::NTSTATUS = 0xC00A003Au32 as i32; +pub const STATUS_PNP_BAD_MPS_TABLE: ::NTSTATUS = 0xC0040035u32 as i32; +pub const STATUS_PNP_TRANSLATION_FAILED: ::NTSTATUS = 0xC0040036u32 as i32; +pub const STATUS_PNP_IRQ_TRANSLATION_FAILED: ::NTSTATUS = 0xC0040037u32 as i32; +pub const STATUS_PNP_INVALID_ID: ::NTSTATUS = 0xC0040038u32 as i32; +pub const STATUS_IO_REISSUE_AS_CACHED: ::NTSTATUS = 0xC0040039u32 as i32; +pub const STATUS_MUI_FILE_NOT_FOUND: ::NTSTATUS = 0xC00B0001u32 as i32; +pub const STATUS_MUI_INVALID_FILE: ::NTSTATUS = 0xC00B0002u32 as i32; +pub const STATUS_MUI_INVALID_RC_CONFIG: ::NTSTATUS = 0xC00B0003u32 as i32; +pub const STATUS_MUI_INVALID_LOCALE_NAME: ::NTSTATUS = 0xC00B0004u32 as i32; +pub const STATUS_MUI_INVALID_ULTIMATEFALLBACK_NAME: ::NTSTATUS = 0xC00B0005u32 as i32; +pub const STATUS_MUI_FILE_NOT_LOADED: ::NTSTATUS = 0xC00B0006u32 as i32; +pub const STATUS_RESOURCE_ENUM_USER_STOP: ::NTSTATUS = 0xC00B0007u32 as i32; +pub const STATUS_FLT_NO_HANDLER_DEFINED: ::NTSTATUS = 0xC01C0001u32 as i32; +pub const STATUS_FLT_CONTEXT_ALREADY_DEFINED: ::NTSTATUS = 0xC01C0002u32 as i32; +pub const STATUS_FLT_INVALID_ASYNCHRONOUS_REQUEST: ::NTSTATUS = 0xC01C0003u32 as i32; +pub const STATUS_FLT_DISALLOW_FAST_IO: ::NTSTATUS = 0xC01C0004u32 as i32; +pub const STATUS_FLT_INVALID_NAME_REQUEST: ::NTSTATUS = 0xC01C0005u32 as i32; +pub const STATUS_FLT_NOT_SAFE_TO_POST_OPERATION: ::NTSTATUS = 0xC01C0006u32 as i32; +pub const STATUS_FLT_NOT_INITIALIZED: ::NTSTATUS = 0xC01C0007u32 as i32; +pub const STATUS_FLT_FILTER_NOT_READY: ::NTSTATUS = 0xC01C0008u32 as i32; +pub const STATUS_FLT_POST_OPERATION_CLEANUP: ::NTSTATUS = 0xC01C0009u32 as i32; +pub const STATUS_FLT_INTERNAL_ERROR: ::NTSTATUS = 0xC01C000Au32 as i32; +pub const STATUS_FLT_DELETING_OBJECT: ::NTSTATUS = 0xC01C000Bu32 as i32; +pub const STATUS_FLT_MUST_BE_NONPAGED_POOL: ::NTSTATUS = 0xC01C000Cu32 as i32; +pub const STATUS_FLT_DUPLICATE_ENTRY: ::NTSTATUS = 0xC01C000Du32 as i32; +pub const STATUS_FLT_CBDQ_DISABLED: ::NTSTATUS = 0xC01C000Eu32 as i32; +pub const STATUS_FLT_DO_NOT_ATTACH: ::NTSTATUS = 0xC01C000Fu32 as i32; +pub const STATUS_FLT_DO_NOT_DETACH: ::NTSTATUS = 0xC01C0010u32 as i32; +pub const STATUS_FLT_INSTANCE_ALTITUDE_COLLISION: ::NTSTATUS = 0xC01C0011u32 as i32; +pub const STATUS_FLT_INSTANCE_NAME_COLLISION: ::NTSTATUS = 0xC01C0012u32 as i32; +pub const STATUS_FLT_FILTER_NOT_FOUND: ::NTSTATUS = 0xC01C0013u32 as i32; +pub const STATUS_FLT_VOLUME_NOT_FOUND: ::NTSTATUS = 0xC01C0014u32 as i32; +pub const STATUS_FLT_INSTANCE_NOT_FOUND: ::NTSTATUS = 0xC01C0015u32 as i32; +pub const STATUS_FLT_CONTEXT_ALLOCATION_NOT_FOUND: ::NTSTATUS = 0xC01C0016u32 as i32; +pub const STATUS_FLT_INVALID_CONTEXT_REGISTRATION: ::NTSTATUS = 0xC01C0017u32 as i32; +pub const STATUS_FLT_NAME_CACHE_MISS: ::NTSTATUS = 0xC01C0018u32 as i32; +pub const STATUS_FLT_NO_DEVICE_OBJECT: ::NTSTATUS = 0xC01C0019u32 as i32; +pub const STATUS_FLT_VOLUME_ALREADY_MOUNTED: ::NTSTATUS = 0xC01C001Au32 as i32; +pub const STATUS_FLT_ALREADY_ENLISTED: ::NTSTATUS = 0xC01C001Bu32 as i32; +pub const STATUS_FLT_CONTEXT_ALREADY_LINKED: ::NTSTATUS = 0xC01C001Cu32 as i32; +pub const STATUS_FLT_NO_WAITER_FOR_REPLY: ::NTSTATUS = 0xC01C0020u32 as i32; +pub const STATUS_FLT_REGISTRATION_BUSY: ::NTSTATUS = 0xC01C0023u32 as i32; +pub const STATUS_SXS_SECTION_NOT_FOUND: ::NTSTATUS = 0xC0150001u32 as i32; +pub const STATUS_SXS_CANT_GEN_ACTCTX: ::NTSTATUS = 0xC0150002u32 as i32; +pub const STATUS_SXS_INVALID_ACTCTXDATA_FORMAT: ::NTSTATUS = 0xC0150003u32 as i32; +pub const STATUS_SXS_ASSEMBLY_NOT_FOUND: ::NTSTATUS = 0xC0150004u32 as i32; +pub const STATUS_SXS_MANIFEST_FORMAT_ERROR: ::NTSTATUS = 0xC0150005u32 as i32; +pub const STATUS_SXS_MANIFEST_PARSE_ERROR: ::NTSTATUS = 0xC0150006u32 as i32; +pub const STATUS_SXS_ACTIVATION_CONTEXT_DISABLED: ::NTSTATUS = 0xC0150007u32 as i32; +pub const STATUS_SXS_KEY_NOT_FOUND: ::NTSTATUS = 0xC0150008u32 as i32; +pub const STATUS_SXS_VERSION_CONFLICT: ::NTSTATUS = 0xC0150009u32 as i32; +pub const STATUS_SXS_WRONG_SECTION_TYPE: ::NTSTATUS = 0xC015000Au32 as i32; +pub const STATUS_SXS_THREAD_QUERIES_DISABLED: ::NTSTATUS = 0xC015000Bu32 as i32; +pub const STATUS_SXS_ASSEMBLY_MISSING: ::NTSTATUS = 0xC015000Cu32 as i32; +pub const STATUS_SXS_RELEASE_ACTIVATION_CONTEXT: ::NTSTATUS = 0x4015000D; +pub const STATUS_SXS_PROCESS_DEFAULT_ALREADY_SET: ::NTSTATUS = 0xC015000Eu32 as i32; +pub const STATUS_SXS_EARLY_DEACTIVATION: ::NTSTATUS = 0xC015000Fu32 as i32; +pub const STATUS_SXS_INVALID_DEACTIVATION: ::NTSTATUS = 0xC0150010u32 as i32; +pub const STATUS_SXS_MULTIPLE_DEACTIVATION: ::NTSTATUS = 0xC0150011u32 as i32; +pub const STATUS_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: ::NTSTATUS = 0xC0150012u32 as i32; +pub const STATUS_SXS_PROCESS_TERMINATION_REQUESTED: ::NTSTATUS = 0xC0150013u32 as i32; +pub const STATUS_SXS_CORRUPT_ACTIVATION_STACK: ::NTSTATUS = 0xC0150014u32 as i32; +pub const STATUS_SXS_CORRUPTION: ::NTSTATUS = 0xC0150015u32 as i32; +pub const STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: ::NTSTATUS = 0xC0150016u32 as i32; +pub const STATUS_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: ::NTSTATUS = 0xC0150017u32 as i32; +pub const STATUS_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: ::NTSTATUS = 0xC0150018u32 as i32; +pub const STATUS_SXS_IDENTITY_PARSE_ERROR: ::NTSTATUS = 0xC0150019u32 as i32; +pub const STATUS_SXS_COMPONENT_STORE_CORRUPT: ::NTSTATUS = 0xC015001Au32 as i32; +pub const STATUS_SXS_FILE_HASH_MISMATCH: ::NTSTATUS = 0xC015001Bu32 as i32; +pub const STATUS_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: ::NTSTATUS = 0xC015001Cu32 as i32; +pub const STATUS_SXS_IDENTITIES_DIFFERENT: ::NTSTATUS = 0xC015001Du32 as i32; +pub const STATUS_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: ::NTSTATUS = 0xC015001Eu32 as i32; +pub const STATUS_SXS_FILE_NOT_PART_OF_ASSEMBLY: ::NTSTATUS = 0xC015001Fu32 as i32; +pub const STATUS_ADVANCED_INSTALLER_FAILED: ::NTSTATUS = 0xC0150020u32 as i32; +pub const STATUS_XML_ENCODING_MISMATCH: ::NTSTATUS = 0xC0150021u32 as i32; +pub const STATUS_SXS_MANIFEST_TOO_BIG: ::NTSTATUS = 0xC0150022u32 as i32; +pub const STATUS_SXS_SETTING_NOT_REGISTERED: ::NTSTATUS = 0xC0150023u32 as i32; +pub const STATUS_SXS_TRANSACTION_CLOSURE_INCOMPLETE: ::NTSTATUS = 0xC0150024u32 as i32; +pub const STATUS_SMI_PRIMITIVE_INSTALLER_FAILED: ::NTSTATUS = 0xC0150025u32 as i32; +pub const STATUS_GENERIC_COMMAND_FAILED: ::NTSTATUS = 0xC0150026u32 as i32; +pub const STATUS_SXS_FILE_HASH_MISSING: ::NTSTATUS = 0xC0150027u32 as i32; +pub const STATUS_CLUSTER_INVALID_NODE: ::NTSTATUS = 0xC0130001u32 as i32; +pub const STATUS_CLUSTER_NODE_EXISTS: ::NTSTATUS = 0xC0130002u32 as i32; +pub const STATUS_CLUSTER_JOIN_IN_PROGRESS: ::NTSTATUS = 0xC0130003u32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_FOUND: ::NTSTATUS = 0xC0130004u32 as i32; +pub const STATUS_CLUSTER_LOCAL_NODE_NOT_FOUND: ::NTSTATUS = 0xC0130005u32 as i32; +pub const STATUS_CLUSTER_NETWORK_EXISTS: ::NTSTATUS = 0xC0130006u32 as i32; +pub const STATUS_CLUSTER_NETWORK_NOT_FOUND: ::NTSTATUS = 0xC0130007u32 as i32; +pub const STATUS_CLUSTER_NETINTERFACE_EXISTS: ::NTSTATUS = 0xC0130008u32 as i32; +pub const STATUS_CLUSTER_NETINTERFACE_NOT_FOUND: ::NTSTATUS = 0xC0130009u32 as i32; +pub const STATUS_CLUSTER_INVALID_REQUEST: ::NTSTATUS = 0xC013000Au32 as i32; +pub const STATUS_CLUSTER_INVALID_NETWORK_PROVIDER: ::NTSTATUS = 0xC013000Bu32 as i32; +pub const STATUS_CLUSTER_NODE_DOWN: ::NTSTATUS = 0xC013000Cu32 as i32; +pub const STATUS_CLUSTER_NODE_UNREACHABLE: ::NTSTATUS = 0xC013000Du32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_MEMBER: ::NTSTATUS = 0xC013000Eu32 as i32; +pub const STATUS_CLUSTER_JOIN_NOT_IN_PROGRESS: ::NTSTATUS = 0xC013000Fu32 as i32; +pub const STATUS_CLUSTER_INVALID_NETWORK: ::NTSTATUS = 0xC0130010u32 as i32; +pub const STATUS_CLUSTER_NO_NET_ADAPTERS: ::NTSTATUS = 0xC0130011u32 as i32; +pub const STATUS_CLUSTER_NODE_UP: ::NTSTATUS = 0xC0130012u32 as i32; +pub const STATUS_CLUSTER_NODE_PAUSED: ::NTSTATUS = 0xC0130013u32 as i32; +pub const STATUS_CLUSTER_NODE_NOT_PAUSED: ::NTSTATUS = 0xC0130014u32 as i32; +pub const STATUS_CLUSTER_NO_SECURITY_CONTEXT: ::NTSTATUS = 0xC0130015u32 as i32; +pub const STATUS_CLUSTER_NETWORK_NOT_INTERNAL: ::NTSTATUS = 0xC0130016u32 as i32; +pub const STATUS_CLUSTER_POISONED: ::NTSTATUS = 0xC0130017u32 as i32; +pub const STATUS_CLUSTER_NON_CSV_PATH: ::NTSTATUS = 0xC0130018u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_NOT_LOCAL: ::NTSTATUS = 0xC0130019u32 as i32; +pub const STATUS_CLUSTER_CSV_READ_OPLOCK_BREAK_IN_PROGRESS: ::NTSTATUS = 0xC0130020u32 as i32; +pub const STATUS_CLUSTER_CSV_AUTO_PAUSE_ERROR: ::NTSTATUS = 0xC0130021u32 as i32; +pub const STATUS_CLUSTER_CSV_REDIRECTED: ::NTSTATUS = 0xC0130022u32 as i32; +pub const STATUS_CLUSTER_CSV_NOT_REDIRECTED: ::NTSTATUS = 0xC0130023u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_DRAINING: ::NTSTATUS = 0xC0130024u32 as i32; +pub const STATUS_CLUSTER_CSV_SNAPSHOT_CREATION_IN_PROGRESS: ::NTSTATUS = 0xC0130025u32 as i32; +pub const STATUS_CLUSTER_CSV_VOLUME_DRAINING_SUCCEEDED_DOWNLEVEL: ::NTSTATUS = 0xC0130026u32 as i32; +pub const STATUS_CLUSTER_CSV_NO_SNAPSHOTS: ::NTSTATUS = 0xC0130027u32 as i32; +pub const STATUS_CSV_IO_PAUSE_TIMEOUT: ::NTSTATUS = 0xC0130028u32 as i32; +pub const STATUS_TRANSACTIONAL_CONFLICT: ::NTSTATUS = 0xC0190001u32 as i32; +pub const STATUS_INVALID_TRANSACTION: ::NTSTATUS = 0xC0190002u32 as i32; +pub const STATUS_TRANSACTION_NOT_ACTIVE: ::NTSTATUS = 0xC0190003u32 as i32; +pub const STATUS_TM_INITIALIZATION_FAILED: ::NTSTATUS = 0xC0190004u32 as i32; +pub const STATUS_RM_NOT_ACTIVE: ::NTSTATUS = 0xC0190005u32 as i32; +pub const STATUS_RM_METADATA_CORRUPT: ::NTSTATUS = 0xC0190006u32 as i32; +pub const STATUS_TRANSACTION_NOT_JOINED: ::NTSTATUS = 0xC0190007u32 as i32; +pub const STATUS_DIRECTORY_NOT_RM: ::NTSTATUS = 0xC0190008u32 as i32; +pub const STATUS_COULD_NOT_RESIZE_LOG: ::NTSTATUS = 0x80190009u32 as i32; +pub const STATUS_TRANSACTIONS_UNSUPPORTED_REMOTE: ::NTSTATUS = 0xC019000Au32 as i32; +pub const STATUS_LOG_RESIZE_INVALID_SIZE: ::NTSTATUS = 0xC019000Bu32 as i32; +pub const STATUS_REMOTE_FILE_VERSION_MISMATCH: ::NTSTATUS = 0xC019000Cu32 as i32; +pub const STATUS_CRM_PROTOCOL_ALREADY_EXISTS: ::NTSTATUS = 0xC019000Fu32 as i32; +pub const STATUS_TRANSACTION_PROPAGATION_FAILED: ::NTSTATUS = 0xC0190010u32 as i32; +pub const STATUS_CRM_PROTOCOL_NOT_FOUND: ::NTSTATUS = 0xC0190011u32 as i32; +pub const STATUS_TRANSACTION_SUPERIOR_EXISTS: ::NTSTATUS = 0xC0190012u32 as i32; +pub const STATUS_TRANSACTION_REQUEST_NOT_VALID: ::NTSTATUS = 0xC0190013u32 as i32; +pub const STATUS_TRANSACTION_NOT_REQUESTED: ::NTSTATUS = 0xC0190014u32 as i32; +pub const STATUS_TRANSACTION_ALREADY_ABORTED: ::NTSTATUS = 0xC0190015u32 as i32; +pub const STATUS_TRANSACTION_ALREADY_COMMITTED: ::NTSTATUS = 0xC0190016u32 as i32; +pub const STATUS_TRANSACTION_INVALID_MARSHALL_BUFFER: ::NTSTATUS = 0xC0190017u32 as i32; +pub const STATUS_CURRENT_TRANSACTION_NOT_VALID: ::NTSTATUS = 0xC0190018u32 as i32; +pub const STATUS_LOG_GROWTH_FAILED: ::NTSTATUS = 0xC0190019u32 as i32; +pub const STATUS_OBJECT_NO_LONGER_EXISTS: ::NTSTATUS = 0xC0190021u32 as i32; +pub const STATUS_STREAM_MINIVERSION_NOT_FOUND: ::NTSTATUS = 0xC0190022u32 as i32; +pub const STATUS_STREAM_MINIVERSION_NOT_VALID: ::NTSTATUS = 0xC0190023u32 as i32; +pub const STATUS_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: ::NTSTATUS = 0xC0190024u32 as i32; +pub const STATUS_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: ::NTSTATUS = 0xC0190025u32 as i32; +pub const STATUS_CANT_CREATE_MORE_STREAM_MINIVERSIONS: ::NTSTATUS = 0xC0190026u32 as i32; +pub const STATUS_HANDLE_NO_LONGER_VALID: ::NTSTATUS = 0xC0190028u32 as i32; +pub const STATUS_NO_TXF_METADATA: ::NTSTATUS = 0x80190029u32 as i32; +pub const STATUS_LOG_CORRUPTION_DETECTED: ::NTSTATUS = 0xC0190030u32 as i32; +pub const STATUS_CANT_RECOVER_WITH_HANDLE_OPEN: ::NTSTATUS = 0x80190031u32 as i32; +pub const STATUS_RM_DISCONNECTED: ::NTSTATUS = 0xC0190032u32 as i32; +pub const STATUS_ENLISTMENT_NOT_SUPERIOR: ::NTSTATUS = 0xC0190033u32 as i32; +pub const STATUS_RECOVERY_NOT_NEEDED: ::NTSTATUS = 0x40190034; +pub const STATUS_RM_ALREADY_STARTED: ::NTSTATUS = 0x40190035; +pub const STATUS_FILE_IDENTITY_NOT_PERSISTENT: ::NTSTATUS = 0xC0190036u32 as i32; +pub const STATUS_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: ::NTSTATUS = 0xC0190037u32 as i32; +pub const STATUS_CANT_CROSS_RM_BOUNDARY: ::NTSTATUS = 0xC0190038u32 as i32; +pub const STATUS_TXF_DIR_NOT_EMPTY: ::NTSTATUS = 0xC0190039u32 as i32; +pub const STATUS_INDOUBT_TRANSACTIONS_EXIST: ::NTSTATUS = 0xC019003Au32 as i32; +pub const STATUS_TM_VOLATILE: ::NTSTATUS = 0xC019003Bu32 as i32; +pub const STATUS_ROLLBACK_TIMER_EXPIRED: ::NTSTATUS = 0xC019003Cu32 as i32; +pub const STATUS_TXF_ATTRIBUTE_CORRUPT: ::NTSTATUS = 0xC019003Du32 as i32; +pub const STATUS_EFS_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC019003Eu32 as i32; +pub const STATUS_TRANSACTIONAL_OPEN_NOT_ALLOWED: ::NTSTATUS = 0xC019003Fu32 as i32; +pub const STATUS_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: ::NTSTATUS = 0xC0190040u32 as i32; +pub const STATUS_TXF_METADATA_ALREADY_PRESENT: ::NTSTATUS = 0x80190041u32 as i32; +pub const STATUS_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: ::NTSTATUS = 0x80190042u32 as i32; +pub const STATUS_TRANSACTION_REQUIRED_PROMOTION: ::NTSTATUS = 0xC0190043u32 as i32; +pub const STATUS_CANNOT_EXECUTE_FILE_IN_TRANSACTION: ::NTSTATUS = 0xC0190044u32 as i32; +pub const STATUS_TRANSACTIONS_NOT_FROZEN: ::NTSTATUS = 0xC0190045u32 as i32; +pub const STATUS_TRANSACTION_FREEZE_IN_PROGRESS: ::NTSTATUS = 0xC0190046u32 as i32; +pub const STATUS_NOT_SNAPSHOT_VOLUME: ::NTSTATUS = 0xC0190047u32 as i32; +pub const STATUS_NO_SAVEPOINT_WITH_OPEN_FILES: ::NTSTATUS = 0xC0190048u32 as i32; +pub const STATUS_SPARSE_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC0190049u32 as i32; +pub const STATUS_TM_IDENTITY_MISMATCH: ::NTSTATUS = 0xC019004Au32 as i32; +pub const STATUS_FLOATED_SECTION: ::NTSTATUS = 0xC019004Bu32 as i32; +pub const STATUS_CANNOT_ACCEPT_TRANSACTED_WORK: ::NTSTATUS = 0xC019004Cu32 as i32; +pub const STATUS_CANNOT_ABORT_TRANSACTIONS: ::NTSTATUS = 0xC019004Du32 as i32; +pub const STATUS_TRANSACTION_NOT_FOUND: ::NTSTATUS = 0xC019004Eu32 as i32; +pub const STATUS_RESOURCEMANAGER_NOT_FOUND: ::NTSTATUS = 0xC019004Fu32 as i32; +pub const STATUS_ENLISTMENT_NOT_FOUND: ::NTSTATUS = 0xC0190050u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_NOT_FOUND: ::NTSTATUS = 0xC0190051u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_NOT_ONLINE: ::NTSTATUS = 0xC0190052u32 as i32; +pub const STATUS_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: ::NTSTATUS = 0xC0190053u32 as i32; +pub const STATUS_TRANSACTION_NOT_ROOT: ::NTSTATUS = 0xC0190054u32 as i32; +pub const STATUS_TRANSACTION_OBJECT_EXPIRED: ::NTSTATUS = 0xC0190055u32 as i32; +pub const STATUS_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: ::NTSTATUS = 0xC0190056u32 as i32; +pub const STATUS_TRANSACTION_RESPONSE_NOT_ENLISTED: ::NTSTATUS = 0xC0190057u32 as i32; +pub const STATUS_TRANSACTION_RECORD_TOO_LONG: ::NTSTATUS = 0xC0190058u32 as i32; +pub const STATUS_NO_LINK_TRACKING_IN_TRANSACTION: ::NTSTATUS = 0xC0190059u32 as i32; +pub const STATUS_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: ::NTSTATUS = 0xC019005Au32 as i32; +pub const STATUS_TRANSACTION_INTEGRITY_VIOLATED: ::NTSTATUS = 0xC019005Bu32 as i32; +pub const STATUS_TRANSACTIONMANAGER_IDENTITY_MISMATCH: ::NTSTATUS = 0xC019005Cu32 as i32; +pub const STATUS_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: ::NTSTATUS = 0xC019005Du32 as i32; +pub const STATUS_TRANSACTION_MUST_WRITETHROUGH: ::NTSTATUS = 0xC019005Eu32 as i32; +pub const STATUS_TRANSACTION_NO_SUPERIOR: ::NTSTATUS = 0xC019005Fu32 as i32; +pub const STATUS_EXPIRED_HANDLE: ::NTSTATUS = 0xC0190060u32 as i32; +pub const STATUS_TRANSACTION_NOT_ENLISTED: ::NTSTATUS = 0xC0190061u32 as i32; +pub const STATUS_LOG_SECTOR_INVALID: ::NTSTATUS = 0xC01A0001u32 as i32; +pub const STATUS_LOG_SECTOR_PARITY_INVALID: ::NTSTATUS = 0xC01A0002u32 as i32; +pub const STATUS_LOG_SECTOR_REMAPPED: ::NTSTATUS = 0xC01A0003u32 as i32; +pub const STATUS_LOG_BLOCK_INCOMPLETE: ::NTSTATUS = 0xC01A0004u32 as i32; +pub const STATUS_LOG_INVALID_RANGE: ::NTSTATUS = 0xC01A0005u32 as i32; +pub const STATUS_LOG_BLOCKS_EXHAUSTED: ::NTSTATUS = 0xC01A0006u32 as i32; +pub const STATUS_LOG_READ_CONTEXT_INVALID: ::NTSTATUS = 0xC01A0007u32 as i32; +pub const STATUS_LOG_RESTART_INVALID: ::NTSTATUS = 0xC01A0008u32 as i32; +pub const STATUS_LOG_BLOCK_VERSION: ::NTSTATUS = 0xC01A0009u32 as i32; +pub const STATUS_LOG_BLOCK_INVALID: ::NTSTATUS = 0xC01A000Au32 as i32; +pub const STATUS_LOG_READ_MODE_INVALID: ::NTSTATUS = 0xC01A000Bu32 as i32; +pub const STATUS_LOG_NO_RESTART: ::NTSTATUS = 0x401A000C; +pub const STATUS_LOG_METADATA_CORRUPT: ::NTSTATUS = 0xC01A000Du32 as i32; +pub const STATUS_LOG_METADATA_INVALID: ::NTSTATUS = 0xC01A000Eu32 as i32; +pub const STATUS_LOG_METADATA_INCONSISTENT: ::NTSTATUS = 0xC01A000Fu32 as i32; +pub const STATUS_LOG_RESERVATION_INVALID: ::NTSTATUS = 0xC01A0010u32 as i32; +pub const STATUS_LOG_CANT_DELETE: ::NTSTATUS = 0xC01A0011u32 as i32; +pub const STATUS_LOG_CONTAINER_LIMIT_EXCEEDED: ::NTSTATUS = 0xC01A0012u32 as i32; +pub const STATUS_LOG_START_OF_LOG: ::NTSTATUS = 0xC01A0013u32 as i32; +pub const STATUS_LOG_POLICY_ALREADY_INSTALLED: ::NTSTATUS = 0xC01A0014u32 as i32; +pub const STATUS_LOG_POLICY_NOT_INSTALLED: ::NTSTATUS = 0xC01A0015u32 as i32; +pub const STATUS_LOG_POLICY_INVALID: ::NTSTATUS = 0xC01A0016u32 as i32; +pub const STATUS_LOG_POLICY_CONFLICT: ::NTSTATUS = 0xC01A0017u32 as i32; +pub const STATUS_LOG_PINNED_ARCHIVE_TAIL: ::NTSTATUS = 0xC01A0018u32 as i32; +pub const STATUS_LOG_RECORD_NONEXISTENT: ::NTSTATUS = 0xC01A0019u32 as i32; +pub const STATUS_LOG_RECORDS_RESERVED_INVALID: ::NTSTATUS = 0xC01A001Au32 as i32; +pub const STATUS_LOG_SPACE_RESERVED_INVALID: ::NTSTATUS = 0xC01A001Bu32 as i32; +pub const STATUS_LOG_TAIL_INVALID: ::NTSTATUS = 0xC01A001Cu32 as i32; +pub const STATUS_LOG_FULL: ::NTSTATUS = 0xC01A001Du32 as i32; +pub const STATUS_LOG_MULTIPLEXED: ::NTSTATUS = 0xC01A001Eu32 as i32; +pub const STATUS_LOG_DEDICATED: ::NTSTATUS = 0xC01A001Fu32 as i32; +pub const STATUS_LOG_ARCHIVE_NOT_IN_PROGRESS: ::NTSTATUS = 0xC01A0020u32 as i32; +pub const STATUS_LOG_ARCHIVE_IN_PROGRESS: ::NTSTATUS = 0xC01A0021u32 as i32; +pub const STATUS_LOG_EPHEMERAL: ::NTSTATUS = 0xC01A0022u32 as i32; +pub const STATUS_LOG_NOT_ENOUGH_CONTAINERS: ::NTSTATUS = 0xC01A0023u32 as i32; +pub const STATUS_LOG_CLIENT_ALREADY_REGISTERED: ::NTSTATUS = 0xC01A0024u32 as i32; +pub const STATUS_LOG_CLIENT_NOT_REGISTERED: ::NTSTATUS = 0xC01A0025u32 as i32; +pub const STATUS_LOG_FULL_HANDLER_IN_PROGRESS: ::NTSTATUS = 0xC01A0026u32 as i32; +pub const STATUS_LOG_CONTAINER_READ_FAILED: ::NTSTATUS = 0xC01A0027u32 as i32; +pub const STATUS_LOG_CONTAINER_WRITE_FAILED: ::NTSTATUS = 0xC01A0028u32 as i32; +pub const STATUS_LOG_CONTAINER_OPEN_FAILED: ::NTSTATUS = 0xC01A0029u32 as i32; +pub const STATUS_LOG_CONTAINER_STATE_INVALID: ::NTSTATUS = 0xC01A002Au32 as i32; +pub const STATUS_LOG_STATE_INVALID: ::NTSTATUS = 0xC01A002Bu32 as i32; +pub const STATUS_LOG_PINNED: ::NTSTATUS = 0xC01A002Cu32 as i32; +pub const STATUS_LOG_METADATA_FLUSH_FAILED: ::NTSTATUS = 0xC01A002Du32 as i32; +pub const STATUS_LOG_INCONSISTENT_SECURITY: ::NTSTATUS = 0xC01A002Eu32 as i32; +pub const STATUS_LOG_APPENDED_FLUSH_FAILED: ::NTSTATUS = 0xC01A002Fu32 as i32; +pub const STATUS_LOG_PINNED_RESERVATION: ::NTSTATUS = 0xC01A0030u32 as i32; +pub const STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD: ::NTSTATUS = 0xC01B00EAu32 as i32; +pub const STATUS_VIDEO_HUNG_DISPLAY_DRIVER_THREAD_RECOVERED: ::NTSTATUS = 0x801B00EBu32 as i32; +pub const STATUS_VIDEO_DRIVER_DEBUG_REPORT_REQUEST: ::NTSTATUS = 0x401B00EC; +pub const STATUS_MONITOR_NO_DESCRIPTOR: ::NTSTATUS = 0xC01D0001u32 as i32; +pub const STATUS_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: ::NTSTATUS = 0xC01D0002u32 as i32; +pub const STATUS_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: ::NTSTATUS = 0xC01D0003u32 as i32; +pub const STATUS_MONITOR_INVALID_STANDARD_TIMING_BLOCK: ::NTSTATUS = 0xC01D0004u32 as i32; +pub const STATUS_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: ::NTSTATUS = 0xC01D0005u32 as i32; +pub const STATUS_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: ::NTSTATUS = 0xC01D0006u32 as i32; +pub const STATUS_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: ::NTSTATUS = 0xC01D0007u32 as i32; +pub const STATUS_MONITOR_NO_MORE_DESCRIPTOR_DATA: ::NTSTATUS = 0xC01D0008u32 as i32; +pub const STATUS_MONITOR_INVALID_DETAILED_TIMING_BLOCK: ::NTSTATUS = 0xC01D0009u32 as i32; +pub const STATUS_MONITOR_INVALID_MANUFACTURE_DATE: ::NTSTATUS = 0xC01D000Au32 as i32; +pub const STATUS_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: ::NTSTATUS = 0xC01E0000u32 as i32; +pub const STATUS_GRAPHICS_INSUFFICIENT_DMA_BUFFER: ::NTSTATUS = 0xC01E0001u32 as i32; +pub const STATUS_GRAPHICS_INVALID_DISPLAY_ADAPTER: ::NTSTATUS = 0xC01E0002u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_WAS_RESET: ::NTSTATUS = 0xC01E0003u32 as i32; +pub const STATUS_GRAPHICS_INVALID_DRIVER_MODEL: ::NTSTATUS = 0xC01E0004u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_MODE_CHANGED: ::NTSTATUS = 0xC01E0005u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_OCCLUDED: ::NTSTATUS = 0xC01E0006u32 as i32; +pub const STATUS_GRAPHICS_PRESENT_DENIED: ::NTSTATUS = 0xC01E0007u32 as i32; +pub const STATUS_GRAPHICS_CANNOTCOLORCONVERT: ::NTSTATUS = 0xC01E0008u32 as i32; +pub const STATUS_GRAPHICS_DRIVER_MISMATCH: ::NTSTATUS = 0xC01E0009u32 as i32; +pub const STATUS_GRAPHICS_PARTIAL_DATA_POPULATED: ::NTSTATUS = 0x401E000A; +pub const STATUS_GRAPHICS_PRESENT_REDIRECTION_DISABLED: ::NTSTATUS = 0xC01E000Bu32 as i32; +pub const STATUS_GRAPHICS_PRESENT_UNOCCLUDED: ::NTSTATUS = 0xC01E000Cu32 as i32; +pub const STATUS_GRAPHICS_WINDOWDC_NOT_AVAILABLE: ::NTSTATUS = 0xC01E000Du32 as i32; +pub const STATUS_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: ::NTSTATUS = 0xC01E000Eu32 as i32; +pub const STATUS_GRAPHICS_NO_VIDEO_MEMORY: ::NTSTATUS = 0xC01E0100u32 as i32; +pub const STATUS_GRAPHICS_CANT_LOCK_MEMORY: ::NTSTATUS = 0xC01E0101u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_BUSY: ::NTSTATUS = 0xC01E0102u32 as i32; +pub const STATUS_GRAPHICS_TOO_MANY_REFERENCES: ::NTSTATUS = 0xC01E0103u32 as i32; +pub const STATUS_GRAPHICS_TRY_AGAIN_LATER: ::NTSTATUS = 0xC01E0104u32 as i32; +pub const STATUS_GRAPHICS_TRY_AGAIN_NOW: ::NTSTATUS = 0xC01E0105u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_INVALID: ::NTSTATUS = 0xC01E0106u32 as i32; +pub const STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: ::NTSTATUS = 0xC01E0107u32 as i32; +pub const STATUS_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: ::NTSTATUS = 0xC01E0108u32 as i32; +pub const STATUS_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: ::NTSTATUS = 0xC01E0109u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_USAGE: ::NTSTATUS = 0xC01E0110u32 as i32; +pub const STATUS_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: ::NTSTATUS = 0xC01E0111u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_CLOSED: ::NTSTATUS = 0xC01E0112u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_INSTANCE: ::NTSTATUS = 0xC01E0113u32 as i32; +pub const STATUS_GRAPHICS_INVALID_ALLOCATION_HANDLE: ::NTSTATUS = 0xC01E0114u32 as i32; +pub const STATUS_GRAPHICS_WRONG_ALLOCATION_DEVICE: ::NTSTATUS = 0xC01E0115u32 as i32; +pub const STATUS_GRAPHICS_ALLOCATION_CONTENT_LOST: ::NTSTATUS = 0xC01E0116u32 as i32; +pub const STATUS_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: ::NTSTATUS = 0xC01E0200u32 as i32; +pub const STATUS_GRAPHICS_SKIP_ALLOCATION_PREPARATION: ::NTSTATUS = 0x401E0201; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E0300u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0301u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0302u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN: ::NTSTATUS = 0xC01E0303u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: ::NTSTATUS = 0xC01E0304u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: ::NTSTATUS = 0xC01E0305u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0306u32 as i32; +pub const STATUS_GRAPHICS_MODE_NOT_PINNED: ::NTSTATUS = 0x401E0307; +pub const STATUS_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: ::NTSTATUS = 0xC01E0308u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TARGETMODESET: ::NTSTATUS = 0xC01E0309u32 as i32; +pub const STATUS_GRAPHICS_INVALID_FREQUENCY: ::NTSTATUS = 0xC01E030Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_ACTIVE_REGION: ::NTSTATUS = 0xC01E030Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_TOTAL_REGION: ::NTSTATUS = 0xC01E030Cu32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: ::NTSTATUS = 0xC01E0310u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: ::NTSTATUS = 0xC01E0311u32 as i32; +pub const STATUS_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: ::NTSTATUS = 0xC01E0312u32 as i32; +pub const STATUS_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0313u32 as i32; +pub const STATUS_GRAPHICS_MODE_ALREADY_IN_MODESET: ::NTSTATUS = 0xC01E0314u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: ::NTSTATUS = 0xC01E0315u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: ::NTSTATUS = 0xC01E0316u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_ALREADY_IN_SET: ::NTSTATUS = 0xC01E0317u32 as i32; +pub const STATUS_GRAPHICS_TARGET_ALREADY_IN_SET: ::NTSTATUS = 0xC01E0318u32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: ::NTSTATUS = 0xC01E0319u32 as i32; +pub const STATUS_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E031Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: ::NTSTATUS = 0xC01E031Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: ::NTSTATUS = 0xC01E031Cu32 as i32; +pub const STATUS_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: ::NTSTATUS = 0xC01E031Du32 as i32; +pub const STATUS_GRAPHICS_NO_PREFERRED_MODE: ::NTSTATUS = 0x401E031E; +pub const STATUS_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: ::NTSTATUS = 0xC01E031Fu32 as i32; +pub const STATUS_GRAPHICS_STALE_MODESET: ::NTSTATUS = 0xC01E0320u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: ::NTSTATUS = 0xC01E0321u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: ::NTSTATUS = 0xC01E0322u32 as i32; +pub const STATUS_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: ::NTSTATUS = 0xC01E0323u32 as i32; +pub const STATUS_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0324u32 as i32; +pub const STATUS_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: ::NTSTATUS = 0xC01E0325u32 as i32; +pub const STATUS_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: ::NTSTATUS = 0xC01E0326u32 as i32; +pub const STATUS_GRAPHICS_PATH_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0327u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: ::NTSTATUS = 0xC01E0328u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: ::NTSTATUS = 0xC01E0329u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITORDESCRIPTORSET: ::NTSTATUS = 0xC01E032Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITORDESCRIPTOR: ::NTSTATUS = 0xC01E032Bu32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: ::NTSTATUS = 0xC01E032Cu32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: ::NTSTATUS = 0xC01E032Du32 as i32; +pub const STATUS_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E032Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: ::NTSTATUS = 0xC01E032Fu32 as i32; +pub const STATUS_GRAPHICS_RESOURCES_NOT_RELATED: ::NTSTATUS = 0xC01E0330u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0331u32 as i32; +pub const STATUS_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: ::NTSTATUS = 0xC01E0332u32 as i32; +pub const STATUS_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: ::NTSTATUS = 0xC01E0333u32 as i32; +pub const STATUS_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: ::NTSTATUS = 0xC01E0334u32 as i32; +pub const STATUS_GRAPHICS_NO_VIDPNMGR: ::NTSTATUS = 0xC01E0335u32 as i32; +pub const STATUS_GRAPHICS_NO_ACTIVE_VIDPN: ::NTSTATUS = 0xC01E0336u32 as i32; +pub const STATUS_GRAPHICS_STALE_VIDPN_TOPOLOGY: ::NTSTATUS = 0xC01E0337u32 as i32; +pub const STATUS_GRAPHICS_MONITOR_NOT_CONNECTED: ::NTSTATUS = 0xC01E0338u32 as i32; +pub const STATUS_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0339u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: ::NTSTATUS = 0xC01E033Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_VISIBLEREGION_SIZE: ::NTSTATUS = 0xC01E033Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_STRIDE: ::NTSTATUS = 0xC01E033Cu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PIXELFORMAT: ::NTSTATUS = 0xC01E033Du32 as i32; +pub const STATUS_GRAPHICS_INVALID_COLORBASIS: ::NTSTATUS = 0xC01E033Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: ::NTSTATUS = 0xC01E033Fu32 as i32; +pub const STATUS_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: ::NTSTATUS = 0xC01E0340u32 as i32; +pub const STATUS_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: ::NTSTATUS = 0xC01E0341u32 as i32; +pub const STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: ::NTSTATUS = 0xC01E0342u32 as i32; +pub const STATUS_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: ::NTSTATUS = 0xC01E0343u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: ::NTSTATUS = 0xC01E0344u32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: ::NTSTATUS = 0xC01E0345u32 as i32; +pub const STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0346u32 as i32; +pub const STATUS_GRAPHICS_INVALID_GAMMA_RAMP: ::NTSTATUS = 0xC01E0347u32 as i32; +pub const STATUS_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0348u32 as i32; +pub const STATUS_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0349u32 as i32; +pub const STATUS_GRAPHICS_MODE_NOT_IN_MODESET: ::NTSTATUS = 0xC01E034Au32 as i32; +pub const STATUS_GRAPHICS_DATASET_IS_EMPTY: ::NTSTATUS = 0x401E034B; +pub const STATUS_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: ::NTSTATUS = 0x401E034C; +pub const STATUS_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: ::NTSTATUS = 0xC01E034Du32 as i32; +pub const STATUS_GRAPHICS_INVALID_PATH_CONTENT_TYPE: ::NTSTATUS = 0xC01E034Eu32 as i32; +pub const STATUS_GRAPHICS_INVALID_COPYPROTECTION_TYPE: ::NTSTATUS = 0xC01E034Fu32 as i32; +pub const STATUS_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: ::NTSTATUS = 0xC01E0350u32 as i32; +pub const STATUS_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: ::NTSTATUS = 0x401E0351; +pub const STATUS_GRAPHICS_INVALID_SCANLINE_ORDERING: ::NTSTATUS = 0xC01E0352u32 as i32; +pub const STATUS_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: ::NTSTATUS = 0xC01E0353u32 as i32; +pub const STATUS_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: ::NTSTATUS = 0xC01E0354u32 as i32; +pub const STATUS_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: ::NTSTATUS = 0xC01E0355u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: ::NTSTATUS = 0xC01E0356u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: ::NTSTATUS = 0xC01E0357u32 as i32; +pub const STATUS_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: ::NTSTATUS = 0xC01E0358u32 as i32; +pub const STATUS_GRAPHICS_MAX_NUM_PATHS_REACHED: ::NTSTATUS = 0xC01E0359u32 as i32; +pub const STATUS_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: ::NTSTATUS = 0xC01E035Au32 as i32; +pub const STATUS_GRAPHICS_INVALID_CLIENT_TYPE: ::NTSTATUS = 0xC01E035Bu32 as i32; +pub const STATUS_GRAPHICS_CLIENTVIDPN_NOT_SET: ::NTSTATUS = 0xC01E035Cu32 as i32; +pub const STATUS_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: ::NTSTATUS = 0xC01E0400u32 as i32; +pub const STATUS_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0401u32 as i32; +pub const STATUS_GRAPHICS_UNKNOWN_CHILD_STATUS: ::NTSTATUS = 0x401E042F; +pub const STATUS_GRAPHICS_NOT_A_LINKED_ADAPTER: ::NTSTATUS = 0xC01E0430u32 as i32; +pub const STATUS_GRAPHICS_LEADLINK_NOT_ENUMERATED: ::NTSTATUS = 0xC01E0431u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: ::NTSTATUS = 0xC01E0432u32 as i32; +pub const STATUS_GRAPHICS_ADAPTER_CHAIN_NOT_READY: ::NTSTATUS = 0xC01E0433u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_STARTED: ::NTSTATUS = 0xC01E0434u32 as i32; +pub const STATUS_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: ::NTSTATUS = 0xC01E0435u32 as i32; +pub const STATUS_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: ::NTSTATUS = 0xC01E0436u32 as i32; +pub const STATUS_GRAPHICS_LEADLINK_START_DEFERRED: ::NTSTATUS = 0x401E0437; +pub const STATUS_GRAPHICS_NOT_POST_DEVICE_DRIVER: ::NTSTATUS = 0xC01E0438u32 as i32; +pub const STATUS_GRAPHICS_POLLING_TOO_FREQUENTLY: ::NTSTATUS = 0x401E0439; +pub const STATUS_GRAPHICS_START_DEFERRED: ::NTSTATUS = 0x401E043A; +pub const STATUS_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: ::NTSTATUS = 0xC01E043Bu32 as i32; +pub const STATUS_GRAPHICS_DEPENDABLE_CHILD_STATUS: ::NTSTATUS = 0x401E043C; +pub const STATUS_GRAPHICS_OPM_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0500u32 as i32; +pub const STATUS_GRAPHICS_COPP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0501u32 as i32; +pub const STATUS_GRAPHICS_UAB_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0502u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: ::NTSTATUS = 0xC01E0503u32 as i32; +pub const STATUS_GRAPHICS_OPM_NO_PROTECTED_OUTPUTS_EXIST: ::NTSTATUS = 0xC01E0505u32 as i32; +pub const STATUS_GRAPHICS_OPM_INTERNAL_ERROR: ::NTSTATUS = 0xC01E050Bu32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_HANDLE: ::NTSTATUS = 0xC01E050Cu32 as i32; +pub const STATUS_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: ::NTSTATUS = 0xC01E050Eu32 as i32; +pub const STATUS_GRAPHICS_OPM_SPANNING_MODE_ENABLED: ::NTSTATUS = 0xC01E050Fu32 as i32; +pub const STATUS_GRAPHICS_OPM_THEATER_MODE_ENABLED: ::NTSTATUS = 0xC01E0510u32 as i32; +pub const STATUS_GRAPHICS_PVP_HFS_FAILED: ::NTSTATUS = 0xC01E0511u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_SRM: ::NTSTATUS = 0xC01E0512u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: ::NTSTATUS = 0xC01E0513u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: ::NTSTATUS = 0xC01E0514u32 as i32; +pub const STATUS_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: ::NTSTATUS = 0xC01E0515u32 as i32; +pub const STATUS_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: ::NTSTATUS = 0xC01E0516u32 as i32; +pub const STATUS_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: ::NTSTATUS = 0xC01E0517u32 as i32; +pub const STATUS_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: ::NTSTATUS = 0xC01E0518u32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_NO_LONGER_EXISTS: ::NTSTATUS = 0xC01E051Au32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: ::NTSTATUS = 0xC01E051Cu32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: ::NTSTATUS = 0xC01E051Du32 as i32; +pub const STATUS_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: ::NTSTATUS = 0xC01E051Eu32 as i32; +pub const STATUS_GRAPHICS_OPM_PROTECTED_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: ::NTSTATUS = 0xC01E051Fu32 as i32; +pub const STATUS_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0520u32 as i32; +pub const STATUS_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: ::NTSTATUS = 0xC01E0521u32 as i32; +pub const STATUS_GRAPHICS_I2C_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0580u32 as i32; +pub const STATUS_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: ::NTSTATUS = 0xC01E0581u32 as i32; +pub const STATUS_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: ::NTSTATUS = 0xC01E0582u32 as i32; +pub const STATUS_GRAPHICS_I2C_ERROR_RECEIVING_DATA: ::NTSTATUS = 0xC01E0583u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: ::NTSTATUS = 0xC01E0584u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_DATA: ::NTSTATUS = 0xC01E0585u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: ::NTSTATUS = 0xC01E0586u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_CAPABILITIES_STRING: ::NTSTATUS = 0xC01E0587u32 as i32; +pub const STATUS_GRAPHICS_MCA_INTERNAL_ERROR: ::NTSTATUS = 0xC01E0588u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: ::NTSTATUS = 0xC01E0589u32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: ::NTSTATUS = 0xC01E058Au32 as i32; +pub const STATUS_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: ::NTSTATUS = 0xC01E058Bu32 as i32; +pub const STATUS_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: ::NTSTATUS = 0xC01E058Cu32 as i32; +pub const STATUS_GRAPHICS_MONITOR_NO_LONGER_EXISTS: ::NTSTATUS = 0xC01E058Du32 as i32; +pub const STATUS_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: ::NTSTATUS = 0xC01E05E0u32 as i32; +pub const STATUS_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: ::NTSTATUS = 0xC01E05E1u32 as i32; +pub const STATUS_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: ::NTSTATUS = 0xC01E05E2u32 as i32; +pub const STATUS_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: ::NTSTATUS = 0xC01E05E3u32 as i32; +pub const STATUS_GRAPHICS_INVALID_POINTER: ::NTSTATUS = 0xC01E05E4u32 as i32; +pub const STATUS_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: ::NTSTATUS = 0xC01E05E5u32 as i32; +pub const STATUS_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: ::NTSTATUS = 0xC01E05E6u32 as i32; +pub const STATUS_GRAPHICS_INTERNAL_ERROR: ::NTSTATUS = 0xC01E05E7u32 as i32; +pub const STATUS_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: ::NTSTATUS = 0xC01E05E8u32 as i32; +pub const STATUS_FVE_LOCKED_VOLUME: ::NTSTATUS = 0xC0210000u32 as i32; +pub const STATUS_FVE_NOT_ENCRYPTED: ::NTSTATUS = 0xC0210001u32 as i32; +pub const STATUS_FVE_BAD_INFORMATION: ::NTSTATUS = 0xC0210002u32 as i32; +pub const STATUS_FVE_TOO_SMALL: ::NTSTATUS = 0xC0210003u32 as i32; +pub const STATUS_FVE_FAILED_WRONG_FS: ::NTSTATUS = 0xC0210004u32 as i32; +pub const STATUS_FVE_BAD_PARTITION_SIZE: ::NTSTATUS = 0xC0210005u32 as i32; +pub const STATUS_FVE_FS_NOT_EXTENDED: ::NTSTATUS = 0xC0210006u32 as i32; +pub const STATUS_FVE_FS_MOUNTED: ::NTSTATUS = 0xC0210007u32 as i32; +pub const STATUS_FVE_NO_LICENSE: ::NTSTATUS = 0xC0210008u32 as i32; +pub const STATUS_FVE_ACTION_NOT_ALLOWED: ::NTSTATUS = 0xC0210009u32 as i32; +pub const STATUS_FVE_BAD_DATA: ::NTSTATUS = 0xC021000Au32 as i32; +pub const STATUS_FVE_VOLUME_NOT_BOUND: ::NTSTATUS = 0xC021000Bu32 as i32; +pub const STATUS_FVE_NOT_DATA_VOLUME: ::NTSTATUS = 0xC021000Cu32 as i32; +pub const STATUS_FVE_CONV_READ_ERROR: ::NTSTATUS = 0xC021000Du32 as i32; +pub const STATUS_FVE_CONV_WRITE_ERROR: ::NTSTATUS = 0xC021000Eu32 as i32; +pub const STATUS_FVE_OVERLAPPED_UPDATE: ::NTSTATUS = 0xC021000Fu32 as i32; +pub const STATUS_FVE_FAILED_SECTOR_SIZE: ::NTSTATUS = 0xC0210010u32 as i32; +pub const STATUS_FVE_FAILED_AUTHENTICATION: ::NTSTATUS = 0xC0210011u32 as i32; +pub const STATUS_FVE_NOT_OS_VOLUME: ::NTSTATUS = 0xC0210012u32 as i32; +pub const STATUS_FVE_KEYFILE_NOT_FOUND: ::NTSTATUS = 0xC0210013u32 as i32; +pub const STATUS_FVE_KEYFILE_INVALID: ::NTSTATUS = 0xC0210014u32 as i32; +pub const STATUS_FVE_KEYFILE_NO_VMK: ::NTSTATUS = 0xC0210015u32 as i32; +pub const STATUS_FVE_TPM_DISABLED: ::NTSTATUS = 0xC0210016u32 as i32; +pub const STATUS_FVE_TPM_SRK_AUTH_NOT_ZERO: ::NTSTATUS = 0xC0210017u32 as i32; +pub const STATUS_FVE_TPM_INVALID_PCR: ::NTSTATUS = 0xC0210018u32 as i32; +pub const STATUS_FVE_TPM_NO_VMK: ::NTSTATUS = 0xC0210019u32 as i32; +pub const STATUS_FVE_PIN_INVALID: ::NTSTATUS = 0xC021001Au32 as i32; +pub const STATUS_FVE_AUTH_INVALID_APPLICATION: ::NTSTATUS = 0xC021001Bu32 as i32; +pub const STATUS_FVE_AUTH_INVALID_CONFIG: ::NTSTATUS = 0xC021001Cu32 as i32; +pub const STATUS_FVE_DEBUGGER_ENABLED: ::NTSTATUS = 0xC021001Du32 as i32; +pub const STATUS_FVE_DRY_RUN_FAILED: ::NTSTATUS = 0xC021001Eu32 as i32; +pub const STATUS_FVE_BAD_METADATA_POINTER: ::NTSTATUS = 0xC021001Fu32 as i32; +pub const STATUS_FVE_OLD_METADATA_COPY: ::NTSTATUS = 0xC0210020u32 as i32; +pub const STATUS_FVE_REBOOT_REQUIRED: ::NTSTATUS = 0xC0210021u32 as i32; +pub const STATUS_FVE_RAW_ACCESS: ::NTSTATUS = 0xC0210022u32 as i32; +pub const STATUS_FVE_RAW_BLOCKED: ::NTSTATUS = 0xC0210023u32 as i32; +pub const STATUS_FVE_NO_AUTOUNLOCK_MASTER_KEY: ::NTSTATUS = 0xC0210024u32 as i32; +pub const STATUS_FVE_MOR_FAILED: ::NTSTATUS = 0xC0210025u32 as i32; +pub const STATUS_FVE_NO_FEATURE_LICENSE: ::NTSTATUS = 0xC0210026u32 as i32; +pub const STATUS_FVE_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: ::NTSTATUS = 0xC0210027u32 as i32; +pub const STATUS_FVE_CONV_RECOVERY_FAILED: ::NTSTATUS = 0xC0210028u32 as i32; +pub const STATUS_FVE_VIRTUALIZED_SPACE_TOO_BIG: ::NTSTATUS = 0xC0210029u32 as i32; +pub const STATUS_FVE_INVALID_DATUM_TYPE: ::NTSTATUS = 0xC021002Au32 as i32; +pub const STATUS_FVE_VOLUME_TOO_SMALL: ::NTSTATUS = 0xC0210030u32 as i32; +pub const STATUS_FVE_ENH_PIN_INVALID: ::NTSTATUS = 0xC0210031u32 as i32; +pub const STATUS_FVE_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: ::NTSTATUS = 0xC0210032u32 as i32; +pub const STATUS_FVE_WIPE_NOT_ALLOWED_ON_TP_STORAGE: ::NTSTATUS = 0xC0210033u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_ON_CSV_STACK: ::NTSTATUS = 0xC0210034u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_ON_CLUSTER: ::NTSTATUS = 0xC0210035u32 as i32; +pub const STATUS_FVE_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: ::NTSTATUS = 0xC0210036u32 as i32; +pub const STATUS_FVE_WIPE_CANCEL_NOT_APPLICABLE: ::NTSTATUS = 0xC0210037u32 as i32; +pub const STATUS_FVE_EDRIVE_DRY_RUN_FAILED: ::NTSTATUS = 0xC0210038u32 as i32; +pub const STATUS_FVE_SECUREBOOT_DISABLED: ::NTSTATUS = 0xC0210039u32 as i32; +pub const STATUS_FVE_SECUREBOOT_CONFIG_CHANGE: ::NTSTATUS = 0xC021003Au32 as i32; +pub const STATUS_FVE_DEVICE_LOCKEDOUT: ::NTSTATUS = 0xC021003Bu32 as i32; +pub const STATUS_FVE_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: ::NTSTATUS = 0xC021003Cu32 as i32; +pub const STATUS_FVE_NOT_DE_VOLUME: ::NTSTATUS = 0xC021003Du32 as i32; +pub const STATUS_FVE_PROTECTION_DISABLED: ::NTSTATUS = 0xC021003Eu32 as i32; +pub const STATUS_FVE_PROTECTION_CANNOT_BE_DISABLED: ::NTSTATUS = 0xC021003Fu32 as i32; +pub const STATUS_FWP_CALLOUT_NOT_FOUND: ::NTSTATUS = 0xC0220001u32 as i32; +pub const STATUS_FWP_CONDITION_NOT_FOUND: ::NTSTATUS = 0xC0220002u32 as i32; +pub const STATUS_FWP_FILTER_NOT_FOUND: ::NTSTATUS = 0xC0220003u32 as i32; +pub const STATUS_FWP_LAYER_NOT_FOUND: ::NTSTATUS = 0xC0220004u32 as i32; +pub const STATUS_FWP_PROVIDER_NOT_FOUND: ::NTSTATUS = 0xC0220005u32 as i32; +pub const STATUS_FWP_PROVIDER_CONTEXT_NOT_FOUND: ::NTSTATUS = 0xC0220006u32 as i32; +pub const STATUS_FWP_SUBLAYER_NOT_FOUND: ::NTSTATUS = 0xC0220007u32 as i32; +pub const STATUS_FWP_NOT_FOUND: ::NTSTATUS = 0xC0220008u32 as i32; +pub const STATUS_FWP_ALREADY_EXISTS: ::NTSTATUS = 0xC0220009u32 as i32; +pub const STATUS_FWP_IN_USE: ::NTSTATUS = 0xC022000Au32 as i32; +pub const STATUS_FWP_DYNAMIC_SESSION_IN_PROGRESS: ::NTSTATUS = 0xC022000Bu32 as i32; +pub const STATUS_FWP_WRONG_SESSION: ::NTSTATUS = 0xC022000Cu32 as i32; +pub const STATUS_FWP_NO_TXN_IN_PROGRESS: ::NTSTATUS = 0xC022000Du32 as i32; +pub const STATUS_FWP_TXN_IN_PROGRESS: ::NTSTATUS = 0xC022000Eu32 as i32; +pub const STATUS_FWP_TXN_ABORTED: ::NTSTATUS = 0xC022000Fu32 as i32; +pub const STATUS_FWP_SESSION_ABORTED: ::NTSTATUS = 0xC0220010u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_TXN: ::NTSTATUS = 0xC0220011u32 as i32; +pub const STATUS_FWP_TIMEOUT: ::NTSTATUS = 0xC0220012u32 as i32; +pub const STATUS_FWP_NET_EVENTS_DISABLED: ::NTSTATUS = 0xC0220013u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_LAYER: ::NTSTATUS = 0xC0220014u32 as i32; +pub const STATUS_FWP_KM_CLIENTS_ONLY: ::NTSTATUS = 0xC0220015u32 as i32; +pub const STATUS_FWP_LIFETIME_MISMATCH: ::NTSTATUS = 0xC0220016u32 as i32; +pub const STATUS_FWP_BUILTIN_OBJECT: ::NTSTATUS = 0xC0220017u32 as i32; +pub const STATUS_FWP_TOO_MANY_CALLOUTS: ::NTSTATUS = 0xC0220018u32 as i32; +pub const STATUS_FWP_NOTIFICATION_DROPPED: ::NTSTATUS = 0xC0220019u32 as i32; +pub const STATUS_FWP_TRAFFIC_MISMATCH: ::NTSTATUS = 0xC022001Au32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_SA_STATE: ::NTSTATUS = 0xC022001Bu32 as i32; +pub const STATUS_FWP_NULL_POINTER: ::NTSTATUS = 0xC022001Cu32 as i32; +pub const STATUS_FWP_INVALID_ENUMERATOR: ::NTSTATUS = 0xC022001Du32 as i32; +pub const STATUS_FWP_INVALID_FLAGS: ::NTSTATUS = 0xC022001Eu32 as i32; +pub const STATUS_FWP_INVALID_NET_MASK: ::NTSTATUS = 0xC022001Fu32 as i32; +pub const STATUS_FWP_INVALID_RANGE: ::NTSTATUS = 0xC0220020u32 as i32; +pub const STATUS_FWP_INVALID_INTERVAL: ::NTSTATUS = 0xC0220021u32 as i32; +pub const STATUS_FWP_ZERO_LENGTH_ARRAY: ::NTSTATUS = 0xC0220022u32 as i32; +pub const STATUS_FWP_NULL_DISPLAY_NAME: ::NTSTATUS = 0xC0220023u32 as i32; +pub const STATUS_FWP_INVALID_ACTION_TYPE: ::NTSTATUS = 0xC0220024u32 as i32; +pub const STATUS_FWP_INVALID_WEIGHT: ::NTSTATUS = 0xC0220025u32 as i32; +pub const STATUS_FWP_MATCH_TYPE_MISMATCH: ::NTSTATUS = 0xC0220026u32 as i32; +pub const STATUS_FWP_TYPE_MISMATCH: ::NTSTATUS = 0xC0220027u32 as i32; +pub const STATUS_FWP_OUT_OF_BOUNDS: ::NTSTATUS = 0xC0220028u32 as i32; +pub const STATUS_FWP_RESERVED: ::NTSTATUS = 0xC0220029u32 as i32; +pub const STATUS_FWP_DUPLICATE_CONDITION: ::NTSTATUS = 0xC022002Au32 as i32; +pub const STATUS_FWP_DUPLICATE_KEYMOD: ::NTSTATUS = 0xC022002Bu32 as i32; +pub const STATUS_FWP_ACTION_INCOMPATIBLE_WITH_LAYER: ::NTSTATUS = 0xC022002Cu32 as i32; +pub const STATUS_FWP_ACTION_INCOMPATIBLE_WITH_SUBLAYER: ::NTSTATUS = 0xC022002Du32 as i32; +pub const STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_LAYER: ::NTSTATUS = 0xC022002Eu32 as i32; +pub const STATUS_FWP_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: ::NTSTATUS = 0xC022002Fu32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_AUTH_METHOD: ::NTSTATUS = 0xC0220030u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_DH_GROUP: ::NTSTATUS = 0xC0220031u32 as i32; +pub const STATUS_FWP_EM_NOT_SUPPORTED: ::NTSTATUS = 0xC0220032u32 as i32; +pub const STATUS_FWP_NEVER_MATCH: ::NTSTATUS = 0xC0220033u32 as i32; +pub const STATUS_FWP_PROVIDER_CONTEXT_MISMATCH: ::NTSTATUS = 0xC0220034u32 as i32; +pub const STATUS_FWP_INVALID_PARAMETER: ::NTSTATUS = 0xC0220035u32 as i32; +pub const STATUS_FWP_TOO_MANY_SUBLAYERS: ::NTSTATUS = 0xC0220036u32 as i32; +pub const STATUS_FWP_CALLOUT_NOTIFICATION_FAILED: ::NTSTATUS = 0xC0220037u32 as i32; +pub const STATUS_FWP_INVALID_AUTH_TRANSFORM: ::NTSTATUS = 0xC0220038u32 as i32; +pub const STATUS_FWP_INVALID_CIPHER_TRANSFORM: ::NTSTATUS = 0xC0220039u32 as i32; +pub const STATUS_FWP_INCOMPATIBLE_CIPHER_TRANSFORM: ::NTSTATUS = 0xC022003Au32 as i32; +pub const STATUS_FWP_INVALID_TRANSFORM_COMBINATION: ::NTSTATUS = 0xC022003Bu32 as i32; +pub const STATUS_FWP_DUPLICATE_AUTH_METHOD: ::NTSTATUS = 0xC022003Cu32 as i32; +pub const STATUS_FWP_INVALID_TUNNEL_ENDPOINT: ::NTSTATUS = 0xC022003Du32 as i32; +pub const STATUS_FWP_L2_DRIVER_NOT_READY: ::NTSTATUS = 0xC022003Eu32 as i32; +pub const STATUS_FWP_KEY_DICTATOR_ALREADY_REGISTERED: ::NTSTATUS = 0xC022003Fu32 as i32; +pub const STATUS_FWP_KEY_DICTATION_INVALID_KEYING_MATERIAL: ::NTSTATUS = 0xC0220040u32 as i32; +pub const STATUS_FWP_CONNECTIONS_DISABLED: ::NTSTATUS = 0xC0220041u32 as i32; +pub const STATUS_FWP_INVALID_DNS_NAME: ::NTSTATUS = 0xC0220042u32 as i32; +pub const STATUS_FWP_STILL_ON: ::NTSTATUS = 0xC0220043u32 as i32; +pub const STATUS_FWP_IKEEXT_NOT_RUNNING: ::NTSTATUS = 0xC0220044u32 as i32; +pub const STATUS_FWP_TCPIP_NOT_READY: ::NTSTATUS = 0xC0220100u32 as i32; +pub const STATUS_FWP_INJECT_HANDLE_CLOSING: ::NTSTATUS = 0xC0220101u32 as i32; +pub const STATUS_FWP_INJECT_HANDLE_STALE: ::NTSTATUS = 0xC0220102u32 as i32; +pub const STATUS_FWP_CANNOT_PEND: ::NTSTATUS = 0xC0220103u32 as i32; +pub const STATUS_FWP_DROP_NOICMP: ::NTSTATUS = 0xC0220104u32 as i32; +pub const STATUS_NDIS_CLOSING: ::NTSTATUS = 0xC0230002u32 as i32; +pub const STATUS_NDIS_BAD_VERSION: ::NTSTATUS = 0xC0230004u32 as i32; +pub const STATUS_NDIS_BAD_CHARACTERISTICS: ::NTSTATUS = 0xC0230005u32 as i32; +pub const STATUS_NDIS_ADAPTER_NOT_FOUND: ::NTSTATUS = 0xC0230006u32 as i32; +pub const STATUS_NDIS_OPEN_FAILED: ::NTSTATUS = 0xC0230007u32 as i32; +pub const STATUS_NDIS_DEVICE_FAILED: ::NTSTATUS = 0xC0230008u32 as i32; +pub const STATUS_NDIS_MULTICAST_FULL: ::NTSTATUS = 0xC0230009u32 as i32; +pub const STATUS_NDIS_MULTICAST_EXISTS: ::NTSTATUS = 0xC023000Au32 as i32; +pub const STATUS_NDIS_MULTICAST_NOT_FOUND: ::NTSTATUS = 0xC023000Bu32 as i32; +pub const STATUS_NDIS_REQUEST_ABORTED: ::NTSTATUS = 0xC023000Cu32 as i32; +pub const STATUS_NDIS_RESET_IN_PROGRESS: ::NTSTATUS = 0xC023000Du32 as i32; +pub const STATUS_NDIS_NOT_SUPPORTED: ::NTSTATUS = 0xC02300BBu32 as i32; +pub const STATUS_NDIS_INVALID_PACKET: ::NTSTATUS = 0xC023000Fu32 as i32; +pub const STATUS_NDIS_ADAPTER_NOT_READY: ::NTSTATUS = 0xC0230011u32 as i32; +pub const STATUS_NDIS_INVALID_LENGTH: ::NTSTATUS = 0xC0230014u32 as i32; +pub const STATUS_NDIS_INVALID_DATA: ::NTSTATUS = 0xC0230015u32 as i32; +pub const STATUS_NDIS_BUFFER_TOO_SHORT: ::NTSTATUS = 0xC0230016u32 as i32; +pub const STATUS_NDIS_INVALID_OID: ::NTSTATUS = 0xC0230017u32 as i32; +pub const STATUS_NDIS_ADAPTER_REMOVED: ::NTSTATUS = 0xC0230018u32 as i32; +pub const STATUS_NDIS_UNSUPPORTED_MEDIA: ::NTSTATUS = 0xC0230019u32 as i32; +pub const STATUS_NDIS_GROUP_ADDRESS_IN_USE: ::NTSTATUS = 0xC023001Au32 as i32; +pub const STATUS_NDIS_FILE_NOT_FOUND: ::NTSTATUS = 0xC023001Bu32 as i32; +pub const STATUS_NDIS_ERROR_READING_FILE: ::NTSTATUS = 0xC023001Cu32 as i32; +pub const STATUS_NDIS_ALREADY_MAPPED: ::NTSTATUS = 0xC023001Du32 as i32; +pub const STATUS_NDIS_RESOURCE_CONFLICT: ::NTSTATUS = 0xC023001Eu32 as i32; +pub const STATUS_NDIS_MEDIA_DISCONNECTED: ::NTSTATUS = 0xC023001Fu32 as i32; +pub const STATUS_NDIS_INVALID_ADDRESS: ::NTSTATUS = 0xC0230022u32 as i32; +pub const STATUS_NDIS_INVALID_DEVICE_REQUEST: ::NTSTATUS = 0xC0230010u32 as i32; +pub const STATUS_NDIS_PAUSED: ::NTSTATUS = 0xC023002Au32 as i32; +pub const STATUS_NDIS_INTERFACE_NOT_FOUND: ::NTSTATUS = 0xC023002Bu32 as i32; +pub const STATUS_NDIS_UNSUPPORTED_REVISION: ::NTSTATUS = 0xC023002Cu32 as i32; +pub const STATUS_NDIS_INVALID_PORT: ::NTSTATUS = 0xC023002Du32 as i32; +pub const STATUS_NDIS_INVALID_PORT_STATE: ::NTSTATUS = 0xC023002Eu32 as i32; +pub const STATUS_NDIS_LOW_POWER_STATE: ::NTSTATUS = 0xC023002Fu32 as i32; +pub const STATUS_NDIS_REINIT_REQUIRED: ::NTSTATUS = 0xC0230030u32 as i32; +pub const STATUS_NDIS_DOT11_AUTO_CONFIG_ENABLED: ::NTSTATUS = 0xC0232000u32 as i32; +pub const STATUS_NDIS_DOT11_MEDIA_IN_USE: ::NTSTATUS = 0xC0232001u32 as i32; +pub const STATUS_NDIS_DOT11_POWER_STATE_INVALID: ::NTSTATUS = 0xC0232002u32 as i32; +pub const STATUS_NDIS_PM_WOL_PATTERN_LIST_FULL: ::NTSTATUS = 0xC0232003u32 as i32; +pub const STATUS_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: ::NTSTATUS = 0xC0232004u32 as i32; +pub const STATUS_NDIS_INDICATION_REQUIRED: ::NTSTATUS = 0x40230001; +pub const STATUS_NDIS_OFFLOAD_POLICY: ::NTSTATUS = 0xC023100Fu32 as i32; +pub const STATUS_NDIS_OFFLOAD_CONNECTION_REJECTED: ::NTSTATUS = 0xC0231012u32 as i32; +pub const STATUS_NDIS_OFFLOAD_PATH_REJECTED: ::NTSTATUS = 0xC0231013u32 as i32; +pub const STATUS_TPM_ERROR_MASK: ::NTSTATUS = 0xC0290000u32 as i32; +pub const STATUS_TPM_AUTHFAIL: ::NTSTATUS = 0xC0290001u32 as i32; +pub const STATUS_TPM_BADINDEX: ::NTSTATUS = 0xC0290002u32 as i32; +pub const STATUS_TPM_BAD_PARAMETER: ::NTSTATUS = 0xC0290003u32 as i32; +pub const STATUS_TPM_AUDITFAILURE: ::NTSTATUS = 0xC0290004u32 as i32; +pub const STATUS_TPM_CLEAR_DISABLED: ::NTSTATUS = 0xC0290005u32 as i32; +pub const STATUS_TPM_DEACTIVATED: ::NTSTATUS = 0xC0290006u32 as i32; +pub const STATUS_TPM_DISABLED: ::NTSTATUS = 0xC0290007u32 as i32; +pub const STATUS_TPM_DISABLED_CMD: ::NTSTATUS = 0xC0290008u32 as i32; +pub const STATUS_TPM_FAIL: ::NTSTATUS = 0xC0290009u32 as i32; +pub const STATUS_TPM_BAD_ORDINAL: ::NTSTATUS = 0xC029000Au32 as i32; +pub const STATUS_TPM_INSTALL_DISABLED: ::NTSTATUS = 0xC029000Bu32 as i32; +pub const STATUS_TPM_INVALID_KEYHANDLE: ::NTSTATUS = 0xC029000Cu32 as i32; +pub const STATUS_TPM_KEYNOTFOUND: ::NTSTATUS = 0xC029000Du32 as i32; +pub const STATUS_TPM_INAPPROPRIATE_ENC: ::NTSTATUS = 0xC029000Eu32 as i32; +pub const STATUS_TPM_MIGRATEFAIL: ::NTSTATUS = 0xC029000Fu32 as i32; +pub const STATUS_TPM_INVALID_PCR_INFO: ::NTSTATUS = 0xC0290010u32 as i32; +pub const STATUS_TPM_NOSPACE: ::NTSTATUS = 0xC0290011u32 as i32; +pub const STATUS_TPM_NOSRK: ::NTSTATUS = 0xC0290012u32 as i32; +pub const STATUS_TPM_NOTSEALED_BLOB: ::NTSTATUS = 0xC0290013u32 as i32; +pub const STATUS_TPM_OWNER_SET: ::NTSTATUS = 0xC0290014u32 as i32; +pub const STATUS_TPM_RESOURCES: ::NTSTATUS = 0xC0290015u32 as i32; +pub const STATUS_TPM_SHORTRANDOM: ::NTSTATUS = 0xC0290016u32 as i32; +pub const STATUS_TPM_SIZE: ::NTSTATUS = 0xC0290017u32 as i32; +pub const STATUS_TPM_WRONGPCRVAL: ::NTSTATUS = 0xC0290018u32 as i32; +pub const STATUS_TPM_BAD_PARAM_SIZE: ::NTSTATUS = 0xC0290019u32 as i32; +pub const STATUS_TPM_SHA_THREAD: ::NTSTATUS = 0xC029001Au32 as i32; +pub const STATUS_TPM_SHA_ERROR: ::NTSTATUS = 0xC029001Bu32 as i32; +pub const STATUS_TPM_FAILEDSELFTEST: ::NTSTATUS = 0xC029001Cu32 as i32; +pub const STATUS_TPM_AUTH2FAIL: ::NTSTATUS = 0xC029001Du32 as i32; +pub const STATUS_TPM_BADTAG: ::NTSTATUS = 0xC029001Eu32 as i32; +pub const STATUS_TPM_IOERROR: ::NTSTATUS = 0xC029001Fu32 as i32; +pub const STATUS_TPM_ENCRYPT_ERROR: ::NTSTATUS = 0xC0290020u32 as i32; +pub const STATUS_TPM_DECRYPT_ERROR: ::NTSTATUS = 0xC0290021u32 as i32; +pub const STATUS_TPM_INVALID_AUTHHANDLE: ::NTSTATUS = 0xC0290022u32 as i32; +pub const STATUS_TPM_NO_ENDORSEMENT: ::NTSTATUS = 0xC0290023u32 as i32; +pub const STATUS_TPM_INVALID_KEYUSAGE: ::NTSTATUS = 0xC0290024u32 as i32; +pub const STATUS_TPM_WRONG_ENTITYTYPE: ::NTSTATUS = 0xC0290025u32 as i32; +pub const STATUS_TPM_INVALID_POSTINIT: ::NTSTATUS = 0xC0290026u32 as i32; +pub const STATUS_TPM_INAPPROPRIATE_SIG: ::NTSTATUS = 0xC0290027u32 as i32; +pub const STATUS_TPM_BAD_KEY_PROPERTY: ::NTSTATUS = 0xC0290028u32 as i32; +pub const STATUS_TPM_BAD_MIGRATION: ::NTSTATUS = 0xC0290029u32 as i32; +pub const STATUS_TPM_BAD_SCHEME: ::NTSTATUS = 0xC029002Au32 as i32; +pub const STATUS_TPM_BAD_DATASIZE: ::NTSTATUS = 0xC029002Bu32 as i32; +pub const STATUS_TPM_BAD_MODE: ::NTSTATUS = 0xC029002Cu32 as i32; +pub const STATUS_TPM_BAD_PRESENCE: ::NTSTATUS = 0xC029002Du32 as i32; +pub const STATUS_TPM_BAD_VERSION: ::NTSTATUS = 0xC029002Eu32 as i32; +pub const STATUS_TPM_NO_WRAP_TRANSPORT: ::NTSTATUS = 0xC029002Fu32 as i32; +pub const STATUS_TPM_AUDITFAIL_UNSUCCESSFUL: ::NTSTATUS = 0xC0290030u32 as i32; +pub const STATUS_TPM_AUDITFAIL_SUCCESSFUL: ::NTSTATUS = 0xC0290031u32 as i32; +pub const STATUS_TPM_NOTRESETABLE: ::NTSTATUS = 0xC0290032u32 as i32; +pub const STATUS_TPM_NOTLOCAL: ::NTSTATUS = 0xC0290033u32 as i32; +pub const STATUS_TPM_BAD_TYPE: ::NTSTATUS = 0xC0290034u32 as i32; +pub const STATUS_TPM_INVALID_RESOURCE: ::NTSTATUS = 0xC0290035u32 as i32; +pub const STATUS_TPM_NOTFIPS: ::NTSTATUS = 0xC0290036u32 as i32; +pub const STATUS_TPM_INVALID_FAMILY: ::NTSTATUS = 0xC0290037u32 as i32; +pub const STATUS_TPM_NO_NV_PERMISSION: ::NTSTATUS = 0xC0290038u32 as i32; +pub const STATUS_TPM_REQUIRES_SIGN: ::NTSTATUS = 0xC0290039u32 as i32; +pub const STATUS_TPM_KEY_NOTSUPPORTED: ::NTSTATUS = 0xC029003Au32 as i32; +pub const STATUS_TPM_AUTH_CONFLICT: ::NTSTATUS = 0xC029003Bu32 as i32; +pub const STATUS_TPM_AREA_LOCKED: ::NTSTATUS = 0xC029003Cu32 as i32; +pub const STATUS_TPM_BAD_LOCALITY: ::NTSTATUS = 0xC029003Du32 as i32; +pub const STATUS_TPM_READ_ONLY: ::NTSTATUS = 0xC029003Eu32 as i32; +pub const STATUS_TPM_PER_NOWRITE: ::NTSTATUS = 0xC029003Fu32 as i32; +pub const STATUS_TPM_FAMILYCOUNT: ::NTSTATUS = 0xC0290040u32 as i32; +pub const STATUS_TPM_WRITE_LOCKED: ::NTSTATUS = 0xC0290041u32 as i32; +pub const STATUS_TPM_BAD_ATTRIBUTES: ::NTSTATUS = 0xC0290042u32 as i32; +pub const STATUS_TPM_INVALID_STRUCTURE: ::NTSTATUS = 0xC0290043u32 as i32; +pub const STATUS_TPM_KEY_OWNER_CONTROL: ::NTSTATUS = 0xC0290044u32 as i32; +pub const STATUS_TPM_BAD_COUNTER: ::NTSTATUS = 0xC0290045u32 as i32; +pub const STATUS_TPM_NOT_FULLWRITE: ::NTSTATUS = 0xC0290046u32 as i32; +pub const STATUS_TPM_CONTEXT_GAP: ::NTSTATUS = 0xC0290047u32 as i32; +pub const STATUS_TPM_MAXNVWRITES: ::NTSTATUS = 0xC0290048u32 as i32; +pub const STATUS_TPM_NOOPERATOR: ::NTSTATUS = 0xC0290049u32 as i32; +pub const STATUS_TPM_RESOURCEMISSING: ::NTSTATUS = 0xC029004Au32 as i32; +pub const STATUS_TPM_DELEGATE_LOCK: ::NTSTATUS = 0xC029004Bu32 as i32; +pub const STATUS_TPM_DELEGATE_FAMILY: ::NTSTATUS = 0xC029004Cu32 as i32; +pub const STATUS_TPM_DELEGATE_ADMIN: ::NTSTATUS = 0xC029004Du32 as i32; +pub const STATUS_TPM_TRANSPORT_NOTEXCLUSIVE: ::NTSTATUS = 0xC029004Eu32 as i32; +pub const STATUS_TPM_OWNER_CONTROL: ::NTSTATUS = 0xC029004Fu32 as i32; +pub const STATUS_TPM_DAA_RESOURCES: ::NTSTATUS = 0xC0290050u32 as i32; +pub const STATUS_TPM_DAA_INPUT_DATA0: ::NTSTATUS = 0xC0290051u32 as i32; +pub const STATUS_TPM_DAA_INPUT_DATA1: ::NTSTATUS = 0xC0290052u32 as i32; +pub const STATUS_TPM_DAA_ISSUER_SETTINGS: ::NTSTATUS = 0xC0290053u32 as i32; +pub const STATUS_TPM_DAA_TPM_SETTINGS: ::NTSTATUS = 0xC0290054u32 as i32; +pub const STATUS_TPM_DAA_STAGE: ::NTSTATUS = 0xC0290055u32 as i32; +pub const STATUS_TPM_DAA_ISSUER_VALIDITY: ::NTSTATUS = 0xC0290056u32 as i32; +pub const STATUS_TPM_DAA_WRONG_W: ::NTSTATUS = 0xC0290057u32 as i32; +pub const STATUS_TPM_BAD_HANDLE: ::NTSTATUS = 0xC0290058u32 as i32; +pub const STATUS_TPM_BAD_DELEGATE: ::NTSTATUS = 0xC0290059u32 as i32; +pub const STATUS_TPM_BADCONTEXT: ::NTSTATUS = 0xC029005Au32 as i32; +pub const STATUS_TPM_TOOMANYCONTEXTS: ::NTSTATUS = 0xC029005Bu32 as i32; +pub const STATUS_TPM_MA_TICKET_SIGNATURE: ::NTSTATUS = 0xC029005Cu32 as i32; +pub const STATUS_TPM_MA_DESTINATION: ::NTSTATUS = 0xC029005Du32 as i32; +pub const STATUS_TPM_MA_SOURCE: ::NTSTATUS = 0xC029005Eu32 as i32; +pub const STATUS_TPM_MA_AUTHORITY: ::NTSTATUS = 0xC029005Fu32 as i32; +pub const STATUS_TPM_PERMANENTEK: ::NTSTATUS = 0xC0290061u32 as i32; +pub const STATUS_TPM_BAD_SIGNATURE: ::NTSTATUS = 0xC0290062u32 as i32; +pub const STATUS_TPM_NOCONTEXTSPACE: ::NTSTATUS = 0xC0290063u32 as i32; +pub const STATUS_TPM_COMMAND_BLOCKED: ::NTSTATUS = 0xC0290400u32 as i32; +pub const STATUS_TPM_INVALID_HANDLE: ::NTSTATUS = 0xC0290401u32 as i32; +pub const STATUS_TPM_DUPLICATE_VHANDLE: ::NTSTATUS = 0xC0290402u32 as i32; +pub const STATUS_TPM_EMBEDDED_COMMAND_BLOCKED: ::NTSTATUS = 0xC0290403u32 as i32; +pub const STATUS_TPM_EMBEDDED_COMMAND_UNSUPPORTED: ::NTSTATUS = 0xC0290404u32 as i32; +pub const STATUS_TPM_RETRY: ::NTSTATUS = 0xC0290800u32 as i32; +pub const STATUS_TPM_NEEDS_SELFTEST: ::NTSTATUS = 0xC0290801u32 as i32; +pub const STATUS_TPM_DOING_SELFTEST: ::NTSTATUS = 0xC0290802u32 as i32; +pub const STATUS_TPM_DEFEND_LOCK_RUNNING: ::NTSTATUS = 0xC0290803u32 as i32; +pub const STATUS_TPM_COMMAND_CANCELED: ::NTSTATUS = 0xC0291001u32 as i32; +pub const STATUS_TPM_TOO_MANY_CONTEXTS: ::NTSTATUS = 0xC0291002u32 as i32; +pub const STATUS_TPM_NOT_FOUND: ::NTSTATUS = 0xC0291003u32 as i32; +pub const STATUS_TPM_ACCESS_DENIED: ::NTSTATUS = 0xC0291004u32 as i32; +pub const STATUS_TPM_INSUFFICIENT_BUFFER: ::NTSTATUS = 0xC0291005u32 as i32; +pub const STATUS_TPM_PPI_FUNCTION_UNSUPPORTED: ::NTSTATUS = 0xC0291006u32 as i32; +pub const STATUS_PCP_ERROR_MASK: ::NTSTATUS = 0xC0292000u32 as i32; +pub const STATUS_PCP_DEVICE_NOT_READY: ::NTSTATUS = 0xC0292001u32 as i32; +pub const STATUS_PCP_INVALID_HANDLE: ::NTSTATUS = 0xC0292002u32 as i32; +pub const STATUS_PCP_INVALID_PARAMETER: ::NTSTATUS = 0xC0292003u32 as i32; +pub const STATUS_PCP_FLAG_NOT_SUPPORTED: ::NTSTATUS = 0xC0292004u32 as i32; +pub const STATUS_PCP_NOT_SUPPORTED: ::NTSTATUS = 0xC0292005u32 as i32; +pub const STATUS_PCP_BUFFER_TOO_SMALL: ::NTSTATUS = 0xC0292006u32 as i32; +pub const STATUS_PCP_INTERNAL_ERROR: ::NTSTATUS = 0xC0292007u32 as i32; +pub const STATUS_PCP_AUTHENTICATION_FAILED: ::NTSTATUS = 0xC0292008u32 as i32; +pub const STATUS_PCP_AUTHENTICATION_IGNORED: ::NTSTATUS = 0xC0292009u32 as i32; +pub const STATUS_PCP_POLICY_NOT_FOUND: ::NTSTATUS = 0xC029200Au32 as i32; +pub const STATUS_PCP_PROFILE_NOT_FOUND: ::NTSTATUS = 0xC029200Bu32 as i32; +pub const STATUS_PCP_VALIDATION_FAILED: ::NTSTATUS = 0xC029200Cu32 as i32; +pub const STATUS_PCP_DEVICE_NOT_FOUND: ::NTSTATUS = 0xC029200Du32 as i32; +pub const STATUS_RTPM_CONTEXT_CONTINUE: ::NTSTATUS = 0x00293000; +pub const STATUS_RTPM_CONTEXT_COMPLETE: ::NTSTATUS = 0x00293001; +pub const STATUS_RTPM_NO_RESULT: ::NTSTATUS = 0xC0293002u32 as i32; +pub const STATUS_RTPM_PCR_READ_INCOMPLETE: ::NTSTATUS = 0xC0293003u32 as i32; +pub const STATUS_RTPM_INVALID_CONTEXT: ::NTSTATUS = 0xC0293004u32 as i32; +pub const STATUS_RTPM_UNSUPPORTED_CMD: ::NTSTATUS = 0xC0293005u32 as i32; +pub const STATUS_HV_INVALID_HYPERCALL_CODE: ::NTSTATUS = 0xC0350002u32 as i32; +pub const STATUS_HV_INVALID_HYPERCALL_INPUT: ::NTSTATUS = 0xC0350003u32 as i32; +pub const STATUS_HV_INVALID_ALIGNMENT: ::NTSTATUS = 0xC0350004u32 as i32; +pub const STATUS_HV_INVALID_PARAMETER: ::NTSTATUS = 0xC0350005u32 as i32; +pub const STATUS_HV_ACCESS_DENIED: ::NTSTATUS = 0xC0350006u32 as i32; +pub const STATUS_HV_INVALID_PARTITION_STATE: ::NTSTATUS = 0xC0350007u32 as i32; +pub const STATUS_HV_OPERATION_DENIED: ::NTSTATUS = 0xC0350008u32 as i32; +pub const STATUS_HV_UNKNOWN_PROPERTY: ::NTSTATUS = 0xC0350009u32 as i32; +pub const STATUS_HV_PROPERTY_VALUE_OUT_OF_RANGE: ::NTSTATUS = 0xC035000Au32 as i32; +pub const STATUS_HV_INSUFFICIENT_MEMORY: ::NTSTATUS = 0xC035000Bu32 as i32; +pub const STATUS_HV_PARTITION_TOO_DEEP: ::NTSTATUS = 0xC035000Cu32 as i32; +pub const STATUS_HV_INVALID_PARTITION_ID: ::NTSTATUS = 0xC035000Du32 as i32; +pub const STATUS_HV_INVALID_VP_INDEX: ::NTSTATUS = 0xC035000Eu32 as i32; +pub const STATUS_HV_INVALID_PORT_ID: ::NTSTATUS = 0xC0350011u32 as i32; +pub const STATUS_HV_INVALID_CONNECTION_ID: ::NTSTATUS = 0xC0350012u32 as i32; +pub const STATUS_HV_INSUFFICIENT_BUFFERS: ::NTSTATUS = 0xC0350013u32 as i32; +pub const STATUS_HV_NOT_ACKNOWLEDGED: ::NTSTATUS = 0xC0350014u32 as i32; +pub const STATUS_HV_ACKNOWLEDGED: ::NTSTATUS = 0xC0350016u32 as i32; +pub const STATUS_HV_INVALID_SAVE_RESTORE_STATE: ::NTSTATUS = 0xC0350017u32 as i32; +pub const STATUS_HV_INVALID_SYNIC_STATE: ::NTSTATUS = 0xC0350018u32 as i32; +pub const STATUS_HV_OBJECT_IN_USE: ::NTSTATUS = 0xC0350019u32 as i32; +pub const STATUS_HV_INVALID_PROXIMITY_DOMAIN_INFO: ::NTSTATUS = 0xC035001Au32 as i32; +pub const STATUS_HV_NO_DATA: ::NTSTATUS = 0xC035001Bu32 as i32; +pub const STATUS_HV_INACTIVE: ::NTSTATUS = 0xC035001Cu32 as i32; +pub const STATUS_HV_NO_RESOURCES: ::NTSTATUS = 0xC035001Du32 as i32; +pub const STATUS_HV_FEATURE_UNAVAILABLE: ::NTSTATUS = 0xC035001Eu32 as i32; +pub const STATUS_HV_INSUFFICIENT_BUFFER: ::NTSTATUS = 0xC0350033u32 as i32; +pub const STATUS_HV_INSUFFICIENT_DEVICE_DOMAINS: ::NTSTATUS = 0xC0350038u32 as i32; +pub const STATUS_HV_CPUID_FEATURE_VALIDATION_ERROR: ::NTSTATUS = 0xC035003Cu32 as i32; +pub const STATUS_HV_CPUID_XSAVE_FEATURE_VALIDATION_ERROR: ::NTSTATUS = 0xC035003Du32 as i32; +pub const STATUS_HV_PROCESSOR_STARTUP_TIMEOUT: ::NTSTATUS = 0xC035003Eu32 as i32; +pub const STATUS_HV_SMX_ENABLED: ::NTSTATUS = 0xC035003Fu32 as i32; +pub const STATUS_HV_INVALID_LP_INDEX: ::NTSTATUS = 0xC0350041u32 as i32; +pub const STATUS_HV_INVALID_REGISTER_VALUE: ::NTSTATUS = 0xC0350050u32 as i32; +pub const STATUS_HV_INVALID_VTL_STATE: ::NTSTATUS = 0xC0350051u32 as i32; +pub const STATUS_HV_NX_NOT_DETECTED: ::NTSTATUS = 0xC0350055u32 as i32; +pub const STATUS_HV_INVALID_DEVICE_ID: ::NTSTATUS = 0xC0350057u32 as i32; +pub const STATUS_HV_INVALID_DEVICE_STATE: ::NTSTATUS = 0xC0350058u32 as i32; +pub const STATUS_HV_PENDING_PAGE_REQUESTS: ::NTSTATUS = 0x00350059; +pub const STATUS_HV_PAGE_REQUEST_INVALID: ::NTSTATUS = 0xC0350060u32 as i32; +pub const STATUS_HV_NOT_PRESENT: ::NTSTATUS = 0xC0351000u32 as i32; +pub const STATUS_VID_DUPLICATE_HANDLER: ::NTSTATUS = 0xC0370001u32 as i32; +pub const STATUS_VID_TOO_MANY_HANDLERS: ::NTSTATUS = 0xC0370002u32 as i32; +pub const STATUS_VID_QUEUE_FULL: ::NTSTATUS = 0xC0370003u32 as i32; +pub const STATUS_VID_HANDLER_NOT_PRESENT: ::NTSTATUS = 0xC0370004u32 as i32; +pub const STATUS_VID_INVALID_OBJECT_NAME: ::NTSTATUS = 0xC0370005u32 as i32; +pub const STATUS_VID_PARTITION_NAME_TOO_LONG: ::NTSTATUS = 0xC0370006u32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_NAME_TOO_LONG: ::NTSTATUS = 0xC0370007u32 as i32; +pub const STATUS_VID_PARTITION_ALREADY_EXISTS: ::NTSTATUS = 0xC0370008u32 as i32; +pub const STATUS_VID_PARTITION_DOES_NOT_EXIST: ::NTSTATUS = 0xC0370009u32 as i32; +pub const STATUS_VID_PARTITION_NAME_NOT_FOUND: ::NTSTATUS = 0xC037000Au32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_ALREADY_EXISTS: ::NTSTATUS = 0xC037000Bu32 as i32; +pub const STATUS_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: ::NTSTATUS = 0xC037000Cu32 as i32; +pub const STATUS_VID_MB_STILL_REFERENCED: ::NTSTATUS = 0xC037000Du32 as i32; +pub const STATUS_VID_CHILD_GPA_PAGE_SET_CORRUPTED: ::NTSTATUS = 0xC037000Eu32 as i32; +pub const STATUS_VID_INVALID_NUMA_SETTINGS: ::NTSTATUS = 0xC037000Fu32 as i32; +pub const STATUS_VID_INVALID_NUMA_NODE_INDEX: ::NTSTATUS = 0xC0370010u32 as i32; +pub const STATUS_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: ::NTSTATUS = 0xC0370011u32 as i32; +pub const STATUS_VID_INVALID_MEMORY_BLOCK_HANDLE: ::NTSTATUS = 0xC0370012u32 as i32; +pub const STATUS_VID_PAGE_RANGE_OVERFLOW: ::NTSTATUS = 0xC0370013u32 as i32; +pub const STATUS_VID_INVALID_MESSAGE_QUEUE_HANDLE: ::NTSTATUS = 0xC0370014u32 as i32; +pub const STATUS_VID_INVALID_GPA_RANGE_HANDLE: ::NTSTATUS = 0xC0370015u32 as i32; +pub const STATUS_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: ::NTSTATUS = 0xC0370016u32 as i32; +pub const STATUS_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: ::NTSTATUS = 0xC0370017u32 as i32; +pub const STATUS_VID_INVALID_PPM_HANDLE: ::NTSTATUS = 0xC0370018u32 as i32; +pub const STATUS_VID_MBPS_ARE_LOCKED: ::NTSTATUS = 0xC0370019u32 as i32; +pub const STATUS_VID_MESSAGE_QUEUE_CLOSED: ::NTSTATUS = 0xC037001Au32 as i32; +pub const STATUS_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: ::NTSTATUS = 0xC037001Bu32 as i32; +pub const STATUS_VID_STOP_PENDING: ::NTSTATUS = 0xC037001Cu32 as i32; +pub const STATUS_VID_INVALID_PROCESSOR_STATE: ::NTSTATUS = 0xC037001Du32 as i32; +pub const STATUS_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: ::NTSTATUS = 0xC037001Eu32 as i32; +pub const STATUS_VID_KM_INTERFACE_ALREADY_INITIALIZED: ::NTSTATUS = 0xC037001Fu32 as i32; +pub const STATUS_VID_MB_PROPERTY_ALREADY_SET_RESET: ::NTSTATUS = 0xC0370020u32 as i32; +pub const STATUS_VID_MMIO_RANGE_DESTROYED: ::NTSTATUS = 0xC0370021u32 as i32; +pub const STATUS_VID_INVALID_CHILD_GPA_PAGE_SET: ::NTSTATUS = 0xC0370022u32 as i32; +pub const STATUS_VID_RESERVE_PAGE_SET_IS_BEING_USED: ::NTSTATUS = 0xC0370023u32 as i32; +pub const STATUS_VID_RESERVE_PAGE_SET_TOO_SMALL: ::NTSTATUS = 0xC0370024u32 as i32; +pub const STATUS_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: ::NTSTATUS = 0xC0370025u32 as i32; +pub const STATUS_VID_MBP_COUNT_EXCEEDED_LIMIT: ::NTSTATUS = 0xC0370026u32 as i32; +pub const STATUS_VID_SAVED_STATE_CORRUPT: ::NTSTATUS = 0xC0370027u32 as i32; +pub const STATUS_VID_SAVED_STATE_UNRECOGNIZED_ITEM: ::NTSTATUS = 0xC0370028u32 as i32; +pub const STATUS_VID_SAVED_STATE_INCOMPATIBLE: ::NTSTATUS = 0xC0370029u32 as i32; +pub const STATUS_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: ::NTSTATUS = 0x80370001u32 as i32; +pub const STATUS_IPSEC_BAD_SPI: ::NTSTATUS = 0xC0360001u32 as i32; +pub const STATUS_IPSEC_SA_LIFETIME_EXPIRED: ::NTSTATUS = 0xC0360002u32 as i32; +pub const STATUS_IPSEC_WRONG_SA: ::NTSTATUS = 0xC0360003u32 as i32; +pub const STATUS_IPSEC_REPLAY_CHECK_FAILED: ::NTSTATUS = 0xC0360004u32 as i32; +pub const STATUS_IPSEC_INVALID_PACKET: ::NTSTATUS = 0xC0360005u32 as i32; +pub const STATUS_IPSEC_INTEGRITY_CHECK_FAILED: ::NTSTATUS = 0xC0360006u32 as i32; +pub const STATUS_IPSEC_CLEAR_TEXT_DROP: ::NTSTATUS = 0xC0360007u32 as i32; +pub const STATUS_IPSEC_AUTH_FIREWALL_DROP: ::NTSTATUS = 0xC0360008u32 as i32; +pub const STATUS_IPSEC_THROTTLE_DROP: ::NTSTATUS = 0xC0360009u32 as i32; +pub const STATUS_IPSEC_DOSP_BLOCK: ::NTSTATUS = 0xC0368000u32 as i32; +pub const STATUS_IPSEC_DOSP_RECEIVED_MULTICAST: ::NTSTATUS = 0xC0368001u32 as i32; +pub const STATUS_IPSEC_DOSP_INVALID_PACKET: ::NTSTATUS = 0xC0368002u32 as i32; +pub const STATUS_IPSEC_DOSP_STATE_LOOKUP_FAILED: ::NTSTATUS = 0xC0368003u32 as i32; +pub const STATUS_IPSEC_DOSP_MAX_ENTRIES: ::NTSTATUS = 0xC0368004u32 as i32; +pub const STATUS_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: ::NTSTATUS = 0xC0368005u32 as i32; +pub const STATUS_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: ::NTSTATUS = 0xC0368006u32 as i32; +pub const STATUS_VOLMGR_INCOMPLETE_REGENERATION: ::NTSTATUS = 0x80380001u32 as i32; +pub const STATUS_VOLMGR_INCOMPLETE_DISK_MIGRATION: ::NTSTATUS = 0x80380002u32 as i32; +pub const STATUS_VOLMGR_DATABASE_FULL: ::NTSTATUS = 0xC0380001u32 as i32; +pub const STATUS_VOLMGR_DISK_CONFIGURATION_CORRUPTED: ::NTSTATUS = 0xC0380002u32 as i32; +pub const STATUS_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: ::NTSTATUS = 0xC0380003u32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_UPDATE_FAILED: ::NTSTATUS = 0xC0380004u32 as i32; +pub const STATUS_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: ::NTSTATUS = 0xC0380005u32 as i32; +pub const STATUS_VOLMGR_DISK_DUPLICATE: ::NTSTATUS = 0xC0380006u32 as i32; +pub const STATUS_VOLMGR_DISK_DYNAMIC: ::NTSTATUS = 0xC0380007u32 as i32; +pub const STATUS_VOLMGR_DISK_ID_INVALID: ::NTSTATUS = 0xC0380008u32 as i32; +pub const STATUS_VOLMGR_DISK_INVALID: ::NTSTATUS = 0xC0380009u32 as i32; +pub const STATUS_VOLMGR_DISK_LAST_VOTER: ::NTSTATUS = 0xC038000Au32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_INVALID: ::NTSTATUS = 0xC038000Bu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: ::NTSTATUS = 0xC038000Cu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: ::NTSTATUS = 0xC038000Du32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: ::NTSTATUS = 0xC038000Eu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: ::NTSTATUS = 0xC038000Fu32 as i32; +pub const STATUS_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: ::NTSTATUS = 0xC0380010u32 as i32; +pub const STATUS_VOLMGR_DISK_MISSING: ::NTSTATUS = 0xC0380011u32 as i32; +pub const STATUS_VOLMGR_DISK_NOT_EMPTY: ::NTSTATUS = 0xC0380012u32 as i32; +pub const STATUS_VOLMGR_DISK_NOT_ENOUGH_SPACE: ::NTSTATUS = 0xC0380013u32 as i32; +pub const STATUS_VOLMGR_DISK_REVECTORING_FAILED: ::NTSTATUS = 0xC0380014u32 as i32; +pub const STATUS_VOLMGR_DISK_SECTOR_SIZE_INVALID: ::NTSTATUS = 0xC0380015u32 as i32; +pub const STATUS_VOLMGR_DISK_SET_NOT_CONTAINED: ::NTSTATUS = 0xC0380016u32 as i32; +pub const STATUS_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: ::NTSTATUS = 0xC0380017u32 as i32; +pub const STATUS_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: ::NTSTATUS = 0xC0380018u32 as i32; +pub const STATUS_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: ::NTSTATUS = 0xC0380019u32 as i32; +pub const STATUS_VOLMGR_EXTENT_ALREADY_USED: ::NTSTATUS = 0xC038001Au32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_CONTIGUOUS: ::NTSTATUS = 0xC038001Bu32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: ::NTSTATUS = 0xC038001Cu32 as i32; +pub const STATUS_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: ::NTSTATUS = 0xC038001Du32 as i32; +pub const STATUS_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: ::NTSTATUS = 0xC038001Eu32 as i32; +pub const STATUS_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: ::NTSTATUS = 0xC038001Fu32 as i32; +pub const STATUS_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: ::NTSTATUS = 0xC0380020u32 as i32; +pub const STATUS_VOLMGR_INTERLEAVE_LENGTH_INVALID: ::NTSTATUS = 0xC0380021u32 as i32; +pub const STATUS_VOLMGR_MAXIMUM_REGISTERED_USERS: ::NTSTATUS = 0xC0380022u32 as i32; +pub const STATUS_VOLMGR_MEMBER_IN_SYNC: ::NTSTATUS = 0xC0380023u32 as i32; +pub const STATUS_VOLMGR_MEMBER_INDEX_DUPLICATE: ::NTSTATUS = 0xC0380024u32 as i32; +pub const STATUS_VOLMGR_MEMBER_INDEX_INVALID: ::NTSTATUS = 0xC0380025u32 as i32; +pub const STATUS_VOLMGR_MEMBER_MISSING: ::NTSTATUS = 0xC0380026u32 as i32; +pub const STATUS_VOLMGR_MEMBER_NOT_DETACHED: ::NTSTATUS = 0xC0380027u32 as i32; +pub const STATUS_VOLMGR_MEMBER_REGENERATING: ::NTSTATUS = 0xC0380028u32 as i32; +pub const STATUS_VOLMGR_ALL_DISKS_FAILED: ::NTSTATUS = 0xC0380029u32 as i32; +pub const STATUS_VOLMGR_NO_REGISTERED_USERS: ::NTSTATUS = 0xC038002Au32 as i32; +pub const STATUS_VOLMGR_NO_SUCH_USER: ::NTSTATUS = 0xC038002Bu32 as i32; +pub const STATUS_VOLMGR_NOTIFICATION_RESET: ::NTSTATUS = 0xC038002Cu32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_MEMBERS_INVALID: ::NTSTATUS = 0xC038002Du32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_PLEXES_INVALID: ::NTSTATUS = 0xC038002Eu32 as i32; +pub const STATUS_VOLMGR_PACK_DUPLICATE: ::NTSTATUS = 0xC038002Fu32 as i32; +pub const STATUS_VOLMGR_PACK_ID_INVALID: ::NTSTATUS = 0xC0380030u32 as i32; +pub const STATUS_VOLMGR_PACK_INVALID: ::NTSTATUS = 0xC0380031u32 as i32; +pub const STATUS_VOLMGR_PACK_NAME_INVALID: ::NTSTATUS = 0xC0380032u32 as i32; +pub const STATUS_VOLMGR_PACK_OFFLINE: ::NTSTATUS = 0xC0380033u32 as i32; +pub const STATUS_VOLMGR_PACK_HAS_QUORUM: ::NTSTATUS = 0xC0380034u32 as i32; +pub const STATUS_VOLMGR_PACK_WITHOUT_QUORUM: ::NTSTATUS = 0xC0380035u32 as i32; +pub const STATUS_VOLMGR_PARTITION_STYLE_INVALID: ::NTSTATUS = 0xC0380036u32 as i32; +pub const STATUS_VOLMGR_PARTITION_UPDATE_FAILED: ::NTSTATUS = 0xC0380037u32 as i32; +pub const STATUS_VOLMGR_PLEX_IN_SYNC: ::NTSTATUS = 0xC0380038u32 as i32; +pub const STATUS_VOLMGR_PLEX_INDEX_DUPLICATE: ::NTSTATUS = 0xC0380039u32 as i32; +pub const STATUS_VOLMGR_PLEX_INDEX_INVALID: ::NTSTATUS = 0xC038003Au32 as i32; +pub const STATUS_VOLMGR_PLEX_LAST_ACTIVE: ::NTSTATUS = 0xC038003Bu32 as i32; +pub const STATUS_VOLMGR_PLEX_MISSING: ::NTSTATUS = 0xC038003Cu32 as i32; +pub const STATUS_VOLMGR_PLEX_REGENERATING: ::NTSTATUS = 0xC038003Du32 as i32; +pub const STATUS_VOLMGR_PLEX_TYPE_INVALID: ::NTSTATUS = 0xC038003Eu32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_RAID5: ::NTSTATUS = 0xC038003Fu32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_SIMPLE: ::NTSTATUS = 0xC0380040u32 as i32; +pub const STATUS_VOLMGR_STRUCTURE_SIZE_INVALID: ::NTSTATUS = 0xC0380041u32 as i32; +pub const STATUS_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: ::NTSTATUS = 0xC0380042u32 as i32; +pub const STATUS_VOLMGR_TRANSACTION_IN_PROGRESS: ::NTSTATUS = 0xC0380043u32 as i32; +pub const STATUS_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: ::NTSTATUS = 0xC0380044u32 as i32; +pub const STATUS_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: ::NTSTATUS = 0xC0380045u32 as i32; +pub const STATUS_VOLMGR_VOLUME_ID_INVALID: ::NTSTATUS = 0xC0380046u32 as i32; +pub const STATUS_VOLMGR_VOLUME_LENGTH_INVALID: ::NTSTATUS = 0xC0380047u32 as i32; +pub const STATUS_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: ::NTSTATUS = 0xC0380048u32 as i32; +pub const STATUS_VOLMGR_VOLUME_NOT_MIRRORED: ::NTSTATUS = 0xC0380049u32 as i32; +pub const STATUS_VOLMGR_VOLUME_NOT_RETAINED: ::NTSTATUS = 0xC038004Au32 as i32; +pub const STATUS_VOLMGR_VOLUME_OFFLINE: ::NTSTATUS = 0xC038004Bu32 as i32; +pub const STATUS_VOLMGR_VOLUME_RETAINED: ::NTSTATUS = 0xC038004Cu32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_EXTENTS_INVALID: ::NTSTATUS = 0xC038004Du32 as i32; +pub const STATUS_VOLMGR_DIFFERENT_SECTOR_SIZE: ::NTSTATUS = 0xC038004Eu32 as i32; +pub const STATUS_VOLMGR_BAD_BOOT_DISK: ::NTSTATUS = 0xC038004Fu32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_OFFLINE: ::NTSTATUS = 0xC0380050u32 as i32; +pub const STATUS_VOLMGR_PACK_CONFIG_ONLINE: ::NTSTATUS = 0xC0380051u32 as i32; +pub const STATUS_VOLMGR_NOT_PRIMARY_PACK: ::NTSTATUS = 0xC0380052u32 as i32; +pub const STATUS_VOLMGR_PACK_LOG_UPDATE_FAILED: ::NTSTATUS = 0xC0380053u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: ::NTSTATUS = 0xC0380054u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: ::NTSTATUS = 0xC0380055u32 as i32; +pub const STATUS_VOLMGR_VOLUME_MIRRORED: ::NTSTATUS = 0xC0380056u32 as i32; +pub const STATUS_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: ::NTSTATUS = 0xC0380057u32 as i32; +pub const STATUS_VOLMGR_NO_VALID_LOG_COPIES: ::NTSTATUS = 0xC0380058u32 as i32; +pub const STATUS_VOLMGR_PRIMARY_PACK_PRESENT: ::NTSTATUS = 0xC0380059u32 as i32; +pub const STATUS_VOLMGR_NUMBER_OF_DISKS_INVALID: ::NTSTATUS = 0xC038005Au32 as i32; +pub const STATUS_VOLMGR_MIRROR_NOT_SUPPORTED: ::NTSTATUS = 0xC038005Bu32 as i32; +pub const STATUS_VOLMGR_RAID5_NOT_SUPPORTED: ::NTSTATUS = 0xC038005Cu32 as i32; +pub const STATUS_BCD_NOT_ALL_ENTRIES_IMPORTED: ::NTSTATUS = 0x80390001u32 as i32; +pub const STATUS_BCD_TOO_MANY_ELEMENTS: ::NTSTATUS = 0xC0390002u32 as i32; +pub const STATUS_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: ::NTSTATUS = 0x80390003u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_MISSING: ::NTSTATUS = 0xC03A0001u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC03A0002u32 as i32; +pub const STATUS_VHD_DRIVE_FOOTER_CORRUPT: ::NTSTATUS = 0xC03A0003u32 as i32; +pub const STATUS_VHD_FORMAT_UNKNOWN: ::NTSTATUS = 0xC03A0004u32 as i32; +pub const STATUS_VHD_FORMAT_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC03A0005u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: ::NTSTATUS = 0xC03A0006u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC03A0007u32 as i32; +pub const STATUS_VHD_SPARSE_HEADER_CORRUPT: ::NTSTATUS = 0xC03A0008u32 as i32; +pub const STATUS_VHD_BLOCK_ALLOCATION_FAILURE: ::NTSTATUS = 0xC03A0009u32 as i32; +pub const STATUS_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: ::NTSTATUS = 0xC03A000Au32 as i32; +pub const STATUS_VHD_INVALID_BLOCK_SIZE: ::NTSTATUS = 0xC03A000Bu32 as i32; +pub const STATUS_VHD_BITMAP_MISMATCH: ::NTSTATUS = 0xC03A000Cu32 as i32; +pub const STATUS_VHD_PARENT_VHD_NOT_FOUND: ::NTSTATUS = 0xC03A000Du32 as i32; +pub const STATUS_VHD_CHILD_PARENT_ID_MISMATCH: ::NTSTATUS = 0xC03A000Eu32 as i32; +pub const STATUS_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: ::NTSTATUS = 0xC03A000Fu32 as i32; +pub const STATUS_VHD_METADATA_READ_FAILURE: ::NTSTATUS = 0xC03A0010u32 as i32; +pub const STATUS_VHD_METADATA_WRITE_FAILURE: ::NTSTATUS = 0xC03A0011u32 as i32; +pub const STATUS_VHD_INVALID_SIZE: ::NTSTATUS = 0xC03A0012u32 as i32; +pub const STATUS_VHD_INVALID_FILE_SIZE: ::NTSTATUS = 0xC03A0013u32 as i32; +pub const STATUS_VIRTDISK_PROVIDER_NOT_FOUND: ::NTSTATUS = 0xC03A0014u32 as i32; +pub const STATUS_VIRTDISK_NOT_VIRTUAL_DISK: ::NTSTATUS = 0xC03A0015u32 as i32; +pub const STATUS_VHD_PARENT_VHD_ACCESS_DENIED: ::NTSTATUS = 0xC03A0016u32 as i32; +pub const STATUS_VHD_CHILD_PARENT_SIZE_MISMATCH: ::NTSTATUS = 0xC03A0017u32 as i32; +pub const STATUS_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: ::NTSTATUS = 0xC03A0018u32 as i32; +pub const STATUS_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: ::NTSTATUS = 0xC03A0019u32 as i32; +pub const STATUS_VIRTUAL_DISK_LIMITATION: ::NTSTATUS = 0xC03A001Au32 as i32; +pub const STATUS_VHD_INVALID_TYPE: ::NTSTATUS = 0xC03A001Bu32 as i32; +pub const STATUS_VHD_INVALID_STATE: ::NTSTATUS = 0xC03A001Cu32 as i32; +pub const STATUS_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: ::NTSTATUS = 0xC03A001Du32 as i32; +pub const STATUS_VIRTDISK_DISK_ALREADY_OWNED: ::NTSTATUS = 0xC03A001Eu32 as i32; +pub const STATUS_VIRTDISK_DISK_ONLINE_AND_WRITABLE: ::NTSTATUS = 0xC03A001Fu32 as i32; +pub const STATUS_CTLOG_TRACKING_NOT_INITIALIZED: ::NTSTATUS = 0xC03A0020u32 as i32; +pub const STATUS_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: ::NTSTATUS = 0xC03A0021u32 as i32; +pub const STATUS_CTLOG_VHD_CHANGED_OFFLINE: ::NTSTATUS = 0xC03A0022u32 as i32; +pub const STATUS_CTLOG_INVALID_TRACKING_STATE: ::NTSTATUS = 0xC03A0023u32 as i32; +pub const STATUS_CTLOG_INCONSISTENT_TRACKING_FILE: ::NTSTATUS = 0xC03A0024u32 as i32; +pub const STATUS_VHD_METADATA_FULL: ::NTSTATUS = 0xC03A0028u32 as i32; +pub const STATUS_VHD_INVALID_CHANGE_TRACKING_ID: ::NTSTATUS = 0xC03A0029u32 as i32; +pub const STATUS_VHD_CHANGE_TRACKING_DISABLED: ::NTSTATUS = 0xC03A002Au32 as i32; +pub const STATUS_VHD_MISSING_CHANGE_TRACKING_INFORMATION: ::NTSTATUS = 0xC03A0030u32 as i32; +pub const STATUS_VHD_RESIZE_WOULD_TRUNCATE_DATA: ::NTSTATUS = 0xC03A0031u32 as i32; +pub const STATUS_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: ::NTSTATUS = 0xC03A0032u32 as i32; +pub const STATUS_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: ::NTSTATUS = 0xC03A0033u32 as i32; +pub const STATUS_QUERY_STORAGE_ERROR: ::NTSTATUS = 0x803A0001u32 as i32; +pub const STATUS_RKF_KEY_NOT_FOUND: ::NTSTATUS = 0xC0400001u32 as i32; +pub const STATUS_RKF_DUPLICATE_KEY: ::NTSTATUS = 0xC0400002u32 as i32; +pub const STATUS_RKF_BLOB_FULL: ::NTSTATUS = 0xC0400003u32 as i32; +pub const STATUS_RKF_STORE_FULL: ::NTSTATUS = 0xC0400004u32 as i32; +pub const STATUS_RKF_FILE_BLOCKED: ::NTSTATUS = 0xC0400005u32 as i32; +pub const STATUS_RKF_ACTIVE_KEY: ::NTSTATUS = 0xC0400006u32 as i32; +pub const STATUS_RDBSS_RESTART_OPERATION: ::NTSTATUS = 0xC0410001u32 as i32; +pub const STATUS_RDBSS_CONTINUE_OPERATION: ::NTSTATUS = 0xC0410002u32 as i32; +pub const STATUS_RDBSS_POST_OPERATION: ::NTSTATUS = 0xC0410003u32 as i32; +pub const STATUS_BTH_ATT_INVALID_HANDLE: ::NTSTATUS = 0xC0420001u32 as i32; +pub const STATUS_BTH_ATT_READ_NOT_PERMITTED: ::NTSTATUS = 0xC0420002u32 as i32; +pub const STATUS_BTH_ATT_WRITE_NOT_PERMITTED: ::NTSTATUS = 0xC0420003u32 as i32; +pub const STATUS_BTH_ATT_INVALID_PDU: ::NTSTATUS = 0xC0420004u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_AUTHENTICATION: ::NTSTATUS = 0xC0420005u32 as i32; +pub const STATUS_BTH_ATT_REQUEST_NOT_SUPPORTED: ::NTSTATUS = 0xC0420006u32 as i32; +pub const STATUS_BTH_ATT_INVALID_OFFSET: ::NTSTATUS = 0xC0420007u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_AUTHORIZATION: ::NTSTATUS = 0xC0420008u32 as i32; +pub const STATUS_BTH_ATT_PREPARE_QUEUE_FULL: ::NTSTATUS = 0xC0420009u32 as i32; +pub const STATUS_BTH_ATT_ATTRIBUTE_NOT_FOUND: ::NTSTATUS = 0xC042000Au32 as i32; +pub const STATUS_BTH_ATT_ATTRIBUTE_NOT_LONG: ::NTSTATUS = 0xC042000Bu32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: ::NTSTATUS = 0xC042000Cu32 as i32; +pub const STATUS_BTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: ::NTSTATUS = 0xC042000Du32 as i32; +pub const STATUS_BTH_ATT_UNLIKELY: ::NTSTATUS = 0xC042000Eu32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_ENCRYPTION: ::NTSTATUS = 0xC042000Fu32 as i32; +pub const STATUS_BTH_ATT_UNSUPPORTED_GROUP_TYPE: ::NTSTATUS = 0xC0420010u32 as i32; +pub const STATUS_BTH_ATT_INSUFFICIENT_RESOURCES: ::NTSTATUS = 0xC0420011u32 as i32; +pub const STATUS_BTH_ATT_UNKNOWN_ERROR: ::NTSTATUS = 0xC0421000u32 as i32; +pub const STATUS_SECUREBOOT_ROLLBACK_DETECTED: ::NTSTATUS = 0xC0430001u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_VIOLATION: ::NTSTATUS = 0xC0430002u32 as i32; +pub const STATUS_SECUREBOOT_INVALID_POLICY: ::NTSTATUS = 0xC0430003u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: ::NTSTATUS = 0xC0430004u32 as i32; +pub const STATUS_SECUREBOOT_POLICY_NOT_SIGNED: ::NTSTATUS = 0xC0430005u32 as i32; +pub const STATUS_SECUREBOOT_NOT_ENABLED: ::NTSTATUS = 0x80430006u32 as i32; +pub const STATUS_SECUREBOOT_FILE_REPLACED: ::NTSTATUS = 0xC0430007u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_ROLLBACK_DETECTED: ::NTSTATUS = 0xC0E90001u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_POLICY_VIOLATION: ::NTSTATUS = 0xC0E90002u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_INVALID_POLICY: ::NTSTATUS = 0xC0E90003u32 as i32; +pub const STATUS_SYSTEM_INTEGRITY_POLICY_NOT_SIGNED: ::NTSTATUS = 0xC0E90004u32 as i32; +pub const STATUS_NO_APPLICABLE_APP_LICENSES_FOUND: ::NTSTATUS = 0xC0EA0001u32 as i32; +pub const STATUS_AUDIO_ENGINE_NODE_NOT_FOUND: ::NTSTATUS = 0xC0440001u32 as i32; +pub const STATUS_HDAUDIO_EMPTY_CONNECTION_LIST: ::NTSTATUS = 0xC0440002u32 as i32; +pub const STATUS_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: ::NTSTATUS = 0xC0440003u32 as i32; +pub const STATUS_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: ::NTSTATUS = 0xC0440004u32 as i32; +pub const STATUS_HDAUDIO_NULL_LINKED_LIST_ENTRY: ::NTSTATUS = 0xC0440005u32 as i32; +pub const STATUS_SPACES_RESILIENCY_TYPE_INVALID: ::NTSTATUS = 0xC0E70003u32 as i32; +pub const STATUS_SPACES_DRIVE_SECTOR_SIZE_INVALID: ::NTSTATUS = 0xC0E70004u32 as i32; +pub const STATUS_SPACES_DRIVE_REDUNDANCY_INVALID: ::NTSTATUS = 0xC0E70006u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_DATA_COPIES_INVALID: ::NTSTATUS = 0xC0E70007u32 as i32; +pub const STATUS_SPACES_INTERLEAVE_LENGTH_INVALID: ::NTSTATUS = 0xC0E70009u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_COLUMNS_INVALID: ::NTSTATUS = 0xC0E7000Au32 as i32; +pub const STATUS_SPACES_NOT_ENOUGH_DRIVES: ::NTSTATUS = 0xC0E7000Bu32 as i32; +pub const STATUS_SPACES_EXTENDED_ERROR: ::NTSTATUS = 0xC0E7000Cu32 as i32; +pub const STATUS_SPACES_PROVISIONING_TYPE_INVALID: ::NTSTATUS = 0xC0E7000Du32 as i32; +pub const STATUS_SPACES_ALLOCATION_SIZE_INVALID: ::NTSTATUS = 0xC0E7000Eu32 as i32; +pub const STATUS_SPACES_ENCLOSURE_AWARE_INVALID: ::NTSTATUS = 0xC0E7000Fu32 as i32; +pub const STATUS_SPACES_WRITE_CACHE_SIZE_INVALID: ::NTSTATUS = 0xC0E70010u32 as i32; +pub const STATUS_SPACES_NUMBER_OF_GROUPS_INVALID: ::NTSTATUS = 0xC0E70011u32 as i32; +pub const STATUS_SPACES_DRIVE_OPERATIONAL_STATE_INVALID: ::NTSTATUS = 0xC0E70012u32 as i32; +pub const STATUS_SPACES_UPDATE_COLUMN_STATE: ::NTSTATUS = 0xC0E70013u32 as i32; +pub const STATUS_SPACES_MAP_REQUIRED: ::NTSTATUS = 0xC0E70014u32 as i32; +pub const STATUS_SPACES_UNSUPPORTED_VERSION: ::NTSTATUS = 0xC0E70015u32 as i32; +pub const STATUS_SPACES_CORRUPT_METADATA: ::NTSTATUS = 0xC0E70016u32 as i32; +pub const STATUS_SPACES_DRT_FULL: ::NTSTATUS = 0xC0E70017u32 as i32; +pub const STATUS_SPACES_INCONSISTENCY: ::NTSTATUS = 0xC0E70018u32 as i32; +pub const STATUS_SPACES_LOG_NOT_READY: ::NTSTATUS = 0xC0E70019u32 as i32; +pub const STATUS_SPACES_NO_REDUNDANCY: ::NTSTATUS = 0xC0E7001Au32 as i32; +pub const STATUS_SPACES_DRIVE_NOT_READY: ::NTSTATUS = 0xC0E7001Bu32 as i32; +pub const STATUS_SPACES_REPAIRED: ::NTSTATUS = 0x00E7001C; +pub const STATUS_SPACES_PAUSE: ::NTSTATUS = 0x00E7001D; +pub const STATUS_SPACES_COMPLETE: ::NTSTATUS = 0x00E7001E; +pub const STATUS_VOLSNAP_BOOTFILE_NOT_VALID: ::NTSTATUS = 0xC0500003u32 as i32; +pub const STATUS_IO_PREEMPTED: ::NTSTATUS = 0xC0510001u32 as i32; +pub const STATUS_SVHDX_ERROR_STORED: ::NTSTATUS = 0xC05C0000u32 as i32; +pub const STATUS_SVHDX_ERROR_NOT_AVAILABLE: ::NTSTATUS = 0xC05CFF00u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_AVAILABLE: ::NTSTATUS = 0xC05CFF01u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: ::NTSTATUS = 0xC05CFF02u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: ::NTSTATUS = 0xC05CFF03u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: ::NTSTATUS = 0xC05CFF04u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: ::NTSTATUS = 0xC05CFF05u32 as i32; +pub const STATUS_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: ::NTSTATUS = 0xC05CFF06u32 as i32; +pub const STATUS_SVHDX_RESERVATION_CONFLICT: ::NTSTATUS = 0xC05CFF07u32 as i32; +pub const STATUS_SVHDX_WRONG_FILE_TYPE: ::NTSTATUS = 0xC05CFF08u32 as i32; +pub const STATUS_SVHDX_VERSION_MISMATCH: ::NTSTATUS = 0xC05CFF09u32 as i32; +pub const STATUS_VHD_SHARED: ::NTSTATUS = 0xC05CFF0Au32 as i32; +pub const STATUS_SVHDX_NO_INITIATOR: ::NTSTATUS = 0xC05CFF0Bu32 as i32; +pub const STATUS_VHDSET_BACKING_STORAGE_NOT_FOUND: ::NTSTATUS = 0xC05CFF0Cu32 as i32; +pub const STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP: ::NTSTATUS = 0xC05D0000u32 as i32; +pub const STATUS_SMB_BAD_CLUSTER_DIALECT: ::NTSTATUS = 0xC05D0001u32 as i32; +pub const STATUS_SMB_GUEST_LOGON_BLOCKED: ::NTSTATUS = 0xC05D0002u32 as i32; +pub const STATUS_SECCORE_INVALID_COMMAND: ::NTSTATUS = 0xC0E80000u32 as i32; +pub const STATUS_VSM_NOT_INITIALIZED: ::NTSTATUS = 0xC0450000u32 as i32; +pub const STATUS_VSM_DMA_PROTECTION_NOT_IN_USE: ::NTSTATUS = 0xC0450001u32 as i32; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/oaidl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/oaidl.rs new file mode 100644 index 0000000..c705060 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/oaidl.rs @@ -0,0 +1,590 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of OAIdl.h +pub type wireBRECORD = *mut _wireBRECORD; +pub type wireVARIANT = *mut _wireVARIANT; +STRUCT!{struct SAFEARRAYBOUND { + cElements: ::ULONG, + lLbound: ::LONG, +}} +STRUCT!{struct SAFEARR_BSTR { + Size: ::ULONG, + aBstr: *mut ::wireBSTR, +}} +STRUCT!{struct SAFEARR_UNKNOWN { + Size: ::ULONG, + apUnknown: *mut *mut ::IUnknown, +}} +STRUCT!{struct SAFEARR_DISPATCH { + Size: ::ULONG, + apDispatch: *mut *mut IDispatch, +}} +STRUCT!{struct SAFEARR_VARIANT { + Size: ::ULONG, + aVariant: *mut wireVARIANT, +}} +STRUCT!{struct SAFEARR_BRECORD { + Size: ::ULONG, + aRecord: *mut wireBRECORD, +}} +STRUCT!{struct SAFEARR_HAVEIID { + Size: ::ULONG, + apUnknown: *mut *mut ::IUnknown, + iid: ::IID, +}} +ENUM!{enum SF_TYPE { + SF_ERROR = ::VT_ERROR.0, + SF_I1 = ::VT_I1.0, + SF_I2 = ::VT_I2.0, + SF_I4 = ::VT_I4.0, + SF_I8 = ::VT_I8.0, + SF_BSTR = ::VT_BSTR.0, + SF_UNKNOWN = ::VT_UNKNOWN.0, + SF_DISPATCH = ::VT_DISPATCH.0, + SF_VARIANT = ::VT_VARIANT.0, + SF_RECORD = ::VT_RECORD.0, + SF_HAVEIID = ::VT_UNKNOWN.0 | ::VT_RESERVED.0, +}} +STRUCT!{struct SAFEARRAYUNION { + sfType: ::ULONG, + u: __MIDL_IOleAutomationTypes_0001, +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct __MIDL_IOleAutomationTypes_0001 { + data0: u32, + data1: [u32; 6], +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct __MIDL_IOleAutomationTypes_0001 { + data0: u32, + data1: [u32; 5], +}} +UNION!(__MIDL_IOleAutomationTypes_0001, data0, BstrStr, BstrStr_mut, SAFEARR_BSTR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, UnknownStr, UnknownStr_mut, SAFEARR_UNKNOWN); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, DispatchStr, DispatchStr_mut, SAFEARR_DISPATCH); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, VariantStr, VariantStr_mut, SAFEARR_VARIANT); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, RecordStr, RecordStr_mut, SAFEARR_BRECORD); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, HaveIidStr, HaveIidStr_mut, SAFEARR_HAVEIID); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, ByteStr, ByteStr_mut, ::BYTE_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, WordStr, WordStr_mut, ::WORD_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, LongStr, LongStr_mut, ::DWORD_SIZEDARR); +UNION!(__MIDL_IOleAutomationTypes_0001, data0, HyperStr, HyperStr_mut, ::HYPER_SIZEDARR); +STRUCT!{struct _wireSAFEARRAY { + cDims: ::USHORT, + fFeatures: ::USHORT, + cbElements: ::ULONG, + cLocks: ::ULONG, + uArrayStructs: SAFEARRAYUNION, + rgsaBound: [SAFEARRAYBOUND; 1], +}} +pub type wireSAFEARRAY = *mut _wireSAFEARRAY; +pub type wirePSAFEARRAY = *mut wireSAFEARRAY; +STRUCT!{struct SAFEARRAY { + cDims: ::USHORT, + fFeatures: ::USHORT, + cbElements: ::ULONG, + cLocks: ::ULONG, + pvData: ::PVOID, + rgsabound: [SAFEARRAYBOUND; 1], +}} +pub type LPSAFEARRAY = *mut SAFEARRAY; +pub const FADF_AUTO: ::DWORD = 0x1; +pub const FADF_STATIC: ::DWORD = 0x2; +pub const FADF_EMBEDDED: ::DWORD = 0x4; +pub const FADF_FIXEDSIZE: ::DWORD = 0x10; +pub const FADF_RECORD: ::DWORD = 0x20; +pub const FADF_HAVEIID: ::DWORD = 0x40; +pub const FADF_HAVEVARTYPE: ::DWORD = 0x80; +pub const FADF_BSTR: ::DWORD = 0x100; +pub const FADF_UNKNOWN: ::DWORD = 0x200; +pub const FADF_DISPATCH: ::DWORD = 0x400; +pub const FADF_VARIANT: ::DWORD = 0x800; +pub const FADF_RESERVED: ::DWORD = 0xf008; +#[cfg(target_arch = "x86_64")] +STRUCT!{struct VARIANT { + data0: u64, + data1: u64, + data2: u64, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct VARIANT { + data0: u64, + data1: u32, + data2: u32, +}} +UNION!(VARIANT, data0, vt, vt_mut, ::VARTYPE); +UNION!(VARIANT, data1, llVal, llVal_mut, ::LONGLONG); +UNION!(VARIANT, data1, lVal, lVal_mut, ::LONG); +UNION!(VARIANT, data1, bVal, bVal_mut, ::BYTE); +UNION!(VARIANT, data1, iVal, iVal_mut, ::SHORT); +UNION!(VARIANT, data1, fltVal, fltVal_mut, ::FLOAT); +UNION!(VARIANT, data1, dblVal, dblVal_mut, ::DOUBLE); +UNION!(VARIANT, data1, boolVal, boolVal_mut, ::VARIANT_BOOL); +UNION!(VARIANT, data1, scode, scode_mut, ::SCODE); +UNION!(VARIANT, data1, cyVal, cyVal_mut, ::CY); +UNION!(VARIANT, data1, date, date_mut, ::DATE); +UNION!(VARIANT, data1, bstrVal, bstrVal_mut, ::BSTR); +UNION!(VARIANT, data1, punkVal, punkVal_mut, *mut ::IUnknown); +UNION!(VARIANT, data1, pdispVal, pdispVal_mut, *mut IDispatch); +UNION!(VARIANT, data1, parray, parray_mut, *mut SAFEARRAY); +UNION!(VARIANT, data1, pllVal, pllVal_mut, *mut ::LONGLONG); +UNION!(VARIANT, data1, plVal, plVal_mut, *mut ::LONG); +UNION!(VARIANT, data1, pbVal, pbVal_mut, *mut ::BYTE); +UNION!(VARIANT, data1, piVal, piVal_mut, *mut ::SHORT); +UNION!(VARIANT, data1, pfltVal, pfltVal_mut, *mut ::FLOAT); +UNION!(VARIANT, data1, pdblVal, pdblVal_mut, *mut ::DOUBLE); +UNION!(VARIANT, data1, pboolVal, pboolVal_mut, *mut ::VARIANT_BOOL); +UNION!(VARIANT, data1, pscode, pscode_mut, *mut ::SCODE); +UNION!(VARIANT, data1, pcyVal, pcyVal_mut, *mut ::CY); +UNION!(VARIANT, data1, pdate, pdate_mut, *mut ::DATE); +UNION!(VARIANT, data1, pbstrVal, pbstrVal_mut, *mut ::BSTR); +UNION!(VARIANT, data1, ppunkVal, ppunkVal_mut, *mut *mut ::IUnknown); +UNION!(VARIANT, data1, ppdispVal, ppdispVal_mut, *mut *mut IDispatch); +UNION!(VARIANT, data1, pparray, pparray_mut, *mut *mut SAFEARRAY); +UNION!(VARIANT, data1, pvarVal, pvarVal_mut, *mut VARIANT); +UNION!(VARIANT, data1, byref, byref_mut, ::PVOID); +UNION!(VARIANT, data1, cVal, cVal_mut, ::CHAR); +UNION!(VARIANT, data1, uiVal, uiVal_mut, ::USHORT); +UNION!(VARIANT, data1, ulVal, ulVal_mut, ::ULONG); +UNION!(VARIANT, data1, ullVal, ullVal_mut, ::ULONGLONG); +UNION!(VARIANT, data1, intVal, intVal_mut, ::INT); +UNION!(VARIANT, data1, uintVal, uintVal_mut, ::UINT); +UNION!(VARIANT, data1, pdecVal, pdecVal_mut, *mut ::DECIMAL); +UNION!(VARIANT, data1, pcVal, pcVal_mut, *mut ::CHAR); +UNION!(VARIANT, data1, puiVal, puiVal_mut, *mut ::USHORT); +UNION!(VARIANT, data1, pulVal, pulVal_mut, *mut ::ULONG); +UNION!(VARIANT, data1, pullVal, pullVal_mut, *mut ::ULONGLONG); +UNION!(VARIANT, data1, pintVal, pintVal_mut, *mut ::INT); +UNION!(VARIANT, data1, puintVal, puintVal_mut, *mut ::UINT); +UNION!(VARIANT, data1, pvRecord, pvRecord_mut, ::PVOID); +UNION!(VARIANT, data2, pRecInfo, pRecInfo_mut, *mut IRecordInfo); +UNION!(VARIANT, data0, decVal, decVal_mut, ::DECIMAL); +pub type LPVARIANT = *mut VARIANT; +pub type VARIANTARG = VARIANT; +pub type LPVARIANTARG = *mut VARIANT; +pub type REFVARIANT = *const VARIANT; +STRUCT!{struct _wireBRECORD { + fFlags: ::ULONG, + clSize: ::ULONG, + pRecInfo: *mut IRecordInfo, + pRecord: *mut ::BYTE, +}} +STRUCT!{struct _wireVARIANT { + clSize: ::DWORD, + rpcReserved: ::DWORD, + vt: ::USHORT, + wReserved1: ::USHORT, + wReserved2: ::USHORT, + wReserved3: ::USHORT, + data0: u64, + data1: u64, +}} +UNION!(_wireVARIANT, data0, llVal, llVal_mut, ::LONGLONG); +UNION!(_wireVARIANT, data0, lVal, lVal_mut, ::LONG); +UNION!(_wireVARIANT, data0, bVal, bVal_mut, ::BYTE); +UNION!(_wireVARIANT, data0, iVal, iVal_mut, ::SHORT); +UNION!(_wireVARIANT, data0, fltVal, fltVal_mut, ::FLOAT); +UNION!(_wireVARIANT, data0, dblVal, dblVal_mut, ::DOUBLE); +UNION!(_wireVARIANT, data0, boolVal, boolVal_mut, ::VARIANT_BOOL); +UNION!(_wireVARIANT, data0, scode, scode_mut, ::SCODE); +UNION!(_wireVARIANT, data0, cyVal, cyVal_mut, ::CY); +UNION!(_wireVARIANT, data0, date, date_mut, ::DATE); +UNION!(_wireVARIANT, data0, bstrVal, bstrVal_mut, ::wireBSTR); +UNION!(_wireVARIANT, data0, punkVal, punkVal_mut, *mut ::IUnknown); +UNION!(_wireVARIANT, data0, pdispVal, pdispVal_mut, *mut IDispatch); +UNION!(_wireVARIANT, data0, parray, parray_mut, wirePSAFEARRAY); +UNION!(_wireVARIANT, data0, brecVal, brecVal_mut, wireBRECORD); +UNION!(_wireVARIANT, data0, pllVal, pllVal_mut, *mut ::LONGLONG); +UNION!(_wireVARIANT, data0, plVal, plVal_mut, *mut ::LONG); +UNION!(_wireVARIANT, data0, pbVal, pbVal_mut, *mut ::BYTE); +UNION!(_wireVARIANT, data0, piVal, piVal_mut, *mut ::SHORT); +UNION!(_wireVARIANT, data0, pfltVal, pfltVal_mut, *mut ::FLOAT); +UNION!(_wireVARIANT, data0, pdblVal, pdblVal_mut, *mut ::DOUBLE); +UNION!(_wireVARIANT, data0, pboolVal, pboolVal_mut, *mut ::VARIANT_BOOL); +UNION!(_wireVARIANT, data0, pscode, pscode_mut, *mut ::SCODE); +UNION!(_wireVARIANT, data0, pcyVal, pcyVal_mut, *mut ::CY); +UNION!(_wireVARIANT, data0, pdate, pdate_mut, *mut ::DATE); +UNION!(_wireVARIANT, data0, pbstrVal, pbstrVal_mut, *mut ::wireBSTR); +UNION!(_wireVARIANT, data0, ppunkVal, ppunkVal_mut, *mut *mut ::IUnknown); +UNION!(_wireVARIANT, data0, ppdispVal, ppdispVal_mut, *mut *mut IDispatch); +UNION!(_wireVARIANT, data0, pparray, pparray_mut, *mut wirePSAFEARRAY); +UNION!(_wireVARIANT, data0, pvarVal, pvarVal_mut, *mut wireVARIANT); +UNION!(_wireVARIANT, data0, cVal, cVal_mut, ::CHAR); +UNION!(_wireVARIANT, data0, uiVal, uiVal_mut, ::USHORT); +UNION!(_wireVARIANT, data0, ulVal, ulVal_mut, ::ULONG); +UNION!(_wireVARIANT, data0, ullVal, ullVal_mut, ::ULONGLONG); +UNION!(_wireVARIANT, data0, intVal, intVal_mut, ::INT); +UNION!(_wireVARIANT, data0, uintVal, uintVal_mut, ::UINT); +UNION!(_wireVARIANT, data0, decVal, decVal_mut, ::DECIMAL); +UNION!(_wireVARIANT, data0, pcVal, pcVal_mut, *mut ::CHAR); +UNION!(_wireVARIANT, data0, puiVal, puiVal_mut, *mut ::USHORT); +UNION!(_wireVARIANT, data0, pulVal, pulVal_mut, *mut ::ULONG); +UNION!(_wireVARIANT, data0, pullVal, pullVal_mut, *mut ::ULONGLONG); +UNION!(_wireVARIANT, data0, pintVal, pintVal_mut, *mut ::INT); +UNION!(_wireVARIANT, data0, puintVal, puintVal_mut, *mut ::UINT); +UNION!(_wireVARIANT, data0, pdecVal, pdecVal_mut, *mut ::DECIMAL); +pub type DISPID = ::LONG; +pub type MEMBERID = DISPID; +pub type HREFTYPE = ::DWORD; +ENUM!{enum TYPEKIND { + TKIND_ENUM = 0, + TKIND_RECORD, + TKIND_MODULE, + TKIND_INTERFACE, + TKIND_DISPATCH, + TKIND_COCLASS, + TKIND_ALIAS, + TKIND_UNION, + TKIND_MAX, +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct TYPEDESC { + data: u64, + vt: ::VARTYPE, +}} +#[cfg(target_arch = "x86")] +STRUCT!{struct TYPEDESC { + data: u32, + vt: ::VARTYPE, +}} +UNION!(TYPEDESC, data, lptdesc, lptdesc_mut, *mut TYPEDESC); +UNION!(TYPEDESC, data, lpadesc, lpadesc_mut, *mut ARRAYDESC); +UNION!(TYPEDESC, data, hreftype, hreftype_mut, HREFTYPE); +STRUCT!{struct ARRAYDESC { + tdescElem: TYPEDESC, + cDims: ::USHORT, + rgbounds: [SAFEARRAYBOUND; 1], +}} +STRUCT!{struct PARAMDESCEX { + cBytes: ::ULONG, + varDefaultValue: VARIANTARG, +}} +pub type LPPARAMDESCEX = *mut PARAMDESCEX; +STRUCT!{struct PARAMDESC { + pparamdescex: LPPARAMDESCEX, + wParamFlags: ::USHORT, +}} +pub type LPPARAMDESC = *mut PARAMDESC; +pub const PARAMFLAG_NONE: ::DWORD = 0; +pub const PARAMFLAG_FIN: ::DWORD = 0x1; +pub const PARAMFLAG_FOUT: ::DWORD = 0x2; +pub const PARAMFLAG_FLCID: ::DWORD = 0x4; +pub const PARAMFLAG_FRETVAL: ::DWORD = 0x8; +pub const PARAMFLAG_FOPT: ::DWORD = 0x10; +pub const PARAMFLAG_FHASDEFAULT: ::DWORD = 0x20; +pub const PARAMFLAG_FHASCUSTDATA: ::DWORD = 0x40; +STRUCT!{struct IDLDESC { + dwReserved: ::ULONG_PTR, + wIDLFlags: ::USHORT, +}} +pub type LPIDLDESC = *mut IDLDESC; +pub const IDLFLAG_NONE: ::DWORD = PARAMFLAG_NONE; +pub const IDLFLAG_FIN: ::DWORD = PARAMFLAG_FIN; +pub const IDLFLAG_FOUT: ::DWORD = PARAMFLAG_FOUT; +pub const IDLFLAG_FLCID: ::DWORD = PARAMFLAG_FLCID; +pub const IDLFLAG_FRETVAL: ::DWORD = PARAMFLAG_FRETVAL; +STRUCT!{struct ELEMDESC { + tdesc: TYPEDESC, + idldesc: IDLDESC, +}} +UNION!(ELEMDESC, idldesc, paramdesc, paramdesc_mut, PARAMDESC); +pub type LPELEMDESC = *mut ELEMDESC; +STRUCT!{struct TYPEATTR { + guid: ::GUID, + lcid: ::LCID, + dwReserved: ::DWORD, + memidConstructor: ::MEMBERID, + memidDestructor: ::MEMBERID, + lpstrSchema: ::LPOLESTR, + cbSizeInstance: ::ULONG, + typekind: ::TYPEKIND, + cFuncs: ::WORD, + cVars: ::WORD, + cImplTypes: ::WORD, + cbSizeVft: ::WORD, + cbAlignment: ::WORD, + wTypeFlags: ::WORD, + wMajorVerNum: ::WORD, + wMinorVerNum: ::WORD, + tdescAlias: ::TYPEDESC, + idldescType: ::IDLDESC, +}} +pub type LPTYPEATTR = *mut TYPEATTR; +STRUCT!{struct DISPPARAMS { + rgvarg: *mut VARIANTARG, + rgdispidNamedArgs: *mut DISPID, + cArgs: ::UINT, + cNamedArgs: ::UINT, +}} +STRUCT!{nodebug struct EXCEPINFO { + wCode: ::WORD, + wReserved: ::WORD, + bstrSource: ::BSTR, + bstrDescription: ::BSTR, + bstrHelpFile: ::BSTR, + dwHelpContext: ::DWORD, + pvReserved: ::PVOID, + pfnDeferredFillIn: Option ::HRESULT>, + scode: ::SCODE, +}} +ENUM!{enum CALLCONV { + CC_FASTCALL = 0, + CC_CDECL = 1, + CC_MSCPASCAL, + CC_PASCAL, + CC_MACPASCAL, + CC_STDCALL, + CC_FPFASTCALL, + CC_SYSCALL, + CC_MPWCDECL, + CC_MPWPASCAL, + CC_MAX, +}} +ENUM!{enum FUNCKIND { + FUNC_VIRTUAL = 0, + FUNC_PUREVIRTUAL, + FUNC_NONVIRTUAL, + FUNC_STATIC, + FUNC_DISPATCH, +}} +FLAGS!{enum INVOKEKIND { + INVOKE_FUNC = 1, + INVOKE_PROPERTYGET = 2, + INVOKE_PROPERTYPUT = 4, + INVOKE_PROPERTYPUTREF = 8, +}} +STRUCT!{struct FUNCDESC { + memid: ::MEMBERID, + lprgscode: *mut ::SCODE, + lprgelemdescParam: *mut ::ELEMDESC, + funckind: ::FUNCKIND, + invkind: ::INVOKEKIND, + callconv: ::CALLCONV, + cParams: ::SHORT, + cParamsOpt: ::SHORT, + oVft: ::SHORT, + cScodes: ::SHORT, + elemdescFunc: ::ELEMDESC, + wFuncFlags: ::WORD, +}} +pub type LPFUNCDESC = *mut FUNCDESC; +ENUM!{enum VARKIND { + VAR_PERINSTANCE = 0, + VAR_STATIC, + VAR_CONST, + VAR_DISPATCH, +}} +pub const IMPLTYPEFLAG_FDEFAULT: ::DWORD = 0x1; +pub const IMPLTYPEFLAG_FSOURCE: ::DWORD = 0x2; +pub const IMPLTYPEFLAG_FRESTRICTED: ::DWORD = 0x4; +pub const IMPLTYPEFLAG_FDEFAULTVTABLE: ::DWORD = 0x8; +STRUCT!{struct VARDESC { + memid: MEMBERID, + lpstrSchema: ::LPOLESTR, + lpvarValue: *mut VARIANT, + elemdescVar: ::ELEMDESC, + wVarFlags: ::WORD, + varkind: VARKIND, +}} +UNION!(VARDESC, lpvarValue, oInst, oInst_mut, ::ULONG); +pub type LPVARDESC = *mut VARDESC; +FLAGS!{enum TYPEFLAGS { + TYPEFLAG_FAPPOBJECT = 0x1, + TYPEFLAG_FCANCREATE = 0x2, + TYPEFLAG_FLICENSED = 0x4, + TYPEFLAG_FPREDECLID = 0x8, + TYPEFLAG_FHIDDEN = 0x10, + TYPEFLAG_FCONTROL = 0x20, + TYPEFLAG_FDUAL = 0x40, + TYPEFLAG_FNONEXTENSIBLE = 0x80, + TYPEFLAG_FOLEAUTOMATION = 0x100, + TYPEFLAG_FRESTRICTED = 0x200, + TYPEFLAG_FAGGREGATABLE = 0x400, + TYPEFLAG_FREPLACEABLE = 0x800, + TYPEFLAG_FDISPATCHABLE = 0x1000, + TYPEFLAG_FREVERSEBIND = 0x2000, + TYPEFLAG_FPROXY = 0x4000, +}} +FLAGS!{enum FUNCFLAGS { + FUNCFLAG_FRESTRICTED = 0x1, + FUNCFLAG_FSOURCE = 0x2, + FUNCFLAG_FBINDABLE = 0x4, + FUNCFLAG_FREQUESTEDIT = 0x8, + FUNCFLAG_FDISPLAYBIND = 0x10, + FUNCFLAG_FDEFAULTBIND = 0x20, + FUNCFLAG_FHIDDEN = 0x40, + FUNCFLAG_FUSESGETLASTERROR = 0x80, + FUNCFLAG_FDEFAULTCOLLELEM = 0x100, + FUNCFLAG_FUIDEFAULT = 0x200, + FUNCFLAG_FNONBROWSABLE = 0x400, + FUNCFLAG_FREPLACEABLE = 0x800, + FUNCFLAG_FIMMEDIATEBIND = 0x1000, +}} +FLAGS!{enum VARFLAGS { + VARFLAG_FREADONLY = 0x1, + VARFLAG_FSOURCE = 0x2, + VARFLAG_FBINDABLE = 0x4, + VARFLAG_FREQUESTEDIT = 0x8, + VARFLAG_FDISPLAYBIND = 0x10, + VARFLAG_FDEFAULTBIND = 0x20, + VARFLAG_FHIDDEN = 0x40, + VARFLAG_FRESTRICTED = 0x80, + VARFLAG_FDEFAULTCOLLELEM = 0x100, + VARFLAG_FUIDEFAULT = 0x200, + VARFLAG_FNONBROWSABLE = 0x400, + VARFLAG_FREPLACEABLE = 0x800, + VARFLAG_FIMMEDIATEBIND = 0x1000, +}} +STRUCT!{struct CLEANLOCALSTORAGE { + pInterface: *mut ::IUnknown, + pStorage: ::PVOID, + flags: ::DWORD, +}} +STRUCT!{struct CUSTDATAITEM { + guid: ::GUID, + varValue: VARIANTARG, +}} +pub type LPCUSTDATAITEM = *mut CUSTDATAITEM; +STRUCT!{struct CUSTDATA { + cCustData: ::DWORD, + prgCustData: LPCUSTDATAITEM, +}} +pub type LPCUSTDATA = *mut CUSTDATA; +pub type LPCREATETYPEINFO = *mut ICreateTypeInfo; +RIDL!( +interface ICreateTypeInfo(ICreateTypeInfoVtbl): IUnknown(IUnknownVtbl) { + fn SetGuid(&mut self, guid: ::REFGUID) -> ::HRESULT, + fn SetTypeFlags(&mut self, uTypeFlags: ::UINT) -> ::HRESULT, + fn SetDocString(&mut self, pStrDoc: ::LPOLESTR) -> ::HRESULT, + fn SetHelpContext(&mut self, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetVersion(&mut self, wMajorVerNum: ::WORD, wMinorVerNum: ::WORD) -> ::HRESULT, + fn AddRefTypeInfo(&mut self, pTInfo: *mut ITypeInfo) -> ::HRESULT, + fn AddFuncDesc(&mut self, index: ::UINT, pFuncDesc: *mut FUNCDESC) -> ::HRESULT, + fn SetImplTypeFlags(&mut self, index: ::UINT, implTypeFlags: ::INT) -> ::HRESULT, + fn SetAlignment(&mut self, cbAlignment: ::WORD) -> ::HRESULT, + fn SetSchema(&mut self, pStrSchema: ::LPOLESTR) -> ::HRESULT, + fn AddVarDesc(&mut self, index: ::UINT, pVarDesc: *mut VARDESC) -> ::HRESULT, + fn SetFuncAndParamNames( + &mut self, index: ::UINT, rgszNames: *mut ::LPOLESTR, cNames: ::UINT + ) -> ::HRESULT, + fn SetVarName(&mut self, index: ::UINT, szName: ::LPOLESTR) -> ::HRESULT, + fn SetTypeDescAlias(&mut self, pTDescAlias: *mut TYPEDESC) -> ::HRESULT, + fn DefineFuncAsDllEntry( + &mut self, index: ::UINT, szDllName: ::LPOLESTR, szProcName: ::LPOLESTR + ) -> ::HRESULT, + fn SetFuncDocString(&mut self, index: ::UINT, szDocString: ::LPOLESTR) -> ::HRESULT, + fn SetVarDocString(&mut self, index: ::UINT, szDocString: ::LPOLESTR) -> ::HRESULT, + fn SetFuncHelpContext(&mut self, index: ::UINT, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetVarHelpContext(&mut self, index: ::UINT, dwHelpContext: ::DWORD) -> ::HRESULT, + fn SetMops(&mut self, index: ::UINT, bstrMops: ::BSTR) -> ::HRESULT, + fn SetTypeIdldesc(&mut self, pIdlDesc: *mut IDLDESC) -> ::HRESULT, + fn LayOut(&mut self) -> ::HRESULT +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeInfo2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeLib; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateTypeLib2; +pub type LPDISPATCH = *mut IDispatch; +pub const DISPID_UNKNOWN: ::INT = -1; +pub const DISPID_VALUE: ::INT = 0; +pub const DISPID_PROPERTYPUT: ::INT = -3; +pub const DISPID_NEWENUM: ::INT = -4; +pub const DISPID_EVALUATE: ::INT = -5; +pub const DISPID_CONSTRUCTOR: ::INT = -6; +pub const DISPID_DESTRUCTOR: ::INT = -7; +pub const DISPID_COLLECT: ::INT = -8; +RIDL!( +interface IDispatch(IDispatchVtbl): IUnknown(IUnknownVtbl) { + fn GetTypeInfoCount(&mut self, pctinfo: *mut ::UINT) -> ::HRESULT, + fn GetTypeInfo( + &mut self, iTInfo: ::UINT, lcid: ::LCID, ppTInfo: *mut *mut ITypeInfo + ) -> ::HRESULT, + fn GetIDsOfNames( + &mut self, riid: ::REFIID, rgszNames: *mut ::LPOLESTR, cNames: ::UINT, lcid: ::LCID, + rgDispId: *mut ::DISPID + ) -> ::HRESULT, + fn Invoke( + &mut self, dispIdMember: ::DISPID, riid: ::REFIID, lcid: ::LCID, wFlags: ::WORD, + pDispParams: *mut ::DISPPARAMS, pVarResult: *mut VARIANT, pExcepInfo: *mut ::EXCEPINFO, + puArgErr: *mut ::UINT + ) -> ::HRESULT +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumVARIANT; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeComp; +RIDL!( +interface ITypeInfo(ITypeInfoVtbl): IUnknown(IUnknownVtbl) { + fn GetTypeAttr(&mut self, ppTypeAttr: *mut *mut TYPEATTR) -> ::HRESULT, + fn GetTypeComp(&mut self, ppTComp: *mut *mut ITypeComp) -> ::HRESULT, + fn GetFuncDesc(&mut self, index: ::UINT, ppFunDesc: *mut *mut FUNCDESC) -> ::HRESULT, + fn GetVarDesc(&mut self, index: ::UINT, pPVarDesc: *mut *mut VARDESC) -> ::HRESULT, + fn GetNames( + &mut self, memid: MEMBERID, rgBstrNames: *mut ::BSTR, cMaxNames: ::UINT, + pcNames: *mut ::UINT + ) -> ::HRESULT, + fn GetRefTypeOfImplType(&mut self, index: ::UINT, pRefType: *mut HREFTYPE) -> ::HRESULT, + fn GetImplTypeFlags(&mut self, index: ::UINT, pImplTypeFlags: *mut ::INT) -> ::HRESULT, + fn GetIDsOfNames( + &mut self, rgszNames: *mut ::LPOLESTR, cNames: ::UINT, pMemId: *mut MEMBERID + ) -> ::HRESULT, + fn Invoke( + &mut self, pvInstance: ::PVOID, memid: MEMBERID, wFlags: ::WORD, + pDispParams: *mut DISPPARAMS, pVarResult: *mut VARIANT, pExcepInfo: *mut EXCEPINFO, + puArgErr: *mut ::UINT + ) -> ::HRESULT, + fn GetDocumentation( + &mut self, memid: MEMBERID, pBstrName: *mut ::BSTR, pBstrDocString: *mut ::BSTR, + pdwHelpContext: *mut ::DWORD, pBstrHelpFile: *mut ::BSTR + ) -> ::HRESULT, + fn GetDllEntry( + &mut self, memid: MEMBERID, invKind: ::INVOKEKIND, pBstrDllName: *mut ::BSTR, + pBstrName: *mut ::BSTR, pwOrdinal: *mut ::WORD + ) -> ::HRESULT, + fn GetRefTypeInfo(&mut self, hRefType: HREFTYPE, ppTInfo: *mut *mut ITypeInfo) -> ::HRESULT, + fn AddressOfMember( + &mut self, memid: MEMBERID, invKind: ::INVOKEKIND, ppv: *mut ::PVOID + ) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, riid: ::REFIID, ppvObj: *mut ::PVOID + ) -> ::HRESULT, + fn GetMops(&mut self, memid: MEMBERID, pBstrMops: *mut ::BSTR) -> ::HRESULT, + fn GetContainingTypeLib( + &mut self, ppTLib: *mut *mut ITypeLib, pIndex: *mut ::UINT + ) -> ::HRESULT, + fn ReleaseTypeAttr(&mut self, pTypeAttr: *mut TYPEATTR) -> (), + fn ReleaseFuncDesc(&mut self, pFuncDesc: *mut FUNCDESC) -> (), + fn ReleaseVarDesc(&mut self, pVarDesc: *mut VARDESC) -> () +} +); +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeInfo2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeLib; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeLib2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeChangeEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICreateErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISupportErrorInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITypeMarshal; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRecordInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IErrorLog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPropertyBag; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/objbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/objbase.rs new file mode 100644 index 0000000..cfd2b79 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/objbase.rs @@ -0,0 +1,5 @@ +//! Component object model defintions +pub const COINIT_APARTMENTTHREADED: ::DWORD = 0x2; +pub const COINIT_MULTITHREADED: ::DWORD = 0x0; +pub const COINIT_DISABLE_OLE1DDE: ::DWORD = 0x4; +pub const COINIT_SPEED_OVER_MEMORY: ::DWORD = 0x8; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/objidl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/objidl.rs new file mode 100644 index 0000000..ac49010 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/objidl.rs @@ -0,0 +1,100 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//8402 +STRUCT!{struct BIND_OPTS { + cbStruct: ::DWORD, + grfFlags: ::DWORD, + grfMode: ::DWORD, + dwTickCountDeadline: ::DWORD, +}} +pub type LPBIND_OPTS = *mut BIND_OPTS; +//8479 +RIDL!( +interface IBindCtx(IBindCtxVtbl): IUnknown(IUnknownVtbl) { + fn RegisterObjectBound(&mut self, punk: *mut ::IUnknown) -> ::HRESULT, + fn RevokeObjectBound(&mut self, punk: *mut ::IUnknown) -> ::HRESULT, + fn ReleaseBoundObjects(&mut self) -> ::HRESULT, + fn SetBindOptions(&mut self, pbindopts: *mut BIND_OPTS) -> ::HRESULT, + fn GetBindOptions(&mut self, pbindopts: *mut BIND_OPTS) -> ::HRESULT, + fn GetRunningObjectTable(&mut self, pprot: *mut *mut IRunningObjectTable) -> ::HRESULT, + fn RegisterObjectParam(&mut self, pszKey: ::LPOLESTR, punk: *mut ::IUnknown) -> ::HRESULT, + fn GetObjectParam(&mut self, pszKey: ::LPOLESTR, ppunk: *mut *mut ::IUnknown) -> ::HRESULT, + fn EnumObjectParam(&mut self, ppenum: *mut *mut ::IEnumString) -> ::HRESULT, + fn RevokeObjectParam(&mut self, pszKey: ::LPOLESTR) -> ::HRESULT +} +); +//8681 +pub type IEnumMoniker = ::IUnknown; // TODO +//8958 +RIDL!( +interface IRunningObjectTable(IRunningObjectTableVtbl): IUnknown(IUnknownVtbl) { + fn Register( + &mut self, grfFlags: ::DWORD, punkObject: *mut ::IUnknown, pmkObjectName: *mut IMoniker, + pdwRegister: *mut ::DWORD + ) -> ::HRESULT, + fn Revoke(&mut self, dwRegister: ::DWORD) -> ::HRESULT, + fn IsRunning(&mut self, pmkObjectName: *mut IMoniker) -> ::HRESULT, + fn GetObject( + &mut self, pmkObjectName: *mut IMoniker, ppunkObject: *mut *mut ::IUnknown + ) -> ::HRESULT, + fn NoteChangeTime(&mut self, dwRegister: ::DWORD, pfiletime: *mut ::FILETIME) -> ::HRESULT, + fn GetTimeOfLastChange( + &mut self, pmkObjectName: *mut IMoniker, pfiletime: *mut ::FILETIME + ) -> ::HRESULT, + fn EnumRunning(&mut self, ppenumMoniker: *mut *mut IEnumMoniker) -> ::HRESULT +} +); +//9350 +pub type IMoniker = ::IUnknown; // TODO +pub type EOLE_AUTHENTICATION_CAPABILITIES = ::DWORD; +pub const EOAC_NONE: ::DWORD = 0; +pub const EOAC_MUTUAL_AUTH: ::DWORD = 0x1; +pub const EOAC_STATIC_CLOAKING: ::DWORD = 0x20; +pub const EOAC_DYNAMIC_CLOAKING: ::DWORD = 0x40; +pub const EOAC_ANY_AUTHORITY: ::DWORD = 0x80; +pub const EOAC_MAKE_FULLSIC: ::DWORD = 0x100; +pub const EOAC_DEFAULT: ::DWORD = 0x800; +pub const EOAC_SECURE_REFS: ::DWORD = 0x2; +pub const EOAC_ACCESS_CONTROL: ::DWORD = 0x4; +pub const EOAC_APPID: ::DWORD = 0x8; +pub const EOAC_DYNAMIC: ::DWORD = 0x10; +pub const EOAC_REQUIRE_FULLSIC: ::DWORD = 0x200; +pub const EOAC_AUTO_IMPERSONATE: ::DWORD = 0x400; +pub const EOAC_NO_CUSTOM_MARSHAL: ::DWORD = 0x2000; +pub const EOAC_DISABLE_AAA: ::DWORD = 0x1000; +STRUCT!{struct SOLE_AUTHENTICATION_SERVICE { + dwAuthnSvc: ::DWORD, + dwAuthzSvc: ::DWORD, + pPrincipalName: *mut ::OLECHAR, + hr: ::HRESULT, +}} + +RIDL!( +interface IApartmentShutdown(IApartmentShutdownVtbl): IUnknown(IUnknownVtbl) { + fn OnUninitialize(&mut self, ui64ApartmentIdentifier: ::UINT64) -> ::VOID +} +); + +RIDL!( +interface IMarshal(IMarshalVtbl): IUnknown(IUnknownVtbl) { + fn GetUnmarshalClass( + &mut self, riid: ::REFIID, pv: *const ::VOID, dwDestContext: ::DWORD, + pvDestContext: *const ::VOID, mshlflags: ::DWORD, pCid: *mut ::CLSID + ) -> ::HRESULT, + fn GetMarshalSizeMax( + &mut self, riid: ::REFIID, pv: *const ::VOID, dwDestContext: ::DWORD, + pvDestContext: *const ::VOID, mshlflags: ::DWORD, pSize: *mut ::DWORD + ) -> ::HRESULT, + fn MarshalInterface( + &mut self, pStm: *const ::IStream, riid: ::REFIID, pv: *const ::VOID, + dwDestContext: ::DWORD, pvDestContext: *const ::VOID, + mshlflags: ::DWORD + ) -> ::HRESULT, + fn UnmarshalInterface( + &mut self, pStm: *const ::IStream, riid: ::REFIID, ppv: *mut *mut ::VOID + ) -> ::HRESULT, + fn ReleaseMarshalData(&mut self, pStm: *const ::IStream) -> ::HRESULT, + fn DisconnectObject(&mut self, dwReserved: ::DWORD) -> ::HRESULT +} +); \ No newline at end of file diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/objidlbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/objidlbase.rs new file mode 100644 index 0000000..f49353f --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/objidlbase.rs @@ -0,0 +1,93 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +RIDL!( +interface IMalloc(IMallocVtbl): IUnknown(IUnknownVtbl) { + fn Alloc(&mut self, cb: ::SIZE_T) -> *mut ::c_void, + fn Realloc(&mut self, pv: *mut ::c_void, cb: ::SIZE_T) -> *mut ::c_void, + fn Free(&mut self, pv: *mut ::c_void) -> (), + fn GetSize(&mut self, pv: *mut ::c_void) -> ::SIZE_T, + fn DidAlloc(&mut self, pv: *mut ::c_void) -> ::c_int, + fn HeapMinimize(&mut self) -> () +} +); +pub type LPMALLOC = *mut IMalloc; +STRUCT!{struct STATSTG { + pwcsName: ::LPOLESTR, + type_: ::DWORD, + cbSize: ::ULARGE_INTEGER, + mtime: ::FILETIME, + ctime: ::FILETIME, + atime: ::FILETIME, + grfMode: ::DWORD, + grfLocksSupported: ::DWORD, + clsid: ::CLSID, + grfStateBits: ::DWORD, + reserved: ::DWORD, +}} +//1945 +pub type IEnumString = ::IUnknown; // TODO +//2075 +RIDL!( +interface ISequentialStream(ISequentialStreamVtbl): IUnknown(IUnknownVtbl) { + fn Read(&mut self, pv: *mut ::c_void, cb: ::ULONG, pcbRead: *mut ::ULONG) -> ::HRESULT, + fn Write(&mut self, pv: *const ::c_void, cb: ::ULONG, pcbWritten: *mut ::ULONG) -> ::HRESULT +} +); +ENUM!{enum STGTY { + STGTY_STORAGE = 1, + STGTY_STREAM = 2, + STGTY_LOCKBYTES = 3, + STGTY_PROPERTY = 4, +}} +ENUM!{enum STREAM_SEEK { + STREAM_SEEK_SET = 0, + STREAM_SEEK_CUR = 1, + STREAM_SEEK_END = 2, +}} +ENUM!{enum LOCKTYPE { + LOCK_WRITE = 1, + LOCK_EXCLUSIVE = 2, + LOCK_ONLYONCE = 4, +}} +//2255 +RIDL!( +interface IStream(IStreamVtbl): ISequentialStream(ISequentialStreamVtbl) { + fn Seek( + &mut self, dlibMove: ::LARGE_INTEGER, dwOrigin: ::DWORD, + plibNewPosition: *mut ::ULARGE_INTEGER + ) -> ::HRESULT, + fn SetSize(&mut self, libNewSize: ::ULARGE_INTEGER) -> ::HRESULT, + fn CopyTo( + &mut self, pstm: *mut IStream, cb: ::ULARGE_INTEGER, pcbRead: *mut ::ULARGE_INTEGER, + pcbWritten: *mut ::ULARGE_INTEGER + ) -> ::HRESULT, + fn Commit(&mut self, grfCommitFlags: ::DWORD) -> ::HRESULT, + fn Revert(&mut self) -> ::HRESULT, + fn LockRegion( + &mut self, libOffset: ::ULARGE_INTEGER, cb: ::ULARGE_INTEGER, dwLockType: ::DWORD + ) -> ::HRESULT, + fn UnlockRegion( + &mut self, libOffset: ::ULARGE_INTEGER, cb: ::ULARGE_INTEGER, dwLockType: ::DWORD + ) -> ::HRESULT, + fn Stat(&mut self, pstatstg: *mut STATSTG, grfStatFlag: ::DWORD) -> ::HRESULT, + fn Clone(&mut self, ppstm: *mut *mut IStream) -> ::HRESULT +} +); +pub type LPSTREAM = *mut IStream; +ENUM!{enum APTTYPEQUALIFIER { + APTTYPEQUALIFIER_NONE = 0, + APTTYPEQUALIFIER_IMPLICIT_MTA = 1, + APTTYPEQUALIFIER_NA_ON_MTA = 2, + APTTYPEQUALIFIER_NA_ON_STA = 3, + APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA = 4, + APTTYPEQUALIFIER_NA_ON_MAINSTA = 5, + APTTYPEQUALIFIER_APPLICATION_STA= 6, +}} +ENUM!{enum APTTYPE { + APTTYPE_CURRENT = -1i32 as u32, + APTTYPE_STA = 0, + APTTYPE_MTA = 1, + APTTYPE_NA = 2, + APTTYPE_MAINSTA = 3, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/olectl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/olectl.rs new file mode 100644 index 0000000..b557621 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/olectl.rs @@ -0,0 +1,10 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! OLE Control interfaces +//299 +pub const SELFREG_E_FIRST: ::HRESULT = MAKE_SCODE!(::SEVERITY_ERROR, ::FACILITY_ITF, 0x0200); +pub const SELFREG_E_LAST: ::HRESULT = MAKE_SCODE!(::SEVERITY_ERROR, ::FACILITY_ITF, 0x020F); +pub const SELFREG_S_FIRST: ::HRESULT = MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_ITF, 0x0200); +pub const SELFREG_S_LAST: ::HRESULT = MAKE_SCODE!(::SEVERITY_SUCCESS, ::FACILITY_ITF, 0x020F); +pub const SELFREG_E_TYPELIB: ::HRESULT = SELFREG_E_FIRST + 0; +pub const SELFREG_E_CLASS: ::HRESULT = SELFREG_E_FIRST + 1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/pdh.rs b/third_party/cargo/vendor/winapi-0.2.8/src/pdh.rs new file mode 100644 index 0000000..165fe1e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/pdh.rs @@ -0,0 +1,52 @@ +// Copyright © 2016, Klavs Madsen +// Licensed under the MIT License +//! Common Performance Data Helper definitions +pub const PDH_FMT_RAW: ::DWORD = 0x00000010; +pub const PDH_FMT_ANSI: ::DWORD = 0x00000020; +pub const PDH_FMT_UNICODE: ::DWORD = 0x00000040; +pub const PDH_FMT_LONG: ::DWORD = 0x00000100; +pub const PDH_FMT_DOUBLE: ::DWORD = 0x00000200; +pub const PDH_FMT_LARGE: ::DWORD = 0x00000400; +pub const PDH_FMT_NOSCALE: ::DWORD = 0x00001000; +pub const PDH_FMT_1000: ::DWORD = 0x00002000; +pub const PDH_FMT_NODATA: ::DWORD = 0x00004000; +pub const PDH_FMT_NOCAP100: ::DWORD = 0x00008000; +pub const PERF_DETAIL_COSTLY: ::DWORD = 0x00010000; +pub const PERF_DETAIL_STANDARD: ::DWORD = 0x0000FFFF; + +pub type PDH_STATUS = ::LONG; +pub type PDH_HQUERY = ::HANDLE; +pub type HQUERY = PDH_HQUERY; +pub type PDH_HCOUNTER = ::HANDLE; +pub type HCOUNTER = PDH_HCOUNTER; + +STRUCT!{struct PDH_FMT_COUNTERVALUE { + CStatus: ::DWORD, + largeValue: ::LONGLONG, +}} +UNION!(PDH_FMT_COUNTERVALUE, largeValue, largeValue, largeValue_mut, ::LONGLONG); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, longValue, longValue_mut, ::LONG); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, doubleValue, doubleValue_mut, ::DOUBLE); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, AnsiStringValue, AnsiStringValue_mut, ::LPCSTR); +UNION!(PDH_FMT_COUNTERVALUE, largeValue, WideStringValue, WideStringValue_mut, ::LPCWSTR); +pub type PPDH_FMT_COUNTERVALUE = *mut PDH_FMT_COUNTERVALUE; + +STRUCT!{struct PDH_COUNTER_PATH_ELEMENTS_A { + szMachineName: ::LPSTR, + szObjectName: ::LPSTR, + szInstanceName: ::LPSTR, + szParentInstance: ::LPSTR, + dwInstanceIndex: ::DWORD, + szCounterName: ::LPSTR, +}} +pub type PPDH_COUNTER_PATH_ELEMENTS_A = *mut PDH_COUNTER_PATH_ELEMENTS_A; + +STRUCT!{struct PDH_COUNTER_PATH_ELEMENTS_W { + szMachineName: ::LPWSTR, + szObjectName: ::LPWSTR, + szInstanceName: ::LPWSTR, + szParentInstance: ::LPWSTR, + dwInstanceIndex: ::DWORD, + szCounterName: ::LPWSTR, +}} +pub type PPDH_COUNTER_PATH_ELEMENTS_W = *mut PDH_COUNTER_PATH_ELEMENTS_W; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/playsoundapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/playsoundapi.rs new file mode 100644 index 0000000..99f4501 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/playsoundapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub const SND_SYNC: DWORD = 0x0000; +pub const SND_ASYNC: DWORD = 0x0001; +pub const SND_NODEFAULT: DWORD = 0x0002; +pub const SND_MEMORY: DWORD = 0x0004; +pub const SND_LOOP: DWORD = 0x0008; +pub const SND_NOSTOP: DWORD = 0x0010; +pub const SND_NOWAIT: DWORD = 0x00002000; +pub const SND_ALIAS: DWORD = 0x00010000; +pub const SND_ALIAS_ID: DWORD = 0x00110000; +pub const SND_FILENAME: DWORD = 0x00020000; +pub const SND_RESOURCE: DWORD = 0x00040004; +pub const SND_PURGE: DWORD = 0x0040; +pub const SND_APPLICATION: DWORD = 0x0080; +pub const SND_SENTRY: DWORD = 0x00080000; +pub const SND_RING: DWORD = 0x00100000; +pub const SND_SYSTEM: DWORD = 0x00200000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/processsnapshot.rs b/third_party/cargo/vendor/winapi-0.2.8/src/processsnapshot.rs new file mode 100644 index 0000000..73ea679 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/processsnapshot.rs @@ -0,0 +1,58 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Defines the process snapshot API +FLAGS!{enum PSS_CAPTURE_FLAGS { + PSS_CAPTURE_NONE = 0x00000000, + PSS_CAPTURE_VA_CLONE = 0x00000001, + PSS_CAPTURE_RESERVED_00000002 = 0x00000002, + PSS_CAPTURE_HANDLES = 0x00000004, + PSS_CAPTURE_HANDLE_NAME_INFORMATION = 0x00000008, + PSS_CAPTURE_HANDLE_BASIC_INFORMATION = 0x00000010, + PSS_CAPTURE_HANDLE_TYPE_SPECIFIC_INFORMATION = 0x00000020, + PSS_CAPTURE_HANDLE_TRACE = 0x00000040, + PSS_CAPTURE_THREADS = 0x00000080, + PSS_CAPTURE_THREAD_CONTEXT = 0x00000100, + PSS_CAPTURE_THREAD_CONTEXT_EXTENDED = 0x00000200, + PSS_CAPTURE_RESERVED_00000400 = 0x00000400, + PSS_CAPTURE_VA_SPACE = 0x00000800, + PSS_CAPTURE_VA_SPACE_SECTION_INFORMATION = 0x00001000, + PSS_CREATE_BREAKAWAY_OPTIONAL = 0x04000000, + PSS_CREATE_BREAKAWAY = 0x08000000, + PSS_CREATE_FORCE_BREAKAWAY = 0x10000000, + PSS_CREATE_USE_VM_ALLOCATIONS = 0x20000000, + PSS_CREATE_MEASURE_PERFORMANCE = 0x40000000, + PSS_CREATE_RELEASE_SECTION = -2147483648i32 as u32, +}} +ENUM!{enum PSS_QUERY_INFORMATION_CLASS { + PSS_QUERY_PROCESS_INFORMATION = 0, + PSS_QUERY_VA_CLONE_INFORMATION = 1, + PSS_QUERY_AUXILIARY_PAGES_INFORMATION = 2, + PSS_QUERY_VA_SPACE_INFORMATION = 3, + PSS_QUERY_HANDLE_INFORMATION = 4, + PSS_QUERY_THREAD_INFORMATION = 5, + PSS_QUERY_HANDLE_TRACE_INFORMATION = 6, + PSS_QUERY_PERFORMANCE_COUNTERS = 7, +}} +ENUM!{enum PSS_WALK_INFORMATION_CLASS { + PSS_WALK_AUXILIARY_PAGES = 0, + PSS_WALK_VA_SPACE = 1, + PSS_WALK_HANDLES = 2, + PSS_WALK_THREADS = 3, +}} +FLAGS!{enum PSS_DUPLICATE_FLAGS { + PSS_DUPLICATE_NONE = 0x00, + PSS_DUPLICATE_CLOSE_SOURCE = 0x01, +}} +DECLARE_HANDLE!(HPSS, HPSS__); +DECLARE_HANDLE!(HPSSWALK, HPSSWALK__); +pub type pAllocRoutine = Option *mut ::c_void>; +pub type pFreeRoutine = Option; +STRUCT!{nodebug struct PSS_ALLOCATOR { + Context: *mut ::c_void, + AllocRoutine: pAllocRoutine, + FreeRoutine: pFreeRoutine, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/processthreadsapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/processthreadsapi.rs new file mode 100644 index 0000000..fad58c7 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/processthreadsapi.rs @@ -0,0 +1,62 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +STRUCT!{struct PROCESS_INFORMATION { + hProcess: ::HANDLE, + hThread: ::HANDLE, + dwProcessId: ::DWORD, + dwThreadId: ::DWORD, +}} +pub type PPROCESS_INFORMATION = *mut PROCESS_INFORMATION; +pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; +STRUCT!{struct STARTUPINFOA { + cb: ::DWORD, + lpReserved: ::LPSTR, + lpDesktop: ::LPSTR, + lpTitle: ::LPSTR, + dwX: ::DWORD, + dwY: ::DWORD, + dwXSize: ::DWORD, + dwYSize: ::DWORD, + dwXCountChars: ::DWORD, + dwYCountChars: ::DWORD, + dwFillAttribute: ::DWORD, + dwFlags: ::DWORD, + wShowWindow: ::WORD, + cbReserved2: ::WORD, + lpReserved2: ::LPBYTE, + hStdInput: ::HANDLE, + hStdOutput: ::HANDLE, + hStdError: ::HANDLE, +}} +pub type LPSTARTUPINFOA = *mut STARTUPINFOA; +STRUCT!{struct STARTUPINFOW { + cb: ::DWORD, + lpReserved: ::LPWSTR, + lpDesktop: ::LPWSTR, + lpTitle: ::LPWSTR, + dwX: ::DWORD, + dwY: ::DWORD, + dwXSize: ::DWORD, + dwYSize: ::DWORD, + dwXCountChars: ::DWORD, + dwYCountChars: ::DWORD, + dwFillAttribute: ::DWORD, + dwFlags: ::DWORD, + wShowWindow: ::WORD, + cbReserved2: ::WORD, + lpReserved2: ::LPBYTE, + hStdInput: ::HANDLE, + hStdOutput: ::HANDLE, + hStdError: ::HANDLE, +}} +pub type LPSTARTUPINFOW = *mut STARTUPINFOW; +STRUCT!{struct PROC_THREAD_ATTRIBUTE_LIST { + dummy: *mut ::c_void, +}} +pub type PPROC_THREAD_ATTRIBUTE_LIST = *mut PROC_THREAD_ATTRIBUTE_LIST; +pub type LPPROC_THREAD_ATTRIBUTE_LIST = *mut PROC_THREAD_ATTRIBUTE_LIST; +ENUM!{enum THREAD_INFORMATION_CLASS { + ThreadMemoryPriority, + ThreadAbsoluteCpuPriority, + ThreadInformationClassMax, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/propidl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/propidl.rs new file mode 100644 index 0000000..802bd18 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/propidl.rs @@ -0,0 +1,10 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +STRUCT!{struct PROPVARIANT { + vt: VARTYPE, + wReserved1: WORD, + wReserved2: WORD, + wReserved3: WORD, + data: [u8; 16], +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/propsys.rs b/third_party/cargo/vendor/winapi-0.2.8/src/propsys.rs new file mode 100644 index 0000000..0666fbd --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/propsys.rs @@ -0,0 +1,4 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub type IPropertyDescriptionList = ::IUnknown; // TODO +pub type IPropertyStore = ::IUnknown; // TODO diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/prsht.rs b/third_party/cargo/vendor/winapi-0.2.8/src/prsht.rs new file mode 100644 index 0000000..e1795a1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/prsht.rs @@ -0,0 +1,262 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Interface for the Windows Property Sheet Pages +pub enum PSP {} +pub type HPROPSHEETPAGE = *mut PSP; +pub type LPFNPSPCALLBACKA = Option ::UINT>; +pub type LPFNPSPCALLBACKW = Option ::UINT>; +pub const PSP_DEFAULT: ::DWORD = 0x00000000; +pub const PSP_DLGINDIRECT: ::DWORD = 0x00000001; +pub const PSP_USEHICON: ::DWORD = 0x00000002; +pub const PSP_USEICONID: ::DWORD = 0x00000004; +pub const PSP_USETITLE: ::DWORD = 0x00000008; +pub const PSP_RTLREADING: ::DWORD = 0x00000010; +pub const PSP_HASHELP: ::DWORD = 0x00000020; +pub const PSP_USEREFPARENT: ::DWORD = 0x00000040; +pub const PSP_USECALLBACK: ::DWORD = 0x00000080; +pub const PSP_PREMATURE: ::DWORD = 0x00000400; +pub const PSP_HIDEHEADER: ::DWORD = 0x00000800; +pub const PSP_USEHEADERTITLE: ::DWORD = 0x00001000; +pub const PSP_USEHEADERSUBTITLE: ::DWORD = 0x00002000; +pub const PSP_USEFUSIONCONTEXT: ::DWORD = 0x00004000; +pub const PSPCB_ADDREF: ::UINT = 0; +pub const PSPCB_RELEASE: ::UINT = 1; +pub const PSPCB_CREATE: ::UINT = 2; +pub type PROPSHEETPAGE_RESOURCE = ::LPCDLGTEMPLATEA; +STRUCT!{nodebug struct PROPSHEETPAGEA_V4 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hInstance: ::HINSTANCE, + pszTemplate: ::LPCSTR, + hIcon: ::HICON, + pszTitle: ::LPCSTR, + pfnDlgProc: ::DLGPROC, + lParam: ::LPARAM, + pfnCallback: LPFNPSPCALLBACKA, + pcRefParent: *mut ::UINT, + pszHeaderTitle: ::LPCSTR, + pszHeaderSubTitle: ::LPCSTR, + hActCtx: ::HANDLE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETPAGEA_V4, pszTemplate, pResource, pResource_mut, PROPSHEETPAGE_RESOURCE); +UNION!(PROPSHEETPAGEA_V4, hIcon, pszIcon, pszIcon_mut, ::LPCSTR); +UNION!(PROPSHEETPAGEA_V4, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCSTR); +pub type LPPROPSHEETPAGEA_V4 = *mut PROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEA_V4 = *const PROPSHEETPAGEA_V4; +STRUCT!{nodebug struct PROPSHEETPAGEW_V4 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hInstance: ::HINSTANCE, + pszTemplate: ::LPCWSTR, + hIcon: ::HICON, + pszTitle: ::LPCWSTR, + pfnDlgProc: ::DLGPROC, + lParam: ::LPARAM, + pfnCallback: LPFNPSPCALLBACKW, + pcRefParent: *mut ::UINT, + pszHeaderTitle: ::LPCWSTR, + pszHeaderSubTitle: ::LPCWSTR, + hActCtx: ::HANDLE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETPAGEW_V4, pszTemplate, pResource, pResource_mut, PROPSHEETPAGE_RESOURCE); +UNION!(PROPSHEETPAGEW_V4, hIcon, pszIcon, pszIcon_mut, ::LPCWSTR); +UNION!(PROPSHEETPAGEW_V4, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCWSTR); +pub type LPPROPSHEETPAGEW_V4 = *mut PROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEW_V4 = *const PROPSHEETPAGEW_V4; +pub type PROPSHEETPAGEA_LATEST = PROPSHEETPAGEA_V4; +pub type PROPSHEETPAGEW_LATEST = PROPSHEETPAGEW_V4; +pub type LPPROPSHEETPAGEA_LATEST = LPPROPSHEETPAGEA_V4; +pub type LPPROPSHEETPAGEW_LATEST = LPPROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEA_LATEST = LPCPROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEW_LATEST = LPCPROPSHEETPAGEW_V4; +pub type PROPSHEETPAGEA = PROPSHEETPAGEA_V4; +pub type PROPSHEETPAGEW = PROPSHEETPAGEW_V4; +pub type LPPROPSHEETPAGEA = LPPROPSHEETPAGEA_V4; +pub type LPPROPSHEETPAGEW = LPPROPSHEETPAGEW_V4; +pub type LPCPROPSHEETPAGEA = LPCPROPSHEETPAGEA_V4; +pub type LPCPROPSHEETPAGEW = LPCPROPSHEETPAGEW_V4; +pub const PSH_DEFAULT: ::DWORD = 0x00000000; +pub const PSH_PROPTITLE: ::DWORD = 0x00000001; +pub const PSH_USEHICON: ::DWORD = 0x00000002; +pub const PSH_USEICONID: ::DWORD = 0x00000004; +pub const PSH_PROPSHEETPAGE: ::DWORD = 0x00000008; +pub const PSH_WIZARDHASFINISH: ::DWORD = 0x00000010; +pub const PSH_WIZARD: ::DWORD = 0x00000020; +pub const PSH_USEPSTARTPAGE: ::DWORD = 0x00000040; +pub const PSH_NOAPPLYNOW: ::DWORD = 0x00000080; +pub const PSH_USECALLBACK: ::DWORD = 0x00000100; +pub const PSH_HASHELP: ::DWORD = 0x00000200; +pub const PSH_MODELESS: ::DWORD = 0x00000400; +pub const PSH_RTLREADING: ::DWORD = 0x00000800; +pub const PSH_WIZARDCONTEXTHELP: ::DWORD = 0x00001000; +pub const PSH_WIZARD97: ::DWORD = 0x01000000; +pub const PSH_WATERMARK: ::DWORD = 0x00008000; +pub const PSH_USEHBMWATERMARK: ::DWORD = 0x00010000; +pub const PSH_USEHPLWATERMARK: ::DWORD = 0x00020000; +pub const PSH_STRETCHWATERMARK: ::DWORD = 0x00040000; +pub const PSH_HEADER: ::DWORD = 0x00080000; +pub const PSH_USEHBMHEADER: ::DWORD = 0x00100000; +pub const PSH_USEPAGELANG: ::DWORD = 0x00200000; +pub const PSH_WIZARD_LITE: ::DWORD = 0x00400000; +pub const PSH_NOCONTEXTHELP: ::DWORD = 0x02000000; +pub const PSH_AEROWIZARD: ::DWORD = 0x00004000; +pub const PSH_RESIZABLE: ::DWORD = 0x04000000; +pub const PSH_HEADERBITMAP: ::DWORD = 0x08000000; +pub const PSH_NOMARGIN: ::DWORD = 0x10000000; +pub type PFNPROPSHEETCALLBACK = Option ::c_int>; +STRUCT!{nodebug struct PROPSHEETHEADERA_V2 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + pszCaption: ::LPCSTR, + nPages: ::UINT, + pStartPage: ::LPCSTR, + ppsp: LPCPROPSHEETPAGEA, + pfnCallback: PFNPROPSHEETCALLBACK, + hbmWatermark: ::HBITMAP, + hplWatermark: ::HPALETTE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETHEADERA_V2, hIcon, pszIcon, pszIcon_mut, ::LPCSTR); +UNION!(PROPSHEETHEADERA_V2, pStartPage, nStartPage, nStartPage_mut, ::UINT); +UNION!(PROPSHEETHEADERA_V2, ppsp, phpage, phpage_mut, *mut HPROPSHEETPAGE); +UNION!(PROPSHEETHEADERA_V2, hbmWatermark, pszbmWatermark, pszbmWatermark_mut, ::LPCSTR); +UNION!(PROPSHEETHEADERA_V2, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCSTR); +pub type LPPROPSHEETHEADERA_V2 = *mut PROPSHEETHEADERA_V2; +pub type LPCPROPSHEETHEADERA_V2 = *const PROPSHEETHEADERA_V2; +STRUCT!{nodebug struct PROPSHEETHEADERW_V2 { + dwSize: ::DWORD, + dwFlags: ::DWORD, + hwndParent: ::HWND, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + pszCaption: ::LPCWSTR, + nPages: ::UINT, + pStartPage: ::LPCWSTR, + ppsp: LPCPROPSHEETPAGEW, + pfnCallback: PFNPROPSHEETCALLBACK, + hbmWatermark: ::HBITMAP, + hplWatermark: ::HPALETTE, + hbmHeader: ::HBITMAP, +}} +UNION!(PROPSHEETHEADERW_V2, hIcon, pszIcon, pszIcon_mut, ::LPCWSTR); +UNION!(PROPSHEETHEADERW_V2, pStartPage, nStartPage, nStartPage_mut, ::UINT); +UNION!(PROPSHEETHEADERW_V2, ppsp, phpage, phpage_mut, *mut HPROPSHEETPAGE); +UNION!(PROPSHEETHEADERW_V2, hbmWatermark, pszbmWatermark, pszbmWatermark_mut, ::LPCWSTR); +UNION!(PROPSHEETHEADERW_V2, hbmHeader, pszbmHeader, pszbmHeader_mut, ::LPCWSTR); +pub type LPPROPSHEETHEADERW_V2 = *mut PROPSHEETHEADERW_V2; +pub type LPCPROPSHEETHEADERW_V2 = *const PROPSHEETHEADERW_V2; +pub type PROPSHEETHEADERA = PROPSHEETHEADERA_V2; +pub type PROPSHEETHEADERW = PROPSHEETHEADERW_V2; +pub type LPPROPSHEETHEADERA = LPPROPSHEETHEADERA_V2; +pub type LPPROPSHEETHEADERW = LPPROPSHEETHEADERW_V2; +pub type LPCPROPSHEETHEADERA = LPCPROPSHEETHEADERA_V2; +pub type LPCPROPSHEETHEADERW = LPCPROPSHEETHEADERW_V2; +pub const PSCB_INITIALIZED: ::UINT = 1; +pub const PSCB_PRECREATE: ::UINT = 2; +pub const PSCB_BUTTONPRESSED: ::UINT = 3; +pub type LPFNADDPROPSHEETPAGE = Option ::BOOL>; +pub type LPFNADDPROPSHEETPAGES = Option ::BOOL>; +STRUCT!{struct PSHNOTIFY { + hdr: ::NMHDR, + lParam: ::LPARAM, +}} +pub type LPPSHNOTIFY = *mut PSHNOTIFY; +pub const PSN_FIRST: ::UINT = -200i32 as ::UINT; +pub const PSN_LAST: ::UINT = -299i32 as ::UINT; +pub const PSN_SETACTIVE: ::UINT = PSN_FIRST - 0; +pub const PSN_KILLACTIVE: ::UINT = PSN_FIRST - 1; +pub const PSN_APPLY: ::UINT = PSN_FIRST - 2; +pub const PSN_RESET: ::UINT = PSN_FIRST - 3; +pub const PSN_HELP: ::UINT = PSN_FIRST - 5; +pub const PSN_WIZBACK: ::UINT = PSN_FIRST - 6; +pub const PSN_WIZNEXT: ::UINT = PSN_FIRST - 7; +pub const PSN_WIZFINISH: ::UINT = PSN_FIRST - 8; +pub const PSN_QUERYCANCEL: ::UINT = PSN_FIRST - 9; +pub const PSN_GETOBJECT: ::UINT = PSN_FIRST - 10; +pub const PSN_TRANSLATEACCELERATOR: ::UINT = PSN_FIRST - 12; +pub const PSN_QUERYINITIALFOCUS: ::UINT = PSN_FIRST - 13; +pub const PSNRET_NOERROR: ::LRESULT = 0; +pub const PSNRET_INVALID: ::LRESULT = 1; +pub const PSNRET_INVALID_NOCHANGEPAGE: ::LRESULT = 2; +pub const PSNRET_MESSAGEHANDLED: ::LRESULT = 3; +pub const PSM_SETCURSEL: ::UINT = ::WM_USER + 101; +pub const PSM_REMOVEPAGE: ::UINT = ::WM_USER + 102; +pub const PSM_ADDPAGE: ::UINT = ::WM_USER + 103; +pub const PSM_CHANGED: ::UINT = ::WM_USER + 104; +pub const PSM_RESTARTWINDOWS: ::UINT = ::WM_USER + 105; +pub const PSM_REBOOTSYSTEM: ::UINT = ::WM_USER + 106; +pub const PSM_CANCELTOCLOSE: ::UINT = ::WM_USER + 107; +pub const PSM_QUERYSIBLINGS: ::UINT = ::WM_USER + 108; +pub const PSM_UNCHANGED: ::UINT = ::WM_USER + 109; +pub const PSM_APPLY: ::UINT = ::WM_USER + 110; +pub const PSM_SETTITLEA: ::UINT = ::WM_USER + 111; +pub const PSM_SETTITLEW: ::UINT = ::WM_USER + 120; +pub const PSM_SETWIZBUTTONS: ::UINT = ::WM_USER + 112; +pub const PSWIZB_BACK: ::DWORD = 0x00000001; +pub const PSWIZB_NEXT: ::DWORD = 0x00000002; +pub const PSWIZB_FINISH: ::DWORD = 0x00000004; +pub const PSWIZB_DISABLEDFINISH: ::DWORD = 0x00000008; +pub const PSWIZB_CANCEL: ::DWORD = 0x00000008; +pub const PSWIZBF_ELEVATIONREQUIRED: ::WPARAM = 0x00000001; +pub const PSBTN_BACK: ::c_int = 0; +pub const PSBTN_NEXT: ::c_int = 1; +pub const PSBTN_FINISH: ::c_int = 2; +pub const PSBTN_OK: ::c_int = 3; +pub const PSBTN_APPLYNOW: ::c_int = 4; +pub const PSBTN_CANCEL: ::c_int = 5; +pub const PSBTN_HELP: ::c_int = 6; +pub const PSBTN_MAX: ::c_int = 6; +pub const PSM_PRESSBUTTON: ::UINT = ::WM_USER + 113; +pub const PSM_SETCURSELID: ::UINT = ::WM_USER + 114; +pub const PSM_SETFINISHTEXTA: ::UINT = ::WM_USER + 115; +pub const PSM_SETFINISHTEXTW: ::UINT = ::WM_USER + 121; +pub const PSM_GETTABCONTROL: ::UINT = ::WM_USER + 116; +pub const PSM_ISDIALOGMESSAGE: ::UINT = ::WM_USER + 117; +pub const PSM_GETCURRENTPAGEHWND: ::UINT = ::WM_USER + 118; +pub const PSM_INSERTPAGE: ::UINT = ::WM_USER + 119; +pub const PSM_SETHEADERTITLEA: ::UINT = ::WM_USER + 125; +pub const PSM_SETHEADERTITLEW: ::UINT = ::WM_USER + 126; +pub const PSWIZF_SETCOLOR: ::UINT = (0 - 1) as ::UINT; +pub const PSM_SETHEADERSUBTITLEA: ::UINT = ::WM_USER + 127; +pub const PSM_SETHEADERSUBTITLEW: ::UINT = ::WM_USER + 128; +pub const PSM_HWNDTOINDEX: ::UINT = ::WM_USER + 129; +pub const PSM_INDEXTOHWND: ::UINT = ::WM_USER + 130; +pub const PSM_PAGETOINDEX: ::UINT = ::WM_USER + 131; +pub const PSM_INDEXTOPAGE: ::UINT = ::WM_USER + 132; +pub const PSM_IDTOINDEX: ::UINT = ::WM_USER + 133; +pub const PSM_INDEXTOID: ::UINT = ::WM_USER + 134; +pub const PSM_GETRESULT: ::UINT = ::WM_USER + 135; +pub const PSM_RECALCPAGESIZES: ::UINT = ::WM_USER + 136; +pub const PSM_SETNEXTTEXTW: ::UINT = ::WM_USER + 137; +pub const PSM_SHOWWIZBUTTONS: ::UINT = ::WM_USER + 138; +pub const PSM_ENABLEWIZBUTTONS: ::UINT = ::WM_USER + 139; +pub const PSM_SETBUTTONTEXTW: ::UINT = ::WM_USER + 140; +pub const PSM_SETBUTTONTEXT: ::UINT = PSM_SETBUTTONTEXTW; +pub const ID_PSRESTARTWINDOWS: ::INT_PTR = 0x2; +pub const ID_PSREBOOTSYSTEM: ::INT_PTR = ID_PSRESTARTWINDOWS | 0x1; +pub const WIZ_CXDLG: ::DWORD = 276; +pub const WIZ_CYDLG: ::DWORD = 140; +pub const WIZ_CXBMP: ::DWORD = 80; +pub const WIZ_BODYX: ::DWORD = 92; +pub const WIZ_BODYCX: ::DWORD = 184; +pub const PROP_SM_CXDLG: ::c_short = 212; +pub const PROP_SM_CYDLG: ::c_short = 188; +pub const PROP_MED_CXDLG: ::c_short = 227; +pub const PROP_MED_CYDLG: ::c_short = 215; +pub const PROP_LG_CXDLG: ::c_short = 252; +pub const PROP_LG_CYDLG: ::c_short = 218; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/psapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/psapi.rs new file mode 100644 index 0000000..801d35c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/psapi.rs @@ -0,0 +1,166 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! API Prototypes and Definitions for PSAPI.DLL +pub const LIST_MODULES_DEFAULT: ::DWORD = 0x0; +pub const LIST_MODULES_32BIT: ::DWORD = 0x01; +pub const LIST_MODULES_64BIT: ::DWORD = 0x02; +pub const LIST_MODULES_ALL: ::DWORD = LIST_MODULES_32BIT | LIST_MODULES_64BIT; +STRUCT!{struct MODULEINFO { + lpBaseOfDll: ::LPVOID, + SizeOfImage: ::DWORD, + EntryPoint: ::LPVOID, +}} +pub type LPMODULEINFO = *mut MODULEINFO; +STRUCT!{struct PSAPI_WORKING_SET_BLOCK { + Flags: ::ULONG_PTR, + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_BLOCK BitFields: ::ULONG_PTR [ + Protection set_Protection[0..5], + ShareCount set_ShareCount[5..8], + Shared set_Shared[8..9], + Reserved set_Reserved[9..12], + VirtualPage set_VirtualPage[12..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_BLOCK BitFields: ::ULONG_PTR [ + Protection set_Protection[0..5], + ShareCount set_ShareCount[5..8], + Shared set_Shared[8..9], + Reserved set_Reserved[9..12], + VirtualPage set_VirtualPage[12..64], +]); +pub type PPSAPI_WORKING_SET_BLOCK = *mut PSAPI_WORKING_SET_BLOCK; +STRUCT!{struct PSAPI_WORKING_SET_INFORMATION { + NumberOfEntries: ::ULONG_PTR, + WorkingSetInfo: [PSAPI_WORKING_SET_BLOCK; 1], +}} +pub type PPSAPI_WORKING_SET_INFORMATION = *mut PSAPI_WORKING_SET_INFORMATION; +STRUCT!{struct PSAPI_WORKING_SET_EX_BLOCK_Invalid { + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK_Invalid BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + Reserved0 set_Reserved0[1..15], + Shared set_Shared[15..16], + Reserved1 set_Reserved1[16..31], + Bad set_Bad[31..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK_Invalid BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + Reserved0 set_Reserved0[1..15], + Shared set_Shared[15..16], + Reserved1 set_Reserved1[16..31], + Bad set_Bad[31..32], + ReservedUlong set_ReservedUlong[32..64], +]); +STRUCT!{struct PSAPI_WORKING_SET_EX_BLOCK { + Flags: ::ULONG_PTR, + BitFields: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + ShareCount set_ShareCount[1..4], + Win32Protection set_Win32Protection[4..15], + Shared set_Shared[15..16], + Node set_Node[16..22], + Locked set_Locked[22..23], + LargePage set_LargePage[23..24], + Reserved set_Reserved[24..31], + Bad set_Bad[31..32], +]); +#[cfg(target_arch="x86_64")] +BITFIELD!(PSAPI_WORKING_SET_EX_BLOCK BitFields: ::ULONG_PTR [ + Valid set_Valid[0..1], + ShareCount set_ShareCount[1..4], + Win32Protection set_Win32Protection[4..15], + Shared set_Shared[15..16], + Node set_Node[16..22], + Locked set_Locked[22..23], + LargePage set_LargePage[23..24], + Reserved set_Reserved[24..31], + Bad set_Bad[31..32], + ReservedUlong set_ReservedUlong[32..64], +]); +UNION!( + PSAPI_WORKING_SET_EX_BLOCK, BitFields, Invalid, Invalid_mut, PSAPI_WORKING_SET_EX_BLOCK_Invalid +); +pub type PPSAPI_WORKING_SET_EX_BLOCK = *mut PSAPI_WORKING_SET_EX_BLOCK; +STRUCT!{struct PSAPI_WORKING_SET_EX_INFORMATION { + VirtualAddress: ::PVOID, + VirtualAttributes: PSAPI_WORKING_SET_EX_BLOCK, +}} +pub type PPSAPI_WORKING_SET_EX_INFORMATION = *mut PSAPI_WORKING_SET_EX_INFORMATION; +STRUCT!{struct PSAPI_WS_WATCH_INFORMATION { + FaultingPc: ::LPVOID, + FaultingVa: ::LPVOID, +}} +pub type PPSAPI_WS_WATCH_INFORMATION = *mut PSAPI_WS_WATCH_INFORMATION; +STRUCT!{struct PSAPI_WS_WATCH_INFORMATION_EX { + BasicInfo: PSAPI_WS_WATCH_INFORMATION, + FaultingThreadId: ::ULONG_PTR, + Flags: ::ULONG_PTR, +}} +pub type PPSAPI_WS_WATCH_INFORMATION_EX = *mut PSAPI_WS_WATCH_INFORMATION_EX; +STRUCT!{struct PROCESS_MEMORY_COUNTERS { + cb: ::DWORD, + PageFaultCount: ::DWORD, + PeakWorkingSetSize: ::SIZE_T, + WorkingSetSize: ::SIZE_T, + QuotaPeakPagedPoolUsage: ::SIZE_T, + QuotaPagedPoolUsage: ::SIZE_T, + QuotaPeakNonPagedPoolUsage: ::SIZE_T, + QuotaNonPagedPoolUsage: ::SIZE_T, + PagefileUsage: ::SIZE_T, + PeakPagefileUsage: ::SIZE_T, +}} +pub type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS; +STRUCT!{struct PROCESS_MEMORY_COUNTERS_EX { + cb: ::DWORD, + PageFaultCount: ::DWORD, + PeakWorkingSetSize: ::SIZE_T, + WorkingSetSize: ::SIZE_T, + QuotaPeakPagedPoolUsage: ::SIZE_T, + QuotaPagedPoolUsage: ::SIZE_T, + QuotaPeakNonPagedPoolUsage: ::SIZE_T, + QuotaNonPagedPoolUsage: ::SIZE_T, + PagefileUsage: ::SIZE_T, + PeakPagefileUsage: ::SIZE_T, + PrivateUsage: ::SIZE_T, +}} +pub type PPROCESS_MEMORY_COUNTERS_EX = *mut PROCESS_MEMORY_COUNTERS_EX; +STRUCT!{struct PERFORMANCE_INFORMATION { + cb: ::DWORD, + CommitTotal: ::SIZE_T, + CommitLimit: ::SIZE_T, + CommitPeak: ::SIZE_T, + PhysicalTotal: ::SIZE_T, + PhysicalAvailable: ::SIZE_T, + SystemCache: ::SIZE_T, + KernelTotal: ::SIZE_T, + KernelPaged: ::SIZE_T, + KernelNonpaged: ::SIZE_T, + PageSize: ::SIZE_T, + HandleCount: ::DWORD, + ProcessCount: ::DWORD, + ThreadCount: ::DWORD, +}} +pub type PPERFORMANCE_INFORMATION = *mut PERFORMANCE_INFORMATION; +STRUCT!{struct ENUM_PAGE_FILE_INFORMATION { + cb: ::DWORD, + Reserved: ::DWORD, + TotalSize: ::SIZE_T, + TotalInUse: ::SIZE_T, + PeakUsage: ::SIZE_T, +}} +pub type PENUM_PAGE_FILE_INFORMATION = *mut ENUM_PAGE_FILE_INFORMATION; +pub type PENUM_PAGE_FILE_CALLBACKA = Option ::BOOL>; +pub type PENUM_PAGE_FILE_CALLBACKW = Option ::BOOL>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/qos.rs b/third_party/cargo/vendor/winapi-0.2.8/src/qos.rs new file mode 100644 index 0000000..91026b3 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/qos.rs @@ -0,0 +1,16 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! QoS definitions for NDIS components. +pub type SERVICETYPE = ::ULONG; +STRUCT!{struct FLOWSPEC { + TokenRate: ::ULONG, + TokenBucketSize: ::ULONG, + PeakBandwidth: ::ULONG, + Latency: ::ULONG, + DelayVariation: ::ULONG, + ServiceType: SERVICETYPE, + MaxSduSize: ::ULONG, + MinimumPolicedSize: ::ULONG, +}} +pub type PFLOWSPEC = *mut FLOWSPEC; +pub type LPFLOWSPEC = *mut FLOWSPEC; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/reason.rs b/third_party/cargo/vendor/winapi-0.2.8/src/reason.rs new file mode 100644 index 0000000..66b3ed3 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/reason.rs @@ -0,0 +1,63 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +// Flags used by the various UIs +pub const SHTDN_REASON_FLAG_COMMENT_REQUIRED: ::DWORD = 0x01000000; +pub const SHTDN_REASON_FLAG_DIRTY_PROBLEM_ID_REQUIRED: ::DWORD = 0x02000000; +pub const SHTDN_REASON_FLAG_CLEAN_UI: ::DWORD = 0x04000000; +pub const SHTDN_REASON_FLAG_DIRTY_UI: ::DWORD = 0x08000000; +// Flags that end up in the event log code. +pub const SHTDN_REASON_FLAG_USER_DEFINED: ::DWORD = 0x40000000; +pub const SHTDN_REASON_FLAG_PLANNED: ::DWORD = 0x80000000; +// Microsoft major reasons. +pub const SHTDN_REASON_MAJOR_OTHER: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MAJOR_NONE: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MAJOR_HARDWARE: ::DWORD = 0x00010000; +pub const SHTDN_REASON_MAJOR_OPERATINGSYSTEM: ::DWORD = 0x00020000; +pub const SHTDN_REASON_MAJOR_SOFTWARE: ::DWORD = 0x00030000; +pub const SHTDN_REASON_MAJOR_APPLICATION: ::DWORD = 0x00040000; +pub const SHTDN_REASON_MAJOR_SYSTEM: ::DWORD = 0x00050000; +pub const SHTDN_REASON_MAJOR_POWER: ::DWORD = 0x00060000; +pub const SHTDN_REASON_MAJOR_LEGACY_API: ::DWORD = 0x00070000; +// Microsoft minor reasons. +pub const SHTDN_REASON_MINOR_OTHER: ::DWORD = 0x00000000; +pub const SHTDN_REASON_MINOR_NONE: ::DWORD = 0x000000ff; +pub const SHTDN_REASON_MINOR_MAINTENANCE: ::DWORD = 0x00000001; +pub const SHTDN_REASON_MINOR_INSTALLATION: ::DWORD = 0x00000002; +pub const SHTDN_REASON_MINOR_UPGRADE: ::DWORD = 0x00000003; +pub const SHTDN_REASON_MINOR_RECONFIG: ::DWORD = 0x00000004; +pub const SHTDN_REASON_MINOR_HUNG: ::DWORD = 0x00000005; +pub const SHTDN_REASON_MINOR_UNSTABLE: ::DWORD = 0x00000006; +pub const SHTDN_REASON_MINOR_DISK: ::DWORD = 0x00000007; +pub const SHTDN_REASON_MINOR_PROCESSOR: ::DWORD = 0x00000008; +pub const SHTDN_REASON_MINOR_NETWORKCARD: ::DWORD = 0x00000009; +pub const SHTDN_REASON_MINOR_POWER_SUPPLY: ::DWORD = 0x0000000a; +pub const SHTDN_REASON_MINOR_CORDUNPLUGGED: ::DWORD = 0x0000000b; +pub const SHTDN_REASON_MINOR_ENVIRONMENT: ::DWORD = 0x0000000c; +pub const SHTDN_REASON_MINOR_HARDWARE_DRIVER: ::DWORD = 0x0000000d; +pub const SHTDN_REASON_MINOR_OTHERDRIVER: ::DWORD = 0x0000000e; +pub const SHTDN_REASON_MINOR_BLUESCREEN: ::DWORD = 0x0000000F; +pub const SHTDN_REASON_MINOR_SERVICEPACK: ::DWORD = 0x00000010; +pub const SHTDN_REASON_MINOR_HOTFIX: ::DWORD = 0x00000011; +pub const SHTDN_REASON_MINOR_SECURITYFIX: ::DWORD = 0x00000012; +pub const SHTDN_REASON_MINOR_SECURITY: ::DWORD = 0x00000013; +pub const SHTDN_REASON_MINOR_NETWORK_CONNECTIVITY: ::DWORD = 0x00000014; +pub const SHTDN_REASON_MINOR_WMI: ::DWORD = 0x00000015; +pub const SHTDN_REASON_MINOR_SERVICEPACK_UNINSTALL: ::DWORD = 0x00000016; +pub const SHTDN_REASON_MINOR_HOTFIX_UNINSTALL: ::DWORD = 0x00000017; +pub const SHTDN_REASON_MINOR_SECURITYFIX_UNINSTALL: ::DWORD = 0x00000018; +pub const SHTDN_REASON_MINOR_MMC: ::DWORD = 0x00000019; +pub const SHTDN_REASON_MINOR_SYSTEMRESTORE: ::DWORD = 0x0000001a; +pub const SHTDN_REASON_MINOR_TERMSRV: ::DWORD = 0x00000020; +pub const SHTDN_REASON_MINOR_DC_PROMOTION: ::DWORD = 0x00000021; +pub const SHTDN_REASON_MINOR_DC_DEMOTION: ::DWORD = 0x00000022; +pub const SHTDN_REASON_UNKNOWN: ::DWORD = SHTDN_REASON_MINOR_NONE; +pub const SHTDN_REASON_LEGACY_API: ::DWORD = + (SHTDN_REASON_MAJOR_LEGACY_API | SHTDN_REASON_FLAG_PLANNED); +// This mask cuts out UI flags. +pub const SHTDN_REASON_VALID_BIT_MASK: ::DWORD = 0xc0ffffff; +// Convenience flags. +pub const PCLEANUI: ::DWORD = (SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_FLAG_CLEAN_UI); +pub const UCLEANUI: ::DWORD = (SHTDN_REASON_FLAG_CLEAN_UI); +pub const PDIRTYUI: ::DWORD = (SHTDN_REASON_FLAG_PLANNED | SHTDN_REASON_FLAG_DIRTY_UI); +pub const UDIRTYUI: ::DWORD = (SHTDN_REASON_FLAG_DIRTY_UI); +//89 diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/restrictederrorinfo.rs b/third_party/cargo/vendor/winapi-0.2.8/src/restrictederrorinfo.rs new file mode 100644 index 0000000..94fbb77 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/restrictederrorinfo.rs @@ -0,0 +1,9 @@ +RIDL!( +interface IRestrictedErrorInfo(IRestrictedErrorInfoVtbl): IUnknown(IUnknownVtbl) { + fn GetErrorDetails( + &mut self, description: *mut ::BSTR, error: *mut ::HRESULT, + restrictedDescription: *mut ::BSTR, capabilitySid: *mut ::BSTR + ) -> ::HRESULT, + fn GetReference(&mut self, reference: *mut ::BSTR) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/roapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/roapi.rs new file mode 100644 index 0000000..db8d5df --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/roapi.rs @@ -0,0 +1,13 @@ +ENUM!{enum RO_INIT_TYPE { + RO_INIT_SINGLETHREADED = 0, + RO_INIT_MULTITHREADED = 1, +}} + +pub enum RO_REGISTRATION_COOKIE__{} +pub type RO_REGISTRATION_COOKIE = *mut RO_REGISTRATION_COOKIE__; + +pub type PFNGETACTIVATIONFACTORY = Option ::HRESULT>; + +DECLARE_HANDLE!(APARTMENT_SHUTDOWN_REGISTRATION_COOKIE, APARTMENT_SHUTDOWN_REGISTRATION_COOKIE__); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/roerrorapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/roerrorapi.rs new file mode 100644 index 0000000..9a0cbcc --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/roerrorapi.rs @@ -0,0 +1,11 @@ +FLAGS!{enum RO_ERROR_REPORTING_FLAGS { + RO_ERROR_REPORTING_NONE = 0x00000000, + RO_ERROR_REPORTING_SUPPRESSEXCEPTIONS = 0x00000001, + RO_ERROR_REPORTING_FORCEEXCEPTIONS = 0x00000002, + RO_ERROR_REPORTING_USESETERRORINFO = 0x00000004, + RO_ERROR_REPORTING_SUPPRESSSETERRORINFO = 0x00000008, +}} + +pub type PINSPECT_MEMORY_CALLBACK = Option ::HRESULT>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/rpc.rs b/third_party/cargo/vendor/winapi-0.2.8/src/rpc.rs new file mode 100644 index 0000000..0b013d3 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/rpc.rs @@ -0,0 +1,5 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// Master include file for RPC applications. +pub type I_RPC_HANDLE = *mut ::c_void; +pub type RPC_STATUS = ::c_long; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/rpcdce.rs b/third_party/cargo/vendor/winapi-0.2.8/src/rpcdce.rs new file mode 100644 index 0000000..68d88c7 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/rpcdce.rs @@ -0,0 +1,535 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License +// This module contains the DCE RPC runtime APIs. +pub type RPC_CSTR = *mut ::c_uchar; +pub type RPC_WSTR = *mut ::wchar_t; +pub type RPC_CWSTR = *const ::wchar_t; +pub type RPC_BINDING_HANDLE = ::I_RPC_HANDLE; +pub type handle_t = RPC_BINDING_HANDLE; +pub type rpc_binding_handle_t = RPC_BINDING_HANDLE; +pub type UUID = ::GUID; +pub type uuid_t = UUID; +STRUCT!{struct RPC_BINDING_VECTOR { + Count: ::c_ulong, + BindingH: [RPC_BINDING_HANDLE; 1], +}} +pub type rpc_binding_vector_t = RPC_BINDING_VECTOR; +STRUCT!{struct UUID_VECTOR { + Count: ::c_ulong, + Uuid: [*mut UUID; 1], +}} +pub type uuid_vector_t = UUID_VECTOR; +pub type RPC_IF_HANDLE = *mut ::c_void; +STRUCT!{struct RPC_IF_ID { + Uuid: UUID, + VersMajor: ::c_ushort, + VersMinor: ::c_ushort, +}} +pub const RPC_C_BINDING_INFINITE_TIMEOUT: ::DWORD = 10; +pub const RPC_C_BINDING_MIN_TIMEOUT: ::DWORD = 0; +pub const RPC_C_BINDING_DEFAULT_TIMEOUT: ::DWORD = 5; +pub const RPC_C_BINDING_MAX_TIMEOUT: ::DWORD = 9; +pub const RPC_C_CANCEL_INFINITE_TIMEOUT: ::c_int = -1; +pub const RPC_C_LISTEN_MAX_CALLS_DEFAULT: ::DWORD = 1234; +pub const RPC_C_PROTSEQ_MAX_REQS_DEFAULT: ::DWORD = 10; +pub const RPC_C_BIND_TO_ALL_NICS: ::DWORD = 1; +pub const RPC_C_USE_INTERNET_PORT: ::DWORD = 0x1; +pub const RPC_C_USE_INTRANET_PORT: ::DWORD = 0x2; +pub const RPC_C_DONT_FAIL: ::DWORD = 0x4; +pub const RPC_C_RPCHTTP_USE_LOAD_BALANCE: ::DWORD = 0x8; +pub const RPC_C_MQ_TEMPORARY: ::DWORD = 0x0000; +pub const RPC_C_MQ_PERMANENT: ::DWORD = 0x0001; +pub const RPC_C_MQ_CLEAR_ON_OPEN: ::DWORD = 0x0002; +pub const RPC_C_MQ_USE_EXISTING_SECURITY: ::DWORD = 0x0004; +pub const RPC_C_MQ_AUTHN_LEVEL_NONE: ::DWORD = 0x0000; +pub const RPC_C_MQ_AUTHN_LEVEL_PKT_INTEGRITY: ::DWORD = 0x0008; +pub const RPC_C_MQ_AUTHN_LEVEL_PKT_PRIVACY: ::DWORD = 0x0010; +pub const RPC_C_OPT_MQ_DELIVERY: ::DWORD = 1; +pub const RPC_C_OPT_MQ_PRIORITY: ::DWORD = 2; +pub const RPC_C_OPT_MQ_JOURNAL: ::DWORD = 3; +pub const RPC_C_OPT_MQ_ACKNOWLEDGE: ::DWORD = 4; +pub const RPC_C_OPT_MQ_AUTHN_SERVICE: ::DWORD = 5; +pub const RPC_C_OPT_MQ_AUTHN_LEVEL: ::DWORD = 6; +pub const RPC_C_OPT_MQ_TIME_TO_REACH_QUEUE: ::DWORD = 7; +pub const RPC_C_OPT_MQ_TIME_TO_BE_RECEIVED: ::DWORD = 8; +pub const RPC_C_OPT_BINDING_NONCAUSAL: ::DWORD = 9; +pub const RPC_C_OPT_SECURITY_CALLBACK: ::DWORD = 10; +pub const RPC_C_OPT_UNIQUE_BINDING: ::DWORD = 11; +pub const RPC_C_OPT_CALL_TIMEOUT: ::DWORD = 12; +pub const RPC_C_OPT_DONT_LINGER: ::DWORD = 13; +pub const RPC_C_OPT_TRUST_PEER: ::DWORD = 14; +pub const RPC_C_OPT_ASYNC_BLOCK: ::DWORD = 15; +pub const RPC_C_OPT_OPTIMIZE_TIME: ::DWORD = 16; +pub const RPC_C_OPT_MAX_OPTIONS: ::DWORD = 17; +pub const RPC_C_MQ_EXPRESS: ::DWORD = 0; +pub const RPC_C_MQ_RECOVERABLE: ::DWORD = 1; +pub const RPC_C_MQ_JOURNAL_NONE: ::DWORD = 0; +pub const RPC_C_MQ_JOURNAL_DEADLETTER: ::DWORD = 1; +pub const RPC_C_MQ_JOURNAL_ALWAYS: ::DWORD = 2; +pub const RPC_C_FULL_CERT_CHAIN: ::DWORD = 0x0001; +STRUCT!{struct RPC_PROTSEQ_VECTORA { + Count: ::c_uint, + Protseq: [*mut ::c_uchar; 1], +}} +STRUCT!{struct RPC_PROTSEQ_VECTORW { + Count: ::c_uint, + Protseq: [*mut ::c_ushort; 1], +}} +STRUCT!{struct RPC_POLICY { + Length: ::c_uint, + EndpointFlags: ::c_ulong, + NICFlags: ::c_ulong, +}} +pub type PRPC_POLICY = *mut RPC_POLICY; +pub type RPC_OBJECT_INQ_FN = Option; +pub type RPC_IF_CALLBACK_FN = Option ::RPC_STATUS>; +pub type RPC_SECURITY_CALLBACK_FN = Option; +pub type RPC_MGR_EPV = ::c_void; +STRUCT!{struct RPC_STATS_VECTOR { + Count: ::c_uint, + Stats: [::c_ulong; 1], +}} +pub const RPC_C_STATS_CALLS_IN: ::c_ulong = 0; +pub const RPC_C_STATS_CALLS_OUT: ::c_ulong = 1; +pub const RPC_C_STATS_PKTS_IN: ::c_ulong = 2; +pub const RPC_C_STATS_PKTS_OUT: ::c_ulong = 3; +STRUCT!{struct RPC_IF_ID_VECTOR { + Count: ::c_ulong, + IfId: [*mut RPC_IF_ID; 1], +}} +pub type RPC_AUTH_IDENTITY_HANDLE = *mut ::c_void; +pub type RPC_AUTHZ_HANDLE = *mut ::c_void; +pub const RPC_C_AUTHN_LEVEL_DEFAULT: ::DWORD = 0; +pub const RPC_C_AUTHN_LEVEL_NONE: ::DWORD = 1; +pub const RPC_C_AUTHN_LEVEL_CONNECT: ::DWORD = 2; +pub const RPC_C_AUTHN_LEVEL_CALL: ::DWORD = 3; +pub const RPC_C_AUTHN_LEVEL_PKT: ::DWORD = 4; +pub const RPC_C_AUTHN_LEVEL_PKT_INTEGRITY: ::DWORD = 5; +pub const RPC_C_AUTHN_LEVEL_PKT_PRIVACY: ::DWORD = 6; +pub const RPC_C_IMP_LEVEL_DEFAULT: ::DWORD = 0; +pub const RPC_C_IMP_LEVEL_ANONYMOUS: ::DWORD = 1; +pub const RPC_C_IMP_LEVEL_IDENTIFY: ::DWORD = 2; +pub const RPC_C_IMP_LEVEL_IMPERSONATE: ::DWORD = 3; +pub const RPC_C_IMP_LEVEL_DELEGATE: ::DWORD = 4; +pub const RPC_C_QOS_IDENTITY_STATIC: ::DWORD = 0; +pub const RPC_C_QOS_IDENTITY_DYNAMIC: ::DWORD = 1; +pub const RPC_C_QOS_CAPABILITIES_DEFAULT: ::DWORD = 0x0; +pub const RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH: ::DWORD = 0x1; +pub const RPC_C_QOS_CAPABILITIES_MAKE_FULLSIC: ::DWORD = 0x2; +pub const RPC_C_QOS_CAPABILITIES_ANY_AUTHORITY: ::DWORD = 0x4; +pub const RPC_C_QOS_CAPABILITIES_IGNORE_DELEGATE_FAILURE: ::DWORD = 0x8; +pub const RPC_C_QOS_CAPABILITIES_LOCAL_MA_HINT: ::DWORD = 0x10; +pub const RPC_C_QOS_CAPABILITIES_SCHANNEL_FULL_AUTH_IDENTITY: ::DWORD = 0x20; +pub const RPC_C_PROTECT_LEVEL_DEFAULT: ::DWORD = RPC_C_AUTHN_LEVEL_DEFAULT; +pub const RPC_C_PROTECT_LEVEL_NONE: ::DWORD = RPC_C_AUTHN_LEVEL_NONE; +pub const RPC_C_PROTECT_LEVEL_CONNECT: ::DWORD = RPC_C_AUTHN_LEVEL_CONNECT; +pub const RPC_C_PROTECT_LEVEL_CALL: ::DWORD = RPC_C_AUTHN_LEVEL_CALL; +pub const RPC_C_PROTECT_LEVEL_PKT: ::DWORD = RPC_C_AUTHN_LEVEL_PKT; +pub const RPC_C_PROTECT_LEVEL_PKT_INTEGRITY: ::DWORD = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY; +pub const RPC_C_PROTECT_LEVEL_PKT_PRIVACY: ::DWORD = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; +pub const RPC_C_AUTHN_NONE: ::DWORD = 0; +pub const RPC_C_AUTHN_DCE_PRIVATE: ::DWORD = 1; +pub const RPC_C_AUTHN_DCE_PUBLIC: ::DWORD = 2; +pub const RPC_C_AUTHN_DEC_PUBLIC: ::DWORD = 4; +pub const RPC_C_AUTHN_GSS_NEGOTIATE: ::DWORD = 9; +pub const RPC_C_AUTHN_WINNT: ::DWORD = 10; +pub const RPC_C_AUTHN_GSS_SCHANNEL: ::DWORD = 14; +pub const RPC_C_AUTHN_GSS_KERBEROS: ::DWORD = 16; +pub const RPC_C_AUTHN_DPA: ::DWORD = 17; +pub const RPC_C_AUTHN_MSN: ::DWORD = 18; +pub const RPC_C_AUTHN_DIGEST: ::DWORD = 21; +pub const RPC_C_AUTHN_KERNEL: ::DWORD = 20; +pub const RPC_C_AUTHN_NEGO_EXTENDER: ::DWORD = 30; +pub const RPC_C_AUTHN_PKU2U: ::DWORD = 31; +pub const RPC_C_AUTHN_LIVE_SSP: ::DWORD = 32; +pub const RPC_C_AUTHN_LIVEXP_SSP: ::DWORD = 35; +pub const RPC_C_AUTHN_MSONLINE: ::DWORD = 82; +pub const RPC_C_AUTHN_MQ: ::DWORD = 100; +pub const RPC_C_AUTHN_DEFAULT: ::DWORD = 0xFFFFFFFF; +pub const RPC_C_NO_CREDENTIALS: ::DWORD = 0xFFFFFFFF; +pub const RPC_C_SECURITY_QOS_VERSION: ::DWORD = 1; +pub const RPC_C_SECURITY_QOS_VERSION_1: ::DWORD = 1; +STRUCT!{struct RPC_SECURITY_QOS { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, +}} +pub type PRPC_SECURITY_QOS = *mut RPC_SECURITY_QOS; +STRUCT!{struct SEC_WINNT_AUTH_IDENTITY_W { + User: *mut ::c_ushort, + UserLength: ::c_ulong, + Domain: *mut ::c_ushort, + DomainLength: ::c_ulong, + Password: *mut ::c_ushort, + PasswordLength: ::c_ulong, + Flags: ::c_ulong, +}} +pub type PSEC_WINNT_AUTH_IDENTITY_W = *mut SEC_WINNT_AUTH_IDENTITY_W; +STRUCT!{struct SEC_WINNT_AUTH_IDENTITY_A { + User: *mut ::c_uchar, + UserLength: ::c_ulong, + Domain: *mut ::c_uchar, + DomainLength: ::c_ulong, + Password: *mut ::c_uchar, + PasswordLength: ::c_ulong, + Flags: ::c_ulong, +}} +pub type PSEC_WINNT_AUTH_IDENTITY_A = *mut SEC_WINNT_AUTH_IDENTITY_A; +pub const RPC_C_AUTHN_INFO_TYPE_HTTP: ::c_ulong = 1; +pub const RPC_C_HTTP_AUTHN_TARGET_SERVER: ::c_ulong = 1; +pub const RPC_C_HTTP_AUTHN_TARGET_PROXY: ::c_ulong = 2; +pub const RPC_C_HTTP_AUTHN_SCHEME_BASIC: ::c_ulong = 0x00000001; +pub const RPC_C_HTTP_AUTHN_SCHEME_NTLM: ::c_ulong = 0x00000002; +pub const RPC_C_HTTP_AUTHN_SCHEME_PASSPORT: ::c_ulong = 0x00000004; +pub const RPC_C_HTTP_AUTHN_SCHEME_DIGEST: ::c_ulong = 0x00000008; +pub const RPC_C_HTTP_AUTHN_SCHEME_NEGOTIATE: ::c_ulong = 0x00000010; +pub const RPC_C_HTTP_AUTHN_SCHEME_CERT: ::c_ulong = 0x00010000; +pub const RPC_C_HTTP_FLAG_USE_SSL: ::c_ulong = 1; +pub const RPC_C_HTTP_FLAG_USE_FIRST_AUTH_SCHEME: ::c_ulong = 2; +pub const RPC_C_HTTP_FLAG_IGNORE_CERT_CN_INVALID: ::c_ulong = 8; +pub const RPC_C_HTTP_FLAG_ENABLE_CERT_REVOCATION_CHECK: ::c_ulong = 16; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_W { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_A { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, + ProxyCredentials: *mut SEC_WINNT_AUTH_IDENTITY_W, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V2_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V2_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A { + TransportCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, + ProxyCredentials: *mut SEC_WINNT_AUTH_IDENTITY_A, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V2_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V2_A; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W { + TransportCredentials: RPC_AUTH_IDENTITY_HANDLE, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_ushort, + ProxyCredentials: *mut RPC_AUTH_IDENTITY_HANDLE, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V3_W = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V3_W; +STRUCT!{struct RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A { + TransportCredentials: RPC_AUTH_IDENTITY_HANDLE, + Flags: ::c_ulong, + AuthenticationTarget: ::c_ulong, + NumberOfAuthnSchemes: ::c_ulong, + AuthnSchemes: *mut ::c_ulong, + ServerCertificateSubject: *mut ::c_uchar, + ProxyCredentials: *mut RPC_AUTH_IDENTITY_HANDLE, + NumberOfProxyAuthnSchemes: ::c_ulong, + ProxyAuthnSchemes: *mut ::c_ulong, +}} +pub type PRPC_HTTP_TRANSPORT_CREDENTIALS_V3_A = *mut RPC_HTTP_TRANSPORT_CREDENTIALS_V3_A; +STRUCT!{struct RPC_SECURITY_QOS_V2_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V2_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V2_W_union, +}} +pub type PRPC_SECURITY_QOS_V2_W = *mut RPC_SECURITY_QOS_V2_W; +STRUCT!{struct RPC_SECURITY_QOS_V2_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V2_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V2_A_union, +}} +pub type PRPC_SECURITY_QOS_V2_A = *mut RPC_SECURITY_QOS_V2_A; +STRUCT!{struct RPC_SECURITY_QOS_V3_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V3_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V3_W_union, + Sid: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V3_W = *mut RPC_SECURITY_QOS_V3_W; +STRUCT!{struct RPC_SECURITY_QOS_V3_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V3_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V3_A_union, + Sid: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V3_A = *mut RPC_SECURITY_QOS_V3_A; +STRUCT!{struct RPC_SECURITY_QOS_V4_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V4_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V4_W_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, +}} +pub type PRPC_SECURITY_QOS_V4_W = *mut RPC_SECURITY_QOS_V4_W; +STRUCT!{struct RPC_SECURITY_QOS_V4_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V4_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V4_A_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, +}} +pub type PRPC_SECURITY_QOS_V4_A = *mut RPC_SECURITY_QOS_V4_A; +STRUCT!{struct RPC_SECURITY_QOS_V5_W_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_W, +}} +STRUCT!{struct RPC_SECURITY_QOS_V5_W { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V5_W_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, + ServerSecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V5_W = *mut RPC_SECURITY_QOS_V5_W; +STRUCT!{struct RPC_SECURITY_QOS_V5_A_union { + HttpCredentials: *mut RPC_HTTP_TRANSPORT_CREDENTIALS_A, +}} +STRUCT!{struct RPC_SECURITY_QOS_V5_A { + Version: ::c_ulong, + Capabilities: ::c_ulong, + IdentityTracking: ::c_ulong, + ImpersonationType: ::c_ulong, + AdditionalSecurityInfoType: ::c_ulong, + u: RPC_SECURITY_QOS_V5_A_union, + Sid: *mut ::c_void, + EffectiveOnly: ::c_uint, + ServerSecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_SECURITY_QOS_V5_A = *mut RPC_SECURITY_QOS_V5_A; +pub const RPC_PROTSEQ_TCP: ::c_ulong = 0x1; +pub const RPC_PROTSEQ_NMP: ::c_ulong = 0x2; +pub const RPC_PROTSEQ_LRPC: ::c_ulong = 0x3; +pub const RPC_PROTSEQ_HTTP: ::c_ulong = 0x4; +pub const RPC_BHT_OBJECT_UUID_VALID: ::c_ulong = 0x1; +pub const RPC_BHO_NONCAUSAL: ::c_ulong = 0x1; +pub const RPC_BHO_DONTLINGER: ::c_ulong = 0x2; +pub const RPC_BHO_EXCLUSIVE_AND_GUARANTEED: ::c_ulong = 0x4; +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_W_union { + Reserved: *mut ::c_ushort, +}} +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_W { + Version: ::c_ulong, + Flags: ::c_ulong, + ProtocolSequence: ::c_ulong, + NetworkAddress: *mut ::c_ushort, + StringEndpoint: *mut ::c_ushort, + u1: RPC_BINDING_HANDLE_TEMPLATE_V1_W_union, + ObjectUuid: UUID, +}} +pub type PRPC_BINDING_HANDLE_TEMPLATE_V1_W = *mut RPC_BINDING_HANDLE_TEMPLATE_V1_W; +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_A_union { + Reserved: *mut ::c_uchar, +}} +STRUCT!{struct RPC_BINDING_HANDLE_TEMPLATE_V1_A { + Version: ::c_ulong, + Flags: ::c_ulong, + ProtocolSequence: ::c_ulong, + NetworkAddress: *mut ::c_uchar, + StringEndpoint: *mut ::c_uchar, + u1: RPC_BINDING_HANDLE_TEMPLATE_V1_A_union, + ObjectUuid: UUID, +}} +pub type PRPC_BINDING_HANDLE_TEMPLATE_V1_A = *mut RPC_BINDING_HANDLE_TEMPLATE_V1_A; +STRUCT!{struct RPC_BINDING_HANDLE_SECURITY_V1_W { + Version: ::c_ulong, + ServerPrincName: *mut ::c_ushort, + AuthnLevel: ::c_ulong, + AuthnSvc: ::c_ulong, + AuthIdentity: *mut SEC_WINNT_AUTH_IDENTITY_W, + SecurityQos: *mut RPC_SECURITY_QOS, +}} +pub type PRPC_BINDING_HANDLE_SECURITY_V1_W = *mut RPC_BINDING_HANDLE_SECURITY_V1_W; +STRUCT!{struct RPC_BINDING_HANDLE_SECURITY_V1_A { + Version: ::c_ulong, + ServerPrincName: *mut ::c_uchar, + AuthnLevel: ::c_ulong, + AuthnSvc: ::c_ulong, + AuthIdentity: *mut SEC_WINNT_AUTH_IDENTITY_A, + SecurityQos: *mut RPC_SECURITY_QOS, +}} +pub type PRPC_BINDING_HANDLE_SECURITY_V1_A = *mut RPC_BINDING_HANDLE_SECURITY_V1_A; +STRUCT!{struct RPC_BINDING_HANDLE_OPTIONS_V1 { + Version: ::c_ulong, + Flags: ::c_ulong, + ComTimeout: ::c_ulong, + CallTimeout: ::c_ulong, +}} +pub type PRPC_BINDING_HANDLE_OPTIONS_V1 = *mut RPC_BINDING_HANDLE_OPTIONS_V1; +ENUM!{enum RPC_HTTP_REDIRECTOR_STAGE { + RPCHTTP_RS_REDIRECT = 1, + RPCHTTP_RS_ACCESS_1, + RPCHTTP_RS_SESSION, + RPCHTTP_RS_ACCESS_2, + RPCHTTP_RS_INTERFACE, +}} +pub type RPC_NEW_HTTP_PROXY_CHANNEL = Option ::RPC_STATUS>; +pub type RPC_HTTP_PROXY_FREE_STRING = Option; +pub const RPC_C_AUTHZ_NONE: ::DWORD = 0; +pub const RPC_C_AUTHZ_NAME: ::DWORD = 1; +pub const RPC_C_AUTHZ_DCE: ::DWORD = 2; +pub const RPC_C_AUTHZ_DEFAULT: ::DWORD = 0xffffffff; +pub type RPC_AUTH_KEY_RETRIEVAL_FN = Option; +STRUCT!{struct RPC_CLIENT_INFORMATION1 { + UserName: *mut ::c_uchar, + ComputerName: *mut ::c_uchar, + Privilege: ::c_ushort, + AuthFlags: ::c_ulong, +}} +pub type PRPC_CLIENT_INFORMATION1 = *mut RPC_CLIENT_INFORMATION1; +pub type RPC_EP_INQ_HANDLE = *mut ::I_RPC_HANDLE; +pub const RPC_C_EP_ALL_ELTS: ::c_ulong = 0; +pub const RPC_C_EP_MATCH_BY_IF: ::c_ulong = 1; +pub const RPC_C_EP_MATCH_BY_OBJ: ::c_ulong = 2; +pub const RPC_C_EP_MATCH_BY_BOTH: ::c_ulong = 3; +pub const RPC_C_VERS_ALL: ::c_ulong = 1; +pub const RPC_C_VERS_COMPATIBLE: ::c_ulong = 2; +pub const RPC_C_VERS_EXACT: ::c_ulong = 3; +pub const RPC_C_VERS_MAJOR_ONLY: ::c_ulong = 4; +pub const RPC_C_VERS_UPTO: ::c_ulong = 5; +pub type RPC_MGMT_AUTHORIZATION_FN = Option ::c_int>; +pub const RPC_C_MGMT_INQ_IF_IDS: ::c_ulong = 0; +pub const RPC_C_MGMT_INQ_PRINC_NAME: ::c_ulong = 1; +pub const RPC_C_MGMT_INQ_STATS: ::c_ulong = 2; +pub const RPC_C_MGMT_IS_SERVER_LISTEN: ::c_ulong = 3; +pub const RPC_C_MGMT_STOP_SERVER_LISTEN: ::c_ulong = 4; +pub const RPC_IF_AUTOLISTEN: ::c_uint = 0x0001; +pub const RPC_IF_OLE: ::c_uint = 0x0002; +pub const RPC_IF_ALLOW_UNKNOWN_AUTHORITY: ::c_uint = 0x0004; +pub const RPC_IF_ALLOW_SECURE_ONLY: ::c_uint = 0x0008; +pub const RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH: ::c_uint = 0x0010; +pub const RPC_IF_ALLOW_LOCAL_ONLY: ::c_uint = 0x0020; +pub const RPC_IF_SEC_NO_CACHE: ::c_uint = 0x0040; +pub const RPC_IF_SEC_CACHE_PER_PROC: ::c_uint = 0x0080; +pub const RPC_IF_ASYNC_CALLBACK: ::c_uint = 0x0100; +pub const RPC_FW_IF_FLAG_DCOM: ::c_uint = 0x0001; +pub type RPC_INTERFACE_GROUP = *mut ::c_void; +pub type PRPC_INTERFACE_GROUP = *mut *mut ::c_void; +STRUCT!{struct RPC_ENDPOINT_TEMPLATEW { + Version: ::c_ulong, + ProtSeq: RPC_WSTR, + Endpoint: RPC_WSTR, + SecurityDescriptor: *mut ::c_void, + Backlog: ::c_ulong, +}} +pub type PRPC_ENDPOINT_TEMPLATEW = *mut RPC_ENDPOINT_TEMPLATEW; +STRUCT!{struct RPC_ENDPOINT_TEMPLATEA { + Version: ::c_ulong, + ProtSeq: RPC_CSTR, + Endpoint: RPC_CSTR, + SecurityDescriptor: *mut ::c_void, + Backlog: ::c_ulong, +}} +pub type PRPC_ENDPOINT_TEMPLATEA = *mut RPC_ENDPOINT_TEMPLATEA; +STRUCT!{struct RPC_INTERFACE_TEMPLATEA { + Version: ::c_ulong, + IfSpec: RPC_IF_HANDLE, + MgrTypeUuid: *mut UUID, + MgrEpv: *mut RPC_MGR_EPV, + Flags: ::c_uint, + MaxCalls: ::c_uint, + MaxRpcSize: ::c_uint, + IfCallback: *mut RPC_IF_CALLBACK_FN, + UuidVector: *mut UUID_VECTOR, + Annotation: RPC_CSTR, + SecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_INTERFACE_TEMPLATEA = *mut RPC_INTERFACE_TEMPLATEA; +STRUCT!{struct RPC_INTERFACE_TEMPLATEW { + Version: ::c_ulong, + IfSpec: RPC_IF_HANDLE, + MgrTypeUuid: *mut UUID, + MgrEpv: *mut RPC_MGR_EPV, + Flags: ::c_uint, + MaxCalls: ::c_uint, + MaxRpcSize: ::c_uint, + IfCallback: *mut RPC_IF_CALLBACK_FN, + UuidVector: *mut UUID_VECTOR, + Annotation: RPC_WSTR, + SecurityDescriptor: *mut ::c_void, +}} +pub type PRPC_INTERFACE_TEMPLATEW = *mut RPC_INTERFACE_TEMPLATEW; +pub type RPC_INTERFACE_GROUP_IDLE_CALLBACK_FN = Option; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/sapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/sapi.rs new file mode 100644 index 0000000..ac6ca11 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/sapi.rs @@ -0,0 +1,2431 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of sapi.h +ENUM!{enum SPDATAKEYLOCATION { + SPDKL_DefaultLocation = 0, + SPDKL_CurrentUser = 1, + SPDKL_LocalMachine = 2, + SPDKL_CurrentConfig = 5, +}} +pub const SPDUI_EngineProperties: &'static str = "EngineProperties"; +pub const SPDUI_AddRemoveWord: &'static str = "AddRemoveWord"; +pub const SPDUI_UserTraining: &'static str = "UserTraining"; +pub const SPDUI_MicTraining: &'static str = "MicTraining"; +pub const SPDUI_RecoProfileProperties: &'static str = "RecoProfileProperties"; +pub const SPDUI_AudioProperties: &'static str = "AudioProperties"; +pub const SPDUI_AudioVolume: &'static str = "AudioVolume"; +pub const SPDUI_UserEnrollment: &'static str = "UserEnrollment"; +pub const SPDUI_ShareData: &'static str = "ShareData"; +pub const SPDUI_Tutorial: &'static str = "Tutorial"; +ENUM!{enum SPSTREAMFORMAT { + SPSF_Default = -1i32 as u32, + SPSF_NoAssignedFormat = 0, + SPSF_Text = 1, + SPSF_NonStandardFormat = 2, + SPSF_ExtendedAudioFormat = 3, + SPSF_8kHz8BitMono = 4, + SPSF_8kHz8BitStereo = 5, + SPSF_8kHz16BitMono = 6, + SPSF_8kHz16BitStereo = 7, + SPSF_11kHz8BitMono = 8, + SPSF_11kHz8BitStereo = 9, + SPSF_11kHz16BitMono = 10, + SPSF_11kHz16BitStereo = 11, + SPSF_12kHz8BitMono = 12, + SPSF_12kHz8BitStereo = 13, + SPSF_12kHz16BitMono = 14, + SPSF_12kHz16BitStereo = 15, + SPSF_16kHz8BitMono = 16, + SPSF_16kHz8BitStereo = 17, + SPSF_16kHz16BitMono = 18, + SPSF_16kHz16BitStereo = 19, + SPSF_22kHz8BitMono = 20, + SPSF_22kHz8BitStereo = 21, + SPSF_22kHz16BitMono = 22, + SPSF_22kHz16BitStereo = 23, + SPSF_24kHz8BitMono = 24, + SPSF_24kHz8BitStereo = 25, + SPSF_24kHz16BitMono = 26, + SPSF_24kHz16BitStereo = 27, + SPSF_32kHz8BitMono = 28, + SPSF_32kHz8BitStereo = 29, + SPSF_32kHz16BitMono = 30, + SPSF_32kHz16BitStereo = 31, + SPSF_44kHz8BitMono = 32, + SPSF_44kHz8BitStereo = 33, + SPSF_44kHz16BitMono = 34, + SPSF_44kHz16BitStereo = 35, + SPSF_48kHz8BitMono = 36, + SPSF_48kHz8BitStereo = 37, + SPSF_48kHz16BitMono = 38, + SPSF_48kHz16BitStereo = 39, + SPSF_TrueSpeech_8kHz1BitMono = 40, + SPSF_CCITT_ALaw_8kHzMono = 41, + SPSF_CCITT_ALaw_8kHzStereo = 42, + SPSF_CCITT_ALaw_11kHzMono = 43, + SPSF_CCITT_ALaw_11kHzStereo = 44, + SPSF_CCITT_ALaw_22kHzMono = 45, + SPSF_CCITT_ALaw_22kHzStereo = 46, + SPSF_CCITT_ALaw_44kHzMono = 47, + SPSF_CCITT_ALaw_44kHzStereo = 48, + SPSF_CCITT_uLaw_8kHzMono = 49, + SPSF_CCITT_uLaw_8kHzStereo = 50, + SPSF_CCITT_uLaw_11kHzMono = 51, + SPSF_CCITT_uLaw_11kHzStereo = 52, + SPSF_CCITT_uLaw_22kHzMono = 53, + SPSF_CCITT_uLaw_22kHzStereo = 54, + SPSF_CCITT_uLaw_44kHzMono = 55, + SPSF_CCITT_uLaw_44kHzStereo = 56, + SPSF_ADPCM_8kHzMono = 57, + SPSF_ADPCM_8kHzStereo = 58, + SPSF_ADPCM_11kHzMono = 59, + SPSF_ADPCM_11kHzStereo = 60, + SPSF_ADPCM_22kHzMono = 61, + SPSF_ADPCM_22kHzStereo = 62, + SPSF_ADPCM_44kHzMono = 63, + SPSF_ADPCM_44kHzStereo = 64, + SPSF_GSM610_8kHzMono = 65, + SPSF_GSM610_11kHzMono = 66, + SPSF_GSM610_22kHzMono = 67, + SPSF_GSM610_44kHzMono = 68, + SPSF_NUM_FORMATS = 69, +}} +pub const SPREG_USER_ROOT: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech"; +pub const SPREG_LOCAL_MACHINE_ROOT: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech"; +pub const SPCAT_AUDIOOUT: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioOutput"; +pub const SPCAT_AUDIOIN: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioInput"; +pub const SPCAT_VOICES: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices"; +pub const SPCAT_RECOGNIZERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Recognizers"; +pub const SPCAT_APPLEXICONS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AppLexicons"; +pub const SPCAT_PHONECONVERTERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\PhoneConverters"; +pub const SPCAT_TEXTNORMALIZERS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\TextNormalizers"; +pub const SPCAT_RECOPROFILES: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\RecoProfiles"; +pub const SPMMSYS_AUDIO_IN_TOKEN_ID: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioInput\\TokenEnums\\MMAudioIn\\"; +pub const SPMMSYS_AUDIO_OUT_TOKEN_ID: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\AudioOutput\\TokenEnums\\MMAudioOut\\"; +pub const SPCURRENT_USER_LEXICON_TOKEN_ID: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\CurrentUserLexicon"; +pub const SPCURRENT_USER_SHORTCUT_TOKEN_ID: &'static str = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Speech\\CurrentUserShortcut"; +pub const SPTOKENVALUE_CLSID: &'static str = "CLSID"; +pub const SPTOKENKEY_FILES: &'static str = "Files"; +pub const SPTOKENKEY_UI: &'static str = "UI"; +pub const SPTOKENKEY_ATTRIBUTES: &'static str = "Attributes"; +pub const SPTOKENKEY_RETAINEDAUDIO: &'static str = "SecondsPerRetainedAudioEvent"; +pub const SPTOKENKEY_AUDIO_LATENCY_WARNING: &'static str = "LatencyWarningThreshold"; +pub const SPTOKENKEY_AUDIO_LATENCY_TRUNCATE: &'static str = "LatencyTruncateThreshold"; +pub const SPTOKENKEY_AUDIO_LATENCY_UPDATE_INTERVAL: &'static str = "LatencyUpdateInterval"; +pub const SPVOICECATEGORY_TTSRATE: &'static str = "DefaultTTSRate"; +pub const SPPROP_RESOURCE_USAGE: &'static str = "ResourceUsage"; +pub const SPPROP_HIGH_CONFIDENCE_THRESHOLD: &'static str = "HighConfidenceThreshold"; +pub const SPPROP_NORMAL_CONFIDENCE_THRESHOLD: &'static str = "NormalConfidenceThreshold"; +pub const SPPROP_LOW_CONFIDENCE_THRESHOLD: &'static str = "LowConfidenceThreshold"; +pub const SPPROP_RESPONSE_SPEED: &'static str = "ResponseSpeed"; +pub const SPPROP_COMPLEX_RESPONSE_SPEED: &'static str = "ComplexResponseSpeed"; +pub const SPPROP_ADAPTATION_ON: &'static str = "AdaptationOn"; +pub const SPPROP_PERSISTED_BACKGROUND_ADAPTATION: &'static str = "PersistedBackgroundAdaptation"; +pub const SPPROP_PERSISTED_LANGUAGE_MODEL_ADAPTATION: &'static str = "PersistedLanguageModelAdaptation"; +pub const SPPROP_UX_IS_LISTENING: &'static str = "UXIsListening"; +pub const SPTOPIC_SPELLING: &'static str = "Spelling"; +pub const SPWILDCARD: &'static str = "..."; +pub const SPDICTATION: &'static str = "*"; +pub const SPINFDICTATION: &'static str = "*+"; +pub const SPREG_SAFE_USER_TOKENS: &'static str = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\UserTokens"; +pub const SP_LOW_CONFIDENCE: i32 = -1; +pub const SP_NORMAL_CONFIDENCE: i32 = 0; +pub const SP_HIGH_CONFIDENCE: i32 = 1; +pub const DEFAULT_WEIGHT: i32 = 1; +pub const SP_MAX_WORD_LENGTH: i32 = 128; +pub const SP_MAX_PRON_LENGTH: i32 = 384; +pub const SP_EMULATE_RESULT: i32 = 0x40000000; +RIDL!( +interface ISpNotifyCallback(ISpNotifyCallbackVtbl) { + fn NotifyCallback(&mut self, wParam: ::WPARAM, lParam: ::LPARAM) -> ::HRESULT +} +); +pub type SPNOTIFYCALLBACK = unsafe extern "system" fn(wParam: ::WPARAM, lParam: ::LPARAM); +RIDL!( +interface ISpNotifySource(ISpNotifySourceVtbl): IUnknown(IUnknownVtbl) { + fn SetNotifySink(&mut self, pNotifySink: *mut ISpNotifySink) -> ::HRESULT, + fn SetNotifyWindowMessage( + &mut self, hWnd: ::HWND, Msg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyCallbackFunction( + &mut self, pfnCallback: SPNOTIFYCALLBACK, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyCallbackInterface( + &mut self, pSpCallback: *mut ISpNotifyCallback, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn SetNotifyWin32Event(&mut self) -> ::HRESULT, + fn WaitForNotifyEvent(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn GetNotifyEventHandle(&mut self) -> ::HANDLE +} +); +RIDL!( +interface ISpNotifySink(ISpNotifySinkVtbl): IUnknown(IUnknownVtbl) { + fn Notify(&mut self) -> ::HRESULT +} +); +RIDL!( +interface ISpNotifyTranslator(ISpNotifyTranslatorVtbl): ISpNotifySink(ISpNotifySinkVtbl) { + fn InitWindowMessage( + &mut self, hWnd: ::HWND, Msg: ::UINT, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitCallback( + &mut self, pfnCallback: SPNOTIFYCALLBACK, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitSpNotifyCallback( + &mut self, pSpCallback: *mut ISpNotifyCallback, wParam: ::WPARAM, lParam: ::LPARAM + ) -> ::HRESULT, + fn InitWin32Event(&mut self, hEvent: ::HANDLE, fCloseHandleOnRelease: ::BOOL) -> ::HRESULT, + fn Wait(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn GetEventHandle(&mut self) -> ::HANDLE +} +); +RIDL!( +interface ISpDataKey(ISpDataKeyVtbl): IUnknown(IUnknownVtbl) { + fn SetData( + &mut self, pszValueName: ::LPCWSTR, cbData: ::ULONG, pData: *const ::BYTE + ) -> ::HRESULT, + fn GetData( + &mut self, pszValueName: ::LPCWSTR, pcbData: *mut ::ULONG, pData: *mut ::BYTE + ) -> ::HRESULT, + fn SetStringValue(&mut self, pszValueName: ::LPCWSTR, pszValue: ::LPCWSTR) -> ::HRESULT, + fn GetStringValue(&mut self, pszValueName: ::LPCWSTR, ppszValue: *mut ::LPWSTR) -> ::HRESULT, + fn SetDWORD(&mut self, pszValueName: ::LPCWSTR, dwValue: ::DWORD) -> ::HRESULT, + fn GetDWORD(&mut self, pszValueName: ::LPCWSTR, pdwValue: *mut ::DWORD) -> ::HRESULT, + fn OpenKey(&mut self, pszSubKeyName: ::LPCWSTR, ppSubKey: *mut *mut ISpDataKey) -> ::HRESULT, + fn CreateKey(&mut self, pszSubKey: ::LPCWSTR, ppSubKey: *mut *mut ISpDataKey) -> ::HRESULT, + fn DeleteKey(&mut self, pszSubKey: ::LPCWSTR) -> ::HRESULT, + fn DeleteValue(&mut self, pszValueName: ::LPCWSTR) -> ::HRESULT, + fn EnumKeys(&mut self, Index: ::ULONG, ppszSubKeyName: *mut ::LPWSTR) -> ::HRESULT, + fn EnumValues(&mut self, Index: ::ULONG, ppszValueName: *mut ::LPWSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpRegDataKey(ISpRegDataKeyVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetKey(&mut self, hkey: ::HKEY, fReadOnly: ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectTokenCategory(ISpObjectTokenCategoryVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetId(&mut self, pszCategoryId: ::LPCWSTR, fCreateIfNotExist: ::BOOL) -> ::HRESULT, + fn GetId(&mut self, ppszCoMemCategoryId: *mut ::LPWSTR) -> ::HRESULT, + fn GetDataKey( + &mut self, spdkl: SPDATAKEYLOCATION, pppDataKey: *mut *mut ISpDataKey + ) -> ::HRESULT, + fn EnumTokens( + &mut self, pzsReqAttribs: ::LPCWSTR, pszOptAttribs: ::LPCWSTR, + ppEnum: *mut *mut IEnumSpObjectTokens + ) -> ::HRESULT, + fn SetDefaultTokenId(&mut self, pszTokenId: ::LPCWSTR) -> ::HRESULT, + fn GetDefaultTokenId(&mut self, ppszCoMemTokenId: *mut ::LPWSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectToken(ISpObjectTokenVtbl): ISpDataKey(ISpDataKeyVtbl) { + fn SetId( + &mut self, pszCategoryId: ::LPCWSTR, pszTokenId: ::LPCWSTR, fCreateIfNotExist: ::BOOL + ) -> ::HRESULT, + fn GetId(&mut self, ppszCoMemTokenId: *mut ::LPWSTR) -> ::HRESULT, + fn GetCategory(&mut self, ppTokenCategory: *mut *mut ISpObjectTokenCategory) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, dwClsContext: ::DWORD, riid: ::REFIID, + ppvObject: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetStorageFileName( + &mut self, clsidCaller: ::REFCLSID, pszValueName: ::LPCWSTR, + pszFileNameSpecifier: ::LPCWSTR, nFolder: ::ULONG, ppszFilePath: *mut ::LPWSTR + ) -> ::HRESULT, + fn RemoveStorageFileName(&mut self, pszKeyName: ::LPCWSTR, fDeleteFile: ::BOOL) -> ::HRESULT, + fn Remove(&mut self, pclsidCaller: *const ::CLSID) -> ::HRESULT, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + punkObject: *mut ::IUnknown, pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, punkObject: *mut ::IUnknown + ) -> ::HRESULT, + fn MatchesAttributes(&mut self, pszAttributes: ::LPCWSTR, pfMatches: *mut ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectTokenInit(ISpObjectTokenInitVtbl): ISpObjectToken(ISpObjectTokenVtbl) { + fn InitFromDataKey( + &mut self, pszCategoryId: ::LPCWSTR, pszTokenId: ::LPCWSTR, pDataKey: *mut ISpDataKey + ) -> ::HRESULT +} +); +RIDL!( +interface IEnumSpObjectTokens(IEnumSpObjectTokensVtbl): IUnknown(IUnknownVtbl) { + fn Next( + &mut self, celt: ::ULONG, pelt: *mut *mut ISpObjectToken, pceltFetched: *mut ::ULONG + ) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppEnum: *mut *mut IEnumSpObjectTokens) -> ::HRESULT, + fn Item(&mut self, Index: ::ULONG, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetCount(&mut self, pCount: *mut ::ULONG) -> ::HRESULT +} +); +RIDL!( +interface ISpObjectWithToken(ISpObjectWithTokenVtbl): IUnknown(IUnknownVtbl) { + fn SetObjectToken(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn GetObjectToken(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT +} +); +RIDL!( +interface ISpResourceManager(ISpResourceManagerVtbl): IServiceProvider(IServiceProviderVtbl) { + fn SetObject(&mut self, guidServiceId: ::REFGUID, pUnkObject: *mut ::IUnknown) -> ::HRESULT, + fn GetObject( + &mut self, guidServiceId: ::REFGUID, ObjectCLSID: ::REFCLSID, ObjectIID: ::REFIID, + fReleaseWhenLastExternalRefReleased: ::BOOL, ppObject: *mut *mut ::c_void + ) -> ::HRESULT +} +); +ENUM!{enum SPEVENTLPARAMTYPE { + SPET_LPARAM_IS_UNDEFINED = 0, + SPET_LPARAM_IS_TOKEN, + SPET_LPARAM_IS_OBJECT, + SPET_LPARAM_IS_POINTER, + SPET_LPARAM_IS_STRING, +}} +ENUM!{enum SPEVENTENUM { + SPEI_UNDEFINED = 0, + SPEI_START_INPUT_STREAM = 1, + SPEI_END_INPUT_STREAM = 2, + SPEI_VOICE_CHANGE = 3, + SPEI_TTS_BOOKMARK = 4, + SPEI_WORD_BOUNDARY = 5, + SPEI_PHONEME = 6, + SPEI_SENTENCE_BOUNDARY = 7, + SPEI_VISEME = 8, + SPEI_TTS_AUDIO_LEVEL = 9, + SPEI_TTS_PRIVATE = 15, + SPEI_END_SR_STREAM = 34, + SPEI_SOUND_START = 35, + SPEI_SOUND_END = 36, + SPEI_PHRASE_START = 37, + SPEI_RECOGNITION = 38, + SPEI_HYPOTHESIS = 39, + SPEI_SR_BOOKMARK = 40, + SPEI_PROPERTY_NUM_CHANGE = 41, + SPEI_PROPERTY_STRING_CHANGE = 42, + SPEI_FALSE_RECOGNITION = 43, + SPEI_INTERFERENCE = 44, + SPEI_REQUEST_UI = 45, + SPEI_RECO_STATE_CHANGE = 46, + SPEI_ADAPTATION = 47, + SPEI_START_SR_STREAM = 48, + SPEI_RECO_OTHER_CONTEXT = 49, + SPEI_SR_AUDIO_LEVEL = 50, + SPEI_SR_RETAINEDAUDIO = 51, + SPEI_SR_PRIVATE = 52, + SPEI_ACTIVE_CATEGORY_CHANGED = 53, + SPEI_RESERVED5 = 54, + SPEI_RESERVED6 = 55, + SPEI_RESERVED1 = 30, + SPEI_RESERVED2 = 33, + SPEI_RESERVED3 = 63, +}} +pub const SPEI_MIN_TTS: SPEVENTENUM = SPEI_START_INPUT_STREAM; +pub const SPEI_MAX_TTS: SPEVENTENUM = SPEI_TTS_PRIVATE; +pub const SPEI_MIN_SR: SPEVENTENUM = SPEI_END_SR_STREAM; +pub const SPEI_MAX_SR: SPEVENTENUM = SPEI_RESERVED6; +pub const SPFEI_FLAGCHECK: u64 = (1 << SPEI_RESERVED1.0 as u64) | (1 << SPEI_RESERVED2.0 as u64); +pub const SPFEI_ALL_TTS_EVENTS: u64 = 0x000000000000FFFE | SPFEI_FLAGCHECK; +pub const SPFEI_ALL_SR_EVENTS: u64 = 0x003FFFFC00000000 | SPFEI_FLAGCHECK; +pub const SPFEI_ALL_EVENTS: u64 = 0xEFFFFFFFFFFFFFFF; +#[inline] +pub fn SPFEI(SPEI_ord: u64) -> u64 { + (1 << SPEI_ord) | SPFEI_FLAGCHECK +} +STRUCT!{struct SPEVENT { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + wParam: ::WPARAM, + lParam: ::LPARAM, +}} +STRUCT!{struct SPSERIALIZEDEVENT { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + SerializedwParam: ::ULONG, + SerializedlParam: ::LONG, +}} +STRUCT!{struct SPSERIALIZEDEVENT64 { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + SerializedwParam: ::ULONGLONG, + SerializedlParam: ::LONGLONG, +}} +STRUCT!{struct SPEVENTEX { + eEventId: ::WORD, + elParamType: ::WORD, + ulStreamNum: ::ULONG, + ullAudioStreamOffset: ::ULONGLONG, + wParam: ::WPARAM, + lParam: ::LPARAM, + ullAudioTimeOffset: ::ULONGLONG, +}} +ENUM!{enum SPINTERFERENCE { + SPINTERFERENCE_NONE = 0, + SPINTERFERENCE_NOISE = 1, + SPINTERFERENCE_NOSIGNAL = 2, + SPINTERFERENCE_TOOLOUD = 3, + SPINTERFERENCE_TOOQUIET = 4, + SPINTERFERENCE_TOOFAST = 5, + SPINTERFERENCE_TOOSLOW = 6, + SPINTERFERENCE_LATENCY_WARNING = 7, + SPINTERFERENCE_LATENCY_TRUNCATE_BEGIN = 8, + SPINTERFERENCE_LATENCY_TRUNCATE_END = 9, +}} +FLAGS!{enum SPENDSRSTREAMFLAGS { + SPESF_NONE = 0, + SPESF_STREAM_RELEASED = 1 << 0, + SPESF_EMULATED = 1 << 1, +}} +FLAGS!{enum SPVFEATURE { + SPVFEATURE_STRESSED = 1 << 0, + SPVFEATURE_EMPHASIS = 1 << 1, +}} +ENUM!{enum SPVISEMES { + SP_VISEME_0 = 0, + SP_VISEME_1, + SP_VISEME_2, + SP_VISEME_3, + SP_VISEME_4, + SP_VISEME_5, + SP_VISEME_6, + SP_VISEME_7, + SP_VISEME_8, + SP_VISEME_9, + SP_VISEME_10, + SP_VISEME_11, + SP_VISEME_12, + SP_VISEME_13, + SP_VISEME_14, + SP_VISEME_15, + SP_VISEME_16, + SP_VISEME_17, + SP_VISEME_18, + SP_VISEME_19, + SP_VISEME_20, + SP_VISEME_21, +}} +STRUCT!{struct SPEVENTSOURCEINFO { + ullEventInterest: ::ULONGLONG, + ullQueuedInterest: ::ULONGLONG, + ulCount: ::ULONG, +}} +RIDL!( +interface ISpEventSource(ISpEventSourceVtbl): ISpNotifySource(ISpNotifySourceVtbl) { + fn SetInterest( + &mut self, ullEventInterest: ::ULONGLONG, ullQueuedInterest: ::ULONGLONG + ) -> ::HRESULT, + fn GetEvents( + &mut self, ulCount: ::ULONG, pEventArray: *mut SPEVENT, pulFetched: *mut ::ULONG + ) -> ::HRESULT, + fn GetInfo(&mut self, pInfo: *mut SPEVENTSOURCEINFO) -> ::HRESULT +} +); +RIDL!( +interface ISpEventSource2(ISpEventSource2Vtbl): ISpEventSource(ISpEventSourceVtbl) { + fn GetEventsEx( + &mut self, ulCount: ::ULONG, pEventArray: *mut SPEVENTEX, pulFetched: *mut ::ULONG + ) -> ::HRESULT +} +); +RIDL!( +interface ISpEventSink(ISpEventSinkVtbl): IUnknown(IUnknownVtbl) { + fn AddEvents(&mut self, pEventArray: *const SPEVENT, ulCount: ::ULONG) -> ::HRESULT, + fn GetEventInterest(&mut self, pullEventInterest: *mut ::ULONGLONG) -> ::HRESULT +} +); +RIDL!( +interface ISpStreamFormat(ISpStreamFormatVtbl): IStream(IStreamVtbl) { + fn GetFormat( + &mut self, pguidFormatId: *mut ::GUID, ppCoMemWaveFormatEx: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT +} +); +ENUM!{enum SPFILEMODE { + SPFM_OPEN_READONLY = 0, + SPFM_OPEN_READWRITE = 1, + SPFM_CREATE = 2, + SPFM_CREATE_ALWAYS = 3, + SPFM_NUM_MODES = 4, +}} +RIDL!( +interface ISpStream(ISpStreamVtbl): ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetBaseStream( + &mut self, pStream: *mut ::IStream, rguidFormat: ::REFGUID, + pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetBaseStream(&mut self, ppStream: *mut *mut ::IStream) -> ::HRESULT, + fn BindToFile( + &mut self, pszFileName: ::LPCWSTR, eMode: SPFILEMODE, pFormatId: *const ::GUID, + pWaveFormatEx: *const ::WAVEFORMATEX, ullEventInterest: ::ULONGLONG + ) -> ::HRESULT, + fn Close(&mut self) -> ::HRESULT +} +); +RIDL!( +interface ISpStreamFormatConverter(ISpStreamFormatConverterVtbl) + : ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetBaseStream( + &mut self, pStream: *mut ISpStreamFormat, fSetFormatToBaseStreamFormat: ::BOOL, + fWriteToBaseStream: ::BOOL + ) -> ::HRESULT, + fn GetBaseStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn SetFormat( + &mut self, rguidFormatIdOfConvertedStream: ::REFGUID, + pWaveFormatExOfConvertedStream: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn ResetSeekPosition(&mut self) -> ::HRESULT, + fn ScaleConvertedToBaseOffset( + &mut self, ullOffsetConvertedStream: ::ULONGLONG, pullOffsetBaseStream: *mut ::ULONGLONG + ) -> ::HRESULT, + fn ScaleBaseToConvertedOffset( + &mut self, ullOffsetBaseStream: ::ULONGLONG, pullOffsetConvertedStream: *mut ::ULONGLONG + ) -> ::HRESULT +} +); +ENUM!{enum SPAUDIOSTATE { + SPAS_CLOSED = 0, + SPAS_STOP = 1, + SPAS_PAUSE = 2, + SPAS_RUN = 3, +}} +STRUCT!{struct SPAUDIOSTATUS { + cbFreeBuffSpace: ::LONG, + cbNonBlockingIO: ::ULONG, + State: SPAUDIOSTATE, + CurSeekPos: ::ULONGLONG, + CurDevicePos: ::ULONGLONG, + dwAudioLevel: ::DWORD, + dwReserved2: ::DWORD, +}} +STRUCT!{struct SPAUDIOBUFFERINFO { + ulMsMinNotification: ::ULONG, + ulMsBufferSize: ::ULONG, + ulMsEventBias: ::ULONG, +}} +RIDL!( +interface ISpAudio(ISpAudioVtbl): ISpStreamFormat(ISpStreamFormatVtbl) { + fn SetState(&mut self, NewState: SPAUDIOSTATE, ullReserved: ::ULONGLONG) -> ::HRESULT, + fn SetFormat( + &mut self, rguidFmtId: ::REFGUID, pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetStatus(&mut self, pStatus: *mut SPAUDIOSTATUS) -> ::HRESULT, + fn SetBufferInfo(&mut self, pBuffInfo: *const SPAUDIOBUFFERINFO) -> ::HRESULT, + fn GetBufferInfo(&mut self, pBuffInfo: *mut SPAUDIOBUFFERINFO) -> ::HRESULT, + fn GetDefaultFormat( + &mut self, pFormatId: *mut ::GUID, ppCoMemWaveFormatEx: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn EventHandle(&mut self) -> ::HANDLE, + fn GetVolumeLevel(&mut self, pLevel: *mut ::ULONG) -> ::HRESULT, + fn SetVolumeLevel(&mut self, Level: ::ULONG) -> ::HRESULT, + fn GetBufferNotifySize(&mut self, pcbSize: *mut ::ULONG) -> ::HRESULT, + fn SetBufferNotifySize(&mut self, cbSize: ::ULONG) -> ::HRESULT +} +); +RIDL!( +interface ISpMMSysAudio(ISpMMSysAudioVtbl): ISpAudio(ISpAudioVtbl) { + fn GetDeviceId(&mut self, puDeviceId: *mut ::UINT) -> ::HRESULT, + fn SetDeviceId(&mut self, uDeviceId: ::UINT) -> ::HRESULT, + fn GetMMHandle(&mut self, pHandle: *mut *mut ::c_void) -> ::HRESULT, + fn GetLineId(&mut self, puLineId: *mut ::UINT) -> ::HRESULT, + fn SetLineId(&mut self, uLineId: ::UINT) -> ::HRESULT +} +); +RIDL!( +interface ISpTranscript(ISpTranscriptVtbl): IUnknown(IUnknownVtbl) { + fn GetTranscript(&mut self, ppszTranscript: *mut ::LPWSTR) -> ::HRESULT, + fn AppendTranscript(&mut self, pszTranscript: ::LPCWSTR) -> ::HRESULT +} +); +FLAGS!{enum SPDISPLYATTRIBUTES { + SPAF_ONE_TRAILING_SPACE = 0x2, + SPAF_TWO_TRAILING_SPACES = 0x4, + SPAF_CONSUME_LEADING_SPACES = 0x8, + SPAF_BUFFER_POSITION = 0x10, + SPAF_ALL = 0x1f, + SPAF_USER_SPECIFIED = 0x80, +}} +pub type SPPHONEID = ::WCHAR; +pub type PSPPHONEID = ::LPWSTR; +pub type PCSPPHONEID = ::LPCWSTR; +STRUCT!{struct SPPHRASEELEMENT { + ulAudioTimeOffset: ::ULONG, + ulAudioSizeTime: ::ULONG, + ulAudioStreamOffset: ::ULONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedStreamOffset: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + pszDisplayText: ::LPCWSTR, + pszLexicalForm: ::LPCWSTR, + pszPronunciation: *const SPPHONEID, + bDisplayAttributes: ::BYTE, + RequiredConfidence: ::c_char, + ActualConfidence: ::c_char, + Reserved: ::BYTE, + SREngineConfidence: ::c_float, +}} +STRUCT!{struct SPPHRASERULE { + pszName: ::LPCWSTR, + ulId: ::ULONG, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, + pNextSibling: *const SPPHRASERULE, + pFirstChild: *const SPPHRASERULE, + SREngineConfidence: ::c_float, + Confidence: ::c_char, +}} +ENUM!{enum SPPHRASEPROPERTYUNIONTYPE { + SPPPUT_UNUSED = 0, + SPPPUT_ARRAY_INDEX, +}} +STRUCT!{struct SPPHRASEPROPERTY { + pszName: ::LPCWSTR, + bType: ::BYTE, + bReserved: ::BYTE, + usArrayIndex: u16, + pszValue: ::LPCWSTR, + vValue: ::VARIANT, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, + pNextSibling: *const SPPHRASEPROPERTY, + pFirstChild: *const SPPHRASEPROPERTY, + SREngineConfidence: ::c_float, + Confidence: ::c_char, +}} +UNION!(SPPHRASEPROPERTY, bType, ulId, ulId_mut, ::ULONG); +STRUCT!{struct SPPHRASEREPLACEMENT { + bDisplayAttributes: ::BYTE, + pszReplacementText: ::LPCWSTR, + ulFirstElement: ::ULONG, + ulCountOfElements: ::ULONG, +}} +STRUCT!{struct SPSEMANTICERRORINFO { + ulLineNumber: ::ULONG, + pszScriptLine: ::LPWSTR, + pszSource: ::LPWSTR, + pszDescription: ::LPWSTR, + hrResultCode: ::HRESULT, +}} +ENUM!{enum SPSEMANTICFORMAT { + SPSMF_SAPI_PROPERTIES = 0, + SPSMF_SRGS_SEMANTICINTERPRETATION_MS = 1, + SPSMF_SRGS_SAPIPROPERTIES = 2, + SPSMF_UPS = 4, + SPSMF_SRGS_SEMANTICINTERPRETATION_W3C = 8, +}} +STRUCT!{struct SPPHRASE_50 { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, +}} +STRUCT!{struct SPPHRASE_53 { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, + pSML: ::LPWSTR, + pSemanticErrorInfo: *mut SPSEMANTICERRORINFO, +}} +STRUCT!{struct SPPHRASE { + cbSize: ::ULONG, + LangID: ::WORD, + wHomophoneGroupId: ::WORD, + ullGrammarID: ::ULONGLONG, + ftStartTime: ::ULONGLONG, + ullAudioStreamPosition: ::ULONGLONG, + ulAudioSizeBytes: ::ULONG, + ulRetainedSizeBytes: ::ULONG, + ulAudioSizeTime: ::ULONG, + Rule: ::SPPHRASERULE, + pProperties: *const ::SPPHRASEPROPERTY, + pElements: *const ::SPPHRASEELEMENT, + cReplacements: ::ULONG, + pReplacements: *const ::SPPHRASEREPLACEMENT, + SREngineID: ::GUID, + ulSREnginePrivateDataSize: ::ULONG, + pSREnginePrivateData: *const ::BYTE, + pSML: ::LPWSTR, + pSemanticErrorInfo: *mut SPSEMANTICERRORINFO, + SemanticTagFormat: SPSEMANTICFORMAT, +}} +STRUCT!{struct SPSERIALIZEDPHRASE { + ulSerializedSize: ::ULONG, +}} +STRUCT!{struct SPRULE { + pszRuleName: ::LPCWSTR, + ulRuleId: ::ULONG, + dwAttributes: ::DWORD, +}} +FLAGS!{enum SPVALUETYPE { + SPDF_PROPERTY = 0x1, + SPDF_REPLACEMENT = 0x2, + SPDF_RULE = 0x4, + SPDF_DISPLAYTEXT = 0x8, + SPDF_LEXICALFORM = 0x10, + SPDF_PRONUNCIATION = 0x20, + SPDF_AUDIO = 0x40, + SPDF_ALTERNATES = 0x80, + SPDF_ALL = 0xff, +}} +STRUCT!{struct SPBINARYGRAMMAR { + ulTotalSerializedSize: ::ULONG, +}} +ENUM!{enum SPPHRASERNG { + SPPR_ALL_ELEMENTS = -1i32 as u32, +}} +pub const SP_GETWHOLEPHRASE: SPPHRASERNG = SPPR_ALL_ELEMENTS; +pub const SPRR_ALL_ELEMENTS: SPPHRASERNG = SPPR_ALL_ELEMENTS; +DECLARE_HANDLE!(SPSTATEHANDLE, SPSTATEHANDLE__); +FLAGS!{enum SPRECOEVENTFLAGS { + SPREF_AutoPause = 1 << 0, + SPREF_Emulated = 1 << 1, + SPREF_SMLTimeout = 1 << 2, + SPREF_ExtendableParse = 1 << 3, + SPREF_ReSent = 1 << 4, + SPREF_Hypothesis = 1 << 5, + SPREF_FalseRecognition = 1 << 6, +}} +ENUM!{enum SPPARTOFSPEECH { + SPPS_NotOverriden = -1i32 as u32, + SPPS_Unknown = 0, + SPPS_Noun = 0x1000, + SPPS_Verb = 0x2000, + SPPS_Modifier = 0x3000, + SPPS_Function = 0x4000, + SPPS_Interjection = 0x5000, + SPPS_Noncontent = 0x6000, + SPPS_LMA = 0x7000, + SPPS_SuppressWord = 0xf000, +}} +FLAGS!{enum SPLEXICONTYPE { + eLEXTYPE_USER = 1 << 0, + eLEXTYPE_APP = 1 << 1, + eLEXTYPE_VENDORLEXICON = 1 << 2, + eLEXTYPE_LETTERTOSOUND = 1 << 3, + eLEXTYPE_MORPHOLOGY = 1 << 4, + eLEXTYPE_RESERVED4 = 1 << 5, + eLEXTYPE_USER_SHORTCUT = 1 << 6, + eLEXTYPE_RESERVED6 = 1 << 7, + eLEXTYPE_RESERVED7 = 1 << 8, + eLEXTYPE_RESERVED8 = 1 << 9, + eLEXTYPE_RESERVED9 = 1 << 10, + eLEXTYPE_RESERVED10 = 1 << 11, + eLEXTYPE_PRIVATE1 = 1 << 12, + eLEXTYPE_PRIVATE2 = 1 << 13, + eLEXTYPE_PRIVATE3 = 1 << 14, + eLEXTYPE_PRIVATE4 = 1 << 15, + eLEXTYPE_PRIVATE5 = 1 << 16, + eLEXTYPE_PRIVATE6 = 1 << 17, + eLEXTYPE_PRIVATE7 = 1 << 18, + eLEXTYPE_PRIVATE8 = 1 << 19, + eLEXTYPE_PRIVATE9 = 1 << 20, + eLEXTYPE_PRIVATE10 = 1 << 21, + eLEXTYPE_PRIVATE11 = 1 << 22, + eLEXTYPE_PRIVATE12 = 1 << 23, + eLEXTYPE_PRIVATE13 = 1 << 24, + eLEXTYPE_PRIVATE14 = 1 << 25, + eLEXTYPE_PRIVATE15 = 1 << 26, + eLEXTYPE_PRIVATE16 = 1 << 27, + eLEXTYPE_PRIVATE17 = 1 << 28, + eLEXTYPE_PRIVATE18 = 1 << 29, + eLEXTYPE_PRIVATE19 = 1 << 30, + eLEXTYPE_PRIVATE20 = 1 << 31, +}} +FLAGS!{enum SPWORDTYPE { + eWORDTYPE_ADDED = 1 << 0, + eWORDTYPE_DELETED = 1 << 1, +}} +FLAGS!{enum SPPRONUNCIATIONFLAGS { + ePRONFLAG_USED = 1 << 0, +}} +STRUCT!{struct SPWORDPRONUNCIATION { + pNextWordPronunciation: *mut SPWORDPRONUNCIATION, + eLexiconType: SPLEXICONTYPE, + LangID: ::WORD, + wPronunciationFlags: ::WORD, + ePartOfSpeech: SPPARTOFSPEECH, + szPronunciation: [SPPHONEID; 1], +}} +STRUCT!{struct SPWORDPRONUNCIATIONLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstWordPronunciation: *mut SPWORDPRONUNCIATION, +}} +STRUCT!{struct SPWORD { + pNextWord: *mut SPWORD, + LangID: ::WORD, + wReserved: ::WORD, + eWordType: SPWORDTYPE, + pszWord: ::LPWSTR, + pFirstWordPronunciation: *mut SPWORDPRONUNCIATION, +}} +STRUCT!{struct SPWORDLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstWord: *mut SPWORD, +}} +RIDL!( +interface ISpLexicon(ISpLexiconVtbl): IUnknown(IUnknownVtbl) { + fn GetPronunciations( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, dwFlags: ::DWORD, + pWordPronunciationList: *mut SPWORDPRONUNCIATIONLIST + ) -> ::HRESULT, + fn AddPronunciation( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, ePartOfSpeech: SPPARTOFSPEECH, + pszPronunciation: PCSPPHONEID + ) -> ::HRESULT, + fn RemovePronunciation( + &mut self, pszWord: ::LPCWSTR, LangID: ::WORD, ePartOfSpeech: SPPARTOFSPEECH, + pszPronunciation: PCSPPHONEID + ) -> ::HRESULT, + fn GetGeneration(&mut self, pdwGeneration: *mut ::DWORD) -> ::HRESULT, + fn GetGenerationChange( + &mut self, dwFlags: ::DWORD, pdwGeneration: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetWords( + &mut self, dwFlags: ::DWORD, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, + pWordList: *mut SPWORDLIST + ) -> ::HRESULT +} +); +RIDL!( +interface ISpContainerLexicon(ISpContainerLexiconVtbl): ISpLexicon(ISpLexiconVtbl) { + fn AddLexicon(&mut self, pAddLexicon: *mut ISpLexicon, dwFlags: ::DWORD) -> ::HRESULT +} +); +ENUM!{enum SPSHORTCUTTYPE { + SPSHT_NotOverriden = -1i32 as u32, + SPSHT_Unknown = 0, + SPSHT_EMAIL = 0x1000, + SPSHT_OTHER = 0x2000, + SPPS_RESERVED1 = 0x3000, + SPPS_RESERVED2 = 0x4000, + SPPS_RESERVED3 = 0x5000, + SPPS_RESERVED4 = 0xf000, +}} +STRUCT!{struct SPSHORTCUTPAIR { + pNextSHORTCUTPAIR: *mut SPSHORTCUTPAIR, + LangID: ::WORD, + shType: SPSHORTCUTTYPE, + pszDisplay: ::LPWSTR, + pszSpoken: ::LPWSTR, +}} +STRUCT!{struct SPSHORTCUTPAIRLIST { + ulSize: ::ULONG, + pvBuffer: *mut ::BYTE, + pFirstShortcutPair: *mut SPSHORTCUTPAIR, +}} +RIDL!( +interface ISpShortcut(ISpShortcutVtbl): IUnknown(IUnknownVtbl) { + fn AddShortcut( + &mut self, pszDisplay: ::LPCWSTR, LangID: ::WORD, pszSpoken: ::LPCWSTR, + shType: SPSHORTCUTTYPE + ) -> ::HRESULT, + fn RemoveShortcut( + &mut self, pszDisplay: ::LPCWSTR, LangID: ::WORD, pszSpoken: ::LPCWSTR, + shType: SPSHORTCUTTYPE + ) -> ::HRESULT, + fn GetShortcuts( + &mut self, LangId: ::WORD, pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT, + fn GetGeneration(&mut self, pdwGeneration: *mut ::DWORD) -> ::HRESULT, + fn GetWordsFromGenerationChange( + &mut self, pdwGeneration: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetWords( + &mut self, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, pWordList: *mut SPWORDLIST + ) -> ::HRESULT, + fn GetShortcutsForGeneration( + &mut self, pdwGeneration: *mut ::DWORD, pdwCookie: *mut ::DWORD, + pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT, + fn GetGenerationChange( + &mut self, pdwGeneration: *mut ::DWORD, pShortcutpairList: *mut SPSHORTCUTPAIRLIST + ) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneConverter(ISpPhoneConverterVtbl): ISpObjectWithToken(ISpObjectWithTokenVtbl) { + fn PhoneToId(&mut self, pszPhone: ::LPCWSTR, pId: *mut SPPHONEID) -> ::HRESULT, + fn IdToPhone(&mut self, pId: PCSPPHONEID, pszPhone: *mut ::WCHAR) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneticAlphabetConverter(ISpPhoneticAlphabetConverterVtbl): IUnknown(IUnknownVtbl) { + fn GetLangId(&mut self, pLangID: *mut ::WORD) -> ::HRESULT, + fn SetLangId(&mut self, LangID: *mut ::WORD) -> ::HRESULT, + fn SAPI2UPS( + &mut self, pszSAPIId: *const SPPHONEID, pszUPSId: *mut SPPHONEID, cMaxLength: ::DWORD + ) -> ::HRESULT, + fn UPS2SAPI( + &mut self, pszUPSId: *const SPPHONEID, pszSAPIId: *mut SPPHONEID, cMaxLength: ::DWORD + ) -> ::HRESULT, + fn GetMaxConvertLength( + &mut self, cSrcLength: ::DWORD, bSAPI2UPS: ::BOOL, pcMaxDestLength: *mut ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface ISpPhoneticAlphabetSelection(ISpPhoneticAlphabetSelectionVtbl): IUnknown(IUnknownVtbl) { + fn IsAlphabetUPS(&mut self, pfIsUPS: *mut ::BOOL) -> ::HRESULT, + fn SetAlphabetToUPS(&mut self, fForceUPS: ::BOOL) -> ::HRESULT +} +); +STRUCT!{struct SPVPITCH { + MiddleAdj: ::c_long, + RangeAdj: ::c_long, +}} +ENUM!{enum SPVACTIONS { + SPVA_Speak = 0, + SPVA_Silence, + SPVA_Pronounce, + SPVA_Bookmark, + SPVA_SpellOut, + SPVA_Section, + SPVA_ParseUnknownTag, +}} +STRUCT!{struct SPVCONTEXT { + pCategory: ::LPCWSTR, + pBefore: ::LPCWSTR, + pAfter: ::LPCWSTR, +}} +STRUCT!{struct SPVSTATE { + eAction: SPVACTIONS, + LangID: ::WORD, + wReserved: ::WORD, + EmphAdj: ::c_long, + RateAdj: ::c_long, + Volume: ::ULONG, + PitchAdj: SPVPITCH, + SilenceMSecs: ::ULONG, + pPhoneIds: *mut SPPHONEID, + ePartOfSpeech: SPPARTOFSPEECH, + Context: SPVCONTEXT, +}} +ENUM!{enum SPRUNSTATE { + SPRS_DONE = 1 << 0, + SPRS_IS_SPEAKING = 1 << 1, +}} +ENUM!{enum SPVLIMITS { + SPMIN_VOLUME = 0, + SPMAX_VOLUME = 100, + SPMIN_RATE = -10i32 as u32, + SPMAX_RATE = 10, +}} +ENUM!{enum SPVPRIORITY { + SPVPRI_NORMAL = 0, + SPVPRI_ALERT = 1 << 0, + SPVPRI_OVER = 1 << 1, +}} +STRUCT!{struct SPVOICESTATUS { + ulCurrentStream: ::ULONG, + ulLastStreamQueued: ::ULONG, + hrLastResult: ::HRESULT, + dwRunningState: ::DWORD, + ulInputWordPos: ::ULONG, + ulInputWordLen: ::ULONG, + ulInputSentPos: ::ULONG, + ulInputSentLen: ::ULONG, + lBookmarkId: ::LONG, + PhonemeId: SPPHONEID, + VisemeId: SPVISEMES, + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +FLAGS!{enum SPEAKFLAGS { + SPF_DEFAULT = 0, + SPF_ASYNC = 1 << 0, + SPF_PURGEBEFORESPEAK = 1 << 1, + SPF_IS_FILENAME = 1 << 2, + SPF_IS_XML = 1 << 3, + SPF_IS_NOT_XML = 1 << 4, + SPF_PERSIST_XML = 1 << 5, + SPF_NLP_SPEAK_PUNC = 1 << 6, + SPF_PARSE_SAPI = 1 << 7, + SPF_PARSE_SSML = 1 << 8, +}} +pub const SPF_PARSE_AUTODETECT: SPEAKFLAGS = SPF_DEFAULT; +pub const SPF_NLP_MASK: SPEAKFLAGS = SPF_NLP_SPEAK_PUNC; +pub const SPF_PARSE_MASK: i32 = SPF_PARSE_SAPI.0 as i32 | SPF_PARSE_SSML.0 as i32; +pub const SPF_VOICE_MASK: i32 = + SPF_ASYNC.0 as i32 | SPF_PURGEBEFORESPEAK.0 as i32 | SPF_IS_FILENAME.0 as i32 | SPF_IS_XML.0 as i32 | + SPF_IS_NOT_XML.0 as i32 | SPF_NLP_MASK.0 as i32 | SPF_PERSIST_XML.0 as i32 | SPF_PARSE_MASK; +pub const SPF_UNUSED_FLAGS: i32 = !SPF_VOICE_MASK; +RIDL!( +interface ISpVoice(ISpVoiceVtbl): ISpEventSource(ISpEventSourceVtbl) { + fn SetOutput(&mut self, pUnkOutput: *mut ::IUnknown, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetOutputObjectToken(&mut self, ppObjectToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetOutputStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn Pause(&mut self) -> ::HRESULT, + fn Resume(&mut self) -> ::HRESULT, + fn SetVoice(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn GetVoice(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn Speak( + &mut self, pwcs: ::LPCWSTR, dwFlags: ::DWORD, pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn SpeakStream( + &mut self, pStream: *mut ::IStream, dwFlags: ::DWORD, pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn GetStatus( + &mut self, pStatus: *mut SPVOICESTATUS, ppszLastBookmark: *mut ::LPWSTR + ) -> ::HRESULT, + fn Skip( + &mut self, pItemType: ::LPCWSTR, lNumItems: ::c_long, pulNumSkipped: *mut ::ULONG + ) -> ::HRESULT, + fn SetPriority(&mut self, ePriority: SPVPRIORITY) -> ::HRESULT, + fn GetPriority(&mut self, pePriority: *mut SPVPRIORITY) -> ::HRESULT, + fn SetAlertBoundary(&mut self, eBoundary: SPEVENTENUM) -> ::HRESULT, + fn GetAlertBoundary(&mut self, peBoundary: *mut SPEVENTENUM) -> ::HRESULT, + fn SetRate(&mut self, RateAdjust: ::c_long) -> ::HRESULT, + fn GetRate(&mut self, pRateAdjust: *mut ::c_long) -> ::HRESULT, + fn SetVolume(&mut self, usVolume: ::USHORT) -> ::HRESULT, + fn GetVolume(&mut self, pusVolume: *mut ::USHORT) -> ::HRESULT, + fn WaitUntilDone(&mut self, msTimeout: ::ULONG) -> ::HRESULT, + fn SetSyncSpeakTimeout(&mut self, msTimeout: ::ULONG) -> ::HRESULT, + fn GetSyncSpeakTimeout(&mut self, pmsTimeout: *mut ::ULONG) -> ::HRESULT, + fn SpeakCompleteEvent(&mut self) -> ::HANDLE, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG + ) -> ::HRESULT +} +); +DEFINE_GUID!( + UuidOfISpVoice, + 0x6C44DF74, 0x72B9, 0x4992, 0xA1, 0xEC, 0xEF, 0x99, 0x6E, 0x04, 0x22, 0xD4 +); +RIDL!( +interface ISpPhrase(ISpPhraseVtbl): IUnknown(IUnknownVtbl) { + fn GetPhrase(&mut self, ppCoMemPhrase: *mut *mut SPPHRASE) -> ::HRESULT, + fn GetSerializedPhrase(&mut self, ppCoMemPhrase: *mut *mut SPSERIALIZEDPHRASE) -> ::HRESULT, + fn GetText( + &mut self, ulStart: ::ULONG, ulCount: ::ULONG, fUseTextReplacements: ::BOOL, + ppszCoMemText: *mut ::LPWSTR, pbDisplayAttributes: *mut ::BYTE + ) -> ::HRESULT, + fn Discard(&mut self, dwValueTypes: ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface ISpPhraseAlt(ISpPhraseAltVtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetAltInfo( + &mut self, pParent: *mut *mut ISpPhrase, pulStartElementInParent: *mut ::ULONG, + pcElementsInParent: *mut ::ULONG, pcElementsInAlt: *mut ::ULONG + ) -> ::HRESULT, + fn Commit(&mut self) -> ::HRESULT +} +); +ENUM!{enum SPXMLRESULTOPTIONS { + SPXRO_SML = 0, + SPXRO_Alternates_SML = 1, +}} +RIDL!( +interface ISpPhrase2(ISpPhrase2Vtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetXMLResult( + &mut self, ppszCoMemXMLResult: *mut ::LPWSTR, Options: SPXMLRESULTOPTIONS + ) -> ::HRESULT, + fn GetXMLErrorInfo(&mut self, pSemanticErrorInfo: *mut SPSEMANTICERRORINFO) -> ::HRESULT, + fn GetAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ppStream: *mut *mut ISpStreamFormat + ) -> ::HRESULT +} +); +STRUCT!{struct SPRECORESULTTIMES { + ftStreamTime: ::FILETIME, + ullLength: ::ULONGLONG, + dwTickCount: ::DWORD, + ullStart: ::ULONGLONG, +}} +STRUCT!{struct SPSERIALIZEDRESULT { + ulSerializedSize: ::ULONG, +}} +RIDL!( +interface ISpRecoResult(ISpRecoResultVtbl): ISpPhrase(ISpPhraseVtbl) { + fn GetResultTimes(&mut self, pTimes: *mut SPRECORESULTTIMES) -> ::HRESULT, + fn GetAlternates( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ulRequestCount: ::ULONG, + ppPhrases: *mut *mut ISpPhraseAlt, pcPhrasesReturned: *mut ::ULONG + ) -> ::HRESULT, + fn GetAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, ppStream: *mut *mut ISpStreamFormat + ) -> ::HRESULT, + fn SpeakAudio( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, dwFlags: ::DWORD, + pulStreamNumber: *mut ::ULONG + ) -> ::HRESULT, + fn Serialize(&mut self, ppCoMemSerializedResult: *mut *mut SPSERIALIZEDRESULT) -> ::HRESULT, + fn ScaleAudio( + &mut self, pAudioFormatId: *const ::GUID, pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetRecoContext(&mut self, ppRecoContext: *mut *mut ISpRecoContext) -> ::HRESULT +} +); +FLAGS!{enum SPCOMMITFLAGS { + SPCF_NONE = 0, + SPCF_ADD_TO_USER_LEXICON = 1 << 0, + SPCF_DEFINITE_CORRECTION = 1 << 1, +}} +RIDL!( +interface ISpRecoResult2(ISpRecoResult2Vtbl): ISpRecoResult(ISpRecoResultVtbl) { + fn CommitAlternate( + &mut self, pPhraseAlt: *mut ISpPhraseAlt, ppNewResult: *mut *mut ISpRecoResult + ) -> ::HRESULT, + fn CommitText( + &mut self, ulStartElement: ::ULONG, cElements: ::ULONG, pszCorrectedData: ::LPCWSTR, + eCommitFlags: ::DWORD + ) -> ::HRESULT, + fn SetTextFeedback(&mut self, pszFeedback: ::LPCWSTR, fSuccessful: ::BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpXMLRecoResult(ISpXMLRecoResultVtbl): ISpRecoResult(ISpRecoResultVtbl) { + fn GetXMLResult( + &mut self, ppszCoMemXMLResult: *mut ::LPWSTR, Options: SPXMLRESULTOPTIONS + ) -> ::HRESULT, + fn GetXMLErrorInfo(&mut self, pSemanticErrorInfo: *mut SPSEMANTICERRORINFO) -> ::HRESULT +} +); +STRUCT!{struct SPTEXTSELECTIONINFO { + ulStartActiveOffset: ::ULONG, + cchActiveChars: ::ULONG, + ulStartSelection: ::ULONG, + cchSelection: ::ULONG, +}} +ENUM!{enum SPWORDPRONOUNCEABLE { + SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE = 0, + SPWP_UNKNOWN_WORD_PRONOUNCEABLE = 1, + SPWP_KNOWN_WORD_PRONOUNCEABLE = 2, +}} +ENUM!{enum SPGRAMMARSTATE { + SPGS_DISABLED = 0, + SPGS_ENABLED = 1, + SPGS_EXCLUSIVE = 3, +}} +ENUM!{enum SPCONTEXTSTATE { + SPCS_DISABLED = 0, + SPCS_ENABLED = 1, +}} +ENUM!{enum SPRULESTATE { + SPRS_INACTIVE = 0, + SPRS_ACTIVE = 1, + SPRS_ACTIVE_WITH_AUTO_PAUSE = 3, + SPRS_ACTIVE_USER_DELIMITED = 4, +}} +pub const SP_STREAMPOS_ASAP: ::INT = 0; +pub const SP_STREAMPOS_REALTIME: ::INT = -1; +pub const SPRULETRANS_TEXTBUFFER: SPSTATEHANDLE = -1isize as SPSTATEHANDLE; +pub const SPRULETRANS_WILDCARD: SPSTATEHANDLE = -2isize as SPSTATEHANDLE; +pub const SPRULETRANS_DICTATION: SPSTATEHANDLE = -3isize as SPSTATEHANDLE; +ENUM!{enum SPGRAMMARWORDTYPE { + SPWT_DISPLAY = 0, + SPWT_LEXICAL = 1, + SPWT_PRONUNCIATION = 2, + SPWT_LEXICAL_NO_SPECIAL_CHARS = 3, +}} +STRUCT!{struct SPPROPERTYINFO { + pszName: ::LPCWSTR, + ulId: ::ULONG, + pszValue: ::LPCWSTR, + vValue: ::VARIANT, +}} +FLAGS!{enum SPCFGRULEATTRIBUTES { + SPRAF_TopLevel = 1 << 0, + SPRAF_Active = 1 << 1, + SPRAF_Export = 1 << 2, + SPRAF_Import = 1 << 3, + SPRAF_Interpreter = 1 << 4, + SPRAF_Dynamic = 1 << 5, + SPRAF_Root = 1 << 6, + SPRAF_AutoPause = 1 << 16, + SPRAF_UserDelimited = 1 << 17, +}} +RIDL!( +interface ISpGrammarBuilder(ISpGrammarBuilderVtbl): IUnknown(IUnknownVtbl) { + fn ResetGrammar(&mut self, NewLanguage: ::WORD) -> ::HRESULT, + fn GetRule( + &mut self, pszRuleName: ::LPCWSTR, dwRuleId: ::DWORD, dwAttributes: ::DWORD, + fCreateIfNotExist: ::BOOL, phInitialState: *mut SPSTATEHANDLE + ) -> ::HRESULT, + fn ClearRule(&mut self, hState: SPSTATEHANDLE) -> ::HRESULT, + fn CreateNewState(&mut self, hState: SPSTATEHANDLE, phState: *mut SPSTATEHANDLE) -> ::HRESULT, + fn AddWordTransition( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, psz: ::LPCWSTR, + pszSeparators: ::LPCWSTR, eWordType: SPGRAMMARWORDTYPE, Weight: ::c_float, + pPropInfo: *const SPPROPERTYINFO + ) -> ::HRESULT, + fn AddRuleTransition( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, hRule: SPSTATEHANDLE, + Weight: ::c_float, pPropInfo: *const SPPROPERTYINFO + ) -> ::HRESULT, + fn AddResource( + &mut self, hRuleState: SPSTATEHANDLE, pszResourceName: ::LPCWSTR, + pszResourceValue: ::LPCWSTR + ) -> ::HRESULT, + fn Commit(&mut self, dwReserved: ::DWORD) -> ::HRESULT +} +); +ENUM!{enum SPLOADOPTIONS { + SPLO_STATIC = 0, + SPLO_DYNAMIC = 1, +}} +RIDL!( +interface ISpRecoGrammar(ISpRecoGrammarVtbl): ISpGrammarBuilder(ISpGrammarBuilderVtbl) { + fn GetGrammarId(&mut self, pullGrammarId: *mut ::ULONGLONG) -> ::HRESULT, + fn GetRecoContext(&mut self, ppRecoCtxt: *mut *mut ISpRecoContext) -> ::HRESULT, + fn LoadCmdFromFile(&mut self, pszFileName: ::LPCWSTR, Options: SPLOADOPTIONS) -> ::HRESULT, + fn LoadCmdFromObject( + &mut self, rcid: ::REFCLSID, pszGrammarName: ::LPCWSTR, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromResource( + &mut self, hModule: ::HMODULE, pszResourceName: ::LPCWSTR, pszResourceType: ::LPCWSTR, + wLanguage: ::WORD, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromMemory( + &mut self, pGrammar: *const SPBINARYGRAMMAR, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn LoadCmdFromProprietaryGrammar( + &mut self, rguidParam: ::REFGUID, pszStringParam: ::LPCWSTR, pvDataPrarm: *const ::c_void, + cbDataSize: ::ULONG, Options: SPLOADOPTIONS + ) -> ::HRESULT, + fn SetRuleState( + &mut self, pszName: ::LPCWSTR, pReserved: *mut ::c_void, NewState: SPRULESTATE + ) -> ::HRESULT, + fn SetRuleIdState(&mut self, ulRuleId: ::ULONG, NewState: SPRULESTATE) -> ::HRESULT, + fn LoadDictation(&mut self, pszTopicName: ::LPCWSTR, Options: SPLOADOPTIONS) -> ::HRESULT, + fn UnloadDictation(&mut self) -> ::HRESULT, + fn SetDictationState(&mut self, NewState: SPRULESTATE) -> ::HRESULT, + fn SetWordSequenceData( + &mut self, pText: *const ::WCHAR, cchText: ::ULONG, pInfo: *const SPTEXTSELECTIONINFO + ) -> ::HRESULT, + fn SetTextSelection(&mut self, pInfo: *const SPTEXTSELECTIONINFO) -> ::HRESULT, + fn IsPronounceable( + &mut self, pszWord: ::LPCWSTR, pWordPronounceable: *mut SPWORDPRONOUNCEABLE + ) -> ::HRESULT, + fn SetGrammarState(&mut self, eGrammarState: SPGRAMMARSTATE) -> ::HRESULT, + fn SaveCmd(&mut self, pStream: *mut ::IStream, ppszCoMemErrorText: *mut ::LPWSTR) -> ::HRESULT, + fn GetGrammarState(&mut self, peGrammarState: *mut SPGRAMMARSTATE) -> ::HRESULT +} +); +ENUM!{enum SPMATCHINGMODE { + AllWords = 0, + Subsequence = 1, + OrderedSubset = 3, + SubsequenceContentRequired = 5, + OrderedSubsetContentRequired = 7, +}} +ENUM!{enum PHONETICALPHABET { + PA_Ipa = 0, + PA_Ups = 1, + PA_Sapi = 2, +}} +RIDL!( +interface ISpGrammarBuilder2(ISpGrammarBuilder2Vtbl): IUnknown(IUnknownVtbl) { + fn AddTextSubset( + &mut self, hFromState: SPSTATEHANDLE, hToState: SPSTATEHANDLE, psz: ::LPCWSTR, + eMatchMode: SPMATCHINGMODE + ) -> ::HRESULT, + fn SetPhoneticAlphabet(&mut self, phoneticALphabet: PHONETICALPHABET) -> ::HRESULT +} +); +RIDL!( +interface ISpRecoGrammar2(ISpRecoGrammar2Vtbl): IUnknown(IUnknownVtbl) { + fn GetRules(&mut self, ppCoMemRules: *mut *mut SPRULE, puNumRules: *mut ::UINT) -> ::HRESULT, + fn LoadCmdFromFile2( + &mut self, pszFileName: ::LPCWSTR, Options: SPLOADOPTIONS, pszSharingUri: ::LPCWSTR, + pszBaseUri: ::LPCWSTR + ) -> ::HRESULT, + fn LoadCmdFromMemory2( + &mut self, pGrammar: *const SPBINARYGRAMMAR, Options: SPLOADOPTIONS, + pszSharingUri: ::LPCWSTR, pszBaseUri: ::LPCWSTR + ) -> ::HRESULT, + fn SetRulePriority( + &mut self, pszRuleName: ::LPCWSTR, ulRuleId: ::ULONG, nRulePriority: ::c_int + ) -> ::HRESULT, + fn SetRuleWeight( + &mut self, pszRuleName: ::LPCWSTR, ulRuleId: ::ULONG, flWeight: ::c_float + ) -> ::HRESULT, + fn SetDictationWeight(&mut self, flWeight: ::c_float) -> ::HRESULT, + fn SetGrammarLoader(&mut self, pLoader: *mut ISpeechResourceLoader) -> ::HRESULT, + fn SetSMLSecurityManager( + &mut self, pSMLSecurityManager: *mut ::IInternetSecurityManager + ) -> ::HRESULT +} +); +RIDL!( +interface ISpeechResourceLoader(ISpeechResourceLoaderVtbl): IDispatch(IDispatchVtbl) { + fn LoadResource( + &mut self, bstrResourceUri: ::BSTR, fAlwaysReload: ::VARIANT_BOOL, + pStream: *mut *mut ::IUnknown, pbstrMIMEType: *mut ::BSTR, pfModified: *mut ::VARIANT_BOOL, + pbstrRedirectUrl: *mut ::BSTR + ) -> ::HRESULT, + fn GetLocalCopy( + &mut self, bstrResourceUri: ::BSTR, pbstrLocalPath: *mut ::BSTR, + pbstrMIMEType: *mut ::BSTR, pbstrRedirectUrl: *mut ::BSTR + ) -> ::HRESULT, + fn ReleaseLocalCopy(&mut self, pbstrLocalPath: ::BSTR) -> ::HRESULT +} +); +STRUCT!{nodebug struct SPRECOCONTEXTSTATUS { + eInterference: SPINTERFERENCE, + szRequestTypeOfUI: [::WCHAR; 255], + dwReserved1: ::DWORD, + dwReserved2: ::DWORD, +}} +FLAGS!{enum SPBOOKMARKOPTIONS { + SPBO_NONE = 0, + SPBO_PAUSE = 1 << 0, + SPBO_AHEAD = 1 << 1, + SPBO_TIME_UNITS = 1 << 2, +}} +FLAGS!{enum SPAUDIOOPTIONS { + SPAO_NONE = 0, + SPAO_RETAIN_AUDIO = 1 << 0, +}} +RIDL!( +interface ISpRecoContext(ISpRecoContextVtbl): ISpEventSource(ISpEventSourceVtbl) { + fn GetRecognizer(&mut self, ppRecognizer: *mut *mut ISpRecognizer) -> ::HRESULT, + fn CreateGrammer( + &mut self, ullGrammarId: ::ULONGLONG, ppGrammar: *mut *mut ISpRecoGrammar + ) -> ::HRESULT, + fn GetStatus(&mut self, pState: *mut SPRECOCONTEXTSTATUS) -> ::HRESULT, + fn GetMaxAlternates(&mut self, pcAlternates: *mut ::ULONG) -> ::HRESULT, + fn SetMaxAlternates(&mut self, cAlternates: ::ULONG) -> ::HRESULT, + fn SetAudioOptions( + &mut self, Options: SPAUDIOOPTIONS, pAudioFormatId: *const ::GUID, + pWaveFormatEx: *const ::WAVEFORMATEX + ) -> ::HRESULT, + fn GetAudioOptions( + &mut self, pOptions: *mut SPAUDIOOPTIONS, pAudioFormatId: *mut ::GUID, + ppCoMemWFEX: *mut *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn DeserializeResult( + &mut self, pSerializedResult: *const SPSERIALIZEDRESULT, ppResult: *mut *mut ISpRecoResult + ) -> ::HRESULT, + fn Bookmark( + &mut self, Options: SPBOOKMARKOPTIONS, ullStreamPosition: ::ULONGLONG, + lparamEvent: ::LPARAM + ) -> ::HRESULT, + fn SetAdaptionData(&mut self, pAdaptionData: ::LPCWSTR, cch: ::ULONG) -> ::HRESULT, + fn Pause(&mut self, dwReserved: ::DWORD) -> ::HRESULT, + fn Resume(&mut self, dwReserved: ::DWORD) -> ::HRESULT, + fn SetVoice(&mut self, pVoice: *mut ISpVoice, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetVoice(&mut self, ppVoice: *mut *mut ISpVoice) -> ::HRESULT, + fn SetVoicePurgeEvent(&mut self, ullEventIntereset: ::ULONGLONG) -> ::HRESULT, + fn GetVoicePurgeEvent(&mut self, pullEventIntereset: *mut ::ULONGLONG) -> ::HRESULT, + fn SetContextState(&mut self, eContextState: SPCONTEXTSTATE) -> ::HRESULT, + fn GetContextState(&mut self, peContextState: *mut SPCONTEXTSTATE) -> ::HRESULT +} +); +FLAGS!{enum SPGRAMMAROPTIONS { + SPGO_SAPI = 0x1, + SPGO_SRGS = 0x2, + SPGO_UPS = 0x4, + SPGO_SRGS_MS_SCRIPT = 0x8, + SPGO_SRGS_W3C_SCRIPT = 0x100, + SPGO_SRGS_STG_SCRIPT = 0x200, + SPGO_SRGS_SCRIPT = + SPGO_SRGS.0 | SPGO_SRGS_MS_SCRIPT.0 | SPGO_SRGS_W3C_SCRIPT.0 | + SPGO_SRGS_STG_SCRIPT.0, + SPGO_FILE = 0x10, + SPGO_HTTP = 0x20, + SPGO_RES = 0x40, + SPGO_OBJECT = 0x80, + SPGO_DEFAULT = 0x3fb, + SPGO_ALL = 0x3ff, +}} +FLAGS!{enum SPADAPTATIONSETTINGS { + SPADS_Default = 0, + SPADS_CurrentRecognizer = 0x1, + SPADS_RecoProfile = 0x2, + SPADS_Immediate = 0x4, + SPADS_Reset = 0x8, + SPADS_HighVolumeDataSource = 0x10, +}} +ENUM!{enum SPADAPTATIONRELEVANCE { + SPAR_Unknown = 0, + SPAR_Low = 1, + SPAR_Medium = 2, + SPAR_High = 3, +}} +RIDL!( +interface ISpRecoContext2(ISpRecoContext2Vtbl): IUnknown(IUnknownVtbl) { + fn SetGrammarOptions(&mut self, eGrammarOptions: ::DWORD) -> ::HRESULT, + fn GetGrammarOptions(&mut self, peGrammarOptions: *mut ::DWORD) -> ::HRESULT, + fn SetAdaptationData2( + &mut self, pAdaptationData: ::LPCWSTR, cch: ::ULONG, pTopicName: ::LPCWSTR, + eAdaptationSettings: ::DWORD, eRelevance: SPADAPTATIONRELEVANCE + ) -> ::HRESULT +} +); +RIDL!( +interface ISpProperties(ISpPropertiesVtbl): IUnknown(IUnknownVtbl) { + fn SetPropertyNum(&mut self, pName: ::LPCWSTR, lValue: ::LONG) -> ::HRESULT, + fn GetPropertyNum(&mut self, pName: ::LPCWSTR, plValue: *mut ::LONG) -> ::HRESULT, + fn SetPropertyString(&mut self, pName: ::LPCWSTR, pValue: ::LPCWSTR) -> ::HRESULT, + fn GetPropertyString(&mut self, pName: ::LPCWSTR, ppCoMemValue: *mut ::LPWSTR) -> ::HRESULT +} +); +STRUCT!{struct SPRECOGNIZERSTATUS { + AudioStatus: SPAUDIOSTATUS, + ullRecognitionStreamPos: ::ULONGLONG, + ulStreamNumber: ::ULONG, + ulNumActive: ::ULONG, + clsidEngine: ::CLSID, + cLangIDs: ::ULONG, + aLangID: [::WORD; 20], + ullRecognitionStreamTime: ::ULONGLONG, +}} +ENUM!{enum SPWAVEFORMATTYPE { + SPWF_INPUT = 0, + SPWF_SRENGINE = 1, +}} +pub type SPSTREAMFORMATTYPE = SPWAVEFORMATTYPE; +ENUM!{enum SPRECOSTATE { + SPRST_INACTIVE = 0, + SPRST_ACTIVE = 1, + SPRST_ACTIVE_ALWAYS = 2, + SPRST_INACTIVE_WITH_PURGE = 3, + SPRST_NUM_STATES = 4, +}} +RIDL!( +interface ISpRecognizer(ISpRecognizerVtbl): ISpProperties(ISpPropertiesVtbl) { + fn SetRecognizer(&mut self, pRecognizer: *mut ISpObjectToken) -> ::HRESULT, + fn GetRecognizer(&mut self, ppRecognizer: *mut *mut ISpObjectToken) -> ::HRESULT, + fn SetInput(&mut self, pUnkInput: *mut ::IUnknown, fAllowFormatChanges: ::BOOL) -> ::HRESULT, + fn GetInputObjectToken(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn GetInputStream(&mut self, ppStream: *mut *mut ISpStreamFormat) -> ::HRESULT, + fn CreateRecoContext(&mut self, ppNewCtxt: *mut *mut ISpRecoContext) -> ::HRESULT, + fn GetRecoProfile(&mut self, ppToken: *mut *mut ISpObjectToken) -> ::HRESULT, + fn SetRecoProfile(&mut self, pToken: *mut ISpObjectToken) -> ::HRESULT, + fn IsSharedInstance(&mut self) -> ::HRESULT, + fn GetRecoState(&mut self, pState: *mut SPRECOSTATE) -> ::HRESULT, + fn SetRecoState(&mut self, NewState: SPRECOSTATE) -> ::HRESULT, + fn GetStatus(&mut self, pStatus: *mut SPRECOGNIZERSTATUS) -> ::HRESULT, + fn GetFormat( + &mut self, WaveFormatType: SPSTREAMFORMATTYPE, pFormatId: *mut ::GUID, + ppCoMemWFEX: *mut ::WAVEFORMATEX + ) -> ::HRESULT, + fn IsUISupported( + &mut self, pszTypeOfUI: ::LPCWSTR, pvExtraData: *mut ::c_void, cbExtraData: ::ULONG, + pfSupported: *mut ::BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hwndParent: ::HWND, pszTitle: ::LPCWSTR, pszTypeOfUI: ::LPCWSTR, + pvExtraData: *mut ::c_void, cbExtraData: ::ULONG + ) -> ::HRESULT, + fn EmulateRecognition(&mut self, pPhrase: *mut ISpPhrase) -> ::HRESULT +} +); +RIDL!( +interface ISpSerializeState(ISpSerializeStateVtbl): IUnknown(IUnknownVtbl) { + fn GetSerializedState( + &mut self, ppbData: *mut *mut ::BYTE, pulSize: *mut ::ULONG, dwReserved: ::DWORD + ) -> ::HRESULT, + fn SetSerializedState( + &mut self, pbData: *mut ::BYTE, ulSize: ::ULONG, dwReserved: ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface ISpRecognizer2(ISpRecognizer2Vtbl): IUnknown(IUnknownVtbl) { + fn EmulateRecognitionEx( + &mut self, pPhrase: *mut ISpPhrase, dwCompareFlags: ::DWORD + ) -> ::HRESULT, + fn SetTrainingState( + &mut self, fDoingTraining: ::BOOL, fAdaptFromTrainingData: ::BOOL + ) -> ::HRESULT, + fn ResetAcousticModelAdaptation(&mut self) -> ::HRESULT +} +); +ENUM!{enum SPCATEGORYTYPE { + SPCT_COMMAND = 0, + SPCT_DICTATION, + SPCT_SLEEP, + SPCT_SUB_COMMAND, + SPCT_SUB_DICTATION, +}} +RIDL!( +interface ISpRecoCategory(ISpRecoCategoryVtbl): IUnknown(IUnknownVtbl) { + fn GetType(&mut self, peCategoryType: *mut SPCATEGORYTYPE) -> ::HRESULT +} +); +RIDL!( +interface ISpRecognizer3(ISpRecognizer3Vtbl): IUnknown(IUnknownVtbl) { + fn GetCategory( + &mut self, categoryType: SPCATEGORYTYPE, ppCategory: *mut *mut ISpRecoCategory + ) -> ::HRESULT, + fn SetActiveCategory(&mut self, pCategory: *mut ISpRecoCategory) -> ::HRESULT, + fn GetActiveCategory(&mut self, ppCategory: *mut *mut ISpRecoCategory) -> ::HRESULT +} +); +STRUCT!{struct SPNORMALIZATIONLIST { + ulSize: ::ULONG, + ppszzNormalizedList: *mut *mut ::WCHAR, +}} +RIDL!( +interface ISpEnginePronunciation(ISpEnginePronunciationVtbl): IUnknown(IUnknownVtbl) { + fn Normalize( + &mut self, pszWord: ::LPCWSTR, pszLeftContext: ::LPCWSTR, pszRightContext: ::LPCWSTR, + LangID: ::WORD, pNormalizationList: *mut SPNORMALIZATIONLIST + ) -> ::HRESULT, + fn GetPronunciations( + &mut self, pszWord: ::LPCWSTR, pszLeftContext: ::LPCWSTR, pszRightContext: ::LPCWSTR, + LangID: ::WORD, pEnginePronunciationList: *mut SPWORDPRONUNCIATIONLIST + ) -> ::HRESULT +} +); +STRUCT!{struct SPDISPLAYTOKEN { + pszLexical: *const ::WCHAR, + pszDisplay: *const ::WCHAR, + bDisplayAttributes: ::BYTE, +}} +STRUCT!{struct SPDISPLAYPHRASE { + ulNumTokens: ::ULONG, + pTokens: *mut SPDISPLAYTOKEN, +}} +RIDL!( +interface ISpDisplayAlternates(ISpDisplayAlternatesVtbl): IUnknown(IUnknownVtbl) { + fn GetDisplayAlternates( + &mut self, pPhrase: *const SPDISPLAYPHRASE, cRequestCount: ::ULONG, + ppCoMemPhrases: *mut *mut SPDISPLAYPHRASE, pcPhrasesReturned: *mut ::ULONG + ) -> ::HRESULT, + fn SetFullStopTrailSpace(&mut self, ulTrailSpace: ::ULONG) -> ::HRESULT +} +); +pub type SpeechLanguageId = ::c_long; +ENUM!{enum DISPID_SpeechDataKey { + DISPID_SDKSetBinaryValue = 1, + DISPID_SDKGetBinaryValue, + DISPID_SDKSetStringValue, + DISPID_SDKGetStringValue, + DISPID_SDKSetLongValue, + DISPID_SDKGetlongValue, + DISPID_SDKOpenKey, + DISPID_SDKCreateKey, + DISPID_SDKDeleteKey, + DISPID_SDKDeleteValue, + DISPID_SDKEnumKeys, + DISPID_SDKEnumValues, +}} +ENUM!{enum DISPID_SpeechObjectToken { + DISPID_SOTId = 1, + DISPID_SOTDataKey, + DISPID_SOTCategory, + DISPID_SOTGetDescription, + DISPID_SOTSetId, + DISPID_SOTGetAttribute, + DISPID_SOTCreateInstance, + DISPID_SOTRemove, + DISPID_SOTGetStorageFileName, + DISPID_SOTRemoveStorageFileName, + DISPID_SOTIsUISupported, + DISPID_SOTDisplayUI, + DISPID_SOTMatchesAttributes, +}} +ENUM!{enum SpeechDataKeyLocation { + SDKLDefaultLocation = SPDKL_DefaultLocation.0, + SDKLCurrentUser = SPDKL_CurrentUser.0, + SDKLLocalMachine = SPDKL_LocalMachine.0, + SDKLCurrentConfig = SPDKL_CurrentConfig.0, +}} +ENUM!{enum SpeechTokenContext { + STCInprocServer = ::CLSCTX_INPROC_SERVER, + STCInprocHandler = ::CLSCTX_INPROC_HANDLER, + STCLocalServer = ::CLSCTX_LOCAL_SERVER, + STCRemoteServer = ::CLSCTX_REMOTE_SERVER, + STCAll = ::CLSCTX_INPROC_SERVER | ::CLSCTX_INPROC_HANDLER | + ::CLSCTX_LOCAL_SERVER | ::CLSCTX_REMOTE_SERVER, +}} +ENUM!{enum SpeechTokenShellFolder { + STSF_AppData = 0x1a, + STSF_LocalAppData = 0x1c, + STSF_CommonAppData = 0x23, + STSF_FlagCreate = 0x8000, +}} +ENUM!{enum DISPID_SpeechObjectTokens { + DISPID_SOTsCount = 1, + DISPID_SOTsItem = ::DISPID_VALUE as u32, + DISPID_SOTs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechObjectTokenCategory { + DISPID_SOTCId = 1, + DISPID_SOTCDefault, + DISPID_SOTCSetId, + DISPID_SOTCGetDataKey, + DISPID_SOTCEnumerateTokens, +}} +ENUM!{enum SpeechAudioFormatType { + SAFTDefault = -1i32 as u32, + SAFTNoAssignedFormat = 0, + SAFTText = 1, + SAFTNonStandardFormat = 2, + SAFTExtendedAudioFormat = 3, + SAFT8kHz8BitMono = 4, + SAFT8kHz8BitStereo = 5, + SAFT8kHz16BitMono = 6, + SAFT8kHz16BitStereo = 7, + SAFT11kHz8BitMono = 8, + SAFT11kHz8BitStereo = 9, + SAFT11kHz16BitMono = 10, + SAFT11kHz16BitStereo = 11, + SAFT12kHz8BitMono = 12, + SAFT12kHz8BitStereo = 13, + SAFT12kHz16BitMono = 14, + SAFT12kHz16BitStereo = 15, + SAFT16kHz8BitMono = 16, + SAFT16kHz8BitStereo = 17, + SAFT16kHz16BitMono = 18, + SAFT16kHz16BitStereo = 19, + SAFT22kHz8BitMono = 20, + SAFT22kHz8BitStereo = 21, + SAFT22kHz16BitMono = 22, + SAFT22kHz16BitStereo = 23, + SAFT24kHz8BitMono = 24, + SAFT24kHz8BitStereo = 25, + SAFT24kHz16BitMono = 26, + SAFT24kHz16BitStereo = 27, + SAFT32kHz8BitMono = 28, + SAFT32kHz8BitStereo = 29, + SAFT32kHz16BitMono = 30, + SAFT32kHz16BitStereo = 31, + SAFT44kHz8BitMono = 32, + SAFT44kHz8BitStereo = 33, + SAFT44kHz16BitMono = 34, + SAFT44kHz16BitStereo = 35, + SAFT48kHz8BitMono = 36, + SAFT48kHz8BitStereo = 37, + SAFT48kHz16BitMono = 38, + SAFT48kHz16BitStereo = 39, + SAFTTrueSpeech_8kHz1BitMono = 40, + SAFTCCITT_ALaw_8kHzMono = 41, + SAFTCCITT_ALaw_8kHzStereo = 42, + SAFTCCITT_ALaw_11kHzMono = 43, + SAFTCCITT_ALaw_11kHzStereo = 44, + SAFTCCITT_ALaw_22kHzMono = 45, + SAFTCCITT_ALaw_22kHzStereo = 46, + SAFTCCITT_ALaw_44kHzMono = 47, + SAFTCCITT_ALaw_44kHzStereo = 48, + SAFTCCITT_uLaw_8kHzMono = 49, + SAFTCCITT_uLaw_8kHzStereo = 50, + SAFTCCITT_uLaw_11kHzMono = 51, + SAFTCCITT_uLaw_11kHzStereo = 52, + SAFTCCITT_uLaw_22kHzMono = 53, + SAFTCCITT_uLaw_22kHzStereo = 54, + SAFTCCITT_uLaw_44kHzMono = 55, + SAFTCCITT_uLaw_44kHzStereo = 56, + SAFTADPCM_8kHzMono = 57, + SAFTADPCM_8kHzStereo = 58, + SAFTADPCM_11kHzMono = 59, + SAFTADPCM_11kHzStereo = 60, + SAFTADPCM_22kHzMono = 61, + SAFTADPCM_22kHzStereo = 62, + SAFTADPCM_44kHzMono = 63, + SAFTADPCM_44kHzStereo = 64, + SAFTGSM610_8kHzMono = 65, + SAFTGSM610_11kHzMono = 66, + SAFTGSM610_22kHzMono = 67, + SAFTGSM610_44kHzMono = 68, +}} +ENUM!{enum DISPID_SpeechAudioFormat { + DISPID_SAFType = 1, + DISPID_SAFGuid, + DISPID_SAFGetWaveFormatEx, + DISPID_SAFSetWaveFormatEx, +}} +ENUM!{enum DISPID_SpeechBaseStream { + DISPID_SBSFormat = 1, + DISPID_SBSRead, + DISPID_SBSWrite, + DISPID_SBSSeek, +}} +ENUM!{enum SpeechStreamSeekPositionType { + SSSPTRelativeToStart = ::STREAM_SEEK_SET.0, + SSSPTRelativeToCurrentPosition = ::STREAM_SEEK_CUR.0, + SSSPTRelativeToEnd = ::STREAM_SEEK_END.0, +}} +ENUM!{enum DISPID_SpeechAudio { + DISPID_SAStatus = 200, + DISPID_SABufferInfo, + DISPID_SADefaultFormat, + DISPID_SAVolume, + DISPID_SABufferNotifySize, + DISPID_SAEventHandle, + DISPID_SASetState, +}} +ENUM!{enum SpeechAudioState { + SASClosed = SPAS_CLOSED.0, + SASStop = SPAS_STOP.0, + SASPause = SPAS_PAUSE.0, + SASRun = SPAS_RUN.0, +}} +ENUM!{enum DISPID_SpeechMMSysAudio { + DISPID_SMSADeviceId = 300, + DISPID_SMSALineId, + DISPID_SMSAMMHandle, +}} +ENUM!{enum DISPID_SpeechFileStream { + DISPID_SFSOpen = 100, + DISPID_SFSClose, +}} +ENUM!{enum SpeechStreamFileMode { + SSFMOpenForRead = SPFM_OPEN_READONLY.0, + SSFMOpenReadWrite = SPFM_OPEN_READWRITE.0, + SSFMCreate = SPFM_CREATE.0, + SSFMCreateForWrite = SPFM_CREATE_ALWAYS.0, +}} +ENUM!{enum DISPID_SpeechCustomStream { + DISPID_SCSBaseStream = 100, +}} +ENUM!{enum DISPID_SpeechMemoryStream { + DISPID_SMSSetData = 100, + DISPID_SMSGetData, +}} +ENUM!{enum DISPID_SpeechAudioStatus { + DISPID_SASFreeBufferSpace = 1, + DISPID_SASNonBlockingIO, + DISPID_SASState, + DISPID_SASCurrentSeekPosition, + DISPID_SASCurrentDevicePosition, +}} +ENUM!{enum DISPID_SpeechAudioBufferInfo { + DISPID_SABIMinNotification = 1, + DISPID_SABIBufferSize, + DISPID_SABIEventBias, +}} +ENUM!{enum DISPID_SpeechWaveFormatEx { + DISPID_SWFEFormatTag = 1, + DISPID_SWFEChannels, + DISPID_SWFESamplesPerSec, + DISPID_SWFEAvgBytesPerSec, + DISPID_SWFEBlockAlign, + DISPID_SWFEBitsPerSample, + DISPID_SWFEExtraData, +}} +ENUM!{enum DISPID_SpeechVoice { + DISPID_SVStatus = 1, + DISPID_SVVoice, + DISPID_SVAudioOutput, + DISPID_SVAudioOutputStream, + DISPID_SVRate, + DISPID_SVVolume, + DISPID_SVAllowAudioOuputFormatChangesOnNextSet, + DISPID_SVEventInterests, + DISPID_SVPriority, + DISPID_SVAlertBoundary, + DISPID_SVSyncronousSpeakTimeout, + DISPID_SVSpeak, + DISPID_SVSpeakStream, + DISPID_SVPause, + DISPID_SVResume, + DISPID_SVSkip, + DISPID_SVGetVoices, + DISPID_SVGetAudioOutputs, + DISPID_SVWaitUntilDone, + DISPID_SVSpeakCompleteEvent, + DISPID_SVIsUISupported, + DISPID_SVDisplayUI, +}} +ENUM!{enum SpeechVoicePriority { + SVPNormal = SPVPRI_NORMAL.0, + SVPAlert = SPVPRI_ALERT.0, + SVPOver = SPVPRI_OVER.0, +}} +FLAGS!{enum SpeechVoiceSpeakFlags { + SVSFDefault = SPF_DEFAULT.0, + SVSFlagsAsync = SPF_ASYNC.0, + SVSFPurgeBeforeSpeak = SPF_PURGEBEFORESPEAK.0, + SVSFIsFilename = SPF_IS_FILENAME.0, + SVSFIsXML = SPF_IS_XML.0, + SVSFIsNotXML = SPF_IS_NOT_XML.0, + SVSFPersistXML = SPF_PERSIST_XML.0, + SVSFNLPSpeakPunc = SPF_NLP_SPEAK_PUNC.0, + SVSFParseSapi = SPF_PARSE_SAPI.0, + SVSFParseSsml = SPF_PARSE_SSML.0, + SVSFParseMask = SPF_PARSE_MASK as u32, + SVSFVoiceMask = SPF_VOICE_MASK as u32, + SVSFUnusedFlags = SPF_UNUSED_FLAGS as u32, +}} +pub const SVSFParseAutodetect: SpeechVoiceSpeakFlags = SVSFDefault; +pub const SVSFNLPMask: SpeechVoiceSpeakFlags = SVSFNLPSpeakPunc; +FLAGS!{enum SpeechVoiceEvents { + SVEStartInputStream = 1 << 1, + SVEEndInputStream = 1 << 2, + SVEVoiceChange = 1 << 3, + SVEBookmark = 1 << 4, + SVEWordBoundary = 1 << 5, + SVEPhoneme = 1 << 6, + SVESentenceBoundary = 1 << 7, + SVEViseme = 1 << 8, + SVEAudioLevel = 1 << 9, + SVEPrivate = 1 << 15, + SVEAllEvents = 0x83fe, +}} +ENUM!{enum DISPID_SpeechVoiceStatus { + DISPID_SVSCurrentStreamNumber = 1, + DISPID_SVSLastStreamNumberQueued, + DISPID_SVSLastResult, + DISPID_SVSRunningState, + DISPID_SVSInputWordPosition, + DISPID_SVSInputWordLength, + DISPID_SVSInputSentencePosition, + DISPID_SVSInputSentenceLength, + DISPID_SVSLastBookmark, + DISPID_SVSLastBookmarkId, + DISPID_SVSPhonemeId, + DISPID_SVSVisemeId, +}} +ENUM!{enum SpeechRunState { + SRSEDone = SPRS_DONE.0, + SRSEIsSpeaking = SPRS_IS_SPEAKING.0, +}} +ENUM!{enum SpeechVisemeType { + SVP_0 = 0, + SVP_1, + SVP_2, + SVP_3, + SVP_4, + SVP_5, + SVP_6, + SVP_7, + SVP_8, + SVP_9, + SVP_10, + SVP_11, + SVP_12, + SVP_13, + SVP_14, + SVP_15, + SVP_16, + SVP_17, + SVP_18, + SVP_19, + SVP_20, + SVP_21, +}} +ENUM!{enum SpeechVisemeFeature { + SVF_None = 0, + SVF_Stressed = SPVFEATURE_STRESSED.0, + SVF_Emphasis = SPVFEATURE_EMPHASIS.0, +}} +ENUM!{enum DISPID_SpeechVoiceEvent { + DISPID_SVEStreamStart = 1, + DISPID_SVEStreamEnd, + DISPID_SVEVoiceChange, + DISPID_SVEBookmark, + DISPID_SVEWord, + DISPID_SVEPhoneme, + DISPID_SVESentenceBoundary, + DISPID_SVEViseme, + DISPID_SVEAudioLevel, + DISPID_SVEEnginePrivate, +}} +ENUM!{enum DISPID_SpeechRecognizer { + DISPID_SRRecognizer = 1, + DISPID_SRAllowAudioInputFormatChangesOnNextSet, + DISPID_SRAudioInput, + DISPID_SRAudioInputStream, + DISPID_SRIsShared, + DISPID_SRState, + DISPID_SRStatus, + DISPID_SRProfile, + DISPID_SREmulateRecognition, + DISPID_SRCreateRecoContext, + DISPID_SRGetFormat, + DISPID_SRSetPropertyNumber, + DISPID_SRGetPropertyNumber, + DISPID_SRSetPropertyString, + DISPID_SRGetPropertyString, + DISPID_SRIsUISupported, + DISPID_SRDisplayUI, + DISPID_SRGetRecognizers, + DISPID_SVGetAudioInputs, + DISPID_SVGetProfiles, +}} +ENUM!{enum SpeechRecognizerState { + SRSInactive = SPRST_INACTIVE.0, + SRSActive = SPRST_ACTIVE.0, + SRSActiveAlways = SPRST_ACTIVE_ALWAYS.0, + SRSInactiveWithPurge = SPRST_INACTIVE_WITH_PURGE.0, +}} +ENUM!{enum SpeechDisplayAttributes { + SDA_No_Trailing_Space = 0, + SDA_One_Trailing_Space = SPAF_ONE_TRAILING_SPACE.0, + SDA_Two_Trailing_Spaces = SPAF_TWO_TRAILING_SPACES.0, + SDA_Consume_Leading_Spaces = SPAF_CONSUME_LEADING_SPACES.0, +}} +ENUM!{enum SpeechFormatType { + SFTInput = SPWF_INPUT.0, + SFTSREngine = SPWF_SRENGINE.0, +}} +FLAGS!{enum SpeechEmulationCompareFlags { + SECFIgnoreCase = 0x1, + SECFIgnoreKanaType = 0x10000, + SECFIgnoreWidth = 0x20000, + SECFNoSpecialChars = 0x20000000, + SECFEmulateResult = 0x40000000, + SECFDefault = SECFIgnoreCase.0 | SECFIgnoreKanaType.0 | SECFIgnoreWidth.0, +}} +ENUM!{enum DISPID_SpeechRecognizerStatus { + DISPID_SRSAudioStatus = 1, + DISPID_SRSCurrentStreamPosition, + DISPID_SRSCurrentStreamNumber, + DISPID_SRSNumberOfActiveRules, + DISPID_SRSClsidEngine, + DISPID_SRSSupportedLanguages, +}} +ENUM!{enum DISPID_SpeechRecoContext { + DISPID_SRCRecognizer = 1, + DISPID_SRCAudioInInterferenceStatus, + DISPID_SRCRequestedUIType, + DISPID_SRCVoice, + DISPID_SRAllowVoiceFormatMatchingOnNextSet, + DISPID_SRCVoicePurgeEvent, + DISPID_SRCEventInterests, + DISPID_SRCCmdMaxAlternates, + DISPID_SRCState, + DISPID_SRCRetainedAudio, + DISPID_SRCRetainedAudioFormat, + DISPID_SRCPause, + DISPID_SRCResume, + DISPID_SRCCreateGrammar, + DISPID_SRCCreateResultFromMemory, + DISPID_SRCBookmark, + DISPID_SRCSetAdaptationData, +}} +ENUM!{enum SpeechRetainedAudioOptions { + SRAONone = SPAO_NONE.0, + SRAORetainAudio = SPAO_RETAIN_AUDIO.0, +}} +ENUM!{enum SpeechBookmarkOptions { + SBONone = SPBO_NONE.0, + SBOPause = SPBO_PAUSE.0, +}} +ENUM!{enum SpeechInterference { + SINone = SPINTERFERENCE_NONE.0, + SINoise = SPINTERFERENCE_NOISE.0, + SINoSignal = SPINTERFERENCE_NOSIGNAL.0, + SITooLoud = SPINTERFERENCE_TOOLOUD.0, + SITooQuiet = SPINTERFERENCE_TOOQUIET.0, + SITooFast = SPINTERFERENCE_TOOFAST.0, + SITooSlow = SPINTERFERENCE_TOOSLOW.0, +}} +FLAGS!{enum SpeechRecoEvents { + SREStreamEnd = 1 << 0, + SRESoundStart = 1 << 1, + SRESoundEnd = 1 << 2, + SREPhraseStart = 1 << 3, + SRERecognition = 1 << 4, + SREHypothesis = 1 << 5, + SREBookmark = 1 << 6, + SREPropertyNumChange = 1 << 7, + SREPropertyStringChange = 1 << 8, + SREFalseRecognition = 1 << 9, + SREInterference = 1 << 10, + SRERequestUI = 1 << 11, + SREStateChange = 1 << 12, + SREAdaptation = 1 << 13, + SREStreamStart = 1 << 14, + SRERecoOtherContext = 1 << 15, + SREAudioLevel = 1 << 16, + SREPrivate = 1 << 18, + SREAllEvents = 0x5ffff, +}} +ENUM!{enum SpeechRecoContextState { + SRCS_Disabled = SPCS_DISABLED.0, + SRCS_Enabled = SPCS_ENABLED.0, +}} +ENUM!{enum DISPIDSPRG { + DISPID_SRGId = 1, + DISPID_SRGRecoContext, + DISPID_SRGState, + DISPID_SRGRules, + DISPID_SRGReset, + DISPID_SRGCommit, + DISPID_SRGCmdLoadFromFile, + DISPID_SRGCmdLoadFromObject, + DISPID_SRGCmdLoadFromResource, + DISPID_SRGCmdLoadFromMemory, + DISPID_SRGCmdLoadFromProprietaryGrammar, + DISPID_SRGCmdSetRuleState, + DISPID_SRGCmdSetRuleIdState, + DISPID_SRGDictationLoad, + DISPID_SRGDictationUnload, + DISPID_SRGDictationSetState, + DISPID_SRGSetWordSequenceData, + DISPID_SRGSetTextSelection, + DISPID_SRGIsPronounceable, +}} +ENUM!{enum SpeechLoadOption { + SLOStatic = SPLO_STATIC.0, + SLODynamic = SPLO_DYNAMIC.0, +}} +ENUM!{enum SpeechWordPronounceable { + SWPUnknownWordUnpronounceable = SPWP_UNKNOWN_WORD_UNPRONOUNCEABLE.0, + SWPUnknownWordPronounceable = SPWP_UNKNOWN_WORD_PRONOUNCEABLE.0, + SWPKnownWordPronounceable = SPWP_KNOWN_WORD_PRONOUNCEABLE.0, +}} +ENUM!{enum SpeechGrammarState { + SGSEnabled = SPGS_ENABLED.0, + SGSDisabled = SPGS_DISABLED.0, + SGSExclusive = SPGS_EXCLUSIVE.0, +}} +ENUM!{enum SpeechRuleState { + SGDSInactive = SPRS_INACTIVE.0, + SGDSActive = SPRS_ACTIVE.0, + SGDSActiveWithAutoPause = SPRS_ACTIVE_WITH_AUTO_PAUSE.0, + SGDSActiveUserDelimited = SPRS_ACTIVE_USER_DELIMITED.0, +}} +ENUM!{enum SpeechRuleAttributes { + SRATopLevel = SPRAF_TopLevel.0, + SRADefaultToActive = SPRAF_Active.0, + SRAExport = SPRAF_Export.0, + SRAImport = SPRAF_Import.0, + SRAInterpreter = SPRAF_Interpreter.0, + SRADynamic = SPRAF_Dynamic.0, + SRARoot = SPRAF_Root.0, +}} +ENUM!{enum SpeechGrammarWordType { + SGDisplay = SPWT_DISPLAY.0, + SGLexical = SPWT_LEXICAL.0, + SGPronounciation = SPWT_PRONUNCIATION.0, + SGLexicalNoSpecialChars = SPWT_LEXICAL_NO_SPECIAL_CHARS.0, +}} +ENUM!{enum DISPID_SpeechRecoContextEvents { + DISPID_SRCEStartStream = 1, + DISPID_SRCEEndStream, + DISPID_SRCEBookmark, + DISPID_SRCESoundStart, + DISPID_SRCESoundEnd, + DISPID_SRCEPhraseStart, + DISPID_SRCERecognition, + DISPID_SRCEHypothesis, + DISPID_SRCEPropertyNumberChange, + DISPID_SRCEPropertyStringChange, + DISPID_SRCEFalseRecognition, + DISPID_SRCEInterference, + DISPID_SRCERequestUI, + DISPID_SRCERecognizerStateChange, + DISPID_SRCEAdaptation, + DISPID_SRCERecognitionForOtherContext, + DISPID_SRCEAudioLevel, + DISPID_SRCEEnginePrivate, +}} +ENUM!{enum SpeechRecognitionType { + SRTStandard = 0, + SRTAutopause = SPREF_AutoPause.0, + SRTEmulated = SPREF_Emulated.0, + SRTSMLTimeout = SPREF_SMLTimeout.0, + SRTExtendableParse = SPREF_ExtendableParse.0, + SRTReSent = SPREF_ReSent.0, +}} +ENUM!{enum DISPID_SpeechGrammarRule { + DISPID_SGRAttributes = 1, + DISPID_SGRInitialState, + DISPID_SGRName, + DISPID_SGRId, + DISPID_SGRClear, + DISPID_SGRAddResource, + DISPID_SGRAddState, +}} +ENUM!{enum DISPID_SpeechGrammarRules { + DISPID_SGRsCount = 1, + DISPID_SGRsDynamic, + DISPID_SGRsAdd, + DISPID_SGRsCommit, + DISPID_SGRsCommitAndSave, + DISPID_SGRsFindRule, + DISPID_SGRsItem = ::DISPID_VALUE as u32, + DISPID_SGRs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechGrammarRuleState { + DISPID_SGRSRule = 1, + DISPID_SGRSTransitions, + DISPID_SGRSAddWordTransition, + DISPID_SGRSAddRuleTransition, + DISPID_SGRSAddSpecialTransition, +}} +ENUM!{enum SpeechSpecialTransitionType { + SSTTWildcard = 1, + SSTTDictation, + SSTTTextBuffer, +}} +ENUM!{enum DISPID_SpeechGrammarRuleStateTransitions { + DISPID_SGRSTsCount = 1, + DISPID_SGRSTsItem = ::DISPID_VALUE as u32, + DISPID_SGRSTs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechGrammarRuleStateTransition { + DISPID_SGRSTType = 1, + DISPID_SGRSTText, + DISPID_SGRSTRule, + DISPID_SGRSTWeight, + DISPID_SGRSTPropertyName, + DISPID_SGRSTPropertyId, + DISPID_SGRSTPropertyValue, + DISPID_SGRSTNextState, +}} +ENUM!{enum SpeechGrammarRuleStateTransitionType { + SGRSTTEpsilon = 0, + SGRSTTWord, + SGRSTTRule, + SGRSTTDictation, + SGRSTTWildcard, + SGRSTTTextBuffer, +}} +ENUM!{enum DISPIDSPTSI { + DISPIDSPTSI_ActiveOffset = 1, + DISPIDSPTSI_ActiveLength, + DISPIDSPTSI_SelectionOffset, + DISPIDSPTSI_SelectionLength, +}} +ENUM!{enum DISPID_SpeechRecoResult { + DISPID_SRRRecoContext = 1, + DISPID_SRRTimes, + DISPID_SRRAudioFormat, + DISPID_SRRPhraseInfo, + DISPID_SRRAlternates, + DISPID_SRRAudio, + DISPID_SRRSpeakAudio, + DISPID_SRRSaveToMemory, + DISPID_SRRDiscardResultInfo, +}} +ENUM!{enum SpeechDiscardType { + SDTProperty = SPDF_PROPERTY.0, + SDTReplacement = SPDF_REPLACEMENT.0, + SDTRule = SPDF_RULE.0, + SDTDisplayText = SPDF_DISPLAYTEXT.0, + SDTLexicalForm = SPDF_LEXICALFORM.0, + SDTPronunciation = SPDF_PRONUNCIATION.0, + SDTAudio = SPDF_AUDIO.0, + SDTAlternates = SPDF_ALTERNATES.0, + SDTAll = SPDF_ALL.0, +}} +ENUM!{enum DISPID_SpeechXMLRecoResult { + DISPID_SRRGetXMLResult, + DISPID_SRRGetXMLErrorInfo, +}} +ENUM!{enum DISPID_SpeechRecoResult2 { + DISPID_SRRSetTextFeedback, +}} +ENUM!{enum DISPID_SpeechPhraseBuilder { + DISPID_SPPBRestorePhraseFromMemory = 1, +}} +ENUM!{enum DISPID_SpeechRecoResultTimes { + DISPID_SRRTStreamTime = 1, + DISPID_SRRTLength, + DISPID_SRRTTickCount, + DISPID_SRRTOffsetFromStart, +}} +ENUM!{enum DISPID_SpeechPhraseAlternate { + DISPID_SPARecoResult = 1, + DISPID_SPAStartElementInResult, + DISPID_SPANumberOfElementsInResult, + DISPID_SPAPhraseInfo, + DISPID_SPACommit, +}} +ENUM!{enum DISPID_SpeechPhraseAlternates { + DISPID_SPAsCount = 1, + DISPID_SPAsItem = ::DISPID_VALUE as u32, + DISPID_SPAs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseInfo { + DISPID_SPILanguageId = 1, + DISPID_SPIGrammarId, + DISPID_SPIStartTime, + DISPID_SPIAudioStreamPosition, + DISPID_SPIAudioSizeBytes, + DISPID_SPIRetainedSizeBytes, + DISPID_SPIAudioSizeTime, + DISPID_SPIRule, + DISPID_SPIProperties, + DISPID_SPIElements, + DISPID_SPIReplacements, + DISPID_SPIEngineId, + DISPID_SPIEnginePrivateData, + DISPID_SPISaveToMemory, + DISPID_SPIGetText, + DISPID_SPIGetDisplayAttributes, +}} +ENUM!{enum DISPID_SpeechPhraseElement { + DISPID_SPEAudioTimeOffset = 1, + DISPID_SPEAudioSizeTime, + DISPID_SPEAudioStreamOffset, + DISPID_SPEAudioSizeBytes, + DISPID_SPERetainedStreamOffset, + DISPID_SPERetainedSizeBytes, + DISPID_SPEDisplayText, + DISPID_SPELexicalForm, + DISPID_SPEPronunciation, + DISPID_SPEDisplayAttributes, + DISPID_SPERequiredConfidence, + DISPID_SPEActualConfidence, + DISPID_SPEEngineConfidence, +}} +ENUM!{enum SpeechEngineConfidence { + SECLowConfidence = -1i32 as u32, + SECNormalConfidence = 0, + SECHighConfidence = 1, +}} +ENUM!{enum DISPID_SpeechPhraseElements { + DISPID_SPEsCount = 1, + DISPID_SPEsItem = ::DISPID_VALUE as u32, + DISPID_SPEs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseReplacement { + DISPID_SPRDisplayAttributes = 1, + DISPID_SPRText, + DISPID_SPRFirstElement, + DISPID_SPRNumberOfElements, +}} +ENUM!{enum DISPID_SpeechPhraseReplacements { + DISPID_SPRsCount = 1, + DISPID_SPRsItem = ::DISPID_VALUE as u32, + DISPID_SPRs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseProperty { + DISPID_SPPName = 1, + DISPID_SPPId, + DISPID_SPPValue, + DISPID_SPPFirstElement, + DISPID_SPPNumberOfElements, + DISPID_SPPEngineConfidence, + DISPID_SPPConfidence, + DISPID_SPPParent, + DISPID_SPPChildren, +}} +ENUM!{enum DISPID_SpeechPhraseProperties { + DISPID_SPPsCount = 1, + DISPID_SPPsItem = ::DISPID_VALUE as u32, + DISPID_SPPs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechPhraseRule { + DISPID_SPRuleName = 1, + DISPID_SPRuleId, + DISPID_SPRuleFirstElement, + DISPID_SPRuleNumberOfElements, + DISPID_SPRuleParent, + DISPID_SPRuleChildren, + DISPID_SPRuleConfidence, + DISPID_SPRuleEngineConfidence, +}} +ENUM!{enum DISPID_SpeechPhraseRules { + DISPID_SPRulesCount = 1, + DISPID_SPRulesItem = ::DISPID_VALUE as u32, + DISPID_SPRules_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechLexicon { + DISPID_SLGenerationId = 1, + DISPID_SLGetWords, + DISPID_SLAddPronunciation, + DISPID_SLAddPronunciationByPhoneIds, + DISPID_SLRemovePronunciation, + DISPID_SLRemovePronunciationByPhoneIds, + DISPID_SLGetPronunciations, + DISPID_SLGetGenerationChange, +}} +ENUM!{enum SpeechLexiconType { + SLTUser = eLEXTYPE_USER.0, + SLTApp = eLEXTYPE_APP.0, +}} +ENUM!{enum SpeechPartOfSpeech { + SPSNotOverriden = SPPS_NotOverriden.0, + SPSUnknown = SPPS_Unknown.0, + SPSNoun = SPPS_Noun.0, + SPSVerb = SPPS_Verb.0, + SPSModifier = SPPS_Modifier.0, + SPSFunction = SPPS_Function.0, + SPSInterjection = SPPS_Interjection.0, + SPSLMA = SPPS_LMA.0, + SPSSuppressWord = SPPS_SuppressWord.0, +}} +ENUM!{enum DISPID_SpeechLexiconWords { + DISPID_SLWsCount = 1, + DISPID_SLWsItem = ::DISPID_VALUE as u32, + DISPID_SLWs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum SpeechWordType { + SWTAdded = eWORDTYPE_ADDED.0, + SWTDeleted = eWORDTYPE_DELETED.0, +}} +ENUM!{enum DISPID_SpeechLexiconWord { + DISPID_SLWLangId = 1, + DISPID_SLWType, + DISPID_SLWWord, + DISPID_SLWPronunciations, +}} +ENUM!{enum DISPID_SpeechLexiconProns { + DISPID_SLPsCount = 1, + DISPID_SLPsItem = ::DISPID_VALUE as u32, + DISPID_SLPs_NewEnum = ::DISPID_NEWENUM as u32, +}} +ENUM!{enum DISPID_SpeechLexiconPronunciation { + DISPID_SLPType = 1, + DISPID_SLPLangId, + DISPID_SLPPartOfSpeech, + DISPID_SLPPhoneIds, + DISPID_SLPSymbolic, +}} +ENUM!{enum DISPID_SpeechPhoneConverter { + DISPID_SPCLangId = 1, + DISPID_SPCPhoneToId, + DISPID_SPCIdToPhone, +}} +RIDL!( +interface ISpeechDataKey(ISpeechDataKeyVtbl): IDispatch(IDispatchVtbl) { + fn SetBinaryValue(&mut self, ValueName: ::BSTR, Value: ::VARIANT) -> ::HRESULT, + fn GetBinaryValue(&mut self, ValueName: ::BSTR, Value: *mut ::VARIANT) -> ::HRESULT, + fn SetStringValue(&mut self, ValueName: ::BSTR, Value: ::BSTR) -> ::HRESULT, + fn GetStringValue(&mut self, ValueName: ::BSTR, Value: *mut ::BSTR) -> ::HRESULT, + fn SetLongValue(&mut self, ValueName: ::BSTR, Value: ::c_long) -> ::HRESULT, + fn GetLongValue(&mut self, ValueName: ::BSTR, Value: *mut ::c_long) -> ::HRESULT, + fn OpenKey(&mut self, SubKeyName: ::BSTR, SubKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn CreateKey(&mut self, SubKeyName: ::BSTR, SubKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn DeleteKey(&mut self, SubKeyName: ::BSTR) -> ::HRESULT, + fn DeleteValue(&mut self, ValueName: ::BSTR) -> ::HRESULT, + fn EnumKeys(&mut self, Index: ::c_long, SubKeyName: *mut ::BSTR) -> ::HRESULT, + fn EnumValues(&mut self, Index: ::c_long, ValueName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectToken(ISpeechObjectTokenVtbl): IDispatch(IDispatchVtbl) { + fn get_Id(&mut self, ObjectId: *mut ::BSTR) -> ::HRESULT, + fn get_DataKey(&mut self, DataKey: *mut *mut ISpeechDataKey) -> ::HRESULT, + fn get_Category(&mut self, Category: *mut *mut ISpeechObjectTokenCategory) -> ::HRESULT, + fn GetDescription(&mut self, Locale: ::c_long, Description: *mut ::BSTR) -> ::HRESULT, + fn SetId( + &mut self, Id: ::BSTR, CategoryId: ::BSTR, CreateIfNotExist: ::VARIANT_BOOL + ) -> ::HRESULT, + fn GetAttribute(&mut self, AttributeName: ::BSTR, AttributeValue: *mut ::BSTR) -> ::HRESULT, + fn CreateInstance( + &mut self, pUnkOuter: *mut ::IUnknown, ClsContext: SpeechTokenContext, + Object: *mut *mut ::IUnknown + ) -> ::HRESULT, + fn Remove(&mut self, ObjectStorageCLSID: ::BSTR) -> ::HRESULT, + fn GetStorageFileName( + &mut self, ObjectStorageCLSID: ::BSTR, KeyName: ::BSTR, FileName: ::BSTR, Folder: ::BSTR, + FilePath: *mut ::BSTR + ) -> ::HRESULT, + fn RemoveStorageFileName( + &mut self, ObjectStorageCLSID: ::BSTR, KeyName: ::BSTR, DeleteFile: ::VARIANT_BOOL + ) -> ::HRESULT, + fn IsUISupported( + &mut self, TypeOfUI: ::BSTR, ExtraData: *const ::VARIANT, Object: *mut ::IUnknown, + Supported: *mut ::VARIANT_BOOL + ) -> ::HRESULT, + fn DisplayUI( + &mut self, hWnd: ::c_long, Title: ::BSTR, TypeOfUI: ::BSTR, ExtraData: *const ::VARIANT, + Object: *mut ::IUnknown + ) -> ::HRESULT, + fn MatchesAttributes(&mut self, Attributes: ::BSTR, Matches: *mut ::VARIANT_BOOL) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectTokens(ISpeechObjectTokensVtbl): IDispatch(IDispatchVtbl) { + fn get_Count(&mut self, Count: *mut ::c_long) -> ::HRESULT, + fn Item(&mut self, Index: ::c_long, Token: *mut *mut ISpeechObjectToken) -> ::HRESULT, + fn get__NewEnum(&mut self, ppEnumVARIANT: *mut *mut ::IUnknown) -> ::HRESULT +} +); +RIDL!( +interface ISpeechObjectTokenCategory(ISpeechObjectTokenCategoryVtbl): IDispatch(IDispatchVtbl) { + fn get_Id(&mut self, Id: *mut ::BSTR) -> ::HRESULT, + fn put_Default(&mut self, TokenId: ::BSTR) -> ::HRESULT, + fn get_Default(&mut self, TokenId: *mut ::BSTR) -> ::HRESULT, + fn SetId(&mut self, Id: ::BSTR, CreateIfNotExist: ::VARIANT_BOOL) -> ::HRESULT, + fn GetDataKey( + &mut self, Location: SpeechDataKeyLocation, DataKey: *mut *mut ISpeechDataKey + ) -> ::HRESULT, + fn EnumerateTokens( + &mut self, RequiredAttributes: ::BSTR, OptionalAttributes: ::BSTR, + Tokens: *mut *mut ISpeechObjectTokens + ) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioBufferInfo(ISpeechAudioBufferInfoVtbl): IDispatch(IDispatchVtbl) { + fn get_MinNotification(&mut self, MinNotification: *mut ::c_long) -> ::HRESULT, + fn put_MinNotification(&mut self, MinNotification: ::c_long) -> ::HRESULT, + fn get_BufferSize(&mut self, BufferSize: *mut ::c_long) -> ::HRESULT, + fn put_BufferSize(&mut self, BufferSize: ::c_long) -> ::HRESULT, + fn get_EventBias(&mut self, EventBias: *mut ::c_long) -> ::HRESULT, + fn put_EventBias(&mut self, EventBias: ::c_long) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioStatus(ISpeechAudioStatusVtbl): IDispatch(IDispatchVtbl) { + fn get_FreeBufferSpace(&mut self, FreeBufferSpace: *mut ::c_long) -> ::HRESULT, + fn get_NonBlockingIO(&mut self, NonBlockingIO: *mut ::c_long) -> ::HRESULT, + fn get_State(&mut self, State: *mut SpeechAudioState) -> ::HRESULT, + fn get_CurrentSeekPosition(&mut self, CurrentSeekPosition: *mut ::VARIANT) -> ::HRESULT, + fn get_CurrentDevicePosition(&mut self, CurrentDevicePosition: *mut ::VARIANT) -> ::HRESULT +} +); +RIDL!( +interface ISpeechAudioFormat(ISpeechAudioFormatVtbl): IDispatch(IDispatchVtbl) { + fn get_Type(&mut self, AudioFormat: *mut SpeechAudioFormatType) -> ::HRESULT, + fn put_Type(&mut self, AudioFormat: SpeechAudioFormatType) -> ::HRESULT, + fn get_Guid(&mut self, Guid: *mut ::BSTR) -> ::HRESULT, + fn put_Guid(&mut self, Guid: ::BSTR) -> ::HRESULT, + fn GetWaveFormatEx(&mut self, SpeechWaveFormatEx: *mut *mut ISpeechWaveFormatEx) -> ::HRESULT, + fn SetWaveFormatEx(&mut self, SpeechWaveFormatEx: *mut ISpeechWaveFormatEx) -> ::HRESULT +} +); +RIDL!( +interface ISpeechWaveFormatEx(ISpeechWaveFormatExVtbl): IDispatch(IDispatchVtbl) { + fn get_FormatTag(&mut self, FormatTag: *mut ::c_short) -> ::HRESULT, + fn put_FormatTag(&mut self, FormatTag: ::c_short) -> ::HRESULT, + fn get_Channels(&mut self, Channels: *mut ::c_short) -> ::HRESULT, + fn put_Channels(&mut self, Channels: ::c_short) -> ::HRESULT, + fn get_SamplesPerSec(&mut self, SamplesPerSec: *mut ::c_long) -> ::HRESULT, + fn put_SamplesPerSec(&mut self, SamplesPerSec: ::c_long) -> ::HRESULT, + fn get_AvgBytesPerSec(&mut self, AvgBytesPerSec: *mut ::c_long) -> ::HRESULT, + fn put_AvgBytesPerSec(&mut self, AvgBytesPerSec: ::c_long) -> ::HRESULT, + fn get_BlockAlign(&mut self, BlockAlign: *mut ::c_short) -> ::HRESULT, + fn put_BlockAlign(&mut self, BlockAlign: ::c_short) -> ::HRESULT, + fn get_BitsPerSample(&mut self, BitsPerSample: *mut ::c_short) -> ::HRESULT, + fn put_BitsPerSample(&mut self, BitsPerSample: ::c_short) -> ::HRESULT, + fn get_ExtraData(&mut self, ExtraData: *mut ::VARIANT) -> ::HRESULT, + fn put_ExtraData(&mut self, ExtraData: ::VARIANT) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/schannel.rs b/third_party/cargo/vendor/winapi-0.2.8/src/schannel.rs new file mode 100644 index 0000000..d57aec8 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/schannel.rs @@ -0,0 +1,333 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Public Definitions for SCHANNEL Security Provider +pub const UNISP_NAME: &'static str = "Microsoft Unified Security Protocol Provider"; +pub const SSL2SP_NAME: &'static str = "Microsoft SSL 2.0"; +pub const SSL3SP_NAME: &'static str = "Microsoft SSL 3.0"; +pub const TLS1SP_NAME: &'static str = "Microsoft TLS 1.0"; +pub const PCT1SP_NAME: &'static str = "Microsoft PCT 1.0"; +pub const SCHANNEL_NAME: &'static str = "Schannel"; +ENUM!{enum eTlsSignatureAlgorithm { + TlsSignatureAlgorithm_Anonymous = 0, + TlsSignatureAlgorithm_Rsa = 1, + TlsSignatureAlgorithm_Dsa = 2, + TlsSignatureAlgorithm_Ecdsa = 3, +}} +ENUM!{enum eTlsHashAlgorithm { + TlsHashAlgorithm_None = 0, + TlsHashAlgorithm_Md5 = 1, + TlsHashAlgorithm_Sha1 = 2, + TlsHashAlgorithm_Sha224 = 3, + TlsHashAlgorithm_Sha256 = 4, + TlsHashAlgorithm_Sha384 = 5, + TlsHashAlgorithm_Sha512 = 6, +}} +pub const UNISP_RPC_ID: ::DWORD = 14; +STRUCT!{struct SecPkgContext_RemoteCredentialInfo { + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, + cCertificates: ::DWORD, + fFlags: ::DWORD, + dwBits: ::DWORD, +}} +pub type PSecPkgContext_RemoteCredentialInfo = *mut SecPkgContext_RemoteCredentialInfo; +pub type SecPkgContext_RemoteCredenitalInfo = SecPkgContext_RemoteCredentialInfo; +pub type PSecPkgContext_RemoteCredenitalInfo = *mut SecPkgContext_RemoteCredentialInfo; +pub const RCRED_STATUS_NOCRED: ::DWORD = 0x00000000; +pub const RCRED_CRED_EXISTS: ::DWORD = 0x00000001; +pub const RCRED_STATUS_UNKNOWN_ISSUER: ::DWORD = 0x00000002; +STRUCT!{struct SecPkgContext_LocalCredentialInfo { + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, + cCertificates: ::DWORD, + fFlags: ::DWORD, + dwBits: ::DWORD, +}} +pub type PSecPkgContext_LocalCredentialInfo = *mut SecPkgContext_LocalCredentialInfo; +pub type SecPkgContext_LocalCredenitalInfo = SecPkgContext_LocalCredentialInfo; +pub type PSecPkgContext_LocalCredenitalInfo = *mut SecPkgContext_LocalCredentialInfo; +pub const LCRED_STATUS_NOCRED: ::DWORD = 0x00000000; +pub const LCRED_CRED_EXISTS: ::DWORD = 0x00000001; +pub const LCRED_STATUS_UNKNOWN_ISSUER: ::DWORD = 0x00000002; +STRUCT!{struct SecPkgContext_ClientCertPolicyResult { + dwPolicyResult: ::HRESULT, + guidPolicyId: ::GUID, +}} +pub type PSecPkgContext_ClientCertPolicyResult = *mut SecPkgContext_ClientCertPolicyResult; +STRUCT!{struct SecPkgContext_IssuerListInfoEx { + aIssuers: ::PCERT_NAME_BLOB, + cIssuers: ::DWORD, +}} +pub type PSecPkgContext_IssuerListInfoEx = *mut SecPkgContext_IssuerListInfoEx; +STRUCT!{struct SecPkgContext_ConnectionInfo { + dwProtocol: ::DWORD, + aiCipher: ::ALG_ID, + dwCipherStrength: ::DWORD, + aiHash: ::ALG_ID, + dwHashStrength: ::DWORD, + aiExch: ::ALG_ID, + dwExchStrength: ::DWORD, +}} +pub type PSecPkgContext_ConnectionInfo = *mut SecPkgContext_ConnectionInfo; +pub const SZ_ALG_MAX_SIZE: usize = 64; +pub const SECPKGCONTEXT_CIPHERINFO_V1: ::DWORD = 1; +STRUCT!{nodebug struct SecPkgContext_CipherInfo { + dwVersion: ::DWORD, + dwProtocol: ::DWORD, + dwCipherSuite: ::DWORD, + dwBaseCipherSuite: ::DWORD, + szCipherSuite: [::WCHAR; SZ_ALG_MAX_SIZE], + szCipher: [::WCHAR; SZ_ALG_MAX_SIZE], + dwCipherLen: ::DWORD, + dwCipherBlockLen: ::DWORD, + szHash: [::WCHAR; SZ_ALG_MAX_SIZE], + dwHashLen: ::DWORD, + szExchange: [::WCHAR; SZ_ALG_MAX_SIZE], + dwMinExchangeLen: ::DWORD, + dwMaxExchangeLen: ::DWORD, + szCertificate: [::WCHAR; SZ_ALG_MAX_SIZE], + dwKeyType: ::DWORD, +}} +pub type PSecPkgContext_CipherInfo = *mut SecPkgContext_CipherInfo; +STRUCT!{nodebug struct SecPkgContext_EapKeyBlock { + rgbKeys: [::BYTE; 128], + rgbIVs: [::BYTE; 64], +}} +pub type PSecPkgContext_EapKeyBlock = *mut SecPkgContext_EapKeyBlock; +STRUCT!{struct SecPkgContext_MappedCredAttr { + dwAttribute: ::DWORD, + pvBuffer: ::PVOID, +}} +pub type PSecPkgContext_MappedCredAttr = *mut SecPkgContext_MappedCredAttr; +pub const SSL_SESSION_RECONNECT: ::DWORD = 1; +STRUCT!{struct SecPkgContext_SessionInfo { + dwFlags: ::DWORD, + cbSessionId: ::DWORD, + rgbSessionId: [::BYTE; 32], +}} +pub type PSecPkgContext_SessionInfo = *mut SecPkgContext_SessionInfo; +STRUCT!{struct SecPkgContext_SessionAppData { + dwFlags: ::DWORD, + cbAppData: ::DWORD, + pbAppData: ::PBYTE, +}} +pub type PSecPkgContext_SessionAppData = *mut SecPkgContext_SessionAppData; +STRUCT!{struct SecPkgContext_EapPrfInfo { + dwVersion: ::DWORD, + cbPrfData: ::DWORD, + pbPrfData: ::PBYTE, +}} +pub type PSecPkgContext_EapPrfInfo = *mut SecPkgContext_EapPrfInfo; +STRUCT!{struct SecPkgContext_SupportedSignatures { + cSignatureAndHashAlgorithms: ::WORD, + pSignatureAndHashAlgorithms: *mut ::WORD, +}} +pub type PSecPkgContext_SupportedSignatures = *mut SecPkgContext_SupportedSignatures; +STRUCT!{struct SecPkgContext_Certificates { + cCertificates: ::DWORD, + cbCertificateChain: ::DWORD, + pbCertificateChain: ::PBYTE, +}} +pub type PSecPkgContext_Certificates = *mut SecPkgContext_Certificates; +STRUCT!{struct SecPkgContext_CertInfo { + dwVersion: ::DWORD, + cbSubjectName: ::DWORD, + pwszSubjectName: ::LPWSTR, + cbIssuerName: ::DWORD, + pwszIssuerName: ::LPWSTR, + dwKeySize: ::DWORD, +}} +pub type PSecPkgContext_CertInfo = *mut SecPkgContext_CertInfo; +pub const KERN_CONTEXT_CERT_INFO_V1: ::DWORD = 0x00000000; +STRUCT!{struct SecPkgContext_UiInfo { + hParentWindow: ::HWND, +}} +pub type PSecPkgContext_UiInfo = *mut SecPkgContext_UiInfo; +STRUCT!{struct SecPkgContext_EarlyStart { + dwEarlyStartFlags: ::DWORD, +}} +pub type PSecPkgContext_EarlyStart = *mut SecPkgContext_EarlyStart; +pub const ENABLE_TLS_CLIENT_EARLY_START: ::DWORD = 0x00000001; +pub const SCH_CRED_V1: ::DWORD = 0x00000001; +pub const SCH_CRED_V2: ::DWORD = 0x00000002; +pub const SCH_CRED_VERSION: ::DWORD = 0x00000002; +pub const SCH_CRED_V3: ::DWORD = 0x00000003; +pub const SCHANNEL_CRED_VERSION: ::DWORD = 0x00000004; +pub enum _HMAPPER {} +STRUCT!{struct SCHANNEL_CRED { + dwVersion: ::DWORD, + cCreds: ::DWORD, + paCred: *mut ::PCCERT_CONTEXT, + hRootStore: ::HCERTSTORE, + cMappers: ::DWORD, + aphMappers: *mut *mut _HMAPPER, + cSupportedAlgs: ::DWORD, + palgSupportedAlgs: *mut ::ALG_ID, + grbitEnabledProtocols: ::DWORD, + dwMinimumCipherStrength: ::DWORD, + dwMaximumCipherStrength: ::DWORD, + dwSessionLifespan: ::DWORD, + dwFlags: ::DWORD, + dwCredFormat: ::DWORD, +}} +pub type PSCHANNEL_CRED = *mut SCHANNEL_CRED; +pub const SCH_CRED_FORMAT_CERT_CONTEXT: ::DWORD = 0x00000000; +pub const SCH_CRED_FORMAT_CERT_HASH: ::DWORD = 0x00000001; +pub const SCH_CRED_FORMAT_CERT_HASH_STORE: ::DWORD = 0x00000002; +pub const SCH_CRED_MAX_STORE_NAME_SIZE: usize = 128; +pub const SCH_CRED_MAX_SUPPORTED_ALGS: ::DWORD = 256; +pub const SCH_CRED_MAX_SUPPORTED_CERTS: ::DWORD = 100; +STRUCT!{struct SCHANNEL_CERT_HASH { + dwLength: ::DWORD, + dwFlags: ::DWORD, + hProv: ::HCRYPTPROV, + ShaHash: [::BYTE; 20], +}} +pub type PSCHANNEL_CERT_HASH = *mut SCHANNEL_CERT_HASH; +STRUCT!{nodebug struct SCHANNEL_CERT_HASH_STORE { + dwLength: ::DWORD, + dwFlags: ::DWORD, + hProv: ::HCRYPTPROV, + ShaHash: [::BYTE; 20], + pwszStoreName: [::WCHAR; SCH_CRED_MAX_STORE_NAME_SIZE], +}} +pub type PSCHANNEL_CERT_HASH_STORE = *mut SCHANNEL_CERT_HASH_STORE; +pub const SCH_MACHINE_CERT_HASH: ::DWORD = 0x00000001; +pub const SCH_CRED_NO_SYSTEM_MAPPER: ::DWORD = 0x00000002; +pub const SCH_CRED_NO_SERVERNAME_CHECK: ::DWORD = 0x00000004; +pub const SCH_CRED_MANUAL_CRED_VALIDATION: ::DWORD = 0x00000008; +pub const SCH_CRED_NO_DEFAULT_CREDS: ::DWORD = 0x00000010; +pub const SCH_CRED_AUTO_CRED_VALIDATION: ::DWORD = 0x00000020; +pub const SCH_CRED_USE_DEFAULT_CREDS: ::DWORD = 0x00000040; +pub const SCH_CRED_DISABLE_RECONNECTS: ::DWORD = 0x00000080; +pub const SCH_CRED_REVOCATION_CHECK_END_CERT: ::DWORD = 0x00000100; +pub const SCH_CRED_REVOCATION_CHECK_CHAIN: ::DWORD = 0x00000200; +pub const SCH_CRED_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: ::DWORD = 0x00000400; +pub const SCH_CRED_IGNORE_NO_REVOCATION_CHECK: ::DWORD = 0x00000800; +pub const SCH_CRED_IGNORE_REVOCATION_OFFLINE: ::DWORD = 0x00001000; +pub const SCH_CRED_RESTRICTED_ROOTS: ::DWORD = 0x00002000; +pub const SCH_CRED_REVOCATION_CHECK_CACHE_ONLY: ::DWORD = 0x00004000; +pub const SCH_CRED_CACHE_ONLY_URL_RETRIEVAL: ::DWORD = 0x00008000; +pub const SCH_CRED_MEMORY_STORE_CERT: ::DWORD = 0x00010000; +pub const SCH_CRED_CACHE_ONLY_URL_RETRIEVAL_ON_CREATE: ::DWORD = 0x00020000; +pub const SCH_SEND_ROOT_CERT: ::DWORD = 0x00040000; +pub const SCH_CRED_SNI_CREDENTIAL: ::DWORD = 0x00080000; +pub const SCH_CRED_SNI_ENABLE_OCSP: ::DWORD = 0x00100000; +pub const SCH_SEND_AUX_RECORD: ::DWORD = 0x00200000; +pub const SCH_USE_STRONG_CRYPTO: ::DWORD = 0x00400000; +pub const SCHANNEL_RENEGOTIATE: ::DWORD = 0; +pub const SCHANNEL_SHUTDOWN: ::DWORD = 1; +pub const SCHANNEL_ALERT: ::DWORD = 2; +pub const SCHANNEL_SESSION: ::DWORD = 3; +STRUCT!{struct SCHANNEL_ALERT_TOKEN { + dwTokenType: ::DWORD, + dwAlertType: ::DWORD, + dwAlertNumber: ::DWORD, +}} +pub const TLS1_ALERT_WARNING: ::DWORD = 1; +pub const TLS1_ALERT_FATAL: ::DWORD = 2; +pub const TLS1_ALERT_CLOSE_NOTIFY: ::DWORD = 0; +pub const TLS1_ALERT_UNEXPECTED_MESSAGE: ::DWORD = 10; +pub const TLS1_ALERT_BAD_RECORD_MAC: ::DWORD = 20; +pub const TLS1_ALERT_DECRYPTION_FAILED: ::DWORD = 21; +pub const TLS1_ALERT_RECORD_OVERFLOW: ::DWORD = 22; +pub const TLS1_ALERT_DECOMPRESSION_FAIL: ::DWORD = 30; +pub const TLS1_ALERT_HANDSHAKE_FAILURE: ::DWORD = 40; +pub const TLS1_ALERT_BAD_CERTIFICATE: ::DWORD = 42; +pub const TLS1_ALERT_UNSUPPORTED_CERT: ::DWORD = 43; +pub const TLS1_ALERT_CERTIFICATE_REVOKED: ::DWORD = 44; +pub const TLS1_ALERT_CERTIFICATE_EXPIRED: ::DWORD = 45; +pub const TLS1_ALERT_CERTIFICATE_UNKNOWN: ::DWORD = 46; +pub const TLS1_ALERT_ILLEGAL_PARAMETER: ::DWORD = 47; +pub const TLS1_ALERT_UNKNOWN_CA: ::DWORD = 48; +pub const TLS1_ALERT_ACCESS_DENIED: ::DWORD = 49; +pub const TLS1_ALERT_DECODE_ERROR: ::DWORD = 50; +pub const TLS1_ALERT_DECRYPT_ERROR: ::DWORD = 51; +pub const TLS1_ALERT_EXPORT_RESTRICTION: ::DWORD = 60; +pub const TLS1_ALERT_PROTOCOL_VERSION: ::DWORD = 70; +pub const TLS1_ALERT_INSUFFIENT_SECURITY: ::DWORD = 71; +pub const TLS1_ALERT_INTERNAL_ERROR: ::DWORD = 80; +pub const TLS1_ALERT_USER_CANCELED: ::DWORD = 90; +pub const TLS1_ALERT_NO_RENEGOTIATION: ::DWORD = 100; +pub const TLS1_ALERT_UNSUPPORTED_EXT: ::DWORD = 110; +pub const TLS1_ALERT_NO_APP_PROTOCOL: ::DWORD = 120; +pub const SSL_SESSION_ENABLE_RECONNECTS: ::DWORD = 1; +pub const SSL_SESSION_DISABLE_RECONNECTS: ::DWORD = 2; +STRUCT!{struct SCHANNEL_SESSION_TOKEN { + dwTokenType: ::DWORD, + dwFlags: ::DWORD, +}} +STRUCT!{nodebug struct SCHANNEL_CLIENT_SIGNATURE { + cbLength: ::DWORD, + aiHash: ::ALG_ID, + cbHash: ::DWORD, + HashValue: [::BYTE; 36], + CertThumbprint: [::BYTE; 20], +}} +pub type PSCHANNEL_CLIENT_SIGNATURE = *mut SCHANNEL_CLIENT_SIGNATURE; +pub const SP_PROT_PCT1_SERVER: ::DWORD = 0x00000001; +pub const SP_PROT_PCT1_CLIENT: ::DWORD = 0x00000002; +pub const SP_PROT_PCT1: ::DWORD = SP_PROT_PCT1_SERVER | SP_PROT_PCT1_CLIENT; +pub const SP_PROT_SSL2_SERVER: ::DWORD = 0x00000004; +pub const SP_PROT_SSL2_CLIENT: ::DWORD = 0x00000008; +pub const SP_PROT_SSL2: ::DWORD = SP_PROT_SSL2_SERVER | SP_PROT_SSL2_CLIENT; +pub const SP_PROT_SSL3_SERVER: ::DWORD = 0x00000010; +pub const SP_PROT_SSL3_CLIENT: ::DWORD = 0x00000020; +pub const SP_PROT_SSL3: ::DWORD = SP_PROT_SSL3_SERVER | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_TLS1_SERVER: ::DWORD = 0x00000040; +pub const SP_PROT_TLS1_CLIENT: ::DWORD = 0x00000080; +pub const SP_PROT_TLS1: ::DWORD = SP_PROT_TLS1_SERVER | SP_PROT_TLS1_CLIENT; +pub const SP_PROT_SSL3TLS1_CLIENTS: ::DWORD = SP_PROT_TLS1_CLIENT | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_SSL3TLS1_SERVERS: ::DWORD = SP_PROT_TLS1_SERVER | SP_PROT_SSL3_SERVER; +pub const SP_PROT_SSL3TLS1: ::DWORD = SP_PROT_SSL3 | SP_PROT_TLS1; +pub const SP_PROT_UNI_SERVER: ::DWORD = 0x40000000; +pub const SP_PROT_UNI_CLIENT: ::DWORD = 0x80000000; +pub const SP_PROT_UNI: ::DWORD = SP_PROT_UNI_SERVER | SP_PROT_UNI_CLIENT; +pub const SP_PROT_ALL: ::DWORD = 0xffffffff; +pub const SP_PROT_NONE: ::DWORD = 0; +pub const SP_PROT_CLIENTS: ::DWORD = SP_PROT_PCT1_CLIENT | SP_PROT_SSL2_CLIENT + | SP_PROT_SSL3_CLIENT | SP_PROT_UNI_CLIENT | SP_PROT_TLS1_CLIENT; +pub const SP_PROT_SERVERS: ::DWORD = SP_PROT_PCT1_SERVER | SP_PROT_SSL2_SERVER + | SP_PROT_SSL3_SERVER | SP_PROT_UNI_SERVER | SP_PROT_TLS1_SERVER; +pub const SP_PROT_TLS1_0_SERVER: ::DWORD = SP_PROT_TLS1_SERVER; +pub const SP_PROT_TLS1_0_CLIENT: ::DWORD = SP_PROT_TLS1_CLIENT; +pub const SP_PROT_TLS1_0: ::DWORD = SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_0_CLIENT; +pub const SP_PROT_TLS1_1_SERVER: ::DWORD = 0x00000100; +pub const SP_PROT_TLS1_1_CLIENT: ::DWORD = 0x00000200; +pub const SP_PROT_TLS1_1: ::DWORD = SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_1_CLIENT; +pub const SP_PROT_TLS1_2_SERVER: ::DWORD = 0x00000400; +pub const SP_PROT_TLS1_2_CLIENT: ::DWORD = 0x00000800; +pub const SP_PROT_TLS1_2: ::DWORD = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_DTLS_SERVER: ::DWORD = 0x00010000; +pub const SP_PROT_DTLS_CLIENT: ::DWORD = 0x00020000; +pub const SP_PROT_DTLS: ::DWORD = SP_PROT_DTLS_SERVER | SP_PROT_DTLS_CLIENT; +pub const SP_PROT_DTLS1_0_SERVER: ::DWORD = SP_PROT_DTLS_SERVER; +pub const SP_PROT_DTLS1_0_CLIENT: ::DWORD = SP_PROT_DTLS_CLIENT; +pub const SP_PROT_DTLS1_0: ::DWORD = SP_PROT_DTLS1_0_SERVER | SP_PROT_DTLS1_0_CLIENT; +pub const SP_PROT_DTLS1_X_SERVER: ::DWORD = SP_PROT_DTLS1_0_SERVER; +pub const SP_PROT_DTLS1_X_CLIENT: ::DWORD = SP_PROT_DTLS1_0_CLIENT; +pub const SP_PROT_DTLS1_X: ::DWORD = SP_PROT_DTLS1_X_SERVER | SP_PROT_DTLS1_X_CLIENT; +pub const SP_PROT_TLS1_1PLUS_SERVER: ::DWORD = SP_PROT_TLS1_1_SERVER | SP_PROT_TLS1_2_SERVER; +pub const SP_PROT_TLS1_1PLUS_CLIENT: ::DWORD = SP_PROT_TLS1_1_CLIENT | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_TLS1_1PLUS: ::DWORD = SP_PROT_TLS1_1PLUS_SERVER | SP_PROT_TLS1_1PLUS_CLIENT; +pub const SP_PROT_TLS1_X_SERVER: ::DWORD = SP_PROT_TLS1_0_SERVER | SP_PROT_TLS1_1_SERVER + | SP_PROT_TLS1_2_SERVER; +pub const SP_PROT_TLS1_X_CLIENT: ::DWORD = SP_PROT_TLS1_0_CLIENT | SP_PROT_TLS1_1_CLIENT + | SP_PROT_TLS1_2_CLIENT; +pub const SP_PROT_TLS1_X: ::DWORD = SP_PROT_TLS1_X_SERVER | SP_PROT_TLS1_X_CLIENT; +pub const SP_PROT_SSL3TLS1_X_CLIENTS: ::DWORD = SP_PROT_TLS1_X_CLIENT | SP_PROT_SSL3_CLIENT; +pub const SP_PROT_SSL3TLS1_X_SERVERS: ::DWORD = SP_PROT_TLS1_X_SERVER | SP_PROT_SSL3_SERVER; +pub const SP_PROT_SSL3TLS1_X: ::DWORD = SP_PROT_SSL3 | SP_PROT_TLS1_X; +pub const SP_PROT_X_CLIENTS: ::DWORD = SP_PROT_CLIENTS | SP_PROT_TLS1_X_CLIENT + | SP_PROT_DTLS1_X_CLIENT; +pub const SP_PROT_X_SERVERS: ::DWORD = SP_PROT_SERVERS | SP_PROT_TLS1_X_SERVER + | SP_PROT_DTLS1_X_SERVER; +//716 +pub const SCHANNEL_SECRET_TYPE_CAPI: ::DWORD = 0x00000001; +pub const SCHANNEL_SECRET_PRIVKEY: ::DWORD = 0x00000002; +pub const SCH_CRED_X509_CERTCHAIN: ::DWORD = 0x00000001; +pub const SCH_CRED_X509_CAPI: ::DWORD = 0x00000002; +pub const SCH_CRED_CERT_CONTEXT: ::DWORD = 0x00000003; +//838 +pub const SSL_CRACK_CERTIFICATE_NAME: &'static str = "SslCrackCertificate"; +pub const SSL_FREE_CERTIFICATE_NAME: &'static str = "SslFreeCertificate"; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/servprov.rs b/third_party/cargo/vendor/winapi-0.2.8/src/servprov.rs new file mode 100644 index 0000000..8b37ba8 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/servprov.rs @@ -0,0 +1,11 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of servprov.h +pub type LPSERVICEPROVIDER = *mut IServiceProvider; +RIDL!( +interface IServiceProvider(IServiceProviderVtbl): IUnknown(IUnknownVtbl) { + fn QueryService( + &mut self, guidService: ::REFGUID, riid: ::REFIID, ppvObject: *mut *mut ::c_void + ) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/setupapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/setupapi.rs new file mode 100644 index 0000000..cf3149d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/setupapi.rs @@ -0,0 +1,1301 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Windows NT Setup and Device Installer services +pub const LINE_LEN: usize = 256; +pub const MAX_INF_STRING_LENGTH: usize = 4096; +pub const MAX_INF_SECTION_NAME_LENGTH: usize = 255; +pub const MAX_TITLE_LEN: usize = 60; +pub const MAX_INSTRUCTION_LEN: usize = 256; +pub const MAX_LABEL_LEN: usize = 30; +pub const MAX_SERVICE_NAME_LEN: usize = 256; +pub const MAX_SUBTITLE_LEN: usize = 256; +pub const SP_MAX_MACHINENAME_LENGTH: usize = ::MAX_PATH + 3; +pub type HINF = ::PVOID; +STRUCT!{struct INFCONTEXT { + Inf: ::PVOID, + CurrentInf: ::PVOID, + Section: ::UINT, + Line: ::UINT, +}} +pub type PINFCONTEXT = *mut INFCONTEXT; +STRUCT!{struct SP_INF_INFORMATION { + InfStyle: ::DWORD, + InfCount: ::DWORD, + VersionData: [::BYTE; ::ANYSIZE_ARRAY], +}} +pub type PSP_INF_INFORMATION = *mut SP_INF_INFORMATION; +STRUCT!{struct SP_ALTPLATFORM_INFO_V2 { + cbSize: ::DWORD, + Platform: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + ProcessorArchitecture: ::WORD, + Reserved: ::WORD, + FirstValidatedMajorVersion: ::DWORD, + FirstValidatedMinorVersion: ::DWORD, +}} +UNION!(SP_ALTPLATFORM_INFO_V2, Reserved, Flags, Flags_mut, ::WORD); +pub type PSP_ALTPLATFORM_INFO_V2 = *mut SP_ALTPLATFORM_INFO_V2; +STRUCT!{struct SP_ALTPLATFORM_INFO_V1 { + cbSize: ::DWORD, + Platform: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + ProcessorArchitecture: ::WORD, + Reserved: ::WORD, +}} +pub type PSP_ALTPLATFORM_INFO_V1 = *mut SP_ALTPLATFORM_INFO_V1; +pub type SP_ALTPLATFORM_INFO = SP_ALTPLATFORM_INFO_V2; +pub type PSP_ALTPLATFORM_INFO = PSP_ALTPLATFORM_INFO_V2; +pub const SP_ALTPLATFORM_FLAGS_VERSION_RANGE: ::WORD = 0x0001; +STRUCT!{nodebug struct SP_ORIGINAL_FILE_INFO_A { + cbSize: ::DWORD, + OriginalInfName: [::CHAR; ::MAX_PATH], + OriginalCatalogName: [::CHAR; ::MAX_PATH], +}} +pub type PSP_ORIGINAL_FILE_INFO_A = *mut SP_ORIGINAL_FILE_INFO_A; +STRUCT!{nodebug struct SP_ORIGINAL_FILE_INFO_W { + cbSize: ::DWORD, + OriginalInfName: [::WCHAR; ::MAX_PATH], + OriginalCatalogName: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_ORIGINAL_FILE_INFO_W = *mut SP_ORIGINAL_FILE_INFO_W; +pub const INF_STYLE_NONE: ::DWORD = 0x00000000; +pub const INF_STYLE_OLDNT: ::DWORD = 0x00000001; +pub const INF_STYLE_WIN4: ::DWORD = 0x00000002; +pub const INF_STYLE_CACHE_ENABLE: ::DWORD = 0x00000010; +pub const INF_STYLE_CACHE_DISABLE: ::DWORD = 0x00000020; +pub const INF_STYLE_CACHE_IGNORE: ::DWORD = 0x00000040; +pub const DIRID_ABSOLUTE: ::DWORD = -1i32 as ::DWORD; +pub const DIRID_ABSOLUTE_16BIT: ::DWORD = 0xffff; +pub const DIRID_NULL: ::DWORD = 0; +pub const DIRID_SRCPATH: ::DWORD = 1; +pub const DIRID_WINDOWS: ::DWORD = 10; +pub const DIRID_SYSTEM: ::DWORD = 11; +pub const DIRID_DRIVERS: ::DWORD = 12; +pub const DIRID_IOSUBSYS: ::DWORD = DIRID_DRIVERS; +pub const DIRID_DRIVER_STORE: ::DWORD = 13; +pub const DIRID_INF: ::DWORD = 17; +pub const DIRID_HELP: ::DWORD = 18; +pub const DIRID_FONTS: ::DWORD = 20; +pub const DIRID_VIEWERS: ::DWORD = 21; +pub const DIRID_COLOR: ::DWORD = 23; +pub const DIRID_APPS: ::DWORD = 24; +pub const DIRID_SHARED: ::DWORD = 25; +pub const DIRID_BOOT: ::DWORD = 30; +pub const DIRID_SYSTEM16: ::DWORD = 50; +pub const DIRID_SPOOL: ::DWORD = 51; +pub const DIRID_SPOOLDRIVERS: ::DWORD = 52; +pub const DIRID_USERPROFILE: ::DWORD = 53; +pub const DIRID_LOADER: ::DWORD = 54; +pub const DIRID_PRINTPROCESSOR: ::DWORD = 55; +pub const DIRID_DEFAULT: ::DWORD = DIRID_SYSTEM; +pub const DIRID_COMMON_STARTMENU: ::DWORD = 16406; +pub const DIRID_COMMON_PROGRAMS: ::DWORD = 16407; +pub const DIRID_COMMON_STARTUP: ::DWORD = 16408; +pub const DIRID_COMMON_DESKTOPDIRECTORY: ::DWORD = 16409; +pub const DIRID_COMMON_FAVORITES: ::DWORD = 16415; +pub const DIRID_COMMON_APPDATA: ::DWORD = 16419; +pub const DIRID_PROGRAM_FILES: ::DWORD = 16422; +pub const DIRID_SYSTEM_X86: ::DWORD = 16425; +pub const DIRID_PROGRAM_FILES_X86: ::DWORD = 16426; +pub const DIRID_PROGRAM_FILES_COMMON: ::DWORD = 16427; +pub const DIRID_PROGRAM_FILES_COMMONX86: ::DWORD = 16428; +pub const DIRID_COMMON_TEMPLATES: ::DWORD = 16429; +pub const DIRID_COMMON_DOCUMENTS: ::DWORD = 16430; +pub const DIRID_USER: ::DWORD = 0x8000; +pub type PSP_FILE_CALLBACK_A = Option ::UINT>; +pub type PSP_FILE_CALLBACK_W = Option ::UINT>; +pub const SPFILENOTIFY_STARTQUEUE: ::UINT = 0x00000001; +pub const SPFILENOTIFY_ENDQUEUE: ::UINT = 0x00000002; +pub const SPFILENOTIFY_STARTSUBQUEUE: ::UINT = 0x00000003; +pub const SPFILENOTIFY_ENDSUBQUEUE: ::UINT = 0x00000004; +pub const SPFILENOTIFY_STARTDELETE: ::UINT = 0x00000005; +pub const SPFILENOTIFY_ENDDELETE: ::UINT = 0x00000006; +pub const SPFILENOTIFY_DELETEERROR: ::UINT = 0x00000007; +pub const SPFILENOTIFY_STARTRENAME: ::UINT = 0x00000008; +pub const SPFILENOTIFY_ENDRENAME: ::UINT = 0x00000009; +pub const SPFILENOTIFY_RENAMEERROR: ::UINT = 0x0000000a; +pub const SPFILENOTIFY_STARTCOPY: ::UINT = 0x0000000b; +pub const SPFILENOTIFY_ENDCOPY: ::UINT = 0x0000000c; +pub const SPFILENOTIFY_COPYERROR: ::UINT = 0x0000000d; +pub const SPFILENOTIFY_NEEDMEDIA: ::UINT = 0x0000000e; +pub const SPFILENOTIFY_QUEUESCAN: ::UINT = 0x0000000f; +pub const SPFILENOTIFY_CABINETINFO: ::UINT = 0x00000010; +pub const SPFILENOTIFY_FILEINCABINET: ::UINT = 0x00000011; +pub const SPFILENOTIFY_NEEDNEWCABINET: ::UINT = 0x00000012; +pub const SPFILENOTIFY_FILEEXTRACTED: ::UINT = 0x00000013; +pub const SPFILENOTIFY_FILEOPDELAYED: ::UINT = 0x00000014; +pub const SPFILENOTIFY_STARTBACKUP: ::UINT = 0x00000015; +pub const SPFILENOTIFY_BACKUPERROR: ::UINT = 0x00000016; +pub const SPFILENOTIFY_ENDBACKUP: ::UINT = 0x00000017; +pub const SPFILENOTIFY_QUEUESCAN_EX: ::UINT = 0x00000018; +pub const SPFILENOTIFY_STARTREGISTRATION: ::UINT = 0x00000019; +pub const SPFILENOTIFY_ENDREGISTRATION: ::UINT = 0x00000020; +pub const SPFILENOTIFY_QUEUESCAN_SIGNERINFO: ::UINT = 0x00000040; +pub const SPFILENOTIFY_LANGMISMATCH: ::UINT = 0x00010000; +pub const SPFILENOTIFY_TARGETEXISTS: ::UINT = 0x00020000; +pub const SPFILENOTIFY_TARGETNEWER: ::UINT = 0x00040000; +pub const FILEOP_COPY: ::UINT = 0; +pub const FILEOP_RENAME: ::UINT = 1; +pub const FILEOP_DELETE: ::UINT = 2; +pub const FILEOP_BACKUP: ::UINT = 3; +pub const FILEOP_ABORT: ::UINT = 0; +pub const FILEOP_DOIT: ::UINT = 1; +pub const FILEOP_SKIP: ::UINT = 2; +pub const FILEOP_RETRY: ::UINT = FILEOP_DOIT; +pub const FILEOP_NEWPATH: ::UINT = 4; +pub const COPYFLG_WARN_IF_SKIP: ::UINT = 0x00000001; +pub const COPYFLG_NOSKIP: ::UINT = 0x00000002; +pub const COPYFLG_NOVERSIONCHECK: ::UINT = 0x00000004; +pub const COPYFLG_FORCE_FILE_IN_USE: ::UINT = 0x00000008; +pub const COPYFLG_NO_OVERWRITE: ::UINT = 0x00000010; +pub const COPYFLG_NO_VERSION_DIALOG: ::UINT = 0x00000020; +pub const COPYFLG_OVERWRITE_OLDER_ONLY: ::UINT = 0x00000040; +pub const COPYFLG_PROTECTED_WINDOWS_DRIVER_FILE: ::UINT = 0x00000100; +pub const COPYFLG_REPLACEONLY: ::UINT = 0x00000400; +pub const COPYFLG_NODECOMP: ::UINT = 0x00000800; +pub const COPYFLG_REPLACE_BOOT_FILE: ::UINT = 0x00001000; +pub const COPYFLG_NOPRUNE: ::UINT = 0x00002000; +pub const COPYFLG_IN_USE_TRY_RENAME: ::UINT = 0x00004000; +pub const DELFLG_IN_USE: ::UINT = 0x00000001; +pub const DELFLG_IN_USE1: ::UINT = 0x00010000; +STRUCT!{struct FILEPATHS_A { + Target: ::PCSTR, + Source: ::PCSTR, + Win32Error: ::UINT, + Flags: ::DWORD, +}} +pub type PFILEPATHS_A = *mut FILEPATHS_A; +STRUCT!{struct FILEPATHS_W { + Target: ::PCWSTR, + Source: ::PCWSTR, + Win32Error: ::UINT, + Flags: ::DWORD, +}} +pub type PFILEPATHS_W = *mut FILEPATHS_W; +STRUCT!{struct FILEPATHS_SIGNERINFO_A { + Target: ::PCSTR, + Source: ::PCSTR, + Win32Error: ::UINT, + Flags: ::DWORD, + DigitalSigner: ::PCSTR, + Version: ::PCSTR, + CatalogFile: ::PCSTR, +}} +pub type PFILEPATHS_SIGNERINFO_A = *mut FILEPATHS_SIGNERINFO_A; +STRUCT!{struct FILEPATHS_SIGNERINFO_W { + Target: ::PCWSTR, + Source: ::PCWSTR, + Win32Error: ::UINT, + Flags: ::DWORD, + DigitalSigner: ::PCWSTR, + Version: ::PCWSTR, + CatalogFile: ::PCWSTR, +}} +pub type PFILEPATHS_SIGNERINFO_W = *mut FILEPATHS_SIGNERINFO_W; +STRUCT!{struct SOURCE_MEDIA_A { + Reserved: ::PCSTR, + Tagfile: ::PCSTR, + Description: ::PCSTR, + SourcePath: ::PCSTR, + SourceFile: ::PCSTR, + Flags: ::DWORD, +}} +pub type PSOURCE_MEDIA_A = *mut SOURCE_MEDIA_A; +STRUCT!{struct SOURCE_MEDIA_W { + Reserved: ::PCWSTR, + Tagfile: ::PCWSTR, + Description: ::PCWSTR, + SourcePath: ::PCWSTR, + SourceFile: ::PCWSTR, + Flags: ::DWORD, +}} +pub type PSOURCE_MEDIA_W = *mut SOURCE_MEDIA_W; +STRUCT!{struct CABINET_INFO_A { + CabinetPath: ::PCSTR, + CabinetFile: ::PCSTR, + DiskName: ::PCSTR, + SetId: ::USHORT, + CabinetNumber: ::USHORT, +}} +pub type PCABINET_INFO_A = *mut CABINET_INFO_A; +STRUCT!{struct CABINET_INFO_W { + CabinetPath: ::PCWSTR, + CabinetFile: ::PCWSTR, + DiskName: ::PCWSTR, + SetId: ::USHORT, + CabinetNumber: ::USHORT, +}} +pub type PCABINET_INFO_W = *mut CABINET_INFO_W; +STRUCT!{nodebug struct FILE_IN_CABINET_INFO_A { + NameInCabinet: ::PCSTR, + FileSize: ::DWORD, + Win32Error: ::DWORD, + DosDate: ::WORD, + DosTime: ::WORD, + DosAttribs: ::WORD, + FullTargetName: [::CHAR; ::MAX_PATH], +}} +pub type PFILE_IN_CABINET_INFO_A = *mut FILE_IN_CABINET_INFO_A; +STRUCT!{nodebug struct FILE_IN_CABINET_INFO_W { + NameInCabinet: ::PCWSTR, + FileSize: ::DWORD, + Win32Error: ::DWORD, + DosDate: ::WORD, + DosTime: ::WORD, + DosAttribs: ::WORD, + FullTargetName: [::WCHAR; ::MAX_PATH], +}} +pub type PFILE_IN_CABINET_INFO_W = *mut FILE_IN_CABINET_INFO_W; +STRUCT!{struct SP_REGISTER_CONTROL_STATUSA { + cbSize: ::DWORD, + FileName: ::PCSTR, + Win32Error: ::DWORD, + FailureCode: ::DWORD, +}} +pub type PSP_REGISTER_CONTROL_STATUSA = *mut SP_REGISTER_CONTROL_STATUSA; +STRUCT!{struct SP_REGISTER_CONTROL_STATUSW { + cbSize: ::DWORD, + FileName: ::PCWSTR, + Win32Error: ::DWORD, + FailureCode: ::DWORD, +}} +pub type PSP_REGISTER_CONTROL_STATUSW = *mut SP_REGISTER_CONTROL_STATUSW; +pub const SPREG_SUCCESS: ::DWORD = 0x00000000; +pub const SPREG_LOADLIBRARY: ::DWORD = 0x00000001; +pub const SPREG_GETPROCADDR: ::DWORD = 0x00000002; +pub const SPREG_REGSVR: ::DWORD = 0x00000003; +pub const SPREG_DLLINSTALL: ::DWORD = 0x00000004; +pub const SPREG_TIMEOUT: ::DWORD = 0x00000005; +pub const SPREG_UNKNOWN: ::DWORD = 0xFFFFFFFF; +pub type HSPFILEQ = ::PVOID; +STRUCT!{struct SP_FILE_COPY_PARAMS_A { + cbSize: ::DWORD, + QueueHandle: HSPFILEQ, + SourceRootPath: ::PCSTR, + SourcePath: ::PCSTR, + SourceFilename: ::PCSTR, + SourceDescription: ::PCSTR, + SourceTagfile: ::PCSTR, + TargetDirectory: ::PCSTR, + TargetFilename: ::PCSTR, + CopyStyle: ::DWORD, + LayoutInf: HINF, + SecurityDescriptor: ::PCSTR, +}} +pub type PSP_FILE_COPY_PARAMS_A = *mut SP_FILE_COPY_PARAMS_A; +STRUCT!{struct SP_FILE_COPY_PARAMS_W { + cbSize: ::DWORD, + QueueHandle: HSPFILEQ, + SourceRootPath: ::PCWSTR, + SourcePath: ::PCWSTR, + SourceFilename: ::PCWSTR, + SourceDescription: ::PCWSTR, + SourceTagfile: ::PCWSTR, + TargetDirectory: ::PCWSTR, + TargetFilename: ::PCWSTR, + CopyStyle: ::DWORD, + LayoutInf: HINF, + SecurityDescriptor: ::PCWSTR, +}} +pub type PSP_FILE_COPY_PARAMS_W = *mut SP_FILE_COPY_PARAMS_W; +pub type HDSKSPC = ::PVOID; +pub type HDEVINFO = ::PVOID; +STRUCT!{struct SP_DEVINFO_DATA { + cbSize: ::DWORD, + ClassGuid: ::GUID, + DevInst: ::DWORD, + Reserved: ::ULONG_PTR, +}} +pub type PSP_DEVINFO_DATA = *mut SP_DEVINFO_DATA; +STRUCT!{struct SP_DEVICE_INTERFACE_DATA { + cbSize: ::DWORD, + InterfaceClassGuid: ::GUID, + Flags: ::DWORD, + Reserved: ::ULONG_PTR, +}} +pub type PSP_DEVICE_INTERFACE_DATA = *mut SP_DEVICE_INTERFACE_DATA; +pub const SPINT_ACTIVE: ::DWORD = 0x00000001; +pub const SPINT_DEFAULT: ::DWORD = 0x00000002; +pub const SPINT_REMOVED: ::DWORD = 0x00000004; +pub type SP_INTERFACE_DEVICE_DATA = SP_DEVICE_INTERFACE_DATA; +pub type PSP_INTERFACE_DEVICE_DATA = PSP_DEVICE_INTERFACE_DATA; +pub const SPID_ACTIVE: ::DWORD = SPINT_ACTIVE; +pub const SPID_DEFAULT: ::DWORD = SPINT_DEFAULT; +pub const SPID_REMOVED: ::DWORD = SPINT_REMOVED; +STRUCT!{struct SP_DEVICE_INTERFACE_DETAIL_DATA_A { + cbSize: ::DWORD, + DevicePath: [::CHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DEVICE_INTERFACE_DETAIL_DATA_A = *mut SP_DEVICE_INTERFACE_DETAIL_DATA_A; +STRUCT!{struct SP_DEVICE_INTERFACE_DETAIL_DATA_W { + cbSize: ::DWORD, + DevicePath: [::WCHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DEVICE_INTERFACE_DETAIL_DATA_W = *mut SP_DEVICE_INTERFACE_DETAIL_DATA_W; +STRUCT!{nodebug struct SP_DEVINFO_LIST_DETAIL_DATA_A { + cbSize: ::DWORD, + ClassGuid: ::GUID, + RemoteMachineHandle: ::HANDLE, + RemoteMachineName: [::CHAR; SP_MAX_MACHINENAME_LENGTH], +}} +pub type PSP_DEVINFO_LIST_DETAIL_DATA_A = *mut SP_DEVINFO_LIST_DETAIL_DATA_A; +STRUCT!{nodebug struct SP_DEVINFO_LIST_DETAIL_DATA_W { + cbSize: ::DWORD, + ClassGuid: ::GUID, + RemoteMachineHandle: ::HANDLE, + RemoteMachineName: [::WCHAR; SP_MAX_MACHINENAME_LENGTH], +}} +pub type PSP_DEVINFO_LIST_DETAIL_DATA_W = *mut SP_DEVINFO_LIST_DETAIL_DATA_W; +pub const DIF_SELECTDEVICE: DI_FUNCTION = 0x00000001; +pub const DIF_INSTALLDEVICE: DI_FUNCTION = 0x00000002; +pub const DIF_ASSIGNRESOURCES: DI_FUNCTION = 0x00000003; +pub const DIF_PROPERTIES: DI_FUNCTION = 0x00000004; +pub const DIF_REMOVE: DI_FUNCTION = 0x00000005; +pub const DIF_FIRSTTIMESETUP: DI_FUNCTION = 0x00000006; +pub const DIF_FOUNDDEVICE: DI_FUNCTION = 0x00000007; +pub const DIF_SELECTCLASSDRIVERS: DI_FUNCTION = 0x00000008; +pub const DIF_VALIDATECLASSDRIVERS: DI_FUNCTION = 0x00000009; +pub const DIF_INSTALLCLASSDRIVERS: DI_FUNCTION = 0x0000000A; +pub const DIF_CALCDISKSPACE: DI_FUNCTION = 0x0000000B; +pub const DIF_DESTROYPRIVATEDATA: DI_FUNCTION = 0x0000000C; +pub const DIF_VALIDATEDRIVER: DI_FUNCTION = 0x0000000D; +pub const DIF_DETECT: DI_FUNCTION = 0x0000000F; +pub const DIF_INSTALLWIZARD: DI_FUNCTION = 0x00000010; +pub const DIF_DESTROYWIZARDDATA: DI_FUNCTION = 0x00000011; +pub const DIF_PROPERTYCHANGE: DI_FUNCTION = 0x00000012; +pub const DIF_ENABLECLASS: DI_FUNCTION = 0x00000013; +pub const DIF_DETECTVERIFY: DI_FUNCTION = 0x00000014; +pub const DIF_INSTALLDEVICEFILES: DI_FUNCTION = 0x00000015; +pub const DIF_UNREMOVE: DI_FUNCTION = 0x00000016; +pub const DIF_SELECTBESTCOMPATDRV: DI_FUNCTION = 0x00000017; +pub const DIF_ALLOW_INSTALL: DI_FUNCTION = 0x00000018; +pub const DIF_REGISTERDEVICE: DI_FUNCTION = 0x00000019; +pub const DIF_NEWDEVICEWIZARD_PRESELECT: DI_FUNCTION = 0x0000001A; +pub const DIF_NEWDEVICEWIZARD_SELECT: DI_FUNCTION = 0x0000001B; +pub const DIF_NEWDEVICEWIZARD_PREANALYZE: DI_FUNCTION = 0x0000001C; +pub const DIF_NEWDEVICEWIZARD_POSTANALYZE: DI_FUNCTION = 0x0000001D; +pub const DIF_NEWDEVICEWIZARD_FINISHINSTALL: DI_FUNCTION = 0x0000001E; +pub const DIF_UNUSED1: DI_FUNCTION = 0x0000001F; +pub const DIF_INSTALLINTERFACES: DI_FUNCTION = 0x00000020; +pub const DIF_DETECTCANCEL: DI_FUNCTION = 0x00000021; +pub const DIF_REGISTER_COINSTALLERS: DI_FUNCTION = 0x00000022; +pub const DIF_ADDPROPERTYPAGE_ADVANCED: DI_FUNCTION = 0x00000023; +pub const DIF_ADDPROPERTYPAGE_BASIC: DI_FUNCTION = 0x00000024; +pub const DIF_RESERVED1: DI_FUNCTION = 0x00000025; +pub const DIF_TROUBLESHOOTER: DI_FUNCTION = 0x00000026; +pub const DIF_POWERMESSAGEWAKE: DI_FUNCTION = 0x00000027; +pub const DIF_ADDREMOTEPROPERTYPAGE_ADVANCED: DI_FUNCTION = 0x00000028; +pub const DIF_UPDATEDRIVER_UI: DI_FUNCTION = 0x00000029; +pub const DIF_FINISHINSTALL_ACTION: DI_FUNCTION = 0x0000002A; +pub const DIF_RESERVED2: DI_FUNCTION = 0x00000030; +pub const DIF_MOVEDEVICE: DI_FUNCTION = 0x0000000E; +pub type DI_FUNCTION = ::UINT; +STRUCT!{nodebug struct SP_DEVINSTALL_PARAMS_A { + cbSize: ::DWORD, + Flags: ::DWORD, + FlagsEx: ::DWORD, + hwndParent: ::HWND, + InstallMsgHandler: PSP_FILE_CALLBACK_A, + InstallMsgHandlerContext: ::PVOID, + FileQueue: HSPFILEQ, + ClassInstallReserved: ::ULONG_PTR, + Reserved: ::DWORD, + DriverPath: [::CHAR; ::MAX_PATH], +}} +pub type PSP_DEVINSTALL_PARAMS_A = *mut SP_DEVINSTALL_PARAMS_A; +STRUCT!{nodebug struct SP_DEVINSTALL_PARAMS_W { + cbSize: ::DWORD, + Flags: ::DWORD, + FlagsEx: ::DWORD, + hwndParent: ::HWND, + InstallMsgHandler: PSP_FILE_CALLBACK_W, + InstallMsgHandlerContext: ::PVOID, + FileQueue: HSPFILEQ, + ClassInstallReserved: ::ULONG_PTR, + Reserved: ::DWORD, + DriverPath: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_DEVINSTALL_PARAMS_W = *mut SP_DEVINSTALL_PARAMS_W; +pub const DI_SHOWOEM: ::DWORD = 0x00000001; +pub const DI_SHOWCOMPAT: ::DWORD = 0x00000002; +pub const DI_SHOWCLASS: ::DWORD = 0x00000004; +pub const DI_SHOWALL: ::DWORD = 0x00000007; +pub const DI_NOVCP: ::DWORD = 0x00000008; +pub const DI_DIDCOMPAT: ::DWORD = 0x00000010; +pub const DI_DIDCLASS: ::DWORD = 0x00000020; +pub const DI_AUTOASSIGNRES: ::DWORD = 0x00000040; +pub const DI_NEEDRESTART: ::DWORD = 0x00000080; +pub const DI_NEEDREBOOT: ::DWORD = 0x00000100; +pub const DI_NOBROWSE: ::DWORD = 0x00000200; +pub const DI_MULTMFGS: ::DWORD = 0x00000400; +pub const DI_DISABLED: ::DWORD = 0x00000800; +pub const DI_GENERALPAGE_ADDED: ::DWORD = 0x00001000; +pub const DI_RESOURCEPAGE_ADDED: ::DWORD = 0x00002000; +pub const DI_PROPERTIES_CHANGE: ::DWORD = 0x00004000; +pub const DI_INF_IS_SORTED: ::DWORD = 0x00008000; +pub const DI_ENUMSINGLEINF: ::DWORD = 0x00010000; +pub const DI_DONOTCALLCONFIGMG: ::DWORD = 0x00020000; +pub const DI_INSTALLDISABLED: ::DWORD = 0x00040000; +pub const DI_COMPAT_FROM_CLASS: ::DWORD = 0x00080000; +pub const DI_CLASSINSTALLPARAMS: ::DWORD = 0x00100000; +pub const DI_NODI_DEFAULTACTION: ::DWORD = 0x00200000; +pub const DI_QUIETINSTALL: ::DWORD = 0x00800000; +pub const DI_NOFILECOPY: ::DWORD = 0x01000000; +pub const DI_FORCECOPY: ::DWORD = 0x02000000; +pub const DI_DRIVERPAGE_ADDED: ::DWORD = 0x04000000; +pub const DI_USECI_SELECTSTRINGS: ::DWORD = 0x08000000; +pub const DI_OVERRIDE_INFFLAGS: ::DWORD = 0x10000000; +pub const DI_PROPS_NOCHANGEUSAGE: ::DWORD = 0x20000000; +pub const DI_NOSELECTICONS: ::DWORD = 0x40000000; +pub const DI_NOWRITE_IDS: ::DWORD = 0x80000000; +pub const DI_FLAGSEX_RESERVED2: ::DWORD = 0x00000001; +pub const DI_FLAGSEX_RESERVED3: ::DWORD = 0x00000002; +pub const DI_FLAGSEX_CI_FAILED: ::DWORD = 0x00000004; +pub const DI_FLAGSEX_FINISHINSTALL_ACTION: ::DWORD = 0x00000008; +pub const DI_FLAGSEX_DIDINFOLIST: ::DWORD = 0x00000010; +pub const DI_FLAGSEX_DIDCOMPATINFO: ::DWORD = 0x00000020; +pub const DI_FLAGSEX_FILTERCLASSES: ::DWORD = 0x00000040; +pub const DI_FLAGSEX_SETFAILEDINSTALL: ::DWORD = 0x00000080; +pub const DI_FLAGSEX_DEVICECHANGE: ::DWORD = 0x00000100; +pub const DI_FLAGSEX_ALWAYSWRITEIDS: ::DWORD = 0x00000200; +pub const DI_FLAGSEX_PROPCHANGE_PENDING: ::DWORD = 0x00000400; +pub const DI_FLAGSEX_ALLOWEXCLUDEDDRVS: ::DWORD = 0x00000800; +pub const DI_FLAGSEX_NOUIONQUERYREMOVE: ::DWORD = 0x00001000; +pub const DI_FLAGSEX_USECLASSFORCOMPAT: ::DWORD = 0x00002000; +pub const DI_FLAGSEX_RESERVED4: ::DWORD = 0x00004000; +pub const DI_FLAGSEX_NO_DRVREG_MODIFY: ::DWORD = 0x00008000; +pub const DI_FLAGSEX_IN_SYSTEM_SETUP: ::DWORD = 0x00010000; +pub const DI_FLAGSEX_INET_DRIVER: ::DWORD = 0x00020000; +pub const DI_FLAGSEX_APPENDDRIVERLIST: ::DWORD = 0x00040000; +pub const DI_FLAGSEX_PREINSTALLBACKUP: ::DWORD = 0x00080000; +pub const DI_FLAGSEX_BACKUPONREPLACE: ::DWORD = 0x00100000; +pub const DI_FLAGSEX_DRIVERLIST_FROM_URL: ::DWORD = 0x00200000; +pub const DI_FLAGSEX_RESERVED1: ::DWORD = 0x00400000; +pub const DI_FLAGSEX_EXCLUDE_OLD_INET_DRIVERS: ::DWORD = 0x00800000; +pub const DI_FLAGSEX_POWERPAGE_ADDED: ::DWORD = 0x01000000; +pub const DI_FLAGSEX_FILTERSIMILARDRIVERS: ::DWORD = 0x02000000; +pub const DI_FLAGSEX_INSTALLEDDRIVER: ::DWORD = 0x04000000; +pub const DI_FLAGSEX_NO_CLASSLIST_NODE_MERGE: ::DWORD = 0x08000000; +pub const DI_FLAGSEX_ALTPLATFORM_DRVSEARCH: ::DWORD = 0x10000000; +pub const DI_FLAGSEX_RESTART_DEVICE_ONLY: ::DWORD = 0x20000000; +pub const DI_FLAGSEX_RECURSIVESEARCH: ::DWORD = 0x40000000; +pub const DI_FLAGSEX_SEARCH_PUBLISHED_INFS: ::DWORD = 0x80000000; +STRUCT!{struct SP_CLASSINSTALL_HEADER { + cbSize: ::DWORD, + InstallFunction: DI_FUNCTION, +}} +pub type PSP_CLASSINSTALL_HEADER = *mut SP_CLASSINSTALL_HEADER; +STRUCT!{struct SP_ENABLECLASS_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ClassGuid: ::GUID, + EnableMessage: ::DWORD, +}} +pub type PSP_ENABLECLASS_PARAMS = *mut SP_ENABLECLASS_PARAMS; +pub const ENABLECLASS_QUERY: ::DWORD = 0; +pub const ENABLECLASS_SUCCESS: ::DWORD = 1; +pub const ENABLECLASS_FAILURE: ::DWORD = 2; +pub const DICS_ENABLE: ::DWORD = 0x00000001; +pub const DICS_DISABLE: ::DWORD = 0x00000002; +pub const DICS_PROPCHANGE: ::DWORD = 0x00000003; +pub const DICS_START: ::DWORD = 0x00000004; +pub const DICS_STOP: ::DWORD = 0x00000005; +pub const DICS_FLAG_GLOBAL: ::DWORD = 0x00000001; +pub const DICS_FLAG_CONFIGSPECIFIC: ::DWORD = 0x00000002; +pub const DICS_FLAG_CONFIGGENERAL: ::DWORD = 0x00000004; +STRUCT!{struct SP_PROPCHANGE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + StateChange: ::DWORD, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_PROPCHANGE_PARAMS = *mut SP_PROPCHANGE_PARAMS; +STRUCT!{struct SP_REMOVEDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_REMOVEDEVICE_PARAMS = *mut SP_REMOVEDEVICE_PARAMS; +pub const DI_REMOVEDEVICE_GLOBAL: ::DWORD = 0x00000001; +pub const DI_REMOVEDEVICE_CONFIGSPECIFIC: ::DWORD = 0x00000002; +STRUCT!{struct SP_UNREMOVEDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Scope: ::DWORD, + HwProfile: ::DWORD, +}} +pub type PSP_UNREMOVEDEVICE_PARAMS = *mut SP_UNREMOVEDEVICE_PARAMS; +pub const DI_UNREMOVEDEVICE_CONFIGSPECIFIC: ::DWORD = 0x00000002; +STRUCT!{nodebug struct SP_SELECTDEVICE_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Title: [::CHAR; MAX_TITLE_LEN], + Instructions: [::CHAR; MAX_INSTRUCTION_LEN], + ListLabel: [::CHAR; MAX_LABEL_LEN], + SubTitle: [::CHAR; MAX_SUBTITLE_LEN], + Reserved: [::BYTE; 2], +}} +pub type PSP_SELECTDEVICE_PARAMS_A = *mut SP_SELECTDEVICE_PARAMS_A; +STRUCT!{nodebug struct SP_SELECTDEVICE_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Title: [::WCHAR; MAX_TITLE_LEN], + Instructions: [::WCHAR; MAX_INSTRUCTION_LEN], + ListLabel: [::WCHAR; MAX_LABEL_LEN], + SubTitle: [::WCHAR; MAX_SUBTITLE_LEN], +}} +pub type PSP_SELECTDEVICE_PARAMS_W = *mut SP_SELECTDEVICE_PARAMS_W; +pub type PDETECT_PROGRESS_NOTIFY = Option ::BOOL>; +STRUCT!{nodebug struct SP_DETECTDEVICE_PARAMS { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + DetectProgressNotify: PDETECT_PROGRESS_NOTIFY, + ProgressNotifyParam: ::PVOID, +}} +pub type PSP_DETECTDEVICE_PARAMS = *mut SP_DETECTDEVICE_PARAMS; +pub const MAX_INSTALLWIZARD_DYNAPAGES: usize = 20; +STRUCT!{struct SP_INSTALLWIZARD_DATA { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Flags: ::DWORD, + DynamicPages: [::HPROPSHEETPAGE; MAX_INSTALLWIZARD_DYNAPAGES], + NumDynamicPages: ::DWORD, + DynamicPageFlags: ::DWORD, + PrivateFlags: ::DWORD, + PrivateData: ::LPARAM, + hwndWizardDlg: ::HWND, +}} +pub type PSP_INSTALLWIZARD_DATA = *mut SP_INSTALLWIZARD_DATA; +pub const NDW_INSTALLFLAG_DIDFACTDEFS: ::DWORD = 0x00000001; +pub const NDW_INSTALLFLAG_HARDWAREALLREADYIN: ::DWORD = 0x00000002; +pub const NDW_INSTALLFLAG_NEEDRESTART: ::DWORD = DI_NEEDRESTART; +pub const NDW_INSTALLFLAG_NEEDREBOOT: ::DWORD = DI_NEEDREBOOT; +pub const NDW_INSTALLFLAG_NEEDSHUTDOWN: ::DWORD = 0x00000200; +pub const NDW_INSTALLFLAG_EXPRESSINTRO: ::DWORD = 0x00000400; +pub const NDW_INSTALLFLAG_SKIPISDEVINSTALLED: ::DWORD = 0x00000800; +pub const NDW_INSTALLFLAG_NODETECTEDDEVS: ::DWORD = 0x00001000; +pub const NDW_INSTALLFLAG_INSTALLSPECIFIC: ::DWORD = 0x00002000; +pub const NDW_INSTALLFLAG_SKIPCLASSLIST: ::DWORD = 0x00004000; +pub const NDW_INSTALLFLAG_CI_PICKED_OEM: ::DWORD = 0x00008000; +pub const NDW_INSTALLFLAG_PCMCIAMODE: ::DWORD = 0x00010000; +pub const NDW_INSTALLFLAG_PCMCIADEVICE: ::DWORD = 0x00020000; +pub const NDW_INSTALLFLAG_USERCANCEL: ::DWORD = 0x00040000; +pub const NDW_INSTALLFLAG_KNOWNCLASS: ::DWORD = 0x00080000; +pub const DYNAWIZ_FLAG_PAGESADDED: ::DWORD = 0x00000001; +pub const DYNAWIZ_FLAG_ANALYZE_HANDLECONFLICT: ::DWORD = 0x00000008; +pub const DYNAWIZ_FLAG_INSTALLDET_NEXT: ::DWORD = 0x00000002; +pub const DYNAWIZ_FLAG_INSTALLDET_PREV: ::DWORD = 0x00000004; +pub const MIN_IDD_DYNAWIZ_RESOURCE_ID: ::c_int = 10000; +pub const MAX_IDD_DYNAWIZ_RESOURCE_ID: ::c_int = 11000; +pub const IDD_DYNAWIZ_FIRSTPAGE: ::c_int = 10000; +pub const IDD_DYNAWIZ_SELECT_PREVPAGE: ::c_int = 10001; +pub const IDD_DYNAWIZ_SELECT_NEXTPAGE: ::c_int = 10002; +pub const IDD_DYNAWIZ_ANALYZE_PREVPAGE: ::c_int = 10003; +pub const IDD_DYNAWIZ_ANALYZE_NEXTPAGE: ::c_int = 10004; +pub const IDD_DYNAWIZ_SELECTDEV_PAGE: ::c_int = 10009; +pub const IDD_DYNAWIZ_ANALYZEDEV_PAGE: ::c_int = 10010; +pub const IDD_DYNAWIZ_INSTALLDETECTEDDEVS_PAGE: ::c_int = 10011; +pub const IDD_DYNAWIZ_SELECTCLASS_PAGE: ::c_int = 10012; +pub const IDD_DYNAWIZ_INSTALLDETECTED_PREVPAGE: ::c_int = 10006; +pub const IDD_DYNAWIZ_INSTALLDETECTED_NEXTPAGE: ::c_int = 10007; +pub const IDD_DYNAWIZ_INSTALLDETECTED_NODEVS: ::c_int = 10008; +STRUCT!{struct SP_NEWDEVICEWIZARD_DATA { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + Flags: ::DWORD, + DynamicPages: [::HPROPSHEETPAGE; MAX_INSTALLWIZARD_DYNAPAGES], + NumDynamicPages: ::DWORD, + hwndWizardDlg: ::HWND, +}} +pub type PSP_NEWDEVICEWIZARD_DATA = *mut SP_NEWDEVICEWIZARD_DATA; +pub type SP_ADDPROPERTYPAGE_DATA = SP_NEWDEVICEWIZARD_DATA; +pub type PSP_ADDPROPERTYPAGE_DATA = PSP_NEWDEVICEWIZARD_DATA; +STRUCT!{nodebug struct SP_TROUBLESHOOTER_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ChmFile: [::CHAR; ::MAX_PATH], + HtmlTroubleShooter: [::CHAR; ::MAX_PATH], +}} +pub type PSP_TROUBLESHOOTER_PARAMS_A = *mut SP_TROUBLESHOOTER_PARAMS_A; +STRUCT!{nodebug struct SP_TROUBLESHOOTER_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + ChmFile: [::WCHAR; ::MAX_PATH], + HtmlTroubleShooter: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_TROUBLESHOOTER_PARAMS_W = *mut SP_TROUBLESHOOTER_PARAMS_W; +STRUCT!{nodebug struct SP_POWERMESSAGEWAKE_PARAMS_A { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + PowerMessageWake: [::CHAR; LINE_LEN * 2], +}} +pub type PSP_POWERMESSAGEWAKE_PARAMS_A = *mut SP_POWERMESSAGEWAKE_PARAMS_A; +STRUCT!{nodebug struct SP_POWERMESSAGEWAKE_PARAMS_W { + ClassInstallHeader: SP_CLASSINSTALL_HEADER, + PowerMessageWake: [::WCHAR; LINE_LEN * 2], +}} +pub type PSP_POWERMESSAGEWAKE_PARAMS_W = *mut SP_POWERMESSAGEWAKE_PARAMS_W; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V2_A { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::CHAR; LINE_LEN], + MfgName: [::CHAR; LINE_LEN], + ProviderName: [::CHAR; LINE_LEN], + DriverDate: ::FILETIME, + DriverVersion: ::DWORDLONG, +}} +pub type PSP_DRVINFO_DATA_V2_A = *mut SP_DRVINFO_DATA_V2_A; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V2_W { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::WCHAR; LINE_LEN], + MfgName: [::WCHAR; LINE_LEN], + ProviderName: [::WCHAR; LINE_LEN], + DriverDate: ::FILETIME, + DriverVersion: ::DWORDLONG, +}} +pub type PSP_DRVINFO_DATA_V2_W = *mut SP_DRVINFO_DATA_V2_W; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V1_A { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::CHAR; LINE_LEN], + MfgName: [::CHAR; LINE_LEN], + ProviderName: [::CHAR; LINE_LEN], +}} +pub type PSP_DRVINFO_DATA_V1_A = *mut SP_DRVINFO_DATA_V1_A; +STRUCT!{nodebug struct SP_DRVINFO_DATA_V1_W { + cbSize: ::DWORD, + DriverType: ::DWORD, + Reserved: ::ULONG_PTR, + Description: [::WCHAR; LINE_LEN], + MfgName: [::WCHAR; LINE_LEN], + ProviderName: [::WCHAR; LINE_LEN], +}} +pub type PSP_DRVINFO_DATA_V1_W = *mut SP_DRVINFO_DATA_V1_W; +pub type SP_DRVINFO_DATA_A = SP_DRVINFO_DATA_V2_A; +pub type PSP_DRVINFO_DATA_A = PSP_DRVINFO_DATA_V2_A; +pub type SP_DRVINFO_DATA_W = SP_DRVINFO_DATA_V2_W; +pub type PSP_DRVINFO_DATA_W = PSP_DRVINFO_DATA_V2_W; +STRUCT!{nodebug struct SP_DRVINFO_DETAIL_DATA_A { + cbSize: ::DWORD, + InfDate: ::FILETIME, + CompatIDsOffset: ::DWORD, + CompatIDsLength: ::DWORD, + Reserved: ::ULONG_PTR, + SectionName: [::CHAR; LINE_LEN], + InfFileName: [::CHAR; ::MAX_PATH], + DrvDescription: [::CHAR; LINE_LEN], + HardwareID: [::CHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DRVINFO_DETAIL_DATA_A = *mut SP_DRVINFO_DETAIL_DATA_A; +STRUCT!{nodebug struct SP_DRVINFO_DETAIL_DATA_W { + cbSize: ::DWORD, + InfDate: ::FILETIME, + CompatIDsOffset: ::DWORD, + CompatIDsLength: ::DWORD, + Reserved: ::ULONG_PTR, + SectionName: [::WCHAR; LINE_LEN], + InfFileName: [::WCHAR; ::MAX_PATH], + DrvDescription: [::WCHAR; LINE_LEN], + HardwareID: [::WCHAR; ::ANYSIZE_ARRAY], +}} +pub type PSP_DRVINFO_DETAIL_DATA_W = *mut SP_DRVINFO_DETAIL_DATA_W; +STRUCT!{struct SP_DRVINSTALL_PARAMS { + cbSize: ::DWORD, + Rank: ::DWORD, + Flags: ::DWORD, + PrivateData: ::DWORD_PTR, + Reserved: ::DWORD, +}} +pub type PSP_DRVINSTALL_PARAMS = *mut SP_DRVINSTALL_PARAMS; +pub const DNF_DUPDESC: ::DWORD = 0x00000001; +pub const DNF_OLDDRIVER: ::DWORD = 0x00000002; +pub const DNF_EXCLUDEFROMLIST: ::DWORD = 0x00000004; +pub const DNF_NODRIVER: ::DWORD = 0x00000008; +pub const DNF_LEGACYINF: ::DWORD = 0x00000010; +pub const DNF_CLASS_DRIVER: ::DWORD = 0x00000020; +pub const DNF_COMPATIBLE_DRIVER: ::DWORD = 0x00000040; +pub const DNF_INET_DRIVER: ::DWORD = 0x00000080; +pub const DNF_UNUSED1: ::DWORD = 0x00000100; +pub const DNF_UNUSED2: ::DWORD = 0x00000200; +pub const DNF_OLD_INET_DRIVER: ::DWORD = 0x00000400; +pub const DNF_BAD_DRIVER: ::DWORD = 0x00000800; +pub const DNF_DUPPROVIDER: ::DWORD = 0x00001000; +pub const DNF_INF_IS_SIGNED: ::DWORD = 0x00002000; +pub const DNF_OEM_F6_INF: ::DWORD = 0x00004000; +pub const DNF_DUPDRIVERVER: ::DWORD = 0x00008000; +pub const DNF_BASIC_DRIVER: ::DWORD = 0x00010000; +pub const DNF_AUTHENTICODE_SIGNED: ::DWORD = 0x00020000; +pub const DNF_INSTALLEDDRIVER: ::DWORD = 0x00040000; +pub const DNF_ALWAYSEXCLUDEFROMLIST: ::DWORD = 0x00080000; +pub const DNF_INBOX_DRIVER: ::DWORD = 0x00100000; +pub const DNF_REQUESTADDITIONALSOFTWARE: ::DWORD = 0x00200000; +pub const DNF_UNUSED_22: ::DWORD = 0x00400000; +pub const DNF_UNUSED_23: ::DWORD = 0x00800000; +pub const DNF_UNUSED_24: ::DWORD = 0x01000000; +pub const DNF_UNUSED_25: ::DWORD = 0x02000000; +pub const DNF_UNUSED_26: ::DWORD = 0x04000000; +pub const DNF_UNUSED_27: ::DWORD = 0x08000000; +pub const DNF_UNUSED_28: ::DWORD = 0x10000000; +pub const DNF_UNUSED_29: ::DWORD = 0x20000000; +pub const DNF_UNUSED_30: ::DWORD = 0x40000000; +pub const DNF_UNUSED_31: ::DWORD = 0x80000000; +pub type PSP_DETSIG_CMPPROC = Option ::DWORD>; +STRUCT!{struct COINSTALLER_CONTEXT_DATA { + PostProcessing: ::BOOL, + InstallResult: ::DWORD, + PrivateData: ::PVOID, +}} +pub type PCOINSTALLER_CONTEXT_DATA = *mut COINSTALLER_CONTEXT_DATA; +STRUCT!{struct SP_CLASSIMAGELIST_DATA { + cbSize: ::DWORD, + ImageList: ::HIMAGELIST, + Reserved: ::ULONG_PTR, +}} +pub type PSP_CLASSIMAGELIST_DATA = *mut SP_CLASSIMAGELIST_DATA; +STRUCT!{struct SP_PROPSHEETPAGE_REQUEST { + cbSize: ::DWORD, + PageRequested: ::DWORD, + DeviceInfoSet: HDEVINFO, + DeviceInfoData: PSP_DEVINFO_DATA, +}} +pub type PSP_PROPSHEETPAGE_REQUEST = *mut SP_PROPSHEETPAGE_REQUEST; +pub const SPPSR_SELECT_DEVICE_RESOURCES: ::DWORD = 1; +pub const SPPSR_ENUM_BASIC_DEVICE_PROPERTIES: ::DWORD = 2; +pub const SPPSR_ENUM_ADV_DEVICE_PROPERTIES: ::DWORD = 3; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V2_A { + cbSize: ::DWORD, + FullInfPath: [::CHAR; ::MAX_PATH], + FilenameOffset: ::INT, + ReinstallInstance: [::CHAR; ::MAX_PATH], +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V2_A = *mut SP_BACKUP_QUEUE_PARAMS_V2_A; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V2_W { + cbSize: ::DWORD, + FullInfPath: [::WCHAR; ::MAX_PATH], + FilenameOffset: ::INT, + ReinstallInstance: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V2_W = *mut SP_BACKUP_QUEUE_PARAMS_V2_W; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V1_A { + cbSize: ::DWORD, + FullInfPath: [::CHAR; ::MAX_PATH], + FilenameOffset: ::INT, +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V1_A = *mut SP_BACKUP_QUEUE_PARAMS_V1_A; +STRUCT!{nodebug struct SP_BACKUP_QUEUE_PARAMS_V1_W { + cbSize: ::DWORD, + FullInfPath: [::WCHAR; ::MAX_PATH], + FilenameOffset: ::INT, +}} +pub type PSP_BACKUP_QUEUE_PARAMS_V1_W = *mut SP_BACKUP_QUEUE_PARAMS_V1_W; +pub type SP_BACKUP_QUEUE_PARAMS_A = SP_BACKUP_QUEUE_PARAMS_V2_A; +pub type PSP_BACKUP_QUEUE_PARAMS_A = PSP_BACKUP_QUEUE_PARAMS_V2_A; +pub type SP_BACKUP_QUEUE_PARAMS_W = SP_BACKUP_QUEUE_PARAMS_V2_W; +pub type PSP_BACKUP_QUEUE_PARAMS_W = PSP_BACKUP_QUEUE_PARAMS_V2_W; +pub const ERROR_EXPECTED_SECTION_NAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0; +pub const ERROR_BAD_SECTION_NAME_LINE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 1; +pub const ERROR_SECTION_NAME_TOO_LONG: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 2; +pub const ERROR_GENERAL_SYNTAX: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 3; +pub const ERROR_WRONG_INF_STYLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x100; +pub const ERROR_SECTION_NOT_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x101; +pub const ERROR_LINE_NOT_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x102; +pub const ERROR_NO_BACKUP: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x103; +pub const ERROR_NO_ASSOCIATED_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x200; +pub const ERROR_CLASS_MISMATCH: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x201; +pub const ERROR_DUPLICATE_FOUND: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x202; +pub const ERROR_NO_DRIVER_SELECTED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x203; +pub const ERROR_KEY_DOES_NOT_EXIST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x204; +pub const ERROR_INVALID_DEVINST_NAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x205; +pub const ERROR_INVALID_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x206; +pub const ERROR_DEVINST_ALREADY_EXISTS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x207; +pub const ERROR_DEVINFO_NOT_REGISTERED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x208; +pub const ERROR_INVALID_REG_PROPERTY: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x209; +pub const ERROR_NO_INF: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20A; +pub const ERROR_NO_SUCH_DEVINST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x20B; +pub const ERROR_CANT_LOAD_CLASS_ICON: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x20C; +pub const ERROR_INVALID_CLASS_INSTALLER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x20D; +pub const ERROR_DI_DO_DEFAULT: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20E; +pub const ERROR_DI_NOFILECOPY: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x20F; +pub const ERROR_INVALID_HWPROFILE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x210; +pub const ERROR_NO_DEVICE_SELECTED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x211; +pub const ERROR_DEVINFO_LIST_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x212; +pub const ERROR_DEVINFO_DATA_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x213; +pub const ERROR_DI_BAD_PATH: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x214; +pub const ERROR_NO_CLASSINSTALL_PARAMS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x215; +pub const ERROR_FILEQUEUE_LOCKED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x216; +pub const ERROR_BAD_SERVICE_INSTALLSECT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x217; +pub const ERROR_NO_CLASS_DRIVER_LIST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x218; +pub const ERROR_NO_ASSOCIATED_SERVICE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x219; +pub const ERROR_NO_DEFAULT_DEVICE_INTERFACE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21A; +pub const ERROR_DEVICE_INTERFACE_ACTIVE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21B; +pub const ERROR_DEVICE_INTERFACE_REMOVED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21C; +pub const ERROR_BAD_INTERFACE_INSTALLSECT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21D; +pub const ERROR_NO_SUCH_INTERFACE_CLASS: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21E; +pub const ERROR_INVALID_REFERENCE_STRING: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x21F; +pub const ERROR_INVALID_MACHINENAME: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x220; +pub const ERROR_REMOTE_COMM_FAILURE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x221; +pub const ERROR_MACHINE_UNAVAILABLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x222; +pub const ERROR_NO_CONFIGMGR_SERVICES: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x223; +pub const ERROR_INVALID_PROPPAGE_PROVIDER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x224; +pub const ERROR_NO_SUCH_DEVICE_INTERFACE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x225; +pub const ERROR_DI_POSTPROCESSING_REQUIRED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x226; +pub const ERROR_INVALID_COINSTALLER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x227; +pub const ERROR_NO_COMPAT_DRIVERS: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x228; +pub const ERROR_NO_DEVICE_ICON: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x229; +pub const ERROR_INVALID_INF_LOGCONFIG: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22A; +pub const ERROR_DI_DONT_INSTALL: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22B; +pub const ERROR_INVALID_FILTER_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22C; +pub const ERROR_NON_WINDOWS_NT_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22D; +pub const ERROR_NON_WINDOWS_DRIVER: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22E; +pub const ERROR_NO_CATALOG_FOR_OEM_INF: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x22F; +pub const ERROR_DEVINSTALL_QUEUE_NONNATIVE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x230; +pub const ERROR_NOT_DISABLEABLE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x231; +pub const ERROR_CANT_REMOVE_DEVINST: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x232; +pub const ERROR_INVALID_TARGET: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x233; +pub const ERROR_DRIVER_NONNATIVE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x234; +pub const ERROR_IN_WOW64: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x235; +pub const ERROR_SET_SYSTEM_RESTORE_POINT: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x236; +pub const ERROR_SCE_DISABLED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR | 0x238; +pub const ERROR_UNKNOWN_EXCEPTION: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x239; +pub const ERROR_PNP_REGISTRY_ERROR: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23A; +pub const ERROR_REMOTE_REQUEST_UNSUPPORTED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23B; +pub const ERROR_NOT_AN_INSTALLED_OEM_INF: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23C; +pub const ERROR_INF_IN_USE_BY_DEVICES: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23D; +pub const ERROR_DI_FUNCTION_OBSOLETE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x23E; +pub const ERROR_NO_AUTHENTICODE_CATALOG: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x23F; +pub const ERROR_AUTHENTICODE_DISALLOWED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x240; +pub const ERROR_AUTHENTICODE_TRUSTED_PUBLISHER: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x241; +pub const ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x242; +pub const ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x243; +pub const ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x244; +pub const ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x245; +pub const ERROR_DEVICE_INSTALLER_NOT_READY: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x246; +pub const ERROR_DRIVER_STORE_ADD_FAILED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x247; +pub const ERROR_DEVICE_INSTALL_BLOCKED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x248; +pub const ERROR_DRIVER_INSTALL_BLOCKED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x249; +pub const ERROR_WRONG_INF_TYPE: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x24A; +pub const ERROR_FILE_HASH_NOT_IN_CATALOG: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x24B; +pub const ERROR_DRIVER_STORE_DELETE_FAILED: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x24C; +pub const ERROR_UNRECOVERABLE_STACK_OVERFLOW: ::DWORD = ::APPLICATION_ERROR_MASK + | ::ERROR_SEVERITY_ERROR | 0x300; +pub const EXCEPTION_SPAPI_UNRECOVERABLE_STACK_OVERFLOW: ::DWORD = + ERROR_UNRECOVERABLE_STACK_OVERFLOW; +pub const ERROR_NO_DEFAULT_INTERFACE_DEVICE: ::DWORD = ERROR_NO_DEFAULT_DEVICE_INTERFACE; +pub const ERROR_INTERFACE_DEVICE_ACTIVE: ::DWORD = ERROR_DEVICE_INTERFACE_ACTIVE; +pub const ERROR_INTERFACE_DEVICE_REMOVED: ::DWORD = ERROR_DEVICE_INTERFACE_REMOVED; +pub const ERROR_NO_SUCH_INTERFACE_DEVICE: ::DWORD = ERROR_NO_SUCH_DEVICE_INTERFACE; +pub const ERROR_NOT_INSTALLED: ::DWORD = ::APPLICATION_ERROR_MASK | ::ERROR_SEVERITY_ERROR + | 0x1000; +pub const INFINFO_INF_SPEC_IS_HINF: ::DWORD = 1; +pub const INFINFO_INF_NAME_IS_ABSOLUTE: ::DWORD = 2; +pub const INFINFO_DEFAULT_SEARCH: ::DWORD = 3; +pub const INFINFO_REVERSE_DEFAULT_SEARCH: ::DWORD = 4; +pub const INFINFO_INF_PATH_LIST_SEARCH: ::DWORD = 5; +pub const FILE_COMPRESSION_NONE: ::UINT = 0; +pub const FILE_COMPRESSION_WINLZA: ::UINT = 1; +pub const FILE_COMPRESSION_MSZIP: ::UINT = 2; +pub const FILE_COMPRESSION_NTCAB: ::UINT = 3; +pub const SRCLIST_TEMPORARY: ::DWORD = 0x00000001; +pub const SRCLIST_NOBROWSE: ::DWORD = 0x00000002; +pub const SRCLIST_SYSTEM: ::DWORD = 0x00000010; +pub const SRCLIST_USER: ::DWORD = 0x00000020; +pub const SRCLIST_SYSIFADMIN: ::DWORD = 0x00000040; +pub const SRCLIST_SUBDIRS: ::DWORD = 0x00000100; +pub const SRCLIST_APPEND: ::DWORD = 0x00000200; +pub const SRCLIST_NOSTRIPPLATFORM: ::DWORD = 0x00000400; +pub const IDF_NOBROWSE: ::DWORD = 0x00000001; +pub const IDF_NOSKIP: ::DWORD = 0x00000002; +pub const IDF_NODETAILS: ::DWORD = 0x00000004; +pub const IDF_NOCOMPRESSED: ::DWORD = 0x00000008; +pub const IDF_CHECKFIRST: ::DWORD = 0x00000100; +pub const IDF_NOBEEP: ::DWORD = 0x00000200; +pub const IDF_NOFOREGROUND: ::DWORD = 0x00000400; +pub const IDF_WARNIFSKIP: ::DWORD = 0x00000800; +pub const IDF_NOREMOVABLEMEDIAPROMPT: ::DWORD = 0x00001000; +pub const IDF_USEDISKNAMEASPROMPT: ::DWORD = 0x00002000; +pub const IDF_OEMDISK: ::DWORD = 0x80000000; +pub const DPROMPT_SUCCESS: ::UINT = 0; +pub const DPROMPT_CANCEL: ::UINT = 1; +pub const DPROMPT_SKIPFILE: ::UINT = 2; +pub const DPROMPT_BUFFERTOOSMALL: ::UINT = 3; +pub const DPROMPT_OUTOFMEMORY: ::UINT = 4; +pub const SETDIRID_NOT_FULL_PATH: ::DWORD = 0x00000001; +pub const SRCINFO_PATH: ::UINT = 1; +pub const SRCINFO_TAGFILE: ::UINT = 2; +pub const SRCINFO_DESCRIPTION: ::UINT = 3; +pub const SRCINFO_FLAGS: ::UINT = 4; +pub const SRCINFO_TAGFILE2: ::UINT = 4; +pub const SRC_FLAGS_CABFILE: ::UINT = 0x0010; +pub const SP_COPY_DELETESOURCE: ::DWORD = 0x0000001; +pub const SP_COPY_REPLACEONLY: ::DWORD = 0x0000002; +pub const SP_COPY_NEWER: ::DWORD = 0x0000004; +pub const SP_COPY_NEWER_OR_SAME: ::DWORD = SP_COPY_NEWER; +pub const SP_COPY_NOOVERWRITE: ::DWORD = 0x0000008; +pub const SP_COPY_NODECOMP: ::DWORD = 0x0000010; +pub const SP_COPY_LANGUAGEAWARE: ::DWORD = 0x0000020; +pub const SP_COPY_SOURCE_ABSOLUTE: ::DWORD = 0x0000040; +pub const SP_COPY_SOURCEPATH_ABSOLUTE: ::DWORD = 0x0000080; +pub const SP_COPY_IN_USE_NEEDS_REBOOT: ::DWORD = 0x0000100; +pub const SP_COPY_FORCE_IN_USE: ::DWORD = 0x0000200; +pub const SP_COPY_NOSKIP: ::DWORD = 0x0000400; +pub const SP_FLAG_CABINETCONTINUATION: ::DWORD = 0x0000800; +pub const SP_COPY_FORCE_NOOVERWRITE: ::DWORD = 0x0001000; +pub const SP_COPY_FORCE_NEWER: ::DWORD = 0x0002000; +pub const SP_COPY_WARNIFSKIP: ::DWORD = 0x0004000; +pub const SP_COPY_NOBROWSE: ::DWORD = 0x0008000; +pub const SP_COPY_NEWER_ONLY: ::DWORD = 0x0010000; +pub const SP_COPY_RESERVED: ::DWORD = 0x0020000; +pub const SP_COPY_OEMINF_CATALOG_ONLY: ::DWORD = 0x0040000; +pub const SP_COPY_REPLACE_BOOT_FILE: ::DWORD = 0x0080000; +pub const SP_COPY_NOPRUNE: ::DWORD = 0x0100000; +pub const SP_COPY_OEM_F6_INF: ::DWORD = 0x0200000; +pub const SP_COPY_ALREADYDECOMP: ::DWORD = 0x0400000; +pub const SP_COPY_WINDOWS_SIGNED: ::DWORD = 0x1000000; +pub const SP_COPY_PNPLOCKED: ::DWORD = 0x2000000; +pub const SP_COPY_IN_USE_TRY_RENAME: ::DWORD = 0x4000000; +pub const SP_COPY_INBOX_INF: ::DWORD = 0x8000000; +pub const SP_COPY_HARDLINK: ::DWORD = 0x10000000; +pub const SP_BACKUP_BACKUPPASS: ::DWORD = 0x00000001; +pub const SP_BACKUP_DEMANDPASS: ::DWORD = 0x00000002; +pub const SP_BACKUP_SPECIAL: ::DWORD = 0x00000004; +pub const SP_BACKUP_BOOTFILE: ::DWORD = 0x00000008; +pub const SPQ_SCAN_FILE_PRESENCE: ::DWORD = 0x00000001; +pub const SPQ_SCAN_FILE_VALIDITY: ::DWORD = 0x00000002; +pub const SPQ_SCAN_USE_CALLBACK: ::DWORD = 0x00000004; +pub const SPQ_SCAN_USE_CALLBACKEX: ::DWORD = 0x00000008; +pub const SPQ_SCAN_INFORM_USER: ::DWORD = 0x00000010; +pub const SPQ_SCAN_PRUNE_COPY_QUEUE: ::DWORD = 0x00000020; +pub const SPQ_SCAN_USE_CALLBACK_SIGNERINFO: ::DWORD = 0x00000040; +pub const SPQ_SCAN_PRUNE_DELREN: ::DWORD = 0x00000080; +pub const SPQ_SCAN_FILE_PRESENCE_WITHOUT_SOURCE: ::DWORD = 0x00000100; +pub const SPQ_SCAN_FILE_COMPARISON: ::DWORD = 0x00000200; +pub const SPQ_SCAN_ACTIVATE_DRP: ::DWORD = 0x00000400; +pub const SPQ_DELAYED_COPY: ::DWORD = 0x00000001; +pub const SPQ_FLAG_BACKUP_AWARE: ::DWORD = 0x00000001; +pub const SPQ_FLAG_ABORT_IF_UNSIGNED: ::DWORD = 0x00000002; +pub const SPQ_FLAG_FILES_MODIFIED: ::DWORD = 0x00000004; +pub const SPQ_FLAG_DO_SHUFFLEMOVE: ::DWORD = 0x00000008; +pub const SPQ_FLAG_VALID: ::DWORD = 0x0000000F; +pub const SPOST_NONE: ::DWORD = 0; +pub const SPOST_PATH: ::DWORD = 1; +pub const SPOST_URL: ::DWORD = 2; +pub const SPOST_MAX: ::DWORD = 3; +pub const SUOI_FORCEDELETE: ::DWORD = 0x00000001; +pub const SUOI_INTERNAL1: ::DWORD = 0x00000002; +pub const SPDSL_IGNORE_DISK: ::UINT = 0x00000001; +pub const SPDSL_DISALLOW_NEGATIVE_ADJUST: ::UINT = 0x00000002; +pub const SPFILEQ_FILE_IN_USE: ::INT = 0x00000001; +pub const SPFILEQ_REBOOT_RECOMMENDED: ::INT = 0x00000002; +pub const SPFILEQ_REBOOT_IN_PROGRESS: ::INT = 0x00000004; +pub const FLG_ADDREG_DELREG_BIT: ::DWORD = 0x00008000; +pub const FLG_ADDREG_BINVALUETYPE: ::DWORD = 0x00000001; +pub const FLG_ADDREG_NOCLOBBER: ::DWORD = 0x00000002; +pub const FLG_ADDREG_DELVAL: ::DWORD = 0x00000004; +pub const FLG_ADDREG_APPEND: ::DWORD = 0x00000008; +pub const FLG_ADDREG_KEYONLY: ::DWORD = 0x00000010; +pub const FLG_ADDREG_OVERWRITEONLY: ::DWORD = 0x00000020; +pub const FLG_ADDREG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_ADDREG_KEYONLY_COMMON: ::DWORD = 0x00002000; +pub const FLG_ADDREG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_ADDREG_TYPE_MASK: ::DWORD = 0xFFFF0000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_SZ: ::DWORD = 0x00000000; +pub const FLG_ADDREG_TYPE_MULTI_SZ: ::DWORD = 0x00010000; +pub const FLG_ADDREG_TYPE_EXPAND_SZ: ::DWORD = 0x00020000; +pub const FLG_ADDREG_TYPE_BINARY: ::DWORD = 0x00000000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_DWORD: ::DWORD = 0x00010000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_ADDREG_TYPE_NONE: ::DWORD = 0x00020000 | FLG_ADDREG_BINVALUETYPE; +pub const FLG_DELREG_VALUE: ::DWORD = 0x00000000; +pub const FLG_DELREG_TYPE_MASK: ::DWORD = FLG_ADDREG_TYPE_MASK; +pub const FLG_DELREG_TYPE_SZ: ::DWORD = FLG_ADDREG_TYPE_SZ; +pub const FLG_DELREG_TYPE_MULTI_SZ: ::DWORD = FLG_ADDREG_TYPE_MULTI_SZ; +pub const FLG_DELREG_TYPE_EXPAND_SZ: ::DWORD = FLG_ADDREG_TYPE_EXPAND_SZ; +pub const FLG_DELREG_TYPE_BINARY: ::DWORD = FLG_ADDREG_TYPE_BINARY; +pub const FLG_DELREG_TYPE_DWORD: ::DWORD = FLG_ADDREG_TYPE_DWORD; +pub const FLG_DELREG_TYPE_NONE: ::DWORD = FLG_ADDREG_TYPE_NONE; +pub const FLG_DELREG_64BITKEY: ::DWORD = FLG_ADDREG_64BITKEY; +pub const FLG_DELREG_KEYONLY_COMMON: ::DWORD = FLG_ADDREG_KEYONLY_COMMON; +pub const FLG_DELREG_32BITKEY: ::DWORD = FLG_ADDREG_32BITKEY; +pub const FLG_DELREG_OPERATION_MASK: ::DWORD = 0x000000FE; +pub const FLG_DELREG_MULTI_SZ_DELSTRING: ::DWORD = FLG_DELREG_TYPE_MULTI_SZ | FLG_ADDREG_DELREG_BIT + | 0x00000002; +pub const FLG_BITREG_CLEARBITS: ::DWORD = 0x00000000; +pub const FLG_BITREG_SETBITS: ::DWORD = 0x00000001; +pub const FLG_BITREG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_BITREG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_INI2REG_64BITKEY: ::DWORD = 0x00001000; +pub const FLG_INI2REG_32BITKEY: ::DWORD = 0x00004000; +pub const FLG_REGSVR_DLLREGISTER: ::DWORD = 0x00000001; +pub const FLG_REGSVR_DLLINSTALL: ::DWORD = 0x00000002; +pub const FLG_PROFITEM_CURRENTUSER: ::DWORD = 0x00000001; +pub const FLG_PROFITEM_DELETE: ::DWORD = 0x00000002; +pub const FLG_PROFITEM_GROUP: ::DWORD = 0x00000004; +pub const FLG_PROFITEM_CSIDL: ::DWORD = 0x00000008; +pub const FLG_ADDPROPERTY_NOCLOBBER: ::DWORD = 0x00000001; +pub const FLG_ADDPROPERTY_OVERWRITEONLY: ::DWORD = 0x00000002; +pub const FLG_ADDPROPERTY_APPEND: ::DWORD = 0x00000004; +pub const FLG_ADDPROPERTY_OR: ::DWORD = 0x00000008; +pub const FLG_ADDPROPERTY_AND: ::DWORD = 0x00000010; +pub const FLG_DELPROPERTY_MULTI_SZ_DELSTRING: ::DWORD = 0x00000001; +pub const SPINST_LOGCONFIG: ::UINT = 0x00000001; +pub const SPINST_INIFILES: ::UINT = 0x00000002; +pub const SPINST_REGISTRY: ::UINT = 0x00000004; +pub const SPINST_INI2REG: ::UINT = 0x00000008; +pub const SPINST_FILES: ::UINT = 0x00000010; +pub const SPINST_BITREG: ::UINT = 0x00000020; +pub const SPINST_REGSVR: ::UINT = 0x00000040; +pub const SPINST_UNREGSVR: ::UINT = 0x00000080; +pub const SPINST_PROFILEITEMS: ::UINT = 0x00000100; +pub const SPINST_COPYINF: ::UINT = 0x00000200; +pub const SPINST_PROPERTIES: ::UINT = 0x00000400; +pub const SPINST_ALL: ::UINT = 0x000007ff; +pub const SPINST_SINGLESECTION: ::UINT = 0x00010000; +pub const SPINST_LOGCONFIG_IS_FORCED: ::UINT = 0x00020000; +pub const SPINST_LOGCONFIGS_ARE_OVERRIDES: ::UINT = 0x00040000; +pub const SPINST_REGISTERCALLBACKAWARE: ::UINT = 0x00080000; +pub const SPINST_DEVICEINSTALL: ::UINT = 0x00100000; +pub const SPSVCINST_TAGTOFRONT: ::DWORD = 0x00000001; +pub const SPSVCINST_ASSOCSERVICE: ::DWORD = 0x00000002; +pub const SPSVCINST_DELETEEVENTLOGENTRY: ::DWORD = 0x00000004; +pub const SPSVCINST_NOCLOBBER_DISPLAYNAME: ::DWORD = 0x00000008; +pub const SPSVCINST_NOCLOBBER_STARTTYPE: ::DWORD = 0x00000010; +pub const SPSVCINST_NOCLOBBER_ERRORCONTROL: ::DWORD = 0x00000020; +pub const SPSVCINST_NOCLOBBER_LOADORDERGROUP: ::DWORD = 0x00000040; +pub const SPSVCINST_NOCLOBBER_DEPENDENCIES: ::DWORD = 0x00000080; +pub const SPSVCINST_NOCLOBBER_DESCRIPTION: ::DWORD = 0x00000100; +pub const SPSVCINST_STOPSERVICE: ::DWORD = 0x00000200; +pub const SPSVCINST_CLOBBER_SECURITY: ::DWORD = 0x00000400; +pub const SPSVCINST_STARTSERVICE: ::DWORD = 0x00000800; +pub const SPSVCINST_NOCLOBBER_REQUIREDPRIVILEGES: ::DWORD = 0x00001000; +pub type HSPFILELOG = ::PVOID; +pub const SPFILELOG_SYSTEMLOG: ::DWORD = 0x00000001; +pub const SPFILELOG_FORCENEW: ::DWORD = 0x00000002; +pub const SPFILELOG_QUERYONLY: ::DWORD = 0x00000004; +pub const SPFILELOG_OEMFILE: ::DWORD = 0x00000001; +ENUM!{enum SetupFileLogInfo { + SetupFileLogSourceFilename, + SetupFileLogChecksum, + SetupFileLogDiskTagfile, + SetupFileLogDiskDescription, + SetupFileLogOtherInfo, + SetupFileLogMax, +}} +pub type LogSeverity = ::DWORD; +pub const LogSevInformation: LogSeverity = 0x00000000; +pub const LogSevWarning: LogSeverity = 0x00000001; +pub const LogSevError: LogSeverity = 0x00000002; +pub const LogSevFatalError: LogSeverity = 0x00000003; +pub const LogSevMaximum: LogSeverity = 0x00000004; +pub const DICD_GENERATE_ID: ::DWORD = 0x00000001; +pub const DICD_INHERIT_CLASSDRVS: ::DWORD = 0x00000002; +pub const DIOD_INHERIT_CLASSDRVS: ::DWORD = 0x00000002; +pub const DIOD_CANCEL_REMOVE: ::DWORD = 0x00000004; +pub const DIODI_NO_ADD: ::DWORD = 0x00000001; +pub const SPRDI_FIND_DUPS: ::DWORD = 0x00000001; +pub const SPDIT_NODRIVER: ::DWORD = 0x00000000; +pub const SPDIT_CLASSDRIVER: ::DWORD = 0x00000001; +pub const SPDIT_COMPATDRIVER: ::DWORD = 0x00000002; +pub const DIGCF_DEFAULT: ::DWORD = 0x00000001; +pub const DIGCF_PRESENT: ::DWORD = 0x00000002; +pub const DIGCF_ALLCLASSES: ::DWORD = 0x00000004; +pub const DIGCF_PROFILE: ::DWORD = 0x00000008; +pub const DIGCF_DEVICEINTERFACE: ::DWORD = 0x00000010; +pub const DIBCI_NOINSTALLCLASS: ::DWORD = 0x00000001; +pub const DIBCI_NODISPLAYCLASS: ::DWORD = 0x00000002; +pub const DIOCR_INSTALLER: ::DWORD = 0x00000001; +pub const DIOCR_INTERFACE: ::DWORD = 0x00000002; +pub const DIREG_DEV: ::DWORD = 0x00000001; +pub const DIREG_DRV: ::DWORD = 0x00000002; +pub const DIREG_BOTH: ::DWORD = 0x00000004; +pub const DICLASSPROP_INSTALLER: ::DWORD = 0x00000001; +pub const DICLASSPROP_INTERFACE: ::DWORD = 0x00000002; +pub const SPDRP_DEVICEDESC: ::DWORD = 0x00000000; +pub const SPDRP_HARDWAREID: ::DWORD = 0x00000001; +pub const SPDRP_COMPATIBLEIDS: ::DWORD = 0x00000002; +pub const SPDRP_UNUSED0: ::DWORD = 0x00000003; +pub const SPDRP_SERVICE: ::DWORD = 0x00000004; +pub const SPDRP_UNUSED1: ::DWORD = 0x00000005; +pub const SPDRP_UNUSED2: ::DWORD = 0x00000006; +pub const SPDRP_CLASS: ::DWORD = 0x00000007; +pub const SPDRP_CLASSGUID: ::DWORD = 0x00000008; +pub const SPDRP_DRIVER: ::DWORD = 0x00000009; +pub const SPDRP_CONFIGFLAGS: ::DWORD = 0x0000000A; +pub const SPDRP_MFG: ::DWORD = 0x0000000B; +pub const SPDRP_FRIENDLYNAME: ::DWORD = 0x0000000C; +pub const SPDRP_LOCATION_INFORMATION: ::DWORD = 0x0000000D; +pub const SPDRP_PHYSICAL_DEVICE_OBJECT_NAME: ::DWORD = 0x0000000E; +pub const SPDRP_CAPABILITIES: ::DWORD = 0x0000000F; +pub const SPDRP_UI_NUMBER: ::DWORD = 0x00000010; +pub const SPDRP_UPPERFILTERS: ::DWORD = 0x00000011; +pub const SPDRP_LOWERFILTERS: ::DWORD = 0x00000012; +pub const SPDRP_BUSTYPEGUID: ::DWORD = 0x00000013; +pub const SPDRP_LEGACYBUSTYPE: ::DWORD = 0x00000014; +pub const SPDRP_BUSNUMBER: ::DWORD = 0x00000015; +pub const SPDRP_ENUMERATOR_NAME: ::DWORD = 0x00000016; +pub const SPDRP_SECURITY: ::DWORD = 0x00000017; +pub const SPDRP_SECURITY_SDS: ::DWORD = 0x00000018; +pub const SPDRP_DEVTYPE: ::DWORD = 0x00000019; +pub const SPDRP_EXCLUSIVE: ::DWORD = 0x0000001A; +pub const SPDRP_CHARACTERISTICS: ::DWORD = 0x0000001B; +pub const SPDRP_ADDRESS: ::DWORD = 0x0000001C; +pub const SPDRP_UI_NUMBER_DESC_FORMAT: ::DWORD = 0x0000001D; +pub const SPDRP_DEVICE_POWER_DATA: ::DWORD = 0x0000001E; +pub const SPDRP_REMOVAL_POLICY: ::DWORD = 0x0000001F; +pub const SPDRP_REMOVAL_POLICY_HW_DEFAULT: ::DWORD = 0x00000020; +pub const SPDRP_REMOVAL_POLICY_OVERRIDE: ::DWORD = 0x00000021; +pub const SPDRP_INSTALL_STATE: ::DWORD = 0x00000022; +pub const SPDRP_LOCATION_PATHS: ::DWORD = 0x00000023; +pub const SPDRP_BASE_CONTAINERID: ::DWORD = 0x00000024; +pub const SPDRP_MAXIMUM_PROPERTY: ::DWORD = 0x00000025; +pub const SPCRP_UPPERFILTERS: ::DWORD = 0x00000011; +pub const SPCRP_LOWERFILTERS: ::DWORD = 0x00000012; +pub const SPCRP_SECURITY: ::DWORD = 0x00000017; +pub const SPCRP_SECURITY_SDS: ::DWORD = 0x00000018; +pub const SPCRP_DEVTYPE: ::DWORD = 0x00000019; +pub const SPCRP_EXCLUSIVE: ::DWORD = 0x0000001A; +pub const SPCRP_CHARACTERISTICS: ::DWORD = 0x0000001B; +pub const SPCRP_MAXIMUM_PROPERTY: ::DWORD = 0x0000001C; +pub const DMI_MASK: ::DWORD = 0x00000001; +pub const DMI_BKCOLOR: ::DWORD = 0x00000002; +pub const DMI_USERECT: ::DWORD = 0x00000004; +pub const DIGCDP_FLAG_BASIC: ::DWORD = 0x00000001; +pub const DIGCDP_FLAG_ADVANCED: ::DWORD = 0x00000002; +pub const DIGCDP_FLAG_REMOTE_BASIC: ::DWORD = 0x00000003; +pub const DIGCDP_FLAG_REMOTE_ADVANCED: ::DWORD = 0x00000004; +pub const IDI_RESOURCEFIRST: ::c_int = 159; +pub const IDI_RESOURCE: ::c_int = 159; +pub const IDI_RESOURCELAST: ::c_int = 161; +pub const IDI_RESOURCEOVERLAYFIRST: ::c_int = 161; +pub const IDI_RESOURCEOVERLAYLAST: ::c_int = 161; +pub const IDI_CONFLICT: ::c_int = 161; +pub const IDI_CLASSICON_OVERLAYFIRST: ::c_int = 500; +pub const IDI_CLASSICON_OVERLAYLAST: ::c_int = 502; +pub const IDI_PROBLEM_OVL: ::c_int = 500; +pub const IDI_DISABLED_OVL: ::c_int = 501; +pub const IDI_FORCED_OVL: ::c_int = 502; +pub const SPWPT_SELECTDEVICE: ::DWORD = 0x00000001; +pub const SPWP_USE_DEVINFO_DATA: ::DWORD = 0x00000001; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V1_A { + cbSize: ::DWORD, + CatalogFile: [::CHAR; ::MAX_PATH], + DigitalSigner: [::CHAR; ::MAX_PATH], + DigitalSignerVersion: [::CHAR; ::MAX_PATH], +}} +pub type PSP_INF_SIGNER_INFO_V1_A = *mut SP_INF_SIGNER_INFO_V1_A; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V1_W { + cbSize: ::DWORD, + CatalogFile: [::WCHAR; ::MAX_PATH], + DigitalSigner: [::WCHAR; ::MAX_PATH], + DigitalSignerVersion: [::WCHAR; ::MAX_PATH], +}} +pub type PSP_INF_SIGNER_INFO_V1_W = *mut SP_INF_SIGNER_INFO_V1_W; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V2_A { + cbSize: ::DWORD, + CatalogFile: [::CHAR; ::MAX_PATH], + DigitalSigner: [::CHAR; ::MAX_PATH], + DigitalSignerVersion: [::CHAR; ::MAX_PATH], + SignerScore: ::DWORD, +}} +pub type PSP_INF_SIGNER_INFO_V2_A = *mut SP_INF_SIGNER_INFO_V2_A; +STRUCT!{nodebug struct SP_INF_SIGNER_INFO_V2_W { + cbSize: ::DWORD, + CatalogFile: [::WCHAR; ::MAX_PATH], + DigitalSigner: [::WCHAR; ::MAX_PATH], + DigitalSignerVersion: [::WCHAR; ::MAX_PATH], + SignerScore: ::DWORD, +}} +pub type PSP_INF_SIGNER_INFO_V2_W = *mut SP_INF_SIGNER_INFO_V2_W; +pub type SP_INF_SIGNER_INFO_A = SP_INF_SIGNER_INFO_V2_A; +pub type PSP_INF_SIGNER_INFO_A = PSP_INF_SIGNER_INFO_V2_A; +pub type SP_INF_SIGNER_INFO_W = SP_INF_SIGNER_INFO_V2_W; +pub type PSP_INF_SIGNER_INFO_W = PSP_INF_SIGNER_INFO_V2_W; +pub const SIGNERSCORE_UNKNOWN: ::DWORD = 0xFF000000; +pub const SIGNERSCORE_W9X_SUSPECT: ::DWORD = 0xC0000000; +pub const SIGNERSCORE_UNSIGNED: ::DWORD = 0x80000000; +pub const SIGNERSCORE_AUTHENTICODE: ::DWORD = 0x0F000000; +pub const SIGNERSCORE_WHQL: ::DWORD = 0x0D000005; +pub const SIGNERSCORE_UNCLASSIFIED: ::DWORD = 0x0D000004; +pub const SIGNERSCORE_INBOX: ::DWORD = 0x0D000003; +pub const SIGNERSCORE_LOGO_STANDARD: ::DWORD = 0x0D000002; +pub const SIGNERSCORE_LOGO_PREMIUM: ::DWORD = 0x0D000001; +pub const SIGNERSCORE_MASK: ::DWORD = 0xFF000000; +pub const SIGNERSCORE_SIGNED_MASK: ::DWORD = 0xF0000000; +pub const DICUSTOMDEVPROP_MERGE_MULTISZ: ::DWORD = 0x00000001; +pub const SCWMI_CLOBBER_SECURITY: ::DWORD = 0x00000001; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shellapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shellapi.rs new file mode 100644 index 0000000..6f253cf --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shellapi.rs @@ -0,0 +1,62 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +// STUB +DECLARE_HANDLE!(HDROP, HDROP__); + +pub const NIM_ADD: ::DWORD = 0x00000000; +pub const NIM_MODIFY: ::DWORD = 0x00000001; +pub const NIM_DELETE: ::DWORD = 0x00000002; +pub const NIM_SETFOCUS: ::DWORD = 0x00000003; +pub const NIM_SETVERSION: ::DWORD = 0x00000004; +pub const NIF_MESSAGE: ::UINT = 0x00000001; +pub const NIF_ICON: ::UINT = 0x00000002; +pub const NIF_TIP: ::UINT = 0x00000004; +pub const NIF_STATE: ::UINT = 0x00000008; +pub const NIF_INFO: ::UINT = 0x00000010; +pub const NIF_GUID: ::UINT = 0x00000020; +pub const NIF_REALTIME: ::UINT = 0x00000040; +pub const NIF_SHOWTIP: ::UINT = 0x00000080; +pub const NOTIFYICON_VERSION: ::UINT = 3; +pub const NOTIFYICON_VERSION_4: ::UINT = 4; + +STRUCT!{nodebug struct NOTIFYICONDATAA { + cbSize: ::DWORD, + hWnd: ::HWND, + uID: ::UINT, + uFlags: ::UINT, + uCallbackMessage: ::UINT, + hIcon: ::HICON, + szTip: [::CHAR; 128], + dwState: ::DWORD, + dwStateMask: ::DWORD, + szInfo: [::CHAR; 256], + uTimeout: ::UINT, + szInfoTitle: [::CHAR; 64], + dwInfoFlags: ::DWORD, + guidItem: ::GUID, + hBalloonIcon: ::HICON, +}} +UNION!(NOTIFYICONDATAA, uTimeout, uTimeout, uTimeout_mut, ::UINT); +UNION!(NOTIFYICONDATAA, uTimeout, uVersion, uVersion_mut, ::UINT); +pub type PNOTIFYICONDATAA = *mut NOTIFYICONDATAA; + +STRUCT!{nodebug struct NOTIFYICONDATAW { + cbSize: ::DWORD, + hWnd: ::HWND, + uID: ::UINT, + uFlags: ::UINT, + uCallbackMessage: ::UINT, + hIcon: ::HICON, + szTip: [::WCHAR; 128], + dwState: ::DWORD, + dwStateMask: ::DWORD, + szInfo: [::WCHAR; 256], + uTimeout: ::UINT, + szInfoTitle: [::WCHAR; 64], + dwInfoFlags: ::DWORD, + guidItem: ::GUID, + hBalloonIcon: ::HICON, +}} +UNION!(NOTIFYICONDATAW, uTimeout, uTimeout, uTimeout_mut, ::UINT); +UNION!(NOTIFYICONDATAW, uTimeout, uVersion, uVersion_mut, ::UINT); // used with NIM_SETVERSION, values 0, 3 and 4 +pub type PNOTIFYICONDATAW = *mut NOTIFYICONDATAW; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shellscalingapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shellscalingapi.rs new file mode 100644 index 0000000..d313dde --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shellscalingapi.rs @@ -0,0 +1,19 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +// ShellScalingApi.h +ENUM!{enum PROCESS_DPI_AWARENESS { + Process_DPI_Unaware = 0, + Process_System_DPI_Aware = 1, + Process_Per_Monitor_DPI_Aware = 2, +}} +ENUM!{enum SHELL_UI_COMPONENT { + SHELL_UI_COMPONENT_TASKBARS = 0, + SHELL_UI_COMPONENT_NOTIFICATIONAREA = 1, + SHELL_UI_COMPONENT_DESKBAND = 2, +}} +ENUM!{enum MONITOR_DPI_TYPE { + MDT_EFFECTIVE_DPI = 0, + MDT_ANGULAR_DPI = 1, + MDT_RAW_DPI = 2, +}} +pub const MDT_DEFAULT: MONITOR_DPI_TYPE = MDT_EFFECTIVE_DPI; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shlguid.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shlguid.rs new file mode 100644 index 0000000..f01b4e4 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shlguid.rs @@ -0,0 +1,2 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shlobj.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shlobj.rs new file mode 100644 index 0000000..d551f92 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shlobj.rs @@ -0,0 +1,94 @@ +// Copyright © 2015, Peter Atashian, skdltmxn +// Licensed under the MIT License +pub const INVALID_HANDLE_VALUE: ::HANDLE = -1isize as ::HANDLE; +pub type GPFIDL_FLAGS = ::c_int; +ENUM!{enum KNOWN_FOLDER_FLAG { + KF_FLAG_DEFAULT = 0x00000000, + KF_FLAG_NO_APPCONTAINER_REDIRECTION = 0x00010000, + KF_FLAG_CREATE = 0x00008000, + KF_FLAG_DONT_VERIFY = 0x00004000, + KF_FLAG_DONT_UNEXPAND = 0x00002000, + KF_FLAG_NO_ALIAS = 0x00001000, + KF_FLAG_INIT = 0x00000800, + KF_FLAG_DEFAULT_PATH = 0x00000400, + KF_FLAG_NOT_PARENT_RELATIVE = 0x00000200, + KF_FLAG_SIMPLE_IDLIST = 0x00000100, + KF_FLAG_ALIAS_ONLY = 0x80000000, +}} +pub const IDO_SHGIOI_SHARE: ::c_int = 0x0FFFFFFF; +pub const IDO_SHGIOI_LINK: ::c_int = 0x0FFFFFFE; +// Yes, these values are supposed to overflow. Blame Microsoft. +pub const IDO_SHGIOI_SLOWFILE: ::c_int = 0xFFFFFFFDu32 as ::c_int; +pub const IDO_SHGIOI_DEFAULT: ::c_int = 0xFFFFFFFCu32 as ::c_int; +pub const GPFIDL_DEFAULT: GPFIDL_FLAGS = 0x0000; +pub const GPFIDL_ALTNAME: GPFIDL_FLAGS = 0x0001; +pub const GPFIDL_UNCPRINTER: GPFIDL_FLAGS = 0x0002; +pub const OFASI_EDIT: ::DWORD = 0x0001; +pub const OFASI_OPENDESKTOP: ::DWORD = 0x0002; +// 1204 +pub const CSIDL_DESKTOP: ::c_int = 0x0000; +pub const CSIDL_INTERNET: ::c_int = 0x0001; +pub const CSIDL_PROGRAMS: ::c_int = 0x0002; +pub const CSIDL_CONTROLS: ::c_int = 0x0003; +pub const CSIDL_PRINTERS: ::c_int = 0x0004; +pub const CSIDL_PERSONAL: ::c_int = 0x0005; +pub const CSIDL_FAVORITES: ::c_int = 0x0006; +pub const CSIDL_STARTUP: ::c_int = 0x0007; +pub const CSIDL_RECENT: ::c_int = 0x0008; +pub const CSIDL_SENDTO: ::c_int = 0x0009; +pub const CSIDL_BITBUCKET: ::c_int = 0x000a; +pub const CSIDL_STARTMENU: ::c_int = 0x000b; +pub const CSIDL_MYDOCUMENTS: ::c_int = CSIDL_PERSONAL; +pub const CSIDL_MYMUSIC: ::c_int = 0x000d; +pub const CSIDL_MYVIDEO: ::c_int = 0x000e; +pub const CSIDL_DESKTOPDIRECTORY: ::c_int = 0x0010; +pub const CSIDL_DRIVES: ::c_int = 0x0011; +pub const CSIDL_NETWORK: ::c_int = 0x0012; +pub const CSIDL_NETHOOD: ::c_int = 0x0013; +pub const CSIDL_FONTS: ::c_int = 0x0014; +pub const CSIDL_TEMPLATES: ::c_int = 0x0015; +pub const CSIDL_COMMON_STARTMENU: ::c_int = 0x0016; +pub const CSIDL_COMMON_PROGRAMS: ::c_int = 0x0017; +pub const CSIDL_COMMON_STARTUP: ::c_int = 0x0018; +pub const CSIDL_COMMON_DESKTOPDIRECTORY: ::c_int = 0x0019; +pub const CSIDL_APPDATA: ::c_int = 0x001a; +pub const CSIDL_PRINTHOOD: ::c_int = 0x001b; +pub const CSIDL_LOCAL_APPDATA: ::c_int = 0x001c; +pub const CSIDL_ALTSTARTUP: ::c_int = 0x001d; +pub const CSIDL_COMMON_ALTSTARTUP: ::c_int = 0x001e; +pub const CSIDL_COMMON_FAVORITES: ::c_int = 0x001f; +pub const CSIDL_INTERNET_CACHE: ::c_int = 0x0020; +pub const CSIDL_COOKIES: ::c_int = 0x0021; +pub const CSIDL_HISTORY: ::c_int = 0x0022; +pub const CSIDL_COMMON_APPDATA: ::c_int = 0x0023; +pub const CSIDL_WINDOWS: ::c_int = 0x0024; +pub const CSIDL_SYSTEM: ::c_int = 0x0025; +pub const CSIDL_PROGRAM_FILES: ::c_int = 0x0026; +pub const CSIDL_MYPICTURES: ::c_int = 0x0027; +pub const CSIDL_PROFILE: ::c_int = 0x0028; +pub const CSIDL_SYSTEMX86: ::c_int = 0x0029; +pub const CSIDL_PROGRAM_FILESX86: ::c_int = 0x002a; +pub const CSIDL_PROGRAM_FILES_COMMON: ::c_int = 0x002b; +pub const CSIDL_PROGRAM_FILES_COMMONX86: ::c_int = 0x002c; +pub const CSIDL_COMMON_TEMPLATES: ::c_int = 0x002d; +pub const CSIDL_COMMON_DOCUMENTS: ::c_int = 0x002e; +pub const CSIDL_COMMON_ADMINTOOLS: ::c_int = 0x002f; +pub const CSIDL_ADMINTOOLS: ::c_int = 0x0030; +pub const CSIDL_CONNECTIONS: ::c_int = 0x0031; +pub const CSIDL_COMMON_MUSIC: ::c_int = 0x0035; +pub const CSIDL_COMMON_PICTURES: ::c_int = 0x0036; +pub const CSIDL_COMMON_VIDEO: ::c_int = 0x0037; +pub const CSIDL_RESOURCES: ::c_int = 0x0038; +pub const CSIDL_RESOURCES_LOCALIZED: ::c_int = 0x0039; +pub const CSIDL_COMMON_OEM_LINKS: ::c_int = 0x003a; +pub const CSIDL_CDBURN_AREA: ::c_int = 0x003b; +pub const CSIDL_COMPUTERSNEARME: ::c_int = 0x003d; +pub const CSIDL_FLAG_CREATE: ::c_int = 0x8000; +pub const CSIDL_FLAG_DONT_VERIFY: ::c_int = 0x4000; +pub const CSIDL_FLAG_DONT_UNEXPAND: ::c_int = 0x2000; +pub const CSIDL_FLAG_NO_ALIAS: ::c_int = 0x1000; +pub const CSIDL_FLAG_PER_USER_INIT: ::c_int = 0x0800; +pub const CSIDL_FLAG_MASK: ::c_int = 0xff00; +//1312 +pub const SHGFP_TYPE_CURRENT: ::DWORD = 0; +pub const SHGFP_TYPE_DEFAULT: ::DWORD = 1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shobjidl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shobjidl.rs new file mode 100644 index 0000000..ef7caa1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shobjidl.rs @@ -0,0 +1,652 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +//Terrible forward declarations that need to be filled in +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenu3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRunnableTask; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellTaskScheduler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryCodePage; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistFolder3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPersistIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumFullIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSyncMergeHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithFolderEnumMode; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IParseAndCreateItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumExtraSearch; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellFolder2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewOptions; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellView3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISearchBoxInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderView2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandlerVisuals; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IVisualProperties; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICommDlgBrowser3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IColumnManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderFilterSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderFilter; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObjectSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObject; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInputObject2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellIcon; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IProfferService; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItem2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItemImageFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserAccountChangeCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumShellItems; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferAdviseSink; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferSource; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumResources; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellItemResources; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferDestination; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStreamAsync; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStreamUnbufferedInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithSelection; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithBackReferences; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPropertyUI; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICategoryProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICategorizer; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDropTargetHelper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDragSourceHelper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDragSourceHelper2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkA; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkW; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLinkDataList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IResolveShellLink; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IActionProgressDialog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHWEventHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHWEventHandler2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryCancelAutoPlay; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDynamicHWHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IActionProgress; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellExtInit; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellPropSheetExt; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRemoteComputer; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IQueryContinue; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithCancelEvent; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotification; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotificationCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUserNotification2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IItemNameLimits; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISearchFolderItemFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExtractImage; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExtractImage2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IThumbnailHandlerFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IParentAndItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDockingWindow; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBandInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBand2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList3; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITaskbarList4; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IStartMenuPinnedList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICDBurn; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWizardSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWizardExtension; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IWebWizardExtension; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPublishingWizard; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderViewHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerBrowserEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerBrowser; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibleObject; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IResultsFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumObjects; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOperationsProgressDialog; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IIOCancelInformation; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileOperation; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalkCB; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalkCB2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INamespaceWalk; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAutoCompleteDropDown; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBandSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICDBurnExt; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenuSite; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumReadyCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumerableView; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInsertItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMenuBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFolderBandPriv; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRegTreeItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IImageRecompress; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDeskBar; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMenuPopup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileIsInUse; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationAssociationRegistration; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationAssociationRegistrationUI; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDelegateFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBrowserFrameOptions; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INewWindowManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAttachmentExecute; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellMenuCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellMenu; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellRunDll; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IKnownFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IKnownFolderManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISharingConfigurationManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviousVersionsInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IRelatedItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IIdentityName; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDelegateItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICurrentItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITransferMediumItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUseToBrowseItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDisplayItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IViewStateIdentityItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewItem; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDestinationStreamFactory; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INewMenuClient; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithBindCtx; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControl; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControl2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlDropHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeAccessible; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlCustomDraw; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct INameSpaceTreeControlFolderCapabilities; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPreviewHandlerFrame; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ITrayDeskBand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IBandHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerPaneVisibility; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContextMenuCB; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDefaultExtractIconInit; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommandState; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumExplorerCommand; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExplorerCommandProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IMarkupCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IControlMarkup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeNetworkFolder; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOpenControlPanel; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IComputerInfoChangeNotify; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSystemBindData; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFileSystemBindData2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ICustomDestinationList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDestinations; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDocumentLists; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithAppUserModelID; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IObjectWithProgID; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IUpdateIDList; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDesktopGadget; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDesktopWallpaper; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHomeGroup; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithPropertyStore; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IOpenSearchSource; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IShellLibrary; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDefaultFolderMenuInitialize; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationActivationManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAssocHandlerInvoker; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAssocHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IEnumAssocHandlers; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDataObjectProvider; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IDataTransferManagerInterop; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFrameworkInputPaneHandler; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IFrameworkInputPane; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibilityDockingServiceCallback; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAccessibilityDockingService; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAppVisibilityEvents; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IAppVisibility; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPackageExecutionStateChangeNotification; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IPackageDebugSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ISuspensionDependencyManager; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommandApplicationHostEnvironment; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IExecuteCommandHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDesignModeSettings; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IApplicationDesignModeSettings2; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchTargetMonitor; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchSourceViewSizePreference; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchTargetViewSizePreference; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct ILaunchSourceAppUserModelId; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInitializeWithWindow; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHandlerInfo; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IHandlerActivationHost; +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IContactManagerInterop; +//4498 +pub type SFGAOF = ::ULONG; +//9466 +ENUM!{enum SIGDN { + SIGDN_NORMALDISPLAY = 0, + SIGDN_PARENTRELATIVEPARSING = 0x80018001, + SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, + SIGDN_PARENTRELATIVEEDITING = 0x80031001, + SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, + SIGDN_FILESYSPATH = 0x80058000, + SIGDN_URL = 0x80068000, + SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001, + SIGDN_PARENTRELATIVE = 0x80080001, + SIGDN_PARENTRELATIVEFORUI = 0x80094001, +}} +ENUM!{enum SICHINTF { + SICHINT_DISPLAY = 0, + SICHINT_ALLFIELDS = 0x80000000, + SICHINT_CANONICAL = 0x10000000, + SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000, +}} +//9498 +RIDL!( +interface IShellItem(IShellItemVtbl): IUnknown(IUnknownVtbl) { + fn BindToHandler( + &mut self, pbc: *mut ::IBindCtx, bhid: ::REFGUID, riid: ::REFIID, ppv: *mut *mut ::c_void + ) -> ::HRESULT, + fn GetParent(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn GetDisplayName(&mut self, sigdnName: SIGDN, ppszName: *mut ::LPWSTR) -> ::HRESULT, + fn GetAttributes(&mut self, sfgaoMask: SFGAOF, psfgaoAttribs: *mut SFGAOF) -> ::HRESULT, + fn Compare(&mut self, psi: *mut IShellItem, hint: SICHINTF, piOrder: *mut ::c_int) -> ::HRESULT +} +); +//11963 +pub type IFileOperationProgressSink = ::IUnknown; // TODO +pub type IShellItemArray = ::IUnknown; // TODO +//20869 +RIDL!( +interface IModalWindow(IModalWindowVtbl): IUnknown(IUnknownVtbl) { + fn Show(&mut self, hwndOwner: ::HWND) -> ::HRESULT +} +); +//22307 +ENUM!{enum FDE_OVERWRITE_RESPONSE { + FDEOR_DEFAULT = 0, + FDEOR_ACCEPT = 1, + FDEOR_REFUSE = 2, +}} +ENUM!{enum FDE_SHAREVIOLATION_RESPONSE { + FDESVR_DEFAULT = 0, + FDESVR_ACCEPT = 1, + FDESVR_REFUSE = 2, +}} +ENUM!{enum FDAP { + FDAP_BOTTOM = 0, + FDAP_TOP = 1, +}} +RIDL!( +interface IFileDialogEvents(IFileDialogEventsVtbl): IUnknown(IUnknownVtbl) { + fn OnFileOk(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnFolderChanging(&mut self, pfd: *mut IFileDialog, psiFolder: *mut IShellItem) -> ::HRESULT, + fn OnFolderChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnSelectionChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnShareViolation( + &mut self, pfd: *mut IFileDialog, psi: *mut IShellItem, + pResponse: *mut FDE_SHAREVIOLATION_RESPONSE + ) -> ::HRESULT, + fn OnTypeChange(&mut self, pfd: *mut IFileDialog) -> ::HRESULT, + fn OnOverwrite( + &mut self, pfd: *mut IFileDialog, psi: *mut IShellItem, + pResponse: *mut FDE_OVERWRITE_RESPONSE + ) -> ::HRESULT +} +); +FLAGS!{enum FILEOPENDIALOGOPTIONS { + FOS_OVERWRITEPROMPT = 0x2, + FOS_STRICTFILETYPES = 0x4, + FOS_NOCHANGEDIR = 0x8, + FOS_PICKFOLDERS = 0x20, + FOS_FORCEFILESYSTEM = 0x40, + FOS_ALLNONSTORAGEITEMS = 0x80, + FOS_NOVALIDATE = 0x100, + FOS_ALLOWMULTISELECT = 0x200, + FOS_PATHMUSTEXIST = 0x800, + FOS_FILEMUSTEXIST = 0x1000, + FOS_CREATEPROMPT = 0x2000, + FOS_SHAREAWARE = 0x4000, + FOS_NOREADONLYRETURN = 0x8000, + FOS_NOTESTFILECREATE = 0x10000, + FOS_HIDEMRUPLACES = 0x20000, + FOS_HIDEPINNEDPLACES = 0x40000, + FOS_NODEREFERENCELINKS = 0x100000, + FOS_DONTADDTORECENT = 0x2000000, + FOS_FORCESHOWHIDDEN = 0x10000000, + FOS_DEFAULTNOMINIMODE = 0x20000000, + FOS_FORCEPREVIEWPANEON = 0x40000000, + FOS_SUPPORTSTREAMABLEITEMS = 0x80000000, +}} +RIDL!( +interface IFileDialog(IFileDialogVtbl): IModalWindow(IModalWindowVtbl) { + fn SetFileTypes( + &mut self, cFileTypes: ::UINT, rgFilterSpec: *const ::COMDLG_FILTERSPEC + ) -> ::HRESULT, + fn SetFileTypeIndex(&mut self, iFileType: ::UINT) -> ::HRESULT, + fn GetFileTypeIndex(&mut self, piFileType: *mut ::UINT) -> ::HRESULT, + fn Advise(&mut self, pfde: *mut IFileDialogEvents, pdwCookie: *mut ::DWORD) -> ::HRESULT, + fn Unadvise(&mut self, dwCookie: ::DWORD) -> ::HRESULT, + fn SetOptions(&mut self, fos: FILEOPENDIALOGOPTIONS) -> ::HRESULT, + fn GetOptions(&mut self, pfos: *mut FILEOPENDIALOGOPTIONS) -> ::HRESULT, + fn SetDefaultFolder(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn SetFolder(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn GetFolder(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn GetCurrentSelection(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn SetFileName(&mut self, pszName: ::LPCWSTR) -> ::HRESULT, + fn GetFileName(&mut self, pszName: *mut ::LPWSTR) -> ::HRESULT, + fn SetTitle(&mut self, pszTitle: ::LPCWSTR) -> ::HRESULT, + fn SetOkButtonLabel(&mut self, pszText: ::LPCWSTR) -> ::HRESULT, + fn SetFileNameLabel(&mut self, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn GetResult(&mut self, ppsi: *mut *mut IShellItem) -> ::HRESULT, + fn AddPlace(&mut self, psi: *mut IShellItem, fdap: FDAP) -> ::HRESULT, + fn SetDefaultExtension(&mut self, pszDefaultExtension: ::LPCWSTR) -> ::HRESULT, + fn Close(&mut self, hr: ::HRESULT) -> ::HRESULT, + fn SetClientGuid(&mut self, guid: ::REFGUID) -> ::HRESULT, + fn ClearClientData(&mut self) -> ::HRESULT, + fn SetFilter(&mut self, pFilter: *mut IShellItemFilter) -> ::HRESULT +} +); +RIDL!( +interface IFileSaveDialog(IFileSaveDialogVtbl): IFileDialog(IFileDialogVtbl) { + fn SetSaveAsItem(&mut self, psi: *mut IShellItem) -> ::HRESULT, + fn SetProperties(&mut self, pStore: *mut ::IPropertyStore) -> ::HRESULT, + fn SetCollectedProperties( + &mut self, pList: *mut ::IPropertyDescriptionList, fAppendDefault: ::BOOL + ) -> ::HRESULT, + fn GetProperties(&mut self, ppStore: *mut *mut ::IPropertyStore) -> ::HRESULT, + fn ApplyProperties( + &mut self, psi: *mut IShellItem, pStore: *mut ::IPropertyStore, hwnd: ::HWND, + pSink: *mut IFileOperationProgressSink + ) -> ::HRESULT +} +); +RIDL!( +interface IFileOpenDialog(IFileOpenDialogVtbl): IFileDialog(IFileDialogVtbl) { + fn GetResults(&mut self, ppenum: *mut *mut IShellItemArray) -> ::HRESULT, + fn GetSelectedItems(&mut self, ppsai: *mut *mut IShellItemArray) -> ::HRESULT +} +); +ENUM!{enum CDCONTROLSTATE { + CDCS_INACTIVE = 0x00000000, + CDCS_ENABLED = 0x00000001, + CDCS_VISIBLE = 0x00000002, + CDCS_ENABLEDVISIBLE = 0x00000003, +}} +RIDL!( +interface IFileDialogCustomize(IFileDialogCustomizeVtbl): IUnknown(IUnknownVtbl) { + fn EnableOpenDropDown(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddMenu(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn AddPushButton(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn AddComboBox(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddRadioButtonList(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddCheckButton( + &mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR, bChecked: ::BOOL + ) -> ::HRESULT, + fn AddEditBox(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn AddSeparator(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn AddText(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn SetControlLabel(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn GetControlState(&mut self, dwIDCtl: ::DWORD, pdwState: *mut CDCONTROLSTATE) -> ::HRESULT, + fn SetControlState(&mut self, dwIDCtl: ::DWORD, dwState: CDCONTROLSTATE) -> ::HRESULT, + fn GetEditBoxText(&mut self, dwIDCtl: ::DWORD, ppszText: *mut *mut ::WCHAR) -> ::HRESULT, + fn SetEditBoxText(&mut self, dwIDCtl: ::DWORD, pszText: ::LPCWSTR) -> ::HRESULT, + fn GetCheckButtonState(&mut self, dwIDCtl: ::DWORD, pbChecked: *mut ::BOOL) -> ::HRESULT, + fn SetCheckButtonState(&mut self, dwIDCtl: ::DWORD, bChecked: ::BOOL) -> ::HRESULT, + fn AddControlItem( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pszLabel: ::LPCWSTR + ) -> ::HRESULT, + fn RemoveControlItem(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD) -> ::HRESULT, + fn RemoveAllControlItems(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn GetControlItemState( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pdwState: *mut CDCONTROLSTATE + ) -> ::HRESULT, + fn SetControlItemState( + &mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, dwState: CDCONTROLSTATE + ) -> ::HRESULT, + fn GetSelectedControlItem(&mut self, dwIDCtl: ::DWORD, pdwIDItem: *mut ::DWORD) -> ::HRESULT, + fn SetSelectedControlItem(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD) -> ::HRESULT, + fn StartVisualGroup(&mut self, dwIDCtl: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn EndVisualGroup(&mut self) -> ::HRESULT, + fn MakeProminent(&mut self, dwIDCtl: ::DWORD) -> ::HRESULT, + fn SetControlItemText(&mut self, dwIDCtl: ::DWORD, dwIDItem: ::DWORD, pszLabel: ::LPCWSTR) -> ::HRESULT +} +); +RIDL!( +interface IFileDialogControlEvents(IFileDialogControlEventsVtbl): IUnknown(IUnknownVtbl) { + fn OnItemSelected( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD, dwIDItem: ::DWORD + ) -> ::HRESULT, + fn OnButtonClicked(&mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD) -> ::HRESULT, + fn OnCheckButtonToggled( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD, bChecked: ::BOOL + ) -> ::HRESULT, + fn OnControlActivating( + &mut self, pfdc: *mut IFileDialogCustomize, dwIDCtl: ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface IFileDialog2(IFileDialog2Vtbl): IFileDialog(IFileDialogVtbl) { + fn SetCancelButtonLabel(&mut self, pszLabel: ::LPCWSTR) -> ::HRESULT, + fn SetNavigationRoot(&mut self, psi: IShellItem) -> ::HRESULT +} +); +//27457 +pub type IShellItemFilter = ::IUnknown; // TODO diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/shtypes.rs b/third_party/cargo/vendor/winapi-0.2.8/src/shtypes.rs new file mode 100644 index 0000000..0bea4b1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/shtypes.rs @@ -0,0 +1,40 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +#[repr(C)] #[allow(missing_copy_implementations)] +pub struct SHITEMID { + pub cb: ::USHORT, + pub abID: [::BYTE; 0], +} +pub type LPSHITEMID = *mut SHITEMID; +pub type LPCSHITEMID = *const SHITEMID; +#[repr(C)] +pub struct ITEMIDLIST { + pub mkid: SHITEMID, +} +pub type ITEMIDLIST_RELATIVE = ITEMIDLIST; +pub type ITEMID_CHILD = ITEMIDLIST; +pub type ITEMIDLIST_ABSOLUTE = ITEMIDLIST; +pub type LPITEMIDLIST = *mut ITEMIDLIST; +pub type LPCITEMIDLIST = *const ITEMIDLIST; +pub type PIDLIST_ABSOLUTE = *mut ITEMIDLIST_ABSOLUTE; +pub type PCIDLIST_ABSOLUTE = *const ITEMIDLIST_ABSOLUTE; +pub type PCUIDLIST_ABSOLUTE = *const ITEMIDLIST_ABSOLUTE; +pub type PIDLIST_RELATIVE = *mut ITEMIDLIST_RELATIVE; +pub type PCIDLIST_RELATIVE = *const ITEMIDLIST_RELATIVE; +pub type PUIDLIST_RELATIVE = *mut ITEMIDLIST_RELATIVE; +pub type PCUIDLIST_RELATIVE = *const ITEMIDLIST_RELATIVE; +pub type PITEMID_CHILD = *mut ITEMID_CHILD; +pub type PCITEMID_CHILD = *const ITEMID_CHILD; +pub type PUITEMID_CHILD = *mut ITEMID_CHILD; +pub type PCUITEMID_CHILD = *const ITEMID_CHILD; +pub type PCUITEMID_CHILD_ARRAY = *const PCUITEMID_CHILD; +pub type PCUIDLIST_RELATIVE_ARRAY = *const PCUIDLIST_RELATIVE; +pub type PCIDLIST_ABSOLUTE_ARRAY = *const PCIDLIST_ABSOLUTE; +pub type PCUIDLIST_ABSOLUTE_ARRAY = *const PCUIDLIST_ABSOLUTE; +STRUCT!{struct COMDLG_FILTERSPEC { + pszName: ::LPCWSTR, + pszSpec: ::LPCWSTR, +}} +pub type KNOWNFOLDERID = ::GUID; +pub type REFKNOWNFOLDERID = *const KNOWNFOLDERID; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/spapidef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/spapidef.rs new file mode 100644 index 0000000..05861dd --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/spapidef.rs @@ -0,0 +1,48 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Windows NT Setup and Device Installer services +pub type SP_LOG_TOKEN = ::DWORDLONG; +pub type PSP_LOG_TOKEN = *mut ::DWORDLONG; +pub const LOGTOKEN_TYPE_MASK: SP_LOG_TOKEN = 3; +pub const LOGTOKEN_UNSPECIFIED: SP_LOG_TOKEN = 0; +pub const LOGTOKEN_NO_LOG: SP_LOG_TOKEN = 1; +pub const LOGTOKEN_SETUPAPI_APPLOG: SP_LOG_TOKEN = 2; +pub const LOGTOKEN_SETUPAPI_DEVLOG: SP_LOG_TOKEN = 3; +pub const TXTLOG_SETUPAPI_DEVLOG: ::DWORD = 0x00000001; +pub const TXTLOG_SETUPAPI_CMDLINE: ::DWORD = 0x00000002; +pub const TXTLOG_SETUPAPI_BITS: ::DWORD = 0x00000003; +pub const TXTLOG_ERROR: ::DWORD = 0x1; +pub const TXTLOG_WARNING: ::DWORD = 0x2; +pub const TXTLOG_SYSTEM_STATE_CHANGE: ::DWORD = 0x3; +pub const TXTLOG_SUMMARY: ::DWORD = 0x4; +pub const TXTLOG_DETAILS: ::DWORD = 0x5; +pub const TXTLOG_VERBOSE: ::DWORD = 0x6; +pub const TXTLOG_VERY_VERBOSE: ::DWORD = 0x7; +pub const TXTLOG_RESERVED_FLAGS: ::DWORD = 0x0000FFF0; +pub const TXTLOG_TIMESTAMP: ::DWORD = 0x00010000; +pub const TXTLOG_DEPTH_INCR: ::DWORD = 0x00020000; +pub const TXTLOG_DEPTH_DECR: ::DWORD = 0x00040000; +pub const TXTLOG_TAB_1: ::DWORD = 0x00080000; +pub const TXTLOG_FLUSH_FILE: ::DWORD = 0x00100000; +#[inline] #[allow(dead_code)] +pub fn TXTLOG_LEVEL(flags: ::DWORD) -> ::DWORD { + return flags & 0xf; +} +pub const TXTLOG_DEVINST: ::DWORD = 0x00000001; +pub const TXTLOG_INF: ::DWORD = 0x00000002; +pub const TXTLOG_FILEQ: ::DWORD = 0x00000004; +pub const TXTLOG_COPYFILES: ::DWORD = 0x00000008; +pub const TXTLOG_SIGVERIF: ::DWORD = 0x00000020; +pub const TXTLOG_BACKUP: ::DWORD = 0x00000080; +pub const TXTLOG_UI: ::DWORD = 0x00000100; +pub const TXTLOG_UTIL: ::DWORD = 0x00000200; +pub const TXTLOG_INFDB: ::DWORD = 0x00000400; +pub const TXTLOG_POLICY: ::DWORD = 0x00800000; +pub const TXTLOG_NEWDEV: ::DWORD = 0x01000000; +pub const TXTLOG_UMPNPMGR: ::DWORD = 0x02000000; +pub const TXTLOG_DRIVER_STORE: ::DWORD = 0x04000000; +pub const TXTLOG_SETUP: ::DWORD = 0x08000000; +pub const TXTLOG_CMI: ::DWORD = 0x10000000; +pub const TXTLOG_DEVMGR: ::DWORD = 0x20000000; +pub const TXTLOG_INSTALLER: ::DWORD = 0x40000000; +pub const TXTLOG_VENDOR: ::DWORD = 0x80000000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/sql.rs b/third_party/cargo/vendor/winapi-0.2.8/src/sql.rs new file mode 100644 index 0000000..503fa81 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/sql.rs @@ -0,0 +1,179 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub const SQL_NULL_DATA: SQLLEN = -1; +pub const SQL_DATA_AT_EXEC: SQLLEN = -2; +pub const SQL_SUCCESS: SQLRETURN = 0; +pub const SQL_SUCCESS_WITH_INFO: SQLRETURN = 1; +pub const SQL_NO_DATA: SQLRETURN = 100; +pub const SQL_PARAM_DATA_AVAILABLE: SQLRETURN = 101; +pub const SQL_ERROR: SQLRETURN = -1; +pub const SQL_INVALID_HANDLE: SQLRETURN = -2; +pub const SQL_STILL_EXECUTING: SQLRETURN = 2; +pub const SQL_NEED_DATA: SQLRETURN = 99; +pub const SQL_NTS: SQLSMALLINT = -3; +pub const SQL_MAX_MESSAGE_LENGTH: usize = 512; +pub const SQL_DATE_LEN: usize = 10; +pub const SQL_TIME_LEN: usize = 8; +pub const SQL_TIMESTAMP_LEN: usize = 19; +pub const SQL_HANDLE_ENV: SQLSMALLINT = 1; +pub const SQL_HANDLE_DBC: SQLSMALLINT = 2; +pub const SQL_HANDLE_STMT: SQLSMALLINT = 3; +pub const SQL_HANDLE_DESC: SQLSMALLINT = 4; +pub const SQL_ATTR_OUTPUT_NTS: SQLINTEGER = 10001; +pub const SQL_ATTR_AUTO_IPD: SQLINTEGER = 10001; +pub const SQL_ATTR_METADATA_ID: SQLINTEGER = 10014; +pub const SQL_ATTR_APP_ROW_DESC: SQLINTEGER = 10010; +pub const SQL_ATTR_APP_PARAM_DESC: SQLINTEGER = 10011; +pub const SQL_ATTR_IMP_ROW_DESC: SQLINTEGER = 10012; +pub const SQL_ATTR_IMP_PARAM_DESC: SQLINTEGER = 10013; +pub const SQL_ATTR_CURSOR_SCROLLABLE: SQLINTEGER = -1; +pub const SQL_ATTR_CURSOR_SENSITIVITY: SQLINTEGER = -2; + +//Null handle used in place of parent handle when allocating HENV +pub const SQL_NULL_HANDLE: SQLHANDLE = 0 as SQLHANDLE; + +//Special length/indicator values + +//Return values from functions + + +//Values of NULLABLE field in descriptor +pub const SQL_NO_NULLS: SQLSMALLINT = 0; +pub const SQL_NULLABLE: SQLSMALLINT = 1; +pub const SQL_NULLABLE_UNKNOWN: SQLSMALLINT = 2; + +//Env attribute +pub const SQL_ATTR_ODBC_VERSION: SQLINTEGER = 200; +pub const SQL_ATTR_CONNECTION_POOLING: SQLINTEGER = 201; +pub const SQL_ATTR_CP_MATCH: SQLINTEGER = 202; + +//Values for SQL_ATTR_ODBC_VERSION +pub const SQL_OV_ODBC2: SQLINTEGER = 2; +pub const SQL_OV_ODBC3: SQLINTEGER = 3; +pub const SQL_OV_ODBC3_80: SQLINTEGER = 380; + +//Connection attributes +pub const SQL_ACCESS_MODE: SQLINTEGER = 101; +pub const SQL_AUTOCOMMIT: SQLINTEGER = 102; +pub const SQL_LOGIN_TIMEOUT: SQLINTEGER = 103; +pub const SQL_OPT_TRACE: SQLINTEGER = 104; +pub const SQL_OPT_TRACEFILE: SQLINTEGER = 105; +pub const SQL_TRANSLATE_DLL: SQLINTEGER = 106; +pub const SQL_TRANSLATE_OPTION: SQLINTEGER = 107; +pub const SQL_TXN_ISOLATION: SQLINTEGER = 108; +pub const SQL_CURRENT_QUALIFIER: SQLINTEGER = 109; +pub const SQL_ODBC_CURSORS: SQLINTEGER = 110; +pub const SQL_QUIET_MODE: SQLINTEGER = 111; +pub const SQL_PACKET_SIZE: SQLINTEGER = 112; + +//Connection attributes with new names +pub const SQL_ATTR_ACCESS_MODE: SQLINTEGER = SQL_ACCESS_MODE; +pub const SQL_ATTR_AUTOCOMMIT: SQLINTEGER = SQL_AUTOCOMMIT; +pub const SQL_ATTR_CONNECTION_TIMEOUT: SQLINTEGER = 113; +pub const SQL_ATTR_CURRENT_CATALOG: SQLINTEGER = SQL_CURRENT_QUALIFIER; +pub const SQL_ATTR_DISCONNECT_BEHAVIOR: SQLINTEGER = 114; +pub const SQL_ATTR_ENLIST_IN_DTC: SQLINTEGER = 1207; +pub const SQL_ATTR_ENLIST_IN_XA: SQLINTEGER = 1208; +pub const SQL_ATTR_LOGIN_TIMEOUT: SQLINTEGER = SQL_LOGIN_TIMEOUT; +pub const SQL_ATTR_ODBC_CURSORS: SQLINTEGER = SQL_ODBC_CURSORS; +pub const SQL_ATTR_PACKET_SIZE: SQLINTEGER = SQL_PACKET_SIZE; +pub const SQL_ATTR_QUIET_MODE: SQLINTEGER = SQL_QUIET_MODE; +pub const SQL_ATTR_TRACE: SQLINTEGER = SQL_OPT_TRACE; +pub const SQL_ATTR_TRACEFILE: SQLINTEGER = SQL_OPT_TRACEFILE; +pub const SQL_ATTR_TRANSLATE_LIB: SQLINTEGER = SQL_TRANSLATE_DLL; +pub const SQL_ATTR_TRANSLATE_OPTION: SQLINTEGER = SQL_TRANSLATE_OPTION; +pub const SQL_ATTR_TXN_ISOLATION: SQLINTEGER = SQL_TXN_ISOLATION; +pub const SQL_ATTR_CONNECTION_DEAD: SQLINTEGER = 1209; + +//Flags for null-terminated string +pub const SQL_NTS: SQLSMALLINT = -3; + +//Options for SQLDriverConnect +pub const SQL_DRIVER_NOPROMPT: SQLUSMALLINT = 0; +pub const SQL_DRIVER_COMPLETE: SQLUSMALLINT = 1; +pub const SQL_DRIVER_PROMPT: SQLUSMALLINT = 2; +pub const SQL_DRIVER_COMPLETE_REQUIRED: SQLUSMALLINT = 3; + +//Whether an attribute is a pointer or not +pub const SQL_IS_POINTER: SQLINTEGER = -4; +pub const SQL_IS_UINTEGER: SQLINTEGER = -5; +pub const SQL_IS_INTEGER: SQLINTEGER = -6; +pub const SQL_IS_USMALLINT: SQLINTEGER = -7; +pub const SQL_IS_SMALLINT: SQLINTEGER = -8; + +//FreeStmt options +pub const SQL_CLOSE: SQLUSMALLINT = 0; +pub const SQL_DROP: SQLUSMALLINT = 1; +pub const SQL_UNBIND: SQLUSMALLINT = 2; +pub const SQL_RESET_PARAMS: SQLUSMALLINT = 3; + +//C datatype to SQL datatype mapping +pub const SQL_UNKNOWN_TYPE: SQLSMALLINT = 0; +pub const SQL_CHAR: SQLSMALLINT = 1; +pub const SQL_NUMERIC: SQLSMALLINT = 2; +pub const SQL_DECIMAL: SQLSMALLINT = 3; +pub const SQL_INTEGER: SQLSMALLINT = 4; +pub const SQL_SMALLINT: SQLSMALLINT = 5; +pub const SQL_FLOAT: SQLSMALLINT = 6; +pub const SQL_REAL: SQLSMALLINT = 7; +pub const SQL_DOUBLE: SQLSMALLINT = 8; +pub const SQL_DATETIME: SQLSMALLINT = 9; +pub const SQL_VARCHAR: SQLSMALLINT = 12; + +pub const SQL_TYPE_DATE: SQLSMALLINT = 91; +pub const SQL_TYPE_TIME: SQLSMALLINT = 92; +pub const SQL_TYPE_TIMESTAMP: SQLSMALLINT = 93; + +pub const SQL_DATE: SQLSMALLINT = 9; +pub const SQL_INTERVAL: SQLSMALLINT = 10; +pub const SQL_TIME: SQLSMALLINT = 10; +pub const SQL_TIMESTAMP: SQLSMALLINT = 11; +pub const SQL_LONGVARCHAR: SQLSMALLINT = -1; +pub const SQL_BINARY: SQLSMALLINT = -2; +pub const SQL_VARBINARY: SQLSMALLINT = -3; +pub const SQL_LONGVARBINARY: SQLSMALLINT = -4; +pub const SQL_BIGINT: SQLSMALLINT = -5; +pub const SQL_TINYINT: SQLSMALLINT = -6; +pub const SQL_BIT: SQLSMALLINT = -7; +pub const SQL_GUID: SQLSMALLINT = -11; + +pub const SQL_C_CHAR: SQLSMALLINT = SQL_CHAR; +pub const SQL_C_LONG: SQLSMALLINT = SQL_INTEGER; +pub const SQL_C_SHORT: SQLSMALLINT = SQL_SMALLINT; +pub const SQL_C_FLOAT: SQLSMALLINT = SQL_REAL; +pub const SQL_C_DOUBLE: SQLSMALLINT = SQL_DOUBLE; +pub const SQL_C_NUMERIC: SQLSMALLINT = SQL_NUMERIC; +pub const SQL_C_DEFAULT: SQLSMALLINT = 99; + +pub const SQL_SIGNED_OFFSET: SQLSMALLINT = -20; +pub const SQL_UNSIGNED_OFFSET: SQLSMALLINT = -22; + +pub const SQL_C_DATE: SQLSMALLINT = SQL_DATE; +pub const SQL_C_TIME: SQLSMALLINT = SQL_TIME; +pub const SQL_C_TIMESTAMP: SQLSMALLINT = SQL_TIMESTAMP; + +pub const SQL_C_TYPE_DATE: SQLSMALLINT = SQL_TYPE_DATE; +pub const SQL_C_TYPE_TIME: SQLSMALLINT = SQL_TYPE_TIME; +pub const SQL_C_TYPE_TIMESTAMP: SQLSMALLINT = SQL_TYPE_TIMESTAMP; + +pub const SQL_C_BINARY: SQLSMALLINT = SQL_BINARY; +pub const SQL_C_BIT: SQLSMALLINT = SQL_BIT; +pub const SQL_C_SBIGINT: SQLSMALLINT = SQL_BIGINT + SQL_SIGNED_OFFSET; +pub const SQL_C_UBIGINT: SQLSMALLINT = SQL_BIGINT + SQL_UNSIGNED_OFFSET; +pub const SQL_C_TINYINT: SQLSMALLINT = SQL_TINYINT; +pub const SQL_C_SLONG: SQLSMALLINT = SQL_C_LONG + SQL_SIGNED_OFFSET; +pub const SQL_C_SSHORT: SQLSMALLINT = SQL_C_SHORT + SQL_SIGNED_OFFSET; +pub const SQL_C_STINYINT: SQLSMALLINT = SQL_TINYINT + SQL_SIGNED_OFFSET; +pub const SQL_C_ULONG: SQLSMALLINT = SQL_C_LONG + SQL_UNSIGNED_OFFSET; +pub const SQL_C_USHORT: SQLSMALLINT = SQL_C_SHORT + SQL_UNSIGNED_OFFSET; +pub const SQL_C_UTINYINT: SQLSMALLINT = SQL_TINYINT + SQL_UNSIGNED_OFFSET; + +pub const SQL_C_GUID: SQLSMALLINT = SQL_GUID; + +pub const SQL_WCHAR: SQLSMALLINT = -8; +pub const SQL_WVARCHAR: SQLSMALLINT = -9; +pub const SQL_WLONGVARCHAR: SQLSMALLINT = -10; +pub const SQL_C_WCHAR: SQLSMALLINT = SQL_WCHAR; + +pub const SQL_TYPE_NULL: SQLSMALLINT = 0; + diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/sqltypes.rs b/third_party/cargo/vendor/winapi-0.2.8/src/sqltypes.rs new file mode 100644 index 0000000..a5ded3a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/sqltypes.rs @@ -0,0 +1,130 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub type SQLCHAR = ::c_uchar; +pub type SQLSCHAR = ::c_schar; +pub type SQLDATE = ::c_uchar; +pub type SQLDECIMAL = ::c_uchar; +pub type SQLDOUBLE = ::c_double; +pub type SQLFLOAT = ::c_double; +pub type SQLINTEGER = ::c_long; +pub type SQLUINTEGER = ::c_ulong; +#[cfg(target_arch = "x86_64")] +pub type SQLLEN = ::INT64; +#[cfg(target_arch = "x86_64")] +pub type SQLULEN = ::UINT64; +#[cfg(target_arch = "x86_64")] +pub type SQLSETPOSIROW = ::UINT64; +#[cfg(target_arch = "x86")] +pub type SQLLEN = SQLINTEGER; +#[cfg(target_arch = "x86")] +pub type SQLULEN = SQLUINTEGER; +#[cfg(target_arch = "x86")] +pub type SQLSETPOSIROW = SQLUSMALLINT; +pub type SQLROWCOUNT = SQLULEN; +pub type SQLROWSETSIZE = SQLULEN; +pub type SQLTRANSID = SQLULEN; +pub type SQLROWOFFSET = SQLLEN; +pub type SQLNUMERIC = ::c_uchar; +pub type SQLPOINTER = *mut ::c_void; +pub type SQLREAL = ::c_float; +pub type SQLSMALLINT = ::c_short; +pub type SQLUSMALLINT = ::c_ushort; +pub type SQLTIME = ::c_uchar; +pub type SQLTIMESTAMP = ::c_uchar; +pub type SQLVARCHAR = ::c_uchar; +pub type SQLRETURN = SQLSMALLINT; +pub type SQLHANDLE = *mut ::c_void; +pub type SQLHENV = SQLHANDLE; +pub type SQLHDBC = SQLHANDLE; +pub type SQLHSTMT = SQLHANDLE; +pub type SQLHDESC = SQLHANDLE; +//pub type UCHAR = ::c_uchar; +pub type SCHAR = ::c_schar; +//pub type SQLSCHAR = SCHAR; +pub type SDWORD = ::c_long; +pub type SWORD = ::c_short; +pub type UDWORD = ::c_ulong; +//pub type UWORD = ::c_ushort; +//#[cfg(target_arch = "x86")] +//pub type SQLUINTEGER = ::UDWORD; +pub type SLONG = ::c_long; +pub type SSHORT = ::c_short; +//pub type ULONG = ::c_ulong; +//pub type USHORT = ::c_ushort; +pub type SDOUBLE = ::c_double; +pub type LDOUBLE = ::c_double; +pub type SFLOAT = ::c_float; +pub type PTR = *mut ::c_void; +pub type HENV = *mut ::c_void; +pub type HDBC = *mut ::c_void; +pub type HSTMT = *mut ::c_void; +pub type RETCODE = ::c_short; +pub type SQLHWND = ::HWND; +STRUCT!{struct DATE_STRUCT { + year: SQLSMALLINT, + month: SQLUSMALLINT, + day: SQLUSMALLINT, +}} +pub type SQL_DATE_STRUCT = DATE_STRUCT; +STRUCT!{struct TIME_STRUCT { + hour: SQLUSMALLINT, + minute: SQLUSMALLINT, + second: SQLUSMALLINT, +}} +pub type SQL_TIME_STRUCT = TIME_STRUCT; +STRUCT!{struct TIMESTAMP_STRUCT { + year: SQLSMALLINT, + month: SQLUSMALLINT, + day: SQLUSMALLINT, + hour: SQLUSMALLINT, + minute: SQLUSMALLINT, + second: SQLUSMALLINT, + fraction: SQLUINTEGER, +}} +pub type SQL_TIMESTAMP_STRUCT = TIMESTAMP_STRUCT; +ENUM!{enum SQLINTERVAL { + SQL_IS_YEAR = 1, + SQL_IS_MONTH = 2, + SQL_IS_DAY = 3, + SQL_IS_HOUR = 4, + SQL_IS_MINUTE = 5, + SQL_IS_SECOND = 6, + SQL_IS_YEAR_TO_MONTH = 7, + SQL_IS_DAY_TO_HOUR = 8, + SQL_IS_DAY_TO_MINUTE = 9, + SQL_IS_DAY_TO_SECOND = 10, + SQL_IS_HOUR_TO_MINUTE = 11, + SQL_IS_HOUR_TO_SECOND = 12, + SQL_IS_MINUTE_TO_SECOND = 13, +}} +STRUCT!{struct SQL_YEAR_MONTH_STRUCT { + year: SQLUINTEGER, + month: SQLUINTEGER, +}} +STRUCT!{struct SQL_DAY_SECOND_STRUCT { + day: SQLUINTEGER, + hour: SQLUINTEGER, + minute: SQLUINTEGER, + second: SQLUINTEGER, + fraction: SQLUINTEGER, +}} +STRUCT!{struct SQL_INTERVAL_STRUCT { + interval_type: SQLINTERVAL, + interval_sign: SQLSMALLINT, + intval: [u32; 5], +}} +UNION!{SQL_INTERVAL_STRUCT, intval, year_month, year_month_mut, SQL_YEAR_MONTH_STRUCT} +UNION!{SQL_INTERVAL_STRUCT, intval, day_second, day_second_mut, SQL_DAY_SECOND_STRUCT} +pub type ODBCINT64 = ::__int64; +pub type SQLBIGINT = ODBCINT64; +pub type SQLUBIGINT = ::__uint64; +pub const SQL_MAX_NUMERIC_LEN: usize = 16; +STRUCT!{struct SQL_NUMERIC_STRUCT { + precision: SQLCHAR, + scale: SQLSCHAR, + sign: SQLCHAR, + val: [SQLCHAR; SQL_MAX_NUMERIC_LEN], +}} +pub type SQLGUID = ::GUID; +pub type BOOKMARK = SQLULEN; +pub type SQLWCHAR = ::wchar_t; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/sspi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/sspi.rs new file mode 100644 index 0000000..688fe70 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/sspi.rs @@ -0,0 +1,657 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Security Support Provider Interface Prototypes and structure definitions +pub type SEC_WCHAR = ::WCHAR; +pub type SEC_CHAR = ::CHAR; +pub type SECURITY_STATUS = ::LONG; +STRUCT!{struct SecHandle { + dwLower: ::ULONG_PTR, + dwUpper: ::ULONG_PTR, +}} +pub type PSecHandle = *mut SecHandle; +pub const SEC_DELETED_HANDLE: ::ULONG_PTR = 2; +pub type CredHandle = SecHandle; +pub type PCredHandle = PSecHandle; +pub type CtxtHandle = SecHandle; +pub type PCtxtHandle = PSecHandle; +pub type SECURITY_INTEGER = ::LARGE_INTEGER; +pub type PSECURITY_INTEGER = *mut ::LARGE_INTEGER; +pub type TimeStamp = SECURITY_INTEGER; +pub type PTimeStamp = *mut SECURITY_INTEGER; +STRUCT!{struct SECURITY_STRING { + Length: ::c_ushort, + MaximumLength: ::c_ushort, + Buffer: *mut ::c_ushort, +}} +pub type PSECURITY_STRING = *mut SECURITY_STRING; +STRUCT!{struct SecPkgInfoW { + fCapabilities: ::c_ulong, + wVersion: ::c_ushort, + wRPCID: ::c_ushort, + cbMaxToken: ::c_ulong, + Name: *mut SEC_WCHAR, + Comment: *mut SEC_WCHAR, +}} +pub type PSecPkgInfoW = *mut SecPkgInfoW; +STRUCT!{struct SecPkgInfoA { + fCapabilities: ::c_ulong, + wVersion: ::c_ushort, + wRPCID: ::c_ushort, + cbMaxToken: ::c_ulong, + Name: *mut SEC_CHAR, + Comment: *mut SEC_CHAR, +}} +pub type PSecPkgInfoA = *mut SecPkgInfoA; +pub const SECPKG_FLAG_INTEGRITY: ::c_ulong = 0x00000001; +pub const SECPKG_FLAG_PRIVACY: ::c_ulong = 0x00000002; +pub const SECPKG_FLAG_TOKEN_ONLY: ::c_ulong = 0x00000004; +pub const SECPKG_FLAG_DATAGRAM: ::c_ulong = 0x00000008; +pub const SECPKG_FLAG_CONNECTION: ::c_ulong = 0x00000010; +pub const SECPKG_FLAG_MULTI_REQUIRED: ::c_ulong = 0x00000020; +pub const SECPKG_FLAG_CLIENT_ONLY: ::c_ulong = 0x00000040; +pub const SECPKG_FLAG_EXTENDED_ERROR: ::c_ulong = 0x00000080; +pub const SECPKG_FLAG_IMPERSONATION: ::c_ulong = 0x00000100; +pub const SECPKG_FLAG_ACCEPT_WIN32_NAME: ::c_ulong = 0x00000200; +pub const SECPKG_FLAG_STREAM: ::c_ulong = 0x00000400; +pub const SECPKG_FLAG_NEGOTIABLE: ::c_ulong = 0x00000800; +pub const SECPKG_FLAG_GSS_COMPATIBLE: ::c_ulong = 0x00001000; +pub const SECPKG_FLAG_LOGON: ::c_ulong = 0x00002000; +pub const SECPKG_FLAG_ASCII_BUFFERS: ::c_ulong = 0x00004000; +pub const SECPKG_FLAG_FRAGMENT: ::c_ulong = 0x00008000; +pub const SECPKG_FLAG_MUTUAL_AUTH: ::c_ulong = 0x00010000; +pub const SECPKG_FLAG_DELEGATION: ::c_ulong = 0x00020000; +pub const SECPKG_FLAG_READONLY_WITH_CHECKSUM: ::c_ulong = 0x00040000; +pub const SECPKG_FLAG_RESTRICTED_TOKENS: ::c_ulong = 0x00080000; +pub const SECPKG_FLAG_NEGO_EXTENDER: ::c_ulong = 0x00100000; +pub const SECPKG_FLAG_NEGOTIABLE2: ::c_ulong = 0x00200000; +pub const SECPKG_FLAG_APPCONTAINER_PASSTHROUGH: ::c_ulong = 0x00400000; +pub const SECPKG_FLAG_APPCONTAINER_CHECKS: ::c_ulong = 0x00800000; +pub const SECPKG_ID_NONE: ::c_ulong = 0xFFFF; +pub const SECPKG_CALLFLAGS_APPCONTAINER: ::c_ulong = 0x00000001; +pub const SECPKG_CALLFLAGS_APPCONTAINER_AUTHCAPABLE: ::c_ulong = 0x00000002; +pub const SECPKG_CALLFLAGS_FORCE_SUPPLIED: ::c_ulong = 0x00000004; +STRUCT!{struct SecBuffer { + cbBuffer: ::c_ulong, + BufferType: ::c_ulong, + pvBuffer: *mut ::c_void, +}} +pub type PSecBuffer = *mut SecBuffer; +STRUCT!{struct SecBufferDesc { + ulVersion: ::c_ulong, + cBuffers: ::c_ulong, + pBuffers: PSecBuffer, +}} +pub type PSecBufferDesc = *mut SecBufferDesc; +pub const SECBUFFER_VERSION: ::c_ulong = 0; +pub const SECBUFFER_EMPTY: ::c_ulong = 0; +pub const SECBUFFER_DATA: ::c_ulong = 1; +pub const SECBUFFER_TOKEN: ::c_ulong = 2; +pub const SECBUFFER_PKG_PARAMS: ::c_ulong = 3; +pub const SECBUFFER_MISSING: ::c_ulong = 4; +pub const SECBUFFER_EXTRA: ::c_ulong = 5; +pub const SECBUFFER_STREAM_TRAILER: ::c_ulong = 6; +pub const SECBUFFER_STREAM_HEADER: ::c_ulong = 7; +pub const SECBUFFER_NEGOTIATION_INFO: ::c_ulong = 8; +pub const SECBUFFER_PADDING: ::c_ulong = 9; +pub const SECBUFFER_STREAM: ::c_ulong = 10; +pub const SECBUFFER_MECHLIST: ::c_ulong = 11; +pub const SECBUFFER_MECHLIST_SIGNATURE: ::c_ulong = 12; +pub const SECBUFFER_TARGET: ::c_ulong = 13; +pub const SECBUFFER_CHANNEL_BINDINGS: ::c_ulong = 14; +pub const SECBUFFER_CHANGE_PASS_RESPONSE: ::c_ulong = 15; +pub const SECBUFFER_TARGET_HOST: ::c_ulong = 16; +pub const SECBUFFER_ALERT: ::c_ulong = 17; +pub const SECBUFFER_APPLICATION_PROTOCOLS: ::c_ulong = 18; +pub const SECBUFFER_ATTRMASK: ::c_ulong = 0xF0000000; +pub const SECBUFFER_READONLY: ::c_ulong = 0x80000000; +pub const SECBUFFER_READONLY_WITH_CHECKSUM: ::c_ulong = 0x10000000; +pub const SECBUFFER_RESERVED: ::c_ulong = 0x60000000; +STRUCT!{struct SEC_NEGOTIATION_INFO { + Size: ::c_ulong, + NameLength: ::c_ulong, + Name: *mut SEC_WCHAR, + Reserved: *mut ::c_void, +}} +pub type PSEC_NEGOTIATION_INFO = *mut SEC_NEGOTIATION_INFO; +STRUCT!{struct SEC_CHANNEL_BINDINGS { + dwInitiatorAddrType: ::c_ulong, + cbInitiatorLength: ::c_ulong, + dwInitiatorOffset: ::c_ulong, + dwAcceptorAddrType: ::c_ulong, + cbAcceptorLength: ::c_ulong, + dwAcceptorOffset: ::c_ulong, + cbApplicationDataLength: ::c_ulong, + dwApplicationDataOffset: ::c_ulong, +}} +pub type PSEC_CHANNEL_BINDINGS = *mut SEC_CHANNEL_BINDINGS; +ENUM!{enum SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT { + SecApplicationProtocolNegotiationExt_None, + SecApplicationProtocolNegotiationExt_NPN, + SecApplicationProtocolNegotiationExt_ALPN, +}} +pub type PSEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT = *mut SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT; +STRUCT!{struct SEC_APPLICATION_PROTOCOL_LIST { + ProtoNegoExt: ::SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT, + ProtocolListSize: ::c_ushort, + ProtocolList: [::c_uchar; 0], +}} +STRUCT!{struct SEC_APPLICATION_PROTOCOLS { + ProtocolListsSize: ::c_ulong, + ProtocolLists: [SEC_APPLICATION_PROTOCOL_LIST; 0], +}} +pub type PSEC_APPLICATION_PROTOCOLS = *mut SEC_APPLICATION_PROTOCOLS; +pub const SECURITY_NATIVE_DREP: ::c_ulong = 0x00000010; +pub const SECURITY_NETWORK_DREP: ::c_ulong = 0x00000000; +pub const SECPKG_CRED_INBOUND: ::c_ulong = 0x00000001; +pub const SECPKG_CRED_OUTBOUND: ::c_ulong = 0x00000002; +pub const SECPKG_CRED_BOTH: ::c_ulong = 0x00000003; +pub const SECPKG_CRED_DEFAULT: ::c_ulong = 0x00000004; +pub const SECPKG_CRED_RESERVED: ::c_ulong = 0xF0000000; +pub const SECPKG_CRED_AUTOLOGON_RESTRICTED: ::c_ulong = 0x00000010; +pub const SECPKG_CRED_PROCESS_POLICY_ONLY: ::c_ulong = 0x00000020; +pub const ISC_REQ_DELEGATE: ::c_ulong = 0x00000001; +pub const ISC_REQ_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ISC_REQ_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ISC_REQ_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ISC_REQ_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ISC_REQ_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ISC_REQ_PROMPT_FOR_CREDS: ::c_ulong = 0x00000040; +pub const ISC_REQ_USE_SUPPLIED_CREDS: ::c_ulong = 0x00000080; +pub const ISC_REQ_ALLOCATE_MEMORY: ::c_ulong = 0x00000100; +pub const ISC_REQ_USE_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ISC_REQ_DATAGRAM: ::c_ulong = 0x00000400; +pub const ISC_REQ_CONNECTION: ::c_ulong = 0x00000800; +pub const ISC_REQ_CALL_LEVEL: ::c_ulong = 0x00001000; +pub const ISC_REQ_FRAGMENT_SUPPLIED: ::c_ulong = 0x00002000; +pub const ISC_REQ_EXTENDED_ERROR: ::c_ulong = 0x00004000; +pub const ISC_REQ_STREAM: ::c_ulong = 0x00008000; +pub const ISC_REQ_INTEGRITY: ::c_ulong = 0x00010000; +pub const ISC_REQ_IDENTIFY: ::c_ulong = 0x00020000; +pub const ISC_REQ_NULL_SESSION: ::c_ulong = 0x00040000; +pub const ISC_REQ_MANUAL_CRED_VALIDATION: ::c_ulong = 0x00080000; +pub const ISC_REQ_RESERVED1: ::c_ulong = 0x00100000; +pub const ISC_REQ_FRAGMENT_TO_FIT: ::c_ulong = 0x00200000; +pub const ISC_REQ_FORWARD_CREDENTIALS: ::c_ulong = 0x00400000; +pub const ISC_REQ_NO_INTEGRITY: ::c_ulong = 0x00800000; +pub const ISC_REQ_USE_HTTP_STYLE: ::c_ulong = 0x01000000; +pub const ISC_REQ_UNVERIFIED_TARGET_NAME: ::c_ulong = 0x20000000; +pub const ISC_REQ_CONFIDENTIALITY_ONLY: ::c_ulong = 0x40000000; +pub const ISC_RET_DELEGATE: ::c_ulong = 0x00000001; +pub const ISC_RET_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ISC_RET_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ISC_RET_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ISC_RET_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ISC_RET_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ISC_RET_USED_COLLECTED_CREDS: ::c_ulong = 0x00000040; +pub const ISC_RET_USED_SUPPLIED_CREDS: ::c_ulong = 0x00000080; +pub const ISC_RET_ALLOCATED_MEMORY: ::c_ulong = 0x00000100; +pub const ISC_RET_USED_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ISC_RET_DATAGRAM: ::c_ulong = 0x00000400; +pub const ISC_RET_CONNECTION: ::c_ulong = 0x00000800; +pub const ISC_RET_INTERMEDIATE_RETURN: ::c_ulong = 0x00001000; +pub const ISC_RET_CALL_LEVEL: ::c_ulong = 0x00002000; +pub const ISC_RET_EXTENDED_ERROR: ::c_ulong = 0x00004000; +pub const ISC_RET_STREAM: ::c_ulong = 0x00008000; +pub const ISC_RET_INTEGRITY: ::c_ulong = 0x00010000; +pub const ISC_RET_IDENTIFY: ::c_ulong = 0x00020000; +pub const ISC_RET_NULL_SESSION: ::c_ulong = 0x00040000; +pub const ISC_RET_MANUAL_CRED_VALIDATION: ::c_ulong = 0x00080000; +pub const ISC_RET_RESERVED1: ::c_ulong = 0x00100000; +pub const ISC_RET_FRAGMENT_ONLY: ::c_ulong = 0x00200000; +pub const ISC_RET_FORWARD_CREDENTIALS: ::c_ulong = 0x00400000; +pub const ISC_RET_USED_HTTP_STYLE: ::c_ulong = 0x01000000; +pub const ISC_RET_NO_ADDITIONAL_TOKEN: ::c_ulong = 0x02000000; +pub const ISC_RET_REAUTHENTICATION: ::c_ulong = 0x08000000; +pub const ISC_RET_CONFIDENTIALITY_ONLY: ::c_ulong = 0x40000000; +pub const ASC_REQ_DELEGATE: ::c_ulong = 0x00000001; +pub const ASC_REQ_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ASC_REQ_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ASC_REQ_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ASC_REQ_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ASC_REQ_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ASC_REQ_SESSION_TICKET: ::c_ulong = 0x00000040; +pub const ASC_REQ_ALLOCATE_MEMORY: ::c_ulong = 0x00000100; +pub const ASC_REQ_USE_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ASC_REQ_DATAGRAM: ::c_ulong = 0x00000400; +pub const ASC_REQ_CONNECTION: ::c_ulong = 0x00000800; +pub const ASC_REQ_CALL_LEVEL: ::c_ulong = 0x00001000; +pub const ASC_REQ_EXTENDED_ERROR: ::c_ulong = 0x00008000; +pub const ASC_REQ_STREAM: ::c_ulong = 0x00010000; +pub const ASC_REQ_INTEGRITY: ::c_ulong = 0x00020000; +pub const ASC_REQ_LICENSING: ::c_ulong = 0x00040000; +pub const ASC_REQ_IDENTIFY: ::c_ulong = 0x00080000; +pub const ASC_REQ_ALLOW_NULL_SESSION: ::c_ulong = 0x00100000; +pub const ASC_REQ_ALLOW_NON_USER_LOGONS: ::c_ulong = 0x00200000; +pub const ASC_REQ_ALLOW_CONTEXT_REPLAY: ::c_ulong = 0x00400000; +pub const ASC_REQ_FRAGMENT_TO_FIT: ::c_ulong = 0x00800000; +pub const ASC_REQ_FRAGMENT_SUPPLIED: ::c_ulong = 0x00002000; +pub const ASC_REQ_NO_TOKEN: ::c_ulong = 0x01000000; +pub const ASC_REQ_PROXY_BINDINGS: ::c_ulong = 0x04000000; +pub const ASC_REQ_ALLOW_MISSING_BINDINGS: ::c_ulong = 0x10000000; +pub const ASC_RET_DELEGATE: ::c_ulong = 0x00000001; +pub const ASC_RET_MUTUAL_AUTH: ::c_ulong = 0x00000002; +pub const ASC_RET_REPLAY_DETECT: ::c_ulong = 0x00000004; +pub const ASC_RET_SEQUENCE_DETECT: ::c_ulong = 0x00000008; +pub const ASC_RET_CONFIDENTIALITY: ::c_ulong = 0x00000010; +pub const ASC_RET_USE_SESSION_KEY: ::c_ulong = 0x00000020; +pub const ASC_RET_SESSION_TICKET: ::c_ulong = 0x00000040; +pub const ASC_RET_ALLOCATED_MEMORY: ::c_ulong = 0x00000100; +pub const ASC_RET_USED_DCE_STYLE: ::c_ulong = 0x00000200; +pub const ASC_RET_DATAGRAM: ::c_ulong = 0x00000400; +pub const ASC_RET_CONNECTION: ::c_ulong = 0x00000800; +pub const ASC_RET_CALL_LEVEL: ::c_ulong = 0x00002000; +pub const ASC_RET_THIRD_LEG_FAILED: ::c_ulong = 0x00004000; +pub const ASC_RET_EXTENDED_ERROR: ::c_ulong = 0x00008000; +pub const ASC_RET_STREAM: ::c_ulong = 0x00010000; +pub const ASC_RET_INTEGRITY: ::c_ulong = 0x00020000; +pub const ASC_RET_LICENSING: ::c_ulong = 0x00040000; +pub const ASC_RET_IDENTIFY: ::c_ulong = 0x00080000; +pub const ASC_RET_NULL_SESSION: ::c_ulong = 0x00100000; +pub const ASC_RET_ALLOW_NON_USER_LOGONS: ::c_ulong = 0x00200000; +pub const ASC_RET_ALLOW_CONTEXT_REPLAY: ::c_ulong = 0x00400000; +pub const ASC_RET_FRAGMENT_ONLY: ::c_ulong = 0x00800000; +pub const ASC_RET_NO_TOKEN: ::c_ulong = 0x01000000; +pub const ASC_RET_NO_ADDITIONAL_TOKEN: ::c_ulong = 0x02000000; +pub const SECPKG_CRED_ATTR_NAMES: ::c_ulong = 1; +pub const SECPKG_CRED_ATTR_SSI_PROVIDER: ::c_ulong = 2; +pub const SECPKG_CRED_ATTR_KDC_PROXY_SETTINGS: ::c_ulong = 3; +pub const SECPKG_CRED_ATTR_CERT: ::c_ulong = 4; +STRUCT!{struct SecPkgCredentials_NamesW { + sUserName: *mut SEC_WCHAR, +}} +pub type PSecPkgCredentials_NamesW = *mut SecPkgCredentials_NamesW; +STRUCT!{struct SecPkgCredentials_NamesA { + sUserName: *mut SEC_CHAR, +}} +pub type PSecPkgCredentials_NamesA = *mut SecPkgCredentials_NamesA; +STRUCT!{struct SecPkgCredentials_SSIProviderW { + sProviderName: *mut SEC_WCHAR, + ProviderInfoLength: ::c_ulong, + ProviderInfo: *mut ::c_char, +}} +pub type PSecPkgCredentials_SSIProviderW = *mut SecPkgCredentials_SSIProviderW; +STRUCT!{struct SecPkgCredentials_SSIProviderA { + sProviderName: *mut SEC_CHAR, + ProviderInfoLength: ::c_ulong, + ProviderInfo: *mut ::c_char, +}} +pub type PSecPkgCredentials_SSIProviderA = *mut SecPkgCredentials_SSIProviderA; +pub const KDC_PROXY_SETTINGS_V1: ::ULONG = 1; +pub const KDC_PROXY_SETTINGS_FLAGS_FORCEPROXY: ::ULONG = 0x1; +STRUCT!{struct SecPkgCredentials_KdcProxySettingsW { + Version: ::ULONG, + Flags: ::ULONG, + ProxyServerOffset: ::USHORT, + ProxyServerLength: ::USHORT, + ClientTlsCredOffset: ::USHORT, + ClientTlsCredLength: ::USHORT, +}} +pub type PSecPkgCredentials_KdcProxySettingsW = *mut SecPkgCredentials_KdcProxySettingsW; +STRUCT!{struct SecPkgCredentials_Cert { + EncodedCertSize: ::c_ulong, + EncodedCert: *mut ::c_uchar, +}} +pub type PSecPkgCredentials_Cert = *mut SecPkgCredentials_Cert; +pub const SECPKG_ATTR_SIZES: ::c_ulong = 0; +pub const SECPKG_ATTR_NAMES: ::c_ulong = 1; +pub const SECPKG_ATTR_LIFESPAN: ::c_ulong = 2; +pub const SECPKG_ATTR_DCE_INFO: ::c_ulong = 3; +pub const SECPKG_ATTR_STREAM_SIZES: ::c_ulong = 4; +pub const SECPKG_ATTR_KEY_INFO: ::c_ulong = 5; +pub const SECPKG_ATTR_AUTHORITY: ::c_ulong = 6; +pub const SECPKG_ATTR_PROTO_INFO: ::c_ulong = 7; +pub const SECPKG_ATTR_PASSWORD_EXPIRY: ::c_ulong = 8; +pub const SECPKG_ATTR_SESSION_KEY: ::c_ulong = 9; +pub const SECPKG_ATTR_PACKAGE_INFO: ::c_ulong = 10; +pub const SECPKG_ATTR_USER_FLAGS: ::c_ulong = 11; +pub const SECPKG_ATTR_NEGOTIATION_INFO: ::c_ulong = 12; +pub const SECPKG_ATTR_NATIVE_NAMES: ::c_ulong = 13; +pub const SECPKG_ATTR_FLAGS: ::c_ulong = 14; +pub const SECPKG_ATTR_USE_VALIDATED: ::c_ulong = 15; +pub const SECPKG_ATTR_CREDENTIAL_NAME: ::c_ulong = 16; +pub const SECPKG_ATTR_TARGET_INFORMATION: ::c_ulong = 17; +pub const SECPKG_ATTR_ACCESS_TOKEN: ::c_ulong = 18; +pub const SECPKG_ATTR_TARGET: ::c_ulong = 19; +pub const SECPKG_ATTR_AUTHENTICATION_ID: ::c_ulong = 20; +pub const SECPKG_ATTR_LOGOFF_TIME: ::c_ulong = 21; +pub const SECPKG_ATTR_NEGO_KEYS: ::c_ulong = 22; +pub const SECPKG_ATTR_PROMPTING_NEEDED: ::c_ulong = 24; +pub const SECPKG_ATTR_UNIQUE_BINDINGS: ::c_ulong = 25; +pub const SECPKG_ATTR_ENDPOINT_BINDINGS: ::c_ulong = 26; +pub const SECPKG_ATTR_CLIENT_SPECIFIED_TARGET: ::c_ulong = 27; +pub const SECPKG_ATTR_LAST_CLIENT_TOKEN_STATUS: ::c_ulong = 30; +pub const SECPKG_ATTR_NEGO_PKG_INFO: ::c_ulong = 31; +pub const SECPKG_ATTR_NEGO_STATUS: ::c_ulong = 32; +pub const SECPKG_ATTR_CONTEXT_DELETED: ::c_ulong = 33; +pub const SECPKG_ATTR_DTLS_MTU: ::c_ulong = 34; +pub const SECPKG_ATTR_DATAGRAM_SIZES: ::c_ulong = SECPKG_ATTR_STREAM_SIZES; +pub const SECPKG_ATTR_SUBJECT_SECURITY_ATTRIBUTES: ::c_ulong = 128; +pub const SECPKG_ATTR_APPLICATION_PROTOCOL: ::c_ulong = 35; +STRUCT!{struct SecPkgContext_SubjectAttributes { + AttributeInfo: *mut ::c_void, +}} +pub type PSecPkgContext_SubjectAttributes = *mut SecPkgContext_SubjectAttributes; +pub const SECPKG_ATTR_NEGO_INFO_FLAG_NO_KERBEROS: ::c_ulong = 0x1; +pub const SECPKG_ATTR_NEGO_INFO_FLAG_NO_NTLM: ::c_ulong = 0x2; +ENUM!{enum SECPKG_CRED_CLASS { + SecPkgCredClass_None = 0, + SecPkgCredClass_Ephemeral = 10, + SecPkgCredClass_PersistedGeneric = 20, + SecPkgCredClass_PersistedSpecific = 30, + SecPkgCredClass_Explicit = 40, +}} +pub type PSECPKG_CRED_CLASS = *mut SECPKG_CRED_CLASS; +STRUCT!{struct SecPkgContext_CredInfo { + CredClass: SECPKG_CRED_CLASS, + IsPromptingNeeded: ::c_ulong, +}} +pub type PSecPkgContext_CredInfo = *mut SecPkgContext_CredInfo; +STRUCT!{struct SecPkgContext_NegoPackageInfo { + PackageMask: ::c_ulong, +}} +pub type PSecPkgContext_NegoPackageInfo = *mut SecPkgContext_NegoPackageInfo; +STRUCT!{struct SecPkgContext_NegoStatus { + LastStatus: ::c_ulong, +}} +pub type PSecPkgContext_NegoStatus = *mut SecPkgContext_NegoStatus; +STRUCT!{struct SecPkgContext_Sizes { + cbMaxToken: ::c_ulong, + cbMaxSignature: ::c_ulong, + cbBlockSize: ::c_ulong, + cbSecurityTrailer: ::c_ulong, +}} +pub type PSecPkgContext_Sizes = *mut SecPkgContext_Sizes; +STRUCT!{struct SecPkgContext_StreamSizes { + cbHeader: ::c_ulong, + cbTrailer: ::c_ulong, + cbMaximumMessage: ::c_ulong, + cBuffers: ::c_ulong, + cbBlockSize: ::c_ulong, +}} +pub type PSecPkgContext_StreamSizes = *mut SecPkgContext_StreamSizes; +pub type SecPkgContext_DatagramSizes = SecPkgContext_StreamSizes; +pub type PSecPkgContext_DatagramSizes = PSecPkgContext_StreamSizes; +STRUCT!{struct SecPkgContext_NamesW { + sUserName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_NamesW = *mut SecPkgContext_NamesW; +ENUM!{enum SECPKG_ATTR_LCT_STATUS { + SecPkgAttrLastClientTokenYes, + SecPkgAttrLastClientTokenNo, + SecPkgAttrLastClientTokenMaybe, +}} +pub type PSECPKG_ATTR_LCT_STATUS = *mut SECPKG_ATTR_LCT_STATUS; +STRUCT!{struct SecPkgContext_LastClientTokenStatus { + LastClientTokenStatus: SECPKG_ATTR_LCT_STATUS, +}} +pub type PSecPkgContext_LastClientTokenStatus = *mut SecPkgContext_LastClientTokenStatus; +STRUCT!{struct SecPkgContext_NamesA { + sUserName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_NamesA = *mut SecPkgContext_NamesA; +STRUCT!{struct SecPkgContext_Lifespan { + tsStart: TimeStamp, + tsExpiry: TimeStamp, +}} +pub type PSecPkgContext_Lifespan = *mut SecPkgContext_Lifespan; +STRUCT!{struct SecPkgContext_DceInfo { + AuthzSvc: ::c_ulong, + pPac: *mut ::c_void, +}} +pub type PSecPkgContext_DceInfo = *mut SecPkgContext_DceInfo; +STRUCT!{struct SecPkgContext_KeyInfoA { + sSignatureAlgorithmName: *mut ::SEC_CHAR, + sEncryptAlgorithmName: *mut ::SEC_CHAR, + KeySize: ::c_ulong, + SignatureAlgorithm: ::c_ulong, + EncryptAlgorithm: ::c_ulong, +}} +pub type PSecPkgContext_KeyInfoA = *mut SecPkgContext_KeyInfoA; +STRUCT!{struct SecPkgContext_KeyInfoW { + sSignatureAlgorithmName: *mut ::SEC_WCHAR, + sEncryptAlgorithmName: *mut ::SEC_WCHAR, + KeySize: ::c_ulong, + SignatureAlgorithm: ::c_ulong, + EncryptAlgorithm: ::c_ulong, +}} +pub type PSecPkgContext_KeyInfoW = *mut SecPkgContext_KeyInfoW; +STRUCT!{struct SecPkgContext_AuthorityA { + sAuthorityName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_AuthorityA = *mut SecPkgContext_AuthorityA; +STRUCT!{struct SecPkgContext_AuthorityW { + sAuthorityName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_AuthorityW = *mut SecPkgContext_AuthorityW; +STRUCT!{struct SecPkgContext_ProtoInfoA { + sProtocolName: *mut SEC_CHAR, + majorVersion: ::c_ulong, + minorVersion: ::c_ulong, +}} +pub type PSecPkgContext_ProtoInfoA = *mut SecPkgContext_ProtoInfoA; +STRUCT!{struct SecPkgContext_ProtoInfoW { + sProtocolName: *mut SEC_WCHAR, + majorVersion: ::c_ulong, + minorVersion: ::c_ulong, +}} +pub type PSecPkgContext_ProtoInfoW = *mut SecPkgContext_ProtoInfoW; +STRUCT!{struct SecPkgContext_PasswordExpiry { + tsPasswordExpires: TimeStamp, +}} +pub type PSecPkgContext_PasswordExpiry = *mut SecPkgContext_PasswordExpiry; +STRUCT!{struct SecPkgContext_LogoffTime { + tsLogoffTime: TimeStamp, +}} +pub type PSecPkgContext_LogoffTime = *mut SecPkgContext_LogoffTime; +STRUCT!{struct SecPkgContext_SessionKey { + SessionKeyLength: ::c_ulong, + SessionKey: *mut ::c_uchar, +}} +pub type PSecPkgContext_SessionKey = *mut SecPkgContext_SessionKey; +STRUCT!{struct SecPkgContext_NegoKeys { + KeyType: ::c_ulong, + KeyLength: ::c_ushort, + KeyValue: *mut ::c_uchar, + VerifyKeyType: ::c_ulong, + VerifyKeyLength: ::c_ushort, + VerifyKeyValue: *mut ::c_uchar, +}} +pub type PSecPkgContext_NegoKeys = *mut SecPkgContext_NegoKeys; +STRUCT!{struct SecPkgContext_PackageInfoW { + PackageInfo: PSecPkgInfoW, +}} +pub type PSecPkgContext_PackageInfoW = *mut SecPkgContext_PackageInfoW; +STRUCT!{struct SecPkgContext_PackageInfoA { + PackageInfo: PSecPkgInfoA, +}} +pub type PSecPkgContext_PackageInfoA = *mut SecPkgContext_PackageInfoA; +STRUCT!{struct SecPkgContext_UserFlags { + UserFlags: ::c_ulong, +}} +pub type PSecPkgContext_UserFlags = *mut SecPkgContext_UserFlags; +STRUCT!{struct SecPkgContext_Flags { + Flags: ::c_ulong, +}} +pub type PSecPkgContext_Flags = *mut SecPkgContext_Flags; +STRUCT!{struct SecPkgContext_NegotiationInfoA { + PackageInfo: PSecPkgInfoA, + NegotiationState: ::c_ulong, +}} +pub type PSecPkgContext_NegotiationInfoA = *mut SecPkgContext_NegotiationInfoA; +STRUCT!{struct SecPkgContext_NegotiationInfoW { + PackageInfo: PSecPkgInfoW, + NegotiationState: ::c_ulong, +}} +pub type PSecPkgContext_NegotiationInfoW = *mut SecPkgContext_NegotiationInfoW; +pub const SECPKG_NEGOTIATION_COMPLETE: ::c_ulong = 0; +pub const SECPKG_NEGOTIATION_OPTIMISTIC: ::c_ulong = 1; +pub const SECPKG_NEGOTIATION_IN_PROGRESS: ::c_ulong = 2; +pub const SECPKG_NEGOTIATION_DIRECT: ::c_ulong = 3; +pub const SECPKG_NEGOTIATION_TRY_MULTICRED: ::c_ulong = 4; +STRUCT!{struct SecPkgContext_NativeNamesW { + sClientName: SEC_WCHAR, + sServerName: SEC_WCHAR, +}} +pub type PSecPkgContext_NativeNamesW = *mut SecPkgContext_NativeNamesW; +STRUCT!{struct SecPkgContext_NativeNamesA { + sClientName: SEC_CHAR, + sServerName: SEC_CHAR, +}} +pub type PSecPkgContext_NativeNamesA = *mut SecPkgContext_NativeNamesA; +STRUCT!{struct SecPkgContext_CredentialNameW { + CredentialType: ::c_ulong, + sCredentialName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_CredentialNameW = *mut SecPkgContext_CredentialNameW; +STRUCT!{struct SecPkgContext_CredentialNameA { + CredentialType: ::c_ulong, + sCredentialName: *mut SEC_CHAR, +}} +pub type PSecPkgContext_CredentialNameA = *mut SecPkgContext_CredentialNameA; +STRUCT!{struct SecPkgContext_AccessToken { + AccessToken: *mut ::c_void, +}} +pub type PSecPkgContext_AccessToken = *mut SecPkgContext_AccessToken; +STRUCT!{struct SecPkgContext_TargetInformation { + MarshalledTargetInfoLength: ::c_ulong, + MarshalledTargetInfo: *mut ::c_uchar, +}} +pub type PSecPkgContext_TargetInformation = *mut SecPkgContext_TargetInformation; +STRUCT!{struct SecPkgContext_AuthzID { + AuthzIDLength: ::c_ulong, + AuthzID: *mut ::c_char, +}} +pub type PSecPkgContext_AuthzID = *mut SecPkgContext_AuthzID; +STRUCT!{struct SecPkgContext_Target { + TargetLength: ::c_ulong, + Target: *mut ::c_char, +}} +pub type PSecPkgContext_Target = *mut SecPkgContext_Target; +STRUCT!{struct SecPkgContext_ClientSpecifiedTarget { + sTargetName: *mut SEC_WCHAR, +}} +pub type PSecPkgContext_ClientSpecifiedTarget = *mut SecPkgContext_ClientSpecifiedTarget; +STRUCT!{struct SecPkgContext_Bindings { + BindingsLength: ::c_ulong, + Bindings: *mut SEC_CHANNEL_BINDINGS, +}} +pub type PSecPkgContext_Bindings = *mut SecPkgContext_Bindings; +ENUM!{enum SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS { + SecApplicationProtocolNegotiationStatus_None, + SecApplicationProtocolNegotiationStatus_Success, + SecApplicationProtocolNegotiationStatus_SelectedClientOnly, +}} +pub type PSEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS = + *mut SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS; +pub const MAX_PROTOCOL_ID_SIZE: usize = 0xff; +STRUCT!{nodebug struct SecPkgContext_ApplicationProtocol { + ProtoNegoStatus: SEC_APPLICATION_PROTOCOL_NEGOTIATION_STATUS, + ProtoNegoExt: SEC_APPLICATION_PROTOCOL_NEGOTIATION_EXT, + ProtocolIdSize: ::c_uchar, + ProtocolId: [::c_uchar; MAX_PROTOCOL_ID_SIZE], +}} +pub type PSecPkgContext_ApplicationProtocol = *mut SecPkgContext_ApplicationProtocol; +pub type SEC_GET_KEY_FN = Option; +pub const SECPKG_CONTEXT_EXPORT_RESET_NEW: ::c_ulong = 0x00000001; +pub const SECPKG_CONTEXT_EXPORT_DELETE_OLD: ::c_ulong = 0x00000002; +pub const SECPKG_CONTEXT_EXPORT_TO_KERNEL: ::c_ulong = 0x00000004; +pub type ACQUIRE_CREDENTIALS_HANDLE_FN_W = Option SECURITY_STATUS>; +pub type ACQUIRE_CREDENTIALS_HANDLE_FN_A = Option SECURITY_STATUS>; +pub type FREE_CREDENTIALS_HANDLE_FN = Option SECURITY_STATUS>; +pub type ADD_CREDENTIALS_FN_W = Option SECURITY_STATUS>; +pub type ADD_CREDENTIALS_FN_A = Option SECURITY_STATUS>; +pub type CHANGE_PASSWORD_FN_W = Option SECURITY_STATUS>; +pub type CHANGE_PASSWORD_FN_A = Option SECURITY_STATUS>; +//1844 +ENUM!{enum SecDelegationType { + SecFull, + SecService, + SecTree, + SecDirectory, + SecObject, +}} +pub type PSecDelegationType = *mut SecDelegationType; +STRUCT!{struct SEC_WINNT_AUTH_BYTE_VECTOR { + ByteArrayOffset: ::c_ulong, + ByteArrayLength: ::c_ushort, +}} +pub type PSEC_WINNT_AUTH_BYTE_VECTOR = *mut SEC_WINNT_AUTH_BYTE_VECTOR; +STRUCT!{struct SEC_WINNT_AUTH_DATA { + CredType: ::GUID, + CredData: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_DATA = *mut SEC_WINNT_AUTH_DATA; +STRUCT!{struct SEC_WINNT_AUTH_PACKED_CREDENTIALS { + cbHeaderLength: ::c_ushort, + cbStructureLength: ::c_ushort, + AuthData: SEC_WINNT_AUTH_DATA, +}} +pub type PSEC_WINNT_AUTH_PACKED_CREDENTIALS = *mut SEC_WINNT_AUTH_PACKED_CREDENTIALS; +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_PASSWORD, 0x28bfc32f, 0x10f6, 0x4738, + 0x98, 0xd1, 0x1a, 0xc0, 0x61, 0xdf, 0x71, 0x6a); +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_CERT, 0x235f69ad, 0x73fb, 0x4dbc, + 0x82, 0x3, 0x6, 0x29, 0xe7, 0x39, 0x33, 0x9b); +STRUCT!{struct SEC_WINNT_AUTH_DATA_PASSWORD { + UnicodePassword: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_DATA_PASSWORD = *mut SEC_WINNT_AUTH_DATA_PASSWORD; +DEFINE_GUID!(SEC_WINNT_AUTH_DATA_TYPE_CSP_DATA, 0x68fd9879, 0x79c, 0x4dfe, + 0x82, 0x81, 0x57, 0x8a, 0xad, 0xc1, 0xc1, 0x0); +STRUCT!{struct SEC_WINNT_AUTH_CERTIFICATE_DATA { + cbHeaderLength: ::c_ushort, + cbStructureLength: ::c_ushort, + Certificate: SEC_WINNT_AUTH_BYTE_VECTOR, +}} +pub type PSEC_WINNT_AUTH_CERTIFICATE_DATA = *mut SEC_WINNT_AUTH_CERTIFICATE_DATA; +STRUCT!{struct SEC_WINNT_CREDUI_CONTEXT_VECTOR { + CredUIContextArrayOffset: ::ULONG, + CredUIContextCount: ::USHORT, +}} +pub type PSEC_WINNT_CREDUI_CONTEXT_VECTOR = *mut SEC_WINNT_CREDUI_CONTEXT_VECTOR; +STRUCT!{struct SEC_WINNT_AUTH_SHORT_VECTOR { + ShortArrayOffset: ::ULONG, + ShortArrayCount: ::USHORT, +}} +pub type PSEC_WINNT_AUTH_SHORT_VECTOR = *mut SEC_WINNT_AUTH_SHORT_VECTOR; +STRUCT!{struct CREDUIWIN_MARSHALED_CONTEXT { + StructureType: ::GUID, + cbHeaderLength: ::USHORT, + LogonId: ::LUID, + MarshaledDataType: ::GUID, + MarshaledDataOffset: ::ULONG, + MarshaledDataLength: ::USHORT, +}} +pub type PCREDUIWIN_MARSHALED_CONTEXT = *mut CREDUIWIN_MARSHALED_CONTEXT; +STRUCT!{struct SEC_WINNT_CREDUI_CONTEXT { + cbHeaderLength: ::USHORT, + CredUIContextHandle: ::HANDLE, + UIInfo: ::PCREDUI_INFOW, + dwAuthError: ::ULONG, + pInputAuthIdentity: PSEC_WINNT_AUTH_IDENTITY_OPAQUE, + TargetName: ::PUNICODE_STRING, +}} +pub type PSEC_WINNT_CREDUI_CONTEXT = *mut SEC_WINNT_CREDUI_CONTEXT; +pub type PSEC_WINNT_AUTH_IDENTITY_OPAQUE = ::PVOID; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/strmif.rs b/third_party/cargo/vendor/winapi-0.2.8/src/strmif.rs new file mode 100644 index 0000000..0edfe72 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/strmif.rs @@ -0,0 +1,4 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub type REFERENCE_TIME = LONGLONG; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/subauth.rs b/third_party/cargo/vendor/winapi-0.2.8/src/subauth.rs new file mode 100644 index 0000000..d84dc8c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/subauth.rs @@ -0,0 +1,198 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Types and macros for Subauthentication Packages. +STRUCT!{struct UNICODE_STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PWSTR, +}} +pub type PUNICODE_STRING = *mut UNICODE_STRING; +STRUCT!{struct STRING { + Length: ::USHORT, + MaximumLength: ::USHORT, + Buffer: ::PCHAR, +}} +pub type PSTRING = *mut STRING; +STRUCT!{struct OLD_LARGE_INTEGER { + LowPart: ::ULONG, + HighPart: ::LONG, +}} +pub type POLD_LARGE_INTEGER = *mut OLD_LARGE_INTEGER; +pub type SAM_HANDLE = ::PVOID; +pub type PSAM_HANDLE = *mut ::PVOID; +pub const USER_ACCOUNT_DISABLED: ::ULONG = 0x00000001; +pub const USER_HOME_DIRECTORY_REQUIRED: ::ULONG = 0x00000002; +pub const USER_PASSWORD_NOT_REQUIRED: ::ULONG = 0x00000004; +pub const USER_TEMP_DUPLICATE_ACCOUNT: ::ULONG = 0x00000008; +pub const USER_NORMAL_ACCOUNT: ::ULONG = 0x00000010; +pub const USER_MNS_LOGON_ACCOUNT: ::ULONG = 0x00000020; +pub const USER_INTERDOMAIN_TRUST_ACCOUNT: ::ULONG = 0x00000040; +pub const USER_WORKSTATION_TRUST_ACCOUNT: ::ULONG = 0x00000080; +pub const USER_SERVER_TRUST_ACCOUNT: ::ULONG = 0x00000100; +pub const USER_DONT_EXPIRE_PASSWORD: ::ULONG = 0x00000200; +pub const USER_ACCOUNT_AUTO_LOCKED: ::ULONG = 0x00000400; +pub const USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED: ::ULONG = 0x00000800; +pub const USER_SMARTCARD_REQUIRED: ::ULONG = 0x00001000; +pub const USER_TRUSTED_FOR_DELEGATION: ::ULONG = 0x00002000; +pub const USER_NOT_DELEGATED: ::ULONG = 0x00004000; +pub const USER_USE_DES_KEY_ONLY: ::ULONG = 0x00008000; +pub const USER_DONT_REQUIRE_PREAUTH: ::ULONG = 0x00010000; +pub const USER_PASSWORD_EXPIRED: ::ULONG = 0x00020000; +pub const USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: ::ULONG = 0x00040000; +pub const USER_NO_AUTH_DATA_REQUIRED: ::ULONG = 0x00080000; +pub const USER_PARTIAL_SECRETS_ACCOUNT: ::ULONG = 0x00100000; +pub const USER_USE_AES_KEYS: ::ULONG = 0x00200000; +pub const NEXT_FREE_ACCOUNT_CONTROL_BIT: ::ULONG = USER_USE_AES_KEYS << 1; +pub const USER_MACHINE_ACCOUNT_MASK: ::ULONG = USER_INTERDOMAIN_TRUST_ACCOUNT + | USER_WORKSTATION_TRUST_ACCOUNT | USER_SERVER_TRUST_ACCOUNT; +pub const USER_ACCOUNT_TYPE_MASK: ::ULONG = USER_TEMP_DUPLICATE_ACCOUNT | USER_NORMAL_ACCOUNT + | USER_MACHINE_ACCOUNT_MASK; +pub const USER_COMPUTED_ACCOUNT_CONTROL_BITS: ::ULONG = USER_ACCOUNT_AUTO_LOCKED +| USER_PASSWORD_EXPIRED; +pub const SAM_DAYS_PER_WEEK: ::USHORT = 7; +pub const SAM_HOURS_PER_WEEK: ::USHORT = 24 * SAM_DAYS_PER_WEEK; +pub const SAM_MINUTES_PER_WEEK: ::USHORT = 60 * SAM_HOURS_PER_WEEK; +STRUCT!{struct LOGON_HOURS { + UnitsPerWeek: ::USHORT, + LogonHours: ::PUCHAR, +}} +pub type PLOGON_HOURS = *mut LOGON_HOURS; +STRUCT!{struct SR_SECURITY_DESCRIPTOR { + Length: ::ULONG, + SecurityDescriptor: ::PUCHAR, +}} +pub type PSR_SECURITY_DESCRIPTOR = *mut SR_SECURITY_DESCRIPTOR; +STRUCT!{struct USER_ALL_INFORMATION { + LastLogon: ::LARGE_INTEGER, + LastLogoff: ::LARGE_INTEGER, + PasswordLastSet: ::LARGE_INTEGER, + AccountExpires: ::LARGE_INTEGER, + PasswordCanChange: ::LARGE_INTEGER, + PasswordMustChange: ::LARGE_INTEGER, + UserName: UNICODE_STRING, + FullName: UNICODE_STRING, + HomeDirectory: UNICODE_STRING, + HomeDirectoryDrive: UNICODE_STRING, + ScriptPath: UNICODE_STRING, + ProfilePath: UNICODE_STRING, + AdminComment: UNICODE_STRING, + WorkStations: UNICODE_STRING, + UserComment: UNICODE_STRING, + Parameters: UNICODE_STRING, + LmPassword: UNICODE_STRING, + NtPassword: UNICODE_STRING, + PrivateData: UNICODE_STRING, + SecurityDescriptor: SR_SECURITY_DESCRIPTOR, + UserId: ::ULONG, + PrimaryGroupId: ::ULONG, + UserAccountControl: ::ULONG, + WhichFields: ::ULONG, + LogonHours: LOGON_HOURS, + BadPasswordCount: ::USHORT, + LogonCount: ::USHORT, + CountryCode: ::USHORT, + CodePage: ::USHORT, + LmPasswordPresent: ::BOOLEAN, + NtPasswordPresent: ::BOOLEAN, + PasswordExpired: ::BOOLEAN, + PrivateDataSensitive: ::BOOLEAN, +}} +pub type PUSER_ALL_INFORMATION = *mut USER_ALL_INFORMATION; +pub const USER_ALL_PARAMETERS: ::ULONG = 0x00200000; +pub const CLEAR_BLOCK_LENGTH: usize = 8; +STRUCT!{struct CLEAR_BLOCK { + data: [::CHAR; CLEAR_BLOCK_LENGTH], +}} +pub type PCLEAR_BLOCK = *mut CLEAR_BLOCK; +pub const CYPHER_BLOCK_LENGTH: usize = 8; +STRUCT!{struct CYPHER_BLOCK { + data: [::CHAR; CYPHER_BLOCK_LENGTH], +}} +pub type PCYPHER_BLOCK = *mut CYPHER_BLOCK; +STRUCT!{struct LM_OWF_PASSWORD { + data: [CYPHER_BLOCK; 2], +}} +pub type PLM_OWF_PASSWORD = *mut LM_OWF_PASSWORD; +pub type LM_CHALLENGE = CLEAR_BLOCK; +pub type PLM_CHALLENGE = *mut LM_CHALLENGE; +pub type NT_OWF_PASSWORD = LM_OWF_PASSWORD; +pub type PNT_OWF_PASSWORD = *mut NT_OWF_PASSWORD; +pub type NT_CHALLENGE = LM_CHALLENGE; +pub type PNT_CHALLENGE = *mut NT_CHALLENGE; +pub const USER_SESSION_KEY_LENGTH: usize = CYPHER_BLOCK_LENGTH * 2; +STRUCT!{struct USER_SESSION_KEY { + data: [CYPHER_BLOCK; 2], +}} +pub type PUSER_SESSION_KEY = *mut USER_SESSION_KEY; +ENUM!{enum NETLOGON_LOGON_INFO_CLASS { + NetlogonInteractiveInformation = 1, + NetlogonNetworkInformation, + NetlogonServiceInformation, + NetlogonGenericInformation, + NetlogonInteractiveTransitiveInformation, + NetlogonNetworkTransitiveInformation, + NetlogonServiceTransitiveInformation, +}} +STRUCT!{struct NETLOGON_LOGON_IDENTITY_INFO { + LogonDomainName: UNICODE_STRING, + ParameterControl: ::ULONG, + LogonId: OLD_LARGE_INTEGER, + UserName: UNICODE_STRING, + Workstation: UNICODE_STRING, +}} +pub type PNETLOGON_LOGON_IDENTITY_INFO = *mut NETLOGON_LOGON_IDENTITY_INFO; +STRUCT!{struct NETLOGON_INTERACTIVE_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmOwfPassword: LM_OWF_PASSWORD, + NtOwfPassword: NT_OWF_PASSWORD, +}} +pub type PNETLOGON_INTERACTIVE_INFO = *mut NETLOGON_INTERACTIVE_INFO; +STRUCT!{struct NETLOGON_SERVICE_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmOwfPassword: LM_OWF_PASSWORD, + NtOwfPassword: NT_OWF_PASSWORD, +}} +pub type PNETLOGON_SERVICE_INFO = *mut NETLOGON_SERVICE_INFO; +STRUCT!{struct NETLOGON_NETWORK_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + LmChallenge: LM_CHALLENGE, + NtChallengeResponse: STRING, + LmChallengeResponse: STRING, +}} +pub type PNETLOGON_NETWORK_INFO = *mut NETLOGON_NETWORK_INFO; +STRUCT!{struct NETLOGON_GENERIC_INFO { + Identity: NETLOGON_LOGON_IDENTITY_INFO, + PackageName: UNICODE_STRING, + DataLength: ::ULONG, + LogonData: ::PUCHAR, +}} +pub type PNETLOGON_GENERIC_INFO = *mut NETLOGON_GENERIC_INFO; +pub const MSV1_0_PASSTHRU: ::ULONG = 0x01; +pub const MSV1_0_GUEST_LOGON: ::ULONG = 0x02; +STRUCT!{struct MSV1_0_VALIDATION_INFO { + LogoffTime: ::LARGE_INTEGER, + KickoffTime: ::LARGE_INTEGER, + LogonServer: UNICODE_STRING, + LogonDomainName: UNICODE_STRING, + SessionKey: USER_SESSION_KEY, + Authoritative: ::BOOLEAN, + UserFlags: ::ULONG, + WhichFields: ::ULONG, + UserId: ::ULONG, +}} +pub type PMSV1_0_VALIDATION_INFO = *mut MSV1_0_VALIDATION_INFO; +pub const MSV1_0_VALIDATION_LOGOFF_TIME: ::ULONG = 0x00000001; +pub const MSV1_0_VALIDATION_KICKOFF_TIME: ::ULONG = 0x00000002; +pub const MSV1_0_VALIDATION_LOGON_SERVER: ::ULONG = 0x00000004; +pub const MSV1_0_VALIDATION_LOGON_DOMAIN: ::ULONG = 0x00000008; +pub const MSV1_0_VALIDATION_SESSION_KEY: ::ULONG = 0x00000010; +pub const MSV1_0_VALIDATION_USER_FLAGS: ::ULONG = 0x00000020; +pub const MSV1_0_VALIDATION_USER_ID: ::ULONG = 0x00000040; +pub const MSV1_0_SUBAUTH_ACCOUNT_DISABLED: ::ULONG = 0x00000001; +pub const MSV1_0_SUBAUTH_PASSWORD: ::ULONG = 0x00000002; +pub const MSV1_0_SUBAUTH_WORKSTATIONS: ::ULONG = 0x00000004; +pub const MSV1_0_SUBAUTH_LOGON_HOURS: ::ULONG = 0x00000008; +pub const MSV1_0_SUBAUTH_ACCOUNT_EXPIRY: ::ULONG = 0x00000010; +pub const MSV1_0_SUBAUTH_PASSWORD_EXPIRY: ::ULONG = 0x00000020; +pub const MSV1_0_SUBAUTH_ACCOUNT_TYPE: ::ULONG = 0x00000040; +pub const MSV1_0_SUBAUTH_LOCKOUT: ::ULONG = 0x00000080; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/synchapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/synchapi.rs new file mode 100644 index 0000000..2eb9d1a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/synchapi.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-synch-l1 +pub type SRWLOCK = ::RTL_SRWLOCK; +pub type PSRWLOCK = *mut ::RTL_SRWLOCK; +pub type SYNCHRONIZATION_BARRIER = ::RTL_BARRIER; +pub type PSYNCHRONIZATION_BARRIER = ::PRTL_BARRIER; +pub type LPSYNCHRONIZATION_BARRIER = ::PRTL_BARRIER; +pub type PINIT_ONCE_FN = Option ::BOOL>; +pub type PTIMERAPCROUTINE = Option; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/sysinfoapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/sysinfoapi.rs new file mode 100644 index 0000000..95c38c6 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/sysinfoapi.rs @@ -0,0 +1,46 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-sysinfo-l1. +STRUCT!{struct SYSTEM_INFO { + wProcessorArchitecture: ::WORD, + wReserved: ::WORD, + dwPageSize: ::DWORD, + lpMinimumApplicationAddress: ::LPVOID, + lpMaximumApplicationAddress: ::LPVOID, + dwActiveProcessorMask: ::DWORD_PTR, + dwNumberOfProcessors: ::DWORD, + dwProcessorType: ::DWORD, + dwAllocationGranularity: ::DWORD, + wProcessorLevel: ::WORD, + wProcessorRevision: ::WORD, +}} +UNION!(SYSTEM_INFO, wProcessorArchitecture, dwOemId, dwOemId_mut, ::DWORD); +pub type LPSYSTEM_INFO = *mut SYSTEM_INFO; +STRUCT!{struct MEMORYSTATUSEX { + dwLength: ::DWORD, + dwMemoryLoad: ::DWORD, + ullTotalPhys: ::DWORDLONG, + ullAvailPhys: ::DWORDLONG, + ullTotalPageFile: ::DWORDLONG, + ullAvailPageFile: ::DWORDLONG, + ullTotalVirtual: ::DWORDLONG, + ullAvailVirtual: ::DWORDLONG, + ullAvailExtendedVirtual: ::DWORDLONG, +}} +pub type LPMEMORYSTATUSEX = *mut MEMORYSTATUSEX; +ENUM!{enum COMPUTER_NAME_FORMAT { + ComputerNameNetBIOS, + ComputerNameDnsHostname, + ComputerNameDnsDomain, + ComputerNameDnsFullyQualified, + ComputerNamePhysicalNetBIOS, + ComputerNamePhysicalDnsHostname, + ComputerNamePhysicalDnsDomain, + ComputerNamePhysicalDnsFullyQualified, + ComputerNameMax, +}} +pub type INIT_ONCE = ::RTL_RUN_ONCE; +pub type PINIT_ONCE = ::PRTL_RUN_ONCE; +pub type LPINIT_ONCE = ::PRTL_RUN_ONCE; +pub type CONDITION_VARIABLE = ::RTL_CONDITION_VARIABLE; +pub type PCONDITION_VARIABLE = *mut CONDITION_VARIABLE; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/threadpoolapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/threadpoolapi.rs new file mode 100644 index 0000000..ec21aa0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/threadpoolapi.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-threadpool-l1. +pub type PTP_WIN32_IO_CALLBACK = Option; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/timezoneapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/timezoneapi.rs new file mode 100644 index 0000000..3c84b20 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/timezoneapi.rs @@ -0,0 +1,27 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! ApiSet Contract for api-ms-win-core-timezone-l1 +pub const TIME_ZONE_ID_INVALID: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct TIME_ZONE_INFORMATION { + Bias: ::LONG, + StandardName: [::WCHAR; 32], + StandardDate: ::SYSTEMTIME, + StandardBias: ::LONG, + DaylightName: [::WCHAR; 32], + DaylightDate: ::SYSTEMTIME, + DaylightBias: ::LONG, +}} +pub type PTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION; +pub type LPTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION; +STRUCT!{nodebug struct DYNAMIC_TIME_ZONE_INFORMATION { + Bias: ::LONG, + StandardName: [::WCHAR; 32], + StandardDate: ::SYSTEMTIME, + StandardBias: ::LONG, + DaylightName: [::WCHAR; 32], + DaylightDate: ::SYSTEMTIME, + DaylightBias: ::LONG, + TimeZoneKeyName: [::WCHAR; 128], + DynamicDaylightTimeDisabled: ::BOOLEAN, +}} +pub type PDYNAMIC_TIME_ZONE_INFORMATION = *mut DYNAMIC_TIME_ZONE_INFORMATION; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/tlhelp32.rs b/third_party/cargo/vendor/winapi-0.2.8/src/tlhelp32.rs new file mode 100644 index 0000000..2e809b2 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/tlhelp32.rs @@ -0,0 +1,104 @@ +// Copyright © 2015, Gigih Aji Ibrahim +// Licensed under the MIT License +pub const MAX_MODULE_NAME32: usize = 255; +pub const TH32CS_SNAPHEAPLIST: ::DWORD = 0x00000001; +pub const TH32CS_SNAPPROCESS: ::DWORD = 0x00000002; +pub const TH32CS_SNAPTHREAD: ::DWORD = 0x00000004; +pub const TH32CS_SNAPMODULE: ::DWORD = 0x00000008; +pub const TH32CS_SNAPMODULE32: ::DWORD = 0x00000010; +pub const TH32CS_SNAPALL: ::DWORD = + (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE); +pub const TH32CS_INHERIT: ::DWORD = 0x80000000; +STRUCT!{struct HEAPLIST32 { + dwSize: ::SIZE_T, + th32ProcessID: ::DWORD, + th32HeapID: :: ULONG_PTR, + dwFlags: ::DWORD, +}} +pub type PHEAPLIST32 = *mut HEAPLIST32; +pub type LPHEAPLIST32 = *mut HEAPLIST32; +pub const HF32_DEFAULT: ::DWORD = 1; +pub const HF32_SHARED: ::DWORD = 2; +STRUCT!{struct HEAPENTRY32 { + dwSize: ::SIZE_T, + hHandle: ::HANDLE, + dwAddress: ::ULONG_PTR, + dwBlockSize: ::SIZE_T, + dwFlags: ::DWORD, + dwLockCount: ::DWORD, + dwResvd: ::DWORD, + th32ProcessID: ::DWORD, + th32HeapID: ::ULONG_PTR, +}} +pub type PHEAPENTRY32 = *mut HEAPENTRY32; +pub type LPHEAPENTRY32 = *mut HEAPENTRY32; +pub const LF32_FIXED: ::DWORD = 0x00000001; +pub const LF32_FREE: ::DWORD = 0x00000002; +pub const LF32_MOVEABLE: ::DWORD = 0x00000004; +STRUCT!{nodebug struct PROCESSENTRY32W { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ProcessID: ::DWORD, + th32DefaultHeapID: ::ULONG_PTR, + th32ModuleID: ::DWORD, + cntThreads: ::DWORD, + th32ParentProcessID: ::DWORD, + pcPriClassBase: ::LONG, + dwFlags: ::DWORD, + szExeFile: [::WCHAR; ::MAX_PATH], +}} +pub type PPROCESSENTRY32W = *mut PROCESSENTRY32W; +pub type LPPROCESSENTRY32W = *mut PROCESSENTRY32W; +STRUCT!{nodebug struct PROCESSENTRY32 { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ProcessID: ::DWORD, + th32DefaultHeapID: ::ULONG_PTR, + th32ModuleID: ::DWORD, + cntThreads: ::DWORD, + th32ParentProcessID: ::DWORD, + pcPriClassBase: ::LONG, + dwFlags: ::DWORD, + szExeFile: [::CHAR; ::MAX_PATH], +}} +pub type PPROCESSENTRY32 = *mut PROCESSENTRY32; +pub type LPPROCESSENTRY32 = *mut PROCESSENTRY32; +STRUCT!{struct THREADENTRY32 { + dwSize: ::DWORD, + cntUsage: ::DWORD, + th32ThreadID: ::DWORD, + th32OwnerProcessID: ::DWORD, + tpBasePri: ::LONG, + tpDeltaPri: ::LONG, + dwFlags: ::DWORD, +}} +pub type PTHREADENTRY32 = *mut THREADENTRY32; +pub type LPTHREADENTRY32 = *mut THREADENTRY32; +STRUCT!{nodebug struct MODULEENTRY32W { + dwSize: ::DWORD, + th32ModuleID: ::DWORD, + th32ProcessID: ::DWORD, + GlblcntUsage: ::DWORD, + ProccntUsage: ::DWORD, + modBaseAddr: *mut ::BYTE, + modBaseSize: ::DWORD, + hModule: ::HMODULE, + szModule: [::WCHAR; ::MAX_MODULE_NAME32 + 1], + szExePath: [::WCHAR; ::MAX_PATH], +}} +pub type PMODULEENTRY32W = *mut MODULEENTRY32W; +pub type LPMODULEENTRY32W = *mut MODULEENTRY32W; +STRUCT!{nodebug struct MODULEENTRY32 { + dwSize: ::DWORD, + th32ModuleID: ::DWORD, + th32ProcessID: ::DWORD, + GlblcntUsage: ::DWORD, + ProccntUsage: ::DWORD, + modBaseAddr: *mut ::BYTE, + modBaseSize: ::DWORD, + hModule: ::HMODULE, + szModule: [::CHAR; ::MAX_MODULE_NAME32 + 1], + szExePath: [::CHAR; ::MAX_PATH], +}} +pub type PMODULEENTRY32 = *mut MODULEENTRY32; +pub type LPMODULEENTRY32 = *mut MODULEENTRY32; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/unknwnbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/unknwnbase.rs new file mode 100644 index 0000000..2112561 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/unknwnbase.rs @@ -0,0 +1,29 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! this ALWAYS GENERATED file contains the definitions for the interfaces +RIDL!( +interface IUnknown(IUnknownVtbl) { + fn QueryInterface(&mut self, riid: ::REFIID, ppvObject: *mut *mut ::c_void) -> ::HRESULT, + fn AddRef(&mut self) -> ::ULONG, + fn Release(&mut self) -> ::ULONG +} +); +pub type LPUNKNOWN = *mut IUnknown; +RIDL!( +interface AsyncIUnknown(AsyncIUnknownVtbl): IUnknown(IUnknownVtbl) { + fn Begin_QueryInterface(&mut self, riid: ::REFIID) -> ::HRESULT, + fn Finish_QueryInterface(&mut self, ppvObject: *mut *mut ::c_void) -> ::HRESULT, + fn Begin_AddRef(&mut self) -> ::HRESULT, + fn Finish_AddRef(&mut self) -> ::ULONG, + fn Begin_Release(&mut self) -> ::HRESULT, + fn Finish_Release(&mut self) -> ::ULONG +} +); +RIDL!( +interface IClassFactory(IClassFactoryVtbl): IUnknown(IUnknownVtbl) { + fn CreateInstance( + &mut self, pUnkOuter: *mut IUnknown, riid: ::REFIID, ppvObject: *mut *mut ::c_void + ) -> ::HRESULT, + fn LockServer(&mut self, fLock: ::BOOL) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/urlhist.rs b/third_party/cargo/vendor/winapi-0.2.8/src/urlhist.rs new file mode 100644 index 0000000..b6fc2db --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/urlhist.rs @@ -0,0 +1,56 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Url History Interfaces +pub const STATURL_QUERYFLAG_ISCACHED: ::DWORD = 0x00010000; +pub const STATURL_QUERYFLAG_NOURL: ::DWORD = 0x00020000; +pub const STATURL_QUERYFLAG_NOTITLE: ::DWORD = 0x00040000; +pub const STATURL_QUERYFLAG_TOPLEVEL: ::DWORD = 0x00080000; +pub const STATURLFLAG_ISCACHED: ::DWORD = 0x00000001; +pub const STATURLFLAG_ISTOPLEVEL: ::DWORD = 0x00000002; +ENUM!{enum ADDURL_FLAG { + ADDURL_FIRST = 0, + ADDURL_ADDTOHISTORYANDCACHE = 0, + ADDURL_ADDTOCACHE = 1, + ADDURL_Max = 2147483647, +}} +pub type LPENUMSTATURL = *mut IEnumSTATURL; +STRUCT!{struct STATURL { + cbSize: ::DWORD, + pwcsUrl: ::LPWSTR, + pwcsTitle: ::LPWSTR, + ftLastVisited: ::FILETIME, + ftLastUpdated: ::FILETIME, + ftExpires: ::FILETIME, + dwFlags: ::DWORD, +}} +pub type LPSTATURL = *mut STATURL; +RIDL!{interface IEnumSTATURL(IEnumSTATURLVtbl): IUnknown(IUnknownVtbl) { + fn Next(&mut self, celt: ::ULONG, rgelt: LPSTATURL, pceltFetched: *mut ::ULONG) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppenum: *mut *mut ::IEnumSTATURL) -> ::HRESULT, + fn SetFilter(&mut self, poszFilter: ::LPCOLESTR, dwFlags: ::DWORD) -> ::HRESULT +}} +pub type LPURLHISTORYSTG = *mut IUrlHistoryStg; +RIDL!{interface IUrlHistoryStg(IUrlHistoryStgVtbl): IUnknown(IUnknownVtbl) { + fn AddUrl(&mut self, pocsUrl: ::LPCOLESTR) -> ::HRESULT, + fn DeleteUrl(&mut self, pocsUrl: ::LPCOLESTR, dwFlags: ::DWORD) -> ::HRESULT, + fn QueryUrl( + &mut self, pocsUrl: ::LPCOLESTR, dwFlags: ::DWORD, lpSTATURL: LPSTATURL + ) -> ::HRESULT, + fn BindToObject( + &mut self, pocsUrl: ::LPCOLESTR, riid: ::REFIID, ppvOut: *mut *mut ::c_void + ) -> ::HRESULT, + fn EnumUrls(&mut self, ppEnum: *mut *mut ::IEnumSTATURL) -> ::HRESULT +}} +pub type LPURLHISTORYSTG2 = *mut IUrlHistoryStg2; +RIDL!{interface IUrlHistoryStg2(IUrlHistoryStg2Vtbl): IUrlHistoryStg(IUrlHistoryStgVtbl) { + fn AddUrlAndNotify( + &mut self, pocsUrl: ::LPCOLESTR, pocsTitle: ::LPCOLESTR, dwFlags: ::DWORD, + fWriteHistory: ::BOOL, poctNotify: *mut ::IOleCommandTarget, punkISFolder: *mut ::IUnknown + ) -> ::HRESULT, + fn ClearHistory(&mut self) -> ::HRESULT +}} +pub type LPURLHISTORYNOTIFY = *mut IUrlHistoryNotify; +RIDL!{interface IUrlHistoryNotify(IUrlHistoryNotifyVtbl): + IOleCommandTarget(IOleCommandTargetVtbl) {}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/urlmon.rs b/third_party/cargo/vendor/winapi-0.2.8/src/urlmon.rs new file mode 100644 index 0000000..e0a5e93 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/urlmon.rs @@ -0,0 +1,6 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of Urlmon.h +// FIXME: Implement these interfaces +#[repr(C)] #[derive(Clone, Copy, Debug)] +pub struct IInternetSecurityManager; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/usb.rs b/third_party/cargo/vendor/winapi-0.2.8/src/usb.rs new file mode 100644 index 0000000..5a5904e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/usb.rs @@ -0,0 +1,18 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License +//! USB Definitions. +ENUM!{enum USBD_PIPE_TYPE { + UsbdPipeTypeControl, + UsbdPipeTypeIsochronous, + UsbdPipeTypeBulk, + UsbdPipeTypeInterrupt, +}} + +pub type USBD_STATUS = ::LONG; + +STRUCT!{struct USBD_ISO_PACKET_DESCRIPTOR { + Offset: ::ULONG, + Length: ::ULONG, + Status: ::USBD_STATUS, +}} +pub type PUSBD_ISO_PACKET_DESCRIPTOR = *mut USBD_ISO_PACKET_DESCRIPTOR; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/usbspec.rs b/third_party/cargo/vendor/winapi-0.2.8/src/usbspec.rs new file mode 100644 index 0000000..6b9605b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/usbspec.rs @@ -0,0 +1,41 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License +//! USB Spec Definitions. +ENUM!{enum USB_DEVICE_SPEED { + UsbLowSpeed = 0, + UsbFullSpeed, + UsbHighSpeed, + UsbSuperSpeed, +}} +ENUM!{enum USB_DEVICE_TYPE { + Usb11Device = 0, + Usb20Device, +}} +STRUCT!{struct BM_REQUEST_TYPE { + _BM: ::UCHAR, + B: ::UCHAR, +}} +BITFIELD!{BM_REQUEST_TYPE _BM: ::UINT8 [ + Recipient set_Recipient[0..2], + Reserved set_Reserved[2..5], + Type set_Type[5..7], + Dir set_Dir[7..8], +]} +pub type PBM_REQUEST_TYPE = *mut BM_REQUEST_TYPE; + +STRUCT!{#[repr(packed)] struct USB_CONFIGURATION_DESCRIPTOR { + bLength: ::UCHAR, + bDescriptorType: ::UCHAR, + wTotalLength: ::USHORT, + bNumInterfaces: ::UCHAR, + bConfigurationValue: ::UCHAR, + iConfiguration: ::UCHAR, + bmAttributes: ::UCHAR, + MaxPower: ::UCHAR, +}} +pub type PUSB_CONFIGURATION_DESCRIPTOR = *mut USB_CONFIGURATION_DESCRIPTOR; +#[test] +fn test_USB_CONFIGURATION_DESCRIPTOR_size() { + use std::mem::size_of; + assert_eq!(size_of::(), 9) +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/usp10.rs b/third_party/cargo/vendor/winapi-0.2.8/src/usp10.rs new file mode 100644 index 0000000..6c7b42b --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/usp10.rs @@ -0,0 +1,201 @@ +// Copyright © 2015, Jordan Miner +// Licensed under the MIT License +//! Uniscribe structure declarations and constant definitions +pub const SCRIPT_UNDEFINED: ::WORD = 0; +pub const USP_E_SCRIPT_NOT_IN_FONT: ::HRESULT = MAKE_HRESULT!( + ::SEVERITY_ERROR, ::FACILITY_ITF, 0x200 +); +DECLARE_HANDLE!(SCRIPT_CACHE, SCRIPT_CACHE__); +STRUCT!{struct SCRIPT_CONTROL { + bit_fields: ::DWORD, +}} +BITFIELD!(SCRIPT_CONTROL bit_fields: ::DWORD [ + uDefaultLanguage set_uDefaultLanguage[0..16], + fContextDigits set_fContextDigits[16..17], + fInvertPreBoundDir set_fInvertPreBoundDir[17..18], + fInvertPostBoundDir set_fInvertPostBoundDir[18..19], + fLinkStringBefore set_fLinkStringBefore[19..20], + fLinkStringAfter set_fLinkStringAfter[20..21], + fNeutralOverride set_fNeutralOverride[21..22], + fNumericOverride set_fNumericOverride[22..23], + fLegacyBidiClass set_fLegacyBidiClass[23..24], + fMergeNeutralItems set_fMergeNeutralItems[24..25], + fReserved set_fReserved[25..32], +]); +STRUCT!{struct SCRIPT_STATE { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_STATE bit_fields: ::WORD [ + uBidiLevel set_uBidiLevel[0..5], + fOverrideDirection set_fOverrideDirection[5..6], + fInhibitSymSwap set_fInhibitSymSwap[6..7], + fCharShape set_fCharShape[7..8], + fDigitSubstitute set_fDigitSubstitute[8..9], + fInhibitLigate set_fInhibitLigate[9..10], + fDisplayZWG set_fDisplayZWG[10..11], + fArabicNumContext set_fArabicNumContext[11..12], + fGcpClusters set_fGcpClusters[12..13], + fReserved set_fReserved[13..14], + fEngineReserved set_fEngineReserved[14..16], +]); +STRUCT!{struct SCRIPT_ANALYSIS { + bit_fields: ::WORD, + s: SCRIPT_STATE, +}} +BITFIELD!(SCRIPT_ANALYSIS bit_fields: ::WORD [ + eScript set_eScript[0..10], + fRTL set_fRTL[10..11], + fLayoutRTL set_fLayoutRTL[11..12], + fLinkBefore set_fLinkBefore[12..13], + fLinkAfter set_fLinkAfter[13..14], + fLogicalOrder set_fLogicalOrder[14..15], + fNoGlyphIndex set_fNoGlyphIndex[15..16], +]); +STRUCT!{struct SCRIPT_ITEM { + iCharPos: ::c_int, + a: SCRIPT_ANALYSIS, +}} +//490 +pub const SCRIPT_JUSTIFY_NONE: ::WORD = 0; +pub const SCRIPT_JUSTIFY_ARABIC_BLANK: ::WORD = 1; +pub const SCRIPT_JUSTIFY_CHARACTER: ::WORD = 2; +pub const SCRIPT_JUSTIFY_RESERVED1: ::WORD = 3; +pub const SCRIPT_JUSTIFY_BLANK: ::WORD = 4; +pub const SCRIPT_JUSTIFY_RESERVED2: ::WORD = 5; +pub const SCRIPT_JUSTIFY_RESERVED3: ::WORD = 6; +pub const SCRIPT_JUSTIFY_ARABIC_NORMAL: ::WORD = 7; +pub const SCRIPT_JUSTIFY_ARABIC_KASHIDA: ::WORD = 8; +pub const SCRIPT_JUSTIFY_ARABIC_ALEF: ::WORD = 9; +pub const SCRIPT_JUSTIFY_ARABIC_HA: ::WORD = 10; +pub const SCRIPT_JUSTIFY_ARABIC_RA: ::WORD = 11; +pub const SCRIPT_JUSTIFY_ARABIC_BA: ::WORD = 12; +pub const SCRIPT_JUSTIFY_ARABIC_BARA: ::WORD = 13; +pub const SCRIPT_JUSTIFY_ARABIC_SEEN: ::WORD = 14; +pub const SCRIPT_JUSTIFY_ARABIC_SEEN_M: ::WORD = 15; +STRUCT!{struct SCRIPT_VISATTR { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_VISATTR bit_fields: ::WORD [ + uJustification set_uJustification[0..4], + fClusterStart set_fClusterStart[4..5], + fDiacritic set_fDiacritic[5..6], + fZeroWidth set_fZeroWidth[6..7], + fReserved set_fReserved[7..8], + fShapeReserved set_fShapeReserved[8..16], +]); +STRUCT!{struct GOFFSET { + du: ::LONG, + dv: ::LONG, +}} +STRUCT!{struct SCRIPT_LOGATTR { + bit_fields: ::BYTE, +}} +BITFIELD!(SCRIPT_LOGATTR bit_fields: ::BYTE [ + fSoftBreak set_fSoftBreak[0..1], + fWhiteSpace set_fWhiteSpace[1..2], + fCharStop set_fCharStop[2..3], + fWordStop set_fWordStop[3..4], + fInvalid set_fInvalid[4..5], + fReserved set_fReserved[5..8], +]); +pub const SGCM_RTL: ::DWORD = 0x00000001; +STRUCT!{struct SCRIPT_PROPERTIES { + bit_fields1: ::DWORD, + bit_fields2: ::DWORD, +}} +BITFIELD!(SCRIPT_PROPERTIES bit_fields1: ::DWORD [ + langid set_langid[0..16], + fNumeric set_fNumeric[16..17], + fComplex set_fComplex[17..18], + fNeedsWordBreaking set_fNeedsWordBreaking[18..19], + fNeedsCaretInfo set_fNeedsCaretInfo[19..20], + bCharSet set_bCharSet[20..28], + fControl set_fControl[28..29], + fPrivateUseArea set_fPrivateUseArea[29..30], + fNeedsCharacterJustify set_fNeedsCharacterJustify[30..31], + fInvalidGlyph set_fInvalidGlyph[31..32], +]); +BITFIELD!(SCRIPT_PROPERTIES bit_fields2: ::DWORD [ + fInvalidLogAttr set_fInvalidLogAttr[0..1], + fCDM set_fCDM[1..2], + fAmbiguousCharSet set_fAmbiguousCharSet[2..3], + fClusterSizeVaries set_fClusterSizeVaries[3..4], + fRejectInvalid set_fRejectInvalid[4..5], +]); +STRUCT!{struct SCRIPT_FONTPROPERTIES { + cBytes: ::c_int, + wgBlank: ::WORD, + wgDefault: ::WORD, + wgInvalid: ::WORD, + wgKashida: ::WORD, + iKashidaWidth: ::c_int, +}} +//1440 +pub const SSA_PASSWORD: ::DWORD = 0x00000001; +pub const SSA_TAB: ::DWORD = 0x00000002; +pub const SSA_CLIP: ::DWORD = 0x00000004; +pub const SSA_FIT: ::DWORD = 0x00000008; +pub const SSA_DZWG: ::DWORD = 0x00000010; +pub const SSA_FALLBACK: ::DWORD = 0x00000020; +pub const SSA_BREAK: ::DWORD = 0x00000040; +pub const SSA_GLYPHS: ::DWORD = 0x00000080; +pub const SSA_RTL: ::DWORD = 0x00000100; +pub const SSA_GCP: ::DWORD = 0x00000200; +pub const SSA_HOTKEY: ::DWORD = 0x00000400; +pub const SSA_METAFILE: ::DWORD = 0x00000800; +pub const SSA_LINK: ::DWORD = 0x00001000; +pub const SSA_HIDEHOTKEY: ::DWORD = 0x00002000; +pub const SSA_HOTKEYONLY: ::DWORD = 0x00002400; +pub const SSA_FULLMEASURE: ::DWORD = 0x04000000; +pub const SSA_LPKANSIFALLBACK: ::DWORD = 0x08000000; +pub const SSA_PIDX: ::DWORD = 0x10000000; +pub const SSA_LAYOUTRTL: ::DWORD = 0x20000000; +pub const SSA_DONTGLYPH: ::DWORD = 0x40000000; +pub const SSA_NOKASHIDA: ::DWORD = 0x80000000; +STRUCT!{struct SCRIPT_TABDEF { + cTabStops: ::c_int, + iScale: ::c_int, + pTabStops: *mut ::c_int, + iTabOrigin: ::c_int, +}} +DECLARE_HANDLE!(SCRIPT_STRING_ANALYSIS, SCRIPT_STRING_ANALYSIS__); +pub const SIC_COMPLEX: ::DWORD = 1; +pub const SIC_ASCIIDIGIT: ::DWORD = 2; +pub const SIC_NEUTRAL: ::DWORD = 4; +STRUCT!{struct SCRIPT_DIGITSUBSTITUTE { + bit_fields1: ::DWORD, + bit_fields2: ::DWORD, + dwReserved: ::DWORD, +}} +BITFIELD!(SCRIPT_DIGITSUBSTITUTE bit_fields1: ::DWORD [ + NationalDigitLanguage set_NationalDigitLanguage[0..16], + TraditionalDigitLanguage set_TraditionalDigitLanguage[16..32], +]); +BITFIELD!(SCRIPT_DIGITSUBSTITUTE bit_fields2: ::DWORD [ + DigitSubstitute set_DigitSubstitute[0..8], +]); +pub const SCRIPT_DIGITSUBSTITUTE_CONTEXT: ::BYTE = 0; +pub const SCRIPT_DIGITSUBSTITUTE_NONE: ::BYTE = 1; +pub const SCRIPT_DIGITSUBSTITUTE_NATIONAL: ::BYTE = 2; +pub const SCRIPT_DIGITSUBSTITUTE_TRADITIONAL: ::BYTE = 3; +pub type OPENTYPE_TAG = ::ULONG; +pub const SCRIPT_TAG_UNKNOWN: OPENTYPE_TAG = 0x00000000; +STRUCT!{struct OPENTYPE_FEATURE_RECORD { + tagFeature: OPENTYPE_TAG, + lParameter: ::LONG, +}} +STRUCT!{struct TEXTRANGE_PROPERTIES { + potfRecords: *mut OPENTYPE_FEATURE_RECORD, + cotfRecords: ::c_int, +}} +STRUCT!{struct SCRIPT_CHARPROP { + bit_fields: ::WORD, +}} +BITFIELD!(SCRIPT_CHARPROP bit_fields: ::WORD [ + fCanGlyphAlone set_fCanGlyphAlone[0..1], + reserved set_reserved[1..16], +]); +STRUCT!{struct SCRIPT_GLYPHPROP { + sva: SCRIPT_VISATTR, + reserved: ::WORD, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/vadefs.rs b/third_party/cargo/vendor/winapi-0.2.8/src/vadefs.rs new file mode 100644 index 0000000..c482026 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/vadefs.rs @@ -0,0 +1,7 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Definitions of macro helpers used by . This is the topmost header in the CRT header +//! lattice, and is always the first CRT header to be included, explicitly or implicitly. +//! Therefore, this header also has several definitions that are used throughout the CRT. +//39 +pub type va_list = *mut ::c_char; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/vsbackup.rs b/third_party/cargo/vendor/winapi-0.2.8/src/vsbackup.rs new file mode 100644 index 0000000..5f6036a --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/vsbackup.rs @@ -0,0 +1,303 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License +//! VSS backup interfaces +DEFINE_GUID!(IID_IVssExamineWriterMetadata, 0x902fcf7f, 0xb7fd, 0x42f8, + 0x81, 0xf1, 0xb2, 0xe4, 0x00, 0xb1, 0xe5, 0xbd); +DEFINE_GUID!(IID_IVssExamineWriterMetadataEx, 0x0c0e5ec0, 0xca44, 0x472b, + 0xb7, 0x02, 0xe6, 0x52, 0xdb, 0x1c, 0x04, 0x51); +DEFINE_GUID!(IID_IVssBackupComponents, 0x665c1d5f, 0xc218, 0x414d, + 0xa0, 0x5d, 0x7f, 0xef, 0x5f, 0x9d, 0x5c, 0x86); +DEFINE_GUID!(IID_IVssBackupComponentsEx, 0x963f03ad, 0x9e4c, 0x4a34, + 0xac, 0x15, 0xe4, 0xb6, 0x17, 0x4e, 0x50, 0x36); +STRUCT!{struct VSS_COMPONENTINFO { + type_: ::VSS_COMPONENT_TYPE, // type is a keyword in rust + bstrLogicalPath: ::BSTR, + bstrComponentName: ::BSTR, + bstrCaption: ::BSTR, + pbIcon: *mut ::BYTE, + cbIcon: ::UINT, + bRestoreMetadata: bool, + bNotifyOnBackupComplete: bool, + bSelectable: bool, + bSelectableForRestore: bool, + dwComponentFlags: ::DWORD, + cFileCount: ::UINT, + cDatabases: ::UINT, + cLogFiles: ::UINT, + cDependencies: ::UINT, +}} +pub type PVSSCOMPONENTINFO = *const ::VSS_COMPONENTINFO; +RIDL!( +interface IVssWMComponent(IVssWMComponentVtbl): IUnknown(IUnknownVtbl) { + fn GetComponentInfo(&mut self, ppInfo: *mut ::PVSSCOMPONENTINFO) -> ::HRESULT, + fn FreeComponentInfo(&mut self, pInfo: ::PVSSCOMPONENTINFO) -> ::HRESULT, + fn GetFile(&mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc) -> ::HRESULT, + fn GetDatabaseFile( + &mut self, iDBFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetDatabaseLogFile( + &mut self, iDbLogFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetDependency( + &mut self, iDependency: ::UINT, ppDependency: *mut *mut ::IVssWMDependency + ) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadata(IVssExamineWriterMetadataVtbl): IUnknown(IUnknownVtbl) { + fn GetIdentity( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriterName: *mut ::BSTR, pUsage: *mut ::VSS_USAGE_TYPE, + pSource: *mut ::VSS_SOURCE_TYPE + ) -> ::HRESULT, + fn GetFileCounts(&mut self, pcIncludeFiles: *mut ::UINT, pcExcludeFiles: *mut ::UINT, + pcComponents: *mut ::UINT + ) -> ::HRESULT, + fn GetIncludeFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetExcludeFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetComponent( + &mut self, iComponent: ::UINT, ppComponent: *mut *mut ::IVssWMComponent + ) -> ::HRESULT, + fn GetRestoreMethod( + &mut self, pMethod: *mut ::VSS_RESTOREMETHOD_ENUM, pbstrService: *mut ::BSTR, + pbstrUserProcedure: *mut ::BSTR, pwriterRestore: *mut ::VSS_WRITERRESTORE_ENUM, + pbRebootRequired: *mut bool, pcMappings: *mut ::UINT + ) -> ::HRESULT, + fn GetAlternateLocationMapping( + &mut self, iMapping: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn GetBackupSchema(&mut self, pdwSchemaMask: *mut ::DWORD) -> ::HRESULT, + fn GetDocument(&mut self, pDoc: *mut ::c_void) -> ::HRESULT, //TODO IXMLDOMDocument + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT, + fn LoadFromXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadataEx(IVssExamineWriterMetadataExVtbl): + IVssExamineWriterMetadata(IVssExamineWriterMetadataVtbl) { + fn GetIdentityEx( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriterName: *mut ::BSTR, pbstrInstanceName: *mut ::BSTR, + pUsage: *mut ::VSS_USAGE_TYPE, pSource: *mut ::VSS_SOURCE_TYPE + ) -> ::HRESULT +} +); +RIDL!( +interface IVssExamineWriterMetadataEx2(IVssExamineWriterMetadataEx2Vtbl): + IVssExamineWriterMetadataEx(IVssExamineWriterMetadataExVtbl) { + fn GetVersion( + &mut self, pdwMajorVersion: *mut ::DWORD, pdwMinorVersion: *mut ::DWORD + ) -> ::HRESULT, + fn GetExcludeFromSnapshotCount(&mut self, pcExcludedFromSnapshot: *mut ::UINT) -> ::HRESULT, + fn GetExcludeFromSnapshotFile( + &mut self, iFile: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT +} +); +#[repr(C)] +pub struct IVssWriterComponentsExt { + pub lpVtbl: *const IVssWriterComponentsExtVtbl, +} +#[repr(C)] +pub struct IVssWriterComponentsExtVtbl { + pub parent1: ::IVssWriterComponentsVtbl, + pub parent2: ::IUnknownVtbl, +} +RIDL!( +interface IVssBackupComponents(IVssBackupComponentsVtbl): IUnknown(IUnknownVtbl) { + fn GetWriterComponentsCount(&mut self, pcComponents: *mut ::UINT) -> ::HRESULT, + fn GetWriterComponents( + &mut self, iWriter: ::UINT, ppWriter: *mut *mut IVssWriterComponentsExt + ) -> ::HRESULT, + fn InitializeForBackup(&mut self, bstrXML: ::BSTR) -> ::HRESULT, + fn SetBackupState( + &mut self, bSelectComponents: bool, bBackupBootableSystemState: bool, + backupType: ::VSS_BACKUP_TYPE, bPartialFileSupport: bool + ) -> ::HRESULT, + fn InitializeForRestore(&mut self, bstrXML: ::BSTR) -> ::HRESULT, + fn SetRestoreState(&mut self, restoreType: ::VSS_RESTORE_TYPE) -> ::HRESULT, + fn GatherWriterMetadata(&mut self, pAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetWriterMetadataCount(&mut self, pcWriters: *mut ::UINT) -> ::HRESULT, + fn GetWriterMetadata( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, + ppMetadata: *mut *mut IVssExamineWriterMetadata + ) -> ::HRESULT, + fn FreeWriterMetadata(&mut self) -> ::HRESULT, + fn AddComponent( + &mut self, instanceId: ::VSS_ID, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, + wszLogicalPath: ::LPCWSTR, wszComponentName: ::LPCWSTR + ) -> ::HRESULT, + fn PrepareForBackup(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn AbortBackup(&mut self) -> ::HRESULT, + fn GatherWriterStatus(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetWriterStatusCount(&mut self, pcWriters: *mut ::UINT) -> ::HRESULT, + fn FreeWriterStatus(&mut self) -> ::HRESULT, + fn GetWriterStatus( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriter: *mut ::BSTR, pnStatus: *mut ::VSS_WRITER_STATE, + phResultFailure: *mut ::HRESULT + ) -> ::HRESULT, + fn SetBackupSucceeded( + &mut self, instanceId: ::VSS_ID, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, + wszLogicalPath: ::LPCWSTR, wszComponentName: ::LPCWSTR, bSucceded: bool + ) -> ::HRESULT, + fn SetBackupOptions( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszBackupOptions: ::LPCWSTR + ) -> ::HRESULT, + fn SetSelectedForRestore( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bSelectedForRestore: bool + ) -> ::HRESULT, + fn SetRestoreOptions( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszRestoreOptions: ::LPCWSTR + ) -> ::HRESULT, + fn SetAdditionalRestores( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bAdditionalRestores: bool + ) -> ::HRESULT, + fn SetPreviousBackupStamp( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPreviousBackupStamp: ::LPCWSTR + ) -> ::HRESULT, + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT, + fn BackupComplete(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn AddAlternativeLocationMapping( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszDestination: ::LPCWSTR + ) -> ::HRESULT, + fn AddRestoreSubcomponent( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszSubComponentLogicalPath: ::LPCWSTR, + wszSubComponentName: ::LPCWSTR, bRepair: bool + ) -> ::HRESULT, + fn SetFileRestoreStatus( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, status: ::VSS_FILE_RESTORE_STATUS + ) -> ::HRESULT, + fn AddNewTarget( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszPath: ::LPCWSTR, wszFileName: ::LPCWSTR, bRecursive: bool, + wszAlternatePath: ::LPCWSTR + ) -> ::HRESULT, + fn SetRangesFilePath( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, iPartialFile: ::UINT, wszRangesFile: ::LPCWSTR + ) -> ::HRESULT, + fn PreRestore(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn PostRestore(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn SetContext(&mut self, lContext: ::LONG) -> ::HRESULT, + fn StartSnapshotSet(&mut self, pSnapshotSetId: *mut ::VSS_ID) -> ::HRESULT, + fn AddToSnapshotSet( + &mut self, pwszVolumeName: ::VSS_PWSZ, ProviderId: ::VSS_ID, pidSnapshot: *mut ::VSS_ID + ) -> ::HRESULT, + fn DoSnapshotSet(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn DeleteSnapshots( + &mut self, SourceObjectId: ::VSS_ID, eSourceObjectType: ::VSS_OBJECT_TYPE, + bForceDelete: ::BOOL, plDeletedSnapshots: *mut ::LONG, pNondeletedSnapshotID: *mut ::VSS_ID + ) -> ::HRESULT, + fn ImportSnapshots(&mut self, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn BreakSnapshotSet(&mut self, SnapshotSetId: ::VSS_ID) -> ::HRESULT, + fn GetSnapshotProperties( + &mut self, SnapshotId: ::VSS_ID, + pProp: *mut ::VSS_SNAPSHOT_PROP + ) -> ::HRESULT, + fn Query(&mut self, QueriedObjectId: ::VSS_ID, eQueriedObjectType: ::VSS_OBJECT_TYPE, + eReturnedObjectsType: ::VSS_OBJECT_TYPE, ppEnum: *mut *mut ::IVssEnumObject) -> ::HRESULT, + fn IsVolumeSupported( + &mut self, ProviderId: ::VSS_ID, pwszVolumeName: ::VSS_PWSZ, + pbSupportedByThisProvider: *mut ::BOOL + ) -> ::HRESULT, + fn DisableWriterClasses( + &mut self, rgWriterClassId: *const ::VSS_ID, cClassId: ::UINT + ) -> ::HRESULT, + fn EnableWriterClasses( + &mut self, rgWriterClassId: *const ::VSS_ID, cClassId: ::UINT + ) -> ::HRESULT, + fn DisableWriterInstances( + &mut self, rgWriterInstanceId: *const ::VSS_ID, cInstanceId: ::UINT + ) -> ::HRESULT, + fn ExposeSnapshot(&mut self, SnapshotId: ::VSS_ID, wszPathFromRoot: ::VSS_PWSZ, + lAttributes: ::LONG, wszExpose: ::VSS_PWSZ, pwszExposed: ::VSS_PWSZ + ) -> ::HRESULT, + fn RevertToSnapshot(&mut self, SnapshotId: ::VSS_ID, bForceDismount: ::BOOL) -> ::HRESULT, + fn QueryRevertStatus( + &mut self, pwszVolume: ::VSS_PWSZ, ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx(IVssBackupComponentsExVtbl): + IVssBackupComponents(IVssBackupComponentsVtbl) { + fn GetWriterMetadataEx( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, + ppMetadata: *mut *mut ::IVssExamineWriterMetadataEx + ) -> ::HRESULT, + fn SetSelectedForRestoreEx( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bSelectedForRestore: bool, instanceId: ::VSS_ID + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx2(IVssBackupComponentsEx2Vtbl): + IVssBackupComponentsEx(IVssBackupComponentsExVtbl) { + fn UnexposeSnapshot(&mut self, snapshotId: ::VSS_ID) -> ::HRESULT, + fn SetAuthoritativeRestore( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, bAuth: bool + ) -> ::HRESULT, + fn SetRollForward( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, rollType: ::VSS_ROLLFORWARD_TYPE, + wszRollForwardPoint: ::LPCWSTR + ) -> ::HRESULT, + fn SetRestoreName( + &mut self, writerId: ::VSS_ID, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszRestoreName: ::LPCWSTR + ) -> ::HRESULT, + fn BreakSnapshotSetEx( + &mut self, SnapshotSetID: ::VSS_ID, dwBreakFlags: ::DWORD, ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT, + fn PreFastRecovery( + &mut self, SnapshotSetID: ::VSS_ID, dwPreFastRecoveryFlags: ::DWORD, + ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT, + fn FastRecovery( + &mut self, SnapshotSetID: ::VSS_ID, dwFastRecoveryFlags: ::DWORD, + ppAsync: *mut *mut ::IVssAsync + ) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx3(IVssBackupComponentsEx3Vtbl): + IVssBackupComponentsEx2(IVssBackupComponentsEx2Vtbl) { + fn GetWriterStatusEx( + &mut self, iWriter: ::UINT, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID, + pbstrWriter: *mut ::BSTR, pnStatus: *mut ::VSS_WRITER_STATE, + phrFailureWriter: *mut ::HRESULT, phrApplication: *mut ::HRESULT, + pbstrApplicationMessage: *mut ::BSTR + ) -> ::HRESULT, + fn AddSnapshotToRecoverySet( + &mut self, snapshotId: ::VSS_ID, dwFlags: ::DWORD, pwszDestinationVolume: ::VSS_PWSZ + ) -> ::HRESULT, + fn RecoverSet(&mut self, dwFlags: ::DWORD, ppAsync: *mut *mut ::IVssAsync) -> ::HRESULT, + fn GetSessionId(&mut self, idSession: *mut ::VSS_ID) -> ::HRESULT +} +); +RIDL!( +interface IVssBackupComponentsEx4(IVssBackupComponentsEx4Vtbl): + IVssBackupComponentsEx3(IVssBackupComponentsEx3Vtbl) { + fn GetRootAndLogicalPrefixPaths( + &mut self, pwszFilePath: ::VSS_PWSZ, ppwszRootPath: *mut ::VSS_PWSZ, + ppwszLogicalPrefix: *mut ::VSS_PWSZ, bNormalizeFQDNforRootPath: ::BOOL + ) -> ::HRESULT +} +); +pub const VSS_SW_BOOTABLE_STATE: ::DWORD = 1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/vss.rs b/third_party/cargo/vendor/winapi-0.2.8/src/vss.rs new file mode 100644 index 0000000..259f181 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/vss.rs @@ -0,0 +1,256 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License +//! VSS header file +ENUM!{enum VSS_OBJECT_TYPE { + VSS_OBJECT_UNKNOWN = 0, + VSS_OBJECT_NONE = 1, + VSS_OBJECT_SNAPSHOT_SET = 2, + VSS_OBJECT_SNAPSHOT = 3, + VSS_OBJECT_PROVIDER = 4, + VSS_OBJECT_TYPE_COUNT = 5, +}} +pub type PVSS_OBJECT_TYPE = *mut VSS_OBJECT_TYPE; +ENUM!{enum VSS_SNAPSHOT_STATE { + VSS_SS_UNKNOWN = 0x00, + VSS_SS_PREPARING = 0x01, + VSS_SS_PROCESSING_PREPARE = 0x02, + VSS_SS_PREPARED = 0x03, + VSS_SS_PROCESSING_PRECOMMIT = 0x04, + VSS_SS_PRECOMMITTED = 0x05, + VSS_SS_PROCESSING_COMMIT = 0x06, + VSS_SS_COMMITTED = 0x07, + VSS_SS_PROCESSING_POSTCOMMIT = 0x08, + VSS_SS_PROCESSING_PREFINALCOMMIT = 0x09, + VSS_SS_PREFINALCOMMITTED = 0x0a, + VSS_SS_PROCESSING_POSTFINALCOMMIT = 0x0b, + VSS_SS_CREATED = 0x0c, + VSS_SS_ABORTED = 0x0d, + VSS_SS_DELETED = 0x0e, + VSS_SS_POSTCOMMITTED = 0x0f, + VSS_SS_COUNT = 0x10, +}} +pub type PVSS_SNAPSHOT_STATE = *mut VSS_SNAPSHOT_STATE; +pub type VSS_VOLUME_SNAPSHOT_ATTRIBUTES = ::LONG; +pub const VSS_VOLSNAP_ATTR_PERSISTENT: ::LONG = 0x00000001; +pub const VSS_VOLSNAP_ATTR_NO_AUTORECOVERY: ::LONG = 0x00000002; +pub const VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE: ::LONG = 0x00000004; +pub const VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE: ::LONG = 0x00000008; +pub const VSS_VOLSNAP_ATTR_NO_WRITERS: ::LONG = 0x00000010; +pub const VSS_VOLSNAP_ATTR_TRANSPORTABLE: ::LONG = 0x00000020; +pub const VSS_VOLSNAP_ATTR_NOT_SURFACED: ::LONG = 0x00000040; +pub const VSS_VOLSNAP_ATTR_NOT_TRANSACTED: ::LONG = 0x00000080; +pub const VSS_VOLSNAP_ATTR_HARDWARE_ASSISTED: ::LONG = 0x00010000; +pub const VSS_VOLSNAP_ATTR_DIFFERENTIAL: ::LONG = 0x00020000; +pub const VSS_VOLSNAP_ATTR_PLEX: ::LONG = 0x00040000; +pub const VSS_VOLSNAP_ATTR_IMPORTED: ::LONG = 0x00080000; +pub const VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY: ::LONG = 0x00100000; +pub const VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY: ::LONG = 0x00200000; +pub const VSS_VOLSNAP_ATTR_AUTORECOVER: ::LONG = 0x00400000; +pub const VSS_VOLSNAP_ATTR_ROLLBACK_RECOVERY: ::LONG = 0x00800000; +pub const VSS_VOLSNAP_ATTR_DELAYED_POSTSNAPSHOT: ::LONG = 0x01000000; +pub const VSS_VOLSNAP_ATTR_TXF_RECOVERY: ::LONG = 0x02000000; +pub const VSS_VOLSNAP_ATTR_FILE_SHARE: ::LONG = 0x04000000; +pub type PVSS_VOLUME_SNAPSHOT_ATTRIBUTES = *mut VSS_VOLUME_SNAPSHOT_ATTRIBUTES; +pub type VSS_SNAPSHOT_CONTEXT = ::LONG; +pub type PVSS_SNAPSHOT_CONTEXT = *mut VSS_SNAPSHOT_CONTEXT; +pub const VSS_CTX_BACKUP: ::LONG = 0; +pub const VSS_CTX_FILE_SHARE_BACKUP: ::LONG = VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_NAS_ROLLBACK: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE | VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_APP_ROLLBACK: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE; +pub const VSS_CTX_CLIENT_ACCESSIBLE: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE + | VSS_VOLSNAP_ATTR_NO_WRITERS; +pub const VSS_CTX_CLIENT_ACCESSIBLE_WRITERS: ::LONG = VSS_VOLSNAP_ATTR_PERSISTENT + | VSS_VOLSNAP_ATTR_CLIENT_ACCESSIBLE | VSS_VOLSNAP_ATTR_NO_AUTO_RELEASE; +pub const VSS_CTX_ALL: ::LONG = 0xffffffffu32 as ::LONG; +pub type VSS_PROVIDER_CAPABILITIES = ::DWORD; +pub type PVSS_PROVIDER_CAPABILITIES = *mut VSS_PROVIDER_CAPABILITIES; +pub const VSS_PRV_CAPABILITY_LEGACY: ::DWORD = 0x1; +pub const VSS_PRV_CAPABILITY_COMPLIANT: ::DWORD = 0x2; +pub const VSS_PRV_CAPABILITY_LUN_REPOINT: ::DWORD = 0x4; +pub const VSS_PRV_CAPABILITY_LUN_RESYNC: ::DWORD = 0x8; +pub const VSS_PRV_CAPABILITY_OFFLINE_CREATION: ::DWORD = 0x10; +pub const VSS_PRV_CAPABILITY_MULTIPLE_IMPORT: ::DWORD = 0x20; +pub const VSS_PRV_CAPABILITY_RECYCLING: ::DWORD = 0x40; +pub const VSS_PRV_CAPABILITY_PLEX: ::DWORD = 0x80; +pub const VSS_PRV_CAPABILITY_DIFFERENTIAL: ::DWORD = 0x100; +pub const VSS_PRV_CAPABILITY_CLUSTERED: ::DWORD = 0x200; +pub type VSS_HARDWARE_OPTIONS = ::DWORD; +pub type PVSS_HARDWARE_OPTIONS = *mut VSS_HARDWARE_OPTIONS; +pub const VSS_BREAKEX_FLAG_MASK_LUNS: ::DWORD = 0x1; +pub const VSS_BREAKEX_FLAG_MAKE_READ_WRITE: ::DWORD = 0x2; +pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_ALL: ::DWORD = 0x4; +pub const VSS_BREAKEX_FLAG_REVERT_IDENTITY_NONE: ::DWORD = 0x8; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_READ_WRITE: ::DWORD = 0x100; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_PRE_RECOVERY: ::DWORD = 0x200; +pub const VSS_ONLUNSTATECHANGE_NOTIFY_LUN_POST_RECOVERY: ::DWORD = 0x400; +pub const VSS_ONLUNSTATECHANGE_DO_MASK_LUNS: ::DWORD = 0x800; +pub type VSS_RECOVERY_OPTIONS = ::DWORD; +pub type PVSS_RECOVERY_OPTIONS = *mut VSS_RECOVERY_OPTIONS; +pub const VSS_RECOVERY_REVERT_IDENTITY_ALL: ::DWORD = 0x00000100; +pub const VSS_RECOVERY_NO_VOLUME_CHECK: ::DWORD = 0x00000200; +ENUM!{enum VSS_WRITER_STATE { + VSS_WS_UNKNOWN = 0, + VSS_WS_STABLE = 1, + VSS_WS_WAITING_FOR_FREEZE = 2, + VSS_WS_WAITING_FOR_THAW = 3, + VSS_WS_WAITING_FOR_POST_SNAPSHOT = 4, + VSS_WS_WAITING_FOR_BACKUP_COMPLETE = 5, + VSS_WS_FAILED_AT_IDENTIFY = 6, + VSS_WS_FAILED_AT_PREPARE_BACKUP = 7, + VSS_WS_FAILED_AT_PREPARE_SNAPSHOT = 8, + VSS_WS_FAILED_AT_FREEZE = 9, + VSS_WS_FAILED_AT_THAW = 10, + VSS_WS_FAILED_AT_POST_SNAPSHOT = 11, + VSS_WS_FAILED_AT_BACKUP_COMPLETE = 12, + VSS_WS_FAILED_AT_PRE_RESTORE = 13, + VSS_WS_FAILED_AT_POST_RESTORE = 14, + VSS_WS_FAILED_AT_BACKUPSHUTDOWN = 15, + VSS_WS_COUNT = 16, +}} +pub type PVSS_WRITER_STATE = *mut VSS_WRITER_STATE; +ENUM!{enum VSS_BACKUP_TYPE { + VSS_BT_UNDEFINED = 0, + VSS_BT_FULL = 1, + VSS_BT_INCREMENTAL = 2, + VSS_BT_DIFFERENTIAL = 3, + VSS_BT_LOG = 4, + VSS_BT_COPY = 5, + VSS_BT_OTHER = 6, +}} +pub type PVSS_BACKUP_TYPE = *mut VSS_BACKUP_TYPE; +ENUM!{enum VSS_RESTORE_TYPE { + VSS_RTYPE_UNDEFINED = 0, + VSS_RTYPE_BY_COPY = 1, + VSS_RTYPE_IMPORT = 2, + VSS_RTYPE_OTHER = 3, +}} +pub type PVSS_RESTORE_TYPE = *mut VSS_RESTORE_TYPE; +ENUM!{enum VSS_ROLLFORWARD_TYPE { + VSS_RF_UNDEFINED = 0, + VSS_RF_NONE = 1, + VSS_RF_ALL = 2, + VSS_RF_PARTIAL = 3, +}} +pub type PVSS_ROLLFORWARD_TYPE = *mut VSS_ROLLFORWARD_TYPE; +ENUM!{enum VSS_PROVIDER_TYPE { + VSS_PROV_UNKNOWN = 0, + VSS_PROV_SYSTEM = 1, + VSS_PROV_SOFTWARE = 2, + VSS_PROV_HARDWARE = 3, + VSS_PROV_FILESHARE = 4, +}} +pub type PVSS_PROVIDER_TYPE = *mut VSS_PROVIDER_TYPE; +ENUM!{enum VSS_APPLICATION_LEVEL { + VSS_APP_UNKNOWN = 0, + VSS_APP_SYSTEM = 1, + VSS_APP_BACK_END = 2, + VSS_APP_FRONT_END = 3, + VSS_APP_SYSTEM_RM = 4, + VSS_APP_AUTO = -1i32 as u32, +}} +pub type PVSS_APPLICATION_LEVEL = *mut VSS_APPLICATION_LEVEL; +ENUM!{enum VSS_SNAPSHOT_PROPERTY_ID { + VSS_SPROPID_UNKNOWN = 0, + VSS_SPROPID_SNAPSHOT_ID = 0x1, + VSS_SPROPID_SNAPSHOT_SET_ID = 0x2, + VSS_SPROPID_SNAPSHOTS_COUNT = 0x3, + VSS_SPROPID_SNAPSHOT_DEVICE = 0x4, + VSS_SPROPID_ORIGINAL_VOLUME = 0x5, + VSS_SPROPID_ORIGINATING_MACHINE = 0x6, + VSS_SPROPID_SERVICE_MACHINE = 0x7, + VSS_SPROPID_EXPOSED_NAME = 0x8, + VSS_SPROPID_EXPOSED_PATH = 0x9, + VSS_SPROPID_PROVIDER_ID = 0xa, + VSS_SPROPID_SNAPSHOT_ATTRIBUTES = 0xb, + VSS_SPROPID_CREATION_TIMESTAMP = 0xc, + VSS_SPROPID_STATUS = 0xd, +}} +pub type PVSS_SNAPSHOT_PROPERTY_ID = *mut VSS_SNAPSHOT_PROPERTY_ID; +pub type VSS_FILE_SPEC_BACKUP_TYPE = ::DWORD; +pub type PVSS_FILE_SPEC_BACKUP_TYPE = *mut VSS_FILE_SPEC_BACKUP_TYPE; +pub const VSS_FSBT_FULL_BACKUP_REQUIRED: ::DWORD = 0x1; +pub const VSS_FSBT_DIFFERENTIAL_BACKUP_REQUIRED: ::DWORD = 0x2; +pub const VSS_FSBT_INCREMENTAL_BACKUP_REQUIRED: ::DWORD = 0x4; +pub const VSS_FSBT_LOG_BACKUP_REQUIRED: ::DWORD = 0x8; +pub const VSS_FSBT_FULL_SNAPSHOT_REQUIRED: ::DWORD = 0x100; +pub const VSS_FSBT_DIFFERENTIAL_SNAPSHOT_REQUIRED: ::DWORD = 0x200; +pub const VSS_FSBT_INCREMENTAL_SNAPSHOT_REQUIRED: ::DWORD = 0x400; +pub const VSS_FSBT_LOG_SNAPSHOT_REQUIRED: ::DWORD = 0x800; +pub const VSS_FSBT_CREATED_DURING_BACKUP: ::DWORD = 0x10000; +pub const VSS_FSBT_ALL_BACKUP_REQUIRED: ::DWORD = 0xf; +pub const VSS_FSBT_ALL_SNAPSHOT_REQUIRED: ::DWORD = 0xf00; +pub type VSS_BACKUP_SCHEMA = ::DWORD; +pub type PVSS_BACKUP_SCHEMA = *mut VSS_BACKUP_SCHEMA; +pub const VSS_BS_UNDEFINED: ::DWORD = 0; +pub const VSS_BS_DIFFERENTIAL: ::DWORD = 0x1; +pub const VSS_BS_INCREMENTAL: ::DWORD = 0x2; +pub const VSS_BS_EXCLUSIVE_INCREMENTAL_DIFFERENTIAL: ::DWORD = 0x4; +pub const VSS_BS_LOG: ::DWORD = 0x8; +pub const VSS_BS_COPY: ::DWORD = 0x10; +pub const VSS_BS_TIMESTAMPED: ::DWORD = 0x20; +pub const VSS_BS_LAST_MODIFY: ::DWORD = 0x40; +pub const VSS_BS_LSN: ::DWORD = 0x80; +pub const VSS_BS_WRITER_SUPPORTS_NEW_TARGET: ::DWORD = 0x100; +pub const VSS_BS_WRITER_SUPPORTS_RESTORE_WITH_MOVE: ::DWORD = 0x200; +pub const VSS_BS_INDEPENDENT_SYSTEM_STATE: ::DWORD = 0x400; +pub const VSS_BS_ROLLFORWARD_RESTORE: ::DWORD = 0x1000; +pub const VSS_BS_RESTORE_RENAME: ::DWORD = 0x2000; +pub const VSS_BS_AUTHORITATIVE_RESTORE: ::DWORD = 0x4000; +pub const VSS_BS_WRITER_SUPPORTS_PARALLEL_RESTORES: ::DWORD = 0x8000; +pub type VSS_ID = ::GUID; +pub type VSS_PWSZ = *mut ::WCHAR; +pub type VSS_TIMESTAMP = ::LONGLONG; +STRUCT!{struct VSS_SNAPSHOT_PROP { + m_SnapshotId: ::VSS_ID, + m_SnapshotSetId: ::VSS_ID, + m_lSnapshotsCount: ::LONG, + m_pwszSnapshotDeviceObject: ::VSS_PWSZ, + m_pwszOriginalVolumeName: ::VSS_PWSZ, + m_pwszOriginatingMachine: ::VSS_PWSZ, + m_pwszServiceMachine: ::VSS_PWSZ, + m_pwszExposedName: ::VSS_PWSZ, + m_pwszExposedPath: ::VSS_PWSZ, + m_ProviderId: ::VSS_ID, + m_lSnapshotAttributes: ::LONG, + m_tsCreationTimestamp: ::VSS_TIMESTAMP, + m_eStatus: ::VSS_SNAPSHOT_STATE, +}} +type PVSS_SNAPSHOT_PROP = *mut VSS_SNAPSHOT_PROP; +STRUCT!{struct VSS_PROVIDER_PROP { + m_ProviderId: ::VSS_ID, + m_pwszProviderName: ::VSS_PWSZ, + m_eProviderType: ::VSS_PROVIDER_TYPE, + m_pwszProviderVersion: ::VSS_PWSZ, + m_ProviderVersionId: ::VSS_ID, + m_ClassId: ::CLSID, +}} +type PVSS_PROVIDER_PROP = *mut VSS_PROVIDER_PROP; +STRUCT!{struct VSS_OBJECT_UNION { + Snap: ::VSS_SNAPSHOT_PROP, +}} +UNION!(VSS_OBJECT_UNION, Snap, Prov, Prov_mut, VSS_PROVIDER_PROP); +STRUCT!{struct VSS_OBJECT_PROP { + Type: ::VSS_OBJECT_TYPE, + Obj: ::VSS_OBJECT_UNION, +}} +type PVSS_OBJECT_PROP = *mut VSS_OBJECT_PROP; +RIDL!( +interface IVssEnumObject(IVssEnumObjectVtbl): IUnknown(IUnknownVtbl) { + fn Next( + &mut self, celt: ::ULONG, rgelt: *mut ::VSS_OBJECT_PROP, pceltFetched: *mut ::ULONG + ) -> ::HRESULT, + fn Skip(&mut self, celt: ::ULONG) -> ::HRESULT, + fn Reset(&mut self) -> ::HRESULT, + fn Clone(&mut self, ppenum: *mut *mut ::IVssEnumObject) -> ::HRESULT +} +); +RIDL!( +interface IVssAsync(IVssAsyncVtbl): IUnknown(IUnknownVtbl) { + fn Cancel(&mut self) -> ::HRESULT, + fn Wait(&mut self, dwMilliseconds: ::DWORD) -> ::HRESULT, + fn QueryStatus(&mut self, pHrResult: *mut ::HRESULT, pReserved: *mut ::INT) -> ::HRESULT +} +); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/vsserror.rs b/third_party/cargo/vendor/winapi-0.2.8/src/vsserror.rs new file mode 100644 index 0000000..ef84af0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/vsserror.rs @@ -0,0 +1,85 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License +//! VSS Error header file +pub const VSS_E_BAD_STATE: ::HRESULT = 0x80042301u32 as i32; +pub const VSS_E_UNEXPECTED: ::HRESULT = 0x80042302u32 as i32; +pub const VSS_E_PROVIDER_ALREADY_REGISTERED: ::HRESULT = 0x80042303u32 as i32; +pub const VSS_E_PROVIDER_NOT_REGISTERED: ::HRESULT = 0x80042304u32 as i32; +pub const VSS_E_PROVIDER_VETO: ::HRESULT = 0x80042306u32 as i32; +pub const VSS_E_PROVIDER_IN_USE: ::HRESULT = 0x80042307u32 as i32; +pub const VSS_E_OBJECT_NOT_FOUND: ::HRESULT = 0x80042308u32 as i32; +pub const VSS_S_ASYNC_PENDING: ::HRESULT = 0x00042309u32 as i32; +pub const VSS_S_ASYNC_FINISHED: ::HRESULT = 0x0004230Au32 as i32; +pub const VSS_S_ASYNC_CANCELLED: ::HRESULT = 0x0004230Bu32 as i32; +pub const VSS_E_VOLUME_NOT_SUPPORTED: ::HRESULT = 0x8004230Cu32 as i32; +pub const VSS_E_VOLUME_NOT_SUPPORTED_BY_PROVIDER: ::HRESULT = 0x8004230Eu32 as i32; +pub const VSS_E_OBJECT_ALREADY_EXISTS: ::HRESULT = 0x8004230Du32 as i32; +pub const VSS_E_UNEXPECTED_PROVIDER_ERROR: ::HRESULT = 0x8004230Fu32 as i32; +pub const VSS_E_CORRUPT_XML_DOCUMENT: ::HRESULT = 0x80042310u32 as i32; +pub const VSS_E_INVALID_XML_DOCUMENT: ::HRESULT = 0x80042311u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_VOLUMES_REACHED: ::HRESULT = 0x80042312u32 as i32; +pub const VSS_E_FLUSH_WRITES_TIMEOUT: ::HRESULT = 0x80042313u32 as i32; +pub const VSS_E_HOLD_WRITES_TIMEOUT: ::HRESULT = 0x80042314u32 as i32; +pub const VSS_E_UNEXPECTED_WRITER_ERROR: ::HRESULT = 0x80042315u32 as i32; +pub const VSS_E_SNAPSHOT_SET_IN_PROGRESS: ::HRESULT = 0x80042316u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_SNAPSHOTS_REACHED: ::HRESULT = 0x80042317u32 as i32; +pub const VSS_E_WRITER_INFRASTRUCTURE: ::HRESULT = 0x80042318u32 as i32; +pub const VSS_E_WRITER_NOT_RESPONDING: ::HRESULT = 0x80042319u32 as i32; +pub const VSS_E_WRITER_ALREADY_SUBSCRIBED: ::HRESULT = 0x8004231Au32 as i32; +pub const VSS_E_UNSUPPORTED_CONTEXT: ::HRESULT = 0x8004231Bu32 as i32; +pub const VSS_E_VOLUME_IN_USE: ::HRESULT = 0x8004231Du32 as i32; +pub const VSS_E_MAXIMUM_DIFFAREA_ASSOCIATIONS_REACHED: ::HRESULT = 0x8004231Eu32 as i32; +pub const VSS_E_INSUFFICIENT_STORAGE: ::HRESULT = 0x8004231Fu32 as i32; +pub const VSS_E_NO_SNAPSHOTS_IMPORTED: ::HRESULT = 0x80042320u32 as i32; +pub const VSS_S_SOME_SNAPSHOTS_NOT_IMPORTED: ::HRESULT = 0x00042321u32 as i32; +pub const VSS_E_SOME_SNAPSHOTS_NOT_IMPORTED: ::HRESULT = 0x80042321u32 as i32; +pub const VSS_E_MAXIMUM_NUMBER_OF_REMOTE_MACHINES_REACHED: ::HRESULT = 0x80042322u32 as i32; +pub const VSS_E_REMOTE_SERVER_UNAVAILABLE: ::HRESULT = 0x80042323u32 as i32; +pub const VSS_E_REMOTE_SERVER_UNSUPPORTED: ::HRESULT = 0x80042324u32 as i32; +pub const VSS_E_REVERT_IN_PROGRESS: ::HRESULT = 0x80042325u32 as i32; +pub const VSS_E_REVERT_VOLUME_LOST: ::HRESULT = 0x80042326u32 as i32; +pub const VSS_E_REBOOT_REQUIRED: ::HRESULT = 0x80042327u32 as i32; +pub const VSS_E_TRANSACTION_FREEZE_TIMEOUT: ::HRESULT = 0x80042328u32 as i32; +pub const VSS_E_TRANSACTION_THAW_TIMEOUT: ::HRESULT = 0x80042329u32 as i32; +pub const VSS_E_VOLUME_NOT_LOCAL: ::HRESULT = 0x8004232Du32 as i32; +pub const VSS_E_CLUSTER_TIMEOUT: ::HRESULT = 0x8004232Eu32 as i32; +pub const VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT: ::HRESULT = 0x800423F0u32 as i32; +pub const VSS_E_WRITERERROR_OUTOFRESOURCES: ::HRESULT = 0x800423F1u32 as i32; +pub const VSS_E_WRITERERROR_TIMEOUT: ::HRESULT = 0x800423F2u32 as i32; +pub const VSS_E_WRITERERROR_RETRYABLE: ::HRESULT = 0x800423F3u32 as i32; +pub const VSS_E_WRITERERROR_NONRETRYABLE: ::HRESULT = 0x800423F4u32 as i32; +pub const VSS_E_WRITERERROR_RECOVERY_FAILED: ::HRESULT = 0x800423F5u32 as i32; +pub const VSS_E_BREAK_REVERT_ID_FAILED: ::HRESULT = 0x800423F6u32 as i32; +pub const VSS_E_LEGACY_PROVIDER: ::HRESULT = 0x800423F7u32 as i32; +pub const VSS_E_MISSING_DISK: ::HRESULT = 0x800423F8u32 as i32; +pub const VSS_E_MISSING_HIDDEN_VOLUME: ::HRESULT = 0x800423F9u32 as i32; +pub const VSS_E_MISSING_VOLUME: ::HRESULT = 0x800423FAu32 as i32; +pub const VSS_E_AUTORECOVERY_FAILED: ::HRESULT = 0x800423FBu32 as i32; +pub const VSS_E_DYNAMIC_DISK_ERROR: ::HRESULT = 0x800423FCu32 as i32; +pub const VSS_E_NONTRANSPORTABLE_BCD: ::HRESULT = 0x800423FDu32 as i32; +pub const VSS_E_CANNOT_REVERT_DISKID: ::HRESULT = 0x800423FEu32 as i32; +pub const VSS_E_RESYNC_IN_PROGRESS: ::HRESULT = 0x800423FFu32 as i32; +pub const VSS_E_CLUSTER_ERROR: ::HRESULT = 0x80042400u32 as i32; +pub const VSS_E_UNSELECTED_VOLUME: ::HRESULT = 0x8004232Au32 as i32; +pub const VSS_E_SNAPSHOT_NOT_IN_SET: ::HRESULT = 0x8004232Bu32 as i32; +pub const VSS_E_NESTED_VOLUME_LIMIT: ::HRESULT = 0x8004232Cu32 as i32; +pub const VSS_E_NOT_SUPPORTED: ::HRESULT = 0x8004232Fu32 as i32; +pub const VSS_E_WRITERERROR_PARTIAL_FAILURE: ::HRESULT = 0x80042336u32 as i32; +pub const VSS_E_ASRERROR_DISK_ASSIGNMENT_FAILED: ::HRESULT = 0x80042401u32 as i32; +pub const VSS_E_ASRERROR_DISK_RECREATION_FAILED: ::HRESULT = 0x80042402u32 as i32; +pub const VSS_E_ASRERROR_NO_ARCPATH: ::HRESULT = 0x80042403u32 as i32; +pub const VSS_E_ASRERROR_MISSING_DYNDISK: ::HRESULT = 0x80042404u32 as i32; +pub const VSS_E_ASRERROR_SHARED_CRIDISK: ::HRESULT = 0x80042405u32 as i32; +pub const VSS_E_ASRERROR_DATADISK_RDISK0: ::HRESULT = 0x80042406u32 as i32; +pub const VSS_E_ASRERROR_RDISK0_TOOSMALL: ::HRESULT = 0x80042407u32 as i32; +pub const VSS_E_ASRERROR_CRITICAL_DISKS_TOO_SMALL: ::HRESULT = 0x80042408u32 as i32; +pub const VSS_E_WRITER_STATUS_NOT_AVAILABLE: ::HRESULT = 0x80042409u32 as i32; +pub const VSS_E_ASRERROR_DYNAMIC_VHD_NOT_SUPPORTED: ::HRESULT = 0x8004240Au32 as i32; +pub const VSS_E_CRITICAL_VOLUME_ON_INVALID_DISK: ::HRESULT = 0x80042411u32 as i32; +pub const VSS_E_ASRERROR_RDISK_FOR_SYSTEM_DISK_NOT_FOUND: ::HRESULT = 0x80042412u32 as i32; +pub const VSS_E_ASRERROR_NO_PHYSICAL_DISK_AVAILABLE: ::HRESULT = 0x80042413u32 as i32; +pub const VSS_E_ASRERROR_FIXED_PHYSICAL_DISK_AVAILABLE_AFTER_DISK_EXCLUSION: ::HRESULT = + 0x80042414u32 as i32; +pub const VSS_E_ASRERROR_CRITICAL_DISK_CANNOT_BE_EXCLUDED: ::HRESULT = 0x80042415u32 as i32; +pub const VSS_E_ASRERROR_SYSTEM_PARTITION_HIDDEN: ::HRESULT = 0x80042416u32 as i32; +pub const VSS_E_FSS_TIMEOUT: ::HRESULT = 0x80042417u32 as i32; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/vswriter.rs b/third_party/cargo/vendor/winapi-0.2.8/src/vswriter.rs new file mode 100644 index 0000000..fd1509c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/vswriter.rs @@ -0,0 +1,241 @@ +// Copyright © 2015, Brian Vincent +// Licensed under the MIT License +//! VSS Writer header file +ENUM!{enum VSS_USAGE_TYPE { + VSS_UT_UNDEFINED = 0, + VSS_UT_BOOTABLESYSTEMSTATE = 1, + VSS_UT_SYSTEMSERVICE = 2, + VSS_UT_USERDATA = 3, + VSS_UT_OTHER = 4, +}} +ENUM!{enum VSS_SOURCE_TYPE { + VSS_ST_UNDEFINED = 0, + VSS_ST_TRANSACTEDDB = 1, + VSS_ST_NONTRANSACTEDDB = 2, + VSS_ST_OTHER = 3, +}} +ENUM!{enum VSS_RESTOREMETHOD_ENUM { + VSS_RME_UNDEFINED = 0, + VSS_RME_RESTORE_IF_NOT_THERE = 1, + VSS_RME_RESTORE_IF_CAN_REPLACE = 2, + VSS_RME_STOP_RESTORE_START = 3, + VSS_RME_RESTORE_TO_ALTERNATE_LOCATION = 4, + VSS_RME_RESTORE_AT_REBOOT = 5, + VSS_RME_RESTORE_AT_REBOOT_IF_CANNOT_REPLACE = 6, + VSS_RME_CUSTOM = 7, + VSS_RME_RESTORE_STOP_START = 8, +}} +ENUM!{enum VSS_WRITERRESTORE_ENUM { + VSS_WRE_UNDEFINED = 0, + VSS_WRE_NEVER = 1, + VSS_WRE_IF_REPLACE_FAILS = 2, + VSS_WRE_ALWAYS = 3, +}} +ENUM!{enum VSS_COMPONENT_TYPE { + VSS_CT_UNDEFINED = 0, + VSS_CT_DATABASE = 1, + VSS_CT_FILEGROUP = 2, +}} +ENUM!{enum VSS_ALTERNATE_WRITER_STATE { + VSS_AWS_UNDEFINED = 0, + VSS_AWS_NO_ALTERNATE_WRITER = 1, + VSS_AWS_ALTERNATE_WRITER_EXISTS = 2, + VSS_AWS_THIS_IS_ALTERNATE_WRITER = 3, +}} +pub type VSS_SUBSCRIBE_MASK = ::DWORD; +pub const VSS_SM_POST_SNAPSHOT_FLAG: ::DWORD = 0x00000001; +pub const VSS_SM_BACKUP_EVENTS_FLAG: ::DWORD = 0x00000002; +pub const VSS_SM_RESTORE_EVENTS_FLAG: ::DWORD = 0x00000004; +pub const VSS_SM_IO_THROTTLING_FLAG: ::DWORD = 0x00000008; +pub const VSS_SM_ALL_FLAGS: ::DWORD = 0xffffffff; +ENUM!{enum VSS_RESTORE_TARGET { + VSS_RT_UNDEFINED = 0, + VSS_RT_ORIGINAL = 1, + VSS_RT_ALTERNATE = 2, + VSS_RT_DIRECTED = 3, + VSS_RT_ORIGINAL_LOCATION = 4, +}} +ENUM!{enum VSS_FILE_RESTORE_STATUS { + VSS_RS_UNDEFINED = 0, + VSS_RS_NONE = 1, + VSS_RS_ALL = 2, + VSS_RS_FAILED = 3, +}} +pub type VSS_COMPONENT_FLAGS = ::DWORD; +pub const VSS_CF_BACKUP_RECOVERY: ::DWORD = 0x00000001; +pub const VSS_CF_APP_ROLLBACK_RECOVERY: ::DWORD = 0x00000002; +pub const VSS_CF_NOT_SYSTEM_STATE: ::DWORD = 0x00000004; +RIDL!( +interface IVssWMFiledesc(IVssWMFiledescVtbl): IUnknown(IUnknownVtbl) { + fn GetPath(&mut self, pbstrPath: *mut ::BSTR) -> ::HRESULT, + fn GetFilespec(&mut self, pbstrFilespec: *mut ::BSTR) -> ::HRESULT, + fn GetRecursive(&mut self, pbRecursive: *mut bool) -> ::HRESULT, + fn GetAlternateLocation(&mut self, pbstrAlternateLocation: *mut ::BSTR) -> ::HRESULT, + fn GetBackupTypeMask(&mut self, pdwTypeMask: *mut ::DWORD) -> ::HRESULT +} +); +RIDL!( +interface IVssWMDependency(IVssWMDependencyVtbl): IUnknown(IUnknownVtbl) { + fn GetWriterId(&mut self, pWriterId: *mut ::VSS_ID) -> ::HRESULT, + fn GetLogicalPath(&mut self, pbstrLogicalPath: *mut ::BSTR) -> ::HRESULT, + fn GetComponentName(&mut self, pbstrComponentName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssComponent(IVssComponentVtbl): IUnknown(IUnknownVtbl) { + fn GetLogicalPath(&mut self, pbstrPath: *mut ::BSTR) -> ::HRESULT, + fn GetComponentType(&mut self, pct: *mut ::VSS_COMPONENT_TYPE) -> ::HRESULT, + fn GetComponentName(&mut self, pbstrName: *mut ::BSTR) -> ::HRESULT, + fn GetBackupSucceeded(&mut self, pbSucceeded: *mut bool) -> ::HRESULT, + fn GetAlternateLocationMappingCount(&mut self, pcMappings: *mut ::UINT) -> ::HRESULT, + fn GetAlternateLocationMapping( + &mut self, iMapping: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn SetBackupMetadata(&mut self, wszData: ::LPCWSTR) -> ::HRESULT, + fn GetBackupMetadata(&mut self, pbstrData: *mut ::BSTR) -> ::HRESULT, + fn AddPartialFile( + &mut self, wszPath: ::LPCWSTR, wszFilename: ::LPCWSTR, wszRanges: ::LPCWSTR, + wszMetadata: ::LPCWSTR + ) -> ::HRESULT, + fn GetPartialFileCount(&mut self, pcPartialFiles: *mut ::UINT) -> ::HRESULT, + fn GetPartialFile( + &mut self, iPartialFile: ::UINT, pbstrPath: *mut ::BSTR, pbstrFilename: *mut ::BSTR, + pbstrRange: *mut ::BSTR, pbstrMetadata: *mut ::BSTR + ) -> ::HRESULT, + fn IsSelectedForRestore(&mut self, pbSelectedForRestore: *mut bool) -> ::HRESULT, + fn GetAdditionalRestores(&mut self, pbAdditionalRestores: *mut bool) -> ::HRESULT, + fn GetNewTargetCount(&mut self, pcNewTarget: *mut ::UINT) -> ::HRESULT, + fn GetNewTarget( + &mut self, iNewTarget: ::UINT, ppFiledesc: *mut *mut ::IVssWMFiledesc + ) -> ::HRESULT, + fn AddDirectedTarget( + &mut self, wszSourcePath: ::LPCWSTR, wszSourceFilename: ::LPCWSTR, + wszSourceRangeList: ::LPCWSTR, wszDestinationPath: ::LPCWSTR, + wszDestinationFilename: ::LPCWSTR, wszDestinationRangeList: ::LPCWSTR + ) -> ::HRESULT, + fn GetDirectedTargetCount(&mut self, pcDirectedTarget: *mut ::UINT) -> ::HRESULT, + fn GetDirectedTarget( + &mut self, iDirectedTarget: ::UINT, pbstrSourcePath: *mut ::BSTR, + pbstrSourceFileName: *mut ::BSTR, pbstrSourceRangeList: *mut ::BSTR, + pbstrDestinationPath: *mut ::BSTR, pbstrDestinationFilename: *mut ::BSTR, + pbstrDestinationRangeList: *mut ::BSTR + ) -> ::HRESULT, + fn SetRestoreMetadata(&mut self, wszRestoreMetadata: ::LPCWSTR) -> ::HRESULT, + fn GetRestoreMetadata(&mut self, pbstrRestoreMetadata: *mut ::BSTR) -> ::HRESULT, + fn SetRestoreTarget(&mut self, target: ::VSS_RESTORE_TARGET) -> ::HRESULT, + fn GetRestoreTarget(&mut self, pTarget: *mut ::VSS_RESTORE_TARGET) -> ::HRESULT, + fn SetPreRestoreFailureMsg(&mut self, wszPreRestoreFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPreRestoreFailureMsg(&mut self, pbstrPreRestoreFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn SetPostRestoreFailureMsg(&mut self, wszPostRestoreFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPostRestoreFailureMsg(&mut self, pbstrPostRestoreFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn SetBackupStamp(&mut self, wszBackupStamp: ::LPCWSTR) -> ::HRESULT, + fn GetBackupStamp(&mut self, pbstrBackupStamp: *mut ::BSTR) -> ::HRESULT, + fn GetPreviousBackupStamp(&mut self, pbstrBackupStamp: *mut ::BSTR) -> ::HRESULT, + fn GetBackupOptions(&mut self, pbstrBackupOptions: *mut ::BSTR) -> ::HRESULT, + fn GetRestoreOptions(&mut self, pbstrRestoreOptions: *mut ::BSTR) -> ::HRESULT, + fn GetRestoreSubcomponentCount(&mut self, pcRestoreSubcomponent: *mut ::UINT) -> ::HRESULT, + fn GetRestoreSubcomponent( + &mut self, iComponent: ::UINT, pbstrLogicalPath: *mut ::BSTR, + pbstrComponentName: *mut ::BSTR, pbRepair: *mut bool + ) -> ::HRESULT, + fn GetFileRestoreStatus(&mut self, pStatus: *mut VSS_FILE_RESTORE_STATUS) -> ::HRESULT, + fn AddDifferencedFilesByLastModifyTime( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: ::BOOL, + ftLastModifyTime: ::FILETIME + ) -> ::HRESULT, + fn AddDifferencedFilesByLastModifyLSN( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: ::BOOL, + bstrLsnString: ::BSTR + ) -> ::HRESULT, + fn GetDifferencedFilesCount(&mut self, pcDifferencedFiles: *mut ::UINT) -> ::HRESULT, + fn GetDifferencedFile( + &mut self, iDifferencedFile: ::UINT, pbstrPath: *mut ::BSTR, pbstrFilespec: *mut ::BSTR, + pbRecursive: *mut ::BOOL, pbstrLsnString: *mut ::BSTR, pftLastModifyTime: *mut ::FILETIME + ) -> ::HRESULT +} +); +RIDL!( +interface IVssWriterComponents(IVssWriterComponentsVtbl) { + fn GetComponentCount(&mut self, pcComponents: *mut ::UINT) -> ::HRESULT, + fn GetWriterInfo( + &mut self, pidInstance: *mut ::VSS_ID, pidWriter: *mut ::VSS_ID + ) -> ::HRESULT, + fn GetComponent( + &mut self, iComponent: ::UINT, ppComponent: *mut *mut ::IVssComponent + ) -> ::HRESULT +} +); +RIDL!( +interface IVssComponentEx(IVssComponentExVtbl): IVssComponent(IVssComponentVtbl) { + fn SetPrepareForBackupFailureMsg(&mut self, wszFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn SetPostSnapshotFailureMsg(&mut self, wszFailureMsg: ::LPCWSTR) -> ::HRESULT, + fn GetPrepareForBackupFailureMsg(&mut self, pbstrFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn GetPostSnapshotFailureMsg(&mut self, pbstrFailureMsg: *mut ::BSTR) -> ::HRESULT, + fn GetAuthoritativeRestore(&mut self, pbAuth: *mut bool) -> ::HRESULT, + fn GetRollForward( + &mut self, pRollType: *mut ::VSS_ROLLFORWARD_TYPE, pbstrPoint: *mut ::BSTR + ) -> ::HRESULT, + fn GetRestoreName(&mut self, pbstrName: *mut ::BSTR) -> ::HRESULT +} +); +RIDL!( +interface IVssComponentEx2(IVssComponentEx2Vtbl): IVssComponentEx(IVssComponentExVtbl) { + fn SetFailure( + &mut self, hr: ::HRESULT, hrApplication: ::HRESULT, wszApplicationMessage: ::LPCWSTR, + dwReserved: ::DWORD + ) -> ::HRESULT, + fn GetFailure( + &mut self, phr: *mut ::HRESULT, phrApplication: *mut ::HRESULT, + pbstrApplicationMessage: *mut ::BSTR, pdwReserved: *mut ::DWORD + ) -> ::HRESULT +} +); +RIDL!( +interface IVssCreateWriterMetadata(IVssCreateWriterMetadataVtbl) { + fn AddIncludeFiles( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszAlternateLocation: ::LPCWSTR + ) -> ::HRESULT, + fn AddExcludeFiles( + &mut self, wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool + ) -> ::HRESULT, + fn AddComponent( + &mut self, ct: ::VSS_COMPONENT_TYPE, wszLogicalPath: ::LPCWSTR, + wszComponentName: ::LPCWSTR, wszCaption: ::LPCWSTR, pbIcon: *const ::BYTE, cbIcon: ::UINT, + bRestoreMetadata: bool, bNotifyOnBackupComplete: bool, bSelectableForRestore: bool, + dwComponentFlags: ::DWORD + ) -> ::HRESULT, + fn AddDatabaseFiles( + &mut self, wszLogicalPath: ::LPCWSTR, wszDatabaseName: ::LPCWSTR, wszPath: ::LPCWSTR, + wszFilespec: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn AddDatabaseLogFiles(&mut self, wszLogicalPath: ::LPCWSTR, wszDatabaseName: ::LPCWSTR, + wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn AddFilesToFileGroup(&mut self, wszLogicalPath: ::LPCWSTR, wszGroupName: ::LPCWSTR, + wszPath: ::LPCWSTR, wszFilespec: ::LPCWSTR, bRecursive: bool, + wszAlternateLocation: ::LPCWSTR, dwBackupTypeMask: ::DWORD + ) -> ::HRESULT, + fn SetRestoreMethod(&mut self, method: ::VSS_RESTOREMETHOD_ENUM, wszService: ::LPCWSTR, + wszUserProcedure: ::LPCWSTR, writerRestore: ::VSS_WRITERRESTORE_ENUM, + bRebootRequired: bool + ) -> ::HRESULT, + fn AddAlternateLocationMapping(&mut self, wszSourcePath: ::LPCWSTR, + wszSourceFilespec: ::LPCWSTR, bRecursive: bool, wszDestination: ::LPCWSTR + ) -> ::HRESULT, + fn AddComponentDependency(&mut self, wszForLogicalPath: ::LPCWSTR, + wszForComponentName: ::LPCWSTR, onWriterId: ::VSS_ID, wszOnLogicalPath: ::LPCWSTR, + wszOnComponentName: ::LPCWSTR + ) -> ::HRESULT, + fn SetBackupSchema(&mut self, dwSchemaMask: ::DWORD) -> ::HRESULT, + fn GetDocument(&mut self, pDoc: *mut *mut ::VOID) -> ::HRESULT, //TODO IXMLDOMDocument + fn SaveAsXML(&mut self, pbstrXML: *mut ::BSTR) -> ::HRESULT +} +); +//IVssCreateWriterMetadataEx +//IVssWriterImpl +//IVssCreateExpressWriterMetadata +//IVssExpressWriter +//CVssWriter +//CVssWriterEx +//CVssWriterEx2 diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/werapi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/werapi.rs new file mode 100644 index 0000000..33a5a50 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/werapi.rs @@ -0,0 +1,8 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Function prototypes for Windows Error Reporting (WER) +ENUM!{enum WER_REGISTER_FILE_TYPE { + WerRegFileTypeUserDocument = 1, + WerRegFileTypeOther = 2, + WerRegFileTypeMax, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winbase.rs new file mode 100644 index 0000000..59e3988 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winbase.rs @@ -0,0 +1,552 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This module defines the 32-Bit Windows Base APIs +pub const FILE_BEGIN: ::DWORD = 0; +pub const FILE_CURRENT: ::DWORD = 1; +pub const FILE_END: ::DWORD = 2; +pub const WAIT_FAILED: ::DWORD = 0xFFFFFFFF; +pub const WAIT_OBJECT_0: ::DWORD = ::STATUS_WAIT_0 as ::DWORD; +pub const WAIT_ABANDONED: ::DWORD = ::STATUS_ABANDONED_WAIT_0 as ::DWORD; +pub const WAIT_ABANDONED_0: ::DWORD = ::STATUS_ABANDONED_WAIT_0 as ::DWORD; +pub const WAIT_IO_COMPLETION: ::DWORD = ::STATUS_USER_APC as ::DWORD; +pub const FILE_FLAG_WRITE_THROUGH: ::DWORD = 0x80000000; +pub const FILE_FLAG_OVERLAPPED: ::DWORD = 0x40000000; +pub const FILE_FLAG_NO_BUFFERING: ::DWORD = 0x20000000; +pub const FILE_FLAG_RANDOM_ACCESS: ::DWORD = 0x10000000; +pub const FILE_FLAG_SEQUENTIAL_SCAN: ::DWORD = 0x08000000; +pub const FILE_FLAG_DELETE_ON_CLOSE: ::DWORD = 0x04000000; +pub const FILE_FLAG_BACKUP_SEMANTICS: ::DWORD = 0x02000000; +pub const FILE_FLAG_POSIX_SEMANTICS: ::DWORD = 0x01000000; +pub const FILE_FLAG_SESSION_AWARE: ::DWORD = 0x00800000; +pub const FILE_FLAG_OPEN_REPARSE_POINT: ::DWORD = 0x00200000; +pub const FILE_FLAG_OPEN_NO_RECALL: ::DWORD = 0x00100000; +pub const FILE_FLAG_FIRST_PIPE_INSTANCE: ::DWORD = 0x00080000; +pub const FILE_FLAG_OPEN_REQUIRING_OPLOCK: ::DWORD = 0x00040000; +pub const PROGRESS_CONTINUE: ::DWORD = 0; +pub const PROGRESS_CANCEL: ::DWORD = 1; +pub const PROGRESS_STOP: ::DWORD = 2; +pub const PROGRESS_QUIET: ::DWORD = 3; +pub const CALLBACK_CHUNK_FINISHED: ::DWORD = 0x00000000; +pub const CALLBACK_STREAM_SWITCH: ::DWORD = 0x00000001; +pub const COPY_FILE_FAIL_IF_EXISTS: ::DWORD = 0x00000001; +pub const COPY_FILE_RESTARTABLE: ::DWORD = 0x00000002; +pub const COPY_FILE_OPEN_SOURCE_FOR_WRITE: ::DWORD = 0x00000004; +pub const COPY_FILE_ALLOW_DECRYPTED_DESTINATION: ::DWORD = 0x00000008; +pub const COPY_FILE_COPY_SYMLINK: ::DWORD = 0x00000800; +pub const COPY_FILE_NO_BUFFERING: ::DWORD = 0x00001000; +pub const COPY_FILE_REQUEST_SECURITY_PRIVILEGES: ::DWORD = 0x00002000; +pub const COPY_FILE_RESUME_FROM_PAUSE: ::DWORD = 0x00004000; +pub const COPY_FILE_NO_OFFLOAD: ::DWORD = 0x00040000; +pub const REPLACEFILE_WRITE_THROUGH: ::DWORD = 0x00000001; +pub const REPLACEFILE_IGNORE_MERGE_ERRORS: ::DWORD = 0x00000002; +pub const REPLACEFILE_IGNORE_ACL_ERRORS: ::DWORD = 0x00000004; +pub const PIPE_ACCESS_INBOUND: ::DWORD = 0x00000001; +pub const PIPE_ACCESS_OUTBOUND: ::DWORD = 0x00000002; +pub const PIPE_ACCESS_DUPLEX: ::DWORD = 0x00000003; +pub const PIPE_CLIENT_END: ::DWORD = 0x00000000; +pub const PIPE_SERVER_END: ::DWORD = 0x00000001; +pub const PIPE_WAIT: ::DWORD = 0x00000000; +pub const PIPE_NOWAIT: ::DWORD = 0x00000001; +pub const PIPE_READMODE_BYTE: ::DWORD = 0x00000000; +pub const PIPE_READMODE_MESSAGE: ::DWORD = 0x00000002; +pub const PIPE_TYPE_BYTE: ::DWORD = 0x00000000; +pub const PIPE_TYPE_MESSAGE: ::DWORD = 0x00000004; +pub const PIPE_ACCEPT_REMOTE_CLIENTS: ::DWORD = 0x00000000; +pub const PIPE_REJECT_REMOTE_CLIENTS: ::DWORD = 0x00000008; +pub const PIPE_UNLIMITED_INSTANCES: ::DWORD = 255; +//270 +pub const SECURITY_CONTEXT_TRACKING: ::DWORD = 0x00040000; +pub const SECURITY_EFFECTIVE_ONLY: ::DWORD = 0x00080000; +pub const SECURITY_SQOS_PRESENT: ::DWORD = 0x00100000; +pub const SECURITY_VALID_SQOS_FLAGS: ::DWORD = 0x001F0000; +//282 +pub type PFIBER_START_ROUTINE = Option; +pub type LPFIBER_START_ROUTINE = PFIBER_START_ROUTINE; +pub type PFIBER_CALLOUT_ROUTINE = Option ::LPVOID>; +//299 +pub type LPLDT_ENTRY = ::LPVOID; // TODO - fix this for 32-bit +//405 +STRUCT!{struct COMMPROP { + wPacketLength: ::WORD, + wPacketVersion: ::WORD, + dwServiceMask: ::DWORD, + dwReserved1: ::DWORD, + dwMaxTxQueue: ::DWORD, + dwMaxRxQueue: ::DWORD, + dwMaxBaud: ::DWORD, + dwProvSubType: ::DWORD, + dwProvCapabilities: ::DWORD, + dwSettableParams: ::DWORD, + dwSettableBaud: ::DWORD, + wSettableData: ::WORD, + wSettableStopParity: ::WORD, + dwCurrentTxQueue: ::DWORD, + dwCurrentRxQueue: ::DWORD, + dwProvSpec1: ::DWORD, + dwProvSpec2: ::DWORD, + wcProvChar: [::WCHAR; 1], +}} +pub type LPCOMMPROP = *mut COMMPROP; +//432 +STRUCT!{struct COMSTAT { + BitFields: ::DWORD, + cbInQue: ::DWORD, + cbOutQue : ::DWORD, +}} +BITFIELD!(COMSTAT BitFields: ::DWORD [ + fCtsHold set_fCtsHold[0..1], + fDsrHold set_fDsrHold[1..2], + fRlsdHold set_fRlsdHold[2..3], + fXoffHold set_fXoffHold[3..4], + fXoffSent set_fXoffSent[4..5], + fEof set_fEof[5..6], + fTxim set_fTxim[6..7], + fReserved set_fReserved[7..32], +]); +pub type LPCOMSTAT = *mut COMSTAT; +//460 +STRUCT!{struct DCB { + DCBlength: ::DWORD, + BaudRate: ::DWORD, + BitFields: ::DWORD, + wReserved: ::WORD, + XonLim: ::WORD, + XoffLim: ::WORD, + ByteSize: ::BYTE, + Parity: ::BYTE, + StopBits: ::BYTE, + XonChar: ::c_char, + XoffChar: ::c_char, + ErrorChar: ::c_char, + EofChar: ::c_char, + EvtChar: ::c_char, + wReserved1: ::WORD, +}} +BITFIELD!(DCB BitFields: ::DWORD [ + fBinary set_fBinary[0..1], + fParity set_fParity[1..2], + fOutxCtsFlow set_fOutxCtsFlow[2..3], + fOutxDsrFlow set_fOutxDsrFlow[3..4], + fDtrControl set_fDtrControl[4..6], + fDsrSensitivity set_fDsrSensitivity[6..7], + fTXContinueOnXoff set_fTXContinueOnXoff[7..8], + fOutX set_fOutX[8..9], + fInX set_fInX[9..10], + fErrorChar set_fErrorChar[10..11], + fNull set_fNull[11..12], + fRtsControl set_fRtsControl[12..14], + fAbortOnError set_fAbortOnError[14..15], + fDummy2 set_fDummy2[15..32], +]); +pub type LPDCB = *mut DCB; +STRUCT!{struct COMMTIMEOUTS { + ReadIntervalTimeout: ::DWORD, + ReadTotalTimeoutMultiplier: ::DWORD, + ReadTotalTimeoutConstant: ::DWORD, + WriteTotalTimeoutMultiplier: ::DWORD, + WriteTotalTimeoutConstant: ::DWORD, +}} +pub type LPCOMMTIMEOUTS = *mut COMMTIMEOUTS; +STRUCT!{struct COMMCONFIG { + dwSize: ::DWORD, + wVersion: ::WORD, + wReserved: ::WORD, + dcb: DCB, + dwProviderSubType: ::DWORD, + dwProviderOffset: ::DWORD, + dwProviderSize: ::DWORD, + wcProviderData: [::WCHAR; 1], +}} +pub type LPCOMMCONFIG = *mut COMMCONFIG; +//547 +STRUCT!{struct MEMORYSTATUS { + dwLength: ::DWORD, + dwMemoryLoad: ::DWORD, + dwTotalPhys: ::SIZE_T, + dwAvailPhys: ::SIZE_T, + dwTotalPageFile: ::SIZE_T, + dwAvailPageFile: ::SIZE_T, + dwTotalVirtual: ::SIZE_T, + dwAvailVirtual: ::SIZE_T, +}} +pub type LPMEMORYSTATUS = *mut MEMORYSTATUS; +//568 +pub const DEBUG_PROCESS: ::DWORD = 0x00000001; +pub const DEBUG_ONLY_THIS_PROCESS: ::DWORD = 0x00000002; +pub const CREATE_SUSPENDED: ::DWORD = 0x00000004; +pub const DETACHED_PROCESS: ::DWORD = 0x00000008; +pub const CREATE_NEW_CONSOLE: ::DWORD = 0x00000010; +pub const NORMAL_PRIORITY_CLASS: ::DWORD = 0x00000020; +pub const IDLE_PRIORITY_CLASS: ::DWORD = 0x00000040; +pub const HIGH_PRIORITY_CLASS: ::DWORD = 0x00000080; +pub const REALTIME_PRIORITY_CLASS: ::DWORD = 0x00000100; +pub const CREATE_NEW_PROCESS_GROUP: ::DWORD = 0x00000200; +pub const CREATE_UNICODE_ENVIRONMENT: ::DWORD = 0x00000400; +pub const CREATE_SEPARATE_WOW_VDM: ::DWORD = 0x00000800; +pub const CREATE_SHARED_WOW_VDM: ::DWORD = 0x00001000; +pub const CREATE_FORCEDOS: ::DWORD = 0x00002000; +pub const BELOW_NORMAL_PRIORITY_CLASS: ::DWORD = 0x00004000; +pub const ABOVE_NORMAL_PRIORITY_CLASS: ::DWORD = 0x00008000; +pub const INHERIT_PARENT_AFFINITY: ::DWORD = 0x00010000; +pub const INHERIT_CALLER_PRIORITY: ::DWORD = 0x00020000; +pub const CREATE_PROTECTED_PROCESS: ::DWORD = 0x00040000; +pub const EXTENDED_STARTUPINFO_PRESENT: ::DWORD = 0x00080000; +pub const PROCESS_MODE_BACKGROUND_BEGIN: ::DWORD = 0x00100000; +pub const PROCESS_MODE_BACKGROUND_END: ::DWORD = 0x00200000; +pub const CREATE_BREAKAWAY_FROM_JOB: ::DWORD = 0x01000000; +pub const CREATE_PRESERVE_CODE_AUTHZ_LEVEL: ::DWORD = 0x02000000; +pub const CREATE_DEFAULT_ERROR_MODE: ::DWORD = 0x04000000; +pub const CREATE_NO_WINDOW: ::DWORD = 0x08000000; +pub const PROFILE_USER: ::DWORD = 0x10000000; +pub const PROFILE_KERNEL: ::DWORD = 0x20000000; +pub const PROFILE_SERVER: ::DWORD = 0x40000000; +pub const CREATE_IGNORE_SYSTEM_DEFAULT: ::DWORD = 0x80000000; +//618 +pub const THREAD_PRIORITY_LOWEST: ::DWORD = ::THREAD_BASE_PRIORITY_MIN; +pub const THREAD_PRIORITY_BELOW_NORMAL: ::DWORD = THREAD_PRIORITY_LOWEST + 1; +pub const THREAD_PRIORITY_NORMAL: ::DWORD = 0; +pub const THREAD_PRIORITY_HIGHEST: ::DWORD = ::THREAD_BASE_PRIORITY_MAX; +pub const THREAD_PRIORITY_ABOVE_NORMAL: ::DWORD = THREAD_PRIORITY_HIGHEST - 1; +pub const THREAD_PRIORITY_ERROR_RETURN: ::DWORD = ::MAXLONG as ::DWORD; +pub const THREAD_PRIORITY_TIME_CRITICAL: ::DWORD = ::THREAD_BASE_PRIORITY_LOWRT; +pub const THREAD_PRIORITY_IDLE: ::DWORD = ::THREAD_BASE_PRIORITY_IDLE; +pub const THREAD_MODE_BACKGROUND_BEGIN: ::DWORD = 0x00010000; +pub const THREAD_MODE_BACKGROUND_END: ::DWORD = 0x00020000; +//666 +pub const DRIVE_UNKNOWN: ::DWORD = 0; +pub const DRIVE_NO_ROOT_DIR: ::DWORD = 1; +pub const DRIVE_REMOVABLE: ::DWORD = 2; +pub const DRIVE_FIXED: ::DWORD = 3; +pub const DRIVE_REMOTE: ::DWORD = 4; +pub const DRIVE_CDROM: ::DWORD = 5; +pub const DRIVE_RAMDISK: ::DWORD = 6; +pub const FILE_TYPE_UNKNOWN: ::DWORD = 0x0000; +pub const FILE_TYPE_DISK: ::DWORD = 0x0001; +pub const FILE_TYPE_CHAR: ::DWORD = 0x0002; +pub const FILE_TYPE_PIPE: ::DWORD = 0x0003; +pub const FILE_TYPE_REMOTE: ::DWORD = 0x8000; +pub const STD_INPUT_HANDLE: ::DWORD = 0xFFFFFFF6; +pub const STD_OUTPUT_HANDLE: ::DWORD = 0xFFFFFFF5; +pub const STD_ERROR_HANDLE: ::DWORD = 0xFFFFFFF4; +pub const NOPARITY: ::DWORD = 0; +pub const ODDPARITY: ::DWORD = 1; +pub const EVENPARITY: ::DWORD = 2; +pub const MARKPARITY: ::DWORD = 3; +pub const SPACEPARITY: ::DWORD = 4; +pub const ONESTOPBIT: ::DWORD = 0; +pub const ONE5STOPBITS: ::DWORD = 1; +pub const TWOSTOPBITS: ::DWORD = 2; +pub const IGNORE: ::DWORD = 0; +pub const INFINITE: ::DWORD = 0xFFFFFFFF; +//1729 +pub const SEM_FAILCRITICALERRORS: ::UINT = 0x0001; +pub const SEM_NOGPFAULTERRORBOX: ::UINT = 0x0002; +pub const SEM_NOALIGNMENTFAULTEXCEPT: ::UINT = 0x0004; +pub const SEM_NOOPENFILEERRORBOX: ::UINT = 0x8000; +//2320 +pub const FORMAT_MESSAGE_IGNORE_INSERTS: ::DWORD = 0x00000200; +pub const FORMAT_MESSAGE_FROM_STRING: ::DWORD = 0x00000400; +pub const FORMAT_MESSAGE_FROM_HMODULE: ::DWORD = 0x00000800; +pub const FORMAT_MESSAGE_FROM_SYSTEM: ::DWORD = 0x00001000; +pub const FORMAT_MESSAGE_ARGUMENT_ARRAY: ::DWORD = 0x00002000; +pub const FORMAT_MESSAGE_MAX_WIDTH_MASK: ::DWORD = 0x000000FF; +pub const FORMAT_MESSAGE_ALLOCATE_BUFFER: ::DWORD = 0x00000100; +//2873 +pub const STARTF_USESHOWWINDOW: ::DWORD = 0x00000001; +pub const STARTF_USESIZE: ::DWORD = 0x00000002; +pub const STARTF_USEPOSITION: ::DWORD = 0x00000004; +pub const STARTF_USECOUNTCHARS: ::DWORD = 0x00000008; +pub const STARTF_USEFILLATTRIBUTE: ::DWORD = 0x00000010; +pub const STARTF_RUNFULLSCREEN: ::DWORD = 0x00000020; +pub const STARTF_FORCEONFEEDBACK: ::DWORD = 0x00000040; +pub const STARTF_FORCEOFFFEEDBACK: ::DWORD = 0x00000080; +pub const STARTF_USESTDHANDLES: ::DWORD = 0x00000100; +pub const STARTF_USEHOTKEY: ::DWORD = 0x00000200; +pub const STARTF_TITLEISLINKNAME: ::DWORD = 0x00000800; +pub const STARTF_TITLEISAPPID: ::DWORD = 0x00001000; +pub const STARTF_PREVENTPINNING: ::DWORD = 0x00002000; +pub const STARTF_UNTRUSTEDSOURCE: ::DWORD = 0x00008000; +//5002 +pub type LPPROGRESS_ROUTINE = Option ::DWORD>; +//5095 +ENUM!{enum COPYFILE2_MESSAGE_TYPE { + COPYFILE2_CALLBACK_NONE = 0, + COPYFILE2_CALLBACK_CHUNK_STARTED, + COPYFILE2_CALLBACK_CHUNK_FINISHED, + COPYFILE2_CALLBACK_STREAM_STARTED, + COPYFILE2_CALLBACK_STREAM_FINISHED, + COPYFILE2_CALLBACK_POLL_CONTINUE, + COPYFILE2_CALLBACK_ERROR, + COPYFILE2_CALLBACK_MAX, +}} +ENUM!{enum COPYFILE2_MESSAGE_ACTION { + COPYFILE2_PROGRESS_CONTINUE = 0, + COPYFILE2_PROGRESS_CANCEL, + COPYFILE2_PROGRESS_STOP, + COPYFILE2_PROGRESS_QUIET, + COPYFILE2_PROGRESS_PAUSE, +}} +ENUM!{enum COPYFILE2_COPY_PHASE { + COPYFILE2_PHASE_NONE = 0, + COPYFILE2_PHASE_PREPARE_SOURCE, + COPYFILE2_PHASE_PREPARE_DEST, + COPYFILE2_PHASE_READ_SOURCE, + COPYFILE2_PHASE_WRITE_DESTINATION, + COPYFILE2_PHASE_SERVER_COPY, + COPYFILE2_PHASE_NAMEGRAFT_COPY, + COPYFILE2_PHASE_MAX, +}} +//5129 +STRUCT!{struct COPYFILE2_MESSAGE_ChunkStarted { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliChunkNumber: ::ULARGE_INTEGER, + uliChunkSize: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_ChunkFinished { + dwStreamNumber: ::DWORD, + dwFlags: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliChunkNumber: ::ULARGE_INTEGER, + uliChunkSize: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_StreamStarted { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliStreamSize: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_StreamFinished { + dwStreamNumber: ::DWORD, + dwReserved: ::DWORD, + hSourceFile: ::HANDLE, + hDestinationFile: ::HANDLE, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +STRUCT!{struct COPYFILE2_MESSAGE_PollContinue { + dwReserved: ::DWORD, +}} +STRUCT!{struct COPYFILE2_MESSAGE_Error { + CopyPhase: COPYFILE2_COPY_PHASE, + dwStreamNumber: ::DWORD, + hrFailure: ::HRESULT, + dwReserved: ::DWORD, + uliChunkNumber: ::ULARGE_INTEGER, + uliStreamSize: ::ULARGE_INTEGER, + uliStreamBytesTransferred: ::ULARGE_INTEGER, + uliTotalFileSize: ::ULARGE_INTEGER, + uliTotalBytesTransferred: ::ULARGE_INTEGER, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct COPYFILE2_MESSAGE { + Type: COPYFILE2_MESSAGE_TYPE, + dwPadding: ::DWORD, + Info: [u64; 8], +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct COPYFILE2_MESSAGE { + Type: COPYFILE2_MESSAGE_TYPE, + dwPadding: ::DWORD, + Info: [u64; 9], +}} +UNION!{COPYFILE2_MESSAGE, Info, ChunkStarted, ChunkStarted_mut, COPYFILE2_MESSAGE_ChunkStarted} +UNION!{COPYFILE2_MESSAGE, Info, ChunkFinished, ChunkFinished_mut, COPYFILE2_MESSAGE_ChunkFinished} +UNION!{COPYFILE2_MESSAGE, Info, StreamStarted, StreamStarted_mut, COPYFILE2_MESSAGE_StreamStarted} +UNION!{COPYFILE2_MESSAGE, Info, StreamFinished, StreamFinished_mut, + COPYFILE2_MESSAGE_StreamFinished} +UNION!{COPYFILE2_MESSAGE, Info, PollContinue, PollContinue_mut, COPYFILE2_MESSAGE_PollContinue} +UNION!{COPYFILE2_MESSAGE, Info, Error, Error_mut, COPYFILE2_MESSAGE_Error} +pub type PCOPYFILE2_PROGRESS_ROUTINE = Option COPYFILE2_MESSAGE_ACTION>; +STRUCT!{nodebug struct COPYFILE2_EXTENDED_PARAMETERS { + dwSize: ::DWORD, + dwCopyFlags: ::DWORD, + pfCancel: *mut ::BOOL, + pProgressRoutine: PCOPYFILE2_PROGRESS_ROUTINE, + pvCallbackContext: ::PVOID, +}} +//5377 +pub const MOVEFILE_REPLACE_EXISTING: ::DWORD = 0x00000001; +pub const MOVEFILE_COPY_ALLOWED: ::DWORD = 0x00000002; +pub const MOVEFILE_DELAY_UNTIL_REBOOT: ::DWORD = 0x00000004; +pub const MOVEFILE_WRITE_THROUGH: ::DWORD = 0x00000008; +pub const MOVEFILE_CREATE_HARDLINK: ::DWORD = 0x00000010; +pub const MOVEFILE_FAIL_IF_NOT_TRACKABLE: ::DWORD = 0x00000020; +//7176 +pub const HW_PROFILE_GUIDLEN: usize = 39; +//pub const MAX_PROFILE_LEN: usize = 80; +pub const DOCKINFO_UNDOCKED: ::DWORD = 0x1; +pub const DOCKINFO_DOCKED: ::DWORD = 0x2; +pub const DOCKINFO_USER_SUPPLIED: ::DWORD = 0x4; +pub const DOCKINFO_USER_UNDOCKED: ::DWORD = DOCKINFO_USER_SUPPLIED | DOCKINFO_UNDOCKED; +pub const DOCKINFO_USER_DOCKED: ::DWORD = DOCKINFO_USER_SUPPLIED | DOCKINFO_DOCKED; +STRUCT!{nodebug struct HW_PROFILE_INFOA { + dwDockInfo: ::DWORD, + szHwProfileGuid: [::CHAR; HW_PROFILE_GUIDLEN], + szHwProfileName: [::CHAR; ::MAX_PROFILE_LEN], +}} +pub type LPHW_PROFILE_INFOA = *mut HW_PROFILE_INFOA; +STRUCT!{nodebug struct HW_PROFILE_INFOW { + dwDockInfo: ::DWORD, + szHwProfileGuid: [::WCHAR; HW_PROFILE_GUIDLEN], + szHwProfileName: [::WCHAR; ::MAX_PROFILE_LEN], +}} +pub type LPHW_PROFILE_INFOW = *mut HW_PROFILE_INFOW; +//7574 +STRUCT!{struct ACTCTXA { + cbSize: ::ULONG, + dwFlags: ::DWORD, + lpSource: ::LPCSTR, + wProcessorArchitecture: ::USHORT, + wLangId: ::LANGID, + lpAssemblyDirectory: ::LPCSTR, + lpResourceName: ::LPCSTR, + lpApplicationName: ::LPCSTR, + hModule: ::HMODULE, +}} +pub type PACTCTXA = *mut ACTCTXA; +STRUCT!{struct ACTCTXW { + cbSize: ::ULONG, + dwFlags: ::DWORD, + lpSource: ::LPCWSTR, + wProcessorArchitecture: ::USHORT, + wLangId: ::LANGID, + lpAssemblyDirectory: ::LPCWSTR, + lpResourceName: ::LPCWSTR, + lpApplicationName: ::LPCWSTR, + hModule: ::HMODULE, +}} +pub type PACTCTXW = *mut ACTCTXW; +pub type PCACTCTXA = *const ACTCTXA; +pub type PCACTCTXW = *const ACTCTXW; +// +pub type PUMS_CONTEXT = *mut ::c_void; +pub type PUMS_COMPLETION_LIST = *mut ::c_void; +pub type UMS_THREAD_INFO_CLASS = ::RTL_UMS_THREAD_INFO_CLASS; +pub type PUMS_THREAD_INFO_CLASS = *mut UMS_THREAD_INFO_CLASS; +pub type PUMS_SCHEDULER_ENTRY_POINT = ::PRTL_UMS_SCHEDULER_ENTRY_POINT; +STRUCT!{nodebug struct UMS_SCHEDULER_STARTUP_INFO { + UmsVersion: ::ULONG, + CompletionList: PUMS_COMPLETION_LIST, + SchedulerProc: PUMS_SCHEDULER_ENTRY_POINT, + SchedulerParam: ::PVOID, +}} +pub type PUMS_SCHEDULER_STARTUP_INFO = *mut UMS_SCHEDULER_STARTUP_INFO; +STRUCT!{struct UMS_SYSTEM_THREAD_INFORMATION { + UmsVersion: ::ULONG, + BitFields: ::ULONG, +}} +BITFIELD!(UMS_SYSTEM_THREAD_INFORMATION BitFields: ::ULONG [ + IsUmsSchedulerThread set_IsUmsSchedulerThread[0..1], + IsUmsWorkerThread set_IsUmsWorkerThread[1..2], +]); +UNION!( + UMS_SYSTEM_THREAD_INFORMATION, BitFields, ThreadUmsFlags, ThreadUmsFlags_mut, + ::ULONG +); +pub type PUMS_SYSTEM_THREAD_INFORMATION = *mut UMS_SYSTEM_THREAD_INFORMATION; +STRUCT!{struct ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA { + lpInformation: ::PVOID, + lpSectionBase: ::PVOID, + ulSectionLength: ::ULONG, + lpSectionGlobalDataBase: ::PVOID, + ulSectionGlobalDataLength: ::ULONG, +}} +pub type PACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA = + *mut ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA; +pub type PCACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA = + *const ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA; +STRUCT!{struct ACTCTX_SECTION_KEYED_DATA { + cbSize: ::ULONG, + ulDataFormatVersion: ::ULONG, + lpData: ::PVOID, + ulLength: ::ULONG, + lpSectionGlobalData: ::PVOID, + ulSectionGlobalDataLength: ::ULONG, + lpSectionBase: ::PVOID, + ulSectionTotalLength: ::ULONG, + hActCtx: ::HANDLE, + ulAssemblyRosterIndex: ::ULONG, + ulFlags: ::ULONG, + AssemblyMetadata: ACTCTX_SECTION_KEYED_DATA_ASSEMBLY_METADATA, +}} +pub type PACTCTX_SECTION_KEYED_DATA = *mut ACTCTX_SECTION_KEYED_DATA; +pub type PCACTCTX_SECTION_KEYED_DATA = *const ACTCTX_SECTION_KEYED_DATA; +ENUM!{enum STREAM_INFO_LEVELS { + FindStreamInfoStandard, + FindStreamInfoMaxInfoLevel, +}} +ENUM!{enum PROCESS_INFORMATION_CLASS { + ProcessMemoryPriority, + ProcessInformationClassMax, +}} +ENUM!{enum DEP_SYSTEM_POLICY_TYPE { + DEPPolicyAlwaysOff = 0, + DEPPolicyAlwaysOn, + DEPPolicyOptIn, + DEPPolicyOptOut, + DEPTotalPolicyCount, +}} +ENUM!{enum PIPE_ATTRIBUTE_TYPE { + PipeAttribute, + PipeConnectionAttribute, + PipeHandleAttribute, +}} +pub type APPLICATION_RECOVERY_CALLBACK = Option ::DWORD>; +STRUCT!{struct SYSTEM_POWER_STATUS { + ACLineStatus: ::BYTE, + BatteryFlag: ::BYTE, + BatteryLifePercent: ::BYTE, + Reserved1: ::BYTE, + BatteryLifeTime: ::DWORD, + BatteryFullLifeTime: ::DWORD, +}} +pub type LPSYSTEM_POWER_STATUS = *mut SYSTEM_POWER_STATUS; +pub const OFS_MAXPATHNAME: usize = 128; +STRUCT!{nodebug struct OFSTRUCT { + cBytes: ::BYTE, + fFixedDisk: ::BYTE, + nErrCode: ::WORD, + Reserved1: ::WORD, + Reserved2: ::WORD, + szPathName: [::CHAR; OFS_MAXPATHNAME], +}} +pub type POFSTRUCT = *mut OFSTRUCT; +pub type LPOFSTRUCT = *mut OFSTRUCT; +ENUM!{enum FILE_ID_TYPE { + FileIdType, + ObjectIdType, + ExtendedFileIdType, + MaximumFileIdType, +}} +STRUCT!{struct FILE_ID_DESCRIPTOR { + dwSize: ::DWORD, + Type: FILE_ID_TYPE, + ObjectId: ::GUID, +}} +UNION!(FILE_ID_DESCRIPTOR, ObjectId, FileId, FileId_mut, ::LARGE_INTEGER); +UNION!(FILE_ID_DESCRIPTOR, ObjectId, ExtendedFileId, ExtendedFileId_mut, ::FILE_ID_128); +pub type LPFILE_ID_DESCRIPTOR = *mut FILE_ID_DESCRIPTOR; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wincon.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wincon.rs new file mode 100644 index 0000000..23c2e74 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wincon.rs @@ -0,0 +1,198 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This module contains the public data structures, data types, and procedures exported by the NT +//! console subsystem. +STRUCT!{struct COORD { + X: ::SHORT, + Y: ::SHORT, +}} +pub type PCOORD = *mut COORD; +STRUCT!{struct SMALL_RECT { + Left: ::SHORT, + Top: ::SHORT, + Right: ::SHORT, + Bottom: ::SHORT, +}} +pub type PSMALL_RECT = *mut SMALL_RECT; +STRUCT!{struct KEY_EVENT_RECORD { + bKeyDown: ::BOOL, + wRepeatCount: ::WORD, + wVirtualKeyCode: ::WORD, + wVirtualScanCode: ::WORD, + UnicodeChar: ::WCHAR, + dwControlKeyState: ::DWORD, +}} +UNION!{KEY_EVENT_RECORD, UnicodeChar, AsciiChar, AsciiChar_mut, ::CHAR} +pub type PKEY_EVENT_RECORD = *mut KEY_EVENT_RECORD; +pub const RIGHT_ALT_PRESSED: ::DWORD = 0x0001; +pub const LEFT_ALT_PRESSED: ::DWORD = 0x0002; +pub const RIGHT_CTRL_PRESSED: ::DWORD = 0x0004; +pub const LEFT_CTRL_PRESSED: ::DWORD = 0x0008; +pub const SHIFT_PRESSED: ::DWORD = 0x0010; +pub const NUMLOCK_ON: ::DWORD = 0x0020; +pub const SCROLLLOCK_ON: ::DWORD = 0x0040; +pub const CAPSLOCK_ON: ::DWORD = 0x0080; +pub const ENHANCED_KEY: ::DWORD = 0x0100; +pub const NLS_DBCSCHAR: ::DWORD = 0x00010000; +pub const NLS_ALPHANUMERIC: ::DWORD = 0x00000000; +pub const NLS_KATAKANA: ::DWORD = 0x00020000; +pub const NLS_HIRAGANA: ::DWORD = 0x00040000; +pub const NLS_ROMAN: ::DWORD = 0x00400000; +pub const NLS_IME_CONVERSION: ::DWORD = 0x00800000; +pub const NLS_IME_DISABLE: ::DWORD = 0x20000000; +STRUCT!{struct MOUSE_EVENT_RECORD { + dwMousePosition: COORD, + dwButtonState: ::DWORD, + dwControlKeyState: ::DWORD, + dwEventFlags: ::DWORD, +}} +pub type PMOUSE_EVENT_RECORD = *mut MOUSE_EVENT_RECORD; +pub const FROM_LEFT_1ST_BUTTON_PRESSED: ::DWORD = 0x0001; +pub const RIGHTMOST_BUTTON_PRESSED: ::DWORD = 0x0002; +pub const FROM_LEFT_2ND_BUTTON_PRESSED: ::DWORD = 0x0004; +pub const FROM_LEFT_3RD_BUTTON_PRESSED: ::DWORD = 0x0008; +pub const FROM_LEFT_4TH_BUTTON_PRESSED: ::DWORD = 0x0010; +pub const MOUSE_MOVED: ::DWORD = 0x0001; +pub const DOUBLE_CLICK: ::DWORD = 0x0002; +pub const MOUSE_WHEELED: ::DWORD = 0x0004; +pub const MOUSE_HWHEELED: ::DWORD = 0x0008; +STRUCT!{struct WINDOW_BUFFER_SIZE_RECORD { + dwSize: COORD, +}} +pub type PWINDOW_BUFFER_SIZE_RECORD = *mut WINDOW_BUFFER_SIZE_RECORD; +STRUCT!{struct MENU_EVENT_RECORD { + dwCommandId: ::UINT, +}} +pub type PMENU_EVENT_RECORD = *mut MENU_EVENT_RECORD; +STRUCT!{struct FOCUS_EVENT_RECORD { + bSetFocus: ::BOOL, +}} +pub type PFOCUS_EVENT_RECORD = *mut FOCUS_EVENT_RECORD; +STRUCT!{struct INPUT_RECORD { + EventType: ::WORD, + Event: [u32; 4], +}} +UNION!{INPUT_RECORD, Event, KeyEvent, KeyEvent_mut, KEY_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, MouseEvent, MouseEvent_mut, MOUSE_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, WindowBufferSizeEvent, WindowBufferSizeEvent_mut, + WINDOW_BUFFER_SIZE_RECORD} +UNION!{INPUT_RECORD, Event, MenuEvent, MenuEvent_mut, MENU_EVENT_RECORD} +UNION!{INPUT_RECORD, Event, FocusEvent, FocusEvent_mut, FOCUS_EVENT_RECORD} +pub type PINPUT_RECORD = *mut INPUT_RECORD; +pub const KEY_EVENT: ::WORD = 0x0001; +pub const MOUSE_EVENT: ::WORD = 0x0002; +pub const WINDOW_BUFFER_SIZE_EVENT: ::WORD = 0x0004; +pub const MENU_EVENT: ::WORD = 0x0008; +pub const FOCUS_EVENT: ::WORD = 0x0010; +STRUCT!{struct CHAR_INFO { + UnicodeChar: ::WCHAR, + Attributes: ::WORD, +}} +UNION!{CHAR_INFO, UnicodeChar, AsciiChar, AsciiChar_mut, ::CHAR} +pub type PCHAR_INFO = *mut CHAR_INFO; +pub const FOREGROUND_BLUE: ::DWORD = 0x0001; +pub const FOREGROUND_GREEN: ::DWORD = 0x0002; +pub const FOREGROUND_RED: ::DWORD = 0x0004; +pub const FOREGROUND_INTENSITY: ::DWORD = 0x0008; +pub const BACKGROUND_BLUE: ::DWORD = 0x0010; +pub const BACKGROUND_GREEN: ::DWORD = 0x0020; +pub const BACKGROUND_RED: ::DWORD = 0x0040; +pub const BACKGROUND_INTENSITY: ::DWORD = 0x0080; +pub const COMMON_LVB_LEADING_BYTE: ::DWORD = 0x0100; +pub const COMMON_LVB_TRAILING_BYTE: ::DWORD = 0x0200; +pub const COMMON_LVB_GRID_HORIZONTAL: ::DWORD = 0x0400; +pub const COMMON_LVB_GRID_LVERTICAL: ::DWORD = 0x0800; +pub const COMMON_LVB_GRID_RVERTICAL: ::DWORD = 0x1000; +pub const COMMON_LVB_REVERSE_VIDEO: ::DWORD = 0x4000; +pub const COMMON_LVB_UNDERSCORE: ::DWORD = 0x8000; +pub const COMMON_LVB_SBCSDBCS: ::DWORD = 0x0300; +STRUCT!{struct CONSOLE_SCREEN_BUFFER_INFO { + dwSize: COORD, + dwCursorPosition: COORD, + wAttributes: ::WORD, + srWindow: SMALL_RECT, + dwMaximumWindowSize: COORD, +}} +pub type PCONSOLE_SCREEN_BUFFER_INFO = *mut CONSOLE_SCREEN_BUFFER_INFO; +STRUCT!{struct CONSOLE_SCREEN_BUFFER_INFOEX { + cbSize: ::ULONG, + dwSize: COORD, + dwCursorPosition: COORD, + wAttributes: ::WORD, + srWindow: SMALL_RECT, + dwMaximumWindowSize: COORD, + wPopupAttributes: ::WORD, + bFullscreenSupported: ::BOOL, + ColorTable: [::COLORREF; 16], +}} +pub type PCONSOLE_SCREEN_BUFFER_INFOEX = *mut CONSOLE_SCREEN_BUFFER_INFOEX; +STRUCT!{struct CONSOLE_CURSOR_INFO { + dwSize: ::DWORD, + bVisible: ::BOOL, +}} +pub type PCONSOLE_CURSOR_INFO = *mut CONSOLE_CURSOR_INFO; +STRUCT!{struct CONSOLE_FONT_INFO { + nFont: ::DWORD, + dwFontSize: ::COORD, +}} +pub type PCONSOLE_FONT_INFO = *mut CONSOLE_FONT_INFO; +STRUCT!{struct CONSOLE_FONT_INFOEX { + cbSize: ::ULONG, + nFont: ::DWORD, + dwFontSize: COORD, + FontFamily: ::UINT, + FontWeight: ::UINT, + FaceName: [::WCHAR; ::LF_FACESIZE], +}} +pub type PCONSOLE_FONT_INFOEX = *mut CONSOLE_FONT_INFOEX; +pub const HISTORY_NO_DUP_FLAG: ::DWORD = 0x1; +STRUCT!{struct CONSOLE_HISTORY_INFO { + cbSize: ::UINT, + HistoryBufferSize: ::UINT, + NumberOfHistoryBuffers: ::UINT, + dwFlags: ::DWORD, +}} +pub type PCONSOLE_HISTORY_INFO = *mut CONSOLE_HISTORY_INFO; +STRUCT!{struct CONSOLE_SELECTION_INFO { + dwFlags: ::DWORD, + dwSelectionAnchor: COORD, + srSelection: SMALL_RECT, +}} +pub type PCONSOLE_SELECTION_INFO = *mut CONSOLE_SELECTION_INFO; +pub const CONSOLE_NO_SELECTION: ::DWORD = 0x0000; +pub const CONSOLE_SELECTION_IN_PROGRESS: ::DWORD = 0x0001; +pub const CONSOLE_SELECTION_NOT_EMPTY: ::DWORD = 0x0002; +pub const CONSOLE_MOUSE_SELECTION: ::DWORD = 0x0004; +pub const CONSOLE_MOUSE_DOWN: ::DWORD = 0x0008; +pub type PHANDLER_ROUTINE = Option ::BOOL>; +pub const CTRL_C_EVENT: ::DWORD = 0; +pub const CTRL_BREAK_EVENT: ::DWORD = 1; +pub const CTRL_CLOSE_EVENT: ::DWORD = 2; +pub const CTRL_LOGOFF_EVENT: ::DWORD = 5; +pub const CTRL_SHUTDOWN_EVENT: ::DWORD = 6; +pub const ENABLE_PROCESSED_INPUT: ::DWORD = 0x0001; +pub const ENABLE_LINE_INPUT: ::DWORD = 0x0002; +pub const ENABLE_ECHO_INPUT: ::DWORD = 0x0004; +pub const ENABLE_WINDOW_INPUT: ::DWORD = 0x0008; +pub const ENABLE_MOUSE_INPUT: ::DWORD = 0x0010; +pub const ENABLE_INSERT_MODE: ::DWORD = 0x0020; +pub const ENABLE_QUICK_EDIT_MODE: ::DWORD = 0x0040; +pub const ENABLE_EXTENDED_FLAGS: ::DWORD = 0x0080; +pub const ENABLE_AUTO_POSITION: ::DWORD = 0x0100; +pub const ENABLE_PROCESSED_OUTPUT: ::DWORD = 0x0001; +pub const ENABLE_WRAP_AT_EOL_OUTPUT: ::DWORD = 0x0002; +pub const CONSOLE_REAL_OUTPUT_HANDLE: *mut ::c_void = -2isize as *mut ::c_void; +pub const CONSOLE_REAL_INPUT_HANDLE: *mut ::c_void = -3isize as *mut ::c_void; +pub const ATTACH_PARENT_PROCESS: ::DWORD = 0xFFFFFFFF; +STRUCT!{struct CONSOLE_READCONSOLE_CONTROL { + nLength: ::ULONG, + nInitialChars: ::ULONG, + dwCtrlWakeupMask: ::ULONG, + dwControlKeyState: ::ULONG, +}} +pub type PCONSOLE_READCONSOLE_CONTROL = *mut CONSOLE_READCONSOLE_CONTROL; +pub const CONSOLE_TEXTMODE_BUFFER: ::DWORD = 1; +pub const CONSOLE_FULLSCREEN: ::DWORD = 1; +pub const CONSOLE_FULLSCREEN_HARDWARE: ::DWORD = 2; +pub const CONSOLE_FULLSCREEN_MODE: ::DWORD = 1; +pub const CONSOLE_WINDOWED_MODE: ::DWORD = 2; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wincred.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wincred.rs new file mode 100644 index 0000000..af98bd9 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wincred.rs @@ -0,0 +1,209 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Authentication API Prototypes and Definitions +pub const NERR_BASE: ::DWORD = 2100; +pub const NERR_PasswordExpired: ::DWORD = NERR_BASE+142; +pub const CRED_MAX_STRING_LENGTH: ::DWORD = 256; +pub const CRED_MAX_USERNAME_LENGTH: ::DWORD = 256+1+256; +pub const CRED_MAX_GENERIC_TARGET_NAME_LENGTH: ::DWORD = 32767; +pub const CRED_MAX_DOMAIN_TARGET_NAME_LENGTH: ::DWORD = 256+1+80; +pub const CRED_MAX_TARGETNAME_NAMESPACE_LENGTH: ::DWORD = 256; +pub const CRED_MAX_TARGETNAME_ATTRIBUTE_LENGTH: ::DWORD = 256; +pub const CRED_MAX_VALUE_SIZE: ::DWORD = 256; +pub const CRED_MAX_ATTRIBUTES: ::DWORD = 64; +pub const CRED_LOGON_TYPES_MASK: ::DWORD = 0xF000; +pub const CRED_FLAGS_PASSWORD_FOR_CERT: ::DWORD = 0x0001; +pub const CRED_FLAGS_PROMPT_NOW: ::DWORD = 0x0002; +pub const CRED_FLAGS_USERNAME_TARGET: ::DWORD = 0x0004; +pub const CRED_FLAGS_OWF_CRED_BLOB: ::DWORD = 0x0008; +pub const CRED_FLAGS_REQUIRE_CONFIRMATION: ::DWORD = 0x0010; +pub const CRED_FLAGS_WILDCARD_MATCH: ::DWORD = 0x0020; +pub const CRED_FLAGS_VALID_FLAGS: ::DWORD = 0xF03F; +pub const CRED_FLAGS_VALID_INPUT_FLAGS: ::DWORD = 0xF01F; +pub const CRED_TYPE_GENERIC: ::DWORD = 1; +pub const CRED_TYPE_DOMAIN_PASSWORD: ::DWORD = 2; +pub const CRED_TYPE_DOMAIN_CERTIFICATE: ::DWORD = 3; +pub const CRED_TYPE_DOMAIN_VISIBLE_PASSWORD: ::DWORD = 4; +pub const CRED_TYPE_GENERIC_CERTIFICATE: ::DWORD = 5; +pub const CRED_TYPE_DOMAIN_EXTENDED: ::DWORD = 6; +pub const CRED_TYPE_MAXIMUM: ::DWORD = 7; +pub const CRED_TYPE_MAXIMUM_EX: ::DWORD = CRED_TYPE_MAXIMUM+1000; +pub const CRED_MAX_CREDENTIAL_BLOB_SIZE: ::DWORD = 5*512; +pub const CRED_PERSIST_NONE: ::DWORD = 0; +pub const CRED_PERSIST_SESSION: ::DWORD = 1; +pub const CRED_PERSIST_LOCAL_MACHINE: ::DWORD = 2; +pub const CRED_PERSIST_ENTERPRISE: ::DWORD = 3; +STRUCT!{struct CREDENTIAL_ATTRIBUTEA { + Keyword: ::LPSTR, + Flags: ::DWORD, + ValueSize: ::DWORD, + Value: ::LPBYTE, +}} +pub type PCREDENTIAL_ATTRIBUTEA = *mut CREDENTIAL_ATTRIBUTEA; +STRUCT!{struct CREDENTIAL_ATTRIBUTEW { + Keyword: ::LPWSTR, + Flags: ::DWORD, + ValueSize: ::DWORD, + Value: ::LPBYTE, +}} +pub type PCREDENTIAL_ATTRIBUTEW = *mut CREDENTIAL_ATTRIBUTEW; +STRUCT!{struct CREDENTIALA { + Flags: ::DWORD, + Type: ::DWORD, + TargetName: ::LPSTR, + Comment: ::LPSTR, + LastWritten: ::FILETIME, + CredentialBlobSize: ::DWORD, + CredentialBlob: ::LPBYTE, + Persist: ::DWORD, + AttributeCount: ::DWORD, + Attributes: PCREDENTIAL_ATTRIBUTEA, + TargetAlias: ::LPSTR, + UserName: ::LPSTR, +}} +pub type PCREDENTIALA = *mut CREDENTIALA; +STRUCT!{struct CREDENTIALW { + Flags: ::DWORD, + Type: ::DWORD, + TargetName: ::LPWSTR, + Comment: ::LPWSTR, + LastWritten: ::FILETIME, + CredentialBlobSize: ::DWORD, + CredentialBlob: ::LPBYTE, + Persist: ::DWORD, + AttributeCount: ::DWORD, + Attributes: PCREDENTIAL_ATTRIBUTEW, + TargetAlias: ::LPWSTR, + UserName: ::LPWSTR, +}} +pub type PCREDENTIALW = *mut CREDENTIALW; +pub const CRED_TI_SERVER_FORMAT_UNKNOWN: ::ULONG = 0x0001; +pub const CRED_TI_DOMAIN_FORMAT_UNKNOWN: ::ULONG = 0x0002; +pub const CRED_TI_ONLY_PASSWORD_REQUIRED: ::ULONG = 0x0004; +pub const CRED_TI_USERNAME_TARGET: ::ULONG = 0x0008; +pub const CRED_TI_CREATE_EXPLICIT_CRED: ::ULONG = 0x0010; +pub const CRED_TI_WORKGROUP_MEMBER: ::ULONG = 0x0020; +pub const CRED_TI_VALID_FLAGS: ::ULONG = 0xF07F; +STRUCT!{struct CREDENTIAL_TARGET_INFORMATIONA { + TargetName: ::LPSTR, + NetbiosServerName: ::LPSTR, + DnsServerName: ::LPSTR, + NetbiosDomainName: ::LPSTR, + DnsDomainName: ::LPSTR, + DnsTreeName: ::LPSTR, + PackageName: ::LPSTR, + Flags: ::ULONG, + CredTypeCount: ::DWORD, + CredTypes: ::LPDWORD, +}} +pub type PCREDENTIAL_TARGET_INFORMATIONA = *mut CREDENTIAL_TARGET_INFORMATIONA; +STRUCT!{struct CREDENTIAL_TARGET_INFORMATIONW { + TargetName: ::LPWSTR, + NetbiosServerName: ::LPWSTR, + DnsServerName: ::LPWSTR, + NetbiosDomainName: ::LPWSTR, + DnsDomainName: ::LPWSTR, + DnsTreeName: ::LPWSTR, + PackageName: ::LPWSTR, + Flags: ::ULONG, + CredTypeCount: ::DWORD, + CredTypes: ::LPDWORD, +}} +pub type PCREDENTIAL_TARGET_INFORMATIONW = *mut CREDENTIAL_TARGET_INFORMATIONW; +pub const CERT_HASH_LENGTH: usize = 20; +STRUCT!{struct CERT_CREDENTIAL_INFO { + cbSize: ::ULONG, + rgbHashOfCert: [::UCHAR; CERT_HASH_LENGTH], +}} +pub type PCERT_CREDENTIAL_INFO = *mut CERT_CREDENTIAL_INFO; +STRUCT!{struct USERNAME_TARGET_CREDENTIAL_INFO { + UserName: ::LPWSTR, +}} +pub type PUSERNAME_TARGET_CREDENTIAL_INFO = *mut USERNAME_TARGET_CREDENTIAL_INFO; +STRUCT!{struct BINARY_BLOB_CREDENTIAL_INFO { + cbBlob: ::ULONG, + pbBlob: ::LPBYTE, +}} +pub type PBINARY_BLOB_CREDENTIAL_INFO = *mut BINARY_BLOB_CREDENTIAL_INFO; +ENUM!{enum CRED_MARSHAL_TYPE { + CertCredential = 1, + UsernameTargetCredential, + BinaryBlobCredential, + UsernameForPackedCredentials, +}} +pub type PCRED_MARSHAL_TYPE = *mut CRED_MARSHAL_TYPE; +ENUM!{enum CRED_PROTECTION_TYPE { + CredUnprotected, + CredUserProtection, + CredTrustedProtection, +}} +pub type PCRED_PROTECTION_TYPE = *mut CRED_PROTECTION_TYPE; +pub const CRED_PACK_PROTECTED_CREDENTIALS: ::DWORD = 0x1; +pub const CRED_PACK_WOW_BUFFER: ::DWORD = 0x2; +pub const CRED_PACK_GENERIC_CREDENTIALS: ::DWORD = 0x4; +pub const CRED_PACK_ID_PROVIDER_CREDENTIALS: ::DWORD = 0x8; +STRUCT!{struct CREDUI_INFOA { + cbSize: ::DWORD, + hwndParent: ::HWND, + pszMessageText: ::PCSTR, + pszCaptionText: ::PCSTR, + hbmBanner: ::HBITMAP, +}} +pub type PCREDUI_INFOA = *mut CREDUI_INFOA; +STRUCT!{struct CREDUI_INFOW { + cbSize: ::DWORD, + hwndParent: ::HWND, + pszMessageText: ::PCWSTR, + pszCaptionText: ::PCWSTR, + hbmBanner: ::HBITMAP, +}} +pub type PCREDUI_INFOW = *mut CREDUI_INFOW; +pub const CREDUI_MAX_MESSAGE_LENGTH: ::DWORD = 1024; +pub const CREDUI_MAX_CAPTION_LENGTH: ::DWORD = 128; +pub const CREDUI_MAX_GENERIC_TARGET_LENGTH: ::DWORD = CRED_MAX_GENERIC_TARGET_NAME_LENGTH; +pub const CREDUI_MAX_DOMAIN_TARGET_LENGTH: ::DWORD = CRED_MAX_DOMAIN_TARGET_NAME_LENGTH; +pub const CREDUI_MAX_USERNAME_LENGTH: ::DWORD = CRED_MAX_USERNAME_LENGTH; +pub const CREDUI_MAX_PASSWORD_LENGTH: ::DWORD = 512 / 2; +pub const CREDUI_FLAGS_INCORRECT_PASSWORD: ::DWORD = 0x00001; +pub const CREDUI_FLAGS_DO_NOT_PERSIST: ::DWORD = 0x00002; +pub const CREDUI_FLAGS_REQUEST_ADMINISTRATOR: ::DWORD = 0x00004; +pub const CREDUI_FLAGS_EXCLUDE_CERTIFICATES: ::DWORD = 0x00008; +pub const CREDUI_FLAGS_REQUIRE_CERTIFICATE: ::DWORD = 0x00010; +pub const CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX: ::DWORD = 0x00040; +pub const CREDUI_FLAGS_ALWAYS_SHOW_UI: ::DWORD = 0x00080; +pub const CREDUI_FLAGS_REQUIRE_SMARTCARD: ::DWORD = 0x00100; +pub const CREDUI_FLAGS_PASSWORD_ONLY_OK: ::DWORD = 0x00200; +pub const CREDUI_FLAGS_VALIDATE_USERNAME: ::DWORD = 0x00400; +pub const CREDUI_FLAGS_COMPLETE_USERNAME: ::DWORD = 0x00800; +pub const CREDUI_FLAGS_PERSIST: ::DWORD = 0x01000; +pub const CREDUI_FLAGS_SERVER_CREDENTIAL: ::DWORD = 0x04000; +pub const CREDUI_FLAGS_EXPECT_CONFIRMATION: ::DWORD = 0x20000; +pub const CREDUI_FLAGS_GENERIC_CREDENTIALS: ::DWORD = 0x40000; +pub const CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS: ::DWORD = 0x80000; +pub const CREDUI_FLAGS_KEEP_USERNAME: ::DWORD = 0x100000; +pub const CREDUI_FLAGS_PROMPT_VALID: ::DWORD = CREDUI_FLAGS_INCORRECT_PASSWORD + | CREDUI_FLAGS_DO_NOT_PERSIST | CREDUI_FLAGS_REQUEST_ADMINISTRATOR + | CREDUI_FLAGS_EXCLUDE_CERTIFICATES | CREDUI_FLAGS_REQUIRE_CERTIFICATE + | CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX | CREDUI_FLAGS_ALWAYS_SHOW_UI + | CREDUI_FLAGS_REQUIRE_SMARTCARD | CREDUI_FLAGS_PASSWORD_ONLY_OK + | CREDUI_FLAGS_VALIDATE_USERNAME | CREDUI_FLAGS_COMPLETE_USERNAME | CREDUI_FLAGS_PERSIST + | CREDUI_FLAGS_SERVER_CREDENTIAL | CREDUI_FLAGS_EXPECT_CONFIRMATION + | CREDUI_FLAGS_GENERIC_CREDENTIALS | CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS + | CREDUI_FLAGS_KEEP_USERNAME; +pub const CREDUIWIN_GENERIC: ::DWORD = 0x00000001; +pub const CREDUIWIN_CHECKBOX: ::DWORD = 0x00000002; +pub const CREDUIWIN_AUTHPACKAGE_ONLY: ::DWORD = 0x00000010; +pub const CREDUIWIN_IN_CRED_ONLY: ::DWORD = 0x00000020; +pub const CREDUIWIN_ENUMERATE_ADMINS: ::DWORD = 0x00000100; +pub const CREDUIWIN_ENUMERATE_CURRENT_USER: ::DWORD = 0x00000200; +pub const CREDUIWIN_SECURE_PROMPT: ::DWORD = 0x00001000; +pub const CREDUIWIN_PREPROMPTING: ::DWORD = 0x00002000; +pub const CREDUIWIN_PACK_32_WOW: ::DWORD = 0x10000000; +pub const CREDUIWIN_VALID_FLAGS: ::DWORD = CREDUIWIN_GENERIC | CREDUIWIN_CHECKBOX + | CREDUIWIN_AUTHPACKAGE_ONLY | CREDUIWIN_IN_CRED_ONLY | CREDUIWIN_ENUMERATE_ADMINS + | CREDUIWIN_ENUMERATE_CURRENT_USER | CREDUIWIN_SECURE_PROMPT | CREDUIWIN_PREPROMPTING + | CREDUIWIN_PACK_32_WOW; +pub const CRED_PRESERVE_CREDENTIAL_BLOB: ::DWORD = 0x1; +pub const CRED_ENUMERATE_ALL_CREDENTIALS: ::DWORD = 0x1; +pub const CRED_CACHE_TARGET_INFORMATION: ::DWORD = 0x1; +pub const CRED_ALLOW_NAME_RESOLUTION: ::DWORD = 0x1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wincrypt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wincrypt.rs new file mode 100644 index 0000000..5b3e748 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wincrypt.rs @@ -0,0 +1,2206 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Cryptographic API Prototypes and Definitions +//108 +pub const ALG_CLASS_ANY: ALG_ID = 0; +pub const ALG_CLASS_SIGNATURE: ALG_ID = 1 << 13; +pub const ALG_CLASS_MSG_ENCRYPT: ALG_ID = 2 << 13; +pub const ALG_CLASS_DATA_ENCRYPT: ALG_ID = 3 << 13; +pub const ALG_CLASS_HASH: ALG_ID = 4 << 13; +pub const ALG_CLASS_KEY_EXCHANGE: ALG_ID = 5 << 13; +pub const ALG_CLASS_ALL: ALG_ID = 7 << 13; +pub const ALG_TYPE_ANY: ALG_ID = 0; +pub const ALG_TYPE_DSS: ALG_ID = 1 << 9; +pub const ALG_TYPE_RSA: ALG_ID = 2 << 9; +pub const ALG_TYPE_BLOCK: ALG_ID = 3 << 9; +pub const ALG_TYPE_STREAM: ALG_ID = 4 << 9; +pub const ALG_TYPE_DH: ALG_ID = 5 << 9; +pub const ALG_TYPE_SECURECHANNEL: ALG_ID = 6 << 9; +pub const ALG_SID_ANY: ALG_ID = 0; +pub const ALG_SID_RSA_ANY: ALG_ID = 0; +pub const ALG_SID_RSA_PKCS: ALG_ID = 1; +pub const ALG_SID_RSA_MSATWORK: ALG_ID = 2; +pub const ALG_SID_RSA_ENTRUST: ALG_ID = 3; +pub const ALG_SID_RSA_PGP: ALG_ID = 4; +pub const ALG_SID_DSS_ANY: ALG_ID = 0; +pub const ALG_SID_DSS_PKCS: ALG_ID = 1; +pub const ALG_SID_DSS_DMS: ALG_ID = 2; +pub const ALG_SID_ECDSA: ALG_ID = 3; +pub const ALG_SID_DES: ALG_ID = 1; +pub const ALG_SID_3DES: ALG_ID = 3; +pub const ALG_SID_DESX: ALG_ID = 4; +pub const ALG_SID_IDEA: ALG_ID = 5; +pub const ALG_SID_CAST: ALG_ID = 6; +pub const ALG_SID_SAFERSK64: ALG_ID = 7; +pub const ALG_SID_SAFERSK128: ALG_ID = 8; +pub const ALG_SID_3DES_112: ALG_ID = 9; +pub const ALG_SID_CYLINK_MEK: ALG_ID = 12; +pub const ALG_SID_RC5: ALG_ID = 13; +pub const ALG_SID_AES_128: ALG_ID = 14; +pub const ALG_SID_AES_192: ALG_ID = 15; +pub const ALG_SID_AES_256: ALG_ID = 16; +pub const ALG_SID_AES: ALG_ID = 17; +pub const ALG_SID_SKIPJACK: ALG_ID = 10; +pub const ALG_SID_TEK: ALG_ID = 11; +pub const CRYPT_MODE_CBCI: ALG_ID = 6; +pub const CRYPT_MODE_CFBP: ALG_ID = 7; +pub const CRYPT_MODE_OFBP: ALG_ID = 8; +pub const CRYPT_MODE_CBCOFM: ALG_ID = 9; +pub const CRYPT_MODE_CBCOFMI: ALG_ID = 10; +pub const ALG_SID_RC2: ALG_ID = 2; +pub const ALG_SID_RC4: ALG_ID = 1; +pub const ALG_SID_SEAL: ALG_ID = 2; +pub const ALG_SID_DH_SANDF: ALG_ID = 1; +pub const ALG_SID_DH_EPHEM: ALG_ID = 2; +pub const ALG_SID_AGREED_KEY_ANY: ALG_ID = 3; +pub const ALG_SID_KEA: ALG_ID = 4; +pub const ALG_SID_ECDH: ALG_ID = 5; +pub const ALG_SID_MD2: ALG_ID = 1; +pub const ALG_SID_MD4: ALG_ID = 2; +pub const ALG_SID_MD5: ALG_ID = 3; +pub const ALG_SID_SHA: ALG_ID = 4; +pub const ALG_SID_SHA1: ALG_ID = 4; +pub const ALG_SID_MAC: ALG_ID = 5; +pub const ALG_SID_RIPEMD: ALG_ID = 6; +pub const ALG_SID_RIPEMD160: ALG_ID = 7; +pub const ALG_SID_SSL3SHAMD5: ALG_ID = 8; +pub const ALG_SID_HMAC: ALG_ID = 9; +pub const ALG_SID_TLS1PRF: ALG_ID = 10; +pub const ALG_SID_HASH_REPLACE_OWF: ALG_ID = 11; +pub const ALG_SID_SHA_256: ALG_ID = 12; +pub const ALG_SID_SHA_384: ALG_ID = 13; +pub const ALG_SID_SHA_512: ALG_ID = 14; +pub const ALG_SID_SSL3_MASTER: ALG_ID = 1; +pub const ALG_SID_SCHANNEL_MASTER_HASH: ALG_ID = 2; +pub const ALG_SID_SCHANNEL_MAC_KEY: ALG_ID = 3; +pub const ALG_SID_PCT1_MASTER: ALG_ID = 4; +pub const ALG_SID_SSL2_MASTER: ALG_ID = 5; +pub const ALG_SID_TLS1_MASTER: ALG_ID = 6; +pub const ALG_SID_SCHANNEL_ENC_KEY: ALG_ID = 7; +pub const ALG_SID_ECMQV: ALG_ID = 1; +pub const ALG_SID_EXAMPLE: ALG_ID = 80; +pub type ALG_ID = ::c_uint; +pub const CALG_MD2: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD2; +pub const CALG_MD4: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD4; +pub const CALG_MD5: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MD5; +pub const CALG_SHA: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA; +pub const CALG_SHA1: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA1; +pub const CALG_MAC: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_MAC; +pub const CALG_RSA_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | ALG_SID_RSA_ANY; +pub const CALG_DSS_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_DSS_ANY; +pub const CALG_NO_SIGN: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_ANY | ALG_SID_ANY; +pub const CALG_RSA_KEYX: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | ALG_SID_RSA_ANY; +pub const CALG_DES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DES; +pub const CALG_3DES_112: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES_112; +pub const CALG_3DES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_3DES; +pub const CALG_DESX: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_DESX; +pub const CALG_RC2: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC2; +pub const CALG_RC4: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_RC4; +pub const CALG_SEAL: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | ALG_SID_SEAL; +pub const CALG_DH_SF: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_SANDF; +pub const CALG_DH_EPHEM: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_DH_EPHEM; +pub const CALG_AGREEDKEY_ANY: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH + | ALG_SID_AGREED_KEY_ANY; +pub const CALG_KEA_KEYX: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_KEA; +pub const CALG_HUGHES_MD5: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_MD5; +pub const CALG_SKIPJACK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_SKIPJACK; +pub const CALG_TEK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_TEK; +pub const CALG_CYLINK_MEK: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_CYLINK_MEK; +pub const CALG_SSL3_SHAMD5: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5; +pub const CALG_SSL3_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SSL3_MASTER; +pub const CALG_SCHANNEL_MASTER_HASH: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_MASTER_HASH; +pub const CALG_SCHANNEL_MAC_KEY: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_MAC_KEY; +pub const CALG_SCHANNEL_ENC_KEY: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SCHANNEL_ENC_KEY; +pub const CALG_PCT1_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_PCT1_MASTER; +pub const CALG_SSL2_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_SSL2_MASTER; +pub const CALG_TLS1_MASTER: ALG_ID = ALG_CLASS_MSG_ENCRYPT | ALG_TYPE_SECURECHANNEL + | ALG_SID_TLS1_MASTER; +pub const CALG_RC5: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_RC5; +pub const CALG_HMAC: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HMAC; +pub const CALG_TLS1PRF: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_TLS1PRF; +pub const CALG_HASH_REPLACE_OWF: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_HASH_REPLACE_OWF; +pub const CALG_AES_128: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_128; +pub const CALG_AES_192: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_192; +pub const CALG_AES_256: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256; +pub const CALG_AES: ALG_ID = ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES; +pub const CALG_SHA_256: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256; +pub const CALG_SHA_384: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384; +pub const CALG_SHA_512: ALG_ID = ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512; +pub const CALG_ECDH: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_DH | ALG_SID_ECDH; +pub const CALG_ECMQV: ALG_ID = ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_ANY | ALG_SID_ECMQV; +pub const CALG_ECDSA: ALG_ID = ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | ALG_SID_ECDSA; +pub type HCRYPTPROV = ::ULONG_PTR; +pub type HCRYPTKEY = ::ULONG_PTR; +pub type HCRYPTHASH = ::ULONG_PTR; +pub const CRYPT_VERIFYCONTEXT: ::DWORD = 0xF0000000; +pub const CRYPT_NEWKEYSET: ::DWORD = 0x00000008; +pub const CRYPT_DELETEKEYSET: ::DWORD = 0x00000010; +pub const CRYPT_MACHINE_KEYSET: ::DWORD = 0x00000020; +pub const CRYPT_SILENT: ::DWORD = 0x00000040; +pub const CRYPT_DEFAULT_CONTAINER_OPTIONAL: ::DWORD = 0x00000080; +pub const CRYPT_EXPORTABLE: ::DWORD = 0x00000001; +pub const CRYPT_USER_PROTECTED: ::DWORD = 0x00000002; +pub const CRYPT_CREATE_SALT: ::DWORD = 0x00000004; +pub const CRYPT_UPDATE_KEY: ::DWORD = 0x00000008; +pub const CRYPT_NO_SALT: ::DWORD = 0x00000010; +pub const CRYPT_PREGEN: ::DWORD = 0x00000040; +pub const CRYPT_RECIPIENT: ::DWORD = 0x00000010; +pub const CRYPT_INITIATOR: ::DWORD = 0x00000040; +pub const CRYPT_ONLINE: ::DWORD = 0x00000080; +pub const CRYPT_SF: ::DWORD = 0x00000100; +pub const CRYPT_CREATE_IV: ::DWORD = 0x00000200; +pub const CRYPT_KEK: ::DWORD = 0x00000400; +pub const CRYPT_DATA_KEY: ::DWORD = 0x00000800; +pub const CRYPT_VOLATILE: ::DWORD = 0x00001000; +pub const CRYPT_SGCKEY: ::DWORD = 0x00002000; +pub const CRYPT_USER_PROTECTED_STRONG: ::DWORD = 0x00100000; +pub const CRYPT_ARCHIVABLE: ::DWORD = 0x00004000; +pub const CRYPT_FORCE_KEY_PROTECTION_HIGH: ::DWORD = 0x00008000; +pub const RSA1024BIT_KEY: ::DWORD = 0x04000000; +pub const CRYPT_SERVER: ::DWORD = 0x00000400; +pub const KEY_LENGTH_MASK: ::DWORD = 0xFFFF0000; +pub const CRYPT_Y_ONLY: ::DWORD = 0x00000001; +pub const CRYPT_SSL2_FALLBACK: ::DWORD = 0x00000002; +pub const CRYPT_DESTROYKEY: ::DWORD = 0x00000004; +pub const CRYPT_OAEP: ::DWORD = 0x00000040; +pub const CRYPT_BLOB_VER3: ::DWORD = 0x00000080; +pub const CRYPT_IPSEC_HMAC_KEY: ::DWORD = 0x00000100; +pub const CRYPT_DECRYPT_RSA_NO_PADDING_CHECK: ::DWORD = 0x00000020; +pub const CRYPT_SECRETDIGEST: ::DWORD = 0x00000001; +pub const CRYPT_OWF_REPL_LM_HASH: ::DWORD = 0x00000001; +pub const CRYPT_LITTLE_ENDIAN: ::DWORD = 0x00000001; +pub const CRYPT_NOHASHOID: ::DWORD = 0x00000001; +pub const CRYPT_TYPE2_FORMAT: ::DWORD = 0x00000002; +pub const CRYPT_X931_FORMAT: ::DWORD = 0x00000004; +pub const CRYPT_MACHINE_DEFAULT: ::DWORD = 0x00000001; +pub const CRYPT_USER_DEFAULT: ::DWORD = 0x00000002; +pub const CRYPT_DELETE_DEFAULT: ::DWORD = 0x00000004; +pub const SIMPLEBLOB: ::DWORD = 0x1; +pub const PUBLICKEYBLOB: ::DWORD = 0x6; +pub const PRIVATEKEYBLOB: ::DWORD = 0x7; +pub const PLAINTEXTKEYBLOB: ::DWORD = 0x8; +pub const OPAQUEKEYBLOB: ::DWORD = 0x9; +pub const PUBLICKEYBLOBEX: ::DWORD = 0xA; +pub const SYMMETRICWRAPKEYBLOB: ::DWORD = 0xB; +pub const KEYSTATEBLOB: ::DWORD = 0xC; +pub const AT_KEYEXCHANGE: ::DWORD = 1; +pub const AT_SIGNATURE: ::DWORD = 2; +pub const CRYPT_USERDATA: ::DWORD = 1; +pub const KP_IV: ::DWORD = 1; +pub const KP_SALT: ::DWORD = 2; +pub const KP_PADDING: ::DWORD = 3; +pub const KP_MODE: ::DWORD = 4; +pub const KP_MODE_BITS: ::DWORD = 5; +pub const KP_PERMISSIONS: ::DWORD = 6; +pub const KP_ALGID: ::DWORD = 7; +pub const KP_BLOCKLEN: ::DWORD = 8; +pub const KP_KEYLEN: ::DWORD = 9; +pub const KP_SALT_EX: ::DWORD = 10; +pub const KP_P: ::DWORD = 11; +pub const KP_G: ::DWORD = 12; +pub const KP_Q: ::DWORD = 13; +pub const KP_X: ::DWORD = 14; +pub const KP_Y: ::DWORD = 15; +pub const KP_RA: ::DWORD = 16; +pub const KP_RB: ::DWORD = 17; +pub const KP_INFO: ::DWORD = 18; +pub const KP_EFFECTIVE_KEYLEN: ::DWORD = 19; +pub const KP_SCHANNEL_ALG: ::DWORD = 20; +pub const KP_CLIENT_RANDOM: ::DWORD = 21; +pub const KP_SERVER_RANDOM: ::DWORD = 22; +pub const KP_RP: ::DWORD = 23; +pub const KP_PRECOMP_MD5: ::DWORD = 24; +pub const KP_PRECOMP_SHA: ::DWORD = 25; +pub const KP_CERTIFICATE: ::DWORD = 26; +pub const KP_CLEAR_KEY: ::DWORD = 27; +pub const KP_PUB_EX_LEN: ::DWORD = 28; +pub const KP_PUB_EX_VAL: ::DWORD = 29; +pub const KP_KEYVAL: ::DWORD = 30; +pub const KP_ADMIN_PIN: ::DWORD = 31; +pub const KP_KEYEXCHANGE_PIN: ::DWORD = 32; +pub const KP_SIGNATURE_PIN: ::DWORD = 33; +pub const KP_PREHASH: ::DWORD = 34; +pub const KP_ROUNDS: ::DWORD = 35; +pub const KP_OAEP_PARAMS: ::DWORD = 36; +pub const KP_CMS_KEY_INFO: ::DWORD = 37; +pub const KP_CMS_DH_KEY_INFO: ::DWORD = 38; +pub const KP_PUB_PARAMS: ::DWORD = 39; +pub const KP_VERIFY_PARAMS: ::DWORD = 40; +pub const KP_HIGHEST_VERSION: ::DWORD = 41; +pub const KP_GET_USE_COUNT: ::DWORD = 42; +pub const KP_PIN_ID: ::DWORD = 43; +pub const KP_PIN_INFO: ::DWORD = 44; +pub const PKCS5_PADDING: ::DWORD = 1; +pub const RANDOM_PADDING: ::DWORD = 2; +pub const ZERO_PADDING: ::DWORD = 3; +pub const CRYPT_MODE_CBC: ::DWORD = 1; +pub const CRYPT_MODE_ECB: ::DWORD = 2; +pub const CRYPT_MODE_OFB: ::DWORD = 3; +pub const CRYPT_MODE_CFB: ::DWORD = 4; +pub const CRYPT_MODE_CTS: ::DWORD = 5; +pub const CRYPT_ENCRYPT: ::DWORD = 0x0001; +pub const CRYPT_DECRYPT: ::DWORD = 0x0002; +pub const CRYPT_EXPORT: ::DWORD = 0x0004; +pub const CRYPT_READ: ::DWORD = 0x0008; +pub const CRYPT_WRITE: ::DWORD = 0x0010; +pub const CRYPT_MAC: ::DWORD = 0x0020; +pub const CRYPT_EXPORT_KEY: ::DWORD = 0x0040; +pub const CRYPT_IMPORT_KEY: ::DWORD = 0x0080; +pub const CRYPT_ARCHIVE: ::DWORD = 0x0100; +pub const HP_ALGID: ::DWORD = 0x0001; +pub const HP_HASHVAL: ::DWORD = 0x0002; +pub const HP_HASHSIZE: ::DWORD = 0x0004; +pub const HP_HMAC_INFO: ::DWORD = 0x0005; +pub const HP_TLS1PRF_LABEL: ::DWORD = 0x0006; +pub const HP_TLS1PRF_SEED: ::DWORD = 0x0007; +pub const CRYPT_FAILED: ::BOOL = ::FALSE; +pub const CRYPT_SUCCEED: ::BOOL = ::TRUE; +pub const PP_ENUMALGS: ::DWORD = 1; +pub const PP_ENUMCONTAINERS: ::DWORD = 2; +pub const PP_IMPTYPE: ::DWORD = 3; +pub const PP_NAME: ::DWORD = 4; +pub const PP_VERSION: ::DWORD = 5; +pub const PP_CONTAINER: ::DWORD = 6; +pub const PP_CHANGE_PASSWORD: ::DWORD = 7; +pub const PP_KEYSET_SEC_DESCR: ::DWORD = 8; +pub const PP_CERTCHAIN: ::DWORD = 9; +pub const PP_KEY_TYPE_SUBTYPE: ::DWORD = 10; +pub const PP_PROVTYPE: ::DWORD = 16; +pub const PP_KEYSTORAGE: ::DWORD = 17; +pub const PP_APPLI_CERT: ::DWORD = 18; +pub const PP_SYM_KEYSIZE: ::DWORD = 19; +pub const PP_SESSION_KEYSIZE: ::DWORD = 20; +pub const PP_UI_PROMPT: ::DWORD = 21; +pub const PP_ENUMALGS_EX: ::DWORD = 22; +pub const PP_ENUMMANDROOTS: ::DWORD = 25; +pub const PP_ENUMELECTROOTS: ::DWORD = 26; +pub const PP_KEYSET_TYPE: ::DWORD = 27; +pub const PP_ADMIN_PIN: ::DWORD = 31; +pub const PP_KEYEXCHANGE_PIN: ::DWORD = 32; +pub const PP_SIGNATURE_PIN: ::DWORD = 33; +pub const PP_SIG_KEYSIZE_INC: ::DWORD = 34; +pub const PP_KEYX_KEYSIZE_INC: ::DWORD = 35; +pub const PP_UNIQUE_CONTAINER: ::DWORD = 36; +pub const PP_SGC_INFO: ::DWORD = 37; +pub const PP_USE_HARDWARE_RNG: ::DWORD = 38; +pub const PP_KEYSPEC: ::DWORD = 39; +pub const PP_ENUMEX_SIGNING_PROT: ::DWORD = 40; +pub const PP_CRYPT_COUNT_KEY_USE: ::DWORD = 41; +pub const PP_USER_CERTSTORE: ::DWORD = 42; +pub const PP_SMARTCARD_READER: ::DWORD = 43; +pub const PP_SMARTCARD_GUID: ::DWORD = 45; +pub const PP_ROOT_CERTSTORE: ::DWORD = 46; +pub const PP_SMARTCARD_READER_ICON: ::DWORD = 47; +pub const CRYPT_FIRST: ::DWORD = 1; +pub const CRYPT_NEXT: ::DWORD = 2; +pub const CRYPT_SGC_ENUM: ::DWORD = 4; +pub const CRYPT_IMPL_HARDWARE: ::DWORD = 1; +pub const CRYPT_IMPL_SOFTWARE: ::DWORD = 2; +pub const CRYPT_IMPL_MIXED: ::DWORD = 3; +pub const CRYPT_IMPL_UNKNOWN: ::DWORD = 4; +pub const CRYPT_IMPL_REMOVABLE: ::DWORD = 8; +pub const CRYPT_SEC_DESCR: ::DWORD = 0x00000001; +pub const CRYPT_PSTORE: ::DWORD = 0x00000002; +pub const CRYPT_UI_PROMPT: ::DWORD = 0x00000004; +pub const CRYPT_FLAG_PCT1: ::DWORD = 0x0001; +pub const CRYPT_FLAG_SSL2: ::DWORD = 0x0002; +pub const CRYPT_FLAG_SSL3: ::DWORD = 0x0004; +pub const CRYPT_FLAG_TLS1: ::DWORD = 0x0008; +pub const CRYPT_FLAG_IPSEC: ::DWORD = 0x0010; +pub const CRYPT_FLAG_SIGNING: ::DWORD = 0x0020; +pub const CRYPT_SGC: ::DWORD = 0x0001; +pub const CRYPT_FASTSGC: ::DWORD = 0x0002; +pub const PP_CLIENT_HWND: ::DWORD = 1; +pub const PP_CONTEXT_INFO: ::DWORD = 11; +pub const PP_KEYEXCHANGE_KEYSIZE: ::DWORD = 12; +pub const PP_SIGNATURE_KEYSIZE: ::DWORD = 13; +pub const PP_KEYEXCHANGE_ALG: ::DWORD = 14; +pub const PP_SIGNATURE_ALG: ::DWORD = 15; +pub const PP_DELETEKEY: ::DWORD = 24; +pub const PP_PIN_PROMPT_STRING: ::DWORD = 44; +pub const PP_SECURE_KEYEXCHANGE_PIN: ::DWORD = 47; +pub const PP_SECURE_SIGNATURE_PIN: ::DWORD = 48; +pub const PROV_RSA_FULL: ::DWORD = 1; +pub const PROV_RSA_SIG: ::DWORD = 2; +pub const PROV_DSS: ::DWORD = 3; +pub const PROV_FORTEZZA: ::DWORD = 4; +pub const PROV_MS_EXCHANGE: ::DWORD = 5; +pub const PROV_SSL: ::DWORD = 6; +pub const PROV_RSA_SCHANNEL: ::DWORD = 12; +pub const PROV_DSS_DH: ::DWORD = 13; +pub const PROV_EC_ECDSA_SIG: ::DWORD = 14; +pub const PROV_EC_ECNRA_SIG: ::DWORD = 15; +pub const PROV_EC_ECDSA_FULL: ::DWORD = 16; +pub const PROV_EC_ECNRA_FULL: ::DWORD = 17; +pub const PROV_DH_SCHANNEL: ::DWORD = 18; +pub const PROV_SPYRUS_LYNKS: ::DWORD = 20; +pub const PROV_RNG: ::DWORD = 21; +pub const PROV_INTEL_SEC: ::DWORD = 22; +pub const PROV_REPLACE_OWF: ::DWORD = 23; +pub const PROV_RSA_AES: ::DWORD = 24; +pub const MS_DEF_PROV: &'static str = "Microsoft Base Cryptographic Provider v1.0"; +pub const MS_ENHANCED_PROV: &'static str = "Microsoft Enhanced Cryptographic Provider v1.0"; +pub const MS_STRONG_PROV: &'static str = "Microsoft Strong Cryptographic Provider"; +pub const MS_DEF_RSA_SIG_PROV: &'static str = "Microsoft RSA Signature Cryptographic Provider"; +pub const MS_DEF_RSA_SCHANNEL_PROV: &'static str = "Microsoft RSA SChannel Cryptographic Provider"; +pub const MS_DEF_DSS_PROV: &'static str = "Microsoft Base DSS Cryptographic Provider"; +pub const MS_DEF_DSS_DH_PROV: &'static str = + "Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"; +pub const MS_ENH_DSS_DH_PROV: &'static str = + "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"; +pub const MS_DEF_DH_SCHANNEL_PROV: &'static str = "Microsoft DH SChannel Cryptographic Provider"; +pub const MS_SCARD_PROV: &'static str = "Microsoft Base Smart Card Crypto Provider"; +pub const MS_ENH_RSA_AES_PROV: &'static str = + "Microsoft Enhanced RSA and AES Cryptographic Provider"; +pub const MS_ENH_RSA_AES_PROV_XP: &'static str = + "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"; +pub const MAXUIDLEN: usize = 64; +pub const EXPO_OFFLOAD_REG_VALUE: &'static str = "ExpoOffload"; +pub const EXPO_OFFLOAD_FUNC_NAME: &'static str = "OffloadModExpo"; +pub const szKEY_CRYPTOAPI_PRIVATE_KEY_OPTIONS: &'static str = + "Software\\Policies\\Microsoft\\Cryptography"; +pub const szKEY_CACHE_ENABLED: &'static str = "CachePrivateKeys"; +pub const szKEY_CACHE_SECONDS: &'static str = "PrivateKeyLifetimeSeconds"; +pub const szPRIV_KEY_CACHE_MAX_ITEMS: &'static str = "PrivKeyCacheMaxItems"; +pub const cPRIV_KEY_CACHE_MAX_ITEMS_DEFAULT: ::DWORD = 20; +pub const szPRIV_KEY_CACHE_PURGE_INTERVAL_SECONDS: &'static str = + "PrivKeyCachePurgeIntervalSeconds"; +pub const cPRIV_KEY_CACHE_PURGE_INTERVAL_SECONDS_DEFAULT: ::DWORD = 86400; +pub const CUR_BLOB_VERSION: ::DWORD = 2; +STRUCT!{struct CMS_KEY_INFO { + dwVersion: ::DWORD, + Algid: ALG_ID, + pbOID: *mut ::BYTE, + cbOID: ::DWORD, +}} +pub type PCMS_KEY_INFO = *mut CMS_KEY_INFO; +STRUCT!{struct HMAC_INFO { + HashAlgid: ALG_ID, + pbInnerString: *mut ::BYTE, + cbInnerString: ::DWORD, + pbOuterString: *mut ::BYTE, + cbOuterString: ::DWORD, +}} +pub type PHMAC_INFO = *mut HMAC_INFO; +STRUCT!{struct SCHANNEL_ALG { + dwUse: ::DWORD, + Algid: ALG_ID, + cBits: ::DWORD, + dwFlags: ::DWORD, + dwReserved: ::DWORD, +}} +pub type PSCHANNEL_ALG = *mut SCHANNEL_ALG; +pub const SCHANNEL_MAC_KEY: ::DWORD = 0x00000000; +pub const SCHANNEL_ENC_KEY: ::DWORD = 0x00000001; +pub const INTERNATIONAL_USAGE: ::DWORD = 0x00000001; +STRUCT!{struct PROV_ENUMALGS { + aiAlgid: ALG_ID, + dwBitLen: ::DWORD, + dwNameLen: ::DWORD, + szName: [::CHAR; 20], +}} +STRUCT!{nodebug struct PROV_ENUMALGS_EX { + aiAlgid: ALG_ID, + dwDefaultLen: ::DWORD, + dwMinLen: ::DWORD, + dwMaxLen: ::DWORD, + dwProtocols: ::DWORD, + dwNameLen: ::DWORD, + szName: [::CHAR; 20], + dwLongNameLen: ::DWORD, + szLongName: [::CHAR; 40], +}} +STRUCT!{struct BLOBHEADER { + bType: ::BYTE, + bVersion: ::BYTE, + reserved: ::WORD, + aiKeyAlg: ::ALG_ID, +}} +pub type PUBLICKEYSTRUC = BLOBHEADER; +STRUCT!{struct RSAPUBKEY { + magic: ::DWORD, + bitlen: ::DWORD, + pubexp: ::DWORD, +}} +STRUCT!{struct DHPUBKEY { + magic: ::DWORD, + bitlen: ::DWORD, +}} +pub type DSSPUBKEY = DHPUBKEY; +pub type KEAPUBKEY = DHPUBKEY; +pub type TEKPUBKEY = DHPUBKEY; +STRUCT!{struct DSSSEED { + counter: ::DWORD, + seed: [::BYTE; 20], +}} +STRUCT!{struct DHPUBKEY_VER3 { + magic: ::DWORD, + bitlenP: ::DWORD, + bitlenQ: ::DWORD, + bitlenJ: ::DWORD, + DSSSeed: DSSSEED, +}} +pub type DSSPUBKEY_VER3 = DHPUBKEY_VER3; +STRUCT!{struct DHPRIVKEY_VER3 { + magic: ::DWORD, + bitlenP: ::DWORD, + bitlenQ: ::DWORD, + bitlenJ: ::DWORD, + bitlenX: ::DWORD, + DSSSeed: DSSSEED, +}} +pub type DSSPRIVKEY_VER3 = DHPRIVKEY_VER3; +STRUCT!{struct KEY_TYPE_SUBTYPE { + dwKeySpec: ::DWORD, + Type: ::GUID, + Subtype: ::GUID, +}} +pub type PKEY_TYPE_SUBTYPE = *mut KEY_TYPE_SUBTYPE; +STRUCT!{nodebug struct CERT_FORTEZZA_DATA_PROP { + SerialNumber: [::c_uchar; 8], + CertIndex: ::c_int, + CertLabel: [::c_uchar; 36], +}} +STRUCT!{nodebug struct CRYPT_RC4_KEY_STATE { + Key: [::c_uchar; 16], + SBox: [::c_uchar; 256], + i: ::c_uchar, + j: ::c_uchar, +}} +pub type PCRYPT_RC4_KEY_STATE = *mut CRYPT_RC4_KEY_STATE; +STRUCT!{struct CRYPT_DES_KEY_STATE { + Key: [::c_uchar; 8], + IV: [::c_uchar; 8], + Feedback: [::c_uchar; 8], +}} +pub type PCRYPT_DES_KEY_STATE = *mut CRYPT_DES_KEY_STATE; +STRUCT!{struct CRYPT_3DES_KEY_STATE { + Key: [::c_uchar; 24], + IV: [::c_uchar; 8], + Feedback: [::c_uchar; 8], +}} +pub type PCRYPT_3DES_KEY_STATE = *mut CRYPT_3DES_KEY_STATE; +STRUCT!{struct CRYPT_AES_128_KEY_STATE { + Key: [::c_uchar; 16], + IV: [::c_uchar; 16], + EncryptionState: [[::c_uchar; 16]; 11], + DecryptionState: [[::c_uchar; 16]; 11], + Feedback: [::c_uchar; 16], +}} +pub type PCRYPT_AES_128_KEY_STATE = *mut CRYPT_AES_128_KEY_STATE; +STRUCT!{struct CRYPT_AES_256_KEY_STATE { + Key: [::c_uchar; 32], + IV: [::c_uchar; 16], + EncryptionState: [[::c_uchar; 16]; 15], + DecryptionState: [[::c_uchar; 16]; 15], + Feedback: [::c_uchar; 16], +}} +pub type PCRYPT_AES_256_KEY_STATE = *mut CRYPT_AES_256_KEY_STATE; +STRUCT!{struct CRYPTOAPI_BLOB { + cbData: ::DWORD, + pbData: *mut ::BYTE, +}} +pub type CRYPT_INTEGER_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_INTEGER_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_UINT_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_UINT_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_OBJID_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_OBJID_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_NAME_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_NAME_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_RDN_VALUE_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_RDN_VALUE_BLOB = *mut CRYPTOAPI_BLOB; +pub type CERT_BLOB = CRYPTOAPI_BLOB; +pub type PCERT_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRL_BLOB = CRYPTOAPI_BLOB; +pub type PCRL_BLOB = *mut CRYPTOAPI_BLOB; +pub type DATA_BLOB = CRYPTOAPI_BLOB; +pub type PDATA_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DATA_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DATA_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_HASH_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_HASH_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DIGEST_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DIGEST_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_DER_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_DER_BLOB = *mut CRYPTOAPI_BLOB; +pub type CRYPT_ATTR_BLOB = CRYPTOAPI_BLOB; +pub type PCRYPT_ATTR_BLOB = *mut CRYPTOAPI_BLOB; +STRUCT!{struct CMS_DH_KEY_INFO { + dwVersion: ::DWORD, + Algid: ALG_ID, + pszContentEncObjId: ::LPSTR, + PubInfo: CRYPT_DATA_BLOB, + pReserved: *mut ::c_void, +}} +pub type PCMS_DH_KEY_INFO = *mut CMS_DH_KEY_INFO; +pub type HCRYPTPROV_OR_NCRYPT_KEY_HANDLE = ::ULONG_PTR; +pub type HCRYPTPROV_LEGACY = ::ULONG_PTR; +STRUCT!{struct CRYPT_BIT_BLOB { + cbData: ::DWORD, + pbData: *mut ::BYTE, + cUnusedBits: ::DWORD, +}} +pub type PCRYPT_BIT_BLOB = *mut CRYPT_BIT_BLOB; +STRUCT!{struct CRYPT_ALGORITHM_IDENTIFIER { + pszObjId: ::LPSTR, + Parameters: CRYPT_OBJID_BLOB, +}} +pub type PCRYPT_ALGORITHM_IDENTIFIER = *mut CRYPT_ALGORITHM_IDENTIFIER; +pub const szOID_RSA: &'static str = "1.2.840.113549"; +pub const szOID_PKCS: &'static str = "1.2.840.113549.1"; +pub const szOID_RSA_HASH: &'static str = "1.2.840.113549.2"; +pub const szOID_RSA_ENCRYPT: &'static str = "1.2.840.113549.3"; +pub const szOID_PKCS_1: &'static str = "1.2.840.113549.1.1"; +pub const szOID_PKCS_2: &'static str = "1.2.840.113549.1.2"; +pub const szOID_PKCS_3: &'static str = "1.2.840.113549.1.3"; +pub const szOID_PKCS_4: &'static str = "1.2.840.113549.1.4"; +pub const szOID_PKCS_5: &'static str = "1.2.840.113549.1.5"; +pub const szOID_PKCS_6: &'static str = "1.2.840.113549.1.6"; +pub const szOID_PKCS_7: &'static str = "1.2.840.113549.1.7"; +pub const szOID_PKCS_8: &'static str = "1.2.840.113549.1.8"; +pub const szOID_PKCS_9: &'static str = "1.2.840.113549.1.9"; +pub const szOID_PKCS_10: &'static str = "1.2.840.113549.1.10"; +pub const szOID_PKCS_12: &'static str = "1.2.840.113549.1.12"; +pub const szOID_RSA_RSA: &'static str = "1.2.840.113549.1.1.1"; +pub const szOID_RSA_MD2RSA: &'static str = "1.2.840.113549.1.1.2"; +pub const szOID_RSA_MD4RSA: &'static str = "1.2.840.113549.1.1.3"; +pub const szOID_RSA_MD5RSA: &'static str = "1.2.840.113549.1.1.4"; +pub const szOID_RSA_SHA1RSA: &'static str = "1.2.840.113549.1.1.5"; +pub const szOID_RSA_SETOAEP_RSA: &'static str = "1.2.840.113549.1.1.6"; +pub const szOID_RSAES_OAEP: &'static str = "1.2.840.113549.1.1.7"; +pub const szOID_RSA_MGF1: &'static str = "1.2.840.113549.1.1.8"; +pub const szOID_RSA_PSPECIFIED: &'static str = "1.2.840.113549.1.1.9"; +pub const szOID_RSA_SSA_PSS: &'static str = "1.2.840.113549.1.1.10"; +pub const szOID_RSA_SHA256RSA: &'static str = "1.2.840.113549.1.1.11"; +pub const szOID_RSA_SHA384RSA: &'static str = "1.2.840.113549.1.1.12"; +pub const szOID_RSA_SHA512RSA: &'static str = "1.2.840.113549.1.1.13"; +pub const szOID_RSA_DH: &'static str = "1.2.840.113549.1.3.1"; +pub const szOID_RSA_data: &'static str = "1.2.840.113549.1.7.1"; +pub const szOID_RSA_signedData: &'static str = "1.2.840.113549.1.7.2"; +pub const szOID_RSA_envelopedData: &'static str = "1.2.840.113549.1.7.3"; +pub const szOID_RSA_signEnvData: &'static str = "1.2.840.113549.1.7.4"; +pub const szOID_RSA_digestedData: &'static str = "1.2.840.113549.1.7.5"; +pub const szOID_RSA_hashedData: &'static str = "1.2.840.113549.1.7.5"; +pub const szOID_RSA_encryptedData: &'static str = "1.2.840.113549.1.7.6"; +pub const szOID_RSA_emailAddr: &'static str = "1.2.840.113549.1.9.1"; +pub const szOID_RSA_unstructName: &'static str = "1.2.840.113549.1.9.2"; +pub const szOID_RSA_contentType: &'static str = "1.2.840.113549.1.9.3"; +pub const szOID_RSA_messageDigest: &'static str = "1.2.840.113549.1.9.4"; +pub const szOID_RSA_signingTime: &'static str = "1.2.840.113549.1.9.5"; +pub const szOID_RSA_counterSign: &'static str = "1.2.840.113549.1.9.6"; +pub const szOID_RSA_challengePwd: &'static str = "1.2.840.113549.1.9.7"; +pub const szOID_RSA_unstructAddr: &'static str = "1.2.840.113549.1.9.8"; +pub const szOID_RSA_extCertAttrs: &'static str = "1.2.840.113549.1.9.9"; +pub const szOID_RSA_certExtensions: &'static str = "1.2.840.113549.1.9.14"; +pub const szOID_RSA_SMIMECapabilities: &'static str = "1.2.840.113549.1.9.15"; +pub const szOID_RSA_preferSignedData: &'static str = "1.2.840.113549.1.9.15.1"; +pub const szOID_TIMESTAMP_TOKEN: &'static str = "1.2.840.113549.1.9.16.1.4"; +pub const szOID_RFC3161_counterSign: &'static str = "1.3.6.1.4.1.311.3.3.1"; +pub const szOID_RSA_SMIMEalg: &'static str = "1.2.840.113549.1.9.16.3"; +pub const szOID_RSA_SMIMEalgESDH: &'static str = "1.2.840.113549.1.9.16.3.5"; +pub const szOID_RSA_SMIMEalgCMS3DESwrap: &'static str = "1.2.840.113549.1.9.16.3.6"; +pub const szOID_RSA_SMIMEalgCMSRC2wrap: &'static str = "1.2.840.113549.1.9.16.3.7"; +pub const szOID_RSA_MD2: &'static str = "1.2.840.113549.2.2"; +pub const szOID_RSA_MD4: &'static str = "1.2.840.113549.2.4"; +pub const szOID_RSA_MD5: &'static str = "1.2.840.113549.2.5"; +pub const szOID_RSA_RC2CBC: &'static str = "1.2.840.113549.3.2"; +pub const szOID_RSA_RC4: &'static str = "1.2.840.113549.3.4"; +pub const szOID_RSA_DES_EDE3_CBC: &'static str = "1.2.840.113549.3.7"; +pub const szOID_RSA_RC5_CBCPad: &'static str = "1.2.840.113549.3.9"; +pub const szOID_ANSI_X942: &'static str = "1.2.840.10046"; +pub const szOID_ANSI_X942_DH: &'static str = "1.2.840.10046.2.1"; +pub const szOID_X957: &'static str = "1.2.840.10040"; +pub const szOID_X957_DSA: &'static str = "1.2.840.10040.4.1"; +pub const szOID_X957_SHA1DSA: &'static str = "1.2.840.10040.4.3"; +pub const szOID_ECC_PUBLIC_KEY: &'static str = "1.2.840.10045.2.1"; +pub const szOID_ECC_CURVE_P256: &'static str = "1.2.840.10045.3.1.7"; +pub const szOID_ECC_CURVE_P384: &'static str = "1.3.132.0.34"; +pub const szOID_ECC_CURVE_P521: &'static str = "1.3.132.0.35"; +pub const szOID_ECDSA_SHA1: &'static str = "1.2.840.10045.4.1"; +pub const szOID_ECDSA_SPECIFIED: &'static str = "1.2.840.10045.4.3"; +pub const szOID_ECDSA_SHA256: &'static str = "1.2.840.10045.4.3.2"; +pub const szOID_ECDSA_SHA384: &'static str = "1.2.840.10045.4.3.3"; +pub const szOID_ECDSA_SHA512: &'static str = "1.2.840.10045.4.3.4"; +pub const szOID_NIST_AES128_CBC: &'static str = "2.16.840.1.101.3.4.1.2"; +pub const szOID_NIST_AES192_CBC: &'static str = "2.16.840.1.101.3.4.1.22"; +pub const szOID_NIST_AES256_CBC: &'static str = "2.16.840.1.101.3.4.1.42"; +pub const szOID_NIST_AES128_WRAP: &'static str = "2.16.840.1.101.3.4.1.5"; +pub const szOID_NIST_AES192_WRAP: &'static str = "2.16.840.1.101.3.4.1.25"; +pub const szOID_NIST_AES256_WRAP: &'static str = "2.16.840.1.101.3.4.1.45"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA1_KDF: &'static str = "1.3.133.16.840.63.0.2"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA256_KDF: &'static str = "1.3.132.1.11.1"; +pub const szOID_DH_SINGLE_PASS_STDDH_SHA384_KDF: &'static str = "1.3.132.1.11.2"; +pub const szOID_DS: &'static str = "2.5"; +pub const szOID_DSALG: &'static str = "2.5.8"; +pub const szOID_DSALG_CRPT: &'static str = "2.5.8.1"; +pub const szOID_DSALG_HASH: &'static str = "2.5.8.2"; +pub const szOID_DSALG_SIGN: &'static str = "2.5.8.3"; +pub const szOID_DSALG_RSA: &'static str = "2.5.8.1.1"; +pub const szOID_OIW: &'static str = "1.3.14"; +pub const szOID_OIWSEC: &'static str = "1.3.14.3.2"; +pub const szOID_OIWSEC_md4RSA: &'static str = "1.3.14.3.2.2"; +pub const szOID_OIWSEC_md5RSA: &'static str = "1.3.14.3.2.3"; +pub const szOID_OIWSEC_md4RSA2: &'static str = "1.3.14.3.2.4"; +pub const szOID_OIWSEC_desECB: &'static str = "1.3.14.3.2.6"; +pub const szOID_OIWSEC_desCBC: &'static str = "1.3.14.3.2.7"; +pub const szOID_OIWSEC_desOFB: &'static str = "1.3.14.3.2.8"; +pub const szOID_OIWSEC_desCFB: &'static str = "1.3.14.3.2.9"; +pub const szOID_OIWSEC_desMAC: &'static str = "1.3.14.3.2.10"; +pub const szOID_OIWSEC_rsaSign: &'static str = "1.3.14.3.2.11"; +pub const szOID_OIWSEC_dsa: &'static str = "1.3.14.3.2.12"; +pub const szOID_OIWSEC_shaDSA: &'static str = "1.3.14.3.2.13"; +pub const szOID_OIWSEC_mdc2RSA: &'static str = "1.3.14.3.2.14"; +pub const szOID_OIWSEC_shaRSA: &'static str = "1.3.14.3.2.15"; +pub const szOID_OIWSEC_dhCommMod: &'static str = "1.3.14.3.2.16"; +pub const szOID_OIWSEC_desEDE: &'static str = "1.3.14.3.2.17"; +pub const szOID_OIWSEC_sha: &'static str = "1.3.14.3.2.18"; +pub const szOID_OIWSEC_mdc2: &'static str = "1.3.14.3.2.19"; +pub const szOID_OIWSEC_dsaComm: &'static str = "1.3.14.3.2.20"; +pub const szOID_OIWSEC_dsaCommSHA: &'static str = "1.3.14.3.2.21"; +pub const szOID_OIWSEC_rsaXchg: &'static str = "1.3.14.3.2.22"; +pub const szOID_OIWSEC_keyHashSeal: &'static str = "1.3.14.3.2.23"; +pub const szOID_OIWSEC_md2RSASign: &'static str = "1.3.14.3.2.24"; +pub const szOID_OIWSEC_md5RSASign: &'static str = "1.3.14.3.2.25"; +pub const szOID_OIWSEC_sha1: &'static str = "1.3.14.3.2.26"; +pub const szOID_OIWSEC_dsaSHA1: &'static str = "1.3.14.3.2.27"; +pub const szOID_OIWSEC_dsaCommSHA1: &'static str = "1.3.14.3.2.28"; +pub const szOID_OIWSEC_sha1RSASign: &'static str = "1.3.14.3.2.29"; +pub const szOID_OIWDIR: &'static str = "1.3.14.7.2"; +pub const szOID_OIWDIR_CRPT: &'static str = "1.3.14.7.2.1"; +pub const szOID_OIWDIR_HASH: &'static str = "1.3.14.7.2.2"; +pub const szOID_OIWDIR_SIGN: &'static str = "1.3.14.7.2.3"; +pub const szOID_OIWDIR_md2: &'static str = "1.3.14.7.2.2.1"; +pub const szOID_OIWDIR_md2RSA: &'static str = "1.3.14.7.2.3.1"; +pub const szOID_INFOSEC: &'static str = "2.16.840.1.101.2.1"; +pub const szOID_INFOSEC_sdnsSignature: &'static str = "2.16.840.1.101.2.1.1.1"; +pub const szOID_INFOSEC_mosaicSignature: &'static str = "2.16.840.1.101.2.1.1.2"; +pub const szOID_INFOSEC_sdnsConfidentiality: &'static str = "2.16.840.1.101.2.1.1.3"; +pub const szOID_INFOSEC_mosaicConfidentiality: &'static str = "2.16.840.1.101.2.1.1.4"; +pub const szOID_INFOSEC_sdnsIntegrity: &'static str = "2.16.840.1.101.2.1.1.5"; +pub const szOID_INFOSEC_mosaicIntegrity: &'static str = "2.16.840.1.101.2.1.1.6"; +pub const szOID_INFOSEC_sdnsTokenProtection: &'static str = "2.16.840.1.101.2.1.1.7"; +pub const szOID_INFOSEC_mosaicTokenProtection: &'static str = "2.16.840.1.101.2.1.1.8"; +pub const szOID_INFOSEC_sdnsKeyManagement: &'static str = "2.16.840.1.101.2.1.1.9"; +pub const szOID_INFOSEC_mosaicKeyManagement: &'static str = "2.16.840.1.101.2.1.1.10"; +pub const szOID_INFOSEC_sdnsKMandSig: &'static str = "2.16.840.1.101.2.1.1.11"; +pub const szOID_INFOSEC_mosaicKMandSig: &'static str = "2.16.840.1.101.2.1.1.12"; +pub const szOID_INFOSEC_SuiteASignature: &'static str = "2.16.840.1.101.2.1.1.13"; +pub const szOID_INFOSEC_SuiteAConfidentiality: &'static str = "2.16.840.1.101.2.1.1.14"; +pub const szOID_INFOSEC_SuiteAIntegrity: &'static str = "2.16.840.1.101.2.1.1.15"; +pub const szOID_INFOSEC_SuiteATokenProtection: &'static str = "2.16.840.1.101.2.1.1.16"; +pub const szOID_INFOSEC_SuiteAKeyManagement: &'static str = "2.16.840.1.101.2.1.1.17"; +pub const szOID_INFOSEC_SuiteAKMandSig: &'static str = "2.16.840.1.101.2.1.1.18"; +pub const szOID_INFOSEC_mosaicUpdatedSig: &'static str = "2.16.840.1.101.2.1.1.19"; +pub const szOID_INFOSEC_mosaicKMandUpdSig: &'static str = "2.16.840.1.101.2.1.1.20"; +pub const szOID_INFOSEC_mosaicUpdatedInteg: &'static str = "2.16.840.1.101.2.1.1.21"; +pub const szOID_NIST_sha256: &'static str = "2.16.840.1.101.3.4.2.1"; +pub const szOID_NIST_sha384: &'static str = "2.16.840.1.101.3.4.2.2"; +pub const szOID_NIST_sha512: &'static str = "2.16.840.1.101.3.4.2.3"; +STRUCT!{struct CRYPT_OBJID_TABLE { + dwAlgId: ::DWORD, + pszObjId: ::LPCSTR, +}} +pub type PCRYPT_OBJID_TABLE = *mut CRYPT_OBJID_TABLE; +STRUCT!{struct CRYPT_HASH_INFO { + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Hash: CRYPT_HASH_BLOB, +}} +pub type PCRYPT_HASH_INFO = *mut CRYPT_HASH_INFO; +STRUCT!{struct CERT_EXTENSION { + pszObjId: ::LPSTR, + fCritical: ::BOOL, + Value: CRYPT_OBJID_BLOB, +}} +pub type PCERT_EXTENSION = *mut CERT_EXTENSION; +pub type PCCERT_EXTENSION = *const CERT_EXTENSION; +STRUCT!{struct CRYPT_ATTRIBUTE_TYPE_VALUE { + pszObjId: ::LPSTR, + Value: CRYPT_OBJID_BLOB, +}} +pub type PCRYPT_ATTRIBUTE_TYPE_VALUE = *mut CRYPT_ATTRIBUTE_TYPE_VALUE; +STRUCT!{struct CRYPT_ATTRIBUTE { + pszObjId: ::LPSTR, + cValue: ::DWORD, + rgValue: PCRYPT_ATTR_BLOB, +}} +pub type PCRYPT_ATTRIBUTE = *mut CRYPT_ATTRIBUTE; +STRUCT!{struct CRYPT_ATTRIBUTES { + cAttr: ::DWORD, + rgAttr: PCRYPT_ATTRIBUTE, +}} +pub type PCRYPT_ATTRIBUTES = *mut CRYPT_ATTRIBUTES; +STRUCT!{struct CERT_RDN_ATTR { + pszObjId: ::LPSTR, + dwValueType: ::DWORD, + Value: CERT_RDN_VALUE_BLOB, +}} +pub type PCERT_RDN_ATTR = *mut CERT_RDN_ATTR; +pub const szOID_COMMON_NAME: &'static str = "2.5.4.3"; +pub const szOID_SUR_NAME: &'static str = "2.5.4.4"; +pub const szOID_DEVICE_SERIAL_NUMBER: &'static str = "2.5.4.5"; +pub const szOID_COUNTRY_NAME: &'static str = "2.5.4.6"; +pub const szOID_LOCALITY_NAME: &'static str = "2.5.4.7"; +pub const szOID_STATE_OR_PROVINCE_NAME: &'static str = "2.5.4.8"; +pub const szOID_STREET_ADDRESS: &'static str = "2.5.4.9"; +pub const szOID_ORGANIZATION_NAME: &'static str = "2.5.4.10"; +pub const szOID_ORGANIZATIONAL_UNIT_NAME: &'static str = "2.5.4.11"; +pub const szOID_TITLE: &'static str = "2.5.4.12"; +pub const szOID_DESCRIPTION: &'static str = "2.5.4.13"; +pub const szOID_SEARCH_GUIDE: &'static str = "2.5.4.14"; +pub const szOID_BUSINESS_CATEGORY: &'static str = "2.5.4.15"; +pub const szOID_POSTAL_ADDRESS: &'static str = "2.5.4.16"; +pub const szOID_POSTAL_CODE: &'static str = "2.5.4.17"; +pub const szOID_POST_OFFICE_BOX: &'static str = "2.5.4.18"; +pub const szOID_PHYSICAL_DELIVERY_OFFICE_NAME: &'static str = "2.5.4.19"; +pub const szOID_TELEPHONE_NUMBER: &'static str = "2.5.4.20"; +pub const szOID_TELEX_NUMBER: &'static str = "2.5.4.21"; +pub const szOID_TELETEXT_TERMINAL_IDENTIFIER: &'static str = "2.5.4.22"; +pub const szOID_FACSIMILE_TELEPHONE_NUMBER: &'static str = "2.5.4.23"; +pub const szOID_X21_ADDRESS: &'static str = "2.5.4.24"; +pub const szOID_INTERNATIONAL_ISDN_NUMBER: &'static str = "2.5.4.25"; +pub const szOID_REGISTERED_ADDRESS: &'static str = "2.5.4.26"; +pub const szOID_DESTINATION_INDICATOR: &'static str = "2.5.4.27"; +pub const szOID_PREFERRED_DELIVERY_METHOD: &'static str = "2.5.4.28"; +pub const szOID_PRESENTATION_ADDRESS: &'static str = "2.5.4.29"; +pub const szOID_SUPPORTED_APPLICATION_CONTEXT: &'static str = "2.5.4.30"; +pub const szOID_MEMBER: &'static str = "2.5.4.31"; +pub const szOID_OWNER: &'static str = "2.5.4.32"; +pub const szOID_ROLE_OCCUPANT: &'static str = "2.5.4.33"; +pub const szOID_SEE_ALSO: &'static str = "2.5.4.34"; +pub const szOID_USER_PASSWORD: &'static str = "2.5.4.35"; +pub const szOID_USER_CERTIFICATE: &'static str = "2.5.4.36"; +pub const szOID_CA_CERTIFICATE: &'static str = "2.5.4.37"; +pub const szOID_AUTHORITY_REVOCATION_LIST: &'static str = "2.5.4.38"; +pub const szOID_CERTIFICATE_REVOCATION_LIST: &'static str = "2.5.4.39"; +pub const szOID_CROSS_CERTIFICATE_PAIR: &'static str = "2.5.4.40"; +pub const szOID_GIVEN_NAME: &'static str = "2.5.4.42"; +pub const szOID_INITIALS: &'static str = "2.5.4.43"; +pub const szOID_DN_QUALIFIER: &'static str = "2.5.4.46"; +pub const szOID_DOMAIN_COMPONENT: &'static str = "0.9.2342.19200300.100.1.25"; +pub const szOID_PKCS_12_FRIENDLY_NAME_ATTR: &'static str = "1.2.840.113549.1.9.20"; +pub const szOID_PKCS_12_LOCAL_KEY_ID: &'static str = "1.2.840.113549.1.9.21"; +pub const szOID_PKCS_12_KEY_PROVIDER_NAME_ATTR: &'static str = "1.3.6.1.4.1.311.17.1"; +pub const szOID_LOCAL_MACHINE_KEYSET: &'static str = "1.3.6.1.4.1.311.17.2"; +pub const szOID_PKCS_12_EXTENDED_ATTRIBUTES: &'static str = "1.3.6.1.4.1.311.17.3"; +pub const szOID_PKCS_12_PROTECTED_PASSWORD_SECRET_BAG_TYPE_ID: &'static str = + "1.3.6.1.4.1.311.17.4"; +pub const szOID_KEYID_RDN: &'static str = "1.3.6.1.4.1.311.10.7.1"; +pub const szOID_EV_RDN_LOCALE: &'static str = "1.3.6.1.4.1.311.60.2.1.1"; +pub const szOID_EV_RDN_STATE_OR_PROVINCE: &'static str = "1.3.6.1.4.1.311.60.2.1.2"; +pub const szOID_EV_RDN_COUNTRY: &'static str = "1.3.6.1.4.1.311.60.2.1.3"; +pub const CERT_RDN_ANY_TYPE: ::DWORD = 0; +pub const CERT_RDN_ENCODED_BLOB: ::DWORD = 1; +pub const CERT_RDN_OCTET_STRING: ::DWORD = 2; +pub const CERT_RDN_NUMERIC_STRING: ::DWORD = 3; +pub const CERT_RDN_PRINTABLE_STRING: ::DWORD = 4; +pub const CERT_RDN_TELETEX_STRING: ::DWORD = 5; +pub const CERT_RDN_T61_STRING: ::DWORD = 5; +pub const CERT_RDN_VIDEOTEX_STRING: ::DWORD = 6; +pub const CERT_RDN_IA5_STRING: ::DWORD = 7; +pub const CERT_RDN_GRAPHIC_STRING: ::DWORD = 8; +pub const CERT_RDN_VISIBLE_STRING: ::DWORD = 9; +pub const CERT_RDN_ISO646_STRING: ::DWORD = 9; +pub const CERT_RDN_GENERAL_STRING: ::DWORD = 10; +pub const CERT_RDN_UNIVERSAL_STRING: ::DWORD = 11; +pub const CERT_RDN_INT4_STRING: ::DWORD = 11; +pub const CERT_RDN_BMP_STRING: ::DWORD = 12; +pub const CERT_RDN_UNICODE_STRING: ::DWORD = 12; +pub const CERT_RDN_UTF8_STRING: ::DWORD = 13; +pub const CERT_RDN_TYPE_MASK: ::DWORD = 0x000000FF; +pub const CERT_RDN_FLAGS_MASK: ::DWORD = 0xFF000000; +pub const CERT_RDN_ENABLE_T61_UNICODE_FLAG: ::DWORD = 0x80000000; +pub const CERT_RDN_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = 0x20000000; +pub const CERT_RDN_FORCE_UTF8_UNICODE_FLAG: ::DWORD = 0x10000000; +pub const CERT_RDN_DISABLE_CHECK_TYPE_FLAG: ::DWORD = 0x40000000; +pub const CERT_RDN_DISABLE_IE4_UTF8_FLAG: ::DWORD = 0x01000000; +pub const CERT_RDN_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x02000000; +STRUCT!{struct CERT_RDN { + cRDNAttr: ::DWORD, + rgRDNAttr: PCERT_RDN_ATTR, +}} +pub type PCERT_RDN = *mut CERT_RDN; +STRUCT!{struct CERT_NAME_INFO { + cRDN: ::DWORD, + rgRDN: PCERT_RDN, +}} +pub type PCERT_NAME_INFO = *mut CERT_NAME_INFO; +STRUCT!{struct CERT_NAME_VALUE { + dwValueType: ::DWORD, + Value: CERT_RDN_VALUE_BLOB, +}} +pub type PCERT_NAME_VALUE = *mut CERT_NAME_VALUE; +STRUCT!{struct CERT_PUBLIC_KEY_INFO { + Algorithm: CRYPT_ALGORITHM_IDENTIFIER, + PublicKey: CRYPT_BIT_BLOB, +}} +pub type PCERT_PUBLIC_KEY_INFO = *mut CERT_PUBLIC_KEY_INFO; +pub const CERT_RSA_PUBLIC_KEY_OBJID: &'static str = szOID_RSA_RSA; +pub const CERT_DEFAULT_OID_PUBLIC_KEY_SIGN: &'static str = szOID_RSA_RSA; +pub const CERT_DEFAULT_OID_PUBLIC_KEY_XCHG: &'static str = szOID_RSA_RSA; +STRUCT!{struct CRYPT_ECC_PRIVATE_KEY_INFO { + dwVersion: ::DWORD, + PrivateKey: CRYPT_DER_BLOB, + szCurveOid: ::LPSTR, + PublicKey: CRYPT_BIT_BLOB, +}} +pub type PCRYPT_ECC_PRIVATE_KEY_INFO = *mut CRYPT_ECC_PRIVATE_KEY_INFO; +pub const CRYPT_ECC_PRIVATE_KEY_INFO_v1: ::DWORD = 1; +STRUCT!{struct CRYPT_PRIVATE_KEY_INFO { + Version: ::DWORD, + Algorithm: CRYPT_ALGORITHM_IDENTIFIER, + PrivateKey: CRYPT_DER_BLOB, + pAttributes: PCRYPT_ATTRIBUTES, +}} +pub type PCRYPT_PRIVATE_KEY_INFO = *mut CRYPT_PRIVATE_KEY_INFO; +STRUCT!{struct CRYPT_ENCRYPTED_PRIVATE_KEY_INFO { + EncryptionAlgorithm: ::CRYPT_ALGORITHM_IDENTIFIER, + EncryptedPrivateKey: ::CRYPT_DATA_BLOB, +}} +pub type PCRYPT_ENCRYPTED_PRIVATE_KEY_INFO = *mut CRYPT_ENCRYPTED_PRIVATE_KEY_INFO; +pub type PCRYPT_DECRYPT_PRIVATE_KEY_FUNC = Option ::BOOL>; +pub type PCRYPT_ENCRYPT_PRIVATE_KEY_FUNC = Option ::BOOL>; +pub type PCRYPT_RESOLVE_HCRYPTPROV_FUNC = Option ::BOOL>; +STRUCT!{nodebug struct CRYPT_PKCS8_IMPORT_PARAMS { + PrivateKey: CRYPT_DIGEST_BLOB, + pResolvehCryptProvFunc: PCRYPT_RESOLVE_HCRYPTPROV_FUNC, + pVoidResolveFunc: ::LPVOID, + pDecryptPrivateKeyFunc: PCRYPT_DECRYPT_PRIVATE_KEY_FUNC, + pVoidDecryptFunc: ::LPVOID, +}} +pub type PCRYPT_PKCS8_IMPORT_PARAMS = *mut CRYPT_PKCS8_IMPORT_PARAMS; +pub type CRYPT_PRIVATE_KEY_BLOB_AND_PARAMS = CRYPT_PKCS8_IMPORT_PARAMS; +pub type PPCRYPT_PRIVATE_KEY_BLOB_AND_PARAMS = *mut CRYPT_PKCS8_IMPORT_PARAMS; +STRUCT!{nodebug struct CRYPT_PKCS8_EXPORT_PARAMS { + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + pszPrivateKeyObjId: ::LPSTR, + pEncryptPrivateKeyFunc: PCRYPT_ENCRYPT_PRIVATE_KEY_FUNC, + pVoidEncryptFunc: ::LPVOID, +}} +pub type PCRYPT_PKCS8_EXPORT_PARAMS = *mut CRYPT_PKCS8_EXPORT_PARAMS; +STRUCT!{struct CERT_INFO { + dwVersion: ::DWORD, + SerialNumber: CRYPT_INTEGER_BLOB, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Issuer: CERT_NAME_BLOB, + NotBefore: ::FILETIME, + NotAfter: ::FILETIME, + Subject: CERT_NAME_BLOB, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + IssuerUniqueId: CRYPT_BIT_BLOB, + SubjectUniqueId: CRYPT_BIT_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCERT_INFO = *mut CERT_INFO; +pub const CERT_V1: ::DWORD = 0; +pub const CERT_V2: ::DWORD = 1; +pub const CERT_V3: ::DWORD = 2; +pub const CERT_INFO_VERSION_FLAG: ::DWORD = 1; +pub const CERT_INFO_SERIAL_NUMBER_FLAG: ::DWORD = 2; +pub const CERT_INFO_SIGNATURE_ALGORITHM_FLAG: ::DWORD = 3; +pub const CERT_INFO_ISSUER_FLAG: ::DWORD = 4; +pub const CERT_INFO_NOT_BEFORE_FLAG: ::DWORD = 5; +pub const CERT_INFO_NOT_AFTER_FLAG: ::DWORD = 6; +pub const CERT_INFO_SUBJECT_FLAG: ::DWORD = 7; +pub const CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG: ::DWORD = 8; +pub const CERT_INFO_ISSUER_UNIQUE_ID_FLAG: ::DWORD = 9; +pub const CERT_INFO_SUBJECT_UNIQUE_ID_FLAG: ::DWORD = 10; +pub const CERT_INFO_EXTENSION_FLAG: ::DWORD = 11; +STRUCT!{struct CRL_ENTRY { + SerialNumber: CRYPT_INTEGER_BLOB, + RevocationDate: ::FILETIME, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRL_ENTRY = *mut CRL_ENTRY; +STRUCT!{struct CRL_INFO { + dwVersion: ::DWORD, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Issuer: CERT_NAME_BLOB, + ThisUpdate: ::FILETIME, + NextUpdate: ::FILETIME, + cCRLEntry: ::DWORD, + rgCRLEntry: PCRL_ENTRY, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRL_INFO = *mut CRL_INFO; +pub const CRL_V1: ::DWORD = 0; +pub const CRL_V2: ::DWORD = 1; +pub const CERT_BUNDLE_CERTIFICATE: ::DWORD = 0; +pub const CERT_BUNDLE_CRL: ::DWORD = 1; +STRUCT!{struct CERT_OR_CRL_BLOB { + dwChoice: ::DWORD, + cbEncoded: ::DWORD, + pbEncoded: *mut ::BYTE, +}} +pub type PCERT_OR_CRL_BLOB = *mut CERT_OR_CRL_BLOB; +STRUCT!{struct CERT_OR_CRL_BUNDLE { + cItem: ::DWORD, + rgItem: PCERT_OR_CRL_BLOB, +}} +pub type PCERT_OR_CRL_BUNDLE = *mut CERT_OR_CRL_BUNDLE; +STRUCT!{struct CERT_REQUEST_INFO { + dwVersion: ::DWORD, + Subject: CERT_NAME_BLOB, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCERT_REQUEST_INFO = *mut CERT_REQUEST_INFO; +pub const CERT_REQUEST_V1: ::DWORD = 0; +STRUCT!{struct CERT_KEYGEN_REQUEST_INFO { + dwVersion: ::DWORD, + SubjectPublicKeyInfo: CERT_PUBLIC_KEY_INFO, + pwszChallengeString: ::LPWSTR, +}} +pub type PCERT_KEYGEN_REQUEST_INFO = *mut CERT_KEYGEN_REQUEST_INFO; +pub const CERT_KEYGEN_REQUEST_V1: ::DWORD = 0; +STRUCT!{struct CERT_SIGNED_CONTENT_INFO { + ToBeSigned: CRYPT_DER_BLOB, + SignatureAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + Signature: CRYPT_BIT_BLOB, +}} +pub type PCERT_SIGNED_CONTENT_INFO = *mut CERT_SIGNED_CONTENT_INFO; +STRUCT!{struct CTL_USAGE { + cUsageIdentifier: ::DWORD, + rgpszUsageIdentifier: *mut ::LPSTR, +}} +pub type PCTL_USAGE = *mut CTL_USAGE; +pub type CERT_ENHKEY_USAGE = CTL_USAGE; +pub type PCERT_ENHKEY_USAGE = *mut CERT_ENHKEY_USAGE; +pub type PCCTL_USAGE = *const CTL_USAGE; +pub type PCCERT_ENHKEY_USAGE = *const CERT_ENHKEY_USAGE; +STRUCT!{struct CTL_ENTRY { + SubjectIdentifier: CRYPT_DATA_BLOB, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCTL_ENTRY = *mut CTL_ENTRY; +STRUCT!{struct CTL_INFO { + dwVersion: ::DWORD, + SubjectUsage: CTL_USAGE, + ListIdentifier: CRYPT_DATA_BLOB, + SequenceNumber: CRYPT_INTEGER_BLOB, + ThisUpdate: ::FILETIME, + NextUpdate: ::FILETIME, + SubjectAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + cCTLEntry: ::DWORD, + rgCTLEntry: PCTL_ENTRY, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCTL_INFO = *mut CTL_INFO; +pub const CTL_V1: ::DWORD = 0; +STRUCT!{struct CRYPT_TIME_STAMP_REQUEST_INFO { + pszTimeStampAlgorithm: ::LPSTR, + pszContentType: ::LPSTR, + Content: CRYPT_OBJID_BLOB, + cAttribute: ::DWORD, + rgAttribute: PCRYPT_ATTRIBUTE, +}} +pub type PCRYPT_TIME_STAMP_REQUEST_INFO = *mut CRYPT_TIME_STAMP_REQUEST_INFO; +STRUCT!{struct CRYPT_ENROLLMENT_NAME_VALUE_PAIR { + pwszName: ::LPWSTR, + pwszValue: ::LPWSTR, +}} +pub type PCRYPT_ENROLLMENT_NAME_VALUE_PAIR = *mut CRYPT_ENROLLMENT_NAME_VALUE_PAIR; +STRUCT!{struct CRYPT_CSP_PROVIDER { + dwKeySpec: ::DWORD, + pwszProviderName: ::LPWSTR, + Signature: CRYPT_BIT_BLOB, +}} +pub type PCRYPT_CSP_PROVIDER = *mut CRYPT_CSP_PROVIDER; +pub const CERT_ENCODING_TYPE_MASK: ::DWORD = 0x0000FFFF; +pub const CMSG_ENCODING_TYPE_MASK: ::DWORD = 0xFFFF0000; +pub const CRYPT_ASN_ENCODING: ::DWORD = 0x00000001; +pub const CRYPT_NDR_ENCODING: ::DWORD = 0x00000002; +pub const X509_ASN_ENCODING: ::DWORD = 0x00000001; +pub const X509_NDR_ENCODING: ::DWORD = 0x00000002; +pub const PKCS_7_ASN_ENCODING: ::DWORD = 0x00010000; +pub const PKCS_7_NDR_ENCODING: ::DWORD = 0x00020000; +pub const CRYPT_FORMAT_STR_MULTI_LINE: ::DWORD = 0x0001; +pub const CRYPT_FORMAT_STR_NO_HEX: ::DWORD = 0x0010; +pub const CRYPT_FORMAT_SIMPLE: ::DWORD = 0x0001; +pub const CRYPT_FORMAT_X509: ::DWORD = 0x0002; +pub const CRYPT_FORMAT_OID: ::DWORD = 0x0004; +pub const CRYPT_FORMAT_RDN_SEMICOLON: ::DWORD = 0x0100; +pub const CRYPT_FORMAT_RDN_CRLF: ::DWORD = 0x0200; +pub const CRYPT_FORMAT_RDN_UNQUOTE: ::DWORD = 0x0400; +pub const CRYPT_FORMAT_RDN_REVERSE: ::DWORD = 0x0800; +pub const CRYPT_FORMAT_COMMA: ::DWORD = 0x1000; +pub const CRYPT_FORMAT_SEMICOLON: ::DWORD = CRYPT_FORMAT_RDN_SEMICOLON; +pub const CRYPT_FORMAT_CRLF: ::DWORD = CRYPT_FORMAT_RDN_CRLF; +pub type PFN_CRYPT_ALLOC = Option; +pub type PFN_CRYPT_FREE = Option; +STRUCT!{nodebug struct CRYPT_ENCODE_PARA { + cbSize: ::DWORD, + pfnAlloc: PFN_CRYPT_ALLOC, + pfnFree: PFN_CRYPT_FREE, +}} +pub type PCRYPT_ENCODE_PARA = *mut CRYPT_ENCODE_PARA; +pub const CRYPT_ENCODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: ::DWORD = 0x8; +pub const CRYPT_ENCODE_ALLOC_FLAG: ::DWORD = 0x8000; +pub const CRYPT_UNICODE_NAME_ENCODE_ENABLE_T61_UNICODE_FLAG: ::DWORD = + CERT_RDN_ENABLE_T61_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = + CERT_RDN_ENABLE_UTF8_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_FORCE_UTF8_UNICODE_FLAG: ::DWORD = + CERT_RDN_FORCE_UTF8_UNICODE_FLAG; +pub const CRYPT_UNICODE_NAME_ENCODE_DISABLE_CHECK_TYPE_FLAG: ::DWORD = + CERT_RDN_DISABLE_CHECK_TYPE_FLAG; +pub const CRYPT_SORTED_CTL_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: ::DWORD = 0x10000; +pub const CRYPT_ENCODE_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x20000; +pub const CRYPT_ENCODE_ENABLE_UTF8PERCENT_FLAG: ::DWORD = 0x40000; +pub const CRYPT_ENCODE_ENABLE_IA5CONVERSION_FLAG: ::DWORD = CRYPT_ENCODE_ENABLE_PUNYCODE_FLAG + | CRYPT_ENCODE_ENABLE_UTF8PERCENT_FLAG; +STRUCT!{nodebug struct CRYPT_DECODE_PARA { + cbSize: ::DWORD, + pfnAlloc: PFN_CRYPT_ALLOC, + pfnFree: PFN_CRYPT_FREE, +}} +pub type PCRYPT_DECODE_PARA = *mut CRYPT_DECODE_PARA; +pub const CRYPT_DECODE_NOCOPY_FLAG: ::DWORD = 0x1; +pub const CRYPT_DECODE_TO_BE_SIGNED_FLAG: ::DWORD = 0x2; +pub const CRYPT_DECODE_SHARE_OID_STRING_FLAG: ::DWORD = 0x4; +pub const CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: ::DWORD = 0x8; +pub const CRYPT_DECODE_ALLOC_FLAG: ::DWORD = 0x8000; +pub const CRYPT_UNICODE_NAME_DECODE_DISABLE_IE4_UTF8_FLAG: ::DWORD = + CERT_RDN_DISABLE_IE4_UTF8_FLAG; +pub const CRYPT_DECODE_ENABLE_PUNYCODE_FLAG: ::DWORD = 0x02000000; +pub const CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG: ::DWORD = 0x04000000; +pub const CRYPT_DECODE_ENABLE_IA5CONVERSION_FLAG: ::DWORD = CRYPT_DECODE_ENABLE_PUNYCODE_FLAG + | CRYPT_DECODE_ENABLE_UTF8PERCENT_FLAG; +pub const CRYPT_ENCODE_DECODE_NONE: ::LPCSTR = 0 as ::LPCSTR; +pub const X509_CERT: ::LPCSTR = 1 as ::LPCSTR; +pub const X509_CERT_TO_BE_SIGNED: ::LPCSTR = 2 as ::LPCSTR; +pub const X509_CERT_CRL_TO_BE_SIGNED: ::LPCSTR = 3 as ::LPCSTR; +pub const X509_CERT_REQUEST_TO_BE_SIGNED: ::LPCSTR = 4 as ::LPCSTR; +pub const X509_EXTENSIONS: ::LPCSTR = 5 as ::LPCSTR; +pub const X509_NAME_VALUE: ::LPCSTR = 6 as ::LPCSTR; +pub const X509_NAME: ::LPCSTR = 7 as ::LPCSTR; +pub const X509_PUBLIC_KEY_INFO: ::LPCSTR = 8 as ::LPCSTR; +pub const X509_AUTHORITY_KEY_ID: ::LPCSTR = 9 as ::LPCSTR; +pub const X509_KEY_ATTRIBUTES: ::LPCSTR = 10 as ::LPCSTR; +pub const X509_KEY_USAGE_RESTRICTION: ::LPCSTR = 11 as ::LPCSTR; +pub const X509_ALTERNATE_NAME: ::LPCSTR = 12 as ::LPCSTR; +pub const X509_BASIC_CONSTRAINTS: ::LPCSTR = 13 as ::LPCSTR; +pub const X509_KEY_USAGE: ::LPCSTR = 14 as ::LPCSTR; +pub const X509_BASIC_CONSTRAINTS2: ::LPCSTR = 15 as ::LPCSTR; +pub const X509_CERT_POLICIES: ::LPCSTR = 16 as ::LPCSTR; +pub const PKCS_UTC_TIME: ::LPCSTR = 17 as ::LPCSTR; +pub const PKCS_TIME_REQUEST: ::LPCSTR = 18 as ::LPCSTR; +pub const RSA_CSP_PUBLICKEYBLOB: ::LPCSTR = 19 as ::LPCSTR; +pub const X509_UNICODE_NAME: ::LPCSTR = 20 as ::LPCSTR; +pub const X509_KEYGEN_REQUEST_TO_BE_SIGNED: ::LPCSTR = 21 as ::LPCSTR; +pub const PKCS_ATTRIBUTE: ::LPCSTR = 22 as ::LPCSTR; +pub const PKCS_CONTENT_INFO_SEQUENCE_OF_ANY: ::LPCSTR = 23 as ::LPCSTR; +pub const X509_UNICODE_NAME_VALUE: ::LPCSTR = 24 as ::LPCSTR; +pub const X509_ANY_STRING: ::LPCSTR = X509_NAME_VALUE; +pub const X509_UNICODE_ANY_STRING: ::LPCSTR = X509_UNICODE_NAME_VALUE; +pub const X509_OCTET_STRING: ::LPCSTR = 25 as ::LPCSTR; +pub const X509_BITS: ::LPCSTR = 26 as ::LPCSTR; +pub const X509_INTEGER: ::LPCSTR = 27 as ::LPCSTR; +pub const X509_MULTI_BYTE_INTEGER: ::LPCSTR = 28 as ::LPCSTR; +pub const X509_ENUMERATED: ::LPCSTR = 29 as ::LPCSTR; +pub const X509_CHOICE_OF_TIME: ::LPCSTR = 30 as ::LPCSTR; +pub const X509_AUTHORITY_KEY_ID2: ::LPCSTR = 31 as ::LPCSTR; +pub const X509_AUTHORITY_INFO_ACCESS: ::LPCSTR = 32 as ::LPCSTR; +pub const X509_SUBJECT_INFO_ACCESS: ::LPCSTR = X509_AUTHORITY_INFO_ACCESS; +pub const X509_CRL_REASON_CODE: ::LPCSTR = X509_ENUMERATED; +pub const PKCS_CONTENT_INFO: ::LPCSTR = 33 as ::LPCSTR; +pub const X509_SEQUENCE_OF_ANY: ::LPCSTR = 34 as ::LPCSTR; +pub const X509_CRL_DIST_POINTS: ::LPCSTR = 35 as ::LPCSTR; +pub const X509_ENHANCED_KEY_USAGE: ::LPCSTR = 36 as ::LPCSTR; +pub const PKCS_CTL: ::LPCSTR = 37 as ::LPCSTR; +pub const X509_MULTI_BYTE_UINT: ::LPCSTR = 38 as ::LPCSTR; +pub const X509_DSS_PUBLICKEY: ::LPCSTR = X509_MULTI_BYTE_UINT; +pub const X509_DSS_PARAMETERS: ::LPCSTR = 39 as ::LPCSTR; +pub const X509_DSS_SIGNATURE: ::LPCSTR = 40 as ::LPCSTR; +pub const PKCS_RC2_CBC_PARAMETERS: ::LPCSTR = 41 as ::LPCSTR; +pub const PKCS_SMIME_CAPABILITIES: ::LPCSTR = 42 as ::LPCSTR; +pub const X509_QC_STATEMENTS_EXT: ::LPCSTR = 42 as ::LPCSTR; +pub const PKCS_RSA_PRIVATE_KEY: ::LPCSTR = 43 as ::LPCSTR; +pub const PKCS_PRIVATE_KEY_INFO: ::LPCSTR = 44 as ::LPCSTR; +pub const PKCS_ENCRYPTED_PRIVATE_KEY_INFO: ::LPCSTR = 45 as ::LPCSTR; +pub const X509_PKIX_POLICY_QUALIFIER_USERNOTICE: ::LPCSTR = 46 as ::LPCSTR; +pub const X509_DH_PUBLICKEY: ::LPCSTR = X509_MULTI_BYTE_UINT; +pub const X509_DH_PARAMETERS: ::LPCSTR = 47 as ::LPCSTR; +pub const PKCS_ATTRIBUTES: ::LPCSTR = 48 as ::LPCSTR; +pub const PKCS_SORTED_CTL: ::LPCSTR = 49 as ::LPCSTR; +pub const X509_ECC_SIGNATURE: ::LPCSTR = 47 as ::LPCSTR; +pub const X942_DH_PARAMETERS: ::LPCSTR = 50 as ::LPCSTR; +pub const X509_BITS_WITHOUT_TRAILING_ZEROES: ::LPCSTR = 51 as ::LPCSTR; +pub const X942_OTHER_INFO: ::LPCSTR = 52 as ::LPCSTR; +pub const X509_CERT_PAIR: ::LPCSTR = 53 as ::LPCSTR; +pub const X509_ISSUING_DIST_POINT: ::LPCSTR = 54 as ::LPCSTR; +pub const X509_NAME_CONSTRAINTS: ::LPCSTR = 55 as ::LPCSTR; +pub const X509_POLICY_MAPPINGS: ::LPCSTR = 56 as ::LPCSTR; +pub const X509_POLICY_CONSTRAINTS: ::LPCSTR = 57 as ::LPCSTR; +pub const X509_CROSS_CERT_DIST_POINTS: ::LPCSTR = 58 as ::LPCSTR; +pub const CMC_DATA: ::LPCSTR = 59 as ::LPCSTR; +pub const CMC_RESPONSE: ::LPCSTR = 60 as ::LPCSTR; +pub const CMC_STATUS: ::LPCSTR = 61 as ::LPCSTR; +pub const CMC_ADD_EXTENSIONS: ::LPCSTR = 62 as ::LPCSTR; +pub const CMC_ADD_ATTRIBUTES: ::LPCSTR = 63 as ::LPCSTR; +pub const X509_CERTIFICATE_TEMPLATE: ::LPCSTR = 64 as ::LPCSTR; +pub const OCSP_SIGNED_REQUEST: ::LPCSTR = 65 as ::LPCSTR; +pub const OCSP_REQUEST: ::LPCSTR = 66 as ::LPCSTR; +pub const OCSP_RESPONSE: ::LPCSTR = 67 as ::LPCSTR; +pub const OCSP_BASIC_SIGNED_RESPONSE: ::LPCSTR = 68 as ::LPCSTR; +pub const OCSP_BASIC_RESPONSE: ::LPCSTR = 69 as ::LPCSTR; +pub const X509_LOGOTYPE_EXT: ::LPCSTR = 70 as ::LPCSTR; +pub const X509_BIOMETRIC_EXT: ::LPCSTR = 71 as ::LPCSTR; +pub const CNG_RSA_PUBLIC_KEY_BLOB: ::LPCSTR = 72 as ::LPCSTR; +pub const X509_OBJECT_IDENTIFIER: ::LPCSTR = 73 as ::LPCSTR; +pub const X509_ALGORITHM_IDENTIFIER: ::LPCSTR = 74 as ::LPCSTR; +pub const PKCS_RSA_SSA_PSS_PARAMETERS: ::LPCSTR = 75 as ::LPCSTR; +pub const PKCS_RSAES_OAEP_PARAMETERS: ::LPCSTR = 76 as ::LPCSTR; +pub const ECC_CMS_SHARED_INFO: ::LPCSTR = 77 as ::LPCSTR; +pub const TIMESTAMP_REQUEST: ::LPCSTR = 78 as ::LPCSTR; +pub const TIMESTAMP_RESPONSE: ::LPCSTR = 79 as ::LPCSTR; +pub const TIMESTAMP_INFO: ::LPCSTR = 80 as ::LPCSTR; +pub const X509_CERT_BUNDLE: ::LPCSTR = 81 as ::LPCSTR; +pub const X509_ECC_PRIVATE_KEY: ::LPCSTR = 82 as ::LPCSTR; +pub const CNG_RSA_PRIVATE_KEY_BLOB: ::LPCSTR = 83 as ::LPCSTR; +pub const X509_SUBJECT_DIR_ATTRS: ::LPCSTR = 84 as ::LPCSTR; +pub const PKCS7_SIGNER_INFO: ::LPCSTR = 500 as ::LPCSTR; +pub const CMS_SIGNER_INFO: ::LPCSTR = 501 as ::LPCSTR; +pub const szOID_AUTHORITY_KEY_IDENTIFIER: &'static str = "2.5.29.1"; +pub const szOID_KEY_ATTRIBUTES: &'static str = "2.5.29.2"; +pub const szOID_CERT_POLICIES_95: &'static str = "2.5.29.3"; +pub const szOID_KEY_USAGE_RESTRICTION: &'static str = "2.5.29.4"; +pub const szOID_SUBJECT_ALT_NAME: &'static str = "2.5.29.7"; +pub const szOID_ISSUER_ALT_NAME: &'static str = "2.5.29.8"; +pub const szOID_BASIC_CONSTRAINTS: &'static str = "2.5.29.10"; +pub const szOID_KEY_USAGE: &'static str = "2.5.29.15"; +pub const szOID_PRIVATEKEY_USAGE_PERIOD: &'static str = "2.5.29.16"; +pub const szOID_BASIC_CONSTRAINTS2: &'static str = "2.5.29.19"; +pub const szOID_CERT_POLICIES: &'static str = "2.5.29.32"; +pub const szOID_ANY_CERT_POLICY: &'static str = "2.5.29.32.0"; +pub const szOID_INHIBIT_ANY_POLICY: &'static str = "2.5.29.54"; +pub const szOID_AUTHORITY_KEY_IDENTIFIER2: &'static str = "2.5.29.35"; +pub const szOID_SUBJECT_KEY_IDENTIFIER: &'static str = "2.5.29.14"; +pub const szOID_SUBJECT_ALT_NAME2: &'static str = "2.5.29.17"; +pub const szOID_ISSUER_ALT_NAME2: &'static str = "2.5.29.18"; +pub const szOID_CRL_REASON_CODE: &'static str = "2.5.29.21"; +pub const szOID_REASON_CODE_HOLD: &'static str = "2.5.29.23"; +pub const szOID_CRL_DIST_POINTS: &'static str = "2.5.29.31"; +pub const szOID_ENHANCED_KEY_USAGE: &'static str = "2.5.29.37"; +pub const szOID_ANY_ENHANCED_KEY_USAGE: &'static str = "2.5.29.37.0"; +pub const szOID_CRL_NUMBER: &'static str = "2.5.29.20"; +pub const szOID_DELTA_CRL_INDICATOR: &'static str = "2.5.29.27"; +pub const szOID_ISSUING_DIST_POINT: &'static str = "2.5.29.28"; +pub const szOID_FRESHEST_CRL: &'static str = "2.5.29.46"; +pub const szOID_NAME_CONSTRAINTS: &'static str = "2.5.29.30"; +pub const szOID_POLICY_MAPPINGS: &'static str = "2.5.29.33"; +pub const szOID_LEGACY_POLICY_MAPPINGS: &'static str = "2.5.29.5"; +pub const szOID_POLICY_CONSTRAINTS: &'static str = "2.5.29.36"; +pub const szOID_RENEWAL_CERTIFICATE: &'static str = "1.3.6.1.4.1.311.13.1"; +pub const szOID_ENROLLMENT_NAME_VALUE_PAIR: &'static str = "1.3.6.1.4.1.311.13.2.1"; +pub const szOID_ENROLLMENT_CSP_PROVIDER: &'static str = "1.3.6.1.4.1.311.13.2.2"; +pub const szOID_OS_VERSION: &'static str = "1.3.6.1.4.1.311.13.2.3"; +pub const szOID_ENROLLMENT_AGENT: &'static str = "1.3.6.1.4.1.311.20.2.1"; +pub const szOID_PKIX: &'static str = "1.3.6.1.5.5.7"; +pub const szOID_PKIX_PE: &'static str = "1.3.6.1.5.5.7.1"; +pub const szOID_AUTHORITY_INFO_ACCESS: &'static str = "1.3.6.1.5.5.7.1.1"; +pub const szOID_SUBJECT_INFO_ACCESS: &'static str = "1.3.6.1.5.5.7.1.11"; +pub const szOID_BIOMETRIC_EXT: &'static str = "1.3.6.1.5.5.7.1.2"; +pub const szOID_QC_STATEMENTS_EXT: &'static str = "1.3.6.1.5.5.7.1.3"; +pub const szOID_LOGOTYPE_EXT: &'static str = "1.3.6.1.5.5.7.1.12"; +pub const szOID_CERT_EXTENSIONS: &'static str = "1.3.6.1.4.1.311.2.1.14"; +pub const szOID_NEXT_UPDATE_LOCATION: &'static str = "1.3.6.1.4.1.311.10.2"; +pub const szOID_REMOVE_CERTIFICATE: &'static str = "1.3.6.1.4.1.311.10.8.1"; +pub const szOID_CROSS_CERT_DIST_POINTS: &'static str = "1.3.6.1.4.1.311.10.9.1"; +pub const szOID_CTL: &'static str = "1.3.6.1.4.1.311.10.1"; +pub const szOID_SORTED_CTL: &'static str = "1.3.6.1.4.1.311.10.1.1"; +pub const szOID_SERIALIZED: &'static str = "1.3.6.1.4.1.311.10.3.3.1"; +pub const szOID_NT_PRINCIPAL_NAME: &'static str = "1.3.6.1.4.1.311.20.2.3"; +pub const szOID_INTERNATIONALIZED_EMAIL_ADDRESS: &'static str = "1.3.6.1.4.1.311.20.2.4"; +pub const szOID_PRODUCT_UPDATE: &'static str = "1.3.6.1.4.1.311.31.1"; +pub const szOID_ANY_APPLICATION_POLICY: &'static str = "1.3.6.1.4.1.311.10.12.1"; +pub const szOID_AUTO_ENROLL_CTL_USAGE: &'static str = "1.3.6.1.4.1.311.20.1"; +pub const szOID_ENROLL_CERTTYPE_EXTENSION: &'static str = "1.3.6.1.4.1.311.20.2"; +pub const szOID_CERT_MANIFOLD: &'static str = "1.3.6.1.4.1.311.20.3"; +pub const szOID_CERTSRV_CA_VERSION: &'static str = "1.3.6.1.4.1.311.21.1"; +pub const szOID_CERTSRV_PREVIOUS_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.2"; +pub const szOID_CRL_VIRTUAL_BASE: &'static str = "1.3.6.1.4.1.311.21.3"; +pub const szOID_CRL_NEXT_PUBLISH: &'static str = "1.3.6.1.4.1.311.21.4"; +pub const szOID_KP_CA_EXCHANGE: &'static str = "1.3.6.1.4.1.311.21.5"; +pub const szOID_KP_KEY_RECOVERY_AGENT: &'static str = "1.3.6.1.4.1.311.21.6"; +pub const szOID_CERTIFICATE_TEMPLATE: &'static str = "1.3.6.1.4.1.311.21.7"; +pub const szOID_ENTERPRISE_OID_ROOT: &'static str = "1.3.6.1.4.1.311.21.8"; +pub const szOID_RDN_DUMMY_SIGNER: &'static str = "1.3.6.1.4.1.311.21.9"; +pub const szOID_APPLICATION_CERT_POLICIES: &'static str = "1.3.6.1.4.1.311.21.10"; +pub const szOID_APPLICATION_POLICY_MAPPINGS: &'static str = "1.3.6.1.4.1.311.21.11"; +pub const szOID_APPLICATION_POLICY_CONSTRAINTS: &'static str = "1.3.6.1.4.1.311.21.12"; +pub const szOID_ARCHIVED_KEY_ATTR: &'static str = "1.3.6.1.4.1.311.21.13"; +pub const szOID_CRL_SELF_CDP: &'static str = "1.3.6.1.4.1.311.21.14"; +pub const szOID_REQUIRE_CERT_CHAIN_POLICY: &'static str = "1.3.6.1.4.1.311.21.15"; +pub const szOID_ARCHIVED_KEY_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.16"; +pub const szOID_ISSUED_CERT_HASH: &'static str = "1.3.6.1.4.1.311.21.17"; +pub const szOID_DS_EMAIL_REPLICATION: &'static str = "1.3.6.1.4.1.311.21.19"; +pub const szOID_REQUEST_CLIENT_INFO: &'static str = "1.3.6.1.4.1.311.21.20"; +pub const szOID_ENCRYPTED_KEY_HASH: &'static str = "1.3.6.1.4.1.311.21.21"; +pub const szOID_CERTSRV_CROSSCA_VERSION: &'static str = "1.3.6.1.4.1.311.21.22"; +pub const szOID_NTDS_REPLICATION: &'static str = "1.3.6.1.4.1.311.25.1"; +pub const szOID_SUBJECT_DIR_ATTRS: &'static str = "2.5.29.9"; +pub const szOID_PKIX_KP: &'static str = "1.3.6.1.5.5.7.3"; +pub const szOID_PKIX_KP_SERVER_AUTH: &'static str = "1.3.6.1.5.5.7.3.1"; +pub const szOID_PKIX_KP_CLIENT_AUTH: &'static str = "1.3.6.1.5.5.7.3.2"; +pub const szOID_PKIX_KP_CODE_SIGNING: &'static str = "1.3.6.1.5.5.7.3.3"; +pub const szOID_PKIX_KP_EMAIL_PROTECTION: &'static str = "1.3.6.1.5.5.7.3.4"; +pub const szOID_PKIX_KP_IPSEC_END_SYSTEM: &'static str = "1.3.6.1.5.5.7.3.5"; +pub const szOID_PKIX_KP_IPSEC_TUNNEL: &'static str = "1.3.6.1.5.5.7.3.6"; +pub const szOID_PKIX_KP_IPSEC_USER: &'static str = "1.3.6.1.5.5.7.3.7"; +pub const szOID_PKIX_KP_TIMESTAMP_SIGNING: &'static str = "1.3.6.1.5.5.7.3.8"; +pub const szOID_PKIX_KP_OCSP_SIGNING: &'static str = "1.3.6.1.5.5.7.3.9"; +pub const szOID_PKIX_OCSP_NOCHECK: &'static str = "1.3.6.1.5.5.7.48.1.5"; +pub const szOID_PKIX_OCSP_NONCE: &'static str = "1.3.6.1.5.5.7.48.1.2"; +pub const szOID_IPSEC_KP_IKE_INTERMEDIATE: &'static str = "1.3.6.1.5.5.8.2.2"; +pub const szOID_PKINIT_KP_KDC: &'static str = "1.3.6.1.5.2.3.5"; +pub const szOID_KP_CTL_USAGE_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.1"; +pub const szOID_KP_TIME_STAMP_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.2"; +pub const szOID_SERVER_GATED_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.3"; +pub const szOID_SGC_NETSCAPE: &'static str = "2.16.840.1.113730.4.1"; +pub const szOID_KP_EFS: &'static str = "1.3.6.1.4.1.311.10.3.4"; +pub const szOID_EFS_RECOVERY: &'static str = "1.3.6.1.4.1.311.10.3.4.1"; +pub const szOID_WHQL_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.5"; +pub const szOID_NT5_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.6"; +pub const szOID_OEM_WHQL_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.7"; +pub const szOID_EMBEDDED_NT_CRYPTO: &'static str = "1.3.6.1.4.1.311.10.3.8"; +pub const szOID_ROOT_LIST_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.9"; +pub const szOID_KP_QUALIFIED_SUBORDINATION: &'static str = "1.3.6.1.4.1.311.10.3.10"; +pub const szOID_KP_KEY_RECOVERY: &'static str = "1.3.6.1.4.1.311.10.3.11"; +pub const szOID_KP_DOCUMENT_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.12"; +pub const szOID_KP_LIFETIME_SIGNING: &'static str = "1.3.6.1.4.1.311.10.3.13"; +pub const szOID_KP_MOBILE_DEVICE_SOFTWARE: &'static str = "1.3.6.1.4.1.311.10.3.14"; +pub const szOID_KP_SMART_DISPLAY: &'static str = "1.3.6.1.4.1.311.10.3.15"; +pub const szOID_KP_CSP_SIGNATURE: &'static str = "1.3.6.1.4.1.311.10.3.16"; +pub const szOID_DRM: &'static str = "1.3.6.1.4.1.311.10.5.1"; +pub const szOID_DRM_INDIVIDUALIZATION: &'static str = "1.3.6.1.4.1.311.10.5.2"; +pub const szOID_LICENSES: &'static str = "1.3.6.1.4.1.311.10.6.1"; +pub const szOID_LICENSE_SERVER: &'static str = "1.3.6.1.4.1.311.10.6.2"; +pub const szOID_KP_SMARTCARD_LOGON: &'static str = "1.3.6.1.4.1.311.20.2.2"; +pub const szOID_KP_KERNEL_MODE_CODE_SIGNING: &'static str = "1.3.6.1.4.1.311.61.1.1"; +pub const szOID_KP_KERNEL_MODE_TRUSTED_BOOT_SIGNING: &'static str = "1.3.6.1.4.1.311.61.4.1"; +pub const szOID_REVOKED_LIST_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.19"; +pub const szOID_WINDOWS_KITS_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.20"; +pub const szOID_WINDOWS_RT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.21"; +pub const szOID_PROTECTED_PROCESS_LIGHT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.22"; +pub const szOID_WINDOWS_TCB_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.23"; +pub const szOID_PROTECTED_PROCESS_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.24"; +pub const szOID_WINDOWS_THIRD_PARTY_COMPONENT_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.25"; +pub const szOID_WINDOWS_SOFTWARE_EXTENSION_SIGNER: &'static str = "1.3.6.1.4.1.311.10.3.26"; +pub const szOID_DISALLOWED_LIST: &'static str = "1.3.6.1.4.1.311.10.3.30"; +pub const szOID_SYNC_ROOT_CTL_EXT: &'static str = "1.3.6.1.4.1.311.10.3.50"; +pub const szOID_KP_KERNEL_MODE_HAL_EXTENSION_SIGNING: &'static str = "1.3.6.1.4.1.311.61.5.1"; +pub const szOID_WINDOWS_STORE_SIGNER: &'static str = "1.3.6.1.4.1.311.76.3.1"; +pub const szOID_DYNAMIC_CODE_GEN_SIGNER: &'static str = "1.3.6.1.4.1.311.76.5.1"; +pub const szOID_MICROSOFT_PUBLISHER_SIGNER: &'static str = "1.3.6.1.4.1.311.76.8.1"; +pub const szOID_YESNO_TRUST_ATTR: &'static str = "1.3.6.1.4.1.311.10.4.1"; +pub const szOID_PKIX_POLICY_QUALIFIER_CPS: &'static str = "1.3.6.1.5.5.7.2.1"; +pub const szOID_PKIX_POLICY_QUALIFIER_USERNOTICE: &'static str = "1.3.6.1.5.5.7.2.2"; +pub const szOID_ROOT_PROGRAM_FLAGS: &'static str = "1.3.6.1.4.1.311.60.1.1"; +//6992 +pub type HCRYPTMSG = *mut ::c_void; +//9353 +pub type HCERTSTORE = *mut ::c_void; +STRUCT!{struct CERT_CONTEXT { + dwCertEncodingType: ::DWORD, + pbCertEncoded: *mut ::BYTE, + cbCertEncoded: ::DWORD, + pCertInfo: ::PCERT_INFO, + hCertStore: HCERTSTORE, +}} +pub type PCERT_CONTEXT = *mut CERT_CONTEXT; +pub type PCCERT_CONTEXT = *const CERT_CONTEXT; +STRUCT!{struct CRL_CONTEXT { + dwCertEncodingType: ::DWORD, + pbCrlEncoded: *mut ::BYTE, + cbCrlEncoded: ::DWORD, + pCrlInfo: ::PCRL_INFO, + hCertStore: HCERTSTORE, +}} +pub type PCRL_CONTEXT = *mut CRL_CONTEXT; +pub type PCCRL_CONTEXT = *const CRL_CONTEXT; +STRUCT!{struct CTL_CONTEXT { + dwMsgAndCertEncodingType: ::DWORD, + pbCtlEncoded: *mut ::BYTE, + cbCtlEncoded: ::DWORD, + pCtlInfo: ::PCTL_INFO, + hCertStore: HCERTSTORE, + hCryptMsg: HCRYPTMSG, + pbCtlContent: *mut ::BYTE, + cbCtlContent: ::DWORD, +}} +pub type PCTL_CONTEXT = *mut CTL_CONTEXT; +pub type PCCTL_CONTEXT = *const CTL_CONTEXT; +pub const CERT_STORE_PROV_MSG: ::DWORD = 1; +pub const CERT_STORE_PROV_MEMORY: ::DWORD = 2; +pub const CERT_STORE_PROV_FILE: ::DWORD = 3; +pub const CERT_STORE_PROV_REG: ::DWORD = 4; +pub const CERT_STORE_PROV_PKCS7: ::DWORD = 5; +pub const CERT_STORE_PROV_SERIALIZED: ::DWORD = 6; +pub const CERT_STORE_PROV_FILENAME_A: ::DWORD = 7; +pub const CERT_STORE_PROV_FILENAME_W: ::DWORD = 8; +pub const CERT_STORE_PROV_FILENAME: ::DWORD = CERT_STORE_PROV_FILENAME_W; +pub const CERT_STORE_PROV_SYSTEM_A: ::DWORD = 9; +pub const CERT_STORE_PROV_SYSTEM_W: ::DWORD = 10; +pub const CERT_STORE_PROV_SYSTEM: ::DWORD = CERT_STORE_PROV_SYSTEM_W; +pub const CERT_STORE_PROV_COLLECTION: ::DWORD = 11; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY_A: ::DWORD = 12; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY_W: ::DWORD = 13; +pub const CERT_STORE_PROV_SYSTEM_REGISTRY: ::DWORD = CERT_STORE_PROV_SYSTEM_REGISTRY_W; +pub const CERT_STORE_PROV_PHYSICAL_W: ::DWORD = 14; +pub const CERT_STORE_PROV_PHYSICAL: ::DWORD = CERT_STORE_PROV_PHYSICAL_W; +pub const CERT_STORE_PROV_SMART_CARD_W: ::DWORD = 15; +pub const CERT_STORE_PROV_SMART_CARD: ::DWORD = CERT_STORE_PROV_SMART_CARD_W; +pub const CERT_STORE_PROV_LDAP_W: ::DWORD = 16; +pub const CERT_STORE_PROV_LDAP: ::DWORD = CERT_STORE_PROV_LDAP_W; +pub const CERT_STORE_NO_CRYPT_RELEASE_FLAG: ::DWORD = 0x00000001; +pub const CERT_STORE_SET_LOCALIZED_NAME_FLAG: ::DWORD = 0x00000002; +pub const CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG: ::DWORD = 0x00000004; +pub const CERT_STORE_DELETE_FLAG: ::DWORD = 0x00000010; +pub const CERT_STORE_SHARE_STORE_FLAG: ::DWORD = 0x00000040; +pub const CERT_STORE_SHARE_CONTEXT_FLAG: ::DWORD = 0x00000080; +pub const CERT_STORE_MANIFOLD_FLAG: ::DWORD = 0x00000100; +pub const CERT_STORE_ENUM_ARCHIVED_FLAG: ::DWORD = 0x00000200; +pub const CERT_STORE_UPDATE_KEYID_FLAG: ::DWORD = 0x00000400; +pub const CERT_STORE_BACKUP_RESTORE_FLAG: ::DWORD = 0x00000800; +pub const CERT_STORE_READONLY_FLAG: ::DWORD = 0x00008000; +pub const CERT_STORE_OPEN_EXISTING_FLAG: ::DWORD = 0x00004000; +pub const CERT_STORE_CREATE_NEW_FLAG: ::DWORD = 0x00002000; +pub const CERT_STORE_MAXIMUM_ALLOWED_FLAG: ::DWORD = 0x00001000; +pub const CERT_SYSTEM_STORE_UNPROTECTED_FLAG: ::DWORD = 0x40000000; +pub const CERT_SYSTEM_STORE_LOCATION_MASK: ::DWORD = 0x00FF0000; +pub const CERT_SYSTEM_STORE_LOCATION_SHIFT: ::DWORD = 16; +pub const CERT_SYSTEM_STORE_CURRENT_USER_ID: ::DWORD = 1; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ID: ::DWORD = 2; +pub const CERT_SYSTEM_STORE_CURRENT_SERVICE_ID: ::DWORD = 4; +pub const CERT_SYSTEM_STORE_SERVICES_ID: ::DWORD = 5; +pub const CERT_SYSTEM_STORE_USERS_ID: ::DWORD = 6; +pub const CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID: ::DWORD = 7; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID: ::DWORD = 8; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID: ::DWORD = 9; +pub const CERT_SYSTEM_STORE_CURRENT_USER: ::DWORD = CERT_SYSTEM_STORE_CURRENT_USER_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE: ::DWORD = CERT_SYSTEM_STORE_LOCAL_MACHINE_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_CURRENT_SERVICE: ::DWORD = CERT_SYSTEM_STORE_CURRENT_SERVICE_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_SERVICES: ::DWORD = CERT_SYSTEM_STORE_SERVICES_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_USERS: ::DWORD = CERT_SYSTEM_STORE_USERS_ID + << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY: ::DWORD = + CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY: ::DWORD = + CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE: ::DWORD = + CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID << CERT_SYSTEM_STORE_LOCATION_SHIFT; +pub const CERT_NAME_EMAIL_TYPE: ::DWORD = 1; +pub const CERT_NAME_RDN_TYPE: ::DWORD = 2; +pub const CERT_NAME_ATTR_TYPE: ::DWORD = 3; +pub const CERT_NAME_SIMPLE_DISPLAY_TYPE: ::DWORD = 4; +pub const CERT_NAME_FRIENDLY_DISPLAY_TYPE: ::DWORD = 5; +pub const CERT_NAME_DNS_TYPE: ::DWORD = 6; +pub const CERT_NAME_URL_TYPE: ::DWORD = 7; +pub const CERT_NAME_UPN_TYPE: ::DWORD = 8; +pub const CERT_SIMPLE_NAME_STR: ::DWORD = 1; +pub const CERT_OID_NAME_STR: ::DWORD = 2; +pub const CERT_X500_NAME_STR: ::DWORD = 3; + +pub const CERT_NAME_STR_SEMICOLON_FLAG: ::DWORD = 0x40000000; +pub const CERT_NAME_STR_NO_PLUS_FLAG: ::DWORD = 0x20000000; +pub const CERT_NAME_STR_NO_QUOTING_FLAG: ::DWORD = 0x10000000; +pub const CERT_NAME_STR_CRLF_FLAG: ::DWORD = 0x08000000; +pub const CERT_NAME_STR_COMMA_FLAG: ::DWORD = 0x04000000; +pub const CERT_NAME_STR_REVERSE_FLAG: ::DWORD = 0x02000000; + +pub const CERT_NAME_ISSUER_FLAG: ::DWORD = 0x1; +pub const CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG: ::DWORD = 0x00010000; +pub const CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG: ::DWORD = 0x00020000; +pub const CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG: ::DWORD = 0x00040000; +pub const CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG: ::DWORD = 0x00080000; +pub const CERT_DELETE_KEYSET_PROP_ID: ::DWORD = 101; +pub const CERT_COMPARE_MASK: ::DWORD = 0xFFFF; +pub const CERT_COMPARE_SHIFT: ::DWORD = 16; +pub const CERT_COMPARE_ANY: ::DWORD = 0; +pub const CERT_COMPARE_SHA1_HASH: ::DWORD = 1; +pub const CERT_COMPARE_NAME: ::DWORD = 2; +pub const CERT_COMPARE_ATTR: ::DWORD = 3; +pub const CERT_COMPARE_MD5_HASH: ::DWORD = 4; +pub const CERT_COMPARE_PROPERTY: ::DWORD = 5; +pub const CERT_COMPARE_PUBLIC_KEY: ::DWORD = 6; +pub const CERT_COMPARE_HASH: ::DWORD = CERT_COMPARE_SHA1_HASH; +pub const CERT_COMPARE_NAME_STR_A: ::DWORD = 7; +pub const CERT_COMPARE_NAME_STR_W: ::DWORD = 8; +pub const CERT_COMPARE_KEY_SPEC: ::DWORD = 9; +pub const CERT_COMPARE_ENHKEY_USAGE: ::DWORD = 10; +pub const CERT_COMPARE_CTL_USAGE: ::DWORD = CERT_COMPARE_ENHKEY_USAGE; +pub const CERT_COMPARE_SUBJECT_CERT: ::DWORD = 11; +pub const CERT_COMPARE_ISSUER_OF: ::DWORD = 12; +pub const CERT_COMPARE_EXISTING: ::DWORD = 13; +pub const CERT_COMPARE_SIGNATURE_HASH: ::DWORD = 14; +pub const CERT_COMPARE_KEY_IDENTIFIER: ::DWORD = 15; +pub const CERT_COMPARE_CERT_ID: ::DWORD = 16; +pub const CERT_COMPARE_CROSS_CERT_DIST_POINTS: ::DWORD = 17; +pub const CERT_COMPARE_PUBKEY_MD5_HASH: ::DWORD = 18; +pub const CERT_FIND_ANY: ::DWORD = CERT_COMPARE_ANY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SHA1_HASH: ::DWORD = CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_MD5_HASH: ::DWORD = CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SIGNATURE_HASH: ::DWORD = CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT; +pub const CERT_FIND_KEY_IDENTIFIER: ::DWORD = CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT; +pub const CERT_FIND_HASH: ::DWORD = CERT_FIND_SHA1_HASH; +pub const CERT_FIND_PROPERTY: ::DWORD = CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_PUBLIC_KEY: ::DWORD = CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT; +pub const CERT_FIND_SUBJECT_NAME: ::DWORD = (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_ATTR: ::DWORD = (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_ISSUER_NAME: ::DWORD = (CERT_COMPARE_NAME << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_ATTR: ::DWORD = (CERT_COMPARE_ATTR << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_SUBJECT_STR_A: ::DWORD = (CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_STR_W: ::DWORD = (CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT) + | CERT_INFO_SUBJECT_FLAG; +pub const CERT_FIND_SUBJECT_STR: ::DWORD = CERT_FIND_SUBJECT_STR_W; +pub const CERT_FIND_ISSUER_STR_A: ::DWORD = (CERT_COMPARE_NAME_STR_A << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_STR_W: ::DWORD = (CERT_COMPARE_NAME_STR_W << CERT_COMPARE_SHIFT) + | CERT_INFO_ISSUER_FLAG; +pub const CERT_FIND_ISSUER_STR: ::DWORD = CERT_FIND_ISSUER_STR_W; +pub const CERT_FIND_KEY_SPEC: ::DWORD = CERT_COMPARE_KEY_SPEC << CERT_COMPARE_SHIFT; +pub const CERT_FIND_ENHKEY_USAGE: ::DWORD = CERT_COMPARE_ENHKEY_USAGE << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CTL_USAGE: ::DWORD = CERT_FIND_ENHKEY_USAGE; +pub const CERT_FIND_SUBJECT_CERT: ::DWORD = CERT_COMPARE_SUBJECT_CERT << CERT_COMPARE_SHIFT; +pub const CERT_FIND_ISSUER_OF: ::DWORD = CERT_COMPARE_ISSUER_OF << CERT_COMPARE_SHIFT; +pub const CERT_FIND_EXISTING: ::DWORD = CERT_COMPARE_EXISTING << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CERT_ID: ::DWORD = CERT_COMPARE_CERT_ID << CERT_COMPARE_SHIFT; +pub const CERT_FIND_CROSS_CERT_DIST_POINTS: ::DWORD = CERT_COMPARE_CROSS_CERT_DIST_POINTS + << CERT_COMPARE_SHIFT; +pub const CERT_FIND_PUBKEY_MD5_HASH: ::DWORD = CERT_COMPARE_PUBKEY_MD5_HASH << CERT_COMPARE_SHIFT; +pub const CERT_ENCIPHER_ONLY_KEY_USAGE: ::DWORD = 0x0001; +pub const CERT_CRL_SIGN_KEY_USAGE: ::DWORD = 0x0002; +pub const CERT_KEY_CERT_SIGN_KEY_USAGE: ::DWORD = 0x0004; +pub const CERT_KEY_AGREEMENT_KEY_USAGE: ::DWORD = 0x0008; +pub const CERT_DATA_ENCIPHERMENT_KEY_USAGE: ::DWORD = 0x0010; +pub const CERT_KEY_ENCIPHERMENT_KEY_USAGE: ::DWORD = 0x0020; +pub const CERT_NON_REPUDIATION_KEY_USAGE: ::DWORD = 0x0040; +pub const CERT_DIGITAL_SIGNATURE_KEY_USAGE: ::DWORD = 0x0080; +pub const CERT_DECIPHER_ONLY_KEY_USAGE: ::DWORD = 0x8000; +pub const CERT_STORE_ADD_NEW: ::DWORD = 1; +pub const CERT_STORE_ADD_USE_EXISTING: ::DWORD = 2; +pub const CERT_STORE_ADD_REPLACE_EXISTING: ::DWORD = 3; +pub const CERT_STORE_ADD_ALWAYS: ::DWORD = 4; +pub const CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: ::DWORD = 5; +pub const CERT_STORE_ADD_NEWER: ::DWORD = 6; +pub const CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: ::DWORD = 7; +pub const CERT_STORE_SAVE_AS_STORE: ::DWORD = 1; +pub const CERT_STORE_SAVE_AS_PKCS7: ::DWORD = 2; +pub const CERT_STORE_SAVE_TO_FILE: ::DWORD = 1; +pub const CERT_STORE_SAVE_TO_MEMORY: ::DWORD = 2; +pub const CERT_STORE_SAVE_TO_FILENAME_A: ::DWORD = 3; +pub const CERT_STORE_SAVE_TO_FILENAME_W: ::DWORD = 4; +pub const CERT_STORE_SAVE_TO_FILENAME: ::DWORD = CERT_STORE_SAVE_TO_FILENAME_W; +pub const CERT_CA_SUBJECT_FLAG: ::DWORD = 0x80; +pub const CERT_END_ENTITY_SUBJECT_FLAG: ::DWORD = 0x40; +pub const CERT_CHAIN_POLICY_BASE: ::DWORD = 1; +pub const CERT_CHAIN_POLICY_AUTHENTICODE: ::DWORD = 2; +pub const CERT_CHAIN_POLICY_AUTHENTICODE_TS: ::DWORD = 3; +pub const CERT_CHAIN_POLICY_SSL: ::DWORD = 4; +pub const CERT_CHAIN_POLICY_BASIC_CONSTRAINTS: ::DWORD = 5; +pub const CERT_CHAIN_POLICY_NT_AUTH: ::DWORD = 6; +pub const CERT_CHAIN_POLICY_MICROSOFT_ROOT: ::DWORD = 7; +pub const CERT_CHAIN_REVOCATION_CHECK_END_CERT: ::DWORD = 0x10000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CHAIN: ::DWORD = 0x20000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: ::DWORD = 0x40000000; +pub const CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY: ::DWORD = 0x80000000; +pub const CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT: ::DWORD = 0x08000000; +pub const CERT_TRUST_NO_ERROR: ::DWORD = 0x00000000; +pub const CERT_TRUST_IS_NOT_TIME_VALID: ::DWORD = 0x00000001; +pub const CERT_TRUST_IS_NOT_TIME_NESTED: ::DWORD = 0x00000002; +pub const CERT_TRUST_IS_REVOKED: ::DWORD = 0x00000004; +pub const CERT_TRUST_IS_NOT_SIGNATURE_VALID: ::DWORD = 0x00000008; +pub const CERT_TRUST_IS_NOT_VALID_FOR_USAGE: ::DWORD = 0x00000010; +pub const CERT_TRUST_IS_UNTRUSTED_ROOT: ::DWORD = 0x00000020; +pub const CERT_TRUST_REVOCATION_STATUS_UNKNOWN: ::DWORD = 0x00000040; +pub const CERT_TRUST_IS_CYCLIC: ::DWORD = 0x00000080; + +pub const CERT_TRUST_INVALID_EXTENSION: ::DWORD = 0x00000100; +pub const CERT_TRUST_INVALID_POLICY_CONSTRAINTS: ::DWORD = 0x00000200; +pub const CERT_TRUST_INVALID_BASIC_CONSTRAINTS: ::DWORD = 0x00000400; +pub const CERT_TRUST_INVALID_NAME_CONSTRAINTS: ::DWORD = 0x00000800; +pub const CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT: ::DWORD = 0x00001000; +pub const CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT: ::DWORD = 0x00002000; +pub const CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT: ::DWORD = 0x00004000; +pub const CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT: ::DWORD = 0x00008000; + +pub const CERT_TRUST_IS_OFFLINE_REVOCATION: ::DWORD = 0x01000000; +pub const CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY: ::DWORD = 0x02000000; +pub const CERT_TRUST_IS_PARTIAL_CHAIN: ::DWORD = 0x00010000; +pub const CERT_TRUST_CTL_IS_NOT_TIME_VALID: ::DWORD = 0x00020000; +pub const CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID: ::DWORD = 0x00040000; +pub const CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE: ::DWORD = 0x00080000; +pub const CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG: ::DWORD = 0x00000001; +pub const CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG: ::DWORD = 0x00000002; +pub const CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG: ::DWORD = 0x00000004; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG: ::DWORD = 0x00000008; + +pub const CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG: ::DWORD = 0x00000010; +pub const CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG: ::DWORD = 0x00000020; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG: ::DWORD = 0x00000040; +pub const CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG: ::DWORD = 0x00000080; + +pub const CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG: ::DWORD = 0x00000100; +pub const CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG: ::DWORD = 0x00000200; +pub const CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG: ::DWORD = 0x00000400; +pub const CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG: ::DWORD = 0x00000800; + +pub const CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS: ::DWORD = + CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG | + CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG; +pub const CERT_TRUST_HAS_EXACT_MATCH_ISSUER: ::DWORD = 0x00000001; +pub const CERT_TRUST_HAS_KEY_MATCH_ISSUER: ::DWORD = 0x00000002; +pub const CERT_TRUST_HAS_NAME_MATCH_ISSUER: ::DWORD = 0x00000004; +pub const CERT_TRUST_IS_SELF_SIGNED: ::DWORD = 0x00000008; +pub const CERT_TRUST_HAS_PREFERRED_ISSUER: ::DWORD = 0x00000100; +pub const CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY: ::DWORD = 0x00000200; +pub const CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS: ::DWORD = 0x00000400; +pub const CERT_TRUST_IS_COMPLEX_CHAIN: ::DWORD = 0x00010000; +pub const CERT_ALT_NAME_OTHER_NAME: ::DWORD = 1; +pub const CERT_ALT_NAME_RFC822_NAME: ::DWORD = 2; +pub const CERT_ALT_NAME_DNS_NAME: ::DWORD = 3; +pub const CERT_ALT_NAME_X400_ADDRESS: ::DWORD = 4; +pub const CERT_ALT_NAME_DIRECTORY_NAME: ::DWORD = 5; +pub const CERT_ALT_NAME_EDI_PARTY_NAME: ::DWORD = 6; +pub const CERT_ALT_NAME_URL: ::DWORD = 7; +pub const CERT_ALT_NAME_IP_ADDRESS: ::DWORD = 8; +pub const CERT_ALT_NAME_REGISTERED_ID: ::DWORD = 9; +pub const CERT_STORE_CTRL_RESYNC: ::DWORD = 1; +pub const CERT_STORE_CTRL_NOTIFY_CHANGE: ::DWORD = 2; +pub const CERT_STORE_CTRL_COMMIT: ::DWORD = 3; +pub const CERT_STORE_CTRL_AUTO_RESYNC: ::DWORD = 4; +pub const CERT_STORE_CTRL_CANCEL_NOTIFY: ::DWORD = 5; +pub const CERT_ID_ISSUER_SERIAL_NUMBER: ::DWORD = 1; +pub const CERT_ID_KEY_IDENTIFIER: ::DWORD = 2; +pub const CERT_ID_SHA1_HASH: ::DWORD = 3; +pub const CERT_KEY_PROV_HANDLE_PROP_ID: ::DWORD = 1; +pub const CERT_KEY_PROV_INFO_PROP_ID: ::DWORD = 2; +pub const CERT_SHA1_HASH_PROP_ID: ::DWORD = 3; +pub const CERT_MD5_HASH_PROP_ID: ::DWORD = 4; +pub const CERT_HASH_PROP_ID: ::DWORD = CERT_SHA1_HASH_PROP_ID; +pub const CERT_KEY_CONTEXT_PROP_ID: ::DWORD = 5; +pub const CERT_KEY_SPEC_PROP_ID: ::DWORD = 6; +pub const CERT_IE30_RESERVED_PROP_ID: ::DWORD = 7; +pub const CERT_PUBKEY_HASH_RESERVED_PROP_ID: ::DWORD = 8; +pub const CERT_ENHKEY_USAGE_PROP_ID: ::DWORD = 9; +pub const CERT_CTL_USAGE_PROP_ID: ::DWORD = CERT_ENHKEY_USAGE_PROP_ID; +pub const CERT_NEXT_UPDATE_LOCATION_PROP_ID: ::DWORD = 10; +pub const CERT_FRIENDLY_NAME_PROP_ID: ::DWORD = 11; +pub const CERT_PVK_FILE_PROP_ID: ::DWORD = 12; +pub const CERT_DESCRIPTION_PROP_ID: ::DWORD = 13; +pub const CERT_ACCESS_STATE_PROP_ID: ::DWORD = 14; +pub const CERT_SIGNATURE_HASH_PROP_ID: ::DWORD = 15; +pub const CERT_SMART_CARD_DATA_PROP_ID: ::DWORD = 16; +pub const CERT_EFS_PROP_ID: ::DWORD = 17; +pub const CERT_FORTEZZA_DATA_PROP_ID: ::DWORD = 18; +pub const CERT_ARCHIVED_PROP_ID: ::DWORD = 19; +pub const CERT_KEY_IDENTIFIER_PROP_ID: ::DWORD = 20; +pub const CERT_AUTO_ENROLL_PROP_ID: ::DWORD = 21; +pub const CERT_PUBKEY_ALG_PARA_PROP_ID: ::DWORD = 22; +pub const CERT_CROSS_CERT_DIST_POINTS_PROP_ID: ::DWORD = 23; +pub const CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID: ::DWORD = 24; +pub const CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID: ::DWORD = 25; +pub const CERT_ENROLLMENT_PROP_ID: ::DWORD = 26; +pub const CERT_DATE_STAMP_PROP_ID: ::DWORD = 27; +pub const CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: ::DWORD = 28; +pub const CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: ::DWORD = 29; +pub const CERT_EXTENDED_ERROR_INFO_PROP_ID: ::DWORD = 30; +pub const CERT_RENEWAL_PROP_ID: ::DWORD = 64; +pub const CERT_ARCHIVED_KEY_HASH_PROP_ID: ::DWORD = 65; +pub const CERT_AUTO_ENROLL_RETRY_PROP_ID: ::DWORD = 66; +pub const CERT_AIA_URL_RETRIEVED_PROP_ID: ::DWORD = 67; +pub const CERT_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 68; +pub const CERT_BACKED_UP_PROP_ID: ::DWORD = 69; +pub const CERT_OCSP_RESPONSE_PROP_ID: ::DWORD = 70; +pub const CERT_REQUEST_ORIGINATOR_PROP_ID: ::DWORD = 71; +pub const CERT_SOURCE_LOCATION_PROP_ID: ::DWORD = 72; +pub const CERT_SOURCE_URL_PROP_ID: ::DWORD = 73; +pub const CERT_NEW_KEY_PROP_ID: ::DWORD = 74; +pub const CERT_OCSP_CACHE_PREFIX_PROP_ID: ::DWORD = 75; +pub const CERT_SMART_CARD_ROOT_INFO_PROP_ID: ::DWORD = 76; +pub const CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID: ::DWORD = 77; +pub const CERT_NCRYPT_KEY_HANDLE_PROP_ID: ::DWORD = 78; +pub const CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID: ::DWORD = 79; +pub const CERT_SUBJECT_INFO_ACCESS_PROP_ID: ::DWORD = 80; +pub const CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 81; +pub const CERT_CA_DISABLE_CRL_PROP_ID: ::DWORD = 82; +pub const CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID: ::DWORD = 83; +pub const CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID: ::DWORD = 84; +pub const CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: ::DWORD = 85; +pub const CERT_SUBJECT_DISABLE_CRL_PROP_ID: ::DWORD = 86; +pub const CERT_CEP_PROP_ID: ::DWORD = 87; +pub const CERT_SIGN_HASH_CNG_ALG_PROP_ID: ::DWORD = 89; +pub const CERT_SCARD_PIN_ID_PROP_ID: ::DWORD = 90; +pub const CERT_SCARD_PIN_INFO_PROP_ID: ::DWORD = 91; +pub const CERT_SUBJECT_PUB_KEY_BIT_LENGTH_PROP_ID: ::DWORD = 92; +pub const CERT_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID: ::DWORD = 93; +pub const CERT_ISSUER_PUB_KEY_BIT_LENGTH_PROP_ID: ::DWORD = 94; +pub const CERT_ISSUER_CHAIN_SIGN_HASH_CNG_ALG_PROP_ID: ::DWORD = 95; +pub const CERT_ISSUER_CHAIN_PUB_KEY_CNG_ALG_BIT_LENGTH_PROP_ID: ::DWORD = 96; +pub const CERT_NO_EXPIRE_NOTIFICATION_PROP_ID: ::DWORD = 97; +pub const CERT_AUTH_ROOT_SHA256_HASH_PROP_ID: ::DWORD = 98; +pub const CERT_NCRYPT_KEY_HANDLE_TRANSFER_PROP_ID: ::DWORD = 99; +pub const CERT_HCRYPTPROV_TRANSFER_PROP_ID: ::DWORD = 100; +pub const CERT_SMART_CARD_READER_PROP_ID: ::DWORD = 101; +pub const CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID: ::DWORD = 102; +pub const CERT_KEY_REPAIR_ATTEMPTED_PROP_ID: ::DWORD = 103; +pub const CERT_DISALLOWED_FILETIME_PROP_ID: ::DWORD = 104; +pub const CERT_ROOT_PROGRAM_CHAIN_POLICIES_PROP_ID: ::DWORD = 105; +pub const CERT_SMART_CARD_READER_NON_REMOVABLE_PROP_ID: ::DWORD = 106; +pub const CERT_SHA256_HASH_PROP_ID: ::DWORD = 107; +pub const CERT_SCEP_SERVER_CERTS_PROP_ID: ::DWORD = 108; +pub const CERT_SCEP_RA_SIGNATURE_CERT_PROP_ID: ::DWORD = 109; +pub const CERT_SCEP_RA_ENCRYPTION_CERT_PROP_ID: ::DWORD = 110; +pub const CERT_SCEP_CA_CERT_PROP_ID: ::DWORD = 111; +pub const CERT_SCEP_SIGNER_CERT_PROP_ID: ::DWORD = 112; +pub const CERT_SCEP_NONCE_PROP_ID: ::DWORD = 113; +pub const CERT_SCEP_ENCRYPT_HASH_CNG_ALG_PROP_ID: ::DWORD = 114; +pub const CERT_SCEP_FLAGS_PROP_ID: ::DWORD = 115; +pub const CERT_SCEP_GUID_PROP_ID: ::DWORD = 116; +pub const CERT_SERIALIZABLE_KEY_CONTEXT_PROP_ID: ::DWORD = 117; +pub const CERT_ISOLATED_KEY_PROP_ID: ::DWORD = 118; +pub const CERT_FIRST_RESERVED_PROP_ID: ::DWORD = 119; +pub const CERT_LAST_RESERVED_PROP_ID: ::DWORD = 0x00007FFF; +pub const CERT_FIRST_USER_PROP_ID: ::DWORD = 0x00008000; +pub const CERT_LAST_USER_PROP_ID: ::DWORD = 0x0000FFFF; +pub const szOID_CERT_PROP_ID_PREFIX: &'static str = "1.3.6.1.4.1.311.10.11."; +pub const szOID_CERT_KEY_IDENTIFIER_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.20"; +pub const szOID_CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: &'static str + = "1.3.6.1.4.1.311.10.11.28"; +pub const szOID_CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.29"; +pub const szOID_CERT_MD5_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.4"; +pub const szOID_CERT_SIGNATURE_HASH_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.15"; +pub const szOID_DISALLOWED_HASH: &'static str = szOID_CERT_SIGNATURE_HASH_PROP_ID; +pub const szOID_CERT_DISALLOWED_FILETIME_PROP_ID: &'static str = "1.3.6.1.4.1.311.10.11.104"; +pub const CERT_ACCESS_STATE_WRITE_PERSIST_FLAG: ::DWORD = 0x1; +pub const CERT_ACCESS_STATE_SYSTEM_STORE_FLAG: ::DWORD = 0x2; +pub const CERT_ACCESS_STATE_LM_SYSTEM_STORE_FLAG: ::DWORD = 0x4; +pub const CERT_ACCESS_STATE_GP_SYSTEM_STORE_FLAG: ::DWORD = 0x8; +pub const CERT_ACCESS_STATE_SHARED_USER_FLAG: ::DWORD = 0x10; +pub const szOID_ROOT_PROGRAM_AUTO_UPDATE_CA_REVOCATION: &'static str = "1.3.6.1.4.1.311.60.3.1"; +pub const szOID_ROOT_PROGRAM_AUTO_UPDATE_END_REVOCATION: &'static str = "1.3.6.1.4.1.311.60.3.2"; +pub const szOID_ROOT_PROGRAM_NO_OCSP_FAILOVER_TO_CRL: &'static str = "1.3.6.1.4.1.311.60.3.3"; +STRUCT!{struct CRYPT_KEY_PROV_PARAM { + dwParam: ::DWORD, + pbData: *mut ::BYTE, + cbData: ::DWORD, + dwFlags: ::DWORD, +}} +pub type PCRYPT_KEY_PROV_PARAM = *mut CRYPT_KEY_PROV_PARAM; +STRUCT!{struct CRYPT_KEY_PROV_INFO { + pwszContainerName: ::LPWSTR, + pwszProvName: ::LPWSTR, + dwProvType: ::DWORD, + dwFlags: ::DWORD, + cProvParam: ::DWORD, + rgProvParam: PCRYPT_KEY_PROV_PARAM, + dwKeySpec: ::DWORD, +}} +pub type PCRYPT_KEY_PROV_INFO = *mut CRYPT_KEY_PROV_INFO; +pub const CERT_SET_KEY_PROV_HANDLE_PROP_ID: ::DWORD = 0x00000001; +pub const CERT_SET_KEY_CONTEXT_PROP_ID: ::DWORD = 0x00000001; +pub const CERT_NCRYPT_KEY_SPEC: ::DWORD = 0xFFFFFFFF; +//20213 +pub type HCERT_SERVER_OCSP_RESPONSE = *mut ::c_void; +STRUCT!{struct CERT_SERVER_OCSP_RESPONSE_CONTEXT { + cbSize: ::DWORD, + pbEncodedOcspResponse: *mut ::BYTE, + cbEncodedOcspResponse: ::DWORD, +}} +pub type PCERT_SERVER_OCSP_RESPONSE_CONTEXT = *mut CERT_SERVER_OCSP_RESPONSE_CONTEXT; +pub type PCCERT_SERVER_OCSP_RESPONSE_CONTEXT = *const CERT_SERVER_OCSP_RESPONSE_CONTEXT; + +pub const CERT_CHAIN_CACHE_END_CERT: ::DWORD = 0x00000001; +pub const CERT_CHAIN_THREAD_STORE_SYNC: ::DWORD = 0x00000002; +pub const CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL: ::DWORD = 0x00000004; +pub const CERT_CHAIN_USE_LOCAL_MACHINE_STORE: ::DWORD = 0x00000008; +pub const CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE: ::DWORD = 0x00000010; +pub const CERT_CHAIN_ENABLE_SHARE_STORE: ::DWORD = 0x00000020; + +STRUCT!{struct CERT_CHAIN_ENGINE_CONFIG { + cbSize: ::DWORD, + hRestrictedRoot: HCERTSTORE, + hRestrictedTrust: HCERTSTORE, + hRestrictedOther: HCERTSTORE, + cAdditionalStore: ::DWORD, + rghAdditionalStore: *mut HCERTSTORE, + dwFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + MaximumCachedCertificates: ::DWORD, + CycleDetectionModulus: ::DWORD, + // #if (NTDDI_VERSION >= NTDDI_WIN7) + hExclusiveRoot: HCERTSTORE, + hExclusiveTrustedPeople: HCERTSTORE, + // #if (NTDDI_VERSION >= NTDDI_WIN8) + dwExclusiveFlags: ::DWORD, +}} +pub type PCERT_CHAIN_ENGINE_CONFIG = *mut CERT_CHAIN_ENGINE_CONFIG; +// 18748 +pub type HCERTCHAINENGINE = ::HANDLE; +pub type PFN_CERT_CREATE_CONTEXT_SORT_FUNC = Option ::BOOL>; +STRUCT!{nodebug struct CERT_CREATE_CONTEXT_PARA { + cbSize: ::DWORD, + pfnFree: PFN_CRYPT_FREE, + pvFree: *mut ::c_void, + pfnSort: PFN_CERT_CREATE_CONTEXT_SORT_FUNC, + pvSort: *mut ::c_void, +}} +pub type PCERT_CREATE_CONTEXT_PARA = *mut CERT_CREATE_CONTEXT_PARA; +STRUCT!{struct CERT_EXTENSIONS { + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCERT_EXTENSIONS = *mut CERT_EXTENSIONS; +STRUCT!{struct CERT_REVOCATION_CRL_INFO { + cbSize: ::DWORD, + pBaseCrlContext: PCCRL_CONTEXT, + pDeltaCrlContext: PCCRL_CONTEXT, + pCrlEntry: PCRL_ENTRY, + fDeltaCrlEntry: ::BOOL, +}} +pub type PCERT_REVOCATION_CRL_INFO = *mut CERT_REVOCATION_CRL_INFO; +STRUCT!{struct CERT_TRUST_STATUS { + dwErrorStatus: ::DWORD, + dwInfoStatus: ::DWORD, +}} +pub type PCERT_TRUST_STATUS = *mut CERT_TRUST_STATUS; +STRUCT!{struct CERT_REVOCATION_INFO { + cbSize: ::DWORD, + dwRevocationResult: ::DWORD, + pszRevocationOid: ::LPCSTR, + pvOidSpecificInfo: ::LPVOID, + fHasFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, + pCrlInfo: PCERT_REVOCATION_CRL_INFO, +}} +pub type PCERT_REVOCATION_INFO = *mut CERT_REVOCATION_INFO; +STRUCT!{struct CERT_TRUST_LIST_INFO { + cbSize: ::DWORD, + pCtlEntry: PCTL_ENTRY, + pCtlContext: PCCTL_CONTEXT, +}} +pub type PCERT_TRUST_LIST_INFO = *mut CERT_TRUST_LIST_INFO; +STRUCT!{struct CERT_CHAIN_ELEMENT { + cbSize: ::DWORD, + pCertContext: PCCERT_CONTEXT, + TrustStatus: CERT_TRUST_STATUS, + pRevocationInfo: PCERT_REVOCATION_INFO, + pIssuanceUsage: PCERT_ENHKEY_USAGE, + pApplicationUsage: PCERT_ENHKEY_USAGE, + pwszExtendedErrorInfo: ::LPWSTR, +}} +pub type PCERT_CHAIN_ELEMENT = *mut CERT_CHAIN_ELEMENT; +pub type PCCERT_CHAIN_ELEMENT = *const CERT_CHAIN_ELEMENT; +STRUCT!{struct CERT_SIMPLE_CHAIN { + cbSize: ::DWORD, + TrustStatus: CERT_TRUST_STATUS, + cElement: ::DWORD, + rgpElement: *mut PCERT_CHAIN_ELEMENT, + pTrustListInfo: PCERT_TRUST_LIST_INFO, + fHasRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, +}} +pub type PCERT_SIMPLE_CHAIN = *mut CERT_SIMPLE_CHAIN; +pub type PCCERT_SIMPLE_CHAIN = *const CERT_SIMPLE_CHAIN; +STRUCT!{struct CERT_CHAIN_CONTEXT { + cbSize: ::DWORD, + TrustStatus: CERT_TRUST_STATUS, + cChain: ::DWORD, + rgpChain: *mut PCERT_SIMPLE_CHAIN, + cLowerQualityChainContext: ::DWORD, + rgpLowerQualityChainContext: *mut PCCERT_CHAIN_CONTEXT, + fHasRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + dwCreateFlags: ::DWORD, + ChainId: ::GUID, +}} +pub type PCERT_CHAIN_CONTEXT = *mut CERT_CHAIN_CONTEXT; +pub type PCCERT_CHAIN_CONTEXT = *const CERT_CHAIN_CONTEXT; +STRUCT!{struct CERT_PHYSICAL_STORE_INFO { + cbSize: ::DWORD, + pszOpenStoreProvider: ::LPSTR, + dwOpenEncodingType: ::DWORD, + dwOpenFlags: ::DWORD, + OpenParameters: CRYPT_DATA_BLOB, + dwFlags: ::DWORD, + dwPriority: ::DWORD, +}} +pub type PCERT_PHYSICAL_STORE_INFO = *mut CERT_PHYSICAL_STORE_INFO; +STRUCT!{struct CERT_SYSTEM_STORE_INFO { + cbSize: ::DWORD, +}} +pub type PCERT_SYSTEM_STORE_INFO = *mut CERT_SYSTEM_STORE_INFO; +//13401 +pub type PFN_CERT_ENUM_SYSTEM_STORE_LOCATION = Option ::BOOL>; +//13408 +pub type PFN_CERT_ENUM_SYSTEM_STORE = Option ::BOOL>; +//13416 +pub type PFN_CERT_ENUM_PHYSICAL_STORE = Option ::BOOL>; +STRUCT!{struct CERT_STRONG_SIGN_SERIALIZED_INFO { + dwFlags: ::DWORD, + pwszCNGSignHashAlgids: ::LPWSTR, + pwszCNGPubKeyMinBitLengths: ::LPWSTR, +}} +pub type PCERT_STRONG_SIGN_SERIALIZED_INFO = *mut CERT_STRONG_SIGN_SERIALIZED_INFO; +STRUCT!{struct CERT_STRONG_SIGN_PARA { + cbSize: ::DWORD, + dwInfoChoice: ::DWORD, + pvInfo: *mut ::c_void, +}} +UNION!( + CERT_STRONG_SIGN_PARA, pvInfo, pSerializedInfo, pSerializedInfo_mut, + PCERT_STRONG_SIGN_SERIALIZED_INFO +); +UNION!(CERT_STRONG_SIGN_PARA, pvInfo, pszOID, pszOID_mut, ::LPSTR); +pub type PCERT_STRONG_SIGN_PARA = *mut CERT_STRONG_SIGN_PARA; +pub type PCCERT_STRONG_SIGN_PARA = *const CERT_STRONG_SIGN_PARA; +pub const USAGE_MATCH_TYPE_AND: ::DWORD = 0x00000000; +pub const USAGE_MATCH_TYPE_OR: ::DWORD = 0x00000001; +STRUCT!{struct CERT_USAGE_MATCH { + dwType: ::DWORD, + Usage: CERT_ENHKEY_USAGE, +}} +pub type PCERT_USAGE_MATCH = *mut CERT_USAGE_MATCH; +STRUCT!{struct CERT_CHAIN_PARA { + cbSize: ::DWORD, + RequestedUsage: CERT_USAGE_MATCH, + RequestedIssuancePolicy: CERT_USAGE_MATCH, + dwUrlRetrievalTimeout: ::DWORD, + fCheckRevocationFreshnessTime: ::BOOL, + dwRevocationFreshnessTime: ::DWORD, + pftCacheResync: ::LPFILETIME, + pStrongSignPara: PCCERT_STRONG_SIGN_PARA, + dwStrongSignFlags: ::DWORD, +}} +pub type PCERT_CHAIN_PARA = *mut CERT_CHAIN_PARA; +STRUCT!{struct CERT_SELECT_CHAIN_PARA { + hChainEngine: HCERTCHAINENGINE, + pTime: ::PFILETIME, + hAdditionalStore: HCERTSTORE, + pChainPara: PCERT_CHAIN_PARA, + dwFlags: ::DWORD, +}} +pub type PCERT_SELECT_CHAIN_PARA = *mut CERT_SELECT_CHAIN_PARA; +pub type PCCERT_SELECT_CHAIN_PARA = *const CERT_SELECT_CHAIN_PARA; +STRUCT!{struct CERT_SELECT_CRITERIA { + dwType: ::DWORD, + cPara: ::DWORD, + ppPara: *mut *mut ::c_void, +}} +pub type PCERT_SELECT_CRITERIA = *mut CERT_SELECT_CRITERIA; +pub type PCCERT_SELECT_CRITERIA = *const CERT_SELECT_CRITERIA; +STRUCT!{struct CTL_VERIFY_USAGE_PARA { + cbSize: ::DWORD, + ListIdentifier: CRYPT_DATA_BLOB, + cCtlStore: ::DWORD, + rghCtlStore: *mut HCERTSTORE, + cSignerStore: ::DWORD, + rghSignerStore: *mut HCERTSTORE, +}} +pub type PCTL_VERIFY_USAGE_PARA = *mut CTL_VERIFY_USAGE_PARA; +STRUCT!{struct CTL_VERIFY_USAGE_STATUS { + cbSize: ::DWORD, + dwError: ::DWORD, + dwFlags: ::DWORD, + ppCtl: *mut PCCTL_CONTEXT, + dwCtlEntryIndex: ::DWORD, + ppSigner: *mut PCCERT_CONTEXT, + dwSignerIndex: ::DWORD, +}} +pub type PCTL_VERIFY_USAGE_STATUS = *mut CTL_VERIFY_USAGE_STATUS; +STRUCT!{struct CERT_CHAIN_POLICY_PARA { + cbSize: ::DWORD, + dwFlags: ::DWORD, + pvExtraPolicyPara: *mut ::c_void, +}} +pub type PCERT_CHAIN_POLICY_PARA = *mut CERT_CHAIN_POLICY_PARA; +STRUCT!{struct CERT_CHAIN_POLICY_STATUS { + cbSize: ::DWORD, + dwError: ::DWORD, + lChainIndex: ::LONG, + lElementIndex: ::LONG, + pvExtraPolicyStatus: *mut ::c_void, +}} +pub type PCERT_CHAIN_POLICY_STATUS = *mut CERT_CHAIN_POLICY_STATUS; +STRUCT!{struct CERT_REVOCATION_CHAIN_PARA { + cbSize: ::DWORD, + hChainEngine: HCERTCHAINENGINE, + hAdditionalStore: HCERTSTORE, + dwChainFlags: ::DWORD, + dwUrlRetrievalTimeout: ::DWORD, + pftCurrentTime: ::LPFILETIME, + pftCacheResync: ::LPFILETIME, +}} +pub type PCERT_REVOCATION_CHAIN_PARA = *mut CERT_REVOCATION_CHAIN_PARA; +STRUCT!{struct CERT_REVOCATION_PARA { + cbSize: ::DWORD, + pIssuerCert: PCCERT_CONTEXT, + cCertStore: ::DWORD, + rgCertStore: *mut HCERTSTORE, + hCrlStore: HCERTSTORE, + pftTimeToUse: ::LPFILETIME, + dwUrlRetrievalTimeout: ::DWORD, + fCheckFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, + pftCurrentTime: ::LPFILETIME, + pCrlInfo: PCERT_REVOCATION_CRL_INFO, + pftCacheResync: ::LPFILETIME, + pChainPara: PCERT_REVOCATION_CHAIN_PARA, +}} +pub type PCERT_REVOCATION_PARA = *mut CERT_REVOCATION_PARA; +STRUCT!{struct CERT_REVOCATION_STATUS { + cbSize: ::DWORD, + dwIndex: ::DWORD, + dwError: ::DWORD, + dwReason: ::DWORD, + fHasFreshnessTime: ::BOOL, + dwFreshnessTime: ::DWORD, +}} +pub type PCERT_REVOCATION_STATUS = *mut CERT_REVOCATION_STATUS; +//16990 +pub type HCRYPTASYNC = ::HANDLE; +pub type PHCRYPTASYNC = *mut ::HANDLE; +STRUCT!{struct CRYPT_ENCRYPT_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + ContentEncryptionAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvEncryptionAuxInfo: *mut ::c_void, + dwFlags: ::DWORD, + dwInnerContentType: ::DWORD, +}} +pub type PCRYPT_ENCRYPT_MESSAGE_PARA = *mut CRYPT_DECRYPT_MESSAGE_PARA; +STRUCT!{struct CRYPT_DECRYPT_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + cCertStore: ::DWORD, + rghCertStore: *mut HCERTSTORE, + dwFlags: ::DWORD, +}} +pub type PCRYPT_DECRYPT_MESSAGE_PARA = *mut CRYPT_DECRYPT_MESSAGE_PARA; +pub type PFN_CRYPT_GET_SIGNER_CERTIFICATE = Option PCCERT_CONTEXT>; +STRUCT!{nodebug struct CRYPT_VERIFY_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + pfnGetSignerCertificate: PFN_CRYPT_GET_SIGNER_CERTIFICATE, + pvGetArg: *mut ::c_void, + pStrongSignPara: PCCERT_STRONG_SIGN_PARA, +}} +pub type PCRYPT_VERIFY_MESSAGE_PARA = *mut CRYPT_VERIFY_MESSAGE_PARA; +STRUCT!{struct CRYPT_OID_INFO { + cbSize: ::DWORD, + oszOID: ::LPCSTR, + pwszName: ::LPCWSTR, + dwGroupId: ::DWORD, + dwValue: ::DWORD, + ExtraInfo: CRYPT_DATA_BLOB, + pwszCNGAlgid: ::LPCWSTR, + pwszCNGExtraAlgid: ::LPCWSTR, +}} +UNION!(CRYPT_OID_INFO, dwValue, Algid, Algid_mut, ALG_ID); +UNION!(CRYPT_OID_INFO, dwValue, dwLength, dwLength_mut, ::DWORD); +pub type PCRYPT_OID_INFO = *mut CRYPT_OID_INFO; +pub type PCCRYPT_OID_INFO = *const CRYPT_OID_INFO; +//18004 +pub type PFN_CRYPT_ENUM_KEYID_PROP = Option ::BOOL>; +//6379 +pub type PFN_CRYPT_ENUM_OID_FUNC = Option ::BOOL>; +//6675 +pub type PFN_CRYPT_ENUM_OID_INFO = Option ::BOOL>; +//6022 +pub type HCRYPTOIDFUNCSET = *mut ::c_void; +pub type HCRYPTOIDFUNCADDR = *mut ::c_void; +pub type PFN_CRYPT_ASYNC_PARAM_FREE_FUNC = Option; +STRUCT!{struct CRYPT_HASH_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, +}} +pub type PCRYPT_HASH_MESSAGE_PARA = *mut CRYPT_HASH_MESSAGE_PARA; +//14750 +pub type HCRYPTDEFAULTCONTEXT = *mut ::c_void; +STRUCT!{struct CRYPT_OID_FUNC_ENTRY { + pszOID: ::LPCSTR, + pvFuncAddr: *mut ::c_void, +}} +pub type PCRYPT_OID_FUNC_ENTRY = *mut CRYPT_OID_FUNC_ENTRY; +STRUCT!{struct CMSG_SIGNER_ENCODE_INFO { + cbSize: ::DWORD, + pCertInfo: PCERT_INFO, + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + cAuthAttr: ::DWORD, + rgAuthAttr: PCRYPT_ATTRIBUTE, + cUnauthAttr: ::DWORD, + rgUnauthAttr: PCRYPT_ATTRIBUTE, +}} +UNION!(CMSG_SIGNER_ENCODE_INFO, hCryptProv, hNCryptKey, hNCryptKey_mut, ::NCRYPT_KEY_HANDLE); +pub type PCMSG_SIGNER_ENCODE_INFO = *mut CMSG_SIGNER_ENCODE_INFO; +STRUCT!{struct CMSG_SIGNED_ENCODE_INFO { + cbSize: ::DWORD, + cSigners: ::DWORD, + rgSigners: PCMSG_SIGNER_ENCODE_INFO, + cCertEncoded: ::DWORD, + rgCertEncoded: PCERT_BLOB, + cCrlEncoded: ::DWORD, + rgCrlEncoded: PCRL_BLOB, +}} +pub type PCMSG_SIGNED_ENCODE_INFO = *mut CMSG_SIGNED_ENCODE_INFO; +//7393 +pub type PFN_CMSG_STREAM_OUTPUT = Option ::BOOL>; +STRUCT!{nodebug struct CMSG_STREAM_INFO { + cbContent: ::DWORD, + pfnStreamOutput: PFN_CMSG_STREAM_OUTPUT, + pvArg: *mut ::c_void, +}} +pub type PCMSG_STREAM_INFO = *mut CMSG_STREAM_INFO; +STRUCT!{struct CRYPT_TIMESTAMP_ACCURACY { + dwSeconds: ::DWORD, + dwMillis: ::DWORD, + dwMicros: ::DWORD, +}} +pub type PCRYPT_TIMESTAMP_ACCURACY = *mut CRYPT_TIMESTAMP_ACCURACY; +STRUCT!{struct CRYPT_TIMESTAMP_INFO { + dwVersion: ::DWORD, + pszTSAPolicyId: ::LPSTR, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + HashedMessage: CRYPT_DER_BLOB, + SerialNumber: CRYPT_INTEGER_BLOB, + ftTime: ::FILETIME, + pvAccuracy: PCRYPT_TIMESTAMP_ACCURACY, + fOrdering: ::BOOL, + Nonce: CRYPT_DER_BLOB, + Tsa: CRYPT_DER_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRYPT_TIMESTAMP_INFO = *mut CRYPT_TIMESTAMP_INFO; +STRUCT!{struct CRYPT_TIMESTAMP_CONTEXT { + cbEncoded: ::DWORD, + pbEncoded: *mut ::BYTE, + pTimeStamp: PCRYPT_TIMESTAMP_INFO, +}} +pub type PCRYPT_TIMESTAMP_CONTEXT = *mut CRYPT_TIMESTAMP_CONTEXT; +STRUCT!{struct CRYPT_TIMESTAMP_PARA { + pszTSAPolicyId: ::LPCSTR, + fRequestCerts: ::BOOL, + Nonce: CRYPT_INTEGER_BLOB, + cExtension: ::DWORD, + rgExtension: PCERT_EXTENSION, +}} +pub type PCRYPT_TIMESTAMP_PARA = *mut CRYPT_TIMESTAMP_PARA; +STRUCT!{struct CRYPT_SIGN_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + pSigningCert: PCCERT_CONTEXT, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + cMsgCert: ::DWORD, + rgpMsgCert: *mut PCCERT_CONTEXT, + cMsgCrl: ::DWORD, + rgpMsgCrl: *mut PCCRL_CONTEXT, + cAuthAttr: ::DWORD, + rgAuthAttr: PCRYPT_ATTRIBUTE, + cUnauthAttr: ::DWORD, + rgUnauthAttr: PCRYPT_ATTRIBUTE, + dwFlags: ::DWORD, + dwInnerContentType: ::DWORD, +}} +pub type PCRYPT_SIGN_MESSAGE_PARA = *mut CRYPT_SIGN_MESSAGE_PARA; +STRUCT!{struct CRYPT_KEY_SIGN_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgAndCertEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV, + dwKeySpec: ::DWORD, + HashAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, + pvHashAuxInfo: *mut ::c_void, + PubKeyAlgorithm: CRYPT_ALGORITHM_IDENTIFIER, +}} +UNION!(CRYPT_KEY_SIGN_MESSAGE_PARA, hCryptProv, hNCryptKey, hNCryptKey_mut, ::NCRYPT_KEY_HANDLE); +pub type PCRYPT_KEY_SIGN_MESSAGE_PARA = *mut CRYPT_KEY_SIGN_MESSAGE_PARA; +STRUCT!{struct CRYPT_KEY_VERIFY_MESSAGE_PARA { + cbSize: ::DWORD, + dwMsgEncodingType: ::DWORD, + hCryptProv: HCRYPTPROV_LEGACY, +}} +pub type PCRYPT_KEY_VERIFY_MESSAGE_PARA = *mut CRYPT_KEY_VERIFY_MESSAGE_PARA; +STRUCT!{struct HTTPSPolicyCallbackData { + cbSize: ::DWORD, + dwAuthType: ::DWORD, + fdwChecks: ::DWORD, + pwszServerName: *mut ::WCHAR, +}} +pub type PHTTPSPolicyCallbackData = *mut HTTPSPolicyCallbackData; +pub type SSL_EXTRA_CERT_CHAIN_POLICY_PARA = HTTPSPolicyCallbackData; +pub type PSSL_EXTRA_CERT_CHAIN_POLICY_PARA = *mut HTTPSPolicyCallbackData; +pub const AUTHTYPE_CLIENT: ::DWORD = 1; +pub const AUTHTYPE_SERVER: ::DWORD = 2; +pub const CTL_ENTRY_FROM_PROP_CHAIN_FLAG: ::DWORD = 0x1; +pub const CMSG_ENCODE_SORTED_CTL_FLAG: ::DWORD = 0x1; +pub const CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: ::DWORD = 0x2; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/windef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/windef.rs new file mode 100644 index 0000000..6493b48 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/windef.rs @@ -0,0 +1,57 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Basic Windows Type Definitions +DECLARE_HANDLE!(HWND, HWND__); +DECLARE_HANDLE!(HHOOK, HHOOK__); +DECLARE_HANDLE!(HEVENT, HEVENT__); +pub type HGDIOBJ = *mut ::c_void; +DECLARE_HANDLE!(HACCEL, HACCEL__); +DECLARE_HANDLE!(HBITMAP, HBITMAP__); +DECLARE_HANDLE!(HBRUSH, HBRUSH__); +DECLARE_HANDLE!(HCOLORSPACE, HCOLORSPACE__); +DECLARE_HANDLE!(HDC, HDC__); +DECLARE_HANDLE!(HGLRC, HGLRC__); +DECLARE_HANDLE!(HDESK, HDESK__); +DECLARE_HANDLE!(HENHMETAFILE, HENHMETAFILE__); +DECLARE_HANDLE!(HFONT, HFONT__); +DECLARE_HANDLE!(HICON, HICON__); +DECLARE_HANDLE!(HMENU, HMENU__); +DECLARE_HANDLE!(HPALETTE, HPALETTE__); +DECLARE_HANDLE!(HPEN, HPEN__); +DECLARE_HANDLE!(HWINEVENTHOOK, HWINEVENTHOOK__); +DECLARE_HANDLE!(HMONITOR, HMONITOR__); +DECLARE_HANDLE!(HUMPD, HUMPD__); +pub type HCURSOR = HICON; +pub type COLORREF = ::DWORD; +pub type LPCOLORREF = *mut ::DWORD; +STRUCT!{struct RECT { + left: ::LONG, + top: ::LONG, + right: ::LONG, + bottom: ::LONG, +}} +pub type PRECT = *mut RECT; +pub type NPRECT = *mut RECT; +pub type LPRECT = *mut RECT; +pub type LPCRECT = *const RECT; +STRUCT!{struct RECTL { + left: ::LONG, + top: ::LONG, + right: ::LONG, + bottom: ::LONG, +}} +pub type PRECTL = *mut RECTL; +pub type LPRECTL = *mut RECTL; +pub type LPCRECTL = *const RECTL; +STRUCT!{struct POINT { + x: ::LONG, + y: ::LONG, +}} +pub type PPOINT = *mut POINT; +pub type NPPOINT = *mut POINT; +pub type LPPOINT = *mut POINT; +STRUCT!{struct POINTL { + x: ::LONG, + y: ::LONG, +}} +pub type PPOINTL = *mut POINTL; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/windowscodecs.rs b/third_party/cargo/vendor/winapi-0.2.8/src/windowscodecs.rs new file mode 100644 index 0000000..3759626 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/windowscodecs.rs @@ -0,0 +1,363 @@ +// Copyright © 2015; Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of wincodec.h +pub type WICColor = ::UINT32; +pub type WICInProcPointer = *mut ::BYTE; +pub type REFWICPixelFormatGUID = ::REFGUID; +pub type WICPixelFormatGUID = ::GUID; +STRUCT!{struct WICRect { + X: ::INT, + Y: ::INT, + Width: ::INT, + Height: ::INT, +}} +ENUM!{enum WICColorContextType { + WICColorContextUninitialized = 0, + WICColorContextProfile = 0x1, + WICColorContextExifColorSpace = 0x2, +}} +ENUM!{enum WICBitmapCreateCacheOption { + WICBitmapNoCache = 0, + WICBitmapCacheOnDemand = 0x1, + WICBitmapCacheOnLoad = 0x2, +}} +ENUM!{enum WICDecodeOptions { + WICDecodeMetadataCacheOnDemand = 0, + WICDecodeMetadataCacheOnLoad = 0x1, +}} +ENUM!{enum WICBitmapEncoderCacheOption { + WICBitmapEncoderCacheInMemory = 0, + WICBitmapEncoderCacheTempFile = 0x1, + WICBitmapEncoderNoCache = 0x2, +}} +FLAGS!{enum WICComponentType { + WICDecoder = 0x1, + WICEncoder = 0x2, + WICPixelFormatConverter = 0x4, + WICMetadataReader = 0x8, + WICMetadataWriter = 0x10, + WICPixelFormat = 0x20, + WICAllComponents = 0x3f, +}} +FLAGS!{enum WICComponentEnumerateOptions { + WICComponentEnumerateDefault = 0, + WICComponentEnumerateRefresh = 0x1, + WICComponentEnumerateDisabled = 0x80000000, + WICComponentEnumerateUnsigned = 0x40000000, + WICComponentEnumerateBuiltInOnly = 0x20000000, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPattern { + Position: ::ULARGE_INTEGER, + Length: ::ULONG, + Pattern: *mut ::BYTE, + Mask: *mut ::BYTE, + EndOfStream: ::BOOL, +}} +ENUM!{enum WICBitmapInterpolationMode { + WICBitmapInterpolationModeNearestNeighbor = 0, + WICBitmapInterpolationModeLinear = 0x1, + WICBitmapInterpolationModeCubic = 0x2, + WICBitmapInterpolationModeFant = 0x3, +}} +ENUM!{enum WICBitmapPaletteType { + WICBitmapPaletteTypeCustom = 0, + WICBitmapPaletteTypeMedianCut = 0x1, + WICBitmapPaletteTypeFixedBW = 0x2, + WICBitmapPaletteTypeFixedHalftone8 = 0x3, + WICBitmapPaletteTypeFixedHalftone27 = 0x4, + WICBitmapPaletteTypeFixedHalftone64 = 0x5, + WICBitmapPaletteTypeFixedHalftone125 = 0x6, + WICBitmapPaletteTypeFixedHalftone216 = 0x7, + WICBitmapPaletteTypeFixedHalftone252 = 0x8, + WICBitmapPaletteTypeFixedHalftone256 = 0x9, + WICBitmapPaletteTypeFixedGray4 = 0xa, + WICBitmapPaletteTypeFixedGray16 = 0xb, + WICBitmapPaletteTypeFixedGray256 = 0xc, +}} +pub const WICBitmapPaletteTypeFixedWebPalette: WICBitmapPaletteType = + WICBitmapPaletteTypeFixedHalftone216; +ENUM!{enum WICBitmapDitherType { + WICBitmapDitherTypeSolid = 0, + WICBitmapDitherTypeOrdered4x4 = 0x1, + WICBitmapDitherTypeOrdered8x8 = 0x2, + WICBitmapDitherTypeOrdered16x16 = 0x3, + WICBitmapDitherTypeSpiral4x4 = 0x4, + WICBitmapDitherTypeSpiral8x8 = 0x5, + WICBitmapDitherTypeDualSpiral4x4 = 0x6, + WICBitmapDitherTypeDualSpiral8x8 = 0x7, + WICBitmapDitherTypeErrorDiffusion = 0x8, +}} +pub const WICBitmapDitherTypeNone: WICBitmapDitherType = WICBitmapDitherTypeSolid; +ENUM!{enum WICBitmapAlphaChannelOption { + WICBitmapUseAlpha = 0, + WICBitmapUsePremultipliedAlpha = 0x1, + WICBitmapIgnoreAlpha = 0x2, +}} +FLAGS!{enum WICBitmapTransformOptions { + WICBitmapTransformRotate0 = 0, + WICBitmapTransformRotate90 = 0x1, + WICBitmapTransformRotate180 = 0x2, + WICBitmapTransformRotate270 = 0x3, + WICBitmapTransformFlipHorizontal = 0x8, + WICBitmapTransformFlipVertical = 0x10, +}} +FLAGS!{enum WICBitmapLockFlags { + WICBitmapLockRead = 0x1, + WICBitmapLockWrite = 0x2, +}} +FLAGS!{enum WICBitmapDecoderCapabilities { + WICBitmapDecoderCapabilitySameEncoder = 0x1, + WICBitmapDecoderCapabilityCanDecodeAllImages = 0x2, + WICBitmapDecoderCapabilityCanDecodeSomeImages = 0x4, + WICBitmapDecoderCapabilityCanEnumerateMetadata = 0x8, + WICBitmapDecoderCapabilityCanDecodeThumbnail = 0x10, +}} +FLAGS!{enum WICProgressOperation { + WICProgressOperationCopyPixels = 0x1, + WICProgressOperationWritePixels = 0x2, + WICProgressOperationAll = 0xffff, +}} +FLAGS!{enum WICProgressNotification { + WICProgressNotificationBegin = 0x10000, + WICProgressNotificationEnd = 0x20000, + WICProgressNotificationFrequent = 0x40000, + WICProgressNotificationAll = 0xffff0000, +}} +FLAGS!{enum WICComponentSigning { + WICComponentSigned = 0x1, + WICComponentUnsigned = 0x2, + WICComponentSafe = 0x4, + WICComponentDisabled = 0x80000000, +}} +ENUM!{enum WICGifLogicalScreenDescriptorProperties { + WICGifLogicalScreenSignature = 0x1, + WICGifLogicalScreenDescriptorWidth = 0x2, + WICGifLogicalScreenDescriptorHeight = 0x3, + WICGifLogicalScreenDescriptorGlobalColorTableFlag = 0x4, + WICGifLogicalScreenDescriptorColorResolution = 0x5, + WICGifLogicalScreenDescriptorSortFlag = 0x6, + WICGifLogicalScreenDescriptorGlobalColorTableSize = 0x7, + WICGifLogicalScreenDescriptorBackgroundColorIndex = 0x8, + WICGifLogicalScreenDescriptorPixelAspectRatio = 0x9, +}} +ENUM!{enum WICGifImageDescriptorProperties { + WICGifImageDescriptorLeft = 0x1, + WICGifImageDescriptorTop = 0x2, + WICGifImageDescriptorWidth = 0x3, + WICGifImageDescriptorHeight = 0x4, + WICGifImageDescriptorLocalColorTableFlag = 0x5, + WICGifImageDescriptorInterlaceFlag = 0x6, + WICGifImageDescriptorSortFlag = 0x7, + WICGifImageDescriptorLocalColorTableSize = 0x8, +}} +ENUM!{enum WICGifGraphicControlExtensionProperties { + WICGifGraphicControlExtensionDisposal = 0x1, + WICGifGraphicControlExtensionUserInputFlag = 0x2, + WICGifGraphicControlExtensionTransparencyFlag = 0x3, + WICGifGraphicControlExtensionDelay = 0x4, + WICGifGraphicControlExtensionTransparentColorIndex = 0x5, +}} +ENUM!{enum WICGifApplicationExtensionProperties { + WICGifApplicationExtensionApplication = 0x1, + WICGifApplicationExtensionData = 0x2, +}} +ENUM!{enum WICGifCommentExtensionProperties { + WICGifCommentExtensionText = 0x1, +}} +ENUM!{enum WICJpegCommentProperties { + WICJpegCommentText = 0x1, +}} +ENUM!{enum WICJpegLuminanceProperties { + WICJpegLuminanceTable = 0x1, +}} +ENUM!{enum WICJpegChrominanceProperties { + WICJpegChrominanceTable = 0x1, +}} +ENUM!{enum WIC8BIMIptcProperties { + WIC8BIMIptcPString = 0, + WIC8BIMIptcEmbeddedIPTC = 0x1, +}} +ENUM!{enum WIC8BIMResolutionInfoProperties { + WIC8BIMResolutionInfoPString = 0x1, + WIC8BIMResolutionInfoHResolution = 0x2, + WIC8BIMResolutionInfoHResolutionUnit = 0x3, + WIC8BIMResolutionInfoWidthUnit = 0x4, + WIC8BIMResolutionInfoVResolution = 0x5, + WIC8BIMResolutionInfoVResolutionUnit = 0x6, + WIC8BIMResolutionInfoHeightUnit = 0x7, +}} +ENUM!{enum WIC8BIMIptcDigestProperties { + WIC8BIMIptcDigestPString = 0x1, + WIC8BIMIptcDigestIptcDigest = 0x2, +}} +ENUM!{enum WICPngGamaProperties { + WICPngGamaGamma = 0x1, +}} +ENUM!{enum WICPngBkgdProperties { + WICPngBkgdBackgroundColor = 0x1, +}} +ENUM!{enum WICPngItxtProperties { + WICPngItxtKeyword = 0x1, + WICPngItxtCompressionFlag = 0x2, + WICPngItxtLanguageTag = 0x3, + WICPngItxtTranslatedKeyword = 0x4, + WICPngItxtText = 0x5, +}} +ENUM!{enum WICPngChrmProperties { + WICPngChrmWhitePointX = 0x1, + WICPngChrmWhitePointY = 0x2, + WICPngChrmRedX = 0x3, + WICPngChrmRedY = 0x4, + WICPngChrmGreenX = 0x5, + WICPngChrmGreenY = 0x6, + WICPngChrmBlueX = 0x7, + WICPngChrmBlueY = 0x8, +}} +ENUM!{enum WICPngHistProperties { + WICPngHistFrequencies = 0x1, +}} +ENUM!{enum WICPngIccpProperties { + WICPngIccpProfileName = 0x1, + WICPngIccpProfileData = 0x2, +}} +ENUM!{enum WICPngSrgbProperties { + WICPngSrgbRenderingIntent = 0x1, +}} +ENUM!{enum WICPngTimeProperties { + WICPngTimeYear = 0x1, + WICPngTimeMonth = 0x2, + WICPngTimeDay = 0x3, + WICPngTimeHour = 0x4, + WICPngTimeMinute = 0x5, + WICPngTimeSecond = 0x6, +}} +ENUM!{enum WICSectionAccessLevel { + WICSectionAccessLevelRead = 0x1, + WICSectionAccessLevelReadWrite = 0x3, +}} +ENUM!{enum WICPixelFormatNumericRepresentation { + WICPixelFormatNumericRepresentationUnspecified = 0, + WICPixelFormatNumericRepresentationIndexed = 0x1, + WICPixelFormatNumericRepresentationUnsignedInteger = 0x2, + WICPixelFormatNumericRepresentationSignedInteger = 0x3, + WICPixelFormatNumericRepresentationFixed = 0x4, + WICPixelFormatNumericRepresentationFloat = 0x5, +}} +ENUM!{enum WICPlanarOptions { + WICPlanarOptionsDefault = 0, + WICPlanarOptionsPreserveSubsampling = 0x1, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICImageParameters { + PixelFormat: ::D2D1_PIXEL_FORMAT, + DpiX: ::FLOAT, + DpiY: ::FLOAT, + Top: ::FLOAT, + Left: ::FLOAT, + PixelWidth: ::FLOAT, + PixelHeight: ::FLOAT, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPlaneDescription { + Format: WICPixelFormatGUID, + Width: ::UINT, + Height: ::UINT, +}} +#[allow(unused_qualifications)] +STRUCT!{struct WICBitmapPlane { + Format: WICPixelFormatGUID, + pbBuffer: *mut ::BYTE, + cbStride: ::UINT, + cbBufferSize: ::UINT, +}} +RIDL!( +interface IWICPalette(IWICPaletteVtbl): IUnknown(IUnknownVtbl) { + fn InitializePredefined( + &mut self, ePaletteType: WICBitmapPaletteType, fAddTransparentColor: ::BOOL + ) -> ::HRESULT, + fn InitializeCustom(&mut self, pColors: *mut WICColor, cCount: ::UINT) -> ::HRESULT, + fn InitializeFromBitmap( + &mut self, pISurface: *mut IWICBitmapSource, cCount: ::UINT, fAddTransparentColor: ::BOOL + ) -> ::HRESULT, + fn InitializeFromPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn GetType(&mut self, pePaletteType: *mut WICBitmapPaletteType) -> ::HRESULT, + fn GetColorCount(&mut self, pcCount: *mut ::UINT) -> ::HRESULT, + fn GetColors( + &mut self, cCount: ::UINT, pColros: *mut WICColor, pcActualColors: *mut ::UINT + ) -> ::HRESULT, + fn IsBlackWhite(&mut self, pfIsBlackWhite: *mut ::BOOL) -> ::HRESULT, + fn IsGrayscale(&mut self, pfIsGrayscale: *mut ::BOOL) -> ::HRESULT, + fn HasAlpha(&mut self, pfHasAlpha: *mut ::BOOL) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapSource(IWICBitmapSourceVtbl): IUnknown(IUnknownVtbl) { + fn GetSize(&mut self, puiWidth: *mut ::UINT, puiHeight: ::UINT) -> ::HRESULT, + fn GetPixelFormat(&mut self, pPixelFormat: *mut WICPixelFormatGUID) -> ::HRESULT, + fn GetResolution(&mut self, pDpiX: *mut f64, pDpiY: *mut f64) -> ::HRESULT, + fn CopyPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn CopyPixels( + &mut self, prc: *const WICRect, cbStride: ::UINT, cbBufferSize: ::UINT, + pbBuffer: *mut ::BYTE + ) -> ::HRESULT +}); +RIDL!( +interface IWICFormatConverter(IWICFormatConverterVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, dstFormat: REFWICPixelFormatGUID, + dither: WICBitmapDitherType, pIPalette: *mut IWICPalette, alphaThreasholdPercent: f64, + paletteTranslate: WICBitmapPaletteType + ) -> ::HRESULT, + fn CanConvert( + &mut self, srcPixelFormat: REFWICPixelFormatGUID, dstPixelFormat: REFWICPixelFormatGUID, + pfCanConvert: *mut ::BOOL + ) -> ::HRESULT +}); +RIDL!( +interface IWICPlanarFormatConverter(IWICPlanarFormatConverterVtbl) + : IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, ppPlanes: *mut *mut IWICBitmapSource, cPlanes: ::UINT, + dstFormat: REFWICPixelFormatGUID, dither: WICBitmapDitherType, pIPalette: *mut IWICPalette, + alphaThreasholdPercent: f64, paletteTranslate: WICBitmapPaletteType + ) -> ::HRESULT, + fn CanConvert( + &mut self, pSrcPixelFormats: *const WICPixelFormatGUID, cSrcPlanes: ::UINT, + dstPixelFormat: REFWICPixelFormatGUID, pfCanConvert: *mut ::BOOL + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapScaler(IWICBitmapScalerVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, uiWidth: ::UINT, uiHeight: ::UINT, + mode: WICBitmapInterpolationMode + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapClipper(IWICBitmapClipperVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize(&mut self, pISource: *mut IWICBitmapSource, prc: *const WICRect) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapFlipRotator(IWICBitmapFlipRotatorVtbl) + : IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Initialize( + &mut self, pISource: *mut IWICBitmapSource, options: WICBitmapTransformOptions + ) -> ::HRESULT +}); +RIDL!( +interface IWICBitmapLock(IWICBitmapLockVtbl): IUnknown(IUnknownVtbl) { + fn GetSize(&mut self, puiWidth: *mut ::UINT, puiHeight: *mut ::UINT) -> ::HRESULT, + fn GetStride(&mut self, pcbStride: *mut ::UINT) -> ::HRESULT, + fn GetDataPointer( + &mut self, pcbBufferSize: *mut ::UINT, ppbData: *mut WICInProcPointer + ) -> ::HRESULT, + fn GetPixelFormat(&mut self, pPixelFormat: *mut WICPixelFormatGUID) -> ::HRESULT +}); +RIDL!( +interface IWICBitmap(IWICBitmapVtbl): IWICBitmapSource(IWICBitmapSourceVtbl) { + fn Lock( + &mut self, prcLock: *const WICRect, flags: ::DWORD, ppILock: *mut *mut IWICBitmapLock + ) -> ::HRESULT, + fn SetPalette(&mut self, pIPalette: *mut IWICPalette) -> ::HRESULT, + fn SetResolution(&mut self, dpiX: f64, dpiY: f64) -> ::HRESULT +}); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/windowsx.rs b/third_party/cargo/vendor/winapi-0.2.8/src/windowsx.rs new file mode 100644 index 0000000..0441e63 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/windowsx.rs @@ -0,0 +1,22 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Macro APIs, window message crackers, and control APIs +//1233 +pub fn GET_X_LPARAM(lp: ::LPARAM) -> ::c_int { + ::LOWORD(lp as ::DWORD) as ::c_short as ::c_int +} +pub fn GET_Y_LPARAM(lp: ::LPARAM) -> ::c_int { + ::HIWORD(lp as ::DWORD) as ::c_short as ::c_int +} +#[test] +fn test_get_x_lparam() { + assert_eq!(GET_X_LPARAM(0xDEAD1234u32 as ::LPARAM), 0x1234); + assert_eq!(GET_X_LPARAM(0xBEEFffffu32 as ::LPARAM), -1); + assert_eq!(GET_X_LPARAM(0xCAFEFB2Eu32 as ::LPARAM), -1234); +} +#[test] +fn test_get_y_lparam() { + assert_eq!(GET_Y_LPARAM(0x1234DEADu32 as ::LPARAM), 0x1234); + assert_eq!(GET_Y_LPARAM(0xffffBEEFu32 as ::LPARAM), -1); + assert_eq!(GET_Y_LPARAM(0xFB2ECAFEu32 as ::LPARAM), -1234); +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winerror.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winerror.rs new file mode 100644 index 0000000..6792cf8 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winerror.rs @@ -0,0 +1,6065 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! error code definitions for the Win32 API functions +#[inline] +pub fn SUCCEEDED(hr: HRESULT) -> bool { + hr >= 0 +} +pub const FACILITY_XPS: HRESULT = 82; +pub const FACILITY_XAML: HRESULT = 43; +pub const FACILITY_USN: HRESULT = 129; +pub const FACILITY_BLBUI: HRESULT = 128; +pub const FACILITY_SPP: HRESULT = 256; +pub const FACILITY_WSB_ONLINE: HRESULT = 133; +pub const FACILITY_DLS: HRESULT = 153; +pub const FACILITY_BLB_CLI: HRESULT = 121; +pub const FACILITY_BLB: HRESULT = 120; +pub const FACILITY_WSBAPP: HRESULT = 122; +pub const FACILITY_WPN: HRESULT = 62; +pub const FACILITY_WMAAECMA: HRESULT = 1996; +pub const FACILITY_WINRM: HRESULT = 51; +pub const FACILITY_WINPE: HRESULT = 61; +pub const FACILITY_WINDOWSUPDATE: HRESULT = 36; +pub const FACILITY_WINDOWS_STORE: HRESULT = 63; +pub const FACILITY_WINDOWS_SETUP: HRESULT = 48; +pub const FACILITY_WINDOWS_DEFENDER: HRESULT = 80; +pub const FACILITY_WINDOWS_CE: HRESULT = 24; +pub const FACILITY_WINDOWS: HRESULT = 8; +pub const FACILITY_WINCODEC_DWRITE_DWM: HRESULT = 2200; +pub const FACILITY_WIA: HRESULT = 33; +pub const FACILITY_WER: HRESULT = 27; +pub const FACILITY_WEP: HRESULT = 2049; +pub const FACILITY_WEB_SOCKET: HRESULT = 886; +pub const FACILITY_WEB: HRESULT = 885; +pub const FACILITY_USERMODE_VOLSNAP: HRESULT = 130; +pub const FACILITY_USERMODE_VOLMGR: HRESULT = 56; +pub const FACILITY_VISUALCPP: HRESULT = 109; +pub const FACILITY_USERMODE_VIRTUALIZATION: HRESULT = 55; +pub const FACILITY_USERMODE_VHD: HRESULT = 58; +pub const FACILITY_URT: HRESULT = 19; +pub const FACILITY_UMI: HRESULT = 22; +pub const FACILITY_UI: HRESULT = 42; +pub const FACILITY_TPM_SOFTWARE: HRESULT = 41; +pub const FACILITY_TPM_SERVICES: HRESULT = 40; +pub const FACILITY_TIERING: HRESULT = 131; +pub const FACILITY_SYNCENGINE: HRESULT = 2050; +pub const FACILITY_SXS: HRESULT = 23; +pub const FACILITY_STORAGE: HRESULT = 3; +pub const FACILITY_STATE_MANAGEMENT: HRESULT = 34; +pub const FACILITY_SSPI: HRESULT = 9; +pub const FACILITY_USERMODE_SPACES: HRESULT = 231; +pub const FACILITY_SOS: HRESULT = 160; +pub const FACILITY_SCARD: HRESULT = 16; +pub const FACILITY_SHELL: HRESULT = 39; +pub const FACILITY_SETUPAPI: HRESULT = 15; +pub const FACILITY_SECURITY: HRESULT = 9; +pub const FACILITY_SDIAG: HRESULT = 60; +pub const FACILITY_USERMODE_SDBUS: HRESULT = 2305; +pub const FACILITY_RPC: HRESULT = 1; +pub const FACILITY_RESTORE: HRESULT = 256; +pub const FACILITY_SCRIPT: HRESULT = 112; +pub const FACILITY_PARSE: HRESULT = 113; +pub const FACILITY_RAS: HRESULT = 83; +pub const FACILITY_POWERSHELL: HRESULT = 84; +pub const FACILITY_PLA: HRESULT = 48; +pub const FACILITY_PIDGENX: HRESULT = 2561; +pub const FACILITY_P2P_INT: HRESULT = 98; +pub const FACILITY_P2P: HRESULT = 99; +pub const FACILITY_OPC: HRESULT = 81; +pub const FACILITY_ONLINE_ID: HRESULT = 134; +pub const FACILITY_WIN32: HRESULT = 7; +pub const FACILITY_CONTROL: HRESULT = 10; +pub const FACILITY_WEBSERVICES: HRESULT = 61; +pub const FACILITY_NULL: HRESULT = 0; +pub const FACILITY_NDIS: HRESULT = 52; +pub const FACILITY_NAP: HRESULT = 39; +pub const FACILITY_MOBILE: HRESULT = 1793; +pub const FACILITY_METADIRECTORY: HRESULT = 35; +pub const FACILITY_MSMQ: HRESULT = 14; +pub const FACILITY_MEDIASERVER: HRESULT = 13; +pub const FACILITY_MBN: HRESULT = 84; +pub const FACILITY_LINGUISTIC_SERVICES: HRESULT = 305; +pub const FACILITY_LEAP: HRESULT = 2184; +pub const FACILITY_JSCRIPT: HRESULT = 2306; +pub const FACILITY_INTERNET: HRESULT = 12; +pub const FACILITY_ITF: HRESULT = 4; +pub const FACILITY_INPUT: HRESULT = 64; +pub const FACILITY_USERMODE_HYPERVISOR: HRESULT = 53; +pub const FACILITY_ACCELERATOR: HRESULT = 1536; +pub const FACILITY_HTTP: HRESULT = 25; +pub const FACILITY_GRAPHICS: HRESULT = 38; +pub const FACILITY_FWP: HRESULT = 50; +pub const FACILITY_FVE: HRESULT = 49; +pub const FACILITY_USERMODE_FILTER_MANAGER: HRESULT = 31; +pub const FACILITY_EAS: HRESULT = 85; +pub const FACILITY_EAP: HRESULT = 66; +pub const FACILITY_DXGI_DDI: HRESULT = 2171; +pub const FACILITY_DXGI: HRESULT = 2170; +pub const FACILITY_DPLAY: HRESULT = 21; +pub const FACILITY_DMSERVER: HRESULT = 256; +pub const FACILITY_DISPATCH: HRESULT = 2; +pub const FACILITY_DIRECTORYSERVICE: HRESULT = 37; +pub const FACILITY_DIRECTMUSIC: HRESULT = 2168; +pub const FACILITY_DIRECT3D11: HRESULT = 2172; +pub const FACILITY_DIRECT3D10: HRESULT = 2169; +pub const FACILITY_DIRECT2D: HRESULT = 2201; +pub const FACILITY_DAF: HRESULT = 100; +pub const FACILITY_DEPLOYMENT_SERVICES_UTIL: HRESULT = 260; +pub const FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT: HRESULT = 272; +pub const FACILITY_DEPLOYMENT_SERVICES_TFTP: HRESULT = 264; +pub const FACILITY_DEPLOYMENT_SERVICES_PXE: HRESULT = 263; +pub const FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER: HRESULT = 289; +pub const FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT: HRESULT = 290; +pub const FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT: HRESULT = 259; +pub const FACILITY_DEPLOYMENT_SERVICES_IMAGING: HRESULT = 258; +pub const FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING: HRESULT = 278; +pub const FACILITY_DEPLOYMENT_SERVICES_SERVER: HRESULT = 257; +pub const FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER: HRESULT = 293; +pub const FACILITY_DEPLOYMENT_SERVICES_BINLSVC: HRESULT = 261; +pub const FACILITY_DEFRAG: HRESULT = 2304; +pub const FACILITY_DEBUGGERS: HRESULT = 176; +pub const FACILITY_CONFIGURATION: HRESULT = 33; +pub const FACILITY_COMPLUS: HRESULT = 17; +pub const FACILITY_USERMODE_COMMONLOG: HRESULT = 26; +pub const FACILITY_CMI: HRESULT = 54; +pub const FACILITY_CERT: HRESULT = 11; +pub const FACILITY_BLUETOOTH_ATT: HRESULT = 101; +pub const FACILITY_BCD: HRESULT = 57; +pub const FACILITY_BACKGROUNDCOPY: HRESULT = 32; +pub const FACILITY_AUDIOSTREAMING: HRESULT = 1094; +pub const FACILITY_AUDCLNT: HRESULT = 2185; +pub const FACILITY_AUDIO: HRESULT = 102; +pub const FACILITY_ACTION_QUEUE: HRESULT = 44; +pub const FACILITY_ACS: HRESULT = 20; +pub const FACILITY_AAF: HRESULT = 18; +pub const ERROR_SUCCESS: ::DWORD = 0; +pub const NO_ERROR: ::DWORD = 0; +pub const SEC_E_OK: HRESULT = 0; +pub const ERROR_INVALID_FUNCTION: ::DWORD = 1; +pub const ERROR_FILE_NOT_FOUND: ::DWORD = 2; +pub const ERROR_PATH_NOT_FOUND: ::DWORD = 3; +pub const ERROR_TOO_MANY_OPEN_FILES: ::DWORD = 4; +pub const ERROR_ACCESS_DENIED: ::DWORD = 5; +pub const ERROR_INVALID_HANDLE: ::DWORD = 6; +pub const ERROR_ARENA_TRASHED: ::DWORD = 7; +pub const ERROR_NOT_ENOUGH_MEMORY: ::DWORD = 8; +pub const ERROR_INVALID_BLOCK: ::DWORD = 9; +pub const ERROR_BAD_ENVIRONMENT: ::DWORD = 10; +pub const ERROR_BAD_FORMAT: ::DWORD = 11; +pub const ERROR_INVALID_ACCESS: ::DWORD = 12; +pub const ERROR_INVALID_DATA: ::DWORD = 13; +pub const ERROR_OUTOFMEMORY: ::DWORD = 14; +pub const ERROR_INVALID_DRIVE: ::DWORD = 15; +pub const ERROR_CURRENT_DIRECTORY: ::DWORD = 16; +pub const ERROR_NOT_SAME_DEVICE: ::DWORD = 17; +pub const ERROR_NO_MORE_FILES: ::DWORD = 18; +pub const ERROR_WRITE_PROTECT: ::DWORD = 19; +pub const ERROR_BAD_UNIT: ::DWORD = 20; +pub const ERROR_NOT_READY: ::DWORD = 21; +pub const ERROR_BAD_COMMAND: ::DWORD = 22; +pub const ERROR_CRC: ::DWORD = 23; +pub const ERROR_BAD_LENGTH: ::DWORD = 24; +pub const ERROR_SEEK: ::DWORD = 25; +pub const ERROR_NOT_DOS_DISK: ::DWORD = 26; +pub const ERROR_SECTOR_NOT_FOUND: ::DWORD = 27; +pub const ERROR_OUT_OF_PAPER: ::DWORD = 28; +pub const ERROR_WRITE_FAULT: ::DWORD = 29; +pub const ERROR_READ_FAULT: ::DWORD = 30; +pub const ERROR_GEN_FAILURE: ::DWORD = 31; +pub const ERROR_SHARING_VIOLATION: ::DWORD = 32; +pub const ERROR_LOCK_VIOLATION: ::DWORD = 33; +pub const ERROR_WRONG_DISK: ::DWORD = 34; +pub const ERROR_SHARING_BUFFER_EXCEEDED: ::DWORD = 36; +pub const ERROR_HANDLE_EOF: ::DWORD = 38; +pub const ERROR_HANDLE_DISK_FULL: ::DWORD = 39; +pub const ERROR_NOT_SUPPORTED: ::DWORD = 50; +pub const ERROR_REM_NOT_LIST: ::DWORD = 51; +pub const ERROR_DUP_NAME: ::DWORD = 52; +pub const ERROR_BAD_NETPATH: ::DWORD = 53; +pub const ERROR_NETWORK_BUSY: ::DWORD = 54; +pub const ERROR_DEV_NOT_EXIST: ::DWORD = 55; +pub const ERROR_TOO_MANY_CMDS: ::DWORD = 56; +pub const ERROR_ADAP_HDW_ERR: ::DWORD = 57; +pub const ERROR_BAD_NET_RESP: ::DWORD = 58; +pub const ERROR_UNEXP_NET_ERR: ::DWORD = 59; +pub const ERROR_BAD_REM_ADAP: ::DWORD = 60; +pub const ERROR_PRINTQ_FULL: ::DWORD = 61; +pub const ERROR_NO_SPOOL_SPACE: ::DWORD = 62; +pub const ERROR_PRINT_CANCELLED: ::DWORD = 63; +pub const ERROR_NETNAME_DELETED: ::DWORD = 64; +pub const ERROR_NETWORK_ACCESS_DENIED: ::DWORD = 65; +pub const ERROR_BAD_DEV_TYPE: ::DWORD = 66; +pub const ERROR_BAD_NET_NAME: ::DWORD = 67; +pub const ERROR_TOO_MANY_NAMES: ::DWORD = 68; +pub const ERROR_TOO_MANY_SESS: ::DWORD = 69; +pub const ERROR_SHARING_PAUSED: ::DWORD = 70; +pub const ERROR_REQ_NOT_ACCEP: ::DWORD = 71; +pub const ERROR_REDIR_PAUSED: ::DWORD = 72; +pub const ERROR_FILE_EXISTS: ::DWORD = 80; +pub const ERROR_CANNOT_MAKE: ::DWORD = 82; +pub const ERROR_FAIL_I24: ::DWORD = 83; +pub const ERROR_OUT_OF_STRUCTURES: ::DWORD = 84; +pub const ERROR_ALREADY_ASSIGNED: ::DWORD = 85; +pub const ERROR_INVALID_PASSWORD: ::DWORD = 86; +pub const ERROR_INVALID_PARAMETER: ::DWORD = 87; +pub const ERROR_NET_WRITE_FAULT: ::DWORD = 88; +pub const ERROR_NO_PROC_SLOTS: ::DWORD = 89; +pub const ERROR_TOO_MANY_SEMAPHORES: ::DWORD = 100; +pub const ERROR_EXCL_SEM_ALREADY_OWNED: ::DWORD = 101; +pub const ERROR_SEM_IS_SET: ::DWORD = 102; +pub const ERROR_TOO_MANY_SEM_REQUESTS: ::DWORD = 103; +pub const ERROR_INVALID_AT_INTERRUPT_TIME: ::DWORD = 104; +pub const ERROR_SEM_OWNER_DIED: ::DWORD = 105; +pub const ERROR_SEM_USER_LIMIT: ::DWORD = 106; +pub const ERROR_DISK_CHANGE: ::DWORD = 107; +pub const ERROR_DRIVE_LOCKED: ::DWORD = 108; +pub const ERROR_BROKEN_PIPE: ::DWORD = 109; +pub const ERROR_OPEN_FAILED: ::DWORD = 110; +pub const ERROR_BUFFER_OVERFLOW: ::DWORD = 111; +pub const ERROR_DISK_FULL: ::DWORD = 112; +pub const ERROR_NO_MORE_SEARCH_HANDLES: ::DWORD = 113; +pub const ERROR_INVALID_TARGET_HANDLE: ::DWORD = 114; +pub const ERROR_INVALID_CATEGORY: ::DWORD = 117; +pub const ERROR_INVALID_VERIFY_SWITCH: ::DWORD = 118; +pub const ERROR_BAD_DRIVER_LEVEL: ::DWORD = 119; +pub const ERROR_CALL_NOT_IMPLEMENTED: ::DWORD = 120; +pub const ERROR_SEM_TIMEOUT: ::DWORD = 121; +pub const ERROR_INSUFFICIENT_BUFFER: ::DWORD = 122; +pub const ERROR_INVALID_NAME: ::DWORD = 123; +pub const ERROR_INVALID_LEVEL: ::DWORD = 124; +pub const ERROR_NO_VOLUME_LABEL: ::DWORD = 125; +pub const ERROR_MOD_NOT_FOUND: ::DWORD = 126; +pub const ERROR_PROC_NOT_FOUND: ::DWORD = 127; +pub const ERROR_WAIT_NO_CHILDREN: ::DWORD = 128; +pub const ERROR_CHILD_NOT_COMPLETE: ::DWORD = 129; +pub const ERROR_DIRECT_ACCESS_HANDLE: ::DWORD = 130; +pub const ERROR_NEGATIVE_SEEK: ::DWORD = 131; +pub const ERROR_SEEK_ON_DEVICE: ::DWORD = 132; +pub const ERROR_IS_JOIN_TARGET: ::DWORD = 133; +pub const ERROR_IS_JOINED: ::DWORD = 134; +pub const ERROR_IS_SUBSTED: ::DWORD = 135; +pub const ERROR_NOT_JOINED: ::DWORD = 136; +pub const ERROR_NOT_SUBSTED: ::DWORD = 137; +pub const ERROR_JOIN_TO_JOIN: ::DWORD = 138; +pub const ERROR_SUBST_TO_SUBST: ::DWORD = 139; +pub const ERROR_JOIN_TO_SUBST: ::DWORD = 140; +pub const ERROR_SUBST_TO_JOIN: ::DWORD = 141; +pub const ERROR_BUSY_DRIVE: ::DWORD = 142; +pub const ERROR_SAME_DRIVE: ::DWORD = 143; +pub const ERROR_DIR_NOT_ROOT: ::DWORD = 144; +pub const ERROR_DIR_NOT_EMPTY: ::DWORD = 145; +pub const ERROR_IS_SUBST_PATH: ::DWORD = 146; +pub const ERROR_IS_JOIN_PATH: ::DWORD = 147; +pub const ERROR_PATH_BUSY: ::DWORD = 148; +pub const ERROR_IS_SUBST_TARGET: ::DWORD = 149; +pub const ERROR_SYSTEM_TRACE: ::DWORD = 150; +pub const ERROR_INVALID_EVENT_COUNT: ::DWORD = 151; +pub const ERROR_TOO_MANY_MUXWAITERS: ::DWORD = 152; +pub const ERROR_INVALID_LIST_FORMAT: ::DWORD = 153; +pub const ERROR_LABEL_TOO_LONG: ::DWORD = 154; +pub const ERROR_TOO_MANY_TCBS: ::DWORD = 155; +pub const ERROR_SIGNAL_REFUSED: ::DWORD = 156; +pub const ERROR_DISCARDED: ::DWORD = 157; +pub const ERROR_NOT_LOCKED: ::DWORD = 158; +pub const ERROR_BAD_THREADID_ADDR: ::DWORD = 159; +pub const ERROR_BAD_ARGUMENTS: ::DWORD = 160; +pub const ERROR_BAD_PATHNAME: ::DWORD = 161; +pub const ERROR_SIGNAL_PENDING: ::DWORD = 162; +pub const ERROR_MAX_THRDS_REACHED: ::DWORD = 164; +pub const ERROR_LOCK_FAILED: ::DWORD = 167; +pub const ERROR_BUSY: ::DWORD = 170; +pub const ERROR_DEVICE_SUPPORT_IN_PROGRESS: ::DWORD = 171; +pub const ERROR_CANCEL_VIOLATION: ::DWORD = 173; +pub const ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: ::DWORD = 174; +pub const ERROR_INVALID_SEGMENT_NUMBER: ::DWORD = 180; +pub const ERROR_INVALID_ORDINAL: ::DWORD = 182; +pub const ERROR_ALREADY_EXISTS: ::DWORD = 183; +pub const ERROR_INVALID_FLAG_NUMBER: ::DWORD = 186; +pub const ERROR_SEM_NOT_FOUND: ::DWORD = 187; +pub const ERROR_INVALID_STARTING_CODESEG: ::DWORD = 188; +pub const ERROR_INVALID_STACKSEG: ::DWORD = 189; +pub const ERROR_INVALID_MODULETYPE: ::DWORD = 190; +pub const ERROR_INVALID_EXE_SIGNATURE: ::DWORD = 191; +pub const ERROR_EXE_MARKED_INVALID: ::DWORD = 192; +pub const ERROR_BAD_EXE_FORMAT: ::DWORD = 193; +pub const ERROR_ITERATED_DATA_EXCEEDS_64k: ::DWORD = 194; +pub const ERROR_INVALID_MINALLOCSIZE: ::DWORD = 195; +pub const ERROR_DYNLINK_FROM_INVALID_RING: ::DWORD = 196; +pub const ERROR_IOPL_NOT_ENABLED: ::DWORD = 197; +pub const ERROR_INVALID_SEGDPL: ::DWORD = 198; +pub const ERROR_AUTODATASEG_EXCEEDS_64k: ::DWORD = 199; +pub const ERROR_RING2SEG_MUST_BE_MOVABLE: ::DWORD = 200; +pub const ERROR_RELOC_CHAIN_XEEDS_SEGLIM: ::DWORD = 201; +pub const ERROR_INFLOOP_IN_RELOC_CHAIN: ::DWORD = 202; +pub const ERROR_ENVVAR_NOT_FOUND: ::DWORD = 203; +pub const ERROR_NO_SIGNAL_SENT: ::DWORD = 205; +pub const ERROR_FILENAME_EXCED_RANGE: ::DWORD = 206; +pub const ERROR_RING2_STACK_IN_USE: ::DWORD = 207; +pub const ERROR_META_EXPANSION_TOO_LONG: ::DWORD = 208; +pub const ERROR_INVALID_SIGNAL_NUMBER: ::DWORD = 209; +pub const ERROR_THREAD_1_INACTIVE: ::DWORD = 210; +pub const ERROR_LOCKED: ::DWORD = 212; +pub const ERROR_TOO_MANY_MODULES: ::DWORD = 214; +pub const ERROR_NESTING_NOT_ALLOWED: ::DWORD = 215; +pub const ERROR_EXE_MACHINE_TYPE_MISMATCH: ::DWORD = 216; +pub const ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: ::DWORD = 217; +pub const ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: ::DWORD = 218; +pub const ERROR_FILE_CHECKED_OUT: ::DWORD = 220; +pub const ERROR_CHECKOUT_REQUIRED: ::DWORD = 221; +pub const ERROR_BAD_FILE_TYPE: ::DWORD = 222; +pub const ERROR_FILE_TOO_LARGE: ::DWORD = 223; +pub const ERROR_FORMS_AUTH_REQUIRED: ::DWORD = 224; +pub const ERROR_VIRUS_INFECTED: ::DWORD = 225; +pub const ERROR_VIRUS_DELETED: ::DWORD = 226; +pub const ERROR_PIPE_LOCAL: ::DWORD = 229; +pub const ERROR_BAD_PIPE: ::DWORD = 230; +pub const ERROR_PIPE_BUSY: ::DWORD = 231; +pub const ERROR_NO_DATA: ::DWORD = 232; +pub const ERROR_PIPE_NOT_CONNECTED: ::DWORD = 233; +pub const ERROR_MORE_DATA: ::DWORD = 234; +pub const ERROR_VC_DISCONNECTED: ::DWORD = 240; +pub const ERROR_INVALID_EA_NAME: ::DWORD = 254; +pub const ERROR_EA_LIST_INCONSISTENT: ::DWORD = 255; +pub const WAIT_TIMEOUT: ::DWORD = 258; +pub const ERROR_NO_MORE_ITEMS: ::DWORD = 259; +pub const ERROR_CANNOT_COPY: ::DWORD = 266; +pub const ERROR_DIRECTORY: ::DWORD = 267; +pub const ERROR_EAS_DIDNT_FIT: ::DWORD = 275; +pub const ERROR_EA_FILE_CORRUPT: ::DWORD = 276; +pub const ERROR_EA_TABLE_FULL: ::DWORD = 277; +pub const ERROR_INVALID_EA_HANDLE: ::DWORD = 278; +pub const ERROR_EAS_NOT_SUPPORTED: ::DWORD = 282; +pub const ERROR_NOT_OWNER: ::DWORD = 288; +pub const ERROR_TOO_MANY_POSTS: ::DWORD = 298; +pub const ERROR_PARTIAL_COPY: ::DWORD = 299; +pub const ERROR_OPLOCK_NOT_GRANTED: ::DWORD = 300; +pub const ERROR_INVALID_OPLOCK_PROTOCOL: ::DWORD = 301; +pub const ERROR_DISK_TOO_FRAGMENTED: ::DWORD = 302; +pub const ERROR_DELETE_PENDING: ::DWORD = 303; +pub const ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: ::DWORD = 304; +pub const ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: ::DWORD = 305; +pub const ERROR_SECURITY_STREAM_IS_INCONSISTENT: ::DWORD = 306; +pub const ERROR_INVALID_LOCK_RANGE: ::DWORD = 307; +pub const ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT: ::DWORD = 308; +pub const ERROR_NOTIFICATION_GUID_ALREADY_DEFINED: ::DWORD = 309; +pub const ERROR_INVALID_EXCEPTION_HANDLER: ::DWORD = 310; +pub const ERROR_DUPLICATE_PRIVILEGES: ::DWORD = 311; +pub const ERROR_NO_RANGES_PROCESSED: ::DWORD = 312; +pub const ERROR_NOT_ALLOWED_ON_SYSTEM_FILE: ::DWORD = 313; +pub const ERROR_DISK_RESOURCES_EXHAUSTED: ::DWORD = 314; +pub const ERROR_INVALID_TOKEN: ::DWORD = 315; +pub const ERROR_DEVICE_FEATURE_NOT_SUPPORTED: ::DWORD = 316; +pub const ERROR_MR_MID_NOT_FOUND: ::DWORD = 317; +pub const ERROR_SCOPE_NOT_FOUND: ::DWORD = 318; +pub const ERROR_UNDEFINED_SCOPE: ::DWORD = 319; +pub const ERROR_INVALID_CAP: ::DWORD = 320; +pub const ERROR_DEVICE_UNREACHABLE: ::DWORD = 321; +pub const ERROR_DEVICE_NO_RESOURCES: ::DWORD = 322; +pub const ERROR_DATA_CHECKSUM_ERROR: ::DWORD = 323; +pub const ERROR_INTERMIXED_KERNEL_EA_OPERATION: ::DWORD = 324; +pub const ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED: ::DWORD = 326; +pub const ERROR_OFFSET_ALIGNMENT_VIOLATION: ::DWORD = 327; +pub const ERROR_INVALID_FIELD_IN_PARAMETER_LIST: ::DWORD = 328; +pub const ERROR_OPERATION_IN_PROGRESS: ::DWORD = 329; +pub const ERROR_BAD_DEVICE_PATH: ::DWORD = 330; +pub const ERROR_TOO_MANY_DESCRIPTORS: ::DWORD = 331; +pub const ERROR_SCRUB_DATA_DISABLED: ::DWORD = 332; +pub const ERROR_NOT_REDUNDANT_STORAGE: ::DWORD = 333; +pub const ERROR_RESIDENT_FILE_NOT_SUPPORTED: ::DWORD = 334; +pub const ERROR_COMPRESSED_FILE_NOT_SUPPORTED: ::DWORD = 335; +pub const ERROR_DIRECTORY_NOT_SUPPORTED: ::DWORD = 336; +pub const ERROR_NOT_READ_FROM_COPY: ::DWORD = 337; +pub const ERROR_FT_WRITE_FAILURE: ::DWORD = 338; +pub const ERROR_FT_DI_SCAN_REQUIRED: ::DWORD = 339; +pub const ERROR_INVALID_KERNEL_INFO_VERSION: ::DWORD = 340; +pub const ERROR_INVALID_PEP_INFO_VERSION: ::DWORD = 341; +pub const ERROR_OBJECT_NOT_EXTERNALLY_BACKED: ::DWORD = 342; +pub const ERROR_EXTERNAL_BACKING_PROVIDER_UNKNOWN: ::DWORD = 343; +pub const ERROR_FAIL_NOACTION_REBOOT: ::DWORD = 350; +pub const ERROR_FAIL_SHUTDOWN: ::DWORD = 351; +pub const ERROR_FAIL_RESTART: ::DWORD = 352; +pub const ERROR_MAX_SESSIONS_REACHED: ::DWORD = 353; +pub const ERROR_THREAD_MODE_ALREADY_BACKGROUND: ::DWORD = 400; +pub const ERROR_THREAD_MODE_NOT_BACKGROUND: ::DWORD = 401; +pub const ERROR_PROCESS_MODE_ALREADY_BACKGROUND: ::DWORD = 402; +pub const ERROR_PROCESS_MODE_NOT_BACKGROUND: ::DWORD = 403; +pub const ERROR_DEVICE_HARDWARE_ERROR: ::DWORD = 483; +pub const ERROR_INVALID_ADDRESS: ::DWORD = 487; +pub const ERROR_USER_PROFILE_LOAD: ::DWORD = 500; +pub const ERROR_ARITHMETIC_OVERFLOW: ::DWORD = 534; +pub const ERROR_PIPE_CONNECTED: ::DWORD = 535; +pub const ERROR_PIPE_LISTENING: ::DWORD = 536; +pub const ERROR_VERIFIER_STOP: ::DWORD = 537; +pub const ERROR_ABIOS_ERROR: ::DWORD = 538; +pub const ERROR_WX86_WARNING: ::DWORD = 539; +pub const ERROR_WX86_ERROR: ::DWORD = 540; +pub const ERROR_TIMER_NOT_CANCELED: ::DWORD = 541; +pub const ERROR_UNWIND: ::DWORD = 542; +pub const ERROR_BAD_STACK: ::DWORD = 543; +pub const ERROR_INVALID_UNWIND_TARGET: ::DWORD = 544; +pub const ERROR_INVALID_PORT_ATTRIBUTES: ::DWORD = 545; +pub const ERROR_PORT_MESSAGE_TOO_LONG: ::DWORD = 546; +pub const ERROR_INVALID_QUOTA_LOWER: ::DWORD = 547; +pub const ERROR_DEVICE_ALREADY_ATTACHED: ::DWORD = 548; +pub const ERROR_INSTRUCTION_MISALIGNMENT: ::DWORD = 549; +pub const ERROR_PROFILING_NOT_STARTED: ::DWORD = 550; +pub const ERROR_PROFILING_NOT_STOPPED: ::DWORD = 551; +pub const ERROR_COULD_NOT_INTERPRET: ::DWORD = 552; +pub const ERROR_PROFILING_AT_LIMIT: ::DWORD = 553; +pub const ERROR_CANT_WAIT: ::DWORD = 554; +pub const ERROR_CANT_TERMINATE_SELF: ::DWORD = 555; +pub const ERROR_UNEXPECTED_MM_CREATE_ERR: ::DWORD = 556; +pub const ERROR_UNEXPECTED_MM_MAP_ERROR: ::DWORD = 557; +pub const ERROR_UNEXPECTED_MM_EXTEND_ERR: ::DWORD = 558; +pub const ERROR_BAD_FUNCTION_TABLE: ::DWORD = 559; +pub const ERROR_NO_GUID_TRANSLATION: ::DWORD = 560; +pub const ERROR_INVALID_LDT_SIZE: ::DWORD = 561; +pub const ERROR_INVALID_LDT_OFFSET: ::DWORD = 563; +pub const ERROR_INVALID_LDT_DESCRIPTOR: ::DWORD = 564; +pub const ERROR_TOO_MANY_THREADS: ::DWORD = 565; +pub const ERROR_THREAD_NOT_IN_PROCESS: ::DWORD = 566; +pub const ERROR_PAGEFILE_QUOTA_EXCEEDED: ::DWORD = 567; +pub const ERROR_LOGON_SERVER_CONFLICT: ::DWORD = 568; +pub const ERROR_SYNCHRONIZATION_REQUIRED: ::DWORD = 569; +pub const ERROR_NET_OPEN_FAILED: ::DWORD = 570; +pub const ERROR_IO_PRIVILEGE_FAILED: ::DWORD = 571; +pub const ERROR_CONTROL_C_EXIT: ::DWORD = 572; +pub const ERROR_MISSING_SYSTEMFILE: ::DWORD = 573; +pub const ERROR_UNHANDLED_EXCEPTION: ::DWORD = 574; +pub const ERROR_APP_INIT_FAILURE: ::DWORD = 575; +pub const ERROR_PAGEFILE_CREATE_FAILED: ::DWORD = 576; +pub const ERROR_INVALID_IMAGE_HASH: ::DWORD = 577; +pub const ERROR_NO_PAGEFILE: ::DWORD = 578; +pub const ERROR_ILLEGAL_FLOAT_CONTEXT: ::DWORD = 579; +pub const ERROR_NO_EVENT_PAIR: ::DWORD = 580; +pub const ERROR_DOMAIN_CTRLR_CONFIG_ERROR: ::DWORD = 581; +pub const ERROR_ILLEGAL_CHARACTER: ::DWORD = 582; +pub const ERROR_UNDEFINED_CHARACTER: ::DWORD = 583; +pub const ERROR_FLOPPY_VOLUME: ::DWORD = 584; +pub const ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT: ::DWORD = 585; +pub const ERROR_BACKUP_CONTROLLER: ::DWORD = 586; +pub const ERROR_MUTANT_LIMIT_EXCEEDED: ::DWORD = 587; +pub const ERROR_FS_DRIVER_REQUIRED: ::DWORD = 588; +pub const ERROR_CANNOT_LOAD_REGISTRY_FILE: ::DWORD = 589; +pub const ERROR_DEBUG_ATTACH_FAILED: ::DWORD = 590; +pub const ERROR_SYSTEM_PROCESS_TERMINATED: ::DWORD = 591; +pub const ERROR_DATA_NOT_ACCEPTED: ::DWORD = 592; +pub const ERROR_VDM_HARD_ERROR: ::DWORD = 593; +pub const ERROR_DRIVER_CANCEL_TIMEOUT: ::DWORD = 594; +pub const ERROR_REPLY_MESSAGE_MISMATCH: ::DWORD = 595; +pub const ERROR_LOST_WRITEBEHIND_DATA: ::DWORD = 596; +pub const ERROR_CLIENT_SERVER_PARAMETERS_INVALID: ::DWORD = 597; +pub const ERROR_NOT_TINY_STREAM: ::DWORD = 598; +pub const ERROR_STACK_OVERFLOW_READ: ::DWORD = 599; +pub const ERROR_CONVERT_TO_LARGE: ::DWORD = 600; +pub const ERROR_FOUND_OUT_OF_SCOPE: ::DWORD = 601; +pub const ERROR_ALLOCATE_BUCKET: ::DWORD = 602; +pub const ERROR_MARSHALL_OVERFLOW: ::DWORD = 603; +pub const ERROR_INVALID_VARIANT: ::DWORD = 604; +pub const ERROR_BAD_COMPRESSION_BUFFER: ::DWORD = 605; +pub const ERROR_AUDIT_FAILED: ::DWORD = 606; +pub const ERROR_TIMER_RESOLUTION_NOT_SET: ::DWORD = 607; +pub const ERROR_INSUFFICIENT_LOGON_INFO: ::DWORD = 608; +pub const ERROR_BAD_DLL_ENTRYPOINT: ::DWORD = 609; +pub const ERROR_BAD_SERVICE_ENTRYPOINT: ::DWORD = 610; +pub const ERROR_IP_ADDRESS_CONFLICT1: ::DWORD = 611; +pub const ERROR_IP_ADDRESS_CONFLICT2: ::DWORD = 612; +pub const ERROR_REGISTRY_QUOTA_LIMIT: ::DWORD = 613; +pub const ERROR_NO_CALLBACK_ACTIVE: ::DWORD = 614; +pub const ERROR_PWD_TOO_SHORT: ::DWORD = 615; +pub const ERROR_PWD_TOO_RECENT: ::DWORD = 616; +pub const ERROR_PWD_HISTORY_CONFLICT: ::DWORD = 617; +pub const ERROR_UNSUPPORTED_COMPRESSION: ::DWORD = 618; +pub const ERROR_INVALID_HW_PROFILE: ::DWORD = 619; +pub const ERROR_INVALID_PLUGPLAY_DEVICE_PATH: ::DWORD = 620; +pub const ERROR_QUOTA_LIST_INCONSISTENT: ::DWORD = 621; +pub const ERROR_EVALUATION_EXPIRATION: ::DWORD = 622; +pub const ERROR_ILLEGAL_DLL_RELOCATION: ::DWORD = 623; +pub const ERROR_DLL_INIT_FAILED_LOGOFF: ::DWORD = 624; +pub const ERROR_VALIDATE_CONTINUE: ::DWORD = 625; +pub const ERROR_NO_MORE_MATCHES: ::DWORD = 626; +pub const ERROR_RANGE_LIST_CONFLICT: ::DWORD = 627; +pub const ERROR_SERVER_SID_MISMATCH: ::DWORD = 628; +pub const ERROR_CANT_ENABLE_DENY_ONLY: ::DWORD = 629; +pub const ERROR_FLOAT_MULTIPLE_FAULTS: ::DWORD = 630; +pub const ERROR_FLOAT_MULTIPLE_TRAPS: ::DWORD = 631; +pub const ERROR_NOINTERFACE: ::DWORD = 632; +pub const ERROR_DRIVER_FAILED_SLEEP: ::DWORD = 633; +pub const ERROR_CORRUPT_SYSTEM_FILE: ::DWORD = 634; +pub const ERROR_COMMITMENT_MINIMUM: ::DWORD = 635; +pub const ERROR_PNP_RESTART_ENUMERATION: ::DWORD = 636; +pub const ERROR_SYSTEM_IMAGE_BAD_SIGNATURE: ::DWORD = 637; +pub const ERROR_PNP_REBOOT_REQUIRED: ::DWORD = 638; +pub const ERROR_INSUFFICIENT_POWER: ::DWORD = 639; +pub const ERROR_MULTIPLE_FAULT_VIOLATION: ::DWORD = 640; +pub const ERROR_SYSTEM_SHUTDOWN: ::DWORD = 641; +pub const ERROR_PORT_NOT_SET: ::DWORD = 642; +pub const ERROR_DS_VERSION_CHECK_FAILURE: ::DWORD = 643; +pub const ERROR_RANGE_NOT_FOUND: ::DWORD = 644; +pub const ERROR_NOT_SAFE_MODE_DRIVER: ::DWORD = 646; +pub const ERROR_FAILED_DRIVER_ENTRY: ::DWORD = 647; +pub const ERROR_DEVICE_ENUMERATION_ERROR: ::DWORD = 648; +pub const ERROR_MOUNT_POINT_NOT_RESOLVED: ::DWORD = 649; +pub const ERROR_INVALID_DEVICE_OBJECT_PARAMETER: ::DWORD = 650; +pub const ERROR_MCA_OCCURED: ::DWORD = 651; +pub const ERROR_DRIVER_DATABASE_ERROR: ::DWORD = 652; +pub const ERROR_SYSTEM_HIVE_TOO_LARGE: ::DWORD = 653; +pub const ERROR_DRIVER_FAILED_PRIOR_UNLOAD: ::DWORD = 654; +pub const ERROR_VOLSNAP_PREPARE_HIBERNATE: ::DWORD = 655; +pub const ERROR_HIBERNATION_FAILURE: ::DWORD = 656; +pub const ERROR_PWD_TOO_LONG: ::DWORD = 657; +pub const ERROR_FILE_SYSTEM_LIMITATION: ::DWORD = 665; +pub const ERROR_ASSERTION_FAILURE: ::DWORD = 668; +pub const ERROR_ACPI_ERROR: ::DWORD = 669; +pub const ERROR_WOW_ASSERTION: ::DWORD = 670; +pub const ERROR_PNP_BAD_MPS_TABLE: ::DWORD = 671; +pub const ERROR_PNP_TRANSLATION_FAILED: ::DWORD = 672; +pub const ERROR_PNP_IRQ_TRANSLATION_FAILED: ::DWORD = 673; +pub const ERROR_PNP_INVALID_ID: ::DWORD = 674; +pub const ERROR_WAKE_SYSTEM_DEBUGGER: ::DWORD = 675; +pub const ERROR_HANDLES_CLOSED: ::DWORD = 676; +pub const ERROR_EXTRANEOUS_INFORMATION: ::DWORD = 677; +pub const ERROR_RXACT_COMMIT_NECESSARY: ::DWORD = 678; +pub const ERROR_MEDIA_CHECK: ::DWORD = 679; +pub const ERROR_GUID_SUBSTITUTION_MADE: ::DWORD = 680; +pub const ERROR_STOPPED_ON_SYMLINK: ::DWORD = 681; +pub const ERROR_LONGJUMP: ::DWORD = 682; +pub const ERROR_PLUGPLAY_QUERY_VETOED: ::DWORD = 683; +pub const ERROR_UNWIND_CONSOLIDATE: ::DWORD = 684; +pub const ERROR_REGISTRY_HIVE_RECOVERED: ::DWORD = 685; +pub const ERROR_DLL_MIGHT_BE_INSECURE: ::DWORD = 686; +pub const ERROR_DLL_MIGHT_BE_INCOMPATIBLE: ::DWORD = 687; +pub const ERROR_DBG_EXCEPTION_NOT_HANDLED: ::DWORD = 688; +pub const ERROR_DBG_REPLY_LATER: ::DWORD = 689; +pub const ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE: ::DWORD = 690; +pub const ERROR_DBG_TERMINATE_THREAD: ::DWORD = 691; +pub const ERROR_DBG_TERMINATE_PROCESS: ::DWORD = 692; +pub const ERROR_DBG_CONTROL_C: ::DWORD = 693; +pub const ERROR_DBG_PRINTEXCEPTION_C: ::DWORD = 694; +pub const ERROR_DBG_RIPEXCEPTION: ::DWORD = 695; +pub const ERROR_DBG_CONTROL_BREAK: ::DWORD = 696; +pub const ERROR_DBG_COMMAND_EXCEPTION: ::DWORD = 697; +pub const ERROR_OBJECT_NAME_EXISTS: ::DWORD = 698; +pub const ERROR_THREAD_WAS_SUSPENDED: ::DWORD = 699; +pub const ERROR_IMAGE_NOT_AT_BASE: ::DWORD = 700; +pub const ERROR_RXACT_STATE_CREATED: ::DWORD = 701; +pub const ERROR_SEGMENT_NOTIFICATION: ::DWORD = 702; +pub const ERROR_BAD_CURRENT_DIRECTORY: ::DWORD = 703; +pub const ERROR_FT_READ_RECOVERY_FROM_BACKUP: ::DWORD = 704; +pub const ERROR_FT_WRITE_RECOVERY: ::DWORD = 705; +pub const ERROR_IMAGE_MACHINE_TYPE_MISMATCH: ::DWORD = 706; +pub const ERROR_RECEIVE_PARTIAL: ::DWORD = 707; +pub const ERROR_RECEIVE_EXPEDITED: ::DWORD = 708; +pub const ERROR_RECEIVE_PARTIAL_EXPEDITED: ::DWORD = 709; +pub const ERROR_EVENT_DONE: ::DWORD = 710; +pub const ERROR_EVENT_PENDING: ::DWORD = 711; +pub const ERROR_CHECKING_FILE_SYSTEM: ::DWORD = 712; +pub const ERROR_FATAL_APP_EXIT: ::DWORD = 713; +pub const ERROR_PREDEFINED_HANDLE: ::DWORD = 714; +pub const ERROR_WAS_UNLOCKED: ::DWORD = 715; +pub const ERROR_SERVICE_NOTIFICATION: ::DWORD = 716; +pub const ERROR_WAS_LOCKED: ::DWORD = 717; +pub const ERROR_LOG_HARD_ERROR: ::DWORD = 718; +pub const ERROR_ALREADY_WIN32: ::DWORD = 719; +pub const ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE: ::DWORD = 720; +pub const ERROR_NO_YIELD_PERFORMED: ::DWORD = 721; +pub const ERROR_TIMER_RESUME_IGNORED: ::DWORD = 722; +pub const ERROR_ARBITRATION_UNHANDLED: ::DWORD = 723; +pub const ERROR_CARDBUS_NOT_SUPPORTED: ::DWORD = 724; +pub const ERROR_MP_PROCESSOR_MISMATCH: ::DWORD = 725; +pub const ERROR_HIBERNATED: ::DWORD = 726; +pub const ERROR_RESUME_HIBERNATION: ::DWORD = 727; +pub const ERROR_FIRMWARE_UPDATED: ::DWORD = 728; +pub const ERROR_DRIVERS_LEAKING_LOCKED_PAGES: ::DWORD = 729; +pub const ERROR_WAKE_SYSTEM: ::DWORD = 730; +pub const ERROR_WAIT_1: ::DWORD = 731; +pub const ERROR_WAIT_2: ::DWORD = 732; +pub const ERROR_WAIT_3: ::DWORD = 733; +pub const ERROR_WAIT_63: ::DWORD = 734; +pub const ERROR_ABANDONED_WAIT_0: ::DWORD = 735; +pub const ERROR_ABANDONED_WAIT_63: ::DWORD = 736; +pub const ERROR_USER_APC: ::DWORD = 737; +pub const ERROR_KERNEL_APC: ::DWORD = 738; +pub const ERROR_ALERTED: ::DWORD = 739; +pub const ERROR_ELEVATION_REQUIRED: ::DWORD = 740; +pub const ERROR_REPARSE: ::DWORD = 741; +pub const ERROR_OPLOCK_BREAK_IN_PROGRESS: ::DWORD = 742; +pub const ERROR_VOLUME_MOUNTED: ::DWORD = 743; +pub const ERROR_RXACT_COMMITTED: ::DWORD = 744; +pub const ERROR_NOTIFY_CLEANUP: ::DWORD = 745; +pub const ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED: ::DWORD = 746; +pub const ERROR_PAGE_FAULT_TRANSITION: ::DWORD = 747; +pub const ERROR_PAGE_FAULT_DEMAND_ZERO: ::DWORD = 748; +pub const ERROR_PAGE_FAULT_COPY_ON_WRITE: ::DWORD = 749; +pub const ERROR_PAGE_FAULT_GUARD_PAGE: ::DWORD = 750; +pub const ERROR_PAGE_FAULT_PAGING_FILE: ::DWORD = 751; +pub const ERROR_CACHE_PAGE_LOCKED: ::DWORD = 752; +pub const ERROR_CRASH_DUMP: ::DWORD = 753; +pub const ERROR_BUFFER_ALL_ZEROS: ::DWORD = 754; +pub const ERROR_REPARSE_OBJECT: ::DWORD = 755; +pub const ERROR_RESOURCE_REQUIREMENTS_CHANGED: ::DWORD = 756; +pub const ERROR_TRANSLATION_COMPLETE: ::DWORD = 757; +pub const ERROR_NOTHING_TO_TERMINATE: ::DWORD = 758; +pub const ERROR_PROCESS_NOT_IN_JOB: ::DWORD = 759; +pub const ERROR_PROCESS_IN_JOB: ::DWORD = 760; +pub const ERROR_VOLSNAP_HIBERNATE_READY: ::DWORD = 761; +pub const ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY: ::DWORD = 762; +pub const ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED: ::DWORD = 763; +pub const ERROR_INTERRUPT_STILL_CONNECTED: ::DWORD = 764; +pub const ERROR_WAIT_FOR_OPLOCK: ::DWORD = 765; +pub const ERROR_DBG_EXCEPTION_HANDLED: ::DWORD = 766; +pub const ERROR_DBG_CONTINUE: ::DWORD = 767; +pub const ERROR_CALLBACK_POP_STACK: ::DWORD = 768; +pub const ERROR_COMPRESSION_DISABLED: ::DWORD = 769; +pub const ERROR_CANTFETCHBACKWARDS: ::DWORD = 770; +pub const ERROR_CANTSCROLLBACKWARDS: ::DWORD = 771; +pub const ERROR_ROWSNOTRELEASED: ::DWORD = 772; +pub const ERROR_BAD_ACCESSOR_FLAGS: ::DWORD = 773; +pub const ERROR_ERRORS_ENCOUNTERED: ::DWORD = 774; +pub const ERROR_NOT_CAPABLE: ::DWORD = 775; +pub const ERROR_REQUEST_OUT_OF_SEQUENCE: ::DWORD = 776; +pub const ERROR_VERSION_PARSE_ERROR: ::DWORD = 777; +pub const ERROR_BADSTARTPOSITION: ::DWORD = 778; +pub const ERROR_MEMORY_HARDWARE: ::DWORD = 779; +pub const ERROR_DISK_REPAIR_DISABLED: ::DWORD = 780; +pub const ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: ::DWORD = 781; +pub const ERROR_SYSTEM_POWERSTATE_TRANSITION: ::DWORD = 782; +pub const ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: ::DWORD = 783; +pub const ERROR_MCA_EXCEPTION: ::DWORD = 784; +pub const ERROR_ACCESS_AUDIT_BY_POLICY: ::DWORD = 785; +pub const ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: ::DWORD = 786; +pub const ERROR_ABANDON_HIBERFILE: ::DWORD = 787; +pub const ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: ::DWORD = 788; +pub const ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: ::DWORD = 789; +pub const ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: ::DWORD = 790; +pub const ERROR_BAD_MCFG_TABLE: ::DWORD = 791; +pub const ERROR_DISK_REPAIR_REDIRECTED: ::DWORD = 792; +pub const ERROR_DISK_REPAIR_UNSUCCESSFUL: ::DWORD = 793; +pub const ERROR_CORRUPT_LOG_OVERFULL: ::DWORD = 794; +pub const ERROR_CORRUPT_LOG_CORRUPTED: ::DWORD = 795; +pub const ERROR_CORRUPT_LOG_UNAVAILABLE: ::DWORD = 796; +pub const ERROR_CORRUPT_LOG_DELETED_FULL: ::DWORD = 797; +pub const ERROR_CORRUPT_LOG_CLEARED: ::DWORD = 798; +pub const ERROR_ORPHAN_NAME_EXHAUSTED: ::DWORD = 799; +pub const ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE: ::DWORD = 800; +pub const ERROR_CANNOT_GRANT_REQUESTED_OPLOCK: ::DWORD = 801; +pub const ERROR_CANNOT_BREAK_OPLOCK: ::DWORD = 802; +pub const ERROR_OPLOCK_HANDLE_CLOSED: ::DWORD = 803; +pub const ERROR_NO_ACE_CONDITION: ::DWORD = 804; +pub const ERROR_INVALID_ACE_CONDITION: ::DWORD = 805; +pub const ERROR_FILE_HANDLE_REVOKED: ::DWORD = 806; +pub const ERROR_IMAGE_AT_DIFFERENT_BASE: ::DWORD = 807; +pub const ERROR_ENCRYPTED_IO_NOT_POSSIBLE: ::DWORD = 808; +pub const ERROR_EA_ACCESS_DENIED: ::DWORD = 994; +pub const ERROR_OPERATION_ABORTED: ::DWORD = 995; +pub const ERROR_IO_INCOMPLETE: ::DWORD = 996; +pub const ERROR_IO_PENDING: ::DWORD = 997; +pub const ERROR_NOACCESS: ::DWORD = 998; +pub const ERROR_SWAPERROR: ::DWORD = 999; +pub const ERROR_STACK_OVERFLOW: ::DWORD = 1001; +pub const ERROR_INVALID_MESSAGE: ::DWORD = 1002; +pub const ERROR_CAN_NOT_COMPLETE: ::DWORD = 1003; +pub const ERROR_INVALID_FLAGS: ::DWORD = 1004; +pub const ERROR_UNRECOGNIZED_VOLUME: ::DWORD = 1005; +pub const ERROR_FILE_INVALID: ::DWORD = 1006; +pub const ERROR_FULLSCREEN_MODE: ::DWORD = 1007; +pub const ERROR_NO_TOKEN: ::DWORD = 1008; +pub const ERROR_BADDB: ::DWORD = 1009; +pub const ERROR_BADKEY: ::DWORD = 1010; +pub const ERROR_CANTOPEN: ::DWORD = 1011; +pub const ERROR_CANTREAD: ::DWORD = 1012; +pub const ERROR_CANTWRITE: ::DWORD = 1013; +pub const ERROR_REGISTRY_RECOVERED: ::DWORD = 1014; +pub const ERROR_REGISTRY_CORRUPT: ::DWORD = 1015; +pub const ERROR_REGISTRY_IO_FAILED: ::DWORD = 1016; +pub const ERROR_NOT_REGISTRY_FILE: ::DWORD = 1017; +pub const ERROR_KEY_DELETED: ::DWORD = 1018; +pub const ERROR_NO_LOG_SPACE: ::DWORD = 1019; +pub const ERROR_KEY_HAS_CHILDREN: ::DWORD = 1020; +pub const ERROR_CHILD_MUST_BE_VOLATILE: ::DWORD = 1021; +pub const ERROR_NOTIFY_ENUM_DIR: ::DWORD = 1022; +pub const ERROR_DEPENDENT_SERVICES_RUNNING: ::DWORD = 1051; +pub const ERROR_INVALID_SERVICE_CONTROL: ::DWORD = 1052; +pub const ERROR_SERVICE_REQUEST_TIMEOUT: ::DWORD = 1053; +pub const ERROR_SERVICE_NO_THREAD: ::DWORD = 1054; +pub const ERROR_SERVICE_DATABASE_LOCKED: ::DWORD = 1055; +pub const ERROR_SERVICE_ALREADY_RUNNING: ::DWORD = 1056; +pub const ERROR_INVALID_SERVICE_ACCOUNT: ::DWORD = 1057; +pub const ERROR_SERVICE_DISABLED: ::DWORD = 1058; +pub const ERROR_CIRCULAR_DEPENDENCY: ::DWORD = 1059; +pub const ERROR_SERVICE_DOES_NOT_EXIST: ::DWORD = 1060; +pub const ERROR_SERVICE_CANNOT_ACCEPT_CTRL: ::DWORD = 1061; +pub const ERROR_SERVICE_NOT_ACTIVE: ::DWORD = 1062; +pub const ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: ::DWORD = 1063; +pub const ERROR_EXCEPTION_IN_SERVICE: ::DWORD = 1064; +pub const ERROR_DATABASE_DOES_NOT_EXIST: ::DWORD = 1065; +pub const ERROR_SERVICE_SPECIFIC_ERROR: ::DWORD = 1066; +pub const ERROR_PROCESS_ABORTED: ::DWORD = 1067; +pub const ERROR_SERVICE_DEPENDENCY_FAIL: ::DWORD = 1068; +pub const ERROR_SERVICE_LOGON_FAILED: ::DWORD = 1069; +pub const ERROR_SERVICE_START_HANG: ::DWORD = 1070; +pub const ERROR_INVALID_SERVICE_LOCK: ::DWORD = 1071; +pub const ERROR_SERVICE_MARKED_FOR_DELETE: ::DWORD = 1072; +pub const ERROR_SERVICE_EXISTS: ::DWORD = 1073; +pub const ERROR_ALREADY_RUNNING_LKG: ::DWORD = 1074; +pub const ERROR_SERVICE_DEPENDENCY_DELETED: ::DWORD = 1075; +pub const ERROR_BOOT_ALREADY_ACCEPTED: ::DWORD = 1076; +pub const ERROR_SERVICE_NEVER_STARTED: ::DWORD = 1077; +pub const ERROR_DUPLICATE_SERVICE_NAME: ::DWORD = 1078; +pub const ERROR_DIFFERENT_SERVICE_ACCOUNT: ::DWORD = 1079; +pub const ERROR_CANNOT_DETECT_DRIVER_FAILURE: ::DWORD = 1080; +pub const ERROR_CANNOT_DETECT_PROCESS_ABORT: ::DWORD = 1081; +pub const ERROR_NO_RECOVERY_PROGRAM: ::DWORD = 1082; +pub const ERROR_SERVICE_NOT_IN_EXE: ::DWORD = 1083; +pub const ERROR_NOT_SAFEBOOT_SERVICE: ::DWORD = 1084; +pub const ERROR_END_OF_MEDIA: ::DWORD = 1100; +pub const ERROR_FILEMARK_DETECTED: ::DWORD = 1101; +pub const ERROR_BEGINNING_OF_MEDIA: ::DWORD = 1102; +pub const ERROR_SETMARK_DETECTED: ::DWORD = 1103; +pub const ERROR_NO_DATA_DETECTED: ::DWORD = 1104; +pub const ERROR_PARTITION_FAILURE: ::DWORD = 1105; +pub const ERROR_INVALID_BLOCK_LENGTH: ::DWORD = 1106; +pub const ERROR_DEVICE_NOT_PARTITIONED: ::DWORD = 1107; +pub const ERROR_UNABLE_TO_LOCK_MEDIA: ::DWORD = 1108; +pub const ERROR_UNABLE_TO_UNLOAD_MEDIA: ::DWORD = 1109; +pub const ERROR_MEDIA_CHANGED: ::DWORD = 1110; +pub const ERROR_BUS_RESET: ::DWORD = 1111; +pub const ERROR_NO_MEDIA_IN_DRIVE: ::DWORD = 1112; +pub const ERROR_NO_UNICODE_TRANSLATION: ::DWORD = 1113; +pub const ERROR_DLL_INIT_FAILED: ::DWORD = 1114; +pub const ERROR_SHUTDOWN_IN_PROGRESS: ::DWORD = 1115; +pub const ERROR_NO_SHUTDOWN_IN_PROGRESS: ::DWORD = 1116; +pub const ERROR_IO_DEVICE: ::DWORD = 1117; +pub const ERROR_SERIAL_NO_DEVICE: ::DWORD = 1118; +pub const ERROR_IRQ_BUSY: ::DWORD = 1119; +pub const ERROR_MORE_WRITES: ::DWORD = 1120; +pub const ERROR_COUNTER_TIMEOUT: ::DWORD = 1121; +pub const ERROR_FLOPPY_ID_MARK_NOT_FOUND: ::DWORD = 1122; +pub const ERROR_FLOPPY_WRONG_CYLINDER: ::DWORD = 1123; +pub const ERROR_FLOPPY_UNKNOWN_ERROR: ::DWORD = 1124; +pub const ERROR_FLOPPY_BAD_REGISTERS: ::DWORD = 1125; +pub const ERROR_DISK_RECALIBRATE_FAILED: ::DWORD = 1126; +pub const ERROR_DISK_OPERATION_FAILED: ::DWORD = 1127; +pub const ERROR_DISK_RESET_FAILED: ::DWORD = 1128; +pub const ERROR_EOM_OVERFLOW: ::DWORD = 1129; +pub const ERROR_NOT_ENOUGH_SERVER_MEMORY: ::DWORD = 1130; +pub const ERROR_POSSIBLE_DEADLOCK: ::DWORD = 1131; +pub const ERROR_MAPPED_ALIGNMENT: ::DWORD = 1132; +pub const ERROR_SET_POWER_STATE_VETOED: ::DWORD = 1140; +pub const ERROR_SET_POWER_STATE_FAILED: ::DWORD = 1141; +pub const ERROR_TOO_MANY_LINKS: ::DWORD = 1142; +pub const ERROR_OLD_WIN_VERSION: ::DWORD = 1150; +pub const ERROR_APP_WRONG_OS: ::DWORD = 1151; +pub const ERROR_SINGLE_INSTANCE_APP: ::DWORD = 1152; +pub const ERROR_RMODE_APP: ::DWORD = 1153; +pub const ERROR_INVALID_DLL: ::DWORD = 1154; +pub const ERROR_NO_ASSOCIATION: ::DWORD = 1155; +pub const ERROR_DDE_FAIL: ::DWORD = 1156; +pub const ERROR_DLL_NOT_FOUND: ::DWORD = 1157; +pub const ERROR_NO_MORE_USER_HANDLES: ::DWORD = 1158; +pub const ERROR_MESSAGE_SYNC_ONLY: ::DWORD = 1159; +pub const ERROR_SOURCE_ELEMENT_EMPTY: ::DWORD = 1160; +pub const ERROR_DESTINATION_ELEMENT_FULL: ::DWORD = 1161; +pub const ERROR_ILLEGAL_ELEMENT_ADDRESS: ::DWORD = 1162; +pub const ERROR_MAGAZINE_NOT_PRESENT: ::DWORD = 1163; +pub const ERROR_DEVICE_REINITIALIZATION_NEEDED: ::DWORD = 1164; +pub const ERROR_DEVICE_REQUIRES_CLEANING: ::DWORD = 1165; +pub const ERROR_DEVICE_DOOR_OPEN: ::DWORD = 1166; +pub const ERROR_DEVICE_NOT_CONNECTED: ::DWORD = 1167; +pub const ERROR_NOT_FOUND: ::DWORD = 1168; +pub const ERROR_NO_MATCH: ::DWORD = 1169; +pub const ERROR_SET_NOT_FOUND: ::DWORD = 1170; +pub const ERROR_POINT_NOT_FOUND: ::DWORD = 1171; +pub const ERROR_NO_TRACKING_SERVICE: ::DWORD = 1172; +pub const ERROR_NO_VOLUME_ID: ::DWORD = 1173; +pub const ERROR_UNABLE_TO_REMOVE_REPLACED: ::DWORD = 1175; +pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT: ::DWORD = 1176; +pub const ERROR_UNABLE_TO_MOVE_REPLACEMENT_2: ::DWORD = 1177; +pub const ERROR_JOURNAL_DELETE_IN_PROGRESS: ::DWORD = 1178; +pub const ERROR_JOURNAL_NOT_ACTIVE: ::DWORD = 1179; +pub const ERROR_POTENTIAL_FILE_FOUND: ::DWORD = 1180; +pub const ERROR_JOURNAL_ENTRY_DELETED: ::DWORD = 1181; +pub const ERROR_SHUTDOWN_IS_SCHEDULED: ::DWORD = 1190; +pub const ERROR_SHUTDOWN_USERS_LOGGED_ON: ::DWORD = 1191; +pub const ERROR_BAD_DEVICE: ::DWORD = 1200; +pub const ERROR_CONNECTION_UNAVAIL: ::DWORD = 1201; +pub const ERROR_DEVICE_ALREADY_REMEMBERED: ::DWORD = 1202; +pub const ERROR_NO_NET_OR_BAD_PATH: ::DWORD = 1203; +pub const ERROR_BAD_PROVIDER: ::DWORD = 1204; +pub const ERROR_CANNOT_OPEN_PROFILE: ::DWORD = 1205; +pub const ERROR_BAD_PROFILE: ::DWORD = 1206; +pub const ERROR_NOT_CONTAINER: ::DWORD = 1207; +pub const ERROR_EXTENDED_ERROR: ::DWORD = 1208; +pub const ERROR_INVALID_GROUPNAME: ::DWORD = 1209; +pub const ERROR_INVALID_COMPUTERNAME: ::DWORD = 1210; +pub const ERROR_INVALID_EVENTNAME: ::DWORD = 1211; +pub const ERROR_INVALID_DOMAINNAME: ::DWORD = 1212; +pub const ERROR_INVALID_SERVICENAME: ::DWORD = 1213; +pub const ERROR_INVALID_NETNAME: ::DWORD = 1214; +pub const ERROR_INVALID_SHARENAME: ::DWORD = 1215; +pub const ERROR_INVALID_PASSWORDNAME: ::DWORD = 1216; +pub const ERROR_INVALID_MESSAGENAME: ::DWORD = 1217; +pub const ERROR_INVALID_MESSAGEDEST: ::DWORD = 1218; +pub const ERROR_SESSION_CREDENTIAL_CONFLICT: ::DWORD = 1219; +pub const ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: ::DWORD = 1220; +pub const ERROR_DUP_DOMAINNAME: ::DWORD = 1221; +pub const ERROR_NO_NETWORK: ::DWORD = 1222; +pub const ERROR_CANCELLED: ::DWORD = 1223; +pub const ERROR_USER_MAPPED_FILE: ::DWORD = 1224; +pub const ERROR_CONNECTION_REFUSED: ::DWORD = 1225; +pub const ERROR_GRACEFUL_DISCONNECT: ::DWORD = 1226; +pub const ERROR_ADDRESS_ALREADY_ASSOCIATED: ::DWORD = 1227; +pub const ERROR_ADDRESS_NOT_ASSOCIATED: ::DWORD = 1228; +pub const ERROR_CONNECTION_INVALID: ::DWORD = 1229; +pub const ERROR_CONNECTION_ACTIVE: ::DWORD = 1230; +pub const ERROR_NETWORK_UNREACHABLE: ::DWORD = 1231; +pub const ERROR_HOST_UNREACHABLE: ::DWORD = 1232; +pub const ERROR_PROTOCOL_UNREACHABLE: ::DWORD = 1233; +pub const ERROR_PORT_UNREACHABLE: ::DWORD = 1234; +pub const ERROR_REQUEST_ABORTED: ::DWORD = 1235; +pub const ERROR_CONNECTION_ABORTED: ::DWORD = 1236; +pub const ERROR_RETRY: ::DWORD = 1237; +pub const ERROR_CONNECTION_COUNT_LIMIT: ::DWORD = 1238; +pub const ERROR_LOGIN_TIME_RESTRICTION: ::DWORD = 1239; +pub const ERROR_LOGIN_WKSTA_RESTRICTION: ::DWORD = 1240; +pub const ERROR_INCORRECT_ADDRESS: ::DWORD = 1241; +pub const ERROR_ALREADY_REGISTERED: ::DWORD = 1242; +pub const ERROR_SERVICE_NOT_FOUND: ::DWORD = 1243; +pub const ERROR_NOT_AUTHENTICATED: ::DWORD = 1244; +pub const ERROR_NOT_LOGGED_ON: ::DWORD = 1245; +pub const ERROR_CONTINUE: ::DWORD = 1246; +pub const ERROR_ALREADY_INITIALIZED: ::DWORD = 1247; +pub const ERROR_NO_MORE_DEVICES: ::DWORD = 1248; +pub const ERROR_NO_SUCH_SITE: ::DWORD = 1249; +pub const ERROR_DOMAIN_CONTROLLER_EXISTS: ::DWORD = 1250; +pub const ERROR_ONLY_IF_CONNECTED: ::DWORD = 1251; +pub const ERROR_OVERRIDE_NOCHANGES: ::DWORD = 1252; +pub const ERROR_BAD_USER_PROFILE: ::DWORD = 1253; +pub const ERROR_NOT_SUPPORTED_ON_SBS: ::DWORD = 1254; +pub const ERROR_SERVER_SHUTDOWN_IN_PROGRESS: ::DWORD = 1255; +pub const ERROR_HOST_DOWN: ::DWORD = 1256; +pub const ERROR_NON_ACCOUNT_SID: ::DWORD = 1257; +pub const ERROR_NON_DOMAIN_SID: ::DWORD = 1258; +pub const ERROR_APPHELP_BLOCK: ::DWORD = 1259; +pub const ERROR_ACCESS_DISABLED_BY_POLICY: ::DWORD = 1260; +pub const ERROR_REG_NAT_CONSUMPTION: ::DWORD = 1261; +pub const ERROR_CSCSHARE_OFFLINE: ::DWORD = 1262; +pub const ERROR_PKINIT_FAILURE: ::DWORD = 1263; +pub const ERROR_SMARTCARD_SUBSYSTEM_FAILURE: ::DWORD = 1264; +pub const ERROR_DOWNGRADE_DETECTED: ::DWORD = 1265; +pub const ERROR_MACHINE_LOCKED: ::DWORD = 1271; +pub const ERROR_CALLBACK_SUPPLIED_INVALID_DATA: ::DWORD = 1273; +pub const ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED: ::DWORD = 1274; +pub const ERROR_DRIVER_BLOCKED: ::DWORD = 1275; +pub const ERROR_INVALID_IMPORT_OF_NON_DLL: ::DWORD = 1276; +pub const ERROR_ACCESS_DISABLED_WEBBLADE: ::DWORD = 1277; +pub const ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER: ::DWORD = 1278; +pub const ERROR_RECOVERY_FAILURE: ::DWORD = 1279; +pub const ERROR_ALREADY_FIBER: ::DWORD = 1280; +pub const ERROR_ALREADY_THREAD: ::DWORD = 1281; +pub const ERROR_STACK_BUFFER_OVERRUN: ::DWORD = 1282; +pub const ERROR_PARAMETER_QUOTA_EXCEEDED: ::DWORD = 1283; +pub const ERROR_DEBUGGER_INACTIVE: ::DWORD = 1284; +pub const ERROR_DELAY_LOAD_FAILED: ::DWORD = 1285; +pub const ERROR_VDM_DISALLOWED: ::DWORD = 1286; +pub const ERROR_UNIDENTIFIED_ERROR: ::DWORD = 1287; +pub const ERROR_INVALID_CRUNTIME_PARAMETER: ::DWORD = 1288; +pub const ERROR_BEYOND_VDL: ::DWORD = 1289; +pub const ERROR_INCOMPATIBLE_SERVICE_SID_TYPE: ::DWORD = 1290; +pub const ERROR_DRIVER_PROCESS_TERMINATED: ::DWORD = 1291; +pub const ERROR_IMPLEMENTATION_LIMIT: ::DWORD = 1292; +pub const ERROR_PROCESS_IS_PROTECTED: ::DWORD = 1293; +pub const ERROR_SERVICE_NOTIFY_CLIENT_LAGGING: ::DWORD = 1294; +pub const ERROR_DISK_QUOTA_EXCEEDED: ::DWORD = 1295; +pub const ERROR_CONTENT_BLOCKED: ::DWORD = 1296; +pub const ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE: ::DWORD = 1297; +pub const ERROR_APP_HANG: ::DWORD = 1298; +pub const ERROR_INVALID_LABEL: ::DWORD = 1299; +pub const ERROR_NOT_ALL_ASSIGNED: ::DWORD = 1300; +pub const ERROR_SOME_NOT_MAPPED: ::DWORD = 1301; +pub const ERROR_NO_QUOTAS_FOR_ACCOUNT: ::DWORD = 1302; +pub const ERROR_LOCAL_USER_SESSION_KEY: ::DWORD = 1303; +pub const ERROR_NULL_LM_PASSWORD: ::DWORD = 1304; +pub const ERROR_UNKNOWN_REVISION: ::DWORD = 1305; +pub const ERROR_REVISION_MISMATCH: ::DWORD = 1306; +pub const ERROR_INVALID_OWNER: ::DWORD = 1307; +pub const ERROR_INVALID_PRIMARY_GROUP: ::DWORD = 1308; +pub const ERROR_NO_IMPERSONATION_TOKEN: ::DWORD = 1309; +pub const ERROR_CANT_DISABLE_MANDATORY: ::DWORD = 1310; +pub const ERROR_NO_LOGON_SERVERS: ::DWORD = 1311; +pub const ERROR_NO_SUCH_LOGON_SESSION: ::DWORD = 1312; +pub const ERROR_NO_SUCH_PRIVILEGE: ::DWORD = 1313; +pub const ERROR_PRIVILEGE_NOT_HELD: ::DWORD = 1314; +pub const ERROR_INVALID_ACCOUNT_NAME: ::DWORD = 1315; +pub const ERROR_USER_EXISTS: ::DWORD = 1316; +pub const ERROR_NO_SUCH_USER: ::DWORD = 1317; +pub const ERROR_GROUP_EXISTS: ::DWORD = 1318; +pub const ERROR_NO_SUCH_GROUP: ::DWORD = 1319; +pub const ERROR_MEMBER_IN_GROUP: ::DWORD = 1320; +pub const ERROR_MEMBER_NOT_IN_GROUP: ::DWORD = 1321; +pub const ERROR_LAST_ADMIN: ::DWORD = 1322; +pub const ERROR_WRONG_PASSWORD: ::DWORD = 1323; +pub const ERROR_ILL_FORMED_PASSWORD: ::DWORD = 1324; +pub const ERROR_PASSWORD_RESTRICTION: ::DWORD = 1325; +pub const ERROR_LOGON_FAILURE: ::DWORD = 1326; +pub const ERROR_ACCOUNT_RESTRICTION: ::DWORD = 1327; +pub const ERROR_INVALID_LOGON_HOURS: ::DWORD = 1328; +pub const ERROR_INVALID_WORKSTATION: ::DWORD = 1329; +pub const ERROR_PASSWORD_EXPIRED: ::DWORD = 1330; +pub const ERROR_ACCOUNT_DISABLED: ::DWORD = 1331; +pub const ERROR_NONE_MAPPED: ::DWORD = 1332; +pub const ERROR_TOO_MANY_LUIDS_REQUESTED: ::DWORD = 1333; +pub const ERROR_LUIDS_EXHAUSTED: ::DWORD = 1334; +pub const ERROR_INVALID_SUB_AUTHORITY: ::DWORD = 1335; +pub const ERROR_INVALID_ACL: ::DWORD = 1336; +pub const ERROR_INVALID_SID: ::DWORD = 1337; +pub const ERROR_INVALID_SECURITY_DESCR: ::DWORD = 1338; +pub const ERROR_BAD_INHERITANCE_ACL: ::DWORD = 1340; +pub const ERROR_SERVER_DISABLED: ::DWORD = 1341; +pub const ERROR_SERVER_NOT_DISABLED: ::DWORD = 1342; +pub const ERROR_INVALID_ID_AUTHORITY: ::DWORD = 1343; +pub const ERROR_ALLOTTED_SPACE_EXCEEDED: ::DWORD = 1344; +pub const ERROR_INVALID_GROUP_ATTRIBUTES: ::DWORD = 1345; +pub const ERROR_BAD_IMPERSONATION_LEVEL: ::DWORD = 1346; +pub const ERROR_CANT_OPEN_ANONYMOUS: ::DWORD = 1347; +pub const ERROR_BAD_VALIDATION_CLASS: ::DWORD = 1348; +pub const ERROR_BAD_TOKEN_TYPE: ::DWORD = 1349; +pub const ERROR_NO_SECURITY_ON_OBJECT: ::DWORD = 1350; +pub const ERROR_CANT_ACCESS_DOMAIN_INFO: ::DWORD = 1351; +pub const ERROR_INVALID_SERVER_STATE: ::DWORD = 1352; +pub const ERROR_INVALID_DOMAIN_STATE: ::DWORD = 1353; +pub const ERROR_INVALID_DOMAIN_ROLE: ::DWORD = 1354; +pub const ERROR_NO_SUCH_DOMAIN: ::DWORD = 1355; +pub const ERROR_DOMAIN_EXISTS: ::DWORD = 1356; +pub const ERROR_DOMAIN_LIMIT_EXCEEDED: ::DWORD = 1357; +pub const ERROR_INTERNAL_DB_CORRUPTION: ::DWORD = 1358; +pub const ERROR_INTERNAL_ERROR: ::DWORD = 1359; +pub const ERROR_GENERIC_NOT_MAPPED: ::DWORD = 1360; +pub const ERROR_BAD_DESCRIPTOR_FORMAT: ::DWORD = 1361; +pub const ERROR_NOT_LOGON_PROCESS: ::DWORD = 1362; +pub const ERROR_LOGON_SESSION_EXISTS: ::DWORD = 1363; +pub const ERROR_NO_SUCH_PACKAGE: ::DWORD = 1364; +pub const ERROR_BAD_LOGON_SESSION_STATE: ::DWORD = 1365; +pub const ERROR_LOGON_SESSION_COLLISION: ::DWORD = 1366; +pub const ERROR_INVALID_LOGON_TYPE: ::DWORD = 1367; +pub const ERROR_CANNOT_IMPERSONATE: ::DWORD = 1368; +pub const ERROR_RXACT_INVALID_STATE: ::DWORD = 1369; +pub const ERROR_RXACT_COMMIT_FAILURE: ::DWORD = 1370; +pub const ERROR_SPECIAL_ACCOUNT: ::DWORD = 1371; +pub const ERROR_SPECIAL_GROUP: ::DWORD = 1372; +pub const ERROR_SPECIAL_USER: ::DWORD = 1373; +pub const ERROR_MEMBERS_PRIMARY_GROUP: ::DWORD = 1374; +pub const ERROR_TOKEN_ALREADY_IN_USE: ::DWORD = 1375; +pub const ERROR_NO_SUCH_ALIAS: ::DWORD = 1376; +pub const ERROR_MEMBER_NOT_IN_ALIAS: ::DWORD = 1377; +pub const ERROR_MEMBER_IN_ALIAS: ::DWORD = 1378; +pub const ERROR_ALIAS_EXISTS: ::DWORD = 1379; +pub const ERROR_LOGON_NOT_GRANTED: ::DWORD = 1380; +pub const ERROR_TOO_MANY_SECRETS: ::DWORD = 1381; +pub const ERROR_SECRET_TOO_LONG: ::DWORD = 1382; +pub const ERROR_INTERNAL_DB_ERROR: ::DWORD = 1383; +pub const ERROR_TOO_MANY_CONTEXT_IDS: ::DWORD = 1384; +pub const ERROR_LOGON_TYPE_NOT_GRANTED: ::DWORD = 1385; +pub const ERROR_NT_CROSS_ENCRYPTION_REQUIRED: ::DWORD = 1386; +pub const ERROR_NO_SUCH_MEMBER: ::DWORD = 1387; +pub const ERROR_INVALID_MEMBER: ::DWORD = 1388; +pub const ERROR_TOO_MANY_SIDS: ::DWORD = 1389; +pub const ERROR_LM_CROSS_ENCRYPTION_REQUIRED: ::DWORD = 1390; +pub const ERROR_NO_INHERITANCE: ::DWORD = 1391; +pub const ERROR_FILE_CORRUPT: ::DWORD = 1392; +pub const ERROR_DISK_CORRUPT: ::DWORD = 1393; +pub const ERROR_NO_USER_SESSION_KEY: ::DWORD = 1394; +pub const ERROR_LICENSE_QUOTA_EXCEEDED: ::DWORD = 1395; +pub const ERROR_WRONG_TARGET_NAME: ::DWORD = 1396; +pub const ERROR_MUTUAL_AUTH_FAILED: ::DWORD = 1397; +pub const ERROR_TIME_SKEW: ::DWORD = 1398; +pub const ERROR_CURRENT_DOMAIN_NOT_ALLOWED: ::DWORD = 1399; +pub const ERROR_INVALID_WINDOW_HANDLE: ::DWORD = 1400; +pub const ERROR_INVALID_MENU_HANDLE: ::DWORD = 1401; +pub const ERROR_INVALID_CURSOR_HANDLE: ::DWORD = 1402; +pub const ERROR_INVALID_ACCEL_HANDLE: ::DWORD = 1403; +pub const ERROR_INVALID_HOOK_HANDLE: ::DWORD = 1404; +pub const ERROR_INVALID_DWP_HANDLE: ::DWORD = 1405; +pub const ERROR_TLW_WITH_WSCHILD: ::DWORD = 1406; +pub const ERROR_CANNOT_FIND_WND_CLASS: ::DWORD = 1407; +pub const ERROR_WINDOW_OF_OTHER_THREAD: ::DWORD = 1408; +pub const ERROR_HOTKEY_ALREADY_REGISTERED: ::DWORD = 1409; +pub const ERROR_CLASS_ALREADY_EXISTS: ::DWORD = 1410; +pub const ERROR_CLASS_DOES_NOT_EXIST: ::DWORD = 1411; +pub const ERROR_CLASS_HAS_WINDOWS: ::DWORD = 1412; +pub const ERROR_INVALID_INDEX: ::DWORD = 1413; +pub const ERROR_INVALID_ICON_HANDLE: ::DWORD = 1414; +pub const ERROR_PRIVATE_DIALOG_INDEX: ::DWORD = 1415; +pub const ERROR_LISTBOX_ID_NOT_FOUND: ::DWORD = 1416; +pub const ERROR_NO_WILDCARD_CHARACTERS: ::DWORD = 1417; +pub const ERROR_CLIPBOARD_NOT_OPEN: ::DWORD = 1418; +pub const ERROR_HOTKEY_NOT_REGISTERED: ::DWORD = 1419; +pub const ERROR_WINDOW_NOT_DIALOG: ::DWORD = 1420; +pub const ERROR_CONTROL_ID_NOT_FOUND: ::DWORD = 1421; +pub const ERROR_INVALID_COMBOBOX_MESSAGE: ::DWORD = 1422; +pub const ERROR_WINDOW_NOT_COMBOBOX: ::DWORD = 1423; +pub const ERROR_INVALID_EDIT_HEIGHT: ::DWORD = 1424; +pub const ERROR_DC_NOT_FOUND: ::DWORD = 1425; +pub const ERROR_INVALID_HOOK_FILTER: ::DWORD = 1426; +pub const ERROR_INVALID_FILTER_PROC: ::DWORD = 1427; +pub const ERROR_HOOK_NEEDS_HMOD: ::DWORD = 1428; +pub const ERROR_GLOBAL_ONLY_HOOK: ::DWORD = 1429; +pub const ERROR_JOURNAL_HOOK_SET: ::DWORD = 1430; +pub const ERROR_HOOK_NOT_INSTALLED: ::DWORD = 1431; +pub const ERROR_INVALID_LB_MESSAGE: ::DWORD = 1432; +pub const ERROR_SETCOUNT_ON_BAD_LB: ::DWORD = 1433; +pub const ERROR_LB_WITHOUT_TABSTOPS: ::DWORD = 1434; +pub const ERROR_DESTROY_OBJECT_OF_OTHER_THREAD: ::DWORD = 1435; +pub const ERROR_CHILD_WINDOW_MENU: ::DWORD = 1436; +pub const ERROR_NO_SYSTEM_MENU: ::DWORD = 1437; +pub const ERROR_INVALID_MSGBOX_STYLE: ::DWORD = 1438; +pub const ERROR_INVALID_SPI_VALUE: ::DWORD = 1439; +pub const ERROR_SCREEN_ALREADY_LOCKED: ::DWORD = 1440; +pub const ERROR_HWNDS_HAVE_DIFF_PARENT: ::DWORD = 1441; +pub const ERROR_NOT_CHILD_WINDOW: ::DWORD = 1442; +pub const ERROR_INVALID_GW_COMMAND: ::DWORD = 1443; +pub const ERROR_INVALID_THREAD_ID: ::DWORD = 1444; +pub const ERROR_NON_MDICHILD_WINDOW: ::DWORD = 1445; +pub const ERROR_POPUP_ALREADY_ACTIVE: ::DWORD = 1446; +pub const ERROR_NO_SCROLLBARS: ::DWORD = 1447; +pub const ERROR_INVALID_SCROLLBAR_RANGE: ::DWORD = 1448; +pub const ERROR_INVALID_SHOWWIN_COMMAND: ::DWORD = 1449; +pub const ERROR_NO_SYSTEM_RESOURCES: ::DWORD = 1450; +pub const ERROR_NONPAGED_SYSTEM_RESOURCES: ::DWORD = 1451; +pub const ERROR_PAGED_SYSTEM_RESOURCES: ::DWORD = 1452; +pub const ERROR_WORKING_SET_QUOTA: ::DWORD = 1453; +pub const ERROR_PAGEFILE_QUOTA: ::DWORD = 1454; +pub const ERROR_COMMITMENT_LIMIT: ::DWORD = 1455; +pub const ERROR_MENU_ITEM_NOT_FOUND: ::DWORD = 1456; +pub const ERROR_INVALID_KEYBOARD_HANDLE: ::DWORD = 1457; +pub const ERROR_HOOK_TYPE_NOT_ALLOWED: ::DWORD = 1458; +pub const ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION: ::DWORD = 1459; +pub const ERROR_TIMEOUT: ::DWORD = 1460; +pub const ERROR_INVALID_MONITOR_HANDLE: ::DWORD = 1461; +pub const ERROR_INCORRECT_SIZE: ::DWORD = 1462; +pub const ERROR_SYMLINK_CLASS_DISABLED: ::DWORD = 1463; +pub const ERROR_SYMLINK_NOT_SUPPORTED: ::DWORD = 1464; +pub const ERROR_XML_PARSE_ERROR: ::DWORD = 1465; +pub const ERROR_XMLDSIG_ERROR: ::DWORD = 1466; +pub const ERROR_RESTART_APPLICATION: ::DWORD = 1467; +pub const ERROR_WRONG_COMPARTMENT: ::DWORD = 1468; +pub const ERROR_AUTHIP_FAILURE: ::DWORD = 1469; +pub const ERROR_NO_NVRAM_RESOURCES: ::DWORD = 1470; +pub const ERROR_NOT_GUI_PROCESS: ::DWORD = 1471; +pub const ERROR_EVENTLOG_FILE_CORRUPT: ::DWORD = 1500; +pub const ERROR_EVENTLOG_CANT_START: ::DWORD = 1501; +pub const ERROR_LOG_FILE_FULL: ::DWORD = 1502; +pub const ERROR_EVENTLOG_FILE_CHANGED: ::DWORD = 1503; +pub const ERROR_INVALID_TASK_NAME: ::DWORD = 1550; +pub const ERROR_INVALID_TASK_INDEX: ::DWORD = 1551; +pub const ERROR_THREAD_ALREADY_IN_TASK: ::DWORD = 1552; +pub const ERROR_INSTALL_SERVICE_FAILURE: ::DWORD = 1601; +pub const ERROR_INSTALL_USEREXIT: ::DWORD = 1602; +pub const ERROR_INSTALL_FAILURE: ::DWORD = 1603; +pub const ERROR_INSTALL_SUSPEND: ::DWORD = 1604; +pub const ERROR_UNKNOWN_PRODUCT: ::DWORD = 1605; +pub const ERROR_UNKNOWN_FEATURE: ::DWORD = 1606; +pub const ERROR_UNKNOWN_COMPONENT: ::DWORD = 1607; +pub const ERROR_UNKNOWN_PROPERTY: ::DWORD = 1608; +pub const ERROR_INVALID_HANDLE_STATE: ::DWORD = 1609; +pub const ERROR_BAD_CONFIGURATION: ::DWORD = 1610; +pub const ERROR_INDEX_ABSENT: ::DWORD = 1611; +pub const ERROR_INSTALL_SOURCE_ABSENT: ::DWORD = 1612; +pub const ERROR_INSTALL_PACKAGE_VERSION: ::DWORD = 1613; +pub const ERROR_PRODUCT_UNINSTALLED: ::DWORD = 1614; +pub const ERROR_BAD_QUERY_SYNTAX: ::DWORD = 1615; +pub const ERROR_INVALID_FIELD: ::DWORD = 1616; +pub const ERROR_DEVICE_REMOVED: ::DWORD = 1617; +pub const ERROR_INSTALL_ALREADY_RUNNING: ::DWORD = 1618; +pub const ERROR_INSTALL_PACKAGE_OPEN_FAILED: ::DWORD = 1619; +pub const ERROR_INSTALL_PACKAGE_INVALID: ::DWORD = 1620; +pub const ERROR_INSTALL_UI_FAILURE: ::DWORD = 1621; +pub const ERROR_INSTALL_LOG_FAILURE: ::DWORD = 1622; +pub const ERROR_INSTALL_LANGUAGE_UNSUPPORTED: ::DWORD = 1623; +pub const ERROR_INSTALL_TRANSFORM_FAILURE: ::DWORD = 1624; +pub const ERROR_INSTALL_PACKAGE_REJECTED: ::DWORD = 1625; +pub const ERROR_FUNCTION_NOT_CALLED: ::DWORD = 1626; +pub const ERROR_FUNCTION_FAILED: ::DWORD = 1627; +pub const ERROR_INVALID_TABLE: ::DWORD = 1628; +pub const ERROR_DATATYPE_MISMATCH: ::DWORD = 1629; +pub const ERROR_UNSUPPORTED_TYPE: ::DWORD = 1630; +pub const ERROR_CREATE_FAILED: ::DWORD = 1631; +pub const ERROR_INSTALL_TEMP_UNWRITABLE: ::DWORD = 1632; +pub const ERROR_INSTALL_PLATFORM_UNSUPPORTED: ::DWORD = 1633; +pub const ERROR_INSTALL_NOTUSED: ::DWORD = 1634; +pub const ERROR_PATCH_PACKAGE_OPEN_FAILED: ::DWORD = 1635; +pub const ERROR_PATCH_PACKAGE_INVALID: ::DWORD = 1636; +pub const ERROR_PATCH_PACKAGE_UNSUPPORTED: ::DWORD = 1637; +pub const ERROR_PRODUCT_VERSION: ::DWORD = 1638; +pub const ERROR_INVALID_COMMAND_LINE: ::DWORD = 1639; +pub const ERROR_INSTALL_REMOTE_DISALLOWED: ::DWORD = 1640; +pub const ERROR_SUCCESS_REBOOT_INITIATED: ::DWORD = 1641; +pub const ERROR_PATCH_TARGET_NOT_FOUND: ::DWORD = 1642; +pub const ERROR_PATCH_PACKAGE_REJECTED: ::DWORD = 1643; +pub const ERROR_INSTALL_TRANSFORM_REJECTED: ::DWORD = 1644; +pub const ERROR_INSTALL_REMOTE_PROHIBITED: ::DWORD = 1645; +pub const ERROR_PATCH_REMOVAL_UNSUPPORTED: ::DWORD = 1646; +pub const ERROR_UNKNOWN_PATCH: ::DWORD = 1647; +pub const ERROR_PATCH_NO_SEQUENCE: ::DWORD = 1648; +pub const ERROR_PATCH_REMOVAL_DISALLOWED: ::DWORD = 1649; +pub const ERROR_INVALID_PATCH_XML: ::DWORD = 1650; +pub const ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT: ::DWORD = 1651; +pub const ERROR_INSTALL_SERVICE_SAFEBOOT: ::DWORD = 1652; +pub const ERROR_FAIL_FAST_EXCEPTION: ::DWORD = 1653; +pub const ERROR_INSTALL_REJECTED: ::DWORD = 1654; +pub const ERROR_DYNAMIC_CODE_BLOCKED: ::DWORD = 1655; +pub const RPC_S_INVALID_STRING_BINDING: ::DWORD = 1700; +pub const RPC_S_WRONG_KIND_OF_BINDING: ::DWORD = 1701; +pub const RPC_S_INVALID_BINDING: ::DWORD = 1702; +pub const RPC_S_PROTSEQ_NOT_SUPPORTED: ::DWORD = 1703; +pub const RPC_S_INVALID_RPC_PROTSEQ: ::DWORD = 1704; +pub const RPC_S_INVALID_STRING_UUID: ::DWORD = 1705; +pub const RPC_S_INVALID_ENDPOINT_FORMAT: ::DWORD = 1706; +pub const RPC_S_INVALID_NET_ADDR: ::DWORD = 1707; +pub const RPC_S_NO_ENDPOINT_FOUND: ::DWORD = 1708; +pub const RPC_S_INVALID_TIMEOUT: ::DWORD = 1709; +pub const RPC_S_OBJECT_NOT_FOUND: ::DWORD = 1710; +pub const RPC_S_ALREADY_REGISTERED: ::DWORD = 1711; +pub const RPC_S_TYPE_ALREADY_REGISTERED: ::DWORD = 1712; +pub const RPC_S_ALREADY_LISTENING: ::DWORD = 1713; +pub const RPC_S_NO_PROTSEQS_REGISTERED: ::DWORD = 1714; +pub const RPC_S_NOT_LISTENING: ::DWORD = 1715; +pub const RPC_S_UNKNOWN_MGR_TYPE: ::DWORD = 1716; +pub const RPC_S_UNKNOWN_IF: ::DWORD = 1717; +pub const RPC_S_NO_BINDINGS: ::DWORD = 1718; +pub const RPC_S_NO_PROTSEQS: ::DWORD = 1719; +pub const RPC_S_CANT_CREATE_ENDPOINT: ::DWORD = 1720; +pub const RPC_S_OUT_OF_RESOURCES: ::DWORD = 1721; +pub const RPC_S_SERVER_UNAVAILABLE: ::DWORD = 1722; +pub const RPC_S_SERVER_TOO_BUSY: ::DWORD = 1723; +pub const RPC_S_INVALID_NETWORK_OPTIONS: ::DWORD = 1724; +pub const RPC_S_NO_CALL_ACTIVE: ::DWORD = 1725; +pub const RPC_S_CALL_FAILED: ::DWORD = 1726; +pub const RPC_S_CALL_FAILED_DNE: ::DWORD = 1727; +pub const RPC_S_PROTOCOL_ERROR: ::DWORD = 1728; +pub const RPC_S_PROXY_ACCESS_DENIED: ::DWORD = 1729; +pub const RPC_S_UNSUPPORTED_TRANS_SYN: ::DWORD = 1730; +pub const RPC_S_UNSUPPORTED_TYPE: ::DWORD = 1732; +pub const RPC_S_INVALID_TAG: ::DWORD = 1733; +pub const RPC_S_INVALID_BOUND: ::DWORD = 1734; +pub const RPC_S_NO_ENTRY_NAME: ::DWORD = 1735; +pub const RPC_S_INVALID_NAME_SYNTAX: ::DWORD = 1736; +pub const RPC_S_UNSUPPORTED_NAME_SYNTAX: ::DWORD = 1737; +pub const RPC_S_UUID_NO_ADDRESS: ::DWORD = 1739; +pub const RPC_S_DUPLICATE_ENDPOINT: ::DWORD = 1740; +pub const RPC_S_UNKNOWN_AUTHN_TYPE: ::DWORD = 1741; +pub const RPC_S_MAX_CALLS_TOO_SMALL: ::DWORD = 1742; +pub const RPC_S_STRING_TOO_LONG: ::DWORD = 1743; +pub const RPC_S_PROTSEQ_NOT_FOUND: ::DWORD = 1744; +pub const RPC_S_PROCNUM_OUT_OF_RANGE: ::DWORD = 1745; +pub const RPC_S_BINDING_HAS_NO_AUTH: ::DWORD = 1746; +pub const RPC_S_UNKNOWN_AUTHN_SERVICE: ::DWORD = 1747; +pub const RPC_S_UNKNOWN_AUTHN_LEVEL: ::DWORD = 1748; +pub const RPC_S_INVALID_AUTH_IDENTITY: ::DWORD = 1749; +pub const RPC_S_UNKNOWN_AUTHZ_SERVICE: ::DWORD = 1750; +pub const EPT_S_INVALID_ENTRY: ::DWORD = 1751; +pub const EPT_S_CANT_PERFORM_OP: ::DWORD = 1752; +pub const EPT_S_NOT_REGISTERED: ::DWORD = 1753; +pub const RPC_S_NOTHING_TO_EXPORT: ::DWORD = 1754; +pub const RPC_S_INCOMPLETE_NAME: ::DWORD = 1755; +pub const RPC_S_INVALID_VERS_OPTION: ::DWORD = 1756; +pub const RPC_S_NO_MORE_MEMBERS: ::DWORD = 1757; +pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED: ::DWORD = 1758; +pub const RPC_S_INTERFACE_NOT_FOUND: ::DWORD = 1759; +pub const RPC_S_ENTRY_ALREADY_EXISTS: ::DWORD = 1760; +pub const RPC_S_ENTRY_NOT_FOUND: ::DWORD = 1761; +pub const RPC_S_NAME_SERVICE_UNAVAILABLE: ::DWORD = 1762; +pub const RPC_S_INVALID_NAF_ID: ::DWORD = 1763; +pub const RPC_S_CANNOT_SUPPORT: ::DWORD = 1764; +pub const RPC_S_NO_CONTEXT_AVAILABLE: ::DWORD = 1765; +pub const RPC_S_INTERNAL_ERROR: ::DWORD = 1766; +pub const RPC_S_ZERO_DIVIDE: ::DWORD = 1767; +pub const RPC_S_ADDRESS_ERROR: ::DWORD = 1768; +pub const RPC_S_FP_DIV_ZERO: ::DWORD = 1769; +pub const RPC_S_FP_UNDERFLOW: ::DWORD = 1770; +pub const RPC_S_FP_OVERFLOW: ::DWORD = 1771; +pub const RPC_X_NO_MORE_ENTRIES: ::DWORD = 1772; +pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL: ::DWORD = 1773; +pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE: ::DWORD = 1774; +pub const RPC_X_SS_IN_NULL_CONTEXT: ::DWORD = 1775; +pub const RPC_X_SS_CONTEXT_DAMAGED: ::DWORD = 1777; +pub const RPC_X_SS_HANDLES_MISMATCH: ::DWORD = 1778; +pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE: ::DWORD = 1779; +pub const RPC_X_NULL_REF_POINTER: ::DWORD = 1780; +pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE: ::DWORD = 1781; +pub const RPC_X_BYTE_COUNT_TOO_SMALL: ::DWORD = 1782; +pub const RPC_X_BAD_STUB_DATA: ::DWORD = 1783; +pub const ERROR_INVALID_USER_BUFFER: ::DWORD = 1784; +pub const ERROR_UNRECOGNIZED_MEDIA: ::DWORD = 1785; +pub const ERROR_NO_TRUST_LSA_SECRET: ::DWORD = 1786; +pub const ERROR_NO_TRUST_SAM_ACCOUNT: ::DWORD = 1787; +pub const ERROR_TRUSTED_DOMAIN_FAILURE: ::DWORD = 1788; +pub const ERROR_TRUSTED_RELATIONSHIP_FAILURE: ::DWORD = 1789; +pub const ERROR_TRUST_FAILURE: ::DWORD = 1790; +pub const RPC_S_CALL_IN_PROGRESS: ::DWORD = 1791; +pub const ERROR_NETLOGON_NOT_STARTED: ::DWORD = 1792; +pub const ERROR_ACCOUNT_EXPIRED: ::DWORD = 1793; +pub const ERROR_REDIRECTOR_HAS_OPEN_HANDLES: ::DWORD = 1794; +pub const ERROR_PRINTER_DRIVER_ALREADY_INSTALLED: ::DWORD = 1795; +pub const ERROR_UNKNOWN_PORT: ::DWORD = 1796; +pub const ERROR_UNKNOWN_PRINTER_DRIVER: ::DWORD = 1797; +pub const ERROR_UNKNOWN_PRINTPROCESSOR: ::DWORD = 1798; +pub const ERROR_INVALID_SEPARATOR_FILE: ::DWORD = 1799; +pub const ERROR_INVALID_PRIORITY: ::DWORD = 1800; +pub const ERROR_INVALID_PRINTER_NAME: ::DWORD = 1801; +pub const ERROR_PRINTER_ALREADY_EXISTS: ::DWORD = 1802; +pub const ERROR_INVALID_PRINTER_COMMAND: ::DWORD = 1803; +pub const ERROR_INVALID_DATATYPE: ::DWORD = 1804; +pub const ERROR_INVALID_ENVIRONMENT: ::DWORD = 1805; +pub const RPC_S_NO_MORE_BINDINGS: ::DWORD = 1806; +pub const ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: ::DWORD = 1807; +pub const ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT: ::DWORD = 1808; +pub const ERROR_NOLOGON_SERVER_TRUST_ACCOUNT: ::DWORD = 1809; +pub const ERROR_DOMAIN_TRUST_INCONSISTENT: ::DWORD = 1810; +pub const ERROR_SERVER_HAS_OPEN_HANDLES: ::DWORD = 1811; +pub const ERROR_RESOURCE_DATA_NOT_FOUND: ::DWORD = 1812; +pub const ERROR_RESOURCE_TYPE_NOT_FOUND: ::DWORD = 1813; +pub const ERROR_RESOURCE_NAME_NOT_FOUND: ::DWORD = 1814; +pub const ERROR_RESOURCE_LANG_NOT_FOUND: ::DWORD = 1815; +pub const ERROR_NOT_ENOUGH_QUOTA: ::DWORD = 1816; +pub const RPC_S_NO_INTERFACES: ::DWORD = 1817; +pub const RPC_S_CALL_CANCELLED: ::DWORD = 1818; +pub const RPC_S_BINDING_INCOMPLETE: ::DWORD = 1819; +pub const RPC_S_COMM_FAILURE: ::DWORD = 1820; +pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL: ::DWORD = 1821; +pub const RPC_S_NO_PRINC_NAME: ::DWORD = 1822; +pub const RPC_S_NOT_RPC_ERROR: ::DWORD = 1823; +pub const RPC_S_UUID_LOCAL_ONLY: ::DWORD = 1824; +pub const RPC_S_SEC_PKG_ERROR: ::DWORD = 1825; +pub const RPC_S_NOT_CANCELLED: ::DWORD = 1826; +pub const RPC_X_INVALID_ES_ACTION: ::DWORD = 1827; +pub const RPC_X_WRONG_ES_VERSION: ::DWORD = 1828; +pub const RPC_X_WRONG_STUB_VERSION: ::DWORD = 1829; +pub const RPC_X_INVALID_PIPE_OBJECT: ::DWORD = 1830; +pub const RPC_X_WRONG_PIPE_ORDER: ::DWORD = 1831; +pub const RPC_X_WRONG_PIPE_VERSION: ::DWORD = 1832; +pub const RPC_S_COOKIE_AUTH_FAILED: ::DWORD = 1833; +pub const RPC_S_GROUP_MEMBER_NOT_FOUND: ::DWORD = 1898; +pub const EPT_S_CANT_CREATE: ::DWORD = 1899; +pub const RPC_S_INVALID_OBJECT: ::DWORD = 1900; +pub const ERROR_INVALID_TIME: ::DWORD = 1901; +pub const ERROR_INVALID_FORM_NAME: ::DWORD = 1902; +pub const ERROR_INVALID_FORM_SIZE: ::DWORD = 1903; +pub const ERROR_ALREADY_WAITING: ::DWORD = 1904; +pub const ERROR_PRINTER_DELETED: ::DWORD = 1905; +pub const ERROR_INVALID_PRINTER_STATE: ::DWORD = 1906; +pub const ERROR_PASSWORD_MUST_CHANGE: ::DWORD = 1907; +pub const ERROR_DOMAIN_CONTROLLER_NOT_FOUND: ::DWORD = 1908; +pub const ERROR_ACCOUNT_LOCKED_OUT: ::DWORD = 1909; +pub const OR_INVALID_OXID: ::DWORD = 1910; +pub const OR_INVALID_OID: ::DWORD = 1911; +pub const OR_INVALID_SET: ::DWORD = 1912; +pub const RPC_S_SEND_INCOMPLETE: ::DWORD = 1913; +pub const RPC_S_INVALID_ASYNC_HANDLE: ::DWORD = 1914; +pub const RPC_S_INVALID_ASYNC_CALL: ::DWORD = 1915; +pub const RPC_X_PIPE_CLOSED: ::DWORD = 1916; +pub const RPC_X_PIPE_DISCIPLINE_ERROR: ::DWORD = 1917; +pub const RPC_X_PIPE_EMPTY: ::DWORD = 1918; +pub const ERROR_NO_SITENAME: ::DWORD = 1919; +pub const ERROR_CANT_ACCESS_FILE: ::DWORD = 1920; +pub const ERROR_CANT_RESOLVE_FILENAME: ::DWORD = 1921; +pub const RPC_S_ENTRY_TYPE_MISMATCH: ::DWORD = 1922; +pub const RPC_S_NOT_ALL_OBJS_EXPORTED: ::DWORD = 1923; +pub const RPC_S_INTERFACE_NOT_EXPORTED: ::DWORD = 1924; +pub const RPC_S_PROFILE_NOT_ADDED: ::DWORD = 1925; +pub const RPC_S_PRF_ELT_NOT_ADDED: ::DWORD = 1926; +pub const RPC_S_PRF_ELT_NOT_REMOVED: ::DWORD = 1927; +pub const RPC_S_GRP_ELT_NOT_ADDED: ::DWORD = 1928; +pub const RPC_S_GRP_ELT_NOT_REMOVED: ::DWORD = 1929; +pub const ERROR_KM_DRIVER_BLOCKED: ::DWORD = 1930; +pub const ERROR_CONTEXT_EXPIRED: ::DWORD = 1931; +pub const ERROR_PER_USER_TRUST_QUOTA_EXCEEDED: ::DWORD = 1932; +pub const ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED: ::DWORD = 1933; +pub const ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED: ::DWORD = 1934; +pub const ERROR_AUTHENTICATION_FIREWALL_FAILED: ::DWORD = 1935; +pub const ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED: ::DWORD = 1936; +pub const ERROR_NTLM_BLOCKED: ::DWORD = 1937; +pub const ERROR_PASSWORD_CHANGE_REQUIRED: ::DWORD = 1938; +pub const ERROR_INVALID_PIXEL_FORMAT: ::DWORD = 2000; +pub const ERROR_BAD_DRIVER: ::DWORD = 2001; +pub const ERROR_INVALID_WINDOW_STYLE: ::DWORD = 2002; +pub const ERROR_METAFILE_NOT_SUPPORTED: ::DWORD = 2003; +pub const ERROR_TRANSFORM_NOT_SUPPORTED: ::DWORD = 2004; +pub const ERROR_CLIPPING_NOT_SUPPORTED: ::DWORD = 2005; +pub const ERROR_INVALID_CMM: ::DWORD = 2010; +pub const ERROR_INVALID_PROFILE: ::DWORD = 2011; +pub const ERROR_TAG_NOT_FOUND: ::DWORD = 2012; +pub const ERROR_TAG_NOT_PRESENT: ::DWORD = 2013; +pub const ERROR_DUPLICATE_TAG: ::DWORD = 2014; +pub const ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE: ::DWORD = 2015; +pub const ERROR_PROFILE_NOT_FOUND: ::DWORD = 2016; +pub const ERROR_INVALID_COLORSPACE: ::DWORD = 2017; +pub const ERROR_ICM_NOT_ENABLED: ::DWORD = 2018; +pub const ERROR_DELETING_ICM_XFORM: ::DWORD = 2019; +pub const ERROR_INVALID_TRANSFORM: ::DWORD = 2020; +pub const ERROR_COLORSPACE_MISMATCH: ::DWORD = 2021; +pub const ERROR_INVALID_COLORINDEX: ::DWORD = 2022; +pub const ERROR_PROFILE_DOES_NOT_MATCH_DEVICE: ::DWORD = 2023; +pub const ERROR_CONNECTED_OTHER_PASSWORD: ::DWORD = 2108; +pub const ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT: ::DWORD = 2109; +pub const ERROR_BAD_USERNAME: ::DWORD = 2202; +pub const ERROR_NOT_CONNECTED: ::DWORD = 2250; +pub const ERROR_OPEN_FILES: ::DWORD = 2401; +pub const ERROR_ACTIVE_CONNECTIONS: ::DWORD = 2402; +pub const ERROR_DEVICE_IN_USE: ::DWORD = 2404; +pub const ERROR_UNKNOWN_PRINT_MONITOR: ::DWORD = 3000; +pub const ERROR_PRINTER_DRIVER_IN_USE: ::DWORD = 3001; +pub const ERROR_SPOOL_FILE_NOT_FOUND: ::DWORD = 3002; +pub const ERROR_SPL_NO_STARTDOC: ::DWORD = 3003; +pub const ERROR_SPL_NO_ADDJOB: ::DWORD = 3004; +pub const ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED: ::DWORD = 3005; +pub const ERROR_PRINT_MONITOR_ALREADY_INSTALLED: ::DWORD = 3006; +pub const ERROR_INVALID_PRINT_MONITOR: ::DWORD = 3007; +pub const ERROR_PRINT_MONITOR_IN_USE: ::DWORD = 3008; +pub const ERROR_PRINTER_HAS_JOBS_QUEUED: ::DWORD = 3009; +pub const ERROR_SUCCESS_REBOOT_REQUIRED: ::DWORD = 3010; +pub const ERROR_SUCCESS_RESTART_REQUIRED: ::DWORD = 3011; +pub const ERROR_PRINTER_NOT_FOUND: ::DWORD = 3012; +pub const ERROR_PRINTER_DRIVER_WARNED: ::DWORD = 3013; +pub const ERROR_PRINTER_DRIVER_BLOCKED: ::DWORD = 3014; +pub const ERROR_PRINTER_DRIVER_PACKAGE_IN_USE: ::DWORD = 3015; +pub const ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND: ::DWORD = 3016; +pub const ERROR_FAIL_REBOOT_REQUIRED: ::DWORD = 3017; +pub const ERROR_FAIL_REBOOT_INITIATED: ::DWORD = 3018; +pub const ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED: ::DWORD = 3019; +pub const ERROR_PRINT_JOB_RESTART_REQUIRED: ::DWORD = 3020; +pub const ERROR_INVALID_PRINTER_DRIVER_MANIFEST: ::DWORD = 3021; +pub const ERROR_PRINTER_NOT_SHAREABLE: ::DWORD = 3022; +pub const ERROR_REQUEST_PAUSED: ::DWORD = 3050; +pub const ERROR_IO_REISSUE_AS_CACHED: ::DWORD = 3950; +pub const ERROR_WINS_INTERNAL: ::DWORD = 4000; +pub const ERROR_CAN_NOT_DEL_LOCAL_WINS: ::DWORD = 4001; +pub const ERROR_STATIC_INIT: ::DWORD = 4002; +pub const ERROR_INC_BACKUP: ::DWORD = 4003; +pub const ERROR_FULL_BACKUP: ::DWORD = 4004; +pub const ERROR_REC_NON_EXISTENT: ::DWORD = 4005; +pub const ERROR_RPL_NOT_ALLOWED: ::DWORD = 4006; +pub const PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED: ::DWORD = 4050; +pub const PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO: ::DWORD = 4051; +pub const PEERDIST_ERROR_MISSING_DATA: ::DWORD = 4052; +pub const PEERDIST_ERROR_NO_MORE: ::DWORD = 4053; +pub const PEERDIST_ERROR_NOT_INITIALIZED: ::DWORD = 4054; +pub const PEERDIST_ERROR_ALREADY_INITIALIZED: ::DWORD = 4055; +pub const PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS: ::DWORD = 4056; +pub const PEERDIST_ERROR_INVALIDATED: ::DWORD = 4057; +pub const PEERDIST_ERROR_ALREADY_EXISTS: ::DWORD = 4058; +pub const PEERDIST_ERROR_OPERATION_NOTFOUND: ::DWORD = 4059; +pub const PEERDIST_ERROR_ALREADY_COMPLETED: ::DWORD = 4060; +pub const PEERDIST_ERROR_OUT_OF_BOUNDS: ::DWORD = 4061; +pub const PEERDIST_ERROR_VERSION_UNSUPPORTED: ::DWORD = 4062; +pub const PEERDIST_ERROR_INVALID_CONFIGURATION: ::DWORD = 4063; +pub const PEERDIST_ERROR_NOT_LICENSED: ::DWORD = 4064; +pub const PEERDIST_ERROR_SERVICE_UNAVAILABLE: ::DWORD = 4065; +pub const PEERDIST_ERROR_TRUST_FAILURE: ::DWORD = 4066; +pub const ERROR_DHCP_ADDRESS_CONFLICT: ::DWORD = 4100; +pub const ERROR_WMI_GUID_NOT_FOUND: ::DWORD = 4200; +pub const ERROR_WMI_INSTANCE_NOT_FOUND: ::DWORD = 4201; +pub const ERROR_WMI_ITEMID_NOT_FOUND: ::DWORD = 4202; +pub const ERROR_WMI_TRY_AGAIN: ::DWORD = 4203; +pub const ERROR_WMI_DP_NOT_FOUND: ::DWORD = 4204; +pub const ERROR_WMI_UNRESOLVED_INSTANCE_REF: ::DWORD = 4205; +pub const ERROR_WMI_ALREADY_ENABLED: ::DWORD = 4206; +pub const ERROR_WMI_GUID_DISCONNECTED: ::DWORD = 4207; +pub const ERROR_WMI_SERVER_UNAVAILABLE: ::DWORD = 4208; +pub const ERROR_WMI_DP_FAILED: ::DWORD = 4209; +pub const ERROR_WMI_INVALID_MOF: ::DWORD = 4210; +pub const ERROR_WMI_INVALID_REGINFO: ::DWORD = 4211; +pub const ERROR_WMI_ALREADY_DISABLED: ::DWORD = 4212; +pub const ERROR_WMI_READ_ONLY: ::DWORD = 4213; +pub const ERROR_WMI_SET_FAILURE: ::DWORD = 4214; +pub const ERROR_NOT_APPCONTAINER: ::DWORD = 4250; +pub const ERROR_APPCONTAINER_REQUIRED: ::DWORD = 4251; +pub const ERROR_NOT_SUPPORTED_IN_APPCONTAINER: ::DWORD = 4252; +pub const ERROR_INVALID_PACKAGE_SID_LENGTH: ::DWORD = 4253; +pub const ERROR_INVALID_MEDIA: ::DWORD = 4300; +pub const ERROR_INVALID_LIBRARY: ::DWORD = 4301; +pub const ERROR_INVALID_MEDIA_POOL: ::DWORD = 4302; +pub const ERROR_DRIVE_MEDIA_MISMATCH: ::DWORD = 4303; +pub const ERROR_MEDIA_OFFLINE: ::DWORD = 4304; +pub const ERROR_LIBRARY_OFFLINE: ::DWORD = 4305; +pub const ERROR_EMPTY: ::DWORD = 4306; +pub const ERROR_NOT_EMPTY: ::DWORD = 4307; +pub const ERROR_MEDIA_UNAVAILABLE: ::DWORD = 4308; +pub const ERROR_RESOURCE_DISABLED: ::DWORD = 4309; +pub const ERROR_INVALID_CLEANER: ::DWORD = 4310; +pub const ERROR_UNABLE_TO_CLEAN: ::DWORD = 4311; +pub const ERROR_OBJECT_NOT_FOUND: ::DWORD = 4312; +pub const ERROR_DATABASE_FAILURE: ::DWORD = 4313; +pub const ERROR_DATABASE_FULL: ::DWORD = 4314; +pub const ERROR_MEDIA_INCOMPATIBLE: ::DWORD = 4315; +pub const ERROR_RESOURCE_NOT_PRESENT: ::DWORD = 4316; +pub const ERROR_INVALID_OPERATION: ::DWORD = 4317; +pub const ERROR_MEDIA_NOT_AVAILABLE: ::DWORD = 4318; +pub const ERROR_DEVICE_NOT_AVAILABLE: ::DWORD = 4319; +pub const ERROR_REQUEST_REFUSED: ::DWORD = 4320; +pub const ERROR_INVALID_DRIVE_OBJECT: ::DWORD = 4321; +pub const ERROR_LIBRARY_FULL: ::DWORD = 4322; +pub const ERROR_MEDIUM_NOT_ACCESSIBLE: ::DWORD = 4323; +pub const ERROR_UNABLE_TO_LOAD_MEDIUM: ::DWORD = 4324; +pub const ERROR_UNABLE_TO_INVENTORY_DRIVE: ::DWORD = 4325; +pub const ERROR_UNABLE_TO_INVENTORY_SLOT: ::DWORD = 4326; +pub const ERROR_UNABLE_TO_INVENTORY_TRANSPORT: ::DWORD = 4327; +pub const ERROR_TRANSPORT_FULL: ::DWORD = 4328; +pub const ERROR_CONTROLLING_IEPORT: ::DWORD = 4329; +pub const ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA: ::DWORD = 4330; +pub const ERROR_CLEANER_SLOT_SET: ::DWORD = 4331; +pub const ERROR_CLEANER_SLOT_NOT_SET: ::DWORD = 4332; +pub const ERROR_CLEANER_CARTRIDGE_SPENT: ::DWORD = 4333; +pub const ERROR_UNEXPECTED_OMID: ::DWORD = 4334; +pub const ERROR_CANT_DELETE_LAST_ITEM: ::DWORD = 4335; +pub const ERROR_MESSAGE_EXCEEDS_MAX_SIZE: ::DWORD = 4336; +pub const ERROR_VOLUME_CONTAINS_SYS_FILES: ::DWORD = 4337; +pub const ERROR_INDIGENOUS_TYPE: ::DWORD = 4338; +pub const ERROR_NO_SUPPORTING_DRIVES: ::DWORD = 4339; +pub const ERROR_CLEANER_CARTRIDGE_INSTALLED: ::DWORD = 4340; +pub const ERROR_IEPORT_FULL: ::DWORD = 4341; +pub const ERROR_FILE_OFFLINE: ::DWORD = 4350; +pub const ERROR_REMOTE_STORAGE_NOT_ACTIVE: ::DWORD = 4351; +pub const ERROR_REMOTE_STORAGE_MEDIA_ERROR: ::DWORD = 4352; +pub const ERROR_NOT_A_REPARSE_POINT: ::DWORD = 4390; +pub const ERROR_REPARSE_ATTRIBUTE_CONFLICT: ::DWORD = 4391; +pub const ERROR_INVALID_REPARSE_DATA: ::DWORD = 4392; +pub const ERROR_REPARSE_TAG_INVALID: ::DWORD = 4393; +pub const ERROR_REPARSE_TAG_MISMATCH: ::DWORD = 4394; +pub const ERROR_APP_DATA_NOT_FOUND: ::DWORD = 4400; +pub const ERROR_APP_DATA_EXPIRED: ::DWORD = 4401; +pub const ERROR_APP_DATA_CORRUPT: ::DWORD = 4402; +pub const ERROR_APP_DATA_LIMIT_EXCEEDED: ::DWORD = 4403; +pub const ERROR_APP_DATA_REBOOT_REQUIRED: ::DWORD = 4404; +pub const ERROR_SECUREBOOT_ROLLBACK_DETECTED: ::DWORD = 4420; +pub const ERROR_SECUREBOOT_POLICY_VIOLATION: ::DWORD = 4421; +pub const ERROR_SECUREBOOT_INVALID_POLICY: ::DWORD = 4422; +pub const ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: ::DWORD = 4423; +pub const ERROR_SECUREBOOT_POLICY_NOT_SIGNED: ::DWORD = 4424; +pub const ERROR_SECUREBOOT_NOT_ENABLED: ::DWORD = 4425; +pub const ERROR_SECUREBOOT_FILE_REPLACED: ::DWORD = 4426; +pub const ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED: ::DWORD = 4440; +pub const ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: ::DWORD = 4441; +pub const ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED: ::DWORD = 4442; +pub const ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: ::DWORD = 4443; +pub const ERROR_VOLUME_NOT_SIS_ENABLED: ::DWORD = 4500; +pub const ERROR_DEPENDENT_RESOURCE_EXISTS: ::DWORD = 5001; +pub const ERROR_DEPENDENCY_NOT_FOUND: ::DWORD = 5002; +pub const ERROR_DEPENDENCY_ALREADY_EXISTS: ::DWORD = 5003; +pub const ERROR_RESOURCE_NOT_ONLINE: ::DWORD = 5004; +pub const ERROR_HOST_NODE_NOT_AVAILABLE: ::DWORD = 5005; +pub const ERROR_RESOURCE_NOT_AVAILABLE: ::DWORD = 5006; +pub const ERROR_RESOURCE_NOT_FOUND: ::DWORD = 5007; +pub const ERROR_SHUTDOWN_CLUSTER: ::DWORD = 5008; +pub const ERROR_CANT_EVICT_ACTIVE_NODE: ::DWORD = 5009; +pub const ERROR_OBJECT_ALREADY_EXISTS: ::DWORD = 5010; +pub const ERROR_OBJECT_IN_LIST: ::DWORD = 5011; +pub const ERROR_GROUP_NOT_AVAILABLE: ::DWORD = 5012; +pub const ERROR_GROUP_NOT_FOUND: ::DWORD = 5013; +pub const ERROR_GROUP_NOT_ONLINE: ::DWORD = 5014; +pub const ERROR_HOST_NODE_NOT_RESOURCE_OWNER: ::DWORD = 5015; +pub const ERROR_HOST_NODE_NOT_GROUP_OWNER: ::DWORD = 5016; +pub const ERROR_RESMON_CREATE_FAILED: ::DWORD = 5017; +pub const ERROR_RESMON_ONLINE_FAILED: ::DWORD = 5018; +pub const ERROR_RESOURCE_ONLINE: ::DWORD = 5019; +pub const ERROR_QUORUM_RESOURCE: ::DWORD = 5020; +pub const ERROR_NOT_QUORUM_CAPABLE: ::DWORD = 5021; +pub const ERROR_CLUSTER_SHUTTING_DOWN: ::DWORD = 5022; +pub const ERROR_INVALID_STATE: ::DWORD = 5023; +pub const ERROR_RESOURCE_PROPERTIES_STORED: ::DWORD = 5024; +pub const ERROR_NOT_QUORUM_CLASS: ::DWORD = 5025; +pub const ERROR_CORE_RESOURCE: ::DWORD = 5026; +pub const ERROR_QUORUM_RESOURCE_ONLINE_FAILED: ::DWORD = 5027; +pub const ERROR_QUORUMLOG_OPEN_FAILED: ::DWORD = 5028; +pub const ERROR_CLUSTERLOG_CORRUPT: ::DWORD = 5029; +pub const ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE: ::DWORD = 5030; +pub const ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE: ::DWORD = 5031; +pub const ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND: ::DWORD = 5032; +pub const ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE: ::DWORD = 5033; +pub const ERROR_QUORUM_OWNER_ALIVE: ::DWORD = 5034; +pub const ERROR_NETWORK_NOT_AVAILABLE: ::DWORD = 5035; +pub const ERROR_NODE_NOT_AVAILABLE: ::DWORD = 5036; +pub const ERROR_ALL_NODES_NOT_AVAILABLE: ::DWORD = 5037; +pub const ERROR_RESOURCE_FAILED: ::DWORD = 5038; +pub const ERROR_CLUSTER_INVALID_NODE: ::DWORD = 5039; +pub const ERROR_CLUSTER_NODE_EXISTS: ::DWORD = 5040; +pub const ERROR_CLUSTER_JOIN_IN_PROGRESS: ::DWORD = 5041; +pub const ERROR_CLUSTER_NODE_NOT_FOUND: ::DWORD = 5042; +pub const ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND: ::DWORD = 5043; +pub const ERROR_CLUSTER_NETWORK_EXISTS: ::DWORD = 5044; +pub const ERROR_CLUSTER_NETWORK_NOT_FOUND: ::DWORD = 5045; +pub const ERROR_CLUSTER_NETINTERFACE_EXISTS: ::DWORD = 5046; +pub const ERROR_CLUSTER_NETINTERFACE_NOT_FOUND: ::DWORD = 5047; +pub const ERROR_CLUSTER_INVALID_REQUEST: ::DWORD = 5048; +pub const ERROR_CLUSTER_INVALID_NETWORK_PROVIDER: ::DWORD = 5049; +pub const ERROR_CLUSTER_NODE_DOWN: ::DWORD = 5050; +pub const ERROR_CLUSTER_NODE_UNREACHABLE: ::DWORD = 5051; +pub const ERROR_CLUSTER_NODE_NOT_MEMBER: ::DWORD = 5052; +pub const ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS: ::DWORD = 5053; +pub const ERROR_CLUSTER_INVALID_NETWORK: ::DWORD = 5054; +pub const ERROR_CLUSTER_NODE_UP: ::DWORD = 5056; +pub const ERROR_CLUSTER_IPADDR_IN_USE: ::DWORD = 5057; +pub const ERROR_CLUSTER_NODE_NOT_PAUSED: ::DWORD = 5058; +pub const ERROR_CLUSTER_NO_SECURITY_CONTEXT: ::DWORD = 5059; +pub const ERROR_CLUSTER_NETWORK_NOT_INTERNAL: ::DWORD = 5060; +pub const ERROR_CLUSTER_NODE_ALREADY_UP: ::DWORD = 5061; +pub const ERROR_CLUSTER_NODE_ALREADY_DOWN: ::DWORD = 5062; +pub const ERROR_CLUSTER_NETWORK_ALREADY_ONLINE: ::DWORD = 5063; +pub const ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE: ::DWORD = 5064; +pub const ERROR_CLUSTER_NODE_ALREADY_MEMBER: ::DWORD = 5065; +pub const ERROR_CLUSTER_LAST_INTERNAL_NETWORK: ::DWORD = 5066; +pub const ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS: ::DWORD = 5067; +pub const ERROR_INVALID_OPERATION_ON_QUORUM: ::DWORD = 5068; +pub const ERROR_DEPENDENCY_NOT_ALLOWED: ::DWORD = 5069; +pub const ERROR_CLUSTER_NODE_PAUSED: ::DWORD = 5070; +pub const ERROR_NODE_CANT_HOST_RESOURCE: ::DWORD = 5071; +pub const ERROR_CLUSTER_NODE_NOT_READY: ::DWORD = 5072; +pub const ERROR_CLUSTER_NODE_SHUTTING_DOWN: ::DWORD = 5073; +pub const ERROR_CLUSTER_JOIN_ABORTED: ::DWORD = 5074; +pub const ERROR_CLUSTER_INCOMPATIBLE_VERSIONS: ::DWORD = 5075; +pub const ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED: ::DWORD = 5076; +pub const ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED: ::DWORD = 5077; +pub const ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND: ::DWORD = 5078; +pub const ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED: ::DWORD = 5079; +pub const ERROR_CLUSTER_RESNAME_NOT_FOUND: ::DWORD = 5080; +pub const ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED: ::DWORD = 5081; +pub const ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST: ::DWORD = 5082; +pub const ERROR_CLUSTER_DATABASE_SEQMISMATCH: ::DWORD = 5083; +pub const ERROR_RESMON_INVALID_STATE: ::DWORD = 5084; +pub const ERROR_CLUSTER_GUM_NOT_LOCKER: ::DWORD = 5085; +pub const ERROR_QUORUM_DISK_NOT_FOUND: ::DWORD = 5086; +pub const ERROR_DATABASE_BACKUP_CORRUPT: ::DWORD = 5087; +pub const ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT: ::DWORD = 5088; +pub const ERROR_RESOURCE_PROPERTY_UNCHANGEABLE: ::DWORD = 5089; +pub const ERROR_NO_ADMIN_ACCESS_POINT: ::DWORD = 5090; +pub const ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE: ::DWORD = 5890; +pub const ERROR_CLUSTER_QUORUMLOG_NOT_FOUND: ::DWORD = 5891; +pub const ERROR_CLUSTER_MEMBERSHIP_HALT: ::DWORD = 5892; +pub const ERROR_CLUSTER_INSTANCE_ID_MISMATCH: ::DWORD = 5893; +pub const ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP: ::DWORD = 5894; +pub const ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH: ::DWORD = 5895; +pub const ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP: ::DWORD = 5896; +pub const ERROR_CLUSTER_PARAMETER_MISMATCH: ::DWORD = 5897; +pub const ERROR_NODE_CANNOT_BE_CLUSTERED: ::DWORD = 5898; +pub const ERROR_CLUSTER_WRONG_OS_VERSION: ::DWORD = 5899; +pub const ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME: ::DWORD = 5900; +pub const ERROR_CLUSCFG_ALREADY_COMMITTED: ::DWORD = 5901; +pub const ERROR_CLUSCFG_ROLLBACK_FAILED: ::DWORD = 5902; +pub const ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT: ::DWORD = 5903; +pub const ERROR_CLUSTER_OLD_VERSION: ::DWORD = 5904; +pub const ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME: ::DWORD = 5905; +pub const ERROR_CLUSTER_NO_NET_ADAPTERS: ::DWORD = 5906; +pub const ERROR_CLUSTER_POISONED: ::DWORD = 5907; +pub const ERROR_CLUSTER_GROUP_MOVING: ::DWORD = 5908; +pub const ERROR_CLUSTER_RESOURCE_TYPE_BUSY: ::DWORD = 5909; +pub const ERROR_RESOURCE_CALL_TIMED_OUT: ::DWORD = 5910; +pub const ERROR_INVALID_CLUSTER_IPV6_ADDRESS: ::DWORD = 5911; +pub const ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION: ::DWORD = 5912; +pub const ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS: ::DWORD = 5913; +pub const ERROR_CLUSTER_PARTIAL_SEND: ::DWORD = 5914; +pub const ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION: ::DWORD = 5915; +pub const ERROR_CLUSTER_INVALID_STRING_TERMINATION: ::DWORD = 5916; +pub const ERROR_CLUSTER_INVALID_STRING_FORMAT: ::DWORD = 5917; +pub const ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS: ::DWORD = 5918; +pub const ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS: ::DWORD = 5919; +pub const ERROR_CLUSTER_NULL_DATA: ::DWORD = 5920; +pub const ERROR_CLUSTER_PARTIAL_READ: ::DWORD = 5921; +pub const ERROR_CLUSTER_PARTIAL_WRITE: ::DWORD = 5922; +pub const ERROR_CLUSTER_CANT_DESERIALIZE_DATA: ::DWORD = 5923; +pub const ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT: ::DWORD = 5924; +pub const ERROR_CLUSTER_NO_QUORUM: ::DWORD = 5925; +pub const ERROR_CLUSTER_INVALID_IPV6_NETWORK: ::DWORD = 5926; +pub const ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK: ::DWORD = 5927; +pub const ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP: ::DWORD = 5928; +pub const ERROR_DEPENDENCY_TREE_TOO_COMPLEX: ::DWORD = 5929; +pub const ERROR_EXCEPTION_IN_RESOURCE_CALL: ::DWORD = 5930; +pub const ERROR_CLUSTER_RHS_FAILED_INITIALIZATION: ::DWORD = 5931; +pub const ERROR_CLUSTER_NOT_INSTALLED: ::DWORD = 5932; +pub const ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE: ::DWORD = 5933; +pub const ERROR_CLUSTER_MAX_NODES_IN_CLUSTER: ::DWORD = 5934; +pub const ERROR_CLUSTER_TOO_MANY_NODES: ::DWORD = 5935; +pub const ERROR_CLUSTER_OBJECT_ALREADY_USED: ::DWORD = 5936; +pub const ERROR_NONCORE_GROUPS_FOUND: ::DWORD = 5937; +pub const ERROR_FILE_SHARE_RESOURCE_CONFLICT: ::DWORD = 5938; +pub const ERROR_CLUSTER_EVICT_INVALID_REQUEST: ::DWORD = 5939; +pub const ERROR_CLUSTER_SINGLETON_RESOURCE: ::DWORD = 5940; +pub const ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE: ::DWORD = 5941; +pub const ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED: ::DWORD = 5942; +pub const ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR: ::DWORD = 5943; +pub const ERROR_CLUSTER_GROUP_BUSY: ::DWORD = 5944; +pub const ERROR_CLUSTER_NOT_SHARED_VOLUME: ::DWORD = 5945; +pub const ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR: ::DWORD = 5946; +pub const ERROR_CLUSTER_SHARED_VOLUMES_IN_USE: ::DWORD = 5947; +pub const ERROR_CLUSTER_USE_SHARED_VOLUMES_API: ::DWORD = 5948; +pub const ERROR_CLUSTER_BACKUP_IN_PROGRESS: ::DWORD = 5949; +pub const ERROR_NON_CSV_PATH: ::DWORD = 5950; +pub const ERROR_CSV_VOLUME_NOT_LOCAL: ::DWORD = 5951; +pub const ERROR_CLUSTER_WATCHDOG_TERMINATING: ::DWORD = 5952; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES: ::DWORD = 5953; +pub const ERROR_CLUSTER_INVALID_NODE_WEIGHT: ::DWORD = 5954; +pub const ERROR_CLUSTER_RESOURCE_VETOED_CALL: ::DWORD = 5955; +pub const ERROR_RESMON_SYSTEM_RESOURCES_LACKING: ::DWORD = 5956; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION: ::DWORD = 5957; +pub const ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE: ::DWORD = 5958; +pub const ERROR_CLUSTER_GROUP_QUEUED: ::DWORD = 5959; +pub const ERROR_CLUSTER_RESOURCE_LOCKED_STATUS: ::DWORD = 5960; +pub const ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED: ::DWORD = 5961; +pub const ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS: ::DWORD = 5962; +pub const ERROR_CLUSTER_DISK_NOT_CONNECTED: ::DWORD = 5963; +pub const ERROR_DISK_NOT_CSV_CAPABLE: ::DWORD = 5964; +pub const ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE: ::DWORD = 5965; +pub const ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED: ::DWORD = 5966; +pub const ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED: ::DWORD = 5967; +pub const ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES: ::DWORD = 5968; +pub const ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES: ::DWORD = 5969; +pub const ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE: ::DWORD = 5970; +pub const ERROR_CLUSTER_AFFINITY_CONFLICT: ::DWORD = 5971; +pub const ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE: ::DWORD = 5972; +pub const ERROR_ENCRYPTION_FAILED: ::DWORD = 6000; +pub const ERROR_DECRYPTION_FAILED: ::DWORD = 6001; +pub const ERROR_FILE_ENCRYPTED: ::DWORD = 6002; +pub const ERROR_NO_RECOVERY_POLICY: ::DWORD = 6003; +pub const ERROR_NO_EFS: ::DWORD = 6004; +pub const ERROR_WRONG_EFS: ::DWORD = 6005; +pub const ERROR_NO_USER_KEYS: ::DWORD = 6006; +pub const ERROR_FILE_NOT_ENCRYPTED: ::DWORD = 6007; +pub const ERROR_NOT_EXPORT_FORMAT: ::DWORD = 6008; +pub const ERROR_FILE_READ_ONLY: ::DWORD = 6009; +pub const ERROR_DIR_EFS_DISALLOWED: ::DWORD = 6010; +pub const ERROR_EFS_SERVER_NOT_TRUSTED: ::DWORD = 6011; +pub const ERROR_BAD_RECOVERY_POLICY: ::DWORD = 6012; +pub const ERROR_EFS_ALG_BLOB_TOO_BIG: ::DWORD = 6013; +pub const ERROR_VOLUME_NOT_SUPPORT_EFS: ::DWORD = 6014; +pub const ERROR_EFS_DISABLED: ::DWORD = 6015; +pub const ERROR_EFS_VERSION_NOT_SUPPORT: ::DWORD = 6016; +pub const ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: ::DWORD = 6017; +pub const ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER: ::DWORD = 6018; +pub const ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: ::DWORD = 6019; +pub const ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: ::DWORD = 6020; +pub const ERROR_CS_ENCRYPTION_FILE_NOT_CSE: ::DWORD = 6021; +pub const ERROR_ENCRYPTION_POLICY_DENIES_OPERATION: ::DWORD = 6022; +pub const ERROR_NO_BROWSER_SERVERS_FOUND: ::DWORD = 6118; +pub const SCHED_E_SERVICE_NOT_LOCALSYSTEM: ::DWORD = 6200; +pub const ERROR_LOG_SECTOR_INVALID: ::DWORD = 6600; +pub const ERROR_LOG_SECTOR_PARITY_INVALID: ::DWORD = 6601; +pub const ERROR_LOG_SECTOR_REMAPPED: ::DWORD = 6602; +pub const ERROR_LOG_BLOCK_INCOMPLETE: ::DWORD = 6603; +pub const ERROR_LOG_INVALID_RANGE: ::DWORD = 6604; +pub const ERROR_LOG_BLOCKS_EXHAUSTED: ::DWORD = 6605; +pub const ERROR_LOG_READ_CONTEXT_INVALID: ::DWORD = 6606; +pub const ERROR_LOG_RESTART_INVALID: ::DWORD = 6607; +pub const ERROR_LOG_BLOCK_VERSION: ::DWORD = 6608; +pub const ERROR_LOG_BLOCK_INVALID: ::DWORD = 6609; +pub const ERROR_LOG_READ_MODE_INVALID: ::DWORD = 6610; +pub const ERROR_LOG_NO_RESTART: ::DWORD = 6611; +pub const ERROR_LOG_METADATA_CORRUPT: ::DWORD = 6612; +pub const ERROR_LOG_METADATA_INVALID: ::DWORD = 6613; +pub const ERROR_LOG_METADATA_INCONSISTENT: ::DWORD = 6614; +pub const ERROR_LOG_RESERVATION_INVALID: ::DWORD = 6615; +pub const ERROR_LOG_CANT_DELETE: ::DWORD = 6616; +pub const ERROR_LOG_CONTAINER_LIMIT_EXCEEDED: ::DWORD = 6617; +pub const ERROR_LOG_START_OF_LOG: ::DWORD = 6618; +pub const ERROR_LOG_POLICY_ALREADY_INSTALLED: ::DWORD = 6619; +pub const ERROR_LOG_POLICY_NOT_INSTALLED: ::DWORD = 6620; +pub const ERROR_LOG_POLICY_INVALID: ::DWORD = 6621; +pub const ERROR_LOG_POLICY_CONFLICT: ::DWORD = 6622; +pub const ERROR_LOG_PINNED_ARCHIVE_TAIL: ::DWORD = 6623; +pub const ERROR_LOG_RECORD_NONEXISTENT: ::DWORD = 6624; +pub const ERROR_LOG_RECORDS_RESERVED_INVALID: ::DWORD = 6625; +pub const ERROR_LOG_SPACE_RESERVED_INVALID: ::DWORD = 6626; +pub const ERROR_LOG_TAIL_INVALID: ::DWORD = 6627; +pub const ERROR_LOG_FULL: ::DWORD = 6628; +pub const ERROR_COULD_NOT_RESIZE_LOG: ::DWORD = 6629; +pub const ERROR_LOG_MULTIPLEXED: ::DWORD = 6630; +pub const ERROR_LOG_DEDICATED: ::DWORD = 6631; +pub const ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS: ::DWORD = 6632; +pub const ERROR_LOG_ARCHIVE_IN_PROGRESS: ::DWORD = 6633; +pub const ERROR_LOG_EPHEMERAL: ::DWORD = 6634; +pub const ERROR_LOG_NOT_ENOUGH_CONTAINERS: ::DWORD = 6635; +pub const ERROR_LOG_CLIENT_ALREADY_REGISTERED: ::DWORD = 6636; +pub const ERROR_LOG_CLIENT_NOT_REGISTERED: ::DWORD = 6637; +pub const ERROR_LOG_FULL_HANDLER_IN_PROGRESS: ::DWORD = 6638; +pub const ERROR_LOG_CONTAINER_READ_FAILED: ::DWORD = 6639; +pub const ERROR_LOG_CONTAINER_WRITE_FAILED: ::DWORD = 6640; +pub const ERROR_LOG_CONTAINER_OPEN_FAILED: ::DWORD = 6641; +pub const ERROR_LOG_CONTAINER_STATE_INVALID: ::DWORD = 6642; +pub const ERROR_LOG_STATE_INVALID: ::DWORD = 6643; +pub const ERROR_LOG_PINNED: ::DWORD = 6644; +pub const ERROR_LOG_METADATA_FLUSH_FAILED: ::DWORD = 6645; +pub const ERROR_LOG_INCONSISTENT_SECURITY: ::DWORD = 6646; +pub const ERROR_LOG_APPENDED_FLUSH_FAILED: ::DWORD = 6647; +pub const ERROR_LOG_PINNED_RESERVATION: ::DWORD = 6648; +pub const ERROR_INVALID_TRANSACTION: ::DWORD = 6700; +pub const ERROR_TRANSACTION_NOT_ACTIVE: ::DWORD = 6701; +pub const ERROR_TRANSACTION_REQUEST_NOT_VALID: ::DWORD = 6702; +pub const ERROR_TRANSACTION_NOT_REQUESTED: ::DWORD = 6703; +pub const ERROR_TRANSACTION_ALREADY_ABORTED: ::DWORD = 6704; +pub const ERROR_TRANSACTION_ALREADY_COMMITTED: ::DWORD = 6705; +pub const ERROR_TM_INITIALIZATION_FAILED: ::DWORD = 6706; +pub const ERROR_RESOURCEMANAGER_READ_ONLY: ::DWORD = 6707; +pub const ERROR_TRANSACTION_NOT_JOINED: ::DWORD = 6708; +pub const ERROR_TRANSACTION_SUPERIOR_EXISTS: ::DWORD = 6709; +pub const ERROR_CRM_PROTOCOL_ALREADY_EXISTS: ::DWORD = 6710; +pub const ERROR_TRANSACTION_PROPAGATION_FAILED: ::DWORD = 6711; +pub const ERROR_CRM_PROTOCOL_NOT_FOUND: ::DWORD = 6712; +pub const ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER: ::DWORD = 6713; +pub const ERROR_CURRENT_TRANSACTION_NOT_VALID: ::DWORD = 6714; +pub const ERROR_TRANSACTION_NOT_FOUND: ::DWORD = 6715; +pub const ERROR_RESOURCEMANAGER_NOT_FOUND: ::DWORD = 6716; +pub const ERROR_ENLISTMENT_NOT_FOUND: ::DWORD = 6717; +pub const ERROR_TRANSACTIONMANAGER_NOT_FOUND: ::DWORD = 6718; +pub const ERROR_TRANSACTIONMANAGER_NOT_ONLINE: ::DWORD = 6719; +pub const ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: ::DWORD = 6720; +pub const ERROR_TRANSACTION_NOT_ROOT: ::DWORD = 6721; +pub const ERROR_TRANSACTION_OBJECT_EXPIRED: ::DWORD = 6722; +pub const ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED: ::DWORD = 6723; +pub const ERROR_TRANSACTION_RECORD_TOO_LONG: ::DWORD = 6724; +pub const ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED: ::DWORD = 6725; +pub const ERROR_TRANSACTION_INTEGRITY_VIOLATED: ::DWORD = 6726; +pub const ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH: ::DWORD = 6727; +pub const ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: ::DWORD = 6728; +pub const ERROR_TRANSACTION_MUST_WRITETHROUGH: ::DWORD = 6729; +pub const ERROR_TRANSACTION_NO_SUPERIOR: ::DWORD = 6730; +pub const ERROR_HEURISTIC_DAMAGE_POSSIBLE: ::DWORD = 6731; +pub const ERROR_TRANSACTIONAL_CONFLICT: ::DWORD = 6800; +pub const ERROR_RM_NOT_ACTIVE: ::DWORD = 6801; +pub const ERROR_RM_METADATA_CORRUPT: ::DWORD = 6802; +pub const ERROR_DIRECTORY_NOT_RM: ::DWORD = 6803; +pub const ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE: ::DWORD = 6805; +pub const ERROR_LOG_RESIZE_INVALID_SIZE: ::DWORD = 6806; +pub const ERROR_OBJECT_NO_LONGER_EXISTS: ::DWORD = 6807; +pub const ERROR_STREAM_MINIVERSION_NOT_FOUND: ::DWORD = 6808; +pub const ERROR_STREAM_MINIVERSION_NOT_VALID: ::DWORD = 6809; +pub const ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: ::DWORD = 6810; +pub const ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: ::DWORD = 6811; +pub const ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS: ::DWORD = 6812; +pub const ERROR_REMOTE_FILE_VERSION_MISMATCH: ::DWORD = 6814; +pub const ERROR_HANDLE_NO_LONGER_VALID: ::DWORD = 6815; +pub const ERROR_NO_TXF_METADATA: ::DWORD = 6816; +pub const ERROR_LOG_CORRUPTION_DETECTED: ::DWORD = 6817; +pub const ERROR_CANT_RECOVER_WITH_HANDLE_OPEN: ::DWORD = 6818; +pub const ERROR_RM_DISCONNECTED: ::DWORD = 6819; +pub const ERROR_ENLISTMENT_NOT_SUPERIOR: ::DWORD = 6820; +pub const ERROR_RECOVERY_NOT_NEEDED: ::DWORD = 6821; +pub const ERROR_RM_ALREADY_STARTED: ::DWORD = 6822; +pub const ERROR_FILE_IDENTITY_NOT_PERSISTENT: ::DWORD = 6823; +pub const ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: ::DWORD = 6824; +pub const ERROR_CANT_CROSS_RM_BOUNDARY: ::DWORD = 6825; +pub const ERROR_TXF_DIR_NOT_EMPTY: ::DWORD = 6826; +pub const ERROR_INDOUBT_TRANSACTIONS_EXIST: ::DWORD = 6827; +pub const ERROR_TM_VOLATILE: ::DWORD = 6828; +pub const ERROR_ROLLBACK_TIMER_EXPIRED: ::DWORD = 6829; +pub const ERROR_TXF_ATTRIBUTE_CORRUPT: ::DWORD = 6830; +pub const ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6831; +pub const ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED: ::DWORD = 6832; +pub const ERROR_LOG_GROWTH_FAILED: ::DWORD = 6833; +pub const ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: ::DWORD = 6834; +pub const ERROR_TXF_METADATA_ALREADY_PRESENT: ::DWORD = 6835; +pub const ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: ::DWORD = 6836; +pub const ERROR_TRANSACTION_REQUIRED_PROMOTION: ::DWORD = 6837; +pub const ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION: ::DWORD = 6838; +pub const ERROR_TRANSACTIONS_NOT_FROZEN: ::DWORD = 6839; +pub const ERROR_TRANSACTION_FREEZE_IN_PROGRESS: ::DWORD = 6840; +pub const ERROR_NOT_SNAPSHOT_VOLUME: ::DWORD = 6841; +pub const ERROR_NO_SAVEPOINT_WITH_OPEN_FILES: ::DWORD = 6842; +pub const ERROR_DATA_LOST_REPAIR: ::DWORD = 6843; +pub const ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6844; +pub const ERROR_TM_IDENTITY_MISMATCH: ::DWORD = 6845; +pub const ERROR_FLOATED_SECTION: ::DWORD = 6846; +pub const ERROR_CANNOT_ACCEPT_TRANSACTED_WORK: ::DWORD = 6847; +pub const ERROR_CANNOT_ABORT_TRANSACTIONS: ::DWORD = 6848; +pub const ERROR_BAD_CLUSTERS: ::DWORD = 6849; +pub const ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: ::DWORD = 6850; +pub const ERROR_VOLUME_DIRTY: ::DWORD = 6851; +pub const ERROR_NO_LINK_TRACKING_IN_TRANSACTION: ::DWORD = 6852; +pub const ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: ::DWORD = 6853; +pub const ERROR_EXPIRED_HANDLE: ::DWORD = 6854; +pub const ERROR_TRANSACTION_NOT_ENLISTED: ::DWORD = 6855; +pub const ERROR_CTX_WINSTATION_NAME_INVALID: ::DWORD = 7001; +pub const ERROR_CTX_INVALID_PD: ::DWORD = 7002; +pub const ERROR_CTX_PD_NOT_FOUND: ::DWORD = 7003; +pub const ERROR_CTX_WD_NOT_FOUND: ::DWORD = 7004; +pub const ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY: ::DWORD = 7005; +pub const ERROR_CTX_SERVICE_NAME_COLLISION: ::DWORD = 7006; +pub const ERROR_CTX_CLOSE_PENDING: ::DWORD = 7007; +pub const ERROR_CTX_NO_OUTBUF: ::DWORD = 7008; +pub const ERROR_CTX_MODEM_INF_NOT_FOUND: ::DWORD = 7009; +pub const ERROR_CTX_INVALID_MODEMNAME: ::DWORD = 7010; +pub const ERROR_CTX_MODEM_RESPONSE_ERROR: ::DWORD = 7011; +pub const ERROR_CTX_MODEM_RESPONSE_TIMEOUT: ::DWORD = 7012; +pub const ERROR_CTX_MODEM_RESPONSE_NO_CARRIER: ::DWORD = 7013; +pub const ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE: ::DWORD = 7014; +pub const ERROR_CTX_MODEM_RESPONSE_BUSY: ::DWORD = 7015; +pub const ERROR_CTX_MODEM_RESPONSE_VOICE: ::DWORD = 7016; +pub const ERROR_CTX_TD_ERROR: ::DWORD = 7017; +pub const ERROR_CTX_WINSTATION_NOT_FOUND: ::DWORD = 7022; +pub const ERROR_CTX_WINSTATION_ALREADY_EXISTS: ::DWORD = 7023; +pub const ERROR_CTX_WINSTATION_BUSY: ::DWORD = 7024; +pub const ERROR_CTX_BAD_VIDEO_MODE: ::DWORD = 7025; +pub const ERROR_CTX_GRAPHICS_INVALID: ::DWORD = 7035; +pub const ERROR_CTX_LOGON_DISABLED: ::DWORD = 7037; +pub const ERROR_CTX_NOT_CONSOLE: ::DWORD = 7038; +pub const ERROR_CTX_CLIENT_QUERY_TIMEOUT: ::DWORD = 7040; +pub const ERROR_CTX_CONSOLE_DISCONNECT: ::DWORD = 7041; +pub const ERROR_CTX_CONSOLE_CONNECT: ::DWORD = 7042; +pub const ERROR_CTX_SHADOW_DENIED: ::DWORD = 7044; +pub const ERROR_CTX_WINSTATION_ACCESS_DENIED: ::DWORD = 7045; +pub const ERROR_CTX_INVALID_WD: ::DWORD = 7049; +pub const ERROR_CTX_SHADOW_INVALID: ::DWORD = 7050; +pub const ERROR_CTX_SHADOW_DISABLED: ::DWORD = 7051; +pub const ERROR_CTX_CLIENT_LICENSE_IN_USE: ::DWORD = 7052; +pub const ERROR_CTX_CLIENT_LICENSE_NOT_SET: ::DWORD = 7053; +pub const ERROR_CTX_LICENSE_NOT_AVAILABLE: ::DWORD = 7054; +pub const ERROR_CTX_LICENSE_CLIENT_INVALID: ::DWORD = 7055; +pub const ERROR_CTX_LICENSE_EXPIRED: ::DWORD = 7056; +pub const ERROR_CTX_SHADOW_NOT_RUNNING: ::DWORD = 7057; +pub const ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE: ::DWORD = 7058; +pub const ERROR_ACTIVATION_COUNT_EXCEEDED: ::DWORD = 7059; +pub const ERROR_CTX_WINSTATIONS_DISABLED: ::DWORD = 7060; +pub const ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED: ::DWORD = 7061; +pub const ERROR_CTX_SESSION_IN_USE: ::DWORD = 7062; +pub const ERROR_CTX_NO_FORCE_LOGOFF: ::DWORD = 7063; +pub const ERROR_CTX_ACCOUNT_RESTRICTION: ::DWORD = 7064; +pub const ERROR_RDP_PROTOCOL_ERROR: ::DWORD = 7065; +pub const ERROR_CTX_CDM_CONNECT: ::DWORD = 7066; +pub const ERROR_CTX_CDM_DISCONNECT: ::DWORD = 7067; +pub const ERROR_CTX_SECURITY_LAYER_ERROR: ::DWORD = 7068; +pub const ERROR_TS_INCOMPATIBLE_SESSIONS: ::DWORD = 7069; +pub const ERROR_TS_VIDEO_SUBSYSTEM_ERROR: ::DWORD = 7070; +pub const FRS_ERR_INVALID_API_SEQUENCE: ::DWORD = 8001; +pub const FRS_ERR_STARTING_SERVICE: ::DWORD = 8002; +pub const FRS_ERR_STOPPING_SERVICE: ::DWORD = 8003; +pub const FRS_ERR_INTERNAL_API: ::DWORD = 8004; +pub const FRS_ERR_INTERNAL: ::DWORD = 8005; +pub const FRS_ERR_SERVICE_COMM: ::DWORD = 8006; +pub const FRS_ERR_INSUFFICIENT_PRIV: ::DWORD = 8007; +pub const FRS_ERR_AUTHENTICATION: ::DWORD = 8008; +pub const FRS_ERR_PARENT_INSUFFICIENT_PRIV: ::DWORD = 8009; +pub const FRS_ERR_PARENT_AUTHENTICATION: ::DWORD = 8010; +pub const FRS_ERR_CHILD_TO_PARENT_COMM: ::DWORD = 8011; +pub const FRS_ERR_PARENT_TO_CHILD_COMM: ::DWORD = 8012; +pub const FRS_ERR_SYSVOL_POPULATE: ::DWORD = 8013; +pub const FRS_ERR_SYSVOL_POPULATE_TIMEOUT: ::DWORD = 8014; +pub const FRS_ERR_SYSVOL_IS_BUSY: ::DWORD = 8015; +pub const FRS_ERR_SYSVOL_DEMOTE: ::DWORD = 8016; +pub const FRS_ERR_INVALID_SERVICE_PARAMETER: ::DWORD = 8017; +pub const DS_S_SUCCESS: ::DWORD = NO_ERROR; +pub const ERROR_DS_NOT_INSTALLED: ::DWORD = 8200; +pub const ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY: ::DWORD = 8201; +pub const ERROR_DS_NO_ATTRIBUTE_OR_VALUE: ::DWORD = 8202; +pub const ERROR_DS_INVALID_ATTRIBUTE_SYNTAX: ::DWORD = 8203; +pub const ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED: ::DWORD = 8204; +pub const ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS: ::DWORD = 8205; +pub const ERROR_DS_BUSY: ::DWORD = 8206; +pub const ERROR_DS_UNAVAILABLE: ::DWORD = 8207; +pub const ERROR_DS_NO_RIDS_ALLOCATED: ::DWORD = 8208; +pub const ERROR_DS_NO_MORE_RIDS: ::DWORD = 8209; +pub const ERROR_DS_INCORRECT_ROLE_OWNER: ::DWORD = 8210; +pub const ERROR_DS_RIDMGR_INIT_ERROR: ::DWORD = 8211; +pub const ERROR_DS_OBJ_CLASS_VIOLATION: ::DWORD = 8212; +pub const ERROR_DS_CANT_ON_NON_LEAF: ::DWORD = 8213; +pub const ERROR_DS_CANT_ON_RDN: ::DWORD = 8214; +pub const ERROR_DS_CANT_MOD_OBJ_CLASS: ::DWORD = 8215; +pub const ERROR_DS_CROSS_DOM_MOVE_ERROR: ::DWORD = 8216; +pub const ERROR_DS_GC_NOT_AVAILABLE: ::DWORD = 8217; +pub const ERROR_SHARED_POLICY: ::DWORD = 8218; +pub const ERROR_POLICY_OBJECT_NOT_FOUND: ::DWORD = 8219; +pub const ERROR_POLICY_ONLY_IN_DS: ::DWORD = 8220; +pub const ERROR_PROMOTION_ACTIVE: ::DWORD = 8221; +pub const ERROR_NO_PROMOTION_ACTIVE: ::DWORD = 8222; +pub const ERROR_DS_OPERATIONS_ERROR: ::DWORD = 8224; +pub const ERROR_DS_PROTOCOL_ERROR: ::DWORD = 8225; +pub const ERROR_DS_TIMELIMIT_EXCEEDED: ::DWORD = 8226; +pub const ERROR_DS_SIZELIMIT_EXCEEDED: ::DWORD = 8227; +pub const ERROR_DS_ADMIN_LIMIT_EXCEEDED: ::DWORD = 8228; +pub const ERROR_DS_COMPARE_FALSE: ::DWORD = 8229; +pub const ERROR_DS_COMPARE_TRUE: ::DWORD = 8230; +pub const ERROR_DS_AUTH_METHOD_NOT_SUPPORTED: ::DWORD = 8231; +pub const ERROR_DS_STRONG_AUTH_REQUIRED: ::DWORD = 8232; +pub const ERROR_DS_INAPPROPRIATE_AUTH: ::DWORD = 8233; +pub const ERROR_DS_AUTH_UNKNOWN: ::DWORD = 8234; +pub const ERROR_DS_REFERRAL: ::DWORD = 8235; +pub const ERROR_DS_UNAVAILABLE_CRIT_EXTENSION: ::DWORD = 8236; +pub const ERROR_DS_CONFIDENTIALITY_REQUIRED: ::DWORD = 8237; +pub const ERROR_DS_INAPPROPRIATE_MATCHING: ::DWORD = 8238; +pub const ERROR_DS_CONSTRAINT_VIOLATION: ::DWORD = 8239; +pub const ERROR_DS_NO_SUCH_OBJECT: ::DWORD = 8240; +pub const ERROR_DS_ALIAS_PROBLEM: ::DWORD = 8241; +pub const ERROR_DS_INVALID_DN_SYNTAX: ::DWORD = 8242; +pub const ERROR_DS_IS_LEAF: ::DWORD = 8243; +pub const ERROR_DS_ALIAS_DEREF_PROBLEM: ::DWORD = 8244; +pub const ERROR_DS_UNWILLING_TO_PERFORM: ::DWORD = 8245; +pub const ERROR_DS_LOOP_DETECT: ::DWORD = 8246; +pub const ERROR_DS_NAMING_VIOLATION: ::DWORD = 8247; +pub const ERROR_DS_OBJECT_RESULTS_TOO_LARGE: ::DWORD = 8248; +pub const ERROR_DS_AFFECTS_MULTIPLE_DSAS: ::DWORD = 8249; +pub const ERROR_DS_SERVER_DOWN: ::DWORD = 8250; +pub const ERROR_DS_LOCAL_ERROR: ::DWORD = 8251; +pub const ERROR_DS_ENCODING_ERROR: ::DWORD = 8252; +pub const ERROR_DS_DECODING_ERROR: ::DWORD = 8253; +pub const ERROR_DS_FILTER_UNKNOWN: ::DWORD = 8254; +pub const ERROR_DS_PARAM_ERROR: ::DWORD = 8255; +pub const ERROR_DS_NOT_SUPPORTED: ::DWORD = 8256; +pub const ERROR_DS_NO_RESULTS_RETURNED: ::DWORD = 8257; +pub const ERROR_DS_CONTROL_NOT_FOUND: ::DWORD = 8258; +pub const ERROR_DS_CLIENT_LOOP: ::DWORD = 8259; +pub const ERROR_DS_REFERRAL_LIMIT_EXCEEDED: ::DWORD = 8260; +pub const ERROR_DS_SORT_CONTROL_MISSING: ::DWORD = 8261; +pub const ERROR_DS_OFFSET_RANGE_ERROR: ::DWORD = 8262; +pub const ERROR_DS_RIDMGR_DISABLED: ::DWORD = 8263; +pub const ERROR_DS_ROOT_MUST_BE_NC: ::DWORD = 8301; +pub const ERROR_DS_ADD_REPLICA_INHIBITED: ::DWORD = 8302; +pub const ERROR_DS_ATT_NOT_DEF_IN_SCHEMA: ::DWORD = 8303; +pub const ERROR_DS_MAX_OBJ_SIZE_EXCEEDED: ::DWORD = 8304; +pub const ERROR_DS_OBJ_STRING_NAME_EXISTS: ::DWORD = 8305; +pub const ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA: ::DWORD = 8306; +pub const ERROR_DS_RDN_DOESNT_MATCH_SCHEMA: ::DWORD = 8307; +pub const ERROR_DS_NO_REQUESTED_ATTS_FOUND: ::DWORD = 8308; +pub const ERROR_DS_USER_BUFFER_TO_SMALL: ::DWORD = 8309; +pub const ERROR_DS_ATT_IS_NOT_ON_OBJ: ::DWORD = 8310; +pub const ERROR_DS_ILLEGAL_MOD_OPERATION: ::DWORD = 8311; +pub const ERROR_DS_OBJ_TOO_LARGE: ::DWORD = 8312; +pub const ERROR_DS_BAD_INSTANCE_TYPE: ::DWORD = 8313; +pub const ERROR_DS_MASTERDSA_REQUIRED: ::DWORD = 8314; +pub const ERROR_DS_OBJECT_CLASS_REQUIRED: ::DWORD = 8315; +pub const ERROR_DS_MISSING_REQUIRED_ATT: ::DWORD = 8316; +pub const ERROR_DS_ATT_NOT_DEF_FOR_CLASS: ::DWORD = 8317; +pub const ERROR_DS_ATT_ALREADY_EXISTS: ::DWORD = 8318; +pub const ERROR_DS_CANT_ADD_ATT_VALUES: ::DWORD = 8320; +pub const ERROR_DS_SINGLE_VALUE_CONSTRAINT: ::DWORD = 8321; +pub const ERROR_DS_RANGE_CONSTRAINT: ::DWORD = 8322; +pub const ERROR_DS_ATT_VAL_ALREADY_EXISTS: ::DWORD = 8323; +pub const ERROR_DS_CANT_REM_MISSING_ATT: ::DWORD = 8324; +pub const ERROR_DS_CANT_REM_MISSING_ATT_VAL: ::DWORD = 8325; +pub const ERROR_DS_ROOT_CANT_BE_SUBREF: ::DWORD = 8326; +pub const ERROR_DS_NO_CHAINING: ::DWORD = 8327; +pub const ERROR_DS_NO_CHAINED_EVAL: ::DWORD = 8328; +pub const ERROR_DS_NO_PARENT_OBJECT: ::DWORD = 8329; +pub const ERROR_DS_PARENT_IS_AN_ALIAS: ::DWORD = 8330; +pub const ERROR_DS_CANT_MIX_MASTER_AND_REPS: ::DWORD = 8331; +pub const ERROR_DS_CHILDREN_EXIST: ::DWORD = 8332; +pub const ERROR_DS_OBJ_NOT_FOUND: ::DWORD = 8333; +pub const ERROR_DS_ALIASED_OBJ_MISSING: ::DWORD = 8334; +pub const ERROR_DS_BAD_NAME_SYNTAX: ::DWORD = 8335; +pub const ERROR_DS_ALIAS_POINTS_TO_ALIAS: ::DWORD = 8336; +pub const ERROR_DS_CANT_DEREF_ALIAS: ::DWORD = 8337; +pub const ERROR_DS_OUT_OF_SCOPE: ::DWORD = 8338; +pub const ERROR_DS_OBJECT_BEING_REMOVED: ::DWORD = 8339; +pub const ERROR_DS_CANT_DELETE_DSA_OBJ: ::DWORD = 8340; +pub const ERROR_DS_GENERIC_ERROR: ::DWORD = 8341; +pub const ERROR_DS_DSA_MUST_BE_INT_MASTER: ::DWORD = 8342; +pub const ERROR_DS_CLASS_NOT_DSA: ::DWORD = 8343; +pub const ERROR_DS_INSUFF_ACCESS_RIGHTS: ::DWORD = 8344; +pub const ERROR_DS_ILLEGAL_SUPERIOR: ::DWORD = 8345; +pub const ERROR_DS_ATTRIBUTE_OWNED_BY_SAM: ::DWORD = 8346; +pub const ERROR_DS_NAME_TOO_MANY_PARTS: ::DWORD = 8347; +pub const ERROR_DS_NAME_TOO_LONG: ::DWORD = 8348; +pub const ERROR_DS_NAME_VALUE_TOO_LONG: ::DWORD = 8349; +pub const ERROR_DS_NAME_UNPARSEABLE: ::DWORD = 8350; +pub const ERROR_DS_NAME_TYPE_UNKNOWN: ::DWORD = 8351; +pub const ERROR_DS_NOT_AN_OBJECT: ::DWORD = 8352; +pub const ERROR_DS_SEC_DESC_TOO_SHORT: ::DWORD = 8353; +pub const ERROR_DS_SEC_DESC_INVALID: ::DWORD = 8354; +pub const ERROR_DS_NO_DELETED_NAME: ::DWORD = 8355; +pub const ERROR_DS_SUBREF_MUST_HAVE_PARENT: ::DWORD = 8356; +pub const ERROR_DS_NCNAME_MUST_BE_NC: ::DWORD = 8357; +pub const ERROR_DS_CANT_ADD_SYSTEM_ONLY: ::DWORD = 8358; +pub const ERROR_DS_CLASS_MUST_BE_CONCRETE: ::DWORD = 8359; +pub const ERROR_DS_INVALID_DMD: ::DWORD = 8360; +pub const ERROR_DS_OBJ_GUID_EXISTS: ::DWORD = 8361; +pub const ERROR_DS_NOT_ON_BACKLINK: ::DWORD = 8362; +pub const ERROR_DS_NO_CROSSREF_FOR_NC: ::DWORD = 8363; +pub const ERROR_DS_SHUTTING_DOWN: ::DWORD = 8364; +pub const ERROR_DS_UNKNOWN_OPERATION: ::DWORD = 8365; +pub const ERROR_DS_INVALID_ROLE_OWNER: ::DWORD = 8366; +pub const ERROR_DS_COULDNT_CONTACT_FSMO: ::DWORD = 8367; +pub const ERROR_DS_CROSS_NC_DN_RENAME: ::DWORD = 8368; +pub const ERROR_DS_CANT_MOD_SYSTEM_ONLY: ::DWORD = 8369; +pub const ERROR_DS_REPLICATOR_ONLY: ::DWORD = 8370; +pub const ERROR_DS_OBJ_CLASS_NOT_DEFINED: ::DWORD = 8371; +pub const ERROR_DS_OBJ_CLASS_NOT_SUBCLASS: ::DWORD = 8372; +pub const ERROR_DS_NAME_REFERENCE_INVALID: ::DWORD = 8373; +pub const ERROR_DS_CROSS_REF_EXISTS: ::DWORD = 8374; +pub const ERROR_DS_CANT_DEL_MASTER_CROSSREF: ::DWORD = 8375; +pub const ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD: ::DWORD = 8376; +pub const ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX: ::DWORD = 8377; +pub const ERROR_DS_DUP_RDN: ::DWORD = 8378; +pub const ERROR_DS_DUP_OID: ::DWORD = 8379; +pub const ERROR_DS_DUP_MAPI_ID: ::DWORD = 8380; +pub const ERROR_DS_DUP_SCHEMA_ID_GUID: ::DWORD = 8381; +pub const ERROR_DS_DUP_LDAP_DISPLAY_NAME: ::DWORD = 8382; +pub const ERROR_DS_SEMANTIC_ATT_TEST: ::DWORD = 8383; +pub const ERROR_DS_SYNTAX_MISMATCH: ::DWORD = 8384; +pub const ERROR_DS_EXISTS_IN_MUST_HAVE: ::DWORD = 8385; +pub const ERROR_DS_EXISTS_IN_MAY_HAVE: ::DWORD = 8386; +pub const ERROR_DS_NONEXISTENT_MAY_HAVE: ::DWORD = 8387; +pub const ERROR_DS_NONEXISTENT_MUST_HAVE: ::DWORD = 8388; +pub const ERROR_DS_AUX_CLS_TEST_FAIL: ::DWORD = 8389; +pub const ERROR_DS_NONEXISTENT_POSS_SUP: ::DWORD = 8390; +pub const ERROR_DS_SUB_CLS_TEST_FAIL: ::DWORD = 8391; +pub const ERROR_DS_BAD_RDN_ATT_ID_SYNTAX: ::DWORD = 8392; +pub const ERROR_DS_EXISTS_IN_AUX_CLS: ::DWORD = 8393; +pub const ERROR_DS_EXISTS_IN_SUB_CLS: ::DWORD = 8394; +pub const ERROR_DS_EXISTS_IN_POSS_SUP: ::DWORD = 8395; +pub const ERROR_DS_RECALCSCHEMA_FAILED: ::DWORD = 8396; +pub const ERROR_DS_TREE_DELETE_NOT_FINISHED: ::DWORD = 8397; +pub const ERROR_DS_CANT_DELETE: ::DWORD = 8398; +pub const ERROR_DS_ATT_SCHEMA_REQ_ID: ::DWORD = 8399; +pub const ERROR_DS_BAD_ATT_SCHEMA_SYNTAX: ::DWORD = 8400; +pub const ERROR_DS_CANT_CACHE_ATT: ::DWORD = 8401; +pub const ERROR_DS_CANT_CACHE_CLASS: ::DWORD = 8402; +pub const ERROR_DS_CANT_REMOVE_ATT_CACHE: ::DWORD = 8403; +pub const ERROR_DS_CANT_REMOVE_CLASS_CACHE: ::DWORD = 8404; +pub const ERROR_DS_CANT_RETRIEVE_DN: ::DWORD = 8405; +pub const ERROR_DS_MISSING_SUPREF: ::DWORD = 8406; +pub const ERROR_DS_CANT_RETRIEVE_INSTANCE: ::DWORD = 8407; +pub const ERROR_DS_CODE_INCONSISTENCY: ::DWORD = 8408; +pub const ERROR_DS_DATABASE_ERROR: ::DWORD = 8409; +pub const ERROR_DS_GOVERNSID_MISSING: ::DWORD = 8410; +pub const ERROR_DS_MISSING_EXPECTED_ATT: ::DWORD = 8411; +pub const ERROR_DS_NCNAME_MISSING_CR_REF: ::DWORD = 8412; +pub const ERROR_DS_SECURITY_CHECKING_ERROR: ::DWORD = 8413; +pub const ERROR_DS_SCHEMA_NOT_LOADED: ::DWORD = 8414; +pub const ERROR_DS_SCHEMA_ALLOC_FAILED: ::DWORD = 8415; +pub const ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: ::DWORD = 8416; +pub const ERROR_DS_GCVERIFY_ERROR: ::DWORD = 8417; +pub const ERROR_DS_DRA_SCHEMA_MISMATCH: ::DWORD = 8418; +pub const ERROR_DS_CANT_FIND_DSA_OBJ: ::DWORD = 8419; +pub const ERROR_DS_CANT_FIND_EXPECTED_NC: ::DWORD = 8420; +pub const ERROR_DS_CANT_FIND_NC_IN_CACHE: ::DWORD = 8421; +pub const ERROR_DS_CANT_RETRIEVE_CHILD: ::DWORD = 8422; +pub const ERROR_DS_SECURITY_ILLEGAL_MODIFY: ::DWORD = 8423; +pub const ERROR_DS_CANT_REPLACE_HIDDEN_REC: ::DWORD = 8424; +pub const ERROR_DS_BAD_HIERARCHY_FILE: ::DWORD = 8425; +pub const ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED: ::DWORD = 8426; +pub const ERROR_DS_CONFIG_PARAM_MISSING: ::DWORD = 8427; +pub const ERROR_DS_COUNTING_AB_INDICES_FAILED: ::DWORD = 8428; +pub const ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED: ::DWORD = 8429; +pub const ERROR_DS_INTERNAL_FAILURE: ::DWORD = 8430; +pub const ERROR_DS_UNKNOWN_ERROR: ::DWORD = 8431; +pub const ERROR_DS_ROOT_REQUIRES_CLASS_TOP: ::DWORD = 8432; +pub const ERROR_DS_REFUSING_FSMO_ROLES: ::DWORD = 8433; +pub const ERROR_DS_MISSING_FSMO_SETTINGS: ::DWORD = 8434; +pub const ERROR_DS_UNABLE_TO_SURRENDER_ROLES: ::DWORD = 8435; +pub const ERROR_DS_DRA_GENERIC: ::DWORD = 8436; +pub const ERROR_DS_DRA_INVALID_PARAMETER: ::DWORD = 8437; +pub const ERROR_DS_DRA_BUSY: ::DWORD = 8438; +pub const ERROR_DS_DRA_BAD_DN: ::DWORD = 8439; +pub const ERROR_DS_DRA_BAD_NC: ::DWORD = 8440; +pub const ERROR_DS_DRA_DN_EXISTS: ::DWORD = 8441; +pub const ERROR_DS_DRA_INTERNAL_ERROR: ::DWORD = 8442; +pub const ERROR_DS_DRA_INCONSISTENT_DIT: ::DWORD = 8443; +pub const ERROR_DS_DRA_CONNECTION_FAILED: ::DWORD = 8444; +pub const ERROR_DS_DRA_BAD_INSTANCE_TYPE: ::DWORD = 8445; +pub const ERROR_DS_DRA_OUT_OF_MEM: ::DWORD = 8446; +pub const ERROR_DS_DRA_MAIL_PROBLEM: ::DWORD = 8447; +pub const ERROR_DS_DRA_REF_ALREADY_EXISTS: ::DWORD = 8448; +pub const ERROR_DS_DRA_REF_NOT_FOUND: ::DWORD = 8449; +pub const ERROR_DS_DRA_OBJ_IS_REP_SOURCE: ::DWORD = 8450; +pub const ERROR_DS_DRA_DB_ERROR: ::DWORD = 8451; +pub const ERROR_DS_DRA_NO_REPLICA: ::DWORD = 8452; +pub const ERROR_DS_DRA_ACCESS_DENIED: ::DWORD = 8453; +pub const ERROR_DS_DRA_NOT_SUPPORTED: ::DWORD = 8454; +pub const ERROR_DS_DRA_RPC_CANCELLED: ::DWORD = 8455; +pub const ERROR_DS_DRA_SOURCE_DISABLED: ::DWORD = 8456; +pub const ERROR_DS_DRA_SINK_DISABLED: ::DWORD = 8457; +pub const ERROR_DS_DRA_NAME_COLLISION: ::DWORD = 8458; +pub const ERROR_DS_DRA_SOURCE_REINSTALLED: ::DWORD = 8459; +pub const ERROR_DS_DRA_MISSING_PARENT: ::DWORD = 8460; +pub const ERROR_DS_DRA_PREEMPTED: ::DWORD = 8461; +pub const ERROR_DS_DRA_ABANDON_SYNC: ::DWORD = 8462; +pub const ERROR_DS_DRA_SHUTDOWN: ::DWORD = 8463; +pub const ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET: ::DWORD = 8464; +pub const ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA: ::DWORD = 8465; +pub const ERROR_DS_DRA_EXTN_CONNECTION_FAILED: ::DWORD = 8466; +pub const ERROR_DS_INSTALL_SCHEMA_MISMATCH: ::DWORD = 8467; +pub const ERROR_DS_DUP_LINK_ID: ::DWORD = 8468; +pub const ERROR_DS_NAME_ERROR_RESOLVING: ::DWORD = 8469; +pub const ERROR_DS_NAME_ERROR_NOT_FOUND: ::DWORD = 8470; +pub const ERROR_DS_NAME_ERROR_NOT_UNIQUE: ::DWORD = 8471; +pub const ERROR_DS_NAME_ERROR_NO_MAPPING: ::DWORD = 8472; +pub const ERROR_DS_NAME_ERROR_DOMAIN_ONLY: ::DWORD = 8473; +pub const ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: ::DWORD = 8474; +pub const ERROR_DS_CONSTRUCTED_ATT_MOD: ::DWORD = 8475; +pub const ERROR_DS_WRONG_OM_OBJ_CLASS: ::DWORD = 8476; +pub const ERROR_DS_DRA_REPL_PENDING: ::DWORD = 8477; +pub const ERROR_DS_DS_REQUIRED: ::DWORD = 8478; +pub const ERROR_DS_INVALID_LDAP_DISPLAY_NAME: ::DWORD = 8479; +pub const ERROR_DS_NON_BASE_SEARCH: ::DWORD = 8480; +pub const ERROR_DS_CANT_RETRIEVE_ATTS: ::DWORD = 8481; +pub const ERROR_DS_BACKLINK_WITHOUT_LINK: ::DWORD = 8482; +pub const ERROR_DS_EPOCH_MISMATCH: ::DWORD = 8483; +pub const ERROR_DS_SRC_NAME_MISMATCH: ::DWORD = 8484; +pub const ERROR_DS_SRC_AND_DST_NC_IDENTICAL: ::DWORD = 8485; +pub const ERROR_DS_DST_NC_MISMATCH: ::DWORD = 8486; +pub const ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC: ::DWORD = 8487; +pub const ERROR_DS_SRC_GUID_MISMATCH: ::DWORD = 8488; +pub const ERROR_DS_CANT_MOVE_DELETED_OBJECT: ::DWORD = 8489; +pub const ERROR_DS_PDC_OPERATION_IN_PROGRESS: ::DWORD = 8490; +pub const ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD: ::DWORD = 8491; +pub const ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION: ::DWORD = 8492; +pub const ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS: ::DWORD = 8493; +pub const ERROR_DS_NC_MUST_HAVE_NC_PARENT: ::DWORD = 8494; +pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE: ::DWORD = 8495; +pub const ERROR_DS_DST_DOMAIN_NOT_NATIVE: ::DWORD = 8496; +pub const ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER: ::DWORD = 8497; +pub const ERROR_DS_CANT_MOVE_ACCOUNT_GROUP: ::DWORD = 8498; +pub const ERROR_DS_CANT_MOVE_RESOURCE_GROUP: ::DWORD = 8499; +pub const ERROR_DS_INVALID_SEARCH_FLAG: ::DWORD = 8500; +pub const ERROR_DS_NO_TREE_DELETE_ABOVE_NC: ::DWORD = 8501; +pub const ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE: ::DWORD = 8502; +pub const ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE: ::DWORD = 8503; +pub const ERROR_DS_SAM_INIT_FAILURE: ::DWORD = 8504; +pub const ERROR_DS_SENSITIVE_GROUP_VIOLATION: ::DWORD = 8505; +pub const ERROR_DS_CANT_MOD_PRIMARYGROUPID: ::DWORD = 8506; +pub const ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD: ::DWORD = 8507; +pub const ERROR_DS_NONSAFE_SCHEMA_CHANGE: ::DWORD = 8508; +pub const ERROR_DS_SCHEMA_UPDATE_DISALLOWED: ::DWORD = 8509; +pub const ERROR_DS_CANT_CREATE_UNDER_SCHEMA: ::DWORD = 8510; +pub const ERROR_DS_INSTALL_NO_SRC_SCH_VERSION: ::DWORD = 8511; +pub const ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE: ::DWORD = 8512; +pub const ERROR_DS_INVALID_GROUP_TYPE: ::DWORD = 8513; +pub const ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: ::DWORD = 8514; +pub const ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: ::DWORD = 8515; +pub const ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: ::DWORD = 8516; +pub const ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: ::DWORD = 8517; +pub const ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: ::DWORD = 8518; +pub const ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: ::DWORD = 8519; +pub const ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: ::DWORD = 8520; +pub const ERROR_DS_HAVE_PRIMARY_MEMBERS: ::DWORD = 8521; +pub const ERROR_DS_STRING_SD_CONVERSION_FAILED: ::DWORD = 8522; +pub const ERROR_DS_NAMING_MASTER_GC: ::DWORD = 8523; +pub const ERROR_DS_DNS_LOOKUP_FAILURE: ::DWORD = 8524; +pub const ERROR_DS_COULDNT_UPDATE_SPNS: ::DWORD = 8525; +pub const ERROR_DS_CANT_RETRIEVE_SD: ::DWORD = 8526; +pub const ERROR_DS_KEY_NOT_UNIQUE: ::DWORD = 8527; +pub const ERROR_DS_WRONG_LINKED_ATT_SYNTAX: ::DWORD = 8528; +pub const ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD: ::DWORD = 8529; +pub const ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY: ::DWORD = 8530; +pub const ERROR_DS_CANT_START: ::DWORD = 8531; +pub const ERROR_DS_INIT_FAILURE: ::DWORD = 8532; +pub const ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: ::DWORD = 8533; +pub const ERROR_DS_SOURCE_DOMAIN_IN_FOREST: ::DWORD = 8534; +pub const ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: ::DWORD = 8535; +pub const ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: ::DWORD = 8536; +pub const ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: ::DWORD = 8537; +pub const ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: ::DWORD = 8538; +pub const ERROR_DS_SRC_SID_EXISTS_IN_FOREST: ::DWORD = 8539; +pub const ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: ::DWORD = 8540; +pub const ERROR_SAM_INIT_FAILURE: ::DWORD = 8541; +pub const ERROR_DS_DRA_SCHEMA_INFO_SHIP: ::DWORD = 8542; +pub const ERROR_DS_DRA_SCHEMA_CONFLICT: ::DWORD = 8543; +pub const ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT: ::DWORD = 8544; +pub const ERROR_DS_DRA_OBJ_NC_MISMATCH: ::DWORD = 8545; +pub const ERROR_DS_NC_STILL_HAS_DSAS: ::DWORD = 8546; +pub const ERROR_DS_GC_REQUIRED: ::DWORD = 8547; +pub const ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: ::DWORD = 8548; +pub const ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS: ::DWORD = 8549; +pub const ERROR_DS_CANT_ADD_TO_GC: ::DWORD = 8550; +pub const ERROR_DS_NO_CHECKPOINT_WITH_PDC: ::DWORD = 8551; +pub const ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: ::DWORD = 8552; +pub const ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC: ::DWORD = 8553; +pub const ERROR_DS_INVALID_NAME_FOR_SPN: ::DWORD = 8554; +pub const ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS: ::DWORD = 8555; +pub const ERROR_DS_UNICODEPWD_NOT_IN_QUOTES: ::DWORD = 8556; +pub const ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: ::DWORD = 8557; +pub const ERROR_DS_MUST_BE_RUN_ON_DST_DC: ::DWORD = 8558; +pub const ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: ::DWORD = 8559; +pub const ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ: ::DWORD = 8560; +pub const ERROR_DS_INIT_FAILURE_CONSOLE: ::DWORD = 8561; +pub const ERROR_DS_SAM_INIT_FAILURE_CONSOLE: ::DWORD = 8562; +pub const ERROR_DS_FOREST_VERSION_TOO_HIGH: ::DWORD = 8563; +pub const ERROR_DS_DOMAIN_VERSION_TOO_HIGH: ::DWORD = 8564; +pub const ERROR_DS_FOREST_VERSION_TOO_LOW: ::DWORD = 8565; +pub const ERROR_DS_DOMAIN_VERSION_TOO_LOW: ::DWORD = 8566; +pub const ERROR_DS_INCOMPATIBLE_VERSION: ::DWORD = 8567; +pub const ERROR_DS_LOW_DSA_VERSION: ::DWORD = 8568; +pub const ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN: ::DWORD = 8569; +pub const ERROR_DS_NOT_SUPPORTED_SORT_ORDER: ::DWORD = 8570; +pub const ERROR_DS_NAME_NOT_UNIQUE: ::DWORD = 8571; +pub const ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4: ::DWORD = 8572; +pub const ERROR_DS_OUT_OF_VERSION_STORE: ::DWORD = 8573; +pub const ERROR_DS_INCOMPATIBLE_CONTROLS_USED: ::DWORD = 8574; +pub const ERROR_DS_NO_REF_DOMAIN: ::DWORD = 8575; +pub const ERROR_DS_RESERVED_LINK_ID: ::DWORD = 8576; +pub const ERROR_DS_LINK_ID_NOT_AVAILABLE: ::DWORD = 8577; +pub const ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: ::DWORD = 8578; +pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE: ::DWORD = 8579; +pub const ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC: ::DWORD = 8580; +pub const ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG: ::DWORD = 8581; +pub const ERROR_DS_MODIFYDN_WRONG_GRANDPARENT: ::DWORD = 8582; +pub const ERROR_DS_NAME_ERROR_TRUST_REFERRAL: ::DWORD = 8583; +pub const ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER: ::DWORD = 8584; +pub const ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD: ::DWORD = 8585; +pub const ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2: ::DWORD = 8586; +pub const ERROR_DS_THREAD_LIMIT_EXCEEDED: ::DWORD = 8587; +pub const ERROR_DS_NOT_CLOSEST: ::DWORD = 8588; +pub const ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF: ::DWORD = 8589; +pub const ERROR_DS_SINGLE_USER_MODE_FAILED: ::DWORD = 8590; +pub const ERROR_DS_NTDSCRIPT_SYNTAX_ERROR: ::DWORD = 8591; +pub const ERROR_DS_NTDSCRIPT_PROCESS_ERROR: ::DWORD = 8592; +pub const ERROR_DS_DIFFERENT_REPL_EPOCHS: ::DWORD = 8593; +pub const ERROR_DS_DRS_EXTENSIONS_CHANGED: ::DWORD = 8594; +pub const ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR: ::DWORD = 8595; +pub const ERROR_DS_NO_MSDS_INTID: ::DWORD = 8596; +pub const ERROR_DS_DUP_MSDS_INTID: ::DWORD = 8597; +pub const ERROR_DS_EXISTS_IN_RDNATTID: ::DWORD = 8598; +pub const ERROR_DS_AUTHORIZATION_FAILED: ::DWORD = 8599; +pub const ERROR_DS_INVALID_SCRIPT: ::DWORD = 8600; +pub const ERROR_DS_REMOTE_CROSSREF_OP_FAILED: ::DWORD = 8601; +pub const ERROR_DS_CROSS_REF_BUSY: ::DWORD = 8602; +pub const ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN: ::DWORD = 8603; +pub const ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC: ::DWORD = 8604; +pub const ERROR_DS_DUPLICATE_ID_FOUND: ::DWORD = 8605; +pub const ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT: ::DWORD = 8606; +pub const ERROR_DS_GROUP_CONVERSION_ERROR: ::DWORD = 8607; +pub const ERROR_DS_CANT_MOVE_APP_BASIC_GROUP: ::DWORD = 8608; +pub const ERROR_DS_CANT_MOVE_APP_QUERY_GROUP: ::DWORD = 8609; +pub const ERROR_DS_ROLE_NOT_VERIFIED: ::DWORD = 8610; +pub const ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL: ::DWORD = 8611; +pub const ERROR_DS_DOMAIN_RENAME_IN_PROGRESS: ::DWORD = 8612; +pub const ERROR_DS_EXISTING_AD_CHILD_NC: ::DWORD = 8613; +pub const ERROR_DS_REPL_LIFETIME_EXCEEDED: ::DWORD = 8614; +pub const ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER: ::DWORD = 8615; +pub const ERROR_DS_LDAP_SEND_QUEUE_FULL: ::DWORD = 8616; +pub const ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: ::DWORD = 8617; +pub const ERROR_DS_POLICY_NOT_KNOWN: ::DWORD = 8618; +pub const ERROR_NO_SITE_SETTINGS_OBJECT: ::DWORD = 8619; +pub const ERROR_NO_SECRETS: ::DWORD = 8620; +pub const ERROR_NO_WRITABLE_DC_FOUND: ::DWORD = 8621; +pub const ERROR_DS_NO_SERVER_OBJECT: ::DWORD = 8622; +pub const ERROR_DS_NO_NTDSA_OBJECT: ::DWORD = 8623; +pub const ERROR_DS_NON_ASQ_SEARCH: ::DWORD = 8624; +pub const ERROR_DS_AUDIT_FAILURE: ::DWORD = 8625; +pub const ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE: ::DWORD = 8626; +pub const ERROR_DS_INVALID_SEARCH_FLAG_TUPLE: ::DWORD = 8627; +pub const ERROR_DS_HIERARCHY_TABLE_TOO_DEEP: ::DWORD = 8628; +pub const ERROR_DS_DRA_CORRUPT_UTD_VECTOR: ::DWORD = 8629; +pub const ERROR_DS_DRA_SECRETS_DENIED: ::DWORD = 8630; +pub const ERROR_DS_RESERVED_MAPI_ID: ::DWORD = 8631; +pub const ERROR_DS_MAPI_ID_NOT_AVAILABLE: ::DWORD = 8632; +pub const ERROR_DS_DRA_MISSING_KRBTGT_SECRET: ::DWORD = 8633; +pub const ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST: ::DWORD = 8634; +pub const ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST: ::DWORD = 8635; +pub const ERROR_INVALID_USER_PRINCIPAL_NAME: ::DWORD = 8636; +pub const ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: ::DWORD = 8637; +pub const ERROR_DS_OID_NOT_FOUND: ::DWORD = 8638; +pub const ERROR_DS_DRA_RECYCLED_TARGET: ::DWORD = 8639; +pub const ERROR_DS_DISALLOWED_NC_REDIRECT: ::DWORD = 8640; +pub const ERROR_DS_HIGH_ADLDS_FFL: ::DWORD = 8641; +pub const ERROR_DS_HIGH_DSA_VERSION: ::DWORD = 8642; +pub const ERROR_DS_LOW_ADLDS_FFL: ::DWORD = 8643; +pub const ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION: ::DWORD = 8644; +pub const ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED: ::DWORD = 8645; +pub const ERROR_INCORRECT_ACCOUNT_TYPE: ::DWORD = 8646; +pub const ERROR_DS_SPN_VALUE_NOT_UNIQUE_IN_FOREST: ::DWORD = 8647; +pub const ERROR_DS_UPN_VALUE_NOT_UNIQUE_IN_FOREST: ::DWORD = 8648; +pub const DNS_ERROR_RESPONSE_CODES_BASE: ::DWORD = 9000; +pub const DNS_ERROR_RCODE_NO_ERROR: ::DWORD = NO_ERROR; +pub const DNS_ERROR_MASK: ::DWORD = 0x00002328; +pub const DNS_ERROR_RCODE_FORMAT_ERROR: ::DWORD = 9001; +pub const DNS_ERROR_RCODE_SERVER_FAILURE: ::DWORD = 9002; +pub const DNS_ERROR_RCODE_NAME_ERROR: ::DWORD = 9003; +pub const DNS_ERROR_RCODE_NOT_IMPLEMENTED: ::DWORD = 9004; +pub const DNS_ERROR_RCODE_REFUSED: ::DWORD = 9005; +pub const DNS_ERROR_RCODE_YXDOMAIN: ::DWORD = 9006; +pub const DNS_ERROR_RCODE_YXRRSET: ::DWORD = 9007; +pub const DNS_ERROR_RCODE_NXRRSET: ::DWORD = 9008; +pub const DNS_ERROR_RCODE_NOTAUTH: ::DWORD = 9009; +pub const DNS_ERROR_RCODE_NOTZONE: ::DWORD = 9010; +pub const DNS_ERROR_RCODE_BADSIG: ::DWORD = 9016; +pub const DNS_ERROR_RCODE_BADKEY: ::DWORD = 9017; +pub const DNS_ERROR_RCODE_BADTIME: ::DWORD = 9018; +pub const DNS_ERROR_RCODE_LAST: ::DWORD = DNS_ERROR_RCODE_BADTIME; +pub const DNS_ERROR_DNSSEC_BASE: ::DWORD = 9100; +pub const DNS_ERROR_KEYMASTER_REQUIRED: ::DWORD = 9101; +pub const DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE: ::DWORD = 9102; +pub const DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1: ::DWORD = 9103; +pub const DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS: ::DWORD = 9104; +pub const DNS_ERROR_UNSUPPORTED_ALGORITHM: ::DWORD = 9105; +pub const DNS_ERROR_INVALID_KEY_SIZE: ::DWORD = 9106; +pub const DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE: ::DWORD = 9107; +pub const DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION: ::DWORD = 9108; +pub const DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR: ::DWORD = 9109; +pub const DNS_ERROR_UNEXPECTED_CNG_ERROR: ::DWORD = 9110; +pub const DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION: ::DWORD = 9111; +pub const DNS_ERROR_KSP_NOT_ACCESSIBLE: ::DWORD = 9112; +pub const DNS_ERROR_TOO_MANY_SKDS: ::DWORD = 9113; +pub const DNS_ERROR_INVALID_ROLLOVER_PERIOD: ::DWORD = 9114; +pub const DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET: ::DWORD = 9115; +pub const DNS_ERROR_ROLLOVER_IN_PROGRESS: ::DWORD = 9116; +pub const DNS_ERROR_STANDBY_KEY_NOT_PRESENT: ::DWORD = 9117; +pub const DNS_ERROR_NOT_ALLOWED_ON_ZSK: ::DWORD = 9118; +pub const DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD: ::DWORD = 9119; +pub const DNS_ERROR_ROLLOVER_ALREADY_QUEUED: ::DWORD = 9120; +pub const DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE: ::DWORD = 9121; +pub const DNS_ERROR_BAD_KEYMASTER: ::DWORD = 9122; +pub const DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD: ::DWORD = 9123; +pub const DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT: ::DWORD = 9124; +pub const DNS_ERROR_DNSSEC_IS_DISABLED: ::DWORD = 9125; +pub const DNS_ERROR_INVALID_XML: ::DWORD = 9126; +pub const DNS_ERROR_NO_VALID_TRUST_ANCHORS: ::DWORD = 9127; +pub const DNS_ERROR_ROLLOVER_NOT_POKEABLE: ::DWORD = 9128; +pub const DNS_ERROR_NSEC3_NAME_COLLISION: ::DWORD = 9129; +pub const DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1: ::DWORD = 9130; +pub const DNS_ERROR_PACKET_FMT_BASE: ::DWORD = 9500; +pub const DNS_INFO_NO_RECORDS: ::DWORD = 9501; +pub const DNS_ERROR_BAD_PACKET: ::DWORD = 9502; +pub const DNS_ERROR_NO_PACKET: ::DWORD = 9503; +pub const DNS_ERROR_RCODE: ::DWORD = 9504; +pub const DNS_ERROR_UNSECURE_PACKET: ::DWORD = 9505; +pub const DNS_STATUS_PACKET_UNSECURE: ::DWORD = DNS_ERROR_UNSECURE_PACKET; +pub const DNS_REQUEST_PENDING: ::DWORD = 9506; +pub const DNS_ERROR_NO_MEMORY: ::DWORD = ERROR_OUTOFMEMORY; +pub const DNS_ERROR_INVALID_NAME: ::DWORD = ERROR_INVALID_NAME; +pub const DNS_ERROR_INVALID_DATA: ::DWORD = ERROR_INVALID_DATA; +pub const DNS_ERROR_GENERAL_API_BASE: ::DWORD = 9550; +pub const DNS_ERROR_INVALID_TYPE: ::DWORD = 9551; +pub const DNS_ERROR_INVALID_IP_ADDRESS: ::DWORD = 9552; +pub const DNS_ERROR_INVALID_PROPERTY: ::DWORD = 9553; +pub const DNS_ERROR_TRY_AGAIN_LATER: ::DWORD = 9554; +pub const DNS_ERROR_NOT_UNIQUE: ::DWORD = 9555; +pub const DNS_ERROR_NON_RFC_NAME: ::DWORD = 9556; +pub const DNS_STATUS_FQDN: ::DWORD = 9557; +pub const DNS_STATUS_DOTTED_NAME: ::DWORD = 9558; +pub const DNS_STATUS_SINGLE_PART_NAME: ::DWORD = 9559; +pub const DNS_ERROR_INVALID_NAME_CHAR: ::DWORD = 9560; +pub const DNS_ERROR_NUMERIC_NAME: ::DWORD = 9561; +pub const DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER: ::DWORD = 9562; +pub const DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION: ::DWORD = 9563; +pub const DNS_ERROR_CANNOT_FIND_ROOT_HINTS: ::DWORD = 9564; +pub const DNS_ERROR_INCONSISTENT_ROOT_HINTS: ::DWORD = 9565; +pub const DNS_ERROR_DWORD_VALUE_TOO_SMALL: ::DWORD = 9566; +pub const DNS_ERROR_DWORD_VALUE_TOO_LARGE: ::DWORD = 9567; +pub const DNS_ERROR_BACKGROUND_LOADING: ::DWORD = 9568; +pub const DNS_ERROR_NOT_ALLOWED_ON_RODC: ::DWORD = 9569; +pub const DNS_ERROR_NOT_ALLOWED_UNDER_DNAME: ::DWORD = 9570; +pub const DNS_ERROR_DELEGATION_REQUIRED: ::DWORD = 9571; +pub const DNS_ERROR_INVALID_POLICY_TABLE: ::DWORD = 9572; +pub const DNS_ERROR_ZONE_BASE: ::DWORD = 9600; +pub const DNS_ERROR_ZONE_DOES_NOT_EXIST: ::DWORD = 9601; +pub const DNS_ERROR_NO_ZONE_INFO: ::DWORD = 9602; +pub const DNS_ERROR_INVALID_ZONE_OPERATION: ::DWORD = 9603; +pub const DNS_ERROR_ZONE_CONFIGURATION_ERROR: ::DWORD = 9604; +pub const DNS_ERROR_ZONE_HAS_NO_SOA_RECORD: ::DWORD = 9605; +pub const DNS_ERROR_ZONE_HAS_NO_NS_RECORDS: ::DWORD = 9606; +pub const DNS_ERROR_ZONE_LOCKED: ::DWORD = 9607; +pub const DNS_ERROR_ZONE_CREATION_FAILED: ::DWORD = 9608; +pub const DNS_ERROR_ZONE_ALREADY_EXISTS: ::DWORD = 9609; +pub const DNS_ERROR_AUTOZONE_ALREADY_EXISTS: ::DWORD = 9610; +pub const DNS_ERROR_INVALID_ZONE_TYPE: ::DWORD = 9611; +pub const DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP: ::DWORD = 9612; +pub const DNS_ERROR_ZONE_NOT_SECONDARY: ::DWORD = 9613; +pub const DNS_ERROR_NEED_SECONDARY_ADDRESSES: ::DWORD = 9614; +pub const DNS_ERROR_WINS_INIT_FAILED: ::DWORD = 9615; +pub const DNS_ERROR_NEED_WINS_SERVERS: ::DWORD = 9616; +pub const DNS_ERROR_NBSTAT_INIT_FAILED: ::DWORD = 9617; +pub const DNS_ERROR_SOA_DELETE_INVALID: ::DWORD = 9618; +pub const DNS_ERROR_FORWARDER_ALREADY_EXISTS: ::DWORD = 9619; +pub const DNS_ERROR_ZONE_REQUIRES_MASTER_IP: ::DWORD = 9620; +pub const DNS_ERROR_ZONE_IS_SHUTDOWN: ::DWORD = 9621; +pub const DNS_ERROR_ZONE_LOCKED_FOR_SIGNING: ::DWORD = 9622; +pub const DNS_ERROR_DATAFILE_BASE: ::DWORD = 9650; +pub const DNS_ERROR_PRIMARY_REQUIRES_DATAFILE: ::DWORD = 9651; +pub const DNS_ERROR_INVALID_DATAFILE_NAME: ::DWORD = 9652; +pub const DNS_ERROR_DATAFILE_OPEN_FAILURE: ::DWORD = 9653; +pub const DNS_ERROR_FILE_WRITEBACK_FAILED: ::DWORD = 9654; +pub const DNS_ERROR_DATAFILE_PARSING: ::DWORD = 9655; +pub const DNS_ERROR_DATABASE_BASE: ::DWORD = 9700; +pub const DNS_ERROR_RECORD_DOES_NOT_EXIST: ::DWORD = 9701; +pub const DNS_ERROR_RECORD_FORMAT: ::DWORD = 9702; +pub const DNS_ERROR_NODE_CREATION_FAILED: ::DWORD = 9703; +pub const DNS_ERROR_UNKNOWN_RECORD_TYPE: ::DWORD = 9704; +pub const DNS_ERROR_RECORD_TIMED_OUT: ::DWORD = 9705; +pub const DNS_ERROR_NAME_NOT_IN_ZONE: ::DWORD = 9706; +pub const DNS_ERROR_CNAME_LOOP: ::DWORD = 9707; +pub const DNS_ERROR_NODE_IS_CNAME: ::DWORD = 9708; +pub const DNS_ERROR_CNAME_COLLISION: ::DWORD = 9709; +pub const DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT: ::DWORD = 9710; +pub const DNS_ERROR_RECORD_ALREADY_EXISTS: ::DWORD = 9711; +pub const DNS_ERROR_SECONDARY_DATA: ::DWORD = 9712; +pub const DNS_ERROR_NO_CREATE_CACHE_DATA: ::DWORD = 9713; +pub const DNS_ERROR_NAME_DOES_NOT_EXIST: ::DWORD = 9714; +pub const DNS_WARNING_PTR_CREATE_FAILED: ::DWORD = 9715; +pub const DNS_WARNING_DOMAIN_UNDELETED: ::DWORD = 9716; +pub const DNS_ERROR_DS_UNAVAILABLE: ::DWORD = 9717; +pub const DNS_ERROR_DS_ZONE_ALREADY_EXISTS: ::DWORD = 9718; +pub const DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE: ::DWORD = 9719; +pub const DNS_ERROR_NODE_IS_DNAME: ::DWORD = 9720; +pub const DNS_ERROR_DNAME_COLLISION: ::DWORD = 9721; +pub const DNS_ERROR_ALIAS_LOOP: ::DWORD = 9722; +pub const DNS_ERROR_OPERATION_BASE: ::DWORD = 9750; +pub const DNS_INFO_AXFR_COMPLETE: ::DWORD = 9751; +pub const DNS_ERROR_AXFR: ::DWORD = 9752; +pub const DNS_INFO_ADDED_LOCAL_WINS: ::DWORD = 9753; +pub const DNS_ERROR_SECURE_BASE: ::DWORD = 9800; +pub const DNS_STATUS_CONTINUE_NEEDED: ::DWORD = 9801; +pub const DNS_ERROR_SETUP_BASE: ::DWORD = 9850; +pub const DNS_ERROR_NO_TCPIP: ::DWORD = 9851; +pub const DNS_ERROR_NO_DNS_SERVERS: ::DWORD = 9852; +pub const DNS_ERROR_DP_BASE: ::DWORD = 9900; +pub const DNS_ERROR_DP_DOES_NOT_EXIST: ::DWORD = 9901; +pub const DNS_ERROR_DP_ALREADY_EXISTS: ::DWORD = 9902; +pub const DNS_ERROR_DP_NOT_ENLISTED: ::DWORD = 9903; +pub const DNS_ERROR_DP_ALREADY_ENLISTED: ::DWORD = 9904; +pub const DNS_ERROR_DP_NOT_AVAILABLE: ::DWORD = 9905; +pub const DNS_ERROR_DP_FSMO_ERROR: ::DWORD = 9906; +pub const DNS_ERROR_ZONESCOPE_ALREADY_EXISTS: ::DWORD = 9951; +pub const DNS_ERROR_ZONESCOPE_DOES_NOT_EXIST: ::DWORD = 9952; +pub const DNS_ERROR_DEFAULT_ZONESCOPE: ::DWORD = 9953; +pub const DNS_ERROR_INVALID_ZONESCOPE_NAME: ::DWORD = 9954; +pub const DNS_ERROR_NOT_ALLOWED_WITH_ZONESCOPES: ::DWORD = 9955; +pub const DNS_ERROR_LOAD_ZONESCOPE_FAILED: ::DWORD = 9956; +pub const DNS_ERROR_ZONESCOPE_FILE_WRITEBACK_FAILED: ::DWORD = 9957; +pub const DNS_ERROR_INVALID_SCOPE_NAME: ::DWORD = 9958; +pub const DNS_ERROR_SCOPE_DOES_NOT_EXIST: ::DWORD = 9959; +pub const DNS_ERROR_DEFAULT_SCOPE: ::DWORD = 9960; +pub const DNS_ERROR_INVALID_SCOPE_OPERATION: ::DWORD = 9961; +pub const DNS_ERROR_SCOPE_LOCKED: ::DWORD = 9962; +pub const DNS_ERROR_SCOPE_ALREADY_EXISTS: ::DWORD = 9963; +pub const WSABASEERR: ::DWORD = 10000; +pub const WSAEINTR: ::DWORD = 10004; +pub const WSAEBADF: ::DWORD = 10009; +pub const WSAEACCES: ::DWORD = 10013; +pub const WSAEFAULT: ::DWORD = 10014; +pub const WSAEINVAL: ::DWORD = 10022; +pub const WSAEMFILE: ::DWORD = 10024; +pub const WSAEWOULDBLOCK: ::DWORD = 10035; +pub const WSAEINPROGRESS: ::DWORD = 10036; +pub const WSAEALREADY: ::DWORD = 10037; +pub const WSAENOTSOCK: ::DWORD = 10038; +pub const WSAEDESTADDRREQ: ::DWORD = 10039; +pub const WSAEMSGSIZE: ::DWORD = 10040; +pub const WSAEPROTOTYPE: ::DWORD = 10041; +pub const WSAENOPROTOOPT: ::DWORD = 10042; +pub const WSAEPROTONOSUPPORT: ::DWORD = 10043; +pub const WSAESOCKTNOSUPPORT: ::DWORD = 10044; +pub const WSAEOPNOTSUPP: ::DWORD = 10045; +pub const WSAEPFNOSUPPORT: ::DWORD = 10046; +pub const WSAEAFNOSUPPORT: ::DWORD = 10047; +pub const WSAEADDRINUSE: ::DWORD = 10048; +pub const WSAEADDRNOTAVAIL: ::DWORD = 10049; +pub const WSAENETDOWN: ::DWORD = 10050; +pub const WSAENETUNREACH: ::DWORD = 10051; +pub const WSAENETRESET: ::DWORD = 10052; +pub const WSAECONNABORTED: ::DWORD = 10053; +pub const WSAECONNRESET: ::DWORD = 10054; +pub const WSAENOBUFS: ::DWORD = 10055; +pub const WSAEISCONN: ::DWORD = 10056; +pub const WSAENOTCONN: ::DWORD = 10057; +pub const WSAESHUTDOWN: ::DWORD = 10058; +pub const WSAETOOMANYREFS: ::DWORD = 10059; +pub const WSAETIMEDOUT: ::DWORD = 10060; +pub const WSAECONNREFUSED: ::DWORD = 10061; +pub const WSAELOOP: ::DWORD = 10062; +pub const WSAENAMETOOLONG: ::DWORD = 10063; +pub const WSAEHOSTDOWN: ::DWORD = 10064; +pub const WSAEHOSTUNREACH: ::DWORD = 10065; +pub const WSAENOTEMPTY: ::DWORD = 10066; +pub const WSAEPROCLIM: ::DWORD = 10067; +pub const WSAEUSERS: ::DWORD = 10068; +pub const WSAEDQUOT: ::DWORD = 10069; +pub const WSAESTALE: ::DWORD = 10070; +pub const WSAEREMOTE: ::DWORD = 10071; +pub const WSASYSNOTREADY: ::DWORD = 10091; +pub const WSAVERNOTSUPPORTED: ::DWORD = 10092; +pub const WSANOTINITIALISED: ::DWORD = 10093; +pub const WSAEDISCON: ::DWORD = 10101; +pub const WSAENOMORE: ::DWORD = 10102; +pub const WSAECANCELLED: ::DWORD = 10103; +pub const WSAEINVALIDPROCTABLE: ::DWORD = 10104; +pub const WSAEINVALIDPROVIDER: ::DWORD = 10105; +pub const WSAEPROVIDERFAILEDINIT: ::DWORD = 10106; +pub const WSASYSCALLFAILURE: ::DWORD = 10107; +pub const WSASERVICE_NOT_FOUND: ::DWORD = 10108; +pub const WSATYPE_NOT_FOUND: ::DWORD = 10109; +pub const WSA_E_NO_MORE: ::DWORD = 10110; +pub const WSA_E_CANCELLED: ::DWORD = 10111; +pub const WSAEREFUSED: ::DWORD = 10112; +pub const WSAHOST_NOT_FOUND: ::DWORD = 11001; +pub const WSATRY_AGAIN: ::DWORD = 11002; +pub const WSANO_RECOVERY: ::DWORD = 11003; +pub const WSANO_DATA: ::DWORD = 11004; +pub const WSA_QOS_RECEIVERS: ::DWORD = 11005; +pub const WSA_QOS_SENDERS: ::DWORD = 11006; +pub const WSA_QOS_NO_SENDERS: ::DWORD = 11007; +pub const WSA_QOS_NO_RECEIVERS: ::DWORD = 11008; +pub const WSA_QOS_REQUEST_CONFIRMED: ::DWORD = 11009; +pub const WSA_QOS_ADMISSION_FAILURE: ::DWORD = 11010; +pub const WSA_QOS_POLICY_FAILURE: ::DWORD = 11011; +pub const WSA_QOS_BAD_STYLE: ::DWORD = 11012; +pub const WSA_QOS_BAD_OBJECT: ::DWORD = 11013; +pub const WSA_QOS_TRAFFIC_CTRL_ERROR: ::DWORD = 11014; +pub const WSA_QOS_GENERIC_ERROR: ::DWORD = 11015; +pub const WSA_QOS_ESERVICETYPE: ::DWORD = 11016; +pub const WSA_QOS_EFLOWSPEC: ::DWORD = 11017; +pub const WSA_QOS_EPROVSPECBUF: ::DWORD = 11018; +pub const WSA_QOS_EFILTERSTYLE: ::DWORD = 11019; +pub const WSA_QOS_EFILTERTYPE: ::DWORD = 11020; +pub const WSA_QOS_EFILTERCOUNT: ::DWORD = 11021; +pub const WSA_QOS_EOBJLENGTH: ::DWORD = 11022; +pub const WSA_QOS_EFLOWCOUNT: ::DWORD = 11023; +pub const WSA_QOS_EUNKOWNPSOBJ: ::DWORD = 11024; +pub const WSA_QOS_EPOLICYOBJ: ::DWORD = 11025; +pub const WSA_QOS_EFLOWDESC: ::DWORD = 11026; +pub const WSA_QOS_EPSFLOWSPEC: ::DWORD = 11027; +pub const WSA_QOS_EPSFILTERSPEC: ::DWORD = 11028; +pub const WSA_QOS_ESDMODEOBJ: ::DWORD = 11029; +pub const WSA_QOS_ESHAPERATEOBJ: ::DWORD = 11030; +pub const WSA_QOS_RESERVED_PETYPE: ::DWORD = 11031; +pub const WSA_SECURE_HOST_NOT_FOUND: ::DWORD = 11032; +pub const WSA_IPSEC_NAME_POLICY_ERROR: ::DWORD = 11033; +pub const ERROR_IPSEC_QM_POLICY_EXISTS: ::DWORD = 13000; +pub const ERROR_IPSEC_QM_POLICY_NOT_FOUND: ::DWORD = 13001; +pub const ERROR_IPSEC_QM_POLICY_IN_USE: ::DWORD = 13002; +pub const ERROR_IPSEC_MM_POLICY_EXISTS: ::DWORD = 13003; +pub const ERROR_IPSEC_MM_POLICY_NOT_FOUND: ::DWORD = 13004; +pub const ERROR_IPSEC_MM_POLICY_IN_USE: ::DWORD = 13005; +pub const ERROR_IPSEC_MM_FILTER_EXISTS: ::DWORD = 13006; +pub const ERROR_IPSEC_MM_FILTER_NOT_FOUND: ::DWORD = 13007; +pub const ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: ::DWORD = 13008; +pub const ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: ::DWORD = 13009; +pub const ERROR_IPSEC_MM_AUTH_EXISTS: ::DWORD = 13010; +pub const ERROR_IPSEC_MM_AUTH_NOT_FOUND: ::DWORD = 13011; +pub const ERROR_IPSEC_MM_AUTH_IN_USE: ::DWORD = 13012; +pub const ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: ::DWORD = 13013; +pub const ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: ::DWORD = 13014; +pub const ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: ::DWORD = 13015; +pub const ERROR_IPSEC_TUNNEL_FILTER_EXISTS: ::DWORD = 13016; +pub const ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: ::DWORD = 13017; +pub const ERROR_IPSEC_MM_FILTER_PENDING_DELETION: ::DWORD = 13018; +pub const ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: ::DWORD = 13019; +pub const ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: ::DWORD = 13020; +pub const ERROR_IPSEC_MM_POLICY_PENDING_DELETION: ::DWORD = 13021; +pub const ERROR_IPSEC_MM_AUTH_PENDING_DELETION: ::DWORD = 13022; +pub const ERROR_IPSEC_QM_POLICY_PENDING_DELETION: ::DWORD = 13023; +pub const WARNING_IPSEC_MM_POLICY_PRUNED: ::DWORD = 13024; +pub const WARNING_IPSEC_QM_POLICY_PRUNED: ::DWORD = 13025; +pub const ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: ::DWORD = 13800; +pub const ERROR_IPSEC_IKE_AUTH_FAIL: ::DWORD = 13801; +pub const ERROR_IPSEC_IKE_ATTRIB_FAIL: ::DWORD = 13802; +pub const ERROR_IPSEC_IKE_NEGOTIATION_PENDING: ::DWORD = 13803; +pub const ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: ::DWORD = 13804; +pub const ERROR_IPSEC_IKE_TIMED_OUT: ::DWORD = 13805; +pub const ERROR_IPSEC_IKE_NO_CERT: ::DWORD = 13806; +pub const ERROR_IPSEC_IKE_SA_DELETED: ::DWORD = 13807; +pub const ERROR_IPSEC_IKE_SA_REAPED: ::DWORD = 13808; +pub const ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: ::DWORD = 13809; +pub const ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: ::DWORD = 13810; +pub const ERROR_IPSEC_IKE_QUEUE_DROP_MM: ::DWORD = 13811; +pub const ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: ::DWORD = 13812; +pub const ERROR_IPSEC_IKE_DROP_NO_RESPONSE: ::DWORD = 13813; +pub const ERROR_IPSEC_IKE_MM_DELAY_DROP: ::DWORD = 13814; +pub const ERROR_IPSEC_IKE_QM_DELAY_DROP: ::DWORD = 13815; +pub const ERROR_IPSEC_IKE_ERROR: ::DWORD = 13816; +pub const ERROR_IPSEC_IKE_CRL_FAILED: ::DWORD = 13817; +pub const ERROR_IPSEC_IKE_INVALID_KEY_USAGE: ::DWORD = 13818; +pub const ERROR_IPSEC_IKE_INVALID_CERT_TYPE: ::DWORD = 13819; +pub const ERROR_IPSEC_IKE_NO_PRIVATE_KEY: ::DWORD = 13820; +pub const ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY: ::DWORD = 13821; +pub const ERROR_IPSEC_IKE_DH_FAIL: ::DWORD = 13822; +pub const ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED: ::DWORD = 13823; +pub const ERROR_IPSEC_IKE_INVALID_HEADER: ::DWORD = 13824; +pub const ERROR_IPSEC_IKE_NO_POLICY: ::DWORD = 13825; +pub const ERROR_IPSEC_IKE_INVALID_SIGNATURE: ::DWORD = 13826; +pub const ERROR_IPSEC_IKE_KERBEROS_ERROR: ::DWORD = 13827; +pub const ERROR_IPSEC_IKE_NO_PUBLIC_KEY: ::DWORD = 13828; +pub const ERROR_IPSEC_IKE_PROCESS_ERR: ::DWORD = 13829; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_SA: ::DWORD = 13830; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_PROP: ::DWORD = 13831; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: ::DWORD = 13832; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_KE: ::DWORD = 13833; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_ID: ::DWORD = 13834; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT: ::DWORD = 13835; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: ::DWORD = 13836; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_HASH: ::DWORD = 13837; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_SIG: ::DWORD = 13838; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: ::DWORD = 13839; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: ::DWORD = 13840; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: ::DWORD = 13841; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: ::DWORD = 13842; +pub const ERROR_IPSEC_IKE_INVALID_PAYLOAD: ::DWORD = 13843; +pub const ERROR_IPSEC_IKE_LOAD_SOFT_SA: ::DWORD = 13844; +pub const ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: ::DWORD = 13845; +pub const ERROR_IPSEC_IKE_INVALID_COOKIE: ::DWORD = 13846; +pub const ERROR_IPSEC_IKE_NO_PEER_CERT: ::DWORD = 13847; +pub const ERROR_IPSEC_IKE_PEER_CRL_FAILED: ::DWORD = 13848; +pub const ERROR_IPSEC_IKE_POLICY_CHANGE: ::DWORD = 13849; +pub const ERROR_IPSEC_IKE_NO_MM_POLICY: ::DWORD = 13850; +pub const ERROR_IPSEC_IKE_NOTCBPRIV: ::DWORD = 13851; +pub const ERROR_IPSEC_IKE_SECLOADFAIL: ::DWORD = 13852; +pub const ERROR_IPSEC_IKE_FAILSSPINIT: ::DWORD = 13853; +pub const ERROR_IPSEC_IKE_FAILQUERYSSP: ::DWORD = 13854; +pub const ERROR_IPSEC_IKE_SRVACQFAIL: ::DWORD = 13855; +pub const ERROR_IPSEC_IKE_SRVQUERYCRED: ::DWORD = 13856; +pub const ERROR_IPSEC_IKE_GETSPIFAIL: ::DWORD = 13857; +pub const ERROR_IPSEC_IKE_INVALID_FILTER: ::DWORD = 13858; +pub const ERROR_IPSEC_IKE_OUT_OF_MEMORY: ::DWORD = 13859; +pub const ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: ::DWORD = 13860; +pub const ERROR_IPSEC_IKE_INVALID_POLICY: ::DWORD = 13861; +pub const ERROR_IPSEC_IKE_UNKNOWN_DOI: ::DWORD = 13862; +pub const ERROR_IPSEC_IKE_INVALID_SITUATION: ::DWORD = 13863; +pub const ERROR_IPSEC_IKE_DH_FAILURE: ::DWORD = 13864; +pub const ERROR_IPSEC_IKE_INVALID_GROUP: ::DWORD = 13865; +pub const ERROR_IPSEC_IKE_ENCRYPT: ::DWORD = 13866; +pub const ERROR_IPSEC_IKE_DECRYPT: ::DWORD = 13867; +pub const ERROR_IPSEC_IKE_POLICY_MATCH: ::DWORD = 13868; +pub const ERROR_IPSEC_IKE_UNSUPPORTED_ID: ::DWORD = 13869; +pub const ERROR_IPSEC_IKE_INVALID_HASH: ::DWORD = 13870; +pub const ERROR_IPSEC_IKE_INVALID_HASH_ALG: ::DWORD = 13871; +pub const ERROR_IPSEC_IKE_INVALID_HASH_SIZE: ::DWORD = 13872; +pub const ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: ::DWORD = 13873; +pub const ERROR_IPSEC_IKE_INVALID_AUTH_ALG: ::DWORD = 13874; +pub const ERROR_IPSEC_IKE_INVALID_SIG: ::DWORD = 13875; +pub const ERROR_IPSEC_IKE_LOAD_FAILED: ::DWORD = 13876; +pub const ERROR_IPSEC_IKE_RPC_DELETE: ::DWORD = 13877; +pub const ERROR_IPSEC_IKE_BENIGN_REINIT: ::DWORD = 13878; +pub const ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: ::DWORD = 13879; +pub const ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION: ::DWORD = 13880; +pub const ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: ::DWORD = 13881; +pub const ERROR_IPSEC_IKE_MM_LIMIT: ::DWORD = 13882; +pub const ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: ::DWORD = 13883; +pub const ERROR_IPSEC_IKE_QM_LIMIT: ::DWORD = 13884; +pub const ERROR_IPSEC_IKE_MM_EXPIRED: ::DWORD = 13885; +pub const ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: ::DWORD = 13886; +pub const ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH: ::DWORD = 13887; +pub const ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID: ::DWORD = 13888; +pub const ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD: ::DWORD = 13889; +pub const ERROR_IPSEC_IKE_DOS_COOKIE_SENT: ::DWORD = 13890; +pub const ERROR_IPSEC_IKE_SHUTTING_DOWN: ::DWORD = 13891; +pub const ERROR_IPSEC_IKE_CGA_AUTH_FAILED: ::DWORD = 13892; +pub const ERROR_IPSEC_IKE_PROCESS_ERR_NATOA: ::DWORD = 13893; +pub const ERROR_IPSEC_IKE_INVALID_MM_FOR_QM: ::DWORD = 13894; +pub const ERROR_IPSEC_IKE_QM_EXPIRED: ::DWORD = 13895; +pub const ERROR_IPSEC_IKE_TOO_MANY_FILTERS: ::DWORD = 13896; +pub const ERROR_IPSEC_IKE_NEG_STATUS_END: ::DWORD = 13897; +pub const ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL: ::DWORD = 13898; +pub const ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE: ::DWORD = 13899; +pub const ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING: ::DWORD = 13900; +pub const ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING: ::DWORD = 13901; +pub const ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS: ::DWORD = 13902; +pub const ERROR_IPSEC_IKE_RATELIMIT_DROP: ::DWORD = 13903; +pub const ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE: ::DWORD = 13904; +pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE: ::DWORD = 13905; +pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE: ::DWORD = 13906; +pub const ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY: ::DWORD = 13907; +pub const ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE: ::DWORD = 13908; +pub const ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END: ::DWORD = 13909; +pub const ERROR_IPSEC_BAD_SPI: ::DWORD = 13910; +pub const ERROR_IPSEC_SA_LIFETIME_EXPIRED: ::DWORD = 13911; +pub const ERROR_IPSEC_WRONG_SA: ::DWORD = 13912; +pub const ERROR_IPSEC_REPLAY_CHECK_FAILED: ::DWORD = 13913; +pub const ERROR_IPSEC_INVALID_PACKET: ::DWORD = 13914; +pub const ERROR_IPSEC_INTEGRITY_CHECK_FAILED: ::DWORD = 13915; +pub const ERROR_IPSEC_CLEAR_TEXT_DROP: ::DWORD = 13916; +pub const ERROR_IPSEC_AUTH_FIREWALL_DROP: ::DWORD = 13917; +pub const ERROR_IPSEC_THROTTLE_DROP: ::DWORD = 13918; +pub const ERROR_IPSEC_DOSP_BLOCK: ::DWORD = 13925; +pub const ERROR_IPSEC_DOSP_RECEIVED_MULTICAST: ::DWORD = 13926; +pub const ERROR_IPSEC_DOSP_INVALID_PACKET: ::DWORD = 13927; +pub const ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED: ::DWORD = 13928; +pub const ERROR_IPSEC_DOSP_MAX_ENTRIES: ::DWORD = 13929; +pub const ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: ::DWORD = 13930; +pub const ERROR_IPSEC_DOSP_NOT_INSTALLED: ::DWORD = 13931; +pub const ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: ::DWORD = 13932; +pub const ERROR_SXS_SECTION_NOT_FOUND: ::DWORD = 14000; +pub const ERROR_SXS_CANT_GEN_ACTCTX: ::DWORD = 14001; +pub const ERROR_SXS_INVALID_ACTCTXDATA_FORMAT: ::DWORD = 14002; +pub const ERROR_SXS_ASSEMBLY_NOT_FOUND: ::DWORD = 14003; +pub const ERROR_SXS_MANIFEST_FORMAT_ERROR: ::DWORD = 14004; +pub const ERROR_SXS_MANIFEST_PARSE_ERROR: ::DWORD = 14005; +pub const ERROR_SXS_ACTIVATION_CONTEXT_DISABLED: ::DWORD = 14006; +pub const ERROR_SXS_KEY_NOT_FOUND: ::DWORD = 14007; +pub const ERROR_SXS_VERSION_CONFLICT: ::DWORD = 14008; +pub const ERROR_SXS_WRONG_SECTION_TYPE: ::DWORD = 14009; +pub const ERROR_SXS_THREAD_QUERIES_DISABLED: ::DWORD = 14010; +pub const ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET: ::DWORD = 14011; +pub const ERROR_SXS_UNKNOWN_ENCODING_GROUP: ::DWORD = 14012; +pub const ERROR_SXS_UNKNOWN_ENCODING: ::DWORD = 14013; +pub const ERROR_SXS_INVALID_XML_NAMESPACE_URI: ::DWORD = 14014; +pub const ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED: ::DWORD = 14015; +pub const ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED: ::DWORD = 14016; +pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE: ::DWORD = 14017; +pub const ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE: ::DWORD = 14018; +pub const ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE: ::DWORD = 14019; +pub const ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT: ::DWORD = 14020; +pub const ERROR_SXS_DUPLICATE_DLL_NAME: ::DWORD = 14021; +pub const ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME: ::DWORD = 14022; +pub const ERROR_SXS_DUPLICATE_CLSID: ::DWORD = 14023; +pub const ERROR_SXS_DUPLICATE_IID: ::DWORD = 14024; +pub const ERROR_SXS_DUPLICATE_TLBID: ::DWORD = 14025; +pub const ERROR_SXS_DUPLICATE_PROGID: ::DWORD = 14026; +pub const ERROR_SXS_DUPLICATE_ASSEMBLY_NAME: ::DWORD = 14027; +pub const ERROR_SXS_FILE_HASH_MISMATCH: ::DWORD = 14028; +pub const ERROR_SXS_POLICY_PARSE_ERROR: ::DWORD = 14029; +pub const ERROR_SXS_XML_E_MISSINGQUOTE: ::DWORD = 14030; +pub const ERROR_SXS_XML_E_COMMENTSYNTAX: ::DWORD = 14031; +pub const ERROR_SXS_XML_E_BADSTARTNAMECHAR: ::DWORD = 14032; +pub const ERROR_SXS_XML_E_BADNAMECHAR: ::DWORD = 14033; +pub const ERROR_SXS_XML_E_BADCHARINSTRING: ::DWORD = 14034; +pub const ERROR_SXS_XML_E_XMLDECLSYNTAX: ::DWORD = 14035; +pub const ERROR_SXS_XML_E_BADCHARDATA: ::DWORD = 14036; +pub const ERROR_SXS_XML_E_MISSINGWHITESPACE: ::DWORD = 14037; +pub const ERROR_SXS_XML_E_EXPECTINGTAGEND: ::DWORD = 14038; +pub const ERROR_SXS_XML_E_MISSINGSEMICOLON: ::DWORD = 14039; +pub const ERROR_SXS_XML_E_UNBALANCEDPAREN: ::DWORD = 14040; +pub const ERROR_SXS_XML_E_INTERNALERROR: ::DWORD = 14041; +pub const ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE: ::DWORD = 14042; +pub const ERROR_SXS_XML_E_INCOMPLETE_ENCODING: ::DWORD = 14043; +pub const ERROR_SXS_XML_E_MISSING_PAREN: ::DWORD = 14044; +pub const ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE: ::DWORD = 14045; +pub const ERROR_SXS_XML_E_MULTIPLE_COLONS: ::DWORD = 14046; +pub const ERROR_SXS_XML_E_INVALID_DECIMAL: ::DWORD = 14047; +pub const ERROR_SXS_XML_E_INVALID_HEXIDECIMAL: ::DWORD = 14048; +pub const ERROR_SXS_XML_E_INVALID_UNICODE: ::DWORD = 14049; +pub const ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK: ::DWORD = 14050; +pub const ERROR_SXS_XML_E_UNEXPECTEDENDTAG: ::DWORD = 14051; +pub const ERROR_SXS_XML_E_UNCLOSEDTAG: ::DWORD = 14052; +pub const ERROR_SXS_XML_E_DUPLICATEATTRIBUTE: ::DWORD = 14053; +pub const ERROR_SXS_XML_E_MULTIPLEROOTS: ::DWORD = 14054; +pub const ERROR_SXS_XML_E_INVALIDATROOTLEVEL: ::DWORD = 14055; +pub const ERROR_SXS_XML_E_BADXMLDECL: ::DWORD = 14056; +pub const ERROR_SXS_XML_E_MISSINGROOT: ::DWORD = 14057; +pub const ERROR_SXS_XML_E_UNEXPECTEDEOF: ::DWORD = 14058; +pub const ERROR_SXS_XML_E_BADPEREFINSUBSET: ::DWORD = 14059; +pub const ERROR_SXS_XML_E_UNCLOSEDSTARTTAG: ::DWORD = 14060; +pub const ERROR_SXS_XML_E_UNCLOSEDENDTAG: ::DWORD = 14061; +pub const ERROR_SXS_XML_E_UNCLOSEDSTRING: ::DWORD = 14062; +pub const ERROR_SXS_XML_E_UNCLOSEDCOMMENT: ::DWORD = 14063; +pub const ERROR_SXS_XML_E_UNCLOSEDDECL: ::DWORD = 14064; +pub const ERROR_SXS_XML_E_UNCLOSEDCDATA: ::DWORD = 14065; +pub const ERROR_SXS_XML_E_RESERVEDNAMESPACE: ::DWORD = 14066; +pub const ERROR_SXS_XML_E_INVALIDENCODING: ::DWORD = 14067; +pub const ERROR_SXS_XML_E_INVALIDSWITCH: ::DWORD = 14068; +pub const ERROR_SXS_XML_E_BADXMLCASE: ::DWORD = 14069; +pub const ERROR_SXS_XML_E_INVALID_STANDALONE: ::DWORD = 14070; +pub const ERROR_SXS_XML_E_UNEXPECTED_STANDALONE: ::DWORD = 14071; +pub const ERROR_SXS_XML_E_INVALID_VERSION: ::DWORD = 14072; +pub const ERROR_SXS_XML_E_MISSINGEQUALS: ::DWORD = 14073; +pub const ERROR_SXS_PROTECTION_RECOVERY_FAILED: ::DWORD = 14074; +pub const ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT: ::DWORD = 14075; +pub const ERROR_SXS_PROTECTION_CATALOG_NOT_VALID: ::DWORD = 14076; +pub const ERROR_SXS_UNTRANSLATABLE_HRESULT: ::DWORD = 14077; +pub const ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING: ::DWORD = 14078; +pub const ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE: ::DWORD = 14079; +pub const ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME: ::DWORD = 14080; +pub const ERROR_SXS_ASSEMBLY_MISSING: ::DWORD = 14081; +pub const ERROR_SXS_CORRUPT_ACTIVATION_STACK: ::DWORD = 14082; +pub const ERROR_SXS_CORRUPTION: ::DWORD = 14083; +pub const ERROR_SXS_EARLY_DEACTIVATION: ::DWORD = 14084; +pub const ERROR_SXS_INVALID_DEACTIVATION: ::DWORD = 14085; +pub const ERROR_SXS_MULTIPLE_DEACTIVATION: ::DWORD = 14086; +pub const ERROR_SXS_PROCESS_TERMINATION_REQUESTED: ::DWORD = 14087; +pub const ERROR_SXS_RELEASE_ACTIVATION_CONTEXT: ::DWORD = 14088; +pub const ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: ::DWORD = 14089; +pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: ::DWORD = 14090; +pub const ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: ::DWORD = 14091; +pub const ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: ::DWORD = 14092; +pub const ERROR_SXS_IDENTITY_PARSE_ERROR: ::DWORD = 14093; +pub const ERROR_MALFORMED_SUBSTITUTION_STRING: ::DWORD = 14094; +pub const ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN: ::DWORD = 14095; +pub const ERROR_UNMAPPED_SUBSTITUTION_STRING: ::DWORD = 14096; +pub const ERROR_SXS_ASSEMBLY_NOT_LOCKED: ::DWORD = 14097; +pub const ERROR_SXS_COMPONENT_STORE_CORRUPT: ::DWORD = 14098; +pub const ERROR_ADVANCED_INSTALLER_FAILED: ::DWORD = 14099; +pub const ERROR_XML_ENCODING_MISMATCH: ::DWORD = 14100; +pub const ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: ::DWORD = 14101; +pub const ERROR_SXS_IDENTITIES_DIFFERENT: ::DWORD = 14102; +pub const ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: ::DWORD = 14103; +pub const ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY: ::DWORD = 14104; +pub const ERROR_SXS_MANIFEST_TOO_BIG: ::DWORD = 14105; +pub const ERROR_SXS_SETTING_NOT_REGISTERED: ::DWORD = 14106; +pub const ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE: ::DWORD = 14107; +pub const ERROR_SMI_PRIMITIVE_INSTALLER_FAILED: ::DWORD = 14108; +pub const ERROR_GENERIC_COMMAND_FAILED: ::DWORD = 14109; +pub const ERROR_SXS_FILE_HASH_MISSING: ::DWORD = 14110; +pub const ERROR_EVT_INVALID_CHANNEL_PATH: ::DWORD = 15000; +pub const ERROR_EVT_INVALID_QUERY: ::DWORD = 15001; +pub const ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND: ::DWORD = 15002; +pub const ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND: ::DWORD = 15003; +pub const ERROR_EVT_INVALID_PUBLISHER_NAME: ::DWORD = 15004; +pub const ERROR_EVT_INVALID_EVENT_DATA: ::DWORD = 15005; +pub const ERROR_EVT_CHANNEL_NOT_FOUND: ::DWORD = 15007; +pub const ERROR_EVT_MALFORMED_XML_TEXT: ::DWORD = 15008; +pub const ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL: ::DWORD = 15009; +pub const ERROR_EVT_CONFIGURATION_ERROR: ::DWORD = 15010; +pub const ERROR_EVT_QUERY_RESULT_STALE: ::DWORD = 15011; +pub const ERROR_EVT_QUERY_RESULT_INVALID_POSITION: ::DWORD = 15012; +pub const ERROR_EVT_NON_VALIDATING_MSXML: ::DWORD = 15013; +pub const ERROR_EVT_FILTER_ALREADYSCOPED: ::DWORD = 15014; +pub const ERROR_EVT_FILTER_NOTELTSET: ::DWORD = 15015; +pub const ERROR_EVT_FILTER_INVARG: ::DWORD = 15016; +pub const ERROR_EVT_FILTER_INVTEST: ::DWORD = 15017; +pub const ERROR_EVT_FILTER_INVTYPE: ::DWORD = 15018; +pub const ERROR_EVT_FILTER_PARSEERR: ::DWORD = 15019; +pub const ERROR_EVT_FILTER_UNSUPPORTEDOP: ::DWORD = 15020; +pub const ERROR_EVT_FILTER_UNEXPECTEDTOKEN: ::DWORD = 15021; +pub const ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL: ::DWORD = 15022; +pub const ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE: ::DWORD = 15023; +pub const ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE: ::DWORD = 15024; +pub const ERROR_EVT_CHANNEL_CANNOT_ACTIVATE: ::DWORD = 15025; +pub const ERROR_EVT_FILTER_TOO_COMPLEX: ::DWORD = 15026; +pub const ERROR_EVT_MESSAGE_NOT_FOUND: ::DWORD = 15027; +pub const ERROR_EVT_MESSAGE_ID_NOT_FOUND: ::DWORD = 15028; +pub const ERROR_EVT_UNRESOLVED_VALUE_INSERT: ::DWORD = 15029; +pub const ERROR_EVT_UNRESOLVED_PARAMETER_INSERT: ::DWORD = 15030; +pub const ERROR_EVT_MAX_INSERTS_REACHED: ::DWORD = 15031; +pub const ERROR_EVT_EVENT_DEFINITION_NOT_FOUND: ::DWORD = 15032; +pub const ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: ::DWORD = 15033; +pub const ERROR_EVT_VERSION_TOO_OLD: ::DWORD = 15034; +pub const ERROR_EVT_VERSION_TOO_NEW: ::DWORD = 15035; +pub const ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY: ::DWORD = 15036; +pub const ERROR_EVT_PUBLISHER_DISABLED: ::DWORD = 15037; +pub const ERROR_EVT_FILTER_OUT_OF_RANGE: ::DWORD = 15038; +pub const ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE: ::DWORD = 15080; +pub const ERROR_EC_LOG_DISABLED: ::DWORD = 15081; +pub const ERROR_EC_CIRCULAR_FORWARDING: ::DWORD = 15082; +pub const ERROR_EC_CREDSTORE_FULL: ::DWORD = 15083; +pub const ERROR_EC_CRED_NOT_FOUND: ::DWORD = 15084; +pub const ERROR_EC_NO_ACTIVE_CHANNEL: ::DWORD = 15085; +pub const ERROR_MUI_FILE_NOT_FOUND: ::DWORD = 15100; +pub const ERROR_MUI_INVALID_FILE: ::DWORD = 15101; +pub const ERROR_MUI_INVALID_RC_CONFIG: ::DWORD = 15102; +pub const ERROR_MUI_INVALID_LOCALE_NAME: ::DWORD = 15103; +pub const ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME: ::DWORD = 15104; +pub const ERROR_MUI_FILE_NOT_LOADED: ::DWORD = 15105; +pub const ERROR_RESOURCE_ENUM_USER_STOP: ::DWORD = 15106; +pub const ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED: ::DWORD = 15107; +pub const ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME: ::DWORD = 15108; +pub const ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE: ::DWORD = 15110; +pub const ERROR_MRM_INVALID_PRICONFIG: ::DWORD = 15111; +pub const ERROR_MRM_INVALID_FILE_TYPE: ::DWORD = 15112; +pub const ERROR_MRM_UNKNOWN_QUALIFIER: ::DWORD = 15113; +pub const ERROR_MRM_INVALID_QUALIFIER_VALUE: ::DWORD = 15114; +pub const ERROR_MRM_NO_CANDIDATE: ::DWORD = 15115; +pub const ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE: ::DWORD = 15116; +pub const ERROR_MRM_RESOURCE_TYPE_MISMATCH: ::DWORD = 15117; +pub const ERROR_MRM_DUPLICATE_MAP_NAME: ::DWORD = 15118; +pub const ERROR_MRM_DUPLICATE_ENTRY: ::DWORD = 15119; +pub const ERROR_MRM_INVALID_RESOURCE_IDENTIFIER: ::DWORD = 15120; +pub const ERROR_MRM_FILEPATH_TOO_LONG: ::DWORD = 15121; +pub const ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE: ::DWORD = 15122; +pub const ERROR_MRM_INVALID_PRI_FILE: ::DWORD = 15126; +pub const ERROR_MRM_NAMED_RESOURCE_NOT_FOUND: ::DWORD = 15127; +pub const ERROR_MRM_MAP_NOT_FOUND: ::DWORD = 15135; +pub const ERROR_MRM_UNSUPPORTED_PROFILE_TYPE: ::DWORD = 15136; +pub const ERROR_MRM_INVALID_QUALIFIER_OPERATOR: ::DWORD = 15137; +pub const ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE: ::DWORD = 15138; +pub const ERROR_MRM_AUTOMERGE_ENABLED: ::DWORD = 15139; +pub const ERROR_MRM_TOO_MANY_RESOURCES: ::DWORD = 15140; +pub const ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_MERGE: ::DWORD = 15141; +pub const ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_LOAD_UNLOAD_PRI_FILE: ::DWORD = 15142; +pub const ERROR_MRM_NO_CURRENT_VIEW_ON_THREAD: ::DWORD = 15143; +pub const ERROR_DIFFERENT_PROFILE_RESOURCE_MANAGER_EXIST: ::DWORD = 15144; +pub const ERROR_OPERATION_NOT_ALLOWED_FROM_SYSTEM_COMPONENT: ::DWORD = 15145; +pub const ERROR_MRM_DIRECT_REF_TO_NON_DEFAULT_RESOURCE: ::DWORD = 15146; +pub const ERROR_MRM_GENERATION_COUNT_MISMATCH: ::DWORD = 15147; +pub const ERROR_MCA_INVALID_CAPABILITIES_STRING: ::DWORD = 15200; +pub const ERROR_MCA_INVALID_VCP_VERSION: ::DWORD = 15201; +pub const ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: ::DWORD = 15202; +pub const ERROR_MCA_MCCS_VERSION_MISMATCH: ::DWORD = 15203; +pub const ERROR_MCA_UNSUPPORTED_MCCS_VERSION: ::DWORD = 15204; +pub const ERROR_MCA_INTERNAL_ERROR: ::DWORD = 15205; +pub const ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: ::DWORD = 15206; +pub const ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE: ::DWORD = 15207; +pub const ERROR_AMBIGUOUS_SYSTEM_DEVICE: ::DWORD = 15250; +pub const ERROR_SYSTEM_DEVICE_NOT_FOUND: ::DWORD = 15299; +pub const ERROR_HASH_NOT_SUPPORTED: ::DWORD = 15300; +pub const ERROR_HASH_NOT_PRESENT: ::DWORD = 15301; +pub const ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED: ::DWORD = 15321; +pub const ERROR_GPIO_CLIENT_INFORMATION_INVALID: ::DWORD = 15322; +pub const ERROR_GPIO_VERSION_NOT_SUPPORTED: ::DWORD = 15323; +pub const ERROR_GPIO_INVALID_REGISTRATION_PACKET: ::DWORD = 15324; +pub const ERROR_GPIO_OPERATION_DENIED: ::DWORD = 15325; +pub const ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE: ::DWORD = 15326; +pub const ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED: ::DWORD = 15327; +pub const ERROR_CANNOT_SWITCH_RUNLEVEL: ::DWORD = 15400; +pub const ERROR_INVALID_RUNLEVEL_SETTING: ::DWORD = 15401; +pub const ERROR_RUNLEVEL_SWITCH_TIMEOUT: ::DWORD = 15402; +pub const ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT: ::DWORD = 15403; +pub const ERROR_RUNLEVEL_SWITCH_IN_PROGRESS: ::DWORD = 15404; +pub const ERROR_SERVICES_FAILED_AUTOSTART: ::DWORD = 15405; +pub const ERROR_COM_TASK_STOP_PENDING: ::DWORD = 15501; +pub const ERROR_INSTALL_OPEN_PACKAGE_FAILED: ::DWORD = 15600; +pub const ERROR_INSTALL_PACKAGE_NOT_FOUND: ::DWORD = 15601; +pub const ERROR_INSTALL_INVALID_PACKAGE: ::DWORD = 15602; +pub const ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED: ::DWORD = 15603; +pub const ERROR_INSTALL_OUT_OF_DISK_SPACE: ::DWORD = 15604; +pub const ERROR_INSTALL_NETWORK_FAILURE: ::DWORD = 15605; +pub const ERROR_INSTALL_REGISTRATION_FAILURE: ::DWORD = 15606; +pub const ERROR_INSTALL_DEREGISTRATION_FAILURE: ::DWORD = 15607; +pub const ERROR_INSTALL_CANCEL: ::DWORD = 15608; +pub const ERROR_INSTALL_FAILED: ::DWORD = 15609; +pub const ERROR_REMOVE_FAILED: ::DWORD = 15610; +pub const ERROR_PACKAGE_ALREADY_EXISTS: ::DWORD = 15611; +pub const ERROR_NEEDS_REMEDIATION: ::DWORD = 15612; +pub const ERROR_INSTALL_PREREQUISITE_FAILED: ::DWORD = 15613; +pub const ERROR_PACKAGE_REPOSITORY_CORRUPTED: ::DWORD = 15614; +pub const ERROR_INSTALL_POLICY_FAILURE: ::DWORD = 15615; +pub const ERROR_PACKAGE_UPDATING: ::DWORD = 15616; +pub const ERROR_DEPLOYMENT_BLOCKED_BY_POLICY: ::DWORD = 15617; +pub const ERROR_PACKAGES_IN_USE: ::DWORD = 15618; +pub const ERROR_RECOVERY_FILE_CORRUPT: ::DWORD = 15619; +pub const ERROR_INVALID_STAGED_SIGNATURE: ::DWORD = 15620; +pub const ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED: ::DWORD = 15621; +pub const ERROR_INSTALL_PACKAGE_DOWNGRADE: ::DWORD = 15622; +pub const ERROR_SYSTEM_NEEDS_REMEDIATION: ::DWORD = 15623; +pub const ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN: ::DWORD = 15624; +pub const ERROR_RESILIENCY_FILE_CORRUPT: ::DWORD = 15625; +pub const ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING: ::DWORD = 15626; +pub const APPMODEL_ERROR_NO_PACKAGE: ::DWORD = 15700; +pub const APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT: ::DWORD = 15701; +pub const APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT: ::DWORD = 15702; +pub const APPMODEL_ERROR_NO_APPLICATION: ::DWORD = 15703; +pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_READ_FAILED: ::DWORD = 15704; +pub const APPMODEL_ERROR_DYNAMIC_PROPERTY_INVALID: ::DWORD = 15705; +pub const ERROR_STATE_LOAD_STORE_FAILED: ::DWORD = 15800; +pub const ERROR_STATE_GET_VERSION_FAILED: ::DWORD = 15801; +pub const ERROR_STATE_SET_VERSION_FAILED: ::DWORD = 15802; +pub const ERROR_STATE_STRUCTURED_RESET_FAILED: ::DWORD = 15803; +pub const ERROR_STATE_OPEN_CONTAINER_FAILED: ::DWORD = 15804; +pub const ERROR_STATE_CREATE_CONTAINER_FAILED: ::DWORD = 15805; +pub const ERROR_STATE_DELETE_CONTAINER_FAILED: ::DWORD = 15806; +pub const ERROR_STATE_READ_SETTING_FAILED: ::DWORD = 15807; +pub const ERROR_STATE_WRITE_SETTING_FAILED: ::DWORD = 15808; +pub const ERROR_STATE_DELETE_SETTING_FAILED: ::DWORD = 15809; +pub const ERROR_STATE_QUERY_SETTING_FAILED: ::DWORD = 15810; +pub const ERROR_STATE_READ_COMPOSITE_SETTING_FAILED: ::DWORD = 15811; +pub const ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED: ::DWORD = 15812; +pub const ERROR_STATE_ENUMERATE_CONTAINER_FAILED: ::DWORD = 15813; +pub const ERROR_STATE_ENUMERATE_SETTINGS_FAILED: ::DWORD = 15814; +pub const ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: ::DWORD = 15815; +pub const ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: ::DWORD = 15816; +pub const ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED: ::DWORD = 15817; +pub const ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED: ::DWORD = 15818; +pub const ERROR_API_UNAVAILABLE: ::DWORD = 15841; +pub const STORE_ERROR_UNLICENSED: ::DWORD = 15861; +pub const STORE_ERROR_UNLICENSED_USER: ::DWORD = 15862; +pub const STORE_ERROR_PENDING_COM_TRANSACTION: ::DWORD = 15863; +pub const STORE_ERROR_LICENSE_REVOKED: ::DWORD = 15864; +pub const SEVERITY_SUCCESS: HRESULT = 0; +pub const SEVERITY_ERROR: HRESULT = 1; +#[inline] +pub fn MAKE_HRESULT(sev: HRESULT, fac: HRESULT, code: HRESULT) -> HRESULT { + (sev << 31) | (fac << 16) | code +} +pub type HRESULT = ::c_long; +pub const NOERROR: HRESULT = 0; +pub const E_UNEXPECTED: HRESULT = 0x8000FFFFu32 as HRESULT; +pub const E_NOTIMPL: HRESULT = 0x80004001u32 as HRESULT; +pub const E_OUTOFMEMORY: HRESULT = 0x8007000Eu32 as HRESULT; +pub const E_INVALIDARG: HRESULT = 0x80070057u32 as HRESULT; +pub const E_NOINTERFACE: HRESULT = 0x80004002u32 as HRESULT; +pub const E_POINTER: HRESULT = 0x80004003u32 as HRESULT; +pub const E_HANDLE: HRESULT = 0x80070006u32 as HRESULT; +pub const E_ABORT: HRESULT = 0x80004004u32 as HRESULT; +pub const E_FAIL: HRESULT = 0x80004005u32 as HRESULT; +pub const E_ACCESSDENIED: HRESULT = 0x80070005u32 as HRESULT; +pub const E_PENDING: HRESULT = 0x8000000Au32 as HRESULT; +pub const E_BOUNDS: HRESULT = 0x8000000Bu32 as HRESULT; +pub const E_CHANGED_STATE: HRESULT = 0x8000000Cu32 as HRESULT; +pub const E_ILLEGAL_STATE_CHANGE: HRESULT = 0x8000000Du32 as HRESULT; +pub const E_ILLEGAL_METHOD_CALL: HRESULT = 0x8000000Eu32 as HRESULT; +pub const RO_E_METADATA_NAME_NOT_FOUND: HRESULT = 0x8000000Fu32 as HRESULT; +pub const RO_E_METADATA_NAME_IS_NAMESPACE: HRESULT = 0x80000010u32 as HRESULT; +pub const RO_E_METADATA_INVALID_TYPE_FORMAT: HRESULT = 0x80000011u32 as HRESULT; +pub const RO_E_INVALID_METADATA_FILE: HRESULT = 0x80000012u32 as HRESULT; +pub const RO_E_CLOSED: HRESULT = 0x80000013u32 as HRESULT; +pub const RO_E_EXCLUSIVE_WRITE: HRESULT = 0x80000014u32 as HRESULT; +pub const RO_E_CHANGE_NOTIFICATION_IN_PROGRESS: HRESULT = 0x80000015u32 as HRESULT; +pub const RO_E_ERROR_STRING_NOT_FOUND: HRESULT = 0x80000016u32 as HRESULT; +pub const E_STRING_NOT_NULL_TERMINATED: HRESULT = 0x80000017u32 as HRESULT; +pub const E_ILLEGAL_DELEGATE_ASSIGNMENT: HRESULT = 0x80000018u32 as HRESULT; +pub const E_ASYNC_OPERATION_NOT_STARTED: HRESULT = 0x80000019u32 as HRESULT; +pub const E_APPLICATION_EXITING: HRESULT = 0x8000001Au32 as HRESULT; +pub const E_APPLICATION_VIEW_EXITING: HRESULT = 0x8000001Bu32 as HRESULT; +pub const RO_E_MUST_BE_AGILE: HRESULT = 0x8000001Cu32 as HRESULT; +pub const RO_E_UNSUPPORTED_FROM_MTA: HRESULT = 0x8000001Du32 as HRESULT; +pub const RO_E_COMMITTED: HRESULT = 0x8000001Eu32 as HRESULT; +pub const RO_E_BLOCKED_CROSS_ASTA_CALL: HRESULT = 0x8000001Fu32 as HRESULT; +pub const CO_E_INIT_TLS: HRESULT = 0x80004006u32 as HRESULT; +pub const CO_E_INIT_SHARED_ALLOCATOR: HRESULT = 0x80004007u32 as HRESULT; +pub const CO_E_INIT_MEMORY_ALLOCATOR: HRESULT = 0x80004008u32 as HRESULT; +pub const CO_E_INIT_CLASS_CACHE: HRESULT = 0x80004009u32 as HRESULT; +pub const CO_E_INIT_RPC_CHANNEL: HRESULT = 0x8000400Au32 as HRESULT; +pub const CO_E_INIT_TLS_SET_CHANNEL_CONTROL: HRESULT = 0x8000400Bu32 as HRESULT; +pub const CO_E_INIT_TLS_CHANNEL_CONTROL: HRESULT = 0x8000400Cu32 as HRESULT; +pub const CO_E_INIT_UNACCEPTED_USER_ALLOCATOR: HRESULT = 0x8000400Du32 as HRESULT; +pub const CO_E_INIT_SCM_MUTEX_EXISTS: HRESULT = 0x8000400Eu32 as HRESULT; +pub const CO_E_INIT_SCM_FILE_MAPPING_EXISTS: HRESULT = 0x8000400Fu32 as HRESULT; +pub const CO_E_INIT_SCM_MAP_VIEW_OF_FILE: HRESULT = 0x80004010u32 as HRESULT; +pub const CO_E_INIT_SCM_EXEC_FAILURE: HRESULT = 0x80004011u32 as HRESULT; +pub const CO_E_INIT_ONLY_SINGLE_THREADED: HRESULT = 0x80004012u32 as HRESULT; +pub const CO_E_CANT_REMOTE: HRESULT = 0x80004013u32 as HRESULT; +pub const CO_E_BAD_SERVER_NAME: HRESULT = 0x80004014u32 as HRESULT; +pub const CO_E_WRONG_SERVER_IDENTITY: HRESULT = 0x80004015u32 as HRESULT; +pub const CO_E_OLE1DDE_DISABLED: HRESULT = 0x80004016u32 as HRESULT; +pub const CO_E_RUNAS_SYNTAX: HRESULT = 0x80004017u32 as HRESULT; +pub const CO_E_CREATEPROCESS_FAILURE: HRESULT = 0x80004018u32 as HRESULT; +pub const CO_E_RUNAS_CREATEPROCESS_FAILURE: HRESULT = 0x80004019u32 as HRESULT; +pub const CO_E_RUNAS_LOGON_FAILURE: HRESULT = 0x8000401Au32 as HRESULT; +pub const CO_E_LAUNCH_PERMSSION_DENIED: HRESULT = 0x8000401Bu32 as HRESULT; +pub const CO_E_START_SERVICE_FAILURE: HRESULT = 0x8000401Cu32 as HRESULT; +pub const CO_E_REMOTE_COMMUNICATION_FAILURE: HRESULT = 0x8000401Du32 as HRESULT; +pub const CO_E_SERVER_START_TIMEOUT: HRESULT = 0x8000401Eu32 as HRESULT; +pub const CO_E_CLSREG_INCONSISTENT: HRESULT = 0x8000401Fu32 as HRESULT; +pub const CO_E_IIDREG_INCONSISTENT: HRESULT = 0x80004020u32 as HRESULT; +pub const CO_E_NOT_SUPPORTED: HRESULT = 0x80004021u32 as HRESULT; +pub const CO_E_RELOAD_DLL: HRESULT = 0x80004022u32 as HRESULT; +pub const CO_E_MSI_ERROR: HRESULT = 0x80004023u32 as HRESULT; +pub const CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT: HRESULT = 0x80004024u32 as HRESULT; +pub const CO_E_SERVER_PAUSED: HRESULT = 0x80004025u32 as HRESULT; +pub const CO_E_SERVER_NOT_PAUSED: HRESULT = 0x80004026u32 as HRESULT; +pub const CO_E_CLASS_DISABLED: HRESULT = 0x80004027u32 as HRESULT; +pub const CO_E_CLRNOTAVAILABLE: HRESULT = 0x80004028u32 as HRESULT; +pub const CO_E_ASYNC_WORK_REJECTED: HRESULT = 0x80004029u32 as HRESULT; +pub const CO_E_SERVER_INIT_TIMEOUT: HRESULT = 0x8000402Au32 as HRESULT; +pub const CO_E_NO_SECCTX_IN_ACTIVATE: HRESULT = 0x8000402Bu32 as HRESULT; +pub const CO_E_TRACKER_CONFIG: HRESULT = 0x80004030u32 as HRESULT; +pub const CO_E_THREADPOOL_CONFIG: HRESULT = 0x80004031u32 as HRESULT; +pub const CO_E_SXS_CONFIG: HRESULT = 0x80004032u32 as HRESULT; +pub const CO_E_MALFORMED_SPN: HRESULT = 0x80004033u32 as HRESULT; +pub const CO_E_UNREVOKED_REGISTRATION_ON_APARTMENT_SHUTDOWN: HRESULT = 0x80004034u32 as HRESULT; +pub const CO_E_PREMATURE_STUB_RUNDOWN: HRESULT = 0x80004035u32 as HRESULT; +pub const S_OK: HRESULT = 0; +pub const S_FALSE: HRESULT = 1; +pub const OLE_E_FIRST: HRESULT = 0x80040000u32 as HRESULT; +pub const OLE_E_LAST: HRESULT = 0x800400FFu32 as HRESULT; +pub const OLE_S_FIRST: HRESULT = 0x00040000; +pub const OLE_S_LAST: HRESULT = 0x000400FF; +pub const OLE_E_OLEVERB: HRESULT = 0x80040000u32 as HRESULT; +pub const OLE_E_ADVF: HRESULT = 0x80040001u32 as HRESULT; +pub const OLE_E_ENUM_NOMORE: HRESULT = 0x80040002u32 as HRESULT; +pub const OLE_E_ADVISENOTSUPPORTED: HRESULT = 0x80040003u32 as HRESULT; +pub const OLE_E_NOCONNECTION: HRESULT = 0x80040004u32 as HRESULT; +pub const OLE_E_NOTRUNNING: HRESULT = 0x80040005u32 as HRESULT; +pub const OLE_E_NOCACHE: HRESULT = 0x80040006u32 as HRESULT; +pub const OLE_E_BLANK: HRESULT = 0x80040007u32 as HRESULT; +pub const OLE_E_CLASSDIFF: HRESULT = 0x80040008u32 as HRESULT; +pub const OLE_E_CANT_GETMONIKER: HRESULT = 0x80040009u32 as HRESULT; +pub const OLE_E_CANT_BINDTOSOURCE: HRESULT = 0x8004000Au32 as HRESULT; +pub const OLE_E_STATIC: HRESULT = 0x8004000Bu32 as HRESULT; +pub const OLE_E_PROMPTSAVECANCELLED: HRESULT = 0x8004000Cu32 as HRESULT; +pub const OLE_E_INVALIDRECT: HRESULT = 0x8004000Du32 as HRESULT; +pub const OLE_E_WRONGCOMPOBJ: HRESULT = 0x8004000Eu32 as HRESULT; +pub const OLE_E_INVALIDHWND: HRESULT = 0x8004000Fu32 as HRESULT; +pub const OLE_E_NOT_INPLACEACTIVE: HRESULT = 0x80040010u32 as HRESULT; +pub const OLE_E_CANTCONVERT: HRESULT = 0x80040011u32 as HRESULT; +pub const OLE_E_NOSTORAGE: HRESULT = 0x80040012u32 as HRESULT; +pub const DV_E_FORMATETC: HRESULT = 0x80040064u32 as HRESULT; +pub const DV_E_DVTARGETDEVICE: HRESULT = 0x80040065u32 as HRESULT; +pub const DV_E_STGMEDIUM: HRESULT = 0x80040066u32 as HRESULT; +pub const DV_E_STATDATA: HRESULT = 0x80040067u32 as HRESULT; +pub const DV_E_LINDEX: HRESULT = 0x80040068u32 as HRESULT; +pub const DV_E_TYMED: HRESULT = 0x80040069u32 as HRESULT; +pub const DV_E_CLIPFORMAT: HRESULT = 0x8004006Au32 as HRESULT; +pub const DV_E_DVASPECT: HRESULT = 0x8004006Bu32 as HRESULT; +pub const DV_E_DVTARGETDEVICE_SIZE: HRESULT = 0x8004006Cu32 as HRESULT; +pub const DV_E_NOIVIEWOBJECT: HRESULT = 0x8004006Du32 as HRESULT; +pub const DRAGDROP_E_FIRST: HRESULT = 0x80040100u32 as HRESULT; +pub const DRAGDROP_E_LAST: HRESULT = 0x8004010Fu32 as HRESULT; +pub const DRAGDROP_S_FIRST: HRESULT = 0x00040100; +pub const DRAGDROP_S_LAST: HRESULT = 0x0004010F; +pub const DRAGDROP_E_NOTREGISTERED: HRESULT = 0x80040100u32 as HRESULT; +pub const DRAGDROP_E_ALREADYREGISTERED: HRESULT = 0x80040101u32 as HRESULT; +pub const DRAGDROP_E_INVALIDHWND: HRESULT = 0x80040102u32 as HRESULT; +pub const DRAGDROP_E_CONCURRENT_DRAG_ATTEMPTED: HRESULT = 0x80040103u32 as HRESULT; +pub const CLASSFACTORY_E_FIRST: HRESULT = 0x80040110u32 as HRESULT; +pub const CLASSFACTORY_E_LAST: HRESULT = 0x8004011Fu32 as HRESULT; +pub const CLASSFACTORY_S_FIRST: HRESULT = 0x00040110; +pub const CLASSFACTORY_S_LAST: HRESULT = 0x0004011F; +pub const CLASS_E_NOAGGREGATION: HRESULT = 0x80040110u32 as HRESULT; +pub const CLASS_E_CLASSNOTAVAILABLE: HRESULT = 0x80040111u32 as HRESULT; +pub const CLASS_E_NOTLICENSED: HRESULT = 0x80040112u32 as HRESULT; +pub const MARSHAL_E_FIRST: HRESULT = 0x80040120u32 as HRESULT; +pub const MARSHAL_E_LAST: HRESULT = 0x8004012Fu32 as HRESULT; +pub const MARSHAL_S_FIRST: HRESULT = 0x00040120; +pub const MARSHAL_S_LAST: HRESULT = 0x0004012F; +pub const DATA_E_FIRST: HRESULT = 0x80040130u32 as HRESULT; +pub const DATA_E_LAST: HRESULT = 0x8004013Fu32 as HRESULT; +pub const DATA_S_FIRST: HRESULT = 0x00040130; +pub const DATA_S_LAST: HRESULT = 0x0004013F; +pub const VIEW_E_FIRST: HRESULT = 0x80040140u32 as HRESULT; +pub const VIEW_E_LAST: HRESULT = 0x8004014Fu32 as HRESULT; +pub const VIEW_S_FIRST: HRESULT = 0x00040140; +pub const VIEW_S_LAST: HRESULT = 0x0004014F; +pub const VIEW_E_DRAW: HRESULT = 0x80040140u32 as HRESULT; +pub const REGDB_E_FIRST: HRESULT = 0x80040150u32 as HRESULT; +pub const REGDB_E_LAST: HRESULT = 0x8004015Fu32 as HRESULT; +pub const REGDB_S_FIRST: HRESULT = 0x00040150; +pub const REGDB_S_LAST: HRESULT = 0x0004015F; +pub const REGDB_E_READREGDB: HRESULT = 0x80040150u32 as HRESULT; +pub const REGDB_E_WRITEREGDB: HRESULT = 0x80040151u32 as HRESULT; +pub const REGDB_E_KEYMISSING: HRESULT = 0x80040152u32 as HRESULT; +pub const REGDB_E_INVALIDVALUE: HRESULT = 0x80040153u32 as HRESULT; +pub const REGDB_E_CLASSNOTREG: HRESULT = 0x80040154u32 as HRESULT; +pub const REGDB_E_IIDNOTREG: HRESULT = 0x80040155u32 as HRESULT; +pub const REGDB_E_BADTHREADINGMODEL: HRESULT = 0x80040156u32 as HRESULT; +pub const CAT_E_FIRST: HRESULT = 0x80040160u32 as HRESULT; +pub const CAT_E_LAST: HRESULT = 0x80040161u32 as HRESULT; +pub const CAT_E_CATIDNOEXIST: HRESULT = 0x80040160u32 as HRESULT; +pub const CAT_E_NODESCRIPTION: HRESULT = 0x80040161u32 as HRESULT; +pub const CS_E_FIRST: HRESULT = 0x80040164u32 as HRESULT; +pub const CS_E_LAST: HRESULT = 0x8004016Fu32 as HRESULT; +pub const CS_E_PACKAGE_NOTFOUND: HRESULT = 0x80040164u32 as HRESULT; +pub const CS_E_NOT_DELETABLE: HRESULT = 0x80040165u32 as HRESULT; +pub const CS_E_CLASS_NOTFOUND: HRESULT = 0x80040166u32 as HRESULT; +pub const CS_E_INVALID_VERSION: HRESULT = 0x80040167u32 as HRESULT; +pub const CS_E_NO_CLASSSTORE: HRESULT = 0x80040168u32 as HRESULT; +pub const CS_E_OBJECT_NOTFOUND: HRESULT = 0x80040169u32 as HRESULT; +pub const CS_E_OBJECT_ALREADY_EXISTS: HRESULT = 0x8004016Au32 as HRESULT; +pub const CS_E_INVALID_PATH: HRESULT = 0x8004016Bu32 as HRESULT; +pub const CS_E_NETWORK_ERROR: HRESULT = 0x8004016Cu32 as HRESULT; +pub const CS_E_ADMIN_LIMIT_EXCEEDED: HRESULT = 0x8004016Du32 as HRESULT; +pub const CS_E_SCHEMA_MISMATCH: HRESULT = 0x8004016Eu32 as HRESULT; +pub const CS_E_INTERNAL_ERROR: HRESULT = 0x8004016Fu32 as HRESULT; +pub const CACHE_E_FIRST: HRESULT = 0x80040170u32 as HRESULT; +pub const CACHE_E_LAST: HRESULT = 0x8004017Fu32 as HRESULT; +pub const CACHE_S_FIRST: HRESULT = 0x00040170; +pub const CACHE_S_LAST: HRESULT = 0x0004017F; +pub const CACHE_E_NOCACHE_UPDATED: HRESULT = 0x80040170u32 as HRESULT; +pub const OLEOBJ_E_FIRST: HRESULT = 0x80040180u32 as HRESULT; +pub const OLEOBJ_E_LAST: HRESULT = 0x8004018Fu32 as HRESULT; +pub const OLEOBJ_S_FIRST: HRESULT = 0x00040180; +pub const OLEOBJ_S_LAST: HRESULT = 0x0004018F; +pub const OLEOBJ_E_NOVERBS: HRESULT = 0x80040180u32 as HRESULT; +pub const OLEOBJ_E_INVALIDVERB: HRESULT = 0x80040181u32 as HRESULT; +pub const CLIENTSITE_E_FIRST: HRESULT = 0x80040190u32 as HRESULT; +pub const CLIENTSITE_E_LAST: HRESULT = 0x8004019Fu32 as HRESULT; +pub const CLIENTSITE_S_FIRST: HRESULT = 0x00040190; +pub const CLIENTSITE_S_LAST: HRESULT = 0x0004019F; +pub const INPLACE_E_NOTUNDOABLE: HRESULT = 0x800401A0u32 as HRESULT; +pub const INPLACE_E_NOTOOLSPACE: HRESULT = 0x800401A1u32 as HRESULT; +pub const INPLACE_E_FIRST: HRESULT = 0x800401A0u32 as HRESULT; +pub const INPLACE_E_LAST: HRESULT = 0x800401AFu32 as HRESULT; +pub const INPLACE_S_FIRST: HRESULT = 0x000401A0; +pub const INPLACE_S_LAST: HRESULT = 0x000401AF; +pub const ENUM_E_FIRST: HRESULT = 0x800401B0u32 as HRESULT; +pub const ENUM_E_LAST: HRESULT = 0x800401BFu32 as HRESULT; +pub const ENUM_S_FIRST: HRESULT = 0x000401B0; +pub const ENUM_S_LAST: HRESULT = 0x000401BF; +pub const CONVERT10_E_FIRST: HRESULT = 0x800401C0u32 as HRESULT; +pub const CONVERT10_E_LAST: HRESULT = 0x800401CFu32 as HRESULT; +pub const CONVERT10_S_FIRST: HRESULT = 0x000401C0; +pub const CONVERT10_S_LAST: HRESULT = 0x000401CF; +pub const CONVERT10_E_OLESTREAM_GET: HRESULT = 0x800401C0u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_PUT: HRESULT = 0x800401C1u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_FMT: HRESULT = 0x800401C2u32 as HRESULT; +pub const CONVERT10_E_OLESTREAM_BITMAP_TO_DIB: HRESULT = 0x800401C3u32 as HRESULT; +pub const CONVERT10_E_STG_FMT: HRESULT = 0x800401C4u32 as HRESULT; +pub const CONVERT10_E_STG_NO_STD_STREAM: HRESULT = 0x800401C5u32 as HRESULT; +pub const CONVERT10_E_STG_DIB_TO_BITMAP: HRESULT = 0x800401C6u32 as HRESULT; +pub const CLIPBRD_E_FIRST: HRESULT = 0x800401D0u32 as HRESULT; +pub const CLIPBRD_E_LAST: HRESULT = 0x800401DFu32 as HRESULT; +pub const CLIPBRD_S_FIRST: HRESULT = 0x000401D0; +pub const CLIPBRD_S_LAST: HRESULT = 0x000401DF; +pub const CLIPBRD_E_CANT_OPEN: HRESULT = 0x800401D0u32 as HRESULT; +pub const CLIPBRD_E_CANT_EMPTY: HRESULT = 0x800401D1u32 as HRESULT; +pub const CLIPBRD_E_CANT_SET: HRESULT = 0x800401D2u32 as HRESULT; +pub const CLIPBRD_E_BAD_DATA: HRESULT = 0x800401D3u32 as HRESULT; +pub const CLIPBRD_E_CANT_CLOSE: HRESULT = 0x800401D4u32 as HRESULT; +pub const MK_E_FIRST: HRESULT = 0x800401E0u32 as HRESULT; +pub const MK_E_LAST: HRESULT = 0x800401EFu32 as HRESULT; +pub const MK_S_FIRST: HRESULT = 0x000401E0; +pub const MK_S_LAST: HRESULT = 0x000401EF; +pub const MK_E_CONNECTMANUALLY: HRESULT = 0x800401E0u32 as HRESULT; +pub const MK_E_EXCEEDEDDEADLINE: HRESULT = 0x800401E1u32 as HRESULT; +pub const MK_E_NEEDGENERIC: HRESULT = 0x800401E2u32 as HRESULT; +pub const MK_E_UNAVAILABLE: HRESULT = 0x800401E3u32 as HRESULT; +pub const MK_E_SYNTAX: HRESULT = 0x800401E4u32 as HRESULT; +pub const MK_E_NOOBJECT: HRESULT = 0x800401E5u32 as HRESULT; +pub const MK_E_INVALIDEXTENSION: HRESULT = 0x800401E6u32 as HRESULT; +pub const MK_E_INTERMEDIATEINTERFACENOTSUPPORTED: HRESULT = 0x800401E7u32 as HRESULT; +pub const MK_E_NOTBINDABLE: HRESULT = 0x800401E8u32 as HRESULT; +pub const MK_E_NOTBOUND: HRESULT = 0x800401E9u32 as HRESULT; +pub const MK_E_CANTOPENFILE: HRESULT = 0x800401EAu32 as HRESULT; +pub const MK_E_MUSTBOTHERUSER: HRESULT = 0x800401EBu32 as HRESULT; +pub const MK_E_NOINVERSE: HRESULT = 0x800401ECu32 as HRESULT; +pub const MK_E_NOSTORAGE: HRESULT = 0x800401EDu32 as HRESULT; +pub const MK_E_NOPREFIX: HRESULT = 0x800401EEu32 as HRESULT; +pub const MK_E_ENUMERATION_FAILED: HRESULT = 0x800401EFu32 as HRESULT; +pub const CO_E_FIRST: HRESULT = 0x800401F0u32 as HRESULT; +pub const CO_E_LAST: HRESULT = 0x800401FFu32 as HRESULT; +pub const CO_S_FIRST: HRESULT = 0x000401F0; +pub const CO_S_LAST: HRESULT = 0x000401FF; +pub const CO_E_NOTINITIALIZED: HRESULT = 0x800401F0u32 as HRESULT; +pub const CO_E_ALREADYINITIALIZED: HRESULT = 0x800401F1u32 as HRESULT; +pub const CO_E_CANTDETERMINECLASS: HRESULT = 0x800401F2u32 as HRESULT; +pub const CO_E_CLASSSTRING: HRESULT = 0x800401F3u32 as HRESULT; +pub const CO_E_IIDSTRING: HRESULT = 0x800401F4u32 as HRESULT; +pub const CO_E_APPNOTFOUND: HRESULT = 0x800401F5u32 as HRESULT; +pub const CO_E_APPSINGLEUSE: HRESULT = 0x800401F6u32 as HRESULT; +pub const CO_E_ERRORINAPP: HRESULT = 0x800401F7u32 as HRESULT; +pub const CO_E_DLLNOTFOUND: HRESULT = 0x800401F8u32 as HRESULT; +pub const CO_E_ERRORINDLL: HRESULT = 0x800401F9u32 as HRESULT; +pub const CO_E_WRONGOSFORAPP: HRESULT = 0x800401FAu32 as HRESULT; +pub const CO_E_OBJNOTREG: HRESULT = 0x800401FBu32 as HRESULT; +pub const CO_E_OBJISREG: HRESULT = 0x800401FCu32 as HRESULT; +pub const CO_E_OBJNOTCONNECTED: HRESULT = 0x800401FDu32 as HRESULT; +pub const CO_E_APPDIDNTREG: HRESULT = 0x800401FEu32 as HRESULT; +pub const CO_E_RELEASED: HRESULT = 0x800401FFu32 as HRESULT; +pub const EVENT_E_FIRST: HRESULT = 0x80040200u32 as HRESULT; +pub const EVENT_E_LAST: HRESULT = 0x8004021Fu32 as HRESULT; +pub const EVENT_S_FIRST: HRESULT = 0x00040200; +pub const EVENT_S_LAST: HRESULT = 0x0004021F; +pub const EVENT_S_SOME_SUBSCRIBERS_FAILED: HRESULT = 0x00040200; +pub const EVENT_E_ALL_SUBSCRIBERS_FAILED: HRESULT = 0x80040201u32 as HRESULT; +pub const EVENT_S_NOSUBSCRIBERS: HRESULT = 0x00040202; +pub const EVENT_E_QUERYSYNTAX: HRESULT = 0x80040203u32 as HRESULT; +pub const EVENT_E_QUERYFIELD: HRESULT = 0x80040204u32 as HRESULT; +pub const EVENT_E_INTERNALEXCEPTION: HRESULT = 0x80040205u32 as HRESULT; +pub const EVENT_E_INTERNALERROR: HRESULT = 0x80040206u32 as HRESULT; +pub const EVENT_E_INVALID_PER_USER_SID: HRESULT = 0x80040207u32 as HRESULT; +pub const EVENT_E_USER_EXCEPTION: HRESULT = 0x80040208u32 as HRESULT; +pub const EVENT_E_TOO_MANY_METHODS: HRESULT = 0x80040209u32 as HRESULT; +pub const EVENT_E_MISSING_EVENTCLASS: HRESULT = 0x8004020Au32 as HRESULT; +pub const EVENT_E_NOT_ALL_REMOVED: HRESULT = 0x8004020Bu32 as HRESULT; +pub const EVENT_E_COMPLUS_NOT_INSTALLED: HRESULT = 0x8004020Cu32 as HRESULT; +pub const EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT: HRESULT = 0x8004020Du32 as HRESULT; +pub const EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT: HRESULT = 0x8004020Eu32 as HRESULT; +pub const EVENT_E_INVALID_EVENT_CLASS_PARTITION: HRESULT = 0x8004020Fu32 as HRESULT; +pub const EVENT_E_PER_USER_SID_NOT_LOGGED_ON: HRESULT = 0x80040210u32 as HRESULT; +pub const TPC_E_INVALID_PROPERTY: HRESULT = 0x80040241u32 as HRESULT; +pub const TPC_E_NO_DEFAULT_TABLET: HRESULT = 0x80040212u32 as HRESULT; +pub const TPC_E_UNKNOWN_PROPERTY: HRESULT = 0x8004021Bu32 as HRESULT; +pub const TPC_E_INVALID_INPUT_RECT: HRESULT = 0x80040219u32 as HRESULT; +pub const TPC_E_INVALID_STROKE: HRESULT = 0x80040222u32 as HRESULT; +pub const TPC_E_INITIALIZE_FAIL: HRESULT = 0x80040223u32 as HRESULT; +pub const TPC_E_NOT_RELEVANT: HRESULT = 0x80040232u32 as HRESULT; +pub const TPC_E_INVALID_PACKET_DESCRIPTION: HRESULT = 0x80040233u32 as HRESULT; +pub const TPC_E_RECOGNIZER_NOT_REGISTERED: HRESULT = 0x80040235u32 as HRESULT; +pub const TPC_E_INVALID_RIGHTS: HRESULT = 0x80040236u32 as HRESULT; +pub const TPC_E_OUT_OF_ORDER_CALL: HRESULT = 0x80040237u32 as HRESULT; +pub const TPC_E_QUEUE_FULL: HRESULT = 0x80040238u32 as HRESULT; +pub const TPC_E_INVALID_CONFIGURATION: HRESULT = 0x80040239u32 as HRESULT; +pub const TPC_E_INVALID_DATA_FROM_RECOGNIZER: HRESULT = 0x8004023Au32 as HRESULT; +pub const TPC_S_TRUNCATED: HRESULT = 0x00040252; +pub const TPC_S_INTERRUPTED: HRESULT = 0x00040253; +pub const TPC_S_NO_DATA_TO_PROCESS: HRESULT = 0x00040254; +pub const XACT_E_FIRST: HRESULT = 0x8004D000u32 as HRESULT; +pub const XACT_E_LAST: HRESULT = 0x8004D02Bu32 as HRESULT; +pub const XACT_S_FIRST: HRESULT = 0x0004D000; +pub const XACT_S_LAST: HRESULT = 0x0004D010; +pub const XACT_E_ALREADYOTHERSINGLEPHASE: HRESULT = 0x8004D000u32 as HRESULT; +pub const XACT_E_CANTRETAIN: HRESULT = 0x8004D001u32 as HRESULT; +pub const XACT_E_COMMITFAILED: HRESULT = 0x8004D002u32 as HRESULT; +pub const XACT_E_COMMITPREVENTED: HRESULT = 0x8004D003u32 as HRESULT; +pub const XACT_E_HEURISTICABORT: HRESULT = 0x8004D004u32 as HRESULT; +pub const XACT_E_HEURISTICCOMMIT: HRESULT = 0x8004D005u32 as HRESULT; +pub const XACT_E_HEURISTICDAMAGE: HRESULT = 0x8004D006u32 as HRESULT; +pub const XACT_E_HEURISTICDANGER: HRESULT = 0x8004D007u32 as HRESULT; +pub const XACT_E_ISOLATIONLEVEL: HRESULT = 0x8004D008u32 as HRESULT; +pub const XACT_E_NOASYNC: HRESULT = 0x8004D009u32 as HRESULT; +pub const XACT_E_NOENLIST: HRESULT = 0x8004D00Au32 as HRESULT; +pub const XACT_E_NOISORETAIN: HRESULT = 0x8004D00Bu32 as HRESULT; +pub const XACT_E_NORESOURCE: HRESULT = 0x8004D00Cu32 as HRESULT; +pub const XACT_E_NOTCURRENT: HRESULT = 0x8004D00Du32 as HRESULT; +pub const XACT_E_NOTRANSACTION: HRESULT = 0x8004D00Eu32 as HRESULT; +pub const XACT_E_NOTSUPPORTED: HRESULT = 0x8004D00Fu32 as HRESULT; +pub const XACT_E_UNKNOWNRMGRID: HRESULT = 0x8004D010u32 as HRESULT; +pub const XACT_E_WRONGSTATE: HRESULT = 0x8004D011u32 as HRESULT; +pub const XACT_E_WRONGUOW: HRESULT = 0x8004D012u32 as HRESULT; +pub const XACT_E_XTIONEXISTS: HRESULT = 0x8004D013u32 as HRESULT; +pub const XACT_E_NOIMPORTOBJECT: HRESULT = 0x8004D014u32 as HRESULT; +pub const XACT_E_INVALIDCOOKIE: HRESULT = 0x8004D015u32 as HRESULT; +pub const XACT_E_INDOUBT: HRESULT = 0x8004D016u32 as HRESULT; +pub const XACT_E_NOTIMEOUT: HRESULT = 0x8004D017u32 as HRESULT; +pub const XACT_E_ALREADYINPROGRESS: HRESULT = 0x8004D018u32 as HRESULT; +pub const XACT_E_ABORTED: HRESULT = 0x8004D019u32 as HRESULT; +pub const XACT_E_LOGFULL: HRESULT = 0x8004D01Au32 as HRESULT; +pub const XACT_E_TMNOTAVAILABLE: HRESULT = 0x8004D01Bu32 as HRESULT; +pub const XACT_E_CONNECTION_DOWN: HRESULT = 0x8004D01Cu32 as HRESULT; +pub const XACT_E_CONNECTION_DENIED: HRESULT = 0x8004D01Du32 as HRESULT; +pub const XACT_E_REENLISTTIMEOUT: HRESULT = 0x8004D01Eu32 as HRESULT; +pub const XACT_E_TIP_CONNECT_FAILED: HRESULT = 0x8004D01Fu32 as HRESULT; +pub const XACT_E_TIP_PROTOCOL_ERROR: HRESULT = 0x8004D020u32 as HRESULT; +pub const XACT_E_TIP_PULL_FAILED: HRESULT = 0x8004D021u32 as HRESULT; +pub const XACT_E_DEST_TMNOTAVAILABLE: HRESULT = 0x8004D022u32 as HRESULT; +pub const XACT_E_TIP_DISABLED: HRESULT = 0x8004D023u32 as HRESULT; +pub const XACT_E_NETWORK_TX_DISABLED: HRESULT = 0x8004D024u32 as HRESULT; +pub const XACT_E_PARTNER_NETWORK_TX_DISABLED: HRESULT = 0x8004D025u32 as HRESULT; +pub const XACT_E_XA_TX_DISABLED: HRESULT = 0x8004D026u32 as HRESULT; +pub const XACT_E_UNABLE_TO_READ_DTC_CONFIG: HRESULT = 0x8004D027u32 as HRESULT; +pub const XACT_E_UNABLE_TO_LOAD_DTC_PROXY: HRESULT = 0x8004D028u32 as HRESULT; +pub const XACT_E_ABORTING: HRESULT = 0x8004D029u32 as HRESULT; +pub const XACT_E_PUSH_COMM_FAILURE: HRESULT = 0x8004D02Au32 as HRESULT; +pub const XACT_E_PULL_COMM_FAILURE: HRESULT = 0x8004D02Bu32 as HRESULT; +pub const XACT_E_LU_TX_DISABLED: HRESULT = 0x8004D02Cu32 as HRESULT; +pub const XACT_E_CLERKNOTFOUND: HRESULT = 0x8004D080u32 as HRESULT; +pub const XACT_E_CLERKEXISTS: HRESULT = 0x8004D081u32 as HRESULT; +pub const XACT_E_RECOVERYINPROGRESS: HRESULT = 0x8004D082u32 as HRESULT; +pub const XACT_E_TRANSACTIONCLOSED: HRESULT = 0x8004D083u32 as HRESULT; +pub const XACT_E_INVALIDLSN: HRESULT = 0x8004D084u32 as HRESULT; +pub const XACT_E_REPLAYREQUEST: HRESULT = 0x8004D085u32 as HRESULT; +pub const XACT_S_ASYNC: HRESULT = 0x0004D000; +pub const XACT_S_DEFECT: HRESULT = 0x0004D001; +pub const XACT_S_READONLY: HRESULT = 0x0004D002; +pub const XACT_S_SOMENORETAIN: HRESULT = 0x0004D003; +pub const XACT_S_OKINFORM: HRESULT = 0x0004D004; +pub const XACT_S_MADECHANGESCONTENT: HRESULT = 0x0004D005; +pub const XACT_S_MADECHANGESINFORM: HRESULT = 0x0004D006; +pub const XACT_S_ALLNORETAIN: HRESULT = 0x0004D007; +pub const XACT_S_ABORTING: HRESULT = 0x0004D008; +pub const XACT_S_SINGLEPHASE: HRESULT = 0x0004D009; +pub const XACT_S_LOCALLY_OK: HRESULT = 0x0004D00A; +pub const XACT_S_LASTRESOURCEMANAGER: HRESULT = 0x0004D010; +pub const CONTEXT_E_FIRST: HRESULT = 0x8004E000u32 as HRESULT; +pub const CONTEXT_E_LAST: HRESULT = 0x8004E02Fu32 as HRESULT; +pub const CONTEXT_S_FIRST: HRESULT = 0x0004E000; +pub const CONTEXT_S_LAST: HRESULT = 0x0004E02F; +pub const CONTEXT_E_ABORTED: HRESULT = 0x8004E002u32 as HRESULT; +pub const CONTEXT_E_ABORTING: HRESULT = 0x8004E003u32 as HRESULT; +pub const CONTEXT_E_NOCONTEXT: HRESULT = 0x8004E004u32 as HRESULT; +pub const CONTEXT_E_WOULD_DEADLOCK: HRESULT = 0x8004E005u32 as HRESULT; +pub const CONTEXT_E_SYNCH_TIMEOUT: HRESULT = 0x8004E006u32 as HRESULT; +pub const CONTEXT_E_OLDREF: HRESULT = 0x8004E007u32 as HRESULT; +pub const CONTEXT_E_ROLENOTFOUND: HRESULT = 0x8004E00Cu32 as HRESULT; +pub const CONTEXT_E_TMNOTAVAILABLE: HRESULT = 0x8004E00Fu32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED: HRESULT = 0x8004E021u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_EVENTLOGGED: HRESULT = 0x8004E022u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_CATALOGERROR: HRESULT = 0x8004E023u32 as HRESULT; +pub const CO_E_ACTIVATIONFAILED_TIMEOUT: HRESULT = 0x8004E024u32 as HRESULT; +pub const CO_E_INITIALIZATIONFAILED: HRESULT = 0x8004E025u32 as HRESULT; +pub const CONTEXT_E_NOJIT: HRESULT = 0x8004E026u32 as HRESULT; +pub const CONTEXT_E_NOTRANSACTION: HRESULT = 0x8004E027u32 as HRESULT; +pub const CO_E_THREADINGMODEL_CHANGED: HRESULT = 0x8004E028u32 as HRESULT; +pub const CO_E_NOIISINTRINSICS: HRESULT = 0x8004E029u32 as HRESULT; +pub const CO_E_NOCOOKIES: HRESULT = 0x8004E02Au32 as HRESULT; +pub const CO_E_DBERROR: HRESULT = 0x8004E02Bu32 as HRESULT; +pub const CO_E_NOTPOOLED: HRESULT = 0x8004E02Cu32 as HRESULT; +pub const CO_E_NOTCONSTRUCTED: HRESULT = 0x8004E02Du32 as HRESULT; +pub const CO_E_NOSYNCHRONIZATION: HRESULT = 0x8004E02Eu32 as HRESULT; +pub const CO_E_ISOLEVELMISMATCH: HRESULT = 0x8004E02Fu32 as HRESULT; +pub const CO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED: HRESULT = 0x8004E030u32 as HRESULT; +pub const CO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED: HRESULT = 0x8004E031u32 as HRESULT; +pub const OLE_S_USEREG: HRESULT = 0x00040000; +pub const OLE_S_STATIC: HRESULT = 0x00040001; +pub const OLE_S_MAC_CLIPFORMAT: HRESULT = 0x00040002; +pub const DRAGDROP_S_DROP: HRESULT = 0x00040100; +pub const DRAGDROP_S_CANCEL: HRESULT = 0x00040101; +pub const DRAGDROP_S_USEDEFAULTCURSORS: HRESULT = 0x00040102; +pub const DATA_S_SAMEFORMATETC: HRESULT = 0x00040130; +pub const VIEW_S_ALREADY_FROZEN: HRESULT = 0x00040140; +pub const CACHE_S_FORMATETC_NOTSUPPORTED: HRESULT = 0x00040170; +pub const CACHE_S_SAMECACHE: HRESULT = 0x00040171; +pub const CACHE_S_SOMECACHES_NOTUPDATED: HRESULT = 0x00040172; +pub const OLEOBJ_S_INVALIDVERB: HRESULT = 0x00040180; +pub const OLEOBJ_S_CANNOT_DOVERB_NOW: HRESULT = 0x00040181; +pub const OLEOBJ_S_INVALIDHWND: HRESULT = 0x00040182; +pub const INPLACE_S_TRUNCATED: HRESULT = 0x000401A0; +pub const CONVERT10_S_NO_PRESENTATION: HRESULT = 0x000401C0; +pub const MK_S_REDUCED_TO_SELF: HRESULT = 0x000401E2; +pub const MK_S_ME: HRESULT = 0x000401E4; +pub const MK_S_HIM: HRESULT = 0x000401E5; +pub const MK_S_US: HRESULT = 0x000401E6; +pub const MK_S_MONIKERALREADYREGISTERED: HRESULT = 0x000401E7; +pub const SCHED_S_TASK_READY: HRESULT = 0x00041300; +pub const SCHED_S_TASK_RUNNING: HRESULT = 0x00041301; +pub const SCHED_S_TASK_DISABLED: HRESULT = 0x00041302; +pub const SCHED_S_TASK_HAS_NOT_RUN: HRESULT = 0x00041303; +pub const SCHED_S_TASK_NO_MORE_RUNS: HRESULT = 0x00041304; +pub const SCHED_S_TASK_NOT_SCHEDULED: HRESULT = 0x00041305; +pub const SCHED_S_TASK_TERMINATED: HRESULT = 0x00041306; +pub const SCHED_S_TASK_NO_VALID_TRIGGERS: HRESULT = 0x00041307; +pub const SCHED_S_EVENT_TRIGGER: HRESULT = 0x00041308; +pub const SCHED_E_TRIGGER_NOT_FOUND: HRESULT = 0x80041309u32 as HRESULT; +pub const SCHED_E_TASK_NOT_READY: HRESULT = 0x8004130Au32 as HRESULT; +pub const SCHED_E_TASK_NOT_RUNNING: HRESULT = 0x8004130Bu32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_INSTALLED: HRESULT = 0x8004130Cu32 as HRESULT; +pub const SCHED_E_CANNOT_OPEN_TASK: HRESULT = 0x8004130Du32 as HRESULT; +pub const SCHED_E_INVALID_TASK: HRESULT = 0x8004130Eu32 as HRESULT; +pub const SCHED_E_ACCOUNT_INFORMATION_NOT_SET: HRESULT = 0x8004130Fu32 as HRESULT; +pub const SCHED_E_ACCOUNT_NAME_NOT_FOUND: HRESULT = 0x80041310u32 as HRESULT; +pub const SCHED_E_ACCOUNT_DBASE_CORRUPT: HRESULT = 0x80041311u32 as HRESULT; +pub const SCHED_E_NO_SECURITY_SERVICES: HRESULT = 0x80041312u32 as HRESULT; +pub const SCHED_E_UNKNOWN_OBJECT_VERSION: HRESULT = 0x80041313u32 as HRESULT; +pub const SCHED_E_UNSUPPORTED_ACCOUNT_OPTION: HRESULT = 0x80041314u32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_RUNNING: HRESULT = 0x80041315u32 as HRESULT; +pub const SCHED_E_UNEXPECTEDNODE: HRESULT = 0x80041316u32 as HRESULT; +pub const SCHED_E_NAMESPACE: HRESULT = 0x80041317u32 as HRESULT; +pub const SCHED_E_INVALIDVALUE: HRESULT = 0x80041318u32 as HRESULT; +pub const SCHED_E_MISSINGNODE: HRESULT = 0x80041319u32 as HRESULT; +pub const SCHED_E_MALFORMEDXML: HRESULT = 0x8004131Au32 as HRESULT; +pub const SCHED_S_SOME_TRIGGERS_FAILED: HRESULT = 0x0004131B; +pub const SCHED_S_BATCH_LOGON_PROBLEM: HRESULT = 0x0004131C; +pub const SCHED_E_TOO_MANY_NODES: HRESULT = 0x8004131Du32 as HRESULT; +pub const SCHED_E_PAST_END_BOUNDARY: HRESULT = 0x8004131Eu32 as HRESULT; +pub const SCHED_E_ALREADY_RUNNING: HRESULT = 0x8004131Fu32 as HRESULT; +pub const SCHED_E_USER_NOT_LOGGED_ON: HRESULT = 0x80041320u32 as HRESULT; +pub const SCHED_E_INVALID_TASK_HASH: HRESULT = 0x80041321u32 as HRESULT; +pub const SCHED_E_SERVICE_NOT_AVAILABLE: HRESULT = 0x80041322u32 as HRESULT; +pub const SCHED_E_SERVICE_TOO_BUSY: HRESULT = 0x80041323u32 as HRESULT; +pub const SCHED_E_TASK_ATTEMPTED: HRESULT = 0x80041324u32 as HRESULT; +pub const SCHED_S_TASK_QUEUED: HRESULT = 0x00041325; +pub const SCHED_E_TASK_DISABLED: HRESULT = 0x80041326u32 as HRESULT; +pub const SCHED_E_TASK_NOT_V1_COMPAT: HRESULT = 0x80041327u32 as HRESULT; +pub const SCHED_E_START_ON_DEMAND: HRESULT = 0x80041328u32 as HRESULT; +pub const SCHED_E_TASK_NOT_UBPM_COMPAT: HRESULT = 0x80041329u32 as HRESULT; +pub const SCHED_E_DEPRECATED_FEATURE_USED: HRESULT = 0x80041330u32 as HRESULT; +pub const CO_E_CLASS_CREATE_FAILED: HRESULT = 0x80080001u32 as HRESULT; +pub const CO_E_SCM_ERROR: HRESULT = 0x80080002u32 as HRESULT; +pub const CO_E_SCM_RPC_FAILURE: HRESULT = 0x80080003u32 as HRESULT; +pub const CO_E_BAD_PATH: HRESULT = 0x80080004u32 as HRESULT; +pub const CO_E_SERVER_EXEC_FAILURE: HRESULT = 0x80080005u32 as HRESULT; +pub const CO_E_OBJSRV_RPC_FAILURE: HRESULT = 0x80080006u32 as HRESULT; +pub const MK_E_NO_NORMALIZED: HRESULT = 0x80080007u32 as HRESULT; +pub const CO_E_SERVER_STOPPING: HRESULT = 0x80080008u32 as HRESULT; +pub const MEM_E_INVALID_ROOT: HRESULT = 0x80080009u32 as HRESULT; +pub const MEM_E_INVALID_LINK: HRESULT = 0x80080010u32 as HRESULT; +pub const MEM_E_INVALID_SIZE: HRESULT = 0x80080011u32 as HRESULT; +pub const CO_S_NOTALLINTERFACES: HRESULT = 0x00080012; +pub const CO_S_MACHINENAMENOTFOUND: HRESULT = 0x00080013; +pub const CO_E_MISSING_DISPLAYNAME: HRESULT = 0x80080015u32 as HRESULT; +pub const CO_E_RUNAS_VALUE_MUST_BE_AAA: HRESULT = 0x80080016u32 as HRESULT; +pub const CO_E_ELEVATION_DISABLED: HRESULT = 0x80080017u32 as HRESULT; +pub const APPX_E_PACKAGING_INTERNAL: HRESULT = 0x80080200u32 as HRESULT; +pub const APPX_E_INTERLEAVING_NOT_ALLOWED: HRESULT = 0x80080201u32 as HRESULT; +pub const APPX_E_RELATIONSHIPS_NOT_ALLOWED: HRESULT = 0x80080202u32 as HRESULT; +pub const APPX_E_MISSING_REQUIRED_FILE: HRESULT = 0x80080203u32 as HRESULT; +pub const APPX_E_INVALID_MANIFEST: HRESULT = 0x80080204u32 as HRESULT; +pub const APPX_E_INVALID_BLOCKMAP: HRESULT = 0x80080205u32 as HRESULT; +pub const APPX_E_CORRUPT_CONTENT: HRESULT = 0x80080206u32 as HRESULT; +pub const APPX_E_BLOCK_HASH_INVALID: HRESULT = 0x80080207u32 as HRESULT; +pub const APPX_E_REQUESTED_RANGE_TOO_LARGE: HRESULT = 0x80080208u32 as HRESULT; +pub const APPX_E_INVALID_SIP_CLIENT_DATA: HRESULT = 0x80080209u32 as HRESULT; +pub const BT_E_SPURIOUS_ACTIVATION: HRESULT = 0x80080300u32 as HRESULT; +pub const DISP_E_UNKNOWNINTERFACE: HRESULT = 0x80020001u32 as HRESULT; +pub const DISP_E_MEMBERNOTFOUND: HRESULT = 0x80020003u32 as HRESULT; +pub const DISP_E_PARAMNOTFOUND: HRESULT = 0x80020004u32 as HRESULT; +pub const DISP_E_TYPEMISMATCH: HRESULT = 0x80020005u32 as HRESULT; +pub const DISP_E_UNKNOWNNAME: HRESULT = 0x80020006u32 as HRESULT; +pub const DISP_E_NONAMEDARGS: HRESULT = 0x80020007u32 as HRESULT; +pub const DISP_E_BADVARTYPE: HRESULT = 0x80020008u32 as HRESULT; +pub const DISP_E_EXCEPTION: HRESULT = 0x80020009u32 as HRESULT; +pub const DISP_E_OVERFLOW: HRESULT = 0x8002000Au32 as HRESULT; +pub const DISP_E_BADINDEX: HRESULT = 0x8002000Bu32 as HRESULT; +pub const DISP_E_UNKNOWNLCID: HRESULT = 0x8002000Cu32 as HRESULT; +pub const DISP_E_ARRAYISLOCKED: HRESULT = 0x8002000Du32 as HRESULT; +pub const DISP_E_BADPARAMCOUNT: HRESULT = 0x8002000Eu32 as HRESULT; +pub const DISP_E_PARAMNOTOPTIONAL: HRESULT = 0x8002000Fu32 as HRESULT; +pub const DISP_E_BADCALLEE: HRESULT = 0x80020010u32 as HRESULT; +pub const DISP_E_NOTACOLLECTION: HRESULT = 0x80020011u32 as HRESULT; +pub const DISP_E_DIVBYZERO: HRESULT = 0x80020012u32 as HRESULT; +pub const DISP_E_BUFFERTOOSMALL: HRESULT = 0x80020013u32 as HRESULT; +pub const TYPE_E_BUFFERTOOSMALL: HRESULT = 0x80028016u32 as HRESULT; +pub const TYPE_E_FIELDNOTFOUND: HRESULT = 0x80028017u32 as HRESULT; +pub const TYPE_E_INVDATAREAD: HRESULT = 0x80028018u32 as HRESULT; +pub const TYPE_E_UNSUPFORMAT: HRESULT = 0x80028019u32 as HRESULT; +pub const TYPE_E_REGISTRYACCESS: HRESULT = 0x8002801Cu32 as HRESULT; +pub const TYPE_E_LIBNOTREGISTERED: HRESULT = 0x8002801Du32 as HRESULT; +pub const TYPE_E_UNDEFINEDTYPE: HRESULT = 0x80028027u32 as HRESULT; +pub const TYPE_E_QUALIFIEDNAMEDISALLOWED: HRESULT = 0x80028028u32 as HRESULT; +pub const TYPE_E_INVALIDSTATE: HRESULT = 0x80028029u32 as HRESULT; +pub const TYPE_E_WRONGTYPEKIND: HRESULT = 0x8002802Au32 as HRESULT; +pub const TYPE_E_ELEMENTNOTFOUND: HRESULT = 0x8002802Bu32 as HRESULT; +pub const TYPE_E_AMBIGUOUSNAME: HRESULT = 0x8002802Cu32 as HRESULT; +pub const TYPE_E_NAMECONFLICT: HRESULT = 0x8002802Du32 as HRESULT; +pub const TYPE_E_UNKNOWNLCID: HRESULT = 0x8002802Eu32 as HRESULT; +pub const TYPE_E_DLLFUNCTIONNOTFOUND: HRESULT = 0x8002802Fu32 as HRESULT; +pub const TYPE_E_BADMODULEKIND: HRESULT = 0x800288BDu32 as HRESULT; +pub const TYPE_E_SIZETOOBIG: HRESULT = 0x800288C5u32 as HRESULT; +pub const TYPE_E_DUPLICATEID: HRESULT = 0x800288C6u32 as HRESULT; +pub const TYPE_E_INVALIDID: HRESULT = 0x800288CFu32 as HRESULT; +pub const TYPE_E_TYPEMISMATCH: HRESULT = 0x80028CA0u32 as HRESULT; +pub const TYPE_E_OUTOFBOUNDS: HRESULT = 0x80028CA1u32 as HRESULT; +pub const TYPE_E_IOERROR: HRESULT = 0x80028CA2u32 as HRESULT; +pub const TYPE_E_CANTCREATETMPFILE: HRESULT = 0x80028CA3u32 as HRESULT; +pub const TYPE_E_CANTLOADLIBRARY: HRESULT = 0x80029C4Au32 as HRESULT; +pub const TYPE_E_INCONSISTENTPROPFUNCS: HRESULT = 0x80029C83u32 as HRESULT; +pub const TYPE_E_CIRCULARTYPE: HRESULT = 0x80029C84u32 as HRESULT; +pub const STG_E_INVALIDFUNCTION: HRESULT = 0x80030001u32 as HRESULT; +pub const STG_E_FILENOTFOUND: HRESULT = 0x80030002u32 as HRESULT; +pub const STG_E_PATHNOTFOUND: HRESULT = 0x80030003u32 as HRESULT; +pub const STG_E_TOOMANYOPENFILES: HRESULT = 0x80030004u32 as HRESULT; +pub const STG_E_ACCESSDENIED: HRESULT = 0x80030005u32 as HRESULT; +pub const STG_E_INVALIDHANDLE: HRESULT = 0x80030006u32 as HRESULT; +pub const STG_E_INSUFFICIENTMEMORY: HRESULT = 0x80030008u32 as HRESULT; +pub const STG_E_INVALIDPOINTER: HRESULT = 0x80030009u32 as HRESULT; +pub const STG_E_NOMOREFILES: HRESULT = 0x80030012u32 as HRESULT; +pub const STG_E_DISKISWRITEPROTECTED: HRESULT = 0x80030013u32 as HRESULT; +pub const STG_E_SEEKERROR: HRESULT = 0x80030019u32 as HRESULT; +pub const STG_E_WRITEFAULT: HRESULT = 0x8003001Du32 as HRESULT; +pub const STG_E_READFAULT: HRESULT = 0x8003001Eu32 as HRESULT; +pub const STG_E_SHAREVIOLATION: HRESULT = 0x80030020u32 as HRESULT; +pub const STG_E_LOCKVIOLATION: HRESULT = 0x80030021u32 as HRESULT; +pub const STG_E_FILEALREADYEXISTS: HRESULT = 0x80030050u32 as HRESULT; +pub const STG_E_INVALIDPARAMETER: HRESULT = 0x80030057u32 as HRESULT; +pub const STG_E_MEDIUMFULL: HRESULT = 0x80030070u32 as HRESULT; +pub const STG_E_PROPSETMISMATCHED: HRESULT = 0x800300F0u32 as HRESULT; +pub const STG_E_ABNORMALAPIEXIT: HRESULT = 0x800300FAu32 as HRESULT; +pub const STG_E_INVALIDHEADER: HRESULT = 0x800300FBu32 as HRESULT; +pub const STG_E_INVALIDNAME: HRESULT = 0x800300FCu32 as HRESULT; +pub const STG_E_UNKNOWN: HRESULT = 0x800300FDu32 as HRESULT; +pub const STG_E_UNIMPLEMENTEDFUNCTION: HRESULT = 0x800300FEu32 as HRESULT; +pub const STG_E_INVALIDFLAG: HRESULT = 0x800300FFu32 as HRESULT; +pub const STG_E_INUSE: HRESULT = 0x80030100u32 as HRESULT; +pub const STG_E_NOTCURRENT: HRESULT = 0x80030101u32 as HRESULT; +pub const STG_E_REVERTED: HRESULT = 0x80030102u32 as HRESULT; +pub const STG_E_CANTSAVE: HRESULT = 0x80030103u32 as HRESULT; +pub const STG_E_OLDFORMAT: HRESULT = 0x80030104u32 as HRESULT; +pub const STG_E_OLDDLL: HRESULT = 0x80030105u32 as HRESULT; +pub const STG_E_SHAREREQUIRED: HRESULT = 0x80030106u32 as HRESULT; +pub const STG_E_NOTFILEBASEDSTORAGE: HRESULT = 0x80030107u32 as HRESULT; +pub const STG_E_EXTANTMARSHALLINGS: HRESULT = 0x80030108u32 as HRESULT; +pub const STG_E_DOCFILECORRUPT: HRESULT = 0x80030109u32 as HRESULT; +pub const STG_E_BADBASEADDRESS: HRESULT = 0x80030110u32 as HRESULT; +pub const STG_E_DOCFILETOOLARGE: HRESULT = 0x80030111u32 as HRESULT; +pub const STG_E_NOTSIMPLEFORMAT: HRESULT = 0x80030112u32 as HRESULT; +pub const STG_E_INCOMPLETE: HRESULT = 0x80030201u32 as HRESULT; +pub const STG_E_TERMINATED: HRESULT = 0x80030202u32 as HRESULT; +pub const STG_S_CONVERTED: HRESULT = 0x00030200; +pub const STG_S_BLOCK: HRESULT = 0x00030201; +pub const STG_S_RETRYNOW: HRESULT = 0x00030202; +pub const STG_S_MONITORING: HRESULT = 0x00030203; +pub const STG_S_MULTIPLEOPENS: HRESULT = 0x00030204; +pub const STG_S_CONSOLIDATIONFAILED: HRESULT = 0x00030205; +pub const STG_S_CANNOTCONSOLIDATE: HRESULT = 0x00030206; +pub const STG_E_STATUS_COPY_PROTECTION_FAILURE: HRESULT = 0x80030305u32 as HRESULT; +pub const STG_E_CSS_AUTHENTICATION_FAILURE: HRESULT = 0x80030306u32 as HRESULT; +pub const STG_E_CSS_KEY_NOT_PRESENT: HRESULT = 0x80030307u32 as HRESULT; +pub const STG_E_CSS_KEY_NOT_ESTABLISHED: HRESULT = 0x80030308u32 as HRESULT; +pub const STG_E_CSS_SCRAMBLED_SECTOR: HRESULT = 0x80030309u32 as HRESULT; +pub const STG_E_CSS_REGION_MISMATCH: HRESULT = 0x8003030Au32 as HRESULT; +pub const STG_E_RESETS_EXHAUSTED: HRESULT = 0x8003030Bu32 as HRESULT; +pub const RPC_E_CALL_REJECTED: HRESULT = 0x80010001u32 as HRESULT; +pub const RPC_E_CALL_CANCELED: HRESULT = 0x80010002u32 as HRESULT; +pub const RPC_E_CANTPOST_INSENDCALL: HRESULT = 0x80010003u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_INASYNCCALL: HRESULT = 0x80010004u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_INEXTERNALCALL: HRESULT = 0x80010005u32 as HRESULT; +pub const RPC_E_CONNECTION_TERMINATED: HRESULT = 0x80010006u32 as HRESULT; +pub const RPC_E_SERVER_DIED: HRESULT = 0x80010007u32 as HRESULT; +pub const RPC_E_CLIENT_DIED: HRESULT = 0x80010008u32 as HRESULT; +pub const RPC_E_INVALID_DATAPACKET: HRESULT = 0x80010009u32 as HRESULT; +pub const RPC_E_CANTTRANSMIT_CALL: HRESULT = 0x8001000Au32 as HRESULT; +pub const RPC_E_CLIENT_CANTMARSHAL_DATA: HRESULT = 0x8001000Bu32 as HRESULT; +pub const RPC_E_CLIENT_CANTUNMARSHAL_DATA: HRESULT = 0x8001000Cu32 as HRESULT; +pub const RPC_E_SERVER_CANTMARSHAL_DATA: HRESULT = 0x8001000Du32 as HRESULT; +pub const RPC_E_SERVER_CANTUNMARSHAL_DATA: HRESULT = 0x8001000Eu32 as HRESULT; +pub const RPC_E_INVALID_DATA: HRESULT = 0x8001000Fu32 as HRESULT; +pub const RPC_E_INVALID_PARAMETER: HRESULT = 0x80010010u32 as HRESULT; +pub const RPC_E_CANTCALLOUT_AGAIN: HRESULT = 0x80010011u32 as HRESULT; +pub const RPC_E_SERVER_DIED_DNE: HRESULT = 0x80010012u32 as HRESULT; +pub const RPC_E_SYS_CALL_FAILED: HRESULT = 0x80010100u32 as HRESULT; +pub const RPC_E_OUT_OF_RESOURCES: HRESULT = 0x80010101u32 as HRESULT; +pub const RPC_E_ATTEMPTED_MULTITHREAD: HRESULT = 0x80010102u32 as HRESULT; +pub const RPC_E_NOT_REGISTERED: HRESULT = 0x80010103u32 as HRESULT; +pub const RPC_E_FAULT: HRESULT = 0x80010104u32 as HRESULT; +pub const RPC_E_SERVERFAULT: HRESULT = 0x80010105u32 as HRESULT; +pub const RPC_E_CHANGED_MODE: HRESULT = 0x80010106u32 as HRESULT; +pub const RPC_E_INVALIDMETHOD: HRESULT = 0x80010107u32 as HRESULT; +pub const RPC_E_DISCONNECTED: HRESULT = 0x80010108u32 as HRESULT; +pub const RPC_E_RETRY: HRESULT = 0x80010109u32 as HRESULT; +pub const RPC_E_SERVERCALL_RETRYLATER: HRESULT = 0x8001010Au32 as HRESULT; +pub const RPC_E_SERVERCALL_REJECTED: HRESULT = 0x8001010Bu32 as HRESULT; +pub const RPC_E_INVALID_CALLDATA: HRESULT = 0x8001010Cu32 as HRESULT; +pub const RPC_E_CANTCALLOUT_ININPUTSYNCCALL: HRESULT = 0x8001010Du32 as HRESULT; +pub const RPC_E_WRONG_THREAD: HRESULT = 0x8001010Eu32 as HRESULT; +pub const RPC_E_THREAD_NOT_INIT: HRESULT = 0x8001010Fu32 as HRESULT; +pub const RPC_E_VERSION_MISMATCH: HRESULT = 0x80010110u32 as HRESULT; +pub const RPC_E_INVALID_HEADER: HRESULT = 0x80010111u32 as HRESULT; +pub const RPC_E_INVALID_EXTENSION: HRESULT = 0x80010112u32 as HRESULT; +pub const RPC_E_INVALID_IPID: HRESULT = 0x80010113u32 as HRESULT; +pub const RPC_E_INVALID_OBJECT: HRESULT = 0x80010114u32 as HRESULT; +pub const RPC_S_CALLPENDING: HRESULT = 0x80010115u32 as HRESULT; +pub const RPC_S_WAITONTIMER: HRESULT = 0x80010116u32 as HRESULT; +pub const RPC_E_CALL_COMPLETE: HRESULT = 0x80010117u32 as HRESULT; +pub const RPC_E_UNSECURE_CALL: HRESULT = 0x80010118u32 as HRESULT; +pub const RPC_E_TOO_LATE: HRESULT = 0x80010119u32 as HRESULT; +pub const RPC_E_NO_GOOD_SECURITY_PACKAGES: HRESULT = 0x8001011Au32 as HRESULT; +pub const RPC_E_ACCESS_DENIED: HRESULT = 0x8001011Bu32 as HRESULT; +pub const RPC_E_REMOTE_DISABLED: HRESULT = 0x8001011Cu32 as HRESULT; +pub const RPC_E_INVALID_OBJREF: HRESULT = 0x8001011Du32 as HRESULT; +pub const RPC_E_NO_CONTEXT: HRESULT = 0x8001011Eu32 as HRESULT; +pub const RPC_E_TIMEOUT: HRESULT = 0x8001011Fu32 as HRESULT; +pub const RPC_E_NO_SYNC: HRESULT = 0x80010120u32 as HRESULT; +pub const RPC_E_FULLSIC_REQUIRED: HRESULT = 0x80010121u32 as HRESULT; +pub const RPC_E_INVALID_STD_NAME: HRESULT = 0x80010122u32 as HRESULT; +pub const CO_E_FAILEDTOIMPERSONATE: HRESULT = 0x80010123u32 as HRESULT; +pub const CO_E_FAILEDTOGETSECCTX: HRESULT = 0x80010124u32 as HRESULT; +pub const CO_E_FAILEDTOOPENTHREADTOKEN: HRESULT = 0x80010125u32 as HRESULT; +pub const CO_E_FAILEDTOGETTOKENINFO: HRESULT = 0x80010126u32 as HRESULT; +pub const CO_E_TRUSTEEDOESNTMATCHCLIENT: HRESULT = 0x80010127u32 as HRESULT; +pub const CO_E_FAILEDTOQUERYCLIENTBLANKET: HRESULT = 0x80010128u32 as HRESULT; +pub const CO_E_FAILEDTOSETDACL: HRESULT = 0x80010129u32 as HRESULT; +pub const CO_E_ACCESSCHECKFAILED: HRESULT = 0x8001012Au32 as HRESULT; +pub const CO_E_NETACCESSAPIFAILED: HRESULT = 0x8001012Bu32 as HRESULT; +pub const CO_E_WRONGTRUSTEENAMESYNTAX: HRESULT = 0x8001012Cu32 as HRESULT; +pub const CO_E_INVALIDSID: HRESULT = 0x8001012Du32 as HRESULT; +pub const CO_E_CONVERSIONFAILED: HRESULT = 0x8001012Eu32 as HRESULT; +pub const CO_E_NOMATCHINGSIDFOUND: HRESULT = 0x8001012Fu32 as HRESULT; +pub const CO_E_LOOKUPACCSIDFAILED: HRESULT = 0x80010130u32 as HRESULT; +pub const CO_E_NOMATCHINGNAMEFOUND: HRESULT = 0x80010131u32 as HRESULT; +pub const CO_E_LOOKUPACCNAMEFAILED: HRESULT = 0x80010132u32 as HRESULT; +pub const CO_E_SETSERLHNDLFAILED: HRESULT = 0x80010133u32 as HRESULT; +pub const CO_E_FAILEDTOGETWINDIR: HRESULT = 0x80010134u32 as HRESULT; +pub const CO_E_PATHTOOLONG: HRESULT = 0x80010135u32 as HRESULT; +pub const CO_E_FAILEDTOGENUUID: HRESULT = 0x80010136u32 as HRESULT; +pub const CO_E_FAILEDTOCREATEFILE: HRESULT = 0x80010137u32 as HRESULT; +pub const CO_E_FAILEDTOCLOSEHANDLE: HRESULT = 0x80010138u32 as HRESULT; +pub const CO_E_EXCEEDSYSACLLIMIT: HRESULT = 0x80010139u32 as HRESULT; +pub const CO_E_ACESINWRONGORDER: HRESULT = 0x8001013Au32 as HRESULT; +pub const CO_E_INCOMPATIBLESTREAMVERSION: HRESULT = 0x8001013Bu32 as HRESULT; +pub const CO_E_FAILEDTOOPENPROCESSTOKEN: HRESULT = 0x8001013Cu32 as HRESULT; +pub const CO_E_DECODEFAILED: HRESULT = 0x8001013Du32 as HRESULT; +pub const CO_E_ACNOTINITIALIZED: HRESULT = 0x8001013Fu32 as HRESULT; +pub const CO_E_CANCEL_DISABLED: HRESULT = 0x80010140u32 as HRESULT; +pub const RPC_E_UNEXPECTED: HRESULT = 0x8001FFFFu32 as HRESULT; +pub const ERROR_AUDITING_DISABLED: HRESULT = 0xC0090001u32 as HRESULT; +pub const ERROR_ALL_SIDS_FILTERED: HRESULT = 0xC0090002u32 as HRESULT; +pub const ERROR_BIZRULES_NOT_ENABLED: HRESULT = 0xC0090003u32 as HRESULT; +pub const NTE_BAD_UID: HRESULT = 0x80090001u32 as HRESULT; +pub const NTE_BAD_HASH: HRESULT = 0x80090002u32 as HRESULT; +pub const NTE_BAD_KEY: HRESULT = 0x80090003u32 as HRESULT; +pub const NTE_BAD_LEN: HRESULT = 0x80090004u32 as HRESULT; +pub const NTE_BAD_DATA: HRESULT = 0x80090005u32 as HRESULT; +pub const NTE_BAD_SIGNATURE: HRESULT = 0x80090006u32 as HRESULT; +pub const NTE_BAD_VER: HRESULT = 0x80090007u32 as HRESULT; +pub const NTE_BAD_ALGID: HRESULT = 0x80090008u32 as HRESULT; +pub const NTE_BAD_FLAGS: HRESULT = 0x80090009u32 as HRESULT; +pub const NTE_BAD_TYPE: HRESULT = 0x8009000Au32 as HRESULT; +pub const NTE_BAD_KEY_STATE: HRESULT = 0x8009000Bu32 as HRESULT; +pub const NTE_BAD_HASH_STATE: HRESULT = 0x8009000Cu32 as HRESULT; +pub const NTE_NO_KEY: HRESULT = 0x8009000Du32 as HRESULT; +pub const NTE_NO_MEMORY: HRESULT = 0x8009000Eu32 as HRESULT; +pub const NTE_EXISTS: HRESULT = 0x8009000Fu32 as HRESULT; +pub const NTE_PERM: HRESULT = 0x80090010u32 as HRESULT; +pub const NTE_NOT_FOUND: HRESULT = 0x80090011u32 as HRESULT; +pub const NTE_DOUBLE_ENCRYPT: HRESULT = 0x80090012u32 as HRESULT; +pub const NTE_BAD_PROVIDER: HRESULT = 0x80090013u32 as HRESULT; +pub const NTE_BAD_PROV_TYPE: HRESULT = 0x80090014u32 as HRESULT; +pub const NTE_BAD_PUBLIC_KEY: HRESULT = 0x80090015u32 as HRESULT; +pub const NTE_BAD_KEYSET: HRESULT = 0x80090016u32 as HRESULT; +pub const NTE_PROV_TYPE_NOT_DEF: HRESULT = 0x80090017u32 as HRESULT; +pub const NTE_PROV_TYPE_ENTRY_BAD: HRESULT = 0x80090018u32 as HRESULT; +pub const NTE_KEYSET_NOT_DEF: HRESULT = 0x80090019u32 as HRESULT; +pub const NTE_KEYSET_ENTRY_BAD: HRESULT = 0x8009001Au32 as HRESULT; +pub const NTE_PROV_TYPE_NO_MATCH: HRESULT = 0x8009001Bu32 as HRESULT; +pub const NTE_SIGNATURE_FILE_BAD: HRESULT = 0x8009001Cu32 as HRESULT; +pub const NTE_PROVIDER_DLL_FAIL: HRESULT = 0x8009001Du32 as HRESULT; +pub const NTE_PROV_DLL_NOT_FOUND: HRESULT = 0x8009001Eu32 as HRESULT; +pub const NTE_BAD_KEYSET_PARAM: HRESULT = 0x8009001Fu32 as HRESULT; +pub const NTE_FAIL: HRESULT = 0x80090020u32 as HRESULT; +pub const NTE_SYS_ERR: HRESULT = 0x80090021u32 as HRESULT; +pub const NTE_SILENT_CONTEXT: HRESULT = 0x80090022u32 as HRESULT; +pub const NTE_TOKEN_KEYSET_STORAGE_FULL: HRESULT = 0x80090023u32 as HRESULT; +pub const NTE_TEMPORARY_PROFILE: HRESULT = 0x80090024u32 as HRESULT; +pub const NTE_FIXEDPARAMETER: HRESULT = 0x80090025u32 as HRESULT; +pub const NTE_INVALID_HANDLE: HRESULT = 0x80090026u32 as HRESULT; +pub const NTE_INVALID_PARAMETER: HRESULT = 0x80090027u32 as HRESULT; +pub const NTE_BUFFER_TOO_SMALL: HRESULT = 0x80090028u32 as HRESULT; +pub const NTE_NOT_SUPPORTED: HRESULT = 0x80090029u32 as HRESULT; +pub const NTE_NO_MORE_ITEMS: HRESULT = 0x8009002Au32 as HRESULT; +pub const NTE_BUFFERS_OVERLAP: HRESULT = 0x8009002Bu32 as HRESULT; +pub const NTE_DECRYPTION_FAILURE: HRESULT = 0x8009002Cu32 as HRESULT; +pub const NTE_INTERNAL_ERROR: HRESULT = 0x8009002Du32 as HRESULT; +pub const NTE_UI_REQUIRED: HRESULT = 0x8009002Eu32 as HRESULT; +pub const NTE_HMAC_NOT_SUPPORTED: HRESULT = 0x8009002Fu32 as HRESULT; +pub const NTE_DEVICE_NOT_READY: HRESULT = 0x80090030u32 as HRESULT; +pub const NTE_AUTHENTICATION_IGNORED: HRESULT = 0x80090031u32 as HRESULT; +pub const NTE_VALIDATION_FAILED: HRESULT = 0x80090032u32 as HRESULT; +pub const NTE_INCORRECT_PASSWORD: HRESULT = 0x80090033u32 as HRESULT; +pub const NTE_ENCRYPTION_FAILURE: HRESULT = 0x80090034u32 as HRESULT; +pub const NTE_DEVICE_NOT_FOUND: HRESULT = 0x80090035u32 as HRESULT; +pub const SEC_E_INSUFFICIENT_MEMORY: HRESULT = 0x80090300u32 as HRESULT; +pub const SEC_E_INVALID_HANDLE: HRESULT = 0x80090301u32 as HRESULT; +pub const SEC_E_UNSUPPORTED_FUNCTION: HRESULT = 0x80090302u32 as HRESULT; +pub const SEC_E_TARGET_UNKNOWN: HRESULT = 0x80090303u32 as HRESULT; +pub const SEC_E_INTERNAL_ERROR: HRESULT = 0x80090304u32 as HRESULT; +pub const SEC_E_SECPKG_NOT_FOUND: HRESULT = 0x80090305u32 as HRESULT; +pub const SEC_E_NOT_OWNER: HRESULT = 0x80090306u32 as HRESULT; +pub const SEC_E_CANNOT_INSTALL: HRESULT = 0x80090307u32 as HRESULT; +pub const SEC_E_INVALID_TOKEN: HRESULT = 0x80090308u32 as HRESULT; +pub const SEC_E_CANNOT_PACK: HRESULT = 0x80090309u32 as HRESULT; +pub const SEC_E_QOP_NOT_SUPPORTED: HRESULT = 0x8009030Au32 as HRESULT; +pub const SEC_E_NO_IMPERSONATION: HRESULT = 0x8009030Bu32 as HRESULT; +pub const SEC_E_LOGON_DENIED: HRESULT = 0x8009030Cu32 as HRESULT; +pub const SEC_E_UNKNOWN_CREDENTIALS: HRESULT = 0x8009030Du32 as HRESULT; +pub const SEC_E_NO_CREDENTIALS: HRESULT = 0x8009030Eu32 as HRESULT; +pub const SEC_E_MESSAGE_ALTERED: HRESULT = 0x8009030Fu32 as HRESULT; +pub const SEC_E_OUT_OF_SEQUENCE: HRESULT = 0x80090310u32 as HRESULT; +pub const SEC_E_NO_AUTHENTICATING_AUTHORITY: HRESULT = 0x80090311u32 as HRESULT; +pub const SEC_I_CONTINUE_NEEDED: HRESULT = 0x00090312; +pub const SEC_I_COMPLETE_NEEDED: HRESULT = 0x00090313; +pub const SEC_I_COMPLETE_AND_CONTINUE: HRESULT = 0x00090314; +pub const SEC_I_LOCAL_LOGON: HRESULT = 0x00090315; +pub const SEC_E_BAD_PKGID: HRESULT = 0x80090316u32 as HRESULT; +pub const SEC_E_CONTEXT_EXPIRED: HRESULT = 0x80090317u32 as HRESULT; +pub const SEC_I_CONTEXT_EXPIRED: HRESULT = 0x00090317; +pub const SEC_E_INCOMPLETE_MESSAGE: HRESULT = 0x80090318u32 as HRESULT; +pub const SEC_E_INCOMPLETE_CREDENTIALS: HRESULT = 0x80090320u32 as HRESULT; +pub const SEC_E_BUFFER_TOO_SMALL: HRESULT = 0x80090321u32 as HRESULT; +pub const SEC_I_INCOMPLETE_CREDENTIALS: HRESULT = 0x00090320; +pub const SEC_I_RENEGOTIATE: HRESULT = 0x00090321; +pub const SEC_E_WRONG_PRINCIPAL: HRESULT = 0x80090322u32 as HRESULT; +pub const SEC_I_NO_LSA_CONTEXT: HRESULT = 0x00090323; +pub const SEC_E_TIME_SKEW: HRESULT = 0x80090324u32 as HRESULT; +pub const SEC_E_UNTRUSTED_ROOT: HRESULT = 0x80090325u32 as HRESULT; +pub const SEC_E_ILLEGAL_MESSAGE: HRESULT = 0x80090326u32 as HRESULT; +pub const SEC_E_CERT_UNKNOWN: HRESULT = 0x80090327u32 as HRESULT; +pub const SEC_E_CERT_EXPIRED: HRESULT = 0x80090328u32 as HRESULT; +pub const SEC_E_ENCRYPT_FAILURE: HRESULT = 0x80090329u32 as HRESULT; +pub const SEC_E_DECRYPT_FAILURE: HRESULT = 0x80090330u32 as HRESULT; +pub const SEC_E_ALGORITHM_MISMATCH: HRESULT = 0x80090331u32 as HRESULT; +pub const SEC_E_SECURITY_QOS_FAILED: HRESULT = 0x80090332u32 as HRESULT; +pub const SEC_E_UNFINISHED_CONTEXT_DELETED: HRESULT = 0x80090333u32 as HRESULT; +pub const SEC_E_NO_TGT_REPLY: HRESULT = 0x80090334u32 as HRESULT; +pub const SEC_E_NO_IP_ADDRESSES: HRESULT = 0x80090335u32 as HRESULT; +pub const SEC_E_WRONG_CREDENTIAL_HANDLE: HRESULT = 0x80090336u32 as HRESULT; +pub const SEC_E_CRYPTO_SYSTEM_INVALID: HRESULT = 0x80090337u32 as HRESULT; +pub const SEC_E_MAX_REFERRALS_EXCEEDED: HRESULT = 0x80090338u32 as HRESULT; +pub const SEC_E_MUST_BE_KDC: HRESULT = 0x80090339u32 as HRESULT; +pub const SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: HRESULT = 0x8009033Au32 as HRESULT; +pub const SEC_E_TOO_MANY_PRINCIPALS: HRESULT = 0x8009033Bu32 as HRESULT; +pub const SEC_E_NO_PA_DATA: HRESULT = 0x8009033Cu32 as HRESULT; +pub const SEC_E_PKINIT_NAME_MISMATCH: HRESULT = 0x8009033Du32 as HRESULT; +pub const SEC_E_SMARTCARD_LOGON_REQUIRED: HRESULT = 0x8009033Eu32 as HRESULT; +pub const SEC_E_SHUTDOWN_IN_PROGRESS: HRESULT = 0x8009033Fu32 as HRESULT; +pub const SEC_E_KDC_INVALID_REQUEST: HRESULT = 0x80090340u32 as HRESULT; +pub const SEC_E_KDC_UNABLE_TO_REFER: HRESULT = 0x80090341u32 as HRESULT; +pub const SEC_E_KDC_UNKNOWN_ETYPE: HRESULT = 0x80090342u32 as HRESULT; +pub const SEC_E_UNSUPPORTED_PREAUTH: HRESULT = 0x80090343u32 as HRESULT; +pub const SEC_E_DELEGATION_REQUIRED: HRESULT = 0x80090345u32 as HRESULT; +pub const SEC_E_BAD_BINDINGS: HRESULT = 0x80090346u32 as HRESULT; +pub const SEC_E_MULTIPLE_ACCOUNTS: HRESULT = 0x80090347u32 as HRESULT; +pub const SEC_E_NO_KERB_KEY: HRESULT = 0x80090348u32 as HRESULT; +pub const SEC_E_CERT_WRONG_USAGE: HRESULT = 0x80090349u32 as HRESULT; +pub const SEC_E_DOWNGRADE_DETECTED: HRESULT = 0x80090350u32 as HRESULT; +pub const SEC_E_SMARTCARD_CERT_REVOKED: HRESULT = 0x80090351u32 as HRESULT; +pub const SEC_E_ISSUING_CA_UNTRUSTED: HRESULT = 0x80090352u32 as HRESULT; +pub const SEC_E_REVOCATION_OFFLINE_C: HRESULT = 0x80090353u32 as HRESULT; +pub const SEC_E_PKINIT_CLIENT_FAILURE: HRESULT = 0x80090354u32 as HRESULT; +pub const SEC_E_SMARTCARD_CERT_EXPIRED: HRESULT = 0x80090355u32 as HRESULT; +pub const SEC_E_NO_S4U_PROT_SUPPORT: HRESULT = 0x80090356u32 as HRESULT; +pub const SEC_E_CROSSREALM_DELEGATION_FAILURE: HRESULT = 0x80090357u32 as HRESULT; +pub const SEC_E_REVOCATION_OFFLINE_KDC: HRESULT = 0x80090358u32 as HRESULT; +pub const SEC_E_ISSUING_CA_UNTRUSTED_KDC: HRESULT = 0x80090359u32 as HRESULT; +pub const SEC_E_KDC_CERT_EXPIRED: HRESULT = 0x8009035Au32 as HRESULT; +pub const SEC_E_KDC_CERT_REVOKED: HRESULT = 0x8009035Bu32 as HRESULT; +pub const SEC_I_SIGNATURE_NEEDED: HRESULT = 0x0009035C; +pub const SEC_E_INVALID_PARAMETER: HRESULT = 0x8009035Du32 as HRESULT; +pub const SEC_E_DELEGATION_POLICY: HRESULT = 0x8009035Eu32 as HRESULT; +pub const SEC_E_POLICY_NLTM_ONLY: HRESULT = 0x8009035Fu32 as HRESULT; +pub const SEC_I_NO_RENEGOTIATION: HRESULT = 0x00090360; +pub const SEC_E_NO_CONTEXT: HRESULT = 0x80090361u32 as HRESULT; +pub const SEC_E_PKU2U_CERT_FAILURE: HRESULT = 0x80090362u32 as HRESULT; +pub const SEC_E_MUTUAL_AUTH_FAILED: HRESULT = 0x80090363u32 as HRESULT; +pub const SEC_I_MESSAGE_FRAGMENT: HRESULT = 0x00090364; +pub const SEC_E_ONLY_HTTPS_ALLOWED: HRESULT = 0x80090365u32 as HRESULT; +pub const SEC_I_CONTINUE_NEEDED_MESSAGE_OK: HRESULT = 0x00090366; +pub const SEC_E_APPLICATION_PROTOCOL_MISMATCH: HRESULT = 0x80090367u32 as HRESULT; +pub const SEC_E_NO_SPM: HRESULT = SEC_E_INTERNAL_ERROR; +pub const SEC_E_NOT_SUPPORTED: HRESULT = SEC_E_UNSUPPORTED_FUNCTION; +pub const CRYPT_E_MSG_ERROR: HRESULT = 0x80091001u32 as HRESULT; +pub const CRYPT_E_UNKNOWN_ALGO: HRESULT = 0x80091002u32 as HRESULT; +pub const CRYPT_E_OID_FORMAT: HRESULT = 0x80091003u32 as HRESULT; +pub const CRYPT_E_INVALID_MSG_TYPE: HRESULT = 0x80091004u32 as HRESULT; +pub const CRYPT_E_UNEXPECTED_ENCODING: HRESULT = 0x80091005u32 as HRESULT; +pub const CRYPT_E_AUTH_ATTR_MISSING: HRESULT = 0x80091006u32 as HRESULT; +pub const CRYPT_E_HASH_VALUE: HRESULT = 0x80091007u32 as HRESULT; +pub const CRYPT_E_INVALID_INDEX: HRESULT = 0x80091008u32 as HRESULT; +pub const CRYPT_E_ALREADY_DECRYPTED: HRESULT = 0x80091009u32 as HRESULT; +pub const CRYPT_E_NOT_DECRYPTED: HRESULT = 0x8009100Au32 as HRESULT; +pub const CRYPT_E_RECIPIENT_NOT_FOUND: HRESULT = 0x8009100Bu32 as HRESULT; +pub const CRYPT_E_CONTROL_TYPE: HRESULT = 0x8009100Cu32 as HRESULT; +pub const CRYPT_E_ISSUER_SERIALNUMBER: HRESULT = 0x8009100Du32 as HRESULT; +pub const CRYPT_E_SIGNER_NOT_FOUND: HRESULT = 0x8009100Eu32 as HRESULT; +pub const CRYPT_E_ATTRIBUTES_MISSING: HRESULT = 0x8009100Fu32 as HRESULT; +pub const CRYPT_E_STREAM_MSG_NOT_READY: HRESULT = 0x80091010u32 as HRESULT; +pub const CRYPT_E_STREAM_INSUFFICIENT_DATA: HRESULT = 0x80091011u32 as HRESULT; +pub const CRYPT_I_NEW_PROTECTION_REQUIRED: HRESULT = 0x00091012; +pub const CRYPT_E_BAD_LEN: HRESULT = 0x80092001u32 as HRESULT; +pub const CRYPT_E_BAD_ENCODE: HRESULT = 0x80092002u32 as HRESULT; +pub const CRYPT_E_FILE_ERROR: HRESULT = 0x80092003u32 as HRESULT; +pub const CRYPT_E_NOT_FOUND: HRESULT = 0x80092004u32 as HRESULT; +pub const CRYPT_E_EXISTS: HRESULT = 0x80092005u32 as HRESULT; +pub const CRYPT_E_NO_PROVIDER: HRESULT = 0x80092006u32 as HRESULT; +pub const CRYPT_E_SELF_SIGNED: HRESULT = 0x80092007u32 as HRESULT; +pub const CRYPT_E_DELETED_PREV: HRESULT = 0x80092008u32 as HRESULT; +pub const CRYPT_E_NO_MATCH: HRESULT = 0x80092009u32 as HRESULT; +pub const CRYPT_E_UNEXPECTED_MSG_TYPE: HRESULT = 0x8009200Au32 as HRESULT; +pub const CRYPT_E_NO_KEY_PROPERTY: HRESULT = 0x8009200Bu32 as HRESULT; +pub const CRYPT_E_NO_DECRYPT_CERT: HRESULT = 0x8009200Cu32 as HRESULT; +pub const CRYPT_E_BAD_MSG: HRESULT = 0x8009200Du32 as HRESULT; +pub const CRYPT_E_NO_SIGNER: HRESULT = 0x8009200Eu32 as HRESULT; +pub const CRYPT_E_PENDING_CLOSE: HRESULT = 0x8009200Fu32 as HRESULT; +pub const CRYPT_E_REVOKED: HRESULT = 0x80092010u32 as HRESULT; +pub const CRYPT_E_NO_REVOCATION_DLL: HRESULT = 0x80092011u32 as HRESULT; +pub const CRYPT_E_NO_REVOCATION_CHECK: HRESULT = 0x80092012u32 as HRESULT; +pub const CRYPT_E_REVOCATION_OFFLINE: HRESULT = 0x80092013u32 as HRESULT; +pub const CRYPT_E_NOT_IN_REVOCATION_DATABASE: HRESULT = 0x80092014u32 as HRESULT; +pub const CRYPT_E_INVALID_NUMERIC_STRING: HRESULT = 0x80092020u32 as HRESULT; +pub const CRYPT_E_INVALID_PRINTABLE_STRING: HRESULT = 0x80092021u32 as HRESULT; +pub const CRYPT_E_INVALID_IA5_STRING: HRESULT = 0x80092022u32 as HRESULT; +pub const CRYPT_E_INVALID_X500_STRING: HRESULT = 0x80092023u32 as HRESULT; +pub const CRYPT_E_NOT_CHAR_STRING: HRESULT = 0x80092024u32 as HRESULT; +pub const CRYPT_E_FILERESIZED: HRESULT = 0x80092025u32 as HRESULT; +pub const CRYPT_E_SECURITY_SETTINGS: HRESULT = 0x80092026u32 as HRESULT; +pub const CRYPT_E_NO_VERIFY_USAGE_DLL: HRESULT = 0x80092027u32 as HRESULT; +pub const CRYPT_E_NO_VERIFY_USAGE_CHECK: HRESULT = 0x80092028u32 as HRESULT; +pub const CRYPT_E_VERIFY_USAGE_OFFLINE: HRESULT = 0x80092029u32 as HRESULT; +pub const CRYPT_E_NOT_IN_CTL: HRESULT = 0x8009202Au32 as HRESULT; +pub const CRYPT_E_NO_TRUSTED_SIGNER: HRESULT = 0x8009202Bu32 as HRESULT; +pub const CRYPT_E_MISSING_PUBKEY_PARA: HRESULT = 0x8009202Cu32 as HRESULT; +pub const CRYPT_E_OBJECT_LOCATOR_OBJECT_NOT_FOUND: HRESULT = 0x8009202Du32 as HRESULT; +pub const CRYPT_E_OSS_ERROR: HRESULT = 0x80093000u32 as HRESULT; +pub const OSS_MORE_BUF: HRESULT = 0x80093001u32 as HRESULT; +pub const OSS_NEGATIVE_UINTEGER: HRESULT = 0x80093002u32 as HRESULT; +pub const OSS_PDU_RANGE: HRESULT = 0x80093003u32 as HRESULT; +pub const OSS_MORE_INPUT: HRESULT = 0x80093004u32 as HRESULT; +pub const OSS_DATA_ERROR: HRESULT = 0x80093005u32 as HRESULT; +pub const OSS_BAD_ARG: HRESULT = 0x80093006u32 as HRESULT; +pub const OSS_BAD_VERSION: HRESULT = 0x80093007u32 as HRESULT; +pub const OSS_OUT_MEMORY: HRESULT = 0x80093008u32 as HRESULT; +pub const OSS_PDU_MISMATCH: HRESULT = 0x80093009u32 as HRESULT; +pub const OSS_LIMITED: HRESULT = 0x8009300Au32 as HRESULT; +pub const OSS_BAD_PTR: HRESULT = 0x8009300Bu32 as HRESULT; +pub const OSS_BAD_TIME: HRESULT = 0x8009300Cu32 as HRESULT; +pub const OSS_INDEFINITE_NOT_SUPPORTED: HRESULT = 0x8009300Du32 as HRESULT; +pub const OSS_MEM_ERROR: HRESULT = 0x8009300Eu32 as HRESULT; +pub const OSS_BAD_TABLE: HRESULT = 0x8009300Fu32 as HRESULT; +pub const OSS_TOO_LONG: HRESULT = 0x80093010u32 as HRESULT; +pub const OSS_CONSTRAINT_VIOLATED: HRESULT = 0x80093011u32 as HRESULT; +pub const OSS_FATAL_ERROR: HRESULT = 0x80093012u32 as HRESULT; +pub const OSS_ACCESS_SERIALIZATION_ERROR: HRESULT = 0x80093013u32 as HRESULT; +pub const OSS_NULL_TBL: HRESULT = 0x80093014u32 as HRESULT; +pub const OSS_NULL_FCN: HRESULT = 0x80093015u32 as HRESULT; +pub const OSS_BAD_ENCRULES: HRESULT = 0x80093016u32 as HRESULT; +pub const OSS_UNAVAIL_ENCRULES: HRESULT = 0x80093017u32 as HRESULT; +pub const OSS_CANT_OPEN_TRACE_WINDOW: HRESULT = 0x80093018u32 as HRESULT; +pub const OSS_UNIMPLEMENTED: HRESULT = 0x80093019u32 as HRESULT; +pub const OSS_OID_DLL_NOT_LINKED: HRESULT = 0x8009301Au32 as HRESULT; +pub const OSS_CANT_OPEN_TRACE_FILE: HRESULT = 0x8009301Bu32 as HRESULT; +pub const OSS_TRACE_FILE_ALREADY_OPEN: HRESULT = 0x8009301Cu32 as HRESULT; +pub const OSS_TABLE_MISMATCH: HRESULT = 0x8009301Du32 as HRESULT; +pub const OSS_TYPE_NOT_SUPPORTED: HRESULT = 0x8009301Eu32 as HRESULT; +pub const OSS_REAL_DLL_NOT_LINKED: HRESULT = 0x8009301Fu32 as HRESULT; +pub const OSS_REAL_CODE_NOT_LINKED: HRESULT = 0x80093020u32 as HRESULT; +pub const OSS_OUT_OF_RANGE: HRESULT = 0x80093021u32 as HRESULT; +pub const OSS_COPIER_DLL_NOT_LINKED: HRESULT = 0x80093022u32 as HRESULT; +pub const OSS_CONSTRAINT_DLL_NOT_LINKED: HRESULT = 0x80093023u32 as HRESULT; +pub const OSS_COMPARATOR_DLL_NOT_LINKED: HRESULT = 0x80093024u32 as HRESULT; +pub const OSS_COMPARATOR_CODE_NOT_LINKED: HRESULT = 0x80093025u32 as HRESULT; +pub const OSS_MEM_MGR_DLL_NOT_LINKED: HRESULT = 0x80093026u32 as HRESULT; +pub const OSS_PDV_DLL_NOT_LINKED: HRESULT = 0x80093027u32 as HRESULT; +pub const OSS_PDV_CODE_NOT_LINKED: HRESULT = 0x80093028u32 as HRESULT; +pub const OSS_API_DLL_NOT_LINKED: HRESULT = 0x80093029u32 as HRESULT; +pub const OSS_BERDER_DLL_NOT_LINKED: HRESULT = 0x8009302Au32 as HRESULT; +pub const OSS_PER_DLL_NOT_LINKED: HRESULT = 0x8009302Bu32 as HRESULT; +pub const OSS_OPEN_TYPE_ERROR: HRESULT = 0x8009302Cu32 as HRESULT; +pub const OSS_MUTEX_NOT_CREATED: HRESULT = 0x8009302Du32 as HRESULT; +pub const OSS_CANT_CLOSE_TRACE_FILE: HRESULT = 0x8009302Eu32 as HRESULT; +pub const CRYPT_E_ASN1_ERROR: HRESULT = 0x80093100u32 as HRESULT; +pub const CRYPT_E_ASN1_INTERNAL: HRESULT = 0x80093101u32 as HRESULT; +pub const CRYPT_E_ASN1_EOD: HRESULT = 0x80093102u32 as HRESULT; +pub const CRYPT_E_ASN1_CORRUPT: HRESULT = 0x80093103u32 as HRESULT; +pub const CRYPT_E_ASN1_LARGE: HRESULT = 0x80093104u32 as HRESULT; +pub const CRYPT_E_ASN1_CONSTRAINT: HRESULT = 0x80093105u32 as HRESULT; +pub const CRYPT_E_ASN1_MEMORY: HRESULT = 0x80093106u32 as HRESULT; +pub const CRYPT_E_ASN1_OVERFLOW: HRESULT = 0x80093107u32 as HRESULT; +pub const CRYPT_E_ASN1_BADPDU: HRESULT = 0x80093108u32 as HRESULT; +pub const CRYPT_E_ASN1_BADARGS: HRESULT = 0x80093109u32 as HRESULT; +pub const CRYPT_E_ASN1_BADREAL: HRESULT = 0x8009310Au32 as HRESULT; +pub const CRYPT_E_ASN1_BADTAG: HRESULT = 0x8009310Bu32 as HRESULT; +pub const CRYPT_E_ASN1_CHOICE: HRESULT = 0x8009310Cu32 as HRESULT; +pub const CRYPT_E_ASN1_RULE: HRESULT = 0x8009310Du32 as HRESULT; +pub const CRYPT_E_ASN1_UTF8: HRESULT = 0x8009310Eu32 as HRESULT; +pub const CRYPT_E_ASN1_PDU_TYPE: HRESULT = 0x80093133u32 as HRESULT; +pub const CRYPT_E_ASN1_NYI: HRESULT = 0x80093134u32 as HRESULT; +pub const CRYPT_E_ASN1_EXTENDED: HRESULT = 0x80093201u32 as HRESULT; +pub const CRYPT_E_ASN1_NOEOD: HRESULT = 0x80093202u32 as HRESULT; +pub const CERTSRV_E_BAD_REQUESTSUBJECT: HRESULT = 0x80094001u32 as HRESULT; +pub const CERTSRV_E_NO_REQUEST: HRESULT = 0x80094002u32 as HRESULT; +pub const CERTSRV_E_BAD_REQUESTSTATUS: HRESULT = 0x80094003u32 as HRESULT; +pub const CERTSRV_E_PROPERTY_EMPTY: HRESULT = 0x80094004u32 as HRESULT; +pub const CERTSRV_E_INVALID_CA_CERTIFICATE: HRESULT = 0x80094005u32 as HRESULT; +pub const CERTSRV_E_SERVER_SUSPENDED: HRESULT = 0x80094006u32 as HRESULT; +pub const CERTSRV_E_ENCODING_LENGTH: HRESULT = 0x80094007u32 as HRESULT; +pub const CERTSRV_E_ROLECONFLICT: HRESULT = 0x80094008u32 as HRESULT; +pub const CERTSRV_E_RESTRICTEDOFFICER: HRESULT = 0x80094009u32 as HRESULT; +pub const CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED: HRESULT = 0x8009400Au32 as HRESULT; +pub const CERTSRV_E_NO_VALID_KRA: HRESULT = 0x8009400Bu32 as HRESULT; +pub const CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL: HRESULT = 0x8009400Cu32 as HRESULT; +pub const CERTSRV_E_NO_CAADMIN_DEFINED: HRESULT = 0x8009400Du32 as HRESULT; +pub const CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE: HRESULT = 0x8009400Eu32 as HRESULT; +pub const CERTSRV_E_NO_DB_SESSIONS: HRESULT = 0x8009400Fu32 as HRESULT; +pub const CERTSRV_E_ALIGNMENT_FAULT: HRESULT = 0x80094010u32 as HRESULT; +pub const CERTSRV_E_ENROLL_DENIED: HRESULT = 0x80094011u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_DENIED: HRESULT = 0x80094012u32 as HRESULT; +pub const CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE: HRESULT = 0x80094013u32 as HRESULT; +pub const CERTSRV_E_ADMIN_DENIED_REQUEST: HRESULT = 0x80094014u32 as HRESULT; +pub const CERTSRV_E_NO_POLICY_SERVER: HRESULT = 0x80094015u32 as HRESULT; +pub const CERTSRV_E_WEAK_SIGNATURE_OR_KEY: HRESULT = 0x80094016u32 as HRESULT; +pub const CERTSRV_E_KEY_ATTESTATION_NOT_SUPPORTED: HRESULT = 0x80094017u32 as HRESULT; +pub const CERTSRV_E_ENCRYPTION_CERT_REQUIRED: HRESULT = 0x80094018u32 as HRESULT; +pub const CERTSRV_E_UNSUPPORTED_CERT_TYPE: HRESULT = 0x80094800u32 as HRESULT; +pub const CERTSRV_E_NO_CERT_TYPE: HRESULT = 0x80094801u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_CONFLICT: HRESULT = 0x80094802u32 as HRESULT; +pub const CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED: HRESULT = 0x80094803u32 as HRESULT; +pub const CERTSRV_E_ARCHIVED_KEY_REQUIRED: HRESULT = 0x80094804u32 as HRESULT; +pub const CERTSRV_E_SMIME_REQUIRED: HRESULT = 0x80094805u32 as HRESULT; +pub const CERTSRV_E_BAD_RENEWAL_SUBJECT: HRESULT = 0x80094806u32 as HRESULT; +pub const CERTSRV_E_BAD_TEMPLATE_VERSION: HRESULT = 0x80094807u32 as HRESULT; +pub const CERTSRV_E_TEMPLATE_POLICY_REQUIRED: HRESULT = 0x80094808u32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_POLICY_REQUIRED: HRESULT = 0x80094809u32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_COUNT: HRESULT = 0x8009480Au32 as HRESULT; +pub const CERTSRV_E_SIGNATURE_REJECTED: HRESULT = 0x8009480Bu32 as HRESULT; +pub const CERTSRV_E_ISSUANCE_POLICY_REQUIRED: HRESULT = 0x8009480Cu32 as HRESULT; +pub const CERTSRV_E_SUBJECT_UPN_REQUIRED: HRESULT = 0x8009480Du32 as HRESULT; +pub const CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED: HRESULT = 0x8009480Eu32 as HRESULT; +pub const CERTSRV_E_SUBJECT_DNS_REQUIRED: HRESULT = 0x8009480Fu32 as HRESULT; +pub const CERTSRV_E_ARCHIVED_KEY_UNEXPECTED: HRESULT = 0x80094810u32 as HRESULT; +pub const CERTSRV_E_KEY_LENGTH: HRESULT = 0x80094811u32 as HRESULT; +pub const CERTSRV_E_SUBJECT_EMAIL_REQUIRED: HRESULT = 0x80094812u32 as HRESULT; +pub const CERTSRV_E_UNKNOWN_CERT_TYPE: HRESULT = 0x80094813u32 as HRESULT; +pub const CERTSRV_E_CERT_TYPE_OVERLAP: HRESULT = 0x80094814u32 as HRESULT; +pub const CERTSRV_E_TOO_MANY_SIGNATURES: HRESULT = 0x80094815u32 as HRESULT; +pub const CERTSRV_E_RENEWAL_BAD_PUBLIC_KEY: HRESULT = 0x80094816u32 as HRESULT; +pub const CERTSRV_E_INVALID_EK: HRESULT = 0x80094817u32 as HRESULT; +pub const CERTSRV_E_INVALID_IDBINDING: HRESULT = 0x80094818u32 as HRESULT; +pub const CERTSRV_E_INVALID_ATTESTATION: HRESULT = 0x80094819u32 as HRESULT; +pub const CERTSRV_E_KEY_ATTESTATION: HRESULT = 0x8009481Au32 as HRESULT; +pub const CERTSRV_E_CORRUPT_KEY_ATTESTATION: HRESULT = 0x8009481Bu32 as HRESULT; +pub const CERTSRV_E_EXPIRED_CHALLENGE: HRESULT = 0x8009481Cu32 as HRESULT; +pub const CERTSRV_E_INVALID_RESPONSE: HRESULT = 0x8009481Du32 as HRESULT; +pub const CERTSRV_E_INVALID_REQUESTID: HRESULT = 0x8009481Eu32 as HRESULT; +pub const XENROLL_E_KEY_NOT_EXPORTABLE: HRESULT = 0x80095000u32 as HRESULT; +pub const XENROLL_E_CANNOT_ADD_ROOT_CERT: HRESULT = 0x80095001u32 as HRESULT; +pub const XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND: HRESULT = 0x80095002u32 as HRESULT; +pub const XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH: HRESULT = 0x80095003u32 as HRESULT; +pub const XENROLL_E_RESPONSE_KA_HASH_MISMATCH: HRESULT = 0x80095004u32 as HRESULT; +pub const XENROLL_E_KEYSPEC_SMIME_MISMATCH: HRESULT = 0x80095005u32 as HRESULT; +pub const TRUST_E_SYSTEM_ERROR: HRESULT = 0x80096001u32 as HRESULT; +pub const TRUST_E_NO_SIGNER_CERT: HRESULT = 0x80096002u32 as HRESULT; +pub const TRUST_E_COUNTER_SIGNER: HRESULT = 0x80096003u32 as HRESULT; +pub const TRUST_E_CERT_SIGNATURE: HRESULT = 0x80096004u32 as HRESULT; +pub const TRUST_E_TIME_STAMP: HRESULT = 0x80096005u32 as HRESULT; +pub const TRUST_E_BAD_DIGEST: HRESULT = 0x80096010u32 as HRESULT; +pub const TRUST_E_BASIC_CONSTRAINTS: HRESULT = 0x80096019u32 as HRESULT; +pub const TRUST_E_FINANCIAL_CRITERIA: HRESULT = 0x8009601Eu32 as HRESULT; +pub const MSSIPOTF_E_OUTOFMEMRANGE: HRESULT = 0x80097001u32 as HRESULT; +pub const MSSIPOTF_E_CANTGETOBJECT: HRESULT = 0x80097002u32 as HRESULT; +pub const MSSIPOTF_E_NOHEADTABLE: HRESULT = 0x80097003u32 as HRESULT; +pub const MSSIPOTF_E_BAD_MAGICNUMBER: HRESULT = 0x80097004u32 as HRESULT; +pub const MSSIPOTF_E_BAD_OFFSET_TABLE: HRESULT = 0x80097005u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_TAGORDER: HRESULT = 0x80097006u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_LONGWORD: HRESULT = 0x80097007u32 as HRESULT; +pub const MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT: HRESULT = 0x80097008u32 as HRESULT; +pub const MSSIPOTF_E_TABLES_OVERLAP: HRESULT = 0x80097009u32 as HRESULT; +pub const MSSIPOTF_E_TABLE_PADBYTES: HRESULT = 0x8009700Au32 as HRESULT; +pub const MSSIPOTF_E_FILETOOSMALL: HRESULT = 0x8009700Bu32 as HRESULT; +pub const MSSIPOTF_E_TABLE_CHECKSUM: HRESULT = 0x8009700Cu32 as HRESULT; +pub const MSSIPOTF_E_FILE_CHECKSUM: HRESULT = 0x8009700Du32 as HRESULT; +pub const MSSIPOTF_E_FAILED_POLICY: HRESULT = 0x80097010u32 as HRESULT; +pub const MSSIPOTF_E_FAILED_HINTS_CHECK: HRESULT = 0x80097011u32 as HRESULT; +pub const MSSIPOTF_E_NOT_OPENTYPE: HRESULT = 0x80097012u32 as HRESULT; +pub const MSSIPOTF_E_FILE: HRESULT = 0x80097013u32 as HRESULT; +pub const MSSIPOTF_E_CRYPT: HRESULT = 0x80097014u32 as HRESULT; +pub const MSSIPOTF_E_BADVERSION: HRESULT = 0x80097015u32 as HRESULT; +pub const MSSIPOTF_E_DSIG_STRUCTURE: HRESULT = 0x80097016u32 as HRESULT; +pub const MSSIPOTF_E_PCONST_CHECK: HRESULT = 0x80097017u32 as HRESULT; +pub const MSSIPOTF_E_STRUCTURE: HRESULT = 0x80097018u32 as HRESULT; +pub const ERROR_CRED_REQUIRES_CONFIRMATION: HRESULT = 0x80097019u32 as HRESULT; +pub const NTE_OP_OK: HRESULT = 0; +pub const TRUST_E_PROVIDER_UNKNOWN: HRESULT = 0x800B0001u32 as HRESULT; +pub const TRUST_E_ACTION_UNKNOWN: HRESULT = 0x800B0002u32 as HRESULT; +pub const TRUST_E_SUBJECT_FORM_UNKNOWN: HRESULT = 0x800B0003u32 as HRESULT; +pub const TRUST_E_SUBJECT_NOT_TRUSTED: HRESULT = 0x800B0004u32 as HRESULT; +pub const DIGSIG_E_ENCODE: HRESULT = 0x800B0005u32 as HRESULT; +pub const DIGSIG_E_DECODE: HRESULT = 0x800B0006u32 as HRESULT; +pub const DIGSIG_E_EXTENSIBILITY: HRESULT = 0x800B0007u32 as HRESULT; +pub const DIGSIG_E_CRYPTO: HRESULT = 0x800B0008u32 as HRESULT; +pub const PERSIST_E_SIZEDEFINITE: HRESULT = 0x800B0009u32 as HRESULT; +pub const PERSIST_E_SIZEINDEFINITE: HRESULT = 0x800B000Au32 as HRESULT; +pub const PERSIST_E_NOTSELFSIZING: HRESULT = 0x800B000Bu32 as HRESULT; +pub const TRUST_E_NOSIGNATURE: HRESULT = 0x800B0100u32 as HRESULT; +pub const CERT_E_EXPIRED: HRESULT = 0x800B0101u32 as HRESULT; +pub const CERT_E_VALIDITYPERIODNESTING: HRESULT = 0x800B0102u32 as HRESULT; +pub const CERT_E_ROLE: HRESULT = 0x800B0103u32 as HRESULT; +pub const CERT_E_PATHLENCONST: HRESULT = 0x800B0104u32 as HRESULT; +pub const CERT_E_CRITICAL: HRESULT = 0x800B0105u32 as HRESULT; +pub const CERT_E_PURPOSE: HRESULT = 0x800B0106u32 as HRESULT; +pub const CERT_E_ISSUERCHAINING: HRESULT = 0x800B0107u32 as HRESULT; +pub const CERT_E_MALFORMED: HRESULT = 0x800B0108u32 as HRESULT; +pub const CERT_E_UNTRUSTEDROOT: HRESULT = 0x800B0109u32 as HRESULT; +pub const CERT_E_CHAINING: HRESULT = 0x800B010Au32 as HRESULT; +pub const TRUST_E_FAIL: HRESULT = 0x800B010Bu32 as HRESULT; +pub const CERT_E_REVOKED: HRESULT = 0x800B010Cu32 as HRESULT; +pub const CERT_E_UNTRUSTEDTESTROOT: HRESULT = 0x800B010Du32 as HRESULT; +pub const CERT_E_REVOCATION_FAILURE: HRESULT = 0x800B010Eu32 as HRESULT; +pub const CERT_E_CN_NO_MATCH: HRESULT = 0x800B010Fu32 as HRESULT; +pub const CERT_E_WRONG_USAGE: HRESULT = 0x800B0110u32 as HRESULT; +pub const TRUST_E_EXPLICIT_DISTRUST: HRESULT = 0x800B0111u32 as HRESULT; +pub const CERT_E_UNTRUSTEDCA: HRESULT = 0x800B0112u32 as HRESULT; +pub const CERT_E_INVALID_POLICY: HRESULT = 0x800B0113u32 as HRESULT; +pub const CERT_E_INVALID_NAME: HRESULT = 0x800B0114u32 as HRESULT; +pub const SPAPI_E_EXPECTED_SECTION_NAME: HRESULT = 0x800F0000u32 as HRESULT; +pub const SPAPI_E_BAD_SECTION_NAME_LINE: HRESULT = 0x800F0001u32 as HRESULT; +pub const SPAPI_E_SECTION_NAME_TOO_LONG: HRESULT = 0x800F0002u32 as HRESULT; +pub const SPAPI_E_GENERAL_SYNTAX: HRESULT = 0x800F0003u32 as HRESULT; +pub const SPAPI_E_WRONG_INF_STYLE: HRESULT = 0x800F0100u32 as HRESULT; +pub const SPAPI_E_SECTION_NOT_FOUND: HRESULT = 0x800F0101u32 as HRESULT; +pub const SPAPI_E_LINE_NOT_FOUND: HRESULT = 0x800F0102u32 as HRESULT; +pub const SPAPI_E_NO_BACKUP: HRESULT = 0x800F0103u32 as HRESULT; +pub const SPAPI_E_NO_ASSOCIATED_CLASS: HRESULT = 0x800F0200u32 as HRESULT; +pub const SPAPI_E_CLASS_MISMATCH: HRESULT = 0x800F0201u32 as HRESULT; +pub const SPAPI_E_DUPLICATE_FOUND: HRESULT = 0x800F0202u32 as HRESULT; +pub const SPAPI_E_NO_DRIVER_SELECTED: HRESULT = 0x800F0203u32 as HRESULT; +pub const SPAPI_E_KEY_DOES_NOT_EXIST: HRESULT = 0x800F0204u32 as HRESULT; +pub const SPAPI_E_INVALID_DEVINST_NAME: HRESULT = 0x800F0205u32 as HRESULT; +pub const SPAPI_E_INVALID_CLASS: HRESULT = 0x800F0206u32 as HRESULT; +pub const SPAPI_E_DEVINST_ALREADY_EXISTS: HRESULT = 0x800F0207u32 as HRESULT; +pub const SPAPI_E_DEVINFO_NOT_REGISTERED: HRESULT = 0x800F0208u32 as HRESULT; +pub const SPAPI_E_INVALID_REG_PROPERTY: HRESULT = 0x800F0209u32 as HRESULT; +pub const SPAPI_E_NO_INF: HRESULT = 0x800F020Au32 as HRESULT; +pub const SPAPI_E_NO_SUCH_DEVINST: HRESULT = 0x800F020Bu32 as HRESULT; +pub const SPAPI_E_CANT_LOAD_CLASS_ICON: HRESULT = 0x800F020Cu32 as HRESULT; +pub const SPAPI_E_INVALID_CLASS_INSTALLER: HRESULT = 0x800F020Du32 as HRESULT; +pub const SPAPI_E_DI_DO_DEFAULT: HRESULT = 0x800F020Eu32 as HRESULT; +pub const SPAPI_E_DI_NOFILECOPY: HRESULT = 0x800F020Fu32 as HRESULT; +pub const SPAPI_E_INVALID_HWPROFILE: HRESULT = 0x800F0210u32 as HRESULT; +pub const SPAPI_E_NO_DEVICE_SELECTED: HRESULT = 0x800F0211u32 as HRESULT; +pub const SPAPI_E_DEVINFO_LIST_LOCKED: HRESULT = 0x800F0212u32 as HRESULT; +pub const SPAPI_E_DEVINFO_DATA_LOCKED: HRESULT = 0x800F0213u32 as HRESULT; +pub const SPAPI_E_DI_BAD_PATH: HRESULT = 0x800F0214u32 as HRESULT; +pub const SPAPI_E_NO_CLASSINSTALL_PARAMS: HRESULT = 0x800F0215u32 as HRESULT; +pub const SPAPI_E_FILEQUEUE_LOCKED: HRESULT = 0x800F0216u32 as HRESULT; +pub const SPAPI_E_BAD_SERVICE_INSTALLSECT: HRESULT = 0x800F0217u32 as HRESULT; +pub const SPAPI_E_NO_CLASS_DRIVER_LIST: HRESULT = 0x800F0218u32 as HRESULT; +pub const SPAPI_E_NO_ASSOCIATED_SERVICE: HRESULT = 0x800F0219u32 as HRESULT; +pub const SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE: HRESULT = 0x800F021Au32 as HRESULT; +pub const SPAPI_E_DEVICE_INTERFACE_ACTIVE: HRESULT = 0x800F021Bu32 as HRESULT; +pub const SPAPI_E_DEVICE_INTERFACE_REMOVED: HRESULT = 0x800F021Cu32 as HRESULT; +pub const SPAPI_E_BAD_INTERFACE_INSTALLSECT: HRESULT = 0x800F021Du32 as HRESULT; +pub const SPAPI_E_NO_SUCH_INTERFACE_CLASS: HRESULT = 0x800F021Eu32 as HRESULT; +pub const SPAPI_E_INVALID_REFERENCE_STRING: HRESULT = 0x800F021Fu32 as HRESULT; +pub const SPAPI_E_INVALID_MACHINENAME: HRESULT = 0x800F0220u32 as HRESULT; +pub const SPAPI_E_REMOTE_COMM_FAILURE: HRESULT = 0x800F0221u32 as HRESULT; +pub const SPAPI_E_MACHINE_UNAVAILABLE: HRESULT = 0x800F0222u32 as HRESULT; +pub const SPAPI_E_NO_CONFIGMGR_SERVICES: HRESULT = 0x800F0223u32 as HRESULT; +pub const SPAPI_E_INVALID_PROPPAGE_PROVIDER: HRESULT = 0x800F0224u32 as HRESULT; +pub const SPAPI_E_NO_SUCH_DEVICE_INTERFACE: HRESULT = 0x800F0225u32 as HRESULT; +pub const SPAPI_E_DI_POSTPROCESSING_REQUIRED: HRESULT = 0x800F0226u32 as HRESULT; +pub const SPAPI_E_INVALID_COINSTALLER: HRESULT = 0x800F0227u32 as HRESULT; +pub const SPAPI_E_NO_COMPAT_DRIVERS: HRESULT = 0x800F0228u32 as HRESULT; +pub const SPAPI_E_NO_DEVICE_ICON: HRESULT = 0x800F0229u32 as HRESULT; +pub const SPAPI_E_INVALID_INF_LOGCONFIG: HRESULT = 0x800F022Au32 as HRESULT; +pub const SPAPI_E_DI_DONT_INSTALL: HRESULT = 0x800F022Bu32 as HRESULT; +pub const SPAPI_E_INVALID_FILTER_DRIVER: HRESULT = 0x800F022Cu32 as HRESULT; +pub const SPAPI_E_NON_WINDOWS_NT_DRIVER: HRESULT = 0x800F022Du32 as HRESULT; +pub const SPAPI_E_NON_WINDOWS_DRIVER: HRESULT = 0x800F022Eu32 as HRESULT; +pub const SPAPI_E_NO_CATALOG_FOR_OEM_INF: HRESULT = 0x800F022Fu32 as HRESULT; +pub const SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE: HRESULT = 0x800F0230u32 as HRESULT; +pub const SPAPI_E_NOT_DISABLEABLE: HRESULT = 0x800F0231u32 as HRESULT; +pub const SPAPI_E_CANT_REMOVE_DEVINST: HRESULT = 0x800F0232u32 as HRESULT; +pub const SPAPI_E_INVALID_TARGET: HRESULT = 0x800F0233u32 as HRESULT; +pub const SPAPI_E_DRIVER_NONNATIVE: HRESULT = 0x800F0234u32 as HRESULT; +pub const SPAPI_E_IN_WOW64: HRESULT = 0x800F0235u32 as HRESULT; +pub const SPAPI_E_SET_SYSTEM_RESTORE_POINT: HRESULT = 0x800F0236u32 as HRESULT; +pub const SPAPI_E_INCORRECTLY_COPIED_INF: HRESULT = 0x800F0237u32 as HRESULT; +pub const SPAPI_E_SCE_DISABLED: HRESULT = 0x800F0238u32 as HRESULT; +pub const SPAPI_E_UNKNOWN_EXCEPTION: HRESULT = 0x800F0239u32 as HRESULT; +pub const SPAPI_E_PNP_REGISTRY_ERROR: HRESULT = 0x800F023Au32 as HRESULT; +pub const SPAPI_E_REMOTE_REQUEST_UNSUPPORTED: HRESULT = 0x800F023Bu32 as HRESULT; +pub const SPAPI_E_NOT_AN_INSTALLED_OEM_INF: HRESULT = 0x800F023Cu32 as HRESULT; +pub const SPAPI_E_INF_IN_USE_BY_DEVICES: HRESULT = 0x800F023Du32 as HRESULT; +pub const SPAPI_E_DI_FUNCTION_OBSOLETE: HRESULT = 0x800F023Eu32 as HRESULT; +pub const SPAPI_E_NO_AUTHENTICODE_CATALOG: HRESULT = 0x800F023Fu32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_DISALLOWED: HRESULT = 0x800F0240u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER: HRESULT = 0x800F0241u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED: HRESULT = 0x800F0242u32 as HRESULT; +pub const SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: HRESULT = 0x800F0243u32 as HRESULT; +pub const SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH: HRESULT = 0x800F0244u32 as HRESULT; +pub const SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE: HRESULT = 0x800F0245u32 as HRESULT; +pub const SPAPI_E_DEVICE_INSTALLER_NOT_READY: HRESULT = 0x800F0246u32 as HRESULT; +pub const SPAPI_E_DRIVER_STORE_ADD_FAILED: HRESULT = 0x800F0247u32 as HRESULT; +pub const SPAPI_E_DEVICE_INSTALL_BLOCKED: HRESULT = 0x800F0248u32 as HRESULT; +pub const SPAPI_E_DRIVER_INSTALL_BLOCKED: HRESULT = 0x800F0249u32 as HRESULT; +pub const SPAPI_E_WRONG_INF_TYPE: HRESULT = 0x800F024Au32 as HRESULT; +pub const SPAPI_E_FILE_HASH_NOT_IN_CATALOG: HRESULT = 0x800F024Bu32 as HRESULT; +pub const SPAPI_E_DRIVER_STORE_DELETE_FAILED: HRESULT = 0x800F024Cu32 as HRESULT; +pub const SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW: HRESULT = 0x800F0300u32 as HRESULT; +pub const SPAPI_E_ERROR_NOT_INSTALLED: HRESULT = 0x800F1000u32 as HRESULT; +pub const SCARD_S_SUCCESS: HRESULT = NO_ERROR as HRESULT; +pub const SCARD_F_INTERNAL_ERROR: HRESULT = 0x80100001u32 as HRESULT; +pub const SCARD_E_CANCELLED: HRESULT = 0x80100002u32 as HRESULT; +pub const SCARD_E_INVALID_HANDLE: HRESULT = 0x80100003u32 as HRESULT; +pub const SCARD_E_INVALID_PARAMETER: HRESULT = 0x80100004u32 as HRESULT; +pub const SCARD_E_INVALID_TARGET: HRESULT = 0x80100005u32 as HRESULT; +pub const SCARD_E_NO_MEMORY: HRESULT = 0x80100006u32 as HRESULT; +pub const SCARD_F_WAITED_TOO_LONG: HRESULT = 0x80100007u32 as HRESULT; +pub const SCARD_E_INSUFFICIENT_BUFFER: HRESULT = 0x80100008u32 as HRESULT; +pub const SCARD_E_UNKNOWN_READER: HRESULT = 0x80100009u32 as HRESULT; +pub const SCARD_E_TIMEOUT: HRESULT = 0x8010000Au32 as HRESULT; +pub const SCARD_E_SHARING_VIOLATION: HRESULT = 0x8010000Bu32 as HRESULT; +pub const SCARD_E_NO_SMARTCARD: HRESULT = 0x8010000Cu32 as HRESULT; +pub const SCARD_E_UNKNOWN_CARD: HRESULT = 0x8010000Du32 as HRESULT; +pub const SCARD_E_CANT_DISPOSE: HRESULT = 0x8010000Eu32 as HRESULT; +pub const SCARD_E_PROTO_MISMATCH: HRESULT = 0x8010000Fu32 as HRESULT; +pub const SCARD_E_NOT_READY: HRESULT = 0x80100010u32 as HRESULT; +pub const SCARD_E_INVALID_VALUE: HRESULT = 0x80100011u32 as HRESULT; +pub const SCARD_E_SYSTEM_CANCELLED: HRESULT = 0x80100012u32 as HRESULT; +pub const SCARD_F_COMM_ERROR: HRESULT = 0x80100013u32 as HRESULT; +pub const SCARD_F_UNKNOWN_ERROR: HRESULT = 0x80100014u32 as HRESULT; +pub const SCARD_E_INVALID_ATR: HRESULT = 0x80100015u32 as HRESULT; +pub const SCARD_E_NOT_TRANSACTED: HRESULT = 0x80100016u32 as HRESULT; +pub const SCARD_E_READER_UNAVAILABLE: HRESULT = 0x80100017u32 as HRESULT; +pub const SCARD_P_SHUTDOWN: HRESULT = 0x80100018u32 as HRESULT; +pub const SCARD_E_PCI_TOO_SMALL: HRESULT = 0x80100019u32 as HRESULT; +pub const SCARD_E_READER_UNSUPPORTED: HRESULT = 0x8010001Au32 as HRESULT; +pub const SCARD_E_DUPLICATE_READER: HRESULT = 0x8010001Bu32 as HRESULT; +pub const SCARD_E_CARD_UNSUPPORTED: HRESULT = 0x8010001Cu32 as HRESULT; +pub const SCARD_E_NO_SERVICE: HRESULT = 0x8010001Du32 as HRESULT; +pub const SCARD_E_SERVICE_STOPPED: HRESULT = 0x8010001Eu32 as HRESULT; +pub const SCARD_E_UNEXPECTED: HRESULT = 0x8010001Fu32 as HRESULT; +pub const SCARD_E_ICC_INSTALLATION: HRESULT = 0x80100020u32 as HRESULT; +pub const SCARD_E_ICC_CREATEORDER: HRESULT = 0x80100021u32 as HRESULT; +pub const SCARD_E_UNSUPPORTED_FEATURE: HRESULT = 0x80100022u32 as HRESULT; +pub const SCARD_E_DIR_NOT_FOUND: HRESULT = 0x80100023u32 as HRESULT; +pub const SCARD_E_FILE_NOT_FOUND: HRESULT = 0x80100024u32 as HRESULT; +pub const SCARD_E_NO_DIR: HRESULT = 0x80100025u32 as HRESULT; +pub const SCARD_E_NO_FILE: HRESULT = 0x80100026u32 as HRESULT; +pub const SCARD_E_NO_ACCESS: HRESULT = 0x80100027u32 as HRESULT; +pub const SCARD_E_WRITE_TOO_MANY: HRESULT = 0x80100028u32 as HRESULT; +pub const SCARD_E_BAD_SEEK: HRESULT = 0x80100029u32 as HRESULT; +pub const SCARD_E_INVALID_CHV: HRESULT = 0x8010002Au32 as HRESULT; +pub const SCARD_E_UNKNOWN_RES_MNG: HRESULT = 0x8010002Bu32 as HRESULT; +pub const SCARD_E_NO_SUCH_CERTIFICATE: HRESULT = 0x8010002Cu32 as HRESULT; +pub const SCARD_E_CERTIFICATE_UNAVAILABLE: HRESULT = 0x8010002Du32 as HRESULT; +pub const SCARD_E_NO_READERS_AVAILABLE: HRESULT = 0x8010002Eu32 as HRESULT; +pub const SCARD_E_COMM_DATA_LOST: HRESULT = 0x8010002Fu32 as HRESULT; +pub const SCARD_E_NO_KEY_CONTAINER: HRESULT = 0x80100030u32 as HRESULT; +pub const SCARD_E_SERVER_TOO_BUSY: HRESULT = 0x80100031u32 as HRESULT; +pub const SCARD_E_PIN_CACHE_EXPIRED: HRESULT = 0x80100032u32 as HRESULT; +pub const SCARD_E_NO_PIN_CACHE: HRESULT = 0x80100033u32 as HRESULT; +pub const SCARD_E_READ_ONLY_CARD: HRESULT = 0x80100034u32 as HRESULT; +pub const SCARD_W_UNSUPPORTED_CARD: HRESULT = 0x80100065u32 as HRESULT; +pub const SCARD_W_UNRESPONSIVE_CARD: HRESULT = 0x80100066u32 as HRESULT; +pub const SCARD_W_UNPOWERED_CARD: HRESULT = 0x80100067u32 as HRESULT; +pub const SCARD_W_RESET_CARD: HRESULT = 0x80100068u32 as HRESULT; +pub const SCARD_W_REMOVED_CARD: HRESULT = 0x80100069u32 as HRESULT; +pub const SCARD_W_SECURITY_VIOLATION: HRESULT = 0x8010006Au32 as HRESULT; +pub const SCARD_W_WRONG_CHV: HRESULT = 0x8010006Bu32 as HRESULT; +pub const SCARD_W_CHV_BLOCKED: HRESULT = 0x8010006Cu32 as HRESULT; +pub const SCARD_W_EOF: HRESULT = 0x8010006Du32 as HRESULT; +pub const SCARD_W_CANCELLED_BY_USER: HRESULT = 0x8010006Eu32 as HRESULT; +pub const SCARD_W_CARD_NOT_AUTHENTICATED: HRESULT = 0x8010006Fu32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_NOT_FOUND: HRESULT = 0x80100070u32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_STALE: HRESULT = 0x80100071u32 as HRESULT; +pub const SCARD_W_CACHE_ITEM_TOO_BIG: HRESULT = 0x80100072u32 as HRESULT; +pub const COMADMIN_E_OBJECTERRORS: HRESULT = 0x80110401u32 as HRESULT; +pub const COMADMIN_E_OBJECTINVALID: HRESULT = 0x80110402u32 as HRESULT; +pub const COMADMIN_E_KEYMISSING: HRESULT = 0x80110403u32 as HRESULT; +pub const COMADMIN_E_ALREADYINSTALLED: HRESULT = 0x80110404u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_WRITEFAIL: HRESULT = 0x80110407u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_READFAIL: HRESULT = 0x80110408u32 as HRESULT; +pub const COMADMIN_E_APP_FILE_VERSION: HRESULT = 0x80110409u32 as HRESULT; +pub const COMADMIN_E_BADPATH: HRESULT = 0x8011040Au32 as HRESULT; +pub const COMADMIN_E_APPLICATIONEXISTS: HRESULT = 0x8011040Bu32 as HRESULT; +pub const COMADMIN_E_ROLEEXISTS: HRESULT = 0x8011040Cu32 as HRESULT; +pub const COMADMIN_E_CANTCOPYFILE: HRESULT = 0x8011040Du32 as HRESULT; +pub const COMADMIN_E_NOUSER: HRESULT = 0x8011040Fu32 as HRESULT; +pub const COMADMIN_E_INVALIDUSERIDS: HRESULT = 0x80110410u32 as HRESULT; +pub const COMADMIN_E_NOREGISTRYCLSID: HRESULT = 0x80110411u32 as HRESULT; +pub const COMADMIN_E_BADREGISTRYPROGID: HRESULT = 0x80110412u32 as HRESULT; +pub const COMADMIN_E_AUTHENTICATIONLEVEL: HRESULT = 0x80110413u32 as HRESULT; +pub const COMADMIN_E_USERPASSWDNOTVALID: HRESULT = 0x80110414u32 as HRESULT; +pub const COMADMIN_E_CLSIDORIIDMISMATCH: HRESULT = 0x80110418u32 as HRESULT; +pub const COMADMIN_E_REMOTEINTERFACE: HRESULT = 0x80110419u32 as HRESULT; +pub const COMADMIN_E_DLLREGISTERSERVER: HRESULT = 0x8011041Au32 as HRESULT; +pub const COMADMIN_E_NOSERVERSHARE: HRESULT = 0x8011041Bu32 as HRESULT; +pub const COMADMIN_E_DLLLOADFAILED: HRESULT = 0x8011041Du32 as HRESULT; +pub const COMADMIN_E_BADREGISTRYLIBID: HRESULT = 0x8011041Eu32 as HRESULT; +pub const COMADMIN_E_APPDIRNOTFOUND: HRESULT = 0x8011041Fu32 as HRESULT; +pub const COMADMIN_E_REGISTRARFAILED: HRESULT = 0x80110423u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_DOESNOTEXIST: HRESULT = 0x80110424u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_LOADDLLFAIL: HRESULT = 0x80110425u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_GETCLASSOBJ: HRESULT = 0x80110426u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_CLASSNOTAVAIL: HRESULT = 0x80110427u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_BADTLB: HRESULT = 0x80110428u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_NOTINSTALLABLE: HRESULT = 0x80110429u32 as HRESULT; +pub const COMADMIN_E_NOTCHANGEABLE: HRESULT = 0x8011042Au32 as HRESULT; +pub const COMADMIN_E_NOTDELETEABLE: HRESULT = 0x8011042Bu32 as HRESULT; +pub const COMADMIN_E_SESSION: HRESULT = 0x8011042Cu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_LOCKED: HRESULT = 0x8011042Du32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_BAD_DEST: HRESULT = 0x8011042Eu32 as HRESULT; +pub const COMADMIN_E_REGISTERTLB: HRESULT = 0x80110430u32 as HRESULT; +pub const COMADMIN_E_SYSTEMAPP: HRESULT = 0x80110433u32 as HRESULT; +pub const COMADMIN_E_COMPFILE_NOREGISTRAR: HRESULT = 0x80110434u32 as HRESULT; +pub const COMADMIN_E_COREQCOMPINSTALLED: HRESULT = 0x80110435u32 as HRESULT; +pub const COMADMIN_E_SERVICENOTINSTALLED: HRESULT = 0x80110436u32 as HRESULT; +pub const COMADMIN_E_PROPERTYSAVEFAILED: HRESULT = 0x80110437u32 as HRESULT; +pub const COMADMIN_E_OBJECTEXISTS: HRESULT = 0x80110438u32 as HRESULT; +pub const COMADMIN_E_COMPONENTEXISTS: HRESULT = 0x80110439u32 as HRESULT; +pub const COMADMIN_E_REGFILE_CORRUPT: HRESULT = 0x8011043Bu32 as HRESULT; +pub const COMADMIN_E_PROPERTY_OVERFLOW: HRESULT = 0x8011043Cu32 as HRESULT; +pub const COMADMIN_E_NOTINREGISTRY: HRESULT = 0x8011043Eu32 as HRESULT; +pub const COMADMIN_E_OBJECTNOTPOOLABLE: HRESULT = 0x8011043Fu32 as HRESULT; +pub const COMADMIN_E_APPLID_MATCHES_CLSID: HRESULT = 0x80110446u32 as HRESULT; +pub const COMADMIN_E_ROLE_DOES_NOT_EXIST: HRESULT = 0x80110447u32 as HRESULT; +pub const COMADMIN_E_START_APP_NEEDS_COMPONENTS: HRESULT = 0x80110448u32 as HRESULT; +pub const COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM: HRESULT = 0x80110449u32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY: HRESULT = 0x8011044Au32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_START_APP: HRESULT = 0x8011044Bu32 as HRESULT; +pub const COMADMIN_E_CAN_NOT_EXPORT_SYS_APP: HRESULT = 0x8011044Cu32 as HRESULT; +pub const COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT: HRESULT = 0x8011044Du32 as HRESULT; +pub const COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER: HRESULT = 0x8011044Eu32 as HRESULT; +pub const COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE: HRESULT = 0x8011044Fu32 as HRESULT; +pub const COMADMIN_E_BASE_PARTITION_ONLY: HRESULT = 0x80110450u32 as HRESULT; +pub const COMADMIN_E_START_APP_DISABLED: HRESULT = 0x80110451u32 as HRESULT; +pub const COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME: HRESULT = 0x80110457u32 as HRESULT; +pub const COMADMIN_E_CAT_INVALID_PARTITION_NAME: HRESULT = 0x80110458u32 as HRESULT; +pub const COMADMIN_E_CAT_PARTITION_IN_USE: HRESULT = 0x80110459u32 as HRESULT; +pub const COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES: HRESULT = 0x8011045Au32 as HRESULT; +pub const COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED: HRESULT = 0x8011045Bu32 as HRESULT; +pub const COMADMIN_E_AMBIGUOUS_APPLICATION_NAME: HRESULT = 0x8011045Cu32 as HRESULT; +pub const COMADMIN_E_AMBIGUOUS_PARTITION_NAME: HRESULT = 0x8011045Du32 as HRESULT; +pub const COMADMIN_E_REGDB_NOTINITIALIZED: HRESULT = 0x80110472u32 as HRESULT; +pub const COMADMIN_E_REGDB_NOTOPEN: HRESULT = 0x80110473u32 as HRESULT; +pub const COMADMIN_E_REGDB_SYSTEMERR: HRESULT = 0x80110474u32 as HRESULT; +pub const COMADMIN_E_REGDB_ALREADYRUNNING: HRESULT = 0x80110475u32 as HRESULT; +pub const COMADMIN_E_MIG_VERSIONNOTSUPPORTED: HRESULT = 0x80110480u32 as HRESULT; +pub const COMADMIN_E_MIG_SCHEMANOTFOUND: HRESULT = 0x80110481u32 as HRESULT; +pub const COMADMIN_E_CAT_BITNESSMISMATCH: HRESULT = 0x80110482u32 as HRESULT; +pub const COMADMIN_E_CAT_UNACCEPTABLEBITNESS: HRESULT = 0x80110483u32 as HRESULT; +pub const COMADMIN_E_CAT_WRONGAPPBITNESS: HRESULT = 0x80110484u32 as HRESULT; +pub const COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED: HRESULT = 0x80110485u32 as HRESULT; +pub const COMADMIN_E_CAT_SERVERFAULT: HRESULT = 0x80110486u32 as HRESULT; +pub const COMQC_E_APPLICATION_NOT_QUEUED: HRESULT = 0x80110600u32 as HRESULT; +pub const COMQC_E_NO_QUEUEABLE_INTERFACES: HRESULT = 0x80110601u32 as HRESULT; +pub const COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE: HRESULT = 0x80110602u32 as HRESULT; +pub const COMQC_E_NO_IPERSISTSTREAM: HRESULT = 0x80110603u32 as HRESULT; +pub const COMQC_E_BAD_MESSAGE: HRESULT = 0x80110604u32 as HRESULT; +pub const COMQC_E_UNAUTHENTICATED: HRESULT = 0x80110605u32 as HRESULT; +pub const COMQC_E_UNTRUSTED_ENQUEUER: HRESULT = 0x80110606u32 as HRESULT; +pub const MSDTC_E_DUPLICATE_RESOURCE: HRESULT = 0x80110701u32 as HRESULT; +pub const COMADMIN_E_OBJECT_PARENT_MISSING: HRESULT = 0x80110808u32 as HRESULT; +pub const COMADMIN_E_OBJECT_DOES_NOT_EXIST: HRESULT = 0x80110809u32 as HRESULT; +pub const COMADMIN_E_APP_NOT_RUNNING: HRESULT = 0x8011080Au32 as HRESULT; +pub const COMADMIN_E_INVALID_PARTITION: HRESULT = 0x8011080Bu32 as HRESULT; +pub const COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE: HRESULT = 0x8011080Du32 as HRESULT; +pub const COMADMIN_E_USER_IN_SET: HRESULT = 0x8011080Eu32 as HRESULT; +pub const COMADMIN_E_CANTRECYCLELIBRARYAPPS: HRESULT = 0x8011080Fu32 as HRESULT; +pub const COMADMIN_E_CANTRECYCLESERVICEAPPS: HRESULT = 0x80110811u32 as HRESULT; +pub const COMADMIN_E_PROCESSALREADYRECYCLED: HRESULT = 0x80110812u32 as HRESULT; +pub const COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED: HRESULT = 0x80110813u32 as HRESULT; +pub const COMADMIN_E_CANTMAKEINPROCSERVICE: HRESULT = 0x80110814u32 as HRESULT; +pub const COMADMIN_E_PROGIDINUSEBYCLSID: HRESULT = 0x80110815u32 as HRESULT; +pub const COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET: HRESULT = 0x80110816u32 as HRESULT; +pub const COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED: HRESULT = 0x80110817u32 as HRESULT; +pub const COMADMIN_E_PARTITION_ACCESSDENIED: HRESULT = 0x80110818u32 as HRESULT; +pub const COMADMIN_E_PARTITION_MSI_ONLY: HRESULT = 0x80110819u32 as HRESULT; +pub const COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT: HRESULT = 0x8011081Au32 as HRESULT; +pub const COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS: HRESULT = 0x8011081Bu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_SOURCE: HRESULT = 0x8011081Cu32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_DEST: HRESULT = 0x8011081Du32 as HRESULT; +pub const COMADMIN_E_COMP_MOVE_PRIVATE: HRESULT = 0x8011081Eu32 as HRESULT; +pub const COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET: HRESULT = 0x8011081Fu32 as HRESULT; +pub const COMADMIN_E_CANNOT_ALIAS_EVENTCLASS: HRESULT = 0x80110820u32 as HRESULT; +pub const COMADMIN_E_PRIVATE_ACCESSDENIED: HRESULT = 0x80110821u32 as HRESULT; +pub const COMADMIN_E_SAFERINVALID: HRESULT = 0x80110822u32 as HRESULT; +pub const COMADMIN_E_REGISTRY_ACCESSDENIED: HRESULT = 0x80110823u32 as HRESULT; +pub const COMADMIN_E_PARTITIONS_DISABLED: HRESULT = 0x80110824u32 as HRESULT; +pub const WER_S_REPORT_DEBUG: HRESULT = 0x001B0000; +pub const WER_S_REPORT_UPLOADED: HRESULT = 0x001B0001; +pub const WER_S_REPORT_QUEUED: HRESULT = 0x001B0002; +pub const WER_S_DISABLED: HRESULT = 0x001B0003; +pub const WER_S_SUSPENDED_UPLOAD: HRESULT = 0x001B0004; +pub const WER_S_DISABLED_QUEUE: HRESULT = 0x001B0005; +pub const WER_S_DISABLED_ARCHIVE: HRESULT = 0x001B0006; +pub const WER_S_REPORT_ASYNC: HRESULT = 0x001B0007; +pub const WER_S_IGNORE_ASSERT_INSTANCE: HRESULT = 0x001B0008; +pub const WER_S_IGNORE_ALL_ASSERTS: HRESULT = 0x001B0009; +pub const WER_S_ASSERT_CONTINUE: HRESULT = 0x001B000A; +pub const WER_S_THROTTLED: HRESULT = 0x001B000B; +pub const WER_E_CRASH_FAILURE: HRESULT = 0x801B8000u32 as HRESULT; +pub const WER_E_CANCELED: HRESULT = 0x801B8001u32 as HRESULT; +pub const WER_E_NETWORK_FAILURE: HRESULT = 0x801B8002u32 as HRESULT; +pub const WER_E_NOT_INITIALIZED: HRESULT = 0x801B8003u32 as HRESULT; +pub const WER_E_ALREADY_REPORTING: HRESULT = 0x801B8004u32 as HRESULT; +pub const WER_E_DUMP_THROTTLED: HRESULT = 0x801B8005u32 as HRESULT; +pub const ERROR_FLT_IO_COMPLETE: HRESULT = 0x001F0001; +pub const ERROR_FLT_NO_HANDLER_DEFINED: HRESULT = 0x801F0001u32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALREADY_DEFINED: HRESULT = 0x801F0002u32 as HRESULT; +pub const ERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST: HRESULT = 0x801F0003u32 as HRESULT; +pub const ERROR_FLT_DISALLOW_FAST_IO: HRESULT = 0x801F0004u32 as HRESULT; +pub const ERROR_FLT_INVALID_NAME_REQUEST: HRESULT = 0x801F0005u32 as HRESULT; +pub const ERROR_FLT_NOT_SAFE_TO_POST_OPERATION: HRESULT = 0x801F0006u32 as HRESULT; +pub const ERROR_FLT_NOT_INITIALIZED: HRESULT = 0x801F0007u32 as HRESULT; +pub const ERROR_FLT_FILTER_NOT_READY: HRESULT = 0x801F0008u32 as HRESULT; +pub const ERROR_FLT_POST_OPERATION_CLEANUP: HRESULT = 0x801F0009u32 as HRESULT; +pub const ERROR_FLT_INTERNAL_ERROR: HRESULT = 0x801F000Au32 as HRESULT; +pub const ERROR_FLT_DELETING_OBJECT: HRESULT = 0x801F000Bu32 as HRESULT; +pub const ERROR_FLT_MUST_BE_NONPAGED_POOL: HRESULT = 0x801F000Cu32 as HRESULT; +pub const ERROR_FLT_DUPLICATE_ENTRY: HRESULT = 0x801F000Du32 as HRESULT; +pub const ERROR_FLT_CBDQ_DISABLED: HRESULT = 0x801F000Eu32 as HRESULT; +pub const ERROR_FLT_DO_NOT_ATTACH: HRESULT = 0x801F000Fu32 as HRESULT; +pub const ERROR_FLT_DO_NOT_DETACH: HRESULT = 0x801F0010u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_ALTITUDE_COLLISION: HRESULT = 0x801F0011u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_NAME_COLLISION: HRESULT = 0x801F0012u32 as HRESULT; +pub const ERROR_FLT_FILTER_NOT_FOUND: HRESULT = 0x801F0013u32 as HRESULT; +pub const ERROR_FLT_VOLUME_NOT_FOUND: HRESULT = 0x801F0014u32 as HRESULT; +pub const ERROR_FLT_INSTANCE_NOT_FOUND: HRESULT = 0x801F0015u32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND: HRESULT = 0x801F0016u32 as HRESULT; +pub const ERROR_FLT_INVALID_CONTEXT_REGISTRATION: HRESULT = 0x801F0017u32 as HRESULT; +pub const ERROR_FLT_NAME_CACHE_MISS: HRESULT = 0x801F0018u32 as HRESULT; +pub const ERROR_FLT_NO_DEVICE_OBJECT: HRESULT = 0x801F0019u32 as HRESULT; +pub const ERROR_FLT_VOLUME_ALREADY_MOUNTED: HRESULT = 0x801F001Au32 as HRESULT; +pub const ERROR_FLT_ALREADY_ENLISTED: HRESULT = 0x801F001Bu32 as HRESULT; +pub const ERROR_FLT_CONTEXT_ALREADY_LINKED: HRESULT = 0x801F001Cu32 as HRESULT; +pub const ERROR_FLT_NO_WAITER_FOR_REPLY: HRESULT = 0x801F0020u32 as HRESULT; +pub const ERROR_FLT_REGISTRATION_BUSY: HRESULT = 0x801F0023u32 as HRESULT; +pub const ERROR_HUNG_DISPLAY_DRIVER_THREAD: HRESULT = 0x80260001u32 as HRESULT; +pub const DWM_E_COMPOSITIONDISABLED: HRESULT = 0x80263001u32 as HRESULT; +pub const DWM_E_REMOTING_NOT_SUPPORTED: HRESULT = 0x80263002u32 as HRESULT; +pub const DWM_E_NO_REDIRECTION_SURFACE_AVAILABLE: HRESULT = 0x80263003u32 as HRESULT; +pub const DWM_E_NOT_QUEUING_PRESENTS: HRESULT = 0x80263004u32 as HRESULT; +pub const DWM_E_ADAPTER_NOT_FOUND: HRESULT = 0x80263005u32 as HRESULT; +pub const DWM_S_GDI_REDIRECTION_SURFACE: HRESULT = 0x00263005; +pub const DWM_E_TEXTURE_TOO_LARGE: HRESULT = 0x80263007u32 as HRESULT; +pub const ERROR_MONITOR_NO_DESCRIPTOR: HRESULT = 0x80261001u32 as HRESULT; +pub const ERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: HRESULT = 0x80261002u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: HRESULT = 0xC0261003u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK: HRESULT = 0xC0261004u32 as HRESULT; +pub const ERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: HRESULT = 0xC0261005u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: HRESULT = 0xC0261006u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: HRESULT = 0xC0261007u32 as HRESULT; +pub const ERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA: HRESULT = 0xC0261008u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK: HRESULT = 0xC0261009u32 as HRESULT; +pub const ERROR_MONITOR_INVALID_MANUFACTURE_DATE: HRESULT = 0xC026100Au32 as HRESULT; +pub const ERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: HRESULT = 0xC0262000u32 as HRESULT; +pub const ERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER: HRESULT = 0xC0262001u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER: HRESULT = 0xC0262002u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_WAS_RESET: HRESULT = 0xC0262003u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_DRIVER_MODEL: HRESULT = 0xC0262004u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_MODE_CHANGED: HRESULT = 0xC0262005u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_OCCLUDED: HRESULT = 0xC0262006u32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_DENIED: HRESULT = 0xC0262007u32 as HRESULT; +pub const ERROR_GRAPHICS_CANNOTCOLORCONVERT: HRESULT = 0xC0262008u32 as HRESULT; +pub const ERROR_GRAPHICS_DRIVER_MISMATCH: HRESULT = 0xC0262009u32 as HRESULT; +pub const ERROR_GRAPHICS_PARTIAL_DATA_POPULATED: HRESULT = 0x4026200A; +pub const ERROR_GRAPHICS_PRESENT_REDIRECTION_DISABLED: HRESULT = 0xC026200Bu32 as HRESULT; +pub const ERROR_GRAPHICS_PRESENT_UNOCCLUDED: HRESULT = 0xC026200Cu32 as HRESULT; +pub const ERROR_GRAPHICS_WINDOWDC_NOT_AVAILABLE: HRESULT = 0xC026200Du32 as HRESULT; +pub const ERROR_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: HRESULT = 0xC026200Eu32 as HRESULT; +pub const ERROR_GRAPHICS_NO_VIDEO_MEMORY: HRESULT = 0xC0262100u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_LOCK_MEMORY: HRESULT = 0xC0262101u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_BUSY: HRESULT = 0xC0262102u32 as HRESULT; +pub const ERROR_GRAPHICS_TOO_MANY_REFERENCES: HRESULT = 0xC0262103u32 as HRESULT; +pub const ERROR_GRAPHICS_TRY_AGAIN_LATER: HRESULT = 0xC0262104u32 as HRESULT; +pub const ERROR_GRAPHICS_TRY_AGAIN_NOW: HRESULT = 0xC0262105u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_INVALID: HRESULT = 0xC0262106u32 as HRESULT; +pub const ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: HRESULT = 0xC0262107u32 as HRESULT; +pub const ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: HRESULT = 0xC0262108u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: HRESULT = 0xC0262109u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_USAGE: HRESULT = 0xC0262110u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: HRESULT = 0xC0262111u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_CLOSED: HRESULT = 0xC0262112u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE: HRESULT = 0xC0262113u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE: HRESULT = 0xC0262114u32 as HRESULT; +pub const ERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE: HRESULT = 0xC0262115u32 as HRESULT; +pub const ERROR_GRAPHICS_ALLOCATION_CONTENT_LOST: HRESULT = 0xC0262116u32 as HRESULT; +pub const ERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: HRESULT = 0xC0262200u32 as HRESULT; +pub const ERROR_GRAPHICS_SKIP_ALLOCATION_PREPARATION: HRESULT = 0x40262201; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY: HRESULT = 0xC0262300u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: HRESULT = 0xC0262301u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: HRESULT = 0xC0262302u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN: HRESULT = 0xC0262303u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: HRESULT = 0xC0262304u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: HRESULT = 0xC0262305u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: HRESULT = 0xC0262306u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_NOT_PINNED: HRESULT = 0x00262307; +pub const ERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: HRESULT = 0xC0262308u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET: HRESULT = 0xC0262309u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_FREQUENCY: HRESULT = 0xC026230Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_ACTIVE_REGION: HRESULT = 0xC026230Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_TOTAL_REGION: HRESULT = 0xC026230Cu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: HRESULT = 0xC0262310u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: HRESULT = 0xC0262311u32 as HRESULT; +pub const ERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: HRESULT = 0xC0262312u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: HRESULT = 0xC0262313u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_ALREADY_IN_MODESET: HRESULT = 0xC0262314u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: HRESULT = 0xC0262315u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: HRESULT = 0xC0262316u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_ALREADY_IN_SET: HRESULT = 0xC0262317u32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_ALREADY_IN_SET: HRESULT = 0xC0262318u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: HRESULT = 0xC0262319u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: HRESULT = 0xC026231Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: HRESULT = 0xC026231Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: HRESULT = 0xC026231Cu32 as HRESULT; +pub const ERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: HRESULT = 0xC026231Du32 as HRESULT; +pub const ERROR_GRAPHICS_NO_PREFERRED_MODE: HRESULT = 0x0026231E; +pub const ERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: HRESULT = 0xC026231Fu32 as HRESULT; +pub const ERROR_GRAPHICS_STALE_MODESET: HRESULT = 0xC0262320u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: HRESULT = 0xC0262321u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: HRESULT = 0xC0262322u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: HRESULT = 0xC0262323u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262324u32 as HRESULT; +pub const ERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: HRESULT = 0xC0262325u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: HRESULT = 0xC0262326u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY: HRESULT = 0xC0262327u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: HRESULT = 0xC0262328u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: HRESULT = 0xC0262329u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET: HRESULT = 0xC026232Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR: HRESULT = 0xC026232Bu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: HRESULT = 0xC026232Cu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: HRESULT = 0xC026232Du32 as HRESULT; +pub const ERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: HRESULT = 0xC026232Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: HRESULT = 0xC026232Fu32 as HRESULT; +pub const ERROR_GRAPHICS_RESOURCES_NOT_RELATED: HRESULT = 0xC0262330u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262331u32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: HRESULT = 0xC0262332u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: HRESULT = 0xC0262333u32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: HRESULT = 0xC0262334u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_VIDPNMGR: HRESULT = 0xC0262335u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_ACTIVE_VIDPN: HRESULT = 0xC0262336u32 as HRESULT; +pub const ERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY: HRESULT = 0xC0262337u32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_NOT_CONNECTED: HRESULT = 0xC0262338u32 as HRESULT; +pub const ERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: HRESULT = 0xC0262339u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: HRESULT = 0xC026233Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE: HRESULT = 0xC026233Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_STRIDE: HRESULT = 0xC026233Cu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PIXELFORMAT: HRESULT = 0xC026233Du32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_COLORBASIS: HRESULT = 0xC026233Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: HRESULT = 0xC026233Fu32 as HRESULT; +pub const ERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: HRESULT = 0xC0262340u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: HRESULT = 0xC0262341u32 as HRESULT; +pub const ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0xC0262342u32 as HRESULT; +pub const ERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: HRESULT = 0xC0262343u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: HRESULT = 0xC0262344u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: HRESULT = 0xC0262345u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: HRESULT = 0xC0262346u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_GAMMA_RAMP: HRESULT = 0xC0262347u32 as HRESULT; +pub const ERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: HRESULT = 0xC0262348u32 as HRESULT; +pub const ERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: HRESULT = 0xC0262349u32 as HRESULT; +pub const ERROR_GRAPHICS_MODE_NOT_IN_MODESET: HRESULT = 0xC026234Au32 as HRESULT; +pub const ERROR_GRAPHICS_DATASET_IS_EMPTY: HRESULT = 0x0026234B; +pub const ERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: HRESULT = 0x0026234C; +pub const ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: HRESULT = 0xC026234Du32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE: HRESULT = 0xC026234Eu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE: HRESULT = 0xC026234Fu32 as HRESULT; +pub const ERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: HRESULT = 0xC0262350u32 as HRESULT; +pub const ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: HRESULT = 0x00262351; +pub const ERROR_GRAPHICS_INVALID_SCANLINE_ORDERING: HRESULT = 0xC0262352u32 as HRESULT; +pub const ERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: HRESULT = 0xC0262353u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: HRESULT = 0xC0262354u32 as HRESULT; +pub const ERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: HRESULT = 0xC0262355u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: HRESULT = 0xC0262356u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: HRESULT = 0xC0262357u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: HRESULT = 0xC0262358u32 as HRESULT; +pub const ERROR_GRAPHICS_MAX_NUM_PATHS_REACHED: HRESULT = 0xC0262359u32 as HRESULT; +pub const ERROR_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: HRESULT = 0xC026235Au32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_CLIENT_TYPE: HRESULT = 0xC026235Bu32 as HRESULT; +pub const ERROR_GRAPHICS_CLIENTVIDPN_NOT_SET: HRESULT = 0xC026235Cu32 as HRESULT; +pub const ERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: HRESULT = 0xC0262400u32 as HRESULT; +pub const ERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: HRESULT = 0xC0262401u32 as HRESULT; +pub const ERROR_GRAPHICS_UNKNOWN_CHILD_STATUS: HRESULT = 0x4026242F; +pub const ERROR_GRAPHICS_NOT_A_LINKED_ADAPTER: HRESULT = 0xC0262430u32 as HRESULT; +pub const ERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED: HRESULT = 0xC0262431u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: HRESULT = 0xC0262432u32 as HRESULT; +pub const ERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY: HRESULT = 0xC0262433u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_STARTED: HRESULT = 0xC0262434u32 as HRESULT; +pub const ERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: HRESULT = 0xC0262435u32 as HRESULT; +pub const ERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: HRESULT = 0xC0262436u32 as HRESULT; +pub const ERROR_GRAPHICS_LEADLINK_START_DEFERRED: HRESULT = 0x40262437; +pub const ERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER: HRESULT = 0xC0262438u32 as HRESULT; +pub const ERROR_GRAPHICS_POLLING_TOO_FREQUENTLY: HRESULT = 0x40262439; +pub const ERROR_GRAPHICS_START_DEFERRED: HRESULT = 0x4026243A; +pub const ERROR_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: HRESULT = 0xC026243Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_NOT_SUPPORTED: HRESULT = 0xC0262500u32 as HRESULT; +pub const ERROR_GRAPHICS_COPP_NOT_SUPPORTED: HRESULT = 0xC0262501u32 as HRESULT; +pub const ERROR_GRAPHICS_UAB_NOT_SUPPORTED: HRESULT = 0xC0262502u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: HRESULT = 0xC0262503u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST: HRESULT = 0xC0262505u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INTERNAL_ERROR: HRESULT = 0xC026250Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_HANDLE: HRESULT = 0xC026250Cu32 as HRESULT; +pub const ERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: HRESULT = 0xC026250Eu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED: HRESULT = 0xC026250Fu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED: HRESULT = 0xC0262510u32 as HRESULT; +pub const ERROR_GRAPHICS_PVP_HFS_FAILED: HRESULT = 0xC0262511u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_SRM: HRESULT = 0xC0262512u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: HRESULT = 0xC0262513u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: HRESULT = 0xC0262514u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: HRESULT = 0xC0262515u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: HRESULT = 0xC0262516u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: HRESULT = 0xC0262517u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: HRESULT = 0xC0262518u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS: HRESULT = 0xC026251Au32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS: HRESULT = 0xC026251Bu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: HRESULT = 0xC026251Cu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: HRESULT = 0xC026251Du32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: HRESULT = 0xC026251Eu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: HRESULT = 0xC026251Fu32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: HRESULT = 0xC0262520u32 as HRESULT; +pub const ERROR_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: HRESULT = 0xC0262521u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_NOT_SUPPORTED: HRESULT = 0xC0262580u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: HRESULT = 0xC0262581u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: HRESULT = 0xC0262582u32 as HRESULT; +pub const ERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA: HRESULT = 0xC0262583u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: HRESULT = 0xC0262584u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_DATA: HRESULT = 0xC0262585u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: HRESULT = 0xC0262586u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING: HRESULT = 0xC0262587u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INTERNAL_ERROR: HRESULT = 0xC0262588u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: HRESULT = 0xC0262589u32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: HRESULT = 0xC026258Au32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: HRESULT = 0xC026258Bu32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: HRESULT = 0xC026258Cu32 as HRESULT; +pub const ERROR_GRAPHICS_MONITOR_NO_LONGER_EXISTS: HRESULT = 0xC026258Du32 as HRESULT; +pub const ERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE: HRESULT = 0xC02625D8u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_VCP_VERSION: HRESULT = 0xC02625D9u32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: HRESULT = 0xC02625DAu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH: HRESULT = 0xC02625DBu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION: HRESULT = 0xC02625DCu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: HRESULT = 0xC02625DEu32 as HRESULT; +pub const ERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE: HRESULT = 0xC02625DFu32 as HRESULT; +pub const ERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: HRESULT = 0xC02625E0u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: HRESULT = 0xC02625E1u32 as HRESULT; +pub const ERROR_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: HRESULT = 0xC02625E2u32 as HRESULT; +pub const ERROR_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: HRESULT = 0xC02625E3u32 as HRESULT; +pub const ERROR_GRAPHICS_INVALID_POINTER: HRESULT = 0xC02625E4u32 as HRESULT; +pub const ERROR_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: HRESULT = 0xC02625E5u32 as HRESULT; +pub const ERROR_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: HRESULT = 0xC02625E6u32 as HRESULT; +pub const ERROR_GRAPHICS_INTERNAL_ERROR: HRESULT = 0xC02625E7u32 as HRESULT; +pub const ERROR_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: HRESULT = 0xC02605E8u32 as HRESULT; +pub const NAP_E_INVALID_PACKET: HRESULT = 0x80270001u32 as HRESULT; +pub const NAP_E_MISSING_SOH: HRESULT = 0x80270002u32 as HRESULT; +pub const NAP_E_CONFLICTING_ID: HRESULT = 0x80270003u32 as HRESULT; +pub const NAP_E_NO_CACHED_SOH: HRESULT = 0x80270004u32 as HRESULT; +pub const NAP_E_STILL_BOUND: HRESULT = 0x80270005u32 as HRESULT; +pub const NAP_E_NOT_REGISTERED: HRESULT = 0x80270006u32 as HRESULT; +pub const NAP_E_NOT_INITIALIZED: HRESULT = 0x80270007u32 as HRESULT; +pub const NAP_E_MISMATCHED_ID: HRESULT = 0x80270008u32 as HRESULT; +pub const NAP_E_NOT_PENDING: HRESULT = 0x80270009u32 as HRESULT; +pub const NAP_E_ID_NOT_FOUND: HRESULT = 0x8027000Au32 as HRESULT; +pub const NAP_E_MAXSIZE_TOO_SMALL: HRESULT = 0x8027000Bu32 as HRESULT; +pub const NAP_E_SERVICE_NOT_RUNNING: HRESULT = 0x8027000Cu32 as HRESULT; +pub const NAP_S_CERT_ALREADY_PRESENT: HRESULT = 0x0027000D; +pub const NAP_E_ENTITY_DISABLED: HRESULT = 0x8027000Eu32 as HRESULT; +pub const NAP_E_NETSH_GROUPPOLICY_ERROR: HRESULT = 0x8027000Fu32 as HRESULT; +pub const NAP_E_TOO_MANY_CALLS: HRESULT = 0x80270010u32 as HRESULT; +pub const NAP_E_SHV_CONFIG_EXISTED: HRESULT = 0x80270011u32 as HRESULT; +pub const NAP_E_SHV_CONFIG_NOT_FOUND: HRESULT = 0x80270012u32 as HRESULT; +pub const NAP_E_SHV_TIMEOUT: HRESULT = 0x80270013u32 as HRESULT; +pub const TPM_E_ERROR_MASK: HRESULT = 0x80280000u32 as HRESULT; +pub const TPM_E_AUTHFAIL: HRESULT = 0x80280001u32 as HRESULT; +pub const TPM_E_BADINDEX: HRESULT = 0x80280002u32 as HRESULT; +pub const TPM_E_BAD_PARAMETER: HRESULT = 0x80280003u32 as HRESULT; +pub const TPM_E_AUDITFAILURE: HRESULT = 0x80280004u32 as HRESULT; +pub const TPM_E_CLEAR_DISABLED: HRESULT = 0x80280005u32 as HRESULT; +pub const TPM_E_DEACTIVATED: HRESULT = 0x80280006u32 as HRESULT; +pub const TPM_E_DISABLED: HRESULT = 0x80280007u32 as HRESULT; +pub const TPM_E_DISABLED_CMD: HRESULT = 0x80280008u32 as HRESULT; +pub const TPM_E_FAIL: HRESULT = 0x80280009u32 as HRESULT; +pub const TPM_E_BAD_ORDINAL: HRESULT = 0x8028000Au32 as HRESULT; +pub const TPM_E_INSTALL_DISABLED: HRESULT = 0x8028000Bu32 as HRESULT; +pub const TPM_E_INVALID_KEYHANDLE: HRESULT = 0x8028000Cu32 as HRESULT; +pub const TPM_E_KEYNOTFOUND: HRESULT = 0x8028000Du32 as HRESULT; +pub const TPM_E_INAPPROPRIATE_ENC: HRESULT = 0x8028000Eu32 as HRESULT; +pub const TPM_E_MIGRATEFAIL: HRESULT = 0x8028000Fu32 as HRESULT; +pub const TPM_E_INVALID_PCR_INFO: HRESULT = 0x80280010u32 as HRESULT; +pub const TPM_E_NOSPACE: HRESULT = 0x80280011u32 as HRESULT; +pub const TPM_E_NOSRK: HRESULT = 0x80280012u32 as HRESULT; +pub const TPM_E_NOTSEALED_BLOB: HRESULT = 0x80280013u32 as HRESULT; +pub const TPM_E_OWNER_SET: HRESULT = 0x80280014u32 as HRESULT; +pub const TPM_E_RESOURCES: HRESULT = 0x80280015u32 as HRESULT; +pub const TPM_E_SHORTRANDOM: HRESULT = 0x80280016u32 as HRESULT; +pub const TPM_E_SIZE: HRESULT = 0x80280017u32 as HRESULT; +pub const TPM_E_WRONGPCRVAL: HRESULT = 0x80280018u32 as HRESULT; +pub const TPM_E_BAD_PARAM_SIZE: HRESULT = 0x80280019u32 as HRESULT; +pub const TPM_E_SHA_THREAD: HRESULT = 0x8028001Au32 as HRESULT; +pub const TPM_E_SHA_ERROR: HRESULT = 0x8028001Bu32 as HRESULT; +pub const TPM_E_FAILEDSELFTEST: HRESULT = 0x8028001Cu32 as HRESULT; +pub const TPM_E_AUTH2FAIL: HRESULT = 0x8028001Du32 as HRESULT; +pub const TPM_E_BADTAG: HRESULT = 0x8028001Eu32 as HRESULT; +pub const TPM_E_IOERROR: HRESULT = 0x8028001Fu32 as HRESULT; +pub const TPM_E_ENCRYPT_ERROR: HRESULT = 0x80280020u32 as HRESULT; +pub const TPM_E_DECRYPT_ERROR: HRESULT = 0x80280021u32 as HRESULT; +pub const TPM_E_INVALID_AUTHHANDLE: HRESULT = 0x80280022u32 as HRESULT; +pub const TPM_E_NO_ENDORSEMENT: HRESULT = 0x80280023u32 as HRESULT; +pub const TPM_E_INVALID_KEYUSAGE: HRESULT = 0x80280024u32 as HRESULT; +pub const TPM_E_WRONG_ENTITYTYPE: HRESULT = 0x80280025u32 as HRESULT; +pub const TPM_E_INVALID_POSTINIT: HRESULT = 0x80280026u32 as HRESULT; +pub const TPM_E_INAPPROPRIATE_SIG: HRESULT = 0x80280027u32 as HRESULT; +pub const TPM_E_BAD_KEY_PROPERTY: HRESULT = 0x80280028u32 as HRESULT; +pub const TPM_E_BAD_MIGRATION: HRESULT = 0x80280029u32 as HRESULT; +pub const TPM_E_BAD_SCHEME: HRESULT = 0x8028002Au32 as HRESULT; +pub const TPM_E_BAD_DATASIZE: HRESULT = 0x8028002Bu32 as HRESULT; +pub const TPM_E_BAD_MODE: HRESULT = 0x8028002Cu32 as HRESULT; +pub const TPM_E_BAD_PRESENCE: HRESULT = 0x8028002Du32 as HRESULT; +pub const TPM_E_BAD_VERSION: HRESULT = 0x8028002Eu32 as HRESULT; +pub const TPM_E_NO_WRAP_TRANSPORT: HRESULT = 0x8028002Fu32 as HRESULT; +pub const TPM_E_AUDITFAIL_UNSUCCESSFUL: HRESULT = 0x80280030u32 as HRESULT; +pub const TPM_E_AUDITFAIL_SUCCESSFUL: HRESULT = 0x80280031u32 as HRESULT; +pub const TPM_E_NOTRESETABLE: HRESULT = 0x80280032u32 as HRESULT; +pub const TPM_E_NOTLOCAL: HRESULT = 0x80280033u32 as HRESULT; +pub const TPM_E_BAD_TYPE: HRESULT = 0x80280034u32 as HRESULT; +pub const TPM_E_INVALID_RESOURCE: HRESULT = 0x80280035u32 as HRESULT; +pub const TPM_E_NOTFIPS: HRESULT = 0x80280036u32 as HRESULT; +pub const TPM_E_INVALID_FAMILY: HRESULT = 0x80280037u32 as HRESULT; +pub const TPM_E_NO_NV_PERMISSION: HRESULT = 0x80280038u32 as HRESULT; +pub const TPM_E_REQUIRES_SIGN: HRESULT = 0x80280039u32 as HRESULT; +pub const TPM_E_KEY_NOTSUPPORTED: HRESULT = 0x8028003Au32 as HRESULT; +pub const TPM_E_AUTH_CONFLICT: HRESULT = 0x8028003Bu32 as HRESULT; +pub const TPM_E_AREA_LOCKED: HRESULT = 0x8028003Cu32 as HRESULT; +pub const TPM_E_BAD_LOCALITY: HRESULT = 0x8028003Du32 as HRESULT; +pub const TPM_E_READ_ONLY: HRESULT = 0x8028003Eu32 as HRESULT; +pub const TPM_E_PER_NOWRITE: HRESULT = 0x8028003Fu32 as HRESULT; +pub const TPM_E_FAMILYCOUNT: HRESULT = 0x80280040u32 as HRESULT; +pub const TPM_E_WRITE_LOCKED: HRESULT = 0x80280041u32 as HRESULT; +pub const TPM_E_BAD_ATTRIBUTES: HRESULT = 0x80280042u32 as HRESULT; +pub const TPM_E_INVALID_STRUCTURE: HRESULT = 0x80280043u32 as HRESULT; +pub const TPM_E_KEY_OWNER_CONTROL: HRESULT = 0x80280044u32 as HRESULT; +pub const TPM_E_BAD_COUNTER: HRESULT = 0x80280045u32 as HRESULT; +pub const TPM_E_NOT_FULLWRITE: HRESULT = 0x80280046u32 as HRESULT; +pub const TPM_E_CONTEXT_GAP: HRESULT = 0x80280047u32 as HRESULT; +pub const TPM_E_MAXNVWRITES: HRESULT = 0x80280048u32 as HRESULT; +pub const TPM_E_NOOPERATOR: HRESULT = 0x80280049u32 as HRESULT; +pub const TPM_E_RESOURCEMISSING: HRESULT = 0x8028004Au32 as HRESULT; +pub const TPM_E_DELEGATE_LOCK: HRESULT = 0x8028004Bu32 as HRESULT; +pub const TPM_E_DELEGATE_FAMILY: HRESULT = 0x8028004Cu32 as HRESULT; +pub const TPM_E_DELEGATE_ADMIN: HRESULT = 0x8028004Du32 as HRESULT; +pub const TPM_E_TRANSPORT_NOTEXCLUSIVE: HRESULT = 0x8028004Eu32 as HRESULT; +pub const TPM_E_OWNER_CONTROL: HRESULT = 0x8028004Fu32 as HRESULT; +pub const TPM_E_DAA_RESOURCES: HRESULT = 0x80280050u32 as HRESULT; +pub const TPM_E_DAA_INPUT_DATA0: HRESULT = 0x80280051u32 as HRESULT; +pub const TPM_E_DAA_INPUT_DATA1: HRESULT = 0x80280052u32 as HRESULT; +pub const TPM_E_DAA_ISSUER_SETTINGS: HRESULT = 0x80280053u32 as HRESULT; +pub const TPM_E_DAA_TPM_SETTINGS: HRESULT = 0x80280054u32 as HRESULT; +pub const TPM_E_DAA_STAGE: HRESULT = 0x80280055u32 as HRESULT; +pub const TPM_E_DAA_ISSUER_VALIDITY: HRESULT = 0x80280056u32 as HRESULT; +pub const TPM_E_DAA_WRONG_W: HRESULT = 0x80280057u32 as HRESULT; +pub const TPM_E_BAD_HANDLE: HRESULT = 0x80280058u32 as HRESULT; +pub const TPM_E_BAD_DELEGATE: HRESULT = 0x80280059u32 as HRESULT; +pub const TPM_E_BADCONTEXT: HRESULT = 0x8028005Au32 as HRESULT; +pub const TPM_E_TOOMANYCONTEXTS: HRESULT = 0x8028005Bu32 as HRESULT; +pub const TPM_E_MA_TICKET_SIGNATURE: HRESULT = 0x8028005Cu32 as HRESULT; +pub const TPM_E_MA_DESTINATION: HRESULT = 0x8028005Du32 as HRESULT; +pub const TPM_E_MA_SOURCE: HRESULT = 0x8028005Eu32 as HRESULT; +pub const TPM_E_MA_AUTHORITY: HRESULT = 0x8028005Fu32 as HRESULT; +pub const TPM_E_PERMANENTEK: HRESULT = 0x80280061u32 as HRESULT; +pub const TPM_E_BAD_SIGNATURE: HRESULT = 0x80280062u32 as HRESULT; +pub const TPM_E_NOCONTEXTSPACE: HRESULT = 0x80280063u32 as HRESULT; +pub const TPM_E_COMMAND_BLOCKED: HRESULT = 0x80280400u32 as HRESULT; +pub const TPM_E_INVALID_HANDLE: HRESULT = 0x80280401u32 as HRESULT; +pub const TPM_E_DUPLICATE_VHANDLE: HRESULT = 0x80280402u32 as HRESULT; +pub const TPM_E_EMBEDDED_COMMAND_BLOCKED: HRESULT = 0x80280403u32 as HRESULT; +pub const TPM_E_EMBEDDED_COMMAND_UNSUPPORTED: HRESULT = 0x80280404u32 as HRESULT; +pub const TPM_E_RETRY: HRESULT = 0x80280800u32 as HRESULT; +pub const TPM_E_NEEDS_SELFTEST: HRESULT = 0x80280801u32 as HRESULT; +pub const TPM_E_DOING_SELFTEST: HRESULT = 0x80280802u32 as HRESULT; +pub const TPM_E_DEFEND_LOCK_RUNNING: HRESULT = 0x80280803u32 as HRESULT; +pub const TBS_E_INTERNAL_ERROR: HRESULT = 0x80284001u32 as HRESULT; +pub const TBS_E_BAD_PARAMETER: HRESULT = 0x80284002u32 as HRESULT; +pub const TBS_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80284003u32 as HRESULT; +pub const TBS_E_INVALID_CONTEXT: HRESULT = 0x80284004u32 as HRESULT; +pub const TBS_E_INSUFFICIENT_BUFFER: HRESULT = 0x80284005u32 as HRESULT; +pub const TBS_E_IOERROR: HRESULT = 0x80284006u32 as HRESULT; +pub const TBS_E_INVALID_CONTEXT_PARAM: HRESULT = 0x80284007u32 as HRESULT; +pub const TBS_E_SERVICE_NOT_RUNNING: HRESULT = 0x80284008u32 as HRESULT; +pub const TBS_E_TOO_MANY_TBS_CONTEXTS: HRESULT = 0x80284009u32 as HRESULT; +pub const TBS_E_TOO_MANY_RESOURCES: HRESULT = 0x8028400Au32 as HRESULT; +pub const TBS_E_SERVICE_START_PENDING: HRESULT = 0x8028400Bu32 as HRESULT; +pub const TBS_E_PPI_NOT_SUPPORTED: HRESULT = 0x8028400Cu32 as HRESULT; +pub const TBS_E_COMMAND_CANCELED: HRESULT = 0x8028400Du32 as HRESULT; +pub const TBS_E_BUFFER_TOO_LARGE: HRESULT = 0x8028400Eu32 as HRESULT; +pub const TBS_E_TPM_NOT_FOUND: HRESULT = 0x8028400Fu32 as HRESULT; +pub const TBS_E_SERVICE_DISABLED: HRESULT = 0x80284010u32 as HRESULT; +pub const TBS_E_NO_EVENT_LOG: HRESULT = 0x80284011u32 as HRESULT; +pub const TBS_E_ACCESS_DENIED: HRESULT = 0x80284012u32 as HRESULT; +pub const TBS_E_PROVISIONING_NOT_ALLOWED: HRESULT = 0x80284013u32 as HRESULT; +pub const TBS_E_PPI_FUNCTION_UNSUPPORTED: HRESULT = 0x80284014u32 as HRESULT; +pub const TBS_E_OWNERAUTH_NOT_FOUND: HRESULT = 0x80284015u32 as HRESULT; +pub const TBS_E_PROVISIONING_INCOMPLETE: HRESULT = 0x80284016u32 as HRESULT; +pub const TPMAPI_E_INVALID_STATE: HRESULT = 0x80290100u32 as HRESULT; +pub const TPMAPI_E_NOT_ENOUGH_DATA: HRESULT = 0x80290101u32 as HRESULT; +pub const TPMAPI_E_TOO_MUCH_DATA: HRESULT = 0x80290102u32 as HRESULT; +pub const TPMAPI_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80290103u32 as HRESULT; +pub const TPMAPI_E_INVALID_PARAMETER: HRESULT = 0x80290104u32 as HRESULT; +pub const TPMAPI_E_OUT_OF_MEMORY: HRESULT = 0x80290105u32 as HRESULT; +pub const TPMAPI_E_BUFFER_TOO_SMALL: HRESULT = 0x80290106u32 as HRESULT; +pub const TPMAPI_E_INTERNAL_ERROR: HRESULT = 0x80290107u32 as HRESULT; +pub const TPMAPI_E_ACCESS_DENIED: HRESULT = 0x80290108u32 as HRESULT; +pub const TPMAPI_E_AUTHORIZATION_FAILED: HRESULT = 0x80290109u32 as HRESULT; +pub const TPMAPI_E_INVALID_CONTEXT_HANDLE: HRESULT = 0x8029010Au32 as HRESULT; +pub const TPMAPI_E_TBS_COMMUNICATION_ERROR: HRESULT = 0x8029010Bu32 as HRESULT; +pub const TPMAPI_E_TPM_COMMAND_ERROR: HRESULT = 0x8029010Cu32 as HRESULT; +pub const TPMAPI_E_MESSAGE_TOO_LARGE: HRESULT = 0x8029010Du32 as HRESULT; +pub const TPMAPI_E_INVALID_ENCODING: HRESULT = 0x8029010Eu32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_SIZE: HRESULT = 0x8029010Fu32 as HRESULT; +pub const TPMAPI_E_ENCRYPTION_FAILED: HRESULT = 0x80290110u32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_PARAMS: HRESULT = 0x80290111u32 as HRESULT; +pub const TPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB: HRESULT = 0x80290112u32 as HRESULT; +pub const TPMAPI_E_INVALID_PCR_INDEX: HRESULT = 0x80290113u32 as HRESULT; +pub const TPMAPI_E_INVALID_DELEGATE_BLOB: HRESULT = 0x80290114u32 as HRESULT; +pub const TPMAPI_E_INVALID_CONTEXT_PARAMS: HRESULT = 0x80290115u32 as HRESULT; +pub const TPMAPI_E_INVALID_KEY_BLOB: HRESULT = 0x80290116u32 as HRESULT; +pub const TPMAPI_E_INVALID_PCR_DATA: HRESULT = 0x80290117u32 as HRESULT; +pub const TPMAPI_E_INVALID_OWNER_AUTH: HRESULT = 0x80290118u32 as HRESULT; +pub const TPMAPI_E_FIPS_RNG_CHECK_FAILED: HRESULT = 0x80290119u32 as HRESULT; +pub const TPMAPI_E_EMPTY_TCG_LOG: HRESULT = 0x8029011Au32 as HRESULT; +pub const TPMAPI_E_INVALID_TCG_LOG_ENTRY: HRESULT = 0x8029011Bu32 as HRESULT; +pub const TPMAPI_E_TCG_SEPARATOR_ABSENT: HRESULT = 0x8029011Cu32 as HRESULT; +pub const TPMAPI_E_TCG_INVALID_DIGEST_ENTRY: HRESULT = 0x8029011Du32 as HRESULT; +pub const TPMAPI_E_POLICY_DENIES_OPERATION: HRESULT = 0x8029011Eu32 as HRESULT; +pub const TBSIMP_E_BUFFER_TOO_SMALL: HRESULT = 0x80290200u32 as HRESULT; +pub const TBSIMP_E_CLEANUP_FAILED: HRESULT = 0x80290201u32 as HRESULT; +pub const TBSIMP_E_INVALID_CONTEXT_HANDLE: HRESULT = 0x80290202u32 as HRESULT; +pub const TBSIMP_E_INVALID_CONTEXT_PARAM: HRESULT = 0x80290203u32 as HRESULT; +pub const TBSIMP_E_TPM_ERROR: HRESULT = 0x80290204u32 as HRESULT; +pub const TBSIMP_E_HASH_BAD_KEY: HRESULT = 0x80290205u32 as HRESULT; +pub const TBSIMP_E_DUPLICATE_VHANDLE: HRESULT = 0x80290206u32 as HRESULT; +pub const TBSIMP_E_INVALID_OUTPUT_POINTER: HRESULT = 0x80290207u32 as HRESULT; +pub const TBSIMP_E_INVALID_PARAMETER: HRESULT = 0x80290208u32 as HRESULT; +pub const TBSIMP_E_RPC_INIT_FAILED: HRESULT = 0x80290209u32 as HRESULT; +pub const TBSIMP_E_SCHEDULER_NOT_RUNNING: HRESULT = 0x8029020Au32 as HRESULT; +pub const TBSIMP_E_COMMAND_CANCELED: HRESULT = 0x8029020Bu32 as HRESULT; +pub const TBSIMP_E_OUT_OF_MEMORY: HRESULT = 0x8029020Cu32 as HRESULT; +pub const TBSIMP_E_LIST_NO_MORE_ITEMS: HRESULT = 0x8029020Du32 as HRESULT; +pub const TBSIMP_E_LIST_NOT_FOUND: HRESULT = 0x8029020Eu32 as HRESULT; +pub const TBSIMP_E_NOT_ENOUGH_SPACE: HRESULT = 0x8029020Fu32 as HRESULT; +pub const TBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS: HRESULT = 0x80290210u32 as HRESULT; +pub const TBSIMP_E_COMMAND_FAILED: HRESULT = 0x80290211u32 as HRESULT; +pub const TBSIMP_E_UNKNOWN_ORDINAL: HRESULT = 0x80290212u32 as HRESULT; +pub const TBSIMP_E_RESOURCE_EXPIRED: HRESULT = 0x80290213u32 as HRESULT; +pub const TBSIMP_E_INVALID_RESOURCE: HRESULT = 0x80290214u32 as HRESULT; +pub const TBSIMP_E_NOTHING_TO_UNLOAD: HRESULT = 0x80290215u32 as HRESULT; +pub const TBSIMP_E_HASH_TABLE_FULL: HRESULT = 0x80290216u32 as HRESULT; +pub const TBSIMP_E_TOO_MANY_TBS_CONTEXTS: HRESULT = 0x80290217u32 as HRESULT; +pub const TBSIMP_E_TOO_MANY_RESOURCES: HRESULT = 0x80290218u32 as HRESULT; +pub const TBSIMP_E_PPI_NOT_SUPPORTED: HRESULT = 0x80290219u32 as HRESULT; +pub const TBSIMP_E_TPM_INCOMPATIBLE: HRESULT = 0x8029021Au32 as HRESULT; +pub const TBSIMP_E_NO_EVENT_LOG: HRESULT = 0x8029021Bu32 as HRESULT; +pub const TPM_E_PPI_ACPI_FAILURE: HRESULT = 0x80290300u32 as HRESULT; +pub const TPM_E_PPI_USER_ABORT: HRESULT = 0x80290301u32 as HRESULT; +pub const TPM_E_PPI_BIOS_FAILURE: HRESULT = 0x80290302u32 as HRESULT; +pub const TPM_E_PPI_NOT_SUPPORTED: HRESULT = 0x80290303u32 as HRESULT; +pub const TPM_E_PPI_BLOCKED_IN_BIOS: HRESULT = 0x80290304u32 as HRESULT; +pub const TPM_E_PCP_ERROR_MASK: HRESULT = 0x80290400u32 as HRESULT; +pub const TPM_E_PCP_DEVICE_NOT_READY: HRESULT = 0x80290401u32 as HRESULT; +pub const TPM_E_PCP_INVALID_HANDLE: HRESULT = 0x80290402u32 as HRESULT; +pub const TPM_E_PCP_INVALID_PARAMETER: HRESULT = 0x80290403u32 as HRESULT; +pub const TPM_E_PCP_FLAG_NOT_SUPPORTED: HRESULT = 0x80290404u32 as HRESULT; +pub const TPM_E_PCP_NOT_SUPPORTED: HRESULT = 0x80290405u32 as HRESULT; +pub const TPM_E_PCP_BUFFER_TOO_SMALL: HRESULT = 0x80290406u32 as HRESULT; +pub const TPM_E_PCP_INTERNAL_ERROR: HRESULT = 0x80290407u32 as HRESULT; +pub const TPM_E_PCP_AUTHENTICATION_FAILED: HRESULT = 0x80290408u32 as HRESULT; +pub const TPM_E_PCP_AUTHENTICATION_IGNORED: HRESULT = 0x80290409u32 as HRESULT; +pub const TPM_E_PCP_POLICY_NOT_FOUND: HRESULT = 0x8029040Au32 as HRESULT; +pub const TPM_E_PCP_PROFILE_NOT_FOUND: HRESULT = 0x8029040Bu32 as HRESULT; +pub const TPM_E_PCP_VALIDATION_FAILED: HRESULT = 0x8029040Cu32 as HRESULT; +pub const PLA_E_DCS_NOT_FOUND: HRESULT = 0x80300002u32 as HRESULT; +pub const PLA_E_DCS_IN_USE: HRESULT = 0x803000AAu32 as HRESULT; +pub const PLA_E_TOO_MANY_FOLDERS: HRESULT = 0x80300045u32 as HRESULT; +pub const PLA_E_NO_MIN_DISK: HRESULT = 0x80300070u32 as HRESULT; +pub const PLA_E_DCS_ALREADY_EXISTS: HRESULT = 0x803000B7u32 as HRESULT; +pub const PLA_S_PROPERTY_IGNORED: HRESULT = 0x00300100; +pub const PLA_E_PROPERTY_CONFLICT: HRESULT = 0x80300101u32 as HRESULT; +pub const PLA_E_DCS_SINGLETON_REQUIRED: HRESULT = 0x80300102u32 as HRESULT; +pub const PLA_E_CREDENTIALS_REQUIRED: HRESULT = 0x80300103u32 as HRESULT; +pub const PLA_E_DCS_NOT_RUNNING: HRESULT = 0x80300104u32 as HRESULT; +pub const PLA_E_CONFLICT_INCL_EXCL_API: HRESULT = 0x80300105u32 as HRESULT; +pub const PLA_E_NETWORK_EXE_NOT_VALID: HRESULT = 0x80300106u32 as HRESULT; +pub const PLA_E_EXE_ALREADY_CONFIGURED: HRESULT = 0x80300107u32 as HRESULT; +pub const PLA_E_EXE_PATH_NOT_VALID: HRESULT = 0x80300108u32 as HRESULT; +pub const PLA_E_DC_ALREADY_EXISTS: HRESULT = 0x80300109u32 as HRESULT; +pub const PLA_E_DCS_START_WAIT_TIMEOUT: HRESULT = 0x8030010Au32 as HRESULT; +pub const PLA_E_DC_START_WAIT_TIMEOUT: HRESULT = 0x8030010Bu32 as HRESULT; +pub const PLA_E_REPORT_WAIT_TIMEOUT: HRESULT = 0x8030010Cu32 as HRESULT; +pub const PLA_E_NO_DUPLICATES: HRESULT = 0x8030010Du32 as HRESULT; +pub const PLA_E_EXE_FULL_PATH_REQUIRED: HRESULT = 0x8030010Eu32 as HRESULT; +pub const PLA_E_INVALID_SESSION_NAME: HRESULT = 0x8030010Fu32 as HRESULT; +pub const PLA_E_PLA_CHANNEL_NOT_ENABLED: HRESULT = 0x80300110u32 as HRESULT; +pub const PLA_E_TASKSCHED_CHANNEL_NOT_ENABLED: HRESULT = 0x80300111u32 as HRESULT; +pub const PLA_E_RULES_MANAGER_FAILED: HRESULT = 0x80300112u32 as HRESULT; +pub const PLA_E_CABAPI_FAILURE: HRESULT = 0x80300113u32 as HRESULT; +pub const FVE_E_LOCKED_VOLUME: HRESULT = 0x80310000u32 as HRESULT; +pub const FVE_E_NOT_ENCRYPTED: HRESULT = 0x80310001u32 as HRESULT; +pub const FVE_E_NO_TPM_BIOS: HRESULT = 0x80310002u32 as HRESULT; +pub const FVE_E_NO_MBR_METRIC: HRESULT = 0x80310003u32 as HRESULT; +pub const FVE_E_NO_BOOTSECTOR_METRIC: HRESULT = 0x80310004u32 as HRESULT; +pub const FVE_E_NO_BOOTMGR_METRIC: HRESULT = 0x80310005u32 as HRESULT; +pub const FVE_E_WRONG_BOOTMGR: HRESULT = 0x80310006u32 as HRESULT; +pub const FVE_E_SECURE_KEY_REQUIRED: HRESULT = 0x80310007u32 as HRESULT; +pub const FVE_E_NOT_ACTIVATED: HRESULT = 0x80310008u32 as HRESULT; +pub const FVE_E_ACTION_NOT_ALLOWED: HRESULT = 0x80310009u32 as HRESULT; +pub const FVE_E_AD_SCHEMA_NOT_INSTALLED: HRESULT = 0x8031000Au32 as HRESULT; +pub const FVE_E_AD_INVALID_DATATYPE: HRESULT = 0x8031000Bu32 as HRESULT; +pub const FVE_E_AD_INVALID_DATASIZE: HRESULT = 0x8031000Cu32 as HRESULT; +pub const FVE_E_AD_NO_VALUES: HRESULT = 0x8031000Du32 as HRESULT; +pub const FVE_E_AD_ATTR_NOT_SET: HRESULT = 0x8031000Eu32 as HRESULT; +pub const FVE_E_AD_GUID_NOT_FOUND: HRESULT = 0x8031000Fu32 as HRESULT; +pub const FVE_E_BAD_INFORMATION: HRESULT = 0x80310010u32 as HRESULT; +pub const FVE_E_TOO_SMALL: HRESULT = 0x80310011u32 as HRESULT; +pub const FVE_E_SYSTEM_VOLUME: HRESULT = 0x80310012u32 as HRESULT; +pub const FVE_E_FAILED_WRONG_FS: HRESULT = 0x80310013u32 as HRESULT; +pub const FVE_E_BAD_PARTITION_SIZE: HRESULT = 0x80310014u32 as HRESULT; +pub const FVE_E_NOT_SUPPORTED: HRESULT = 0x80310015u32 as HRESULT; +pub const FVE_E_BAD_DATA: HRESULT = 0x80310016u32 as HRESULT; +pub const FVE_E_VOLUME_NOT_BOUND: HRESULT = 0x80310017u32 as HRESULT; +pub const FVE_E_TPM_NOT_OWNED: HRESULT = 0x80310018u32 as HRESULT; +pub const FVE_E_NOT_DATA_VOLUME: HRESULT = 0x80310019u32 as HRESULT; +pub const FVE_E_AD_INSUFFICIENT_BUFFER: HRESULT = 0x8031001Au32 as HRESULT; +pub const FVE_E_CONV_READ: HRESULT = 0x8031001Bu32 as HRESULT; +pub const FVE_E_CONV_WRITE: HRESULT = 0x8031001Cu32 as HRESULT; +pub const FVE_E_KEY_REQUIRED: HRESULT = 0x8031001Du32 as HRESULT; +pub const FVE_E_CLUSTERING_NOT_SUPPORTED: HRESULT = 0x8031001Eu32 as HRESULT; +pub const FVE_E_VOLUME_BOUND_ALREADY: HRESULT = 0x8031001Fu32 as HRESULT; +pub const FVE_E_OS_NOT_PROTECTED: HRESULT = 0x80310020u32 as HRESULT; +pub const FVE_E_PROTECTION_DISABLED: HRESULT = 0x80310021u32 as HRESULT; +pub const FVE_E_RECOVERY_KEY_REQUIRED: HRESULT = 0x80310022u32 as HRESULT; +pub const FVE_E_FOREIGN_VOLUME: HRESULT = 0x80310023u32 as HRESULT; +pub const FVE_E_OVERLAPPED_UPDATE: HRESULT = 0x80310024u32 as HRESULT; +pub const FVE_E_TPM_SRK_AUTH_NOT_ZERO: HRESULT = 0x80310025u32 as HRESULT; +pub const FVE_E_FAILED_SECTOR_SIZE: HRESULT = 0x80310026u32 as HRESULT; +pub const FVE_E_FAILED_AUTHENTICATION: HRESULT = 0x80310027u32 as HRESULT; +pub const FVE_E_NOT_OS_VOLUME: HRESULT = 0x80310028u32 as HRESULT; +pub const FVE_E_AUTOUNLOCK_ENABLED: HRESULT = 0x80310029u32 as HRESULT; +pub const FVE_E_WRONG_BOOTSECTOR: HRESULT = 0x8031002Au32 as HRESULT; +pub const FVE_E_WRONG_SYSTEM_FS: HRESULT = 0x8031002Bu32 as HRESULT; +pub const FVE_E_POLICY_PASSWORD_REQUIRED: HRESULT = 0x8031002Cu32 as HRESULT; +pub const FVE_E_CANNOT_SET_FVEK_ENCRYPTED: HRESULT = 0x8031002Du32 as HRESULT; +pub const FVE_E_CANNOT_ENCRYPT_NO_KEY: HRESULT = 0x8031002Eu32 as HRESULT; +pub const FVE_E_BOOTABLE_CDDVD: HRESULT = 0x80310030u32 as HRESULT; +pub const FVE_E_PROTECTOR_EXISTS: HRESULT = 0x80310031u32 as HRESULT; +pub const FVE_E_RELATIVE_PATH: HRESULT = 0x80310032u32 as HRESULT; +pub const FVE_E_PROTECTOR_NOT_FOUND: HRESULT = 0x80310033u32 as HRESULT; +pub const FVE_E_INVALID_KEY_FORMAT: HRESULT = 0x80310034u32 as HRESULT; +pub const FVE_E_INVALID_PASSWORD_FORMAT: HRESULT = 0x80310035u32 as HRESULT; +pub const FVE_E_FIPS_RNG_CHECK_FAILED: HRESULT = 0x80310036u32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_RECOVERY_PASSWORD: HRESULT = 0x80310037u32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_EXTERNAL_KEY_EXPORT: HRESULT = 0x80310038u32 as HRESULT; +pub const FVE_E_NOT_DECRYPTED: HRESULT = 0x80310039u32 as HRESULT; +pub const FVE_E_INVALID_PROTECTOR_TYPE: HRESULT = 0x8031003Au32 as HRESULT; +pub const FVE_E_NO_PROTECTORS_TO_TEST: HRESULT = 0x8031003Bu32 as HRESULT; +pub const FVE_E_KEYFILE_NOT_FOUND: HRESULT = 0x8031003Cu32 as HRESULT; +pub const FVE_E_KEYFILE_INVALID: HRESULT = 0x8031003Du32 as HRESULT; +pub const FVE_E_KEYFILE_NO_VMK: HRESULT = 0x8031003Eu32 as HRESULT; +pub const FVE_E_TPM_DISABLED: HRESULT = 0x8031003Fu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_IN_SAFE_MODE: HRESULT = 0x80310040u32 as HRESULT; +pub const FVE_E_TPM_INVALID_PCR: HRESULT = 0x80310041u32 as HRESULT; +pub const FVE_E_TPM_NO_VMK: HRESULT = 0x80310042u32 as HRESULT; +pub const FVE_E_PIN_INVALID: HRESULT = 0x80310043u32 as HRESULT; +pub const FVE_E_AUTH_INVALID_APPLICATION: HRESULT = 0x80310044u32 as HRESULT; +pub const FVE_E_AUTH_INVALID_CONFIG: HRESULT = 0x80310045u32 as HRESULT; +pub const FVE_E_FIPS_DISABLE_PROTECTION_NOT_ALLOWED: HRESULT = 0x80310046u32 as HRESULT; +pub const FVE_E_FS_NOT_EXTENDED: HRESULT = 0x80310047u32 as HRESULT; +pub const FVE_E_FIRMWARE_TYPE_NOT_SUPPORTED: HRESULT = 0x80310048u32 as HRESULT; +pub const FVE_E_NO_LICENSE: HRESULT = 0x80310049u32 as HRESULT; +pub const FVE_E_NOT_ON_STACK: HRESULT = 0x8031004Au32 as HRESULT; +pub const FVE_E_FS_MOUNTED: HRESULT = 0x8031004Bu32 as HRESULT; +pub const FVE_E_TOKEN_NOT_IMPERSONATED: HRESULT = 0x8031004Cu32 as HRESULT; +pub const FVE_E_DRY_RUN_FAILED: HRESULT = 0x8031004Du32 as HRESULT; +pub const FVE_E_REBOOT_REQUIRED: HRESULT = 0x8031004Eu32 as HRESULT; +pub const FVE_E_DEBUGGER_ENABLED: HRESULT = 0x8031004Fu32 as HRESULT; +pub const FVE_E_RAW_ACCESS: HRESULT = 0x80310050u32 as HRESULT; +pub const FVE_E_RAW_BLOCKED: HRESULT = 0x80310051u32 as HRESULT; +pub const FVE_E_BCD_APPLICATIONS_PATH_INCORRECT: HRESULT = 0x80310052u32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_IN_VERSION: HRESULT = 0x80310053u32 as HRESULT; +pub const FVE_E_NO_AUTOUNLOCK_MASTER_KEY: HRESULT = 0x80310054u32 as HRESULT; +pub const FVE_E_MOR_FAILED: HRESULT = 0x80310055u32 as HRESULT; +pub const FVE_E_HIDDEN_VOLUME: HRESULT = 0x80310056u32 as HRESULT; +pub const FVE_E_TRANSIENT_STATE: HRESULT = 0x80310057u32 as HRESULT; +pub const FVE_E_PUBKEY_NOT_ALLOWED: HRESULT = 0x80310058u32 as HRESULT; +pub const FVE_E_VOLUME_HANDLE_OPEN: HRESULT = 0x80310059u32 as HRESULT; +pub const FVE_E_NO_FEATURE_LICENSE: HRESULT = 0x8031005Au32 as HRESULT; +pub const FVE_E_INVALID_STARTUP_OPTIONS: HRESULT = 0x8031005Bu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_PASSWORD_NOT_ALLOWED: HRESULT = 0x8031005Cu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_PASSWORD_REQUIRED: HRESULT = 0x8031005Du32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_KEY_NOT_ALLOWED: HRESULT = 0x8031005Eu32 as HRESULT; +pub const FVE_E_POLICY_RECOVERY_KEY_REQUIRED: HRESULT = 0x8031005Fu32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_NOT_ALLOWED: HRESULT = 0x80310060u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_REQUIRED: HRESULT = 0x80310061u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_KEY_NOT_ALLOWED: HRESULT = 0x80310062u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_KEY_REQUIRED: HRESULT = 0x80310063u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_KEY_NOT_ALLOWED: HRESULT = 0x80310064u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_PIN_KEY_REQUIRED: HRESULT = 0x80310065u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_TPM_NOT_ALLOWED: HRESULT = 0x80310066u32 as HRESULT; +pub const FVE_E_POLICY_STARTUP_TPM_REQUIRED: HRESULT = 0x80310067u32 as HRESULT; +pub const FVE_E_POLICY_INVALID_PIN_LENGTH: HRESULT = 0x80310068u32 as HRESULT; +pub const FVE_E_KEY_PROTECTOR_NOT_SUPPORTED: HRESULT = 0x80310069u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_NOT_ALLOWED: HRESULT = 0x8031006Au32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_REQUIRED: HRESULT = 0x8031006Bu32 as HRESULT; +pub const FVE_E_FIPS_PREVENTS_PASSPHRASE: HRESULT = 0x8031006Cu32 as HRESULT; +pub const FVE_E_OS_VOLUME_PASSPHRASE_NOT_ALLOWED: HRESULT = 0x8031006Du32 as HRESULT; +pub const FVE_E_INVALID_BITLOCKER_OID: HRESULT = 0x8031006Eu32 as HRESULT; +pub const FVE_E_VOLUME_TOO_SMALL: HRESULT = 0x8031006Fu32 as HRESULT; +pub const FVE_E_DV_NOT_SUPPORTED_ON_FS: HRESULT = 0x80310070u32 as HRESULT; +pub const FVE_E_DV_NOT_ALLOWED_BY_GP: HRESULT = 0x80310071u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERTIFICATE_NOT_ALLOWED: HRESULT = 0x80310072u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERTIFICATE_REQUIRED: HRESULT = 0x80310073u32 as HRESULT; +pub const FVE_E_POLICY_USER_CERT_MUST_BE_HW: HRESULT = 0x80310074u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_FDV_AUTOUNLOCK_NOT_ALLOWED: HRESULT = 0x80310075u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_RDV_AUTOUNLOCK_NOT_ALLOWED: HRESULT = 0x80310076u32 as HRESULT; +pub const FVE_E_POLICY_USER_CONFIGURE_RDV_NOT_ALLOWED: HRESULT = 0x80310077u32 as HRESULT; +pub const FVE_E_POLICY_USER_ENABLE_RDV_NOT_ALLOWED: HRESULT = 0x80310078u32 as HRESULT; +pub const FVE_E_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: HRESULT = 0x80310079u32 as HRESULT; +pub const FVE_E_POLICY_INVALID_PASSPHRASE_LENGTH: HRESULT = 0x80310080u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_TOO_SIMPLE: HRESULT = 0x80310081u32 as HRESULT; +pub const FVE_E_RECOVERY_PARTITION: HRESULT = 0x80310082u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_FDV_RK_OFF_AUK_ON: HRESULT = 0x80310083u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RDV_RK_OFF_AUK_ON: HRESULT = 0x80310084u32 as HRESULT; +pub const FVE_E_NON_BITLOCKER_OID: HRESULT = 0x80310085u32 as HRESULT; +pub const FVE_E_POLICY_PROHIBITS_SELFSIGNED: HRESULT = 0x80310086u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RO_AND_STARTUP_KEY_REQUIRED: HRESULT = 0x80310087u32 as HRESULT; +pub const FVE_E_CONV_RECOVERY_FAILED: HRESULT = 0x80310088u32 as HRESULT; +pub const FVE_E_VIRTUALIZED_SPACE_TOO_BIG: HRESULT = 0x80310089u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_OSV_RP_OFF_ADB_ON: HRESULT = 0x80310090u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_FDV_RP_OFF_ADB_ON: HRESULT = 0x80310091u32 as HRESULT; +pub const FVE_E_POLICY_CONFLICT_RDV_RP_OFF_ADB_ON: HRESULT = 0x80310092u32 as HRESULT; +pub const FVE_E_NON_BITLOCKER_KU: HRESULT = 0x80310093u32 as HRESULT; +pub const FVE_E_PRIVATEKEY_AUTH_FAILED: HRESULT = 0x80310094u32 as HRESULT; +pub const FVE_E_REMOVAL_OF_DRA_FAILED: HRESULT = 0x80310095u32 as HRESULT; +pub const FVE_E_OPERATION_NOT_SUPPORTED_ON_VISTA_VOLUME: HRESULT = 0x80310096u32 as HRESULT; +pub const FVE_E_CANT_LOCK_AUTOUNLOCK_ENABLED_VOLUME: HRESULT = 0x80310097u32 as HRESULT; +pub const FVE_E_FIPS_HASH_KDF_NOT_ALLOWED: HRESULT = 0x80310098u32 as HRESULT; +pub const FVE_E_ENH_PIN_INVALID: HRESULT = 0x80310099u32 as HRESULT; +pub const FVE_E_INVALID_PIN_CHARS: HRESULT = 0x8031009Au32 as HRESULT; +pub const FVE_E_INVALID_DATUM_TYPE: HRESULT = 0x8031009Bu32 as HRESULT; +pub const FVE_E_EFI_ONLY: HRESULT = 0x8031009Cu32 as HRESULT; +pub const FVE_E_MULTIPLE_NKP_CERTS: HRESULT = 0x8031009Du32 as HRESULT; +pub const FVE_E_REMOVAL_OF_NKP_FAILED: HRESULT = 0x8031009Eu32 as HRESULT; +pub const FVE_E_INVALID_NKP_CERT: HRESULT = 0x8031009Fu32 as HRESULT; +pub const FVE_E_NO_EXISTING_PIN: HRESULT = 0x803100A0u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_PIN_MISMATCH: HRESULT = 0x803100A1u32 as HRESULT; +pub const FVE_E_PIN_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: HRESULT = 0x803100A2u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_MAX_PIN_CHANGE_ATTEMPTS_REACHED: HRESULT = 0x803100A3u32 as HRESULT; +pub const FVE_E_POLICY_PASSPHRASE_REQUIRES_ASCII: HRESULT = 0x803100A4u32 as HRESULT; +pub const FVE_E_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: HRESULT = 0x803100A5u32 as HRESULT; +pub const FVE_E_WIPE_NOT_ALLOWED_ON_TP_STORAGE: HRESULT = 0x803100A6u32 as HRESULT; +pub const FVE_E_KEY_LENGTH_NOT_SUPPORTED_BY_EDRIVE: HRESULT = 0x803100A7u32 as HRESULT; +pub const FVE_E_NO_EXISTING_PASSPHRASE: HRESULT = 0x803100A8u32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_PASSPHRASE_MISMATCH: HRESULT = 0x803100A9u32 as HRESULT; +pub const FVE_E_PASSPHRASE_TOO_LONG: HRESULT = 0x803100AAu32 as HRESULT; +pub const FVE_E_NO_PASSPHRASE_WITH_TPM: HRESULT = 0x803100ABu32 as HRESULT; +pub const FVE_E_NO_TPM_WITH_PASSPHRASE: HRESULT = 0x803100ACu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_ON_CSV_STACK: HRESULT = 0x803100ADu32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_ON_CLUSTER: HRESULT = 0x803100AEu32 as HRESULT; +pub const FVE_E_EDRIVE_NO_FAILOVER_TO_SW: HRESULT = 0x803100AFu32 as HRESULT; +pub const FVE_E_EDRIVE_BAND_IN_USE: HRESULT = 0x803100B0u32 as HRESULT; +pub const FVE_E_EDRIVE_DISALLOWED_BY_GP: HRESULT = 0x803100B1u32 as HRESULT; +pub const FVE_E_EDRIVE_INCOMPATIBLE_VOLUME: HRESULT = 0x803100B2u32 as HRESULT; +pub const FVE_E_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: HRESULT = 0x803100B3u32 as HRESULT; +pub const FVE_E_EDRIVE_DV_NOT_SUPPORTED: HRESULT = 0x803100B4u32 as HRESULT; +pub const FVE_E_NO_PREBOOT_KEYBOARD_DETECTED: HRESULT = 0x803100B5u32 as HRESULT; +pub const FVE_E_NO_PREBOOT_KEYBOARD_OR_WINRE_DETECTED: HRESULT = 0x803100B6u32 as HRESULT; +pub const FVE_E_POLICY_REQUIRES_STARTUP_PIN_ON_TOUCH_DEVICE: HRESULT = 0x803100B7u32 as HRESULT; +pub const FVE_E_POLICY_REQUIRES_RECOVERY_PASSWORD_ON_TOUCH_DEVICE: HRESULT = 0x803100B8u32 as HRESULT; +pub const FVE_E_WIPE_CANCEL_NOT_APPLICABLE: HRESULT = 0x803100B9u32 as HRESULT; +pub const FVE_E_SECUREBOOT_DISABLED: HRESULT = 0x803100BAu32 as HRESULT; +pub const FVE_E_SECUREBOOT_CONFIGURATION_INVALID: HRESULT = 0x803100BBu32 as HRESULT; +pub const FVE_E_EDRIVE_DRY_RUN_FAILED: HRESULT = 0x803100BCu32 as HRESULT; +pub const FVE_E_SHADOW_COPY_PRESENT: HRESULT = 0x803100BDu32 as HRESULT; +pub const FVE_E_POLICY_INVALID_ENHANCED_BCD_SETTINGS: HRESULT = 0x803100BEu32 as HRESULT; +pub const FVE_E_EDRIVE_INCOMPATIBLE_FIRMWARE: HRESULT = 0x803100BFu32 as HRESULT; +pub const FVE_E_PROTECTOR_CHANGE_MAX_PASSPHRASE_CHANGE_ATTEMPTS_REACHED: HRESULT = 0x803100C0u32 as HRESULT; +pub const FVE_E_PASSPHRASE_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: HRESULT = 0x803100C1u32 as HRESULT; +pub const FVE_E_LIVEID_ACCOUNT_SUSPENDED: HRESULT = 0x803100C2u32 as HRESULT; +pub const FVE_E_LIVEID_ACCOUNT_BLOCKED: HRESULT = 0x803100C3u32 as HRESULT; +pub const FVE_E_NOT_PROVISIONED_ON_ALL_VOLUMES: HRESULT = 0x803100C4u32 as HRESULT; +pub const FVE_E_DE_FIXED_DATA_NOT_SUPPORTED: HRESULT = 0x803100C5u32 as HRESULT; +pub const FVE_E_DE_HARDWARE_NOT_COMPLIANT: HRESULT = 0x803100C6u32 as HRESULT; +pub const FVE_E_DE_WINRE_NOT_CONFIGURED: HRESULT = 0x803100C7u32 as HRESULT; +pub const FVE_E_DE_PROTECTION_SUSPENDED: HRESULT = 0x803100C8u32 as HRESULT; +pub const FVE_E_DE_OS_VOLUME_NOT_PROTECTED: HRESULT = 0x803100C9u32 as HRESULT; +pub const FVE_E_DE_DEVICE_LOCKEDOUT: HRESULT = 0x803100CAu32 as HRESULT; +pub const FVE_E_DE_PROTECTION_NOT_YET_ENABLED: HRESULT = 0x803100CBu32 as HRESULT; +pub const FVE_E_INVALID_PIN_CHARS_DETAILED: HRESULT = 0x803100CCu32 as HRESULT; +pub const FVE_E_DEVICE_LOCKOUT_COUNTER_UNAVAILABLE: HRESULT = 0x803100CDu32 as HRESULT; +pub const FVE_E_DEVICELOCKOUT_COUNTER_MISMATCH: HRESULT = 0x803100CEu32 as HRESULT; +pub const FVE_E_BUFFER_TOO_LARGE: HRESULT = 0x803100CFu32 as HRESULT; +pub const FVE_E_NO_SUCH_CAPABILITY_ON_TARGET: HRESULT = 0x803100D0u32 as HRESULT; +pub const FVE_E_DE_PREVENTED_FOR_OS: HRESULT = 0x803100D1u32 as HRESULT; +pub const FVE_E_DE_VOLUME_OPTED_OUT: HRESULT = 0x803100D2u32 as HRESULT; +pub const FVE_E_DE_VOLUME_NOT_SUPPORTED: HRESULT = 0x803100D3u32 as HRESULT; +pub const FVE_E_EOW_NOT_SUPPORTED_IN_VERSION: HRESULT = 0x803100D4u32 as HRESULT; +pub const FVE_E_ADBACKUP_NOT_ENABLED: HRESULT = 0x803100D5u32 as HRESULT; +pub const FVE_E_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: HRESULT = 0x803100D6u32 as HRESULT; +pub const FVE_E_NOT_DE_VOLUME: HRESULT = 0x803100D7u32 as HRESULT; +pub const FVE_E_PROTECTION_CANNOT_BE_DISABLED: HRESULT = 0x803100D8u32 as HRESULT; +pub const FWP_E_CALLOUT_NOT_FOUND: HRESULT = 0x80320001u32 as HRESULT; +pub const FWP_E_CONDITION_NOT_FOUND: HRESULT = 0x80320002u32 as HRESULT; +pub const FWP_E_FILTER_NOT_FOUND: HRESULT = 0x80320003u32 as HRESULT; +pub const FWP_E_LAYER_NOT_FOUND: HRESULT = 0x80320004u32 as HRESULT; +pub const FWP_E_PROVIDER_NOT_FOUND: HRESULT = 0x80320005u32 as HRESULT; +pub const FWP_E_PROVIDER_CONTEXT_NOT_FOUND: HRESULT = 0x80320006u32 as HRESULT; +pub const FWP_E_SUBLAYER_NOT_FOUND: HRESULT = 0x80320007u32 as HRESULT; +pub const FWP_E_NOT_FOUND: HRESULT = 0x80320008u32 as HRESULT; +pub const FWP_E_ALREADY_EXISTS: HRESULT = 0x80320009u32 as HRESULT; +pub const FWP_E_IN_USE: HRESULT = 0x8032000Au32 as HRESULT; +pub const FWP_E_DYNAMIC_SESSION_IN_PROGRESS: HRESULT = 0x8032000Bu32 as HRESULT; +pub const FWP_E_WRONG_SESSION: HRESULT = 0x8032000Cu32 as HRESULT; +pub const FWP_E_NO_TXN_IN_PROGRESS: HRESULT = 0x8032000Du32 as HRESULT; +pub const FWP_E_TXN_IN_PROGRESS: HRESULT = 0x8032000Eu32 as HRESULT; +pub const FWP_E_TXN_ABORTED: HRESULT = 0x8032000Fu32 as HRESULT; +pub const FWP_E_SESSION_ABORTED: HRESULT = 0x80320010u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_TXN: HRESULT = 0x80320011u32 as HRESULT; +pub const FWP_E_TIMEOUT: HRESULT = 0x80320012u32 as HRESULT; +pub const FWP_E_NET_EVENTS_DISABLED: HRESULT = 0x80320013u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_LAYER: HRESULT = 0x80320014u32 as HRESULT; +pub const FWP_E_KM_CLIENTS_ONLY: HRESULT = 0x80320015u32 as HRESULT; +pub const FWP_E_LIFETIME_MISMATCH: HRESULT = 0x80320016u32 as HRESULT; +pub const FWP_E_BUILTIN_OBJECT: HRESULT = 0x80320017u32 as HRESULT; +pub const FWP_E_TOO_MANY_CALLOUTS: HRESULT = 0x80320018u32 as HRESULT; +pub const FWP_E_NOTIFICATION_DROPPED: HRESULT = 0x80320019u32 as HRESULT; +pub const FWP_E_TRAFFIC_MISMATCH: HRESULT = 0x8032001Au32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_SA_STATE: HRESULT = 0x8032001Bu32 as HRESULT; +pub const FWP_E_NULL_POINTER: HRESULT = 0x8032001Cu32 as HRESULT; +pub const FWP_E_INVALID_ENUMERATOR: HRESULT = 0x8032001Du32 as HRESULT; +pub const FWP_E_INVALID_FLAGS: HRESULT = 0x8032001Eu32 as HRESULT; +pub const FWP_E_INVALID_NET_MASK: HRESULT = 0x8032001Fu32 as HRESULT; +pub const FWP_E_INVALID_RANGE: HRESULT = 0x80320020u32 as HRESULT; +pub const FWP_E_INVALID_INTERVAL: HRESULT = 0x80320021u32 as HRESULT; +pub const FWP_E_ZERO_LENGTH_ARRAY: HRESULT = 0x80320022u32 as HRESULT; +pub const FWP_E_NULL_DISPLAY_NAME: HRESULT = 0x80320023u32 as HRESULT; +pub const FWP_E_INVALID_ACTION_TYPE: HRESULT = 0x80320024u32 as HRESULT; +pub const FWP_E_INVALID_WEIGHT: HRESULT = 0x80320025u32 as HRESULT; +pub const FWP_E_MATCH_TYPE_MISMATCH: HRESULT = 0x80320026u32 as HRESULT; +pub const FWP_E_TYPE_MISMATCH: HRESULT = 0x80320027u32 as HRESULT; +pub const FWP_E_OUT_OF_BOUNDS: HRESULT = 0x80320028u32 as HRESULT; +pub const FWP_E_RESERVED: HRESULT = 0x80320029u32 as HRESULT; +pub const FWP_E_DUPLICATE_CONDITION: HRESULT = 0x8032002Au32 as HRESULT; +pub const FWP_E_DUPLICATE_KEYMOD: HRESULT = 0x8032002Bu32 as HRESULT; +pub const FWP_E_ACTION_INCOMPATIBLE_WITH_LAYER: HRESULT = 0x8032002Cu32 as HRESULT; +pub const FWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER: HRESULT = 0x8032002Du32 as HRESULT; +pub const FWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER: HRESULT = 0x8032002Eu32 as HRESULT; +pub const FWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: HRESULT = 0x8032002Fu32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_AUTH_METHOD: HRESULT = 0x80320030u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_DH_GROUP: HRESULT = 0x80320031u32 as HRESULT; +pub const FWP_E_EM_NOT_SUPPORTED: HRESULT = 0x80320032u32 as HRESULT; +pub const FWP_E_NEVER_MATCH: HRESULT = 0x80320033u32 as HRESULT; +pub const FWP_E_PROVIDER_CONTEXT_MISMATCH: HRESULT = 0x80320034u32 as HRESULT; +pub const FWP_E_INVALID_PARAMETER: HRESULT = 0x80320035u32 as HRESULT; +pub const FWP_E_TOO_MANY_SUBLAYERS: HRESULT = 0x80320036u32 as HRESULT; +pub const FWP_E_CALLOUT_NOTIFICATION_FAILED: HRESULT = 0x80320037u32 as HRESULT; +pub const FWP_E_INVALID_AUTH_TRANSFORM: HRESULT = 0x80320038u32 as HRESULT; +pub const FWP_E_INVALID_CIPHER_TRANSFORM: HRESULT = 0x80320039u32 as HRESULT; +pub const FWP_E_INCOMPATIBLE_CIPHER_TRANSFORM: HRESULT = 0x8032003Au32 as HRESULT; +pub const FWP_E_INVALID_TRANSFORM_COMBINATION: HRESULT = 0x8032003Bu32 as HRESULT; +pub const FWP_E_DUPLICATE_AUTH_METHOD: HRESULT = 0x8032003Cu32 as HRESULT; +pub const FWP_E_INVALID_TUNNEL_ENDPOINT: HRESULT = 0x8032003Du32 as HRESULT; +pub const FWP_E_L2_DRIVER_NOT_READY: HRESULT = 0x8032003Eu32 as HRESULT; +pub const FWP_E_KEY_DICTATOR_ALREADY_REGISTERED: HRESULT = 0x8032003Fu32 as HRESULT; +pub const FWP_E_KEY_DICTATION_INVALID_KEYING_MATERIAL: HRESULT = 0x80320040u32 as HRESULT; +pub const FWP_E_CONNECTIONS_DISABLED: HRESULT = 0x80320041u32 as HRESULT; +pub const FWP_E_INVALID_DNS_NAME: HRESULT = 0x80320042u32 as HRESULT; +pub const FWP_E_STILL_ON: HRESULT = 0x80320043u32 as HRESULT; +pub const FWP_E_IKEEXT_NOT_RUNNING: HRESULT = 0x80320044u32 as HRESULT; +pub const FWP_E_DROP_NOICMP: HRESULT = 0x80320104u32 as HRESULT; +pub const WS_S_ASYNC: HRESULT = 0x003D0000; +pub const WS_S_END: HRESULT = 0x003D0001; +pub const WS_E_INVALID_FORMAT: HRESULT = 0x803D0000u32 as HRESULT; +pub const WS_E_OBJECT_FAULTED: HRESULT = 0x803D0001u32 as HRESULT; +pub const WS_E_NUMERIC_OVERFLOW: HRESULT = 0x803D0002u32 as HRESULT; +pub const WS_E_INVALID_OPERATION: HRESULT = 0x803D0003u32 as HRESULT; +pub const WS_E_OPERATION_ABORTED: HRESULT = 0x803D0004u32 as HRESULT; +pub const WS_E_ENDPOINT_ACCESS_DENIED: HRESULT = 0x803D0005u32 as HRESULT; +pub const WS_E_OPERATION_TIMED_OUT: HRESULT = 0x803D0006u32 as HRESULT; +pub const WS_E_OPERATION_ABANDONED: HRESULT = 0x803D0007u32 as HRESULT; +pub const WS_E_QUOTA_EXCEEDED: HRESULT = 0x803D0008u32 as HRESULT; +pub const WS_E_NO_TRANSLATION_AVAILABLE: HRESULT = 0x803D0009u32 as HRESULT; +pub const WS_E_SECURITY_VERIFICATION_FAILURE: HRESULT = 0x803D000Au32 as HRESULT; +pub const WS_E_ADDRESS_IN_USE: HRESULT = 0x803D000Bu32 as HRESULT; +pub const WS_E_ADDRESS_NOT_AVAILABLE: HRESULT = 0x803D000Cu32 as HRESULT; +pub const WS_E_ENDPOINT_NOT_FOUND: HRESULT = 0x803D000Du32 as HRESULT; +pub const WS_E_ENDPOINT_NOT_AVAILABLE: HRESULT = 0x803D000Eu32 as HRESULT; +pub const WS_E_ENDPOINT_FAILURE: HRESULT = 0x803D000Fu32 as HRESULT; +pub const WS_E_ENDPOINT_UNREACHABLE: HRESULT = 0x803D0010u32 as HRESULT; +pub const WS_E_ENDPOINT_ACTION_NOT_SUPPORTED: HRESULT = 0x803D0011u32 as HRESULT; +pub const WS_E_ENDPOINT_TOO_BUSY: HRESULT = 0x803D0012u32 as HRESULT; +pub const WS_E_ENDPOINT_FAULT_RECEIVED: HRESULT = 0x803D0013u32 as HRESULT; +pub const WS_E_ENDPOINT_DISCONNECTED: HRESULT = 0x803D0014u32 as HRESULT; +pub const WS_E_PROXY_FAILURE: HRESULT = 0x803D0015u32 as HRESULT; +pub const WS_E_PROXY_ACCESS_DENIED: HRESULT = 0x803D0016u32 as HRESULT; +pub const WS_E_NOT_SUPPORTED: HRESULT = 0x803D0017u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_BASIC_AUTH: HRESULT = 0x803D0018u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_DIGEST_AUTH: HRESULT = 0x803D0019u32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_NTLM_AUTH: HRESULT = 0x803D001Au32 as HRESULT; +pub const WS_E_PROXY_REQUIRES_NEGOTIATE_AUTH: HRESULT = 0x803D001Bu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_BASIC_AUTH: HRESULT = 0x803D001Cu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_DIGEST_AUTH: HRESULT = 0x803D001Du32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_NTLM_AUTH: HRESULT = 0x803D001Eu32 as HRESULT; +pub const WS_E_SERVER_REQUIRES_NEGOTIATE_AUTH: HRESULT = 0x803D001Fu32 as HRESULT; +pub const WS_E_INVALID_ENDPOINT_URL: HRESULT = 0x803D0020u32 as HRESULT; +pub const WS_E_OTHER: HRESULT = 0x803D0021u32 as HRESULT; +pub const WS_E_SECURITY_TOKEN_EXPIRED: HRESULT = 0x803D0022u32 as HRESULT; +pub const WS_E_SECURITY_SYSTEM_FAILURE: HRESULT = 0x803D0023u32 as HRESULT; +pub const ERROR_NDIS_INTERFACE_CLOSING: HRESULT = 0x80340002u32 as HRESULT; +pub const ERROR_NDIS_BAD_VERSION: HRESULT = 0x80340004u32 as HRESULT; +pub const ERROR_NDIS_BAD_CHARACTERISTICS: HRESULT = 0x80340005u32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_NOT_FOUND: HRESULT = 0x80340006u32 as HRESULT; +pub const ERROR_NDIS_OPEN_FAILED: HRESULT = 0x80340007u32 as HRESULT; +pub const ERROR_NDIS_DEVICE_FAILED: HRESULT = 0x80340008u32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_FULL: HRESULT = 0x80340009u32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_EXISTS: HRESULT = 0x8034000Au32 as HRESULT; +pub const ERROR_NDIS_MULTICAST_NOT_FOUND: HRESULT = 0x8034000Bu32 as HRESULT; +pub const ERROR_NDIS_REQUEST_ABORTED: HRESULT = 0x8034000Cu32 as HRESULT; +pub const ERROR_NDIS_RESET_IN_PROGRESS: HRESULT = 0x8034000Du32 as HRESULT; +pub const ERROR_NDIS_NOT_SUPPORTED: HRESULT = 0x803400BBu32 as HRESULT; +pub const ERROR_NDIS_INVALID_PACKET: HRESULT = 0x8034000Fu32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_NOT_READY: HRESULT = 0x80340011u32 as HRESULT; +pub const ERROR_NDIS_INVALID_LENGTH: HRESULT = 0x80340014u32 as HRESULT; +pub const ERROR_NDIS_INVALID_DATA: HRESULT = 0x80340015u32 as HRESULT; +pub const ERROR_NDIS_BUFFER_TOO_SHORT: HRESULT = 0x80340016u32 as HRESULT; +pub const ERROR_NDIS_INVALID_OID: HRESULT = 0x80340017u32 as HRESULT; +pub const ERROR_NDIS_ADAPTER_REMOVED: HRESULT = 0x80340018u32 as HRESULT; +pub const ERROR_NDIS_UNSUPPORTED_MEDIA: HRESULT = 0x80340019u32 as HRESULT; +pub const ERROR_NDIS_GROUP_ADDRESS_IN_USE: HRESULT = 0x8034001Au32 as HRESULT; +pub const ERROR_NDIS_FILE_NOT_FOUND: HRESULT = 0x8034001Bu32 as HRESULT; +pub const ERROR_NDIS_ERROR_READING_FILE: HRESULT = 0x8034001Cu32 as HRESULT; +pub const ERROR_NDIS_ALREADY_MAPPED: HRESULT = 0x8034001Du32 as HRESULT; +pub const ERROR_NDIS_RESOURCE_CONFLICT: HRESULT = 0x8034001Eu32 as HRESULT; +pub const ERROR_NDIS_MEDIA_DISCONNECTED: HRESULT = 0x8034001Fu32 as HRESULT; +pub const ERROR_NDIS_INVALID_ADDRESS: HRESULT = 0x80340022u32 as HRESULT; +pub const ERROR_NDIS_INVALID_DEVICE_REQUEST: HRESULT = 0x80340010u32 as HRESULT; +pub const ERROR_NDIS_PAUSED: HRESULT = 0x8034002Au32 as HRESULT; +pub const ERROR_NDIS_INTERFACE_NOT_FOUND: HRESULT = 0x8034002Bu32 as HRESULT; +pub const ERROR_NDIS_UNSUPPORTED_REVISION: HRESULT = 0x8034002Cu32 as HRESULT; +pub const ERROR_NDIS_INVALID_PORT: HRESULT = 0x8034002Du32 as HRESULT; +pub const ERROR_NDIS_INVALID_PORT_STATE: HRESULT = 0x8034002Eu32 as HRESULT; +pub const ERROR_NDIS_LOW_POWER_STATE: HRESULT = 0x8034002Fu32 as HRESULT; +pub const ERROR_NDIS_REINIT_REQUIRED: HRESULT = 0x80340030u32 as HRESULT; +pub const ERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED: HRESULT = 0x80342000u32 as HRESULT; +pub const ERROR_NDIS_DOT11_MEDIA_IN_USE: HRESULT = 0x80342001u32 as HRESULT; +pub const ERROR_NDIS_DOT11_POWER_STATE_INVALID: HRESULT = 0x80342002u32 as HRESULT; +pub const ERROR_NDIS_PM_WOL_PATTERN_LIST_FULL: HRESULT = 0x80342003u32 as HRESULT; +pub const ERROR_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: HRESULT = 0x80342004u32 as HRESULT; +pub const ERROR_NDIS_INDICATION_REQUIRED: HRESULT = 0x00340001; +pub const ERROR_NDIS_OFFLOAD_POLICY: HRESULT = 0xC034100Fu32 as HRESULT; +pub const ERROR_NDIS_OFFLOAD_CONNECTION_REJECTED: HRESULT = 0xC0341012u32 as HRESULT; +pub const ERROR_NDIS_OFFLOAD_PATH_REJECTED: HRESULT = 0xC0341013u32 as HRESULT; +pub const ERROR_HV_INVALID_HYPERCALL_CODE: HRESULT = 0xC0350002u32 as HRESULT; +pub const ERROR_HV_INVALID_HYPERCALL_INPUT: HRESULT = 0xC0350003u32 as HRESULT; +pub const ERROR_HV_INVALID_ALIGNMENT: HRESULT = 0xC0350004u32 as HRESULT; +pub const ERROR_HV_INVALID_PARAMETER: HRESULT = 0xC0350005u32 as HRESULT; +pub const ERROR_HV_ACCESS_DENIED: HRESULT = 0xC0350006u32 as HRESULT; +pub const ERROR_HV_INVALID_PARTITION_STATE: HRESULT = 0xC0350007u32 as HRESULT; +pub const ERROR_HV_OPERATION_DENIED: HRESULT = 0xC0350008u32 as HRESULT; +pub const ERROR_HV_UNKNOWN_PROPERTY: HRESULT = 0xC0350009u32 as HRESULT; +pub const ERROR_HV_PROPERTY_VALUE_OUT_OF_RANGE: HRESULT = 0xC035000Au32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_MEMORY: HRESULT = 0xC035000Bu32 as HRESULT; +pub const ERROR_HV_PARTITION_TOO_DEEP: HRESULT = 0xC035000Cu32 as HRESULT; +pub const ERROR_HV_INVALID_PARTITION_ID: HRESULT = 0xC035000Du32 as HRESULT; +pub const ERROR_HV_INVALID_VP_INDEX: HRESULT = 0xC035000Eu32 as HRESULT; +pub const ERROR_HV_INVALID_PORT_ID: HRESULT = 0xC0350011u32 as HRESULT; +pub const ERROR_HV_INVALID_CONNECTION_ID: HRESULT = 0xC0350012u32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_BUFFERS: HRESULT = 0xC0350013u32 as HRESULT; +pub const ERROR_HV_NOT_ACKNOWLEDGED: HRESULT = 0xC0350014u32 as HRESULT; +pub const ERROR_HV_ACKNOWLEDGED: HRESULT = 0xC0350016u32 as HRESULT; +pub const ERROR_HV_INVALID_SAVE_RESTORE_STATE: HRESULT = 0xC0350017u32 as HRESULT; +pub const ERROR_HV_INVALID_SYNIC_STATE: HRESULT = 0xC0350018u32 as HRESULT; +pub const ERROR_HV_OBJECT_IN_USE: HRESULT = 0xC0350019u32 as HRESULT; +pub const ERROR_HV_INVALID_PROXIMITY_DOMAIN_INFO: HRESULT = 0xC035001Au32 as HRESULT; +pub const ERROR_HV_NO_DATA: HRESULT = 0xC035001Bu32 as HRESULT; +pub const ERROR_HV_INACTIVE: HRESULT = 0xC035001Cu32 as HRESULT; +pub const ERROR_HV_NO_RESOURCES: HRESULT = 0xC035001Du32 as HRESULT; +pub const ERROR_HV_FEATURE_UNAVAILABLE: HRESULT = 0xC035001Eu32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_BUFFER: HRESULT = 0xC0350033u32 as HRESULT; +pub const ERROR_HV_INSUFFICIENT_DEVICE_DOMAINS: HRESULT = 0xC0350038u32 as HRESULT; +pub const ERROR_HV_INVALID_LP_INDEX: HRESULT = 0xC0350041u32 as HRESULT; +pub const ERROR_HV_NOT_PRESENT: HRESULT = 0xC0351000u32 as HRESULT; +pub const ERROR_VID_DUPLICATE_HANDLER: HRESULT = 0xC0370001u32 as HRESULT; +pub const ERROR_VID_TOO_MANY_HANDLERS: HRESULT = 0xC0370002u32 as HRESULT; +pub const ERROR_VID_QUEUE_FULL: HRESULT = 0xC0370003u32 as HRESULT; +pub const ERROR_VID_HANDLER_NOT_PRESENT: HRESULT = 0xC0370004u32 as HRESULT; +pub const ERROR_VID_INVALID_OBJECT_NAME: HRESULT = 0xC0370005u32 as HRESULT; +pub const ERROR_VID_PARTITION_NAME_TOO_LONG: HRESULT = 0xC0370006u32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_NAME_TOO_LONG: HRESULT = 0xC0370007u32 as HRESULT; +pub const ERROR_VID_PARTITION_ALREADY_EXISTS: HRESULT = 0xC0370008u32 as HRESULT; +pub const ERROR_VID_PARTITION_DOES_NOT_EXIST: HRESULT = 0xC0370009u32 as HRESULT; +pub const ERROR_VID_PARTITION_NAME_NOT_FOUND: HRESULT = 0xC037000Au32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_ALREADY_EXISTS: HRESULT = 0xC037000Bu32 as HRESULT; +pub const ERROR_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: HRESULT = 0xC037000Cu32 as HRESULT; +pub const ERROR_VID_MB_STILL_REFERENCED: HRESULT = 0xC037000Du32 as HRESULT; +pub const ERROR_VID_CHILD_GPA_PAGE_SET_CORRUPTED: HRESULT = 0xC037000Eu32 as HRESULT; +pub const ERROR_VID_INVALID_NUMA_SETTINGS: HRESULT = 0xC037000Fu32 as HRESULT; +pub const ERROR_VID_INVALID_NUMA_NODE_INDEX: HRESULT = 0xC0370010u32 as HRESULT; +pub const ERROR_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: HRESULT = 0xC0370011u32 as HRESULT; +pub const ERROR_VID_INVALID_MEMORY_BLOCK_HANDLE: HRESULT = 0xC0370012u32 as HRESULT; +pub const ERROR_VID_PAGE_RANGE_OVERFLOW: HRESULT = 0xC0370013u32 as HRESULT; +pub const ERROR_VID_INVALID_MESSAGE_QUEUE_HANDLE: HRESULT = 0xC0370014u32 as HRESULT; +pub const ERROR_VID_INVALID_GPA_RANGE_HANDLE: HRESULT = 0xC0370015u32 as HRESULT; +pub const ERROR_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: HRESULT = 0xC0370016u32 as HRESULT; +pub const ERROR_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: HRESULT = 0xC0370017u32 as HRESULT; +pub const ERROR_VID_INVALID_PPM_HANDLE: HRESULT = 0xC0370018u32 as HRESULT; +pub const ERROR_VID_MBPS_ARE_LOCKED: HRESULT = 0xC0370019u32 as HRESULT; +pub const ERROR_VID_MESSAGE_QUEUE_CLOSED: HRESULT = 0xC037001Au32 as HRESULT; +pub const ERROR_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: HRESULT = 0xC037001Bu32 as HRESULT; +pub const ERROR_VID_STOP_PENDING: HRESULT = 0xC037001Cu32 as HRESULT; +pub const ERROR_VID_INVALID_PROCESSOR_STATE: HRESULT = 0xC037001Du32 as HRESULT; +pub const ERROR_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: HRESULT = 0xC037001Eu32 as HRESULT; +pub const ERROR_VID_KM_INTERFACE_ALREADY_INITIALIZED: HRESULT = 0xC037001Fu32 as HRESULT; +pub const ERROR_VID_MB_PROPERTY_ALREADY_SET_RESET: HRESULT = 0xC0370020u32 as HRESULT; +pub const ERROR_VID_MMIO_RANGE_DESTROYED: HRESULT = 0xC0370021u32 as HRESULT; +pub const ERROR_VID_INVALID_CHILD_GPA_PAGE_SET: HRESULT = 0xC0370022u32 as HRESULT; +pub const ERROR_VID_RESERVE_PAGE_SET_IS_BEING_USED: HRESULT = 0xC0370023u32 as HRESULT; +pub const ERROR_VID_RESERVE_PAGE_SET_TOO_SMALL: HRESULT = 0xC0370024u32 as HRESULT; +pub const ERROR_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: HRESULT = 0xC0370025u32 as HRESULT; +pub const ERROR_VID_MBP_COUNT_EXCEEDED_LIMIT: HRESULT = 0xC0370026u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_CORRUPT: HRESULT = 0xC0370027u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_UNRECOGNIZED_ITEM: HRESULT = 0xC0370028u32 as HRESULT; +pub const ERROR_VID_SAVED_STATE_INCOMPATIBLE: HRESULT = 0xC0370029u32 as HRESULT; +pub const ERROR_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: HRESULT = 0x80370001u32 as HRESULT; +pub const ERROR_VOLMGR_INCOMPLETE_REGENERATION: HRESULT = 0x80380001u32 as HRESULT; +pub const ERROR_VOLMGR_INCOMPLETE_DISK_MIGRATION: HRESULT = 0x80380002u32 as HRESULT; +pub const ERROR_VOLMGR_DATABASE_FULL: HRESULT = 0xC0380001u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONFIGURATION_CORRUPTED: HRESULT = 0xC0380002u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: HRESULT = 0xC0380003u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_UPDATE_FAILED: HRESULT = 0xC0380004u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: HRESULT = 0xC0380005u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_DUPLICATE: HRESULT = 0xC0380006u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_DYNAMIC: HRESULT = 0xC0380007u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_ID_INVALID: HRESULT = 0xC0380008u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_INVALID: HRESULT = 0xC0380009u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAST_VOTER: HRESULT = 0xC038000Au32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_INVALID: HRESULT = 0xC038000Bu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: HRESULT = 0xC038000Cu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: HRESULT = 0xC038000Du32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: HRESULT = 0xC038000Eu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: HRESULT = 0xC038000Fu32 as HRESULT; +pub const ERROR_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: HRESULT = 0xC0380010u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_MISSING: HRESULT = 0xC0380011u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_NOT_EMPTY: HRESULT = 0xC0380012u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_NOT_ENOUGH_SPACE: HRESULT = 0xC0380013u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_REVECTORING_FAILED: HRESULT = 0xC0380014u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_SECTOR_SIZE_INVALID: HRESULT = 0xC0380015u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_SET_NOT_CONTAINED: HRESULT = 0xC0380016u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: HRESULT = 0xC0380017u32 as HRESULT; +pub const ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: HRESULT = 0xC0380018u32 as HRESULT; +pub const ERROR_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: HRESULT = 0xC0380019u32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_ALREADY_USED: HRESULT = 0xC038001Au32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_CONTIGUOUS: HRESULT = 0xC038001Bu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: HRESULT = 0xC038001Cu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: HRESULT = 0xC038001Du32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: HRESULT = 0xC038001Eu32 as HRESULT; +pub const ERROR_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: HRESULT = 0xC038001Fu32 as HRESULT; +pub const ERROR_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: HRESULT = 0xC0380020u32 as HRESULT; +pub const ERROR_VOLMGR_INTERLEAVE_LENGTH_INVALID: HRESULT = 0xC0380021u32 as HRESULT; +pub const ERROR_VOLMGR_MAXIMUM_REGISTERED_USERS: HRESULT = 0xC0380022u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_IN_SYNC: HRESULT = 0xC0380023u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_INDEX_DUPLICATE: HRESULT = 0xC0380024u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_INDEX_INVALID: HRESULT = 0xC0380025u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_MISSING: HRESULT = 0xC0380026u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_NOT_DETACHED: HRESULT = 0xC0380027u32 as HRESULT; +pub const ERROR_VOLMGR_MEMBER_REGENERATING: HRESULT = 0xC0380028u32 as HRESULT; +pub const ERROR_VOLMGR_ALL_DISKS_FAILED: HRESULT = 0xC0380029u32 as HRESULT; +pub const ERROR_VOLMGR_NO_REGISTERED_USERS: HRESULT = 0xC038002Au32 as HRESULT; +pub const ERROR_VOLMGR_NO_SUCH_USER: HRESULT = 0xC038002Bu32 as HRESULT; +pub const ERROR_VOLMGR_NOTIFICATION_RESET: HRESULT = 0xC038002Cu32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_MEMBERS_INVALID: HRESULT = 0xC038002Du32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_PLEXES_INVALID: HRESULT = 0xC038002Eu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_DUPLICATE: HRESULT = 0xC038002Fu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_ID_INVALID: HRESULT = 0xC0380030u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_INVALID: HRESULT = 0xC0380031u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_NAME_INVALID: HRESULT = 0xC0380032u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_OFFLINE: HRESULT = 0xC0380033u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_HAS_QUORUM: HRESULT = 0xC0380034u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_WITHOUT_QUORUM: HRESULT = 0xC0380035u32 as HRESULT; +pub const ERROR_VOLMGR_PARTITION_STYLE_INVALID: HRESULT = 0xC0380036u32 as HRESULT; +pub const ERROR_VOLMGR_PARTITION_UPDATE_FAILED: HRESULT = 0xC0380037u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_IN_SYNC: HRESULT = 0xC0380038u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_INDEX_DUPLICATE: HRESULT = 0xC0380039u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_INDEX_INVALID: HRESULT = 0xC038003Au32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_LAST_ACTIVE: HRESULT = 0xC038003Bu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_MISSING: HRESULT = 0xC038003Cu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_REGENERATING: HRESULT = 0xC038003Du32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_TYPE_INVALID: HRESULT = 0xC038003Eu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_RAID5: HRESULT = 0xC038003Fu32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_SIMPLE: HRESULT = 0xC0380040u32 as HRESULT; +pub const ERROR_VOLMGR_STRUCTURE_SIZE_INVALID: HRESULT = 0xC0380041u32 as HRESULT; +pub const ERROR_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: HRESULT = 0xC0380042u32 as HRESULT; +pub const ERROR_VOLMGR_TRANSACTION_IN_PROGRESS: HRESULT = 0xC0380043u32 as HRESULT; +pub const ERROR_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: HRESULT = 0xC0380044u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: HRESULT = 0xC0380045u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_ID_INVALID: HRESULT = 0xC0380046u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_LENGTH_INVALID: HRESULT = 0xC0380047u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: HRESULT = 0xC0380048u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_NOT_MIRRORED: HRESULT = 0xC0380049u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_NOT_RETAINED: HRESULT = 0xC038004Au32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_OFFLINE: HRESULT = 0xC038004Bu32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_RETAINED: HRESULT = 0xC038004Cu32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_EXTENTS_INVALID: HRESULT = 0xC038004Du32 as HRESULT; +pub const ERROR_VOLMGR_DIFFERENT_SECTOR_SIZE: HRESULT = 0xC038004Eu32 as HRESULT; +pub const ERROR_VOLMGR_BAD_BOOT_DISK: HRESULT = 0xC038004Fu32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_OFFLINE: HRESULT = 0xC0380050u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_CONFIG_ONLINE: HRESULT = 0xC0380051u32 as HRESULT; +pub const ERROR_VOLMGR_NOT_PRIMARY_PACK: HRESULT = 0xC0380052u32 as HRESULT; +pub const ERROR_VOLMGR_PACK_LOG_UPDATE_FAILED: HRESULT = 0xC0380053u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: HRESULT = 0xC0380054u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: HRESULT = 0xC0380055u32 as HRESULT; +pub const ERROR_VOLMGR_VOLUME_MIRRORED: HRESULT = 0xC0380056u32 as HRESULT; +pub const ERROR_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: HRESULT = 0xC0380057u32 as HRESULT; +pub const ERROR_VOLMGR_NO_VALID_LOG_COPIES: HRESULT = 0xC0380058u32 as HRESULT; +pub const ERROR_VOLMGR_PRIMARY_PACK_PRESENT: HRESULT = 0xC0380059u32 as HRESULT; +pub const ERROR_VOLMGR_NUMBER_OF_DISKS_INVALID: HRESULT = 0xC038005Au32 as HRESULT; +pub const ERROR_VOLMGR_MIRROR_NOT_SUPPORTED: HRESULT = 0xC038005Bu32 as HRESULT; +pub const ERROR_VOLMGR_RAID5_NOT_SUPPORTED: HRESULT = 0xC038005Cu32 as HRESULT; +pub const ERROR_BCD_NOT_ALL_ENTRIES_IMPORTED: HRESULT = 0x80390001u32 as HRESULT; +pub const ERROR_BCD_TOO_MANY_ELEMENTS: HRESULT = 0xC0390002u32 as HRESULT; +pub const ERROR_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: HRESULT = 0x80390003u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_MISSING: HRESULT = 0xC03A0001u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: HRESULT = 0xC03A0002u32 as HRESULT; +pub const ERROR_VHD_DRIVE_FOOTER_CORRUPT: HRESULT = 0xC03A0003u32 as HRESULT; +pub const ERROR_VHD_FORMAT_UNKNOWN: HRESULT = 0xC03A0004u32 as HRESULT; +pub const ERROR_VHD_FORMAT_UNSUPPORTED_VERSION: HRESULT = 0xC03A0005u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: HRESULT = 0xC03A0006u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: HRESULT = 0xC03A0007u32 as HRESULT; +pub const ERROR_VHD_SPARSE_HEADER_CORRUPT: HRESULT = 0xC03A0008u32 as HRESULT; +pub const ERROR_VHD_BLOCK_ALLOCATION_FAILURE: HRESULT = 0xC03A0009u32 as HRESULT; +pub const ERROR_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: HRESULT = 0xC03A000Au32 as HRESULT; +pub const ERROR_VHD_INVALID_BLOCK_SIZE: HRESULT = 0xC03A000Bu32 as HRESULT; +pub const ERROR_VHD_BITMAP_MISMATCH: HRESULT = 0xC03A000Cu32 as HRESULT; +pub const ERROR_VHD_PARENT_VHD_NOT_FOUND: HRESULT = 0xC03A000Du32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_ID_MISMATCH: HRESULT = 0xC03A000Eu32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: HRESULT = 0xC03A000Fu32 as HRESULT; +pub const ERROR_VHD_METADATA_READ_FAILURE: HRESULT = 0xC03A0010u32 as HRESULT; +pub const ERROR_VHD_METADATA_WRITE_FAILURE: HRESULT = 0xC03A0011u32 as HRESULT; +pub const ERROR_VHD_INVALID_SIZE: HRESULT = 0xC03A0012u32 as HRESULT; +pub const ERROR_VHD_INVALID_FILE_SIZE: HRESULT = 0xC03A0013u32 as HRESULT; +pub const ERROR_VIRTDISK_PROVIDER_NOT_FOUND: HRESULT = 0xC03A0014u32 as HRESULT; +pub const ERROR_VIRTDISK_NOT_VIRTUAL_DISK: HRESULT = 0xC03A0015u32 as HRESULT; +pub const ERROR_VHD_PARENT_VHD_ACCESS_DENIED: HRESULT = 0xC03A0016u32 as HRESULT; +pub const ERROR_VHD_CHILD_PARENT_SIZE_MISMATCH: HRESULT = 0xC03A0017u32 as HRESULT; +pub const ERROR_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: HRESULT = 0xC03A0018u32 as HRESULT; +pub const ERROR_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: HRESULT = 0xC03A0019u32 as HRESULT; +pub const ERROR_VIRTUAL_DISK_LIMITATION: HRESULT = 0xC03A001Au32 as HRESULT; +pub const ERROR_VHD_INVALID_TYPE: HRESULT = 0xC03A001Bu32 as HRESULT; +pub const ERROR_VHD_INVALID_STATE: HRESULT = 0xC03A001Cu32 as HRESULT; +pub const ERROR_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: HRESULT = 0xC03A001Du32 as HRESULT; +pub const ERROR_VIRTDISK_DISK_ALREADY_OWNED: HRESULT = 0xC03A001Eu32 as HRESULT; +pub const ERROR_VIRTDISK_DISK_ONLINE_AND_WRITABLE: HRESULT = 0xC03A001Fu32 as HRESULT; +pub const ERROR_CTLOG_TRACKING_NOT_INITIALIZED: HRESULT = 0xC03A0020u32 as HRESULT; +pub const ERROR_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: HRESULT = 0xC03A0021u32 as HRESULT; +pub const ERROR_CTLOG_VHD_CHANGED_OFFLINE: HRESULT = 0xC03A0022u32 as HRESULT; +pub const ERROR_CTLOG_INVALID_TRACKING_STATE: HRESULT = 0xC03A0023u32 as HRESULT; +pub const ERROR_CTLOG_INCONSISTENT_TRACKING_FILE: HRESULT = 0xC03A0024u32 as HRESULT; +pub const ERROR_VHD_RESIZE_WOULD_TRUNCATE_DATA: HRESULT = 0xC03A0025u32 as HRESULT; +pub const ERROR_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: HRESULT = 0xC03A0026u32 as HRESULT; +pub const ERROR_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: HRESULT = 0xC03A0027u32 as HRESULT; +pub const ERROR_VHD_METADATA_FULL: HRESULT = 0xC03A0028u32 as HRESULT; +pub const ERROR_QUERY_STORAGE_ERROR: HRESULT = 0x803A0001u32 as HRESULT; +pub const SDIAG_E_CANCELLED: HRESULT = 0x803C0100u32 as HRESULT; +pub const SDIAG_E_SCRIPT: HRESULT = 0x803C0101u32 as HRESULT; +pub const SDIAG_E_POWERSHELL: HRESULT = 0x803C0102u32 as HRESULT; +pub const SDIAG_E_MANAGEDHOST: HRESULT = 0x803C0103u32 as HRESULT; +pub const SDIAG_E_NOVERIFIER: HRESULT = 0x803C0104u32 as HRESULT; +pub const SDIAG_S_CANNOTRUN: HRESULT = 0x003C0105; +pub const SDIAG_E_DISABLED: HRESULT = 0x803C0106u32 as HRESULT; +pub const SDIAG_E_TRUST: HRESULT = 0x803C0107u32 as HRESULT; +pub const SDIAG_E_CANNOTRUN: HRESULT = 0x803C0108u32 as HRESULT; +pub const SDIAG_E_VERSION: HRESULT = 0x803C0109u32 as HRESULT; +pub const SDIAG_E_RESOURCE: HRESULT = 0x803C010Au32 as HRESULT; +pub const SDIAG_E_ROOTCAUSE: HRESULT = 0x803C010Bu32 as HRESULT; +pub const WPN_E_CHANNEL_CLOSED: HRESULT = 0x803E0100u32 as HRESULT; +pub const WPN_E_CHANNEL_REQUEST_NOT_COMPLETE: HRESULT = 0x803E0101u32 as HRESULT; +pub const WPN_E_INVALID_APP: HRESULT = 0x803E0102u32 as HRESULT; +pub const WPN_E_OUTSTANDING_CHANNEL_REQUEST: HRESULT = 0x803E0103u32 as HRESULT; +pub const WPN_E_DUPLICATE_CHANNEL: HRESULT = 0x803E0104u32 as HRESULT; +pub const WPN_E_PLATFORM_UNAVAILABLE: HRESULT = 0x803E0105u32 as HRESULT; +pub const WPN_E_NOTIFICATION_POSTED: HRESULT = 0x803E0106u32 as HRESULT; +pub const WPN_E_NOTIFICATION_HIDDEN: HRESULT = 0x803E0107u32 as HRESULT; +pub const WPN_E_NOTIFICATION_NOT_POSTED: HRESULT = 0x803E0108u32 as HRESULT; +pub const WPN_E_CLOUD_DISABLED: HRESULT = 0x803E0109u32 as HRESULT; +pub const WPN_E_CLOUD_INCAPABLE: HRESULT = 0x803E0110u32 as HRESULT; +pub const WPN_E_CLOUD_AUTH_UNAVAILABLE: HRESULT = 0x803E011Au32 as HRESULT; +pub const WPN_E_CLOUD_SERVICE_UNAVAILABLE: HRESULT = 0x803E011Bu32 as HRESULT; +pub const WPN_E_FAILED_LOCK_SCREEN_UPDATE_INTIALIZATION: HRESULT = 0x803E011Cu32 as HRESULT; +pub const WPN_E_NOTIFICATION_DISABLED: HRESULT = 0x803E0111u32 as HRESULT; +pub const WPN_E_NOTIFICATION_INCAPABLE: HRESULT = 0x803E0112u32 as HRESULT; +pub const WPN_E_INTERNET_INCAPABLE: HRESULT = 0x803E0113u32 as HRESULT; +pub const WPN_E_NOTIFICATION_TYPE_DISABLED: HRESULT = 0x803E0114u32 as HRESULT; +pub const WPN_E_NOTIFICATION_SIZE: HRESULT = 0x803E0115u32 as HRESULT; +pub const WPN_E_TAG_SIZE: HRESULT = 0x803E0116u32 as HRESULT; +pub const WPN_E_ACCESS_DENIED: HRESULT = 0x803E0117u32 as HRESULT; +pub const WPN_E_DUPLICATE_REGISTRATION: HRESULT = 0x803E0118u32 as HRESULT; +pub const WPN_E_PUSH_NOTIFICATION_INCAPABLE: HRESULT = 0x803E0119u32 as HRESULT; +pub const WPN_E_DEV_ID_SIZE: HRESULT = 0x803E0120u32 as HRESULT; +pub const WPN_E_TAG_ALPHANUMERIC: HRESULT = 0x803E012Au32 as HRESULT; +pub const WPN_E_INVALID_HTTP_STATUS_CODE: HRESULT = 0x803E012Bu32 as HRESULT; +pub const WPN_E_OUT_OF_SESSION: HRESULT = 0x803E0200u32 as HRESULT; +pub const WPN_E_POWER_SAVE: HRESULT = 0x803E0201u32 as HRESULT; +pub const WPN_E_IMAGE_NOT_FOUND_IN_CACHE: HRESULT = 0x803E0202u32 as HRESULT; +pub const WPN_E_ALL_URL_NOT_COMPLETED: HRESULT = 0x803E0203u32 as HRESULT; +pub const WPN_E_INVALID_CLOUD_IMAGE: HRESULT = 0x803E0204u32 as HRESULT; +pub const WPN_E_NOTIFICATION_ID_MATCHED: HRESULT = 0x803E0205u32 as HRESULT; +pub const WPN_E_CALLBACK_ALREADY_REGISTERED: HRESULT = 0x803E0206u32 as HRESULT; +pub const WPN_E_TOAST_NOTIFICATION_DROPPED: HRESULT = 0x803E0207u32 as HRESULT; +pub const WPN_E_STORAGE_LOCKED: HRESULT = 0x803E0208u32 as HRESULT; +pub const E_MBN_CONTEXT_NOT_ACTIVATED: HRESULT = 0x80548201u32 as HRESULT; +pub const E_MBN_BAD_SIM: HRESULT = 0x80548202u32 as HRESULT; +pub const E_MBN_DATA_CLASS_NOT_AVAILABLE: HRESULT = 0x80548203u32 as HRESULT; +pub const E_MBN_INVALID_ACCESS_STRING: HRESULT = 0x80548204u32 as HRESULT; +pub const E_MBN_MAX_ACTIVATED_CONTEXTS: HRESULT = 0x80548205u32 as HRESULT; +pub const E_MBN_PACKET_SVC_DETACHED: HRESULT = 0x80548206u32 as HRESULT; +pub const E_MBN_PROVIDER_NOT_VISIBLE: HRESULT = 0x80548207u32 as HRESULT; +pub const E_MBN_RADIO_POWER_OFF: HRESULT = 0x80548208u32 as HRESULT; +pub const E_MBN_SERVICE_NOT_ACTIVATED: HRESULT = 0x80548209u32 as HRESULT; +pub const E_MBN_SIM_NOT_INSERTED: HRESULT = 0x8054820Au32 as HRESULT; +pub const E_MBN_VOICE_CALL_IN_PROGRESS: HRESULT = 0x8054820Bu32 as HRESULT; +pub const E_MBN_INVALID_CACHE: HRESULT = 0x8054820Cu32 as HRESULT; +pub const E_MBN_NOT_REGISTERED: HRESULT = 0x8054820Du32 as HRESULT; +pub const E_MBN_PROVIDERS_NOT_FOUND: HRESULT = 0x8054820Eu32 as HRESULT; +pub const E_MBN_PIN_NOT_SUPPORTED: HRESULT = 0x8054820Fu32 as HRESULT; +pub const E_MBN_PIN_REQUIRED: HRESULT = 0x80548210u32 as HRESULT; +pub const E_MBN_PIN_DISABLED: HRESULT = 0x80548211u32 as HRESULT; +pub const E_MBN_FAILURE: HRESULT = 0x80548212u32 as HRESULT; +pub const E_MBN_INVALID_PROFILE: HRESULT = 0x80548218u32 as HRESULT; +pub const E_MBN_DEFAULT_PROFILE_EXIST: HRESULT = 0x80548219u32 as HRESULT; +pub const E_MBN_SMS_ENCODING_NOT_SUPPORTED: HRESULT = 0x80548220u32 as HRESULT; +pub const E_MBN_SMS_FILTER_NOT_SUPPORTED: HRESULT = 0x80548221u32 as HRESULT; +pub const E_MBN_SMS_INVALID_MEMORY_INDEX: HRESULT = 0x80548222u32 as HRESULT; +pub const E_MBN_SMS_LANG_NOT_SUPPORTED: HRESULT = 0x80548223u32 as HRESULT; +pub const E_MBN_SMS_MEMORY_FAILURE: HRESULT = 0x80548224u32 as HRESULT; +pub const E_MBN_SMS_NETWORK_TIMEOUT: HRESULT = 0x80548225u32 as HRESULT; +pub const E_MBN_SMS_UNKNOWN_SMSC_ADDRESS: HRESULT = 0x80548226u32 as HRESULT; +pub const E_MBN_SMS_FORMAT_NOT_SUPPORTED: HRESULT = 0x80548227u32 as HRESULT; +pub const E_MBN_SMS_OPERATION_NOT_ALLOWED: HRESULT = 0x80548228u32 as HRESULT; +pub const E_MBN_SMS_MEMORY_FULL: HRESULT = 0x80548229u32 as HRESULT; +pub const PEER_E_IPV6_NOT_INSTALLED: HRESULT = 0x80630001u32 as HRESULT; +pub const PEER_E_NOT_INITIALIZED: HRESULT = 0x80630002u32 as HRESULT; +pub const PEER_E_CANNOT_START_SERVICE: HRESULT = 0x80630003u32 as HRESULT; +pub const PEER_E_NOT_LICENSED: HRESULT = 0x80630004u32 as HRESULT; +pub const PEER_E_INVALID_GRAPH: HRESULT = 0x80630010u32 as HRESULT; +pub const PEER_E_DBNAME_CHANGED: HRESULT = 0x80630011u32 as HRESULT; +pub const PEER_E_DUPLICATE_GRAPH: HRESULT = 0x80630012u32 as HRESULT; +pub const PEER_E_GRAPH_NOT_READY: HRESULT = 0x80630013u32 as HRESULT; +pub const PEER_E_GRAPH_SHUTTING_DOWN: HRESULT = 0x80630014u32 as HRESULT; +pub const PEER_E_GRAPH_IN_USE: HRESULT = 0x80630015u32 as HRESULT; +pub const PEER_E_INVALID_DATABASE: HRESULT = 0x80630016u32 as HRESULT; +pub const PEER_E_TOO_MANY_ATTRIBUTES: HRESULT = 0x80630017u32 as HRESULT; +pub const PEER_E_CONNECTION_NOT_FOUND: HRESULT = 0x80630103u32 as HRESULT; +pub const PEER_E_CONNECT_SELF: HRESULT = 0x80630106u32 as HRESULT; +pub const PEER_E_ALREADY_LISTENING: HRESULT = 0x80630107u32 as HRESULT; +pub const PEER_E_NODE_NOT_FOUND: HRESULT = 0x80630108u32 as HRESULT; +pub const PEER_E_CONNECTION_FAILED: HRESULT = 0x80630109u32 as HRESULT; +pub const PEER_E_CONNECTION_NOT_AUTHENTICATED: HRESULT = 0x8063010Au32 as HRESULT; +pub const PEER_E_CONNECTION_REFUSED: HRESULT = 0x8063010Bu32 as HRESULT; +pub const PEER_E_CLASSIFIER_TOO_LONG: HRESULT = 0x80630201u32 as HRESULT; +pub const PEER_E_TOO_MANY_IDENTITIES: HRESULT = 0x80630202u32 as HRESULT; +pub const PEER_E_NO_KEY_ACCESS: HRESULT = 0x80630203u32 as HRESULT; +pub const PEER_E_GROUPS_EXIST: HRESULT = 0x80630204u32 as HRESULT; +pub const PEER_E_RECORD_NOT_FOUND: HRESULT = 0x80630301u32 as HRESULT; +pub const PEER_E_DATABASE_ACCESSDENIED: HRESULT = 0x80630302u32 as HRESULT; +pub const PEER_E_DBINITIALIZATION_FAILED: HRESULT = 0x80630303u32 as HRESULT; +pub const PEER_E_MAX_RECORD_SIZE_EXCEEDED: HRESULT = 0x80630304u32 as HRESULT; +pub const PEER_E_DATABASE_ALREADY_PRESENT: HRESULT = 0x80630305u32 as HRESULT; +pub const PEER_E_DATABASE_NOT_PRESENT: HRESULT = 0x80630306u32 as HRESULT; +pub const PEER_E_IDENTITY_NOT_FOUND: HRESULT = 0x80630401u32 as HRESULT; +pub const PEER_E_EVENT_HANDLE_NOT_FOUND: HRESULT = 0x80630501u32 as HRESULT; +pub const PEER_E_INVALID_SEARCH: HRESULT = 0x80630601u32 as HRESULT; +pub const PEER_E_INVALID_ATTRIBUTES: HRESULT = 0x80630602u32 as HRESULT; +pub const PEER_E_INVITATION_NOT_TRUSTED: HRESULT = 0x80630701u32 as HRESULT; +pub const PEER_E_CHAIN_TOO_LONG: HRESULT = 0x80630703u32 as HRESULT; +pub const PEER_E_INVALID_TIME_PERIOD: HRESULT = 0x80630705u32 as HRESULT; +pub const PEER_E_CIRCULAR_CHAIN_DETECTED: HRESULT = 0x80630706u32 as HRESULT; +pub const PEER_E_CERT_STORE_CORRUPTED: HRESULT = 0x80630801u32 as HRESULT; +pub const PEER_E_NO_CLOUD: HRESULT = 0x80631001u32 as HRESULT; +pub const PEER_E_CLOUD_NAME_AMBIGUOUS: HRESULT = 0x80631005u32 as HRESULT; +pub const PEER_E_INVALID_RECORD: HRESULT = 0x80632010u32 as HRESULT; +pub const PEER_E_NOT_AUTHORIZED: HRESULT = 0x80632020u32 as HRESULT; +pub const PEER_E_PASSWORD_DOES_NOT_MEET_POLICY: HRESULT = 0x80632021u32 as HRESULT; +pub const PEER_E_DEFERRED_VALIDATION: HRESULT = 0x80632030u32 as HRESULT; +pub const PEER_E_INVALID_GROUP_PROPERTIES: HRESULT = 0x80632040u32 as HRESULT; +pub const PEER_E_INVALID_PEER_NAME: HRESULT = 0x80632050u32 as HRESULT; +pub const PEER_E_INVALID_CLASSIFIER: HRESULT = 0x80632060u32 as HRESULT; +pub const PEER_E_INVALID_FRIENDLY_NAME: HRESULT = 0x80632070u32 as HRESULT; +pub const PEER_E_INVALID_ROLE_PROPERTY: HRESULT = 0x80632071u32 as HRESULT; +pub const PEER_E_INVALID_CLASSIFIER_PROPERTY: HRESULT = 0x80632072u32 as HRESULT; +pub const PEER_E_INVALID_RECORD_EXPIRATION: HRESULT = 0x80632080u32 as HRESULT; +pub const PEER_E_INVALID_CREDENTIAL_INFO: HRESULT = 0x80632081u32 as HRESULT; +pub const PEER_E_INVALID_CREDENTIAL: HRESULT = 0x80632082u32 as HRESULT; +pub const PEER_E_INVALID_RECORD_SIZE: HRESULT = 0x80632083u32 as HRESULT; +pub const PEER_E_UNSUPPORTED_VERSION: HRESULT = 0x80632090u32 as HRESULT; +pub const PEER_E_GROUP_NOT_READY: HRESULT = 0x80632091u32 as HRESULT; +pub const PEER_E_GROUP_IN_USE: HRESULT = 0x80632092u32 as HRESULT; +pub const PEER_E_INVALID_GROUP: HRESULT = 0x80632093u32 as HRESULT; +pub const PEER_E_NO_MEMBERS_FOUND: HRESULT = 0x80632094u32 as HRESULT; +pub const PEER_E_NO_MEMBER_CONNECTIONS: HRESULT = 0x80632095u32 as HRESULT; +pub const PEER_E_UNABLE_TO_LISTEN: HRESULT = 0x80632096u32 as HRESULT; +pub const PEER_E_IDENTITY_DELETED: HRESULT = 0x806320A0u32 as HRESULT; +pub const PEER_E_SERVICE_NOT_AVAILABLE: HRESULT = 0x806320A1u32 as HRESULT; +pub const PEER_E_CONTACT_NOT_FOUND: HRESULT = 0x80636001u32 as HRESULT; +pub const PEER_S_GRAPH_DATA_CREATED: HRESULT = 0x00630001; +pub const PEER_S_NO_EVENT_DATA: HRESULT = 0x00630002; +pub const PEER_S_ALREADY_CONNECTED: HRESULT = 0x00632000; +pub const PEER_S_SUBSCRIPTION_EXISTS: HRESULT = 0x00636000; +pub const PEER_S_NO_CONNECTIVITY: HRESULT = 0x00630005; +pub const PEER_S_ALREADY_A_MEMBER: HRESULT = 0x00630006; +pub const PEER_E_CANNOT_CONVERT_PEER_NAME: HRESULT = 0x80634001u32 as HRESULT; +pub const PEER_E_INVALID_PEER_HOST_NAME: HRESULT = 0x80634002u32 as HRESULT; +pub const PEER_E_NO_MORE: HRESULT = 0x80634003u32 as HRESULT; +pub const PEER_E_PNRP_DUPLICATE_PEER_NAME: HRESULT = 0x80634005u32 as HRESULT; +pub const PEER_E_INVITE_CANCELLED: HRESULT = 0x80637000u32 as HRESULT; +pub const PEER_E_INVITE_RESPONSE_NOT_AVAILABLE: HRESULT = 0x80637001u32 as HRESULT; +pub const PEER_E_NOT_SIGNED_IN: HRESULT = 0x80637003u32 as HRESULT; +pub const PEER_E_PRIVACY_DECLINED: HRESULT = 0x80637004u32 as HRESULT; +pub const PEER_E_TIMEOUT: HRESULT = 0x80637005u32 as HRESULT; +pub const PEER_E_INVALID_ADDRESS: HRESULT = 0x80637007u32 as HRESULT; +pub const PEER_E_FW_EXCEPTION_DISABLED: HRESULT = 0x80637008u32 as HRESULT; +pub const PEER_E_FW_BLOCKED_BY_POLICY: HRESULT = 0x80637009u32 as HRESULT; +pub const PEER_E_FW_BLOCKED_BY_SHIELDS_UP: HRESULT = 0x8063700Au32 as HRESULT; +pub const PEER_E_FW_DECLINED: HRESULT = 0x8063700Bu32 as HRESULT; +pub const UI_E_CREATE_FAILED: HRESULT = 0x802A0001u32 as HRESULT; +pub const UI_E_SHUTDOWN_CALLED: HRESULT = 0x802A0002u32 as HRESULT; +pub const UI_E_ILLEGAL_REENTRANCY: HRESULT = 0x802A0003u32 as HRESULT; +pub const UI_E_OBJECT_SEALED: HRESULT = 0x802A0004u32 as HRESULT; +pub const UI_E_VALUE_NOT_SET: HRESULT = 0x802A0005u32 as HRESULT; +pub const UI_E_VALUE_NOT_DETERMINED: HRESULT = 0x802A0006u32 as HRESULT; +pub const UI_E_INVALID_OUTPUT: HRESULT = 0x802A0007u32 as HRESULT; +pub const UI_E_BOOLEAN_EXPECTED: HRESULT = 0x802A0008u32 as HRESULT; +pub const UI_E_DIFFERENT_OWNER: HRESULT = 0x802A0009u32 as HRESULT; +pub const UI_E_AMBIGUOUS_MATCH: HRESULT = 0x802A000Au32 as HRESULT; +pub const UI_E_FP_OVERFLOW: HRESULT = 0x802A000Bu32 as HRESULT; +pub const UI_E_WRONG_THREAD: HRESULT = 0x802A000Cu32 as HRESULT; +pub const UI_E_STORYBOARD_ACTIVE: HRESULT = 0x802A0101u32 as HRESULT; +pub const UI_E_STORYBOARD_NOT_PLAYING: HRESULT = 0x802A0102u32 as HRESULT; +pub const UI_E_START_KEYFRAME_AFTER_END: HRESULT = 0x802A0103u32 as HRESULT; +pub const UI_E_END_KEYFRAME_NOT_DETERMINED: HRESULT = 0x802A0104u32 as HRESULT; +pub const UI_E_LOOPS_OVERLAP: HRESULT = 0x802A0105u32 as HRESULT; +pub const UI_E_TRANSITION_ALREADY_USED: HRESULT = 0x802A0106u32 as HRESULT; +pub const UI_E_TRANSITION_NOT_IN_STORYBOARD: HRESULT = 0x802A0107u32 as HRESULT; +pub const UI_E_TRANSITION_ECLIPSED: HRESULT = 0x802A0108u32 as HRESULT; +pub const UI_E_TIME_BEFORE_LAST_UPDATE: HRESULT = 0x802A0109u32 as HRESULT; +pub const UI_E_TIMER_CLIENT_ALREADY_CONNECTED: HRESULT = 0x802A010Au32 as HRESULT; +pub const UI_E_INVALID_DIMENSION: HRESULT = 0x802A010Bu32 as HRESULT; +pub const UI_E_PRIMITIVE_OUT_OF_BOUNDS: HRESULT = 0x802A010Cu32 as HRESULT; +pub const UI_E_WINDOW_CLOSED: HRESULT = 0x802A0201u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_HANDLE: HRESULT = 0x80650001u32 as HRESULT; +pub const E_BLUETOOTH_ATT_READ_NOT_PERMITTED: HRESULT = 0x80650002u32 as HRESULT; +pub const E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED: HRESULT = 0x80650003u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_PDU: HRESULT = 0x80650004u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_AUTHENTICATION: HRESULT = 0x80650005u32 as HRESULT; +pub const E_BLUETOOTH_ATT_REQUEST_NOT_SUPPORTED: HRESULT = 0x80650006u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_OFFSET: HRESULT = 0x80650007u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_AUTHORIZATION: HRESULT = 0x80650008u32 as HRESULT; +pub const E_BLUETOOTH_ATT_PREPARE_QUEUE_FULL: HRESULT = 0x80650009u32 as HRESULT; +pub const E_BLUETOOTH_ATT_ATTRIBUTE_NOT_FOUND: HRESULT = 0x8065000Au32 as HRESULT; +pub const E_BLUETOOTH_ATT_ATTRIBUTE_NOT_LONG: HRESULT = 0x8065000Bu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: HRESULT = 0x8065000Cu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: HRESULT = 0x8065000Du32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNLIKELY: HRESULT = 0x8065000Eu32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION: HRESULT = 0x8065000Fu32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNSUPPORTED_GROUP_TYPE: HRESULT = 0x80650010u32 as HRESULT; +pub const E_BLUETOOTH_ATT_INSUFFICIENT_RESOURCES: HRESULT = 0x80650011u32 as HRESULT; +pub const E_BLUETOOTH_ATT_UNKNOWN_ERROR: HRESULT = 0x80651000u32 as HRESULT; +pub const E_AUDIO_ENGINE_NODE_NOT_FOUND: HRESULT = 0x80660001u32 as HRESULT; +pub const E_HDAUDIO_EMPTY_CONNECTION_LIST: HRESULT = 0x80660002u32 as HRESULT; +pub const E_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: HRESULT = 0x80660003u32 as HRESULT; +pub const E_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: HRESULT = 0x80660004u32 as HRESULT; +pub const E_HDAUDIO_NULL_LINKED_LIST_ENTRY: HRESULT = 0x80660005u32 as HRESULT; +pub const ERROR_SPACES_POOL_WAS_DELETED: HRESULT = 0x00E70001; +pub const ERROR_SPACES_RESILIENCY_TYPE_INVALID: HRESULT = 0x80E70003u32 as HRESULT; +pub const ERROR_SPACES_DRIVE_SECTOR_SIZE_INVALID: HRESULT = 0x80E70004u32 as HRESULT; +pub const ERROR_SPACES_DRIVE_REDUNDANCY_INVALID: HRESULT = 0x80E70006u32 as HRESULT; +pub const ERROR_SPACES_NUMBER_OF_DATA_COPIES_INVALID: HRESULT = 0x80E70007u32 as HRESULT; +pub const ERROR_SPACES_PARITY_LAYOUT_INVALID: HRESULT = 0x80E70008u32 as HRESULT; +pub const ERROR_SPACES_INTERLEAVE_LENGTH_INVALID: HRESULT = 0x80E70009u32 as HRESULT; +pub const ERROR_SPACES_NUMBER_OF_COLUMNS_INVALID: HRESULT = 0x80E7000Au32 as HRESULT; +pub const ERROR_SPACES_NOT_ENOUGH_DRIVES: HRESULT = 0x80E7000Bu32 as HRESULT; +pub const ERROR_VOLSNAP_BOOTFILE_NOT_VALID: HRESULT = 0x80820001u32 as HRESULT; +pub const ERROR_TIERING_NOT_SUPPORTED_ON_VOLUME: HRESULT = 0x80830001u32 as HRESULT; +pub const ERROR_TIERING_VOLUME_DISMOUNT_IN_PROGRESS: HRESULT = 0x80830002u32 as HRESULT; +pub const ERROR_TIERING_STORAGE_TIER_NOT_FOUND: HRESULT = 0x80830003u32 as HRESULT; +pub const ERROR_TIERING_INVALID_FILE_ID: HRESULT = 0x80830004u32 as HRESULT; +pub const ERROR_TIERING_WRONG_CLUSTER_NODE: HRESULT = 0x80830005u32 as HRESULT; +pub const ERROR_TIERING_ALREADY_PROCESSING: HRESULT = 0x80830006u32 as HRESULT; +pub const ERROR_TIERING_CANNOT_PIN_OBJECT: HRESULT = 0x80830007u32 as HRESULT; +pub const DXGI_STATUS_OCCLUDED: HRESULT = 0x087A0001; +pub const DXGI_STATUS_CLIPPED: HRESULT = 0x087A0002; +pub const DXGI_STATUS_NO_REDIRECTION: HRESULT = 0x087A0004; +pub const DXGI_STATUS_NO_DESKTOP_ACCESS: HRESULT = 0x087A0005; +pub const DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0x087A0006; +pub const DXGI_STATUS_MODE_CHANGED: HRESULT = 0x087A0007; +pub const DXGI_STATUS_MODE_CHANGE_IN_PROGRESS: HRESULT = 0x087A0008; +pub const DXGI_ERROR_INVALID_CALL: HRESULT = 0x887A0001u32 as HRESULT; +pub const DXGI_ERROR_NOT_FOUND: HRESULT = 0x887A0002u32 as HRESULT; +pub const DXGI_ERROR_MORE_DATA: HRESULT = 0x887A0003u32 as HRESULT; +pub const DXGI_ERROR_UNSUPPORTED: HRESULT = 0x887A0004u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_REMOVED: HRESULT = 0x887A0005u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_HUNG: HRESULT = 0x887A0006u32 as HRESULT; +pub const DXGI_ERROR_DEVICE_RESET: HRESULT = 0x887A0007u32 as HRESULT; +pub const DXGI_ERROR_WAS_STILL_DRAWING: HRESULT = 0x887A000Au32 as HRESULT; +pub const DXGI_ERROR_FRAME_STATISTICS_DISJOINT: HRESULT = 0x887A000Bu32 as HRESULT; +pub const DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: HRESULT = 0x887A000Cu32 as HRESULT; +pub const DXGI_ERROR_DRIVER_INTERNAL_ERROR: HRESULT = 0x887A0020u32 as HRESULT; +pub const DXGI_ERROR_NONEXCLUSIVE: HRESULT = 0x887A0021u32 as HRESULT; +pub const DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: HRESULT = 0x887A0022u32 as HRESULT; +pub const DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED: HRESULT = 0x887A0023u32 as HRESULT; +pub const DXGI_ERROR_REMOTE_OUTOFMEMORY: HRESULT = 0x887A0024u32 as HRESULT; +pub const DXGI_ERROR_ACCESS_LOST: HRESULT = 0x887A0026u32 as HRESULT; +pub const DXGI_ERROR_WAIT_TIMEOUT: HRESULT = 0x887A0027u32 as HRESULT; +pub const DXGI_ERROR_SESSION_DISCONNECTED: HRESULT = 0x887A0028u32 as HRESULT; +pub const DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE: HRESULT = 0x887A0029u32 as HRESULT; +pub const DXGI_ERROR_CANNOT_PROTECT_CONTENT: HRESULT = 0x887A002Au32 as HRESULT; +pub const DXGI_ERROR_ACCESS_DENIED: HRESULT = 0x887A002Bu32 as HRESULT; +pub const DXGI_ERROR_NAME_ALREADY_EXISTS: HRESULT = 0x887A002Cu32 as HRESULT; +pub const DXGI_ERROR_SDK_COMPONENT_MISSING: HRESULT = 0x887A002Du32 as HRESULT; +pub const DXGI_STATUS_UNOCCLUDED: HRESULT = 0x087A0009; +pub const DXGI_STATUS_DDA_WAS_STILL_DRAWING: HRESULT = 0x087A000A; +pub const DXGI_ERROR_MODE_CHANGE_IN_PROGRESS: HRESULT = 0x887A0025u32 as HRESULT; +pub const DXGI_DDI_ERR_WASSTILLDRAWING: HRESULT = 0x887B0001u32 as HRESULT; +pub const DXGI_DDI_ERR_UNSUPPORTED: HRESULT = 0x887B0002u32 as HRESULT; +pub const DXGI_DDI_ERR_NONEXCLUSIVE: HRESULT = 0x887B0003u32 as HRESULT; +pub const D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: HRESULT = 0x88790001u32 as HRESULT; +pub const D3D10_ERROR_FILE_NOT_FOUND: HRESULT = 0x88790002u32 as HRESULT; +pub const D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: HRESULT = 0x887C0001u32 as HRESULT; +pub const D3D11_ERROR_FILE_NOT_FOUND: HRESULT = 0x887C0002u32 as HRESULT; +pub const D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS: HRESULT = 0x887C0003u32 as HRESULT; +pub const D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD: HRESULT = 0x887C0004u32 as HRESULT; +pub const D2DERR_WRONG_STATE: HRESULT = 0x88990001u32 as HRESULT; +pub const D2DERR_NOT_INITIALIZED: HRESULT = 0x88990002u32 as HRESULT; +pub const D2DERR_UNSUPPORTED_OPERATION: HRESULT = 0x88990003u32 as HRESULT; +pub const D2DERR_SCANNER_FAILED: HRESULT = 0x88990004u32 as HRESULT; +pub const D2DERR_SCREEN_ACCESS_DENIED: HRESULT = 0x88990005u32 as HRESULT; +pub const D2DERR_DISPLAY_STATE_INVALID: HRESULT = 0x88990006u32 as HRESULT; +pub const D2DERR_ZERO_VECTOR: HRESULT = 0x88990007u32 as HRESULT; +pub const D2DERR_INTERNAL_ERROR: HRESULT = 0x88990008u32 as HRESULT; +pub const D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED: HRESULT = 0x88990009u32 as HRESULT; +pub const D2DERR_INVALID_CALL: HRESULT = 0x8899000Au32 as HRESULT; +pub const D2DERR_NO_HARDWARE_DEVICE: HRESULT = 0x8899000Bu32 as HRESULT; +pub const D2DERR_RECREATE_TARGET: HRESULT = 0x8899000Cu32 as HRESULT; +pub const D2DERR_TOO_MANY_SHADER_ELEMENTS: HRESULT = 0x8899000Du32 as HRESULT; +pub const D2DERR_SHADER_COMPILE_FAILED: HRESULT = 0x8899000Eu32 as HRESULT; +pub const D2DERR_MAX_TEXTURE_SIZE_EXCEEDED: HRESULT = 0x8899000Fu32 as HRESULT; +pub const D2DERR_UNSUPPORTED_VERSION: HRESULT = 0x88990010u32 as HRESULT; +pub const D2DERR_BAD_NUMBER: HRESULT = 0x88990011u32 as HRESULT; +pub const D2DERR_WRONG_FACTORY: HRESULT = 0x88990012u32 as HRESULT; +pub const D2DERR_LAYER_ALREADY_IN_USE: HRESULT = 0x88990013u32 as HRESULT; +pub const D2DERR_POP_CALL_DID_NOT_MATCH_PUSH: HRESULT = 0x88990014u32 as HRESULT; +pub const D2DERR_WRONG_RESOURCE_DOMAIN: HRESULT = 0x88990015u32 as HRESULT; +pub const D2DERR_PUSH_POP_UNBALANCED: HRESULT = 0x88990016u32 as HRESULT; +pub const D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT: HRESULT = 0x88990017u32 as HRESULT; +pub const D2DERR_INCOMPATIBLE_BRUSH_TYPES: HRESULT = 0x88990018u32 as HRESULT; +pub const D2DERR_WIN32_ERROR: HRESULT = 0x88990019u32 as HRESULT; +pub const D2DERR_TARGET_NOT_GDI_COMPATIBLE: HRESULT = 0x8899001Au32 as HRESULT; +pub const D2DERR_TEXT_EFFECT_IS_WRONG_TYPE: HRESULT = 0x8899001Bu32 as HRESULT; +pub const D2DERR_TEXT_RENDERER_NOT_RELEASED: HRESULT = 0x8899001Cu32 as HRESULT; +pub const D2DERR_EXCEEDS_MAX_BITMAP_SIZE: HRESULT = 0x8899001Du32 as HRESULT; +pub const D2DERR_INVALID_GRAPH_CONFIGURATION: HRESULT = 0x8899001Eu32 as HRESULT; +pub const D2DERR_INVALID_INTERNAL_GRAPH_CONFIGURATION: HRESULT = 0x8899001Fu32 as HRESULT; +pub const D2DERR_CYCLIC_GRAPH: HRESULT = 0x88990020u32 as HRESULT; +pub const D2DERR_BITMAP_CANNOT_DRAW: HRESULT = 0x88990021u32 as HRESULT; +pub const D2DERR_OUTSTANDING_BITMAP_REFERENCES: HRESULT = 0x88990022u32 as HRESULT; +pub const D2DERR_ORIGINAL_TARGET_NOT_BOUND: HRESULT = 0x88990023u32 as HRESULT; +pub const D2DERR_INVALID_TARGET: HRESULT = 0x88990024u32 as HRESULT; +pub const D2DERR_BITMAP_BOUND_AS_TARGET: HRESULT = 0x88990025u32 as HRESULT; +pub const D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES: HRESULT = 0x88990026u32 as HRESULT; +pub const D2DERR_INTERMEDIATE_TOO_LARGE: HRESULT = 0x88990027u32 as HRESULT; +pub const D2DERR_EFFECT_IS_NOT_REGISTERED: HRESULT = 0x88990028u32 as HRESULT; +pub const D2DERR_INVALID_PROPERTY: HRESULT = 0x88990029u32 as HRESULT; +pub const D2DERR_NO_SUBPROPERTIES: HRESULT = 0x8899002Au32 as HRESULT; +pub const D2DERR_PRINT_JOB_CLOSED: HRESULT = 0x8899002Bu32 as HRESULT; +pub const D2DERR_PRINT_FORMAT_NOT_SUPPORTED: HRESULT = 0x8899002Cu32 as HRESULT; +pub const D2DERR_TOO_MANY_TRANSFORM_INPUTS: HRESULT = 0x8899002Du32 as HRESULT; +pub const DWRITE_E_FILEFORMAT: HRESULT = 0x88985000u32 as HRESULT; +pub const DWRITE_E_UNEXPECTED: HRESULT = 0x88985001u32 as HRESULT; +pub const DWRITE_E_NOFONT: HRESULT = 0x88985002u32 as HRESULT; +pub const DWRITE_E_FILENOTFOUND: HRESULT = 0x88985003u32 as HRESULT; +pub const DWRITE_E_FILEACCESS: HRESULT = 0x88985004u32 as HRESULT; +pub const DWRITE_E_FONTCOLLECTIONOBSOLETE: HRESULT = 0x88985005u32 as HRESULT; +pub const DWRITE_E_ALREADYREGISTERED: HRESULT = 0x88985006u32 as HRESULT; +pub const DWRITE_E_CACHEFORMAT: HRESULT = 0x88985007u32 as HRESULT; +pub const DWRITE_E_CACHEVERSION: HRESULT = 0x88985008u32 as HRESULT; +pub const DWRITE_E_UNSUPPORTEDOPERATION: HRESULT = 0x88985009u32 as HRESULT; +pub const DWRITE_E_TEXTRENDERERINCOMPATIBLE: HRESULT = 0x8898500Au32 as HRESULT; +pub const DWRITE_E_FLOWDIRECTIONCONFLICTS: HRESULT = 0x8898500Bu32 as HRESULT; +pub const DWRITE_E_NOCOLOR: HRESULT = 0x8898500Cu32 as HRESULT; +pub const WINCODEC_ERR_WRONGSTATE: HRESULT = 0x88982F04u32 as HRESULT; +pub const WINCODEC_ERR_VALUEOUTOFRANGE: HRESULT = 0x88982F05u32 as HRESULT; +pub const WINCODEC_ERR_UNKNOWNIMAGEFORMAT: HRESULT = 0x88982F07u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDVERSION: HRESULT = 0x88982F0Bu32 as HRESULT; +pub const WINCODEC_ERR_NOTINITIALIZED: HRESULT = 0x88982F0Cu32 as HRESULT; +pub const WINCODEC_ERR_ALREADYLOCKED: HRESULT = 0x88982F0Du32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYNOTFOUND: HRESULT = 0x88982F40u32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYNOTSUPPORTED: HRESULT = 0x88982F41u32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYSIZE: HRESULT = 0x88982F42u32 as HRESULT; +pub const WINCODEC_ERR_CODECPRESENT: HRESULT = 0x88982F43u32 as HRESULT; +pub const WINCODEC_ERR_CODECNOTHUMBNAIL: HRESULT = 0x88982F44u32 as HRESULT; +pub const WINCODEC_ERR_PALETTEUNAVAILABLE: HRESULT = 0x88982F45u32 as HRESULT; +pub const WINCODEC_ERR_CODECTOOMANYSCANLINES: HRESULT = 0x88982F46u32 as HRESULT; +pub const WINCODEC_ERR_INTERNALERROR: HRESULT = 0x88982F48u32 as HRESULT; +pub const WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS: HRESULT = 0x88982F49u32 as HRESULT; +pub const WINCODEC_ERR_COMPONENTNOTFOUND: HRESULT = 0x88982F50u32 as HRESULT; +pub const WINCODEC_ERR_IMAGESIZEOUTOFRANGE: HRESULT = 0x88982F51u32 as HRESULT; +pub const WINCODEC_ERR_TOOMUCHMETADATA: HRESULT = 0x88982F52u32 as HRESULT; +pub const WINCODEC_ERR_BADIMAGE: HRESULT = 0x88982F60u32 as HRESULT; +pub const WINCODEC_ERR_BADHEADER: HRESULT = 0x88982F61u32 as HRESULT; +pub const WINCODEC_ERR_FRAMEMISSING: HRESULT = 0x88982F62u32 as HRESULT; +pub const WINCODEC_ERR_BADMETADATAHEADER: HRESULT = 0x88982F63u32 as HRESULT; +pub const WINCODEC_ERR_BADSTREAMDATA: HRESULT = 0x88982F70u32 as HRESULT; +pub const WINCODEC_ERR_STREAMWRITE: HRESULT = 0x88982F71u32 as HRESULT; +pub const WINCODEC_ERR_STREAMREAD: HRESULT = 0x88982F72u32 as HRESULT; +pub const WINCODEC_ERR_STREAMNOTAVAILABLE: HRESULT = 0x88982F73u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT: HRESULT = 0x88982F80u32 as HRESULT; +pub const WINCODEC_ERR_UNSUPPORTEDOPERATION: HRESULT = 0x88982F81u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDREGISTRATION: HRESULT = 0x88982F8Au32 as HRESULT; +pub const WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: HRESULT = 0x88982F8Bu32 as HRESULT; +pub const WINCODEC_ERR_INSUFFICIENTBUFFER: HRESULT = 0x88982F8Cu32 as HRESULT; +pub const WINCODEC_ERR_DUPLICATEMETADATAPRESENT: HRESULT = 0x88982F8Du32 as HRESULT; +pub const WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE: HRESULT = 0x88982F8Eu32 as HRESULT; +pub const WINCODEC_ERR_UNEXPECTEDSIZE: HRESULT = 0x88982F8Fu32 as HRESULT; +pub const WINCODEC_ERR_INVALIDQUERYREQUEST: HRESULT = 0x88982F90u32 as HRESULT; +pub const WINCODEC_ERR_UNEXPECTEDMETADATATYPE: HRESULT = 0x88982F91u32 as HRESULT; +pub const WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT: HRESULT = 0x88982F92u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDQUERYCHARACTER: HRESULT = 0x88982F93u32 as HRESULT; +pub const WINCODEC_ERR_WIN32ERROR: HRESULT = 0x88982F94u32 as HRESULT; +pub const WINCODEC_ERR_INVALIDPROGRESSIVELEVEL: HRESULT = 0x88982F95u32 as HRESULT; +pub const MILERR_OBJECTBUSY: HRESULT = 0x88980001u32 as HRESULT; +pub const MILERR_INSUFFICIENTBUFFER: HRESULT = 0x88980002u32 as HRESULT; +pub const MILERR_WIN32ERROR: HRESULT = 0x88980003u32 as HRESULT; +pub const MILERR_SCANNER_FAILED: HRESULT = 0x88980004u32 as HRESULT; +pub const MILERR_SCREENACCESSDENIED: HRESULT = 0x88980005u32 as HRESULT; +pub const MILERR_DISPLAYSTATEINVALID: HRESULT = 0x88980006u32 as HRESULT; +pub const MILERR_NONINVERTIBLEMATRIX: HRESULT = 0x88980007u32 as HRESULT; +pub const MILERR_ZEROVECTOR: HRESULT = 0x88980008u32 as HRESULT; +pub const MILERR_TERMINATED: HRESULT = 0x88980009u32 as HRESULT; +pub const MILERR_BADNUMBER: HRESULT = 0x8898000Au32 as HRESULT; +pub const MILERR_INTERNALERROR: HRESULT = 0x88980080u32 as HRESULT; +pub const MILERR_DISPLAYFORMATNOTSUPPORTED: HRESULT = 0x88980084u32 as HRESULT; +pub const MILERR_INVALIDCALL: HRESULT = 0x88980085u32 as HRESULT; +pub const MILERR_ALREADYLOCKED: HRESULT = 0x88980086u32 as HRESULT; +pub const MILERR_NOTLOCKED: HRESULT = 0x88980087u32 as HRESULT; +pub const MILERR_DEVICECANNOTRENDERTEXT: HRESULT = 0x88980088u32 as HRESULT; +pub const MILERR_GLYPHBITMAPMISSED: HRESULT = 0x88980089u32 as HRESULT; +pub const MILERR_MALFORMEDGLYPHCACHE: HRESULT = 0x8898008Au32 as HRESULT; +pub const MILERR_GENERIC_IGNORE: HRESULT = 0x8898008Bu32 as HRESULT; +pub const MILERR_MALFORMED_GUIDELINE_DATA: HRESULT = 0x8898008Cu32 as HRESULT; +pub const MILERR_NO_HARDWARE_DEVICE: HRESULT = 0x8898008Du32 as HRESULT; +pub const MILERR_NEED_RECREATE_AND_PRESENT: HRESULT = 0x8898008Eu32 as HRESULT; +pub const MILERR_ALREADY_INITIALIZED: HRESULT = 0x8898008Fu32 as HRESULT; +pub const MILERR_MISMATCHED_SIZE: HRESULT = 0x88980090u32 as HRESULT; +pub const MILERR_NO_REDIRECTION_SURFACE_AVAILABLE: HRESULT = 0x88980091u32 as HRESULT; +pub const MILERR_REMOTING_NOT_SUPPORTED: HRESULT = 0x88980092u32 as HRESULT; +pub const MILERR_QUEUED_PRESENT_NOT_SUPPORTED: HRESULT = 0x88980093u32 as HRESULT; +pub const MILERR_NOT_QUEUING_PRESENTS: HRESULT = 0x88980094u32 as HRESULT; +pub const MILERR_NO_REDIRECTION_SURFACE_RETRY_LATER: HRESULT = 0x88980095u32 as HRESULT; +pub const MILERR_TOOMANYSHADERELEMNTS: HRESULT = 0x88980096u32 as HRESULT; +pub const MILERR_MROW_READLOCK_FAILED: HRESULT = 0x88980097u32 as HRESULT; +pub const MILERR_MROW_UPDATE_FAILED: HRESULT = 0x88980098u32 as HRESULT; +pub const MILERR_SHADER_COMPILE_FAILED: HRESULT = 0x88980099u32 as HRESULT; +pub const MILERR_MAX_TEXTURE_SIZE_EXCEEDED: HRESULT = 0x8898009Au32 as HRESULT; +pub const MILERR_QPC_TIME_WENT_BACKWARD: HRESULT = 0x8898009Bu32 as HRESULT; +pub const MILERR_DXGI_ENUMERATION_OUT_OF_SYNC: HRESULT = 0x8898009Du32 as HRESULT; +pub const MILERR_ADAPTER_NOT_FOUND: HRESULT = 0x8898009Eu32 as HRESULT; +pub const MILERR_COLORSPACE_NOT_SUPPORTED: HRESULT = 0x8898009Fu32 as HRESULT; +pub const MILERR_PREFILTER_NOT_SUPPORTED: HRESULT = 0x889800A0u32 as HRESULT; +pub const MILERR_DISPLAYID_ACCESS_DENIED: HRESULT = 0x889800A1u32 as HRESULT; +pub const UCEERR_INVALIDPACKETHEADER: HRESULT = 0x88980400u32 as HRESULT; +pub const UCEERR_UNKNOWNPACKET: HRESULT = 0x88980401u32 as HRESULT; +pub const UCEERR_ILLEGALPACKET: HRESULT = 0x88980402u32 as HRESULT; +pub const UCEERR_MALFORMEDPACKET: HRESULT = 0x88980403u32 as HRESULT; +pub const UCEERR_ILLEGALHANDLE: HRESULT = 0x88980404u32 as HRESULT; +pub const UCEERR_HANDLELOOKUPFAILED: HRESULT = 0x88980405u32 as HRESULT; +pub const UCEERR_RENDERTHREADFAILURE: HRESULT = 0x88980406u32 as HRESULT; +pub const UCEERR_CTXSTACKFRSTTARGETNULL: HRESULT = 0x88980407u32 as HRESULT; +pub const UCEERR_CONNECTIONIDLOOKUPFAILED: HRESULT = 0x88980408u32 as HRESULT; +pub const UCEERR_BLOCKSFULL: HRESULT = 0x88980409u32 as HRESULT; +pub const UCEERR_MEMORYFAILURE: HRESULT = 0x8898040Au32 as HRESULT; +pub const UCEERR_PACKETRECORDOUTOFRANGE: HRESULT = 0x8898040Bu32 as HRESULT; +pub const UCEERR_ILLEGALRECORDTYPE: HRESULT = 0x8898040Cu32 as HRESULT; +pub const UCEERR_OUTOFHANDLES: HRESULT = 0x8898040Du32 as HRESULT; +pub const UCEERR_UNCHANGABLE_UPDATE_ATTEMPTED: HRESULT = 0x8898040Eu32 as HRESULT; +pub const UCEERR_NO_MULTIPLE_WORKER_THREADS: HRESULT = 0x8898040Fu32 as HRESULT; +pub const UCEERR_REMOTINGNOTSUPPORTED: HRESULT = 0x88980410u32 as HRESULT; +pub const UCEERR_MISSINGENDCOMMAND: HRESULT = 0x88980411u32 as HRESULT; +pub const UCEERR_MISSINGBEGINCOMMAND: HRESULT = 0x88980412u32 as HRESULT; +pub const UCEERR_CHANNELSYNCTIMEDOUT: HRESULT = 0x88980413u32 as HRESULT; +pub const UCEERR_CHANNELSYNCABANDONED: HRESULT = 0x88980414u32 as HRESULT; +pub const UCEERR_UNSUPPORTEDTRANSPORTVERSION: HRESULT = 0x88980415u32 as HRESULT; +pub const UCEERR_TRANSPORTUNAVAILABLE: HRESULT = 0x88980416u32 as HRESULT; +pub const UCEERR_FEEDBACK_UNSUPPORTED: HRESULT = 0x88980417u32 as HRESULT; +pub const UCEERR_COMMANDTRANSPORTDENIED: HRESULT = 0x88980418u32 as HRESULT; +pub const UCEERR_GRAPHICSSTREAMUNAVAILABLE: HRESULT = 0x88980419u32 as HRESULT; +pub const UCEERR_GRAPHICSSTREAMALREADYOPEN: HRESULT = 0x88980420u32 as HRESULT; +pub const UCEERR_TRANSPORTDISCONNECTED: HRESULT = 0x88980421u32 as HRESULT; +pub const UCEERR_TRANSPORTOVERLOADED: HRESULT = 0x88980422u32 as HRESULT; +pub const UCEERR_PARTITION_ZOMBIED: HRESULT = 0x88980423u32 as HRESULT; +pub const MILAVERR_NOCLOCK: HRESULT = 0x88980500u32 as HRESULT; +pub const MILAVERR_NOMEDIATYPE: HRESULT = 0x88980501u32 as HRESULT; +pub const MILAVERR_NOVIDEOMIXER: HRESULT = 0x88980502u32 as HRESULT; +pub const MILAVERR_NOVIDEOPRESENTER: HRESULT = 0x88980503u32 as HRESULT; +pub const MILAVERR_NOREADYFRAMES: HRESULT = 0x88980504u32 as HRESULT; +pub const MILAVERR_MODULENOTLOADED: HRESULT = 0x88980505u32 as HRESULT; +pub const MILAVERR_WMPFACTORYNOTREGISTERED: HRESULT = 0x88980506u32 as HRESULT; +pub const MILAVERR_INVALIDWMPVERSION: HRESULT = 0x88980507u32 as HRESULT; +pub const MILAVERR_INSUFFICIENTVIDEORESOURCES: HRESULT = 0x88980508u32 as HRESULT; +pub const MILAVERR_VIDEOACCELERATIONNOTAVAILABLE: HRESULT = 0x88980509u32 as HRESULT; +pub const MILAVERR_REQUESTEDTEXTURETOOBIG: HRESULT = 0x8898050Au32 as HRESULT; +pub const MILAVERR_SEEKFAILED: HRESULT = 0x8898050Bu32 as HRESULT; +pub const MILAVERR_UNEXPECTEDWMPFAILURE: HRESULT = 0x8898050Cu32 as HRESULT; +pub const MILAVERR_MEDIAPLAYERCLOSED: HRESULT = 0x8898050Du32 as HRESULT; +pub const MILAVERR_UNKNOWNHARDWAREERROR: HRESULT = 0x8898050Eu32 as HRESULT; +pub const MILEFFECTSERR_UNKNOWNPROPERTY: HRESULT = 0x8898060Eu32 as HRESULT; +pub const MILEFFECTSERR_EFFECTNOTPARTOFGROUP: HRESULT = 0x8898060Fu32 as HRESULT; +pub const MILEFFECTSERR_NOINPUTSOURCEATTACHED: HRESULT = 0x88980610u32 as HRESULT; +pub const MILEFFECTSERR_CONNECTORNOTCONNECTED: HRESULT = 0x88980611u32 as HRESULT; +pub const MILEFFECTSERR_CONNECTORNOTASSOCIATEDWITHEFFECT: HRESULT = 0x88980612u32 as HRESULT; +pub const MILEFFECTSERR_RESERVED: HRESULT = 0x88980613u32 as HRESULT; +pub const MILEFFECTSERR_CYCLEDETECTED: HRESULT = 0x88980614u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTINMORETHANONEGRAPH: HRESULT = 0x88980615u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTALREADYINAGRAPH: HRESULT = 0x88980616u32 as HRESULT; +pub const MILEFFECTSERR_EFFECTHASNOCHILDREN: HRESULT = 0x88980617u32 as HRESULT; +pub const MILEFFECTSERR_ALREADYATTACHEDTOLISTENER: HRESULT = 0x88980618u32 as HRESULT; +pub const MILEFFECTSERR_NOTAFFINETRANSFORM: HRESULT = 0x88980619u32 as HRESULT; +pub const MILEFFECTSERR_EMPTYBOUNDS: HRESULT = 0x8898061Au32 as HRESULT; +pub const MILEFFECTSERR_OUTPUTSIZETOOLARGE: HRESULT = 0x8898061Bu32 as HRESULT; +pub const DWMERR_STATE_TRANSITION_FAILED: HRESULT = 0x88980700u32 as HRESULT; +pub const DWMERR_THEME_FAILED: HRESULT = 0x88980701u32 as HRESULT; +pub const DWMERR_CATASTROPHIC_FAILURE: HRESULT = 0x88980702u32 as HRESULT; +pub const DCOMPOSITION_ERROR_WINDOW_ALREADY_COMPOSED: HRESULT = 0x88980800u32 as HRESULT; +pub const DCOMPOSITION_ERROR_SURFACE_BEING_RENDERED: HRESULT = 0x88980801u32 as HRESULT; +pub const DCOMPOSITION_ERROR_SURFACE_NOT_BEING_RENDERED: HRESULT = 0x88980802u32 as HRESULT; +pub const ONL_E_INVALID_AUTHENTICATION_TARGET: HRESULT = 0x80860001u32 as HRESULT; +pub const ONL_E_ACCESS_DENIED_BY_TOU: HRESULT = 0x80860002u32 as HRESULT; +pub const ONL_E_INVALID_APPLICATION: HRESULT = 0x80860003u32 as HRESULT; +pub const ONL_E_PASSWORD_UPDATE_REQUIRED: HRESULT = 0x80860004u32 as HRESULT; +pub const ONL_E_ACCOUNT_UPDATE_REQUIRED: HRESULT = 0x80860005u32 as HRESULT; +pub const ONL_E_FORCESIGNIN: HRESULT = 0x80860006u32 as HRESULT; +pub const ONL_E_ACCOUNT_LOCKED: HRESULT = 0x80860007u32 as HRESULT; +pub const ONL_E_PARENTAL_CONSENT_REQUIRED: HRESULT = 0x80860008u32 as HRESULT; +pub const ONL_E_EMAIL_VERIFICATION_REQUIRED: HRESULT = 0x80860009u32 as HRESULT; +pub const ONL_E_ACCOUNT_SUSPENDED_COMPROIMISE: HRESULT = 0x8086000Au32 as HRESULT; +pub const ONL_E_ACCOUNT_SUSPENDED_ABUSE: HRESULT = 0x8086000Bu32 as HRESULT; +pub const ONL_E_ACTION_REQUIRED: HRESULT = 0x8086000Cu32 as HRESULT; +pub const ONL_CONNECTION_COUNT_LIMIT: HRESULT = 0x8086000Du32 as HRESULT; +pub const ONL_E_CONNECTED_ACCOUNT_CAN_NOT_SIGNOUT: HRESULT = 0x8086000Eu32 as HRESULT; +pub const ONL_E_USER_AUTHENTICATION_REQUIRED: HRESULT = 0x8086000Fu32 as HRESULT; +pub const ONL_E_REQUEST_THROTTLED: HRESULT = 0x80860010u32 as HRESULT; +pub const FA_E_MAX_PERSISTED_ITEMS_REACHED: HRESULT = 0x80270220u32 as HRESULT; +pub const FA_E_HOMEGROUP_NOT_AVAILABLE: HRESULT = 0x80270222u32 as HRESULT; +pub const E_MONITOR_RESOLUTION_TOO_LOW: HRESULT = 0x80270250u32 as HRESULT; +pub const E_ELEVATED_ACTIVATION_NOT_SUPPORTED: HRESULT = 0x80270251u32 as HRESULT; +pub const E_UAC_DISABLED: HRESULT = 0x80270252u32 as HRESULT; +pub const E_FULL_ADMIN_NOT_SUPPORTED: HRESULT = 0x80270253u32 as HRESULT; +pub const E_APPLICATION_NOT_REGISTERED: HRESULT = 0x80270254u32 as HRESULT; +pub const E_MULTIPLE_EXTENSIONS_FOR_APPLICATION: HRESULT = 0x80270255u32 as HRESULT; +pub const E_MULTIPLE_PACKAGES_FOR_FAMILY: HRESULT = 0x80270256u32 as HRESULT; +pub const E_APPLICATION_MANAGER_NOT_RUNNING: HRESULT = 0x80270257u32 as HRESULT; +pub const S_STORE_LAUNCHED_FOR_REMEDIATION: HRESULT = 0x00270258; +pub const S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG: HRESULT = 0x00270259; +pub const E_APPLICATION_ACTIVATION_TIMED_OUT: HRESULT = 0x8027025Au32 as HRESULT; +pub const E_APPLICATION_ACTIVATION_EXEC_FAILURE: HRESULT = 0x8027025Bu32 as HRESULT; +pub const E_APPLICATION_TEMPORARY_LICENSE_ERROR: HRESULT = 0x8027025Cu32 as HRESULT; +pub const E_APPLICATION_TRIAL_LICENSE_EXPIRED: HRESULT = 0x8027025Du32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_FILE_SYSTEM_NOT_SUPPORTED: HRESULT = 0x80270260u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_OVERLAP: HRESULT = 0x80270261u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_CANNOT_INDEX: HRESULT = 0x80270262u32 as HRESULT; +pub const E_SKYDRIVE_FILE_NOT_UPLOADED: HRESULT = 0x80270263u32 as HRESULT; +pub const E_SKYDRIVE_UPDATE_AVAILABILITY_FAIL: HRESULT = 0x80270264u32 as HRESULT; +pub const E_SKYDRIVE_ROOT_TARGET_VOLUME_ROOT_NOT_SUPPORTED: HRESULT = 0x80270265u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SIZE_OVER_LIMIT: HRESULT = 0x8802B001u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SIZE_EXCEEDS_REMAINING_QUOTA: HRESULT = 0x8802B002u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_FILE_NAME: HRESULT = 0x8802B003u32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_ITEM_COUNT_LIMIT_EXCEEDED: HRESULT = 0x8802B004u32 as HRESULT; +pub const E_SYNCENGINE_FILE_SYNC_PARTNER_ERROR: HRESULT = 0x8802B005u32 as HRESULT; +pub const E_SYNCENGINE_SYNC_PAUSED_BY_SERVICE: HRESULT = 0x8802B006u32 as HRESULT; +pub const E_SYNCENGINE_FILE_IDENTIFIER_UNKNOWN: HRESULT = 0x8802C002u32 as HRESULT; +pub const E_SYNCENGINE_SERVICE_AUTHENTICATION_FAILED: HRESULT = 0x8802C003u32 as HRESULT; +pub const E_SYNCENGINE_UNKNOWN_SERVICE_ERROR: HRESULT = 0x8802C004u32 as HRESULT; +pub const E_SYNCENGINE_SERVICE_RETURNED_UNEXPECTED_SIZE: HRESULT = 0x8802C005u32 as HRESULT; +pub const E_SYNCENGINE_REQUEST_BLOCKED_BY_SERVICE: HRESULT = 0x8802C006u32 as HRESULT; +pub const E_SYNCENGINE_REQUEST_BLOCKED_DUE_TO_CLIENT_ERROR: HRESULT = 0x8802C007u32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_INACCESSIBLE: HRESULT = 0x8802D001u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_FOLDER_NAME: HRESULT = 0x8802D002u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_MARKET: HRESULT = 0x8802D003u32 as HRESULT; +pub const E_SYNCENGINE_PATH_LENGTH_LIMIT_EXCEEDED: HRESULT = 0x8802D004u32 as HRESULT; +pub const E_SYNCENGINE_REMOTE_PATH_LENGTH_LIMIT_EXCEEDED: HRESULT = 0x8802D005u32 as HRESULT; +pub const E_SYNCENGINE_CLIENT_UPDATE_NEEDED: HRESULT = 0x8802D006u32 as HRESULT; +pub const E_SYNCENGINE_PROXY_AUTHENTICATION_REQUIRED: HRESULT = 0x8802D007u32 as HRESULT; +pub const E_SYNCENGINE_STORAGE_SERVICE_PROVISIONING_FAILED: HRESULT = 0x8802D008u32 as HRESULT; +pub const E_SYNCENGINE_UNSUPPORTED_REPARSE_POINT: HRESULT = 0x8802D009u32 as HRESULT; +pub const E_SYNCENGINE_STORAGE_SERVICE_BLOCKED: HRESULT = 0x8802D00Au32 as HRESULT; +pub const E_SYNCENGINE_FOLDER_IN_REDIRECTION: HRESULT = 0x8802D00Bu32 as HRESULT; +pub const EAS_E_POLICY_NOT_MANAGED_BY_OS: HRESULT = 0x80550001u32 as HRESULT; +pub const EAS_E_POLICY_COMPLIANT_WITH_ACTIONS: HRESULT = 0x80550002u32 as HRESULT; +pub const EAS_E_REQUESTED_POLICY_NOT_ENFORCEABLE: HRESULT = 0x80550003u32 as HRESULT; +pub const EAS_E_CURRENT_USER_HAS_BLANK_PASSWORD: HRESULT = 0x80550004u32 as HRESULT; +pub const EAS_E_REQUESTED_POLICY_PASSWORD_EXPIRATION_INCOMPATIBLE: HRESULT = 0x80550005u32 as HRESULT; +pub const EAS_E_USER_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550006u32 as HRESULT; +pub const EAS_E_ADMINS_HAVE_BLANK_PASSWORD: HRESULT = 0x80550007u32 as HRESULT; +pub const EAS_E_ADMINS_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550008u32 as HRESULT; +pub const EAS_E_LOCAL_CONTROLLED_USERS_CANNOT_CHANGE_PASSWORD: HRESULT = 0x80550009u32 as HRESULT; +pub const EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CONNECTED_ADMINS: HRESULT = 0x8055000Au32 as HRESULT; +pub const EAS_E_CONNECTED_ADMINS_NEED_TO_CHANGE_PASSWORD: HRESULT = 0x8055000Bu32 as HRESULT; +pub const EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CURRENT_CONNECTED_USER: HRESULT = 0x8055000Cu32 as HRESULT; +pub const EAS_E_CURRENT_CONNECTED_USER_NEED_TO_CHANGE_PASSWORD: HRESULT = 0x8055000Du32 as HRESULT; +pub const WEB_E_UNSUPPORTED_FORMAT: HRESULT = 0x83750001u32 as HRESULT; +pub const WEB_E_INVALID_XML: HRESULT = 0x83750002u32 as HRESULT; +pub const WEB_E_MISSING_REQUIRED_ELEMENT: HRESULT = 0x83750003u32 as HRESULT; +pub const WEB_E_MISSING_REQUIRED_ATTRIBUTE: HRESULT = 0x83750004u32 as HRESULT; +pub const WEB_E_UNEXPECTED_CONTENT: HRESULT = 0x83750005u32 as HRESULT; +pub const WEB_E_RESOURCE_TOO_LARGE: HRESULT = 0x83750006u32 as HRESULT; +pub const WEB_E_INVALID_JSON_STRING: HRESULT = 0x83750007u32 as HRESULT; +pub const WEB_E_INVALID_JSON_NUMBER: HRESULT = 0x83750008u32 as HRESULT; +pub const WEB_E_JSON_VALUE_NOT_FOUND: HRESULT = 0x83750009u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED: HRESULT = 0x80190001u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_REDIRECTION: HRESULT = 0x80190003u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_CLIENT_ERROR: HRESULT = 0x80190004u32 as HRESULT; +pub const HTTP_E_STATUS_UNEXPECTED_SERVER_ERROR: HRESULT = 0x80190005u32 as HRESULT; +pub const HTTP_E_STATUS_AMBIGUOUS: HRESULT = 0x8019012Cu32 as HRESULT; +pub const HTTP_E_STATUS_MOVED: HRESULT = 0x8019012Du32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT: HRESULT = 0x8019012Eu32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT_METHOD: HRESULT = 0x8019012Fu32 as HRESULT; +pub const HTTP_E_STATUS_NOT_MODIFIED: HRESULT = 0x80190130u32 as HRESULT; +pub const HTTP_E_STATUS_USE_PROXY: HRESULT = 0x80190131u32 as HRESULT; +pub const HTTP_E_STATUS_REDIRECT_KEEP_VERB: HRESULT = 0x80190133u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_REQUEST: HRESULT = 0x80190190u32 as HRESULT; +pub const HTTP_E_STATUS_DENIED: HRESULT = 0x80190191u32 as HRESULT; +pub const HTTP_E_STATUS_PAYMENT_REQ: HRESULT = 0x80190192u32 as HRESULT; +pub const HTTP_E_STATUS_FORBIDDEN: HRESULT = 0x80190193u32 as HRESULT; +pub const HTTP_E_STATUS_NOT_FOUND: HRESULT = 0x80190194u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_METHOD: HRESULT = 0x80190195u32 as HRESULT; +pub const HTTP_E_STATUS_NONE_ACCEPTABLE: HRESULT = 0x80190196u32 as HRESULT; +pub const HTTP_E_STATUS_PROXY_AUTH_REQ: HRESULT = 0x80190197u32 as HRESULT; +pub const HTTP_E_STATUS_REQUEST_TIMEOUT: HRESULT = 0x80190198u32 as HRESULT; +pub const HTTP_E_STATUS_CONFLICT: HRESULT = 0x80190199u32 as HRESULT; +pub const HTTP_E_STATUS_GONE: HRESULT = 0x8019019Au32 as HRESULT; +pub const HTTP_E_STATUS_LENGTH_REQUIRED: HRESULT = 0x8019019Bu32 as HRESULT; +pub const HTTP_E_STATUS_PRECOND_FAILED: HRESULT = 0x8019019Cu32 as HRESULT; +pub const HTTP_E_STATUS_REQUEST_TOO_LARGE: HRESULT = 0x8019019Du32 as HRESULT; +pub const HTTP_E_STATUS_URI_TOO_LONG: HRESULT = 0x8019019Eu32 as HRESULT; +pub const HTTP_E_STATUS_UNSUPPORTED_MEDIA: HRESULT = 0x8019019Fu32 as HRESULT; +pub const HTTP_E_STATUS_RANGE_NOT_SATISFIABLE: HRESULT = 0x801901A0u32 as HRESULT; +pub const HTTP_E_STATUS_EXPECTATION_FAILED: HRESULT = 0x801901A1u32 as HRESULT; +pub const HTTP_E_STATUS_SERVER_ERROR: HRESULT = 0x801901F4u32 as HRESULT; +pub const HTTP_E_STATUS_NOT_SUPPORTED: HRESULT = 0x801901F5u32 as HRESULT; +pub const HTTP_E_STATUS_BAD_GATEWAY: HRESULT = 0x801901F6u32 as HRESULT; +pub const HTTP_E_STATUS_SERVICE_UNAVAIL: HRESULT = 0x801901F7u32 as HRESULT; +pub const HTTP_E_STATUS_GATEWAY_TIMEOUT: HRESULT = 0x801901F8u32 as HRESULT; +pub const HTTP_E_STATUS_VERSION_NOT_SUP: HRESULT = 0x801901F9u32 as HRESULT; +pub const E_INVALID_PROTOCOL_OPERATION: HRESULT = 0x83760001u32 as HRESULT; +pub const E_INVALID_PROTOCOL_FORMAT: HRESULT = 0x83760002u32 as HRESULT; +pub const E_PROTOCOL_EXTENSIONS_NOT_SUPPORTED: HRESULT = 0x83760003u32 as HRESULT; +pub const E_SUBPROTOCOL_NOT_SUPPORTED: HRESULT = 0x83760004u32 as HRESULT; +pub const E_PROTOCOL_VERSION_NOT_SUPPORTED: HRESULT = 0x83760005u32 as HRESULT; +pub const INPUT_E_OUT_OF_ORDER: HRESULT = 0x80400000u32 as HRESULT; +pub const INPUT_E_REENTRANCY: HRESULT = 0x80400001u32 as HRESULT; +pub const INPUT_E_MULTIMODAL: HRESULT = 0x80400002u32 as HRESULT; +pub const INPUT_E_PACKET: HRESULT = 0x80400003u32 as HRESULT; +pub const INPUT_E_FRAME: HRESULT = 0x80400004u32 as HRESULT; +pub const INPUT_E_HISTORY: HRESULT = 0x80400005u32 as HRESULT; +pub const INPUT_E_DEVICE_INFO: HRESULT = 0x80400006u32 as HRESULT; +pub const INPUT_E_TRANSFORM: HRESULT = 0x80400007u32 as HRESULT; +pub const INPUT_E_DEVICE_PROPERTY: HRESULT = 0x80400008u32 as HRESULT; +pub const INET_E_INVALID_URL: HRESULT = 0x800C0002u32 as HRESULT; +pub const INET_E_NO_SESSION: HRESULT = 0x800C0003u32 as HRESULT; +pub const INET_E_CANNOT_CONNECT: HRESULT = 0x800C0004u32 as HRESULT; +pub const INET_E_RESOURCE_NOT_FOUND: HRESULT = 0x800C0005u32 as HRESULT; +pub const INET_E_OBJECT_NOT_FOUND: HRESULT = 0x800C0006u32 as HRESULT; +pub const INET_E_DATA_NOT_AVAILABLE: HRESULT = 0x800C0007u32 as HRESULT; +pub const INET_E_DOWNLOAD_FAILURE: HRESULT = 0x800C0008u32 as HRESULT; +pub const INET_E_AUTHENTICATION_REQUIRED: HRESULT = 0x800C0009u32 as HRESULT; +pub const INET_E_NO_VALID_MEDIA: HRESULT = 0x800C000Au32 as HRESULT; +pub const INET_E_CONNECTION_TIMEOUT: HRESULT = 0x800C000Bu32 as HRESULT; +pub const INET_E_INVALID_REQUEST: HRESULT = 0x800C000Cu32 as HRESULT; +pub const INET_E_UNKNOWN_PROTOCOL: HRESULT = 0x800C000Du32 as HRESULT; +pub const INET_E_SECURITY_PROBLEM: HRESULT = 0x800C000Eu32 as HRESULT; +pub const INET_E_CANNOT_LOAD_DATA: HRESULT = 0x800C000Fu32 as HRESULT; +pub const INET_E_CANNOT_INSTANTIATE_OBJECT: HRESULT = 0x800C0010u32 as HRESULT; +pub const INET_E_INVALID_CERTIFICATE: HRESULT = 0x800C0019u32 as HRESULT; +pub const INET_E_REDIRECT_FAILED: HRESULT = 0x800C0014u32 as HRESULT; +pub const INET_E_REDIRECT_TO_DIR: HRESULT = 0x800C0015u32 as HRESULT; +pub const ERROR_DBG_CREATE_PROCESS_FAILURE_LOCKDOWN: HRESULT = 0x80B00001u32 as HRESULT; +pub const ERROR_DBG_ATTACH_PROCESS_FAILURE_LOCKDOWN: HRESULT = 0x80B00002u32 as HRESULT; +pub const ERROR_DBG_CONNECT_SERVER_FAILURE_LOCKDOWN: HRESULT = 0x80B00003u32 as HRESULT; +pub const ERROR_DBG_START_SERVER_FAILURE_LOCKDOWN: HRESULT = 0x80B00004u32 as HRESULT; +pub const ERROR_IO_PREEMPTED: HRESULT = 0x89010001u32 as HRESULT; +pub const JSCRIPT_E_CANTEXECUTE: HRESULT = 0x89020001u32 as HRESULT; +pub const WEP_E_NOT_PROVISIONED_ON_ALL_VOLUMES: HRESULT = 0x88010001u32 as HRESULT; +pub const WEP_E_FIXED_DATA_NOT_SUPPORTED: HRESULT = 0x88010002u32 as HRESULT; +pub const WEP_E_HARDWARE_NOT_COMPLIANT: HRESULT = 0x88010003u32 as HRESULT; +pub const WEP_E_LOCK_NOT_CONFIGURED: HRESULT = 0x88010004u32 as HRESULT; +pub const WEP_E_PROTECTION_SUSPENDED: HRESULT = 0x88010005u32 as HRESULT; +pub const WEP_E_NO_LICENSE: HRESULT = 0x88010006u32 as HRESULT; +pub const WEP_E_OS_NOT_PROTECTED: HRESULT = 0x88010007u32 as HRESULT; +pub const WEP_E_UNEXPECTED_FAIL: HRESULT = 0x88010008u32 as HRESULT; +pub const WEP_E_BUFFER_TOO_LARGE: HRESULT = 0x88010009u32 as HRESULT; +pub const ERROR_SVHDX_ERROR_STORED: HRESULT = 0xC05C0000u32 as HRESULT; +pub const ERROR_SVHDX_ERROR_NOT_AVAILABLE: HRESULT = 0xC05CFF00u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_AVAILABLE: HRESULT = 0xC05CFF01u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: HRESULT = 0xC05CFF02u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: HRESULT = 0xC05CFF03u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: HRESULT = 0xC05CFF04u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: HRESULT = 0xC05CFF05u32 as HRESULT; +pub const ERROR_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: HRESULT = 0xC05CFF06u32 as HRESULT; +pub const ERROR_SVHDX_RESERVATION_CONFLICT: HRESULT = 0xC05CFF07u32 as HRESULT; +pub const ERROR_SVHDX_WRONG_FILE_TYPE: HRESULT = 0xC05CFF08u32 as HRESULT; +pub const ERROR_SVHDX_VERSION_MISMATCH: HRESULT = 0xC05CFF09u32 as HRESULT; +pub const ERROR_VHD_SHARED: HRESULT = 0xC05CFF0Au32 as HRESULT; +pub const WININET_E_OUT_OF_HANDLES: HRESULT = 0x80072EE1u32 as HRESULT; +pub const WININET_E_TIMEOUT: HRESULT = 0x80072EE2u32 as HRESULT; +pub const WININET_E_EXTENDED_ERROR: HRESULT = 0x80072EE3u32 as HRESULT; +pub const WININET_E_INTERNAL_ERROR: HRESULT = 0x80072EE4u32 as HRESULT; +pub const WININET_E_INVALID_URL: HRESULT = 0x80072EE5u32 as HRESULT; +pub const WININET_E_UNRECOGNIZED_SCHEME: HRESULT = 0x80072EE6u32 as HRESULT; +pub const WININET_E_NAME_NOT_RESOLVED: HRESULT = 0x80072EE7u32 as HRESULT; +pub const WININET_E_PROTOCOL_NOT_FOUND: HRESULT = 0x80072EE8u32 as HRESULT; +pub const WININET_E_INVALID_OPTION: HRESULT = 0x80072EE9u32 as HRESULT; +pub const WININET_E_BAD_OPTION_LENGTH: HRESULT = 0x80072EEAu32 as HRESULT; +pub const WININET_E_OPTION_NOT_SETTABLE: HRESULT = 0x80072EEBu32 as HRESULT; +pub const WININET_E_SHUTDOWN: HRESULT = 0x80072EECu32 as HRESULT; +pub const WININET_E_INCORRECT_USER_NAME: HRESULT = 0x80072EEDu32 as HRESULT; +pub const WININET_E_INCORRECT_PASSWORD: HRESULT = 0x80072EEEu32 as HRESULT; +pub const WININET_E_LOGIN_FAILURE: HRESULT = 0x80072EEFu32 as HRESULT; +pub const WININET_E_INVALID_OPERATION: HRESULT = 0x80072EF0u32 as HRESULT; +pub const WININET_E_OPERATION_CANCELLED: HRESULT = 0x80072EF1u32 as HRESULT; +pub const WININET_E_INCORRECT_HANDLE_TYPE: HRESULT = 0x80072EF2u32 as HRESULT; +pub const WININET_E_INCORRECT_HANDLE_STATE: HRESULT = 0x80072EF3u32 as HRESULT; +pub const WININET_E_NOT_PROXY_REQUEST: HRESULT = 0x80072EF4u32 as HRESULT; +pub const WININET_E_REGISTRY_VALUE_NOT_FOUND: HRESULT = 0x80072EF5u32 as HRESULT; +pub const WININET_E_BAD_REGISTRY_PARAMETER: HRESULT = 0x80072EF6u32 as HRESULT; +pub const WININET_E_NO_DIRECT_ACCESS: HRESULT = 0x80072EF7u32 as HRESULT; +pub const WININET_E_NO_CONTEXT: HRESULT = 0x80072EF8u32 as HRESULT; +pub const WININET_E_NO_CALLBACK: HRESULT = 0x80072EF9u32 as HRESULT; +pub const WININET_E_REQUEST_PENDING: HRESULT = 0x80072EFAu32 as HRESULT; +pub const WININET_E_INCORRECT_FORMAT: HRESULT = 0x80072EFBu32 as HRESULT; +pub const WININET_E_ITEM_NOT_FOUND: HRESULT = 0x80072EFCu32 as HRESULT; +pub const WININET_E_CANNOT_CONNECT: HRESULT = 0x80072EFDu32 as HRESULT; +pub const WININET_E_CONNECTION_ABORTED: HRESULT = 0x80072EFEu32 as HRESULT; +pub const WININET_E_CONNECTION_RESET: HRESULT = 0x80072EFFu32 as HRESULT; +pub const WININET_E_FORCE_RETRY: HRESULT = 0x80072F00u32 as HRESULT; +pub const WININET_E_INVALID_PROXY_REQUEST: HRESULT = 0x80072F01u32 as HRESULT; +pub const WININET_E_NEED_UI: HRESULT = 0x80072F02u32 as HRESULT; +pub const WININET_E_HANDLE_EXISTS: HRESULT = 0x80072F04u32 as HRESULT; +pub const WININET_E_SEC_CERT_DATE_INVALID: HRESULT = 0x80072F05u32 as HRESULT; +pub const WININET_E_SEC_CERT_CN_INVALID: HRESULT = 0x80072F06u32 as HRESULT; +pub const WININET_E_HTTP_TO_HTTPS_ON_REDIR: HRESULT = 0x80072F07u32 as HRESULT; +pub const WININET_E_HTTPS_TO_HTTP_ON_REDIR: HRESULT = 0x80072F08u32 as HRESULT; +pub const WININET_E_MIXED_SECURITY: HRESULT = 0x80072F09u32 as HRESULT; +pub const WININET_E_CHG_POST_IS_NON_SECURE: HRESULT = 0x80072F0Au32 as HRESULT; +pub const WININET_E_POST_IS_NON_SECURE: HRESULT = 0x80072F0Bu32 as HRESULT; +pub const WININET_E_CLIENT_AUTH_CERT_NEEDED: HRESULT = 0x80072F0Cu32 as HRESULT; +pub const WININET_E_INVALID_CA: HRESULT = 0x80072F0Du32 as HRESULT; +pub const WININET_E_CLIENT_AUTH_NOT_SETUP: HRESULT = 0x80072F0Eu32 as HRESULT; +pub const WININET_E_ASYNC_THREAD_FAILED: HRESULT = 0x80072F0Fu32 as HRESULT; +pub const WININET_E_REDIRECT_SCHEME_CHANGE: HRESULT = 0x80072F10u32 as HRESULT; +pub const WININET_E_DIALOG_PENDING: HRESULT = 0x80072F11u32 as HRESULT; +pub const WININET_E_RETRY_DIALOG: HRESULT = 0x80072F12u32 as HRESULT; +pub const WININET_E_NO_NEW_CONTAINERS: HRESULT = 0x80072F13u32 as HRESULT; +pub const WININET_E_HTTPS_HTTP_SUBMIT_REDIR: HRESULT = 0x80072F14u32 as HRESULT; +pub const WININET_E_SEC_CERT_ERRORS: HRESULT = 0x80072F17u32 as HRESULT; +pub const WININET_E_SEC_CERT_REV_FAILED: HRESULT = 0x80072F19u32 as HRESULT; +pub const WININET_E_HEADER_NOT_FOUND: HRESULT = 0x80072F76u32 as HRESULT; +pub const WININET_E_DOWNLEVEL_SERVER: HRESULT = 0x80072F77u32 as HRESULT; +pub const WININET_E_INVALID_SERVER_RESPONSE: HRESULT = 0x80072F78u32 as HRESULT; +pub const WININET_E_INVALID_HEADER: HRESULT = 0x80072F79u32 as HRESULT; +pub const WININET_E_INVALID_QUERY_REQUEST: HRESULT = 0x80072F7Au32 as HRESULT; +pub const WININET_E_HEADER_ALREADY_EXISTS: HRESULT = 0x80072F7Bu32 as HRESULT; +pub const WININET_E_REDIRECT_FAILED: HRESULT = 0x80072F7Cu32 as HRESULT; +pub const WININET_E_SECURITY_CHANNEL_ERROR: HRESULT = 0x80072F7Du32 as HRESULT; +pub const WININET_E_UNABLE_TO_CACHE_FILE: HRESULT = 0x80072F7Eu32 as HRESULT; +pub const WININET_E_TCPIP_NOT_INSTALLED: HRESULT = 0x80072F7Fu32 as HRESULT; +pub const WININET_E_DISCONNECTED: HRESULT = 0x80072F83u32 as HRESULT; +pub const WININET_E_SERVER_UNREACHABLE: HRESULT = 0x80072F84u32 as HRESULT; +pub const WININET_E_PROXY_SERVER_UNREACHABLE: HRESULT = 0x80072F85u32 as HRESULT; +pub const WININET_E_BAD_AUTO_PROXY_SCRIPT: HRESULT = 0x80072F86u32 as HRESULT; +pub const WININET_E_UNABLE_TO_DOWNLOAD_SCRIPT: HRESULT = 0x80072F87u32 as HRESULT; +pub const WININET_E_SEC_INVALID_CERT: HRESULT = 0x80072F89u32 as HRESULT; +pub const WININET_E_SEC_CERT_REVOKED: HRESULT = 0x80072F8Au32 as HRESULT; +pub const WININET_E_FAILED_DUETOSECURITYCHECK: HRESULT = 0x80072F8Bu32 as HRESULT; +pub const WININET_E_NOT_INITIALIZED: HRESULT = 0x80072F8Cu32 as HRESULT; +pub const WININET_E_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: HRESULT = 0x80072F8Eu32 as HRESULT; +pub const WININET_E_DECODING_FAILED: HRESULT = 0x80072F8Fu32 as HRESULT; +pub const WININET_E_NOT_REDIRECTED: HRESULT = 0x80072F80u32 as HRESULT; +pub const WININET_E_COOKIE_NEEDS_CONFIRMATION: HRESULT = 0x80072F81u32 as HRESULT; +pub const WININET_E_COOKIE_DECLINED: HRESULT = 0x80072F82u32 as HRESULT; +pub const WININET_E_REDIRECT_NEEDS_CONFIRMATION: HRESULT = 0x80072F88u32 as HRESULT; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winevt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winevt.rs new file mode 100644 index 0000000..3f2d6a0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winevt.rs @@ -0,0 +1,40 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Windows Events API +pub type EVT_HANDLE = ::HANDLE; +pub type PEVT_HANDLE = *mut ::HANDLE; +ENUM!{enum EVT_VARIANT_TYPE { + EvtVarTypeNull = 0, + EvtVarTypeString = 1, + EvtVarTypeAnsiString = 2, + EvtVarTypeSByte = 3, + EvtVarTypeByte = 4, + EvtVarTypeInt16 = 5, + EvtVarTypeUInt16 = 6, + EvtVarTypeInt32 = 7, + EvtVarTypeUInt32 = 8, + EvtVarTypeInt64 = 9, + EvtVarTypeUInt64 = 10, + EvtVarTypeSingle = 11, + EvtVarTypeDouble = 12, + EvtVarTypeBoolean = 13, + EvtVarTypeBinary = 14, + EvtVarTypeGuid = 15, + EvtVarTypeSizeT = 16, + EvtVarTypeFileTime = 17, + EvtVarTypeSysTime = 18, + EvtVarTypeSid = 19, + EvtVarTypeHexInt32 = 20, + EvtVarTypeHexInt64 = 21, + EvtVarTypeEvtHandle = 32, + EvtVarTypeEvtXml = 35, +}} +pub const EVT_VARIANT_TYPE_MASK: ::DWORD = 0x7f; +pub const EVT_VARIANT_TYPE_ARRAY: ::DWORD = 128; +STRUCT!{struct EVT_VARIANT { + u: u64, + Count: ::DWORD, + Type: ::DWORD, +}} +// TODO - All the UNION! for each variant +// TODO - The rest of this header diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wingdi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wingdi.rs new file mode 100644 index 0000000..edc5850 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wingdi.rs @@ -0,0 +1,1238 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! GDI procedure declarations, constant definitions and macros +pub const DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: ::DWORD = 0x00000001; +pub const DISPLAY_DEVICE_MULTI_DRIVER: ::DWORD = 0x00000002; +pub const DISPLAY_DEVICE_PRIMARY_DEVICE: ::DWORD = 0x00000004; +pub const DISPLAY_DEVICE_MIRRORING_DRIVER: ::DWORD = 0x00000008; +pub const DISPLAY_DEVICE_VGA_COMPATIBLE: ::DWORD = 0x00000010; +pub const DISPLAY_DEVICE_REMOVABLE: ::DWORD = 0x00000020; +pub const DISPLAY_DEVICE_ACC_DRIVER: ::DWORD = 0x00000040; +pub const DISPLAY_DEVICE_MODESPRUNED: ::DWORD = 0x08000000; +pub const DISPLAY_DEVICE_REMOTE: ::DWORD = 0x04000000; +pub const DISPLAY_DEVICE_DISCONNECT: ::DWORD = 0x02000000; +pub const DISPLAY_DEVICE_TS_COMPATIBLE: ::DWORD = 0x00200000; +pub const DISPLAY_DEVICE_UNSAFE_MODES_ON: ::DWORD = 0x00080000; +pub const DISPLAY_DEVICE_ACTIVE: ::DWORD = 0x00000001; +pub const DISPLAY_DEVICE_ATTACHED: ::DWORD = 0x00000002; +pub const DM_ORIENTATION: ::DWORD = 0x00000001; +pub const DM_PAPERSIZE: ::DWORD = 0x00000002; +pub const DM_PAPERLENGTH: ::DWORD = 0x00000004; +pub const DM_PAPERWIDTH: ::DWORD = 0x00000008; +pub const DM_SCALE: ::DWORD = 0x00000010; +pub const DM_POSITION: ::DWORD = 0x00000020; +pub const DM_NUP: ::DWORD = 0x00000040; +pub const DM_DISPLAYORIENTATION: ::DWORD = 0x00000080; +pub const DM_COPIES: ::DWORD = 0x00000100; +pub const DM_DEFAULTSOURCE: ::DWORD = 0x00000200; +pub const DM_PRINTQUALITY: ::DWORD = 0x00000400; +pub const DM_COLOR: ::DWORD = 0x00000800; +pub const DM_DUPLEX: ::DWORD = 0x00001000; +pub const DM_YRESOLUTION: ::DWORD = 0x00002000; +pub const DM_TTOPTION: ::DWORD = 0x00004000; +pub const DM_COLLATE: ::DWORD = 0x00008000; +pub const DM_FORMNAME: ::DWORD = 0x00010000; +pub const DM_LOGPIXELS: ::DWORD = 0x00020000; +pub const DM_BITSPERPEL: ::DWORD = 0x00040000; +pub const DM_PELSWIDTH: ::DWORD = 0x00080000; +pub const DM_PELSHEIGHT: ::DWORD = 0x00100000; +pub const DM_DISPLAYFLAGS: ::DWORD = 0x00200000; +pub const DM_DISPLAYFREQUENCY: ::DWORD = 0x00400000; +pub const DM_ICMMETHOD: ::DWORD = 0x00800000; +pub const DM_ICMINTENT: ::DWORD = 0x01000000; +pub const DM_MEDIATYPE: ::DWORD = 0x02000000; +pub const DM_DITHERTYPE: ::DWORD = 0x04000000; +pub const DM_PANNINGWIDTH: ::DWORD = 0x08000000; +pub const DM_PANNINGHEIGHT: ::DWORD = 0x10000000; +pub const DM_DISPLAYFIXEDOUTPUT: ::DWORD = 0x20000000; +pub const PFD_TYPE_RGBA: ::BYTE = 0; +pub const PFD_TYPE_COLORINDEX: ::BYTE = 1; +pub const PFD_MAIN_PLANE: ::BYTE = 0; +pub const PFD_OVERLAY_PLANE: ::BYTE = 1; +pub const PFD_UNDERLAY_PLANE: ::BYTE = 0xFF; +pub const PFD_DOUBLEBUFFER: ::DWORD = 0x00000001; +pub const PFD_STEREO: ::DWORD = 0x00000002; +pub const PFD_DRAW_TO_WINDOW: ::DWORD = 0x00000004; +pub const PFD_DRAW_TO_BITMAP: ::DWORD = 0x00000008; +pub const PFD_SUPPORT_GDI: ::DWORD = 0x00000010; +pub const PFD_SUPPORT_OPENGL: ::DWORD = 0x00000020; +pub const PFD_GENERIC_FORMAT: ::DWORD = 0x00000040; +pub const PFD_NEED_PALETTE: ::DWORD = 0x00000080; +pub const PFD_NEED_SYSTEM_PALETTE: ::DWORD = 0x00000100; +pub const PFD_SWAP_EXCHANGE: ::DWORD = 0x00000200; +pub const PFD_SWAP_COPY: ::DWORD = 0x00000400; +pub const PFD_SWAP_LAYER_BUFFERS: ::DWORD = 0x00000800; +pub const PFD_GENERIC_ACCELERATED: ::DWORD = 0x00001000; +pub const PFD_SUPPORT_DIRECTDRAW: ::DWORD = 0x00002000; +pub const PFD_DIRECT3D_ACCELERATED: ::DWORD = 0x00004000; +pub const PFD_SUPPORT_COMPOSITION: ::DWORD = 0x00008000; +pub const PFD_DEPTH_DONTCARE: ::DWORD = 0x20000000; +pub const PFD_DOUBLEBUFFER_DONTCARE: ::DWORD = 0x40000000; +pub const PFD_STEREO_DONTCARE: ::DWORD = 0x80000000; +pub const CCHFORMNAME: usize = 32; +STRUCT!{struct DEVMODEA { + dmDeviceName: [::CHAR; ::CCHDEVICENAME], + dmSpecVersion: ::WORD, + dmDriverVersion: ::WORD, + dmSize: ::WORD, + dmDriverExtra: ::WORD, + dmFields: ::DWORD, + union1: [u8; 16], + dmColor: ::c_short, + dmDuplex: ::c_short, + dmYResolution: ::c_short, + dmTTOption: ::c_short, + dmCollate: ::c_short, + dmFormName: [::CHAR; CCHFORMNAME], + dmLogPixels: ::WORD, + dmBitsPerPel: ::DWORD, + dmPelsWidth: ::DWORD, + dmPelsHeight: ::DWORD, + dmDisplayFlags: ::DWORD, + dmDisplayFrequency: ::DWORD, + dmICMMethod: ::DWORD, + dmICMIntent: ::DWORD, + dmMediaType: ::DWORD, + dmDitherType: ::DWORD, + dmReserved1: ::DWORD, + dmReserved2: ::DWORD, + dmPanningWidth: ::DWORD, + dmPanningHeight: ::DWORD, +}} +pub type PDEVMODEA = *mut DEVMODEA; +pub type NPDEVMODEA = *mut DEVMODEA; +pub type LPDEVMODEA = *mut DEVMODEA; +STRUCT!{struct DEVMODEW { + dmDeviceName: [::WCHAR; ::CCHDEVICENAME], + dmSpecVersion: ::WORD, + dmDriverVersion: ::WORD, + dmSize: ::WORD, + dmDriverExtra: ::WORD, + dmFields: ::DWORD, + union1: [u8; 16], + dmColor: ::c_short, + dmDuplex: ::c_short, + dmYResolution: ::c_short, + dmTTOption: ::c_short, + dmCollate: ::c_short, + dmFormName: [::WCHAR; CCHFORMNAME], + dmLogPixels: ::WORD, + dmBitsPerPel: ::DWORD, + dmPelsWidth: ::DWORD, + dmPelsHeight: ::DWORD, + dmDisplayFlags: ::DWORD, + dmDisplayFrequency: ::DWORD, + dmICMMethod: ::DWORD, + dmICMIntent: ::DWORD, + dmMediaType: ::DWORD, + dmDitherType: ::DWORD, + dmReserved1: ::DWORD, + dmReserved2: ::DWORD, + dmPanningWidth: ::DWORD, + dmPanningHeight: ::DWORD, +}} +pub type PDEVMODEW = *mut DEVMODEW; +pub type NPDEVMODEW = *mut DEVMODEW; +pub type LPDEVMODEW = *mut DEVMODEW; +STRUCT!{nodebug struct DISPLAY_DEVICEW { + cb: ::DWORD, + DeviceName: [::WCHAR; 32], + DeviceString: [::WCHAR; 128], + StateFlags: ::DWORD, + DeviceID: [::WCHAR; 128], + DeviceKey: [::WCHAR; 128], +}} +pub type PDISPLAY_DEVICEW = *mut DISPLAY_DEVICEW; +pub type LPDISPLAY_DEVICEW = *mut DISPLAY_DEVICEW; +STRUCT!{nodebug struct DISPLAY_DEVICEA { + cb: ::DWORD, + DeviceName: [::CHAR; 32], + DeviceString: [::CHAR; 128], + StateFlags: ::DWORD, + DeviceID: [::CHAR; 128], + DeviceKey: [::CHAR; 128], +}} +pub type PDISPLAY_DEVICEA = *mut DISPLAY_DEVICEA; +pub type LPDISPLAY_DEVICEA = *mut DISPLAY_DEVICEA; +STRUCT!{struct PIXELFORMATDESCRIPTOR { + nSize: ::WORD, + nVersion: ::WORD, + dwFlags: ::DWORD, + iPixelType: ::BYTE, + cColorBits: ::BYTE, + cRedBits: ::BYTE, + cRedShift: ::BYTE, + cGreenBits: ::BYTE, + cGreenShift: ::BYTE, + cBlueBits: ::BYTE, + cBlueShift: ::BYTE, + cAlphaBits: ::BYTE, + cAlphaShift: ::BYTE, + cAccumBits: ::BYTE, + cAccumRedBits: ::BYTE, + cAccumGreenBits: ::BYTE, + cAccumBlueBits: ::BYTE, + cAccumAlphaBits: ::BYTE, + cDepthBits: ::BYTE, + cStencilBits: ::BYTE, + cAuxBuffers: ::BYTE, + iLayerType: ::BYTE, + bReserved: ::BYTE, + dwLayerMask: ::DWORD, + dwVisibleMask: ::DWORD, + dwDamageMask: ::DWORD, +}} +pub type PPIXELFORMATDESCRIPTOR = *mut PIXELFORMATDESCRIPTOR; +pub type LPPIXELFORMATDESCRIPTOR = *mut PIXELFORMATDESCRIPTOR; +pub const R2_BLACK: ::c_int = 1; +pub const R2_NOTMERGEPEN: ::c_int = 2; +pub const R2_MASKNOTPEN: ::c_int = 3; +pub const R2_NOTCOPYPEN: ::c_int = 4; +pub const R2_MASKPENNOT: ::c_int = 5; +pub const R2_NOT: ::c_int = 6; +pub const R2_XORPEN: ::c_int = 7; +pub const R2_NOTMASKPEN: ::c_int = 8; +pub const R2_MASKPEN: ::c_int = 9; +pub const R2_NOTXORPEN: ::c_int = 10; +pub const R2_NOP: ::c_int = 11; +pub const R2_MERGENOTPEN: ::c_int = 12; +pub const R2_COPYPEN: ::c_int = 13; +pub const R2_MERGEPENNOT: ::c_int = 14; +pub const R2_MERGEPEN: ::c_int = 15; +pub const R2_WHITE: ::c_int = 16; +pub const R2_LAST: ::c_int = 16; +//83 +pub const SRCCOPY: ::DWORD = 0x00CC0020; +pub const SRCPAINT: ::DWORD = 0x00EE0086; +pub const SRCAND: ::DWORD = 0x008800C6; +pub const SRCINVERT: ::DWORD = 0x00660046; +pub const SRCERASE: ::DWORD = 0x00440328; +pub const NOTSRCCOPY: ::DWORD = 0x00330008; +pub const NOTSRCERASE: ::DWORD = 0x001100A6; +pub const MERGECOPY: ::DWORD = 0x00C000CA; +pub const MERGEPAINT: ::DWORD = 0x00BB0226; +pub const PATCOPY: ::DWORD = 0x00F00021; +pub const PATPAINT: ::DWORD = 0x00FB0A09; +pub const PATINVERT: ::DWORD = 0x005A0049; +pub const DSTINVERT: ::DWORD = 0x00550009; +pub const BLACKNESS: ::DWORD = 0x00000042; +pub const WHITENESS: ::DWORD = 0x00FF0062; +//121 +// fnCombineMode values for CombineRgn +pub const RGN_AND: ::c_int = 1; +pub const RGN_OR: ::c_int = 2; +pub const RGN_XOR: ::c_int = 3; +pub const RGN_DIFF: ::c_int = 4; +pub const RGN_COPY: ::c_int = 5; +pub const RGN_MIN: ::c_int = RGN_AND; +pub const RGN_MAX: ::c_int = RGN_COPY; +//572 (Win 7 SDK) +STRUCT!{struct BITMAP { + bmType: ::LONG, + bmWidth: ::LONG, + bmHeight: ::LONG, + bmWidthBytes: ::LONG, + bmPlanes: ::WORD, + bmBitsPixel: ::WORD, + bmBits: ::LPVOID, +}} +pub type PBITMAP = *mut BITMAP; +pub type NPBITMAP = *mut BITMAP; +pub type LPBITMAP = *mut BITMAP; +STRUCT!{struct RGBQUAD { + rgbBlue: ::BYTE, + rgbGreen: ::BYTE, + rgbRed: ::BYTE, + rgbReserved: ::BYTE, +}} +pub type LPRGBQUAD = *mut RGBQUAD; +pub const CS_ENABLE: ::DWORD = 0x00000001; +pub const CS_DISABLE: ::DWORD = 0x00000002; +pub const CS_DELETE_TRANSFORM: ::DWORD = 0x00000003; +pub const LCS_SIGNATURE: ::DWORD = 0x5053_4F43; // 'PSOC' +pub const LCS_sRGB: LCSCSTYPE = 0x7352_4742; // 'sRGB' +pub const LCS_WINDOWS_COLOR_SPACE: LCSCSTYPE = 0x5769_6E20; // 'Win ' +pub type LCSCSTYPE = ::LONG; +pub const LCS_CALIBRATED_RGB: LCSCSTYPE = 0x00000000; +pub type LCSGAMUTMATCH = ::LONG; +pub const LCS_GM_BUSINESS: LCSGAMUTMATCH = 0x00000001; +pub const LCS_GM_GRAPHICS: LCSGAMUTMATCH = 0x00000002; +pub const LCS_GM_IMAGES: LCSGAMUTMATCH = 0x00000004; +pub const LCS_GM_ABS_COLORIMETRIC: LCSGAMUTMATCH = 0x00000008; +pub const CM_OUT_OF_GAMUT: ::BYTE = 255; +pub const CM_IN_GAMUT: ::BYTE = 0; +pub const ICM_ADDPROFILE: ::UINT = 1; +pub const ICM_DELETEPROFILE: ::UINT = 2; +pub const ICM_QUERYPROFILE: ::UINT = 3; +pub const ICM_SETDEFAULTPROFILE: ::UINT = 4; +pub const ICM_REGISTERICMATCHER: ::UINT = 5; +pub const ICM_UNREGISTERICMATCHER: ::UINT = 6; +pub const ICM_QUERYMATCH: ::UINT = 7; +pub type FXPT16DOT16 = ::c_long; +pub type LPFXPT16DOT16 = *mut ::c_long; +pub type FXPT2DOT30 = ::c_long; +pub type LPFXPT2DOT30 = *mut ::c_long; +STRUCT!{struct CIEXYZ { + ciexyzX: FXPT2DOT30, + ciexyzY: FXPT2DOT30, + ciexyzZ: FXPT2DOT30, +}} +pub type LPCIEXYZ = *mut CIEXYZ; +STRUCT!{struct CIEXYZTRIPLE { + ciexyzRed: CIEXYZ, + ciexyzGreen: CIEXYZ, + ciexyzBlue: CIEXYZ, +}} +pub type LPCIEXYZTRIPLE = *mut CIEXYZTRIPLE; +//716 (Win 7 SDK) +STRUCT!{struct BITMAPINFOHEADER { + biSize: ::DWORD, + biWidth: ::LONG, + biHeight: ::LONG, + biPlanes: ::WORD, + biBitCount: ::WORD, + biCompression: ::DWORD, + biSizeImage: ::DWORD, + biXPelsPerMeter: ::LONG, + biYPelsPerMeter: ::LONG, + biClrUsed: ::DWORD, + biClrImportant: ::DWORD, +}} +pub type LPBITMAPINFOHEADER = *mut BITMAPINFOHEADER; +pub type PBITMAPINFOHEADER = *mut BITMAPINFOHEADER; +STRUCT!{struct BITMAPV5HEADER { + bV5Size: ::DWORD, + bV5Width: ::LONG, + bV5Height: ::LONG, + bV5Planes: ::WORD, + bV5BitCount: ::WORD, + bV5Compression: ::DWORD, + bV5SizeImage: ::DWORD, + bV5XPelsPerMeter: ::LONG, + bV5YPelsPerMeter: ::LONG, + bV5ClrUsed: ::DWORD, + bV5ClrImportant: ::DWORD, + bV5RedMask: ::DWORD, + bV5GreenMask: ::DWORD, + bV5BlueMask: ::DWORD, + bV5AlphaMask: ::DWORD, + bV5CSType: ::LONG, // LONG to match LOGCOLORSPACE + bV5Endpoints: CIEXYZTRIPLE, + bV5GammaRed: ::DWORD, + bV5GammaGreen: ::DWORD, + bV5GammaBlue: ::DWORD, + bV5Intent: ::LONG, // LONG to match LOGCOLORSPACE + bV5ProfileData: ::DWORD, + bV5ProfileSize: ::DWORD, + bV5Reserved: ::DWORD, +}} +pub type LPBITMAPV5HEADER = *mut BITMAPV5HEADER; +pub type PBITMAPV5HEADER = *mut BITMAPV5HEADER; +pub const PROFILE_LINKED: ::LONG = 0x4C49_4E4B; // 'LINK' +pub const PROFILE_EMBEDDED: ::LONG = 0x4D42_4544; // 'MBED' +pub const BI_RGB: ::DWORD = 0; +pub const BI_RLE8: ::DWORD = 1; +pub const BI_RLE4: ::DWORD = 2; +pub const BI_BITFIELDS: ::DWORD = 3; +pub const BI_JPEG: ::DWORD = 4; +pub const BI_PNG: ::DWORD = 5; +STRUCT!{struct BITMAPINFO { + bmiHeader: BITMAPINFOHEADER, + bmiColors: [RGBQUAD; 0], +}} +pub type LPBITMAPINFO = *mut BITMAPINFO; +pub type PBITMAPINFO = *mut BITMAPINFO; +//1438 +pub const LF_FACESIZE: usize = 32; +STRUCT!{nodebug struct LOGFONTA { + lfHeight: ::LONG, + lfWidth: ::LONG, + lfEscapement: ::LONG, + lfOrientation: ::LONG, + lfWeight: ::LONG, + lfItalic: ::BYTE, + lfUnderline: ::BYTE, + lfStrikeOut: ::BYTE, + lfCharSet: ::BYTE, + lfOutPrecision: ::BYTE, + lfClipPrecision: ::BYTE, + lfQuality: ::BYTE, + lfPitchAndFamily: ::BYTE, + lfFaceName: [::CHAR; LF_FACESIZE], +}} +pub type LPLOGFONTA = *mut LOGFONTA; +STRUCT!{nodebug struct LOGFONTW { + lfHeight: ::LONG, + lfWidth: ::LONG, + lfEscapement: ::LONG, + lfOrientation: ::LONG, + lfWeight: ::LONG, + lfItalic: ::BYTE, + lfUnderline: ::BYTE, + lfStrikeOut: ::BYTE, + lfCharSet: ::BYTE, + lfOutPrecision: ::BYTE, + lfClipPrecision: ::BYTE, + lfQuality: ::BYTE, + lfPitchAndFamily: ::BYTE, + lfFaceName: [::WCHAR; LF_FACESIZE], +}} +pub type LPLOGFONTW = *mut LOGFONTW; +//1595 +#[inline] +pub fn RGB (r: ::BYTE, g: ::BYTE, b: ::BYTE) -> ::COLORREF { + r as ::COLORREF | ((g as ::COLORREF) << 8) | ((b as ::COLORREF) << 16) +} +// +pub const DRIVERVERSION: ::c_int = 0; +pub const TECHNOLOGY: ::c_int = 2; +pub const HORZSIZE: ::c_int = 4; +pub const VERTSIZE: ::c_int = 6; +pub const HORZRES: ::c_int = 8; +pub const VERTRES: ::c_int = 10; +pub const BITSPIXEL: ::c_int = 12; +pub const PLANES: ::c_int = 14; +pub const NUMBRUSHES: ::c_int = 16; +pub const NUMPENS: ::c_int = 18; +pub const NUMMARKERS: ::c_int = 20; +pub const NUMFONTS: ::c_int = 22; +pub const NUMCOLORS: ::c_int = 24; +pub const PDEVICESIZE: ::c_int = 26; +pub const CURVECAPS: ::c_int = 28; +pub const LINECAPS: ::c_int = 30; +pub const POLYGONALCAPS: ::c_int = 32; +pub const TEXTCAPS: ::c_int = 34; +pub const CLIPCAPS: ::c_int = 36; +pub const RASTERCAPS: ::c_int = 38; +pub const ASPECTX: ::c_int = 40; +pub const ASPECTY: ::c_int = 42; +pub const ASPECTXY: ::c_int = 44; +pub const LOGPIXELSX: ::c_int = 88; +pub const LOGPIXELSY: ::c_int = 90; +pub const SIZEPALETTE: ::c_int = 104; +pub const NUMRESERVED: ::c_int = 106; +pub const COLORRES: ::c_int = 108; +pub const PHYSICALWIDTH: ::c_int = 110; +pub const PHYSICALHEIGHT: ::c_int = 111; +pub const PHYSICALOFFSETX: ::c_int = 112; +pub const PHYSICALOFFSETY: ::c_int = 113; +pub const SCALINGFACTORX: ::c_int = 114; +pub const SCALINGFACTORY: ::c_int = 115; +pub const VREFRESH: ::c_int = 116; +pub const DESKTOPVERTRES: ::c_int = 117; +pub const DESKTOPHORZRES: ::c_int = 118; +pub const BLTALIGNMENT: ::c_int = 119; +pub const SHADEBLENDCAPS: ::c_int = 120; +pub const COLORMGMTCAPS: ::c_int = 121; +//1906 +pub const DIB_RGB_COLORS: ::UINT = 0; +pub const DIB_PAL_COLORS: ::UINT = 1; +pub const CBM_INIT: ::DWORD = 4; +STRUCT!{struct RGNDATAHEADER { + dwSize: ::DWORD, + iType: ::DWORD, + nCount: ::DWORD, + nRgnSize: ::DWORD, + rcBound: ::RECT, +}} +pub type PRGNDATAHEADER = *mut RGNDATAHEADER; +STRUCT!{nodebug struct RGNDATA { + rdh: RGNDATAHEADER, + Buffer: [::c_char; 0], +}} +pub type PRGNDATA = *mut RGNDATA; +pub type NPRGNDATA = *mut RGNDATA; +pub type LPRGNDATA = *mut RGNDATA; +STRUCT!{struct PALETTEENTRY { + peRed: ::BYTE, + peGreen: ::BYTE, + peBlue: ::BYTE, + peFlags: ::BYTE, +}} +pub type PPALETTEENTRY = *mut PALETTEENTRY; +pub type LPPALETTEENTRY = *mut PALETTEENTRY; +//2824 (Win 7 SDK) +STRUCT!{struct ABC { + abcA: ::c_int, + abcB: ::UINT, + abcC: ::c_int, +}} +pub type PABC = *mut ABC; +pub type NPABC = *mut ABC; +pub type LPABC = *mut ABC; +STRUCT!{struct ABCFLOAT { + abcfA: ::FLOAT, + abcfB: ::FLOAT, + abcfC: ::FLOAT, +}} +pub type PABCFLOAT = *mut ABCFLOAT; +pub type NPABCFLOAT = *mut ABCFLOAT; +pub type LPABCFLOAT = *mut ABCFLOAT; +//3581 +pub type LINEDDAPROC = Option; +STRUCT!{struct XFORM { + eM11: ::FLOAT, + eM12: ::FLOAT, + eM21: ::FLOAT, + eM22: ::FLOAT, + eDx: ::FLOAT, + eDy: ::FLOAT, +}} +pub type PXFORM = *mut XFORM; +pub type LPXFORM = *mut XFORM; +STRUCT!{struct LOGBRUSH { + lbStyle: ::UINT, + lbColor: ::COLORREF, + lbHatch: ::ULONG_PTR, +}} +pub type PLOGBRUSH = *mut LOGBRUSH; +STRUCT!{nodebug struct LOGCOLORSPACEA { + lcsSignature: ::DWORD, + lcsVersion: ::DWORD, + lcsSize: ::DWORD, + lcsCSType: LCSCSTYPE, + lcsIntent: LCSGAMUTMATCH, + lcsEndpoints: CIEXYZTRIPLE, + lcsGammaRed: ::DWORD, + lcsGammaGreen: ::DWORD, + lcsGammaBlue: ::DWORD, + lcsFilename: [::CHAR; ::MAX_PATH], +}} +pub type LPLOGCOLORSPACEA = *mut LOGCOLORSPACEA; +STRUCT!{nodebug struct LOGCOLORSPACEW { + lcsSignature: ::DWORD, + lcsVersion: ::DWORD, + lcsSize: ::DWORD, + lcsCSType: LCSCSTYPE, + lcsIntent: LCSGAMUTMATCH, + lcsEndpoints: CIEXYZTRIPLE, + lcsGammaRed: ::DWORD, + lcsGammaGreen: ::DWORD, + lcsGammaBlue: ::DWORD, + lcsFilename: [::WCHAR; ::MAX_PATH], +}} +pub type LPLOGCOLORSPACEW = *mut LOGCOLORSPACEW; +pub const LF_FULLFACESIZE: usize = 64; +STRUCT!{nodebug struct ENUMLOGFONTEXA { + elfLogFont: LOGFONTA, + elfFullName: [::BYTE; LF_FULLFACESIZE], + elfStyle: [::BYTE; LF_FACESIZE], + elfScript: [::BYTE; LF_FACESIZE], +}} +pub type LPENUMLOGFONTEXA = *mut ENUMLOGFONTEXA; +STRUCT!{nodebug struct ENUMLOGFONTEXW { + elfLogFont: LOGFONTW, + elfFullName: [::WCHAR; LF_FULLFACESIZE], + elfStyle: [::WCHAR; LF_FACESIZE], + elfScript: [::WCHAR; LF_FACESIZE], +}} +pub type LPENUMLOGFONTEXW = *mut ENUMLOGFONTEXW; +pub const MM_MAX_NUMAXES: usize = 16; +STRUCT!{struct DESIGNVECTOR { + dvReserved: ::DWORD, + dvNumAxes: ::DWORD, + dvValues: [::LONG; MM_MAX_NUMAXES], +}} +pub type PDESIGNVECTOR = *mut DESIGNVECTOR; +pub type LPDESIGNVECTOR = *mut DESIGNVECTOR; +STRUCT!{nodebug struct ENUMLOGFONTEXDVA { + elfEnumLogfontEx: ENUMLOGFONTEXA, + elfDesignVector: DESIGNVECTOR, +}} +pub type PENUMLOGFONTEXDVA = *mut ENUMLOGFONTEXDVA; +pub type LPENUMLOGFONTEXDVA = *mut ENUMLOGFONTEXDVA; +STRUCT!{nodebug struct ENUMLOGFONTEXDVW { + elfEnumLogfontEx: ENUMLOGFONTEXW, + elfDesignVector: DESIGNVECTOR, +}} +pub type PENUMLOGFONTEXDVW = *mut ENUMLOGFONTEXDVW; +pub type LPENUMLOGFONTEXDVW = *mut ENUMLOGFONTEXDVW; +STRUCT!{struct LOGPALETTE { + palVersion: ::WORD, + palNumEntries: ::WORD, + palPalEntry: [PALETTEENTRY; 1], +}} +pub type PLOGPALETTE = *mut LOGPALETTE; +pub type NPLOGPALETTE = *mut LOGPALETTE; +pub type LPLOGPALETTE = *mut LOGPALETTE; +STRUCT!{struct LOGPEN { + lopnStyle: ::UINT, + lopnWidth: ::POINT, + lopnColor: ::COLORREF, +}} +pub type PLOGPEN = *mut LOGPEN; +pub type NPLOGPEN = *mut LOGPEN; +pub type LPLOGPEN = *mut LOGPEN; +STRUCT!{struct BLENDFUNCTION { + BlendOp: ::BYTE, + BlendFlags: ::BYTE, + SourceConstantAlpha: ::BYTE, + AlphaFormat: ::BYTE, +}} +pub type PBLENDFUNCTION = *mut BLENDFUNCTION; +pub const TMPF_FIXED_PITCH: ::BYTE = 0x01; +pub const TMPF_VECTOR: ::BYTE = 0x02; +pub const TMPF_DEVICE: ::BYTE = 0x08; +pub const TMPF_TRUETYPE: ::BYTE = 0x04; +STRUCT!{struct TEXTMETRICA { + tmHeight: ::LONG, + tmAscent: ::LONG, + tmDescent: ::LONG, + tmInternalLeading: ::LONG, + tmExternalLeading: ::LONG, + tmAveCharWidth: ::LONG, + tmMaxCharWidth: ::LONG, + tmWeight: ::LONG, + tmOverhang: ::LONG, + tmDigitizedAspectX: ::LONG, + tmDigitizedAspectY: ::LONG, + tmFirstChar: ::BYTE, + tmLastChar: ::BYTE, + tmDefaultChar: ::BYTE, + tmBreakChar: ::BYTE, + tmItalic: ::BYTE, + tmUnderlined: ::BYTE, + tmStruckOut: ::BYTE, + tmPitchAndFamily: ::BYTE, + tmCharSet: ::BYTE, +}} +pub type PTEXTMETRICA = *mut TEXTMETRICA; +pub type NPTEXTMETRICA = *mut TEXTMETRICA; +pub type LPTEXTMETRICA = *mut TEXTMETRICA; +STRUCT!{struct TEXTMETRICW { + tmHeight: ::LONG, + tmAscent: ::LONG, + tmDescent: ::LONG, + tmInternalLeading: ::LONG, + tmExternalLeading: ::LONG, + tmAveCharWidth: ::LONG, + tmMaxCharWidth: ::LONG, + tmWeight: ::LONG, + tmOverhang: ::LONG, + tmDigitizedAspectX: ::LONG, + tmDigitizedAspectY: ::LONG, + tmFirstChar: ::WCHAR, + tmLastChar: ::WCHAR, + tmDefaultChar: ::WCHAR, + tmBreakChar: ::WCHAR, + tmItalic: ::BYTE, + tmUnderlined: ::BYTE, + tmStruckOut: ::BYTE, + tmPitchAndFamily: ::BYTE, + tmCharSet: ::BYTE, +}} +pub type PTEXTMETRICW = *mut TEXTMETRICW; +pub type NPTEXTMETRICW = *mut TEXTMETRICW; +pub type LPTEXTMETRICW = *mut TEXTMETRICW; +pub const TA_NOUPDATECP: ::UINT = 0; +pub const TA_UPDATECP: ::UINT = 1; +pub const TA_LEFT: ::UINT = 0; +pub const TA_RIGHT: ::UINT = 2; +pub const TA_CENTER: ::UINT = 6; +pub const TA_TOP: ::UINT = 0; +pub const TA_BOTTOM: ::UINT = 8; +pub const TA_BASELINE: ::UINT = 24; +pub const TA_RTLREADING: ::UINT = 256; +pub const TA_MASK: ::UINT = TA_BASELINE + TA_CENTER + TA_UPDATECP + TA_RTLREADING; +pub const WHITE_BRUSH: ::c_int = 0; +pub const LTGRAY_BRUSH: ::c_int = 1; +pub const GRAY_BRUSH: ::c_int = 2; +pub const DKGRAY_BRUSH: ::c_int = 3; +pub const BLACK_BRUSH: ::c_int = 4; +pub const NULL_BRUSH: ::c_int = 5; +pub const HOLLOW_BRUSH: ::c_int = 5; +pub const WHITE_PEN: ::c_int = 6; +pub const BLACK_PEN: ::c_int = 7; +pub const NULL_PEN: ::c_int = 8; +pub const OEM_FIXED_FONT: ::c_int = 10; +pub const ANSI_FIXED_FONT: ::c_int = 11; +pub const ANSI_VAR_FONT: ::c_int = 12; +pub const SYSTEM_FONT: ::c_int = 13; +pub const DEVICE_DEFAULT_FONT: ::c_int = 14; +pub const DEFAULT_PALETTE: ::c_int = 15; +pub const SYSTEM_FIXED_FONT: ::c_int = 16; +pub const DEFAULT_GUI_FONT: ::c_int = 17; +pub const DC_BRUSH: ::c_int = 18; +pub const DC_PEN: ::c_int = 19; +pub const STOCK_LAST: ::c_int = 19;pub const PS_SOLID: ::c_int = 0; +pub const PS_DASH: ::c_int = 1; +pub const PS_DOT: ::c_int = 2; +pub const PS_DASHDOT: ::c_int = 3; +pub const PS_DASHDOTDOT: ::c_int = 4; +pub const PS_NULL: ::c_int = 5; +pub const PS_INSIDEFRAME: ::c_int = 6; +pub const PS_USERSTYLE: ::c_int = 7; +pub const PS_ALTERNATE: ::c_int = 8; +pub const TRANSPARENT: ::c_int = 1; +pub const OPAQUE: ::c_int = 2; +pub const BKMODE_LAST: ::c_int = 2; +pub const MM_TEXT: ::c_int = 1; +pub const MM_LOMETRIC: ::c_int = 2; +pub const MM_HIMETRIC: ::c_int = 3; +pub const MM_LOENGLISH: ::c_int = 4; +pub const MM_HIENGLISH: ::c_int = 5; +pub const MM_TWIPS: ::c_int = 6; +pub const MM_ISOTROPIC: ::c_int = 7; +pub const MM_ANISOTROPIC: ::c_int = 8; +pub const ALTERNATE: ::c_int = 1; +pub const WINDING: ::c_int = 2; +pub const POLYFILL_LAST: ::c_int = 2; +pub const OUT_DEFAULT_PRECIS: ::DWORD = 0; +pub const OUT_STRING_PRECIS: ::DWORD = 1; +pub const OUT_CHARACTER_PRECIS: ::DWORD = 2; +pub const OUT_STROKE_PRECIS: ::DWORD = 3; +pub const OUT_TT_PRECIS: ::DWORD = 4; +pub const OUT_DEVICE_PRECIS: ::DWORD = 5; +pub const OUT_RASTER_PRECIS: ::DWORD = 6; +pub const OUT_TT_ONLY_PRECIS: ::DWORD = 7; +pub const OUT_OUTLINE_PRECIS: ::DWORD = 8; +pub const OUT_SCREEN_OUTLINE_PRECIS: ::DWORD = 9; +pub const OUT_PS_ONLY_PRECIS: ::DWORD = 10; +pub const CLIP_DEFAULT_PRECIS: ::DWORD = 0; +pub const CLIP_CHARACTER_PRECIS: ::DWORD = 1; +pub const CLIP_STROKE_PRECIS: ::DWORD = 2; +pub const CLIP_MASK: ::DWORD = 0xf; +pub const CLIP_LH_ANGLES: ::DWORD = 1 << 4; +pub const CLIP_TT_ALWAYS: ::DWORD = 2 << 4; +pub const CLIP_DFA_DISABLE: ::DWORD = 4 << 4; +pub const CLIP_EMBEDDED: ::DWORD = 8 << 4; +pub const DEFAULT_QUALITY: ::DWORD = 0; +pub const DRAFT_QUALITY: ::DWORD = 1; +pub const PROOF_QUALITY: ::DWORD = 2; +pub const NONANTIALIASED_QUALITY: ::DWORD = 3; +pub const ANTIALIASED_QUALITY: ::DWORD = 4; +pub const CLEARTYPE_QUALITY: ::DWORD = 5; +pub const CLEARTYPE_NATURAL_QUALITY: ::DWORD = 6; +pub const DEFAULT_PITCH: ::DWORD = 0; +pub const FIXED_PITCH: ::DWORD = 1; +pub const VARIABLE_PITCH: ::DWORD = 2; +pub const FF_DONTCARE: ::DWORD = 0 << 4; +pub const FF_ROMAN: ::DWORD = 1 << 4; +pub const FF_SWISS: ::DWORD = 2 << 4; +pub const FF_MODERN: ::DWORD = 3 << 4; +pub const FF_SCRIPT: ::DWORD = 4 << 4; +pub const FF_DECORATIVE: ::DWORD = 5 << 4; +pub const MONO_FONT: ::DWORD = 8; +pub const ANSI_CHARSET: ::DWORD = 0; +pub const DEFAULT_CHARSET: ::DWORD = 1; +pub const SYMBOL_CHARSET: ::DWORD = 2; +pub const SHIFTJIS_CHARSET: ::DWORD = 128; +pub const HANGEUL_CHARSET: ::DWORD = 129; +pub const HANGUL_CHARSET: ::DWORD = 129; +pub const GB2312_CHARSET: ::DWORD = 134; +pub const CHINESEBIG5_CHARSET: ::DWORD = 136; +pub const OEM_CHARSET: ::DWORD = 255; +pub const JOHAB_CHARSET: ::DWORD = 130; +pub const HEBREW_CHARSET: ::DWORD = 177; +pub const ARABIC_CHARSET: ::DWORD = 178; +pub const GREEK_CHARSET: ::DWORD = 161; +pub const TURKISH_CHARSET: ::DWORD = 162; +pub const VIETNAMESE_CHARSET: ::DWORD = 163; +pub const THAI_CHARSET: ::DWORD = 222; +pub const EASTEUROPE_CHARSET: ::DWORD = 238; +pub const RUSSIAN_CHARSET: ::DWORD = 204; +pub const MAC_CHARSET: ::DWORD = 77; +pub const BALTIC_CHARSET: ::DWORD = 186; +pub const FS_LATIN1: ::DWORD = 0x00000001; +pub const FS_LATIN2: ::DWORD = 0x00000002; +pub const FS_CYRILLIC: ::DWORD = 0x00000004; +pub const FS_GREEK: ::DWORD = 0x00000008; +pub const FS_TURKISH: ::DWORD = 0x00000010; +pub const FS_HEBREW: ::DWORD = 0x00000020; +pub const FS_ARABIC: ::DWORD = 0x00000040; +pub const FS_BALTIC: ::DWORD = 0x00000080; +pub const FS_VIETNAMESE: ::DWORD = 0x00000100; +pub const FS_THAI: ::DWORD = 0x00010000; +pub const FS_JISJAPAN: ::DWORD = 0x00020000; +pub const FS_CHINESESIMP: ::DWORD = 0x00040000; +pub const FS_WANSUNG: ::DWORD = 0x00080000; +pub const FS_CHINESETRAD: ::DWORD = 0x00100000; +pub const FS_JOHAB: ::DWORD = 0x00200000; +pub const FS_SYMBOL: ::DWORD = 0x80000000; +pub const FW_DONTCARE: ::c_int = 0; +pub const FW_THIN: ::c_int = 100; +pub const FW_EXTRALIGHT: ::c_int = 200; +pub const FW_LIGHT: ::c_int = 300; +pub const FW_NORMAL: ::c_int = 400; +pub const FW_MEDIUM: ::c_int = 500; +pub const FW_SEMIBOLD: ::c_int = 600; +pub const FW_BOLD: ::c_int = 700; +pub const FW_EXTRABOLD: ::c_int = 800; +pub const FW_HEAVY: ::c_int = 900; +pub const FW_ULTRALIGHT: ::c_int = FW_EXTRALIGHT; +pub const FW_REGULAR: ::c_int = FW_NORMAL; +pub const FW_DEMIBOLD: ::c_int = FW_SEMIBOLD; +pub const FW_ULTRABOLD: ::c_int = FW_EXTRABOLD; +pub const FW_BLACK: ::c_int = FW_HEAVY; +pub type COLOR16 = ::c_ushort; +STRUCT!{struct TRIVERTEX { + x: ::LONG, + y: ::LONG, + Red: COLOR16, + Green: COLOR16, + Blue: COLOR16, + Alpha: COLOR16, +}} +pub type PTRIVERTEX = *mut TRIVERTEX; +pub type LPTRIVERTEX = *mut TRIVERTEX; +STRUCT!{struct GRADIENT_RECT { + UpperLeft: ::ULONG, + LowerRight: ::ULONG, +}} +pub type PGRADIENT_RECT = *mut GRADIENT_RECT; +pub type LPGRADIENT_RECT = *mut GRADIENT_RECT; +/* Object Definitions for EnumObjects() */ +pub const OBJ_PEN: ::UINT = 1; +pub const OBJ_BRUSH: ::UINT = 2; +pub const OBJ_DC: ::UINT = 3; +pub const OBJ_METADC: ::UINT = 4; +pub const OBJ_PAL: ::UINT = 5; +pub const OBJ_FONT: ::UINT = 6; +pub const OBJ_BITMAP: ::UINT = 7; +pub const OBJ_REGION: ::UINT = 8; +pub const OBJ_METAFILE: ::UINT = 9; +pub const OBJ_MEMDC: ::UINT = 10; +pub const OBJ_EXTPEN: ::UINT = 11; +pub const OBJ_ENHMETADC: ::UINT = 12; +pub const OBJ_ENHMETAFILE: ::UINT = 13; +pub const OBJ_COLORSPACE: ::UINT = 14; +pub const GDI_OBJ_LAST: ::UINT = OBJ_COLORSPACE; +STRUCT!{struct COLORADJUSTMENT { + caSize: ::WORD, + caFlags: ::WORD, + caIlluminantIndex: ::WORD, + caRedGamma: ::WORD, + caGreenGamma: ::WORD, + caBlueGamma: ::WORD, + caReferenceBlack: ::WORD, + caReferenceWhite: ::WORD, + caContrast: ::SHORT, + caBrightness: ::SHORT, + caColorfulness: ::SHORT, + caRedGreenTint: ::SHORT, +}} +pub type PCOLORADJUSTMENT = *mut COLORADJUSTMENT; +pub type LPCOLORADJUSTMENT = *mut COLORADJUSTMENT; +pub type OLDFONTENUMPROCA = Option ::c_int>; +pub type OLDFONTENUMPROCW = Option ::c_int>; +pub type FONTENUMPROCA = OLDFONTENUMPROCA; +pub type FONTENUMPROCW = OLDFONTENUMPROCW; +STRUCT!{struct WCRANGE { + wcLow: ::WCHAR, + cGlyphs: ::USHORT, +}} +pub type PWCRANGE = *mut WCRANGE; +pub type LPWCRANGE = *mut WCRANGE; +STRUCT!{struct GLYPHSET { + cbThis: ::DWORD, + flAccel: ::DWORD, + cGlyphsSupported: ::DWORD, + cRanges: ::DWORD, + ranges: [WCRANGE;1], +}} +pub type PGLYPHSET = *mut GLYPHSET; +pub type LPGLYPHSET = *mut GLYPHSET; +pub type ABORTPROC = Option ::BOOL>; +STRUCT!{struct DOCINFOA { + cbSize: ::c_int, + lpszDocName: ::LPCSTR, + lpszOutput: ::LPCSTR, + lpszDatatype: ::LPCSTR, + fwType: ::DWORD, +}} +pub type LPDOCINFOA = *mut DOCINFOA; +STRUCT!{struct DOCINFOW { + cbSize: ::c_int, + lpszDocName: ::LPCWSTR, + lpszOutput: ::LPCWSTR, + lpszDatatype: ::LPCWSTR, + fwType: ::DWORD, +}} +pub type LPDOCINFOW = *mut DOCINFOW; +pub type ICMENUMPROCA = Option ::c_int>; +pub type ICMENUMPROCW = Option ::c_int>; +STRUCT!{struct HANDLETABLE { + objectHandle: [::HGDIOBJ; 1], +}} +pub type LPHANDLETABLE = *mut HANDLETABLE; +pub type PHANDLETABLE = *mut HANDLETABLE; +STRUCT!{struct METARECORD { + rdSize: ::DWORD, + rdFunction: ::WORD, + rdParm: [::WORD; 1], +}} +pub type PMETARECORD = *mut METARECORD; +pub type LPMETARECORD = *mut METARECORD; +pub type MFENUMPROC = Option ::c_int>; +pub type GOBJENUMPROC = Option ::c_int>; +STRUCT!{struct GCP_RESULTSA { + lStructSize: ::DWORD, + lpOutString: ::LPSTR, + lpOrder: *const ::UINT, + lpDx: *const ::c_int, + lpCaretPos: *const ::c_int, + lpClass: ::LPSTR, + lpGlyphs: ::LPWSTR, + nGlyphs: ::UINT, + nMaxFit: ::c_int, +}} +pub type LPGCP_RESULTSA = *mut GCP_RESULTSA; +STRUCT!{struct GCP_RESULTSW { + lStructSize: ::DWORD, + lpOutString: ::LPWSTR, + lpOrder: *const ::UINT, + lpDx: *const ::c_int, + lpCaretPos: *const ::c_int, + lpClass: ::LPSTR, + lpGlyphs: ::LPWSTR, + nGlyphs: ::UINT, + nMaxFit: ::c_int, +}} +pub type LPGCP_RESULTSW = *mut GCP_RESULTSW; +STRUCT!{struct FONTSIGNATURE { + fsUsb: [::DWORD; 4], + fsCsb: [::DWORD; 2], +}} +pub type LPFONTSIGNATURE = *mut FONTSIGNATURE; +pub type PFONTSIGNATURE = *mut FONTSIGNATURE; +STRUCT!{struct POLYTEXTA { + x: ::c_int, + y: ::c_int, + n: ::UINT, + lpstr: ::LPCSTR, + uiFlags: ::UINT, + rcl: ::RECT, + pdx: *const ::c_int, +}} +pub type PPOLYTEXTA = *mut POLYTEXTA; +pub type NPPOLYTEXTA = *mut POLYTEXTA; +pub type LPPOLYTEXTA = *mut POLYTEXTA; +STRUCT!{struct POLYTEXTW { + x: ::c_int, + y: ::c_int, + n: ::UINT, + lpstr: ::LPCWSTR, + uiFlags: ::UINT, + rcl: ::RECT, + pdx: *const ::c_int, +}} +pub type PPOLYTEXTW = *mut POLYTEXTW; +pub type NPPOLYTEXTW = *mut POLYTEXTW; +pub type LPPOLYTEXTW = *mut POLYTEXTW; +STRUCT!{struct CHARSETINFO { + ciCharset: ::UINT, + ciACP: ::UINT, + fs: ::FONTSIGNATURE, +}} +pub type PCHARSETINFO = *mut CHARSETINFO; +pub type NPCHARSETINFO = *mut CHARSETINFO; +pub type LPCHARSETINFO = *mut CHARSETINFO; +pub const GRADIENT_FILL_RECT_H: ::ULONG = 0x00000000; +pub const GRADIENT_FILL_RECT_V: ::ULONG = 0x00000001; +pub const GRADIENT_FILL_TRIANGLE: ::ULONG = 0x00000002; +pub const GRADIENT_FILL_OP_FLAG: ::ULONG = 0x000000ff; +STRUCT!{struct LAYERPLANEDESCRIPTOR { + nSize: ::WORD, + nVersion: ::WORD, + dwFlags: ::DWORD, + iPixelType: ::BYTE, + cColorBits: ::BYTE, + cRedBits: ::BYTE, + cRedShift: ::BYTE, + cGreenBits: ::BYTE, + cGreenShift: ::BYTE, + cBlueBits: ::BYTE, + cBlueShift: ::BYTE, + cAlphaBits: ::BYTE, + cAlphaShift: ::BYTE, + cAccumBits: ::BYTE, + cAccumRedBits: ::BYTE, + cAccumGreenBits: ::BYTE, + cAccumBlueBits: ::BYTE, + cAccumAlphaBits: ::BYTE, + cDepthBits: ::BYTE, + cStencilBits: ::BYTE, + cAuxBuffers: ::BYTE, + iLayerPlane: ::BYTE, + bReserved: ::BYTE, + crTransparent: ::COLORREF, +}} +pub type PLAYERPLANEDESCRIPTOR = *mut LAYERPLANEDESCRIPTOR; +pub type LPLAYERPLANEDESCRIPTOR = *mut LAYERPLANEDESCRIPTOR; +STRUCT!{struct ENHMETAHEADER { + iType: ::DWORD, + nSize: ::DWORD, + rclBounds: ::RECTL, + rclFrame: ::RECTL, + dSignature: ::DWORD, + nVersion: ::DWORD, + nBytes: ::DWORD, + nRecords: ::DWORD, + nHandles: ::WORD, + sReserved: ::WORD, + nDescription: ::DWORD, + offDescription: ::DWORD, + nPalEntries: ::DWORD, + szlDevice: ::SIZEL, + szlMillimeters: ::SIZEL, + cbPixelFormat: ::DWORD, + offPixelFormat: ::DWORD, + bOpenGL: ::DWORD, + szlMicrometers: ::SIZEL, +}} +pub type PENHMETAHEADER = *mut ENHMETAHEADER; +pub type LPENHMETAHEADER = *mut ENHMETAHEADER; +STRUCT!{struct FIXED { + fract: ::WORD, + value: ::c_short, +}} +STRUCT!{struct MAT2 { + eM11: FIXED, + eM12: FIXED, + eM21: FIXED, + eM22: FIXED, +}} +pub type LPMAT2 = *mut MAT2; +STRUCT!{struct GLYPHMETRICS { + gmBlackBoxX: ::UINT, + gmBlackBoxY: ::UINT, + gmptGlyphOrigin: ::POINT, + gmCellIncX: ::c_short, + gmCellIncY: ::c_short, +}} +pub type LPGLYPHMETRICS = *mut GLYPHMETRICS; +STRUCT!{struct KERNINGPAIR { + wFirst: ::WORD, + wSecond: ::WORD, + iKernAmount: ::c_int, +}} +pub type LPKERNINGPAIR = *mut KERNINGPAIR; +STRUCT!{struct PANOSE { + bFamilyType: ::BYTE, + bSerifStyle: ::BYTE, + bWeight: ::BYTE, + bProportion: ::BYTE, + bContrast: ::BYTE, + bStrokeVariation: ::BYTE, + bArmStyle: ::BYTE, + bLetterform: ::BYTE, + bMidline: ::BYTE, + bXHeight: ::BYTE, +}} +pub type LPPANOSE = *mut PANOSE; +STRUCT!{struct OUTLINETEXTMETRICA { + otmSize: ::UINT, + otmTextMetrics: TEXTMETRICA, + otmFiller: ::BYTE, + otmPanoseNumber: ::PANOSE, + otmfsSelection: ::UINT, + otmfsType: ::UINT, + otmsCharSlopeRise: ::c_int, + otmsCharSlopeRun: ::c_int, + otmItalicAngle: ::c_int, + otmEMSquare: ::UINT, + otmAscent: ::c_int, + otmDescent: ::c_int, + otmLineGap: ::UINT, + otmsCapEmHeight: ::UINT, + otmsXHeight: ::UINT, + otmrcFontBox: ::RECT, + otmMacAscent: ::c_int, + otmMacDescent: ::c_int, + otmMacLineGap: ::UINT, + otmusMinimumPPEM: ::UINT, + otmptSubscriptSize: ::POINT, + otmptSubscriptOffset: ::POINT, + otmptSuperscriptSize: ::POINT, + otmptSuperscriptOffset: ::POINT, + otmsStrikeoutSize: ::UINT, + otmsStrikeoutPosition: ::c_int, + otmsUnderscoreSize: ::c_int, + otmsUnderscorePosition: ::c_int, + otmpFamilyName: ::PSTR, + otmpFaceName: ::PSTR, + otmpStyleName: ::PSTR, + otmpFullName: ::PSTR, +}} +pub type POUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +pub type NPOUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +pub type LPOUTLINETEXTMETRICA = *mut OUTLINETEXTMETRICA; +STRUCT!{struct OUTLINETEXTMETRICW { + otmSize: ::UINT, + otmTextMetrics: TEXTMETRICW, + otmFiller: ::BYTE, + otmPanoseNumber: ::PANOSE, + otmfsSelection: ::UINT, + otmfsType: ::UINT, + otmsCharSlopeRise: ::c_int, + otmsCharSlopeRun: ::c_int, + otmItalicAngle: ::c_int, + otmEMSquare: ::UINT, + otmAscent: ::c_int, + otmDescent: ::c_int, + otmLineGap: ::UINT, + otmsCapEmHeight: ::UINT, + otmsXHeight: ::UINT, + otmrcFontBox: ::RECT, + otmMacAscent: ::c_int, + otmMacDescent: ::c_int, + otmMacLineGap: ::UINT, + otmusMinimumPPEM: ::UINT, + otmptSubscriptSize: ::POINT, + otmptSubscriptOffset: ::POINT, + otmptSuperscriptSize: ::POINT, + otmptSuperscriptOffset: ::POINT, + otmsStrikeoutSize: ::UINT, + otmsStrikeoutPosition: ::c_int, + otmsUnderscoreSize: ::c_int, + otmsUnderscorePosition: ::c_int, + otmpFamilyName: ::PSTR, + otmpFaceName: ::PSTR, + otmpStyleName: ::PSTR, + otmpFullName: ::PSTR, +}} +pub type POUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +pub type NPOUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +pub type LPOUTLINETEXTMETRICW = *mut OUTLINETEXTMETRICW; +STRUCT!{struct RASTERIZER_STATUS { + nSize: ::c_short, + wFlags: ::c_short, + nLanguageID: ::c_short, +}} +pub type LPRASTERIZER_STATUS = *mut RASTERIZER_STATUS; +STRUCT!{struct ENHMETARECORD { + iType: ::DWORD, + nSize: ::DWORD, + dParm: [::DWORD; 1], +}} +pub type PENHMETARECORD = *mut ENHMETARECORD; +pub type LPENHMETARECORD = *mut ENHMETARECORD; +STRUCT!{struct METAFILEPICT { + mm: ::LONG, + xExt: ::LONG, + yExt: ::LONG, + hMF: ::HMETAFILE, +}} +pub type LPMETAFILEPICT = *mut METAFILEPICT; +STRUCT!{struct POINTFLOAT { + x: ::FLOAT, + y: ::FLOAT, +}} +pub type PPOINTFLOAT = *mut POINTFLOAT; +STRUCT!{struct GLYPHMETRICSFLOAT { + gmfBlackBoxX: ::FLOAT, + gmfBlackBoxY: ::FLOAT, + gmfptGlyphOrigin: POINTFLOAT, + gmfCellIncX: ::FLOAT, + gmfCellIncY: ::FLOAT, +}} +pub type PGLYPHMETRICSFLOAT = *mut GLYPHMETRICSFLOAT; +pub type LPGLYPHMETRICSFLOAT = *mut GLYPHMETRICSFLOAT; +pub const DT_PLOTTER: ::c_int = 0; +pub const DT_RASDISPLAY: ::c_int = 1; +pub const DT_RASPRINTER: ::c_int = 2; +pub const DT_RASCAMERA: ::c_int = 3; +pub const DT_CHARSTREAM: ::c_int = 4; +pub const DT_METAFILE: ::c_int = 5; +pub const DT_DISPFILE: ::c_int = 6; +pub const CLR_INVALID: ::COLORREF = 0xFFFFFFFF; +pub const ETO_OPAQUE: ::UINT = 0x0002; +pub const ETO_CLIPPED: ::UINT = 0x0004; +pub const ETO_GLYPH_INDEX: ::UINT = 0x0010; +pub const ETO_RTLREADING: ::UINT = 0x0080; +pub const ETO_NUMERICSLOCAL: ::UINT = 0x0400; +pub const ETO_NUMERICSLATIN: ::UINT = 0x0800; +pub const ETO_IGNORELANGUAGE: ::UINT = 0x1000; +pub const ETO_PDY: ::UINT = 0x2000; +pub const ETO_REVERSE_INDEX_MAP: ::UINT = 0x10000; +STRUCT!{struct EXTLOGPEN { + elpPenStyle: ::DWORD, + elpWidth: ::DWORD, + elpBrushStyle: ::UINT, + elpColor: ::COLORREF, + elpHatch: ::ULONG_PTR, + elpNumEntries: ::DWORD, + elpStyleEntry: [::DWORD; 1], +}} +pub type PEXTLOGPEN = *mut EXTLOGPEN; +pub type NPEXTLOGPEN = *mut EXTLOGPEN; +pub type LPEXTLOGPEN = *mut EXTLOGPEN; +pub type ENHMFENUMPROC = Option ::c_int>; +/* Metafile Functions */ +pub const META_SETBKCOLOR: ::WORD = 0x0201; +pub const META_SETBKMODE: ::WORD = 0x0102; +pub const META_SETMAPMODE: ::WORD = 0x0103; +pub const META_SETROP2: ::WORD = 0x0104; +pub const META_SETRELABS: ::WORD = 0x0105; +pub const META_SETPOLYFILLMODE: ::WORD = 0x0106; +pub const META_SETSTRETCHBLTMODE: ::WORD = 0x0107; +pub const META_SETTEXTCHAREXTRA: ::WORD = 0x0108; +pub const META_SETTEXTCOLOR: ::WORD = 0x0209; +pub const META_SETTEXTJUSTIFICATION: ::WORD = 0x020A; +pub const META_SETWINDOWORG: ::WORD = 0x020B; +pub const META_SETWINDOWEXT: ::WORD = 0x020C; +pub const META_SETVIEWPORTORG: ::WORD = 0x020D; +pub const META_SETVIEWPORTEXT: ::WORD = 0x020E; +pub const META_OFFSETWINDOWORG: ::WORD = 0x020F; +pub const META_SCALEWINDOWEXT: ::WORD = 0x0410; +pub const META_OFFSETVIEWPORTORG: ::WORD = 0x0211; +pub const META_SCALEVIEWPORTEXT: ::WORD = 0x0412; +pub const META_LINETO: ::WORD = 0x0213; +pub const META_MOVETO: ::WORD = 0x0214; +pub const META_EXCLUDECLIPRECT: ::WORD = 0x0415; +pub const META_INTERSECTCLIPRECT: ::WORD = 0x0416; +pub const META_ARC: ::WORD = 0x0817; +pub const META_ELLIPSE: ::WORD = 0x0418; +pub const META_FLOODFILL: ::WORD = 0x0419; +pub const META_PIE: ::WORD = 0x081A; +pub const META_RECTANGLE: ::WORD = 0x041B; +pub const META_ROUNDRECT: ::WORD = 0x061C; +pub const META_PATBLT: ::WORD = 0x061D; +pub const META_SAVEDC: ::WORD = 0x001E; +pub const META_SETPIXEL: ::WORD = 0x041F; +pub const META_OFFSETCLIPRGN: ::WORD = 0x0220; +pub const META_TEXTOUT: ::WORD = 0x0521; +pub const META_BITBLT: ::WORD = 0x0922; +pub const META_STRETCHBLT: ::WORD = 0x0B23; +pub const META_POLYGON: ::WORD = 0x0324; +pub const META_POLYLINE: ::WORD = 0x0325; +pub const META_ESCAPE: ::WORD = 0x0626; +pub const META_RESTOREDC: ::WORD = 0x0127; +pub const META_FILLREGION: ::WORD = 0x0228; +pub const META_FRAMEREGION: ::WORD = 0x0429; +pub const META_INVERTREGION: ::WORD = 0x012A; +pub const META_PAINTREGION: ::WORD = 0x012B; +pub const META_SELECTCLIPREGION: ::WORD = 0x012C; +pub const META_SELECTOBJECT: ::WORD = 0x012D; +pub const META_SETTEXTALIGN: ::WORD = 0x012E; +pub const META_CHORD: ::WORD = 0x0830; +pub const META_SETMAPPERFLAGS: ::WORD = 0x0231; +pub const META_EXTTEXTOUT: ::WORD = 0x0a32; +pub const META_SETDIBTODEV: ::WORD = 0x0d33; +pub const META_SELECTPALETTE: ::WORD = 0x0234; +pub const META_REALIZEPALETTE: ::WORD = 0x0035; +pub const META_ANIMATEPALETTE: ::WORD = 0x0436; +pub const META_SETPALENTRIES: ::WORD = 0x0037; +pub const META_POLYPOLYGON: ::WORD = 0x0538; +pub const META_RESIZEPALETTE: ::WORD = 0x0139; +pub const META_DIBBITBLT: ::WORD = 0x0940; +pub const META_DIBSTRETCHBLT: ::WORD = 0x0b41; +pub const META_DIBCREATEPATTERNBRUSH: ::WORD = 0x0142; +pub const META_STRETCHDIB: ::WORD = 0x0f43; +pub const META_EXTFLOODFILL: ::WORD = 0x0548; +pub const META_SETLAYOUT: ::WORD = 0x0149; +pub const META_DELETEOBJECT: ::WORD = 0x01f0; +pub const META_CREATEPALETTE: ::WORD = 0x00f7; +pub const META_CREATEPATTERNBRUSH: ::WORD = 0x01F9; +pub const META_CREATEPENINDIRECT: ::WORD = 0x02FA; +pub const META_CREATEFONTINDIRECT: ::WORD = 0x02FB; +pub const META_CREATEBRUSHINDIRECT: ::WORD = 0x02FC; +pub const META_CREATEREGION: ::WORD = 0x06FF; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winhttp.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winhttp.rs new file mode 100644 index 0000000..e8ca6f6 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winhttp.rs @@ -0,0 +1,441 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Windows HTTP Services API constant definitions and macros +//54 +pub type HINTERNET = ::LPVOID; +pub type LPHINTERNET = *mut HINTERNET; +pub type INTERNET_PORT = ::WORD; +pub type LPINTERNET_PORT = *mut INTERNET_PORT; +pub const INTERNET_DEFAULT_PORT: INTERNET_PORT = 0; +pub const INTERNET_DEFAULT_HTTP_PORT: INTERNET_PORT = 80; +pub const INTERNET_DEFAULT_HTTPS_PORT: INTERNET_PORT = 443; +pub const WINHTTP_FLAG_ASYNC: ::DWORD = 0x10000000; +pub const WINHTTP_FLAG_SECURE: ::DWORD = 0x00800000; +pub const WINHTTP_FLAG_ESCAPE_PERCENT: ::DWORD = 0x00000004; +pub const WINHTTP_FLAG_NULL_CODEPAGE: ::DWORD = 0x00000008; +pub const WINHTTP_FLAG_BYPASS_PROXY_CACHE: ::DWORD = 0x00000100; +pub const WINHTTP_FLAG_REFRESH: ::DWORD = WINHTTP_FLAG_BYPASS_PROXY_CACHE; +pub const WINHTTP_FLAG_ESCAPE_DISABLE: ::DWORD = 0x00000040; +pub const WINHTTP_FLAG_ESCAPE_DISABLE_QUERY: ::DWORD = 0x00000080; +STRUCT!{struct WINHTTP_ASYNC_RESULT { + dwResult: ::DWORD_PTR, + dwError: ::DWORD, +}} +pub type LPWINHTTP_ASYNC_RESULT = *mut WINHTTP_ASYNC_RESULT; +pub type INTERNET_SCHEME = ::c_int; +pub type LPINTERNET_SCHEME = *mut ::c_int; +pub const INTERNET_SCHEME_HTTP: INTERNET_SCHEME = 1; +pub const INTERNET_SCHEME_HTTPS: INTERNET_SCHEME = 2; +pub const INTERNET_SCHEME_FTP: INTERNET_SCHEME = 3; +pub const INTERNET_SCHEME_SOCKS: INTERNET_SCHEME = 4; +STRUCT!{struct URL_COMPONENTS { + dwStructSize: ::DWORD, + lpszScheme: ::LPWSTR, + dwSchemeLength: ::DWORD, + nScheme: INTERNET_SCHEME, + lpszHostName: ::LPWSTR, + dwHostNameLength: ::DWORD, + nPort: INTERNET_PORT, + lpszUserName: ::LPWSTR, + dwUserNameLength: ::DWORD, + lpszPassword: ::LPWSTR, + dwPasswordLength: ::DWORD, + lpszUrlPath: ::LPWSTR, + dwUrlPathLength: ::DWORD, + lpszExtraInfo: ::LPWSTR, + dwExtraInfoLength: ::DWORD, +}} +pub type LPURL_COMPONENTS = *mut URL_COMPONENTS; +pub type URL_COMPONENTSW = URL_COMPONENTS; +pub type LPURL_COMPONENTSW = LPURL_COMPONENTS; +STRUCT!{struct WINHTTP_PROXY_INFO { + dwAccessType: ::DWORD, + lpszProxy: ::LPWSTR, + lpszProxyBypass: ::LPWSTR, +}} +pub type LPWINHTTP_PROXY_INFO = *mut WINHTTP_PROXY_INFO; +pub type WINHTTP_PROXY_INFOW = WINHTTP_PROXY_INFO; +pub type LPWINHTTP_PROXY_INFOW = LPWINHTTP_PROXY_INFO; +STRUCT!{struct WINHTTP_AUTOPROXY_OPTIONS { + dwFlags: ::DWORD, + dwAutoDetectFlags: ::DWORD, + lpszAutoConfigUrl: ::LPCWSTR, + lpvReserved: ::LPVOID, + dwReserved: ::DWORD, + fAutoLogonIfChallenged: ::BOOL, +}} +pub const WINHTTP_AUTOPROXY_AUTO_DETECT: ::DWORD = 0x00000001; +pub const WINHTTP_AUTOPROXY_CONFIG_URL: ::DWORD = 0x00000002; +pub const WINHTTP_AUTOPROXY_HOST_KEEPCASE: ::DWORD = 0x00000004; +pub const WINHTTP_AUTOPROXY_HOST_LOWERCASE: ::DWORD = 0x00000008; +pub const WINHTTP_AUTOPROXY_RUN_INPROCESS: ::DWORD = 0x00010000; +pub const WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY: ::DWORD = 0x00020000; +pub const WINHTTP_AUTOPROXY_NO_DIRECTACCESS: ::DWORD = 0x00040000; +pub const WINHTTP_AUTOPROXY_NO_CACHE_CLIENT: ::DWORD = 0x00080000; +pub const WINHTTP_AUTOPROXY_NO_CACHE_SVC: ::DWORD = 0x00100000; +pub const WINHTTP_AUTOPROXY_SORT_RESULTS: ::DWORD = 0x00400000; +pub const WINHTTP_AUTO_DETECT_TYPE_DHCP: ::DWORD = 0x00000001; +pub const WINHTTP_AUTO_DETECT_TYPE_DNS_A: ::DWORD = 0x00000002; +STRUCT!{struct WINHTTP_PROXY_RESULT_ENTRY { + fProxy: ::BOOL, + fBypass: ::BOOL, + ProxyScheme: INTERNET_SCHEME, + pwszProxy: ::PWSTR, + ProxyPort: INTERNET_PORT, +}} +STRUCT!{struct WINHTTP_PROXY_RESULT { + cEntries: ::DWORD, + pEntries: *mut WINHTTP_PROXY_RESULT_ENTRY, +}} +pub const WINHTTP_FIRST_OPTION: ::DWORD = WINHTTP_OPTION_CALLBACK; +pub const WINHTTP_OPTION_CALLBACK: ::DWORD = 1; +pub const WINHTTP_OPTION_RESOLVE_TIMEOUT: ::DWORD = 2; +pub const WINHTTP_OPTION_CONNECT_TIMEOUT: ::DWORD = 3; +pub const WINHTTP_OPTION_CONNECT_RETRIES: ::DWORD = 4; +pub const WINHTTP_OPTION_SEND_TIMEOUT: ::DWORD = 5; +pub const WINHTTP_OPTION_RECEIVE_TIMEOUT: ::DWORD = 6; +pub const WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT: ::DWORD = 7; +pub const WINHTTP_OPTION_HANDLE_TYPE: ::DWORD = 9; +pub const WINHTTP_OPTION_READ_BUFFER_SIZE: ::DWORD = 12; +pub const WINHTTP_OPTION_WRITE_BUFFER_SIZE: ::DWORD = 13; +pub const WINHTTP_OPTION_PARENT_HANDLE: ::DWORD = 21; +pub const WINHTTP_OPTION_EXTENDED_ERROR: ::DWORD = 24; +pub const WINHTTP_OPTION_SECURITY_FLAGS: ::DWORD = 31; +pub const WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT: ::DWORD = 32; +pub const WINHTTP_OPTION_URL: ::DWORD = 34; +pub const WINHTTP_OPTION_SECURITY_KEY_BITNESS: ::DWORD = 36; +pub const WINHTTP_OPTION_PROXY: ::DWORD = 38; +pub const WINHTTP_OPTION_PROXY_RESULT_ENTRY: ::DWORD = 39; +pub const WINHTTP_OPTION_USER_AGENT: ::DWORD = 41; +pub const WINHTTP_OPTION_CONTEXT_VALUE: ::DWORD = 45; +pub const WINHTTP_OPTION_CLIENT_CERT_CONTEXT: ::DWORD = 47; +pub const WINHTTP_OPTION_REQUEST_PRIORITY: ::DWORD = 58; +pub const WINHTTP_OPTION_HTTP_VERSION: ::DWORD = 59; +pub const WINHTTP_OPTION_DISABLE_FEATURE: ::DWORD = 63; +pub const WINHTTP_OPTION_CODEPAGE: ::DWORD = 68; +pub const WINHTTP_OPTION_MAX_CONNS_PER_SERVER: ::DWORD = 73; +pub const WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER: ::DWORD = 74; +pub const WINHTTP_OPTION_AUTOLOGON_POLICY: ::DWORD = 77; +pub const WINHTTP_OPTION_SERVER_CERT_CONTEXT: ::DWORD = 78; +pub const WINHTTP_OPTION_ENABLE_FEATURE: ::DWORD = 79; +pub const WINHTTP_OPTION_WORKER_THREAD_COUNT: ::DWORD = 80; +pub const WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT: ::DWORD = 81; +pub const WINHTTP_OPTION_PASSPORT_COBRANDING_URL: ::DWORD = 82; +pub const WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH: ::DWORD = 83; +pub const WINHTTP_OPTION_SECURE_PROTOCOLS: ::DWORD = 84; +pub const WINHTTP_OPTION_ENABLETRACING: ::DWORD = 85; +pub const WINHTTP_OPTION_PASSPORT_SIGN_OUT: ::DWORD = 86; +pub const WINHTTP_OPTION_PASSPORT_RETURN_URL: ::DWORD = 87; +pub const WINHTTP_OPTION_REDIRECT_POLICY: ::DWORD = 88; +pub const WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS: ::DWORD = 89; +pub const WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE: ::DWORD = 90; +pub const WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE: ::DWORD = 91; +pub const WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE: ::DWORD = 92; +pub const WINHTTP_OPTION_CONNECTION_INFO: ::DWORD = 93; +pub const WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST: ::DWORD = 94; +pub const WINHTTP_OPTION_SPN: ::DWORD = 96; +pub const WINHTTP_OPTION_GLOBAL_PROXY_CREDS: ::DWORD = 97; +pub const WINHTTP_OPTION_GLOBAL_SERVER_CREDS: ::DWORD = 98; +pub const WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT: ::DWORD = 99; +pub const WINHTTP_OPTION_REJECT_USERPWD_IN_URL: ::DWORD = 100; +pub const WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS: ::DWORD = 101; +pub const WINHTTP_OPTION_RECEIVE_PROXY_CONNECT_RESPONSE: ::DWORD = 103; +pub const WINHTTP_OPTION_IS_PROXY_CONNECT_RESPONSE: ::DWORD = 104; +pub const WINHTTP_OPTION_SERVER_SPN_USED: ::DWORD = 106; +pub const WINHTTP_OPTION_PROXY_SPN_USED: ::DWORD = 107; +pub const WINHTTP_OPTION_SERVER_CBT: ::DWORD = 108; +pub const WINHTTP_OPTION_UNSAFE_HEADER_PARSING: ::DWORD = 110; +pub const WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS: ::DWORD = 111; +pub const WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET: ::DWORD = 114; +pub const WINHTTP_OPTION_WEB_SOCKET_CLOSE_TIMEOUT: ::DWORD = 115; +pub const WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL: ::DWORD = 116; +pub const WINHTTP_OPTION_DECOMPRESSION: ::DWORD = 118; +pub const WINHTTP_OPTION_WEB_SOCKET_RECEIVE_BUFFER_SIZE: ::DWORD = 122; +pub const WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE: ::DWORD = 123; +pub const WINHTTP_LAST_OPTION: ::DWORD = WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE; +pub const WINHTTP_OPTION_USERNAME: ::DWORD = 0x1000; +pub const WINHTTP_OPTION_PASSWORD: ::DWORD = 0x1001; +pub const WINHTTP_OPTION_PROXY_USERNAME: ::DWORD = 0x1002; +pub const WINHTTP_OPTION_PROXY_PASSWORD: ::DWORD = 0x1003; +//552 +pub type WINHTTP_STATUS_CALLBACK = Option; +pub type LPWINHTTP_STATUS_CALLBACK = *mut WINHTTP_STATUS_CALLBACK; +pub const WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: ::DWORD = 0x00000001; +pub const WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: ::DWORD = 0x00000002; +pub const WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: ::DWORD = 0x00000004; +pub const WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: ::DWORD = 0x00000008; +pub const WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: ::DWORD = 0x00000010; +pub const WINHTTP_CALLBACK_STATUS_REQUEST_SENT: ::DWORD = 0x00000020; +pub const WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: ::DWORD = 0x00000040; +pub const WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: ::DWORD = 0x00000080; +pub const WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: ::DWORD = 0x00000100; +pub const WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: ::DWORD = 0x00000200; +pub const WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: ::DWORD = 0x00000400; +pub const WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: ::DWORD = 0x00000800; +pub const WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: ::DWORD = 0x00001000; +pub const WINHTTP_CALLBACK_STATUS_REDIRECT: ::DWORD = 0x00004000; +pub const WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: ::DWORD = 0x00008000; +pub const WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: ::DWORD = 0x00010000; +pub const WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: ::DWORD = 0x00020000; +pub const WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: ::DWORD = 0x00040000; +pub const WINHTTP_CALLBACK_STATUS_READ_COMPLETE: ::DWORD = 0x00080000; +pub const WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: ::DWORD = 0x00100000; +pub const WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: ::DWORD = 0x00200000; +pub const WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: ::DWORD = 0x00400000; +pub const WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE: ::DWORD = 0x01000000; +pub const WINHTTP_CALLBACK_STATUS_CLOSE_COMPLETE: ::DWORD = 0x02000000; +pub const WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: ::DWORD = 0x04000000; +pub const WINHTTP_CALLBACK_FLAG_RESOLVE_NAME: ::DWORD = WINHTTP_CALLBACK_STATUS_RESOLVING_NAME + | WINHTTP_CALLBACK_STATUS_NAME_RESOLVED; +pub const WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER: ::DWORD = + WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER | WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER; +pub const WINHTTP_CALLBACK_FLAG_SEND_REQUEST: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDING_REQUEST | WINHTTP_CALLBACK_STATUS_REQUEST_SENT; +pub const WINHTTP_CALLBACK_FLAG_RECEIVE_RESPONSE: ::DWORD = + WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE | WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED; +pub const WINHTTP_CALLBACK_FLAG_CLOSE_CONNECTION: ::DWORD = + WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION | WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED; +pub const WINHTTP_CALLBACK_FLAG_HANDLES: ::DWORD = + WINHTTP_CALLBACK_STATUS_HANDLE_CREATED | WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING; +pub const WINHTTP_CALLBACK_FLAG_DETECTING_PROXY: ::DWORD = WINHTTP_CALLBACK_STATUS_DETECTING_PROXY; +pub const WINHTTP_CALLBACK_FLAG_REDIRECT: ::DWORD = WINHTTP_CALLBACK_STATUS_REDIRECT; +pub const WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE: ::DWORD = + WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE; +pub const WINHTTP_CALLBACK_FLAG_SECURE_FAILURE: ::DWORD = WINHTTP_CALLBACK_STATUS_SECURE_FAILURE; +pub const WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE: ::DWORD = + WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE; +pub const WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE: ::DWORD = WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE; +pub const WINHTTP_CALLBACK_FLAG_READ_COMPLETE: ::DWORD = WINHTTP_CALLBACK_STATUS_READ_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE: ::DWORD = WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_REQUEST_ERROR: ::DWORD = WINHTTP_CALLBACK_STATUS_REQUEST_ERROR; +pub const WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE: ::DWORD = + WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS: ::DWORD = + WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE | WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE + | WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE | WINHTTP_CALLBACK_STATUS_READ_COMPLETE + | WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE | WINHTTP_CALLBACK_STATUS_REQUEST_ERROR + | WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE; +pub const WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS: ::DWORD = 0xffffffff; +pub const WINHTTP_QUERY_MIME_VERSION: ::DWORD = 0; +pub const WINHTTP_QUERY_CONTENT_TYPE: ::DWORD = 1; +pub const WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING: ::DWORD = 2; +pub const WINHTTP_QUERY_CONTENT_ID: ::DWORD = 3; +pub const WINHTTP_QUERY_CONTENT_DESCRIPTION: ::DWORD = 4; +pub const WINHTTP_QUERY_CONTENT_LENGTH: ::DWORD = 5; +pub const WINHTTP_QUERY_CONTENT_LANGUAGE: ::DWORD = 6; +pub const WINHTTP_QUERY_ALLOW: ::DWORD = 7; +pub const WINHTTP_QUERY_PUBLIC: ::DWORD = 8; +pub const WINHTTP_QUERY_DATE: ::DWORD = 9; +pub const WINHTTP_QUERY_EXPIRES: ::DWORD = 10; +pub const WINHTTP_QUERY_LAST_MODIFIED: ::DWORD = 11; +pub const WINHTTP_QUERY_MESSAGE_ID: ::DWORD = 12; +pub const WINHTTP_QUERY_URI: ::DWORD = 13; +pub const WINHTTP_QUERY_DERIVED_FROM: ::DWORD = 14; +pub const WINHTTP_QUERY_COST: ::DWORD = 15; +pub const WINHTTP_QUERY_LINK: ::DWORD = 16; +pub const WINHTTP_QUERY_PRAGMA: ::DWORD = 17; +pub const WINHTTP_QUERY_VERSION: ::DWORD = 18; +pub const WINHTTP_QUERY_STATUS_CODE: ::DWORD = 19; +pub const WINHTTP_QUERY_STATUS_TEXT: ::DWORD = 20; +pub const WINHTTP_QUERY_RAW_HEADERS: ::DWORD = 21; +pub const WINHTTP_QUERY_RAW_HEADERS_CRLF: ::DWORD = 22; +pub const WINHTTP_QUERY_CONNECTION: ::DWORD = 23; +pub const WINHTTP_QUERY_ACCEPT: ::DWORD = 24; +pub const WINHTTP_QUERY_ACCEPT_CHARSET: ::DWORD = 25; +pub const WINHTTP_QUERY_ACCEPT_ENCODING: ::DWORD = 26; +pub const WINHTTP_QUERY_ACCEPT_LANGUAGE: ::DWORD = 27; +pub const WINHTTP_QUERY_AUTHORIZATION: ::DWORD = 28; +pub const WINHTTP_QUERY_CONTENT_ENCODING: ::DWORD = 29; +pub const WINHTTP_QUERY_FORWARDED: ::DWORD = 30; +pub const WINHTTP_QUERY_FROM: ::DWORD = 31; +pub const WINHTTP_QUERY_IF_MODIFIED_SINCE: ::DWORD = 32; +pub const WINHTTP_QUERY_LOCATION: ::DWORD = 33; +pub const WINHTTP_QUERY_ORIG_URI: ::DWORD = 34; +pub const WINHTTP_QUERY_REFERER: ::DWORD = 35; +pub const WINHTTP_QUERY_RETRY_AFTER: ::DWORD = 36; +pub const WINHTTP_QUERY_SERVER: ::DWORD = 37; +pub const WINHTTP_QUERY_TITLE: ::DWORD = 38; +pub const WINHTTP_QUERY_USER_AGENT: ::DWORD = 39; +pub const WINHTTP_QUERY_WWW_AUTHENTICATE: ::DWORD = 40; +pub const WINHTTP_QUERY_PROXY_AUTHENTICATE: ::DWORD = 41; +pub const WINHTTP_QUERY_ACCEPT_RANGES: ::DWORD = 42; +pub const WINHTTP_QUERY_SET_COOKIE: ::DWORD = 43; +pub const WINHTTP_QUERY_COOKIE: ::DWORD = 44; +pub const WINHTTP_QUERY_REQUEST_METHOD: ::DWORD = 45; +pub const WINHTTP_QUERY_REFRESH: ::DWORD = 46; +pub const WINHTTP_QUERY_CONTENT_DISPOSITION: ::DWORD = 47; +pub const WINHTTP_QUERY_AGE: ::DWORD = 48; +pub const WINHTTP_QUERY_CACHE_CONTROL: ::DWORD = 49; +pub const WINHTTP_QUERY_CONTENT_BASE: ::DWORD = 50; +pub const WINHTTP_QUERY_CONTENT_LOCATION: ::DWORD = 51; +pub const WINHTTP_QUERY_CONTENT_MD5: ::DWORD = 52; +pub const WINHTTP_QUERY_CONTENT_RANGE: ::DWORD = 53; +pub const WINHTTP_QUERY_ETAG: ::DWORD = 54; +pub const WINHTTP_QUERY_HOST: ::DWORD = 55; +pub const WINHTTP_QUERY_IF_MATCH: ::DWORD = 56; +pub const WINHTTP_QUERY_IF_NONE_MATCH: ::DWORD = 57; +pub const WINHTTP_QUERY_IF_RANGE: ::DWORD = 58; +pub const WINHTTP_QUERY_IF_UNMODIFIED_SINCE: ::DWORD = 59; +pub const WINHTTP_QUERY_MAX_FORWARDS: ::DWORD = 60; +pub const WINHTTP_QUERY_PROXY_AUTHORIZATION: ::DWORD = 61; +pub const WINHTTP_QUERY_RANGE: ::DWORD = 62; +pub const WINHTTP_QUERY_TRANSFER_ENCODING: ::DWORD = 63; +pub const WINHTTP_QUERY_UPGRADE: ::DWORD = 64; +pub const WINHTTP_QUERY_VARY: ::DWORD = 65; +pub const WINHTTP_QUERY_VIA: ::DWORD = 66; +pub const WINHTTP_QUERY_WARNING: ::DWORD = 67; +pub const WINHTTP_QUERY_EXPECT: ::DWORD = 68; +pub const WINHTTP_QUERY_PROXY_CONNECTION: ::DWORD = 69; +pub const WINHTTP_QUERY_UNLESS_MODIFIED_SINCE: ::DWORD = 70; +pub const WINHTTP_QUERY_PROXY_SUPPORT: ::DWORD = 75; +pub const WINHTTP_QUERY_AUTHENTICATION_INFO: ::DWORD = 76; +pub const WINHTTP_QUERY_PASSPORT_URLS: ::DWORD = 77; +pub const WINHTTP_QUERY_PASSPORT_CONFIG: ::DWORD = 78; +pub const WINHTTP_QUERY_MAX: ::DWORD = 78; +pub const WINHTTP_QUERY_CUSTOM: ::DWORD = 65535; +pub const WINHTTP_QUERY_FLAG_REQUEST_HEADERS: ::DWORD = 0x80000000; +pub const WINHTTP_QUERY_FLAG_SYSTEMTIME: ::DWORD = 0x40000000; +pub const WINHTTP_QUERY_FLAG_NUMBER: ::DWORD = 0x20000000; +pub const HTTP_STATUS_CONTINUE: ::DWORD = 100; +pub const HTTP_STATUS_SWITCH_PROTOCOLS: ::DWORD = 101; +pub const HTTP_STATUS_OK: ::DWORD = 200; +pub const HTTP_STATUS_CREATED: ::DWORD = 201; +pub const HTTP_STATUS_ACCEPTED: ::DWORD = 202; +pub const HTTP_STATUS_PARTIAL: ::DWORD = 203; +pub const HTTP_STATUS_NO_CONTENT: ::DWORD = 204; +pub const HTTP_STATUS_RESET_CONTENT: ::DWORD = 205; +pub const HTTP_STATUS_PARTIAL_CONTENT: ::DWORD = 206; +pub const HTTP_STATUS_WEBDAV_MULTI_STATUS: ::DWORD = 207; +pub const HTTP_STATUS_AMBIGUOUS: ::DWORD = 300; +pub const HTTP_STATUS_MOVED: ::DWORD = 301; +pub const HTTP_STATUS_REDIRECT: ::DWORD = 302; +pub const HTTP_STATUS_REDIRECT_METHOD: ::DWORD = 303; +pub const HTTP_STATUS_NOT_MODIFIED: ::DWORD = 304; +pub const HTTP_STATUS_USE_PROXY: ::DWORD = 305; +pub const HTTP_STATUS_REDIRECT_KEEP_VERB: ::DWORD = 307; +pub const HTTP_STATUS_BAD_REQUEST: ::DWORD = 400; +pub const HTTP_STATUS_DENIED: ::DWORD = 401; +pub const HTTP_STATUS_PAYMENT_REQ: ::DWORD = 402; +pub const HTTP_STATUS_FORBIDDEN: ::DWORD = 403; +pub const HTTP_STATUS_NOT_FOUND: ::DWORD = 404; +pub const HTTP_STATUS_BAD_METHOD: ::DWORD = 405; +pub const HTTP_STATUS_NONE_ACCEPTABLE: ::DWORD = 406; +pub const HTTP_STATUS_PROXY_AUTH_REQ: ::DWORD = 407; +pub const HTTP_STATUS_REQUEST_TIMEOUT: ::DWORD = 408; +pub const HTTP_STATUS_CONFLICT: ::DWORD = 409; +pub const HTTP_STATUS_GONE: ::DWORD = 410; +pub const HTTP_STATUS_LENGTH_REQUIRED: ::DWORD = 411; +pub const HTTP_STATUS_PRECOND_FAILED: ::DWORD = 412; +pub const HTTP_STATUS_REQUEST_TOO_LARGE: ::DWORD = 413; +pub const HTTP_STATUS_URI_TOO_LONG: ::DWORD = 414; +pub const HTTP_STATUS_UNSUPPORTED_MEDIA: ::DWORD = 415; +pub const HTTP_STATUS_RETRY_WITH: ::DWORD = 449; +pub const HTTP_STATUS_SERVER_ERROR: ::DWORD = 500; +pub const HTTP_STATUS_NOT_SUPPORTED: ::DWORD = 501; +pub const HTTP_STATUS_BAD_GATEWAY: ::DWORD = 502; +pub const HTTP_STATUS_SERVICE_UNAVAIL: ::DWORD = 503; +pub const HTTP_STATUS_GATEWAY_TIMEOUT: ::DWORD = 504; +pub const HTTP_STATUS_VERSION_NOT_SUP: ::DWORD = 505; +pub const HTTP_STATUS_FIRST: ::DWORD = HTTP_STATUS_CONTINUE; +pub const HTTP_STATUS_LAST: ::DWORD = HTTP_STATUS_VERSION_NOT_SUP; +pub const WINHTTP_ACCESS_TYPE_DEFAULT_PROXY: ::DWORD = 0; +pub const WINHTTP_ACCESS_TYPE_NO_PROXY: ::DWORD = 1; +pub const WINHTTP_ACCESS_TYPE_NAMED_PROXY: ::DWORD = 3; +pub const WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY: ::DWORD = 4; +pub const WINHTTP_ERROR_BASE: ::DWORD = 12000; +pub const ERROR_WINHTTP_OUT_OF_HANDLES: ::DWORD = WINHTTP_ERROR_BASE + 1; +pub const ERROR_WINHTTP_TIMEOUT: ::DWORD = WINHTTP_ERROR_BASE + 2; +pub const ERROR_WINHTTP_INTERNAL_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 4; +pub const ERROR_WINHTTP_INVALID_URL: ::DWORD = WINHTTP_ERROR_BASE + 5; +pub const ERROR_WINHTTP_UNRECOGNIZED_SCHEME: ::DWORD = WINHTTP_ERROR_BASE + 6; +pub const ERROR_WINHTTP_NAME_NOT_RESOLVED: ::DWORD = WINHTTP_ERROR_BASE + 7; +pub const ERROR_WINHTTP_INVALID_OPTION: ::DWORD = WINHTTP_ERROR_BASE + 9; +pub const ERROR_WINHTTP_OPTION_NOT_SETTABLE: ::DWORD = WINHTTP_ERROR_BASE + 11; +pub const ERROR_WINHTTP_SHUTDOWN: ::DWORD = WINHTTP_ERROR_BASE + 12; +pub const ERROR_WINHTTP_LOGIN_FAILURE: ::DWORD = WINHTTP_ERROR_BASE + 15; +pub const ERROR_WINHTTP_OPERATION_CANCELLED: ::DWORD = WINHTTP_ERROR_BASE + 17; +pub const ERROR_WINHTTP_INCORRECT_HANDLE_TYPE: ::DWORD = WINHTTP_ERROR_BASE + 18; +pub const ERROR_WINHTTP_INCORRECT_HANDLE_STATE: ::DWORD = WINHTTP_ERROR_BASE + 19; +pub const ERROR_WINHTTP_CANNOT_CONNECT: ::DWORD = WINHTTP_ERROR_BASE + 29; +pub const ERROR_WINHTTP_CONNECTION_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 30; +pub const ERROR_WINHTTP_RESEND_REQUEST: ::DWORD = WINHTTP_ERROR_BASE + 32; +pub const ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: ::DWORD = WINHTTP_ERROR_BASE + 44; +pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN: ::DWORD = WINHTTP_ERROR_BASE + 100; +pub const ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND: ::DWORD = WINHTTP_ERROR_BASE + 101; +pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND: ::DWORD = WINHTTP_ERROR_BASE + 102; +pub const ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN: ::DWORD = WINHTTP_ERROR_BASE + 103; +pub const ERROR_WINHTTP_HEADER_NOT_FOUND: ::DWORD = WINHTTP_ERROR_BASE + 150; +pub const ERROR_WINHTTP_INVALID_SERVER_RESPONSE: ::DWORD = WINHTTP_ERROR_BASE + 152; +pub const ERROR_WINHTTP_INVALID_HEADER: ::DWORD = WINHTTP_ERROR_BASE + 153; +pub const ERROR_WINHTTP_INVALID_QUERY_REQUEST: ::DWORD = WINHTTP_ERROR_BASE + 154; +pub const ERROR_WINHTTP_HEADER_ALREADY_EXISTS: ::DWORD = WINHTTP_ERROR_BASE + 155; +pub const ERROR_WINHTTP_REDIRECT_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 156; +pub const ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 178; +pub const ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: ::DWORD = WINHTTP_ERROR_BASE + 166; +pub const ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: ::DWORD = WINHTTP_ERROR_BASE + 167; +pub const ERROR_WINHTTP_UNHANDLED_SCRIPT_TYPE: ::DWORD = WINHTTP_ERROR_BASE + 176; +pub const ERROR_WINHTTP_SCRIPT_EXECUTION_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 177; +pub const ERROR_WINHTTP_NOT_INITIALIZED: ::DWORD = WINHTTP_ERROR_BASE + 172; +pub const ERROR_WINHTTP_SECURE_FAILURE: ::DWORD = WINHTTP_ERROR_BASE + 175; +pub const ERROR_WINHTTP_SECURE_CERT_DATE_INVALID: ::DWORD = WINHTTP_ERROR_BASE + 37; +pub const ERROR_WINHTTP_SECURE_CERT_CN_INVALID: ::DWORD = WINHTTP_ERROR_BASE + 38; +pub const ERROR_WINHTTP_SECURE_INVALID_CA: ::DWORD = WINHTTP_ERROR_BASE + 45; +pub const ERROR_WINHTTP_SECURE_CERT_REV_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 57; +pub const ERROR_WINHTTP_SECURE_CHANNEL_ERROR: ::DWORD = WINHTTP_ERROR_BASE + 157; +pub const ERROR_WINHTTP_SECURE_INVALID_CERT: ::DWORD = WINHTTP_ERROR_BASE + 169; +pub const ERROR_WINHTTP_SECURE_CERT_REVOKED: ::DWORD = WINHTTP_ERROR_BASE + 170; +pub const ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE: ::DWORD = WINHTTP_ERROR_BASE + 179; +pub const ERROR_WINHTTP_AUTODETECTION_FAILED: ::DWORD = WINHTTP_ERROR_BASE + 180; +pub const ERROR_WINHTTP_HEADER_COUNT_EXCEEDED: ::DWORD = WINHTTP_ERROR_BASE + 181; +pub const ERROR_WINHTTP_HEADER_SIZE_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 182; +pub const ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 183; +pub const ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW: ::DWORD = WINHTTP_ERROR_BASE + 184; +pub const ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY: ::DWORD = WINHTTP_ERROR_BASE + 185; +pub const ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY: ::DWORD = WINHTTP_ERROR_BASE + 186; +pub const WINHTTP_ERROR_LAST: ::DWORD = WINHTTP_ERROR_BASE + 186; +pub const WINHTTP_RESET_STATE: ::DWORD = 0x00000001; +pub const WINHTTP_RESET_SWPAD_CURRENT_NETWORK: ::DWORD = 0x00000002; +pub const WINHTTP_RESET_SWPAD_ALL: ::DWORD = 0x00000004; +pub const WINHTTP_RESET_SCRIPT_CACHE: ::DWORD = 0x00000008; +pub const WINHTTP_RESET_ALL: ::DWORD = 0x0000FFFF; +pub const WINHTTP_RESET_NOTIFY_NETWORK_CHANGED: ::DWORD = 0x00010000; +pub const WINHTTP_RESET_OUT_OF_PROC: ::DWORD = 0x00020000; +STRUCT!{struct WINHTTP_CURRENT_USER_IE_PROXY_CONFIG { + fAutoDetect: ::BOOL, + lpszAutoConfigUrl: ::LPWSTR, + lpszProxy: ::LPWSTR, + lpszProxyBypass: ::LPWSTR, +}} +//1370 +ENUM!{enum WINHTTP_WEB_SOCKET_OPERATION { + WINHTTP_WEB_SOCKET_SEND_OPERATION = 0, + WINHTTP_WEB_SOCKET_RECEIVE_OPERATION = 1, + WINHTTP_WEB_SOCKET_CLOSE_OPERATION = 2, + WINHTTP_WEB_SOCKET_SHUTDOWN_OPERATION = 3, +}} +ENUM!{enum WINHTTP_WEB_SOCKET_BUFFER_TYPE { + WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE = 0, + WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE = 1, + WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE = 2, + WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE = 3, + WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE = 4, +}} +ENUM!{enum WINHTTP_WEB_SOCKET_CLOSE_STATUS { + WINHTTP_WEB_SOCKET_SUCCESS_CLOSE_STATUS = 1000, + WINHTTP_WEB_SOCKET_ENDPOINT_TERMINATED_CLOSE_STATUS = 1001, + WINHTTP_WEB_SOCKET_PROTOCOL_ERROR_CLOSE_STATUS = 1002, + WINHTTP_WEB_SOCKET_INVALID_DATA_TYPE_CLOSE_STATUS = 1003, + WINHTTP_WEB_SOCKET_EMPTY_CLOSE_STATUS = 1005, + WINHTTP_WEB_SOCKET_ABORTED_CLOSE_STATUS = 1006, + WINHTTP_WEB_SOCKET_INVALID_PAYLOAD_CLOSE_STATUS = 1007, + WINHTTP_WEB_SOCKET_POLICY_VIOLATION_CLOSE_STATUS = 1008, + WINHTTP_WEB_SOCKET_MESSAGE_TOO_BIG_CLOSE_STATUS = 1009, + WINHTTP_WEB_SOCKET_UNSUPPORTED_EXTENSIONS_CLOSE_STATUS = 1010, + WINHTTP_WEB_SOCKET_SERVER_ERROR_CLOSE_STATUS = 1011, + WINHTTP_WEB_SOCKET_SECURE_HANDSHAKE_ERROR_CLOSE_STATUS = 1015, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winioctl.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winioctl.rs new file mode 100644 index 0000000..de3b961 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winioctl.rs @@ -0,0 +1,754 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This module defines the 32-Bit Windows Device I/O control codes. +//123 +pub const FILE_DEVICE_BEEP: ::DWORD = 0x00000001; +pub const FILE_DEVICE_CD_ROM: ::DWORD = 0x00000002; +pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM: ::DWORD = 0x00000003; +pub const FILE_DEVICE_CONTROLLER: ::DWORD = 0x00000004; +pub const FILE_DEVICE_DATALINK: ::DWORD = 0x00000005; +pub const FILE_DEVICE_DFS: ::DWORD = 0x00000006; +pub const FILE_DEVICE_DISK: ::DWORD = 0x00000007; +pub const FILE_DEVICE_DISK_FILE_SYSTEM: ::DWORD = 0x00000008; +pub const FILE_DEVICE_FILE_SYSTEM: ::DWORD = 0x00000009; +pub const FILE_DEVICE_INPORT_PORT: ::DWORD = 0x0000000a; +pub const FILE_DEVICE_KEYBOARD: ::DWORD = 0x0000000b; +pub const FILE_DEVICE_MAILSLOT: ::DWORD = 0x0000000c; +pub const FILE_DEVICE_MIDI_IN: ::DWORD = 0x0000000d; +pub const FILE_DEVICE_MIDI_OUT: ::DWORD = 0x0000000e; +pub const FILE_DEVICE_MOUSE: ::DWORD = 0x0000000f; +pub const FILE_DEVICE_MULTI_UNC_PROVIDER: ::DWORD = 0x00000010; +pub const FILE_DEVICE_NAMED_PIPE: ::DWORD = 0x00000011; +pub const FILE_DEVICE_NETWORK: ::DWORD = 0x00000012; +pub const FILE_DEVICE_NETWORK_BROWSER: ::DWORD = 0x00000013; +pub const FILE_DEVICE_NETWORK_FILE_SYSTEM: ::DWORD = 0x00000014; +pub const FILE_DEVICE_NULL: ::DWORD = 0x00000015; +pub const FILE_DEVICE_PARALLEL_PORT: ::DWORD = 0x00000016; +pub const FILE_DEVICE_PHYSICAL_NETCARD: ::DWORD = 0x00000017; +pub const FILE_DEVICE_PRINTER: ::DWORD = 0x00000018; +pub const FILE_DEVICE_SCANNER: ::DWORD = 0x00000019; +pub const FILE_DEVICE_SERIAL_MOUSE_PORT: ::DWORD = 0x0000001a; +pub const FILE_DEVICE_SERIAL_PORT: ::DWORD = 0x0000001b; +pub const FILE_DEVICE_SCREEN: ::DWORD = 0x0000001c; +pub const FILE_DEVICE_SOUND: ::DWORD = 0x0000001d; +pub const FILE_DEVICE_STREAMS: ::DWORD = 0x0000001e; +pub const FILE_DEVICE_TAPE: ::DWORD = 0x0000001f; +pub const FILE_DEVICE_TAPE_FILE_SYSTEM: ::DWORD = 0x00000020; +pub const FILE_DEVICE_TRANSPORT: ::DWORD = 0x00000021; +pub const FILE_DEVICE_UNKNOWN: ::DWORD = 0x00000022; +pub const FILE_DEVICE_VIDEO: ::DWORD = 0x00000023; +pub const FILE_DEVICE_VIRTUAL_DISK: ::DWORD = 0x00000024; +pub const FILE_DEVICE_WAVE_IN: ::DWORD = 0x00000025; +pub const FILE_DEVICE_WAVE_OUT: ::DWORD = 0x00000026; +pub const FILE_DEVICE_8042_PORT: ::DWORD = 0x00000027; +pub const FILE_DEVICE_NETWORK_REDIRECTOR: ::DWORD = 0x00000028; +pub const FILE_DEVICE_BATTERY: ::DWORD = 0x00000029; +pub const FILE_DEVICE_BUS_EXTENDER: ::DWORD = 0x0000002a; +pub const FILE_DEVICE_MODEM: ::DWORD = 0x0000002b; +pub const FILE_DEVICE_VDM: ::DWORD = 0x0000002c; +pub const FILE_DEVICE_MASS_STORAGE: ::DWORD = 0x0000002d; +pub const FILE_DEVICE_SMB: ::DWORD = 0x0000002e; +pub const FILE_DEVICE_KS: ::DWORD = 0x0000002f; +pub const FILE_DEVICE_CHANGER: ::DWORD = 0x00000030; +pub const FILE_DEVICE_SMARTCARD: ::DWORD = 0x00000031; +pub const FILE_DEVICE_ACPI: ::DWORD = 0x00000032; +pub const FILE_DEVICE_DVD: ::DWORD = 0x00000033; +pub const FILE_DEVICE_FULLSCREEN_VIDEO: ::DWORD = 0x00000034; +pub const FILE_DEVICE_DFS_FILE_SYSTEM: ::DWORD = 0x00000035; +pub const FILE_DEVICE_DFS_VOLUME: ::DWORD = 0x00000036; +pub const FILE_DEVICE_SERENUM: ::DWORD = 0x00000037; +pub const FILE_DEVICE_TERMSRV: ::DWORD = 0x00000038; +pub const FILE_DEVICE_KSEC: ::DWORD = 0x00000039; +pub const FILE_DEVICE_FIPS: ::DWORD = 0x0000003A; +pub const FILE_DEVICE_INFINIBAND: ::DWORD = 0x0000003B; +pub const FILE_DEVICE_VMBUS: ::DWORD = 0x0000003E; +pub const FILE_DEVICE_CRYPT_PROVIDER: ::DWORD = 0x0000003F; +pub const FILE_DEVICE_WPD: ::DWORD = 0x00000040; +pub const FILE_DEVICE_BLUETOOTH: ::DWORD = 0x00000041; +pub const FILE_DEVICE_MT_COMPOSITE: ::DWORD = 0x00000042; +pub const FILE_DEVICE_MT_TRANSPORT: ::DWORD = 0x00000043; +pub const FILE_DEVICE_BIOMETRIC: ::DWORD = 0x00000044; +pub const FILE_DEVICE_PMI: ::DWORD = 0x00000045; +pub const FILE_DEVICE_EHSTOR: ::DWORD = 0x00000046; +pub const FILE_DEVICE_DEVAPI: ::DWORD = 0x00000047; +pub const FILE_DEVICE_GPIO: ::DWORD = 0x00000048; +pub const FILE_DEVICE_USBEX: ::DWORD = 0x00000049; +pub const FILE_DEVICE_CONSOLE: ::DWORD = 0x00000050; +pub const FILE_DEVICE_NFP: ::DWORD = 0x00000051; +pub const FILE_DEVICE_SYSENV: ::DWORD = 0x00000052; +pub const FILE_DEVICE_VIRTUAL_BLOCK: ::DWORD = 0x00000053; +pub const FILE_DEVICE_POINT_OF_SERVICE: ::DWORD = 0x00000054; +//224 +pub const METHOD_BUFFERED: ::DWORD = 0; +pub const METHOD_IN_DIRECT: ::DWORD = 1; +pub const METHOD_OUT_DIRECT: ::DWORD = 2; +pub const METHOD_NEITHER: ::DWORD = 3; +//253 +pub const FILE_ANY_ACCESS: ::DWORD = 0; +pub const FILE_SPECIAL_ACCESS: ::DWORD = FILE_ANY_ACCESS; +pub const FILE_READ_ACCESS: ::DWORD = 0x0001; +pub const FILE_WRITE_ACCESS: ::DWORD = 0x0002; +//281 +pub const IOCTL_STORAGE_BASE: ::DWORD = FILE_DEVICE_MASS_STORAGE; +pub const IOCTL_STORAGE_CHECK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0200, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_CHECK_VERIFY2: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0200, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MEDIA_REMOVAL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0201, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_EJECT_MEDIA: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0202, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_LOAD_MEDIA: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0203, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_LOAD_MEDIA2: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0203, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_RESERVE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0204, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_RELEASE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0205, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_FIND_NEW_DEVICES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0206, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_EJECTION_CONTROL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0250, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MCN_CONTROL: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0251, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_TYPES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0300, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_TYPES_EX: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0301, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0304, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_HOTPLUG_INFO: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0305, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_SET_HOTPLUG_INFO: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0306, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_RESET_BUS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_STORAGE_RESET_DEVICE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0401, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_BREAK_RESERVATION: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0405, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_PERSISTENT_RESERVE_IN: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0406, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_PERSISTENT_RESERVE_OUT: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0407, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_NUMBER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0420, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_PREDICT_FAILURE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0440, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_FAILURE_PREDICTION_CONFIG: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0441, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_READ_CAPACITY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0450, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0470, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_DEVICE_TELEMETRY_NOTIFY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0471, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_DEVICE_TELEMETRY_QUERY_CAPS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0472, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY_RAW: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0473, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_QUERY_PROPERTY: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0500, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0501, + METHOD_BUFFERED, FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_GET_LB_PROVISIONING_MAP_RESOURCES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0502, METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_GET_BC_PROPERTIES: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0600, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_STORAGE_ALLOCATE_BC_STREAM: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0601, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_FREE_BC_STREAM: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0602, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, + 0x0620, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_START_DATA_INTEGRITY_CHECK: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0621, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_STOP_DATA_INTEGRITY_CHECK: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0622, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const OBSOLETE_IOCTL_STORAGE_RESET_BUS: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0400, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const OBSOLETE_IOCTL_STORAGE_RESET_DEVICE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0401, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_STORAGE_ENABLE_IDLE_POWER: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0720, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_GET_IDLE_POWERUP_REASON: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0721, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_POWER_ACTIVE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0722, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_POWER_IDLE: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0723, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_STORAGE_EVENT_NOTIFICATION: ::DWORD = CTL_CODE!(IOCTL_STORAGE_BASE, 0x0724, + METHOD_BUFFERED, FILE_ANY_ACCESS); +//2627 +pub const IOCTL_DISK_BASE: ::DWORD = FILE_DEVICE_DISK; +pub const IOCTL_DISK_GET_DRIVE_GEOMETRY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0000, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_GET_PARTITION_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0001, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_PARTITION_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0002, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0003, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0004, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0005, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_TRACKS: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0006, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_REASSIGN_BLOCKS: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0007, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_PERFORMANCE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0008, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_IS_WRITABLE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0009, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_LOGGING: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000a, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_TRACKS_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000b, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_STRUCTURE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000c, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000d, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_HISTOGRAM_RESET: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000e, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_REQUEST_STRUCTURE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x000f, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_REQUEST_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0010, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_PERFORMANCE_OFF: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0018, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_CONTROLLER_NUMBER: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0011, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const SMART_GET_VERSION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const SMART_SEND_DRIVE_COMMAND: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const SMART_RCV_DRIVE_DATA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_PARTITION_INFO_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0012, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_PARTITION_INFO_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0013, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_LAYOUT_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0014, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_DRIVE_LAYOUT_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0015, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_CREATE_DISK: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0016, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_LENGTH_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0028, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_REASSIGN_BLOCKS_EX: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0029, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_UPDATE_DRIVE_SIZE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0032, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GROW_PARTITION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0034, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_CACHE_INFORMATION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0035, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_SET_CACHE_INFORMATION: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0036, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_GET_WRITE_CACHE_STATE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0037, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const OBSOLETE_DISK_GET_WRITE_CACHE_STATE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0037, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_DELETE_DRIVE_LAYOUT: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0040, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_UPDATE_PROPERTIES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0050, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_FORMAT_DRIVE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x00f3, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_SENSE_DEVICE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x00f8, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_CHECK_VERIFY: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0200, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_MEDIA_REMOVAL: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0201, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_EJECT_MEDIA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0202, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_LOAD_MEDIA: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0203, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_RESERVE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0204, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_RELEASE: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0205, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const IOCTL_DISK_FIND_NEW_DEVICES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0206, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_DISK_GET_MEDIA_TYPES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0300, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_DISK_GET_DISK_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x003c, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const IOCTL_DISK_SET_DISK_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x003d, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_DISK_RESET_SNAPSHOT_INFO: ::DWORD = CTL_CODE!(IOCTL_DISK_BASE, 0x0084, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +//3907 +pub const IOCTL_CHANGER_BASE: ::DWORD = FILE_DEVICE_CHANGER; +pub const IOCTL_CHANGER_GET_PARAMETERS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0000, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_GET_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0001, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_GET_PRODUCT_DATA: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0002, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_SET_ACCESS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0004, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_CHANGER_GET_ELEMENT_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0005, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0006, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_SET_POSITION: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0007, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_EXCHANGE_MEDIUM: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0008, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_MOVE_MEDIUM: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x0009, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_REINITIALIZE_TRANSPORT: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x000A, + METHOD_BUFFERED, FILE_READ_ACCESS); +pub const IOCTL_CHANGER_QUERY_VOLUME_TAGS: ::DWORD = CTL_CODE!(IOCTL_CHANGER_BASE, 0x000B, + METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_SERIAL_LSRMST_INSERT: ::DWORD = CTL_CODE!(FILE_DEVICE_SERIAL_PORT, 31, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_EXPOSE_HARDWARE: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 128, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_REMOVE_HARDWARE: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 129, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_PORT_DESC: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 130, + METHOD_BUFFERED,FILE_ANY_ACCESS); +pub const IOCTL_SERENUM_GET_PORT_NAME: ::DWORD = CTL_CODE!(FILE_DEVICE_SERENUM, 131, + METHOD_BUFFERED,FILE_ANY_ACCESS); +//4690 +pub const FSCTL_REQUEST_OPLOCK_LEVEL_1: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 0, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_OPLOCK_LEVEL_2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 1, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_BATCH_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 2, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPLOCK_BREAK_ACKNOWLEDGE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 3, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPBATCH_ACK_CLOSE_PENDING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 4, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OPLOCK_BREAK_NOTIFY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 5, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_LOCK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_UNLOCK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DISMOUNT_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_IS_VOLUME_MOUNTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 10, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_PATHNAME_VALID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 11, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_MARK_VOLUME_DIRTY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 12, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_RETRIEVAL_POINTERS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 14, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_GET_COMPRESSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 15, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SET_COMPRESSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 16, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_SET_BOOTLOADER_ACCESSED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 19, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_MARK_AS_SYSTEM_HIVE: ::DWORD = FSCTL_SET_BOOTLOADER_ACCESSED; +pub const FSCTL_OPLOCK_BREAK_ACK_NO_2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 20, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_INVALIDATE_VOLUMES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 21, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FAT_BPB: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 22, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_FILTER_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 23, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILESYSTEM_GET_STATISTICS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 24, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_NTFS_VOLUME_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 25, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_NTFS_FILE_RECORD: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 26, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_VOLUME_BITMAP: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 27, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_GET_RETRIEVAL_POINTERS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 28, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_MOVE_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 29, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_IS_VOLUME_DIRTY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 30, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_ALLOW_EXTENDED_DASD_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 32, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_FIND_FILES_BY_SID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 35, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 38, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 39, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DELETE_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 40, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 41, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 42, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_REPARSE_POINT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 43, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_ENUM_USN_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 44, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_SECURITY_ID_CHECK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 45, METHOD_NEITHER, + ::FILE_READ_DATA); +pub const FSCTL_READ_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 46, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SET_OBJECT_ID_EXTENDED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 47, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_CREATE_OR_GET_OBJECT_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 48, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_SPARSE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 49, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_ZERO_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 50, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_ALLOCATED_RANGES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 51, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_ENABLE_UPGRADE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 52, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_SET_ENCRYPTION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 53, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_ENCRYPTION_FSCTL_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 54, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_RAW_ENCRYPTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 55, + METHOD_NEITHER, FILE_SPECIAL_ACCESS); +pub const FSCTL_READ_RAW_ENCRYPTED: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 56, + METHOD_NEITHER, FILE_SPECIAL_ACCESS); +pub const FSCTL_CREATE_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 57, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_READ_FILE_USN_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 58, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_USN_CLOSE_RECORD: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 59, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_EXTEND_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 60, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_QUERY_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 61, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_USN_JOURNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 62, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_MARK_HANDLE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 63, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SIS_COPYFILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 64, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SIS_LINK_FILES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 65, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_RECALL_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 69, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_READ_FROM_PLEX: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 71, METHOD_OUT_DIRECT, + ::FILE_READ_DATA); +pub const FSCTL_FILE_PREFETCH: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 72, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_MAKE_MEDIA_COMPATIBLE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 76, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_SET_DEFECT_MANAGEMENT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 77, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_SPARING_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 78, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_ON_DISK_VOLUME_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 79, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_VOLUME_COMPRESSION_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 80, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_TXFS_MODIFY_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 81, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_QUERY_RM_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 82, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_ROLLFORWARD_REDO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 84, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_ROLLFORWARD_UNDO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 85, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_START_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 86, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_SHUTDOWN_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 87, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_READ_BACKUP_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 88, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 89, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_CREATE_SECONDARY_RM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 90, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_GET_METADATA_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 91, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_GET_TRANSACTED_VERSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 92, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_SAVEPOINT_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 94, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_CREATE_MINIVERSION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 95, + METHOD_BUFFERED, ::FILE_WRITE_DATA); +pub const FSCTL_TXFS_TRANSACTION_ACTIVE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 99, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_SET_ZERO_ON_DEALLOCATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 101, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 102, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_GET_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 103, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_WAIT_FOR_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 104, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_INITIATE_REPAIR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 106, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSC_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 107, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SHRINK_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 108, METHOD_BUFFERED, + FILE_SPECIAL_ACCESS); +pub const FSCTL_SET_SHORT_NAME_BEHAVIOR: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 109, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DFSR_SET_GHOST_HANDLE_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 110, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 120, METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_TXFS_LIST_TRANSACTIONS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 121, + METHOD_BUFFERED, ::FILE_READ_DATA); +pub const FSCTL_QUERY_PAGEFILE_ENCRYPTION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 122, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_RESET_VOLUME_ALLOCATION_HINTS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 123, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_DEPENDENT_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 124, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SD_GLOBAL_CHANGE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 125, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_READ_BACKUP_INFORMATION2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 126, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_LOOKUP_STREAM_FROM_CLUSTER: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 127, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION2: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 128, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILE_TYPE_NOTIFICATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 129, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_FILE_LEVEL_TRIM: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 130, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_GET_BOOT_AREA_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 140, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_RETRIEVAL_POINTER_BASE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 141, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_PERSISTENT_VOLUME_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 142, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_PERSISTENT_VOLUME_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 143, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_REQUEST_OPLOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 144, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 145, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_CSV_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 146, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FILE_SYSTEM_RECOGNITION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 147, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_PATH_NAME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 148, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_NAME_FOR_VOLUME_MOUNT_POINT: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 149, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_GET_VOLUME_PATH_NAMES_FOR_VOLUME_NAME: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 150, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_IS_FILE_ON_CSV_VOLUME: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 151, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CORRUPTION_HANDLING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 152, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_OFFLOAD_READ: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 153, METHOD_BUFFERED, + FILE_READ_ACCESS); +pub const FSCTL_OFFLOAD_WRITE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 154, METHOD_BUFFERED, + FILE_WRITE_ACCESS); +pub const FSCTL_CSV_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 155, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_SET_PURGE_FAILURE_MODE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 156, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_FILE_LAYOUT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 157, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_IS_VOLUME_OWNED_BYCSVFS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 158, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_GET_INTEGRITY_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 159, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_INTEGRITY_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 160, + METHOD_BUFFERED, ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_QUERY_FILE_REGIONS: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 161, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DEDUP_FILE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 165, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_DEDUP_QUERY_FILE_HASHES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 166, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_DEDUP_QUERY_RANGE_STATE: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 167, + METHOD_NEITHER, ::FILE_READ_DATA); +pub const FSCTL_DEDUP_QUERY_REPARSE_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 168, + METHOD_NEITHER, FILE_ANY_ACCESS); +pub const FSCTL_RKF_INTERNAL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 171, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_SCRUB_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 172, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_REPAIR_COPIES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 173, METHOD_BUFFERED, + ::FILE_READ_DATA | ::FILE_WRITE_DATA); +pub const FSCTL_DISABLE_LOCAL_BUFFERING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 174, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_MGMT_LOCK: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 175, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_QUERY_DOWN_LEVEL_FILE_SYSTEM_CHARACTERISTICS: ::DWORD = CTL_CODE!( + FILE_DEVICE_FILE_SYSTEM, 176, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_ADVANCE_FILE_ID: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 177, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_CSV_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 178, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_QUERY_VETO_FILE_DIRECT_IO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 179, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_WRITE_USN_REASON: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 180, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_CONTROL: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 181, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const FSCTL_GET_REFS_VOLUME_DATA: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 182, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_CSV_H_BREAKING_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 185, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_STORAGE_CLASSES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 187, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_REGION_INFO: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 188, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_USN_TRACK_MODIFIED_RANGES: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 189, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, + 192, METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SVHDX_SYNC_TUNNEL_REQUEST: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 193, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SVHDX_SET_INITIATOR_INFORMATION: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 194, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_SET_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 195, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_GET_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 196, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_DELETE_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 197, + METHOD_BUFFERED, FILE_SPECIAL_ACCESS); +pub const FSCTL_ENUM_EXTERNAL_BACKING: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 198, + METHOD_BUFFERED, FILE_ANY_ACCESS); +pub const FSCTL_ENUM_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 199, METHOD_NEITHER, + FILE_ANY_ACCESS); +pub const FSCTL_ADD_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 204, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_REMOVE_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 205, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +pub const FSCTL_UPDATE_OVERLAY: ::DWORD = CTL_CODE!(FILE_DEVICE_FILE_SYSTEM, 206, METHOD_BUFFERED, + ::FILE_WRITE_DATA); +// FILE_DEVICE_AVIO is defined nowhere +//pub const IOCTL_AVIO_ALLOCATE_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 1, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +//pub const IOCTL_AVIO_FREE_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 2, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +//pub const IOCTL_AVIO_MODIFY_STREAM: ::DWORD = CTL_CODE!(FILE_DEVICE_AVIO, 3, METHOD_BUFFERED, +// FILE_SPECIAL_ACCESS); +STRUCT!{struct PATHNAME_BUFFER { + PathNameLength: ::DWORD, + Name: [::WCHAR; 1], +}} +pub type PPATHNAME_BUFFER = *mut PATHNAME_BUFFER; +STRUCT!{nodebug struct FSCTL_QUERY_FAT_BPB_BUFFER { + First0x24BytesOfBootSector: [::BYTE; 0x24], +}} +pub type PFSCTL_QUERY_FAT_BPB_BUFFER = *mut FSCTL_QUERY_FAT_BPB_BUFFER; +STRUCT!{struct NTFS_VOLUME_DATA_BUFFER { + VolumeSerialNumber: ::LARGE_INTEGER, + NumberSectors: ::LARGE_INTEGER, + TotalClusters: ::LARGE_INTEGER, + FreeClusters: ::LARGE_INTEGER, + TotalReserved: ::LARGE_INTEGER, + BytesPerSector: ::DWORD, + BytesPerCluster: ::DWORD, + BytesPerFileRecordSegment: ::DWORD, + ClustersPerFileRecordSegment: ::DWORD, + MftValidDataLength: ::LARGE_INTEGER, + MftStartLcn: ::LARGE_INTEGER, + Mft2StartLcn: ::LARGE_INTEGER, + MftZoneStart: ::LARGE_INTEGER, + MftZoneEnd: ::LARGE_INTEGER, +}} +pub type PNTFS_VOLUME_DATA_BUFFER = *mut NTFS_VOLUME_DATA_BUFFER; +STRUCT!{struct NTFS_EXTENDED_VOLUME_DATA { + ByteCount: ::DWORD, + MajorVersion: ::WORD, + MinorVersion: ::WORD, + BytesPerPhysicalSector: ::DWORD, + LfsMajorVersion: ::WORD, + LfsMinorVersion: ::WORD, +}} +pub type PNTFS_EXTENDED_VOLUME_DATA = *mut NTFS_EXTENDED_VOLUME_DATA; +STRUCT!{struct REFS_VOLUME_DATA_BUFFER { + ByteCount: ::DWORD, + MajorVersion: ::DWORD, + MinorVersion: ::DWORD, + BytesPerPhysicalSector: ::DWORD, + VolumeSerialNumber: ::LARGE_INTEGER, + NumberSectors: ::LARGE_INTEGER, + TotalClusters: ::LARGE_INTEGER, + FreeClusters: ::LARGE_INTEGER, + TotalReserved: ::LARGE_INTEGER, + BytesPerSector: ::DWORD, + BytesPerCluster: ::DWORD, + MaximumSizeOfResidentFile: ::LARGE_INTEGER, + Reserved: [::LARGE_INTEGER; 10], +}} +pub type PREFS_VOLUME_DATA_BUFFER = *mut REFS_VOLUME_DATA_BUFFER; +STRUCT!{struct STARTING_LCN_INPUT_BUFFER { + StartingLcn: ::LARGE_INTEGER, +}} +pub type PSTARTING_LCN_INPUT_BUFFER = *mut STARTING_LCN_INPUT_BUFFER; +STRUCT!{struct VOLUME_BITMAP_BUFFER { + StartingLcn: ::LARGE_INTEGER, + BitmapSize: ::LARGE_INTEGER, + Buffer: [::BYTE; 1], +}} +pub type PVOLUME_BITMAP_BUFFER = *mut VOLUME_BITMAP_BUFFER; +STRUCT!{struct STARTING_VCN_INPUT_BUFFER { + StartingVcn: ::LARGE_INTEGER, +}} +pub type PSTARTING_VCN_INPUT_BUFFER = *mut STARTING_VCN_INPUT_BUFFER; +STRUCT!{struct RETRIEVAL_POINTERS_BUFFER_INTERNAL { + NextVcn: ::LARGE_INTEGER, + Lcn: ::LARGE_INTEGER, +}} +STRUCT!{struct RETRIEVAL_POINTERS_BUFFER { + ExtentCount: ::DWORD, + StartingVcn: ::LARGE_INTEGER, + Extents: [RETRIEVAL_POINTERS_BUFFER_INTERNAL; 1], +}} +pub type PRETRIEVAL_POINTERS_BUFFER = *mut RETRIEVAL_POINTERS_BUFFER; +STRUCT!{struct NTFS_FILE_RECORD_INPUT_BUFFER { + FileReferenceNumber: ::LARGE_INTEGER, +}} +pub type PNTFS_FILE_RECORD_INPUT_BUFFER = *mut NTFS_FILE_RECORD_INPUT_BUFFER; +STRUCT!{struct NTFS_FILE_RECORD_OUTPUT_BUFFER { + FileReferenceNumber: ::LARGE_INTEGER, + FileRecordLength: ::DWORD, + FileRecordBuffer: [::BYTE; 1], +}} +pub type PNTFS_FILE_RECORD_OUTPUT_BUFFER = *mut NTFS_FILE_RECORD_OUTPUT_BUFFER; +STRUCT!{struct MOVE_FILE_DATA { + FileHandle: ::HANDLE, + StartingVcn: ::LARGE_INTEGER, + StartingLcn: ::LARGE_INTEGER, + ClusterCount: ::DWORD, +}} +pub type PMOVE_FILE_DATA = *mut MOVE_FILE_DATA; +STRUCT!{struct MOVE_FILE_RECORD_DATA { + FileHandle: ::HANDLE, + SourceFileRecord: ::LARGE_INTEGER, + TargetFileRecord: ::LARGE_INTEGER, +}} +pub type PMOVE_FILE_RECORD_DATA = *mut MOVE_FILE_RECORD_DATA; +//9207 +pub const IOCTL_VOLUME_BASE: ::DWORD = 0x00000056; +pub const IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 0, + METHOD_BUFFERED, FILE_ANY_ACCESS); +STRUCT!{struct DISK_EXTENT { + DiskNumber: ::DWORD, + StartingOffset: ::LARGE_INTEGER, + ExtentLength: ::LARGE_INTEGER, +}} +pub type PDISK_EXTENT = *mut DISK_EXTENT; +STRUCT!{struct VOLUME_DISK_EXTENTS { + NumberOfDiskExtents: ::DWORD, + Extents: [DISK_EXTENT; ::ANYSIZE_ARRAY], +}} +pub type PVOLUME_DISK_EXTENTS = *mut VOLUME_DISK_EXTENTS; +pub const IOCTL_VOLUME_ONLINE: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 2, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_VOLUME_OFFLINE: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 3, METHOD_BUFFERED, + FILE_READ_ACCESS | FILE_WRITE_ACCESS); +pub const IOCTL_VOLUME_IS_CLUSTERED: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 12, METHOD_BUFFERED, + FILE_ANY_ACCESS); +pub const IOCTL_VOLUME_GET_GPT_ATTRIBUTES: ::DWORD = CTL_CODE!(IOCTL_VOLUME_BASE, 14, + METHOD_BUFFERED, FILE_ANY_ACCESS); diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winnetwk.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winnetwk.rs new file mode 100644 index 0000000..665d283 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winnetwk.rs @@ -0,0 +1,275 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Standard WINNET Header File for WIN32 +pub const WNNC_NET_MSNET: ::DWORD = 0x00010000; +pub const WNNC_NET_SMB: ::DWORD = 0x00020000; +pub const WNNC_NET_NETWARE: ::DWORD = 0x00030000; +pub const WNNC_NET_VINES: ::DWORD = 0x00040000; +pub const WNNC_NET_10NET: ::DWORD = 0x00050000; +pub const WNNC_NET_LOCUS: ::DWORD = 0x00060000; +pub const WNNC_NET_SUN_PC_NFS: ::DWORD = 0x00070000; +pub const WNNC_NET_LANSTEP: ::DWORD = 0x00080000; +pub const WNNC_NET_9TILES: ::DWORD = 0x00090000; +pub const WNNC_NET_LANTASTIC: ::DWORD = 0x000A0000; +pub const WNNC_NET_AS400: ::DWORD = 0x000B0000; +pub const WNNC_NET_FTP_NFS: ::DWORD = 0x000C0000; +pub const WNNC_NET_PATHWORKS: ::DWORD = 0x000D0000; +pub const WNNC_NET_LIFENET: ::DWORD = 0x000E0000; +pub const WNNC_NET_POWERLAN: ::DWORD = 0x000F0000; +pub const WNNC_NET_BWNFS: ::DWORD = 0x00100000; +pub const WNNC_NET_COGENT: ::DWORD = 0x00110000; +pub const WNNC_NET_FARALLON: ::DWORD = 0x00120000; +pub const WNNC_NET_APPLETALK: ::DWORD = 0x00130000; +pub const WNNC_NET_INTERGRAPH: ::DWORD = 0x00140000; +pub const WNNC_NET_SYMFONET: ::DWORD = 0x00150000; +pub const WNNC_NET_CLEARCASE: ::DWORD = 0x00160000; +pub const WNNC_NET_FRONTIER: ::DWORD = 0x00170000; +pub const WNNC_NET_BMC: ::DWORD = 0x00180000; +pub const WNNC_NET_DCE: ::DWORD = 0x00190000; +pub const WNNC_NET_AVID: ::DWORD = 0x001A0000; +pub const WNNC_NET_DOCUSPACE: ::DWORD = 0x001B0000; +pub const WNNC_NET_MANGOSOFT: ::DWORD = 0x001C0000; +pub const WNNC_NET_SERNET: ::DWORD = 0x001D0000; +pub const WNNC_NET_RIVERFRONT1: ::DWORD = 0x001E0000; +pub const WNNC_NET_RIVERFRONT2: ::DWORD = 0x001F0000; +pub const WNNC_NET_DECORB: ::DWORD = 0x00200000; +pub const WNNC_NET_PROTSTOR: ::DWORD = 0x00210000; +pub const WNNC_NET_FJ_REDIR: ::DWORD = 0x00220000; +pub const WNNC_NET_DISTINCT: ::DWORD = 0x00230000; +pub const WNNC_NET_TWINS: ::DWORD = 0x00240000; +pub const WNNC_NET_RDR2SAMPLE: ::DWORD = 0x00250000; +pub const WNNC_NET_CSC: ::DWORD = 0x00260000; +pub const WNNC_NET_3IN1: ::DWORD = 0x00270000; +pub const WNNC_NET_EXTENDNET: ::DWORD = 0x00290000; +pub const WNNC_NET_STAC: ::DWORD = 0x002A0000; +pub const WNNC_NET_FOXBAT: ::DWORD = 0x002B0000; +pub const WNNC_NET_YAHOO: ::DWORD = 0x002C0000; +pub const WNNC_NET_EXIFS: ::DWORD = 0x002D0000; +pub const WNNC_NET_DAV: ::DWORD = 0x002E0000; +pub const WNNC_NET_KNOWARE: ::DWORD = 0x002F0000; +pub const WNNC_NET_OBJECT_DIRE: ::DWORD = 0x00300000; +pub const WNNC_NET_MASFAX: ::DWORD = 0x00310000; +pub const WNNC_NET_HOB_NFS: ::DWORD = 0x00320000; +pub const WNNC_NET_SHIVA: ::DWORD = 0x00330000; +pub const WNNC_NET_IBMAL: ::DWORD = 0x00340000; +pub const WNNC_NET_LOCK: ::DWORD = 0x00350000; +pub const WNNC_NET_TERMSRV: ::DWORD = 0x00360000; +pub const WNNC_NET_SRT: ::DWORD = 0x00370000; +pub const WNNC_NET_QUINCY: ::DWORD = 0x00380000; +pub const WNNC_NET_OPENAFS: ::DWORD = 0x00390000; +pub const WNNC_NET_AVID1: ::DWORD = 0x003A0000; +pub const WNNC_NET_DFS: ::DWORD = 0x003B0000; +pub const WNNC_NET_KWNP: ::DWORD = 0x003C0000; +pub const WNNC_NET_ZENWORKS: ::DWORD = 0x003D0000; +pub const WNNC_NET_DRIVEONWEB: ::DWORD = 0x003E0000; +pub const WNNC_NET_VMWARE: ::DWORD = 0x003F0000; +pub const WNNC_NET_RSFX: ::DWORD = 0x00400000; +pub const WNNC_NET_MFILES: ::DWORD = 0x00410000; +pub const WNNC_NET_MS_NFS: ::DWORD = 0x00420000; +pub const WNNC_NET_GOOGLE: ::DWORD = 0x00430000; +pub const WNNC_NET_NDFS: ::DWORD = 0x00440000; +pub const WNNC_NET_DOCUSHARE: ::DWORD = 0x00450000; +pub const WNNC_CRED_MANAGER: ::DWORD = 0xFFFF0000; +pub const WNNC_NET_LANMAN: ::DWORD = WNNC_NET_SMB; +pub const RESOURCE_CONNECTED: ::DWORD = 0x00000001; +pub const RESOURCE_GLOBALNET: ::DWORD = 0x00000002; +pub const RESOURCE_REMEMBERED: ::DWORD = 0x00000003; +pub const RESOURCE_RECENT: ::DWORD = 0x00000004; +pub const RESOURCE_CONTEXT: ::DWORD = 0x00000005; +pub const RESOURCETYPE_ANY: ::DWORD = 0x00000000; +pub const RESOURCETYPE_DISK: ::DWORD = 0x00000001; +pub const RESOURCETYPE_PRINT: ::DWORD = 0x00000002; +pub const RESOURCETYPE_RESERVED: ::DWORD = 0x00000008; +pub const RESOURCETYPE_UNKNOWN: ::DWORD = 0xFFFFFFFF; +pub const RESOURCEUSAGE_CONNECTABLE: ::DWORD = 0x00000001; +pub const RESOURCEUSAGE_CONTAINER: ::DWORD = 0x00000002; +pub const RESOURCEUSAGE_NOLOCALDEVICE: ::DWORD = 0x00000004; +pub const RESOURCEUSAGE_SIBLING: ::DWORD = 0x00000008; +pub const RESOURCEUSAGE_ATTACHED: ::DWORD = 0x00000010; +pub const RESOURCEUSAGE_ALL: ::DWORD = RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER + | RESOURCEUSAGE_ATTACHED; +pub const RESOURCEUSAGE_RESERVED: ::DWORD = 0x80000000; +pub const RESOURCEDISPLAYTYPE_GENERIC: ::DWORD = 0x00000000; +pub const RESOURCEDISPLAYTYPE_DOMAIN: ::DWORD = 0x00000001; +pub const RESOURCEDISPLAYTYPE_SERVER: ::DWORD = 0x00000002; +pub const RESOURCEDISPLAYTYPE_SHARE: ::DWORD = 0x00000003; +pub const RESOURCEDISPLAYTYPE_FILE: ::DWORD = 0x00000004; +pub const RESOURCEDISPLAYTYPE_GROUP: ::DWORD = 0x00000005; +pub const RESOURCEDISPLAYTYPE_NETWORK: ::DWORD = 0x00000006; +pub const RESOURCEDISPLAYTYPE_ROOT: ::DWORD = 0x00000007; +pub const RESOURCEDISPLAYTYPE_SHAREADMIN: ::DWORD = 0x00000008; +pub const RESOURCEDISPLAYTYPE_DIRECTORY: ::DWORD = 0x00000009; +pub const RESOURCEDISPLAYTYPE_TREE: ::DWORD = 0x0000000A; +pub const RESOURCEDISPLAYTYPE_NDSCONTAINER: ::DWORD = 0x0000000B; +STRUCT!{struct NETRESOURCEA { + dwScope: ::DWORD, + dwType: ::DWORD, + dwDisplayType: ::DWORD, + dwUsage: ::DWORD, + lpLocalName: ::LPSTR, + lpRemoteName: ::LPSTR, + lpComment: ::LPSTR, + lpProvider: ::LPSTR, +}} +pub type LPNETRESOURCEA = *mut NETRESOURCEA; +STRUCT!{struct NETRESOURCEW { + dwScope: ::DWORD, + dwType: ::DWORD, + dwDisplayType: ::DWORD, + dwUsage: ::DWORD, + lpLocalName: ::LPWSTR, + lpRemoteName: ::LPWSTR, + lpComment: ::LPWSTR, + lpProvider: ::LPWSTR, +}} +pub type LPNETRESOURCEW = *mut NETRESOURCEW; +pub const NETPROPERTY_PERSISTENT: ::DWORD = 1; +pub const CONNECT_UPDATE_PROFILE: ::DWORD = 0x00000001; +pub const CONNECT_UPDATE_RECENT: ::DWORD = 0x00000002; +pub const CONNECT_TEMPORARY: ::DWORD = 0x00000004; +pub const CONNECT_INTERACTIVE: ::DWORD = 0x00000008; +pub const CONNECT_PROMPT: ::DWORD = 0x00000010; +pub const CONNECT_NEED_DRIVE: ::DWORD = 0x00000020; +pub const CONNECT_REFCOUNT: ::DWORD = 0x00000040; +pub const CONNECT_REDIRECT: ::DWORD = 0x00000080; +pub const CONNECT_LOCALDRIVE: ::DWORD = 0x00000100; +pub const CONNECT_CURRENT_MEDIA: ::DWORD = 0x00000200; +pub const CONNECT_DEFERRED: ::DWORD = 0x00000400; +pub const CONNECT_RESERVED: ::DWORD = 0xFF000000; +pub const CONNECT_COMMANDLINE: ::DWORD = 0x00000800; +pub const CONNECT_CMD_SAVECRED: ::DWORD = 0x00001000; +pub const CONNECT_CRED_RESET: ::DWORD = 0x00002000; +STRUCT!{struct CONNECTDLGSTRUCTA { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpConnRes: ::LPNETRESOURCEA, + dwFlags: ::DWORD, + dwDevNum: ::DWORD, +}} +pub type LPCONNECTDLGSTRUCTA = *mut CONNECTDLGSTRUCTA; +STRUCT!{struct CONNECTDLGSTRUCTW { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpConnRes: ::LPNETRESOURCEW, + dwFlags: ::DWORD, + dwDevNum: ::DWORD, +}} +pub type LPCONNECTDLGSTRUCTW = *mut CONNECTDLGSTRUCTW; +pub const CONNDLG_RO_PATH: ::DWORD = 0x00000001; +pub const CONNDLG_CONN_POINT: ::DWORD = 0x00000002; +pub const CONNDLG_USE_MRU: ::DWORD = 0x00000004; +pub const CONNDLG_HIDE_BOX: ::DWORD = 0x00000008; +pub const CONNDLG_PERSIST: ::DWORD = 0x00000010; +pub const CONNDLG_NOT_PERSIST: ::DWORD = 0x00000020; +STRUCT!{struct DISCDLGSTRUCTA { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpLocalName: ::LPSTR, + lpRemoteName: ::LPSTR, + dwFlags: ::DWORD, +}} +pub type LPDISCDLGSTRUCTA = *mut DISCDLGSTRUCTA; +STRUCT!{struct DISCDLGSTRUCTW { + cbStructure: ::DWORD, + hwndOwner: ::HWND, + lpLocalName: ::LPWSTR, + lpRemoteName: ::LPWSTR, + dwFlags: ::DWORD, +}} +pub type LPDISCDLGSTRUCTW = *mut DISCDLGSTRUCTW; +pub const DISC_UPDATE_PROFILE: ::DWORD = 0x00000001; +pub const DISC_NO_FORCE: ::DWORD = 0x00000040; +pub const UNIVERSAL_NAME_INFO_LEVEL: ::DWORD = 0x00000001; +pub const REMOTE_NAME_INFO_LEVEL: ::DWORD = 0x00000002; +STRUCT!{struct UNIVERSAL_NAME_INFOA { + lpUniversalName: ::LPSTR, +}} +pub type LPUNIVERSAL_NAME_INFOA = *mut UNIVERSAL_NAME_INFOA; +STRUCT!{struct UNIVERSAL_NAME_INFOW { + lpUniversalName: ::LPWSTR, +}} +pub type LPUNIVERSAL_NAME_INFOW = *mut UNIVERSAL_NAME_INFOW; +STRUCT!{struct REMOTE_NAME_INFOA { + lpUniversalName: ::LPSTR, + lpConnectionName: ::LPSTR, + lpRemainingPath: ::LPSTR, +}} +pub type LPREMOTE_NAME_INFOA = *mut REMOTE_NAME_INFOA; +STRUCT!{struct REMOTE_NAME_INFOW { + lpUniversalName: ::LPWSTR, + lpConnectionName: ::LPWSTR, + lpRemainingPath: ::LPWSTR, +}} +pub type LPREMOTE_NAME_INFOW = *mut REMOTE_NAME_INFOW; +pub const WNFMT_MULTILINE: ::DWORD = 0x01; +pub const WNFMT_ABBREVIATED: ::DWORD = 0x02; +pub const WNFMT_INENUM: ::DWORD = 0x10; +pub const WNFMT_CONNECTION: ::DWORD = 0x20; +STRUCT!{struct NETINFOSTRUCT { + cbStructure: ::DWORD, + dwProviderVersion: ::DWORD, + dwStatus: ::DWORD, + dwCharacteristics: ::DWORD, + dwHandle: ::ULONG_PTR, + wNetType: ::WORD, + dwPrinters: ::DWORD, + dwDrives: ::DWORD, +}} +pub type LPNETINFOSTRUCT = *mut NETINFOSTRUCT; +pub const NETINFO_DLL16: ::DWORD = 0x00000001; +pub const NETINFO_DISKRED: ::DWORD = 0x00000004; +pub const NETINFO_PRINTERRED: ::DWORD = 0x00000008; +pub const WN_SUCCESS: ::DWORD = ::NO_ERROR; +pub const WN_NO_ERROR: ::DWORD = ::NO_ERROR; +pub const WN_NOT_SUPPORTED: ::DWORD = ::ERROR_NOT_SUPPORTED; +pub const WN_CANCEL: ::DWORD = ::ERROR_CANCELLED; +pub const WN_RETRY: ::DWORD = ::ERROR_RETRY; +pub const WN_NET_ERROR: ::DWORD = ::ERROR_UNEXP_NET_ERR; +pub const WN_MORE_DATA: ::DWORD = ::ERROR_MORE_DATA; +pub const WN_BAD_POINTER: ::DWORD = ::ERROR_INVALID_ADDRESS; +pub const WN_BAD_VALUE: ::DWORD = ::ERROR_INVALID_PARAMETER; +pub const WN_BAD_USER: ::DWORD = ::ERROR_BAD_USERNAME; +pub const WN_BAD_PASSWORD: ::DWORD = ::ERROR_INVALID_PASSWORD; +pub const WN_ACCESS_DENIED: ::DWORD = ::ERROR_ACCESS_DENIED; +pub const WN_FUNCTION_BUSY: ::DWORD = ::ERROR_BUSY; +pub const WN_WINDOWS_ERROR: ::DWORD = ::ERROR_UNEXP_NET_ERR; +pub const WN_OUT_OF_MEMORY: ::DWORD = ::ERROR_NOT_ENOUGH_MEMORY; +pub const WN_NO_NETWORK: ::DWORD = ::ERROR_NO_NETWORK; +pub const WN_EXTENDED_ERROR: ::DWORD = ::ERROR_EXTENDED_ERROR; +pub const WN_BAD_LEVEL: ::DWORD = ::ERROR_INVALID_LEVEL; +pub const WN_BAD_HANDLE: ::DWORD = ::ERROR_INVALID_HANDLE; +pub const WN_NOT_INITIALIZING: ::DWORD = ::ERROR_ALREADY_INITIALIZED; +pub const WN_NO_MORE_DEVICES: ::DWORD = ::ERROR_NO_MORE_DEVICES; +pub const WN_NOT_CONNECTED: ::DWORD = ::ERROR_NOT_CONNECTED; +pub const WN_OPEN_FILES: ::DWORD = ::ERROR_OPEN_FILES; +pub const WN_DEVICE_IN_USE: ::DWORD = ::ERROR_DEVICE_IN_USE; +pub const WN_BAD_NETNAME: ::DWORD = ::ERROR_BAD_NET_NAME; +pub const WN_BAD_LOCALNAME: ::DWORD = ::ERROR_BAD_DEVICE; +pub const WN_ALREADY_CONNECTED: ::DWORD = ::ERROR_ALREADY_ASSIGNED; +pub const WN_DEVICE_ERROR: ::DWORD = ::ERROR_GEN_FAILURE; +pub const WN_CONNECTION_CLOSED: ::DWORD = ::ERROR_CONNECTION_UNAVAIL; +pub const WN_NO_NET_OR_BAD_PATH: ::DWORD = ::ERROR_NO_NET_OR_BAD_PATH; +pub const WN_BAD_PROVIDER: ::DWORD = ::ERROR_BAD_PROVIDER; +pub const WN_CANNOT_OPEN_PROFILE: ::DWORD = ::ERROR_CANNOT_OPEN_PROFILE; +pub const WN_BAD_PROFILE: ::DWORD = ::ERROR_BAD_PROFILE; +pub const WN_BAD_DEV_TYPE: ::DWORD = ::ERROR_BAD_DEV_TYPE; +pub const WN_DEVICE_ALREADY_REMEMBERED: ::DWORD = ::ERROR_DEVICE_ALREADY_REMEMBERED; +pub const WN_CONNECTED_OTHER_PASSWORD: ::DWORD = ::ERROR_CONNECTED_OTHER_PASSWORD; +pub const WN_CONNECTED_OTHER_PASSWORD_DEFAULT: ::DWORD = ::ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT; +pub const WN_NO_MORE_ENTRIES: ::DWORD = ::ERROR_NO_MORE_ITEMS; +pub const WN_NOT_CONTAINER: ::DWORD = ::ERROR_NOT_CONTAINER; +pub const WN_NOT_AUTHENTICATED: ::DWORD = ::ERROR_NOT_AUTHENTICATED; +pub const WN_NOT_LOGGED_ON: ::DWORD = ::ERROR_NOT_LOGGED_ON; +pub const WN_NOT_VALIDATED: ::DWORD = ::ERROR_NO_LOGON_SERVERS; +STRUCT!{struct NETCONNECTINFOSTRUCT { + cbStructure: ::DWORD, + dwFlags: ::DWORD, + dwSpeed: ::DWORD, + dwDelay: ::DWORD, + dwOptDataSize: ::DWORD, +}} +pub type LPNETCONNECTINFOSTRUCT = *mut NETCONNECTINFOSTRUCT; +pub const WNCON_FORNETCARD: ::DWORD = 0x00000001; +pub const WNCON_NOTROUTED: ::DWORD = 0x00000002; +pub const WNCON_SLOWLINK: ::DWORD = 0x00000004; +pub const WNCON_DYNAMIC: ::DWORD = 0x00000008; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winnls.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winnls.rs new file mode 100644 index 0000000..b27e2f0 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winnls.rs @@ -0,0 +1,164 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Procedure declarations, constant definitions, and macros for the NLS component. +pub const CP_ACP: ::DWORD = 0; +pub const CP_OEMCP: ::DWORD = 1; +pub const CP_MACCP: ::DWORD = 2; +pub const CP_THREAD_ACP: ::DWORD = 3; +pub const CP_SYMBOL: ::DWORD = 42; +pub const CP_UTF7: ::DWORD = 65000; +pub const CP_UTF8: ::DWORD = 65001; +pub const MAX_LEADBYTES: usize = 12; +pub const MAX_DEFAULTCHAR: usize = 2; +pub type LGRPID = ::DWORD; +pub type LCTYPE = ::DWORD; +pub type CALTYPE = ::DWORD; +pub type CALID = ::DWORD; +pub type GEOID = ::LONG; +pub type GEOTYPE = ::DWORD; +pub type GEOCLASS = ::DWORD; +STRUCT!{struct NLSVERSIONINFO { + dwNLSVersionInfoSize: ::DWORD, + dwNLSVersion: ::DWORD, + dwDefinedVersion: ::DWORD, + dwEffectiveId: ::DWORD, + guidCustomVersion: ::GUID, +}} +pub type LPNLSVERSIONINFO = *mut NLSVERSIONINFO; +STRUCT!{struct NLSVERSIONINFOEX { + dwNLSVersionInfoSize: ::DWORD, + dwNLSVersion: ::DWORD, + dwDefinedVersion: ::DWORD, + dwEffectiveId: ::DWORD, + guidCustomVersion: ::GUID, +}} +pub type LPNLSVERSIONINFOEX = *mut NLSVERSIONINFOEX; +ENUM!{enum NORM_FORM { + NormalizationOther = 0, + NormalizationC = 0x1, + NormalizationD = 0x2, + NormalizationKC = 0x5, + NormalizationKD = 0x6, +}} +pub type LANGUAGEGROUP_ENUMPROCA = Option ::BOOL>; +pub type LANGGROUPLOCALE_ENUMPROCA = Option ::BOOL>; +pub type UILANGUAGE_ENUMPROCA = Option ::BOOL>; +pub type CODEPAGE_ENUMPROCA = Option ::BOOL>; +pub type DATEFMT_ENUMPROCA = Option ::BOOL>; +pub type DATEFMT_ENUMPROCEXA = Option ::BOOL>; +pub type TIMEFMT_ENUMPROCA = Option ::BOOL>; +pub type CALINFO_ENUMPROCA = Option ::BOOL>; +pub type CALINFO_ENUMPROCEXA = Option ::BOOL>; +pub type LOCALE_ENUMPROCA = Option ::BOOL>; +pub type LOCALE_ENUMPROCW = Option ::BOOL>; +pub type LANGUAGEGROUP_ENUMPROCW = Option ::BOOL>; +pub type LANGGROUPLOCALE_ENUMPROCW = Option ::BOOL>; +pub type UILANGUAGE_ENUMPROCW = Option ::BOOL>; +pub type CODEPAGE_ENUMPROCW = Option ::BOOL>; +pub type DATEFMT_ENUMPROCW = Option ::BOOL>; +pub type DATEFMT_ENUMPROCEXW = Option ::BOOL>; +pub type TIMEFMT_ENUMPROCW = Option ::BOOL>; +pub type CALINFO_ENUMPROCW = Option ::BOOL>; +pub type CALINFO_ENUMPROCEXW = Option ::BOOL>; +pub type GEO_ENUMPROC = Option ::BOOL>; +STRUCT!{struct CPINFO { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], +}} +pub type LPCPINFO = *mut CPINFO; +STRUCT!{nodebug struct CPINFOEXA { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], + UnicodeDefaultChar: ::WCHAR, + CodePage: ::UINT, + CodePageName: [::CHAR; ::MAX_PATH], +}} +pub type LPCPINFOEXA = *mut CPINFOEXA; +STRUCT!{nodebug struct CPINFOEXW { + MaxCharSize: ::UINT, + DefaultChar: [::BYTE; MAX_DEFAULTCHAR], + LeadByte: [::BYTE; MAX_LEADBYTES], + UnicodeDefaultChar: ::WCHAR, + CodePage: ::UINT, + CodePageName: [::WCHAR; ::MAX_PATH], +}} +pub type LPCPINFOEXW = *mut CPINFOEXW; +STRUCT!{struct NUMBERFMTA { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPSTR, + lpThousandSep: ::LPSTR, + NegativeOrder: ::UINT, +}} +pub type LPNUMBERFMTA = *mut NUMBERFMTA; +STRUCT!{struct NUMBERFMTW { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPWSTR, + lpThousandSep: ::LPWSTR, + NegativeOrder: ::UINT, +}} +pub type LPNUMBERFMTW = *mut NUMBERFMTW; +STRUCT!{struct CURRENCYFMTA { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPSTR, + lpThousandSep: ::LPSTR, + NegativeOrder: ::UINT, + PositiveOrder: ::UINT, + lpCurrencySymbol: ::LPSTR, +}} +pub type LPCURRENCYFMTA = *mut CURRENCYFMTA; +STRUCT!{struct CURRENCYFMTW { + NumDigits: ::UINT, + LeadingZero: ::UINT, + Grouping: ::UINT, + lpDecimalSep: ::LPWSTR, + lpThousandSep: ::LPWSTR, + NegativeOrder: ::UINT, + PositiveOrder: ::UINT, + lpCurrencySymbol: ::LPWSTR, +}} +pub type LPCURRENCYFMTW = *mut CURRENCYFMTW; +pub type NLS_FUNCTION = ::DWORD; +STRUCT!{struct FILEMUIINFO { + dwSize: ::DWORD, + dwVersion: ::DWORD, + dwFileType: ::DWORD, + pChecksum: [::BYTE; 16], + pServiceChecksum: [::BYTE; 16], + dwLanguageNameOffset: ::DWORD, + dwTypeIDMainSize: ::DWORD, + dwTypeIDMainOffset: ::DWORD, + dwTypeNameMainOffset: ::DWORD, + dwTypeIDMUISize: ::DWORD, + dwTypeIDMUIOffset: ::DWORD, + dwTypeNameMUIOffset: ::DWORD, + abBuffer: [::BYTE; 8], +}} +pub type PFILEMUIINFO = *mut FILEMUIINFO; +pub type CALINFO_ENUMPROCEXEX = Option ::BOOL>; +pub type DATEFMT_ENUMPROCEXEX = Option ::BOOL>; +pub type TIMEFMT_ENUMPROCEX = Option ::BOOL>; +pub type LOCALE_ENUMPROCEX = Option ::BOOL>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winnt.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winnt.rs new file mode 100644 index 0000000..cce242e --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winnt.rs @@ -0,0 +1,2368 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This module defines the 32-Bit Windows types and constants that are defined by NT, but exposed +//! through the Win32 API. +pub const ANYSIZE_ARRAY: usize = 1; +//341 +pub type PVOID = *mut ::c_void; +pub type PVOID64 = u64; // This is a 64-bit pointer, even when in 32-bit +//382 +pub type VOID = ::c_void; +pub type CHAR = ::c_char; +pub type SHORT = ::c_short; +pub type LONG = ::c_long; +// pub type INT = ::c_int; // Already defined by minwindef.h +pub type WCHAR = ::wchar_t; +pub type PWCHAR = *mut WCHAR; +pub type LPWCH = *mut WCHAR; +pub type PWCH = *mut WCHAR; +pub type LPCWCH = *const WCHAR; +pub type PCWCH = *const WCHAR; +pub type NWPSTR = *mut WCHAR; +pub type LPWSTR = *mut WCHAR; +pub type PWSTR = *mut WCHAR; +pub type PZPWSTR = *mut PWSTR; +pub type PCZPWSTR = *const PWSTR; +pub type LPUWSTR = *mut WCHAR; +pub type PUWSTR = *mut WCHAR; +pub type LPCWSTR = *const WCHAR; +pub type PCWSTR = *const WCHAR; +pub type PZPCWSTR= *mut PCWSTR; +pub type PCZPCWSTR = *const PCWSTR; +pub type LPCUWSTR = *const WCHAR; +pub type PCUWSTR = *const WCHAR; +pub type PZZWSTR= *mut WCHAR; +pub type PCZZWSTR = *const WCHAR; +pub type PUZZWSTR = *mut WCHAR; +pub type PCUZZWSTR = *const WCHAR; +pub type PNZWCH = *mut WCHAR; +pub type PCNZWCH = *const WCHAR; +pub type PUNZWCH = *mut WCHAR; +pub type PCUNZWCH = *const WCHAR; +pub type LPCWCHAR = *const WCHAR; +pub type PCWCHAR = *const WCHAR; +pub type LPCUWCHAR = *const WCHAR; +pub type PCUWCHAR = *const WCHAR; +pub type UCSCHAR = ::c_ulong; +pub type PUCSCHAR = *mut UCSCHAR; +pub type PCUCSCHAR = *const UCSCHAR; +pub type PUCSSTR = *mut UCSCHAR; +pub type PUUCSSTR = *mut UCSCHAR; +pub type PCUCSSTR = *const UCSCHAR; +pub type PCUUCSSTR = *const UCSCHAR; +pub type PUUCSCHAR = *mut UCSCHAR; +pub type PCUUCSCHAR = *const UCSCHAR; +pub type PCHAR = *mut CHAR; +pub type LPCH = *mut CHAR; +pub type PCH = *mut CHAR; +pub type LPCCH = *const CHAR; +pub type PCCH = *const CHAR; +pub type NPSTR = *mut CHAR; +pub type LPSTR = *mut CHAR; +pub type PSTR = *mut CHAR; +pub type PZPSTR = *mut PSTR; +pub type PCZPSTR = *const PSTR; +pub type LPCSTR = *const CHAR; +pub type PCSTR = *const CHAR; +pub type PZPCSTR = *mut PCSTR; +pub type PCZPCSTR = *const PCSTR; +pub type PZZSTR = *mut CHAR; +pub type PCZZSTR = *const CHAR; +pub type PNZCH = *mut CHAR; +pub type PCNZCH = *const CHAR; +// Skipping TCHAR things +pub type PSHORT = *mut SHORT; +pub type PLONG = *mut LONG; +STRUCT!{struct PROCESSOR_NUMBER { + Group: ::WORD, + Number: ::BYTE, + Reserved: ::BYTE, +}} +pub type PPROCESSOR_NUMBER = *mut PROCESSOR_NUMBER; +STRUCT!{struct GROUP_AFFINITY { + Mask: ::KAFFINITY, + Group: ::WORD, + Reserved: [::WORD; 3], +}} +pub type PGROUP_AFFINITY = *mut GROUP_AFFINITY; +pub type HANDLE = *mut ::c_void; +pub type PHANDLE = *mut HANDLE; +pub type FCHAR = ::BYTE; +pub type FSHORT = ::WORD; +pub type FLONG = ::DWORD; +//667 +pub type CCHAR = ::c_char; +pub type LCID = ::DWORD; +pub type PLCID = ::PDWORD; +pub type LANGID = ::WORD; +ENUM!{enum COMPARTMENT_ID { + UNSPECIFIED_COMPARTMENT_ID = 0, + DEFAULT_COMPARTMENT_ID = 1, +}} +pub type PCOMPARTMENT_ID = *mut COMPARTMENT_ID; +pub const APPLICATION_ERROR_MASK: ::DWORD = 0x20000000; +pub const ERROR_SEVERITY_SUCCESS: ::DWORD = 0x00000000; +pub const ERROR_SEVERITY_INFORMATIONAL: ::DWORD = 0x40000000; +pub const ERROR_SEVERITY_WARNING: ::DWORD = 0x80000000; +pub const ERROR_SEVERITY_ERROR: ::DWORD = 0xC0000000; +//710 +STRUCT!{struct FLOAT128 { + LowPart: ::__int64, + HighPart: ::__int64, +}} +pub type PFLOAT128 = *mut FLOAT128; +pub type LONGLONG = ::__int64; +pub type ULONGLONG = ::__uint64; +pub type PLONGLONG = *mut LONGLONG; +pub type PULONGLONG = *mut ULONGLONG; +pub type USN = LONGLONG; +pub type LARGE_INTEGER = LONGLONG; +pub type PLARGE_INTEGER = *mut LARGE_INTEGER; +pub type ULARGE_INTEGER = ULONGLONG; +pub type PULARGE_INTEGER= *mut ULARGE_INTEGER; +pub type RTL_REFERENCE_COUNT = ::LONG_PTR; +pub type PRTL_REFERENCE_COUNT = *mut ::LONG_PTR; +STRUCT!{struct LUID { + LowPart: ::DWORD, + HighPart: LONG, +}} +pub type PLUID = *mut LUID; +pub type DWORDLONG = ULONGLONG; +pub type PDWORDLONG = *mut DWORDLONG; +//1042 +pub type BOOLEAN = ::BYTE; +pub type PBOOLEAN = *mut BOOLEAN; +STRUCT!{struct LIST_ENTRY { + Flink: *mut LIST_ENTRY, + Blink: *mut LIST_ENTRY, +}} +pub type PLIST_ENTRY = *mut LIST_ENTRY; +STRUCT!{struct SINGLE_LIST_ENTRY { + Next: *mut SINGLE_LIST_ENTRY, +}} +pub type PSINGLE_LIST_ENTRY = *mut SINGLE_LIST_ENTRY; +STRUCT!{struct LIST_ENTRY32 { + Flink: ::DWORD, + Blink: ::DWORD, +}} +pub type PLIST_ENTRY32 = *mut LIST_ENTRY32; +STRUCT!{struct LIST_ENTRY64 { + Flink: ULONGLONG, + Blink: ULONGLONG, +}} +pub type PLIST_ENTRY64 = *mut LIST_ENTRY64; +STRUCT!{struct OBJECTID { + Lineage: ::GUID, + Uniquifier: ::DWORD, +}} +pub const MINCHAR: ::CHAR = 0x80u8 as ::CHAR; +pub const MAXCHAR: ::CHAR = 0x7f; +pub const MINSHORT: ::SHORT = 0x8000u16 as ::SHORT; +pub const MAXSHORT: ::SHORT = 0x7fff; +pub const MINLONG: ::LONG = 0x80000000u32 as ::LONG; +pub const MAXLONG: ::LONG = 0x7fffffff; +pub const MAXBYTE: ::BYTE = 0xff; +pub const MAXWORD: ::WORD = 0xffff; +pub const MAXDWORD: ::DWORD = 0xffffffff; +//1300 +pub type PEXCEPTION_ROUTINE = Option ::EXCEPTION_DISPOSITION>; +//1498 +pub const LANG_NEUTRAL: ::WORD = 0x00; +pub const LANG_INVARIANT: ::WORD = 0x7f; +pub const LANG_AFRIKAANS: ::WORD = 0x36; +pub const LANG_ALBANIAN: ::WORD = 0x1c; +pub const LANG_ALSATIAN: ::WORD = 0x84; +pub const LANG_AMHARIC: ::WORD = 0x5e; +pub const LANG_ARABIC: ::WORD = 0x01; +pub const LANG_ARMENIAN: ::WORD = 0x2b; +pub const LANG_ASSAMESE: ::WORD = 0x4d; +pub const LANG_AZERI: ::WORD = 0x2c; +pub const LANG_AZERBAIJANI: ::WORD = 0x2c; +pub const LANG_BANGLA: ::WORD = 0x45; +pub const LANG_BASHKIR: ::WORD = 0x6d; +pub const LANG_BASQUE: ::WORD = 0x2d; +pub const LANG_BELARUSIAN: ::WORD = 0x23; +pub const LANG_BENGALI: ::WORD = 0x45; +pub const LANG_BRETON: ::WORD = 0x7e; +pub const LANG_BOSNIAN: ::WORD = 0x1a; +pub const LANG_BOSNIAN_NEUTRAL: ::WORD = 0x781a; +pub const LANG_BULGARIAN: ::WORD = 0x02; +pub const LANG_CATALAN: ::WORD = 0x03; +pub const LANG_CENTRAL_KURDISH: ::WORD = 0x92; +pub const LANG_CHEROKEE: ::WORD = 0x5c; +pub const LANG_CHINESE: ::WORD = 0x04; +pub const LANG_CHINESE_SIMPLIFIED: ::WORD = 0x04; +pub const LANG_CHINESE_TRADITIONAL: ::WORD = 0x7c04; +pub const LANG_CORSICAN: ::WORD = 0x83; +pub const LANG_CROATIAN: ::WORD = 0x1a; +pub const LANG_CZECH: ::WORD = 0x05; +pub const LANG_DANISH: ::WORD = 0x06; +pub const LANG_DARI: ::WORD = 0x8c; +pub const LANG_DIVEHI: ::WORD = 0x65; +pub const LANG_DUTCH: ::WORD = 0x13; +pub const LANG_ENGLISH: ::WORD = 0x09; +pub const LANG_ESTONIAN: ::WORD = 0x25; +pub const LANG_FAEROESE: ::WORD = 0x38; +pub const LANG_FARSI: ::WORD = 0x29; +pub const LANG_FILIPINO: ::WORD = 0x64; +pub const LANG_FINNISH: ::WORD = 0x0b; +pub const LANG_FRENCH: ::WORD = 0x0c; +pub const LANG_FRISIAN: ::WORD = 0x62; +pub const LANG_FULAH: ::WORD = 0x67; +pub const LANG_GALICIAN: ::WORD = 0x56; +pub const LANG_GEORGIAN: ::WORD = 0x37; +pub const LANG_GERMAN: ::WORD = 0x07; +pub const LANG_GREEK: ::WORD = 0x08; +pub const LANG_GREENLANDIC: ::WORD = 0x6f; +pub const LANG_GUJARATI: ::WORD = 0x47; +pub const LANG_HAUSA: ::WORD = 0x68; +pub const LANG_HAWAIIAN: ::WORD = 0x75; +pub const LANG_HEBREW: ::WORD = 0x0d; +pub const LANG_HINDI: ::WORD = 0x39; +pub const LANG_HUNGARIAN: ::WORD = 0x0e; +pub const LANG_ICELANDIC: ::WORD = 0x0f; +pub const LANG_IGBO: ::WORD = 0x70; +pub const LANG_INDONESIAN: ::WORD = 0x21; +pub const LANG_INUKTITUT: ::WORD = 0x5d; +pub const LANG_IRISH: ::WORD = 0x3c; +pub const LANG_ITALIAN: ::WORD = 0x10; +pub const LANG_JAPANESE: ::WORD = 0x11; +pub const LANG_KANNADA: ::WORD = 0x4b; +pub const LANG_KASHMIRI: ::WORD = 0x60; +pub const LANG_KAZAK: ::WORD = 0x3f; +pub const LANG_KHMER: ::WORD = 0x53; +pub const LANG_KICHE: ::WORD = 0x86; +pub const LANG_KINYARWANDA: ::WORD = 0x87; +pub const LANG_KONKANI: ::WORD = 0x57; +pub const LANG_KOREAN: ::WORD = 0x12; +pub const LANG_KYRGYZ: ::WORD = 0x40; +pub const LANG_LAO: ::WORD = 0x54; +pub const LANG_LATVIAN: ::WORD = 0x26; +pub const LANG_LITHUANIAN: ::WORD = 0x27; +pub const LANG_LOWER_SORBIAN: ::WORD = 0x2e; +pub const LANG_LUXEMBOURGISH: ::WORD = 0x6e; +pub const LANG_MACEDONIAN: ::WORD = 0x2f; +pub const LANG_MALAY: ::WORD = 0x3e; +pub const LANG_MALAYALAM: ::WORD = 0x4c; +pub const LANG_MALTESE: ::WORD = 0x3a; +pub const LANG_MANIPURI: ::WORD = 0x58; +pub const LANG_MAORI: ::WORD = 0x81; +pub const LANG_MAPUDUNGUN: ::WORD = 0x7a; +pub const LANG_MARATHI: ::WORD = 0x4e; +pub const LANG_MOHAWK: ::WORD = 0x7c; +pub const LANG_MONGOLIAN: ::WORD = 0x50; +pub const LANG_NEPALI: ::WORD = 0x61; +pub const LANG_NORWEGIAN: ::WORD = 0x14; +pub const LANG_OCCITAN: ::WORD = 0x82; +pub const LANG_ODIA: ::WORD = 0x48; +pub const LANG_ORIYA: ::WORD = 0x48; +pub const LANG_PASHTO: ::WORD = 0x63; +pub const LANG_PERSIAN: ::WORD = 0x29; +pub const LANG_POLISH: ::WORD = 0x15; +pub const LANG_PORTUGUESE: ::WORD = 0x16; +pub const LANG_PULAR: ::WORD = 0x67; +pub const LANG_PUNJABI: ::WORD = 0x46; +pub const LANG_QUECHUA: ::WORD = 0x6b; +pub const LANG_ROMANIAN: ::WORD = 0x18; +pub const LANG_ROMANSH: ::WORD = 0x17; +pub const LANG_RUSSIAN: ::WORD = 0x19; +pub const LANG_SAKHA: ::WORD = 0x85; +pub const LANG_SAMI: ::WORD = 0x3b; +pub const LANG_SANSKRIT: ::WORD = 0x4f; +pub const LANG_SCOTTISH_GAELIC: ::WORD = 0x91; +pub const LANG_SERBIAN: ::WORD = 0x1a; +pub const LANG_SERBIAN_NEUTRAL: ::WORD = 0x7c1a; +pub const LANG_SINDHI: ::WORD = 0x59; +pub const LANG_SINHALESE: ::WORD = 0x5b; +pub const LANG_SLOVAK: ::WORD = 0x1b; +pub const LANG_SLOVENIAN: ::WORD = 0x24; +pub const LANG_SOTHO: ::WORD = 0x6c; +pub const LANG_SPANISH: ::WORD = 0x0a; +pub const LANG_SWAHILI: ::WORD = 0x41; +pub const LANG_SWEDISH: ::WORD = 0x1d; +pub const LANG_SYRIAC: ::WORD = 0x5a; +pub const LANG_TAJIK: ::WORD = 0x28; +pub const LANG_TAMAZIGHT: ::WORD = 0x5f; +pub const LANG_TAMIL: ::WORD = 0x49; +pub const LANG_TATAR: ::WORD = 0x44; +pub const LANG_TELUGU: ::WORD = 0x4a; +pub const LANG_THAI: ::WORD = 0x1e; +pub const LANG_TIBETAN: ::WORD = 0x51; +pub const LANG_TIGRIGNA: ::WORD = 0x73; +pub const LANG_TIGRINYA: ::WORD = 0x73; +pub const LANG_TSWANA: ::WORD = 0x32; +pub const LANG_TURKISH: ::WORD = 0x1f; +pub const LANG_TURKMEN: ::WORD = 0x42; +pub const LANG_UIGHUR: ::WORD = 0x80; +pub const LANG_UKRAINIAN: ::WORD = 0x22; +pub const LANG_UPPER_SORBIAN: ::WORD = 0x2e; +pub const LANG_URDU: ::WORD = 0x20; +pub const LANG_UZBEK: ::WORD = 0x43; +pub const LANG_VALENCIAN: ::WORD = 0x03; +pub const LANG_VIETNAMESE: ::WORD = 0x2a; +pub const LANG_WELSH: ::WORD = 0x52; +pub const LANG_WOLOF: ::WORD = 0x88; +pub const LANG_XHOSA: ::WORD = 0x34; +pub const LANG_YAKUT: ::WORD = 0x85; +pub const LANG_YI: ::WORD = 0x78; +pub const LANG_YORUBA: ::WORD = 0x6a; +pub const LANG_ZULU: ::WORD = 0x35; +//1651 +pub const SUBLANG_NEUTRAL: ::WORD = 0x00; +pub const SUBLANG_DEFAULT: ::WORD = 0x01; +pub const SUBLANG_SYS_DEFAULT: ::WORD = 0x02; +pub const SUBLANG_CUSTOM_DEFAULT: ::WORD = 0x03; +pub const SUBLANG_CUSTOM_UNSPECIFIED: ::WORD = 0x04; +pub const SUBLANG_UI_CUSTOM_DEFAULT: ::WORD = 0x05; +pub const SUBLANG_AFRIKAANS_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_ALBANIAN_ALBANIA: ::WORD = 0x01; +pub const SUBLANG_ALSATIAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_AMHARIC_ETHIOPIA: ::WORD = 0x01; +pub const SUBLANG_ARABIC_SAUDI_ARABIA: ::WORD = 0x01; +pub const SUBLANG_ARABIC_IRAQ: ::WORD = 0x02; +pub const SUBLANG_ARABIC_EGYPT: ::WORD = 0x03; +pub const SUBLANG_ARABIC_LIBYA: ::WORD = 0x04; +pub const SUBLANG_ARABIC_ALGERIA: ::WORD = 0x05; +pub const SUBLANG_ARABIC_MOROCCO: ::WORD = 0x06; +pub const SUBLANG_ARABIC_TUNISIA: ::WORD = 0x07; +pub const SUBLANG_ARABIC_OMAN: ::WORD = 0x08; +pub const SUBLANG_ARABIC_YEMEN: ::WORD = 0x09; +pub const SUBLANG_ARABIC_SYRIA: ::WORD = 0x0a; +pub const SUBLANG_ARABIC_JORDAN: ::WORD = 0x0b; +pub const SUBLANG_ARABIC_LEBANON: ::WORD = 0x0c; +pub const SUBLANG_ARABIC_KUWAIT: ::WORD = 0x0d; +pub const SUBLANG_ARABIC_UAE: ::WORD = 0x0e; +pub const SUBLANG_ARABIC_BAHRAIN: ::WORD = 0x0f; +pub const SUBLANG_ARABIC_QATAR: ::WORD = 0x10; +pub const SUBLANG_ARMENIAN_ARMENIA: ::WORD = 0x01; +pub const SUBLANG_ASSAMESE_INDIA: ::WORD = 0x01; +pub const SUBLANG_AZERI_LATIN: ::WORD = 0x01; +pub const SUBLANG_AZERI_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_LATIN: ::WORD = 0x01; +pub const SUBLANG_AZERBAIJANI_AZERBAIJAN_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_BANGLA_INDIA: ::WORD = 0x01; +pub const SUBLANG_BANGLA_BANGLADESH: ::WORD = 0x02; +pub const SUBLANG_BASHKIR_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_BASQUE_BASQUE: ::WORD = 0x01; +pub const SUBLANG_BELARUSIAN_BELARUS: ::WORD = 0x01; +pub const SUBLANG_BENGALI_INDIA: ::WORD = 0x01; +pub const SUBLANG_BENGALI_BANGLADESH: ::WORD = 0x02; +pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x05; +pub const SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC: ::WORD = 0x08; +pub const SUBLANG_BRETON_FRANCE: ::WORD = 0x01; +pub const SUBLANG_BULGARIAN_BULGARIA: ::WORD = 0x01; +pub const SUBLANG_CATALAN_CATALAN: ::WORD = 0x01; +pub const SUBLANG_CENTRAL_KURDISH_IRAQ: ::WORD = 0x01; +pub const SUBLANG_CHEROKEE_CHEROKEE: ::WORD = 0x01; +pub const SUBLANG_CHINESE_TRADITIONAL: ::WORD = 0x01; +pub const SUBLANG_CHINESE_SIMPLIFIED: ::WORD = 0x02; +pub const SUBLANG_CHINESE_HONGKONG: ::WORD = 0x03; +pub const SUBLANG_CHINESE_SINGAPORE: ::WORD = 0x04; +pub const SUBLANG_CHINESE_MACAU: ::WORD = 0x05; +pub const SUBLANG_CORSICAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_CZECH_CZECH_REPUBLIC: ::WORD = 0x01; +pub const SUBLANG_CROATIAN_CROATIA: ::WORD = 0x01; +pub const SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x04; +pub const SUBLANG_DANISH_DENMARK: ::WORD = 0x01; +pub const SUBLANG_DARI_AFGHANISTAN: ::WORD = 0x01; +pub const SUBLANG_DIVEHI_MALDIVES: ::WORD = 0x01; +pub const SUBLANG_DUTCH: ::WORD = 0x01; +pub const SUBLANG_DUTCH_BELGIAN: ::WORD = 0x02; +pub const SUBLANG_ENGLISH_US: ::WORD = 0x01; +pub const SUBLANG_ENGLISH_UK: ::WORD = 0x02; +pub const SUBLANG_ENGLISH_AUS: ::WORD = 0x03; +pub const SUBLANG_ENGLISH_CAN: ::WORD = 0x04; +pub const SUBLANG_ENGLISH_NZ: ::WORD = 0x05; +pub const SUBLANG_ENGLISH_EIRE: ::WORD = 0x06; +pub const SUBLANG_ENGLISH_SOUTH_AFRICA: ::WORD = 0x07; +pub const SUBLANG_ENGLISH_JAMAICA: ::WORD = 0x08; +pub const SUBLANG_ENGLISH_CARIBBEAN: ::WORD = 0x09; +pub const SUBLANG_ENGLISH_BELIZE: ::WORD = 0x0a; +pub const SUBLANG_ENGLISH_TRINIDAD: ::WORD = 0x0b; +pub const SUBLANG_ENGLISH_ZIMBABWE: ::WORD = 0x0c; +pub const SUBLANG_ENGLISH_PHILIPPINES: ::WORD = 0x0d; +pub const SUBLANG_ENGLISH_INDIA: ::WORD = 0x10; +pub const SUBLANG_ENGLISH_MALAYSIA: ::WORD = 0x11; +pub const SUBLANG_ENGLISH_SINGAPORE: ::WORD = 0x12; +pub const SUBLANG_ESTONIAN_ESTONIA: ::WORD = 0x01; +pub const SUBLANG_FAEROESE_FAROE_ISLANDS: ::WORD = 0x01; +pub const SUBLANG_FILIPINO_PHILIPPINES: ::WORD = 0x01; +pub const SUBLANG_FINNISH_FINLAND: ::WORD = 0x01; +pub const SUBLANG_FRENCH: ::WORD = 0x01; +pub const SUBLANG_FRENCH_BELGIAN: ::WORD = 0x02; +pub const SUBLANG_FRENCH_CANADIAN: ::WORD = 0x03; +pub const SUBLANG_FRENCH_SWISS: ::WORD = 0x04; +pub const SUBLANG_FRENCH_LUXEMBOURG: ::WORD = 0x05; +pub const SUBLANG_FRENCH_MONACO: ::WORD = 0x06; +pub const SUBLANG_FRISIAN_NETHERLANDS: ::WORD = 0x01; +pub const SUBLANG_FULAH_SENEGAL: ::WORD = 0x02; +pub const SUBLANG_GALICIAN_GALICIAN: ::WORD = 0x01; +pub const SUBLANG_GEORGIAN_GEORGIA: ::WORD = 0x01; +pub const SUBLANG_GERMAN: ::WORD = 0x01; +pub const SUBLANG_GERMAN_SWISS: ::WORD = 0x02; +pub const SUBLANG_GERMAN_AUSTRIAN: ::WORD = 0x03; +pub const SUBLANG_GERMAN_LUXEMBOURG: ::WORD = 0x04; +pub const SUBLANG_GERMAN_LIECHTENSTEIN: ::WORD = 0x05; +pub const SUBLANG_GREEK_GREECE: ::WORD = 0x01; +pub const SUBLANG_GREENLANDIC_GREENLAND: ::WORD = 0x01; +pub const SUBLANG_GUJARATI_INDIA: ::WORD = 0x01; +pub const SUBLANG_HAUSA_NIGERIA_LATIN: ::WORD = 0x01; +pub const SUBLANG_HAWAIIAN_US: ::WORD = 0x01; +pub const SUBLANG_HEBREW_ISRAEL: ::WORD = 0x01; +pub const SUBLANG_HINDI_INDIA: ::WORD = 0x01; +pub const SUBLANG_HUNGARIAN_HUNGARY: ::WORD = 0x01; +pub const SUBLANG_ICELANDIC_ICELAND: ::WORD = 0x01; +pub const SUBLANG_IGBO_NIGERIA: ::WORD = 0x01; +pub const SUBLANG_INDONESIAN_INDONESIA: ::WORD = 0x01; +pub const SUBLANG_INUKTITUT_CANADA: ::WORD = 0x01; +pub const SUBLANG_INUKTITUT_CANADA_LATIN: ::WORD = 0x02; +pub const SUBLANG_IRISH_IRELAND: ::WORD = 0x02; +pub const SUBLANG_ITALIAN: ::WORD = 0x01; +pub const SUBLANG_ITALIAN_SWISS: ::WORD = 0x02; +pub const SUBLANG_JAPANESE_JAPAN: ::WORD = 0x01; +pub const SUBLANG_KANNADA_INDIA: ::WORD = 0x01; +pub const SUBLANG_KASHMIRI_SASIA: ::WORD = 0x02; +pub const SUBLANG_KASHMIRI_INDIA: ::WORD = 0x02; +pub const SUBLANG_KAZAK_KAZAKHSTAN: ::WORD = 0x01; +pub const SUBLANG_KHMER_CAMBODIA: ::WORD = 0x01; +pub const SUBLANG_KICHE_GUATEMALA: ::WORD = 0x01; +pub const SUBLANG_KINYARWANDA_RWANDA: ::WORD = 0x01; +pub const SUBLANG_KONKANI_INDIA: ::WORD = 0x01; +pub const SUBLANG_KOREAN: ::WORD = 0x01; +pub const SUBLANG_KYRGYZ_KYRGYZSTAN: ::WORD = 0x01; +pub const SUBLANG_LAO_LAO: ::WORD = 0x01; +pub const SUBLANG_LATVIAN_LATVIA: ::WORD = 0x01; +pub const SUBLANG_LITHUANIAN: ::WORD = 0x01; +pub const SUBLANG_LOWER_SORBIAN_GERMANY: ::WORD = 0x02; +pub const SUBLANG_LUXEMBOURGISH_LUXEMBOURG: ::WORD = 0x01; +pub const SUBLANG_MACEDONIAN_MACEDONIA: ::WORD = 0x01; +pub const SUBLANG_MALAY_MALAYSIA: ::WORD = 0x01; +pub const SUBLANG_MALAY_BRUNEI_DARUSSALAM: ::WORD = 0x02; +pub const SUBLANG_MALAYALAM_INDIA: ::WORD = 0x01; +pub const SUBLANG_MALTESE_MALTA: ::WORD = 0x01; +pub const SUBLANG_MAORI_NEW_ZEALAND: ::WORD = 0x01; +pub const SUBLANG_MAPUDUNGUN_CHILE: ::WORD = 0x01; +pub const SUBLANG_MARATHI_INDIA: ::WORD = 0x01; +pub const SUBLANG_MOHAWK_MOHAWK: ::WORD = 0x01; +pub const SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA: ::WORD = 0x01; +pub const SUBLANG_MONGOLIAN_PRC: ::WORD = 0x02; +pub const SUBLANG_NEPALI_INDIA: ::WORD = 0x02; +pub const SUBLANG_NEPALI_NEPAL: ::WORD = 0x01; +pub const SUBLANG_NORWEGIAN_BOKMAL: ::WORD = 0x01; +pub const SUBLANG_NORWEGIAN_NYNORSK: ::WORD = 0x02; +pub const SUBLANG_OCCITAN_FRANCE: ::WORD = 0x01; +pub const SUBLANG_ODIA_INDIA: ::WORD = 0x01; +pub const SUBLANG_ORIYA_INDIA: ::WORD = 0x01; +pub const SUBLANG_PASHTO_AFGHANISTAN: ::WORD = 0x01; +pub const SUBLANG_PERSIAN_IRAN: ::WORD = 0x01; +pub const SUBLANG_POLISH_POLAND: ::WORD = 0x01; +pub const SUBLANG_PORTUGUESE: ::WORD = 0x02; +pub const SUBLANG_PORTUGUESE_BRAZILIAN: ::WORD = 0x01; +pub const SUBLANG_PULAR_SENEGAL: ::WORD = 0x02; +pub const SUBLANG_PUNJABI_INDIA: ::WORD = 0x01; +pub const SUBLANG_PUNJABI_PAKISTAN: ::WORD = 0x02; +pub const SUBLANG_QUECHUA_BOLIVIA: ::WORD = 0x01; +pub const SUBLANG_QUECHUA_ECUADOR: ::WORD = 0x02; +pub const SUBLANG_QUECHUA_PERU: ::WORD = 0x03; +pub const SUBLANG_ROMANIAN_ROMANIA: ::WORD = 0x01; +pub const SUBLANG_ROMANSH_SWITZERLAND: ::WORD = 0x01; +pub const SUBLANG_RUSSIAN_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_SAKHA_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_SAMI_NORTHERN_NORWAY: ::WORD = 0x01; +pub const SUBLANG_SAMI_NORTHERN_SWEDEN: ::WORD = 0x02; +pub const SUBLANG_SAMI_NORTHERN_FINLAND: ::WORD = 0x03; +pub const SUBLANG_SAMI_LULE_NORWAY: ::WORD = 0x04; +pub const SUBLANG_SAMI_LULE_SWEDEN: ::WORD = 0x05; +pub const SUBLANG_SAMI_SOUTHERN_NORWAY: ::WORD = 0x06; +pub const SUBLANG_SAMI_SOUTHERN_SWEDEN: ::WORD = 0x07; +pub const SUBLANG_SAMI_SKOLT_FINLAND: ::WORD = 0x08; +pub const SUBLANG_SAMI_INARI_FINLAND: ::WORD = 0x09; +pub const SUBLANG_SANSKRIT_INDIA: ::WORD = 0x01; +pub const SUBLANG_SCOTTISH_GAELIC: ::WORD = 0x01; +pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN: ::WORD = 0x06; +pub const SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC: ::WORD = 0x07; +pub const SUBLANG_SERBIAN_MONTENEGRO_LATIN: ::WORD = 0x0b; +pub const SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC: ::WORD = 0x0c; +pub const SUBLANG_SERBIAN_SERBIA_LATIN: ::WORD = 0x09; +pub const SUBLANG_SERBIAN_SERBIA_CYRILLIC: ::WORD = 0x0a; +pub const SUBLANG_SERBIAN_CROATIA: ::WORD = 0x01; +pub const SUBLANG_SERBIAN_LATIN: ::WORD = 0x02; +pub const SUBLANG_SERBIAN_CYRILLIC: ::WORD = 0x03; +pub const SUBLANG_SINDHI_INDIA: ::WORD = 0x01; +pub const SUBLANG_SINDHI_PAKISTAN: ::WORD = 0x02; +pub const SUBLANG_SINDHI_AFGHANISTAN: ::WORD = 0x02; +pub const SUBLANG_SINHALESE_SRI_LANKA: ::WORD = 0x01; +pub const SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_SLOVAK_SLOVAKIA: ::WORD = 0x01; +pub const SUBLANG_SLOVENIAN_SLOVENIA: ::WORD = 0x01; +pub const SUBLANG_SPANISH: ::WORD = 0x01; +pub const SUBLANG_SPANISH_MEXICAN: ::WORD = 0x02; +pub const SUBLANG_SPANISH_MODERN: ::WORD = 0x03; +pub const SUBLANG_SPANISH_GUATEMALA: ::WORD = 0x04; +pub const SUBLANG_SPANISH_COSTA_RICA: ::WORD = 0x05; +pub const SUBLANG_SPANISH_PANAMA: ::WORD = 0x06; +pub const SUBLANG_SPANISH_DOMINICAN_REPUBLIC: ::WORD = 0x07; +pub const SUBLANG_SPANISH_VENEZUELA: ::WORD = 0x08; +pub const SUBLANG_SPANISH_COLOMBIA: ::WORD = 0x09; +pub const SUBLANG_SPANISH_PERU: ::WORD = 0x0a; +pub const SUBLANG_SPANISH_ARGENTINA: ::WORD = 0x0b; +pub const SUBLANG_SPANISH_ECUADOR: ::WORD = 0x0c; +pub const SUBLANG_SPANISH_CHILE: ::WORD = 0x0d; +pub const SUBLANG_SPANISH_URUGUAY: ::WORD = 0x0e; +pub const SUBLANG_SPANISH_PARAGUAY: ::WORD = 0x0f; +pub const SUBLANG_SPANISH_BOLIVIA: ::WORD = 0x10; +pub const SUBLANG_SPANISH_EL_SALVADOR: ::WORD = 0x11; +pub const SUBLANG_SPANISH_HONDURAS: ::WORD = 0x12; +pub const SUBLANG_SPANISH_NICARAGUA: ::WORD = 0x13; +pub const SUBLANG_SPANISH_PUERTO_RICO: ::WORD = 0x14; +pub const SUBLANG_SPANISH_US: ::WORD = 0x15; +pub const SUBLANG_SWAHILI_KENYA: ::WORD = 0x01; +pub const SUBLANG_SWEDISH: ::WORD = 0x01; +pub const SUBLANG_SWEDISH_FINLAND: ::WORD = 0x02; +pub const SUBLANG_SYRIAC_SYRIA: ::WORD = 0x01; +pub const SUBLANG_TAJIK_TAJIKISTAN: ::WORD = 0x01; +pub const SUBLANG_TAMAZIGHT_ALGERIA_LATIN: ::WORD = 0x02; +pub const SUBLANG_TAMAZIGHT_MOROCCO_TIFINAGH: ::WORD = 0x04; +pub const SUBLANG_TAMIL_INDIA: ::WORD = 0x01; +pub const SUBLANG_TAMIL_SRI_LANKA: ::WORD = 0x02; +pub const SUBLANG_TATAR_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_TELUGU_INDIA: ::WORD = 0x01; +pub const SUBLANG_THAI_THAILAND: ::WORD = 0x01; +pub const SUBLANG_TIBETAN_PRC: ::WORD = 0x01; +pub const SUBLANG_TIGRIGNA_ERITREA: ::WORD = 0x02; +pub const SUBLANG_TIGRINYA_ERITREA: ::WORD = 0x02; +pub const SUBLANG_TIGRINYA_ETHIOPIA: ::WORD = 0x01; +pub const SUBLANG_TSWANA_BOTSWANA: ::WORD = 0x02; +pub const SUBLANG_TSWANA_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_TURKISH_TURKEY: ::WORD = 0x01; +pub const SUBLANG_TURKMEN_TURKMENISTAN: ::WORD = 0x01; +pub const SUBLANG_UIGHUR_PRC: ::WORD = 0x01; +pub const SUBLANG_UKRAINIAN_UKRAINE: ::WORD = 0x01; +pub const SUBLANG_UPPER_SORBIAN_GERMANY: ::WORD = 0x01; +pub const SUBLANG_URDU_PAKISTAN: ::WORD = 0x01; +pub const SUBLANG_URDU_INDIA: ::WORD = 0x02; +pub const SUBLANG_UZBEK_LATIN: ::WORD = 0x01; +pub const SUBLANG_UZBEK_CYRILLIC: ::WORD = 0x02; +pub const SUBLANG_VALENCIAN_VALENCIA: ::WORD = 0x02; +pub const SUBLANG_VIETNAMESE_VIETNAM: ::WORD = 0x01; +pub const SUBLANG_WELSH_UNITED_KINGDOM: ::WORD = 0x01; +pub const SUBLANG_WOLOF_SENEGAL: ::WORD = 0x01; +pub const SUBLANG_XHOSA_SOUTH_AFRICA: ::WORD = 0x01; +pub const SUBLANG_YAKUT_RUSSIA: ::WORD = 0x01; +pub const SUBLANG_YI_PRC: ::WORD = 0x01; +pub const SUBLANG_YORUBA_NIGERIA: ::WORD = 0x01; +pub const SUBLANG_ZULU_SOUTH_AFRICA: ::WORD = 0x01; +//1962 +// FIXME: Once feature(const_fn) or some CTFE alternative becomes stable, MAKELANGID! can go +// unless we want to #[macro_export] it ... +macro_rules! MAKELANGID { ($p:expr, $s:expr) => ($s << 10 | $p) } +pub fn MAKELANGID(p: ::WORD, s: ::WORD) -> ::LANGID { MAKELANGID!(p, s) } +pub fn PRIMARYLANGID(lgid: ::LANGID) -> ::WORD { lgid & 0x3ff } +pub fn SUBLANGID(lgid: ::LANGID) -> ::WORD { lgid >> 10 } +//2019 +pub const LANG_SYSTEM_DEFAULT: LANGID = MAKELANGID!(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT); +pub const LANG_USER_DEFAULT: LANGID = MAKELANGID!(LANG_NEUTRAL, SUBLANG_DEFAULT); +//2214 +pub const MAXIMUM_WAIT_OBJECTS: ::DWORD = 64; +pub const MAXIMUM_SUSPEND_COUNT: ::CHAR = MAXCHAR; +//2277 +pub type KSPIN_LOCK = ::ULONG_PTR; +pub type PKSPIN_LOCK = *mut KSPIN_LOCK; +STRUCT!{struct M128A { // FIXME align 16 + Low: ULONGLONG, + High: LONGLONG, +}} +pub type PM128A = *mut M128A; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct XSAVE_FORMAT { // FIXME align 16 + ControlWord: ::WORD, + StatusWord: ::WORD, + TagWord: ::BYTE, + Reserved1: ::BYTE, + ErrorOpcode: ::WORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::WORD, + Reserved2: ::WORD, + DataOffset: ::DWORD, + DataSelector: ::WORD, + Reserved3: ::WORD, + MxCsr: ::DWORD, + MxCsr_Mask: ::DWORD, + FloatRegisters: [M128A; 8], + XmmRegisters: [M128A; 8], + Reserved4: [::BYTE; 224], +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{nodebug struct XSAVE_FORMAT { // FIXME align 16 + ControlWord: ::WORD, + StatusWord: ::WORD, + TagWord: ::BYTE, + Reserved1: ::BYTE, + ErrorOpcode: ::WORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::WORD, + Reserved2: ::WORD, + DataOffset: ::DWORD, + DataSelector: ::WORD, + Reserved3: ::WORD, + MxCsr: ::DWORD, + MxCsr_Mask: ::DWORD, + FloatRegisters: [M128A; 8], + XmmRegisters: [M128A; 16], + Reserved4: [::BYTE; 96], +}} +//3563 +#[cfg(target_arch = "x86")] +pub const SIZE_OF_80387_REGISTERS: usize = 80; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct FLOATING_SAVE_AREA { + ControlWord: ::DWORD, + StatusWord: ::DWORD, + TagWord: ::DWORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::DWORD, + DataOffset: ::DWORD, + DataSelector: ::DWORD, + RegisterArea: [::BYTE; SIZE_OF_80387_REGISTERS], + Spare0: ::DWORD, +}} +#[cfg(target_arch = "x86")] +pub type PFLOATING_SAVE_AREA = *mut FLOATING_SAVE_AREA; +#[cfg(target_arch = "x86")] +pub const MAXIMUM_SUPPORTED_EXTENSION: usize = 512; +#[cfg(target_arch = "x86")] +STRUCT!{nodebug struct CONTEXT { + ContextFlags: ::DWORD, + Dr0: ::DWORD, + Dr1: ::DWORD, + Dr2: ::DWORD, + Dr3: ::DWORD, + Dr6: ::DWORD, + Dr7: ::DWORD, + FloatSave: FLOATING_SAVE_AREA, + SegGs: ::DWORD, + SegFs: ::DWORD, + SegEs: ::DWORD, + SegDs: ::DWORD, + Edi: ::DWORD, + Esi: ::DWORD, + Ebx: ::DWORD, + Edx: ::DWORD, + Ecx: ::DWORD, + Eax: ::DWORD, + Ebp: ::DWORD, + Eip: ::DWORD, + SegCs: ::DWORD, + EFlags: ::DWORD, + Esp: ::DWORD, + SegSs: ::DWORD, + ExtendedRegisters: [::BYTE; MAXIMUM_SUPPORTED_EXTENSION], +}} +#[cfg(target_arch = "x86_64")] +pub type XMM_SAVE_AREA32 = XSAVE_FORMAT; +pub type PXMM_SAVE_AREA32 = *mut XSAVE_FORMAT; +// FIXME - Align 16 +#[cfg(target_arch = "x86_64")] +STRUCT!{nodebug struct CONTEXT { + P1Home: ::DWORD64, + P2Home: ::DWORD64, + P3Home: ::DWORD64, + P4Home: ::DWORD64, + P5Home: ::DWORD64, + P6Home: ::DWORD64, + ContextFlags: ::DWORD, + MxCsr: ::DWORD, + SegCs: ::WORD, + SegDs: ::WORD, + SegEs: ::WORD, + SegFs: ::WORD, + SegGs: ::WORD, + SegSs: ::WORD, + EFlags: ::DWORD, + Dr0: ::DWORD64, + Dr1: ::DWORD64, + Dr2: ::DWORD64, + Dr3: ::DWORD64, + Dr6: ::DWORD64, + Dr7: ::DWORD64, + Rax: ::DWORD64, + Rcx: ::DWORD64, + Rdx: ::DWORD64, + Rbx: ::DWORD64, + Rsp: ::DWORD64, + Rbp: ::DWORD64, + Rsi: ::DWORD64, + Rdi: ::DWORD64, + R8: ::DWORD64, + R9: ::DWORD64, + R10: ::DWORD64, + R11: ::DWORD64, + R12: ::DWORD64, + R13: ::DWORD64, + R14: ::DWORD64, + R15: ::DWORD64, + Rip: ::DWORD64, + FltSave: XMM_SAVE_AREA32, + VectorRegister: [::M128A; 26], + VectorControl: ::DWORD64, + DebugControl: ::DWORD64, + LastBranchToRip: ::DWORD64, + LastBranchFromRip: ::DWORD64, + LastExceptionToRip: ::DWORD64, + LastExceptionFromRip: ::DWORD64, +}} +pub type PCONTEXT = *mut CONTEXT; +#[test] +fn test_CONTEXT_size() { + use std::mem::size_of; + if cfg!(target_arch = "x86_64") { + assert_eq!(size_of::(), 1232) + } else if cfg!(target_arch = "x86") { + assert_eq!(size_of::(), 716) + } +} +pub type RUNTIME_FUNCTION = IMAGE_RUNTIME_FUNCTION_ENTRY; +pub type PRUNTIME_FUNCTION = *mut RUNTIME_FUNCTION; +pub const UNWIND_HISTORY_TABLE_SIZE: usize = 12; +STRUCT!{struct UNWIND_HISTORY_TABLE_ENTRY { + ImageBase: ::DWORD64, + FunctionEntry: PRUNTIME_FUNCTION, +}} +pub type PUNWIND_HISTORY_TABLE_ENTRY = *mut UNWIND_HISTORY_TABLE_ENTRY; +STRUCT!{struct UNWIND_HISTORY_TABLE { + Count: ::DWORD, + LocalHint: ::BYTE, + GlobalHint: ::BYTE, + Search: ::BYTE, + Once: ::BYTE, + LowAddress: ::DWORD64, + HighAddress: ::DWORD64, + Entry: [UNWIND_HISTORY_TABLE_ENTRY; UNWIND_HISTORY_TABLE_SIZE], +}} +pub type PUNWIND_HISTORY_TABLE = *mut UNWIND_HISTORY_TABLE; +pub type PGET_RUNTIME_FUNCTION_CALLBACK = Option PRUNTIME_FUNCTION>; +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS_u1 { + Xmm0: PM128A, + Xmm1: PM128A, + Xmm2: PM128A, + Xmm3: PM128A, + Xmm4: PM128A, + Xmm5: PM128A, + Xmm6: PM128A, + Xmm7: PM128A, + Xmm8: PM128A, + Xmm9: PM128A, + Xmm10: PM128A, + Xmm11: PM128A, + Xmm12: PM128A, + Xmm14: PM128A, + Xmm15: PM128A, +}} +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS_u2 { + Rax: ::DWORD64, + Rcx: ::DWORD64, + Rdx: ::DWORD64, + Rbx: ::DWORD64, + Rsp: ::DWORD64, + Rbp: ::DWORD64, + Rsi: ::DWORD64, + Rdi: ::DWORD64, + R8: ::DWORD64, + R9: ::DWORD64, + R10: ::DWORD64, + R11: ::DWORD64, + R12: ::DWORD64, + R13: ::DWORD64, + R14: ::DWORD64, + R15: ::DWORD64, +}} +STRUCT!{struct KNONVOLATILE_CONTEXT_POINTERS { + FloatingContext: [PM128A; 16], + IntegerContext: [::PDWORD64; 16], +}} +// FIXME: all unions are untagged +UNION!( + KNONVOLATILE_CONTEXT_POINTERS, FloatingContext, Xmms, Xmms_mut, + KNONVOLATILE_CONTEXT_POINTERS_u1 +); +UNION!( + KNONVOLATILE_CONTEXT_POINTERS, IntegerContext, Regs, Regs_mut, + KNONVOLATILE_CONTEXT_POINTERS_u2 +); +pub type PKNONVOLATILE_CONTEXT_POINTERS = *mut KNONVOLATILE_CONTEXT_POINTERS; +//8983 +pub const EXCEPTION_MAXIMUM_PARAMETERS: usize = 15; +STRUCT!{struct EXCEPTION_RECORD { + ExceptionCode: ::DWORD, + ExceptionFlags: ::DWORD, + ExceptionRecord: *mut EXCEPTION_RECORD, + ExceptionAddress: ::PVOID, + NumberParameters: ::DWORD, + ExceptionInformation: [::ULONG_PTR; EXCEPTION_MAXIMUM_PARAMETERS], +}} +pub type PEXCEPTION_RECORD = *mut EXCEPTION_RECORD; +//9023 +STRUCT!{struct EXCEPTION_POINTERS { + ExceptionRecord: PEXCEPTION_RECORD, + ContextRecord: PCONTEXT, +}} +pub type PEXCEPTION_POINTERS = *mut EXCEPTION_POINTERS; +pub type PACCESS_TOKEN = ::PVOID; +pub type PSECURITY_DESCRIPTOR = ::PVOID; +pub type PSID = ::PVOID; +pub type PCLAIMS_BLOB = ::PVOID; +//9091 +pub type ACCESS_MASK = ::DWORD; +pub type PACCESS_MASK = *mut ACCESS_MASK; +pub const DELETE: ::DWORD = 0x00010000; +pub const READ_CONTROL: ::DWORD = 0x00020000; +pub const WRITE_DAC: ::DWORD = 0x00040000; +pub const WRITE_OWNER: ::DWORD = 0x00080000; +pub const SYNCHRONIZE: ::DWORD = 0x00100000; +pub const STANDARD_RIGHTS_REQUIRED: ::DWORD = 0x000F0000; +pub const STANDARD_RIGHTS_READ: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_WRITE: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_EXECUTE: ::DWORD = READ_CONTROL; +pub const STANDARD_RIGHTS_ALL: ::DWORD = 0x001F0000; +pub const SPECIFIC_RIGHTS_ALL: ::DWORD = 0x0000FFFF; +pub const ACCESS_SYSTEM_SECURITY: ::DWORD = 0x01000000; +pub const MAXIMUM_ALLOWED: ::DWORD = 0x02000000; +pub const GENERIC_READ: ::DWORD = 0x80000000; +pub const GENERIC_WRITE: ::DWORD = 0x40000000; +pub const GENERIC_EXECUTE: ::DWORD = 0x20000000; +pub const GENERIC_ALL: ::DWORD = 0x10000000; +//9170 +STRUCT!{struct LUID_AND_ATTRIBUTES { + Luid: LUID, + Attributes: ::DWORD, +}} +pub type PLUID_AND_ATTRIBUTES = *mut LUID_AND_ATTRIBUTES; +//9243 +ENUM!{enum SID_NAME_USE { + SidTypeUser = 1, + SidTypeGroup, + SidTypeDomain, + SidTypeAlias, + SidTypeWellKnownGroup, + SidTypeDeletedAccount, + SidTypeInvalid, + SidTypeUnknown, + SidTypeComputer, + SidTypeLabel, +}} +pub type PSID_NAME_USE = *mut SID_NAME_USE; +STRUCT!{struct SID_AND_ATTRIBUTES { + Sid: PSID, + Attributes: ::DWORD, +}} +pub type PSID_AND_ATTRIBUTES = *mut SID_AND_ATTRIBUTES; +//9802 +pub const ACL_REVISION: ::BYTE = 2; +pub const ACL_REVISION_DS: ::BYTE = 4; +pub const ACL_REVISION1: ::BYTE = 1; +pub const MIN_ACL_REVISION: ::BYTE = ACL_REVISION2; +pub const ACL_REVISION2: ::BYTE = 2; +pub const ACL_REVISION3: ::BYTE = 3; +pub const ACL_REVISION4: ::BYTE = 4; +pub const MAX_ACL_REVISION: ::BYTE = ACL_REVISION4; +STRUCT!{struct ACL { + AclRevision: ::BYTE, + Sbz1: ::BYTE, + AclSize: ::WORD, + AceCount: ::WORD, + Sbz2: ::WORD, +}} +pub type PACL = *mut ACL; +//9888 +pub const SE_PRIVILEGE_ENABLED_BY_DEFAULT: ::DWORD = 0x00000001; +pub const SE_PRIVILEGE_ENABLED: ::DWORD = 0x00000002; +pub const SE_PRIVILEGE_REMOVED: ::DWORD = 0x00000004; +pub const SE_PRIVILEGE_USED_FOR_ACCESS: ::DWORD = 0x80000000; +pub const SE_PRIVILEGE_VALID_ATTRIBUTES: ::DWORD = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS; +pub const PRIVILEGE_SET_ALL_NECESSARY: ::DWORD = 1; +//10689 +pub const TOKEN_ASSIGN_PRIMARY: ::DWORD = 0x0001; +pub const TOKEN_DUPLICATE: ::DWORD = 0x0002; +pub const TOKEN_IMPERSONATE: ::DWORD = 0x0004; +pub const TOKEN_QUERY: ::DWORD = 0x0008; +pub const TOKEN_QUERY_SOURCE: ::DWORD = 0x0010; +pub const TOKEN_ADJUST_PRIVILEGES: ::DWORD = 0x0020; +pub const TOKEN_ADJUST_GROUPS: ::DWORD = 0x0040; +pub const TOKEN_ADJUST_DEFAULT: ::DWORD = 0x0080; +pub const TOKEN_ADJUST_SESSIONID: ::DWORD = 0x0100; +pub const TOKEN_ALL_ACCESS_P: ::DWORD = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY + | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE + | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT; +pub const TOKEN_ALL_ACCESS: ::DWORD = TOKEN_ALL_ACCESS_P | TOKEN_ADJUST_SESSIONID; +pub const TOKEN_READ: ::DWORD = STANDARD_RIGHTS_READ | TOKEN_QUERY; +pub const TOKEN_WRITE: ::DWORD = STANDARD_RIGHTS_WRITE | TOKEN_ADJUST_PRIVILEGES + | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT; +pub const TOKEN_EXECUTE: ::DWORD = STANDARD_RIGHTS_EXECUTE; +//10823 +STRUCT!{nodebug struct TOKEN_PRIVILEGES { + PrivilegeCount: ::DWORD, + Privileges: [LUID_AND_ATTRIBUTES; 0], +}} +pub type PTOKEN_PRIVILEGES = *mut TOKEN_PRIVILEGES; +//10965 +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INVALID: ::WORD = 0x00; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_INT64: ::WORD = 0x01; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_UINT64: ::WORD = 0x02; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_STRING: ::WORD = 0x03; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE { + Version: ::DWORD64, + Name: ::PWSTR, +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE = *mut CLAIM_SECURITY_ATTRIBUTE_FQBN_VALUE; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_FQBN: ::WORD = 0x04; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_SID: ::WORD = 0x05; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_BOOLEAN: ::WORD = 0x06; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE { + pValue: ::PVOID, + ValueLength: ::DWORD, +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE = + *mut CLAIM_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE; +pub const CLAIM_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING: ::WORD = 0x10; +pub const CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE: ::DWORD = 0x0001; +pub const CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE: ::DWORD = 0x0002; +pub const CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY: ::DWORD = 0x0004; +pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT: ::DWORD = 0x0008; +pub const CLAIM_SECURITY_ATTRIBUTE_DISABLED: ::DWORD = 0x0010; +pub const CLAIM_SECURITY_ATTRIBUTE_MANDATORY: ::DWORD = 0x0020; +pub const CLAIM_SECURITY_ATTRIBUTE_VALID_FLAGS: ::DWORD = CLAIM_SECURITY_ATTRIBUTE_NON_INHERITABLE + | CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE | CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY + | CLAIM_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT | CLAIM_SECURITY_ATTRIBUTE_DISABLED + | CLAIM_SECURITY_ATTRIBUTE_MANDATORY; +pub const CLAIM_SECURITY_ATTRIBUTE_CUSTOM_FLAGS: ::DWORD = 0xFFFF0000; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_V1 { + Name: ::PWSTR, + ValueType: ::WORD, + Reserved: ::WORD, + Flags: ::DWORD, + ValueCount: ::DWORD, + // Put data here +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_V1 = *mut CLAIM_SECURITY_ATTRIBUTE_V1; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 { + Name: ::DWORD, + ValueType: ::WORD, + Reserved: ::WORD, + Flags: ::DWORD, + ValueCount: ::DWORD, + // Put array here +}} +pub type PCLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 = *mut CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1; +pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1: ::WORD = 1; +pub const CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION: ::WORD = + CLAIM_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1; +STRUCT!{struct CLAIM_SECURITY_ATTRIBUTES_INFORMATION { + Version: ::WORD, + Reserved: ::WORD, + AttributeCount: ::DWORD, + pAttributeV1: PCLAIM_SECURITY_ATTRIBUTE_V1, +}} +pub type PCLAIM_SECURITY_ATTRIBUTES_INFORMATION = *mut CLAIM_SECURITY_ATTRIBUTES_INFORMATION; +//11257 +pub type SECURITY_INFORMATION = ::DWORD; +pub type PSECURITY_INFORMATION = *mut ::DWORD; +pub const OWNER_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000001; +pub const GROUP_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000002; +pub const DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000004; +pub const SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000008; +pub const LABEL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000010; +pub const ATTRIBUTE_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000020; +pub const SCOPE_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000040; +pub const PROCESS_TRUST_LABEL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00000080; +pub const BACKUP_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x00010000; +pub const PROTECTED_DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x80000000; +pub const PROTECTED_SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x40000000; +pub const UNPROTECTED_DACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x20000000; +pub const UNPROTECTED_SACL_SECURITY_INFORMATION: SECURITY_INFORMATION = 0x10000000; +ENUM!{enum SE_LEARNING_MODE_DATA_TYPE { + SeLearningModeInvalidType = 0, + SeLearningModeSettings, + SeLearningModeMax, +}} +STRUCT!{struct SECURITY_CAPABILITIES { + AppContainerSid: PSID, + Capabilities: PSID_AND_ATTRIBUTES, + CapabilityCount: ::DWORD, + Reserved: ::DWORD, +}} +pub type PSECURITY_CAPABILITIES = *mut SECURITY_CAPABILITIES; +pub type LPSECURITY_CAPABILITIES = *mut SECURITY_CAPABILITIES; +pub const PROCESS_TERMINATE: ::DWORD = 0x0001; +pub const PROCESS_CREATE_THREAD: ::DWORD = 0x0002; +pub const PROCESS_SET_SESSIONID: ::DWORD = 0x0004; +pub const PROCESS_VM_OPERATION: ::DWORD = 0x0008; +pub const PROCESS_VM_READ: ::DWORD = 0x0010; +pub const PROCESS_VM_WRITE: ::DWORD = 0x0020; +pub const PROCESS_DUP_HANDLE: ::DWORD = 0x0040; +pub const PROCESS_CREATE_PROCESS: ::DWORD = 0x0080; +pub const PROCESS_SET_QUOTA: ::DWORD = 0x0100; +pub const PROCESS_SET_INFORMATION: ::DWORD = 0x0200; +pub const PROCESS_QUERY_INFORMATION: ::DWORD = 0x0400; +pub const PROCESS_SUSPEND_RESUME: ::DWORD = 0x0800; +pub const PROCESS_QUERY_LIMITED_INFORMATION: ::DWORD = 0x1000; +pub const PROCESS_SET_LIMITED_INFORMATION: ::DWORD = 0x2000; +pub const PROCESS_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF; +//11007 +pub const THREAD_BASE_PRIORITY_LOWRT: ::DWORD = 15; +pub const THREAD_BASE_PRIORITY_MAX: ::DWORD = 2; +pub const THREAD_BASE_PRIORITY_MIN: ::DWORD = -2i32 as ::DWORD; +pub const THREAD_BASE_PRIORITY_IDLE: ::DWORD = -15i32 as ::DWORD; +//11018 +STRUCT!{struct QUOTA_LIMITS { + PagedPoolLimit: ::SIZE_T, + NonPagedPoolLimit: ::SIZE_T, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + PagefileLimit: ::SIZE_T, + TimeLimit: ::LARGE_INTEGER, +}} +pub type PQUOTA_LIMITS = *mut QUOTA_LIMITS; +pub const QUOTA_LIMITS_HARDWS_MIN_ENABLE: ::DWORD = 0x00000001; +pub const QUOTA_LIMITS_HARDWS_MIN_DISABLE: ::DWORD = 0x00000002; +pub const QUOTA_LIMITS_HARDWS_MAX_ENABLE: ::DWORD = 0x00000004; +pub const QUOTA_LIMITS_HARDWS_MAX_DISABLE: ::DWORD = 0x00000008; +pub const QUOTA_LIMITS_USE_DEFAULT_LIMITS: ::DWORD = 0x00000010; +STRUCT!{struct RATE_QUOTA_LIMIT { + RateData: ::DWORD, + BitFields: ::DWORD, +}} +BITFIELD!(RATE_QUOTA_LIMIT BitFields: ::DWORD [ + RatePercent set_RatePercent[0..7], + Reserved0 set_Reserved0[7..32], +]); +pub type PRATE_QUOTA_LIMIT = *mut RATE_QUOTA_LIMIT; +STRUCT!{struct QUOTA_LIMITS_EX { + PagedPoolLimit: ::SIZE_T, + NonPagedPoolLimit: ::SIZE_T, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + PagefileLimit: ::SIZE_T, + TimeLimit: ::LARGE_INTEGER, + WorkingSetLimit: ::SIZE_T, + Reserved2: ::SIZE_T, + Reserved3: ::SIZE_T, + Reserved4: ::SIZE_T, + Flags: ::DWORD, + CpuRateLimit: RATE_QUOTA_LIMIT, +}} +pub type PQUOTA_LIMITS_EX = *mut QUOTA_LIMITS_EX; +STRUCT!{struct IO_COUNTERS { + ReadOperationCount: ::ULONGLONG, + WriteOperationCount: ::ULONGLONG, + OtherOperationCount: ::ULONGLONG, + ReadTransferCount: ::ULONGLONG, + WriteTransferCount: ::ULONGLONG, + OtherTransferCount: ::ULONGLONG, +}} +pub type PIO_COUNTERS = *mut IO_COUNTERS; +//11192 +STRUCT!{struct JOBOBJECT_BASIC_LIMIT_INFORMATION { + PerProcessUserTimeLimit: ::LARGE_INTEGER, + PerJobUserTimeLimit: ::LARGE_INTEGER, + LimitFlags: ::DWORD, + MinimumWorkingSetSize: ::SIZE_T, + MaximumWorkingSetSize: ::SIZE_T, + ActiveProcessLimit: ::DWORD, + Affinity: ::ULONG_PTR, + PriorityClass: ::DWORD, + SchedulingClass: ::DWORD, +}} +pub type PJOBOBJECT_BASIC_LIMIT_INFORMATION = *mut JOBOBJECT_BASIC_LIMIT_INFORMATION; +STRUCT!{struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { + BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION, + IoInfo: IO_COUNTERS, + ProcessMemoryLimit: ::SIZE_T, + JobMemoryLimit: ::SIZE_T, + PeakProcessMemoryUsed: ::SIZE_T, + PeakJobMemoryUsed: ::SIZE_T, +}} +pub type PJOBOBJECT_EXTENDED_LIMIT_INFORMATION = *mut JOBOBJECT_EXTENDED_LIMIT_INFORMATION; +STRUCT!{struct JOBOBJECT_BASIC_PROCESS_ID_LIST { + NumberOfAssignedProcesses: ::DWORD, + NumberOfProcessIdsInList: ::DWORD, + ProcessIdList: [::ULONG_PTR; 0], +}} +//11712 +pub const JOB_OBJECT_TERMINATE_AT_END_OF_JOB: ::DWORD = 0; +pub const JOB_OBJECT_POST_AT_END_OF_JOB: ::DWORD = 1; +pub const JOB_OBJECT_MSG_END_OF_JOB_TIME: ::DWORD = 1; +pub const JOB_OBJECT_MSG_END_OF_PROCESS_TIME: ::DWORD = 2; +pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: ::DWORD = 3; +pub const JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: ::DWORD = 4; +pub const JOB_OBJECT_MSG_NEW_PROCESS: ::DWORD = 6; +pub const JOB_OBJECT_MSG_EXIT_PROCESS: ::DWORD = 7; +pub const JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: ::DWORD = 8; +pub const JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: ::DWORD = 9; +pub const JOB_OBJECT_MSG_JOB_MEMORY_LIMIT: ::DWORD = 10; +pub const JOB_OBJECT_MSG_NOTIFICATION_LIMIT: ::DWORD = 11; +pub const JOB_OBJECT_MSG_JOB_CYCLE_TIME_LIMIT: ::DWORD = 12; +pub const JOB_OBJECT_MSG_MINIMUM: ::DWORD = 1; +pub const JOB_OBJECT_MSG_MAXIMUM: ::DWORD = 12; +pub const JOB_OBJECT_VALID_COMPLETION_FILTER: ::DWORD = ((1 << (JOB_OBJECT_MSG_MAXIMUM + 1)) - 1) + - ((1 << JOB_OBJECT_MSG_MINIMUM) - 1); +pub const JOB_OBJECT_LIMIT_WORKINGSET: ::DWORD = 0x00000001; +pub const JOB_OBJECT_LIMIT_PROCESS_TIME: ::DWORD = 0x00000002; +pub const JOB_OBJECT_LIMIT_JOB_TIME: ::DWORD = 0x00000004; +pub const JOB_OBJECT_LIMIT_ACTIVE_PROCESS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_LIMIT_AFFINITY: ::DWORD = 0x00000010; +pub const JOB_OBJECT_LIMIT_PRIORITY_CLASS: ::DWORD = 0x00000020; +pub const JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME: ::DWORD = 0x00000040; +pub const JOB_OBJECT_LIMIT_SCHEDULING_CLASS: ::DWORD = 0x00000080; +pub const JOB_OBJECT_LIMIT_PROCESS_MEMORY: ::DWORD = 0x00000100; +pub const JOB_OBJECT_LIMIT_JOB_MEMORY: ::DWORD = 0x00000200; +pub const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: ::DWORD = 0x00000400; +pub const JOB_OBJECT_LIMIT_BREAKAWAY_OK: ::DWORD = 0x00000800; +pub const JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: ::DWORD = 0x00001000; +pub const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: ::DWORD = 0x00002000; +pub const JOB_OBJECT_LIMIT_SUBSET_AFFINITY: ::DWORD = 0x00004000; +pub const JOB_OBJECT_LIMIT_JOB_READ_BYTES: ::DWORD = 0x00010000; +pub const JOB_OBJECT_LIMIT_JOB_WRITE_BYTES: ::DWORD = 0x00020000; +pub const JOB_OBJECT_LIMIT_RATE_CONTROL: ::DWORD = 0x00040000; +pub const JOB_OBJECT_LIMIT_RESERVED3: ::DWORD = 0x00008000; +pub const JOB_OBJECT_LIMIT_VALID_FLAGS: ::DWORD = 0x0007ffff; +pub const JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS: ::DWORD = 0x000000ff; +pub const JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS: ::DWORD = 0x00007fff; +pub const JOB_OBJECT_NOTIFICATION_LIMIT_VALID_FLAGS: ::DWORD = 0x00070204; +pub const JOB_OBJECT_RESERVED_LIMIT_VALID_FLAGS: ::DWORD = 0x0007ffff; +pub const JOB_OBJECT_UILIMIT_NONE: ::DWORD = 0x00000000; +pub const JOB_OBJECT_UILIMIT_HANDLES: ::DWORD = 0x00000001; +pub const JOB_OBJECT_UILIMIT_READCLIPBOARD: ::DWORD = 0x00000002; +pub const JOB_OBJECT_UILIMIT_WRITECLIPBOARD: ::DWORD = 0x00000004; +pub const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: ::DWORD = 0x00000010; +pub const JOB_OBJECT_UILIMIT_GLOBALATOMS: ::DWORD = 0x00000020; +pub const JOB_OBJECT_UILIMIT_DESKTOP: ::DWORD = 0x00000040; +pub const JOB_OBJECT_UILIMIT_EXITWINDOWS: ::DWORD = 0x00000080; +pub const JOB_OBJECT_UILIMIT_ALL: ::DWORD = 0x000000FF; +pub const JOB_OBJECT_UI_VALID_FLAGS: ::DWORD = 0x000000FF; +pub const JOB_OBJECT_SECURITY_NO_ADMIN: ::DWORD = 0x00000001; +pub const JOB_OBJECT_SECURITY_RESTRICTED_TOKEN: ::DWORD = 0x00000002; +pub const JOB_OBJECT_SECURITY_ONLY_TOKEN: ::DWORD = 0x00000004; +pub const JOB_OBJECT_SECURITY_FILTER_TOKENS: ::DWORD = 0x00000008; +pub const JOB_OBJECT_SECURITY_VALID_FLAGS: ::DWORD = 0x0000000f; +pub const JOB_OBJECT_CPU_RATE_CONTROL_ENABLE: ::DWORD = 0x1; +pub const JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED: ::DWORD = 0x2; +pub const JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP: ::DWORD = 0x4; +pub const JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY: ::DWORD = 0x8; +pub const JOB_OBJECT_CPU_RATE_CONTROL_VALID_FLAGS: ::DWORD = 0xf; +ENUM!{enum JOBOBJECTINFOCLASS { + JobObjectBasicAccountingInformation = 1, + JobObjectBasicLimitInformation, + JobObjectBasicProcessIdList, + JobObjectBasicUIRestrictions, + JobObjectSecurityLimitInformation, + JobObjectEndOfJobTimeInformation, + JobObjectAssociateCompletionPortInformation, + JobObjectBasicAndIoAccountingInformation, + JobObjectExtendedLimitInformation, + JobObjectJobSetInformation, + JobObjectGroupInformation, + JobObjectNotificationLimitInformation, + JobObjectLimitViolationInformation, + JobObjectGroupInformationEx, + JobObjectCpuRateControlInformation, + JobObjectCompletionFilter, + JobObjectCompletionCounter, + JobObjectReserved1Information = 18, + JobObjectReserved2Information, + JobObjectReserved3Information, + JobObjectReserved4Information, + JobObjectReserved5Information, + JobObjectReserved6Information, + JobObjectReserved7Information, + JobObjectReserved8Information, + JobObjectReserved9Information, + MaxJobObjectInfoClass, +}} +//12063 +pub const SECTION_QUERY: ::DWORD = 0x0001; +pub const SECTION_MAP_WRITE: ::DWORD = 0x0002; +pub const SECTION_MAP_READ: ::DWORD = 0x0004; +pub const SECTION_MAP_EXECUTE: ::DWORD = 0x0008; +pub const SECTION_EXTEND_SIZE: ::DWORD = 0x0010; +pub const SECTION_MAP_EXECUTE_EXPLICIT: ::DWORD = 0x0020; +pub const SECTION_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SECTION_QUERY + | SECTION_MAP_WRITE | SECTION_MAP_READ | SECTION_MAP_EXECUTE | SECTION_EXTEND_SIZE; +//12100 +pub const PAGE_NOACCESS: ::DWORD = 0x01; +pub const PAGE_READONLY: ::DWORD = 0x02; +pub const PAGE_READWRITE: ::DWORD = 0x04; +pub const PAGE_WRITECOPY: ::DWORD = 0x08; +pub const PAGE_EXECUTE: ::DWORD = 0x10; +pub const PAGE_EXECUTE_READ: ::DWORD = 0x20; +pub const PAGE_EXECUTE_READWRITE: ::DWORD = 0x40; +pub const PAGE_EXECUTE_WRITECOPY: ::DWORD = 0x80; +pub const PAGE_GUARD: ::DWORD = 0x100; +pub const PAGE_NOCACHE: ::DWORD = 0x200; +pub const PAGE_WRITECOMBINE: ::DWORD = 0x400; +pub const PAGE_REVERT_TO_FILE_MAP: ::DWORD = 0x80000000; +pub const PAGE_TARGETS_NO_UPDATE: ::DWORD = 0x40000000; +pub const PAGE_TARGETS_INVALID: ::DWORD = 0x40000000; +pub const MEM_COMMIT: ::DWORD = 0x1000; +pub const MEM_RESERVE: ::DWORD = 0x2000; +pub const MEM_DECOMMIT: ::DWORD = 0x4000; +pub const MEM_RELEASE: ::DWORD = 0x8000; +pub const MEM_FREE: ::DWORD = 0x10000; +pub const MEM_PRIVATE: ::DWORD = 0x20000; +pub const MEM_MAPPED: ::DWORD = 0x40000; +pub const MEM_RESET: ::DWORD = 0x80000; +pub const MEM_TOP_DOWN: ::DWORD = 0x100000; +pub const MEM_WRITE_WATCH: ::DWORD = 0x200000; +pub const MEM_PHYSICAL: ::DWORD = 0x400000; +pub const MEM_ROTATE: ::DWORD = 0x800000; +pub const MEM_DIFFERENT_IMAGE_BASE_OK: ::DWORD = 0x800000; +pub const MEM_RESET_UNDO: ::DWORD = 0x1000000; +pub const MEM_LARGE_PAGES: ::DWORD = 0x20000000; +pub const MEM_4MB_PAGES: ::DWORD = 0x80000000; +pub const SEC_FILE: ::DWORD = 0x800000; +pub const SEC_IMAGE: ::DWORD = 0x1000000; +pub const SEC_PROTECTED_IMAGE: ::DWORD = 0x2000000; +pub const SEC_RESERVE: ::DWORD = 0x4000000; +pub const SEC_COMMIT: ::DWORD = 0x8000000; +pub const SEC_NOCACHE: ::DWORD = 0x10000000; +pub const SEC_WRITECOMBINE: ::DWORD = 0x40000000; +pub const SEC_LARGE_PAGES: ::DWORD = 0x80000000; +pub const SEC_IMAGE_NO_EXECUTE: ::DWORD = (SEC_IMAGE | SEC_NOCACHE); +pub const MEM_IMAGE: ::DWORD = SEC_IMAGE; +pub const WRITE_WATCH_FLAG_RESET: ::DWORD = 0x01; +pub const MEM_UNMAP_WITH_TRANSIENT_BOOST: ::DWORD = 0x01; +//12217 +pub const FILE_READ_DATA: ::DWORD = 0x0001; +pub const FILE_LIST_DIRECTORY: ::DWORD = 0x0001; +pub const FILE_WRITE_DATA: ::DWORD = 0x0002; +pub const FILE_ADD_FILE: ::DWORD = 0x0002; +pub const FILE_APPEND_DATA: ::DWORD = 0x0004; +pub const FILE_ADD_SUBDIRECTORY: ::DWORD = 0x0004; +pub const FILE_CREATE_PIPE_INSTANCE: ::DWORD = 0x0004; +pub const FILE_READ_EA: ::DWORD = 0x0008; +pub const FILE_WRITE_EA: ::DWORD = 0x0010; +pub const FILE_EXECUTE: ::DWORD = 0x0020; +pub const FILE_TRAVERSE: ::DWORD = 0x0020; +pub const FILE_DELETE_CHILD: ::DWORD = 0x0040; +pub const FILE_READ_ATTRIBUTES: ::DWORD = 0x0080; +pub const FILE_WRITE_ATTRIBUTES: ::DWORD = 0x0100; +pub const FILE_ALL_ACCESS: ::DWORD = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF; +pub const FILE_GENERIC_READ: ::DWORD = STANDARD_RIGHTS_READ | FILE_READ_DATA + | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE; +pub const FILE_GENERIC_WRITE: ::DWORD = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA + | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE; +pub const FILE_GENERIC_EXECUTE: ::DWORD = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES + | FILE_EXECUTE | SYNCHRONIZE; +pub const FILE_SHARE_READ: ::DWORD = 0x00000001; +pub const FILE_SHARE_WRITE: ::DWORD = 0x00000002; +pub const FILE_SHARE_DELETE: ::DWORD = 0x00000004; +pub const FILE_ATTRIBUTE_READONLY: ::DWORD = 0x00000001; +pub const FILE_ATTRIBUTE_HIDDEN: ::DWORD = 0x00000002; +pub const FILE_ATTRIBUTE_SYSTEM: ::DWORD = 0x00000004; +pub const FILE_ATTRIBUTE_DIRECTORY: ::DWORD = 0x00000010; +pub const FILE_ATTRIBUTE_ARCHIVE: ::DWORD = 0x00000020; +pub const FILE_ATTRIBUTE_DEVICE: ::DWORD = 0x00000040; +pub const FILE_ATTRIBUTE_NORMAL: ::DWORD = 0x00000080; +pub const FILE_ATTRIBUTE_TEMPORARY: ::DWORD = 0x00000100; +pub const FILE_ATTRIBUTE_SPARSE_FILE: ::DWORD = 0x00000200; +pub const FILE_ATTRIBUTE_REPARSE_POINT: ::DWORD = 0x00000400; +pub const FILE_ATTRIBUTE_COMPRESSED: ::DWORD = 0x00000800; +pub const FILE_ATTRIBUTE_OFFLINE: ::DWORD = 0x00001000; +pub const FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: ::DWORD = 0x00002000; +pub const FILE_ATTRIBUTE_ENCRYPTED: ::DWORD = 0x00004000; +pub const FILE_ATTRIBUTE_INTEGRITY_STREAM: ::DWORD = 0x00008000; +pub const FILE_ATTRIBUTE_VIRTUAL: ::DWORD = 0x00010000; +pub const FILE_ATTRIBUTE_NO_SCRUB_DATA: ::DWORD = 0x00020000; +pub const FILE_ATTRIBUTE_EA: ::DWORD = 0x00040000; +pub const FILE_NOTIFY_CHANGE_FILE_NAME: ::DWORD = 0x00000001; +pub const FILE_NOTIFY_CHANGE_DIR_NAME: ::DWORD = 0x00000002; +pub const FILE_NOTIFY_CHANGE_ATTRIBUTES: ::DWORD = 0x00000004; +pub const FILE_NOTIFY_CHANGE_SIZE: ::DWORD = 0x00000008; +pub const FILE_NOTIFY_CHANGE_LAST_WRITE: ::DWORD = 0x00000010; +pub const FILE_NOTIFY_CHANGE_LAST_ACCESS: ::DWORD = 0x00000020; +pub const FILE_NOTIFY_CHANGE_CREATION: ::DWORD = 0x00000040; +pub const FILE_NOTIFY_CHANGE_SECURITY: ::DWORD = 0x00000100; +pub const FILE_ACTION_ADDED: ::DWORD = 0x00000001; +pub const FILE_ACTION_REMOVED: ::DWORD = 0x00000002; +pub const FILE_ACTION_MODIFIED: ::DWORD = 0x00000003; +pub const FILE_ACTION_RENAMED_OLD_NAME: ::DWORD = 0x00000004; +pub const FILE_ACTION_RENAMED_NEW_NAME: ::DWORD = 0x00000005; +pub const MAILSLOT_NO_MESSAGE: ::DWORD = 0xFFFFFFFF; +pub const MAILSLOT_WAIT_FOREVER: ::DWORD = 0xFFFFFFFF; +pub const FILE_CASE_SENSITIVE_SEARCH: ::DWORD = 0x00000001; +pub const FILE_CASE_PRESERVED_NAMES: ::DWORD = 0x00000002; +pub const FILE_UNICODE_ON_DISK: ::DWORD = 0x00000004; +pub const FILE_PERSISTENT_ACLS: ::DWORD = 0x00000008; +pub const FILE_FILE_COMPRESSION: ::DWORD = 0x00000010; +pub const FILE_VOLUME_QUOTAS: ::DWORD = 0x00000020; +pub const FILE_SUPPORTS_SPARSE_FILES: ::DWORD = 0x00000040; +pub const FILE_SUPPORTS_REPARSE_POINTS: ::DWORD = 0x00000080; +pub const FILE_SUPPORTS_REMOTE_STORAGE: ::DWORD = 0x00000100; +pub const FILE_VOLUME_IS_COMPRESSED: ::DWORD = 0x00008000; +pub const FILE_SUPPORTS_OBJECT_IDS: ::DWORD = 0x00010000; +pub const FILE_SUPPORTS_ENCRYPTION: ::DWORD = 0x00020000; +pub const FILE_NAMED_STREAMS: ::DWORD = 0x00040000; +pub const FILE_READ_ONLY_VOLUME: ::DWORD = 0x00080000; +pub const FILE_SEQUENTIAL_WRITE_ONCE: ::DWORD = 0x00100000; +pub const FILE_SUPPORTS_TRANSACTIONS: ::DWORD = 0x00200000; +pub const FILE_SUPPORTS_HARD_LINKS: ::DWORD = 0x00400000; +pub const FILE_SUPPORTS_EXTENDED_ATTRIBUTES: ::DWORD = 0x00800000; +pub const FILE_SUPPORTS_OPEN_BY_FILE_ID: ::DWORD = 0x01000000; +pub const FILE_SUPPORTS_USN_JOURNAL: ::DWORD = 0x02000000; +pub const FILE_SUPPORTS_INTEGRITY_STREAMS: ::DWORD = 0x04000000; +pub const FILE_INVALID_FILE_ID: ::LONGLONG = -1; +STRUCT!{struct FILE_ID_128 { + Identifier: [::BYTE; 16], +}} +pub type PFILE_ID_128 = *mut FILE_ID_128; +STRUCT!{struct FILE_NOTIFY_INFORMATION { + NextEntryOffset: ::DWORD, + Action: ::DWORD, + FileNameLength: ::DWORD, + FileName: [::WCHAR; 0], +}} +STRUCT!{struct FILE_SEGMENT_ELEMENT { + Buffer: ::PVOID64, + Alignment: ::ULONGLONG, +}} +pub type PFILE_SEGMENT_ELEMENT = *mut FILE_SEGMENT_ELEMENT; +//12475 +pub const IO_REPARSE_TAG_MOUNT_POINT: ::DWORD = 0xA0000003; +pub const IO_REPARSE_TAG_HSM: ::DWORD = 0xC0000004; +pub const IO_REPARSE_TAG_HSM2: ::DWORD = 0x80000006; +pub const IO_REPARSE_TAG_SIS: ::DWORD = 0x80000007; +pub const IO_REPARSE_TAG_WIM: ::DWORD = 0x80000008; +pub const IO_REPARSE_TAG_CSV: ::DWORD = 0x80000009; +pub const IO_REPARSE_TAG_DFS: ::DWORD = 0x8000000A; +pub const IO_REPARSE_TAG_SYMLINK: ::DWORD = 0xA000000C; +pub const IO_REPARSE_TAG_DFSR: ::DWORD = 0x80000012; +pub const IO_REPARSE_TAG_DEDUP: ::DWORD = 0x80000013; +pub const IO_REPARSE_TAG_NFS: ::DWORD = 0x80000014; +pub const IO_REPARSE_TAG_FILE_PLACEHOLDER: ::DWORD = 0x80000015; +pub const IO_REPARSE_TAG_WOF: ::DWORD = 0x80000017; +//12788 +pub const DUPLICATE_CLOSE_SOURCE: ::DWORD = 0x00000001; +pub const DUPLICATE_SAME_ACCESS: ::DWORD = 0x00000002; +//14708 +STRUCT!{struct PROCESSOR_POWER_POLICY_INFO { + TimeCheck: ::DWORD, + DemoteLimit: ::DWORD, + PromoteLimit: ::DWORD, + DemotePercent: ::BYTE, + PromotePercent: ::BYTE, + Spare: [::BYTE; 2], + Reserved: ::DWORD, +}} +BITFIELD!(PROCESSOR_POWER_POLICY_INFO Reserved: ::DWORD [ + AllowDemotion set_AllowDemotion[0..1], + AllowPromotion set_AllowPromotion[1..2], +]); +pub type PPROCESSOR_POWER_POLICY_INFO = *mut PROCESSOR_POWER_POLICY_INFO; +//15000 +STRUCT!{struct IMAGE_FILE_HEADER { + Machine: ::WORD, + NumberOfSections: ::WORD, + TimeDateStamp: ::DWORD, + PointerToSymbolTable: ::DWORD, + NumberOfSymbols: ::DWORD, + SizeOfOptionalHeader: ::WORD, + Characteristics: ::WORD, +}} +pub type PIMAGE_FILE_HEADER = *mut IMAGE_FILE_HEADER; +pub const IMAGE_SIZEOF_FILE_HEADER: usize = 20; +pub const IMAGE_FILE_RELOCS_STRIPPED: ::WORD = 0x0001; +pub const IMAGE_FILE_EXECUTABLE_IMAGE: ::WORD = 0x0002; +pub const IMAGE_FILE_LINE_NUMS_STRIPPED: ::WORD = 0x0004; +pub const IMAGE_FILE_LOCAL_SYMS_STRIPPED: ::WORD = 0x0008; +pub const IMAGE_FILE_AGGRESIVE_WS_TRIM: ::WORD = 0x0010; +pub const IMAGE_FILE_LARGE_ADDRESS_AWARE: ::WORD = 0x0020; +pub const IMAGE_FILE_BYTES_REVERSED_LO: ::WORD = 0x0080; +pub const IMAGE_FILE_32BIT_MACHINE: ::WORD = 0x0100; +pub const IMAGE_FILE_DEBUG_STRIPPED: ::WORD = 0x0200; +pub const IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP: ::WORD = 0x0400; +pub const IMAGE_FILE_NET_RUN_FROM_SWAP: ::WORD = 0x0800; +pub const IMAGE_FILE_SYSTEM: ::WORD = 0x1000; +pub const IMAGE_FILE_DLL: ::WORD = 0x2000; +pub const IMAGE_FILE_UP_SYSTEM_ONLY: ::WORD = 0x4000; +pub const IMAGE_FILE_BYTES_REVERSED_HI: ::WORD = 0x8000; +pub const IMAGE_FILE_MACHINE_UNKNOWN: ::WORD = 0; +pub const IMAGE_FILE_MACHINE_I386: ::WORD = 0x014c; +pub const IMAGE_FILE_MACHINE_R3000: ::WORD = 0x0162; +pub const IMAGE_FILE_MACHINE_R4000: ::WORD = 0x0166; +pub const IMAGE_FILE_MACHINE_R10000: ::WORD = 0x0168; +pub const IMAGE_FILE_MACHINE_WCEMIPSV2: ::WORD = 0x0169; +pub const IMAGE_FILE_MACHINE_ALPHA: ::WORD = 0x0184; +pub const IMAGE_FILE_MACHINE_SH3: ::WORD = 0x01a2; +pub const IMAGE_FILE_MACHINE_SH3DSP: ::WORD = 0x01a3; +pub const IMAGE_FILE_MACHINE_SH3E: ::WORD = 0x01a4; +pub const IMAGE_FILE_MACHINE_SH4: ::WORD = 0x01a6; +pub const IMAGE_FILE_MACHINE_SH5: ::WORD = 0x01a8; +pub const IMAGE_FILE_MACHINE_ARM: ::WORD = 0x01c0; +pub const IMAGE_FILE_MACHINE_THUMB: ::WORD = 0x01c2; +pub const IMAGE_FILE_MACHINE_ARMNT: ::WORD = 0x01c4; +pub const IMAGE_FILE_MACHINE_AM33: ::WORD = 0x01d3; +pub const IMAGE_FILE_MACHINE_POWERPC: ::WORD = 0x01F0; +pub const IMAGE_FILE_MACHINE_POWERPCFP: ::WORD = 0x01f1; +pub const IMAGE_FILE_MACHINE_IA64: ::WORD = 0x0200; +pub const IMAGE_FILE_MACHINE_MIPS16: ::WORD = 0x0266; +pub const IMAGE_FILE_MACHINE_ALPHA64: ::WORD = 0x0284; +pub const IMAGE_FILE_MACHINE_MIPSFPU: ::WORD = 0x0366; +pub const IMAGE_FILE_MACHINE_MIPSFPU16: ::WORD = 0x0466; +pub const IMAGE_FILE_MACHINE_AXP64: ::WORD = IMAGE_FILE_MACHINE_ALPHA64; +pub const IMAGE_FILE_MACHINE_TRICORE: ::WORD = 0x0520; +pub const IMAGE_FILE_MACHINE_CEF: ::WORD = 0x0CEF; +pub const IMAGE_FILE_MACHINE_EBC: ::WORD = 0x0EBC; +pub const IMAGE_FILE_MACHINE_AMD64: ::WORD = 0x8664; +pub const IMAGE_FILE_MACHINE_M32R: ::WORD = 0x9041; +pub const IMAGE_FILE_MACHINE_CEE: ::WORD = 0xC0EE; +STRUCT!{struct IMAGE_DATA_DIRECTORY { + VirtualAddress: ::DWORD, + Size: ::DWORD, +}} +pub type PIMAGE_DATA_DIRECTORY = *mut IMAGE_DATA_DIRECTORY; +pub const IMAGE_NUMBEROF_DIRECTORY_ENTRIES: usize = 16; +STRUCT!{struct IMAGE_OPTIONAL_HEADER32 { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + BaseOfData: ::DWORD, + ImageBase: ::DWORD, + SectionAlignment: ::DWORD, + FileAlignment: ::DWORD, + MajorOperatingSystemVersion: ::WORD, + MinorOperatingSystemVersion: ::WORD, + MajorImageVersion: ::WORD, + MinorImageVersion: ::WORD, + MajorSubsystemVersion: ::WORD, + MinorSubsystemVersion: ::WORD, + Win32VersionValue: ::DWORD, + SizeOfImage: ::DWORD, + SizeOfHeaders: ::DWORD, + CheckSum: ::DWORD, + Subsystem: ::WORD, + DllCharacteristics: ::WORD, + SizeOfStackReserve: ::DWORD, + SizeOfStackCommit: ::DWORD, + SizeOfHeapReserve: ::DWORD, + SizeOfHeapCommit: ::DWORD, + LoaderFlags: ::DWORD, + NumberOfRvaAndSizes: ::DWORD, + DataDirectory: [IMAGE_DATA_DIRECTORY; IMAGE_NUMBEROF_DIRECTORY_ENTRIES], +}} +pub type PIMAGE_OPTIONAL_HEADER32 = *mut IMAGE_OPTIONAL_HEADER32; +STRUCT!{struct IMAGE_ROM_OPTIONAL_HEADER { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + BaseOfData: ::DWORD, + BaseOfBss: ::DWORD, + GprMask: ::DWORD, + CprMask: [::DWORD; 4], + GpValue: ::DWORD, +}} +pub type PIMAGE_ROM_OPTIONAL_HEADER = *mut IMAGE_ROM_OPTIONAL_HEADER; +STRUCT!{struct IMAGE_OPTIONAL_HEADER64 { + Magic: ::WORD, + MajorLinkerVersion: ::BYTE, + MinorLinkerVersion: ::BYTE, + SizeOfCode: ::DWORD, + SizeOfInitializedData: ::DWORD, + SizeOfUninitializedData: ::DWORD, + AddressOfEntryPoint: ::DWORD, + BaseOfCode: ::DWORD, + ImageBase: ::ULONGLONG, + SectionAlignment: ::DWORD, + FileAlignment: ::DWORD, + MajorOperatingSystemVersion: ::WORD, + MinorOperatingSystemVersion: ::WORD, + MajorImageVersion: ::WORD, + MinorImageVersion: ::WORD, + MajorSubsystemVersion: ::WORD, + MinorSubsystemVersion: ::WORD, + Win32VersionValue: ::DWORD, + SizeOfImage: ::DWORD, + SizeOfHeaders: ::DWORD, + CheckSum: ::DWORD, + Subsystem: ::WORD, + DllCharacteristics: ::WORD, + SizeOfStackReserve: ULONGLONG, + SizeOfStackCommit: ULONGLONG, + SizeOfHeapReserve: ULONGLONG, + SizeOfHeapCommit: ULONGLONG, + LoaderFlags: ::DWORD, + NumberOfRvaAndSizes: ::DWORD, + DataDirectory: [IMAGE_DATA_DIRECTORY; IMAGE_NUMBEROF_DIRECTORY_ENTRIES], +}} +pub type PIMAGE_OPTIONAL_HEADER64 = *mut IMAGE_OPTIONAL_HEADER64; +pub const IMAGE_NT_OPTIONAL_HDR32_MAGIC: ::WORD = 0x10b; +pub const IMAGE_NT_OPTIONAL_HDR64_MAGIC: ::WORD = 0x20b; +pub const IMAGE_ROM_OPTIONAL_HDR_MAGIC: ::WORD = 0x107; +#[cfg(target_arch = "x86_64")] +pub type IMAGE_OPTIONAL_HEADER = IMAGE_OPTIONAL_HEADER64; +#[cfg(target_arch = "x86_64")] +pub type PIMAGE_OPTIONAL_HEADER = PIMAGE_OPTIONAL_HEADER64; +#[cfg(target_arch = "x86")] +pub type IMAGE_OPTIONAL_HEADER = IMAGE_OPTIONAL_HEADER32; +#[cfg(target_arch = "x86")] +pub type PIMAGE_OPTIONAL_HEADER = PIMAGE_OPTIONAL_HEADER32; +STRUCT!{struct IMAGE_NT_HEADERS64 { + Signature: ::DWORD, + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_OPTIONAL_HEADER64, +}} +pub type PIMAGE_NT_HEADERS64 = *mut IMAGE_NT_HEADERS64; +STRUCT!{struct IMAGE_NT_HEADERS32 { + Signature: ::DWORD, + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_OPTIONAL_HEADER32, +}} +pub type PIMAGE_NT_HEADERS32 = *mut IMAGE_NT_HEADERS32; +STRUCT!{struct IMAGE_ROM_HEADERS { + FileHeader: IMAGE_FILE_HEADER, + OptionalHeader: IMAGE_ROM_OPTIONAL_HEADER, +}} +pub type PIMAGE_ROM_HEADERS = *mut IMAGE_ROM_HEADERS; +#[cfg(target_arch = "x86_64")] +pub type IMAGE_NT_HEADERS = IMAGE_NT_HEADERS64; +#[cfg(target_arch = "x86_64")] +pub type PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS64; +#[cfg(target_arch = "x86")] +pub type IMAGE_NT_HEADERS = IMAGE_NT_HEADERS32; +#[cfg(target_arch = "x86")] +pub type PIMAGE_NT_HEADERS = PIMAGE_NT_HEADERS32; +pub const IMAGE_SUBSYSTEM_UNKNOWN: ::WORD = 0; +pub const IMAGE_SUBSYSTEM_NATIVE: ::WORD = 1; +pub const IMAGE_SUBSYSTEM_WINDOWS_GUI: ::WORD = 2; +pub const IMAGE_SUBSYSTEM_WINDOWS_CUI: ::WORD = 3; +pub const IMAGE_SUBSYSTEM_OS2_CUI: ::WORD = 5; +pub const IMAGE_SUBSYSTEM_POSIX_CUI: ::WORD = 7; +pub const IMAGE_SUBSYSTEM_NATIVE_WINDOWS: ::WORD = 8; +pub const IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: ::WORD = 9; +pub const IMAGE_SUBSYSTEM_EFI_APPLICATION: ::WORD = 10; +pub const IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: ::WORD = 11; +pub const IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: ::WORD = 12; +pub const IMAGE_SUBSYSTEM_EFI_ROM: ::WORD = 13; +pub const IMAGE_SUBSYSTEM_XBOX: ::WORD = 14; +pub const IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: ::WORD = 16; +pub const IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA: ::WORD = 0x0020; +pub const IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE: ::WORD = 0x0040; +pub const IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY: ::WORD = 0x0080; +pub const IMAGE_DLLCHARACTERISTICS_NX_COMPAT: ::WORD = 0x0100; +pub const IMAGE_DLLCHARACTERISTICS_NO_ISOLATION: ::WORD = 0x0200; +pub const IMAGE_DLLCHARACTERISTICS_NO_SEH: ::WORD = 0x0400; +pub const IMAGE_DLLCHARACTERISTICS_NO_BIND: ::WORD = 0x0800; +pub const IMAGE_DLLCHARACTERISTICS_APPCONTAINER: ::WORD = 0x1000; +pub const IMAGE_DLLCHARACTERISTICS_WDM_DRIVER: ::WORD = 0x2000; +pub const IMAGE_DLLCHARACTERISTICS_GUARD_CF: ::WORD = 0x4000; +pub const IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE: ::WORD = 0x8000; +pub const IMAGE_DIRECTORY_ENTRY_EXPORT: ::WORD = 0; +pub const IMAGE_DIRECTORY_ENTRY_IMPORT: ::WORD = 1; +pub const IMAGE_DIRECTORY_ENTRY_RESOURCE: ::WORD = 2; +pub const IMAGE_DIRECTORY_ENTRY_EXCEPTION: ::WORD = 3; +pub const IMAGE_DIRECTORY_ENTRY_SECURITY: ::WORD = 4; +pub const IMAGE_DIRECTORY_ENTRY_BASERELOC: ::WORD = 5; +pub const IMAGE_DIRECTORY_ENTRY_DEBUG: ::WORD = 6; +pub const IMAGE_DIRECTORY_ENTRY_ARCHITECTURE: ::WORD = 7; +pub const IMAGE_DIRECTORY_ENTRY_GLOBALPTR: ::WORD = 8; +pub const IMAGE_DIRECTORY_ENTRY_TLS: ::WORD = 9; +pub const IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: ::WORD = 10; +pub const IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: ::WORD = 11; +pub const IMAGE_DIRECTORY_ENTRY_IAT: ::WORD = 12; +pub const IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT: ::WORD = 13; +pub const IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR: ::WORD = 14; +STRUCT!{struct ANON_OBJECT_HEADER { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, +}} +STRUCT!{struct ANON_OBJECT_HEADER_V2 { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, + Flags: ::DWORD, + MetaDataSize: ::DWORD, + MetaDataOffset: ::DWORD, +}} +STRUCT!{struct ANON_OBJECT_HEADER_BIGOBJ { + Sig1: ::WORD, + Sig2: ::WORD, + Version: ::WORD, + Machine: ::WORD, + TimeDateStamp: ::DWORD, + ClassID: ::CLSID, + SizeOfData: ::DWORD, + Flags: ::DWORD, + MetaDataSize: ::DWORD, + MetaDataOffset: ::DWORD, + NumberOfSections: ::DWORD, + PointerToSymbolTable: ::DWORD, + NumberOfSymbols: ::DWORD, +}} +pub const IMAGE_SIZEOF_SHORT_NAME: usize = 8; +STRUCT!{struct IMAGE_SECTION_HEADER { + Name: [::BYTE; IMAGE_SIZEOF_SHORT_NAME], + PhysicalAddressOrVirtualSize: ::DWORD, + VirtualAddress: ::DWORD, + SizeOfRawData: ::DWORD, + PointerToRawData: ::DWORD, + PointerToRelocations: ::DWORD, + PointerToLinenumbers: ::DWORD, + NumberOfRelocations: ::WORD, + NumberOfLinenumbers: ::WORD, + Characteristics: ::DWORD, +}} +pub type PIMAGE_SECTION_HEADER = *mut IMAGE_SECTION_HEADER; +pub const IMAGE_SIZEOF_SECTION_HEADER: usize = 40; +pub const IMAGE_SCN_TYPE_NO_PAD: ::DWORD = 0x00000008; +pub const IMAGE_SCN_CNT_CODE: ::DWORD = 0x00000020; +pub const IMAGE_SCN_CNT_INITIALIZED_DATA: ::DWORD = 0x00000040; +pub const IMAGE_SCN_CNT_UNINITIALIZED_DATA: ::DWORD = 0x00000080; +pub const IMAGE_SCN_LNK_OTHER: ::DWORD = 0x00000100; +pub const IMAGE_SCN_LNK_INFO: ::DWORD = 0x00000200; +pub const IMAGE_SCN_LNK_REMOVE: ::DWORD = 0x00000800; +pub const IMAGE_SCN_LNK_COMDAT: ::DWORD = 0x00001000; +pub const IMAGE_SCN_NO_DEFER_SPEC_EXC: ::DWORD = 0x00004000; +pub const IMAGE_SCN_GPREL: ::DWORD = 0x00008000; +pub const IMAGE_SCN_MEM_FARDATA: ::DWORD = 0x00008000; +pub const IMAGE_SCN_MEM_PURGEABLE: ::DWORD = 0x00020000; +pub const IMAGE_SCN_MEM_16BIT: ::DWORD = 0x00020000; +pub const IMAGE_SCN_MEM_LOCKED: ::DWORD = 0x00040000; +pub const IMAGE_SCN_MEM_PRELOAD: ::DWORD = 0x00080000; +pub const IMAGE_SCN_ALIGN_1BYTES: ::DWORD = 0x00100000; +pub const IMAGE_SCN_ALIGN_2BYTES: ::DWORD = 0x00200000; +pub const IMAGE_SCN_ALIGN_4BYTES: ::DWORD = 0x00300000; +pub const IMAGE_SCN_ALIGN_8BYTES: ::DWORD = 0x00400000; +pub const IMAGE_SCN_ALIGN_16BYTES: ::DWORD = 0x00500000; +pub const IMAGE_SCN_ALIGN_32BYTES: ::DWORD = 0x00600000; +pub const IMAGE_SCN_ALIGN_64BYTES: ::DWORD = 0x00700000; +pub const IMAGE_SCN_ALIGN_128BYTES: ::DWORD = 0x00800000; +pub const IMAGE_SCN_ALIGN_256BYTES: ::DWORD = 0x00900000; +pub const IMAGE_SCN_ALIGN_512BYTES: ::DWORD = 0x00A00000; +pub const IMAGE_SCN_ALIGN_1024BYTES: ::DWORD = 0x00B00000; +pub const IMAGE_SCN_ALIGN_2048BYTES: ::DWORD = 0x00C00000; +pub const IMAGE_SCN_ALIGN_4096BYTES: ::DWORD = 0x00D00000; +pub const IMAGE_SCN_ALIGN_8192BYTES: ::DWORD = 0x00E00000; +pub const IMAGE_SCN_ALIGN_MASK: ::DWORD = 0x00F00000; +pub const IMAGE_SCN_LNK_NRELOC_OVFL: ::DWORD = 0x01000000; +pub const IMAGE_SCN_MEM_DISCARDABLE: ::DWORD = 0x02000000; +pub const IMAGE_SCN_MEM_NOT_CACHED: ::DWORD = 0x04000000; +pub const IMAGE_SCN_MEM_NOT_PAGED: ::DWORD = 0x08000000; +pub const IMAGE_SCN_MEM_SHARED: ::DWORD = 0x10000000; +pub const IMAGE_SCN_MEM_EXECUTE: ::DWORD = 0x20000000; +pub const IMAGE_SCN_MEM_READ: ::DWORD = 0x40000000; +pub const IMAGE_SCN_MEM_WRITE: ::DWORD = 0x80000000; +pub const IMAGE_SCN_SCALE_INDEX: ::DWORD = 0x00000001; +//16590 +STRUCT!{struct IMAGE_DEBUG_DIRECTORY { + Characteristics: ::DWORD, + TimeDateStamp: ::DWORD, + MajorVersion: ::WORD, + MinorVersion: ::WORD, + Type: ::DWORD, + SizeOfData: ::DWORD, + AddressOfRawData: ::DWORD, + PointerToRawData: ::DWORD, +}} +pub type PIMAGE_DEBUG_DIRECTORY = *mut IMAGE_DEBUG_DIRECTORY; +pub const IMAGE_DEBUG_TYPE_UNKNOWN: ::DWORD = 0; +pub const IMAGE_DEBUG_TYPE_COFF: ::DWORD = 1; +pub const IMAGE_DEBUG_TYPE_CODEVIEW: ::DWORD = 2; +pub const IMAGE_DEBUG_TYPE_FPO: ::DWORD = 3; +pub const IMAGE_DEBUG_TYPE_MISC: ::DWORD = 4; +pub const IMAGE_DEBUG_TYPE_EXCEPTION: ::DWORD = 5; +pub const IMAGE_DEBUG_TYPE_FIXUP: ::DWORD = 6; +pub const IMAGE_DEBUG_TYPE_OMAP_TO_SRC: ::DWORD = 7; +pub const IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: ::DWORD = 8; +pub const IMAGE_DEBUG_TYPE_BORLAND: ::DWORD = 9; +pub const IMAGE_DEBUG_TYPE_RESERVED10: ::DWORD = 10; +pub const IMAGE_DEBUG_TYPE_CLSID: ::DWORD = 11; +STRUCT!{struct IMAGE_COFF_SYMBOLS_HEADER { + NumberOfSymbols: ::DWORD, + LvaToFirstSymbol: ::DWORD, + NumberOfLinenumbers: ::DWORD, + LvaToFirstLinenumber: ::DWORD, + RvaToFirstByteOfCode: ::DWORD, + RvaToLastByteOfCode: ::DWORD, + RvaToFirstByteOfData: ::DWORD, + RvaToLastByteOfData: ::DWORD, +}} +pub type PIMAGE_COFF_SYMBOLS_HEADER = *mut IMAGE_COFF_SYMBOLS_HEADER; +STRUCT!{struct IMAGE_RUNTIME_FUNCTION_ENTRY { + BeginAddress: ::DWORD, + EndAddress: ::DWORD, + UnwindInfoAddress: ::DWORD, +}} +UNION!(IMAGE_RUNTIME_FUNCTION_ENTRY, UnwindInfoAddress, UnwindData, UnwindData_mut, ::DWORD); +pub type PIMAGE_RUNTIME_FUNCTION_ENTRY = *mut IMAGE_RUNTIME_FUNCTION_ENTRY; +pub const FRAME_FPO: ::WORD = 0; +pub const FRAME_TRAP: ::WORD = 1; +pub const FRAME_TSS: ::WORD = 2; +pub const FRAME_NONFPO: ::WORD = 3; +STRUCT!{struct FPO_DATA { + ulOffStart: ::DWORD, + cbProcSize: ::DWORD, + cdwLocals: ::DWORD, + cdwParams: ::WORD, + bitfield: ::WORD, +}} +pub type PFPO_DATA = *mut FPO_DATA; +pub const SIZEOF_RFPO_DATA: usize = 16; +pub const IMAGE_DEBUG_MISC_EXENAME: ::DWORD = 1; +STRUCT!{struct IMAGE_DEBUG_MISC { + DataType: ::DWORD, + Length: ::DWORD, + Unicode: ::BOOLEAN, + Reserved: [::BYTE; 3], + Data: [::BYTE; 0], +}} +pub type PIMAGE_DEBUG_MISC = *mut IMAGE_DEBUG_MISC; +STRUCT!{struct IMAGE_FUNCTION_ENTRY { + StartingAddress: ::DWORD, + EndingAddress: ::DWORD, + EndOfPrologue: ::DWORD, +}} +pub type PIMAGE_FUNCTION_ENTRY = *mut IMAGE_FUNCTION_ENTRY; +STRUCT!{struct IMAGE_FUNCTION_ENTRY64 { + StartingAddress: ::ULONGLONG, + EndingAddress: ::ULONGLONG, + EndOfPrologueOrUnwindInfoAddress: ::ULONGLONG, +}} +pub type PIMAGE_FUNCTION_ENTRY64 = *mut IMAGE_FUNCTION_ENTRY64; +//18245 +pub const HEAP_NO_SERIALIZE: ::DWORD = 0x00000001; +pub const HEAP_GROWABLE: ::DWORD = 0x00000002; +pub const HEAP_GENERATE_EXCEPTIONS: ::DWORD = 0x00000004; +pub const HEAP_ZERO_MEMORY: ::DWORD = 0x00000008; +pub const HEAP_REALLOC_IN_PLACE_ONLY: ::DWORD = 0x00000010; +pub const HEAP_TAIL_CHECKING_ENABLED: ::DWORD = 0x00000020; +pub const HEAP_FREE_CHECKING_ENABLED: ::DWORD = 0x00000040; +pub const HEAP_DISABLE_COALESCE_ON_FREE: ::DWORD = 0x00000080; +pub const HEAP_CREATE_ALIGN_16: ::DWORD = 0x00010000; +pub const HEAP_CREATE_ENABLE_TRACING: ::DWORD = 0x00020000; +pub const HEAP_CREATE_ENABLE_EXECUTE: ::DWORD = 0x00040000; +pub const HEAP_MAXIMUM_TAG: ::DWORD = 0x0FFF; +pub const HEAP_PSEUDO_TAG_FLAG: ::DWORD = 0x8000; +pub const HEAP_TAG_SHIFT: ::DWORD = 18; +//18145 +STRUCT!{struct RTL_CRITICAL_SECTION_DEBUG { + Type: ::WORD, + CreatorBackTraceIndex: ::WORD, + CriticalSection: *mut ::RTL_CRITICAL_SECTION, + ProcessLocksList: ::LIST_ENTRY, + EntryCount: ::DWORD, + ContentionCount: ::DWORD, + Flags: ::DWORD, + CreatorBackTraceIndexHigh: ::WORD, + SpareWORD: ::WORD, +}} +pub type PRTL_CRITICAL_SECTION_DEBUG = *mut RTL_CRITICAL_SECTION_DEBUG; +pub type RTL_RESOURCE_DEBUG = RTL_CRITICAL_SECTION_DEBUG; +pub type PRTL_RESOURCE_DEBUG = *mut RTL_CRITICAL_SECTION_DEBUG; +pub const RTL_CRITSECT_TYPE: ::WORD = 0; +pub const RTL_RESOURCE_TYPE: ::WORD = 1; +pub const RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO: ::ULONG_PTR = 0x01000000; +pub const RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN: ::ULONG_PTR = 0x02000000; +pub const RTL_CRITICAL_SECTION_FLAG_STATIC_INIT: ::ULONG_PTR = 0x04000000; +pub const RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE: ::ULONG_PTR = 0x08000000; +pub const RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO: ::ULONG_PTR = 0x10000000; +pub const RTL_CRITICAL_SECTION_ALL_FLAG_BITS: ::ULONG_PTR = 0xFF000000; +pub const RTL_CRITICAL_SECTION_FLAG_RESERVED: ::ULONG_PTR = RTL_CRITICAL_SECTION_ALL_FLAG_BITS & !(RTL_CRITICAL_SECTION_FLAG_NO_DEBUG_INFO | RTL_CRITICAL_SECTION_FLAG_DYNAMIC_SPIN | RTL_CRITICAL_SECTION_FLAG_STATIC_INIT | RTL_CRITICAL_SECTION_FLAG_RESOURCE_TYPE | RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO); +pub const RTL_CRITICAL_SECTION_DEBUG_FLAG_STATIC_INIT: ::DWORD = 0x00000001; +STRUCT!{struct RTL_CRITICAL_SECTION { + DebugInfo: ::PRTL_CRITICAL_SECTION_DEBUG, + LockCount: ::LONG, + RecursionCount: ::LONG, + OwningThread: ::HANDLE, + LockSemaphore: ::HANDLE, + SpinCount: ::ULONG_PTR, +}} +pub type PRTL_CRITICAL_SECTION = *mut RTL_CRITICAL_SECTION; +STRUCT!{struct RTL_SRWLOCK { + Ptr: ::PVOID, +}} +pub type PRTL_SRWLOCK = *mut RTL_SRWLOCK; +pub const RTL_SRWLOCK_INIT: RTL_SRWLOCK = RTL_SRWLOCK { Ptr: 0 as PVOID }; +STRUCT!{struct RTL_CONDITION_VARIABLE { + Ptr: ::PVOID, +}} +pub type PRTL_CONDITION_VARIABLE = *mut RTL_CONDITION_VARIABLE; +pub const RTL_CONDITION_VARIABLE_INIT: RTL_CONDITION_VARIABLE = RTL_CONDITION_VARIABLE { + Ptr: 0 as PVOID +}; +//18204 +pub type PAPCFUNC = Option; +pub type PVECTORED_EXCEPTION_HANDLER = Option ::LONG>; +ENUM!{enum HEAP_INFORMATION_CLASS { + HeapCompatibilityInformation = 0, + HeapEnableTerminationOnCorruption = 1, + HeapOptimizeResources = 3, +}} +//pub use self::HEAP_INFORMATION_CLASS::*; +pub const HEAP_OPTIMIZE_RESOURCES_CURRENT_VERSION: ::DWORD = 1; +STRUCT!{struct HEAP_OPTIMIZE_RESOURCES_INFORMATION { + Version: ::DWORD, + Flags: ::DWORD, +}} +pub type PHEAP_OPTIMIZE_RESOURCES_INFORMATION = *mut HEAP_OPTIMIZE_RESOURCES_INFORMATION; +pub const WT_EXECUTEDEFAULT: ::ULONG = 0x00000000; +pub const WT_EXECUTEINIOTHREAD: ::ULONG = 0x00000001; +pub const WT_EXECUTEINUITHREAD: ::ULONG = 0x00000002; +pub const WT_EXECUTEINWAITTHREAD: ::ULONG = 0x00000004; +pub const WT_EXECUTEONLYONCE: ::ULONG = 0x00000008; +pub const WT_EXECUTEINTIMERTHREAD: ::ULONG = 0x00000020; +pub const WT_EXECUTELONGFUNCTION: ::ULONG = 0x00000010; +pub const WT_EXECUTEINPERSISTENTIOTHREAD: ::ULONG = 0x00000040; +pub const WT_EXECUTEINPERSISTENTTHREAD: ::ULONG = 0x00000080; +pub const WT_TRANSFER_IMPERSONATION: ::ULONG = 0x00000100; +pub type WAITORTIMERCALLBACKFUNC = Option; +pub type WORKERCALLBACKFUNC = Option; +pub type APC_CALLBACK_FUNCTION = Option; +pub type WAITORTIMERCALLBACK = WAITORTIMERCALLBACKFUNC; +pub type PFLS_CALLBACK_FUNCTION = Option; +pub type PSECURE_MEMORY_CACHE_CALLBACK = Option ::BOOLEAN>; +pub const WT_EXECUTEINLONGTHREAD: ::ULONG = 0x00000010; +pub const WT_EXECUTEDELETEWAIT: ::ULONG = 0x00000008; +//18570 +pub const KEY_QUERY_VALUE: ::REGSAM = 0x0001; +pub const KEY_SET_VALUE: ::REGSAM = 0x0002; +pub const KEY_CREATE_SUB_KEY: ::REGSAM = 0x0004; +pub const KEY_ENUMERATE_SUB_KEYS: ::REGSAM = 0x0008; +pub const KEY_NOTIFY: ::REGSAM = 0x0010; +pub const KEY_CREATE_LINK: ::REGSAM = 0x0020; +pub const KEY_WOW64_32KEY: ::REGSAM = 0x0200; +pub const KEY_WOW64_64KEY: ::REGSAM = 0x0100; +pub const KEY_WOW64_RES: ::REGSAM = 0x0300; +pub const KEY_READ: ::REGSAM = ( + STANDARD_RIGHTS_READ | + KEY_QUERY_VALUE | + KEY_ENUMERATE_SUB_KEYS | + KEY_NOTIFY + ) & (!SYNCHRONIZE); +pub const KEY_WRITE: ::REGSAM = (STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (!SYNCHRONIZE); +pub const KEY_EXECUTE: ::REGSAM = KEY_READ & (!SYNCHRONIZE); +pub const KEY_ALL_ACCESS: ::REGSAM = ( + STANDARD_RIGHTS_ALL | + KEY_QUERY_VALUE | + KEY_SET_VALUE | + KEY_CREATE_SUB_KEY | + KEY_ENUMERATE_SUB_KEYS | + KEY_NOTIFY | + KEY_CREATE_LINK + ) & (!SYNCHRONIZE); +pub const REG_CREATED_NEW_KEY: ::DWORD = 0x00000001; +pub const REG_OPENED_EXISTING_KEY: ::DWORD = 0x00000002; +pub const REG_NOTIFY_CHANGE_NAME: ::DWORD = 0x00000001; +pub const REG_NOTIFY_CHANGE_ATTRIBUTES: ::DWORD = 0x00000002; +pub const REG_NOTIFY_CHANGE_LAST_SET: ::DWORD = 0x00000004; +pub const REG_NOTIFY_CHANGE_SECURITY: ::DWORD = 0x00000008; +pub const REG_LEGAL_CHANGE_FILTER: ::DWORD = REG_NOTIFY_CHANGE_NAME | + REG_NOTIFY_CHANGE_ATTRIBUTES | + REG_NOTIFY_CHANGE_LAST_SET | + REG_NOTIFY_CHANGE_SECURITY; +pub const REG_NOTIFY_THREAD_AGNOSTIC: ::DWORD = 0x10000000; //supported only on Windows 8 and later +pub const REG_OPTION_RESERVED: ::DWORD = 0x00000000; +pub const REG_OPTION_NON_VOLATILE: ::DWORD = 0x00000000; +pub const REG_OPTION_VOLATILE: ::DWORD = 0x00000001; +pub const REG_OPTION_CREATE_LINK: ::DWORD = 0x00000002; +pub const REG_OPTION_BACKUP_RESTORE: ::DWORD = 0x00000004; +pub const REG_OPTION_OPEN_LINK: ::DWORD = 0x00000008; +pub const REG_NONE: ::DWORD = 0; +pub const REG_SZ: ::DWORD = 1; +pub const REG_EXPAND_SZ: ::DWORD = 2; +pub const REG_BINARY: ::DWORD = 3; +pub const REG_DWORD: ::DWORD = 4; +pub const REG_DWORD_LITTLE_ENDIAN: ::DWORD = 4; +pub const REG_DWORD_BIG_ENDIAN: ::DWORD = 5; +pub const REG_LINK: ::DWORD = 6; +pub const REG_MULTI_SZ: ::DWORD = 7; +pub const REG_RESOURCE_LIST: ::DWORD = 8; +pub const REG_FULL_RESOURCE_DESCRIPTOR: ::DWORD = 9; +pub const REG_RESOURCE_REQUIREMENTS_LIST: ::DWORD = 10; +pub const REG_QWORD: ::DWORD = 11; +pub const REG_QWORD_LITTLE_ENDIAN: ::DWORD = 11; +//18720 +pub const SERVICE_KERNEL_DRIVER: ::DWORD = 0x00000001; +pub const SERVICE_FILE_SYSTEM_DRIVER: ::DWORD = 0x00000002; +pub const SERVICE_ADAPTER: ::DWORD = 0x00000004; +pub const SERVICE_RECOGNIZER_DRIVER: ::DWORD = 0x00000008; +pub const SERVICE_DRIVER: ::DWORD = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER + | SERVICE_RECOGNIZER_DRIVER; +pub const SERVICE_WIN32_OWN_PROCESS: ::DWORD = 0x00000010; +pub const SERVICE_WIN32_SHARE_PROCESS: ::DWORD = 0x00000020; +pub const SERVICE_WIN32: ::DWORD = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS; +pub const SERVICE_INTERACTIVE_PROCESS: ::DWORD = 0x00000100; +pub const SERVICE_TYPE_ALL: ::DWORD = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER + | SERVICE_INTERACTIVE_PROCESS; +STRUCT!{struct TP_CALLBACK_INSTANCE { + dummy: *mut ::c_void, +}} +pub type PTP_CALLBACK_INSTANCE = *mut TP_CALLBACK_INSTANCE; +STRUCT!{struct TP_IO { + dummy: *mut ::c_void, +}} +pub type PTP_IO = *mut TP_IO; +STRUCT!{struct TP_POOL { + dummy: *mut ::c_void, +}} +pub type PTP_POOL = *mut TP_POOL; +STRUCT!{struct TP_CLEANUP_GROUP { + dummy: *mut ::c_void, +}} +pub type PTP_CLEANUP_GROUP = *mut TP_CLEANUP_GROUP; +STRUCT!{struct TP_TIMER { + dummy: *mut ::c_void, +}} +pub type PTP_TIMER = *mut TP_TIMER; +STRUCT!{struct TP_WAIT { + dummy: *mut ::c_void, +}} +pub type PTP_WAIT = *mut TP_WAIT; +STRUCT!{struct TP_WORK { + dummy: *mut ::c_void, +}} +pub type PTP_WORK = *mut TP_WORK; +STRUCT!{struct ACTIVATION_CONTEXT { + dummy: *mut ::c_void, +}} +ENUM!{enum TP_CALLBACK_PRIORITY { + TP_CALLBACK_PRIORITY_HIGH, + TP_CALLBACK_PRIORITY_NORMAL, + TP_CALLBACK_PRIORITY_LOW, + TP_CALLBACK_PRIORITY_INVALID, + TP_CALLBACK_PRIORITY_COUNT = 4, +}} +pub type PTP_CLEANUP_GROUP_CANCEL_CALLBACK = Option; +pub type PTP_SIMPLE_CALLBACK = Option; +pub type PTP_WORK_CALLBACK = Option; +pub type PTP_TIMER_CALLBACK = Option; +pub type TP_WAIT_RESULT = ::DWORD; +pub type PTP_WAIT_CALLBACK = Option; +pub type TP_VERSION = ::DWORD; +pub type PTP_VERSION = *mut ::DWORD; +STRUCT!{struct TP_POOL_STACK_INFORMATION { + StackReserve: ::SIZE_T, + StackCommit: ::SIZE_T, +}} +pub type PTP_POOL_STACK_INFORMATION = *mut TP_POOL_STACK_INFORMATION; +STRUCT!{struct TP_CALLBACK_ENVIRON_V3_s { + BitFields: ::DWORD, +}} +BITFIELD!(TP_CALLBACK_ENVIRON_V3_s BitFields: ::DWORD [ + LongFunction set_LongFunction[0..1], + Persistent set_Persistent[1..2], + Private set_Private[2..32], +]); +STRUCT!{nodebug struct TP_CALLBACK_ENVIRON_V3 { + Version: TP_VERSION, + Pool: PTP_POOL, + CleanupGroup: PTP_CLEANUP_GROUP, + CleanupGroupCancelCallback: PTP_CLEANUP_GROUP_CANCEL_CALLBACK, + RaceDll: ::PVOID, + ActivationContext: *mut ACTIVATION_CONTEXT, + FinalizationCallback: PTP_SIMPLE_CALLBACK, + u: ::DWORD, + CallbackPriority: TP_CALLBACK_PRIORITY, + Size: ::DWORD, +}} +UNION!(TP_CALLBACK_ENVIRON_V3, u, Flags, Flags_mut, ::DWORD); +UNION!(TP_CALLBACK_ENVIRON_V3, u, s, s_mut, TP_CALLBACK_ENVIRON_V3_s); +pub type TP_CALLBACK_ENVIRON = TP_CALLBACK_ENVIRON_V3; +pub type PTP_CALLBACK_ENVIRON = *mut TP_CALLBACK_ENVIRON_V3; +STRUCT!{struct JOB_SET_ARRAY { + JobHandle: ::HANDLE, + MemberLevel: ::DWORD, + Flags: ::DWORD, +}} +pub type PJOB_SET_ARRAY = *mut JOB_SET_ARRAY; +STRUCT!{struct RTL_BARRIER { + Reserved1: ::DWORD, + Reserved2: ::DWORD, + Reserved3: [::ULONG_PTR; 2], + Reserved4: ::DWORD, + Reserved5: ::DWORD, +}} +pub type PRTL_BARRIER = *mut RTL_BARRIER; +STRUCT!{struct RTL_RUN_ONCE { + Ptr: ::PVOID, +}} +pub type PRTL_RUN_ONCE = *mut RTL_RUN_ONCE; +ENUM!{enum RTL_UMS_THREAD_INFO_CLASS { + UmsThreadInvalidInfoClass = 0, + UmsThreadUserContext, + UmsThreadPriority, // Reserved + UmsThreadAffinity, // Reserved + UmsThreadTeb, + UmsThreadIsSuspended, + UmsThreadIsTerminated, + UmsThreadMaxInfoClass, +}} +ENUM!{enum RTL_UMS_SCHEDULER_REASON { + UmsSchedulerStartup = 0, + UmsSchedulerThreadBlocked, + UmsSchedulerThreadYield, +}} +pub type PRTL_UMS_SCHEDULER_ENTRY_POINT = Option; +ENUM!{enum FIRMWARE_TYPE { + FirmwareTypeUnknown, + FirmwareTypeBios, + FirmwareTypeUefi, + FirmwareTypeMax, +}} +pub type PFIRMWARE_TYPE = *mut FIRMWARE_TYPE; +ENUM!{enum LOGICAL_PROCESSOR_RELATIONSHIP { + RelationProcessorCore, + RelationNumaNode, + RelationCache, + RelationProcessorPackage, + RelationGroup, + RelationAll = 0xffff, +}} +ENUM!{enum PROCESSOR_CACHE_TYPE { + CacheUnified, + CacheInstruction, + CacheData, + CacheTrace, +}} +STRUCT!{struct CACHE_DESCRIPTOR { + Level: ::BYTE, + Associativity: ::BYTE, + LineSize: ::WORD, + Size: ::DWORD, + Type: PROCESSOR_CACHE_TYPE, +}} +pub type PCACHE_DESCRIPTOR = *mut CACHE_DESCRIPTOR; +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_ProcessorCore { + Flags: ::BYTE, +}} +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION_NumaNode { + NodeNumber: ::DWORD, +}} +STRUCT!{struct SYSTEM_LOGICAL_PROCESSOR_INFORMATION { + ProcessorMask: ::ULONG_PTR, + Relationship: LOGICAL_PROCESSOR_RELATIONSHIP, + Reserved: [::ULONGLONG; 2], +}} +UNION!( + SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, ProcessorCore, ProcessorCore_mut, + SYSTEM_LOGICAL_PROCESSOR_INFORMATION_ProcessorCore +); +UNION!( + SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, NumaNode, NumaNode_mut, + SYSTEM_LOGICAL_PROCESSOR_INFORMATION_NumaNode +); +UNION!(SYSTEM_LOGICAL_PROCESSOR_INFORMATION, Reserved, Cache, Cache_mut, CACHE_DESCRIPTOR); +pub type PSYSTEM_LOGICAL_PROCESSOR_INFORMATION = *mut SYSTEM_LOGICAL_PROCESSOR_INFORMATION; +STRUCT!{struct SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION { + CycleTime: ::DWORD64, +}} +pub type PSYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION = *mut SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION; +ENUM!{enum HARDWARE_COUNTER_TYPE { + PMCCounter, + MaxHardwareCounterType, +}} +pub type PHARDWARE_COUNTER_TYPE = *mut HARDWARE_COUNTER_TYPE; +ENUM!{enum PROCESS_MITIGATION_POLICY { + ProcessDEPPolicy, + ProcessASLRPolicy, + ProcessDynamicCodePolicy, + ProcessStrictHandleCheckPolicy, + ProcessSystemCallDisablePolicy, + ProcessMitigationOptionsMask, + ProcessExtensionPointDisablePolicy, + ProcessReserved1Policy, + ProcessSignaturePolicy, + MaxProcessMitigationPolicy, +}} +STRUCT!{nodebug struct OSVERSIONINFOA { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::CHAR; 128], +}} +pub type POSVERSIONINFOA = *mut OSVERSIONINFOA; +pub type LPOSVERSIONINFOA = *mut OSVERSIONINFOA; +STRUCT!{nodebug struct OSVERSIONINFOW { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::WCHAR; 128], +}} +pub type POSVERSIONINFOW = *mut OSVERSIONINFOW; +pub type LPOSVERSIONINFOW = *mut OSVERSIONINFOW; +STRUCT!{nodebug struct OSVERSIONINFOEXA { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::CHAR; 128], + wServicePackMajor: ::WORD, + wServicePackMinor: ::WORD, + wSuiteMask: ::WORD, + wProductType: ::BYTE, + wReserved: ::BYTE, +}} +pub type POSVERSIONINFOEXA = *mut OSVERSIONINFOEXA; +pub type LPOSVERSIONINFOEXA = *mut OSVERSIONINFOEXA; +STRUCT!{nodebug struct OSVERSIONINFOEXW { + dwOSVersionInfoSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + dwBuildNumber: ::DWORD, + dwPlatformId: ::DWORD, + szCSDVersion: [::WCHAR; 128], + wServicePackMajor: ::WORD, + wServicePackMinor: ::WORD, + wSuiteMask: ::WORD, + wProductType: ::BYTE, + wReserved: ::BYTE, +}} +pub type POSVERSIONINFOEXW = *mut OSVERSIONINFOEXW; +pub type LPOSVERSIONINFOEXW = *mut OSVERSIONINFOEXW; +STRUCT!{struct SLIST_ENTRY { + Next: *mut SLIST_ENTRY, +}} +pub type PSLIST_ENTRY = *mut SLIST_ENTRY; +STRUCT!{struct SLIST_HEADER_HeaderX64 { + BitFields1: ::ULONGLONG, + BitFields2: ::ULONGLONG, +}} +BITFIELD!(SLIST_HEADER_HeaderX64 BitFields1: ::ULONGLONG [ + Depth set_Depth[0..16], + Sequence set_Sequence[16..64], +]); +BITFIELD!(SLIST_HEADER_HeaderX64 BitFields2: ::ULONGLONG [ + Reserved set_Reserved[0..4], + NextEntry set_NextEntry[4..64], +]); +STRUCT!{struct SLIST_HEADER { + Alignment: ::ULONGLONG, + Region: ::ULONGLONG, +}} +UNION!(SLIST_HEADER, Alignment, HeaderX64, HeaderX64_mut, SLIST_HEADER_HeaderX64); +pub type PSLIST_HEADER = *mut SLIST_HEADER; +ENUM!{enum SYSTEM_POWER_STATE { + PowerSystemUnspecified = 0, + PowerSystemWorking = 1, + PowerSystemSleeping1 = 2, + PowerSystemSleeping2 = 3, + PowerSystemSleeping3 = 4, + PowerSystemHibernate = 5, + PowerSystemShutdown = 6, + PowerSystemMaximum = 7, +}} +pub type PSYSTEM_POWER_STATE = *mut SYSTEM_POWER_STATE; +ENUM!{enum POWER_ACTION { + PowerActionNone = 0, + PowerActionReserved, + PowerActionSleep, + PowerActionHibernate, + PowerActionShutdown, + PowerActionShutdownReset, + PowerActionShutdownOff, + PowerActionWarmEject, +}} +pub type PPOWER_ACTION = *mut POWER_ACTION; +ENUM!{enum DEVICE_POWER_STATE { + PowerDeviceUnspecified = 0, + PowerDeviceD0, + PowerDeviceD1, + PowerDeviceD2, + PowerDeviceD3, + PowerDeviceMaximum, +}} +pub type PDEVICE_POWER_STATE = *mut DEVICE_POWER_STATE; +ENUM!{enum MONITOR_DISPLAY_STATE { + PowerMonitorOff = 0, + PowerMonitorOn, + PowerMonitorDim, +}} +pub type PMONITOR_DISPLAY_STATE = *mut MONITOR_DISPLAY_STATE; +ENUM!{enum USER_ACTIVITY_PRESENCE { + PowerUserPresent = 0, + PowerUserNotPresent, + PowerUserInactive, + PowerUserMaximum, + //PowerUserInvalid = 3, +}} +pub type PUSER_ACTIVITY_PRESENCE = *mut USER_ACTIVITY_PRESENCE; +pub type EXECUTION_STATE = ::DWORD; +pub type PEXECUTION_STATE = *mut ::DWORD; +ENUM!{enum LATENCY_TIME { + LT_DONT_CARE, + LT_LOWEST_LATENCY, +}} +ENUM!{enum POWER_REQUEST_TYPE { + PowerRequestDisplayRequired, + PowerRequestSystemRequired, + PowerRequestAwayModeRequired, + PowerRequestExecutionRequired, +}} +pub type PPOWER_REQUEST_TYPE = *mut POWER_REQUEST_TYPE; +pub const MAX_HW_COUNTERS: usize = 16; +STRUCT!{struct HARDWARE_COUNTER_DATA { + Type: HARDWARE_COUNTER_TYPE, + Reserved: ::DWORD, + Value: ::DWORD64, +}} +pub type PHARDWARE_COUNTER_DATA = *mut HARDWARE_COUNTER_DATA; +STRUCT!{struct PERFORMANCE_DATA { + Size: ::WORD, + Version: ::BYTE, + HwCountersCount: ::BYTE, + ContextSwitchCount: ::DWORD, + WaitReasonBitMap: ::DWORD64, + CycleTime: ::DWORD64, + RetryCount: ::DWORD, + Reserved: ::DWORD, + HwCounters: [HARDWARE_COUNTER_DATA; MAX_HW_COUNTERS], +}} +pub type PPERFORMANCE_DATA = *mut PERFORMANCE_DATA; +STRUCT!{struct MEMORY_BASIC_INFORMATION { + BaseAddress: ::PVOID, + AllocationBase: ::PVOID, + AllocationProtect: ::DWORD, + RegionSize: ::SIZE_T, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION = *mut MEMORY_BASIC_INFORMATION; +STRUCT!{struct MEMORY_BASIC_INFORMATION32 { + BaseAddress: ::DWORD, + AllocationBase: ::DWORD, + AllocationProtect: ::DWORD, + RegionSize: ::DWORD, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION32 = *mut MEMORY_BASIC_INFORMATION32; +STRUCT!{struct MEMORY_BASIC_INFORMATION64 { // FIXME: align 16 + BaseAddress: ::ULONGLONG, + AllocationBase: ::ULONGLONG, + AllocationProtect: ::DWORD, + __alignment1: ::DWORD, + RegionSize: ::ULONGLONG, + State: ::DWORD, + Protect: ::DWORD, + Type: ::DWORD, + __alignment2: ::DWORD, +}} +pub type PMEMORY_BASIC_INFORMATION64 = *mut MEMORY_BASIC_INFORMATION64; +pub const WOW64_SIZE_OF_80387_REGISTERS: usize = 80; +pub const WOW64_MAXIMUM_SUPPORTED_EXTENSION: usize = 512; +STRUCT!{nodebug struct WOW64_FLOATING_SAVE_AREA { + ControlWord: ::DWORD, + StatusWord: ::DWORD, + TagWord: ::DWORD, + ErrorOffset: ::DWORD, + ErrorSelector: ::DWORD, + DataOffset: ::DWORD, + DataSelector: ::DWORD, + RegisterArea: [::BYTE; WOW64_SIZE_OF_80387_REGISTERS], + Cr0NpxState: ::DWORD, +}} +pub type PWOW64_FLOATING_SAVE_AREA = *mut WOW64_FLOATING_SAVE_AREA; +STRUCT!{nodebug struct WOW64_CONTEXT { + ContextFlags: ::DWORD, + Dr0: ::DWORD, + Dr1: ::DWORD, + Dr2: ::DWORD, + Dr3: ::DWORD, + Dr4: ::DWORD, + Dr5: ::DWORD, + Dr6: ::DWORD, + Dr7: ::DWORD, + FloatSave: WOW64_FLOATING_SAVE_AREA, + SegGs: ::DWORD, + SegFs: ::DWORD, + SegEs: ::DWORD, + SegDs: ::DWORD, + Edi: ::DWORD, + Esi: ::DWORD, + Ebx: ::DWORD, + Edx: ::DWORD, + Ecx: ::DWORD, + Eax: ::DWORD, + Ebp: ::DWORD, + Eip: ::DWORD, + SegCs: ::DWORD, + EFlags: ::DWORD, + Esp: ::DWORD, + SegSs: ::DWORD, + ExtendedRegisters: [::BYTE; WOW64_MAXIMUM_SUPPORTED_EXTENSION], +}} +pub type PWOW64_CONTEXT = *mut WOW64_CONTEXT; +STRUCT!{struct WOW64_LDT_ENTRY_Bytes { + BaseMid: ::BYTE, + Flags1: ::BYTE, + Flags2: ::BYTE, + BaseHi: ::BYTE, +}} +STRUCT!{struct WOW64_LDT_ENTRY_Bits { + BitFields: ::DWORD, +}} +BITFIELD!(WOW64_LDT_ENTRY_Bits BitFields: ::DWORD [ + BaseMid set_BaseMid[0..8], + Type set_Type[8..13], + Dpl set_Dpl[13..15], + Pres set_Pres[15..16], + LimitHi set_LimitHi[16..20], + Sys set_Sys[20..21], + Reserved_0 set_Reserved_0[21..22], + Default_Big set_Default_Big[22..23], + Granularity set_Granularity[23..24], + BaseHi set_BaseHi[24..32], +]); +STRUCT!{struct WOW64_LDT_ENTRY { + LimitLow: ::WORD, + BaseLow: ::WORD, + HighWord: ::DWORD, +}} +UNION!(WOW64_LDT_ENTRY, HighWord, Bytes, Bytes_mut, WOW64_LDT_ENTRY_Bytes); +UNION!(WOW64_LDT_ENTRY, HighWord, Bits, Bits_mut, WOW64_LDT_ENTRY_Bits); +pub type PWOW64_LDT_ENTRY = *mut WOW64_LDT_ENTRY; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winreg.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winreg.rs new file mode 100644 index 0000000..91ef168 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winreg.rs @@ -0,0 +1,41 @@ +// Copyright © 2016, Peter Atashian +// Licensed under the MIT License +use super::*; +pub type REGSAM = ACCESS_MASK; +STRUCT!{struct VALENTA { + ve_valuename: LPSTR, + ve_valuelen: DWORD, + ve_valueptr: DWORD_PTR, + ve_type: DWORD, +}} +pub type PVALENTA = *mut VALENTA; +STRUCT!{struct VALENTW { + ve_valuename: LPWSTR, + ve_valuelen: DWORD, + ve_valueptr: DWORD_PTR, + ve_type: DWORD, +}} +pub type PVALENTW = *mut VALENTW; +pub const HKEY_CLASSES_ROOT: HKEY = 0x80000000 as HKEY; +pub const HKEY_CURRENT_USER: HKEY = 0x80000001 as HKEY; +pub const HKEY_LOCAL_MACHINE: HKEY = 0x80000002 as HKEY; +pub const HKEY_USERS: HKEY = 0x80000003 as HKEY; +pub const HKEY_PERFORMANCE_DATA: HKEY = 0x80000004 as HKEY; +pub const HKEY_PERFORMANCE_TEXT: HKEY = 0x80000050 as HKEY; +pub const HKEY_PERFORMANCE_NLSTEXT: HKEY = 0x80000060 as HKEY; +pub const HKEY_CURRENT_CONFIG: HKEY = 0x80000005 as HKEY; +pub const HKEY_DYN_DATA: HKEY = 0x80000006 as HKEY; +pub const HKEY_CURRENT_USER_LOCAL_SETTINGS: HKEY = 0x80000007 as HKEY; +pub const REG_MUI_STRING_TRUNCATE: DWORD = 0x00000001; +pub const RRF_RT_REG_NONE: DWORD = 0x00000001; +pub const RRF_RT_REG_SZ: DWORD = 0x00000002; +pub const RRF_RT_REG_EXPAND_SZ: DWORD = 0x00000004; +pub const RRF_RT_REG_BINARY: DWORD = 0x00000008; +pub const RRF_RT_REG_DWORD: DWORD = 0x00000010; +pub const RRF_RT_REG_MULTI_SZ: DWORD = 0x00000020; +pub const RRF_RT_REG_QWORD: DWORD = 0x00000040; +pub const RRF_RT_DWORD: DWORD = RRF_RT_REG_BINARY|RRF_RT_REG_DWORD; +pub const RRF_RT_QWORD: DWORD = RRF_RT_REG_BINARY|RRF_RT_REG_QWORD; +pub const RRF_RT_ANY: DWORD = 0x0000ffff; +pub const RRF_NOEXPAND: DWORD = 0x10000000; +pub const RRF_ZEROONFAILURE: DWORD = 0x20000000; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winscard.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winscard.rs new file mode 100644 index 0000000..7d20c2d --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winscard.rs @@ -0,0 +1,269 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Data Protection API Prototypes and Definitions +// This header file provides the definitions and symbols necessary for an +// Application or Smart Card Service Provider to access the Smartcard Subsystem. +pub type LPCBYTE = *const ::BYTE; +pub type SCARDCONTEXT = ::ULONG_PTR; +pub type PSCARDCONTEXT = *mut SCARDCONTEXT; +pub type LPSCARDCONTEXT = *mut SCARDCONTEXT; +pub type SCARDHANDLE = ::ULONG_PTR; +pub type PSCARDHANDLE = *mut SCARDHANDLE; +pub type LPSCARDHANDLE = *mut SCARDHANDLE; +pub const SCARD_AUTOALLOCATE: ::DWORD = -1i32 as ::DWORD; +pub const SCARD_SCOPE_USER: ::DWORD = 0; +pub const SCARD_SCOPE_TERMINAL: ::DWORD = 1; +pub const SCARD_SCOPE_SYSTEM: ::DWORD = 2; +pub const SCARD_PROVIDER_PRIMARY: ::DWORD = 1; +pub const SCARD_PROVIDER_CSP: ::DWORD = 2; +pub const SCARD_PROVIDER_KSP: ::DWORD = 3; +STRUCT!{nodebug struct SCARD_READERSTATEA { + szReader: ::LPCSTR, + pvUserData: ::LPVOID, + dwCurrentState: ::DWORD, + dwEventState: ::DWORD, + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], +}} +pub type PSCARD_READERSTATEA = *mut SCARD_READERSTATEA; +pub type LPSCARD_READERSTATEA = *mut SCARD_READERSTATEA; +STRUCT!{nodebug struct SCARD_READERSTATEW { + szReader: ::LPCWSTR, + pvUserData: ::LPVOID, + dwCurrentState: ::DWORD, + dwEventState: ::DWORD, + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], +}} +pub type PSCARD_READERSTATEW = *mut SCARD_READERSTATEW; +pub type LPSCARD_READERSTATEW = *mut SCARD_READERSTATEW; +pub type SCARD_READERSTATE_A = SCARD_READERSTATEA; +pub type SCARD_READERSTATE_W = SCARD_READERSTATEW; +pub type PSCARD_READERSTATE_A = PSCARD_READERSTATEA; +pub type PSCARD_READERSTATE_W = PSCARD_READERSTATEW; +pub type LPSCARD_READERSTATE_A = LPSCARD_READERSTATEA; +pub type LPSCARD_READERSTATE_W = LPSCARD_READERSTATEW; +pub const SCARD_STATE_UNAWARE: ::DWORD = 0x00000000; +pub const SCARD_STATE_IGNORE: ::DWORD = 0x00000001; +pub const SCARD_STATE_CHANGED: ::DWORD = 0x00000002; +pub const SCARD_STATE_UNKNOWN: ::DWORD = 0x00000004; +pub const SCARD_STATE_UNAVAILABLE: ::DWORD = 0x00000008; +pub const SCARD_STATE_EMPTY: ::DWORD = 0x00000010; +pub const SCARD_STATE_PRESENT: ::DWORD = 0x00000020; +pub const SCARD_STATE_ATRMATCH: ::DWORD = 0x00000040; +pub const SCARD_STATE_EXCLUSIVE: ::DWORD = 0x00000080; +pub const SCARD_STATE_INUSE: ::DWORD = 0x00000100; +pub const SCARD_STATE_MUTE: ::DWORD = 0x00000200; +pub const SCARD_STATE_UNPOWERED: ::DWORD = 0x00000400; +STRUCT!{nodebug struct SCARD_ATRMASK { + cbAtr: ::DWORD, + rgbAtr: [::BYTE; 36], + rgbMask: [::BYTE; 36], +}} +pub type PSCARD_ATRMASK = *mut SCARD_ATRMASK; +pub type LPSCARD_ATRMASK = *mut SCARD_ATRMASK; +pub const SCARD_SHARE_EXCLUSIVE: ::DWORD = 1; +pub const SCARD_SHARE_SHARED: ::DWORD = 2; +pub const SCARD_SHARE_DIRECT: ::DWORD = 3; +pub const SCARD_LEAVE_CARD: ::DWORD = 0; +pub const SCARD_RESET_CARD: ::DWORD = 1; +pub const SCARD_UNPOWER_CARD: ::DWORD = 2; +pub const SCARD_EJECT_CARD: ::DWORD = 3; +pub const SC_DLG_MINIMAL_UI: ::DWORD = 0x01; +pub const SC_DLG_NO_UI: ::DWORD = 0x02; +pub const SC_DLG_FORCE_UI: ::DWORD = 0x04; +pub const SCERR_NOCARDNAME: ::DWORD = 0x4000; +pub const SCERR_NOGUIDS: ::DWORD = 0x8000; +pub type LPOCNCONNPROCA = Option SCARDHANDLE>; +pub type LPOCNCONNPROCW = Option SCARDHANDLE>; +pub type LPOCNCHKPROC = Option ::BOOL>; +pub type LPOCNDSCPROC = Option; +STRUCT!{nodebug struct OPENCARD_SEARCH_CRITERIAA { + dwStructSize: ::DWORD, + lpstrGroupNames: ::LPSTR, + nMaxGroupNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrCardNames: ::LPSTR, + nMaxCardNames: ::DWORD, + lpfnCheck: LPOCNCHKPROC, + lpfnConnect: LPOCNCONNPROCA, + lpfnDisconnect: LPOCNDSCPROC, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, +}} +pub type POPENCARD_SEARCH_CRITERIAA = *mut OPENCARD_SEARCH_CRITERIAA; +pub type LPOPENCARD_SEARCH_CRITERIAA = *mut OPENCARD_SEARCH_CRITERIAA; +STRUCT!{nodebug struct OPENCARD_SEARCH_CRITERIAW { + dwStructSize: ::DWORD, + lpstrGroupNames: ::LPWSTR, + nMaxGroupNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrCardNames: ::LPWSTR, + nMaxCardNames: ::DWORD, + lpfnCheck: LPOCNCHKPROC, + lpfnConnect: LPOCNCONNPROCW, + lpfnDisconnect: LPOCNDSCPROC, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, +}} +pub type POPENCARD_SEARCH_CRITERIAW = *mut OPENCARD_SEARCH_CRITERIAW; +pub type LPOPENCARD_SEARCH_CRITERIAW = *mut OPENCARD_SEARCH_CRITERIAW; +STRUCT!{nodebug struct OPENCARDNAME_EXA { + dwStructSize: ::DWORD, + hSCardContext: SCARDCONTEXT, + hwndOwner: ::HWND, + dwFlags: ::DWORD, + lpstrTitle: ::LPCSTR, + lpstrSearchDesc: ::LPCSTR, + hIcon: ::HICON, + pOpenCardSearchCriteria: POPENCARD_SEARCH_CRITERIAA, + lpfnConnect: LPOCNCONNPROCA, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + lpstrRdr: ::LPSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPSTR, + nMaxCard: ::DWORD, + dwActiveProtocol: ::DWORD, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAME_EXA = *mut OPENCARDNAME_EXA; +pub type LPOPENCARDNAME_EXA = *mut OPENCARDNAME_EXA; +STRUCT!{nodebug struct OPENCARDNAME_EXW { + dwStructSize: ::DWORD, + hSCardContext: SCARDCONTEXT, + hwndOwner: ::HWND, + dwFlags: ::DWORD, + lpstrTitle: ::LPCWSTR, + lpstrSearchDesc: ::LPCWSTR, + hIcon: ::HICON, + pOpenCardSearchCriteria: POPENCARD_SEARCH_CRITERIAW, + lpfnConnect: LPOCNCONNPROCW, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + lpstrRdr: ::LPWSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPWSTR, + nMaxCard: ::DWORD, + dwActiveProtocol: ::DWORD, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAME_EXW = *mut OPENCARDNAME_EXW; +pub type LPOPENCARDNAME_EXW = *mut OPENCARDNAME_EXW; +pub type OPENCARDNAMEA_EX = OPENCARDNAME_EXA; +pub type OPENCARDNAMEW_EX = OPENCARDNAME_EXW; +pub type POPENCARDNAMEA_EX = POPENCARDNAME_EXA; +pub type POPENCARDNAMEW_EX = POPENCARDNAME_EXW; +pub type LPOPENCARDNAMEA_EX = LPOPENCARDNAME_EXA; +pub type LPOPENCARDNAMEW_EX = LPOPENCARDNAME_EXW; +pub const SCARD_READER_SEL_AUTH_PACKAGE: ::DWORD = -629i32 as ::DWORD; +ENUM!{enum READER_SEL_REQUEST_MATCH_TYPE { + RSR_MATCH_TYPE_READER_AND_CONTAINER = 1, + RSR_MATCH_TYPE_SERIAL_NUMBER, + RSR_MATCH_TYPE_ALL_CARDS, +}} +STRUCT!{struct READER_SEL_REQUEST_ReaderAndContainerParameter { + cbReaderNameOffset: ::DWORD, + cchReaderNameLength: ::DWORD, + cbContainerNameOffset: ::DWORD, + cchContainerNameLength: ::DWORD, + dwDesiredCardModuleVersion: ::DWORD, + dwCspFlags: ::DWORD, +}} +STRUCT!{struct READER_SEL_REQUEST_SerialNumberParameter { + cbSerialNumberOffset: ::DWORD, + cbSerialNumberLength: ::DWORD, + dwDesiredCardModuleVersion: ::DWORD, +}} +STRUCT!{struct READER_SEL_REQUEST { + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + MatchType: READER_SEL_REQUEST_MATCH_TYPE, + ReaderAndContainerParameter: READER_SEL_REQUEST_ReaderAndContainerParameter, +}} +UNION!( + READER_SEL_REQUEST, ReaderAndContainerParameter, SerialNumberParameter, + SerialNumberParameter_mut, READER_SEL_REQUEST_SerialNumberParameter +); +pub type PREADER_SEL_REQUEST = *mut READER_SEL_REQUEST; +STRUCT!{struct READER_SEL_RESPONSE { + cbReaderNameOffset: ::DWORD, + cchReaderNameLength: ::DWORD, + cbCardNameOffset: ::DWORD, + cchCardNameLength: ::DWORD, +}} +pub type PREADER_SEL_RESPONSE = *mut READER_SEL_RESPONSE; +STRUCT!{nodebug struct OPENCARDNAMEA { + dwStructSize: ::DWORD, + hwndOwner: ::HWND, + hSCardContext: SCARDCONTEXT, + lpstrGroupNames: ::LPSTR, + nMaxGroupNames: ::DWORD, + lpstrCardNames: ::LPSTR, + nMaxCardNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrRdr: ::LPSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPSTR, + nMaxCard: ::DWORD, + lpstrTitle: ::LPCSTR, + dwFlags: ::DWORD, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + dwActiveProtocol: ::DWORD, + lpfnConnect: LPOCNCONNPROCA, + lpfnCheck: LPOCNCHKPROC, + lpfnDisconnect: LPOCNDSCPROC, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAMEA = *mut OPENCARDNAMEA; +pub type LPOPENCARDNAMEA = *mut OPENCARDNAMEA; +STRUCT!{nodebug struct OPENCARDNAMEW { + dwStructSize: ::DWORD, + hwndOwner: ::HWND, + hSCardContext: SCARDCONTEXT, + lpstrGroupNames: ::LPWSTR, + nMaxGroupNames: ::DWORD, + lpstrCardNames: ::LPWSTR, + nMaxCardNames: ::DWORD, + rgguidInterfaces: ::LPCGUID, + cguidInterfaces: ::DWORD, + lpstrRdr: ::LPWSTR, + nMaxRdr: ::DWORD, + lpstrCard: ::LPWSTR, + nMaxCard: ::DWORD, + lpstrTitle: ::LPCWSTR, + dwFlags: ::DWORD, + pvUserData: ::LPVOID, + dwShareMode: ::DWORD, + dwPreferredProtocols: ::DWORD, + dwActiveProtocol: ::DWORD, + lpfnConnect: LPOCNCONNPROCW, + lpfnCheck: LPOCNCHKPROC, + lpfnDisconnect: LPOCNDSCPROC, + hCardHandle: SCARDHANDLE, +}} +pub type POPENCARDNAMEW = *mut OPENCARDNAMEW; +pub type LPOPENCARDNAMEW = *mut OPENCARDNAMEW; +pub type OPENCARDNAME_A = OPENCARDNAMEA; +pub type OPENCARDNAME_W = OPENCARDNAMEW; +pub type POPENCARDNAME_A = POPENCARDNAMEA; +pub type POPENCARDNAME_W = POPENCARDNAMEW; +pub type LPOPENCARDNAME_A = LPOPENCARDNAMEA; +pub type LPOPENCARDNAME_W = LPOPENCARDNAMEW; +pub const SCARD_AUDIT_CHV_FAILURE: ::DWORD = 0x0; +pub const SCARD_AUDIT_CHV_SUCCESS: ::DWORD = 0x1; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winsmcrd.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winsmcrd.rs new file mode 100644 index 0000000..28f3474 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winsmcrd.rs @@ -0,0 +1,157 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +// Smart Card class/port IOCTL codes. +pub type UWORD = ::WORD; +DEFINE_GUID!(GUID_DEVINTERFACE_SMARTCARD_READER, 0x50DD5230, 0xBA8A, 0x11D1, + 0xBF, 0x5D, 0x00, 0x00, 0xF8, 0x05, 0xF5, 0x30); +pub const SCARD_ATR_LENGTHL: ::DWORD = 33; +pub const SCARD_PROTOCOL_UNDEFINED: ::DWORD = 0x00000000; +pub const SCARD_PROTOCOL_T0: ::DWORD = 0x00000001; +pub const SCARD_PROTOCOL_T1: ::DWORD = 0x00000002; +pub const SCARD_PROTOCOL_RAW: ::DWORD = 0x00010000; +pub const SCARD_PROTOCOL_Tx: ::DWORD = SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1; +pub const SCARD_PROTOCOL_DEFAULT: ::DWORD = 0x80000000; +pub const SCARD_PROTOCOL_OPTIMAL: ::DWORD = 0x00000000; +pub const SCARD_POWER_DOWN: ::DWORD = 0; +pub const SCARD_COLD_RESET: ::DWORD = 1; +pub const SCARD_WARM_RESET: ::DWORD = 2; +pub const IOCTL_SMARTCARD_POWER: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 1, ::METHOD_BUFFERED, + ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_ATTRIBUTE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 2, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SET_ATTRIBUTE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 3, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_CONFISCATE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 4, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_TRANSMIT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 5, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_EJECT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 6, ::METHOD_BUFFERED, + ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SWALLOW: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 7, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_IS_PRESENT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 10, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_IS_ABSENT: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 11, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_SET_PROTOCOL: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 12, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_STATE: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 14, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_LAST_ERROR: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 15, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const IOCTL_SMARTCARD_GET_PERF_CNTR: ::DWORD = CTL_CODE!(::FILE_DEVICE_SMARTCARD, 16, + ::METHOD_BUFFERED, ::FILE_ANY_ACCESS); +pub const MAXIMUM_ATTR_STRING_LENGTH: ::DWORD = 32; +pub const MAXIMUM_SMARTCARD_READERS: ::DWORD = 10; +pub const SCARD_CLASS_VENDOR_INFO: ::ULONG = 1; +pub const SCARD_CLASS_COMMUNICATIONS: ::ULONG = 2; +pub const SCARD_CLASS_PROTOCOL: ::ULONG = 3; +pub const SCARD_CLASS_POWER_MGMT: ::ULONG = 4; +pub const SCARD_CLASS_SECURITY: ::ULONG = 5; +pub const SCARD_CLASS_MECHANICAL: ::ULONG = 6; +pub const SCARD_CLASS_VENDOR_DEFINED: ::ULONG = 7; +pub const SCARD_CLASS_IFD_PROTOCOL: ::ULONG = 8; +pub const SCARD_CLASS_ICC_STATE: ::ULONG = 9; +pub const SCARD_CLASS_PERF: ::ULONG = 0x7ffe; +pub const SCARD_CLASS_SYSTEM: ::ULONG = 0x7fff; +pub const SCARD_ATTR_VENDOR_NAME: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0100; +pub const SCARD_ATTR_VENDOR_IFD_TYPE: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0101; +pub const SCARD_ATTR_VENDOR_IFD_VERSION: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0102; +pub const SCARD_ATTR_VENDOR_IFD_SERIAL_NO: ::ULONG = SCARD_CLASS_VENDOR_INFO << 16 | 0x0103; +pub const SCARD_ATTR_CHANNEL_ID: ::ULONG = SCARD_CLASS_COMMUNICATIONS << 16 | 0x0110; +pub const SCARD_ATTR_PROTOCOL_TYPES: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0120; +pub const SCARD_ATTR_DEFAULT_CLK: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0121; +pub const SCARD_ATTR_MAX_CLK: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0122; +pub const SCARD_ATTR_DEFAULT_DATA_RATE: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0123; +pub const SCARD_ATTR_MAX_DATA_RATE: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0124; +pub const SCARD_ATTR_MAX_IFSD: ::ULONG = SCARD_CLASS_PROTOCOL << 16 | 0x0125; +pub const SCARD_ATTR_POWER_MGMT_SUPPORT: ::ULONG = SCARD_CLASS_POWER_MGMT << 16 | 0x0131; +pub const SCARD_ATTR_USER_TO_CARD_AUTH_DEVICE: ::ULONG = SCARD_CLASS_SECURITY << 16 | 0x0140; +pub const SCARD_ATTR_USER_AUTH_INPUT_DEVICE: ::ULONG = SCARD_CLASS_SECURITY << 16 | 0x0142; +pub const SCARD_ATTR_CHARACTERISTICS: ::ULONG = SCARD_CLASS_MECHANICAL << 16 | 0x0150; +pub const SCARD_ATTR_CURRENT_PROTOCOL_TYPE: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0201; +pub const SCARD_ATTR_CURRENT_CLK: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0202; +pub const SCARD_ATTR_CURRENT_F: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0203; +pub const SCARD_ATTR_CURRENT_D: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0204; +pub const SCARD_ATTR_CURRENT_N: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0205; +pub const SCARD_ATTR_CURRENT_W: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0206; +pub const SCARD_ATTR_CURRENT_IFSC: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0207; +pub const SCARD_ATTR_CURRENT_IFSD: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0208; +pub const SCARD_ATTR_CURRENT_BWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x0209; +pub const SCARD_ATTR_CURRENT_CWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020a; +pub const SCARD_ATTR_CURRENT_EBC_ENCODING: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020b; +pub const SCARD_ATTR_EXTENDED_BWT: ::ULONG = SCARD_CLASS_IFD_PROTOCOL << 16 | 0x020c; +pub const SCARD_ATTR_ICC_PRESENCE: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0300; +pub const SCARD_ATTR_ICC_INTERFACE_STATUS: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0301; +pub const SCARD_ATTR_CURRENT_IO_STATE: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0302; +pub const SCARD_ATTR_ATR_STRING: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0303; +pub const SCARD_ATTR_ICC_TYPE_PER_ATR: ::ULONG = SCARD_CLASS_ICC_STATE << 16 | 0x0304; +pub const SCARD_ATTR_ESC_RESET: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA000; +pub const SCARD_ATTR_ESC_CANCEL: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA003; +pub const SCARD_ATTR_ESC_AUTHREQUEST: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA005; +pub const SCARD_ATTR_MAXINPUT: ::ULONG = SCARD_CLASS_VENDOR_DEFINED << 16 | 0xA007; +pub const SCARD_ATTR_DEVICE_UNIT: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0001; +pub const SCARD_ATTR_DEVICE_IN_USE: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0002; +pub const SCARD_ATTR_DEVICE_FRIENDLY_NAME_A: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0003; +pub const SCARD_ATTR_DEVICE_SYSTEM_NAME_A: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0004; +pub const SCARD_ATTR_DEVICE_FRIENDLY_NAME_W: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0005; +pub const SCARD_ATTR_DEVICE_SYSTEM_NAME_W: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0006; +pub const SCARD_ATTR_SUPRESS_T1_IFS_REQUEST: ::ULONG = SCARD_CLASS_SYSTEM << 16 | 0x0007; +pub const SCARD_PERF_NUM_TRANSMISSIONS: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0001; +pub const SCARD_PERF_BYTES_TRANSMITTED: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0002; +pub const SCARD_PERF_TRANSMISSION_TIME: ::ULONG = SCARD_CLASS_PERF << 16 | 0x0003; +pub const SCARD_T0_HEADER_LENGTH: ::DWORD = 7; +pub const SCARD_T0_CMD_LENGTH: ::DWORD = 5; +pub const SCARD_T1_PROLOGUE_LENGTH: ::DWORD = 3; +pub const SCARD_T1_EPILOGUE_LENGTH: ::DWORD = 2; +pub const SCARD_T1_MAX_IFS: ::DWORD = 254; +pub const SCARD_UNKNOWN: ::ULONG = 0; +pub const SCARD_ABSENT: ::ULONG = 1; +pub const SCARD_PRESENT: ::ULONG = 2; +pub const SCARD_SWALLOWED: ::ULONG = 3; +pub const SCARD_POWERED: ::ULONG = 4; +pub const SCARD_NEGOTIABLE: ::ULONG = 5; +pub const SCARD_SPECIFIC: ::ULONG = 6; +STRUCT!{struct SCARD_IO_REQUEST { + dwProtocol: ::DWORD, + cbPciLength: ::DWORD, +}} +pub type PSCARD_IO_REQUEST = *mut SCARD_IO_REQUEST; +pub type LPSCARD_IO_REQUEST = *mut SCARD_IO_REQUEST; +pub type LPCSCARD_IO_REQUEST = *const SCARD_IO_REQUEST; +STRUCT!{struct SCARD_T0_COMMAND { + bCla: ::BYTE, + bIns: ::BYTE, + bP1: ::BYTE, + bP2: ::BYTE, + bP3: ::BYTE, +}} +pub type LPSCARD_T0_COMMAND = *mut SCARD_T0_COMMAND; +STRUCT!{struct SCARD_T0_REQUEST { + ioRequest: SCARD_IO_REQUEST, + bSw1: ::BYTE, + bSw2: ::BYTE, + CmdBytes: SCARD_T0_COMMAND, +}} +UNION!(SCARD_T0_REQUEST, CmdBytes, rgbHeader, rgbHeader_mut, [::BYTE; 5]); +pub type PSCARD_T0_REQUEST = *mut SCARD_T0_REQUEST; +pub type LPSCARD_T0_REQUEST = *mut SCARD_T0_REQUEST; +STRUCT!{struct SCARD_T1_REQUEST { + ioRequest: SCARD_IO_REQUEST, +}} +pub type PSCARD_T1_REQUEST = *mut SCARD_T1_REQUEST; +pub type LPSCARD_T1_REQUEST = *mut SCARD_T1_REQUEST; +pub const SCARD_READER_SWALLOWS: ::ULONG = 0x00000001; +pub const SCARD_READER_EJECTS: ::ULONG = 0x00000002; +pub const SCARD_READER_CONFISCATES: ::ULONG = 0x00000004; +pub const SCARD_READER_TYPE_SERIAL: ::ULONG = 0x01; +pub const SCARD_READER_TYPE_PARALELL: ::ULONG = 0x02; +pub const SCARD_READER_TYPE_KEYBOARD: ::ULONG = 0x04; +pub const SCARD_READER_TYPE_SCSI: ::ULONG = 0x08; +pub const SCARD_READER_TYPE_IDE: ::ULONG = 0x10; +pub const SCARD_READER_TYPE_USB: ::ULONG = 0x20; +pub const SCARD_READER_TYPE_PCMCIA: ::ULONG = 0x40; +pub const SCARD_READER_TYPE_TPM: ::ULONG = 0x80; +pub const SCARD_READER_TYPE_NFC: ::ULONG = 0x100; +pub const SCARD_READER_TYPE_UICC: ::ULONG = 0x200; +pub const SCARD_READER_TYPE_VENDOR: ::ULONG = 0xF0; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winsock2.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winsock2.rs new file mode 100644 index 0000000..05b62f2 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winsock2.rs @@ -0,0 +1,429 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! definitions to be used with the WinSock 2 DLL and WinSock 2 applications. +//! +//! This header file corresponds to version 2.2.x of the WinSock API specification. +pub const WINSOCK_VERSION: ::WORD = 2 | (2 << 8); +pub type u_char = ::c_uchar; +pub type u_short = ::c_ushort; +pub type u_int = ::c_uint; +pub type u_long = ::c_ulong; +pub type u_int64 = ::__uint64; +pub type SOCKET = ::UINT_PTR; +pub type GROUP = ::c_uint; +pub const FD_SETSIZE: usize = 64; +pub const FD_MAX_EVENTS: usize = 10; +STRUCT!{nodebug struct fd_set { + fd_count: u_int, + fd_array: [SOCKET; FD_SETSIZE], +}} +STRUCT!{struct timeval { + tv_sec: ::c_long, + tv_usec: ::c_long, +}} +STRUCT!{struct hostent { + h_name: *mut ::c_char, + h_aliases: *mut *mut ::c_char, + h_addrtype: ::c_short, + h_length: ::c_short, + h_addr_list: *mut *mut ::c_char, +}} +STRUCT!{struct netent { + n_name: *mut ::c_char, + n_aliases: *mut *mut ::c_char, + n_addrtype: ::c_short, + n_net: u_long, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct servent { + s_name: *mut ::c_char, + s_aliases: *mut *mut ::c_char, + s_port: ::c_short, + s_proto: *mut ::c_char, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct servent { + s_name: *mut ::c_char, + s_aliases: *mut *mut ::c_char, + s_proto: *mut ::c_char, + s_port: ::c_short, +}} +STRUCT!{struct protoent { + p_name: *mut ::c_char, + p_aliases: *mut *mut ::c_char, + p_proto: ::c_short, +}} +pub const WSADESCRIPTION_LEN: usize = 256; +pub const WSASYS_STATUS_LEN: usize = 128; +#[cfg(target_arch="x86")] +STRUCT!{nodebug struct WSADATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + szDescription: [::c_char; WSADESCRIPTION_LEN + 1], + szSystemStatus: [::c_char; WSASYS_STATUS_LEN + 1], + iMaxSockets: ::c_ushort, + iMaxUdpDg: ::c_ushort, + lpVendorInfo: *mut ::c_char, +}} +#[cfg(target_arch="x86_64")] +STRUCT!{nodebug struct WSADATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + iMaxSockets: ::c_ushort, + iMaxUdpDg: ::c_ushort, + lpVendorInfo: *mut ::c_char, + szDescription: [::c_char; WSADESCRIPTION_LEN + 1], + szSystemStatus: [::c_char; WSASYS_STATUS_LEN + 1], +}} +pub type LPWSADATA = *mut WSADATA; +//391 +pub const INVALID_SOCKET: SOCKET = !0; +pub const SOCKET_ERROR: ::c_int = -1; +STRUCT!{struct sockproto { + sp_family: u_short, + sp_protocol: u_short, +}} +pub const PF_UNSPEC: ::c_int = ::AF_UNSPEC; +pub const PF_UNIX: ::c_int = ::AF_UNIX; +pub const PF_INET: ::c_int = ::AF_INET; +pub const PF_IMPLINK: ::c_int = ::AF_IMPLINK; +pub const PF_PUP: ::c_int = ::AF_PUP; +pub const PF_CHAOS: ::c_int = ::AF_CHAOS; +pub const PF_NS: ::c_int = ::AF_NS; +pub const PF_IPX: ::c_int = ::AF_IPX; +pub const PF_ISO: ::c_int = ::AF_ISO; +pub const PF_OSI: ::c_int = ::AF_OSI; +pub const PF_ECMA: ::c_int = ::AF_ECMA; +pub const PF_DATAKIT: ::c_int = ::AF_DATAKIT; +pub const PF_CCITT: ::c_int = ::AF_CCITT; +pub const PF_SNA: ::c_int = ::AF_SNA; +pub const PF_DECnet: ::c_int = ::AF_DECnet; +pub const PF_DLI: ::c_int = ::AF_DLI; +pub const PF_LAT: ::c_int = ::AF_LAT; +pub const PF_HYLINK: ::c_int = ::AF_HYLINK; +pub const PF_APPLETALK: ::c_int = ::AF_APPLETALK; +pub const PF_VOICEVIEW: ::c_int = ::AF_VOICEVIEW; +pub const PF_FIREFOX: ::c_int = ::AF_FIREFOX; +pub const PF_UNKNOWN1: ::c_int = ::AF_UNKNOWN1; +pub const PF_BAN: ::c_int = ::AF_BAN; +pub const PF_ATM: ::c_int = ::AF_ATM; +pub const PF_INET6: ::c_int = ::AF_INET6; +pub const PF_BTH: ::c_int = ::AF_BTH; +pub const PF_MAX: ::c_int = ::AF_MAX; +STRUCT!{struct linger { + l_onoff: u_short, + l_linger: u_short, +}} +pub const SOMAXCONN: ::c_int = 0x7fffffff; +pub type WSAEVENT = ::HANDLE; +pub type LPWSAEVENT = ::LPHANDLE; +pub type WSAOVERLAPPED = ::OVERLAPPED; +pub type LPWSAOVERLAPPED = *mut ::OVERLAPPED; +pub const WSA_IO_PENDING: ::DWORD = ::ERROR_IO_PENDING; +pub const WSA_IO_INCOMPLETE: ::DWORD = ::ERROR_IO_INCOMPLETE; +pub const WSA_INVALID_HANDLE: ::DWORD = ::ERROR_INVALID_HANDLE; +pub const WSA_INVALID_PARAMETER: ::DWORD = ::ERROR_INVALID_PARAMETER; +pub const WSA_NOT_ENOUGH_MEMORY: ::DWORD = ::ERROR_NOT_ENOUGH_MEMORY; +pub const WSA_OPERATION_ABORTED: ::DWORD = ::ERROR_OPERATION_ABORTED; +STRUCT!{struct QOS { + SendingFlowspec: ::FLOWSPEC, + FLOWSPEC: ::FLOWSPEC, + ProviderSpecific: ::WSABUF, +}} +pub type LPQOS = *mut QOS; +STRUCT!{struct WSANETWORKEVENTS { + lNetworkEvents: ::c_long, + iErrorCode: [::c_int; FD_MAX_EVENTS], +}} +pub type LPWSANETWORKEVENTS = *mut WSANETWORKEVENTS; +pub const MAX_PROTOCOL_CHAIN: usize = 7; +STRUCT!{struct WSAPROTOCOLCHAIN { + ChainLen: ::c_int, + ChainEntries: [::DWORD; MAX_PROTOCOL_CHAIN], +}} +pub type LPWSAPROTOCOLCHAIN = *mut WSAPROTOCOLCHAIN; +pub const WSAPROTOCOL_LEN: usize = 255; +STRUCT!{nodebug struct WSAPROTOCOL_INFOA { + dwServiceFlags1: ::DWORD, + dwServiceFlags2: ::DWORD, + dwServiceFlags3: ::DWORD, + dwServiceFlags4: ::DWORD, + dwServiceFlags5: ::DWORD, + ProviderId: ::GUID, + dwCatalogEntryId: ::DWORD, + ProtocolChain: WSAPROTOCOLCHAIN, + iVersion: ::c_int, + iAddressFamily: ::c_int, + iMaxSockAddr: ::c_int, + iMinSockAddr: ::c_int, + iSocketType: ::c_int, + iProtocol: ::c_int, + iProtocolMaxOffset: ::c_int, + iNetworkByteOrder: ::c_int, + iSecurityScheme: ::c_int, + dwMessageSize: ::DWORD, + dwProviderReserved: ::DWORD, + szProtocol: [::CHAR; WSAPROTOCOL_LEN + 1], +}} +pub type LPWSAPROTOCOL_INFOA = *mut WSAPROTOCOL_INFOA; +STRUCT!{nodebug struct WSAPROTOCOL_INFOW { + dwServiceFlags1: ::DWORD, + dwServiceFlags2: ::DWORD, + dwServiceFlags3: ::DWORD, + dwServiceFlags4: ::DWORD, + dwServiceFlags5: ::DWORD, + ProviderId: ::GUID, + dwCatalogEntryId: ::DWORD, + ProtocolChain: WSAPROTOCOLCHAIN, + iVersion: ::c_int, + iAddressFamily: ::c_int, + iMaxSockAddr: ::c_int, + iMinSockAddr: ::c_int, + iSocketType: ::c_int, + iProtocol: ::c_int, + iProtocolMaxOffset: ::c_int, + iNetworkByteOrder: ::c_int, + iSecurityScheme: ::c_int, + dwMessageSize: ::DWORD, + dwProviderReserved: ::DWORD, + szProtocol: [::WCHAR; WSAPROTOCOL_LEN + 1], +}} +pub type LPWSAPROTOCOL_INFOW = *mut WSAPROTOCOL_INFOW; +pub type LPCONDITIONPROC = Option ::c_int>; +pub type LPWSAOVERLAPPED_COMPLETION_ROUTINE = Option; +ENUM!{enum WSACOMPLETIONTYPE { + NSP_NOTIFY_IMMEDIATELY = 0, + NSP_NOTIFY_HWND, + NSP_NOTIFY_EVENT, + NSP_NOTIFY_PORT, + NSP_NOTIFY_APC, +}} +pub type PWSACOMPLETIONTYPE = *mut WSACOMPLETIONTYPE; +pub type LPWSACOMPLETIONTYPE = *mut WSACOMPLETIONTYPE; +STRUCT!{struct WSACOMPLETION_WindowMessage { + hWnd: ::HWND, + uMsg: ::UINT, + context: ::WPARAM, +}} +STRUCT!{struct WSACOMPLETION_Event { + lpOverlapped: LPWSAOVERLAPPED, +}} +STRUCT!{nodebug struct WSACOMPLETION_Apc { + lpOverlapped: LPWSAOVERLAPPED, + lpfnCompletionProc: LPWSAOVERLAPPED_COMPLETION_ROUTINE, +}} +STRUCT!{struct WSACOMPLETION_Port { + lpOverlapped: LPWSAOVERLAPPED, + hPort: ::HANDLE, + Key: ::ULONG_PTR, +}} +#[cfg(target_arch="x86")] +STRUCT!{struct WSACOMPLETION { + Type: WSACOMPLETIONTYPE, + Parameters: [u8; 12], +}} +#[cfg(target_arch="x86_64")] +STRUCT!{struct WSACOMPLETION { + Type: WSACOMPLETIONTYPE, + Parameters: [u8; 24], +}} +UNION!(WSACOMPLETION, Parameters, WindowMessage, WindowMessage_mut, WSACOMPLETION_WindowMessage); +UNION!(WSACOMPLETION, Parameters, Event, Event_mut, WSACOMPLETION_Event); +UNION!(WSACOMPLETION, Parameters, Apc, Apc_mut, WSACOMPLETION_Apc); +UNION!(WSACOMPLETION, Parameters, Port, Port_mut, WSACOMPLETION_Port); +pub type PWSACOMPLETION = *mut WSACOMPLETION; +pub type LPWSACOMPLETION = *mut WSACOMPLETION; +STRUCT!{struct AFPROTOCOLS { + iAddressFamily: ::INT, + iProtocol: ::INT, +}} +pub type PAFPROTOCOLS = *mut AFPROTOCOLS; +pub type LPAFPROTOCOLS = *mut AFPROTOCOLS; +ENUM!{enum WSAECOMPARATOR { + COMP_EQUAL = 0, + COMP_NOTLESS, +}} +pub type PWSAECOMPARATOR = *mut WSAECOMPARATOR; +pub type LPWSAECOMPARATOR = *mut WSAECOMPARATOR; +STRUCT!{struct WSAVERSION { + dwVersion: ::DWORD, + ecHow: WSAECOMPARATOR, +}} +pub type PWSAVERSION = *mut WSAVERSION; +pub type LPWSAVERSION = *mut WSAVERSION; +STRUCT!{struct WSAQUERYSETA { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPSTR, + lpServiceClassId: ::LPGUID, + lpVersion: LPWSAVERSION, + lpszComment: ::LPSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSETA = *mut WSAQUERYSETA; +pub type LPWSAQUERYSETA = *mut WSAQUERYSETA; +STRUCT!{struct WSAQUERYSETW { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPWSTR, + lpServiceClassId: ::LPGUID, + lpVersion: LPWSAVERSION, + lpszComment: ::LPWSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPWSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPWSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSETW = *mut WSAQUERYSETW; +pub type LPWSAQUERYSETW = *mut WSAQUERYSETW; +STRUCT!{struct WSAQUERYSET2A { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPSTR, + lpVersion: LPWSAVERSION, + lpszComment: ::LPSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSET2A = *mut WSAQUERYSET2A; +pub type LPWSAQUERYSET2A = *mut WSAQUERYSET2A; +STRUCT!{struct WSAQUERYSET2W { + dwSize: ::DWORD, + lpszServiceInstanceName: ::LPWSTR, + lpVersion: LPWSAVERSION, + lpszComment: ::LPWSTR, + dwNameSpace: ::DWORD, + lpNSProviderId: ::LPGUID, + lpszContext: ::LPWSTR, + dwNumberOfProtocols: ::DWORD, + lpafpProtocols: LPAFPROTOCOLS, + lpszQueryString: ::LPWSTR, + dwNumberOfCsAddrs: ::DWORD, + lpcsaBuffer: ::LPCSADDR_INFO, + dwOutputFlags: ::DWORD, + lpBlob: ::LPBLOB, +}} +pub type PWSAQUERYSET2W = *mut WSAQUERYSET2W; +pub type LPWSAQUERYSET2W = *mut WSAQUERYSET2W; +ENUM!{enum WSAESETSERVICEOP { + RNRSERVICE_REGISTER = 0, + RNRSERVICE_DEREGISTER, + RNRSERVICE_DELETE, +}} +pub type PWSAESETSERVICEOP = *mut WSAESETSERVICEOP; +pub type LPWSAESETSERVICEOP = *mut WSAESETSERVICEOP; +STRUCT!{struct WSANSCLASSINFOA { + lpszName: ::LPSTR, + dwNameSpace: ::DWORD, + dwValueType: ::DWORD, + dwValueSize: ::DWORD, + lpValue: ::LPVOID, +}} +pub type PWSANSCLASSINFOA = *mut WSANSCLASSINFOA; +pub type LPWSANSCLASSINFOA = *mut WSANSCLASSINFOA; +STRUCT!{struct WSANSCLASSINFOW { + lpszName: ::LPWSTR, + dwNameSpace: ::DWORD, + dwValueType: ::DWORD, + dwValueSize: ::DWORD, + lpValue: ::LPVOID, +}} +pub type PWSANSCLASSINFOW = *mut WSANSCLASSINFOW; +pub type LPWSANSCLASSINFOW = *mut WSANSCLASSINFOW; +STRUCT!{struct WSASERVICECLASSINFOA { + lpServiceClassId: ::LPGUID, + lpszServiceClassName: ::LPSTR, + dwCount: ::DWORD, + lpClassInfos: LPWSANSCLASSINFOA, +}} +pub type PWSASERVICECLASSINFOA = *mut WSASERVICECLASSINFOA; +pub type LPWSASERVICECLASSINFOA = *mut WSASERVICECLASSINFOA; +STRUCT!{struct WSASERVICECLASSINFOW { + lpServiceClassId: ::LPGUID, + lpszServiceClassName: ::LPWSTR, + dwCount: ::DWORD, + lpClassInfos: LPWSANSCLASSINFOW, +}} +pub type PWSASERVICECLASSINFOW = *mut WSASERVICECLASSINFOW; +pub type LPWSASERVICECLASSINFOW = *mut WSASERVICECLASSINFOW; +STRUCT!{struct WSANAMESPACE_INFOA { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPSTR, +}} +pub type PWSANAMESPACE_INFOA = *mut WSANAMESPACE_INFOA; +pub type LPWSANAMESPACE_INFOA = *mut WSANAMESPACE_INFOA; +STRUCT!{struct WSANAMESPACE_INFOW { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPWSTR, +}} +pub type PWSANAMESPACE_INFOW = *mut WSANAMESPACE_INFOW; +pub type LPWSANAMESPACE_INFOW = *mut WSANAMESPACE_INFOW; +STRUCT!{struct WSANAMESPACE_INFOEXA { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPSTR, + ProviderSpecific: ::BLOB, +}} +pub type PWSANAMESPACE_INFOEXA = *mut WSANAMESPACE_INFOEXA; +pub type LPWSANAMESPACE_INFOEXA = *mut WSANAMESPACE_INFOEXA; +STRUCT!{struct WSANAMESPACE_INFOEXW { + NSProviderId: ::GUID, + dwNameSpace: ::DWORD, + fActive: ::BOOL, + dwVersion: ::DWORD, + lpszIdentifier: ::LPWSTR, + ProviderSpecific: ::BLOB, +}} +pub type PWSANAMESPACE_INFOEXW = *mut WSANAMESPACE_INFOEXW; +pub type LPWSANAMESPACE_INFOEXW = *mut WSANAMESPACE_INFOEXW; +pub const POLLRDNORM: ::SHORT = 0x0100; +pub const POLLRDBAND: ::SHORT = 0x0200; +pub const POLLIN: ::SHORT = POLLRDNORM | POLLRDBAND; +pub const POLLPRI: ::SHORT = 0x0400; +pub const POLLWRNORM: ::SHORT = 0x0010; +pub const POLLOUT: ::SHORT = POLLWRNORM; +pub const POLLWRBAND: ::SHORT = 0x0020; +pub const POLLERR: ::SHORT = 0x0001; +pub const POLLHUP: ::SHORT = 0x0002; +pub const POLLNVAL: ::SHORT = 0x0004; +STRUCT!{struct WSAPOLLFD { + fd: ::SOCKET, + events: ::SHORT, + revents: ::SHORT, +}} +pub type PWSAPOLLFD = *mut WSAPOLLFD; +pub type LPWSAPOLLFD = *mut WSAPOLLFD; +pub const FIONBIO: ::c_ulong = 0x8004667e; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winspool.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winspool.rs new file mode 100644 index 0000000..eec339c --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winspool.rs @@ -0,0 +1,29 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Winspool header file +STRUCT!{struct PRINTER_DEFAULTSA { + pDataType: ::LPSTR, + pDevMode: ::LPDEVMODEA, + DesiredAccess: ::ACCESS_MASK, +}} +pub type PPRINTER_DEFAULTSA = *mut PRINTER_DEFAULTSA; +pub type LPPRINTER_DEFAULTSA = *mut PRINTER_DEFAULTSA; +STRUCT!{struct PRINTER_DEFAULTSW { + pDataType: ::LPWSTR, + pDevMode: ::LPDEVMODEW, + DesiredAccess: ::ACCESS_MASK, +}} +pub type PPRINTER_DEFAULTSW = *mut PRINTER_DEFAULTSW; +pub type LPPRINTER_DEFAULTSW = *mut PRINTER_DEFAULTSW; +STRUCT!{struct PRINTER_OPTIONSA { + cbSize: ::UINT, + dwFlags: ::DWORD, +}} +pub type PPRINTER_OPTIONSA = *mut PRINTER_OPTIONSA; +pub type LPPRINTER_OPTIONSA = *mut PRINTER_OPTIONSA; +STRUCT!{struct PRINTER_OPTIONSW { + cbSize: ::UINT, + dwFlags: ::DWORD, +}} +pub type PPRINTER_OPTIONSW = *mut PRINTER_OPTIONSW; +pub type LPPRINTER_OPTIONSW = *mut PRINTER_OPTIONSW; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winstring.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winstring.rs new file mode 100644 index 0000000..74053d4 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winstring.rs @@ -0,0 +1,3 @@ +pub type PINSPECT_HSTRING_CALLBACK = Option ::HRESULT>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winsvc.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winsvc.rs new file mode 100644 index 0000000..9351366 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winsvc.rs @@ -0,0 +1,200 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! Header file for the Service Control Manager +//80 +pub const SERVICE_NO_CHANGE: ::DWORD = 0xffffffff; +pub const SERVICE_ACTIVE: ::DWORD = 0x00000001; +pub const SERVICE_INACTIVE: ::DWORD = 0x00000002; +pub const SERVICE_STATE_ALL: ::DWORD = SERVICE_ACTIVE | SERVICE_INACTIVE; +pub const SERVICE_CONTROL_STOP: ::DWORD = 0x00000001; +pub const SERVICE_CONTROL_PAUSE: ::DWORD = 0x00000002; +pub const SERVICE_CONTROL_CONTINUE: ::DWORD = 0x00000003; +pub const SERVICE_CONTROL_INTERROGATE: ::DWORD = 0x00000004; +pub const SERVICE_CONTROL_SHUTDOWN: ::DWORD = 0x00000005; +pub const SERVICE_CONTROL_PARAMCHANGE: ::DWORD = 0x00000006; +pub const SERVICE_CONTROL_NETBINDADD: ::DWORD = 0x00000007; +pub const SERVICE_CONTROL_NETBINDREMOVE: ::DWORD = 0x00000008; +pub const SERVICE_CONTROL_NETBINDENABLE: ::DWORD = 0x00000009; +pub const SERVICE_CONTROL_NETBINDDISABLE: ::DWORD = 0x0000000A; +pub const SERVICE_CONTROL_DEVICEEVENT: ::DWORD = 0x0000000B; +pub const SERVICE_CONTROL_HARDWAREPROFILECHANGE: ::DWORD = 0x0000000C; +pub const SERVICE_CONTROL_POWEREVENT: ::DWORD = 0x0000000D; +pub const SERVICE_CONTROL_SESSIONCHANGE: ::DWORD = 0x0000000E; +pub const SERVICE_CONTROL_PRESHUTDOWN: ::DWORD = 0x0000000F; +pub const SERVICE_CONTROL_TIMECHANGE: ::DWORD = 0x00000010; +pub const SERVICE_CONTROL_TRIGGEREVENT: ::DWORD = 0x00000020; +pub const SERVICE_STOPPED: ::DWORD = 0x00000001; +pub const SERVICE_START_PENDING: ::DWORD = 0x00000002; +pub const SERVICE_STOP_PENDING: ::DWORD = 0x00000003; +pub const SERVICE_RUNNING: ::DWORD = 0x00000004; +pub const SERVICE_CONTINUE_PENDING: ::DWORD = 0x00000005; +pub const SERVICE_PAUSE_PENDING: ::DWORD = 0x00000006; +pub const SERVICE_PAUSED: ::DWORD = 0x00000007; +pub const SERVICE_ACCEPT_STOP: ::DWORD = 0x00000001; +pub const SERVICE_ACCEPT_PAUSE_CONTINUE: ::DWORD = 0x00000002; +pub const SERVICE_ACCEPT_SHUTDOWN: ::DWORD = 0x00000004; +pub const SERVICE_ACCEPT_PARAMCHANGE: ::DWORD = 0x00000008; +pub const SERVICE_ACCEPT_NETBINDCHANGE: ::DWORD = 0x00000010; +pub const SERVICE_ACCEPT_HARDWAREPROFILECHANGE: ::DWORD = 0x00000020; +pub const SERVICE_ACCEPT_POWEREVENT: ::DWORD = 0x00000040; +pub const SERVICE_ACCEPT_SESSIONCHANGE: ::DWORD = 0x00000080; +pub const SERVICE_ACCEPT_PRESHUTDOWN: ::DWORD = 0x00000100; +pub const SERVICE_ACCEPT_TIMECHANGE: ::DWORD = 0x00000200; +pub const SERVICE_ACCEPT_TRIGGEREVENT: ::DWORD = 0x00000400; +pub const SC_MANAGER_CONNECT: ::DWORD = 0x0001; +pub const SC_MANAGER_CREATE_SERVICE: ::DWORD = 0x0002; +pub const SC_MANAGER_ENUMERATE_SERVICE: ::DWORD = 0x0004; +pub const SC_MANAGER_LOCK: ::DWORD = 0x0008; +pub const SC_MANAGER_QUERY_LOCK_STATUS: ::DWORD = 0x0010; +pub const SC_MANAGER_MODIFY_BOOT_CONFIG: ::DWORD = 0x0020; +pub const SC_MANAGER_ALL_ACCESS: ::DWORD = ::STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT + | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK + | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG; +pub const SERVICE_QUERY_CONFIG: ::DWORD = 0x0001; +pub const SERVICE_CHANGE_CONFIG: ::DWORD = 0x0002; +pub const SERVICE_QUERY_STATUS: ::DWORD = 0x0004; +pub const SERVICE_ENUMERATE_DEPENDENTS: ::DWORD = 0x0008; +pub const SERVICE_START: ::DWORD = 0x0010; +pub const SERVICE_STOP: ::DWORD = 0x0020; +pub const SERVICE_PAUSE_CONTINUE: ::DWORD = 0x0040; +pub const SERVICE_INTERROGATE: ::DWORD = 0x0080; +pub const SERVICE_USER_DEFINED_CONTROL: ::DWORD = 0x0100; +pub const SERVICE_ALL_ACCESS: ::DWORD = ::STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG + | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START + | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL; +pub const SERVICE_RUNS_IN_SYSTEM_PROCESS: ::DWORD = 0x00000001; +pub const SERVICE_CONFIG_DESCRIPTION: ::DWORD = 1; +pub const SERVICE_CONFIG_FAILURE_ACTIONS: ::DWORD = 2; +pub const SERVICE_CONFIG_DELAYED_AUTO_START_INFO: ::DWORD = 3; +pub const SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: ::DWORD = 4; +pub const SERVICE_CONFIG_SERVICE_SID_INFO: ::DWORD = 5; +pub const SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO: ::DWORD = 6; +pub const SERVICE_CONFIG_PRESHUTDOWN_INFO: ::DWORD = 7; +pub const SERVICE_CONFIG_TRIGGER_INFO: ::DWORD = 8; +pub const SERVICE_CONFIG_PREFERRED_NODE: ::DWORD = 9; +pub const SERVICE_CONFIG_LAUNCH_PROTECTED: ::DWORD = 12; +pub const SERVICE_NOTIFY_STATUS_CHANGE_1: ::DWORD = 1; +pub const SERVICE_NOTIFY_STATUS_CHANGE_2: ::DWORD = 2; +pub const SERVICE_NOTIFY_STATUS_CHANGE: ::DWORD = SERVICE_NOTIFY_STATUS_CHANGE_2; +pub const SERVICE_NOTIFY_STOPPED: ::DWORD = 0x00000001; +pub const SERVICE_NOTIFY_START_PENDING: ::DWORD = 0x00000002; +pub const SERVICE_NOTIFY_STOP_PENDING: ::DWORD = 0x00000004; +pub const SERVICE_NOTIFY_RUNNING: ::DWORD = 0x00000008; +pub const SERVICE_NOTIFY_CONTINUE_PENDING: ::DWORD = 0x00000010; +pub const SERVICE_NOTIFY_PAUSE_PENDING: ::DWORD = 0x00000020; +pub const SERVICE_NOTIFY_PAUSED: ::DWORD = 0x00000040; +pub const SERVICE_NOTIFY_CREATED: ::DWORD = 0x00000080; +pub const SERVICE_NOTIFY_DELETED: ::DWORD = 0x00000100; +pub const SERVICE_NOTIFY_DELETE_PENDING: ::DWORD = 0x00000200; +pub const SERVICE_STOP_REASON_FLAG_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_FLAG_UNPLANNED: ::DWORD = 0x10000000; +pub const SERVICE_STOP_REASON_FLAG_CUSTOM: ::DWORD = 0x20000000; +pub const SERVICE_STOP_REASON_FLAG_PLANNED: ::DWORD = 0x40000000; +pub const SERVICE_STOP_REASON_FLAG_MAX: ::DWORD = 0x80000000; +pub const SERVICE_STOP_REASON_MAJOR_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_MAJOR_OTHER: ::DWORD = 0x00010000; +pub const SERVICE_STOP_REASON_MAJOR_HARDWARE: ::DWORD = 0x00020000; +pub const SERVICE_STOP_REASON_MAJOR_OPERATINGSYSTEM: ::DWORD = 0x00030000; +pub const SERVICE_STOP_REASON_MAJOR_SOFTWARE: ::DWORD = 0x00040000; +pub const SERVICE_STOP_REASON_MAJOR_APPLICATION: ::DWORD = 0x00050000; +pub const SERVICE_STOP_REASON_MAJOR_NONE: ::DWORD = 0x00060000; +pub const SERVICE_STOP_REASON_MAJOR_MAX: ::DWORD = 0x00070000; +pub const SERVICE_STOP_REASON_MAJOR_MIN_CUSTOM: ::DWORD = 0x00400000; +pub const SERVICE_STOP_REASON_MAJOR_MAX_CUSTOM: ::DWORD = 0x00ff0000; +pub const SERVICE_STOP_REASON_MINOR_MIN: ::DWORD = 0x00000000; +pub const SERVICE_STOP_REASON_MINOR_OTHER: ::DWORD = 0x00000001; +pub const SERVICE_STOP_REASON_MINOR_MAINTENANCE: ::DWORD = 0x00000002; +pub const SERVICE_STOP_REASON_MINOR_INSTALLATION: ::DWORD = 0x00000003; +pub const SERVICE_STOP_REASON_MINOR_UPGRADE: ::DWORD = 0x00000004; +pub const SERVICE_STOP_REASON_MINOR_RECONFIG: ::DWORD = 0x00000005; +pub const SERVICE_STOP_REASON_MINOR_HUNG: ::DWORD = 0x00000006; +pub const SERVICE_STOP_REASON_MINOR_UNSTABLE: ::DWORD = 0x00000007; +pub const SERVICE_STOP_REASON_MINOR_DISK: ::DWORD = 0x00000008; +pub const SERVICE_STOP_REASON_MINOR_NETWORKCARD: ::DWORD = 0x00000009; +pub const SERVICE_STOP_REASON_MINOR_ENVIRONMENT: ::DWORD = 0x0000000a; +pub const SERVICE_STOP_REASON_MINOR_HARDWARE_DRIVER: ::DWORD = 0x0000000b; +pub const SERVICE_STOP_REASON_MINOR_OTHERDRIVER: ::DWORD = 0x0000000c; +pub const SERVICE_STOP_REASON_MINOR_SERVICEPACK: ::DWORD = 0x0000000d; +pub const SERVICE_STOP_REASON_MINOR_SOFTWARE_UPDATE: ::DWORD = 0x0000000e; +pub const SERVICE_STOP_REASON_MINOR_SECURITYFIX: ::DWORD = 0x0000000f; +pub const SERVICE_STOP_REASON_MINOR_SECURITY: ::DWORD = 0x00000010; +pub const SERVICE_STOP_REASON_MINOR_NETWORK_CONNECTIVITY: ::DWORD = 0x00000011; +pub const SERVICE_STOP_REASON_MINOR_WMI: ::DWORD = 0x00000012; +pub const SERVICE_STOP_REASON_MINOR_SERVICEPACK_UNINSTALL: ::DWORD = 0x00000013; +pub const SERVICE_STOP_REASON_MINOR_SOFTWARE_UPDATE_UNINSTALL: ::DWORD = 0x00000014; +pub const SERVICE_STOP_REASON_MINOR_SECURITYFIX_UNINSTALL: ::DWORD = 0x00000015; +pub const SERVICE_STOP_REASON_MINOR_MMC: ::DWORD = 0x00000016; +pub const SERVICE_STOP_REASON_MINOR_NONE: ::DWORD = 0x00000017; +pub const SERVICE_STOP_REASON_MINOR_MAX: ::DWORD = 0x00000018; +pub const SERVICE_STOP_REASON_MINOR_MIN_CUSTOM: ::DWORD = 0x00000100; +pub const SERVICE_STOP_REASON_MINOR_MAX_CUSTOM: ::DWORD = 0x0000FFFF; +pub const SERVICE_CONTROL_STATUS_REASON_INFO: ::DWORD = 1; +pub const SERVICE_SID_TYPE_NONE: ::DWORD = 0x00000000; +pub const SERVICE_SID_TYPE_UNRESTRICTED: ::DWORD = 0x00000001; +pub const SERVICE_SID_TYPE_RESTRICTED: ::DWORD = 0x00000002 | SERVICE_SID_TYPE_UNRESTRICTED; +pub const SERVICE_TRIGGER_TYPE_DEVICE_INTERFACE_ARRIVAL: ::DWORD = 1; +pub const SERVICE_TRIGGER_TYPE_IP_ADDRESS_AVAILABILITY: ::DWORD = 2; +pub const SERVICE_TRIGGER_TYPE_DOMAIN_JOIN: ::DWORD = 3; +pub const SERVICE_TRIGGER_TYPE_FIREWALL_PORT_EVENT: ::DWORD = 4; +pub const SERVICE_TRIGGER_TYPE_GROUP_POLICY: ::DWORD = 5; +pub const SERVICE_TRIGGER_TYPE_NETWORK_ENDPOINT: ::DWORD = 6; +pub const SERVICE_TRIGGER_TYPE_CUSTOM_SYSTEM_STATE_CHANGE: ::DWORD = 7; +pub const SERVICE_TRIGGER_TYPE_CUSTOM: ::DWORD = 20; +pub const SERVICE_TRIGGER_DATA_TYPE_BINARY: ::DWORD = 1; +pub const SERVICE_TRIGGER_DATA_TYPE_STRING: ::DWORD = 2; +pub const SERVICE_TRIGGER_DATA_TYPE_LEVEL: ::DWORD = 3; +pub const SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ANY: ::DWORD = 4; +pub const SERVICE_TRIGGER_DATA_TYPE_KEYWORD_ALL: ::DWORD = 5; +pub const SERVICE_START_REASON_DEMAND: ::DWORD = 0x00000001; +pub const SERVICE_START_REASON_AUTO: ::DWORD = 0x00000002; +pub const SERVICE_START_REASON_TRIGGER: ::DWORD = 0x00000004; +pub const SERVICE_START_REASON_RESTART_ON_FAILURE: ::DWORD = 0x00000008; +pub const SERVICE_START_REASON_DELAYEDAUTO: ::DWORD = 0x00000010; +pub const SERVICE_DYNAMIC_INFORMATION_LEVEL_START_REASON: ::DWORD = 1; +pub const SERVICE_LAUNCH_PROTECTED_NONE: ::DWORD = 0; +pub const SERVICE_LAUNCH_PROTECTED_WINDOWS: ::DWORD = 1; +pub const SERVICE_LAUNCH_PROTECTED_WINDOWS_LIGHT: ::DWORD = 2; +pub const SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT: ::DWORD = 3; +//678 +DECLARE_HANDLE!(SC_HANDLE, SC_HANDLE__); +pub type LPSC_HANDLE = *mut SC_HANDLE; +DECLARE_HANDLE!(SERVICE_STATUS_HANDLE, SERVICE_STATUS_HANDLE__); +ENUM!{enum SC_STATUS_TYPE { + SC_STATUS_PROCESS_INFO = 0, +}} +ENUM!{enum _SC_ENUM_TYPE { + SC_ENUM_PROCESS_INFO = 0, +}} +//700 +STRUCT!{struct SERVICE_STATUS { + dwServiceType: ::DWORD, + dwCurrentState: ::DWORD, + dwControlsAccepted: ::DWORD, + dwWin32ExitCode: ::DWORD, + dwServiceSpecificExitCode: ::DWORD, + dwCheckPoint: ::DWORD, + dwWaitHint: ::DWORD, +}} +pub type LPSERVICE_STATUS = *mut SERVICE_STATUS; +//848 +pub type LPSERVICE_MAIN_FUNCTIONW = Option; +pub type LPSERVICE_MAIN_FUNCTIONA = Option; +STRUCT!{nodebug struct SERVICE_TABLE_ENTRYA { + lpServiceName: ::LPCSTR, + lpServiceProc: LPSERVICE_MAIN_FUNCTIONA, +}} +pub type LPSERVICE_TABLE_ENTRYA = *mut SERVICE_TABLE_ENTRYA; +STRUCT!{nodebug struct SERVICE_TABLE_ENTRYW { + lpServiceName: ::LPCWSTR, + lpServiceProc: LPSERVICE_MAIN_FUNCTIONW, +}} +pub type LPSERVICE_TABLE_ENTRYW = *mut SERVICE_TABLE_ENTRYW; +//900 +pub type LPHANDLER_FUNCTION = Option; +pub type LPHANDLER_FUNCTION_EX = Option ::DWORD>; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winusb.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winusb.rs new file mode 100644 index 0000000..2fbb619 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winusb.rs @@ -0,0 +1,33 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License +//! FFI bindings to winusb. +pub type WINUSB_INTERFACE_HANDLE = ::PVOID; +pub type PWINUSB_INTERFACE_HANDLE = *mut ::PVOID; +pub type WINUSB_ISOCH_BUFFER_HANDLE = ::PVOID; +pub type PWINUSB_ISOCH_BUFFER_HANDLE = *mut ::PVOID; +STRUCT!{#[repr(packed)] struct WINUSB_SETUP_PACKET { + RequestType: ::UCHAR, + Request: ::UCHAR, + Value: ::USHORT, + Index: ::USHORT, + Length: ::USHORT, +}} +pub type PWINUSB_SETUP_PACKET = *mut WINUSB_SETUP_PACKET; + +STRUCT!{struct USB_INTERFACE_DESCRIPTOR { + bLength: ::UCHAR, + bDescriptorType: ::UCHAR, + bInterfaceNumber: ::UCHAR, + bAlternateSetting: ::UCHAR, + bNumEndpoints: ::UCHAR, + bInterfaceClass: ::UCHAR, + bInterfaceSubClass: ::UCHAR, + bInterfaceProtocol: ::UCHAR, + iInterface: ::UCHAR, +}} +pub type PUSB_INTERFACE_DESCRIPTOR = *mut USB_INTERFACE_DESCRIPTOR; +#[test] +fn test_USB_INTERFACE_DESCRIPTOR_size() { + use std::mem::size_of; + assert_eq!(size_of::(), 9) +} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winusbio.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winusbio.rs new file mode 100644 index 0000000..3dedf22 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winusbio.rs @@ -0,0 +1,18 @@ +// Copyright © 2016, bitbegin +// Licensed under the MIT License +//! USBIO Definitions. +STRUCT!{struct WINUSB_PIPE_INFORMATION { + PipeType: ::USBD_PIPE_TYPE, + PipeId: ::UCHAR, + MaximumPacketSize: ::USHORT, + Interval: ::UCHAR, +}} +pub type PWINUSB_PIPE_INFORMATION = *mut WINUSB_PIPE_INFORMATION; +STRUCT!{struct WINUSB_PIPE_INFORMATION_EX { + PipeType: ::USBD_PIPE_TYPE, + PipeId: ::UCHAR, + MaximumPacketSize: ::USHORT, + Interval: ::UCHAR, + MaximumBytesPerInterval: ::ULONG, +}} +pub type PWINUSB_PIPE_INFORMATION_EX = *mut WINUSB_PIPE_INFORMATION_EX; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/winuser.rs b/third_party/cargo/vendor/winapi-0.2.8/src/winuser.rs new file mode 100644 index 0000000..5769489 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/winuser.rs @@ -0,0 +1,2334 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! USER procedure declarations, constant definitions and macros + +// Edit Control Styles +// +pub const ES_LEFT: ::DWORD = 0x0000; +pub const ES_CENTER: ::DWORD = 0x0001; +pub const ES_RIGHT: ::DWORD = 0x0002; +pub const ES_MULTILINE: ::DWORD = 0x0004; +pub const ES_UPPERCASE: ::DWORD = 0x0008; +pub const ES_LOWERCASE: ::DWORD = 0x0010; +pub const ES_PASSWORD: ::DWORD = 0x0020; +pub const ES_AUTOVSCROLL: ::DWORD = 0x0040; +pub const ES_AUTOHSCROLL: ::DWORD = 0x0080; +pub const ES_NOHIDESEL: ::DWORD = 0x0100; +pub const ES_OEMCONVERT: ::DWORD = 0x0400; +pub const ES_READONLY: ::DWORD = 0x0800; +pub const ES_WANTRETURN: ::DWORD = 0x1000; +pub const ES_NUMBER: ::DWORD = 0x2000; + +// Edit Control Notification Codes +// +pub const EN_SETFOCUS: ::WORD = 0x0100; +pub const EN_KILLFOCUS: ::WORD = 0x0200; +pub const EN_CHANGE: ::WORD = 0x0300; +pub const EN_UPDATE: ::WORD = 0x0400; +pub const EN_ERRSPACE: ::WORD = 0x0500; +pub const EN_MAXTEXT: ::WORD = 0x0501; +pub const EN_HSCROLL: ::WORD = 0x0601; +pub const EN_VSCROLL: ::WORD = 0x0602; + +pub const EN_ALIGN_LTR_EC: ::WORD = 0x0700; +pub const EN_ALIGN_RTL_EC: ::WORD = 0x0701; + +// Edit control EM_SETMARGIN parameters +pub const EC_LEFTMARGIN: ::WORD = 0x0001; +pub const EC_RIGHTMARGIN: ::WORD = 0x0002; +pub const EC_USEFONTINFO: ::WORD = 0xffff; + +// wParam of EM_GET/SETIMESTATUS +pub const EMSIS_COMPOSITIONSTRING: ::WORD = 0x0001; + +// lParam for EMSIS_COMPOSITIONSTRING +pub const EIMES_GETCOMPSTRATONCE: ::WORD = 0x0001; +pub const EIMES_CANCELCOMPSTRINFOCUS: ::WORD = 0x0002; +pub const EIMES_COMPLETECOMPSTRKILLFOCUS: ::WORD = 0x0004; + +// Edit Control Messages +// +pub const EM_GETSEL: ::WORD = 0x00B0; +pub const EM_SETSEL: ::WORD = 0x00B1; +pub const EM_GETRECT: ::WORD = 0x00B2; +pub const EM_SETRECT: ::WORD = 0x00B3; +pub const EM_SETRECTNP: ::WORD = 0x00B4; +pub const EM_SCROLL: ::WORD = 0x00B5; +pub const EM_LINESCROLL: ::WORD = 0x00B6; +pub const EM_SCROLLCARET: ::WORD = 0x00B7; +pub const EM_GETMODIFY: ::WORD = 0x00B8; +pub const EM_SETMODIFY: ::WORD = 0x00B9; +pub const EM_GETLINECOUNT: ::WORD = 0x00BA; +pub const EM_LINEINDEX: ::WORD = 0x00BB; +pub const EM_SETHANDLE: ::WORD = 0x00BC; +pub const EM_GETHANDLE: ::WORD = 0x00BD; +pub const EM_GETTHUMB: ::WORD = 0x00BE; +pub const EM_LINELENGTH: ::WORD = 0x00C1; +pub const EM_REPLACESEL: ::WORD = 0x00C2; +pub const EM_GETLINE: ::WORD = 0x00C4; +pub const EM_LIMITTEXT: ::WORD = 0x00C5; +pub const EM_CANUNDO: ::WORD = 0x00C6; +pub const EM_UNDO: ::WORD = 0x00C7; +pub const EM_FMTLINES: ::WORD = 0x00C8; +pub const EM_LINEFROMCHAR: ::WORD = 0x00C9; +pub const EM_SETTABSTOPS: ::WORD = 0x00CB; +pub const EM_SETPASSWORDCHAR: ::WORD = 0x00CC; +pub const EM_EMPTYUNDOBUFFER: ::WORD = 0x00CD; +pub const EM_GETFIRSTVISIBLELINE: ::WORD = 0x00CE; +pub const EM_SETREADONLY: ::WORD = 0x00CF; +pub const EM_SETWORDBREAKPROC: ::WORD = 0x00D0; +pub const EM_GETWORDBREAKPROC: ::WORD = 0x00D1; +pub const EM_GETPASSWORDCHAR: ::WORD = 0x00D2; + +pub const EM_SETMARGINS: ::WORD = 0x00D3; +pub const EM_GETMARGINS: ::WORD = 0x00D4; +pub const EM_SETLIMITTEXT: ::WORD = EM_LIMITTEXT; +pub const EM_GETLIMITTEXT: ::WORD = 0x00D5; +pub const EM_POSFROMCHAR: ::WORD = 0x00D6; +pub const EM_CHARFROMPOS: ::WORD = 0x00D7; + +pub const EM_SETIMESTATUS: ::WORD = 0x00D8; +pub const EM_GETIMESTATUS: ::WORD = 0x00D9; + +// EDITWORDBREAKPROC code values +// +pub const WB_LEFT: ::WORD = 0; +pub const WB_RIGHT: ::WORD = 1; +pub const WB_ISDELIMITER: ::WORD = 2; + +pub const BN_CLICKED: ::WORD = 0; +pub const BN_PAINT: ::WORD = 1; +pub const BN_HILITE: ::WORD = 2; +pub const BN_UNHILITE: ::WORD = 3; +pub const BN_DISABLE: ::WORD = 4; +pub const BN_DOUBLECLICKED: ::WORD = 5; +pub const BN_PUSHED: ::WORD = BN_HILITE; +pub const BN_UNPUSHED: ::WORD = BN_UNHILITE; +pub const BN_DBLCLK: ::WORD = BN_DOUBLECLICKED; +pub const BN_SETFOCUS: ::WORD = 6; +pub const BN_KILLFOCUS: ::WORD = 7; +pub const BS_PUSHBUTTON: ::DWORD = 0x00000000; +pub const BS_DEFPUSHBUTTON: ::DWORD = 0x00000001; +pub const BS_CHECKBOX: ::DWORD = 0x00000002; +pub const BS_AUTOCHECKBOX: ::DWORD = 0x00000003; +pub const BS_RADIOBUTTON: ::DWORD = 0x00000004; +pub const BS_3STATE: ::DWORD = 0x00000005; +pub const BS_AUTO3STATE: ::DWORD = 0x00000006; +pub const BS_GROUPBOX: ::DWORD = 0x00000007; +pub const BS_USERBUTTON: ::DWORD = 0x00000008; +pub const BS_AUTORADIOBUTTON: ::DWORD = 0x00000009; +pub const BS_PUSHBOX: ::DWORD = 0x0000000A; +pub const BS_OWNERDRAW: ::DWORD = 0x0000000B; +pub const BS_TYPEMASK: ::DWORD = 0x0000000F; +pub const BS_LEFTTEXT: ::DWORD = 0x00000020; +pub const BS_TEXT: ::DWORD = 0x00000000; +pub const BS_ICON: ::DWORD = 0x00000040; +pub const BS_BITMAP: ::DWORD = 0x00000080; +pub const BS_LEFT: ::DWORD = 0x00000100; +pub const BS_RIGHT: ::DWORD = 0x00000200; +pub const BS_CENTER: ::DWORD = 0x00000300; +pub const BS_TOP: ::DWORD = 0x00000400; +pub const BS_BOTTOM: ::DWORD = 0x00000800; +pub const BS_VCENTER: ::DWORD = 0x00000C00; +pub const BS_PUSHLIKE: ::DWORD = 0x00001000; +pub const BS_MULTILINE: ::DWORD = 0x00002000; +pub const BS_NOTIFY: ::DWORD = 0x00004000; +pub const BS_FLAT: ::DWORD = 0x00008000; +pub const BS_RIGHTBUTTON: ::DWORD = BS_LEFTTEXT; +pub const CCHILDREN_SCROLLBAR: usize = 5; +pub const CDS_UPDATEREGISTRY: ::DWORD = 0x00000001; +pub const CDS_TEST: ::DWORD = 0x00000002; +pub const CDS_FULLSCREEN: ::DWORD = 0x00000004; +pub const CDS_GLOBAL: ::DWORD = 0x00000008; +pub const CDS_SET_PRIMARY: ::DWORD = 0x00000010; +pub const CDS_VIDEOPARAMETERS: ::DWORD = 0x00000020; +pub const CDS_ENABLE_UNSAFE_MODES: ::DWORD = 0x00000100; +pub const CDS_DISABLE_UNSAFE_MODES: ::DWORD = 0x00000200; +pub const CDS_RESET: ::DWORD = 0x40000000; +pub const CDS_RESET_EX: ::DWORD = 0x20000000; +pub const CDS_NORESET: ::DWORD = 0x10000000; +pub const CF_TEXT: ::UINT = 1; +pub const CF_BITMAP: ::UINT = 2; +pub const CF_METAFILEPICT: ::UINT = 3; +pub const CF_SYLK: ::UINT = 4; +pub const CF_DIF: ::UINT = 5; +pub const CF_TIFF: ::UINT = 6; +pub const CF_OEMTEXT: ::UINT = 7; +pub const CF_DIB: ::UINT = 8; +pub const CF_PALETTE: ::UINT = 9; +pub const CF_PENDATA: ::UINT = 10; +pub const CF_RIFF: ::UINT = 11; +pub const CF_WAVE: ::UINT = 12; +pub const CF_UNICODETEXT: ::UINT = 13; +pub const CF_ENHMETAFILE: ::UINT = 14; +pub const CF_HDROP: ::UINT = 15; +pub const CF_LOCALE: ::UINT = 16; +pub const CF_DIBV5: ::UINT = 17; +pub const CF_OWNERDISPLAY: ::UINT = 0x0080; +pub const CF_DSPTEXT: ::UINT = 0x0081; +pub const CF_DSPBITMAP: ::UINT = 0x0082; +pub const CF_DSPENHMETAFILE: ::UINT = 0x008E; +pub const CF_DSPMETAFILEPICT: ::UINT = 0x0083; +pub const CF_PRIVATEFIRST: ::UINT = 0x0200; +pub const CF_PRIVATELAST: ::UINT = 0x02FF; +pub const CF_GDIOBJFIRST: ::UINT = 0x0300; +pub const CF_GDIOBJLAST: ::UINT = 0x03FF; +pub const CS_VREDRAW: ::DWORD = 0x0001; +pub const CS_HREDRAW: ::DWORD = 0x0002; +pub const CS_DBLCLKS: ::DWORD = 0x0008; +pub const CS_OWNDC: ::DWORD = 0x0020; +pub const CS_CLASSDC: ::DWORD = 0x0040; +pub const CS_PARENTDC: ::DWORD = 0x0080; +pub const CS_NOCLOSE: ::DWORD = 0x0200; +pub const CS_SAVEBITS: ::DWORD = 0x0800; +pub const CS_BYTEALIGNCLIENT: ::DWORD = 0x1000; +pub const CS_BYTEALIGNWINDOW: ::DWORD = 0x2000; +pub const CS_GLOBALCLASS: ::DWORD = 0x4000; +pub const CS_IME: ::DWORD = 0x00010000; +pub const CS_DROPSHADOW: ::DWORD = 0x00020000; +pub const DFC_CAPTION: ::UINT = 1; +pub const DFC_MENU: ::UINT = 2; +pub const DFC_SCROLL: ::UINT = 3; +pub const DFC_BUTTON: ::UINT = 4; +pub const DFCS_CAPTIONCLOSE: ::UINT = 0x0000; +pub const DFCS_CAPTIONMIN: ::UINT = 0x0001; +pub const DFCS_CAPTIONMAX: ::UINT = 0x0002; +pub const DFCS_CAPTIONRESTORE: ::UINT = 0x0003; +pub const DFCS_CAPTIONHELP: ::UINT = 0x0004; +pub const DFCS_MENUARROW: ::UINT = 0x0000; +pub const DFCS_MENUCHECK: ::UINT = 0x0001; +pub const DFCS_MENUBULLET: ::UINT = 0x0002; +pub const DFCS_MENUARROWRIGHT: ::UINT = 0x0004; +pub const DFCS_SCROLLUP: ::UINT = 0x0000; +pub const DFCS_SCROLLDOWN: ::UINT = 0x0001; +pub const DFCS_SCROLLLEFT: ::UINT = 0x0002; +pub const DFCS_SCROLLRIGHT: ::UINT = 0x0003; +pub const DFCS_SCROLLCOMBOBOX: ::UINT = 0x0005; +pub const DFCS_SCROLLSIZEGRIP: ::UINT = 0x0008; +pub const DFCS_SCROLLSIZEGRIPRIGHT: ::UINT = 0x0010; +pub const DFCS_BUTTONCHECK: ::UINT = 0x0000; +pub const DFCS_BUTTONRADIOIMAGE: ::UINT = 0x0001; +pub const DFCS_BUTTONRADIOMASK: ::UINT = 0x0002; +pub const DFCS_BUTTONRADIO: ::UINT = 0x0004; +pub const DFCS_BUTTON3STATE: ::UINT = 0x0008; +pub const DFCS_BUTTONPUSH: ::UINT = 0x0010; +pub const DFCS_INACTIVE: ::UINT = 0x0100; +pub const DFCS_PUSHED: ::UINT = 0x0200; +pub const DFCS_CHECKED: ::UINT = 0x0400; +// if WINVER >= 0x0500 +pub const DFCS_TRANSPARENT: ::UINT = 0x0800; +pub const DFCS_HOT: ::UINT = 0x1000; +// end if WINVER >= 0x0500 +pub const DFCS_ADJUSTRECT: ::UINT = 0x2000; +pub const DFCS_FLAT: ::UINT = 0x4000; +pub const DFCS_MONO: ::UINT = 0x8000; +pub const CW_USEDEFAULT: ::c_int = 0x80000000u32 as ::c_int; +pub const DISP_CHANGE_SUCCESSFUL: ::LONG = 0; +pub const DISP_CHANGE_RESTART: ::LONG = 1; +pub const DISP_CHANGE_FAILED: ::LONG = -1; +pub const DISP_CHANGE_BADMODE: ::LONG = -2; +pub const DISP_CHANGE_NOTUPDATED: ::LONG = -3; +pub const DISP_CHANGE_BADFLAGS: ::LONG = -4; +pub const DISP_CHANGE_BADPARAM: ::LONG = -5; +pub const DISP_CHANGE_BADDUALVIEW: ::LONG = -6; +pub const EDD_GET_DEVICE_INTERFACE_NAME: ::DWORD = 0x00000001; +pub const ENUM_CURRENT_SETTINGS: ::DWORD = 0xFFFFFFFF; +pub const ENUM_REGISTRY_SETTINGS: ::DWORD = 0xFFFFFFFE; +pub const GW_HWNDFIRST: ::UINT = 0; +pub const GW_HWNDLAST: ::UINT = 1; +pub const GW_HWNDNEXT: ::UINT = 2; +pub const GW_HWNDPREV: ::UINT = 3; +pub const GW_OWNER: ::UINT = 4; +pub const GW_CHILD: ::UINT = 5; +pub const GW_ENABLEDPOPUP: ::UINT = 6; +pub const GW_MAX: ::UINT = 6; +pub const HTERROR: ::c_int = -2; +pub const HTTRANSPARENT: ::c_int = -1; +pub const HTNOWHERE: ::c_int = 0; +pub const HTCLIENT: ::c_int = 1; +pub const HTCAPTION: ::c_int = 2; +pub const HTSYSMENU: ::c_int = 3; +pub const HTGROWBOX: ::c_int = 4; +pub const HTSIZE: ::c_int = HTGROWBOX; +pub const HTMENU: ::c_int = 5; +pub const HTHSCROLL: ::c_int = 6; +pub const HTVSCROLL: ::c_int = 7; +pub const HTMINBUTTON: ::c_int = 8; +pub const HTMAXBUTTON: ::c_int = 9; +pub const HTLEFT: ::c_int = 10; +pub const HTRIGHT: ::c_int = 11; +pub const HTTOP: ::c_int = 12; +pub const HTTOPLEFT: ::c_int = 13; +pub const HTTOPRIGHT: ::c_int = 14; +pub const HTBOTTOM: ::c_int = 15; +pub const HTBOTTOMLEFT: ::c_int = 16; +pub const HTBOTTOMRIGHT: ::c_int = 17; +pub const HTBORDER: ::c_int = 18; +pub const HTREDUCE: ::c_int = HTMINBUTTON; +pub const HTZOOM: ::c_int = HTMAXBUTTON; +pub const HTSIZEFIRST: ::c_int = HTLEFT; +pub const HTSIZELAST: ::c_int = HTBOTTOMRIGHT; +pub const HTOBJECT: ::c_int = 19; +pub const HTCLOSE: ::c_int = 20; +pub const HTHELP: ::c_int = 21; +pub const LSFW_LOCK: ::UINT = 1; +pub const LSFW_UNLOCK: ::UINT = 2; +pub const MDITILE_VERTICAL: ::UINT = 0x0000; +pub const MDITILE_HORIZONTAL: ::UINT = 0x0001; +pub const MDITILE_SKIPDISABLED: ::UINT = 0x0002; +pub const MDITILE_ZORDER: ::UINT = 0x0004; +pub const MB_OK: ::DWORD = 0x00000000; +pub const MB_OKCANCEL: ::DWORD = 0x00000001; +pub const MB_ABORTRETRYIGNORE: ::DWORD = 0x00000002; +pub const MB_YESNOCANCEL: ::DWORD = 0x00000003; +pub const MB_YESNO: ::DWORD = 0x00000004; +pub const MB_RETRYCANCEL: ::DWORD = 0x00000005; +pub const MB_CANCELTRYCONTINUE: ::DWORD = 0x00000006; +pub const MB_ICONHAND: ::DWORD = 0x00000010; +pub const MB_ICONQUESTION: ::DWORD = 0x00000020; +pub const MB_ICONEXCLAMATION: ::DWORD = 0x00000030; +pub const MB_ICONASTERISK: ::DWORD = 0x00000040; +pub const MB_USERICON: ::DWORD = 0x00000080; +pub const MB_ICONWARNING: ::DWORD = MB_ICONEXCLAMATION; +pub const MB_ICONERROR: ::DWORD = MB_ICONHAND; +pub const MB_ICONINFORMATION: ::DWORD = MB_ICONASTERISK; +pub const MB_ICONSTOP: ::DWORD = MB_ICONHAND; +pub const MB_DEFBUTTON1: ::DWORD = 0x00000000; +pub const MB_DEFBUTTON2: ::DWORD = 0x00000100; +pub const MB_DEFBUTTON3: ::DWORD = 0x00000200; +pub const MB_DEFBUTTON4: ::DWORD = 0x00000300; +pub const MB_APPLMODAL: ::DWORD = 0x00000000; +pub const MB_SYSTEMMODAL: ::DWORD = 0x00001000; +pub const MB_TASKMODAL: ::DWORD = 0x00002000; +pub const MB_HELP: ::DWORD = 0x00004000; +pub const MB_NOFOCUS: ::DWORD = 0x00008000; +pub const MB_SETFOREGROUND: ::DWORD = 0x00010000; +pub const MB_DEFAULT_DESKTOP_ONLY: ::DWORD = 0x00020000; +pub const MB_TOPMOST: ::DWORD = 0x00040000; +pub const MB_RIGHT: ::DWORD = 0x00080000; +pub const MB_RTLREADING: ::DWORD = 0x00100000; +pub const MB_SERVICE_NOTIFICATION: ::DWORD = 0x00200000; +pub const MB_SERVICE_NOTIFICATION_NT3X: ::DWORD = 0x00040000; +pub const MB_TYPEMASK: ::DWORD = 0x0000000F; +pub const MB_ICONMASK: ::DWORD = 0x000000F0; +pub const MB_DEFMASK: ::DWORD = 0x00000F00; +pub const MB_MODEMASK: ::DWORD = 0x00003000; +pub const MB_MISCMASK: ::DWORD = 0x0000C000; +pub const MF_BITMAP: ::UINT = 0x00000004; +pub const MF_CHECKED: ::UINT = 0x00000008; +pub const MF_DISABLED: ::UINT = 0x00000002; +pub const MF_ENABLED: ::UINT = 0x00000000; +pub const MF_GRAYED: ::UINT = 0x00000001; +pub const MF_MENUBARBREAK: ::UINT = 0x00000020; +pub const MF_MENUBREAK: ::UINT = 0x00000040; +pub const MF_OWNERDRAW: ::UINT = 0x00000100; +pub const MF_POPUP: ::UINT = 0x00000010; +pub const MF_SEPARATOR: ::UINT = 0x00000800; +pub const MF_STRING: ::UINT = 0x00000000; +pub const MF_UNCHECKED: ::UINT = 0x00000000; +pub const SB_HORZ: ::c_int = 0; +pub const SB_VERT: ::c_int = 1; +pub const SB_CTL: ::c_int = 2; +pub const SB_BOTH: ::c_int = 3; +pub const SW_HIDE: ::c_int = 0; +pub const SW_SHOWNORMAL: ::c_int = 1; +pub const SW_NORMAL: ::c_int = 1; +pub const SW_SHOWMINIMIZED: ::c_int = 2; +pub const SW_SHOWMAXIMIZED: ::c_int = 3; +pub const SW_MAXIMIZE: ::c_int = 3; +pub const SW_SHOWNOACTIVATE: ::c_int = 4; +pub const SW_SHOW: ::c_int = 5; +pub const SW_MINIMIZE: ::c_int = 6; +pub const SW_SHOWMINNOACTIVE: ::c_int = 7; +pub const SW_SHOWNA: ::c_int = 8; +pub const SW_RESTORE: ::c_int = 9; +pub const SW_SHOWDEFAULT: ::c_int = 10; +pub const SW_FORCEMINIMIZE: ::c_int = 11; +pub const SW_MAX: ::c_int = 11; +pub const SWP_NOSIZE: ::UINT = 0x0001; +pub const SWP_NOMOVE: ::UINT = 0x0002; +pub const SWP_NOZORDER: ::UINT = 0x0004; +pub const SWP_NOREDRAW: ::UINT = 0x0008; +pub const SWP_NOACTIVATE: ::UINT = 0x0010; +pub const SWP_FRAMECHANGED: ::UINT = 0x0020; +pub const SWP_SHOWWINDOW: ::UINT = 0x0040; +pub const SWP_HIDEWINDOW: ::UINT = 0x0080; +pub const SWP_NOCOPYBITS: ::UINT = 0x0100; +pub const SWP_NOOWNERZORDER: ::UINT = 0x0200; +pub const SWP_NOSENDCHANGING: ::UINT = 0x0400; +pub const SWP_DRAWFRAME: ::UINT = SWP_FRAMECHANGED; +pub const SWP_NOREPOSITION: ::UINT = SWP_NOOWNERZORDER; +pub const SWP_DEFERERASE: ::UINT = 0x2000; +pub const SWP_ASYNCWINDOWPOS: ::UINT = 0x4000; +pub const VK_LBUTTON: ::c_int = 0x01; +pub const VK_RBUTTON: ::c_int = 0x02; +pub const VK_CANCEL: ::c_int = 0x03; +pub const VK_MBUTTON: ::c_int = 0x04; +pub const VK_XBUTTON1: ::c_int = 0x05; +pub const VK_XBUTTON2: ::c_int = 0x06; +pub const VK_BACK: ::c_int = 0x08; +pub const VK_TAB: ::c_int = 0x09; +pub const VK_CLEAR: ::c_int = 0x0C; +pub const VK_RETURN: ::c_int = 0x0D; +pub const VK_SHIFT: ::c_int = 0x10; +pub const VK_CONTROL: ::c_int = 0x11; +pub const VK_MENU: ::c_int = 0x12; +pub const VK_PAUSE: ::c_int = 0x13; +pub const VK_CAPITAL: ::c_int = 0x14; +pub const VK_KANA: ::c_int = 0x15; +pub const VK_HANGUEL: ::c_int = 0x15; +pub const VK_HANGUL: ::c_int = 0x15; +pub const VK_JUNJA: ::c_int = 0x17; +pub const VK_FINAL: ::c_int = 0x18; +pub const VK_HANJA: ::c_int = 0x19; +pub const VK_KANJI: ::c_int = 0x19; +pub const VK_ESCAPE: ::c_int = 0x1B; +pub const VK_CONVERT: ::c_int = 0x1C; +pub const VK_NONCONVERT: ::c_int = 0x1D; +pub const VK_ACCEPT: ::c_int = 0x1E; +pub const VK_MODECHANGE: ::c_int = 0x1F; +pub const VK_SPACE: ::c_int = 0x20; +pub const VK_PRIOR: ::c_int = 0x21; +pub const VK_NEXT: ::c_int = 0x22; +pub const VK_END: ::c_int = 0x23; +pub const VK_HOME: ::c_int = 0x24; +pub const VK_LEFT: ::c_int = 0x25; +pub const VK_UP: ::c_int = 0x26; +pub const VK_RIGHT: ::c_int = 0x27; +pub const VK_DOWN: ::c_int = 0x28; +pub const VK_SELECT: ::c_int = 0x29; +pub const VK_PRINT: ::c_int = 0x2A; +pub const VK_EXECUTE: ::c_int = 0x2B; +pub const VK_SNAPSHOT: ::c_int = 0x2C; +pub const VK_INSERT: ::c_int = 0x2D; +pub const VK_DELETE: ::c_int = 0x2E; +pub const VK_HELP: ::c_int = 0x2F; +pub const VK_LWIN: ::c_int = 0x5B; +pub const VK_RWIN: ::c_int = 0x5C; +pub const VK_APPS: ::c_int = 0x5D; +pub const VK_SLEEP: ::c_int = 0x5F; +pub const VK_NUMPAD0: ::c_int = 0x60; +pub const VK_NUMPAD1: ::c_int = 0x61; +pub const VK_NUMPAD2: ::c_int = 0x62; +pub const VK_NUMPAD3: ::c_int = 0x63; +pub const VK_NUMPAD4: ::c_int = 0x64; +pub const VK_NUMPAD5: ::c_int = 0x65; +pub const VK_NUMPAD6: ::c_int = 0x66; +pub const VK_NUMPAD7: ::c_int = 0x67; +pub const VK_NUMPAD8: ::c_int = 0x68; +pub const VK_NUMPAD9: ::c_int = 0x69; +pub const VK_MULTIPLY: ::c_int = 0x6A; +pub const VK_ADD: ::c_int = 0x6B; +pub const VK_SEPARATOR: ::c_int = 0x6C; +pub const VK_SUBTRACT: ::c_int = 0x6D; +pub const VK_DECIMAL: ::c_int = 0x6E; +pub const VK_DIVIDE: ::c_int = 0x6F; +pub const VK_F1: ::c_int = 0x70; +pub const VK_F2: ::c_int = 0x71; +pub const VK_F3: ::c_int = 0x72; +pub const VK_F4: ::c_int = 0x73; +pub const VK_F5: ::c_int = 0x74; +pub const VK_F6: ::c_int = 0x75; +pub const VK_F7: ::c_int = 0x76; +pub const VK_F8: ::c_int = 0x77; +pub const VK_F9: ::c_int = 0x78; +pub const VK_F10: ::c_int = 0x79; +pub const VK_F11: ::c_int = 0x7A; +pub const VK_F12: ::c_int = 0x7B; +pub const VK_F13: ::c_int = 0x7C; +pub const VK_F14: ::c_int = 0x7D; +pub const VK_F15: ::c_int = 0x7E; +pub const VK_F16: ::c_int = 0x7F; +pub const VK_F17: ::c_int = 0x80; +pub const VK_F18: ::c_int = 0x81; +pub const VK_F19: ::c_int = 0x82; +pub const VK_F20: ::c_int = 0x83; +pub const VK_F21: ::c_int = 0x84; +pub const VK_F22: ::c_int = 0x85; +pub const VK_F23: ::c_int = 0x86; +pub const VK_F24: ::c_int = 0x87; +pub const VK_NUMLOCK: ::c_int = 0x90; +pub const VK_SCROLL: ::c_int = 0x91; +pub const VK_OEM_NEC_EQUAL: ::c_int = 0x92; +pub const VK_OEM_FJ_JISHO: ::c_int = 0x92; +pub const VK_OEM_FJ_MASSHOU: ::c_int = 0x93; +pub const VK_OEM_FJ_TOUROKU: ::c_int = 0x94; +pub const VK_OEM_FJ_LOYA: ::c_int = 0x95; +pub const VK_OEM_FJ_ROYA: ::c_int = 0x96; +pub const VK_LSHIFT: ::c_int = 0xA0; +pub const VK_RSHIFT: ::c_int = 0xA1; +pub const VK_LCONTROL: ::c_int = 0xA2; +pub const VK_RCONTROL: ::c_int = 0xA3; +pub const VK_LMENU: ::c_int = 0xA4; +pub const VK_RMENU: ::c_int = 0xA5; +pub const VK_BROWSER_BACK: ::c_int = 0xA6; +pub const VK_BROWSER_FORWARD: ::c_int = 0xA7; +pub const VK_BROWSER_REFRESH: ::c_int = 0xA8; +pub const VK_BROWSER_STOP: ::c_int = 0xA9; +pub const VK_BROWSER_SEARCH: ::c_int = 0xAA; +pub const VK_BROWSER_FAVORITES: ::c_int = 0xAB; +pub const VK_BROWSER_HOME: ::c_int = 0xAC; +pub const VK_VOLUME_MUTE: ::c_int = 0xAD; +pub const VK_VOLUME_DOWN: ::c_int = 0xAE; +pub const VK_VOLUME_UP: ::c_int = 0xAF; +pub const VK_MEDIA_NEXT_TRACK: ::c_int = 0xB0; +pub const VK_MEDIA_PREV_TRACK: ::c_int = 0xB1; +pub const VK_MEDIA_STOP: ::c_int = 0xB2; +pub const VK_MEDIA_PLAY_PAUSE: ::c_int = 0xB3; +pub const VK_LAUNCH_MAIL: ::c_int = 0xB4; +pub const VK_LAUNCH_MEDIA_SELECT: ::c_int = 0xB5; +pub const VK_LAUNCH_APP1: ::c_int = 0xB6; +pub const VK_LAUNCH_APP2: ::c_int = 0xB7; +pub const VK_OEM_1: ::c_int = 0xBA; +pub const VK_OEM_PLUS: ::c_int = 0xBB; +pub const VK_OEM_COMMA: ::c_int = 0xBC; +pub const VK_OEM_MINUS: ::c_int = 0xBD; +pub const VK_OEM_PERIOD: ::c_int = 0xBE; +pub const VK_OEM_2: ::c_int = 0xBF; +pub const VK_OEM_3: ::c_int = 0xC0; +pub const VK_OEM_4: ::c_int = 0xDB; +pub const VK_OEM_5: ::c_int = 0xDC; +pub const VK_OEM_6: ::c_int = 0xDD; +pub const VK_OEM_7: ::c_int = 0xDE; +pub const VK_OEM_8: ::c_int = 0xDF; +pub const VK_OEM_AX: ::c_int = 0xE1; +pub const VK_OEM_102: ::c_int = 0xE2; +pub const VK_ICO_HELP: ::c_int = 0xE3; +pub const VK_ICO_00: ::c_int = 0xE4; +pub const VK_PROCESSKEY: ::c_int = 0xE5; +pub const VK_ICO_CLEAR: ::c_int = 0xE6; +pub const VK_PACKET: ::c_int = 0xE7; +pub const VK_OEM_RESET: ::c_int = 0xE9; +pub const VK_OEM_JUMP: ::c_int = 0xEA; +pub const VK_OEM_PA1: ::c_int = 0xEB; +pub const VK_OEM_PA2: ::c_int = 0xEC; +pub const VK_OEM_PA3: ::c_int = 0xED; +pub const VK_OEM_WSCTRL: ::c_int = 0xEE; +pub const VK_OEM_CUSEL: ::c_int = 0xEF; +pub const VK_OEM_ATTN: ::c_int = 0xF0; +pub const VK_OEM_FINISH: ::c_int = 0xF1; +pub const VK_OEM_COPY: ::c_int = 0xF2; +pub const VK_OEM_AUTO: ::c_int = 0xF3; +pub const VK_OEM_ENLW: ::c_int = 0xF4; +pub const VK_OEM_BACKTAB: ::c_int = 0xF5; +pub const VK_ATTN: ::c_int = 0xF6; +pub const VK_CRSEL: ::c_int = 0xF7; +pub const VK_EXSEL: ::c_int = 0xF8; +pub const VK_EREOF: ::c_int = 0xF9; +pub const VK_PLAY: ::c_int = 0xFA; +pub const VK_ZOOM: ::c_int = 0xFB; +pub const VK_NONAME: ::c_int = 0xFC; +pub const VK_PA1: ::c_int = 0xFD; +pub const VK_OEM_CLEAR: ::c_int = 0xFE; +// if _WIN32_WINNT >= 0x0500 +pub const APPCOMMAND_BROWSER_BACKWARD: ::c_short = 1; +pub const APPCOMMAND_BROWSER_FORWARD: ::c_short = 2; +pub const APPCOMMAND_BROWSER_REFRESH: ::c_short = 3; +pub const APPCOMMAND_BROWSER_STOP: ::c_short = 4; +pub const APPCOMMAND_BROWSER_SEARCH: ::c_short = 5; +pub const APPCOMMAND_BROWSER_FAVORITES: ::c_short = 6; +pub const APPCOMMAND_BROWSER_HOME: ::c_short = 7; +pub const APPCOMMAND_VOLUME_MUTE: ::c_short = 8; +pub const APPCOMMAND_VOLUME_DOWN: ::c_short = 9; +pub const APPCOMMAND_VOLUME_UP: ::c_short = 10; +pub const APPCOMMAND_MEDIA_NEXTTRACK: ::c_short = 11; +pub const APPCOMMAND_MEDIA_PREVIOUSTRACK: ::c_short = 12; +pub const APPCOMMAND_MEDIA_STOP: ::c_short = 13; +pub const APPCOMMAND_MEDIA_PLAY_PAUSE: ::c_short = 14; +pub const APPCOMMAND_LAUNCH_MAIL: ::c_short = 15; +pub const APPCOMMAND_LAUNCH_MEDIA_SELECT: ::c_short = 16; +pub const APPCOMMAND_LAUNCH_APP1: ::c_short = 17; +pub const APPCOMMAND_LAUNCH_APP2: ::c_short = 18; +pub const APPCOMMAND_BASS_DOWN: ::c_short = 19; +pub const APPCOMMAND_BASS_BOOST: ::c_short = 20; +pub const APPCOMMAND_BASS_UP: ::c_short = 21; +pub const APPCOMMAND_TREBLE_DOWN: ::c_short = 22; +pub const APPCOMMAND_TREBLE_UP: ::c_short = 23; +// if _WIN32_WINNT >= 0x0501 +pub const APPCOMMAND_MICROPHONE_VOLUME_MUTE: ::c_short = 24; +pub const APPCOMMAND_MICROPHONE_VOLUME_DOWN: ::c_short = 25; +pub const APPCOMMAND_MICROPHONE_VOLUME_UP: ::c_short = 26; +pub const APPCOMMAND_HELP: ::c_short = 27; +pub const APPCOMMAND_FIND: ::c_short = 28; +pub const APPCOMMAND_NEW: ::c_short = 29; +pub const APPCOMMAND_OPEN: ::c_short = 30; +pub const APPCOMMAND_CLOSE: ::c_short = 31; +pub const APPCOMMAND_SAVE: ::c_short = 32; +pub const APPCOMMAND_PRINT: ::c_short = 33; +pub const APPCOMMAND_UNDO: ::c_short = 34; +pub const APPCOMMAND_REDO: ::c_short = 35; +pub const APPCOMMAND_COPY: ::c_short = 36; +pub const APPCOMMAND_CUT: ::c_short = 37; +pub const APPCOMMAND_PASTE: ::c_short = 38; +pub const APPCOMMAND_REPLY_TO_MAIL: ::c_short = 39; +pub const APPCOMMAND_FORWARD_MAIL: ::c_short = 40; +pub const APPCOMMAND_SEND_MAIL: ::c_short = 41; +pub const APPCOMMAND_SPELL_CHECK: ::c_short = 42; +pub const APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: ::c_short = 43; +pub const APPCOMMAND_MIC_ON_OFF_TOGGLE: ::c_short = 44; +pub const APPCOMMAND_CORRECTION_LIST: ::c_short = 45; +pub const APPCOMMAND_MEDIA_PLAY: ::c_short = 46; +pub const APPCOMMAND_MEDIA_PAUSE: ::c_short = 47; +pub const APPCOMMAND_MEDIA_RECORD: ::c_short = 48; +pub const APPCOMMAND_MEDIA_FAST_FORWARD: ::c_short = 49; +pub const APPCOMMAND_MEDIA_REWIND: ::c_short = 50; +pub const APPCOMMAND_MEDIA_CHANNEL_UP: ::c_short = 51; +pub const APPCOMMAND_MEDIA_CHANNEL_DOWN: ::c_short = 52; +// end if _WIN32_WINNT >= 0x0501 +// if _WIN32_WINNT >= 0x0600 +pub const APPCOMMAND_DELETE: ::c_short = 53; +pub const APPCOMMAND_DWM_FLIP3D: ::c_short = 54; +// end if _WIN32_WINNT >= 0x0600 +pub const WM_NULL: ::UINT = 0x0000; +pub const WM_CREATE: ::UINT = 0x0001; +pub const WM_DESTROY: ::UINT = 0x0002; +pub const WM_MOVE: ::UINT = 0x0003; +pub const WM_SIZE: ::UINT = 0x0005; +pub const WM_ACTIVATE: ::UINT = 0x0006; +pub const WM_SETFOCUS: ::UINT = 0x0007; +pub const WM_KILLFOCUS: ::UINT = 0x0008; +pub const WM_ENABLE: ::UINT = 0x000A; +pub const WM_SETREDRAW: ::UINT = 0x000B; +pub const WM_SETTEXT: ::UINT = 0x000C; +pub const WM_GETTEXT: ::UINT = 0x000D; +pub const WM_GETTEXTLENGTH: ::UINT = 0x000E; +pub const WM_PAINT: ::UINT = 0x000F; +pub const WM_CLOSE: ::UINT = 0x0010; +pub const WM_QUERYENDSESSION: ::UINT = 0x0011; +pub const WM_QUERYOPEN: ::UINT = 0x0013; +pub const WM_ENDSESSION: ::UINT = 0x0016; +pub const WM_QUIT: ::UINT = 0x0012; +pub const WM_ERASEBKGND: ::UINT = 0x0014; +pub const WM_SYSCOLORCHANGE: ::UINT = 0x0015; +pub const WM_SHOWWINDOW: ::UINT = 0x0018; +pub const WM_WININICHANGE: ::UINT = 0x001A; +pub const WM_SETTINGCHANGE: ::UINT = WM_WININICHANGE; +pub const WM_DEVMODECHANGE: ::UINT = 0x001B; +pub const WM_ACTIVATEAPP: ::UINT = 0x001C; +pub const WM_FONTCHANGE: ::UINT = 0x001D; +pub const WM_TIMECHANGE: ::UINT = 0x001E; +pub const WM_CANCELMODE: ::UINT = 0x001F; +pub const WM_SETCURSOR: ::UINT = 0x0020; +pub const WM_MOUSEACTIVATE: ::UINT = 0x0021; +pub const WM_CHILDACTIVATE: ::UINT = 0x0022; +pub const WM_QUEUESYNC: ::UINT = 0x0023; +pub const WM_GETMINMAXINFO: ::UINT = 0x0024; +pub const WM_PAINTICON: ::UINT = 0x0026; +pub const WM_ICONERASEBKGND: ::UINT = 0x0027; +pub const WM_NEXTDLGCTL: ::UINT = 0x0028; +pub const WM_SPOOLERSTATUS: ::UINT = 0x002A; +pub const WM_DRAWITEM: ::UINT = 0x002B; +pub const WM_MEASUREITEM: ::UINT = 0x002C; +pub const WM_DELETEITEM: ::UINT = 0x002D; +pub const WM_VKEYTOITEM: ::UINT = 0x002E; +pub const WM_CHARTOITEM: ::UINT = 0x002F; +pub const WM_SETFONT: ::UINT = 0x0030; +pub const WM_GETFONT: ::UINT = 0x0031; +pub const WM_SETHOTKEY: ::UINT = 0x0032; +pub const WM_GETHOTKEY: ::UINT = 0x0033; +pub const WM_QUERYDRAGICON: ::UINT = 0x0037; +pub const WM_COMPAREITEM: ::UINT = 0x0039; +pub const WM_GETOBJECT: ::UINT = 0x003D; +pub const WM_COMPACTING: ::UINT = 0x0041; +pub const WM_COMMNOTIFY: ::UINT = 0x0044; +pub const WM_WINDOWPOSCHANGING: ::UINT = 0x0046; +pub const WM_WINDOWPOSCHANGED: ::UINT = 0x0047; +pub const WM_POWER: ::UINT = 0x0048; +pub const WM_COPYDATA: ::UINT = 0x004A; +pub const WM_CANCELJOURNAL: ::UINT = 0x004B; +pub const WM_NOTIFY: ::UINT = 0x004E; +pub const WM_INPUTLANGCHANGEREQUEST: ::UINT = 0x0050; +pub const WM_INPUTLANGCHANGE: ::UINT = 0x0051; +pub const WM_TCARD: ::UINT = 0x0052; +pub const WM_HELP: ::UINT = 0x0053; +pub const WM_USERCHANGED: ::UINT = 0x0054; +pub const WM_NOTIFYFORMAT: ::UINT = 0x0055; +pub const WM_CONTEXTMENU: ::UINT = 0x007B; +pub const WM_STYLECHANGING: ::UINT = 0x007C; +pub const WM_STYLECHANGED: ::UINT = 0x007D; +pub const WM_DISPLAYCHANGE: ::UINT = 0x007E; +pub const WM_GETICON: ::UINT = 0x007F; +pub const WM_SETICON: ::UINT = 0x0080; +pub const WM_NCCREATE: ::UINT = 0x0081; +pub const WM_NCDESTROY: ::UINT = 0x0082; +pub const WM_NCCALCSIZE: ::UINT = 0x0083; +pub const WM_NCHITTEST: ::UINT = 0x0084; +pub const WM_NCPAINT: ::UINT = 0x0085; +pub const WM_NCACTIVATE: ::UINT = 0x0086; +pub const WM_GETDLGCODE: ::UINT = 0x0087; +pub const WM_SYNCPAINT: ::UINT = 0x0088; +pub const WM_NCMOUSEMOVE: ::UINT = 0x00A0; +pub const WM_NCLBUTTONDOWN: ::UINT = 0x00A1; +pub const WM_NCLBUTTONUP: ::UINT = 0x00A2; +pub const WM_NCLBUTTONDBLCLK: ::UINT = 0x00A3; +pub const WM_NCRBUTTONDOWN: ::UINT = 0x00A4; +pub const WM_NCRBUTTONUP: ::UINT = 0x00A5; +pub const WM_NCRBUTTONDBLCLK: ::UINT = 0x00A6; +pub const WM_NCMBUTTONDOWN: ::UINT = 0x00A7; +pub const WM_NCMBUTTONUP: ::UINT = 0x00A8; +pub const WM_NCMBUTTONDBLCLK: ::UINT = 0x00A9; +pub const WM_NCXBUTTONDOWN: ::UINT = 0x00AB; +pub const WM_NCXBUTTONUP: ::UINT = 0x00AC; +pub const WM_NCXBUTTONDBLCLK: ::UINT = 0x00AD; +pub const WM_INPUT_DEVICE_CHANGE: ::UINT = 0x00FE; +pub const WM_INPUT: ::UINT = 0x00FF; +pub const WM_KEYFIRST: ::UINT = 0x0100; +pub const WM_KEYDOWN: ::UINT = 0x0100; +pub const WM_KEYUP: ::UINT = 0x0101; +pub const WM_CHAR: ::UINT = 0x0102; +pub const WM_DEADCHAR: ::UINT = 0x0103; +pub const WM_SYSKEYDOWN: ::UINT = 0x0104; +pub const WM_SYSKEYUP: ::UINT = 0x0105; +pub const WM_SYSCHAR: ::UINT = 0x0106; +pub const WM_SYSDEADCHAR: ::UINT = 0x0107; +pub const WM_UNICHAR: ::UINT = 0x0109; +pub const WM_KEYLAST: ::UINT = 0x0109; +pub const WM_IME_STARTCOMPOSITION: ::UINT = 0x010D; +pub const WM_IME_ENDCOMPOSITION: ::UINT = 0x010E; +pub const WM_IME_COMPOSITION: ::UINT = 0x010F; +pub const WM_IME_KEYLAST: ::UINT = 0x010F; +pub const WM_INITDIALOG: ::UINT = 0x0110; +pub const WM_COMMAND: ::UINT = 0x0111; +pub const WM_SYSCOMMAND: ::UINT = 0x0112; +pub const WM_TIMER: ::UINT = 0x0113; +pub const WM_HSCROLL: ::UINT = 0x0114; +pub const WM_VSCROLL: ::UINT = 0x0115; +pub const WM_INITMENU: ::UINT = 0x0116; +pub const WM_INITMENUPOPUP: ::UINT = 0x0117; +pub const WM_GESTURE: ::UINT = 0x0119; +pub const WM_GESTURENOTIFY: ::UINT = 0x011A; +pub const WM_MENUSELECT: ::UINT = 0x011F; +pub const WM_MENUCHAR: ::UINT = 0x0120; +pub const WM_ENTERIDLE: ::UINT = 0x0121; +pub const WM_MENURBUTTONUP: ::UINT = 0x0122; +pub const WM_MENUDRAG: ::UINT = 0x0123; +pub const WM_MENUGETOBJECT: ::UINT = 0x0124; +pub const WM_UNINITMENUPOPUP: ::UINT = 0x0125; +pub const WM_MENUCOMMAND: ::UINT = 0x0126; +pub const WM_CHANGEUISTATE: ::UINT = 0x0127; +pub const WM_UPDATEUISTATE: ::UINT = 0x0128; +pub const WM_QUERYUISTATE: ::UINT = 0x0129; +pub const WM_CTLCOLORMSGBOX: ::UINT = 0x0132; +pub const WM_CTLCOLOREDIT: ::UINT = 0x0133; +pub const WM_CTLCOLORLISTBOX: ::UINT = 0x0134; +pub const WM_CTLCOLORBTN: ::UINT = 0x0135; +pub const WM_CTLCOLORDLG: ::UINT = 0x0136; +pub const WM_CTLCOLORSCROLLBAR: ::UINT = 0x0137; +pub const WM_CTLCOLORSTATIC: ::UINT = 0x0138; +pub const WM_MOUSEFIRST: ::UINT = 0x0200; +pub const WM_MOUSEMOVE: ::UINT = 0x0200; +pub const WM_LBUTTONDOWN: ::UINT = 0x0201; +pub const WM_LBUTTONUP: ::UINT = 0x0202; +pub const WM_LBUTTONDBLCLK: ::UINT = 0x0203; +pub const WM_RBUTTONDOWN: ::UINT = 0x0204; +pub const WM_RBUTTONUP: ::UINT = 0x0205; +pub const WM_RBUTTONDBLCLK: ::UINT = 0x0206; +pub const WM_MBUTTONDOWN: ::UINT = 0x0207; +pub const WM_MBUTTONUP: ::UINT = 0x0208; +pub const WM_MBUTTONDBLCLK: ::UINT = 0x0209; +pub const WM_MOUSEWHEEL: ::UINT = 0x020A; +pub const WM_XBUTTONDOWN: ::UINT = 0x020B; +pub const WM_XBUTTONUP: ::UINT = 0x020C; +pub const WM_XBUTTONDBLCLK: ::UINT = 0x020D; +pub const WM_MOUSEHWHEEL: ::UINT = 0x020E; +pub const WM_MOUSELAST: ::UINT = 0x020E; +pub const WM_PARENTNOTIFY: ::UINT = 0x0210; +pub const WM_ENTERMENULOOP: ::UINT = 0x0211; +pub const WM_EXITMENULOOP: ::UINT = 0x0212; +pub const WM_NEXTMENU: ::UINT = 0x0213; +pub const WM_SIZING: ::UINT = 0x0214; +pub const WM_CAPTURECHANGED: ::UINT = 0x0215; +pub const WM_MOVING: ::UINT = 0x0216; +pub const WM_POWERBROADCAST: ::UINT = 0x0218; +pub const WM_DEVICECHANGE: ::UINT = 0x0219; +pub const WM_MDICREATE: ::UINT = 0x0220; +pub const WM_MDIDESTROY: ::UINT = 0x0221; +pub const WM_MDIACTIVATE: ::UINT = 0x0222; +pub const WM_MDIRESTORE: ::UINT = 0x0223; +pub const WM_MDINEXT: ::UINT = 0x0224; +pub const WM_MDIMAXIMIZE: ::UINT = 0x0225; +pub const WM_MDITILE: ::UINT = 0x0226; +pub const WM_MDICASCADE: ::UINT = 0x0227; +pub const WM_MDIICONARRANGE: ::UINT = 0x0228; +pub const WM_MDIGETACTIVE: ::UINT = 0x0229; +pub const WM_MDISETMENU: ::UINT = 0x0230; +pub const WM_ENTERSIZEMOVE: ::UINT = 0x0231; +pub const WM_EXITSIZEMOVE: ::UINT = 0x0232; +pub const WM_DROPFILES: ::UINT = 0x0233; +pub const WM_MDIREFRESHMENU: ::UINT = 0x0234; +pub const WM_POINTERDEVICECHANGE: ::UINT = 0x238; +pub const WM_POINTERDEVICEINRANGE: ::UINT = 0x239; +pub const WM_POINTERDEVICEOUTOFRANGE: ::UINT = 0x23A; +pub const WM_TOUCH: ::UINT = 0x0240; +pub const WM_NCPOINTERUPDATE: ::UINT = 0x0241; +pub const WM_NCPOINTERDOWN: ::UINT = 0x0242; +pub const WM_NCPOINTERUP: ::UINT = 0x0243; +pub const WM_POINTERUPDATE: ::UINT = 0x0245; +pub const WM_POINTERDOWN: ::UINT = 0x0246; +pub const WM_POINTERUP: ::UINT = 0x0247; +pub const WM_POINTERENTER: ::UINT = 0x0249; +pub const WM_POINTERLEAVE: ::UINT = 0x024A; +pub const WM_POINTERACTIVATE: ::UINT = 0x024B; +pub const WM_POINTERCAPTURECHANGED: ::UINT = 0x024C; +pub const WM_TOUCHHITTESTING: ::UINT = 0x024D; +pub const WM_POINTERWHEEL: ::UINT = 0x024E; +pub const WM_POINTERHWHEEL: ::UINT = 0x024F; +pub const WM_IME_SETCONTEXT: ::UINT = 0x0281; +pub const WM_IME_NOTIFY: ::UINT = 0x0282; +pub const WM_IME_CONTROL: ::UINT = 0x0283; +pub const WM_IME_COMPOSITIONFULL: ::UINT = 0x0284; +pub const WM_IME_SELECT: ::UINT = 0x0285; +pub const WM_IME_CHAR: ::UINT = 0x0286; +pub const WM_IME_REQUEST: ::UINT = 0x0288; +pub const WM_IME_KEYDOWN: ::UINT = 0x0290; +pub const WM_IME_KEYUP: ::UINT = 0x0291; +pub const WM_MOUSEHOVER: ::UINT = 0x02A1; +pub const WM_MOUSELEAVE: ::UINT = 0x02A3; +pub const WM_NCMOUSEHOVER: ::UINT = 0x02A0; +pub const WM_NCMOUSELEAVE: ::UINT = 0x02A2; +pub const WM_WTSSESSION_CHANGE: ::UINT = 0x02B1; +pub const WM_TABLET_FIRST: ::UINT = 0x02c0; +pub const WM_TABLET_LAST: ::UINT = 0x02df; +pub const WM_DPICHANGED: ::UINT = 0x02E0; +pub const WM_CUT: ::UINT = 0x0300; +pub const WM_COPY: ::UINT = 0x0301; +pub const WM_PASTE: ::UINT = 0x0302; +pub const WM_CLEAR: ::UINT = 0x0303; +pub const WM_UNDO: ::UINT = 0x0304; +pub const WM_RENDERFORMAT: ::UINT = 0x0305; +pub const WM_RENDERALLFORMATS: ::UINT = 0x0306; +pub const WM_DESTROYCLIPBOARD: ::UINT = 0x0307; +pub const WM_DRAWCLIPBOARD: ::UINT = 0x0308; +pub const WM_PAINTCLIPBOARD: ::UINT = 0x0309; +pub const WM_VSCROLLCLIPBOARD: ::UINT = 0x030A; +pub const WM_SIZECLIPBOARD: ::UINT = 0x030B; +pub const WM_ASKCBFORMATNAME: ::UINT = 0x030C; +pub const WM_CHANGECBCHAIN: ::UINT = 0x030D; +pub const WM_HSCROLLCLIPBOARD: ::UINT = 0x030E; +pub const WM_QUERYNEWPALETTE: ::UINT = 0x030F; +pub const WM_PALETTEISCHANGING: ::UINT = 0x0310; +pub const WM_PALETTECHANGED: ::UINT = 0x0311; +pub const WM_HOTKEY: ::UINT = 0x0312; +pub const WM_PRINT: ::UINT = 0x0317; +pub const WM_PRINTCLIENT: ::UINT = 0x0318; +pub const WM_APPCOMMAND: ::UINT = 0x0319; +pub const WM_THEMECHANGED: ::UINT = 0x031A; +pub const WM_CLIPBOARDUPDATE: ::UINT = 0x031D; +pub const WM_DWMCOMPOSITIONCHANGED: ::UINT = 0x031E; +pub const WM_DWMNCRENDERINGCHANGED: ::UINT = 0x031F; +pub const WM_DWMCOLORIZATIONCOLORCHANGED: ::UINT = 0x0320; +pub const WM_DWMWINDOWMAXIMIZEDCHANGE: ::UINT = 0x0321; +pub const WM_DWMSENDICONICTHUMBNAIL: ::UINT = 0x0323; +pub const WM_DWMSENDICONICLIVEPREVIEWBITMAP: ::UINT = 0x0326; +pub const WM_GETTITLEBARINFOEX: ::UINT = 0x033F; +pub const WM_HANDHELDFIRST: ::UINT = 0x0358; +pub const WM_HANDHELDLAST: ::UINT = 0x035F; +pub const WM_AFXFIRST: ::UINT = 0x0360; +pub const WM_AFXLAST: ::UINT = 0x037F; +pub const WM_PENWINFIRST: ::UINT = 0x0380; +pub const WM_PENWINLAST: ::UINT = 0x038F; +pub const WM_APP: ::UINT = 0x8000; +pub const WM_USER: ::UINT = 0x0400; +pub const WMSZ_LEFT: ::UINT = 1; +pub const WMSZ_RIGHT: ::UINT = 2; +pub const WMSZ_TOP: ::UINT = 3; +pub const WMSZ_TOPLEFT: ::UINT = 4; +pub const WMSZ_TOPRIGHT: ::UINT = 5; +pub const WMSZ_BOTTOM: ::UINT = 6; +pub const WMSZ_BOTTOMLEFT: ::UINT = 7; +pub const WMSZ_BOTTOMRIGHT: ::UINT = 8; +pub const SMTO_NORMAL: ::UINT = 0x0000; +pub const SMTO_BLOCK: ::UINT = 0x0001; +pub const SMTO_ABORTIFHUNG: ::UINT = 0x0002; +pub const SMTO_NOTIMEOUTIFNOTHUNG: ::UINT = 0x0008; +pub const SMTO_ERRORONEXIT: ::UINT = 0x0020; +pub const MA_ACTIVATE: ::UINT = 1; +pub const MA_ACTIVATEANDEAT: ::UINT = 2; +pub const MA_NOACTIVATE: ::UINT = 3; +pub const MA_NOACTIVATEANDEAT: ::UINT = 4; +pub const ICON_SMALL: ::UINT = 0; +pub const ICON_BIG: ::UINT = 1; +pub const ICON_SMALL2: ::UINT = 2; +pub const SIZE_RESTORED: ::UINT = 0; +pub const SIZE_MINIMIZED: ::UINT = 1; +pub const SIZE_MAXIMIZED: ::UINT = 2; +pub const SIZE_MAXSHOW: ::UINT = 3; +pub const SIZE_MAXHIDE: ::UINT = 4; +pub const SIZENORMAL: ::UINT = SIZE_RESTORED; +pub const SIZEICONIC: ::UINT = SIZE_MINIMIZED; +pub const SIZEFULLSCREEN: ::UINT = SIZE_MAXIMIZED; +pub const SIZEZOOMSHOW: ::UINT = SIZE_MAXSHOW; +pub const SIZEZOOMHIDE: ::UINT = SIZE_MAXHIDE; +STRUCT!{struct NCCALCSIZE_PARAMS { + rgrc: [::RECT; 3], + lppos: PWINDOWPOS, +}} +pub type PNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub type NPNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub type LPNCCALCSIZE_PARAMS = *mut NCCALCSIZE_PARAMS; +pub const WVR_ALIGNTOP: ::UINT = 0x0010; +pub const WVR_ALIGNLEFT: ::UINT = 0x0020; +pub const WVR_ALIGNBOTTOM: ::UINT = 0x0040; +pub const WVR_ALIGNRIGHT: ::UINT = 0x0080; +pub const WVR_HREDRAW: ::UINT = 0x0100; +pub const WVR_VREDRAW: ::UINT = 0x0200; +pub const WVR_REDRAW: ::UINT = WVR_HREDRAW | WVR_VREDRAW; +pub const WVR_VALIDRECTS: ::UINT = 0x0400; +pub const HOVER_DEFAULT: ::UINT = 0xFFFFFFFF; +pub const WS_OVERLAPPED: ::DWORD = 0x00000000; +pub const WS_POPUP: ::DWORD = 0x80000000; +pub const WS_CHILD: ::DWORD = 0x40000000; +pub const WS_MINIMIZE: ::DWORD = 0x20000000; +pub const WS_VISIBLE: ::DWORD = 0x10000000; +pub const WS_DISABLED: ::DWORD = 0x08000000; +pub const WS_CLIPSIBLINGS: ::DWORD = 0x04000000; +pub const WS_CLIPCHILDREN: ::DWORD = 0x02000000; +pub const WS_MAXIMIZE: ::DWORD = 0x01000000; +pub const WS_CAPTION: ::DWORD = 0x00C00000; +pub const WS_BORDER: ::DWORD = 0x00800000; +pub const WS_DLGFRAME: ::DWORD = 0x00400000; +pub const WS_VSCROLL: ::DWORD = 0x00200000; +pub const WS_HSCROLL: ::DWORD = 0x00100000; +pub const WS_SYSMENU: ::DWORD = 0x00080000; +pub const WS_THICKFRAME: ::DWORD = 0x00040000; +pub const WS_GROUP: ::DWORD = 0x00020000; +pub const WS_TABSTOP: ::DWORD = 0x00010000; +pub const WS_MINIMIZEBOX: ::DWORD = 0x00020000; +pub const WS_MAXIMIZEBOX: ::DWORD = 0x00010000; +pub const WS_TILED: ::DWORD = WS_OVERLAPPED; +pub const WS_ICONIC: ::DWORD = WS_MINIMIZE; +pub const WS_SIZEBOX: ::DWORD = WS_THICKFRAME; +pub const WS_TILEDWINDOW: ::DWORD = WS_OVERLAPPEDWINDOW; +pub const WS_OVERLAPPEDWINDOW: ::DWORD = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; +pub const WS_POPUPWINDOW: ::DWORD = WS_POPUP | WS_BORDER | WS_SYSMENU; +pub const WS_CHILDWINDOW: ::DWORD = WS_CHILD; +pub const WS_EX_DLGMODALFRAME: ::DWORD = 0x00000001; +pub const WS_EX_NOPARENTNOTIFY: ::DWORD = 0x00000004; +pub const WS_EX_TOPMOST: ::DWORD = 0x00000008; +pub const WS_EX_ACCEPTFILES: ::DWORD = 0x00000010; +pub const WS_EX_TRANSPARENT: ::DWORD = 0x00000020; +pub const WS_EX_MDICHILD: ::DWORD = 0x00000040; +pub const WS_EX_TOOLWINDOW: ::DWORD = 0x00000080; +pub const WS_EX_WINDOWEDGE: ::DWORD = 0x00000100; +pub const WS_EX_CLIENTEDGE: ::DWORD = 0x00000200; +pub const WS_EX_CONTEXTHELP: ::DWORD = 0x00000400; +pub const WS_EX_RIGHT: ::DWORD = 0x00001000; +pub const WS_EX_LEFT: ::DWORD = 0x00000000; +pub const WS_EX_RTLREADING: ::DWORD = 0x00002000; +pub const WS_EX_LTRREADING: ::DWORD = 0x00000000; +pub const WS_EX_LEFTSCROLLBAR: ::DWORD = 0x00004000; +pub const WS_EX_RIGHTSCROLLBAR: ::DWORD = 0x00000000; +pub const WS_EX_CONTROLPARENT: ::DWORD = 0x00010000; +pub const WS_EX_STATICEDGE: ::DWORD = 0x00020000; +pub const WS_EX_APPWINDOW: ::DWORD = 0x00040000; +pub const WS_EX_OVERLAPPEDWINDOW: ::DWORD = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE; +pub const WS_EX_PALETTEWINDOW: ::DWORD = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST; +pub const WS_EX_LAYERED: ::DWORD = 0x00080000; +pub const WS_EX_NOINHERITLAYOUT: ::DWORD = 0x00100000; +pub const WS_EX_NOREDIRECTIONBITMAP: ::DWORD = 0x00200000; +pub const WS_EX_LAYOUTRTL: ::DWORD = 0x00400000; +pub const WS_EX_COMPOSITED: ::DWORD = 0x02000000; +pub const WS_EX_NOACTIVATE: ::DWORD = 0x08000000; +pub type NAMEENUMPROCA = Option ::BOOL>; +pub type NAMEENUMPROCW = Option ::BOOL>; +pub type DESKTOPENUMPROCA = NAMEENUMPROCA; +pub type DESKTOPENUMPROCW = NAMEENUMPROCW; +pub type WINSTAENUMPROCA = NAMEENUMPROCA; +pub type WINSTAENUMPROCW = NAMEENUMPROCW; +pub type WNDENUMPROC = Option ::BOOL>; +pub type WNDPROC = Option ::LRESULT>; +pub type DLGPROC = Option ::INT_PTR>; +pub type HOOKPROC = Option ::LRESULT>; +pub type TimerProc = Option; +pub type DRAWSTATEPROC = Option ::BOOL>; +pub type PROPENUMPROCA = Option ::BOOL>; +pub type PROPENUMPROCW = Option ::BOOL>; +pub type GRAYSTRINGPROC = Option ::BOOL>; +pub type MSGBOXCALLBACK = Option; +pub type WINEVENTPROC = Option; +pub type HDEVNOTIFY = ::PVOID; +pub type MENUTEMPLATEA = ::VOID; +pub type MENUTEMPLATEW = ::VOID; +STRUCT!{struct MSG { + hwnd: ::HWND, + message: ::UINT, + wParam: ::WPARAM, + lParam: ::LPARAM, + time: ::DWORD, + pt: ::POINT, +}} +pub type PMSG = *mut MSG; +pub type NPMSG = *mut MSG; +pub type LPMSG = *mut MSG; +STRUCT!{struct PAINTSTRUCT { + hdc: ::HDC, + fErase: ::BOOL, + rcPaint: ::RECT, + fRestore: ::BOOL, + fIncUpdate: ::BOOL, + rgbReserved: [::BYTE; 32], +}} +pub type PPAINTSTRUCT = *mut PAINTSTRUCT; +pub type NPPAINTSTRUCT = *mut PAINTSTRUCT; +pub type LPPAINTSTRUCT = *mut PAINTSTRUCT; +STRUCT!{struct WINDOWPLACEMENT { + length: ::UINT, + flags: ::UINT, + showCmd: ::UINT, + ptMinPosition: ::POINT, + ptMaxPosition: ::POINT, + rcNormalPosition: ::RECT, +}} +pub type PWINDOWPLACEMENT = *mut WINDOWPLACEMENT; +pub type LPWINDOWPLACEMENT = *mut WINDOWPLACEMENT; +STRUCT!{nodebug struct WNDCLASSEXW { + cbSize: ::UINT, + style: ::UINT, + lpfnWndProc: WNDPROC, + cbClsExtra: ::c_int, + cbWndExtra: ::c_int, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + hCursor: ::HCURSOR, + hbrBackground: ::HBRUSH, + lpszMenuName: ::LPCWSTR, + lpszClassName: ::LPCWSTR, + hIconSm: ::HICON, +}} +pub type PWNDCLASSEXW = *mut WNDCLASSEXW; +pub type NPWNDCLASSEXW = *mut WNDCLASSEXW; +pub type LPWNDCLASSEXW = *mut WNDCLASSEXW; +STRUCT!{nodebug struct WNDCLASSW { + style: ::UINT, + lpfnWndProc: WNDPROC, + cbClsExtra: ::c_int, + cbWndExtra: ::c_int, + hInstance: ::HINSTANCE, + hIcon: ::HICON, + hCursor: ::HCURSOR, + hbrBackground: ::HBRUSH, + lpszMenuName: ::LPCWSTR, + lpszClassName: ::LPCWSTR, +}} +pub type PWNDCLASSW = *mut WNDCLASSW; +pub type NPWNDCLASSW = *mut WNDCLASSW; +pub type LPWNDCLASSW = *mut WNDCLASSW; +STRUCT!{struct MINMAXINFO { + ptReserved: ::POINT, + ptMaxSize: ::POINT, + ptMaxPosition: ::POINT, + ptMinTrackSize: ::POINT, + ptMaxTrackSize: ::POINT, +}} +STRUCT!{struct SCROLLBARINFO { + cbSize: ::DWORD, + rcScrollBar: ::RECT, + dxyLineButton: ::c_int, + xyThumbTop: ::c_int, + xyThumbBottom: ::c_int, + reserved: ::c_int, + rgstate: [::DWORD; CCHILDREN_SCROLLBAR + 1], +}} +pub type PSCROLLBARINFO = *mut SCROLLBARINFO; +pub type LPSCROLLBARINFO = *mut SCROLLBARINFO; +STRUCT!{struct SCROLLINFO { + cbSize: ::UINT, + fMask: ::UINT, + nMin: ::c_int, + nMax: ::c_int, + nPage: ::UINT, + nPos: ::c_int, + nTrackPos: ::c_int, +}} +pub type LPSCROLLINFO = *mut SCROLLINFO; +pub type LPCSCROLLINFO = *const SCROLLINFO; +STRUCT!{struct SIZE { + cx: ::LONG, + cy: ::LONG, +}} +pub type PSIZE = *mut SIZE; +pub type LPSIZE = *mut SIZE; +pub type SIZEL = SIZE; +pub type PSIZEL = *mut SIZEL; +pub type LPSIZEL = *mut SIZEL; +//1913 +pub const UNICODE_NOCHAR: ::WPARAM = 0xffff; +pub type HDWP = *mut ::HANDLE; +//2193 +pub const WHEEL_DELTA: ::DWORD = 120; +//2206 +pub const XBUTTON1: ::DWORD = 0x0001; +pub const XBUTTON2: ::DWORD = 0x0002; +//2392 +pub const MK_LBUTTON: ::WPARAM = 0x0001; +pub const MK_RBUTTON: ::WPARAM = 0x0002; +pub const MK_SHIFT: ::WPARAM = 0x0004; +pub const MK_CONTROL: ::WPARAM = 0x0008; +pub const MK_MBUTTON: ::WPARAM = 0x0010; +pub const MK_XBUTTON1: ::WPARAM = 0x0020; +pub const MK_XBUTTON2: ::WPARAM = 0x0040; +//2408 +pub const TME_HOVER: ::DWORD = 0x0000_0001; +pub const TME_LEAVE: ::DWORD = 0x0000_0002; +pub const TME_NONCLIENT: ::DWORD = 0x0000_0010; +pub const TME_QUERY: ::DWORD = 0x4000_0000; +pub const TME_CANCEL: ::DWORD = 0x8000_0000; +pub const HWND_BROADCAST: ::HWND = 0xFFFF as ::HWND; +pub const HWND_MESSAGE: ::HWND = -3isize as ::HWND; +STRUCT!{struct TRACKMOUSEEVENT { + cbSize: ::DWORD, + dwFlags: ::DWORD, + hwndTrack: ::HWND, + dwHoverTime: ::DWORD, +}} +pub type LPTRACKMOUSEEVENT = *mut TRACKMOUSEEVENT; +//2575 +STRUCT!{nodebug struct WINDOWPOS { + hwnd: ::HWND, + hwndInsertAfter: ::HWND, + x: ::c_int, + y: ::c_int, + cx: ::c_int, + cy: ::c_int, + flags: ::UINT, +}} +pub type LPWINDOWPOS = *mut WINDOWPOS; +pub type PWINDOWPOS = *mut WINDOWPOS; +//3082 +STRUCT!{struct CREATESTRUCTA { + lpCreateParams: ::LPVOID, + hInstance: ::HINSTANCE, + hMenu: ::HMENU, + hwndParent: ::HWND, + cy: ::c_int, + cx: ::c_int, + y: ::c_int, + x: ::c_int, + style: ::LONG, + lpszName: ::LPCSTR, + lpszClass: ::LPCSTR, + dwExStyle: ::DWORD, +}} +pub type LPCREATESTRUCTA = *mut CREATESTRUCTA; +STRUCT!{struct CREATESTRUCTW { + lpCreateParams: ::LPVOID, + hInstance: ::HINSTANCE, + hMenu: ::HMENU, + hwndParent: ::HWND, + cy: ::c_int, + cx: ::c_int, + y: ::c_int, + x: ::c_int, + style: ::LONG, + lpszName: ::LPCWSTR, + lpszClass: ::LPCWSTR, + dwExStyle: ::DWORD, +}} +pub type LPCREATESTRUCTW = *mut CREATESTRUCTW; +//3145 +STRUCT!{struct NMHDR { + hwndFrom: ::HWND, + idFrom: ::UINT_PTR, + code: ::UINT, // NM_ code +}} +pub type LPNMHDR = *mut NMHDR; +//3400 +pub const PM_NOREMOVE: ::UINT = 0x0000; +pub const PM_REMOVE: ::UINT = 0x0001; +pub const PM_NOYIELD: ::UINT = 0x0002; +pub const PM_QS_INPUT: ::UINT = QS_INPUT << 16; +pub const PM_QS_POSTMESSAGE: ::UINT = (QS_POSTMESSAGE | QS_HOTKEY | QS_TIMER) << 16; +pub const PM_QS_PAINT: ::UINT = QS_PAINT << 16; +pub const PM_QS_SENDMESSAGE: ::UINT = QS_SENDMESSAGE << 16; +// +pub const LWA_COLORKEY: ::DWORD = 0x00000001; +pub const LWA_ALPHA: ::DWORD = 0x00000002; +//3469 +pub const EWX_LOGOFF: ::UINT = 0x00000000; +pub const EWX_SHUTDOWN: ::UINT = 0x00000001; +pub const EWX_REBOOT: ::UINT = 0x00000002; +pub const EWX_FORCE: ::UINT = 0x00000004; +pub const EWX_POWEROFF: ::UINT = 0x00000008; +pub const EWX_FORCEIFHUNG: ::UINT = 0x00000010; +pub const EWX_QUICKRESOLVE: ::UINT = 0x00000020; +pub const EWX_RESTARTAPPS: ::UINT = 0x00000040; +pub const EWX_HYBRID_SHUTDOWN: ::UINT = 0x00400000; +pub const EWX_BOOTOPTIONS: ::UINT = 0x01000000; +//4054 (Win 7 SDK) +STRUCT!{struct FLASHWINFO { + cbSize: ::UINT, + hwnd: ::HWND, + dwFlags: ::DWORD, + uCount: ::UINT, + dwTimeout: ::DWORD, +}} +pub type PFLASHWINFO = *mut FLASHWINFO; +pub const FLASHW_STOP: ::DWORD = 0; +pub const FLASHW_CAPTION: ::DWORD = 0x00000001; +pub const FLASHW_TRAY: ::DWORD = 0x00000002; +pub const FLASHW_ALL: ::DWORD = FLASHW_CAPTION | FLASHW_TRAY; +pub const FLASHW_TIMER: ::DWORD = 0x00000004; +pub const FLASHW_TIMERNOFG: ::DWORD = 0x0000000C; +// 4674 +pub const HWND_TOP: ::HWND = 0 as ::HWND; +pub const HWND_BOTTOM: ::HWND = 1 as ::HWND; +pub const HWND_TOPMOST: ::HWND = -1isize as ::HWND; +pub const HWND_NOTOPMOST: ::HWND = -2isize as ::HWND; +//5499 +pub const MAPVK_VK_TO_VSC: ::UINT = 0; +pub const MAPVK_VSC_TO_VK: ::UINT = 1; +pub const MAPVK_VK_TO_CHAR: ::UINT = 2; +pub const MAPVK_VSC_TO_VK_EX: ::UINT = 3; +pub const MAPVK_VK_TO_VSC_EX: ::UINT = 4; +//5741 +pub const KEYEVENTF_EXTENDEDKEY: ::DWORD = 0x0001; +pub const KEYEVENTF_KEYUP: ::DWORD = 0x0002; +pub const KEYEVENTF_UNICODE: ::DWORD = 0x0004; +pub const KEYEVENTF_SCANCODE: ::DWORD = 0x0008; +pub const MOUSEEVENTF_MOVE: ::DWORD = 0x0001; +pub const MOUSEEVENTF_LEFTDOWN: ::DWORD = 0x0002; +pub const MOUSEEVENTF_LEFTUP: ::DWORD = 0x0004; +pub const MOUSEEVENTF_RIGHTDOWN: ::DWORD = 0x0008; +pub const MOUSEEVENTF_RIGHTUP: ::DWORD = 0x0010; +pub const MOUSEEVENTF_MIDDLEDOWN: ::DWORD = 0x0020; +pub const MOUSEEVENTF_MIDDLEUP: ::DWORD = 0x0040; +pub const MOUSEEVENTF_XDOWN: ::DWORD = 0x0080; +pub const MOUSEEVENTF_XUP: ::DWORD = 0x0100; +pub const MOUSEEVENTF_WHEEL: ::DWORD = 0x0800; +pub const MOUSEEVENTF_HWHEEL: ::DWORD = 0x01000; +pub const MOUSEEVENTF_MOVE_NOCOALESCE: ::DWORD = 0x2000; +pub const MOUSEEVENTF_VIRTUALDESK: ::DWORD = 0x4000; +pub const MOUSEEVENTF_ABSOLUTE: ::DWORD = 0x8000; +STRUCT!{struct MOUSEINPUT { + dx: ::LONG, + dy: ::LONG, + mouseData: ::DWORD, + dwFlags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PMOUSEINPUT = *mut MOUSEINPUT; +pub type LPMOUSEINPUT = *mut MOUSEINPUT; +STRUCT!{struct KEYBDINPUT { + wVk: ::WORD, + wScan: ::WORD, + dwFlags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PKEYBDINPUT = *mut KEYBDINPUT; +pub type LPKEYBDINPUT = *mut KEYBDINPUT; +STRUCT!{struct HARDWAREINPUT { + uMsg: ::DWORD, + wParamL: ::WORD, + wParamH: ::WORD, +}} +pub type PHARDWAREINPUT = *mut HARDWAREINPUT; +pub type LPHARDWAREINPUT= *mut HARDWAREINPUT; +pub const INPUT_MOUSE: ::DWORD = 0; +pub const INPUT_KEYBOARD: ::DWORD = 1; +pub const INPUT_HARDWARE: ::DWORD = 2; +#[cfg(target_arch = "x86")] +STRUCT!{struct INPUT { + type_: ::DWORD, + u: [u32; 6], +}} +#[cfg(target_arch = "x86_64")] +STRUCT!{struct INPUT { + type_: ::DWORD, + u: [u64; 4], +}} +UNION!{INPUT, u, mi, mi_mut, MOUSEINPUT} +UNION!{INPUT, u, ki, ki_mut, KEYBDINPUT} +UNION!{INPUT, u, hi, hi_mut, HARDWAREINPUT} +pub type PINPUT = *mut INPUT; +pub type LPINPUT = *mut INPUT; +// if WINVER >= 0x0601 +DECLARE_HANDLE!(HTOUCHINPUT, HTOUCHINPUT__); +STRUCT!{struct TOUCHINPUT { + x: ::LONG, + y: ::LONG, + hSource: ::HANDLE, + dwID: ::DWORD, + dwFlags: ::DWORD, + dwMask: ::DWORD, + dwTime: ::DWORD, + dwExtraInfo: ::ULONG_PTR, + cxContact: ::DWORD, + cyContact: ::DWORD, +}} +pub type PTOUCHINPUT = *mut TOUCHINPUT; +pub type PCTOUCHINPUT = *const TOUCHINPUT; +//Touch input flag values (TOUCHINPUT.dwFlags) +pub const TOUCHEVENTF_MOVE: ::DWORD = 0x0001; +pub const TOUCHEVENTF_DOWN: ::DWORD = 0x0002; +pub const TOUCHEVENTF_UP: ::DWORD = 0x0004; +pub const TOUCHEVENTF_INRANGE: ::DWORD = 0x0008; +pub const TOUCHEVENTF_PRIMARY: ::DWORD = 0x0010; +pub const TOUCHEVENTF_NOCOALESCE: ::DWORD = 0x0020; +pub const TOUCHEVENTF_PEN: ::DWORD = 0x0040; +pub const TOUCHEVENTF_PALM: ::DWORD = 0x0080; +//Touch input mask values (TOUCHINPUT.dwMask) +pub const TOUCHINPUTMASKF_TIMEFROMSYSTEM: ::DWORD = 0x0001; +pub const TOUCHINPUTMASKF_EXTRAINFO: ::DWORD = 0x0002; +pub const TOUCHINPUTMASKF_CONTACTAREA: ::DWORD = 0x0004; +//RegisterTouchWindow flag values +pub const TWF_FINETOUCH: ::ULONG = 0x00000001; +pub const TWF_WANTPALM: ::ULONG = 0x00000002; +// end if WINVER >= 0x0601 +//Indices for GetWindowLong etc. +pub const GWL_EXSTYLE: ::c_int = -20; +pub const GWL_STYLE: ::c_int = -16; +pub const GWL_WNDPROC: ::c_int = -4; +pub const GWLP_WNDPROC: ::c_int = -4; +pub const GWL_HINSTANCE: ::c_int = -6; +pub const GWLP_HINSTANCE: ::c_int = -6; +pub const GWL_HWNDPARENT: ::c_int = -8; +pub const GWLP_HWNDPARENT: ::c_int = -8; +pub const GWL_ID: ::c_int = -12; +pub const GWLP_ID: ::c_int = -12; +pub const GWL_USERDATA: ::c_int = -21; +pub const GWLP_USERDATA: ::c_int = -21; +//5976 +ENUM!{enum POINTER_INPUT_TYPE { + PT_POINTER = 0x00000001, + PT_TOUCH = 0x00000002, + PT_PEN = 0x00000003, + PT_MOUSE = 0x00000004, + PT_TOUCHPAD = 0x00000005, +}} +//6566 +// flags for MsgWaitForMultipleObjectsEx +pub const MWMO_WAITALL: ::DWORD = 0x0001; +pub const MWMO_ALERTABLE: ::DWORD = 0x0002; +pub const MWMO_INPUTAVAILABLE: ::DWORD = 0x0004; +//6573 +pub const QS_KEY: ::UINT = 0x0001; +pub const QS_MOUSEMOVE: ::UINT = 0x0002; +pub const QS_MOUSEBUTTON: ::UINT = 0x0004; +pub const QS_POSTMESSAGE: ::UINT = 0x0008; +pub const QS_TIMER: ::UINT = 0x0010; +pub const QS_PAINT: ::UINT = 0x0020; +pub const QS_SENDMESSAGE: ::UINT = 0x0040; +pub const QS_HOTKEY: ::UINT = 0x0080; +pub const QS_ALLPOSTMESSAGE: ::UINT = 0x0100; +pub const QS_RAWINPUT: ::UINT = 0x0400; +pub const QS_TOUCH: ::UINT = 0x0800; +pub const QS_POINTER: ::UINT = 0x1000; +pub const QS_MOUSE: ::UINT = QS_MOUSEMOVE | QS_MOUSEBUTTON; +pub const QS_INPUT: ::UINT = QS_MOUSE | QS_KEY | QS_RAWINPUT | QS_TOUCH | QS_POINTER; +pub const QS_ALLEVENTS: ::UINT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY; +pub const QS_ALLINPUT: ::UINT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER + | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE; +//6789 +pub const SM_CXSCREEN: ::c_int = 0; +pub const SM_CYSCREEN: ::c_int = 1; +pub const SM_CXVSCROLL: ::c_int = 2; +pub const SM_CYHSCROLL: ::c_int = 3; +pub const SM_CYCAPTION: ::c_int = 4; +pub const SM_CXBORDER: ::c_int = 5; +pub const SM_CYBORDER: ::c_int = 6; +pub const SM_CXDLGFRAME: ::c_int = 7; +pub const SM_CYDLGFRAME: ::c_int = 8; +pub const SM_CYVTHUMB: ::c_int = 9; +pub const SM_CXHTHUMB: ::c_int = 10; +pub const SM_CXICON: ::c_int = 11; +pub const SM_CYICON: ::c_int = 12; +pub const SM_CXCURSOR: ::c_int = 13; +pub const SM_CYCURSOR: ::c_int = 14; +pub const SM_CYMENU: ::c_int = 15; +pub const SM_CXFULLSCREEN: ::c_int = 16; +pub const SM_CYFULLSCREEN: ::c_int = 17; +pub const SM_CYKANJIWINDOW: ::c_int = 18; +pub const SM_MOUSEPRESENT: ::c_int = 19; +pub const SM_CYVSCROLL: ::c_int = 20; +pub const SM_CXHSCROLL: ::c_int = 21; +pub const SM_DEBUG: ::c_int = 22; +pub const SM_SWAPBUTTON: ::c_int = 23; +pub const SM_RESERVED1: ::c_int = 24; +pub const SM_RESERVED2: ::c_int = 25; +pub const SM_RESERVED3: ::c_int = 26; +pub const SM_RESERVED4: ::c_int = 27; +pub const SM_CXMIN: ::c_int = 28; +pub const SM_CYMIN: ::c_int = 29; +pub const SM_CXSIZE: ::c_int = 30; +pub const SM_CYSIZE: ::c_int = 31; +pub const SM_CXFRAME: ::c_int = 32; +pub const SM_CYFRAME: ::c_int = 33; +pub const SM_CXMINTRACK: ::c_int = 34; +pub const SM_CYMINTRACK: ::c_int = 35; +pub const SM_CXDOUBLECLK: ::c_int = 36; +pub const SM_CYDOUBLECLK: ::c_int = 37; +pub const SM_CXICONSPACING: ::c_int = 38; +pub const SM_CYICONSPACING: ::c_int = 39; +pub const SM_MENUDROPALIGNMENT: ::c_int = 40; +pub const SM_PENWINDOWS: ::c_int = 41; +pub const SM_DBCSENABLED: ::c_int = 42; +pub const SM_CMOUSEBUTTONS: ::c_int = 43; +pub const SM_CXFIXEDFRAME: ::c_int = SM_CXDLGFRAME; +pub const SM_CYFIXEDFRAME: ::c_int = SM_CYDLGFRAME; +pub const SM_CXSIZEFRAME: ::c_int = SM_CXFRAME; +pub const SM_CYSIZEFRAME: ::c_int = SM_CYFRAME; +pub const SM_SECURE: ::c_int = 44; +pub const SM_CXEDGE: ::c_int = 45; +pub const SM_CYEDGE: ::c_int = 46; +pub const SM_CXMINSPACING: ::c_int = 47; +pub const SM_CYMINSPACING: ::c_int = 48; +pub const SM_CXSMICON: ::c_int = 49; +pub const SM_CYSMICON: ::c_int = 50; +pub const SM_CYSMCAPTION: ::c_int = 51; +pub const SM_CXSMSIZE: ::c_int = 52; +pub const SM_CYSMSIZE: ::c_int = 53; +pub const SM_CXMENUSIZE: ::c_int = 54; +pub const SM_CYMENUSIZE: ::c_int = 55; +pub const SM_ARRANGE: ::c_int = 56; +pub const SM_CXMINIMIZED: ::c_int = 57; +pub const SM_CYMINIMIZED: ::c_int = 58; +pub const SM_CXMAXTRACK: ::c_int = 59; +pub const SM_CYMAXTRACK: ::c_int = 60; +pub const SM_CXMAXIMIZED: ::c_int = 61; +pub const SM_CYMAXIMIZED: ::c_int = 62; +pub const SM_NETWORK: ::c_int = 63; +pub const SM_CLEANBOOT: ::c_int = 67; +pub const SM_CXDRAG: ::c_int = 68; +pub const SM_CYDRAG: ::c_int = 69; +pub const SM_SHOWSOUNDS: ::c_int = 70; +pub const SM_CXMENUCHECK: ::c_int = 71; +pub const SM_CYMENUCHECK: ::c_int = 72; +pub const SM_SLOWMACHINE: ::c_int = 73; +pub const SM_MIDEASTENABLED: ::c_int = 74; +pub const SM_MOUSEWHEELPRESENT: ::c_int = 75; +pub const SM_XVIRTUALSCREEN: ::c_int = 76; +pub const SM_YVIRTUALSCREEN: ::c_int = 77; +pub const SM_CXVIRTUALSCREEN: ::c_int = 78; +pub const SM_CYVIRTUALSCREEN: ::c_int = 79; +pub const SM_CMONITORS: ::c_int = 80; +pub const SM_SAMEDISPLAYFORMAT: ::c_int = 81; +pub const SM_IMMENABLED: ::c_int = 82; +pub const SM_CXFOCUSBORDER: ::c_int = 83; +pub const SM_CYFOCUSBORDER: ::c_int = 84; +pub const SM_TABLETPC: ::c_int = 86; +pub const SM_MEDIACENTER: ::c_int = 87; +pub const SM_STARTER: ::c_int = 88; +pub const SM_SERVERR2: ::c_int = 89; +pub const SM_MOUSEHORIZONTALWHEELPRESENT: ::c_int = 91; +pub const SM_CXPADDEDBORDER: ::c_int = 92; +pub const SM_DIGITIZER: ::c_int = 94; +pub const SM_MAXIMUMTOUCHES: ::c_int = 95; +pub const SM_CMETRICS: ::c_int = 97; +pub const SM_REMOTESESSION: ::c_int = 0x1000; +pub const SM_SHUTTINGDOWN: ::c_int = 0x2000; +pub const SM_REMOTECONTROL: ::c_int = 0x2001; +pub const SM_CARETBLINKINGENABLED: ::c_int = 0x2002; +pub const SM_CONVERTIBLESLATEMODE: ::c_int = 0x2003; +pub const SM_SYSTEMDOCKED: ::c_int = 0x2004; +//8855 (Win 7 SDK) +STRUCT!{struct ICONINFO { + fIcon: ::BOOL, + xHotspot: ::DWORD, + yHotspot: ::DWORD, + hbmMask: ::HBITMAP, + hbmColor: ::HBITMAP, +}} +pub type PICONINFO = *mut ICONINFO; +//9066 +// Color indexes for use in GetSysColor and SetSysColor +// 0-18 (after incrementing) are also valid in RegisterClass's WNDCLASS +pub const COLOR_SCROLLBAR: ::c_int = 0; +pub const COLOR_BACKGROUND: ::c_int = 1; +pub const COLOR_ACTIVECAPTION: ::c_int = 2; +pub const COLOR_INACTIVECAPTION: ::c_int = 3; +pub const COLOR_MENU: ::c_int = 4; +pub const COLOR_WINDOW: ::c_int = 5; +pub const COLOR_WINDOWFRAME: ::c_int = 6; +pub const COLOR_MENUTEXT: ::c_int = 7; +pub const COLOR_WINDOWTEXT: ::c_int = 8; +pub const COLOR_CAPTIONTEXT: ::c_int = 9; +pub const COLOR_ACTIVEBORDER: ::c_int = 10; +pub const COLOR_INACTIVEBORDER: ::c_int = 11; +pub const COLOR_APPWORKSPACE: ::c_int = 12; +pub const COLOR_HIGHLIGHT: ::c_int = 13; +pub const COLOR_HIGHLIGHTTEXT: ::c_int = 14; +pub const COLOR_BTNFACE: ::c_int = 15; +pub const COLOR_BTNSHADOW: ::c_int = 16; +pub const COLOR_GRAYTEXT: ::c_int = 17; +pub const COLOR_BTNTEXT: ::c_int = 18; +pub const COLOR_INACTIVECAPTIONTEXT: ::c_int = 19; +pub const COLOR_BTNHIGHLIGHT: ::c_int = 20; +// Introduced in Windows 95 (winver 0x0400): +pub const COLOR_3DDKSHADOW: ::c_int = 21; +pub const COLOR_3DLIGHT: ::c_int = 22; +pub const COLOR_INFOTEXT: ::c_int = 23; +pub const COLOR_INFOBK: ::c_int = 24; +pub const COLOR_DESKTOP: ::c_int = COLOR_BACKGROUND; +pub const COLOR_3DFACE: ::c_int = COLOR_BTNFACE; +pub const COLOR_3DSHADOW: ::c_int = COLOR_BTNSHADOW; +pub const COLOR_3DHIGHLIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +pub const COLOR_3DHILIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +pub const COLOR_BTNHILIGHT: ::c_int = COLOR_BTNHIGHLIGHT; +// Introduced in Windows 2000 (winver 0x0500) +pub const COLOR_HOTLIGHT: ::c_int = 26; +pub const COLOR_GRADIENTACTIVECAPTION: ::c_int = 27; +pub const COLOR_GRADIENTINACTIVECAPTION: ::c_int = 28; +// Introduced in Windows XP (winver 0x0501) +pub const COLOR_MENUHILIGHT: ::c_int = 29; +pub const COLOR_MENUBAR: ::c_int = 30; +//10069 +pub const IDC_ARROW: ::LPCWSTR = 32512 as ::LPCWSTR; +pub const IDC_IBEAM: ::LPCWSTR = 32513 as ::LPCWSTR; +pub const IDC_WAIT: ::LPCWSTR = 32514 as ::LPCWSTR; +pub const IDC_CROSS: ::LPCWSTR = 32515 as ::LPCWSTR; +pub const IDC_UPARROW: ::LPCWSTR = 32516 as ::LPCWSTR; +pub const IDC_SIZE: ::LPCWSTR = 32640 as ::LPCWSTR; +pub const IDC_ICON: ::LPCWSTR = 32641 as ::LPCWSTR; +pub const IDC_SIZENWSE: ::LPCWSTR = 32642 as ::LPCWSTR; +pub const IDC_SIZENESW: ::LPCWSTR = 32643 as ::LPCWSTR; +pub const IDC_SIZEWE: ::LPCWSTR = 32644 as ::LPCWSTR; +pub const IDC_SIZENS: ::LPCWSTR = 32645 as ::LPCWSTR; +pub const IDC_SIZEALL: ::LPCWSTR = 32646 as ::LPCWSTR; +pub const IDC_NO: ::LPCWSTR = 32648 as ::LPCWSTR; +pub const IDC_HAND: ::LPCWSTR = 32649 as ::LPCWSTR; +pub const IDC_APPSTARTING: ::LPCWSTR = 32650 as ::LPCWSTR; +pub const IDC_HELP: ::LPCWSTR = 32651 as ::LPCWSTR; +//10492 +pub const IDI_APPLICATION: ::LPCWSTR = 32512 as ::LPCWSTR; +pub const IDI_HAND: ::LPCWSTR = 32513 as ::LPCWSTR; +pub const IDI_QUESTION: ::LPCWSTR = 32514 as ::LPCWSTR; +pub const IDI_EXCLAMATION: ::LPCWSTR = 32515 as ::LPCWSTR; +pub const IDI_ASTERISK: ::LPCWSTR = 32516 as ::LPCWSTR; +pub const IDI_WINLOGO: ::LPCWSTR = 32517 as ::LPCWSTR; +pub const IDI_SHIELD: ::LPCWSTR = 32518 as ::LPCWSTR; +pub const IDI_WARNING: ::LPCWSTR = IDI_EXCLAMATION; +pub const IDI_ERROR: ::LPCWSTR = IDI_HAND; +pub const IDI_INFORMATION: ::LPCWSTR = IDI_ASTERISK; +pub const SPI_GETBEEP: ::UINT = 0x0001; +pub const SPI_SETBEEP: ::UINT = 0x0002; +pub const SPI_GETMOUSE: ::UINT = 0x0003; +pub const SPI_SETMOUSE: ::UINT = 0x0004; +pub const SPI_GETBORDER: ::UINT = 0x0005; +pub const SPI_SETBORDER: ::UINT = 0x0006; +pub const SPI_GETKEYBOARDSPEED: ::UINT = 0x000A; +pub const SPI_SETKEYBOARDSPEED: ::UINT = 0x000B; +pub const SPI_LANGDRIVER: ::UINT = 0x000C; +pub const SPI_ICONHORIZONTALSPACING: ::UINT = 0x000D; +pub const SPI_GETSCREENSAVETIMEOUT: ::UINT = 0x000E; +pub const SPI_SETSCREENSAVETIMEOUT: ::UINT = 0x000F; +pub const SPI_GETSCREENSAVEACTIVE: ::UINT = 0x0010; +pub const SPI_SETSCREENSAVEACTIVE: ::UINT = 0x0011; +pub const SPI_GETGRIDGRANULARITY: ::UINT = 0x0012; +pub const SPI_SETGRIDGRANULARITY: ::UINT = 0x0013; +pub const SPI_SETDESKWALLPAPER: ::UINT = 0x0014; +pub const SPI_SETDESKPATTERN: ::UINT = 0x0015; +pub const SPI_GETKEYBOARDDELAY: ::UINT = 0x0016; +pub const SPI_SETKEYBOARDDELAY: ::UINT = 0x0017; +pub const SPI_ICONVERTICALSPACING: ::UINT = 0x0018; +pub const SPI_GETICONTITLEWRAP: ::UINT = 0x0019; +pub const SPI_SETICONTITLEWRAP: ::UINT = 0x001A; +pub const SPI_GETMENUDROPALIGNMENT: ::UINT = 0x001B; +pub const SPI_SETMENUDROPALIGNMENT: ::UINT = 0x001C; +pub const SPI_SETDOUBLECLKWIDTH: ::UINT = 0x001D; +pub const SPI_SETDOUBLECLKHEIGHT: ::UINT = 0x001E; +pub const SPI_GETICONTITLELOGFONT: ::UINT = 0x001F; +pub const SPI_SETDOUBLECLICKTIME: ::UINT = 0x0020; +pub const SPI_SETMOUSEBUTTONSWAP: ::UINT = 0x0021; +pub const SPI_SETICONTITLELOGFONT: ::UINT = 0x0022; +pub const SPI_GETFASTTASKSWITCH: ::UINT = 0x0023; +pub const SPI_SETFASTTASKSWITCH: ::UINT = 0x0024; +pub const SPI_SETDRAGFULLWINDOWS: ::UINT = 0x0025; +pub const SPI_GETDRAGFULLWINDOWS: ::UINT = 0x0026; +pub const SPI_GETNONCLIENTMETRICS: ::UINT = 0x0029; +pub const SPI_SETNONCLIENTMETRICS: ::UINT = 0x002A; +pub const SPI_GETMINIMIZEDMETRICS: ::UINT = 0x002B; +pub const SPI_SETMINIMIZEDMETRICS: ::UINT = 0x002C; +pub const SPI_GETICONMETRICS: ::UINT = 0x002D; +pub const SPI_SETICONMETRICS: ::UINT = 0x002E; +pub const SPI_SETWORKAREA: ::UINT = 0x002F; +pub const SPI_GETWORKAREA: ::UINT = 0x0030; +pub const SPI_SETPENWINDOWS: ::UINT = 0x0031; +pub const SPI_GETHIGHCONTRAST: ::UINT = 0x0042; +pub const SPI_SETHIGHCONTRAST: ::UINT = 0x0043; +pub const SPI_GETKEYBOARDPREF: ::UINT = 0x0044; +pub const SPI_SETKEYBOARDPREF: ::UINT = 0x0045; +pub const SPI_GETSCREENREADER: ::UINT = 0x0046; +pub const SPI_SETSCREENREADER: ::UINT = 0x0047; +pub const SPI_GETANIMATION: ::UINT = 0x0048; +pub const SPI_SETANIMATION: ::UINT = 0x0049; +pub const SPI_GETFONTSMOOTHING: ::UINT = 0x004A; +pub const SPI_SETFONTSMOOTHING: ::UINT = 0x004B; +pub const SPI_SETDRAGWIDTH: ::UINT = 0x004C; +pub const SPI_SETDRAGHEIGHT: ::UINT = 0x004D; +pub const SPI_SETHANDHELD: ::UINT = 0x004E; +pub const SPI_GETLOWPOWERTIMEOUT: ::UINT = 0x004F; +pub const SPI_GETPOWEROFFTIMEOUT: ::UINT = 0x0050; +pub const SPI_SETLOWPOWERTIMEOUT: ::UINT = 0x0051; +pub const SPI_SETPOWEROFFTIMEOUT: ::UINT = 0x0052; +pub const SPI_GETLOWPOWERACTIVE: ::UINT = 0x0053; +pub const SPI_GETPOWEROFFACTIVE: ::UINT = 0x0054; +pub const SPI_SETLOWPOWERACTIVE: ::UINT = 0x0055; +pub const SPI_SETPOWEROFFACTIVE: ::UINT = 0x0056; +pub const SPI_SETCURSORS: ::UINT = 0x0057; +pub const SPI_SETICONS: ::UINT = 0x0058; +pub const SPI_GETDEFAULTINPUTLANG: ::UINT = 0x0059; +pub const SPI_SETDEFAULTINPUTLANG: ::UINT = 0x005A; +pub const SPI_SETLANGTOGGLE: ::UINT = 0x005B; +pub const SPI_GETWINDOWSEXTENSION: ::UINT = 0x005C; +pub const SPI_SETMOUSETRAILS: ::UINT = 0x005D; +pub const SPI_GETMOUSETRAILS: ::UINT = 0x005E; +pub const SPI_SETSCREENSAVERRUNNING: ::UINT = 0x0061; +pub const SPI_SCREENSAVERRUNNING: ::UINT = SPI_SETSCREENSAVERRUNNING; +pub const SPI_GETFILTERKEYS: ::UINT = 0x0032; +pub const SPI_SETFILTERKEYS: ::UINT = 0x0033; +pub const SPI_GETTOGGLEKEYS: ::UINT = 0x0034; +pub const SPI_SETTOGGLEKEYS: ::UINT = 0x0035; +pub const SPI_GETMOUSEKEYS: ::UINT = 0x0036; +pub const SPI_SETMOUSEKEYS: ::UINT = 0x0037; +pub const SPI_GETSHOWSOUNDS: ::UINT = 0x0038; +pub const SPI_SETSHOWSOUNDS: ::UINT = 0x0039; +pub const SPI_GETSTICKYKEYS: ::UINT = 0x003A; +pub const SPI_SETSTICKYKEYS: ::UINT = 0x003B; +pub const SPI_GETACCESSTIMEOUT: ::UINT = 0x003C; +pub const SPI_SETACCESSTIMEOUT: ::UINT = 0x003D; +pub const SPI_GETSERIALKEYS: ::UINT = 0x003E; +pub const SPI_SETSERIALKEYS: ::UINT = 0x003F; +pub const SPI_GETSOUNDSENTRY: ::UINT = 0x0040; +pub const SPI_SETSOUNDSENTRY: ::UINT = 0x0041; +pub const SPI_GETSNAPTODEFBUTTON: ::UINT = 0x005F; +pub const SPI_SETSNAPTODEFBUTTON: ::UINT = 0x0060; +pub const SPI_GETMOUSEHOVERWIDTH: ::UINT = 0x0062; +pub const SPI_SETMOUSEHOVERWIDTH: ::UINT = 0x0063; +pub const SPI_GETMOUSEHOVERHEIGHT: ::UINT = 0x0064; +pub const SPI_SETMOUSEHOVERHEIGHT: ::UINT = 0x0065; +pub const SPI_GETMOUSEHOVERTIME: ::UINT = 0x0066; +pub const SPI_SETMOUSEHOVERTIME: ::UINT = 0x0067; +pub const SPI_GETWHEELSCROLLLINES: ::UINT = 0x0068; +pub const SPI_SETWHEELSCROLLLINES: ::UINT = 0x0069; +pub const SPI_GETMENUSHOWDELAY: ::UINT = 0x006A; +pub const SPI_SETMENUSHOWDELAY: ::UINT = 0x006B; +pub const SPI_GETWHEELSCROLLCHARS: ::UINT = 0x006C; +pub const SPI_SETWHEELSCROLLCHARS: ::UINT = 0x006D; +pub const SPI_GETSHOWIMEUI: ::UINT = 0x006E; +pub const SPI_SETSHOWIMEUI: ::UINT = 0x006F; +pub const SPI_GETMOUSESPEED: ::UINT = 0x0070; +pub const SPI_SETMOUSESPEED: ::UINT = 0x0071; +pub const SPI_GETSCREENSAVERRUNNING: ::UINT = 0x0072; +pub const SPI_GETDESKWALLPAPER: ::UINT = 0x0073; +pub const SPI_GETAUDIODESCRIPTION: ::UINT = 0x0074; +pub const SPI_SETAUDIODESCRIPTION: ::UINT = 0x0075; +pub const SPI_GETSCREENSAVESECURE: ::UINT = 0x0076; +pub const SPI_SETSCREENSAVESECURE: ::UINT = 0x0077; +pub const SPI_GETHUNGAPPTIMEOUT: ::UINT = 0x0078; +pub const SPI_SETHUNGAPPTIMEOUT: ::UINT = 0x0079; +pub const SPI_GETWAITTOKILLTIMEOUT: ::UINT = 0x007A; +pub const SPI_SETWAITTOKILLTIMEOUT: ::UINT = 0x007B; +pub const SPI_GETWAITTOKILLSERVICETIMEOUT: ::UINT = 0x007C; +pub const SPI_SETWAITTOKILLSERVICETIMEOUT: ::UINT = 0x007D; +pub const SPI_GETMOUSEDOCKTHRESHOLD: ::UINT = 0x007E; +pub const SPI_SETMOUSEDOCKTHRESHOLD: ::UINT = 0x007F; +pub const SPI_GETPENDOCKTHRESHOLD: ::UINT = 0x0080; +pub const SPI_SETPENDOCKTHRESHOLD: ::UINT = 0x0081; +pub const SPI_GETWINARRANGING: ::UINT = 0x0082; +pub const SPI_SETWINARRANGING: ::UINT = 0x0083; +pub const SPI_GETMOUSEDRAGOUTTHRESHOLD: ::UINT = 0x0084; +pub const SPI_SETMOUSEDRAGOUTTHRESHOLD: ::UINT = 0x0085; +pub const SPI_GETPENDRAGOUTTHRESHOLD: ::UINT = 0x0086; +pub const SPI_SETPENDRAGOUTTHRESHOLD: ::UINT = 0x0087; +pub const SPI_GETMOUSESIDEMOVETHRESHOLD: ::UINT = 0x0088; +pub const SPI_SETMOUSESIDEMOVETHRESHOLD: ::UINT = 0x0089; +pub const SPI_GETPENSIDEMOVETHRESHOLD: ::UINT = 0x008A; +pub const SPI_SETPENSIDEMOVETHRESHOLD: ::UINT = 0x008B; +pub const SPI_GETDRAGFROMMAXIMIZE: ::UINT = 0x008C; +pub const SPI_SETDRAGFROMMAXIMIZE: ::UINT = 0x008D; +pub const SPI_GETSNAPSIZING: ::UINT = 0x008E; +pub const SPI_SETSNAPSIZING: ::UINT = 0x008F; +pub const SPI_GETDOCKMOVING: ::UINT = 0x0090; +pub const SPI_SETDOCKMOVING: ::UINT = 0x0091; +pub const SPI_GETACTIVEWINDOWTRACKING: ::UINT = 0x1000; +pub const SPI_SETACTIVEWINDOWTRACKING: ::UINT = 0x1001; +pub const SPI_GETMENUANIMATION: ::UINT = 0x1002; +pub const SPI_SETMENUANIMATION: ::UINT = 0x1003; +pub const SPI_GETCOMBOBOXANIMATION: ::UINT = 0x1004; +pub const SPI_SETCOMBOBOXANIMATION: ::UINT = 0x1005; +pub const SPI_GETLISTBOXSMOOTHSCROLLING: ::UINT = 0x1006; +pub const SPI_SETLISTBOXSMOOTHSCROLLING: ::UINT = 0x1007; +pub const SPI_GETGRADIENTCAPTIONS: ::UINT = 0x1008; +pub const SPI_SETGRADIENTCAPTIONS: ::UINT = 0x1009; +pub const SPI_GETKEYBOARDCUES: ::UINT = 0x100A; +pub const SPI_SETKEYBOARDCUES: ::UINT = 0x100B; +pub const SPI_GETMENUUNDERLINES: ::UINT = SPI_GETKEYBOARDCUES; +pub const SPI_SETMENUUNDERLINES: ::UINT = SPI_SETKEYBOARDCUES; +pub const SPI_GETACTIVEWNDTRKZORDER: ::UINT = 0x100C; +pub const SPI_SETACTIVEWNDTRKZORDER: ::UINT = 0x100D; +pub const SPI_GETHOTTRACKING: ::UINT = 0x100E; +pub const SPI_SETHOTTRACKING: ::UINT = 0x100F; +pub const SPI_GETMENUFADE: ::UINT = 0x1012; +pub const SPI_SETMENUFADE: ::UINT = 0x1013; +pub const SPI_GETSELECTIONFADE: ::UINT = 0x1014; +pub const SPI_SETSELECTIONFADE: ::UINT = 0x1015; +pub const SPI_GETTOOLTIPANIMATION: ::UINT = 0x1016; +pub const SPI_SETTOOLTIPANIMATION: ::UINT = 0x1017; +pub const SPI_GETTOOLTIPFADE: ::UINT = 0x1018; +pub const SPI_SETTOOLTIPFADE: ::UINT = 0x1019; +pub const SPI_GETCURSORSHADOW: ::UINT = 0x101A; +pub const SPI_SETCURSORSHADOW: ::UINT = 0x101B; +pub const SPI_GETMOUSESONAR: ::UINT = 0x101C; +pub const SPI_SETMOUSESONAR: ::UINT = 0x101D; +pub const SPI_GETMOUSECLICKLOCK: ::UINT = 0x101E; +pub const SPI_SETMOUSECLICKLOCK: ::UINT = 0x101F; +pub const SPI_GETMOUSEVANISH: ::UINT = 0x1020; +pub const SPI_SETMOUSEVANISH: ::UINT = 0x1021; +pub const SPI_GETFLATMENU: ::UINT = 0x1022; +pub const SPI_SETFLATMENU: ::UINT = 0x1023; +pub const SPI_GETDROPSHADOW: ::UINT = 0x1024; +pub const SPI_SETDROPSHADOW: ::UINT = 0x1025; +pub const SPI_GETBLOCKSENDINPUTRESETS: ::UINT = 0x1026; +pub const SPI_SETBLOCKSENDINPUTRESETS: ::UINT = 0x1027; +pub const SPI_GETUIEFFECTS: ::UINT = 0x103E; +pub const SPI_SETUIEFFECTS: ::UINT = 0x103F; +pub const SPI_GETDISABLEOVERLAPPEDCONTENT: ::UINT = 0x1040; +pub const SPI_SETDISABLEOVERLAPPEDCONTENT: ::UINT = 0x1041; +pub const SPI_GETCLIENTAREAANIMATION: ::UINT = 0x1042; +pub const SPI_SETCLIENTAREAANIMATION: ::UINT = 0x1043; +pub const SPI_GETCLEARTYPE: ::UINT = 0x1048; +pub const SPI_SETCLEARTYPE: ::UINT = 0x1049; +pub const SPI_GETSPEECHRECOGNITION: ::UINT = 0x104A; +pub const SPI_SETSPEECHRECOGNITION: ::UINT = 0x104B; +pub const SPI_GETFOREGROUNDLOCKTIMEOUT: ::UINT = 0x2000; +pub const SPI_SETFOREGROUNDLOCKTIMEOUT: ::UINT = 0x2001; +pub const SPI_GETACTIVEWNDTRKTIMEOUT: ::UINT = 0x2002; +pub const SPI_SETACTIVEWNDTRKTIMEOUT: ::UINT = 0x2003; +pub const SPI_GETFOREGROUNDFLASHCOUNT: ::UINT = 0x2004; +pub const SPI_SETFOREGROUNDFLASHCOUNT: ::UINT = 0x2005; +pub const SPI_GETCARETWIDTH: ::UINT = 0x2006; +pub const SPI_SETCARETWIDTH: ::UINT = 0x2007; +pub const SPI_GETMOUSECLICKLOCKTIME: ::UINT = 0x2008; +pub const SPI_SETMOUSECLICKLOCKTIME: ::UINT = 0x2009; +pub const SPI_GETFONTSMOOTHINGTYPE: ::UINT = 0x200A; +pub const SPI_SETFONTSMOOTHINGTYPE: ::UINT = 0x200B; +pub const FE_FONTSMOOTHINGSTANDARD: ::UINT = 0x0001; +pub const FE_FONTSMOOTHINGCLEARTYPE: ::UINT = 0x0002; +pub const SPI_GETFONTSMOOTHINGCONTRAST: ::UINT = 0x200C; +pub const SPI_SETFONTSMOOTHINGCONTRAST: ::UINT = 0x200D; +pub const SPI_GETFOCUSBORDERWIDTH: ::UINT = 0x200E; +pub const SPI_SETFOCUSBORDERWIDTH: ::UINT = 0x200F; +pub const SPI_GETFOCUSBORDERHEIGHT: ::UINT = 0x2010; +pub const SPI_SETFOCUSBORDERHEIGHT: ::UINT = 0x2011; +pub const SPI_GETFONTSMOOTHINGORIENTATION: ::UINT = 0x2012; +pub const SPI_SETFONTSMOOTHINGORIENTATION: ::UINT = 0x2013; +pub const FE_FONTSMOOTHINGORIENTATIONBGR: ::UINT = 0x0000; +pub const FE_FONTSMOOTHINGORIENTATIONRGB: ::UINT = 0x0001; +pub const SPI_GETMINIMUMHITRADIUS: ::UINT = 0x2014; +pub const SPI_SETMINIMUMHITRADIUS: ::UINT = 0x2015; +pub const SPI_GETMESSAGEDURATION: ::UINT = 0x2016; +pub const SPI_SETMESSAGEDURATION: ::UINT = 0x2017; +//11264 +pub const CB_GETEDITSEL: ::UINT = 0x0140; +pub const CB_LIMITTEXT: ::UINT = 0x0141; +pub const CB_SETEDITSEL: ::UINT = 0x0142; +pub const CB_ADDSTRING: ::UINT = 0x0143; +pub const CB_DELETESTRING: ::UINT = 0x0144; +pub const CB_DIR: ::UINT = 0x0145; +pub const CB_GETCOUNT: ::UINT = 0x0146; +pub const CB_GETCURSEL: ::UINT = 0x0147; +pub const CB_GETLBTEXT: ::UINT = 0x0148; +pub const CB_GETLBTEXTLEN: ::UINT = 0x0149; +pub const CB_INSERTSTRING: ::UINT = 0x014A; +pub const CB_RESETCONTENT: ::UINT = 0x014B; +pub const CB_FINDSTRING: ::UINT = 0x014C; +pub const CB_SELECTSTRING: ::UINT = 0x014D; +pub const CB_SETCURSEL: ::UINT = 0x014E; +pub const CB_SHOWDROPDOWN: ::UINT = 0x014F; +pub const CB_GETITEMDATA: ::UINT = 0x0150; +pub const CB_SETITEMDATA: ::UINT = 0x0151; +pub const CB_GETDROPPEDCONTROLRECT: ::UINT = 0x0152; +pub const CB_SETITEMHEIGHT: ::UINT = 0x0153; +pub const CB_GETITEMHEIGHT: ::UINT = 0x0154; +pub const CB_SETEXTENDEDUI: ::UINT = 0x0155; +pub const CB_GETEXTENDEDUI: ::UINT = 0x0156; +pub const CB_GETDROPPEDSTATE: ::UINT = 0x0157; +pub const CB_FINDSTRINGEXACT: ::UINT = 0x0158; +pub const CB_SETLOCALE: ::UINT = 0x0159; +pub const CB_GETLOCALE: ::UINT = 0x015A; +pub const CB_GETTOPINDEX: ::UINT = 0x015b; +pub const CB_SETTOPINDEX: ::UINT = 0x015c; +pub const CB_GETHORIZONTALEXTENT: ::UINT = 0x015d; +pub const CB_SETHORIZONTALEXTENT: ::UINT = 0x015e; +pub const CB_GETDROPPEDWIDTH: ::UINT = 0x015f; +pub const CB_SETDROPPEDWIDTH: ::UINT = 0x0160; +pub const CB_INITSTORAGE: ::UINT = 0x0161; +//12141 +STRUCT!{nodebug struct NONCLIENTMETRICSA { + cbSize: ::UINT, + iBorderWidth: ::c_int, + iScrollWidth: ::c_int, + iScrollHeight: ::c_int, + iCaptionWidth: ::c_int, + iCaptionHeight: ::c_int, + lfCaptionFont: ::LOGFONTA, + iSmCaptionWidth: ::c_int, + iSmCaptionHeight: ::c_int, + lfSmCaptionFont: ::LOGFONTA, + iMenuWidth: ::c_int, + iMenuHeight: ::c_int, + lfMenuFont: ::LOGFONTA, + lfStatusFont: ::LOGFONTA, + lfMessageFont: ::LOGFONTA, + iPaddedBorderWidth: ::c_int, +}} +pub type LPNONCLIENTMETRICSA = *mut NONCLIENTMETRICSA; +STRUCT!{nodebug struct NONCLIENTMETRICSW { + cbSize: ::UINT, + iBorderWidth: ::c_int, + iScrollWidth: ::c_int, + iScrollHeight: ::c_int, + iCaptionWidth: ::c_int, + iCaptionHeight: ::c_int, + lfCaptionFont: ::LOGFONTW, + iSmCaptionWidth: ::c_int, + iSmCaptionHeight: ::c_int, + lfSmCaptionFont: ::LOGFONTW, + iMenuWidth: ::c_int, + iMenuHeight: ::c_int, + lfMenuFont: ::LOGFONTW, + lfStatusFont: ::LOGFONTW, + lfMessageFont: ::LOGFONTW, + iPaddedBorderWidth: ::c_int, +}} +pub type LPNONCLIENTMETRICSW = *mut NONCLIENTMETRICSW; +//12869 +pub const MONITOR_DEFAULTTONULL: ::DWORD = 0x00000000; +pub const MONITOR_DEFAULTTOPRIMARY: ::DWORD = 0x00000001; +pub const MONITOR_DEFAULTTONEAREST: ::DWORD = 0x00000002; +//12900 +pub const MONITORINFOF_PRIMARY: ::DWORD = 1; +pub const CCHDEVICENAME: usize = 32; +STRUCT!{struct MONITORINFO { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, +}} +pub type LPMONITORINFO = *mut MONITORINFO; +STRUCT!{struct MONITORINFOEXA { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, + szDevice: [::CHAR; ::CCHDEVICENAME], +}} +pub type LPMONITORINFOEXA = *mut MONITORINFOEXA; +STRUCT!{struct MONITORINFOEXW { + cbSize: ::DWORD, + rcMonitor: ::RECT, + rcWork: ::RECT, + dwFlags: ::DWORD, + szDevice: [::WCHAR; ::CCHDEVICENAME], +}} +pub type LPMONITORINFOEXW = *mut MONITORINFOEXW; +//12971 +pub type MONITORENUMPROC = Option ::BOOL>; +//14098 +DECLARE_HANDLE!(HRAWINPUT, HRAWINPUT__); +pub fn GET_RAWINPUT_CODE_WPARAM(wParam: ::WPARAM) -> ::WPARAM { wParam & 0xff } +pub const RIM_INPUT: ::WPARAM = 0; +pub const RIM_INPUTSINK: ::WPARAM = 1; +STRUCT!{struct RAWINPUTHEADER { + dwType: ::DWORD, + dwSize: ::DWORD, + hDevice: ::HANDLE, + wParam: ::WPARAM, +}} +pub type PRAWINPUTHEADER = *mut RAWINPUTHEADER; +pub type LPRAWINPUTHEADER = *mut RAWINPUTHEADER; +pub const RIM_TYPEMOUSE: ::DWORD = 0; +pub const RIM_TYPEKEYBOARD: ::DWORD = 1; +pub const RIM_TYPEHID: ::DWORD = 2; +STRUCT!{struct RAWMOUSE { + usFlags: ::USHORT, + memory_padding: ::USHORT, // 16bit Padding for 32bit align in following union + usButtonFlags: ::USHORT, + usButtonData: ::USHORT, + ulRawButtons: ::ULONG, + lLastX: ::LONG, + lLastY: ::LONG, + ulExtraInformation: ::ULONG, +}} +pub type PRAWMOUSE = *mut RAWMOUSE; +pub type LPRAWMOUSE = *mut RAWMOUSE; +pub const RI_MOUSE_LEFT_BUTTON_DOWN: ::USHORT = 0x0001; +pub const RI_MOUSE_LEFT_BUTTON_UP: ::USHORT = 0x0002; +pub const RI_MOUSE_RIGHT_BUTTON_DOWN: ::USHORT = 0x0004; +pub const RI_MOUSE_RIGHT_BUTTON_UP: ::USHORT = 0x0008; +pub const RI_MOUSE_MIDDLE_BUTTON_DOWN: ::USHORT = 0x0010; +pub const RI_MOUSE_MIDDLE_BUTTON_UP: ::USHORT = 0x0020; +pub const RI_MOUSE_BUTTON_1_DOWN: ::USHORT = RI_MOUSE_LEFT_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_1_UP: ::USHORT = RI_MOUSE_LEFT_BUTTON_UP; +pub const RI_MOUSE_BUTTON_2_DOWN: ::USHORT = RI_MOUSE_RIGHT_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_2_UP: ::USHORT = RI_MOUSE_RIGHT_BUTTON_UP; +pub const RI_MOUSE_BUTTON_3_DOWN: ::USHORT = RI_MOUSE_MIDDLE_BUTTON_DOWN; +pub const RI_MOUSE_BUTTON_3_UP: ::USHORT = RI_MOUSE_MIDDLE_BUTTON_UP; +pub const RI_MOUSE_BUTTON_4_DOWN: ::USHORT = 0x0040; +pub const RI_MOUSE_BUTTON_4_UP: ::USHORT = 0x0080; +pub const RI_MOUSE_BUTTON_5_DOWN: ::USHORT = 0x0100; +pub const RI_MOUSE_BUTTON_5_UP: ::USHORT = 0x0200; +pub const RI_MOUSE_WHEEL: ::USHORT = 0x0400; +pub const MOUSE_MOVE_RELATIVE: ::USHORT = 0; +pub const MOUSE_MOVE_ABSOLUTE: ::USHORT = 1; +pub const MOUSE_VIRTUAL_DESKTOP: ::USHORT = 0x02; +pub const MOUSE_ATTRIBUTES_CHANGED: ::USHORT = 0x04; +pub const MOUSE_MOVE_NOCOALESCE: ::USHORT = 0x08; +STRUCT!{struct RAWKEYBOARD { + MakeCode: ::USHORT, + Flags: ::USHORT, + Reserved: ::USHORT, + VKey: ::USHORT, + Message: ::UINT, + ExtraInformation: ::ULONG, +}} +pub type PRAWKEYBOARD = *mut RAWKEYBOARD; +pub type LPRAWKEYBOARD = *mut RAWKEYBOARD; +pub const KEYBOARD_OVERRUN_MAKE_CODE: ::DWORD = 0xFF; +pub const RI_KEY_MAKE: ::DWORD = 0; +pub const RI_KEY_BREAK: ::DWORD = 1; +pub const RI_KEY_E0: ::DWORD = 2; +pub const RI_KEY_E1: ::DWORD = 4; +pub const RI_KEY_TERMSRV_SET_LED: ::DWORD = 8; +pub const RI_KEY_TERMSRV_SHADOW: ::DWORD = 0x10; +STRUCT!{struct RAWHID { + dwSizeHid: ::DWORD, + dwCount: ::DWORD, + bRawData: [::BYTE; 0], +}} +pub type PRAWHID = *mut RAWHID; +pub type LPRAWHID = *mut RAWHID; +STRUCT!{struct RAWINPUT { + header: RAWINPUTHEADER, + mouse: RAWMOUSE, +}} +UNION!(RAWINPUT, mouse, mouse, mouse_mut, RAWMOUSE); +UNION!(RAWINPUT, mouse, keyboard, keyboard_mut, RAWKEYBOARD); +UNION!(RAWINPUT, mouse, hid, hid_mut, RAWHID); +#[test] +fn test_RAWINPUT() { + use std::mem::{size_of, align_of}; + assert!(size_of::() >= size_of::()); + assert!(size_of::() >= size_of::()); + assert!(size_of::() >= size_of::()); + assert!(align_of::() >= align_of::()); + assert!(align_of::() >= align_of::()); + assert!(align_of::() >= align_of::()); +} +pub type PRAWINPUT = *mut RAWINPUT; +pub type LPRAWINPUT = *mut RAWINPUT; +pub const RID_INPUT: ::DWORD = 0x10000003; +pub const RID_HEADER: ::DWORD = 0x10000005; +pub const RIDI_PREPARSEDDATA: ::DWORD = 0x20000005; +pub const RIDI_DEVICENAME: ::DWORD = 0x20000007; +pub const RIDI_DEVICEINFO: ::DWORD = 0x2000000b; +STRUCT!{struct RID_DEVICE_INFO_MOUSE { + dwId: ::DWORD, + dwNumberOfButtons: ::DWORD, + dwSampleRate: ::DWORD, + fHasHorizontalWheel: ::BOOL, +}} +pub type PRID_DEVICE_INFO_MOUSE = *mut RID_DEVICE_INFO_MOUSE; +STRUCT!{struct RID_DEVICE_INFO_KEYBOARD { + dwType: ::DWORD, + dwSubType: ::DWORD, + dwKeyboardMode: ::DWORD, + dwNumberOfFunctionKeys: ::DWORD, + dwNumberOfIndicators: ::DWORD, + dwNumberOfKeysTotal: ::DWORD, +}} +pub type PRID_DEVICE_INFO_KEYBOARD = *mut RID_DEVICE_INFO_KEYBOARD; +STRUCT!{struct RID_DEVICE_INFO_HID { + dwVendorId: ::DWORD, + dwProductId: ::DWORD, + dwVersionNumber: ::DWORD, + usUsagePage: ::USHORT, + usUsage: ::USHORT, +}} +pub type PRID_DEVICE_INFO_HID = *mut RID_DEVICE_INFO_HID; +STRUCT!{struct RID_DEVICE_INFO { + cbSize: ::DWORD, + dwType: ::DWORD, + keyboard: RID_DEVICE_INFO_KEYBOARD, +}} +UNION!(RID_DEVICE_INFO, keyboard, mouse, mouse_mut, RID_DEVICE_INFO_MOUSE); +UNION!(RID_DEVICE_INFO, keyboard, keyboard, keyboard_mut, RID_DEVICE_INFO_KEYBOARD); +UNION!(RID_DEVICE_INFO, keyboard, hid, hid_mut, RID_DEVICE_INFO_HID); +#[test] +fn test_RID_DEVICE_INFO() { + use std::mem::{size_of, align_of}; + assert!(size_of::() >= size_of::()); + assert!(size_of::() >= size_of::()); + assert!(size_of::() >= size_of::()); + assert!(align_of::() >= align_of::()); + assert!(align_of::() + >= align_of::()); + assert!(align_of::() >= align_of::()); +} +pub type PRID_DEVICE_INFO = *mut RID_DEVICE_INFO; +pub type LPRID_DEVICE_INFO = *mut RID_DEVICE_INFO; +STRUCT!{struct RAWINPUTDEVICE { + usUsagePage: ::USHORT, + usUsage: ::USHORT, + dwFlags: ::DWORD, + hwndTarget: ::HWND, +}} +pub type PRAWINPUTDEVICE = *mut RAWINPUTDEVICE; +pub type LPRAWINPUTDEVICE = *mut RAWINPUTDEVICE; +pub type PCRAWINPUTDEVICE = *const RAWINPUTDEVICE; +pub const RIDEV_REMOVE: ::DWORD = 0x00000001; +pub const RIDEV_EXCLUDE: ::DWORD = 0x00000010; +pub const RIDEV_PAGEONLY: ::DWORD = 0x00000020; +pub const RIDEV_NOLEGACY: ::DWORD = 0x00000030; +pub const RIDEV_INPUTSINK: ::DWORD = 0x00000100; +pub const RIDEV_CAPTUREMOUSE: ::DWORD = 0x00000200; +pub const RIDEV_NOHOTKEYS: ::DWORD = 0x00000200; +pub const RIDEV_APPKEYS: ::DWORD = 0x00000400; +pub const RIDEV_EXINPUTSINK: ::DWORD = 0x00001000; +pub const RIDEV_DEVNOTIFY: ::DWORD = 0x00002000; +pub const RIDEV_EXMODEMASK: ::DWORD = 0x000000F0; +pub const GIDC_ARRIVAL: ::DWORD = 1; +pub const GIDC_REMOVAL: ::DWORD = 2; +STRUCT!{struct RAWINPUTDEVICELIST { + hDevice: ::HANDLE, + dwType: ::DWORD, +}} +pub type PRAWINPUTDEVICELIST = *mut RAWINPUTDEVICELIST; +STRUCT!{struct CHANGEFILTERSTRUCT { + cbSize: ::DWORD, + ExtStatus: ::DWORD, +}} +pub type PCHANGEFILTERSTRUCT = *mut CHANGEFILTERSTRUCT; +STRUCT!{struct DLGTEMPLATE { + style: ::DWORD, + dwExtendedStyle: ::DWORD, + cdit: ::WORD, + x: ::c_short, + y: ::c_short, + cx: ::c_short, + cy: ::c_short, +}} +pub type LPDLGTEMPLATEA = *mut DLGTEMPLATE; +pub type LPDLGTEMPLATEW = *mut DLGTEMPLATE; +pub type LPCDLGTEMPLATEA = *const DLGTEMPLATE; +pub type LPCDLGTEMPLATEW = *const DLGTEMPLATE; +STRUCT!{struct DRAWTEXTPARAMS { + cbSize: ::UINT, + iTabLength: ::c_int, + iLeftMargin: ::c_int, + iRightMargin: ::c_int, + uiLengthDrawn: ::UINT, +}} +pub type LPDRAWTEXTPARAMS = *mut DRAWTEXTPARAMS; +STRUCT!{struct ACCEL { + fVirt: ::BYTE, + key: ::WORD, + cmd: ::WORD, +}} +pub type LPACCEL = *mut ACCEL; +STRUCT!{struct MENUITEMINFOA { + cbSize: ::UINT, + fMask: ::UINT, + fType: ::UINT, + fState: ::UINT, + wID: ::UINT, + hSubMenu: ::HMENU, + hbmpChecked: ::HBITMAP, + hbmpUnchecked: ::HBITMAP, + dwItemData: ::ULONG_PTR, + dwTypeData: ::LPSTR, + cch: ::UINT, + hbmpItem: ::HBITMAP, +}} +pub type LPMENUITEMINFOA = *mut MENUITEMINFOA; +pub type LPCMENUITEMINFOA = *const MENUITEMINFOA; +STRUCT!{struct MENUITEMINFOW { + cbSize: ::UINT, + fMask: ::UINT, + fType: ::UINT, + fState: ::UINT, + wID: ::UINT, + hSubMenu: ::HMENU, + hbmpChecked: ::HBITMAP, + hbmpUnchecked: ::HBITMAP, + dwItemData: ::ULONG_PTR, + dwTypeData: ::LPWSTR, + cch: ::UINT, + hbmpItem: ::HBITMAP, +}} +pub type LPMENUITEMINFOW = *mut MENUITEMINFOW; +pub type LPCMENUITEMINFOW = *const MENUITEMINFOW; +STRUCT!{nodebug struct MSGBOXPARAMSA { + cbSize: ::UINT, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpszText: ::LPCSTR, + lpszCaption: ::LPCSTR, + dwStyle: ::DWORD, + lpszIcon: ::LPCSTR, + dwContextHelpId: ::DWORD_PTR, + lpfnMsgBoxCallback: ::MSGBOXCALLBACK, + dwLanguageId: ::DWORD, +}} +pub type PMSGBOXPARAMSA = *mut MSGBOXPARAMSA; +pub type LPMSGBOXPARAMSA = *mut MSGBOXPARAMSA; +STRUCT!{nodebug struct MSGBOXPARAMSW { + cbSize: ::UINT, + hwndOwner: ::HWND, + hInstance: ::HINSTANCE, + lpszText: ::LPCWSTR, + lpszCaption: ::LPCWSTR, + dwStyle: ::DWORD, + lpszIcon: ::LPCWSTR, + dwContextHelpId: ::DWORD_PTR, + lpfnMsgBoxCallback: ::MSGBOXCALLBACK, + dwLanguageId: ::DWORD, +}} +pub type PMSGBOXPARAMSW = *mut MSGBOXPARAMSW; +pub type LPMSGBOXPARAMSW = *mut MSGBOXPARAMSW; +STRUCT!{struct HELPINFO { + cbSize: ::UINT, + iContextType: ::c_int, + iCtrlId: ::c_int, + hItemHandle: ::HANDLE, + dwContextId: ::DWORD, + MousePos: ::POINT, +}} +pub type LPHELPINFO = *mut HELPINFO; +#[allow(trivial_numeric_casts)] +pub fn GET_WHEEL_DELTA_WPARAM(wParam: ::WPARAM) -> ::c_short { + ::HIWORD(wParam as ::DWORD) as ::c_short +} +#[allow(trivial_numeric_casts)] +pub fn GET_KEYSTATE_WPARAM(wparam: ::WPARAM) -> ::c_int { + ::LOWORD(wparam as ::DWORD) as ::c_short as ::c_int +} +#[allow(trivial_numeric_casts)] +pub fn GET_XBUTTON_WPARAM(wparam: ::WPARAM) -> ::c_int { + ::HIWORD(wparam as ::DWORD) as ::c_int +} +pub const SIF_RANGE: ::UINT = 0x0001; +pub const SIF_PAGE: ::UINT = 0x0002; +pub const SIF_POS: ::UINT = 0x0004; +pub const SIF_DISABLENOSCROLL: ::UINT = 0x0008; +pub const SIF_TRACKPOS: ::UINT = 0x0010; +pub const SIF_ALL: ::UINT = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS; +pub const SW_SCROLLCHILDREN: ::UINT = 0x0001; +pub const SW_INVALIDATE: ::UINT = 0x0002; +pub const SW_ERASE: ::UINT = 0x0004; +pub const SW_SMOOTHSCROLL: ::UINT = 0x0010; +pub const SB_LINEUP: ::c_int = 0; +pub const SB_LINELEFT: ::c_int = 0; +pub const SB_LINEDOWN: ::c_int = 1; +pub const SB_LINERIGHT: ::c_int = 1; +pub const SB_PAGEUP: ::c_int = 2; +pub const SB_PAGELEFT: ::c_int = 2; +pub const SB_PAGEDOWN: ::c_int = 3; +pub const SB_PAGERIGHT: ::c_int = 3; +pub const SB_THUMBPOSITION: ::c_int = 4; +pub const SB_THUMBTRACK: ::c_int = 5; +pub const SB_TOP: ::c_int = 6; +pub const SB_LEFT: ::c_int = 6; +pub const SB_BOTTOM: ::c_int = 7; +pub const SB_RIGHT: ::c_int = 7; +pub const SB_ENDSCROLL: ::c_int = 8; +pub const LR_DEFAULTCOLOR: ::UINT = 0x00000000; +pub const LR_MONOCHROME: ::UINT = 0x00000001; +pub const LR_COLOR: ::UINT = 0x00000002; +pub const LR_COPYRETURNORG: ::UINT = 0x00000004; +pub const LR_COPYDELETEORG: ::UINT = 0x00000008; +pub const LR_LOADFROMFILE: ::UINT = 0x00000010; +pub const LR_LOADTRANSPARENT: ::UINT = 0x00000020; +pub const LR_DEFAULTSIZE: ::UINT = 0x00000040; +pub const LR_VGACOLOR: ::UINT = 0x00000080; +pub const LR_LOADMAP3DCOLORS: ::UINT = 0x00001000; +pub const LR_CREATEDIBSECTION: ::UINT = 0x00002000; +pub const LR_COPYFROMRESOURCE: ::UINT = 0x00004000; +pub const LR_SHARED: ::UINT = 0x00008000; +pub const IMAGE_BITMAP: ::UINT = 0; +pub const IMAGE_ICON: ::UINT = 1; +pub const IMAGE_CURSOR: ::UINT = 2; +pub const IMAGE_ENHMETAFILE: ::UINT = 3; +pub const DT_TOP: ::UINT = 0x00000000; +pub const DT_LEFT: ::UINT = 0x00000000; +pub const DT_CENTER: ::UINT = 0x00000001; +pub const DT_RIGHT: ::UINT = 0x00000002; +pub const DT_VCENTER: ::UINT = 0x00000004; +pub const DT_BOTTOM: ::UINT = 0x00000008; +pub const DT_WORDBREAK: ::UINT = 0x00000010; +pub const DT_SINGLELINE: ::UINT = 0x00000020; +pub const DT_EXPANDTABS: ::UINT = 0x00000040; +pub const DT_TABSTOP: ::UINT = 0x00000080; +pub const DT_NOCLIP: ::UINT = 0x00000100; +pub const DT_EXTERNALLEADING: ::UINT = 0x00000200; +pub const DT_CALCRECT: ::UINT = 0x00000400; +pub const DT_NOPREFIX: ::UINT = 0x00000800; +pub const DT_INTERNAL: ::UINT = 0x00001000; +pub const DT_EDITCONTROL: ::UINT = 0x00002000; +pub const DT_PATH_ELLIPSIS: ::UINT = 0x00004000; +pub const DT_END_ELLIPSIS: ::UINT = 0x00008000; +pub const DT_MODIFYSTRING: ::UINT = 0x00010000; +pub const DT_RTLREADING: ::UINT = 0x00020000; +pub const DT_WORD_ELLIPSIS: ::UINT = 0x00040000; +pub const DT_NOFULLWIDTHCHARBREAK: ::UINT = 0x00080000; +pub const DT_HIDEPREFIX: ::UINT = 0x00100000; +pub const DT_PREFIXONLY: ::UINT = 0x00200000; +STRUCT!{struct KBDLLHOOKSTRUCT { + vkCode: ::DWORD, + scanCode: ::DWORD, + flags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PKBDLLHOOKSTRUCT = *mut KBDLLHOOKSTRUCT; +pub type LPKBDLLHOOKSTRUCT = *mut KBDLLHOOKSTRUCT; +STRUCT!{struct MSLLHOOKSTRUCT { + pt: ::POINT, + mouseData: ::DWORD, + flags: ::DWORD, + time: ::DWORD, + dwExtraInfo: ::ULONG_PTR, +}} +pub type PMSLLHOOKSTRUCT = *mut MSLLHOOKSTRUCT; +pub type LPMSLLHOOKSTRUCT = *mut MSLLHOOKSTRUCT; +pub const WH_MIN: ::c_int = -1; +pub const WH_MSGFILTER: ::c_int = -1; +pub const WH_JOURNALRECORD: ::c_int = 0; +pub const WH_JOURNALPLAYBACK: ::c_int = 1; +pub const WH_KEYBOARD: ::c_int = 2; +pub const WH_GETMESSAGE: ::c_int = 3; +pub const WH_CALLWNDPROC: ::c_int = 4; +pub const WH_CBT: ::c_int = 5; +pub const WH_SYSMSGFILTER: ::c_int = 6; +pub const WH_MOUSE: ::c_int = 7; +pub const WH_HARDWARE: ::c_int = 8; +pub const WH_DEBUG: ::c_int = 9; +pub const WH_SHELL: ::c_int = 10; +pub const WH_FOREGROUNDIDLE: ::c_int = 11; +pub const WH_CALLWNDPROCRET: ::c_int = 12; +pub const WH_KEYBOARD_LL: ::c_int = 13; +pub const WH_MOUSE_LL: ::c_int = 14; +pub const WH_MAX: ::c_int = 14; +pub const WH_MINHOOK: ::c_int = WH_MIN; +pub const WH_MAXHOOK: ::c_int = WH_MAX; +pub const KLF_ACTIVATE: ::UINT = 1; +pub const KLF_SUBSTITUTE_OK: ::UINT = 2; +pub const KLF_UNLOADPREVIOUS: ::UINT = 4; +pub const KLF_REORDER: ::UINT = 8; +pub const KLF_REPLACELANG: ::UINT = 16; +pub const KLF_NOTELLSHELL: ::UINT = 128; +pub const KLF_SETFORPROCESS: ::UINT = 256; +//RedrawWindow() flags +pub const RDW_INVALIDATE: ::UINT = 0x0001; +pub const RDW_INTERNALPAINT: ::UINT = 0x0002; +pub const RDW_ERASE: ::UINT = 0x0004; +pub const RDW_VALIDATE: ::UINT = 0x0008; +pub const RDW_NOINTERNALPAINT: ::UINT = 0x0010; +pub const RDW_NOERASE: ::UINT = 0x0020; +pub const RDW_NOCHILDREN: ::UINT = 0x0040; +pub const RDW_ALLCHILDREN: ::UINT = 0x0080; +pub const RDW_UPDATENOW: ::UINT = 0x0100; +pub const RDW_ERASENOW: ::UINT = 0x0200; +pub const RDW_FRAME: ::UINT = 0x0400; +pub const RDW_NOFRAME: ::UINT = 0x0800; +STRUCT!{struct MEASUREITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + itemWidth: ::UINT, + itemHeight: ::UINT, + itemData: ::ULONG_PTR, +}} +pub type LPMEASUREITEMSTRUCT = *mut MEASUREITEMSTRUCT; +STRUCT!{struct DRAWITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + itemAction: ::UINT, + itemState: ::UINT, + hwndItem: ::HWND, + hDC: ::HDC, + rcItem: ::RECT, + itemData: ::ULONG_PTR, +}} +pub type LPDRAWITEMSTRUCT = *mut DRAWITEMSTRUCT; +STRUCT!{struct DELETEITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + itemID: ::UINT, + hwndItem: ::HWND, + itemData: ::ULONG_PTR, +}} +pub type LPDELETEITEMSTRUCT = *mut DELETEITEMSTRUCT; +STRUCT!{struct COMPAREITEMSTRUCT { + CtlType: ::UINT, + CtlID: ::UINT, + hwndItem: ::HWND, + itemID1: ::UINT, + itemData1: ::ULONG_PTR, + itemID2: ::UINT, + itemData2: ::ULONG_PTR, + dwLocaleId: ::DWORD, +}} +pub type LPCOMPAREITEMSTRUCT = *mut COMPAREITEMSTRUCT; +/* Image type */ +pub const DST_COMPLEX: ::UINT = 0x0000; +pub const DST_TEXT: ::UINT = 0x0001; +pub const DST_PREFIXTEXT: ::UINT = 0x0002; +pub const DST_ICON: ::UINT = 0x0003; +pub const DST_BITMAP: ::UINT = 0x0004; +pub const DI_MASK: ::UINT = 0x0001; +pub const DI_IMAGE: ::UINT = 0x0002; +pub const DI_NORMAL: ::UINT = 0x0003; +pub const DI_COMPAT: ::UINT = 0x0004; +pub const DI_DEFAULTSIZE: ::UINT = 0x0008; +// if WINVER >= 0x0601 +// GetSystemMetrics(SM_DIGITIZER) flag values +pub const NID_INTEGRATED_TOUCH: ::UINT = 0x00000001; +pub const NID_EXTERNAL_TOUCH: ::UINT = 0x00000002; +pub const NID_INTEGRATED_PEN: ::UINT = 0x00000004; +pub const NID_EXTERNAL_PEN: ::UINT = 0x00000008; +pub const NID_MULTI_INPUT: ::UINT = 0x00000040; +pub const NID_READY: ::UINT = 0x00000080; +// end if WINVER >= 0x0601 + +// System Menu Command Values +// +pub const SC_SIZE: ::WPARAM = 0xF000; +pub const SC_MOVE: ::WPARAM = 0xF010; +pub const SC_MINIMIZE: ::WPARAM = 0xF020; +pub const SC_MAXIMIZE: ::WPARAM = 0xF030; +pub const SC_NEXTWINDOW: ::WPARAM = 0xF040; +pub const SC_PREVWINDOW: ::WPARAM = 0xF050; +pub const SC_CLOSE: ::WPARAM = 0xF060; +pub const SC_VSCROLL: ::WPARAM = 0xF070; +pub const SC_HSCROLL: ::WPARAM = 0xF080; +pub const SC_MOUSEMENU: ::WPARAM = 0xF090; +pub const SC_KEYMENU: ::WPARAM = 0xF100; +pub const SC_ARRANGE: ::WPARAM = 0xF110; +pub const SC_RESTORE: ::WPARAM = 0xF120; +pub const SC_TASKLIST: ::WPARAM = 0xF130; +pub const SC_SCREENSAVE: ::WPARAM = 0xF140; +pub const SC_HOTKEY: ::WPARAM = 0xF150; +// if WINVER >= 0x0400 +pub const SC_DEFAULT: ::WPARAM = 0xF160; +pub const SC_MONITORPOWER: ::WPARAM = 0xF170; +pub const SC_CONTEXTHELP: ::WPARAM = 0xF180; +pub const SC_SEPARATOR: ::WPARAM = 0xF00F; +// endif WINVER >= 0x0400 diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ws2def.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ws2def.rs new file mode 100644 index 0000000..dcc4aaa --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ws2def.rs @@ -0,0 +1,279 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! This file contains the core definitions for the Winsock2 specification that can be used by +//! both user-mode and kernel mode modules. +pub type ADDRESS_FAMILY = ::USHORT; +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NS: ::c_int = 6; +pub const AF_IPX: ::c_int = AF_NS; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_ECMA: ::c_int = 8; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_NETBIOS: ::c_int = 17; +pub const AF_VOICEVIEW: ::c_int = 18; +pub const AF_FIREFOX: ::c_int = 19; +pub const AF_UNKNOWN1: ::c_int = 20; +pub const AF_BAN: ::c_int = 21; +pub const AF_ATM: ::c_int = 22; +pub const AF_INET6: ::c_int = 23; +pub const AF_CLUSTER: ::c_int = 24; +pub const AF_12844: ::c_int = 25; +pub const AF_IRDA: ::c_int = 26; +pub const AF_NETDES: ::c_int = 28; +pub const AF_TCNPROCESS: ::c_int = 29; +pub const AF_TCNMESSAGE: ::c_int = 30; +pub const AF_ICLFXBM: ::c_int = 31; +pub const AF_BTH: ::c_int = 32; +pub const AF_LINK: ::c_int = 33; +pub const AF_MAX: ::c_int = 34; +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x0001; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_DONTLINGER: ::c_int = !SO_LINGER; +pub const SO_EXCLUSIVEADDRUSE: ::c_int = !SO_REUSEADDR; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_BSP_STATE: ::c_int = 0x1009; +pub const SO_GROUP_ID: ::c_int = 0x2001; +pub const SO_GROUP_PRIORITY: ::c_int = 0x2002; +pub const SO_MAX_MSG_SIZE: ::c_int = 0x2003; +pub const SO_CONDITIONAL_ACCEPT: ::c_int = 0x3002; +pub const SO_PAUSE_ACCEPT: ::c_int = 0x3003; +pub const SO_COMPARTMENT_ID: ::c_int = 0x3004; +pub const SO_RANDOMIZE_PORT: ::c_int = 0x3005; +pub const SO_PORT_SCALABILITY: ::c_int = 0x3006; +pub const WSK_SO_BASE: ::c_int = 0x4000; +pub const TCP_NODELAY: ::c_int = 0x0001; +STRUCT!{struct SOCKADDR { + sa_family: ADDRESS_FAMILY, + sa_data: [::CHAR; 14], +}} +pub type PSOCKADDR = *mut SOCKADDR; +pub type LPSOCKADDR = *mut SOCKADDR; +STRUCT!{struct SOCKET_ADDRESS { + lpSockaddr: LPSOCKADDR, + iSockaddrLength: ::INT, +}} +pub type PSOCKET_ADDRESS = *mut SOCKET_ADDRESS; +pub type LPSOCKET_ADDRESS = *mut SOCKET_ADDRESS; +STRUCT!{nodebug struct SOCKET_ADDRESS_LIST { + iAddressCount: ::INT, + Address: [SOCKET_ADDRESS; 0], +}} +pub type PSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST; +pub type LPSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST; +STRUCT!{struct CSADDR_INFO { + LocalAddr: SOCKET_ADDRESS, + RemoteAddr: SOCKET_ADDRESS, + iSocketType: ::INT, + iProtocol: ::INT, +}} +pub type PCSADDR_INFO = *mut CSADDR_INFO; +pub type LPCSADDR_INFO = *mut CSADDR_INFO; +STRUCT!{nodebug struct SOCKADDR_STORAGE_LH { + ss_family: ADDRESS_FAMILY, + __ss_pad1: [::CHAR; 6], + __ss_align: ::__int64, + __ss_pad2: [::CHAR; 112], +}} +pub type PSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH; +pub type LPSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH; +STRUCT!{nodebug struct SOCKADDR_STORAGE_XP { + ss_family: ::c_short, + __ss_pad1: [::CHAR; 6], + __ss_align: ::__int64, + __ss_pad2: [::CHAR; 112], +}} +pub type PSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP; +pub type LPSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP; +pub type SOCKADDR_STORAGE = SOCKADDR_STORAGE_LH; +pub type PSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE; +pub type LPSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE; +STRUCT!{struct SOCKET_PROCESSOR_AFFINITY { + Processor: ::PROCESSOR_NUMBER, + NumaNodeId: ::USHORT, + Reserved: ::USHORT, +}} +pub type PSOCKET_PROCESSOR_AFFINITY = *mut SOCKET_PROCESSOR_AFFINITY; +pub const IOC_UNIX: ::DWORD = 0x00000000; +pub const IOC_WS2: ::DWORD = 0x08000000; +pub const IOC_PROTOCOL: ::DWORD = 0x10000000; +pub const IOC_VENDOR: ::DWORD = 0x18000000; +pub const IOC_WSK: ::DWORD = IOC_WS2 | 0x07000000; +macro_rules! _WSAIO { ($x:expr, $y:expr) => { IOC_VOID | $x | $y } } +macro_rules! _WSAIOR { ($x:expr, $y:expr) => { IOC_OUT | $x | $y } } +macro_rules! _WSAIOW { ($x:expr, $y:expr) => { IOC_IN | $x | $y } } +macro_rules! _WSAIORW { ($x:expr, $y:expr) => { IOC_INOUT | $x | $y } } +pub const SIO_ASSOCIATE_HANDLE: ::DWORD = _WSAIOW!(IOC_WS2, 1); +pub const SIO_ENABLE_CIRCULAR_QUEUEING: ::DWORD = _WSAIO!(IOC_WS2, 2); +pub const SIO_FIND_ROUTE: ::DWORD = _WSAIOR!(IOC_WS2, 3); +pub const SIO_FLUSH: ::DWORD = _WSAIO!(IOC_WS2, 4); +pub const SIO_GET_BROADCAST_ADDRESS: ::DWORD = _WSAIOR!(IOC_WS2, 5); +pub const SIO_GET_EXTENSION_FUNCTION_POINTER: ::DWORD = _WSAIORW!(IOC_WS2, 6); +pub const SIO_GET_QOS: ::DWORD = _WSAIORW!(IOC_WS2, 7); +pub const SIO_GET_GROUP_QOS: ::DWORD = _WSAIORW!(IOC_WS2, 8); +pub const SIO_MULTIPOINT_LOOPBACK: ::DWORD = _WSAIOW!(IOC_WS2, 9); +pub const SIO_MULTICAST_SCOPE: ::DWORD = _WSAIOW!(IOC_WS2, 10); +pub const SIO_SET_QOS: ::DWORD = _WSAIOW!(IOC_WS2, 11); +pub const SIO_SET_GROUP_QOS: ::DWORD = _WSAIOW!(IOC_WS2, 12); +pub const SIO_TRANSLATE_HANDLE: ::DWORD = _WSAIORW!(IOC_WS2, 13); +pub const SIO_ROUTING_INTERFACE_QUERY: ::DWORD = _WSAIORW!(IOC_WS2, 20); +pub const SIO_ROUTING_INTERFACE_CHANGE: ::DWORD = _WSAIOW!(IOC_WS2, 21); +pub const SIO_ADDRESS_LIST_QUERY: ::DWORD = _WSAIOR!(IOC_WS2, 22); +pub const SIO_ADDRESS_LIST_CHANGE: ::DWORD = _WSAIO!(IOC_WS2, 23); +pub const SIO_QUERY_TARGET_PNP_HANDLE: ::DWORD = _WSAIOR!(IOC_WS2, 24); +pub const SIO_QUERY_RSS_PROCESSOR_INFO: ::DWORD = _WSAIOR!(IOC_WS2, 37); +pub const SIO_ADDRESS_LIST_SORT: ::DWORD = _WSAIORW!(IOC_WS2, 25); +pub const SIO_RESERVED_1: ::DWORD = _WSAIOW!(IOC_WS2, 26); +pub const SIO_RESERVED_2: ::DWORD = _WSAIOW!(IOC_WS2, 33); +pub const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: ::DWORD = _WSAIORW!(IOC_WS2, 36); +pub const IPPROTO_IP: ::c_int = 0; +ENUM!{enum IPPROTO { + IPPROTO_HOPOPTS = 0, // IPv6 Hop-by-Hop options + IPPROTO_ICMP = 1, + IPPROTO_IGMP = 2, + IPPROTO_GGP = 3, + IPPROTO_IPV4 = 4, + IPPROTO_ST = 5, + IPPROTO_TCP = 6, + IPPROTO_CBT = 7, + IPPROTO_EGP = 8, + IPPROTO_IGP = 9, + IPPROTO_PUP = 12, + IPPROTO_UDP = 17, + IPPROTO_IDP = 22, + IPPROTO_RDP = 27, + IPPROTO_IPV6 = 41, // IPv6 header + IPPROTO_ROUTING = 43, // IPv6 Routing header + IPPROTO_FRAGMENT = 44, // IPv6 fragmentation header + IPPROTO_ESP = 50, // encapsulating security payload + IPPROTO_AH = 51, // authentication header + IPPROTO_ICMPV6 = 58, // ICMPv6 + IPPROTO_NONE = 59, // IPv6 no next header + IPPROTO_DSTOPTS = 60, // IPv6 Destination options + IPPROTO_ND = 77, + IPPROTO_ICLFXBM = 78, + IPPROTO_PIM = 103, + IPPROTO_PGM = 113, + IPPROTO_L2TP = 115, + IPPROTO_SCTP = 132, + IPPROTO_RAW = 255, + IPPROTO_MAX = 256, + IPPROTO_RESERVED_RAW = 257, + IPPROTO_RESERVED_IPSEC = 258, + IPPROTO_RESERVED_IPSECOFFLOAD = 259, + IPPROTO_RESERVED_WNV = 260, + IPPROTO_RESERVED_MAX = 261, +}} +pub type PIPPROTO = *mut IPPROTO; +STRUCT!{struct SOCKADDR_IN { + sin_family: ADDRESS_FAMILY, + sin_port: ::USHORT, + sin_addr: ::IN_ADDR, + sin_zero: [::CHAR; 8], +}} +pub type PSOCKADDR_IN = *mut SOCKADDR_IN; +//645 +pub const IOCPARM_MASK: ::DWORD = 0x7f; +pub const IOC_VOID: ::DWORD = 0x20000000; +pub const IOC_OUT: ::DWORD = 0x40000000; +pub const IOC_IN: ::DWORD = 0x80000000; +pub const IOC_INOUT: ::DWORD = IOC_IN | IOC_OUT; +STRUCT!{struct WSABUF { + len: ::ULONG, + buf: *mut ::CHAR, +}} +pub type LPWSABUF = *mut WSABUF; +STRUCT!{struct WSAMSG { + name: LPSOCKADDR, + namelen: ::INT, + lpBuffers: LPWSABUF, + dwBufferCount: ::ULONG, + Control: WSABUF, + dwFlags: ::ULONG, +}} +pub type PWSAMSG = *mut WSAMSG; +pub type LPWSAMSG = *mut WSAMSG; +STRUCT!{struct ADDRINFOA { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: *mut ::c_char, + ai_addr: *mut SOCKADDR, + ai_next: *mut ADDRINFOA, +}} +pub type PADDRINFOA = *mut ADDRINFOA; +STRUCT!{struct ADDRINFOW { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: ::PWSTR, + ai_addr: *mut SOCKADDR, + ai_next: *mut ADDRINFOW, +}} +pub type PADDRINFOW = *mut ADDRINFOW; +STRUCT!{struct ADDRINFOEXA { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: *mut ::c_char, + ai_addr: *mut SOCKADDR, + ai_blob: *mut ::c_void, + ai_bloblen: ::size_t, + ai_provider: ::LPGUID, + ai_next: *mut ADDRINFOEXW, +}} +pub type PADDRINFOEXA = *mut ADDRINFOEXA; +pub type LPADDRINFOEXA = *mut ADDRINFOEXA; +STRUCT!{struct ADDRINFOEXW { + ai_flags: ::c_int, + ai_family: ::c_int, + ai_socktype: ::c_int, + ai_protocol: ::c_int, + ai_addrlen: ::size_t, + ai_canonname: ::PWSTR, + ai_addr: *mut SOCKADDR, + ai_blob: *mut ::c_void, + ai_bloblen: ::size_t, + ai_provider: ::LPGUID, + ai_next: *mut ADDRINFOEXW, +}} +pub type PADDRINFOEXW = *mut ADDRINFOEXW; +pub type LPADDRINFOEXW = *mut ADDRINFOEXW; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ws2ipdef.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ws2ipdef.rs new file mode 100644 index 0000000..86d3ffa --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ws2ipdef.rs @@ -0,0 +1,42 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub const IPV6_HOPOPTS: ::c_int = 1; +pub const IPV6_HDRINCL: ::c_int = 2; +pub const IPV6_UNICAST_HOPS: ::c_int = 4; +pub const IPV6_MULTICAST_IF: ::c_int = 9; +pub const IPV6_MULTICAST_HOPS: ::c_int = 10; +pub const IPV6_MULTICAST_LOOP: ::c_int = 11; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 12; +pub const IPV6_JOIN_GROUP: ::c_int = IPV6_ADD_MEMBERSHIP; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 13; +pub const IPV6_LEAVE_GROUP: ::c_int = IPV6_DROP_MEMBERSHIP; +pub const IPV6_DONTFRAG: ::c_int = 14; +pub const IPV6_PKTINFO: ::c_int = 19; +pub const IPV6_HOPLIMIT: ::c_int = 21; +pub const IPV6_PROTECTION_LEVEL: ::c_int = 23; +pub const IPV6_RECVIF: ::c_int = 24; +pub const IPV6_RECVDSTADDR: ::c_int = 25; +pub const IPV6_CHECKSUM: ::c_int = 26; +pub const IPV6_V6ONLY: ::c_int = 27; +pub const IPV6_IFLIST: ::c_int = 28; +pub const IPV6_ADD_IFLIST: ::c_int = 29; +pub const IPV6_DEL_IFLIST: ::c_int = 30; +pub const IPV6_UNICAST_IF: ::c_int = 31; +pub const IPV6_RTHDR: ::c_int = 32; +pub const IPV6_RECVRTHDR: ::c_int = 38; +pub const IPV6_TCLASS: ::c_int = 39; +pub const IPV6_RECVTCLASS: ::c_int = 40; +STRUCT!{struct ipv6_mreq { + ipv6mr_multiaddr: in6_addr, + ipv6mr_interface: ::c_uint, +}} +STRUCT!{struct in6_addr { + s6_addr: [u8; 16], +}} +STRUCT!{struct sockaddr_in6 { + sin6_family: ::c_short, + sin6_port: ::c_ushort, + sin6_flowinfo: ::c_ulong, + sin6_addr: in6_addr, + sin6_scope_id: ::c_ulong, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ws2spi.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ws2spi.rs new file mode 100644 index 0000000..9df67c1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ws2spi.rs @@ -0,0 +1,57 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! Definitions to be used with the WinSock service provider +pub const WSPDESCRIPTION_LEN: usize = 255; +STRUCT!{nodebug struct WSPDATA { + wVersion: ::WORD, + wHighVersion: ::WORD, + szDescription: [::WCHAR; WSPDESCRIPTION_LEN + 1], +}} +pub type LPWSPDATA = *mut WSPDATA; +STRUCT!{struct WSATHREADID { + ThreadHandle: ::HANDLE, + Reserved: ::DWORD_PTR, +}} +pub type LPWSATHREADID = *mut WSATHREADID; +pub type LPNSPV2STARTUP = Option ::INT>; +pub type LPNSPV2CLEANUP = Option ::INT>; +pub type LPNSPV2LOOKUPSERVICEBEGIN = Option ::INT>; +pub type LPNSPV2LOOKUPSERVICENEXTEX = Option; +pub type LPNSPV2LOOKUPSERVICEEND = Option ::INT>; +pub type LPNSPV2SETSERVICEEX = Option; +pub type LPNSPV2CLIENTSESSIONRUNDOWN = Option; +STRUCT!{nodebug struct NSPV2_ROUTINE { + cbSize: ::DWORD, + dwMajorVersion: ::DWORD, + dwMinorVersion: ::DWORD, + NSPv2Startup: LPNSPV2STARTUP, + NSPv2Cleanup: LPNSPV2CLEANUP, + NSPv2LookupServiceBegin: LPNSPV2LOOKUPSERVICEBEGIN, + NSPv2LookupServiceNextEx: LPNSPV2LOOKUPSERVICENEXTEX, + NSPv2LookupServiceEnd: LPNSPV2LOOKUPSERVICEEND, + NSPv2SetServiceEx: LPNSPV2SETSERVICEEX, + NSPv2ClientSessionRundown: LPNSPV2CLIENTSESSIONRUNDOWN, +}} +pub type PNSPV2_ROUTINE = *mut NSPV2_ROUTINE; +pub type LPNSPV2_ROUTINE = *mut NSPV2_ROUTINE; +pub type PCNSPV2_ROUTINE = *const NSPV2_ROUTINE; +pub type LPCNSPV2_ROUTINE = *const NSPV2_ROUTINE; +ENUM!{enum WSC_PROVIDER_INFO_TYPE { + ProviderInfoLspCategories, + ProviderInfoAudit, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/ws2tcpip.rs b/third_party/cargo/vendor/winapi-0.2.8/src/ws2tcpip.rs new file mode 100644 index 0000000..d60c841 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/ws2tcpip.rs @@ -0,0 +1,27 @@ +// Copyright © 2015, skdltmxn +// Licensed under the MIT License +//! WinSock2 Extension for TCP/IP protocols +pub type LPLOOKUPSERVICE_COMPLETION_ROUTINE = Option; +pub type socklen_t = ::c_int; +STRUCT!{struct ip_mreq { + imr_multiaddr: ::in_addr, + imr_interface: ::in_addr, +}} +pub const IP_OPTIONS: ::c_int = 1; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_TOS: ::c_int = 3; +pub const IP_TTL: ::c_int = 4; +pub const IP_MULTICAST_IF: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IP_DONTFRAGMENT: ::c_int = 14; +pub const IP_ADD_SOURCE_MEMBERSHIP: ::c_int = 15; +pub const IP_DROP_SOURCE_MEMBERSHIP: ::c_int = 16; +pub const IP_BLOCK_SOURCE: ::c_int = 17; +pub const IP_UNBLOCK_SOURCE: ::c_int = 18; +pub const IP_PKTINFO: ::c_int = 19; +pub const IP_RECEIVE_BROADCAST: ::c_int = 22; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wtypes.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wtypes.rs new file mode 100644 index 0000000..36c8059 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wtypes.rs @@ -0,0 +1,75 @@ +// Copyright © 2015, Connor Hilarides +// Licensed under the MIT License +//! Mappings for the contents of wstypes.h +ENUM!{enum VARENUM { + VT_EMPTY = 0, + VT_NULL = 1, + VT_I2 = 2, + VT_I4 = 3, + VT_R4 = 4, + VT_R8 = 5, + VT_CY = 6, + VT_DATE = 7, + VT_BSTR = 8, + VT_DISPATCH = 9, + VT_ERROR = 10, + VT_BOOL = 11, + VT_VARIANT = 12, + VT_UNKNOWN = 13, + VT_DECIMAL = 14, + VT_I1 = 16, + VT_UI1 = 17, + VT_UI2 = 18, + VT_UI4 = 19, + VT_I8 = 20, + VT_UI8 = 21, + VT_INT = 22, + VT_UINT = 23, + VT_VOID = 24, + VT_HRESULT = 25, + VT_PTR = 26, + VT_SAFEARRAY = 27, + VT_CARRAY = 28, + VT_USERDEFINED = 29, + VT_LPSTR = 30, + VT_LPWSTR = 31, + VT_RECORD = 36, + VT_INT_PTR = 37, + VT_UINT_PTR = 38, + VT_FILETIME = 64, + VT_BLOB = 65, + VT_STREAM = 66, + VT_STORAGE = 67, + VT_STREAMED_OBJECT = 68, + VT_STORED_OBJECT = 69, + VT_BLOB_OBJECT = 70, + VT_CF = 71, + VT_CLSID = 72, + VT_VERSIONED_STREAM = 73, + VT_BSTR_BLOB = 0xfff, + VT_VECTOR = 0x1000, + VT_ARRAY = 0x2000, + VT_BYREF = 0x4000, + VT_RESERVED = 0x8000, + VT_ILLEGAL = 0xffff, +}} +pub const VT_ILLEGALMASKED: VARENUM = VT_BSTR_BLOB; +pub const VT_TYPEMASK: VARENUM = VT_BSTR_BLOB; +pub type DATE = ::c_double; +STRUCT!{struct CY { + int64: ::LONGLONG, +}} +STRUCT!{struct DECIMAL { + wReserved: ::USHORT, + scale: ::BYTE, + sign: ::BYTE, + Hi32: ::ULONG, + Lo64: ::ULONGLONG, +}} +pub const DECIMAL_NEG: ::BYTE = 0x80; +pub type LPDECIMAL = *mut DECIMAL; +pub type VARTYPE = ::c_ushort; +pub type wireBSTR = *mut ::FLAGGED_WORD_BLOB; +pub type BSTR = *mut ::OLECHAR; +pub type LPBSTR = *mut BSTR; +pub type VARIANT_BOOL = ::c_short; diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/wtypesbase.rs b/third_party/cargo/vendor/winapi-0.2.8/src/wtypesbase.rs new file mode 100644 index 0000000..8683c53 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/wtypesbase.rs @@ -0,0 +1,37 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//114 +pub type OLECHAR = ::WCHAR; +pub type LPOLESTR = *mut OLECHAR; +pub type LPCOLESTR = *const OLECHAR; +//147 +pub type DOUBLE = ::c_double; +//281 +pub type SCODE = ::LONG; +pub type PSCODE = *mut SCODE; +STRUCT!{struct BLOB { + cbSize: ::ULONG, + pBlobData: *mut ::BYTE, +}} +pub type LPBLOB = *mut BLOB; +STRUCT!{struct FLAGGED_WORD_BLOB { + fFlags: ::ULONG, + clSize: ::ULONG, + asData: [::c_ushort; 1], +}} +STRUCT!{struct BYTE_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::BYTE, +}} +STRUCT!{struct WORD_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::c_ushort, +}} +STRUCT!{struct DWORD_SIZEDARR { + clSize: ::ULONG, + pData: *mut ::ULONG, +}} +STRUCT!{struct HYPER_SIZEDARR { + clSize: ::ULONG, + pData: *mut i64, +}} diff --git a/third_party/cargo/vendor/winapi-0.2.8/src/xinput.rs b/third_party/cargo/vendor/winapi-0.2.8/src/xinput.rs new file mode 100644 index 0000000..d18d465 --- /dev/null +++ b/third_party/cargo/vendor/winapi-0.2.8/src/xinput.rs @@ -0,0 +1,118 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! XInput procedure declarations, constant definitions and macros +pub const XINPUT_DEVTYPE_GAMEPAD: ::BYTE = 0x01; +pub const XINPUT_DEVSUBTYPE_GAMEPAD: ::BYTE = 0x01; +pub const XINPUT_DEVSUBTYPE_WHEEL: ::BYTE = 0x02; +pub const XINPUT_DEVSUBTYPE_ARCADE_STICK: ::BYTE = 0x03; +pub const XINPUT_DEVSUBTYPE_FLIGHT_SICK: ::BYTE = 0x04; +pub const XINPUT_DEVSUBTYPE_DANCE_PAD: ::BYTE = 0x05; +pub const XINPUT_DEVSUBTYPE_GUITAR: ::BYTE = 0x06; +pub const XINPUT_DEVSUBTYPE_DRUM_KIT: ::BYTE = 0x08; +pub const XINPUT_CAPS_VOICE_SUPPORTED: ::WORD = 0x0004; +pub const XINPUT_GAMEPAD_DPAD_UP: ::WORD = 0x0001; +pub const XINPUT_GAMEPAD_DPAD_DOWN: ::WORD = 0x0002; +pub const XINPUT_GAMEPAD_DPAD_LEFT: ::WORD = 0x0004; +pub const XINPUT_GAMEPAD_DPAD_RIGHT: ::WORD = 0x0008; +pub const XINPUT_GAMEPAD_START: ::WORD = 0x0010; +pub const XINPUT_GAMEPAD_BACK: ::WORD = 0x0020; +pub const XINPUT_GAMEPAD_LEFT_THUMB: ::WORD = 0x0040; +pub const XINPUT_GAMEPAD_RIGHT_THUMB: ::WORD = 0x0080; +pub const XINPUT_GAMEPAD_LEFT_SHOULDER: ::WORD = 0x0100; +pub const XINPUT_GAMEPAD_RIGHT_SHOULDER: ::WORD = 0x0200; +pub const XINPUT_GAMEPAD_A: ::WORD = 0x1000; +pub const XINPUT_GAMEPAD_B: ::WORD = 0x2000; +pub const XINPUT_GAMEPAD_X: ::WORD = 0x4000; +pub const XINPUT_GAMEPAD_Y: ::WORD = 0x8000; +pub const XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE: ::SHORT = 7849; +pub const XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE: ::SHORT = 8689; +pub const XINPUT_GAMEPAD_TRIGGER_THRESHOLD: ::BYTE = 30; +pub const XINPUT_FLAG_GAMEPAD: ::DWORD = 0x00000001; +pub const BATTERY_DEVTYPE_GAMEPAD: ::BYTE = 0x00; +pub const BATTERY_DEVTYPE_HEADSET: ::BYTE = 0x01; +pub const BATTERY_TYPE_DISCONNECTED: ::BYTE = 0x00; +pub const BATTERY_TYPE_WIRED: ::BYTE = 0x01; +pub const BATTERY_TYPE_ALKALINE: ::BYTE = 0x02; +pub const BATTERY_TYPE_NIMH: ::BYTE = 0x03; +pub const BATTERY_TYPE_UNKNOWN: ::BYTE = 0xFF; +pub const BATTERY_LEVEL_EMPTY: ::BYTE = 0x00; +pub const BATTERY_LEVEL_LOW: ::BYTE = 0x01; +pub const BATTERY_LEVEL_MEDIUM: ::BYTE = 0x02; +pub const BATTERY_LEVEL_FULL: ::BYTE = 0x03; +pub const XUSER_MAX_COUNT: ::DWORD = 4; +pub const XUSER_INDEX_ANY: ::DWORD = 0x000000FF; +pub const VK_PAD_A: ::WORD = 0x5800; +pub const VK_PAD_B: ::WORD = 0x5801; +pub const VK_PAD_X: ::WORD = 0x5802; +pub const VK_PAD_Y: ::WORD = 0x5803; +pub const VK_PAD_RSHOULDER: ::WORD = 0x5804; +pub const VK_PAD_LSHOULDER: ::WORD = 0x5805; +pub const VK_PAD_LTRIGGER: ::WORD = 0x5806; +pub const VK_PAD_RTRIGGER: ::WORD = 0x5807; +pub const VK_PAD_DPAD_UP: ::WORD = 0x5810; +pub const VK_PAD_DPAD_DOWN: ::WORD = 0x5811; +pub const VK_PAD_DPAD_LEFT: ::WORD = 0x5812; +pub const VK_PAD_DPAD_RIGHT: ::WORD = 0x5813; +pub const VK_PAD_START: ::WORD = 0x5814; +pub const VK_PAD_BACK: ::WORD = 0x5815; +pub const VK_PAD_LTHUMB_PRESS: ::WORD = 0x5816; +pub const VK_PAD_RTHUMB_PRESS: ::WORD = 0x5817; +pub const VK_PAD_LTHUMB_UP: ::WORD = 0x5820; +pub const VK_PAD_LTHUMB_DOWN: ::WORD = 0x5821; +pub const VK_PAD_LTHUMB_RIGHT: ::WORD = 0x5822; +pub const VK_PAD_LTHUMB_LEFT: ::WORD = 0x5823; +pub const VK_PAD_LTHUMB_UPLEFT: ::WORD = 0x5824; +pub const VK_PAD_LTHUMB_UPRIGHT: ::WORD = 0x5825; +pub const VK_PAD_LTHUMB_DOWNRIGHT: ::WORD = 0x5826; +pub const VK_PAD_LTHUMB_DOWNLEFT: ::WORD = 0x5827; +pub const VK_PAD_RTHUMB_UP: ::WORD = 0x5830; +pub const VK_PAD_RTHUMB_DOWN: ::WORD = 0x5831; +pub const VK_PAD_RTHUMB_RIGHT: ::WORD = 0x5832; +pub const VK_PAD_RTHUMB_LEFT: ::WORD = 0x5833; +pub const VK_PAD_RTHUMB_UPLEFT: ::WORD = 0x5834; +pub const VK_PAD_RTHUMB_UPRIGHT: ::WORD = 0x5835; +pub const VK_PAD_RTHUMB_DOWNRIGHT: ::WORD = 0x5836; +pub const VK_PAD_RTHUMB_DOWNLEFT: ::WORD = 0x5837; +pub const XINPUT_KEYSTROKE_KEYDOWN: ::WORD = 0x0001; +pub const XINPUT_KEYSTROKE_KEYUP: ::WORD = 0x0002; +pub const XINPUT_KEYSTROKE_REPEAT: ::WORD = 0x0004; +STRUCT!{struct XINPUT_GAMEPAD { + wButtons: ::WORD, + bLeftTrigger: ::BYTE, + bRightTrigger: ::BYTE, + sThumbLX: ::SHORT, + sThumbLY: ::SHORT, + sThumbRX: ::SHORT, + sThumbRY: ::SHORT, +}} +pub type PXINPUT_GAMEPAD = *mut XINPUT_GAMEPAD; +STRUCT!{struct XINPUT_STATE { + dwPacketNumber: ::DWORD, + Gamepad: ::XINPUT_GAMEPAD, +}} +pub type PXINPUT_STATE = *mut XINPUT_STATE; +STRUCT!{struct XINPUT_VIBRATION { + wLeftMotorSpeed: ::WORD, + wRightMotorSpeed: ::WORD, +}} +pub type PXINPUT_VIBRATION = *mut XINPUT_VIBRATION; +STRUCT!{struct XINPUT_CAPABILITIES { + Type: ::BYTE, + SubType: ::BYTE, + Flags: ::WORD, + Gamepad: ::XINPUT_GAMEPAD, + Vibration: ::XINPUT_VIBRATION, +}} +pub type PXINPUT_CAPABILITIES = *mut XINPUT_CAPABILITIES; +STRUCT!{struct XINPUT_BATTERY_INFORMATION { + BatteryType: ::BYTE, + BatteryLevel: ::BYTE, +}} +pub type PXINPUT_BATTERY_INFORMATION = *mut XINPUT_BATTERY_INFORMATION; +STRUCT!{struct XINPUT_KEYSTROKE { + VirtualKey: ::WORD, + Unicode: ::WCHAR, + UserIndex: ::BYTE, + HidCode: ::BYTE, +}} +pub type PXINPUT_KEYSTROKE = *mut XINPUT_KEYSTROKE; diff --git a/third_party/cargo/vendor/winapi-0.3.8/BUILD b/third_party/cargo/vendor/winapi-0.3.8/BUILD index feef361..429536c 100644 --- a/third_party/cargo/vendor/winapi-0.3.8/BUILD +++ b/third_party/cargo/vendor/winapi-0.3.8/BUILD @@ -40,6 +40,7 @@ rust_library( crate_features = [ "basetsd", "combaseapi", + "commctrl", "consoleapi", "dwmapi", "errhandlingapi", @@ -69,7 +70,11 @@ rust_library( "winerror", "wingdi", "winnt", + "winsock2", "winuser", + "ws2def", + "ws2ipdef", + "ws2tcpip", ], ) diff --git a/third_party/cargo/vendor/winapi-build-0.1.1/.cargo-checksum.json b/third_party/cargo/vendor/winapi-build-0.1.1/.cargo-checksum.json new file mode 100644 index 0000000..4d5fc4c --- /dev/null +++ b/third_party/cargo/vendor/winapi-build-0.1.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"982633c62ba05c95429b1768896a54c9a032a40fbd1e11049a9b087e9fd89176","src/lib.rs":"1d88932534b784973d3d87ac18cd8f2a0294ce5166cf30488c68ca90443e1750"},"package":"2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"} \ No newline at end of file diff --git a/third_party/cargo/vendor/objc_id-0.1.1/BUILD b/third_party/cargo/vendor/winapi-build-0.1.1/BUILD similarity index 90% rename from third_party/cargo/vendor/objc_id-0.1.1/BUILD rename to third_party/cargo/vendor/winapi-build-0.1.1/BUILD index b65d342..64e9fa6 100644 --- a/third_party/cargo/vendor/objc_id-0.1.1/BUILD +++ b/third_party/cargo/vendor/winapi-build-0.1.1/BUILD @@ -23,15 +23,18 @@ load( ) +alias( + name = "winapi_build", + actual = ":build", +) rust_library( - name = "objc_id", + name = "build", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/objc-0.2.7:objc", ], rustc_flags = [ "--cap-lints=allow", diff --git a/third_party/cargo/vendor/winapi-build-0.1.1/Cargo.toml b/third_party/cargo/vendor/winapi-build-0.1.1/Cargo.toml new file mode 100644 index 0000000..e1be0b1 --- /dev/null +++ b/third_party/cargo/vendor/winapi-build-0.1.1/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "winapi-build" +version = "0.1.1" +authors = ["Peter Atashian "] +description = "Common code for build.rs in WinAPI -sys crates." +repository = "https://github.com/retep998/winapi-rs" +keywords = ["Windows", "FFI", "WinSDK"] +license = "MIT" + +[lib] +name = "build" diff --git a/third_party/cargo/vendor/winapi-build-0.1.1/src/lib.rs b/third_party/cargo/vendor/winapi-build-0.1.1/src/lib.rs new file mode 100644 index 0000000..fab0c6c --- /dev/null +++ b/third_party/cargo/vendor/winapi-build-0.1.1/src/lib.rs @@ -0,0 +1,14 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +pub fn link(name: &str, bundled: bool) { + use std::env::var; + let target = var("TARGET").unwrap(); + let target: Vec<_> = target.split('-').collect(); + if target.get(2) == Some(&"windows") { + println!("cargo:rustc-link-lib=dylib={}", name); + if bundled && target.get(3) == Some(&"gnu") { + let dir = var("CARGO_MANIFEST_DIR").unwrap(); + println!("cargo:rustc-link-search=native={}/{}", dir, target[0]); + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/.cargo-checksum.json b/third_party/cargo/vendor/winit-0.18.1/.cargo-checksum.json deleted file mode 100644 index eab3c62..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"21bc78e0ba4ef6b69846554ec723b4b0ad4568427d94cad2d1d8d521611d37b6","CONTRIBUTING.md":"b2ce30780143f51c660b7d575f8854bec10561a37bccaaf611f5a23041a99cc1","Cargo.toml":"797e6f14f44723b9c7eed8dfc36aeb2f8557ca010297d2467fe844de685f31fe","LICENSE":"6dc0e068dcf3a5bc8e054205b85b7720e1d49265bbc64bf515d2cf79197df69a","README.md":"12286e856c1859aa6a1b350ce24e0d5de54d97a9a9b829abeb90593637a5e633","appveyor.yml":"5238507dc1a10b6fa09883a367b5e4d5be850a04793fd8b88bde8af823df97dd","examples/cursor.rs":"e3380a2cb9d234ebe17ea35d42f72ad93876ef8ece2ade27bbfa8b347f391529","examples/cursor_grab.rs":"b2e43b7e1dfe0fb687b8e764b92ebf5f99a62e033afe724a207be0c7e407be2c","examples/fullscreen.rs":"5c31df4f6d0d990075136056b91abc7087f89ae2ff8344e5c6b0c0c3aa21a9bf","examples/handling_close.rs":"69ec624074de4af2fb4baaca5df7354a1815918103f408ddd24d556ea6529993","examples/icon.png":"4340d72fb8b5d95a10e3b2c02230f1060dff0950a137bd1d830c63dbc020dd45","examples/min_max_size.rs":"be6333d35d413f69a8247ea8198122f0488fc10929c74584e5a8e46a28b13c54","examples/monitor_list.rs":"fe0b1b5e3e309ffea053faf3b0b3e8342851af282bc89bf885235ee4a6b132e7","examples/multiwindow.rs":"55e4c88746019482e67ee7926546120bac3d371e19cc2971577e3d9757715232","examples/proxy.rs":"e1e4e6cff2dc2e393023c46061503b78622754bd653ebf8f786eaaa8958a217a","examples/resizable.rs":"e07d92e9b88f504ae7fd903a4eba0112c0113d1cb0922a534068ac331cc192f8","examples/transparent.rs":"e7a4c31c3c9f3e4a97e1bc272b10ca050a0f87931c988bd57ebc0ae137edb4a9","examples/window.rs":"3ebb9df8c8680782941a1612605e8d9e676872ab645b4ea594c7ac2c3983de28","examples/window_icon.rs":"875f1dba4deb9b669a6e52ff6936a3ae343f58d913dfcfd2fc7f23637a8a38b4","src/dpi.rs":"2d9b952576e0cf37cc09facab5140c7cbafbbc22854e574282a2bdf81fd31725","src/events.rs":"c8e9dd3508bdf9440664b73b4e04b9a2e2e499501ec4dd505e3fe599abd1f327","src/icon.rs":"3f59ac9213e4f1113fa64138e3d09505ad06561f562d2da1ce511a1ee772068d","src/lib.rs":"94d861c169f518bcfa4cbcf85c21451119f4bf3db015416317c9d4a4477a186c","src/os/android.rs":"f0a3a8acc8d33645b997338df297378510642547c1cd443c7593577bc35d43f7","src/os/ios.rs":"ebff4e61f92b48b435861030a4c48358852b05d9a644267ad1c106d5a5dde43c","src/os/macos.rs":"f26e38ac2ca36f442fc74839e9e1bbe3dc71df8cacbfff79e1adcd4ef594f25b","src/os/mod.rs":"ef2009932ff2f2e783681a997d14cd60750a5837b698444a2968b0499b9a5d0c","src/os/unix.rs":"4dfbc9dd8e26a91085b27279b7081882acf493fd874f6d9bbdfb5053da719671","src/os/windows.rs":"bf5a98340e63e32a7436be0357910a3227b2ff7af48a821114936f9b4bf9f2ec","src/platform/android/ffi.rs":"229b59cf0d8a482835ce4ec154643c1698f8baa3e2ebc52e1116eee0f2c04f9d","src/platform/android/mod.rs":"907824f8aa09ef94fa958e5c395f2e87622fbc223badef976e52e5a21704d7e7","src/platform/emscripten/ffi.rs":"7bc7d06f6a37583f9693b1793e769584b1b2ce4c107556c831160c3c75b05e81","src/platform/emscripten/mod.rs":"5e319a90b37176c7260ee603477e5bff3211bcd1eaecaaf9e21a67b96c0e492f","src/platform/ios/ffi.rs":"b2737d51d1f8c6fec58af346bd0033eb84f4ce8b165034ae9a3721748526cc98","src/platform/ios/mod.rs":"90b54a17677e68c01728b3187d67d274e185f02c8b29cf3c84208a29c402450f","src/platform/linux/dlopen.rs":"bb3da0d4c37cd8001d987b91fb0a3516bff318d9d531b78210ae66d799e9c241","src/platform/linux/mod.rs":"ed4ff513d9876d8ff40256b092aed07366e73be0f96928b1fe5df1c9bbf50fca","src/platform/linux/wayland/event_loop.rs":"ee6ec7db28319fc52afe133d5b3c7a50084c3d8bca0ef5ba8750d30630d64b4a","src/platform/linux/wayland/keyboard.rs":"69b052282d0dd44903a059823e391d910e0c32b8e36d3784a643e5000db46c92","src/platform/linux/wayland/mod.rs":"94e2a06d4c1e7db9aae126863750eaf1b1f16fed09dc1ee6efa7320c91c876ab","src/platform/linux/wayland/pointer.rs":"645873302efb578528eafcac5f4825d5aa8da14556feb99b36716f5078bd0a0b","src/platform/linux/wayland/touch.rs":"532616829085978b20b716c4a23a6c918dd4a1aa1ef1c449aef4a66e366d9f05","src/platform/linux/wayland/window.rs":"569f2855351193e2b257da878c69008b14dcd4f8ee2a2726bd1d4b0313776b88","src/platform/linux/x11/dnd.rs":"e8f08b6f732f21819ca0f561757c7af226dd084dcdd926b86b3c7ff8ece63825","src/platform/linux/x11/events.rs":"0307003d6c5d8ae68458b226fac9766920cd80ee3ba8a9bd9f0fb55e0e056181","src/platform/linux/x11/ffi.rs":"1e4b73679de689953c101a0072e9631b7be195ec5bbdbdab0526a40c6caee65e","src/platform/linux/x11/ime/callbacks.rs":"68ab9eedaae2d1a5c203edb46a940406c8215f32e3d02494f8089988fbd97c21","src/platform/linux/x11/ime/context.rs":"4fb3d2be0eaa07c084ecd453b7f6ca070fd2db5dbe475663948860c23c66a498","src/platform/linux/x11/ime/inner.rs":"8ee005cb68ea12432f8c526f185ff461498efba4f7f76c81b9386a751f5c5dcf","src/platform/linux/x11/ime/input_method.rs":"9fbddd9068f7b6400b9914b05c1a91046cc8f4f72433a7debb5bd79f7e0f0aac","src/platform/linux/x11/ime/mod.rs":"e4b81489f170daa525dddafa38f53a759c5ec9dc2b75f30a559dbceabc943e79","src/platform/linux/x11/mod.rs":"2672f96e82c735665b27a37d270e0c8b96564176d8695b7e401edd62c1638a7d","src/platform/linux/x11/monitor.rs":"a59df2bdd8555b1fe5d274f28334bf35c01fd7f686a4f6d2e2666942bff1f1fb","src/platform/linux/x11/util/atom.rs":"557b546ef237dd7a51820e40077c02e26c6c3581ffbe904875f4c60b06191337","src/platform/linux/x11/util/client_msg.rs":"206c5481e8bd2163b59a8c75bf0a50b40a8307612884cb4fe9cd8044f026fa14","src/platform/linux/x11/util/format.rs":"01c19e93c04bb05cd67988f0594a26281d74e4464c2c96115eb5912801b81caa","src/platform/linux/x11/util/geometry.rs":"389c112e8ba74e6b982c785775da2521cb585f6597f93f4bdfe390940efa81f0","src/platform/linux/x11/util/hint.rs":"071e3b68640804e69341068fec59a6207c1a7f61619532ba38fdff8271693046","src/platform/linux/x11/util/icon.rs":"8c435ccd89148697ea6746a44208105f41bdab4a61d363637e2ffba3e9cae0d8","src/platform/linux/x11/util/input.rs":"24a6c356f05f2d57abab7f1c42efb0850ba0e0323b3e8537c027b42942396320","src/platform/linux/x11/util/memory.rs":"aa35e341e78878cbc8f856dde2b7aeb31a34d88cb61f9132c76b336a9c8c37b7","src/platform/linux/x11/util/mod.rs":"e7f5f3591ff8b85b6cc1cc71c8d1e98921f51c889cbff6f35163048bfc41bc32","src/platform/linux/x11/util/randr.rs":"1aee592ded5c3b5fdc6ec17ed8beb91a182209c0ba7230d553e801fd94207185","src/platform/linux/x11/util/window_property.rs":"479a8791ba06a64794e18b26db61e2f1904a9773061c48f6e43eb9391bafc1fb","src/platform/linux/x11/util/wm.rs":"a2ea247d2c65da5ee1feb22b0eb8ca8181c9e69e54835c3a6bff9d85fcd84b67","src/platform/linux/x11/window.rs":"44ae08a4d5560f11d169eb9e4b2595f6dd0ad58fdc8422d64453d920f0628e75","src/platform/linux/x11/xdisplay.rs":"e8391c9374b11cace9c3297df4554cbe5b0dc26b7ef8c23814b74b06d402cc57","src/platform/macos/events_loop.rs":"a82f9ced90f3c30b43d0df5c6810ec1f42aa0acaffd012ee06b77b7c54ff4c3a","src/platform/macos/ffi.rs":"05dfa9d37e6e25ca931704a7703d638b914e207a712097616b99d76d2e6dbe1f","src/platform/macos/mod.rs":"5060640a333aea78f560b90376335abb54339b7a11fc3ba04ad954cc1592d64a","src/platform/macos/monitor.rs":"e77d7bea35ac9b4e10fa1270099043b2d8283921af4ece31c772fe13833c311d","src/platform/macos/util/cursor.rs":"6355e64e1ff62028f69daac0cbacbe43ff9919b52dbe45d946e0c106d5256944","src/platform/macos/util/into_option.rs":"7bbfe330a5e32fc342ca471471a95f5d9c9b986946334ccdbe5f5ce617078363","src/platform/macos/util/mod.rs":"4f65062a069db738848cc6a1ad345ebcc2cabc2f5077d6873e292d2b801c2a9e","src/platform/macos/view.rs":"9f8ff5ed9598416df1cbfcb7ec1c9833273b00e5ec227bc073cdbd9ca6387340","src/platform/macos/window.rs":"6b5f0a28de4760c66b5785137be0fa3b4074a6e96582c3c8d8448de704e3913f","src/platform/mod.rs":"46ab9469d5cceb8d6c8abeb6702afff192026430a13c53ba53d1fa54317c45db","src/platform/windows/dpi.rs":"676001f721cf6a19f94e8e918e5e196063eca84b842fb1cf2d98120b452cde24","src/platform/windows/drop_handler.rs":"ba15e54c4bafa822377cf68abbb162b1f2490ec130d947c5a537735d1c4754c8","src/platform/windows/event.rs":"e4ac1baa001bf0df41ec8ae82bcdc4d3c216a46fe82f19439743cad5eb3eb4da","src/platform/windows/events_loop.rs":"9c7367571c66f553123bb5313a4ea8472f33938d8d62d59248ea0fa534db6bf1","src/platform/windows/icon.rs":"36ebdbbb13159021baa4ab83cfffeabfe0fd41a1281eb170374b9ad773015ac0","src/platform/windows/mod.rs":"3147d497ba297658565ff5121e498ce2ba5b771dd51addd7d14c834902b48f62","src/platform/windows/monitor.rs":"6b7895366c693ad44c1719a931a32baedf21ef4bc33d906adfccc99ff4e1f4d7","src/platform/windows/raw_input.rs":"407a2b7f75145cc0f5f5423c45a13b24865f690c5173d76a0396e4e0f1dcc634","src/platform/windows/util.rs":"91c1525a3cbaa7217c4485165dc7c558f1993a82bb29371e39039155b2dda6b7","src/platform/windows/window.rs":"3b8a4bc032150c17ea2fe2cfc14c9f7b293f66afee90d7ed2c824f8ec001d92c","src/window.rs":"be0fc4232fde4ce0032d2d7a892f1473c83501fba93b0d954886b5116416da08","tests/send_objects.rs":"8afcfed9702d1ef656e478ee7bdd1f3f2f8b9c092306c9b3e2240ebbeb01dde0","tests/serde_objects.rs":"0f29db9a798db854e4f06f8aca7977f247a6e3b3f90a492a19638a42ec9c7595","tests/sync_object.rs":"70ebde6478cb4404c004c4e59a1f4da293a34c14763ca86c87c59521a0a38c00"},"package":"8c57c15bd4c0ef18dff33e263e452abe32d00e2e05771cacaa410a14cc1c0776"} \ No newline at end of file diff --git a/third_party/cargo/vendor/winit-0.18.1/CONTRIBUTING.md b/third_party/cargo/vendor/winit-0.18.1/CONTRIBUTING.md deleted file mode 100644 index d32ec8a..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/CONTRIBUTING.md +++ /dev/null @@ -1,70 +0,0 @@ -# Winit Contributing Guidelines - -## Scope - -Winit aims to provide a generic platform abstracting the main graphic platforms (Windows, macOS, X11, -Wayland, Android, iOS and the web platform via Emscripten). - -Most platforms expose capabilities that cannot be meaningfully transposed to the others. Winit does not -aim to support every single functionality of every platform, but rather to abstract the set of -capabilities that is common to all platforms. In this context, APIs exposed in winit can be split into -different "support levels": - -- Tier 1: features which are in the main scope of winit. They are part of the common API of winit, and - are taken care of by the maintainers. Any part of these features that is not working correctly is - considered a bug in winit. -- Tier 2: some platform-specific features can be sufficiently fundamental to the platform that winit can - integrate support for them in the platform-specific part of the API. These features are not considered - directly handled by the maintainers of winit. If you have a strong incentive to have such a feature - integrated in winit, consider implementing it and proposing yourself to maintain it in the future. -- Tier 3: these features are not directly exposed by winit, but rather can be implemented using the - raw handles to the underlying platform that winit exposes. If your feature of interest is rather - niche, this is probably where it belongs. - -The exact list of supported Tier 1 features is tracked in this issue: -[#252](https://github.com/tomaka/winit/issues/252). - -## Reporting an issue - -When reporting an issue, in order to help the maintainers understand what the problem is, please make -your description of the issue as detailed as possible: - -- if it is a bug, please provide clear explanation of what happens, what should happen, and how to - reproduce the issue, ideally by providing a minimal program exhibiting the problem -- if it is a feature request, please provide a clear argumentation about why you believe this feature - should be supported by winit - -## Making a pull request - -When making a code contribution to winit, before opening your pull request, please make sure that: - -- you tested your modifications on all the platforms impacted, or if not possible detail which platforms - were not tested, and what should be tested, so that a maintainer or another contributor can test them -- you updated any relevant documentation in winit -- you left comments in your code explaining any part that is not straightforward, so that the - maintainers and future contributors don't have to try to guess what your code is supposed to do -- your PR adds an entry to the changelog file if the introduced change is relevant to winit users - -Once your PR is open, you can ask for review by a maintainer of your platform. Winit's merging policy -is that a PR must be approved by at least two maintainers of winit before being merged, including -at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it). - -## Maintainers & Testers - -Winit is managed by several people, each with their specialities, and each maintaining a subset of the -backends of winit. As such, depending on your platform of interest, your contacts will be different. - -This table summarizes who can be contacted in which case, with the following legend: - -- `M`: is a main maintainer for this platform -- `R`: can review code for this platform -- `T`: has the ability of testing the platform -- ` `: knows nothing of this platform - -| Platform | Windows | macOS | X11 | Wayland | Android | iOS | Emscripten | -| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | -| @francesca64 | R | M | M | | M | R | | -| @mitchmindtree | T | | T | T | | | | -| @Osspial | M | | T | T | T | | T | -| @vberger | | | T | M | | | | -| @mtak- | | T | | | T | M | | diff --git a/third_party/cargo/vendor/winit-0.18.1/README.md b/third_party/cargo/vendor/winit-0.18.1/README.md deleted file mode 100644 index 0360e12..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# winit - Cross-platform window creation and management in Rust - -[![](http://meritbadge.herokuapp.com/winit)](https://crates.io/crates/winit) -[![Docs.rs](https://docs.rs/winit/badge.svg)](https://docs.rs/winit) -[![Build Status](https://travis-ci.org/tomaka/winit.svg?branch=master)](https://travis-ci.org/tomaka/winit) -[![Build status](https://ci.appveyor.com/api/projects/status/5h87hj0g4q2xe3j9/branch/master?svg=true)](https://ci.appveyor.com/project/tomaka/winit/branch/master) - -```toml -[dependencies] -winit = "0.18.1" -``` - -## [Documentation](https://docs.rs/winit) - -## Usage - -Winit is a window creation and management library. It can create windows and lets you handle -events (for example: the window being resized, a key being pressed, a mouse movement, etc.) -produced by window. - -Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to -show something on the window you need to use the platform-specific getters provided by winit, or -another library. - -```rust -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - let window = winit::Window::new(&events_loop).unwrap(); - - events_loop.run_forever(|event| { - match event { - winit::Event::WindowEvent { - event: winit::WindowEvent::CloseRequested, - .. - } => winit::ControlFlow::Break, - _ => winit::ControlFlow::Continue, - } - }); -} -``` - -Winit is only officially supported on the latest stable version of the Rust compiler. - -### Cargo Features - -Winit provides the following features, which can be enabled in your `Cargo.toml` file: -* `icon_loading`: Enables loading window icons directly from files. Depends on the [`image` crate](https://crates.io/crates/image). -* `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). - -### Platform-specific usage - -#### Emscripten and WebAssembly - -Building a binary will yield a `.js` file. In order to use it in an HTML file, you need to: - -- Put a `` element somewhere. A canvas corresponds to a winit "window". -- Write a Javascript code that creates a global variable named `Module`. Set `Module.canvas` to - the element of the `` element (in the example you would retrieve it via `document.getElementById("my_id")`). - More information [here](https://kripken.github.io/emscripten-site/docs/api_reference/module.html). -- Make sure that you insert the `.js` file generated by Rust after the `Module` variable is created. diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/cursor.rs b/third_party/cargo/vendor/winit-0.18.1/examples/cursor.rs deleted file mode 100644 index d2df71a..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/cursor.rs +++ /dev/null @@ -1,32 +0,0 @@ -extern crate winit; - -use winit::{Event, ElementState, MouseCursor, WindowEvent, KeyboardInput, ControlFlow}; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let window = winit::WindowBuilder::new().build(&events_loop).unwrap(); - window.set_title("A fantastic window!"); - - let cursors = [MouseCursor::Default, MouseCursor::Crosshair, MouseCursor::Hand, MouseCursor::Arrow, MouseCursor::Move, MouseCursor::Text, MouseCursor::Wait, MouseCursor::Help, MouseCursor::Progress, MouseCursor::NotAllowed, MouseCursor::ContextMenu, MouseCursor::Cell, MouseCursor::VerticalText, MouseCursor::Alias, MouseCursor::Copy, MouseCursor::NoDrop, MouseCursor::Grab, MouseCursor::Grabbing, MouseCursor::AllScroll, MouseCursor::ZoomIn, MouseCursor::ZoomOut, MouseCursor::EResize, MouseCursor::NResize, MouseCursor::NeResize, MouseCursor::NwResize, MouseCursor::SResize, MouseCursor::SeResize, MouseCursor::SwResize, MouseCursor::WResize, MouseCursor::EwResize, MouseCursor::NsResize, MouseCursor::NeswResize, MouseCursor::NwseResize, MouseCursor::ColResize, MouseCursor::RowResize]; - let mut cursor_idx = 0; - - events_loop.run_forever(|event| { - match event { - Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, .. }, .. }, .. } => { - println!("Setting cursor to \"{:?}\"", cursors[cursor_idx]); - window.set_cursor(cursors[cursor_idx]); - if cursor_idx < cursors.len() - 1 { - cursor_idx += 1; - } else { - cursor_idx = 0; - } - }, - Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { - return ControlFlow::Break; - }, - _ => () - } - ControlFlow::Continue - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/cursor_grab.rs b/third_party/cargo/vendor/winit-0.18.1/examples/cursor_grab.rs deleted file mode 100644 index 641a324..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/cursor_grab.rs +++ /dev/null @@ -1,38 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let window = winit::WindowBuilder::new() - .with_title("Super Cursor Grab'n'Hide Simulator 9000") - .build(&events_loop) - .unwrap(); - - events_loop.run_forever(|event| { - if let winit::Event::WindowEvent { event, .. } = event { - use winit::WindowEvent::*; - match event { - CloseRequested => return winit::ControlFlow::Break, - KeyboardInput { - input: winit::KeyboardInput { - state: winit::ElementState::Released, - virtual_keycode: Some(key), - modifiers, - .. - }, - .. - } => { - use winit::VirtualKeyCode::*; - match key { - Escape => return winit::ControlFlow::Break, - G => window.grab_cursor(!modifiers.shift).unwrap(), - H => window.hide_cursor(!modifiers.shift), - _ => (), - } - } - _ => (), - } - } - winit::ControlFlow::Continue - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/fullscreen.rs b/third_party/cargo/vendor/winit-0.18.1/examples/fullscreen.rs deleted file mode 100644 index c29013c..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/fullscreen.rs +++ /dev/null @@ -1,121 +0,0 @@ -extern crate winit; - -use std::io::{self, Write}; -use winit::{ControlFlow, Event, WindowEvent}; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - #[cfg(target_os = "macos")] - let mut macos_use_simple_fullscreen = false; - - let monitor = { - // On macOS there are two fullscreen modes "native" and "simple" - #[cfg(target_os = "macos")] - { - print!("Please choose the fullscreen mode: (1) native, (2) simple: "); - io::stdout().flush().unwrap(); - - let mut num = String::new(); - io::stdin().read_line(&mut num).unwrap(); - let num = num.trim().parse().ok().expect("Please enter a number"); - match num { - 2 => macos_use_simple_fullscreen = true, - _ => {} - } - - // Prompt for monitor when using native fullscreen - if !macos_use_simple_fullscreen { - Some(prompt_for_monitor(&events_loop)) - } else { - None - } - } - - #[cfg(not(target_os = "macos"))] - Some(prompt_for_monitor(&events_loop)) - }; - - let mut is_fullscreen = monitor.is_some(); - let mut is_maximized = false; - let mut decorations = true; - - let window = winit::WindowBuilder::new() - .with_title("Hello world!") - .with_fullscreen(monitor) - .build(&events_loop) - .unwrap(); - - events_loop.run_forever(|event| { - println!("{:?}", event); - - match event { - Event::WindowEvent { event, .. } => match event { - WindowEvent::CloseRequested => return ControlFlow::Break, - WindowEvent::KeyboardInput { - input: - winit::KeyboardInput { - virtual_keycode: Some(virtual_code), - state, - .. - }, - .. - } => match (virtual_code, state) { - (winit::VirtualKeyCode::Escape, _) => return ControlFlow::Break, - (winit::VirtualKeyCode::F, winit::ElementState::Pressed) => { - #[cfg(target_os = "macos")] - { - if macos_use_simple_fullscreen { - use winit::os::macos::WindowExt; - if WindowExt::set_simple_fullscreen(&window, !is_fullscreen) { - is_fullscreen = !is_fullscreen; - } - - return ControlFlow::Continue; - } - } - - is_fullscreen = !is_fullscreen; - if !is_fullscreen { - window.set_fullscreen(None); - } else { - window.set_fullscreen(Some(window.get_current_monitor())); - } - } - (winit::VirtualKeyCode::M, winit::ElementState::Pressed) => { - is_maximized = !is_maximized; - window.set_maximized(is_maximized); - } - (winit::VirtualKeyCode::D, winit::ElementState::Pressed) => { - decorations = !decorations; - window.set_decorations(decorations); - } - _ => (), - }, - _ => (), - }, - _ => {} - } - - ControlFlow::Continue - }); -} - -// Enumerate monitors and prompt user to choose one -fn prompt_for_monitor(events_loop: &winit::EventsLoop) -> winit::MonitorId { - for (num, monitor) in events_loop.get_available_monitors().enumerate() { - println!("Monitor #{}: {:?}", num, monitor.get_name()); - } - - print!("Please write the number of the monitor to use: "); - io::stdout().flush().unwrap(); - - let mut num = String::new(); - io::stdin().read_line(&mut num).unwrap(); - let num = num.trim().parse().ok().expect("Please enter a number"); - let monitor = events_loop.get_available_monitors().nth(num).expect("Please enter a valid ID"); - - println!("Using {:?}", monitor.get_name()); - - monitor -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/handling_close.rs b/third_party/cargo/vendor/winit-0.18.1/examples/handling_close.rs deleted file mode 100644 index 101f45c..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/handling_close.rs +++ /dev/null @@ -1,74 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let _window = winit::WindowBuilder::new() - .with_title("Your faithful window") - .build(&events_loop) - .unwrap(); - - let mut close_requested = false; - - events_loop.run_forever(|event| { - use winit::WindowEvent::*; - use winit::ElementState::Released; - use winit::VirtualKeyCode::{N, Y}; - - match event { - winit::Event::WindowEvent { event, .. } => match event { - CloseRequested => { - // `CloseRequested` is sent when the close button on the window is pressed (or - // through whatever other mechanisms the window manager provides for closing a - // window). If you don't handle this event, the close button won't actually do - // anything. - - // A common thing to do here is prompt the user if they have unsaved work. - // Creating a proper dialog box for that is far beyond the scope of this - // example, so here we'll just respond to the Y and N keys. - println!("Are you ready to bid your window farewell? [Y/N]"); - close_requested = true; - - // In applications where you can safely close the window without further - // action from the user, this is generally where you'd handle cleanup before - // closing the window. How to close the window is detailed in the handler for - // the Y key. - } - KeyboardInput { - input: - winit::KeyboardInput { - virtual_keycode: Some(virtual_code), - state: Released, - .. - }, - .. - } => match virtual_code { - Y => { - if close_requested { - // This is where you'll want to do any cleanup you need. - println!("Buh-bye!"); - - // For a single-window application like this, you'd normally just - // break out of the event loop here. If you wanted to keep running the - // event loop (i.e. if it's a multi-window application), you need to - // drop the window. That closes it, and results in `Destroyed` being - // sent. - return winit::ControlFlow::Break; - } - } - N => { - if close_requested { - println!("Your window will continue to stay by your side."); - close_requested = false; - } - } - _ => (), - }, - _ => (), - }, - _ => (), - } - - winit::ControlFlow::Continue - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/min_max_size.rs b/third_party/cargo/vendor/winit-0.18.1/examples/min_max_size.rs deleted file mode 100644 index 06f4aa1..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/min_max_size.rs +++ /dev/null @@ -1,23 +0,0 @@ -extern crate winit; - -use winit::dpi::LogicalSize; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let window = winit::WindowBuilder::new() - .build(&events_loop) - .unwrap(); - - window.set_min_dimensions(Some(LogicalSize::new(400.0, 200.0))); - window.set_max_dimensions(Some(LogicalSize::new(800.0, 400.0))); - - events_loop.run_forever(|event| { - println!("{:?}", event); - - match event { - winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break, - _ => winit::ControlFlow::Continue, - } - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/monitor_list.rs b/third_party/cargo/vendor/winit-0.18.1/examples/monitor_list.rs deleted file mode 100644 index e40ac30..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/monitor_list.rs +++ /dev/null @@ -1,7 +0,0 @@ -extern crate winit; - -fn main() { - let event_loop = winit::EventsLoop::new(); - let window = winit::WindowBuilder::new().build(&event_loop).unwrap(); - println!("{:#?}\nPrimary: {:#?}", window.get_available_monitors(), window.get_primary_monitor()); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/multiwindow.rs b/third_party/cargo/vendor/winit-0.18.1/examples/multiwindow.rs deleted file mode 100644 index b558aa2..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/multiwindow.rs +++ /dev/null @@ -1,33 +0,0 @@ -extern crate winit; - -use std::collections::HashMap; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let mut windows = HashMap::new(); - for _ in 0..3 { - let window = winit::Window::new(&events_loop).unwrap(); - windows.insert(window.id(), window); - } - - events_loop.run_forever(|event| { - match event { - winit::Event::WindowEvent { - event: winit::WindowEvent::CloseRequested, - window_id, - } => { - println!("Window {:?} has received the signal to close", window_id); - - // This drops the window, causing it to close. - windows.remove(&window_id); - - if windows.is_empty() { - return winit::ControlFlow::Break; - } - } - _ => (), - } - winit::ControlFlow::Continue - }) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/proxy.rs b/third_party/cargo/vendor/winit-0.18.1/examples/proxy.rs deleted file mode 100644 index a975181..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/proxy.rs +++ /dev/null @@ -1,29 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let _window = winit::WindowBuilder::new() - .with_title("A fantastic window!") - .build(&events_loop) - .unwrap(); - - let proxy = events_loop.create_proxy(); - - std::thread::spawn(move || { - // Wake up the `events_loop` once every second. - loop { - std::thread::sleep(std::time::Duration::from_secs(1)); - proxy.wakeup().unwrap(); - } - }); - - events_loop.run_forever(|event| { - println!("{:?}", event); - match event { - winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => - winit::ControlFlow::Break, - _ => winit::ControlFlow::Continue, - } - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/resizable.rs b/third_party/cargo/vendor/winit-0.18.1/examples/resizable.rs deleted file mode 100644 index 749e852..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/resizable.rs +++ /dev/null @@ -1,38 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let mut resizable = false; - - let window = winit::WindowBuilder::new() - .with_title("Hit space to toggle resizability.") - .with_dimensions((400, 200).into()) - .with_resizable(resizable) - .build(&events_loop) - .unwrap(); - - events_loop.run_forever(|event| { - match event { - winit::Event::WindowEvent { event, .. } => match event { - winit::WindowEvent::CloseRequested => return winit::ControlFlow::Break, - winit::WindowEvent::KeyboardInput { - input: - winit::KeyboardInput { - virtual_keycode: Some(winit::VirtualKeyCode::Space), - state: winit::ElementState::Released, - .. - }, - .. - } => { - resizable = !resizable; - println!("Resizable: {}", resizable); - window.set_resizable(resizable); - } - _ => (), - }, - _ => (), - }; - winit::ControlFlow::Continue - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/transparent.rs b/third_party/cargo/vendor/winit-0.18.1/examples/transparent.rs deleted file mode 100644 index a558350..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/transparent.rs +++ /dev/null @@ -1,20 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let window = winit::WindowBuilder::new().with_decorations(false) - .with_transparency(true) - .build(&events_loop).unwrap(); - - window.set_title("A fantastic window!"); - - events_loop.run_forever(|event| { - println!("{:?}", event); - - match event { - winit::Event::WindowEvent { event: winit::WindowEvent::CloseRequested, .. } => winit::ControlFlow::Break, - _ => winit::ControlFlow::Continue, - } - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/window.rs b/third_party/cargo/vendor/winit-0.18.1/examples/window.rs deleted file mode 100644 index fcc7d9e..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/window.rs +++ /dev/null @@ -1,22 +0,0 @@ -extern crate winit; - -fn main() { - let mut events_loop = winit::EventsLoop::new(); - - let _window = winit::WindowBuilder::new() - .with_title("A fantastic window!") - .build(&events_loop) - .unwrap(); - - events_loop.run_forever(|event| { - println!("{:?}", event); - - match event { - winit::Event::WindowEvent { - event: winit::WindowEvent::CloseRequested, - .. - } => winit::ControlFlow::Break, - _ => winit::ControlFlow::Continue, - } - }); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/window_icon.rs b/third_party/cargo/vendor/winit-0.18.1/examples/window_icon.rs deleted file mode 100644 index 5be1433..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/examples/window_icon.rs +++ /dev/null @@ -1,94 +0,0 @@ -// Heads up: you need to compile this example with `--features icon_loading`. -// `Icon::from_path` won't be available otherwise, though for your own applications, you could use -// `Icon::from_rgba` if you don't want to depend on the `image` crate. - -extern crate winit; -#[cfg(feature = "icon_loading")] -extern crate image; - -#[cfg(feature = "icon_loading")] -fn main() { - use winit::Icon; - // You'll have to choose an icon size at your own discretion. On X11, the desired size varies - // by WM, and on Windows, you still have to account for screen scaling. Here we use 32px, - // since it seems to work well enough in most cases. Be careful about going too high, or - // you'll be bitten by the low-quality downscaling built into the WM. - let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png"); - // While `Icon::from_path` is the most straightforward, you have a few other options. If you - // want to use the `include_bytes` macro, then pass the result to `Icon::from_bytes`. See the - // docs for the full list of options (you'll have to generate the docs with the `icon_loading` - // feature enabled). - let icon = Icon::from_path(path).expect("Failed to open icon"); - - let mut events_loop = winit::EventsLoop::new(); - - let window = winit::WindowBuilder::new() - .with_title("An iconic window!") - // At present, this only does anything on Windows and X11, so if you want to save load - // time, you can put icon loading behind a function that returns `None` on other platforms. - .with_window_icon(Some(icon)) - .build(&events_loop) - .unwrap(); - - events_loop.run_forever(|event| { - if let winit::Event::WindowEvent { event, .. } = event { - use winit::WindowEvent::*; - match event { - CloseRequested => return winit::ControlFlow::Break, - DroppedFile(path) => { - use image::GenericImageView; - - let icon_image = image::open(path).expect("Failed to open window icon"); - - let (width, height) = icon_image.dimensions(); - const DESIRED_SIZE: u32 = 32; - let (new_width, new_height) = if width == height { - (DESIRED_SIZE, DESIRED_SIZE) - } else { - // Note that this will never divide by zero, due to the previous condition. - let aspect_adjustment = DESIRED_SIZE as f64 - / std::cmp::max(width, height) as f64; - ( - (width as f64 * aspect_adjustment) as u32, - (height as f64 * aspect_adjustment) as u32, - ) - }; - - // By scaling the icon ourselves, we get higher-quality filtering and save - // some memory. - let icon = image::imageops::resize( - &icon_image, - new_width, - new_height, - image::FilterType::Lanczos3, - ); - - let (offset_x, offset_y) = ( - (DESIRED_SIZE - new_width) / 2, - (DESIRED_SIZE - new_height) / 2, - ); - - let mut canvas = image::ImageBuffer::new(DESIRED_SIZE, DESIRED_SIZE); - image::imageops::replace( - &mut canvas, - &icon, - offset_x, - offset_y, - ); - - window.set_window_icon(Some(canvas.into())); - }, - _ => (), - } - } - winit::ControlFlow::Continue - }); -} - -#[cfg(not(feature = "icon_loading"))] -fn main() { - print!( -r#"This example requires the `icon_loading` feature: - cargo run --example window_icon --features icon_loading -"#); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/dpi.rs b/third_party/cargo/vendor/winit-0.18.1/src/dpi.rs deleted file mode 100644 index 0d15142..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/dpi.rs +++ /dev/null @@ -1,331 +0,0 @@ - -//! DPI is important, so read the docs for this module if you don't want to be confused. -//! -//! Originally, `winit` dealt entirely in physical pixels (excluding unintentional inconsistencies), but now all -//! window-related functions both produce and consume logical pixels. Monitor-related functions still use physical -//! pixels, as do any context-related functions in `glutin`. -//! -//! If you've never heard of these terms before, then you're not alone, and this documentation will explain the -//! concepts. -//! -//! Modern screens have a defined physical resolution, most commonly 1920x1080. Indepedent of that is the amount of -//! space the screen occupies, which is to say, the height and width in millimeters. The relationship between these two -//! measurements is the *pixel density*. Mobile screens require a high pixel density, as they're held close to the -//! eyes. Larger displays also require a higher pixel density, hence the growing presence of 1440p and 4K displays. -//! -//! So, this presents a problem. Let's say we want to render a square 100px button. It will occupy 100x100 of the -//! screen's pixels, which in many cases, seems perfectly fine. However, because this size doesn't account for the -//! screen's dimensions or pixel density, the button's size can vary quite a bit. On a 4K display, it would be unusably -//! small. -//! -//! That's a description of what happens when the button is 100x100 *physical* pixels. Instead, let's try using 100x100 -//! *logical* pixels. To map logical pixels to physical pixels, we simply multiply by the DPI (dots per inch) factor. -//! On a "typical" desktop display, the DPI factor will be 1.0, so 100x100 logical pixels equates to 100x100 physical -//! pixels. However, a 1440p display may have a DPI factor of 1.25, so the button is rendered as 125x125 physical pixels. -//! Ideally, the button now has approximately the same perceived size across varying displays. -//! -//! Failure to account for the DPI factor can create a badly degraded user experience. Most notably, it can make users -//! feel like they have bad eyesight, which will potentially cause them to think about growing elderly, resulting in -//! them entering an existential panic. Once users enter that state, they will no longer be focused on your application. -//! -//! There are two ways to get the DPI factor: -//! - You can track the [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) event of your -//! windows. This event is sent any time the DPI factor changes, either because the window moved to another monitor, -//! or because the user changed the configuration of their screen. -//! - You can also retrieve the DPI factor of a monitor by calling -//! [`MonitorId::get_hidpi_factor`](../struct.MonitorId.html#method.get_hidpi_factor), or the -//! current DPI factor applied to a window by calling -//! [`Window::get_hidpi_factor`](../struct.Window.html#method.get_hidpi_factor), which is roughly equivalent -//! to `window.get_current_monitor().get_hidpi_factor()`. -//! -//! Depending on the platform, the window's actual DPI factor may only be known after -//! the event loop has started and your window has been drawn once. To properly handle these cases, -//! the most robust way is to monitor the [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) -//! event and dynamically adapt your drawing logic to follow the DPI factor. -//! -//! Here's an overview of what sort of DPI factors you can expect, and where they come from: -//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the display settings. -//! While users are free to select any option they want, they're only given a selection of "nice" DPI factors, i.e. -//! 1.0, 1.25, 1.5... on Windows 7, the DPI factor is global and changing it requires logging out. -//! - **macOS:** The buzzword is "retina displays", which have a DPI factor of 2.0. Otherwise, the DPI factor is 1.0. -//! Intermediate DPI factors are never used, thus 1440p displays/etc. aren't properly supported. It's possible for any -//! display to use that 2.0 DPI factor, given the use of the command line. -//! - **X11:** On X11, we calcuate the DPI factor based on the millimeter dimensions provided by XRandR. This can -//! result in a wide range of possible values, including some interesting ones like 1.0833333333333333. This can be -//! overridden using the `WINIT_HIDPI_FACTOR` environment variable, though that's not recommended. -//! - **Wayland:** On Wayland, DPI factors are set per-screen by the server, and are always integers (most often 1 or 2). -//! - **iOS:** DPI factors are both constant and device-specific on iOS. -//! - **Android:** This feature isn't yet implemented on Android, so the DPI factor will always be returned as 1.0. -//! -//! The window's logical size is conserved across DPI changes, resulting in the physical size changing instead. This -//! may be surprising on X11, but is quite standard elsewhere. Physical size changes always produce a -//! [`Resized`](../enum.WindowEvent.html#variant.Resized) event, even on platforms where no resize actually occurs, -//! such as macOS and Wayland. As a result, it's not necessary to separately handle -//! [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) if you're only listening for size. -//! -//! Your GPU has no awareness of the concept of logical pixels, and unless you like wasting pixel density, your -//! framebuffer's size should be in physical pixels. -//! -//! `winit` will send [`Resized`](../enum.WindowEvent.html#variant.Resized) events whenever a window's logical size -//! changes, and [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) events -//! whenever the DPI factor changes. Receiving either of these events means that the physical size of your window has -//! changed, and you should recompute it using the latest values you received for each. If the logical size and the -//! DPI factor change simultaneously, `winit` will send both events together; thus, it's recommended to buffer -//! these events and process them at the end of the queue. -//! -//! If you never received any [`HiDpiFactorChanged`](../enum.WindowEvent.html#variant.HiDpiFactorChanged) events, -//! then your window's DPI factor is 1. - -/// Checks that the DPI factor is a normal positive `f64`. -/// -/// All functions that take a DPI factor assert that this will return `true`. If you're sourcing DPI factors from -/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit; -/// otherwise, you risk panics. -#[inline] -pub fn validate_hidpi_factor(dpi_factor: f64) -> bool { - dpi_factor.is_sign_positive() && dpi_factor.is_normal() -} - -/// A position represented in logical pixels. -/// -/// The position is stored as floats, so please be careful. Casting floats to integers truncates the fractional part, -/// which can cause noticable issues. To help with that, an `Into<(i32, i32)>` implementation is provided which -/// does the rounding for you. -#[derive(Debug, Copy, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct LogicalPosition { - pub x: f64, - pub y: f64, -} - -impl LogicalPosition { - #[inline] - pub fn new(x: f64, y: f64) -> Self { - LogicalPosition { x, y } - } - - #[inline] - pub fn from_physical>(physical: T, dpi_factor: f64) -> Self { - physical.into().to_logical(dpi_factor) - } - - #[inline] - pub fn to_physical(&self, dpi_factor: f64) -> PhysicalPosition { - assert!(validate_hidpi_factor(dpi_factor)); - let x = self.x * dpi_factor; - let y = self.y * dpi_factor; - PhysicalPosition::new(x, y) - } -} - -impl From<(f64, f64)> for LogicalPosition { - #[inline] - fn from((x, y): (f64, f64)) -> Self { - Self::new(x, y) - } -} - -impl From<(i32, i32)> for LogicalPosition { - #[inline] - fn from((x, y): (i32, i32)) -> Self { - Self::new(x as f64, y as f64) - } -} - -impl Into<(f64, f64)> for LogicalPosition { - #[inline] - fn into(self) -> (f64, f64) { - (self.x, self.y) - } -} - -impl Into<(i32, i32)> for LogicalPosition { - /// Note that this rounds instead of truncating. - #[inline] - fn into(self) -> (i32, i32) { - (self.x.round() as _, self.y.round() as _) - } -} - -/// A position represented in physical pixels. -/// -/// The position is stored as floats, so please be careful. Casting floats to integers truncates the fractional part, -/// which can cause noticable issues. To help with that, an `Into<(i32, i32)>` implementation is provided which -/// does the rounding for you. -#[derive(Debug, Copy, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct PhysicalPosition { - pub x: f64, - pub y: f64, -} - -impl PhysicalPosition { - #[inline] - pub fn new(x: f64, y: f64) -> Self { - PhysicalPosition { x, y } - } - - #[inline] - pub fn from_logical>(logical: T, dpi_factor: f64) -> Self { - logical.into().to_physical(dpi_factor) - } - - #[inline] - pub fn to_logical(&self, dpi_factor: f64) -> LogicalPosition { - assert!(validate_hidpi_factor(dpi_factor)); - let x = self.x / dpi_factor; - let y = self.y / dpi_factor; - LogicalPosition::new(x, y) - } -} - -impl From<(f64, f64)> for PhysicalPosition { - #[inline] - fn from((x, y): (f64, f64)) -> Self { - Self::new(x, y) - } -} - -impl From<(i32, i32)> for PhysicalPosition { - #[inline] - fn from((x, y): (i32, i32)) -> Self { - Self::new(x as f64, y as f64) - } -} - -impl Into<(f64, f64)> for PhysicalPosition { - #[inline] - fn into(self) -> (f64, f64) { - (self.x, self.y) - } -} - -impl Into<(i32, i32)> for PhysicalPosition { - /// Note that this rounds instead of truncating. - #[inline] - fn into(self) -> (i32, i32) { - (self.x.round() as _, self.y.round() as _) - } -} - -/// A size represented in logical pixels. -/// -/// The size is stored as floats, so please be careful. Casting floats to integers truncates the fractional part, -/// which can cause noticable issues. To help with that, an `Into<(u32, u32)>` implementation is provided which -/// does the rounding for you. -#[derive(Debug, Copy, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct LogicalSize { - pub width: f64, - pub height: f64, -} - -impl LogicalSize { - #[inline] - pub fn new(width: f64, height: f64) -> Self { - LogicalSize { width, height } - } - - #[inline] - pub fn from_physical>(physical: T, dpi_factor: f64) -> Self { - physical.into().to_logical(dpi_factor) - } - - #[inline] - pub fn to_physical(&self, dpi_factor: f64) -> PhysicalSize { - assert!(validate_hidpi_factor(dpi_factor)); - let width = self.width * dpi_factor; - let height = self.height * dpi_factor; - PhysicalSize::new(width, height) - } -} - -impl From<(f64, f64)> for LogicalSize { - #[inline] - fn from((width, height): (f64, f64)) -> Self { - Self::new(width, height) - } -} - -impl From<(u32, u32)> for LogicalSize { - #[inline] - fn from((width, height): (u32, u32)) -> Self { - Self::new(width as f64, height as f64) - } -} - -impl Into<(f64, f64)> for LogicalSize { - #[inline] - fn into(self) -> (f64, f64) { - (self.width, self.height) - } -} - -impl Into<(u32, u32)> for LogicalSize { - /// Note that this rounds instead of truncating. - #[inline] - fn into(self) -> (u32, u32) { - (self.width.round() as _, self.height.round() as _) - } -} - -/// A size represented in physical pixels. -/// -/// The size is stored as floats, so please be careful. Casting floats to integers truncates the fractional part, -/// which can cause noticable issues. To help with that, an `Into<(u32, u32)>` implementation is provided which -/// does the rounding for you. -#[derive(Debug, Copy, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct PhysicalSize { - pub width: f64, - pub height: f64, -} - -impl PhysicalSize { - #[inline] - pub fn new(width: f64, height: f64) -> Self { - PhysicalSize { width, height } - } - - #[inline] - pub fn from_logical>(logical: T, dpi_factor: f64) -> Self { - logical.into().to_physical(dpi_factor) - } - - #[inline] - pub fn to_logical(&self, dpi_factor: f64) -> LogicalSize { - assert!(validate_hidpi_factor(dpi_factor)); - let width = self.width / dpi_factor; - let height = self.height / dpi_factor; - LogicalSize::new(width, height) - } -} - -impl From<(f64, f64)> for PhysicalSize { - #[inline] - fn from((width, height): (f64, f64)) -> Self { - Self::new(width, height) - } -} - -impl From<(u32, u32)> for PhysicalSize { - #[inline] - fn from((width, height): (u32, u32)) -> Self { - Self::new(width as f64, height as f64) - } -} - -impl Into<(f64, f64)> for PhysicalSize { - #[inline] - fn into(self) -> (f64, f64) { - (self.width, self.height) - } -} - -impl Into<(u32, u32)> for PhysicalSize { - /// Note that this rounds instead of truncating. - #[inline] - fn into(self) -> (u32, u32) { - (self.width.round() as _, self.height.round() as _) - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/events.rs b/third_party/cargo/vendor/winit-0.18.1/src/events.rs deleted file mode 100644 index 69a8ec7..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/events.rs +++ /dev/null @@ -1,480 +0,0 @@ -use std::path::PathBuf; - -use {DeviceId, LogicalPosition, LogicalSize, WindowId}; - -/// Describes a generic event. -#[derive(Clone, Debug, PartialEq)] -pub enum Event { - WindowEvent { - window_id: WindowId, - event: WindowEvent, - }, - DeviceEvent { - device_id: DeviceId, - event: DeviceEvent, - }, - Awakened, - - /// The application has been suspended or resumed. - /// - /// The parameter is true if app was suspended, and false if it has been resumed. - Suspended(bool), -} - -/// Describes an event from a `Window`. -#[derive(Clone, Debug, PartialEq)] -pub enum WindowEvent { - /// The size of the window has changed. Contains the client area's new dimensions. - Resized(LogicalSize), - - /// The position of the window has changed. Contains the window's new position. - Moved(LogicalPosition), - - /// The window has been requested to close. - CloseRequested, - - /// The window has been destroyed. - Destroyed, - - /// A file has been dropped into the window. - /// - /// When the user drops multiple files at once, this event will be emitted for each file - /// separately. - DroppedFile(PathBuf), - - /// A file is being hovered over the window. - /// - /// When the user hovers multiple files at once, this event will be emitted for each file - /// separately. - HoveredFile(PathBuf), - - /// A file was hovered, but has exited the window. - /// - /// There will be a single `HoveredFileCancelled` event triggered even if multiple files were - /// hovered. - HoveredFileCancelled, - - /// The window received a unicode character. - ReceivedCharacter(char), - - /// The window gained or lost focus. - /// - /// The parameter is true if the window has gained focus, and false if it has lost focus. - Focused(bool), - - /// An event from the keyboard has been received. - KeyboardInput { device_id: DeviceId, input: KeyboardInput }, - - /// The cursor has moved on the window. - CursorMoved { - device_id: DeviceId, - - /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range of this data is - /// limited by the display area and it may have been transformed by the OS to implement effects such as cursor - /// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control. - position: LogicalPosition, - modifiers: ModifiersState - }, - - /// The cursor has entered the window. - CursorEntered { device_id: DeviceId }, - - /// The cursor has left the window. - CursorLeft { device_id: DeviceId }, - - /// A mouse wheel movement or touchpad scroll occurred. - MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase, modifiers: ModifiersState }, - - /// An mouse button press has been received. - MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton, modifiers: ModifiersState }, - - - /// Touchpad pressure event. - /// - /// At the moment, only supported on Apple forcetouch-capable macbooks. - /// The parameters are: pressure level (value between 0 and 1 representing how hard the touchpad - /// is being pressed) and stage (integer representing the click level). - TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64 }, - - /// Motion on some analog axis. May report data redundant to other, more specific events. - AxisMotion { device_id: DeviceId, axis: AxisId, value: f64 }, - - /// The window needs to be redrawn. - Refresh, - - /// Touch event has been received - Touch(Touch), - - /// The DPI factor of the window has changed. - /// - /// The following user actions can cause DPI changes: - /// - /// * Changing the display's resolution. - /// * Changing the display's DPI factor (e.g. in Control Panel on Windows). - /// * Moving the window to a display with a different DPI factor. - /// - /// For more information about DPI in general, see the [`dpi`](dpi/index.html) module. - HiDpiFactorChanged(f64), -} - -/// Represents raw hardware events that are not associated with any particular window. -/// -/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person -/// game controls. Many physical actions, such as mouse movement, can produce both device and window events. Because -/// window events typically arise from virtual devices (corresponding to GUI cursors and keyboard focus) the device IDs -/// may not match. -/// -/// Note that these events are delivered regardless of input focus. -#[derive(Clone, Debug, PartialEq)] -pub enum DeviceEvent { - Added, - Removed, - - /// Change in physical position of a pointing device. - /// - /// This represents raw, unfiltered physical motion. Not to be confused with `WindowEvent::CursorMoved`. - MouseMotion { - /// (x, y) change in position in unspecified units. - /// - /// Different devices may use different units. - delta: (f64, f64), - }, - - /// Physical scroll event - MouseWheel { - delta: MouseScrollDelta, - }, - - /// Motion on some analog axis. This event will be reported for all arbitrary input devices - /// that winit supports on this platform, including mouse devices. If the device is a mouse - /// device then this will be reported alongside the MouseMotion event. - Motion { axis: AxisId, value: f64 }, - - Button { button: ButtonId, state: ElementState }, - Key(KeyboardInput), - Text { codepoint: char }, -} - -/// Describes a keyboard input event. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct KeyboardInput { - /// Identifies the physical key pressed - /// - /// This should not change if the user adjusts the host's keyboard map. Use when the physical location of the - /// key is more important than the key's host GUI semantics, such as for movement controls in a first-person - /// game. - pub scancode: ScanCode, - - pub state: ElementState, - - /// Identifies the semantic meaning of the key - /// - /// Use when the semantics of the key are more important than the physical location of the key, such as when - /// implementing appropriate behavior for "page up." - pub virtual_keycode: Option, - - /// Modifier keys active at the time of this input. - /// - /// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from - /// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere. - pub modifiers: ModifiersState -} - -/// Describes touch-screen input state. -#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum TouchPhase { - Started, - Moved, - Ended, - Cancelled -} - -/// Represents touch event -/// -/// Every time user touches screen new Start event with some finger id is generated. -/// When the finger is removed from the screen End event with same id is generated. -/// -/// For every id there will be at least 2 events with phases Start and End (or Cancelled). -/// There may be 0 or more Move events. -/// -/// -/// Depending on platform implementation id may or may not be reused by system after End event. -/// -/// Gesture regonizer using this event should assume that Start event received with same id -/// as previously received End event is a new finger and has nothing to do with an old one. -/// -/// Touch may be cancelled if for example window lost focus. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Touch { - pub device_id: DeviceId, - pub phase: TouchPhase, - pub location: LogicalPosition, - /// unique identifier of a finger. - pub id: u64 -} - -/// Hardware-dependent keyboard scan code. -pub type ScanCode = u32; - -/// Identifier for a specific analog axis on some device. -pub type AxisId = u32; - -/// Identifier for a specific button on some device. -pub type ButtonId = u32; - -/// Describes the input state of a key. -#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum ElementState { - Pressed, - Released, -} - -/// Describes a button of a mouse controller. -#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum MouseButton { - Left, - Right, - Middle, - Other(u8), -} - -/// Describes a difference in the mouse scroll wheel state. -#[derive(Debug, Clone, Copy, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum MouseScrollDelta { - /// Amount in lines or rows to scroll in the horizontal - /// and vertical directions. - /// - /// Positive values indicate movement forward - /// (away from the user) or rightwards. - LineDelta(f32, f32), - /// Amount in pixels to scroll in the horizontal and - /// vertical direction. - /// - /// Scroll events are expressed as a PixelDelta if - /// supported by the device (eg. a touchpad) and - /// platform. - PixelDelta(LogicalPosition), -} - -/// Symbolic name for a keyboard key. -#[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] -#[repr(u32)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum VirtualKeyCode { - /// The '1' key over the letters. - Key1, - /// The '2' key over the letters. - Key2, - /// The '3' key over the letters. - Key3, - /// The '4' key over the letters. - Key4, - /// The '5' key over the letters. - Key5, - /// The '6' key over the letters. - Key6, - /// The '7' key over the letters. - Key7, - /// The '8' key over the letters. - Key8, - /// The '9' key over the letters. - Key9, - /// The '0' key over the 'O' and 'P' keys. - Key0, - - A, - B, - C, - D, - E, - F, - G, - H, - I, - J, - K, - L, - M, - N, - O, - P, - Q, - R, - S, - T, - U, - V, - W, - X, - Y, - Z, - - /// The Escape key, next to F1. - Escape, - - F1, - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, - F13, - F14, - F15, - F16, - F17, - F18, - F19, - F20, - F21, - F22, - F23, - F24, - - /// Print Screen/SysRq. - Snapshot, - /// Scroll Lock. - Scroll, - /// Pause/Break key, next to Scroll lock. - Pause, - - /// `Insert`, next to Backspace. - Insert, - Home, - Delete, - End, - PageDown, - PageUp, - - Left, - Up, - Right, - Down, - - /// The Backspace key, right over Enter. - // TODO: rename - Back, - /// The Enter key. - Return, - /// The space bar. - Space, - - /// The "Compose" key on Linux. - Compose, - - Caret, - - Numlock, - Numpad0, - Numpad1, - Numpad2, - Numpad3, - Numpad4, - Numpad5, - Numpad6, - Numpad7, - Numpad8, - Numpad9, - - AbntC1, - AbntC2, - Add, - Apostrophe, - Apps, - At, - Ax, - Backslash, - Calculator, - Capital, - Colon, - Comma, - Convert, - Decimal, - Divide, - Equals, - Grave, - Kana, - Kanji, - LAlt, - LBracket, - LControl, - LShift, - LWin, - Mail, - MediaSelect, - MediaStop, - Minus, - Multiply, - Mute, - MyComputer, - NavigateForward, // also called "Prior" - NavigateBackward, // also called "Next" - NextTrack, - NoConvert, - NumpadComma, - NumpadEnter, - NumpadEquals, - OEM102, - Period, - PlayPause, - Power, - PrevTrack, - RAlt, - RBracket, - RControl, - RShift, - RWin, - Semicolon, - Slash, - Sleep, - Stop, - Subtract, - Sysrq, - Tab, - Underline, - Unlabeled, - VolumeDown, - VolumeUp, - Wake, - WebBack, - WebFavorites, - WebForward, - WebHome, - WebRefresh, - WebSearch, - WebStop, - Yen, - Copy, - Paste, - Cut, -} - -/// Represents the current state of the keyboard modifiers -/// -/// Each field of this struct represents a modifier and is `true` if this modifier is active. -#[derive(Default, Debug, Hash, PartialEq, Eq, Clone, Copy)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "serde", serde(default))] -pub struct ModifiersState { - /// The "shift" key - pub shift: bool, - /// The "control" key - pub ctrl: bool, - /// The "alt" key - pub alt: bool, - /// The "logo" key - /// - /// This is the "windows" key on PC and "command" key on Mac. - pub logo: bool -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/icon.rs b/third_party/cargo/vendor/winit-0.18.1/src/icon.rs deleted file mode 100644 index 404fc29..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/icon.rs +++ /dev/null @@ -1,170 +0,0 @@ -use std::{fmt, mem}; -use std::error::Error; -#[cfg(feature = "icon_loading")] -use std::io::{BufRead, Seek}; -#[cfg(feature = "icon_loading")] -use std::path::Path; - -#[cfg(feature = "icon_loading")] -use image; - -#[repr(C)] -#[derive(Debug)] -pub(crate) struct Pixel { - pub(crate) r: u8, - pub(crate) g: u8, - pub(crate) b: u8, - pub(crate) a: u8, -} - -pub(crate) const PIXEL_SIZE: usize = mem::size_of::(); - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -/// An error produced when using `Icon::from_rgba` with invalid arguments. -pub enum BadIcon { - /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be - /// safely interpreted as 32bpp RGBA pixels. - ByteCountNotDivisibleBy4 { - byte_count: usize, - }, - /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. - /// At least one of your arguments is incorrect. - DimensionsVsPixelCount { - width: u32, - height: u32, - width_x_height: usize, - pixel_count: usize, - }, -} - -impl fmt::Display for BadIcon { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let msg = match self { - &BadIcon::ByteCountNotDivisibleBy4 { byte_count } => format!( - "The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.", - byte_count, - ), - &BadIcon::DimensionsVsPixelCount { - width, - height, - width_x_height, - pixel_count, - } => format!( - "The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.", - width, height, pixel_count, width_x_height, - ), - }; - write!(formatter, "{}", msg) - } -} - -impl Error for BadIcon { - fn description(&self) -> &str { - "A valid icon cannot be created from these arguments" - } - - fn cause(&self) -> Option<&Error> { - Some(self) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -/// An icon used for the window titlebar, taskbar, etc. -/// -/// Enabling the `icon_loading` feature provides you with several convenience methods for creating -/// an `Icon` from any format supported by the [image](https://github.com/PistonDevelopers/image) -/// crate. -pub struct Icon { - pub(crate) rgba: Vec, - pub(crate) width: u32, - pub(crate) height: u32, -} - -impl Icon { - /// Creates an `Icon` from 32bpp RGBA data. - /// - /// The length of `rgba` must be divisible by 4, and `width * height` must equal - /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. - pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { - if rgba.len() % PIXEL_SIZE != 0 { - return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() }); - } - let pixel_count = rgba.len() / PIXEL_SIZE; - if pixel_count != (width * height) as usize { - Err(BadIcon::DimensionsVsPixelCount { - width, - height, - width_x_height: (width * height) as usize, - pixel_count, - }) - } else { - Ok(Icon { rgba, width, height }) - } - } - - #[cfg(feature = "icon_loading")] - /// Loads an `Icon` from the path of an image on the filesystem. - /// - /// Requires the `icon_loading` feature. - pub fn from_path>(path: P) -> image::ImageResult { - image::open(path).map(Into::into) - } - - #[cfg(feature = "icon_loading")] - /// Loads an `Icon` from anything implementing `BufRead` and `Seek`. - /// - /// Requires the `icon_loading` feature. - pub fn from_reader( - reader: R, - format: image::ImageFormat, - ) -> image::ImageResult { - image::load(reader, format).map(Into::into) - } - - #[cfg(feature = "icon_loading")] - /// Loads an `Icon` from the unprocessed bytes of an image file. - /// Uses heuristics to determine format. - /// - /// Requires the `icon_loading` feature. - pub fn from_bytes(bytes: &[u8]) -> image::ImageResult { - image::load_from_memory(bytes).map(Into::into) - } - - #[cfg(feature = "icon_loading")] - /// Loads an `Icon` from the unprocessed bytes of an image. - /// - /// Requires the `icon_loading` feature. - pub fn from_bytes_with_format( - bytes: &[u8], - format: image::ImageFormat, - ) -> image::ImageResult { - image::load_from_memory_with_format(bytes, format).map(Into::into) - } -} - -#[cfg(feature = "icon_loading")] -/// Requires the `icon_loading` feature. -impl From for Icon { - fn from(image: image::DynamicImage) -> Self { - use image::{GenericImageView, Pixel}; - let (width, height) = image.dimensions(); - let mut rgba = Vec::with_capacity((width * height) as usize * PIXEL_SIZE); - for (_, _, pixel) in image.pixels() { - rgba.extend_from_slice(&pixel.to_rgba().data); - } - Icon { rgba, width, height } - } -} - -#[cfg(feature = "icon_loading")] -/// Requires the `icon_loading` feature. -impl From for Icon { - fn from(buf: image::RgbaImage) -> Self { - let (width, height) = buf.dimensions(); - let mut rgba = Vec::with_capacity((width * height) as usize * PIXEL_SIZE); - for (_, _, pixel) in buf.enumerate_pixels() { - rgba.extend_from_slice(&pixel.data); - } - Icon { rgba, width, height } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/lib.rs b/third_party/cargo/vendor/winit-0.18.1/src/lib.rs deleted file mode 100644 index ece7d35..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/lib.rs +++ /dev/null @@ -1,539 +0,0 @@ -//! Winit allows you to build a window on as many platforms as possible. -//! -//! # Building a window -//! -//! Before you can build a window, you first need to build an `EventsLoop`. This is done with the -//! `EventsLoop::new()` function. Example: -//! -//! ```no_run -//! use winit::EventsLoop; -//! let events_loop = EventsLoop::new(); -//! ``` -//! -//! Once this is done there are two ways to create a window: -//! -//! - Calling `Window::new(&events_loop)`. -//! - Calling `let builder = WindowBuilder::new()` then `builder.build(&events_loop)`. -//! -//! The first way is the simplest way and will give you default values for everything. -//! -//! The second way allows you to customize the way your window will look and behave by modifying -//! the fields of the `WindowBuilder` object before you create the window. -//! -//! # Events handling -//! -//! Once a window has been created, it will *generate events*. For example whenever the user moves -//! the window, resizes the window, moves the mouse, etc. an event is generated. -//! -//! The events generated by a window can be retrieved from the `EventsLoop` the window was created -//! with. -//! -//! There are two ways to do so. The first is to call `events_loop.poll_events(...)`, which will -//! retrieve all the events pending on the windows and immediately return after no new event is -//! available. You usually want to use this method in application that render continuously on the -//! screen, such as video games. -//! -//! ```no_run -//! use winit::{Event, WindowEvent}; -//! use winit::dpi::LogicalSize; -//! # use winit::EventsLoop; -//! # let mut events_loop = EventsLoop::new(); -//! -//! loop { -//! events_loop.poll_events(|event| { -//! match event { -//! Event::WindowEvent { -//! event: WindowEvent::Resized(LogicalSize { width, height }), -//! .. -//! } => { -//! println!("The window was resized to {}x{}", width, height); -//! }, -//! _ => () -//! } -//! }); -//! } -//! ``` -//! -//! The second way is to call `events_loop.run_forever(...)`. As its name tells, it will run -//! forever unless it is stopped by returning `ControlFlow::Break`. -//! -//! ```no_run -//! use winit::{ControlFlow, Event, WindowEvent}; -//! # use winit::EventsLoop; -//! # let mut events_loop = EventsLoop::new(); -//! -//! events_loop.run_forever(|event| { -//! match event { -//! Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { -//! println!("The close button was pressed; stopping"); -//! ControlFlow::Break -//! }, -//! _ => ControlFlow::Continue, -//! } -//! }); -//! ``` -//! -//! If you use multiple windows, the `WindowEvent` event has a member named `window_id`. You can -//! compare it with the value returned by the `id()` method of `Window` in order to know which -//! window has received the event. -//! -//! # Drawing on the window -//! -//! Winit doesn't provide any function that allows drawing on a window. However it allows you to -//! retrieve the raw handle of the window (see the `os` module for that), which in turn allows you -//! to create an OpenGL/Vulkan/DirectX/Metal/etc. context that will draw on the window. -//! - -#[allow(unused_imports)] -#[macro_use] -extern crate lazy_static; -extern crate libc; -#[macro_use] -extern crate log; -#[cfg(feature = "icon_loading")] -extern crate image; -#[cfg(feature = "serde")] -#[macro_use] -extern crate serde; - -#[cfg(target_os = "windows")] -extern crate winapi; -#[cfg(target_os = "windows")] -extern crate backtrace; -#[cfg(any(target_os = "macos", target_os = "ios"))] -#[macro_use] -extern crate objc; -#[cfg(target_os = "macos")] -extern crate cocoa; -#[cfg(target_os = "macos")] -extern crate core_foundation; -#[cfg(target_os = "macos")] -extern crate core_graphics; -#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -extern crate x11_dl; -#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -extern crate parking_lot; -#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -extern crate percent_encoding; -#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -extern crate smithay_client_toolkit as sctk; - -pub(crate) use dpi::*; // TODO: Actually change the imports throughout the codebase. -pub use events::*; -pub use window::{AvailableMonitorsIter, MonitorId}; -pub use icon::*; - -pub mod dpi; -mod events; -mod icon; -mod platform; -mod window; - -pub mod os; - -/// Represents a window. -/// -/// # Example -/// -/// ```no_run -/// use winit::{Event, EventsLoop, Window, WindowEvent, ControlFlow}; -/// -/// let mut events_loop = EventsLoop::new(); -/// let window = Window::new(&events_loop).unwrap(); -/// -/// events_loop.run_forever(|event| { -/// match event { -/// Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { -/// ControlFlow::Break -/// }, -/// _ => ControlFlow::Continue, -/// } -/// }); -/// ``` -pub struct Window { - window: platform::Window, -} - -impl std::fmt::Debug for Window { - fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> std::fmt::Result { - fmtr.pad("Window { .. }") - } -} - -/// Identifier of a window. Unique for each window. -/// -/// Can be obtained with `window.id()`. -/// -/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you -/// can then compare to the ids of your windows. -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WindowId(platform::WindowId); - -impl WindowId { - /// Returns a dummy `WindowId`, useful for unit testing. The only guarantee made about the return - /// value of this function is that it will always be equal to itself and to future values returned - /// by this function. No other guarantees are made. This may be equal to a real `WindowId`. - /// - /// **Passing this into a winit function will result in undefined behavior.** - pub unsafe fn dummy() -> Self { - WindowId(platform::WindowId::dummy()) - } -} - -/// Identifier of an input device. -/// -/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which -/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or -/// physical. Virtual devices typically aggregate inputs from multiple physical devices. -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DeviceId(platform::DeviceId); - -impl DeviceId { - /// Returns a dummy `DeviceId`, useful for unit testing. The only guarantee made about the return - /// value of this function is that it will always be equal to itself and to future values returned - /// by this function. No other guarantees are made. This may be equal to a real `DeviceId`. - /// - /// **Passing this into a winit function will result in undefined behavior.** - pub unsafe fn dummy() -> Self { - DeviceId(platform::DeviceId::dummy()) - } -} - -/// Provides a way to retrieve events from the system and from the windows that were registered to -/// the events loop. -/// -/// An `EventsLoop` can be seen more or less as a "context". Calling `EventsLoop::new()` -/// initializes everything that will be required to create windows. For example on Linux creating -/// an events loop opens a connection to the X or Wayland server. -/// -/// To wake up an `EventsLoop` from a another thread, see the `EventsLoopProxy` docs. -/// -/// Note that the `EventsLoop` cannot be shared accross threads (due to platform-dependant logic -/// forbiding it), as such it is neither `Send` nor `Sync`. If you need cross-thread access, the -/// `Window` created from this `EventsLoop` _can_ be sent to an other thread, and the -/// `EventsLoopProxy` allows you to wakeup an `EventsLoop` from an other thread. -pub struct EventsLoop { - events_loop: platform::EventsLoop, - _marker: ::std::marker::PhantomData<*mut ()> // Not Send nor Sync -} - -impl std::fmt::Debug for EventsLoop { - fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> std::fmt::Result { - fmtr.pad("EventsLoop { .. }") - } -} - -/// Returned by the user callback given to the `EventsLoop::run_forever` method. -/// -/// Indicates whether the `run_forever` method should continue or complete. -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum ControlFlow { - /// Continue looping and waiting for events. - Continue, - /// Break from the event loop. - Break, -} - -impl EventsLoop { - /// Builds a new events loop. - /// - /// Usage will result in display backend initialisation, this can be controlled on linux - /// using an environment variable `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`. - /// If it is not set, winit will try to connect to a wayland connection, and if it fails will - /// fallback on x11. If this variable is set with any other value, winit will panic. - pub fn new() -> EventsLoop { - EventsLoop { - events_loop: platform::EventsLoop::new(), - _marker: ::std::marker::PhantomData, - } - } - - /// Returns the list of all the monitors available on the system. - /// - // Note: should be replaced with `-> impl Iterator` once stable. - #[inline] - pub fn get_available_monitors(&self) -> AvailableMonitorsIter { - let data = self.events_loop.get_available_monitors(); - AvailableMonitorsIter{ data: data.into_iter() } - } - - /// Returns the primary monitor of the system. - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId { inner: self.events_loop.get_primary_monitor() } - } - - /// Fetches all the events that are pending, calls the callback function for each of them, - /// and returns. - #[inline] - pub fn poll_events(&mut self, callback: F) - where F: FnMut(Event) - { - self.events_loop.poll_events(callback) - } - - /// Calls `callback` every time an event is received. If no event is available, sleeps the - /// current thread and waits for an event. If the callback returns `ControlFlow::Break` then - /// `run_forever` will immediately return. - /// - /// # Danger! - /// - /// The callback is run after *every* event, so if its execution time is non-trivial the event queue may not empty - /// at a sufficient rate. Rendering in the callback with vsync enabled **will** cause significant lag. - #[inline] - pub fn run_forever(&mut self, callback: F) - where F: FnMut(Event) -> ControlFlow - { - self.events_loop.run_forever(callback) - } - - /// Creates an `EventsLoopProxy` that can be used to wake up the `EventsLoop` from another - /// thread. - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy { - events_loop_proxy: self.events_loop.create_proxy(), - } - } -} - -/// Used to wake up the `EventsLoop` from another thread. -#[derive(Clone)] -pub struct EventsLoopProxy { - events_loop_proxy: platform::EventsLoopProxy, -} - -impl std::fmt::Debug for EventsLoopProxy { - fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> std::fmt::Result { - fmtr.pad("EventsLoopProxy { .. }") - } -} - -impl EventsLoopProxy { - /// Wake up the `EventsLoop` from which this proxy was created. - /// - /// This causes the `EventsLoop` to emit an `Awakened` event. - /// - /// Returns an `Err` if the associated `EventsLoop` no longer exists. - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - self.events_loop_proxy.wakeup() - } -} - -/// The error that is returned when an `EventsLoopProxy` attempts to wake up an `EventsLoop` that -/// no longer exists. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub struct EventsLoopClosed; - -impl std::fmt::Display for EventsLoopClosed { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", std::error::Error::description(self)) - } -} - -impl std::error::Error for EventsLoopClosed { - fn description(&self) -> &str { - "Tried to wake up a closed `EventsLoop`" - } -} - -/// Object that allows you to build windows. -#[derive(Clone)] -pub struct WindowBuilder { - /// The attributes to use to create the window. - pub window: WindowAttributes, - - // Platform-specific configuration. Private. - platform_specific: platform::PlatformSpecificWindowBuilderAttributes, -} - -impl std::fmt::Debug for WindowBuilder { - fn fmt(&self, fmtr: &mut std::fmt::Formatter) -> std::fmt::Result { - fmtr.debug_struct("WindowBuilder") - .field("window", &self.window) - .finish() - } -} - -/// Error that can happen while creating a window or a headless renderer. -#[derive(Debug, Clone)] -pub enum CreationError { - OsError(String), - /// TODO: remove this error - NotSupported, -} - -impl CreationError { - fn to_string(&self) -> &str { - match *self { - CreationError::OsError(ref text) => &text, - CreationError::NotSupported => "Some of the requested attributes are not supported", - } - } -} - -impl std::fmt::Display for CreationError { - fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { - formatter.write_str(self.to_string()) - } -} - -impl std::error::Error for CreationError { - fn description(&self) -> &str { - self.to_string() - } -} - -/// Describes the appearance of the mouse cursor. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub enum MouseCursor { - /// The platform-dependent default cursor. - Default, - /// A simple crosshair. - Crosshair, - /// A hand (often used to indicate links in web browsers). - Hand, - /// Self explanatory. - Arrow, - /// Indicates something is to be moved. - Move, - /// Indicates text that may be selected or edited. - Text, - /// Program busy indicator. - Wait, - /// Help indicator (often rendered as a "?") - Help, - /// Progress indicator. Shows that processing is being done. But in contrast - /// with "Wait" the user may still interact with the program. Often rendered - /// as a spinning beach ball, or an arrow with a watch or hourglass. - Progress, - - /// Cursor showing that something cannot be done. - NotAllowed, - ContextMenu, - Cell, - VerticalText, - Alias, - Copy, - NoDrop, - Grab, - Grabbing, - AllScroll, - ZoomIn, - ZoomOut, - - /// Indicate that some edge is to be moved. For example, the 'SeResize' cursor - /// is used when the movement starts from the south-east corner of the box. - EResize, - NResize, - NeResize, - NwResize, - SResize, - SeResize, - SwResize, - WResize, - EwResize, - NsResize, - NeswResize, - NwseResize, - ColResize, - RowResize, -} - -impl Default for MouseCursor { - fn default() -> Self { - MouseCursor::Default - } -} - -/// Attributes to use when creating a window. -#[derive(Debug, Clone)] -pub struct WindowAttributes { - /// The dimensions of the window. If this is `None`, some platform-specific dimensions will be - /// used. - /// - /// The default is `None`. - pub dimensions: Option, - - /// The minimum dimensions a window can be, If this is `None`, the window will have no minimum dimensions (aside from reserved). - /// - /// The default is `None`. - pub min_dimensions: Option, - - /// The maximum dimensions a window can be, If this is `None`, the maximum will have no maximum or will be set to the primary monitor's dimensions by the platform. - /// - /// The default is `None`. - pub max_dimensions: Option, - - /// Whether the window is resizable or not. - /// - /// The default is `true`. - pub resizable: bool, - - /// Whether the window should be set as fullscreen upon creation. - /// - /// The default is `None`. - pub fullscreen: Option, - - /// The title of the window in the title bar. - /// - /// The default is `"winit window"`. - pub title: String, - - /// Whether the window should be maximized upon creation. - /// - /// The default is `false`. - pub maximized: bool, - - /// Whether the window should be immediately visible upon creation. - /// - /// The default is `true`. - pub visible: bool, - - /// Whether the the window should be transparent. If this is true, writing colors - /// with alpha values different than `1.0` will produce a transparent window. - /// - /// The default is `false`. - pub transparent: bool, - - /// Whether the window should have borders and bars. - /// - /// The default is `true`. - pub decorations: bool, - - /// Whether the window should always be on top of other windows. - /// - /// The default is `false`. - pub always_on_top: bool, - - /// The window icon. - /// - /// The default is `None`. - pub window_icon: Option, - - /// [iOS only] Enable multitouch, - /// see [multipleTouchEnabled](https://developer.apple.com/documentation/uikit/uiview/1622519-multipletouchenabled) - pub multitouch: bool, -} - -impl Default for WindowAttributes { - #[inline] - fn default() -> WindowAttributes { - WindowAttributes { - dimensions: None, - min_dimensions: None, - max_dimensions: None, - resizable: true, - title: "winit window".to_owned(), - maximized: false, - fullscreen: None, - visible: true, - transparent: false, - decorations: true, - always_on_top: false, - window_icon: None, - multitouch: false, - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/android.rs b/third_party/cargo/vendor/winit-0.18.1/src/os/android.rs deleted file mode 100644 index 06661a3..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/android.rs +++ /dev/null @@ -1,38 +0,0 @@ -#![cfg(any(target_os = "android"))] - -use std::os::raw::c_void; -use EventsLoop; -use Window; -use WindowBuilder; - -/// Additional methods on `EventsLoop` that are specific to Android. -pub trait EventsLoopExt { - /// Makes it possible for glutin to register a callback when a suspend event happens on Android - fn set_suspend_callback(&self, cb: Option ()>>); -} - -impl EventsLoopExt for EventsLoop { - fn set_suspend_callback(&self, cb: Option ()>>) { - self.events_loop.set_suspend_callback(cb); - } -} - -/// Additional methods on `Window` that are specific to Android. -pub trait WindowExt { - fn get_native_window(&self) -> *const c_void; -} - -impl WindowExt for Window { - #[inline] - fn get_native_window(&self) -> *const c_void { - self.window.get_native_window() - } -} - -/// Additional methods on `WindowBuilder` that are specific to Android. -pub trait WindowBuilderExt { - -} - -impl WindowBuilderExt for WindowBuilder { -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/ios.rs b/third_party/cargo/vendor/winit-0.18.1/src/os/ios.rs deleted file mode 100644 index 62c2c24..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/ios.rs +++ /dev/null @@ -1,59 +0,0 @@ -#![cfg(target_os = "ios")] - -use std::os::raw::c_void; - -use {MonitorId, Window, WindowBuilder}; - -/// Additional methods on `Window` that are specific to iOS. -pub trait WindowExt { - /// Returns a pointer to the `UIWindow` that is used by this window. - /// - /// The pointer will become invalid when the `Window` is destroyed. - fn get_uiwindow(&self) -> *mut c_void; - - /// Returns a pointer to the `UIView` that is used by this window. - /// - /// The pointer will become invalid when the `Window` is destroyed. - fn get_uiview(&self) -> *mut c_void; -} - -impl WindowExt for Window { - #[inline] - fn get_uiwindow(&self) -> *mut c_void { - self.window.get_uiwindow() as _ - } - - #[inline] - fn get_uiview(&self) -> *mut c_void { - self.window.get_uiview() as _ - } -} - -/// Additional methods on `WindowBuilder` that are specific to iOS. -pub trait WindowBuilderExt { - /// Sets the root view class used by the `Window`, otherwise a barebones `UIView` is provided. - /// - /// The class will be initialized by calling `[root_view initWithFrame:CGRect]` - fn with_root_view_class(self, root_view_class: *const c_void) -> WindowBuilder; -} - -impl WindowBuilderExt for WindowBuilder { - #[inline] - fn with_root_view_class(mut self, root_view_class: *const c_void) -> WindowBuilder { - self.platform_specific.root_view_class = unsafe { &*(root_view_class as *const _) }; - self - } -} - -/// Additional methods on `MonitorId` that are specific to iOS. -pub trait MonitorIdExt { - /// Returns a pointer to the `UIScreen` that is used by this monitor. - fn get_uiscreen(&self) -> *mut c_void; -} - -impl MonitorIdExt for MonitorId { - #[inline] - fn get_uiscreen(&self) -> *mut c_void { - self.inner.get_uiscreen() as _ - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/unix.rs b/third_party/cargo/vendor/winit-0.18.1/src/os/unix.rs deleted file mode 100644 index 3d1525b..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/unix.rs +++ /dev/null @@ -1,306 +0,0 @@ -#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] - -use std::os::raw; -use std::ptr; -use std::sync::Arc; - -use { - EventsLoop, - LogicalSize, - MonitorId, - Window, - WindowBuilder, -}; -use platform::{ - EventsLoop as LinuxEventsLoop, - Window as LinuxWindow, -}; -use platform::x11::XConnection; -use platform::x11::ffi::XVisualInfo; - -// TODO: stupid hack so that glutin can do its work -#[doc(hidden)] -pub use platform::x11; - -pub use platform::XNotSupported; -pub use platform::x11::util::WindowType as XWindowType; - -/// Additional methods on `EventsLoop` that are specific to Linux. -pub trait EventsLoopExt { - /// Builds a new `EventsLoop` that is forced to use X11. - fn new_x11() -> Result - where Self: Sized; - - /// Builds a new `EventsLoop` that is forced to use Wayland. - fn new_wayland() -> Self - where Self: Sized; - - /// True if the `EventsLoop` uses Wayland. - fn is_wayland(&self) -> bool; - - /// True if the `EventsLoop` uses X11. - fn is_x11(&self) -> bool; - - #[doc(hidden)] - fn get_xlib_xconnection(&self) -> Option>; -} - -impl EventsLoopExt for EventsLoop { - #[inline] - fn new_x11() -> Result { - LinuxEventsLoop::new_x11().map(|ev| - EventsLoop { - events_loop: ev, - _marker: ::std::marker::PhantomData, - } - ) - } - - #[inline] - fn new_wayland() -> Self { - EventsLoop { - events_loop: match LinuxEventsLoop::new_wayland() { - Ok(e) => e, - Err(_) => panic!() // TODO: propagate - }, - _marker: ::std::marker::PhantomData, - } - } - - #[inline] - fn is_wayland(&self) -> bool { - self.events_loop.is_wayland() - } - - #[inline] - fn is_x11(&self) -> bool { - !self.events_loop.is_wayland() - } - - #[inline] - #[doc(hidden)] - fn get_xlib_xconnection(&self) -> Option> { - self.events_loop.x_connection().cloned() - } -} - -/// Additional methods on `Window` that are specific to Unix. -pub trait WindowExt { - /// Returns the ID of the `Window` xlib object that is used by this window. - /// - /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). - fn get_xlib_window(&self) -> Option; - - /// Returns a pointer to the `Display` object of xlib that is used by this window. - /// - /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). - /// - /// The pointer will become invalid when the glutin `Window` is destroyed. - fn get_xlib_display(&self) -> Option<*mut raw::c_void>; - - fn get_xlib_screen_id(&self) -> Option; - - #[doc(hidden)] - fn get_xlib_xconnection(&self) -> Option>; - - /// Set window urgency hint (`XUrgencyHint`). Only relevant on X. - fn set_urgent(&self, is_urgent: bool); - - /// This function returns the underlying `xcb_connection_t` of an xlib `Display`. - /// - /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). - /// - /// The pointer will become invalid when the glutin `Window` is destroyed. - fn get_xcb_connection(&self) -> Option<*mut raw::c_void>; - - /// Returns a pointer to the `wl_surface` object of wayland that is used by this window. - /// - /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). - /// - /// The pointer will become invalid when the glutin `Window` is destroyed. - fn get_wayland_surface(&self) -> Option<*mut raw::c_void>; - - /// Returns a pointer to the `wl_display` object of wayland that is used by this window. - /// - /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). - /// - /// The pointer will become invalid when the glutin `Window` is destroyed. - fn get_wayland_display(&self) -> Option<*mut raw::c_void>; - - /// Check if the window is ready for drawing - /// - /// It is a remnant of a previous implementation detail for the - /// wayland backend, and is no longer relevant. - /// - /// Always return true. - #[deprecated] - fn is_ready(&self) -> bool; -} - -impl WindowExt for Window { - #[inline] - fn get_xlib_window(&self) -> Option { - match self.window { - LinuxWindow::X(ref w) => Some(w.get_xlib_window()), - _ => None - } - } - - #[inline] - fn get_xlib_display(&self) -> Option<*mut raw::c_void> { - match self.window { - LinuxWindow::X(ref w) => Some(w.get_xlib_display()), - _ => None - } - } - - #[inline] - fn get_xlib_screen_id(&self) -> Option { - match self.window { - LinuxWindow::X(ref w) => Some(w.get_xlib_screen_id()), - _ => None - } - } - - #[inline] - #[doc(hidden)] - fn get_xlib_xconnection(&self) -> Option> { - match self.window { - LinuxWindow::X(ref w) => Some(w.get_xlib_xconnection()), - _ => None - } - } - - #[inline] - fn get_xcb_connection(&self) -> Option<*mut raw::c_void> { - match self.window { - LinuxWindow::X(ref w) => Some(w.get_xcb_connection()), - _ => None - } - } - - #[inline] - fn set_urgent(&self, is_urgent: bool) { - if let LinuxWindow::X(ref w) = self.window { - w.set_urgent(is_urgent); - } - } - - #[inline] - fn get_wayland_surface(&self) -> Option<*mut raw::c_void> { - match self.window { - LinuxWindow::Wayland(ref w) => Some(w.get_surface().c_ptr() as *mut _), - _ => None - } - } - - #[inline] - fn get_wayland_display(&self) -> Option<*mut raw::c_void> { - match self.window { - LinuxWindow::Wayland(ref w) => Some(w.get_display().c_ptr() as *mut _), - _ => None - } - } - - #[inline] - fn is_ready(&self) -> bool { - true - } -} - -/// Additional methods on `WindowBuilder` that are specific to Unix. -pub trait WindowBuilderExt { - fn with_x11_visual(self, visual_infos: *const T) -> WindowBuilder; - fn with_x11_screen(self, screen_id: i32) -> WindowBuilder; - - /// Build window with `WM_CLASS` hint; defaults to the name of the binary. Only relevant on X11. - fn with_class(self, class: String, instance: String) -> WindowBuilder; - /// Build window with override-redirect flag; defaults to false. Only relevant on X11. - fn with_override_redirect(self, override_redirect: bool) -> WindowBuilder; - /// Build window with `_NET_WM_WINDOW_TYPE` hint; defaults to `Normal`. Only relevant on X11. - fn with_x11_window_type(self, x11_window_type: XWindowType) -> WindowBuilder; - /// Build window with `_GTK_THEME_VARIANT` hint set to the specified value. Currently only relevant on X11. - fn with_gtk_theme_variant(self, variant: String) -> WindowBuilder; - /// Build window with resize increment hint. Only implemented on X11. - fn with_resize_increments(self, increments: LogicalSize) -> WindowBuilder; - /// Build window with base size hint. Only implemented on X11. - fn with_base_size(self, base_size: LogicalSize) -> WindowBuilder; - - /// Build window with a given application ID. It should match the `.desktop` file distributed with - /// your program. Only relevant on Wayland. - /// - /// For details about application ID conventions, see the - /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) - fn with_app_id(self, app_id: String) -> WindowBuilder; -} - -impl WindowBuilderExt for WindowBuilder { - #[inline] - fn with_x11_visual(mut self, visual_infos: *const T) -> WindowBuilder { - self.platform_specific.visual_infos = Some( - unsafe { ptr::read(visual_infos as *const XVisualInfo) } - ); - self - } - - #[inline] - fn with_x11_screen(mut self, screen_id: i32) -> WindowBuilder { - self.platform_specific.screen_id = Some(screen_id); - self - } - - #[inline] - fn with_class(mut self, instance: String, class: String) -> WindowBuilder { - self.platform_specific.class = Some((instance, class)); - self - } - - #[inline] - fn with_override_redirect(mut self, override_redirect: bool) -> WindowBuilder { - self.platform_specific.override_redirect = override_redirect; - self - } - - #[inline] - fn with_x11_window_type(mut self, x11_window_type: XWindowType) -> WindowBuilder { - self.platform_specific.x11_window_type = x11_window_type; - self - } - - #[inline] - fn with_resize_increments(mut self, increments: LogicalSize) -> WindowBuilder { - self.platform_specific.resize_increments = Some(increments.into()); - self - } - - #[inline] - fn with_base_size(mut self, base_size: LogicalSize) -> WindowBuilder { - self.platform_specific.base_size = Some(base_size.into()); - self - } - - #[inline] - fn with_gtk_theme_variant(mut self, variant: String) -> WindowBuilder { - self.platform_specific.gtk_theme_variant = Some(variant); - self - } - - #[inline] - fn with_app_id(mut self, app_id: String) -> WindowBuilder { - self.platform_specific.app_id = Some(app_id); - self - } -} - -/// Additional methods on `MonitorId` that are specific to Linux. -pub trait MonitorIdExt { - /// Returns the inner identifier of the monitor. - fn native_id(&self) -> u32; -} - -impl MonitorIdExt for MonitorId { - #[inline] - fn native_id(&self) -> u32 { - self.inner.get_native_identifier() - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/windows.rs b/third_party/cargo/vendor/winit-0.18.1/src/os/windows.rs deleted file mode 100644 index 62b16c7..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/windows.rs +++ /dev/null @@ -1,117 +0,0 @@ -#![cfg(target_os = "windows")] - -use std::os::raw::c_void; - -use libc; -use winapi::shared::windef::HWND; - -use {DeviceId, EventsLoop, Icon, MonitorId, Window, WindowBuilder}; -use platform::EventsLoop as WindowsEventsLoop; - -/// Additional methods on `EventsLoop` that are specific to Windows. -pub trait EventsLoopExt { - /// By default, winit on Windows will attempt to enable process-wide DPI awareness. If that's - /// undesirable, you can create an `EventsLoop` using this function instead. - fn new_dpi_unaware() -> Self where Self: Sized; -} - -impl EventsLoopExt for EventsLoop { - #[inline] - fn new_dpi_unaware() -> Self { - EventsLoop { - events_loop: WindowsEventsLoop::with_dpi_awareness(false), - _marker: ::std::marker::PhantomData, - } - } -} - -/// Additional methods on `Window` that are specific to Windows. -pub trait WindowExt { - /// Returns the native handle that is used by this window. - /// - /// The pointer will become invalid when the native window was destroyed. - fn get_hwnd(&self) -> *mut libc::c_void; - - /// This sets `ICON_BIG`. A good ceiling here is 256x256. - fn set_taskbar_icon(&self, taskbar_icon: Option); -} - -impl WindowExt for Window { - #[inline] - fn get_hwnd(&self) -> *mut libc::c_void { - self.window.hwnd() as *mut _ - } - - #[inline] - fn set_taskbar_icon(&self, taskbar_icon: Option) { - self.window.set_taskbar_icon(taskbar_icon) - } -} - -/// Additional methods on `WindowBuilder` that are specific to Windows. -pub trait WindowBuilderExt { - /// Sets a parent to the window to be created. - fn with_parent_window(self, parent: HWND) -> WindowBuilder; - - /// This sets `ICON_BIG`. A good ceiling here is 256x256. - fn with_taskbar_icon(self, taskbar_icon: Option) -> WindowBuilder; - - /// This sets `WS_EX_NOREDIRECTIONBITMAP`. - fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder; -} - -impl WindowBuilderExt for WindowBuilder { - #[inline] - fn with_parent_window(mut self, parent: HWND) -> WindowBuilder { - self.platform_specific.parent = Some(parent); - self - } - - #[inline] - fn with_taskbar_icon(mut self, taskbar_icon: Option) -> WindowBuilder { - self.platform_specific.taskbar_icon = taskbar_icon; - self - } - - #[inline] - fn with_no_redirection_bitmap(mut self, flag: bool) -> WindowBuilder { - self.platform_specific.no_redirection_bitmap = flag; - self - } -} - -/// Additional methods on `MonitorId` that are specific to Windows. -pub trait MonitorIdExt { - /// Returns the name of the monitor adapter specific to the Win32 API. - fn native_id(&self) -> String; - - /// Returns the handle of the monitor - `HMONITOR`. - fn hmonitor(&self) -> *mut c_void; -} - -impl MonitorIdExt for MonitorId { - #[inline] - fn native_id(&self) -> String { - self.inner.get_native_identifier() - } - - #[inline] - fn hmonitor(&self) -> *mut c_void { - self.inner.get_hmonitor() as *mut _ - } -} - -/// Additional methods on `DeviceId` that are specific to Windows. -pub trait DeviceIdExt { - /// Returns an identifier that persistently refers to this specific device. - /// - /// Will return `None` if the device is no longer available. - fn get_persistent_identifier(&self) -> Option; -} - -impl DeviceIdExt for DeviceId { - #[inline] - fn get_persistent_identifier(&self) -> Option { - self.0.get_persistent_identifier() - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/android/ffi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/android/ffi.rs deleted file mode 100644 index af8c50b..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/android/ffi.rs +++ /dev/null @@ -1,108 +0,0 @@ -#![allow(dead_code)] -#![allow(non_snake_case)] -#![allow(non_camel_case_types)] -#![allow(non_upper_case_globals)] - -use libc; -use std::os::raw; - -#[link(name = "android")] -#[link(name = "EGL")] -#[link(name = "GLESv2")] -extern {} - -/** - * asset_manager.h - */ -pub type AAssetManager = raw::c_void; - -/** - * native_window.h - */ -pub type ANativeWindow = raw::c_void; - -extern { - pub fn ANativeWindow_getHeight(window: *const ANativeWindow) -> libc::int32_t; - pub fn ANativeWindow_getWidth(window: *const ANativeWindow) -> libc::int32_t; -} - -/** - * native_activity.h - */ -pub type JavaVM = (); -pub type JNIEnv = (); -pub type jobject = *const libc::c_void; - -pub type AInputQueue = (); // FIXME: wrong -pub type ARect = (); // FIXME: wrong - -#[repr(C)] -pub struct ANativeActivity { - pub callbacks: *mut ANativeActivityCallbacks, - pub vm: *mut JavaVM, - pub env: *mut JNIEnv, - pub clazz: jobject, - pub internalDataPath: *const libc::c_char, - pub externalDataPath: *const libc::c_char, - pub sdkVersion: libc::int32_t, - pub instance: *mut libc::c_void, - pub assetManager: *mut AAssetManager, - pub obbPath: *const libc::c_char, -} - -#[repr(C)] -pub struct ANativeActivityCallbacks { - pub onStart: extern fn(*mut ANativeActivity), - pub onResume: extern fn(*mut ANativeActivity), - pub onSaveInstanceState: extern fn(*mut ANativeActivity, *mut libc::size_t), - pub onPause: extern fn(*mut ANativeActivity), - pub onStop: extern fn(*mut ANativeActivity), - pub onDestroy: extern fn(*mut ANativeActivity), - pub onWindowFocusChanged: extern fn(*mut ANativeActivity, libc::c_int), - pub onNativeWindowCreated: extern fn(*mut ANativeActivity, *const ANativeWindow), - pub onNativeWindowResized: extern fn(*mut ANativeActivity, *const ANativeWindow), - pub onNativeWindowRedrawNeeded: extern fn(*mut ANativeActivity, *const ANativeWindow), - pub onNativeWindowDestroyed: extern fn(*mut ANativeActivity, *const ANativeWindow), - pub onInputQueueCreated: extern fn(*mut ANativeActivity, *mut AInputQueue), - pub onInputQueueDestroyed: extern fn(*mut ANativeActivity, *mut AInputQueue), - pub onContentRectChanged: extern fn(*mut ANativeActivity, *const ARect), - pub onConfigurationChanged: extern fn(*mut ANativeActivity), - pub onLowMemory: extern fn(*mut ANativeActivity), -} - -/** - * looper.h - */ -pub type ALooper = (); - -#[link(name = "android")] -extern { - pub fn ALooper_forThread() -> *const ALooper; - pub fn ALooper_acquire(looper: *const ALooper); - pub fn ALooper_release(looper: *const ALooper); - pub fn ALooper_prepare(opts: libc::c_int) -> *const ALooper; - pub fn ALooper_pollOnce(timeoutMillis: libc::c_int, outFd: *mut libc::c_int, - outEvents: *mut libc::c_int, outData: *mut *mut libc::c_void) -> libc::c_int; - pub fn ALooper_pollAll(timeoutMillis: libc::c_int, outFd: *mut libc::c_int, - outEvents: *mut libc::c_int, outData: *mut *mut libc::c_void) -> libc::c_int; - pub fn ALooper_wake(looper: *const ALooper); - pub fn ALooper_addFd(looper: *const ALooper, fd: libc::c_int, ident: libc::c_int, - events: libc::c_int, callback: ALooper_callbackFunc, data: *mut libc::c_void) - -> libc::c_int; - pub fn ALooper_removeFd(looper: *const ALooper, fd: libc::c_int) -> libc::c_int; -} - -pub const ALOOPER_PREPARE_ALLOW_NON_CALLBACKS: libc::c_int = 1 << 0; - -pub const ALOOPER_POLL_WAKE: libc::c_int = -1; -pub const ALOOPER_POLL_CALLBACK: libc::c_int = -2; -pub const ALOOPER_POLL_TIMEOUT: libc::c_int = -3; -pub const ALOOPER_POLL_ERROR: libc::c_int = -4; - -pub const ALOOPER_EVENT_INPUT: libc::c_int = 1 << 0; -pub const ALOOPER_EVENT_OUTPUT: libc::c_int = 1 << 1; -pub const ALOOPER_EVENT_ERROR: libc::c_int = 1 << 2; -pub const ALOOPER_EVENT_HANGUP: libc::c_int = 1 << 3; -pub const ALOOPER_EVENT_INVALID: libc::c_int = 1 << 4; - -pub type ALooper_callbackFunc = extern fn(libc::c_int, libc::c_int, *mut libc::c_void) -> libc::c_int; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/ffi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/ffi.rs deleted file mode 100644 index 8da2663..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/ffi.rs +++ /dev/null @@ -1,314 +0,0 @@ -#![allow(dead_code, non_camel_case_types, non_snake_case)] - -use std::os::raw::{c_int, c_char, c_void, c_ulong, c_double, c_long, c_ushort}; -#[cfg(test)] -use std::mem; - -pub type EM_BOOL = c_int; -pub type EM_UTF8 = c_char; -pub type EMSCRIPTEN_RESULT = c_int; - -pub const EM_TRUE: EM_BOOL = 1; -pub const EM_FALSE: EM_BOOL = 0; - -// values for EMSCRIPTEN_RESULT -pub const EMSCRIPTEN_RESULT_SUCCESS: c_int = 0; -pub const EMSCRIPTEN_RESULT_DEFERRED: c_int = 1; -pub const EMSCRIPTEN_RESULT_NOT_SUPPORTED: c_int = -1; -pub const EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED: c_int = -2; -pub const EMSCRIPTEN_RESULT_INVALID_TARGET: c_int = -3; -pub const EMSCRIPTEN_RESULT_UNKNOWN_TARGET: c_int = -4; -pub const EMSCRIPTEN_RESULT_INVALID_PARAM: c_int = -5; -pub const EMSCRIPTEN_RESULT_FAILED: c_int = -6; -pub const EMSCRIPTEN_RESULT_NO_DATA: c_int = -7; - -// values for EMSCRIPTEN EVENT -pub const EMSCRIPTEN_EVENT_KEYPRESS: c_int = 1; -pub const EMSCRIPTEN_EVENT_KEYDOWN: c_int = 2; -pub const EMSCRIPTEN_EVENT_KEYUP: c_int = 3; -pub const EMSCRIPTEN_EVENT_CLICK: c_int = 4; -pub const EMSCRIPTEN_EVENT_MOUSEDOWN: c_int = 5; -pub const EMSCRIPTEN_EVENT_MOUSEUP: c_int = 6; -pub const EMSCRIPTEN_EVENT_DBLCLICK: c_int = 7; -pub const EMSCRIPTEN_EVENT_MOUSEMOVE: c_int = 8; -pub const EMSCRIPTEN_EVENT_WHEEL: c_int = 9; -pub const EMSCRIPTEN_EVENT_RESIZE: c_int = 10; -pub const EMSCRIPTEN_EVENT_SCROLL: c_int = 11; -pub const EMSCRIPTEN_EVENT_BLUR: c_int = 12; -pub const EMSCRIPTEN_EVENT_FOCUS: c_int = 13; -pub const EMSCRIPTEN_EVENT_FOCUSIN: c_int = 14; -pub const EMSCRIPTEN_EVENT_FOCUSOUT: c_int = 15; -pub const EMSCRIPTEN_EVENT_DEVICEORIENTATION: c_int = 16; -pub const EMSCRIPTEN_EVENT_DEVICEMOTION: c_int = 17; -pub const EMSCRIPTEN_EVENT_ORIENTATIONCHANGE: c_int = 18; -pub const EMSCRIPTEN_EVENT_FULLSCREENCHANGE: c_int = 19; -pub const EMSCRIPTEN_EVENT_POINTERLOCKCHANGE: c_int = 20; -pub const EMSCRIPTEN_EVENT_VISIBILITYCHANGE: c_int = 21; -pub const EMSCRIPTEN_EVENT_TOUCHSTART: c_int = 22; -pub const EMSCRIPTEN_EVENT_TOUCHEND: c_int = 23; -pub const EMSCRIPTEN_EVENT_TOUCHMOVE: c_int = 24; -pub const EMSCRIPTEN_EVENT_TOUCHCANCEL: c_int = 25; -pub const EMSCRIPTEN_EVENT_GAMEPADCONNECTED: c_int = 26; -pub const EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED: c_int = 27; -pub const EMSCRIPTEN_EVENT_BEFOREUNLOAD: c_int = 28; -pub const EMSCRIPTEN_EVENT_BATTERYCHARGINGCHANGE: c_int = 29; -pub const EMSCRIPTEN_EVENT_BATTERYLEVELCHANGE: c_int = 30; -pub const EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: c_int = 31; -pub const EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: c_int = 32; -pub const EMSCRIPTEN_EVENT_MOUSEENTER: c_int = 33; -pub const EMSCRIPTEN_EVENT_MOUSELEAVE: c_int = 34; -pub const EMSCRIPTEN_EVENT_MOUSEOVER: c_int = 35; -pub const EMSCRIPTEN_EVENT_MOUSEOUT: c_int = 36; -pub const EMSCRIPTEN_EVENT_CANVASRESIZED: c_int = 37; -pub const EMSCRIPTEN_EVENT_POINTERLOCKERROR: c_int = 38; - -pub const EM_HTML5_SHORT_STRING_LEN_BYTES: usize = 32; - -pub const DOM_KEY_LOCATION_STANDARD: c_ulong = 0x00; -pub const DOM_KEY_LOCATION_LEFT: c_ulong = 0x01; -pub const DOM_KEY_LOCATION_RIGHT: c_ulong = 0x02; -pub const DOM_KEY_LOCATION_NUMPAD: c_ulong = 0x03; - -pub type em_callback_func = Option; - -pub type em_key_callback_func = Option EM_BOOL>; - -pub type em_mouse_callback_func = Option EM_BOOL>; - -pub type em_pointerlockchange_callback_func = Option EM_BOOL>; - -pub type em_fullscreenchange_callback_func = Option EM_BOOL>; - -pub type em_touch_callback_func = Option EM_BOOL>; - -#[repr(C)] -pub struct EmscriptenFullscreenChangeEvent { - pub isFullscreen: c_int, - pub fullscreenEnabled: c_int, - pub nodeName: [c_char; 128usize], - pub id: [c_char; 128usize], - pub elementWidth: c_int, - pub elementHeight: c_int, - pub screenWidth: c_int, - pub screenHeight: c_int, -} -#[test] -fn bindgen_test_layout_EmscriptenFullscreenChangeEvent() { - assert_eq!(mem::size_of::(), 280usize); - assert_eq!(mem::align_of::(), 4usize); -} - -#[repr(C)] -#[derive(Debug, Copy)] -pub struct EmscriptenKeyboardEvent { - pub key: [c_char; 32usize], - pub code: [c_char; 32usize], - pub location: c_ulong, - pub ctrlKey: c_int, - pub shiftKey: c_int, - pub altKey: c_int, - pub metaKey: c_int, - pub repeat: c_int, - pub locale: [c_char; 32usize], - pub charValue: [c_char; 32usize], - pub charCode: c_ulong, - pub keyCode: c_ulong, - pub which: c_ulong, -} -#[test] -fn bindgen_test_layout_EmscriptenKeyboardEvent() { - assert_eq!(mem::size_of::(), 184usize); - assert_eq!(mem::align_of::(), 8usize); -} -impl Clone for EmscriptenKeyboardEvent { - fn clone(&self) -> Self { *self } -} - -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct EmscriptenMouseEvent { - pub timestamp: f64, - pub screenX: c_long, - pub screenY: c_long, - pub clientX: c_long, - pub clientY: c_long, - pub ctrlKey: c_int, - pub shiftKey: c_int, - pub altKey: c_int, - pub metaKey: c_int, - pub button: c_ushort, - pub buttons: c_ushort, - pub movementX: c_long, - pub movementY: c_long, - pub targetX: c_long, - pub targetY: c_long, - pub canvasX: c_long, - pub canvasY: c_long, - pub padding: c_long, -} -#[test] -fn bindgen_test_layout_EmscriptenMouseEvent() { - assert_eq!(mem::size_of::(), 120usize); - assert_eq!(mem::align_of::(), 8usize); -} - -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct EmscriptenTouchPoint { - pub identifier: c_long, - pub screenX: c_long, - pub screenY: c_long, - pub clientX: c_long, - pub clientY: c_long, - pub pageX: c_long, - pub pageY: c_long, - pub isChanged: c_int, - pub onTarget: c_int, - pub targetX: c_long, - pub targetY: c_long, - pub canvasX: c_long, - pub canvasY: c_long, -} -#[test] -fn bindgen_test_layout_EmscriptenTouchPoint() { - assert_eq!(mem::size_of::(), 96usize); - assert_eq!(mem::align_of::(), 8usize); -} - -#[repr(C)] -#[derive(Debug, Copy, Clone)] -pub struct EmscriptenTouchEvent { - pub numTouches: c_int, - pub ctrlKey: c_int, - pub shiftKey: c_int, - pub altKey: c_int, - pub metaKey: c_int, - pub touches: [EmscriptenTouchPoint; 32usize], -} -#[test] -fn bindgen_test_layout_EmscriptenTouchEvent() { - assert_eq!(mem::size_of::(), 3096usize); - assert_eq!(mem::align_of::(), 8usize); -} - -#[repr(C)] -pub struct EmscriptenPointerlockChangeEvent { - pub isActive: c_int, - pub nodeName: [c_char; 128usize], - pub id: [c_char; 128usize], -} -#[test] -fn bindgen_test_layout_EmscriptenPointerlockChangeEvent() { - assert_eq!(mem::size_of::(), 260usize); - assert_eq!(mem::align_of::(), 4usize); -} - -extern "C" { - pub fn emscripten_set_canvas_size( - width: c_int, height: c_int) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_get_canvas_size( - width: *mut c_int, height: *mut c_int, - is_fullscreen: *mut c_int) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_element_css_size( - target: *const c_char, width: c_double, - height: c_double) -> EMSCRIPTEN_RESULT; - - pub fn emscripten_get_element_css_size( - target: *const c_char, width: *mut c_double, - height: *mut c_double) -> EMSCRIPTEN_RESULT; - - pub fn emscripten_request_pointerlock( - target: *const c_char, deferUntilInEventHandler: EM_BOOL) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_exit_pointerlock() -> EMSCRIPTEN_RESULT; - - pub fn emscripten_request_fullscreen( - target: *const c_char, deferUntilInEventHandler: EM_BOOL) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_exit_fullscreen() -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_keydown_callback( - target: *const c_char, userData: *mut c_void, - useCapture: EM_BOOL, callback: em_key_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_keyup_callback( - target: *const c_char, userData: *mut c_void, - useCapture: EM_BOOL, callback: em_key_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_mousemove_callback( - target: *const c_char, user_data: *mut c_void, - use_capture: EM_BOOL, callback: em_mouse_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_mousedown_callback( - target: *const c_char, user_data: *mut c_void, - use_capture: EM_BOOL, callback: em_mouse_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_mouseup_callback( - target: *const c_char, user_data: *mut c_void, - use_capture: EM_BOOL, callback: em_mouse_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_hide_mouse(); - - pub fn emscripten_get_device_pixel_ratio() -> f64; - - pub fn emscripten_set_pointerlockchange_callback( - target: *const c_char, userData: *mut c_void, useCapture: EM_BOOL, - callback: em_pointerlockchange_callback_func) -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_fullscreenchange_callback( - target: *const c_char, userData: *mut c_void, useCapture: EM_BOOL, - callback: em_fullscreenchange_callback_func) -> EMSCRIPTEN_RESULT; - - pub fn emscripten_asm_const(code: *const c_char); - - pub fn emscripten_set_main_loop( - func: em_callback_func, fps: c_int, simulate_infinite_loop: EM_BOOL); - - pub fn emscripten_cancel_main_loop(); - - pub fn emscripten_set_touchstart_callback( - target: *const c_char, userData: *mut c_void, - useCapture: c_int, callback: em_touch_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_touchend_callback( - target: *const c_char, userData: *mut c_void, - useCapture: c_int, callback: em_touch_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_touchmove_callback( - target: *const c_char, userData: *mut c_void, - useCapture: c_int, callback: em_touch_callback_func) - -> EMSCRIPTEN_RESULT; - - pub fn emscripten_set_touchcancel_callback( - target: *const c_char, userData: *mut c_void, - useCapture: c_int, callback: em_touch_callback_func) - -> EMSCRIPTEN_RESULT; -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/mod.rs deleted file mode 100644 index 3a5feb6..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/emscripten/mod.rs +++ /dev/null @@ -1,1135 +0,0 @@ -#![cfg(target_os = "emscripten")] - -mod ffi; - -use std::{mem, ptr, str}; -use std::cell::RefCell; -use std::collections::VecDeque; -use std::os::raw::{c_char, c_void, c_double, c_ulong, c_int}; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Mutex, Arc}; - -use dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; -use window::MonitorId as RootMonitorId; - -const DOCUMENT_NAME: &'static str = "#document\0"; - -fn get_hidpi_factor() -> f64 { - unsafe { ffi::emscripten_get_device_pixel_ratio() as f64 } -} - -#[derive(Clone, Default)] -pub struct PlatformSpecificWindowBuilderAttributes; - -unsafe impl Send for PlatformSpecificWindowBuilderAttributes {} -unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DeviceId; - -impl DeviceId { - pub unsafe fn dummy() -> Self { - DeviceId - } -} - -#[derive(Clone, Default)] -pub struct PlatformSpecificHeadlessBuilderAttributes; - -#[derive(Debug, Clone)] -pub struct MonitorId; - -impl MonitorId { - #[inline] - pub fn get_name(&self) -> Option { - Some("Canvas".to_owned()) - } - - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - unimplemented!() - } - - #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { - (0, 0).into() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - get_hidpi_factor() - } -} - -// Used to assign a callback to emscripten main loop -thread_local!(static MAIN_LOOP_CALLBACK: RefCell<*mut c_void> = RefCell::new(ptr::null_mut())); - -// Used to assign a callback to emscripten main loop -pub fn set_main_loop_callback(callback : F) where F : FnMut() { - MAIN_LOOP_CALLBACK.with(|log| { - *log.borrow_mut() = &callback as *const _ as *mut c_void; - }); - - unsafe { ffi::emscripten_set_main_loop(Some(wrapper::), 0, 1); } - - unsafe extern "C" fn wrapper() where F : FnMut() { - MAIN_LOOP_CALLBACK.with(|z| { - let closure = *z.borrow_mut() as *mut F; - (*closure)(); - }); - } -} - -#[derive(Clone)] -pub struct EventsLoopProxy; - -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), ::EventsLoopClosed> { - unimplemented!() - } -} - -pub struct EventsLoop { - window: Mutex>>, - interrupted: AtomicBool, -} - -impl EventsLoop { - pub fn new() -> EventsLoop { - EventsLoop { - window: Mutex::new(None), - interrupted: AtomicBool::new(false), - } - } - - #[inline] - pub fn interrupt(&self) { - self.interrupted.store(true, Ordering::Relaxed); - } - - #[inline] - pub fn create_proxy(&self) -> EventsLoopProxy { - unimplemented!() - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - let mut list = VecDeque::with_capacity(1); - list.push_back(MonitorId); - list - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId - } - - pub fn poll_events(&self, mut callback: F) - where F: FnMut(::Event) - { - let ref mut window = *self.window.lock().unwrap(); - if let &mut Some(ref mut window) = window { - while let Some(event) = window.events.lock().unwrap().pop_front() { - callback(event) - } - } - } - - pub fn run_forever(&self, mut callback: F) - where F: FnMut(::Event) -> ::ControlFlow - { - self.interrupted.store(false, Ordering::Relaxed); - - // TODO: handle control flow - - set_main_loop_callback(|| { - self.poll_events(|e| { callback(e); }); - ::std::thread::sleep(::std::time::Duration::from_millis(5)); - if self.interrupted.load(Ordering::Relaxed) { - unsafe { ffi::emscripten_cancel_main_loop(); } - } - }); - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WindowId(usize); - -impl WindowId { - pub unsafe fn dummy() -> Self { - WindowId(0) - } -} - -pub struct Window2 { - cursor_grabbed: Mutex, - cursor_hidden: Mutex, - is_fullscreen: bool, - events: Box>>, -} - -pub struct Window { - window: Arc, -} - -fn show_mouse() { - // Hide mouse hasn't show mouse equivalent. - // There is a pull request on emscripten that hasn't been merged #4616 - // that contains: - // - // var styleSheet = document.styleSheets[0]; - // var rules = styleSheet.cssRules; - // for (var i = 0; i < rules.length; i++) { - // if (rules[i].cssText.substr(0, 6) == 'canvas') { - // styleSheet.deleteRule(i); - // i--; - // } - // } - // styleSheet.insertRule('canvas.emscripten { border: none; cursor: auto; }', 0); - unsafe { - ffi::emscripten_asm_const(b"var styleSheet = document.styleSheets[0]; var rules = styleSheet.cssRules; for (var i = 0; i < rules.length; i++) { if (rules[i].cssText.substr(0, 6) == 'canvas') { styleSheet.deleteRule(i); i--; } } styleSheet.insertRule('canvas.emscripten { border: none; cursor: auto; }', 0);\0".as_ptr() as *const c_char); - } -} - -extern "C" fn mouse_callback( - event_type: c_int, - event: *const ffi::EmscriptenMouseEvent, - event_queue: *mut c_void) -> ffi::EM_BOOL -{ - unsafe { - let queue: &Mutex> = mem::transmute(event_queue); - - let modifiers = ::ModifiersState { - shift: (*event).shiftKey == ffi::EM_TRUE, - ctrl: (*event).ctrlKey == ffi::EM_TRUE, - alt: (*event).altKey == ffi::EM_TRUE, - logo: (*event).metaKey == ffi::EM_TRUE, - }; - - match event_type { - ffi::EMSCRIPTEN_EVENT_MOUSEMOVE => { - let dpi_factor = get_hidpi_factor(); - let position = LogicalPosition::from_physical( - ((*event).canvasX as f64, (*event).canvasY as f64), - dpi_factor, - ); - queue.lock().unwrap().push_back(::Event::WindowEvent { - window_id: ::WindowId(WindowId(0)), - event: ::WindowEvent::CursorMoved { - device_id: ::DeviceId(DeviceId), - position, - modifiers: modifiers, - } - }); - queue.lock().unwrap().push_back(::Event::DeviceEvent { - device_id: ::DeviceId(DeviceId), - event: ::DeviceEvent::MouseMotion { - delta: ((*event).movementX as f64, (*event).movementY as f64), - } - }); - }, - mouse_input @ ffi::EMSCRIPTEN_EVENT_MOUSEDOWN | - mouse_input @ ffi::EMSCRIPTEN_EVENT_MOUSEUP => { - let button = match (*event).button { - 0 => ::MouseButton::Left, - 1 => ::MouseButton::Middle, - 2 => ::MouseButton::Right, - other => ::MouseButton::Other(other as u8), - }; - let state = match mouse_input { - ffi::EMSCRIPTEN_EVENT_MOUSEDOWN => ::ElementState::Pressed, - ffi::EMSCRIPTEN_EVENT_MOUSEUP => ::ElementState::Released, - _ => unreachable!(), - }; - queue.lock().unwrap().push_back(::Event::WindowEvent { - window_id: ::WindowId(WindowId(0)), - event: ::WindowEvent::MouseInput { - device_id: ::DeviceId(DeviceId), - state: state, - button: button, - modifiers: modifiers, - } - }) - }, - _ => { - } - } - } - ffi::EM_FALSE -} - -extern "C" fn keyboard_callback( - event_type: c_int, - event: *const ffi::EmscriptenKeyboardEvent, - event_queue: *mut c_void) -> ffi::EM_BOOL -{ - unsafe { - let queue: &Mutex> = mem::transmute(event_queue); - - let modifiers = ::ModifiersState { - shift: (*event).shiftKey == ffi::EM_TRUE, - ctrl: (*event).ctrlKey == ffi::EM_TRUE, - alt: (*event).altKey == ffi::EM_TRUE, - logo: (*event).metaKey == ffi::EM_TRUE, - }; - - match event_type { - ffi::EMSCRIPTEN_EVENT_KEYDOWN => { - queue.lock().unwrap().push_back(::Event::WindowEvent { - window_id: ::WindowId(WindowId(0)), - event: ::WindowEvent::KeyboardInput { - device_id: ::DeviceId(DeviceId), - input: ::KeyboardInput { - scancode: key_translate((*event).key) as u32, - state: ::ElementState::Pressed, - virtual_keycode: key_translate_virt((*event).key, (*event).location), - modifiers, - }, - }, - }); - }, - ffi::EMSCRIPTEN_EVENT_KEYUP => { - queue.lock().unwrap().push_back(::Event::WindowEvent { - window_id: ::WindowId(WindowId(0)), - event: ::WindowEvent::KeyboardInput { - device_id: ::DeviceId(DeviceId), - input: ::KeyboardInput { - scancode: key_translate((*event).key) as u32, - state: ::ElementState::Released, - virtual_keycode: key_translate_virt((*event).key, (*event).location), - modifiers, - }, - }, - }); - }, - _ => { - } - } - } - ffi::EM_FALSE -} - -extern fn touch_callback( - event_type: c_int, - event: *const ffi::EmscriptenTouchEvent, - event_queue: *mut c_void) -> ffi::EM_BOOL -{ - unsafe { - let queue: &Mutex> = mem::transmute(event_queue); - - let phase = match event_type { - ffi::EMSCRIPTEN_EVENT_TOUCHSTART => ::TouchPhase::Started, - ffi::EMSCRIPTEN_EVENT_TOUCHEND => ::TouchPhase::Ended, - ffi::EMSCRIPTEN_EVENT_TOUCHMOVE => ::TouchPhase::Moved, - ffi::EMSCRIPTEN_EVENT_TOUCHCANCEL => ::TouchPhase::Cancelled, - _ => return ffi::EM_FALSE, - }; - - for touch in 0..(*event).numTouches as usize { - let touch = (*event).touches[touch]; - if touch.isChanged == ffi::EM_TRUE { - let dpi_factor = get_hidpi_factor(); - let location = LogicalPosition::from_physical( - (touch.canvasX as f64, touch.canvasY as f64), - dpi_factor, - ); - queue.lock().unwrap().push_back(::Event::WindowEvent { - window_id: ::WindowId(WindowId(0)), - event: ::WindowEvent::Touch(::Touch { - device_id: ::DeviceId(DeviceId), - phase, - id: touch.identifier as u64, - location, - }), - }); - } - } - } - ffi::EM_FALSE -} - -// In case of fullscreen window this method will request fullscreen on change -#[allow(non_snake_case)] -unsafe extern "C" fn fullscreen_callback( - _eventType: c_int, - _fullscreenChangeEvent: *const ffi::EmscriptenFullscreenChangeEvent, - _userData: *mut c_void) -> ffi::EM_BOOL -{ - ffi::emscripten_request_fullscreen(ptr::null(), ffi::EM_TRUE); - ffi::EM_FALSE -} - -// In case of pointer grabbed this method will request pointer lock on change -#[allow(non_snake_case)] -unsafe extern "C" fn pointerlockchange_callback( - _eventType: c_int, - _pointerlockChangeEvent: *const ffi::EmscriptenPointerlockChangeEvent, - _userData: *mut c_void) -> ffi::EM_BOOL -{ - ffi::emscripten_request_pointerlock(ptr::null(), ffi::EM_TRUE); - ffi::EM_FALSE -} - -fn em_try(res: ffi::EMSCRIPTEN_RESULT) -> Result<(), String> { - match res { - ffi::EMSCRIPTEN_RESULT_SUCCESS | ffi::EMSCRIPTEN_RESULT_DEFERRED => Ok(()), - r @ _ => Err(error_to_str(r).to_string()), - } -} - -impl Window { - pub fn new(events_loop: &EventsLoop, attribs: ::WindowAttributes, - _pl_attribs: PlatformSpecificWindowBuilderAttributes) - -> Result - { - if events_loop.window.lock().unwrap().is_some() { - return Err(::CreationError::OsError("Cannot create another window".to_owned())); - } - - let w = Window2 { - cursor_grabbed: Default::default(), - cursor_hidden: Default::default(), - events: Default::default(), - is_fullscreen: attribs.fullscreen.is_some(), - }; - - let window = Window { - window: Arc::new(w), - }; - - - // TODO: set up more event callbacks - unsafe { - em_try(ffi::emscripten_set_mousemove_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(mouse_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_mousedown_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(mouse_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_mouseup_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(mouse_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_keydown_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(keyboard_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_keyup_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(keyboard_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_touchstart_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(touch_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_touchend_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(touch_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_touchmove_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(touch_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - em_try(ffi::emscripten_set_touchcancel_callback(DOCUMENT_NAME.as_ptr() as *const c_char, mem::transmute(&*window.window.events), ffi::EM_FALSE, Some(touch_callback))) - .map_err(|e| ::CreationError::OsError(format!("emscripten error: {}", e)))?; - } - - if attribs.fullscreen.is_some() { - unsafe { - em_try(ffi::emscripten_request_fullscreen(ptr::null(), ffi::EM_TRUE)) - .map_err(|e| ::CreationError::OsError(e))?; - em_try(ffi::emscripten_set_fullscreenchange_callback(ptr::null(), 0 as *mut c_void, ffi::EM_FALSE, Some(fullscreen_callback))) - .map_err(|e| ::CreationError::OsError(e))?; - } - } else if let Some(size) = attribs.dimensions { - window.set_inner_size(size); - } - - *events_loop.window.lock().unwrap() = Some(window.window.clone()); - Ok(window) - } - - #[inline] - pub fn id(&self) -> WindowId { - WindowId(0) - } - - #[inline] - pub fn set_title(&self, _title: &str) { - } - - #[inline] - pub fn get_position(&self) -> Option { - Some((0, 0).into()) - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - Some((0, 0).into()) - } - - #[inline] - pub fn set_position(&self, _: LogicalPosition) { - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - unsafe { - let mut width = 0; - let mut height = 0; - let mut fullscreen = 0; - - if ffi::emscripten_get_canvas_size(&mut width, &mut height, &mut fullscreen) - != ffi::EMSCRIPTEN_RESULT_SUCCESS - { - None - } else { - let dpi_factor = self.get_hidpi_factor(); - let logical = LogicalSize::from_physical((width as u32, height as u32), dpi_factor); - Some(logical) - } - } - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - self.get_inner_size() - } - - #[inline] - pub fn set_inner_size(&self, size: LogicalSize) { - unsafe { - let dpi_factor = self.get_hidpi_factor(); - let physical = PhysicalSize::from_logical(size, dpi_factor); - let (width, height): (u32, u32) = physical.into(); - ffi::emscripten_set_element_css_size( - ptr::null(), - width as c_double, - height as c_double, - ); - } - } - - #[inline] - pub fn set_min_dimensions(&self, _dimensions: Option) { - // N/A - } - - #[inline] - pub fn set_max_dimensions(&self, _dimensions: Option) { - // N/A - } - - #[inline] - pub fn set_resizable(&self, _resizable: bool) { - // N/A - } - - #[inline] - pub fn show(&self) { - // N/A - } - - #[inline] - pub fn hide(&self) { - // N/A - } - - #[inline] - pub fn set_cursor(&self, _cursor: ::MouseCursor) { - // N/A - } - - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - let mut grabbed_lock = self.window.cursor_grabbed.lock().unwrap(); - if grab == *grabbed_lock { return Ok(()); } - unsafe { - if grab { - em_try(ffi::emscripten_set_pointerlockchange_callback( - ptr::null(), - 0 as *mut c_void, - ffi::EM_FALSE, - Some(pointerlockchange_callback), - ))?; - em_try(ffi::emscripten_request_pointerlock(ptr::null(), ffi::EM_TRUE))?; - } else { - em_try(ffi::emscripten_set_pointerlockchange_callback( - ptr::null(), - 0 as *mut c_void, - ffi::EM_FALSE, - None, - ))?; - em_try(ffi::emscripten_exit_pointerlock())?; - } - } - *grabbed_lock = grab; - Ok(()) - } - - #[inline] - pub fn hide_cursor(&self, hide: bool) { - let mut hidden_lock = self.window.cursor_hidden.lock().unwrap(); - if hide == *hidden_lock { return; } - if hide { - unsafe { ffi::emscripten_hide_mouse() }; - } else { - show_mouse(); - } - *hidden_lock = hide; - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - get_hidpi_factor() - } - - #[inline] - pub fn set_cursor_position(&self, _position: LogicalPosition) -> Result<(), String> { - Err("Setting cursor position is not possible on Emscripten.".to_owned()) - } - - #[inline] - pub fn set_maximized(&self, _maximized: bool) { - // iOS has single screen maximized apps so nothing to do - } - - #[inline] - pub fn set_fullscreen(&self, _monitor: Option<::MonitorId>) { - // iOS has single screen maximized apps so nothing to do - } - - #[inline] - pub fn set_decorations(&self, _decorations: bool) { - // N/A - } - - #[inline] - pub fn set_always_on_top(&self, _always_on_top: bool) { - // N/A - } - - #[inline] - pub fn set_window_icon(&self, _icon: Option<::Icon>) { - // N/A - } - - #[inline] - pub fn set_ime_spot(&self, _logical_spot: LogicalPosition) { - // N/A - } - - #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - RootMonitorId { inner: MonitorId } - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - let mut list = VecDeque::with_capacity(1); - list.push_back(MonitorId); - list - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId - } -} - -impl Drop for Window { - fn drop(&mut self) { - // Delete window from events_loop - // TODO: ? - /*if let Some(ev) = self.events_loop.upgrade() { - let _ = ev.window.lock().unwrap().take().unwrap(); - }*/ - - unsafe { - // Return back to normal cursor state - self.hide_cursor(false); - self.grab_cursor(false); - - // Exit fullscreen if on - if self.window.is_fullscreen { - ffi::emscripten_set_fullscreenchange_callback(ptr::null(), 0 as *mut c_void, ffi::EM_FALSE, None); - ffi::emscripten_exit_fullscreen(); - } - - // Delete callbacks - ffi::emscripten_set_keydown_callback(DOCUMENT_NAME.as_ptr() as *const c_char, 0 as *mut c_void, ffi::EM_FALSE,None); - ffi::emscripten_set_keyup_callback(DOCUMENT_NAME.as_ptr() as *const c_char, 0 as *mut c_void, ffi::EM_FALSE,None); - } - } -} - -fn error_to_str(code: ffi::EMSCRIPTEN_RESULT) -> &'static str { - match code { - ffi::EMSCRIPTEN_RESULT_SUCCESS | ffi::EMSCRIPTEN_RESULT_DEFERRED - => "Internal error in the library (success detected as failure)", - - ffi::EMSCRIPTEN_RESULT_NOT_SUPPORTED => "Not supported", - ffi::EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED => "Failed not deferred", - ffi::EMSCRIPTEN_RESULT_INVALID_TARGET => "Invalid target", - ffi::EMSCRIPTEN_RESULT_UNKNOWN_TARGET => "Unknown target", - ffi::EMSCRIPTEN_RESULT_INVALID_PARAM => "Invalid parameter", - ffi::EMSCRIPTEN_RESULT_FAILED => "Failed", - ffi::EMSCRIPTEN_RESULT_NO_DATA => "No data", - - _ => "Undocumented error" - } -} - -fn key_translate(input: [ffi::EM_UTF8; ffi::EM_HTML5_SHORT_STRING_LEN_BYTES]) -> u8 { - let slice = &input[0..input.iter().take_while(|x| **x != 0).count()]; - let maybe_key = unsafe { str::from_utf8(mem::transmute::<_, &[u8]>(slice)) }; - let key = match maybe_key { - Ok(key) => key, - Err(_) => { return 0; }, - }; - if key.chars().count() == 1 { - key.as_bytes()[0] - } else { - 0 - } -} - -fn key_translate_virt(input: [ffi::EM_UTF8; ffi::EM_HTML5_SHORT_STRING_LEN_BYTES], - location: c_ulong) -> Option<::VirtualKeyCode> -{ - let slice = &input[0..input.iter().take_while(|x| **x != 0).count()]; - let maybe_key = unsafe { str::from_utf8(mem::transmute::<_, &[u8]>(slice)) }; - let key = match maybe_key { - Ok(key) => key, - Err(_) => { return None; }, - }; - use VirtualKeyCode::*; - match key { - "Alt" => match location { - ffi::DOM_KEY_LOCATION_LEFT => Some(LAlt), - ffi::DOM_KEY_LOCATION_RIGHT => Some(RAlt), - _ => None, - }, - "AltGraph" => None, - "CapsLock" => None, - "Control" => match location { - ffi::DOM_KEY_LOCATION_LEFT => Some(LControl), - ffi::DOM_KEY_LOCATION_RIGHT => Some(RControl), - _ => None, - }, - "Fn" => None, - "FnLock" => None, - "Hyper" => None, - "Meta" => None, - "NumLock" => Some(Numlock), - "ScrollLock" => Some(Scroll), - "Shift" => match location { - ffi::DOM_KEY_LOCATION_LEFT => Some(LShift), - ffi::DOM_KEY_LOCATION_RIGHT => Some(RShift), - _ => None, - }, - "Super" => None, - "Symbol" => None, - "SymbolLock" => None, - - "Enter" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(NumpadEnter), - _ => Some(Return), - }, - "Tab" => Some(Tab), - " " => Some(Space), - - "ArrowDown" => Some(Down), - "ArrowLeft" => Some(Left), - "ArrowRight" => Some(Right), - "ArrowUp" => Some(Up), - "End" => None, - "Home" => None, - "PageDown" => None, - "PageUp" => None, - - "Backspace" => Some(Back), - "Clear" => None, - "Copy" => None, - "CrSel" => None, - "Cut" => None, - "Delete" => None, - "EraseEof" => None, - "ExSel" => None, - "Insert" => Some(Insert), - "Paste" => None, - "Redo" => None, - "Undo" => None, - - "Accept" => None, - "Again" => None, - "Attn" => None, - "Cancel" => None, - "ContextMenu" => None, - "Escape" => Some(Escape), - "Execute" => None, - "Find" => None, - "Finish" => None, - "Help" => None, - "Pause" => Some(Pause), - "Play" => None, - "Props" => None, - "Select" => None, - "ZoomIn" => None, - "ZoomOut" => None, - - "BrightnessDown" => None, - "BrightnessUp" => None, - "Eject" => None, - "LogOff" => None, - "Power" => Some(Power), - "PowerOff" => None, - "PrintScreen" => Some(Snapshot), - "Hibernate" => None, - "Standby" => Some(Sleep), - "WakeUp" => Some(Wake), - - "AllCandidates" => None, - "Alphanumeric" => None, - "CodeInput" => None, - "Compose" => Some(Compose), - "Convert" => Some(Convert), - "Dead" => None, - "FinalMode" => None, - "GroupFirst" => None, - "GroupLast" => None, - "GroupNext" => None, - "GroupPrevious" => None, - "ModeChange" => None, - "NextCandidate" => None, - "NonConvert" => None, - "PreviousCandidate" => None, - "Process" => None, - "SingleCandidate" => None, - - "HangulMode" => None, - "HanjaMode" => None, - "JunjaMode" => None, - - "Eisu" => None, - "Hankaku" => None, - "Hiragana" => None, - "HiraganaKatakana" => None, - "KanaMode" => Some(Kana), - "KanjiMode" => Some(Kanji), - "Romaji" => None, - "Zenkaku" => None, - "ZenkakuHanaku" => None, - - "F1" => Some(F1), - "F2" => Some(F2), - "F3" => Some(F3), - "F4" => Some(F4), - "F5" => Some(F5), - "F6" => Some(F6), - "F7" => Some(F7), - "F8" => Some(F8), - "F9" => Some(F9), - "F10" => Some(F10), - "F11" => Some(F11), - "F12" => Some(F12), - "F13" => Some(F13), - "F14" => Some(F14), - "F15" => Some(F15), - "F16" => Some(F16), - "F17" => Some(F17), - "F18" => Some(F18), - "F19" => Some(F19), - "F20" => Some(F20), - "F21" => Some(F21), - "F22" => Some(F22), - "F23" => Some(F23), - "F24" => Some(F24), - "Soft1" => None, - "Soft2" => None, - "Soft3" => None, - "Soft4" => None, - - "AppSwitch" => None, - "Call" => None, - "Camera" => None, - "CameraFocus" => None, - "EndCall" => None, - "GoBack" => None, - "GoHome" => None, - "HeadsetHook" => None, - "LastNumberRedial" => None, - "Notification" => None, - "MannerMode" => None, - "VoiceDial" => None, - - "ChannelDown" => None, - "ChannelUp" => None, - "MediaFastForward" => None, - "MediaPause" => None, - "MediaPlay" => None, - "MediaPlayPause" => Some(PlayPause), - "MediaRecord" => None, - "MediaRewind" => None, - "MediaStop" => Some(MediaStop), - "MediaTrackNext" => Some(NextTrack), - "MediaTrackPrevious" => Some(PrevTrack), - - "AudioBalanceLeft" => None, - "AudioBalanceRight" => None, - "AudioBassDown" => None, - "AudioBassBoostDown" => None, - "AudioBassBoostToggle" => None, - "AudioBassBoostUp" => None, - "AudioBassUp" => None, - "AudioFaderFront" => None, - "AudioFaderRear" => None, - "AudioSurroundModeNext" => None, - "AudioTrebleDown" => None, - "AudioTrebleUp" => None, - "AudioVolumeDown" => Some(VolumeDown), - "AudioVolumeMute" => Some(Mute), - "AudioVolumeUp" => Some(VolumeUp), - "MicrophoneToggle" => None, - "MicrophoneVolumeDown" => None, - "MicrophoneVolumeMute" => None, - "MicrophoneVolumeUp" => None, - - "TV" => None, - "TV3DMode" => None, - "TVAntennaCable" => None, - "TVAudioDescription" => None, - "TVAudioDescriptionMixDown" => None, - "TVAudioDescriptionMixUp" => None, - "TVContentsMenu" => None, - "TVDataService" => None, - "TVInput" => None, - "TVInputComponent1" => None, - "TVInputComponent2" => None, - "TVInputComposite1" => None, - "TVInputComposite2" => None, - "TVInputHDM1" => None, - "TVInputHDM2" => None, - "TVInputHDM3" => None, - "TVInputHDM4" => None, - "TVInputVGA1" => None, - "TVMediaContext" => None, - "TVNetwork" => None, - "TVNumberEntry" => None, - "TVPower" => None, - "TVRadioService" => None, - "TVSatellite" => None, - "TVSatelliteBS" => None, - "TVSatelliteCS" => None, - "TVSatelliteToggle" => None, - "TVTerrestrialAnalog" => None, - "TVTerrestrialDigital" => None, - "TVTimer" => None, - - "AVRInput" => None, - "AVRPower" => None, - "ColorF0Red" => None, - "ColorF1Green" => None, - "ColorF2Yellow" => None, - "ColorF3Blue" => None, - "ColorF4Grey" => None, - "ColorF5Brown" => None, - "ClosedCaptionToggle" => None, - "Dimmer" => None, - "DisplaySwap" => None, - "DVR" => None, - "Exit" => None, - "FavoriteClear0" => None, - "FavoriteClear1" => None, - "FavoriteClear2" => None, - "FavoriteClear3" => None, - "FavoriteRecall0" => None, - "FavoriteRecall1" => None, - "FavoriteRecall2" => None, - "FavoriteRecall3" => None, - "FavoriteStore0" => None, - "FavoriteStore1" => None, - "FavoriteStore2" => None, - "FavoriteStore3" => None, - "FavoriteStore4" => None, - "Guide" => None, - "GuideNextDay" => None, - "GuidePreviousDay" => None, - "Info" => None, - "InstantReplay" => None, - "Link" => None, - "ListProgram" => None, - "LiveContent" => None, - "Lock" => None, - "MediaApps" => None, - "MediaAudioTrack" => None, - "MediaLast" => None, - "MediaSkipBackward" => None, - "MediaSkipForward" => None, - "MediaStepBackward" => None, - "MediaStepForward" => None, - "MediaTopMenu" => None, - "NavigateIn" => None, - "NavigateNext" => None, - "NavigateOut" => None, - "NavigatePrevious" => None, - "NextFavoriteChannel" => None, - "NextUserProfile" => None, - "OnDemand" => None, - "Pairing" => None, - "PinPDown" => None, - "PinPMove" => None, - "PinPToggle" => None, - "PinPUp" => None, - "PlaySpeedDown" => None, - "PlaySpeedReset" => None, - "PlaySpeedUp" => None, - "RandomToggle" => None, - "RcLowBattery" => None, - "RecordSpeedNext" => None, - "RfBypass" => None, - "ScanChannelsToggle" => None, - "ScreenModeNext" => None, - "Settings" => None, - "SplitScreenToggle" => None, - "STBInput" => None, - "STBPower" => None, - "Subtitle" => None, - "Teletext" => None, - "VideoModeNext" => None, - "Wink" => None, - "ZoomToggle" => None, - - "SpeechCorrectionList" => None, - "SpeechInputToggle" => None, - - "Close" => None, - "New" => None, - "Open" => None, - "Print" => None, - "Save" => None, - "SpellCheck" => None, - "MailForward" => None, - "MailReply" => None, - "MailSend" => None, - - "LaunchCalculator" => Some(Calculator), - "LaunchCalendar" => None, - "LaunchContacts" => None, - "LaunchMail" => Some(Mail), - "LaunchMediaPlayer" => None, - "LaunchMusicPlayer" => None, - "LaunchMyComputer" => Some(MyComputer), - "LaunchPhone" => None, - "LaunchScreenSaver" => None, - "LaunchSpreadsheet" => None, - "LaunchWebCam" => None, - "LaunchWordProcessor" => None, - "LaunchApplication1" => None, - "LaunchApplication2" => None, - "LaunchApplication3" => None, - "LaunchApplication4" => None, - "LaunchApplication5" => None, - "LaunchApplication6" => None, - "LaunchApplication7" => None, - "LaunchApplication8" => None, - "LaunchApplication9" => None, - "LaunchApplication10" => None, - "LaunchApplication11" => None, - "LaunchApplication12" => None, - "LaunchApplication13" => None, - "LaunchApplication14" => None, - "LaunchApplication15" => None, - "LaunchApplication16" => None, - - "BrowserBack" => Some(WebBack), - "BrowserFavorites" => Some(WebFavorites), - "BrowserForward" => Some(WebForward), - "BrowserHome" => Some(WebHome), - "BrowserRefresh" => Some(WebRefresh), - "BrowserSearch" => Some(WebSearch), - "BrowserStop" => Some(WebStop), - - "Decimal" => Some(Decimal), - "Key11" => None, - "Key12" => None, - "Multiply" | "*" => Some(Multiply), - "Add" | "+" => Some(Add), - // "Clear" => None, - "Divide" => Some(Divide), - "Subtract" | "-" => Some(Subtract), - "Separator" => None, - "0" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad0), - _ => Some(Key0), - }, - "1" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad1), - _ => Some(Key1), - }, - "2" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad2), - _ => Some(Key2), - }, - "3" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad3), - _ => Some(Key3), - }, - "4" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad4), - _ => Some(Key4), - }, - "5" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad5), - _ => Some(Key5), - }, - "6" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad6), - _ => Some(Key6), - }, - "7" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad7), - _ => Some(Key7), - }, - "8" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad8), - _ => Some(Key8), - }, - "9" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(Numpad9), - _ => Some(Key9), - }, - - "A" | "a" => Some(A), - "B" | "b" => Some(B), - "C" | "c" => Some(C), - "D" | "d" => Some(D), - "E" | "e" => Some(E), - "F" | "f" => Some(F), - "G" | "g" => Some(G), - "H" | "h" => Some(H), - "I" | "i" => Some(I), - "J" | "j" => Some(J), - "K" | "k" => Some(K), - "L" | "l" => Some(L), - "M" | "m" => Some(M), - "N" | "n" => Some(N), - "O" | "o" => Some(O), - "P" | "p" => Some(P), - "Q" | "q" => Some(Q), - "R" | "r" => Some(R), - "S" | "s" => Some(S), - "T" | "t" => Some(T), - "U" | "u" => Some(U), - "V" | "v" => Some(V), - "W" | "w" => Some(W), - "X" | "x" => Some(X), - "Y" | "y" => Some(Y), - "Z" | "z" => Some(Z), - - "'" => Some(Apostrophe), - "\\" => Some(Backslash), - ":" => Some(Colon), - "," => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(NumpadComma), - _ => Some(Comma), - }, - "=" => match location { - ffi::DOM_KEY_LOCATION_NUMPAD => Some(NumpadEquals), - _ => Some(Equals), - }, - "{" => Some(LBracket), - "." => Some(Period), - "}" => Some(RBracket), - ";" => Some(Semicolon), - "/" => Some(Slash), - - _ => None, - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/ffi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/ffi.rs deleted file mode 100644 index 6fd1a7c..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/ffi.rs +++ /dev/null @@ -1,110 +0,0 @@ -#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] - -use std::ffi::CString; -use std::os::raw::*; - -use objc::runtime::Object; - -pub type id = *mut Object; -pub const nil: id = 0 as id; - -pub type CFStringRef = *const c_void; -pub type CFTimeInterval = f64; -pub type Boolean = u32; - -pub const kCFRunLoopRunHandledSource: i32 = 4; - -#[cfg(target_pointer_width = "32")] -pub type CGFloat = f32; -#[cfg(target_pointer_width = "64")] -pub type CGFloat = f64; - -#[repr(C)] -#[derive(Debug, Clone)] -pub struct CGPoint { - pub x: CGFloat, - pub y: CGFloat, -} - -#[repr(C)] -#[derive(Debug, Clone)] -pub struct CGRect { - pub origin: CGPoint, - pub size: CGSize, -} - -#[repr(C)] -#[derive(Debug, Clone)] -pub struct CGSize { - pub width: CGFloat, - pub height: CGFloat, -} - -#[link(name = "UIKit", kind = "framework")] -#[link(name = "CoreFoundation", kind = "framework")] -#[link(name = "GlKit", kind = "framework")] -extern { - pub static kCFRunLoopDefaultMode: CFStringRef; - - // int UIApplicationMain ( int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName ); - pub fn UIApplicationMain( - argc: c_int, - argv: *const c_char, - principalClassName: id, - delegateClassName: id, - ) -> c_int; - - // SInt32 CFRunLoopRunInMode ( CFStringRef mode, CFTimeInterval seconds, Boolean returnAfterSourceHandled ); - pub fn CFRunLoopRunInMode( - mode: CFStringRef, - seconds: CFTimeInterval, - returnAfterSourceHandled: Boolean, - ) -> i32; -} - -extern { - pub fn setjmp(env: *mut c_void) -> c_int; - pub fn longjmp(env: *mut c_void, val: c_int) -> !; -} - -// values taken from "setjmp.h" header in xcode iPhoneOS/iPhoneSimulator SDK -#[cfg(any(target_arch = "x86_64"))] -pub const JBLEN: usize = (9 * 2) + 3 + 16; -#[cfg(any(target_arch = "x86"))] -pub const JBLEN: usize = 18; -#[cfg(target_arch = "arm")] -pub const JBLEN: usize = 10 + 16 + 2; -#[cfg(target_arch = "aarch64")] -pub const JBLEN: usize = (14 + 8 + 2) * 2; - -pub type JmpBuf = [c_int; JBLEN]; - -pub trait NSString: Sized { - unsafe fn alloc(_: Self) -> id { - msg_send![class!(NSString), alloc] - } - - unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id; - unsafe fn stringByAppendingString_(self, other: id) -> id; - unsafe fn init_str(self, string: &str) -> Self; - unsafe fn UTF8String(self) -> *const c_char; -} - -impl NSString for id { - unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id { - msg_send![self, initWithUTF8String:c_string as id] - } - - unsafe fn stringByAppendingString_(self, other: id) -> id { - msg_send![self, stringByAppendingString:other] - } - - unsafe fn init_str(self, string: &str) -> id { - let cstring = CString::new(string).unwrap(); - self.initWithUTF8String_(cstring.as_ptr()) - } - - unsafe fn UTF8String(self) -> *const c_char { - msg_send![self, UTF8String] - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/mod.rs deleted file mode 100644 index 6830ace..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/ios/mod.rs +++ /dev/null @@ -1,702 +0,0 @@ -//! iOS support -//! -//! # Building app -//! To build ios app you will need rustc built for this targets: -//! -//! - armv7-apple-ios -//! - armv7s-apple-ios -//! - i386-apple-ios -//! - aarch64-apple-ios -//! - x86_64-apple-ios -//! -//! Then -//! -//! ``` -//! cargo build --target=... -//! ``` -//! The simplest way to integrate your app into xcode environment is to build it -//! as a static library. Wrap your main function and export it. -//! -//! ```rust, ignore -//! #[no_mangle] -//! pub extern fn start_winit_app() { -//! start_inner() -//! } -//! -//! fn start_inner() { -//! ... -//! } -//! -//! ``` -//! -//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode. -//! -//! ```ignore -//! void start_winit_app(); -//! ``` -//! -//! Use start_winit_app inside your xcode's main function. -//! -//! -//! # App lifecycle and events -//! -//! iOS environment is very different from other platforms and you must be very -//! careful with it's events. Familiarize yourself with -//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/). -//! -//! -//! This is how those event are represented in winit: -//! -//! - applicationDidBecomeActive is Focused(true) -//! - applicationWillResignActive is Focused(false) -//! - applicationDidEnterBackground is Suspended(true) -//! - applicationWillEnterForeground is Suspended(false) -//! - applicationWillTerminate is Destroyed -//! -//! Keep in mind that after Destroyed event is received every attempt to draw with -//! opengl will result in segfault. -//! -//! Also note that app will not receive Destroyed event if suspended, it will be SIGKILL'ed - -#![cfg(target_os = "ios")] - -use std::{fmt, mem, ptr}; -use std::cell::RefCell; -use std::collections::VecDeque; -use std::os::raw::*; -use std::sync::Arc; - -use objc::declare::ClassDecl; -use objc::runtime::{BOOL, Class, Object, Sel, YES}; - -use { - CreationError, - Event, - LogicalPosition, - LogicalSize, - MouseCursor, - PhysicalPosition, - PhysicalSize, - WindowAttributes, - WindowEvent, - WindowId as RootEventId, -}; -use events::{Touch, TouchPhase}; -use window::MonitorId as RootMonitorId; - -mod ffi; -use self::ffi::{ - CFTimeInterval, - CFRunLoopRunInMode, - CGFloat, - CGPoint, - CGRect, - id, - JBLEN, - JmpBuf, - kCFRunLoopDefaultMode, - kCFRunLoopRunHandledSource, - longjmp, - nil, - NSString, - setjmp, - UIApplicationMain, - }; - -static mut JMPBUF: Option> = None; - -pub struct Window { - _events_queue: Arc>>, - delegate_state: Box, -} - -unsafe impl Send for Window {} -unsafe impl Sync for Window {} - -#[derive(Debug)] -struct DelegateState { - window: id, - controller: id, - view: id, - size: LogicalSize, - scale: f64, -} - -impl DelegateState { - fn new(window: id, controller: id, view: id, size: LogicalSize, scale: f64) -> DelegateState { - DelegateState { - window, - controller, - view, - size, - scale, - } - } -} - -impl Drop for DelegateState { - fn drop(&mut self) { - unsafe { - let _: () = msg_send![self.window, release]; - let _: () = msg_send![self.controller, release]; - let _: () = msg_send![self.view, release]; - } - } -} - -#[derive(Clone)] -pub struct MonitorId; - -impl fmt::Debug for MonitorId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - #[derive(Debug)] - struct MonitorId { - name: Option, - dimensions: PhysicalSize, - position: PhysicalPosition, - hidpi_factor: f64, - } - - let monitor_id_proxy = MonitorId { - name: self.get_name(), - dimensions: self.get_dimensions(), - position: self.get_position(), - hidpi_factor: self.get_hidpi_factor(), - }; - - monitor_id_proxy.fmt(f) - } -} - -impl MonitorId { - #[inline] - pub fn get_uiscreen(&self) -> id { - let class = class!(UIScreen); - unsafe { msg_send![class, mainScreen] } - } - - #[inline] - pub fn get_name(&self) -> Option { - Some("Primary".to_string()) - } - - #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { - let bounds: CGRect = unsafe { msg_send![self.get_uiscreen(), nativeBounds] }; - (bounds.size.width as f64, bounds.size.height as f64).into() - } - - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - // iOS assumes single screen - (0, 0).into() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - let scale: CGFloat = unsafe { msg_send![self.get_uiscreen(), nativeScale] }; - scale as f64 - } -} - -pub struct EventsLoop { - events_queue: Arc>>, -} - -#[derive(Clone)] -pub struct EventsLoopProxy; - -impl EventsLoop { - pub fn new() -> EventsLoop { - unsafe { - if !msg_send![class!(NSThread), isMainThread] { - panic!("`EventsLoop` can only be created on the main thread on iOS"); - } - } - EventsLoop { events_queue: Default::default() } - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - let mut rb = VecDeque::with_capacity(1); - rb.push_back(MonitorId); - rb - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId - } - - pub fn poll_events(&mut self, mut callback: F) - where F: FnMut(::Event) - { - if let Some(event) = self.events_queue.borrow_mut().pop_front() { - callback(event); - return; - } - - unsafe { - // jump hack, so we won't quit on willTerminate event before processing it - assert!(JMPBUF.is_some(), "`EventsLoop::poll_events` must be called after window creation on iOS"); - if setjmp(mem::transmute_copy(&mut JMPBUF)) != 0 { - if let Some(event) = self.events_queue.borrow_mut().pop_front() { - callback(event); - return; - } - } - } - - unsafe { - // run runloop - let seconds: CFTimeInterval = 0.000002; - while CFRunLoopRunInMode(kCFRunLoopDefaultMode, seconds, 1) == kCFRunLoopRunHandledSource {} - } - - if let Some(event) = self.events_queue.borrow_mut().pop_front() { - callback(event) - } - } - - pub fn run_forever(&mut self, mut callback: F) - where F: FnMut(::Event) -> ::ControlFlow, - { - // Yeah that's a very bad implementation. - loop { - let mut control_flow = ::ControlFlow::Continue; - self.poll_events(|e| { - if let ::ControlFlow::Break = callback(e) { - control_flow = ::ControlFlow::Break; - } - }); - if let ::ControlFlow::Break = control_flow { - break; - } - ::std::thread::sleep(::std::time::Duration::from_millis(5)); - } - } - - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy - } -} - -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), ::EventsLoopClosed> { - unimplemented!() - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WindowId; - -impl WindowId { - pub unsafe fn dummy() -> Self { - WindowId - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DeviceId; - -impl DeviceId { - pub unsafe fn dummy() -> Self { - DeviceId - } -} - -#[derive(Clone)] -pub struct PlatformSpecificWindowBuilderAttributes { - pub root_view_class: &'static Class, -} - -impl Default for PlatformSpecificWindowBuilderAttributes { - fn default() -> Self { - PlatformSpecificWindowBuilderAttributes { - root_view_class: class!(UIView), - } - } -} - -// TODO: AFAIK transparency is enabled by default on iOS, -// so to be consistent with other platforms we have to change that. -impl Window { - pub fn new( - ev: &EventsLoop, - _attributes: WindowAttributes, - pl_attributes: PlatformSpecificWindowBuilderAttributes, - ) -> Result { - unsafe { - debug_assert!(mem::size_of_val(&JMPBUF) == mem::size_of::>()); - assert!(mem::replace(&mut JMPBUF, Some(Box::new([0; JBLEN]))).is_none(), "Only one `Window` is supported on iOS"); - } - - unsafe { - if setjmp(mem::transmute_copy(&mut JMPBUF)) != 0 { - let app_class = class!(UIApplication); - let app: id = msg_send![app_class, sharedApplication]; - let delegate: id = msg_send![app, delegate]; - let state: *mut c_void = *(&*delegate).get_ivar("winitState"); - let mut delegate_state = Box::from_raw(state as *mut DelegateState); - let events_queue = &*ev.events_queue; - (&mut *delegate).set_ivar("eventsQueue", mem::transmute::<_, *mut c_void>(events_queue)); - - // easiest? way to get access to PlatformSpecificWindowBuilderAttributes to configure the view - let rect: CGRect = msg_send![MonitorId.get_uiscreen(), bounds]; - - let uiview_class = class!(UIView); - let root_view_class = pl_attributes.root_view_class; - let is_uiview: BOOL = msg_send![root_view_class, isSubclassOfClass:uiview_class]; - assert!(is_uiview == YES, "`root_view_class` must inherit from `UIView`"); - - delegate_state.view = msg_send![root_view_class, alloc]; - assert!(!delegate_state.view.is_null(), "Failed to create `UIView` instance"); - delegate_state.view = msg_send![delegate_state.view, initWithFrame:rect]; - assert!(!delegate_state.view.is_null(), "Failed to initialize `UIView` instance"); - - let _: () = msg_send![delegate_state.controller, setView:delegate_state.view]; - let _: () = msg_send![delegate_state.window, makeKeyAndVisible]; - - return Ok(Window { - _events_queue: ev.events_queue.clone(), - delegate_state, - }); - } - } - - create_delegate_class(); - start_app(); - - panic!("Couldn't create `UIApplication`!") - } - - #[inline] - pub fn get_uiwindow(&self) -> id { - self.delegate_state.window - } - - #[inline] - pub fn get_uiview(&self) -> id { - self.delegate_state.view - } - - #[inline] - pub fn set_title(&self, _title: &str) { - // N/A - } - - #[inline] - pub fn show(&self) { - // N/A - } - - #[inline] - pub fn hide(&self) { - // N/A - } - - #[inline] - pub fn get_position(&self) -> Option { - // N/A - None - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - // N/A - None - } - - #[inline] - pub fn set_position(&self, _position: LogicalPosition) { - // N/A - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - Some(self.delegate_state.size) - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - self.get_inner_size() - } - - #[inline] - pub fn set_inner_size(&self, _size: LogicalSize) { - // N/A - } - - #[inline] - pub fn set_min_dimensions(&self, _dimensions: Option) { - // N/A - } - - #[inline] - pub fn set_max_dimensions(&self, _dimensions: Option) { - // N/A - } - - #[inline] - pub fn set_resizable(&self, _resizable: bool) { - // N/A - } - - #[inline] - pub fn set_cursor(&self, _cursor: MouseCursor) { - // N/A - } - - #[inline] - pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> { - Err("Cursor grabbing is not possible on iOS.".to_owned()) - } - - #[inline] - pub fn hide_cursor(&self, _hide: bool) { - // N/A - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.delegate_state.scale - } - - #[inline] - pub fn set_cursor_position(&self, _position: LogicalPosition) -> Result<(), String> { - Err("Setting cursor position is not possible on iOS.".to_owned()) - } - - #[inline] - pub fn set_maximized(&self, _maximized: bool) { - // N/A - // iOS has single screen maximized apps so nothing to do - } - - #[inline] - pub fn set_fullscreen(&self, _monitor: Option) { - // N/A - // iOS has single screen maximized apps so nothing to do - } - - #[inline] - pub fn set_decorations(&self, _decorations: bool) { - // N/A - } - - #[inline] - pub fn set_always_on_top(&self, _always_on_top: bool) { - // N/A - } - - #[inline] - pub fn set_window_icon(&self, _icon: Option<::Icon>) { - // N/A - } - - #[inline] - pub fn set_ime_spot(&self, _logical_spot: LogicalPosition) { - // N/A - } - - #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - RootMonitorId { inner: MonitorId } - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - let mut rb = VecDeque::with_capacity(1); - rb.push_back(MonitorId); - rb - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId - } - - #[inline] - pub fn id(&self) -> WindowId { - WindowId - } -} - -fn create_delegate_class() { - extern fn did_finish_launching(this: &mut Object, _: Sel, _: id, _: id) -> BOOL { - let screen_class = class!(UIScreen); - let window_class = class!(UIWindow); - let controller_class = class!(UIViewController); - unsafe { - let main_screen: id = msg_send![screen_class, mainScreen]; - let bounds: CGRect = msg_send![main_screen, bounds]; - let scale: CGFloat = msg_send![main_screen, nativeScale]; - - let window: id = msg_send![window_class, alloc]; - let window: id = msg_send![window, initWithFrame:bounds.clone()]; - - let size = (bounds.size.width as f64, bounds.size.height as f64).into(); - - let view_controller: id = msg_send![controller_class, alloc]; - let view_controller: id = msg_send![view_controller, init]; - - let _: () = msg_send![window, setRootViewController:view_controller]; - - let state = Box::new(DelegateState::new(window, view_controller, ptr::null_mut(), size, scale as f64)); - let state_ptr: *mut DelegateState = mem::transmute(state); - this.set_ivar("winitState", state_ptr as *mut c_void); - - // The `UIView` is setup in `Window::new` which gets `longjmp`'ed to here. - // This makes it easier to configure the specific `UIView` type. - let _: () = msg_send![this, performSelector:sel!(postLaunch:) withObject:nil afterDelay:0.0]; - } - YES - } - - extern fn post_launch(_: &Object, _: Sel, _: id) { - unsafe { longjmp(mem::transmute_copy(&mut JMPBUF), 1); } - } - - extern fn did_become_active(this: &Object, _: Sel, _: id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - events_queue.borrow_mut().push_back(Event::WindowEvent { - window_id: RootEventId(WindowId), - event: WindowEvent::Focused(true), - }); - } - } - - extern fn will_resign_active(this: &Object, _: Sel, _: id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - events_queue.borrow_mut().push_back(Event::WindowEvent { - window_id: RootEventId(WindowId), - event: WindowEvent::Focused(false), - }); - } - } - - extern fn will_enter_foreground(this: &Object, _: Sel, _: id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - events_queue.borrow_mut().push_back(Event::Suspended(false)); - } - } - - extern fn did_enter_background(this: &Object, _: Sel, _: id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - events_queue.borrow_mut().push_back(Event::Suspended(true)); - } - } - - extern fn will_terminate(this: &Object, _: Sel, _: id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - // push event to the front to garantee that we'll process it - // immidiatly after jump - events_queue.borrow_mut().push_front(Event::WindowEvent { - window_id: RootEventId(WindowId), - event: WindowEvent::Destroyed, - }); - longjmp(mem::transmute_copy(&mut JMPBUF), 1); - } - } - - extern fn handle_touches(this: &Object, _: Sel, touches: id, _:id) { - unsafe { - let events_queue: *mut c_void = *this.get_ivar("eventsQueue"); - let events_queue = &*(events_queue as *const RefCell>); - - let touches_enum: id = msg_send![touches, objectEnumerator]; - - loop { - let touch: id = msg_send![touches_enum, nextObject]; - if touch == nil { - break - } - let location: CGPoint = msg_send![touch, locationInView:nil]; - let touch_id = touch as u64; - let phase: i32 = msg_send![touch, phase]; - - events_queue.borrow_mut().push_back(Event::WindowEvent { - window_id: RootEventId(WindowId), - event: WindowEvent::Touch(Touch { - device_id: DEVICE_ID, - id: touch_id, - location: (location.x as f64, location.y as f64).into(), - phase: match phase { - 0 => TouchPhase::Started, - 1 => TouchPhase::Moved, - // 2 is UITouchPhaseStationary and is not expected here - 3 => TouchPhase::Ended, - 4 => TouchPhase::Cancelled, - _ => panic!("unexpected touch phase: {:?}", phase) - } - }), - }); - } - } - } - - let ui_responder = class!(UIResponder); - let mut decl = ClassDecl::new("AppDelegate", ui_responder).expect("Failed to declare class `AppDelegate`"); - - unsafe { - decl.add_method(sel!(application:didFinishLaunchingWithOptions:), - did_finish_launching as extern fn(&mut Object, Sel, id, id) -> BOOL); - - decl.add_method(sel!(applicationDidBecomeActive:), - did_become_active as extern fn(&Object, Sel, id)); - - decl.add_method(sel!(applicationWillResignActive:), - will_resign_active as extern fn(&Object, Sel, id)); - - decl.add_method(sel!(applicationWillEnterForeground:), - will_enter_foreground as extern fn(&Object, Sel, id)); - - decl.add_method(sel!(applicationDidEnterBackground:), - did_enter_background as extern fn(&Object, Sel, id)); - - decl.add_method(sel!(applicationWillTerminate:), - will_terminate as extern fn(&Object, Sel, id)); - - - decl.add_method(sel!(touchesBegan:withEvent:), - handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id)); - - decl.add_method(sel!(touchesMoved:withEvent:), - handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id)); - - decl.add_method(sel!(touchesEnded:withEvent:), - handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id)); - - decl.add_method(sel!(touchesCancelled:withEvent:), - handle_touches as extern fn(this: &Object, _: Sel, _: id, _:id)); - - - decl.add_method(sel!(postLaunch:), - post_launch as extern fn(&Object, Sel, id)); - - decl.add_ivar::<*mut c_void>("winitState"); - decl.add_ivar::<*mut c_void>("eventsQueue"); - - decl.register(); - } -} - -#[inline] -fn start_app() { - unsafe { - UIApplicationMain(0, ptr::null(), nil, NSString::alloc(nil).init_str("AppDelegate")); - } -} - -// Constant device ID, to be removed when this backend is updated to report real device IDs. -const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId); diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/dlopen.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/dlopen.rs deleted file mode 100644 index d9ad3fb..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/dlopen.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -#![allow(dead_code)] - -use std::os::raw::{c_void, c_char, c_int}; - -pub const RTLD_LAZY: c_int = 0x001; -pub const RTLD_NOW: c_int = 0x002; - -#[link="dl"] -extern { - pub fn dlopen(filename: *const c_char, flag: c_int) -> *mut c_void; - pub fn dlerror() -> *mut c_char; - pub fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; - pub fn dlclose(handle: *mut c_void) -> c_int; -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/mod.rs deleted file mode 100644 index 1f88cdf..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/mod.rs +++ /dev/null @@ -1,542 +0,0 @@ -#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] - -use std::collections::VecDeque; -use std::{env, mem}; -use std::ffi::CStr; -use std::os::raw::*; -use std::sync::Arc; - -use parking_lot::Mutex; -use sctk::reexports::client::ConnectError; - -use { - CreationError, - EventsLoopClosed, - Icon, - MouseCursor, - ControlFlow, - WindowAttributes, -}; -use dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; -use window::MonitorId as RootMonitorId; -use self::x11::{XConnection, XError}; -use self::x11::ffi::XVisualInfo; -pub use self::x11::XNotSupported; - -mod dlopen; -pub mod wayland; -pub mod x11; - -/// Environment variable specifying which backend should be used on unix platform. -/// -/// Legal values are x11 and wayland. If this variable is set only the named backend -/// will be tried by winit. If it is not set, winit will try to connect to a wayland connection, -/// and if it fails will fallback on x11. -/// -/// If this variable is set with any other value, winit will panic. -const BACKEND_PREFERENCE_ENV_VAR: &str = "WINIT_UNIX_BACKEND"; - -#[derive(Clone, Default)] -pub struct PlatformSpecificWindowBuilderAttributes { - pub visual_infos: Option, - pub screen_id: Option, - pub resize_increments: Option<(u32, u32)>, - pub base_size: Option<(u32, u32)>, - pub class: Option<(String, String)>, - pub override_redirect: bool, - pub x11_window_type: x11::util::WindowType, - pub gtk_theme_variant: Option, - pub app_id: Option -} - -lazy_static!( - pub static ref X11_BACKEND: Mutex, XNotSupported>> = { - Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)) - }; -); - -pub enum Window { - X(x11::Window), - Wayland(wayland::Window), -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum WindowId { - X(x11::WindowId), - Wayland(wayland::WindowId), -} - -impl WindowId { - pub unsafe fn dummy() -> Self { - WindowId::X(x11::WindowId::dummy()) - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum DeviceId { - X(x11::DeviceId), - Wayland(wayland::DeviceId), -} - -impl DeviceId { - pub unsafe fn dummy() -> Self { - DeviceId::X(x11::DeviceId::dummy()) - } -} - -#[derive(Debug, Clone)] -pub enum MonitorId { - X(x11::MonitorId), - Wayland(wayland::MonitorId), -} - -impl MonitorId { - #[inline] - pub fn get_name(&self) -> Option { - match self { - &MonitorId::X(ref m) => m.get_name(), - &MonitorId::Wayland(ref m) => m.get_name(), - } - } - - #[inline] - pub fn get_native_identifier(&self) -> u32 { - match self { - &MonitorId::X(ref m) => m.get_native_identifier(), - &MonitorId::Wayland(ref m) => m.get_native_identifier(), - } - } - - #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { - match self { - &MonitorId::X(ref m) => m.get_dimensions(), - &MonitorId::Wayland(ref m) => m.get_dimensions(), - } - } - - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - match self { - &MonitorId::X(ref m) => m.get_position(), - &MonitorId::Wayland(ref m) => m.get_position(), - } - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - match self { - &MonitorId::X(ref m) => m.get_hidpi_factor(), - &MonitorId::Wayland(ref m) => m.get_hidpi_factor() as f64, - } - } -} - -impl Window { - #[inline] - pub fn new( - events_loop: &EventsLoop, - attribs: WindowAttributes, - pl_attribs: PlatformSpecificWindowBuilderAttributes, - ) -> Result { - match *events_loop { - EventsLoop::Wayland(ref events_loop) => { - wayland::Window::new(events_loop, attribs, pl_attribs).map(Window::Wayland) - }, - EventsLoop::X(ref events_loop) => { - x11::Window::new(events_loop, attribs, pl_attribs).map(Window::X) - }, - } - } - - #[inline] - pub fn id(&self) -> WindowId { - match self { - &Window::X(ref w) => WindowId::X(w.id()), - &Window::Wayland(ref w) => WindowId::Wayland(w.id()), - } - } - - #[inline] - pub fn set_title(&self, title: &str) { - match self { - &Window::X(ref w) => w.set_title(title), - &Window::Wayland(ref w) => w.set_title(title), - } - } - - #[inline] - pub fn show(&self) { - match self { - &Window::X(ref w) => w.show(), - &Window::Wayland(ref w) => w.show(), - } - } - - #[inline] - pub fn hide(&self) { - match self { - &Window::X(ref w) => w.hide(), - &Window::Wayland(ref w) => w.hide(), - } - } - - #[inline] - pub fn get_position(&self) -> Option { - match self { - &Window::X(ref w) => w.get_position(), - &Window::Wayland(ref w) => w.get_position(), - } - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - match self { - &Window::X(ref m) => m.get_inner_position(), - &Window::Wayland(ref m) => m.get_inner_position(), - } - } - - #[inline] - pub fn set_position(&self, position: LogicalPosition) { - match self { - &Window::X(ref w) => w.set_position(position), - &Window::Wayland(ref w) => w.set_position(position), - } - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - match self { - &Window::X(ref w) => w.get_inner_size(), - &Window::Wayland(ref w) => w.get_inner_size(), - } - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - match self { - &Window::X(ref w) => w.get_outer_size(), - &Window::Wayland(ref w) => w.get_outer_size(), - } - } - - #[inline] - pub fn set_inner_size(&self, size: LogicalSize) { - match self { - &Window::X(ref w) => w.set_inner_size(size), - &Window::Wayland(ref w) => w.set_inner_size(size), - } - } - - #[inline] - pub fn set_min_dimensions(&self, dimensions: Option) { - match self { - &Window::X(ref w) => w.set_min_dimensions(dimensions), - &Window::Wayland(ref w) => w.set_min_dimensions(dimensions), - } - } - - #[inline] - pub fn set_max_dimensions(&self, dimensions: Option) { - match self { - &Window::X(ref w) => w.set_max_dimensions(dimensions), - &Window::Wayland(ref w) => w.set_max_dimensions(dimensions), - } - } - - #[inline] - pub fn set_resizable(&self, resizable: bool) { - match self { - &Window::X(ref w) => w.set_resizable(resizable), - &Window::Wayland(ref w) => w.set_resizable(resizable), - } - } - - #[inline] - pub fn set_cursor(&self, cursor: MouseCursor) { - match self { - &Window::X(ref w) => w.set_cursor(cursor), - &Window::Wayland(ref w) => w.set_cursor(cursor) - } - } - - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - match self { - &Window::X(ref window) => window.grab_cursor(grab), - &Window::Wayland(ref window) => window.grab_cursor(grab), - } - } - - #[inline] - pub fn hide_cursor(&self, hide: bool) { - match self { - &Window::X(ref window) => window.hide_cursor(hide), - &Window::Wayland(ref window) => window.hide_cursor(hide), - } - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - match self { - &Window::X(ref w) => w.get_hidpi_factor(), - &Window::Wayland(ref w) => w.hidpi_factor() as f64, - } - } - - #[inline] - pub fn set_cursor_position(&self, position: LogicalPosition) -> Result<(), String> { - match self { - &Window::X(ref w) => w.set_cursor_position(position), - &Window::Wayland(ref w) => w.set_cursor_position(position), - } - } - - #[inline] - pub fn set_maximized(&self, maximized: bool) { - match self { - &Window::X(ref w) => w.set_maximized(maximized), - &Window::Wayland(ref w) => w.set_maximized(maximized), - } - } - - #[inline] - pub fn set_fullscreen(&self, monitor: Option) { - match self { - &Window::X(ref w) => w.set_fullscreen(monitor), - &Window::Wayland(ref w) => w.set_fullscreen(monitor) - } - } - - #[inline] - pub fn set_decorations(&self, decorations: bool) { - match self { - &Window::X(ref w) => w.set_decorations(decorations), - &Window::Wayland(ref w) => w.set_decorations(decorations) - } - } - - #[inline] - pub fn set_always_on_top(&self, always_on_top: bool) { - match self { - &Window::X(ref w) => w.set_always_on_top(always_on_top), - &Window::Wayland(_) => (), - } - } - - #[inline] - pub fn set_window_icon(&self, window_icon: Option) { - match self { - &Window::X(ref w) => w.set_window_icon(window_icon), - &Window::Wayland(_) => (), - } - } - - #[inline] - pub fn set_ime_spot(&self, position: LogicalPosition) { - match self { - &Window::X(ref w) => w.set_ime_spot(position), - &Window::Wayland(_) => (), - } - } - - #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - match self { - &Window::X(ref window) => RootMonitorId { inner: MonitorId::X(window.get_current_monitor()) }, - &Window::Wayland(ref window) => RootMonitorId { inner: MonitorId::Wayland(window.get_current_monitor()) }, - } - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - match self { - &Window::X(ref window) => window.get_available_monitors() - .into_iter() - .map(MonitorId::X) - .collect(), - &Window::Wayland(ref window) => window.get_available_monitors() - .into_iter() - .map(MonitorId::Wayland) - .collect(), - } - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - match self { - &Window::X(ref window) => MonitorId::X(window.get_primary_monitor()), - &Window::Wayland(ref window) => MonitorId::Wayland(window.get_primary_monitor()), - } - } -} - -unsafe extern "C" fn x_error_callback( - display: *mut x11::ffi::Display, - event: *mut x11::ffi::XErrorEvent, -) -> c_int { - let xconn_lock = X11_BACKEND.lock(); - if let Ok(ref xconn) = *xconn_lock { - let mut buf: [c_char; 1024] = mem::uninitialized(); - (xconn.xlib.XGetErrorText)( - display, - (*event).error_code as c_int, - buf.as_mut_ptr(), - buf.len() as c_int, - ); - let description = CStr::from_ptr(buf.as_ptr()).to_string_lossy(); - - let error = XError { - description: description.into_owned(), - error_code: (*event).error_code, - request_code: (*event).request_code, - minor_code: (*event).minor_code, - }; - - error!("X11 error: {:#?}", error); - - *xconn.latest_error.lock() = Some(error); - } - // Fun fact: this return value is completely ignored. - 0 -} - -pub enum EventsLoop { - Wayland(wayland::EventsLoop), - X(x11::EventsLoop) -} - -#[derive(Clone)] -pub enum EventsLoopProxy { - X(x11::EventsLoopProxy), - Wayland(wayland::EventsLoopProxy), -} - -impl EventsLoop { - pub fn new() -> EventsLoop { - if let Ok(env_var) = env::var(BACKEND_PREFERENCE_ENV_VAR) { - match env_var.as_str() { - "x11" => { - // TODO: propagate - return EventsLoop::new_x11().expect("Failed to initialize X11 backend"); - }, - "wayland" => { - return EventsLoop::new_wayland() - .expect("Failed to initialize Wayland backend"); - }, - _ => panic!( - "Unknown environment variable value for {}, try one of `x11`,`wayland`", - BACKEND_PREFERENCE_ENV_VAR, - ), - } - } - - let wayland_err = match EventsLoop::new_wayland() { - Ok(event_loop) => return event_loop, - Err(err) => err, - }; - - let x11_err = match EventsLoop::new_x11() { - Ok(event_loop) => return event_loop, - Err(err) => err, - }; - - let err_string = format!( - "Failed to initialize any backend! Wayland status: {:?} X11 status: {:?}", - wayland_err, - x11_err, - ); - panic!(err_string); - } - - pub fn new_wayland() -> Result { - wayland::EventsLoop::new() - .map(EventsLoop::Wayland) - } - - pub fn new_x11() -> Result { - X11_BACKEND - .lock() - .as_ref() - .map(Arc::clone) - .map(x11::EventsLoop::new) - .map(EventsLoop::X) - .map_err(|err| err.clone()) - } - - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - match *self { - EventsLoop::Wayland(ref evlp) => evlp - .get_available_monitors() - .into_iter() - .map(MonitorId::Wayland) - .collect(), - EventsLoop::X(ref evlp) => evlp - .x_connection() - .get_available_monitors() - .into_iter() - .map(MonitorId::X) - .collect(), - } - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - match *self { - EventsLoop::Wayland(ref evlp) => MonitorId::Wayland(evlp.get_primary_monitor()), - EventsLoop::X(ref evlp) => MonitorId::X(evlp.x_connection().get_primary_monitor()), - } - } - - pub fn create_proxy(&self) -> EventsLoopProxy { - match *self { - EventsLoop::Wayland(ref evlp) => EventsLoopProxy::Wayland(evlp.create_proxy()), - EventsLoop::X(ref evlp) => EventsLoopProxy::X(evlp.create_proxy()), - } - } - - pub fn poll_events(&mut self, callback: F) - where F: FnMut(::Event) - { - match *self { - EventsLoop::Wayland(ref mut evlp) => evlp.poll_events(callback), - EventsLoop::X(ref mut evlp) => evlp.poll_events(callback) - } - } - - pub fn run_forever(&mut self, callback: F) - where F: FnMut(::Event) -> ControlFlow - { - match *self { - EventsLoop::Wayland(ref mut evlp) => evlp.run_forever(callback), - EventsLoop::X(ref mut evlp) => evlp.run_forever(callback) - } - } - - #[inline] - pub fn is_wayland(&self) -> bool { - match *self { - EventsLoop::Wayland(_) => true, - EventsLoop::X(_) => false, - } - } - - #[inline] - pub fn x_connection(&self) -> Option<&Arc> { - match *self { - EventsLoop::Wayland(_) => None, - EventsLoop::X(ref ev) => Some(ev.x_connection()), - } - } -} - -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - match *self { - EventsLoopProxy::Wayland(ref proxy) => proxy.wakeup(), - EventsLoopProxy::X(ref proxy) => proxy.wakeup(), - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/event_loop.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/event_loop.rs deleted file mode 100644 index ee48348..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/event_loop.rs +++ /dev/null @@ -1,534 +0,0 @@ -use std::cell::RefCell; -use std::collections::VecDeque; -use std::fmt; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, Weak}; - -use {ControlFlow, EventsLoopClosed, PhysicalPosition, PhysicalSize}; - -use super::window::WindowStore; -use super::WindowId; - -use sctk::output::OutputMgr; -use sctk::reexports::client::protocol::{ - wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat, wl_touch, -}; -use sctk::reexports::client::{ConnectError, Display, EventQueue, GlobalEvent, Proxy}; -use sctk::Environment; - -use sctk::reexports::client::protocol::wl_display::RequestsTrait as DisplayRequests; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait; - -use ModifiersState; - -pub struct EventsLoopSink { - buffer: VecDeque<::Event>, -} - -impl EventsLoopSink { - pub fn new() -> EventsLoopSink { - EventsLoopSink { - buffer: VecDeque::new(), - } - } - - pub fn send_event(&mut self, evt: ::WindowEvent, wid: WindowId) { - let evt = ::Event::WindowEvent { - event: evt, - window_id: ::WindowId(::platform::WindowId::Wayland(wid)), - }; - self.buffer.push_back(evt); - } - - pub fn send_raw_event(&mut self, evt: ::Event) { - self.buffer.push_back(evt); - } - - fn empty_with(&mut self, callback: &mut F) - where - F: FnMut(::Event), - { - for evt in self.buffer.drain(..) { - callback(evt) - } - } -} - -pub struct EventsLoop { - // The Event Queue - pub evq: RefCell, - // our sink, shared with some handlers, buffering the events - sink: Arc>, - // Whether or not there is a pending `Awakened` event to be emitted. - pending_wakeup: Arc, - // The window store - pub store: Arc>, - // the env - pub env: Environment, - // a cleanup switch to prune dead windows - pub cleanup_needed: Arc>, - // The wayland display - pub display: Arc, - // The list of seats - pub seats: Arc)>>>, -} - -// A handle that can be sent across threads and used to wake up the `EventsLoop`. -// -// We should only try and wake up the `EventsLoop` if it still exists, so we hold Weak ptrs. -#[derive(Clone)] -pub struct EventsLoopProxy { - display: Weak, - pending_wakeup: Weak, -} - -impl EventsLoopProxy { - // Causes the `EventsLoop` to stop blocking on `run_forever` and emit an `Awakened` event. - // - // Returns `Err` if the associated `EventsLoop` no longer exists. - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - let display = self.display.upgrade(); - let wakeup = self.pending_wakeup.upgrade(); - match (display, wakeup) { - (Some(display), Some(wakeup)) => { - // Update the `EventsLoop`'s `pending_wakeup` flag. - wakeup.store(true, Ordering::Relaxed); - // Cause the `EventsLoop` to break from `dispatch` if it is currently blocked. - let _ = display.sync(|callback| callback.implement(|_, _| {}, ())); - display.flush().map_err(|_| EventsLoopClosed)?; - Ok(()) - } - _ => Err(EventsLoopClosed), - } - } -} - -impl EventsLoop { - pub fn new() -> Result { - let (display, mut event_queue) = Display::connect_to_env()?; - - let display = Arc::new(display); - let pending_wakeup = Arc::new(AtomicBool::new(false)); - let sink = Arc::new(Mutex::new(EventsLoopSink::new())); - let store = Arc::new(Mutex::new(WindowStore::new())); - let seats = Arc::new(Mutex::new(Vec::new())); - - let mut seat_manager = SeatManager { - sink: sink.clone(), - store: store.clone(), - seats: seats.clone(), - events_loop_proxy: EventsLoopProxy { - display: Arc::downgrade(&display), - pending_wakeup: Arc::downgrade(&pending_wakeup), - }, - }; - - let env = Environment::from_display_with_cb( - &display, - &mut event_queue, - move |event, registry| { - match event { - GlobalEvent::New { id, ref interface, version } => { - if interface == "wl_seat" { - seat_manager.add_seat(id, version, registry) - } - }, - GlobalEvent::Removed { id, ref interface } => { - if interface == "wl_seat" { - seat_manager.remove_seat(id) - } - }, - } - }, - ).unwrap(); - - Ok(EventsLoop { - display, - evq: RefCell::new(event_queue), - sink, - pending_wakeup, - store, - env, - cleanup_needed: Arc::new(Mutex::new(false)), - seats, - }) - } - - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy { - display: Arc::downgrade(&self.display), - pending_wakeup: Arc::downgrade(&self.pending_wakeup), - } - } - - pub fn poll_events(&mut self, mut callback: F) - where - F: FnMut(::Event), - { - // send pending events to the server - self.display.flush().expect("Wayland connection lost."); - - // dispatch any pre-buffered events - self.sink.lock().unwrap().empty_with(&mut callback); - - // try to read pending events - if let Some(h) = self.evq.get_mut().prepare_read() { - h.read_events().expect("Wayland connection lost."); - } - // dispatch wayland events - self.evq - .get_mut() - .dispatch_pending() - .expect("Wayland connection lost."); - self.post_dispatch_triggers(); - - // dispatch buffered events to client - self.sink.lock().unwrap().empty_with(&mut callback); - } - - pub fn run_forever(&mut self, mut callback: F) - where - F: FnMut(::Event) -> ControlFlow, - { - // send pending events to the server - self.display.flush().expect("Wayland connection lost."); - - // Check for control flow by wrapping the callback. - let control_flow = ::std::cell::Cell::new(ControlFlow::Continue); - let mut callback = |event| { - if let ControlFlow::Break = callback(event) { - control_flow.set(ControlFlow::Break); - } - }; - - // dispatch any pre-buffered events - self.post_dispatch_triggers(); - self.sink.lock().unwrap().empty_with(&mut callback); - - loop { - // dispatch events blocking if needed - self.evq - .get_mut() - .dispatch() - .expect("Wayland connection lost."); - self.post_dispatch_triggers(); - - // empty buffer of events - self.sink.lock().unwrap().empty_with(&mut callback); - - if let ControlFlow::Break = control_flow.get() { - break; - } - } - } - - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor(&self.env.outputs) - } - - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors(&self.env.outputs) - } -} - -/* - * Private EventsLoop Internals - */ - -impl EventsLoop { - fn post_dispatch_triggers(&mut self) { - let mut sink = self.sink.lock().unwrap(); - // process a possible pending wakeup call - if self.pending_wakeup.load(Ordering::Relaxed) { - sink.send_raw_event(::Event::Awakened); - self.pending_wakeup.store(false, Ordering::Relaxed); - } - // prune possible dead windows - { - let mut cleanup_needed = self.cleanup_needed.lock().unwrap(); - if *cleanup_needed { - let pruned = self.store.lock().unwrap().cleanup(); - *cleanup_needed = false; - for wid in pruned { - sink.send_event(::WindowEvent::Destroyed, wid); - } - } - } - // process pending resize/refresh - self.store.lock().unwrap().for_each( - |newsize, size, new_dpi, refresh, frame_refresh, closed, wid, frame| { - if let Some(frame) = frame { - if let Some((w, h)) = newsize { - frame.resize(w, h); - frame.refresh(); - let logical_size = ::LogicalSize::new(w as f64, h as f64); - sink.send_event(::WindowEvent::Resized(logical_size), wid); - *size = (w, h); - } else if frame_refresh { - frame.refresh(); - if !refresh { - frame.surface().commit() - } - } - } - if let Some(dpi) = new_dpi { - sink.send_event(::WindowEvent::HiDpiFactorChanged(dpi as f64), wid); - } - if refresh { - sink.send_event(::WindowEvent::Refresh, wid); - } - if closed { - sink.send_event(::WindowEvent::CloseRequested, wid); - } - }, - ) - } -} - -/* - * Wayland protocol implementations - */ - -struct SeatManager { - sink: Arc>, - store: Arc>, - seats: Arc)>>>, - events_loop_proxy: EventsLoopProxy, -} - -impl SeatManager { - fn add_seat(&mut self, id: u32, version: u32, registry: Proxy) { - use self::wl_registry::RequestsTrait as RegistryRequests; - use std::cmp::min; - - let mut seat_data = SeatData { - sink: self.sink.clone(), - store: self.store.clone(), - pointer: None, - keyboard: None, - touch: None, - events_loop_proxy: self.events_loop_proxy.clone(), - modifiers_tracker: Arc::new(Mutex::new(ModifiersState::default())), - }; - let seat = registry - .bind(min(version, 5), id, move |seat| { - seat.implement(move |event, seat| { - seat_data.receive(event, seat) - }, ()) - }) - .unwrap(); - self.store.lock().unwrap().new_seat(&seat); - self.seats.lock().unwrap().push((id, seat)); - } - - fn remove_seat(&mut self, id: u32) { - use self::wl_seat::RequestsTrait as SeatRequests; - let mut seats = self.seats.lock().unwrap(); - if let Some(idx) = seats.iter().position(|&(i, _)| i == id) { - let (_, seat) = seats.swap_remove(idx); - if seat.version() >= 5 { - seat.release(); - } - } - } -} - -struct SeatData { - sink: Arc>, - store: Arc>, - pointer: Option>, - keyboard: Option>, - touch: Option>, - events_loop_proxy: EventsLoopProxy, - modifiers_tracker: Arc>, -} - -impl SeatData { - fn receive(&mut self, evt: wl_seat::Event, seat: Proxy) { - match evt { - wl_seat::Event::Name { .. } => (), - wl_seat::Event::Capabilities { capabilities } => { - // create pointer if applicable - if capabilities.contains(wl_seat::Capability::Pointer) && self.pointer.is_none() { - self.pointer = Some(super::pointer::implement_pointer( - &seat, - self.sink.clone(), - self.store.clone(), - self.modifiers_tracker.clone(), - )) - } - // destroy pointer if applicable - if !capabilities.contains(wl_seat::Capability::Pointer) { - if let Some(pointer) = self.pointer.take() { - if pointer.version() >= 3 { - use self::wl_pointer::RequestsTrait; - pointer.release(); - } - } - } - // create keyboard if applicable - if capabilities.contains(wl_seat::Capability::Keyboard) && self.keyboard.is_none() { - self.keyboard = Some(super::keyboard::init_keyboard( - &seat, - self.sink.clone(), - self.events_loop_proxy.clone(), - self.modifiers_tracker.clone(), - )) - } - // destroy keyboard if applicable - if !capabilities.contains(wl_seat::Capability::Keyboard) { - if let Some(kbd) = self.keyboard.take() { - if kbd.version() >= 3 { - use self::wl_keyboard::RequestsTrait; - kbd.release(); - } - } - } - // create touch if applicable - if capabilities.contains(wl_seat::Capability::Touch) && self.touch.is_none() { - self.touch = Some(super::touch::implement_touch( - &seat, - self.sink.clone(), - self.store.clone(), - )) - } - // destroy touch if applicable - if !capabilities.contains(wl_seat::Capability::Touch) { - if let Some(touch) = self.touch.take() { - if touch.version() >= 3 { - use self::wl_touch::RequestsTrait; - touch.release(); - } - } - } - } - } - } -} - -impl Drop for SeatData { - fn drop(&mut self) { - if let Some(pointer) = self.pointer.take() { - if pointer.version() >= 3 { - use self::wl_pointer::RequestsTrait; - pointer.release(); - } - } - if let Some(kbd) = self.keyboard.take() { - if kbd.version() >= 3 { - use self::wl_keyboard::RequestsTrait; - kbd.release(); - } - } - if let Some(touch) = self.touch.take() { - if touch.version() >= 3 { - use self::wl_touch::RequestsTrait; - touch.release(); - } - } - } -} - -/* - * Monitor stuff - */ - -pub struct MonitorId { - pub(crate) proxy: Proxy, - pub(crate) mgr: OutputMgr, -} - -impl Clone for MonitorId { - fn clone(&self) -> MonitorId { - MonitorId { - proxy: self.proxy.clone(), - mgr: self.mgr.clone(), - } - } -} - -impl fmt::Debug for MonitorId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - #[derive(Debug)] - struct MonitorId { - name: Option, - native_identifier: u32, - dimensions: PhysicalSize, - position: PhysicalPosition, - hidpi_factor: i32, - } - - let monitor_id_proxy = MonitorId { - name: self.get_name(), - native_identifier: self.get_native_identifier(), - dimensions: self.get_dimensions(), - position: self.get_position(), - hidpi_factor: self.get_hidpi_factor(), - }; - - monitor_id_proxy.fmt(f) - } -} - -impl MonitorId { - pub fn get_name(&self) -> Option { - self.mgr.with_info(&self.proxy, |_, info| { - format!("{} ({})", info.model, info.make) - }) - } - - #[inline] - pub fn get_native_identifier(&self) -> u32 { - self.mgr.with_info(&self.proxy, |id, _| id).unwrap_or(0) - } - - pub fn get_dimensions(&self) -> PhysicalSize { - match self.mgr.with_info(&self.proxy, |_, info| { - info.modes - .iter() - .find(|m| m.is_current) - .map(|m| m.dimensions) - }) { - Some(Some((w, h))) => (w as u32, h as u32), - _ => (0, 0), - }.into() - } - - pub fn get_position(&self) -> PhysicalPosition { - self.mgr - .with_info(&self.proxy, |_, info| info.location) - .unwrap_or((0, 0)) - .into() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> i32 { - self.mgr - .with_info(&self.proxy, |_, info| info.scale_factor) - .unwrap_or(1) - } -} - -pub fn get_primary_monitor(outputs: &OutputMgr) -> MonitorId { - outputs.with_all(|list| { - if let Some(&(_, ref proxy, _)) = list.first() { - MonitorId { - proxy: proxy.clone(), - mgr: outputs.clone(), - } - } else { - panic!("No monitor is available.") - } - }) -} - -pub fn get_available_monitors(outputs: &OutputMgr) -> VecDeque { - outputs.with_all(|list| { - list.iter() - .map(|&(_, ref proxy, _)| MonitorId { - proxy: proxy.clone(), - mgr: outputs.clone(), - }) - .collect() - }) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/pointer.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/pointer.rs deleted file mode 100644 index ebe9d10..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/pointer.rs +++ /dev/null @@ -1,189 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use {ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent}; -use events::ModifiersState; - -use super::DeviceId; -use super::event_loop::EventsLoopSink; -use super::window::WindowStore; - -use sctk::reexports::client::Proxy; -use sctk::reexports::client::protocol::wl_pointer::{self, Event as PtrEvent, WlPointer}; -use sctk::reexports::client::protocol::wl_seat; -use sctk::reexports::client::protocol::wl_seat::RequestsTrait as SeatRequests; - -pub fn implement_pointer( - seat: &Proxy, - sink: Arc>, - store: Arc>, - modifiers_tracker: Arc>, -) -> Proxy { - let mut mouse_focus = None; - let mut axis_buffer = None; - let mut axis_discrete_buffer = None; - let mut axis_state = TouchPhase::Ended; - - seat.get_pointer(|pointer| { - pointer.implement(move |evt, pointer| { - let mut sink = sink.lock().unwrap(); - let store = store.lock().unwrap(); - match evt { - PtrEvent::Enter { - surface, - surface_x, - surface_y, - .. - } => { - let wid = store.find_wid(&surface); - if let Some(wid) = wid { - mouse_focus = Some(wid); - sink.send_event( - WindowEvent::CursorEntered { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - }, - wid, - ); - sink.send_event( - WindowEvent::CursorMoved { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - position: (surface_x, surface_y).into(), - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } - } - PtrEvent::Leave { surface, .. } => { - mouse_focus = None; - let wid = store.find_wid(&surface); - if let Some(wid) = wid { - sink.send_event( - WindowEvent::CursorLeft { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - }, - wid, - ); - } - } - PtrEvent::Motion { - surface_x, - surface_y, - .. - } => { - if let Some(wid) = mouse_focus { - sink.send_event( - WindowEvent::CursorMoved { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - position: (surface_x, surface_y).into(), - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } - } - PtrEvent::Button { button, state, .. } => { - if let Some(wid) = mouse_focus { - let state = match state { - wl_pointer::ButtonState::Pressed => ElementState::Pressed, - wl_pointer::ButtonState::Released => ElementState::Released, - }; - let button = match button { - 0x110 => MouseButton::Left, - 0x111 => MouseButton::Right, - 0x112 => MouseButton::Middle, - // TODO figure out the translation ? - _ => return, - }; - sink.send_event( - WindowEvent::MouseInput { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - state: state, - button: button, - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } - } - PtrEvent::Axis { axis, value, .. } => { - if let Some(wid) = mouse_focus { - if pointer.version() < 5 { - let (mut x, mut y) = (0.0, 0.0); - // old seat compatibility - match axis { - // wayland vertical sign convention is the inverse of winit - wl_pointer::Axis::VerticalScroll => y -= value as f32, - wl_pointer::Axis::HorizontalScroll => x += value as f32, - } - sink.send_event( - WindowEvent::MouseWheel { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - delta: MouseScrollDelta::PixelDelta((x as f64, y as f64).into()), - phase: TouchPhase::Moved, - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } else { - let (mut x, mut y) = axis_buffer.unwrap_or((0.0, 0.0)); - match axis { - // wayland vertical sign convention is the inverse of winit - wl_pointer::Axis::VerticalScroll => y -= value as f32, - wl_pointer::Axis::HorizontalScroll => x += value as f32, - } - axis_buffer = Some((x, y)); - axis_state = match axis_state { - TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved, - _ => TouchPhase::Started, - } - } - } - } - PtrEvent::Frame => { - let axis_buffer = axis_buffer.take(); - let axis_discrete_buffer = axis_discrete_buffer.take(); - if let Some(wid) = mouse_focus { - if let Some((x, y)) = axis_discrete_buffer { - sink.send_event( - WindowEvent::MouseWheel { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - delta: MouseScrollDelta::LineDelta(x as f32, y as f32), - phase: axis_state, - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } else if let Some((x, y)) = axis_buffer { - sink.send_event( - WindowEvent::MouseWheel { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - delta: MouseScrollDelta::PixelDelta((x as f64, y as f64).into()), - phase: axis_state, - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - wid, - ); - } - } - } - PtrEvent::AxisSource { .. } => (), - PtrEvent::AxisStop { .. } => { - axis_state = TouchPhase::Ended; - } - PtrEvent::AxisDiscrete { axis, discrete } => { - let (mut x, mut y) = axis_discrete_buffer.unwrap_or((0, 0)); - match axis { - // wayland vertical sign convention is the inverse of winit - wl_pointer::Axis::VerticalScroll => y -= discrete, - wl_pointer::Axis::HorizontalScroll => x += discrete, - } - axis_discrete_buffer = Some((x, y)); - axis_state = match axis_state { - TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved, - _ => TouchPhase::Started, - } - } - } - }, ()) - }).unwrap() -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/touch.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/touch.rs deleted file mode 100644 index e9e28d6..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/touch.rs +++ /dev/null @@ -1,97 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use {TouchPhase, WindowEvent}; - -use super::{DeviceId, WindowId}; -use super::event_loop::EventsLoopSink; -use super::window::WindowStore; - -use sctk::reexports::client::Proxy; -use sctk::reexports::client::protocol::wl_touch::{Event as TouchEvent, WlTouch}; -use sctk::reexports::client::protocol::wl_seat; -use sctk::reexports::client::protocol::wl_seat::RequestsTrait as SeatRequests; - -struct TouchPoint { - wid: WindowId, - location: (f64, f64), - id: i32, -} - -pub(crate) fn implement_touch( - seat: &Proxy, - sink: Arc>, - store: Arc>, -) -> Proxy { - let mut pending_ids = Vec::new(); - seat.get_touch(|touch| { - touch.implement(move |evt, _| { - let mut sink = sink.lock().unwrap(); - let store = store.lock().unwrap(); - match evt { - TouchEvent::Down { - surface, id, x, y, .. - } => { - let wid = store.find_wid(&surface); - if let Some(wid) = wid { - sink.send_event( - WindowEvent::Touch(::Touch { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - phase: TouchPhase::Started, - location: (x, y).into(), - id: id as u64, - }), - wid, - ); - pending_ids.push(TouchPoint { - wid: wid, - location: (x, y), - id: id, - }); - } - } - TouchEvent::Up { id, .. } => { - let idx = pending_ids.iter().position(|p| p.id == id); - if let Some(idx) = idx { - let pt = pending_ids.remove(idx); - sink.send_event( - WindowEvent::Touch(::Touch { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - phase: TouchPhase::Ended, - location: pt.location.into(), - id: id as u64, - }), - pt.wid, - ); - } - } - TouchEvent::Motion { id, x, y, .. } => { - let pt = pending_ids.iter_mut().find(|p| p.id == id); - if let Some(pt) = pt { - pt.location = (x, y); - sink.send_event( - WindowEvent::Touch(::Touch { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - phase: TouchPhase::Moved, - location: (x, y).into(), - id: id as u64, - }), - pt.wid, - ); - } - } - TouchEvent::Frame => (), - TouchEvent::Cancel => for pt in pending_ids.drain(..) { - sink.send_event( - WindowEvent::Touch(::Touch { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - phase: TouchPhase::Cancelled, - location: pt.location.into(), - id: pt.id as u64, - }), - pt.wid, - ); - }, - } - }, ()) - }).unwrap() -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/window.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/window.rs deleted file mode 100644 index 62a74be..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/window.rs +++ /dev/null @@ -1,383 +0,0 @@ -use std::collections::VecDeque; -use std::sync::{Arc, Mutex, Weak}; - -use {CreationError, MouseCursor, WindowAttributes}; -use dpi::{LogicalPosition, LogicalSize}; -use platform::{MonitorId as PlatformMonitorId, PlatformSpecificWindowBuilderAttributes as PlAttributes}; -use window::MonitorId as RootMonitorId; - -use sctk::surface::{get_dpi_factor, get_outputs}; -use sctk::window::{ConceptFrame, Event as WEvent, Window as SWindow}; -use sctk::reexports::client::{Display, Proxy}; -use sctk::reexports::client::protocol::{wl_seat, wl_surface}; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests; -use sctk::output::OutputMgr; - -use super::{make_wid, EventsLoop, MonitorId, WindowId}; -use platform::platform::wayland::event_loop::{get_available_monitors, get_primary_monitor}; - -pub struct Window { - surface: Proxy, - frame: Arc>>, - outputs: OutputMgr, // Access to info for all monitors - size: Arc>, - kill_switch: (Arc>, Arc>), - display: Arc, - need_frame_refresh: Arc>, -} - -impl Window { - pub fn new(evlp: &EventsLoop, attributes: WindowAttributes, pl_attribs: PlAttributes) -> Result { - let (width, height) = attributes.dimensions.map(Into::into).unwrap_or((800, 600)); - // Create the window - let size = Arc::new(Mutex::new((width, height))); - - let window_store = evlp.store.clone(); - let surface = evlp.env.create_surface(move |dpi, surface| { - window_store.lock().unwrap().dpi_change(&surface, dpi); - surface.set_buffer_scale(dpi); - }); - - let window_store = evlp.store.clone(); - let my_surface = surface.clone(); - let mut frame = SWindow::::init_from_env( - &evlp.env, - surface.clone(), - (width, height), - move |event| match event { - WEvent::Configure { new_size, .. } => { - let mut store = window_store.lock().unwrap(); - for window in &mut store.windows { - if window.surface.equals(&my_surface) { - window.newsize = new_size; - window.need_refresh = true; - *(window.need_frame_refresh.lock().unwrap()) = true; - return; - } - } - } - WEvent::Refresh => { - let store = window_store.lock().unwrap(); - for window in &store.windows { - if window.surface.equals(&my_surface) { - *(window.need_frame_refresh.lock().unwrap()) = true; - return; - } - } - } - WEvent::Close => { - let mut store = window_store.lock().unwrap(); - for window in &mut store.windows { - if window.surface.equals(&my_surface) { - window.closed = true; - return; - } - } - } - }, - ).unwrap(); - - if let Some(app_id) = pl_attribs.app_id { - frame.set_app_id(app_id); - } - - for &(_, ref seat) in evlp.seats.lock().unwrap().iter() { - frame.new_seat(seat); - } - - // Check for fullscreen requirements - if let Some(RootMonitorId { - inner: PlatformMonitorId::Wayland(ref monitor_id), - }) = attributes.fullscreen - { - frame.set_fullscreen(Some(&monitor_id.proxy)); - } else if attributes.maximized { - frame.set_maximized(); - } - - frame.set_resizable(attributes.resizable); - - // set decorations - frame.set_decorate(attributes.decorations); - - // min-max dimensions - frame.set_min_size(attributes.min_dimensions.map(Into::into)); - frame.set_max_size(attributes.max_dimensions.map(Into::into)); - - let kill_switch = Arc::new(Mutex::new(false)); - let need_frame_refresh = Arc::new(Mutex::new(true)); - let frame = Arc::new(Mutex::new(frame)); - - evlp.store.lock().unwrap().windows.push(InternalWindow { - closed: false, - newsize: None, - size: size.clone(), - need_refresh: false, - need_frame_refresh: need_frame_refresh.clone(), - surface: surface.clone(), - kill_switch: kill_switch.clone(), - frame: Arc::downgrade(&frame), - current_dpi: 1, - new_dpi: None, - }); - evlp.evq.borrow_mut().sync_roundtrip().unwrap(); - - Ok(Window { - display: evlp.display.clone(), - surface: surface, - frame: frame, - outputs: evlp.env.outputs.clone(), - size: size, - kill_switch: (kill_switch, evlp.cleanup_needed.clone()), - need_frame_refresh: need_frame_refresh, - }) - } - - #[inline] - pub fn id(&self) -> WindowId { - make_wid(&self.surface) - } - - pub fn set_title(&self, title: &str) { - self.frame.lock().unwrap().set_title(title.into()); - } - - #[inline] - pub fn show(&self) { - // TODO - } - - #[inline] - pub fn hide(&self) { - // TODO - } - - #[inline] - pub fn get_position(&self) -> Option { - // Not possible with wayland - None - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - // Not possible with wayland - None - } - - #[inline] - pub fn set_position(&self, _pos: LogicalPosition) { - // Not possible with wayland - } - - pub fn get_inner_size(&self) -> Option { - Some(self.size.lock().unwrap().clone().into()) - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - let (w, h) = self.size.lock().unwrap().clone(); - // let (w, h) = super::wayland_window::add_borders(w as i32, h as i32); - Some((w, h).into()) - } - - #[inline] - // NOTE: This will only resize the borders, the contents must be updated by the user - pub fn set_inner_size(&self, size: LogicalSize) { - let (w, h) = size.into(); - self.frame.lock().unwrap().resize(w, h); - *(self.size.lock().unwrap()) = (w, h); - } - - #[inline] - pub fn set_min_dimensions(&self, dimensions: Option) { - self.frame.lock().unwrap().set_min_size(dimensions.map(Into::into)); - } - - #[inline] - pub fn set_max_dimensions(&self, dimensions: Option) { - self.frame.lock().unwrap().set_max_size(dimensions.map(Into::into)); - } - - #[inline] - pub fn set_resizable(&self, resizable: bool) { - self.frame.lock().unwrap().set_resizable(resizable); - } - - #[inline] - pub fn hidpi_factor(&self) -> i32 { - get_dpi_factor(&self.surface) - } - - pub fn set_decorations(&self, decorate: bool) { - self.frame.lock().unwrap().set_decorate(decorate); - *(self.need_frame_refresh.lock().unwrap()) = true; - } - - pub fn set_maximized(&self, maximized: bool) { - if maximized { - self.frame.lock().unwrap().set_maximized(); - } else { - self.frame.lock().unwrap().unset_maximized(); - } - } - - pub fn set_fullscreen(&self, monitor: Option) { - if let Some(RootMonitorId { - inner: PlatformMonitorId::Wayland(ref monitor_id), - }) = monitor - { - self.frame - .lock() - .unwrap() - .set_fullscreen(Some(&monitor_id.proxy)); - } else { - self.frame.lock().unwrap().unset_fullscreen(); - } - } - - #[inline] - pub fn set_cursor(&self, _cursor: MouseCursor) { - // TODO - } - - #[inline] - pub fn hide_cursor(&self, _hide: bool) { - // TODO: This isn't possible on Wayland yet - } - - #[inline] - pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> { - Err("Cursor grabbing is not yet possible on Wayland.".to_owned()) - } - - #[inline] - pub fn set_cursor_position(&self, _pos: LogicalPosition) -> Result<(), String> { - Err("Setting the cursor position is not yet possible on Wayland.".to_owned()) - } - - pub fn get_display(&self) -> &Display { - &*self.display - } - - pub fn get_surface(&self) -> &Proxy { - &self.surface - } - - pub fn get_current_monitor(&self) -> MonitorId { - let output = get_outputs(&self.surface).last().unwrap().clone(); - MonitorId { - proxy: output, - mgr: self.outputs.clone(), - } - } - - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors(&self.outputs) - } - - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor(&self.outputs) - } -} - -impl Drop for Window { - fn drop(&mut self) { - *(self.kill_switch.0.lock().unwrap()) = true; - *(self.kill_switch.1.lock().unwrap()) = true; - } -} - -/* - * Internal store for windows - */ - -struct InternalWindow { - surface: Proxy, - newsize: Option<(u32, u32)>, - size: Arc>, - need_refresh: bool, - need_frame_refresh: Arc>, - closed: bool, - kill_switch: Arc>, - frame: Weak>>, - current_dpi: i32, - new_dpi: Option, -} - -pub struct WindowStore { - windows: Vec, -} - -impl WindowStore { - pub fn new() -> WindowStore { - WindowStore { - windows: Vec::new(), - } - } - - pub fn find_wid(&self, surface: &Proxy) -> Option { - for window in &self.windows { - if surface.equals(&window.surface) { - return Some(make_wid(surface)); - } - } - None - } - - pub fn cleanup(&mut self) -> Vec { - let mut pruned = Vec::new(); - self.windows.retain(|w| { - if *w.kill_switch.lock().unwrap() { - // window is dead, cleanup - pruned.push(make_wid(&w.surface)); - w.surface.destroy(); - false - } else { - true - } - }); - pruned - } - - pub fn new_seat(&self, seat: &Proxy) { - for window in &self.windows { - if let Some(w) = window.frame.upgrade() { - w.lock().unwrap().new_seat(seat); - } - } - } - - fn dpi_change(&mut self, surface: &Proxy, new: i32) { - for window in &mut self.windows { - if surface.equals(&window.surface) { - window.new_dpi = Some(new); - } - } - } - - pub fn for_each(&mut self, mut f: F) - where - F: FnMut(Option<(u32, u32)>, &mut (u32, u32), Option, bool, bool, bool, WindowId, Option<&mut SWindow>), - { - for window in &mut self.windows { - let opt_arc = window.frame.upgrade(); - let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap()); - f( - window.newsize.take(), - &mut *(window.size.lock().unwrap()), - window.new_dpi, - window.need_refresh, - ::std::mem::replace(&mut *window.need_frame_refresh.lock().unwrap(), false), - window.closed, - make_wid(&window.surface), - opt_mutex_lock.as_mut().map(|m| &mut **m), - ); - if let Some(dpi) = window.new_dpi.take() { - window.current_dpi = dpi; - } - window.need_refresh = false; - // avoid re-spamming the event - window.closed = false; - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/events.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/events.rs deleted file mode 100644 index 037ee4c..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/events.rs +++ /dev/null @@ -1,1008 +0,0 @@ -use {events, libc}; -use super::ffi; -use VirtualKeyCode; - -pub fn keysym_to_element(keysym: libc::c_uint) -> Option { - Some(match keysym { - ffi::XK_BackSpace => events::VirtualKeyCode::Back, - ffi::XK_Tab => events::VirtualKeyCode::Tab, - //ffi::XK_Linefeed => events::VirtualKeyCode::Linefeed, - //ffi::XK_Clear => events::VirtualKeyCode::Clear, - ffi::XK_Return => events::VirtualKeyCode::Return, - //ffi::XK_Pause => events::VirtualKeyCode::Pause, - //ffi::XK_Scroll_Lock => events::VirtualKeyCode::Scroll_lock, - //ffi::XK_Sys_Req => events::VirtualKeyCode::Sys_req, - ffi::XK_Escape => events::VirtualKeyCode::Escape, - ffi::XK_Delete => events::VirtualKeyCode::Delete, - ffi::XK_Multi_key => events::VirtualKeyCode::Compose, - //ffi::XK_Kanji => events::VirtualKeyCode::Kanji, - //ffi::XK_Muhenkan => events::VirtualKeyCode::Muhenkan, - //ffi::XK_Henkan_Mode => events::VirtualKeyCode::Henkan_mode, - //ffi::XK_Henkan => events::VirtualKeyCode::Henkan, - //ffi::XK_Romaji => events::VirtualKeyCode::Romaji, - //ffi::XK_Hiragana => events::VirtualKeyCode::Hiragana, - //ffi::XK_Katakana => events::VirtualKeyCode::Katakana, - //ffi::XK_Hiragana_Katakana => events::VirtualKeyCode::Hiragana_katakana, - //ffi::XK_Zenkaku => events::VirtualKeyCode::Zenkaku, - //ffi::XK_Hankaku => events::VirtualKeyCode::Hankaku, - //ffi::XK_Zenkaku_Hankaku => events::VirtualKeyCode::Zenkaku_hankaku, - //ffi::XK_Touroku => events::VirtualKeyCode::Touroku, - //ffi::XK_Massyo => events::VirtualKeyCode::Massyo, - //ffi::XK_Kana_Lock => events::VirtualKeyCode::Kana_lock, - //ffi::XK_Kana_Shift => events::VirtualKeyCode::Kana_shift, - //ffi::XK_Eisu_Shift => events::VirtualKeyCode::Eisu_shift, - //ffi::XK_Eisu_toggle => events::VirtualKeyCode::Eisu_toggle, - ffi::XK_Home => events::VirtualKeyCode::Home, - ffi::XK_Left => events::VirtualKeyCode::Left, - ffi::XK_Up => events::VirtualKeyCode::Up, - ffi::XK_Right => events::VirtualKeyCode::Right, - ffi::XK_Down => events::VirtualKeyCode::Down, - //ffi::XK_Prior => events::VirtualKeyCode::Prior, - ffi::XK_Page_Up => events::VirtualKeyCode::PageUp, - //ffi::XK_Next => events::VirtualKeyCode::Next, - ffi::XK_Page_Down => events::VirtualKeyCode::PageDown, - ffi::XK_End => events::VirtualKeyCode::End, - //ffi::XK_Begin => events::VirtualKeyCode::Begin, - //ffi::XK_Win_L => events::VirtualKeyCode::Win_l, - //ffi::XK_Win_R => events::VirtualKeyCode::Win_r, - //ffi::XK_App => events::VirtualKeyCode::App, - //ffi::XK_Select => events::VirtualKeyCode::Select, - //ffi::XK_Print => events::VirtualKeyCode::Print, - //ffi::XK_Execute => events::VirtualKeyCode::Execute, - ffi::XK_Insert => events::VirtualKeyCode::Insert, - //ffi::XK_Undo => events::VirtualKeyCode::Undo, - //ffi::XK_Redo => events::VirtualKeyCode::Redo, - //ffi::XK_Menu => events::VirtualKeyCode::Menu, - //ffi::XK_Find => events::VirtualKeyCode::Find, - //ffi::XK_Cancel => events::VirtualKeyCode::Cancel, - //ffi::XK_Help => events::VirtualKeyCode::Help, - //ffi::XK_Break => events::VirtualKeyCode::Break, - //ffi::XK_Mode_switch => events::VirtualKeyCode::Mode_switch, - //ffi::XK_script_switch => events::VirtualKeyCode::Script_switch, - //ffi::XK_Num_Lock => events::VirtualKeyCode::Num_lock, - //ffi::XK_KP_Space => events::VirtualKeyCode::Kp_space, - //ffi::XK_KP_Tab => events::VirtualKeyCode::Kp_tab, - //ffi::XK_KP_Enter => events::VirtualKeyCode::Kp_enter, - //ffi::XK_KP_F1 => events::VirtualKeyCode::Kp_f1, - //ffi::XK_KP_F2 => events::VirtualKeyCode::Kp_f2, - //ffi::XK_KP_F3 => events::VirtualKeyCode::Kp_f3, - //ffi::XK_KP_F4 => events::VirtualKeyCode::Kp_f4, - ffi::XK_KP_Home => events::VirtualKeyCode::Home, - ffi::XK_KP_Left => events::VirtualKeyCode::Left, - ffi::XK_KP_Up => events::VirtualKeyCode::Up, - ffi::XK_KP_Right => events::VirtualKeyCode::Right, - ffi::XK_KP_Down => events::VirtualKeyCode::Down, - //ffi::XK_KP_Prior => events::VirtualKeyCode::Kp_prior, - ffi::XK_KP_Page_Up => events::VirtualKeyCode::PageUp, - //ffi::XK_KP_Next => events::VirtualKeyCode::Kp_next, - ffi::XK_KP_Page_Down => events::VirtualKeyCode::PageDown, - ffi::XK_KP_End => events::VirtualKeyCode::End, - //ffi::XK_KP_Begin => events::VirtualKeyCode::Kp_begin, - ffi::XK_KP_Insert => events::VirtualKeyCode::Insert, - ffi::XK_KP_Delete => events::VirtualKeyCode::Delete, - ffi::XK_KP_Equal => events::VirtualKeyCode::NumpadEquals, - //ffi::XK_KP_Multiply => events::VirtualKeyCode::NumpadMultiply, - //ffi::XK_KP_Add => events::VirtualKeyCode::NumpadAdd, - //ffi::XK_KP_Separator => events::VirtualKeyCode::Kp_separator, - //ffi::XK_KP_Subtract => events::VirtualKeyCode::NumpadSubtract, - //ffi::XK_KP_Decimal => events::VirtualKeyCode::Kp_decimal, - //ffi::XK_KP_Divide => events::VirtualKeyCode::NumpadDivide, - ffi::XK_KP_0 => events::VirtualKeyCode::Numpad0, - ffi::XK_KP_1 => events::VirtualKeyCode::Numpad1, - ffi::XK_KP_2 => events::VirtualKeyCode::Numpad2, - ffi::XK_KP_3 => events::VirtualKeyCode::Numpad3, - ffi::XK_KP_4 => events::VirtualKeyCode::Numpad4, - ffi::XK_KP_5 => events::VirtualKeyCode::Numpad5, - ffi::XK_KP_6 => events::VirtualKeyCode::Numpad6, - ffi::XK_KP_7 => events::VirtualKeyCode::Numpad7, - ffi::XK_KP_8 => events::VirtualKeyCode::Numpad8, - ffi::XK_KP_9 => events::VirtualKeyCode::Numpad9, - ffi::XK_F1 => events::VirtualKeyCode::F1, - ffi::XK_F2 => events::VirtualKeyCode::F2, - ffi::XK_F3 => events::VirtualKeyCode::F3, - ffi::XK_F4 => events::VirtualKeyCode::F4, - ffi::XK_F5 => events::VirtualKeyCode::F5, - ffi::XK_F6 => events::VirtualKeyCode::F6, - ffi::XK_F7 => events::VirtualKeyCode::F7, - ffi::XK_F8 => events::VirtualKeyCode::F8, - ffi::XK_F9 => events::VirtualKeyCode::F9, - ffi::XK_F10 => events::VirtualKeyCode::F10, - ffi::XK_F11 => events::VirtualKeyCode::F11, - //ffi::XK_L1 => events::VirtualKeyCode::L1, - ffi::XK_F12 => events::VirtualKeyCode::F12, - //ffi::XK_L2 => events::VirtualKeyCode::L2, - ffi::XK_F13 => events::VirtualKeyCode::F13, - //ffi::XK_L3 => events::VirtualKeyCode::L3, - ffi::XK_F14 => events::VirtualKeyCode::F14, - //ffi::XK_L4 => events::VirtualKeyCode::L4, - ffi::XK_F15 => events::VirtualKeyCode::F15, - //ffi::XK_L5 => events::VirtualKeyCode::L5, - ffi::XK_F16 => events::VirtualKeyCode::F16, - //ffi::XK_L6 => events::VirtualKeyCode::L6, - ffi::XK_F17 => events::VirtualKeyCode::F17, - //ffi::XK_L7 => events::VirtualKeyCode::L7, - ffi::XK_F18 => events::VirtualKeyCode::F18, - //ffi::XK_L8 => events::VirtualKeyCode::L8, - ffi::XK_F19 => events::VirtualKeyCode::F19, - //ffi::XK_L9 => events::VirtualKeyCode::L9, - ffi::XK_F20 => events::VirtualKeyCode::F20, - //ffi::XK_L10 => events::VirtualKeyCode::L10, - ffi::XK_F21 => events::VirtualKeyCode::F21, - //ffi::XK_R1 => events::VirtualKeyCode::R1, - ffi::XK_F22 => events::VirtualKeyCode::F22, - //ffi::XK_R2 => events::VirtualKeyCode::R2, - ffi::XK_F23 => events::VirtualKeyCode::F23, - //ffi::XK_R3 => events::VirtualKeyCode::R3, - ffi::XK_F24 => events::VirtualKeyCode::F24, - //ffi::XK_R4 => events::VirtualKeyCode::R4, - //ffi::XK_F25 => events::VirtualKeyCode::F25, - //ffi::XK_R5 => events::VirtualKeyCode::R5, - //ffi::XK_F26 => events::VirtualKeyCode::F26, - //ffi::XK_R6 => events::VirtualKeyCode::R6, - //ffi::XK_F27 => events::VirtualKeyCode::F27, - //ffi::XK_R7 => events::VirtualKeyCode::R7, - //ffi::XK_F28 => events::VirtualKeyCode::F28, - //ffi::XK_R8 => events::VirtualKeyCode::R8, - //ffi::XK_F29 => events::VirtualKeyCode::F29, - //ffi::XK_R9 => events::VirtualKeyCode::R9, - //ffi::XK_F30 => events::VirtualKeyCode::F30, - //ffi::XK_R10 => events::VirtualKeyCode::R10, - //ffi::XK_F31 => events::VirtualKeyCode::F31, - //ffi::XK_R11 => events::VirtualKeyCode::R11, - //ffi::XK_F32 => events::VirtualKeyCode::F32, - //ffi::XK_R12 => events::VirtualKeyCode::R12, - //ffi::XK_F33 => events::VirtualKeyCode::F33, - //ffi::XK_R13 => events::VirtualKeyCode::R13, - //ffi::XK_F34 => events::VirtualKeyCode::F34, - //ffi::XK_R14 => events::VirtualKeyCode::R14, - //ffi::XK_F35 => events::VirtualKeyCode::F35, - //ffi::XK_R15 => events::VirtualKeyCode::R15, - ffi::XK_Shift_L => events::VirtualKeyCode::LShift, - ffi::XK_Shift_R => events::VirtualKeyCode::RShift, - ffi::XK_Control_L => events::VirtualKeyCode::LControl, - ffi::XK_Control_R => events::VirtualKeyCode::RControl, - //ffi::XK_Caps_Lock => events::VirtualKeyCode::Caps_lock, - //ffi::XK_Shift_Lock => events::VirtualKeyCode::Shift_lock, - //ffi::XK_Meta_L => events::VirtualKeyCode::Meta_l, - //ffi::XK_Meta_R => events::VirtualKeyCode::Meta_r, - ffi::XK_Alt_L => events::VirtualKeyCode::LAlt, - ffi::XK_Alt_R => events::VirtualKeyCode::RAlt, - //ffi::XK_Super_L => events::VirtualKeyCode::Super_l, - //ffi::XK_Super_R => events::VirtualKeyCode::Super_r, - //ffi::XK_Hyper_L => events::VirtualKeyCode::Hyper_l, - //ffi::XK_Hyper_R => events::VirtualKeyCode::Hyper_r, - ffi::XK_ISO_Left_Tab => events::VirtualKeyCode::Tab, - ffi::XK_space => events::VirtualKeyCode::Space, - //ffi::XK_exclam => events::VirtualKeyCode::Exclam, - //ffi::XK_quotedbl => events::VirtualKeyCode::Quotedbl, - //ffi::XK_numbersign => events::VirtualKeyCode::Numbersign, - //ffi::XK_dollar => events::VirtualKeyCode::Dollar, - //ffi::XK_percent => events::VirtualKeyCode::Percent, - //ffi::XK_ampersand => events::VirtualKeyCode::Ampersand, - ffi::XK_apostrophe => events::VirtualKeyCode::Apostrophe, - //ffi::XK_quoteright => events::VirtualKeyCode::Quoteright, - //ffi::XK_parenleft => events::VirtualKeyCode::Parenleft, - //ffi::XK_parenright => events::VirtualKeyCode::Parenright, - //ffi::XK_asterisk => events::VirtualKeyCode::Asterisk, - ffi::XK_plus => events::VirtualKeyCode::Add, - ffi::XK_comma => events::VirtualKeyCode::Comma, - ffi::XK_minus => events::VirtualKeyCode::Subtract, - ffi::XK_period => events::VirtualKeyCode::Period, - ffi::XK_slash => events::VirtualKeyCode::Slash, - ffi::XK_0 => events::VirtualKeyCode::Key0, - ffi::XK_1 => events::VirtualKeyCode::Key1, - ffi::XK_2 => events::VirtualKeyCode::Key2, - ffi::XK_3 => events::VirtualKeyCode::Key3, - ffi::XK_4 => events::VirtualKeyCode::Key4, - ffi::XK_5 => events::VirtualKeyCode::Key5, - ffi::XK_6 => events::VirtualKeyCode::Key6, - ffi::XK_7 => events::VirtualKeyCode::Key7, - ffi::XK_8 => events::VirtualKeyCode::Key8, - ffi::XK_9 => events::VirtualKeyCode::Key9, - ffi::XK_colon => events::VirtualKeyCode::Colon, - ffi::XK_semicolon => events::VirtualKeyCode::Semicolon, - //ffi::XK_less => events::VirtualKeyCode::Less, - ffi::XK_equal => events::VirtualKeyCode::Equals, - //ffi::XK_greater => events::VirtualKeyCode::Greater, - //ffi::XK_question => events::VirtualKeyCode::Question, - ffi::XK_at => events::VirtualKeyCode::At, - ffi::XK_A => events::VirtualKeyCode::A, - ffi::XK_B => events::VirtualKeyCode::B, - ffi::XK_C => events::VirtualKeyCode::C, - ffi::XK_D => events::VirtualKeyCode::D, - ffi::XK_E => events::VirtualKeyCode::E, - ffi::XK_F => events::VirtualKeyCode::F, - ffi::XK_G => events::VirtualKeyCode::G, - ffi::XK_H => events::VirtualKeyCode::H, - ffi::XK_I => events::VirtualKeyCode::I, - ffi::XK_J => events::VirtualKeyCode::J, - ffi::XK_K => events::VirtualKeyCode::K, - ffi::XK_L => events::VirtualKeyCode::L, - ffi::XK_M => events::VirtualKeyCode::M, - ffi::XK_N => events::VirtualKeyCode::N, - ffi::XK_O => events::VirtualKeyCode::O, - ffi::XK_P => events::VirtualKeyCode::P, - ffi::XK_Q => events::VirtualKeyCode::Q, - ffi::XK_R => events::VirtualKeyCode::R, - ffi::XK_S => events::VirtualKeyCode::S, - ffi::XK_T => events::VirtualKeyCode::T, - ffi::XK_U => events::VirtualKeyCode::U, - ffi::XK_V => events::VirtualKeyCode::V, - ffi::XK_W => events::VirtualKeyCode::W, - ffi::XK_X => events::VirtualKeyCode::X, - ffi::XK_Y => events::VirtualKeyCode::Y, - ffi::XK_Z => events::VirtualKeyCode::Z, - ffi::XK_bracketleft => events::VirtualKeyCode::LBracket, - ffi::XK_backslash => events::VirtualKeyCode::Backslash, - ffi::XK_bracketright => events::VirtualKeyCode::RBracket, - //ffi::XK_asciicircum => events::VirtualKeyCode::Asciicircum, - //ffi::XK_underscore => events::VirtualKeyCode::Underscore, - ffi::XK_grave => events::VirtualKeyCode::Grave, - //ffi::XK_quoteleft => events::VirtualKeyCode::Quoteleft, - ffi::XK_a => events::VirtualKeyCode::A, - ffi::XK_b => events::VirtualKeyCode::B, - ffi::XK_c => events::VirtualKeyCode::C, - ffi::XK_d => events::VirtualKeyCode::D, - ffi::XK_e => events::VirtualKeyCode::E, - ffi::XK_f => events::VirtualKeyCode::F, - ffi::XK_g => events::VirtualKeyCode::G, - ffi::XK_h => events::VirtualKeyCode::H, - ffi::XK_i => events::VirtualKeyCode::I, - ffi::XK_j => events::VirtualKeyCode::J, - ffi::XK_k => events::VirtualKeyCode::K, - ffi::XK_l => events::VirtualKeyCode::L, - ffi::XK_m => events::VirtualKeyCode::M, - ffi::XK_n => events::VirtualKeyCode::N, - ffi::XK_o => events::VirtualKeyCode::O, - ffi::XK_p => events::VirtualKeyCode::P, - ffi::XK_q => events::VirtualKeyCode::Q, - ffi::XK_r => events::VirtualKeyCode::R, - ffi::XK_s => events::VirtualKeyCode::S, - ffi::XK_t => events::VirtualKeyCode::T, - ffi::XK_u => events::VirtualKeyCode::U, - ffi::XK_v => events::VirtualKeyCode::V, - ffi::XK_w => events::VirtualKeyCode::W, - ffi::XK_x => events::VirtualKeyCode::X, - ffi::XK_y => events::VirtualKeyCode::Y, - ffi::XK_z => events::VirtualKeyCode::Z, - //ffi::XK_braceleft => events::VirtualKeyCode::Braceleft, - //ffi::XK_bar => events::VirtualKeyCode::Bar, - //ffi::XK_braceright => events::VirtualKeyCode::Braceright, - //ffi::XK_asciitilde => events::VirtualKeyCode::Asciitilde, - //ffi::XK_nobreakspace => events::VirtualKeyCode::Nobreakspace, - //ffi::XK_exclamdown => events::VirtualKeyCode::Exclamdown, - //ffi::XK_cent => events::VirtualKeyCode::Cent, - //ffi::XK_sterling => events::VirtualKeyCode::Sterling, - //ffi::XK_currency => events::VirtualKeyCode::Currency, - //ffi::XK_yen => events::VirtualKeyCode::Yen, - //ffi::XK_brokenbar => events::VirtualKeyCode::Brokenbar, - //ffi::XK_section => events::VirtualKeyCode::Section, - //ffi::XK_diaeresis => events::VirtualKeyCode::Diaeresis, - //ffi::XK_copyright => events::VirtualKeyCode::Copyright, - //ffi::XK_ordfeminine => events::VirtualKeyCode::Ordfeminine, - //ffi::XK_guillemotleft => events::VirtualKeyCode::Guillemotleft, - //ffi::XK_notsign => events::VirtualKeyCode::Notsign, - //ffi::XK_hyphen => events::VirtualKeyCode::Hyphen, - //ffi::XK_registered => events::VirtualKeyCode::Registered, - //ffi::XK_macron => events::VirtualKeyCode::Macron, - //ffi::XK_degree => events::VirtualKeyCode::Degree, - //ffi::XK_plusminus => events::VirtualKeyCode::Plusminus, - //ffi::XK_twosuperior => events::VirtualKeyCode::Twosuperior, - //ffi::XK_threesuperior => events::VirtualKeyCode::Threesuperior, - //ffi::XK_acute => events::VirtualKeyCode::Acute, - //ffi::XK_mu => events::VirtualKeyCode::Mu, - //ffi::XK_paragraph => events::VirtualKeyCode::Paragraph, - //ffi::XK_periodcentered => events::VirtualKeyCode::Periodcentered, - //ffi::XK_cedilla => events::VirtualKeyCode::Cedilla, - //ffi::XK_onesuperior => events::VirtualKeyCode::Onesuperior, - //ffi::XK_masculine => events::VirtualKeyCode::Masculine, - //ffi::XK_guillemotright => events::VirtualKeyCode::Guillemotright, - //ffi::XK_onequarter => events::VirtualKeyCode::Onequarter, - //ffi::XK_onehalf => events::VirtualKeyCode::Onehalf, - //ffi::XK_threequarters => events::VirtualKeyCode::Threequarters, - //ffi::XK_questiondown => events::VirtualKeyCode::Questiondown, - //ffi::XK_Agrave => events::VirtualKeyCode::Agrave, - //ffi::XK_Aacute => events::VirtualKeyCode::Aacute, - //ffi::XK_Acircumflex => events::VirtualKeyCode::Acircumflex, - //ffi::XK_Atilde => events::VirtualKeyCode::Atilde, - //ffi::XK_Adiaeresis => events::VirtualKeyCode::Adiaeresis, - //ffi::XK_Aring => events::VirtualKeyCode::Aring, - //ffi::XK_AE => events::VirtualKeyCode::Ae, - //ffi::XK_Ccedilla => events::VirtualKeyCode::Ccedilla, - //ffi::XK_Egrave => events::VirtualKeyCode::Egrave, - //ffi::XK_Eacute => events::VirtualKeyCode::Eacute, - //ffi::XK_Ecircumflex => events::VirtualKeyCode::Ecircumflex, - //ffi::XK_Ediaeresis => events::VirtualKeyCode::Ediaeresis, - //ffi::XK_Igrave => events::VirtualKeyCode::Igrave, - //ffi::XK_Iacute => events::VirtualKeyCode::Iacute, - //ffi::XK_Icircumflex => events::VirtualKeyCode::Icircumflex, - //ffi::XK_Idiaeresis => events::VirtualKeyCode::Idiaeresis, - //ffi::XK_ETH => events::VirtualKeyCode::Eth, - //ffi::XK_Eth => events::VirtualKeyCode::Eth, - //ffi::XK_Ntilde => events::VirtualKeyCode::Ntilde, - //ffi::XK_Ograve => events::VirtualKeyCode::Ograve, - //ffi::XK_Oacute => events::VirtualKeyCode::Oacute, - //ffi::XK_Ocircumflex => events::VirtualKeyCode::Ocircumflex, - //ffi::XK_Otilde => events::VirtualKeyCode::Otilde, - //ffi::XK_Odiaeresis => events::VirtualKeyCode::Odiaeresis, - //ffi::XK_multiply => events::VirtualKeyCode::Multiply, - //ffi::XK_Ooblique => events::VirtualKeyCode::Ooblique, - //ffi::XK_Ugrave => events::VirtualKeyCode::Ugrave, - //ffi::XK_Uacute => events::VirtualKeyCode::Uacute, - //ffi::XK_Ucircumflex => events::VirtualKeyCode::Ucircumflex, - //ffi::XK_Udiaeresis => events::VirtualKeyCode::Udiaeresis, - //ffi::XK_Yacute => events::VirtualKeyCode::Yacute, - //ffi::XK_THORN => events::VirtualKeyCode::Thorn, - //ffi::XK_Thorn => events::VirtualKeyCode::Thorn, - //ffi::XK_ssharp => events::VirtualKeyCode::Ssharp, - //ffi::XK_agrave => events::VirtualKeyCode::Agrave, - //ffi::XK_aacute => events::VirtualKeyCode::Aacute, - //ffi::XK_acircumflex => events::VirtualKeyCode::Acircumflex, - //ffi::XK_atilde => events::VirtualKeyCode::Atilde, - //ffi::XK_adiaeresis => events::VirtualKeyCode::Adiaeresis, - //ffi::XK_aring => events::VirtualKeyCode::Aring, - //ffi::XK_ae => events::VirtualKeyCode::Ae, - //ffi::XK_ccedilla => events::VirtualKeyCode::Ccedilla, - //ffi::XK_egrave => events::VirtualKeyCode::Egrave, - //ffi::XK_eacute => events::VirtualKeyCode::Eacute, - //ffi::XK_ecircumflex => events::VirtualKeyCode::Ecircumflex, - //ffi::XK_ediaeresis => events::VirtualKeyCode::Ediaeresis, - //ffi::XK_igrave => events::VirtualKeyCode::Igrave, - //ffi::XK_iacute => events::VirtualKeyCode::Iacute, - //ffi::XK_icircumflex => events::VirtualKeyCode::Icircumflex, - //ffi::XK_idiaeresis => events::VirtualKeyCode::Idiaeresis, - //ffi::XK_eth => events::VirtualKeyCode::Eth, - //ffi::XK_ntilde => events::VirtualKeyCode::Ntilde, - //ffi::XK_ograve => events::VirtualKeyCode::Ograve, - //ffi::XK_oacute => events::VirtualKeyCode::Oacute, - //ffi::XK_ocircumflex => events::VirtualKeyCode::Ocircumflex, - //ffi::XK_otilde => events::VirtualKeyCode::Otilde, - //ffi::XK_odiaeresis => events::VirtualKeyCode::Odiaeresis, - //ffi::XK_division => events::VirtualKeyCode::Division, - //ffi::XK_oslash => events::VirtualKeyCode::Oslash, - //ffi::XK_ugrave => events::VirtualKeyCode::Ugrave, - //ffi::XK_uacute => events::VirtualKeyCode::Uacute, - //ffi::XK_ucircumflex => events::VirtualKeyCode::Ucircumflex, - //ffi::XK_udiaeresis => events::VirtualKeyCode::Udiaeresis, - //ffi::XK_yacute => events::VirtualKeyCode::Yacute, - //ffi::XK_thorn => events::VirtualKeyCode::Thorn, - //ffi::XK_ydiaeresis => events::VirtualKeyCode::Ydiaeresis, - //ffi::XK_Aogonek => events::VirtualKeyCode::Aogonek, - //ffi::XK_breve => events::VirtualKeyCode::Breve, - //ffi::XK_Lstroke => events::VirtualKeyCode::Lstroke, - //ffi::XK_Lcaron => events::VirtualKeyCode::Lcaron, - //ffi::XK_Sacute => events::VirtualKeyCode::Sacute, - //ffi::XK_Scaron => events::VirtualKeyCode::Scaron, - //ffi::XK_Scedilla => events::VirtualKeyCode::Scedilla, - //ffi::XK_Tcaron => events::VirtualKeyCode::Tcaron, - //ffi::XK_Zacute => events::VirtualKeyCode::Zacute, - //ffi::XK_Zcaron => events::VirtualKeyCode::Zcaron, - //ffi::XK_Zabovedot => events::VirtualKeyCode::Zabovedot, - //ffi::XK_aogonek => events::VirtualKeyCode::Aogonek, - //ffi::XK_ogonek => events::VirtualKeyCode::Ogonek, - //ffi::XK_lstroke => events::VirtualKeyCode::Lstroke, - //ffi::XK_lcaron => events::VirtualKeyCode::Lcaron, - //ffi::XK_sacute => events::VirtualKeyCode::Sacute, - //ffi::XK_caron => events::VirtualKeyCode::Caron, - //ffi::XK_scaron => events::VirtualKeyCode::Scaron, - //ffi::XK_scedilla => events::VirtualKeyCode::Scedilla, - //ffi::XK_tcaron => events::VirtualKeyCode::Tcaron, - //ffi::XK_zacute => events::VirtualKeyCode::Zacute, - //ffi::XK_doubleacute => events::VirtualKeyCode::Doubleacute, - //ffi::XK_zcaron => events::VirtualKeyCode::Zcaron, - //ffi::XK_zabovedot => events::VirtualKeyCode::Zabovedot, - //ffi::XK_Racute => events::VirtualKeyCode::Racute, - //ffi::XK_Abreve => events::VirtualKeyCode::Abreve, - //ffi::XK_Lacute => events::VirtualKeyCode::Lacute, - //ffi::XK_Cacute => events::VirtualKeyCode::Cacute, - //ffi::XK_Ccaron => events::VirtualKeyCode::Ccaron, - //ffi::XK_Eogonek => events::VirtualKeyCode::Eogonek, - //ffi::XK_Ecaron => events::VirtualKeyCode::Ecaron, - //ffi::XK_Dcaron => events::VirtualKeyCode::Dcaron, - //ffi::XK_Dstroke => events::VirtualKeyCode::Dstroke, - //ffi::XK_Nacute => events::VirtualKeyCode::Nacute, - //ffi::XK_Ncaron => events::VirtualKeyCode::Ncaron, - //ffi::XK_Odoubleacute => events::VirtualKeyCode::Odoubleacute, - //ffi::XK_Rcaron => events::VirtualKeyCode::Rcaron, - //ffi::XK_Uring => events::VirtualKeyCode::Uring, - //ffi::XK_Udoubleacute => events::VirtualKeyCode::Udoubleacute, - //ffi::XK_Tcedilla => events::VirtualKeyCode::Tcedilla, - //ffi::XK_racute => events::VirtualKeyCode::Racute, - //ffi::XK_abreve => events::VirtualKeyCode::Abreve, - //ffi::XK_lacute => events::VirtualKeyCode::Lacute, - //ffi::XK_cacute => events::VirtualKeyCode::Cacute, - //ffi::XK_ccaron => events::VirtualKeyCode::Ccaron, - //ffi::XK_eogonek => events::VirtualKeyCode::Eogonek, - //ffi::XK_ecaron => events::VirtualKeyCode::Ecaron, - //ffi::XK_dcaron => events::VirtualKeyCode::Dcaron, - //ffi::XK_dstroke => events::VirtualKeyCode::Dstroke, - //ffi::XK_nacute => events::VirtualKeyCode::Nacute, - //ffi::XK_ncaron => events::VirtualKeyCode::Ncaron, - //ffi::XK_odoubleacute => events::VirtualKeyCode::Odoubleacute, - //ffi::XK_udoubleacute => events::VirtualKeyCode::Udoubleacute, - //ffi::XK_rcaron => events::VirtualKeyCode::Rcaron, - //ffi::XK_uring => events::VirtualKeyCode::Uring, - //ffi::XK_tcedilla => events::VirtualKeyCode::Tcedilla, - //ffi::XK_abovedot => events::VirtualKeyCode::Abovedot, - //ffi::XK_Hstroke => events::VirtualKeyCode::Hstroke, - //ffi::XK_Hcircumflex => events::VirtualKeyCode::Hcircumflex, - //ffi::XK_Iabovedot => events::VirtualKeyCode::Iabovedot, - //ffi::XK_Gbreve => events::VirtualKeyCode::Gbreve, - //ffi::XK_Jcircumflex => events::VirtualKeyCode::Jcircumflex, - //ffi::XK_hstroke => events::VirtualKeyCode::Hstroke, - //ffi::XK_hcircumflex => events::VirtualKeyCode::Hcircumflex, - //ffi::XK_idotless => events::VirtualKeyCode::Idotless, - //ffi::XK_gbreve => events::VirtualKeyCode::Gbreve, - //ffi::XK_jcircumflex => events::VirtualKeyCode::Jcircumflex, - //ffi::XK_Cabovedot => events::VirtualKeyCode::Cabovedot, - //ffi::XK_Ccircumflex => events::VirtualKeyCode::Ccircumflex, - //ffi::XK_Gabovedot => events::VirtualKeyCode::Gabovedot, - //ffi::XK_Gcircumflex => events::VirtualKeyCode::Gcircumflex, - //ffi::XK_Ubreve => events::VirtualKeyCode::Ubreve, - //ffi::XK_Scircumflex => events::VirtualKeyCode::Scircumflex, - //ffi::XK_cabovedot => events::VirtualKeyCode::Cabovedot, - //ffi::XK_ccircumflex => events::VirtualKeyCode::Ccircumflex, - //ffi::XK_gabovedot => events::VirtualKeyCode::Gabovedot, - //ffi::XK_gcircumflex => events::VirtualKeyCode::Gcircumflex, - //ffi::XK_ubreve => events::VirtualKeyCode::Ubreve, - //ffi::XK_scircumflex => events::VirtualKeyCode::Scircumflex, - //ffi::XK_kra => events::VirtualKeyCode::Kra, - //ffi::XK_kappa => events::VirtualKeyCode::Kappa, - //ffi::XK_Rcedilla => events::VirtualKeyCode::Rcedilla, - //ffi::XK_Itilde => events::VirtualKeyCode::Itilde, - //ffi::XK_Lcedilla => events::VirtualKeyCode::Lcedilla, - //ffi::XK_Emacron => events::VirtualKeyCode::Emacron, - //ffi::XK_Gcedilla => events::VirtualKeyCode::Gcedilla, - //ffi::XK_Tslash => events::VirtualKeyCode::Tslash, - //ffi::XK_rcedilla => events::VirtualKeyCode::Rcedilla, - //ffi::XK_itilde => events::VirtualKeyCode::Itilde, - //ffi::XK_lcedilla => events::VirtualKeyCode::Lcedilla, - //ffi::XK_emacron => events::VirtualKeyCode::Emacron, - //ffi::XK_gcedilla => events::VirtualKeyCode::Gcedilla, - //ffi::XK_tslash => events::VirtualKeyCode::Tslash, - //ffi::XK_ENG => events::VirtualKeyCode::Eng, - //ffi::XK_eng => events::VirtualKeyCode::Eng, - //ffi::XK_Amacron => events::VirtualKeyCode::Amacron, - //ffi::XK_Iogonek => events::VirtualKeyCode::Iogonek, - //ffi::XK_Eabovedot => events::VirtualKeyCode::Eabovedot, - //ffi::XK_Imacron => events::VirtualKeyCode::Imacron, - //ffi::XK_Ncedilla => events::VirtualKeyCode::Ncedilla, - //ffi::XK_Omacron => events::VirtualKeyCode::Omacron, - //ffi::XK_Kcedilla => events::VirtualKeyCode::Kcedilla, - //ffi::XK_Uogonek => events::VirtualKeyCode::Uogonek, - //ffi::XK_Utilde => events::VirtualKeyCode::Utilde, - //ffi::XK_Umacron => events::VirtualKeyCode::Umacron, - //ffi::XK_amacron => events::VirtualKeyCode::Amacron, - //ffi::XK_iogonek => events::VirtualKeyCode::Iogonek, - //ffi::XK_eabovedot => events::VirtualKeyCode::Eabovedot, - //ffi::XK_imacron => events::VirtualKeyCode::Imacron, - //ffi::XK_ncedilla => events::VirtualKeyCode::Ncedilla, - //ffi::XK_omacron => events::VirtualKeyCode::Omacron, - //ffi::XK_kcedilla => events::VirtualKeyCode::Kcedilla, - //ffi::XK_uogonek => events::VirtualKeyCode::Uogonek, - //ffi::XK_utilde => events::VirtualKeyCode::Utilde, - //ffi::XK_umacron => events::VirtualKeyCode::Umacron, - //ffi::XK_overline => events::VirtualKeyCode::Overline, - //ffi::XK_kana_fullstop => events::VirtualKeyCode::Kana_fullstop, - //ffi::XK_kana_openingbracket => events::VirtualKeyCode::Kana_openingbracket, - //ffi::XK_kana_closingbracket => events::VirtualKeyCode::Kana_closingbracket, - //ffi::XK_kana_comma => events::VirtualKeyCode::Kana_comma, - //ffi::XK_kana_conjunctive => events::VirtualKeyCode::Kana_conjunctive, - //ffi::XK_kana_middledot => events::VirtualKeyCode::Kana_middledot, - //ffi::XK_kana_WO => events::VirtualKeyCode::Kana_wo, - //ffi::XK_kana_a => events::VirtualKeyCode::Kana_a, - //ffi::XK_kana_i => events::VirtualKeyCode::Kana_i, - //ffi::XK_kana_u => events::VirtualKeyCode::Kana_u, - //ffi::XK_kana_e => events::VirtualKeyCode::Kana_e, - //ffi::XK_kana_o => events::VirtualKeyCode::Kana_o, - //ffi::XK_kana_ya => events::VirtualKeyCode::Kana_ya, - //ffi::XK_kana_yu => events::VirtualKeyCode::Kana_yu, - //ffi::XK_kana_yo => events::VirtualKeyCode::Kana_yo, - //ffi::XK_kana_tsu => events::VirtualKeyCode::Kana_tsu, - //ffi::XK_kana_tu => events::VirtualKeyCode::Kana_tu, - //ffi::XK_prolongedsound => events::VirtualKeyCode::Prolongedsound, - //ffi::XK_kana_A => events::VirtualKeyCode::Kana_a, - //ffi::XK_kana_I => events::VirtualKeyCode::Kana_i, - //ffi::XK_kana_U => events::VirtualKeyCode::Kana_u, - //ffi::XK_kana_E => events::VirtualKeyCode::Kana_e, - //ffi::XK_kana_O => events::VirtualKeyCode::Kana_o, - //ffi::XK_kana_KA => events::VirtualKeyCode::Kana_ka, - //ffi::XK_kana_KI => events::VirtualKeyCode::Kana_ki, - //ffi::XK_kana_KU => events::VirtualKeyCode::Kana_ku, - //ffi::XK_kana_KE => events::VirtualKeyCode::Kana_ke, - //ffi::XK_kana_KO => events::VirtualKeyCode::Kana_ko, - //ffi::XK_kana_SA => events::VirtualKeyCode::Kana_sa, - //ffi::XK_kana_SHI => events::VirtualKeyCode::Kana_shi, - //ffi::XK_kana_SU => events::VirtualKeyCode::Kana_su, - //ffi::XK_kana_SE => events::VirtualKeyCode::Kana_se, - //ffi::XK_kana_SO => events::VirtualKeyCode::Kana_so, - //ffi::XK_kana_TA => events::VirtualKeyCode::Kana_ta, - //ffi::XK_kana_CHI => events::VirtualKeyCode::Kana_chi, - //ffi::XK_kana_TI => events::VirtualKeyCode::Kana_ti, - //ffi::XK_kana_TSU => events::VirtualKeyCode::Kana_tsu, - //ffi::XK_kana_TU => events::VirtualKeyCode::Kana_tu, - //ffi::XK_kana_TE => events::VirtualKeyCode::Kana_te, - //ffi::XK_kana_TO => events::VirtualKeyCode::Kana_to, - //ffi::XK_kana_NA => events::VirtualKeyCode::Kana_na, - //ffi::XK_kana_NI => events::VirtualKeyCode::Kana_ni, - //ffi::XK_kana_NU => events::VirtualKeyCode::Kana_nu, - //ffi::XK_kana_NE => events::VirtualKeyCode::Kana_ne, - //ffi::XK_kana_NO => events::VirtualKeyCode::Kana_no, - //ffi::XK_kana_HA => events::VirtualKeyCode::Kana_ha, - //ffi::XK_kana_HI => events::VirtualKeyCode::Kana_hi, - //ffi::XK_kana_FU => events::VirtualKeyCode::Kana_fu, - //ffi::XK_kana_HU => events::VirtualKeyCode::Kana_hu, - //ffi::XK_kana_HE => events::VirtualKeyCode::Kana_he, - //ffi::XK_kana_HO => events::VirtualKeyCode::Kana_ho, - //ffi::XK_kana_MA => events::VirtualKeyCode::Kana_ma, - //ffi::XK_kana_MI => events::VirtualKeyCode::Kana_mi, - //ffi::XK_kana_MU => events::VirtualKeyCode::Kana_mu, - //ffi::XK_kana_ME => events::VirtualKeyCode::Kana_me, - //ffi::XK_kana_MO => events::VirtualKeyCode::Kana_mo, - //ffi::XK_kana_YA => events::VirtualKeyCode::Kana_ya, - //ffi::XK_kana_YU => events::VirtualKeyCode::Kana_yu, - //ffi::XK_kana_YO => events::VirtualKeyCode::Kana_yo, - //ffi::XK_kana_RA => events::VirtualKeyCode::Kana_ra, - //ffi::XK_kana_RI => events::VirtualKeyCode::Kana_ri, - //ffi::XK_kana_RU => events::VirtualKeyCode::Kana_ru, - //ffi::XK_kana_RE => events::VirtualKeyCode::Kana_re, - //ffi::XK_kana_RO => events::VirtualKeyCode::Kana_ro, - //ffi::XK_kana_WA => events::VirtualKeyCode::Kana_wa, - //ffi::XK_kana_N => events::VirtualKeyCode::Kana_n, - //ffi::XK_voicedsound => events::VirtualKeyCode::Voicedsound, - //ffi::XK_semivoicedsound => events::VirtualKeyCode::Semivoicedsound, - //ffi::XK_kana_switch => events::VirtualKeyCode::Kana_switch, - //ffi::XK_Arabic_comma => events::VirtualKeyCode::Arabic_comma, - //ffi::XK_Arabic_semicolon => events::VirtualKeyCode::Arabic_semicolon, - //ffi::XK_Arabic_question_mark => events::VirtualKeyCode::Arabic_question_mark, - //ffi::XK_Arabic_hamza => events::VirtualKeyCode::Arabic_hamza, - //ffi::XK_Arabic_maddaonalef => events::VirtualKeyCode::Arabic_maddaonalef, - //ffi::XK_Arabic_hamzaonalef => events::VirtualKeyCode::Arabic_hamzaonalef, - //ffi::XK_Arabic_hamzaonwaw => events::VirtualKeyCode::Arabic_hamzaonwaw, - //ffi::XK_Arabic_hamzaunderalef => events::VirtualKeyCode::Arabic_hamzaunderalef, - //ffi::XK_Arabic_hamzaonyeh => events::VirtualKeyCode::Arabic_hamzaonyeh, - //ffi::XK_Arabic_alef => events::VirtualKeyCode::Arabic_alef, - //ffi::XK_Arabic_beh => events::VirtualKeyCode::Arabic_beh, - //ffi::XK_Arabic_tehmarbuta => events::VirtualKeyCode::Arabic_tehmarbuta, - //ffi::XK_Arabic_teh => events::VirtualKeyCode::Arabic_teh, - //ffi::XK_Arabic_theh => events::VirtualKeyCode::Arabic_theh, - //ffi::XK_Arabic_jeem => events::VirtualKeyCode::Arabic_jeem, - //ffi::XK_Arabic_hah => events::VirtualKeyCode::Arabic_hah, - //ffi::XK_Arabic_khah => events::VirtualKeyCode::Arabic_khah, - //ffi::XK_Arabic_dal => events::VirtualKeyCode::Arabic_dal, - //ffi::XK_Arabic_thal => events::VirtualKeyCode::Arabic_thal, - //ffi::XK_Arabic_ra => events::VirtualKeyCode::Arabic_ra, - //ffi::XK_Arabic_zain => events::VirtualKeyCode::Arabic_zain, - //ffi::XK_Arabic_seen => events::VirtualKeyCode::Arabic_seen, - //ffi::XK_Arabic_sheen => events::VirtualKeyCode::Arabic_sheen, - //ffi::XK_Arabic_sad => events::VirtualKeyCode::Arabic_sad, - //ffi::XK_Arabic_dad => events::VirtualKeyCode::Arabic_dad, - //ffi::XK_Arabic_tah => events::VirtualKeyCode::Arabic_tah, - //ffi::XK_Arabic_zah => events::VirtualKeyCode::Arabic_zah, - //ffi::XK_Arabic_ain => events::VirtualKeyCode::Arabic_ain, - //ffi::XK_Arabic_ghain => events::VirtualKeyCode::Arabic_ghain, - //ffi::XK_Arabic_tatweel => events::VirtualKeyCode::Arabic_tatweel, - //ffi::XK_Arabic_feh => events::VirtualKeyCode::Arabic_feh, - //ffi::XK_Arabic_qaf => events::VirtualKeyCode::Arabic_qaf, - //ffi::XK_Arabic_kaf => events::VirtualKeyCode::Arabic_kaf, - //ffi::XK_Arabic_lam => events::VirtualKeyCode::Arabic_lam, - //ffi::XK_Arabic_meem => events::VirtualKeyCode::Arabic_meem, - //ffi::XK_Arabic_noon => events::VirtualKeyCode::Arabic_noon, - //ffi::XK_Arabic_ha => events::VirtualKeyCode::Arabic_ha, - //ffi::XK_Arabic_heh => events::VirtualKeyCode::Arabic_heh, - //ffi::XK_Arabic_waw => events::VirtualKeyCode::Arabic_waw, - //ffi::XK_Arabic_alefmaksura => events::VirtualKeyCode::Arabic_alefmaksura, - //ffi::XK_Arabic_yeh => events::VirtualKeyCode::Arabic_yeh, - //ffi::XK_Arabic_fathatan => events::VirtualKeyCode::Arabic_fathatan, - //ffi::XK_Arabic_dammatan => events::VirtualKeyCode::Arabic_dammatan, - //ffi::XK_Arabic_kasratan => events::VirtualKeyCode::Arabic_kasratan, - //ffi::XK_Arabic_fatha => events::VirtualKeyCode::Arabic_fatha, - //ffi::XK_Arabic_damma => events::VirtualKeyCode::Arabic_damma, - //ffi::XK_Arabic_kasra => events::VirtualKeyCode::Arabic_kasra, - //ffi::XK_Arabic_shadda => events::VirtualKeyCode::Arabic_shadda, - //ffi::XK_Arabic_sukun => events::VirtualKeyCode::Arabic_sukun, - //ffi::XK_Arabic_switch => events::VirtualKeyCode::Arabic_switch, - //ffi::XK_Serbian_dje => events::VirtualKeyCode::Serbian_dje, - //ffi::XK_Macedonia_gje => events::VirtualKeyCode::Macedonia_gje, - //ffi::XK_Cyrillic_io => events::VirtualKeyCode::Cyrillic_io, - //ffi::XK_Ukrainian_ie => events::VirtualKeyCode::Ukrainian_ie, - //ffi::XK_Ukranian_je => events::VirtualKeyCode::Ukranian_je, - //ffi::XK_Macedonia_dse => events::VirtualKeyCode::Macedonia_dse, - //ffi::XK_Ukrainian_i => events::VirtualKeyCode::Ukrainian_i, - //ffi::XK_Ukranian_i => events::VirtualKeyCode::Ukranian_i, - //ffi::XK_Ukrainian_yi => events::VirtualKeyCode::Ukrainian_yi, - //ffi::XK_Ukranian_yi => events::VirtualKeyCode::Ukranian_yi, - //ffi::XK_Cyrillic_je => events::VirtualKeyCode::Cyrillic_je, - //ffi::XK_Serbian_je => events::VirtualKeyCode::Serbian_je, - //ffi::XK_Cyrillic_lje => events::VirtualKeyCode::Cyrillic_lje, - //ffi::XK_Serbian_lje => events::VirtualKeyCode::Serbian_lje, - //ffi::XK_Cyrillic_nje => events::VirtualKeyCode::Cyrillic_nje, - //ffi::XK_Serbian_nje => events::VirtualKeyCode::Serbian_nje, - //ffi::XK_Serbian_tshe => events::VirtualKeyCode::Serbian_tshe, - //ffi::XK_Macedonia_kje => events::VirtualKeyCode::Macedonia_kje, - //ffi::XK_Byelorussian_shortu => events::VirtualKeyCode::Byelorussian_shortu, - //ffi::XK_Cyrillic_dzhe => events::VirtualKeyCode::Cyrillic_dzhe, - //ffi::XK_Serbian_dze => events::VirtualKeyCode::Serbian_dze, - //ffi::XK_numerosign => events::VirtualKeyCode::Numerosign, - //ffi::XK_Serbian_DJE => events::VirtualKeyCode::Serbian_dje, - //ffi::XK_Macedonia_GJE => events::VirtualKeyCode::Macedonia_gje, - //ffi::XK_Cyrillic_IO => events::VirtualKeyCode::Cyrillic_io, - //ffi::XK_Ukrainian_IE => events::VirtualKeyCode::Ukrainian_ie, - //ffi::XK_Ukranian_JE => events::VirtualKeyCode::Ukranian_je, - //ffi::XK_Macedonia_DSE => events::VirtualKeyCode::Macedonia_dse, - //ffi::XK_Ukrainian_I => events::VirtualKeyCode::Ukrainian_i, - //ffi::XK_Ukranian_I => events::VirtualKeyCode::Ukranian_i, - //ffi::XK_Ukrainian_YI => events::VirtualKeyCode::Ukrainian_yi, - //ffi::XK_Ukranian_YI => events::VirtualKeyCode::Ukranian_yi, - //ffi::XK_Cyrillic_JE => events::VirtualKeyCode::Cyrillic_je, - //ffi::XK_Serbian_JE => events::VirtualKeyCode::Serbian_je, - //ffi::XK_Cyrillic_LJE => events::VirtualKeyCode::Cyrillic_lje, - //ffi::XK_Serbian_LJE => events::VirtualKeyCode::Serbian_lje, - //ffi::XK_Cyrillic_NJE => events::VirtualKeyCode::Cyrillic_nje, - //ffi::XK_Serbian_NJE => events::VirtualKeyCode::Serbian_nje, - //ffi::XK_Serbian_TSHE => events::VirtualKeyCode::Serbian_tshe, - //ffi::XK_Macedonia_KJE => events::VirtualKeyCode::Macedonia_kje, - //ffi::XK_Byelorussian_SHORTU => events::VirtualKeyCode::Byelorussian_shortu, - //ffi::XK_Cyrillic_DZHE => events::VirtualKeyCode::Cyrillic_dzhe, - //ffi::XK_Serbian_DZE => events::VirtualKeyCode::Serbian_dze, - //ffi::XK_Cyrillic_yu => events::VirtualKeyCode::Cyrillic_yu, - //ffi::XK_Cyrillic_a => events::VirtualKeyCode::Cyrillic_a, - //ffi::XK_Cyrillic_be => events::VirtualKeyCode::Cyrillic_be, - //ffi::XK_Cyrillic_tse => events::VirtualKeyCode::Cyrillic_tse, - //ffi::XK_Cyrillic_de => events::VirtualKeyCode::Cyrillic_de, - //ffi::XK_Cyrillic_ie => events::VirtualKeyCode::Cyrillic_ie, - //ffi::XK_Cyrillic_ef => events::VirtualKeyCode::Cyrillic_ef, - //ffi::XK_Cyrillic_ghe => events::VirtualKeyCode::Cyrillic_ghe, - //ffi::XK_Cyrillic_ha => events::VirtualKeyCode::Cyrillic_ha, - //ffi::XK_Cyrillic_i => events::VirtualKeyCode::Cyrillic_i, - //ffi::XK_Cyrillic_shorti => events::VirtualKeyCode::Cyrillic_shorti, - //ffi::XK_Cyrillic_ka => events::VirtualKeyCode::Cyrillic_ka, - //ffi::XK_Cyrillic_el => events::VirtualKeyCode::Cyrillic_el, - //ffi::XK_Cyrillic_em => events::VirtualKeyCode::Cyrillic_em, - //ffi::XK_Cyrillic_en => events::VirtualKeyCode::Cyrillic_en, - //ffi::XK_Cyrillic_o => events::VirtualKeyCode::Cyrillic_o, - //ffi::XK_Cyrillic_pe => events::VirtualKeyCode::Cyrillic_pe, - //ffi::XK_Cyrillic_ya => events::VirtualKeyCode::Cyrillic_ya, - //ffi::XK_Cyrillic_er => events::VirtualKeyCode::Cyrillic_er, - //ffi::XK_Cyrillic_es => events::VirtualKeyCode::Cyrillic_es, - //ffi::XK_Cyrillic_te => events::VirtualKeyCode::Cyrillic_te, - //ffi::XK_Cyrillic_u => events::VirtualKeyCode::Cyrillic_u, - //ffi::XK_Cyrillic_zhe => events::VirtualKeyCode::Cyrillic_zhe, - //ffi::XK_Cyrillic_ve => events::VirtualKeyCode::Cyrillic_ve, - //ffi::XK_Cyrillic_softsign => events::VirtualKeyCode::Cyrillic_softsign, - //ffi::XK_Cyrillic_yeru => events::VirtualKeyCode::Cyrillic_yeru, - //ffi::XK_Cyrillic_ze => events::VirtualKeyCode::Cyrillic_ze, - //ffi::XK_Cyrillic_sha => events::VirtualKeyCode::Cyrillic_sha, - //ffi::XK_Cyrillic_e => events::VirtualKeyCode::Cyrillic_e, - //ffi::XK_Cyrillic_shcha => events::VirtualKeyCode::Cyrillic_shcha, - //ffi::XK_Cyrillic_che => events::VirtualKeyCode::Cyrillic_che, - //ffi::XK_Cyrillic_hardsign => events::VirtualKeyCode::Cyrillic_hardsign, - //ffi::XK_Cyrillic_YU => events::VirtualKeyCode::Cyrillic_yu, - //ffi::XK_Cyrillic_A => events::VirtualKeyCode::Cyrillic_a, - //ffi::XK_Cyrillic_BE => events::VirtualKeyCode::Cyrillic_be, - //ffi::XK_Cyrillic_TSE => events::VirtualKeyCode::Cyrillic_tse, - //ffi::XK_Cyrillic_DE => events::VirtualKeyCode::Cyrillic_de, - //ffi::XK_Cyrillic_IE => events::VirtualKeyCode::Cyrillic_ie, - //ffi::XK_Cyrillic_EF => events::VirtualKeyCode::Cyrillic_ef, - //ffi::XK_Cyrillic_GHE => events::VirtualKeyCode::Cyrillic_ghe, - //ffi::XK_Cyrillic_HA => events::VirtualKeyCode::Cyrillic_ha, - //ffi::XK_Cyrillic_I => events::VirtualKeyCode::Cyrillic_i, - //ffi::XK_Cyrillic_SHORTI => events::VirtualKeyCode::Cyrillic_shorti, - //ffi::XK_Cyrillic_KA => events::VirtualKeyCode::Cyrillic_ka, - //ffi::XK_Cyrillic_EL => events::VirtualKeyCode::Cyrillic_el, - //ffi::XK_Cyrillic_EM => events::VirtualKeyCode::Cyrillic_em, - //ffi::XK_Cyrillic_EN => events::VirtualKeyCode::Cyrillic_en, - //ffi::XK_Cyrillic_O => events::VirtualKeyCode::Cyrillic_o, - //ffi::XK_Cyrillic_PE => events::VirtualKeyCode::Cyrillic_pe, - //ffi::XK_Cyrillic_YA => events::VirtualKeyCode::Cyrillic_ya, - //ffi::XK_Cyrillic_ER => events::VirtualKeyCode::Cyrillic_er, - //ffi::XK_Cyrillic_ES => events::VirtualKeyCode::Cyrillic_es, - //ffi::XK_Cyrillic_TE => events::VirtualKeyCode::Cyrillic_te, - //ffi::XK_Cyrillic_U => events::VirtualKeyCode::Cyrillic_u, - //ffi::XK_Cyrillic_ZHE => events::VirtualKeyCode::Cyrillic_zhe, - //ffi::XK_Cyrillic_VE => events::VirtualKeyCode::Cyrillic_ve, - //ffi::XK_Cyrillic_SOFTSIGN => events::VirtualKeyCode::Cyrillic_softsign, - //ffi::XK_Cyrillic_YERU => events::VirtualKeyCode::Cyrillic_yeru, - //ffi::XK_Cyrillic_ZE => events::VirtualKeyCode::Cyrillic_ze, - //ffi::XK_Cyrillic_SHA => events::VirtualKeyCode::Cyrillic_sha, - //ffi::XK_Cyrillic_E => events::VirtualKeyCode::Cyrillic_e, - //ffi::XK_Cyrillic_SHCHA => events::VirtualKeyCode::Cyrillic_shcha, - //ffi::XK_Cyrillic_CHE => events::VirtualKeyCode::Cyrillic_che, - //ffi::XK_Cyrillic_HARDSIGN => events::VirtualKeyCode::Cyrillic_hardsign, - //ffi::XK_Greek_ALPHAaccent => events::VirtualKeyCode::Greek_alphaaccent, - //ffi::XK_Greek_EPSILONaccent => events::VirtualKeyCode::Greek_epsilonaccent, - //ffi::XK_Greek_ETAaccent => events::VirtualKeyCode::Greek_etaaccent, - //ffi::XK_Greek_IOTAaccent => events::VirtualKeyCode::Greek_iotaaccent, - //ffi::XK_Greek_IOTAdiaeresis => events::VirtualKeyCode::Greek_iotadiaeresis, - //ffi::XK_Greek_OMICRONaccent => events::VirtualKeyCode::Greek_omicronaccent, - //ffi::XK_Greek_UPSILONaccent => events::VirtualKeyCode::Greek_upsilonaccent, - //ffi::XK_Greek_UPSILONdieresis => events::VirtualKeyCode::Greek_upsilondieresis, - //ffi::XK_Greek_OMEGAaccent => events::VirtualKeyCode::Greek_omegaaccent, - //ffi::XK_Greek_accentdieresis => events::VirtualKeyCode::Greek_accentdieresis, - //ffi::XK_Greek_horizbar => events::VirtualKeyCode::Greek_horizbar, - //ffi::XK_Greek_alphaaccent => events::VirtualKeyCode::Greek_alphaaccent, - //ffi::XK_Greek_epsilonaccent => events::VirtualKeyCode::Greek_epsilonaccent, - //ffi::XK_Greek_etaaccent => events::VirtualKeyCode::Greek_etaaccent, - //ffi::XK_Greek_iotaaccent => events::VirtualKeyCode::Greek_iotaaccent, - //ffi::XK_Greek_iotadieresis => events::VirtualKeyCode::Greek_iotadieresis, - //ffi::XK_Greek_iotaaccentdieresis => events::VirtualKeyCode::Greek_iotaaccentdieresis, - //ffi::XK_Greek_omicronaccent => events::VirtualKeyCode::Greek_omicronaccent, - //ffi::XK_Greek_upsilonaccent => events::VirtualKeyCode::Greek_upsilonaccent, - //ffi::XK_Greek_upsilondieresis => events::VirtualKeyCode::Greek_upsilondieresis, - //ffi::XK_Greek_upsilonaccentdieresis => events::VirtualKeyCode::Greek_upsilonaccentdieresis, - //ffi::XK_Greek_omegaaccent => events::VirtualKeyCode::Greek_omegaaccent, - //ffi::XK_Greek_ALPHA => events::VirtualKeyCode::Greek_alpha, - //ffi::XK_Greek_BETA => events::VirtualKeyCode::Greek_beta, - //ffi::XK_Greek_GAMMA => events::VirtualKeyCode::Greek_gamma, - //ffi::XK_Greek_DELTA => events::VirtualKeyCode::Greek_delta, - //ffi::XK_Greek_EPSILON => events::VirtualKeyCode::Greek_epsilon, - //ffi::XK_Greek_ZETA => events::VirtualKeyCode::Greek_zeta, - //ffi::XK_Greek_ETA => events::VirtualKeyCode::Greek_eta, - //ffi::XK_Greek_THETA => events::VirtualKeyCode::Greek_theta, - //ffi::XK_Greek_IOTA => events::VirtualKeyCode::Greek_iota, - //ffi::XK_Greek_KAPPA => events::VirtualKeyCode::Greek_kappa, - //ffi::XK_Greek_LAMDA => events::VirtualKeyCode::Greek_lamda, - //ffi::XK_Greek_LAMBDA => events::VirtualKeyCode::Greek_lambda, - //ffi::XK_Greek_MU => events::VirtualKeyCode::Greek_mu, - //ffi::XK_Greek_NU => events::VirtualKeyCode::Greek_nu, - //ffi::XK_Greek_XI => events::VirtualKeyCode::Greek_xi, - //ffi::XK_Greek_OMICRON => events::VirtualKeyCode::Greek_omicron, - //ffi::XK_Greek_PI => events::VirtualKeyCode::Greek_pi, - //ffi::XK_Greek_RHO => events::VirtualKeyCode::Greek_rho, - //ffi::XK_Greek_SIGMA => events::VirtualKeyCode::Greek_sigma, - //ffi::XK_Greek_TAU => events::VirtualKeyCode::Greek_tau, - //ffi::XK_Greek_UPSILON => events::VirtualKeyCode::Greek_upsilon, - //ffi::XK_Greek_PHI => events::VirtualKeyCode::Greek_phi, - //ffi::XK_Greek_CHI => events::VirtualKeyCode::Greek_chi, - //ffi::XK_Greek_PSI => events::VirtualKeyCode::Greek_psi, - //ffi::XK_Greek_OMEGA => events::VirtualKeyCode::Greek_omega, - //ffi::XK_Greek_alpha => events::VirtualKeyCode::Greek_alpha, - //ffi::XK_Greek_beta => events::VirtualKeyCode::Greek_beta, - //ffi::XK_Greek_gamma => events::VirtualKeyCode::Greek_gamma, - //ffi::XK_Greek_delta => events::VirtualKeyCode::Greek_delta, - //ffi::XK_Greek_epsilon => events::VirtualKeyCode::Greek_epsilon, - //ffi::XK_Greek_zeta => events::VirtualKeyCode::Greek_zeta, - //ffi::XK_Greek_eta => events::VirtualKeyCode::Greek_eta, - //ffi::XK_Greek_theta => events::VirtualKeyCode::Greek_theta, - //ffi::XK_Greek_iota => events::VirtualKeyCode::Greek_iota, - //ffi::XK_Greek_kappa => events::VirtualKeyCode::Greek_kappa, - //ffi::XK_Greek_lamda => events::VirtualKeyCode::Greek_lamda, - //ffi::XK_Greek_lambda => events::VirtualKeyCode::Greek_lambda, - //ffi::XK_Greek_mu => events::VirtualKeyCode::Greek_mu, - //ffi::XK_Greek_nu => events::VirtualKeyCode::Greek_nu, - //ffi::XK_Greek_xi => events::VirtualKeyCode::Greek_xi, - //ffi::XK_Greek_omicron => events::VirtualKeyCode::Greek_omicron, - //ffi::XK_Greek_pi => events::VirtualKeyCode::Greek_pi, - //ffi::XK_Greek_rho => events::VirtualKeyCode::Greek_rho, - //ffi::XK_Greek_sigma => events::VirtualKeyCode::Greek_sigma, - //ffi::XK_Greek_finalsmallsigma => events::VirtualKeyCode::Greek_finalsmallsigma, - //ffi::XK_Greek_tau => events::VirtualKeyCode::Greek_tau, - //ffi::XK_Greek_upsilon => events::VirtualKeyCode::Greek_upsilon, - //ffi::XK_Greek_phi => events::VirtualKeyCode::Greek_phi, - //ffi::XK_Greek_chi => events::VirtualKeyCode::Greek_chi, - //ffi::XK_Greek_psi => events::VirtualKeyCode::Greek_psi, - //ffi::XK_Greek_omega => events::VirtualKeyCode::Greek_omega, - //ffi::XK_Greek_switch => events::VirtualKeyCode::Greek_switch, - //ffi::XK_leftradical => events::VirtualKeyCode::Leftradical, - //ffi::XK_topleftradical => events::VirtualKeyCode::Topleftradical, - //ffi::XK_horizconnector => events::VirtualKeyCode::Horizconnector, - //ffi::XK_topintegral => events::VirtualKeyCode::Topintegral, - //ffi::XK_botintegral => events::VirtualKeyCode::Botintegral, - //ffi::XK_vertconnector => events::VirtualKeyCode::Vertconnector, - //ffi::XK_topleftsqbracket => events::VirtualKeyCode::Topleftsqbracket, - //ffi::XK_botleftsqbracket => events::VirtualKeyCode::Botleftsqbracket, - //ffi::XK_toprightsqbracket => events::VirtualKeyCode::Toprightsqbracket, - //ffi::XK_botrightsqbracket => events::VirtualKeyCode::Botrightsqbracket, - //ffi::XK_topleftparens => events::VirtualKeyCode::Topleftparens, - //ffi::XK_botleftparens => events::VirtualKeyCode::Botleftparens, - //ffi::XK_toprightparens => events::VirtualKeyCode::Toprightparens, - //ffi::XK_botrightparens => events::VirtualKeyCode::Botrightparens, - //ffi::XK_leftmiddlecurlybrace => events::VirtualKeyCode::Leftmiddlecurlybrace, - //ffi::XK_rightmiddlecurlybrace => events::VirtualKeyCode::Rightmiddlecurlybrace, - //ffi::XK_topleftsummation => events::VirtualKeyCode::Topleftsummation, - //ffi::XK_botleftsummation => events::VirtualKeyCode::Botleftsummation, - //ffi::XK_topvertsummationconnector => events::VirtualKeyCode::Topvertsummationconnector, - //ffi::XK_botvertsummationconnector => events::VirtualKeyCode::Botvertsummationconnector, - //ffi::XK_toprightsummation => events::VirtualKeyCode::Toprightsummation, - //ffi::XK_botrightsummation => events::VirtualKeyCode::Botrightsummation, - //ffi::XK_rightmiddlesummation => events::VirtualKeyCode::Rightmiddlesummation, - //ffi::XK_lessthanequal => events::VirtualKeyCode::Lessthanequal, - //ffi::XK_notequal => events::VirtualKeyCode::Notequal, - //ffi::XK_greaterthanequal => events::VirtualKeyCode::Greaterthanequal, - //ffi::XK_integral => events::VirtualKeyCode::Integral, - //ffi::XK_therefore => events::VirtualKeyCode::Therefore, - //ffi::XK_variation => events::VirtualKeyCode::Variation, - //ffi::XK_infinity => events::VirtualKeyCode::Infinity, - //ffi::XK_nabla => events::VirtualKeyCode::Nabla, - //ffi::XK_approximate => events::VirtualKeyCode::Approximate, - //ffi::XK_similarequal => events::VirtualKeyCode::Similarequal, - //ffi::XK_ifonlyif => events::VirtualKeyCode::Ifonlyif, - //ffi::XK_implies => events::VirtualKeyCode::Implies, - //ffi::XK_identical => events::VirtualKeyCode::Identical, - //ffi::XK_radical => events::VirtualKeyCode::Radical, - //ffi::XK_includedin => events::VirtualKeyCode::Includedin, - //ffi::XK_includes => events::VirtualKeyCode::Includes, - //ffi::XK_intersection => events::VirtualKeyCode::Intersection, - //ffi::XK_union => events::VirtualKeyCode::Union, - //ffi::XK_logicaland => events::VirtualKeyCode::Logicaland, - //ffi::XK_logicalor => events::VirtualKeyCode::Logicalor, - //ffi::XK_partialderivative => events::VirtualKeyCode::Partialderivative, - //ffi::XK_function => events::VirtualKeyCode::Function, - //ffi::XK_leftarrow => events::VirtualKeyCode::Leftarrow, - //ffi::XK_uparrow => events::VirtualKeyCode::Uparrow, - //ffi::XK_rightarrow => events::VirtualKeyCode::Rightarrow, - //ffi::XK_downarrow => events::VirtualKeyCode::Downarrow, - //ffi::XK_blank => events::VirtualKeyCode::Blank, - //ffi::XK_soliddiamond => events::VirtualKeyCode::Soliddiamond, - //ffi::XK_checkerboard => events::VirtualKeyCode::Checkerboard, - //ffi::XK_ht => events::VirtualKeyCode::Ht, - //ffi::XK_ff => events::VirtualKeyCode::Ff, - //ffi::XK_cr => events::VirtualKeyCode::Cr, - //ffi::XK_lf => events::VirtualKeyCode::Lf, - //ffi::XK_nl => events::VirtualKeyCode::Nl, - //ffi::XK_vt => events::VirtualKeyCode::Vt, - //ffi::XK_lowrightcorner => events::VirtualKeyCode::Lowrightcorner, - //ffi::XK_uprightcorner => events::VirtualKeyCode::Uprightcorner, - //ffi::XK_upleftcorner => events::VirtualKeyCode::Upleftcorner, - //ffi::XK_lowleftcorner => events::VirtualKeyCode::Lowleftcorner, - //ffi::XK_crossinglines => events::VirtualKeyCode::Crossinglines, - //ffi::XK_horizlinescan1 => events::VirtualKeyCode::Horizlinescan1, - //ffi::XK_horizlinescan3 => events::VirtualKeyCode::Horizlinescan3, - //ffi::XK_horizlinescan5 => events::VirtualKeyCode::Horizlinescan5, - //ffi::XK_horizlinescan7 => events::VirtualKeyCode::Horizlinescan7, - //ffi::XK_horizlinescan9 => events::VirtualKeyCode::Horizlinescan9, - //ffi::XK_leftt => events::VirtualKeyCode::Leftt, - //ffi::XK_rightt => events::VirtualKeyCode::Rightt, - //ffi::XK_bott => events::VirtualKeyCode::Bott, - //ffi::XK_topt => events::VirtualKeyCode::Topt, - //ffi::XK_vertbar => events::VirtualKeyCode::Vertbar, - //ffi::XK_emspace => events::VirtualKeyCode::Emspace, - //ffi::XK_enspace => events::VirtualKeyCode::Enspace, - //ffi::XK_em3space => events::VirtualKeyCode::Em3space, - //ffi::XK_em4space => events::VirtualKeyCode::Em4space, - //ffi::XK_digitspace => events::VirtualKeyCode::Digitspace, - //ffi::XK_punctspace => events::VirtualKeyCode::Punctspace, - //ffi::XK_thinspace => events::VirtualKeyCode::Thinspace, - //ffi::XK_hairspace => events::VirtualKeyCode::Hairspace, - //ffi::XK_emdash => events::VirtualKeyCode::Emdash, - //ffi::XK_endash => events::VirtualKeyCode::Endash, - //ffi::XK_signifblank => events::VirtualKeyCode::Signifblank, - //ffi::XK_ellipsis => events::VirtualKeyCode::Ellipsis, - //ffi::XK_doubbaselinedot => events::VirtualKeyCode::Doubbaselinedot, - //ffi::XK_onethird => events::VirtualKeyCode::Onethird, - //ffi::XK_twothirds => events::VirtualKeyCode::Twothirds, - //ffi::XK_onefifth => events::VirtualKeyCode::Onefifth, - //ffi::XK_twofifths => events::VirtualKeyCode::Twofifths, - //ffi::XK_threefifths => events::VirtualKeyCode::Threefifths, - //ffi::XK_fourfifths => events::VirtualKeyCode::Fourfifths, - //ffi::XK_onesixth => events::VirtualKeyCode::Onesixth, - //ffi::XK_fivesixths => events::VirtualKeyCode::Fivesixths, - //ffi::XK_careof => events::VirtualKeyCode::Careof, - //ffi::XK_figdash => events::VirtualKeyCode::Figdash, - //ffi::XK_leftanglebracket => events::VirtualKeyCode::Leftanglebracket, - //ffi::XK_decimalpoint => events::VirtualKeyCode::Decimalpoint, - //ffi::XK_rightanglebracket => events::VirtualKeyCode::Rightanglebracket, - //ffi::XK_marker => events::VirtualKeyCode::Marker, - //ffi::XK_oneeighth => events::VirtualKeyCode::Oneeighth, - //ffi::XK_threeeighths => events::VirtualKeyCode::Threeeighths, - //ffi::XK_fiveeighths => events::VirtualKeyCode::Fiveeighths, - //ffi::XK_seveneighths => events::VirtualKeyCode::Seveneighths, - //ffi::XK_trademark => events::VirtualKeyCode::Trademark, - //ffi::XK_signaturemark => events::VirtualKeyCode::Signaturemark, - //ffi::XK_trademarkincircle => events::VirtualKeyCode::Trademarkincircle, - //ffi::XK_leftopentriangle => events::VirtualKeyCode::Leftopentriangle, - //ffi::XK_rightopentriangle => events::VirtualKeyCode::Rightopentriangle, - //ffi::XK_emopencircle => events::VirtualKeyCode::Emopencircle, - //ffi::XK_emopenrectangle => events::VirtualKeyCode::Emopenrectangle, - //ffi::XK_leftsinglequotemark => events::VirtualKeyCode::Leftsinglequotemark, - //ffi::XK_rightsinglequotemark => events::VirtualKeyCode::Rightsinglequotemark, - //ffi::XK_leftdoublequotemark => events::VirtualKeyCode::Leftdoublequotemark, - //ffi::XK_rightdoublequotemark => events::VirtualKeyCode::Rightdoublequotemark, - //ffi::XK_prescription => events::VirtualKeyCode::Prescription, - //ffi::XK_minutes => events::VirtualKeyCode::Minutes, - //ffi::XK_seconds => events::VirtualKeyCode::Seconds, - //ffi::XK_latincross => events::VirtualKeyCode::Latincross, - //ffi::XK_hexagram => events::VirtualKeyCode::Hexagram, - //ffi::XK_filledrectbullet => events::VirtualKeyCode::Filledrectbullet, - //ffi::XK_filledlefttribullet => events::VirtualKeyCode::Filledlefttribullet, - //ffi::XK_filledrighttribullet => events::VirtualKeyCode::Filledrighttribullet, - //ffi::XK_emfilledcircle => events::VirtualKeyCode::Emfilledcircle, - //ffi::XK_emfilledrect => events::VirtualKeyCode::Emfilledrect, - //ffi::XK_enopencircbullet => events::VirtualKeyCode::Enopencircbullet, - //ffi::XK_enopensquarebullet => events::VirtualKeyCode::Enopensquarebullet, - //ffi::XK_openrectbullet => events::VirtualKeyCode::Openrectbullet, - //ffi::XK_opentribulletup => events::VirtualKeyCode::Opentribulletup, - //ffi::XK_opentribulletdown => events::VirtualKeyCode::Opentribulletdown, - //ffi::XK_openstar => events::VirtualKeyCode::Openstar, - //ffi::XK_enfilledcircbullet => events::VirtualKeyCode::Enfilledcircbullet, - //ffi::XK_enfilledsqbullet => events::VirtualKeyCode::Enfilledsqbullet, - //ffi::XK_filledtribulletup => events::VirtualKeyCode::Filledtribulletup, - //ffi::XK_filledtribulletdown => events::VirtualKeyCode::Filledtribulletdown, - //ffi::XK_leftpointer => events::VirtualKeyCode::Leftpointer, - //ffi::XK_rightpointer => events::VirtualKeyCode::Rightpointer, - //ffi::XK_club => events::VirtualKeyCode::Club, - //ffi::XK_diamond => events::VirtualKeyCode::Diamond, - //ffi::XK_heart => events::VirtualKeyCode::Heart, - //ffi::XK_maltesecross => events::VirtualKeyCode::Maltesecross, - //ffi::XK_dagger => events::VirtualKeyCode::Dagger, - //ffi::XK_doubledagger => events::VirtualKeyCode::Doubledagger, - //ffi::XK_checkmark => events::VirtualKeyCode::Checkmark, - //ffi::XK_ballotcross => events::VirtualKeyCode::Ballotcross, - //ffi::XK_musicalsharp => events::VirtualKeyCode::Musicalsharp, - //ffi::XK_musicalflat => events::VirtualKeyCode::Musicalflat, - //ffi::XK_malesymbol => events::VirtualKeyCode::Malesymbol, - //ffi::XK_femalesymbol => events::VirtualKeyCode::Femalesymbol, - //ffi::XK_telephone => events::VirtualKeyCode::Telephone, - //ffi::XK_telephonerecorder => events::VirtualKeyCode::Telephonerecorder, - //ffi::XK_phonographcopyright => events::VirtualKeyCode::Phonographcopyright, - //ffi::XK_caret => events::VirtualKeyCode::Caret, - //ffi::XK_singlelowquotemark => events::VirtualKeyCode::Singlelowquotemark, - //ffi::XK_doublelowquotemark => events::VirtualKeyCode::Doublelowquotemark, - //ffi::XK_cursor => events::VirtualKeyCode::Cursor, - //ffi::XK_leftcaret => events::VirtualKeyCode::Leftcaret, - //ffi::XK_rightcaret => events::VirtualKeyCode::Rightcaret, - //ffi::XK_downcaret => events::VirtualKeyCode::Downcaret, - //ffi::XK_upcaret => events::VirtualKeyCode::Upcaret, - //ffi::XK_overbar => events::VirtualKeyCode::Overbar, - //ffi::XK_downtack => events::VirtualKeyCode::Downtack, - //ffi::XK_upshoe => events::VirtualKeyCode::Upshoe, - //ffi::XK_downstile => events::VirtualKeyCode::Downstile, - //ffi::XK_underbar => events::VirtualKeyCode::Underbar, - //ffi::XK_jot => events::VirtualKeyCode::Jot, - //ffi::XK_quad => events::VirtualKeyCode::Quad, - //ffi::XK_uptack => events::VirtualKeyCode::Uptack, - //ffi::XK_circle => events::VirtualKeyCode::Circle, - //ffi::XK_upstile => events::VirtualKeyCode::Upstile, - //ffi::XK_downshoe => events::VirtualKeyCode::Downshoe, - //ffi::XK_rightshoe => events::VirtualKeyCode::Rightshoe, - //ffi::XK_leftshoe => events::VirtualKeyCode::Leftshoe, - //ffi::XK_lefttack => events::VirtualKeyCode::Lefttack, - //ffi::XK_righttack => events::VirtualKeyCode::Righttack, - //ffi::XK_hebrew_doublelowline => events::VirtualKeyCode::Hebrew_doublelowline, - //ffi::XK_hebrew_aleph => events::VirtualKeyCode::Hebrew_aleph, - //ffi::XK_hebrew_bet => events::VirtualKeyCode::Hebrew_bet, - //ffi::XK_hebrew_beth => events::VirtualKeyCode::Hebrew_beth, - //ffi::XK_hebrew_gimel => events::VirtualKeyCode::Hebrew_gimel, - //ffi::XK_hebrew_gimmel => events::VirtualKeyCode::Hebrew_gimmel, - //ffi::XK_hebrew_dalet => events::VirtualKeyCode::Hebrew_dalet, - //ffi::XK_hebrew_daleth => events::VirtualKeyCode::Hebrew_daleth, - //ffi::XK_hebrew_he => events::VirtualKeyCode::Hebrew_he, - //ffi::XK_hebrew_waw => events::VirtualKeyCode::Hebrew_waw, - //ffi::XK_hebrew_zain => events::VirtualKeyCode::Hebrew_zain, - //ffi::XK_hebrew_zayin => events::VirtualKeyCode::Hebrew_zayin, - //ffi::XK_hebrew_chet => events::VirtualKeyCode::Hebrew_chet, - //ffi::XK_hebrew_het => events::VirtualKeyCode::Hebrew_het, - //ffi::XK_hebrew_tet => events::VirtualKeyCode::Hebrew_tet, - //ffi::XK_hebrew_teth => events::VirtualKeyCode::Hebrew_teth, - //ffi::XK_hebrew_yod => events::VirtualKeyCode::Hebrew_yod, - //ffi::XK_hebrew_finalkaph => events::VirtualKeyCode::Hebrew_finalkaph, - //ffi::XK_hebrew_kaph => events::VirtualKeyCode::Hebrew_kaph, - //ffi::XK_hebrew_lamed => events::VirtualKeyCode::Hebrew_lamed, - //ffi::XK_hebrew_finalmem => events::VirtualKeyCode::Hebrew_finalmem, - //ffi::XK_hebrew_mem => events::VirtualKeyCode::Hebrew_mem, - //ffi::XK_hebrew_finalnun => events::VirtualKeyCode::Hebrew_finalnun, - //ffi::XK_hebrew_nun => events::VirtualKeyCode::Hebrew_nun, - //ffi::XK_hebrew_samech => events::VirtualKeyCode::Hebrew_samech, - //ffi::XK_hebrew_samekh => events::VirtualKeyCode::Hebrew_samekh, - //ffi::XK_hebrew_ayin => events::VirtualKeyCode::Hebrew_ayin, - //ffi::XK_hebrew_finalpe => events::VirtualKeyCode::Hebrew_finalpe, - //ffi::XK_hebrew_pe => events::VirtualKeyCode::Hebrew_pe, - //ffi::XK_hebrew_finalzade => events::VirtualKeyCode::Hebrew_finalzade, - //ffi::XK_hebrew_finalzadi => events::VirtualKeyCode::Hebrew_finalzadi, - //ffi::XK_hebrew_zade => events::VirtualKeyCode::Hebrew_zade, - //ffi::XK_hebrew_zadi => events::VirtualKeyCode::Hebrew_zadi, - //ffi::XK_hebrew_qoph => events::VirtualKeyCode::Hebrew_qoph, - //ffi::XK_hebrew_kuf => events::VirtualKeyCode::Hebrew_kuf, - //ffi::XK_hebrew_resh => events::VirtualKeyCode::Hebrew_resh, - //ffi::XK_hebrew_shin => events::VirtualKeyCode::Hebrew_shin, - //ffi::XK_hebrew_taw => events::VirtualKeyCode::Hebrew_taw, - //ffi::XK_hebrew_taf => events::VirtualKeyCode::Hebrew_taf, - //ffi::XK_Hebrew_switch => events::VirtualKeyCode::Hebrew_switch, - ffi::XF86XK_Back => VirtualKeyCode::NavigateBackward, - ffi::XF86XK_Forward => VirtualKeyCode::NavigateForward, - ffi::XF86XK_Copy => VirtualKeyCode::Copy, - ffi::XF86XK_Paste => VirtualKeyCode::Paste, - ffi::XF86XK_Cut => VirtualKeyCode::Cut, - _ => return None - }) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ffi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ffi.rs deleted file mode 100644 index 964b0ce..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ffi.rs +++ /dev/null @@ -1,8 +0,0 @@ -pub use x11_dl::keysym::*; -pub use x11_dl::xcursor::*; -pub use x11_dl::xlib::*; -pub use x11_dl::xinput::*; -pub use x11_dl::xinput2::*; -pub use x11_dl::xlib_xcb::*; -pub use x11_dl::error::OpenError; -pub use x11_dl::xrandr::*; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/monitor.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/monitor.rs deleted file mode 100644 index d6309f6..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/monitor.rs +++ /dev/null @@ -1,269 +0,0 @@ -use std::os::raw::*; - -use parking_lot::Mutex; - -use {PhysicalPosition, PhysicalSize}; -use super::{util, XConnection, XError}; -use super::ffi::{ - RRCrtcChangeNotifyMask, - RROutputPropertyNotifyMask, - RRScreenChangeNotifyMask, - True, - Window, - XRRScreenResources, -}; - -// Used to test XRandR < 1.5 code path. This should always be committed as false. -const FORCE_RANDR_COMPAT: bool = false; -// Also used for testing. This should always be committed as false. -const DISABLE_MONITOR_LIST_CACHING: bool = false; - -lazy_static! { - static ref XRANDR_VERSION: Mutex> = Mutex::default(); - static ref MONITORS: Mutex>> = Mutex::default(); -} - -fn version_is_at_least(major: c_int, minor: c_int) -> bool { - if let Some((avail_major, avail_minor)) = *XRANDR_VERSION.lock() { - if avail_major == major { - avail_minor >= minor - } else { - avail_major > major - } - } else { - unreachable!(); - } -} - -pub fn invalidate_cached_monitor_list() -> Option> { - // We update this lazily. - (*MONITORS.lock()).take() -} - -#[derive(Debug, Clone)] -pub struct MonitorId { - /// The actual id - id: u32, - /// The name of the monitor - pub(crate) name: String, - /// The size of the monitor - dimensions: (u32, u32), - /// The position of the monitor in the X screen - position: (i32, i32), - /// If the monitor is the primary one - primary: bool, - /// The DPI scale factor - pub(crate) hidpi_factor: f64, - /// Used to determine which windows are on this monitor - pub(crate) rect: util::AaRect, -} - -impl MonitorId { - fn from_repr( - xconn: &XConnection, - resources: *mut XRRScreenResources, - id: u32, - repr: util::MonitorRepr, - primary: bool, - ) -> Option { - let (name, hidpi_factor) = unsafe { xconn.get_output_info(resources, &repr)? }; - let (dimensions, position) = unsafe { (repr.get_dimensions(), repr.get_position()) }; - let rect = util::AaRect::new(position, dimensions); - Some(MonitorId { - id, - name, - hidpi_factor, - dimensions, - position, - primary, - rect, - }) - } - - pub fn get_name(&self) -> Option { - Some(self.name.clone()) - } - - #[inline] - pub fn get_native_identifier(&self) -> u32 { - self.id as u32 - } - - pub fn get_dimensions(&self) -> PhysicalSize { - self.dimensions.into() - } - - pub fn get_position(&self) -> PhysicalPosition { - self.position.into() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.hidpi_factor - } -} - -impl XConnection { - pub fn get_monitor_for_window(&self, window_rect: Option) -> MonitorId { - let monitors = self.get_available_monitors(); - let default = monitors - .get(0) - .expect("[winit] Failed to find any monitors using XRandR."); - - let window_rect = match window_rect { - Some(rect) => rect, - None => return default.to_owned(), - }; - - let mut largest_overlap = 0; - let mut matched_monitor = default; - for monitor in &monitors { - let overlapping_area = window_rect.get_overlapping_area(&monitor.rect); - if overlapping_area > largest_overlap { - largest_overlap = overlapping_area; - matched_monitor = &monitor; - } - } - - matched_monitor.to_owned() - } - - fn query_monitor_list(&self) -> Vec { - unsafe { - let root = (self.xlib.XDefaultRootWindow)(self.display); - // WARNING: this function is supposedly very slow, on the order of hundreds of ms. - // Upon failure, `resources` will be null. - let resources = (self.xrandr.XRRGetScreenResources)(self.display, root); - if resources.is_null() { - panic!("[winit] `XRRGetScreenResources` returned NULL. That should only happen if the root window doesn't exist."); - } - - let mut available; - let mut has_primary = false; - - if self.xrandr_1_5.is_some() && version_is_at_least(1, 5) && !FORCE_RANDR_COMPAT { - // We're in XRandR >= 1.5, enumerate monitors. This supports things like MST and - // videowalls. - let xrandr_1_5 = self.xrandr_1_5.as_ref().unwrap(); - let mut monitor_count = 0; - let monitors = (xrandr_1_5.XRRGetMonitors)(self.display, root, 1, &mut monitor_count); - assert!(monitor_count >= 0); - available = Vec::with_capacity(monitor_count as usize); - for monitor_index in 0..monitor_count { - let monitor = monitors.offset(monitor_index as isize); - let is_primary = (*monitor).primary != 0; - has_primary |= is_primary; - MonitorId::from_repr( - self, - resources, - monitor_index as u32, - monitor.into(), - is_primary, - ).map(|monitor_id| available.push(monitor_id)); - } - (xrandr_1_5.XRRFreeMonitors)(monitors); - } else { - // We're in XRandR < 1.5, enumerate CRTCs. Everything will work except MST and - // videowall setups will also show monitors that aren't in the logical groups the user - // cares about. - let primary = (self.xrandr.XRRGetOutputPrimary)(self.display, root); - available = Vec::with_capacity((*resources).ncrtc as usize); - for crtc_index in 0..(*resources).ncrtc { - let crtc_id = *((*resources).crtcs.offset(crtc_index as isize)); - let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id); - let is_active = (*crtc).width > 0 && (*crtc).height > 0 && (*crtc).noutput > 0; - if is_active { - let crtc = util::MonitorRepr::from(crtc); - let is_primary = crtc.get_output() == primary; - has_primary |= is_primary; - MonitorId::from_repr( - self, - resources, - crtc_id as u32, - crtc, - is_primary, - ).map(|monitor_id| available.push(monitor_id)); - } - (self.xrandr.XRRFreeCrtcInfo)(crtc); - } - } - - // If no monitors were detected as being primary, we just pick one ourselves! - if !has_primary { - if let Some(ref mut fallback) = available.first_mut() { - // Setting this here will come in handy if we ever add an `is_primary` method. - fallback.primary = true; - } - } - - (self.xrandr.XRRFreeScreenResources)(resources); - available - } - } - - pub fn get_available_monitors(&self) -> Vec { - let mut monitors_lock = MONITORS.lock(); - (*monitors_lock) - .as_ref() - .cloned() - .or_else(|| { - let monitors = Some(self.query_monitor_list()); - if !DISABLE_MONITOR_LIST_CACHING { - (*monitors_lock) = monitors.clone(); - } - monitors - }) - .unwrap() - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - self.get_available_monitors() - .into_iter() - .find(|monitor| monitor.primary) - .expect("[winit] Failed to find any monitors using XRandR.") - } - - pub fn select_xrandr_input(&self, root: Window) -> Result { - { - let mut version_lock = XRANDR_VERSION.lock(); - if version_lock.is_none() { - let mut major = 0; - let mut minor = 0; - let has_extension = unsafe { - (self.xrandr.XRRQueryVersion)( - self.display, - &mut major, - &mut minor, - ) - }; - if has_extension != True { - panic!("[winit] XRandR extension not available."); - } - *version_lock = Some((major, minor)); - } - } - - let mut event_offset = 0; - let mut error_offset = 0; - let status = unsafe { - (self.xrandr.XRRQueryExtension)( - self.display, - &mut event_offset, - &mut error_offset, - ) - }; - - if status != True { - self.check_errors()?; - unreachable!("[winit] `XRRQueryExtension` failed but no error was received."); - } - - let mask = RRCrtcChangeNotifyMask - | RROutputPropertyNotifyMask - | RRScreenChangeNotifyMask; - unsafe { (self.xrandr.XRRSelectInput)(self.display, root, mask) }; - - Ok(event_offset) - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/client_msg.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/client_msg.rs deleted file mode 100644 index 399db4f..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/client_msg.rs +++ /dev/null @@ -1,95 +0,0 @@ -use super::*; - -pub type ClientMsgPayload = [c_long; 5]; - -impl XConnection { - pub fn send_event>( - &self, - target_window: c_ulong, - event_mask: Option, - event: T, - ) -> Flusher { - let event_mask = event_mask.unwrap_or(ffi::NoEventMask); - unsafe { - (self.xlib.XSendEvent)( - self.display, - target_window, - ffi::False, - event_mask, - &mut event.into(), - ); - } - Flusher::new(self) - } - - pub fn send_client_msg( - &self, - window: c_ulong, // The window this is "about"; not necessarily this window - target_window: c_ulong, // The window we're sending to - message_type: ffi::Atom, - event_mask: Option, - data: ClientMsgPayload, - ) -> Flusher { - let mut event: ffi::XClientMessageEvent = unsafe { mem::uninitialized() }; - event.type_ = ffi::ClientMessage; - event.display = self.display; - event.window = window; - event.message_type = message_type; - event.format = c_long::FORMAT as c_int; - event.data = unsafe { mem::transmute(data) }; - self.send_event(target_window, event_mask, event) - } - - // Prepare yourself for the ultimate in unsafety! - // You should favor `send_client_msg` whenever possible, but some protocols (i.e. startup notification) require you - // to send more than one message worth of data. - pub fn send_client_msg_multi( - &self, - window: c_ulong, // The window this is "about"; not necessarily this window - target_window: c_ulong, // The window we're sending to - message_type: ffi::Atom, - event_mask: Option, - data: &[T], - ) -> Flusher { - let format = T::FORMAT; - let size_of_t = mem::size_of::(); - debug_assert_eq!(size_of_t, format.get_actual_size()); - let mut event: ffi::XClientMessageEvent = unsafe { mem::uninitialized() }; - event.type_ = ffi::ClientMessage; - event.display = self.display; - event.window = window; - event.message_type = message_type; - event.format = format as c_int; - - let t_per_payload = format.get_payload_size() / size_of_t; - assert!(t_per_payload > 0); - let payload_count = data.len() / t_per_payload; - let payload_remainder = data.len() % t_per_payload; - let payload_ptr = data.as_ptr() as *const ClientMsgPayload; - - let mut payload_index = 0; - while payload_index < payload_count { - let payload = unsafe { payload_ptr.offset(payload_index as isize) }; - payload_index += 1; - event.data = unsafe { mem::transmute(*payload) }; - self.send_event(target_window, event_mask, &event).queue(); - } - - if payload_remainder > 0 { - let mut payload: ClientMsgPayload = [0; 5]; - let t_payload = payload.as_mut_ptr() as *mut T; - let invalid_payload = unsafe { payload_ptr.offset(payload_index as isize) }; - let invalid_t_payload = invalid_payload as *const T; - let mut t_index = 0; - while t_index < payload_remainder { - let valid_t = unsafe { invalid_t_payload.offset(t_index as isize) }; - unsafe { (*t_payload.offset(t_index as isize)) = (*valid_t).clone() }; - t_index += 1; - } - event.data = unsafe { mem::transmute(payload) }; - self.send_event(target_window, event_mask, &event).queue(); - } - - Flusher::new(self) - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/input.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/input.rs deleted file mode 100644 index 4b75df2..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/input.rs +++ /dev/null @@ -1,159 +0,0 @@ -use std::str; - -use super::*; -use events::ModifiersState; - -pub const VIRTUAL_CORE_POINTER: c_int = 2; -pub const VIRTUAL_CORE_KEYBOARD: c_int = 3; - -// A base buffer size of 1kB uses a negligible amount of RAM while preventing us from having to -// re-allocate (and make another round-trip) in the *vast* majority of cases. -// To test if `lookup_utf8` works correctly, set this to 1. -const TEXT_BUFFER_SIZE: usize = 1024; - -impl From for ModifiersState { - fn from(mods: ffi::XIModifierState) -> Self { - let state = mods.effective as c_uint; - ModifiersState { - alt: state & ffi::Mod1Mask != 0, - shift: state & ffi::ShiftMask != 0, - ctrl: state & ffi::ControlMask != 0, - logo: state & ffi::Mod4Mask != 0, - } - } -} - -pub struct PointerState<'a> { - xconn: &'a XConnection, - root: ffi::Window, - child: ffi::Window, - pub root_x: c_double, - pub root_y: c_double, - win_x: c_double, - win_y: c_double, - buttons: ffi::XIButtonState, - modifiers: ffi::XIModifierState, - group: ffi::XIGroupState, - relative_to_window: bool, -} - -impl<'a> PointerState<'a> { - pub fn get_modifier_state(&self) -> ModifiersState { - self.modifiers.into() - } -} - -impl<'a> Drop for PointerState<'a> { - fn drop(&mut self) { - if !self.buttons.mask.is_null() { - unsafe { - // This is why you need to read the docs carefully... - (self.xconn.xlib.XFree)(self.buttons.mask as _); - } - } - } -} - -impl XConnection { - pub fn select_xinput_events(&self, window: c_ulong, device_id: c_int, mask: i32) -> Flusher { - let mut event_mask = ffi::XIEventMask { - deviceid: device_id, - mask: &mask as *const _ as *mut c_uchar, - mask_len: mem::size_of_val(&mask) as c_int, - }; - unsafe { - (self.xinput2.XISelectEvents)( - self.display, - window, - &mut event_mask as *mut ffi::XIEventMask, - 1, // number of masks to read from pointer above - ); - } - Flusher::new(self) - } - - #[allow(dead_code)] - pub fn select_xkb_events(&self, device_id: c_uint, mask: c_ulong) -> Option { - let status = unsafe { - (self.xlib.XkbSelectEvents)( - self.display, - device_id, - mask, - mask, - ) - }; - if status == ffi::True { - Some(Flusher::new(self)) - } else { - None - } - } - - pub fn query_pointer(&self, window: ffi::Window, device_id: c_int) -> Result { - unsafe { - let mut pointer_state: PointerState = mem::uninitialized(); - pointer_state.xconn = self; - pointer_state.relative_to_window = (self.xinput2.XIQueryPointer)( - self.display, - device_id, - window, - &mut pointer_state.root, - &mut pointer_state.child, - &mut pointer_state.root_x, - &mut pointer_state.root_y, - &mut pointer_state.win_x, - &mut pointer_state.win_y, - &mut pointer_state.buttons, - &mut pointer_state.modifiers, - &mut pointer_state.group, - ) == ffi::True; - if let Err(err) = self.check_errors() { - // Running the destrutor would be bad news for us... - mem::forget(pointer_state); - Err(err) - } else { - Ok(pointer_state) - } - } - } - - fn lookup_utf8_inner( - &self, - ic: ffi::XIC, - key_event: &mut ffi::XKeyEvent, - buffer: &mut [u8], - ) -> (ffi::KeySym, ffi::Status, c_int) { - let mut keysym: ffi::KeySym = 0; - let mut status: ffi::Status = 0; - let count = unsafe { - (self.xlib.Xutf8LookupString)( - ic, - key_event, - buffer.as_mut_ptr() as *mut c_char, - buffer.len() as c_int, - &mut keysym, - &mut status, - ) - }; - (keysym, status, count) - } - - pub fn lookup_utf8(&self, ic: ffi::XIC, key_event: &mut ffi::XKeyEvent) -> String { - let mut buffer: [u8; TEXT_BUFFER_SIZE] = unsafe { mem::uninitialized() }; - let (_, status, count) = self.lookup_utf8_inner(ic, key_event, &mut buffer); - // The buffer overflowed, so we'll make a new one on the heap. - if status == ffi::XBufferOverflow { - let mut buffer = Vec::with_capacity(count as usize); - unsafe { buffer.set_len(count as usize) }; - let (_, _, new_count) = self.lookup_utf8_inner(ic, key_event, &mut buffer); - debug_assert_eq!(count, new_count); - str::from_utf8(&buffer[..count as usize]) - .unwrap_or("") - .to_string() - } else { - str::from_utf8(&buffer[..count as usize]) - .unwrap_or("") - .to_string() - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/randr.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/randr.rs deleted file mode 100644 index e730469..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/randr.rs +++ /dev/null @@ -1,111 +0,0 @@ -use std::{env, slice}; -use std::str::FromStr; - -use validate_hidpi_factor; -use super::*; - -pub fn calc_dpi_factor( - (width_px, height_px): (u32, u32), - (width_mm, height_mm): (u64, u64), -) -> f64 { - // Override DPI if `WINIT_HIDPI_FACTOR` variable is set - let dpi_override = env::var("WINIT_HIDPI_FACTOR") - .ok() - .and_then(|var| f64::from_str(&var).ok()); - if let Some(dpi_override) = dpi_override { - if !validate_hidpi_factor(dpi_override) { - panic!( - "`WINIT_HIDPI_FACTOR` invalid; DPI factors must be normal floats greater than 0. Got `{}`", - dpi_override, - ); - } - return dpi_override; - } - - // See http://xpra.org/trac/ticket/728 for more information. - if width_mm == 0 || width_mm == 0 { - warn!("XRandR reported that the display's 0mm in size, which is certifiably insane"); - return 1.0; - } - - let ppmm = ( - (width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64) - ).sqrt(); - // Quantize 1/12 step size - let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0); - assert!(validate_hidpi_factor(dpi_factor)); - dpi_factor -} - -pub enum MonitorRepr { - Monitor(*mut ffi::XRRMonitorInfo), - Crtc(*mut ffi::XRRCrtcInfo), -} - -impl MonitorRepr { - pub unsafe fn get_output(&self) -> ffi::RROutput { - match *self { - // Same member names, but different locations within the struct... - MonitorRepr::Monitor(monitor) => *((*monitor).outputs.offset(0)), - MonitorRepr::Crtc(crtc) => *((*crtc).outputs.offset(0)), - } - } - - pub unsafe fn get_dimensions(&self) -> (u32, u32) { - match *self { - MonitorRepr::Monitor(monitor) => ((*monitor).width as u32, (*monitor).height as u32), - MonitorRepr::Crtc(crtc) => ((*crtc).width as u32, (*crtc).height as u32), - } - } - - pub unsafe fn get_position(&self) -> (i32, i32) { - match *self { - MonitorRepr::Monitor(monitor) => ((*monitor).x as i32, (*monitor).y as i32), - MonitorRepr::Crtc(crtc) => ((*crtc).x as i32, (*crtc).y as i32), - } - } -} - -impl From<*mut ffi::XRRMonitorInfo> for MonitorRepr { - fn from(monitor: *mut ffi::XRRMonitorInfo) -> Self { - MonitorRepr::Monitor(monitor) - } -} - -impl From<*mut ffi::XRRCrtcInfo> for MonitorRepr { - fn from(crtc: *mut ffi::XRRCrtcInfo) -> Self { - MonitorRepr::Crtc(crtc) - } -} - -impl XConnection { - pub unsafe fn get_output_info( - &self, - resources: *mut ffi::XRRScreenResources, - repr: &MonitorRepr, - ) -> Option<(String, f64)> { - let output_info = (self.xrandr.XRRGetOutputInfo)( - self.display, - resources, - repr.get_output(), - ); - if output_info.is_null() { - // When calling `XRRGetOutputInfo` on a virtual monitor (versus a physical display) - // it's possible for it to return null. - // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=816596 - let _ = self.check_errors(); // discard `BadRROutput` error - return None; - } - let name_slice = slice::from_raw_parts( - (*output_info).name as *mut u8, - (*output_info).nameLen as usize, - ); - let name = String::from_utf8_lossy(name_slice).into(); - let hidpi_factor = calc_dpi_factor( - repr.get_dimensions(), - ((*output_info).mm_width as u64, (*output_info).mm_height as u64), - ); - (self.xrandr.XRRFreeOutputInfo)(output_info); - Some((name, hidpi_factor)) - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/window.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/window.rs deleted file mode 100644 index 8a5f711..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/window.rs +++ /dev/null @@ -1,1213 +0,0 @@ -use std::{cmp, env, mem}; -use std::ffi::CString; -use std::os::raw::*; -use std::path::Path; -use std::sync::Arc; - -use libc; -use parking_lot::Mutex; - -use {Icon, MouseCursor, WindowAttributes}; -use CreationError::{self, OsError}; -use dpi::{LogicalPosition, LogicalSize}; -use platform::MonitorId as PlatformMonitorId; -use platform::PlatformSpecificWindowBuilderAttributes; -use platform::x11::MonitorId as X11MonitorId; -use window::MonitorId as RootMonitorId; - -use super::{ffi, util, ImeSender, XConnection, XError, WindowId, EventsLoop}; - -unsafe extern "C" fn visibility_predicate( - _display: *mut ffi::Display, - event: *mut ffi::XEvent, - arg: ffi::XPointer, // We populate this with the window ID (by value) when we call XIfEvent -) -> ffi::Bool { - let event: &ffi::XAnyEvent = (*event).as_ref(); - let window = arg as ffi::Window; - (event.window == window && event.type_ == ffi::VisibilityNotify) as _ -} - -#[derive(Debug, Default)] -pub struct SharedState { - pub cursor_pos: Option<(f64, f64)>, - pub size: Option<(u32, u32)>, - pub position: Option<(i32, i32)>, - pub inner_position: Option<(i32, i32)>, - pub inner_position_rel_parent: Option<(i32, i32)>, - pub guessed_dpi: Option, - pub last_monitor: Option, - pub dpi_adjusted: Option<(f64, f64)>, - // Used to restore position after exiting fullscreen. - pub restore_position: Option<(i32, i32)>, - pub frame_extents: Option, - pub min_dimensions: Option, - pub max_dimensions: Option, -} - -impl SharedState { - fn new(dpi_factor: f64) -> Mutex { - let mut shared_state = SharedState::default(); - shared_state.guessed_dpi = Some(dpi_factor); - Mutex::new(shared_state) - } -} - -unsafe impl Send for UnownedWindow {} -unsafe impl Sync for UnownedWindow {} - -pub struct UnownedWindow { - pub xconn: Arc, // never changes - xwindow: ffi::Window, // never changes - root: ffi::Window, // never changes - screen_id: i32, // never changes - cursor: Mutex, - cursor_grabbed: Mutex, - cursor_hidden: Mutex, - ime_sender: Mutex, - pub multitouch: bool, // never changes - pub shared_state: Mutex, -} - -impl UnownedWindow { - pub fn new( - event_loop: &EventsLoop, - window_attrs: WindowAttributes, - pl_attribs: PlatformSpecificWindowBuilderAttributes, - ) -> Result { - let xconn = &event_loop.xconn; - let root = event_loop.root; - - let monitors = xconn.get_available_monitors(); - let dpi_factor = if !monitors.is_empty() { - let mut dpi_factor = Some(monitors[0].get_hidpi_factor()); - for monitor in &monitors { - if Some(monitor.get_hidpi_factor()) != dpi_factor { - dpi_factor = None; - } - } - dpi_factor.unwrap_or_else(|| { - xconn.query_pointer(root, util::VIRTUAL_CORE_POINTER) - .ok() - .and_then(|pointer_state| { - let (x, y) = (pointer_state.root_x as i64, pointer_state.root_y as i64); - let mut dpi_factor = None; - for monitor in &monitors { - if monitor.rect.contains_point(x, y) { - dpi_factor = Some(monitor.get_hidpi_factor()); - break; - } - } - dpi_factor - }) - .unwrap_or(1.0) - }) - } else { - return Err(OsError(format!("No monitors were detected."))); - }; - - info!("Guessed window DPI factor: {}", dpi_factor); - - let max_dimensions: Option<(u32, u32)> = window_attrs.max_dimensions.map(|size| { - size.to_physical(dpi_factor).into() - }); - let min_dimensions: Option<(u32, u32)> = window_attrs.min_dimensions.map(|size| { - size.to_physical(dpi_factor).into() - }); - - let dimensions = { - // x11 only applies constraints when the window is actively resized - // by the user, so we have to manually apply the initial constraints - let mut dimensions: (u32, u32) = window_attrs.dimensions - .or_else(|| Some((800, 600).into())) - .map(|size| size.to_physical(dpi_factor)) - .map(Into::into) - .unwrap(); - if let Some(max) = max_dimensions { - dimensions.0 = cmp::min(dimensions.0, max.0); - dimensions.1 = cmp::min(dimensions.1, max.1); - } - if let Some(min) = min_dimensions { - dimensions.0 = cmp::max(dimensions.0, min.0); - dimensions.1 = cmp::max(dimensions.1, min.1); - } - debug!("Calculated physical dimensions: {}x{}", dimensions.0, dimensions.1); - dimensions - }; - - let screen_id = match pl_attribs.screen_id { - Some(id) => id, - None => unsafe { (xconn.xlib.XDefaultScreen)(xconn.display) }, - }; - - // creating - let mut set_win_attr = { - let mut swa: ffi::XSetWindowAttributes = unsafe { mem::zeroed() }; - swa.colormap = if let Some(vi) = pl_attribs.visual_infos { - unsafe { - let visual = vi.visual; - (xconn.xlib.XCreateColormap)(xconn.display, root, visual, ffi::AllocNone) - } - } else { 0 }; - swa.event_mask = ffi::ExposureMask - | ffi::StructureNotifyMask - | ffi::VisibilityChangeMask - | ffi::KeyPressMask - | ffi::KeyReleaseMask - | ffi::KeymapStateMask - | ffi::ButtonPressMask - | ffi::ButtonReleaseMask - | ffi::PointerMotionMask; - swa.border_pixel = 0; - swa.override_redirect = pl_attribs.override_redirect as c_int; - swa - }; - - let mut window_attributes = ffi::CWBorderPixel | ffi::CWColormap | ffi::CWEventMask; - - if pl_attribs.override_redirect { - window_attributes |= ffi::CWOverrideRedirect; - } - - // finally creating the window - let xwindow = unsafe { - (xconn.xlib.XCreateWindow)( - xconn.display, - root, - 0, - 0, - dimensions.0 as c_uint, - dimensions.1 as c_uint, - 0, - match pl_attribs.visual_infos { - Some(vi) => vi.depth, - None => ffi::CopyFromParent, - }, - ffi::InputOutput as c_uint, - match pl_attribs.visual_infos { - Some(vi) => vi.visual, - None => ffi::CopyFromParent as *mut ffi::Visual, - }, - window_attributes, - &mut set_win_attr, - ) - }; - - let window = UnownedWindow { - xconn: Arc::clone(xconn), - xwindow, - root, - screen_id, - cursor: Default::default(), - cursor_grabbed: Default::default(), - cursor_hidden: Default::default(), - ime_sender: Mutex::new(event_loop.ime_sender.clone()), - multitouch: window_attrs.multitouch, - shared_state: SharedState::new(dpi_factor), - }; - - // Title must be set before mapping. Some tiling window managers (i.e. i3) use the window - // title to determine placement/etc., so doing this after mapping would cause the WM to - // act on the wrong title state. - window.set_title_inner(&window_attrs.title).queue(); - window.set_decorations_inner(window_attrs.decorations).queue(); - - { - // Enable drag and drop (TODO: extend API to make this toggleable) - unsafe { - let dnd_aware_atom = xconn.get_atom_unchecked(b"XdndAware\0"); - let version = &[5 as c_ulong]; // Latest version; hasn't changed since 2002 - xconn.change_property( - window.xwindow, - dnd_aware_atom, - ffi::XA_ATOM, - util::PropMode::Replace, - version, - ) - }.queue(); - - // WM_CLASS must be set *before* mapping the window, as per ICCCM! - { - let (class, instance) = if let Some((instance, class)) = pl_attribs.class { - let instance = CString::new(instance.as_str()) - .expect("`WM_CLASS` instance contained null byte"); - let class = CString::new(class.as_str()) - .expect("`WM_CLASS` class contained null byte"); - (instance, class) - } else { - let class = env::args() - .next() - .as_ref() - // Default to the name of the binary (via argv[0]) - .and_then(|path| Path::new(path).file_name()) - .and_then(|bin_name| bin_name.to_str()) - .map(|bin_name| bin_name.to_owned()) - .or_else(|| Some(window_attrs.title.clone())) - .and_then(|string| CString::new(string.as_str()).ok()) - .expect("Default `WM_CLASS` class contained null byte"); - // This environment variable is extraordinarily unlikely to actually be used... - let instance = env::var("RESOURCE_NAME") - .ok() - .and_then(|instance| CString::new(instance.as_str()).ok()) - .or_else(|| Some(class.clone())) - .expect("Default `WM_CLASS` instance contained null byte"); - (instance, class) - }; - - let mut class_hint = xconn.alloc_class_hint(); - (*class_hint).res_name = class.as_ptr() as *mut c_char; - (*class_hint).res_class = instance.as_ptr() as *mut c_char; - - unsafe { - (xconn.xlib.XSetClassHint)( - xconn.display, - window.xwindow, - class_hint.ptr, - ); - }//.queue(); - } - - window.set_pid().map(|flusher| flusher.queue()); - - if pl_attribs.x11_window_type != Default::default() { - window.set_window_type(pl_attribs.x11_window_type).queue(); - } - - if let Some(variant) = pl_attribs.gtk_theme_variant { - window.set_gtk_theme_variant(variant).queue(); - } - - // set size hints - { - let mut min_dimensions = window_attrs.min_dimensions - .map(|size| size.to_physical(dpi_factor)); - let mut max_dimensions = window_attrs.max_dimensions - .map(|size| size.to_physical(dpi_factor)); - if !window_attrs.resizable { - if util::wm_name_is_one_of(&["Xfwm4"]) { - warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); - } else { - max_dimensions = Some(dimensions.into()); - min_dimensions = Some(dimensions.into()); - - let mut shared_state_lock = window.shared_state.lock(); - shared_state_lock.min_dimensions = window_attrs.min_dimensions; - shared_state_lock.max_dimensions = window_attrs.max_dimensions; - } - } - - let mut normal_hints = util::NormalHints::new(xconn); - normal_hints.set_size(Some(dimensions)); - normal_hints.set_min_size(min_dimensions.map(Into::into)); - normal_hints.set_max_size(max_dimensions.map(Into::into)); - normal_hints.set_resize_increments(pl_attribs.resize_increments); - normal_hints.set_base_size(pl_attribs.base_size); - xconn.set_normal_hints(window.xwindow, normal_hints).queue(); - } - - // Set window icons - if let Some(icon) = window_attrs.window_icon { - window.set_icon_inner(icon).queue(); - } - - // Opt into handling window close - unsafe { - (xconn.xlib.XSetWMProtocols)( - xconn.display, - window.xwindow, - &event_loop.wm_delete_window as *const ffi::Atom as *mut ffi::Atom, - 1, - ); - }//.queue(); - - // Set visibility (map window) - if window_attrs.visible { - unsafe { - (xconn.xlib.XMapRaised)(xconn.display, window.xwindow); - }//.queue(); - } - - // Attempt to make keyboard input repeat detectable - unsafe { - let mut supported_ptr = ffi::False; - (xconn.xlib.XkbSetDetectableAutoRepeat)( - xconn.display, - ffi::True, - &mut supported_ptr, - ); - if supported_ptr == ffi::False { - return Err(OsError(format!("`XkbSetDetectableAutoRepeat` failed"))); - } - } - - // Select XInput2 events - let mask = { - let mut mask = ffi::XI_MotionMask - | ffi::XI_ButtonPressMask - | ffi::XI_ButtonReleaseMask - //| ffi::XI_KeyPressMask - //| ffi::XI_KeyReleaseMask - | ffi::XI_EnterMask - | ffi::XI_LeaveMask - | ffi::XI_FocusInMask - | ffi::XI_FocusOutMask; - if window_attrs.multitouch { - mask |= ffi::XI_TouchBeginMask - | ffi::XI_TouchUpdateMask - | ffi::XI_TouchEndMask; - } - mask - }; - xconn.select_xinput_events(window.xwindow, ffi::XIAllMasterDevices, mask).queue(); - - { - let result = event_loop.ime - .borrow_mut() - .create_context(window.xwindow); - if let Err(err) = result { - return Err(OsError(format!("Failed to create input context: {:?}", err))); - } - } - - // These properties must be set after mapping - if window_attrs.maximized { - window.set_maximized_inner(window_attrs.maximized).queue(); - } - if window_attrs.fullscreen.is_some() { - window.set_fullscreen_inner(window_attrs.fullscreen.clone()).queue(); - } - if window_attrs.always_on_top { - window.set_always_on_top_inner(window_attrs.always_on_top).queue(); - } - - if window_attrs.visible { - unsafe { - // XSetInputFocus generates an error if the window is not visible, so we wait - // until we receive VisibilityNotify. - let mut event = mem::uninitialized(); - (xconn.xlib.XIfEvent)( // This will flush the request buffer IF it blocks. - xconn.display, - &mut event as *mut ffi::XEvent, - Some(visibility_predicate), - window.xwindow as _, - ); - (xconn.xlib.XSetInputFocus)( - xconn.display, - window.xwindow, - ffi::RevertToParent, - ffi::CurrentTime, - ); - } - } - } - - // We never want to give the user a broken window, since by then, it's too late to handle. - xconn.sync_with_server() - .map(|_| window) - .map_err(|x_err| OsError( - format!("X server returned error while building window: {:?}", x_err) - )) - } - - fn logicalize_coords(&self, (x, y): (i32, i32)) -> LogicalPosition { - let dpi = self.get_hidpi_factor(); - LogicalPosition::from_physical((x, y), dpi) - } - - fn logicalize_size(&self, (width, height): (u32, u32)) -> LogicalSize { - let dpi = self.get_hidpi_factor(); - LogicalSize::from_physical((width, height), dpi) - } - - fn set_pid(&self) -> Option { - let pid_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_PID\0") }; - let client_machine_atom = unsafe { self.xconn.get_atom_unchecked(b"WM_CLIENT_MACHINE\0") }; - unsafe { - let (hostname, hostname_length) = { - // 64 would suffice for Linux, but 256 will be enough everywhere (as per SUSv2). For instance, this is - // the limit defined by OpenBSD. - const MAXHOSTNAMELEN: usize = 256; - let mut hostname: [c_char; MAXHOSTNAMELEN] = mem::uninitialized(); - let status = libc::gethostname(hostname.as_mut_ptr(), hostname.len()); - if status != 0 { return None; } - hostname[MAXHOSTNAMELEN - 1] = '\0' as c_char; // a little extra safety - let hostname_length = libc::strlen(hostname.as_ptr()); - (hostname, hostname_length as usize) - }; - self.xconn.change_property( - self.xwindow, - pid_atom, - ffi::XA_CARDINAL, - util::PropMode::Replace, - &[libc::getpid() as util::Cardinal], - ).queue(); - let flusher = self.xconn.change_property( - self.xwindow, - client_machine_atom, - ffi::XA_STRING, - util::PropMode::Replace, - &hostname[0..hostname_length], - ); - Some(flusher) - } - } - - fn set_window_type(&self, window_type: util::WindowType) -> util::Flusher { - let hint_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_WINDOW_TYPE\0") }; - let window_type_atom = window_type.as_atom(&self.xconn); - self.xconn.change_property( - self.xwindow, - hint_atom, - ffi::XA_ATOM, - util::PropMode::Replace, - &[window_type_atom], - ) - } - - fn set_gtk_theme_variant(&self, variant: String) -> util::Flusher { - let hint_atom = unsafe { self.xconn.get_atom_unchecked(b"_GTK_THEME_VARIANT\0") }; - let utf8_atom = unsafe { self.xconn.get_atom_unchecked(b"UTF8_STRING\0") }; - let variant = CString::new(variant).expect("`_GTK_THEME_VARIANT` contained null byte"); - self.xconn.change_property( - self.xwindow, - hint_atom, - utf8_atom, - util::PropMode::Replace, - variant.as_bytes(), - ) - } - - #[inline] - pub fn set_urgent(&self, is_urgent: bool) { - let mut wm_hints = self.xconn.get_wm_hints(self.xwindow).expect("`XGetWMHints` failed"); - if is_urgent { - (*wm_hints).flags |= ffi::XUrgencyHint; - } else { - (*wm_hints).flags &= !ffi::XUrgencyHint; - } - self.xconn.set_wm_hints(self.xwindow, wm_hints).flush().expect("Failed to set urgency hint"); - } - - fn set_netwm( - &self, - operation: util::StateOperation, - properties: (c_long, c_long, c_long, c_long), - ) -> util::Flusher { - let state_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE\0") }; - self.xconn.send_client_msg( - self.xwindow, - self.root, - state_atom, - Some(ffi::SubstructureRedirectMask | ffi::SubstructureNotifyMask), - [ - operation as c_long, - properties.0, - properties.1, - properties.2, - properties.3, - ], - ) - } - - fn set_fullscreen_hint(&self, fullscreen: bool) -> util::Flusher { - let fullscreen_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_FULLSCREEN\0") }; - self.set_netwm(fullscreen.into(), (fullscreen_atom as c_long, 0, 0, 0)) - } - - fn set_fullscreen_inner(&self, monitor: Option) -> util::Flusher { - match monitor { - None => { - let flusher = self.set_fullscreen_hint(false); - if let Some(position) = self.shared_state.lock().restore_position.take() { - self.set_position_inner(position.0, position.1).queue(); - } - flusher - }, - Some(RootMonitorId { inner: PlatformMonitorId::X(monitor) }) => { - let window_position = self.get_position_physical(); - self.shared_state.lock().restore_position = window_position; - let monitor_origin: (i32, i32) = monitor.get_position().into(); - self.set_position_inner(monitor_origin.0, monitor_origin.1).queue(); - self.set_fullscreen_hint(true) - } - _ => unreachable!(), - } - } - - #[inline] - pub fn set_fullscreen(&self, monitor: Option) { - self.set_fullscreen_inner(monitor) - .flush() - .expect("Failed to change window fullscreen state"); - self.invalidate_cached_frame_extents(); - } - - fn get_rect(&self) -> Option { - // TODO: This might round-trip more times than needed. - if let (Some(position), Some(size)) = (self.get_position_physical(), self.get_outer_size_physical()) { - Some(util::AaRect::new(position, size)) - } else { - None - } - } - - #[inline] - pub fn get_current_monitor(&self) -> X11MonitorId { - let monitor = self.shared_state - .lock() - .last_monitor - .as_ref() - .cloned(); - monitor - .unwrap_or_else(|| { - let monitor = self.xconn.get_monitor_for_window(self.get_rect()).to_owned(); - self.shared_state.lock().last_monitor = Some(monitor.clone()); - monitor - }) - } - - pub fn get_available_monitors(&self) -> Vec { - self.xconn.get_available_monitors() - } - - pub fn get_primary_monitor(&self) -> X11MonitorId { - self.xconn.get_primary_monitor() - } - - fn set_maximized_inner(&self, maximized: bool) -> util::Flusher { - let horz_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_MAXIMIZED_HORZ\0") }; - let vert_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_MAXIMIZED_VERT\0") }; - self.set_netwm(maximized.into(), (horz_atom as c_long, vert_atom as c_long, 0, 0)) - } - - #[inline] - pub fn set_maximized(&self, maximized: bool) { - self.set_maximized_inner(maximized) - .flush() - .expect("Failed to change window maximization"); - self.invalidate_cached_frame_extents(); - } - - fn set_title_inner(&self, title: &str) -> util::Flusher { - let wm_name_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_NAME\0") }; - let utf8_atom = unsafe { self.xconn.get_atom_unchecked(b"UTF8_STRING\0") }; - let title = CString::new(title).expect("Window title contained null byte"); - unsafe { - (self.xconn.xlib.XStoreName)( - self.xconn.display, - self.xwindow, - title.as_ptr() as *const c_char, - ); - self.xconn.change_property( - self.xwindow, - wm_name_atom, - utf8_atom, - util::PropMode::Replace, - title.as_bytes(), - ) - } - } - - #[inline] - pub fn set_title(&self, title: &str) { - self.set_title_inner(title) - .flush() - .expect("Failed to set window title"); - } - - fn set_decorations_inner(&self, decorations: bool) -> util::Flusher { - let wm_hints = unsafe { self.xconn.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; - self.xconn.change_property( - self.xwindow, - wm_hints, - wm_hints, - util::PropMode::Replace, - &[ - util::MWM_HINTS_DECORATIONS, // flags - 0, // functions - decorations as c_ulong, // decorations - 0, // input mode - 0, // status - ], - ) - } - - #[inline] - pub fn set_decorations(&self, decorations: bool) { - self.set_decorations_inner(decorations) - .flush() - .expect("Failed to set decoration state"); - self.invalidate_cached_frame_extents(); - } - - fn set_always_on_top_inner(&self, always_on_top: bool) -> util::Flusher { - let above_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_ABOVE\0") }; - self.set_netwm(always_on_top.into(), (above_atom as c_long, 0, 0, 0)) - } - - #[inline] - pub fn set_always_on_top(&self, always_on_top: bool) { - self.set_always_on_top_inner(always_on_top) - .flush() - .expect("Failed to set always-on-top state"); - } - - fn set_icon_inner(&self, icon: Icon) -> util::Flusher { - let icon_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_ICON\0") }; - let data = icon.to_cardinals(); - self.xconn.change_property( - self.xwindow, - icon_atom, - ffi::XA_CARDINAL, - util::PropMode::Replace, - data.as_slice(), - ) - } - - fn unset_icon_inner(&self) -> util::Flusher { - let icon_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_ICON\0") }; - let empty_data: [util::Cardinal; 0] = []; - self.xconn.change_property( - self.xwindow, - icon_atom, - ffi::XA_CARDINAL, - util::PropMode::Replace, - &empty_data, - ) - } - - #[inline] - pub fn set_window_icon(&self, icon: Option) { - match icon { - Some(icon) => self.set_icon_inner(icon), - None => self.unset_icon_inner(), - }.flush().expect("Failed to set icons"); - } - - #[inline] - pub fn show(&self) { - unsafe { - (self.xconn.xlib.XMapRaised)(self.xconn.display, self.xwindow); - self.xconn.flush_requests() - .expect("Failed to call XMapRaised"); - } - } - - #[inline] - pub fn hide(&self) { - unsafe { - (self.xconn.xlib.XUnmapWindow)(self.xconn.display, self.xwindow); - self.xconn.flush_requests() - .expect("Failed to call XUnmapWindow"); - } - } - - fn update_cached_frame_extents(&self) { - let extents = self.xconn.get_frame_extents_heuristic(self.xwindow, self.root); - (*self.shared_state.lock()).frame_extents = Some(extents); - } - - pub(crate) fn invalidate_cached_frame_extents(&self) { - (*self.shared_state.lock()).frame_extents.take(); - } - - pub(crate) fn get_position_physical(&self) -> Option<(i32, i32)> { - let extents = (*self.shared_state.lock()).frame_extents.clone(); - if let Some(extents) = extents { - self.get_inner_position_physical() - .map(|(x, y)| extents.inner_pos_to_outer(x, y)) - } else { - self.update_cached_frame_extents(); - self.get_position_physical() - } - } - - #[inline] - pub fn get_position(&self) -> Option { - let extents = (*self.shared_state.lock()).frame_extents.clone(); - if let Some(extents) = extents { - self.get_inner_position() - .map(|logical| extents.inner_pos_to_outer_logical(logical, self.get_hidpi_factor())) - } else { - self.update_cached_frame_extents(); - self.get_position() - } - } - - pub(crate) fn get_inner_position_physical(&self) -> Option<(i32, i32)> { - self.xconn.translate_coords(self.xwindow, self.root) - .ok() - .map(|coords| (coords.x_rel_root, coords.y_rel_root)) - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - self.get_inner_position_physical() - .map(|coords| self.logicalize_coords(coords)) - } - - pub(crate) fn set_position_inner(&self, mut x: i32, mut y: i32) -> util::Flusher { - // There are a few WMs that set client area position rather than window position, so - // we'll translate for consistency. - if util::wm_name_is_one_of(&["Enlightenment", "FVWM"]) { - let extents = (*self.shared_state.lock()).frame_extents.clone(); - if let Some(extents) = extents { - x += extents.frame_extents.left as i32; - y += extents.frame_extents.top as i32; - } else { - self.update_cached_frame_extents(); - return self.set_position_inner(x, y); - } - } - unsafe { - (self.xconn.xlib.XMoveWindow)( - self.xconn.display, - self.xwindow, - x as c_int, - y as c_int, - ); - } - util::Flusher::new(&self.xconn) - } - - pub(crate) fn set_position_physical(&self, x: i32, y: i32) { - self.set_position_inner(x, y) - .flush() - .expect("Failed to call `XMoveWindow`"); - } - - #[inline] - pub fn set_position(&self, logical_position: LogicalPosition) { - let (x, y) = logical_position.to_physical(self.get_hidpi_factor()).into(); - self.set_position_physical(x, y); - } - - pub(crate) fn get_inner_size_physical(&self) -> Option<(u32, u32)> { - self.xconn.get_geometry(self.xwindow) - .ok() - .map(|geo| (geo.width, geo.height)) - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - self.get_inner_size_physical() - .map(|size| self.logicalize_size(size)) - } - - pub(crate) fn get_outer_size_physical(&self) -> Option<(u32, u32)> { - let extents = self.shared_state.lock().frame_extents.clone(); - if let Some(extents) = extents { - self.get_inner_size_physical() - .map(|(w, h)| extents.inner_size_to_outer(w, h)) - } else { - self.update_cached_frame_extents(); - self.get_outer_size_physical() - } - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - let extents = self.shared_state.lock().frame_extents.clone(); - if let Some(extents) = extents { - self.get_inner_size() - .map(|logical| extents.inner_size_to_outer_logical(logical, self.get_hidpi_factor())) - } else { - self.update_cached_frame_extents(); - self.get_outer_size() - } - } - - pub(crate) fn set_inner_size_physical(&self, width: u32, height: u32) { - unsafe { - (self.xconn.xlib.XResizeWindow)( - self.xconn.display, - self.xwindow, - width as c_uint, - height as c_uint, - ); - self.xconn.flush_requests() - }.expect("Failed to call `XResizeWindow`"); - } - - #[inline] - pub fn set_inner_size(&self, logical_size: LogicalSize) { - let dpi_factor = self.get_hidpi_factor(); - let (width, height) = logical_size.to_physical(dpi_factor).into(); - self.set_inner_size_physical(width, height); - } - - fn update_normal_hints(&self, callback: F) -> Result<(), XError> - where F: FnOnce(&mut util::NormalHints) -> () - { - let mut normal_hints = self.xconn.get_normal_hints(self.xwindow)?; - callback(&mut normal_hints); - self.xconn.set_normal_hints(self.xwindow, normal_hints).flush() - } - - pub(crate) fn set_min_dimensions_physical(&self, dimensions: Option<(u32, u32)>) { - self.update_normal_hints(|normal_hints| normal_hints.set_min_size(dimensions)) - .expect("Failed to call `XSetWMNormalHints`"); - } - - #[inline] - pub fn set_min_dimensions(&self, logical_dimensions: Option) { - self.shared_state.lock().min_dimensions = logical_dimensions; - let physical_dimensions = logical_dimensions.map(|logical_dimensions| { - logical_dimensions.to_physical(self.get_hidpi_factor()).into() - }); - self.set_min_dimensions_physical(physical_dimensions); - } - - pub(crate) fn set_max_dimensions_physical(&self, dimensions: Option<(u32, u32)>) { - self.update_normal_hints(|normal_hints| normal_hints.set_max_size(dimensions)) - .expect("Failed to call `XSetWMNormalHints`"); - } - - #[inline] - pub fn set_max_dimensions(&self, logical_dimensions: Option) { - self.shared_state.lock().max_dimensions = logical_dimensions; - let physical_dimensions = logical_dimensions.map(|logical_dimensions| { - logical_dimensions.to_physical(self.get_hidpi_factor()).into() - }); - self.set_max_dimensions_physical(physical_dimensions); - } - - pub(crate) fn adjust_for_dpi( - &self, - old_dpi_factor: f64, - new_dpi_factor: f64, - width: f64, - height: f64, - ) -> (f64, f64, util::Flusher) { - let scale_factor = new_dpi_factor / old_dpi_factor; - let new_width = width * scale_factor; - let new_height = height * scale_factor; - self.update_normal_hints(|normal_hints| { - let dpi_adjuster = |(width, height): (u32, u32)| -> (u32, u32) { - let new_width = width as f64 * scale_factor; - let new_height = height as f64 * scale_factor; - (new_width.round() as u32, new_height.round() as u32) - }; - let max_size = normal_hints.get_max_size().map(&dpi_adjuster); - let min_size = normal_hints.get_min_size().map(&dpi_adjuster); - let resize_increments = normal_hints.get_resize_increments().map(&dpi_adjuster); - let base_size = normal_hints.get_base_size().map(&dpi_adjuster); - normal_hints.set_max_size(max_size); - normal_hints.set_min_size(min_size); - normal_hints.set_resize_increments(resize_increments); - normal_hints.set_base_size(base_size); - }).expect("Failed to update normal hints"); - unsafe { - (self.xconn.xlib.XResizeWindow)( - self.xconn.display, - self.xwindow, - new_width.round() as c_uint, - new_height.round() as c_uint, - ); - } - (new_width, new_height, util::Flusher::new(&self.xconn)) - } - - pub fn set_resizable(&self, resizable: bool) { - if util::wm_name_is_one_of(&["Xfwm4"]) { - // Making the window unresizable on Xfwm prevents further changes to `WM_NORMAL_HINTS` from being detected. - // This makes it impossible for resizing to be re-enabled, and also breaks DPI scaling. As such, we choose - // the lesser of two evils and do nothing. - warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); - return; - } - - let (logical_min, logical_max) = if resizable { - let shared_state_lock = self.shared_state.lock(); - (shared_state_lock.min_dimensions, shared_state_lock.max_dimensions) - } else { - let window_size = self.get_inner_size(); - (window_size.clone(), window_size) - }; - - let dpi_factor = self.get_hidpi_factor(); - let min_dimensions = logical_min - .map(|logical_size| logical_size.to_physical(dpi_factor)) - .map(Into::into); - let max_dimensions = logical_max - .map(|logical_size| logical_size.to_physical(dpi_factor)) - .map(Into::into); - self.update_normal_hints(|normal_hints| { - normal_hints.set_min_size(min_dimensions); - normal_hints.set_max_size(max_dimensions); - }).expect("Failed to call `XSetWMNormalHints`"); - } - - #[inline] - pub fn get_xlib_display(&self) -> *mut c_void { - self.xconn.display as _ - } - - #[inline] - pub fn get_xlib_screen_id(&self) -> c_int { - self.screen_id - } - - #[inline] - pub fn get_xlib_xconnection(&self) -> Arc { - Arc::clone(&self.xconn) - } - - #[inline] - pub fn get_xlib_window(&self) -> c_ulong { - self.xwindow - } - - #[inline] - pub fn get_xcb_connection(&self) -> *mut c_void { - unsafe { - (self.xconn.xlib_xcb.XGetXCBConnection)(self.xconn.display) as *mut _ - } - } - - fn load_cursor(&self, name: &[u8]) -> ffi::Cursor { - unsafe { - (self.xconn.xcursor.XcursorLibraryLoadCursor)( - self.xconn.display, - name.as_ptr() as *const c_char, - ) - } - } - - fn load_first_existing_cursor(&self, names: &[&[u8]]) -> ffi::Cursor { - for name in names.iter() { - let xcursor = self.load_cursor(name); - if xcursor != 0 { - return xcursor; - } - } - 0 - } - - fn get_cursor(&self, cursor: MouseCursor) -> ffi::Cursor { - let load = |name: &[u8]| { - self.load_cursor(name) - }; - - let loadn = |names: &[&[u8]]| { - self.load_first_existing_cursor(names) - }; - - // Try multiple names in some cases where the name - // differs on the desktop environments or themes. - // - // Try the better looking (or more suiting) names first. - match cursor { - MouseCursor::Alias => load(b"link\0"), - MouseCursor::Arrow => load(b"arrow\0"), - MouseCursor::Cell => load(b"plus\0"), - MouseCursor::Copy => load(b"copy\0"), - MouseCursor::Crosshair => load(b"crosshair\0"), - MouseCursor::Default => load(b"left_ptr\0"), - MouseCursor::Hand => loadn(&[b"hand2\0", b"hand1\0"]), - MouseCursor::Help => load(b"question_arrow\0"), - MouseCursor::Move => load(b"move\0"), - MouseCursor::Grab => loadn(&[b"openhand\0", b"grab\0"]), - MouseCursor::Grabbing => loadn(&[b"closedhand\0", b"grabbing\0"]), - MouseCursor::Progress => load(b"left_ptr_watch\0"), - MouseCursor::AllScroll => load(b"all-scroll\0"), - MouseCursor::ContextMenu => load(b"context-menu\0"), - - MouseCursor::NoDrop => loadn(&[b"no-drop\0", b"circle\0"]), - MouseCursor::NotAllowed => load(b"crossed_circle\0"), - - - // Resize cursors - MouseCursor::EResize => load(b"right_side\0"), - MouseCursor::NResize => load(b"top_side\0"), - MouseCursor::NeResize => load(b"top_right_corner\0"), - MouseCursor::NwResize => load(b"top_left_corner\0"), - MouseCursor::SResize => load(b"bottom_side\0"), - MouseCursor::SeResize => load(b"bottom_right_corner\0"), - MouseCursor::SwResize => load(b"bottom_left_corner\0"), - MouseCursor::WResize => load(b"left_side\0"), - MouseCursor::EwResize => load(b"h_double_arrow\0"), - MouseCursor::NsResize => load(b"v_double_arrow\0"), - MouseCursor::NwseResize => loadn(&[b"bd_double_arrow\0", b"size_bdiag\0"]), - MouseCursor::NeswResize => loadn(&[b"fd_double_arrow\0", b"size_fdiag\0"]), - MouseCursor::ColResize => loadn(&[b"split_h\0", b"h_double_arrow\0"]), - MouseCursor::RowResize => loadn(&[b"split_v\0", b"v_double_arrow\0"]), - - MouseCursor::Text => loadn(&[b"text\0", b"xterm\0"]), - MouseCursor::VerticalText => load(b"vertical-text\0"), - - MouseCursor::Wait => load(b"watch\0"), - - MouseCursor::ZoomIn => load(b"zoom-in\0"), - MouseCursor::ZoomOut => load(b"zoom-out\0"), - } - } - - fn update_cursor(&self, cursor: ffi::Cursor) { - unsafe { - (self.xconn.xlib.XDefineCursor)(self.xconn.display, self.xwindow, cursor); - if cursor != 0 { - (self.xconn.xlib.XFreeCursor)(self.xconn.display, cursor); - } - self.xconn.flush_requests().expect("Failed to set or free the cursor"); - } - } - - #[inline] - pub fn set_cursor(&self, cursor: MouseCursor) { - *self.cursor.lock() = cursor; - if !*self.cursor_hidden.lock() { - self.update_cursor(self.get_cursor(cursor)); - } - } - - // TODO: This could maybe be cached. I don't think it's worth - // the complexity, since cursor changes are not so common, - // and this is just allocating a 1x1 pixmap... - fn create_empty_cursor(&self) -> Option { - let data = 0; - let pixmap = unsafe { - (self.xconn.xlib.XCreateBitmapFromData)( - self.xconn.display, - self.xwindow, - &data, - 1, - 1, - ) - }; - if pixmap == 0 { - // Failed to allocate - return None; - } - - let cursor = unsafe { - // We don't care about this color, since it only fills bytes - // in the pixmap which are not 0 in the mask. - let dummy_color: ffi::XColor = mem::uninitialized(); - let cursor = (self.xconn.xlib.XCreatePixmapCursor)( - self.xconn.display, - pixmap, - pixmap, - &dummy_color as *const _ as *mut _, - &dummy_color as *const _ as *mut _, - 0, - 0, - ); - (self.xconn.xlib.XFreePixmap)(self.xconn.display, pixmap); - cursor - }; - Some(cursor) - } - - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - let mut grabbed_lock = self.cursor_grabbed.lock(); - if grab == *grabbed_lock { return Ok(()); } - unsafe { - // We ungrab before grabbing to prevent passive grabs from causing `AlreadyGrabbed`. - // Therefore, this is common to both codepaths. - (self.xconn.xlib.XUngrabPointer)(self.xconn.display, ffi::CurrentTime); - } - let result = if grab { - let result = unsafe { - (self.xconn.xlib.XGrabPointer)( - self.xconn.display, - self.xwindow, - ffi::True, - ( - ffi::ButtonPressMask - | ffi::ButtonReleaseMask - | ffi::EnterWindowMask - | ffi::LeaveWindowMask - | ffi::PointerMotionMask - | ffi::PointerMotionHintMask - | ffi::Button1MotionMask - | ffi::Button2MotionMask - | ffi::Button3MotionMask - | ffi::Button4MotionMask - | ffi::Button5MotionMask - | ffi::ButtonMotionMask - | ffi::KeymapStateMask - ) as c_uint, - ffi::GrabModeAsync, - ffi::GrabModeAsync, - self.xwindow, - 0, - ffi::CurrentTime, - ) - }; - - match result { - ffi::GrabSuccess => Ok(()), - ffi::AlreadyGrabbed => Err("Cursor could not be grabbed: already grabbed by another client"), - ffi::GrabInvalidTime => Err("Cursor could not be grabbed: invalid time"), - ffi::GrabNotViewable => Err("Cursor could not be grabbed: grab location not viewable"), - ffi::GrabFrozen => Err("Cursor could not be grabbed: frozen by another client"), - _ => unreachable!(), - }.map_err(|err| err.to_owned()) - } else { - self.xconn.flush_requests() - .map_err(|err| format!("Failed to call `XUngrabPointer`: {:?}", err)) - }; - if result.is_ok() { - *grabbed_lock = grab; - } - result - } - - #[inline] - pub fn hide_cursor(&self, hide: bool) { - let mut hidden_lock = self.cursor_hidden.lock(); - if hide == *hidden_lock {return; } - let cursor = if hide { - self.create_empty_cursor().expect("Failed to create empty cursor") - } else { - self.get_cursor(*self.cursor.lock()) - }; - *hidden_lock = hide; - drop(hidden_lock); - self.update_cursor(cursor); - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.get_current_monitor().hidpi_factor - } - - pub fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), String> { - unsafe { - (self.xconn.xlib.XWarpPointer)( - self.xconn.display, - 0, - self.xwindow, - 0, - 0, - 0, - 0, - x, - y, - ); - self.xconn.flush_requests().map_err(|e| format!("`XWarpPointer` failed: {:?}", e)) - } - } - - #[inline] - pub fn set_cursor_position(&self, logical_position: LogicalPosition) -> Result<(), String> { - let (x, y) = logical_position.to_physical(self.get_hidpi_factor()).into(); - self.set_cursor_position_physical(x, y) - } - - pub(crate) fn set_ime_spot_physical(&self, x: i32, y: i32) { - let _ = self.ime_sender - .lock() - .send((self.xwindow, x as i16, y as i16)); - } - - #[inline] - pub fn set_ime_spot(&self, logical_spot: LogicalPosition) { - let (x, y) = logical_spot.to_physical(self.get_hidpi_factor()).into(); - self.set_ime_spot_physical(x, y); - } - - #[inline] - pub fn id(&self) -> WindowId { WindowId(self.xwindow) } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/events_loop.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/events_loop.rs deleted file mode 100644 index ca1ff17..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/events_loop.rs +++ /dev/null @@ -1,742 +0,0 @@ -use {ControlFlow, EventsLoopClosed}; -use cocoa::{self, appkit, foundation}; -use cocoa::appkit::{NSApplication, NSEvent, NSEventMask, NSEventModifierFlags, NSEventPhase, NSView, NSWindow}; -use events::{self, ElementState, Event, TouchPhase, WindowEvent, DeviceEvent, ModifiersState, KeyboardInput}; -use std::collections::VecDeque; -use std::sync::{Arc, Mutex, Weak}; -use super::window::Window2; -use std; -use std::os::raw::*; -use super::DeviceId; - -pub struct EventsLoop { - modifiers: Modifiers, - pub shared: Arc, -} - -// State shared between the `EventsLoop` and its registered windows. -pub struct Shared { - pub windows: Mutex>>, - pub pending_events: Mutex>, - // The user event callback given via either of the `poll_events` or `run_forever` methods. - // - // We store the user's callback here so that it may be accessed by each of the window delegate - // callbacks (e.g. resize, close, etc) for the duration of a call to either of the - // `poll_events` or `run_forever` methods. - // - // This is *only* `Some` for the duration of a call to either of these methods and will be - // `None` otherwise. - user_callback: UserCallback, -} - -#[derive(Clone)] -pub struct Proxy {} - -struct Modifiers { - shift_pressed: bool, - ctrl_pressed: bool, - win_pressed: bool, - alt_pressed: bool, -} - -// Wrapping the user callback in a type allows us to: -// -// - ensure the callback pointer is never accidentally cloned -// - ensure that only the `EventsLoop` can `store` and `drop` the callback pointer -// - Share access to the user callback with the NSWindow callbacks. -pub struct UserCallback { - mutex: Mutex>, -} - - -impl Shared { - - pub fn new() -> Self { - Shared { - windows: Mutex::new(Vec::new()), - pending_events: Mutex::new(VecDeque::new()), - user_callback: UserCallback { mutex: Mutex::new(None) }, - } - } - - fn call_user_callback_with_pending_events(&self) { - loop { - let event = match self.pending_events.lock().unwrap().pop_front() { - Some(event) => event, - None => return, - }; - unsafe { - self.user_callback.call_with_event(event); - } - } - } - - // Calls the user callback if one exists. - // - // Otherwise, stores the event in the `pending_events` queue. - // - // This is necessary for the case when `WindowDelegate` callbacks are triggered during a call - // to the user's callback. - pub fn call_user_callback_with_event_or_store_in_pending(&self, event: Event) { - if self.user_callback.mutex.lock().unwrap().is_some() { - unsafe { - self.user_callback.call_with_event(event); - } - } else { - self.pending_events.lock().unwrap().push_back(event); - } - } - - // Removes the window with the given `Id` from the `windows` list. - // - // This is called in response to `windowWillClose`. - pub fn find_and_remove_window(&self, id: super::window::Id) { - if let Ok(mut windows) = self.windows.lock() { - windows.retain(|w| match w.upgrade() { - Some(w) => w.id() != id, - None => false, - }); - } - } - -} - - -impl Modifiers { - pub fn new() -> Self { - Modifiers { - shift_pressed: false, - ctrl_pressed: false, - win_pressed: false, - alt_pressed: false, - } - } -} - - -impl UserCallback { - - // Here we store user's `callback` behind the mutex so that they may be safely shared between - // each of the window delegates. - // - // In order to make sure that the pointer is always valid, we must manually guarantee that it - // is dropped before the callback itself is dropped. Thus, this should *only* be called at the - // beginning of a call to `poll_events` and `run_forever`, both of which *must* drop the - // callback at the end of their scope using the `drop` method. - fn store(&self, callback: &mut F) - where F: FnMut(Event) - { - let trait_object = callback as &mut FnMut(Event); - let trait_object_ptr = trait_object as *const FnMut(Event) as *mut FnMut(Event); - *self.mutex.lock().unwrap() = Some(trait_object_ptr); - } - - // Emits the given event via the user-given callback. - // - // This is unsafe as it requires dereferencing the pointer to the user-given callback. We - // guarantee this is safe by ensuring the `UserCallback` never lives longer than the user-given - // callback. - // - // Note that the callback may not always be `Some`. This is because some `NSWindowDelegate` - // callbacks can be triggered by means other than `NSApp().sendEvent`. For example, if a window - // is destroyed or created during a call to the user's callback, the `WindowDelegate` methods - // may be called with `windowShouldClose` or `windowDidResignKey`. - unsafe fn call_with_event(&self, event: Event) { - let callback = match self.mutex.lock().unwrap().take() { - Some(callback) => callback, - None => return, - }; - (*callback)(event); - *self.mutex.lock().unwrap() = Some(callback); - } - - // Used to drop the user callback pointer at the end of the `poll_events` and `run_forever` - // methods. This is done to enforce our guarantee that the top callback will never live longer - // than the call to either `poll_events` or `run_forever` to which it was given. - fn drop(&self) { - self.mutex.lock().unwrap().take(); - } - -} - - -impl EventsLoop { - - pub fn new() -> Self { - // Mark this thread as the main thread of the Cocoa event system. - // - // This must be done before any worker threads get a chance to call it - // (e.g., via `EventsLoopProxy::wakeup()`), causing a wrong thread to be - // marked as the main thread. - unsafe { appkit::NSApp(); } - - EventsLoop { - shared: Arc::new(Shared::new()), - modifiers: Modifiers::new(), - } - } - - pub fn poll_events(&mut self, mut callback: F) - where F: FnMut(Event), - { - unsafe { - if !msg_send![class!(NSThread), isMainThread] { - panic!("Events can only be polled from the main thread on macOS"); - } - } - - self.shared.user_callback.store(&mut callback); - - // Loop as long as we have pending events to return. - loop { - unsafe { - // First, yield all pending events. - self.shared.call_user_callback_with_pending_events(); - - let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil); - - // Poll for the next event, returning `nil` if there are none. - let ns_event = appkit::NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_( - NSEventMask::NSAnyEventMask.bits() | NSEventMask::NSEventMaskPressure.bits(), - foundation::NSDate::distantPast(cocoa::base::nil), - foundation::NSDefaultRunLoopMode, - cocoa::base::YES); - - let event = self.ns_event_to_event(ns_event); - - let _: () = msg_send![pool, release]; - - match event { - // Call the user's callback. - Some(event) => self.shared.user_callback.call_with_event(event), - None => break, - } - } - } - - self.shared.user_callback.drop(); - } - - pub fn run_forever(&mut self, mut callback: F) - where F: FnMut(Event) -> ControlFlow - { - unsafe { - if !msg_send![class!(NSThread), isMainThread] { - panic!("Events can only be polled from the main thread on macOS"); - } - } - - // Track whether or not control flow has changed. - let control_flow = std::cell::Cell::new(ControlFlow::Continue); - - let mut callback = |event| { - if let ControlFlow::Break = callback(event) { - control_flow.set(ControlFlow::Break); - } - }; - - self.shared.user_callback.store(&mut callback); - - loop { - unsafe { - // First, yield all pending events. - self.shared.call_user_callback_with_pending_events(); - if let ControlFlow::Break = control_flow.get() { - break; - } - - let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil); - - // Wait for the next event. Note that this function blocks during resize. - let ns_event = appkit::NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_( - NSEventMask::NSAnyEventMask.bits() | NSEventMask::NSEventMaskPressure.bits(), - foundation::NSDate::distantFuture(cocoa::base::nil), - foundation::NSDefaultRunLoopMode, - cocoa::base::YES); - - let maybe_event = self.ns_event_to_event(ns_event); - - // Release the pool before calling the top callback in case the user calls either - // `run_forever` or `poll_events` within the callback. - let _: () = msg_send![pool, release]; - - if let Some(event) = maybe_event { - self.shared.user_callback.call_with_event(event); - if let ControlFlow::Break = control_flow.get() { - break; - } - } - } - } - - self.shared.user_callback.drop(); - } - - // Convert some given `NSEvent` into a winit `Event`. - unsafe fn ns_event_to_event(&mut self, ns_event: cocoa::base::id) -> Option { - if ns_event == cocoa::base::nil { - return None; - } - - // FIXME: Despite not being documented anywhere, an `NSEvent` is produced when a user opens - // Spotlight while the NSApplication is in focus. This `NSEvent` produces a `NSEventType` - // with value `21`. This causes a SEGFAULT as soon as we try to match on the `NSEventType` - // enum as there is no variant associated with the value. Thus, we return early if this - // sneaky event occurs. If someone does find some documentation on this, please fix this by - // adding an appropriate variant to the `NSEventType` enum in the cocoa-rs crate. - if ns_event.eventType() as u64 == 21 { - return None; - } - - let event_type = ns_event.eventType(); - let ns_window = ns_event.window(); - let window_id = super::window::get_window_id(ns_window); - - // FIXME: Document this. Why do we do this? Seems like it passes on events to window/app. - // If we don't do this, window does not become main for some reason. - appkit::NSApp().sendEvent_(ns_event); - - let windows = self.shared.windows.lock().unwrap(); - let maybe_window = windows.iter() - .filter_map(Weak::upgrade) - .find(|window| window_id == window.id()); - - let into_event = |window_event| Event::WindowEvent { - window_id: ::WindowId(window_id), - event: window_event, - }; - - // Returns `Some` window if one of our windows is the key window. - let maybe_key_window = || windows.iter() - .filter_map(Weak::upgrade) - .find(|window| { - let is_key_window: cocoa::base::BOOL = msg_send![*window.window, isKeyWindow]; - is_key_window == cocoa::base::YES - }); - - match event_type { - // https://github.com/glfw/glfw/blob/50eccd298a2bbc272b4977bd162d3e4b55f15394/src/cocoa_window.m#L881 - appkit::NSKeyUp => { - if let Some(key_window) = maybe_key_window() { - if event_mods(ns_event).logo { - let _: () = msg_send![*key_window.window, sendEvent:ns_event]; - } - } - None - }, - // similar to above, but for ``, the keyDown is suppressed instead of the - // KeyUp, and the above trick does not appear to work. - appkit::NSKeyDown => { - let modifiers = event_mods(ns_event); - let keycode = NSEvent::keyCode(ns_event); - if modifiers.logo && keycode == 47 { - modifier_event(ns_event, NSEventModifierFlags::NSCommandKeyMask, false) - .map(into_event) - } else { - None - } - }, - appkit::NSFlagsChanged => { - let mut events = std::collections::VecDeque::new(); - - if let Some(window_event) = modifier_event( - ns_event, - NSEventModifierFlags::NSShiftKeyMask, - self.modifiers.shift_pressed, - ) { - self.modifiers.shift_pressed = !self.modifiers.shift_pressed; - events.push_back(into_event(window_event)); - } - - if let Some(window_event) = modifier_event( - ns_event, - NSEventModifierFlags::NSControlKeyMask, - self.modifiers.ctrl_pressed, - ) { - self.modifiers.ctrl_pressed = !self.modifiers.ctrl_pressed; - events.push_back(into_event(window_event)); - } - - if let Some(window_event) = modifier_event( - ns_event, - NSEventModifierFlags::NSCommandKeyMask, - self.modifiers.win_pressed, - ) { - self.modifiers.win_pressed = !self.modifiers.win_pressed; - events.push_back(into_event(window_event)); - } - - if let Some(window_event) = modifier_event( - ns_event, - NSEventModifierFlags::NSAlternateKeyMask, - self.modifiers.alt_pressed, - ) { - self.modifiers.alt_pressed = !self.modifiers.alt_pressed; - events.push_back(into_event(window_event)); - } - - let event = events.pop_front(); - self.shared.pending_events - .lock() - .unwrap() - .extend(events.into_iter()); - event - }, - - appkit::NSMouseEntered => { - let window = match maybe_window.or_else(maybe_key_window) { - Some(window) => window, - None => return None, - }; - - let window_point = ns_event.locationInWindow(); - let view_point = if ns_window == cocoa::base::nil { - let ns_size = foundation::NSSize::new(0.0, 0.0); - let ns_rect = foundation::NSRect::new(window_point, ns_size); - let window_rect = window.window.convertRectFromScreen_(ns_rect); - window.view.convertPoint_fromView_(window_rect.origin, cocoa::base::nil) - } else { - window.view.convertPoint_fromView_(window_point, cocoa::base::nil) - }; - - let view_rect = NSView::frame(*window.view); - let x = view_point.x as f64; - let y = (view_rect.size.height - view_point.y) as f64; - let window_event = WindowEvent::CursorMoved { - device_id: DEVICE_ID, - position: (x, y).into(), - modifiers: event_mods(ns_event), - }; - let event = Event::WindowEvent { window_id: ::WindowId(window.id()), event: window_event }; - self.shared.pending_events.lock().unwrap().push_back(event); - Some(into_event(WindowEvent::CursorEntered { device_id: DEVICE_ID })) - }, - appkit::NSMouseExited => { Some(into_event(WindowEvent::CursorLeft { device_id: DEVICE_ID })) }, - - appkit::NSMouseMoved | - appkit::NSLeftMouseDragged | - appkit::NSOtherMouseDragged | - appkit::NSRightMouseDragged => { - // If the mouse movement was on one of our windows, use it. - // Otherwise, if one of our windows is the key window (receiving input), use it. - // Otherwise, return `None`. - match maybe_window.or_else(maybe_key_window) { - Some(_window) => (), - None => return None, - } - - let mut events = std::collections::VecDeque::with_capacity(3); - - let delta_x = ns_event.deltaX() as f64; - if delta_x != 0.0 { - let motion_event = DeviceEvent::Motion { axis: 0, value: delta_x }; - let event = Event::DeviceEvent { device_id: DEVICE_ID, event: motion_event }; - events.push_back(event); - } - - let delta_y = ns_event.deltaY() as f64; - if delta_y != 0.0 { - let motion_event = DeviceEvent::Motion { axis: 1, value: delta_y }; - let event = Event::DeviceEvent { device_id: DEVICE_ID, event: motion_event }; - events.push_back(event); - } - - if delta_x != 0.0 || delta_y != 0.0 { - let motion_event = DeviceEvent::MouseMotion { delta: (delta_x, delta_y) }; - let event = Event::DeviceEvent { device_id: DEVICE_ID, event: motion_event }; - events.push_back(event); - } - - let event = events.pop_front(); - self.shared.pending_events.lock().unwrap().extend(events.into_iter()); - event - }, - - appkit::NSScrollWheel => { - // If none of the windows received the scroll, return `None`. - if maybe_window.is_none() { - return None; - } - - use events::MouseScrollDelta::{LineDelta, PixelDelta}; - let delta = if ns_event.hasPreciseScrollingDeltas() == cocoa::base::YES { - PixelDelta(( - ns_event.scrollingDeltaX() as f64, - ns_event.scrollingDeltaY() as f64, - ).into()) - } else { - // TODO: This is probably wrong - LineDelta( - ns_event.scrollingDeltaX() as f32, - ns_event.scrollingDeltaY() as f32, - ) - }; - let phase = match ns_event.phase() { - NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => TouchPhase::Started, - NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended, - _ => TouchPhase::Moved, - }; - self.shared.pending_events.lock().unwrap().push_back(Event::DeviceEvent { - device_id: DEVICE_ID, - event: DeviceEvent::MouseWheel { - delta: if ns_event.hasPreciseScrollingDeltas() == cocoa::base::YES { - PixelDelta(( - ns_event.scrollingDeltaX() as f64, - ns_event.scrollingDeltaY() as f64, - ).into()) - } else { - LineDelta( - ns_event.scrollingDeltaX() as f32, - ns_event.scrollingDeltaY() as f32, - ) - }, - } - }); - let window_event = WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: delta, phase: phase, modifiers: event_mods(ns_event) }; - Some(into_event(window_event)) - }, - - appkit::NSEventTypePressure => { - let pressure = ns_event.pressure(); - let stage = ns_event.stage(); - let window_event = WindowEvent::TouchpadPressure { device_id: DEVICE_ID, pressure: pressure, stage: stage }; - Some(into_event(window_event)) - }, - - appkit::NSApplicationDefined => match ns_event.subtype() { - appkit::NSEventSubtype::NSApplicationActivatedEventType => { - Some(Event::Awakened) - }, - _ => None, - }, - - _ => None, - } - } - - pub fn create_proxy(&self) -> Proxy { - Proxy {} - } - -} - -impl Proxy { - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - // Awaken the event loop by triggering `NSApplicationActivatedEventType`. - unsafe { - let pool = foundation::NSAutoreleasePool::new(cocoa::base::nil); - let event = - NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( - cocoa::base::nil, - appkit::NSApplicationDefined, - foundation::NSPoint::new(0.0, 0.0), - appkit::NSEventModifierFlags::empty(), - 0.0, - 0, - cocoa::base::nil, - appkit::NSEventSubtype::NSApplicationActivatedEventType, - 0, - 0); - appkit::NSApp().postEvent_atStart_(event, cocoa::base::NO); - foundation::NSAutoreleasePool::drain(pool); - } - Ok(()) - } -} - -pub fn to_virtual_key_code(code: c_ushort) -> Option { - Some(match code { - 0x00 => events::VirtualKeyCode::A, - 0x01 => events::VirtualKeyCode::S, - 0x02 => events::VirtualKeyCode::D, - 0x03 => events::VirtualKeyCode::F, - 0x04 => events::VirtualKeyCode::H, - 0x05 => events::VirtualKeyCode::G, - 0x06 => events::VirtualKeyCode::Z, - 0x07 => events::VirtualKeyCode::X, - 0x08 => events::VirtualKeyCode::C, - 0x09 => events::VirtualKeyCode::V, - //0x0a => World 1, - 0x0b => events::VirtualKeyCode::B, - 0x0c => events::VirtualKeyCode::Q, - 0x0d => events::VirtualKeyCode::W, - 0x0e => events::VirtualKeyCode::E, - 0x0f => events::VirtualKeyCode::R, - 0x10 => events::VirtualKeyCode::Y, - 0x11 => events::VirtualKeyCode::T, - 0x12 => events::VirtualKeyCode::Key1, - 0x13 => events::VirtualKeyCode::Key2, - 0x14 => events::VirtualKeyCode::Key3, - 0x15 => events::VirtualKeyCode::Key4, - 0x16 => events::VirtualKeyCode::Key6, - 0x17 => events::VirtualKeyCode::Key5, - 0x18 => events::VirtualKeyCode::Equals, - 0x19 => events::VirtualKeyCode::Key9, - 0x1a => events::VirtualKeyCode::Key7, - 0x1b => events::VirtualKeyCode::Minus, - 0x1c => events::VirtualKeyCode::Key8, - 0x1d => events::VirtualKeyCode::Key0, - 0x1e => events::VirtualKeyCode::RBracket, - 0x1f => events::VirtualKeyCode::O, - 0x20 => events::VirtualKeyCode::U, - 0x21 => events::VirtualKeyCode::LBracket, - 0x22 => events::VirtualKeyCode::I, - 0x23 => events::VirtualKeyCode::P, - 0x24 => events::VirtualKeyCode::Return, - 0x25 => events::VirtualKeyCode::L, - 0x26 => events::VirtualKeyCode::J, - 0x27 => events::VirtualKeyCode::Apostrophe, - 0x28 => events::VirtualKeyCode::K, - 0x29 => events::VirtualKeyCode::Semicolon, - 0x2a => events::VirtualKeyCode::Backslash, - 0x2b => events::VirtualKeyCode::Comma, - 0x2c => events::VirtualKeyCode::Slash, - 0x2d => events::VirtualKeyCode::N, - 0x2e => events::VirtualKeyCode::M, - 0x2f => events::VirtualKeyCode::Period, - 0x30 => events::VirtualKeyCode::Tab, - 0x31 => events::VirtualKeyCode::Space, - 0x32 => events::VirtualKeyCode::Grave, - 0x33 => events::VirtualKeyCode::Back, - //0x34 => unkown, - 0x35 => events::VirtualKeyCode::Escape, - 0x36 => events::VirtualKeyCode::LWin, - 0x37 => events::VirtualKeyCode::RWin, - 0x38 => events::VirtualKeyCode::LShift, - //0x39 => Caps lock, - 0x3a => events::VirtualKeyCode::LAlt, - 0x3b => events::VirtualKeyCode::LControl, - 0x3c => events::VirtualKeyCode::RShift, - 0x3d => events::VirtualKeyCode::RAlt, - 0x3e => events::VirtualKeyCode::RControl, - //0x3f => Fn key, - 0x40 => events::VirtualKeyCode::F17, - 0x41 => events::VirtualKeyCode::Decimal, - //0x42 -> unkown, - 0x43 => events::VirtualKeyCode::Multiply, - //0x44 => unkown, - 0x45 => events::VirtualKeyCode::Add, - //0x46 => unkown, - 0x47 => events::VirtualKeyCode::Numlock, - //0x48 => KeypadClear, - 0x49 => events::VirtualKeyCode::VolumeUp, - 0x4a => events::VirtualKeyCode::VolumeDown, - 0x4b => events::VirtualKeyCode::Divide, - 0x4c => events::VirtualKeyCode::NumpadEnter, - //0x4d => unkown, - 0x4e => events::VirtualKeyCode::Subtract, - 0x4f => events::VirtualKeyCode::F18, - 0x50 => events::VirtualKeyCode::F19, - 0x51 => events::VirtualKeyCode::NumpadEquals, - 0x52 => events::VirtualKeyCode::Numpad0, - 0x53 => events::VirtualKeyCode::Numpad1, - 0x54 => events::VirtualKeyCode::Numpad2, - 0x55 => events::VirtualKeyCode::Numpad3, - 0x56 => events::VirtualKeyCode::Numpad4, - 0x57 => events::VirtualKeyCode::Numpad5, - 0x58 => events::VirtualKeyCode::Numpad6, - 0x59 => events::VirtualKeyCode::Numpad7, - 0x5a => events::VirtualKeyCode::F20, - 0x5b => events::VirtualKeyCode::Numpad8, - 0x5c => events::VirtualKeyCode::Numpad9, - 0x5d => events::VirtualKeyCode::Yen, - //0x5e => JIS Ro, - //0x5f => unkown, - 0x60 => events::VirtualKeyCode::F5, - 0x61 => events::VirtualKeyCode::F6, - 0x62 => events::VirtualKeyCode::F7, - 0x63 => events::VirtualKeyCode::F3, - 0x64 => events::VirtualKeyCode::F8, - 0x65 => events::VirtualKeyCode::F9, - //0x66 => JIS Eisuu (macOS), - 0x67 => events::VirtualKeyCode::F11, - //0x68 => JIS Kana (macOS), - 0x69 => events::VirtualKeyCode::F13, - 0x6a => events::VirtualKeyCode::F16, - 0x6b => events::VirtualKeyCode::F14, - //0x6c => unkown, - 0x6d => events::VirtualKeyCode::F10, - //0x6e => unkown, - 0x6f => events::VirtualKeyCode::F12, - //0x70 => unkown, - 0x71 => events::VirtualKeyCode::F15, - 0x72 => events::VirtualKeyCode::Insert, - 0x73 => events::VirtualKeyCode::Home, - 0x74 => events::VirtualKeyCode::PageUp, - 0x75 => events::VirtualKeyCode::Delete, - 0x76 => events::VirtualKeyCode::F4, - 0x77 => events::VirtualKeyCode::End, - 0x78 => events::VirtualKeyCode::F2, - 0x79 => events::VirtualKeyCode::PageDown, - 0x7a => events::VirtualKeyCode::F1, - 0x7b => events::VirtualKeyCode::Left, - 0x7c => events::VirtualKeyCode::Right, - 0x7d => events::VirtualKeyCode::Down, - 0x7e => events::VirtualKeyCode::Up, - //0x7f => unkown, - - 0xa => events::VirtualKeyCode::Caret, - _ => return None, - }) -} - -pub fn check_additional_virtual_key_codes( - s: &Option -) -> Option { - if let &Some(ref s) = s { - if let Some(ch) = s.encode_utf16().next() { - return Some(match ch { - 0xf718 => events::VirtualKeyCode::F21, - 0xf719 => events::VirtualKeyCode::F22, - 0xf71a => events::VirtualKeyCode::F23, - 0xf71b => events::VirtualKeyCode::F24, - _ => return None, - }) - } - } - None -} - -pub fn event_mods(event: cocoa::base::id) -> ModifiersState { - let flags = unsafe { - NSEvent::modifierFlags(event) - }; - ModifiersState { - shift: flags.contains(NSEventModifierFlags::NSShiftKeyMask), - ctrl: flags.contains(NSEventModifierFlags::NSControlKeyMask), - alt: flags.contains(NSEventModifierFlags::NSAlternateKeyMask), - logo: flags.contains(NSEventModifierFlags::NSCommandKeyMask), - } -} - -unsafe fn modifier_event( - ns_event: cocoa::base::id, - keymask: NSEventModifierFlags, - was_key_pressed: bool, -) -> Option { - if !was_key_pressed && NSEvent::modifierFlags(ns_event).contains(keymask) - || was_key_pressed && !NSEvent::modifierFlags(ns_event).contains(keymask) { - let state = if was_key_pressed { - ElementState::Released - } else { - ElementState::Pressed - }; - let keycode = NSEvent::keyCode(ns_event); - let scancode = keycode as u32; - let virtual_keycode = to_virtual_key_code(keycode); - Some(WindowEvent::KeyboardInput { - device_id: DEVICE_ID, - input: KeyboardInput { - state, - scancode, - virtual_keycode, - modifiers: event_mods(ns_event), - }, - }) - } else { - None - } -} - -// Constant device ID, to be removed when this backend is updated to report real device IDs. -pub const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId); diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/ffi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/ffi.rs deleted file mode 100644 index 31c9ed1..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/ffi.rs +++ /dev/null @@ -1,107 +0,0 @@ -// TODO: Upstream these - -#![allow(dead_code, non_snake_case, non_upper_case_globals)] - -use cocoa::base::id; -use cocoa::foundation::{NSInteger, NSUInteger}; -use objc; - -pub const NSNotFound: NSInteger = NSInteger::max_value(); - -#[repr(C)] -pub struct NSRange { - pub location: NSUInteger, - pub length: NSUInteger, -} - -impl NSRange { - #[inline] - pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { - NSRange { location, length } - } -} - -unsafe impl objc::Encode for NSRange { - fn encode() -> objc::Encoding { - let encoding = format!( - // TODO: Verify that this is correct - "{{NSRange={}{}}}", - NSUInteger::encode().as_str(), - NSUInteger::encode().as_str(), - ); - unsafe { objc::Encoding::from_str(&encoding) } - } -} - -pub trait NSMutableAttributedString: Sized { - unsafe fn alloc(_: Self) -> id { - msg_send![class!(NSMutableAttributedString), alloc] - } - - unsafe fn init(self) -> id; // *mut NSMutableAttributedString - unsafe fn initWithString(self, string: id) -> id; - unsafe fn initWithAttributedString(self, string: id) -> id; - - unsafe fn string(self) -> id; // *mut NSString - unsafe fn mutableString(self) -> id; // *mut NSMutableString - unsafe fn length(self) -> NSUInteger; -} - -impl NSMutableAttributedString for id { - unsafe fn init(self) -> id { - msg_send![self, init] - } - - unsafe fn initWithString(self, string: id) -> id { - msg_send![self, initWithString:string] - } - - unsafe fn initWithAttributedString(self, string: id) -> id { - msg_send![self, initWithAttributedString:string] - } - - unsafe fn string(self) -> id { - msg_send![self, string] - } - - unsafe fn mutableString(self) -> id { - msg_send![self, mutableString] - } - - unsafe fn length(self) -> NSUInteger { - msg_send![self, length] - } -} - -pub const kCGBaseWindowLevelKey: NSInteger = 0; -pub const kCGMinimumWindowLevelKey: NSInteger = 1; -pub const kCGDesktopWindowLevelKey: NSInteger = 2; -pub const kCGBackstopMenuLevelKey: NSInteger = 3; -pub const kCGNormalWindowLevelKey: NSInteger = 4; -pub const kCGFloatingWindowLevelKey: NSInteger = 5; -pub const kCGTornOffMenuWindowLevelKey: NSInteger = 6; -pub const kCGDockWindowLevelKey: NSInteger = 7; -pub const kCGMainMenuWindowLevelKey: NSInteger = 8; -pub const kCGStatusWindowLevelKey: NSInteger = 9; -pub const kCGModalPanelWindowLevelKey: NSInteger = 10; -pub const kCGPopUpMenuWindowLevelKey: NSInteger = 11; -pub const kCGDraggingWindowLevelKey: NSInteger = 12; -pub const kCGScreenSaverWindowLevelKey: NSInteger = 13; -pub const kCGMaximumWindowLevelKey: NSInteger = 14; -pub const kCGOverlayWindowLevelKey: NSInteger = 15; -pub const kCGHelpWindowLevelKey: NSInteger = 16; -pub const kCGUtilityWindowLevelKey: NSInteger = 17; -pub const kCGDesktopIconWindowLevelKey: NSInteger = 18; -pub const kCGCursorWindowLevelKey: NSInteger = 19; -pub const kCGNumberOfWindowLevelKeys: NSInteger = 20; - -pub enum NSWindowLevel { - NSNormalWindowLevel = kCGBaseWindowLevelKey as _, - NSFloatingWindowLevel = kCGFloatingWindowLevelKey as _, - NSTornOffMenuWindowLevel = kCGTornOffMenuWindowLevelKey as _, - NSModalPanelWindowLevel = kCGModalPanelWindowLevelKey as _, - NSMainMenuWindowLevel = kCGMainMenuWindowLevelKey as _, - NSStatusWindowLevel = kCGStatusWindowLevelKey as _, - NSPopUpMenuWindowLevel = kCGPopUpMenuWindowLevelKey as _, - NSScreenSaverWindowLevel = kCGScreenSaverWindowLevelKey as _, -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/mod.rs deleted file mode 100644 index 1091648..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/mod.rs +++ /dev/null @@ -1,51 +0,0 @@ -#![cfg(target_os = "macos")] - -pub use self::events_loop::{EventsLoop, Proxy as EventsLoopProxy}; -pub use self::monitor::MonitorId; -pub use self::window::{Id as WindowId, PlatformSpecificWindowBuilderAttributes, Window2}; -use std::sync::Arc; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DeviceId; - -impl DeviceId { - pub unsafe fn dummy() -> Self { - DeviceId - } -} - -use {CreationError}; - -pub struct Window { - pub window: Arc, -} - -impl ::std::ops::Deref for Window { - type Target = Window2; - #[inline] - fn deref(&self) -> &Window2 { - &*self.window - } -} - -impl Window { - - pub fn new(events_loop: &EventsLoop, - attributes: ::WindowAttributes, - pl_attribs: PlatformSpecificWindowBuilderAttributes) -> Result - { - let weak_shared = Arc::downgrade(&events_loop.shared); - let window = Arc::new(try!(Window2::new(weak_shared, attributes, pl_attribs))); - let weak_window = Arc::downgrade(&window); - events_loop.shared.windows.lock().unwrap().push(weak_window); - Ok(Window { window: window }) - } - -} - -mod events_loop; -mod ffi; -mod monitor; -mod util; -mod view; -mod window; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/monitor.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/monitor.rs deleted file mode 100644 index c8786f9..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/monitor.rs +++ /dev/null @@ -1,147 +0,0 @@ -use std::collections::VecDeque; -use std::fmt; - -use cocoa::appkit::NSScreen; -use cocoa::base::{id, nil}; -use cocoa::foundation::{NSString, NSUInteger}; -use core_graphics::display::{CGDirectDisplayID, CGDisplay, CGDisplayBounds}; - -use {PhysicalPosition, PhysicalSize}; -use super::EventsLoop; -use super::window::{IdRef, Window2}; - -#[derive(Clone, PartialEq)] -pub struct MonitorId(CGDirectDisplayID); - -fn get_available_monitors() -> VecDeque { - if let Ok(displays) = CGDisplay::active_displays() { - let mut monitors = VecDeque::with_capacity(displays.len()); - for d in displays { - monitors.push_back(MonitorId(d)); - } - monitors - } else { - VecDeque::with_capacity(0) - } -} - -pub fn get_primary_monitor() -> MonitorId { - let id = MonitorId(CGDisplay::main().id); - id -} - -impl EventsLoop { - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors() - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor() - } - - pub fn make_monitor_from_display(id: CGDirectDisplayID) -> MonitorId { - let id = MonitorId(id); - id - } -} - -impl Window2 { - #[inline] - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors() - } - - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor() - } -} - -impl fmt::Debug for MonitorId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - #[derive(Debug)] - struct MonitorId { - name: Option, - native_identifier: u32, - dimensions: PhysicalSize, - position: PhysicalPosition, - hidpi_factor: f64, - } - - let monitor_id_proxy = MonitorId { - name: self.get_name(), - native_identifier: self.get_native_identifier(), - dimensions: self.get_dimensions(), - position: self.get_position(), - hidpi_factor: self.get_hidpi_factor(), - }; - - monitor_id_proxy.fmt(f) - } -} - -impl MonitorId { - pub fn get_name(&self) -> Option { - let MonitorId(display_id) = *self; - let screen_num = CGDisplay::new(display_id).model_number(); - Some(format!("Monitor #{}", screen_num)) - } - - #[inline] - pub fn get_native_identifier(&self) -> u32 { - self.0 - } - - pub fn get_dimensions(&self) -> PhysicalSize { - let MonitorId(display_id) = *self; - let display = CGDisplay::new(display_id); - let height = display.pixels_high(); - let width = display.pixels_wide(); - PhysicalSize::from_logical( - (width as f64, height as f64), - self.get_hidpi_factor(), - ) - } - - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - let bounds = unsafe { CGDisplayBounds(self.get_native_identifier()) }; - PhysicalPosition::from_logical( - (bounds.origin.x as f64, bounds.origin.y as f64), - self.get_hidpi_factor(), - ) - } - - pub fn get_hidpi_factor(&self) -> f64 { - let screen = match self.get_nsscreen() { - Some(screen) => screen, - None => return 1.0, // default to 1.0 when we can't find the screen - }; - unsafe { NSScreen::backingScaleFactor(screen) as f64 } - } - - pub(crate) fn get_nsscreen(&self) -> Option { - unsafe { - let native_id = self.get_native_identifier(); - let screens = NSScreen::screens(nil); - let count: NSUInteger = msg_send![screens, count]; - let key = IdRef::new(NSString::alloc(nil).init_str("NSScreenNumber")); - let mut matching_screen: Option = None; - for i in 0..count { - let screen = msg_send![screens, objectAtIndex: i as NSUInteger]; - let device_description = NSScreen::deviceDescription(screen); - let value: id = msg_send![device_description, objectForKey:*key]; - if value != nil { - let screen_number: NSUInteger = msg_send![value, unsignedIntegerValue]; - if screen_number as u32 == native_id { - matching_screen = Some(screen); - break; - } - } - } - matching_screen - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/cursor.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/cursor.rs deleted file mode 100644 index e7815d7..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/cursor.rs +++ /dev/null @@ -1,149 +0,0 @@ -use cocoa::{ - appkit::NSImage, base::{id, nil, YES}, - foundation::{NSDictionary, NSPoint, NSString}, -}; -use objc::runtime::Sel; - -use super::IntoOption; -use MouseCursor; - -pub enum Cursor { - Native(&'static str), - Undocumented(&'static str), - WebKit(&'static str), -} - -impl From for Cursor { - fn from(cursor: MouseCursor) -> Self { - match cursor { - MouseCursor::Arrow | MouseCursor::Default => Cursor::Native("arrowCursor"), - MouseCursor::Hand => Cursor::Native("pointingHandCursor"), - MouseCursor::Grabbing | MouseCursor::Grab => Cursor::Native("closedHandCursor"), - MouseCursor::Text => Cursor::Native("IBeamCursor"), - MouseCursor::VerticalText => Cursor::Native("IBeamCursorForVerticalLayout"), - MouseCursor::Copy => Cursor::Native("dragCopyCursor"), - MouseCursor::Alias => Cursor::Native("dragLinkCursor"), - MouseCursor::NotAllowed | MouseCursor::NoDrop => Cursor::Native("operationNotAllowedCursor"), - MouseCursor::ContextMenu => Cursor::Native("contextualMenuCursor"), - MouseCursor::Crosshair => Cursor::Native("crosshairCursor"), - MouseCursor::EResize => Cursor::Native("resizeRightCursor"), - MouseCursor::NResize => Cursor::Native("resizeUpCursor"), - MouseCursor::WResize => Cursor::Native("resizeLeftCursor"), - MouseCursor::SResize => Cursor::Native("resizeDownCursor"), - MouseCursor::EwResize | MouseCursor::ColResize => Cursor::Native("resizeLeftRightCursor"), - MouseCursor::NsResize | MouseCursor::RowResize => Cursor::Native("resizeUpDownCursor"), - - // Undocumented cursors: https://stackoverflow.com/a/46635398/5435443 - MouseCursor::Help => Cursor::Undocumented("_helpCursor"), - MouseCursor::ZoomIn => Cursor::Undocumented("_zoomInCursor"), - MouseCursor::ZoomOut => Cursor::Undocumented("_zoomOutCursor"), - MouseCursor::NeResize => Cursor::Undocumented("_windowResizeNorthEastCursor"), - MouseCursor::NwResize => Cursor::Undocumented("_windowResizeNorthWestCursor"), - MouseCursor::SeResize => Cursor::Undocumented("_windowResizeSouthEastCursor"), - MouseCursor::SwResize => Cursor::Undocumented("_windowResizeSouthWestCursor"), - MouseCursor::NeswResize => Cursor::Undocumented("_windowResizeNorthEastSouthWestCursor"), - MouseCursor::NwseResize => Cursor::Undocumented("_windowResizeNorthWestSouthEastCursor"), - - // While these are available, the former just loads a white arrow, - // and the latter loads an ugly deflated beachball! - // MouseCursor::Move => Cursor::Undocumented("_moveCursor"), - // MouseCursor::Wait => Cursor::Undocumented("_waitCursor"), - - // An even more undocumented cursor... - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=522349 - // This is the wrong semantics for `Wait`, but it's the same as - // what's used in Safari and Chrome. - MouseCursor::Wait | MouseCursor::Progress => Cursor::Undocumented("busyButClickableCursor"), - - // For the rest, we can just snatch the cursors from WebKit... - // They fit the style of the native cursors, and will seem - // completely standard to macOS users. - // https://stackoverflow.com/a/21786835/5435443 - MouseCursor::Move | MouseCursor::AllScroll => Cursor::WebKit("move"), - MouseCursor::Cell => Cursor::WebKit("cell"), - } - } -} - -impl Default for Cursor { - fn default() -> Self { - Cursor::Native("arrowCursor") - } -} - -impl Cursor { - pub unsafe fn load(&self) -> id { - match self { - Cursor::Native(cursor_name) => { - let sel = Sel::register(cursor_name); - msg_send![class!(NSCursor), performSelector:sel] - }, - Cursor::Undocumented(cursor_name) => { - let class = class!(NSCursor); - let sel = Sel::register(cursor_name); - let sel = if msg_send![class, respondsToSelector:sel] { - sel - } else { - warn!("Cursor `{}` appears to be invalid", cursor_name); - sel!(arrowCursor) - }; - msg_send![class, performSelector:sel] - }, - Cursor::WebKit(cursor_name) => load_webkit_cursor(cursor_name) - .unwrap_or_else(|message| { - warn!("{}", message); - Self::default().load() - }), - } - } -} - -// Note that loading `busybutclickable` with this code won't animate the frames; -// instead you'll just get them all in a column. -unsafe fn load_webkit_cursor(cursor_name_str: &str) -> Result { - static CURSOR_ROOT: &'static str = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors"; - let cursor_root = NSString::alloc(nil).init_str(CURSOR_ROOT); - let cursor_name = NSString::alloc(nil).init_str(cursor_name_str); - let cursor_pdf = NSString::alloc(nil).init_str("cursor.pdf"); - let cursor_plist = NSString::alloc(nil).init_str("info.plist"); - let key_x = NSString::alloc(nil).init_str("hotx"); - let key_y = NSString::alloc(nil).init_str("hoty"); - - let cursor_path: id = msg_send![cursor_root, - stringByAppendingPathComponent:cursor_name - ]; - let pdf_path: id = msg_send![cursor_path, - stringByAppendingPathComponent:cursor_pdf - ]; - let info_path: id = msg_send![cursor_path, - stringByAppendingPathComponent:cursor_plist - ]; - - let image = NSImage::alloc(nil) - .initByReferencingFile_(pdf_path) - // This will probably never be `None`, since images are loaded lazily... - .into_option() - // because of that, we need to check for validity. - .filter(|image| image.isValid() == YES) - .ok_or_else(|| - format!("Failed to read image for `{}` cursor", cursor_name_str) - )?; - let info = NSDictionary::dictionaryWithContentsOfFile_(nil, info_path) - .into_option() - .ok_or_else(|| - format!("Failed to read info for `{}` cursor", cursor_name_str) - )?; - let x = info.valueForKey_(key_x); - let y = info.valueForKey_(key_y); - let point = NSPoint::new( - msg_send![x, doubleValue], - msg_send![y, doubleValue], - ); - let cursor: id = msg_send![class!(NSCursor), alloc]; - let cursor: id = msg_send![cursor, initWithImage:image hotSpot:point]; - cursor - .into_option() - .ok_or_else(|| - format!("Failed to initialize `{}` cursor", cursor_name_str) - ) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/into_option.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/into_option.rs deleted file mode 100644 index 4fd32e7..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/into_option.rs +++ /dev/null @@ -1,14 +0,0 @@ -use cocoa::base::{id, nil}; - -pub trait IntoOption: Sized { - fn into_option(self) -> Option; -} - -impl IntoOption for id { - fn into_option(self) -> Option { - match self != nil { - true => Some(self), - false => None, - } - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/mod.rs deleted file mode 100644 index baa0e6e..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/util/mod.rs +++ /dev/null @@ -1,63 +0,0 @@ -mod cursor; -mod into_option; - -pub use self::{cursor::Cursor, into_option::IntoOption}; - -use cocoa::appkit::NSWindowStyleMask; -use cocoa::base::{id, nil}; -use cocoa::foundation::{NSRect, NSUInteger}; -use core_graphics::display::CGDisplay; -use objc::runtime::{Class, Object}; - -use platform::platform::ffi; -use platform::platform::window::IdRef; - -pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange { - location: ffi::NSNotFound as NSUInteger, - length: 0, -}; - -// For consistency with other platforms, this will... -// 1. translate the bottom-left window corner into the top-left window corner -// 2. translate the coordinate from a bottom-left origin coordinate system to a top-left one -pub fn bottom_left_to_top_left(rect: NSRect) -> f64 { - CGDisplay::main().pixels_high() as f64 - (rect.origin.y + rect.size.height) -} - -pub unsafe fn set_style_mask(window: id, view: id, mask: NSWindowStyleMask) { - use cocoa::appkit::NSWindow; - window.setStyleMask_(mask); - // If we don't do this, key handling will break. Therefore, never call `setStyleMask` directly! - window.makeFirstResponder_(view); -} - -pub unsafe fn toggle_style_mask(window: id, view: id, mask: NSWindowStyleMask, on: bool) { - use cocoa::appkit::NSWindow; - - let current_style_mask = window.styleMask(); - if on { - window.setStyleMask_(current_style_mask | mask); - } else { - window.setStyleMask_(current_style_mask & (!mask)); - } - - // If we don't do this, key handling will break. Therefore, never call `setStyleMask` directly! - window.makeFirstResponder_(view); -} - -pub unsafe fn superclass<'a>(this: &'a Object) -> &'a Class { - let superclass: id = msg_send![this, superclass]; - &*(superclass as *const _) -} - -pub unsafe fn create_input_context(view: id) -> IdRef { - let input_context: id = msg_send![class!(NSTextInputContext), alloc]; - let input_context: id = msg_send![input_context, initWithClient:view]; - IdRef::new(input_context) -} - -#[allow(dead_code)] -pub unsafe fn open_emoji_picker() { - let app: id = msg_send![class!(NSApplication), sharedApplication]; - let _: () = msg_send![app, orderFrontCharacterPalette:nil]; -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/view.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/view.rs deleted file mode 100644 index 97372d1..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/view.rs +++ /dev/null @@ -1,648 +0,0 @@ -// This is a pretty close port of the implementation in GLFW: -// https://github.com/glfw/glfw/blob/7ef34eb06de54dd9186d3d21a401b2ef819b59e7/src/cocoa_window.m - -use std::{slice, str}; -use std::boxed::Box; -use std::collections::VecDeque; -use std::os::raw::*; -use std::sync::{Arc, Mutex, Weak}; - -use cocoa::base::{id, nil}; -use cocoa::appkit::{NSEvent, NSView, NSWindow}; -use cocoa::foundation::{NSPoint, NSRect, NSSize, NSString, NSUInteger}; -use objc::declare::ClassDecl; -use objc::runtime::{Class, Object, Protocol, Sel, BOOL, YES}; - -use {ElementState, Event, KeyboardInput, MouseButton, WindowEvent, WindowId}; -use platform::platform::events_loop::{DEVICE_ID, event_mods, Shared, to_virtual_key_code, check_additional_virtual_key_codes}; -use platform::platform::util; -use platform::platform::ffi::*; -use platform::platform::window::{get_window_id, IdRef}; - -struct ViewState { - window: id, - shared: Weak, - cursor: Arc>, - ime_spot: Option<(f64, f64)>, - raw_characters: Option, - is_key_down: bool, -} - -pub fn new_view(window: id, shared: Weak) -> (IdRef, Weak>) { - let cursor = Default::default(); - let cursor_access = Arc::downgrade(&cursor); - let state = ViewState { - window, - shared, - cursor, - ime_spot: None, - raw_characters: None, - is_key_down: false, - }; - unsafe { - // This is free'd in `dealloc` - let state_ptr = Box::into_raw(Box::new(state)) as *mut c_void; - let view: id = msg_send![VIEW_CLASS.0, alloc]; - (IdRef::new(msg_send![view, initWithWinit:state_ptr]), cursor_access) - } -} - -pub fn set_ime_spot(view: id, input_context: id, x: f64, y: f64) { - unsafe { - let state_ptr: *mut c_void = *(*view).get_mut_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - let content_rect = NSWindow::contentRectForFrameRect_( - state.window, - NSWindow::frame(state.window), - ); - let base_x = content_rect.origin.x as f64; - let base_y = (content_rect.origin.y + content_rect.size.height) as f64; - state.ime_spot = Some((base_x + x, base_y - y)); - let _: () = msg_send![input_context, invalidateCharacterCoordinates]; - } -} - -struct ViewClass(*const Class); -unsafe impl Send for ViewClass {} -unsafe impl Sync for ViewClass {} - -lazy_static! { - static ref VIEW_CLASS: ViewClass = unsafe { - let superclass = class!(NSView); - let mut decl = ClassDecl::new("WinitView", superclass).unwrap(); - decl.add_method(sel!(dealloc), dealloc as extern fn(&Object, Sel)); - decl.add_method( - sel!(initWithWinit:), - init_with_winit as extern fn(&Object, Sel, *mut c_void) -> id, - ); - decl.add_method( - sel!(drawRect:), - draw_rect as extern fn(&Object, Sel, NSRect), - ); - decl.add_method( - sel!(resetCursorRects), - reset_cursor_rects as extern fn(&Object, Sel), - ); - decl.add_method(sel!(hasMarkedText), has_marked_text as extern fn(&Object, Sel) -> BOOL); - decl.add_method( - sel!(markedRange), - marked_range as extern fn(&Object, Sel) -> NSRange, - ); - decl.add_method(sel!(selectedRange), selected_range as extern fn(&Object, Sel) -> NSRange); - decl.add_method( - sel!(setMarkedText:selectedRange:replacementRange:), - set_marked_text as extern fn(&mut Object, Sel, id, NSRange, NSRange), - ); - decl.add_method(sel!(unmarkText), unmark_text as extern fn(&Object, Sel)); - decl.add_method( - sel!(validAttributesForMarkedText), - valid_attributes_for_marked_text as extern fn(&Object, Sel) -> id, - ); - decl.add_method( - sel!(attributedSubstringForProposedRange:actualRange:), - attributed_substring_for_proposed_range - as extern fn(&Object, Sel, NSRange, *mut c_void) -> id, - ); - decl.add_method( - sel!(insertText:replacementRange:), - insert_text as extern fn(&Object, Sel, id, NSRange), - ); - decl.add_method( - sel!(characterIndexForPoint:), - character_index_for_point as extern fn(&Object, Sel, NSPoint) -> NSUInteger, - ); - decl.add_method( - sel!(firstRectForCharacterRange:actualRange:), - first_rect_for_character_range - as extern fn(&Object, Sel, NSRange, *mut c_void) -> NSRect, - ); - decl.add_method( - sel!(doCommandBySelector:), - do_command_by_selector as extern fn(&Object, Sel, Sel), - ); - decl.add_method(sel!(keyDown:), key_down as extern fn(&Object, Sel, id)); - decl.add_method(sel!(keyUp:), key_up as extern fn(&Object, Sel, id)); - decl.add_method(sel!(insertTab:), insert_tab as extern fn(&Object, Sel, id)); - decl.add_method(sel!(insertBackTab:), insert_back_tab as extern fn(&Object, Sel, id)); - decl.add_method(sel!(mouseDown:), mouse_down as extern fn(&Object, Sel, id)); - decl.add_method(sel!(mouseUp:), mouse_up as extern fn(&Object, Sel, id)); - decl.add_method(sel!(rightMouseDown:), right_mouse_down as extern fn(&Object, Sel, id)); - decl.add_method(sel!(rightMouseUp:), right_mouse_up as extern fn(&Object, Sel, id)); - decl.add_method(sel!(otherMouseDown:), other_mouse_down as extern fn(&Object, Sel, id)); - decl.add_method(sel!(otherMouseUp:), other_mouse_up as extern fn(&Object, Sel, id)); - decl.add_method(sel!(mouseMoved:), mouse_moved as extern fn(&Object, Sel, id)); - decl.add_method(sel!(mouseDragged:), mouse_dragged as extern fn(&Object, Sel, id)); - decl.add_method(sel!(rightMouseDragged:), right_mouse_dragged as extern fn(&Object, Sel, id)); - decl.add_method(sel!(otherMouseDragged:), other_mouse_dragged as extern fn(&Object, Sel, id)); - decl.add_method(sel!(_wantsKeyDownForEvent:), wants_key_down_for_event as extern fn(&Object, Sel, id) -> BOOL); - decl.add_ivar::<*mut c_void>("winitState"); - decl.add_ivar::("markedText"); - let protocol = Protocol::get("NSTextInputClient").unwrap(); - decl.add_protocol(&protocol); - ViewClass(decl.register()) - }; -} - -extern fn dealloc(this: &Object, _sel: Sel) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let marked_text: id = *this.get_ivar("markedText"); - let _: () = msg_send![marked_text, release]; - Box::from_raw(state as *mut ViewState); - } -} - -extern fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> id { - unsafe { - let this: id = msg_send![this, init]; - if this != nil { - (*this).set_ivar("winitState", state); - let marked_text = ::init( - NSMutableAttributedString::alloc(nil), - ); - (*this).set_ivar("markedText", marked_text); - } - this - } -} - -extern fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) { - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - if let Some(shared) = state.shared.upgrade() { - let window_event = Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::Refresh, - }; - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - } - - let superclass = util::superclass(this); - let () = msg_send![super(this, superclass), drawRect:rect]; - } -} - -extern fn reset_cursor_rects(this: &Object, _sel: Sel) { - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - let bounds: NSRect = msg_send![this, bounds]; - let cursor = state.cursor.lock().unwrap().load(); - let _: () = msg_send![this, - addCursorRect:bounds - cursor:cursor - ]; - } -} - -extern fn has_marked_text(this: &Object, _sel: Sel) -> BOOL { - //println!("hasMarkedText"); - unsafe { - let marked_text: id = *this.get_ivar("markedText"); - (marked_text.length() > 0) as i8 - } -} - -extern fn marked_range(this: &Object, _sel: Sel) -> NSRange { - //println!("markedRange"); - unsafe { - let marked_text: id = *this.get_ivar("markedText"); - let length = marked_text.length(); - if length > 0 { - NSRange::new(0, length - 1) - } else { - util::EMPTY_RANGE - } - } -} - -extern fn selected_range(_this: &Object, _sel: Sel) -> NSRange { - //println!("selectedRange"); - util::EMPTY_RANGE -} - -extern fn set_marked_text( - this: &mut Object, - _sel: Sel, - string: id, - _selected_range: NSRange, - _replacement_range: NSRange, -) { - //println!("setMarkedText"); - unsafe { - let marked_text_ref: &mut id = this.get_mut_ivar("markedText"); - let _: () = msg_send![(*marked_text_ref), release]; - let marked_text = NSMutableAttributedString::alloc(nil); - let has_attr = msg_send![string, isKindOfClass:class!(NSAttributedString)]; - if has_attr { - marked_text.initWithAttributedString(string); - } else { - marked_text.initWithString(string); - }; - *marked_text_ref = marked_text; - } -} - -extern fn unmark_text(this: &Object, _sel: Sel) { - //println!("unmarkText"); - unsafe { - let marked_text: id = *this.get_ivar("markedText"); - let mutable_string = marked_text.mutableString(); - let _: () = msg_send![mutable_string, setString:""]; - let input_context: id = msg_send![this, inputContext]; - let _: () = msg_send![input_context, discardMarkedText]; - } -} - -extern fn valid_attributes_for_marked_text(_this: &Object, _sel: Sel) -> id { - //println!("validAttributesForMarkedText"); - unsafe { msg_send![class!(NSArray), array] } -} - -extern fn attributed_substring_for_proposed_range( - _this: &Object, - _sel: Sel, - _range: NSRange, - _actual_range: *mut c_void, // *mut NSRange -) -> id { - //println!("attributedSubstringForProposedRange"); - nil -} - -extern fn character_index_for_point(_this: &Object, _sel: Sel, _point: NSPoint) -> NSUInteger { - //println!("characterIndexForPoint"); - 0 -} - -extern fn first_rect_for_character_range( - this: &Object, - _sel: Sel, - _range: NSRange, - _actual_range: *mut c_void, // *mut NSRange -) -> NSRect { - //println!("firstRectForCharacterRange"); - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - let (x, y) = state.ime_spot.unwrap_or_else(|| { - let content_rect = NSWindow::contentRectForFrameRect_( - state.window, - NSWindow::frame(state.window), - ); - let x = content_rect.origin.x; - let y = util::bottom_left_to_top_left(content_rect); - (x, y) - }); - - NSRect::new( - NSPoint::new(x as _, y as _), - NSSize::new(0.0, 0.0), - ) - } -} - -extern fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_range: NSRange) { - //println!("insertText"); - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - let has_attr = msg_send![string, isKindOfClass:class!(NSAttributedString)]; - let characters = if has_attr { - // This is a *mut NSAttributedString - msg_send![string, string] - } else { - // This is already a *mut NSString - string - }; - - let slice = slice::from_raw_parts( - characters.UTF8String() as *const c_uchar, - characters.len(), - ); - let string = str::from_utf8_unchecked(slice); - state.is_key_down = true; - - // We don't need this now, but it's here if that changes. - //let event: id = msg_send![class!(NSApp), currentEvent]; - - let mut events = VecDeque::with_capacity(characters.len()); - for character in string.chars() { - events.push_back(Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::ReceivedCharacter(character), - }); - } - - if let Some(shared) = state.shared.upgrade() { - shared.pending_events - .lock() - .unwrap() - .append(&mut events); - } - } -} - -extern fn do_command_by_selector(this: &Object, _sel: Sel, command: Sel) { - //println!("doCommandBySelector"); - // Basically, we're sent this message whenever a keyboard event that doesn't generate a "human readable" character - // happens, i.e. newlines, tabs, and Ctrl+C. - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - let shared = if let Some(shared) = state.shared.upgrade() { - shared - } else { - return; - }; - - let mut events = VecDeque::with_capacity(1); - if command == sel!(insertNewline:) { - // The `else` condition would emit the same character, but I'm keeping this here both... - // 1) as a reminder for how `doCommandBySelector` works - // 2) to make our use of carriage return explicit - events.push_back(Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::ReceivedCharacter('\r'), - }); - } else { - let raw_characters = state.raw_characters.take(); - if let Some(raw_characters) = raw_characters { - for character in raw_characters.chars() { - events.push_back(Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::ReceivedCharacter(character), - }); - } - } - }; - - shared.pending_events - .lock() - .unwrap() - .append(&mut events); - } -} - -fn get_characters(event: id) -> Option { - unsafe { - let characters: id = msg_send![event, characters]; - let slice = slice::from_raw_parts( - characters.UTF8String() as *const c_uchar, - characters.len(), - ); - let string = str::from_utf8_unchecked(slice); - Some(string.to_owned()) - } -} - -extern fn key_down(this: &Object, _sel: Sel, event: id) { - //println!("keyDown"); - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - let window_id = WindowId(get_window_id(state.window)); - - state.raw_characters = get_characters(event); - - let keycode: c_ushort = msg_send![event, keyCode]; - // We are checking here for F21-F24 keys, since their keycode - // can vary, but we know that they are encoded - // in characters property. - let virtual_keycode = to_virtual_key_code(keycode) - .or_else(|| { - check_additional_virtual_key_codes(&state.raw_characters) - }); - let scancode = keycode as u32; - let is_repeat = msg_send![event, isARepeat]; - - let window_event = Event::WindowEvent { - window_id, - event: WindowEvent::KeyboardInput { - device_id: DEVICE_ID, - input: KeyboardInput { - state: ElementState::Pressed, - scancode, - virtual_keycode, - modifiers: event_mods(event), - }, - }, - }; - - let characters: id = msg_send![event, characters]; - let slice = slice::from_raw_parts( - characters.UTF8String() as *const c_uchar, - characters.len(), - ); - let string = str::from_utf8_unchecked(slice); - - state.raw_characters = { - Some(string.to_owned()) - }; - - if let Some(shared) = state.shared.upgrade() { - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - // Emit `ReceivedCharacter` for key repeats - if is_repeat && state.is_key_down{ - for character in string.chars() { - let window_event = Event::WindowEvent { - window_id, - event: WindowEvent::ReceivedCharacter(character), - }; - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - } - } else { - // Some keys (and only *some*, with no known reason) don't trigger `insertText`, while others do... - // So, we don't give repeats the opportunity to trigger that, since otherwise our hack will cause some - // keys to generate twice as many characters. - let array: id = msg_send![class!(NSArray), arrayWithObject:event]; - let (): _ = msg_send![this, interpretKeyEvents:array]; - } - } - } -} - -extern fn key_up(this: &Object, _sel: Sel, event: id) { - //println!("keyUp"); - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - state.is_key_down = false; - - // We need characters here to check for additional keys such as - // F21-F24. - let characters = get_characters(event); - - let keycode: c_ushort = msg_send![event, keyCode]; - let virtual_keycode = to_virtual_key_code(keycode) - .or_else(|| { - check_additional_virtual_key_codes(&characters) - }); - let scancode = keycode as u32; - let window_event = Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::KeyboardInput { - device_id: DEVICE_ID, - input: KeyboardInput { - state: ElementState::Released, - scancode, - virtual_keycode, - modifiers: event_mods(event), - }, - }, - }; - - if let Some(shared) = state.shared.upgrade() { - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - } - } -} - -extern fn insert_tab(this: &Object, _sel: Sel, _sender: id) { - unsafe { - let window: id = msg_send![this, window]; - let first_responder: id = msg_send![window, firstResponder]; - let this_ptr = this as *const _ as *mut _; - if first_responder == this_ptr { - let (): _ = msg_send![window, selectNextKeyView:this]; - } - } -} - -extern fn insert_back_tab(this: &Object, _sel: Sel, _sender: id) { - unsafe { - let window: id = msg_send![this, window]; - let first_responder: id = msg_send![window, firstResponder]; - let this_ptr = this as *const _ as *mut _; - if first_responder == this_ptr { - let (): _ = msg_send![window, selectPreviousKeyView:this]; - } - } -} - -fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: ElementState) { - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - let window_event = Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::MouseInput { - device_id: DEVICE_ID, - state: button_state, - button, - modifiers: event_mods(event), - }, - }; - - if let Some(shared) = state.shared.upgrade() { - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - } - } -} - -extern fn mouse_down(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Left, ElementState::Pressed); -} - -extern fn mouse_up(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Left, ElementState::Released); -} - -extern fn right_mouse_down(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Right, ElementState::Pressed); -} - -extern fn right_mouse_up(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Right, ElementState::Released); -} - -extern fn other_mouse_down(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Middle, ElementState::Pressed); -} - -extern fn other_mouse_up(this: &Object, _sel: Sel, event: id) { - mouse_click(this, event, MouseButton::Middle, ElementState::Released); -} - -fn mouse_motion(this: &Object, event: id) { - unsafe { - let state_ptr: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state_ptr as *mut ViewState); - - // We have to do this to have access to the `NSView` trait... - let view: id = this as *const _ as *mut _; - - let window_point = event.locationInWindow(); - let view_point = view.convertPoint_fromView_(window_point, nil); - let view_rect = NSView::frame(view); - - if view_point.x.is_sign_negative() - || view_point.y.is_sign_negative() - || view_point.x > view_rect.size.width - || view_point.y > view_rect.size.height { - // Point is outside of the client area (view) - return; - } - - let x = view_point.x as f64; - let y = view_rect.size.height as f64 - view_point.y as f64; - - let window_event = Event::WindowEvent { - window_id: WindowId(get_window_id(state.window)), - event: WindowEvent::CursorMoved { - device_id: DEVICE_ID, - position: (x, y).into(), - modifiers: event_mods(event), - }, - }; - - if let Some(shared) = state.shared.upgrade() { - shared.pending_events - .lock() - .unwrap() - .push_back(window_event); - } - } -} - -extern fn mouse_moved(this: &Object, _sel: Sel, event: id) { - mouse_motion(this, event); -} - -extern fn mouse_dragged(this: &Object, _sel: Sel, event: id) { - mouse_motion(this, event); -} - -extern fn right_mouse_dragged(this: &Object, _sel: Sel, event: id) { - mouse_motion(this, event); -} - -extern fn other_mouse_dragged(this: &Object, _sel: Sel, event: id) { - mouse_motion(this, event); -} - -// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 -extern fn wants_key_down_for_event(_this: &Object, _se: Sel, _event: id) -> BOOL { - YES -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/window.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/window.rs deleted file mode 100644 index 4fc2732..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/macos/window.rs +++ /dev/null @@ -1,1362 +0,0 @@ -use std; -use std::cell::{Cell, RefCell}; -use std::f64; -use std::ops::Deref; -use std::os::raw::c_void; -use std::sync::{Mutex, Weak}; -use std::sync::atomic::{Ordering, AtomicBool}; - -use cocoa::appkit::{ - self, - CGFloat, - NSApp, - NSApplication, - NSColor, - NSRequestUserAttentionType, - NSScreen, - NSView, - NSWindow, - NSWindowButton, - NSWindowStyleMask, - NSApplicationActivationPolicy, - NSApplicationPresentationOptions, -}; -use cocoa::base::{id, nil}; -use cocoa::foundation::{NSAutoreleasePool, NSDictionary, NSPoint, NSRect, NSSize, NSString}; - -use core_graphics::display::CGDisplay; - -use objc; -use objc::runtime::{Class, Object, Sel, BOOL, YES, NO}; -use objc::declare::ClassDecl; - -use { - CreationError, - Event, - LogicalPosition, - LogicalSize, - MouseCursor, - WindowAttributes, - WindowEvent, - WindowId, -}; -use CreationError::OsError; -use os::macos::{ActivationPolicy, WindowExt}; -use platform::platform::{ffi, util}; -use platform::platform::events_loop::{EventsLoop, Shared}; -use platform::platform::view::{new_view, set_ime_spot}; -use window::MonitorId as RootMonitorId; - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Id(pub usize); - -impl Id { - pub unsafe fn dummy() -> Self { - Id(0) - } -} - -// TODO: It's possible for delegate methods to be called asynchronously, causing data races / `RefCell` panics. -pub struct DelegateState { - view: IdRef, - window: IdRef, - shared: Weak, - - win_attribs: RefCell, - standard_frame: Cell>, - is_simple_fullscreen: Cell, - save_style_mask: Cell>, - save_presentation_opts: Cell>, - - // This is set when WindowBuilder::with_fullscreen was set, - // see comments of `window_did_fail_to_enter_fullscreen` - handle_with_fullscreen: bool, - - // During `windowDidResize`, we use this to only send Moved if the position changed. - previous_position: Option<(f64, f64)>, - - // Used to prevent redundant events. - previous_dpi_factor: f64, -} - -impl DelegateState { - fn is_zoomed(&self) -> bool { - unsafe { - // Because isZoomed do not work in Borderless mode, we set it - // resizable temporality - let curr_mask = self.window.styleMask(); - - let required = NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; - let needs_temp_mask = !curr_mask.contains(required); - if needs_temp_mask { - util::set_style_mask(*self.window, *self.view, required); - } - - let is_zoomed: BOOL = msg_send![*self.window, isZoomed]; - - // Roll back temp styles - if needs_temp_mask { - util::set_style_mask(*self.window, *self.view, curr_mask); - } - - is_zoomed != 0 - } - } - - unsafe fn saved_style_mask(&self, resizable: bool) -> NSWindowStyleMask { - let base_mask = self.save_style_mask - .take() - .unwrap_or_else(|| self.window.styleMask()); - if resizable { - base_mask | NSWindowStyleMask::NSResizableWindowMask - } else { - base_mask & !NSWindowStyleMask::NSResizableWindowMask - } - } - - fn saved_standard_frame(&self) -> NSRect { - self.standard_frame.get().unwrap_or_else(|| NSRect::new( - NSPoint::new(50.0, 50.0), - NSSize::new(800.0, 600.0), - )) - } - - fn restore_state_from_fullscreen(&mut self) { - let maximized = unsafe { - let mut win_attribs = self.win_attribs.borrow_mut(); - win_attribs.fullscreen = None; - - let mask = self.saved_style_mask(win_attribs.resizable); - util::set_style_mask(*self.window, *self.view, mask); - - win_attribs.maximized - }; - - self.perform_maximized(maximized); - } - - fn perform_maximized(&self, maximized: bool) { - let is_zoomed = self.is_zoomed(); - - if is_zoomed == maximized { - return; - } - - // Save the standard frame sized if it is not zoomed - if !is_zoomed { - unsafe { - self.standard_frame.set(Some(NSWindow::frame(*self.window))); - } - } - - let mut win_attribs = self.win_attribs.borrow_mut(); - win_attribs.maximized = maximized; - - let curr_mask = unsafe { self.window.styleMask() }; - if win_attribs.fullscreen.is_some() { - // Handle it in window_did_exit_fullscreen - return; - } else if curr_mask.contains(NSWindowStyleMask::NSResizableWindowMask) { - // Just use the native zoom if resizable - unsafe { - self.window.zoom_(nil); - } - } else { - // if it's not resizable, we set the frame directly - unsafe { - let new_rect = if maximized { - let screen = NSScreen::mainScreen(nil); - NSScreen::visibleFrame(screen) - } else { - self.saved_standard_frame() - }; - - self.window.setFrame_display_(new_rect, 0); - } - } - } -} - -pub struct WindowDelegate { - state: Box, - _this: IdRef, -} - -impl WindowDelegate { - // Emits an event via the `EventsLoop`'s callback or stores it in the pending queue. - pub fn emit_event(state: &mut DelegateState, window_event: WindowEvent) { - let window_id = get_window_id(*state.window); - let event = Event::WindowEvent { - window_id: WindowId(window_id), - event: window_event, - }; - if let Some(shared) = state.shared.upgrade() { - shared.call_user_callback_with_event_or_store_in_pending(event); - } - } - - pub fn emit_resize_event(state: &mut DelegateState) { - let rect = unsafe { NSView::frame(*state.view) }; - let size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64); - WindowDelegate::emit_event(state, WindowEvent::Resized(size)); - } - - pub fn emit_move_event(state: &mut DelegateState) { - let rect = unsafe { NSWindow::frame(*state.window) }; - let x = rect.origin.x as f64; - let y = util::bottom_left_to_top_left(rect); - let moved = state.previous_position != Some((x, y)); - if moved { - state.previous_position = Some((x, y)); - WindowDelegate::emit_event(state, WindowEvent::Moved((x, y).into())); - } - } - - /// Get the delegate class, initiailizing it neccessary - fn class() -> *const Class { - use std::os::raw::c_void; - - extern fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::CloseRequested); - } - NO - } - - extern fn window_will_close(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - - WindowDelegate::emit_event(state, WindowEvent::Destroyed); - - // Remove the window from the shared state. - if let Some(shared) = state.shared.upgrade() { - let window_id = get_window_id(*state.window); - shared.find_and_remove_window(window_id); - } - } - } - - extern fn window_did_resize(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_resize_event(state); - WindowDelegate::emit_move_event(state); - } - } - - // This won't be triggered if the move was part of a resize. - extern fn window_did_move(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_move_event(state); - } - } - - extern fn window_did_change_screen(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - let dpi_factor = NSWindow::backingScaleFactor(*state.window) as f64; - if state.previous_dpi_factor != dpi_factor { - state.previous_dpi_factor = dpi_factor; - WindowDelegate::emit_event(state, WindowEvent::HiDpiFactorChanged(dpi_factor)); - WindowDelegate::emit_resize_event(state); - } - } - } - - // This will always be called before `window_did_change_screen`. - extern fn window_did_change_backing_properties(this: &Object, _:Sel, _:id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - let dpi_factor = NSWindow::backingScaleFactor(*state.window) as f64; - if state.previous_dpi_factor != dpi_factor { - state.previous_dpi_factor = dpi_factor; - WindowDelegate::emit_event(state, WindowEvent::HiDpiFactorChanged(dpi_factor)); - WindowDelegate::emit_resize_event(state); - } - } - } - - extern fn window_did_become_key(this: &Object, _: Sel, _: id) { - unsafe { - // TODO: center the cursor if the window had mouse grab when it - // lost focus - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::Focused(true)); - } - } - - extern fn window_did_resign_key(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::Focused(false)); - } - } - - /// Invoked when the dragged image enters destination bounds or frame - extern fn dragging_entered(this: &Object, _: Sel, sender: id) -> BOOL { - use cocoa::appkit::NSPasteboard; - use cocoa::foundation::NSFastEnumeration; - use std::path::PathBuf; - - let pb: id = unsafe { msg_send![sender, draggingPasteboard] }; - let filenames = unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) }; - - for file in unsafe { filenames.iter() } { - use cocoa::foundation::NSString; - use std::ffi::CStr; - - unsafe { - let f = NSString::UTF8String(file); - let path = CStr::from_ptr(f).to_string_lossy().into_owned(); - - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::HoveredFile(PathBuf::from(path))); - } - }; - - YES - } - - /// Invoked when the image is released - extern fn prepare_for_drag_operation(_: &Object, _: Sel, _: id) -> BOOL { - YES - } - - /// Invoked after the released image has been removed from the screen - extern fn perform_drag_operation(this: &Object, _: Sel, sender: id) -> BOOL { - use cocoa::appkit::NSPasteboard; - use cocoa::foundation::NSFastEnumeration; - use std::path::PathBuf; - - let pb: id = unsafe { msg_send![sender, draggingPasteboard] }; - let filenames = unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) }; - - for file in unsafe { filenames.iter() } { - use cocoa::foundation::NSString; - use std::ffi::CStr; - - unsafe { - let f = NSString::UTF8String(file); - let path = CStr::from_ptr(f).to_string_lossy().into_owned(); - - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::DroppedFile(PathBuf::from(path))); - } - }; - - YES - } - - /// Invoked when the dragging operation is complete - extern fn conclude_drag_operation(_: &Object, _: Sel, _: id) {} - - /// Invoked when the dragging operation is cancelled - extern fn dragging_exited(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - WindowDelegate::emit_event(state, WindowEvent::HoveredFileCancelled); - } - } - - /// Invoked when entered fullscreen - extern fn window_did_enter_fullscreen(this: &Object, _: Sel, _: id){ - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - state.win_attribs.borrow_mut().fullscreen = Some(get_current_monitor(*state.window)); - - state.handle_with_fullscreen = false; - } - } - - /// Invoked when before enter fullscreen - extern fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - let is_zoomed = state.is_zoomed(); - - state.win_attribs.borrow_mut().maximized = is_zoomed; - } - } - - /// Invoked when exited fullscreen - extern fn window_did_exit_fullscreen(this: &Object, _: Sel, _: id){ - let state = unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - &mut *(state as *mut DelegateState) - }; - - state.restore_state_from_fullscreen(); - } - - /// Invoked when fail to enter fullscreen - /// - /// When this window launch from a fullscreen app (e.g. launch from VS Code - /// terminal), it creates a new virtual destkop and a transition animation. - /// This animation takes one second and cannot be disable without - /// elevated privileges. In this animation time, all toggleFullscreen events - /// will be failed. In this implementation, we will try again by using - /// performSelector:withObject:afterDelay: until window_did_enter_fullscreen. - /// It should be fine as we only do this at initialzation (i.e with_fullscreen - /// was set). - /// - /// From Apple doc: - /// In some cases, the transition to enter full-screen mode can fail, - /// due to being in the midst of handling some other animation or user gesture. - /// This method indicates that there was an error, and you should clean up any - /// work you may have done to prepare to enter full-screen mode. - extern fn window_did_fail_to_enter_fullscreen(this: &Object, _: Sel, _: id) { - unsafe { - let state: *mut c_void = *this.get_ivar("winitState"); - let state = &mut *(state as *mut DelegateState); - - if state.handle_with_fullscreen { - let _: () = msg_send![*state.window, - performSelector:sel!(toggleFullScreen:) - withObject:nil - afterDelay: 0.5 - ]; - } else { - state.restore_state_from_fullscreen(); - } - } - } - - static mut DELEGATE_CLASS: *const Class = 0 as *const Class; - static INIT: std::sync::Once = std::sync::ONCE_INIT; - - INIT.call_once(|| unsafe { - // Create new NSWindowDelegate - let superclass = class!(NSObject); - let mut decl = ClassDecl::new("WinitWindowDelegate", superclass).unwrap(); - - // Add callback methods - decl.add_method(sel!(windowShouldClose:), - window_should_close as extern fn(&Object, Sel, id) -> BOOL); - decl.add_method(sel!(windowWillClose:), - window_will_close as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidResize:), - window_did_resize as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidMove:), - window_did_move as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidChangeScreen:), - window_did_change_screen as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidChangeBackingProperties:), - window_did_change_backing_properties as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidBecomeKey:), - window_did_become_key as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidResignKey:), - window_did_resign_key as extern fn(&Object, Sel, id)); - - // callbacks for drag and drop events - decl.add_method(sel!(draggingEntered:), - dragging_entered as extern fn(&Object, Sel, id) -> BOOL); - decl.add_method(sel!(prepareForDragOperation:), - prepare_for_drag_operation as extern fn(&Object, Sel, id) -> BOOL); - decl.add_method(sel!(performDragOperation:), - perform_drag_operation as extern fn(&Object, Sel, id) -> BOOL); - decl.add_method(sel!(concludeDragOperation:), - conclude_drag_operation as extern fn(&Object, Sel, id)); - decl.add_method(sel!(draggingExited:), - dragging_exited as extern fn(&Object, Sel, id)); - - // callbacks for fullscreen events - decl.add_method(sel!(windowDidEnterFullScreen:), - window_did_enter_fullscreen as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowWillEnterFullScreen:), - window_will_enter_fullscreen as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidExitFullScreen:), - window_did_exit_fullscreen as extern fn(&Object, Sel, id)); - decl.add_method(sel!(windowDidFailToEnterFullScreen:), - window_did_fail_to_enter_fullscreen as extern fn(&Object, Sel, id)); - - // Store internal state as user data - decl.add_ivar::<*mut c_void>("winitState"); - - DELEGATE_CLASS = decl.register(); - }); - - unsafe { - DELEGATE_CLASS - } - } - - fn new(state: DelegateState) -> WindowDelegate { - // Box the state so we can give a pointer to it - let mut state = Box::new(state); - let state_ptr: *mut DelegateState = &mut *state; - unsafe { - let delegate = IdRef::new(msg_send![WindowDelegate::class(), new]); - - // setDelegate uses autorelease on objects, - // so need autorelease - let autoreleasepool = NSAutoreleasePool::new(nil); - - (&mut **delegate).set_ivar("winitState", state_ptr as *mut ::std::os::raw::c_void); - let _: () = msg_send![*state.window, setDelegate:*delegate]; - - let _: () = msg_send![autoreleasepool, drain]; - - WindowDelegate { state: state, _this: delegate } - } - } -} - -impl Drop for WindowDelegate { - fn drop(&mut self) { - unsafe { - // Nil the window's delegate so it doesn't still reference us - // NOTE: setDelegate:nil at first retains the previous value, - // and then autoreleases it, so autorelease pool is needed - let autoreleasepool = NSAutoreleasePool::new(nil); - let _: () = msg_send![*self.state.window, setDelegate:nil]; - let _: () = msg_send![autoreleasepool, drain]; - } - } -} - -#[derive(Clone, Default)] -pub struct PlatformSpecificWindowBuilderAttributes { - pub activation_policy: ActivationPolicy, - pub movable_by_window_background: bool, - pub titlebar_transparent: bool, - pub title_hidden: bool, - pub titlebar_hidden: bool, - pub titlebar_buttons_hidden: bool, - pub fullsize_content_view: bool, - pub resize_increments: Option, -} - -pub struct Window2 { - pub view: IdRef, - pub window: IdRef, - pub delegate: WindowDelegate, - pub input_context: IdRef, - cursor: Weak>, - cursor_hidden: AtomicBool, -} - -unsafe impl Send for Window2 {} -unsafe impl Sync for Window2 {} - -unsafe fn get_current_monitor(window: id) -> RootMonitorId { - let screen: id = msg_send![window, screen]; - let desc = NSScreen::deviceDescription(screen); - let key = IdRef::new(NSString::alloc(nil).init_str("NSScreenNumber")); - let value = NSDictionary::valueForKey_(desc, *key); - let display_id = msg_send![value, unsignedIntegerValue]; - RootMonitorId { inner: EventsLoop::make_monitor_from_display(display_id) } -} - -impl Drop for Window2 { - fn drop(&mut self) { - // Remove this window from the `EventLoop`s list of windows. - // The destructor order is: - // Window -> - // Rc (makes Weak<..> in shared.windows None) -> - // Window2 - // needed to remove the element from array - let id = self.id(); - if let Some(shared) = self.delegate.state.shared.upgrade() { - shared.find_and_remove_window(id); - } - - // nswindow::close uses autorelease - // so autorelease pool - let autoreleasepool = unsafe { - NSAutoreleasePool::new(nil) - }; - - // Close the window if it has not yet been closed. - let nswindow = *self.window; - if nswindow != nil { - unsafe { - let () = msg_send![nswindow, close]; - } - } - - let _: () = unsafe { msg_send![autoreleasepool, drain] }; - } -} - -impl WindowExt for Window2 { - #[inline] - fn get_nswindow(&self) -> *mut c_void { - *self.window as *mut c_void - } - - #[inline] - fn get_nsview(&self) -> *mut c_void { - *self.view as *mut c_void - } - - #[inline] - fn request_user_attention(&self, is_critical: bool) { - let request_type = if is_critical { - NSRequestUserAttentionType::NSCriticalRequest - } else { - NSRequestUserAttentionType::NSInformationalRequest - }; - - unsafe { - NSApp().requestUserAttention_(request_type); - } - } - - #[inline] - fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { - let state = &self.delegate.state; - - unsafe { - let app = NSApp(); - let win_attribs = state.win_attribs.borrow_mut(); - let is_native_fullscreen = win_attribs.fullscreen.is_some(); - let is_simple_fullscreen = state.is_simple_fullscreen.get(); - - // Do nothing if native fullscreen is active. - if is_native_fullscreen || (fullscreen && is_simple_fullscreen) || (!fullscreen && !is_simple_fullscreen) { - return false; - } - - if fullscreen { - // Remember the original window's settings - state.standard_frame.set(Some(NSWindow::frame(*self.window))); - state.save_style_mask.set(Some(self.window.styleMask())); - state.save_presentation_opts.set(Some(app.presentationOptions_())); - - // Tell our window's state that we're in fullscreen - state.is_simple_fullscreen.set(true); - - // Simulate pre-Lion fullscreen by hiding the dock and menu bar - let presentation_options = - NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock | - NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar; - app.setPresentationOptions_(presentation_options); - - // Hide the titlebar - util::toggle_style_mask(*self.window, *self.view, NSWindowStyleMask::NSTitledWindowMask, false); - - // Set the window frame to the screen frame size - let screen = self.window.screen(); - let screen_frame = NSScreen::frame(screen); - NSWindow::setFrame_display_(*self.window, screen_frame, YES); - - // Fullscreen windows can't be resized, minimized, or moved - util::toggle_style_mask(*self.window, *self.view, NSWindowStyleMask::NSMiniaturizableWindowMask, false); - util::toggle_style_mask(*self.window, *self.view, NSWindowStyleMask::NSResizableWindowMask, false); - NSWindow::setMovable_(*self.window, NO); - - true - } else { - let saved_style_mask = state.saved_style_mask(win_attribs.resizable); - util::set_style_mask(*self.window, *self.view, saved_style_mask); - state.is_simple_fullscreen.set(false); - - if let Some(presentation_opts) = state.save_presentation_opts.get() { - app.setPresentationOptions_(presentation_opts); - } - - let frame = state.saved_standard_frame(); - NSWindow::setFrame_display_(*self.window, frame, YES); - NSWindow::setMovable_(*self.window, YES); - - true - } - } - } -} - -impl Window2 { - pub fn new( - shared: Weak, - mut win_attribs: WindowAttributes, - pl_attribs: PlatformSpecificWindowBuilderAttributes, - ) -> Result { - unsafe { - if !msg_send![class!(NSThread), isMainThread] { - panic!("Windows can only be created on the main thread on macOS"); - } - } - - // Might as well save some RAM... - win_attribs.window_icon.take(); - - let autoreleasepool = unsafe { - NSAutoreleasePool::new(nil) - }; - - let app = match Window2::create_app(pl_attribs.activation_policy) { - Some(app) => app, - None => { - let _: () = unsafe { msg_send![autoreleasepool, drain] }; - return Err(OsError(format!("Couldn't create NSApplication"))); - }, - }; - - let window = match Window2::create_window(&win_attribs, &pl_attribs) { - Some(res) => res, - None => { - let _: () = unsafe { msg_send![autoreleasepool, drain] }; - return Err(OsError(format!("Couldn't create NSWindow"))); - }, - }; - let (view, cursor) = match Window2::create_view(*window, Weak::clone(&shared)) { - Some(view) => view, - None => { - let _: () = unsafe { msg_send![autoreleasepool, drain] }; - return Err(OsError(format!("Couldn't create NSView"))); - }, - }; - - let input_context = unsafe { util::create_input_context(*view) }; - - unsafe { - if win_attribs.transparent { - (*window as id).setOpaque_(NO); - (*window as id).setBackgroundColor_(NSColor::clearColor(nil)); - } - - app.activateIgnoringOtherApps_(YES); - - if let Some(dimensions) = win_attribs.min_dimensions { - nswindow_set_min_dimensions(window.0, dimensions); - } - if let Some(dimensions) = win_attribs.max_dimensions { - nswindow_set_max_dimensions(window.0, dimensions); - } - - use cocoa::foundation::NSArray; - // register for drag and drop operations. - let () = msg_send![(*window as id), - registerForDraggedTypes:NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType)]; - } - - let dpi_factor = unsafe { NSWindow::backingScaleFactor(*window) as f64 }; - - let mut delegate_state = DelegateState { - view: view.clone(), - window: window.clone(), - shared, - win_attribs: RefCell::new(win_attribs.clone()), - standard_frame: Cell::new(None), - is_simple_fullscreen: Cell::new(false), - save_style_mask: Cell::new(None), - save_presentation_opts: Cell::new(None), - handle_with_fullscreen: win_attribs.fullscreen.is_some(), - previous_position: None, - previous_dpi_factor: dpi_factor, - }; - delegate_state.win_attribs.borrow_mut().fullscreen = None; - - if dpi_factor != 1.0 { - WindowDelegate::emit_event(&mut delegate_state, WindowEvent::HiDpiFactorChanged(dpi_factor)); - WindowDelegate::emit_resize_event(&mut delegate_state); - } - - let window = Window2 { - view: view, - window: window, - delegate: WindowDelegate::new(delegate_state), - input_context, - cursor, - cursor_hidden: Default::default(), - }; - - // Set fullscreen mode after we setup everything - if let Some(ref monitor) = win_attribs.fullscreen { - unsafe { - if monitor.inner != get_current_monitor(*window.window).inner { - unimplemented!(); - } - } - window.set_fullscreen(Some(monitor.clone())); - } - - // Make key have to be after set fullscreen - // to prevent normal size window brefly appears - unsafe { - if win_attribs.visible { - window.window.makeKeyAndOrderFront_(nil); - } else { - window.window.makeKeyWindow(); - } - } - - if win_attribs.maximized { - window.delegate.state.perform_maximized(win_attribs.maximized); - } - - let _: () = unsafe { msg_send![autoreleasepool, drain] }; - - Ok(window) - } - - pub fn id(&self) -> Id { - get_window_id(*self.window) - } - - fn create_app(activation_policy: ActivationPolicy) -> Option { - unsafe { - let app = appkit::NSApp(); - if app == nil { - None - } else { - let ns_activation_policy = match activation_policy { - ActivationPolicy::Regular => - NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular, - ActivationPolicy::Accessory => - NSApplicationActivationPolicy::NSApplicationActivationPolicyAccessory, - ActivationPolicy::Prohibited => - NSApplicationActivationPolicy::NSApplicationActivationPolicyProhibited, - }; - app.setActivationPolicy_(ns_activation_policy); - app.finishLaunching(); - Some(app) - } - } - } - - fn class() -> *const Class { - static mut WINDOW2_CLASS: *const Class = 0 as *const Class; - static INIT: std::sync::Once = std::sync::ONCE_INIT; - - INIT.call_once(|| unsafe { - let window_superclass = class!(NSWindow); - let mut decl = ClassDecl::new("WinitWindow", window_superclass).unwrap(); - decl.add_method(sel!(canBecomeMainWindow), yes as extern fn(&Object, Sel) -> BOOL); - decl.add_method(sel!(canBecomeKeyWindow), yes as extern fn(&Object, Sel) -> BOOL); - WINDOW2_CLASS = decl.register(); - }); - - unsafe { - WINDOW2_CLASS - } - } - - fn create_window( - attrs: &WindowAttributes, - pl_attrs: &PlatformSpecificWindowBuilderAttributes - ) -> Option { - unsafe { - let autoreleasepool = NSAutoreleasePool::new(nil); - let screen = match attrs.fullscreen { - Some(ref monitor_id) => { - let monitor_screen = monitor_id.inner.get_nsscreen(); - Some(monitor_screen.unwrap_or(appkit::NSScreen::mainScreen(nil))) - }, - _ => None, - }; - let frame = match screen { - Some(screen) => appkit::NSScreen::frame(screen), - None => { - let (width, height) = attrs.dimensions - .map(|logical| (logical.width, logical.height)) - .unwrap_or((800.0, 600.0)); - NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(width, height)) - } - }; - - let mut masks = if !attrs.decorations && !screen.is_some() { - // Resizable Window2 without a titlebar or borders - // if decorations is set to false, ignore pl_attrs - NSWindowStyleMask::NSBorderlessWindowMask - | NSWindowStyleMask::NSResizableWindowMask - } else if pl_attrs.titlebar_hidden { - // if the titlebar is hidden, ignore other pl_attrs - NSWindowStyleMask::NSBorderlessWindowMask | - NSWindowStyleMask::NSResizableWindowMask - } else { - // default case, resizable window with titlebar and titlebar buttons - NSWindowStyleMask::NSClosableWindowMask | - NSWindowStyleMask::NSMiniaturizableWindowMask | - NSWindowStyleMask::NSResizableWindowMask | - NSWindowStyleMask::NSTitledWindowMask - }; - - if !attrs.resizable { - masks &= !NSWindowStyleMask::NSResizableWindowMask; - } - - if pl_attrs.fullsize_content_view { - masks |= NSWindowStyleMask::NSFullSizeContentViewWindowMask; - } - - let winit_window = Window2::class(); - - let window: id = msg_send![winit_window, alloc]; - - let window = IdRef::new(window.initWithContentRect_styleMask_backing_defer_( - frame, - masks, - appkit::NSBackingStoreBuffered, - NO, - )); - let res = window.non_nil().map(|window| { - let title = IdRef::new(NSString::alloc(nil).init_str(&attrs.title)); - window.setReleasedWhenClosed_(NO); - window.setTitle_(*title); - window.setAcceptsMouseMovedEvents_(YES); - - if pl_attrs.titlebar_transparent { - window.setTitlebarAppearsTransparent_(YES); - } - if pl_attrs.title_hidden { - window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden); - } - if pl_attrs.titlebar_buttons_hidden { - let button = window.standardWindowButton_(NSWindowButton::NSWindowFullScreenButton); - let () = msg_send![button, setHidden:YES]; - let button = window.standardWindowButton_(NSWindowButton::NSWindowMiniaturizeButton); - let () = msg_send![button, setHidden:YES]; - let button = window.standardWindowButton_(NSWindowButton::NSWindowCloseButton); - let () = msg_send![button, setHidden:YES]; - let button = window.standardWindowButton_(NSWindowButton::NSWindowZoomButton); - let () = msg_send![button, setHidden:YES]; - } - if pl_attrs.movable_by_window_background { - window.setMovableByWindowBackground_(YES); - } - - if attrs.always_on_top { - let _: () = msg_send![*window, setLevel:ffi::NSWindowLevel::NSFloatingWindowLevel]; - } - - if let Some(increments) = pl_attrs.resize_increments { - let (x, y) = (increments.width, increments.height); - if x >= 1.0 && y >= 1.0 { - let size = NSSize::new(x as CGFloat, y as CGFloat); - window.setResizeIncrements_(size); - } - } - - window.center(); - window - }); - let _: () = msg_send![autoreleasepool, drain]; - res - } - } - - fn create_view(window: id, shared: Weak) -> Option<(IdRef, Weak>)> { - unsafe { - let (view, cursor) = new_view(window, shared); - view.non_nil().map(|view| { - view.setWantsBestResolutionOpenGLSurface_(YES); - - // On Mojave, views automatically become layer-backed shortly after being added to - // a window. Changing the layer-backedness of a view breaks the association between - // the view and its associated OpenGL context. To work around this, on Mojave we - // explicitly make the view layer-backed up front so that AppKit doesn't do it - // itself and break the association with its context. - if f64::floor(appkit::NSAppKitVersionNumber) > appkit::NSAppKitVersionNumber10_12 { - view.setWantsLayer(YES); - } - - window.setContentView_(*view); - window.makeFirstResponder_(*view); - (view, cursor) - }) - } - } - - pub fn set_title(&self, title: &str) { - unsafe { - let title = IdRef::new(NSString::alloc(nil).init_str(title)); - self.window.setTitle_(*title); - } - } - - #[inline] - pub fn show(&self) { - unsafe { NSWindow::makeKeyAndOrderFront_(*self.window, nil); } - } - - #[inline] - pub fn hide(&self) { - unsafe { NSWindow::orderOut_(*self.window, nil); } - } - - pub fn get_position(&self) -> Option { - let frame_rect = unsafe { NSWindow::frame(*self.window) }; - Some(( - frame_rect.origin.x as f64, - util::bottom_left_to_top_left(frame_rect), - ).into()) - } - - pub fn get_inner_position(&self) -> Option { - let content_rect = unsafe { - NSWindow::contentRectForFrameRect_( - *self.window, - NSWindow::frame(*self.window), - ) - }; - Some(( - content_rect.origin.x as f64, - util::bottom_left_to_top_left(content_rect), - ).into()) - } - - pub fn set_position(&self, position: LogicalPosition) { - let dummy = NSRect::new( - NSPoint::new( - position.x, - // While it's true that we're setting the top-left position, it still needs to be - // in a bottom-left coordinate system. - CGDisplay::main().pixels_high() as f64 - position.y, - ), - NSSize::new(0f64, 0f64), - ); - unsafe { - NSWindow::setFrameTopLeftPoint_(*self.window, dummy.origin); - } - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - let view_frame = unsafe { NSView::frame(*self.view) }; - Some((view_frame.size.width as f64, view_frame.size.height as f64).into()) - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - let view_frame = unsafe { NSWindow::frame(*self.window) }; - Some((view_frame.size.width as f64, view_frame.size.height as f64).into()) - } - - #[inline] - pub fn set_inner_size(&self, size: LogicalSize) { - unsafe { - NSWindow::setContentSize_(*self.window, NSSize::new(size.width as CGFloat, size.height as CGFloat)); - } - } - - pub fn set_min_dimensions(&self, dimensions: Option) { - unsafe { - let dimensions = dimensions.unwrap_or_else(|| (0, 0).into()); - nswindow_set_min_dimensions(self.window.0, dimensions); - } - } - - pub fn set_max_dimensions(&self, dimensions: Option) { - unsafe { - let dimensions = dimensions.unwrap_or_else(|| (!0, !0).into()); - nswindow_set_max_dimensions(self.window.0, dimensions); - } - } - - #[inline] - pub fn set_resizable(&self, resizable: bool) { - let mut win_attribs = self.delegate.state.win_attribs.borrow_mut(); - win_attribs.resizable = resizable; - if win_attribs.fullscreen.is_none() { - let mut mask = unsafe { self.window.styleMask() }; - if resizable { - mask |= NSWindowStyleMask::NSResizableWindowMask; - } else { - mask &= !NSWindowStyleMask::NSResizableWindowMask; - } - unsafe { util::set_style_mask(*self.window, *self.view, mask) }; - } // Otherwise, we don't change the mask until we exit fullscreen. - } - - pub fn set_cursor(&self, cursor: MouseCursor) { - let cursor = util::Cursor::from(cursor); - if let Some(cursor_access) = self.cursor.upgrade() { - *cursor_access.lock().unwrap() = cursor; - } - unsafe { - let _: () = msg_send![*self.window, - invalidateCursorRectsForView:*self.view - ]; - } - } - - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 - CGDisplay::associate_mouse_and_mouse_cursor_position(!grab) - .map_err(|status| format!("Failed to grab cursor: `CGError` {:?}", status)) - } - - #[inline] - pub fn hide_cursor(&self, hide: bool) { - let cursor_class = class!(NSCursor); - // macOS uses a "hide counter" like Windows does, so we avoid incrementing it more than once. - // (otherwise, `hide_cursor(false)` would need to be called n times!) - if hide != self.cursor_hidden.load(Ordering::Acquire) { - if hide { - let _: () = unsafe { msg_send![cursor_class, hide] }; - } else { - let _: () = unsafe { msg_send![cursor_class, unhide] }; - } - self.cursor_hidden.store(hide, Ordering::Release); - } - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - unsafe { - NSWindow::backingScaleFactor(*self.window) as f64 - } - } - - #[inline] - pub fn set_cursor_position(&self, cursor_position: LogicalPosition) -> Result<(), String> { - let window_position = self.get_inner_position() - .ok_or("`get_inner_position` failed".to_owned())?; - let point = appkit::CGPoint { - x: (cursor_position.x + window_position.x) as CGFloat, - y: (cursor_position.y + window_position.y) as CGFloat, - }; - CGDisplay::warp_mouse_cursor_position(point) - .map_err(|e| format!("`CGWarpMouseCursorPosition` failed: {:?}", e))?; - CGDisplay::associate_mouse_and_mouse_cursor_position(true) - .map_err(|e| format!("`CGAssociateMouseAndMouseCursorPosition` failed: {:?}", e))?; - - Ok(()) - } - - #[inline] - pub fn set_maximized(&self, maximized: bool) { - self.delegate.state.perform_maximized(maximized) - } - - #[inline] - /// TODO: Right now set_fullscreen do not work on switching monitors - /// in fullscreen mode - pub fn set_fullscreen(&self, monitor: Option) { - let state = &self.delegate.state; - - // Do nothing if simple fullscreen is active. - if state.is_simple_fullscreen.get() { - return - } - - let current = { - let win_attribs = state.win_attribs.borrow_mut(); - - let current = win_attribs.fullscreen.clone(); - match (¤t, monitor) { - (&None, None) => { - return; - } - (&Some(ref a), Some(ref b)) if a.inner != b.inner => { - unimplemented!(); - } - (&Some(_), Some(_)) => { - return; - } - _ => (), - } - - current - }; - - unsafe { - // Because toggleFullScreen will not work if the StyleMask is none, - // We set a normal style to it temporary. - // It will clean up at window_did_exit_fullscreen. - if current.is_none() { - let curr_mask = state.window.styleMask(); - let required = NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; - if !curr_mask.contains(required) { - util::set_style_mask(*self.window, *self.view, required); - state.save_style_mask.set(Some(curr_mask)); - } - } - - self.window.toggleFullScreen_(nil); - } - } - - #[inline] - pub fn set_decorations(&self, decorations: bool) { - let state = &self.delegate.state; - let mut win_attribs = state.win_attribs.borrow_mut(); - - if win_attribs.decorations == decorations { - return; - } - - win_attribs.decorations = decorations; - - // Skip modifiy if we are in fullscreen mode, - // window_did_exit_fullscreen will handle it - if win_attribs.fullscreen.is_some() { - return; - } - - unsafe { - let mut new_mask = if decorations { - NSWindowStyleMask::NSClosableWindowMask - | NSWindowStyleMask::NSMiniaturizableWindowMask - | NSWindowStyleMask::NSResizableWindowMask - | NSWindowStyleMask::NSTitledWindowMask - } else { - NSWindowStyleMask::NSBorderlessWindowMask - | NSWindowStyleMask::NSResizableWindowMask - }; - if !win_attribs.resizable { - new_mask &= !NSWindowStyleMask::NSResizableWindowMask; - } - util::set_style_mask(*state.window, *state.view, new_mask); - } - } - - #[inline] - pub fn set_always_on_top(&self, always_on_top: bool) { - unsafe { - let level = if always_on_top { - ffi::NSWindowLevel::NSFloatingWindowLevel - } else { - ffi::NSWindowLevel::NSNormalWindowLevel - }; - let _: () = msg_send![*self.window, setLevel:level]; - } - } - - #[inline] - pub fn set_window_icon(&self, _icon: Option<::Icon>) { - // macOS doesn't have window icons. Though, there is `setRepresentedFilename`, but that's - // semantically distinct and should only be used when the window is in some way - // representing a specific file/directory. For instance, Terminal.app uses this for the - // CWD. Anyway, that should eventually be implemented as - // `WindowBuilderExt::with_represented_file` or something, and doesn't have anything to do - // with `set_window_icon`. - // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Tasks/SettingWindowTitle.html - } - - #[inline] - pub fn set_ime_spot(&self, logical_spot: LogicalPosition) { - set_ime_spot(*self.view, *self.input_context, logical_spot.x, logical_spot.y); - } - - #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - unsafe { - self::get_current_monitor(*self.window) - } - } -} - -// Convert the `cocoa::base::id` associated with a window to a usize to use as a unique identifier -// for the window. -pub fn get_window_id(window_cocoa_id: id) -> Id { - Id(window_cocoa_id as *const objc::runtime::Object as usize) -} - -unsafe fn nswindow_set_min_dimensions(window: V, mut min_size: LogicalSize) { - let mut current_rect = NSWindow::frame(window); - let content_rect = NSWindow::contentRectForFrameRect_(window, NSWindow::frame(window)); - // Convert from client area size to window size - min_size.width += (current_rect.size.width - content_rect.size.width) as f64; // this tends to be 0 - min_size.height += (current_rect.size.height - content_rect.size.height) as f64; - window.setMinSize_(NSSize { - width: min_size.width as CGFloat, - height: min_size.height as CGFloat, - }); - // If necessary, resize the window to match constraint - if current_rect.size.width < min_size.width { - current_rect.size.width = min_size.width; - window.setFrame_display_(current_rect, 0) - } - if current_rect.size.height < min_size.height { - // The origin point of a rectangle is at its bottom left in Cocoa. - // To ensure the window's top-left point remains the same: - current_rect.origin.y += current_rect.size.height - min_size.height; - current_rect.size.height = min_size.height; - window.setFrame_display_(current_rect, 0) - } -} - -unsafe fn nswindow_set_max_dimensions(window: V, mut max_size: LogicalSize) { - let mut current_rect = NSWindow::frame(window); - let content_rect = NSWindow::contentRectForFrameRect_(window, NSWindow::frame(window)); - // Convert from client area size to window size - max_size.width += (current_rect.size.width - content_rect.size.width) as f64; // this tends to be 0 - max_size.height += (current_rect.size.height - content_rect.size.height) as f64; - window.setMaxSize_(NSSize { - width: max_size.width as CGFloat, - height: max_size.height as CGFloat, - }); - // If necessary, resize the window to match constraint - if current_rect.size.width > max_size.width { - current_rect.size.width = max_size.width; - window.setFrame_display_(current_rect, 0) - } - if current_rect.size.height > max_size.height { - // The origin point of a rectangle is at its bottom left in Cocoa. - // To ensure the window's top-left point remains the same: - current_rect.origin.y += current_rect.size.height - max_size.height; - current_rect.size.height = max_size.height; - window.setFrame_display_(current_rect, 0) - } -} - -pub struct IdRef(id); - -impl IdRef { - pub fn new(i: id) -> IdRef { - IdRef(i) - } - - #[allow(dead_code)] - pub fn retain(i: id) -> IdRef { - if i != nil { - let _: id = unsafe { msg_send![i, retain] }; - } - IdRef(i) - } - - pub fn non_nil(self) -> Option { - if self.0 == nil { None } else { Some(self) } - } -} - -impl Drop for IdRef { - fn drop(&mut self) { - if self.0 != nil { - unsafe { - let autoreleasepool = NSAutoreleasePool::new(nil); - let _ : () = msg_send![self.0, release]; - let _ : () = msg_send![autoreleasepool, release]; - }; - } - } -} - -impl Deref for IdRef { - type Target = id; - fn deref<'a>(&'a self) -> &'a id { - &self.0 - } -} - -impl Clone for IdRef { - fn clone(&self) -> IdRef { - if self.0 != nil { - let _: id = unsafe { msg_send![self.0, retain] }; - } - IdRef(self.0) - } -} - -extern fn yes(_: &Object, _: Sel) -> BOOL { - YES -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/mod.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/mod.rs deleted file mode 100644 index be96878..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/mod.rs +++ /dev/null @@ -1,26 +0,0 @@ -pub use self::platform::*; - -#[cfg(target_os = "windows")] -#[path="windows/mod.rs"] -mod platform; -#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -#[path="linux/mod.rs"] -mod platform; -#[cfg(target_os = "macos")] -#[path="macos/mod.rs"] -mod platform; -#[cfg(target_os = "android")] -#[path="android/mod.rs"] -mod platform; -#[cfg(target_os = "ios")] -#[path="ios/mod.rs"] -mod platform; -#[cfg(target_os = "emscripten")] -#[path="emscripten/mod.rs"] -mod platform; - -#[cfg(all(not(target_os = "ios"), not(target_os = "windows"), not(target_os = "linux"), - not(target_os = "macos"), not(target_os = "android"), not(target_os = "dragonfly"), - not(target_os = "freebsd"), not(target_os = "netbsd"), not(target_os = "openbsd"), - not(target_os = "emscripten")))] -compile_error!("The platform you're compiling for is not supported by winit"); diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/dpi.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/dpi.rs deleted file mode 100644 index ea4bc65..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/dpi.rs +++ /dev/null @@ -1,189 +0,0 @@ -#![allow(non_snake_case, unused_unsafe)] - -use std::mem; -use std::os::raw::c_void; -use std::sync::{Once, ONCE_INIT}; - -use winapi::shared::minwindef::{BOOL, UINT, FALSE}; -use winapi::shared::windef::{ - DPI_AWARENESS_CONTEXT, - DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, - HMONITOR, - HWND, -}; -use winapi::shared::winerror::S_OK; -use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryA}; -use winapi::um::shellscalingapi::{ - MDT_EFFECTIVE_DPI, - MONITOR_DPI_TYPE, - PROCESS_DPI_AWARENESS, - PROCESS_PER_MONITOR_DPI_AWARE, -}; -use winapi::um::wingdi::{GetDeviceCaps, LOGPIXELSX}; -use winapi::um::winnt::{HRESULT, LPCSTR}; -use winapi::um::winuser::{self, MONITOR_DEFAULTTONEAREST}; - -const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = -4isize as _; - -type SetProcessDPIAware = unsafe extern "system" fn () -> BOOL; -type SetProcessDpiAwareness = unsafe extern "system" fn ( - value: PROCESS_DPI_AWARENESS, -) -> HRESULT; -type SetProcessDpiAwarenessContext = unsafe extern "system" fn ( - value: DPI_AWARENESS_CONTEXT, -) -> BOOL; -type GetDpiForWindow = unsafe extern "system" fn (hwnd: HWND) -> UINT; -type GetDpiForMonitor = unsafe extern "system" fn ( - hmonitor: HMONITOR, - dpi_type: MONITOR_DPI_TYPE, - dpi_x: *mut UINT, - dpi_y: *mut UINT, -) -> HRESULT; -type EnableNonClientDpiScaling = unsafe extern "system" fn (hwnd: HWND) -> BOOL; - -// Helper function to dynamically load function pointer. -// `library` and `function` must be zero-terminated. -fn get_function_impl(library: &str, function: &str) -> Option<*const c_void> { - assert_eq!(library.chars().last(), Some('\0')); - assert_eq!(function.chars().last(), Some('\0')); - - // Library names we will use are ASCII so we can use the A version to avoid string conversion. - let module = unsafe { LoadLibraryA(library.as_ptr() as LPCSTR) }; - if module.is_null() { - return None; - } - - let function_ptr = unsafe { GetProcAddress(module, function.as_ptr() as LPCSTR) }; - if function_ptr.is_null() { - return None; - } - - Some(function_ptr as _) -} - -macro_rules! get_function { - ($lib:expr, $func:ident) => { - get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')) - .map(|f| unsafe { mem::transmute::<*const _, $func>(f) }) - } -} - -lazy_static! { - static ref GET_DPI_FOR_WINDOW: Option = get_function!( - "user32.dll", - GetDpiForWindow - ); - static ref GET_DPI_FOR_MONITOR: Option = get_function!( - "shcore.dll", - GetDpiForMonitor - ); - static ref ENABLE_NON_CLIENT_DPI_SCALING: Option = get_function!( - "user32.dll", - EnableNonClientDpiScaling - ); -} - -pub fn become_dpi_aware(enable: bool) { - if !enable { return; } - static ENABLE_DPI_AWARENESS: Once = ONCE_INIT; - ENABLE_DPI_AWARENESS.call_once(|| { unsafe { - if let Some(SetProcessDpiAwarenessContext) = get_function!( - "user32.dll", - SetProcessDpiAwarenessContext - ) { - // We are on Windows 10 Anniversary Update (1607) or later. - if SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) - == FALSE { - // V2 only works with Windows 10 Creators Update (1703). Try using the older - // V1 if we can't set V2. - SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); - } - } else if let Some(SetProcessDpiAwareness) = get_function!( - "shcore.dll", - SetProcessDpiAwareness - ) { - // We are on Windows 8.1 or later. - SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); - } else if let Some(SetProcessDPIAware) = get_function!( - "user32.dll", - SetProcessDPIAware - ) { - // We are on Vista or later. - SetProcessDPIAware(); - } - } }); -} - -pub fn enable_non_client_dpi_scaling(hwnd: HWND) { - unsafe { - if let Some(EnableNonClientDpiScaling) = *ENABLE_NON_CLIENT_DPI_SCALING { - EnableNonClientDpiScaling(hwnd); - } - } -} - -pub fn get_monitor_dpi(hmonitor: HMONITOR) -> Option { - unsafe { - if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { - // We are on Windows 8.1 or later. - let mut dpi_x = 0; - let mut dpi_y = 0; - if GetDpiForMonitor(hmonitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { - // MSDN says that "the values of *dpiX and *dpiY are identical. You only need to - // record one of the values to determine the DPI and respond appropriately". - // https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx - return Some(dpi_x as u32) - } - } - } - None -} - -pub const BASE_DPI: u32 = 96; -pub fn dpi_to_scale_factor(dpi: u32) -> f64 { - dpi as f64 / BASE_DPI as f64 -} - -pub unsafe fn get_hwnd_dpi(hwnd: HWND) -> u32 { - let hdc = winuser::GetDC(hwnd); - if hdc.is_null() { - panic!("[winit] `GetDC` returned null!"); - } - if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { - // We are on Windows 10 Anniversary Update (1607) or later. - match GetDpiForWindow(hwnd) { - 0 => BASE_DPI, // 0 is returned if hwnd is invalid - dpi => dpi as u32, - } - } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { - // We are on Windows 8.1 or later. - let monitor = winuser::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - if monitor.is_null() { - return BASE_DPI; - } - - let mut dpi_x = 0; - let mut dpi_y = 0; - if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { - dpi_x as u32 - } else { - BASE_DPI - } - } else { - // We are on Vista or later. - if winuser::IsProcessDPIAware() != FALSE { - // If the process is DPI aware, then scaling must be handled by the application using - // this DPI value. - GetDeviceCaps(hdc, LOGPIXELSX) as u32 - } else { - // If the process is DPI unaware, then scaling is performed by the OS; we thus return - // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the - // application and the WM. - BASE_DPI - } - } -} - -pub fn get_hwnd_scale_factor(hwnd: HWND) -> f64 { - dpi_to_scale_factor(unsafe { get_hwnd_dpi(hwnd) }) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/events_loop.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/events_loop.rs deleted file mode 100644 index de4a432..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/events_loop.rs +++ /dev/null @@ -1,1299 +0,0 @@ -//! An events loop on Win32 is a background thread. -//! -//! Creating an events loop spawns a thread and blocks it in a permanent Win32 events loop. -//! Destroying the events loop stops the thread. -//! -//! You can use the `execute_in_thread` method to execute some code in the background thread. -//! Since Win32 requires you to create a window in the right thread, you must use this method -//! to create a window. -//! -//! If you create a window whose class is set to `callback`, the window's events will be -//! propagated with `run_forever` and `poll_events`. -//! The closure passed to the `execute_in_thread` method takes an `Inserter` that you can use to -//! add a `WindowState` entry to a list of window to be used by the callback. - -use std::{mem, panic, ptr, thread}; -use std::any::Any; -use std::cell::RefCell; -use std::collections::HashMap; -use std::os::windows::io::AsRawHandle; -use std::sync::{Arc, mpsc, Mutex}; - -use backtrace::Backtrace; -use winapi::ctypes::c_int; -use winapi::shared::minwindef::{ - BOOL, - DWORD, - HIWORD, - INT, - LOWORD, - LPARAM, - LRESULT, - UINT, - WPARAM, -}; -use winapi::shared::windef::{HWND, POINT, RECT}; -use winapi::shared::windowsx; -use winapi::shared::winerror::S_OK; -use winapi::um::{libloaderapi, processthreadsapi, ole2, winuser}; -use winapi::um::oleidl::LPDROPTARGET; -use winapi::um::winnt::{LONG, LPCSTR, SHORT}; - -use { - ControlFlow, - Event, - EventsLoopClosed, - KeyboardInput, - LogicalPosition, - LogicalSize, - PhysicalSize, - WindowEvent, - WindowId as SuperWindowId, -}; -use events::{DeviceEvent, Touch, TouchPhase}; -use platform::platform::{event, Cursor, WindowId, DEVICE_ID, wrap_device_id, util}; -use platform::platform::dpi::{ - become_dpi_aware, - dpi_to_scale_factor, - enable_non_client_dpi_scaling, - get_hwnd_scale_factor, -}; -use platform::platform::drop_handler::FileDropHandler; -use platform::platform::event::{handle_extended_keys, process_key_params, vkey_to_winit_vkey}; -use platform::platform::icon::WinIcon; -use platform::platform::raw_input::{get_raw_input_data, get_raw_mouse_button_state}; -use platform::platform::window::adjust_size; - -/// Contains saved window info for switching between fullscreen -#[derive(Clone)] -pub struct SavedWindowInfo { - /// Window style - pub style: LONG, - /// Window ex-style - pub ex_style: LONG, - /// Window position and size - pub client_rect: RECT, - // Since a window can be fullscreened to a different monitor, a DPI change can be triggered. This could result in - // the window being automitcally resized to smaller/larger than it was supposed to be restored to, so we thus must - // check if the post-fullscreen DPI matches the pre-fullscreen DPI. - pub is_fullscreen: bool, - pub dpi_factor: Option, -} - -/// Contains information about states and the window that the callback is going to use. -#[derive(Clone)] -pub struct WindowState { - /// Cursor to set at the next `WM_SETCURSOR` event received. - pub cursor: Cursor, - pub cursor_grabbed: bool, - pub cursor_hidden: bool, - /// Used by `WM_GETMINMAXINFO`. - pub max_size: Option, - pub min_size: Option, - /// Will contain `true` if the mouse is hovering the window. - pub mouse_in_window: bool, - /// Saved window info for fullscreen restored - pub saved_window_info: Option, - // This is different from the value in `SavedWindowInfo`! That one represents the DPI saved upon entering - // fullscreen. This will always be the most recent DPI for the window. - pub dpi_factor: f64, - pub fullscreen: Option<::MonitorId>, - pub window_icon: Option, - pub taskbar_icon: Option, - pub decorations: bool, - pub always_on_top: bool, - pub maximized: bool, - pub resizable: bool, -} - -impl WindowState { - pub fn update_min_max(&mut self, old_dpi_factor: f64, new_dpi_factor: f64) { - let scale_factor = new_dpi_factor / old_dpi_factor; - let dpi_adjuster = |mut physical_size: PhysicalSize| -> PhysicalSize { - physical_size.width *= scale_factor; - physical_size.height *= scale_factor; - physical_size - }; - self.max_size = self.max_size.map(&dpi_adjuster); - self.min_size = self.min_size.map(&dpi_adjuster); - } -} - -/// Dummy object that allows inserting a window's state. -// We store a pointer in order to !impl Send and Sync. -pub struct Inserter(*mut u8); - -impl Inserter { - /// Inserts a window's state for the callback to use. The state is removed automatically if the - /// callback receives a `WM_CLOSE` message for the window. - pub fn insert(&self, window: HWND, state: Arc>) { - CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - let was_in = context_stash.as_mut().unwrap().windows.insert(window, state); - assert!(was_in.is_none()); - }); - } -} - -pub struct EventsLoop { - thread_msg_target: HWND, - // Id of the background thread from the Win32 API. - thread_id: DWORD, - // Receiver for the events. The sender is in the background thread. - receiver: mpsc::Receiver, - // Sender instance that's paired with the receiver. Used to construct an `EventsLoopProxy`. - sender: mpsc::Sender, -} - -enum EventsLoopEvent { - WinitEvent(Event), - Panic(PanicError), -} - -impl EventsLoop { - pub fn new() -> EventsLoop { - Self::with_dpi_awareness(true) - } - - pub fn with_dpi_awareness(dpi_aware: bool) -> EventsLoop { - struct InitData { - thread_msg_target: HWND, - } - unsafe impl Send for InitData {} - - become_dpi_aware(dpi_aware); - - // The main events transfer channel. - let (tx, rx) = mpsc::channel(); - - // Channel to send initialization data created on the event loop thread back to the main - // thread. - let (init_tx, init_rx) = mpsc::sync_channel(0); - - let thread_sender = tx.clone(); - let panic_sender = tx.clone(); - let thread = thread::spawn(move || { - let tx = thread_sender; - let thread_msg_target = thread_event_target_window(); - - CONTEXT_STASH.with(|context_stash| { - *context_stash.borrow_mut() = Some(ThreadLocalData { - sender: tx, - windows: HashMap::with_capacity(4), - file_drop_handlers: HashMap::with_capacity(4), - mouse_buttons_down: 0, - panic_error: None, - }); - }); - - unsafe { - // Calling `PostThreadMessageA` on a thread that does not have an events queue yet - // will fail. In order to avoid this situation, we call `IsGuiThread` to initialize - // it. - winuser::IsGUIThread(1); - // Then only we unblock the `new()` function. We are sure that we don't call - // `PostThreadMessageA()` before `new()` returns. - init_tx.send(InitData{ thread_msg_target }).ok(); - drop(init_tx); - - let mut msg = mem::uninitialized(); - - loop { - if winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 { - // If a panic occurred in the child callback, forward the panic information - // to the parent thread. - let panic_payload_opt = CONTEXT_STASH.with(|stash| - stash.borrow_mut().as_mut() - .and_then(|s| s.panic_error.take()) - ); - if let Some(panic_payload) = panic_payload_opt { - panic_sender.send(EventsLoopEvent::Panic(panic_payload)).unwrap(); - }; - - // Only happens if the message is `WM_QUIT`. - debug_assert_eq!(msg.message, winuser::WM_QUIT); - break; - } - - // Calls `callback` below. - winuser::TranslateMessage(&msg); - winuser::DispatchMessageW(&msg); - } - } - }); - - // Blocks this function until the background thread has an events loop. See other comments. - let InitData { thread_msg_target } = init_rx.recv().unwrap(); - - let thread_id = unsafe { - let handle = mem::transmute(thread.as_raw_handle()); - processthreadsapi::GetThreadId(handle) - }; - - EventsLoop { - thread_msg_target, - thread_id, - receiver: rx, - sender: tx, - } - } - - pub fn poll_events(&mut self, mut callback: F) - where F: FnMut(Event) - { - loop { - let event = match self.receiver.try_recv() { - Ok(EventsLoopEvent::WinitEvent(e)) => e, - Ok(EventsLoopEvent::Panic(panic)) => { - eprintln!("resuming child thread unwind at: {:?}", Backtrace::new()); - panic::resume_unwind(panic) - }, - Err(_) => break, - }; - - callback(event); - } - } - - pub fn run_forever(&mut self, mut callback: F) - where F: FnMut(Event) -> ControlFlow - { - loop { - let event = match self.receiver.recv() { - Ok(EventsLoopEvent::WinitEvent(e)) => e, - Ok(EventsLoopEvent::Panic(panic)) => { - eprintln!("resuming child thread unwind at: {:?}", Backtrace::new()); - panic::resume_unwind(panic) - }, - Err(_) => break, - }; - - let flow = callback(event); - match flow { - ControlFlow::Continue => continue, - ControlFlow::Break => break, - } - } - } - - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy { - thread_msg_target: self.thread_msg_target, - sender: self.sender.clone(), - } - } - - /// Executes a function in the background thread. - /// - /// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent - /// to the unstable FnBox. - /// - /// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is - /// removed automatically if the callback receives a `WM_CLOSE` message for the window. - pub(super) fn execute_in_thread(&self, function: F) - where F: FnMut(Inserter) + Send + 'static - { - self.create_proxy().execute_in_thread(function) - } -} - -impl Drop for EventsLoop { - fn drop(&mut self) { - unsafe { - // Posting `WM_QUIT` will cause `GetMessage` to stop. - winuser::PostThreadMessageA(self.thread_id, winuser::WM_QUIT, 0, 0); - } - } -} - -#[derive(Clone)] -pub struct EventsLoopProxy { - thread_msg_target: HWND, - sender: mpsc::Sender, -} - -unsafe impl Send for EventsLoopProxy {} -unsafe impl Sync for EventsLoopProxy {} - -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - self.sender.send(EventsLoopEvent::WinitEvent(Event::Awakened)).map_err(|_| EventsLoopClosed) - } - - /// Executes a function in the background thread. - /// - /// Note that we use FnMut instead of FnOnce because boxing FnOnce won't work on stable Rust - /// until 2030 when the design of Box is finally complete. - /// https://github.com/rust-lang/rust/issues/28796 - /// - /// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is - /// removed automatically if the callback receives a `WM_CLOSE` message for the window. - /// - /// Note that if you are using this to change some property of a window and updating - /// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the - /// events may be sent to the other thread in different order to the one in which you set - /// `WindowState`, leaving them out of sync. - pub fn execute_in_thread(&self, function: F) - where - F: FnMut(Inserter) + Send + 'static, - { - // We are using double-boxing here because it make casting back much easier - let double_box = Box::new(Box::new(function) as Box); - let raw = Box::into_raw(double_box); - - let res = unsafe { - winuser::PostMessageW( - self.thread_msg_target, - *EXEC_MSG_ID, - raw as *mut () as usize as WPARAM, - 0, - ) - }; - assert!(res != 0, "PostMessage failed; is the messages queue full?"); - } -} - -lazy_static! { - // Message sent when we want to execute a closure in the thread. - // WPARAM contains a Box> that must be retrieved with `Box::from_raw`, - // and LPARAM is unused. - static ref EXEC_MSG_ID: u32 = { - unsafe { - winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as LPCSTR) - } - }; - // Message sent by a `Window` when it wants to be destroyed by the main thread. - // WPARAM and LPARAM are unused. - pub static ref DESTROY_MSG_ID: u32 = { - unsafe { - winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as LPCSTR) - } - }; - // Message sent by a `Window` after creation if it has a DPI != 96. - // WPARAM is the the DPI (u32). LOWORD of LPARAM is width, and HIWORD is height. - pub static ref INITIAL_DPI_MSG_ID: u32 = { - unsafe { - winuser::RegisterWindowMessageA("Winit::InitialDpiMsg\0".as_ptr() as LPCSTR) - } - }; - static ref THREAD_EVENT_TARGET_WINDOW_CLASS: Vec = unsafe { - use std::ffi::OsStr; - use std::os::windows::ffi::OsStrExt; - - let class_name: Vec<_> = OsStr::new("Winit Thread Event Target") - .encode_wide() - .chain(Some(0).into_iter()) - .collect(); - - let class = winuser::WNDCLASSEXW { - cbSize: mem::size_of::() as UINT, - style: 0, - lpfnWndProc: Some(thread_event_target_callback), - cbClsExtra: 0, - cbWndExtra: 0, - hInstance: libloaderapi::GetModuleHandleW(ptr::null()), - hIcon: ptr::null_mut(), - hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly - hbrBackground: ptr::null_mut(), - lpszMenuName: ptr::null(), - lpszClassName: class_name.as_ptr(), - hIconSm: ptr::null_mut(), - }; - - winuser::RegisterClassExW(&class); - - class_name - }; -} - -fn thread_event_target_window() -> HWND { - unsafe { - let window = winuser::CreateWindowExW( - winuser::WS_EX_NOACTIVATE | winuser::WS_EX_TRANSPARENT | winuser::WS_EX_LAYERED, - THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), - ptr::null_mut(), - 0, - 0, 0, - 0, 0, - ptr::null_mut(), - ptr::null_mut(), - libloaderapi::GetModuleHandleW(ptr::null()), - ptr::null_mut(), - ); - winuser::SetWindowLongPtrW( - window, - winuser::GWL_STYLE, - (winuser::WS_VISIBLE | winuser::WS_POPUP) as _ - ); - - window - } -} - -// There's no parameters passed to the callback function, so it needs to get its context stashed -// in a thread-local variable. -thread_local!(static CONTEXT_STASH: RefCell> = RefCell::new(None)); -struct ThreadLocalData { - sender: mpsc::Sender, - windows: HashMap>>, - file_drop_handlers: HashMap, // Each window has its own drop handler. - mouse_buttons_down: u32, - panic_error: Option, -} -type PanicError = Box; - -// Utility function that dispatches an event on the current thread. -pub fn send_event(event: Event) { - CONTEXT_STASH.with(|context_stash| { - let context_stash = context_stash.borrow(); - - let _ = context_stash.as_ref().unwrap().sender.send(EventsLoopEvent::WinitEvent(event)); // Ignoring if closed - }); -} - -/// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of -/// the window. -unsafe fn capture_mouse(window: HWND) { - let set_capture = CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - if let Some(context_stash) = context_stash.as_mut() { - context_stash.mouse_buttons_down += 1; - true - } else { - false - } - }); - if set_capture { - winuser::SetCapture(window); - } -} - -/// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor -/// is outside the window. -unsafe fn release_mouse() { - let release_capture = CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - if let Some(context_stash) = context_stash.as_mut() { - context_stash.mouse_buttons_down = context_stash.mouse_buttons_down.saturating_sub(1); - if context_stash.mouse_buttons_down == 0 { - return true; - } - } - false - }); - if release_capture { - winuser::ReleaseCapture(); - } -} - -pub unsafe fn run_catch_panic(error: R, f: F) -> R - where F: panic::UnwindSafe + FnOnce() -> R -{ - // If a panic has been triggered, cancel all future operations in the function. - if CONTEXT_STASH.with(|stash| stash.borrow().as_ref().map(|s| s.panic_error.is_some()).unwrap_or(false)) { - return error; - } - - let callback_result = panic::catch_unwind(f); - match callback_result { - Ok(lresult) => lresult, - Err(err) => CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - if let Some(context_stash) = context_stash.as_mut() { - context_stash.panic_error = Some(err); - winuser::PostQuitMessage(-1); - } - error - }) - } -} - -/// Any window whose callback is configured to this function will have its events propagated -/// through the events loop of the thread the window was created in. -// -// This is the callback that is called by `DispatchMessage` in the events loop. -// -// Returning 0 tells the Win32 API that the message has been processed. -// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary -pub unsafe extern "system" fn callback( - window: HWND, - msg: UINT, - wparam: WPARAM, - lparam: LPARAM, -) -> LRESULT { - // Unwinding into foreign code is undefined behavior. So we catch any panics that occur in our - // code, and if a panic happens we cancel any future operations. - run_catch_panic(-1, || callback_inner(window, msg, wparam, lparam)) -} - -unsafe fn callback_inner( - window: HWND, - msg: UINT, - wparam: WPARAM, - lparam: LPARAM, -) -> LRESULT { - match msg { - winuser::WM_CREATE => { - use winapi::shared::winerror::{OLE_E_WRONGCOMPOBJ, RPC_E_CHANGED_MODE}; - let ole_init_result = ole2::OleInitialize(ptr::null_mut()); - // It is ok if the initialize result is `S_FALSE` because it might happen that - // multiple windows are created on the same thread. - if ole_init_result == OLE_E_WRONGCOMPOBJ { - panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`"); - } else if ole_init_result == RPC_E_CHANGED_MODE { - panic!("OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`"); - } - - CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - - let drop_handlers = &mut context_stash.as_mut().unwrap().file_drop_handlers; - let new_handler = FileDropHandler::new(window); - let handler_interface_ptr = &mut (*new_handler.data).interface as LPDROPTARGET; - drop_handlers.insert(window, new_handler); - - assert_eq!(ole2::RegisterDragDrop(window, handler_interface_ptr), S_OK); - }); - 0 - }, - - winuser::WM_NCCREATE => { - enable_non_client_dpi_scaling(window); - winuser::DefWindowProcW(window, msg, wparam, lparam) - }, - - winuser::WM_CLOSE => { - use events::WindowEvent::CloseRequested; - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: CloseRequested - }); - 0 - }, - - winuser::WM_DESTROY => { - use events::WindowEvent::Destroyed; - CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - ole2::RevokeDragDrop(window); - let context_stash_mut = context_stash.as_mut().unwrap(); - context_stash_mut.file_drop_handlers.remove(&window); - context_stash_mut.windows.remove(&window); - }); - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Destroyed - }); - 0 - }, - - winuser::WM_PAINT => { - use events::WindowEvent::Refresh; - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Refresh, - }); - winuser::DefWindowProcW(window, msg, wparam, lparam) - }, - - // WM_MOVE supplies client area positions, so we send Moved here instead. - winuser::WM_WINDOWPOSCHANGED => { - use events::WindowEvent::Moved; - - let windowpos = lparam as *const winuser::WINDOWPOS; - if (*windowpos).flags & winuser::SWP_NOMOVE != winuser::SWP_NOMOVE { - let dpi_factor = get_hwnd_scale_factor(window); - let logical_position = LogicalPosition::from_physical( - ((*windowpos).x, (*windowpos).y), - dpi_factor, - ); - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Moved(logical_position), - }); - } - - // This is necessary for us to still get sent WM_SIZE. - winuser::DefWindowProcW(window, msg, wparam, lparam) - }, - - winuser::WM_SIZE => { - use events::WindowEvent::Resized; - let w = LOWORD(lparam as DWORD) as u32; - let h = HIWORD(lparam as DWORD) as u32; - - // Wait for the parent thread to process the resize event before returning from the - // callback. - CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - let cstash = context_stash.as_mut().unwrap(); - - let dpi_factor = get_hwnd_scale_factor(window); - let logical_size = LogicalSize::from_physical((w, h), dpi_factor); - let event = Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Resized(logical_size), - }; - - cstash.sender.send(EventsLoopEvent::WinitEvent(event)).ok(); - }); - 0 - }, - - winuser::WM_CHAR => { - use std::mem; - use events::WindowEvent::ReceivedCharacter; - let chr: char = mem::transmute(wparam as u32); - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: ReceivedCharacter(chr), - }); - 0 - }, - - // Prevents default windows menu hotkeys playing unwanted - // "ding" sounds. Alternatively could check for WM_SYSCOMMAND - // with wparam being SC_KEYMENU, but this may prevent some - // other unwanted default hotkeys as well. - winuser::WM_SYSCHAR => { - 0 - } - - winuser::WM_MOUSEMOVE => { - use events::WindowEvent::{CursorEntered, CursorMoved}; - let mouse_outside_window = CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - if let Some(context_stash) = context_stash.as_mut() { - if let Some(w) = context_stash.windows.get_mut(&window) { - let mut w = w.lock().unwrap(); - if !w.mouse_in_window { - w.mouse_in_window = true; - return true; - } - } - } - - false - }); - - if mouse_outside_window { - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: CursorEntered { device_id: DEVICE_ID }, - }); - - // Calling TrackMouseEvent in order to receive mouse leave events. - winuser::TrackMouseEvent(&mut winuser::TRACKMOUSEEVENT { - cbSize: mem::size_of::() as DWORD, - dwFlags: winuser::TME_LEAVE, - hwndTrack: window, - dwHoverTime: winuser::HOVER_DEFAULT, - }); - } - - let x = windowsx::GET_X_LPARAM(lparam) as f64; - let y = windowsx::GET_Y_LPARAM(lparam) as f64; - let dpi_factor = get_hwnd_scale_factor(window); - let position = LogicalPosition::from_physical((x, y), dpi_factor); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: CursorMoved { device_id: DEVICE_ID, position, modifiers: event::get_key_mods() }, - }); - - 0 - }, - - winuser::WM_MOUSELEAVE => { - use events::WindowEvent::CursorLeft; - let mouse_in_window = CONTEXT_STASH.with(|context_stash| { - let mut context_stash = context_stash.borrow_mut(); - if let Some(context_stash) = context_stash.as_mut() { - if let Some(w) = context_stash.windows.get_mut(&window) { - let mut w = w.lock().unwrap(); - if w.mouse_in_window { - w.mouse_in_window = false; - return true; - } - } - } - - false - }); - - if mouse_in_window { - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: CursorLeft { device_id: DEVICE_ID } - }); - } - - 0 - }, - - winuser::WM_MOUSEWHEEL => { - use events::MouseScrollDelta::LineDelta; - use events::TouchPhase; - - let value = (wparam >> 16) as i16; - let value = value as i32; - let value = value as f32 / winuser::WHEEL_DELTA as f32; - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: WindowEvent::MouseWheel { device_id: DEVICE_ID, delta: LineDelta(0.0, value), phase: TouchPhase::Moved, modifiers: event::get_key_mods() }, - }); - - 0 - }, - - winuser::WM_KEYDOWN | winuser::WM_SYSKEYDOWN => { - use events::ElementState::Pressed; - use events::VirtualKeyCode; - if msg == winuser::WM_SYSKEYDOWN && wparam as i32 == winuser::VK_F4 { - winuser::DefWindowProcW(window, msg, wparam, lparam) - } else { - if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: WindowEvent::KeyboardInput { - device_id: DEVICE_ID, - input: KeyboardInput { - state: Pressed, - scancode: scancode, - virtual_keycode: vkey, - modifiers: event::get_key_mods(), - } - } - }); - // Windows doesn't emit a delete character by default, but in order to make it - // consistent with the other platforms we'll emit a delete character here. - if vkey == Some(VirtualKeyCode::Delete) { - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: WindowEvent::ReceivedCharacter('\u{7F}'), - }); - } - } - 0 - } - }, - - winuser::WM_KEYUP | winuser::WM_SYSKEYUP => { - use events::ElementState::Released; - if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: WindowEvent::KeyboardInput { - device_id: DEVICE_ID, - input: KeyboardInput { - state: Released, - scancode: scancode, - virtual_keycode: vkey, - modifiers: event::get_key_mods(), - }, - } - }); - } - 0 - }, - - winuser::WM_LBUTTONDOWN => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Left; - use events::ElementState::Pressed; - - capture_mouse(window); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Left, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_LBUTTONUP => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Left; - use events::ElementState::Released; - - release_mouse(); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Released, button: Left, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_RBUTTONDOWN => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Right; - use events::ElementState::Pressed; - - capture_mouse(window); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Right, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_RBUTTONUP => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Right; - use events::ElementState::Released; - - release_mouse(); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Released, button: Right, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_MBUTTONDOWN => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Middle; - use events::ElementState::Pressed; - - capture_mouse(window); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Middle, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_MBUTTONUP => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Middle; - use events::ElementState::Released; - - release_mouse(); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Released, button: Middle, modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_XBUTTONDOWN => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Other; - use events::ElementState::Pressed; - let xbutton = winuser::GET_XBUTTON_WPARAM(wparam); - - capture_mouse(window); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Other(xbutton as u8), modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_XBUTTONUP => { - use events::WindowEvent::MouseInput; - use events::MouseButton::Other; - use events::ElementState::Released; - let xbutton = winuser::GET_XBUTTON_WPARAM(wparam); - - release_mouse(); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: MouseInput { device_id: DEVICE_ID, state: Released, button: Other(xbutton as u8), modifiers: event::get_key_mods() } - }); - 0 - }, - - winuser::WM_INPUT_DEVICE_CHANGE => { - let event = match wparam as _ { - winuser::GIDC_ARRIVAL => DeviceEvent::Added, - winuser::GIDC_REMOVAL => DeviceEvent::Removed, - _ => unreachable!(), - }; - - send_event(Event::DeviceEvent { - device_id: wrap_device_id(lparam as _), - event, - }); - - winuser::DefWindowProcW(window, msg, wparam, lparam) - }, - - winuser::WM_INPUT => { - use events::DeviceEvent::{Motion, MouseMotion, MouseWheel, Button, Key}; - use events::MouseScrollDelta::LineDelta; - use events::ElementState::{Pressed, Released}; - - if let Some(data) = get_raw_input_data(lparam as _) { - let device_id = wrap_device_id(data.header.hDevice as _); - - if data.header.dwType == winuser::RIM_TYPEMOUSE { - let mouse = data.data.mouse(); - - if util::has_flag(mouse.usFlags, winuser::MOUSE_MOVE_RELATIVE) { - let x = mouse.lLastX as f64; - let y = mouse.lLastY as f64; - - if x != 0.0 { - send_event(Event::DeviceEvent { - device_id, - event: Motion { axis: 0, value: x } - }); - } - - if y != 0.0 { - send_event(Event::DeviceEvent { - device_id, - event: Motion { axis: 1, value: y } - }); - } - - if x != 0.0 || y != 0.0 { - send_event(Event::DeviceEvent { - device_id, - event: MouseMotion { delta: (x, y) } - }); - } - } - - if util::has_flag(mouse.usButtonFlags, winuser::RI_MOUSE_WHEEL) { - let delta = mouse.usButtonData as SHORT / winuser::WHEEL_DELTA; - send_event(Event::DeviceEvent { - device_id, - event: MouseWheel { delta: LineDelta(0.0, delta as f32) } - }); - } - - let button_state = get_raw_mouse_button_state(mouse.usButtonFlags); - // Left, middle, and right, respectively. - for (index, state) in button_state.iter().enumerate() { - if let Some(state) = *state { - // This gives us consistency with X11, since there doesn't - // seem to be anything else reasonable to do for a mouse - // button ID. - let button = (index + 1) as _; - send_event(Event::DeviceEvent { - device_id, - event: Button { - button, - state, - } - }); - } - } - } else if data.header.dwType == winuser::RIM_TYPEKEYBOARD { - let keyboard = data.data.keyboard(); - - let pressed = keyboard.Message == winuser::WM_KEYDOWN - || keyboard.Message == winuser::WM_SYSKEYDOWN; - let released = keyboard.Message == winuser::WM_KEYUP - || keyboard.Message == winuser::WM_SYSKEYUP; - - if pressed || released { - let state = if pressed { - Pressed - } else { - Released - }; - - let scancode = keyboard.MakeCode as _; - let extended = util::has_flag(keyboard.Flags, winuser::RI_KEY_E0 as _) - | util::has_flag(keyboard.Flags, winuser::RI_KEY_E1 as _); - if let Some((vkey, scancode)) = handle_extended_keys( - keyboard.VKey as _, - scancode, - extended, - ) { - let virtual_keycode = vkey_to_winit_vkey(vkey); - - send_event(Event::DeviceEvent { - device_id, - event: Key(KeyboardInput { - scancode, - state, - virtual_keycode, - modifiers: event::get_key_mods(), - }), - }); - } - } - } - } - - winuser::DefWindowProcW(window, msg, wparam, lparam) - }, - - winuser::WM_TOUCH => { - let pcount = LOWORD( wparam as DWORD ) as usize; - let mut inputs = Vec::with_capacity( pcount ); - inputs.set_len( pcount ); - let htouch = lparam as winuser::HTOUCHINPUT; - if winuser::GetTouchInputInfo( - htouch, - pcount as UINT, - inputs.as_mut_ptr(), - mem::size_of::() as INT, - ) > 0 { - let dpi_factor = get_hwnd_scale_factor(window); - for input in &inputs { - let x = (input.x as f64) / 100f64; - let y = (input.y as f64) / 100f64; - let location = LogicalPosition::from_physical((x, y), dpi_factor); - send_event( Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: WindowEvent::Touch(Touch { - phase: - if input.dwFlags & winuser::TOUCHEVENTF_DOWN != 0 { - TouchPhase::Started - } else if input.dwFlags & winuser::TOUCHEVENTF_UP != 0 { - TouchPhase::Ended - } else if input.dwFlags & winuser::TOUCHEVENTF_MOVE != 0 { - TouchPhase::Moved - } else { - continue; - }, - location, - id: input.dwID as u64, - device_id: DEVICE_ID, - }) - }); - } - } - winuser::CloseTouchInputHandle( htouch ); - 0 - } - - winuser::WM_SETFOCUS => { - use events::WindowEvent::{Focused, CursorMoved}; - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Focused(true) - }); - - let x = windowsx::GET_X_LPARAM(lparam) as f64; - let y = windowsx::GET_Y_LPARAM(lparam) as f64; - let dpi_factor = get_hwnd_scale_factor(window); - let position = LogicalPosition::from_physical((x, y), dpi_factor); - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: CursorMoved { device_id: DEVICE_ID, position, modifiers: event::get_key_mods() }, - }); - - 0 - }, - - winuser::WM_KILLFOCUS => { - use events::WindowEvent::Focused; - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: Focused(false) - }); - 0 - }, - - winuser::WM_SETCURSOR => { - let call_def_window_proc = CONTEXT_STASH.with(|context_stash| { - context_stash - .borrow() - .as_ref() - .and_then(|cstash| cstash.windows.get(&window)) - .map(|window_state_mutex| { - let window_state = window_state_mutex.lock().unwrap(); - if window_state.mouse_in_window { - let cursor = winuser::LoadCursorW( - ptr::null_mut(), - window_state.cursor.0, - ); - winuser::SetCursor(cursor); - false - } else { - true - } - }) - .unwrap_or(true) - }); - - if call_def_window_proc { - winuser::DefWindowProcW(window, msg, wparam, lparam) - } else { - 0 - } - }, - - winuser::WM_DROPFILES => { - // See `FileDropHandler` for implementation. - 0 - }, - - winuser::WM_GETMINMAXINFO => { - let mmi = lparam as *mut winuser::MINMAXINFO; - //(*mmi).max_position = winapi::shared::windef::POINT { x: -8, y: -8 }; // The upper left corner of the window if it were maximized on the primary monitor. - //(*mmi).max_size = winapi::shared::windef::POINT { x: .., y: .. }; // The dimensions of the primary monitor. - - CONTEXT_STASH.with(|context_stash| { - if let Some(cstash) = context_stash.borrow().as_ref() { - if let Some(wstash) = cstash.windows.get(&window) { - let window_state = wstash.lock().unwrap(); - - if window_state.min_size.is_some() || window_state.max_size.is_some() { - let style = winuser::GetWindowLongA(window, winuser::GWL_STYLE) as DWORD; - let ex_style = winuser::GetWindowLongA(window, winuser::GWL_EXSTYLE) as DWORD; - if let Some(min_size) = window_state.min_size { - let (width, height) = adjust_size(min_size, style, ex_style); - (*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32 }; - } - if let Some(max_size) = window_state.max_size { - let (width, height) = adjust_size(max_size, style, ex_style); - (*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32 }; - } - } - } - } - }); - - 0 - }, - - // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change - // DPI, therefore all applications are closed while DPI is changing. - winuser::WM_DPICHANGED => { - use events::WindowEvent::HiDpiFactorChanged; - - // This message actually provides two DPI values - x and y. However MSDN says that - // "you only need to use either the X-axis or the Y-axis value when scaling your - // application since they are the same". - // https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx - let new_dpi_x = u32::from(LOWORD(wparam as DWORD)); - let new_dpi_factor = dpi_to_scale_factor(new_dpi_x); - - let suppress_resize = CONTEXT_STASH.with(|context_stash| { - context_stash - .borrow() - .as_ref() - .and_then(|cstash| cstash.windows.get(&window)) - .map(|window_state_mutex| { - let mut window_state = window_state_mutex.lock().unwrap(); - let suppress_resize = window_state.saved_window_info - .as_mut() - .map(|saved_window_info| { - let dpi_changed = if !saved_window_info.is_fullscreen { - saved_window_info.dpi_factor.take() != Some(new_dpi_factor) - } else { - false - }; - !dpi_changed || saved_window_info.is_fullscreen - }) - .unwrap_or(false); - // Now we adjust the min/max dimensions for the new DPI. - if !suppress_resize { - let old_dpi_factor = window_state.dpi_factor; - window_state.update_min_max(old_dpi_factor, new_dpi_factor); - } - window_state.dpi_factor = new_dpi_factor; - suppress_resize - }) - .unwrap_or(false) - }); - - // This prevents us from re-applying DPI adjustment to the restored size after exiting - // fullscreen (the restored size is already DPI adjusted). - if !suppress_resize { - // Resize window to the size suggested by Windows. - let rect = &*(lparam as *const RECT); - winuser::SetWindowPos( - window, - ptr::null_mut(), - rect.left, - rect.top, - rect.right - rect.left, - rect.bottom - rect.top, - winuser::SWP_NOZORDER | winuser::SWP_NOACTIVATE, - ); - } - - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: HiDpiFactorChanged(new_dpi_factor), - }); - - 0 - }, - - _ => { - if msg == *DESTROY_MSG_ID { - winuser::DestroyWindow(window); - 0 - } else if msg == *INITIAL_DPI_MSG_ID { - use events::WindowEvent::HiDpiFactorChanged; - let scale_factor = dpi_to_scale_factor(wparam as u32); - send_event(Event::WindowEvent { - window_id: SuperWindowId(WindowId(window)), - event: HiDpiFactorChanged(scale_factor), - }); - // Automatically resize for actual DPI - let width = LOWORD(lparam as DWORD) as u32; - let height = HIWORD(lparam as DWORD) as u32; - let (adjusted_width, adjusted_height): (u32, u32) = PhysicalSize::from_logical( - (width, height), - scale_factor, - ).into(); - // We're not done yet! `SetWindowPos` needs the window size, not the client area size. - let mut rect = RECT { - top: 0, - left: 0, - bottom: adjusted_height as LONG, - right: adjusted_width as LONG, - }; - let dw_style = winuser::GetWindowLongA(window, winuser::GWL_STYLE) as DWORD; - let b_menu = !winuser::GetMenu(window).is_null() as BOOL; - let dw_style_ex = winuser::GetWindowLongA(window, winuser::GWL_EXSTYLE) as DWORD; - winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex); - let outer_x = (rect.right - rect.left).abs() as c_int; - let outer_y = (rect.top - rect.bottom).abs() as c_int; - winuser::SetWindowPos( - window, - ptr::null_mut(), - 0, - 0, - outer_x, - outer_y, - winuser::SWP_NOMOVE - | winuser::SWP_NOREPOSITION - | winuser::SWP_NOZORDER - | winuser::SWP_NOACTIVATE, - ); - 0 - } else { - winuser::DefWindowProcW(window, msg, wparam, lparam) - } - } - } -} - -pub unsafe extern "system" fn thread_event_target_callback( - window: HWND, - msg: UINT, - wparam: WPARAM, - lparam: LPARAM, -) -> LRESULT { - // See `callback` comment. - run_catch_panic(-1, || { - match msg { - _ if msg == *EXEC_MSG_ID => { - let mut function: Box> = Box::from_raw(wparam as usize as *mut _); - function(); - 0 - }, - _ => winuser::DefWindowProcW(window, msg, wparam, lparam) - } - }) -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/icon.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/icon.rs deleted file mode 100644 index 6ea1e99..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/icon.rs +++ /dev/null @@ -1,114 +0,0 @@ -use std::{self, mem, ptr}; -use std::os::windows::ffi::OsStrExt; -use std::path::Path; - -use winapi::ctypes::{c_int, wchar_t}; -use winapi::shared::minwindef::{BYTE, LPARAM, WPARAM}; -use winapi::shared::windef::{HICON, HWND}; -use winapi::um::winuser; - -use {Pixel, PIXEL_SIZE, Icon}; -use platform::platform::util; - -impl Pixel { - fn to_bgra(&mut self) { - mem::swap(&mut self.r, &mut self.b); - } -} - -#[derive(Debug)] -pub enum IconType { - Small = winuser::ICON_SMALL as isize, - Big = winuser::ICON_BIG as isize, -} - -#[derive(Clone, Debug)] -pub struct WinIcon { - pub handle: HICON, -} - -unsafe impl Send for WinIcon {} - -impl WinIcon { - #[allow(dead_code)] - pub fn from_path>(path: P) -> Result { - let wide_path: Vec = path.as_ref().as_os_str().encode_wide().collect(); - let handle = unsafe { - winuser::LoadImageW( - ptr::null_mut(), - wide_path.as_ptr() as *const wchar_t, - winuser::IMAGE_ICON, - 0, // 0 indicates that we want to use the actual width - 0, // and height - winuser::LR_LOADFROMFILE, - ) as HICON - }; - if !handle.is_null() { - Ok(WinIcon { handle }) - } else { - Err(util::WinError::from_last_error()) - } - } - - pub fn from_icon(icon: Icon) -> Result { - Self::from_rgba(icon.rgba, icon.width, icon.height) - } - - pub fn from_rgba(mut rgba: Vec, width: u32, height: u32) -> Result { - assert_eq!(rgba.len() % PIXEL_SIZE, 0); - let pixel_count = rgba.len() / PIXEL_SIZE; - assert_eq!(pixel_count, (width * height) as usize); - let mut and_mask = Vec::with_capacity(pixel_count); - let pixels = rgba.as_mut_ptr() as *mut Pixel; // how not to write idiomatic Rust - for pixel_index in 0..pixel_count { - let pixel = unsafe { &mut *pixels.offset(pixel_index as isize) }; - and_mask.push(pixel.a.wrapping_sub(std::u8::MAX)); // invert alpha channel - pixel.to_bgra(); - } - assert_eq!(and_mask.len(), pixel_count); - let handle = unsafe { - winuser::CreateIcon( - ptr::null_mut(), - width as c_int, - height as c_int, - 1, - (PIXEL_SIZE * 8) as BYTE, - and_mask.as_ptr() as *const BYTE, - rgba.as_ptr() as *const BYTE, - ) as HICON - }; - if !handle.is_null() { - Ok(WinIcon { handle }) - } else { - Err(util::WinError::from_last_error()) - } - } - - pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) { - unsafe { - winuser::SendMessageW( - hwnd, - winuser::WM_SETICON, - icon_type as WPARAM, - self.handle as LPARAM, - ); - } - } -} - -impl Drop for WinIcon { - fn drop(&mut self) { - unsafe { winuser::DestroyIcon(self.handle) }; - } -} - -pub fn unset_for_window(hwnd: HWND, icon_type: IconType) { - unsafe { - winuser::SendMessageW( - hwnd, - winuser::WM_SETICON, - icon_type as WPARAM, - 0 as LPARAM, - ); - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/monitor.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/monitor.rs deleted file mode 100644 index 30394de..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/monitor.rs +++ /dev/null @@ -1,173 +0,0 @@ -use winapi::shared::minwindef::{BOOL, DWORD, LPARAM, TRUE}; -use winapi::shared::windef::{HDC, HMONITOR, HWND, LPRECT, POINT}; -use winapi::um::winnt::LONG; -use winapi::um::winuser; - -use std::{mem, ptr}; -use std::collections::VecDeque; - -use super::{EventsLoop, util}; -use dpi::{PhysicalPosition, PhysicalSize}; -use platform::platform::dpi::{dpi_to_scale_factor, get_monitor_dpi}; -use platform::platform::window::Window; - -/// Win32 implementation of the main `MonitorId` object. -#[derive(Debug, Clone)] -pub struct MonitorId { - /// Monitor handle. - hmonitor: HMonitor, - /// The system name of the monitor. - monitor_name: String, - /// True if this is the primary monitor. - primary: bool, - /// The position of the monitor in pixels on the desktop. - /// - /// A window that is positioned at these coordinates will overlap the monitor. - position: (i32, i32), - /// The current resolution in pixels on the monitor. - dimensions: (u32, u32), - /// DPI scale factor. - hidpi_factor: f64, -} - -// Send is not implemented for HMONITOR, we have to wrap it and implement it manually. -// For more info see: -// https://github.com/retep998/winapi-rs/issues/360 -// https://github.com/retep998/winapi-rs/issues/396 -#[derive(Debug, Clone)] -struct HMonitor(HMONITOR); - -unsafe impl Send for HMonitor {} - -unsafe extern "system" fn monitor_enum_proc( - hmonitor: HMONITOR, - _hdc: HDC, - _place: LPRECT, - data: LPARAM, -) -> BOOL { - let monitors = data as *mut VecDeque; - (*monitors).push_back(MonitorId::from_hmonitor(hmonitor)); - TRUE // continue enumeration -} - -pub fn get_available_monitors() -> VecDeque { - let mut monitors: VecDeque = VecDeque::new(); - unsafe { - winuser::EnumDisplayMonitors( - ptr::null_mut(), - ptr::null_mut(), - Some(monitor_enum_proc), - &mut monitors as *mut _ as LPARAM, - ); - } - monitors -} - -pub fn get_primary_monitor() -> MonitorId { - const ORIGIN: POINT = POINT { x: 0, y: 0 }; - let hmonitor = unsafe { - winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) - }; - MonitorId::from_hmonitor(hmonitor) -} - -impl EventsLoop { - // TODO: Investigate opportunities for caching - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors() - } - - pub fn get_current_monitor(hwnd: HWND) -> MonitorId { - let hmonitor = unsafe { - winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) - }; - MonitorId::from_hmonitor(hmonitor) - } - - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor() - } -} - -impl Window { - pub fn get_available_monitors(&self) -> VecDeque { - get_available_monitors() - } - - pub fn get_primary_monitor(&self) -> MonitorId { - get_primary_monitor() - } -} - -fn get_monitor_info(hmonitor: HMONITOR) -> Result { - let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::uninitialized() }; - monitor_info.cbSize = mem::size_of::() as DWORD; - let status = unsafe { - winuser::GetMonitorInfoW( - hmonitor, - &mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO, - ) - }; - if status == 0 { - Err(util::WinError::from_last_error()) - } else { - Ok(monitor_info) - } -} - -impl MonitorId { - pub(crate) fn from_hmonitor(hmonitor: HMONITOR) -> Self { - let monitor_info = get_monitor_info(hmonitor).expect("`GetMonitorInfoW` failed"); - let place = monitor_info.rcMonitor; - let dimensions = ( - (place.right - place.left) as u32, - (place.bottom - place.top) as u32, - ); - MonitorId { - hmonitor: HMonitor(hmonitor), - monitor_name: util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr()), - primary: util::has_flag(monitor_info.dwFlags, winuser::MONITORINFOF_PRIMARY), - position: (place.left as i32, place.top as i32), - dimensions, - hidpi_factor: dpi_to_scale_factor(get_monitor_dpi(hmonitor).unwrap_or(96)), - } - } - - pub(crate) fn contains_point(&self, point: &POINT) -> bool { - let left = self.position.0 as LONG; - let right = left + self.dimensions.0 as LONG; - let top = self.position.1 as LONG; - let bottom = top + self.dimensions.1 as LONG; - point.x >= left && point.x <= right && point.y >= top && point.y <= bottom - } - - #[inline] - pub fn get_name(&self) -> Option { - Some(self.monitor_name.clone()) - } - - #[inline] - pub fn get_native_identifier(&self) -> String { - self.monitor_name.clone() - } - - #[inline] - pub fn get_hmonitor(&self) -> HMONITOR { - self.hmonitor.0 - } - - #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { - self.dimensions.into() - } - - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - self.position.into() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.hidpi_factor - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/util.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/util.rs deleted file mode 100644 index a9f00ec..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/util.rs +++ /dev/null @@ -1,117 +0,0 @@ -use std::{self, mem, ptr, slice}; -use std::ops::BitAnd; - -use winapi::ctypes::wchar_t; -use winapi::shared::minwindef::{BOOL, DWORD}; -use winapi::shared::windef::{HWND, POINT, RECT}; -use winapi::um::errhandlingapi::GetLastError; -use winapi::um::winbase::{ - FormatMessageW, - FORMAT_MESSAGE_ALLOCATE_BUFFER, - FORMAT_MESSAGE_FROM_SYSTEM, - FORMAT_MESSAGE_IGNORE_INSERTS, - lstrlenW, - LocalFree, -}; -use winapi::um::winnt::{ - LPCWSTR, - MAKELANGID, - LANG_NEUTRAL, - SUBLANG_DEFAULT, -}; -use winapi::um::winuser; - -pub fn has_flag(bitset: T, flag: T) -> bool -where T: - Copy + PartialEq + BitAnd -{ - bitset & flag == flag -} - -pub fn wchar_to_string(wchar: &[wchar_t]) -> String { - String::from_utf16_lossy(wchar).to_string() -} - -pub fn wchar_ptr_to_string(wchar: *const wchar_t) -> String { - let len = unsafe { lstrlenW(wchar) } as usize; - let wchar_slice = unsafe { slice::from_raw_parts(wchar, len) }; - wchar_to_string(wchar_slice) -} - -pub unsafe fn status_map BOOL>(mut fun: F) -> Option { - let mut data: T = mem::uninitialized(); - if fun(&mut data) != 0 { - Some(data) - } else { - None - } -} - -pub fn get_cursor_pos() -> Option { - unsafe { status_map(|cursor_pos| winuser::GetCursorPos(cursor_pos)) } -} - -pub fn get_window_rect(hwnd: HWND) -> Option { - unsafe { status_map(|rect| winuser::GetWindowRect(hwnd, rect)) } -} - -pub fn get_client_rect(hwnd: HWND) -> Option { - unsafe { status_map(|rect| { - let mut top_left = mem::zeroed(); - if 0 == winuser::ClientToScreen(hwnd, &mut top_left) {return 0;}; - if 0 == winuser::GetClientRect(hwnd, rect) {return 0}; - rect.left += top_left.x; - rect.top += top_left.y; - rect.right += top_left.x; - rect.bottom += top_left.y; - 1 - }) } -} - -// This won't be needed anymore if we just add a derive to winapi. -pub fn rect_eq(a: &RECT, b: &RECT) -> bool { - let left_eq = a.left == b.left; - let right_eq = a.right == b.right; - let top_eq = a.top == b.top; - let bottom_eq = a.bottom == b.bottom; - left_eq && right_eq && top_eq && bottom_eq -} - -#[derive(Debug, Default, Clone, PartialEq, Eq)] -pub struct WinError(Option); - -impl WinError { - pub fn from_last_error() -> Self { - WinError(unsafe { get_last_error() }) - } -} - -pub unsafe fn get_last_error() -> Option { - let err = GetLastError(); - if err != 0 { - let buf_addr: LPCWSTR = { - let mut buf_addr: LPCWSTR = mem::uninitialized(); - FormatMessageW( - FORMAT_MESSAGE_ALLOCATE_BUFFER - | FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS, - ptr::null(), - err, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) as DWORD, - // This is a pointer to a pointer - &mut buf_addr as *mut LPCWSTR as *mut _, - 0, - ptr::null_mut(), - ); - buf_addr - }; - if !buf_addr.is_null() { - let buf_len = lstrlenW(buf_addr) as usize; - let buf_slice = std::slice::from_raw_parts(buf_addr, buf_len); - let string = wchar_to_string(buf_slice); - LocalFree(buf_addr as *mut _); - return Some(string); - } - } - None -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/window.rs b/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/window.rs deleted file mode 100644 index e772742..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/window.rs +++ /dev/null @@ -1,1167 +0,0 @@ -#![cfg(target_os = "windows")] - -use std::{io, mem, ptr}; -use std::cell::Cell; -use std::ffi::OsStr; -use std::os::windows::ffi::OsStrExt; -use std::sync::{Arc, Mutex}; -use std::sync::mpsc::channel; - -use winapi::ctypes::c_int; -use winapi::shared::minwindef::{BOOL, DWORD, FALSE, LPARAM, TRUE, UINT, WORD, WPARAM}; -use winapi::shared::windef::{HWND, LPPOINT, POINT, RECT}; -use winapi::um::{combaseapi, dwmapi, libloaderapi, winuser}; -use winapi::um::objbase::COINIT_MULTITHREADED; -use winapi::um::shobjidl_core::{CLSID_TaskbarList, ITaskbarList2}; -use winapi::um::wingdi::{CreateRectRgn, DeleteObject}; -use winapi::um::winnt::{LONG, LPCWSTR}; - -use { - CreationError, - Icon, - LogicalPosition, - LogicalSize, - MonitorId as RootMonitorId, - MouseCursor, - PhysicalSize, - WindowAttributes, -}; -use platform::platform::{Cursor, PlatformSpecificWindowBuilderAttributes, WindowId}; -use platform::platform::dpi::{dpi_to_scale_factor, get_hwnd_dpi}; -use platform::platform::events_loop::{self, EventsLoop, DESTROY_MSG_ID, INITIAL_DPI_MSG_ID}; -use platform::platform::events_loop::WindowState; -use platform::platform::icon::{self, IconType, WinIcon}; -use platform::platform::monitor::get_available_monitors; -use platform::platform::raw_input::register_all_mice_and_keyboards_for_raw_input; -use platform::platform::util; - -const WS_RESIZABLE: DWORD = winuser::WS_SIZEBOX | winuser::WS_MAXIMIZEBOX; - -/// The Win32 implementation of the main `Window` object. -pub struct Window { - /// Main handle for the window. - window: WindowWrapper, - - /// The current window state. - window_state: Arc>, - - // The events loop proxy. - events_loop_proxy: events_loop::EventsLoopProxy, -} - -impl Window { - pub fn new( - events_loop: &EventsLoop, - w_attr: WindowAttributes, - pl_attr: PlatformSpecificWindowBuilderAttributes, - ) -> Result { - let (tx, rx) = channel(); - let proxy = events_loop.create_proxy(); - events_loop.execute_in_thread(move |inserter| { - // We dispatch an `init` function because of code style. - // First person to remove the need for cloning here gets a cookie! - let win = unsafe { init(w_attr.clone(), pl_attr.clone(), inserter, proxy.clone()) }; - let _ = tx.send(win); - }); - rx.recv().unwrap() - } - - pub fn set_title(&self, text: &str) { - let text = OsStr::new(text) - .encode_wide() - .chain(Some(0).into_iter()) - .collect::>(); - unsafe { - winuser::SetWindowTextW(self.window.0, text.as_ptr() as LPCWSTR); - } - } - - #[inline] - pub fn show(&self) { - unsafe { - winuser::ShowWindow(self.window.0, winuser::SW_SHOW); - } - } - - #[inline] - pub fn hide(&self) { - unsafe { - winuser::ShowWindow(self.window.0, winuser::SW_HIDE); - } - } - - pub(crate) fn get_position_physical(&self) -> Option<(i32, i32)> { - util::get_window_rect(self.window.0) - .map(|rect| (rect.left as i32, rect.top as i32)) - } - - #[inline] - pub fn get_position(&self) -> Option { - self.get_position_physical() - .map(|physical_position| { - let dpi_factor = self.get_hidpi_factor(); - LogicalPosition::from_physical(physical_position, dpi_factor) - }) - } - - pub(crate) fn get_inner_position_physical(&self) -> Option<(i32, i32)> { - let mut position: POINT = unsafe { mem::zeroed() }; - if unsafe { winuser::ClientToScreen(self.window.0, &mut position) } == 0 { - return None; - } - Some((position.x, position.y)) - } - - #[inline] - pub fn get_inner_position(&self) -> Option { - self.get_inner_position_physical() - .map(|physical_position| { - let dpi_factor = self.get_hidpi_factor(); - LogicalPosition::from_physical(physical_position, dpi_factor) - }) - } - - pub(crate) fn set_position_physical(&self, x: i32, y: i32) { - unsafe { - winuser::SetWindowPos( - self.window.0, - ptr::null_mut(), - x as c_int, - y as c_int, - 0, - 0, - winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER | winuser::SWP_NOSIZE, - ); - winuser::UpdateWindow(self.window.0); - } - } - - #[inline] - pub fn set_position(&self, logical_position: LogicalPosition) { - let dpi_factor = self.get_hidpi_factor(); - let (x, y) = logical_position.to_physical(dpi_factor).into(); - self.set_position_physical(x, y); - } - - pub(crate) fn get_inner_size_physical(&self) -> Option<(u32, u32)> { - let mut rect: RECT = unsafe { mem::uninitialized() }; - if unsafe { winuser::GetClientRect(self.window.0, &mut rect) } == 0 { - return None; - } - Some(( - (rect.right - rect.left) as u32, - (rect.bottom - rect.top) as u32, - )) - } - - #[inline] - pub fn get_inner_size(&self) -> Option { - self.get_inner_size_physical() - .map(|physical_size| { - let dpi_factor = self.get_hidpi_factor(); - LogicalSize::from_physical(physical_size, dpi_factor) - }) - } - - pub(crate) fn get_outer_size_physical(&self) -> Option<(u32, u32)> { - util::get_window_rect(self.window.0) - .map(|rect| ( - (rect.right - rect.left) as u32, - (rect.bottom - rect.top) as u32, - )) - } - - #[inline] - pub fn get_outer_size(&self) -> Option { - self.get_outer_size_physical() - .map(|physical_size| { - let dpi_factor = self.get_hidpi_factor(); - LogicalSize::from_physical(physical_size, dpi_factor) - }) - } - - pub(crate) fn set_inner_size_physical(&self, x: u32, y: u32) { - unsafe { - let mut rect = RECT { - top: 0, - left: 0, - bottom: y as LONG, - right: x as LONG, - }; - let dw_style = winuser::GetWindowLongA(self.window.0, winuser::GWL_STYLE) as DWORD; - let b_menu = !winuser::GetMenu(self.window.0).is_null() as BOOL; - let dw_style_ex = winuser::GetWindowLongA(self.window.0, winuser::GWL_EXSTYLE) as DWORD; - winuser::AdjustWindowRectEx(&mut rect, dw_style, b_menu, dw_style_ex); - let outer_x = (rect.right - rect.left).abs() as c_int; - let outer_y = (rect.top - rect.bottom).abs() as c_int; - winuser::SetWindowPos( - self.window.0, - ptr::null_mut(), - 0, - 0, - outer_x, - outer_y, - winuser::SWP_ASYNCWINDOWPOS - | winuser::SWP_NOZORDER - | winuser::SWP_NOREPOSITION - | winuser::SWP_NOMOVE, - ); - winuser::UpdateWindow(self.window.0); - } - } - - #[inline] - pub fn set_inner_size(&self, logical_size: LogicalSize) { - let dpi_factor = self.get_hidpi_factor(); - let (width, height) = logical_size.to_physical(dpi_factor).into(); - self.set_inner_size_physical(width, height); - } - - pub(crate) fn set_min_dimensions_physical(&self, dimensions: Option<(u32, u32)>) { - self.window_state.lock().unwrap().min_size = dimensions.map(Into::into); - // Make windows re-check the window size bounds. - self.get_inner_size_physical() - .map(|(width, height)| self.set_inner_size_physical(width, height)); - } - - #[inline] - pub fn set_min_dimensions(&self, logical_size: Option) { - let physical_size = logical_size.map(|logical_size| { - let dpi_factor = self.get_hidpi_factor(); - logical_size.to_physical(dpi_factor).into() - }); - self.set_min_dimensions_physical(physical_size); - } - - pub fn set_max_dimensions_physical(&self, dimensions: Option<(u32, u32)>) { - self.window_state.lock().unwrap().max_size = dimensions.map(Into::into); - // Make windows re-check the window size bounds. - self.get_inner_size_physical() - .map(|(width, height)| self.set_inner_size_physical(width, height)); - } - - #[inline] - pub fn set_max_dimensions(&self, logical_size: Option) { - let physical_size = logical_size.map(|logical_size| { - let dpi_factor = self.get_hidpi_factor(); - logical_size.to_physical(dpi_factor).into() - }); - self.set_max_dimensions_physical(physical_size); - } - - #[inline] - pub fn set_resizable(&self, resizable: bool) { - let mut window_state = self.window_state.lock().unwrap(); - if mem::replace(&mut window_state.resizable, resizable) != resizable { - // If we're in fullscreen, update stored configuration but don't apply anything. - if window_state.fullscreen.is_none() { - let mut style = unsafe { - winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE) - }; - - if resizable { - style |= WS_RESIZABLE as LONG; - } else { - style &= !WS_RESIZABLE as LONG; - } - - unsafe { - winuser::SetWindowLongW(self.window.0, winuser::GWL_STYLE, style as _); - }; - } - } - } - - /// Returns the `hwnd` of this window. - #[inline] - pub fn hwnd(&self) -> HWND { - self.window.0 - } - - #[inline] - pub fn set_cursor(&self, cursor: MouseCursor) { - let cursor_id = Cursor(match cursor { - MouseCursor::Arrow | MouseCursor::Default => winuser::IDC_ARROW, - MouseCursor::Hand => winuser::IDC_HAND, - MouseCursor::Crosshair => winuser::IDC_CROSS, - MouseCursor::Text | MouseCursor::VerticalText => winuser::IDC_IBEAM, - MouseCursor::NotAllowed | MouseCursor::NoDrop => winuser::IDC_NO, - MouseCursor::Grab | MouseCursor::Grabbing | - MouseCursor::Move | MouseCursor::AllScroll => winuser::IDC_SIZEALL, - MouseCursor::EResize | MouseCursor::WResize | - MouseCursor::EwResize | MouseCursor::ColResize => winuser::IDC_SIZEWE, - MouseCursor::NResize | MouseCursor::SResize | - MouseCursor::NsResize | MouseCursor::RowResize => winuser::IDC_SIZENS, - MouseCursor::NeResize | MouseCursor::SwResize | - MouseCursor::NeswResize => winuser::IDC_SIZENESW, - MouseCursor::NwResize | MouseCursor::SeResize | - MouseCursor::NwseResize => winuser::IDC_SIZENWSE, - MouseCursor::Wait => winuser::IDC_WAIT, - MouseCursor::Progress => winuser::IDC_APPSTARTING, - MouseCursor::Help => winuser::IDC_HELP, - _ => winuser::IDC_ARROW, // use arrow for the missing cases. - }); - self.window_state.lock().unwrap().cursor = cursor_id; - self.events_loop_proxy.execute_in_thread(move |_| unsafe { - let cursor = winuser::LoadCursorW( - ptr::null_mut(), - cursor_id.0, - ); - winuser::SetCursor(cursor); - }); - } - - unsafe fn cursor_is_grabbed(&self) -> Result { - let mut client_rect: RECT = mem::uninitialized(); - let mut clip_rect: RECT = mem::uninitialized(); - if winuser::GetClientRect(self.window.0, &mut client_rect) == 0 { - return Err("`GetClientRect` failed".to_owned()); - } - // A `POINT` is two `LONG`s (x, y), and the `RECT` field after `left` is `top`. - if winuser::ClientToScreen(self.window.0, &mut client_rect.left as *mut _ as LPPOINT) == 0 { - return Err("`ClientToScreen` (left, top) failed".to_owned()); - } - if winuser::ClientToScreen(self.window.0, &mut client_rect.right as *mut _ as LPPOINT) == 0 { - return Err("`ClientToScreen` (right, bottom) failed".to_owned()); - } - if winuser::GetClipCursor(&mut clip_rect) == 0 { - return Err("`GetClipCursor` failed".to_owned()); - } - Ok(util::rect_eq(&client_rect, &clip_rect)) - } - - pub(crate) unsafe fn grab_cursor_inner(window: &WindowWrapper, grab: bool) -> Result<(), String> { - if grab { - let mut rect = mem::uninitialized(); - if winuser::GetClientRect(window.0, &mut rect) == 0 { - return Err("`GetClientRect` failed".to_owned()); - } - // A `POINT` is two `LONG`s (x, y), and the `RECT` field after `left` is `top`. - if winuser::ClientToScreen(window.0, &mut rect.left as *mut _ as LPPOINT) == 0 { - return Err("`ClientToScreen` (left, top) failed".to_owned()); - } - if winuser::ClientToScreen(window.0, &mut rect.right as *mut _ as LPPOINT) == 0 { - return Err("`ClientToScreen` (right, bottom) failed".to_owned()); - } - if winuser::ClipCursor(&rect) == 0 { - return Err("`ClipCursor` failed".to_owned()); - } - } else { - if winuser::ClipCursor(ptr::null()) == 0 { - return Err("`ClipCursor` failed".to_owned()); - } - } - Ok(()) - } - - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - let currently_grabbed = unsafe { self.cursor_is_grabbed() }?; - let window_state_lock = self.window_state.lock().unwrap(); - if currently_grabbed == grab && grab == window_state_lock.cursor_grabbed { - return Ok(()); - } - let window = self.window.clone(); - let window_state = Arc::clone(&self.window_state); - let (tx, rx) = channel(); - self.events_loop_proxy.execute_in_thread(move |_| { - let result = unsafe { Self::grab_cursor_inner(&window, grab) }; - if result.is_ok() { - window_state.lock().unwrap().cursor_grabbed = grab; - } - let _ = tx.send(result); - }); - drop(window_state_lock); - rx.recv().unwrap() - } - - pub(crate) unsafe fn hide_cursor_inner(hide: bool) { - if hide { - winuser::ShowCursor(FALSE); - } else { - winuser::ShowCursor(TRUE); - } - } - - #[inline] - pub fn hide_cursor(&self, hide: bool) { - let window_state_lock = self.window_state.lock().unwrap(); - // We don't want to increment/decrement the display count more than once! - if hide == window_state_lock.cursor_hidden { return; } - let (tx, rx) = channel(); - let window_state = Arc::clone(&self.window_state); - self.events_loop_proxy.execute_in_thread(move |_| { - unsafe { Self::hide_cursor_inner(hide) }; - window_state.lock().unwrap().cursor_hidden = hide; - let _ = tx.send(()); - }); - drop(window_state_lock); - rx.recv().unwrap() - } - - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.window_state.lock().unwrap().dpi_factor - } - - fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), String> { - let mut point = POINT { x, y }; - unsafe { - if winuser::ClientToScreen(self.window.0, &mut point) == 0 { - return Err("`ClientToScreen` failed".to_owned()); - } - if winuser::SetCursorPos(point.x, point.y) == 0 { - return Err("`SetCursorPos` failed".to_owned()); - } - } - Ok(()) - } - - #[inline] - pub fn set_cursor_position(&self, logical_position: LogicalPosition) -> Result<(), String> { - let dpi_factor = self.get_hidpi_factor(); - let (x, y) = logical_position.to_physical(dpi_factor).into(); - self.set_cursor_position_physical(x, y) - } - - #[inline] - pub fn id(&self) -> WindowId { - WindowId(self.window.0) - } - - #[inline] - pub fn set_maximized(&self, maximized: bool) { - let mut window_state = self.window_state.lock().unwrap(); - if mem::replace(&mut window_state.maximized, maximized) != maximized { - // We only maximize if we're not in fullscreen. - if window_state.fullscreen.is_none() { - let window = self.window.clone(); - unsafe { - // `ShowWindow` resizes the window, so it must be called from the main thread. - self.events_loop_proxy.execute_in_thread(move |_| { - winuser::ShowWindow( - window.0, - if maximized { - winuser::SW_MAXIMIZE - } else { - winuser::SW_RESTORE - }, - ); - }); - } - } - } - } - - unsafe fn set_fullscreen_style(&self, window_state: &mut WindowState) -> (LONG, LONG) { - if window_state.fullscreen.is_none() || window_state.saved_window_info.is_none() { - let client_rect = util::get_client_rect(self.window.0).expect("client rect retrieval failed"); - let dpi_factor = Some(window_state.dpi_factor); - window_state.saved_window_info = Some(events_loop::SavedWindowInfo { - style: winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE), - ex_style: winuser::GetWindowLongW(self.window.0, winuser::GWL_EXSTYLE), - client_rect, - is_fullscreen: true, - dpi_factor, - }); - } - - // We sync the system maximized state here, it will be used when restoring - let mut placement: winuser::WINDOWPLACEMENT = mem::zeroed(); - placement.length = mem::size_of::() as u32; - winuser::GetWindowPlacement(self.window.0, &mut placement); - window_state.maximized = placement.showCmd == (winuser::SW_SHOWMAXIMIZED as u32); - let saved_window_info = window_state.saved_window_info.as_ref().unwrap(); - - (saved_window_info.style, saved_window_info.ex_style) - } - - unsafe fn restore_saved_window(&self, window_state_lock: &mut WindowState) { - let (client_rect, mut style, ex_style) = { - // 'saved_window_info' can be None if the window has never been - // in fullscreen mode before this method gets called. - if window_state_lock.saved_window_info.is_none() { - return; - } - - let saved_window_info = window_state_lock.saved_window_info.as_mut().unwrap(); - - // Reset original window style and size. The multiple window size/moves - // here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be - // repainted. Better-looking methods welcome. - saved_window_info.is_fullscreen = false; - - let client_rect = saved_window_info.client_rect.clone(); - let (style, ex_style) = (saved_window_info.style, saved_window_info.ex_style); - (client_rect, style, ex_style) - }; - let window = self.window.clone(); - let window_state = Arc::clone(&self.window_state); - - let resizable = window_state_lock.resizable; - let decorations = window_state_lock.decorations; - let maximized = window_state_lock.maximized; - - // We're restoring the window to its size and position from before being fullscreened. - // `ShowWindow` resizes the window, so it must be called from the main thread. - self.events_loop_proxy.execute_in_thread(move |_| { - let _ = Self::grab_cursor_inner(&window, false); - - if resizable && decorations { - style |= WS_RESIZABLE as LONG; - } else { - style &= !WS_RESIZABLE as LONG; - } - winuser::SetWindowLongW(window.0, winuser::GWL_STYLE, style); - winuser::SetWindowLongW(window.0, winuser::GWL_EXSTYLE, ex_style); - - let mut rect = client_rect; - winuser::AdjustWindowRectEx(&mut rect, style as _, 0, ex_style as _); - - winuser::SetWindowPos( - window.0, - ptr::null_mut(), - rect.left, - rect.top, - rect.right - rect.left, - rect.bottom - rect.top, - winuser::SWP_ASYNCWINDOWPOS - | winuser::SWP_NOZORDER - | winuser::SWP_NOACTIVATE - | winuser::SWP_FRAMECHANGED, - ); - - // We apply any requested changes to maximization state that occurred while we were in fullscreen. - winuser::ShowWindow( - window.0, - if maximized { - winuser::SW_MAXIMIZE - } else { - winuser::SW_RESTORE - }, - ); - - mark_fullscreen(window.0, false); - - let window_state_lock = window_state.lock().unwrap(); - let _ = Self::grab_cursor_inner(&window, window_state_lock.cursor_grabbed); - }); - } - - #[inline] - pub fn set_fullscreen(&self, monitor: Option) { - let mut window_state_lock = self.window_state.lock().unwrap(); - unsafe { - match &monitor { - &Some(RootMonitorId { ref inner }) => { - let (x, y): (i32, i32) = inner.get_position().into(); - let (width, height): (u32, u32) = inner.get_dimensions().into(); - let window = self.window.clone(); - let window_state = Arc::clone(&self.window_state); - - let (style, ex_style) = self.set_fullscreen_style(&mut window_state_lock); - self.events_loop_proxy.execute_in_thread(move |_| { - let _ = Self::grab_cursor_inner(&window, false); - - winuser::SetWindowLongW( - window.0, - winuser::GWL_STYLE, - ((style as DWORD) & !(winuser::WS_CAPTION | winuser::WS_THICKFRAME)) - as LONG, - ); - - winuser::SetWindowLongW( - window.0, - winuser::GWL_EXSTYLE, - ((ex_style as DWORD) - & !(winuser::WS_EX_DLGMODALFRAME | winuser::WS_EX_WINDOWEDGE - | winuser::WS_EX_CLIENTEDGE - | winuser::WS_EX_STATICEDGE)) - as LONG, - ); - - winuser::SetWindowPos( - window.0, - ptr::null_mut(), - x as c_int, - y as c_int, - width as c_int, - height as c_int, - winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER - | winuser::SWP_NOACTIVATE - | winuser::SWP_FRAMECHANGED, - ); - - mark_fullscreen(window.0, true); - - let window_state_lock = window_state.lock().unwrap(); - let _ = Self::grab_cursor_inner(&window, window_state_lock.cursor_grabbed); - }); - } - &None => { - self.restore_saved_window(&mut window_state_lock); - } - } - } - - window_state_lock.fullscreen = monitor; - } - - #[inline] - pub fn set_decorations(&self, decorations: bool) { - let mut window_state = self.window_state.lock().unwrap(); - if mem::replace(&mut window_state.decorations, decorations) != decorations { - let style_flags = (winuser::WS_CAPTION | winuser::WS_THICKFRAME) as LONG; - let ex_style_flags = (winuser::WS_EX_WINDOWEDGE) as LONG; - - // if we are in fullscreen mode, we only change the saved window info - if window_state.fullscreen.is_some() { - let resizable = window_state.resizable; - let saved = window_state.saved_window_info.as_mut().unwrap(); - - if decorations { - saved.style = saved.style | style_flags; - saved.ex_style = saved.ex_style | ex_style_flags; - } else { - saved.style = saved.style & !style_flags; - saved.ex_style = saved.ex_style & !ex_style_flags; - } - if resizable { - saved.style |= WS_RESIZABLE as LONG; - } else { - saved.style &= !WS_RESIZABLE as LONG; - } - } else { - unsafe { - let mut rect = util::get_client_rect(self.window.0).expect("Get client rect failed!"); - - let mut style = winuser::GetWindowLongW(self.window.0, winuser::GWL_STYLE); - let mut ex_style = winuser::GetWindowLongW(self.window.0, winuser::GWL_EXSTYLE); - - if decorations { - style = style | style_flags; - ex_style = ex_style | ex_style_flags; - } else { - style = style & !style_flags; - ex_style = ex_style & !ex_style_flags; - } - - let window = self.window.clone(); - - self.events_loop_proxy.execute_in_thread(move |_| { - winuser::SetWindowLongW(window.0, winuser::GWL_STYLE, style); - winuser::SetWindowLongW(window.0, winuser::GWL_EXSTYLE, ex_style); - winuser::AdjustWindowRectEx(&mut rect, style as _, 0, ex_style as _); - - winuser::SetWindowPos( - window.0, - ptr::null_mut(), - rect.left, - rect.top, - rect.right - rect.left, - rect.bottom - rect.top, - winuser::SWP_ASYNCWINDOWPOS - | winuser::SWP_NOZORDER - | winuser::SWP_NOACTIVATE - | winuser::SWP_FRAMECHANGED, - ); - }); - } - } - } - } - - #[inline] - pub fn set_always_on_top(&self, always_on_top: bool) { - let mut window_state = self.window_state.lock().unwrap(); - if mem::replace(&mut window_state.always_on_top, always_on_top) != always_on_top { - let window = self.window.clone(); - self.events_loop_proxy.execute_in_thread(move |_| { - let insert_after = if always_on_top { - winuser::HWND_TOPMOST - } else { - winuser::HWND_NOTOPMOST - }; - unsafe { - winuser::SetWindowPos( - window.0, - insert_after, - 0, - 0, - 0, - 0, - winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOMOVE | winuser::SWP_NOSIZE, - ); - winuser::UpdateWindow(window.0); - } - }); - } - } - - #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - RootMonitorId { - inner: EventsLoop::get_current_monitor(self.window.0), - } - } - - #[inline] - pub fn set_window_icon(&self, mut window_icon: Option) { - let window_icon = window_icon - .take() - .map(|icon| WinIcon::from_icon(icon).expect("Failed to create `ICON_SMALL`")); - if let Some(ref window_icon) = window_icon { - window_icon.set_for_window(self.window.0, IconType::Small); - } else { - icon::unset_for_window(self.window.0, IconType::Small); - } - self.window_state.lock().unwrap().window_icon = window_icon; - } - - #[inline] - pub fn set_taskbar_icon(&self, mut taskbar_icon: Option) { - let taskbar_icon = taskbar_icon - .take() - .map(|icon| WinIcon::from_icon(icon).expect("Failed to create `ICON_BIG`")); - if let Some(ref taskbar_icon) = taskbar_icon { - taskbar_icon.set_for_window(self.window.0, IconType::Big); - } else { - icon::unset_for_window(self.window.0, IconType::Big); - } - self.window_state.lock().unwrap().taskbar_icon = taskbar_icon; - } - - #[inline] - pub fn set_ime_spot(&self, _logical_spot: LogicalPosition) { - unimplemented!(); - } -} - -impl Drop for Window { - #[inline] - fn drop(&mut self) { - unsafe { - // The window must be destroyed from the same thread that created it, so we send a - // custom message to be handled by our callback to do the actual work. - winuser::PostMessageW(self.window.0, *DESTROY_MSG_ID, 0, 0); - } - } -} - -/// A simple non-owning wrapper around a window. -#[doc(hidden)] -#[derive(Clone)] -pub struct WindowWrapper(HWND); - -// Send and Sync are not implemented for HWND and HDC, we have to wrap it and implement them manually. -// For more info see: -// https://github.com/retep998/winapi-rs/issues/360 -// https://github.com/retep998/winapi-rs/issues/396 -unsafe impl Sync for WindowWrapper {} -unsafe impl Send for WindowWrapper {} - -pub unsafe fn adjust_size( - physical_size: PhysicalSize, - style: DWORD, - ex_style: DWORD, -) -> (LONG, LONG) { - let (width, height): (u32, u32) = physical_size.into(); - let mut rect = RECT { - left: 0, - right: width as LONG, - top: 0, - bottom: height as LONG, - }; - winuser::AdjustWindowRectEx(&mut rect, style, 0, ex_style); - (rect.right - rect.left, rect.bottom - rect.top) -} - -unsafe fn init( - mut attributes: WindowAttributes, - mut pl_attribs: PlatformSpecificWindowBuilderAttributes, - inserter: events_loop::Inserter, - events_loop_proxy: events_loop::EventsLoopProxy, -) -> Result { - let title = OsStr::new(&attributes.title) - .encode_wide() - .chain(Some(0).into_iter()) - .collect::>(); - - let window_icon = { - let icon = attributes.window_icon - .take() - .map(WinIcon::from_icon); - if icon.is_some() { - Some(icon.unwrap().map_err(|err| { - CreationError::OsError(format!("Failed to create `ICON_SMALL`: {:?}", err)) - })?) - } else { - None - } - }; - let taskbar_icon = { - let icon = pl_attribs.taskbar_icon - .take() - .map(WinIcon::from_icon); - if icon.is_some() { - Some(icon.unwrap().map_err(|err| { - CreationError::OsError(format!("Failed to create `ICON_BIG`: {:?}", err)) - })?) - } else { - None - } - }; - - // registering the window class - let class_name = register_window_class(&window_icon, &taskbar_icon); - - let guessed_dpi_factor = { - let monitors = get_available_monitors(); - let dpi_factor = if !monitors.is_empty() { - let mut dpi_factor = Some(monitors[0].get_hidpi_factor()); - for monitor in &monitors { - if Some(monitor.get_hidpi_factor()) != dpi_factor { - dpi_factor = None; - } - } - dpi_factor - } else { - return Err(CreationError::OsError(format!("No monitors were detected."))); - }; - dpi_factor.unwrap_or_else(|| { - util::get_cursor_pos() - .and_then(|cursor_pos| { - let mut dpi_factor = None; - for monitor in &monitors { - if monitor.contains_point(&cursor_pos) { - dpi_factor = Some(monitor.get_hidpi_factor()); - break; - } - } - dpi_factor - }) - .unwrap_or(1.0) - }) - }; - info!("Guessed window DPI factor: {}", guessed_dpi_factor); - - let dimensions = attributes.dimensions.unwrap_or_else(|| (1024, 768).into()); - let (width, height): (u32, u32) = dimensions.to_physical(guessed_dpi_factor).into(); - // building a RECT object with coordinates - let mut rect = RECT { - left: 0, - right: width as LONG, - top: 0, - bottom: height as LONG, - }; - - // computing the style and extended style of the window - let (mut ex_style, style) = if !attributes.decorations { - (winuser::WS_EX_APPWINDOW, - //winapi::WS_POPUP is incompatible with winapi::WS_CHILD - if pl_attribs.parent.is_some() { - winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN - } - else { - winuser::WS_POPUP | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN - } - ) - } else { - (winuser::WS_EX_APPWINDOW | winuser::WS_EX_WINDOWEDGE, - winuser::WS_OVERLAPPEDWINDOW | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN) - }; - - if attributes.always_on_top { - ex_style |= winuser::WS_EX_TOPMOST; - } - if pl_attribs.no_redirection_bitmap { - ex_style |= winuser::WS_EX_NOREDIRECTIONBITMAP; - } - if attributes.transparent && attributes.decorations { - ex_style |= winuser::WS_EX_LAYERED; - } - - // adjusting the window coordinates using the style - winuser::AdjustWindowRectEx(&mut rect, style, 0, ex_style); - - // creating the real window this time, by using the functions in `extra_functions` - let real_window = { - let (adjusted_width, adjusted_height) = if attributes.dimensions.is_some() { - let min_dimensions = attributes.min_dimensions - .map(|logical_size| PhysicalSize::from_logical(logical_size, guessed_dpi_factor)) - .map(|physical_size| adjust_size(physical_size, style, ex_style)) - .unwrap_or((0, 0)); - let max_dimensions = attributes.max_dimensions - .map(|logical_size| PhysicalSize::from_logical(logical_size, guessed_dpi_factor)) - .map(|physical_size| adjust_size(physical_size, style, ex_style)) - .unwrap_or((c_int::max_value(), c_int::max_value())); - ( - Some((rect.right - rect.left).min(max_dimensions.0).max(min_dimensions.0)), - Some((rect.bottom - rect.top).min(max_dimensions.1).max(min_dimensions.1)) - ) - } else { - (None, None) - }; - - let mut style = if !attributes.visible { - style - } else { - style | winuser::WS_VISIBLE - }; - - if !attributes.resizable { - style &= !WS_RESIZABLE; - } - - if pl_attribs.parent.is_some() { - style |= winuser::WS_CHILD; - } - - let handle = winuser::CreateWindowExW(ex_style | winuser::WS_EX_ACCEPTFILES, - class_name.as_ptr(), - title.as_ptr() as LPCWSTR, - style | winuser::WS_CLIPSIBLINGS | winuser::WS_CLIPCHILDREN, - winuser::CW_USEDEFAULT, winuser::CW_USEDEFAULT, - adjusted_width.unwrap_or(winuser::CW_USEDEFAULT), - adjusted_height.unwrap_or(winuser::CW_USEDEFAULT), - pl_attribs.parent.unwrap_or(ptr::null_mut()), - ptr::null_mut(), - libloaderapi::GetModuleHandleW(ptr::null()), - ptr::null_mut(), - ); - - if handle.is_null() { - return Err(CreationError::OsError(format!("CreateWindowEx function failed: {}", - format!("{}", io::Error::last_os_error())))); - } - - WindowWrapper(handle) - }; - - // Set up raw input - register_all_mice_and_keyboards_for_raw_input(real_window.0); - - // Register for touch events if applicable - { - let digitizer = winuser::GetSystemMetrics( winuser::SM_DIGITIZER ) as u32; - if digitizer & winuser::NID_READY != 0 { - winuser::RegisterTouchWindow( real_window.0, winuser::TWF_WANTPALM ); - } - } - - let dpi = get_hwnd_dpi(real_window.0); - let dpi_factor = dpi_to_scale_factor(dpi); - if dpi_factor != guessed_dpi_factor { - let (width, height): (u32, u32) = dimensions.into(); - let mut packed_dimensions = 0; - // MAKELPARAM isn't provided by winapi yet. - let ptr = &mut packed_dimensions as *mut LPARAM as *mut WORD; - *ptr.offset(0) = width as WORD; - *ptr.offset(1) = height as WORD; - winuser::PostMessageW( - real_window.0, - *INITIAL_DPI_MSG_ID, - dpi as WPARAM, - packed_dimensions, - ); - } - - let window_state = { - let max_size = attributes.max_dimensions - .map(|logical_size| PhysicalSize::from_logical(logical_size, dpi_factor)); - let min_size = attributes.min_dimensions - .map(|logical_size| PhysicalSize::from_logical(logical_size, dpi_factor)); - let mut window_state = events_loop::WindowState { - cursor: Cursor(winuser::IDC_ARROW), // use arrow by default - cursor_grabbed: false, - cursor_hidden: false, - max_size, - min_size, - mouse_in_window: false, - saved_window_info: None, - dpi_factor, - fullscreen: attributes.fullscreen.clone(), - window_icon, - taskbar_icon, - decorations: attributes.decorations, - maximized: attributes.maximized, - resizable: attributes.resizable, - always_on_top: attributes.always_on_top, - }; - // Creating a mutex to track the current window state - Arc::new(Mutex::new(window_state)) - }; - - // making the window transparent - if attributes.transparent && !pl_attribs.no_redirection_bitmap { - let region = CreateRectRgn(0, 0, -1, -1); // makes the window transparent - - let bb = dwmapi::DWM_BLURBEHIND { - dwFlags: dwmapi::DWM_BB_ENABLE | dwmapi::DWM_BB_BLURREGION, - fEnable: 1, - hRgnBlur: region, - fTransitionOnMaximized: 0, - }; - - dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb); - DeleteObject(region as _); - - if attributes.decorations { - // HACK: When opaque (opacity 255), there is a trail whenever - // the transparent window is moved. By reducing it to 254, - // the window is rendered properly. - let opacity = 254; - - // The color key can be any value except for black (0x0). - let color_key = 0x0030c100; - - winuser::SetLayeredWindowAttributes(real_window.0, color_key, opacity, winuser::LWA_ALPHA); - } - } - - let win = Window { - window: real_window, - window_state, - events_loop_proxy, - }; - - win.set_maximized(attributes.maximized); - if let Some(_) = attributes.fullscreen { - win.set_fullscreen(attributes.fullscreen); - force_window_active(win.window.0); - } - - inserter.insert(win.window.0, win.window_state.clone()); - - Ok(win) -} - -unsafe fn register_window_class( - window_icon: &Option, - taskbar_icon: &Option, -) -> Vec { - let class_name: Vec<_> = OsStr::new("Window Class") - .encode_wide() - .chain(Some(0).into_iter()) - .collect(); - - let h_icon = taskbar_icon - .as_ref() - .map(|icon| icon.handle) - .unwrap_or(ptr::null_mut()); - let h_icon_small = window_icon - .as_ref() - .map(|icon| icon.handle) - .unwrap_or(ptr::null_mut()); - - let class = winuser::WNDCLASSEXW { - cbSize: mem::size_of::() as UINT, - style: winuser::CS_HREDRAW | winuser::CS_VREDRAW | winuser::CS_OWNDC, - lpfnWndProc: Some(events_loop::callback), - cbClsExtra: 0, - cbWndExtra: 0, - hInstance: libloaderapi::GetModuleHandleW(ptr::null()), - hIcon: h_icon, - hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly - hbrBackground: ptr::null_mut(), - lpszMenuName: ptr::null(), - lpszClassName: class_name.as_ptr(), - hIconSm: h_icon_small, - }; - - // We ignore errors because registering the same window class twice would trigger - // an error, and because errors here are detected during CreateWindowEx anyway. - // Also since there is no weird element in the struct, there is no reason for this - // call to fail. - winuser::RegisterClassExW(&class); - - class_name -} - -struct ComInitialized(*mut ()); -impl Drop for ComInitialized { - fn drop(&mut self) { - unsafe { combaseapi::CoUninitialize() }; - } -} - -thread_local!{ - static COM_INITIALIZED: ComInitialized = { - unsafe { - combaseapi::CoInitializeEx(ptr::null_mut(), COINIT_MULTITHREADED); - ComInitialized(ptr::null_mut()) - } - }; - - static TASKBAR_LIST: Cell<*mut ITaskbarList2> = Cell::new(ptr::null_mut()); -} - -pub fn com_initialized() { - COM_INITIALIZED.with(|_| {}); -} - -// Reference Implementation: -// https://github.com/chromium/chromium/blob/f18e79d901f56154f80eea1e2218544285e62623/ui/views/win/fullscreen_handler.cc -// -// As per MSDN marking the window as fullscreen should ensure that the -// taskbar is moved to the bottom of the Z-order when the fullscreen window -// is activated. If the window is not fullscreen, the Shell falls back to -// heuristics to determine how the window should be treated, which means -// that it could still consider the window as fullscreen. :( -unsafe fn mark_fullscreen(handle: HWND, fullscreen: bool) { - com_initialized(); - - TASKBAR_LIST.with(|task_bar_list_ptr| { - let mut task_bar_list = task_bar_list_ptr.get(); - - if task_bar_list == ptr::null_mut() { - use winapi::shared::winerror::S_OK; - use winapi::Interface; - - let hr = combaseapi::CoCreateInstance( - &CLSID_TaskbarList, - ptr::null_mut(), - combaseapi::CLSCTX_ALL, - &ITaskbarList2::uuidof(), - &mut task_bar_list as *mut _ as *mut _, - ); - - if hr != S_OK || (*task_bar_list).HrInit() != S_OK { - // In some old windows, the taskbar object could not be created, we just ignore it - return; - } - task_bar_list_ptr.set(task_bar_list) - } - - task_bar_list = task_bar_list_ptr.get(); - (*task_bar_list).MarkFullscreenWindow(handle, if fullscreen { 1 } else { 0 }); - }) -} - -unsafe fn force_window_active(handle: HWND) { - // In some situation, calling SetForegroundWindow could not bring up the window, - // This is a little hack which can "steal" the foreground window permission - // We only call this function in the window creation, so it should be fine. - // See : https://stackoverflow.com/questions/10740346/setforegroundwindow-only-working-while-visual-studio-is-open - let alt_sc = winuser::MapVirtualKeyW(winuser::VK_MENU as _, winuser::MAPVK_VK_TO_VSC); - - let mut inputs: [winuser::INPUT; 2] = mem::zeroed(); - inputs[0].type_ = winuser::INPUT_KEYBOARD; - inputs[0].u.ki_mut().wVk = winuser::VK_LMENU as _; - inputs[0].u.ki_mut().wScan = alt_sc as _; - inputs[0].u.ki_mut().dwFlags = winuser::KEYEVENTF_EXTENDEDKEY; - - inputs[1].type_ = winuser::INPUT_KEYBOARD; - inputs[1].u.ki_mut().wVk = winuser::VK_LMENU as _; - inputs[1].u.ki_mut().wScan = alt_sc as _; - inputs[1].u.ki_mut().dwFlags = winuser::KEYEVENTF_EXTENDEDKEY | winuser::KEYEVENTF_KEYUP; - - // Simulate a key press and release - winuser::SendInput( - inputs.len() as _, - inputs.as_mut_ptr(), - mem::size_of::() as _, - ); - - winuser::SetForegroundWindow(handle); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/window.rs b/third_party/cargo/vendor/winit-0.18.1/src/window.rs deleted file mode 100644 index cf36044..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/src/window.rs +++ /dev/null @@ -1,494 +0,0 @@ -use std::collections::vec_deque::IntoIter as VecDequeIter; - -use { - CreationError, - EventsLoop, - Icon, - LogicalPosition, - LogicalSize, - MouseCursor, - PhysicalPosition, - PhysicalSize, - platform, - Window, - WindowBuilder, - WindowId, -}; - -impl WindowBuilder { - /// Initializes a new `WindowBuilder` with default values. - #[inline] - pub fn new() -> WindowBuilder { - WindowBuilder { - window: Default::default(), - platform_specific: Default::default(), - } - } - - /// Requests the window to be of specific dimensions. - #[inline] - pub fn with_dimensions(mut self, size: LogicalSize) -> WindowBuilder { - self.window.dimensions = Some(size); - self - } - - /// Sets a minimum dimension size for the window - #[inline] - pub fn with_min_dimensions(mut self, min_size: LogicalSize) -> WindowBuilder { - self.window.min_dimensions = Some(min_size); - self - } - - /// Sets a maximum dimension size for the window - #[inline] - pub fn with_max_dimensions(mut self, max_size: LogicalSize) -> WindowBuilder { - self.window.max_dimensions = Some(max_size); - self - } - - /// Sets whether the window is resizable or not - /// - /// Note that making the window unresizable doesn't exempt you from handling `Resized`, as that event can still be - /// triggered by DPI scaling, entering fullscreen mode, etc. - /// - /// ## Platform-specific - /// - /// This only has an effect on desktop platforms. - /// - /// Due to a bug in XFCE, this has no effect on Xfwm. - #[inline] - pub fn with_resizable(mut self, resizable: bool) -> WindowBuilder { - self.window.resizable = resizable; - self - } - - /// Requests a specific title for the window. - #[inline] - pub fn with_title>(mut self, title: T) -> WindowBuilder { - self.window.title = title.into(); - self - } - - /// Sets the window fullscreen state. None means a normal window, Some(MonitorId) - /// means a fullscreen window on that specific monitor - #[inline] - pub fn with_fullscreen(mut self, monitor: Option) -> WindowBuilder { - self.window.fullscreen = monitor; - self - } - - /// Requests maximized mode. - #[inline] - pub fn with_maximized(mut self, maximized: bool) -> WindowBuilder { - self.window.maximized = maximized; - self - } - - /// Sets whether the window will be initially hidden or visible. - #[inline] - pub fn with_visibility(mut self, visible: bool) -> WindowBuilder { - self.window.visible = visible; - self - } - - /// Sets whether the background of the window should be transparent. - #[inline] - pub fn with_transparency(mut self, transparent: bool) -> WindowBuilder { - self.window.transparent = transparent; - self - } - - /// Sets whether the window should have a border, a title bar, etc. - #[inline] - pub fn with_decorations(mut self, decorations: bool) -> WindowBuilder { - self.window.decorations = decorations; - self - } - - /// Sets whether or not the window will always be on top of other windows. - #[inline] - pub fn with_always_on_top(mut self, always_on_top: bool) -> WindowBuilder { - self.window.always_on_top = always_on_top; - self - } - - /// Sets the window icon. On Windows and X11, this is typically the small icon in the top-left - /// corner of the titlebar. - /// - /// ## Platform-specific - /// - /// This only has an effect on Windows and X11. - /// - /// On Windows, this sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's - /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. - /// - /// X11 has no universal guidelines for icon sizes, so you're at the whims of the WM. That - /// said, it's usually in the same ballpark as on Windows. - #[inline] - pub fn with_window_icon(mut self, window_icon: Option) -> WindowBuilder { - self.window.window_icon = window_icon; - self - } - - /// Enables multitouch. - #[inline] - pub fn with_multitouch(mut self) -> WindowBuilder { - self.window.multitouch = true; - self - } - - /// Builds the window. - /// - /// Error should be very rare and only occur in case of permission denied, incompatible system, - /// out of memory, etc. - #[inline] - pub fn build(mut self, events_loop: &EventsLoop) -> Result { - self.window.dimensions = Some(self.window.dimensions.unwrap_or_else(|| { - if let Some(ref monitor) = self.window.fullscreen { - // resizing the window to the dimensions of the monitor when fullscreen - LogicalSize::from_physical(monitor.get_dimensions(), 1.0) - } else { - // default dimensions - (1024, 768).into() - } - })); - - // building - platform::Window::new( - &events_loop.events_loop, - self.window, - self.platform_specific, - ).map(|window| Window { window }) - } -} - -impl Window { - /// Creates a new Window for platforms where this is appropriate. - /// - /// This function is equivalent to `WindowBuilder::new().build(events_loop)`. - /// - /// Error should be very rare and only occur in case of permission denied, incompatible system, - /// out of memory, etc. - #[inline] - pub fn new(events_loop: &EventsLoop) -> Result { - let builder = WindowBuilder::new(); - builder.build(events_loop) - } - - /// Modifies the title of the window. - /// - /// This is a no-op if the window has already been closed. - #[inline] - pub fn set_title(&self, title: &str) { - self.window.set_title(title) - } - - /// Shows the window if it was hidden. - /// - /// ## Platform-specific - /// - /// - Has no effect on Android - /// - #[inline] - pub fn show(&self) { - self.window.show() - } - - /// Hides the window if it was visible. - /// - /// ## Platform-specific - /// - /// - Has no effect on Android - /// - #[inline] - pub fn hide(&self) { - self.window.hide() - } - - /// Returns the position of the top-left hand corner of the window relative to the - /// top-left hand corner of the desktop. - /// - /// Note that the top-left hand corner of the desktop is not necessarily the same as - /// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner - /// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop. - /// - /// The coordinates can be negative if the top-left hand corner of the window is outside - /// of the visible screen region. - /// - /// Returns `None` if the window no longer exists. - #[inline] - pub fn get_position(&self) -> Option { - self.window.get_position() - } - - /// Returns the position of the top-left hand corner of the window's client area relative to the - /// top-left hand corner of the desktop. - /// - /// The same conditions that apply to `get_position` apply to this method. - #[inline] - pub fn get_inner_position(&self) -> Option { - self.window.get_inner_position() - } - - /// Modifies the position of the window. - /// - /// See `get_position` for more information about the coordinates. - /// - /// This is a no-op if the window has already been closed. - #[inline] - pub fn set_position(&self, position: LogicalPosition) { - self.window.set_position(position) - } - - /// Returns the logical size of the window's client area. - /// - /// The client area is the content of the window, excluding the title bar and borders. - /// - /// Converting the returned `LogicalSize` to `PhysicalSize` produces the size your framebuffer should be. - /// - /// Returns `None` if the window no longer exists. - #[inline] - pub fn get_inner_size(&self) -> Option { - self.window.get_inner_size() - } - - /// Returns the logical size of the entire window. - /// - /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), - /// use `get_inner_size` instead. - /// - /// Returns `None` if the window no longer exists. - #[inline] - pub fn get_outer_size(&self) -> Option { - self.window.get_outer_size() - } - - /// Modifies the inner size of the window. - /// - /// See `get_inner_size` for more information about the values. - /// - /// This is a no-op if the window has already been closed. - #[inline] - pub fn set_inner_size(&self, size: LogicalSize) { - self.window.set_inner_size(size) - } - - /// Sets a minimum dimension size for the window. - #[inline] - pub fn set_min_dimensions(&self, dimensions: Option) { - self.window.set_min_dimensions(dimensions) - } - - /// Sets a maximum dimension size for the window. - #[inline] - pub fn set_max_dimensions(&self, dimensions: Option) { - self.window.set_max_dimensions(dimensions) - } - - /// Sets whether the window is resizable or not. - /// - /// Note that making the window unresizable doesn't exempt you from handling `Resized`, as that event can still be - /// triggered by DPI scaling, entering fullscreen mode, etc. - /// - /// ## Platform-specific - /// - /// This only has an effect on desktop platforms. - /// - /// Due to a bug in XFCE, this has no effect on Xfwm. - #[inline] - pub fn set_resizable(&self, resizable: bool) { - self.window.set_resizable(resizable) - } - - /// Returns the DPI factor that can be used to map logical pixels to physical pixels, and vice versa. - /// - /// See the [`dpi`](dpi/index.html) module for more information. - /// - /// Note that this value can change depending on user action (for example if the window is - /// moved to another screen); as such, tracking `WindowEvent::HiDpiFactorChanged` events is - /// the most robust way to track the DPI you need to use to draw. - /// - /// ## Platform-specific - /// - /// - **X11:** Can be overridden using the `WINIT_HIDPI_FACTOR` environment variable. - /// - **Android:** Always returns 1.0. - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.window.get_hidpi_factor() - } - - /// Modifies the mouse cursor of the window. - /// Has no effect on Android. - #[inline] - pub fn set_cursor(&self, cursor: MouseCursor) { - self.window.set_cursor(cursor); - } - - /// Changes the position of the cursor in window coordinates. - #[inline] - pub fn set_cursor_position(&self, position: LogicalPosition) -> Result<(), String> { - self.window.set_cursor_position(position) - } - - /// Grabs the cursor, preventing it from leaving the window. - /// - /// ## Platform-specific - /// - /// On macOS, this presently merely locks the cursor in a fixed location, which looks visually awkward. - /// - /// This has no effect on Android or iOS. - #[inline] - pub fn grab_cursor(&self, grab: bool) -> Result<(), String> { - self.window.grab_cursor(grab) - } - - /// Hides the cursor, making it invisible but still usable. - /// - /// ## Platform-specific - /// - /// On Windows and X11, the cursor is only hidden within the confines of the window. - /// - /// On macOS, the cursor is hidden as long as the window has input focus, even if the cursor is outside of the - /// window. - /// - /// This has no effect on Android or iOS. - #[inline] - pub fn hide_cursor(&self, hide: bool) { - self.window.hide_cursor(hide) - } - - /// Sets the window to maximized or back - #[inline] - pub fn set_maximized(&self, maximized: bool) { - self.window.set_maximized(maximized) - } - - /// Sets the window to fullscreen or back - #[inline] - pub fn set_fullscreen(&self, monitor: Option) { - self.window.set_fullscreen(monitor) - } - - /// Turn window decorations on or off. - #[inline] - pub fn set_decorations(&self, decorations: bool) { - self.window.set_decorations(decorations) - } - - /// Change whether or not the window will always be on top of other windows. - #[inline] - pub fn set_always_on_top(&self, always_on_top: bool) { - self.window.set_always_on_top(always_on_top) - } - - /// Sets the window icon. On Windows and X11, this is typically the small icon in the top-left - /// corner of the titlebar. - /// - /// For more usage notes, see `WindowBuilder::with_window_icon`. - /// - /// ## Platform-specific - /// - /// This only has an effect on Windows and X11. - #[inline] - pub fn set_window_icon(&self, window_icon: Option) { - self.window.set_window_icon(window_icon) - } - - /// Sets location of IME candidate box in client area coordinates relative to the top left. - #[inline] - pub fn set_ime_spot(&self, position: LogicalPosition) { - self.window.set_ime_spot(position) - } - - /// Returns the monitor on which the window currently resides - #[inline] - pub fn get_current_monitor(&self) -> MonitorId { - self.window.get_current_monitor() - } - - /// Returns the list of all the monitors available on the system. - /// - /// This is the same as `EventsLoop::get_available_monitors`, and is provided for convenience. - #[inline] - pub fn get_available_monitors(&self) -> AvailableMonitorsIter { - let data = self.window.get_available_monitors(); - AvailableMonitorsIter { data: data.into_iter() } - } - - /// Returns the primary monitor of the system. - /// - /// This is the same as `EventsLoop::get_primary_monitor`, and is provided for convenience. - #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId { inner: self.window.get_primary_monitor() } - } - - #[inline] - pub fn id(&self) -> WindowId { - WindowId(self.window.id()) - } -} - -/// An iterator for the list of available monitors. -// Implementation note: we retrieve the list once, then serve each element by one by one. -// This may change in the future. -#[derive(Debug)] -pub struct AvailableMonitorsIter { - pub(crate) data: VecDequeIter, -} - -impl Iterator for AvailableMonitorsIter { - type Item = MonitorId; - - #[inline] - fn next(&mut self) -> Option { - self.data.next().map(|id| MonitorId { inner: id }) - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.data.size_hint() - } -} - -/// Identifier for a monitor. -#[derive(Debug, Clone)] -pub struct MonitorId { - pub(crate) inner: platform::MonitorId -} - -impl MonitorId { - /// Returns a human-readable name of the monitor. - /// - /// Returns `None` if the monitor doesn't exist anymore. - #[inline] - pub fn get_name(&self) -> Option { - self.inner.get_name() - } - - /// Returns the monitor's resolution. - #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { - self.inner.get_dimensions() - } - - /// Returns the top-left corner position of the monitor relative to the larger full - /// screen area. - #[inline] - pub fn get_position(&self) -> PhysicalPosition { - self.inner.get_position() - } - - /// Returns the DPI factor that can be used to map logical pixels to physical pixels, and vice versa. - /// - /// See the [`dpi`](dpi/index.html) module for more information. - /// - /// ## Platform-specific - /// - /// - **X11:** Can be overridden using the `WINIT_HIDPI_FACTOR` environment variable. - /// - **Android:** Always returns 1.0. - #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.inner.get_hidpi_factor() - } -} diff --git a/third_party/cargo/vendor/winit-0.18.1/tests/send_objects.rs b/third_party/cargo/vendor/winit-0.18.1/tests/send_objects.rs deleted file mode 100644 index f3328c1..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/tests/send_objects.rs +++ /dev/null @@ -1,23 +0,0 @@ -extern crate winit; - -fn needs_send() {} - -#[test] -fn events_loop_proxy_send() { - // ensures that `winit::EventsLoopProxy` implements `Send` - needs_send::(); -} - -#[test] -fn window_send() { - // ensures that `winit::Window` implements `Send` - needs_send::(); -} - -#[test] -fn ids_send() { - // ensures that the various `..Id` types implement `Send` - needs_send::(); - needs_send::(); - needs_send::(); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/tests/serde_objects.rs b/third_party/cargo/vendor/winit-0.18.1/tests/serde_objects.rs deleted file mode 100644 index b5a4963..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/tests/serde_objects.rs +++ /dev/null @@ -1,39 +0,0 @@ -#![cfg(feature = "serde")] - -extern crate serde; -extern crate winit; - -use winit::{ControlFlow, MouseCursor}; -use winit::{ - KeyboardInput, TouchPhase, ElementState, MouseButton, MouseScrollDelta, VirtualKeyCode, - ModifiersState -}; -use winit::dpi::{LogicalPosition, PhysicalPosition, LogicalSize, PhysicalSize}; -use serde::{Serialize, Deserialize}; - -fn needs_serde>() {} - -#[test] -fn root_serde() { - needs_serde::(); - needs_serde::(); -} - -#[test] -fn events_serde() { - needs_serde::(); - needs_serde::(); - needs_serde::(); - needs_serde::(); - needs_serde::(); - needs_serde::(); - needs_serde::(); -} - -#[test] -fn dpi_serde() { - needs_serde::(); - needs_serde::(); - needs_serde::(); - needs_serde::(); -} diff --git a/third_party/cargo/vendor/winit-0.18.1/tests/sync_object.rs b/third_party/cargo/vendor/winit-0.18.1/tests/sync_object.rs deleted file mode 100644 index eb9a06e..0000000 --- a/third_party/cargo/vendor/winit-0.18.1/tests/sync_object.rs +++ /dev/null @@ -1,9 +0,0 @@ -extern crate winit; - -fn needs_sync() {} - -#[test] -fn window_sync() { - // ensures that `winit::Window` implements `Sync` - needs_sync::(); -} diff --git a/third_party/cargo/vendor/winit-0.22.0/.cargo-checksum.json b/third_party/cargo/vendor/winit-0.22.0/.cargo-checksum.json new file mode 100644 index 0000000..922ef8c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"5e2d2ce054ef2df03efcb31cf2e0aa50ff3c6ab0389c38098e9099490e9f507c","CONTRIBUTING.md":"807157c17d40bbc6e03670e133863624da2ce0df242aeb22e0279d9a14f613c9","Cargo.lock":"2633fee953c2b5cda9902fbfd78f989eef3a95a64ec3ce224da664b346bfbbd8","Cargo.toml":"c06d72e3ec842773e2b9d99a5c3427cac3332b2b7e4d4c1a786d9869f4c113ad","FEATURES.md":"fdb0dd1fc29add1903746d1e11ca136844ce280cd946411c95d5c8ffc8e111b8","HALL_OF_CHAMPIONS.md":"227425a6ea987c316625b9636ed7d1829f6a2181460655589c0584117442c705","LICENSE":"6dc0e068dcf3a5bc8e054205b85b7720e1d49265bbc64bf515d2cf79197df69a","README.md":"5ce95989172bbc6822bacc8c9cf8592e5fbe90e843d0c53f97691a7c3c281e65","examples/control_flow.rs":"164ab06b2b3fe27607ffe26456ab9b4b4559e95f46b50d31e7f89967dc2e4d38","examples/cursor.rs":"7cceca27c82fb01567dff409e4de3b91595ebccfc2ab6036feb96d826cad9c81","examples/cursor_grab.rs":"9c33e5604fea0dfbcc3b84f27b81f2b09f13cc5160fa306c1627876a956ebbed","examples/custom_events.rs":"fb3e91f941bf963bf8608dc45956ba5164540755900021774d8b5c66d4ebe1ce","examples/fullscreen.rs":"6a89e91ee9bd78a6c8e934ae822b64b9a9d8f4589d84c3d771518a149f53f0a2","examples/handling_close.rs":"3aebc8f2a05a6f1780be260624cf189f92498fc36ece490323af213662b85d15","examples/icon.png":"4340d72fb8b5d95a10e3b2c02230f1060dff0950a137bd1d830c63dbc020dd45","examples/min_max_size.rs":"30fb749ab80050d010e4dd225f9f0f0ecc02f9910485489c87f898c4bb7c088d","examples/minimize.rs":"ea2d7f840b5c4237af819f0fb20a330fda5fe456d33cdec2dd056e1856fa182d","examples/monitor_list.rs":"d20cb662c47cf3c53fba8771e0469f6049fb3fb4c079cb395fd59f04afc4b70c","examples/multithreaded.rs":"4c315461ecd570aa36dfa129f9404fbd651ef31ec4cec3611aa1cded42b137a7","examples/multiwindow.rs":"8731df54cd9027d9a09af46577da3cb97cfd5bec6c9739a75a0688ed54e28b6e","examples/request_redraw.rs":"5e4558c55617185f98d7e633899b613ad095f09da25759798e81eea1d28f0323","examples/request_redraw_threaded.rs":"0310719cb1231914cf2f330b0195db590b6f643d44047e59cf03d5ec0485102a","examples/resizable.rs":"0066757993c8f054f82344832bb24c3894aa7ddf62ae82ce85e6e77aaa7b5c04","examples/timer.rs":"0b51a405ccb08576b9d734b9aaac57b6ba8df1ed85904e1e0d8ddc9f9cefb28e","examples/transparent.rs":"b56b60cccb1c7cc08d7bbb27728a4d4d8742c88b2abc3f89236647f6cc02e5c4","examples/video_modes.rs":"d685e3fba4b1480a07a0c21d9d310471e5ca9a2c2bbfc871b6874b92fe8b7f2c","examples/web.rs":"0e16a92b2466a106cc65ac4cb1b23e61d2b3b5cb8a16d66dd7ec4e311ee1ccdd","examples/window.rs":"cf5e2bcf23299055384d6926ddeac60b2e8de0520bf08734a556fcd3ac511838","examples/window_debug.rs":"9178750d3c631293f944e2720e4e59cff717d642251c9d87d9280f2ee398685d","examples/window_icon.rs":"810ce3b91a595078c09ba657dc23e5da3b4ba514b9ff1701cbd4f94c2b6deaf9","examples/window_run_return.rs":"253c047d3230160676e48d3acb6f4616ded04df2882c61c91a846ef2987ea723","rustfmt.toml":"0f9faac3197a1d133611a48d5c75ed8f381bbeb09112691e0a652f2432bf627f","src/dpi.rs":"53f6989412a174ea8d7e7309c59942997a2e2594118f1a37b9d2e860a78ad842","src/error.rs":"0ffc4b637b93aa0cbeca5767cf98497a1763932f50506f48534ed69b06bb1f9f","src/event.rs":"35e8f19ae9d07b8def245b6b28475d7922fbdbf8a6c67ee8dbb7202091c59379","src/event_loop.rs":"0cb3b437a108f9e27e4d759d03e93ef3439c45148733a1852fc92ced146b01bc","src/icon.rs":"e528da6a04a7e9479d71a97fa5572d6705fea7fb75d37ab80785fd2f25f75ca8","src/lib.rs":"bbd962d1d992cf221253490c33ee3680076dc7acd4a9f01c17f9bd73f36ed22a","src/monitor.rs":"a993f84ba9799f61c4eb1f00effb3513e6e2c13f95c2fc9e1b696a0c06a5107a","src/platform/android.rs":"2f8ca86dd045880deea71b99dcc76efd9de9ebebb37e393552efc326e6f56bfe","src/platform/desktop.rs":"3d294fb1e421033962dff83efab49551bb732786ab14a27d4271128864d9dcdf","src/platform/ios.rs":"050f49d0a19538931fb4555495da75e8c3606de0bb9e3ccec11055d7ed3b88d9","src/platform/macos.rs":"4af86815d4cde9397a3e2c56bb3e458e8ef3f8223280d9546170e49338f11a6f","src/platform/mod.rs":"8b51efb972563581f8a8d244a92f1723609890c4ca0429ba8d4292d159dd0937","src/platform/unix.rs":"faf68532d9ffeaf9e8f364162950732feb8ddfaefa912b486a48029190ec8617","src/platform/web.rs":"22c0075cefc379d2753805cad17f535ecd14bc5a53472ef5d84942ad58d25f49","src/platform/windows.rs":"4ebce126e47d0b5818965dc243988b9ffb88398d4da0bfb86df900bb838e4764","src/platform_impl/android/ffi.rs":"9b80807e62e17c76e929a039c0502d45c429970f5f93518d34b3f7d9cbdaa0d7","src/platform_impl/android/mod.rs":"46e357408f070fe21e43769f99ee8fe6c4bb04e9171382b3b911171906c5e1f5","src/platform_impl/ios/app_state.rs":"e496ec5262fbde8712cf8ab1a699b50cf47cca7e4e3d1d65b45398174c900945","src/platform_impl/ios/event_loop.rs":"b7b76bdd154befff46fe3642862cbffee82989a87588ede0fe21d70b54339b12","src/platform_impl/ios/ffi.rs":"95e200dd49f7630414a85d3161e7fcd941b61d701bb93856af23e88f492b6523","src/platform_impl/ios/mod.rs":"552c2d59bf98ca7fb34ad843dd2b750fe157f038c9a7575b8df9070380d66252","src/platform_impl/ios/monitor.rs":"195218f4d6ddbdef0cccec232317b94c18c99d308e5e56890ba40a5b1301908e","src/platform_impl/ios/view.rs":"7af6c48bf01d5969600cbfcc2c9fe7656ef00b2a5f9c62092ce8649cb50eb0cd","src/platform_impl/ios/window.rs":"bb20144a030fe23758783db4092eb8d27cee57a15a2ce8e4c6460326da210134","src/platform_impl/linux/mod.rs":"35ffd26c3325caadca403470b650f7de103b991592f3956ed9051e32ed68856c","src/platform_impl/linux/wayland/event_loop.rs":"635b409640ccbbe17bf2c33ac5295ab0a1bbee28f0e1c3169a227292c987bcee","src/platform_impl/linux/wayland/keyboard.rs":"54253e9f4d2ede0cf9d19f4f3aa46bb38a3a8623827a96b937b2086a5230c6bf","src/platform_impl/linux/wayland/mod.rs":"62159b2d2ab1dc275e8c92f40b26b9d44497770cb788761870dd9841936d54b1","src/platform_impl/linux/wayland/pointer.rs":"001d6d43d55e9a1c406d946913644e9f4d9e22ae6df2a31477ce06a52006205a","src/platform_impl/linux/wayland/touch.rs":"abe018a8a38445e97cf3f44858216d7d4d23be5aa4e9b075c7eb4931ba8ab5a4","src/platform_impl/linux/wayland/window.rs":"533a6fa523f1aa6670a5f984752ecbf0773a51903f9a25846f4590d717f8c46a","src/platform_impl/linux/x11/dnd.rs":"2c4ed464372e74fb1c0ca81ffdbc81995d4334142195777df4dc3f70c70045b9","src/platform_impl/linux/x11/event_processor.rs":"6c4ae64fc39ca7a0be1217240913c886c1f248c308e5c92f267a081ad6e78d32","src/platform_impl/linux/x11/events.rs":"5ebd5fd236b1840c29da5eda4a1637666a754b11acb7038980c239a3ee238916","src/platform_impl/linux/x11/ffi.rs":"aaa48262584dfdf6ce226ec45cda62a520a191493389278964f4166d89fc5c8d","src/platform_impl/linux/x11/ime/callbacks.rs":"101f0b43d594194db1585f8dec7451f215d8e3406152149e1b7089ec14696dd8","src/platform_impl/linux/x11/ime/context.rs":"0703c16100a63d7b383ec86e26e910489ec868885e4ada9f3302c8e8de466f79","src/platform_impl/linux/x11/ime/inner.rs":"be35f7faed8c97c5f9f7109094ce1c0b12d54fcc674fe3fb37caff0ed9e71c3e","src/platform_impl/linux/x11/ime/input_method.rs":"d79f186798940014f08d4dbc04c40acf45932f9f87326cf96e923d575e9a6f57","src/platform_impl/linux/x11/ime/mod.rs":"8cca51bd04eb551e1e079f806028710f8b2944d70c42ceb783490a9f1d0d6dfe","src/platform_impl/linux/x11/mod.rs":"c33a3a260f13947c42de7906103faa24ff56d8a903258437baba3bfcd889fa59","src/platform_impl/linux/x11/monitor.rs":"77351a74b3603d58dec99745e1289c1fd731bb8d32119345fa37bc3a2ac0c30e","src/platform_impl/linux/x11/util/atom.rs":"df0bb8966f752456ecf9808fea9ae3124d50bb1aa9a300b1828781c6f8834f54","src/platform_impl/linux/x11/util/client_msg.rs":"0ee4ff5f1511888223d4f606220e206ecd7fb317dca6e1dcc8913fdba6ea8ef6","src/platform_impl/linux/x11/util/cursor.rs":"a61585fdd4d2f5d94eedc3e7760f579525d3b246be99258ce7ef7fecd6c8f053","src/platform_impl/linux/x11/util/format.rs":"49bfbb625f6261b004fccd8cfa53d88fe34b6f48987e22d8d82a7a0643ac3b2e","src/platform_impl/linux/x11/util/geometry.rs":"42c6f83586ca7acc4a745bd5c1c3dfce97ecf2ad49f1f81ec598bff9ef570d51","src/platform_impl/linux/x11/util/hint.rs":"d7a0a314108703a47fd564055b58848d9864e43d19944dc59cb3f222894897c7","src/platform_impl/linux/x11/util/icon.rs":"e17832043b4f0368ba45b4b804e2de9dcf921ce73e1d5c97f0a7be5d4312512c","src/platform_impl/linux/x11/util/input.rs":"57792d4bd3a03cfdf7ac077ea022fb46c331402f1c3d089f41f70ee292cdd6b1","src/platform_impl/linux/x11/util/keys.rs":"c983b6abb47f4f1abc64e155dde1edc2393acdd9629ef7a94287493dfa22af35","src/platform_impl/linux/x11/util/memory.rs":"ad76a43ad3fbc7d4c0501c387cab7f385d3ca6c346fc0d1e6b9d918365b63d47","src/platform_impl/linux/x11/util/mod.rs":"e90d53cd3dc80ac20bb4a450b17d04819c07f95b8aca0095f468474d118dd8ef","src/platform_impl/linux/x11/util/modifiers.rs":"65ef5a4864b94e28ed136ceec268bf10a3bc498b9a87fbb06ec1a2f250ce9596","src/platform_impl/linux/x11/util/randr.rs":"4605451b814a42c44d72f4058a3f922074d6fcdbe7dd7f6e23cad2807aaef862","src/platform_impl/linux/x11/util/window_property.rs":"a563550cad6d8fffe2666d2238981f6b34f3a69b99df1d9196c67952e71dc59e","src/platform_impl/linux/x11/util/wm.rs":"f821962c8ac739cb3f3d937d3558a045ebeba5ab5abc2cb4c7fe7aadc99b583a","src/platform_impl/linux/x11/window.rs":"84c8c38afda36a354b7b06e2312354962fe4b56449c49ab1b48f10b7d5234472","src/platform_impl/linux/x11/xdisplay.rs":"6a8ecd2dcea3ba3cb1e6ea7a97edc53eea3ca9fe72e6a93be98c3e66265fdf88","src/platform_impl/macos/activation_hack.rs":"502c0d39546e0420797ea0996ad6d52cf44a35bb4abebd3fcc5168d7a4dda03e","src/platform_impl/macos/app.rs":"3fbef969e7c378260d8e5f93ec0b588a6a4bf48fa1c7b6c180c978d21028a1cf","src/platform_impl/macos/app_delegate.rs":"abd26f7bb3e48a42bd7bcada71a4527fb2e2cf8a794eea5765440b9f4ae4a810","src/platform_impl/macos/app_state.rs":"0d1deb577c42575f8fee147c6fede194c7ac86e3e8f48924945cba13740b0889","src/platform_impl/macos/event.rs":"2b7036f9cfc3209ce23397891ec7d042c03fe9d29eab645601ab321d0537a1b5","src/platform_impl/macos/event_loop.rs":"2dc4b41355de02456e4da312ade7eceb3978bdee19cb8765cc37f14766f7cb74","src/platform_impl/macos/ffi.rs":"fd9e4e1b59d0db8ee0a509e9b40dfc42ab1fc5a9d3c3075d6147fbb09d180304","src/platform_impl/macos/mod.rs":"9d4e9d8dc956cb84b8240736f3d6cf2cdc5771674f76eb91dc0c8f8fefca76fb","src/platform_impl/macos/monitor.rs":"c2d836ccdb555f668139f33912c3c25ed6f2128d536400c27538da9d4be8d653","src/platform_impl/macos/observer.rs":"2b70ae0ca3c6c7e59535490f9095289a58f8e6e261c79df919f3f9adf39d47ed","src/platform_impl/macos/util/async.rs":"62db903be455d4822537dbfd36c2a1bc79fa34ef90d0e2d175f31b4dcfd92553","src/platform_impl/macos/util/cursor.rs":"f82bb7153988494df286b494b3d7df1a4e4f6805e442b42d27ad80b17a8e302e","src/platform_impl/macos/util/mod.rs":"a5eb611636cf0dc2dc32e0fb0fe3204e8d130aa8d0d77a6fbe493252815ce48a","src/platform_impl/macos/view.rs":"b058b1bc03623dd6b578dc4284d8ce0ae7a9f6f6df767b9d9b88e4000a06fca1","src/platform_impl/macos/window.rs":"b9f8fed76c9fe44057649adbe6abde6dc4ea168545e582ffc0ce2567c802a79b","src/platform_impl/macos/window_delegate.rs":"ef5b4fea873148692ae7ea7571cf35426adb2aa3d1b653d44d9bdcb66ad43d84","src/platform_impl/mod.rs":"5377259da98f6a7361d011a537d12a642361c12e04d60c61260229031d417042","src/platform_impl/web/device.rs":"d9635428690cf87bd1447c9550ac62332b7e47c284515d1d2a0c3f6d3a60a354","src/platform_impl/web/error.rs":"aa81b02160abb8707f5420d373ce9fd664f3255fedb49982f8539caf3a5e6083","src/platform_impl/web/event_loop/mod.rs":"b7bbb9093723a0d2a47faecaad67cd932272dcf83042b7a3d47c57ceb1a9fbe7","src/platform_impl/web/event_loop/proxy.rs":"0098dbf3b984cb3af0b17e1167373e422cb3cd2c38f06942c1145d77f4dda364","src/platform_impl/web/event_loop/runner.rs":"283a0429c1a427067df4edc8eef4cfe8e053c0b20b20ca5dd6e1a83f00342d56","src/platform_impl/web/event_loop/state.rs":"6cc95efd5ce48ce68b439333404f3df67b27e705e5a17badbfa12b0279aa71ad","src/platform_impl/web/event_loop/window_target.rs":"cd73979af80d756e176e39d7f2069a8927c8ee8c908996c1e2440e338ede1f30","src/platform_impl/web/mod.rs":"7df7314766f2b3e59214026f27686bdaefe69e0bff9e85452eb8bbf3d0593d57","src/platform_impl/web/monitor.rs":"41d50275687bed6ac302e27e7407be81e85194547e4634b1a8dde6eca2b9dd5e","src/platform_impl/web/stdweb/canvas.rs":"d876491cf38381dd328a394065b8e2e7e61a1a9c7e1c75fe279b4ba4eb82a928","src/platform_impl/web/stdweb/event.rs":"1bb2214ddbfb4a26abf5a3373de04e0824122f5845839867138b4dbbb60200fa","src/platform_impl/web/stdweb/mod.rs":"24fae9db8316a07b355ec3a9cfe1454f0b4e6f04a8ecac4c8a466ff8031e2cb7","src/platform_impl/web/stdweb/timeout.rs":"c2e7689edd275177f49e1c91494fff883cde3f4819cde78a83d853c307a4f1ca","src/platform_impl/web/web_sys/canvas.rs":"d6fc3241bf237d76b5079233b519718f73e7bec2101f033d9d0415ad91aed0e4","src/platform_impl/web/web_sys/event.rs":"df3a7c1beb473183457586b88a29786b037dd6539c32c761472071432c836c41","src/platform_impl/web/web_sys/mod.rs":"1f0c58c6d77bd86aeddfcb16ef2a329f1574cdde1ff4b3e5a5837e63e041e80b","src/platform_impl/web/web_sys/timeout.rs":"976232bf08963196dea2e360a011f63d338e6222398d5175ffcb002b06e9d890","src/platform_impl/web/window.rs":"95f187b66fb94c1a0926b2ffe7f23a812f9584165d93cc69267fb9a4693132f0","src/platform_impl/windows/dark_mode.rs":"06705f3f703675c6c2ee380cbf217e03b11bff58dc8ab109838adb0245a083e6","src/platform_impl/windows/dpi.rs":"fdfbdecfce8c7f63ae0ca580d9f075e14bf4b03c10cd622b576a5ad11110f632","src/platform_impl/windows/drop_handler.rs":"a5c53f4d285401dba669e8296e03265f8439781fb1510f7cdd7d050232f3c674","src/platform_impl/windows/event.rs":"7523ff182908c83ef0d89c20b3e2b2fce685514973fe1fd058901a41afbd0da2","src/platform_impl/windows/event_loop.rs":"5741b4074bc25cdbe8b609fb1004dbd6bb5fdd8d6faa821f99d2e2eef984a21d","src/platform_impl/windows/event_loop/runner.rs":"86b06161dfb5b10b3c844015dadc053ae39558f736b43c12e83d69f00ec02b29","src/platform_impl/windows/icon.rs":"876a1a45f9a497058dcb2a9f64661df9735b690b7b33bd7ef4b2197e6c00e24b","src/platform_impl/windows/mod.rs":"a124b9074c36ef3d65b9667ed9d7658bd9f45f74d33545f6af0c062f90208054","src/platform_impl/windows/monitor.rs":"a23e056dd0b216de12ca873e2ae91291d92a0f35c3206d39dab58d7cce063a59","src/platform_impl/windows/raw_input.rs":"1e13aeec77249e971d51e02fa53fd3bcd6d90cbe8bf5e59f8986d3676fb1d0b1","src/platform_impl/windows/util.rs":"939e0719b20237c3a671027fc0606c70bbdf46e2fc2dc2dc93c8583dd94c7b0e","src/platform_impl/windows/window.rs":"6091627f3c96ca84c814e05ae966e39bc740c0c21d85d712afa7c088258719fb","src/platform_impl/windows/window_state.rs":"8821d769a890022eeb760507ed9e5aba885b1a42390309cfd6875daed9fbdec0","src/window.rs":"037f66b61cfc4894509b0f05cdd45e68c692c1689e5e7686274df8ed6c5809ef","tests/send_objects.rs":"bf91aea7a2506d2d2953c30576b4f24a53e39b82cba4c8feb84daea12569a1bb","tests/serde_objects.rs":"160cd2acc4fd1c6cf1ff98b2b2f5fda2a34d892806d7fd21c9ba25007f29e184","tests/sync_object.rs":"6546a1dd2c6fccf1c7049f035a7993edf475d3fe0d43d4aac0d9c3ca049766cc"},"package":"02e9092b71b48ad6a0d98835a786308d10760cc09369d02e4a166608327f1f26"} \ No newline at end of file diff --git a/third_party/cargo/vendor/winit-0.18.1/BUILD b/third_party/cargo/vendor/winit-0.22.0/BUILD similarity index 58% rename from third_party/cargo/vendor/winit-0.18.1/BUILD rename to third_party/cargo/vendor/winit-0.22.0/BUILD index 951e68b..bae73ba 100644 --- a/third_party/cargo/vendor/winit-0.18.1/BUILD +++ b/third_party/cargo/vendor/winit-0.22.0/BUILD @@ -23,42 +23,57 @@ load( ) +# Unsupported target "control_flow" with type "example" omitted # Unsupported target "cursor" with type "example" omitted # Unsupported target "cursor_grab" with type "example" omitted +# Unsupported target "custom_events" with type "example" omitted # Unsupported target "fullscreen" with type "example" omitted # Unsupported target "handling_close" with type "example" omitted # Unsupported target "min_max_size" with type "example" omitted +# Unsupported target "minimize" with type "example" omitted # Unsupported target "monitor_list" with type "example" omitted +# Unsupported target "multithreaded" with type "example" omitted # Unsupported target "multiwindow" with type "example" omitted -# Unsupported target "proxy" with type "example" omitted +# Unsupported target "request_redraw" with type "example" omitted +# Unsupported target "request_redraw_threaded" with type "example" omitted # Unsupported target "resizable" with type "example" omitted # Unsupported target "send_objects" with type "test" omitted # Unsupported target "serde_objects" with type "test" omitted # Unsupported target "sync_object" with type "test" omitted +# Unsupported target "timer" with type "example" omitted # Unsupported target "transparent" with type "example" omitted +# Unsupported target "video_modes" with type "example" omitted +# Unsupported target "web" with type "example" omitted # Unsupported target "window" with type "example" omitted +# Unsupported target "window_debug" with type "example" omitted # Unsupported target "window_icon" with type "example" omitted +# Unsupported target "window_run_return" with type "example" omitted rust_library( name = "winit", crate_root = "src/lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ + "//third_party/cargo/vendor/bitflags-1.2.1:bitflags", + "//third_party/cargo/vendor/instant-0.1.2:instant", "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", "//third_party/cargo/vendor/libc-0.2.67:libc", "//third_party/cargo/vendor/log-0.4.8:log", - "//third_party/cargo/vendor/parking_lot-0.7.1:parking_lot", - "//third_party/cargo/vendor/percent-encoding-1.0.1:percent_encoding", - "//third_party/cargo/vendor/smithay-client-toolkit-0.4.6:smithay_client_toolkit", - "//third_party/cargo/vendor/wayland-client-0.21.13:wayland_client", + "//third_party/cargo/vendor/mio-0.6.21:mio", + "//third_party/cargo/vendor/mio-extras-2.0.6:mio_extras", + "//third_party/cargo/vendor/parking_lot-0.10.0:parking_lot", + "//third_party/cargo/vendor/percent-encoding-2.1.0:percent_encoding", + "//third_party/cargo/vendor/raw-window-handle-0.3.3:raw_window_handle", + "//third_party/cargo/vendor/smithay-client-toolkit-0.6.6:smithay_client_toolkit", + "//third_party/cargo/vendor/wayland-client-0.23.6:wayland_client", "//third_party/cargo/vendor/x11-dl-2.18.5:x11_dl", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.18.1", + version = "0.22.0", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/winit-0.18.1/CHANGELOG.md b/third_party/cargo/vendor/winit-0.22.0/CHANGELOG.md similarity index 56% rename from third_party/cargo/vendor/winit-0.18.1/CHANGELOG.md rename to third_party/cargo/vendor/winit-0.22.0/CHANGELOG.md index 00b8dc3..8ec38c7 100644 --- a/third_party/cargo/vendor/winit-0.18.1/CHANGELOG.md +++ b/third_party/cargo/vendor/winit-0.22.0/CHANGELOG.md @@ -1,4 +1,269 @@ -# Unreleased +# 0.22.0 (2020-03-07) + +- On Windows, fix minor timing issue in wait_until_time_or_msg +- On Windows, rework handling of request_redraw() to address panics. +- On macOS, fix `set_simple_screen` to remember frame excluding title bar. +- On Wayland, fix coordinates in touch events when scale factor isn't 1. +- On Wayland, fix color from `close_button_icon_color` not applying. +- Ignore locale if unsupported by X11 backend +- On Wayland, Add HiDPI cursor support +- On Web, add the ability to query "Light" or "Dark" system theme send `ThemeChanged` on change. +- Fix `Event::to_static` returning `None` for user events. +- On Wayland, Hide CSD for fullscreen windows. +- On Windows, ignore spurious mouse move messages. +- **Breaking:** Move `ModifiersChanged` variant from `DeviceEvent` to `WindowEvent`. +- On Windows, add `IconExtWindows` trait which exposes creating an `Icon` from an external file or embedded resource +- Add `BadIcon::OsError` variant for when OS icon functionality fails +- On Windows, fix crash at startup on systems that do not properly support Windows' Dark Mode +- Revert On macOS, fix not sending ReceivedCharacter event for specific keys combinations. +- on macOS, fix incorrect ReceivedCharacter events for some key combinations. +- **Breaking:** Use `i32` instead of `u32` for position type in `WindowEvent::Moved`. + +# 0.21.0 (2020-02-04) + +- On Windows, fixed "error: linking with `link.exe` failed: exit code: 1120" error on older versions of windows. +- On macOS, fix set_minimized(true) works only with decorations. +- On macOS, add `hide_application` to `EventLoopWindowTarget` via a new `EventLoopWindowTargetExtMacOS` trait. `hide_application` will hide the entire application by calling `-[NSApplication hide: nil]`. +- On macOS, fix not sending ReceivedCharacter event for specific keys combinations. +- On macOS, fix `CursorMoved` event reporting the cursor position using logical coordinates. +- On macOS, fix issue where unbundled applications would sometimes open without being focused. +- On macOS, fix `run_return` does not return unless it receives a message. +- On Windows, fix bug where `RedrawRequested` would only get emitted every other iteration of the event loop. +- On X11, fix deadlock on window state when handling certain window events. +- `WindowBuilder` now implements `Default`. +- **Breaking:** `WindowEvent::CursorMoved` changed to `f64` units, preserving high-precision data supplied by most backends +- On Wayland, fix coordinates in mouse events when scale factor isn't 1 +- On Web, add the ability to provide a custom canvas +- **Breaking:** On Wayland, the `WaylandTheme` struct has been replaced with a `Theme` trait, allowing for extra configuration + +# 0.20.0 (2020-01-05) + +- On X11, fix `ModifiersChanged` emitting incorrect modifier change events +- **Breaking**: Overhaul how Winit handles DPI: + + Window functions and events now return `PhysicalSize` instead of `LogicalSize`. + + Functions that take `Size` or `Position` types can now take either `Logical` or `Physical` types. + + `hidpi_factor` has been renamed to `scale_factor`. + + `HiDpiFactorChanged` has been renamed to `ScaleFactorChanged`, and lets you control how the OS + resizes the window in response to the change. + + On X11, deprecate `WINIT_HIDPI_FACTOR` environment variable in favor of `WINIT_X11_SCALE_FACTOR`. + + `Size` and `Position` types are now generic over their exact pixel type. + +# 0.20.0 Alpha 6 (2020-01-03) + +- On macOS, fix `set_cursor_visible` hides cursor outside of window. +- On macOS, fix `CursorEntered` and `CursorLeft` events fired at old window size. +- On macOS, fix error when `set_fullscreen` is called during fullscreen transition. +- On all platforms except mobile and WASM, implement `Window::set_minimized`. +- On X11, fix `CursorEntered` event being generated for non-winit windows. +- On macOS, fix crash when starting maximized without decorations. +- On macOS, fix application not terminating on `run_return`. +- On Wayland, fix cursor icon updates on window borders when using CSD. +- On Wayland, under mutter(GNOME Wayland), fix CSD being behind the status bar, when starting window in maximized mode. +- On Windows, theme the title bar according to whether the system theme is "Light" or "Dark". +- Added `WindowEvent::ThemeChanged` variant to handle changes to the system theme. Currently only implemented on Windows. +- **Breaking**: Changes to the `RedrawRequested` event (#1041): + - `RedrawRequested` has been moved from `WindowEvent` to `Event`. + - `EventsCleared` has been renamed to `MainEventsCleared`. + - `RedrawRequested` is now issued only after `MainEventsCleared`. + - `RedrawEventsCleared` is issued after each set of `RedrawRequested` events. +- Implement synthetic window focus key events on Windows. +- **Breaking**: Change `ModifiersState` to a `bitflags` struct. +- On Windows, implement `VirtualKeyCode` translation for `LWin` and `RWin`. +- On Windows, fix closing the last opened window causing `DeviceEvent`s to stop getting emitted. +- On Windows, fix `Window::set_visible` not setting internal flags correctly. This resulted in some weird behavior. +- Add `DeviceEvent::ModifiersChanged`. + - Deprecate `modifiers` fields in other events in favor of `ModifiersChanged`. +- On X11, `WINIT_HIDPI_FACTOR` now dominates `Xft.dpi` when picking DPI factor for output. +- On X11, add special value `randr` for `WINIT_HIDPI_FACTOR` to make winit use self computed DPI factor instead of the one from `Xft.dpi`. + +# 0.20.0 Alpha 5 (2019-12-09) + +- On macOS, fix application termination on `ControlFlow::Exit` +- On Windows, fix missing `ReceivedCharacter` events when Alt is held. +- On macOS, stop emitting private corporate characters in `ReceivedCharacter` events. +- On X11, fix misreporting DPI factor at startup. +- On X11, fix events not being reported when using `run_return`. +- On X11, fix key modifiers being incorrectly reported. +- On X11, fix window creation hanging when another window is fullscreen. +- On Windows, fix focusing unfocused windows when switching from fullscreen to windowed. +- On X11, fix reporting incorrect DPI factor when waking from suspend. +- Change `EventLoopClosed` to contain the original event. +- **Breaking**: Add `is_synthetic` field to `WindowEvent` variant `KeyboardInput`, + indicating that the event is generated by winit. +- On X11, generate synthetic key events for keys held when a window gains or loses focus. +- On X11, issue a `CursorMoved` event when a `Touch` event occurs, + as X11 implicitly moves the cursor for such events. + +# 0.20.0 Alpha 4 (2019-10-18) + +- Add web support via the 'stdweb' or 'web-sys' features +- On Windows, implemented function to get HINSTANCE +- On macOS, implement `run_return`. +- On iOS, fix inverted parameter in `set_prefers_home_indicator_hidden`. +- On X11, performance is improved when rapidly calling `Window::set_cursor_icon`. +- On iOS, fix improper `msg_send` usage that was UB and/or would break if `!` is stabilized. +- On Windows, unset `maximized` when manually changing the window's position or size. +- On Windows, add touch pressure information for touch events. +- On macOS, differentiate between `CursorIcon::Grab` and `CursorIcon::Grabbing`. +- On Wayland, fix event processing sometimes stalling when using OpenGL with vsync. +- Officially remove the Emscripten backend. +- On Windows, fix handling of surrogate pairs when dispatching `ReceivedCharacter`. +- On macOS 10.15, fix freeze upon exiting exclusive fullscreen mode. +- On iOS, fix panic upon closing the app. +- On X11, allow setting mulitple `XWindowType`s. +- On iOS, fix null window on initial `HiDpiFactorChanged` event. +- On Windows, fix fullscreen window shrinking upon getting restored to a normal window. +- On macOS, fix events not being emitted during modal loops, such as when windows are being resized + by the user. +- On Windows, fix hovering the mouse over the active window creating an endless stream of CursorMoved events. +- Always dispatch a `RedrawRequested` event after creating a new window. +- On X11, return dummy monitor data to avoid panicking when no monitors exist. +- On X11, prevent stealing input focus when creating a new window. + Only steal input focus when entering fullscreen mode. +- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced +- On Wayland, add support for set_cursor_visible and set_cursor_grab. +- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced. +- Removed `derivative` crate dependency. +- On Wayland, add support for set_cursor_icon. +- Use `impl Iterator` instead of `AvailableMonitorsIter` consistently. +- On macOS, fix fullscreen state being updated after entering fullscreen instead of before, + resulting in `Window::fullscreen` returning the old state in `Resized` events instead of + reflecting the new fullscreen state +- On X11, fix use-after-free during window creation +- On Windows, disable monitor change keyboard shortcut while in exclusive fullscreen. +- On Windows, ensure that changing a borderless fullscreen window's monitor via keyboard shortcuts keeps the window fullscreen on the new monitor. +- Prevent `EventLoop::new` and `EventLoop::with_user_event` from getting called outside the main thread. + - This is because some platforms cannot run the event loop outside the main thread. Preventing this + reduces the potential for cross-platform compatibility gotchyas. +- On Windows and Linux X11/Wayland, add platform-specific functions for creating an `EventLoop` outside the main thread. +- On Wayland, drop resize events identical to the current window size. +- On Windows, fix window rectangle not getting set correctly on high-DPI systems. + +# 0.20.0 Alpha 3 (2019-08-14) + +- On macOS, drop the run closure on exit. +- On Windows, location of `WindowEvent::Touch` are window client coordinates instead of screen coordinates. +- On X11, fix delayed events after window redraw. +- On macOS, add `WindowBuilderExt::with_disallow_hidpi` to have the option to turn off best resolution openGL surface. +- On Windows, screen saver won't start if the window is in fullscreen mode. +- Change all occurrences of the `new_user_event` method to `with_user_event`. +- On macOS, the dock and the menu bar are now hidden in fullscreen mode. +- `Window::set_fullscreen` now takes `Option` where `Fullscreen` + consists of `Fullscreen::Exclusive(VideoMode)` and + `Fullscreen::Borderless(MonitorHandle)` variants. + - Adds support for exclusive fullscreen mode. +- On iOS, add support for hiding the home indicator. +- On iOS, add support for deferring system gestures. +- On iOS, fix a crash that occurred while acquiring a monitor's name. +- On iOS, fix armv7-apple-ios compile target. +- Removed the `T: Clone` requirement from the `Clone` impl of `EventLoopProxy`. +- On iOS, disable overscan compensation for external displays (removes black + bars surrounding the image). +- On Linux, the functions `is_wayland`, `is_x11`, `xlib_xconnection` and `wayland_display` have been moved to a new `EventLoopWindowTargetExtUnix` trait. +- On iOS, add `set_prefers_status_bar_hidden` extension function instead of + hijacking `set_decorations` for this purpose. +- On macOS and iOS, corrected the auto trait impls of `EventLoopProxy`. +- On iOS, add touch pressure information for touch events. +- Implement `raw_window_handle::HasRawWindowHandle` for `Window` type on all supported platforms. +- On macOS, fix the signature of `-[NSView drawRect:]`. +- On iOS, fix the behavior of `ControlFlow::Poll`. It wasn't polling if that was the only mode ever used by the application. +- On iOS, fix DPI sent out by views on creation was `0.0` - now it gives a reasonable number. +- On iOS, RedrawRequested now works for gl/metal backed views. +- On iOS, RedrawRequested is generally ordered after EventsCleared. + +# 0.20.0 Alpha 2 (2019-07-09) + +- On X11, non-resizable windows now have maximize explicitly disabled. +- On Windows, support paths longer than MAX_PATH (260 characters) in `WindowEvent::DroppedFile` +and `WindowEvent::HoveredFile`. +- On Mac, implement `DeviceEvent::Button`. +- Change `Event::Suspended(true / false)` to `Event::Suspended` and `Event::Resumed`. +- On X11, fix sanity check which checks that a monitor's reported width and height (in millimeters) are non-zero when calculating the DPI factor. +- Revert the use of invisible surfaces in Wayland, which introduced graphical glitches with OpenGL (#835) +- On X11, implement `_NET_WM_PING` to allow desktop environment to kill unresponsive programs. +- On Windows, when a window is initially invisible, it won't take focus from the existing visible windows. +- On Windows, fix multiple calls to `request_redraw` during `EventsCleared` sending multiple `RedrawRequested events.` +- On Windows, fix edge case where `RedrawRequested` could be dispatched before input events in event loop iteration. +- On Windows, fix timing issue that could cause events to be improperly dispatched after `RedrawRequested` but before `EventsCleared`. +- On macOS, drop unused Metal dependency. +- On Windows, fix the trail effect happening on transparent decorated windows. Borderless (or un-decorated) windows were not affected. +- On Windows, fix `with_maximized` not properly setting window size to entire window. +- On macOS, change `WindowExtMacOS::request_user_attention()` to take an `enum` instead of a `bool`. + +# 0.20.0 Alpha 1 (2019-06-21) + +- Changes below are considered **breaking**. +- Change all occurrences of `EventsLoop` to `EventLoop`. +- Previously flat API is now exposed through `event`, `event_loop`, `monitor`, and `window` modules. +- `os` module changes: + - Renamed to `platform`. + - All traits now have platform-specific suffixes. + - Exposes new `desktop` module on Windows, Mac, and Linux. +- Changes to event loop types: + - `EventLoopProxy::wakeup` has been removed in favor of `send_event`. + - **Major:** New `run` method drives winit event loop. + - Returns `!` to ensure API behaves identically across all supported platforms. + - This allows `emscripten` implementation to work without lying about the API. + - `ControlFlow`'s variants have been replaced with `Wait`, `WaitUntil(Instant)`, `Poll`, and `Exit`. + - Is read after `EventsCleared` is processed. + - `Wait` waits until new events are available. + - `WaitUntil` waits until either new events are available or the provided time has been reached. + - `Poll` instantly resumes the event loop. + - `Exit` aborts the event loop. + - Takes a closure that implements `'static + FnMut(Event, &EventLoop, &mut ControlFlow)`. + - `&EventLoop` is provided to allow new `Window`s to be created. + - **Major:** `platform::desktop` module exposes `EventLoopExtDesktop` trait with `run_return` method. + - Behaves identically to `run`, but returns control flow to the calling context and can take non-`'static` closures. + - `EventLoop`'s `poll_events` and `run_forever` methods have been removed in favor of `run` and `run_return`. +- Changes to events: + - Remove `Event::Awakened` in favor of `Event::UserEvent(T)`. + - Can be sent with `EventLoopProxy::send_event`. + - Rename `WindowEvent::Refresh` to `WindowEvent::RedrawRequested`. + - `RedrawRequested` can be sent by the user with the `Window::request_redraw` method. + - `EventLoop`, `EventLoopProxy`, and `Event` are now generic over `T`, for use in `UserEvent`. + - **Major:** Add `NewEvents(StartCause)`, `EventsCleared`, and `LoopDestroyed` variants to `Event`. + - `NewEvents` is emitted when new events are ready to be processed by event loop. + - `StartCause` describes why new events are available, with `ResumeTimeReached`, `Poll`, `WaitCancelled`, and `Init` (sent once at start of loop). + - `EventsCleared` is emitted when all available events have been processed. + - Can be used to perform logic that depends on all events being processed (e.g. an iteration of a game loop). + - `LoopDestroyed` is emitted when the `run` or `run_return` method is about to exit. +- Rename `MonitorId` to `MonitorHandle`. +- Removed `serde` implementations from `ControlFlow`. +- Rename several functions to improve both internal consistency and compliance with Rust API guidelines. +- Remove `WindowBuilder::multitouch` field, since it was only implemented on a few platforms. Multitouch is always enabled now. +- **Breaking:** On macOS, change `ns` identifiers to use snake_case for consistency with iOS's `ui` identifiers. +- Add `MonitorHandle::video_modes` method for retrieving supported video modes for the given monitor. +- On Wayland, the window now exists even if nothing has been drawn. +- On Windows, fix initial dimensions of a fullscreen window. +- On Windows, Fix transparent borderless windows rendering wrong. + +# Version 0.19.1 (2019-04-08) + +- On Wayland, added a `get_wayland_display` function to `EventsLoopExt`. +- On Windows, fix `CursorMoved(0, 0)` getting dispatched on window focus. +- On macOS, fix command key event left and right reverse. +- On FreeBSD, NetBSD, and OpenBSD, fix build of X11 backend. +- On Linux, the numpad's add, subtract and divide keys are now mapped to the `Add`, `Subtract` and `Divide` virtual key codes +- On macOS, the numpad's subtract key has been added to the `Subtract` mapping +- On Wayland, the numpad's home, end, page up and page down keys are now mapped to the `Home`, `End`, `PageUp` and `PageDown` virtual key codes +- On Windows, fix icon not showing up in corner of window. +- On X11, change DPI scaling factor behavior. First, winit tries to read it from "Xft.dpi" XResource, and uses DPI calculation from xrandr dimensions as fallback behavior. + +# Version 0.19.0 (2019-03-06) + +- On X11, we will use the faster `XRRGetScreenResourcesCurrent` function instead of `XRRGetScreenResources` when available. +- On macOS, fix keycodes being incorrect when using a non-US keyboard layout. +- On Wayland, fix `with_title()` not setting the windows title +- On Wayland, add `set_wayland_theme()` to control client decoration color theme +- Added serde serialization to `os::unix::XWindowType`. +- **Breaking:** Remove the `icon_loading` feature and the associated `image` dependency. +- On X11, make event loop thread safe by replacing XNextEvent with select(2) and XCheckIfEvent +- On Windows, fix malformed function pointer typecast that could invoke undefined behavior. +- Refactored Windows state/flag-setting code. +- On Windows, hiding the cursor no longer hides the cursor for all Winit windows - just the one `hide_cursor` was called on. +- On Windows, cursor grabs used to get perpetually canceled when the grabbing window lost focus. Now, cursor grabs automatically get re-initialized when the window regains focus and the mouse moves over the client area. +- On Windows, only vertical mouse wheel events were handled. Now, horizontal mouse wheel events are also handled. +- On Windows, ignore the AltGr key when populating the `ModifersState` type. # Version 0.18.1 (2018-12-30) diff --git a/third_party/cargo/vendor/winit-0.22.0/CONTRIBUTING.md b/third_party/cargo/vendor/winit-0.22.0/CONTRIBUTING.md new file mode 100644 index 0000000..0657334 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Winit Contributing Guidelines + +## Scope +[See `FEATURES.md`](./FEATURES.md). When requesting or implementing a new Winit feature, you should +consider whether or not it's directly related to window creation or input handling. If it isn't, it +may be worth creating a separate crate that extends Winit's API to add that functionality. + + +## Reporting an issue + +When reporting an issue, in order to help the maintainers understand what the problem is, please make +your description of the issue as detailed as possible: + +- if it is a bug, please provide clear explanation of what happens, what should happen, and how to + reproduce the issue, ideally by providing a minimal program exhibiting the problem +- if it is a feature request, please provide a clear argumentation about why you believe this feature + should be supported by winit + +## Making a pull request + +When making a code contribution to winit, before opening your pull request, please make sure that: + +- you tested your modifications on all the platforms impacted, or if not possible detail which platforms + were not tested, and what should be tested, so that a maintainer or another contributor can test them +- you updated any relevant documentation in winit +- you left comments in your code explaining any part that is not straightforward, so that the + maintainers and future contributors don't have to try to guess what your code is supposed to do +- your PR adds an entry to the changelog file if the introduced change is relevant to winit users +- if your PR affects the platform compatibility of one or more features or adds another feature, the + relevant sections in [`FEATURES.md`](https://github.com/rust-windowing/winit/blob/master/FEATURES.md#features) + should be updated. + +Once your PR is open, you can ask for review by a maintainer of your platform. Winit's merging policy +is that a PR must be approved by at least two maintainers of winit before being merged, including +at least a maintainer of the platform (a maintainer making a PR themselves counts as approving it). + +## Maintainers & Testers + +The current [list of testers and contributors](https://github.com/rust-windowing/winit/wiki/Testers-and-Contributors) +can be found on the Wiki. + +If you are interested in contributing or testing on a platform, please add yourself to that table! diff --git a/third_party/cargo/vendor/winit-0.22.0/Cargo.lock b/third_party/cargo/vendor/winit-0.22.0/Cargo.lock new file mode 100644 index 0000000..9fc8f1b --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/Cargo.lock @@ -0,0 +1,1368 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adler32" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" + +[[package]] +name = "andrew" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7f09f89872c2b6b29e319377b1fbe91c6f5947df19a25596e121cf19a7b35e" +dependencies = [ + "bitflags", + "line_drawing", + "rusttype 0.7.9", + "walkdir", + "xdg", + "xml-rs", +] + +[[package]] +name = "android_glue" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000444226fcff248f2bc4c7625be32c63caccfecc2723a2b9f78a7487a49c407" + +[[package]] +name = "approx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arrayvec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi 0.3.8", +] + +[[package]] +name = "autocfg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" + +[[package]] +name = "base-x" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b20b618342cf9891c292c4f5ac2cde7287cc5c87e87e9c769d617793607dec1" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "bumpalo" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f359dc14ff8911330a51ef78022d376f25ed00248912803b58f00cb1c27f742" + +[[package]] +name = "bytemuck" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37fa13df2292ecb479ec23aa06f4507928bef07839be9ef15281411076629431" + +[[package]] +name = "byteorder" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" + +[[package]] +name = "calloop" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa2097be53a00de9e8fc349fea6d76221f398f5c4fa550d420669906962d160" +dependencies = [ + "mio", + "mio-extras", + "nix", +] + +[[package]] +name = "cc" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "chrono" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80094f509cf8b5ae86a4966a39b3ff66cd7e2a3e594accec3743ff3fabeab5b2" +dependencies = [ + "num-integer", + "num-traits", + "time", +] + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +dependencies = [ + "bitflags", +] + +[[package]] +name = "cocoa" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29f7768b2d1be17b96158e3285951d366b40211320fb30826a76cb7a0da6400" +dependencies = [ + "bitflags", + "block", + "core-foundation", + "core-graphics", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "color_quant" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dbbb57365263e881e805dc77d94697c9118fd94d8da011240555aa7b23445bd" + +[[package]] +name = "colored" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4ffc801dacf156c5854b9df4f425a626539c3a6ef7893cc0c5084a23f0b6c59" +dependencies = [ + "atty", + "lazy_static", + "winapi 0.3.8", +] + +[[package]] +name = "console_log" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7871d2947441b0fdd8e2bd1ce2a2f75304f896582c0d572162d48290683c48" +dependencies = [ + "log", + "web-sys", +] + +[[package]] +name = "core-foundation" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" + +[[package]] +name = "core-graphics" +version = "0.17.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56790968ab1c8a1202a102e6de05fc6e1ec87da99e4e93e9a7d13efbfc1e95a9" +dependencies = [ + "bitflags", + "core-foundation", + "foreign-types", + "libc", +] + +[[package]] +name = "core-video-sys" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc065219542086f72d1e9f7aadbbab0989e980263695d129d502082d063a9d0" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "core-graphics", + "libc", + "objc", +] + +[[package]] +name = "crc32fast" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f02af974daeee82218205558e51ec8768b48cf524bd01d550abe5573a608285" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", + "maybe-uninit", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +dependencies = [ + "autocfg", + "cfg-if", + "crossbeam-utils", + "lazy_static", + "maybe-uninit", + "memoffset", + "scopeguard", +] + +[[package]] +name = "crossbeam-queue" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" +dependencies = [ + "cfg-if", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" +dependencies = [ + "autocfg", + "cfg-if", + "lazy_static", +] + +[[package]] +name = "deflate" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050ef6de42a33903b30a7497b76b40d3d58691d4d3eec355348c122444a388f0" +dependencies = [ + "adler32", + "byteorder", +] + +[[package]] +name = "discard" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dlib" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ba6eb47c2131e784a38b726eb54c1e1484904f013e576a25354d0124161af6" + +[[package]] +name = "either" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +dependencies = [ + "bitflags", + "fuchsia-zircon-sys", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" + +[[package]] +name = "futures-channel-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5e5f4df964fa9c1c2f8bddeb5c3611631cacd93baf810fc8bb2fb4b495c263a" +dependencies = [ + "futures-core-preview", +] + +[[package]] +name = "futures-core-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35b6263fb1ef523c3056565fa67b1d16f0a8604ff12b11b08c25f28a734c60a" + +[[package]] +name = "futures-executor-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75236e88bd9fe88e5e8bfcd175b665d0528fe03ca4c5207fabc028c8f9d93e98" +dependencies = [ + "futures-core-preview", + "futures-util-preview", + "num_cpus", +] + +[[package]] +name = "futures-util-preview" +version = "0.3.0-alpha.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ce968633c17e5f97936bd2797b6e38fb56cf16a7422319f7ec2e30d3c470e8d" +dependencies = [ + "futures-core-preview", + "pin-utils", + "slab", +] + +[[package]] +name = "gif" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471d90201b3b223f3451cd4ad53e34295f16a1df17b1edf3736d47761c3981af" +dependencies = [ + "color_quant", + "lzw", +] + +[[package]] +name = "hermit-abi" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1010591b26bbfe835e9faeabeb11866061cc7dcebffd56ad7d0942d0e61aefd8" +dependencies = [ + "libc", +] + +[[package]] +name = "image" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "403f0c29211dc50a78eb53eeeae87945d44cb63071881834212f36677fccb2b4" +dependencies = [ + "bytemuck", + "byteorder", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits", + "png", + "scoped_threadpool", + "tiff", +] + +[[package]] +name = "inflate" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cdb29978cc5797bd8dcc8e5bf7de604891df2a8dc576973d71a281e916db2ff" +dependencies = [ + "adler32", +] + +[[package]] +name = "instant" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c346c299e3fe8ef94dc10c2c0253d858a69aac1245157a3bf4125915d528caf" +dependencies = [ + "stdweb", + "web-sys", +] + +[[package]] +name = "iovec" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b3ea6ff95e175473f8ffe6a7eb7c00d054240321b84c57051175fe3c1e075e" +dependencies = [ + "libc", +] + +[[package]] +name = "itoa" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b7a7c0c47db5545ed3fef7468ee7bb5b74691498139e4b3f6a20685dc6dd8e" + +[[package]] +name = "jpeg-decoder" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0256f0aec7352539102a9efbcb75543227b7ab1117e0f95450023af730128451" +dependencies = [ + "byteorder", + "rayon", +] + +[[package]] +name = "js-sys" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cb931d43e71f560c81badb0191596562bafad2be06a3f9025b845c847c60df5" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "kernel32-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "lazycell" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" + +[[package]] +name = "libc" +version = "0.2.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb147597cdf94ed43ab7a9038716637d2d1bf2bc571da995d0028dec06bd3018" + +[[package]] +name = "libloading" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b111a074963af1d37a139918ac6d49ad1d0d5e47f72fd55388619691a7d753" +dependencies = [ + "cc", + "winapi 0.3.8", +] + +[[package]] +name = "line_drawing" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc7ad3d82c845bdb5dde34ffdcc7a5fb4d2996e1e1ee0f19c33bc80e15196b9" +dependencies = [ + "num-traits", +] + +[[package]] +name = "lock_api" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79b2de95ecb4691949fea4716ca53cdbcfccb2c612e19644a8bad05edcf9f47b" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "lzw" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d947cbb889ed21c2a84be6ffbaebf5b4e0f4340638cba0444907e38b56be084" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "maybe-uninit" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" + +[[package]] +name = "memmap" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +dependencies = [ + "libc", + "winapi 0.3.8", +] + +[[package]] +name = "memoffset" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "miniz_oxide" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa679ff6578b1cddee93d7e82e263b94a575e0bfced07284eb0c037c1d2416a5" +dependencies = [ + "adler32", +] + +[[package]] +name = "mio" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302dec22bcf6bae6dfb69c647187f4b4d0fb6f535521f7bc022430ce8e12008f" +dependencies = [ + "cfg-if", + "fuchsia-zircon", + "fuchsia-zircon-sys", + "iovec", + "kernel32-sys", + "libc", + "log", + "miow", + "net2", + "slab", + "winapi 0.2.8", +] + +[[package]] +name = "mio-extras" +version = "2.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52403fe290012ce777c4626790c8951324a2b9e3316b3143779c72b029742f19" +dependencies = [ + "lazycell", + "log", + "mio", + "slab", +] + +[[package]] +name = "miow" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" +dependencies = [ + "kernel32-sys", + "net2", + "winapi 0.2.8", + "ws2_32-sys", +] + +[[package]] +name = "net2" +version = "0.2.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" +dependencies = [ + "cfg-if", + "libc", + "winapi 0.3.8", +] + +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" +dependencies = [ + "bitflags", + "cc", + "cfg-if", + "libc", + "void", +] + +[[package]] +name = "num-integer" +version = "0.1.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfb0800a0291891dd9f4fe7bd9c19384f98f7fbe0cd0f39a2c6b88b9868bbc00" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da4dc79f9e6c81bef96148c8f6b8e72ad4541caa4a24373e900a36da07de03a3" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[package]] +name = "ordered-float" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18869315e81473c951eb56ad5558bbc56978562d3ecfb87abb7a1e944cea4518" +dependencies = [ + "num-traits", +] + +[[package]] +name = "parking_lot" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e98c49ab0b7ce5b222f2cc9193fc4efe11c6d0bd4f648e374684a6857b1cfc" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7582838484df45743c8434fbff785e8edf260c28748353d44bc0da32e0ceabf1" +dependencies = [ + "cfg-if", + "cloudabi", + "libc", + "redox_syscall", + "smallvec", + "winapi 0.3.8", +] + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" + +[[package]] +name = "pin-utils" +version = "0.1.0-alpha.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5894c618ce612a3fa23881b152b608bafb8c56cfc22f434a3ba3120b40f7b587" + +[[package]] +name = "pkg-config" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05da548ad6865900e60eaba7f589cc0783590a92e940c26953ff81ddbab2d677" + +[[package]] +name = "png" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46060468187c21c00ffa2a920690b29997d7fd543f5a4d400461e4a7d4fccde8" +dependencies = [ + "bitflags", + "crc32fast", + "deflate", + "inflate", +] + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +dependencies = [ + "unicode-xid 0.1.0", +] + +[[package]] +name = "proc-macro2" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c09721c6781493a2a492a96b5a5bf19b65917fe6728884e7c44dd0c60ca3435" +dependencies = [ + "unicode-xid 0.2.0", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +dependencies = [ + "proc-macro2 0.4.30", +] + +[[package]] +name = "quote" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bdc6c187c65bca4260c9011c9e3132efe4909da44726bad24cf7572ae338d7f" +dependencies = [ + "proc-macro2 1.0.9", +] + +[[package]] +name = "raw-window-handle" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a441a7a6c80ad6473bd4b74ec1c9a4c951794285bf941c2126f607c72e48211" +dependencies = [ + "libc", +] + +[[package]] +name = "rayon" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db6ce3297f9c85e16621bb8cca38a06779ffc31bb8184e1be4bed2be4678a098" +dependencies = [ + "crossbeam-deque", + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08a89b46efaf957e52b18062fb2f4660f8b8a4dde1807ca002690868ef2c85a9" +dependencies = [ + "crossbeam-deque", + "crossbeam-queue", + "crossbeam-utils", + "lazy_static", + "num_cpus", +] + +[[package]] +name = "redox_syscall" +version = "0.1.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +dependencies = [ + "semver", +] + +[[package]] +name = "rusttype" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "310942406a39981bed7e12b09182a221a29e0990f3e7e0c971f131922ed135d5" +dependencies = [ + "rusttype 0.8.2", +] + +[[package]] +name = "rusttype" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a911032fb5791ccbeec9f28fdcb9bf0983b81f227bafdfd227c658d0731c8a" +dependencies = [ + "approx", + "arrayvec", + "ordered-float", + "stb_truetype", +] + +[[package]] +name = "ryu" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa8506c1de11c9c4e4c38863ccbe02a305c8188e85a05a784c9e11e1c3910c8" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" + +[[package]] +name = "serde" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64" +dependencies = [ + "proc-macro2 1.0.9", + "quote 1.0.3", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9371ade75d4c2d6cb154141b9752cf3781ec9c05e0e5cf35060e1e70ee7b9c25" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" + +[[package]] +name = "simple_logger" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea0c4611f32f4c2bac73754f22dca1f57e6c1945e0590dae4e5f2a077b92367" +dependencies = [ + "atty", + "chrono", + "colored", + "log", + "winapi 0.3.8", +] + +[[package]] +name = "slab" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" + +[[package]] +name = "smallvec" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc" + +[[package]] +name = "smithay-client-toolkit" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421c8dc7acf5cb205b88160f8b4cc2c5cfabe210e43b2f80f009f4c1ef910f1d" +dependencies = [ + "andrew", + "bitflags", + "dlib", + "lazy_static", + "memmap", + "nix", + "wayland-client", + "wayland-protocols", +] + +[[package]] +name = "stb_truetype" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f77b6b07e862c66a9f3e62a07588fee67cd90a9135a2b942409f195507b4fb51" +dependencies = [ + "byteorder", +] + +[[package]] +name = "stdweb" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" +dependencies = [ + "discard", + "futures-channel-preview", + "futures-core-preview", + "futures-executor-preview", + "futures-util-preview", + "rustc_version", + "serde", + "serde_json", + "stdweb-derive", + "stdweb-internal-macros", + "stdweb-internal-runtime", + "wasm-bindgen", +] + +[[package]] +name = "stdweb-derive" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" +dependencies = [ + "proc-macro2 1.0.9", + "quote 1.0.3", + "serde", + "serde_derive", + "syn", +] + +[[package]] +name = "stdweb-internal-macros" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" +dependencies = [ + "base-x", + "proc-macro2 1.0.9", + "quote 1.0.3", + "serde", + "serde_derive", + "serde_json", + "sha1", + "syn", +] + +[[package]] +name = "stdweb-internal-runtime" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" + +[[package]] +name = "syn" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "123bd9499cfb380418d509322d7a6d52e5315f064fe4b3ad18a53d6b92c07859" +dependencies = [ + "proc-macro2 1.0.9", + "quote 1.0.3", + "unicode-xid 0.2.0", +] + +[[package]] +name = "tiff" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "002351e428db1eb1d8656d4ca61947c3519ac3191e1c804d4600cd32093b77ad" +dependencies = [ + "byteorder", + "lzw", + "miniz_oxide", +] + +[[package]] +name = "time" +version = "0.1.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" +dependencies = [ + "libc", + "redox_syscall", + "winapi 0.3.8", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" + +[[package]] +name = "unicode-xid" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" + +[[package]] +name = "walkdir" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" +dependencies = [ + "same-file", + "winapi 0.3.8", + "winapi-util", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3557c397ab5a8e347d434782bcd31fc1483d927a6826804cec05cc792ee2519d" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0da9c9a19850d3af6df1cb9574970b566d617ecfaf36eb0b706b6f3ef9bd2f8" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2 1.0.9", + "quote 1.0.3", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f6fde1d36e75a714b5fe0cffbb78978f222ea6baebb726af13c78869fdb4205" +dependencies = [ + "quote 1.0.3", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25bda4168030a6412ea8a047e27238cadf56f0e53516e1e83fec0a8b7c786f6d" +dependencies = [ + "proc-macro2 1.0.9", + "quote 1.0.3", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc9f36ad51f25b0219a3d4d13b90eb44cd075dff8b6280cca015775d7acaddd8" + +[[package]] +name = "wayland-client" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1080ebe0efabcf12aef2132152f616038f2d7dcbbccf7b2d8c5270fe14bcda" +dependencies = [ + "bitflags", + "calloop", + "downcast-rs", + "libc", + "mio", + "nix", + "wayland-commons", + "wayland-scanner", + "wayland-sys", +] + +[[package]] +name = "wayland-commons" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb66b0d1a27c39bbce712b6372131c6e25149f03ffb0cd017cf8f7de8d66dbdb" +dependencies = [ + "nix", + "wayland-sys", +] + +[[package]] +name = "wayland-protocols" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cc286643656742777d55dc8e70d144fa4699e426ca8e9d4ef454f4bf15ffcf9" +dependencies = [ + "bitflags", + "wayland-client", + "wayland-commons", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93b02247366f395b9258054f964fe293ddd019c3237afba9be2ccbe9e1651c3d" +dependencies = [ + "proc-macro2 0.4.30", + "quote 0.6.13", + "xml-rs", +] + +[[package]] +name = "wayland-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4" +dependencies = [ + "dlib", + "lazy_static", +] + +[[package]] +name = "web-sys" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "721c6263e2c66fd44501cc5efbfa2b7dfa775d13e4ea38c46299646ed1f9c70a" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-build" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" +dependencies = [ + "winapi 0.3.8", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "winit" +version = "0.22.0" +dependencies = [ + "android_glue", + "bitflags", + "cocoa", + "console_log", + "core-foundation", + "core-graphics", + "core-video-sys", + "dispatch", + "image", + "instant", + "lazy_static", + "libc", + "log", + "mio", + "mio-extras", + "objc", + "parking_lot", + "percent-encoding", + "raw-window-handle", + "serde", + "simple_logger", + "smithay-client-toolkit", + "stdweb", + "wasm-bindgen", + "wayland-client", + "web-sys", + "winapi 0.3.8", + "x11-dl", +] + +[[package]] +name = "ws2_32-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" +dependencies = [ + "winapi 0.2.8", + "winapi-build", +] + +[[package]] +name = "x11-dl" +version = "2.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf981e3a5b3301209754218f962052d4d9ee97e478f4d26d4a6eced34c1fef8" +dependencies = [ + "lazy_static", + "libc", + "maybe-uninit", + "pkg-config", +] + +[[package]] +name = "xdg" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d089681aa106a86fade1b0128fb5daf07d5867a509ab036d99988dec80429a57" + +[[package]] +name = "xml-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" diff --git a/third_party/cargo/vendor/winit-0.18.1/Cargo.toml b/third_party/cargo/vendor/winit-0.22.0/Cargo.toml similarity index 50% rename from third_party/cargo/vendor/winit-0.18.1/Cargo.toml rename to third_party/cargo/vendor/winit-0.22.0/Cargo.toml index 259997e..0b82341 100644 --- a/third_party/cargo/vendor/winit-0.18.1/Cargo.toml +++ b/third_party/cargo/vendor/winit-0.22.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -11,8 +11,9 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "winit" -version = "0.18.1" +version = "0.22.0" authors = ["The winit contributors", "Pierre Krieger "] description = "Cross-platform window creation library." documentation = "https://docs.rs/winit" @@ -20,50 +21,83 @@ readme = "README.md" keywords = ["windowing"] categories = ["gui"] license = "Apache-2.0" -repository = "https://github.com/tomaka/winit" +repository = "https://github.com/rust-windowing/winit" [package.metadata.docs.rs] -features = ["icon_loading", "serde"] -[dependencies.image] -version = "0.20.1" -optional = true +features = ["serde"] +[dependencies.bitflags] +version = "1" + +[dependencies.instant] +version = "0.1" [dependencies.lazy_static] version = "1" [dependencies.libc] -version = "0.2" +version = "0.2.64" [dependencies.log] version = "0.4" +[dependencies.raw-window-handle] +version = "0.3" + [dependencies.serde] version = "1" features = ["serde_derive"] optional = true +[dev-dependencies.image] +version = "0.23" + +[dev-dependencies.simple_logger] +version = "1" [features] -icon_loading = ["image"] -[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.parking_lot] -version = "0.7" +stdweb = ["std_web", "instant/stdweb"] +web-sys = ["web_sys", "wasm-bindgen", "instant/wasm-bindgen"] +[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.mio] +version = "0.6" + +[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.mio-extras] +version = "2.0" [target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.percent-encoding] -version = "1.0" +version = "2.0" [target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.smithay-client-toolkit] -version = "0.4.3" +version = "^0.6.6" [target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.wayland-client] -version = "0.21" -features = ["dlopen", "egl", "cursor"] +version = "0.23.0" +features = ["dlopen", "egl", "cursor", "eventloop"] [target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies.x11-dl] version = "2.18.3" +[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\", target_os = \"windows\"))".dependencies.parking_lot] +version = "0.10" +[target."cfg(target_arch = \"wasm32\")".dependencies.std_web] +version = "=0.4.20" +features = ["experimental_features_which_may_break_on_minor_version_bumps"] +optional = true +package = "stdweb" + +[target."cfg(target_arch = \"wasm32\")".dependencies.wasm-bindgen] +version = "0.2.45" +optional = true + +[target."cfg(target_arch = \"wasm32\")".dependencies.web_sys] +version = "0.3.22" +features = ["console", "CssStyleDeclaration", "BeforeUnloadEvent", "Document", "DomRect", "Element", "Event", "EventTarget", "FocusEvent", "HtmlCanvasElement", "HtmlElement", "KeyboardEvent", "MediaQueryList", "MediaQueryListEvent", "MouseEvent", "Node", "PointerEvent", "Window", "WheelEvent"] +optional = true +package = "web-sys" +[target."cfg(target_arch = \"wasm32\")".dev-dependencies.console_log] +version = "0.1" [target."cfg(target_os = \"android\")".dependencies.android_glue] version = "0.2" [target."cfg(target_os = \"ios\")".dependencies.objc] version = "0.2.3" [target."cfg(target_os = \"macos\")".dependencies.cocoa] -version = "0.18.4" +version = "0.19.1" [target."cfg(target_os = \"macos\")".dependencies.core-foundation] version = "0.6" @@ -71,11 +105,16 @@ version = "0.6" [target."cfg(target_os = \"macos\")".dependencies.core-graphics] version = "0.17.3" -[target."cfg(target_os = \"macos\")".dependencies.objc] -version = "0.2.3" -[target."cfg(target_os = \"windows\")".dependencies.backtrace] -version = "0.3" +[target."cfg(target_os = \"macos\")".dependencies.core-video-sys] +version = "0.1.3" +features = ["display_link"] +default_features = false +[target."cfg(target_os = \"macos\")".dependencies.dispatch] +version = "0.2.0" + +[target."cfg(target_os = \"macos\")".dependencies.objc] +version = "0.2.6" [target."cfg(target_os = \"windows\")".dependencies.winapi] version = "0.3.6" -features = ["combaseapi", "dwmapi", "errhandlingapi", "hidusage", "libloaderapi", "objbase", "ole2", "processthreadsapi", "shellapi", "shellscalingapi", "shobjidl_core", "unknwnbase", "winbase", "windowsx", "winerror", "wingdi", "winnt", "winuser"] +features = ["combaseapi", "commctrl", "dwmapi", "errhandlingapi", "hidusage", "libloaderapi", "objbase", "ole2", "processthreadsapi", "shellapi", "shellscalingapi", "shobjidl_core", "unknwnbase", "winbase", "windowsx", "winerror", "wingdi", "winnt", "winuser"] diff --git a/third_party/cargo/vendor/winit-0.22.0/FEATURES.md b/third_party/cargo/vendor/winit-0.22.0/FEATURES.md new file mode 100644 index 0000000..0918d35 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/FEATURES.md @@ -0,0 +1,237 @@ +# Winit Scope + +Winit aims to expose an interface that abstracts over window creation and input handling, and can +be used to create both games and applications. It supports the main graphical platforms: +- Desktop + - Windows + - macOS + - Unix + - via X11 + - via Wayland +- Mobile + - iOS + - Android +- Web + - via WASM + +Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not +aim to support every single feature of every platform, but rather to abstract over the common features +available everywhere. In this context, APIs exposed in winit can be split into different "support tiers": + +- **Core:** Features that are essential to providing a well-formed abstraction over each platform's + windowing and input APIs. +- **Platform:** Platform-specific features that can't be meaningfully exposed through a common API and + cannot be implemented outside of Winit without exposing a significant amount of Winit's internals + or interfering with Winit's abstractions. +- **Usability:** Features that are not strictly essential to Winit's functionality, but provide meaningful + usability improvements and cannot be reasonably implemented in an external crate. These are + generally optional and exposed through Cargo features. + +Core features are taken care of by the core Winit maintainers. Platform features are not. +When a platform feature is submitted, the submitter is considered the expert in the +feature and may be asked to support the feature should it break in the future. + +Winit ***does not*** directly expose functionality for drawing inside windows or creating native +menus, but ***does*** commit to providing APIs that higher-level crates can use to implement that +functionality. + +## `1.0` and stability + +When all core features are implemented to the satisfaction of the Winit maintainers, Winit 1.0 will +be released and the library will enter maintenance mode. For the most part, new core features will not +be added past this point. New platform features may be accepted and exposed through point releases. + +### Tier upgrades +Some platform features could in theory be exposed across multiple platforms, but have not gone +through the implementation work necessary to function on all platforms. When one of these features +gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature. +If that gets accepted, the platform-specific functions gets deprecated and become permanently +exposed through the core, cross-platform API. + +# Features + +## Extending this section + +If your PR makes notable changes to Winit's features, please update this section as follows: + +- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core + feature, add a row to the feature matrix and describe what platforms the feature has been implemented on. + +- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the + API rework on all relevant platforms, please move it to the `Completed API Reworks` table. + +- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*, + or mark it as *mostly completed* and link to an issue describing the problems with the implementation. + +## Core + +### Windowing +- **Window initialization**: Winit allows the creation of a window +- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context +- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan +- **Window decorations**: The windows created by winit are properly decorated, and the decorations can + be deactivated +- **Window decorations toggle**: Decorations can be turned on or off after window creation +- **Window resizing**: The windows created by winit can be resized and generate the appropriate events + when they are. The application can precisely control its window size if desired. +- **Window resize increments**: When the window gets resized, the application can choose to snap the window's + size to specific values. +- **Window transparency**: Winit allows the creation of windows with a transparent background. +- **Window maximization**: The windows created by winit can be maximized upon creation. +- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after + creation. +- **Window minimization**: The windows created by winit can be minimized after creation. +- **Fullscreen**: The windows created by winit can be put into fullscreen mode. +- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after + creation. +- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor + for fullscreen windows, and if applicable, captures the monitor for exclusive + use by this application. +- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content. +- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent + windows can be disabled in favor of popup windows. This feature also guarantees that popup windows + get drawn above their owner. + + +### System Information +- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary. +- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth). + +### Input Handling +- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events. +- **Mouse set location**: Forcibly changing the location of the pointer. +- **Cursor grab**: Locking the cursor so it cannot exit the client area of a window. +- **Cursor icon**: Changing the cursor icon, or hiding the cursor. +- **Touch events**: Single-touch events. +- **Touch pressure**: Touch events contain information about the amount of force being applied. +- **Multitouch**: Multi-touch events, including cancellation of a gesture. +- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and + translating keypresses into UTF-8 characters, handling dead keys and IMEs. +- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled. +- **Raw Device Events**: Capturing input from input devices without any OS filtering. +- **Gamepad/Joystick events**: Capturing input from gampads and joysticks. +- **Device movement events:**: Capturing input from the device gyroscope and accelerometer. + +## Platform +### Windows +* Setting the taskbar icon +* Setting the parent window +* `WS_EX_NOREDIRECTIONBITMAP` support +* Theme the title bar according to Windows 10 Dark Mode setting + +### macOS +* Window activation policy +* Window movable by background +* Transparent titlebar +* Hidden titlebar +* Hidden titlebar buttons +* Full-size content view + +### Unix +* Window urgency +* X11 Window Class +* X11 Override Redirect Flag +* GTK Theme Variant +* Base window size + +### iOS +* `winit` has a minimum OS requirement of iOS 8 +* Get the `UIWindow` object pointer +* Get the `UIViewController` object pointer +* Get the `UIView` object pointer +* Get the `UIScreen` object pointer +* Setting the `UIView` hidpi factor +* Valid orientations +* Home indicator visibility +* Status bar visibility +* Deferrring system gestures +* Support for custom `UIView` derived class +* Getting the device idiom +* Getting the preferred video mode + +### Web +* Get if systems preferred color scheme is "dark" + +## Usability +* `serde`: Enables serialization/deserialization of certain types with Serde. (Maintainer: @Osspial) + +## Compatibility Matrix + +Legend: + +- ✔️: Works as intended +- ▢: Mostly works but some bugs are known +- ❌: Missing feature or large bugs making it unusable +- **N/A**: Not applicable for this platform +- ❓: Unknown status + +### Windowing +|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |WASM | +|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | +|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ | +|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**| +|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**| +|Window decorations |✔️ |✔️ |✔️ |▢[#306] |**N/A**|**N/A**|**N/A**| +|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**| +|Window resizing |✔️ |▢[#219]|✔️ |▢[#306] |**N/A**|**N/A**|✔️ | +|Window resize increments |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**| +|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A | +|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**| +|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**| +|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**| +|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ | +|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ | +|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**| +|HiDPI support |✔️ |✔️ |✔️ |✔️ |▢[#721]|✔️ |**N/A**| +|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**| + +### System information +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM | +|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | +|Monitor list |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |**N/A**| +|Video mode query |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |**N/A**| + +### Input handling +|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |WASM | +|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | +|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ | +|Mouse set location |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A**|**N/A**| +|Cursor grab |✔️ |▢[#165] |▢[#242] |✔️ |**N/A**|**N/A**|❓ | +|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ | +|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ | +|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ | +|Multitouch |✔️ |❌ |✔️ |✔️ |❓ |✔️ |✔️ | +|Keyboard events |✔️ |✔️ |✔️ |✔️ |❓ |❌ |✔️ | +|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |❌[#306] |**N/A**|**N/A**|❓ | +|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ | +|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ | +|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ | + +### Pending API Reworks +Changes in the API that have been agreed upon but aren't implemented across all platforms. + +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM | +|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | +|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |▢[#721]|✔️ |❓ | +|Event Loop 2.0 ([#459]) |✔️ |✔️ |❌ |✔️ |❌ |✔️ |❓ | +|Keyboard Input ([#812]) |❌ |❌ |❌ |❌ |❌ |❌ |❓ | + +### Completed API Reworks +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |WASM | +|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | + +[#165]: https://github.com/rust-windowing/winit/issues/165 +[#219]: https://github.com/rust-windowing/winit/issues/219 +[#242]: https://github.com/rust-windowing/winit/issues/242 +[#306]: https://github.com/rust-windowing/winit/issues/306 +[#315]: https://github.com/rust-windowing/winit/issues/315 +[#319]: https://github.com/rust-windowing/winit/issues/319 +[#33]: https://github.com/rust-windowing/winit/issues/33 +[#459]: https://github.com/rust-windowing/winit/issues/459 +[#5]: https://github.com/rust-windowing/winit/issues/5 +[#63]: https://github.com/rust-windowing/winit/issues/63 +[#720]: https://github.com/rust-windowing/winit/issues/720 +[#721]: https://github.com/rust-windowing/winit/issues/721 +[#750]: https://github.com/rust-windowing/winit/issues/750 +[#804]: https://github.com/rust-windowing/winit/issues/804 +[#812]: https://github.com/rust-windowing/winit/issues/812 diff --git a/third_party/cargo/vendor/winit-0.22.0/HALL_OF_CHAMPIONS.md b/third_party/cargo/vendor/winit-0.22.0/HALL_OF_CHAMPIONS.md new file mode 100644 index 0000000..946f5eb --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/HALL_OF_CHAMPIONS.md @@ -0,0 +1,14 @@ +# Hall of Champions + +The Winit maintainers would like to recognize the following former Winit +contributors, without whom Winit would not exist in its current form. We thank +them deeply for their time and efforts, and wish them best of luck in their +future endeavors: + +* [@tomaka]: For creating the Winit project and guiding it through its early + years of existence. +* [@francesca64]: For taking over the responsibility of maintaining almost every + Winit backend, and standardizing HiDPI support across all of them + +[@tomaka]: https://github.com/tomaka +[@francesca64]: https://github.com/francesca64 diff --git a/third_party/cargo/vendor/winit-0.18.1/LICENSE b/third_party/cargo/vendor/winit-0.22.0/LICENSE similarity index 100% rename from third_party/cargo/vendor/winit-0.18.1/LICENSE rename to third_party/cargo/vendor/winit-0.22.0/LICENSE diff --git a/third_party/cargo/vendor/winit-0.22.0/README.md b/third_party/cargo/vendor/winit-0.22.0/README.md new file mode 100644 index 0000000..cd8e837 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/README.md @@ -0,0 +1,79 @@ +# winit - Cross-platform window creation and management in Rust + +[![Crates.io](https://img.shields.io/crates/v/winit.svg)](https://crates.io/crates/winit) +[![Docs.rs](https://docs.rs/winit/badge.svg)](https://docs.rs/winit) +[![Build Status](https://travis-ci.org/rust-windowing/winit.svg?branch=master)](https://travis-ci.org/rust-windowing/winit) +[![Build status](https://ci.appveyor.com/api/projects/status/hr89but4x1n3dphq/branch/master?svg=true)](https://ci.appveyor.com/project/Osspial/winit/branch/master) + +```toml +[dependencies] +winit = "0.22.0" +``` + +## [Documentation](https://docs.rs/winit) + +For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md). + +For features _outside_ the scope of winit, see [Missing features provided by other crates](https://github.com/rust-windowing/winit/wiki/Missing-features-provided-by-other-crates) in the wiki. + +## Contact Us + +Join us in any of these: + +[![Freenode](https://img.shields.io/badge/freenode.net-%23glutin-red.svg)](http://webchat.freenode.net?channels=%23glutin&uio=MTY9dHJ1ZSYyPXRydWUmND10cnVlJjExPTE4NSYxMj10cnVlJjE1PXRydWU7a) +[![Matrix](https://img.shields.io/badge/Matrix-%23Glutin%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#Glutin:matrix.org) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tomaka/glutin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## Usage + +Winit is a window creation and management library. It can create windows and lets you handle +events (for example: the window being resized, a key being pressed, a mouse movement, etc.) +produced by window. + +Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to +show something on the window you need to use the platform-specific getters provided by winit, or +another library. + +```rust +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + } if window_id == window.id() => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} +``` + +Winit is only officially supported on the latest stable version of the Rust compiler. + +### Cargo Features + +Winit provides the following features, which can be enabled in your `Cargo.toml` file: +* `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). + +### Platform-specific usage + +#### WebAssembly + +Building a binary will yield a `.js` file. In order to use it in an HTML file, you need to: + +- Put a `` element somewhere. A canvas corresponds to a winit "window". +- Write a Javascript code that creates a global variable named `Module`. Set `Module.canvas` to + the element of the `` element (in the example you would retrieve it via `document.getElementById("my_id")`). + More information [here](https://kripken.github.io/emscripten-site/docs/api_reference/module.html). +- Make sure that you insert the `.js` file generated by Rust after the `Module` variable is created. diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/control_flow.rs b/third_party/cargo/vendor/winit-0.22.0/examples/control_flow.rs new file mode 100644 index 0000000..13b5bcf --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/control_flow.rs @@ -0,0 +1,119 @@ +use std::{thread, time}; + +use winit::{ + event::{Event, KeyboardInput, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + Wait, + WaitUntil, + Poll, +} + +const WAIT_TIME: time::Duration = time::Duration::from_millis(100); +const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100); + +fn main() { + simple_logger::init().unwrap(); + + println!("Press '1' to switch to Wait mode."); + println!("Press '2' to switch to WaitUntil mode."); + println!("Press '3' to switch to Poll mode."); + println!("Press 'R' to toggle request_redraw() calls."); + println!("Press 'Esc' to close the window."); + + let event_loop = EventLoop::new(); + let window = WindowBuilder::new() + .with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.") + .build(&event_loop) + .unwrap(); + + let mut mode = Mode::Wait; + let mut request_redraw = false; + let mut wait_cancelled = false; + let mut close_requested = false; + + event_loop.run(move |event, _, control_flow| { + use winit::event::{ElementState, StartCause, VirtualKeyCode}; + println!("{:?}", event); + match event { + Event::NewEvents(start_cause) => { + wait_cancelled = mode == Mode::WaitUntil; + match start_cause { + StartCause::ResumeTimeReached { + start: _, + requested_resume: _, + } => { + wait_cancelled = false; + } + _ => (), + } + } + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => { + close_requested = true; + } + WindowEvent::KeyboardInput { + input: + KeyboardInput { + virtual_keycode: Some(virtual_code), + state: ElementState::Pressed, + .. + }, + .. + } => match virtual_code { + VirtualKeyCode::Key1 => { + mode = Mode::Wait; + println!("\nmode: {:?}\n", mode); + } + VirtualKeyCode::Key2 => { + mode = Mode::WaitUntil; + println!("\nmode: {:?}\n", mode); + } + VirtualKeyCode::Key3 => { + mode = Mode::Poll; + println!("\nmode: {:?}\n", mode); + } + VirtualKeyCode::R => { + request_redraw = !request_redraw; + println!("\nrequest_redraw: {}\n", request_redraw); + } + VirtualKeyCode::Escape => { + close_requested = true; + } + _ => (), + }, + _ => (), + }, + Event::MainEventsCleared => { + if request_redraw && !wait_cancelled && !close_requested { + window.request_redraw(); + } + if close_requested { + *control_flow = ControlFlow::Exit; + } + } + Event::RedrawRequested(_window_id) => {} + Event::RedrawEventsCleared => { + *control_flow = match mode { + Mode::Wait => ControlFlow::Wait, + Mode::WaitUntil => { + if wait_cancelled { + *control_flow + } else { + ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME) + } + } + Mode::Poll => { + thread::sleep(POLL_SLEEP_TIME); + ControlFlow::Poll + } + }; + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/cursor.rs b/third_party/cargo/vendor/winit-0.22.0/examples/cursor.rs new file mode 100644 index 0000000..de45ada --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/cursor.rs @@ -0,0 +1,88 @@ +use winit::{ + event::{ElementState, Event, KeyboardInput, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::{CursorIcon, WindowBuilder}, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new().build(&event_loop).unwrap(); + window.set_title("A fantastic window!"); + + let mut cursor_idx = 0; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: + WindowEvent::KeyboardInput { + input: + KeyboardInput { + state: ElementState::Pressed, + .. + }, + .. + }, + .. + } => { + println!("Setting cursor to \"{:?}\"", CURSORS[cursor_idx]); + window.set_cursor_icon(CURSORS[cursor_idx]); + if cursor_idx < CURSORS.len() - 1 { + cursor_idx += 1; + } else { + cursor_idx = 0; + } + } + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => { + *control_flow = ControlFlow::Exit; + return; + } + _ => (), + } + }); +} + +const CURSORS: &[CursorIcon] = &[ + CursorIcon::Default, + CursorIcon::Crosshair, + CursorIcon::Hand, + CursorIcon::Arrow, + CursorIcon::Move, + CursorIcon::Text, + CursorIcon::Wait, + CursorIcon::Help, + CursorIcon::Progress, + CursorIcon::NotAllowed, + CursorIcon::ContextMenu, + CursorIcon::Cell, + CursorIcon::VerticalText, + CursorIcon::Alias, + CursorIcon::Copy, + CursorIcon::NoDrop, + CursorIcon::Grab, + CursorIcon::Grabbing, + CursorIcon::AllScroll, + CursorIcon::ZoomIn, + CursorIcon::ZoomOut, + CursorIcon::EResize, + CursorIcon::NResize, + CursorIcon::NeResize, + CursorIcon::NwResize, + CursorIcon::SResize, + CursorIcon::SeResize, + CursorIcon::SwResize, + CursorIcon::WResize, + CursorIcon::EwResize, + CursorIcon::NsResize, + CursorIcon::NeswResize, + CursorIcon::NwseResize, + CursorIcon::ColResize, + CursorIcon::RowResize, +]; diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/cursor_grab.rs b/third_party/cargo/vendor/winit-0.22.0/examples/cursor_grab.rs new file mode 100644 index 0000000..317577e --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/cursor_grab.rs @@ -0,0 +1,55 @@ +use winit::{ + event::{DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("Super Cursor Grab'n'Hide Simulator 9000") + .build(&event_loop) + .unwrap(); + + let mut modifiers = ModifiersState::default(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::KeyboardInput { + input: + KeyboardInput { + state: ElementState::Released, + virtual_keycode: Some(key), + .. + }, + .. + } => { + use winit::event::VirtualKeyCode::*; + match key { + Escape => *control_flow = ControlFlow::Exit, + G => window.set_cursor_grab(!modifiers.shift()).unwrap(), + H => window.set_cursor_visible(modifiers.shift()), + _ => (), + } + } + WindowEvent::ModifiersChanged(m) => modifiers = m, + _ => (), + }, + Event::DeviceEvent { event, .. } => match event { + DeviceEvent::MouseMotion { delta } => println!("mouse moved: {:?}", delta), + DeviceEvent::Button { button, state } => match state { + ElementState::Pressed => println!("mouse button {} pressed", button), + ElementState::Released => println!("mouse button {} released", button), + }, + _ => (), + }, + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/custom_events.rs b/third_party/cargo/vendor/winit-0.22.0/examples/custom_events.rs new file mode 100644 index 0000000..c59299c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/custom_events.rs @@ -0,0 +1,52 @@ +#[cfg(not(target_arch = "wasm32"))] +fn main() { + use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, + }; + + #[derive(Debug, Clone, Copy)] + enum CustomEvent { + Timer, + } + + simple_logger::init().unwrap(); + let event_loop = EventLoop::::with_user_event(); + + let _window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + // `EventLoopProxy` allows you to dispatch custom events to the main Winit event + // loop from any thread. + let event_loop_proxy = event_loop.create_proxy(); + + std::thread::spawn(move || { + // Wake up the `event_loop` once every second and dispatch a custom event + // from a different thread. + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + event_loop_proxy.send_event(CustomEvent::Timer).ok(); + } + }); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::UserEvent(event) => println!("user event: {:?}", event), + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn main() { + panic!("This example is not supported on web."); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/fullscreen.rs b/third_party/cargo/vendor/winit-0.22.0/examples/fullscreen.rs new file mode 100644 index 0000000..4cdb7b6 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/fullscreen.rs @@ -0,0 +1,117 @@ +use std::io::{stdin, stdout, Write}; +use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}; +use winit::event_loop::{ControlFlow, EventLoop}; +use winit::monitor::{MonitorHandle, VideoMode}; +use winit::window::{Fullscreen, WindowBuilder}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + print!("Please choose the fullscreen mode: (1) exclusive, (2) borderless: "); + stdout().flush().unwrap(); + + let mut num = String::new(); + stdin().read_line(&mut num).unwrap(); + let num = num.trim().parse().ok().expect("Please enter a number"); + + let fullscreen = Some(match num { + 1 => Fullscreen::Exclusive(prompt_for_video_mode(&prompt_for_monitor(&event_loop))), + 2 => Fullscreen::Borderless(prompt_for_monitor(&event_loop)), + _ => panic!("Please enter a valid number"), + }); + + let mut is_maximized = false; + let mut decorations = true; + + let window = WindowBuilder::new() + .with_title("Hello world!") + .with_fullscreen(fullscreen.clone()) + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::KeyboardInput { + input: + KeyboardInput { + virtual_keycode: Some(virtual_code), + state, + .. + }, + .. + } => match (virtual_code, state) { + (VirtualKeyCode::Escape, _) => *control_flow = ControlFlow::Exit, + (VirtualKeyCode::F, ElementState::Pressed) => { + if window.fullscreen().is_some() { + window.set_fullscreen(None); + } else { + window.set_fullscreen(fullscreen.clone()); + } + } + (VirtualKeyCode::S, ElementState::Pressed) => { + println!("window.fullscreen {:?}", window.fullscreen()); + } + (VirtualKeyCode::M, ElementState::Pressed) => { + is_maximized = !is_maximized; + window.set_maximized(is_maximized); + } + (VirtualKeyCode::D, ElementState::Pressed) => { + decorations = !decorations; + window.set_decorations(decorations); + } + _ => (), + }, + _ => (), + }, + _ => {} + } + }); +} + +// Enumerate monitors and prompt user to choose one +fn prompt_for_monitor(event_loop: &EventLoop<()>) -> MonitorHandle { + for (num, monitor) in event_loop.available_monitors().enumerate() { + println!("Monitor #{}: {:?}", num, monitor.name()); + } + + print!("Please write the number of the monitor to use: "); + stdout().flush().unwrap(); + + let mut num = String::new(); + stdin().read_line(&mut num).unwrap(); + let num = num.trim().parse().ok().expect("Please enter a number"); + let monitor = event_loop + .available_monitors() + .nth(num) + .expect("Please enter a valid ID"); + + println!("Using {:?}", monitor.name()); + + monitor +} + +fn prompt_for_video_mode(monitor: &MonitorHandle) -> VideoMode { + for (i, video_mode) in monitor.video_modes().enumerate() { + println!("Video mode #{}: {}", i, video_mode); + } + + print!("Please write the number of the video mode to use: "); + stdout().flush().unwrap(); + + let mut num = String::new(); + stdin().read_line(&mut num).unwrap(); + let num = num.trim().parse().ok().expect("Please enter a number"); + let video_mode = monitor + .video_modes() + .nth(num) + .expect("Please enter a valid ID"); + + println!("Using {}", video_mode); + + video_mode +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/handling_close.rs b/third_party/cargo/vendor/winit-0.22.0/examples/handling_close.rs new file mode 100644 index 0000000..cbd5705 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/handling_close.rs @@ -0,0 +1,83 @@ +use winit::{ + event::{Event, KeyboardInput, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let _window = WindowBuilder::new() + .with_title("Your faithful window") + .build(&event_loop) + .unwrap(); + + let mut close_requested = false; + + event_loop.run(move |event, _, control_flow| { + use winit::event::{ + ElementState::Released, + VirtualKeyCode::{N, Y}, + }; + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => { + match event { + WindowEvent::CloseRequested => { + // `CloseRequested` is sent when the close button on the window is pressed (or + // through whatever other mechanisms the window manager provides for closing a + // window). If you don't handle this event, the close button won't actually do + // anything. + + // A common thing to do here is prompt the user if they have unsaved work. + // Creating a proper dialog box for that is far beyond the scope of this + // example, so here we'll just respond to the Y and N keys. + println!("Are you ready to bid your window farewell? [Y/N]"); + close_requested = true; + + // In applications where you can safely close the window without further + // action from the user, this is generally where you'd handle cleanup before + // closing the window. How to close the window is detailed in the handler for + // the Y key. + } + WindowEvent::KeyboardInput { + input: + KeyboardInput { + virtual_keycode: Some(virtual_code), + state: Released, + .. + }, + .. + } => { + match virtual_code { + Y => { + if close_requested { + // This is where you'll want to do any cleanup you need. + println!("Buh-bye!"); + + // For a single-window application like this, you'd normally just + // break out of the event loop here. If you wanted to keep running the + // event loop (i.e. if it's a multi-window application), you need to + // drop the window. That closes it, and results in `Destroyed` being + // sent. + *control_flow = ControlFlow::Exit; + } + } + N => { + if close_requested { + println!("Your window will continue to stay by your side."); + close_requested = false; + } + } + _ => (), + } + } + _ => (), + } + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.18.1/examples/icon.png b/third_party/cargo/vendor/winit-0.22.0/examples/icon.png similarity index 100% rename from third_party/cargo/vendor/winit-0.18.1/examples/icon.png rename to third_party/cargo/vendor/winit-0.22.0/examples/icon.png diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/min_max_size.rs b/third_party/cargo/vendor/winit-0.22.0/examples/min_max_size.rs new file mode 100644 index 0000000..f4fd00c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/min_max_size.rs @@ -0,0 +1,29 @@ +use winit::{ + dpi::LogicalSize, + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + window.set_min_inner_size(Some(LogicalSize::new(400.0, 200.0))); + window.set_max_inner_size(Some(LogicalSize::new(800.0, 400.0))); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + println!("{:?}", event); + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/minimize.rs b/third_party/cargo/vendor/winit-0.22.0/examples/minimize.rs new file mode 100644 index 0000000..871cfe2 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/minimize.rs @@ -0,0 +1,40 @@ +extern crate winit; + +use winit::event::{Event, VirtualKeyCode, WindowEvent}; +use winit::event_loop::{ControlFlow, EventLoop}; +use winit::window::WindowBuilder; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + + // Keyboard input event to handle minimize via a hotkey + Event::WindowEvent { + event: WindowEvent::KeyboardInput { input, .. }, + window_id, + } => { + if window_id == window.id() { + // Pressing the 'M' key will minimize the window + if input.virtual_keycode == Some(VirtualKeyCode::M) { + window.set_minimized(true); + } + } + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/monitor_list.rs b/third_party/cargo/vendor/winit-0.22.0/examples/monitor_list.rs new file mode 100644 index 0000000..66f48ba --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/monitor_list.rs @@ -0,0 +1,10 @@ +use winit::{event_loop::EventLoop, window::WindowBuilder}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + let window = WindowBuilder::new().build(&event_loop).unwrap(); + + dbg!(window.available_monitors().collect::>()); + dbg!(window.primary_monitor()); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/multithreaded.rs b/third_party/cargo/vendor/winit-0.22.0/examples/multithreaded.rs new file mode 100644 index 0000000..60f9d80 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/multithreaded.rs @@ -0,0 +1,185 @@ +#[cfg(not(target_arch = "wasm32"))] +fn main() { + use std::{collections::HashMap, sync::mpsc, thread, time::Duration}; + + use winit::{ + dpi::{PhysicalPosition, PhysicalSize, Position, Size}, + event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::{CursorIcon, Fullscreen, WindowBuilder}, + }; + + const WINDOW_COUNT: usize = 3; + const WINDOW_SIZE: PhysicalSize = PhysicalSize::new(600, 400); + + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + let mut window_senders = HashMap::with_capacity(WINDOW_COUNT); + for _ in 0..WINDOW_COUNT { + let window = WindowBuilder::new() + .with_inner_size(WINDOW_SIZE) + .build(&event_loop) + .unwrap(); + + let mut video_modes: Vec<_> = window.current_monitor().video_modes().collect(); + let mut video_mode_id = 0usize; + + let (tx, rx) = mpsc::channel(); + window_senders.insert(window.id(), tx); + thread::spawn(move || { + while let Ok(event) = rx.recv() { + match event { + WindowEvent::Moved { .. } => { + // We need to update our chosen video mode if the window + // was moved to an another monitor, so that the window + // appears on this monitor instead when we go fullscreen + let previous_video_mode = video_modes.iter().cloned().nth(video_mode_id); + video_modes = window.current_monitor().video_modes().collect(); + video_mode_id = video_mode_id.min(video_modes.len()); + let video_mode = video_modes.iter().nth(video_mode_id); + + // Different monitors may support different video modes, + // and the index we chose previously may now point to a + // completely different video mode, so notify the user + if video_mode != previous_video_mode.as_ref() { + println!( + "Window moved to another monitor, picked video mode: {}", + video_modes.iter().nth(video_mode_id).unwrap() + ); + } + } + #[allow(deprecated)] + WindowEvent::KeyboardInput { + input: + KeyboardInput { + state: ElementState::Released, + virtual_keycode: Some(key), + modifiers, + .. + }, + .. + } => { + window.set_title(&format!("{:?}", key)); + let state = !modifiers.shift(); + use VirtualKeyCode::*; + match key { + A => window.set_always_on_top(state), + C => window.set_cursor_icon(match state { + true => CursorIcon::Progress, + false => CursorIcon::Default, + }), + D => window.set_decorations(!state), + // Cycle through video modes + Right | Left => { + video_mode_id = match key { + Left => video_mode_id.saturating_sub(1), + Right => (video_modes.len() - 1).min(video_mode_id + 1), + _ => unreachable!(), + }; + println!( + "Picking video mode: {}", + video_modes.iter().nth(video_mode_id).unwrap() + ); + } + F => window.set_fullscreen(match (state, modifiers.alt()) { + (true, false) => { + Some(Fullscreen::Borderless(window.current_monitor())) + } + (true, true) => Some(Fullscreen::Exclusive( + video_modes.iter().nth(video_mode_id).unwrap().clone(), + )), + (false, _) => None, + }), + G => window.set_cursor_grab(state).unwrap(), + H => window.set_cursor_visible(!state), + I => { + println!("Info:"); + println!("-> outer_position : {:?}", window.outer_position()); + println!("-> inner_position : {:?}", window.inner_position()); + println!("-> outer_size : {:?}", window.outer_size()); + println!("-> inner_size : {:?}", window.inner_size()); + println!("-> fullscreen : {:?}", window.fullscreen()); + } + L => window.set_min_inner_size(match state { + true => Some(WINDOW_SIZE), + false => None, + }), + M => window.set_maximized(state), + P => window.set_outer_position({ + let mut position = window.outer_position().unwrap(); + let sign = if state { 1 } else { -1 }; + position.x += 10 * sign; + position.y += 10 * sign; + position + }), + Q => window.request_redraw(), + R => window.set_resizable(state), + S => window.set_inner_size(match state { + true => PhysicalSize::new( + WINDOW_SIZE.width + 100, + WINDOW_SIZE.height + 100, + ), + false => WINDOW_SIZE, + }), + W => { + if let Size::Physical(size) = WINDOW_SIZE.into() { + window + .set_cursor_position(Position::Physical( + PhysicalPosition::new( + size.width as i32 / 2, + size.height as i32 / 2, + ), + )) + .unwrap() + } + } + Z => { + window.set_visible(false); + thread::sleep(Duration::from_secs(1)); + window.set_visible(true); + } + _ => (), + } + } + _ => (), + } + } + }); + } + event_loop.run(move |event, _event_loop, control_flow| { + *control_flow = match !window_senders.is_empty() { + true => ControlFlow::Wait, + false => ControlFlow::Exit, + }; + match event { + Event::WindowEvent { event, window_id } => match event { + WindowEvent::CloseRequested + | WindowEvent::Destroyed + | WindowEvent::KeyboardInput { + input: + KeyboardInput { + state: ElementState::Released, + virtual_keycode: Some(VirtualKeyCode::Escape), + .. + }, + .. + } => { + window_senders.remove(&window_id); + } + _ => { + if let Some(tx) = window_senders.get(&window_id) { + if let Some(event) = event.to_static() { + tx.send(event).unwrap(); + } + } + } + }, + _ => (), + } + }) +} + +#[cfg(target_arch = "wasm32")] +fn main() { + panic!("Example not supported on Wasm"); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/multiwindow.rs b/third_party/cargo/vendor/winit-0.22.0/examples/multiwindow.rs new file mode 100644 index 0000000..01c91bb --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/multiwindow.rs @@ -0,0 +1,51 @@ +use std::collections::HashMap; +use winit::{ + event::{ElementState, Event, KeyboardInput, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::Window, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let mut windows = HashMap::new(); + for _ in 0..3 { + let window = Window::new(&event_loop).unwrap(); + windows.insert(window.id(), window); + } + + event_loop.run(move |event, event_loop, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, window_id } => { + match event { + WindowEvent::CloseRequested => { + println!("Window {:?} has received the signal to close", window_id); + + // This drops the window, causing it to close. + windows.remove(&window_id); + + if windows.is_empty() { + *control_flow = ControlFlow::Exit; + } + } + WindowEvent::KeyboardInput { + input: + KeyboardInput { + state: ElementState::Pressed, + .. + }, + .. + } => { + let window = Window::new(&event_loop).unwrap(); + windows.insert(window.id(), window); + } + _ => (), + } + } + _ => (), + } + }) +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw.rs b/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw.rs new file mode 100644 index 0000000..5d761ae --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw.rs @@ -0,0 +1,38 @@ +use winit::{ + event::{ElementState, Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + println!("{:?}", event); + + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::MouseInput { + state: ElementState::Released, + .. + } => { + window.request_redraw(); + } + _ => (), + }, + Event::RedrawRequested(_) => { + println!("\nredrawing!\n"); + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw_threaded.rs b/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw_threaded.rs new file mode 100644 index 0000000..341612c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/request_redraw_threaded.rs @@ -0,0 +1,39 @@ +use std::{thread, time}; + +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + thread::spawn(move || loop { + thread::sleep(time::Duration::from_secs(1)); + window.request_redraw(); + }); + + event_loop.run(move |event, _, control_flow| { + println!("{:?}", event); + + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + _ => (), + }, + Event::RedrawRequested(_) => { + println!("\nredrawing!\n"); + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/resizable.rs b/third_party/cargo/vendor/winit-0.22.0/examples/resizable.rs new file mode 100644 index 0000000..6a90391 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/resizable.rs @@ -0,0 +1,45 @@ +use winit::{ + dpi::LogicalSize, + event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let mut resizable = false; + + let window = WindowBuilder::new() + .with_title("Hit space to toggle resizability.") + .with_inner_size(LogicalSize::new(400.0, 200.0)) + .with_resizable(resizable) + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::WindowEvent { event, .. } => match event { + WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, + WindowEvent::KeyboardInput { + input: + KeyboardInput { + virtual_keycode: Some(VirtualKeyCode::Space), + state: ElementState::Released, + .. + }, + .. + } => { + resizable = !resizable; + println!("Resizable: {}", resizable); + window.set_resizable(resizable); + } + _ => (), + }, + _ => (), + }; + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/timer.rs b/third_party/cargo/vendor/winit-0.22.0/examples/timer.rs new file mode 100644 index 0000000..52a1444 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/timer.rs @@ -0,0 +1,38 @@ +use instant::Instant; +use std::time::Duration; +use winit::{ + event::{Event, StartCause, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let _window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + let timer_length = Duration::new(1, 0); + + event_loop.run(move |event, _, control_flow| { + println!("{:?}", event); + + match event { + Event::NewEvents(StartCause::Init) => { + *control_flow = ControlFlow::WaitUntil(Instant::now() + timer_length) + } + Event::NewEvents(StartCause::ResumeTimeReached { .. }) => { + *control_flow = ControlFlow::WaitUntil(Instant::now() + timer_length); + println!("\nTimer\n"); + } + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/transparent.rs b/third_party/cargo/vendor/winit-0.22.0/examples/transparent.rs new file mode 100644 index 0000000..78e3c4d --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/transparent.rs @@ -0,0 +1,31 @@ +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_decorations(false) + .with_transparent(true) + .build(&event_loop) + .unwrap(); + + window.set_title("A fantastic window!"); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + println!("{:?}", event); + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/video_modes.rs b/third_party/cargo/vendor/winit-0.22.0/examples/video_modes.rs new file mode 100644 index 0000000..366c519 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/video_modes.rs @@ -0,0 +1,13 @@ +use winit::event_loop::EventLoop; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + let monitor = event_loop.primary_monitor(); + + println!("Listing available video modes:"); + + for mode in monitor.video_modes() { + println!("{}", mode); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/web.rs b/third_party/cargo/vendor/winit-0.22.0/examples/web.rs new file mode 100644 index 0000000..46b024c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/web.rs @@ -0,0 +1,74 @@ +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +pub fn main() { + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + #[cfg(feature = "web-sys")] + { + use winit::platform::web::WindowExtWebSys; + + let canvas = window.canvas(); + + let window = web_sys::window().unwrap(); + let document = window.document().unwrap(); + let body = document.body().unwrap(); + + body.append_child(&canvas) + .expect("Append canvas to HTML body"); + } + + #[cfg(feature = "stdweb")] + { + use std_web::web::INode; + use winit::platform::web::WindowExtStdweb; + + let canvas = window.canvas(); + + let document = std_web::web::document(); + let body: std_web::web::Node = document.body().expect("Get HTML body").into(); + + body.append_child(&canvas); + } + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + #[cfg(feature = "web-sys")] + log::debug!("{:?}", event); + + #[cfg(feature = "stdweb")] + std_web::console!(log, "%s", format!("{:?}", event)); + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + } if window_id == window.id() => *control_flow = ControlFlow::Exit, + Event::MainEventsCleared => { + window.request_redraw(); + } + _ => (), + } + }); +} + +#[cfg(feature = "web-sys")] +mod wasm { + use wasm_bindgen::prelude::*; + + #[wasm_bindgen(start)] + pub fn run() { + console_log::init_with_level(log::Level::Debug); + + super::main(); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/window.rs b/third_party/cargo/vendor/winit-0.22.0/examples/window.rs new file mode 100644 index 0000000..c028a50 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/window.rs @@ -0,0 +1,32 @@ +use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::WindowBuilder, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0)) + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + println!("{:?}", event); + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + } if window_id == window.id() => *control_flow = ControlFlow::Exit, + Event::MainEventsCleared => { + window.request_redraw(); + } + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/window_debug.rs b/third_party/cargo/vendor/winit-0.22.0/examples/window_debug.rs new file mode 100644 index 0000000..f6e960a --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/window_debug.rs @@ -0,0 +1,117 @@ +// This example is used by developers to test various window functions. + +use winit::{ + dpi::{LogicalSize, PhysicalSize}, + event::{DeviceEvent, ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + window::{Fullscreen, WindowBuilder}, +}; + +fn main() { + simple_logger::init().unwrap(); + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("A fantastic window!") + .with_inner_size(LogicalSize::new(100.0, 100.0)) + .build(&event_loop) + .unwrap(); + + eprintln!("debugging keys:"); + eprintln!(" (E) Enter exclusive fullscreen"); + eprintln!(" (F) Toggle borderless fullscreen"); + eprintln!(" (M) Toggle minimized"); + eprintln!(" (Q) Quit event loop"); + eprintln!(" (V) Toggle visibility"); + eprintln!(" (X) Toggle maximized"); + + let mut minimized = false; + let mut maximized = false; + let mut visible = true; + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + match event { + Event::DeviceEvent { + event: + DeviceEvent::Key(KeyboardInput { + virtual_keycode: Some(key), + state: ElementState::Pressed, + .. + }), + .. + } => match key { + VirtualKeyCode::M => { + if minimized { + minimized = !minimized; + window.set_minimized(minimized); + } + } + VirtualKeyCode::V => { + if !visible { + visible = !visible; + window.set_visible(visible); + } + } + _ => (), + }, + Event::WindowEvent { + event: WindowEvent::KeyboardInput { input, .. }, + .. + } => match input { + KeyboardInput { + virtual_keycode: Some(key), + state: ElementState::Pressed, + .. + } => match key { + VirtualKeyCode::E => { + fn area(size: PhysicalSize) -> u32 { + size.width * size.height + } + + let monitor = window.current_monitor(); + if let Some(mode) = monitor + .video_modes() + .max_by(|a, b| area(a.size()).cmp(&area(b.size()))) + { + window.set_fullscreen(Some(Fullscreen::Exclusive(mode))); + } else { + eprintln!("no video modes available"); + } + } + VirtualKeyCode::F => { + if window.fullscreen().is_some() { + window.set_fullscreen(None); + } else { + let monitor = window.current_monitor(); + window.set_fullscreen(Some(Fullscreen::Borderless(monitor))); + } + } + VirtualKeyCode::M => { + minimized = !minimized; + window.set_minimized(minimized); + } + VirtualKeyCode::Q => { + *control_flow = ControlFlow::Exit; + } + VirtualKeyCode::V => { + visible = !visible; + window.set_visible(visible); + } + VirtualKeyCode::X => { + maximized = !maximized; + window.set_maximized(maximized); + } + _ => (), + }, + _ => (), + }, + Event::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + } if window_id == window.id() => *control_flow = ControlFlow::Exit, + _ => (), + } + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/window_icon.rs b/third_party/cargo/vendor/winit-0.22.0/examples/window_icon.rs new file mode 100644 index 0000000..734debf --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/window_icon.rs @@ -0,0 +1,56 @@ +extern crate image; +use std::path::Path; +use winit::{ + event::Event, + event_loop::{ControlFlow, EventLoop}, + window::{Icon, WindowBuilder}, +}; + +fn main() { + simple_logger::init().unwrap(); + + // You'll have to choose an icon size at your own discretion. On X11, the desired size varies + // by WM, and on Windows, you still have to account for screen scaling. Here we use 32px, + // since it seems to work well enough in most cases. Be careful about going too high, or + // you'll be bitten by the low-quality downscaling built into the WM. + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png"); + + let icon = load_icon(Path::new(path)); + + let event_loop = EventLoop::new(); + + let window = WindowBuilder::new() + .with_title("An iconic window!") + // At present, this only does anything on Windows and X11, so if you want to save load + // time, you can put icon loading behind a function that returns `None` on other platforms. + .with_window_icon(Some(icon)) + .build(&event_loop) + .unwrap(); + + event_loop.run(move |event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + if let Event::WindowEvent { event, .. } = event { + use winit::event::WindowEvent::*; + match event { + CloseRequested => *control_flow = ControlFlow::Exit, + DroppedFile(path) => { + window.set_window_icon(Some(load_icon(&path))); + } + _ => (), + } + } + }); +} + +fn load_icon(path: &Path) -> Icon { + let (icon_rgba, icon_width, icon_height) = { + let image = image::open(path) + .expect("Failed to open icon path") + .into_rgba(); + let (width, height) = image.dimensions(); + let rgba = image.into_raw(); + (rgba, width, height) + }; + Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") +} diff --git a/third_party/cargo/vendor/winit-0.22.0/examples/window_run_return.rs b/third_party/cargo/vendor/winit-0.22.0/examples/window_run_return.rs new file mode 100644 index 0000000..0112eb3 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/examples/window_run_return.rs @@ -0,0 +1,61 @@ +// Limit this example to only compatible platforms. +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +fn main() { + use std::{thread::sleep, time::Duration}; + use winit::{ + event::{Event, WindowEvent}, + event_loop::{ControlFlow, EventLoop}, + platform::desktop::EventLoopExtDesktop, + window::WindowBuilder, + }; + let mut event_loop = EventLoop::new(); + + simple_logger::init().unwrap(); + let _window = WindowBuilder::new() + .with_title("A fantastic window!") + .build(&event_loop) + .unwrap(); + + let mut quit = false; + + while !quit { + event_loop.run_return(|event, _, control_flow| { + *control_flow = ControlFlow::Wait; + + if let Event::WindowEvent { event, .. } = &event { + // Print only Window events to reduce noise + println!("{:?}", event); + } + + match event { + Event::WindowEvent { + event: WindowEvent::CloseRequested, + .. + } => { + quit = true; + } + Event::MainEventsCleared => { + *control_flow = ControlFlow::Exit; + } + _ => (), + } + }); + + // Sleep for 1/60 second to simulate rendering + println!("rendering"); + sleep(Duration::from_millis(16)); + } +} + +#[cfg(any(target_os = "ios", target_os = "android", target_arch = "wasm32"))] +fn main() { + println!("This platform doesn't support run_return."); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/rustfmt.toml b/third_party/cargo/vendor/winit-0.22.0/rustfmt.toml new file mode 100644 index 0000000..a069b43 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/rustfmt.toml @@ -0,0 +1,3 @@ +force_explicit_abi=true +use_field_init_shorthand=true +# merge_imports=true diff --git a/third_party/cargo/vendor/winit-0.22.0/src/dpi.rs b/third_party/cargo/vendor/winit-0.22.0/src/dpi.rs new file mode 100644 index 0000000..8a56ae6 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/dpi.rs @@ -0,0 +1,501 @@ +//! UI scaling is important, so read the docs for this module if you don't want to be confused. +//! +//! ## Why should I care about UI scaling? +//! +//! Modern computer screens don't have a consistent relationship between resolution and size. +//! 1920x1080 is a common resolution for both desktop and mobile screens, despite mobile screens +//! normally being less than a quarter the size of their desktop counterparts. What's more, neither +//! desktop nor mobile screens are consistent resolutions within their own size classes - common +//! mobile screens range from below 720p to above 1440p, and desktop screens range from 720p to 5K +//! and beyond. +//! +//! Given that, it's a mistake to assume that 2D content will only be displayed on screens with +//! a consistent pixel density. If you were to render a 96-pixel-square image on a 1080p screen, +//! then render the same image on a similarly-sized 4K screen, the 4K rendition would only take up +//! about a quarter of the physical space as it did on the 1080p screen. That issue is especially +//! problematic with text rendering, where quarter-sized text becomes a significant legibility +//! problem. +//! +//! Failure to account for the scale factor can create a significantly degraded user experience. +//! Most notably, it can make users feel like they have bad eyesight, which will potentially cause +//! them to think about growing elderly, resulting in them having an existential crisis. Once users +//! enter that state, they will no longer be focused on your application. +//! +//! ## How should I handle it? +//! +//! The solution to this problem is to account for the device's *scale factor*. The scale factor is +//! the factor UI elements should be scaled by to be consistent with the rest of the user's system - +//! for example, a button that's normally 50 pixels across would be 100 pixels across on a device +//! with a scale factor of `2.0`, or 75 pixels across with a scale factor of `1.5`. +//! +//! Many UI systems, such as CSS, expose DPI-dependent units like [points] or [picas]. That's +//! usually a mistake, since there's no consistent mapping between the scale factor and the screen's +//! actual DPI. Unless you're printing to a physical medium, you should work in scaled pixels rather +//! than any DPI-dependent units. +//! +//! ### Position and Size types +//! +//! Winit's `Physical(Position|Size)` types correspond with the actual pixels on the device, and the +//! `Logical(Position|Size)` types correspond to the physical pixels divided by the scale factor. +//! All of Winit's functions return physical types, but can take either logical or physical +//! coordinates as input, allowing you to use the most convenient coordinate system for your +//! particular application. +//! +//! Winit's position and size types types are generic over their exact pixel type, `P`, to allow the +//! API to have integer precision where appropriate (e.g. most window manipulation functions) and +//! floating precision when necessary (e.g. logical sizes for fractional scale factors and touch +//! input). If `P` is a floating-point type, please do not cast the values with `as {int}`. Doing so +//! will truncate the fractional part of the float, rather than properly round to the nearest +//! integer. Use the provided `cast` function or `From`/`Into` conversions, which handle the +//! rounding properly. Note that precision loss will still occur when rounding from a float to an +//! int, although rounding lessens the problem. +//! +//! ### Events +//! +//! Winit will dispatch a [`ScaleFactorChanged`](crate::event::WindowEvent::ScaleFactorChanged) +//! event whenever a window's scale factor has changed. This can happen if the user drags their +//! window from a standard-resolution monitor to a high-DPI monitor, or if the user changes their +//! DPI settings. This gives you a chance to rescale your application's UI elements and adjust how +//! the platform changes the window's size to reflect the new scale factor. If a window hasn't +//! received a [`ScaleFactorChanged`](crate::event::WindowEvent::ScaleFactorChanged) event, +//! then its scale factor is `1.0`. +//! +//! ## How is the scale factor calculated? +//! +//! Scale factor is calculated differently on different platforms: +//! +//! - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from the +//! display settings. While users are free to select any option they want, they're only given a +//! selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7, the scale factor is +//! global and changing it requires logging out. See [this article][windows_1] for technical +//! details. +//! - **macOS:** "retina displays" have a scale factor of 2.0. Otherwise, the scale factor is 1.0. +//! Intermediate scale factors are never used. It's possible for any display to use that 2.0 scale +//! factor, given the use of the command line. +//! - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit +//! currently uses a three-pronged approach: +//! + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable, if present. +//! + If not present, use the value set in `Xft.dpi` in Xresources. +//! + Otherwise, calcuate the scale factor based on the millimeter monitor dimensions provided by XRandR. +//! +//! If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use the +//! XRandR scaling method. Generally speaking, you should try to configure the standard system +//! variables to do what you want before resorting to `WINIT_X11_SCALE_FACTOR`. +//! - **Wayland:** On Wayland, scale factors are set per-screen by the server, and are always +//! integers (most often 1 or 2). +//! - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range +//! from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more +//! information. +//! - **Android:** Scale factors are set by the manufacturer to the value that best suits the +//! device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. +//! - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. +//! +//! [points]: https://en.wikipedia.org/wiki/Point_(typography) +//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography) +//! [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows +//! [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html +//! [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ +//! [android_1]: https://developer.android.com/training/multiscreen/screendensities + +pub trait Pixel: Copy + Into { + fn from_f64(f: f64) -> Self; + fn cast(self) -> P { + P::from_f64(self.into()) + } +} + +impl Pixel for u8 { + fn from_f64(f: f64) -> Self { + f.round() as u8 + } +} +impl Pixel for u16 { + fn from_f64(f: f64) -> Self { + f.round() as u16 + } +} +impl Pixel for u32 { + fn from_f64(f: f64) -> Self { + f.round() as u32 + } +} +impl Pixel for i8 { + fn from_f64(f: f64) -> Self { + f.round() as i8 + } +} +impl Pixel for i16 { + fn from_f64(f: f64) -> Self { + f.round() as i16 + } +} +impl Pixel for i32 { + fn from_f64(f: f64) -> Self { + f.round() as i32 + } +} +impl Pixel for f32 { + fn from_f64(f: f64) -> Self { + f as f32 + } +} +impl Pixel for f64 { + fn from_f64(f: f64) -> Self { + f + } +} + +/// Checks that the scale factor is a normal positive `f64`. +/// +/// All functions that take a scale factor assert that this will return `true`. If you're sourcing scale factors from +/// anywhere other than winit, it's recommended to validate them using this function before passing them to winit; +/// otherwise, you risk panics. +#[inline] +pub fn validate_scale_factor(scale_factor: f64) -> bool { + scale_factor.is_sign_positive() && scale_factor.is_normal() +} + +/// A position represented in logical pixels. +/// +/// The position is stored as floats, so please be careful. Casting floats to integers truncates the +/// fractional part, which can cause noticable issues. To help with that, an `Into<(i32, i32)>` +/// implementation is provided which does the rounding for you. +#[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct LogicalPosition

{ + pub x: P, + pub y: P, +} + +impl

LogicalPosition

{ + #[inline] + pub const fn new(x: P, y: P) -> Self { + LogicalPosition { x, y } + } +} + +impl LogicalPosition

{ + #[inline] + pub fn from_physical>, X: Pixel>( + physical: T, + scale_factor: f64, + ) -> Self { + physical.into().to_logical(scale_factor) + } + + #[inline] + pub fn to_physical(&self, scale_factor: f64) -> PhysicalPosition { + assert!(validate_scale_factor(scale_factor)); + let x = self.x.into() * scale_factor; + let y = self.y.into() * scale_factor; + PhysicalPosition::new(x, y).cast() + } + + #[inline] + pub fn cast(&self) -> LogicalPosition { + LogicalPosition { + x: self.x.cast(), + y: self.y.cast(), + } + } +} + +impl From<(X, X)> for LogicalPosition

{ + fn from((x, y): (X, X)) -> LogicalPosition

{ + LogicalPosition::new(x.cast(), y.cast()) + } +} + +impl Into<(X, X)> for LogicalPosition

{ + fn into(self: Self) -> (X, X) { + (self.x.cast(), self.y.cast()) + } +} + +impl From<[X; 2]> for LogicalPosition

{ + fn from([x, y]: [X; 2]) -> LogicalPosition

{ + LogicalPosition::new(x.cast(), y.cast()) + } +} + +impl Into<[X; 2]> for LogicalPosition

{ + fn into(self: Self) -> [X; 2] { + [self.x.cast(), self.y.cast()] + } +} + +/// A position represented in physical pixels. +#[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct PhysicalPosition

{ + pub x: P, + pub y: P, +} + +impl

PhysicalPosition

{ + #[inline] + pub const fn new(x: P, y: P) -> Self { + PhysicalPosition { x, y } + } +} + +impl PhysicalPosition

{ + #[inline] + pub fn from_logical>, X: Pixel>( + logical: T, + scale_factor: f64, + ) -> Self { + logical.into().to_physical(scale_factor) + } + + #[inline] + pub fn to_logical(&self, scale_factor: f64) -> LogicalPosition { + assert!(validate_scale_factor(scale_factor)); + let x = self.x.into() / scale_factor; + let y = self.y.into() / scale_factor; + LogicalPosition::new(x, y).cast() + } + + #[inline] + pub fn cast(&self) -> PhysicalPosition { + PhysicalPosition { + x: self.x.cast(), + y: self.y.cast(), + } + } +} + +impl From<(X, X)> for PhysicalPosition

{ + fn from((x, y): (X, X)) -> PhysicalPosition

{ + PhysicalPosition::new(x.cast(), y.cast()) + } +} + +impl Into<(X, X)> for PhysicalPosition

{ + fn into(self: Self) -> (X, X) { + (self.x.cast(), self.y.cast()) + } +} + +impl From<[X; 2]> for PhysicalPosition

{ + fn from([x, y]: [X; 2]) -> PhysicalPosition

{ + PhysicalPosition::new(x.cast(), y.cast()) + } +} + +impl Into<[X; 2]> for PhysicalPosition

{ + fn into(self: Self) -> [X; 2] { + [self.x.cast(), self.y.cast()] + } +} + +/// A size represented in logical pixels. +#[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct LogicalSize

{ + pub width: P, + pub height: P, +} + +impl

LogicalSize

{ + #[inline] + pub const fn new(width: P, height: P) -> Self { + LogicalSize { width, height } + } +} + +impl LogicalSize

{ + #[inline] + pub fn from_physical>, X: Pixel>( + physical: T, + scale_factor: f64, + ) -> Self { + physical.into().to_logical(scale_factor) + } + + #[inline] + pub fn to_physical(&self, scale_factor: f64) -> PhysicalSize { + assert!(validate_scale_factor(scale_factor)); + let width = self.width.into() * scale_factor; + let height = self.height.into() * scale_factor; + PhysicalSize::new(width, height).cast() + } + + #[inline] + pub fn cast(&self) -> LogicalSize { + LogicalSize { + width: self.width.cast(), + height: self.height.cast(), + } + } +} + +impl From<(X, X)> for LogicalSize

{ + fn from((x, y): (X, X)) -> LogicalSize

{ + LogicalSize::new(x.cast(), y.cast()) + } +} + +impl Into<(X, X)> for LogicalSize

{ + fn into(self: LogicalSize

) -> (X, X) { + (self.width.cast(), self.height.cast()) + } +} + +impl From<[X; 2]> for LogicalSize

{ + fn from([x, y]: [X; 2]) -> LogicalSize

{ + LogicalSize::new(x.cast(), y.cast()) + } +} + +impl Into<[X; 2]> for LogicalSize

{ + fn into(self: Self) -> [X; 2] { + [self.width.cast(), self.height.cast()] + } +} + +/// A size represented in physical pixels. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct PhysicalSize

{ + pub width: P, + pub height: P, +} + +impl

PhysicalSize

{ + #[inline] + pub const fn new(width: P, height: P) -> Self { + PhysicalSize { width, height } + } +} + +impl PhysicalSize

{ + #[inline] + pub fn from_logical>, X: Pixel>(logical: T, scale_factor: f64) -> Self { + logical.into().to_physical(scale_factor) + } + + #[inline] + pub fn to_logical(&self, scale_factor: f64) -> LogicalSize { + assert!(validate_scale_factor(scale_factor)); + let width = self.width.into() / scale_factor; + let height = self.height.into() / scale_factor; + LogicalSize::new(width, height).cast() + } + + #[inline] + pub fn cast(&self) -> PhysicalSize { + PhysicalSize { + width: self.width.cast(), + height: self.height.cast(), + } + } +} + +impl From<(X, X)> for PhysicalSize

{ + fn from((x, y): (X, X)) -> PhysicalSize

{ + PhysicalSize::new(x.cast(), y.cast()) + } +} + +impl Into<(X, X)> for PhysicalSize

{ + fn into(self: Self) -> (X, X) { + (self.width.cast(), self.height.cast()) + } +} + +impl From<[X; 2]> for PhysicalSize

{ + fn from([x, y]: [X; 2]) -> PhysicalSize

{ + PhysicalSize::new(x.cast(), y.cast()) + } +} + +impl Into<[X; 2]> for PhysicalSize

{ + fn into(self: Self) -> [X; 2] { + [self.width.cast(), self.height.cast()] + } +} + +/// A size that's either physical or logical. +#[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Size { + Physical(PhysicalSize), + Logical(LogicalSize), +} + +impl Size { + pub fn new>(size: S) -> Size { + size.into() + } + + pub fn to_logical(&self, scale_factor: f64) -> LogicalSize

{ + match *self { + Size::Physical(size) => size.to_logical(scale_factor), + Size::Logical(size) => size.cast(), + } + } + + pub fn to_physical(&self, scale_factor: f64) -> PhysicalSize

{ + match *self { + Size::Physical(size) => size.cast(), + Size::Logical(size) => size.to_physical(scale_factor), + } + } +} + +impl From> for Size { + #[inline] + fn from(size: PhysicalSize

) -> Size { + Size::Physical(size.cast()) + } +} + +impl From> for Size { + #[inline] + fn from(size: LogicalSize

) -> Size { + Size::Logical(size.cast()) + } +} + +/// A position that's either physical or logical. +#[derive(Debug, Copy, Clone, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Position { + Physical(PhysicalPosition), + Logical(LogicalPosition), +} + +impl Position { + pub fn new>(position: S) -> Position { + position.into() + } + + pub fn to_logical(&self, scale_factor: f64) -> LogicalPosition

{ + match *self { + Position::Physical(position) => position.to_logical(scale_factor), + Position::Logical(position) => position.cast(), + } + } + + pub fn to_physical(&self, scale_factor: f64) -> PhysicalPosition

{ + match *self { + Position::Physical(position) => position.cast(), + Position::Logical(position) => position.to_physical(scale_factor), + } + } +} + +impl From> for Position { + #[inline] + fn from(position: PhysicalPosition

) -> Position { + Position::Physical(position.cast()) + } +} + +impl From> for Position { + #[inline] + fn from(position: LogicalPosition

) -> Position { + Position::Logical(position.cast()) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/error.rs b/third_party/cargo/vendor/winit-0.22.0/src/error.rs new file mode 100644 index 0000000..c039f3b --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/error.rs @@ -0,0 +1,82 @@ +use std::{error, fmt}; + +use crate::platform_impl; + +/// An error whose cause it outside Winit's control. +#[derive(Debug)] +pub enum ExternalError { + /// The operation is not supported by the backend. + NotSupported(NotSupportedError), + /// The OS cannot perform the operation. + Os(OsError), +} + +/// The error type for when the requested operation is not supported by the backend. +#[derive(Clone)] +pub struct NotSupportedError { + _marker: (), +} + +/// The error type for when the OS cannot perform the requested operation. +#[derive(Debug)] +pub struct OsError { + line: u32, + file: &'static str, + error: platform_impl::OsError, +} + +impl NotSupportedError { + #[inline] + #[allow(dead_code)] + pub(crate) fn new() -> NotSupportedError { + NotSupportedError { _marker: () } + } +} + +impl OsError { + #[allow(dead_code)] + pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError { + OsError { line, file, error } + } +} + +#[allow(unused_macros)] +macro_rules! os_error { + ($error:expr) => {{ + crate::error::OsError::new(line!(), file!(), $error) + }}; +} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.pad(&format!( + "os error at {}:{}: {}", + self.file, self.line, self.error + )) + } +} + +impl fmt::Display for ExternalError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match self { + ExternalError::NotSupported(e) => e.fmt(f), + ExternalError::Os(e) => e.fmt(f), + } + } +} + +impl fmt::Debug for NotSupportedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.debug_struct("NotSupportedError").finish() + } +} + +impl fmt::Display for NotSupportedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.pad("the requested operation is not supported by Winit") + } +} + +impl error::Error for OsError {} +impl error::Error for ExternalError {} +impl error::Error for NotSupportedError {} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/event.rs b/third_party/cargo/vendor/winit-0.22.0/src/event.rs new file mode 100644 index 0000000..4756f3d --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/event.rs @@ -0,0 +1,945 @@ +//! The `Event` enum and assorted supporting types. +//! +//! These are sent to the closure given to [`EventLoop::run(...)`][event_loop_run], where they get +//! processed and used to modify the program state. For more details, see the root-level documentation. +//! +//! Some of these events represent different "parts" of a traditional event-handling loop. You could +//! approximate the basic ordering loop of [`EventLoop::run(...)`][event_loop_run] like this: +//! +//! ```rust,ignore +//! let mut control_flow = ControlFlow::Poll; +//! let mut start_cause = StartCause::Init; +//! +//! while control_flow != ControlFlow::Exit { +//! event_handler(NewEvents(start_cause), ..., &mut control_flow); +//! +//! for e in (window events, user events, device events) { +//! event_handler(e, ..., &mut control_flow); +//! } +//! event_handler(MainEventsCleared, ..., &mut control_flow); +//! +//! for w in (redraw windows) { +//! event_handler(RedrawRequested(w), ..., &mut control_flow); +//! } +//! event_handler(RedrawEventsCleared, ..., &mut control_flow); +//! +//! start_cause = wait_if_necessary(control_flow); +//! } +//! +//! event_handler(LoopDestroyed, ..., &mut control_flow); +//! ``` +//! +//! This leaves out timing details like `ControlFlow::WaitUntil` but hopefully +//! describes what happens in what order. +//! +//! [event_loop_run]: crate::event_loop::EventLoop::run +use instant::Instant; +use std::path::PathBuf; + +use crate::{ + dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}, + platform_impl, + window::{Theme, WindowId}, +}; + +/// Describes a generic event. +/// +/// See the module-level docs for more information on the event loop manages each event. +#[derive(Debug, PartialEq)] +pub enum Event<'a, T: 'static> { + /// Emitted when new events arrive from the OS to be processed. + /// + /// This event type is useful as a place to put code that should be done before you start + /// processing events, such as updating frame timing information for benchmarking or checking + /// the [`StartCause`][crate::event::StartCause] to see if a timer set by + /// [`ControlFlow::WaitUntil`](crate::event_loop::ControlFlow::WaitUntil) has elapsed. + NewEvents(StartCause), + + /// Emitted when the OS sends an event to a winit window. + WindowEvent { + window_id: WindowId, + event: WindowEvent<'a>, + }, + + /// Emitted when the OS sends an event to a device. + DeviceEvent { + device_id: DeviceId, + event: DeviceEvent, + }, + + /// Emitted when an event is sent from [`EventLoopProxy::send_event`](crate::event_loop::EventLoopProxy::send_event) + UserEvent(T), + + /// Emitted when the application has been suspended. + Suspended, + + /// Emitted when the application has been resumed. + Resumed, + + /// Emitted when all of the event loop's input events have been processed and redraw processing + /// is about to begin. + /// + /// This event is useful as a place to put your code that should be run after all + /// state-changing events have been handled and you want to do stuff (updating state, performing + /// calculations, etc) that happens as the "main body" of your event loop. If your program draws + /// graphics, it's usually better to do it in response to + /// [`Event::RedrawRequested`](crate::event::Event::RedrawRequested), which gets emitted + /// immediately after this event. + MainEventsCleared, + + /// Emitted after `MainEventsCleared` when a window should be redrawn. + /// + /// This gets triggered in two scenarios: + /// - The OS has performed an operation that's invalidated the window's contents (such as + /// resizing the window). + /// - The application has explicitly requested a redraw via + /// [`Window::request_redraw`](crate::window::Window::request_redraw). + /// + /// During each iteration of the event loop, Winit will aggregate duplicate redraw requests + /// into a single event, to help avoid duplicating rendering work. + RedrawRequested(WindowId), + + /// Emitted after all `RedrawRequested` events have been processed and control flow is about to + /// be taken away from the program. If there are no `RedrawRequested` events, it is emitted + /// immediately after `MainEventsCleared`. + /// + /// This event is useful for doing any cleanup or bookkeeping work after all the rendering + /// tasks have been completed. + RedrawEventsCleared, + + /// Emitted when the event loop is being shut down. + /// + /// This is irreversable - if this event is emitted, it is guaranteed to be the last event that + /// gets emitted. You generally want to treat this as an "do on quit" event. + LoopDestroyed, +} + +impl<'a, T> Event<'a, T> { + pub fn map_nonuser_event(self) -> Result, Event<'a, T>> { + use self::Event::*; + match self { + UserEvent(_) => Err(self), + WindowEvent { window_id, event } => Ok(WindowEvent { window_id, event }), + DeviceEvent { device_id, event } => Ok(DeviceEvent { device_id, event }), + NewEvents(cause) => Ok(NewEvents(cause)), + MainEventsCleared => Ok(MainEventsCleared), + RedrawRequested(wid) => Ok(RedrawRequested(wid)), + RedrawEventsCleared => Ok(RedrawEventsCleared), + LoopDestroyed => Ok(LoopDestroyed), + Suspended => Ok(Suspended), + Resumed => Ok(Resumed), + } + } + + /// If the event doesn't contain a reference, turn it into an event with a `'static` lifetime. + /// Otherwise, return `None`. + pub fn to_static(self) -> Option> { + use self::Event::*; + match self { + WindowEvent { window_id, event } => event + .to_static() + .map(|event| WindowEvent { window_id, event }), + UserEvent(event) => Some(UserEvent(event)), + DeviceEvent { device_id, event } => Some(DeviceEvent { device_id, event }), + NewEvents(cause) => Some(NewEvents(cause)), + MainEventsCleared => Some(MainEventsCleared), + RedrawRequested(wid) => Some(RedrawRequested(wid)), + RedrawEventsCleared => Some(RedrawEventsCleared), + LoopDestroyed => Some(LoopDestroyed), + Suspended => Some(Suspended), + Resumed => Some(Resumed), + } + } +} + +/// Describes the reason the event loop is resuming. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StartCause { + /// Sent if the time specified by `ControlFlow::WaitUntil` has been reached. Contains the + /// moment the timeout was requested and the requested resume time. The actual resume time is + /// guaranteed to be equal to or after the requested resume time. + ResumeTimeReached { + start: Instant, + requested_resume: Instant, + }, + + /// Sent if the OS has new events to send to the window, after a wait was requested. Contains + /// the moment the wait was requested and the resume time, if requested. + WaitCancelled { + start: Instant, + requested_resume: Option, + }, + + /// Sent if the event loop is being resumed after the loop's control flow was set to + /// `ControlFlow::Poll`. + Poll, + + /// Sent once, immediately after `run` is called. Indicates that the loop was just initialized. + Init, +} + +/// Describes an event from a `Window`. +#[derive(Debug, PartialEq)] +pub enum WindowEvent<'a> { + /// The size of the window has changed. Contains the client area's new dimensions. + Resized(PhysicalSize), + + /// The position of the window has changed. Contains the window's new position. + Moved(PhysicalPosition), + + /// The window has been requested to close. + CloseRequested, + + /// The window has been destroyed. + Destroyed, + + /// A file has been dropped into the window. + /// + /// When the user drops multiple files at once, this event will be emitted for each file + /// separately. + DroppedFile(PathBuf), + + /// A file is being hovered over the window. + /// + /// When the user hovers multiple files at once, this event will be emitted for each file + /// separately. + HoveredFile(PathBuf), + + /// A file was hovered, but has exited the window. + /// + /// There will be a single `HoveredFileCancelled` event triggered even if multiple files were + /// hovered. + HoveredFileCancelled, + + /// The window received a unicode character. + ReceivedCharacter(char), + + /// The window gained or lost focus. + /// + /// The parameter is true if the window has gained focus, and false if it has lost focus. + Focused(bool), + + /// An event from the keyboard has been received. + KeyboardInput { + device_id: DeviceId, + input: KeyboardInput, + /// If `true`, the event was generated synthetically by winit + /// in one of the following circumstances: + /// + /// * Synthetic key press events are generated for all keys pressed + /// when a window gains focus. Likewise, synthetic key release events + /// are generated for all keys pressed when a window goes out of focus. + /// ***Currently, this is only functional on X11 and Windows*** + /// + /// Otherwise, this value is always `false`. + is_synthetic: bool, + }, + + /// The keyboard modifiers have changed. + /// + /// Platform-specific behavior: + /// - **Web**: This API is currently unimplemented on the web. This isn't by design - it's an + /// issue, and it should get fixed - but it's the current state of the API. + ModifiersChanged(ModifiersState), + + /// The cursor has moved on the window. + CursorMoved { + device_id: DeviceId, + + /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range of this data is + /// limited by the display area and it may have been transformed by the OS to implement effects such as cursor + /// acceleration, it should not be used to implement non-cursor-like interactions such as 3D camera control. + position: PhysicalPosition, + #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] + modifiers: ModifiersState, + }, + + /// The cursor has entered the window. + CursorEntered { device_id: DeviceId }, + + /// The cursor has left the window. + CursorLeft { device_id: DeviceId }, + + /// A mouse wheel movement or touchpad scroll occurred. + MouseWheel { + device_id: DeviceId, + delta: MouseScrollDelta, + phase: TouchPhase, + #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] + modifiers: ModifiersState, + }, + + /// An mouse button press has been received. + MouseInput { + device_id: DeviceId, + state: ElementState, + button: MouseButton, + #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] + modifiers: ModifiersState, + }, + + /// Touchpad pressure event. + /// + /// At the moment, only supported on Apple forcetouch-capable macbooks. + /// The parameters are: pressure level (value between 0 and 1 representing how hard the touchpad + /// is being pressed) and stage (integer representing the click level). + TouchpadPressure { + device_id: DeviceId, + pressure: f32, + stage: i64, + }, + + /// Motion on some analog axis. May report data redundant to other, more specific events. + AxisMotion { + device_id: DeviceId, + axis: AxisId, + value: f64, + }, + + /// Touch event has been received + Touch(Touch), + + /// The window's scale factor has changed. + /// + /// The following user actions can cause DPI changes: + /// + /// * Changing the display's resolution. + /// * Changing the display's scale factor (e.g. in Control Panel on Windows). + /// * Moving the window to a display with a different scale factor. + /// + /// After this event callback has been processed, the window will be resized to whatever value + /// is pointed to by the `new_inner_size` reference. By default, this will contain the size suggested + /// by the OS, but it can be changed to any value. + /// + /// For more information about DPI in general, see the [`dpi`](crate::dpi) module. + ScaleFactorChanged { + scale_factor: f64, + new_inner_size: &'a mut PhysicalSize, + }, + + /// The system window theme has changed. + /// + /// Applications might wish to react to this to change the theme of the content of the window + /// when the system changes the window theme. + /// + /// At the moment this is only supported on Windows. + ThemeChanged(Theme), +} + +impl<'a> WindowEvent<'a> { + pub fn to_static(self) -> Option> { + use self::WindowEvent::*; + match self { + Resized(size) => Some(Resized(size)), + Moved(position) => Some(Moved(position)), + CloseRequested => Some(CloseRequested), + Destroyed => Some(Destroyed), + DroppedFile(file) => Some(DroppedFile(file)), + HoveredFile(file) => Some(HoveredFile(file)), + HoveredFileCancelled => Some(HoveredFileCancelled), + ReceivedCharacter(c) => Some(ReceivedCharacter(c)), + Focused(focused) => Some(Focused(focused)), + KeyboardInput { + device_id, + input, + is_synthetic, + } => Some(KeyboardInput { + device_id, + input, + is_synthetic, + }), + ModifiersChanged(modifiers) => Some(ModifiersChanged(modifiers)), + #[allow(deprecated)] + CursorMoved { + device_id, + position, + modifiers, + } => Some(CursorMoved { + device_id, + position, + modifiers, + }), + CursorEntered { device_id } => Some(CursorEntered { device_id }), + CursorLeft { device_id } => Some(CursorLeft { device_id }), + #[allow(deprecated)] + MouseWheel { + device_id, + delta, + phase, + modifiers, + } => Some(MouseWheel { + device_id, + delta, + phase, + modifiers, + }), + #[allow(deprecated)] + MouseInput { + device_id, + state, + button, + modifiers, + } => Some(MouseInput { + device_id, + state, + button, + modifiers, + }), + TouchpadPressure { + device_id, + pressure, + stage, + } => Some(TouchpadPressure { + device_id, + pressure, + stage, + }), + AxisMotion { + device_id, + axis, + value, + } => Some(AxisMotion { + device_id, + axis, + value, + }), + Touch(touch) => Some(Touch(touch)), + ThemeChanged(theme) => Some(ThemeChanged(theme)), + ScaleFactorChanged { .. } => None, + } + } +} + +/// Identifier of an input device. +/// +/// Whenever you receive an event arising from a particular input device, this event contains a `DeviceId` which +/// identifies its origin. Note that devices may be virtual (representing an on-screen cursor and keyboard focus) or +/// physical. Virtual devices typically aggregate inputs from multiple physical devices. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(pub(crate) platform_impl::DeviceId); + +impl DeviceId { + /// Returns a dummy `DeviceId`, useful for unit testing. The only guarantee made about the return + /// value of this function is that it will always be equal to itself and to future values returned + /// by this function. No other guarantees are made. This may be equal to a real `DeviceId`. + /// + /// **Passing this into a winit function will result in undefined behavior.** + pub unsafe fn dummy() -> Self { + DeviceId(platform_impl::DeviceId::dummy()) + } +} + +/// Represents raw hardware events that are not associated with any particular window. +/// +/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera or first-person +/// game controls. Many physical actions, such as mouse movement, can produce both device and window events. Because +/// window events typically arise from virtual devices (corresponding to GUI cursors and keyboard focus) the device IDs +/// may not match. +/// +/// Note that these events are delivered regardless of input focus. +#[derive(Clone, Debug, PartialEq)] +pub enum DeviceEvent { + Added, + Removed, + + /// Change in physical position of a pointing device. + /// + /// This represents raw, unfiltered physical motion. Not to be confused with `WindowEvent::CursorMoved`. + MouseMotion { + /// (x, y) change in position in unspecified units. + /// + /// Different devices may use different units. + delta: (f64, f64), + }, + + /// Physical scroll event + MouseWheel { + delta: MouseScrollDelta, + }, + + /// Motion on some analog axis. This event will be reported for all arbitrary input devices + /// that winit supports on this platform, including mouse devices. If the device is a mouse + /// device then this will be reported alongside the MouseMotion event. + Motion { + axis: AxisId, + value: f64, + }, + + Button { + button: ButtonId, + state: ElementState, + }, + + Key(KeyboardInput), + + Text { + codepoint: char, + }, +} + +/// Describes a keyboard input event. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct KeyboardInput { + /// Identifies the physical key pressed + /// + /// This should not change if the user adjusts the host's keyboard map. Use when the physical location of the + /// key is more important than the key's host GUI semantics, such as for movement controls in a first-person + /// game. + pub scancode: ScanCode, + + pub state: ElementState, + + /// Identifies the semantic meaning of the key + /// + /// Use when the semantics of the key are more important than the physical location of the key, such as when + /// implementing appropriate behavior for "page up." + pub virtual_keycode: Option, + + /// Modifier keys active at the time of this input. + /// + /// This is tracked internally to avoid tracking errors arising from modifier key state changes when events from + /// this device are not being delivered to the application, e.g. due to keyboard focus being elsewhere. + #[deprecated = "Deprecated in favor of WindowEvent::ModifiersChanged"] + pub modifiers: ModifiersState, +} + +/// Describes touch-screen input state. +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum TouchPhase { + Started, + Moved, + Ended, + Cancelled, +} + +/// Represents a touch event +/// +/// Every time the user touches the screen, a new `Start` event with an unique +/// identifier for the finger is generated. When the finger is lifted, an `End` +/// event is generated with the same finger id. +/// +/// After a `Start` event has been emitted, there may be zero or more `Move` +/// events when the finger is moved or the touch pressure changes. +/// +/// The finger id may be reused by the system after an `End` event. The user +/// should assume that a new `Start` event received with the same id has nothing +/// to do with the old finger and is a new finger. +/// +/// A `Cancelled` event is emitted when the system has canceled tracking this +/// touch, such as when the window loses focus, or on iOS if the user moves the +/// device against their face. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Touch { + pub device_id: DeviceId, + pub phase: TouchPhase, + pub location: PhysicalPosition, + /// Describes how hard the screen was pressed. May be `None` if the platform + /// does not support pressure sensitivity. + /// + /// ## Platform-specific + /// + /// - Only available on **iOS** 9.0+ and **Windows** 8+. + pub force: Option, + /// Unique identifier of a finger. + pub id: u64, +} + +/// Describes the force of a touch event +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Force { + /// On iOS, the force is calibrated so that the same number corresponds to + /// roughly the same amount of pressure on the screen regardless of the + /// device. + Calibrated { + /// The force of the touch, where a value of 1.0 represents the force of + /// an average touch (predetermined by the system, not user-specific). + /// + /// The force reported by Apple Pencil is measured along the axis of the + /// pencil. If you want a force perpendicular to the device, you need to + /// calculate this value using the `altitude_angle` value. + force: f64, + /// The maximum possible force for a touch. + /// + /// The value of this field is sufficiently high to provide a wide + /// dynamic range for values of the `force` field. + max_possible_force: f64, + /// The altitude (in radians) of the stylus. + /// + /// A value of 0 radians indicates that the stylus is parallel to the + /// surface. The value of this property is Pi/2 when the stylus is + /// perpendicular to the surface. + altitude_angle: Option, + }, + /// If the platform reports the force as normalized, we have no way of + /// knowing how much pressure 1.0 corresponds to – we know it's the maximum + /// amount of force, but as to how much force, you might either have to + /// press really really hard, or not hard at all, depending on the device. + Normalized(f64), +} + +impl Force { + /// Returns the force normalized to the range between 0.0 and 1.0 inclusive. + /// Instead of normalizing the force, you should prefer to handle + /// `Force::Calibrated` so that the amount of force the user has to apply is + /// consistent across devices. + pub fn normalized(&self) -> f64 { + match self { + Force::Calibrated { + force, + max_possible_force, + altitude_angle, + } => { + let force = match altitude_angle { + Some(altitude_angle) => force / altitude_angle.sin(), + None => *force, + }; + force / max_possible_force + } + Force::Normalized(force) => *force, + } + } +} + +/// Hardware-dependent keyboard scan code. +pub type ScanCode = u32; + +/// Identifier for a specific analog axis on some device. +pub type AxisId = u32; + +/// Identifier for a specific button on some device. +pub type ButtonId = u32; + +/// Describes the input state of a key. +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum ElementState { + Pressed, + Released, +} + +/// Describes a button of a mouse controller. +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum MouseButton { + Left, + Right, + Middle, + Other(u8), +} + +/// Describes a difference in the mouse scroll wheel state. +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum MouseScrollDelta { + /// Amount in lines or rows to scroll in the horizontal + /// and vertical directions. + /// + /// Positive values indicate movement forward + /// (away from the user) or rightwards. + LineDelta(f32, f32), + /// Amount in pixels to scroll in the horizontal and + /// vertical direction. + /// + /// Scroll events are expressed as a PixelDelta if + /// supported by the device (eg. a touchpad) and + /// platform. + PixelDelta(LogicalPosition), +} + +/// Symbolic name for a keyboard key. +#[derive(Debug, Hash, Ord, PartialOrd, PartialEq, Eq, Clone, Copy)] +#[repr(u32)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum VirtualKeyCode { + /// The '1' key over the letters. + Key1, + /// The '2' key over the letters. + Key2, + /// The '3' key over the letters. + Key3, + /// The '4' key over the letters. + Key4, + /// The '5' key over the letters. + Key5, + /// The '6' key over the letters. + Key6, + /// The '7' key over the letters. + Key7, + /// The '8' key over the letters. + Key8, + /// The '9' key over the letters. + Key9, + /// The '0' key over the 'O' and 'P' keys. + Key0, + + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + + /// The Escape key, next to F1. + Escape, + + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + + /// Print Screen/SysRq. + Snapshot, + /// Scroll Lock. + Scroll, + /// Pause/Break key, next to Scroll lock. + Pause, + + /// `Insert`, next to Backspace. + Insert, + Home, + Delete, + End, + PageDown, + PageUp, + + Left, + Up, + Right, + Down, + + /// The Backspace key, right over Enter. + // TODO: rename + Back, + /// The Enter key. + Return, + /// The space bar. + Space, + + /// The "Compose" key on Linux. + Compose, + + Caret, + + Numlock, + Numpad0, + Numpad1, + Numpad2, + Numpad3, + Numpad4, + Numpad5, + Numpad6, + Numpad7, + Numpad8, + Numpad9, + + AbntC1, + AbntC2, + Add, + Apostrophe, + Apps, + At, + Ax, + Backslash, + Calculator, + Capital, + Colon, + Comma, + Convert, + Decimal, + Divide, + Equals, + Grave, + Kana, + Kanji, + LAlt, + LBracket, + LControl, + LShift, + LWin, + Mail, + MediaSelect, + MediaStop, + Minus, + Multiply, + Mute, + MyComputer, + NavigateForward, // also called "Prior" + NavigateBackward, // also called "Next" + NextTrack, + NoConvert, + NumpadComma, + NumpadEnter, + NumpadEquals, + OEM102, + Period, + PlayPause, + Power, + PrevTrack, + RAlt, + RBracket, + RControl, + RShift, + RWin, + Semicolon, + Slash, + Sleep, + Stop, + Subtract, + Sysrq, + Tab, + Underline, + Unlabeled, + VolumeDown, + VolumeUp, + Wake, + WebBack, + WebFavorites, + WebForward, + WebHome, + WebRefresh, + WebSearch, + WebStop, + Yen, + Copy, + Paste, + Cut, +} + +impl ModifiersState { + /// Returns `true` if the shift key is pressed. + pub fn shift(&self) -> bool { + self.intersects(Self::SHIFT) + } + /// Returns `true` if the control key is pressed. + pub fn ctrl(&self) -> bool { + self.intersects(Self::CTRL) + } + /// Returns `true` if the alt key is pressed. + pub fn alt(&self) -> bool { + self.intersects(Self::ALT) + } + /// Returns `true` if the logo key is pressed. + pub fn logo(&self) -> bool { + self.intersects(Self::LOGO) + } +} + +bitflags! { + /// Represents the current state of the keyboard modifiers + /// + /// Each flag represents a modifier and is set if this modifier is active. + #[derive(Default)] + pub struct ModifiersState: u32 { + // left and right modifiers are currently commented out, but we should be able to support + // them in a future release + /// The "shift" key. + const SHIFT = 0b100 << 0; + // const LSHIFT = 0b010 << 0; + // const RSHIFT = 0b001 << 0; + /// The "control" key. + const CTRL = 0b100 << 3; + // const LCTRL = 0b010 << 3; + // const RCTRL = 0b001 << 3; + /// The "alt" key. + const ALT = 0b100 << 6; + // const LALT = 0b010 << 6; + // const RALT = 0b001 << 6; + /// This is the "windows" key on PC and "command" key on Mac. + const LOGO = 0b100 << 9; + // const LLOGO = 0b010 << 9; + // const RLOGO = 0b001 << 9; + } +} + +#[cfg(feature = "serde")] +mod modifiers_serde { + use super::ModifiersState; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + #[derive(Default, Serialize, Deserialize)] + #[serde(default)] + #[serde(rename = "ModifiersState")] + pub struct ModifiersStateSerialize { + pub shift: bool, + pub ctrl: bool, + pub alt: bool, + pub logo: bool, + } + + impl Serialize for ModifiersState { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let s = ModifiersStateSerialize { + shift: self.shift(), + ctrl: self.ctrl(), + alt: self.alt(), + logo: self.logo(), + }; + s.serialize(serializer) + } + } + + impl<'de> Deserialize<'de> for ModifiersState { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let ModifiersStateSerialize { + shift, + ctrl, + alt, + logo, + } = ModifiersStateSerialize::deserialize(deserializer)?; + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, shift); + m.set(ModifiersState::CTRL, ctrl); + m.set(ModifiersState::ALT, alt); + m.set(ModifiersState::LOGO, logo); + Ok(m) + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/event_loop.rs b/third_party/cargo/vendor/winit-0.22.0/src/event_loop.rs new file mode 100644 index 0000000..8a05e31 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/event_loop.rs @@ -0,0 +1,224 @@ +//! The `EventLoop` struct and assorted supporting types, including `ControlFlow`. +//! +//! If you want to send custom events to the event loop, use [`EventLoop::create_proxy()`][create_proxy] +//! to acquire an [`EventLoopProxy`][event_loop_proxy] and call its [`send_event`][send_event] method. +//! +//! See the root-level documentation for information on how to create and use an event loop to +//! handle events. +//! +//! [create_proxy]: crate::event_loop::EventLoop::create_proxy +//! [event_loop_proxy]: crate::event_loop::EventLoopProxy +//! [send_event]: crate::event_loop::EventLoopProxy::send_event +use instant::Instant; +use std::ops::Deref; +use std::{error, fmt}; + +use crate::{event::Event, monitor::MonitorHandle, platform_impl}; + +/// Provides a way to retrieve events from the system and from the windows that were registered to +/// the events loop. +/// +/// An `EventLoop` can be seen more or less as a "context". Calling `EventLoop::new()` +/// initializes everything that will be required to create windows. For example on Linux creating +/// an event loop opens a connection to the X or Wayland server. +/// +/// To wake up an `EventLoop` from a another thread, see the `EventLoopProxy` docs. +/// +/// Note that the `EventLoop` cannot be shared across threads (due to platform-dependant logic +/// forbidding it), as such it is neither `Send` nor `Sync`. If you need cross-thread access, the +/// `Window` created from this `EventLoop` _can_ be sent to an other thread, and the +/// `EventLoopProxy` allows you to wake up an `EventLoop` from another thread. +/// +pub struct EventLoop { + pub(crate) event_loop: platform_impl::EventLoop, + pub(crate) _marker: ::std::marker::PhantomData<*mut ()>, // Not Send nor Sync +} + +/// Target that associates windows with an `EventLoop`. +/// +/// This type exists to allow you to create new windows while Winit executes +/// your callback. `EventLoop` will coerce into this type (`impl Deref for +/// EventLoop`), so functions that take this as a parameter can also take +/// `&EventLoop`. +pub struct EventLoopWindowTarget { + pub(crate) p: platform_impl::EventLoopWindowTarget, + pub(crate) _marker: ::std::marker::PhantomData<*mut ()>, // Not Send nor Sync +} + +impl fmt::Debug for EventLoop { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("EventLoop { .. }") + } +} + +impl fmt::Debug for EventLoopWindowTarget { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("EventLoopWindowTarget { .. }") + } +} + +/// Set by the user callback given to the `EventLoop::run` method. +/// +/// Indicates the desired behavior of the event loop after [`Event::RedrawEventsCleared`][events_cleared] +/// is emitted. Defaults to `Poll`. +/// +/// ## Persistency +/// Almost every change is persistent between multiple calls to the event loop closure within a +/// given run loop. The only exception to this is `Exit` which, once set, cannot be unset. Changes +/// are **not** persistent between multiple calls to `run_return` - issuing a new call will reset +/// the control flow to `Poll`. +/// +/// [events_cleared]: crate::event::Event::RedrawEventsCleared +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ControlFlow { + /// When the current loop iteration finishes, immediately begin a new iteration regardless of + /// whether or not new events are available to process. + Poll, + /// When the current loop iteration finishes, suspend the thread until another event arrives. + Wait, + /// When the current loop iteration finishes, suspend the thread until either another event + /// arrives or the given time is reached. + WaitUntil(Instant), + /// Send a `LoopDestroyed` event and stop the event loop. This variant is *sticky* - once set, + /// `control_flow` cannot be changed from `Exit`, and any future attempts to do so will result + /// in the `control_flow` parameter being reset to `Exit`. + Exit, +} + +impl Default for ControlFlow { + #[inline(always)] + fn default() -> ControlFlow { + ControlFlow::Poll + } +} + +impl EventLoop<()> { + /// Builds a new event loop with a `()` as the user event type. + /// + /// ***For cross-platform compatibility, the `EventLoop` must be created on the main thread.*** + /// Attempting to create the event loop on a different thread will panic. This restriction isn't + /// strictly necessary on all platforms, but is imposed to eliminate any nasty surprises when + /// porting to platforms that require it. `EventLoopExt::new_any_thread` functions are exposed + /// in the relevant `platform` module if the target platform supports creating an event loop on + /// any thread. + /// + /// Usage will result in display backend initialisation, this can be controlled on linux + /// using an environment variable `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`. + /// If it is not set, winit will try to connect to a wayland connection, and if it fails will + /// fallback on x11. If this variable is set with any other value, winit will panic. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. + pub fn new() -> EventLoop<()> { + EventLoop::<()>::with_user_event() + } +} + +impl EventLoop { + /// Builds a new event loop. + /// + /// All caveats documented in [`EventLoop::new`] apply to this function. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. + pub fn with_user_event() -> EventLoop { + EventLoop { + event_loop: platform_impl::EventLoop::new(), + _marker: ::std::marker::PhantomData, + } + } + + /// Hijacks the calling thread and initializes the winit event loop with the provided + /// closure. Since the closure is `'static`, it must be a `move` closure if it needs to + /// access any data from the calling context. + /// + /// See the [`ControlFlow`] docs for information on how changes to `&mut ControlFlow` impact the + /// event loop's behavior. + /// + /// Any values not passed to this function will *not* be dropped. + /// + /// [`ControlFlow`]: crate::event_loop::ControlFlow + #[inline] + pub fn run(self, event_handler: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &EventLoopWindowTarget, &mut ControlFlow), + { + self.event_loop.run(event_handler) + } + + /// Creates an `EventLoopProxy` that can be used to dispatch user events to the main event loop. + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy { + event_loop_proxy: self.event_loop.create_proxy(), + } + } + + /// Returns the list of all the monitors available on the system. + #[inline] + pub fn available_monitors(&self) -> impl Iterator { + self.event_loop + .available_monitors() + .into_iter() + .map(|inner| MonitorHandle { inner }) + } + + /// Returns the primary monitor of the system. + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + MonitorHandle { + inner: self.event_loop.primary_monitor(), + } + } +} + +impl Deref for EventLoop { + type Target = EventLoopWindowTarget; + fn deref(&self) -> &EventLoopWindowTarget { + self.event_loop.window_target() + } +} + +/// Used to send custom events to `EventLoop`. +pub struct EventLoopProxy { + event_loop_proxy: platform_impl::EventLoopProxy, +} + +impl Clone for EventLoopProxy { + fn clone(&self) -> Self { + Self { + event_loop_proxy: self.event_loop_proxy.clone(), + } + } +} + +impl EventLoopProxy { + /// Send an event to the `EventLoop` from which this proxy was created. This emits a + /// `UserEvent(event)` event in the event loop, where `event` is the value passed to this + /// function. + /// + /// Returns an `Err` if the associated `EventLoop` no longer exists. + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.event_loop_proxy.send_event(event) + } +} + +impl fmt::Debug for EventLoopProxy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("EventLoopProxy { .. }") + } +} + +/// The error that is returned when an `EventLoopProxy` attempts to wake up an `EventLoop` that +/// no longer exists. Contains the original event given to `send_event`. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct EventLoopClosed(pub T); + +impl fmt::Display for EventLoopClosed { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Tried to wake up a closed `EventLoop`") + } +} + +impl error::Error for EventLoopClosed {} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/icon.rs b/third_party/cargo/vendor/winit-0.22.0/src/icon.rs new file mode 100644 index 0000000..418ea03 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/icon.rs @@ -0,0 +1,135 @@ +use crate::platform_impl::PlatformIcon; +use std::{error::Error, fmt, io, mem}; + +#[repr(C)] +#[derive(Debug)] +pub(crate) struct Pixel { + pub(crate) r: u8, + pub(crate) g: u8, + pub(crate) b: u8, + pub(crate) a: u8, +} + +pub(crate) const PIXEL_SIZE: usize = mem::size_of::(); + +#[derive(Debug)] +/// An error produced when using `Icon::from_rgba` with invalid arguments. +pub enum BadIcon { + /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be + /// safely interpreted as 32bpp RGBA pixels. + ByteCountNotDivisibleBy4 { byte_count: usize }, + /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. + /// At least one of your arguments is incorrect. + DimensionsVsPixelCount { + width: u32, + height: u32, + width_x_height: usize, + pixel_count: usize, + }, + /// Produced when underlying OS functionality failed to create the icon + OsError(io::Error), +} + +impl fmt::Display for BadIcon { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f, + "The length of the `rgba` argument ({:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.", + byte_count, + ), + BadIcon::DimensionsVsPixelCount { + width, + height, + width_x_height, + pixel_count, + } => write!(f, + "The specified dimensions ({:?}x{:?}) don't match the number of pixels supplied by the `rgba` argument ({:?}). For those dimensions, the expected pixel count is {:?}.", + width, height, pixel_count, width_x_height, + ), + BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {:?}", e), + } + } +} + +impl Error for BadIcon { + fn source(&self) -> Option<&(dyn Error + 'static)> { + Some(self) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RgbaIcon { + pub(crate) rgba: Vec, + pub(crate) width: u32, + pub(crate) height: u32, +} + +/// For platforms which don't have window icons (e.g. web) +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct NoIcon; + +#[allow(dead_code)] // These are not used on every platform +mod constructors { + use super::*; + + impl RgbaIcon { + /// Creates an `Icon` from 32bpp RGBA data. + /// + /// The length of `rgba` must be divisible by 4, and `width * height` must equal + /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. + pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { + if rgba.len() % PIXEL_SIZE != 0 { + return Err(BadIcon::ByteCountNotDivisibleBy4 { + byte_count: rgba.len(), + }); + } + let pixel_count = rgba.len() / PIXEL_SIZE; + if pixel_count != (width * height) as usize { + Err(BadIcon::DimensionsVsPixelCount { + width, + height, + width_x_height: (width * height) as usize, + pixel_count, + }) + } else { + Ok(RgbaIcon { + rgba, + width, + height, + }) + } + } + } + + impl NoIcon { + pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { + // Create the rgba icon anyway to validate the input + let _ = RgbaIcon::from_rgba(rgba, width, height)?; + Ok(NoIcon) + } + } +} + +/// An icon used for the window titlebar, taskbar, etc. +#[derive(Clone)] +pub struct Icon { + pub(crate) inner: PlatformIcon, +} + +impl fmt::Debug for Icon { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + fmt::Debug::fmt(&self.inner, formatter) + } +} + +impl Icon { + /// Creates an `Icon` from 32bpp RGBA data. + /// + /// The length of `rgba` must be divisible by 4, and `width * height` must equal + /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. + pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { + Ok(Icon { + inner: PlatformIcon::from_rgba(rgba, width, height)?, + }) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/lib.rs b/third_party/cargo/vendor/winit-0.22.0/src/lib.rs new file mode 100644 index 0000000..6011203 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/lib.rs @@ -0,0 +1,150 @@ +//! Winit is a cross-platform window creation and event loop management library. +//! +//! # Building windows +//! +//! Before you can build a [`Window`], you first need to build an [`EventLoop`]. This is done with the +//! [`EventLoop::new()`] function. +//! +//! ```no_run +//! use winit::event_loop::EventLoop; +//! let event_loop = EventLoop::new(); +//! ``` +//! +//! Once this is done there are two ways to create a [`Window`]: +//! +//! - Calling [`Window::new(&event_loop)`][window_new]. +//! - Calling [`let builder = WindowBuilder::new()`][window_builder_new] then [`builder.build(&event_loop)`][window_builder_build]. +//! +//! The first method is the simplest, and will give you default values for everything. The second +//! method allows you to customize the way your [`Window`] will look and behave by modifying the +//! fields of the [`WindowBuilder`] object before you create the [`Window`]. +//! +//! # Event handling +//! +//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can +//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the +//! window or a key getting pressed while the window is focused. Devices can generate +//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window. +//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a +//! [`DeviceEvent`]. You can also create and handle your own custom [`UserEvent`]s, if desired. +//! +//! You can retreive events by calling [`EventLoop::run`][event_loop_run]. This function will +//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and +//! will run until the `control_flow` argument given to the closure is set to +//! [`ControlFlow`]`::`[`Exit`], at which point [`Event`]`::`[`LoopDestroyed`] is emitted and the +//! entire program terminates. +//! +//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator`-based event loop +//! model, since that can't be implemented properly on web and mobile platforms and works poorly on +//! most desktop platforms. However, this model can be re-implemented to an extent on desktops with +//! [`EventLoopExtDesktop::run_return`]. See that method's documentation for more reasons about why +//! it's discouraged, beyond mobile/web compatibility reasons. +//! +//! +//! ```no_run +//! use winit::{ +//! event::{Event, WindowEvent}, +//! event_loop::{ControlFlow, EventLoop}, +//! window::WindowBuilder, +//! }; +//! +//! let event_loop = EventLoop::new(); +//! let window = WindowBuilder::new().build(&event_loop).unwrap(); +//! +//! event_loop.run(move |event, _, control_flow| { +//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't +//! // dispatched any events. This is ideal for games and similar applications. +//! *control_flow = ControlFlow::Poll; +//! +//! // ControlFlow::Wait pauses the event loop if no events are available to process. +//! // This is ideal for non-game applications that only update in response to user +//! // input, and uses significantly less power/CPU time than ControlFlow::Poll. +//! *control_flow = ControlFlow::Wait; +//! +//! match event { +//! Event::WindowEvent { +//! event: WindowEvent::CloseRequested, +//! .. +//! } => { +//! println!("The close button was pressed; stopping"); +//! *control_flow = ControlFlow::Exit +//! }, +//! Event::MainEventsCleared => { +//! // Application update code. +//! +//! // Queue a RedrawRequested event. +//! window.request_redraw(); +//! }, +//! Event::RedrawRequested(_) => { +//! // Redraw the application. +//! // +//! // It's preferrable to render in this event rather than in MainEventsCleared, since +//! // rendering in here allows the program to gracefully handle redraws requested +//! // by the OS. +//! }, +//! _ => () +//! } +//! }); +//! ``` +//! +//! [`Event`]`::`[`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be +//! compared to the value returned by [`Window::id()`][window_id_fn] to determine which [`Window`] +//! dispatched the event. +//! +//! # Drawing on the window +//! +//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However it allows you to +//! retrieve the raw handle of the window (see the [`platform`] module), which in turn allows you +//! to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics. +//! +//! [`EventLoop`]: event_loop::EventLoop +//! [`EventLoopExtDesktop::run_return`]: ./platform/desktop/trait.EventLoopExtDesktop.html#tymethod.run_return +//! [`EventLoop::new()`]: event_loop::EventLoop::new +//! [event_loop_run]: event_loop::EventLoop::run +//! [`ControlFlow`]: event_loop::ControlFlow +//! [`Exit`]: event_loop::ControlFlow::Exit +//! [`Window`]: window::Window +//! [`WindowId`]: window::WindowId +//! [`WindowBuilder`]: window::WindowBuilder +//! [window_new]: window::Window::new +//! [window_builder_new]: window::WindowBuilder::new +//! [window_builder_build]: window::WindowBuilder::build +//! [window_id_fn]: window::Window::id +//! [`Event`]: event::Event +//! [`WindowEvent`]: event::WindowEvent +//! [`DeviceEvent`]: event::DeviceEvent +//! [`UserEvent`]: event::Event::UserEvent +//! [`LoopDestroyed`]: event::Event::LoopDestroyed +//! [`platform`]: platform + +#![deny(rust_2018_idioms)] +#![deny(intra_doc_link_resolution_failure)] + +#[allow(unused_imports)] +#[macro_use] +extern crate lazy_static; +#[allow(unused_imports)] +#[macro_use] +extern crate log; +#[cfg(feature = "serde")] +#[macro_use] +extern crate serde; +#[macro_use] +extern crate bitflags; +#[cfg(any(target_os = "macos", target_os = "ios"))] +#[macro_use] +extern crate objc; +#[cfg(all(target_arch = "wasm32", feature = "std_web"))] +extern crate std_web as stdweb; + +pub mod dpi; +#[macro_use] +pub mod error; +pub mod event; +pub mod event_loop; +mod icon; +pub mod monitor; +mod platform_impl; +pub mod window; + +pub mod platform; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/monitor.rs new file mode 100644 index 0000000..8977c11 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/monitor.rs @@ -0,0 +1,174 @@ +//! Types useful for interacting with a user's monitors. +//! +//! If you want to get basic information about a monitor, you can use the [`MonitorHandle`][monitor_handle] +//! type. This is retreived from one of the following methods, which return an iterator of +//! [`MonitorHandle`][monitor_handle]: +//! - [`EventLoop::available_monitors`][loop_get] +//! - [`Window::available_monitors`][window_get]. +//! +//! [monitor_handle]: crate::monitor::MonitorHandle +//! [loop_get]: crate::event_loop::EventLoop::available_monitors +//! [window_get]: crate::window::Window::available_monitors +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + platform_impl, +}; + +/// Describes a fullscreen video mode of a monitor. +/// +/// Can be acquired with: +/// - [`MonitorHandle::video_modes`][monitor_get]. +/// +/// [monitor_get]: crate::monitor::MonitorHandle::video_modes +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct VideoMode { + pub(crate) video_mode: platform_impl::VideoMode, +} + +impl std::fmt::Debug for VideoMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.video_mode.fmt(f) + } +} + +impl PartialOrd for VideoMode { + fn partial_cmp(&self, other: &VideoMode) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for VideoMode { + fn cmp(&self, other: &VideoMode) -> std::cmp::Ordering { + // TODO: we can impl `Ord` for `PhysicalSize` once we switch from `f32` + // to `u32` there + let size: (u32, u32) = self.size().into(); + let other_size: (u32, u32) = other.size().into(); + self.monitor().cmp(&other.monitor()).then( + size.cmp(&other_size) + .then( + self.refresh_rate() + .cmp(&other.refresh_rate()) + .then(self.bit_depth().cmp(&other.bit_depth())), + ) + .reverse(), + ) + } +} + +impl VideoMode { + /// Returns the resolution of this video mode. + #[inline] + pub fn size(&self) -> PhysicalSize { + self.video_mode.size() + } + + /// Returns the bit depth of this video mode, as in how many bits you have + /// available per color. This is generally 24 bits or 32 bits on modern + /// systems, depending on whether the alpha channel is counted or not. + /// + /// ## Platform-specific + /// + /// - **Wayland:** Always returns 32. + /// - **iOS:** Always returns 32. + #[inline] + pub fn bit_depth(&self) -> u16 { + self.video_mode.bit_depth() + } + + /// Returns the refresh rate of this video mode. **Note**: the returned + /// refresh rate is an integer approximation, and you shouldn't rely on this + /// value to be exact. + #[inline] + pub fn refresh_rate(&self) -> u16 { + self.video_mode.refresh_rate() + } + + /// Returns the monitor that this video mode is valid for. Each monitor has + /// a separate set of valid video modes. + #[inline] + pub fn monitor(&self) -> MonitorHandle { + self.video_mode.monitor() + } +} + +impl std::fmt::Display for VideoMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}x{} @ {} Hz ({} bpp)", + self.size().width, + self.size().height, + self.refresh_rate(), + self.bit_depth() + ) + } +} + +/// Handle to a monitor. +/// +/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation. +/// +/// [`Window`]: crate::window::Window +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct MonitorHandle { + pub(crate) inner: platform_impl::MonitorHandle, +} + +impl MonitorHandle { + /// Returns a human-readable name of the monitor. + /// + /// Returns `None` if the monitor doesn't exist anymore. + /// + /// ## Platform-specific + /// + /// - **Web:** Always returns None + #[inline] + pub fn name(&self) -> Option { + self.inner.name() + } + + /// Returns the monitor's resolution. + /// + /// ## Platform-specific + /// + /// - **Web:** Always returns (0,0) + #[inline] + pub fn size(&self) -> PhysicalSize { + self.inner.size() + } + + /// Returns the top-left corner position of the monitor relative to the larger full + /// screen area. + /// + /// ## Platform-specific + /// + /// - **Web:** Always returns (0,0) + #[inline] + pub fn position(&self) -> PhysicalPosition { + self.inner.position() + } + + /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa. + /// + /// See the [`dpi`](crate::dpi) module for more information. + /// + /// ## Platform-specific + /// + /// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable. + /// - **Android:** Always returns 1.0. + /// - **Web:** Always returns 1.0 + #[inline] + pub fn scale_factor(&self) -> f64 { + self.inner.scale_factor() + } + + /// Returns all fullscreen video modes supported by this monitor. + /// + /// ## Platform-specific + /// + /// - **Web:** Always returns an empty iterator + #[inline] + pub fn video_modes(&self) -> impl Iterator { + self.inner.video_modes() + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/android.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/android.rs new file mode 100644 index 0000000..dafb7a3 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/android.rs @@ -0,0 +1,33 @@ +#![cfg(any(target_os = "android"))] + +use crate::{EventLoop, Window, WindowBuilder}; +use std::os::raw::c_void; + +/// Additional methods on `EventLoop` that are specific to Android. +pub trait EventLoopExtAndroid { + /// Makes it possible for glutin to register a callback when a suspend event happens on Android + fn set_suspend_callback(&self, cb: Option ()>>); +} + +impl EventLoopExtAndroid for EventLoop { + fn set_suspend_callback(&self, cb: Option ()>>) { + self.event_loop.set_suspend_callback(cb); + } +} + +/// Additional methods on `Window` that are specific to Android. +pub trait WindowExtAndroid { + fn native_window(&self) -> *const c_void; +} + +impl WindowExtAndroid for Window { + #[inline] + fn native_window(&self) -> *const c_void { + self.window.native_window() + } +} + +/// Additional methods on `WindowBuilder` that are specific to Android. +pub trait WindowBuilderExtAndroid {} + +impl WindowBuilderExtAndroid for WindowBuilder {} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/desktop.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/desktop.rs new file mode 100644 index 0000000..df80143 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/desktop.rs @@ -0,0 +1,53 @@ +#![cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" +))] + +use crate::{ + event::Event, + event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget}, +}; + +/// Additional methods on `EventLoop` that are specific to desktop platforms. +pub trait EventLoopExtDesktop { + /// A type provided by the user that can be passed through `Event::UserEvent`. + type UserEvent; + + /// Initializes the `winit` event loop. + /// + /// Unlike `run`, this function accepts non-`'static` (i.e. non-`move`) closures and returns + /// control flow to the caller when `control_flow` is set to `ControlFlow::Exit`. + /// + /// # Caveats + /// Despite its apperance at first glance, this is *not* a perfect replacement for + /// `poll_events`. For example, this function will not return on Windows or macOS while a + /// window is getting resized, resulting in all application logic outside of the + /// `event_handler` closure not running until the resize operation ends. Other OS operations + /// may also result in such freezes. This behavior is caused by fundamental limitations in the + /// underyling OS APIs, which cannot be hidden by Winit without severe stability reprecussions. + /// + /// You are strongly encouraged to use `run`, unless the use of this is absolutely necessary. + fn run_return(&mut self, event_handler: F) + where + F: FnMut( + Event<'_, Self::UserEvent>, + &EventLoopWindowTarget, + &mut ControlFlow, + ); +} + +impl EventLoopExtDesktop for EventLoop { + type UserEvent = T; + + fn run_return(&mut self, event_handler: F) + where + F: FnMut( + Event<'_, Self::UserEvent>, + &EventLoopWindowTarget, + &mut ControlFlow, + ), + { + self.event_loop.run_return(event_handler) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/ios.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/ios.rs new file mode 100644 index 0000000..9d982ac --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/ios.rs @@ -0,0 +1,317 @@ +#![cfg(target_os = "ios")] + +use std::os::raw::c_void; + +use crate::{ + event_loop::EventLoop, + monitor::{MonitorHandle, VideoMode}, + window::{Window, WindowBuilder}, +}; + +/// Additional methods on [`EventLoop`] that are specific to iOS. +pub trait EventLoopExtIOS { + /// Returns the [`Idiom`] (phone/tablet/tv/etc) for the current device. + fn idiom(&self) -> Idiom; +} + +impl EventLoopExtIOS for EventLoop { + fn idiom(&self) -> Idiom { + self.event_loop.idiom() + } +} + +/// Additional methods on [`Window`] that are specific to iOS. +pub trait WindowExtIOS { + /// Returns a pointer to the [`UIWindow`] that is used by this window. + /// + /// The pointer will become invalid when the [`Window`] is destroyed. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + fn ui_window(&self) -> *mut c_void; + + /// Returns a pointer to the [`UIViewController`] that is used by this window. + /// + /// The pointer will become invalid when the [`Window`] is destroyed. + /// + /// [`UIViewController`]: https://developer.apple.com/documentation/uikit/uiviewcontroller?language=objc + fn ui_view_controller(&self) -> *mut c_void; + + /// Returns a pointer to the [`UIView`] that is used by this window. + /// + /// The pointer will become invalid when the [`Window`] is destroyed. + /// + /// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc + fn ui_view(&self) -> *mut c_void; + + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandle::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + fn set_scale_factor(&self, scale_factor: f64); + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This changes the value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc), + /// and then calls + /// [`-[UIViewController attemptRotationToDeviceOrientation]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621400-attemptrotationtodeviceorientati?language=objc). + fn set_valid_orientations(&self, valid_orientations: ValidOrientations); + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This changes the value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_prefers_home_indicator_hidden(&self, hidden: bool); + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This changes the value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge); + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This changes the value returned by + /// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsStatusBarAppearanceUpdate]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc). + fn set_prefers_status_bar_hidden(&self, hidden: bool); +} + +impl WindowExtIOS for Window { + #[inline] + fn ui_window(&self) -> *mut c_void { + self.window.ui_window() as _ + } + + #[inline] + fn ui_view_controller(&self) -> *mut c_void { + self.window.ui_view_controller() as _ + } + + #[inline] + fn ui_view(&self) -> *mut c_void { + self.window.ui_view() as _ + } + + #[inline] + fn set_scale_factor(&self, scale_factor: f64) { + self.window.set_scale_factor(scale_factor) + } + + #[inline] + fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + self.window.set_valid_orientations(valid_orientations) + } + + #[inline] + fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + self.window.set_prefers_home_indicator_hidden(hidden) + } + + #[inline] + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + self.window + .set_preferred_screen_edges_deferring_system_gestures(edges) + } + + #[inline] + fn set_prefers_status_bar_hidden(&self, hidden: bool) { + self.window.set_prefers_status_bar_hidden(hidden) + } +} + +/// Additional methods on [`WindowBuilder`] that are specific to iOS. +pub trait WindowBuilderExtIOS { + /// Sets the root view class used by the [`Window`], otherwise a barebones [`UIView`] is provided. + /// + /// An instance of the class will be initialized by calling [`-[UIView initWithFrame:]`](https://developer.apple.com/documentation/uikit/uiview/1622488-initwithframe?language=objc). + /// + /// [`UIView`]: https://developer.apple.com/documentation/uikit/uiview?language=objc + fn with_root_view_class(self, root_view_class: *const c_void) -> WindowBuilder; + + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandle::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + fn with_scale_factor(self, scale_factor: f64) -> WindowBuilder; + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This sets the initial value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc). + fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> WindowBuilder; + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn with_prefers_home_indicator_hidden(self, hidden: bool) -> WindowBuilder; + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This sets the initial value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn with_preferred_screen_edges_deferring_system_gestures( + self, + edges: ScreenEdge, + ) -> WindowBuilder; + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc). + fn with_prefers_status_bar_hidden(self, hidden: bool) -> WindowBuilder; +} + +impl WindowBuilderExtIOS for WindowBuilder { + #[inline] + fn with_root_view_class(mut self, root_view_class: *const c_void) -> WindowBuilder { + self.platform_specific.root_view_class = unsafe { &*(root_view_class as *const _) }; + self + } + + #[inline] + fn with_scale_factor(mut self, scale_factor: f64) -> WindowBuilder { + self.platform_specific.scale_factor = Some(scale_factor); + self + } + + #[inline] + fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> WindowBuilder { + self.platform_specific.valid_orientations = valid_orientations; + self + } + + #[inline] + fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> WindowBuilder { + self.platform_specific.prefers_home_indicator_hidden = hidden; + self + } + + #[inline] + fn with_preferred_screen_edges_deferring_system_gestures( + mut self, + edges: ScreenEdge, + ) -> WindowBuilder { + self.platform_specific + .preferred_screen_edges_deferring_system_gestures = edges; + self + } + + #[inline] + fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> WindowBuilder { + self.platform_specific.prefers_status_bar_hidden = hidden; + self + } +} + +/// Additional methods on [`MonitorHandle`] that are specific to iOS. +pub trait MonitorHandleExtIOS { + /// Returns a pointer to the [`UIScreen`] that is used by this monitor. + /// + /// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc + fn ui_screen(&self) -> *mut c_void; + + /// Returns the preferred [`VideoMode`] for this monitor. + /// + /// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc). + fn preferred_video_mode(&self) -> VideoMode; +} + +impl MonitorHandleExtIOS for MonitorHandle { + #[inline] + fn ui_screen(&self) -> *mut c_void { + self.inner.ui_screen() as _ + } + + #[inline] + fn preferred_video_mode(&self) -> VideoMode { + self.inner.preferred_video_mode() + } +} + +/// Valid orientations for a particular [`Window`]. +#[derive(Clone, Copy, Debug)] +pub enum ValidOrientations { + /// Excludes `PortraitUpsideDown` on iphone + LandscapeAndPortrait, + + Landscape, + + /// Excludes `PortraitUpsideDown` on iphone + Portrait, +} + +impl Default for ValidOrientations { + #[inline] + fn default() -> ValidOrientations { + ValidOrientations::LandscapeAndPortrait + } +} + +/// The device [idiom]. +/// +/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Idiom { + Unspecified, + + /// iPhone and iPod touch. + Phone, + + /// iPad. + Pad, + + /// tvOS and Apple TV. + TV, + CarPlay, +} + +bitflags! { + /// The [edges] of a screen. + /// + /// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc + #[derive(Default)] + pub struct ScreenEdge: u8 { + const NONE = 0; + const TOP = 1 << 0; + const LEFT = 1 << 1; + const BOTTOM = 1 << 2; + const RIGHT = 1 << 3; + const ALL = ScreenEdge::TOP.bits | ScreenEdge::LEFT.bits + | ScreenEdge::BOTTOM.bits | ScreenEdge::RIGHT.bits; + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/macos.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/macos.rs similarity index 62% rename from third_party/cargo/vendor/winit-0.18.1/src/os/macos.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform/macos.rs index b9ea993..b275c75 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/macos.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/macos.rs @@ -1,27 +1,52 @@ #![cfg(target_os = "macos")] use std::os::raw::c_void; -use {LogicalSize, MonitorId, Window, WindowBuilder}; + +use crate::{ + dpi::LogicalSize, + event_loop::EventLoopWindowTarget, + monitor::MonitorHandle, + window::{Window, WindowBuilder}, +}; + +/// Corresponds to `NSRequestUserAttentionType`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RequestUserAttentionType { + /// Corresponds to `NSCriticalRequest`. + /// + /// Dock icon will bounce until the application is focused. + Critical, + + /// Corresponds to `NSInformationalRequest`. + /// + /// Dock icon will bounce once. + Informational, +} + +impl Default for RequestUserAttentionType { + fn default() -> Self { + RequestUserAttentionType::Critical + } +} /// Additional methods on `Window` that are specific to MacOS. -pub trait WindowExt { +pub trait WindowExtMacOS { /// Returns a pointer to the cocoa `NSWindow` that is used by this window. /// /// The pointer will become invalid when the `Window` is destroyed. - fn get_nswindow(&self) -> *mut c_void; + fn ns_window(&self) -> *mut c_void; /// Returns a pointer to the cocoa `NSView` that is used by this window. /// /// The pointer will become invalid when the `Window` is destroyed. - fn get_nsview(&self) -> *mut c_void; + fn ns_view(&self) -> *mut c_void; /// Request user attention, causing the application's dock icon to bounce. /// Note that this has no effect if the application is already focused. - /// - /// The `is_critical` flag has the following effects: - /// - `false`: the dock icon will only bounce once. - /// - `true`: the dock icon will bounce until the application is focused. - fn request_user_attention(&self, is_critical: bool); + fn request_user_attention(&self, request_type: RequestUserAttentionType); + + /// Returns whether or not the window is in simple fullscreen mode. + fn simple_fullscreen(&self) -> bool; /// Toggles a fullscreen mode that doesn't require a new macOS space. /// Returns a boolean indicating whether the transition was successful (this @@ -33,20 +58,25 @@ pub trait WindowExt { fn set_simple_fullscreen(&self, fullscreen: bool) -> bool; } -impl WindowExt for Window { +impl WindowExtMacOS for Window { #[inline] - fn get_nswindow(&self) -> *mut c_void { - self.window.get_nswindow() + fn ns_window(&self) -> *mut c_void { + self.window.ns_window() } #[inline] - fn get_nsview(&self) -> *mut c_void { - self.window.get_nsview() + fn ns_view(&self) -> *mut c_void { + self.window.ns_view() } #[inline] - fn request_user_attention(&self, is_critical: bool) { - self.window.request_user_attention(is_critical) + fn request_user_attention(&self, request_type: RequestUserAttentionType) { + self.window.request_user_attention(request_type) + } + + #[inline] + fn simple_fullscreen(&self) -> bool { + self.window.simple_fullscreen() } #[inline] @@ -82,11 +112,12 @@ impl Default for ActivationPolicy { /// - `with_titlebar_hidden` /// - `with_titlebar_buttons_hidden` /// - `with_fullsize_content_view` -pub trait WindowBuilderExt { +pub trait WindowBuilderExtMacOS { /// Sets the activation policy for the window being built. fn with_activation_policy(self, activation_policy: ActivationPolicy) -> WindowBuilder; /// Enables click-and-drag behavior for the entire window, not just the titlebar. - fn with_movable_by_window_background(self, movable_by_window_background: bool) -> WindowBuilder; + fn with_movable_by_window_background(self, movable_by_window_background: bool) + -> WindowBuilder; /// Makes the titlebar transparent and allows the content to appear behind it. fn with_titlebar_transparent(self, titlebar_transparent: bool) -> WindowBuilder; /// Hides the window title. @@ -98,10 +129,11 @@ pub trait WindowBuilderExt { /// Makes the window content appear behind the titlebar. fn with_fullsize_content_view(self, fullsize_content_view: bool) -> WindowBuilder; /// Build window with `resizeIncrements` property. Values must not be 0. - fn with_resize_increments(self, increments: LogicalSize) -> WindowBuilder; + fn with_resize_increments(self, increments: LogicalSize) -> WindowBuilder; + fn with_disallow_hidpi(self, disallow_hidpi: bool) -> WindowBuilder; } -impl WindowBuilderExt for WindowBuilder { +impl WindowBuilderExtMacOS for WindowBuilder { #[inline] fn with_activation_policy(mut self, activation_policy: ActivationPolicy) -> WindowBuilder { self.platform_specific.activation_policy = activation_policy; @@ -109,7 +141,10 @@ impl WindowBuilderExt for WindowBuilder { } #[inline] - fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> WindowBuilder { + fn with_movable_by_window_background( + mut self, + movable_by_window_background: bool, + ) -> WindowBuilder { self.platform_specific.movable_by_window_background = movable_by_window_background; self } @@ -145,27 +180,47 @@ impl WindowBuilderExt for WindowBuilder { } #[inline] - fn with_resize_increments(mut self, increments: LogicalSize) -> WindowBuilder { + fn with_resize_increments(mut self, increments: LogicalSize) -> WindowBuilder { self.platform_specific.resize_increments = Some(increments.into()); self } + + #[inline] + fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> WindowBuilder { + self.platform_specific.disallow_hidpi = disallow_hidpi; + self + } } -/// Additional methods on `MonitorId` that are specific to MacOS. -pub trait MonitorIdExt { +/// Additional methods on `MonitorHandle` that are specific to MacOS. +pub trait MonitorHandleExtMacOS { /// Returns the identifier of the monitor for Cocoa. fn native_id(&self) -> u32; /// Returns a pointer to the NSScreen representing this monitor. - fn get_nsscreen(&self) -> Option<*mut c_void>; + fn ns_screen(&self) -> Option<*mut c_void>; } -impl MonitorIdExt for MonitorId { +impl MonitorHandleExtMacOS for MonitorHandle { #[inline] fn native_id(&self) -> u32 { - self.inner.get_native_identifier() + self.inner.native_identifier() } - fn get_nsscreen(&self) -> Option<*mut c_void> { - self.inner.get_nsscreen().map(|s| s as *mut c_void) + fn ns_screen(&self) -> Option<*mut c_void> { + self.inner.ns_screen().map(|s| s as *mut c_void) + } +} + +/// Additional methods on `EventLoopWindowTarget` that are specific to macOS. +pub trait EventLoopWindowTargetExtMacOS { + /// Hide the entire application. In most applications this is typically triggered with Command-H. + fn hide_application(&self); +} + +impl EventLoopWindowTargetExtMacOS for EventLoopWindowTarget { + fn hide_application(&self) { + let cls = objc::runtime::Class::get("NSApplication").unwrap(); + let app: cocoa::base::id = unsafe { msg_send![cls, sharedApplication] }; + unsafe { msg_send![app, hide: 0] } } } diff --git a/third_party/cargo/vendor/winit-0.18.1/src/os/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/mod.rs similarity index 61% rename from third_party/cargo/vendor/winit-0.18.1/src/os/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform/mod.rs index 2496769..27ecde1 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/os/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/mod.rs @@ -1,17 +1,25 @@ //! Contains traits with platform-specific methods in them. //! -//! Contains the follow modules: +//! Contains the follow OS-specific modules: //! //! - `android` //! - `ios` //! - `macos` //! - `unix` //! - `windows` +//! - `web` +//! +//! And the following platform-specific module: +//! +//! - `desktop` (available on `windows`, `unix`, and `macos`) //! //! However only the module corresponding to the platform you're compiling to will be available. -//! + pub mod android; pub mod ios; pub mod macos; pub mod unix; pub mod windows; + +pub mod desktop; +pub mod web; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/unix.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/unix.rs new file mode 100644 index 0000000..6ab2d7d --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/unix.rs @@ -0,0 +1,489 @@ +#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] + +use std::{os::raw, ptr, sync::Arc}; + +use smithay_client_toolkit::window::{ButtonState as SCTKButtonState, Theme as SCTKTheme}; + +use crate::{ + dpi::Size, + event_loop::{EventLoop, EventLoopWindowTarget}, + monitor::MonitorHandle, + window::{Window, WindowBuilder}, +}; + +use crate::platform_impl::{ + x11::{ffi::XVisualInfo, XConnection}, + EventLoop as LinuxEventLoop, EventLoopWindowTarget as LinuxEventLoopWindowTarget, + Window as LinuxWindow, +}; + +// TODO: stupid hack so that glutin can do its work +#[doc(hidden)] +pub use crate::platform_impl::x11; + +pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupported}; + +/// Additional methods on `EventLoopWindowTarget` that are specific to Unix. +pub trait EventLoopWindowTargetExtUnix { + /// True if the `EventLoopWindowTarget` uses Wayland. + fn is_wayland(&self) -> bool; + /// + /// True if the `EventLoopWindowTarget` uses X11. + fn is_x11(&self) -> bool; + + #[doc(hidden)] + fn xlib_xconnection(&self) -> Option>; + + /// Returns a pointer to the `wl_display` object of wayland that is used by this + /// `EventLoopWindowTarget`. + /// + /// Returns `None` if the `EventLoop` doesn't use wayland (if it uses xlib for example). + /// + /// The pointer will become invalid when the winit `EventLoop` is destroyed. + fn wayland_display(&self) -> Option<*mut raw::c_void>; +} + +impl EventLoopWindowTargetExtUnix for EventLoopWindowTarget { + #[inline] + fn is_wayland(&self) -> bool { + self.p.is_wayland() + } + + #[inline] + fn is_x11(&self) -> bool { + !self.p.is_wayland() + } + + #[inline] + #[doc(hidden)] + fn xlib_xconnection(&self) -> Option> { + match self.p { + LinuxEventLoopWindowTarget::X(ref e) => Some(e.x_connection().clone()), + _ => None, + } + } + + #[inline] + fn wayland_display(&self) -> Option<*mut raw::c_void> { + match self.p { + LinuxEventLoopWindowTarget::Wayland(ref p) => { + Some(p.display().get_display_ptr() as *mut _) + } + _ => None, + } + } +} + +/// Additional methods on `EventLoop` that are specific to Unix. +pub trait EventLoopExtUnix { + /// Builds a new `EventLoop` that is forced to use X11. + /// + /// # Panics + /// + /// If called outside the main thread. To initialize an X11 event loop outside + /// the main thread, use [`new_x11_any_thread`](#tymethod.new_x11_any_thread). + fn new_x11() -> Result + where + Self: Sized; + + /// Builds a new `EventLoop` that is forced to use Wayland. + /// + /// # Panics + /// + /// If called outside the main thread. To initialize a Wayland event loop outside + /// the main thread, use [`new_wayland_any_thread`](#tymethod.new_wayland_any_thread). + fn new_wayland() -> Self + where + Self: Sized; + + /// Builds a new `EventLoop` on any thread. + /// + /// This method bypasses the cross-platform compatibility requirement + /// that `EventLoop` be created on the main thread. + fn new_any_thread() -> Self + where + Self: Sized; + + /// Builds a new X11 `EventLoop` on any thread. + /// + /// This method bypasses the cross-platform compatibility requirement + /// that `EventLoop` be created on the main thread. + fn new_x11_any_thread() -> Result + where + Self: Sized; + + /// Builds a new Wayland `EventLoop` on any thread. + /// + /// This method bypasses the cross-platform compatibility requirement + /// that `EventLoop` be created on the main thread. + fn new_wayland_any_thread() -> Self + where + Self: Sized; +} + +fn wrap_ev(event_loop: LinuxEventLoop) -> EventLoop { + EventLoop { + event_loop, + _marker: std::marker::PhantomData, + } +} + +impl EventLoopExtUnix for EventLoop { + #[inline] + fn new_any_thread() -> Self { + wrap_ev(LinuxEventLoop::new_any_thread()) + } + + #[inline] + fn new_x11_any_thread() -> Result { + LinuxEventLoop::new_x11_any_thread().map(wrap_ev) + } + + #[inline] + fn new_wayland_any_thread() -> Self { + wrap_ev( + LinuxEventLoop::new_wayland_any_thread() + // TODO: propagate + .expect("failed to open Wayland connection"), + ) + } + + #[inline] + fn new_x11() -> Result { + LinuxEventLoop::new_x11().map(wrap_ev) + } + + #[inline] + fn new_wayland() -> Self { + wrap_ev( + LinuxEventLoop::new_wayland() + // TODO: propagate + .expect("failed to open Wayland connection"), + ) + } +} + +/// Additional methods on `Window` that are specific to Unix. +pub trait WindowExtUnix { + /// Returns the ID of the `Window` xlib object that is used by this window. + /// + /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). + fn xlib_window(&self) -> Option; + + /// Returns a pointer to the `Display` object of xlib that is used by this window. + /// + /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). + /// + /// The pointer will become invalid when the glutin `Window` is destroyed. + fn xlib_display(&self) -> Option<*mut raw::c_void>; + + fn xlib_screen_id(&self) -> Option; + + #[doc(hidden)] + fn xlib_xconnection(&self) -> Option>; + + /// Set window urgency hint (`XUrgencyHint`). Only relevant on X. + fn set_urgent(&self, is_urgent: bool); + + /// This function returns the underlying `xcb_connection_t` of an xlib `Display`. + /// + /// Returns `None` if the window doesn't use xlib (if it uses wayland for example). + /// + /// The pointer will become invalid when the glutin `Window` is destroyed. + fn xcb_connection(&self) -> Option<*mut raw::c_void>; + + /// Returns a pointer to the `wl_surface` object of wayland that is used by this window. + /// + /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). + /// + /// The pointer will become invalid when the glutin `Window` is destroyed. + fn wayland_surface(&self) -> Option<*mut raw::c_void>; + + /// Returns a pointer to the `wl_display` object of wayland that is used by this window. + /// + /// Returns `None` if the window doesn't use wayland (if it uses xlib for example). + /// + /// The pointer will become invalid when the glutin `Window` is destroyed. + fn wayland_display(&self) -> Option<*mut raw::c_void>; + + /// Sets the color theme of the client side window decorations on wayland + fn set_wayland_theme(&self, theme: T); + + /// Check if the window is ready for drawing + /// + /// It is a remnant of a previous implementation detail for the + /// wayland backend, and is no longer relevant. + /// + /// Always return true. + #[deprecated] + fn is_ready(&self) -> bool; +} + +impl WindowExtUnix for Window { + #[inline] + fn xlib_window(&self) -> Option { + match self.window { + LinuxWindow::X(ref w) => Some(w.xlib_window()), + _ => None, + } + } + + #[inline] + fn xlib_display(&self) -> Option<*mut raw::c_void> { + match self.window { + LinuxWindow::X(ref w) => Some(w.xlib_display()), + _ => None, + } + } + + #[inline] + fn xlib_screen_id(&self) -> Option { + match self.window { + LinuxWindow::X(ref w) => Some(w.xlib_screen_id()), + _ => None, + } + } + + #[inline] + #[doc(hidden)] + fn xlib_xconnection(&self) -> Option> { + match self.window { + LinuxWindow::X(ref w) => Some(w.xlib_xconnection()), + _ => None, + } + } + + #[inline] + fn set_urgent(&self, is_urgent: bool) { + if let LinuxWindow::X(ref w) = self.window { + w.set_urgent(is_urgent); + } + } + + #[inline] + fn xcb_connection(&self) -> Option<*mut raw::c_void> { + match self.window { + LinuxWindow::X(ref w) => Some(w.xcb_connection()), + _ => None, + } + } + + #[inline] + fn wayland_surface(&self) -> Option<*mut raw::c_void> { + match self.window { + LinuxWindow::Wayland(ref w) => Some(w.surface().as_ref().c_ptr() as *mut _), + _ => None, + } + } + + #[inline] + fn wayland_display(&self) -> Option<*mut raw::c_void> { + match self.window { + LinuxWindow::Wayland(ref w) => Some(w.display().as_ref().c_ptr() as *mut _), + _ => None, + } + } + + #[inline] + fn set_wayland_theme(&self, theme: T) { + match self.window { + LinuxWindow::Wayland(ref w) => w.set_theme(WaylandTheme(theme)), + _ => {} + } + } + + #[inline] + fn is_ready(&self) -> bool { + true + } +} + +/// Additional methods on `WindowBuilder` that are specific to Unix. +pub trait WindowBuilderExtUnix { + fn with_x11_visual(self, visual_infos: *const T) -> Self; + fn with_x11_screen(self, screen_id: i32) -> Self; + + /// Build window with `WM_CLASS` hint; defaults to the name of the binary. Only relevant on X11. + fn with_class(self, class: String, instance: String) -> Self; + /// Build window with override-redirect flag; defaults to false. Only relevant on X11. + fn with_override_redirect(self, override_redirect: bool) -> Self; + /// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. Only relevant on X11. + fn with_x11_window_type(self, x11_window_type: Vec) -> Self; + /// Build window with `_GTK_THEME_VARIANT` hint set to the specified value. Currently only relevant on X11. + fn with_gtk_theme_variant(self, variant: String) -> Self; + /// Build window with resize increment hint. Only implemented on X11. + fn with_resize_increments>(self, increments: S) -> Self; + /// Build window with base size hint. Only implemented on X11. + fn with_base_size>(self, base_size: S) -> Self; + + /// Build window with a given application ID. It should match the `.desktop` file distributed with + /// your program. Only relevant on Wayland. + /// + /// For details about application ID conventions, see the + /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) + fn with_app_id(self, app_id: String) -> Self; +} + +impl WindowBuilderExtUnix for WindowBuilder { + #[inline] + fn with_x11_visual(mut self, visual_infos: *const T) -> Self { + self.platform_specific.visual_infos = + Some(unsafe { ptr::read(visual_infos as *const XVisualInfo) }); + self + } + + #[inline] + fn with_x11_screen(mut self, screen_id: i32) -> Self { + self.platform_specific.screen_id = Some(screen_id); + self + } + + #[inline] + fn with_class(mut self, instance: String, class: String) -> Self { + self.platform_specific.class = Some((instance, class)); + self + } + + #[inline] + fn with_override_redirect(mut self, override_redirect: bool) -> Self { + self.platform_specific.override_redirect = override_redirect; + self + } + + #[inline] + fn with_x11_window_type(mut self, x11_window_types: Vec) -> Self { + self.platform_specific.x11_window_types = x11_window_types; + self + } + + #[inline] + fn with_gtk_theme_variant(mut self, variant: String) -> Self { + self.platform_specific.gtk_theme_variant = Some(variant); + self + } + + #[inline] + fn with_resize_increments>(mut self, increments: S) -> Self { + self.platform_specific.resize_increments = Some(increments.into()); + self + } + + #[inline] + fn with_base_size>(mut self, base_size: S) -> Self { + self.platform_specific.base_size = Some(base_size.into()); + self + } + + #[inline] + fn with_app_id(mut self, app_id: String) -> Self { + self.platform_specific.app_id = Some(app_id); + self + } +} + +/// Additional methods on `MonitorHandle` that are specific to Linux. +pub trait MonitorHandleExtUnix { + /// Returns the inner identifier of the monitor. + fn native_id(&self) -> u32; +} + +impl MonitorHandleExtUnix for MonitorHandle { + #[inline] + fn native_id(&self) -> u32 { + self.inner.native_identifier() + } +} + +/// Wrapper for implementing SCTK's theme trait. +struct WaylandTheme(T); + +pub trait Theme: Send + 'static { + /// Primary color of the scheme. + fn primary_color(&self, window_active: bool) -> [u8; 4]; + + /// Secondary color of the scheme. + fn secondary_color(&self, window_active: bool) -> [u8; 4]; + + /// Color for the close button. + fn close_button_color(&self, status: ButtonState) -> [u8; 4]; + + /// Icon color for the close button, defaults to the secondary color. + #[allow(unused_variables)] + fn close_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + self.secondary_color(true) + } + + /// Background color for the maximize button. + fn maximize_button_color(&self, status: ButtonState) -> [u8; 4]; + + /// Icon color for the maximize button, defaults to the secondary color. + #[allow(unused_variables)] + fn maximize_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + self.secondary_color(true) + } + + /// Background color for the minimize button. + fn minimize_button_color(&self, status: ButtonState) -> [u8; 4]; + + /// Icon color for the minimize button, defaults to the secondary color. + #[allow(unused_variables)] + fn minimize_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + self.secondary_color(true) + } +} + +impl SCTKTheme for WaylandTheme { + fn get_primary_color(&self, active: bool) -> [u8; 4] { + self.0.primary_color(active) + } + + fn get_secondary_color(&self, active: bool) -> [u8; 4] { + self.0.secondary_color(active) + } + + fn get_close_button_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0.close_button_color(ButtonState::from_sctk(status)) + } + + fn get_close_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0 + .close_button_icon_color(ButtonState::from_sctk(status)) + } + + fn get_maximize_button_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0.maximize_button_color(ButtonState::from_sctk(status)) + } + + fn get_maximize_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0 + .maximize_button_icon_color(ButtonState::from_sctk(status)) + } + + fn get_minimize_button_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0.minimize_button_color(ButtonState::from_sctk(status)) + } + + fn get_minimize_button_icon_color(&self, status: SCTKButtonState) -> [u8; 4] { + self.0 + .minimize_button_icon_color(ButtonState::from_sctk(status)) + } +} + +pub enum ButtonState { + /// Button is being hovered over by pointer. + Hovered, + /// Button is not being hovered over by pointer. + Idle, + /// Button is disabled. + Disabled, +} + +impl ButtonState { + fn from_sctk(button_state: SCTKButtonState) -> Self { + match button_state { + SCTKButtonState::Hovered => Self::Hovered, + SCTKButtonState::Idle => Self::Idle, + SCTKButtonState::Disabled => Self::Disabled, + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/web.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/web.rs new file mode 100644 index 0000000..c5ceca9 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/web.rs @@ -0,0 +1,59 @@ +#![cfg(target_arch = "wasm32")] + +//! The web target does not automatically insert the canvas element object into the web page, to +//! allow end users to determine how the page should be laid out. Use the `WindowExtStdweb` or +//! `WindowExtWebSys` traits (depending on your web backend) to retrieve the canvas from the +//! Window. Alternatively, use the `WindowBuilderExtStdweb` or `WindowBuilderExtWebSys` to provide +//! your own canvas. + +use crate::window::WindowBuilder; + +#[cfg(feature = "stdweb")] +use stdweb::web::html_element::CanvasElement; + +#[cfg(feature = "stdweb")] +pub trait WindowExtStdweb { + fn canvas(&self) -> CanvasElement; + + /// Whether the browser reports the preferred color scheme to be "dark". + fn is_dark_mode(&self) -> bool; +} + +#[cfg(feature = "web-sys")] +use web_sys::HtmlCanvasElement; + +#[cfg(feature = "web-sys")] +pub trait WindowExtWebSys { + fn canvas(&self) -> HtmlCanvasElement; + + /// Whether the browser reports the preferred color scheme to be "dark". + fn is_dark_mode(&self) -> bool; +} + +#[cfg(feature = "stdweb")] +pub trait WindowBuilderExtStdweb { + fn with_canvas(self, canvas: Option) -> Self; +} + +#[cfg(feature = "stdweb")] +impl WindowBuilderExtStdweb for WindowBuilder { + fn with_canvas(mut self, canvas: Option) -> Self { + self.platform_specific.canvas = canvas; + + self + } +} + +#[cfg(feature = "web-sys")] +pub trait WindowBuilderExtWebSys { + fn with_canvas(self, canvas: Option) -> Self; +} + +#[cfg(feature = "web-sys")] +impl WindowBuilderExtWebSys for WindowBuilder { + fn with_canvas(mut self, canvas: Option) -> Self { + self.platform_specific.canvas = canvas; + + self + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform/windows.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform/windows.rs new file mode 100644 index 0000000..a356f1e --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform/windows.rs @@ -0,0 +1,213 @@ +#![cfg(target_os = "windows")] + +use std::os::raw::c_void; +use std::path::Path; + +use libc; +use winapi::shared::minwindef::WORD; +use winapi::shared::windef::HWND; + +use crate::{ + dpi::PhysicalSize, + event::DeviceId, + event_loop::EventLoop, + monitor::MonitorHandle, + platform_impl::{EventLoop as WindowsEventLoop, WinIcon}, + window::{BadIcon, Icon, Window, WindowBuilder}, +}; + +/// Additional methods on `EventLoop` that are specific to Windows. +pub trait EventLoopExtWindows { + /// Creates an event loop off of the main thread. + /// + /// # `Window` caveats + /// + /// Note that any `Window` created on the new thread will be destroyed when the thread + /// terminates. Attempting to use a `Window` after its parent thread terminates has + /// unspecified, although explicitly not undefined, behavior. + fn new_any_thread() -> Self + where + Self: Sized; + + /// By default, winit on Windows will attempt to enable process-wide DPI awareness. If that's + /// undesirable, you can create an `EventLoop` using this function instead. + fn new_dpi_unaware() -> Self + where + Self: Sized; + + /// Creates a DPI-unaware event loop off of the main thread. + /// + /// The `Window` caveats in [`new_any_thread`](EventLoopExtWindows::new_any_thread) also apply here. + fn new_dpi_unaware_any_thread() -> Self + where + Self: Sized; +} + +impl EventLoopExtWindows for EventLoop { + #[inline] + fn new_any_thread() -> Self { + EventLoop { + event_loop: WindowsEventLoop::new_any_thread(), + _marker: ::std::marker::PhantomData, + } + } + + #[inline] + fn new_dpi_unaware() -> Self { + EventLoop { + event_loop: WindowsEventLoop::new_dpi_unaware(), + _marker: ::std::marker::PhantomData, + } + } + + #[inline] + fn new_dpi_unaware_any_thread() -> Self { + EventLoop { + event_loop: WindowsEventLoop::new_dpi_unaware_any_thread(), + _marker: ::std::marker::PhantomData, + } + } +} + +/// Additional methods on `Window` that are specific to Windows. +pub trait WindowExtWindows { + /// Returns the HINSTANCE of the window + fn hinstance(&self) -> *mut libc::c_void; + /// Returns the native handle that is used by this window. + /// + /// The pointer will become invalid when the native window was destroyed. + fn hwnd(&self) -> *mut libc::c_void; + + /// This sets `ICON_BIG`. A good ceiling here is 256x256. + fn set_taskbar_icon(&self, taskbar_icon: Option); + + /// Whether the system theme is currently Windows 10's "Dark Mode". + fn is_dark_mode(&self) -> bool; +} + +impl WindowExtWindows for Window { + #[inline] + fn hinstance(&self) -> *mut libc::c_void { + self.window.hinstance() as *mut _ + } + + #[inline] + fn hwnd(&self) -> *mut libc::c_void { + self.window.hwnd() as *mut _ + } + + #[inline] + fn set_taskbar_icon(&self, taskbar_icon: Option) { + self.window.set_taskbar_icon(taskbar_icon) + } + + #[inline] + fn is_dark_mode(&self) -> bool { + self.window.is_dark_mode() + } +} + +/// Additional methods on `WindowBuilder` that are specific to Windows. +pub trait WindowBuilderExtWindows { + /// Sets a parent to the window to be created. + fn with_parent_window(self, parent: HWND) -> WindowBuilder; + + /// This sets `ICON_BIG`. A good ceiling here is 256x256. + fn with_taskbar_icon(self, taskbar_icon: Option) -> WindowBuilder; + + /// This sets `WS_EX_NOREDIRECTIONBITMAP`. + fn with_no_redirection_bitmap(self, flag: bool) -> WindowBuilder; +} + +impl WindowBuilderExtWindows for WindowBuilder { + #[inline] + fn with_parent_window(mut self, parent: HWND) -> WindowBuilder { + self.platform_specific.parent = Some(parent); + self + } + + #[inline] + fn with_taskbar_icon(mut self, taskbar_icon: Option) -> WindowBuilder { + self.platform_specific.taskbar_icon = taskbar_icon; + self + } + + #[inline] + fn with_no_redirection_bitmap(mut self, flag: bool) -> WindowBuilder { + self.platform_specific.no_redirection_bitmap = flag; + self + } +} + +/// Additional methods on `MonitorHandle` that are specific to Windows. +pub trait MonitorHandleExtWindows { + /// Returns the name of the monitor adapter specific to the Win32 API. + fn native_id(&self) -> String; + + /// Returns the handle of the monitor - `HMONITOR`. + fn hmonitor(&self) -> *mut c_void; +} + +impl MonitorHandleExtWindows for MonitorHandle { + #[inline] + fn native_id(&self) -> String { + self.inner.native_identifier() + } + + #[inline] + fn hmonitor(&self) -> *mut c_void { + self.inner.hmonitor() as *mut _ + } +} + +/// Additional methods on `DeviceId` that are specific to Windows. +pub trait DeviceIdExtWindows { + /// Returns an identifier that persistently refers to this specific device. + /// + /// Will return `None` if the device is no longer available. + fn persistent_identifier(&self) -> Option; +} + +impl DeviceIdExtWindows for DeviceId { + #[inline] + fn persistent_identifier(&self) -> Option { + self.0.persistent_identifier() + } +} + +/// Additional methods on `Icon` that are specific to Windows. +pub trait IconExtWindows: Sized { + /// Create an icon from a file path. + /// + /// Specify `size` to load a specific icon size from the file, or `None` to load the default + /// icon size from the file. + /// + /// In cases where the specified size does not exist in the file, Windows may perform scaling + /// to get an icon of the desired size. + fn from_path>(path: P, size: Option>) + -> Result; + + /// Create an icon from a resource embedded in this executable or library. + /// + /// Specify `size` to load a specific icon size from the file, or `None` to load the default + /// icon size from the file. + /// + /// In cases where the specified size does not exist in the file, Windows may perform scaling + /// to get an icon of the desired size. + fn from_resource(ordinal: WORD, size: Option>) -> Result; +} + +impl IconExtWindows for Icon { + fn from_path>( + path: P, + size: Option>, + ) -> Result { + let win_icon = WinIcon::from_path(path, size)?; + Ok(Icon { inner: win_icon }) + } + + fn from_resource(ordinal: WORD, size: Option>) -> Result { + let win_icon = WinIcon::from_resource(ordinal, size)?; + Ok(Icon { inner: win_icon }) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/ffi.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/ffi.rs new file mode 100644 index 0000000..93a59b8 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/ffi.rs @@ -0,0 +1,122 @@ +#![allow(dead_code)] +#![allow(non_snake_case)] +#![allow(non_camel_case_types)] +#![allow(non_upper_case_globals)] + +use libc; +use std::os::raw; + +#[link(name = "android")] +#[link(name = "EGL")] +#[link(name = "GLESv2")] +extern "C" {} + +/** + ** asset_manager.h + **/ +pub type AAssetManager = raw::c_void; + +/** + ** native_window.h + **/ +pub type ANativeWindow = raw::c_void; + +extern "C" { + pub fn ANativeWindow_getHeight(window: *const ANativeWindow) -> libc::int32_t; + pub fn ANativeWindow_getWidth(window: *const ANativeWindow) -> libc::int32_t; +} + +/** + ** native_activity.h + **/ +pub type JavaVM = (); +pub type JNIEnv = (); +pub type jobject = *const libc::c_void; + +pub type AInputQueue = (); // FIXME: wrong +pub type ARect = (); // FIXME: wrong + +#[repr(C)] +pub struct ANativeActivity { + pub callbacks: *mut ANativeActivityCallbacks, + pub vm: *mut JavaVM, + pub env: *mut JNIEnv, + pub clazz: jobject, + pub internalDataPath: *const libc::c_char, + pub externalDataPath: *const libc::c_char, + pub sdkVersion: libc::int32_t, + pub instance: *mut libc::c_void, + pub assetManager: *mut AAssetManager, + pub obbPath: *const libc::c_char, +} + +#[repr(C)] +pub struct ANativeActivityCallbacks { + pub onStart: extern "C" fn(*mut ANativeActivity), + pub onResume: extern "C" fn(*mut ANativeActivity), + pub onSaveInstanceState: extern "C" fn(*mut ANativeActivity, *mut libc::size_t), + pub onPause: extern "C" fn(*mut ANativeActivity), + pub onStop: extern "C" fn(*mut ANativeActivity), + pub onDestroy: extern "C" fn(*mut ANativeActivity), + pub onWindowFocusChanged: extern "C" fn(*mut ANativeActivity, libc::c_int), + pub onNativeWindowCreated: extern "C" fn(*mut ANativeActivity, *const ANativeWindow), + pub onNativeWindowResized: extern "C" fn(*mut ANativeActivity, *const ANativeWindow), + pub onNativeWindowRedrawNeeded: extern "C" fn(*mut ANativeActivity, *const ANativeWindow), + pub onNativeWindowDestroyed: extern "C" fn(*mut ANativeActivity, *const ANativeWindow), + pub onInputQueueCreated: extern "C" fn(*mut ANativeActivity, *mut AInputQueue), + pub onInputQueueDestroyed: extern "C" fn(*mut ANativeActivity, *mut AInputQueue), + pub onContentRectChanged: extern "C" fn(*mut ANativeActivity, *const ARect), + pub onConfigurationChanged: extern "C" fn(*mut ANativeActivity), + pub onLowMemory: extern "C" fn(*mut ANativeActivity), +} + +/** + ** looper.h + **/ +pub type ALooper = (); + +#[link(name = "android")] +extern "C" { + pub fn ALooper_forThread() -> *const ALooper; + pub fn ALooper_acquire(looper: *const ALooper); + pub fn ALooper_release(looper: *const ALooper); + pub fn ALooper_prepare(opts: libc::c_int) -> *const ALooper; + pub fn ALooper_pollOnce( + timeoutMillis: libc::c_int, + outFd: *mut libc::c_int, + outEvents: *mut libc::c_int, + outData: *mut *mut libc::c_void, + ) -> libc::c_int; + pub fn ALooper_pollAll( + timeoutMillis: libc::c_int, + outFd: *mut libc::c_int, + outEvents: *mut libc::c_int, + outData: *mut *mut libc::c_void, + ) -> libc::c_int; + pub fn ALooper_wake(looper: *const ALooper); + pub fn ALooper_addFd( + looper: *const ALooper, + fd: libc::c_int, + ident: libc::c_int, + events: libc::c_int, + callback: ALooper_callbackFunc, + data: *mut libc::c_void, + ) -> libc::c_int; + pub fn ALooper_removeFd(looper: *const ALooper, fd: libc::c_int) -> libc::c_int; +} + +pub const ALOOPER_PREPARE_ALLOW_NON_CALLBACKS: libc::c_int = 1 << 0; + +pub const ALOOPER_POLL_WAKE: libc::c_int = -1; +pub const ALOOPER_POLL_CALLBACK: libc::c_int = -2; +pub const ALOOPER_POLL_TIMEOUT: libc::c_int = -3; +pub const ALOOPER_POLL_ERROR: libc::c_int = -4; + +pub const ALOOPER_EVENT_INPUT: libc::c_int = 1 << 0; +pub const ALOOPER_EVENT_OUTPUT: libc::c_int = 1 << 1; +pub const ALOOPER_EVENT_ERROR: libc::c_int = 1 << 2; +pub const ALOOPER_EVENT_HANGUP: libc::c_int = 1 << 3; +pub const ALOOPER_EVENT_INVALID: libc::c_int = 1 << 4; + +pub type ALooper_callbackFunc = + extern "C" fn(libc::c_int, libc::c_int, *mut libc::c_void) -> libc::c_int; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/android/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/mod.rs similarity index 55% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/android/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/mod.rs index dad7380..cf18937 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/android/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/android/mod.rs @@ -4,68 +4,69 @@ extern crate android_glue; mod ffi; -use std::cell::RefCell; -use std::collections::VecDeque; -use std::fmt; -use std::os::raw::c_void; -use std::sync::mpsc::{Receiver, channel}; - -use { - CreationError, - Event, - LogicalPosition, - LogicalSize, - MouseCursor, - PhysicalPosition, - PhysicalSize, - WindowAttributes, - WindowEvent, - WindowId as RootWindowId, +use std::{ + cell::RefCell, + collections::VecDeque, + fmt, + os::raw::c_void, + sync::mpsc::{channel, Receiver}, }; -use CreationError::OsError; -use events::{Touch, TouchPhase}; -use window::MonitorId as RootMonitorId; -pub struct EventsLoop { +use crate::{ + error::{ExternalError, NotSupportedError}, + events::{Touch, TouchPhase}, + window::MonitorHandle as RootMonitorHandle, + CreationError, CursorIcon, Event, LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, + WindowAttributes, WindowEvent, WindowId as RootWindowId, +}; +use raw_window_handle::{android::AndroidHandle, RawWindowHandle}; +use CreationError::OsError; + +pub(crate) use crate::icon::NoIcon as PlatformIcon; + +pub type OsError = std::io::Error; + +pub struct EventLoop { event_rx: Receiver, - suspend_callback: RefCell ()>>>, + suspend_callback: RefCell ()>>>, } #[derive(Clone)] -pub struct EventsLoopProxy; +pub struct EventLoopProxy; -impl EventsLoop { - pub fn new() -> EventsLoop { +impl EventLoop { + pub fn new() -> EventLoop { let (tx, rx) = channel(); android_glue::add_sender(tx); - EventsLoop { + EventLoop { event_rx: rx, suspend_callback: Default::default(), } } #[inline] - pub fn get_available_monitors(&self) -> VecDeque { + pub fn available_monitors(&self) -> VecDeque { let mut rb = VecDeque::with_capacity(1); - rb.push_back(MonitorId); + rb.push_back(MonitorHandle); rb } #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId + pub fn primary_monitor(&self) -> MonitorHandle { + MonitorHandle } pub fn poll_events(&mut self, mut callback: F) - where F: FnMut(::Event) + where + F: FnMut(::Event), { while let Ok(event) = self.event_rx.try_recv() { - let e = match event{ + let e = match event { android_glue::Event::EventMotion(motion) => { - let dpi_factor = MonitorId.get_hidpi_factor(); + let scale_factor = MonitorHandle.scale_factor(); let location = LogicalPosition::from_physical( (motion.x as f64, motion.y as f64), - dpi_factor, + scale_factor, ); Some(Event::WindowEvent { window_id: RootWindowId(WindowId), @@ -77,68 +78,65 @@ impl EventsLoop { android_glue::MotionAction::Cancel => TouchPhase::Cancelled, }, location, + force: None, // TODO id: motion.pointer_id as u64, device_id: DEVICE_ID, }), }) - }, + } android_glue::Event::InitWindow => { // The activity went to foreground. if let Some(cb) = self.suspend_callback.borrow().as_ref() { (*cb)(false); } - Some(Event::Suspended(false)) - }, + Some(Event::Resumed) + } android_glue::Event::TermWindow => { // The activity went to background. if let Some(cb) = self.suspend_callback.borrow().as_ref() { (*cb)(true); } - Some(Event::Suspended(true)) - }, - android_glue::Event::WindowResized | - android_glue::Event::ConfigChanged => { + Some(Event::Suspended) + } + android_glue::Event::WindowResized | android_glue::Event::ConfigChanged => { // Activity Orientation changed or resized. - let native_window = unsafe { android_glue::get_native_window() }; + let native_window = unsafe { android_glue::native_window() }; if native_window.is_null() { None } else { - let dpi_factor = MonitorId.get_hidpi_factor(); - let physical_size = MonitorId.get_dimensions(); - let size = LogicalSize::from_physical(physical_size, dpi_factor); + let scale_factor = MonitorHandle.scale_factor(); + let physical_size = MonitorHandle.size(); + let size = LogicalSize::from_physical(physical_size, scale_factor); Some(Event::WindowEvent { window_id: RootWindowId(WindowId), event: WindowEvent::Resized(size), }) } - }, + } android_glue::Event::WindowRedrawNeeded => { // The activity needs to be redrawn. Some(Event::WindowEvent { window_id: RootWindowId(WindowId), - event: WindowEvent::Refresh, + event: WindowEvent::Redraw, }) } - android_glue::Event::Wake => { - Some(Event::Awakened) - } - _ => { - None - } + android_glue::Event::Wake => Some(Event::Awakened), + _ => None, }; if let Some(event) = e { callback(event); } - }; + } } - pub fn set_suspend_callback(&self, cb: Option ()>>) { + pub fn set_suspend_callback(&self, cb: Option ()>>) { *self.suspend_callback.borrow_mut() = cb; } pub fn run_forever(&mut self, mut callback: F) - where F: FnMut(::Event) -> ::ControlFlow, + where + F: FnMut(::Event) -> ::ControlFlow, { // Yeah that's a very bad implementation. loop { @@ -155,13 +153,13 @@ impl EventsLoop { } } - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy } } -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), ::EventsLoopClosed> { +impl EventLoopProxy { + pub fn wakeup(&self) -> Result<(), ::EventLoopClosed<()>> { android_glue::wake_event_loop(); Ok(()) } @@ -190,54 +188,55 @@ pub struct Window { } #[derive(Clone)] -pub struct MonitorId; +pub struct MonitorHandle; -impl fmt::Debug for MonitorId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { #[derive(Debug)] - struct MonitorId { + struct MonitorHandle { name: Option, - dimensions: PhysicalSize, - position: PhysicalPosition, - hidpi_factor: f64, + dimensions: PhysicalSize, + position: PhysicalPosition, + scale_factor: f64, } - let monitor_id_proxy = MonitorId { - name: self.get_name(), - dimensions: self.get_dimensions(), - position: self.get_position(), - hidpi_factor: self.get_hidpi_factor(), + let monitor_id_proxy = MonitorHandle { + name: self.name(), + dimensions: self.size(), + position: self.outer_position(), + scale_factor: self.scale_factor(), }; monitor_id_proxy.fmt(f) } } -impl MonitorId { +impl MonitorHandle { #[inline] - pub fn get_name(&self) -> Option { + pub fn name(&self) -> Option { Some("Primary".to_string()) } #[inline] - pub fn get_dimensions(&self) -> PhysicalSize { + pub fn size(&self) -> PhysicalSize { unsafe { - let window = android_glue::get_native_window(); + let window = android_glue::native_window(); ( ffi::ANativeWindow_getWidth(window) as f64, ffi::ANativeWindow_getHeight(window) as f64, - ).into() + ) + .into() } } #[inline] - pub fn get_position(&self) -> PhysicalPosition { + pub fn outer_position(&self) -> PhysicalPosition { // Android assumes single screen (0, 0).into() } #[inline] - pub fn get_hidpi_factor(&self) -> f64 { + pub fn scale_factor(&self) -> f64 { 1.0 } } @@ -248,16 +247,17 @@ pub struct PlatformSpecificWindowBuilderAttributes; pub struct PlatformSpecificHeadlessBuilderAttributes; impl Window { - pub fn new(_: &EventsLoop, win_attribs: WindowAttributes, - _: PlatformSpecificWindowBuilderAttributes) - -> Result - { - let native_window = unsafe { android_glue::get_native_window() }; + pub fn new( + _: &EventLoop, + win_attribs: WindowAttributes, + _: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + let native_window = unsafe { android_glue::native_window() }; if native_window.is_null() { return Err(OsError(format!("Android's native window is null"))); } - android_glue::set_multitouch(win_attribs.multitouch); + android_glue::set_multitouch(true); Ok(Window { native_window: native_window as *const _, @@ -265,7 +265,7 @@ impl Window { } #[inline] - pub fn get_native_window(&self) -> *const c_void { + pub fn native_window(&self) -> *const c_void { self.native_window } @@ -285,29 +285,29 @@ impl Window { } #[inline] - pub fn get_position(&self) -> Option { + pub fn outer_position(&self) -> Option> { // N/A None } #[inline] - pub fn get_inner_position(&self) -> Option { + pub fn inner_position(&self) -> Option> { // N/A None } #[inline] - pub fn set_position(&self, _position: LogicalPosition) { + pub fn set_outer_position(&self, _position: LogicalPosition) { // N/A } #[inline] - pub fn set_min_dimensions(&self, _dimensions: Option) { + pub fn set_min_inner_size(&self, _dimensions: Option>) { // N/A } #[inline] - pub fn set_max_dimensions(&self, _dimensions: Option) { + pub fn set_max_inner_size(&self, _dimensions: Option>) { // N/A } @@ -317,39 +317,39 @@ impl Window { } #[inline] - pub fn get_inner_size(&self) -> Option { + pub fn inner_size(&self) -> Option> { if self.native_window.is_null() { None } else { - let dpi_factor = self.get_hidpi_factor(); - let physical_size = self.get_current_monitor().get_dimensions(); - Some(LogicalSize::from_physical(physical_size, dpi_factor)) + let scale_factor = self.scale_factor(); + let physical_size = self.current_monitor().size(); + Some(LogicalSize::from_physical(physical_size, scale_factor)) } } #[inline] - pub fn get_outer_size(&self) -> Option { - self.get_inner_size() + pub fn outer_size(&self) -> Option> { + self.inner_size() } #[inline] - pub fn set_inner_size(&self, _size: LogicalSize) { + pub fn set_inner_size(&self, _size: LogicalSize) { // N/A } #[inline] - pub fn get_hidpi_factor(&self) -> f64 { - self.get_current_monitor().get_hidpi_factor() + pub fn scale_factor(&self) -> f64 { + self.current_monitor().scale_factor() } #[inline] - pub fn set_cursor(&self, _: MouseCursor) { + pub fn set_cursor_icon(&self, _: CursorIcon) { // N/A } #[inline] - pub fn grab_cursor(&self, _grab: bool) -> Result<(), String> { - Err("Cursor grabbing is not possible on Android.".to_owned()) + pub fn set_cursor_grab(&self, _grab: bool) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) } #[inline] @@ -358,8 +358,16 @@ impl Window { } #[inline] - pub fn set_cursor_position(&self, _position: LogicalPosition) -> Result<(), String> { - Err("Setting cursor position is not possible on Android.".to_owned()) + pub fn set_cursor_position( + &self, + _position: LogicalPosition, + ) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn set_minimized(&self, _minimized: bool) { + unimplemented!() } #[inline] @@ -369,7 +377,14 @@ impl Window { } #[inline] - pub fn set_fullscreen(&self, _monitor: Option) { + pub fn fullscreen(&self) -> Option { + // N/A + // Android has single screen maximized apps so nothing to do + None + } + + #[inline] + pub fn set_fullscreen(&self, _monitor: Option) { // N/A // Android has single screen maximized apps so nothing to do } @@ -390,31 +405,42 @@ impl Window { } #[inline] - pub fn set_ime_spot(&self, _spot: LogicalPosition) { + pub fn set_ime_position(&self, _spot: LogicalPosition) { // N/A } #[inline] - pub fn get_current_monitor(&self) -> RootMonitorId { - RootMonitorId { inner: MonitorId } + pub fn current_monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: MonitorHandle, + } } #[inline] - pub fn get_available_monitors(&self) -> VecDeque { + pub fn available_monitors(&self) -> VecDeque { let mut rb = VecDeque::with_capacity(1); - rb.push_back(MonitorId); + rb.push_back(MonitorHandle); rb } #[inline] - pub fn get_primary_monitor(&self) -> MonitorId { - MonitorId + pub fn primary_monitor(&self) -> MonitorHandle { + MonitorHandle } #[inline] pub fn id(&self) -> WindowId { WindowId } + + #[inline] + pub fn raw_window_handle(&self) -> RawWindowHandle { + let handle = AndroidHandle { + a_native_window: self.native_window, + ..WindowsHandle::empty() + }; + RawWindowHandle::Android(handle) + } } unsafe impl Send for Window {} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/app_state.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/app_state.rs new file mode 100644 index 0000000..0d388c5 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/app_state.rs @@ -0,0 +1,1046 @@ +#![deny(unused_results)] + +use std::{ + cell::{RefCell, RefMut}, + collections::HashSet, + mem, + os::raw::c_void, + ptr, + time::Instant, +}; + +use objc::runtime::{BOOL, YES}; + +use crate::{ + dpi::LogicalSize, + event::{Event, StartCause, WindowEvent}, + event_loop::ControlFlow, + platform_impl::platform::{ + event_loop::{EventHandler, EventProxy, EventWrapper, Never}, + ffi::{ + id, kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRelease, CFRunLoopAddTimer, + CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate, + CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CGRect, CGSize, NSInteger, + NSOperatingSystemVersion, NSUInteger, + }, + }, + window::WindowId as RootWindowId, +}; + +macro_rules! bug { + ($($msg:tt)*) => { + panic!("winit iOS bug, file an issue: {}", format!($($msg)*)) + }; +} + +macro_rules! bug_assert { + ($test:expr, $($msg:tt)*) => { + assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*)) + }; +} + +enum UserCallbackTransitionResult<'a> { + Success { + event_handler: Box, + active_control_flow: ControlFlow, + processing_redraws: bool, + }, + ReentrancyPrevented { + queued_events: &'a mut Vec, + }, +} + +impl Event<'static, Never> { + fn is_redraw(&self) -> bool { + if let Event::RedrawRequested(_) = self { + true + } else { + false + } + } +} + +// this is the state machine for the app lifecycle +#[derive(Debug)] +#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"] +enum AppStateImpl { + NotLaunched { + queued_windows: Vec, + queued_events: Vec, + queued_gpu_redraws: HashSet, + }, + Launching { + queued_windows: Vec, + queued_events: Vec, + queued_event_handler: Box, + queued_gpu_redraws: HashSet, + }, + ProcessingEvents { + event_handler: Box, + queued_gpu_redraws: HashSet, + active_control_flow: ControlFlow, + }, + // special state to deal with reentrancy and prevent mutable aliasing. + InUserCallback { + queued_events: Vec, + queued_gpu_redraws: HashSet, + }, + ProcessingRedraws { + event_handler: Box, + active_control_flow: ControlFlow, + }, + Waiting { + waiting_event_handler: Box, + start: Instant, + }, + PollFinished { + waiting_event_handler: Box, + }, + Terminated, +} + +struct AppState { + // This should never be `None`, except for briefly during a state transition. + app_state: Option, + control_flow: ControlFlow, + waker: EventLoopWaker, +} + +impl Drop for AppState { + fn drop(&mut self) { + match self.state_mut() { + &mut AppStateImpl::NotLaunched { + ref mut queued_windows, + .. + } + | &mut AppStateImpl::Launching { + ref mut queued_windows, + .. + } => { + for &mut window in queued_windows { + unsafe { + let () = msg_send![window, release]; + } + } + } + _ => {} + } + } +} + +impl AppState { + // requires main thread + unsafe fn get_mut() -> RefMut<'static, AppState> { + // basically everything in UIKit requires the main thread, so it's pointless to use the + // std::sync APIs. + // must be mut because plain `static` requires `Sync` + static mut APP_STATE: RefCell> = RefCell::new(None); + + if cfg!(debug_assertions) { + assert_main_thread!( + "bug in winit: `AppState::get_mut()` can only be called on the main thread" + ); + } + let mut guard = APP_STATE.borrow_mut(); + if guard.is_none() { + #[inline(never)] + #[cold] + unsafe fn init_guard(guard: &mut RefMut<'static, Option>) { + let waker = EventLoopWaker::new(CFRunLoopGetMain()); + **guard = Some(AppState { + app_state: Some(AppStateImpl::NotLaunched { + queued_windows: Vec::new(), + queued_events: Vec::new(), + queued_gpu_redraws: HashSet::new(), + }), + control_flow: ControlFlow::default(), + waker, + }); + } + init_guard(&mut guard) + } + RefMut::map(guard, |state| state.as_mut().unwrap()) + } + + fn state(&self) -> &AppStateImpl { + match &self.app_state { + Some(ref state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn state_mut(&mut self) -> &mut AppStateImpl { + match &mut self.app_state { + Some(ref mut state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn take_state(&mut self) -> AppStateImpl { + match self.app_state.take() { + Some(state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn set_state(&mut self, new_state: AppStateImpl) { + bug_assert!( + self.app_state.is_none(), + "attempted to set an `AppState` without calling `take_state` first {:?}", + self.app_state + ); + self.app_state = Some(new_state) + } + + fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl { + match &mut self.app_state { + Some(ref mut state) => mem::replace(state, new_state), + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn has_launched(&self) -> bool { + match self.state() { + &AppStateImpl::NotLaunched { .. } | &AppStateImpl::Launching { .. } => false, + _ => true, + } + } + + fn will_launch_transition(&mut self, queued_event_handler: Box) { + let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() { + AppStateImpl::NotLaunched { + queued_windows, + queued_events, + queued_gpu_redraws, + } => (queued_windows, queued_events, queued_gpu_redraws), + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::Launching { + queued_windows, + queued_events, + queued_event_handler, + queued_gpu_redraws, + }); + } + + fn did_finish_launching_transition(&mut self) -> (Vec, Vec) { + let (windows, events, event_handler, queued_gpu_redraws) = match self.take_state() { + AppStateImpl::Launching { + queued_windows, + queued_events, + queued_event_handler, + queued_gpu_redraws, + } => ( + queued_windows, + queued_events, + queued_event_handler, + queued_gpu_redraws, + ), + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::ProcessingEvents { + event_handler, + active_control_flow: ControlFlow::Poll, + queued_gpu_redraws, + }); + (windows, events) + } + + fn wakeup_transition(&mut self) -> Option { + // before `AppState::did_finish_launching` is called, pretend there is no running + // event loop. + if !self.has_launched() { + return None; + } + + let (event_handler, event) = match (self.control_flow, self.take_state()) { + ( + ControlFlow::Poll, + AppStateImpl::PollFinished { + waiting_event_handler, + }, + ) => ( + waiting_event_handler, + EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)), + ), + ( + ControlFlow::Wait, + AppStateImpl::Waiting { + waiting_event_handler, + start, + }, + ) => ( + waiting_event_handler, + EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { + start, + requested_resume: None, + })), + ), + ( + ControlFlow::WaitUntil(requested_resume), + AppStateImpl::Waiting { + waiting_event_handler, + start, + }, + ) => { + let event = if Instant::now() >= requested_resume { + EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached { + start, + requested_resume, + })) + } else { + EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { + start, + requested_resume: Some(requested_resume), + })) + }; + (waiting_event_handler, event) + } + (ControlFlow::Exit, _) => bug!("unexpected `ControlFlow` `Exit`"), + s => bug!("`EventHandler` unexpectedly woke up {:?}", s), + }; + + self.set_state(AppStateImpl::ProcessingEvents { + event_handler, + queued_gpu_redraws: Default::default(), + active_control_flow: self.control_flow, + }); + Some(event) + } + + fn try_user_callback_transition(&mut self) -> UserCallbackTransitionResult<'_> { + // If we're not able to process an event due to recursion or `Init` not having been sent out + // yet, then queue the events up. + match self.state_mut() { + &mut AppStateImpl::Launching { + ref mut queued_events, + .. + } + | &mut AppStateImpl::NotLaunched { + ref mut queued_events, + .. + } + | &mut AppStateImpl::InUserCallback { + ref mut queued_events, + .. + } => { + // A lifetime cast: early returns are not currently handled well with NLL, but + // polonius handles them well. This transmute is a safe workaround. + return unsafe { + mem::transmute::< + UserCallbackTransitionResult<'_>, + UserCallbackTransitionResult<'_>, + >(UserCallbackTransitionResult::ReentrancyPrevented { + queued_events, + }) + }; + } + + &mut AppStateImpl::ProcessingEvents { .. } + | &mut AppStateImpl::ProcessingRedraws { .. } => {} + + s @ &mut AppStateImpl::PollFinished { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::Terminated => { + bug!("unexpected attempted to process an event {:?}", s) + } + } + + let (event_handler, queued_gpu_redraws, active_control_flow, processing_redraws) = + match self.take_state() { + AppStateImpl::Launching { .. } + | AppStateImpl::NotLaunched { .. } + | AppStateImpl::InUserCallback { .. } => unreachable!(), + AppStateImpl::ProcessingEvents { + event_handler, + queued_gpu_redraws, + active_control_flow, + } => ( + event_handler, + queued_gpu_redraws, + active_control_flow, + false, + ), + AppStateImpl::ProcessingRedraws { + event_handler, + active_control_flow, + } => (event_handler, Default::default(), active_control_flow, true), + AppStateImpl::PollFinished { .. } + | AppStateImpl::Waiting { .. } + | AppStateImpl::Terminated => unreachable!(), + }; + self.set_state(AppStateImpl::InUserCallback { + queued_events: Vec::new(), + queued_gpu_redraws, + }); + UserCallbackTransitionResult::Success { + event_handler, + active_control_flow, + processing_redraws, + } + } + + fn main_events_cleared_transition(&mut self) -> HashSet { + let (event_handler, queued_gpu_redraws, active_control_flow) = match self.take_state() { + AppStateImpl::ProcessingEvents { + event_handler, + queued_gpu_redraws, + active_control_flow, + } => (event_handler, queued_gpu_redraws, active_control_flow), + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::ProcessingRedraws { + event_handler, + active_control_flow, + }); + queued_gpu_redraws + } + + fn events_cleared_transition(&mut self) { + if !self.has_launched() { + return; + } + let (waiting_event_handler, old) = match self.take_state() { + AppStateImpl::ProcessingRedraws { + event_handler, + active_control_flow, + } => (event_handler, active_control_flow), + s => bug!("unexpected state {:?}", s), + }; + + let new = self.control_flow; + match (old, new) { + (ControlFlow::Poll, ControlFlow::Poll) => self.set_state(AppStateImpl::PollFinished { + waiting_event_handler, + }), + (ControlFlow::Wait, ControlFlow::Wait) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { + waiting_event_handler, + start, + }); + } + (ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant)) + if old_instant == new_instant => + { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { + waiting_event_handler, + start, + }); + } + (_, ControlFlow::Wait) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { + waiting_event_handler, + start, + }); + self.waker.stop() + } + (_, ControlFlow::WaitUntil(new_instant)) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { + waiting_event_handler, + start, + }); + self.waker.start_at(new_instant) + } + (_, ControlFlow::Poll) => { + self.set_state(AppStateImpl::PollFinished { + waiting_event_handler, + }); + self.waker.start() + } + (_, ControlFlow::Exit) => { + // https://developer.apple.com/library/archive/qa/qa1561/_index.html + // it is not possible to quit an iOS app gracefully and programatically + warn!("`ControlFlow::Exit` ignored on iOS"); + self.control_flow = old + } + } + } + + fn terminated_transition(&mut self) -> Box { + match self.replace_state(AppStateImpl::Terminated) { + AppStateImpl::ProcessingEvents { event_handler, .. } => event_handler, + s => bug!( + "`LoopDestroyed` happened while not processing events {:?}", + s + ), + } + } +} + +// requires main thread and window is a UIWindow +// retains window +pub unsafe fn set_key_window(window: id) { + bug_assert!( + { + let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)]; + is_window == YES + }, + "set_key_window called with an incorrect type" + ); + let mut this = AppState::get_mut(); + match this.state_mut() { + &mut AppStateImpl::NotLaunched { + ref mut queued_windows, + .. + } => return queued_windows.push(msg_send![window, retain]), + &mut AppStateImpl::ProcessingEvents { .. } + | &mut AppStateImpl::InUserCallback { .. } + | &mut AppStateImpl::ProcessingRedraws { .. } => {} + s @ &mut AppStateImpl::Launching { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), + &mut AppStateImpl::Terminated => { + panic!("Attempt to create a `Window` after the app has terminated") + } + } + drop(this); + msg_send![window, makeKeyAndVisible] +} + +// requires main thread and window is a UIWindow +// retains window +pub unsafe fn queue_gl_or_metal_redraw(window: id) { + bug_assert!( + { + let is_window: BOOL = msg_send![window, isKindOfClass: class!(UIWindow)]; + is_window == YES + }, + "set_key_window called with an incorrect type" + ); + let mut this = AppState::get_mut(); + match this.state_mut() { + &mut AppStateImpl::NotLaunched { + ref mut queued_gpu_redraws, + .. + } + | &mut AppStateImpl::Launching { + ref mut queued_gpu_redraws, + .. + } + | &mut AppStateImpl::ProcessingEvents { + ref mut queued_gpu_redraws, + .. + } + | &mut AppStateImpl::InUserCallback { + ref mut queued_gpu_redraws, + .. + } => drop(queued_gpu_redraws.insert(window)), + s @ &mut AppStateImpl::ProcessingRedraws { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), + &mut AppStateImpl::Terminated => { + panic!("Attempt to create a `Window` after the app has terminated") + } + } + drop(this); +} + +// requires main thread +pub unsafe fn will_launch(queued_event_handler: Box) { + AppState::get_mut().will_launch_transition(queued_event_handler) +} + +// requires main thread +pub unsafe fn did_finish_launching() { + let mut this = AppState::get_mut(); + let windows = match this.state_mut() { + AppStateImpl::Launching { queued_windows, .. } => mem::replace(queued_windows, Vec::new()), + s => bug!("unexpected state {:?}", s), + }; + + // start waking up the event loop now! + bug_assert!( + this.control_flow == ControlFlow::Poll, + "unexpectedly not setup to `Poll` on launch!" + ); + this.waker.start(); + + // have to drop RefMut because the window setup code below can trigger new events + drop(this); + + for window in windows { + let count: NSUInteger = msg_send![window, retainCount]; + // make sure the window is still referenced + if count > 1 { + // Do a little screen dance here to account for windows being created before + // `UIApplicationMain` is called. This fixes visual issues such as being + // offcenter and sized incorrectly. Additionally, to fix orientation issues, we + // gotta reset the `rootViewController`. + // + // relevant iOS log: + // ``` + // [ApplicationLifecycle] Windows were created before application initialzation + // completed. This may result in incorrect visual appearance. + // ``` + let screen: id = msg_send![window, screen]; + let _: id = msg_send![screen, retain]; + let () = msg_send![window, setScreen:0 as id]; + let () = msg_send![window, setScreen: screen]; + let () = msg_send![screen, release]; + let controller: id = msg_send![window, rootViewController]; + let () = msg_send![window, setRootViewController:ptr::null::<()>()]; + let () = msg_send![window, setRootViewController: controller]; + let () = msg_send![window, makeKeyAndVisible]; + } + let () = msg_send![window, release]; + } + + let (windows, events) = AppState::get_mut().did_finish_launching_transition(); + + let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents( + StartCause::Init, + ))) + .chain(events); + handle_nonuser_events(events); + + // the above window dance hack, could possibly trigger new windows to be created. + // we can just set those windows up normally, as they were created after didFinishLaunching + for window in windows { + let count: NSUInteger = msg_send![window, retainCount]; + // make sure the window is still referenced + if count > 1 { + let () = msg_send![window, makeKeyAndVisible]; + } + let () = msg_send![window, release]; + } +} + +// requires main thread +// AppState::did_finish_launching handles the special transition `Init` +pub unsafe fn handle_wakeup_transition() { + let mut this = AppState::get_mut(); + let wakeup_event = match this.wakeup_transition() { + None => return, + Some(wakeup_event) => wakeup_event, + }; + drop(this); + + handle_nonuser_event(wakeup_event) +} + +// requires main thread +pub unsafe fn handle_nonuser_event(event: EventWrapper) { + handle_nonuser_events(std::iter::once(event)) +} + +// requires main thread +pub unsafe fn handle_nonuser_events>(events: I) { + let mut this = AppState::get_mut(); + let (mut event_handler, active_control_flow, processing_redraws) = + match this.try_user_callback_transition() { + UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => { + queued_events.extend(events); + return; + } + UserCallbackTransitionResult::Success { + event_handler, + active_control_flow, + processing_redraws, + } => (event_handler, active_control_flow, processing_redraws), + }; + let mut control_flow = this.control_flow; + drop(this); + + for wrapper in events { + match wrapper { + EventWrapper::StaticEvent(event) => { + if !processing_redraws && event.is_redraw() { + log::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + log::warn!( + "processing non `RedrawRequested` event after the main event loop: {:#?}", + event + ); + } + event_handler.handle_nonuser_event(event, &mut control_flow) + } + EventWrapper::EventProxy(proxy) => { + handle_event_proxy(&mut event_handler, control_flow, proxy) + } + } + } + + loop { + let mut this = AppState::get_mut(); + let queued_events = match this.state_mut() { + &mut AppStateImpl::InUserCallback { + ref mut queued_events, + queued_gpu_redraws: _, + } => mem::replace(queued_events, Vec::new()), + s => bug!("unexpected state {:?}", s), + }; + if queued_events.is_empty() { + let queued_gpu_redraws = match this.take_state() { + AppStateImpl::InUserCallback { + queued_events: _, + queued_gpu_redraws, + } => queued_gpu_redraws, + _ => unreachable!(), + }; + this.app_state = Some(if processing_redraws { + bug_assert!( + queued_gpu_redraws.is_empty(), + "redraw queued while processing redraws" + ); + AppStateImpl::ProcessingRedraws { + event_handler, + active_control_flow, + } + } else { + AppStateImpl::ProcessingEvents { + event_handler, + queued_gpu_redraws, + active_control_flow, + } + }); + this.control_flow = control_flow; + break; + } + drop(this); + + for wrapper in queued_events { + match wrapper { + EventWrapper::StaticEvent(event) => { + if !processing_redraws && event.is_redraw() { + log::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + log::warn!( + "processing non-`RedrawRequested` event after the main event loop: {:#?}", + event + ); + } + event_handler.handle_nonuser_event(event, &mut control_flow) + } + EventWrapper::EventProxy(proxy) => { + handle_event_proxy(&mut event_handler, control_flow, proxy) + } + } + } + } +} + +// requires main thread +unsafe fn handle_user_events() { + let mut this = AppState::get_mut(); + let mut control_flow = this.control_flow; + let (mut event_handler, active_control_flow, processing_redraws) = + match this.try_user_callback_transition() { + UserCallbackTransitionResult::ReentrancyPrevented { .. } => { + bug!("unexpected attempted to process an event") + } + UserCallbackTransitionResult::Success { + event_handler, + active_control_flow, + processing_redraws, + } => (event_handler, active_control_flow, processing_redraws), + }; + if processing_redraws { + bug!("user events attempted to be sent out while `ProcessingRedraws`"); + } + drop(this); + + event_handler.handle_user_events(&mut control_flow); + + loop { + let mut this = AppState::get_mut(); + let queued_events = match this.state_mut() { + &mut AppStateImpl::InUserCallback { + ref mut queued_events, + queued_gpu_redraws: _, + } => mem::replace(queued_events, Vec::new()), + s => bug!("unexpected state {:?}", s), + }; + if queued_events.is_empty() { + let queued_gpu_redraws = match this.take_state() { + AppStateImpl::InUserCallback { + queued_events: _, + queued_gpu_redraws, + } => queued_gpu_redraws, + _ => unreachable!(), + }; + this.app_state = Some(AppStateImpl::ProcessingEvents { + event_handler, + queued_gpu_redraws, + active_control_flow, + }); + this.control_flow = control_flow; + break; + } + drop(this); + + for wrapper in queued_events { + match wrapper { + EventWrapper::StaticEvent(event) => { + event_handler.handle_nonuser_event(event, &mut control_flow) + } + EventWrapper::EventProxy(proxy) => { + handle_event_proxy(&mut event_handler, control_flow, proxy) + } + } + } + event_handler.handle_user_events(&mut control_flow); + } +} + +// requires main thread +pub unsafe fn handle_main_events_cleared() { + let mut this = AppState::get_mut(); + if !this.has_launched() { + return; + } + match this.state_mut() { + &mut AppStateImpl::ProcessingEvents { .. } => {} + _ => bug!("`ProcessingRedraws` happened unexpectedly"), + }; + drop(this); + + // User events are always sent out at the end of the "MainEventLoop" + handle_user_events(); + handle_nonuser_event(EventWrapper::StaticEvent(Event::MainEventsCleared)); + + let mut this = AppState::get_mut(); + let mut redraw_events: Vec = this + .main_events_cleared_transition() + .into_iter() + .map(|window| { + EventWrapper::StaticEvent(Event::RedrawRequested(RootWindowId(window.into()))) + }) + .collect(); + + if !redraw_events.is_empty() { + redraw_events.push(EventWrapper::StaticEvent(Event::RedrawEventsCleared)); + } + drop(this); + + handle_nonuser_events(redraw_events); +} + +// requires main thread +pub unsafe fn handle_events_cleared() { + AppState::get_mut().events_cleared_transition(); +} + +// requires main thread +pub unsafe fn terminated() { + let mut this = AppState::get_mut(); + let mut event_handler = this.terminated_transition(); + let mut control_flow = this.control_flow; + drop(this); + + event_handler.handle_nonuser_event(Event::LoopDestroyed, &mut control_flow) +} + +fn handle_event_proxy( + event_handler: &mut Box, + control_flow: ControlFlow, + proxy: EventProxy, +) { + match proxy { + EventProxy::DpiChangedProxy { + suggested_size, + scale_factor, + window_id, + } => handle_hidpi_proxy( + event_handler, + control_flow, + suggested_size, + scale_factor, + window_id, + ), + } +} + +fn handle_hidpi_proxy( + event_handler: &mut Box, + mut control_flow: ControlFlow, + suggested_size: LogicalSize, + scale_factor: f64, + window_id: id, +) { + let mut size = suggested_size.to_physical(scale_factor); + let new_inner_size = &mut size; + let event = Event::WindowEvent { + window_id: RootWindowId(window_id.into()), + event: WindowEvent::ScaleFactorChanged { + scale_factor, + new_inner_size, + }, + }; + event_handler.handle_nonuser_event(event, &mut control_flow); + let (view, screen_frame) = get_view_and_screen_frame(window_id); + let physical_size = *new_inner_size; + let logical_size = physical_size.to_logical(scale_factor); + let size = CGSize::new(logical_size); + let new_frame: CGRect = CGRect::new(screen_frame.origin, size); + unsafe { + let () = msg_send![view, setFrame: new_frame]; + } +} + +fn get_view_and_screen_frame(window_id: id) -> (id, CGRect) { + unsafe { + let view_controller: id = msg_send![window_id, rootViewController]; + let view: id = msg_send![view_controller, view]; + let bounds: CGRect = msg_send![window_id, bounds]; + let screen: id = msg_send![window_id, screen]; + let screen_space: id = msg_send![screen, coordinateSpace]; + let screen_frame: CGRect = + msg_send![window_id, convertRect:bounds toCoordinateSpace:screen_space]; + (view, screen_frame) + } +} + +struct EventLoopWaker { + timer: CFRunLoopTimerRef, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + unsafe { + CFRunLoopTimerInvalidate(self.timer); + CFRelease(self.timer as _); + } + } +} + +impl EventLoopWaker { + fn new(rl: CFRunLoopRef) -> EventLoopWaker { + extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimerCreate( + ptr::null_mut(), + std::f64::MAX, + 0.000_000_1, + 0, + 0, + wakeup_main_loop, + ptr::null_mut(), + ); + CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes); + + EventLoopWaker { timer } + } + } + + fn stop(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) } + } + + fn start(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) } + } + + fn start_at(&mut self, instant: Instant) { + let now = Instant::now(); + if now >= instant { + self.start(); + } else { + unsafe { + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = + duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; + CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) + } + } + } +} + +macro_rules! os_capabilities { + ( + $( + $(#[$attr:meta])* + $error_name:ident: $objc_call:literal, + $name:ident: $major:literal-$minor:literal + ),* + $(,)* + ) => { + #[derive(Clone, Debug)] + pub struct OSCapabilities { + $( + pub $name: bool, + )* + + os_version: NSOperatingSystemVersion, + } + + impl From for OSCapabilities { + fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities { + $(let $name = os_version.meets_requirements($major, $minor);)* + OSCapabilities { $($name,)* os_version, } + } + } + + impl OSCapabilities {$( + $(#[$attr])* + pub fn $error_name(&self, extra_msg: &str) { + log::warn!( + concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"), + $major, $minor, self.os_version.major, self.os_version.minor, self.os_version.patch, + extra_msg + ) + } + )*} + }; +} + +os_capabilities! { + /// https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc + #[allow(unused)] // error message unused + safe_area_err_msg: "-[UIView safeAreaInsets]", + safe_area: 11-0, + /// https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc + home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]", + home_indicator_hidden: 11-0, + /// https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc + defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]", + defer_system_gestures: 11-0, + /// https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc + maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]", + maximum_frames_per_second: 10-3, + /// https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc + #[allow(unused)] // error message unused + force_touch_err_msg: "-[UITouch force]", + force_touch: 9-0, +} + +impl NSOperatingSystemVersion { + fn meets_requirements(&self, required_major: NSInteger, required_minor: NSInteger) -> bool { + (self.major, self.minor) >= (required_major, required_minor) + } +} + +pub fn os_capabilities() -> OSCapabilities { + lazy_static! { + static ref OS_CAPABILITIES: OSCapabilities = { + let version: NSOperatingSystemVersion = unsafe { + let process_info: id = msg_send![class!(NSProcessInfo), processInfo]; + let atleast_ios_8: BOOL = msg_send![ + process_info, + respondsToSelector: sel!(operatingSystemVersion) + ]; + // winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions. + // Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support + // debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS + // simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7 + // has been tested to not even run on macOS 10.15 - Xcode 8 might? + // + // The minimum required iOS version is likely to grow in the future. + assert!( + atleast_ios_8 == YES, + "`winit` requires iOS version 8 or greater" + ); + msg_send![process_info, operatingSystemVersion] + }; + version.into() + }; + } + OS_CAPABILITIES.clone() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/event_loop.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/event_loop.rs new file mode 100644 index 0000000..61b389d --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/event_loop.rs @@ -0,0 +1,338 @@ +use std::{ + collections::VecDeque, + ffi::c_void, + fmt::{self, Debug}, + marker::PhantomData, + mem, ptr, + sync::mpsc::{self, Receiver, Sender}, +}; + +use crate::{ + dpi::LogicalSize, + event::Event, + event_loop::{ + ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootEventLoopWindowTarget, + }, + platform::ios::Idiom, +}; + +use crate::platform_impl::platform::{ + app_state, + ffi::{ + id, kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, + kCFRunLoopDefaultMode, kCFRunLoopEntry, kCFRunLoopExit, nil, CFIndex, CFRelease, + CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain, + CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, + CFRunLoopSourceCreate, CFRunLoopSourceInvalidate, CFRunLoopSourceRef, + CFRunLoopSourceSignal, CFRunLoopWakeUp, NSString, UIApplicationMain, UIUserInterfaceIdiom, + }, + monitor, view, MonitorHandle, +}; + +#[derive(Debug)] +pub enum EventWrapper { + StaticEvent(Event<'static, Never>), + EventProxy(EventProxy), +} + +#[derive(Debug, PartialEq)] +pub enum EventProxy { + DpiChangedProxy { + window_id: id, + suggested_size: LogicalSize, + scale_factor: f64, + }, +} + +pub struct EventLoopWindowTarget { + receiver: Receiver, + sender_to_clone: Sender, +} + +pub struct EventLoop { + window_target: RootEventLoopWindowTarget, +} + +impl EventLoop { + pub fn new() -> EventLoop { + static mut SINGLETON_INIT: bool = false; + unsafe { + assert_main_thread!("`EventLoop` can only be created on the main thread on iOS"); + assert!( + !SINGLETON_INIT, + "Only one `EventLoop` is supported on iOS. \ + `EventLoopProxy` might be helpful" + ); + SINGLETON_INIT = true; + view::create_delegate_class(); + } + + let (sender_to_clone, receiver) = mpsc::channel(); + + // this line sets up the main run loop before `UIApplicationMain` + setup_control_flow_observers(); + + EventLoop { + window_target: RootEventLoopWindowTarget { + p: EventLoopWindowTarget { + receiver, + sender_to_clone, + }, + _marker: PhantomData, + }, + } + } + + pub fn run(self, event_handler: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget, &mut ControlFlow), + { + unsafe { + let application: *mut c_void = msg_send![class!(UIApplication), sharedApplication]; + assert_eq!( + application, + ptr::null_mut(), + "\ + `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\ + Note: `EventLoop::run` calls `UIApplicationMain` on iOS" + ); + app_state::will_launch(Box::new(EventLoopHandler { + f: event_handler, + event_loop: self.window_target, + })); + + UIApplicationMain( + 0, + ptr::null(), + nil, + NSString::alloc(nil).init_str("AppDelegate"), + ); + unreachable!() + } + } + + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy::new(self.window_target.p.sender_to_clone.clone()) + } + + pub fn available_monitors(&self) -> VecDeque { + // guaranteed to be on main thread + unsafe { monitor::uiscreens() } + } + + pub fn primary_monitor(&self) -> MonitorHandle { + // guaranteed to be on main thread + unsafe { monitor::main_uiscreen() } + } + + pub fn window_target(&self) -> &RootEventLoopWindowTarget { + &self.window_target + } +} + +// EventLoopExtIOS +impl EventLoop { + pub fn idiom(&self) -> Idiom { + // guaranteed to be on main thread + unsafe { self::get_idiom() } + } +} + +pub struct EventLoopProxy { + sender: Sender, + source: CFRunLoopSourceRef, +} + +unsafe impl Send for EventLoopProxy {} + +impl Clone for EventLoopProxy { + fn clone(&self) -> EventLoopProxy { + EventLoopProxy::new(self.sender.clone()) + } +} + +impl Drop for EventLoopProxy { + fn drop(&mut self) { + unsafe { + CFRunLoopSourceInvalidate(self.source); + CFRelease(self.source as _); + } + } +} + +impl EventLoopProxy { + fn new(sender: Sender) -> EventLoopProxy { + unsafe { + // just wake up the eventloop + extern "C" fn event_loop_proxy_handler(_: *mut c_void) {} + + // adding a Source to the main CFRunLoop lets us wake it up and + // process user events through the normal OS EventLoop mechanisms. + let rl = CFRunLoopGetMain(); + // we want all the members of context to be zero/null, except one + let mut context: CFRunLoopSourceContext = mem::zeroed(); + context.perform = Some(event_loop_proxy_handler); + let source = + CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::max_value() - 1, &mut context); + CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopWakeUp(rl); + + EventLoopProxy { sender, source } + } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.sender + .send(event) + .map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?; + unsafe { + // let the main thread know there's a new event + CFRunLoopSourceSignal(self.source); + let rl = CFRunLoopGetMain(); + CFRunLoopWakeUp(rl); + } + Ok(()) + } +} + +fn setup_control_flow_observers() { + unsafe { + // begin is queued with the highest priority to ensure it is processed before other observers + extern "C" fn control_flow_begin_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + unsafe { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(), + kCFRunLoopEntry => unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } + } + } + + // Core Animation registers its `CFRunLoopObserver` that performs drawing operations in + // `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end + // priority to be 0, in order to send MainEventsCleared before RedrawRequested. This value was + // chosen conservatively to guard against apple using different priorities for their redraw + // observers in different OS's or on different devices. If it so happens that it's too + // conservative, the main symptom would be non-redraw events coming in after `MainEventsCleared`. + // + // The value of `0x1e8480` was determined by inspecting stack traces and the associated + // registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4. + // + // Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4. + extern "C" fn control_flow_main_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + unsafe { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(), + kCFRunLoopExit => unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } + } + } + + // end is queued with the lowest priority to ensure it is processed after other observers + extern "C" fn control_flow_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + unsafe { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(), + kCFRunLoopExit => unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } + } + } + + let main_loop = CFRunLoopGetMain(); + + let begin_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopEntry | kCFRunLoopAfterWaiting, + 1, // repeat = true + CFIndex::min_value(), + control_flow_begin_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, begin_observer, kCFRunLoopDefaultMode); + + let main_end_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + 1, // repeat = true + 0, // see comment on `control_flow_main_end_handler` + control_flow_main_end_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, main_end_observer, kCFRunLoopDefaultMode); + + let end_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + 1, // repeat = true + CFIndex::max_value(), + control_flow_end_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode); + } +} + +#[derive(Debug)] +pub enum Never {} + +pub trait EventHandler: Debug { + fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow); + fn handle_user_events(&mut self, control_flow: &mut ControlFlow); +} + +struct EventLoopHandler { + f: F, + event_loop: RootEventLoopWindowTarget, +} + +impl Debug for EventLoopHandler { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EventLoopHandler") + .field("event_loop", &self.event_loop) + .finish() + } +} + +impl EventHandler for EventLoopHandler +where + F: 'static + FnMut(Event<'_, T>, &RootEventLoopWindowTarget, &mut ControlFlow), + T: 'static, +{ + fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow) { + (self.f)( + event.map_nonuser_event().unwrap(), + &self.event_loop, + control_flow, + ); + } + + fn handle_user_events(&mut self, control_flow: &mut ControlFlow) { + for event in self.event_loop.p.receiver.try_iter() { + (self.f)(Event::UserEvent(event), &self.event_loop, control_flow); + } + } +} + +// must be called on main thread +pub unsafe fn get_idiom() -> Idiom { + let device: id = msg_send![class!(UIDevice), currentDevice]; + let raw_idiom: UIUserInterfaceIdiom = msg_send![device, userInterfaceIdiom]; + raw_idiom.into() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/ffi.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/ffi.rs new file mode 100644 index 0000000..1c464b0 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/ffi.rs @@ -0,0 +1,390 @@ +#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)] + +use std::{convert::TryInto, ffi::CString, ops::BitOr, os::raw::*}; + +use objc::{runtime::Object, Encode, Encoding}; + +use crate::{ + dpi::LogicalSize, + platform::ios::{Idiom, ScreenEdge, ValidOrientations}, +}; + +pub type id = *mut Object; +pub const nil: id = 0 as id; + +#[cfg(target_pointer_width = "32")] +pub type CGFloat = f32; +#[cfg(target_pointer_width = "64")] +pub type CGFloat = f64; + +pub type NSInteger = isize; +pub type NSUInteger = usize; + +#[repr(C)] +#[derive(Clone, Debug)] +pub struct NSOperatingSystemVersion { + pub major: NSInteger, + pub minor: NSInteger, + pub patch: NSInteger, +} + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CGPoint { + pub x: CGFloat, + pub y: CGFloat, +} + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CGSize { + pub width: CGFloat, + pub height: CGFloat, +} + +impl CGSize { + pub fn new(size: LogicalSize) -> CGSize { + CGSize { + width: size.width as _, + height: size.height as _, + } + } +} + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct CGRect { + pub origin: CGPoint, + pub size: CGSize, +} + +impl CGRect { + pub fn new(origin: CGPoint, size: CGSize) -> CGRect { + CGRect { origin, size } + } +} + +unsafe impl Encode for CGRect { + fn encode() -> Encoding { + unsafe { + if cfg!(target_pointer_width = "32") { + Encoding::from_str("{CGRect={CGPoint=ff}{CGSize=ff}}") + } else if cfg!(target_pointer_width = "64") { + Encoding::from_str("{CGRect={CGPoint=dd}{CGSize=dd}}") + } else { + unimplemented!() + } + } + } +} +#[derive(Debug)] +#[allow(dead_code)] +#[repr(isize)] +pub enum UITouchPhase { + Began = 0, + Moved, + Stationary, + Ended, + Cancelled, +} + +#[derive(Debug, PartialEq)] +#[allow(dead_code)] +#[repr(isize)] +pub enum UIForceTouchCapability { + Unknown = 0, + Unavailable, + Available, +} + +#[derive(Debug, PartialEq)] +#[allow(dead_code)] +#[repr(isize)] +pub enum UITouchType { + Direct = 0, + Indirect, + Pencil, +} + +#[repr(C)] +#[derive(Debug, Clone)] +pub struct UIEdgeInsets { + pub top: CGFloat, + pub left: CGFloat, + pub bottom: CGFloat, + pub right: CGFloat, +} + +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UIUserInterfaceIdiom(NSInteger); + +unsafe impl Encode for UIUserInterfaceIdiom { + fn encode() -> Encoding { + NSInteger::encode() + } +} + +impl UIUserInterfaceIdiom { + pub const Unspecified: UIUserInterfaceIdiom = UIUserInterfaceIdiom(-1); + pub const Phone: UIUserInterfaceIdiom = UIUserInterfaceIdiom(0); + pub const Pad: UIUserInterfaceIdiom = UIUserInterfaceIdiom(1); + pub const TV: UIUserInterfaceIdiom = UIUserInterfaceIdiom(2); + pub const CarPlay: UIUserInterfaceIdiom = UIUserInterfaceIdiom(3); +} + +impl From for UIUserInterfaceIdiom { + fn from(idiom: Idiom) -> UIUserInterfaceIdiom { + match idiom { + Idiom::Unspecified => UIUserInterfaceIdiom::Unspecified, + Idiom::Phone => UIUserInterfaceIdiom::Phone, + Idiom::Pad => UIUserInterfaceIdiom::Pad, + Idiom::TV => UIUserInterfaceIdiom::TV, + Idiom::CarPlay => UIUserInterfaceIdiom::CarPlay, + } + } +} + +impl Into for UIUserInterfaceIdiom { + fn into(self) -> Idiom { + match self { + UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified, + UIUserInterfaceIdiom::Phone => Idiom::Phone, + UIUserInterfaceIdiom::Pad => Idiom::Pad, + UIUserInterfaceIdiom::TV => Idiom::TV, + UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay, + _ => unreachable!(), + } + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Debug)] +pub struct UIInterfaceOrientationMask(NSUInteger); + +unsafe impl Encode for UIInterfaceOrientationMask { + fn encode() -> Encoding { + NSUInteger::encode() + } +} + +impl UIInterfaceOrientationMask { + pub const Portrait: UIInterfaceOrientationMask = UIInterfaceOrientationMask(1 << 1); + pub const PortraitUpsideDown: UIInterfaceOrientationMask = UIInterfaceOrientationMask(1 << 2); + pub const LandscapeLeft: UIInterfaceOrientationMask = UIInterfaceOrientationMask(1 << 4); + pub const LandscapeRight: UIInterfaceOrientationMask = UIInterfaceOrientationMask(1 << 3); + pub const Landscape: UIInterfaceOrientationMask = + UIInterfaceOrientationMask(Self::LandscapeLeft.0 | Self::LandscapeRight.0); + pub const AllButUpsideDown: UIInterfaceOrientationMask = + UIInterfaceOrientationMask(Self::Landscape.0 | Self::Portrait.0); + pub const All: UIInterfaceOrientationMask = + UIInterfaceOrientationMask(Self::AllButUpsideDown.0 | Self::PortraitUpsideDown.0); +} + +impl BitOr for UIInterfaceOrientationMask { + type Output = Self; + + fn bitor(self, rhs: Self) -> Self { + UIInterfaceOrientationMask(self.0 | rhs.0) + } +} + +impl UIInterfaceOrientationMask { + pub fn from_valid_orientations_idiom( + valid_orientations: ValidOrientations, + idiom: Idiom, + ) -> UIInterfaceOrientationMask { + match (valid_orientations, idiom) { + (ValidOrientations::LandscapeAndPortrait, Idiom::Phone) => { + UIInterfaceOrientationMask::AllButUpsideDown + } + (ValidOrientations::LandscapeAndPortrait, _) => UIInterfaceOrientationMask::All, + (ValidOrientations::Landscape, _) => UIInterfaceOrientationMask::Landscape, + (ValidOrientations::Portrait, Idiom::Phone) => UIInterfaceOrientationMask::Portrait, + (ValidOrientations::Portrait, _) => { + UIInterfaceOrientationMask::Portrait + | UIInterfaceOrientationMask::PortraitUpsideDown + } + } + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UIRectEdge(NSUInteger); + +unsafe impl Encode for UIRectEdge { + fn encode() -> Encoding { + NSUInteger::encode() + } +} + +impl From for UIRectEdge { + fn from(screen_edge: ScreenEdge) -> UIRectEdge { + assert_eq!( + screen_edge.bits() & !ScreenEdge::ALL.bits(), + 0, + "invalid `ScreenEdge`" + ); + UIRectEdge(screen_edge.bits().into()) + } +} + +impl Into for UIRectEdge { + fn into(self) -> ScreenEdge { + let bits: u8 = self.0.try_into().expect("invalid `UIRectEdge`"); + ScreenEdge::from_bits(bits).expect("invalid `ScreenEdge`") + } +} + +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UIScreenOverscanCompensation(NSInteger); + +unsafe impl Encode for UIScreenOverscanCompensation { + fn encode() -> Encoding { + NSInteger::encode() + } +} + +#[allow(dead_code)] +impl UIScreenOverscanCompensation { + pub const Scale: UIScreenOverscanCompensation = UIScreenOverscanCompensation(0); + pub const InsetBounds: UIScreenOverscanCompensation = UIScreenOverscanCompensation(1); + pub const None: UIScreenOverscanCompensation = UIScreenOverscanCompensation(2); +} + +#[link(name = "UIKit", kind = "framework")] +#[link(name = "CoreFoundation", kind = "framework")] +extern "C" { + pub static kCFRunLoopDefaultMode: CFRunLoopMode; + pub static kCFRunLoopCommonModes: CFRunLoopMode; + + pub fn UIApplicationMain( + argc: c_int, + argv: *const c_char, + principalClassName: id, + delegateClassName: id, + ) -> c_int; + + pub fn CFRunLoopGetMain() -> CFRunLoopRef; + pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); + + pub fn CFRunLoopObserverCreate( + allocator: CFAllocatorRef, + activities: CFOptionFlags, + repeats: Boolean, + order: CFIndex, + callout: CFRunLoopObserverCallBack, + context: *mut CFRunLoopObserverContext, + ) -> CFRunLoopObserverRef; + pub fn CFRunLoopAddObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFRunLoopMode, + ); + + pub fn CFRunLoopTimerCreate( + allocator: CFAllocatorRef, + fireDate: CFAbsoluteTime, + interval: CFTimeInterval, + flags: CFOptionFlags, + order: CFIndex, + callout: CFRunLoopTimerCallBack, + context: *mut CFRunLoopTimerContext, + ) -> CFRunLoopTimerRef; + pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFRunLoopMode); + pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); + pub fn CFRunLoopTimerInvalidate(time: CFRunLoopTimerRef); + + pub fn CFRunLoopSourceCreate( + allocator: CFAllocatorRef, + order: CFIndex, + context: *mut CFRunLoopSourceContext, + ) -> CFRunLoopSourceRef; + pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFRunLoopMode); + pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); + pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); + + pub fn CFAbsoluteTimeGetCurrent() -> CFAbsoluteTime; + pub fn CFRelease(cftype: *const c_void); +} + +pub type Boolean = u8; +pub enum CFAllocator {} +pub type CFAllocatorRef = *mut CFAllocator; +pub enum CFRunLoop {} +pub type CFRunLoopRef = *mut CFRunLoop; +pub type CFRunLoopMode = CFStringRef; +pub enum CFRunLoopObserver {} +pub type CFRunLoopObserverRef = *mut CFRunLoopObserver; +pub enum CFRunLoopTimer {} +pub type CFRunLoopTimerRef = *mut CFRunLoopTimer; +pub enum CFRunLoopSource {} +pub type CFRunLoopSourceRef = *mut CFRunLoopSource; +pub enum CFString {} +pub type CFStringRef = *const CFString; + +pub type CFHashCode = c_ulong; +pub type CFIndex = c_long; +pub type CFOptionFlags = c_ulong; +pub type CFRunLoopActivity = CFOptionFlags; + +pub type CFAbsoluteTime = CFTimeInterval; +pub type CFTimeInterval = f64; + +pub const kCFRunLoopEntry: CFRunLoopActivity = 0; +pub const kCFRunLoopBeforeWaiting: CFRunLoopActivity = 1 << 5; +pub const kCFRunLoopAfterWaiting: CFRunLoopActivity = 1 << 6; +pub const kCFRunLoopExit: CFRunLoopActivity = 1 << 7; + +pub type CFRunLoopObserverCallBack = + extern "C" fn(observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); +pub type CFRunLoopTimerCallBack = extern "C" fn(timer: CFRunLoopTimerRef, info: *mut c_void); + +pub enum CFRunLoopObserverContext {} +pub enum CFRunLoopTimerContext {} + +#[repr(C)] +pub struct CFRunLoopSourceContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option Boolean>, + pub hash: Option CFHashCode>, + pub schedule: Option, + pub cancel: Option, + pub perform: Option, +} + +pub trait NSString: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSString), alloc] + } + + unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id; + unsafe fn stringByAppendingString_(self, other: id) -> id; + unsafe fn init_str(self, string: &str) -> Self; + unsafe fn UTF8String(self) -> *const c_char; +} + +impl NSString for id { + unsafe fn initWithUTF8String_(self, c_string: *const c_char) -> id { + msg_send![self, initWithUTF8String: c_string as id] + } + + unsafe fn stringByAppendingString_(self, other: id) -> id { + msg_send![self, stringByAppendingString: other] + } + + unsafe fn init_str(self, string: &str) -> id { + let cstring = CString::new(string).unwrap(); + self.initWithUTF8String_(cstring.as_ptr()) + } + + unsafe fn UTF8String(self) -> *const c_char { + msg_send![self, UTF8String] + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/mod.rs new file mode 100644 index 0000000..da7b018 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/mod.rs @@ -0,0 +1,113 @@ +//! iOS support +//! +//! # Building app +//! To build ios app you will need rustc built for this targets: +//! +//! - armv7-apple-ios +//! - armv7s-apple-ios +//! - i386-apple-ios +//! - aarch64-apple-ios +//! - x86_64-apple-ios +//! +//! Then +//! +//! ``` +//! cargo build --target=... +//! ``` +//! The simplest way to integrate your app into xcode environment is to build it +//! as a static library. Wrap your main function and export it. +//! +//! ```rust, ignore +//! #[no_mangle] +//! pub extern fn start_winit_app() { +//! start_inner() +//! } +//! +//! fn start_inner() { +//! ... +//! } +//! ``` +//! +//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode. +//! +//! ```ignore +//! void start_winit_app(); +//! ``` +//! +//! Use start_winit_app inside your xcode's main function. +//! +//! +//! # App lifecycle and events +//! +//! iOS environment is very different from other platforms and you must be very +//! careful with it's events. Familiarize yourself with +//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/). +//! +//! +//! This is how those event are represented in winit: +//! +//! - applicationDidBecomeActive is Resumed +//! - applicationWillResignActive is Suspended +//! - applicationWillTerminate is LoopDestroyed +//! +//! Keep in mind that after LoopDestroyed event is received every attempt to draw with +//! opengl will result in segfault. +//! +//! Also note that app may not receive the LoopDestroyed event if suspended; it might be SIGKILL'ed. + +#![cfg(target_os = "ios")] + +// TODO: (mtak-) UIKit requires main thread for virtually all function/method calls. This could be +// worked around in the future by using GCD (grand central dispatch) and/or caching of values like +// window size/position. +macro_rules! assert_main_thread { + ($($t:tt)*) => { + if !msg_send![class!(NSThread), isMainThread] { + panic!($($t)*); + } + }; +} + +mod app_state; +mod event_loop; +mod ffi; +mod monitor; +mod view; +mod window; + +use std::fmt; + +pub use self::{ + event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget}, + monitor::{MonitorHandle, VideoMode}, + window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId}, +}; + +pub(crate) use crate::icon::NoIcon as PlatformIcon; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId { + uiscreen: ffi::id, +} + +impl DeviceId { + pub unsafe fn dummy() -> Self { + DeviceId { + uiscreen: std::ptr::null_mut(), + } + } +} + +unsafe impl Send for DeviceId {} +unsafe impl Sync for DeviceId {} + +#[derive(Debug)] +pub enum OsError {} + +impl fmt::Display for OsError { + fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + _ => unreachable!(), + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/monitor.rs new file mode 100644 index 0000000..42c71ff --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/monitor.rs @@ -0,0 +1,299 @@ +use std::{ + collections::{BTreeSet, VecDeque}, + fmt, + ops::{Deref, DerefMut}, +}; + +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform_impl::platform::{ + app_state, + ffi::{id, nil, CGFloat, CGRect, CGSize, NSInteger, NSUInteger}, + }, +}; + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct VideoMode { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate: u16, + pub(crate) screen_mode: NativeDisplayMode, + pub(crate) monitor: MonitorHandle, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +pub struct NativeDisplayMode(pub id); + +unsafe impl Send for NativeDisplayMode {} + +impl Drop for NativeDisplayMode { + fn drop(&mut self) { + unsafe { + let () = msg_send![self.0, release]; + } + } +} + +impl Clone for NativeDisplayMode { + fn clone(&self) -> Self { + unsafe { + let _: id = msg_send![self.0, retain]; + } + NativeDisplayMode(self.0) + } +} + +impl Clone for VideoMode { + fn clone(&self) -> VideoMode { + VideoMode { + size: self.size, + bit_depth: self.bit_depth, + refresh_rate: self.refresh_rate, + screen_mode: self.screen_mode.clone(), + monitor: self.monitor.clone(), + } + } +} + +impl VideoMode { + unsafe fn retained_new(uiscreen: id, screen_mode: id) -> VideoMode { + assert_main_thread!("`VideoMode` can only be created on the main thread on iOS"); + let os_capabilities = app_state::os_capabilities(); + let refresh_rate: NSInteger = if os_capabilities.maximum_frames_per_second { + msg_send![uiscreen, maximumFramesPerSecond] + } else { + // https://developer.apple.com/library/archive/technotes/tn2460/_index.html + // https://en.wikipedia.org/wiki/IPad_Pro#Model_comparison + // + // All iOS devices support 60 fps, and on devices where `maximumFramesPerSecond` is not + // supported, they are all guaranteed to have 60hz refresh rates. This does not + // correctly handle external displays. ProMotion displays support 120fps, but they were + // introduced at the same time as the `maximumFramesPerSecond` API. + // + // FIXME: earlier OSs could calculate the refresh rate using + // `-[CADisplayLink duration]`. + os_capabilities.maximum_frames_per_second_err_msg("defaulting to 60 fps"); + 60 + }; + let size: CGSize = msg_send![screen_mode, size]; + let screen_mode: id = msg_send![screen_mode, retain]; + let screen_mode = NativeDisplayMode(screen_mode); + VideoMode { + size: (size.width as u32, size.height as u32), + bit_depth: 32, + refresh_rate: refresh_rate as u16, + screen_mode, + monitor: MonitorHandle::retained_new(uiscreen), + } + } + + pub fn size(&self) -> PhysicalSize { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate(&self) -> u16 { + self.refresh_rate + } + + pub fn monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: self.monitor.clone(), + } + } +} + +#[derive(PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Inner { + uiscreen: id, +} + +impl Drop for Inner { + fn drop(&mut self) { + unsafe { + let () = msg_send![self.uiscreen, release]; + } + } +} + +#[derive(PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct MonitorHandle { + inner: Inner, +} + +impl Deref for MonitorHandle { + type Target = Inner; + + fn deref(&self) -> &Inner { + unsafe { + assert_main_thread!( + "`MonitorHandle` methods can only be run on the main thread on iOS" + ); + } + &self.inner + } +} + +impl DerefMut for MonitorHandle { + fn deref_mut(&mut self) -> &mut Inner { + unsafe { + assert_main_thread!( + "`MonitorHandle` methods can only be run on the main thread on iOS" + ); + } + &mut self.inner + } +} + +unsafe impl Send for MonitorHandle {} +unsafe impl Sync for MonitorHandle {} + +impl Clone for MonitorHandle { + fn clone(&self) -> MonitorHandle { + MonitorHandle::retained_new(self.uiscreen) + } +} + +impl Drop for MonitorHandle { + fn drop(&mut self) { + unsafe { + assert_main_thread!("`MonitorHandle` can only be dropped on the main thread on iOS"); + } + } +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + #[derive(Debug)] + struct MonitorHandle { + name: Option, + size: PhysicalSize, + position: PhysicalPosition, + scale_factor: f64, + } + + let monitor_id_proxy = MonitorHandle { + name: self.name(), + size: self.size(), + position: self.position(), + scale_factor: self.scale_factor(), + }; + + monitor_id_proxy.fmt(f) + } +} + +impl MonitorHandle { + pub fn retained_new(uiscreen: id) -> MonitorHandle { + unsafe { + assert_main_thread!("`MonitorHandle` can only be cloned on the main thread on iOS"); + let () = msg_send![uiscreen, retain]; + } + MonitorHandle { + inner: Inner { uiscreen }, + } + } +} + +impl Inner { + pub fn name(&self) -> Option { + unsafe { + let main = main_uiscreen(); + if self.uiscreen == main.uiscreen { + Some("Primary".to_string()) + } else if self.uiscreen == mirrored_uiscreen(&main).uiscreen { + Some("Mirrored".to_string()) + } else { + uiscreens() + .iter() + .position(|rhs| rhs.uiscreen == self.uiscreen) + .map(|idx| idx.to_string()) + } + } + } + + pub fn size(&self) -> PhysicalSize { + unsafe { + let bounds: CGRect = msg_send![self.ui_screen(), nativeBounds]; + PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32) + } + } + + pub fn position(&self) -> PhysicalPosition { + unsafe { + let bounds: CGRect = msg_send![self.ui_screen(), nativeBounds]; + (bounds.origin.x as f64, bounds.origin.y as f64).into() + } + } + + pub fn scale_factor(&self) -> f64 { + unsafe { + let scale: CGFloat = msg_send![self.ui_screen(), nativeScale]; + scale as f64 + } + } + + pub fn video_modes(&self) -> impl Iterator { + let mut modes = BTreeSet::new(); + unsafe { + let available_modes: id = msg_send![self.uiscreen, availableModes]; + let available_mode_count: NSUInteger = msg_send![available_modes, count]; + + for i in 0..available_mode_count { + let mode: id = msg_send![available_modes, objectAtIndex: i]; + modes.insert(RootVideoMode { + video_mode: VideoMode::retained_new(self.uiscreen, mode), + }); + } + } + + modes.into_iter() + } +} + +// MonitorHandleExtIOS +impl Inner { + pub fn ui_screen(&self) -> id { + self.uiscreen + } + + pub fn preferred_video_mode(&self) -> RootVideoMode { + unsafe { + let mode: id = msg_send![self.uiscreen, preferredMode]; + RootVideoMode { + video_mode: VideoMode::retained_new(self.uiscreen, mode), + } + } + } +} + +// requires being run on main thread +pub unsafe fn main_uiscreen() -> MonitorHandle { + let uiscreen: id = msg_send![class!(UIScreen), mainScreen]; + MonitorHandle::retained_new(uiscreen) +} + +// requires being run on main thread +unsafe fn mirrored_uiscreen(monitor: &MonitorHandle) -> MonitorHandle { + let uiscreen: id = msg_send![monitor.uiscreen, mirroredScreen]; + MonitorHandle::retained_new(uiscreen) +} + +// requires being run on main thread +pub unsafe fn uiscreens() -> VecDeque { + let screens: id = msg_send![class!(UIScreen), screens]; + let count: NSUInteger = msg_send![screens, count]; + let mut result = VecDeque::with_capacity(count as _); + let screens_enum: id = msg_send![screens, objectEnumerator]; + loop { + let screen: id = msg_send![screens_enum, nextObject]; + if screen == nil { + break result; + } + result.push_back(MonitorHandle::retained_new(screen)); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/view.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/view.rs new file mode 100644 index 0000000..77f3fc5 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/view.rs @@ -0,0 +1,599 @@ +use std::collections::HashMap; + +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Sel, BOOL, NO, YES}, +}; + +use crate::{ + event::{DeviceId as RootDeviceId, Event, Force, Touch, TouchPhase, WindowEvent}, + platform::ios::MonitorHandleExtIOS, + platform_impl::platform::{ + app_state::{self, OSCapabilities}, + event_loop::{self, EventProxy, EventWrapper}, + ffi::{ + id, nil, CGFloat, CGPoint, CGRect, UIForceTouchCapability, UIInterfaceOrientationMask, + UIRectEdge, UITouchPhase, UITouchType, + }, + window::PlatformSpecificWindowBuilderAttributes, + DeviceId, + }, + window::{Fullscreen, WindowAttributes, WindowId as RootWindowId}, +}; + +macro_rules! add_property { + ( + $decl:ident, + $name:ident: $t:ty, + $setter_name:ident: |$object:ident| $after_set:expr, + $getter_name:ident, + ) => { + add_property!( + $decl, + $name: $t, + $setter_name: true, |_, _|{}; |$object| $after_set, + $getter_name, + ) + }; + ( + $decl:ident, + $name:ident: $t:ty, + $setter_name:ident: $capability:expr, $err:expr; |$object:ident| $after_set:expr, + $getter_name:ident, + ) => { + { + const VAR_NAME: &'static str = concat!("_", stringify!($name)); + $decl.add_ivar::<$t>(VAR_NAME); + let setter = if $capability { + #[allow(non_snake_case)] + extern "C" fn $setter_name($object: &mut Object, _: Sel, value: $t) { + unsafe { + $object.set_ivar::<$t>(VAR_NAME, value); + } + $after_set + } + $setter_name + } else { + #[allow(non_snake_case)] + extern "C" fn $setter_name($object: &mut Object, _: Sel, value: $t) { + unsafe { + $object.set_ivar::<$t>(VAR_NAME, value); + } + $err(&app_state::os_capabilities(), "ignoring") + } + $setter_name + }; + #[allow(non_snake_case)] + extern "C" fn $getter_name($object: &Object, _: Sel) -> $t { + unsafe { *$object.get_ivar::<$t>(VAR_NAME) } + } + $decl.add_method( + sel!($setter_name:), + setter as extern "C" fn(&mut Object, Sel, $t), + ); + $decl.add_method( + sel!($getter_name), + $getter_name as extern "C" fn(&Object, Sel) -> $t, + ); + } + }; +} + +// requires main thread +unsafe fn get_view_class(root_view_class: &'static Class) -> &'static Class { + static mut CLASSES: Option> = None; + static mut ID: usize = 0; + + if CLASSES.is_none() { + CLASSES = Some(HashMap::default()); + } + + let classes = CLASSES.as_mut().unwrap(); + + classes.entry(root_view_class).or_insert_with(move || { + let uiview_class = class!(UIView); + let is_uiview: BOOL = msg_send![root_view_class, isSubclassOfClass: uiview_class]; + assert_eq!( + is_uiview, YES, + "`root_view_class` must inherit from `UIView`" + ); + + extern "C" fn draw_rect(object: &Object, _: Sel, rect: CGRect) { + unsafe { + let window: id = msg_send![object, window]; + assert!(!window.is_null()); + app_state::handle_nonuser_events( + std::iter::once(EventWrapper::StaticEvent(Event::RedrawRequested( + RootWindowId(window.into()), + ))) + .chain(std::iter::once(EventWrapper::StaticEvent( + Event::RedrawEventsCleared, + ))), + ); + let superclass: &'static Class = msg_send![object, superclass]; + let () = msg_send![super(object, superclass), drawRect: rect]; + } + } + + extern "C" fn layout_subviews(object: &Object, _: Sel) { + unsafe { + let superclass: &'static Class = msg_send![object, superclass]; + let () = msg_send![super(object, superclass), layoutSubviews]; + + let window: id = msg_send![object, window]; + assert!(!window.is_null()); + let bounds: CGRect = msg_send![window, bounds]; + let screen: id = msg_send![window, screen]; + let screen_space: id = msg_send![screen, coordinateSpace]; + let screen_frame: CGRect = + msg_send![object, convertRect:bounds toCoordinateSpace:screen_space]; + let scale_factor: CGFloat = msg_send![screen, scale]; + let size = crate::dpi::LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + } + .to_physical(scale_factor.into()); + app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.into()), + event: WindowEvent::Resized(size), + })); + } + } + + extern "C" fn set_content_scale_factor( + object: &mut Object, + _: Sel, + untrusted_scale_factor: CGFloat, + ) { + unsafe { + let superclass: &'static Class = msg_send![object, superclass]; + let () = msg_send![ + super(object, superclass), + setContentScaleFactor: untrusted_scale_factor + ]; + + let window: id = msg_send![object, window]; + // `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow + // makeKeyAndVisible]` at window creation time (either manually or internally by + // UIKit when the `UIView` is first created), in which case we send no events here + if window.is_null() { + return; + } + // `setContentScaleFactor` may be called with a value of 0, which means "reset the + // content scale factor to a device-specific default value", so we can't use the + // parameter here. We can query the actual factor using the getter + let scale_factor: CGFloat = msg_send![object, contentScaleFactor]; + assert!( + !scale_factor.is_nan() + && scale_factor.is_finite() + && scale_factor.is_sign_positive() + && scale_factor > 0.0, + "invalid scale_factor set on UIView", + ); + let scale_factor: f64 = scale_factor.into(); + let bounds: CGRect = msg_send![object, bounds]; + let screen: id = msg_send![window, screen]; + let screen_space: id = msg_send![screen, coordinateSpace]; + let screen_frame: CGRect = + msg_send![object, convertRect:bounds toCoordinateSpace:screen_space]; + let size = crate::dpi::LogicalSize { + width: screen_frame.size.width as _, + height: screen_frame.size.height as _, + }; + app_state::handle_nonuser_events( + std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy { + window_id: window, + scale_factor, + suggested_size: size, + })) + .chain(std::iter::once(EventWrapper::StaticEvent( + Event::WindowEvent { + window_id: RootWindowId(window.into()), + event: WindowEvent::Resized(size.to_physical(scale_factor)), + }, + ))), + ); + } + } + + extern "C" fn handle_touches(object: &Object, _: Sel, touches: id, _: id) { + unsafe { + let window: id = msg_send![object, window]; + assert!(!window.is_null()); + let uiscreen: id = msg_send![window, screen]; + let touches_enum: id = msg_send![touches, objectEnumerator]; + let mut touch_events = Vec::new(); + let os_supports_force = app_state::os_capabilities().force_touch; + loop { + let touch: id = msg_send![touches_enum, nextObject]; + if touch == nil { + break; + } + let location: CGPoint = msg_send![touch, locationInView: nil]; + let touch_type: UITouchType = msg_send![touch, type]; + let force = if os_supports_force { + let trait_collection: id = msg_send![object, traitCollection]; + let touch_capability: UIForceTouchCapability = + msg_send![trait_collection, forceTouchCapability]; + // Both the OS _and_ the device need to be checked for force touch support. + if touch_capability == UIForceTouchCapability::Available { + let force: CGFloat = msg_send![touch, force]; + let max_possible_force: CGFloat = + msg_send![touch, maximumPossibleForce]; + let altitude_angle: Option = if touch_type == UITouchType::Pencil { + let angle: CGFloat = msg_send![touch, altitudeAngle]; + Some(angle as _) + } else { + None + }; + Some(Force::Calibrated { + force: force as _, + max_possible_force: max_possible_force as _, + altitude_angle, + }) + } else { + None + } + } else { + None + }; + let touch_id = touch as u64; + let phase: UITouchPhase = msg_send![touch, phase]; + let phase = match phase { + UITouchPhase::Began => TouchPhase::Started, + UITouchPhase::Moved => TouchPhase::Moved, + // 2 is UITouchPhase::Stationary and is not expected here + UITouchPhase::Ended => TouchPhase::Ended, + UITouchPhase::Cancelled => TouchPhase::Cancelled, + _ => panic!("unexpected touch phase: {:?}", phase as i32), + }; + + touch_events.push(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.into()), + event: WindowEvent::Touch(Touch { + device_id: RootDeviceId(DeviceId { uiscreen }), + id: touch_id, + location: (location.x as f64, location.y as f64).into(), + force, + phase, + }), + })); + } + app_state::handle_nonuser_events(touch_events); + } + } + + let mut decl = ClassDecl::new(&format!("WinitUIView{}", ID), root_view_class) + .expect("Failed to declare class `WinitUIView`"); + ID += 1; + decl.add_method( + sel!(drawRect:), + draw_rect as extern "C" fn(&Object, Sel, CGRect), + ); + decl.add_method( + sel!(layoutSubviews), + layout_subviews as extern "C" fn(&Object, Sel), + ); + decl.add_method( + sel!(setContentScaleFactor:), + set_content_scale_factor as extern "C" fn(&mut Object, Sel, CGFloat), + ); + + decl.add_method( + sel!(touchesBegan:withEvent:), + handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), + ); + decl.add_method( + sel!(touchesMoved:withEvent:), + handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), + ); + decl.add_method( + sel!(touchesEnded:withEvent:), + handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), + ); + decl.add_method( + sel!(touchesCancelled:withEvent:), + handle_touches as extern "C" fn(this: &Object, _: Sel, _: id, _: id), + ); + + decl.register() + }) +} + +// requires main thread +unsafe fn get_view_controller_class() -> &'static Class { + static mut CLASS: Option<&'static Class> = None; + if CLASS.is_none() { + let os_capabilities = app_state::os_capabilities(); + + let uiviewcontroller_class = class!(UIViewController); + + extern "C" fn should_autorotate(_: &Object, _: Sel) -> BOOL { + YES + } + + let mut decl = ClassDecl::new("WinitUIViewController", uiviewcontroller_class) + .expect("Failed to declare class `WinitUIViewController`"); + decl.add_method( + sel!(shouldAutorotate), + should_autorotate as extern "C" fn(&Object, Sel) -> BOOL, + ); + add_property! { + decl, + prefers_status_bar_hidden: BOOL, + setPrefersStatusBarHidden: |object| { + unsafe { + let () = msg_send![object, setNeedsStatusBarAppearanceUpdate]; + } + }, + prefersStatusBarHidden, + } + add_property! { + decl, + prefers_home_indicator_auto_hidden: BOOL, + setPrefersHomeIndicatorAutoHidden: + os_capabilities.home_indicator_hidden, + OSCapabilities::home_indicator_hidden_err_msg; + |object| { + unsafe { + let () = msg_send![object, setNeedsUpdateOfHomeIndicatorAutoHidden]; + } + }, + prefersHomeIndicatorAutoHidden, + } + add_property! { + decl, + supported_orientations: UIInterfaceOrientationMask, + setSupportedInterfaceOrientations: |object| { + unsafe { + let () = msg_send![class!(UIViewController), attemptRotationToDeviceOrientation]; + } + }, + supportedInterfaceOrientations, + } + add_property! { + decl, + preferred_screen_edges_deferring_system_gestures: UIRectEdge, + setPreferredScreenEdgesDeferringSystemGestures: + os_capabilities.defer_system_gestures, + OSCapabilities::defer_system_gestures_err_msg; + |object| { + unsafe { + let () = msg_send![object, setNeedsUpdateOfScreenEdgesDeferringSystemGestures]; + } + }, + preferredScreenEdgesDeferringSystemGestures, + } + CLASS = Some(decl.register()); + } + CLASS.unwrap() +} + +// requires main thread +unsafe fn get_window_class() -> &'static Class { + static mut CLASS: Option<&'static Class> = None; + if CLASS.is_none() { + let uiwindow_class = class!(UIWindow); + + extern "C" fn become_key_window(object: &Object, _: Sel) { + unsafe { + app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(object.into()), + event: WindowEvent::Focused(true), + })); + let () = msg_send![super(object, class!(UIWindow)), becomeKeyWindow]; + } + } + + extern "C" fn resign_key_window(object: &Object, _: Sel) { + unsafe { + app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(object.into()), + event: WindowEvent::Focused(false), + })); + let () = msg_send![super(object, class!(UIWindow)), resignKeyWindow]; + } + } + + let mut decl = ClassDecl::new("WinitUIWindow", uiwindow_class) + .expect("Failed to declare class `WinitUIWindow`"); + decl.add_method( + sel!(becomeKeyWindow), + become_key_window as extern "C" fn(&Object, Sel), + ); + decl.add_method( + sel!(resignKeyWindow), + resign_key_window as extern "C" fn(&Object, Sel), + ); + + CLASS = Some(decl.register()); + } + CLASS.unwrap() +} + +// requires main thread +pub unsafe fn create_view( + _window_attributes: &WindowAttributes, + platform_attributes: &PlatformSpecificWindowBuilderAttributes, + frame: CGRect, +) -> id { + let class = get_view_class(platform_attributes.root_view_class); + + let view: id = msg_send![class, alloc]; + assert!(!view.is_null(), "Failed to create `UIView` instance"); + let view: id = msg_send![view, initWithFrame: frame]; + assert!(!view.is_null(), "Failed to initialize `UIView` instance"); + let () = msg_send![view, setMultipleTouchEnabled: YES]; + if let Some(scale_factor) = platform_attributes.scale_factor { + let () = msg_send![view, setContentScaleFactor: scale_factor as CGFloat]; + } + + view +} + +// requires main thread +pub unsafe fn create_view_controller( + _window_attributes: &WindowAttributes, + platform_attributes: &PlatformSpecificWindowBuilderAttributes, + view: id, +) -> id { + let class = get_view_controller_class(); + + let view_controller: id = msg_send![class, alloc]; + assert!( + !view_controller.is_null(), + "Failed to create `UIViewController` instance" + ); + let view_controller: id = msg_send![view_controller, init]; + assert!( + !view_controller.is_null(), + "Failed to initialize `UIViewController` instance" + ); + let status_bar_hidden = if platform_attributes.prefers_status_bar_hidden { + YES + } else { + NO + }; + let idiom = event_loop::get_idiom(); + let supported_orientations = UIInterfaceOrientationMask::from_valid_orientations_idiom( + platform_attributes.valid_orientations, + idiom, + ); + let prefers_home_indicator_hidden = if platform_attributes.prefers_home_indicator_hidden { + YES + } else { + NO + }; + let edges: UIRectEdge = platform_attributes + .preferred_screen_edges_deferring_system_gestures + .into(); + let () = msg_send![ + view_controller, + setPrefersStatusBarHidden: status_bar_hidden + ]; + let () = msg_send![ + view_controller, + setSupportedInterfaceOrientations: supported_orientations + ]; + let () = msg_send![ + view_controller, + setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden + ]; + let () = msg_send![ + view_controller, + setPreferredScreenEdgesDeferringSystemGestures: edges + ]; + let () = msg_send![view_controller, setView: view]; + view_controller +} + +// requires main thread +pub unsafe fn create_window( + window_attributes: &WindowAttributes, + _platform_attributes: &PlatformSpecificWindowBuilderAttributes, + frame: CGRect, + view_controller: id, +) -> id { + let class = get_window_class(); + + let window: id = msg_send![class, alloc]; + assert!(!window.is_null(), "Failed to create `UIWindow` instance"); + let window: id = msg_send![window, initWithFrame: frame]; + assert!( + !window.is_null(), + "Failed to initialize `UIWindow` instance" + ); + let () = msg_send![window, setRootViewController: view_controller]; + match window_attributes.fullscreen { + Some(Fullscreen::Exclusive(ref video_mode)) => { + let uiscreen = video_mode.monitor().ui_screen() as id; + let () = msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode.0]; + msg_send![window, setScreen:video_mode.monitor().ui_screen()] + } + Some(Fullscreen::Borderless(ref monitor)) => { + msg_send![window, setScreen:monitor.ui_screen()] + } + None => (), + } + + window +} + +pub fn create_delegate_class() { + extern "C" fn did_finish_launching(_: &mut Object, _: Sel, _: id, _: id) -> BOOL { + unsafe { + app_state::did_finish_launching(); + } + YES + } + + extern "C" fn did_become_active(_: &Object, _: Sel, _: id) { + unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::Resumed)) } + } + + extern "C" fn will_resign_active(_: &Object, _: Sel, _: id) { + unsafe { app_state::handle_nonuser_event(EventWrapper::StaticEvent(Event::Suspended)) } + } + + extern "C" fn will_enter_foreground(_: &Object, _: Sel, _: id) {} + extern "C" fn did_enter_background(_: &Object, _: Sel, _: id) {} + + extern "C" fn will_terminate(_: &Object, _: Sel, _: id) { + unsafe { + let app: id = msg_send![class!(UIApplication), sharedApplication]; + let windows: id = msg_send![app, windows]; + let windows_enum: id = msg_send![windows, objectEnumerator]; + let mut events = Vec::new(); + loop { + let window: id = msg_send![windows_enum, nextObject]; + if window == nil { + break; + } + let is_winit_window: BOOL = msg_send![window, isKindOfClass: class!(WinitUIWindow)]; + if is_winit_window == YES { + events.push(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.into()), + event: WindowEvent::Destroyed, + })); + } + } + app_state::handle_nonuser_events(events); + app_state::terminated(); + } + } + + let ui_responder = class!(UIResponder); + let mut decl = + ClassDecl::new("AppDelegate", ui_responder).expect("Failed to declare class `AppDelegate`"); + + unsafe { + decl.add_method( + sel!(application:didFinishLaunchingWithOptions:), + did_finish_launching as extern "C" fn(&mut Object, Sel, id, id) -> BOOL, + ); + + decl.add_method( + sel!(applicationDidBecomeActive:), + did_become_active as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(applicationWillResignActive:), + will_resign_active as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(applicationWillEnterForeground:), + will_enter_foreground as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(applicationDidEnterBackground:), + did_enter_background as extern "C" fn(&Object, Sel, id), + ); + + decl.add_method( + sel!(applicationWillTerminate:), + will_terminate as extern "C" fn(&Object, Sel, id), + ); + + decl.register(); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/window.rs new file mode 100644 index 0000000..ec94311 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/ios/window.rs @@ -0,0 +1,638 @@ +use raw_window_handle::{ios::IOSHandle, RawWindowHandle}; +use std::{ + collections::VecDeque, + ops::{Deref, DerefMut}, +}; + +use objc::runtime::{Class, Object, BOOL, NO, YES}; + +use crate::{ + dpi::{self, LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + event::{Event, WindowEvent}, + icon::Icon, + monitor::MonitorHandle as RootMonitorHandle, + platform::ios::{MonitorHandleExtIOS, ScreenEdge, ValidOrientations}, + platform_impl::platform::{ + app_state, + event_loop::{self, EventProxy, EventWrapper}, + ffi::{ + id, CGFloat, CGPoint, CGRect, CGSize, UIEdgeInsets, UIInterfaceOrientationMask, + UIRectEdge, UIScreenOverscanCompensation, + }, + monitor, view, EventLoopWindowTarget, MonitorHandle, + }, + window::{CursorIcon, Fullscreen, WindowAttributes, WindowId as RootWindowId}, +}; + +pub struct Inner { + pub window: id, + pub view_controller: id, + pub view: id, + gl_or_metal_backed: bool, +} + +impl Drop for Inner { + fn drop(&mut self) { + unsafe { + let () = msg_send![self.view, release]; + let () = msg_send![self.view_controller, release]; + let () = msg_send![self.window, release]; + } + } +} + +impl Inner { + pub fn set_title(&self, _title: &str) { + debug!("`Window::set_title` is ignored on iOS") + } + + pub fn set_visible(&self, visible: bool) { + match visible { + true => unsafe { + let () = msg_send![self.window, setHidden: NO]; + }, + false => unsafe { + let () = msg_send![self.window, setHidden: YES]; + }, + } + } + + pub fn request_redraw(&self) { + unsafe { + if self.gl_or_metal_backed { + // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or CAMetalLayer. + // Ordinarily the OS sets up a bunch of UIKit state before calling drawRect: on a UIView, but when using + // raw or gl/metal for drawing this work is completely avoided. + // + // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been confirmed via + // testing. + // + // https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc + app_state::queue_gl_or_metal_redraw(self.window); + } else { + let () = msg_send![self.view, setNeedsDisplay]; + } + } + } + + pub fn inner_position(&self) -> Result, NotSupportedError> { + unsafe { + let safe_area = self.safe_area_screen_space(); + let position = LogicalPosition { + x: safe_area.origin.x as f64, + y: safe_area.origin.y as f64, + }; + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + } + + pub fn outer_position(&self) -> Result, NotSupportedError> { + unsafe { + let screen_frame = self.screen_frame(); + let position = LogicalPosition { + x: screen_frame.origin.x as f64, + y: screen_frame.origin.y as f64, + }; + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + } + + pub fn set_outer_position(&self, physical_position: Position) { + unsafe { + let scale_factor = self.scale_factor(); + let position = physical_position.to_logical::(scale_factor); + let screen_frame = self.screen_frame(); + let new_screen_frame = CGRect { + origin: CGPoint { + x: position.x as _, + y: position.y as _, + }, + size: screen_frame.size, + }; + let bounds = self.from_screen_space(new_screen_frame); + let () = msg_send![self.window, setBounds: bounds]; + } + } + + pub fn inner_size(&self) -> PhysicalSize { + unsafe { + let scale_factor = self.scale_factor(); + let safe_area = self.safe_area_screen_space(); + let size = LogicalSize { + width: safe_area.size.width as f64, + height: safe_area.size.height as f64, + }; + size.to_physical(scale_factor) + } + } + + pub fn outer_size(&self) -> PhysicalSize { + unsafe { + let scale_factor = self.scale_factor(); + let screen_frame = self.screen_frame(); + let size = LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + }; + size.to_physical(scale_factor) + } + } + + pub fn set_inner_size(&self, _size: Size) { + unimplemented!("not clear what `Window::set_inner_size` means on iOS"); + } + + pub fn set_min_inner_size(&self, _dimensions: Option) { + warn!("`Window::set_min_inner_size` is ignored on iOS") + } + + pub fn set_max_inner_size(&self, _dimensions: Option) { + warn!("`Window::set_max_inner_size` is ignored on iOS") + } + + pub fn set_resizable(&self, _resizable: bool) { + warn!("`Window::set_resizable` is ignored on iOS") + } + + pub fn scale_factor(&self) -> f64 { + unsafe { + let hidpi: CGFloat = msg_send![self.view, contentScaleFactor]; + hidpi as _ + } + } + + pub fn set_cursor_icon(&self, _cursor: CursorIcon) { + debug!("`Window::set_cursor_icon` ignored on iOS") + } + + pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn set_cursor_grab(&self, _grab: bool) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn set_cursor_visible(&self, _visible: bool) { + debug!("`Window::set_cursor_visible` is ignored on iOS") + } + + pub fn set_minimized(&self, _minimized: bool) { + warn!("`Window::set_minimized` is ignored on iOS") + } + + pub fn set_maximized(&self, _maximized: bool) { + warn!("`Window::set_maximized` is ignored on iOS") + } + + pub fn set_fullscreen(&self, monitor: Option) { + unsafe { + let uiscreen = match monitor { + Some(Fullscreen::Exclusive(video_mode)) => { + let uiscreen = video_mode.video_mode.monitor.ui_screen() as id; + let () = msg_send![uiscreen, setCurrentMode: video_mode.video_mode.screen_mode]; + uiscreen + } + Some(Fullscreen::Borderless(monitor)) => monitor.ui_screen() as id, + None => { + warn!("`Window::set_fullscreen(None)` ignored on iOS"); + return; + } + }; + + // this is pretty slow on iOS, so avoid doing it if we can + let current: id = msg_send![self.window, screen]; + if uiscreen != current { + let () = msg_send![self.window, setScreen: uiscreen]; + } + + let bounds: CGRect = msg_send![uiscreen, bounds]; + let () = msg_send![self.window, setFrame: bounds]; + + // For external displays, we must disable overscan compensation or + // the displayed image will have giant black bars surrounding it on + // each side + let () = msg_send![ + uiscreen, + setOverscanCompensation: UIScreenOverscanCompensation::None + ]; + } + } + + pub fn fullscreen(&self) -> Option { + unsafe { + let monitor = self.current_monitor(); + let uiscreen = monitor.inner.ui_screen(); + let screen_space_bounds = self.screen_frame(); + let screen_bounds: CGRect = msg_send![uiscreen, bounds]; + + // TODO: track fullscreen instead of relying on brittle float comparisons + if screen_space_bounds.origin.x == screen_bounds.origin.x + && screen_space_bounds.origin.y == screen_bounds.origin.y + && screen_space_bounds.size.width == screen_bounds.size.width + && screen_space_bounds.size.height == screen_bounds.size.height + { + Some(Fullscreen::Borderless(monitor)) + } else { + None + } + } + } + + pub fn set_decorations(&self, _decorations: bool) { + warn!("`Window::set_decorations` is ignored on iOS") + } + + pub fn set_always_on_top(&self, _always_on_top: bool) { + warn!("`Window::set_always_on_top` is ignored on iOS") + } + + pub fn set_window_icon(&self, _icon: Option) { + warn!("`Window::set_window_icon` is ignored on iOS") + } + + pub fn set_ime_position(&self, _position: Position) { + warn!("`Window::set_ime_position` is ignored on iOS") + } + + pub fn current_monitor(&self) -> RootMonitorHandle { + unsafe { + let uiscreen: id = msg_send![self.window, screen]; + RootMonitorHandle { + inner: MonitorHandle::retained_new(uiscreen), + } + } + } + + pub fn available_monitors(&self) -> VecDeque { + unsafe { monitor::uiscreens() } + } + + pub fn primary_monitor(&self) -> MonitorHandle { + unsafe { monitor::main_uiscreen() } + } + + pub fn id(&self) -> WindowId { + self.window.into() + } + + pub fn raw_window_handle(&self) -> RawWindowHandle { + let handle = IOSHandle { + ui_window: self.window as _, + ui_view: self.view as _, + ui_view_controller: self.view_controller as _, + ..IOSHandle::empty() + }; + RawWindowHandle::IOS(handle) + } +} + +pub struct Window { + pub inner: Inner, +} + +impl Drop for Window { + fn drop(&mut self) { + unsafe { + assert_main_thread!("`Window::drop` can only be run on the main thread on iOS"); + } + } +} + +unsafe impl Send for Window {} +unsafe impl Sync for Window {} + +impl Deref for Window { + type Target = Inner; + + fn deref(&self) -> &Inner { + unsafe { + assert_main_thread!("`Window` methods can only be run on the main thread on iOS"); + } + &self.inner + } +} + +impl DerefMut for Window { + fn deref_mut(&mut self) -> &mut Inner { + unsafe { + assert_main_thread!("`Window` methods can only be run on the main thread on iOS"); + } + &mut self.inner + } +} + +impl Window { + pub fn new( + _event_loop: &EventLoopWindowTarget, + window_attributes: WindowAttributes, + platform_attributes: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + if let Some(_) = window_attributes.min_inner_size { + warn!("`WindowAttributes::min_inner_size` is ignored on iOS"); + } + if let Some(_) = window_attributes.max_inner_size { + warn!("`WindowAttributes::max_inner_size` is ignored on iOS"); + } + if window_attributes.always_on_top { + warn!("`WindowAttributes::always_on_top` is unsupported on iOS"); + } + // TODO: transparency, visible + + unsafe { + let screen = match window_attributes.fullscreen { + Some(Fullscreen::Exclusive(ref video_mode)) => { + video_mode.video_mode.monitor.ui_screen() as id + } + Some(Fullscreen::Borderless(ref monitor)) => monitor.ui_screen() as id, + None => monitor::main_uiscreen().ui_screen(), + }; + + let screen_bounds: CGRect = msg_send![screen, bounds]; + + let frame = match window_attributes.inner_size { + Some(dim) => { + let scale_factor = msg_send![screen, scale]; + let size = dim.to_logical::(scale_factor); + CGRect { + origin: screen_bounds.origin, + size: CGSize { + width: size.width as _, + height: size.height as _, + }, + } + } + None => screen_bounds, + }; + + let view = view::create_view(&window_attributes, &platform_attributes, frame.clone()); + + let gl_or_metal_backed = { + let view_class: id = msg_send![view, class]; + let layer_class: id = msg_send![view_class, layerClass]; + let is_metal: BOOL = + msg_send![layer_class, isSubclassOfClass: class!(CAMetalLayer)]; + let is_gl: BOOL = msg_send![layer_class, isSubclassOfClass: class!(CAEAGLLayer)]; + is_metal == YES || is_gl == YES + }; + + let view_controller = + view::create_view_controller(&window_attributes, &platform_attributes, view); + let window = view::create_window( + &window_attributes, + &platform_attributes, + frame, + view_controller, + ); + + let result = Window { + inner: Inner { + window, + view_controller, + view, + gl_or_metal_backed, + }, + }; + app_state::set_key_window(window); + + // Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized` + // event on window creation if the DPI factor != 1.0 + let scale_factor: CGFloat = msg_send![view, contentScaleFactor]; + let scale_factor: f64 = scale_factor.into(); + if scale_factor != 1.0 { + let bounds: CGRect = msg_send![view, bounds]; + let screen: id = msg_send![window, screen]; + let screen_space: id = msg_send![screen, coordinateSpace]; + let screen_frame: CGRect = + msg_send![view, convertRect:bounds toCoordinateSpace:screen_space]; + let size = crate::dpi::LogicalSize { + width: screen_frame.size.width as _, + height: screen_frame.size.height as _, + }; + app_state::handle_nonuser_events( + std::iter::once(EventWrapper::EventProxy(EventProxy::DpiChangedProxy { + window_id: window, + scale_factor, + suggested_size: size, + })) + .chain(std::iter::once(EventWrapper::StaticEvent( + Event::WindowEvent { + window_id: RootWindowId(window.into()), + event: WindowEvent::Resized(size.to_physical(scale_factor)), + }, + ))), + ); + } + + Ok(result) + } + } +} + +// WindowExtIOS +impl Inner { + pub fn ui_window(&self) -> id { + self.window + } + pub fn ui_view_controller(&self) -> id { + self.view_controller + } + pub fn ui_view(&self) -> id { + self.view + } + + pub fn set_scale_factor(&self, scale_factor: f64) { + unsafe { + assert!( + dpi::validate_scale_factor(scale_factor), + "`WindowExtIOS::set_scale_factor` received an invalid hidpi factor" + ); + let scale_factor = scale_factor as CGFloat; + let () = msg_send![self.view, setContentScaleFactor: scale_factor]; + } + } + + pub fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + unsafe { + let idiom = event_loop::get_idiom(); + let supported_orientations = UIInterfaceOrientationMask::from_valid_orientations_idiom( + valid_orientations, + idiom, + ); + msg_send![ + self.view_controller, + setSupportedInterfaceOrientations: supported_orientations + ] + } + } + + pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + unsafe { + let prefers_home_indicator_hidden = if hidden { YES } else { NO }; + let () = msg_send![ + self.view_controller, + setPrefersHomeIndicatorAutoHidden: prefers_home_indicator_hidden + ]; + } + } + + pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + let edges: UIRectEdge = edges.into(); + unsafe { + let () = msg_send![ + self.view_controller, + setPreferredScreenEdgesDeferringSystemGestures: edges + ]; + } + } + + pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { + unsafe { + let status_bar_hidden = if hidden { YES } else { NO }; + let () = msg_send![ + self.view_controller, + setPrefersStatusBarHidden: status_bar_hidden + ]; + } + } +} + +impl Inner { + // requires main thread + unsafe fn screen_frame(&self) -> CGRect { + self.to_screen_space(msg_send![self.window, bounds]) + } + + // requires main thread + unsafe fn to_screen_space(&self, rect: CGRect) -> CGRect { + let screen: id = msg_send![self.window, screen]; + if !screen.is_null() { + let screen_space: id = msg_send![screen, coordinateSpace]; + msg_send![self.window, convertRect:rect toCoordinateSpace:screen_space] + } else { + rect + } + } + + // requires main thread + unsafe fn from_screen_space(&self, rect: CGRect) -> CGRect { + let screen: id = msg_send![self.window, screen]; + if !screen.is_null() { + let screen_space: id = msg_send![screen, coordinateSpace]; + msg_send![self.window, convertRect:rect fromCoordinateSpace:screen_space] + } else { + rect + } + } + + // requires main thread + unsafe fn safe_area_screen_space(&self) -> CGRect { + let bounds: CGRect = msg_send![self.window, bounds]; + if app_state::os_capabilities().safe_area { + let safe_area: UIEdgeInsets = msg_send![self.window, safeAreaInsets]; + let safe_bounds = CGRect { + origin: CGPoint { + x: bounds.origin.x + safe_area.left, + y: bounds.origin.y + safe_area.top, + }, + size: CGSize { + width: bounds.size.width - safe_area.left - safe_area.right, + height: bounds.size.height - safe_area.top - safe_area.bottom, + }, + }; + self.to_screen_space(safe_bounds) + } else { + let screen_frame = self.to_screen_space(bounds); + let status_bar_frame: CGRect = { + let app: id = msg_send![class!(UIApplication), sharedApplication]; + assert!( + !app.is_null(), + "`Window::get_inner_position` cannot be called before `EventLoop::run` on iOS" + ); + msg_send![app, statusBarFrame] + }; + let (y, height) = if screen_frame.origin.y > status_bar_frame.size.height { + (screen_frame.origin.y, screen_frame.size.height) + } else { + let y = status_bar_frame.size.height; + let height = screen_frame.size.height + - (status_bar_frame.size.height - screen_frame.origin.y); + (y, height) + }; + CGRect { + origin: CGPoint { + x: screen_frame.origin.x, + y, + }, + size: CGSize { + width: screen_frame.size.width, + height, + }, + } + } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId { + window: id, +} + +impl WindowId { + pub unsafe fn dummy() -> Self { + WindowId { + window: std::ptr::null_mut(), + } + } +} + +unsafe impl Send for WindowId {} +unsafe impl Sync for WindowId {} + +impl From<&Object> for WindowId { + fn from(window: &Object) -> WindowId { + WindowId { + window: window as *const _ as _, + } + } +} + +impl From<&mut Object> for WindowId { + fn from(window: &mut Object) -> WindowId { + WindowId { + window: window as _, + } + } +} + +impl From for WindowId { + fn from(window: id) -> WindowId { + WindowId { window } + } +} + +#[derive(Clone)] +pub struct PlatformSpecificWindowBuilderAttributes { + pub root_view_class: &'static Class, + pub scale_factor: Option, + pub valid_orientations: ValidOrientations, + pub prefers_home_indicator_hidden: bool, + pub prefers_status_bar_hidden: bool, + pub preferred_screen_edges_deferring_system_gestures: ScreenEdge, +} + +impl Default for PlatformSpecificWindowBuilderAttributes { + fn default() -> PlatformSpecificWindowBuilderAttributes { + PlatformSpecificWindowBuilderAttributes { + root_view_class: class!(UIView), + scale_factor: None, + valid_orientations: Default::default(), + prefers_home_indicator_hidden: false, + prefers_status_bar_hidden: false, + preferred_screen_edges_deferring_system_gestures: Default::default(), + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/mod.rs new file mode 100644 index 0000000..8958ddc --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/mod.rs @@ -0,0 +1,731 @@ +#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] + +use std::{collections::VecDeque, env, ffi::CStr, fmt, mem::MaybeUninit, os::raw::*, sync::Arc}; + +use parking_lot::Mutex; +use raw_window_handle::RawWindowHandle; +use smithay_client_toolkit::reexports::client::ConnectError; + +pub use self::x11::XNotSupported; +use self::x11::{ffi::XVisualInfo, util::WindowType as XWindowType, XConnection, XError}; +use crate::{ + dpi::{PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + event::Event, + event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW}, + icon::Icon, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + window::{CursorIcon, Fullscreen, WindowAttributes}, +}; + +pub(crate) use crate::icon::RgbaIcon as PlatformIcon; + +pub mod wayland; +pub mod x11; + +/// Environment variable specifying which backend should be used on unix platform. +/// +/// Legal values are x11 and wayland. If this variable is set only the named backend +/// will be tried by winit. If it is not set, winit will try to connect to a wayland connection, +/// and if it fails will fallback on x11. +/// +/// If this variable is set with any other value, winit will panic. +const BACKEND_PREFERENCE_ENV_VAR: &str = "WINIT_UNIX_BACKEND"; + +#[derive(Clone)] +pub struct PlatformSpecificWindowBuilderAttributes { + pub visual_infos: Option, + pub screen_id: Option, + pub resize_increments: Option, + pub base_size: Option, + pub class: Option<(String, String)>, + pub override_redirect: bool, + pub x11_window_types: Vec, + pub gtk_theme_variant: Option, + pub app_id: Option, +} + +impl Default for PlatformSpecificWindowBuilderAttributes { + fn default() -> Self { + Self { + visual_infos: None, + screen_id: None, + resize_increments: None, + base_size: None, + class: None, + override_redirect: false, + x11_window_types: vec![XWindowType::Normal], + gtk_theme_variant: None, + app_id: None, + } + } +} + +lazy_static! { + pub static ref X11_BACKEND: Mutex, XNotSupported>> = + { Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new)) }; +} + +#[derive(Debug, Clone)] +pub enum OsError { + XError(XError), + XMisc(&'static str), +} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match self { + OsError::XError(e) => f.pad(&e.description), + OsError::XMisc(e) => f.pad(e), + } + } +} + +pub enum Window { + X(x11::Window), + Wayland(wayland::Window), +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum WindowId { + X(x11::WindowId), + Wayland(wayland::WindowId), +} + +impl WindowId { + pub unsafe fn dummy() -> Self { + WindowId::Wayland(wayland::WindowId::dummy()) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DeviceId { + X(x11::DeviceId), + Wayland(wayland::DeviceId), +} + +impl DeviceId { + pub unsafe fn dummy() -> Self { + DeviceId::Wayland(wayland::DeviceId::dummy()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum MonitorHandle { + X(x11::MonitorHandle), + Wayland(wayland::MonitorHandle), +} + +impl MonitorHandle { + #[inline] + pub fn name(&self) -> Option { + match self { + &MonitorHandle::X(ref m) => m.name(), + &MonitorHandle::Wayland(ref m) => m.name(), + } + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + match self { + &MonitorHandle::X(ref m) => m.native_identifier(), + &MonitorHandle::Wayland(ref m) => m.native_identifier(), + } + } + + #[inline] + pub fn size(&self) -> PhysicalSize { + match self { + &MonitorHandle::X(ref m) => m.size(), + &MonitorHandle::Wayland(ref m) => m.size(), + } + } + + #[inline] + pub fn position(&self) -> PhysicalPosition { + match self { + &MonitorHandle::X(ref m) => m.position(), + &MonitorHandle::Wayland(ref m) => m.position(), + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + match self { + &MonitorHandle::X(ref m) => m.scale_factor(), + &MonitorHandle::Wayland(ref m) => m.scale_factor() as f64, + } + } + + #[inline] + pub fn video_modes(&self) -> Box> { + match self { + MonitorHandle::X(m) => Box::new(m.video_modes()), + MonitorHandle::Wayland(m) => Box::new(m.video_modes()), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VideoMode { + X(x11::VideoMode), + Wayland(wayland::VideoMode), +} + +impl VideoMode { + #[inline] + pub fn size(&self) -> PhysicalSize { + match self { + &VideoMode::X(ref m) => m.size(), + &VideoMode::Wayland(ref m) => m.size(), + } + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + match self { + &VideoMode::X(ref m) => m.bit_depth(), + &VideoMode::Wayland(ref m) => m.bit_depth(), + } + } + + #[inline] + pub fn refresh_rate(&self) -> u16 { + match self { + &VideoMode::X(ref m) => m.refresh_rate(), + &VideoMode::Wayland(ref m) => m.refresh_rate(), + } + } + + #[inline] + pub fn monitor(&self) -> RootMonitorHandle { + match self { + &VideoMode::X(ref m) => m.monitor(), + &VideoMode::Wayland(ref m) => m.monitor(), + } + } +} + +impl Window { + #[inline] + pub fn new( + window_target: &EventLoopWindowTarget, + attribs: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + match *window_target { + EventLoopWindowTarget::Wayland(ref window_target) => { + wayland::Window::new(window_target, attribs, pl_attribs).map(Window::Wayland) + } + EventLoopWindowTarget::X(ref window_target) => { + x11::Window::new(window_target, attribs, pl_attribs).map(Window::X) + } + } + } + + #[inline] + pub fn id(&self) -> WindowId { + match self { + &Window::X(ref w) => WindowId::X(w.id()), + &Window::Wayland(ref w) => WindowId::Wayland(w.id()), + } + } + + #[inline] + pub fn set_title(&self, title: &str) { + match self { + &Window::X(ref w) => w.set_title(title), + &Window::Wayland(ref w) => w.set_title(title), + } + } + + #[inline] + pub fn set_visible(&self, visible: bool) { + match self { + &Window::X(ref w) => w.set_visible(visible), + &Window::Wayland(ref w) => w.set_visible(visible), + } + } + + #[inline] + pub fn outer_position(&self) -> Result, NotSupportedError> { + match self { + &Window::X(ref w) => w.outer_position(), + &Window::Wayland(ref w) => w.outer_position(), + } + } + + #[inline] + pub fn inner_position(&self) -> Result, NotSupportedError> { + match self { + &Window::X(ref m) => m.inner_position(), + &Window::Wayland(ref m) => m.inner_position(), + } + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + match self { + &Window::X(ref w) => w.set_outer_position(position), + &Window::Wayland(ref w) => w.set_outer_position(position), + } + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + match self { + &Window::X(ref w) => w.inner_size(), + &Window::Wayland(ref w) => w.inner_size(), + } + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + match self { + &Window::X(ref w) => w.outer_size(), + &Window::Wayland(ref w) => w.outer_size(), + } + } + + #[inline] + pub fn set_inner_size(&self, size: Size) { + match self { + &Window::X(ref w) => w.set_inner_size(size), + &Window::Wayland(ref w) => w.set_inner_size(size), + } + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option) { + match self { + &Window::X(ref w) => w.set_min_inner_size(dimensions), + &Window::Wayland(ref w) => w.set_min_inner_size(dimensions), + } + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option) { + match self { + &Window::X(ref w) => w.set_max_inner_size(dimensions), + &Window::Wayland(ref w) => w.set_max_inner_size(dimensions), + } + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + match self { + &Window::X(ref w) => w.set_resizable(resizable), + &Window::Wayland(ref w) => w.set_resizable(resizable), + } + } + + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + match self { + &Window::X(ref w) => w.set_cursor_icon(cursor), + &Window::Wayland(ref w) => w.set_cursor_icon(cursor), + } + } + + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + match self { + &Window::X(ref window) => window.set_cursor_grab(grab), + &Window::Wayland(ref window) => window.set_cursor_grab(grab), + } + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + match self { + &Window::X(ref window) => window.set_cursor_visible(visible), + &Window::Wayland(ref window) => window.set_cursor_visible(visible), + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + match self { + &Window::X(ref w) => w.scale_factor(), + &Window::Wayland(ref w) => w.scale_factor() as f64, + } + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + match self { + &Window::X(ref w) => w.set_cursor_position(position), + &Window::Wayland(ref w) => w.set_cursor_position(position), + } + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + match self { + &Window::X(ref w) => w.set_maximized(maximized), + &Window::Wayland(ref w) => w.set_maximized(maximized), + } + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + match self { + &Window::X(ref w) => w.set_minimized(minimized), + &Window::Wayland(ref w) => w.set_minimized(minimized), + } + } + + #[inline] + pub fn fullscreen(&self) -> Option { + match self { + &Window::X(ref w) => w.fullscreen(), + &Window::Wayland(ref w) => w.fullscreen(), + } + } + + #[inline] + pub fn set_fullscreen(&self, monitor: Option) { + match self { + &Window::X(ref w) => w.set_fullscreen(monitor), + &Window::Wayland(ref w) => w.set_fullscreen(monitor), + } + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + match self { + &Window::X(ref w) => w.set_decorations(decorations), + &Window::Wayland(ref w) => w.set_decorations(decorations), + } + } + + #[inline] + pub fn set_always_on_top(&self, always_on_top: bool) { + match self { + &Window::X(ref w) => w.set_always_on_top(always_on_top), + &Window::Wayland(_) => (), + } + } + + #[inline] + pub fn set_window_icon(&self, window_icon: Option) { + match self { + &Window::X(ref w) => w.set_window_icon(window_icon), + &Window::Wayland(_) => (), + } + } + + #[inline] + pub fn set_ime_position(&self, position: Position) { + match self { + &Window::X(ref w) => w.set_ime_position(position), + &Window::Wayland(_) => (), + } + } + + #[inline] + pub fn request_redraw(&self) { + match self { + &Window::X(ref w) => w.request_redraw(), + &Window::Wayland(ref w) => w.request_redraw(), + } + } + + #[inline] + pub fn current_monitor(&self) -> RootMonitorHandle { + match self { + &Window::X(ref window) => RootMonitorHandle { + inner: MonitorHandle::X(window.current_monitor()), + }, + &Window::Wayland(ref window) => RootMonitorHandle { + inner: MonitorHandle::Wayland(window.current_monitor()), + }, + } + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque { + match self { + &Window::X(ref window) => window + .available_monitors() + .into_iter() + .map(MonitorHandle::X) + .collect(), + &Window::Wayland(ref window) => window + .available_monitors() + .into_iter() + .map(MonitorHandle::Wayland) + .collect(), + } + } + + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + match self { + &Window::X(ref window) => MonitorHandle::X(window.primary_monitor()), + &Window::Wayland(ref window) => MonitorHandle::Wayland(window.primary_monitor()), + } + } + + pub fn raw_window_handle(&self) -> RawWindowHandle { + match self { + &Window::X(ref window) => RawWindowHandle::Xlib(window.raw_window_handle()), + &Window::Wayland(ref window) => RawWindowHandle::Wayland(window.raw_window_handle()), + } + } +} + +unsafe extern "C" fn x_error_callback( + display: *mut x11::ffi::Display, + event: *mut x11::ffi::XErrorEvent, +) -> c_int { + let xconn_lock = X11_BACKEND.lock(); + if let Ok(ref xconn) = *xconn_lock { + // `assume_init` is safe here because the array consists of `MaybeUninit` values, + // which do not require initialization. + let mut buf: [MaybeUninit; 1024] = MaybeUninit::uninit().assume_init(); + (xconn.xlib.XGetErrorText)( + display, + (*event).error_code as c_int, + buf.as_mut_ptr() as *mut c_char, + buf.len() as c_int, + ); + let description = CStr::from_ptr(buf.as_ptr() as *const c_char).to_string_lossy(); + + let error = XError { + description: description.into_owned(), + error_code: (*event).error_code, + request_code: (*event).request_code, + minor_code: (*event).minor_code, + }; + + error!("X11 error: {:#?}", error); + + *xconn.latest_error.lock() = Some(error); + } + // Fun fact: this return value is completely ignored. + 0 +} + +pub enum EventLoop { + Wayland(wayland::EventLoop), + X(x11::EventLoop), +} + +pub enum EventLoopProxy { + X(x11::EventLoopProxy), + Wayland(wayland::EventLoopProxy), +} + +impl Clone for EventLoopProxy { + fn clone(&self) -> Self { + match self { + EventLoopProxy::X(proxy) => EventLoopProxy::X(proxy.clone()), + EventLoopProxy::Wayland(proxy) => EventLoopProxy::Wayland(proxy.clone()), + } + } +} + +impl EventLoop { + pub fn new() -> EventLoop { + assert_is_main_thread("new_any_thread"); + + EventLoop::new_any_thread() + } + + pub fn new_any_thread() -> EventLoop { + if let Ok(env_var) = env::var(BACKEND_PREFERENCE_ENV_VAR) { + match env_var.as_str() { + "x11" => { + // TODO: propagate + return EventLoop::new_x11_any_thread() + .expect("Failed to initialize X11 backend"); + } + "wayland" => { + return EventLoop::new_wayland_any_thread() + .expect("Failed to initialize Wayland backend"); + } + _ => panic!( + "Unknown environment variable value for {}, try one of `x11`,`wayland`", + BACKEND_PREFERENCE_ENV_VAR, + ), + } + } + + let wayland_err = match EventLoop::new_wayland_any_thread() { + Ok(event_loop) => return event_loop, + Err(err) => err, + }; + + let x11_err = match EventLoop::new_x11_any_thread() { + Ok(event_loop) => return event_loop, + Err(err) => err, + }; + + let err_string = format!( + "Failed to initialize any backend! Wayland status: {:?} X11 status: {:?}", + wayland_err, x11_err, + ); + panic!(err_string); + } + + pub fn new_wayland() -> Result, ConnectError> { + assert_is_main_thread("new_wayland_any_thread"); + + EventLoop::new_wayland_any_thread() + } + + pub fn new_wayland_any_thread() -> Result, ConnectError> { + wayland::EventLoop::new().map(EventLoop::Wayland) + } + + pub fn new_x11() -> Result, XNotSupported> { + assert_is_main_thread("new_x11_any_thread"); + + EventLoop::new_x11_any_thread() + } + + pub fn new_x11_any_thread() -> Result, XNotSupported> { + let xconn = match X11_BACKEND.lock().as_ref() { + Ok(xconn) => xconn.clone(), + Err(err) => return Err(err.clone()), + }; + + Ok(EventLoop::X(x11::EventLoop::new(xconn))) + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque { + match *self { + EventLoop::Wayland(ref evlp) => evlp + .available_monitors() + .into_iter() + .map(MonitorHandle::Wayland) + .collect(), + EventLoop::X(ref evlp) => evlp + .x_connection() + .available_monitors() + .into_iter() + .map(MonitorHandle::X) + .collect(), + } + } + + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + match *self { + EventLoop::Wayland(ref evlp) => MonitorHandle::Wayland(evlp.primary_monitor()), + EventLoop::X(ref evlp) => MonitorHandle::X(evlp.x_connection().primary_monitor()), + } + } + + pub fn create_proxy(&self) -> EventLoopProxy { + match *self { + EventLoop::Wayland(ref evlp) => EventLoopProxy::Wayland(evlp.create_proxy()), + EventLoop::X(ref evlp) => EventLoopProxy::X(evlp.create_proxy()), + } + } + + pub fn run_return(&mut self, callback: F) + where + F: FnMut(crate::event::Event<'_, T>, &RootELW, &mut ControlFlow), + { + match *self { + EventLoop::Wayland(ref mut evlp) => evlp.run_return(callback), + EventLoop::X(ref mut evlp) => evlp.run_return(callback), + } + } + + pub fn run(self, callback: F) -> ! + where + F: 'static + FnMut(crate::event::Event<'_, T>, &RootELW, &mut ControlFlow), + { + match self { + EventLoop::Wayland(evlp) => evlp.run(callback), + EventLoop::X(evlp) => evlp.run(callback), + } + } + + pub fn window_target(&self) -> &crate::event_loop::EventLoopWindowTarget { + match *self { + EventLoop::Wayland(ref evl) => evl.window_target(), + EventLoop::X(ref evl) => evl.window_target(), + } + } +} + +impl EventLoopProxy { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + match *self { + EventLoopProxy::Wayland(ref proxy) => proxy.send_event(event), + EventLoopProxy::X(ref proxy) => proxy.send_event(event), + } + } +} + +pub enum EventLoopWindowTarget { + Wayland(wayland::EventLoopWindowTarget), + X(x11::EventLoopWindowTarget), +} + +impl EventLoopWindowTarget { + #[inline] + pub fn is_wayland(&self) -> bool { + match *self { + EventLoopWindowTarget::Wayland(_) => true, + EventLoopWindowTarget::X(_) => false, + } + } +} + +fn sticky_exit_callback( + evt: Event<'_, T>, + target: &RootELW, + control_flow: &mut ControlFlow, + callback: &mut F, +) where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), +{ + // make ControlFlow::Exit sticky by providing a dummy + // control flow reference if it is already Exit. + let mut dummy = ControlFlow::Exit; + let cf = if *control_flow == ControlFlow::Exit { + &mut dummy + } else { + control_flow + }; + // user callback + callback(evt, target, cf) +} + +fn assert_is_main_thread(suggested_method: &str) { + if !is_main_thread() { + panic!( + "Initializing the event loop outside of the main thread is a significant \ + cross-platform compatibility hazard. If you really, absolutely need to create an \ + EventLoop on a different thread, please use the `EventLoopExtUnix::{}` function.", + suggested_method + ); + } +} + +#[cfg(target_os = "linux")] +fn is_main_thread() -> bool { + use libc::{c_long, getpid, syscall, SYS_gettid}; + + unsafe { syscall(SYS_gettid) == getpid() as c_long } +} + +#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))] +fn is_main_thread() -> bool { + use libc::pthread_main_np; + + unsafe { pthread_main_np() == 1 } +} + +#[cfg(target_os = "netbsd")] +fn is_main_thread() -> bool { + use libc::_lwp_self; + + unsafe { _lwp_self() == 1 } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/event_loop.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/event_loop.rs new file mode 100644 index 0000000..47c5aea --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/event_loop.rs @@ -0,0 +1,1131 @@ +use std::{ + cell::RefCell, + collections::VecDeque, + fmt, + io::ErrorKind, + rc::Rc, + sync::{Arc, Mutex}, + time::{Duration, Instant}, +}; + +use mio::{Events, Poll, PollOpt, Ready, Token}; + +use mio_extras::channel::{channel, Receiver, SendError, Sender}; + +use smithay_client_toolkit::reexports::protocols::unstable::pointer_constraints::v1::client::{ + zwp_locked_pointer_v1::ZwpLockedPointerV1, zwp_pointer_constraints_v1::ZwpPointerConstraintsV1, +}; +use smithay_client_toolkit::reexports::protocols::unstable::relative_pointer::v1::client::{ + zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, + zwp_relative_pointer_v1::ZwpRelativePointerV1, +}; + +use smithay_client_toolkit::pointer::{AutoPointer, AutoThemer}; +use smithay_client_toolkit::reexports::client::protocol::{ + wl_compositor::WlCompositor, wl_shm::WlShm, wl_surface::WlSurface, +}; + +use crate::{ + dpi::{LogicalSize, PhysicalPosition, PhysicalSize}, + event::{ + DeviceEvent, DeviceId as RootDeviceId, Event, ModifiersState, StartCause, WindowEvent, + }, + event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform_impl::platform::{ + sticky_exit_callback, DeviceId as PlatformDeviceId, MonitorHandle as PlatformMonitorHandle, + VideoMode as PlatformVideoMode, WindowId as PlatformWindowId, + }, + window::{CursorIcon, WindowId as RootWindowId}, +}; + +use super::{ + window::{DecorationsAction, WindowStore}, + DeviceId, WindowId, +}; + +use smithay_client_toolkit::{ + output::OutputMgr, + reexports::client::{ + protocol::{wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat, wl_touch}, + ConnectError, Display, EventQueue, GlobalEvent, + }, + Environment, +}; + +const KBD_TOKEN: Token = Token(0); +const USER_TOKEN: Token = Token(1); +const EVQ_TOKEN: Token = Token(2); + +#[derive(Clone)] +pub struct EventsSink { + sender: Sender>, +} + +impl EventsSink { + pub fn new(sender: Sender>) -> EventsSink { + EventsSink { sender } + } + + pub fn send_event(&self, event: Event<'static, ()>) { + self.sender.send(event).unwrap() + } + + pub fn send_device_event(&self, event: DeviceEvent, device_id: DeviceId) { + self.send_event(Event::DeviceEvent { + event, + device_id: RootDeviceId(PlatformDeviceId::Wayland(device_id)), + }); + } + + pub fn send_window_event(&self, event: WindowEvent<'static>, window_id: WindowId) { + self.send_event(Event::WindowEvent { + event, + window_id: RootWindowId(PlatformWindowId::Wayland(window_id)), + }); + } +} + +pub struct CursorManager { + pointer_constraints_proxy: Arc>>, + auto_themer: Option, + pointers: Vec, + locked_pointers: Vec, + cursor_visible: bool, + current_cursor: CursorIcon, + scale_factor: u32, +} + +impl CursorManager { + fn new(constraints: Arc>>) -> CursorManager { + CursorManager { + pointer_constraints_proxy: constraints, + auto_themer: None, + pointers: Vec::new(), + locked_pointers: Vec::new(), + cursor_visible: true, + current_cursor: CursorIcon::default(), + scale_factor: 1, + } + } + + fn register_pointer(&mut self, pointer: wl_pointer::WlPointer) { + let auto_themer = self + .auto_themer + .as_ref() + .expect("AutoThemer not initialized. Server did not advertise shm or compositor?"); + self.pointers.push(auto_themer.theme_pointer(pointer)); + } + + fn set_auto_themer(&mut self, auto_themer: AutoThemer) { + self.auto_themer = Some(auto_themer); + } + + pub fn set_cursor_visible(&mut self, visible: bool) { + if !visible { + for pointer in self.pointers.iter() { + (**pointer).set_cursor(0, None, 0, 0); + } + } else { + self.set_cursor_icon_impl(self.current_cursor); + } + self.cursor_visible = visible; + } + + /// A helper function to restore cursor styles on PtrEvent::Enter. + pub fn reload_cursor_style(&mut self) { + if !self.cursor_visible { + self.set_cursor_visible(false); + } else { + self.set_cursor_icon_impl(self.current_cursor); + } + } + + pub fn set_cursor_icon(&mut self, cursor: CursorIcon) { + if cursor != self.current_cursor { + self.current_cursor = cursor; + if self.cursor_visible { + self.set_cursor_icon_impl(cursor); + } + } + } + + pub fn update_scale_factor(&mut self, scale: u32) { + self.scale_factor = scale; + self.reload_cursor_style(); + } + + fn set_cursor_icon_impl(&mut self, cursor: CursorIcon) { + let cursor = match cursor { + CursorIcon::Alias => "link", + CursorIcon::Arrow => "arrow", + CursorIcon::Cell => "plus", + CursorIcon::Copy => "copy", + CursorIcon::Crosshair => "crosshair", + CursorIcon::Default => "left_ptr", + CursorIcon::Hand => "hand", + CursorIcon::Help => "question_arrow", + CursorIcon::Move => "move", + CursorIcon::Grab => "grab", + CursorIcon::Grabbing => "grabbing", + CursorIcon::Progress => "progress", + CursorIcon::AllScroll => "all-scroll", + CursorIcon::ContextMenu => "context-menu", + + CursorIcon::NoDrop => "no-drop", + CursorIcon::NotAllowed => "crossed_circle", + + // Resize cursors + CursorIcon::EResize => "right_side", + CursorIcon::NResize => "top_side", + CursorIcon::NeResize => "top_right_corner", + CursorIcon::NwResize => "top_left_corner", + CursorIcon::SResize => "bottom_side", + CursorIcon::SeResize => "bottom_right_corner", + CursorIcon::SwResize => "bottom_left_corner", + CursorIcon::WResize => "left_side", + CursorIcon::EwResize => "h_double_arrow", + CursorIcon::NsResize => "v_double_arrow", + CursorIcon::NwseResize => "bd_double_arrow", + CursorIcon::NeswResize => "fd_double_arrow", + CursorIcon::ColResize => "h_double_arrow", + CursorIcon::RowResize => "v_double_arrow", + + CursorIcon::Text => "text", + CursorIcon::VerticalText => "vertical-text", + + CursorIcon::Wait => "watch", + + CursorIcon::ZoomIn => "zoom-in", + CursorIcon::ZoomOut => "zoom-out", + }; + + for pointer in self.pointers.iter() { + // Ignore erros, since we don't want to fail hard in case we can't find a proper cursor + // in a given theme. + let _ = pointer.set_cursor_with_scale(cursor, self.scale_factor, None); + } + } + + // This function can only be called from a thread on which `pointer_constraints_proxy` event + // queue is located, so calling it directly from a Window doesn't work well, in case + // you've sent your window to another thread, so we need to pass cursor grab updates to + // the event loop and call this function from there. + fn grab_pointer(&mut self, surface: Option<&WlSurface>) { + for locked_pointer in self.locked_pointers.drain(..) { + locked_pointer.destroy(); + } + + if let Some(surface) = surface { + for pointer in self.pointers.iter() { + let locked_pointer = self + .pointer_constraints_proxy + .try_lock() + .unwrap() + .as_ref() + .and_then(|pointer_constraints| { + super::pointer::implement_locked_pointer( + surface, + &**pointer, + pointer_constraints, + ) + .ok() + }); + + if let Some(locked_pointer) = locked_pointer { + self.locked_pointers.push(locked_pointer); + } + } + } + } +} + +pub struct EventLoop { + // Poll instance + poll: Poll, + // The wayland display + pub display: Arc, + // The output manager + pub outputs: OutputMgr, + // The cursor manager + cursor_manager: Arc>, + kbd_channel: Receiver>, + user_channel: Receiver, + user_sender: Sender, + window_target: RootELW, +} + +// A handle that can be sent across threads and used to wake up the `EventLoop`. +// +// We should only try and wake up the `EventLoop` if it still exists, so we hold Weak ptrs. +pub struct EventLoopProxy { + user_sender: Sender, +} + +pub struct EventLoopWindowTarget { + // the event queue + pub evq: RefCell, + // The window store + pub store: Arc>, + // The cursor manager + pub cursor_manager: Arc>, + // The env + pub env: Environment, + // A cleanup switch to prune dead windows + pub cleanup_needed: Arc>, + // The wayland display + pub display: Arc, + // The list of seats + pub seats: Arc>>, + _marker: ::std::marker::PhantomData, +} + +impl Clone for EventLoopProxy { + fn clone(&self) -> Self { + EventLoopProxy { + user_sender: self.user_sender.clone(), + } + } +} + +impl EventLoopProxy { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.user_sender.send(event).map_err(|e| { + EventLoopClosed(if let SendError::Disconnected(x) = e { + x + } else { + unreachable!() + }) + }) + } +} + +impl EventLoop { + pub fn new() -> Result, ConnectError> { + let (display, mut event_queue) = Display::connect_to_env()?; + + let display = Arc::new(display); + let store = Arc::new(Mutex::new(WindowStore::new())); + let seats = Arc::new(Mutex::new(Vec::new())); + + let poll = Poll::new().unwrap(); + + let (kbd_sender, kbd_channel) = channel(); + + let sink = EventsSink::new(kbd_sender); + + poll.register(&kbd_channel, KBD_TOKEN, Ready::readable(), PollOpt::level()) + .unwrap(); + + let pointer_constraints_proxy = Arc::new(Mutex::new(None)); + + let mut seat_manager = SeatManager { + sink, + store: store.clone(), + seats: seats.clone(), + relative_pointer_manager_proxy: Rc::new(RefCell::new(None)), + pointer_constraints_proxy: pointer_constraints_proxy.clone(), + cursor_manager: Arc::new(Mutex::new(CursorManager::new(pointer_constraints_proxy))), + }; + + let cursor_manager = seat_manager.cursor_manager.clone(); + let cursor_manager_clone = cursor_manager.clone(); + + let shm_cell = Rc::new(RefCell::new(None)); + let compositor_cell = Rc::new(RefCell::new(None)); + + let env = Environment::from_display_with_cb( + &display, + &mut event_queue, + move |event, registry| match event { + GlobalEvent::New { + id, + ref interface, + version, + } => { + if interface == "zwp_relative_pointer_manager_v1" { + let relative_pointer_manager_proxy = registry + .bind(version, id, move |pointer_manager| { + pointer_manager.implement_closure(|_, _| (), ()) + }) + .unwrap(); + + *seat_manager + .relative_pointer_manager_proxy + .try_borrow_mut() + .unwrap() = Some(relative_pointer_manager_proxy); + } + if interface == "zwp_pointer_constraints_v1" { + let pointer_constraints_proxy = registry + .bind(version, id, move |pointer_constraints| { + pointer_constraints.implement_closure(|_, _| (), ()) + }) + .unwrap(); + + *seat_manager.pointer_constraints_proxy.lock().unwrap() = + Some(pointer_constraints_proxy); + } + if interface == "wl_shm" { + let shm: WlShm = registry + .bind(version, id, move |shm| shm.implement_closure(|_, _| (), ())) + .unwrap(); + + (*shm_cell.borrow_mut()) = Some(shm); + } + if interface == "wl_compositor" { + let compositor: WlCompositor = registry + .bind(version, id, move |compositor| { + compositor.implement_closure(|_, _| (), ()) + }) + .unwrap(); + (*compositor_cell.borrow_mut()) = Some(compositor); + } + + if compositor_cell.borrow().is_some() && shm_cell.borrow().is_some() { + let compositor = compositor_cell.borrow_mut().take().unwrap(); + let shm = shm_cell.borrow_mut().take().unwrap(); + let auto_themer = AutoThemer::init(None, compositor, &shm); + cursor_manager_clone + .lock() + .unwrap() + .set_auto_themer(auto_themer); + } + + if interface == "wl_seat" { + seat_manager.add_seat(id, version, registry) + } + } + GlobalEvent::Removed { id, ref interface } => { + if interface == "wl_seat" { + seat_manager.remove_seat(id) + } + } + }, + ) + .unwrap(); + + poll.register(&event_queue, EVQ_TOKEN, Ready::readable(), PollOpt::level()) + .unwrap(); + + let (user_sender, user_channel) = channel(); + + poll.register( + &user_channel, + USER_TOKEN, + Ready::readable(), + PollOpt::level(), + ) + .unwrap(); + + let cursor_manager_clone = cursor_manager.clone(); + Ok(EventLoop { + poll, + display: display.clone(), + outputs: env.outputs.clone(), + user_sender, + user_channel, + kbd_channel, + cursor_manager, + window_target: RootELW { + p: crate::platform_impl::EventLoopWindowTarget::Wayland(EventLoopWindowTarget { + evq: RefCell::new(event_queue), + store, + env, + cursor_manager: cursor_manager_clone, + cleanup_needed: Arc::new(Mutex::new(false)), + seats, + display, + _marker: ::std::marker::PhantomData, + }), + _marker: ::std::marker::PhantomData, + }, + }) + } + + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy { + user_sender: self.user_sender.clone(), + } + } + + pub fn run(mut self, callback: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + self.run_return(callback); + std::process::exit(0); + } + + pub fn run_return(&mut self, mut callback: F) + where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + // send pending events to the server + self.display.flush().expect("Wayland connection lost."); + + let mut control_flow = ControlFlow::default(); + let mut events = Events::with_capacity(8); + + callback( + Event::NewEvents(StartCause::Init), + &self.window_target, + &mut control_flow, + ); + + loop { + // Read events from the event queue + { + let mut evq = get_target(&self.window_target).evq.borrow_mut(); + + evq.dispatch_pending() + .expect("failed to dispatch wayland events"); + + if let Some(read) = evq.prepare_read() { + if let Err(e) = read.read_events() { + if e.kind() != ErrorKind::WouldBlock { + panic!("failed to read wayland events: {}", e); + } + } + + evq.dispatch_pending() + .expect("failed to dispatch wayland events"); + } + } + + self.post_dispatch_triggers(&mut callback, &mut control_flow); + + while let Ok(event) = self.kbd_channel.try_recv() { + let event = event.map_nonuser_event().unwrap(); + sticky_exit_callback(event, &self.window_target, &mut control_flow, &mut callback); + } + + while let Ok(event) = self.user_channel.try_recv() { + sticky_exit_callback( + Event::UserEvent(event), + &self.window_target, + &mut control_flow, + &mut callback, + ); + } + + // send Events cleared + { + sticky_exit_callback( + Event::MainEventsCleared, + &self.window_target, + &mut control_flow, + &mut callback, + ); + } + + // handle request-redraw + { + self.redraw_triggers(|wid, window_target| { + sticky_exit_callback( + Event::RedrawRequested(crate::window::WindowId( + crate::platform_impl::WindowId::Wayland(wid), + )), + window_target, + &mut control_flow, + &mut callback, + ); + }); + } + + // send RedrawEventsCleared + { + sticky_exit_callback( + Event::RedrawEventsCleared, + &self.window_target, + &mut control_flow, + &mut callback, + ); + } + + // send pending events to the server + self.display.flush().expect("Wayland connection lost."); + + // During the run of the user callback, some other code monitoring and reading the + // wayland socket may have been run (mesa for example does this with vsync), if that + // is the case, some events may have been enqueued in our event queue. + // + // If some messages are there, the event loop needs to behave as if it was instantly + // woken up by messages arriving from the wayland socket, to avoid getting stuck. + let instant_wakeup = { + let window_target = match self.window_target.p { + crate::platform_impl::EventLoopWindowTarget::Wayland(ref wt) => wt, + _ => unreachable!(), + }; + let dispatched = window_target + .evq + .borrow_mut() + .dispatch_pending() + .expect("Wayland connection lost."); + dispatched > 0 + }; + + match control_flow { + ControlFlow::Exit => break, + ControlFlow::Poll => { + // non-blocking dispatch + self.poll + .poll(&mut events, Some(Duration::from_millis(0))) + .unwrap(); + events.clear(); + + callback( + Event::NewEvents(StartCause::Poll), + &self.window_target, + &mut control_flow, + ); + } + ControlFlow::Wait => { + if !instant_wakeup { + self.poll.poll(&mut events, None).unwrap(); + events.clear(); + } + + callback( + Event::NewEvents(StartCause::WaitCancelled { + start: Instant::now(), + requested_resume: None, + }), + &self.window_target, + &mut control_flow, + ); + } + ControlFlow::WaitUntil(deadline) => { + let start = Instant::now(); + // compute the blocking duration + let duration = if deadline > start && !instant_wakeup { + deadline - start + } else { + Duration::from_millis(0) + }; + self.poll.poll(&mut events, Some(duration)).unwrap(); + events.clear(); + + let now = Instant::now(); + if now < deadline { + callback( + Event::NewEvents(StartCause::WaitCancelled { + start, + requested_resume: Some(deadline), + }), + &self.window_target, + &mut control_flow, + ); + } else { + callback( + Event::NewEvents(StartCause::ResumeTimeReached { + start, + requested_resume: deadline, + }), + &self.window_target, + &mut control_flow, + ); + } + } + } + } + + callback(Event::LoopDestroyed, &self.window_target, &mut control_flow); + } + + pub fn primary_monitor(&self) -> MonitorHandle { + primary_monitor(&self.outputs) + } + + pub fn available_monitors(&self) -> VecDeque { + available_monitors(&self.outputs) + } + + pub fn window_target(&self) -> &RootELW { + &self.window_target + } +} + +impl EventLoopWindowTarget { + pub fn display(&self) -> &Display { + &*self.display + } +} + +/* + * Private EventLoop Internals + */ + +impl EventLoop { + fn redraw_triggers(&mut self, mut callback: F) + where + F: FnMut(WindowId, &RootELW), + { + let window_target = match self.window_target.p { + crate::platform_impl::EventLoopWindowTarget::Wayland(ref wt) => wt, + _ => unreachable!(), + }; + window_target.store.lock().unwrap().for_each_redraw_trigger( + |refresh, frame_refresh, wid, frame| { + if let Some(frame) = frame { + if frame_refresh { + frame.refresh(); + if !refresh { + frame.surface().commit() + } + } + } + if refresh { + callback(wid, &self.window_target); + } + }, + ) + } + + fn post_dispatch_triggers(&mut self, mut callback: F, control_flow: &mut ControlFlow) + where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + let window_target = match self.window_target.p { + crate::platform_impl::EventLoopWindowTarget::Wayland(ref wt) => wt, + _ => unreachable!(), + }; + + let mut callback = |event: Event<'_, T>| { + sticky_exit_callback(event, &self.window_target, control_flow, &mut callback); + }; + + // prune possible dead windows + { + let mut cleanup_needed = window_target.cleanup_needed.lock().unwrap(); + if *cleanup_needed { + let pruned = window_target.store.lock().unwrap().cleanup(); + *cleanup_needed = false; + for wid in pruned { + callback(Event::WindowEvent { + window_id: crate::window::WindowId( + crate::platform_impl::WindowId::Wayland(wid), + ), + event: WindowEvent::Destroyed, + }); + } + } + } + // process pending resize/refresh + window_target.store.lock().unwrap().for_each(|window| { + let window_id = + crate::window::WindowId(crate::platform_impl::WindowId::Wayland(window.wid)); + if let Some(frame) = window.frame { + if let Some((w, h)) = window.newsize { + // Update decorations state + match window.decorations_action { + Some(DecorationsAction::Hide) => frame.set_decorate(false), + Some(DecorationsAction::Show) => frame.set_decorate(true), + None => (), + } + + // mutter (GNOME Wayland) relies on `set_geometry` to reposition window in case + // it overlaps mutter's `bounding box`, so we can't avoid this resize call, + // which calls `set_geometry` under the hood, for now. + frame.resize(w, h); + frame.refresh(); + + // Don't send resize event downstream if the new size is identical to the + // current one. + if (w, h) != *window.size { + let logical_size = crate::dpi::LogicalSize::new(w as f64, h as f64); + let physical_size = logical_size + .to_physical(window.new_dpi.unwrap_or(window.prev_dpi) as f64); + + callback(Event::WindowEvent { + window_id, + event: WindowEvent::Resized(physical_size), + }); + *window.size = (w, h); + } + } + + if let Some(dpi) = window.new_dpi { + // Update cursor scale factor + { + self.cursor_manager + .lock() + .unwrap() + .update_scale_factor(dpi as u32); + }; + let dpi = dpi as f64; + let logical_size = LogicalSize::::from(*window.size); + let mut new_inner_size = logical_size.to_physical(dpi); + + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: dpi, + new_inner_size: &mut new_inner_size, + }, + }); + + let (w, h) = new_inner_size.to_logical::(dpi).into(); + frame.resize(w, h); + // Refresh frame to rescale decorations + frame.refresh(); + *window.size = (w, h); + } + } + if window.closed { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::CloseRequested, + }); + } + + if let Some(grab_cursor) = window.grab_cursor { + let surface = if grab_cursor { + Some(window.surface) + } else { + None + }; + self.cursor_manager.lock().unwrap().grab_pointer(surface); + } + }) + } +} + +fn get_target(target: &RootELW) -> &EventLoopWindowTarget { + match target.p { + crate::platform_impl::EventLoopWindowTarget::Wayland(ref wt) => wt, + _ => unreachable!(), + } +} + +/* + * Wayland protocol implementations + */ + +struct SeatManager { + sink: EventsSink, + store: Arc>, + seats: Arc>>, + relative_pointer_manager_proxy: Rc>>, + pointer_constraints_proxy: Arc>>, + cursor_manager: Arc>, +} + +impl SeatManager { + fn add_seat(&mut self, id: u32, version: u32, registry: wl_registry::WlRegistry) { + use std::cmp::min; + + let mut seat_data = SeatData { + sink: self.sink.clone(), + store: self.store.clone(), + pointer: None, + relative_pointer: None, + relative_pointer_manager_proxy: self.relative_pointer_manager_proxy.clone(), + keyboard: None, + touch: None, + modifiers_tracker: Arc::new(Mutex::new(ModifiersState::default())), + cursor_manager: self.cursor_manager.clone(), + }; + let seat = registry + .bind(min(version, 5), id, move |seat| { + seat.implement_closure(move |event, seat| seat_data.receive(event, seat), ()) + }) + .unwrap(); + self.store.lock().unwrap().new_seat(&seat); + self.seats.lock().unwrap().push((id, seat)); + } + + fn remove_seat(&mut self, id: u32) { + let mut seats = self.seats.lock().unwrap(); + if let Some(idx) = seats.iter().position(|&(i, _)| i == id) { + let (_, seat) = seats.swap_remove(idx); + if seat.as_ref().version() >= 5 { + seat.release(); + } + } + } +} + +struct SeatData { + sink: EventsSink, + store: Arc>, + pointer: Option, + relative_pointer: Option, + relative_pointer_manager_proxy: Rc>>, + keyboard: Option, + touch: Option, + modifiers_tracker: Arc>, + cursor_manager: Arc>, +} + +impl SeatData { + fn receive(&mut self, evt: wl_seat::Event, seat: wl_seat::WlSeat) { + match evt { + wl_seat::Event::Name { .. } => (), + wl_seat::Event::Capabilities { capabilities } => { + // create pointer if applicable + if capabilities.contains(wl_seat::Capability::Pointer) && self.pointer.is_none() { + self.pointer = Some(super::pointer::implement_pointer( + &seat, + self.sink.clone(), + self.store.clone(), + self.modifiers_tracker.clone(), + self.cursor_manager.clone(), + )); + + self.cursor_manager + .lock() + .unwrap() + .register_pointer(self.pointer.as_ref().unwrap().clone()); + + self.relative_pointer = self + .relative_pointer_manager_proxy + .try_borrow() + .unwrap() + .as_ref() + .and_then(|manager| { + super::pointer::implement_relative_pointer( + self.sink.clone(), + self.pointer.as_ref().unwrap(), + manager, + ) + .ok() + }) + } + // destroy pointer if applicable + if !capabilities.contains(wl_seat::Capability::Pointer) { + if let Some(pointer) = self.pointer.take() { + if pointer.as_ref().version() >= 3 { + pointer.release(); + } + } + } + // create keyboard if applicable + if capabilities.contains(wl_seat::Capability::Keyboard) && self.keyboard.is_none() { + self.keyboard = Some(super::keyboard::init_keyboard( + &seat, + self.sink.clone(), + self.modifiers_tracker.clone(), + )) + } + // destroy keyboard if applicable + if !capabilities.contains(wl_seat::Capability::Keyboard) { + if let Some(kbd) = self.keyboard.take() { + if kbd.as_ref().version() >= 3 { + kbd.release(); + } + } + } + // create touch if applicable + if capabilities.contains(wl_seat::Capability::Touch) && self.touch.is_none() { + self.touch = Some(super::touch::implement_touch( + &seat, + self.sink.clone(), + self.store.clone(), + )) + } + // destroy touch if applicable + if !capabilities.contains(wl_seat::Capability::Touch) { + if let Some(touch) = self.touch.take() { + if touch.as_ref().version() >= 3 { + touch.release(); + } + } + } + } + _ => unreachable!(), + } + } +} + +impl Drop for SeatData { + fn drop(&mut self) { + if let Some(pointer) = self.pointer.take() { + if pointer.as_ref().version() >= 3 { + pointer.release(); + } + } + if let Some(kbd) = self.keyboard.take() { + if kbd.as_ref().version() >= 3 { + kbd.release(); + } + } + if let Some(touch) = self.touch.take() { + if touch.as_ref().version() >= 3 { + touch.release(); + } + } + } +} + +/* + * Monitor stuff + */ + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VideoMode { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate: u16, + pub(crate) monitor: MonitorHandle, +} + +impl VideoMode { + #[inline] + pub fn size(&self) -> PhysicalSize { + self.size.into() + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + #[inline] + pub fn refresh_rate(&self) -> u16 { + self.refresh_rate + } + + #[inline] + pub fn monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: PlatformMonitorHandle::Wayland(self.monitor.clone()), + } + } +} + +#[derive(Clone)] +pub struct MonitorHandle { + pub(crate) proxy: wl_output::WlOutput, + pub(crate) mgr: OutputMgr, +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + self.native_identifier() == other.native_identifier() + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(&other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.native_identifier().cmp(&other.native_identifier()) + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash(&self, state: &mut H) { + self.native_identifier().hash(state); + } +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + #[derive(Debug)] + struct MonitorHandle { + name: Option, + native_identifier: u32, + size: PhysicalSize, + position: PhysicalPosition, + scale_factor: i32, + } + + let monitor_id_proxy = MonitorHandle { + name: self.name(), + native_identifier: self.native_identifier(), + size: self.size(), + position: self.position(), + scale_factor: self.scale_factor(), + }; + + monitor_id_proxy.fmt(f) + } +} + +impl MonitorHandle { + pub fn name(&self) -> Option { + self.mgr.with_info(&self.proxy, |_, info| { + format!("{} ({})", info.model, info.make) + }) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + self.mgr.with_info(&self.proxy, |id, _| id).unwrap_or(0) + } + + pub fn size(&self) -> PhysicalSize { + match self.mgr.with_info(&self.proxy, |_, info| { + info.modes + .iter() + .find(|m| m.is_current) + .map(|m| m.dimensions) + }) { + Some(Some((w, h))) => (w as u32, h as u32), + _ => (0, 0), + } + .into() + } + + pub fn position(&self) -> PhysicalPosition { + self.mgr + .with_info(&self.proxy, |_, info| info.location) + .unwrap_or((0, 0)) + .into() + } + + #[inline] + pub fn scale_factor(&self) -> i32 { + self.mgr + .with_info(&self.proxy, |_, info| info.scale_factor) + .unwrap_or(1) + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator { + let monitor = self.clone(); + + self.mgr + .with_info(&self.proxy, |_, info| info.modes.clone()) + .unwrap_or(vec![]) + .into_iter() + .map(move |x| RootVideoMode { + video_mode: PlatformVideoMode::Wayland(VideoMode { + size: (x.dimensions.0 as u32, x.dimensions.1 as u32), + refresh_rate: (x.refresh_rate as f32 / 1000.0).round() as u16, + bit_depth: 32, + monitor: monitor.clone(), + }), + }) + } +} + +pub fn primary_monitor(outputs: &OutputMgr) -> MonitorHandle { + outputs.with_all(|list| { + if let Some(&(_, ref proxy, _)) = list.first() { + MonitorHandle { + proxy: proxy.clone(), + mgr: outputs.clone(), + } + } else { + panic!("No monitor is available.") + } + }) +} + +pub fn available_monitors(outputs: &OutputMgr) -> VecDeque { + outputs.with_all(|list| { + list.iter() + .map(|&(_, ref proxy, _)| MonitorHandle { + proxy: proxy.clone(), + mgr: outputs.clone(), + }) + .collect() + }) +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/keyboard.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/keyboard.rs similarity index 60% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/keyboard.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/keyboard.rs index 1b48712..8f91188 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/keyboard.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/keyboard.rs @@ -1,22 +1,20 @@ use std::sync::{Arc, Mutex}; -use super::{make_wid, DeviceId, EventsLoopProxy, EventsLoopSink}; -use sctk::keyboard::{ - self, map_keyboard_auto_with_repeat, Event as KbEvent, KeyRepeatEvent, KeyRepeatKind, +use super::{event_loop::EventsSink, make_wid, DeviceId}; +use smithay_client_toolkit::{ + keyboard::{ + self, map_keyboard_auto_with_repeat, Event as KbEvent, KeyRepeatEvent, KeyRepeatKind, + }, + reexports::client::protocol::{wl_keyboard, wl_seat}, }; -use sctk::reexports::client::protocol::wl_keyboard; -use sctk::reexports::client::Proxy; -use sctk::reexports::client::protocol::wl_seat; -use sctk::reexports::client::protocol::wl_seat::RequestsTrait as SeatRequests; -use {ElementState, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}; +use crate::event::{ElementState, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}; pub fn init_keyboard( - seat: &Proxy, - sink: Arc>, - events_loop_proxy: EventsLoopProxy, + seat: &wl_seat::WlSeat, + sink: EventsSink, modifiers_tracker: Arc>, -) -> Proxy { +) -> wl_keyboard::WlKeyboard { // { variables to be captured by the closures let target = Arc::new(Mutex::new(None)); let my_sink = sink.clone(); @@ -27,88 +25,113 @@ pub fn init_keyboard( let ret = map_keyboard_auto_with_repeat( seat, KeyRepeatKind::System, - move |evt: KbEvent, _| match evt { - KbEvent::Enter { surface, .. } => { - let wid = make_wid(&surface); - my_sink - .lock() - .unwrap() - .send_event(WindowEvent::Focused(true), wid); - *target.lock().unwrap() = Some(wid); - } - KbEvent::Leave { surface, .. } => { - let wid = make_wid(&surface); - my_sink - .lock() - .unwrap() - .send_event(WindowEvent::Focused(false), wid); - *target.lock().unwrap() = None; - } - KbEvent::Key { - rawkey, - keysym, - state, - utf8, - .. - } => { - if let Some(wid) = *target.lock().unwrap() { - let state = match state { - wl_keyboard::KeyState::Pressed => ElementState::Pressed, - wl_keyboard::KeyState::Released => ElementState::Released, - }; - let vkcode = key_to_vkey(rawkey, keysym); - let mut guard = my_sink.lock().unwrap(); - guard.send_event( - WindowEvent::KeyboardInput { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - input: KeyboardInput { - state: state, - scancode: rawkey, - virtual_keycode: vkcode, - modifiers: modifiers_tracker.lock().unwrap().clone(), - }, - }, - wid, - ); - // send char event only on key press, not release - if let ElementState::Released = state { - return; + move |evt: KbEvent<'_>, _| { + match evt { + KbEvent::Enter { surface, .. } => { + let wid = make_wid(&surface); + my_sink.send_window_event(WindowEvent::Focused(true), wid); + *target.lock().unwrap() = Some(wid); + + let modifiers = *modifiers_tracker.lock().unwrap(); + + if !modifiers.is_empty() { + my_sink.send_window_event(WindowEvent::ModifiersChanged(modifiers), wid); } - if let Some(txt) = utf8 { - for chr in txt.chars() { - guard.send_event(WindowEvent::ReceivedCharacter(chr), wid); + } + KbEvent::Leave { surface, .. } => { + let wid = make_wid(&surface); + let modifiers = *modifiers_tracker.lock().unwrap(); + + if !modifiers.is_empty() { + my_sink.send_window_event( + WindowEvent::ModifiersChanged(ModifiersState::empty()), + wid, + ); + } + + my_sink.send_window_event(WindowEvent::Focused(false), wid); + *target.lock().unwrap() = None; + } + KbEvent::Key { + rawkey, + keysym, + state, + utf8, + .. + } => { + if let Some(wid) = *target.lock().unwrap() { + let state = match state { + wl_keyboard::KeyState::Pressed => ElementState::Pressed, + wl_keyboard::KeyState::Released => ElementState::Released, + _ => unreachable!(), + }; + let vkcode = key_to_vkey(rawkey, keysym); + my_sink.send_window_event( + #[allow(deprecated)] + WindowEvent::KeyboardInput { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + input: KeyboardInput { + state, + scancode: rawkey, + virtual_keycode: vkcode, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + is_synthetic: false, + }, + wid, + ); + // send char event only on key press, not release + if let ElementState::Released = state { + return; + } + if let Some(txt) = utf8 { + for chr in txt.chars() { + my_sink.send_window_event(WindowEvent::ReceivedCharacter(chr), wid); + } } } } - } - KbEvent::RepeatInfo { .. } => { /* Handled by smithay client toolkit */ } - KbEvent::Modifiers { modifiers: event_modifiers } => { - *modifiers_tracker.lock().unwrap() = event_modifiers.into() + KbEvent::RepeatInfo { .. } => { /* Handled by smithay client toolkit */ } + KbEvent::Modifiers { + modifiers: event_modifiers, + } => { + let modifiers = ModifiersState::from_wayland(event_modifiers); + + *modifiers_tracker.lock().unwrap() = modifiers; + + if let Some(wid) = *target.lock().unwrap() { + my_sink.send_window_event(WindowEvent::ModifiersChanged(modifiers), wid); + } + } } }, move |repeat_event: KeyRepeatEvent, _| { if let Some(wid) = *repeat_target.lock().unwrap() { let state = ElementState::Pressed; let vkcode = key_to_vkey(repeat_event.rawkey, repeat_event.keysym); - let mut guard = repeat_sink.lock().unwrap(); - guard.send_event( + repeat_sink.send_window_event( + #[allow(deprecated)] WindowEvent::KeyboardInput { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), + device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland( + DeviceId, + )), input: KeyboardInput { - state: state, + state, scancode: repeat_event.rawkey, virtual_keycode: vkcode, modifiers: my_modifiers.lock().unwrap().clone(), }, + is_synthetic: false, }, wid, ); if let Some(txt) = repeat_event.utf8 { for chr in txt.chars() { - guard.send_event(WindowEvent::ReceivedCharacter(chr), wid); + repeat_sink.send_window_event(WindowEvent::ReceivedCharacter(chr), wid); } } - events_loop_proxy.wakeup().unwrap(); } }, ); @@ -123,51 +146,55 @@ pub fn init_keyboard( // In this case, we don't have the keymap information (it is // supposed to be serialized by the compositor using libxkbcommon) - // { variables to be captured by the closure - let mut target = None; - let my_sink = sink; - // } seat.get_keyboard(|keyboard| { - keyboard.implement(move |evt, _| match evt { - wl_keyboard::Event::Enter { surface, .. } => { - let wid = make_wid(&surface); - my_sink - .lock() - .unwrap() - .send_event(WindowEvent::Focused(true), wid); - target = Some(wid); - } - wl_keyboard::Event::Leave { surface, .. } => { - let wid = make_wid(&surface); - my_sink - .lock() - .unwrap() - .send_event(WindowEvent::Focused(false), wid); - target = None; - } - wl_keyboard::Event::Key { key, state, .. } => { - if let Some(wid) = target { - let state = match state { - wl_keyboard::KeyState::Pressed => ElementState::Pressed, - wl_keyboard::KeyState::Released => ElementState::Released, - }; - my_sink.lock().unwrap().send_event( - WindowEvent::KeyboardInput { - device_id: ::DeviceId(::platform::DeviceId::Wayland(DeviceId)), - input: KeyboardInput { - state: state, - scancode: key, - virtual_keycode: None, - modifiers: ModifiersState::default(), - }, - }, - wid, - ); + // { variables to be captured by the closure + let mut target = None; + let my_sink = sink; + // } + + keyboard.implement_closure( + move |evt, _| match evt { + wl_keyboard::Event::Enter { surface, .. } => { + let wid = make_wid(&surface); + my_sink.send_window_event(WindowEvent::Focused(true), wid); + target = Some(wid); } - } - _ => (), - }, ()) - }).unwrap() + wl_keyboard::Event::Leave { surface, .. } => { + let wid = make_wid(&surface); + my_sink.send_window_event(WindowEvent::Focused(false), wid); + target = None; + } + wl_keyboard::Event::Key { key, state, .. } => { + if let Some(wid) = target { + let state = match state { + wl_keyboard::KeyState::Pressed => ElementState::Pressed, + wl_keyboard::KeyState::Released => ElementState::Released, + _ => unreachable!(), + }; + my_sink.send_window_event( + #[allow(deprecated)] + WindowEvent::KeyboardInput { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + input: KeyboardInput { + state, + scancode: key, + virtual_keycode: None, + modifiers: ModifiersState::default(), + }, + is_synthetic: false, + }, + wid, + ); + } + } + _ => (), + }, + (), + ) + }) + .unwrap() } } } @@ -190,7 +217,7 @@ fn key_to_vkey(rawkey: u32, keysym: u32) -> Option { } fn keysym_to_vkey(keysym: u32) -> Option { - use sctk::keyboard::keysyms; + use smithay_client_toolkit::keyboard::keysyms; match keysym { // letters keysyms::XKB_KEY_A | keysyms::XKB_KEY_a => Some(VirtualKeyCode::A), @@ -312,6 +339,13 @@ fn keysym_to_vkey(keysym: u32) -> Option { keysyms::XKB_KEY_KP_Separator => Some(VirtualKeyCode::NumpadComma), keysyms::XKB_KEY_KP_Enter => Some(VirtualKeyCode::NumpadEnter), keysyms::XKB_KEY_KP_Equal => Some(VirtualKeyCode::NumpadEquals), + keysyms::XKB_KEY_KP_Add => Some(VirtualKeyCode::Add), + keysyms::XKB_KEY_KP_Subtract => Some(VirtualKeyCode::Subtract), + keysyms::XKB_KEY_KP_Divide => Some(VirtualKeyCode::Divide), + keysyms::XKB_KEY_KP_Page_Up => Some(VirtualKeyCode::PageUp), + keysyms::XKB_KEY_KP_Page_Down => Some(VirtualKeyCode::PageDown), + keysyms::XKB_KEY_KP_Home => Some(VirtualKeyCode::Home), + keysyms::XKB_KEY_KP_End => Some(VirtualKeyCode::End), // => Some(VirtualKeyCode::OEM102), // => Some(VirtualKeyCode::Period), // => Some(VirtualKeyCode::Playpause), @@ -351,13 +385,13 @@ fn keysym_to_vkey(keysym: u32) -> Option { } } -impl From for ModifiersState { - fn from(mods: keyboard::ModifiersState) -> ModifiersState { - ModifiersState { - shift: mods.shift, - ctrl: mods.ctrl, - alt: mods.alt, - logo: mods.logo, - } +impl ModifiersState { + pub(crate) fn from_wayland(mods: keyboard::ModifiersState) -> ModifiersState { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, mods.shift); + m.set(ModifiersState::CTRL, mods.ctrl); + m.set(ModifiersState::ALT, mods.alt); + m.set(ModifiersState::LOGO, mods.logo); + m } } diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/mod.rs similarity index 65% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/mod.rs index 659cb7a..7fdb3fd 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/wayland/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/mod.rs @@ -1,16 +1,17 @@ #![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] -pub use self::window::Window; -pub use self::event_loop::{EventsLoop, EventsLoopProxy, EventsLoopSink, MonitorId}; +pub use self::{ + event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget, MonitorHandle, VideoMode}, + window::Window, +}; -use sctk::reexports::client::protocol::wl_surface; -use sctk::reexports::client::Proxy; +use smithay_client_toolkit::reexports::client::protocol::wl_surface; mod event_loop; +mod keyboard; mod pointer; mod touch; -mod keyboard; mod window; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -32,6 +33,6 @@ impl WindowId { } #[inline] -fn make_wid(s: &Proxy) -> WindowId { - WindowId(s.c_ptr() as usize) +fn make_wid(s: &wl_surface::WlSurface) -> WindowId { + WindowId(s.as_ref().c_ptr() as usize) } diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/pointer.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/pointer.rs new file mode 100644 index 0000000..5f93099 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/pointer.rs @@ -0,0 +1,289 @@ +use std::sync::{Arc, Mutex}; + +use crate::dpi::LogicalPosition; +use crate::event::{ + DeviceEvent, ElementState, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase, + WindowEvent, +}; + +use super::{ + event_loop::{CursorManager, EventsSink}, + make_wid, + window::WindowStore, + DeviceId, +}; + +use smithay_client_toolkit::surface; + +use smithay_client_toolkit::reexports::client::protocol::{ + wl_pointer::{self, Event as PtrEvent, WlPointer}, + wl_seat, +}; + +use smithay_client_toolkit::reexports::protocols::unstable::relative_pointer::v1::client::{ + zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, zwp_relative_pointer_v1::Event, + zwp_relative_pointer_v1::ZwpRelativePointerV1, +}; + +use smithay_client_toolkit::reexports::protocols::unstable::pointer_constraints::v1::client::{ + zwp_locked_pointer_v1::ZwpLockedPointerV1, zwp_pointer_constraints_v1::Lifetime, + zwp_pointer_constraints_v1::ZwpPointerConstraintsV1, +}; + +use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface; + +pub fn implement_pointer( + seat: &wl_seat::WlSeat, + sink: EventsSink, + store: Arc>, + modifiers_tracker: Arc>, + cursor_manager: Arc>, +) -> WlPointer { + seat.get_pointer(|pointer| { + // Currently focused winit surface + let mut mouse_focus = None; + let mut axis_buffer = None; + let mut axis_discrete_buffer = None; + let mut axis_state = TouchPhase::Ended; + + pointer.implement_closure( + move |evt, pointer| { + let store = store.lock().unwrap(); + let mut cursor_manager = cursor_manager.lock().unwrap(); + match evt { + PtrEvent::Enter { + surface, + surface_x, + surface_y, + .. + } => { + let wid = store.find_wid(&surface); + + if let Some(wid) = wid { + let scale_factor = surface::get_dpi_factor(&surface) as f64; + mouse_focus = Some(surface); + + // Reload cursor style only when we enter winit's surface. Calling + // this function every time on `PtrEvent::Enter` could interfere with + // SCTK CSD handling, since it changes cursor icons when you hover + // cursor over the window borders. + cursor_manager.reload_cursor_style(); + + sink.send_window_event( + WindowEvent::CursorEntered { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + }, + wid, + ); + + let position = LogicalPosition::new(surface_x, surface_y) + .to_physical(scale_factor); + + sink.send_window_event( + WindowEvent::CursorMoved { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + position, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + wid, + ); + } + } + PtrEvent::Leave { surface, .. } => { + mouse_focus = None; + let wid = store.find_wid(&surface); + if let Some(wid) = wid { + sink.send_window_event( + WindowEvent::CursorLeft { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + }, + wid, + ); + } + } + PtrEvent::Motion { + surface_x, + surface_y, + .. + } => { + if let Some(surface) = mouse_focus.as_ref() { + let wid = make_wid(surface); + + let scale_factor = surface::get_dpi_factor(&surface) as f64; + let position = LogicalPosition::new(surface_x, surface_y) + .to_physical(scale_factor); + + sink.send_window_event( + WindowEvent::CursorMoved { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + position, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + wid, + ); + } + } + PtrEvent::Button { button, state, .. } => { + if let Some(surface) = mouse_focus.as_ref() { + let state = match state { + wl_pointer::ButtonState::Pressed => ElementState::Pressed, + wl_pointer::ButtonState::Released => ElementState::Released, + _ => unreachable!(), + }; + let button = match button { + 0x110 => MouseButton::Left, + 0x111 => MouseButton::Right, + 0x112 => MouseButton::Middle, + // TODO figure out the translation ? + _ => return, + }; + sink.send_window_event( + WindowEvent::MouseInput { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + state, + button, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + make_wid(surface), + ); + } + } + PtrEvent::Axis { axis, value, .. } => { + if let Some(surface) = mouse_focus.as_ref() { + let wid = make_wid(surface); + if pointer.as_ref().version() < 5 { + let (mut x, mut y) = (0.0, 0.0); + // old seat compatibility + match axis { + // wayland vertical sign convention is the inverse of winit + wl_pointer::Axis::VerticalScroll => y -= value as f32, + wl_pointer::Axis::HorizontalScroll => x += value as f32, + _ => unreachable!(), + } + sink.send_window_event( + WindowEvent::MouseWheel { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + delta: MouseScrollDelta::PixelDelta( + (x as f64, y as f64).into(), + ), + phase: TouchPhase::Moved, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + wid, + ); + } else { + let (mut x, mut y) = axis_buffer.unwrap_or((0.0, 0.0)); + match axis { + // wayland vertical sign convention is the inverse of winit + wl_pointer::Axis::VerticalScroll => y -= value as f32, + wl_pointer::Axis::HorizontalScroll => x += value as f32, + _ => unreachable!(), + } + axis_buffer = Some((x, y)); + axis_state = match axis_state { + TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved, + _ => TouchPhase::Started, + } + } + } + } + PtrEvent::Frame => { + let axis_buffer = axis_buffer.take(); + let axis_discrete_buffer = axis_discrete_buffer.take(); + if let Some(surface) = mouse_focus.as_ref() { + let wid = make_wid(surface); + if let Some((x, y)) = axis_discrete_buffer { + sink.send_window_event( + WindowEvent::MouseWheel { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + delta: MouseScrollDelta::LineDelta(x as f32, y as f32), + phase: axis_state, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + wid, + ); + } else if let Some((x, y)) = axis_buffer { + sink.send_window_event( + WindowEvent::MouseWheel { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + delta: MouseScrollDelta::PixelDelta( + (x as f64, y as f64).into(), + ), + phase: axis_state, + modifiers: modifiers_tracker.lock().unwrap().clone(), + }, + wid, + ); + } + } + } + PtrEvent::AxisSource { .. } => (), + PtrEvent::AxisStop { .. } => { + axis_state = TouchPhase::Ended; + } + PtrEvent::AxisDiscrete { axis, discrete } => { + let (mut x, mut y) = axis_discrete_buffer.unwrap_or((0, 0)); + match axis { + // wayland vertical sign convention is the inverse of winit + wl_pointer::Axis::VerticalScroll => y -= discrete, + wl_pointer::Axis::HorizontalScroll => x += discrete, + _ => unreachable!(), + } + axis_discrete_buffer = Some((x, y)); + axis_state = match axis_state { + TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved, + _ => TouchPhase::Started, + } + } + _ => unreachable!(), + } + }, + (), + ) + }) + .unwrap() +} + +pub fn implement_relative_pointer( + sink: EventsSink, + pointer: &WlPointer, + manager: &ZwpRelativePointerManagerV1, +) -> Result { + manager.get_relative_pointer(pointer, |rel_pointer| { + rel_pointer.implement_closure( + move |evt, _rel_pointer| match evt { + Event::RelativeMotion { dx, dy, .. } => { + sink.send_device_event(DeviceEvent::MouseMotion { delta: (dx, dy) }, DeviceId) + } + _ => unreachable!(), + }, + (), + ) + }) +} + +pub fn implement_locked_pointer( + surface: &WlSurface, + pointer: &WlPointer, + constraints: &ZwpPointerConstraintsV1, +) -> Result { + constraints.lock_pointer(surface, pointer, None, Lifetime::Persistent.to_raw(), |c| { + c.implement_closure(|_, _| (), ()) + }) +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/touch.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/touch.rs new file mode 100644 index 0000000..ce4e32c --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/touch.rs @@ -0,0 +1,132 @@ +use std::sync::{Arc, Mutex}; + +use crate::dpi::LogicalPosition; +use crate::event::{TouchPhase, WindowEvent}; + +use super::{event_loop::EventsSink, make_wid, window::WindowStore, DeviceId}; + +use smithay_client_toolkit::surface; + +use smithay_client_toolkit::reexports::client::protocol::{ + wl_seat, + wl_surface::WlSurface, + wl_touch::{Event as TouchEvent, WlTouch}, +}; + +// location is in logical coordinates. +struct TouchPoint { + surface: WlSurface, + position: LogicalPosition, + id: i32, +} + +pub(crate) fn implement_touch( + seat: &wl_seat::WlSeat, + sink: EventsSink, + store: Arc>, +) -> WlTouch { + let mut pending_ids = Vec::new(); + seat.get_touch(|touch| { + touch.implement_closure( + move |evt, _| { + let store = store.lock().unwrap(); + match evt { + TouchEvent::Down { + surface, id, x, y, .. + } => { + let wid = store.find_wid(&surface); + if let Some(wid) = wid { + let scale_factor = surface::get_dpi_factor(&surface) as f64; + let position = LogicalPosition::new(x, y); + + sink.send_window_event( + WindowEvent::Touch(crate::event::Touch { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + phase: TouchPhase::Started, + location: position.to_physical(scale_factor), + force: None, // TODO + id: id as u64, + }), + wid, + ); + pending_ids.push(TouchPoint { + surface, + position, + id, + }); + } + } + TouchEvent::Up { id, .. } => { + let idx = pending_ids.iter().position(|p| p.id == id); + if let Some(idx) = idx { + let pt = pending_ids.remove(idx); + + let scale_factor = surface::get_dpi_factor(&pt.surface) as f64; + let location = pt.position.to_physical(scale_factor); + + sink.send_window_event( + WindowEvent::Touch(crate::event::Touch { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + phase: TouchPhase::Ended, + location, + force: None, // TODO + id: id as u64, + }), + make_wid(&pt.surface), + ); + } + } + TouchEvent::Motion { id, x, y, .. } => { + let pt = pending_ids.iter_mut().find(|p| p.id == id); + if let Some(pt) = pt { + pt.position = LogicalPosition::new(x, y); + + let scale_factor = surface::get_dpi_factor(&pt.surface) as f64; + let location = pt.position.to_physical(scale_factor); + + sink.send_window_event( + WindowEvent::Touch(crate::event::Touch { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + phase: TouchPhase::Moved, + location, + force: None, // TODO + id: id as u64, + }), + make_wid(&pt.surface), + ); + } + } + TouchEvent::Frame => (), + TouchEvent::Cancel => { + for pt in pending_ids.drain(..) { + let scale_factor = surface::get_dpi_factor(&pt.surface) as f64; + let location = pt.position.to_physical(scale_factor); + + sink.send_window_event( + WindowEvent::Touch(crate::event::Touch { + device_id: crate::event::DeviceId( + crate::platform_impl::DeviceId::Wayland(DeviceId), + ), + phase: TouchPhase::Cancelled, + location, + force: None, // TODO + id: pt.id as u64, + }), + make_wid(&pt.surface), + ); + } + } + _ => unreachable!(), + } + }, + (), + ) + }) + .unwrap() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/window.rs new file mode 100644 index 0000000..7c30a79 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/wayland/window.rs @@ -0,0 +1,555 @@ +use raw_window_handle::unix::WaylandHandle; +use std::{ + collections::VecDeque, + mem::replace, + sync::{Arc, Mutex, Weak}, +}; + +use crate::{ + dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + monitor::MonitorHandle as RootMonitorHandle, + platform_impl::{ + platform::wayland::event_loop::{available_monitors, primary_monitor}, + MonitorHandle as PlatformMonitorHandle, + PlatformSpecificWindowBuilderAttributes as PlAttributes, + }, + window::{CursorIcon, Fullscreen, WindowAttributes}, +}; + +use smithay_client_toolkit::{ + output::OutputMgr, + reexports::client::{ + protocol::{wl_seat, wl_surface}, + Display, + }, + surface::{get_dpi_factor, get_outputs}, + window::{ConceptFrame, Event as WEvent, State as WState, Theme, Window as SWindow}, +}; + +use super::{event_loop::CursorManager, make_wid, EventLoopWindowTarget, MonitorHandle, WindowId}; + +pub struct Window { + surface: wl_surface::WlSurface, + frame: Arc>>, + cursor_manager: Arc>, + outputs: OutputMgr, // Access to info for all monitors + size: Arc>, + kill_switch: (Arc>, Arc>), + display: Arc, + need_frame_refresh: Arc>, + need_refresh: Arc>, + fullscreen: Arc>, + cursor_grab_changed: Arc>>, // Update grab state + decorated: Arc>, +} + +#[derive(Clone, Copy, Debug)] +pub enum DecorationsAction { + Hide, + Show, +} + +impl Window { + pub fn new( + evlp: &EventLoopWindowTarget, + attributes: WindowAttributes, + pl_attribs: PlAttributes, + ) -> Result { + // Create the surface first to get initial DPI + let window_store = evlp.store.clone(); + let cursor_manager = evlp.cursor_manager.clone(); + let surface = evlp.env.create_surface(move |dpi, surface| { + window_store.lock().unwrap().dpi_change(&surface, dpi); + surface.set_buffer_scale(dpi); + }); + + let dpi = get_dpi_factor(&surface) as f64; + let (width, height) = attributes + .inner_size + .map(|size| size.to_logical::(dpi).into()) + .unwrap_or((800, 600)); + + // Create the window + let size = Arc::new(Mutex::new((width, height))); + let fullscreen = Arc::new(Mutex::new(false)); + + let window_store = evlp.store.clone(); + + let decorated = Arc::new(Mutex::new(attributes.decorations)); + let pending_decorations_action = Arc::new(Mutex::new(None)); + + let my_surface = surface.clone(); + let mut frame = SWindow::::init_from_env( + &evlp.env, + surface.clone(), + (width, height), + move |event| match event { + WEvent::Configure { new_size, states } => { + let mut store = window_store.lock().unwrap(); + let is_fullscreen = states.contains(&WState::Fullscreen); + + for window in &mut store.windows { + if window.surface.as_ref().equals(&my_surface.as_ref()) { + window.newsize = new_size; + *(window.need_refresh.lock().unwrap()) = true; + { + // Get whether we're in fullscreen + let mut fullscreen = window.fullscreen.lock().unwrap(); + // Fullscreen state was changed, so update decorations + if *fullscreen != is_fullscreen { + let decorated = { *window.decorated.lock().unwrap() }; + if decorated { + *window.pending_decorations_action.lock().unwrap() = + if is_fullscreen { + Some(DecorationsAction::Hide) + } else { + Some(DecorationsAction::Show) + }; + } + } + *fullscreen = is_fullscreen; + } + *(window.need_frame_refresh.lock().unwrap()) = true; + return; + } + } + } + WEvent::Refresh => { + let store = window_store.lock().unwrap(); + for window in &store.windows { + if window.surface.as_ref().equals(&my_surface.as_ref()) { + *(window.need_frame_refresh.lock().unwrap()) = true; + return; + } + } + } + WEvent::Close => { + let mut store = window_store.lock().unwrap(); + for window in &mut store.windows { + if window.surface.as_ref().equals(&my_surface.as_ref()) { + window.closed = true; + return; + } + } + } + }, + ) + .unwrap(); + + if let Some(app_id) = pl_attribs.app_id { + frame.set_app_id(app_id); + } + + for &(_, ref seat) in evlp.seats.lock().unwrap().iter() { + frame.new_seat(seat); + } + + // Check for fullscreen requirements + match attributes.fullscreen { + Some(Fullscreen::Exclusive(_)) => { + panic!("Wayland doesn't support exclusive fullscreen") + } + Some(Fullscreen::Borderless(RootMonitorHandle { + inner: PlatformMonitorHandle::Wayland(ref monitor_id), + })) => frame.set_fullscreen(Some(&monitor_id.proxy)), + Some(Fullscreen::Borderless(_)) => unreachable!(), + None => { + if attributes.maximized { + frame.set_maximized(); + } + } + } + + frame.set_resizable(attributes.resizable); + + // set decorations + frame.set_decorate(attributes.decorations); + + // set title + frame.set_title(attributes.title); + + // min-max dimensions + frame.set_min_size( + attributes + .min_inner_size + .map(|size| size.to_logical::(dpi).into()), + ); + frame.set_max_size( + attributes + .max_inner_size + .map(|size| size.to_logical::(dpi).into()), + ); + + let kill_switch = Arc::new(Mutex::new(false)); + let need_frame_refresh = Arc::new(Mutex::new(true)); + let frame = Arc::new(Mutex::new(frame)); + let need_refresh = Arc::new(Mutex::new(true)); + let cursor_grab_changed = Arc::new(Mutex::new(None)); + + evlp.store.lock().unwrap().windows.push(InternalWindow { + closed: false, + newsize: None, + size: size.clone(), + need_refresh: need_refresh.clone(), + fullscreen: fullscreen.clone(), + cursor_grab_changed: cursor_grab_changed.clone(), + need_frame_refresh: need_frame_refresh.clone(), + surface: surface.clone(), + kill_switch: kill_switch.clone(), + frame: Arc::downgrade(&frame), + current_dpi: 1, + new_dpi: None, + decorated: decorated.clone(), + pending_decorations_action: pending_decorations_action.clone(), + }); + evlp.evq.borrow_mut().sync_roundtrip().unwrap(); + + Ok(Window { + display: evlp.display.clone(), + surface, + frame, + outputs: evlp.env.outputs.clone(), + size, + kill_switch: (kill_switch, evlp.cleanup_needed.clone()), + need_frame_refresh, + need_refresh, + cursor_manager, + fullscreen, + cursor_grab_changed, + decorated, + }) + } + + #[inline] + pub fn id(&self) -> WindowId { + make_wid(&self.surface) + } + + pub fn set_title(&self, title: &str) { + self.frame.lock().unwrap().set_title(title.into()); + } + + pub fn set_visible(&self, _visible: bool) { + // TODO + } + + #[inline] + pub fn outer_position(&self) -> Result, NotSupportedError> { + Err(NotSupportedError::new()) + } + + #[inline] + pub fn inner_position(&self) -> Result, NotSupportedError> { + Err(NotSupportedError::new()) + } + + #[inline] + pub fn set_outer_position(&self, _pos: Position) { + // Not possible with wayland + } + + pub fn inner_size(&self) -> PhysicalSize { + let dpi = self.scale_factor() as f64; + let size = LogicalSize::::from(*self.size.lock().unwrap()); + size.to_physical(dpi) + } + + pub fn request_redraw(&self) { + *self.need_refresh.lock().unwrap() = true; + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + let dpi = self.scale_factor() as f64; + let (w, h) = self.size.lock().unwrap().clone(); + // let (w, h) = super::wayland_window::add_borders(w as i32, h as i32); + let size = LogicalSize::::from((w, h)); + size.to_physical(dpi) + } + + #[inline] + // NOTE: This will only resize the borders, the contents must be updated by the user + pub fn set_inner_size(&self, size: Size) { + let dpi = self.scale_factor() as f64; + let (w, h) = size.to_logical::(dpi).into(); + self.frame.lock().unwrap().resize(w, h); + *(self.size.lock().unwrap()) = (w, h); + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option) { + let dpi = self.scale_factor() as f64; + self.frame + .lock() + .unwrap() + .set_min_size(dimensions.map(|dim| dim.to_logical::(dpi).into())); + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option) { + let dpi = self.scale_factor() as f64; + self.frame + .lock() + .unwrap() + .set_max_size(dimensions.map(|dim| dim.to_logical::(dpi).into())); + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + self.frame.lock().unwrap().set_resizable(resizable); + } + + #[inline] + pub fn scale_factor(&self) -> i32 { + get_dpi_factor(&self.surface) + } + + pub fn set_decorations(&self, decorate: bool) { + *(self.decorated.lock().unwrap()) = decorate; + self.frame.lock().unwrap().set_decorate(decorate); + *(self.need_frame_refresh.lock().unwrap()) = true; + } + + pub fn set_minimized(&self, minimized: bool) { + // An app cannot un-minimize itself on Wayland + if minimized { + self.frame.lock().unwrap().set_minimized(); + } + } + + pub fn set_maximized(&self, maximized: bool) { + if maximized { + self.frame.lock().unwrap().set_maximized(); + } else { + self.frame.lock().unwrap().unset_maximized(); + } + } + + pub fn fullscreen(&self) -> Option { + if *(self.fullscreen.lock().unwrap()) { + Some(Fullscreen::Borderless(RootMonitorHandle { + inner: PlatformMonitorHandle::Wayland(self.current_monitor()), + })) + } else { + None + } + } + + pub fn set_fullscreen(&self, fullscreen: Option) { + match fullscreen { + Some(Fullscreen::Exclusive(_)) => { + panic!("Wayland doesn't support exclusive fullscreen") + } + Some(Fullscreen::Borderless(RootMonitorHandle { + inner: PlatformMonitorHandle::Wayland(ref monitor_id), + })) => { + self.frame + .lock() + .unwrap() + .set_fullscreen(Some(&monitor_id.proxy)); + } + Some(Fullscreen::Borderless(_)) => unreachable!(), + None => self.frame.lock().unwrap().unset_fullscreen(), + } + } + + pub fn set_theme(&self, theme: T) { + self.frame.lock().unwrap().set_theme(theme) + } + + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + let mut cursor_manager = self.cursor_manager.lock().unwrap(); + cursor_manager.set_cursor_icon(cursor); + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let mut cursor_manager = self.cursor_manager.lock().unwrap(); + cursor_manager.set_cursor_visible(visible); + } + + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + *self.cursor_grab_changed.lock().unwrap() = Some(grab); + Ok(()) + } + + #[inline] + pub fn set_cursor_position(&self, _pos: Position) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn display(&self) -> &Display { + &*self.display + } + + pub fn surface(&self) -> &wl_surface::WlSurface { + &self.surface + } + + pub fn current_monitor(&self) -> MonitorHandle { + let output = get_outputs(&self.surface).last().unwrap().clone(); + MonitorHandle { + proxy: output, + mgr: self.outputs.clone(), + } + } + + pub fn available_monitors(&self) -> VecDeque { + available_monitors(&self.outputs) + } + + pub fn primary_monitor(&self) -> MonitorHandle { + primary_monitor(&self.outputs) + } + + pub fn raw_window_handle(&self) -> WaylandHandle { + WaylandHandle { + surface: self.surface().as_ref().c_ptr() as *mut _, + display: self.display().as_ref().c_ptr() as *mut _, + ..WaylandHandle::empty() + } + } +} + +impl Drop for Window { + fn drop(&mut self) { + *(self.kill_switch.0.lock().unwrap()) = true; + *(self.kill_switch.1.lock().unwrap()) = true; + } +} + +/* + * Internal store for windows + */ + +struct InternalWindow { + surface: wl_surface::WlSurface, + // TODO: CONVERT TO LogicalSizes + newsize: Option<(u32, u32)>, + size: Arc>, + need_refresh: Arc>, + fullscreen: Arc>, + need_frame_refresh: Arc>, + cursor_grab_changed: Arc>>, + closed: bool, + kill_switch: Arc>, + frame: Weak>>, + current_dpi: i32, + new_dpi: Option, + decorated: Arc>, + pending_decorations_action: Arc>>, +} + +pub struct WindowStore { + windows: Vec, +} + +pub struct WindowStoreForEach<'a> { + pub newsize: Option<(u32, u32)>, + pub size: &'a mut (u32, u32), + pub prev_dpi: i32, + pub new_dpi: Option, + pub closed: bool, + pub grab_cursor: Option, + pub surface: &'a wl_surface::WlSurface, + pub wid: WindowId, + pub frame: Option<&'a mut SWindow>, + pub decorations_action: Option, +} + +impl WindowStore { + pub fn new() -> WindowStore { + WindowStore { + windows: Vec::new(), + } + } + + pub fn find_wid(&self, surface: &wl_surface::WlSurface) -> Option { + for window in &self.windows { + if surface.as_ref().equals(&window.surface.as_ref()) { + return Some(make_wid(surface)); + } + } + None + } + + pub fn cleanup(&mut self) -> Vec { + let mut pruned = Vec::new(); + self.windows.retain(|w| { + if *w.kill_switch.lock().unwrap() { + // window is dead, cleanup + pruned.push(make_wid(&w.surface)); + w.surface.destroy(); + false + } else { + true + } + }); + pruned + } + + pub fn new_seat(&self, seat: &wl_seat::WlSeat) { + for window in &self.windows { + if let Some(w) = window.frame.upgrade() { + w.lock().unwrap().new_seat(seat); + } + } + } + + fn dpi_change(&mut self, surface: &wl_surface::WlSurface, new: i32) { + for window in &mut self.windows { + if surface.as_ref().equals(&window.surface.as_ref()) { + window.new_dpi = Some(new); + } + } + } + + pub fn for_each(&mut self, mut f: F) + where + F: FnMut(WindowStoreForEach<'_>), + { + for window in &mut self.windows { + let opt_arc = window.frame.upgrade(); + let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap()); + let mut size = { *window.size.lock().unwrap() }; + let decorations_action = { window.pending_decorations_action.lock().unwrap().take() }; + f(WindowStoreForEach { + newsize: window.newsize.take(), + size: &mut size, + prev_dpi: window.current_dpi, + new_dpi: window.new_dpi, + closed: window.closed, + grab_cursor: window.cursor_grab_changed.lock().unwrap().take(), + surface: &window.surface, + wid: make_wid(&window.surface), + frame: opt_mutex_lock.as_mut().map(|m| &mut **m), + decorations_action, + }); + *window.size.lock().unwrap() = size; + if let Some(dpi) = window.new_dpi.take() { + window.current_dpi = dpi; + } + // avoid re-spamming the event + window.closed = false; + } + } + + pub fn for_each_redraw_trigger(&mut self, mut f: F) + where + F: FnMut(bool, bool, WindowId, Option<&mut SWindow>), + { + for window in &mut self.windows { + let opt_arc = window.frame.upgrade(); + let mut opt_mutex_lock = opt_arc.as_ref().map(|m| m.lock().unwrap()); + f( + replace(&mut *window.need_refresh.lock().unwrap(), false), + replace(&mut *window.need_frame_refresh.lock().unwrap(), false), + make_wid(&window.surface), + opt_mutex_lock.as_mut().map(|m| &mut **m), + ); + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/dnd.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/dnd.rs similarity index 87% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/dnd.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/dnd.rs index c8221fb..997228c 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/dnd.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/dnd.rs @@ -1,8 +1,10 @@ -use std::io; -use std::sync::Arc; -use std::path::{Path, PathBuf}; -use std::str::Utf8Error; -use std::os::raw::*; +use std::{ + io, + os::raw::*, + path::{Path, PathBuf}, + str::Utf8Error, + sync::Arc, +}; use percent_encoding::percent_decode; @@ -127,13 +129,15 @@ impl Dnd { DndState::Accepted => (1, self.atoms.action_private as c_long), DndState::Rejected => (0, self.atoms.none as c_long), }; - self.xconn.send_client_msg( - target_window, - target_window, - self.atoms.status, - None, - [this_window as c_long, accepted, 0, 0, action], - ).flush() + self.xconn + .send_client_msg( + target_window, + target_window, + self.atoms.status, + None, + [this_window as c_long, accepted, 0, 0, action], + ) + .flush() } pub unsafe fn send_finished( @@ -146,24 +150,23 @@ impl Dnd { DndState::Accepted => (1, self.atoms.action_private as c_long), DndState::Rejected => (0, self.atoms.none as c_long), }; - self.xconn.send_client_msg( - target_window, - target_window, - self.atoms.finished, - None, - [this_window as c_long, accepted, action, 0, 0], - ).flush() + self.xconn + .send_client_msg( + target_window, + target_window, + self.atoms.finished, + None, + [this_window as c_long, accepted, action, 0, 0], + ) + .flush() } pub unsafe fn get_type_list( &self, source_window: c_ulong, ) -> Result, util::GetPropertyError> { - self.xconn.get_property( - source_window, - self.atoms.type_list, - ffi::XA_ATOM, - ) + self.xconn + .get_property(source_window, self.atoms.type_list, ffi::XA_ATOM) } pub unsafe fn convert_selection(&self, window: c_ulong, time: c_ulong) { @@ -181,11 +184,8 @@ impl Dnd { &self, window: c_ulong, ) -> Result, util::GetPropertyError> { - self.xconn.get_property( - window, - self.atoms.selection, - self.atoms.uri_list, - ) + self.xconn + .get_property(window, self.atoms.selection, self.atoms.uri_list) } pub fn parse_data(&self, data: &mut Vec) -> Result, DndDataParseError> { diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/event_processor.rs similarity index 51% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/event_processor.rs index 3171289..976c17b 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/event_processor.rs @@ -1,255 +1,173 @@ -#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] +use std::{cell::RefCell, collections::HashMap, rc::Rc, slice, sync::Arc}; -pub mod ffi; -mod events; -mod monitor; -mod window; -mod xdisplay; -mod dnd; -mod ime; -pub mod util; +use libc::{c_char, c_int, c_long, c_uint, c_ulong}; -pub use self::monitor::MonitorId; -pub use self::window::UnownedWindow; -pub use self::xdisplay::{XConnection, XNotSupported, XError}; +use parking_lot::MutexGuard; -use std::{mem, ptr, slice}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::ffi::CStr; -use std::ops::Deref; -use std::os::raw::*; -use std::sync::{Arc, mpsc, Weak}; -use std::sync::atomic::{self, AtomicBool}; - -use libc::{self, setlocale, LC_CTYPE}; - -use { - ControlFlow, - CreationError, - DeviceEvent, - Event, - EventsLoopClosed, - KeyboardInput, - LogicalPosition, - LogicalSize, - WindowAttributes, - WindowEvent, +use super::{ + events, ffi, get_xtarget, mkdid, mkwid, monitor, util, Device, DeviceId, DeviceInfo, Dnd, + DndState, GenericEventCookie, ImeReceiver, ScrollOrientation, UnownedWindow, WindowId, + XExtension, }; -use events::ModifiersState; -use platform::PlatformSpecificWindowBuilderAttributes; -use self::dnd::{Dnd, DndState}; -use self::ime::{ImeReceiver, ImeSender, ImeCreationError, Ime}; -pub struct EventsLoop { - xconn: Arc, - wm_delete_window: ffi::Atom, - dnd: Dnd, - ime_receiver: ImeReceiver, - ime_sender: ImeSender, - ime: RefCell, - randr_event_offset: c_int, - windows: RefCell>>, - devices: RefCell>, - xi2ext: XExtension, - pending_wakeup: Arc, - root: ffi::Window, - // A dummy, `InputOnly` window that we can use to receive wakeup events and interrupt blocking - // `XNextEvent` calls. - wakeup_dummy_window: ffi::Window, +use util::modifiers::{ModifierKeyState, ModifierKeymap}; + +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + event::{ + DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, TouchPhase, WindowEvent, + }, + event_loop::EventLoopWindowTarget as RootELW, +}; + +pub(super) struct EventProcessor { + pub(super) dnd: Dnd, + pub(super) ime_receiver: ImeReceiver, + pub(super) randr_event_offset: c_int, + pub(super) devices: RefCell>, + pub(super) xi2ext: XExtension, + pub(super) target: Rc>, + pub(super) mod_keymap: ModifierKeymap, + pub(super) device_mod_state: ModifierKeyState, + // Number of touch events currently in progress + pub(super) num_touch: u32, + pub(super) first_touch: Option, + // Currently focused window belonging to this process + pub(super) active_window: Option, } -#[derive(Clone)] -pub struct EventsLoopProxy { - pending_wakeup: Weak, - xconn: Weak, - wakeup_dummy_window: ffi::Window, -} - -impl EventsLoop { - pub fn new(xconn: Arc) -> EventsLoop { - let root = unsafe { (xconn.xlib.XDefaultRootWindow)(xconn.display) }; - - let wm_delete_window = unsafe { xconn.get_atom_unchecked(b"WM_DELETE_WINDOW\0") }; - - let dnd = Dnd::new(Arc::clone(&xconn)) - .expect("Failed to call XInternAtoms when initializing drag and drop"); - - let (ime_sender, ime_receiver) = mpsc::channel(); - // Input methods will open successfully without setting the locale, but it won't be - // possible to actually commit pre-edit sequences. - unsafe { setlocale(LC_CTYPE, b"\0".as_ptr() as *const _); } - let ime = RefCell::new({ - let result = Ime::new(Arc::clone(&xconn)); - if let Err(ImeCreationError::OpenFailure(ref state)) = result { - panic!(format!("Failed to open input method: {:#?}", state)); - } - result.expect("Failed to set input method destruction callback") - }); - - let randr_event_offset = xconn.select_xrandr_input(root) - .expect("Failed to query XRandR extension"); - - let xi2ext = unsafe { - let mut result = XExtension { - opcode: mem::uninitialized(), - first_event_id: mem::uninitialized(), - first_error_id: mem::uninitialized(), - }; - let res = (xconn.xlib.XQueryExtension)( - xconn.display, - b"XInputExtension\0".as_ptr() as *const c_char, - &mut result.opcode as *mut c_int, - &mut result.first_event_id as *mut c_int, - &mut result.first_error_id as *mut c_int); - if res == ffi::False { - panic!("X server missing XInput extension"); - } - result - }; - - unsafe { - let mut xinput_major_ver = ffi::XI_2_Major; - let mut xinput_minor_ver = ffi::XI_2_Minor; - if (xconn.xinput2.XIQueryVersion)( - xconn.display, - &mut xinput_major_ver, - &mut xinput_minor_ver, - ) != ffi::Success as libc::c_int { - panic!( - "X server has XInput extension {}.{} but does not support XInput2", - xinput_major_ver, - xinput_minor_ver, - ); +impl EventProcessor { + pub(super) fn init_device(&self, device: c_int) { + let wt = get_xtarget(&self.target); + let mut devices = self.devices.borrow_mut(); + if let Some(info) = DeviceInfo::get(&wt.xconn, device) { + for info in info.iter() { + devices.insert(DeviceId(info.deviceid), Device::new(&self, info)); } } + } - xconn.update_cached_wm_info(root); - - let wakeup_dummy_window = unsafe { - let (x, y, w, h) = (10, 10, 10, 10); - let (border_w, border_px, background_px) = (0, 0, 0); - (xconn.xlib.XCreateSimpleWindow)( - xconn.display, - root, - x, - y, - w, - h, - border_w, - border_px, - background_px, - ) - }; - - let result = EventsLoop { - xconn, - wm_delete_window, - dnd, - ime_receiver, - ime_sender, - ime, - randr_event_offset, - windows: Default::default(), - devices: Default::default(), - xi2ext, - pending_wakeup: Default::default(), - root, - wakeup_dummy_window, - }; - - // Register for device hotplug events - // (The request buffer is flushed during `init_device`) - result.xconn.select_xinput_events( - root, - ffi::XIAllDevices, - ffi::XI_HierarchyChangedMask, - ).queue(); - - result.init_device(ffi::XIAllDevices); - + fn with_window(&self, window_id: ffi::Window, callback: F) -> Option + where + F: Fn(&Arc) -> Ret, + { + let mut deleted = false; + let window_id = WindowId(window_id); + let wt = get_xtarget(&self.target); + let result = wt + .windows + .borrow() + .get(&window_id) + .and_then(|window| { + let arc = window.upgrade(); + deleted = arc.is_none(); + arc + }) + .map(|window| callback(&window)); + if deleted { + // Garbage collection + wt.windows.borrow_mut().remove(&window_id); + } result } - /// Returns the `XConnection` of this events loop. - #[inline] - pub fn x_connection(&self) -> &Arc { - &self.xconn + fn window_exists(&self, window_id: ffi::Window) -> bool { + self.with_window(window_id, |_| ()).is_some() } - pub fn create_proxy(&self) -> EventsLoopProxy { - EventsLoopProxy { - pending_wakeup: Arc::downgrade(&self.pending_wakeup), - xconn: Arc::downgrade(&self.xconn), - wakeup_dummy_window: self.wakeup_dummy_window, + pub(super) fn poll(&self) -> bool { + let wt = get_xtarget(&self.target); + let result = unsafe { (wt.xconn.xlib.XPending)(wt.xconn.display) }; + + result != 0 + } + + pub(super) unsafe fn poll_one_event(&mut self, event_ptr: *mut ffi::XEvent) -> bool { + let wt = get_xtarget(&self.target); + // This function is used to poll and remove a single event + // from the Xlib event queue in a non-blocking, atomic way. + // XCheckIfEvent is non-blocking and removes events from queue. + // XNextEvent can't be used because it blocks while holding the + // global Xlib mutex. + // XPeekEvent does not remove events from the queue. + unsafe extern "C" fn predicate( + _display: *mut ffi::Display, + _event: *mut ffi::XEvent, + _arg: *mut c_char, + ) -> c_int { + // This predicate always returns "true" (1) to accept all events + 1 } + + let result = (wt.xconn.xlib.XCheckIfEvent)( + wt.xconn.display, + event_ptr, + Some(predicate), + std::ptr::null_mut(), + ); + + result != 0 } - pub fn poll_events(&mut self, mut callback: F) - where F: FnMut(Event) - { - let mut xev = unsafe { mem::uninitialized() }; - loop { - // Get next event - unsafe { - // Ensure XNextEvent won't block - let count = (self.xconn.xlib.XPending)(self.xconn.display); - if count == 0 { - break; - } - - (self.xconn.xlib.XNextEvent)(self.xconn.display, &mut xev); - } - self.process_event(&mut xev, &mut callback); - } - } - - pub fn run_forever(&mut self, mut callback: F) - where F: FnMut(Event) -> ControlFlow - { - let mut xev = unsafe { mem::uninitialized() }; - - loop { - unsafe { (self.xconn.xlib.XNextEvent)(self.xconn.display, &mut xev) }; // Blocks as necessary - - let mut control_flow = ControlFlow::Continue; - - // Track whether or not `Break` was returned when processing the event. - { - let mut cb = |event| { - if let ControlFlow::Break = callback(event) { - control_flow = ControlFlow::Break; - } - }; - - self.process_event(&mut xev, &mut cb); - } - - if let ControlFlow::Break = control_flow { - break; - } - } - } - - fn process_event(&mut self, xev: &mut ffi::XEvent, mut callback: F) - where F: FnMut(Event) + pub(super) fn process_event(&mut self, xev: &mut ffi::XEvent, mut callback: F) + where + F: FnMut(Event<'_, T>), { + let wt = get_xtarget(&self.target); // XFilterEvent tells us when an event has been discarded by the input method. // Specifically, this involves all of the KeyPress events in compose/pre-edit sequences, // along with an extra copy of the KeyRelease events. This also prevents backspace and // arrow keys from being detected twice. - if ffi::True == unsafe { (self.xconn.xlib.XFilterEvent)( - xev, - { let xev: &ffi::XAnyEvent = xev.as_ref(); xev.window } - ) } { + if ffi::True + == unsafe { + (wt.xconn.xlib.XFilterEvent)(xev, { + let xev: &ffi::XAnyEvent = xev.as_ref(); + xev.window + }) + } + { return; } + // We can't call a `&mut self` method because of the above borrow, + // so we use this macro for repeated modifier state updates. + macro_rules! update_modifiers { + ( $state:expr , $modifier:expr ) => {{ + match ($state, $modifier) { + (state, modifier) => { + if let Some(modifiers) = + self.device_mod_state.update_state(&state, modifier) + { + if let Some(window_id) = self.active_window { + callback(Event::WindowEvent { + window_id: mkwid(window_id), + event: WindowEvent::ModifiersChanged(modifiers), + }); + } + } + } + } + }}; + } + let event_type = xev.get_type(); match event_type { ffi::MappingNotify => { - unsafe { (self.xconn.xlib.XRefreshKeyboardMapping)(xev.as_mut()); } - self.xconn.check_errors().expect("Failed to call XRefreshKeyboardMapping"); + let mapping: &ffi::XMappingEvent = xev.as_ref(); + + if mapping.request == ffi::MappingModifier + || mapping.request == ffi::MappingKeyboard + { + unsafe { + (wt.xconn.xlib.XRefreshKeyboardMapping)(xev.as_mut()); + } + wt.xconn + .check_errors() + .expect("Failed to call XRefreshKeyboardMapping"); + + self.mod_keymap.reset_from_x_connection(&wt.xconn); + self.device_mod_state.update_keymap(&self.mod_keymap); + } } ffi::ClientMessage => { @@ -258,8 +176,21 @@ impl EventsLoop { let window = client_msg.window; let window_id = mkwid(window); - if client_msg.data.get_long(0) as ffi::Atom == self.wm_delete_window { - callback(Event::WindowEvent { window_id, event: WindowEvent::CloseRequested }); + if client_msg.data.get_long(0) as ffi::Atom == wt.wm_delete_window { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::CloseRequested, + }); + } else if client_msg.data.get_long(0) as ffi::Atom == wt.net_wm_ping { + let response_msg: &mut ffi::XClientMessageEvent = xev.as_mut(); + response_msg.window = wt.root; + wt.xconn + .send_event( + wt.root, + Some(ffi::SubstructureNotifyMask | ffi::SubstructureRedirectMask), + *response_msg, + ) + .queue(); } else if client_msg.message_type == self.dnd.atoms.enter { let source_window = client_msg.data.get_long(0) as c_ulong; let flags = client_msg.data.get_long(1); @@ -270,10 +201,11 @@ impl EventsLoop { let type_list = vec![ client_msg.data.get_long(2) as c_ulong, client_msg.data.get_long(3) as c_ulong, - client_msg.data.get_long(4) as c_ulong + client_msg.data.get_long(4) as c_ulong, ]; self.dnd.type_list = Some(type_list); - } else if let Ok(more_types) = unsafe { self.dnd.get_type_list(source_window) } { + } else if let Ok(more_types) = unsafe { self.dnd.get_type_list(source_window) } + { self.dnd.type_list = Some(more_types); } } else if client_msg.message_type == self.dnd.atoms.position { @@ -321,18 +253,21 @@ impl EventsLoop { // This results in the `SelectionNotify` event below self.dnd.convert_selection(window, time); } - self.dnd.send_status(window, source_window, DndState::Accepted) + self.dnd + .send_status(window, source_window, DndState::Accepted) .expect("Failed to send `XdndStatus` message."); } } else { unsafe { - self.dnd.send_status(window, source_window, DndState::Rejected) + self.dnd + .send_status(window, source_window, DndState::Rejected) .expect("Failed to send `XdndStatus` message."); } self.dnd.reset(); } } else if client_msg.message_type == self.dnd.atoms.drop { - let (source_window, state) = if let Some(source_window) = self.dnd.source_window { + let (source_window, state) = if let Some(source_window) = self.dnd.source_window + { if let Some(Ok(ref path_list)) = self.dnd.result { for path in path_list { callback(Event::WindowEvent { @@ -349,7 +284,8 @@ impl EventsLoop { (source_window, DndState::Rejected) }; unsafe { - self.dnd.send_finished(window, source_window, state) + self.dnd + .send_finished(window, source_window, state) .expect("Failed to send `XdndFinished` message."); } self.dnd.reset(); @@ -359,9 +295,6 @@ impl EventsLoop { window_id, event: WindowEvent::HoveredFileCancelled, }); - } else if self.pending_wakeup.load(atomic::Ordering::Relaxed) { - self.pending_wakeup.store(false, atomic::Ordering::Relaxed); - callback(Event::Awakened); } } @@ -393,16 +326,11 @@ impl EventsLoop { } ffi::ConfigureNotify => { - #[derive(Debug, Default)] - struct Events { - resized: Option, - moved: Option, - dpi_changed: Option, - } - let xev: &ffi::XConfigureEvent = xev.as_ref(); let xwindow = xev.window; - let events = self.with_window(xwindow, |window| { + let window_id = mkwid(xwindow); + + if let Some(window) = self.with_window(xwindow, Arc::clone) { // So apparently... // `XSendEvent` (synthetic `ConfigureNotify`) -> position relative to root // `XConfigureNotify` (real `ConfigureNotify`) -> position relative to parent @@ -416,19 +344,25 @@ impl EventsLoop { let new_inner_size = (xev.width as u32, xev.height as u32); let new_inner_position = (xev.x as i32, xev.y as i32); - let mut monitor = window.get_current_monitor(); // This must be done *before* locking! let mut shared_state_lock = window.shared_state.lock(); let (mut resized, moved) = { - let resized = util::maybe_change(&mut shared_state_lock.size, new_inner_size); + let resized = + util::maybe_change(&mut shared_state_lock.size, new_inner_size); let moved = if is_synthetic { - util::maybe_change(&mut shared_state_lock.inner_position, new_inner_position) + util::maybe_change( + &mut shared_state_lock.inner_position, + new_inner_position, + ) } else { // Detect when frame extents change. // Since this isn't synthetic, as per the notes above, this position is relative to the // parent window. let rel_parent = new_inner_position; - if util::maybe_change(&mut shared_state_lock.inner_position_rel_parent, rel_parent) { + if util::maybe_change( + &mut shared_state_lock.inner_position_rel_parent, + rel_parent, + ) { // This ensures we process the next `Moved`. shared_state_lock.inner_position = None; // Extra insurance against stale frame extents. @@ -439,23 +373,29 @@ impl EventsLoop { (resized, moved) }; - let mut events = Events::default(); - let new_outer_position = if moved || shared_state_lock.position.is_none() { // We need to convert client area position to window position. - let frame_extents = shared_state_lock.frame_extents + let frame_extents = shared_state_lock + .frame_extents .as_ref() .cloned() .unwrap_or_else(|| { - let frame_extents = self.xconn.get_frame_extents_heuristic(xwindow, self.root); + let frame_extents = + wt.xconn.get_frame_extents_heuristic(xwindow, wt.root); shared_state_lock.frame_extents = Some(frame_extents.clone()); frame_extents }); - let outer = frame_extents.inner_pos_to_outer(new_inner_position.0, new_inner_position.1); + let outer = frame_extents + .inner_pos_to_outer(new_inner_position.0, new_inner_position.1); shared_state_lock.position = Some(outer); if moved { - let logical_position = LogicalPosition::from_physical(outer, monitor.hidpi_factor); - events.moved = Some(WindowEvent::Moved(logical_position)); + // Temporarily unlock shared state to prevent deadlock + MutexGuard::unlocked(&mut shared_state_lock, || { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::Moved(outer.into()), + }); + }); } outer } else { @@ -465,36 +405,56 @@ impl EventsLoop { if is_synthetic { // If we don't use the existing adjusted value when available, then the user can screw up the // resizing by dragging across monitors *without* dropping the window. - let (width, height) = shared_state_lock.dpi_adjusted - .unwrap_or_else(|| (xev.width as f64, xev.height as f64)); - let last_hidpi_factor = shared_state_lock.guessed_dpi - .take() - .unwrap_or_else(|| { - shared_state_lock.last_monitor - .as_ref() - .map(|last_monitor| last_monitor.hidpi_factor) - .unwrap_or(1.0) - }); - let new_hidpi_factor = { + let (width, height) = shared_state_lock + .dpi_adjusted + .unwrap_or_else(|| (xev.width as u32, xev.height as u32)); + + let last_scale_factor = shared_state_lock.last_monitor.scale_factor; + let new_scale_factor = { let window_rect = util::AaRect::new(new_outer_position, new_inner_size); - monitor = self.xconn.get_monitor_for_window(Some(window_rect)); - let new_hidpi_factor = monitor.hidpi_factor; - shared_state_lock.last_monitor = Some(monitor.clone()); - new_hidpi_factor + let monitor = wt.xconn.get_monitor_for_window(Some(window_rect)); + + if monitor.is_dummy() { + // Avoid updating monitor using a dummy monitor handle + last_scale_factor + } else { + shared_state_lock.last_monitor = monitor.clone(); + monitor.scale_factor + } }; - if last_hidpi_factor != new_hidpi_factor { - events.dpi_changed = Some(WindowEvent::HiDpiFactorChanged(new_hidpi_factor)); - let (new_width, new_height, flusher) = window.adjust_for_dpi( - last_hidpi_factor, - new_hidpi_factor, + if last_scale_factor != new_scale_factor { + let (new_width, new_height) = window.adjust_for_dpi( + last_scale_factor, + new_scale_factor, width, height, + &shared_state_lock, ); - flusher.queue(); - shared_state_lock.dpi_adjusted = Some((new_width, new_height)); - // if the DPI factor changed, force a resize event to ensure the logical - // size is computed with the right DPI factor - resized = true; + + let old_inner_size = PhysicalSize::new(width, height); + let mut new_inner_size = PhysicalSize::new(new_width, new_height); + + // Temporarily unlock shared state to prevent deadlock + MutexGuard::unlocked(&mut shared_state_lock, || { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + new_inner_size: &mut new_inner_size, + }, + }); + }); + + if new_inner_size != old_inner_size { + window.set_inner_size_physical( + new_inner_size.width, + new_inner_size.height, + ); + shared_state_lock.dpi_adjusted = Some(new_inner_size.into()); + // if the DPI factor changed, force a resize event to ensure the logical + // size is computed with the right DPI factor + resized = true; + } } } @@ -503,40 +463,22 @@ impl EventsLoop { // WMs constrain the window size, making the resize fail. This would cause an endless stream of // XResizeWindow requests, making Xorg, the winit client, and the WM consume 100% of CPU. if let Some(adjusted_size) = shared_state_lock.dpi_adjusted { - let rounded_size = (adjusted_size.0.round() as u32, adjusted_size.1.round() as u32); - if new_inner_size == rounded_size || !util::wm_name_is_one_of(&["Xfwm4"]) { + if new_inner_size == adjusted_size || !util::wm_name_is_one_of(&["Xfwm4"]) { // When this finally happens, the event will not be synthetic. shared_state_lock.dpi_adjusted = None; } else { - unsafe { - (self.xconn.xlib.XResizeWindow)( - self.xconn.display, - xwindow, - rounded_size.0 as c_uint, - rounded_size.1 as c_uint, - ); - } + window.set_inner_size_physical(adjusted_size.0, adjusted_size.1); } } if resized { - let logical_size = LogicalSize::from_physical(new_inner_size, monitor.hidpi_factor); - events.resized = Some(WindowEvent::Resized(logical_size)); - } + // Drop the shared state lock to prevent deadlock + drop(shared_state_lock); - events - }); - - if let Some(events) = events { - let window_id = mkwid(xwindow); - if let Some(event) = events.dpi_changed { - callback(Event::WindowEvent { window_id, event }); - } - if let Some(event) = events.resized { - callback(Event::WindowEvent { window_id, event }); - } - if let Some(event) = events.moved { - callback(Event::WindowEvent { window_id, event }); + callback(Event::WindowEvent { + window_id, + event: WindowEvent::Resized(new_inner_size.into()), + }); } } } @@ -549,7 +491,7 @@ impl EventsLoop { // (which is almost all of them). Failing to correctly update WM info doesn't // really have much impact, since on the WMs affected (xmonad, dwm, etc.) the only // effect is that we waste some time trying to query unsupported properties. - self.xconn.update_cached_wm_info(self.root); + wt.xconn.update_cached_wm_info(wt.root); self.with_window(xev.window, |window| { window.invalidate_cached_frame_extents(); @@ -564,29 +506,43 @@ impl EventsLoop { // In the event that the window's been destroyed without being dropped first, we // cleanup again here. - self.windows.borrow_mut().remove(&WindowId(window)); + wt.windows.borrow_mut().remove(&WindowId(window)); // Since all XIM stuff needs to happen from the same thread, we destroy the input // context here instead of when dropping the window. - self.ime + wt.ime .borrow_mut() .remove_context(window) .expect("Failed to destroy input context"); - callback(Event::WindowEvent { window_id, event: WindowEvent::Destroyed }); + callback(Event::WindowEvent { + window_id, + event: WindowEvent::Destroyed, + }); + } + + ffi::VisibilityNotify => { + let xev: &ffi::XVisibilityEvent = xev.as_ref(); + let xwindow = xev.window; + + self.with_window(xwindow, |window| window.visibility_notify()); } ffi::Expose => { let xev: &ffi::XExposeEvent = xev.as_ref(); - let window = xev.window; - let window_id = mkwid(window); + // Multiple Expose events may be received for subareas of a window. + // We issue `RedrawRequested` only for the last event of such a series. + if xev.count == 0 { + let window = xev.window; + let window_id = mkwid(window); - callback(Event::WindowEvent { window_id, event: WindowEvent::Refresh }); + callback(Event::RedrawRequested(window_id)); + } } ffi::KeyPress | ffi::KeyRelease => { - use events::ElementState::{Pressed, Released}; + use crate::event::ElementState::{Pressed, Released}; // Note that in compose/pre-edit sequences, this will always be Released. let state = if xev.get_type() == ffi::KeyPress { @@ -604,48 +560,41 @@ impl EventsLoop { // value, though this should only be an issue under multiseat configurations. let device = util::VIRTUAL_CORE_KEYBOARD; let device_id = mkdid(device); + let keycode = xkev.keycode; // When a compose sequence or IME pre-edit is finished, it ends in a KeyPress with // a keycode of 0. - if xkev.keycode != 0 { - let modifiers = ModifiersState { - alt: xkev.state & ffi::Mod1Mask != 0, - shift: xkev.state & ffi::ShiftMask != 0, - ctrl: xkev.state & ffi::ControlMask != 0, - logo: xkev.state & ffi::Mod4Mask != 0, - }; - - let keysym = unsafe { - let mut keysym = 0; - (self.xconn.xlib.XLookupString)( - xkev, - ptr::null_mut(), - 0, - &mut keysym, - ptr::null_mut(), - ); - self.xconn.check_errors().expect("Failed to lookup keysym"); - keysym - }; + if keycode != 0 { + let scancode = keycode - 8; + let keysym = wt.xconn.lookup_keysym(xkev); let virtual_keycode = events::keysym_to_element(keysym as c_uint); + update_modifiers!( + ModifiersState::from_x11_mask(xkev.state), + self.mod_keymap.get_modifier(xkev.keycode as ffi::KeyCode) + ); + + let modifiers = self.device_mod_state.modifiers(); + + #[allow(deprecated)] callback(Event::WindowEvent { window_id, event: WindowEvent::KeyboardInput { device_id, input: KeyboardInput { state, - scancode: xkev.keycode - 8, + scancode, virtual_keycode, modifiers, }, - } + is_synthetic: false, + }, }); } if state == Pressed { - let written = if let Some(ic) = self.ime.borrow().get_context(window) { - self.xconn.lookup_utf8(ic, xkev) + let written = if let Some(ic) = wt.ime.borrow().get_context(window) { + wt.xconn.lookup_utf8(ic, xkev) } else { return; }; @@ -661,17 +610,26 @@ impl EventsLoop { } ffi::GenericEvent => { - let guard = if let Some(e) = GenericEventCookie::from_event(&self.xconn, *xev) { e } else { return }; + let guard = if let Some(e) = GenericEventCookie::from_event(&wt.xconn, *xev) { + e + } else { + return; + }; let xev = &guard.cookie; if self.xi2ext.opcode != xev.extension { return; } - use events::WindowEvent::{Focused, CursorEntered, MouseInput, CursorLeft, CursorMoved, MouseWheel, AxisMotion}; - use events::ElementState::{Pressed, Released}; - use events::MouseButton::{Left, Right, Middle, Other}; - use events::MouseScrollDelta::LineDelta; - use events::{Touch, TouchPhase}; + use crate::event::{ + ElementState::{Pressed, Released}, + MouseButton::{Left, Middle, Other, Right}, + MouseScrollDelta::LineDelta, + Touch, + WindowEvent::{ + AxisMotion, CursorEntered, CursorLeft, CursorMoved, Focused, MouseInput, + MouseWheel, + }, + }; match xev.evtype { ffi::XI_ButtonPress | ffi::XI_ButtonRelease => { @@ -680,13 +638,11 @@ impl EventsLoop { let device_id = mkdid(xev.deviceid); if (xev.flags & ffi::XIPointerEmulated) != 0 { // Deliver multi-touch events instead of emulated mouse events. - let return_now = self - .with_window(xev.event, |window| window.multitouch) - .unwrap_or(true); - if return_now { return; } + return; } - let modifiers = ModifiersState::from(xev.mods); + let modifiers = ModifiersState::from_x11(&xev.mods); + update_modifiers!(modifiers, None); let state = if xev.evtype == ffi::XI_ButtonPress { Pressed @@ -725,23 +681,25 @@ impl EventsLoop { // Suppress emulated scroll wheel clicks, since we handle the real motion events for those. // In practice, even clicky scroll wheels appear to be reported by evdev (and XInput2 in // turn) as axis motion, so we don't otherwise special-case these button presses. - 4 | 5 | 6 | 7 => if xev.flags & ffi::XIPointerEmulated == 0 { - callback(Event::WindowEvent { - window_id, - event: MouseWheel { - device_id, - delta: match xev.detail { - 4 => LineDelta(0.0, 1.0), - 5 => LineDelta(0.0, -1.0), - 6 => LineDelta(-1.0, 0.0), - 7 => LineDelta(1.0, 0.0), - _ => unreachable!(), + 4 | 5 | 6 | 7 => { + if xev.flags & ffi::XIPointerEmulated == 0 { + callback(Event::WindowEvent { + window_id, + event: MouseWheel { + device_id, + delta: match xev.detail { + 4 => LineDelta(0.0, 1.0), + 5 => LineDelta(0.0, -1.0), + 6 => LineDelta(-1.0, 0.0), + 7 => LineDelta(1.0, 0.0), + _ => unreachable!(), + }, + phase: TouchPhase::Moved, + modifiers, }, - phase: TouchPhase::Moved, - modifiers, - }, - }); - }, + }); + } + } x => callback(Event::WindowEvent { window_id, @@ -760,32 +718,24 @@ impl EventsLoop { let window_id = mkwid(xev.event); let new_cursor_pos = (xev.event_x, xev.event_y); - let modifiers = ModifiersState::from(xev.mods); + let modifiers = ModifiersState::from_x11(&xev.mods); + update_modifiers!(modifiers, None); let cursor_moved = self.with_window(xev.event, |window| { let mut shared_state_lock = window.shared_state.lock(); util::maybe_change(&mut shared_state_lock.cursor_pos, new_cursor_pos) }); if cursor_moved == Some(true) { - let dpi_factor = self.with_window(xev.event, |window| { - window.get_hidpi_factor() + let position = PhysicalPosition::new(xev.event_x, xev.event_y); + + callback(Event::WindowEvent { + window_id, + event: CursorMoved { + device_id, + position, + modifiers, + }, }); - if let Some(dpi_factor) = dpi_factor { - let position = LogicalPosition::from_physical( - (xev.event_x as f64, xev.event_y as f64), - dpi_factor, - ); - callback(Event::WindowEvent { - window_id, - event: CursorMoved { - device_id, - position, - modifiers, - }, - }); - } else { - return; - } } else if cursor_moved.is_none() { return; } @@ -793,7 +743,12 @@ impl EventsLoop { // More gymnastics, for self.devices let mut events = Vec::new(); { - let mask = unsafe { slice::from_raw_parts(xev.valuators.mask, xev.valuators.mask_len as usize) }; + let mask = unsafe { + slice::from_raw_parts( + xev.valuators.mask, + xev.valuators.mask_len as usize, + ) + }; let mut devices = self.devices.borrow_mut(); let physical_device = match devices.get_mut(&DeviceId(xev.sourceid)) { Some(device) => device, @@ -801,10 +756,14 @@ impl EventsLoop { }; let mut value = xev.valuators.values; - for i in 0..xev.valuators.mask_len*8 { + for i in 0..xev.valuators.mask_len * 8 { if ffi::XIMaskIsSet(mask, i) { let x = unsafe { *value }; - if let Some(&mut (_, ref mut info)) = physical_device.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == i) { + if let Some(&mut (_, ref mut info)) = physical_device + .scroll_axes + .iter_mut() + .find(|&&mut (axis, _)| axis == i) + { let delta = (x - info.position) / info.increment; info.position = x; events.push(Event::WindowEvent { @@ -812,9 +771,13 @@ impl EventsLoop { event: MouseWheel { device_id, delta: match info.orientation { - ScrollOrientation::Horizontal => LineDelta(delta as f32, 0.0), + ScrollOrientation::Horizontal => { + LineDelta(delta as f32, 0.0) + } // X11 vertical scroll coordinates are opposite to winit's - ScrollOrientation::Vertical => LineDelta(0.0, -delta as f32), + ScrollOrientation::Vertical => { + LineDelta(0.0, -delta as f32) + } }, phase: TouchPhase::Moved, modifiers, @@ -845,7 +808,7 @@ impl EventsLoop { let window_id = mkwid(xev.event); let device_id = mkdid(xev.deviceid); - if let Some(all_info) = DeviceInfo::get(&self.xconn, ffi::XIAllDevices) { + if let Some(all_info) = DeviceInfo::get(&wt.xconn, ffi::XIAllDevices) { let mut devices = self.devices.borrow_mut(); for device_info in all_info.iter() { if device_info.deviceid == xev.sourceid @@ -853,7 +816,8 @@ impl EventsLoop { // presumably some other WMs. On those, `XI_Enter` doesn't include // the physical device ID, so both `sourceid` and `deviceid` are // the virtual device. - || device_info.attachment == xev.sourceid { + || device_info.attachment == xev.sourceid + { let device_id = DeviceId(device_info.deviceid); if let Some(device) = devices.get_mut(&device_id) { device.reset_scroll_position(device_info); @@ -861,18 +825,14 @@ impl EventsLoop { } } } - callback(Event::WindowEvent { - window_id, - event: CursorEntered { device_id }, - }); - if let Some(dpi_factor) = self.with_window(xev.event, |window| { - window.get_hidpi_factor() - }) { - let position = LogicalPosition::from_physical( - (xev.event_x as f64, xev.event_y as f64), - dpi_factor, - ); + if self.window_exists(xev.event) { + callback(Event::WindowEvent { + window_id, + event: CursorEntered { device_id }, + }); + + let position = PhysicalPosition::new(xev.event_x, xev.event_y); // The mods field on this event isn't actually populated, so query the // pointer device. In the future, we can likely remove this round-trip by @@ -881,7 +841,8 @@ impl EventsLoop { // This needs to only be done after confirming the window still exists, // since otherwise we risk getting a `BadWindow` error if the window was // dropped with queued events. - let modifiers = self.xconn + let modifiers = wt + .xconn .query_pointer(xev.event, xev.deviceid) .expect("Failed to query pointer device") .get_modifier_state(); @@ -905,60 +866,98 @@ impl EventsLoop { if !window_closed { callback(Event::WindowEvent { window_id: mkwid(xev.event), - event: CursorLeft { device_id: mkdid(xev.deviceid) }, + event: CursorLeft { + device_id: mkdid(xev.deviceid), + }, }); } } ffi::XI_FocusIn => { let xev: &ffi::XIFocusInEvent = unsafe { &*(xev.data as *const _) }; - let dpi_factor = match self.with_window(xev.event, |window| { - window.get_hidpi_factor() - }) { - Some(dpi_factor) => dpi_factor, - None => return, - }; - let window_id = mkwid(xev.event); - - self.ime + wt.ime .borrow_mut() .focus(xev.event) .expect("Failed to focus input context"); - callback(Event::WindowEvent { window_id, event: Focused(true) }); + let modifiers = ModifiersState::from_x11(&xev.mods); - // The deviceid for this event is for a keyboard instead of a pointer, - // so we have to do a little extra work. - let pointer_id = self.devices - .borrow() - .get(&DeviceId(xev.deviceid)) - .map(|device| device.attachment) - .unwrap_or(2); + self.device_mod_state.update_state(&modifiers, None); - let position = LogicalPosition::from_physical( - (xev.event_x as f64, xev.event_y as f64), - dpi_factor, - ); - callback(Event::WindowEvent { - window_id, - event: CursorMoved { - device_id: mkdid(pointer_id), - position, - modifiers: ModifiersState::from(xev.mods), + if self.active_window != Some(xev.event) { + self.active_window = Some(xev.event); + + let window_id = mkwid(xev.event); + let position = PhysicalPosition::new(xev.event_x, xev.event_y); + + callback(Event::WindowEvent { + window_id, + event: Focused(true), + }); + + if !modifiers.is_empty() { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ModifiersChanged(modifiers), + }); } - }); + + // The deviceid for this event is for a keyboard instead of a pointer, + // so we have to do a little extra work. + let pointer_id = self + .devices + .borrow() + .get(&DeviceId(xev.deviceid)) + .map(|device| device.attachment) + .unwrap_or(2); + + callback(Event::WindowEvent { + window_id, + event: CursorMoved { + device_id: mkdid(pointer_id), + position, + modifiers, + }, + }); + + // Issue key press events for all pressed keys + self.handle_pressed_keys( + window_id, + ElementState::Pressed, + &mut callback, + ); + } } ffi::XI_FocusOut => { let xev: &ffi::XIFocusOutEvent = unsafe { &*(xev.data as *const _) }; - if !self.window_exists(xev.event) { return; } - self.ime + if !self.window_exists(xev.event) { + return; + } + wt.ime .borrow_mut() .unfocus(xev.event) .expect("Failed to unfocus input context"); - callback(Event::WindowEvent { - window_id: mkwid(xev.event), - event: Focused(false), - }) + + if self.active_window.take() == Some(xev.event) { + let window_id = mkwid(xev.event); + + // Issue key release events for all pressed keys + self.handle_pressed_keys( + window_id, + ElementState::Released, + &mut callback, + ); + + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ModifiersChanged(ModifiersState::empty()), + }); + + callback(Event::WindowEvent { + window_id, + event: Focused(false), + }) + } } ffi::XI_TouchBegin | ffi::XI_TouchUpdate | ffi::XI_TouchEnd => { @@ -968,23 +967,36 @@ impl EventsLoop { ffi::XI_TouchBegin => TouchPhase::Started, ffi::XI_TouchUpdate => TouchPhase::Moved, ffi::XI_TouchEnd => TouchPhase::Ended, - _ => unreachable!() + _ => unreachable!(), }; - let dpi_factor = self.with_window(xev.event, |window| { - window.get_hidpi_factor() - }); - if let Some(dpi_factor) = dpi_factor { - let location = LogicalPosition::from_physical( - (xev.event_x as f64, xev.event_y as f64), - dpi_factor, - ); + if self.window_exists(xev.event) { + let id = xev.detail as u64; + let modifiers = self.device_mod_state.modifiers(); + let location = + PhysicalPosition::new(xev.event_x as f64, xev.event_y as f64); + + // Mouse cursor position changes when touch events are received. + // Only the first concurrently active touch ID moves the mouse cursor. + if is_first_touch(&mut self.first_touch, &mut self.num_touch, id, phase) + { + callback(Event::WindowEvent { + window_id, + event: WindowEvent::CursorMoved { + device_id: mkdid(util::VIRTUAL_CORE_POINTER), + position: location.cast(), + modifiers, + }, + }); + } + callback(Event::WindowEvent { window_id, event: WindowEvent::Touch(Touch { device_id: mkdid(xev.deviceid), phase, location, - id: xev.detail as u64, + force: None, // TODO + id, }), }) } @@ -993,14 +1005,17 @@ impl EventsLoop { ffi::XI_RawButtonPress | ffi::XI_RawButtonRelease => { let xev: &ffi::XIRawEvent = unsafe { &*(xev.data as *const _) }; if xev.flags & ffi::XIPointerEmulated == 0 { - callback(Event::DeviceEvent { device_id: mkdid(xev.deviceid), event: DeviceEvent::Button { - button: xev.detail as u32, - state: match xev.evtype { - ffi::XI_RawButtonPress => Pressed, - ffi::XI_RawButtonRelease => Released, - _ => unreachable!(), + callback(Event::DeviceEvent { + device_id: mkdid(xev.deviceid), + event: DeviceEvent::Button { + button: xev.detail as u32, + state: match xev.evtype { + ffi::XI_RawButtonPress => Pressed, + ffi::XI_RawButtonRelease => Released, + _ => unreachable!(), + }, }, - }}); + }); } } @@ -1008,11 +1023,16 @@ impl EventsLoop { let xev: &ffi::XIRawEvent = unsafe { &*(xev.data as *const _) }; let did = mkdid(xev.deviceid); - let mask = unsafe { slice::from_raw_parts(xev.valuators.mask, xev.valuators.mask_len as usize) }; + let mask = unsafe { + slice::from_raw_parts( + xev.valuators.mask, + xev.valuators.mask_len as usize, + ) + }; let mut value = xev.raw_values; let mut mouse_delta = (0.0, 0.0); let mut scroll_delta = (0.0, 0.0); - for i in 0..xev.valuators.mask_len*8 { + for i in 0..xev.valuators.mask_len * 8 { if ffi::XIMaskIsSet(mask, i) { let x = unsafe { *value }; // We assume that every XInput2 device with analog axes is a pointing device emitting @@ -1022,24 +1042,31 @@ impl EventsLoop { 1 => mouse_delta.1 = x, 2 => scroll_delta.0 = x as f32, 3 => scroll_delta.1 = x as f32, - _ => {}, + _ => {} } - callback(Event::DeviceEvent { device_id: did, event: DeviceEvent::Motion { - axis: i as u32, - value: x, - }}); + callback(Event::DeviceEvent { + device_id: did, + event: DeviceEvent::Motion { + axis: i as u32, + value: x, + }, + }); value = unsafe { value.offset(1) }; } } if mouse_delta != (0.0, 0.0) { - callback(Event::DeviceEvent { device_id: did, event: DeviceEvent::MouseMotion { - delta: mouse_delta, - }}); + callback(Event::DeviceEvent { + device_id: did, + event: DeviceEvent::MouseMotion { delta: mouse_delta }, + }); } if scroll_delta != (0.0, 0.0) { - callback(Event::DeviceEvent { device_id: did, event: DeviceEvent::MouseWheel { - delta: LineDelta(scroll_delta.0, scroll_delta.1), - }}); + callback(Event::DeviceEvent { + device_id: did, + event: DeviceEvent::MouseWheel { + delta: LineDelta(scroll_delta.0, scroll_delta.1), + }, + }); } } @@ -1052,46 +1079,66 @@ impl EventsLoop { _ => unreachable!(), }; - let device_id = xev.sourceid; + let device_id = mkdid(xev.sourceid); let keycode = xev.detail; - if keycode < 8 { return; } + if keycode < 8 { + return; + } let scancode = (keycode - 8) as u32; - - let keysym = unsafe { - (self.xconn.xlib.XKeycodeToKeysym)( - self.xconn.display, - xev.detail as ffi::KeyCode, - 0, - ) - }; - self.xconn.check_errors().expect("Failed to lookup raw keysym"); - + let keysym = wt.xconn.keycode_to_keysym(keycode as ffi::KeyCode); let virtual_keycode = events::keysym_to_element(keysym as c_uint); + let modifiers = self.device_mod_state.modifiers(); + #[allow(deprecated)] callback(Event::DeviceEvent { - device_id: mkdid(device_id), + device_id, event: DeviceEvent::Key(KeyboardInput { scancode, virtual_keycode, state, - // So, in an ideal world we can use libxkbcommon to get modifiers. - // However, libxkbcommon-x11 isn't as commonly installed as one - // would hope. We can still use the Xkb extension to get - // comprehensive keyboard state updates, but interpreting that - // info manually is going to be involved. - modifiers: ModifiersState::default(), + modifiers, }), }); + + if let Some(modifier) = + self.mod_keymap.get_modifier(keycode as ffi::KeyCode) + { + self.device_mod_state.key_event( + state, + keycode as ffi::KeyCode, + modifier, + ); + + let new_modifiers = self.device_mod_state.modifiers(); + + if modifiers != new_modifiers { + if let Some(window_id) = self.active_window { + callback(Event::WindowEvent { + window_id: mkwid(window_id), + event: WindowEvent::ModifiersChanged(new_modifiers), + }); + } + } + } } ffi::XI_HierarchyChanged => { let xev: &ffi::XIHierarchyEvent = unsafe { &*(xev.data as *const _) }; - for info in unsafe { slice::from_raw_parts(xev.info, xev.num_info as usize) } { + for info in + unsafe { slice::from_raw_parts(xev.info, xev.num_info as usize) } + { if 0 != info.flags & (ffi::XISlaveAdded | ffi::XIMasterAdded) { self.init_device(info.deviceid); - callback(Event::DeviceEvent { device_id: mkdid(info.deviceid), event: DeviceEvent::Added }); - } else if 0 != info.flags & (ffi::XISlaveRemoved | ffi::XIMasterRemoved) { - callback(Event::DeviceEvent { device_id: mkdid(info.deviceid), event: DeviceEvent::Removed }); + callback(Event::DeviceEvent { + device_id: mkdid(info.deviceid), + event: DeviceEvent::Added, + }); + } else if 0 != info.flags & (ffi::XISlaveRemoved | ffi::XIMasterRemoved) + { + callback(Event::DeviceEvent { + device_id: mkdid(info.deviceid), + event: DeviceEvent::Removed, + }); let mut devices = self.devices.borrow_mut(); devices.remove(&DeviceId(info.deviceid)); } @@ -1100,41 +1147,60 @@ impl EventsLoop { _ => {} } - }, + } _ => { if event_type == self.randr_event_offset { // In the future, it would be quite easy to emit monitor hotplug events. let prev_list = monitor::invalidate_cached_monitor_list(); if let Some(prev_list) = prev_list { - let new_list = self.xconn.get_available_monitors(); + let new_list = wt.xconn.available_monitors(); for new_monitor in new_list { prev_list .iter() .find(|prev_monitor| prev_monitor.name == new_monitor.name) .map(|prev_monitor| { - if new_monitor.hidpi_factor != prev_monitor.hidpi_factor { - for (window_id, window) in self.windows.borrow().iter() { + if new_monitor.scale_factor != prev_monitor.scale_factor { + for (window_id, window) in wt.windows.borrow().iter() { if let Some(window) = window.upgrade() { // Check if the window is on this monitor - let monitor = window.get_current_monitor(); + let monitor = window.current_monitor(); if monitor.name == new_monitor.name { - callback(Event::WindowEvent { - window_id: mkwid(window_id.0), - event: WindowEvent::HiDpiFactorChanged( - new_monitor.hidpi_factor + let (width, height) = + window.inner_size_physical(); + let (new_width, new_height) = window + .adjust_for_dpi( + prev_monitor.scale_factor, + new_monitor.scale_factor, + width, + height, + &*window.shared_state.lock(), + ); + + let window_id = crate::window::WindowId( + crate::platform_impl::platform::WindowId::X( + *window_id, ), - }); - let (width, height) = match window.get_inner_size_physical() { - Some(result) => result, - None => continue, - }; - let (_, _, flusher) = window.adjust_for_dpi( - prev_monitor.hidpi_factor, - new_monitor.hidpi_factor, - width as f64, - height as f64, ); - flusher.queue(); + let old_inner_size = + PhysicalSize::new(width, height); + let mut new_inner_size = + PhysicalSize::new(new_width, new_height); + + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: new_monitor.scale_factor, + new_inner_size: &mut new_inner_size, + }, + }); + + if new_inner_size != old_inner_size { + let (new_width, new_height) = + new_inner_size.into(); + window.set_inner_size_physical( + new_width, new_height, + ); + } } } } @@ -1143,305 +1209,76 @@ impl EventsLoop { } } } - }, + } } match self.ime_receiver.try_recv() { Ok((window_id, x, y)) => { - self.ime.borrow_mut().send_xim_spot(window_id, x, y); - }, + wt.ime.borrow_mut().send_xim_spot(window_id, x, y); + } Err(_) => (), } } - fn init_device(&self, device: c_int) { - let mut devices = self.devices.borrow_mut(); - if let Some(info) = DeviceInfo::get(&self.xconn, device) { - for info in info.iter() { - devices.insert(DeviceId(info.deviceid), Device::new(&self, info)); - } - } - } - - fn with_window(&self, window_id: ffi::Window, callback: F) -> Option - where F: Fn(&UnownedWindow) -> T + fn handle_pressed_keys( + &self, + window_id: crate::window::WindowId, + state: ElementState, + callback: &mut F, + ) where + F: FnMut(Event<'_, T>), { - let mut deleted = false; - let window_id = WindowId(window_id); - let result = self.windows - .borrow() - .get(&window_id) - .and_then(|window| { - let arc = window.upgrade(); - deleted = arc.is_none(); - arc - }) - .map(|window| callback(&*window)); - if deleted { - // Garbage collection - self.windows.borrow_mut().remove(&window_id); - } - result - } + let wt = get_xtarget(&self.target); - fn window_exists(&self, window_id: ffi::Window) -> bool { - self.with_window(window_id, |_| ()).is_some() - } -} + let device_id = mkdid(util::VIRTUAL_CORE_KEYBOARD); + let modifiers = self.device_mod_state.modifiers(); -impl EventsLoopProxy { - pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { - // Update the `EventsLoop`'s `pending_wakeup` flag. - let display = match (self.pending_wakeup.upgrade(), self.xconn.upgrade()) { - (Some(wakeup), Some(display)) => { - wakeup.store(true, atomic::Ordering::Relaxed); - display - }, - _ => return Err(EventsLoopClosed), - }; + // Get the set of keys currently pressed and apply Key events to each + let keys = wt.xconn.query_keymap(); - // Push an event on the X event queue so that methods run_forever will advance. - // - // NOTE: This design is taken from the old `WindowProxy::wakeup` implementation. It - // assumes that X11 is thread safe. Is this true? - // (WARNING: it's probably not true) - display.send_client_msg( - self.wakeup_dummy_window, - self.wakeup_dummy_window, - 0, - None, - [0, 0, 0, 0, 0], - ).flush().expect("Failed to call XSendEvent after wakeup"); - - Ok(()) - } -} - -struct DeviceInfo<'a> { - xconn: &'a XConnection, - info: *const ffi::XIDeviceInfo, - count: usize, -} - -impl<'a> DeviceInfo<'a> { - fn get(xconn: &'a XConnection, device: c_int) -> Option { - unsafe { - let mut count = mem::uninitialized(); - let info = (xconn.xinput2.XIQueryDevice)(xconn.display, device, &mut count); - xconn.check_errors() - .ok() - .and_then(|_| { - if info.is_null() || count == 0 { - None - } else { - Some(DeviceInfo { - xconn, - info, - count: count as usize, - }) - } - }) - } - } -} - -impl<'a> Drop for DeviceInfo<'a> { - fn drop(&mut self) { - assert!(!self.info.is_null()); - unsafe { (self.xconn.xinput2.XIFreeDeviceInfo)(self.info as *mut _) }; - } -} - -impl<'a> Deref for DeviceInfo<'a> { - type Target = [ffi::XIDeviceInfo]; - fn deref(&self) -> &Self::Target { - unsafe { slice::from_raw_parts(self.info, self.count) } - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct WindowId(ffi::Window); - -impl WindowId { - pub unsafe fn dummy() -> Self { - WindowId(0) - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct DeviceId(c_int); - -impl DeviceId { - pub unsafe fn dummy() -> Self { - DeviceId(0) - } -} - -pub struct Window(Arc); - -impl Deref for Window { - type Target = UnownedWindow; - #[inline] - fn deref(&self) -> &UnownedWindow { - &*self.0 - } -} - -impl Window { - pub fn new( - event_loop: &EventsLoop, - attribs: WindowAttributes, - pl_attribs: PlatformSpecificWindowBuilderAttributes - ) -> Result { - let window = Arc::new(UnownedWindow::new(&event_loop, attribs, pl_attribs)?); - event_loop.windows - .borrow_mut() - .insert(window.id(), Arc::downgrade(&window)); - Ok(Window(window)) - } -} - -impl Drop for Window { - fn drop(&mut self) { - let window = self.deref(); - let xconn = &window.xconn; - unsafe { - (xconn.xlib.XDestroyWindow)(xconn.display, window.id().0); - // If the window was somehow already destroyed, we'll get a `BadWindow` error, which we don't care about. - let _ = xconn.check_errors(); - } - } -} - -/// XEvents of type GenericEvent store their actual data in an XGenericEventCookie data structure. This is a wrapper to -/// extract the cookie from a GenericEvent XEvent and release the cookie data once it has been processed -struct GenericEventCookie<'a> { - xconn: &'a XConnection, - cookie: ffi::XGenericEventCookie -} - -impl<'a> GenericEventCookie<'a> { - fn from_event<'b>(xconn: &'b XConnection, event: ffi::XEvent) -> Option> { - unsafe { - let mut cookie: ffi::XGenericEventCookie = From::from(event); - if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == ffi::True { - Some(GenericEventCookie { xconn, cookie }) - } else { - None + for keycode in &keys { + if keycode < 8 { + continue; } + + let scancode = (keycode - 8) as u32; + let keysym = wt.xconn.keycode_to_keysym(keycode); + let virtual_keycode = events::keysym_to_element(keysym as c_uint); + + #[allow(deprecated)] + callback(Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { + device_id, + input: KeyboardInput { + scancode, + state, + virtual_keycode, + modifiers, + }, + is_synthetic: true, + }, + }); } } } -impl<'a> Drop for GenericEventCookie<'a> { - fn drop(&mut self) { - unsafe { - (self.xconn.xlib.XFreeEventData)(self.xconn.display, &mut self.cookie); - } - } -} - -#[derive(Debug, Copy, Clone)] -struct XExtension { - opcode: c_int, - first_event_id: c_int, - first_error_id: c_int, -} - -fn mkwid(w: ffi::Window) -> ::WindowId { ::WindowId(::platform::WindowId::X(WindowId(w))) } -fn mkdid(w: c_int) -> ::DeviceId { ::DeviceId(::platform::DeviceId::X(DeviceId(w))) } - -#[derive(Debug)] -struct Device { - name: String, - scroll_axes: Vec<(i32, ScrollAxis)>, - // For master devices, this is the paired device (pointer <-> keyboard). - // For slave devices, this is the master. - attachment: c_int, -} - -#[derive(Debug, Copy, Clone)] -struct ScrollAxis { - increment: f64, - orientation: ScrollOrientation, - position: f64, -} - -#[derive(Debug, Copy, Clone)] -enum ScrollOrientation { - Vertical, - Horizontal, -} - -impl Device { - fn new(el: &EventsLoop, info: &ffi::XIDeviceInfo) -> Self { - let name = unsafe { CStr::from_ptr(info.name).to_string_lossy() }; - let mut scroll_axes = Vec::new(); - - if Device::physical_device(info) { - // Register for global raw events - let mask = ffi::XI_RawMotionMask - | ffi::XI_RawButtonPressMask - | ffi::XI_RawButtonReleaseMask - | ffi::XI_RawKeyPressMask - | ffi::XI_RawKeyReleaseMask; - // The request buffer is flushed when we poll for events - el.xconn.select_xinput_events(el.root, info.deviceid, mask).queue(); - - // Identify scroll axes - for class_ptr in Device::classes(info) { - let class = unsafe { &**class_ptr }; - match class._type { - ffi::XIScrollClass => { - let info = unsafe { mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIScrollClassInfo>(class) }; - scroll_axes.push((info.number, ScrollAxis { - increment: info.increment, - orientation: match info.scroll_type { - ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, - ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, - _ => { unreachable!() } - }, - position: 0.0, - })); - } - _ => {} - } +fn is_first_touch(first: &mut Option, num: &mut u32, id: u64, phase: TouchPhase) -> bool { + match phase { + TouchPhase::Started => { + if *num == 0 { + *first = Some(id); } + *num += 1; } - - let mut device = Device { - name: name.into_owned(), - scroll_axes: scroll_axes, - attachment: info.attachment, - }; - device.reset_scroll_position(info); - device - } - - fn reset_scroll_position(&mut self, info: &ffi::XIDeviceInfo) { - if Device::physical_device(info) { - for class_ptr in Device::classes(info) { - let class = unsafe { &**class_ptr }; - match class._type { - ffi::XIValuatorClass => { - let info = unsafe { mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIValuatorClassInfo>(class) }; - if let Some(&mut (_, ref mut axis)) = self.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == info.number) { - axis.position = info.value; - } - } - _ => {} - } + TouchPhase::Cancelled | TouchPhase::Ended => { + if *first == Some(id) { + *first = None; } + *num = num.saturating_sub(1); } + _ => (), } - #[inline] - fn physical_device(info: &ffi::XIDeviceInfo) -> bool { - info._use == ffi::XISlaveKeyboard || info._use == ffi::XISlavePointer || info._use == ffi::XIFloatingSlave - } - - #[inline] - fn classes(info: &ffi::XIDeviceInfo) -> &[*const ffi::XIAnyClassInfo] { - unsafe { slice::from_raw_parts(info.classes as *const *const ffi::XIAnyClassInfo, info.num_classes as usize) } - } + *first == Some(id) } diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/events.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/events.rs new file mode 100644 index 0000000..1b4996e --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/events.rs @@ -0,0 +1,1008 @@ +use super::ffi; +use crate::event::VirtualKeyCode; +use libc; + +pub fn keysym_to_element(keysym: libc::c_uint) -> Option { + Some(match keysym { + ffi::XK_BackSpace => VirtualKeyCode::Back, + ffi::XK_Tab => VirtualKeyCode::Tab, + //ffi::XK_Linefeed => VirtualKeyCode::Linefeed, + //ffi::XK_Clear => VirtualKeyCode::Clear, + ffi::XK_Return => VirtualKeyCode::Return, + //ffi::XK_Pause => VirtualKeyCode::Pause, + //ffi::XK_Scroll_Lock => VirtualKeyCode::Scroll_lock, + //ffi::XK_Sys_Req => VirtualKeyCode::Sys_req, + ffi::XK_Escape => VirtualKeyCode::Escape, + ffi::XK_Delete => VirtualKeyCode::Delete, + ffi::XK_Multi_key => VirtualKeyCode::Compose, + //ffi::XK_Kanji => VirtualKeyCode::Kanji, + //ffi::XK_Muhenkan => VirtualKeyCode::Muhenkan, + //ffi::XK_Henkan_Mode => VirtualKeyCode::Henkan_mode, + //ffi::XK_Henkan => VirtualKeyCode::Henkan, + //ffi::XK_Romaji => VirtualKeyCode::Romaji, + //ffi::XK_Hiragana => VirtualKeyCode::Hiragana, + //ffi::XK_Katakana => VirtualKeyCode::Katakana, + //ffi::XK_Hiragana_Katakana => VirtualKeyCode::Hiragana_katakana, + //ffi::XK_Zenkaku => VirtualKeyCode::Zenkaku, + //ffi::XK_Hankaku => VirtualKeyCode::Hankaku, + //ffi::XK_Zenkaku_Hankaku => VirtualKeyCode::Zenkaku_hankaku, + //ffi::XK_Touroku => VirtualKeyCode::Touroku, + //ffi::XK_Massyo => VirtualKeyCode::Massyo, + //ffi::XK_Kana_Lock => VirtualKeyCode::Kana_lock, + //ffi::XK_Kana_Shift => VirtualKeyCode::Kana_shift, + //ffi::XK_Eisu_Shift => VirtualKeyCode::Eisu_shift, + //ffi::XK_Eisu_toggle => VirtualKeyCode::Eisu_toggle, + ffi::XK_Home => VirtualKeyCode::Home, + ffi::XK_Left => VirtualKeyCode::Left, + ffi::XK_Up => VirtualKeyCode::Up, + ffi::XK_Right => VirtualKeyCode::Right, + ffi::XK_Down => VirtualKeyCode::Down, + //ffi::XK_Prior => VirtualKeyCode::Prior, + ffi::XK_Page_Up => VirtualKeyCode::PageUp, + //ffi::XK_Next => VirtualKeyCode::Next, + ffi::XK_Page_Down => VirtualKeyCode::PageDown, + ffi::XK_End => VirtualKeyCode::End, + //ffi::XK_Begin => VirtualKeyCode::Begin, + //ffi::XK_Win_L => VirtualKeyCode::Win_l, + //ffi::XK_Win_R => VirtualKeyCode::Win_r, + //ffi::XK_App => VirtualKeyCode::App, + //ffi::XK_Select => VirtualKeyCode::Select, + //ffi::XK_Print => VirtualKeyCode::Print, + //ffi::XK_Execute => VirtualKeyCode::Execute, + ffi::XK_Insert => VirtualKeyCode::Insert, + //ffi::XK_Undo => VirtualKeyCode::Undo, + //ffi::XK_Redo => VirtualKeyCode::Redo, + //ffi::XK_Menu => VirtualKeyCode::Menu, + //ffi::XK_Find => VirtualKeyCode::Find, + //ffi::XK_Cancel => VirtualKeyCode::Cancel, + //ffi::XK_Help => VirtualKeyCode::Help, + //ffi::XK_Break => VirtualKeyCode::Break, + //ffi::XK_Mode_switch => VirtualKeyCode::Mode_switch, + //ffi::XK_script_switch => VirtualKeyCode::Script_switch, + //ffi::XK_Num_Lock => VirtualKeyCode::Num_lock, + //ffi::XK_KP_Space => VirtualKeyCode::Kp_space, + //ffi::XK_KP_Tab => VirtualKeyCode::Kp_tab, + //ffi::XK_KP_Enter => VirtualKeyCode::Kp_enter, + //ffi::XK_KP_F1 => VirtualKeyCode::Kp_f1, + //ffi::XK_KP_F2 => VirtualKeyCode::Kp_f2, + //ffi::XK_KP_F3 => VirtualKeyCode::Kp_f3, + //ffi::XK_KP_F4 => VirtualKeyCode::Kp_f4, + ffi::XK_KP_Home => VirtualKeyCode::Home, + ffi::XK_KP_Left => VirtualKeyCode::Left, + ffi::XK_KP_Up => VirtualKeyCode::Up, + ffi::XK_KP_Right => VirtualKeyCode::Right, + ffi::XK_KP_Down => VirtualKeyCode::Down, + //ffi::XK_KP_Prior => VirtualKeyCode::Kp_prior, + ffi::XK_KP_Page_Up => VirtualKeyCode::PageUp, + //ffi::XK_KP_Next => VirtualKeyCode::Kp_next, + ffi::XK_KP_Page_Down => VirtualKeyCode::PageDown, + ffi::XK_KP_End => VirtualKeyCode::End, + //ffi::XK_KP_Begin => VirtualKeyCode::Kp_begin, + ffi::XK_KP_Insert => VirtualKeyCode::Insert, + ffi::XK_KP_Delete => VirtualKeyCode::Delete, + ffi::XK_KP_Equal => VirtualKeyCode::NumpadEquals, + //ffi::XK_KP_Multiply => VirtualKeyCode::NumpadMultiply, + ffi::XK_KP_Add => VirtualKeyCode::Add, + //ffi::XK_KP_Separator => VirtualKeyCode::Kp_separator, + ffi::XK_KP_Subtract => VirtualKeyCode::Subtract, + //ffi::XK_KP_Decimal => VirtualKeyCode::Kp_decimal, + ffi::XK_KP_Divide => VirtualKeyCode::Divide, + ffi::XK_KP_0 => VirtualKeyCode::Numpad0, + ffi::XK_KP_1 => VirtualKeyCode::Numpad1, + ffi::XK_KP_2 => VirtualKeyCode::Numpad2, + ffi::XK_KP_3 => VirtualKeyCode::Numpad3, + ffi::XK_KP_4 => VirtualKeyCode::Numpad4, + ffi::XK_KP_5 => VirtualKeyCode::Numpad5, + ffi::XK_KP_6 => VirtualKeyCode::Numpad6, + ffi::XK_KP_7 => VirtualKeyCode::Numpad7, + ffi::XK_KP_8 => VirtualKeyCode::Numpad8, + ffi::XK_KP_9 => VirtualKeyCode::Numpad9, + ffi::XK_F1 => VirtualKeyCode::F1, + ffi::XK_F2 => VirtualKeyCode::F2, + ffi::XK_F3 => VirtualKeyCode::F3, + ffi::XK_F4 => VirtualKeyCode::F4, + ffi::XK_F5 => VirtualKeyCode::F5, + ffi::XK_F6 => VirtualKeyCode::F6, + ffi::XK_F7 => VirtualKeyCode::F7, + ffi::XK_F8 => VirtualKeyCode::F8, + ffi::XK_F9 => VirtualKeyCode::F9, + ffi::XK_F10 => VirtualKeyCode::F10, + ffi::XK_F11 => VirtualKeyCode::F11, + //ffi::XK_L1 => VirtualKeyCode::L1, + ffi::XK_F12 => VirtualKeyCode::F12, + //ffi::XK_L2 => VirtualKeyCode::L2, + ffi::XK_F13 => VirtualKeyCode::F13, + //ffi::XK_L3 => VirtualKeyCode::L3, + ffi::XK_F14 => VirtualKeyCode::F14, + //ffi::XK_L4 => VirtualKeyCode::L4, + ffi::XK_F15 => VirtualKeyCode::F15, + //ffi::XK_L5 => VirtualKeyCode::L5, + ffi::XK_F16 => VirtualKeyCode::F16, + //ffi::XK_L6 => VirtualKeyCode::L6, + ffi::XK_F17 => VirtualKeyCode::F17, + //ffi::XK_L7 => VirtualKeyCode::L7, + ffi::XK_F18 => VirtualKeyCode::F18, + //ffi::XK_L8 => VirtualKeyCode::L8, + ffi::XK_F19 => VirtualKeyCode::F19, + //ffi::XK_L9 => VirtualKeyCode::L9, + ffi::XK_F20 => VirtualKeyCode::F20, + //ffi::XK_L10 => VirtualKeyCode::L10, + ffi::XK_F21 => VirtualKeyCode::F21, + //ffi::XK_R1 => VirtualKeyCode::R1, + ffi::XK_F22 => VirtualKeyCode::F22, + //ffi::XK_R2 => VirtualKeyCode::R2, + ffi::XK_F23 => VirtualKeyCode::F23, + //ffi::XK_R3 => VirtualKeyCode::R3, + ffi::XK_F24 => VirtualKeyCode::F24, + //ffi::XK_R4 => VirtualKeyCode::R4, + //ffi::XK_F25 => VirtualKeyCode::F25, + //ffi::XK_R5 => VirtualKeyCode::R5, + //ffi::XK_F26 => VirtualKeyCode::F26, + //ffi::XK_R6 => VirtualKeyCode::R6, + //ffi::XK_F27 => VirtualKeyCode::F27, + //ffi::XK_R7 => VirtualKeyCode::R7, + //ffi::XK_F28 => VirtualKeyCode::F28, + //ffi::XK_R8 => VirtualKeyCode::R8, + //ffi::XK_F29 => VirtualKeyCode::F29, + //ffi::XK_R9 => VirtualKeyCode::R9, + //ffi::XK_F30 => VirtualKeyCode::F30, + //ffi::XK_R10 => VirtualKeyCode::R10, + //ffi::XK_F31 => VirtualKeyCode::F31, + //ffi::XK_R11 => VirtualKeyCode::R11, + //ffi::XK_F32 => VirtualKeyCode::F32, + //ffi::XK_R12 => VirtualKeyCode::R12, + //ffi::XK_F33 => VirtualKeyCode::F33, + //ffi::XK_R13 => VirtualKeyCode::R13, + //ffi::XK_F34 => VirtualKeyCode::F34, + //ffi::XK_R14 => VirtualKeyCode::R14, + //ffi::XK_F35 => VirtualKeyCode::F35, + //ffi::XK_R15 => VirtualKeyCode::R15, + ffi::XK_Shift_L => VirtualKeyCode::LShift, + ffi::XK_Shift_R => VirtualKeyCode::RShift, + ffi::XK_Control_L => VirtualKeyCode::LControl, + ffi::XK_Control_R => VirtualKeyCode::RControl, + //ffi::XK_Caps_Lock => VirtualKeyCode::Caps_lock, + //ffi::XK_Shift_Lock => VirtualKeyCode::Shift_lock, + //ffi::XK_Meta_L => VirtualKeyCode::Meta_l, + //ffi::XK_Meta_R => VirtualKeyCode::Meta_r, + ffi::XK_Alt_L => VirtualKeyCode::LAlt, + ffi::XK_Alt_R => VirtualKeyCode::RAlt, + //ffi::XK_Super_L => VirtualKeyCode::Super_l, + //ffi::XK_Super_R => VirtualKeyCode::Super_r, + //ffi::XK_Hyper_L => VirtualKeyCode::Hyper_l, + //ffi::XK_Hyper_R => VirtualKeyCode::Hyper_r, + ffi::XK_ISO_Left_Tab => VirtualKeyCode::Tab, + ffi::XK_space => VirtualKeyCode::Space, + //ffi::XK_exclam => VirtualKeyCode::Exclam, + //ffi::XK_quotedbl => VirtualKeyCode::Quotedbl, + //ffi::XK_numbersign => VirtualKeyCode::Numbersign, + //ffi::XK_dollar => VirtualKeyCode::Dollar, + //ffi::XK_percent => VirtualKeyCode::Percent, + //ffi::XK_ampersand => VirtualKeyCode::Ampersand, + ffi::XK_apostrophe => VirtualKeyCode::Apostrophe, + //ffi::XK_quoteright => VirtualKeyCode::Quoteright, + //ffi::XK_parenleft => VirtualKeyCode::Parenleft, + //ffi::XK_parenright => VirtualKeyCode::Parenright, + //ffi::XK_asterisk => VirtualKeyCode::Asterisk, + ffi::XK_plus => VirtualKeyCode::Add, + ffi::XK_comma => VirtualKeyCode::Comma, + ffi::XK_minus => VirtualKeyCode::Subtract, + ffi::XK_period => VirtualKeyCode::Period, + ffi::XK_slash => VirtualKeyCode::Slash, + ffi::XK_0 => VirtualKeyCode::Key0, + ffi::XK_1 => VirtualKeyCode::Key1, + ffi::XK_2 => VirtualKeyCode::Key2, + ffi::XK_3 => VirtualKeyCode::Key3, + ffi::XK_4 => VirtualKeyCode::Key4, + ffi::XK_5 => VirtualKeyCode::Key5, + ffi::XK_6 => VirtualKeyCode::Key6, + ffi::XK_7 => VirtualKeyCode::Key7, + ffi::XK_8 => VirtualKeyCode::Key8, + ffi::XK_9 => VirtualKeyCode::Key9, + ffi::XK_colon => VirtualKeyCode::Colon, + ffi::XK_semicolon => VirtualKeyCode::Semicolon, + //ffi::XK_less => VirtualKeyCode::Less, + ffi::XK_equal => VirtualKeyCode::Equals, + //ffi::XK_greater => VirtualKeyCode::Greater, + //ffi::XK_question => VirtualKeyCode::Question, + ffi::XK_at => VirtualKeyCode::At, + ffi::XK_A => VirtualKeyCode::A, + ffi::XK_B => VirtualKeyCode::B, + ffi::XK_C => VirtualKeyCode::C, + ffi::XK_D => VirtualKeyCode::D, + ffi::XK_E => VirtualKeyCode::E, + ffi::XK_F => VirtualKeyCode::F, + ffi::XK_G => VirtualKeyCode::G, + ffi::XK_H => VirtualKeyCode::H, + ffi::XK_I => VirtualKeyCode::I, + ffi::XK_J => VirtualKeyCode::J, + ffi::XK_K => VirtualKeyCode::K, + ffi::XK_L => VirtualKeyCode::L, + ffi::XK_M => VirtualKeyCode::M, + ffi::XK_N => VirtualKeyCode::N, + ffi::XK_O => VirtualKeyCode::O, + ffi::XK_P => VirtualKeyCode::P, + ffi::XK_Q => VirtualKeyCode::Q, + ffi::XK_R => VirtualKeyCode::R, + ffi::XK_S => VirtualKeyCode::S, + ffi::XK_T => VirtualKeyCode::T, + ffi::XK_U => VirtualKeyCode::U, + ffi::XK_V => VirtualKeyCode::V, + ffi::XK_W => VirtualKeyCode::W, + ffi::XK_X => VirtualKeyCode::X, + ffi::XK_Y => VirtualKeyCode::Y, + ffi::XK_Z => VirtualKeyCode::Z, + ffi::XK_bracketleft => VirtualKeyCode::LBracket, + ffi::XK_backslash => VirtualKeyCode::Backslash, + ffi::XK_bracketright => VirtualKeyCode::RBracket, + //ffi::XK_asciicircum => VirtualKeyCode::Asciicircum, + //ffi::XK_underscore => VirtualKeyCode::Underscore, + ffi::XK_grave => VirtualKeyCode::Grave, + //ffi::XK_quoteleft => VirtualKeyCode::Quoteleft, + ffi::XK_a => VirtualKeyCode::A, + ffi::XK_b => VirtualKeyCode::B, + ffi::XK_c => VirtualKeyCode::C, + ffi::XK_d => VirtualKeyCode::D, + ffi::XK_e => VirtualKeyCode::E, + ffi::XK_f => VirtualKeyCode::F, + ffi::XK_g => VirtualKeyCode::G, + ffi::XK_h => VirtualKeyCode::H, + ffi::XK_i => VirtualKeyCode::I, + ffi::XK_j => VirtualKeyCode::J, + ffi::XK_k => VirtualKeyCode::K, + ffi::XK_l => VirtualKeyCode::L, + ffi::XK_m => VirtualKeyCode::M, + ffi::XK_n => VirtualKeyCode::N, + ffi::XK_o => VirtualKeyCode::O, + ffi::XK_p => VirtualKeyCode::P, + ffi::XK_q => VirtualKeyCode::Q, + ffi::XK_r => VirtualKeyCode::R, + ffi::XK_s => VirtualKeyCode::S, + ffi::XK_t => VirtualKeyCode::T, + ffi::XK_u => VirtualKeyCode::U, + ffi::XK_v => VirtualKeyCode::V, + ffi::XK_w => VirtualKeyCode::W, + ffi::XK_x => VirtualKeyCode::X, + ffi::XK_y => VirtualKeyCode::Y, + ffi::XK_z => VirtualKeyCode::Z, + //ffi::XK_braceleft => VirtualKeyCode::Braceleft, + //ffi::XK_bar => VirtualKeyCode::Bar, + //ffi::XK_braceright => VirtualKeyCode::Braceright, + //ffi::XK_asciitilde => VirtualKeyCode::Asciitilde, + //ffi::XK_nobreakspace => VirtualKeyCode::Nobreakspace, + //ffi::XK_exclamdown => VirtualKeyCode::Exclamdown, + //ffi::XK_cent => VirtualKeyCode::Cent, + //ffi::XK_sterling => VirtualKeyCode::Sterling, + //ffi::XK_currency => VirtualKeyCode::Currency, + //ffi::XK_yen => VirtualKeyCode::Yen, + //ffi::XK_brokenbar => VirtualKeyCode::Brokenbar, + //ffi::XK_section => VirtualKeyCode::Section, + //ffi::XK_diaeresis => VirtualKeyCode::Diaeresis, + //ffi::XK_copyright => VirtualKeyCode::Copyright, + //ffi::XK_ordfeminine => VirtualKeyCode::Ordfeminine, + //ffi::XK_guillemotleft => VirtualKeyCode::Guillemotleft, + //ffi::XK_notsign => VirtualKeyCode::Notsign, + //ffi::XK_hyphen => VirtualKeyCode::Hyphen, + //ffi::XK_registered => VirtualKeyCode::Registered, + //ffi::XK_macron => VirtualKeyCode::Macron, + //ffi::XK_degree => VirtualKeyCode::Degree, + //ffi::XK_plusminus => VirtualKeyCode::Plusminus, + //ffi::XK_twosuperior => VirtualKeyCode::Twosuperior, + //ffi::XK_threesuperior => VirtualKeyCode::Threesuperior, + //ffi::XK_acute => VirtualKeyCode::Acute, + //ffi::XK_mu => VirtualKeyCode::Mu, + //ffi::XK_paragraph => VirtualKeyCode::Paragraph, + //ffi::XK_periodcentered => VirtualKeyCode::Periodcentered, + //ffi::XK_cedilla => VirtualKeyCode::Cedilla, + //ffi::XK_onesuperior => VirtualKeyCode::Onesuperior, + //ffi::XK_masculine => VirtualKeyCode::Masculine, + //ffi::XK_guillemotright => VirtualKeyCode::Guillemotright, + //ffi::XK_onequarter => VirtualKeyCode::Onequarter, + //ffi::XK_onehalf => VirtualKeyCode::Onehalf, + //ffi::XK_threequarters => VirtualKeyCode::Threequarters, + //ffi::XK_questiondown => VirtualKeyCode::Questiondown, + //ffi::XK_Agrave => VirtualKeyCode::Agrave, + //ffi::XK_Aacute => VirtualKeyCode::Aacute, + //ffi::XK_Acircumflex => VirtualKeyCode::Acircumflex, + //ffi::XK_Atilde => VirtualKeyCode::Atilde, + //ffi::XK_Adiaeresis => VirtualKeyCode::Adiaeresis, + //ffi::XK_Aring => VirtualKeyCode::Aring, + //ffi::XK_AE => VirtualKeyCode::Ae, + //ffi::XK_Ccedilla => VirtualKeyCode::Ccedilla, + //ffi::XK_Egrave => VirtualKeyCode::Egrave, + //ffi::XK_Eacute => VirtualKeyCode::Eacute, + //ffi::XK_Ecircumflex => VirtualKeyCode::Ecircumflex, + //ffi::XK_Ediaeresis => VirtualKeyCode::Ediaeresis, + //ffi::XK_Igrave => VirtualKeyCode::Igrave, + //ffi::XK_Iacute => VirtualKeyCode::Iacute, + //ffi::XK_Icircumflex => VirtualKeyCode::Icircumflex, + //ffi::XK_Idiaeresis => VirtualKeyCode::Idiaeresis, + //ffi::XK_ETH => VirtualKeyCode::Eth, + //ffi::XK_Eth => VirtualKeyCode::Eth, + //ffi::XK_Ntilde => VirtualKeyCode::Ntilde, + //ffi::XK_Ograve => VirtualKeyCode::Ograve, + //ffi::XK_Oacute => VirtualKeyCode::Oacute, + //ffi::XK_Ocircumflex => VirtualKeyCode::Ocircumflex, + //ffi::XK_Otilde => VirtualKeyCode::Otilde, + //ffi::XK_Odiaeresis => VirtualKeyCode::Odiaeresis, + //ffi::XK_multiply => VirtualKeyCode::Multiply, + //ffi::XK_Ooblique => VirtualKeyCode::Ooblique, + //ffi::XK_Ugrave => VirtualKeyCode::Ugrave, + //ffi::XK_Uacute => VirtualKeyCode::Uacute, + //ffi::XK_Ucircumflex => VirtualKeyCode::Ucircumflex, + //ffi::XK_Udiaeresis => VirtualKeyCode::Udiaeresis, + //ffi::XK_Yacute => VirtualKeyCode::Yacute, + //ffi::XK_THORN => VirtualKeyCode::Thorn, + //ffi::XK_Thorn => VirtualKeyCode::Thorn, + //ffi::XK_ssharp => VirtualKeyCode::Ssharp, + //ffi::XK_agrave => VirtualKeyCode::Agrave, + //ffi::XK_aacute => VirtualKeyCode::Aacute, + //ffi::XK_acircumflex => VirtualKeyCode::Acircumflex, + //ffi::XK_atilde => VirtualKeyCode::Atilde, + //ffi::XK_adiaeresis => VirtualKeyCode::Adiaeresis, + //ffi::XK_aring => VirtualKeyCode::Aring, + //ffi::XK_ae => VirtualKeyCode::Ae, + //ffi::XK_ccedilla => VirtualKeyCode::Ccedilla, + //ffi::XK_egrave => VirtualKeyCode::Egrave, + //ffi::XK_eacute => VirtualKeyCode::Eacute, + //ffi::XK_ecircumflex => VirtualKeyCode::Ecircumflex, + //ffi::XK_ediaeresis => VirtualKeyCode::Ediaeresis, + //ffi::XK_igrave => VirtualKeyCode::Igrave, + //ffi::XK_iacute => VirtualKeyCode::Iacute, + //ffi::XK_icircumflex => VirtualKeyCode::Icircumflex, + //ffi::XK_idiaeresis => VirtualKeyCode::Idiaeresis, + //ffi::XK_eth => VirtualKeyCode::Eth, + //ffi::XK_ntilde => VirtualKeyCode::Ntilde, + //ffi::XK_ograve => VirtualKeyCode::Ograve, + //ffi::XK_oacute => VirtualKeyCode::Oacute, + //ffi::XK_ocircumflex => VirtualKeyCode::Ocircumflex, + //ffi::XK_otilde => VirtualKeyCode::Otilde, + //ffi::XK_odiaeresis => VirtualKeyCode::Odiaeresis, + //ffi::XK_division => VirtualKeyCode::Division, + //ffi::XK_oslash => VirtualKeyCode::Oslash, + //ffi::XK_ugrave => VirtualKeyCode::Ugrave, + //ffi::XK_uacute => VirtualKeyCode::Uacute, + //ffi::XK_ucircumflex => VirtualKeyCode::Ucircumflex, + //ffi::XK_udiaeresis => VirtualKeyCode::Udiaeresis, + //ffi::XK_yacute => VirtualKeyCode::Yacute, + //ffi::XK_thorn => VirtualKeyCode::Thorn, + //ffi::XK_ydiaeresis => VirtualKeyCode::Ydiaeresis, + //ffi::XK_Aogonek => VirtualKeyCode::Aogonek, + //ffi::XK_breve => VirtualKeyCode::Breve, + //ffi::XK_Lstroke => VirtualKeyCode::Lstroke, + //ffi::XK_Lcaron => VirtualKeyCode::Lcaron, + //ffi::XK_Sacute => VirtualKeyCode::Sacute, + //ffi::XK_Scaron => VirtualKeyCode::Scaron, + //ffi::XK_Scedilla => VirtualKeyCode::Scedilla, + //ffi::XK_Tcaron => VirtualKeyCode::Tcaron, + //ffi::XK_Zacute => VirtualKeyCode::Zacute, + //ffi::XK_Zcaron => VirtualKeyCode::Zcaron, + //ffi::XK_Zabovedot => VirtualKeyCode::Zabovedot, + //ffi::XK_aogonek => VirtualKeyCode::Aogonek, + //ffi::XK_ogonek => VirtualKeyCode::Ogonek, + //ffi::XK_lstroke => VirtualKeyCode::Lstroke, + //ffi::XK_lcaron => VirtualKeyCode::Lcaron, + //ffi::XK_sacute => VirtualKeyCode::Sacute, + //ffi::XK_caron => VirtualKeyCode::Caron, + //ffi::XK_scaron => VirtualKeyCode::Scaron, + //ffi::XK_scedilla => VirtualKeyCode::Scedilla, + //ffi::XK_tcaron => VirtualKeyCode::Tcaron, + //ffi::XK_zacute => VirtualKeyCode::Zacute, + //ffi::XK_doubleacute => VirtualKeyCode::Doubleacute, + //ffi::XK_zcaron => VirtualKeyCode::Zcaron, + //ffi::XK_zabovedot => VirtualKeyCode::Zabovedot, + //ffi::XK_Racute => VirtualKeyCode::Racute, + //ffi::XK_Abreve => VirtualKeyCode::Abreve, + //ffi::XK_Lacute => VirtualKeyCode::Lacute, + //ffi::XK_Cacute => VirtualKeyCode::Cacute, + //ffi::XK_Ccaron => VirtualKeyCode::Ccaron, + //ffi::XK_Eogonek => VirtualKeyCode::Eogonek, + //ffi::XK_Ecaron => VirtualKeyCode::Ecaron, + //ffi::XK_Dcaron => VirtualKeyCode::Dcaron, + //ffi::XK_Dstroke => VirtualKeyCode::Dstroke, + //ffi::XK_Nacute => VirtualKeyCode::Nacute, + //ffi::XK_Ncaron => VirtualKeyCode::Ncaron, + //ffi::XK_Odoubleacute => VirtualKeyCode::Odoubleacute, + //ffi::XK_Rcaron => VirtualKeyCode::Rcaron, + //ffi::XK_Uring => VirtualKeyCode::Uring, + //ffi::XK_Udoubleacute => VirtualKeyCode::Udoubleacute, + //ffi::XK_Tcedilla => VirtualKeyCode::Tcedilla, + //ffi::XK_racute => VirtualKeyCode::Racute, + //ffi::XK_abreve => VirtualKeyCode::Abreve, + //ffi::XK_lacute => VirtualKeyCode::Lacute, + //ffi::XK_cacute => VirtualKeyCode::Cacute, + //ffi::XK_ccaron => VirtualKeyCode::Ccaron, + //ffi::XK_eogonek => VirtualKeyCode::Eogonek, + //ffi::XK_ecaron => VirtualKeyCode::Ecaron, + //ffi::XK_dcaron => VirtualKeyCode::Dcaron, + //ffi::XK_dstroke => VirtualKeyCode::Dstroke, + //ffi::XK_nacute => VirtualKeyCode::Nacute, + //ffi::XK_ncaron => VirtualKeyCode::Ncaron, + //ffi::XK_odoubleacute => VirtualKeyCode::Odoubleacute, + //ffi::XK_udoubleacute => VirtualKeyCode::Udoubleacute, + //ffi::XK_rcaron => VirtualKeyCode::Rcaron, + //ffi::XK_uring => VirtualKeyCode::Uring, + //ffi::XK_tcedilla => VirtualKeyCode::Tcedilla, + //ffi::XK_abovedot => VirtualKeyCode::Abovedot, + //ffi::XK_Hstroke => VirtualKeyCode::Hstroke, + //ffi::XK_Hcircumflex => VirtualKeyCode::Hcircumflex, + //ffi::XK_Iabovedot => VirtualKeyCode::Iabovedot, + //ffi::XK_Gbreve => VirtualKeyCode::Gbreve, + //ffi::XK_Jcircumflex => VirtualKeyCode::Jcircumflex, + //ffi::XK_hstroke => VirtualKeyCode::Hstroke, + //ffi::XK_hcircumflex => VirtualKeyCode::Hcircumflex, + //ffi::XK_idotless => VirtualKeyCode::Idotless, + //ffi::XK_gbreve => VirtualKeyCode::Gbreve, + //ffi::XK_jcircumflex => VirtualKeyCode::Jcircumflex, + //ffi::XK_Cabovedot => VirtualKeyCode::Cabovedot, + //ffi::XK_Ccircumflex => VirtualKeyCode::Ccircumflex, + //ffi::XK_Gabovedot => VirtualKeyCode::Gabovedot, + //ffi::XK_Gcircumflex => VirtualKeyCode::Gcircumflex, + //ffi::XK_Ubreve => VirtualKeyCode::Ubreve, + //ffi::XK_Scircumflex => VirtualKeyCode::Scircumflex, + //ffi::XK_cabovedot => VirtualKeyCode::Cabovedot, + //ffi::XK_ccircumflex => VirtualKeyCode::Ccircumflex, + //ffi::XK_gabovedot => VirtualKeyCode::Gabovedot, + //ffi::XK_gcircumflex => VirtualKeyCode::Gcircumflex, + //ffi::XK_ubreve => VirtualKeyCode::Ubreve, + //ffi::XK_scircumflex => VirtualKeyCode::Scircumflex, + //ffi::XK_kra => VirtualKeyCode::Kra, + //ffi::XK_kappa => VirtualKeyCode::Kappa, + //ffi::XK_Rcedilla => VirtualKeyCode::Rcedilla, + //ffi::XK_Itilde => VirtualKeyCode::Itilde, + //ffi::XK_Lcedilla => VirtualKeyCode::Lcedilla, + //ffi::XK_Emacron => VirtualKeyCode::Emacron, + //ffi::XK_Gcedilla => VirtualKeyCode::Gcedilla, + //ffi::XK_Tslash => VirtualKeyCode::Tslash, + //ffi::XK_rcedilla => VirtualKeyCode::Rcedilla, + //ffi::XK_itilde => VirtualKeyCode::Itilde, + //ffi::XK_lcedilla => VirtualKeyCode::Lcedilla, + //ffi::XK_emacron => VirtualKeyCode::Emacron, + //ffi::XK_gcedilla => VirtualKeyCode::Gcedilla, + //ffi::XK_tslash => VirtualKeyCode::Tslash, + //ffi::XK_ENG => VirtualKeyCode::Eng, + //ffi::XK_eng => VirtualKeyCode::Eng, + //ffi::XK_Amacron => VirtualKeyCode::Amacron, + //ffi::XK_Iogonek => VirtualKeyCode::Iogonek, + //ffi::XK_Eabovedot => VirtualKeyCode::Eabovedot, + //ffi::XK_Imacron => VirtualKeyCode::Imacron, + //ffi::XK_Ncedilla => VirtualKeyCode::Ncedilla, + //ffi::XK_Omacron => VirtualKeyCode::Omacron, + //ffi::XK_Kcedilla => VirtualKeyCode::Kcedilla, + //ffi::XK_Uogonek => VirtualKeyCode::Uogonek, + //ffi::XK_Utilde => VirtualKeyCode::Utilde, + //ffi::XK_Umacron => VirtualKeyCode::Umacron, + //ffi::XK_amacron => VirtualKeyCode::Amacron, + //ffi::XK_iogonek => VirtualKeyCode::Iogonek, + //ffi::XK_eabovedot => VirtualKeyCode::Eabovedot, + //ffi::XK_imacron => VirtualKeyCode::Imacron, + //ffi::XK_ncedilla => VirtualKeyCode::Ncedilla, + //ffi::XK_omacron => VirtualKeyCode::Omacron, + //ffi::XK_kcedilla => VirtualKeyCode::Kcedilla, + //ffi::XK_uogonek => VirtualKeyCode::Uogonek, + //ffi::XK_utilde => VirtualKeyCode::Utilde, + //ffi::XK_umacron => VirtualKeyCode::Umacron, + //ffi::XK_overline => VirtualKeyCode::Overline, + //ffi::XK_kana_fullstop => VirtualKeyCode::Kana_fullstop, + //ffi::XK_kana_openingbracket => VirtualKeyCode::Kana_openingbracket, + //ffi::XK_kana_closingbracket => VirtualKeyCode::Kana_closingbracket, + //ffi::XK_kana_comma => VirtualKeyCode::Kana_comma, + //ffi::XK_kana_conjunctive => VirtualKeyCode::Kana_conjunctive, + //ffi::XK_kana_middledot => VirtualKeyCode::Kana_middledot, + //ffi::XK_kana_WO => VirtualKeyCode::Kana_wo, + //ffi::XK_kana_a => VirtualKeyCode::Kana_a, + //ffi::XK_kana_i => VirtualKeyCode::Kana_i, + //ffi::XK_kana_u => VirtualKeyCode::Kana_u, + //ffi::XK_kana_e => VirtualKeyCode::Kana_e, + //ffi::XK_kana_o => VirtualKeyCode::Kana_o, + //ffi::XK_kana_ya => VirtualKeyCode::Kana_ya, + //ffi::XK_kana_yu => VirtualKeyCode::Kana_yu, + //ffi::XK_kana_yo => VirtualKeyCode::Kana_yo, + //ffi::XK_kana_tsu => VirtualKeyCode::Kana_tsu, + //ffi::XK_kana_tu => VirtualKeyCode::Kana_tu, + //ffi::XK_prolongedsound => VirtualKeyCode::Prolongedsound, + //ffi::XK_kana_A => VirtualKeyCode::Kana_a, + //ffi::XK_kana_I => VirtualKeyCode::Kana_i, + //ffi::XK_kana_U => VirtualKeyCode::Kana_u, + //ffi::XK_kana_E => VirtualKeyCode::Kana_e, + //ffi::XK_kana_O => VirtualKeyCode::Kana_o, + //ffi::XK_kana_KA => VirtualKeyCode::Kana_ka, + //ffi::XK_kana_KI => VirtualKeyCode::Kana_ki, + //ffi::XK_kana_KU => VirtualKeyCode::Kana_ku, + //ffi::XK_kana_KE => VirtualKeyCode::Kana_ke, + //ffi::XK_kana_KO => VirtualKeyCode::Kana_ko, + //ffi::XK_kana_SA => VirtualKeyCode::Kana_sa, + //ffi::XK_kana_SHI => VirtualKeyCode::Kana_shi, + //ffi::XK_kana_SU => VirtualKeyCode::Kana_su, + //ffi::XK_kana_SE => VirtualKeyCode::Kana_se, + //ffi::XK_kana_SO => VirtualKeyCode::Kana_so, + //ffi::XK_kana_TA => VirtualKeyCode::Kana_ta, + //ffi::XK_kana_CHI => VirtualKeyCode::Kana_chi, + //ffi::XK_kana_TI => VirtualKeyCode::Kana_ti, + //ffi::XK_kana_TSU => VirtualKeyCode::Kana_tsu, + //ffi::XK_kana_TU => VirtualKeyCode::Kana_tu, + //ffi::XK_kana_TE => VirtualKeyCode::Kana_te, + //ffi::XK_kana_TO => VirtualKeyCode::Kana_to, + //ffi::XK_kana_NA => VirtualKeyCode::Kana_na, + //ffi::XK_kana_NI => VirtualKeyCode::Kana_ni, + //ffi::XK_kana_NU => VirtualKeyCode::Kana_nu, + //ffi::XK_kana_NE => VirtualKeyCode::Kana_ne, + //ffi::XK_kana_NO => VirtualKeyCode::Kana_no, + //ffi::XK_kana_HA => VirtualKeyCode::Kana_ha, + //ffi::XK_kana_HI => VirtualKeyCode::Kana_hi, + //ffi::XK_kana_FU => VirtualKeyCode::Kana_fu, + //ffi::XK_kana_HU => VirtualKeyCode::Kana_hu, + //ffi::XK_kana_HE => VirtualKeyCode::Kana_he, + //ffi::XK_kana_HO => VirtualKeyCode::Kana_ho, + //ffi::XK_kana_MA => VirtualKeyCode::Kana_ma, + //ffi::XK_kana_MI => VirtualKeyCode::Kana_mi, + //ffi::XK_kana_MU => VirtualKeyCode::Kana_mu, + //ffi::XK_kana_ME => VirtualKeyCode::Kana_me, + //ffi::XK_kana_MO => VirtualKeyCode::Kana_mo, + //ffi::XK_kana_YA => VirtualKeyCode::Kana_ya, + //ffi::XK_kana_YU => VirtualKeyCode::Kana_yu, + //ffi::XK_kana_YO => VirtualKeyCode::Kana_yo, + //ffi::XK_kana_RA => VirtualKeyCode::Kana_ra, + //ffi::XK_kana_RI => VirtualKeyCode::Kana_ri, + //ffi::XK_kana_RU => VirtualKeyCode::Kana_ru, + //ffi::XK_kana_RE => VirtualKeyCode::Kana_re, + //ffi::XK_kana_RO => VirtualKeyCode::Kana_ro, + //ffi::XK_kana_WA => VirtualKeyCode::Kana_wa, + //ffi::XK_kana_N => VirtualKeyCode::Kana_n, + //ffi::XK_voicedsound => VirtualKeyCode::Voicedsound, + //ffi::XK_semivoicedsound => VirtualKeyCode::Semivoicedsound, + //ffi::XK_kana_switch => VirtualKeyCode::Kana_switch, + //ffi::XK_Arabic_comma => VirtualKeyCode::Arabic_comma, + //ffi::XK_Arabic_semicolon => VirtualKeyCode::Arabic_semicolon, + //ffi::XK_Arabic_question_mark => VirtualKeyCode::Arabic_question_mark, + //ffi::XK_Arabic_hamza => VirtualKeyCode::Arabic_hamza, + //ffi::XK_Arabic_maddaonalef => VirtualKeyCode::Arabic_maddaonalef, + //ffi::XK_Arabic_hamzaonalef => VirtualKeyCode::Arabic_hamzaonalef, + //ffi::XK_Arabic_hamzaonwaw => VirtualKeyCode::Arabic_hamzaonwaw, + //ffi::XK_Arabic_hamzaunderalef => VirtualKeyCode::Arabic_hamzaunderalef, + //ffi::XK_Arabic_hamzaonyeh => VirtualKeyCode::Arabic_hamzaonyeh, + //ffi::XK_Arabic_alef => VirtualKeyCode::Arabic_alef, + //ffi::XK_Arabic_beh => VirtualKeyCode::Arabic_beh, + //ffi::XK_Arabic_tehmarbuta => VirtualKeyCode::Arabic_tehmarbuta, + //ffi::XK_Arabic_teh => VirtualKeyCode::Arabic_teh, + //ffi::XK_Arabic_theh => VirtualKeyCode::Arabic_theh, + //ffi::XK_Arabic_jeem => VirtualKeyCode::Arabic_jeem, + //ffi::XK_Arabic_hah => VirtualKeyCode::Arabic_hah, + //ffi::XK_Arabic_khah => VirtualKeyCode::Arabic_khah, + //ffi::XK_Arabic_dal => VirtualKeyCode::Arabic_dal, + //ffi::XK_Arabic_thal => VirtualKeyCode::Arabic_thal, + //ffi::XK_Arabic_ra => VirtualKeyCode::Arabic_ra, + //ffi::XK_Arabic_zain => VirtualKeyCode::Arabic_zain, + //ffi::XK_Arabic_seen => VirtualKeyCode::Arabic_seen, + //ffi::XK_Arabic_sheen => VirtualKeyCode::Arabic_sheen, + //ffi::XK_Arabic_sad => VirtualKeyCode::Arabic_sad, + //ffi::XK_Arabic_dad => VirtualKeyCode::Arabic_dad, + //ffi::XK_Arabic_tah => VirtualKeyCode::Arabic_tah, + //ffi::XK_Arabic_zah => VirtualKeyCode::Arabic_zah, + //ffi::XK_Arabic_ain => VirtualKeyCode::Arabic_ain, + //ffi::XK_Arabic_ghain => VirtualKeyCode::Arabic_ghain, + //ffi::XK_Arabic_tatweel => VirtualKeyCode::Arabic_tatweel, + //ffi::XK_Arabic_feh => VirtualKeyCode::Arabic_feh, + //ffi::XK_Arabic_qaf => VirtualKeyCode::Arabic_qaf, + //ffi::XK_Arabic_kaf => VirtualKeyCode::Arabic_kaf, + //ffi::XK_Arabic_lam => VirtualKeyCode::Arabic_lam, + //ffi::XK_Arabic_meem => VirtualKeyCode::Arabic_meem, + //ffi::XK_Arabic_noon => VirtualKeyCode::Arabic_noon, + //ffi::XK_Arabic_ha => VirtualKeyCode::Arabic_ha, + //ffi::XK_Arabic_heh => VirtualKeyCode::Arabic_heh, + //ffi::XK_Arabic_waw => VirtualKeyCode::Arabic_waw, + //ffi::XK_Arabic_alefmaksura => VirtualKeyCode::Arabic_alefmaksura, + //ffi::XK_Arabic_yeh => VirtualKeyCode::Arabic_yeh, + //ffi::XK_Arabic_fathatan => VirtualKeyCode::Arabic_fathatan, + //ffi::XK_Arabic_dammatan => VirtualKeyCode::Arabic_dammatan, + //ffi::XK_Arabic_kasratan => VirtualKeyCode::Arabic_kasratan, + //ffi::XK_Arabic_fatha => VirtualKeyCode::Arabic_fatha, + //ffi::XK_Arabic_damma => VirtualKeyCode::Arabic_damma, + //ffi::XK_Arabic_kasra => VirtualKeyCode::Arabic_kasra, + //ffi::XK_Arabic_shadda => VirtualKeyCode::Arabic_shadda, + //ffi::XK_Arabic_sukun => VirtualKeyCode::Arabic_sukun, + //ffi::XK_Arabic_switch => VirtualKeyCode::Arabic_switch, + //ffi::XK_Serbian_dje => VirtualKeyCode::Serbian_dje, + //ffi::XK_Macedonia_gje => VirtualKeyCode::Macedonia_gje, + //ffi::XK_Cyrillic_io => VirtualKeyCode::Cyrillic_io, + //ffi::XK_Ukrainian_ie => VirtualKeyCode::Ukrainian_ie, + //ffi::XK_Ukranian_je => VirtualKeyCode::Ukranian_je, + //ffi::XK_Macedonia_dse => VirtualKeyCode::Macedonia_dse, + //ffi::XK_Ukrainian_i => VirtualKeyCode::Ukrainian_i, + //ffi::XK_Ukranian_i => VirtualKeyCode::Ukranian_i, + //ffi::XK_Ukrainian_yi => VirtualKeyCode::Ukrainian_yi, + //ffi::XK_Ukranian_yi => VirtualKeyCode::Ukranian_yi, + //ffi::XK_Cyrillic_je => VirtualKeyCode::Cyrillic_je, + //ffi::XK_Serbian_je => VirtualKeyCode::Serbian_je, + //ffi::XK_Cyrillic_lje => VirtualKeyCode::Cyrillic_lje, + //ffi::XK_Serbian_lje => VirtualKeyCode::Serbian_lje, + //ffi::XK_Cyrillic_nje => VirtualKeyCode::Cyrillic_nje, + //ffi::XK_Serbian_nje => VirtualKeyCode::Serbian_nje, + //ffi::XK_Serbian_tshe => VirtualKeyCode::Serbian_tshe, + //ffi::XK_Macedonia_kje => VirtualKeyCode::Macedonia_kje, + //ffi::XK_Byelorussian_shortu => VirtualKeyCode::Byelorussian_shortu, + //ffi::XK_Cyrillic_dzhe => VirtualKeyCode::Cyrillic_dzhe, + //ffi::XK_Serbian_dze => VirtualKeyCode::Serbian_dze, + //ffi::XK_numerosign => VirtualKeyCode::Numerosign, + //ffi::XK_Serbian_DJE => VirtualKeyCode::Serbian_dje, + //ffi::XK_Macedonia_GJE => VirtualKeyCode::Macedonia_gje, + //ffi::XK_Cyrillic_IO => VirtualKeyCode::Cyrillic_io, + //ffi::XK_Ukrainian_IE => VirtualKeyCode::Ukrainian_ie, + //ffi::XK_Ukranian_JE => VirtualKeyCode::Ukranian_je, + //ffi::XK_Macedonia_DSE => VirtualKeyCode::Macedonia_dse, + //ffi::XK_Ukrainian_I => VirtualKeyCode::Ukrainian_i, + //ffi::XK_Ukranian_I => VirtualKeyCode::Ukranian_i, + //ffi::XK_Ukrainian_YI => VirtualKeyCode::Ukrainian_yi, + //ffi::XK_Ukranian_YI => VirtualKeyCode::Ukranian_yi, + //ffi::XK_Cyrillic_JE => VirtualKeyCode::Cyrillic_je, + //ffi::XK_Serbian_JE => VirtualKeyCode::Serbian_je, + //ffi::XK_Cyrillic_LJE => VirtualKeyCode::Cyrillic_lje, + //ffi::XK_Serbian_LJE => VirtualKeyCode::Serbian_lje, + //ffi::XK_Cyrillic_NJE => VirtualKeyCode::Cyrillic_nje, + //ffi::XK_Serbian_NJE => VirtualKeyCode::Serbian_nje, + //ffi::XK_Serbian_TSHE => VirtualKeyCode::Serbian_tshe, + //ffi::XK_Macedonia_KJE => VirtualKeyCode::Macedonia_kje, + //ffi::XK_Byelorussian_SHORTU => VirtualKeyCode::Byelorussian_shortu, + //ffi::XK_Cyrillic_DZHE => VirtualKeyCode::Cyrillic_dzhe, + //ffi::XK_Serbian_DZE => VirtualKeyCode::Serbian_dze, + //ffi::XK_Cyrillic_yu => VirtualKeyCode::Cyrillic_yu, + //ffi::XK_Cyrillic_a => VirtualKeyCode::Cyrillic_a, + //ffi::XK_Cyrillic_be => VirtualKeyCode::Cyrillic_be, + //ffi::XK_Cyrillic_tse => VirtualKeyCode::Cyrillic_tse, + //ffi::XK_Cyrillic_de => VirtualKeyCode::Cyrillic_de, + //ffi::XK_Cyrillic_ie => VirtualKeyCode::Cyrillic_ie, + //ffi::XK_Cyrillic_ef => VirtualKeyCode::Cyrillic_ef, + //ffi::XK_Cyrillic_ghe => VirtualKeyCode::Cyrillic_ghe, + //ffi::XK_Cyrillic_ha => VirtualKeyCode::Cyrillic_ha, + //ffi::XK_Cyrillic_i => VirtualKeyCode::Cyrillic_i, + //ffi::XK_Cyrillic_shorti => VirtualKeyCode::Cyrillic_shorti, + //ffi::XK_Cyrillic_ka => VirtualKeyCode::Cyrillic_ka, + //ffi::XK_Cyrillic_el => VirtualKeyCode::Cyrillic_el, + //ffi::XK_Cyrillic_em => VirtualKeyCode::Cyrillic_em, + //ffi::XK_Cyrillic_en => VirtualKeyCode::Cyrillic_en, + //ffi::XK_Cyrillic_o => VirtualKeyCode::Cyrillic_o, + //ffi::XK_Cyrillic_pe => VirtualKeyCode::Cyrillic_pe, + //ffi::XK_Cyrillic_ya => VirtualKeyCode::Cyrillic_ya, + //ffi::XK_Cyrillic_er => VirtualKeyCode::Cyrillic_er, + //ffi::XK_Cyrillic_es => VirtualKeyCode::Cyrillic_es, + //ffi::XK_Cyrillic_te => VirtualKeyCode::Cyrillic_te, + //ffi::XK_Cyrillic_u => VirtualKeyCode::Cyrillic_u, + //ffi::XK_Cyrillic_zhe => VirtualKeyCode::Cyrillic_zhe, + //ffi::XK_Cyrillic_ve => VirtualKeyCode::Cyrillic_ve, + //ffi::XK_Cyrillic_softsign => VirtualKeyCode::Cyrillic_softsign, + //ffi::XK_Cyrillic_yeru => VirtualKeyCode::Cyrillic_yeru, + //ffi::XK_Cyrillic_ze => VirtualKeyCode::Cyrillic_ze, + //ffi::XK_Cyrillic_sha => VirtualKeyCode::Cyrillic_sha, + //ffi::XK_Cyrillic_e => VirtualKeyCode::Cyrillic_e, + //ffi::XK_Cyrillic_shcha => VirtualKeyCode::Cyrillic_shcha, + //ffi::XK_Cyrillic_che => VirtualKeyCode::Cyrillic_che, + //ffi::XK_Cyrillic_hardsign => VirtualKeyCode::Cyrillic_hardsign, + //ffi::XK_Cyrillic_YU => VirtualKeyCode::Cyrillic_yu, + //ffi::XK_Cyrillic_A => VirtualKeyCode::Cyrillic_a, + //ffi::XK_Cyrillic_BE => VirtualKeyCode::Cyrillic_be, + //ffi::XK_Cyrillic_TSE => VirtualKeyCode::Cyrillic_tse, + //ffi::XK_Cyrillic_DE => VirtualKeyCode::Cyrillic_de, + //ffi::XK_Cyrillic_IE => VirtualKeyCode::Cyrillic_ie, + //ffi::XK_Cyrillic_EF => VirtualKeyCode::Cyrillic_ef, + //ffi::XK_Cyrillic_GHE => VirtualKeyCode::Cyrillic_ghe, + //ffi::XK_Cyrillic_HA => VirtualKeyCode::Cyrillic_ha, + //ffi::XK_Cyrillic_I => VirtualKeyCode::Cyrillic_i, + //ffi::XK_Cyrillic_SHORTI => VirtualKeyCode::Cyrillic_shorti, + //ffi::XK_Cyrillic_KA => VirtualKeyCode::Cyrillic_ka, + //ffi::XK_Cyrillic_EL => VirtualKeyCode::Cyrillic_el, + //ffi::XK_Cyrillic_EM => VirtualKeyCode::Cyrillic_em, + //ffi::XK_Cyrillic_EN => VirtualKeyCode::Cyrillic_en, + //ffi::XK_Cyrillic_O => VirtualKeyCode::Cyrillic_o, + //ffi::XK_Cyrillic_PE => VirtualKeyCode::Cyrillic_pe, + //ffi::XK_Cyrillic_YA => VirtualKeyCode::Cyrillic_ya, + //ffi::XK_Cyrillic_ER => VirtualKeyCode::Cyrillic_er, + //ffi::XK_Cyrillic_ES => VirtualKeyCode::Cyrillic_es, + //ffi::XK_Cyrillic_TE => VirtualKeyCode::Cyrillic_te, + //ffi::XK_Cyrillic_U => VirtualKeyCode::Cyrillic_u, + //ffi::XK_Cyrillic_ZHE => VirtualKeyCode::Cyrillic_zhe, + //ffi::XK_Cyrillic_VE => VirtualKeyCode::Cyrillic_ve, + //ffi::XK_Cyrillic_SOFTSIGN => VirtualKeyCode::Cyrillic_softsign, + //ffi::XK_Cyrillic_YERU => VirtualKeyCode::Cyrillic_yeru, + //ffi::XK_Cyrillic_ZE => VirtualKeyCode::Cyrillic_ze, + //ffi::XK_Cyrillic_SHA => VirtualKeyCode::Cyrillic_sha, + //ffi::XK_Cyrillic_E => VirtualKeyCode::Cyrillic_e, + //ffi::XK_Cyrillic_SHCHA => VirtualKeyCode::Cyrillic_shcha, + //ffi::XK_Cyrillic_CHE => VirtualKeyCode::Cyrillic_che, + //ffi::XK_Cyrillic_HARDSIGN => VirtualKeyCode::Cyrillic_hardsign, + //ffi::XK_Greek_ALPHAaccent => VirtualKeyCode::Greek_alphaaccent, + //ffi::XK_Greek_EPSILONaccent => VirtualKeyCode::Greek_epsilonaccent, + //ffi::XK_Greek_ETAaccent => VirtualKeyCode::Greek_etaaccent, + //ffi::XK_Greek_IOTAaccent => VirtualKeyCode::Greek_iotaaccent, + //ffi::XK_Greek_IOTAdiaeresis => VirtualKeyCode::Greek_iotadiaeresis, + //ffi::XK_Greek_OMICRONaccent => VirtualKeyCode::Greek_omicronaccent, + //ffi::XK_Greek_UPSILONaccent => VirtualKeyCode::Greek_upsilonaccent, + //ffi::XK_Greek_UPSILONdieresis => VirtualKeyCode::Greek_upsilondieresis, + //ffi::XK_Greek_OMEGAaccent => VirtualKeyCode::Greek_omegaaccent, + //ffi::XK_Greek_accentdieresis => VirtualKeyCode::Greek_accentdieresis, + //ffi::XK_Greek_horizbar => VirtualKeyCode::Greek_horizbar, + //ffi::XK_Greek_alphaaccent => VirtualKeyCode::Greek_alphaaccent, + //ffi::XK_Greek_epsilonaccent => VirtualKeyCode::Greek_epsilonaccent, + //ffi::XK_Greek_etaaccent => VirtualKeyCode::Greek_etaaccent, + //ffi::XK_Greek_iotaaccent => VirtualKeyCode::Greek_iotaaccent, + //ffi::XK_Greek_iotadieresis => VirtualKeyCode::Greek_iotadieresis, + //ffi::XK_Greek_iotaaccentdieresis => VirtualKeyCode::Greek_iotaaccentdieresis, + //ffi::XK_Greek_omicronaccent => VirtualKeyCode::Greek_omicronaccent, + //ffi::XK_Greek_upsilonaccent => VirtualKeyCode::Greek_upsilonaccent, + //ffi::XK_Greek_upsilondieresis => VirtualKeyCode::Greek_upsilondieresis, + //ffi::XK_Greek_upsilonaccentdieresis => VirtualKeyCode::Greek_upsilonaccentdieresis, + //ffi::XK_Greek_omegaaccent => VirtualKeyCode::Greek_omegaaccent, + //ffi::XK_Greek_ALPHA => VirtualKeyCode::Greek_alpha, + //ffi::XK_Greek_BETA => VirtualKeyCode::Greek_beta, + //ffi::XK_Greek_GAMMA => VirtualKeyCode::Greek_gamma, + //ffi::XK_Greek_DELTA => VirtualKeyCode::Greek_delta, + //ffi::XK_Greek_EPSILON => VirtualKeyCode::Greek_epsilon, + //ffi::XK_Greek_ZETA => VirtualKeyCode::Greek_zeta, + //ffi::XK_Greek_ETA => VirtualKeyCode::Greek_eta, + //ffi::XK_Greek_THETA => VirtualKeyCode::Greek_theta, + //ffi::XK_Greek_IOTA => VirtualKeyCode::Greek_iota, + //ffi::XK_Greek_KAPPA => VirtualKeyCode::Greek_kappa, + //ffi::XK_Greek_LAMDA => VirtualKeyCode::Greek_lamda, + //ffi::XK_Greek_LAMBDA => VirtualKeyCode::Greek_lambda, + //ffi::XK_Greek_MU => VirtualKeyCode::Greek_mu, + //ffi::XK_Greek_NU => VirtualKeyCode::Greek_nu, + //ffi::XK_Greek_XI => VirtualKeyCode::Greek_xi, + //ffi::XK_Greek_OMICRON => VirtualKeyCode::Greek_omicron, + //ffi::XK_Greek_PI => VirtualKeyCode::Greek_pi, + //ffi::XK_Greek_RHO => VirtualKeyCode::Greek_rho, + //ffi::XK_Greek_SIGMA => VirtualKeyCode::Greek_sigma, + //ffi::XK_Greek_TAU => VirtualKeyCode::Greek_tau, + //ffi::XK_Greek_UPSILON => VirtualKeyCode::Greek_upsilon, + //ffi::XK_Greek_PHI => VirtualKeyCode::Greek_phi, + //ffi::XK_Greek_CHI => VirtualKeyCode::Greek_chi, + //ffi::XK_Greek_PSI => VirtualKeyCode::Greek_psi, + //ffi::XK_Greek_OMEGA => VirtualKeyCode::Greek_omega, + //ffi::XK_Greek_alpha => VirtualKeyCode::Greek_alpha, + //ffi::XK_Greek_beta => VirtualKeyCode::Greek_beta, + //ffi::XK_Greek_gamma => VirtualKeyCode::Greek_gamma, + //ffi::XK_Greek_delta => VirtualKeyCode::Greek_delta, + //ffi::XK_Greek_epsilon => VirtualKeyCode::Greek_epsilon, + //ffi::XK_Greek_zeta => VirtualKeyCode::Greek_zeta, + //ffi::XK_Greek_eta => VirtualKeyCode::Greek_eta, + //ffi::XK_Greek_theta => VirtualKeyCode::Greek_theta, + //ffi::XK_Greek_iota => VirtualKeyCode::Greek_iota, + //ffi::XK_Greek_kappa => VirtualKeyCode::Greek_kappa, + //ffi::XK_Greek_lamda => VirtualKeyCode::Greek_lamda, + //ffi::XK_Greek_lambda => VirtualKeyCode::Greek_lambda, + //ffi::XK_Greek_mu => VirtualKeyCode::Greek_mu, + //ffi::XK_Greek_nu => VirtualKeyCode::Greek_nu, + //ffi::XK_Greek_xi => VirtualKeyCode::Greek_xi, + //ffi::XK_Greek_omicron => VirtualKeyCode::Greek_omicron, + //ffi::XK_Greek_pi => VirtualKeyCode::Greek_pi, + //ffi::XK_Greek_rho => VirtualKeyCode::Greek_rho, + //ffi::XK_Greek_sigma => VirtualKeyCode::Greek_sigma, + //ffi::XK_Greek_finalsmallsigma => VirtualKeyCode::Greek_finalsmallsigma, + //ffi::XK_Greek_tau => VirtualKeyCode::Greek_tau, + //ffi::XK_Greek_upsilon => VirtualKeyCode::Greek_upsilon, + //ffi::XK_Greek_phi => VirtualKeyCode::Greek_phi, + //ffi::XK_Greek_chi => VirtualKeyCode::Greek_chi, + //ffi::XK_Greek_psi => VirtualKeyCode::Greek_psi, + //ffi::XK_Greek_omega => VirtualKeyCode::Greek_omega, + //ffi::XK_Greek_switch => VirtualKeyCode::Greek_switch, + //ffi::XK_leftradical => VirtualKeyCode::Leftradical, + //ffi::XK_topleftradical => VirtualKeyCode::Topleftradical, + //ffi::XK_horizconnector => VirtualKeyCode::Horizconnector, + //ffi::XK_topintegral => VirtualKeyCode::Topintegral, + //ffi::XK_botintegral => VirtualKeyCode::Botintegral, + //ffi::XK_vertconnector => VirtualKeyCode::Vertconnector, + //ffi::XK_topleftsqbracket => VirtualKeyCode::Topleftsqbracket, + //ffi::XK_botleftsqbracket => VirtualKeyCode::Botleftsqbracket, + //ffi::XK_toprightsqbracket => VirtualKeyCode::Toprightsqbracket, + //ffi::XK_botrightsqbracket => VirtualKeyCode::Botrightsqbracket, + //ffi::XK_topleftparens => VirtualKeyCode::Topleftparens, + //ffi::XK_botleftparens => VirtualKeyCode::Botleftparens, + //ffi::XK_toprightparens => VirtualKeyCode::Toprightparens, + //ffi::XK_botrightparens => VirtualKeyCode::Botrightparens, + //ffi::XK_leftmiddlecurlybrace => VirtualKeyCode::Leftmiddlecurlybrace, + //ffi::XK_rightmiddlecurlybrace => VirtualKeyCode::Rightmiddlecurlybrace, + //ffi::XK_topleftsummation => VirtualKeyCode::Topleftsummation, + //ffi::XK_botleftsummation => VirtualKeyCode::Botleftsummation, + //ffi::XK_topvertsummationconnector => VirtualKeyCode::Topvertsummationconnector, + //ffi::XK_botvertsummationconnector => VirtualKeyCode::Botvertsummationconnector, + //ffi::XK_toprightsummation => VirtualKeyCode::Toprightsummation, + //ffi::XK_botrightsummation => VirtualKeyCode::Botrightsummation, + //ffi::XK_rightmiddlesummation => VirtualKeyCode::Rightmiddlesummation, + //ffi::XK_lessthanequal => VirtualKeyCode::Lessthanequal, + //ffi::XK_notequal => VirtualKeyCode::Notequal, + //ffi::XK_greaterthanequal => VirtualKeyCode::Greaterthanequal, + //ffi::XK_integral => VirtualKeyCode::Integral, + //ffi::XK_therefore => VirtualKeyCode::Therefore, + //ffi::XK_variation => VirtualKeyCode::Variation, + //ffi::XK_infinity => VirtualKeyCode::Infinity, + //ffi::XK_nabla => VirtualKeyCode::Nabla, + //ffi::XK_approximate => VirtualKeyCode::Approximate, + //ffi::XK_similarequal => VirtualKeyCode::Similarequal, + //ffi::XK_ifonlyif => VirtualKeyCode::Ifonlyif, + //ffi::XK_implies => VirtualKeyCode::Implies, + //ffi::XK_identical => VirtualKeyCode::Identical, + //ffi::XK_radical => VirtualKeyCode::Radical, + //ffi::XK_includedin => VirtualKeyCode::Includedin, + //ffi::XK_includes => VirtualKeyCode::Includes, + //ffi::XK_intersection => VirtualKeyCode::Intersection, + //ffi::XK_union => VirtualKeyCode::Union, + //ffi::XK_logicaland => VirtualKeyCode::Logicaland, + //ffi::XK_logicalor => VirtualKeyCode::Logicalor, + //ffi::XK_partialderivative => VirtualKeyCode::Partialderivative, + //ffi::XK_function => VirtualKeyCode::Function, + //ffi::XK_leftarrow => VirtualKeyCode::Leftarrow, + //ffi::XK_uparrow => VirtualKeyCode::Uparrow, + //ffi::XK_rightarrow => VirtualKeyCode::Rightarrow, + //ffi::XK_downarrow => VirtualKeyCode::Downarrow, + //ffi::XK_blank => VirtualKeyCode::Blank, + //ffi::XK_soliddiamond => VirtualKeyCode::Soliddiamond, + //ffi::XK_checkerboard => VirtualKeyCode::Checkerboard, + //ffi::XK_ht => VirtualKeyCode::Ht, + //ffi::XK_ff => VirtualKeyCode::Ff, + //ffi::XK_cr => VirtualKeyCode::Cr, + //ffi::XK_lf => VirtualKeyCode::Lf, + //ffi::XK_nl => VirtualKeyCode::Nl, + //ffi::XK_vt => VirtualKeyCode::Vt, + //ffi::XK_lowrightcorner => VirtualKeyCode::Lowrightcorner, + //ffi::XK_uprightcorner => VirtualKeyCode::Uprightcorner, + //ffi::XK_upleftcorner => VirtualKeyCode::Upleftcorner, + //ffi::XK_lowleftcorner => VirtualKeyCode::Lowleftcorner, + //ffi::XK_crossinglines => VirtualKeyCode::Crossinglines, + //ffi::XK_horizlinescan1 => VirtualKeyCode::Horizlinescan1, + //ffi::XK_horizlinescan3 => VirtualKeyCode::Horizlinescan3, + //ffi::XK_horizlinescan5 => VirtualKeyCode::Horizlinescan5, + //ffi::XK_horizlinescan7 => VirtualKeyCode::Horizlinescan7, + //ffi::XK_horizlinescan9 => VirtualKeyCode::Horizlinescan9, + //ffi::XK_leftt => VirtualKeyCode::Leftt, + //ffi::XK_rightt => VirtualKeyCode::Rightt, + //ffi::XK_bott => VirtualKeyCode::Bott, + //ffi::XK_topt => VirtualKeyCode::Topt, + //ffi::XK_vertbar => VirtualKeyCode::Vertbar, + //ffi::XK_emspace => VirtualKeyCode::Emspace, + //ffi::XK_enspace => VirtualKeyCode::Enspace, + //ffi::XK_em3space => VirtualKeyCode::Em3space, + //ffi::XK_em4space => VirtualKeyCode::Em4space, + //ffi::XK_digitspace => VirtualKeyCode::Digitspace, + //ffi::XK_punctspace => VirtualKeyCode::Punctspace, + //ffi::XK_thinspace => VirtualKeyCode::Thinspace, + //ffi::XK_hairspace => VirtualKeyCode::Hairspace, + //ffi::XK_emdash => VirtualKeyCode::Emdash, + //ffi::XK_endash => VirtualKeyCode::Endash, + //ffi::XK_signifblank => VirtualKeyCode::Signifblank, + //ffi::XK_ellipsis => VirtualKeyCode::Ellipsis, + //ffi::XK_doubbaselinedot => VirtualKeyCode::Doubbaselinedot, + //ffi::XK_onethird => VirtualKeyCode::Onethird, + //ffi::XK_twothirds => VirtualKeyCode::Twothirds, + //ffi::XK_onefifth => VirtualKeyCode::Onefifth, + //ffi::XK_twofifths => VirtualKeyCode::Twofifths, + //ffi::XK_threefifths => VirtualKeyCode::Threefifths, + //ffi::XK_fourfifths => VirtualKeyCode::Fourfifths, + //ffi::XK_onesixth => VirtualKeyCode::Onesixth, + //ffi::XK_fivesixths => VirtualKeyCode::Fivesixths, + //ffi::XK_careof => VirtualKeyCode::Careof, + //ffi::XK_figdash => VirtualKeyCode::Figdash, + //ffi::XK_leftanglebracket => VirtualKeyCode::Leftanglebracket, + //ffi::XK_decimalpoint => VirtualKeyCode::Decimalpoint, + //ffi::XK_rightanglebracket => VirtualKeyCode::Rightanglebracket, + //ffi::XK_marker => VirtualKeyCode::Marker, + //ffi::XK_oneeighth => VirtualKeyCode::Oneeighth, + //ffi::XK_threeeighths => VirtualKeyCode::Threeeighths, + //ffi::XK_fiveeighths => VirtualKeyCode::Fiveeighths, + //ffi::XK_seveneighths => VirtualKeyCode::Seveneighths, + //ffi::XK_trademark => VirtualKeyCode::Trademark, + //ffi::XK_signaturemark => VirtualKeyCode::Signaturemark, + //ffi::XK_trademarkincircle => VirtualKeyCode::Trademarkincircle, + //ffi::XK_leftopentriangle => VirtualKeyCode::Leftopentriangle, + //ffi::XK_rightopentriangle => VirtualKeyCode::Rightopentriangle, + //ffi::XK_emopencircle => VirtualKeyCode::Emopencircle, + //ffi::XK_emopenrectangle => VirtualKeyCode::Emopenrectangle, + //ffi::XK_leftsinglequotemark => VirtualKeyCode::Leftsinglequotemark, + //ffi::XK_rightsinglequotemark => VirtualKeyCode::Rightsinglequotemark, + //ffi::XK_leftdoublequotemark => VirtualKeyCode::Leftdoublequotemark, + //ffi::XK_rightdoublequotemark => VirtualKeyCode::Rightdoublequotemark, + //ffi::XK_prescription => VirtualKeyCode::Prescription, + //ffi::XK_minutes => VirtualKeyCode::Minutes, + //ffi::XK_seconds => VirtualKeyCode::Seconds, + //ffi::XK_latincross => VirtualKeyCode::Latincross, + //ffi::XK_hexagram => VirtualKeyCode::Hexagram, + //ffi::XK_filledrectbullet => VirtualKeyCode::Filledrectbullet, + //ffi::XK_filledlefttribullet => VirtualKeyCode::Filledlefttribullet, + //ffi::XK_filledrighttribullet => VirtualKeyCode::Filledrighttribullet, + //ffi::XK_emfilledcircle => VirtualKeyCode::Emfilledcircle, + //ffi::XK_emfilledrect => VirtualKeyCode::Emfilledrect, + //ffi::XK_enopencircbullet => VirtualKeyCode::Enopencircbullet, + //ffi::XK_enopensquarebullet => VirtualKeyCode::Enopensquarebullet, + //ffi::XK_openrectbullet => VirtualKeyCode::Openrectbullet, + //ffi::XK_opentribulletup => VirtualKeyCode::Opentribulletup, + //ffi::XK_opentribulletdown => VirtualKeyCode::Opentribulletdown, + //ffi::XK_openstar => VirtualKeyCode::Openstar, + //ffi::XK_enfilledcircbullet => VirtualKeyCode::Enfilledcircbullet, + //ffi::XK_enfilledsqbullet => VirtualKeyCode::Enfilledsqbullet, + //ffi::XK_filledtribulletup => VirtualKeyCode::Filledtribulletup, + //ffi::XK_filledtribulletdown => VirtualKeyCode::Filledtribulletdown, + //ffi::XK_leftpointer => VirtualKeyCode::Leftpointer, + //ffi::XK_rightpointer => VirtualKeyCode::Rightpointer, + //ffi::XK_club => VirtualKeyCode::Club, + //ffi::XK_diamond => VirtualKeyCode::Diamond, + //ffi::XK_heart => VirtualKeyCode::Heart, + //ffi::XK_maltesecross => VirtualKeyCode::Maltesecross, + //ffi::XK_dagger => VirtualKeyCode::Dagger, + //ffi::XK_doubledagger => VirtualKeyCode::Doubledagger, + //ffi::XK_checkmark => VirtualKeyCode::Checkmark, + //ffi::XK_ballotcross => VirtualKeyCode::Ballotcross, + //ffi::XK_musicalsharp => VirtualKeyCode::Musicalsharp, + //ffi::XK_musicalflat => VirtualKeyCode::Musicalflat, + //ffi::XK_malesymbol => VirtualKeyCode::Malesymbol, + //ffi::XK_femalesymbol => VirtualKeyCode::Femalesymbol, + //ffi::XK_telephone => VirtualKeyCode::Telephone, + //ffi::XK_telephonerecorder => VirtualKeyCode::Telephonerecorder, + //ffi::XK_phonographcopyright => VirtualKeyCode::Phonographcopyright, + //ffi::XK_caret => VirtualKeyCode::Caret, + //ffi::XK_singlelowquotemark => VirtualKeyCode::Singlelowquotemark, + //ffi::XK_doublelowquotemark => VirtualKeyCode::Doublelowquotemark, + //ffi::XK_cursor => VirtualKeyCode::Cursor, + //ffi::XK_leftcaret => VirtualKeyCode::Leftcaret, + //ffi::XK_rightcaret => VirtualKeyCode::Rightcaret, + //ffi::XK_downcaret => VirtualKeyCode::Downcaret, + //ffi::XK_upcaret => VirtualKeyCode::Upcaret, + //ffi::XK_overbar => VirtualKeyCode::Overbar, + //ffi::XK_downtack => VirtualKeyCode::Downtack, + //ffi::XK_upshoe => VirtualKeyCode::Upshoe, + //ffi::XK_downstile => VirtualKeyCode::Downstile, + //ffi::XK_underbar => VirtualKeyCode::Underbar, + //ffi::XK_jot => VirtualKeyCode::Jot, + //ffi::XK_quad => VirtualKeyCode::Quad, + //ffi::XK_uptack => VirtualKeyCode::Uptack, + //ffi::XK_circle => VirtualKeyCode::Circle, + //ffi::XK_upstile => VirtualKeyCode::Upstile, + //ffi::XK_downshoe => VirtualKeyCode::Downshoe, + //ffi::XK_rightshoe => VirtualKeyCode::Rightshoe, + //ffi::XK_leftshoe => VirtualKeyCode::Leftshoe, + //ffi::XK_lefttack => VirtualKeyCode::Lefttack, + //ffi::XK_righttack => VirtualKeyCode::Righttack, + //ffi::XK_hebrew_doublelowline => VirtualKeyCode::Hebrew_doublelowline, + //ffi::XK_hebrew_aleph => VirtualKeyCode::Hebrew_aleph, + //ffi::XK_hebrew_bet => VirtualKeyCode::Hebrew_bet, + //ffi::XK_hebrew_beth => VirtualKeyCode::Hebrew_beth, + //ffi::XK_hebrew_gimel => VirtualKeyCode::Hebrew_gimel, + //ffi::XK_hebrew_gimmel => VirtualKeyCode::Hebrew_gimmel, + //ffi::XK_hebrew_dalet => VirtualKeyCode::Hebrew_dalet, + //ffi::XK_hebrew_daleth => VirtualKeyCode::Hebrew_daleth, + //ffi::XK_hebrew_he => VirtualKeyCode::Hebrew_he, + //ffi::XK_hebrew_waw => VirtualKeyCode::Hebrew_waw, + //ffi::XK_hebrew_zain => VirtualKeyCode::Hebrew_zain, + //ffi::XK_hebrew_zayin => VirtualKeyCode::Hebrew_zayin, + //ffi::XK_hebrew_chet => VirtualKeyCode::Hebrew_chet, + //ffi::XK_hebrew_het => VirtualKeyCode::Hebrew_het, + //ffi::XK_hebrew_tet => VirtualKeyCode::Hebrew_tet, + //ffi::XK_hebrew_teth => VirtualKeyCode::Hebrew_teth, + //ffi::XK_hebrew_yod => VirtualKeyCode::Hebrew_yod, + //ffi::XK_hebrew_finalkaph => VirtualKeyCode::Hebrew_finalkaph, + //ffi::XK_hebrew_kaph => VirtualKeyCode::Hebrew_kaph, + //ffi::XK_hebrew_lamed => VirtualKeyCode::Hebrew_lamed, + //ffi::XK_hebrew_finalmem => VirtualKeyCode::Hebrew_finalmem, + //ffi::XK_hebrew_mem => VirtualKeyCode::Hebrew_mem, + //ffi::XK_hebrew_finalnun => VirtualKeyCode::Hebrew_finalnun, + //ffi::XK_hebrew_nun => VirtualKeyCode::Hebrew_nun, + //ffi::XK_hebrew_samech => VirtualKeyCode::Hebrew_samech, + //ffi::XK_hebrew_samekh => VirtualKeyCode::Hebrew_samekh, + //ffi::XK_hebrew_ayin => VirtualKeyCode::Hebrew_ayin, + //ffi::XK_hebrew_finalpe => VirtualKeyCode::Hebrew_finalpe, + //ffi::XK_hebrew_pe => VirtualKeyCode::Hebrew_pe, + //ffi::XK_hebrew_finalzade => VirtualKeyCode::Hebrew_finalzade, + //ffi::XK_hebrew_finalzadi => VirtualKeyCode::Hebrew_finalzadi, + //ffi::XK_hebrew_zade => VirtualKeyCode::Hebrew_zade, + //ffi::XK_hebrew_zadi => VirtualKeyCode::Hebrew_zadi, + //ffi::XK_hebrew_qoph => VirtualKeyCode::Hebrew_qoph, + //ffi::XK_hebrew_kuf => VirtualKeyCode::Hebrew_kuf, + //ffi::XK_hebrew_resh => VirtualKeyCode::Hebrew_resh, + //ffi::XK_hebrew_shin => VirtualKeyCode::Hebrew_shin, + //ffi::XK_hebrew_taw => VirtualKeyCode::Hebrew_taw, + //ffi::XK_hebrew_taf => VirtualKeyCode::Hebrew_taf, + //ffi::XK_Hebrew_switch => VirtualKeyCode::Hebrew_switch, + ffi::XF86XK_Back => VirtualKeyCode::NavigateBackward, + ffi::XF86XK_Forward => VirtualKeyCode::NavigateForward, + ffi::XF86XK_Copy => VirtualKeyCode::Copy, + ffi::XF86XK_Paste => VirtualKeyCode::Paste, + ffi::XF86XK_Cut => VirtualKeyCode::Cut, + _ => return None, + }) +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ffi.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ffi.rs new file mode 100644 index 0000000..6d7c208 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ffi.rs @@ -0,0 +1,4 @@ +pub use x11_dl::{ + error::OpenError, keysym::*, xcursor::*, xinput::*, xinput2::*, xlib::*, xlib_xcb::*, + xrandr::*, xrender::*, +}; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/callbacks.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/callbacks.rs similarity index 89% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/callbacks.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/callbacks.rs index 0618b23..f254a04 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/callbacks.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/callbacks.rs @@ -1,13 +1,12 @@ -use std::ptr; -use std::sync::Arc; -use std::collections::HashMap; -use std::os::raw::c_char; +use std::{collections::HashMap, os::raw::c_char, ptr, sync::Arc}; use super::{ffi, XConnection, XError}; -use super::inner::{close_im, ImeInner}; -use super::input_method::PotentialInputMethods; -use super::context::{ImeContextCreationError, ImeContext}; +use super::{ + context::{ImeContext, ImeContextCreationError}, + inner::{close_im, ImeInner}, + input_method::PotentialInputMethods, +}; pub unsafe fn xim_set_callback( xconn: &Arc, @@ -17,12 +16,7 @@ pub unsafe fn xim_set_callback( ) -> Result<(), XError> { // It's advisable to wrap variadic FFI functions in our own functions, as we want to minimize // access that isn't type-checked. - (xconn.xlib.XSetIMValues)( - xim, - field, - callback, - ptr::null_mut::<()>(), - ); + (xconn.xlib.XSetIMValues)(xim, field, callback, ptr::null_mut::<()>()); xconn.check_errors() } @@ -107,18 +101,14 @@ unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> { let _ = close_im(xconn, new_im.im); } result - }.map_err(ReplaceImError::SetDestroyCallbackFailed)?; + } + .map_err(ReplaceImError::SetDestroyCallbackFailed)?; let mut new_contexts = HashMap::new(); for (window, old_context) in (*inner).contexts.iter() { let spot = old_context.as_ref().map(|old_context| old_context.ic_spot); let new_context = { - let result = ImeContext::new( - xconn, - new_im.im, - *window, - spot, - ); + let result = ImeContext::new(xconn, new_im.im, *window, spot); if result.is_err() { let _ = close_im(xconn, new_im.im); } @@ -137,7 +127,7 @@ unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> { Ok(()) } -pub unsafe extern fn xim_instantiate_callback( +pub unsafe extern "C" fn xim_instantiate_callback( _display: *mut ffi::Display, client_data: ffi::XPointer, // This field is unsupplied. @@ -160,7 +150,7 @@ pub unsafe extern fn xim_instantiate_callback( // This callback is triggered when the input method is closed on the server end. When this // happens, XCloseIM/XDestroyIC doesn't need to be called, as the resources have already been // free'd (attempting to do so causes our connection to freeze). -pub unsafe extern fn xim_destroy_callback( +pub unsafe extern "C" fn xim_destroy_callback( _xim: ffi::XIM, client_data: ffi::XPointer, // This field is unsupplied. diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/context.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/context.rs similarity index 94% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/context.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/context.rs index 598cd48..8c2ff4c 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/context.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/context.rs @@ -1,6 +1,8 @@ -use std::ptr; -use std::sync::Arc; -use std::os::raw::{c_short, c_void}; +use std::{ + os::raw::{c_short, c_void}, + ptr, + sync::Arc, +}; use super::{ffi, util, XConnection, XError}; @@ -22,7 +24,8 @@ unsafe fn create_pre_edit_attr<'a>( ic_spot, ptr::null_mut::<()>(), ), - ).expect("XVaCreateNestedList returned NULL") + ) + .expect("XVaCreateNestedList returned NULL") } // WARNING: this struct doesn't destroy its XIC resource when dropped. @@ -49,7 +52,9 @@ impl ImeContext { }; let ic = ic.ok_or(ImeContextCreationError::Null)?; - xconn.check_errors().map_err(ImeContextCreationError::XError)?; + xconn + .check_errors() + .map_err(ImeContextCreationError::XError)?; Ok(ImeContext { ic, diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/inner.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/inner.rs similarity index 87% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/inner.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/inner.rs index 34bfbe7..011e22a 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/inner.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/inner.rs @@ -1,12 +1,8 @@ -use std::mem; -use std::ptr; -use std::sync::Arc; -use std::collections::HashMap; +use std::{collections::HashMap, mem, ptr, sync::Arc}; use super::{ffi, XConnection, XError}; -use super::input_method::PotentialInputMethods; -use super::context::ImeContext; +use super::{context::ImeContext, input_method::PotentialInputMethods}; pub unsafe fn close_im(xconn: &Arc, im: ffi::XIM) -> Result<(), XError> { (xconn.xlib.XCloseIM)(im); @@ -33,10 +29,7 @@ pub struct ImeInner { } impl ImeInner { - pub fn new( - xconn: Arc, - potential_input_methods: PotentialInputMethods, - ) -> Self { + pub fn new(xconn: Arc, potential_input_methods: PotentialInputMethods) -> Self { ImeInner { xconn, im: ptr::null_mut(), diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/input_method.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/input_method.rs similarity index 91% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/input_method.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/input_method.rs index fee0a14..142c150 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/input_method.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/input_method.rs @@ -1,9 +1,11 @@ -use std::env; -use std::fmt; -use std::ptr; -use std::sync::Arc; -use std::os::raw::c_char; -use std::ffi::{CStr, CString, IntoStringError}; +use std::{ + env, + ffi::{CStr, CString, IntoStringError}, + fmt, + os::raw::c_char, + ptr, + sync::Arc, +}; use parking_lot::Mutex; @@ -13,16 +15,14 @@ lazy_static! { static ref GLOBAL_LOCK: Mutex<()> = Default::default(); } -unsafe fn open_im( - xconn: &Arc, - locale_modifiers: &CStr, -) -> Option { +unsafe fn open_im(xconn: &Arc, locale_modifiers: &CStr) -> Option { let _lock = GLOBAL_LOCK.lock(); // XSetLocaleModifiers returns... // * The current locale modifiers if it's given a NULL pointer. // * The new locale modifiers if we succeeded in setting them. - // * NULL if the locale modifiers string is malformed. + // * NULL if the locale modifiers string is malformed or if the + // current locale is not supported by Xlib. (xconn.xlib.XSetLocaleModifiers)(locale_modifiers.as_ptr()); let im = (xconn.xlib.XOpenIM)( @@ -97,11 +97,9 @@ unsafe fn get_xim_servers(xconn: &Arc) -> Result, GetXi let root = (xconn.xlib.XDefaultRootWindow)(xconn.display); - let mut atoms: Vec = xconn.get_property( - root, - servers_atom, - ffi::XA_ATOM, - ).map_err(GetXimServersError::GetPropertyError)?; + let mut atoms: Vec = xconn + .get_property(root, servers_atom, ffi::XA_ATOM) + .map_err(GetXimServersError::GetPropertyError)?; let mut names: Vec<*const c_char> = Vec::with_capacity(atoms.len()); (xconn.xlib.XGetAtomNames)( @@ -135,15 +133,12 @@ impl InputMethodName { pub fn from_string(string: String) -> Self { let c_string = CString::new(string.clone()) .expect("String used to construct CString contained null byte"); - InputMethodName { - c_string, - string, - } + InputMethodName { c_string, string } } pub fn from_str(string: &str) -> Self { - let c_string = CString::new(string) - .expect("String used to construct CString contained null byte"); + let c_string = + CString::new(string).expect("String used to construct CString contained null byte"); InputMethodName { c_string, string: string.to_owned(), @@ -152,7 +147,7 @@ impl InputMethodName { } impl fmt::Debug for InputMethodName { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.string.fmt(f) } } @@ -254,7 +249,7 @@ impl PotentialInputMethods { pub fn open_im( &mut self, xconn: &Arc, - callback: Option<&Fn() -> ()>, + callback: Option<&dyn Fn() -> ()>, ) -> InputMethodResult { use self::InputMethodResult::*; diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/mod.rs similarity index 85% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/mod.rs index 2298050..b95da71 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/ime/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/ime/mod.rs @@ -1,19 +1,24 @@ // Important: all XIM calls need to happen from the same thread! +mod callbacks; +mod context; mod inner; mod input_method; -mod context; -mod callbacks; -use std::sync::Arc; -use std::sync::mpsc::{Receiver, Sender}; +use std::sync::{ + mpsc::{Receiver, Sender}, + Arc, +}; use super::{ffi, util, XConnection, XError}; -use self::inner::{close_im, ImeInner}; -use self::input_method::PotentialInputMethods; -use self::context::{ImeContextCreationError, ImeContext}; -use self::callbacks::*; +pub use self::context::ImeContextCreationError; +use self::{ + callbacks::*, + context::ImeContext, + inner::{close_im, ImeInner}, + input_method::PotentialInputMethods, +}; pub type ImeReceiver = Receiver<(ffi::Window, i16, i16)>; pub type ImeSender = Sender<(ffi::Window, i16, i16)>; @@ -36,10 +41,7 @@ impl Ime { let potential_input_methods = PotentialInputMethods::new(&xconn); let (mut inner, client_data) = { - let mut inner = Box::new(ImeInner::new( - xconn, - potential_input_methods, - )); + let mut inner = Box::new(ImeInner::new(xconn, potential_input_methods)); let inner_ptr = Box::into_raw(inner); let client_data = inner_ptr as _; let destroy_callback = ffi::XIMCallback { @@ -53,9 +55,12 @@ impl Ime { let xconn = Arc::clone(&inner.xconn); - let input_method = inner.potential_input_methods.open_im(&xconn, Some(&|| { - let _ = unsafe { set_instantiate_callback(&xconn, client_data) }; - })); + let input_method = inner.potential_input_methods.open_im( + &xconn, + Some(&|| { + let _ = unsafe { set_instantiate_callback(&xconn, client_data) }; + }), + ); let is_fallback = input_method.is_fallback(); if let Some(input_method) = input_method.ok() { @@ -83,19 +88,12 @@ impl Ime { // Ok(_) indicates that nothing went wrong internally // Ok(true) indicates that the action was actually performed // Ok(false) indicates that the action is not presently applicable - pub fn create_context(&mut self, window: ffi::Window) - -> Result - { + pub fn create_context(&mut self, window: ffi::Window) -> Result { let context = if self.is_destroyed() { // Create empty entry in map, so that when IME is rebuilt, this window has a context. None } else { - Some(unsafe { ImeContext::new( - &self.inner.xconn, - self.inner.im, - window, - None, - ) }?) + Some(unsafe { ImeContext::new(&self.inner.xconn, self.inner.im, window, None) }?) }; self.inner.contexts.insert(window, context); Ok(!self.is_destroyed()) diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/mod.rs new file mode 100644 index 0000000..f9e0ea5 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/mod.rs @@ -0,0 +1,712 @@ +#![cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] + +mod dnd; +mod event_processor; +mod events; +pub mod ffi; +mod ime; +mod monitor; +pub mod util; +mod window; +mod xdisplay; + +pub use self::{ + monitor::{MonitorHandle, VideoMode}, + window::UnownedWindow, + xdisplay::{XConnection, XError, XNotSupported}, +}; + +use std::{ + cell::RefCell, + collections::{HashMap, HashSet}, + ffi::CStr, + mem::{self, MaybeUninit}, + ops::Deref, + os::raw::*, + ptr, + rc::Rc, + slice, + sync::{mpsc, Arc, Mutex, Weak}, + time::{Duration, Instant}, +}; + +use libc::{self, setlocale, LC_CTYPE}; + +use mio::{unix::EventedFd, Events, Poll, PollOpt, Ready, Token}; + +use mio_extras::channel::{channel, Receiver, SendError, Sender}; + +use self::{ + dnd::{Dnd, DndState}, + event_processor::EventProcessor, + ime::{Ime, ImeCreationError, ImeReceiver, ImeSender}, + util::modifiers::ModifierKeymap, +}; +use crate::{ + error::OsError as RootOsError, + event::{Event, StartCause}, + event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW}, + platform_impl::{platform::sticky_exit_callback, PlatformSpecificWindowBuilderAttributes}, + window::WindowAttributes, +}; + +const X_TOKEN: Token = Token(0); +const USER_TOKEN: Token = Token(1); + +pub struct EventLoopWindowTarget { + xconn: Arc, + wm_delete_window: ffi::Atom, + net_wm_ping: ffi::Atom, + ime_sender: ImeSender, + root: ffi::Window, + ime: RefCell, + windows: RefCell>>, + pending_redraws: Arc>>, + _marker: ::std::marker::PhantomData, +} + +pub struct EventLoop { + poll: Poll, + event_processor: EventProcessor, + user_channel: Receiver, + user_sender: Sender, + target: Rc>, +} + +pub struct EventLoopProxy { + user_sender: Sender, +} + +impl Clone for EventLoopProxy { + fn clone(&self) -> Self { + EventLoopProxy { + user_sender: self.user_sender.clone(), + } + } +} + +impl EventLoop { + pub fn new(xconn: Arc) -> EventLoop { + let root = unsafe { (xconn.xlib.XDefaultRootWindow)(xconn.display) }; + + let wm_delete_window = unsafe { xconn.get_atom_unchecked(b"WM_DELETE_WINDOW\0") }; + + let net_wm_ping = unsafe { xconn.get_atom_unchecked(b"_NET_WM_PING\0") }; + + let dnd = Dnd::new(Arc::clone(&xconn)) + .expect("Failed to call XInternAtoms when initializing drag and drop"); + + let (ime_sender, ime_receiver) = mpsc::channel(); + // Input methods will open successfully without setting the locale, but it won't be + // possible to actually commit pre-edit sequences. + unsafe { + // Remember default locale to restore it if target locale is unsupported + // by Xlib + let default_locale = setlocale(LC_CTYPE, ptr::null()); + setlocale(LC_CTYPE, b"\0".as_ptr() as *const _); + + // Check if set locale is supported by Xlib. + // If not, calls to some Xlib functions like `XSetLocaleModifiers` + // will fail. + let locale_supported = (xconn.xlib.XSupportsLocale)() == 1; + if !locale_supported { + let unsupported_locale = setlocale(LC_CTYPE, ptr::null()); + warn!( + "Unsupported locale \"{}\". Restoring default locale \"{}\".", + CStr::from_ptr(unsupported_locale).to_string_lossy(), + CStr::from_ptr(default_locale).to_string_lossy() + ); + // Restore default locale + setlocale(LC_CTYPE, default_locale); + } + } + let ime = RefCell::new({ + let result = Ime::new(Arc::clone(&xconn)); + if let Err(ImeCreationError::OpenFailure(ref state)) = result { + panic!(format!("Failed to open input method: {:#?}", state)); + } + result.expect("Failed to set input method destruction callback") + }); + + let randr_event_offset = xconn + .select_xrandr_input(root) + .expect("Failed to query XRandR extension"); + + let xi2ext = unsafe { + let mut ext = XExtension::default(); + + let res = (xconn.xlib.XQueryExtension)( + xconn.display, + b"XInputExtension\0".as_ptr() as *const c_char, + &mut ext.opcode, + &mut ext.first_event_id, + &mut ext.first_error_id, + ); + + if res == ffi::False { + panic!("X server missing XInput extension"); + } + + ext + }; + + unsafe { + let mut xinput_major_ver = ffi::XI_2_Major; + let mut xinput_minor_ver = ffi::XI_2_Minor; + if (xconn.xinput2.XIQueryVersion)( + xconn.display, + &mut xinput_major_ver, + &mut xinput_minor_ver, + ) != ffi::Success as libc::c_int + { + panic!( + "X server has XInput extension {}.{} but does not support XInput2", + xinput_major_ver, xinput_minor_ver, + ); + } + } + + xconn.update_cached_wm_info(root); + + let pending_redraws: Arc>> = Default::default(); + + let mut mod_keymap = ModifierKeymap::new(); + mod_keymap.reset_from_x_connection(&xconn); + + let target = Rc::new(RootELW { + p: super::EventLoopWindowTarget::X(EventLoopWindowTarget { + ime, + root, + windows: Default::default(), + _marker: ::std::marker::PhantomData, + ime_sender, + xconn, + wm_delete_window, + net_wm_ping, + pending_redraws: pending_redraws.clone(), + }), + _marker: ::std::marker::PhantomData, + }); + + let poll = Poll::new().unwrap(); + + let (user_sender, user_channel) = channel(); + + poll.register( + &EventedFd(&get_xtarget(&target).xconn.x11_fd), + X_TOKEN, + Ready::readable(), + PollOpt::level(), + ) + .unwrap(); + + poll.register( + &user_channel, + USER_TOKEN, + Ready::readable(), + PollOpt::level(), + ) + .unwrap(); + + let event_processor = EventProcessor { + target: target.clone(), + dnd, + devices: Default::default(), + randr_event_offset, + ime_receiver, + xi2ext, + mod_keymap, + device_mod_state: Default::default(), + num_touch: 0, + first_touch: None, + active_window: None, + }; + + // Register for device hotplug events + // (The request buffer is flushed during `init_device`) + get_xtarget(&target) + .xconn + .select_xinput_events(root, ffi::XIAllDevices, ffi::XI_HierarchyChangedMask) + .queue(); + + event_processor.init_device(ffi::XIAllDevices); + + let result = EventLoop { + poll, + user_channel, + user_sender, + event_processor, + target, + }; + + result + } + + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy { + user_sender: self.user_sender.clone(), + } + } + + pub(crate) fn window_target(&self) -> &RootELW { + &self.target + } + + pub(crate) fn x_connection(&self) -> &Arc { + get_xtarget(&self.target).x_connection() + } + + pub fn run_return(&mut self, mut callback: F) + where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + let mut control_flow = ControlFlow::default(); + let mut events = Events::with_capacity(8); + + callback( + crate::event::Event::NewEvents(crate::event::StartCause::Init), + &self.target, + &mut control_flow, + ); + + loop { + // Process all pending events + self.drain_events(&mut callback, &mut control_flow); + + let wt = get_xtarget(&self.target); + + // Empty the user event buffer + { + while let Ok(event) = self.user_channel.try_recv() { + sticky_exit_callback( + crate::event::Event::UserEvent(event), + &self.target, + &mut control_flow, + &mut callback, + ); + } + } + // send MainEventsCleared + { + sticky_exit_callback( + crate::event::Event::MainEventsCleared, + &self.target, + &mut control_flow, + &mut callback, + ); + } + // Empty the redraw requests + { + // Release the lock to prevent deadlock + let windows: Vec<_> = wt.pending_redraws.lock().unwrap().drain().collect(); + + for wid in windows { + sticky_exit_callback( + Event::RedrawRequested(crate::window::WindowId(super::WindowId::X(wid))), + &self.target, + &mut control_flow, + &mut callback, + ); + } + } + // send RedrawEventsCleared + { + sticky_exit_callback( + crate::event::Event::RedrawEventsCleared, + &self.target, + &mut control_flow, + &mut callback, + ); + } + + let start = Instant::now(); + let (mut cause, deadline, timeout); + + match control_flow { + ControlFlow::Exit => break, + ControlFlow::Poll => { + cause = StartCause::Poll; + deadline = None; + timeout = Some(Duration::from_millis(0)); + } + ControlFlow::Wait => { + cause = StartCause::WaitCancelled { + start, + requested_resume: None, + }; + deadline = None; + timeout = None; + } + ControlFlow::WaitUntil(wait_deadline) => { + cause = StartCause::ResumeTimeReached { + start, + requested_resume: wait_deadline, + }; + timeout = if wait_deadline > start { + Some(wait_deadline - start) + } else { + Some(Duration::from_millis(0)) + }; + deadline = Some(wait_deadline); + } + } + + if self.event_processor.poll() { + // If the XConnection already contains buffered events, we don't + // need to wait for data on the socket. + // However, we still need to check for user events. + self.poll + .poll(&mut events, Some(Duration::from_millis(0))) + .unwrap(); + events.clear(); + + callback( + crate::event::Event::NewEvents(cause), + &self.target, + &mut control_flow, + ); + } else { + self.poll.poll(&mut events, timeout).unwrap(); + events.clear(); + + let wait_cancelled = deadline.map_or(false, |deadline| Instant::now() < deadline); + + if wait_cancelled { + cause = StartCause::WaitCancelled { + start, + requested_resume: deadline, + }; + } + + callback( + crate::event::Event::NewEvents(cause), + &self.target, + &mut control_flow, + ); + } + } + + callback( + crate::event::Event::LoopDestroyed, + &self.target, + &mut control_flow, + ); + } + + pub fn run(mut self, callback: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + self.run_return(callback); + ::std::process::exit(0); + } + + fn drain_events(&mut self, callback: &mut F, control_flow: &mut ControlFlow) + where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + let target = &self.target; + let mut xev = MaybeUninit::uninit(); + + let wt = get_xtarget(&self.target); + + while unsafe { self.event_processor.poll_one_event(xev.as_mut_ptr()) } { + let mut xev = unsafe { xev.assume_init() }; + self.event_processor.process_event(&mut xev, |event| { + sticky_exit_callback( + event, + target, + control_flow, + &mut |event, window_target, control_flow| { + if let Event::RedrawRequested(crate::window::WindowId( + super::WindowId::X(wid), + )) = event + { + wt.pending_redraws.lock().unwrap().insert(wid); + } else { + callback(event, window_target, control_flow); + } + }, + ); + }); + } + } +} + +pub(crate) fn get_xtarget(target: &RootELW) -> &EventLoopWindowTarget { + match target.p { + super::EventLoopWindowTarget::X(ref target) => target, + _ => unreachable!(), + } +} + +impl EventLoopWindowTarget { + /// Returns the `XConnection` of this events loop. + #[inline] + pub fn x_connection(&self) -> &Arc { + &self.xconn + } +} + +impl EventLoopProxy { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.user_sender.send(event).map_err(|e| { + EventLoopClosed(if let SendError::Disconnected(x) = e { + x + } else { + unreachable!() + }) + }) + } +} + +struct DeviceInfo<'a> { + xconn: &'a XConnection, + info: *const ffi::XIDeviceInfo, + count: usize, +} + +impl<'a> DeviceInfo<'a> { + fn get(xconn: &'a XConnection, device: c_int) -> Option { + unsafe { + let mut count = 0; + let info = (xconn.xinput2.XIQueryDevice)(xconn.display, device, &mut count); + xconn.check_errors().ok()?; + + if info.is_null() || count == 0 { + None + } else { + Some(DeviceInfo { + xconn, + info, + count: count as usize, + }) + } + } + } +} + +impl<'a> Drop for DeviceInfo<'a> { + fn drop(&mut self) { + assert!(!self.info.is_null()); + unsafe { (self.xconn.xinput2.XIFreeDeviceInfo)(self.info as *mut _) }; + } +} + +impl<'a> Deref for DeviceInfo<'a> { + type Target = [ffi::XIDeviceInfo]; + fn deref(&self) -> &Self::Target { + unsafe { slice::from_raw_parts(self.info, self.count) } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(ffi::Window); + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(c_int); + +pub struct Window(Arc); + +impl Deref for Window { + type Target = UnownedWindow; + #[inline] + fn deref(&self) -> &UnownedWindow { + &*self.0 + } +} + +impl Window { + pub fn new( + event_loop: &EventLoopWindowTarget, + attribs: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + let window = Arc::new(UnownedWindow::new(&event_loop, attribs, pl_attribs)?); + event_loop + .windows + .borrow_mut() + .insert(window.id(), Arc::downgrade(&window)); + Ok(Window(window)) + } +} + +impl Drop for Window { + fn drop(&mut self) { + let window = self.deref(); + let xconn = &window.xconn; + unsafe { + (xconn.xlib.XDestroyWindow)(xconn.display, window.id().0); + // If the window was somehow already destroyed, we'll get a `BadWindow` error, which we don't care about. + let _ = xconn.check_errors(); + } + } +} + +/// XEvents of type GenericEvent store their actual data in an XGenericEventCookie data structure. This is a wrapper to +/// extract the cookie from a GenericEvent XEvent and release the cookie data once it has been processed +struct GenericEventCookie<'a> { + xconn: &'a XConnection, + cookie: ffi::XGenericEventCookie, +} + +impl<'a> GenericEventCookie<'a> { + fn from_event<'b>( + xconn: &'b XConnection, + event: ffi::XEvent, + ) -> Option> { + unsafe { + let mut cookie: ffi::XGenericEventCookie = From::from(event); + if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == ffi::True { + Some(GenericEventCookie { xconn, cookie }) + } else { + None + } + } + } +} + +impl<'a> Drop for GenericEventCookie<'a> { + fn drop(&mut self) { + unsafe { + (self.xconn.xlib.XFreeEventData)(self.xconn.display, &mut self.cookie); + } + } +} + +#[derive(Debug, Default, Copy, Clone)] +struct XExtension { + opcode: c_int, + first_event_id: c_int, + first_error_id: c_int, +} + +fn mkwid(w: ffi::Window) -> crate::window::WindowId { + crate::window::WindowId(crate::platform_impl::WindowId::X(WindowId(w))) +} +fn mkdid(w: c_int) -> crate::event::DeviceId { + crate::event::DeviceId(crate::platform_impl::DeviceId::X(DeviceId(w))) +} + +#[derive(Debug)] +struct Device { + name: String, + scroll_axes: Vec<(i32, ScrollAxis)>, + // For master devices, this is the paired device (pointer <-> keyboard). + // For slave devices, this is the master. + attachment: c_int, +} + +#[derive(Debug, Copy, Clone)] +struct ScrollAxis { + increment: f64, + orientation: ScrollOrientation, + position: f64, +} + +#[derive(Debug, Copy, Clone)] +enum ScrollOrientation { + Vertical, + Horizontal, +} + +impl Device { + fn new(el: &EventProcessor, info: &ffi::XIDeviceInfo) -> Self { + let name = unsafe { CStr::from_ptr(info.name).to_string_lossy() }; + let mut scroll_axes = Vec::new(); + + let wt = get_xtarget(&el.target); + + if Device::physical_device(info) { + // Register for global raw events + let mask = ffi::XI_RawMotionMask + | ffi::XI_RawButtonPressMask + | ffi::XI_RawButtonReleaseMask + | ffi::XI_RawKeyPressMask + | ffi::XI_RawKeyReleaseMask; + // The request buffer is flushed when we poll for events + wt.xconn + .select_xinput_events(wt.root, info.deviceid, mask) + .queue(); + + // Identify scroll axes + for class_ptr in Device::classes(info) { + let class = unsafe { &**class_ptr }; + match class._type { + ffi::XIScrollClass => { + let info = unsafe { + mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIScrollClassInfo>(class) + }; + scroll_axes.push(( + info.number, + ScrollAxis { + increment: info.increment, + orientation: match info.scroll_type { + ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, + ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, + _ => unreachable!(), + }, + position: 0.0, + }, + )); + } + _ => {} + } + } + } + + let mut device = Device { + name: name.into_owned(), + scroll_axes, + attachment: info.attachment, + }; + device.reset_scroll_position(info); + device + } + + fn reset_scroll_position(&mut self, info: &ffi::XIDeviceInfo) { + if Device::physical_device(info) { + for class_ptr in Device::classes(info) { + let class = unsafe { &**class_ptr }; + match class._type { + ffi::XIValuatorClass => { + let info = unsafe { + mem::transmute::<&ffi::XIAnyClassInfo, &ffi::XIValuatorClassInfo>(class) + }; + if let Some(&mut (_, ref mut axis)) = self + .scroll_axes + .iter_mut() + .find(|&&mut (axis, _)| axis == info.number) + { + axis.position = info.value; + } + } + _ => {} + } + } + } + } + + #[inline] + fn physical_device(info: &ffi::XIDeviceInfo) -> bool { + info._use == ffi::XISlaveKeyboard + || info._use == ffi::XISlavePointer + || info._use == ffi::XIFloatingSlave + } + + #[inline] + fn classes(info: &ffi::XIDeviceInfo) -> &[*const ffi::XIAnyClassInfo] { + unsafe { + slice::from_raw_parts( + info.classes as *const *const ffi::XIAnyClassInfo, + info.num_classes as usize, + ) + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/monitor.rs new file mode 100644 index 0000000..274e0cd --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/monitor.rs @@ -0,0 +1,314 @@ +use std::os::raw::*; + +use parking_lot::Mutex; + +use super::{ + ffi::{ + RRCrtc, RRCrtcChangeNotifyMask, RRMode, RROutputPropertyNotifyMask, + RRScreenChangeNotifyMask, True, Window, XRRCrtcInfo, XRRScreenResources, + }, + util, XConnection, XError, +}; +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform_impl::{MonitorHandle as PlatformMonitorHandle, VideoMode as PlatformVideoMode}, +}; + +// Used for testing. This should always be committed as false. +const DISABLE_MONITOR_LIST_CACHING: bool = false; + +lazy_static! { + static ref MONITORS: Mutex>> = Mutex::default(); +} + +pub fn invalidate_cached_monitor_list() -> Option> { + // We update this lazily. + (*MONITORS.lock()).take() +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VideoMode { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate: u16, + pub(crate) native_mode: RRMode, + pub(crate) monitor: Option, +} + +impl VideoMode { + #[inline] + pub fn size(&self) -> PhysicalSize { + self.size.into() + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + #[inline] + pub fn refresh_rate(&self) -> u16 { + self.refresh_rate + } + + #[inline] + pub fn monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: PlatformMonitorHandle::X(self.monitor.clone().unwrap()), + } + } +} + +#[derive(Debug, Clone)] +pub struct MonitorHandle { + /// The actual id + pub(crate) id: RRCrtc, + /// The name of the monitor + pub(crate) name: String, + /// The size of the monitor + dimensions: (u32, u32), + /// The position of the monitor in the X screen + position: (i32, i32), + /// If the monitor is the primary one + primary: bool, + /// The DPI scale factor + pub(crate) scale_factor: f64, + /// Used to determine which windows are on this monitor + pub(crate) rect: util::AaRect, + /// Supported video modes on this monitor + video_modes: Vec, +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(&other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.id.cmp(&other.id) + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash(&self, state: &mut H) { + self.id.hash(state); + } +} + +impl MonitorHandle { + fn new( + xconn: &XConnection, + resources: *mut XRRScreenResources, + id: RRCrtc, + crtc: *mut XRRCrtcInfo, + primary: bool, + ) -> Option { + let (name, scale_factor, video_modes) = unsafe { xconn.get_output_info(resources, crtc)? }; + let dimensions = unsafe { ((*crtc).width as u32, (*crtc).height as u32) }; + let position = unsafe { ((*crtc).x as i32, (*crtc).y as i32) }; + let rect = util::AaRect::new(position, dimensions); + Some(MonitorHandle { + id, + name, + scale_factor, + dimensions, + position, + primary, + rect, + video_modes, + }) + } + + pub fn dummy() -> Self { + MonitorHandle { + id: 0, + name: "".into(), + scale_factor: 1.0, + dimensions: (1, 1), + position: (0, 0), + primary: true, + rect: util::AaRect::new((0, 0), (1, 1)), + video_modes: Vec::new(), + } + } + + pub(crate) fn is_dummy(&self) -> bool { + // Zero is an invalid XID value; no real monitor will have it + self.id == 0 + } + + pub fn name(&self) -> Option { + Some(self.name.clone()) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + self.id as u32 + } + + pub fn size(&self) -> PhysicalSize { + self.dimensions.into() + } + + pub fn position(&self) -> PhysicalPosition { + self.position.into() + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.scale_factor + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator { + let monitor = self.clone(); + self.video_modes.clone().into_iter().map(move |mut x| { + x.monitor = Some(monitor.clone()); + RootVideoMode { + video_mode: PlatformVideoMode::X(x), + } + }) + } +} + +impl XConnection { + pub fn get_monitor_for_window(&self, window_rect: Option) -> MonitorHandle { + let monitors = self.available_monitors(); + + if monitors.is_empty() { + // Return a dummy monitor to avoid panicking + return MonitorHandle::dummy(); + } + + let default = monitors.get(0).unwrap(); + + let window_rect = match window_rect { + Some(rect) => rect, + None => return default.to_owned(), + }; + + let mut largest_overlap = 0; + let mut matched_monitor = default; + for monitor in &monitors { + let overlapping_area = window_rect.get_overlapping_area(&monitor.rect); + if overlapping_area > largest_overlap { + largest_overlap = overlapping_area; + matched_monitor = &monitor; + } + } + + matched_monitor.to_owned() + } + + fn query_monitor_list(&self) -> Vec { + unsafe { + let mut major = 0; + let mut minor = 0; + (self.xrandr.XRRQueryVersion)(self.display, &mut major, &mut minor); + + let root = (self.xlib.XDefaultRootWindow)(self.display); + let resources = if (major == 1 && minor >= 3) || major > 1 { + (self.xrandr.XRRGetScreenResourcesCurrent)(self.display, root) + } else { + // WARNING: this function is supposedly very slow, on the order of hundreds of ms. + // Upon failure, `resources` will be null. + (self.xrandr.XRRGetScreenResources)(self.display, root) + }; + + if resources.is_null() { + panic!("[winit] `XRRGetScreenResources` returned NULL. That should only happen if the root window doesn't exist."); + } + + let mut available; + let mut has_primary = false; + + let primary = (self.xrandr.XRRGetOutputPrimary)(self.display, root); + available = Vec::with_capacity((*resources).ncrtc as usize); + for crtc_index in 0..(*resources).ncrtc { + let crtc_id = *((*resources).crtcs.offset(crtc_index as isize)); + let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id); + let is_active = (*crtc).width > 0 && (*crtc).height > 0 && (*crtc).noutput > 0; + if is_active { + let is_primary = *(*crtc).outputs.offset(0) == primary; + has_primary |= is_primary; + MonitorHandle::new(self, resources, crtc_id, crtc, is_primary) + .map(|monitor_id| available.push(monitor_id)); + } + (self.xrandr.XRRFreeCrtcInfo)(crtc); + } + + // If no monitors were detected as being primary, we just pick one ourselves! + if !has_primary { + if let Some(ref mut fallback) = available.first_mut() { + // Setting this here will come in handy if we ever add an `is_primary` method. + fallback.primary = true; + } + } + + (self.xrandr.XRRFreeScreenResources)(resources); + available + } + } + + pub fn available_monitors(&self) -> Vec { + let mut monitors_lock = MONITORS.lock(); + (*monitors_lock) + .as_ref() + .cloned() + .or_else(|| { + let monitors = Some(self.query_monitor_list()); + if !DISABLE_MONITOR_LIST_CACHING { + (*monitors_lock) = monitors.clone(); + } + monitors + }) + .unwrap() + } + + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + self.available_monitors() + .into_iter() + .find(|monitor| monitor.primary) + .unwrap_or_else(MonitorHandle::dummy) + } + + pub fn select_xrandr_input(&self, root: Window) -> Result { + let has_xrandr = unsafe { + let mut major = 0; + let mut minor = 0; + (self.xrandr.XRRQueryVersion)(self.display, &mut major, &mut minor) + }; + assert!( + has_xrandr == True, + "[winit] XRandR extension not available." + ); + + let mut event_offset = 0; + let mut error_offset = 0; + let status = unsafe { + (self.xrandr.XRRQueryExtension)(self.display, &mut event_offset, &mut error_offset) + }; + + if status != True { + self.check_errors()?; + unreachable!("[winit] `XRRQueryExtension` failed but no error was received."); + } + + let mask = RRCrtcChangeNotifyMask | RROutputPropertyNotifyMask | RRScreenChangeNotifyMask; + unsafe { (self.xrandr.XRRSelectInput)(self.display, root, mask) }; + + Ok(event_offset) + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/atom.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/atom.rs similarity index 83% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/atom.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/atom.rs index fe97d3a..c311c5d 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/atom.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/atom.rs @@ -1,7 +1,9 @@ -use std::collections::HashMap; -use std::ffi::{CStr, CString}; -use std::fmt::Debug; -use std::os::raw::*; +use std::{ + collections::HashMap, + ffi::{CStr, CString}, + fmt::Debug, + os::raw::*, +}; use parking_lot::Mutex; @@ -21,11 +23,9 @@ impl XConnection { if let Some(atom) = cached_atom { atom } else { - let atom = unsafe { (self.xlib.XInternAtom)( - self.display, - name.as_ptr() as *const c_char, - ffi::False, - ) }; + let atom = unsafe { + (self.xlib.XInternAtom)(self.display, name.as_ptr() as *const c_char, ffi::False) + }; if atom == 0 { let msg = format!( "`XInternAtom` failed, which really shouldn't happen. Atom: {:?}, Error: {:#?}", @@ -52,7 +52,7 @@ impl XConnection { // Note: this doesn't use caching, for the sake of simplicity. // If you're dealing with this many atoms, you'll usually want to cache them locally anyway. - pub unsafe fn get_atoms(&self, names: &[*mut c_char]) -> Result, XError> { + pub unsafe fn get_atoms(&self, names: &[*mut c_char]) -> Result, XError> { let mut atoms = Vec::with_capacity(names.len()); (self.xlib.XInternAtoms)( self.display, diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/client_msg.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/client_msg.rs new file mode 100644 index 0000000..2f2b7ed --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/client_msg.rs @@ -0,0 +1,46 @@ +use super::*; + +pub type ClientMsgPayload = [c_long; 5]; + +impl XConnection { + pub fn send_event>( + &self, + target_window: c_ulong, + event_mask: Option, + event: T, + ) -> Flusher<'_> { + let event_mask = event_mask.unwrap_or(ffi::NoEventMask); + unsafe { + (self.xlib.XSendEvent)( + self.display, + target_window, + ffi::False, + event_mask, + &mut event.into(), + ); + } + Flusher::new(self) + } + + pub fn send_client_msg( + &self, + window: c_ulong, // The window this is "about"; not necessarily this window + target_window: c_ulong, // The window we're sending to + message_type: ffi::Atom, + event_mask: Option, + data: ClientMsgPayload, + ) -> Flusher<'_> { + let event = ffi::XClientMessageEvent { + type_: ffi::ClientMessage, + display: self.display, + window, + message_type, + format: c_long::FORMAT as c_int, + data: unsafe { mem::transmute(data) }, + // These fields are ignored by `XSendEvent` + serial: 0, + send_event: 0, + }; + self.send_event(target_window, event_mask, event) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/cursor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/cursor.rs new file mode 100644 index 0000000..684af49 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/cursor.rs @@ -0,0 +1,129 @@ +use crate::window::CursorIcon; + +use super::*; + +impl XConnection { + pub fn set_cursor_icon(&self, window: ffi::Window, cursor: Option) { + let cursor = *self + .cursor_cache + .lock() + .entry(cursor) + .or_insert_with(|| self.get_cursor(cursor)); + + self.update_cursor(window, cursor); + } + + fn create_empty_cursor(&self) -> ffi::Cursor { + let data = 0; + let pixmap = unsafe { + let screen = (self.xlib.XDefaultScreen)(self.display); + let window = (self.xlib.XRootWindow)(self.display, screen); + (self.xlib.XCreateBitmapFromData)(self.display, window, &data, 1, 1) + }; + + if pixmap == 0 { + panic!("failed to allocate pixmap for cursor"); + } + + unsafe { + // We don't care about this color, since it only fills bytes + // in the pixmap which are not 0 in the mask. + let mut dummy_color = MaybeUninit::uninit(); + let cursor = (self.xlib.XCreatePixmapCursor)( + self.display, + pixmap, + pixmap, + dummy_color.as_mut_ptr(), + dummy_color.as_mut_ptr(), + 0, + 0, + ); + (self.xlib.XFreePixmap)(self.display, pixmap); + + cursor + } + } + + fn load_cursor(&self, name: &[u8]) -> ffi::Cursor { + unsafe { + (self.xcursor.XcursorLibraryLoadCursor)(self.display, name.as_ptr() as *const c_char) + } + } + + fn load_first_existing_cursor(&self, names: &[&[u8]]) -> ffi::Cursor { + for name in names.iter() { + let xcursor = self.load_cursor(name); + if xcursor != 0 { + return xcursor; + } + } + 0 + } + + fn get_cursor(&self, cursor: Option) -> ffi::Cursor { + let cursor = match cursor { + Some(cursor) => cursor, + None => return self.create_empty_cursor(), + }; + + let load = |name: &[u8]| self.load_cursor(name); + + let loadn = |names: &[&[u8]]| self.load_first_existing_cursor(names); + + // Try multiple names in some cases where the name + // differs on the desktop environments or themes. + // + // Try the better looking (or more suiting) names first. + match cursor { + CursorIcon::Alias => load(b"link\0"), + CursorIcon::Arrow => load(b"arrow\0"), + CursorIcon::Cell => load(b"plus\0"), + CursorIcon::Copy => load(b"copy\0"), + CursorIcon::Crosshair => load(b"crosshair\0"), + CursorIcon::Default => load(b"left_ptr\0"), + CursorIcon::Hand => loadn(&[b"hand2\0", b"hand1\0"]), + CursorIcon::Help => load(b"question_arrow\0"), + CursorIcon::Move => load(b"move\0"), + CursorIcon::Grab => loadn(&[b"openhand\0", b"grab\0"]), + CursorIcon::Grabbing => loadn(&[b"closedhand\0", b"grabbing\0"]), + CursorIcon::Progress => load(b"left_ptr_watch\0"), + CursorIcon::AllScroll => load(b"all-scroll\0"), + CursorIcon::ContextMenu => load(b"context-menu\0"), + + CursorIcon::NoDrop => loadn(&[b"no-drop\0", b"circle\0"]), + CursorIcon::NotAllowed => load(b"crossed_circle\0"), + + // Resize cursors + CursorIcon::EResize => load(b"right_side\0"), + CursorIcon::NResize => load(b"top_side\0"), + CursorIcon::NeResize => load(b"top_right_corner\0"), + CursorIcon::NwResize => load(b"top_left_corner\0"), + CursorIcon::SResize => load(b"bottom_side\0"), + CursorIcon::SeResize => load(b"bottom_right_corner\0"), + CursorIcon::SwResize => load(b"bottom_left_corner\0"), + CursorIcon::WResize => load(b"left_side\0"), + CursorIcon::EwResize => load(b"h_double_arrow\0"), + CursorIcon::NsResize => load(b"v_double_arrow\0"), + CursorIcon::NwseResize => loadn(&[b"bd_double_arrow\0", b"size_bdiag\0"]), + CursorIcon::NeswResize => loadn(&[b"fd_double_arrow\0", b"size_fdiag\0"]), + CursorIcon::ColResize => loadn(&[b"split_h\0", b"h_double_arrow\0"]), + CursorIcon::RowResize => loadn(&[b"split_v\0", b"v_double_arrow\0"]), + + CursorIcon::Text => loadn(&[b"text\0", b"xterm\0"]), + CursorIcon::VerticalText => load(b"vertical-text\0"), + + CursorIcon::Wait => load(b"watch\0"), + + CursorIcon::ZoomIn => load(b"zoom-in\0"), + CursorIcon::ZoomOut => load(b"zoom-out\0"), + } + } + + fn update_cursor(&self, window: ffi::Window, cursor: ffi::Cursor) { + unsafe { + (self.xlib.XDefineCursor)(self.display, window, cursor); + + self.flush_requests().expect("Failed to set the cursor"); + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/format.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/format.rs similarity index 53% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/format.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/format.rs index 1be8b64..1ab5e01 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/format.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/format.rs @@ -1,6 +1,4 @@ -use std::fmt::Debug; -use std::mem; -use std::os::raw::*; +use std::{fmt::Debug, mem, os::raw::*}; // This isn't actually the number of the bits in the format. // X11 does a match on this value to determine which type to call sizeof on. @@ -23,10 +21,6 @@ impl Format { } } - pub fn is_same_size_as(&self) -> bool { - mem::size_of::() == self.get_actual_size() - } - pub fn get_actual_size(&self) -> usize { match self { &Format::Char => mem::size_of::(), @@ -34,15 +28,6 @@ impl Format { &Format::Long => mem::size_of::(), } } - - pub fn get_payload_size(&self) -> usize { - match self { - // Due to the wonders of X11, half the space goes unused if you're not using longs (on 64-bit). - &Format::Char => mem::size_of::() * 20, - &Format::Short => mem::size_of::() * 10, - &Format::Long => mem::size_of::() * 5, - } - } } pub trait Formattable: Debug + Clone + Copy + PartialEq + PartialOrd { @@ -50,9 +35,21 @@ pub trait Formattable: Debug + Clone + Copy + PartialEq + PartialOrd { } // You might be surprised by the absence of c_int, but not as surprised as X11 would be by the presence of it. -impl Formattable for c_schar { const FORMAT: Format = Format::Char; } -impl Formattable for c_uchar { const FORMAT: Format = Format::Char; } -impl Formattable for c_short { const FORMAT: Format = Format::Short; } -impl Formattable for c_ushort { const FORMAT: Format = Format::Short; } -impl Formattable for c_long { const FORMAT: Format = Format::Long; } -impl Formattable for c_ulong { const FORMAT: Format = Format::Long; } +impl Formattable for c_schar { + const FORMAT: Format = Format::Char; +} +impl Formattable for c_uchar { + const FORMAT: Format = Format::Char; +} +impl Formattable for c_short { + const FORMAT: Format = Format::Short; +} +impl Formattable for c_ushort { + const FORMAT: Format = Format::Short; +} +impl Formattable for c_long { + const FORMAT: Format = Format::Long; +} +impl Formattable for c_ulong { + const FORMAT: Format = Format::Long; +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/geometry.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/geometry.rs similarity index 75% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/geometry.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/geometry.rs index 1a85b1c..d8f466f 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/geometry.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/geometry.rs @@ -1,7 +1,6 @@ use std::cmp; use super::*; -use {LogicalPosition, LogicalSize}; // Friendly neighborhood axis-aligned rectangle #[derive(Debug, Clone, PartialEq, Eq)] @@ -16,7 +15,12 @@ impl AaRect { pub fn new((x, y): (i32, i32), (width, height): (u32, u32)) -> Self { let (x, y) = (x as i64, y as i64); let (width, height) = (width as i64, height as i64); - AaRect { x, y, width, height } + AaRect { + x, + y, + width, + height, + } } pub fn contains_point(&self, x: i64, y: i64) -> bool { @@ -36,14 +40,14 @@ impl AaRect { } } -#[derive(Debug)] +#[derive(Debug, Default)] pub struct TranslatedCoords { pub x_rel_root: c_int, pub y_rel_root: c_int, pub child: ffi::Window, } -#[derive(Debug)] +#[derive(Debug, Default)] pub struct Geometry { pub root: ffi::Window, // If you want positions relative to the root window, use translate_coords. @@ -73,22 +77,17 @@ pub struct FrameExtents { impl FrameExtents { pub fn new(left: c_ulong, right: c_ulong, top: c_ulong, bottom: c_ulong) -> Self { - FrameExtents { left, right, top, bottom } + FrameExtents { + left, + right, + top, + bottom, + } } pub fn from_border(border: c_ulong) -> Self { Self::new(border, border, border, border) } - - pub fn as_logical(&self, factor: f64) -> LogicalFrameExtents { - let logicalize = |value: c_ulong| value as f64 / factor; - LogicalFrameExtents { - left: logicalize(self.left), - right: logicalize(self.right), - top: logicalize(self.top), - bottom: logicalize(self.bottom), - } - } } #[derive(Debug, Clone)] @@ -116,45 +115,40 @@ impl FrameExtentsHeuristic { pub fn inner_pos_to_outer(&self, x: i32, y: i32) -> (i32, i32) { use self::FrameExtentsHeuristicPath::*; if self.heuristic_path != UnsupportedBordered { - (x - self.frame_extents.left as i32, y - self.frame_extents.top as i32) + ( + x - self.frame_extents.left as i32, + y - self.frame_extents.top as i32, + ) } else { (x, y) } } - pub fn inner_pos_to_outer_logical(&self, mut logical: LogicalPosition, factor: f64) -> LogicalPosition { - use self::FrameExtentsHeuristicPath::*; - if self.heuristic_path != UnsupportedBordered { - let frame_extents = self.frame_extents.as_logical(factor); - logical.x -= frame_extents.left; - logical.y -= frame_extents.top; - } - logical - } - pub fn inner_size_to_outer(&self, width: u32, height: u32) -> (u32, u32) { ( width.saturating_add( - self.frame_extents.left.saturating_add(self.frame_extents.right) as u32 + self.frame_extents + .left + .saturating_add(self.frame_extents.right) as u32, ), height.saturating_add( - self.frame_extents.top.saturating_add(self.frame_extents.bottom) as u32 + self.frame_extents + .top + .saturating_add(self.frame_extents.bottom) as u32, ), ) } - - pub fn inner_size_to_outer_logical(&self, mut logical: LogicalSize, factor: f64) -> LogicalSize { - let frame_extents = self.frame_extents.as_logical(factor); - logical.width += frame_extents.left + frame_extents.right; - logical.height += frame_extents.top + frame_extents.bottom; - logical - } } impl XConnection { - // This is adequate for get_inner_position - pub fn translate_coords(&self, window: ffi::Window, root: ffi::Window) -> Result { - let mut translated_coords: TranslatedCoords = unsafe { mem::uninitialized() }; + // This is adequate for inner_position + pub fn translate_coords( + &self, + window: ffi::Window, + root: ffi::Window, + ) -> Result { + let mut coords = TranslatedCoords::default(); + unsafe { (self.xlib.XTranslateCoordinates)( self.display, @@ -162,18 +156,20 @@ impl XConnection { root, 0, 0, - &mut translated_coords.x_rel_root, - &mut translated_coords.y_rel_root, - &mut translated_coords.child, + &mut coords.x_rel_root, + &mut coords.y_rel_root, + &mut coords.child, ); } - //println!("XTranslateCoordinates coords:{:?}", translated_coords); - self.check_errors().map(|_| translated_coords) + + self.check_errors()?; + Ok(coords) } - // This is adequate for get_inner_size + // This is adequate for inner_size pub fn get_geometry(&self, window: ffi::Window) -> Result { - let mut geometry: Geometry = unsafe { mem::uninitialized() }; + let mut geometry = Geometry::default(); + let _status = unsafe { (self.xlib.XGetGeometry)( self.display, @@ -187,8 +183,9 @@ impl XConnection { &mut geometry.depth, ) }; - //println!("XGetGeometry geo:{:?}", geometry); - self.check_errors().map(|_| geometry) + + self.check_errors()?; + Ok(geometry) } fn get_frame_extents(&self, window: ffi::Window) -> Option { @@ -201,11 +198,9 @@ impl XConnection { // Of the WMs tested, xmonad, i3, dwm, IceWM (1.3.x and earlier), and blackbox don't // support this. As this is part of EWMH (Extended Window Manager Hints), it's likely to // be unsupported by many smaller WMs. - let extents: Option> = self.get_property( - window, - extents_atom, - ffi::XA_CARDINAL, - ).ok(); + let extents: Option> = self + .get_property(window, extents_atom, ffi::XA_CARDINAL) + .ok(); extents.and_then(|extents| { if extents.len() >= 4 { @@ -228,21 +223,19 @@ impl XConnection { return None; } - let client_list: Option> = self.get_property( - root, - client_list_atom, - ffi::XA_WINDOW, - ).ok(); + let client_list: Option> = self + .get_property(root, client_list_atom, ffi::XA_WINDOW) + .ok(); client_list.map(|client_list| client_list.contains(&window)) } fn get_parent_window(&self, window: ffi::Window) -> Result { let parent = unsafe { - let mut root: ffi::Window = mem::uninitialized(); - let mut parent: ffi::Window = mem::uninitialized(); + let mut root = 0; + let mut parent = 0; let mut children: *mut ffi::Window = ptr::null_mut(); - let mut nchildren: c_uint = mem::uninitialized(); + let mut nchildren = 0; // What's filled into `parent` if `window` is the root window? let _status = (self.xlib.XQueryTree)( @@ -264,7 +257,11 @@ impl XConnection { self.check_errors().map(|_| parent) } - fn climb_hierarchy(&self, window: ffi::Window, root: ffi::Window) -> Result { + fn climb_hierarchy( + &self, + window: ffi::Window, + root: ffi::Window, + ) -> Result { let mut outer_window = window; loop { let candidate = self.get_parent_window(outer_window)?; @@ -276,7 +273,11 @@ impl XConnection { Ok(outer_window) } - pub fn get_frame_extents_heuristic(&self, window: ffi::Window, root: ffi::Window) -> FrameExtentsHeuristic { + pub fn get_frame_extents_heuristic( + &self, + window: ffi::Window, + root: ffi::Window, + ) -> FrameExtentsHeuristic { use self::FrameExtentsHeuristicPath::*; // Position relative to root window. @@ -284,15 +285,16 @@ impl XConnection { // isn't nested are outlined in the comments throghout this function, but in addition to // that, fullscreen windows often aren't nested. let (inner_y_rel_root, child) = { - let coords = self.translate_coords(window, root).expect("Failed to translate window coordinates"); - ( - coords.y_rel_root, - coords.child, - ) + let coords = self + .translate_coords(window, root) + .expect("Failed to translate window coordinates"); + (coords.y_rel_root, coords.child) }; let (width, height, border) = { - let inner_geometry = self.get_geometry(window).expect("Failed to get inner window geometry"); + let inner_geometry = self + .get_geometry(window) + .expect("Failed to get inner window geometry"); ( inner_geometry.width, inner_geometry.height, @@ -343,9 +345,13 @@ impl XConnection { // If the position value we have is for a nested window used as the client area, we'll // just climb up the hierarchy and get the geometry of the outermost window we're // nested in. - let outer_window = self.climb_hierarchy(window, root).expect("Failed to climb window hierarchy"); + let outer_window = self + .climb_hierarchy(window, root) + .expect("Failed to climb window hierarchy"); let (outer_y, outer_width, outer_height) = { - let outer_geometry = self.get_geometry(outer_window).expect("Failed to get outer window geometry"); + let outer_geometry = self + .get_geometry(outer_window) + .expect("Failed to get outer window geometry"); ( outer_geometry.y_rel_parent, outer_geometry.width, @@ -364,12 +370,8 @@ impl XConnection { let top = offset_y; let bottom = diff_y.saturating_sub(offset_y); - let frame_extents = FrameExtents::new( - left.into(), - right.into(), - top.into(), - bottom.into(), - ); + let frame_extents = + FrameExtents::new(left.into(), right.into(), top.into(), bottom.into()); FrameExtentsHeuristic { frame_extents, heuristic_path: UnsupportedNested, diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/hint.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/hint.rs similarity index 53% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/hint.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/hint.rs index c58e908..809f306 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/hint.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/hint.rs @@ -1,10 +1,10 @@ +use std::slice; use std::sync::Arc; use super::*; -pub const MWM_HINTS_DECORATIONS: c_ulong = 2; - #[derive(Debug)] +#[allow(dead_code)] pub enum StateOperation { Remove = 0, // _NET_WM_STATE_REMOVE Add = 1, // _NET_WM_STATE_ADD @@ -24,6 +24,7 @@ impl From for StateOperation { /// X window type. Maps directly to /// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum WindowType { /// A desktop feature. This can include a single window containing desktop icons with the same dimensions as the /// screen, allowing the desktop environment to have full control of the desktop, without the need for proxying @@ -72,51 +73,123 @@ impl Default for WindowType { impl WindowType { pub(crate) fn as_atom(&self, xconn: &Arc) -> ffi::Atom { use self::WindowType::*; - let atom_name: &[u8] = match self { - &Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", - &Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", - &Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", - &Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", - &Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", - &Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", - &Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", - &DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", - &PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", - &Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", - &Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", - &Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", - &Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", - &Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", + let atom_name: &[u8] = match *self { + Desktop => b"_NET_WM_WINDOW_TYPE_DESKTOP\0", + Dock => b"_NET_WM_WINDOW_TYPE_DOCK\0", + Toolbar => b"_NET_WM_WINDOW_TYPE_TOOLBAR\0", + Menu => b"_NET_WM_WINDOW_TYPE_MENU\0", + Utility => b"_NET_WM_WINDOW_TYPE_UTILITY\0", + Splash => b"_NET_WM_WINDOW_TYPE_SPLASH\0", + Dialog => b"_NET_WM_WINDOW_TYPE_DIALOG\0", + DropdownMenu => b"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU\0", + PopupMenu => b"_NET_WM_WINDOW_TYPE_POPUP_MENU\0", + Tooltip => b"_NET_WM_WINDOW_TYPE_TOOLTIP\0", + Notification => b"_NET_WM_WINDOW_TYPE_NOTIFICATION\0", + Combo => b"_NET_WM_WINDOW_TYPE_COMBO\0", + Dnd => b"_NET_WM_WINDOW_TYPE_DND\0", + Normal => b"_NET_WM_WINDOW_TYPE_NORMAL\0", }; unsafe { xconn.get_atom_unchecked(atom_name) } } } +pub struct MotifHints { + hints: MwmHints, +} + +#[repr(C)] +struct MwmHints { + flags: c_ulong, + functions: c_ulong, + decorations: c_ulong, + input_mode: c_long, + status: c_ulong, +} + +#[allow(dead_code)] +mod mwm { + use libc::c_ulong; + + // Motif WM hints are obsolete, but still widely supported. + // https://stackoverflow.com/a/1909708 + pub const MWM_HINTS_FUNCTIONS: c_ulong = 1 << 0; + pub const MWM_HINTS_DECORATIONS: c_ulong = 1 << 1; + + pub const MWM_FUNC_ALL: c_ulong = 1 << 0; + pub const MWM_FUNC_RESIZE: c_ulong = 1 << 1; + pub const MWM_FUNC_MOVE: c_ulong = 1 << 2; + pub const MWM_FUNC_MINIMIZE: c_ulong = 1 << 3; + pub const MWM_FUNC_MAXIMIZE: c_ulong = 1 << 4; + pub const MWM_FUNC_CLOSE: c_ulong = 1 << 5; +} + +impl MotifHints { + pub fn new() -> MotifHints { + MotifHints { + hints: MwmHints { + flags: 0, + functions: 0, + decorations: 0, + input_mode: 0, + status: 0, + }, + } + } + + pub fn set_decorations(&mut self, decorations: bool) { + self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; + self.hints.decorations = decorations as c_ulong; + } + + pub fn set_maximizable(&mut self, maximizable: bool) { + if maximizable { + self.add_func(mwm::MWM_FUNC_MAXIMIZE); + } else { + self.remove_func(mwm::MWM_FUNC_MAXIMIZE); + } + } + + fn add_func(&mut self, func: c_ulong) { + if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 { + if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { + self.hints.functions &= !func; + } else { + self.hints.functions |= func; + } + } + } + + fn remove_func(&mut self, func: c_ulong) { + if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { + self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; + self.hints.functions = mwm::MWM_FUNC_ALL; + } + + if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { + self.hints.functions |= func; + } else { + self.hints.functions &= !func; + } + } +} + +impl MwmHints { + fn as_slice(&self) -> &[c_ulong] { + unsafe { slice::from_raw_parts(self as *const _ as *const c_ulong, 5) } + } +} + pub struct NormalHints<'a> { size_hints: XSmartPointer<'a, ffi::XSizeHints>, } impl<'a> NormalHints<'a> { pub fn new(xconn: &'a XConnection) -> Self { - NormalHints { size_hints: xconn.alloc_size_hints() } - } - - pub fn has_flag(&self, flag: c_long) -> bool { - has_flag(self.size_hints.flags, flag) - } - - fn getter(&self, flag: c_long, field1: &c_int, field2: &c_int) -> Option<(u32, u32)> { - if self.has_flag(flag) { - Some((*field1 as _, *field2 as _)) - } else { - None + NormalHints { + size_hints: xconn.alloc_size_hints(), } } - pub fn get_size(&self) -> Option<(u32, u32)> { - self.getter(ffi::PSize, &self.size_hints.width, &self.size_hints.height) - } - // WARNING: This hint is obsolete pub fn set_size(&mut self, size: Option<(u32, u32)>) { if let Some((width, height)) = size { @@ -128,10 +201,6 @@ impl<'a> NormalHints<'a> { } } - pub fn get_max_size(&self) -> Option<(u32, u32)> { - self.getter(ffi::PMaxSize, &self.size_hints.max_width, &self.size_hints.max_height) - } - pub fn set_max_size(&mut self, max_size: Option<(u32, u32)>) { if let Some((max_width, max_height)) = max_size { self.size_hints.flags |= ffi::PMaxSize; @@ -142,10 +211,6 @@ impl<'a> NormalHints<'a> { } } - pub fn get_min_size(&self) -> Option<(u32, u32)> { - self.getter(ffi::PMinSize, &self.size_hints.min_width, &self.size_hints.min_height) - } - pub fn set_min_size(&mut self, min_size: Option<(u32, u32)>) { if let Some((min_width, min_height)) = min_size { self.size_hints.flags |= ffi::PMinSize; @@ -156,10 +221,6 @@ impl<'a> NormalHints<'a> { } } - pub fn get_resize_increments(&self) -> Option<(u32, u32)> { - self.getter(ffi::PResizeInc, &self.size_hints.width_inc, &self.size_hints.height_inc) - } - pub fn set_resize_increments(&mut self, resize_increments: Option<(u32, u32)>) { if let Some((width_inc, height_inc)) = resize_increments { self.size_hints.flags |= ffi::PResizeInc; @@ -170,10 +231,6 @@ impl<'a> NormalHints<'a> { } } - pub fn get_base_size(&self) -> Option<(u32, u32)> { - self.getter(ffi::PBaseSize, &self.size_hints.base_width, &self.size_hints.base_height) - } - pub fn set_base_size(&mut self, base_size: Option<(u32, u32)>) { if let Some((base_width, base_height)) = base_size { self.size_hints.flags |= ffi::PBaseSize; @@ -186,7 +243,10 @@ impl<'a> NormalHints<'a> { } impl XConnection { - pub fn get_wm_hints(&self, window: ffi::Window) -> Result, XError> { + pub fn get_wm_hints( + &self, + window: ffi::Window, + ) -> Result, XError> { let wm_hints = unsafe { (self.xlib.XGetWMHints)(self.display, window) }; self.check_errors()?; let wm_hints = if wm_hints.is_null() { @@ -197,39 +257,67 @@ impl XConnection { Ok(wm_hints) } - pub fn set_wm_hints(&self, window: ffi::Window, wm_hints: XSmartPointer) -> Flusher { + pub fn set_wm_hints( + &self, + window: ffi::Window, + wm_hints: XSmartPointer<'_, ffi::XWMHints>, + ) -> Flusher<'_> { unsafe { - (self.xlib.XSetWMHints)( - self.display, - window, - wm_hints.ptr, - ); + (self.xlib.XSetWMHints)(self.display, window, wm_hints.ptr); } Flusher::new(self) } - pub fn get_normal_hints(&self, window: ffi::Window) -> Result { + pub fn get_normal_hints(&self, window: ffi::Window) -> Result, XError> { let size_hints = self.alloc_size_hints(); - let mut supplied_by_user: c_long = unsafe { mem::uninitialized() }; + let mut supplied_by_user = MaybeUninit::uninit(); unsafe { (self.xlib.XGetWMNormalHints)( self.display, window, size_hints.ptr, - &mut supplied_by_user, + supplied_by_user.as_mut_ptr(), ); } self.check_errors().map(|_| NormalHints { size_hints }) } - pub fn set_normal_hints(&self, window: ffi::Window, normal_hints: NormalHints) -> Flusher { + pub fn set_normal_hints( + &self, + window: ffi::Window, + normal_hints: NormalHints<'_>, + ) -> Flusher<'_> { unsafe { - (self.xlib.XSetWMNormalHints)( - self.display, - window, - normal_hints.size_hints.ptr, - ); + (self.xlib.XSetWMNormalHints)(self.display, window, normal_hints.size_hints.ptr); } Flusher::new(self) } + + pub fn get_motif_hints(&self, window: ffi::Window) -> MotifHints { + let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; + + let mut hints = MotifHints::new(); + + if let Ok(props) = self.get_property::(window, motif_hints, motif_hints) { + hints.hints.flags = props.get(0).cloned().unwrap_or(0); + hints.hints.functions = props.get(1).cloned().unwrap_or(0); + hints.hints.decorations = props.get(2).cloned().unwrap_or(0); + hints.hints.input_mode = props.get(3).cloned().unwrap_or(0) as c_long; + hints.hints.status = props.get(4).cloned().unwrap_or(0); + } + + hints + } + + pub fn set_motif_hints(&self, window: ffi::Window, hints: &MotifHints) -> Flusher<'_> { + let motif_hints = unsafe { self.get_atom_unchecked(b"_MOTIF_WM_HINTS\0") }; + + self.change_property( + window, + motif_hints, + motif_hints, + PropMode::Replace, + hints.hints.as_slice(), + ) + } } diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/icon.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/icon.rs similarity index 63% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/icon.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/icon.rs index c19b52a..eb13d48 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/icon.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/icon.rs @@ -1,5 +1,5 @@ -use {Icon, Pixel, PIXEL_SIZE}; use super::*; +use crate::icon::{Icon, Pixel, PIXEL_SIZE}; impl Pixel { pub fn to_packed_argb(&self) -> Cardinal { @@ -18,13 +18,14 @@ impl Pixel { impl Icon { pub(crate) fn to_cardinals(&self) -> Vec { - assert_eq!(self.rgba.len() % PIXEL_SIZE, 0); - let pixel_count = self.rgba.len() / PIXEL_SIZE; - assert_eq!(pixel_count, (self.width * self.height) as usize); + let rgba_icon = &self.inner; + assert_eq!(rgba_icon.rgba.len() % PIXEL_SIZE, 0); + let pixel_count = rgba_icon.rgba.len() / PIXEL_SIZE; + assert_eq!(pixel_count, (rgba_icon.width * rgba_icon.height) as usize); let mut data = Vec::with_capacity(pixel_count); - data.push(self.width as Cardinal); - data.push(self.height as Cardinal); - let pixels = self.rgba.as_ptr() as *const Pixel; + data.push(rgba_icon.width as Cardinal); + data.push(rgba_icon.height as Cardinal); + let pixels = rgba_icon.rgba.as_ptr() as *const Pixel; for pixel_index in 0..pixel_count { let pixel = unsafe { &*pixels.offset(pixel_index as isize) }; data.push(pixel.to_packed_argb()); diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/input.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/input.rs new file mode 100644 index 0000000..e9f45ae --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/input.rs @@ -0,0 +1,190 @@ +use std::{slice, str}; + +use super::*; +use crate::event::ModifiersState; + +pub const VIRTUAL_CORE_POINTER: c_int = 2; +pub const VIRTUAL_CORE_KEYBOARD: c_int = 3; + +// A base buffer size of 1kB uses a negligible amount of RAM while preventing us from having to +// re-allocate (and make another round-trip) in the *vast* majority of cases. +// To test if `lookup_utf8` works correctly, set this to 1. +const TEXT_BUFFER_SIZE: usize = 1024; + +impl ModifiersState { + pub(crate) fn from_x11(state: &ffi::XIModifierState) -> Self { + ModifiersState::from_x11_mask(state.effective as c_uint) + } + + pub(crate) fn from_x11_mask(mask: c_uint) -> Self { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::ALT, mask & ffi::Mod1Mask != 0); + m.set(ModifiersState::SHIFT, mask & ffi::ShiftMask != 0); + m.set(ModifiersState::CTRL, mask & ffi::ControlMask != 0); + m.set(ModifiersState::LOGO, mask & ffi::Mod4Mask != 0); + m + } +} + +// NOTE: Some of these fields are not used, but may be of use in the future. +pub struct PointerState<'a> { + xconn: &'a XConnection, + pub root: ffi::Window, + pub child: ffi::Window, + pub root_x: c_double, + pub root_y: c_double, + pub win_x: c_double, + pub win_y: c_double, + buttons: ffi::XIButtonState, + modifiers: ffi::XIModifierState, + pub group: ffi::XIGroupState, + pub relative_to_window: bool, +} + +impl<'a> PointerState<'a> { + pub fn get_modifier_state(&self) -> ModifiersState { + ModifiersState::from_x11(&self.modifiers) + } +} + +impl<'a> Drop for PointerState<'a> { + fn drop(&mut self) { + if !self.buttons.mask.is_null() { + unsafe { + // This is why you need to read the docs carefully... + (self.xconn.xlib.XFree)(self.buttons.mask as _); + } + } + } +} + +impl XConnection { + pub fn select_xinput_events( + &self, + window: c_ulong, + device_id: c_int, + mask: i32, + ) -> Flusher<'_> { + let mut event_mask = ffi::XIEventMask { + deviceid: device_id, + mask: &mask as *const _ as *mut c_uchar, + mask_len: mem::size_of_val(&mask) as c_int, + }; + unsafe { + (self.xinput2.XISelectEvents)( + self.display, + window, + &mut event_mask as *mut ffi::XIEventMask, + 1, // number of masks to read from pointer above + ); + } + Flusher::new(self) + } + + #[allow(dead_code)] + pub fn select_xkb_events(&self, device_id: c_uint, mask: c_ulong) -> Option> { + let status = unsafe { (self.xlib.XkbSelectEvents)(self.display, device_id, mask, mask) }; + if status == ffi::True { + Some(Flusher::new(self)) + } else { + None + } + } + + pub fn query_pointer( + &self, + window: ffi::Window, + device_id: c_int, + ) -> Result, XError> { + unsafe { + let mut root = 0; + let mut child = 0; + let mut root_x = 0.0; + let mut root_y = 0.0; + let mut win_x = 0.0; + let mut win_y = 0.0; + let mut buttons = Default::default(); + let mut modifiers = Default::default(); + let mut group = Default::default(); + + let relative_to_window = (self.xinput2.XIQueryPointer)( + self.display, + device_id, + window, + &mut root, + &mut child, + &mut root_x, + &mut root_y, + &mut win_x, + &mut win_y, + &mut buttons, + &mut modifiers, + &mut group, + ) == ffi::True; + + self.check_errors()?; + + Ok(PointerState { + xconn: self, + root, + child, + root_x, + root_y, + win_x, + win_y, + buttons, + modifiers, + group, + relative_to_window, + }) + } + } + + fn lookup_utf8_inner( + &self, + ic: ffi::XIC, + key_event: &mut ffi::XKeyEvent, + buffer: *mut u8, + size: usize, + ) -> (ffi::KeySym, ffi::Status, c_int) { + let mut keysym: ffi::KeySym = 0; + let mut status: ffi::Status = 0; + let count = unsafe { + (self.xlib.Xutf8LookupString)( + ic, + key_event, + buffer as *mut c_char, + size as c_int, + &mut keysym, + &mut status, + ) + }; + (keysym, status, count) + } + + pub fn lookup_utf8(&self, ic: ffi::XIC, key_event: &mut ffi::XKeyEvent) -> String { + // `assume_init` is safe here because the array consists of `MaybeUninit` values, + // which do not require initialization. + let mut buffer: [MaybeUninit; TEXT_BUFFER_SIZE] = + unsafe { MaybeUninit::uninit().assume_init() }; + // If the buffer overflows, we'll make a new one on the heap. + let mut vec; + + let (_, status, count) = + self.lookup_utf8_inner(ic, key_event, buffer.as_mut_ptr() as *mut u8, buffer.len()); + + let bytes = if status == ffi::XBufferOverflow { + vec = Vec::with_capacity(count as usize); + let (_, _, new_count) = + self.lookup_utf8_inner(ic, key_event, vec.as_mut_ptr(), vec.capacity()); + debug_assert_eq!(count, new_count); + + unsafe { vec.set_len(count as usize) }; + &vec[..count as usize] + } else { + unsafe { slice::from_raw_parts(buffer.as_ptr() as *const u8, count as usize) } + }; + + str::from_utf8(bytes).unwrap_or("").to_string() + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/keys.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/keys.rs new file mode 100644 index 0000000..fc0c9d9 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/keys.rs @@ -0,0 +1,92 @@ +use std::{iter::Enumerate, ptr, slice::Iter}; + +use super::*; + +pub struct Keymap { + keys: [u8; 32], +} + +pub struct KeymapIter<'a> { + iter: Enumerate>, + index: usize, + item: Option, +} + +impl Keymap { + pub fn iter(&self) -> KeymapIter<'_> { + KeymapIter { + iter: self.keys.iter().enumerate(), + index: 0, + item: None, + } + } +} + +impl<'a> IntoIterator for &'a Keymap { + type Item = ffi::KeyCode; + type IntoIter = KeymapIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl Iterator for KeymapIter<'_> { + type Item = ffi::KeyCode; + + fn next(&mut self) -> Option { + if self.item.is_none() { + while let Some((index, &item)) = self.iter.next() { + if item != 0 { + self.index = index; + self.item = Some(item); + break; + } + } + } + + self.item.take().map(|item| { + debug_assert!(item != 0); + + let bit = first_bit(item); + + if item != bit { + // Remove the first bit; save the rest for further iterations + self.item = Some(item ^ bit); + } + + let shift = bit.trailing_zeros() + (self.index * 8) as u32; + shift as ffi::KeyCode + }) + } +} + +impl XConnection { + pub fn keycode_to_keysym(&self, keycode: ffi::KeyCode) -> ffi::KeySym { + unsafe { (self.xlib.XKeycodeToKeysym)(self.display, keycode, 0) } + } + + pub fn lookup_keysym(&self, xkev: &mut ffi::XKeyEvent) -> ffi::KeySym { + let mut keysym = 0; + + unsafe { + (self.xlib.XLookupString)(xkev, ptr::null_mut(), 0, &mut keysym, ptr::null_mut()); + } + + keysym + } + + pub fn query_keymap(&self) -> Keymap { + let mut keys = [0; 32]; + + unsafe { + (self.xlib.XQueryKeymap)(self.display, keys.as_mut_ptr() as *mut c_char); + } + + Keymap { keys } + } +} + +fn first_bit(b: u8) -> u8 { + 1 << b.trailing_zeros() +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/memory.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/memory.rs similarity index 82% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/memory.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/memory.rs index eef0bdc..c85cc37 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/memory.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/memory.rs @@ -12,10 +12,7 @@ impl<'a, T> XSmartPointer<'a, T> { // Returns None if ptr is null. pub fn new(xconn: &'a XConnection, ptr: *mut T) -> Option { if !ptr.is_null() { - Some(XSmartPointer { - xconn, - ptr, - }) + Some(XSmartPointer { xconn, ptr }) } else { None } @@ -45,17 +42,17 @@ impl<'a, T> Drop for XSmartPointer<'a, T> { } impl XConnection { - pub fn alloc_class_hint(&self) -> XSmartPointer { + pub fn alloc_class_hint(&self) -> XSmartPointer<'_, ffi::XClassHint> { XSmartPointer::new(self, unsafe { (self.xlib.XAllocClassHint)() }) .expect("`XAllocClassHint` returned null; out of memory") } - pub fn alloc_size_hints(&self) -> XSmartPointer { + pub fn alloc_size_hints(&self) -> XSmartPointer<'_, ffi::XSizeHints> { XSmartPointer::new(self, unsafe { (self.xlib.XAllocSizeHints)() }) .expect("`XAllocSizeHints` returned null; out of memory") } - pub fn alloc_wm_hints(&self) -> XSmartPointer { + pub fn alloc_wm_hints(&self) -> XSmartPointer<'_, ffi::XWMHints> { XSmartPointer::new(self, unsafe { (self.xlib.XAllocWMHints)() }) .expect("`XAllocWMHints` returned null; out of memory") } diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/mod.rs similarity index 81% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/mod.rs index ccef6e4..4bd1420 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/mod.rs @@ -3,40 +3,32 @@ mod atom; mod client_msg; +mod cursor; mod format; mod geometry; mod hint; mod icon; mod input; +pub mod keys; mod memory; +pub mod modifiers; mod randr; mod window_property; mod wm; -pub use self::atom::*; -pub use self::client_msg::*; -pub use self::format::*; -pub use self::geometry::*; -pub use self::hint::*; -pub use self::icon::*; -pub use self::input::*; -pub use self::memory::*; -pub use self::randr::*; -pub use self::window_property::*; -pub use self::wm::*; +pub use self::{ + atom::*, client_msg::*, format::*, geometry::*, hint::*, icon::*, input::*, memory::*, + randr::*, window_property::*, wm::*, +}; -use std::mem; -use std::ptr; -use std::ops::BitAnd; -use std::os::raw::*; +use std::{ + mem::{self, MaybeUninit}, + os::raw::*, + ptr, +}; use super::{ffi, XConnection, XError}; -pub fn reinterpret<'a, A, B>(a: &'a A) -> &'a B { - let b_ptr = a as *const _ as *const B; - unsafe { &*b_ptr } -} - pub fn maybe_change(field: &mut Option, value: T) -> bool { let wrapped = Some(value); if *field != wrapped { @@ -47,13 +39,6 @@ pub fn maybe_change(field: &mut Option, value: T) -> bool { } } -pub fn has_flag(bitset: T, flag: T) -> bool -where T: - Copy + PartialEq + BitAnd -{ - bitset & flag == flag -} - #[must_use = "This request was made asynchronously, and is still in the output buffer. You must explicitly choose to either `.flush()` (empty the output buffer, sending the request now) or `.queue()` (wait to send the request, allowing you to continue to add more requests without additional round-trips). For more information, see the documentation for `util::flush_requests`."] pub struct Flusher<'a> { xconn: &'a XConnection, diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/modifiers.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/modifiers.rs new file mode 100644 index 0000000..7c95199 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/modifiers.rs @@ -0,0 +1,187 @@ +use std::{collections::HashMap, slice}; + +use super::*; + +use crate::event::{ElementState, ModifiersState}; + +// Offsets within XModifierKeymap to each set of keycodes. +// We are only interested in Shift, Control, Alt, and Logo. +// +// There are 8 sets total. The order of keycode sets is: +// Shift, Lock, Control, Mod1 (Alt), Mod2, Mod3, Mod4 (Logo), Mod5 +// +// https://tronche.com/gui/x/xlib/input/XSetModifierMapping.html +const SHIFT_OFFSET: usize = 0; +const CONTROL_OFFSET: usize = 2; +const ALT_OFFSET: usize = 3; +const LOGO_OFFSET: usize = 6; +const NUM_MODS: usize = 8; + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Modifier { + Alt, + Ctrl, + Shift, + Logo, +} + +#[derive(Debug, Default)] +pub struct ModifierKeymap { + // Maps keycodes to modifiers + keys: HashMap, +} + +#[derive(Clone, Debug, Default)] +pub struct ModifierKeyState { + // Contains currently pressed modifier keys and their corresponding modifiers + keys: HashMap, + state: ModifiersState, +} + +impl ModifierKeymap { + pub fn new() -> ModifierKeymap { + ModifierKeymap::default() + } + + pub fn get_modifier(&self, keycode: ffi::KeyCode) -> Option { + self.keys.get(&keycode).cloned() + } + + pub fn reset_from_x_connection(&mut self, xconn: &XConnection) { + unsafe { + let keymap = (xconn.xlib.XGetModifierMapping)(xconn.display); + + if keymap.is_null() { + panic!("failed to allocate XModifierKeymap"); + } + + self.reset_from_x_keymap(&*keymap); + + (xconn.xlib.XFreeModifiermap)(keymap); + } + } + + pub fn reset_from_x_keymap(&mut self, keymap: &ffi::XModifierKeymap) { + let keys_per_mod = keymap.max_keypermod as usize; + + let keys = unsafe { + slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS) + }; + + self.keys.clear(); + + self.read_x_keys(keys, SHIFT_OFFSET, keys_per_mod, Modifier::Shift); + self.read_x_keys(keys, CONTROL_OFFSET, keys_per_mod, Modifier::Ctrl); + self.read_x_keys(keys, ALT_OFFSET, keys_per_mod, Modifier::Alt); + self.read_x_keys(keys, LOGO_OFFSET, keys_per_mod, Modifier::Logo); + } + + fn read_x_keys( + &mut self, + keys: &[ffi::KeyCode], + offset: usize, + keys_per_mod: usize, + modifier: Modifier, + ) { + let start = offset * keys_per_mod; + let end = start + keys_per_mod; + + for &keycode in &keys[start..end] { + if keycode != 0 { + self.keys.insert(keycode, modifier); + } + } + } +} + +impl ModifierKeyState { + pub fn update_keymap(&mut self, mods: &ModifierKeymap) { + self.keys.retain(|k, v| { + if let Some(m) = mods.get_modifier(*k) { + *v = m; + true + } else { + false + } + }); + + self.reset_state(); + } + + pub fn update_state( + &mut self, + state: &ModifiersState, + except: Option, + ) -> Option { + let mut new_state = *state; + + match except { + Some(Modifier::Alt) => new_state.set(ModifiersState::ALT, self.state.alt()), + Some(Modifier::Ctrl) => new_state.set(ModifiersState::CTRL, self.state.ctrl()), + Some(Modifier::Shift) => new_state.set(ModifiersState::SHIFT, self.state.shift()), + Some(Modifier::Logo) => new_state.set(ModifiersState::LOGO, self.state.logo()), + None => (), + } + + if self.state == new_state { + None + } else { + self.keys.retain(|_k, v| get_modifier(&new_state, *v)); + self.state = new_state; + Some(new_state) + } + } + + pub fn modifiers(&self) -> ModifiersState { + self.state + } + + pub fn key_event(&mut self, state: ElementState, keycode: ffi::KeyCode, modifier: Modifier) { + match state { + ElementState::Pressed => self.key_press(keycode, modifier), + ElementState::Released => self.key_release(keycode), + } + } + + pub fn key_press(&mut self, keycode: ffi::KeyCode, modifier: Modifier) { + self.keys.insert(keycode, modifier); + + set_modifier(&mut self.state, modifier, true); + } + + pub fn key_release(&mut self, keycode: ffi::KeyCode) { + if let Some(modifier) = self.keys.remove(&keycode) { + if self.keys.values().find(|&&m| m == modifier).is_none() { + set_modifier(&mut self.state, modifier, false); + } + } + } + + fn reset_state(&mut self) { + let mut new_state = ModifiersState::default(); + + for &m in self.keys.values() { + set_modifier(&mut new_state, m, true); + } + + self.state = new_state; + } +} + +fn get_modifier(state: &ModifiersState, modifier: Modifier) -> bool { + match modifier { + Modifier::Alt => state.alt(), + Modifier::Ctrl => state.ctrl(), + Modifier::Shift => state.shift(), + Modifier::Logo => state.logo(), + } +} + +fn set_modifier(state: &mut ModifiersState, modifier: Modifier, value: bool) { + match modifier { + Modifier::Alt => state.set(ModifiersState::ALT, value), + Modifier::Ctrl => state.set(ModifiersState::CTRL, value), + Modifier::Shift => state.set(ModifiersState::SHIFT, value), + Modifier::Logo => state.set(ModifiersState::LOGO, value), + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/randr.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/randr.rs new file mode 100644 index 0000000..b9258c6 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/randr.rs @@ -0,0 +1,220 @@ +use std::{env, slice, str::FromStr}; + +use super::{ + ffi::{CurrentTime, RRCrtc, RRMode, Success, XRRCrtcInfo, XRRScreenResources}, + *, +}; +use crate::{dpi::validate_scale_factor, platform_impl::platform::x11::VideoMode}; + +/// Represents values of `WINIT_HIDPI_FACTOR`. +pub enum EnvVarDPI { + Randr, + Scale(f64), + NotSet, +} + +pub fn calc_dpi_factor( + (width_px, height_px): (u32, u32), + (width_mm, height_mm): (u64, u64), +) -> f64 { + // See http://xpra.org/trac/ticket/728 for more information. + if width_mm == 0 || height_mm == 0 { + warn!("XRandR reported that the display's 0mm in size, which is certifiably insane"); + return 1.0; + } + + let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); + // Quantize 1/12 step size + let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0); + assert!(validate_scale_factor(dpi_factor)); + dpi_factor +} + +impl XConnection { + // Retrieve DPI from Xft.dpi property + pub unsafe fn get_xft_dpi(&self) -> Option { + (self.xlib.XrmInitialize)(); + let resource_manager_str = (self.xlib.XResourceManagerString)(self.display); + if resource_manager_str == ptr::null_mut() { + return None; + } + if let Ok(res) = ::std::ffi::CStr::from_ptr(resource_manager_str).to_str() { + let name: &str = "Xft.dpi:\t"; + for pair in res.split("\n") { + if pair.starts_with(&name) { + let res = &pair[name.len()..]; + return f64::from_str(&res).ok(); + } + } + } + None + } + pub unsafe fn get_output_info( + &self, + resources: *mut XRRScreenResources, + crtc: *mut XRRCrtcInfo, + ) -> Option<(String, f64, Vec)> { + let output_info = + (self.xrandr.XRRGetOutputInfo)(self.display, resources, *(*crtc).outputs.offset(0)); + if output_info.is_null() { + // When calling `XRRGetOutputInfo` on a virtual monitor (versus a physical display) + // it's possible for it to return null. + // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=816596 + let _ = self.check_errors(); // discard `BadRROutput` error + return None; + } + + let screen = (self.xlib.XDefaultScreen)(self.display); + let bit_depth = (self.xlib.XDefaultDepth)(self.display, screen); + + let output_modes = + slice::from_raw_parts((*output_info).modes, (*output_info).nmode as usize); + let resource_modes = slice::from_raw_parts((*resources).modes, (*resources).nmode as usize); + + let modes = resource_modes + .iter() + // XRROutputInfo contains an array of mode ids that correspond to + // modes in the array in XRRScreenResources + .filter(|x| output_modes.iter().any(|id| x.id == *id)) + .map(|x| { + let refresh_rate = if x.dotClock > 0 && x.hTotal > 0 && x.vTotal > 0 { + x.dotClock as u64 * 1000 / (x.hTotal as u64 * x.vTotal as u64) + } else { + 0 + }; + + VideoMode { + size: (x.width, x.height), + refresh_rate: (refresh_rate as f32 / 1000.0).round() as u16, + bit_depth: bit_depth as u16, + native_mode: x.id, + // This is populated in `MonitorHandle::video_modes` as the + // video mode is returned to the user + monitor: None, + } + }) + .collect(); + + let name_slice = slice::from_raw_parts( + (*output_info).name as *mut u8, + (*output_info).nameLen as usize, + ); + let name = String::from_utf8_lossy(name_slice).into(); + // Override DPI if `WINIT_X11_SCALE_FACTOR` variable is set + let deprecated_dpi_override = env::var("WINIT_HIDPI_FACTOR").ok(); + if deprecated_dpi_override.is_some() { + warn!( + "The WINIT_HIDPI_FACTOR environment variable is deprecated; use WINIT_X11_SCALE_FACTOR" + ) + } + let dpi_env = env::var("WINIT_X11_SCALE_FACTOR").ok().map_or_else( + || EnvVarDPI::NotSet, + |var| { + if var.to_lowercase() == "randr" { + EnvVarDPI::Randr + } else if let Ok(dpi) = f64::from_str(&var) { + EnvVarDPI::Scale(dpi) + } else if var.is_empty() { + EnvVarDPI::NotSet + } else { + panic!( + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`", + var + ); + } + }, + ); + + let scale_factor = match dpi_env { + EnvVarDPI::Randr => calc_dpi_factor( + ((*crtc).width as u32, (*crtc).height as u32), + ( + (*output_info).mm_width as u64, + (*output_info).mm_height as u64, + ), + ), + EnvVarDPI::Scale(dpi_override) => { + if !validate_scale_factor(dpi_override) { + panic!( + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal floats greater than 0, or `randr`. Got `{}`", + dpi_override, + ); + } + dpi_override + } + EnvVarDPI::NotSet => { + if let Some(dpi) = self.get_xft_dpi() { + dpi / 96. + } else { + calc_dpi_factor( + ((*crtc).width as u32, (*crtc).height as u32), + ( + (*output_info).mm_width as u64, + (*output_info).mm_height as u64, + ), + ) + } + } + }; + + (self.xrandr.XRRFreeOutputInfo)(output_info); + Some((name, scale_factor, modes)) + } + pub fn set_crtc_config(&self, crtc_id: RRCrtc, mode_id: RRMode) -> Result<(), ()> { + unsafe { + let mut major = 0; + let mut minor = 0; + (self.xrandr.XRRQueryVersion)(self.display, &mut major, &mut minor); + + let root = (self.xlib.XDefaultRootWindow)(self.display); + let resources = if (major == 1 && minor >= 3) || major > 1 { + (self.xrandr.XRRGetScreenResourcesCurrent)(self.display, root) + } else { + (self.xrandr.XRRGetScreenResources)(self.display, root) + }; + + let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id); + let status = (self.xrandr.XRRSetCrtcConfig)( + self.display, + resources, + crtc_id, + CurrentTime, + (*crtc).x, + (*crtc).y, + mode_id, + (*crtc).rotation, + (*crtc).outputs.offset(0), + 1, + ); + + (self.xrandr.XRRFreeCrtcInfo)(crtc); + (self.xrandr.XRRFreeScreenResources)(resources); + + if status == Success as i32 { + Ok(()) + } else { + Err(()) + } + } + } + pub fn get_crtc_mode(&self, crtc_id: RRCrtc) -> RRMode { + unsafe { + let mut major = 0; + let mut minor = 0; + (self.xrandr.XRRQueryVersion)(self.display, &mut major, &mut minor); + + let root = (self.xlib.XDefaultRootWindow)(self.display); + let resources = if (major == 1 && minor >= 3) || major > 1 { + (self.xrandr.XRRGetScreenResourcesCurrent)(self.display, root) + } else { + (self.xrandr.XRRGetScreenResources)(self.display, root) + }; + + let crtc = (self.xrandr.XRRGetCrtcInfo)(self.display, resources, crtc_id); + let mode = (*crtc).mode; + (self.xrandr.XRRFreeCrtcInfo)(crtc); + (self.xrandr.XRRFreeScreenResources)(resources); + mode + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/window_property.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/window_property.rs similarity index 89% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/window_property.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/window_property.rs index 47d984e..34977f3 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/window_property.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/window_property.rs @@ -1,5 +1,3 @@ -use std; - use super::*; pub type Cardinal = c_long; @@ -28,6 +26,7 @@ impl GetPropertyError { const PROPERTY_BUFFER_SIZE: c_long = 1024; // 4k of RAM ought to be enough for anyone! #[derive(Debug)] +#[allow(dead_code)] pub enum PropMode { Replace = ffi::PropModeReplace as isize, Prepend = ffi::PropModePrepend as isize, @@ -45,13 +44,14 @@ impl XConnection { let mut offset = 0; let mut done = false; + let mut actual_type = 0; + let mut actual_format = 0; + let mut quantity_returned = 0; + let mut bytes_after = 0; + let mut buf: *mut c_uchar = ptr::null_mut(); + while !done { unsafe { - let mut actual_type: ffi::Atom = mem::uninitialized(); - let mut actual_format: c_int = mem::uninitialized(); - let mut quantity_returned: c_ulong = mem::uninitialized(); - let mut bytes_after: c_ulong = mem::uninitialized(); - let mut buf: *mut c_uchar = ptr::null_mut(); (self.xlib.XGetWindowProperty)( self.display, window, @@ -86,10 +86,8 @@ impl XConnection { if !buf.is_null() { offset += PROPERTY_BUFFER_SIZE; - let new_data = std::slice::from_raw_parts( - buf as *mut T, - quantity_returned as usize, - ); + let new_data = + std::slice::from_raw_parts(buf as *mut T, quantity_returned as usize); /*println!( "XGetWindowProperty prop:{:?} fmt:{:02} len:{:02} off:{:02} out:{:02}, buf:{:?}", property, diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/wm.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/wm.rs similarity index 79% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/wm.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/wm.rs index 738ab76..693bc5c 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/util/wm.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/util/wm.rs @@ -28,11 +28,8 @@ impl XConnection { fn get_supported_hints(&self, root: ffi::Window) -> Vec { let supported_atom = unsafe { self.get_atom_unchecked(b"_NET_SUPPORTED\0") }; - self.get_property( - root, - supported_atom, - ffi::XA_ATOM, - ).unwrap_or_else(|_| Vec::with_capacity(0)) + self.get_property(root, supported_atom, ffi::XA_ATOM) + .unwrap_or_else(|_| Vec::with_capacity(0)) } fn get_wm_name(&self, root: ffi::Window) -> Option { @@ -61,15 +58,9 @@ impl XConnection { // Querying this property on the root window will give us the ID of a child window created by // the WM. let root_window_wm_check = { - let result = self.get_property( - root, - check_atom, - ffi::XA_WINDOW, - ); + let result = self.get_property(root, check_atom, ffi::XA_WINDOW); - let wm_check = result - .ok() - .and_then(|wm_check| wm_check.get(0).cloned()); + let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned()); if let Some(wm_check) = wm_check { wm_check @@ -81,15 +72,9 @@ impl XConnection { // Querying the same property on the child window we were given, we should get this child // window's ID again. let child_window_wm_check = { - let result = self.get_property( - root_window_wm_check, - check_atom, - ffi::XA_WINDOW, - ); + let result = self.get_property(root_window_wm_check, check_atom, ffi::XA_WINDOW); - let wm_check = result - .ok() - .and_then(|wm_check| wm_check.get(0).cloned()); + let wm_check = result.ok().and_then(|wm_check| wm_check.get(0).cloned()); if let Some(wm_check) = wm_check { wm_check @@ -107,11 +92,7 @@ impl XConnection { let wm_name = { let utf8_string_atom = unsafe { self.get_atom_unchecked(b"UTF8_STRING\0") }; - let result = self.get_property( - root_window_wm_check, - wm_name_atom, - utf8_string_atom, - ); + let result = self.get_property(root_window_wm_check, wm_name_atom, utf8_string_atom); // IceWM requires this. IceWM was also the only WM tested that returns a null-terminated // string. For more fun trivia, IceWM is also unique in including version and uname @@ -126,15 +107,12 @@ impl XConnection { }; if no_utf8 { - self.get_property( - root_window_wm_check, - wm_name_atom, - ffi::XA_STRING, - ) + self.get_property(root_window_wm_check, wm_name_atom, ffi::XA_STRING) } else { result } - }.ok(); + } + .ok(); wm_name.and_then(|wm_name| String::from_utf8(wm_name).ok()) } diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/window.rs new file mode 100644 index 0000000..f178ba3 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/window.rs @@ -0,0 +1,1328 @@ +use raw_window_handle::unix::XlibHandle; +use std::{ + cmp, + collections::HashSet, + env, + ffi::CString, + mem::{self, replace, MaybeUninit}, + os::raw::*, + path::Path, + ptr, slice, + sync::Arc, +}; + +use libc; +use parking_lot::Mutex; + +use crate::{ + dpi::{PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform_impl::{ + x11::{ime::ImeContextCreationError, MonitorHandle as X11MonitorHandle}, + MonitorHandle as PlatformMonitorHandle, OsError, PlatformSpecificWindowBuilderAttributes, + VideoMode as PlatformVideoMode, + }, + window::{CursorIcon, Fullscreen, Icon, WindowAttributes}, +}; + +use super::{ffi, util, EventLoopWindowTarget, ImeSender, WindowId, XConnection, XError}; + +#[derive(Debug)] +pub struct SharedState { + pub cursor_pos: Option<(f64, f64)>, + pub size: Option<(u32, u32)>, + pub position: Option<(i32, i32)>, + pub inner_position: Option<(i32, i32)>, + pub inner_position_rel_parent: Option<(i32, i32)>, + pub last_monitor: X11MonitorHandle, + pub dpi_adjusted: Option<(u32, u32)>, + pub fullscreen: Option, + // Set when application calls `set_fullscreen` when window is not visible + pub desired_fullscreen: Option>, + // Used to restore position after exiting fullscreen + pub restore_position: Option<(i32, i32)>, + // Used to restore video mode after exiting fullscreen + pub desktop_video_mode: Option<(ffi::RRCrtc, ffi::RRMode)>, + pub frame_extents: Option, + pub min_inner_size: Option, + pub max_inner_size: Option, + pub resize_increments: Option, + pub base_size: Option, + pub visibility: Visibility, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Visibility { + No, + Yes, + // Waiting for VisibilityNotify + YesWait, +} + +impl SharedState { + fn new(last_monitor: X11MonitorHandle, is_visible: bool) -> Mutex { + let visibility = if is_visible { + Visibility::YesWait + } else { + Visibility::No + }; + + Mutex::new(SharedState { + last_monitor, + visibility, + + cursor_pos: None, + size: None, + position: None, + inner_position: None, + inner_position_rel_parent: None, + dpi_adjusted: None, + fullscreen: None, + desired_fullscreen: None, + restore_position: None, + desktop_video_mode: None, + frame_extents: None, + min_inner_size: None, + max_inner_size: None, + resize_increments: None, + base_size: None, + }) + } +} + +unsafe impl Send for UnownedWindow {} +unsafe impl Sync for UnownedWindow {} + +pub struct UnownedWindow { + pub xconn: Arc, // never changes + xwindow: ffi::Window, // never changes + root: ffi::Window, // never changes + screen_id: i32, // never changes + cursor: Mutex, + cursor_grabbed: Mutex, + cursor_visible: Mutex, + ime_sender: Mutex, + pub shared_state: Mutex, + pending_redraws: Arc<::std::sync::Mutex>>, +} + +impl UnownedWindow { + pub fn new( + event_loop: &EventLoopWindowTarget, + window_attrs: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + let xconn = &event_loop.xconn; + let root = event_loop.root; + + let mut monitors = xconn.available_monitors(); + let guessed_monitor = if monitors.is_empty() { + X11MonitorHandle::dummy() + } else { + xconn + .query_pointer(root, util::VIRTUAL_CORE_POINTER) + .ok() + .and_then(|pointer_state| { + let (x, y) = (pointer_state.root_x as i64, pointer_state.root_y as i64); + + for i in 0..monitors.len() { + if monitors[i].rect.contains_point(x, y) { + return Some(monitors.swap_remove(i)); + } + } + + None + }) + .unwrap_or_else(|| monitors.swap_remove(0)) + }; + let scale_factor = guessed_monitor.scale_factor(); + + info!("Guessed window scale factor: {}", scale_factor); + + let max_inner_size: Option<(u32, u32)> = window_attrs + .max_inner_size + .map(|size| size.to_physical::(scale_factor).into()); + let min_inner_size: Option<(u32, u32)> = window_attrs + .min_inner_size + .map(|size| size.to_physical::(scale_factor).into()); + + let dimensions = { + // x11 only applies constraints when the window is actively resized + // by the user, so we have to manually apply the initial constraints + let mut dimensions: (u32, u32) = window_attrs + .inner_size + .map(|size| size.to_physical::(scale_factor)) + .or_else(|| Some((800, 600).into())) + .map(Into::into) + .unwrap(); + if let Some(max) = max_inner_size { + dimensions.0 = cmp::min(dimensions.0, max.0); + dimensions.1 = cmp::min(dimensions.1, max.1); + } + if let Some(min) = min_inner_size { + dimensions.0 = cmp::max(dimensions.0, min.0); + dimensions.1 = cmp::max(dimensions.1, min.1); + } + debug!( + "Calculated physical dimensions: {}x{}", + dimensions.0, dimensions.1 + ); + dimensions + }; + + let screen_id = match pl_attribs.screen_id { + Some(id) => id, + None => unsafe { (xconn.xlib.XDefaultScreen)(xconn.display) }, + }; + + // creating + let mut set_win_attr = { + let mut swa: ffi::XSetWindowAttributes = unsafe { mem::zeroed() }; + swa.colormap = if let Some(vi) = pl_attribs.visual_infos { + unsafe { + let visual = vi.visual; + (xconn.xlib.XCreateColormap)(xconn.display, root, visual, ffi::AllocNone) + } + } else { + 0 + }; + swa.event_mask = ffi::ExposureMask + | ffi::StructureNotifyMask + | ffi::VisibilityChangeMask + | ffi::KeyPressMask + | ffi::KeyReleaseMask + | ffi::KeymapStateMask + | ffi::ButtonPressMask + | ffi::ButtonReleaseMask + | ffi::PointerMotionMask; + swa.border_pixel = 0; + swa.override_redirect = pl_attribs.override_redirect as c_int; + swa + }; + + let mut window_attributes = ffi::CWBorderPixel | ffi::CWColormap | ffi::CWEventMask; + + if pl_attribs.override_redirect { + window_attributes |= ffi::CWOverrideRedirect; + } + + // finally creating the window + let xwindow = unsafe { + (xconn.xlib.XCreateWindow)( + xconn.display, + root, + 0, + 0, + dimensions.0 as c_uint, + dimensions.1 as c_uint, + 0, + match pl_attribs.visual_infos { + Some(vi) => vi.depth, + None => ffi::CopyFromParent, + }, + ffi::InputOutput as c_uint, + // TODO: If window wants transparency and `visual_infos` is None, + // we need to find our own visual which has an `alphaMask` which + // is > 0, like we do in glutin. + // + // It is non obvious which masks, if any, we should pass to + // `XGetVisualInfo`. winit doesn't recieve any info about what + // properties the user wants. Users should consider choosing the + // visual themselves as glutin does. + match pl_attribs.visual_infos { + Some(vi) => vi.visual, + None => ffi::CopyFromParent as *mut ffi::Visual, + }, + window_attributes, + &mut set_win_attr, + ) + }; + + let mut window = UnownedWindow { + xconn: Arc::clone(xconn), + xwindow, + root, + screen_id, + cursor: Default::default(), + cursor_grabbed: Mutex::new(false), + cursor_visible: Mutex::new(true), + ime_sender: Mutex::new(event_loop.ime_sender.clone()), + shared_state: SharedState::new(guessed_monitor, window_attrs.visible), + pending_redraws: event_loop.pending_redraws.clone(), + }; + + // Title must be set before mapping. Some tiling window managers (i.e. i3) use the window + // title to determine placement/etc., so doing this after mapping would cause the WM to + // act on the wrong title state. + window.set_title_inner(&window_attrs.title).queue(); + window + .set_decorations_inner(window_attrs.decorations) + .queue(); + + { + // Enable drag and drop (TODO: extend API to make this toggleable) + unsafe { + let dnd_aware_atom = xconn.get_atom_unchecked(b"XdndAware\0"); + let version = &[5 as c_ulong]; // Latest version; hasn't changed since 2002 + xconn.change_property( + window.xwindow, + dnd_aware_atom, + ffi::XA_ATOM, + util::PropMode::Replace, + version, + ) + } + .queue(); + + // WM_CLASS must be set *before* mapping the window, as per ICCCM! + { + let (class, instance) = if let Some((instance, class)) = pl_attribs.class { + let instance = CString::new(instance.as_str()) + .expect("`WM_CLASS` instance contained null byte"); + let class = + CString::new(class.as_str()).expect("`WM_CLASS` class contained null byte"); + (instance, class) + } else { + let class = env::args() + .next() + .as_ref() + // Default to the name of the binary (via argv[0]) + .and_then(|path| Path::new(path).file_name()) + .and_then(|bin_name| bin_name.to_str()) + .map(|bin_name| bin_name.to_owned()) + .or_else(|| Some(window_attrs.title.clone())) + .and_then(|string| CString::new(string.as_str()).ok()) + .expect("Default `WM_CLASS` class contained null byte"); + // This environment variable is extraordinarily unlikely to actually be used... + let instance = env::var("RESOURCE_NAME") + .ok() + .and_then(|instance| CString::new(instance.as_str()).ok()) + .or_else(|| Some(class.clone())) + .expect("Default `WM_CLASS` instance contained null byte"); + (instance, class) + }; + + let mut class_hint = xconn.alloc_class_hint(); + (*class_hint).res_name = class.as_ptr() as *mut c_char; + (*class_hint).res_class = instance.as_ptr() as *mut c_char; + + unsafe { + (xconn.xlib.XSetClassHint)(xconn.display, window.xwindow, class_hint.ptr); + } //.queue(); + } + + window.set_pid().map(|flusher| flusher.queue()); + + window.set_window_types(pl_attribs.x11_window_types).queue(); + + if let Some(variant) = pl_attribs.gtk_theme_variant { + window.set_gtk_theme_variant(variant).queue(); + } + + // set size hints + { + let mut min_inner_size = window_attrs + .min_inner_size + .map(|size| size.to_physical::(scale_factor)); + let mut max_inner_size = window_attrs + .max_inner_size + .map(|size| size.to_physical::(scale_factor)); + + if !window_attrs.resizable { + if util::wm_name_is_one_of(&["Xfwm4"]) { + warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); + } else { + max_inner_size = Some(dimensions.into()); + min_inner_size = Some(dimensions.into()); + + let mut shared_state = window.shared_state.get_mut(); + shared_state.min_inner_size = window_attrs.min_inner_size; + shared_state.max_inner_size = window_attrs.max_inner_size; + shared_state.resize_increments = pl_attribs.resize_increments; + shared_state.base_size = pl_attribs.base_size; + } + } + + let mut normal_hints = util::NormalHints::new(xconn); + normal_hints.set_size(Some(dimensions)); + normal_hints.set_min_size(min_inner_size.map(Into::into)); + normal_hints.set_max_size(max_inner_size.map(Into::into)); + normal_hints.set_resize_increments( + pl_attribs + .resize_increments + .map(|size| size.to_physical::(scale_factor).into()), + ); + normal_hints.set_base_size( + pl_attribs + .base_size + .map(|size| size.to_physical::(scale_factor).into()), + ); + xconn.set_normal_hints(window.xwindow, normal_hints).queue(); + } + + // Set window icons + if let Some(icon) = window_attrs.window_icon { + window.set_icon_inner(icon).queue(); + } + + // Opt into handling window close + unsafe { + (xconn.xlib.XSetWMProtocols)( + xconn.display, + window.xwindow, + &[event_loop.wm_delete_window, event_loop.net_wm_ping] as *const ffi::Atom + as *mut ffi::Atom, + 2, + ); + } //.queue(); + + // Set visibility (map window) + if window_attrs.visible { + unsafe { + (xconn.xlib.XMapRaised)(xconn.display, window.xwindow); + } //.queue(); + } + + // Attempt to make keyboard input repeat detectable + unsafe { + let mut supported_ptr = ffi::False; + (xconn.xlib.XkbSetDetectableAutoRepeat)( + xconn.display, + ffi::True, + &mut supported_ptr, + ); + if supported_ptr == ffi::False { + return Err(os_error!(OsError::XMisc( + "`XkbSetDetectableAutoRepeat` failed" + ))); + } + } + + // Select XInput2 events + let mask = { + let mask = ffi::XI_MotionMask + | ffi::XI_ButtonPressMask + | ffi::XI_ButtonReleaseMask + //| ffi::XI_KeyPressMask + //| ffi::XI_KeyReleaseMask + | ffi::XI_EnterMask + | ffi::XI_LeaveMask + | ffi::XI_FocusInMask + | ffi::XI_FocusOutMask + | ffi::XI_TouchBeginMask + | ffi::XI_TouchUpdateMask + | ffi::XI_TouchEndMask; + mask + }; + xconn + .select_xinput_events(window.xwindow, ffi::XIAllMasterDevices, mask) + .queue(); + + { + let result = event_loop.ime.borrow_mut().create_context(window.xwindow); + if let Err(err) = result { + let e = match err { + ImeContextCreationError::XError(err) => OsError::XError(err), + ImeContextCreationError::Null => { + OsError::XMisc("IME Context creation failed") + } + }; + return Err(os_error!(e)); + } + } + + // These properties must be set after mapping + if window_attrs.maximized { + window.set_maximized_inner(window_attrs.maximized).queue(); + } + if window_attrs.fullscreen.is_some() { + window + .set_fullscreen_inner(window_attrs.fullscreen.clone()) + .map(|flusher| flusher.queue()); + } + if window_attrs.always_on_top { + window + .set_always_on_top_inner(window_attrs.always_on_top) + .queue(); + } + } + + // We never want to give the user a broken window, since by then, it's too late to handle. + xconn + .sync_with_server() + .map(|_| window) + .map_err(|x_err| os_error!(OsError::XError(x_err))) + } + + fn set_pid(&self) -> Option> { + let pid_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_PID\0") }; + let client_machine_atom = unsafe { self.xconn.get_atom_unchecked(b"WM_CLIENT_MACHINE\0") }; + unsafe { + // 64 would suffice for Linux, but 256 will be enough everywhere (as per SUSv2). For instance, this is + // the limit defined by OpenBSD. + const MAXHOSTNAMELEN: usize = 256; + // `assume_init` is safe here because the array consists of `MaybeUninit` values, + // which do not require initialization. + let mut buffer: [MaybeUninit; MAXHOSTNAMELEN] = + MaybeUninit::uninit().assume_init(); + let status = libc::gethostname(buffer.as_mut_ptr() as *mut c_char, buffer.len()); + if status != 0 { + return None; + } + ptr::write(buffer[MAXHOSTNAMELEN - 1].as_mut_ptr() as *mut u8, b'\0'); // a little extra safety + let hostname_length = libc::strlen(buffer.as_ptr() as *const c_char); + + let hostname = slice::from_raw_parts(buffer.as_ptr() as *const c_char, hostname_length); + + self.xconn + .change_property( + self.xwindow, + pid_atom, + ffi::XA_CARDINAL, + util::PropMode::Replace, + &[libc::getpid() as util::Cardinal], + ) + .queue(); + let flusher = self.xconn.change_property( + self.xwindow, + client_machine_atom, + ffi::XA_STRING, + util::PropMode::Replace, + &hostname[0..hostname_length], + ); + Some(flusher) + } + } + + fn set_window_types(&self, window_types: Vec) -> util::Flusher<'_> { + let hint_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_WINDOW_TYPE\0") }; + let atoms: Vec<_> = window_types + .iter() + .map(|t| t.as_atom(&self.xconn)) + .collect(); + + self.xconn.change_property( + self.xwindow, + hint_atom, + ffi::XA_ATOM, + util::PropMode::Replace, + &atoms, + ) + } + + fn set_gtk_theme_variant(&self, variant: String) -> util::Flusher<'_> { + let hint_atom = unsafe { self.xconn.get_atom_unchecked(b"_GTK_THEME_VARIANT\0") }; + let utf8_atom = unsafe { self.xconn.get_atom_unchecked(b"UTF8_STRING\0") }; + let variant = CString::new(variant).expect("`_GTK_THEME_VARIANT` contained null byte"); + self.xconn.change_property( + self.xwindow, + hint_atom, + utf8_atom, + util::PropMode::Replace, + variant.as_bytes(), + ) + } + + #[inline] + pub fn set_urgent(&self, is_urgent: bool) { + let mut wm_hints = self + .xconn + .get_wm_hints(self.xwindow) + .expect("`XGetWMHints` failed"); + if is_urgent { + (*wm_hints).flags |= ffi::XUrgencyHint; + } else { + (*wm_hints).flags &= !ffi::XUrgencyHint; + } + self.xconn + .set_wm_hints(self.xwindow, wm_hints) + .flush() + .expect("Failed to set urgency hint"); + } + + fn set_netwm( + &self, + operation: util::StateOperation, + properties: (c_long, c_long, c_long, c_long), + ) -> util::Flusher<'_> { + let state_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE\0") }; + self.xconn.send_client_msg( + self.xwindow, + self.root, + state_atom, + Some(ffi::SubstructureRedirectMask | ffi::SubstructureNotifyMask), + [ + operation as c_long, + properties.0, + properties.1, + properties.2, + properties.3, + ], + ) + } + + fn set_fullscreen_hint(&self, fullscreen: bool) -> util::Flusher<'_> { + let fullscreen_atom = + unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_FULLSCREEN\0") }; + let flusher = self.set_netwm(fullscreen.into(), (fullscreen_atom as c_long, 0, 0, 0)); + + if fullscreen { + // Ensure that the fullscreen window receives input focus to prevent + // locking up the user's display. + unsafe { + (self.xconn.xlib.XSetInputFocus)( + self.xconn.display, + self.xwindow, + ffi::RevertToParent, + ffi::CurrentTime, + ); + } + } + + flusher + } + + fn set_fullscreen_inner(&self, fullscreen: Option) -> Option> { + let mut shared_state_lock = self.shared_state.lock(); + + match shared_state_lock.visibility { + // Setting fullscreen on a window that is not visible will generate an error. + Visibility::No | Visibility::YesWait => { + shared_state_lock.desired_fullscreen = Some(fullscreen); + return None; + } + Visibility::Yes => (), + } + + let old_fullscreen = shared_state_lock.fullscreen.clone(); + if old_fullscreen == fullscreen { + return None; + } + shared_state_lock.fullscreen = fullscreen.clone(); + + match (&old_fullscreen, &fullscreen) { + // Store the desktop video mode before entering exclusive + // fullscreen, so we can restore it upon exit, as XRandR does not + // provide a mechanism to set this per app-session or restore this + // to the desktop video mode as macOS and Windows do + ( + &None, + &Some(Fullscreen::Exclusive(RootVideoMode { + video_mode: PlatformVideoMode::X(ref video_mode), + })), + ) + | ( + &Some(Fullscreen::Borderless(_)), + &Some(Fullscreen::Exclusive(RootVideoMode { + video_mode: PlatformVideoMode::X(ref video_mode), + })), + ) => { + let monitor = video_mode.monitor.as_ref().unwrap(); + shared_state_lock.desktop_video_mode = + Some((monitor.id, self.xconn.get_crtc_mode(monitor.id))); + } + // Restore desktop video mode upon exiting exclusive fullscreen + (&Some(Fullscreen::Exclusive(_)), &None) + | (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Borderless(_))) => { + let (monitor_id, mode_id) = shared_state_lock.desktop_video_mode.take().unwrap(); + self.xconn + .set_crtc_config(monitor_id, mode_id) + .expect("failed to restore desktop video mode"); + } + _ => (), + } + + drop(shared_state_lock); + + match fullscreen { + None => { + let flusher = self.set_fullscreen_hint(false); + let mut shared_state_lock = self.shared_state.lock(); + if let Some(position) = shared_state_lock.restore_position.take() { + self.set_position_inner(position.0, position.1).queue(); + } + Some(flusher) + } + Some(fullscreen) => { + let (video_mode, monitor) = match fullscreen { + Fullscreen::Exclusive(RootVideoMode { + video_mode: PlatformVideoMode::X(ref video_mode), + }) => (Some(video_mode), video_mode.monitor.as_ref().unwrap()), + Fullscreen::Borderless(RootMonitorHandle { + inner: PlatformMonitorHandle::X(ref monitor), + }) => (None, monitor), + _ => unreachable!(), + }; + + // Don't set fullscreen on an invalid dummy monitor handle + if monitor.is_dummy() { + return None; + } + + if let Some(video_mode) = video_mode { + // FIXME: this is actually not correct if we're setting the + // video mode to a resolution higher than the current + // desktop resolution, because XRandR does not automatically + // reposition the monitors to the right and below this + // monitor. + // + // What ends up happening is we will get the fullscreen + // window showing up on those monitors as well, because + // their virtual position now overlaps with the monitor that + // we just made larger.. + // + // It'd be quite a bit of work to handle this correctly (and + // nobody else seems to bother doing this correctly either), + // so we're just leaving this broken. Fixing this would + // involve storing all CRTCs upon entering fullscreen, + // restoring them upon exit, and after entering fullscreen, + // repositioning displays to the right and below this + // display. I think there would still be edge cases that are + // difficult or impossible to handle correctly, e.g. what if + // a new monitor was plugged in while in fullscreen? + // + // I think we might just want to disallow setting the video + // mode higher than the current desktop video mode (I'm sure + // this will make someone unhappy, but it's very unusual for + // games to want to do this anyway). + self.xconn + .set_crtc_config(monitor.id, video_mode.native_mode) + .expect("failed to set video mode"); + } + + let window_position = self.outer_position_physical(); + self.shared_state.lock().restore_position = Some(window_position); + let monitor_origin: (i32, i32) = monitor.position().into(); + self.set_position_inner(monitor_origin.0, monitor_origin.1) + .queue(); + Some(self.set_fullscreen_hint(true)) + } + } + } + + #[inline] + pub fn fullscreen(&self) -> Option { + let shared_state = self.shared_state.lock(); + + shared_state + .desired_fullscreen + .clone() + .unwrap_or_else(|| shared_state.fullscreen.clone()) + } + + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option) { + if let Some(flusher) = self.set_fullscreen_inner(fullscreen) { + flusher + .sync() + .expect("Failed to change window fullscreen state"); + self.invalidate_cached_frame_extents(); + } + } + + // Called by EventProcessor when a VisibilityNotify event is received + pub(crate) fn visibility_notify(&self) { + let mut shared_state = self.shared_state.lock(); + + match shared_state.visibility { + Visibility::No => unsafe { + (self.xconn.xlib.XUnmapWindow)(self.xconn.display, self.xwindow); + }, + Visibility::Yes => (), + Visibility::YesWait => { + shared_state.visibility = Visibility::Yes; + + if let Some(fullscreen) = shared_state.desired_fullscreen.take() { + drop(shared_state); + self.set_fullscreen(fullscreen); + } + } + } + } + + #[inline] + pub fn current_monitor(&self) -> X11MonitorHandle { + self.shared_state.lock().last_monitor.clone() + } + + pub fn available_monitors(&self) -> Vec { + self.xconn.available_monitors() + } + + pub fn primary_monitor(&self) -> X11MonitorHandle { + self.xconn.primary_monitor() + } + + fn set_minimized_inner(&self, minimized: bool) -> util::Flusher<'_> { + unsafe { + if minimized { + let screen = (self.xconn.xlib.XDefaultScreen)(self.xconn.display); + + (self.xconn.xlib.XIconifyWindow)(self.xconn.display, self.xwindow, screen); + + util::Flusher::new(&self.xconn) + } else { + let atom = self.xconn.get_atom_unchecked(b"_NET_ACTIVE_WINDOW\0"); + + self.xconn.send_client_msg( + self.xwindow, + self.root, + atom, + Some(ffi::SubstructureRedirectMask | ffi::SubstructureNotifyMask), + [1, ffi::CurrentTime as c_long, 0, 0, 0], + ) + } + } + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + self.set_minimized_inner(minimized) + .flush() + .expect("Failed to change window minimization"); + } + + fn set_maximized_inner(&self, maximized: bool) -> util::Flusher<'_> { + let horz_atom = unsafe { + self.xconn + .get_atom_unchecked(b"_NET_WM_STATE_MAXIMIZED_HORZ\0") + }; + let vert_atom = unsafe { + self.xconn + .get_atom_unchecked(b"_NET_WM_STATE_MAXIMIZED_VERT\0") + }; + self.set_netwm( + maximized.into(), + (horz_atom as c_long, vert_atom as c_long, 0, 0), + ) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + self.set_maximized_inner(maximized) + .flush() + .expect("Failed to change window maximization"); + self.invalidate_cached_frame_extents(); + } + + fn set_title_inner(&self, title: &str) -> util::Flusher<'_> { + let wm_name_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_NAME\0") }; + let utf8_atom = unsafe { self.xconn.get_atom_unchecked(b"UTF8_STRING\0") }; + let title = CString::new(title).expect("Window title contained null byte"); + unsafe { + (self.xconn.xlib.XStoreName)( + self.xconn.display, + self.xwindow, + title.as_ptr() as *const c_char, + ); + self.xconn.change_property( + self.xwindow, + wm_name_atom, + utf8_atom, + util::PropMode::Replace, + title.as_bytes(), + ) + } + } + + #[inline] + pub fn set_title(&self, title: &str) { + self.set_title_inner(title) + .flush() + .expect("Failed to set window title"); + } + + fn set_decorations_inner(&self, decorations: bool) -> util::Flusher<'_> { + let mut hints = self.xconn.get_motif_hints(self.xwindow); + + hints.set_decorations(decorations); + + self.xconn.set_motif_hints(self.xwindow, &hints) + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + self.set_decorations_inner(decorations) + .flush() + .expect("Failed to set decoration state"); + self.invalidate_cached_frame_extents(); + } + + fn set_maximizable_inner(&self, maximizable: bool) -> util::Flusher<'_> { + let mut hints = self.xconn.get_motif_hints(self.xwindow); + + hints.set_maximizable(maximizable); + + self.xconn.set_motif_hints(self.xwindow, &hints) + } + + fn set_always_on_top_inner(&self, always_on_top: bool) -> util::Flusher<'_> { + let above_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_STATE_ABOVE\0") }; + self.set_netwm(always_on_top.into(), (above_atom as c_long, 0, 0, 0)) + } + + #[inline] + pub fn set_always_on_top(&self, always_on_top: bool) { + self.set_always_on_top_inner(always_on_top) + .flush() + .expect("Failed to set always-on-top state"); + } + + fn set_icon_inner(&self, icon: Icon) -> util::Flusher<'_> { + let icon_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_ICON\0") }; + let data = icon.to_cardinals(); + self.xconn.change_property( + self.xwindow, + icon_atom, + ffi::XA_CARDINAL, + util::PropMode::Replace, + data.as_slice(), + ) + } + + fn unset_icon_inner(&self) -> util::Flusher<'_> { + let icon_atom = unsafe { self.xconn.get_atom_unchecked(b"_NET_WM_ICON\0") }; + let empty_data: [util::Cardinal; 0] = []; + self.xconn.change_property( + self.xwindow, + icon_atom, + ffi::XA_CARDINAL, + util::PropMode::Replace, + &empty_data, + ) + } + + #[inline] + pub fn set_window_icon(&self, icon: Option) { + match icon { + Some(icon) => self.set_icon_inner(icon), + None => self.unset_icon_inner(), + } + .flush() + .expect("Failed to set icons"); + } + + #[inline] + pub fn set_visible(&self, visible: bool) { + let mut shared_state = self.shared_state.lock(); + + match (visible, shared_state.visibility) { + (true, Visibility::Yes) | (true, Visibility::YesWait) | (false, Visibility::No) => { + return + } + _ => (), + } + + if visible { + unsafe { + (self.xconn.xlib.XMapRaised)(self.xconn.display, self.xwindow); + } + self.xconn + .flush_requests() + .expect("Failed to call XMapRaised"); + shared_state.visibility = Visibility::YesWait; + } else { + unsafe { + (self.xconn.xlib.XUnmapWindow)(self.xconn.display, self.xwindow); + } + self.xconn + .flush_requests() + .expect("Failed to call XUnmapWindow"); + shared_state.visibility = Visibility::No; + } + } + + fn update_cached_frame_extents(&self) { + let extents = self + .xconn + .get_frame_extents_heuristic(self.xwindow, self.root); + (*self.shared_state.lock()).frame_extents = Some(extents); + } + + pub(crate) fn invalidate_cached_frame_extents(&self) { + (*self.shared_state.lock()).frame_extents.take(); + } + + pub(crate) fn outer_position_physical(&self) -> (i32, i32) { + let extents = (*self.shared_state.lock()).frame_extents.clone(); + if let Some(extents) = extents { + let (x, y) = self.inner_position_physical(); + extents.inner_pos_to_outer(x, y) + } else { + self.update_cached_frame_extents(); + self.outer_position_physical() + } + } + + #[inline] + pub fn outer_position(&self) -> Result, NotSupportedError> { + let extents = (*self.shared_state.lock()).frame_extents.clone(); + if let Some(extents) = extents { + let (x, y) = self.inner_position_physical(); + Ok(extents.inner_pos_to_outer(x, y).into()) + } else { + self.update_cached_frame_extents(); + self.outer_position() + } + } + + pub(crate) fn inner_position_physical(&self) -> (i32, i32) { + // This should be okay to unwrap since the only error XTranslateCoordinates can return + // is BadWindow, and if the window handle is bad we have bigger problems. + self.xconn + .translate_coords(self.xwindow, self.root) + .map(|coords| (coords.x_rel_root, coords.y_rel_root)) + .unwrap() + } + + #[inline] + pub fn inner_position(&self) -> Result, NotSupportedError> { + Ok(self.inner_position_physical().into()) + } + + pub(crate) fn set_position_inner(&self, mut x: i32, mut y: i32) -> util::Flusher<'_> { + // There are a few WMs that set client area position rather than window position, so + // we'll translate for consistency. + if util::wm_name_is_one_of(&["Enlightenment", "FVWM"]) { + let extents = (*self.shared_state.lock()).frame_extents.clone(); + if let Some(extents) = extents { + x += extents.frame_extents.left as i32; + y += extents.frame_extents.top as i32; + } else { + self.update_cached_frame_extents(); + return self.set_position_inner(x, y); + } + } + unsafe { + (self.xconn.xlib.XMoveWindow)(self.xconn.display, self.xwindow, x as c_int, y as c_int); + } + util::Flusher::new(&self.xconn) + } + + pub(crate) fn set_position_physical(&self, x: i32, y: i32) { + self.set_position_inner(x, y) + .flush() + .expect("Failed to call `XMoveWindow`"); + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + let (x, y) = position.to_physical::(self.scale_factor()).into(); + self.set_position_physical(x, y); + } + + pub(crate) fn inner_size_physical(&self) -> (u32, u32) { + // This should be okay to unwrap since the only error XGetGeometry can return + // is BadWindow, and if the window handle is bad we have bigger problems. + self.xconn + .get_geometry(self.xwindow) + .map(|geo| (geo.width, geo.height)) + .unwrap() + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + self.inner_size_physical().into() + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + let extents = self.shared_state.lock().frame_extents.clone(); + if let Some(extents) = extents { + let (width, height) = self.inner_size_physical(); + extents.inner_size_to_outer(width, height).into() + } else { + self.update_cached_frame_extents(); + self.outer_size() + } + } + + pub(crate) fn set_inner_size_physical(&self, width: u32, height: u32) { + unsafe { + (self.xconn.xlib.XResizeWindow)( + self.xconn.display, + self.xwindow, + width as c_uint, + height as c_uint, + ); + self.xconn.flush_requests() + } + .expect("Failed to call `XResizeWindow`"); + } + + #[inline] + pub fn set_inner_size(&self, size: Size) { + let scale_factor = self.scale_factor(); + let (width, height) = size.to_physical::(scale_factor).into(); + self.set_inner_size_physical(width, height); + } + + fn update_normal_hints(&self, callback: F) -> Result<(), XError> + where + F: FnOnce(&mut util::NormalHints<'_>) -> (), + { + let mut normal_hints = self.xconn.get_normal_hints(self.xwindow)?; + callback(&mut normal_hints); + self.xconn + .set_normal_hints(self.xwindow, normal_hints) + .flush() + } + + pub(crate) fn set_min_inner_size_physical(&self, dimensions: Option<(u32, u32)>) { + self.update_normal_hints(|normal_hints| normal_hints.set_min_size(dimensions)) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option) { + self.shared_state.lock().min_inner_size = dimensions; + let physical_dimensions = + dimensions.map(|dimensions| dimensions.to_physical::(self.scale_factor()).into()); + self.set_min_inner_size_physical(physical_dimensions); + } + + pub(crate) fn set_max_inner_size_physical(&self, dimensions: Option<(u32, u32)>) { + self.update_normal_hints(|normal_hints| normal_hints.set_max_size(dimensions)) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option) { + self.shared_state.lock().max_inner_size = dimensions; + let physical_dimensions = + dimensions.map(|dimensions| dimensions.to_physical::(self.scale_factor()).into()); + self.set_max_inner_size_physical(physical_dimensions); + } + + pub(crate) fn adjust_for_dpi( + &self, + old_scale_factor: f64, + new_scale_factor: f64, + width: u32, + height: u32, + shared_state: &SharedState, + ) -> (u32, u32) { + let scale_factor = new_scale_factor / old_scale_factor; + self.update_normal_hints(|normal_hints| { + let dpi_adjuster = + |size: Size| -> (u32, u32) { size.to_physical::(new_scale_factor).into() }; + let max_size = shared_state.max_inner_size.map(&dpi_adjuster); + let min_size = shared_state.min_inner_size.map(&dpi_adjuster); + let resize_increments = shared_state.resize_increments.map(&dpi_adjuster); + let base_size = shared_state.base_size.map(&dpi_adjuster); + normal_hints.set_max_size(max_size); + normal_hints.set_min_size(min_size); + normal_hints.set_resize_increments(resize_increments); + normal_hints.set_base_size(base_size); + }) + .expect("Failed to update normal hints"); + + let new_width = (width as f64 * scale_factor).round() as u32; + let new_height = (height as f64 * scale_factor).round() as u32; + + (new_width, new_height) + } + + pub fn set_resizable(&self, resizable: bool) { + if util::wm_name_is_one_of(&["Xfwm4"]) { + // Making the window unresizable on Xfwm prevents further changes to `WM_NORMAL_HINTS` from being detected. + // This makes it impossible for resizing to be re-enabled, and also breaks DPI scaling. As such, we choose + // the lesser of two evils and do nothing. + warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); + return; + } + + let (min_size, max_size) = if resizable { + let shared_state_lock = self.shared_state.lock(); + ( + shared_state_lock.min_inner_size, + shared_state_lock.max_inner_size, + ) + } else { + let window_size = Some(Size::from(self.inner_size())); + (window_size.clone(), window_size) + }; + + self.set_maximizable_inner(resizable).queue(); + + let scale_factor = self.scale_factor(); + let min_inner_size = min_size + .map(|size| size.to_physical::(scale_factor)) + .map(Into::into); + let max_inner_size = max_size + .map(|size| size.to_physical::(scale_factor)) + .map(Into::into); + self.update_normal_hints(|normal_hints| { + normal_hints.set_min_size(min_inner_size); + normal_hints.set_max_size(max_inner_size); + }) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn xlib_display(&self) -> *mut c_void { + self.xconn.display as _ + } + + #[inline] + pub fn xlib_screen_id(&self) -> c_int { + self.screen_id + } + + #[inline] + pub fn xlib_xconnection(&self) -> Arc { + Arc::clone(&self.xconn) + } + + #[inline] + pub fn xlib_window(&self) -> c_ulong { + self.xwindow + } + + #[inline] + pub fn xcb_connection(&self) -> *mut c_void { + unsafe { (self.xconn.xlib_xcb.XGetXCBConnection)(self.xconn.display) as *mut _ } + } + + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + let old_cursor = replace(&mut *self.cursor.lock(), cursor); + if cursor != old_cursor && *self.cursor_visible.lock() { + self.xconn.set_cursor_icon(self.xwindow, Some(cursor)); + } + } + + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + let mut grabbed_lock = self.cursor_grabbed.lock(); + if grab == *grabbed_lock { + return Ok(()); + } + unsafe { + // We ungrab before grabbing to prevent passive grabs from causing `AlreadyGrabbed`. + // Therefore, this is common to both codepaths. + (self.xconn.xlib.XUngrabPointer)(self.xconn.display, ffi::CurrentTime); + } + let result = if grab { + let result = unsafe { + (self.xconn.xlib.XGrabPointer)( + self.xconn.display, + self.xwindow, + ffi::True, + (ffi::ButtonPressMask + | ffi::ButtonReleaseMask + | ffi::EnterWindowMask + | ffi::LeaveWindowMask + | ffi::PointerMotionMask + | ffi::PointerMotionHintMask + | ffi::Button1MotionMask + | ffi::Button2MotionMask + | ffi::Button3MotionMask + | ffi::Button4MotionMask + | ffi::Button5MotionMask + | ffi::ButtonMotionMask + | ffi::KeymapStateMask) as c_uint, + ffi::GrabModeAsync, + ffi::GrabModeAsync, + self.xwindow, + 0, + ffi::CurrentTime, + ) + }; + + match result { + ffi::GrabSuccess => Ok(()), + ffi::AlreadyGrabbed => { + Err("Cursor could not be grabbed: already grabbed by another client") + } + ffi::GrabInvalidTime => Err("Cursor could not be grabbed: invalid time"), + ffi::GrabNotViewable => { + Err("Cursor could not be grabbed: grab location not viewable") + } + ffi::GrabFrozen => Err("Cursor could not be grabbed: frozen by another client"), + _ => unreachable!(), + } + .map_err(|err| ExternalError::Os(os_error!(OsError::XMisc(err)))) + } else { + self.xconn + .flush_requests() + .map_err(|err| ExternalError::Os(os_error!(OsError::XError(err)))) + }; + if result.is_ok() { + *grabbed_lock = grab; + } + result + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let mut visible_lock = self.cursor_visible.lock(); + if visible == *visible_lock { + return; + } + let cursor = if visible { + Some(*self.cursor.lock()) + } else { + None + }; + *visible_lock = visible; + drop(visible_lock); + self.xconn.set_cursor_icon(self.xwindow, cursor); + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.current_monitor().scale_factor + } + + pub fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), ExternalError> { + unsafe { + (self.xconn.xlib.XWarpPointer)(self.xconn.display, 0, self.xwindow, 0, 0, 0, 0, x, y); + self.xconn + .flush_requests() + .map_err(|e| ExternalError::Os(os_error!(OsError::XError(e)))) + } + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + let (x, y) = position.to_physical::(self.scale_factor()).into(); + self.set_cursor_position_physical(x, y) + } + + pub(crate) fn set_ime_position_physical(&self, x: i32, y: i32) { + let _ = self + .ime_sender + .lock() + .send((self.xwindow, x as i16, y as i16)); + } + + #[inline] + pub fn set_ime_position(&self, spot: Position) { + let (x, y) = spot.to_physical::(self.scale_factor()).into(); + self.set_ime_position_physical(x, y); + } + + #[inline] + pub fn id(&self) -> WindowId { + WindowId(self.xwindow) + } + + #[inline] + pub fn request_redraw(&self) { + self.pending_redraws + .lock() + .unwrap() + .insert(WindowId(self.xwindow)); + } + + #[inline] + pub fn raw_window_handle(&self) -> XlibHandle { + XlibHandle { + window: self.xwindow, + display: self.xconn.display as _, + ..XlibHandle::empty() + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/xdisplay.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/xdisplay.rs similarity index 72% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/xdisplay.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/xdisplay.rs index c0f1e7d..25065f0 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/linux/x11/xdisplay.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/linux/x11/xdisplay.rs @@ -1,10 +1,10 @@ -use std::ptr; -use std::fmt; -use std::error::Error; +use std::{collections::HashMap, error::Error, fmt, os::raw::c_int, ptr}; use libc; use parking_lot::Mutex; +use crate::window::CursorIcon; + use super::ffi; /// A connection to an X server. @@ -17,14 +17,18 @@ pub struct XConnection { pub xcursor: ffi::Xcursor, pub xinput2: ffi::XInput2, pub xlib_xcb: ffi::Xlib_xcb, + pub xrender: ffi::Xrender, pub display: *mut ffi::Display, + pub x11_fd: c_int, pub latest_error: Mutex>, + pub cursor_cache: Mutex, ffi::Cursor>>, } unsafe impl Send for XConnection {} unsafe impl Sync for XConnection {} -pub type XErrorHandler = Option libc::c_int>; +pub type XErrorHandler = + Option libc::c_int>; impl XConnection { pub fn new(error_handler: XErrorHandler) -> Result { @@ -35,6 +39,7 @@ impl XConnection { let xrandr_1_5 = ffi::Xrandr::open().ok(); let xinput2 = ffi::XInput2::open()?; let xlib_xcb = ffi::Xlib_xcb::open()?; + let xrender = ffi::Xrender::open()?; unsafe { (xlib.XInitThreads)() }; unsafe { (xlib.XSetErrorHandler)(error_handler) }; @@ -48,6 +53,9 @@ impl XConnection { display }; + // Get X11 socket file descriptor + let fd = unsafe { (xlib.XConnectionNumber)(display) }; + Ok(XConnection { xlib, xrandr, @@ -55,8 +63,11 @@ impl XConnection { xcursor, xinput2, xlib_xcb, + xrender, display, + x11_fd: fd, latest_error: Mutex::new(None), + cursor_cache: Default::default(), }) } @@ -79,7 +90,7 @@ impl XConnection { } impl fmt::Debug for XConnection { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.display.fmt(f) } } @@ -100,17 +111,15 @@ pub struct XError { pub minor_code: u8, } -impl Error for XError { - #[inline] - fn description(&self) -> &str { - &self.description - } -} +impl Error for XError {} impl fmt::Display for XError { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - write!(formatter, "X error: {} (code: {}, request code: {}, minor code: {})", - self.description, self.error_code, self.request_code, self.minor_code) + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!( + formatter, + "X error: {} (code: {}, request code: {}, minor code: {})", + self.description, self.error_code, self.request_code, self.minor_code + ) } } @@ -120,7 +129,7 @@ pub enum XNotSupported { /// Failed to load one or several shared libraries. LibraryOpenError(ffi::OpenError), /// Connecting to the X server with `XOpenDisplay` failed. - XOpenDisplayFailed, // TODO: add better message + XOpenDisplayFailed, // TODO: add better message } impl From for XNotSupported { @@ -130,26 +139,27 @@ impl From for XNotSupported { } } -impl Error for XNotSupported { - #[inline] - fn description(&self) -> &str { - match *self { +impl XNotSupported { + fn description(&self) -> &'static str { + match self { XNotSupported::LibraryOpenError(_) => "Failed to load one of xlib's shared libraries", XNotSupported::XOpenDisplayFailed => "Failed to open connection to X server", } } +} +impl Error for XNotSupported { #[inline] - fn cause(&self) -> Option<&Error> { + fn source(&self) -> Option<&(dyn Error + 'static)> { match *self { XNotSupported::LibraryOpenError(ref err) => Some(err), - _ => None + _ => None, } } } impl fmt::Display for XNotSupported { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { formatter.write_str(self.description()) } } diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/activation_hack.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/activation_hack.rs new file mode 100644 index 0000000..6cf1960 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/activation_hack.rs @@ -0,0 +1,208 @@ +// Normally when you run or distribute a macOS app, it's bundled: it's in one +// of those fun little folders that you have to right click "Show Package +// Contents" on, and usually contains myriad delights including, but not +// limited to, plists, icons, and of course, your beloved executable. However, +// when you use `cargo run`, your app is unbundled - it's just a lonely, bare +// executable. +// +// Apple isn't especially fond of unbundled apps, which is to say, they seem to +// barely be supported. If you move the mouse while opening a winit window from +// an unbundled app, the window will fail to activate and be in a grayed-out +// uninteractable state. Switching to another app and back is the only way to +// get the winit window into a normal state. None of this happens if the app is +// bundled, i.e. when running via Xcode. +// +// To workaround this, we just switch focus to the Dock and then switch back to +// our app. We only do this for unbundled apps, and only when they fail to +// become active on their own. +// +// This solution was derived from this Godot PR: +// https://github.com/godotengine/godot/pull/17187 +// (which appears to be based on https://stackoverflow.com/a/7602677) +// The curious specialness of mouse motions is touched upon here: +// https://github.com/godotengine/godot/issues/8653#issuecomment-358130512 +// +// We omit the 2nd step of the solution used in Godot, since it appears to have +// no effect - I speculate that it's just technical debt picked up from the SO +// answer; the API used is fairly exotic, and was historically used for very +// old versions of macOS that didn't support `activateIgnoringOtherApps`, i.e. +// in previous versions of SDL: +// https://hg.libsdl.org/SDL/file/c0bcc39a3491/src/video/cocoa/SDL_cocoaevents.m#l322 +// +// The `performSelector` delays in the Godot solution are used for sequencing, +// since refocusing the app will fail if the call is made before it finishes +// unfocusing. The delays used there are much smaller than the ones in the +// original SO answer, presumably because they found the fastest delay that +// works reliably through trial and error. Instead of using delays, we just +// handle `applicationDidResignActive`; despite the app not activating reliably, +// that still triggers when we switch focus to the Dock. +// +// The Godot solution doesn't appear to skip the hack when an unbundled app +// activates normally. Checking for this is difficult, since if you call +// `isActive` too early, it will always be `NO`. Even though we receive +// `applicationDidResignActive` when switching focus to the Dock, we never +// receive a preceding `applicationDidBecomeActive` if the app fails to +// activate normally. I wasn't able to find a proper point in time to perform +// the `isActive` check, so we instead check for the cause of the quirk: if +// any mouse motion occurs prior to us receiving `applicationDidResignActive`, +// we assume the app failed to become active. +// +// Fun fact: this issue is still present in GLFW +// (https://github.com/glfw/glfw/issues/1515) +// +// A similar issue was found in SDL, but the resolution doesn't seem to work +// for us: https://bugzilla.libsdl.org/show_bug.cgi?id=3051 + +use super::util; +use cocoa::{ + appkit::{NSApp, NSApplicationActivateIgnoringOtherApps}, + base::id, + foundation::NSUInteger, +}; +use objc::runtime::{Object, Sel, BOOL, NO, YES}; +use std::{ + os::raw::c_void, + sync::atomic::{AtomicBool, Ordering}, +}; + +#[derive(Debug, Default)] +pub struct State { + // Indicates that the hack has either completed or been skipped. + activated: AtomicBool, + // Indicates that the mouse has moved at some point in time. + mouse_moved: AtomicBool, + // Indicates that the hack is in progress, and that we should refocus when + // the app resigns active. + needs_refocus: AtomicBool, +} + +impl State { + pub fn name() -> &'static str { + "activationHackState" + } + + pub fn new() -> *mut c_void { + let this = Box::new(Self::default()); + Box::into_raw(this) as *mut c_void + } + + pub unsafe fn free(this: *mut Self) { + Box::from_raw(this); + } + + pub unsafe fn get_ptr(obj: &Object) -> *mut Self { + let this: *mut c_void = *(*obj).get_ivar(Self::name()); + assert!(!this.is_null(), "`activationHackState` pointer was null"); + this as *mut Self + } + + pub unsafe fn set_activated(obj: &Object, value: bool) { + let this = Self::get_ptr(obj); + (*this).activated.store(value, Ordering::Release); + } + + unsafe fn get_activated(obj: &Object) -> bool { + let this = Self::get_ptr(obj); + (*this).activated.load(Ordering::Acquire) + } + + pub unsafe fn set_mouse_moved(obj: &Object, value: bool) { + let this = Self::get_ptr(obj); + (*this).mouse_moved.store(value, Ordering::Release); + } + + pub unsafe fn get_mouse_moved(obj: &Object) -> bool { + let this = Self::get_ptr(obj); + (*this).mouse_moved.load(Ordering::Acquire) + } + + pub unsafe fn set_needs_refocus(obj: &Object, value: bool) { + let this = Self::get_ptr(obj); + (*this).needs_refocus.store(value, Ordering::Release); + } + + unsafe fn get_needs_refocus(obj: &Object) -> bool { + let this = Self::get_ptr(obj); + (*this).needs_refocus.load(Ordering::Acquire) + } +} + +// This is the entry point for the hack - if the app is unbundled and a mouse +// movement occurs before the app activates, it will trigger the hack. Because +// mouse movements prior to activation are the cause of this quirk, they should +// be a reliable way to determine if the hack needs to be performed. +pub extern "C" fn mouse_moved(this: &Object, _: Sel, _: id) { + trace!("Triggered `activationHackMouseMoved`"); + unsafe { + if !State::get_activated(this) { + // We check if `CFBundleName` is undefined to determine if the + // app is unbundled. + if let None = util::app_name() { + info!("App detected as unbundled"); + unfocus(this); + } else { + info!("App detected as bundled"); + } + } + } + trace!("Completed `activationHackMouseMoved`"); +} + +// Switch focus to the dock. +unsafe fn unfocus(this: &Object) { + // We only perform the hack if the app failed to activate, since otherwise, + // there'd be a gross (but fast) flicker as it unfocused and then refocused. + // However, we only enter this function if we detect mouse movement prior + // to activation, so this should always be `NO`. + // + // Note that this check isn't necessarily reliable in detecting a violation + // of the invariant above, since it's not guaranteed that activation will + // resolve before this point. In other words, it can spuriously return `NO`. + // This is also why the mouse motion approach was chosen, since it's not + // obvious how to sequence this check - if someone knows how to, then that + // would almost surely be a cleaner approach. + let active: BOOL = msg_send![NSApp(), isActive]; + if active == YES { + error!("Unbundled app activation hack triggered on an app that's already active; this shouldn't happen!"); + } else { + info!("Performing unbundled app activation hack"); + let dock_bundle_id = util::ns_string_id_ref("com.apple.dock"); + let dock_array: id = msg_send![ + class!(NSRunningApplication), + runningApplicationsWithBundleIdentifier: *dock_bundle_id + ]; + let dock_array_len: NSUInteger = msg_send![dock_array, count]; + if dock_array_len == 0 { + error!("The Dock doesn't seem to be running, so switching focus to it is impossible"); + } else { + State::set_needs_refocus(this, true); + let dock: id = msg_send![dock_array, objectAtIndex: 0]; + // This will trigger `applicationDidResignActive`, which will in + // turn call `refocus`. + let status: BOOL = msg_send![ + dock, + activateWithOptions: NSApplicationActivateIgnoringOtherApps + ]; + if status == NO { + error!("Failed to switch focus to Dock"); + } + } + } +} + +// Switch focus back to our app, causing the user to rejoice! +pub unsafe fn refocus(this: &Object) { + if State::get_needs_refocus(this) { + State::set_needs_refocus(this, false); + let app: id = msg_send![class!(NSRunningApplication), currentApplication]; + // Simply calling `NSApp activateIgnoringOtherApps` doesn't work. The + // nuanced difference isn't clear to me, but hey, I tried. + let success: BOOL = msg_send![ + app, + activateWithOptions: NSApplicationActivateIgnoringOtherApps + ]; + if success == NO { + error!("Failed to refocus app"); + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app.rs new file mode 100644 index 0000000..4cec951 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app.rs @@ -0,0 +1,145 @@ +use std::collections::VecDeque; + +use cocoa::{ + appkit::{self, NSEvent}, + base::{id, nil}, +}; +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Sel}, +}; + +use super::{activation_hack, app_state::AppState, event::EventWrapper, util, DEVICE_ID}; +use crate::event::{DeviceEvent, ElementState, Event}; + +pub struct AppClass(pub *const Class); +unsafe impl Send for AppClass {} +unsafe impl Sync for AppClass {} + +lazy_static! { + pub static ref APP_CLASS: AppClass = unsafe { + let superclass = class!(NSApplication); + let mut decl = ClassDecl::new("WinitApp", superclass).unwrap(); + + decl.add_method( + sel!(sendEvent:), + send_event as extern "C" fn(&Object, Sel, id), + ); + + AppClass(decl.register()) + }; +} + +// Normally, holding Cmd + any key never sends us a `keyUp` event for that key. +// Overriding `sendEvent:` like this fixes that. (https://stackoverflow.com/a/15294196) +// Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553) +extern "C" fn send_event(this: &Object, _sel: Sel, event: id) { + unsafe { + // For posterity, there are some undocumented event types + // (https://github.com/servo/cocoa-rs/issues/155) + // but that doesn't really matter here. + let event_type = event.eventType(); + let modifier_flags = event.modifierFlags(); + if event_type == appkit::NSKeyUp + && util::has_flag( + modifier_flags, + appkit::NSEventModifierFlags::NSCommandKeyMask, + ) + { + let key_window: id = msg_send![this, keyWindow]; + let _: () = msg_send![key_window, sendEvent: event]; + } else { + maybe_dispatch_device_event(this, event); + let superclass = util::superclass(this); + let _: () = msg_send![super(this, superclass), sendEvent: event]; + } + } +} + +unsafe fn maybe_dispatch_device_event(this: &Object, event: id) { + let event_type = event.eventType(); + match event_type { + appkit::NSMouseMoved + | appkit::NSLeftMouseDragged + | appkit::NSOtherMouseDragged + | appkit::NSRightMouseDragged => { + let mut events = VecDeque::with_capacity(3); + + let delta_x = event.deltaX() as f64; + let delta_y = event.deltaY() as f64; + + if delta_x != 0.0 { + events.push_back(EventWrapper::StaticEvent(Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::Motion { + axis: 0, + value: delta_x, + }, + })); + } + + if delta_y != 0.0 { + events.push_back(EventWrapper::StaticEvent(Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::Motion { + axis: 1, + value: delta_y, + }, + })); + } + + if delta_x != 0.0 || delta_y != 0.0 { + events.push_back(EventWrapper::StaticEvent(Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::MouseMotion { + delta: (delta_x, delta_y), + }, + })); + } + + AppState::queue_events(events); + + // Notify the delegate when the first mouse move occurs. This is + // used for the unbundled app activation hack, which needs to know + // if any mouse motions occurred prior to the app activating. + let delegate: id = msg_send![this, delegate]; + assert_ne!(delegate, nil); + if !activation_hack::State::get_mouse_moved(&*delegate) { + activation_hack::State::set_mouse_moved(&*delegate, true); + let () = msg_send![ + delegate, + performSelector: sel!(activationHackMouseMoved:) + withObject: nil + afterDelay: 0.0 + ]; + } + } + appkit::NSLeftMouseDown | appkit::NSRightMouseDown | appkit::NSOtherMouseDown => { + let mut events = VecDeque::with_capacity(1); + + events.push_back(EventWrapper::StaticEvent(Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::Button { + button: event.buttonNumber() as u32, + state: ElementState::Pressed, + }, + })); + + AppState::queue_events(events); + } + appkit::NSLeftMouseUp | appkit::NSRightMouseUp | appkit::NSOtherMouseUp => { + let mut events = VecDeque::with_capacity(1); + + events.push_back(EventWrapper::StaticEvent(Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::Button { + button: event.buttonNumber() as u32, + state: ElementState::Released, + }, + })); + + AppState::queue_events(events); + } + _ => (), + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_delegate.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_delegate.rs new file mode 100644 index 0000000..9263cc1 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_delegate.rs @@ -0,0 +1,81 @@ +use super::{activation_hack, app_state::AppState}; +use cocoa::base::id; +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Sel}, +}; +use std::os::raw::c_void; + +pub struct AppDelegateClass(pub *const Class); +unsafe impl Send for AppDelegateClass {} +unsafe impl Sync for AppDelegateClass {} + +lazy_static! { + pub static ref APP_DELEGATE_CLASS: AppDelegateClass = unsafe { + let superclass = class!(NSResponder); + let mut decl = ClassDecl::new("WinitAppDelegate", superclass).unwrap(); + + decl.add_class_method(sel!(new), new as extern "C" fn(&Class, Sel) -> id); + decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); + decl.add_method( + sel!(applicationDidFinishLaunching:), + did_finish_launching as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(applicationDidBecomeActive:), + did_become_active as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(applicationDidResignActive:), + did_resign_active as extern "C" fn(&Object, Sel, id), + ); + + decl.add_ivar::<*mut c_void>(activation_hack::State::name()); + decl.add_method( + sel!(activationHackMouseMoved:), + activation_hack::mouse_moved as extern "C" fn(&Object, Sel, id), + ); + + AppDelegateClass(decl.register()) + }; +} + +extern "C" fn new(class: &Class, _: Sel) -> id { + unsafe { + let this: id = msg_send![class, alloc]; + let this: id = msg_send![this, init]; + (*this).set_ivar( + activation_hack::State::name(), + activation_hack::State::new(), + ); + this + } +} + +extern "C" fn dealloc(this: &Object, _: Sel) { + unsafe { + activation_hack::State::free(activation_hack::State::get_ptr(this)); + } +} + +extern "C" fn did_finish_launching(_: &Object, _: Sel, _: id) { + trace!("Triggered `applicationDidFinishLaunching`"); + AppState::launched(); + trace!("Completed `applicationDidFinishLaunching`"); +} + +extern "C" fn did_become_active(this: &Object, _: Sel, _: id) { + trace!("Triggered `applicationDidBecomeActive`"); + unsafe { + activation_hack::State::set_activated(this, true); + } + trace!("Completed `applicationDidBecomeActive`"); +} + +extern "C" fn did_resign_active(this: &Object, _: Sel, _: id) { + trace!("Triggered `applicationDidResignActive`"); + unsafe { + activation_hack::refocus(this); + } + trace!("Completed `applicationDidResignActive`"); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_state.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_state.rs new file mode 100644 index 0000000..135a3d2 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/app_state.rs @@ -0,0 +1,373 @@ +use std::{ + collections::VecDeque, + fmt::{self, Debug}, + hint::unreachable_unchecked, + mem, + rc::Rc, + sync::{ + atomic::{AtomicBool, Ordering}, + Mutex, MutexGuard, + }, + time::Instant, +}; + +use cocoa::{ + appkit::{NSApp, NSEventType::NSApplicationDefined, NSWindow}, + base::{id, nil}, + foundation::{NSAutoreleasePool, NSPoint, NSSize}, +}; + +use objc::runtime::YES; + +use crate::{ + dpi::LogicalSize, + event::{Event, StartCause, WindowEvent}, + event_loop::{ControlFlow, EventLoopWindowTarget as RootWindowTarget}, + platform_impl::platform::{ + event::{EventProxy, EventWrapper}, + observer::EventLoopWaker, + util::{IdRef, Never}, + window::get_window_id, + }, + window::WindowId, +}; + +lazy_static! { + static ref HANDLER: Handler = Default::default(); +} + +impl<'a, Never> Event<'a, Never> { + fn userify(self) -> Event<'a, T> { + self.map_nonuser_event() + // `Never` can't be constructed, so the `UserEvent` variant can't + // be present here. + .unwrap_or_else(|_| unsafe { unreachable_unchecked() }) + } +} + +pub trait EventHandler: Debug { + // Not sure probably it should accept Event<'static, Never> + fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow); + fn handle_user_events(&mut self, control_flow: &mut ControlFlow); +} + +struct EventLoopHandler { + callback: Box, &RootWindowTarget, &mut ControlFlow)>, + will_exit: bool, + window_target: Rc>, +} + +impl Debug for EventLoopHandler { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("EventLoopHandler") + .field("window_target", &self.window_target) + .finish() + } +} + +impl EventHandler for EventLoopHandler { + fn handle_nonuser_event(&mut self, event: Event<'_, Never>, control_flow: &mut ControlFlow) { + (self.callback)(event.userify(), &self.window_target, control_flow); + self.will_exit |= *control_flow == ControlFlow::Exit; + if self.will_exit { + *control_flow = ControlFlow::Exit; + } + } + + fn handle_user_events(&mut self, control_flow: &mut ControlFlow) { + let mut will_exit = self.will_exit; + for event in self.window_target.p.receiver.try_iter() { + (self.callback)(Event::UserEvent(event), &self.window_target, control_flow); + will_exit |= *control_flow == ControlFlow::Exit; + if will_exit { + *control_flow = ControlFlow::Exit; + } + } + self.will_exit = will_exit; + } +} + +#[derive(Default)] +struct Handler { + ready: AtomicBool, + in_callback: AtomicBool, + control_flow: Mutex, + control_flow_prev: Mutex, + start_time: Mutex>, + callback: Mutex>>, + pending_events: Mutex>, + pending_redraw: Mutex>, + waker: Mutex, +} + +unsafe impl Send for Handler {} +unsafe impl Sync for Handler {} + +impl Handler { + fn events(&self) -> MutexGuard<'_, VecDeque> { + self.pending_events.lock().unwrap() + } + + fn redraw<'a>(&'a self) -> MutexGuard<'a, Vec> { + self.pending_redraw.lock().unwrap() + } + + fn waker(&self) -> MutexGuard<'_, EventLoopWaker> { + self.waker.lock().unwrap() + } + + fn is_ready(&self) -> bool { + self.ready.load(Ordering::Acquire) + } + + fn set_ready(&self) { + self.ready.store(true, Ordering::Release); + } + + fn should_exit(&self) -> bool { + *self.control_flow.lock().unwrap() == ControlFlow::Exit + } + + fn get_control_flow_and_update_prev(&self) -> ControlFlow { + let control_flow = self.control_flow.lock().unwrap(); + *self.control_flow_prev.lock().unwrap() = *control_flow; + *control_flow + } + + fn get_old_and_new_control_flow(&self) -> (ControlFlow, ControlFlow) { + let old = *self.control_flow_prev.lock().unwrap(); + let new = *self.control_flow.lock().unwrap(); + (old, new) + } + + fn get_start_time(&self) -> Option { + *self.start_time.lock().unwrap() + } + + fn update_start_time(&self) { + *self.start_time.lock().unwrap() = Some(Instant::now()); + } + + fn take_events(&self) -> VecDeque { + mem::replace(&mut *self.events(), Default::default()) + } + + fn should_redraw(&self) -> Vec { + mem::replace(&mut *self.redraw(), Default::default()) + } + + fn get_in_callback(&self) -> bool { + self.in_callback.load(Ordering::Acquire) + } + + fn set_in_callback(&self, in_callback: bool) { + self.in_callback.store(in_callback, Ordering::Release); + } + + fn handle_nonuser_event(&self, wrapper: EventWrapper) { + if let Some(ref mut callback) = *self.callback.lock().unwrap() { + match wrapper { + EventWrapper::StaticEvent(event) => { + callback.handle_nonuser_event(event, &mut *self.control_flow.lock().unwrap()) + } + EventWrapper::EventProxy(proxy) => self.handle_proxy(proxy, callback), + } + } + } + + fn handle_user_events(&self) { + if let Some(ref mut callback) = *self.callback.lock().unwrap() { + callback.handle_user_events(&mut *self.control_flow.lock().unwrap()); + } + } + + fn handle_scale_factor_changed_event( + &self, + callback: &mut Box, + ns_window: IdRef, + suggested_size: LogicalSize, + scale_factor: f64, + ) { + let mut size = suggested_size.to_physical(scale_factor); + let new_inner_size = &mut size; + let event = Event::WindowEvent { + window_id: WindowId(get_window_id(*ns_window)), + event: WindowEvent::ScaleFactorChanged { + scale_factor, + new_inner_size, + }, + }; + + callback.handle_nonuser_event(event, &mut *self.control_flow.lock().unwrap()); + + let physical_size = *new_inner_size; + let logical_size = physical_size.to_logical(scale_factor); + let size = NSSize::new(logical_size.width, logical_size.height); + unsafe { NSWindow::setContentSize_(*ns_window, size) }; + } + + fn handle_proxy(&self, proxy: EventProxy, callback: &mut Box) { + match proxy { + EventProxy::DpiChangedProxy { + ns_window, + suggested_size, + scale_factor, + } => self.handle_scale_factor_changed_event( + callback, + ns_window, + suggested_size, + scale_factor, + ), + } + } +} + +pub enum AppState {} + +impl AppState { + // This function extends lifetime of `callback` to 'static as its side effect + pub unsafe fn set_callback(callback: F, window_target: Rc>) + where + F: FnMut(Event<'_, T>, &RootWindowTarget, &mut ControlFlow), + { + *HANDLER.callback.lock().unwrap() = Some(Box::new(EventLoopHandler { + // This transmute is always safe, in case it was reached through `run`, since our + // lifetime will be already 'static. In other cases caller should ensure that all data + // they passed to callback will actually outlive it, some apps just can't move + // everything to event loop, so this is something that they should care about. + callback: mem::transmute::< + Box, &RootWindowTarget, &mut ControlFlow)>, + Box, &RootWindowTarget, &mut ControlFlow)>, + >(Box::new(callback)), + will_exit: false, + window_target, + })); + } + + pub fn exit() { + HANDLER.set_in_callback(true); + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::LoopDestroyed)); + HANDLER.set_in_callback(false); + HANDLER.callback.lock().unwrap().take(); + } + + pub fn launched() { + HANDLER.set_ready(); + HANDLER.waker().start(); + HANDLER.set_in_callback(true); + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::NewEvents( + StartCause::Init, + ))); + HANDLER.set_in_callback(false); + } + + pub fn wakeup() { + if !HANDLER.is_ready() { + return; + } + let start = HANDLER.get_start_time().unwrap(); + let cause = match HANDLER.get_control_flow_and_update_prev() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { + start, + requested_resume: None, + }, + ControlFlow::WaitUntil(requested_resume) => { + if Instant::now() >= requested_resume { + StartCause::ResumeTimeReached { + start, + requested_resume, + } + } else { + StartCause::WaitCancelled { + start, + requested_resume: Some(requested_resume), + } + } + } + ControlFlow::Exit => StartCause::Poll, //panic!("unexpected `ControlFlow::Exit`"), + }; + HANDLER.set_in_callback(true); + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::NewEvents(cause))); + HANDLER.set_in_callback(false); + } + + // This is called from multiple threads at present + pub fn queue_redraw(window_id: WindowId) { + let mut pending_redraw = HANDLER.redraw(); + if !pending_redraw.contains(&window_id) { + pending_redraw.push(window_id); + } + } + + pub fn queue_event(wrapper: EventWrapper) { + if !unsafe { msg_send![class!(NSThread), isMainThread] } { + panic!("Event queued from different thread: {:#?}", wrapper); + } + HANDLER.events().push_back(wrapper); + } + + pub fn queue_events(mut wrappers: VecDeque) { + if !unsafe { msg_send![class!(NSThread), isMainThread] } { + panic!("Events queued from different thread: {:#?}", wrappers); + } + HANDLER.events().append(&mut wrappers); + } + + pub fn cleared() { + if !HANDLER.is_ready() { + return; + } + if !HANDLER.get_in_callback() { + HANDLER.set_in_callback(true); + HANDLER.handle_user_events(); + for event in HANDLER.take_events() { + HANDLER.handle_nonuser_event(event); + } + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::MainEventsCleared)); + for window_id in HANDLER.should_redraw() { + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawRequested( + window_id, + ))); + } + HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawEventsCleared)); + HANDLER.set_in_callback(false); + } + if HANDLER.should_exit() { + unsafe { + let _: () = msg_send![NSApp(), stop: nil]; + + let pool = NSAutoreleasePool::new(nil); + + let windows: id = msg_send![NSApp(), windows]; + let window: id = msg_send![windows, objectAtIndex:0]; + assert_ne!(window, nil); + + let dummy_event: id = msg_send![class!(NSEvent), + otherEventWithType: NSApplicationDefined + location: NSPoint::new(0.0, 0.0) + modifierFlags: 0 + timestamp: 0 + windowNumber: 0 + context: nil + subtype: 0 + data1: 0 + data2: 0 + ]; + // To stop event loop immediately, we need to post some event here. + let _: () = msg_send![window, postEvent: dummy_event atStart: YES]; + + pool.drain(); + }; + } + HANDLER.update_start_time(); + match HANDLER.get_old_and_new_control_flow() { + (ControlFlow::Exit, _) | (_, ControlFlow::Exit) => (), + (old, new) if old == new => (), + (_, ControlFlow::Wait) => HANDLER.waker().stop(), + (_, ControlFlow::WaitUntil(instant)) => HANDLER.waker().start_at(instant), + (_, ControlFlow::Poll) => HANDLER.waker().start(), + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event.rs new file mode 100644 index 0000000..6e23194 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event.rs @@ -0,0 +1,304 @@ +use std::os::raw::c_ushort; + +use cocoa::{ + appkit::{NSEvent, NSEventModifierFlags}, + base::id, +}; + +use crate::{ + dpi::LogicalSize, + event::{ElementState, Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}, + platform_impl::platform::{ + util::{IdRef, Never}, + DEVICE_ID, + }, +}; + +#[derive(Debug)] +pub enum EventWrapper { + StaticEvent(Event<'static, Never>), + EventProxy(EventProxy), +} + +#[derive(Debug, PartialEq)] +pub enum EventProxy { + DpiChangedProxy { + ns_window: IdRef, + suggested_size: LogicalSize, + scale_factor: f64, + }, +} + +pub fn char_to_keycode(c: char) -> Option { + // We only translate keys that are affected by keyboard layout. + // + // Note that since keys are translated in a somewhat "dumb" way (reading character) + // there is a concern that some combination, i.e. Cmd+char, causes the wrong + // letter to be received, and so we receive the wrong key. + // + // Implementation reference: https://github.com/WebKit/webkit/blob/82bae82cf0f329dbe21059ef0986c4e92fea4ba6/Source/WebCore/platform/cocoa/KeyEventCocoa.mm#L626 + Some(match c { + 'a' | 'A' => VirtualKeyCode::A, + 'b' | 'B' => VirtualKeyCode::B, + 'c' | 'C' => VirtualKeyCode::C, + 'd' | 'D' => VirtualKeyCode::D, + 'e' | 'E' => VirtualKeyCode::E, + 'f' | 'F' => VirtualKeyCode::F, + 'g' | 'G' => VirtualKeyCode::G, + 'h' | 'H' => VirtualKeyCode::H, + 'i' | 'I' => VirtualKeyCode::I, + 'j' | 'J' => VirtualKeyCode::J, + 'k' | 'K' => VirtualKeyCode::K, + 'l' | 'L' => VirtualKeyCode::L, + 'm' | 'M' => VirtualKeyCode::M, + 'n' | 'N' => VirtualKeyCode::N, + 'o' | 'O' => VirtualKeyCode::O, + 'p' | 'P' => VirtualKeyCode::P, + 'q' | 'Q' => VirtualKeyCode::Q, + 'r' | 'R' => VirtualKeyCode::R, + 's' | 'S' => VirtualKeyCode::S, + 't' | 'T' => VirtualKeyCode::T, + 'u' | 'U' => VirtualKeyCode::U, + 'v' | 'V' => VirtualKeyCode::V, + 'w' | 'W' => VirtualKeyCode::W, + 'x' | 'X' => VirtualKeyCode::X, + 'y' | 'Y' => VirtualKeyCode::Y, + 'z' | 'Z' => VirtualKeyCode::Z, + '1' | '!' => VirtualKeyCode::Key1, + '2' | '@' => VirtualKeyCode::Key2, + '3' | '#' => VirtualKeyCode::Key3, + '4' | '$' => VirtualKeyCode::Key4, + '5' | '%' => VirtualKeyCode::Key5, + '6' | '^' => VirtualKeyCode::Key6, + '7' | '&' => VirtualKeyCode::Key7, + '8' | '*' => VirtualKeyCode::Key8, + '9' | '(' => VirtualKeyCode::Key9, + '0' | ')' => VirtualKeyCode::Key0, + '=' | '+' => VirtualKeyCode::Equals, + '-' | '_' => VirtualKeyCode::Minus, + ']' | '}' => VirtualKeyCode::RBracket, + '[' | '{' => VirtualKeyCode::LBracket, + '\'' | '"' => VirtualKeyCode::Apostrophe, + ';' | ':' => VirtualKeyCode::Semicolon, + '\\' | '|' => VirtualKeyCode::Backslash, + ',' | '<' => VirtualKeyCode::Comma, + '/' | '?' => VirtualKeyCode::Slash, + '.' | '>' => VirtualKeyCode::Period, + '`' | '~' => VirtualKeyCode::Grave, + _ => return None, + }) +} + +pub fn scancode_to_keycode(scancode: c_ushort) -> Option { + Some(match scancode { + 0x00 => VirtualKeyCode::A, + 0x01 => VirtualKeyCode::S, + 0x02 => VirtualKeyCode::D, + 0x03 => VirtualKeyCode::F, + 0x04 => VirtualKeyCode::H, + 0x05 => VirtualKeyCode::G, + 0x06 => VirtualKeyCode::Z, + 0x07 => VirtualKeyCode::X, + 0x08 => VirtualKeyCode::C, + 0x09 => VirtualKeyCode::V, + //0x0a => World 1, + 0x0b => VirtualKeyCode::B, + 0x0c => VirtualKeyCode::Q, + 0x0d => VirtualKeyCode::W, + 0x0e => VirtualKeyCode::E, + 0x0f => VirtualKeyCode::R, + 0x10 => VirtualKeyCode::Y, + 0x11 => VirtualKeyCode::T, + 0x12 => VirtualKeyCode::Key1, + 0x13 => VirtualKeyCode::Key2, + 0x14 => VirtualKeyCode::Key3, + 0x15 => VirtualKeyCode::Key4, + 0x16 => VirtualKeyCode::Key6, + 0x17 => VirtualKeyCode::Key5, + 0x18 => VirtualKeyCode::Equals, + 0x19 => VirtualKeyCode::Key9, + 0x1a => VirtualKeyCode::Key7, + 0x1b => VirtualKeyCode::Minus, + 0x1c => VirtualKeyCode::Key8, + 0x1d => VirtualKeyCode::Key0, + 0x1e => VirtualKeyCode::RBracket, + 0x1f => VirtualKeyCode::O, + 0x20 => VirtualKeyCode::U, + 0x21 => VirtualKeyCode::LBracket, + 0x22 => VirtualKeyCode::I, + 0x23 => VirtualKeyCode::P, + 0x24 => VirtualKeyCode::Return, + 0x25 => VirtualKeyCode::L, + 0x26 => VirtualKeyCode::J, + 0x27 => VirtualKeyCode::Apostrophe, + 0x28 => VirtualKeyCode::K, + 0x29 => VirtualKeyCode::Semicolon, + 0x2a => VirtualKeyCode::Backslash, + 0x2b => VirtualKeyCode::Comma, + 0x2c => VirtualKeyCode::Slash, + 0x2d => VirtualKeyCode::N, + 0x2e => VirtualKeyCode::M, + 0x2f => VirtualKeyCode::Period, + 0x30 => VirtualKeyCode::Tab, + 0x31 => VirtualKeyCode::Space, + 0x32 => VirtualKeyCode::Grave, + 0x33 => VirtualKeyCode::Back, + //0x34 => unkown, + 0x35 => VirtualKeyCode::Escape, + 0x36 => VirtualKeyCode::RWin, + 0x37 => VirtualKeyCode::LWin, + 0x38 => VirtualKeyCode::LShift, + //0x39 => Caps lock, + 0x3a => VirtualKeyCode::LAlt, + 0x3b => VirtualKeyCode::LControl, + 0x3c => VirtualKeyCode::RShift, + 0x3d => VirtualKeyCode::RAlt, + 0x3e => VirtualKeyCode::RControl, + //0x3f => Fn key, + 0x40 => VirtualKeyCode::F17, + 0x41 => VirtualKeyCode::Decimal, + //0x42 -> unkown, + 0x43 => VirtualKeyCode::Multiply, + //0x44 => unkown, + 0x45 => VirtualKeyCode::Add, + //0x46 => unkown, + 0x47 => VirtualKeyCode::Numlock, + //0x48 => KeypadClear, + 0x49 => VirtualKeyCode::VolumeUp, + 0x4a => VirtualKeyCode::VolumeDown, + 0x4b => VirtualKeyCode::Divide, + 0x4c => VirtualKeyCode::NumpadEnter, + //0x4d => unkown, + 0x4e => VirtualKeyCode::Subtract, + 0x4f => VirtualKeyCode::F18, + 0x50 => VirtualKeyCode::F19, + 0x51 => VirtualKeyCode::NumpadEquals, + 0x52 => VirtualKeyCode::Numpad0, + 0x53 => VirtualKeyCode::Numpad1, + 0x54 => VirtualKeyCode::Numpad2, + 0x55 => VirtualKeyCode::Numpad3, + 0x56 => VirtualKeyCode::Numpad4, + 0x57 => VirtualKeyCode::Numpad5, + 0x58 => VirtualKeyCode::Numpad6, + 0x59 => VirtualKeyCode::Numpad7, + 0x5a => VirtualKeyCode::F20, + 0x5b => VirtualKeyCode::Numpad8, + 0x5c => VirtualKeyCode::Numpad9, + 0x5d => VirtualKeyCode::Yen, + //0x5e => JIS Ro, + //0x5f => unkown, + 0x60 => VirtualKeyCode::F5, + 0x61 => VirtualKeyCode::F6, + 0x62 => VirtualKeyCode::F7, + 0x63 => VirtualKeyCode::F3, + 0x64 => VirtualKeyCode::F8, + 0x65 => VirtualKeyCode::F9, + //0x66 => JIS Eisuu (macOS), + 0x67 => VirtualKeyCode::F11, + //0x68 => JIS Kanna (macOS), + 0x69 => VirtualKeyCode::F13, + 0x6a => VirtualKeyCode::F16, + 0x6b => VirtualKeyCode::F14, + //0x6c => unkown, + 0x6d => VirtualKeyCode::F10, + //0x6e => unkown, + 0x6f => VirtualKeyCode::F12, + //0x70 => unkown, + 0x71 => VirtualKeyCode::F15, + 0x72 => VirtualKeyCode::Insert, + 0x73 => VirtualKeyCode::Home, + 0x74 => VirtualKeyCode::PageUp, + 0x75 => VirtualKeyCode::Delete, + 0x76 => VirtualKeyCode::F4, + 0x77 => VirtualKeyCode::End, + 0x78 => VirtualKeyCode::F2, + 0x79 => VirtualKeyCode::PageDown, + 0x7a => VirtualKeyCode::F1, + 0x7b => VirtualKeyCode::Left, + 0x7c => VirtualKeyCode::Right, + 0x7d => VirtualKeyCode::Down, + 0x7e => VirtualKeyCode::Up, + //0x7f => unkown, + 0xa => VirtualKeyCode::Caret, + _ => return None, + }) +} + +// While F1-F20 have scancodes we can match on, we have to check against UTF-16 +// constants for the rest. +// https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?preferredLanguage=occ +pub fn check_function_keys(string: &str) -> Option { + if let Some(ch) = string.encode_utf16().next() { + return Some(match ch { + 0xf718 => VirtualKeyCode::F21, + 0xf719 => VirtualKeyCode::F22, + 0xf71a => VirtualKeyCode::F23, + 0xf71b => VirtualKeyCode::F24, + _ => return None, + }); + } + + None +} + +pub fn event_mods(event: id) -> ModifiersState { + let flags = unsafe { NSEvent::modifierFlags(event) }; + let mut m = ModifiersState::empty(); + m.set( + ModifiersState::SHIFT, + flags.contains(NSEventModifierFlags::NSShiftKeyMask), + ); + m.set( + ModifiersState::CTRL, + flags.contains(NSEventModifierFlags::NSControlKeyMask), + ); + m.set( + ModifiersState::ALT, + flags.contains(NSEventModifierFlags::NSAlternateKeyMask), + ); + m.set( + ModifiersState::LOGO, + flags.contains(NSEventModifierFlags::NSCommandKeyMask), + ); + m +} + +pub fn get_scancode(event: cocoa::base::id) -> c_ushort { + // In AppKit, `keyCode` refers to the position (scancode) of a key rather than its character, + // and there is no easy way to navtively retrieve the layout-dependent character. + // In winit, we use keycode to refer to the key's character, and so this function aligns + // AppKit's terminology with ours. + unsafe { msg_send![event, keyCode] } +} + +pub unsafe fn modifier_event( + ns_event: id, + keymask: NSEventModifierFlags, + was_key_pressed: bool, +) -> Option> { + if !was_key_pressed && NSEvent::modifierFlags(ns_event).contains(keymask) + || was_key_pressed && !NSEvent::modifierFlags(ns_event).contains(keymask) + { + let state = if was_key_pressed { + ElementState::Released + } else { + ElementState::Pressed + }; + + let scancode = get_scancode(ns_event); + let virtual_keycode = scancode_to_keycode(scancode); + #[allow(deprecated)] + Some(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state, + scancode: scancode as _, + virtual_keycode, + modifiers: event_mods(ns_event), + }, + is_synthetic: false, + }) + } else { + None + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event_loop.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event_loop.rs new file mode 100644 index 0000000..cc3d392 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/event_loop.rs @@ -0,0 +1,158 @@ +use std::{ + collections::VecDeque, marker::PhantomData, mem, os::raw::c_void, process, ptr, rc::Rc, + sync::mpsc, +}; + +use cocoa::{ + appkit::NSApp, + base::{id, nil}, + foundation::NSAutoreleasePool, +}; + +use crate::{ + event::Event, + event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootWindowTarget}, + platform_impl::platform::{ + app::APP_CLASS, + app_delegate::APP_DELEGATE_CLASS, + app_state::AppState, + monitor::{self, MonitorHandle}, + observer::*, + util::IdRef, + }, +}; + +pub struct EventLoopWindowTarget { + pub sender: mpsc::Sender, // this is only here to be cloned elsewhere + pub receiver: mpsc::Receiver, +} + +impl Default for EventLoopWindowTarget { + fn default() -> Self { + let (sender, receiver) = mpsc::channel(); + EventLoopWindowTarget { sender, receiver } + } +} + +pub struct EventLoop { + window_target: Rc>, + _delegate: IdRef, +} + +impl EventLoop { + pub fn new() -> Self { + let delegate = unsafe { + if !msg_send![class!(NSThread), isMainThread] { + panic!("On macOS, `EventLoop` must be created on the main thread!"); + } + + // This must be done before `NSApp()` (equivalent to sending + // `sharedApplication`) is called anywhere else, or we'll end up + // with the wrong `NSApplication` class and the wrong thread could + // be marked as main. + let app: id = msg_send![APP_CLASS.0, sharedApplication]; + + let delegate = IdRef::new(msg_send![APP_DELEGATE_CLASS.0, new]); + let pool = NSAutoreleasePool::new(nil); + let _: () = msg_send![app, setDelegate:*delegate]; + let _: () = msg_send![pool, drain]; + delegate + }; + setup_control_flow_observers(); + EventLoop { + window_target: Rc::new(RootWindowTarget { + p: Default::default(), + _marker: PhantomData, + }), + _delegate: delegate, + } + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque { + monitor::available_monitors() + } + + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + monitor::primary_monitor() + } + + pub fn window_target(&self) -> &RootWindowTarget { + &self.window_target + } + + pub fn run(mut self, callback: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &RootWindowTarget, &mut ControlFlow), + { + self.run_return(callback); + process::exit(0); + } + + pub fn run_return(&mut self, callback: F) + where + F: FnMut(Event<'_, T>, &RootWindowTarget, &mut ControlFlow), + { + unsafe { + let pool = NSAutoreleasePool::new(nil); + let app = NSApp(); + assert_ne!(app, nil); + AppState::set_callback(callback, Rc::clone(&self.window_target)); + let _: () = msg_send![app, run]; + AppState::exit(); + pool.drain(); + } + } + + pub fn create_proxy(&self) -> Proxy { + Proxy::new(self.window_target.p.sender.clone()) + } +} + +pub struct Proxy { + sender: mpsc::Sender, + source: CFRunLoopSourceRef, +} + +unsafe impl Send for Proxy {} + +impl Clone for Proxy { + fn clone(&self) -> Self { + Proxy::new(self.sender.clone()) + } +} + +impl Proxy { + fn new(sender: mpsc::Sender) -> Self { + unsafe { + // just wake up the eventloop + extern "C" fn event_loop_proxy_handler(_: *mut c_void) {} + + // adding a Source to the main CFRunLoop lets us wake it up and + // process user events through the normal OS EventLoop mechanisms. + let rl = CFRunLoopGetMain(); + let mut context: CFRunLoopSourceContext = mem::zeroed(); + context.perform = Some(event_loop_proxy_handler); + let source = + CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::max_value() - 1, &mut context); + CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopWakeUp(rl); + + Proxy { sender, source } + } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.sender + .send(event) + .map_err(|mpsc::SendError(x)| EventLoopClosed(x))?; + unsafe { + // let the main thread know there's a new event + CFRunLoopSourceSignal(self.source); + let rl = CFRunLoopGetMain(); + CFRunLoopWakeUp(rl); + } + Ok(()) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/ffi.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/ffi.rs new file mode 100644 index 0000000..aec0fc9 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/ffi.rs @@ -0,0 +1,209 @@ +// TODO: Upstream these + +#![allow(dead_code, non_snake_case, non_upper_case_globals)] + +use cocoa::{ + base::id, + foundation::{NSInteger, NSUInteger}, +}; +use core_foundation::{ + array::CFArrayRef, dictionary::CFDictionaryRef, string::CFStringRef, uuid::CFUUIDRef, +}; +use core_graphics::{ + base::CGError, + display::{CGDirectDisplayID, CGDisplayConfigRef}, +}; +use objc; + +pub const NSNotFound: NSInteger = NSInteger::max_value(); + +#[repr(C)] +pub struct NSRange { + pub location: NSUInteger, + pub length: NSUInteger, +} + +impl NSRange { + #[inline] + pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { + NSRange { location, length } + } +} + +unsafe impl objc::Encode for NSRange { + fn encode() -> objc::Encoding { + let encoding = format!( + // TODO: Verify that this is correct + "{{NSRange={}{}}}", + NSUInteger::encode().as_str(), + NSUInteger::encode().as_str(), + ); + unsafe { objc::Encoding::from_str(&encoding) } + } +} + +pub trait NSMutableAttributedString: Sized { + unsafe fn alloc(_: Self) -> id { + msg_send![class!(NSMutableAttributedString), alloc] + } + + unsafe fn init(self) -> id; // *mut NSMutableAttributedString + unsafe fn initWithString(self, string: id) -> id; + unsafe fn initWithAttributedString(self, string: id) -> id; + + unsafe fn string(self) -> id; // *mut NSString + unsafe fn mutableString(self) -> id; // *mut NSMutableString + unsafe fn length(self) -> NSUInteger; +} + +impl NSMutableAttributedString for id { + unsafe fn init(self) -> id { + msg_send![self, init] + } + + unsafe fn initWithString(self, string: id) -> id { + msg_send![self, initWithString: string] + } + + unsafe fn initWithAttributedString(self, string: id) -> id { + msg_send![self, initWithAttributedString: string] + } + + unsafe fn string(self) -> id { + msg_send![self, string] + } + + unsafe fn mutableString(self) -> id { + msg_send![self, mutableString] + } + + unsafe fn length(self) -> NSUInteger { + msg_send![self, length] + } +} + +pub const kCGBaseWindowLevelKey: NSInteger = 0; +pub const kCGMinimumWindowLevelKey: NSInteger = 1; +pub const kCGDesktopWindowLevelKey: NSInteger = 2; +pub const kCGBackstopMenuLevelKey: NSInteger = 3; +pub const kCGNormalWindowLevelKey: NSInteger = 4; +pub const kCGFloatingWindowLevelKey: NSInteger = 5; +pub const kCGTornOffMenuWindowLevelKey: NSInteger = 6; +pub const kCGDockWindowLevelKey: NSInteger = 7; +pub const kCGMainMenuWindowLevelKey: NSInteger = 8; +pub const kCGStatusWindowLevelKey: NSInteger = 9; +pub const kCGModalPanelWindowLevelKey: NSInteger = 10; +pub const kCGPopUpMenuWindowLevelKey: NSInteger = 11; +pub const kCGDraggingWindowLevelKey: NSInteger = 12; +pub const kCGScreenSaverWindowLevelKey: NSInteger = 13; +pub const kCGMaximumWindowLevelKey: NSInteger = 14; +pub const kCGOverlayWindowLevelKey: NSInteger = 15; +pub const kCGHelpWindowLevelKey: NSInteger = 16; +pub const kCGUtilityWindowLevelKey: NSInteger = 17; +pub const kCGDesktopIconWindowLevelKey: NSInteger = 18; +pub const kCGCursorWindowLevelKey: NSInteger = 19; +pub const kCGNumberOfWindowLevelKeys: NSInteger = 20; + +#[derive(Debug, Clone, Copy)] +pub enum NSWindowLevel { + NSNormalWindowLevel = kCGBaseWindowLevelKey as _, + NSFloatingWindowLevel = kCGFloatingWindowLevelKey as _, + NSTornOffMenuWindowLevel = kCGTornOffMenuWindowLevelKey as _, + NSModalPanelWindowLevel = kCGModalPanelWindowLevelKey as _, + NSMainMenuWindowLevel = kCGMainMenuWindowLevelKey as _, + NSStatusWindowLevel = kCGStatusWindowLevelKey as _, + NSPopUpMenuWindowLevel = kCGPopUpMenuWindowLevelKey as _, + NSScreenSaverWindowLevel = kCGScreenSaverWindowLevelKey as _, +} + +pub type CGDisplayFadeInterval = f32; +pub type CGDisplayReservationInterval = f32; +pub type CGDisplayBlendFraction = f32; + +pub const kCGDisplayBlendNormal: f32 = 0.0; +pub const kCGDisplayBlendSolidColor: f32 = 1.0; + +pub type CGDisplayFadeReservationToken = u32; +pub const kCGDisplayFadeReservationInvalidToken: CGDisplayFadeReservationToken = 0; + +pub type Boolean = u8; +pub const FALSE: Boolean = 0; +pub const TRUE: Boolean = 1; + +pub const kCGErrorSuccess: i32 = 0; +pub const kCGErrorFailure: i32 = 1000; +pub const kCGErrorIllegalArgument: i32 = 1001; +pub const kCGErrorInvalidConnection: i32 = 1002; +pub const kCGErrorInvalidContext: i32 = 1003; +pub const kCGErrorCannotComplete: i32 = 1004; +pub const kCGErrorNotImplemented: i32 = 1006; +pub const kCGErrorRangeCheck: i32 = 1007; +pub const kCGErrorTypeCheck: i32 = 1008; +pub const kCGErrorInvalidOperation: i32 = 1010; +pub const kCGErrorNoneAvailable: i32 = 1011; + +pub const IO1BitIndexedPixels: &str = "P"; +pub const IO2BitIndexedPixels: &str = "PP"; +pub const IO4BitIndexedPixels: &str = "PPPP"; +pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; +pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; +pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; + +pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; +pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; + +pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; +pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; + +pub const IOYUV422Pixels: &str = "Y4U2V2"; +pub const IO8BitOverlayPixels: &str = "O8"; + +pub type CGWindowLevel = i32; +pub type CGDisplayModeRef = *mut libc::c_void; + +#[link(name = "CoreGraphics", kind = "framework")] +extern "C" { + pub fn CGRestorePermanentDisplayConfiguration(); + pub fn CGDisplayCapture(display: CGDirectDisplayID) -> CGError; + pub fn CGDisplayRelease(display: CGDirectDisplayID) -> CGError; + pub fn CGConfigureDisplayFadeEffect( + config: CGDisplayConfigRef, + fadeOutSeconds: CGDisplayFadeInterval, + fadeInSeconds: CGDisplayFadeInterval, + fadeRed: f32, + fadeGreen: f32, + fadeBlue: f32, + ) -> CGError; + pub fn CGAcquireDisplayFadeReservation( + seconds: CGDisplayReservationInterval, + token: *mut CGDisplayFadeReservationToken, + ) -> CGError; + pub fn CGDisplayFade( + token: CGDisplayFadeReservationToken, + duration: CGDisplayFadeInterval, + startBlend: CGDisplayBlendFraction, + endBlend: CGDisplayBlendFraction, + redBlend: f32, + greenBlend: f32, + blueBlend: f32, + synchronous: Boolean, + ) -> CGError; + pub fn CGReleaseDisplayFadeReservation(token: CGDisplayFadeReservationToken) -> CGError; + pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef; + pub fn CGShieldingWindowLevel() -> CGWindowLevel; + pub fn CGDisplaySetDisplayMode( + display: CGDirectDisplayID, + mode: CGDisplayModeRef, + options: CFDictionaryRef, + ) -> CGError; + pub fn CGDisplayCopyAllDisplayModes( + display: CGDirectDisplayID, + options: CFDictionaryRef, + ) -> CFArrayRef; + pub fn CGDisplayModeGetPixelWidth(mode: CGDisplayModeRef) -> usize; + pub fn CGDisplayModeGetPixelHeight(mode: CGDisplayModeRef) -> usize; + pub fn CGDisplayModeGetRefreshRate(mode: CGDisplayModeRef) -> f64; + pub fn CGDisplayModeCopyPixelEncoding(mode: CGDisplayModeRef) -> CFStringRef; + pub fn CGDisplayModeRetain(mode: CGDisplayModeRef); + pub fn CGDisplayModeRelease(mode: CGDisplayModeRef); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/mod.rs new file mode 100644 index 0000000..72b8e0a --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/mod.rs @@ -0,0 +1,83 @@ +#![cfg(target_os = "macos")] + +mod activation_hack; +mod app; +mod app_delegate; +mod app_state; +mod event; +mod event_loop; +mod ffi; +mod monitor; +mod observer; +mod util; +mod view; +mod window; +mod window_delegate; + +use std::{fmt, ops::Deref, sync::Arc}; + +pub use self::{ + event_loop::{EventLoop, EventLoopWindowTarget, Proxy as EventLoopProxy}, + monitor::{MonitorHandle, VideoMode}, + window::{Id as WindowId, PlatformSpecificWindowBuilderAttributes, UnownedWindow}, +}; +use crate::{ + error::OsError as RootOsError, event::DeviceId as RootDeviceId, window::WindowAttributes, +}; + +pub(crate) use crate::icon::NoIcon as PlatformIcon; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId; + +impl DeviceId { + pub unsafe fn dummy() -> Self { + DeviceId + } +} + +// Constant device ID; to be removed when if backend is updated to report real device IDs. +pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId); + +pub struct Window { + window: Arc, + // We keep this around so that it doesn't get dropped until the window does. + _delegate: util::IdRef, +} + +#[derive(Debug)] +pub enum OsError { + CGError(core_graphics::base::CGError), + CreationError(&'static str), +} + +unsafe impl Send for Window {} +unsafe impl Sync for Window {} + +impl Deref for Window { + type Target = UnownedWindow; + #[inline] + fn deref(&self) -> &Self::Target { + &*self.window + } +} + +impl Window { + pub fn new( + _window_target: &EventLoopWindowTarget, + attributes: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + let (window, _delegate) = UnownedWindow::new(attributes, pl_attribs)?; + Ok(Window { window, _delegate }) + } +} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OsError::CGError(e) => f.pad(&format!("CGError {}", e)), + OsError::CreationError(e) => f.pad(e), + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/monitor.rs new file mode 100644 index 0000000..817d38e --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/monitor.rs @@ -0,0 +1,322 @@ +use std::{collections::VecDeque, fmt}; + +use super::{ffi, util}; +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, +}; +use cocoa::{ + appkit::NSScreen, + base::{id, nil}, + foundation::NSUInteger, +}; +use core_foundation::{ + array::{CFArrayGetCount, CFArrayGetValueAtIndex}, + base::{CFRelease, TCFType}, + string::CFString, +}; +use core_graphics::display::{CGDirectDisplayID, CGDisplay, CGDisplayBounds}; +use core_video_sys::{ + kCVReturnSuccess, kCVTimeIsIndefinite, CVDisplayLinkCreateWithCGDisplay, + CVDisplayLinkGetNominalOutputVideoRefreshPeriod, CVDisplayLinkRelease, +}; + +#[derive(Clone)] +pub struct VideoMode { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate: u16, + pub(crate) monitor: MonitorHandle, + pub(crate) native_mode: NativeDisplayMode, +} + +impl PartialEq for VideoMode { + fn eq(&self, other: &Self) -> bool { + self.size == other.size + && self.bit_depth == other.bit_depth + && self.refresh_rate == other.refresh_rate + && self.monitor == other.monitor + } +} + +impl Eq for VideoMode {} + +impl std::hash::Hash for VideoMode { + fn hash(&self, state: &mut H) { + self.size.hash(state); + self.bit_depth.hash(state); + self.refresh_rate.hash(state); + self.monitor.hash(state); + } +} + +impl std::fmt::Debug for VideoMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoMode") + .field("size", &self.size) + .field("bit_depth", &self.bit_depth) + .field("refresh_rate", &self.refresh_rate) + .field("monitor", &self.monitor) + .finish() + } +} + +pub struct NativeDisplayMode(pub ffi::CGDisplayModeRef); + +unsafe impl Send for NativeDisplayMode {} + +impl Drop for NativeDisplayMode { + fn drop(&mut self) { + unsafe { + ffi::CGDisplayModeRelease(self.0); + } + } +} + +impl Clone for NativeDisplayMode { + fn clone(&self) -> Self { + unsafe { + ffi::CGDisplayModeRetain(self.0); + } + NativeDisplayMode(self.0) + } +} + +impl VideoMode { + pub fn size(&self) -> PhysicalSize { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate(&self) -> u16 { + self.refresh_rate + } + + pub fn monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: self.monitor.clone(), + } + } +} + +#[derive(Clone)] +pub struct MonitorHandle(CGDirectDisplayID); + +// `CGDirectDisplayID` changes on video mode change, so we cannot rely on that +// for comparisons, but we can use `CGDisplayCreateUUIDFromDisplayID` to get an +// unique identifier that persists even across system reboots +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + unsafe { + ffi::CGDisplayCreateUUIDFromDisplayID(self.0) + == ffi::CGDisplayCreateUUIDFromDisplayID(other.0) + } + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(&other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + unsafe { + ffi::CGDisplayCreateUUIDFromDisplayID(self.0) + .cmp(&ffi::CGDisplayCreateUUIDFromDisplayID(other.0)) + } + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash(&self, state: &mut H) { + unsafe { + ffi::CGDisplayCreateUUIDFromDisplayID(self.0).hash(state); + } + } +} + +pub fn available_monitors() -> VecDeque { + if let Ok(displays) = CGDisplay::active_displays() { + let mut monitors = VecDeque::with_capacity(displays.len()); + for display in displays { + monitors.push_back(MonitorHandle(display)); + } + monitors + } else { + VecDeque::with_capacity(0) + } +} + +pub fn primary_monitor() -> MonitorHandle { + MonitorHandle(CGDisplay::main().id) +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // TODO: Do this using the proper fmt API + #[derive(Debug)] + struct MonitorHandle { + name: Option, + native_identifier: u32, + size: PhysicalSize, + position: PhysicalPosition, + scale_factor: f64, + } + + let monitor_id_proxy = MonitorHandle { + name: self.name(), + native_identifier: self.native_identifier(), + size: self.size(), + position: self.position(), + scale_factor: self.scale_factor(), + }; + + monitor_id_proxy.fmt(f) + } +} + +impl MonitorHandle { + pub fn new(id: CGDirectDisplayID) -> Self { + MonitorHandle(id) + } + + pub fn name(&self) -> Option { + let MonitorHandle(display_id) = *self; + let screen_num = CGDisplay::new(display_id).model_number(); + Some(format!("Monitor #{}", screen_num)) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + self.0 + } + + pub fn size(&self) -> PhysicalSize { + let MonitorHandle(display_id) = *self; + let display = CGDisplay::new(display_id); + let height = display.pixels_high(); + let width = display.pixels_wide(); + PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.scale_factor()) + } + + #[inline] + pub fn position(&self) -> PhysicalPosition { + let bounds = unsafe { CGDisplayBounds(self.native_identifier()) }; + PhysicalPosition::from_logical::<_, f64>( + (bounds.origin.x as f64, bounds.origin.y as f64), + self.scale_factor(), + ) + } + + pub fn scale_factor(&self) -> f64 { + let screen = match self.ns_screen() { + Some(screen) => screen, + None => return 1.0, // default to 1.0 when we can't find the screen + }; + unsafe { NSScreen::backingScaleFactor(screen) as f64 } + } + + pub fn video_modes(&self) -> impl Iterator { + let cv_refresh_rate = unsafe { + let mut display_link = std::ptr::null_mut(); + assert_eq!( + CVDisplayLinkCreateWithCGDisplay(self.0, &mut display_link), + kCVReturnSuccess + ); + let time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link); + CVDisplayLinkRelease(display_link); + + // This value is indefinite if an invalid display link was specified + assert!(time.flags & kCVTimeIsIndefinite == 0); + + time.timeScale as i64 / time.timeValue + }; + + let monitor = self.clone(); + + unsafe { + let modes = { + let array = ffi::CGDisplayCopyAllDisplayModes(self.0, std::ptr::null()); + assert!(!array.is_null(), "failed to get list of display modes"); + let array_count = CFArrayGetCount(array); + let modes: Vec<_> = (0..array_count) + .map(move |i| { + let mode = CFArrayGetValueAtIndex(array, i) as *mut _; + ffi::CGDisplayModeRetain(mode); + mode + }) + .collect(); + CFRelease(array as *const _); + modes + }; + + modes.into_iter().map(move |mode| { + let cg_refresh_rate = ffi::CGDisplayModeGetRefreshRate(mode).round() as i64; + + // CGDisplayModeGetRefreshRate returns 0.0 for any display that + // isn't a CRT + let refresh_rate = if cg_refresh_rate > 0 { + cg_refresh_rate + } else { + cv_refresh_rate + }; + + let pixel_encoding = + CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode)) + .to_string(); + let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) { + 32 + } else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) { + 16 + } else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) { + 30 + } else { + unimplemented!() + }; + + let video_mode = VideoMode { + size: ( + ffi::CGDisplayModeGetPixelWidth(mode) as u32, + ffi::CGDisplayModeGetPixelHeight(mode) as u32, + ), + refresh_rate: refresh_rate as u16, + bit_depth, + monitor: monitor.clone(), + native_mode: NativeDisplayMode(mode), + }; + + RootVideoMode { video_mode } + }) + } + } + + pub(crate) fn ns_screen(&self) -> Option { + unsafe { + let uuid = ffi::CGDisplayCreateUUIDFromDisplayID(self.0); + let screens = NSScreen::screens(nil); + let count: NSUInteger = msg_send![screens, count]; + let key = util::ns_string_id_ref("NSScreenNumber"); + for i in 0..count { + let screen = msg_send![screens, objectAtIndex: i as NSUInteger]; + let device_description = NSScreen::deviceDescription(screen); + let value: id = msg_send![device_description, objectForKey:*key]; + if value != nil { + let other_native_id: NSUInteger = msg_send![value, unsignedIntegerValue]; + let other_uuid = + ffi::CGDisplayCreateUUIDFromDisplayID(other_native_id as CGDirectDisplayID); + if uuid == other_uuid { + return Some(screen); + } + } + } + None + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/observer.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/observer.rs new file mode 100644 index 0000000..aa7f536 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/observer.rs @@ -0,0 +1,242 @@ +use std::{self, os::raw::*, ptr, time::Instant}; + +use crate::platform_impl::platform::{app_state::AppState, ffi}; + +#[link(name = "CoreFoundation", kind = "framework")] +extern "C" { + pub static kCFRunLoopCommonModes: CFRunLoopMode; + + pub fn CFRunLoopGetMain() -> CFRunLoopRef; + pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); + + pub fn CFRunLoopObserverCreate( + allocator: CFAllocatorRef, + activities: CFOptionFlags, + repeats: ffi::Boolean, + order: CFIndex, + callout: CFRunLoopObserverCallBack, + context: *mut CFRunLoopObserverContext, + ) -> CFRunLoopObserverRef; + pub fn CFRunLoopAddObserver( + rl: CFRunLoopRef, + observer: CFRunLoopObserverRef, + mode: CFRunLoopMode, + ); + + pub fn CFRunLoopTimerCreate( + allocator: CFAllocatorRef, + fireDate: CFAbsoluteTime, + interval: CFTimeInterval, + flags: CFOptionFlags, + order: CFIndex, + callout: CFRunLoopTimerCallBack, + context: *mut CFRunLoopTimerContext, + ) -> CFRunLoopTimerRef; + pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFRunLoopMode); + pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); + pub fn CFRunLoopTimerInvalidate(time: CFRunLoopTimerRef); + + pub fn CFRunLoopSourceCreate( + allocator: CFAllocatorRef, + order: CFIndex, + context: *mut CFRunLoopSourceContext, + ) -> CFRunLoopSourceRef; + pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFRunLoopMode); + #[allow(dead_code)] + pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); + pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); + + pub fn CFAbsoluteTimeGetCurrent() -> CFAbsoluteTime; + pub fn CFRelease(cftype: *const c_void); +} + +pub enum CFAllocator {} +pub type CFAllocatorRef = *mut CFAllocator; +pub enum CFRunLoop {} +pub type CFRunLoopRef = *mut CFRunLoop; +pub type CFRunLoopMode = CFStringRef; +pub enum CFRunLoopObserver {} +pub type CFRunLoopObserverRef = *mut CFRunLoopObserver; +pub enum CFRunLoopTimer {} +pub type CFRunLoopTimerRef = *mut CFRunLoopTimer; +pub enum CFRunLoopSource {} +pub type CFRunLoopSourceRef = *mut CFRunLoopSource; +pub enum CFString {} +pub type CFStringRef = *const CFString; + +pub type CFHashCode = c_ulong; +pub type CFIndex = c_long; +pub type CFOptionFlags = c_ulong; +pub type CFRunLoopActivity = CFOptionFlags; + +pub type CFAbsoluteTime = CFTimeInterval; +pub type CFTimeInterval = f64; + +#[allow(non_upper_case_globals)] +pub const kCFRunLoopEntry: CFRunLoopActivity = 0; +#[allow(non_upper_case_globals)] +pub const kCFRunLoopBeforeWaiting: CFRunLoopActivity = 1 << 5; +#[allow(non_upper_case_globals)] +pub const kCFRunLoopAfterWaiting: CFRunLoopActivity = 1 << 6; +#[allow(non_upper_case_globals)] +pub const kCFRunLoopExit: CFRunLoopActivity = 1 << 7; + +pub type CFRunLoopObserverCallBack = + extern "C" fn(observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); +pub type CFRunLoopTimerCallBack = extern "C" fn(timer: CFRunLoopTimerRef, info: *mut c_void); + +pub enum CFRunLoopObserverContext {} +pub enum CFRunLoopTimerContext {} + +#[allow(non_snake_case)] +#[repr(C)] +pub struct CFRunLoopSourceContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, + pub equal: Option ffi::Boolean>, + pub hash: Option CFHashCode>, + pub schedule: Option, + pub cancel: Option, + pub perform: Option, +} + +// begin is queued with the highest priority to ensure it is processed before other observers +extern "C" fn control_flow_begin_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, +) { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopAfterWaiting => { + //trace!("Triggered `CFRunLoopAfterWaiting`"); + AppState::wakeup(); + //trace!("Completed `CFRunLoopAfterWaiting`"); + } + kCFRunLoopEntry => unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } +} + +// end is queued with the lowest priority to ensure it is processed after other observers +// without that, LoopDestroyed would get sent after MainEventsCleared +extern "C" fn control_flow_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, +) { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => { + //trace!("Triggered `CFRunLoopBeforeWaiting`"); + AppState::cleared(); + //trace!("Completed `CFRunLoopBeforeWaiting`"); + } + kCFRunLoopExit => (), //unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } +} + +struct RunLoop(CFRunLoopRef); + +impl RunLoop { + unsafe fn get() -> Self { + RunLoop(CFRunLoopGetMain()) + } + + unsafe fn add_observer( + &self, + flags: CFOptionFlags, + priority: CFIndex, + handler: CFRunLoopObserverCallBack, + ) { + let observer = CFRunLoopObserverCreate( + ptr::null_mut(), + flags, + ffi::TRUE, // Indicates we want this to run repeatedly + priority, // The lower the value, the sooner this will run + handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes); + } +} + +pub fn setup_control_flow_observers() { + unsafe { + let run_loop = RunLoop::get(); + run_loop.add_observer( + kCFRunLoopEntry | kCFRunLoopAfterWaiting, + CFIndex::min_value(), + control_flow_begin_handler, + ); + run_loop.add_observer( + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + CFIndex::max_value(), + control_flow_end_handler, + ); + } +} + +pub struct EventLoopWaker { + timer: CFRunLoopTimerRef, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + unsafe { + CFRunLoopTimerInvalidate(self.timer); + CFRelease(self.timer as _); + } + } +} + +impl Default for EventLoopWaker { + fn default() -> EventLoopWaker { + extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimerCreate( + ptr::null_mut(), + std::f64::MAX, + 0.000_000_1, + 0, + 0, + wakeup_main_loop, + ptr::null_mut(), + ); + CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes); + EventLoopWaker { timer } + } + } +} + +impl EventLoopWaker { + pub fn stop(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) } + } + + pub fn start(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) } + } + + pub fn start_at(&mut self, instant: Instant) { + let now = Instant::now(); + if now >= instant { + self.start(); + } else { + unsafe { + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = + duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; + CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) + } + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/async.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/async.rs new file mode 100644 index 0000000..977ba32 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/async.rs @@ -0,0 +1,216 @@ +use std::{ + ops::Deref, + sync::{Mutex, Weak}, +}; + +use cocoa::{ + appkit::{CGFloat, NSScreen, NSWindow, NSWindowStyleMask}, + base::{id, nil}, + foundation::{NSPoint, NSSize, NSString}, +}; +use dispatch::Queue; +use objc::rc::autoreleasepool; + +use crate::{ + dpi::LogicalSize, + platform_impl::platform::{ffi, util::IdRef, window::SharedState}, +}; + +// Unsafe wrapper type that allows us to dispatch things that aren't Send. +// This should *only* be used to dispatch to the main queue. +// While it is indeed not guaranteed that these types can safely be sent to +// other threads, we know that they're safe to use on the main thread. +struct MainThreadSafe(T); + +unsafe impl Send for MainThreadSafe {} + +impl Deref for MainThreadSafe { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +unsafe fn set_style_mask(ns_window: id, ns_view: id, mask: NSWindowStyleMask) { + ns_window.setStyleMask_(mask); + // If we don't do this, key handling will break + // (at least until the window is clicked again/etc.) + ns_window.makeFirstResponder_(ns_view); +} + +// Always use this function instead of trying to modify `styleMask` directly! +// `setStyleMask:` isn't thread-safe, so we have to use Grand Central Dispatch. +// Otherwise, this would vomit out errors about not being on the main thread +// and fail to do anything. +pub unsafe fn set_style_mask_async(ns_window: id, ns_view: id, mask: NSWindowStyleMask) { + let ns_window = MainThreadSafe(ns_window); + let ns_view = MainThreadSafe(ns_view); + Queue::main().exec_async(move || { + set_style_mask(*ns_window, *ns_view, mask); + }); +} +pub unsafe fn set_style_mask_sync(ns_window: id, ns_view: id, mask: NSWindowStyleMask) { + if msg_send![class!(NSThread), isMainThread] { + set_style_mask(ns_window, ns_view, mask); + } else { + let ns_window = MainThreadSafe(ns_window); + let ns_view = MainThreadSafe(ns_view); + Queue::main().exec_sync(move || { + set_style_mask(*ns_window, *ns_view, mask); + }) + } +} + +// `setContentSize:` isn't thread-safe either, though it doesn't log any errors +// and just fails silently. Anyway, GCD to the rescue! +pub unsafe fn set_content_size_async(ns_window: id, size: LogicalSize) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + ns_window.setContentSize_(NSSize::new(size.width as CGFloat, size.height as CGFloat)); + }); +} + +// `setFrameTopLeftPoint:` isn't thread-safe, but fortunately has the courtesy +// to log errors. +pub unsafe fn set_frame_top_left_point_async(ns_window: id, point: NSPoint) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + ns_window.setFrameTopLeftPoint_(point); + }); +} + +// `setFrameTopLeftPoint:` isn't thread-safe, and fails silently. +pub unsafe fn set_level_async(ns_window: id, level: ffi::NSWindowLevel) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + ns_window.setLevel_(level as _); + }); +} + +// `toggleFullScreen` is thread-safe, but our additional logic to account for +// window styles isn't. +pub unsafe fn toggle_full_screen_async( + ns_window: id, + ns_view: id, + not_fullscreen: bool, + shared_state: Weak>, +) { + let ns_window = MainThreadSafe(ns_window); + let ns_view = MainThreadSafe(ns_view); + let shared_state = MainThreadSafe(shared_state); + Queue::main().exec_async(move || { + // `toggleFullScreen` doesn't work if the `StyleMask` is none, so we + // set a normal style temporarily. The previous state will be + // restored in `WindowDelegate::window_did_exit_fullscreen`. + if not_fullscreen { + let curr_mask = ns_window.styleMask(); + let required = + NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; + if !curr_mask.contains(required) { + set_style_mask(*ns_window, *ns_view, required); + if let Some(shared_state) = shared_state.upgrade() { + trace!("Locked shared state in `toggle_full_screen_callback`"); + let mut shared_state_lock = shared_state.lock().unwrap(); + (*shared_state_lock).saved_style = Some(curr_mask); + trace!("Unlocked shared state in `toggle_full_screen_callback`"); + } + } + } + // Window level must be restored from `CGShieldingWindowLevel() + // + 1` back to normal in order for `toggleFullScreen` to do + // anything + ns_window.setLevel_(0); + ns_window.toggleFullScreen_(nil); + }); +} + +pub unsafe fn restore_display_mode_async(ns_screen: u32) { + Queue::main().exec_async(move || { + ffi::CGRestorePermanentDisplayConfiguration(); + assert_eq!(ffi::CGDisplayRelease(ns_screen), ffi::kCGErrorSuccess); + }); +} + +// `setMaximized` is not thread-safe +pub unsafe fn set_maximized_async( + ns_window: id, + is_zoomed: bool, + maximized: bool, + shared_state: Weak>, +) { + let ns_window = MainThreadSafe(ns_window); + let shared_state = MainThreadSafe(shared_state); + Queue::main().exec_async(move || { + if let Some(shared_state) = shared_state.upgrade() { + trace!("Locked shared state in `set_maximized`"); + let mut shared_state_lock = shared_state.lock().unwrap(); + + // Save the standard frame sized if it is not zoomed + if !is_zoomed { + shared_state_lock.standard_frame = Some(NSWindow::frame(*ns_window)); + } + + shared_state_lock.maximized = maximized; + + let curr_mask = ns_window.styleMask(); + if shared_state_lock.fullscreen.is_some() { + // Handle it in window_did_exit_fullscreen + return; + } else if curr_mask.contains(NSWindowStyleMask::NSResizableWindowMask) { + // Just use the native zoom if resizable + ns_window.zoom_(nil); + } else { + // if it's not resizable, we set the frame directly + let new_rect = if maximized { + let screen = NSScreen::mainScreen(nil); + NSScreen::visibleFrame(screen) + } else { + shared_state_lock.saved_standard_frame() + }; + ns_window.setFrame_display_(new_rect, 0); + } + + trace!("Unlocked shared state in `set_maximized`"); + } + }); +} + +// `orderOut:` isn't thread-safe. Calling it from another thread actually works, +// but with an odd delay. +pub unsafe fn order_out_async(ns_window: id) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + ns_window.orderOut_(nil); + }); +} + +// `makeKeyAndOrderFront:` isn't thread-safe. Calling it from another thread +// actually works, but with an odd delay. +pub unsafe fn make_key_and_order_front_async(ns_window: id) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + ns_window.makeKeyAndOrderFront_(nil); + }); +} + +// `setTitle:` isn't thread-safe. Calling it from another thread invalidates the +// window drag regions, which throws an exception when not done in the main +// thread +pub unsafe fn set_title_async(ns_window: id, title: String) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + let title = IdRef::new(NSString::alloc(nil).init_str(&title)); + ns_window.setTitle_(*title); + }); +} + +// `close:` is thread-safe, but we want the event to be triggered from the main +// thread. Though, it's a good idea to look into that more... +pub unsafe fn close_async(ns_window: id) { + let ns_window = MainThreadSafe(ns_window); + Queue::main().exec_async(move || { + autoreleasepool(move || { + ns_window.close(); + }); + }); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/cursor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/cursor.rs new file mode 100644 index 0000000..5c4d153 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/cursor.rs @@ -0,0 +1,164 @@ +use cocoa::{ + appkit::NSImage, + base::{id, nil}, + foundation::{NSDictionary, NSPoint, NSString}, +}; +use objc::{runtime::Sel, runtime::NO}; +use std::cell::RefCell; + +use crate::window::CursorIcon; + +pub enum Cursor { + Native(&'static str), + Undocumented(&'static str), + WebKit(&'static str), +} + +impl From for Cursor { + fn from(cursor: CursorIcon) -> Self { + // See native cursors at https://developer.apple.com/documentation/appkit/nscursor?language=objc. + match cursor { + CursorIcon::Arrow | CursorIcon::Default => Cursor::Native("arrowCursor"), + CursorIcon::Hand => Cursor::Native("pointingHandCursor"), + CursorIcon::Grab => Cursor::Native("openHandCursor"), + CursorIcon::Grabbing => Cursor::Native("closedHandCursor"), + CursorIcon::Text => Cursor::Native("IBeamCursor"), + CursorIcon::VerticalText => Cursor::Native("IBeamCursorForVerticalLayout"), + CursorIcon::Copy => Cursor::Native("dragCopyCursor"), + CursorIcon::Alias => Cursor::Native("dragLinkCursor"), + CursorIcon::NotAllowed | CursorIcon::NoDrop => { + Cursor::Native("operationNotAllowedCursor") + } + CursorIcon::ContextMenu => Cursor::Native("contextualMenuCursor"), + CursorIcon::Crosshair => Cursor::Native("crosshairCursor"), + CursorIcon::EResize => Cursor::Native("resizeRightCursor"), + CursorIcon::NResize => Cursor::Native("resizeUpCursor"), + CursorIcon::WResize => Cursor::Native("resizeLeftCursor"), + CursorIcon::SResize => Cursor::Native("resizeDownCursor"), + CursorIcon::EwResize | CursorIcon::ColResize => Cursor::Native("resizeLeftRightCursor"), + CursorIcon::NsResize | CursorIcon::RowResize => Cursor::Native("resizeUpDownCursor"), + + // Undocumented cursors: https://stackoverflow.com/a/46635398/5435443 + CursorIcon::Help => Cursor::Undocumented("_helpCursor"), + CursorIcon::ZoomIn => Cursor::Undocumented("_zoomInCursor"), + CursorIcon::ZoomOut => Cursor::Undocumented("_zoomOutCursor"), + CursorIcon::NeResize => Cursor::Undocumented("_windowResizeNorthEastCursor"), + CursorIcon::NwResize => Cursor::Undocumented("_windowResizeNorthWestCursor"), + CursorIcon::SeResize => Cursor::Undocumented("_windowResizeSouthEastCursor"), + CursorIcon::SwResize => Cursor::Undocumented("_windowResizeSouthWestCursor"), + CursorIcon::NeswResize => Cursor::Undocumented("_windowResizeNorthEastSouthWestCursor"), + CursorIcon::NwseResize => Cursor::Undocumented("_windowResizeNorthWestSouthEastCursor"), + + // While these are available, the former just loads a white arrow, + // and the latter loads an ugly deflated beachball! + // CursorIcon::Move => Cursor::Undocumented("_moveCursor"), + // CursorIcon::Wait => Cursor::Undocumented("_waitCursor"), + + // An even more undocumented cursor... + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=522349 + // This is the wrong semantics for `Wait`, but it's the same as + // what's used in Safari and Chrome. + CursorIcon::Wait | CursorIcon::Progress => { + Cursor::Undocumented("busyButClickableCursor") + } + + // For the rest, we can just snatch the cursors from WebKit... + // They fit the style of the native cursors, and will seem + // completely standard to macOS users. + // https://stackoverflow.com/a/21786835/5435443 + CursorIcon::Move | CursorIcon::AllScroll => Cursor::WebKit("move"), + CursorIcon::Cell => Cursor::WebKit("cell"), + } + } +} + +impl Default for Cursor { + fn default() -> Self { + Cursor::Native("arrowCursor") + } +} + +impl Cursor { + pub unsafe fn load(&self) -> id { + match self { + Cursor::Native(cursor_name) => { + let sel = Sel::register(cursor_name); + msg_send![class!(NSCursor), performSelector: sel] + } + Cursor::Undocumented(cursor_name) => { + let class = class!(NSCursor); + let sel = Sel::register(cursor_name); + let sel = if msg_send![class, respondsToSelector: sel] { + sel + } else { + warn!("Cursor `{}` appears to be invalid", cursor_name); + sel!(arrowCursor) + }; + msg_send![class, performSelector: sel] + } + Cursor::WebKit(cursor_name) => load_webkit_cursor(cursor_name), + } + } +} + +// Note that loading `busybutclickable` with this code won't animate the frames; +// instead you'll just get them all in a column. +pub unsafe fn load_webkit_cursor(cursor_name: &str) -> id { + static CURSOR_ROOT: &'static str = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors"; + let cursor_root = NSString::alloc(nil).init_str(CURSOR_ROOT); + let cursor_name = NSString::alloc(nil).init_str(cursor_name); + let cursor_pdf = NSString::alloc(nil).init_str("cursor.pdf"); + let cursor_plist = NSString::alloc(nil).init_str("info.plist"); + let key_x = NSString::alloc(nil).init_str("hotx"); + let key_y = NSString::alloc(nil).init_str("hoty"); + + let cursor_path: id = msg_send![cursor_root, stringByAppendingPathComponent: cursor_name]; + let pdf_path: id = msg_send![cursor_path, stringByAppendingPathComponent: cursor_pdf]; + let info_path: id = msg_send![cursor_path, stringByAppendingPathComponent: cursor_plist]; + + let image = NSImage::alloc(nil).initByReferencingFile_(pdf_path); + let info = NSDictionary::dictionaryWithContentsOfFile_(nil, info_path); + let x = info.valueForKey_(key_x); + let y = info.valueForKey_(key_y); + let point = NSPoint::new(msg_send![x, doubleValue], msg_send![y, doubleValue]); + let cursor: id = msg_send![class!(NSCursor), alloc]; + msg_send![cursor, + initWithImage:image + hotSpot:point + ] +} + +pub unsafe fn invisible_cursor() -> id { + // 16x16 GIF data for invisible cursor + // You can reproduce this via ImageMagick. + // $ convert -size 16x16 xc:none cursor.gif + static CURSOR_BYTES: &[u8] = &[ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x21, 0xF9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0E, 0x84, 0x8F, 0xA9, 0xCB, 0xED, 0x0F, + 0xA3, 0x9C, 0xB4, 0xDA, 0x8B, 0xB3, 0x3E, 0x05, 0x00, 0x3B, + ]; + + thread_local! { + // We can't initialize this at startup. + static CURSOR_OBJECT: RefCell = RefCell::new(nil); + } + + CURSOR_OBJECT.with(|cursor_obj| { + if *cursor_obj.borrow() == nil { + // Create a cursor from `CURSOR_BYTES` + let cursor_data: id = msg_send![class!(NSData), + dataWithBytesNoCopy:CURSOR_BYTES as *const [u8] + length:CURSOR_BYTES.len() + freeWhenDone:NO + ]; + + let ns_image: id = msg_send![class!(NSImage), alloc]; + let _: id = msg_send![ns_image, initWithData: cursor_data]; + let cursor: id = msg_send![class!(NSCursor), alloc]; + *cursor_obj.borrow_mut() = + msg_send![cursor, initWithImage:ns_image hotSpot: NSPoint::new(0.0, 0.0)]; + } + *cursor_obj.borrow() + }) +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/mod.rs new file mode 100644 index 0000000..39a97c9 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/util/mod.rs @@ -0,0 +1,142 @@ +mod r#async; +mod cursor; + +pub use self::{cursor::*, r#async::*}; + +use std::ops::{BitAnd, Deref}; + +use cocoa::{ + appkit::{NSApp, NSWindowStyleMask}, + base::{id, nil}, + foundation::{NSAutoreleasePool, NSRect, NSString, NSUInteger}, +}; +use core_graphics::display::CGDisplay; +use objc::runtime::{Class, Object, Sel, BOOL, YES}; + +use crate::platform_impl::platform::ffi; + +// Replace with `!` once stable +#[derive(Debug)] +pub enum Never {} + +pub fn has_flag(bitset: T, flag: T) -> bool +where + T: Copy + PartialEq + BitAnd, +{ + bitset & flag == flag +} + +pub const EMPTY_RANGE: ffi::NSRange = ffi::NSRange { + location: ffi::NSNotFound as NSUInteger, + length: 0, +}; + +#[derive(Debug, PartialEq)] +pub struct IdRef(id); + +impl IdRef { + pub fn new(inner: id) -> IdRef { + IdRef(inner) + } + + #[allow(dead_code)] + pub fn retain(inner: id) -> IdRef { + if inner != nil { + let () = unsafe { msg_send![inner, retain] }; + } + IdRef(inner) + } + + pub fn non_nil(self) -> Option { + if self.0 == nil { + None + } else { + Some(self) + } + } +} + +impl Drop for IdRef { + fn drop(&mut self) { + if self.0 != nil { + unsafe { + let pool = NSAutoreleasePool::new(nil); + let () = msg_send![self.0, release]; + pool.drain(); + }; + } + } +} + +impl Deref for IdRef { + type Target = id; + fn deref<'a>(&'a self) -> &'a id { + &self.0 + } +} + +impl Clone for IdRef { + fn clone(&self) -> IdRef { + if self.0 != nil { + let _: id = unsafe { msg_send![self.0, retain] }; + } + IdRef(self.0) + } +} + +// For consistency with other platforms, this will... +// 1. translate the bottom-left window corner into the top-left window corner +// 2. translate the coordinate from a bottom-left origin coordinate system to a top-left one +pub fn bottom_left_to_top_left(rect: NSRect) -> f64 { + CGDisplay::main().pixels_high() as f64 - (rect.origin.y + rect.size.height) +} + +pub unsafe fn ns_string_id_ref(s: &str) -> IdRef { + IdRef::new(NSString::alloc(nil).init_str(s)) +} + +pub unsafe fn app_name() -> Option { + let bundle: id = msg_send![class!(NSBundle), mainBundle]; + let dict: id = msg_send![bundle, infoDictionary]; + let key = ns_string_id_ref("CFBundleName"); + let app_name: id = msg_send![dict, objectForKey:*key]; + if app_name != nil { + Some(app_name) + } else { + None + } +} + +pub unsafe fn superclass<'a>(this: &'a Object) -> &'a Class { + let superclass: id = msg_send![this, superclass]; + &*(superclass as *const _) +} + +pub unsafe fn create_input_context(view: id) -> IdRef { + let input_context: id = msg_send![class!(NSTextInputContext), alloc]; + let input_context: id = msg_send![input_context, initWithClient: view]; + IdRef::new(input_context) +} + +#[allow(dead_code)] +pub unsafe fn open_emoji_picker() { + let () = msg_send![NSApp(), orderFrontCharacterPalette: nil]; +} + +pub extern "C" fn yes(_: &Object, _: Sel) -> BOOL { + YES +} + +pub unsafe fn toggle_style_mask(window: id, view: id, mask: NSWindowStyleMask, on: bool) { + use cocoa::appkit::NSWindow; + + let current_style_mask = window.styleMask(); + if on { + window.setStyleMask_(current_style_mask | mask); + } else { + window.setStyleMask_(current_style_mask & (!mask)); + } + + // If we don't do this, key handling will break. Therefore, never call `setStyleMask` directly! + window.makeFirstResponder_(view); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/view.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/view.rs new file mode 100644 index 0000000..839a2bc --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/view.rs @@ -0,0 +1,1060 @@ +use std::{ + boxed::Box, + collections::VecDeque, + os::raw::*, + slice, str, + sync::{Arc, Mutex, Weak}, +}; + +use cocoa::{ + appkit::{NSApp, NSEvent, NSEventModifierFlags, NSEventPhase, NSView, NSWindow}, + base::{id, nil}, + foundation::{NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger}, +}; +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES}, +}; + +use crate::{ + dpi::LogicalPosition, + event::{ + DeviceEvent, ElementState, Event, KeyboardInput, ModifiersState, MouseButton, + MouseScrollDelta, TouchPhase, VirtualKeyCode, WindowEvent, + }, + platform_impl::platform::{ + app_state::AppState, + event::{ + char_to_keycode, check_function_keys, event_mods, get_scancode, modifier_event, + scancode_to_keycode, EventWrapper, + }, + ffi::*, + util::{self, IdRef}, + window::get_window_id, + DEVICE_ID, + }, + window::WindowId, +}; + +pub struct CursorState { + pub visible: bool, + pub cursor: util::Cursor, +} + +impl Default for CursorState { + fn default() -> Self { + Self { + visible: true, + cursor: Default::default(), + } + } +} + +pub(super) struct ViewState { + ns_window: id, + pub cursor_state: Arc>, + ime_spot: Option<(f64, f64)>, + raw_characters: Option, + is_key_down: bool, + pub(super) modifiers: ModifiersState, + tracking_rect: Option, +} + +impl ViewState { + fn get_scale_factor(&self) -> f64 { + (unsafe { NSWindow::backingScaleFactor(self.ns_window) }) as f64 + } +} + +pub fn new_view(ns_window: id) -> (IdRef, Weak>) { + let cursor_state = Default::default(); + let cursor_access = Arc::downgrade(&cursor_state); + let state = ViewState { + ns_window, + cursor_state, + ime_spot: None, + raw_characters: None, + is_key_down: false, + modifiers: Default::default(), + tracking_rect: None, + }; + unsafe { + // This is free'd in `dealloc` + let state_ptr = Box::into_raw(Box::new(state)) as *mut c_void; + let ns_view: id = msg_send![VIEW_CLASS.0, alloc]; + ( + IdRef::new(msg_send![ns_view, initWithWinit: state_ptr]), + cursor_access, + ) + } +} + +pub unsafe fn set_ime_position(ns_view: id, input_context: id, x: f64, y: f64) { + let state_ptr: *mut c_void = *(*ns_view).get_mut_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + let content_rect = + NSWindow::contentRectForFrameRect_(state.ns_window, NSWindow::frame(state.ns_window)); + let base_x = content_rect.origin.x as f64; + let base_y = (content_rect.origin.y + content_rect.size.height) as f64; + state.ime_spot = Some((base_x + x, base_y - y)); + let _: () = msg_send![input_context, invalidateCharacterCoordinates]; +} + +struct ViewClass(*const Class); +unsafe impl Send for ViewClass {} +unsafe impl Sync for ViewClass {} + +lazy_static! { + static ref VIEW_CLASS: ViewClass = unsafe { + let superclass = class!(NSView); + let mut decl = ClassDecl::new("WinitView", superclass).unwrap(); + decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); + decl.add_method( + sel!(initWithWinit:), + init_with_winit as extern "C" fn(&Object, Sel, *mut c_void) -> id, + ); + decl.add_method( + sel!(viewDidMoveToWindow), + view_did_move_to_window as extern "C" fn(&Object, Sel), + ); + decl.add_method( + sel!(drawRect:), + draw_rect as extern "C" fn(&Object, Sel, NSRect), + ); + decl.add_method( + sel!(acceptsFirstResponder), + accepts_first_responder as extern "C" fn(&Object, Sel) -> BOOL, + ); + decl.add_method( + sel!(touchBar), + touch_bar as extern "C" fn(&Object, Sel) -> BOOL, + ); + decl.add_method( + sel!(resetCursorRects), + reset_cursor_rects as extern "C" fn(&Object, Sel), + ); + decl.add_method( + sel!(hasMarkedText), + has_marked_text as extern "C" fn(&Object, Sel) -> BOOL, + ); + decl.add_method( + sel!(markedRange), + marked_range as extern "C" fn(&Object, Sel) -> NSRange, + ); + decl.add_method( + sel!(selectedRange), + selected_range as extern "C" fn(&Object, Sel) -> NSRange, + ); + decl.add_method( + sel!(setMarkedText:selectedRange:replacementRange:), + set_marked_text as extern "C" fn(&mut Object, Sel, id, NSRange, NSRange), + ); + decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel)); + decl.add_method( + sel!(validAttributesForMarkedText), + valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id, + ); + decl.add_method( + sel!(attributedSubstringForProposedRange:actualRange:), + attributed_substring_for_proposed_range + as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id, + ); + decl.add_method( + sel!(insertText:replacementRange:), + insert_text as extern "C" fn(&Object, Sel, id, NSRange), + ); + decl.add_method( + sel!(characterIndexForPoint:), + character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> NSUInteger, + ); + decl.add_method( + sel!(firstRectForCharacterRange:actualRange:), + first_rect_for_character_range + as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> NSRect, + ); + decl.add_method( + sel!(doCommandBySelector:), + do_command_by_selector as extern "C" fn(&Object, Sel, Sel), + ); + decl.add_method(sel!(keyDown:), key_down as extern "C" fn(&Object, Sel, id)); + decl.add_method(sel!(keyUp:), key_up as extern "C" fn(&Object, Sel, id)); + decl.add_method( + sel!(flagsChanged:), + flags_changed as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(insertTab:), + insert_tab as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(insertBackTab:), + insert_back_tab as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(mouseDown:), + mouse_down as extern "C" fn(&Object, Sel, id), + ); + decl.add_method(sel!(mouseUp:), mouse_up as extern "C" fn(&Object, Sel, id)); + decl.add_method( + sel!(rightMouseDown:), + right_mouse_down as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(rightMouseUp:), + right_mouse_up as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(otherMouseDown:), + other_mouse_down as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(otherMouseUp:), + other_mouse_up as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(mouseMoved:), + mouse_moved as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(mouseDragged:), + mouse_dragged as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(rightMouseDragged:), + right_mouse_dragged as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(otherMouseDragged:), + other_mouse_dragged as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(mouseEntered:), + mouse_entered as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(mouseExited:), + mouse_exited as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(scrollWheel:), + scroll_wheel as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(pressureChangeWithEvent:), + pressure_change_with_event as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(_wantsKeyDownForEvent:), + wants_key_down_for_event as extern "C" fn(&Object, Sel, id) -> BOOL, + ); + decl.add_method( + sel!(cancelOperation:), + cancel_operation as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(frameDidChange:), + frame_did_change as extern "C" fn(&Object, Sel, id), + ); + decl.add_ivar::<*mut c_void>("winitState"); + decl.add_ivar::("markedText"); + let protocol = Protocol::get("NSTextInputClient").unwrap(); + decl.add_protocol(&protocol); + ViewClass(decl.register()) + }; +} + +extern "C" fn dealloc(this: &Object, _sel: Sel) { + unsafe { + let state: *mut c_void = *this.get_ivar("winitState"); + let marked_text: id = *this.get_ivar("markedText"); + let _: () = msg_send![marked_text, release]; + Box::from_raw(state as *mut ViewState); + } +} + +extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> id { + unsafe { + let this: id = msg_send![this, init]; + if this != nil { + (*this).set_ivar("winitState", state); + let marked_text = + ::init(NSMutableAttributedString::alloc(nil)); + (*this).set_ivar("markedText", marked_text); + let _: () = msg_send![this, setPostsFrameChangedNotifications: YES]; + + let notification_center: &Object = + msg_send![class!(NSNotificationCenter), defaultCenter]; + let notification_name = + NSString::alloc(nil).init_str("NSViewFrameDidChangeNotification"); + let _: () = msg_send![ + notification_center, + addObserver: this + selector: sel!(frameDidChange:) + name: notification_name + object: this + ]; + } + this + } +} + +extern "C" fn view_did_move_to_window(this: &Object, _sel: Sel) { + trace!("Triggered `viewDidMoveToWindow`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + if let Some(tracking_rect) = state.tracking_rect.take() { + let _: () = msg_send![this, removeTrackingRect: tracking_rect]; + } + + let rect: NSRect = msg_send![this, visibleRect]; + let tracking_rect: NSInteger = msg_send![this, + addTrackingRect:rect + owner:this + userData:nil + assumeInside:NO + ]; + state.tracking_rect = Some(tracking_rect); + } + trace!("Completed `viewDidMoveToWindow`"); +} + +extern "C" fn frame_did_change(this: &Object, _sel: Sel, _event: id) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + if let Some(tracking_rect) = state.tracking_rect.take() { + let _: () = msg_send![this, removeTrackingRect: tracking_rect]; + } + + let rect: NSRect = msg_send![this, visibleRect]; + let tracking_rect: NSInteger = msg_send![this, + addTrackingRect:rect + owner:this + userData:nil + assumeInside:NO + ]; + + state.tracking_rect = Some(tracking_rect); + } +} + +extern "C" fn draw_rect(this: &Object, _sel: Sel, rect: NSRect) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + AppState::queue_redraw(WindowId(get_window_id(state.ns_window))); + + let superclass = util::superclass(this); + let () = msg_send![super(this, superclass), drawRect: rect]; + } +} + +extern "C" fn accepts_first_responder(_this: &Object, _sel: Sel) -> BOOL { + YES +} + +// This is necessary to prevent a beefy terminal error on MacBook Pros: +// IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem +// TODO: Add an API extension for using `NSTouchBar` +extern "C" fn touch_bar(_this: &Object, _sel: Sel) -> BOOL { + NO +} + +extern "C" fn reset_cursor_rects(this: &Object, _sel: Sel) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let bounds: NSRect = msg_send![this, bounds]; + let cursor_state = state.cursor_state.lock().unwrap(); + let cursor = if cursor_state.visible { + cursor_state.cursor.load() + } else { + util::invisible_cursor() + }; + let _: () = msg_send![this, + addCursorRect:bounds + cursor:cursor + ]; + } +} + +extern "C" fn has_marked_text(this: &Object, _sel: Sel) -> BOOL { + unsafe { + trace!("Triggered `hasMarkedText`"); + let marked_text: id = *this.get_ivar("markedText"); + trace!("Completed `hasMarkedText`"); + (marked_text.length() > 0) as i8 + } +} + +extern "C" fn marked_range(this: &Object, _sel: Sel) -> NSRange { + unsafe { + trace!("Triggered `markedRange`"); + let marked_text: id = *this.get_ivar("markedText"); + let length = marked_text.length(); + trace!("Completed `markedRange`"); + if length > 0 { + NSRange::new(0, length - 1) + } else { + util::EMPTY_RANGE + } + } +} + +extern "C" fn selected_range(_this: &Object, _sel: Sel) -> NSRange { + trace!("Triggered `selectedRange`"); + trace!("Completed `selectedRange`"); + util::EMPTY_RANGE +} + +extern "C" fn set_marked_text( + this: &mut Object, + _sel: Sel, + string: id, + _selected_range: NSRange, + _replacement_range: NSRange, +) { + trace!("Triggered `setMarkedText`"); + unsafe { + let marked_text_ref: &mut id = this.get_mut_ivar("markedText"); + let _: () = msg_send![(*marked_text_ref), release]; + let marked_text = NSMutableAttributedString::alloc(nil); + let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)]; + if has_attr { + marked_text.initWithAttributedString(string); + } else { + marked_text.initWithString(string); + }; + *marked_text_ref = marked_text; + } + trace!("Completed `setMarkedText`"); +} + +extern "C" fn unmark_text(this: &Object, _sel: Sel) { + trace!("Triggered `unmarkText`"); + unsafe { + let marked_text: id = *this.get_ivar("markedText"); + let mutable_string = marked_text.mutableString(); + let _: () = msg_send![mutable_string, setString:""]; + let input_context: id = msg_send![this, inputContext]; + let _: () = msg_send![input_context, discardMarkedText]; + } + trace!("Completed `unmarkText`"); +} + +extern "C" fn valid_attributes_for_marked_text(_this: &Object, _sel: Sel) -> id { + trace!("Triggered `validAttributesForMarkedText`"); + trace!("Completed `validAttributesForMarkedText`"); + unsafe { msg_send![class!(NSArray), array] } +} + +extern "C" fn attributed_substring_for_proposed_range( + _this: &Object, + _sel: Sel, + _range: NSRange, + _actual_range: *mut c_void, // *mut NSRange +) -> id { + trace!("Triggered `attributedSubstringForProposedRange`"); + trace!("Completed `attributedSubstringForProposedRange`"); + nil +} + +extern "C" fn character_index_for_point(_this: &Object, _sel: Sel, _point: NSPoint) -> NSUInteger { + trace!("Triggered `characterIndexForPoint`"); + trace!("Completed `characterIndexForPoint`"); + 0 +} + +extern "C" fn first_rect_for_character_range( + this: &Object, + _sel: Sel, + _range: NSRange, + _actual_range: *mut c_void, // *mut NSRange +) -> NSRect { + unsafe { + trace!("Triggered `firstRectForCharacterRange`"); + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + let (x, y) = state.ime_spot.unwrap_or_else(|| { + let content_rect = NSWindow::contentRectForFrameRect_( + state.ns_window, + NSWindow::frame(state.ns_window), + ); + let x = content_rect.origin.x; + let y = util::bottom_left_to_top_left(content_rect); + (x, y) + }); + trace!("Completed `firstRectForCharacterRange`"); + NSRect::new(NSPoint::new(x as _, y as _), NSSize::new(0.0, 0.0)) + } +} + +extern "C" fn insert_text(this: &Object, _sel: Sel, string: id, _replacement_range: NSRange) { + trace!("Triggered `insertText`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let has_attr = msg_send![string, isKindOfClass: class!(NSAttributedString)]; + let characters = if has_attr { + // This is a *mut NSAttributedString + msg_send![string, string] + } else { + // This is already a *mut NSString + string + }; + + let slice = + slice::from_raw_parts(characters.UTF8String() as *const c_uchar, characters.len()); + let string = str::from_utf8_unchecked(slice); + state.is_key_down = true; + + // We don't need this now, but it's here if that changes. + //let event: id = msg_send![NSApp(), currentEvent]; + + let mut events = VecDeque::with_capacity(characters.len()); + for character in string.chars().filter(|c| !is_corporate_character(*c)) { + events.push_back(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::ReceivedCharacter(character), + })); + } + + AppState::queue_events(events); + } + trace!("Completed `insertText`"); +} + +extern "C" fn do_command_by_selector(this: &Object, _sel: Sel, command: Sel) { + trace!("Triggered `doCommandBySelector`"); + // Basically, we're sent this message whenever a keyboard event that doesn't generate a "human readable" character + // happens, i.e. newlines, tabs, and Ctrl+C. + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let mut events = VecDeque::with_capacity(1); + if command == sel!(insertNewline:) { + // The `else` condition would emit the same character, but I'm keeping this here both... + // 1) as a reminder for how `doCommandBySelector` works + // 2) to make our use of carriage return explicit + events.push_back(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::ReceivedCharacter('\r'), + })); + } else { + let raw_characters = state.raw_characters.take(); + if let Some(raw_characters) = raw_characters { + for character in raw_characters + .chars() + .filter(|c| !is_corporate_character(*c)) + { + events.push_back(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::ReceivedCharacter(character), + })); + } + } + }; + + AppState::queue_events(events); + } + trace!("Completed `doCommandBySelector`"); +} + +fn get_characters(event: id, ignore_modifiers: bool) -> String { + unsafe { + let characters: id = if ignore_modifiers { + msg_send![event, charactersIgnoringModifiers] + } else { + msg_send![event, characters] + }; + + assert_ne!(characters, nil); + let slice = + slice::from_raw_parts(characters.UTF8String() as *const c_uchar, characters.len()); + + let string = str::from_utf8_unchecked(slice); + string.to_owned() + } +} + +// As defined in: https://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/CORPCHAR.TXT +fn is_corporate_character(c: char) -> bool { + match c { + '\u{F700}'..='\u{F747}' + | '\u{F802}'..='\u{F84F}' + | '\u{F850}' + | '\u{F85C}' + | '\u{F85D}' + | '\u{F85F}' + | '\u{F860}'..='\u{F86B}' + | '\u{F870}'..='\u{F8FF}' => true, + _ => false, + } +} + +// Retrieves a layout-independent keycode given an event. +fn retrieve_keycode(event: id) -> Option { + #[inline] + fn get_code(ev: id, raw: bool) -> Option { + let characters = get_characters(ev, raw); + characters.chars().next().and_then(|c| char_to_keycode(c)) + } + + // Cmd switches Roman letters for Dvorak-QWERTY layout, so we try modified characters first. + // If we don't get a match, then we fall back to unmodified characters. + let code = get_code(event, false).or_else(|| get_code(event, true)); + + // We've checked all layout related keys, so fall through to scancode. + // Reaching this code means that the key is layout-independent (e.g. Backspace, Return). + // + // We're additionally checking here for F21-F24 keys, since their keycode + // can vary, but we know that they are encoded + // in characters property. + code.or_else(|| { + let scancode = get_scancode(event); + scancode_to_keycode(scancode).or_else(|| check_function_keys(&get_characters(event, true))) + }) +} + +// Update `state.modifiers` if `event` has something different +fn update_potentially_stale_modifiers(state: &mut ViewState, event: id) { + let event_modifiers = event_mods(event); + if state.modifiers != event_modifiers { + state.modifiers = event_modifiers; + + AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::ModifiersChanged(state.modifiers), + })); + } +} + +extern "C" fn key_down(this: &Object, _sel: Sel, event: id) { + trace!("Triggered `keyDown`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + let window_id = WindowId(get_window_id(state.ns_window)); + let characters = get_characters(event, false); + + state.raw_characters = Some(characters.clone()); + + let scancode = get_scancode(event) as u32; + let virtual_keycode = retrieve_keycode(event); + + let is_repeat = msg_send![event, isARepeat]; + + update_potentially_stale_modifiers(state, event); + + #[allow(deprecated)] + let window_event = Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state: ElementState::Pressed, + scancode, + virtual_keycode, + modifiers: event_mods(event), + }, + is_synthetic: false, + }, + }; + + let pass_along = { + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + // Emit `ReceivedCharacter` for key repeats + if is_repeat && state.is_key_down { + for character in characters.chars().filter(|c| !is_corporate_character(*c)) { + AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id, + event: WindowEvent::ReceivedCharacter(character), + })); + } + false + } else { + true + } + }; + + if pass_along { + // Some keys (and only *some*, with no known reason) don't trigger `insertText`, while others do... + // So, we don't give repeats the opportunity to trigger that, since otherwise our hack will cause some + // keys to generate twice as many characters. + let array: id = msg_send![class!(NSArray), arrayWithObject: event]; + let _: () = msg_send![this, interpretKeyEvents: array]; + } + } + trace!("Completed `keyDown`"); +} + +extern "C" fn key_up(this: &Object, _sel: Sel, event: id) { + trace!("Triggered `keyUp`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + state.is_key_down = false; + + let scancode = get_scancode(event) as u32; + let virtual_keycode = retrieve_keycode(event); + + update_potentially_stale_modifiers(state, event); + + #[allow(deprecated)] + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state: ElementState::Released, + scancode, + virtual_keycode, + modifiers: event_mods(event), + }, + is_synthetic: false, + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } + trace!("Completed `keyUp`"); +} + +extern "C" fn flags_changed(this: &Object, _sel: Sel, event: id) { + trace!("Triggered `flagsChanged`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let mut events = VecDeque::with_capacity(4); + + if let Some(window_event) = modifier_event( + event, + NSEventModifierFlags::NSShiftKeyMask, + state.modifiers.shift(), + ) { + state.modifiers.toggle(ModifiersState::SHIFT); + events.push_back(window_event); + } + + if let Some(window_event) = modifier_event( + event, + NSEventModifierFlags::NSControlKeyMask, + state.modifiers.ctrl(), + ) { + state.modifiers.toggle(ModifiersState::CTRL); + events.push_back(window_event); + } + + if let Some(window_event) = modifier_event( + event, + NSEventModifierFlags::NSCommandKeyMask, + state.modifiers.logo(), + ) { + state.modifiers.toggle(ModifiersState::LOGO); + events.push_back(window_event); + } + + if let Some(window_event) = modifier_event( + event, + NSEventModifierFlags::NSAlternateKeyMask, + state.modifiers.alt(), + ) { + state.modifiers.toggle(ModifiersState::ALT); + events.push_back(window_event); + } + + let window_id = WindowId(get_window_id(state.ns_window)); + + for event in events { + AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id, + event, + })); + } + + AppState::queue_event(EventWrapper::StaticEvent(Event::WindowEvent { + window_id, + event: WindowEvent::ModifiersChanged(state.modifiers), + })); + } + trace!("Completed `flagsChanged`"); +} + +extern "C" fn insert_tab(this: &Object, _sel: Sel, _sender: id) { + unsafe { + let window: id = msg_send![this, window]; + let first_responder: id = msg_send![window, firstResponder]; + let this_ptr = this as *const _ as *mut _; + if first_responder == this_ptr { + let (): _ = msg_send![window, selectNextKeyView: this]; + } + } +} + +extern "C" fn insert_back_tab(this: &Object, _sel: Sel, _sender: id) { + unsafe { + let window: id = msg_send![this, window]; + let first_responder: id = msg_send![window, firstResponder]; + let this_ptr = this as *const _ as *mut _; + if first_responder == this_ptr { + let (): _ = msg_send![window, selectPreviousKeyView: this]; + } + } +} + +// Allows us to receive Cmd-. (the shortcut for closing a dialog) +// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6 +extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) { + trace!("Triggered `cancelOperation`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let scancode = 0x2f; + let virtual_keycode = scancode_to_keycode(scancode); + debug_assert_eq!(virtual_keycode, Some(VirtualKeyCode::Period)); + + let event: id = msg_send![NSApp(), currentEvent]; + + update_potentially_stale_modifiers(state, event); + + #[allow(deprecated)] + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state: ElementState::Pressed, + scancode: scancode as _, + virtual_keycode, + modifiers: event_mods(event), + }, + is_synthetic: false, + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } + trace!("Completed `cancelOperation`"); +} + +fn mouse_click(this: &Object, event: id, button: MouseButton, button_state: ElementState) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + update_potentially_stale_modifiers(state, event); + + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::MouseInput { + device_id: DEVICE_ID, + state: button_state, + button, + modifiers: event_mods(event), + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } +} + +extern "C" fn mouse_down(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Left, ElementState::Pressed); +} + +extern "C" fn mouse_up(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Left, ElementState::Released); +} + +extern "C" fn right_mouse_down(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Right, ElementState::Pressed); +} + +extern "C" fn right_mouse_up(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Right, ElementState::Released); +} + +extern "C" fn other_mouse_down(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Middle, ElementState::Pressed); +} + +extern "C" fn other_mouse_up(this: &Object, _sel: Sel, event: id) { + mouse_click(this, event, MouseButton::Middle, ElementState::Released); +} + +fn mouse_motion(this: &Object, event: id) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + // We have to do this to have access to the `NSView` trait... + let view: id = this as *const _ as *mut _; + + let window_point = event.locationInWindow(); + let view_point = view.convertPoint_fromView_(window_point, nil); + let view_rect = NSView::frame(view); + + if view_point.x.is_sign_negative() + || view_point.y.is_sign_negative() + || view_point.x > view_rect.size.width + || view_point.y > view_rect.size.height + { + // Point is outside of the client area (view) + return; + } + + let x = view_point.x as f64; + let y = view_rect.size.height as f64 - view_point.y as f64; + let logical_position = LogicalPosition::new(x, y); + + update_potentially_stale_modifiers(state, event); + + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::CursorMoved { + device_id: DEVICE_ID, + position: logical_position.to_physical(state.get_scale_factor()), + modifiers: event_mods(event), + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } +} + +extern "C" fn mouse_moved(this: &Object, _sel: Sel, event: id) { + mouse_motion(this, event); +} + +extern "C" fn mouse_dragged(this: &Object, _sel: Sel, event: id) { + mouse_motion(this, event); +} + +extern "C" fn right_mouse_dragged(this: &Object, _sel: Sel, event: id) { + mouse_motion(this, event); +} + +extern "C" fn other_mouse_dragged(this: &Object, _sel: Sel, event: id) { + mouse_motion(this, event); +} + +extern "C" fn mouse_entered(this: &Object, _sel: Sel, _event: id) { + trace!("Triggered `mouseEntered`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let enter_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::CursorEntered { + device_id: DEVICE_ID, + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(enter_event)); + } + trace!("Completed `mouseEntered`"); +} + +extern "C" fn mouse_exited(this: &Object, _sel: Sel, _event: id) { + trace!("Triggered `mouseExited`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::CursorLeft { + device_id: DEVICE_ID, + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } + trace!("Completed `mouseExited`"); +} + +extern "C" fn scroll_wheel(this: &Object, _sel: Sel, event: id) { + trace!("Triggered `scrollWheel`"); + unsafe { + let delta = { + let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY()); + if event.hasPreciseScrollingDeltas() == YES { + MouseScrollDelta::PixelDelta((x as f64, y as f64).into()) + } else { + MouseScrollDelta::LineDelta(x as f32, y as f32) + } + }; + let phase = match event.phase() { + NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => { + TouchPhase::Started + } + NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended, + _ => TouchPhase::Moved, + }; + + let device_event = Event::DeviceEvent { + device_id: DEVICE_ID, + event: DeviceEvent::MouseWheel { delta }, + }; + + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + update_potentially_stale_modifiers(state, event); + + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta, + phase, + modifiers: event_mods(event), + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(device_event)); + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } + trace!("Completed `scrollWheel`"); +} + +extern "C" fn pressure_change_with_event(this: &Object, _sel: Sel, event: id) { + trace!("Triggered `pressureChangeWithEvent`"); + unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + let state = &mut *(state_ptr as *mut ViewState); + + let pressure = event.pressure(); + let stage = event.stage(); + + let window_event = Event::WindowEvent { + window_id: WindowId(get_window_id(state.ns_window)), + event: WindowEvent::TouchpadPressure { + device_id: DEVICE_ID, + pressure, + stage, + }, + }; + + AppState::queue_event(EventWrapper::StaticEvent(window_event)); + } + trace!("Completed `pressureChangeWithEvent`"); +} + +// Allows us to receive Ctrl-Tab and Ctrl-Esc. +// Note that this *doesn't* help with any missing Cmd inputs. +// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 +extern "C" fn wants_key_down_for_event(_this: &Object, _sel: Sel, _event: id) -> BOOL { + YES +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window.rs new file mode 100644 index 0000000..2d69294 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window.rs @@ -0,0 +1,1152 @@ +use raw_window_handle::{macos::MacOSHandle, RawWindowHandle}; +use std::{ + collections::VecDeque, + f64, + os::raw::c_void, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, Weak, + }, +}; + +use crate::{ + dpi::{ + LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size, Size::Logical, + }, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + icon::Icon, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform::macos::{ActivationPolicy, RequestUserAttentionType, WindowExtMacOS}, + platform_impl::platform::{ + app_state::AppState, + ffi, + monitor::{self, MonitorHandle, VideoMode}, + util::{self, IdRef}, + view::CursorState, + view::{self, new_view}, + window_delegate::new_delegate, + OsError, + }, + window::{CursorIcon, Fullscreen, WindowAttributes, WindowId as RootWindowId}, +}; +use cocoa::{ + appkit::{ + self, CGFloat, NSApp, NSApplication, NSApplicationActivationPolicy, + NSApplicationPresentationOptions, NSColor, NSRequestUserAttentionType, NSScreen, NSView, + NSWindow, NSWindowButton, NSWindowStyleMask, + }, + base::{id, nil}, + foundation::{NSAutoreleasePool, NSDictionary, NSPoint, NSRect, NSSize}, +}; +use core_graphics::display::{CGDisplay, CGDisplayMode}; +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Sel, BOOL, NO, YES}, +}; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Id(pub usize); + +impl Id { + pub unsafe fn dummy() -> Self { + Id(0) + } +} + +// Convert the `cocoa::base::id` associated with a window to a usize to use as a unique identifier +// for the window. +pub fn get_window_id(window_cocoa_id: id) -> Id { + Id(window_cocoa_id as *const Object as _) +} + +#[derive(Clone, Default)] +pub struct PlatformSpecificWindowBuilderAttributes { + pub activation_policy: ActivationPolicy, + pub movable_by_window_background: bool, + pub titlebar_transparent: bool, + pub title_hidden: bool, + pub titlebar_hidden: bool, + pub titlebar_buttons_hidden: bool, + pub fullsize_content_view: bool, + pub resize_increments: Option>, + pub disallow_hidpi: bool, +} + +fn create_app(activation_policy: ActivationPolicy) -> Option { + unsafe { + let ns_app = NSApp(); + if ns_app == nil { + None + } else { + use self::NSApplicationActivationPolicy::*; + ns_app.setActivationPolicy_(match activation_policy { + ActivationPolicy::Regular => NSApplicationActivationPolicyRegular, + ActivationPolicy::Accessory => NSApplicationActivationPolicyAccessory, + ActivationPolicy::Prohibited => NSApplicationActivationPolicyProhibited, + }); + ns_app.finishLaunching(); + Some(ns_app) + } + } +} + +unsafe fn create_view( + ns_window: id, + pl_attribs: &PlatformSpecificWindowBuilderAttributes, +) -> Option<(IdRef, Weak>)> { + let (ns_view, cursor_state) = new_view(ns_window); + ns_view.non_nil().map(|ns_view| { + if !pl_attribs.disallow_hidpi { + ns_view.setWantsBestResolutionOpenGLSurface_(YES); + } + + // On Mojave, views automatically become layer-backed shortly after being added to + // a window. Changing the layer-backedness of a view breaks the association between + // the view and its associated OpenGL context. To work around this, on Mojave we + // explicitly make the view layer-backed up front so that AppKit doesn't do it + // itself and break the association with its context. + if f64::floor(appkit::NSAppKitVersionNumber) > appkit::NSAppKitVersionNumber10_12 { + ns_view.setWantsLayer(YES); + } + + ns_window.setContentView_(*ns_view); + ns_window.makeFirstResponder_(*ns_view); + (ns_view, cursor_state) + }) +} + +fn create_window( + attrs: &WindowAttributes, + pl_attrs: &PlatformSpecificWindowBuilderAttributes, +) -> Option { + unsafe { + let pool = NSAutoreleasePool::new(nil); + let screen = match attrs.fullscreen { + Some(Fullscreen::Borderless(RootMonitorHandle { inner: ref monitor })) + | Some(Fullscreen::Exclusive(RootVideoMode { + video_mode: VideoMode { ref monitor, .. }, + })) => { + let monitor_screen = monitor.ns_screen(); + Some(monitor_screen.unwrap_or(appkit::NSScreen::mainScreen(nil))) + } + None => None, + }; + let frame = match screen { + Some(screen) => NSScreen::frame(screen), + None => { + let screen = NSScreen::mainScreen(nil); + let scale_factor = NSScreen::backingScaleFactor(screen) as f64; + let (width, height) = match attrs.inner_size { + Some(size) => { + let logical = size.to_logical(scale_factor); + (logical.width, logical.height) + } + None => (800.0, 600.0), + }; + NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(width, height)) + } + }; + + let mut masks = if !attrs.decorations && !screen.is_some() { + // Resizable UnownedWindow without a titlebar or borders + // if decorations is set to false, ignore pl_attrs + NSWindowStyleMask::NSBorderlessWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + } else if pl_attrs.titlebar_hidden { + // if the titlebar is hidden, ignore other pl_attrs + NSWindowStyleMask::NSBorderlessWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + } else { + // default case, resizable window with titlebar and titlebar buttons + NSWindowStyleMask::NSClosableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSTitledWindowMask + }; + + if !attrs.resizable { + masks &= !NSWindowStyleMask::NSResizableWindowMask; + } + + if pl_attrs.fullsize_content_view { + masks |= NSWindowStyleMask::NSFullSizeContentViewWindowMask; + } + + let ns_window: id = msg_send![WINDOW_CLASS.0, alloc]; + let ns_window = IdRef::new(ns_window.initWithContentRect_styleMask_backing_defer_( + frame, + masks, + appkit::NSBackingStoreBuffered, + NO, + )); + let res = ns_window.non_nil().map(|ns_window| { + let title = util::ns_string_id_ref(&attrs.title); + ns_window.setReleasedWhenClosed_(NO); + ns_window.setTitle_(*title); + ns_window.setAcceptsMouseMovedEvents_(YES); + + if pl_attrs.titlebar_transparent { + ns_window.setTitlebarAppearsTransparent_(YES); + } + if pl_attrs.title_hidden { + ns_window.setTitleVisibility_(appkit::NSWindowTitleVisibility::NSWindowTitleHidden); + } + if pl_attrs.titlebar_buttons_hidden { + for titlebar_button in &[ + NSWindowButton::NSWindowFullScreenButton, + NSWindowButton::NSWindowMiniaturizeButton, + NSWindowButton::NSWindowCloseButton, + NSWindowButton::NSWindowZoomButton, + ] { + let button = ns_window.standardWindowButton_(*titlebar_button); + let _: () = msg_send![button, setHidden: YES]; + } + } + if pl_attrs.movable_by_window_background { + ns_window.setMovableByWindowBackground_(YES); + } + + if attrs.always_on_top { + let _: () = msg_send![ + *ns_window, + setLevel: ffi::NSWindowLevel::NSFloatingWindowLevel + ]; + } + + if let Some(increments) = pl_attrs.resize_increments { + let (x, y) = (increments.width, increments.height); + if x >= 1.0 && y >= 1.0 { + let size = NSSize::new(x as CGFloat, y as CGFloat); + ns_window.setResizeIncrements_(size); + } + } + + ns_window.center(); + ns_window + }); + pool.drain(); + res + } +} + +struct WindowClass(*const Class); +unsafe impl Send for WindowClass {} +unsafe impl Sync for WindowClass {} + +lazy_static! { + static ref WINDOW_CLASS: WindowClass = unsafe { + let window_superclass = class!(NSWindow); + let mut decl = ClassDecl::new("WinitWindow", window_superclass).unwrap(); + decl.add_method( + sel!(canBecomeMainWindow), + util::yes as extern "C" fn(&Object, Sel) -> BOOL, + ); + decl.add_method( + sel!(canBecomeKeyWindow), + util::yes as extern "C" fn(&Object, Sel) -> BOOL, + ); + WindowClass(decl.register()) + }; +} + +#[derive(Default)] +pub struct SharedState { + pub resizable: bool, + pub fullscreen: Option, + // This is true between windowWillEnterFullScreen and windowDidEnterFullScreen + // or windowWillExitFullScreen and windowDidExitFullScreen. + // We must not toggle fullscreen when this is true. + pub in_fullscreen_transition: bool, + // If it is attempted to toggle fullscreen when in_fullscreen_transition is true, + // Set target_fullscreen and do after fullscreen transition is end. + pub target_fullscreen: Option>, + pub maximized: bool, + pub standard_frame: Option, + is_simple_fullscreen: bool, + pub saved_style: Option, + /// Presentation options saved before entering `set_simple_fullscreen`, and + /// restored upon exiting it + save_presentation_opts: Option, + pub saved_desktop_display_mode: Option<(CGDisplay, CGDisplayMode)>, +} + +impl SharedState { + pub fn saved_standard_frame(&self) -> NSRect { + self.standard_frame + .unwrap_or_else(|| NSRect::new(NSPoint::new(50.0, 50.0), NSSize::new(800.0, 600.0))) + } +} + +impl From for SharedState { + fn from(attribs: WindowAttributes) -> Self { + SharedState { + resizable: attribs.resizable, + // This fullscreen field tracks the current state of the window + // (as seen by `WindowDelegate`), and since the window hasn't + // actually been fullscreened yet, we can't set it yet. This is + // necessary for state transitions to work right, since otherwise + // the initial value and the first `set_fullscreen` call would be + // identical, resulting in a no-op. + fullscreen: None, + maximized: attribs.maximized, + ..Default::default() + } + } +} + +pub struct UnownedWindow { + pub ns_window: IdRef, // never changes + pub ns_view: IdRef, // never changes + input_context: IdRef, // never changes + pub shared_state: Arc>, + decorations: AtomicBool, + cursor_state: Weak>, + pub inner_rect: Option>, +} + +unsafe impl Send for UnownedWindow {} +unsafe impl Sync for UnownedWindow {} + +impl UnownedWindow { + pub fn new( + mut win_attribs: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + ) -> Result<(Arc, IdRef), RootOsError> { + unsafe { + if !msg_send![class!(NSThread), isMainThread] { + panic!("Windows can only be created on the main thread on macOS"); + } + } + + let pool = unsafe { NSAutoreleasePool::new(nil) }; + + let ns_app = create_app(pl_attribs.activation_policy).ok_or_else(|| { + unsafe { pool.drain() }; + os_error!(OsError::CreationError("Couldn't create `NSApplication`")) + })?; + + let ns_window = create_window(&win_attribs, &pl_attribs).ok_or_else(|| { + unsafe { pool.drain() }; + os_error!(OsError::CreationError("Couldn't create `NSWindow`")) + })?; + + let (ns_view, cursor_state) = + unsafe { create_view(*ns_window, &pl_attribs) }.ok_or_else(|| { + unsafe { pool.drain() }; + os_error!(OsError::CreationError("Couldn't create `NSView`")) + })?; + + let input_context = unsafe { util::create_input_context(*ns_view) }; + + let scale_factor = unsafe { NSWindow::backingScaleFactor(*ns_window) as f64 }; + + unsafe { + if win_attribs.transparent { + ns_window.setOpaque_(NO); + ns_window.setBackgroundColor_(NSColor::clearColor(nil)); + } + + ns_app.activateIgnoringOtherApps_(YES); + win_attribs.min_inner_size.map(|dim| { + let logical_dim = dim.to_logical(scale_factor); + set_min_inner_size(*ns_window, logical_dim) + }); + win_attribs.max_inner_size.map(|dim| { + let logical_dim = dim.to_logical(scale_factor); + set_max_inner_size(*ns_window, logical_dim) + }); + + use cocoa::foundation::NSArray; + // register for drag and drop operations. + let () = msg_send![ + *ns_window, + registerForDraggedTypes: + NSArray::arrayWithObject(nil, appkit::NSFilenamesPboardType) + ]; + } + + // Since `win_attribs` is put into a mutex below, we'll just copy these + // attributes now instead of bothering to lock it later. + // Also, `SharedState` doesn't carry `fullscreen` over; it's set + // indirectly by us calling `set_fullscreen` below, causing handlers in + // `WindowDelegate` to update the state. + let fullscreen = win_attribs.fullscreen.take(); + let maximized = win_attribs.maximized; + let visible = win_attribs.visible; + let decorations = win_attribs.decorations; + let inner_rect = win_attribs + .inner_size + .map(|size| size.to_physical(scale_factor)); + + let window = Arc::new(UnownedWindow { + ns_view, + ns_window, + input_context, + shared_state: Arc::new(Mutex::new(win_attribs.into())), + decorations: AtomicBool::new(decorations), + cursor_state, + inner_rect, + }); + + let delegate = new_delegate(&window, fullscreen.is_some()); + + // Set fullscreen mode after we setup everything + window.set_fullscreen(fullscreen); + + // Setting the window as key has to happen *after* we set the fullscreen + // state, since otherwise we'll briefly see the window at normal size + // before it transitions. + unsafe { + if visible { + window.ns_window.makeKeyAndOrderFront_(nil); + } else { + window.ns_window.makeKeyWindow(); + } + } + + if maximized { + window.set_maximized(maximized); + } + + unsafe { pool.drain() }; + + Ok((window, delegate)) + } + + fn set_style_mask_async(&self, mask: NSWindowStyleMask) { + unsafe { util::set_style_mask_async(*self.ns_window, *self.ns_view, mask) }; + } + + fn set_style_mask_sync(&self, mask: NSWindowStyleMask) { + unsafe { util::set_style_mask_sync(*self.ns_window, *self.ns_view, mask) }; + } + + pub fn id(&self) -> Id { + get_window_id(*self.ns_window) + } + + pub fn set_title(&self, title: &str) { + unsafe { + util::set_title_async(*self.ns_window, title.to_string()); + } + } + + pub fn set_visible(&self, visible: bool) { + match visible { + true => unsafe { util::make_key_and_order_front_async(*self.ns_window) }, + false => unsafe { util::order_out_async(*self.ns_window) }, + } + } + + pub fn request_redraw(&self) { + AppState::queue_redraw(RootWindowId(self.id())); + } + + pub fn outer_position(&self) -> Result, NotSupportedError> { + let frame_rect = unsafe { NSWindow::frame(*self.ns_window) }; + let position = LogicalPosition::new( + frame_rect.origin.x as f64, + util::bottom_left_to_top_left(frame_rect), + ); + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + + pub fn inner_position(&self) -> Result, NotSupportedError> { + let content_rect = unsafe { + NSWindow::contentRectForFrameRect_(*self.ns_window, NSWindow::frame(*self.ns_window)) + }; + let position = LogicalPosition::new( + content_rect.origin.x as f64, + util::bottom_left_to_top_left(content_rect), + ); + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + + pub fn set_outer_position(&self, position: Position) { + let scale_factor = self.scale_factor(); + let position = position.to_logical(scale_factor); + let dummy = NSRect::new( + NSPoint::new( + position.x, + // While it's true that we're setting the top-left position, + // it still needs to be in a bottom-left coordinate system. + CGDisplay::main().pixels_high() as f64 - position.y, + ), + NSSize::new(0f64, 0f64), + ); + unsafe { + util::set_frame_top_left_point_async(*self.ns_window, dummy.origin); + } + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + let view_frame = unsafe { NSView::frame(*self.ns_view) }; + let logical: LogicalSize = + (view_frame.size.width as f64, view_frame.size.height as f64).into(); + let scale_factor = self.scale_factor(); + logical.to_physical(scale_factor) + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + let view_frame = unsafe { NSWindow::frame(*self.ns_window) }; + let logical: LogicalSize = + (view_frame.size.width as f64, view_frame.size.height as f64).into(); + let scale_factor = self.scale_factor(); + logical.to_physical(scale_factor) + } + + #[inline] + pub fn set_inner_size(&self, size: Size) { + unsafe { + let scale_factor = self.scale_factor(); + util::set_content_size_async(*self.ns_window, size.to_logical(scale_factor)); + } + } + + pub fn set_min_inner_size(&self, dimensions: Option) { + unsafe { + let dimensions = dimensions.unwrap_or(Logical(LogicalSize { + width: 0.0, + height: 0.0, + })); + let scale_factor = self.scale_factor(); + set_min_inner_size(*self.ns_window, dimensions.to_logical(scale_factor)); + } + } + + pub fn set_max_inner_size(&self, dimensions: Option) { + unsafe { + let dimensions = dimensions.unwrap_or(Logical(LogicalSize { + width: std::f32::MAX as f64, + height: std::f32::MAX as f64, + })); + let scale_factor = self.scale_factor(); + set_max_inner_size(*self.ns_window, dimensions.to_logical(scale_factor)); + } + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + let fullscreen = { + trace!("Locked shared state in `set_resizable`"); + let mut shared_state_lock = self.shared_state.lock().unwrap(); + shared_state_lock.resizable = resizable; + trace!("Unlocked shared state in `set_resizable`"); + shared_state_lock.fullscreen.is_some() + }; + if !fullscreen { + let mut mask = unsafe { self.ns_window.styleMask() }; + if resizable { + mask |= NSWindowStyleMask::NSResizableWindowMask; + } else { + mask &= !NSWindowStyleMask::NSResizableWindowMask; + } + self.set_style_mask_async(mask); + } // Otherwise, we don't change the mask until we exit fullscreen. + } + + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + let cursor = util::Cursor::from(cursor); + if let Some(cursor_access) = self.cursor_state.upgrade() { + cursor_access.lock().unwrap().cursor = cursor; + } + unsafe { + let _: () = msg_send![*self.ns_window, + invalidateCursorRectsForView:*self.ns_view + ]; + } + } + + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 + CGDisplay::associate_mouse_and_mouse_cursor_position(!grab) + .map_err(|status| ExternalError::Os(os_error!(OsError::CGError(status)))) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + if let Some(cursor_access) = self.cursor_state.upgrade() { + let mut cursor_state = cursor_access.lock().unwrap(); + if visible != cursor_state.visible { + cursor_state.visible = visible; + drop(cursor_state); + unsafe { + let _: () = msg_send![*self.ns_window, + invalidateCursorRectsForView:*self.ns_view + ]; + } + } + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + unsafe { NSWindow::backingScaleFactor(*self.ns_window) as _ } + } + + #[inline] + pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> { + let physical_window_position = self.inner_position().unwrap(); + let scale_factor = self.scale_factor(); + let window_position = physical_window_position.to_logical::(scale_factor); + let logical_cursor_position = cursor_position.to_logical::(scale_factor); + let point = appkit::CGPoint { + x: logical_cursor_position.x + window_position.x, + y: logical_cursor_position.y + window_position.y, + }; + CGDisplay::warp_mouse_cursor_position(point) + .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; + CGDisplay::associate_mouse_and_mouse_cursor_position(true) + .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; + + Ok(()) + } + + pub(crate) fn is_zoomed(&self) -> bool { + // because `isZoomed` doesn't work if the window's borderless, + // we make it resizable temporalily. + let curr_mask = unsafe { self.ns_window.styleMask() }; + + let required = + NSWindowStyleMask::NSTitledWindowMask | NSWindowStyleMask::NSResizableWindowMask; + let needs_temp_mask = !curr_mask.contains(required); + if needs_temp_mask { + self.set_style_mask_sync(required); + } + + let is_zoomed: BOOL = unsafe { msg_send![*self.ns_window, isZoomed] }; + + // Roll back temp styles + if needs_temp_mask { + self.set_style_mask_async(curr_mask); + } + + is_zoomed != 0 + } + + fn saved_style(&self, shared_state: &mut SharedState) -> NSWindowStyleMask { + let base_mask = shared_state + .saved_style + .take() + .unwrap_or_else(|| unsafe { self.ns_window.styleMask() }); + if shared_state.resizable { + base_mask | NSWindowStyleMask::NSResizableWindowMask + } else { + base_mask & !NSWindowStyleMask::NSResizableWindowMask + } + } + + /// This is called when the window is exiting fullscreen, whether by the + /// user clicking on the green fullscreen button or programmatically by + /// `toggleFullScreen:` + pub(crate) fn restore_state_from_fullscreen(&self) { + trace!("Locked shared state in `restore_state_from_fullscreen`"); + let mut shared_state_lock = self.shared_state.lock().unwrap(); + + shared_state_lock.fullscreen = None; + + let maximized = shared_state_lock.maximized; + let mask = self.saved_style(&mut *shared_state_lock); + + drop(shared_state_lock); + trace!("Unocked shared state in `restore_state_from_fullscreen`"); + + self.set_style_mask_async(mask); + self.set_maximized(maximized); + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let is_minimized: BOOL = unsafe { msg_send![*self.ns_window, isMiniaturized] }; + let is_minimized: bool = is_minimized == YES; + if is_minimized == minimized { + return; + } + + if minimized { + unsafe { + NSWindow::miniaturize_(*self.ns_window, *self.ns_window); + } + } else { + unsafe { + NSWindow::deminiaturize_(*self.ns_window, *self.ns_window); + } + } + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let is_zoomed = self.is_zoomed(); + if is_zoomed == maximized { + return; + }; + unsafe { + util::set_maximized_async( + *self.ns_window, + is_zoomed, + maximized, + Arc::downgrade(&self.shared_state), + ); + } + } + + #[inline] + pub fn fullscreen(&self) -> Option { + let shared_state_lock = self.shared_state.lock().unwrap(); + shared_state_lock.fullscreen.clone() + } + + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option) { + trace!("Locked shared state in `set_fullscreen`"); + let mut shared_state_lock = self.shared_state.lock().unwrap(); + if shared_state_lock.is_simple_fullscreen { + trace!("Unlocked shared state in `set_fullscreen`"); + return; + } + if shared_state_lock.in_fullscreen_transition { + // We can't set fullscreen here. + // Set fullscreen after transition. + shared_state_lock.target_fullscreen = Some(fullscreen); + trace!("Unlocked shared state in `set_fullscreen`"); + return; + } + let old_fullscreen = shared_state_lock.fullscreen.clone(); + if fullscreen == old_fullscreen { + trace!("Unlocked shared state in `set_fullscreen`"); + return; + } + trace!("Unlocked shared state in `set_fullscreen`"); + drop(shared_state_lock); + + // If the fullscreen is on a different monitor, we must move the window + // to that monitor before we toggle fullscreen (as `toggleFullScreen` + // does not take a screen parameter, but uses the current screen) + if let Some(ref fullscreen) = fullscreen { + let new_screen = match fullscreen { + Fullscreen::Borderless(RootMonitorHandle { inner: ref monitor }) => monitor, + Fullscreen::Exclusive(RootVideoMode { + video_mode: VideoMode { ref monitor, .. }, + }) => monitor, + } + .ns_screen() + .unwrap(); + + unsafe { + let old_screen = NSWindow::screen(*self.ns_window); + if old_screen != new_screen { + let mut screen_frame: NSRect = msg_send![new_screen, frame]; + // The coordinate system here has its origin at bottom-left + // and Y goes up + screen_frame.origin.y += screen_frame.size.height; + util::set_frame_top_left_point_async(*self.ns_window, screen_frame.origin); + } + } + } + + if let Some(Fullscreen::Exclusive(ref video_mode)) = fullscreen { + // Note: `enterFullScreenMode:withOptions:` seems to do the exact + // same thing as we're doing here (captures the display, sets the + // video mode, and hides the menu bar and dock), with the exception + // of that I couldn't figure out how to set the display mode with + // it. I think `enterFullScreenMode:withOptions:` is still using the + // older display mode API where display modes were of the type + // `CFDictionary`, but this has changed, so we can't obtain the + // correct parameter for this any longer. Apple's code samples for + // this function seem to just pass in "YES" for the display mode + // parameter, which is not consistent with the docs saying that it + // takes a `NSDictionary`.. + + let display_id = video_mode.monitor().inner.native_identifier(); + + let mut fade_token = ffi::kCGDisplayFadeReservationInvalidToken; + + unsafe { + // Fade to black (and wait for the fade to complete) to hide the + // flicker from capturing the display and switching display mode + if ffi::CGAcquireDisplayFadeReservation(5.0, &mut fade_token) + == ffi::kCGErrorSuccess + { + ffi::CGDisplayFade( + fade_token, + 0.3, + ffi::kCGDisplayBlendNormal, + ffi::kCGDisplayBlendSolidColor, + 0.0, + 0.0, + 0.0, + ffi::TRUE, + ); + } + + assert_eq!(ffi::CGDisplayCapture(display_id), ffi::kCGErrorSuccess); + } + + unsafe { + let result = ffi::CGDisplaySetDisplayMode( + display_id, + video_mode.video_mode.native_mode.0, + std::ptr::null(), + ); + assert!(result == ffi::kCGErrorSuccess, "failed to set video mode"); + + // After the display has been configured, fade back in + // asynchronously + if fade_token != ffi::kCGDisplayFadeReservationInvalidToken { + ffi::CGDisplayFade( + fade_token, + 0.6, + ffi::kCGDisplayBlendSolidColor, + ffi::kCGDisplayBlendNormal, + 0.0, + 0.0, + 0.0, + ffi::FALSE, + ); + ffi::CGReleaseDisplayFadeReservation(fade_token); + } + } + } + + trace!("Locked shared state in `set_fullscreen`"); + let mut shared_state_lock = self.shared_state.lock().unwrap(); + shared_state_lock.fullscreen = fullscreen.clone(); + trace!("Unlocked shared state in `set_fullscreen`"); + + match (&old_fullscreen, &fullscreen) { + (&None, &Some(_)) => unsafe { + util::toggle_full_screen_async( + *self.ns_window, + *self.ns_view, + old_fullscreen.is_none(), + Arc::downgrade(&self.shared_state), + ); + }, + (&Some(Fullscreen::Borderless(_)), &None) => unsafe { + // State is restored by `window_did_exit_fullscreen` + util::toggle_full_screen_async( + *self.ns_window, + *self.ns_view, + old_fullscreen.is_none(), + Arc::downgrade(&self.shared_state), + ); + }, + (&Some(Fullscreen::Exclusive(RootVideoMode { ref video_mode })), &None) => unsafe { + util::restore_display_mode_async(video_mode.monitor().inner.native_identifier()); + // Rest of the state is restored by `window_did_exit_fullscreen` + util::toggle_full_screen_async( + *self.ns_window, + *self.ns_view, + old_fullscreen.is_none(), + Arc::downgrade(&self.shared_state), + ); + }, + (&Some(Fullscreen::Borderless(_)), &Some(Fullscreen::Exclusive(_))) => unsafe { + // If we're already in fullscreen mode, calling + // `CGDisplayCapture` will place the shielding window on top of + // our window, which results in a black display and is not what + // we want. So, we must place our window on top of the shielding + // window. Unfortunately, this also makes our window be on top + // of the menu bar, and this looks broken, so we must make sure + // that the menu bar is disabled. This is done in the window + // delegate in `window:willUseFullScreenPresentationOptions:`. + let () = msg_send![*self.ns_window, setLevel: ffi::CGShieldingWindowLevel() + 1]; + }, + ( + &Some(Fullscreen::Exclusive(RootVideoMode { ref video_mode })), + &Some(Fullscreen::Borderless(_)), + ) => unsafe { + util::restore_display_mode_async(video_mode.monitor().inner.native_identifier()); + }, + _ => (), + } + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + if decorations != self.decorations.load(Ordering::Acquire) { + self.decorations.store(decorations, Ordering::Release); + + let (fullscreen, resizable) = { + trace!("Locked shared state in `set_decorations`"); + let shared_state_lock = self.shared_state.lock().unwrap(); + trace!("Unlocked shared state in `set_decorations`"); + ( + shared_state_lock.fullscreen.is_some(), + shared_state_lock.resizable, + ) + }; + + // If we're in fullscreen mode, we wait to apply decoration changes + // until we're in `window_did_exit_fullscreen`. + if fullscreen { + return; + } + + let new_mask = { + let mut new_mask = if decorations { + NSWindowStyleMask::NSClosableWindowMask + | NSWindowStyleMask::NSMiniaturizableWindowMask + | NSWindowStyleMask::NSResizableWindowMask + | NSWindowStyleMask::NSTitledWindowMask + } else { + NSWindowStyleMask::NSBorderlessWindowMask + | NSWindowStyleMask::NSResizableWindowMask + }; + if !resizable { + new_mask &= !NSWindowStyleMask::NSResizableWindowMask; + } + new_mask + }; + self.set_style_mask_async(new_mask); + } + } + + #[inline] + pub fn set_always_on_top(&self, always_on_top: bool) { + let level = if always_on_top { + ffi::NSWindowLevel::NSFloatingWindowLevel + } else { + ffi::NSWindowLevel::NSNormalWindowLevel + }; + unsafe { util::set_level_async(*self.ns_window, level) }; + } + + #[inline] + pub fn set_window_icon(&self, _icon: Option) { + // macOS doesn't have window icons. Though, there is + // `setRepresentedFilename`, but that's semantically distinct and should + // only be used when the window is in some way representing a specific + // file/directory. For instance, Terminal.app uses this for the CWD. + // Anyway, that should eventually be implemented as + // `WindowBuilderExt::with_represented_file` or something, and doesn't + // have anything to do with `set_window_icon`. + // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Tasks/SettingWindowTitle.html + } + + #[inline] + pub fn set_ime_position(&self, spot: Position) { + let scale_factor = self.scale_factor(); + let logical_spot = spot.to_logical(scale_factor); + unsafe { + view::set_ime_position( + *self.ns_view, + *self.input_context, + logical_spot.x, + logical_spot.y, + ); + } + } + + #[inline] + pub fn current_monitor(&self) -> RootMonitorHandle { + unsafe { + let screen: id = msg_send![*self.ns_window, screen]; + let desc = NSScreen::deviceDescription(screen); + let key = util::ns_string_id_ref("NSScreenNumber"); + let value = NSDictionary::valueForKey_(desc, *key); + let display_id = msg_send![value, unsignedIntegerValue]; + RootMonitorHandle { + inner: MonitorHandle::new(display_id), + } + } + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque { + monitor::available_monitors() + } + + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + monitor::primary_monitor() + } + + #[inline] + pub fn raw_window_handle(&self) -> RawWindowHandle { + let handle = MacOSHandle { + ns_window: *self.ns_window as *mut _, + ns_view: *self.ns_view as *mut _, + ..MacOSHandle::empty() + }; + RawWindowHandle::MacOS(handle) + } +} + +impl WindowExtMacOS for UnownedWindow { + #[inline] + fn ns_window(&self) -> *mut c_void { + *self.ns_window as *mut _ + } + + #[inline] + fn ns_view(&self) -> *mut c_void { + *self.ns_view as *mut _ + } + + #[inline] + fn request_user_attention(&self, request_type: RequestUserAttentionType) { + unsafe { + NSApp().requestUserAttention_(match request_type { + RequestUserAttentionType::Critical => NSRequestUserAttentionType::NSCriticalRequest, + RequestUserAttentionType::Informational => { + NSRequestUserAttentionType::NSInformationalRequest + } + }); + } + } + + #[inline] + fn simple_fullscreen(&self) -> bool { + let shared_state_lock = self.shared_state.lock().unwrap(); + shared_state_lock.is_simple_fullscreen + } + + #[inline] + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { + let mut shared_state_lock = self.shared_state.lock().unwrap(); + + unsafe { + let app = NSApp(); + let is_native_fullscreen = shared_state_lock.fullscreen.is_some(); + let is_simple_fullscreen = shared_state_lock.is_simple_fullscreen; + + // Do nothing if native fullscreen is active. + if is_native_fullscreen + || (fullscreen && is_simple_fullscreen) + || (!fullscreen && !is_simple_fullscreen) + { + return false; + } + + if fullscreen { + // Remember the original window's settings + // Exclude title bar + shared_state_lock.standard_frame = Some(NSWindow::contentRectForFrameRect_( + *self.ns_window, + NSWindow::frame(*self.ns_window), + )); + shared_state_lock.saved_style = Some(self.ns_window.styleMask()); + shared_state_lock.save_presentation_opts = Some(app.presentationOptions_()); + + // Tell our window's state that we're in fullscreen + shared_state_lock.is_simple_fullscreen = true; + + // Simulate pre-Lion fullscreen by hiding the dock and menu bar + let presentation_options = + NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock | + NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar; + app.setPresentationOptions_(presentation_options); + + // Hide the titlebar + util::toggle_style_mask( + *self.ns_window, + *self.ns_view, + NSWindowStyleMask::NSTitledWindowMask, + false, + ); + + // Set the window frame to the screen frame size + let screen = self.ns_window.screen(); + let screen_frame = NSScreen::frame(screen); + NSWindow::setFrame_display_(*self.ns_window, screen_frame, YES); + + // Fullscreen windows can't be resized, minimized, or moved + util::toggle_style_mask( + *self.ns_window, + *self.ns_view, + NSWindowStyleMask::NSMiniaturizableWindowMask, + false, + ); + util::toggle_style_mask( + *self.ns_window, + *self.ns_view, + NSWindowStyleMask::NSResizableWindowMask, + false, + ); + NSWindow::setMovable_(*self.ns_window, NO); + + true + } else { + let new_mask = self.saved_style(&mut *shared_state_lock); + self.set_style_mask_async(new_mask); + shared_state_lock.is_simple_fullscreen = false; + + if let Some(presentation_opts) = shared_state_lock.save_presentation_opts { + app.setPresentationOptions_(presentation_opts); + } + + let frame = shared_state_lock.saved_standard_frame(); + NSWindow::setFrame_display_(*self.ns_window, frame, YES); + NSWindow::setMovable_(*self.ns_window, YES); + + true + } + } + } +} + +impl Drop for UnownedWindow { + fn drop(&mut self) { + trace!("Dropping `UnownedWindow` ({:?})", self as *mut _); + // Close the window if it has not yet been closed. + if *self.ns_window != nil { + unsafe { util::close_async(*self.ns_window) }; + } + } +} + +unsafe fn set_min_inner_size(window: V, mut min_size: LogicalSize) { + let mut current_rect = NSWindow::frame(window); + let content_rect = NSWindow::contentRectForFrameRect_(window, NSWindow::frame(window)); + // Convert from client area size to window size + min_size.width += (current_rect.size.width - content_rect.size.width) as f64; // this tends to be 0 + min_size.height += (current_rect.size.height - content_rect.size.height) as f64; + window.setMinSize_(NSSize { + width: min_size.width as CGFloat, + height: min_size.height as CGFloat, + }); + // If necessary, resize the window to match constraint + if current_rect.size.width < min_size.width { + current_rect.size.width = min_size.width; + window.setFrame_display_(current_rect, 0) + } + if current_rect.size.height < min_size.height { + // The origin point of a rectangle is at its bottom left in Cocoa. + // To ensure the window's top-left point remains the same: + current_rect.origin.y += current_rect.size.height - min_size.height; + current_rect.size.height = min_size.height; + window.setFrame_display_(current_rect, 0) + } +} + +unsafe fn set_max_inner_size(window: V, mut max_size: LogicalSize) { + let mut current_rect = NSWindow::frame(window); + let content_rect = NSWindow::contentRectForFrameRect_(window, NSWindow::frame(window)); + // Convert from client area size to window size + max_size.width += (current_rect.size.width - content_rect.size.width) as f64; // this tends to be 0 + max_size.height += (current_rect.size.height - content_rect.size.height) as f64; + window.setMaxSize_(NSSize { + width: max_size.width as CGFloat, + height: max_size.height as CGFloat, + }); + // If necessary, resize the window to match constraint + if current_rect.size.width > max_size.width { + current_rect.size.width = max_size.width; + window.setFrame_display_(current_rect, 0) + } + if current_rect.size.height > max_size.height { + // The origin point of a rectangle is at its bottom left in Cocoa. + // To ensure the window's top-left point remains the same: + current_rect.origin.y += current_rect.size.height - max_size.height; + current_rect.size.height = max_size.height; + window.setFrame_display_(current_rect, 0) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window_delegate.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window_delegate.rs new file mode 100644 index 0000000..a89e99f --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/macos/window_delegate.rs @@ -0,0 +1,572 @@ +use std::{ + f64, + os::raw::c_void, + sync::{Arc, Weak}, +}; + +use cocoa::{ + appkit::{self, NSApplicationPresentationOptions, NSView, NSWindow}, + base::{id, nil}, + foundation::{NSAutoreleasePool, NSUInteger}, +}; +use objc::{ + declare::ClassDecl, + runtime::{Class, Object, Sel, BOOL, NO, YES}, +}; + +use crate::{ + dpi::LogicalSize, + event::{Event, ModifiersState, WindowEvent}, + platform_impl::platform::{ + app_state::AppState, + event::{EventProxy, EventWrapper}, + util::{self, IdRef}, + view::ViewState, + window::{get_window_id, UnownedWindow}, + }, + window::{Fullscreen, WindowId}, +}; + +pub struct WindowDelegateState { + ns_window: IdRef, // never changes + ns_view: IdRef, // never changes + + window: Weak, + + // TODO: It's possible for delegate methods to be called asynchronously, + // causing data races / `RefCell` panics. + + // This is set when WindowBuilder::with_fullscreen was set, + // see comments of `window_did_fail_to_enter_fullscreen` + initial_fullscreen: bool, + + // During `windowDidResize`, we use this to only send Moved if the position changed. + previous_position: Option<(f64, f64)>, + + // Used to prevent redundant events. + previous_scale_factor: f64, +} + +impl WindowDelegateState { + pub fn new(window: &Arc, initial_fullscreen: bool) -> Self { + let scale_factor = window.scale_factor(); + let mut delegate_state = WindowDelegateState { + ns_window: window.ns_window.clone(), + ns_view: window.ns_view.clone(), + window: Arc::downgrade(&window), + initial_fullscreen, + previous_position: None, + previous_scale_factor: scale_factor, + }; + + if scale_factor != 1.0 { + delegate_state.emit_static_scale_factor_changed_event(); + } + + delegate_state + } + + fn with_window(&mut self, callback: F) -> Option + where + F: FnOnce(&UnownedWindow) -> T, + { + self.window.upgrade().map(|ref window| callback(window)) + } + + pub fn emit_event(&mut self, event: WindowEvent<'static>) { + let event = Event::WindowEvent { + window_id: WindowId(get_window_id(*self.ns_window)), + event, + }; + AppState::queue_event(EventWrapper::StaticEvent(event)); + } + + pub fn emit_static_scale_factor_changed_event(&mut self) { + let scale_factor = self.get_scale_factor(); + if scale_factor == self.previous_scale_factor { + return (); + }; + + self.previous_scale_factor = scale_factor; + let wrapper = EventWrapper::EventProxy(EventProxy::DpiChangedProxy { + ns_window: IdRef::retain(*self.ns_window), + suggested_size: self.view_size(), + scale_factor, + }); + AppState::queue_event(wrapper); + } + + pub fn emit_resize_event(&mut self) { + let rect = unsafe { NSView::frame(*self.ns_view) }; + let scale_factor = self.get_scale_factor(); + let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64); + let size = logical_size.to_physical(scale_factor); + self.emit_event(WindowEvent::Resized(size)); + } + + fn emit_move_event(&mut self) { + let rect = unsafe { NSWindow::frame(*self.ns_window) }; + let x = rect.origin.x as f64; + let y = util::bottom_left_to_top_left(rect); + let moved = self.previous_position != Some((x, y)); + if moved { + self.previous_position = Some((x, y)); + self.emit_event(WindowEvent::Moved((x, y).into())); + } + } + + fn get_scale_factor(&self) -> f64 { + (unsafe { NSWindow::backingScaleFactor(*self.ns_window) }) as f64 + } + + fn view_size(&self) -> LogicalSize { + let ns_size = unsafe { NSView::frame(*self.ns_view).size }; + LogicalSize::new(ns_size.width as f64, ns_size.height as f64) + } +} + +pub fn new_delegate(window: &Arc, initial_fullscreen: bool) -> IdRef { + let state = WindowDelegateState::new(window, initial_fullscreen); + unsafe { + // This is free'd in `dealloc` + let state_ptr = Box::into_raw(Box::new(state)) as *mut c_void; + let delegate: id = msg_send![WINDOW_DELEGATE_CLASS.0, alloc]; + IdRef::new(msg_send![delegate, initWithWinit: state_ptr]) + } +} + +struct WindowDelegateClass(*const Class); +unsafe impl Send for WindowDelegateClass {} +unsafe impl Sync for WindowDelegateClass {} + +lazy_static! { + static ref WINDOW_DELEGATE_CLASS: WindowDelegateClass = unsafe { + let superclass = class!(NSResponder); + let mut decl = ClassDecl::new("WinitWindowDelegate", superclass).unwrap(); + + decl.add_method(sel!(dealloc), dealloc as extern "C" fn(&Object, Sel)); + decl.add_method( + sel!(initWithWinit:), + init_with_winit as extern "C" fn(&Object, Sel, *mut c_void) -> id, + ); + + decl.add_method( + sel!(windowShouldClose:), + window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL, + ); + decl.add_method( + sel!(windowWillClose:), + window_will_close as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidResize:), + window_did_resize as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidMove:), + window_did_move as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidChangeBackingProperties:), + window_did_change_backing_properties as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidBecomeKey:), + window_did_become_key as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidResignKey:), + window_did_resign_key as extern "C" fn(&Object, Sel, id), + ); + + decl.add_method( + sel!(draggingEntered:), + dragging_entered as extern "C" fn(&Object, Sel, id) -> BOOL, + ); + decl.add_method( + sel!(prepareForDragOperation:), + prepare_for_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL, + ); + decl.add_method( + sel!(performDragOperation:), + perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL, + ); + decl.add_method( + sel!(concludeDragOperation:), + conclude_drag_operation as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(draggingExited:), + dragging_exited as extern "C" fn(&Object, Sel, id), + ); + + decl.add_method( + sel!(window:willUseFullScreenPresentationOptions:), + window_will_use_fullscreen_presentation_options + as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger, + ); + decl.add_method( + sel!(windowDidEnterFullScreen:), + window_did_enter_fullscreen as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowWillEnterFullScreen:), + window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidExitFullScreen:), + window_did_exit_fullscreen as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowWillExitFullScreen:), + window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id), + ); + decl.add_method( + sel!(windowDidFailToEnterFullScreen:), + window_did_fail_to_enter_fullscreen as extern "C" fn(&Object, Sel, id), + ); + + decl.add_ivar::<*mut c_void>("winitState"); + WindowDelegateClass(decl.register()) + }; +} + +// This function is definitely unsafe, but labeling that would increase +// boilerplate and wouldn't really clarify anything... +fn with_state T, T>(this: &Object, callback: F) { + let state_ptr = unsafe { + let state_ptr: *mut c_void = *this.get_ivar("winitState"); + &mut *(state_ptr as *mut WindowDelegateState) + }; + callback(state_ptr); +} + +extern "C" fn dealloc(this: &Object, _sel: Sel) { + with_state(this, |state| unsafe { + Box::from_raw(state as *mut WindowDelegateState); + }); +} + +extern "C" fn init_with_winit(this: &Object, _sel: Sel, state: *mut c_void) -> id { + unsafe { + let this: id = msg_send![this, init]; + if this != nil { + (*this).set_ivar("winitState", state); + with_state(&*this, |state| { + let () = msg_send![*state.ns_window, setDelegate: this]; + }); + } + this + } +} + +extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL { + trace!("Triggered `windowShouldClose:`"); + with_state(this, |state| state.emit_event(WindowEvent::CloseRequested)); + trace!("Completed `windowShouldClose:`"); + NO +} + +extern "C" fn window_will_close(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowWillClose:`"); + with_state(this, |state| unsafe { + // `setDelegate:` retains the previous value and then autoreleases it + let pool = NSAutoreleasePool::new(nil); + // Since El Capitan, we need to be careful that delegate methods can't + // be called after the window closes. + let () = msg_send![*state.ns_window, setDelegate: nil]; + pool.drain(); + state.emit_event(WindowEvent::Destroyed); + }); + trace!("Completed `windowWillClose:`"); +} + +extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidResize:`"); + with_state(this, |state| { + state.emit_resize_event(); + state.emit_move_event(); + }); + trace!("Completed `windowDidResize:`"); +} + +// This won't be triggered if the move was part of a resize. +extern "C" fn window_did_move(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidMove:`"); + with_state(this, |state| { + state.emit_move_event(); + }); + trace!("Completed `windowDidMove:`"); +} + +extern "C" fn window_did_change_backing_properties(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidChangeBackingProperties:`"); + with_state(this, |state| { + state.emit_static_scale_factor_changed_event(); + }); + trace!("Completed `windowDidChangeBackingProperties:`"); +} + +extern "C" fn window_did_become_key(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidBecomeKey:`"); + with_state(this, |state| { + // TODO: center the cursor if the window had mouse grab when it + // lost focus + state.emit_event(WindowEvent::Focused(true)); + }); + trace!("Completed `windowDidBecomeKey:`"); +} + +extern "C" fn window_did_resign_key(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidResignKey:`"); + with_state(this, |state| { + // It happens rather often, e.g. when the user is Cmd+Tabbing, that the + // NSWindowDelegate will receive a didResignKey event despite no event + // being received when the modifiers are released. This is because + // flagsChanged events are received by the NSView instead of the + // NSWindowDelegate, and as a result a tracked modifiers state can quite + // easily fall out of synchrony with reality. This requires us to emit + // a synthetic ModifiersChanged event when we lose focus. + // + // Here we (very unsafely) acquire the winitState (a ViewState) from the + // Object referenced by state.ns_view (an IdRef, which is dereferenced + // to an id) + let view_state: &mut ViewState = unsafe { + let ns_view: &Object = (*state.ns_view).as_ref().expect("failed to deref"); + let state_ptr: *mut c_void = *ns_view.get_ivar("winitState"); + &mut *(state_ptr as *mut ViewState) + }; + + // Both update the state and emit a ModifiersChanged event. + if !view_state.modifiers.is_empty() { + view_state.modifiers = ModifiersState::empty(); + state.emit_event(WindowEvent::ModifiersChanged(view_state.modifiers)); + } + + state.emit_event(WindowEvent::Focused(false)); + }); + trace!("Completed `windowDidResignKey:`"); +} + +/// Invoked when the dragged image enters destination bounds or frame +extern "C" fn dragging_entered(this: &Object, _: Sel, sender: id) -> BOOL { + trace!("Triggered `draggingEntered:`"); + + use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; + use std::path::PathBuf; + + let pb: id = unsafe { msg_send![sender, draggingPasteboard] }; + let filenames = unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) }; + + for file in unsafe { filenames.iter() } { + use cocoa::foundation::NSString; + use std::ffi::CStr; + + unsafe { + let f = NSString::UTF8String(file); + let path = CStr::from_ptr(f).to_string_lossy().into_owned(); + + with_state(this, |state| { + state.emit_event(WindowEvent::HoveredFile(PathBuf::from(path))); + }); + } + } + + trace!("Completed `draggingEntered:`"); + YES +} + +/// Invoked when the image is released +extern "C" fn prepare_for_drag_operation(_: &Object, _: Sel, _: id) -> BOOL { + trace!("Triggered `prepareForDragOperation:`"); + trace!("Completed `prepareForDragOperation:`"); + YES +} + +/// Invoked after the released image has been removed from the screen +extern "C" fn perform_drag_operation(this: &Object, _: Sel, sender: id) -> BOOL { + trace!("Triggered `performDragOperation:`"); + + use cocoa::{appkit::NSPasteboard, foundation::NSFastEnumeration}; + use std::path::PathBuf; + + let pb: id = unsafe { msg_send![sender, draggingPasteboard] }; + let filenames = unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) }; + + for file in unsafe { filenames.iter() } { + use cocoa::foundation::NSString; + use std::ffi::CStr; + + unsafe { + let f = NSString::UTF8String(file); + let path = CStr::from_ptr(f).to_string_lossy().into_owned(); + + with_state(this, |state| { + state.emit_event(WindowEvent::DroppedFile(PathBuf::from(path))); + }); + } + } + + trace!("Completed `performDragOperation:`"); + YES +} + +/// Invoked when the dragging operation is complete +extern "C" fn conclude_drag_operation(_: &Object, _: Sel, _: id) { + trace!("Triggered `concludeDragOperation:`"); + trace!("Completed `concludeDragOperation:`"); +} + +/// Invoked when the dragging operation is cancelled +extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) { + trace!("Triggered `draggingExited:`"); + with_state(this, |state| { + state.emit_event(WindowEvent::HoveredFileCancelled) + }); + trace!("Completed `draggingExited:`"); +} + +/// Invoked when before enter fullscreen +extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowWillEnterFullscreen:`"); + with_state(this, |state| { + state.with_window(|window| { + trace!("Locked shared state in `window_will_enter_fullscreen`"); + let mut shared_state = window.shared_state.lock().unwrap(); + shared_state.maximized = window.is_zoomed(); + match shared_state.fullscreen { + // Exclusive mode sets the state in `set_fullscreen` as the user + // can't enter exclusive mode by other means (like the + // fullscreen button on the window decorations) + Some(Fullscreen::Exclusive(_)) => (), + // `window_will_enter_fullscreen` was triggered and we're already + // in fullscreen, so we must've reached here by `set_fullscreen` + // as it updates the state + Some(Fullscreen::Borderless(_)) => (), + // Otherwise, we must've reached fullscreen by the user clicking + // on the green fullscreen button. Update state! + None => { + shared_state.fullscreen = Some(Fullscreen::Borderless(window.current_monitor())) + } + } + shared_state.in_fullscreen_transition = true; + trace!("Unlocked shared state in `window_will_enter_fullscreen`"); + }) + }); + trace!("Completed `windowWillEnterFullscreen:`"); +} + +/// Invoked when before exit fullscreen +extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowWillExitFullScreen:`"); + with_state(this, |state| { + state.with_window(|window| { + trace!("Locked shared state in `window_will_exit_fullscreen`"); + let mut shared_state = window.shared_state.lock().unwrap(); + shared_state.in_fullscreen_transition = true; + trace!("Unlocked shared state in `window_will_exit_fullscreen`"); + }); + }); + trace!("Completed `windowWillExitFullScreen:`"); +} + +extern "C" fn window_will_use_fullscreen_presentation_options( + _this: &Object, + _: Sel, + _: id, + _proposed_options: NSUInteger, +) -> NSUInteger { + // Generally, games will want to disable the menu bar and the dock. Ideally, + // this would be configurable by the user. Unfortunately because of our + // `CGShieldingWindowLevel() + 1` hack (see `set_fullscreen`), our window is + // placed on top of the menu bar in exclusive fullscreen mode. This looks + // broken so we always disable the menu bar in exclusive fullscreen. We may + // still want to make this configurable for borderless fullscreen. Right now + // we don't, for consistency. If we do, it should be documented that the + // user-provided options are ignored in exclusive fullscreen. + (NSApplicationPresentationOptions::NSApplicationPresentationFullScreen + | NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar) + .bits() +} + +/// Invoked when entered fullscreen +extern "C" fn window_did_enter_fullscreen(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidEnterFullscreen:`"); + with_state(this, |state| { + state.initial_fullscreen = false; + state.with_window(|window| { + trace!("Locked shared state in `window_did_enter_fullscreen`"); + let mut shared_state = window.shared_state.lock().unwrap(); + shared_state.in_fullscreen_transition = false; + let target_fullscreen = shared_state.target_fullscreen.take(); + trace!("Unlocked shared state in `window_did_enter_fullscreen`"); + drop(shared_state); + if let Some(target_fullscreen) = target_fullscreen { + window.set_fullscreen(target_fullscreen); + } + }); + }); + trace!("Completed `windowDidEnterFullscreen:`"); +} + +/// Invoked when exited fullscreen +extern "C" fn window_did_exit_fullscreen(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidExitFullscreen:`"); + with_state(this, |state| { + state.with_window(|window| { + window.restore_state_from_fullscreen(); + trace!("Locked shared state in `window_did_exit_fullscreen`"); + let mut shared_state = window.shared_state.lock().unwrap(); + shared_state.in_fullscreen_transition = false; + let target_fullscreen = shared_state.target_fullscreen.take(); + trace!("Unlocked shared state in `window_did_exit_fullscreen`"); + drop(shared_state); + if let Some(target_fullscreen) = target_fullscreen { + window.set_fullscreen(target_fullscreen); + } + }) + }); + trace!("Completed `windowDidExitFullscreen:`"); +} + +/// Invoked when fail to enter fullscreen +/// +/// When this window launch from a fullscreen app (e.g. launch from VS Code +/// terminal), it creates a new virtual destkop and a transition animation. +/// This animation takes one second and cannot be disable without +/// elevated privileges. In this animation time, all toggleFullscreen events +/// will be failed. In this implementation, we will try again by using +/// performSelector:withObject:afterDelay: until window_did_enter_fullscreen. +/// It should be fine as we only do this at initialzation (i.e with_fullscreen +/// was set). +/// +/// From Apple doc: +/// In some cases, the transition to enter full-screen mode can fail, +/// due to being in the midst of handling some other animation or user gesture. +/// This method indicates that there was an error, and you should clean up any +/// work you may have done to prepare to enter full-screen mode. +extern "C" fn window_did_fail_to_enter_fullscreen(this: &Object, _: Sel, _: id) { + trace!("Triggered `windowDidFailToEnterFullscreen:`"); + with_state(this, |state| { + state.with_window(|window| { + trace!("Locked shared state in `window_did_fail_to_enter_fullscreen`"); + let mut shared_state = window.shared_state.lock().unwrap(); + shared_state.in_fullscreen_transition = false; + shared_state.target_fullscreen = None; + trace!("Unlocked shared state in `window_did_fail_to_enter_fullscreen`"); + }); + if state.initial_fullscreen { + let _: () = unsafe { + msg_send![*state.ns_window, + performSelector:sel!(toggleFullScreen:) + withObject:nil + afterDelay: 0.5 + ] + }; + } else { + state.with_window(|window| window.restore_state_from_fullscreen()); + } + }); + trace!("Completed `windowDidFailToEnterFullscreen:`"); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/mod.rs new file mode 100644 index 0000000..152065d --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/mod.rs @@ -0,0 +1,40 @@ +pub use self::platform::*; + +#[cfg(target_os = "windows")] +#[path = "windows/mod.rs"] +mod platform; +#[cfg(any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd" +))] +#[path = "linux/mod.rs"] +mod platform; +#[cfg(target_os = "macos")] +#[path = "macos/mod.rs"] +mod platform; +#[cfg(target_os = "android")] +#[path = "android/mod.rs"] +mod platform; +#[cfg(target_os = "ios")] +#[path = "ios/mod.rs"] +mod platform; +#[cfg(target_arch = "wasm32")] +#[path = "web/mod.rs"] +mod platform; + +#[cfg(all( + not(target_os = "ios"), + not(target_os = "windows"), + not(target_os = "linux"), + not(target_os = "macos"), + not(target_os = "android"), + not(target_os = "dragonfly"), + not(target_os = "freebsd"), + not(target_os = "netbsd"), + not(target_os = "openbsd"), + not(target_arch = "wasm32"), +))] +compile_error!("The platform you're compiling for is not supported by winit"); diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/device.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/device.rs new file mode 100644 index 0000000..a2f00b6 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/device.rs @@ -0,0 +1,8 @@ +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Id(pub i32); + +impl Id { + pub unsafe fn dummy() -> Self { + Id(0) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/error.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/error.rs new file mode 100644 index 0000000..6995f2b --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/error.rs @@ -0,0 +1,10 @@ +use std::fmt; + +#[derive(Debug)] +pub struct OsError(pub String); + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/mod.rs new file mode 100644 index 0000000..50640a1 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/mod.rs @@ -0,0 +1,68 @@ +mod proxy; +mod runner; +mod state; +mod window_target; + +pub use self::proxy::Proxy; +pub use self::window_target::WindowTarget; + +use super::{backend, device, monitor, window}; +use crate::event::Event; +use crate::event_loop as root; + +use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque}; +use std::marker::PhantomData; + +pub struct EventLoop { + elw: root::EventLoopWindowTarget, +} + +impl EventLoop { + pub fn new() -> Self { + EventLoop { + elw: root::EventLoopWindowTarget { + p: WindowTarget::new(), + _marker: PhantomData, + }, + } + } + + pub fn available_monitors(&self) -> VecDequeIter { + VecDeque::new().into_iter() + } + + pub fn primary_monitor(&self) -> monitor::Handle { + monitor::Handle + } + + pub fn run(self, mut event_handler: F) -> ! + where + F: 'static + + FnMut(Event<'static, T>, &root::EventLoopWindowTarget, &mut root::ControlFlow), + { + let target = root::EventLoopWindowTarget { + p: self.elw.p.clone(), + _marker: PhantomData, + }; + + self.elw.p.run(Box::new(move |event, flow| { + event_handler(event, &target, flow) + })); + + // Throw an exception to break out of Rust exceution and use unreachable to tell the + // compiler this function won't return, giving it a return type of '!' + backend::throw( + "Using exceptions for control flow, don't mind me. This isn't actually an error!", + ); + + unreachable!(); + } + + pub fn create_proxy(&self) -> Proxy { + self.elw.p.proxy() + } + + pub fn window_target(&self) -> &root::EventLoopWindowTarget { + &self.elw + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/proxy.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/proxy.rs new file mode 100644 index 0000000..6e569c0 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/proxy.rs @@ -0,0 +1,26 @@ +use super::runner; +use crate::event::Event; +use crate::event_loop::EventLoopClosed; + +pub struct Proxy { + runner: runner::Shared, +} + +impl Proxy { + pub fn new(runner: runner::Shared) -> Self { + Proxy { runner } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + self.runner.send_event(Event::UserEvent(event)); + Ok(()) + } +} + +impl Clone for Proxy { + fn clone(&self) -> Self { + Proxy { + runner: self.runner.clone(), + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/runner.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/runner.rs new file mode 100644 index 0000000..398fcaf --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/runner.rs @@ -0,0 +1,295 @@ +use super::{backend, state::State}; +use crate::event::{Event, StartCause}; +use crate::event_loop as root; +use crate::window::WindowId; + +use instant::{Duration, Instant}; +use std::{ + cell::RefCell, + clone::Clone, + collections::{HashSet, VecDeque}, + iter, + rc::Rc, +}; + +pub struct Shared(Rc>); + +impl Clone for Shared { + fn clone(&self) -> Self { + Shared(self.0.clone()) + } +} + +pub struct Execution { + runner: RefCell>>, + events: RefCell>>, + id: RefCell, + redraw_pending: RefCell>, +} + +struct Runner { + state: State, + is_busy: bool, + event_handler: Box, &mut root::ControlFlow)>, +} + +impl Runner { + pub fn new(event_handler: Box, &mut root::ControlFlow)>) -> Self { + Runner { + state: State::Init, + is_busy: false, + event_handler, + } + } +} + +impl Shared { + pub fn new() -> Self { + Shared(Rc::new(Execution { + runner: RefCell::new(None), + events: RefCell::new(VecDeque::new()), + id: RefCell::new(0), + redraw_pending: RefCell::new(HashSet::new()), + })) + } + + // Set the event callback to use for the event loop runner + // This the event callback is a fairly thin layer over the user-provided callback that closes + // over a RootEventLoopWindowTarget reference + pub fn set_listener( + &self, + event_handler: Box, &mut root::ControlFlow)>, + ) { + self.0.runner.replace(Some(Runner::new(event_handler))); + self.init(); + + let close_instance = self.clone(); + backend::on_unload(move || close_instance.handle_unload()); + } + + // Generate a strictly increasing ID + // This is used to differentiate windows when handling events + pub fn generate_id(&self) -> u32 { + let mut id = self.0.id.borrow_mut(); + *id += 1; + + *id + } + + pub fn request_redraw(&self, id: WindowId) { + self.0.redraw_pending.borrow_mut().insert(id); + } + + pub fn init(&self) { + let start_cause = Event::NewEvents(StartCause::Init); + self.run_until_cleared(iter::once(start_cause)); + } + + // Run the polling logic for the Poll ControlFlow, which involves clearing the queue + pub fn poll(&self) { + let start_cause = Event::NewEvents(StartCause::Poll); + self.run_until_cleared(iter::once(start_cause)); + } + + // Run the logic for waking from a WaitUntil, which involves clearing the queue + // Generally there shouldn't be events built up when this is called + pub fn resume_time_reached(&self, start: Instant, requested_resume: Instant) { + let start_cause = Event::NewEvents(StartCause::ResumeTimeReached { + start, + requested_resume, + }); + self.run_until_cleared(iter::once(start_cause)); + } + + // Add an event to the event loop runner, from the user or an event handler + // + // It will determine if the event should be immediately sent to the user or buffered for later + pub fn send_event(&self, event: Event<'static, T>) { + self.send_events(iter::once(event)); + } + + // Add a series of events to the event loop runner + // + // It will determine if the event should be immediately sent to the user or buffered for later + pub fn send_events(&self, events: impl Iterator>) { + // If the event loop is closed, it should discard any new events + if self.is_closed() { + return; + } + // If we can run the event processing right now, or need to queue this and wait for later + let mut process_immediately = true; + if let Some(ref runner) = &*self.0.runner.borrow() { + // If we're currently polling, queue this and wait for the poll() method to be called + if let State::Poll { .. } = runner.state { + process_immediately = false; + } + // If the runner is busy, queue this and wait for it to process it later + if runner.is_busy { + process_immediately = false; + } + } else { + // The runner still hasn't been attached: queue this event and wait for it to be + process_immediately = false; + } + if !process_immediately { + // Queue these events to look at later + self.0.events.borrow_mut().extend(events); + return; + } + // At this point, we know this is a fresh set of events + // Now we determine why new events are incoming, and handle the events + let start_cause = if let Some(runner) = &*self.0.runner.borrow() { + match runner.state { + State::Init => StartCause::Init, + State::Poll { .. } => StartCause::Poll, + State::Wait { start } => StartCause::WaitCancelled { + start, + requested_resume: None, + }, + State::WaitUntil { start, end, .. } => StartCause::WaitCancelled { + start, + requested_resume: Some(end), + }, + State::Exit => { + // If we're in the exit state, don't do event processing + return; + } + } + } else { + unreachable!("The runner cannot process events when it is not attached"); + }; + // Take the start event, then the events provided to this function, and run an iteration of + // the event loop + let start_event = Event::NewEvents(start_cause); + let events = iter::once(start_event).chain(events); + self.run_until_cleared(events); + } + + // Given the set of new events, run the event loop until the main events and redraw events are + // cleared + // + // This will also process any events that have been queued or that are queued during processing + fn run_until_cleared(&self, events: impl Iterator>) { + let mut control = self.current_control_flow(); + for event in events { + self.handle_event(event, &mut control); + } + self.handle_event(Event::MainEventsCleared, &mut control); + + // Collect all of the redraw events to avoid double-locking the RefCell + let redraw_events: Vec = self.0.redraw_pending.borrow_mut().drain().collect(); + for window_id in redraw_events { + self.handle_event(Event::RedrawRequested(window_id), &mut control); + } + self.handle_event(Event::RedrawEventsCleared, &mut control); + + self.apply_control_flow(control); + // If the event loop is closed, it has been closed this iteration and now the closing + // event should be emitted + if self.is_closed() { + self.handle_event(Event::LoopDestroyed, &mut control); + } + } + + fn handle_unload(&self) { + self.apply_control_flow(root::ControlFlow::Exit); + let mut control = self.current_control_flow(); + self.handle_event(Event::LoopDestroyed, &mut control); + } + + // handle_event takes in events and either queues them or applies a callback + // + // It should only ever be called from send_event + fn handle_event(&self, event: Event<'static, T>, control: &mut root::ControlFlow) { + let is_closed = self.is_closed(); + + match *self.0.runner.borrow_mut() { + Some(ref mut runner) => { + // An event is being processed, so the runner should be marked busy + runner.is_busy = true; + + (runner.event_handler)(event, control); + + // Maintain closed state, even if the callback changes it + if is_closed { + *control = root::ControlFlow::Exit; + } + + // An event is no longer being processed + runner.is_busy = false; + } + // If an event is being handled without a runner somehow, add it to the event queue so + // it will eventually be processed + _ => self.0.events.borrow_mut().push_back(event), + } + + // Don't take events out of the queue if the loop is closed or the runner doesn't exist + // If the runner doesn't exist and this method recurses, it will recurse infinitely + if !is_closed && self.0.runner.borrow().is_some() { + // Take an event out of the queue and handle it + if let Some(event) = self.0.events.borrow_mut().pop_front() { + self.handle_event(event, control); + } + } + } + + // Apply the new ControlFlow that has been selected by the user + // Start any necessary timeouts etc + fn apply_control_flow(&self, control_flow: root::ControlFlow) { + let new_state = match control_flow { + root::ControlFlow::Poll => { + let cloned = self.clone(); + State::Poll { + timeout: backend::Timeout::new(move || cloned.poll(), Duration::from_millis(0)), + } + } + root::ControlFlow::Wait => State::Wait { + start: Instant::now(), + }, + root::ControlFlow::WaitUntil(end) => { + let start = Instant::now(); + + let delay = if end <= start { + Duration::from_millis(0) + } else { + end - start + }; + + let cloned = self.clone(); + + State::WaitUntil { + start, + end, + timeout: backend::Timeout::new( + move || cloned.resume_time_reached(start, end), + delay, + ), + } + } + root::ControlFlow::Exit => State::Exit, + }; + + match *self.0.runner.borrow_mut() { + Some(ref mut runner) => { + runner.state = new_state; + } + None => (), + } + } + + // Check if the event loop is currently closed + fn is_closed(&self) -> bool { + match *self.0.runner.borrow() { + Some(ref runner) => runner.state.is_exit(), + None => false, // If the event loop is None, it has not been intialised yet, so it cannot be closed + } + } + + // Get the current control flow state + fn current_control_flow(&self) -> root::ControlFlow { + match *self.0.runner.borrow() { + Some(ref runner) => runner.state.control_flow(), + None => root::ControlFlow::Poll, + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/state.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/state.rs new file mode 100644 index 0000000..23e8045 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/state.rs @@ -0,0 +1,40 @@ +use super::backend; +use crate::event_loop::ControlFlow; + +use instant::Instant; + +#[derive(Debug)] +pub enum State { + Init, + WaitUntil { + timeout: backend::Timeout, + start: Instant, + end: Instant, + }, + Wait { + start: Instant, + }, + Poll { + timeout: backend::Timeout, + }, + Exit, +} + +impl State { + pub fn is_exit(&self) -> bool { + match self { + State::Exit => true, + _ => false, + } + } + + pub fn control_flow(&self) -> ControlFlow { + match self { + State::Init => ControlFlow::Poll, + State::WaitUntil { end, .. } => ControlFlow::WaitUntil(*end), + State::Wait { .. } => ControlFlow::Wait, + State::Poll { .. } => ControlFlow::Poll, + State::Exit => ControlFlow::Exit, + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/window_target.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/window_target.rs new file mode 100644 index 0000000..db485a1 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/event_loop/window_target.rs @@ -0,0 +1,216 @@ +use super::{backend, device, proxy::Proxy, runner, window}; +use crate::dpi::{PhysicalSize, Size}; +use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent}; +use crate::event_loop::ControlFlow; +use crate::window::{Theme, WindowId}; +use std::clone::Clone; + +pub struct WindowTarget { + pub(crate) runner: runner::Shared, +} + +impl Clone for WindowTarget { + fn clone(&self) -> Self { + WindowTarget { + runner: self.runner.clone(), + } + } +} + +impl WindowTarget { + pub fn new() -> Self { + WindowTarget { + runner: runner::Shared::new(), + } + } + + pub fn proxy(&self) -> Proxy { + Proxy::new(self.runner.clone()) + } + + pub fn run(&self, event_handler: Box, &mut ControlFlow)>) { + self.runner.set_listener(event_handler); + } + + pub fn generate_id(&self) -> window::Id { + window::Id(self.runner.generate_id()) + } + + pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) { + let runner = self.runner.clone(); + canvas.set_attribute("data-raw-handle", &id.0.to_string()); + + canvas.on_blur(move || { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::Focused(false), + }); + }); + + let runner = self.runner.clone(); + canvas.on_focus(move || { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::Focused(true), + }); + }); + + let runner = self.runner.clone(); + canvas.on_keyboard_press(move |scancode, virtual_keycode, modifiers| { + #[allow(deprecated)] + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::KeyboardInput { + device_id: DeviceId(unsafe { device::Id::dummy() }), + input: KeyboardInput { + scancode, + state: ElementState::Pressed, + virtual_keycode, + modifiers, + }, + is_synthetic: false, + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_keyboard_release(move |scancode, virtual_keycode, modifiers| { + #[allow(deprecated)] + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::KeyboardInput { + device_id: DeviceId(unsafe { device::Id::dummy() }), + input: KeyboardInput { + scancode, + state: ElementState::Released, + virtual_keycode, + modifiers, + }, + is_synthetic: false, + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_received_character(move |char_code| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::ReceivedCharacter(char_code), + }); + }); + + let runner = self.runner.clone(); + canvas.on_cursor_leave(move |pointer_id| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::CursorLeft { + device_id: DeviceId(device::Id(pointer_id)), + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_cursor_enter(move |pointer_id| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::CursorEntered { + device_id: DeviceId(device::Id(pointer_id)), + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_cursor_move(move |pointer_id, position, modifiers| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::CursorMoved { + device_id: DeviceId(device::Id(pointer_id)), + position, + modifiers, + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_mouse_press(move |pointer_id, button, modifiers| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::MouseInput { + device_id: DeviceId(device::Id(pointer_id)), + state: ElementState::Pressed, + button, + modifiers, + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_mouse_release(move |pointer_id, button, modifiers| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::MouseInput { + device_id: DeviceId(device::Id(pointer_id)), + state: ElementState::Released, + button, + modifiers, + }, + }); + }); + + let runner = self.runner.clone(); + canvas.on_mouse_wheel(move |pointer_id, delta, modifiers| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::MouseWheel { + device_id: DeviceId(device::Id(pointer_id)), + delta, + phase: TouchPhase::Moved, + modifiers, + }, + }); + }); + + let runner = self.runner.clone(); + let raw = canvas.raw().clone(); + + // The size to restore to after exiting fullscreen. + let mut intended_size = PhysicalSize { + width: raw.width() as u32, + height: raw.height() as u32, + }; + canvas.on_fullscreen_change(move || { + // If the canvas is marked as fullscreen, it is moving *into* fullscreen + // If it is not, it is moving *out of* fullscreen + let new_size = if backend::is_fullscreen(&raw) { + intended_size = PhysicalSize { + width: raw.width() as u32, + height: raw.height() as u32, + }; + + backend::window_size().to_physical(backend::scale_factor()) + } else { + intended_size + }; + + backend::set_canvas_size(&raw, Size::Physical(new_size)); + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::Resized(new_size), + }); + runner.request_redraw(WindowId(id)); + }); + + let runner = self.runner.clone(); + canvas.on_dark_mode(move |is_dark_mode| { + let theme = if is_dark_mode { + Theme::Dark + } else { + Theme::Light + }; + runner.send_event(Event::WindowEvent { + window_id: WindowId(id), + event: WindowEvent::ThemeChanged(theme), + }); + }); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/mod.rs new file mode 100644 index 0000000..43bbb2a --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/mod.rs @@ -0,0 +1,48 @@ +// Brief introduction to the internals of the web backend: +// Currently, the web backend supports both wasm-bindgen and stdweb as methods of binding to the +// environment. Because they are both supporting the same underlying APIs, the actual web bindings +// are cordoned off into backend abstractions, which present the thinnest unifying layer possible. +// +// When adding support for new events or interactions with the browser, first consult trusted +// documentation (such as MDN) to ensure it is well-standardised and supported across many browsers. +// Once you have decided on the relevant web APIs, add support to both backends. +// +// The backend is used by the rest of the module to implement Winit's business logic, which forms +// the rest of the code. 'device', 'error', 'monitor', and 'window' define web-specific structures +// for winit's cross-platform structures. They are all relatively simple translations. +// +// The event_loop module handles listening for and processing events. 'Proxy' implements +// EventLoopProxy and 'WindowTarget' implements EventLoopWindowTarget. WindowTarget also handles +// registering the event handlers. The 'Execution' struct in the 'runner' module handles taking +// incoming events (from the registered handlers) and ensuring they are passed to the user in a +// compliant way. + +mod device; +mod error; +mod event_loop; +mod monitor; +mod window; + +#[cfg(feature = "web-sys")] +#[path = "web_sys/mod.rs"] +mod backend; + +#[cfg(feature = "stdweb")] +#[path = "stdweb/mod.rs"] +mod backend; + +#[cfg(not(any(feature = "web-sys", feature = "stdweb")))] +compile_error!("Please select a feature to build for web: `web-sys`, `stdweb`"); + +pub use self::device::Id as DeviceId; +pub use self::error::OsError; +pub use self::event_loop::{ + EventLoop, Proxy as EventLoopProxy, WindowTarget as EventLoopWindowTarget, +}; +pub use self::monitor::{Handle as MonitorHandle, Mode as VideoMode}; +pub use self::window::{ + Id as WindowId, PlatformSpecificBuilderAttributes as PlatformSpecificWindowBuilderAttributes, + Window, +}; + +pub(crate) use crate::icon::NoIcon as PlatformIcon; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/monitor.rs new file mode 100644 index 0000000..d2b3c36 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/monitor.rs @@ -0,0 +1,51 @@ +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::monitor::{MonitorHandle, VideoMode}; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Handle; + +impl Handle { + pub fn scale_factor(&self) -> f64 { + 1.0 + } + + pub fn position(&self) -> PhysicalPosition { + PhysicalPosition { x: 0, y: 0 } + } + + pub fn name(&self) -> Option { + None + } + + pub fn size(&self) -> PhysicalSize { + PhysicalSize { + width: 0, + height: 0, + } + } + + pub fn video_modes(&self) -> impl Iterator { + std::iter::empty() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Mode; + +impl Mode { + pub fn size(&self) -> PhysicalSize { + unimplemented!(); + } + + pub fn bit_depth(&self) -> u16 { + unimplemented!(); + } + + pub fn refresh_rate(&self) -> u16 { + 32 + } + + pub fn monitor(&self) -> MonitorHandle { + MonitorHandle { inner: Handle } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/canvas.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/canvas.rs new file mode 100644 index 0000000..f6ed486 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/canvas.rs @@ -0,0 +1,301 @@ +use super::event; +use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; +use crate::error::OsError as RootOE; +use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode}; +use crate::platform_impl::{OsError, PlatformSpecificWindowBuilderAttributes}; + +use std::cell::RefCell; +use std::rc::Rc; +use stdweb::js; +use stdweb::traits::IPointerEvent; +use stdweb::unstable::TryInto; +use stdweb::web::event::{ + BlurEvent, ConcreteEvent, FocusEvent, FullscreenChangeEvent, KeyDownEvent, KeyPressEvent, + KeyUpEvent, MouseWheelEvent, PointerDownEvent, PointerMoveEvent, PointerOutEvent, + PointerOverEvent, PointerUpEvent, +}; +use stdweb::web::html_element::CanvasElement; +use stdweb::web::{ + document, EventListenerHandle, IChildNode, IElement, IEventTarget, IHtmlElement, +}; + +pub struct Canvas { + /// Note: resizing the CanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained. + raw: CanvasElement, + on_focus: Option, + on_blur: Option, + on_keyboard_release: Option, + on_keyboard_press: Option, + on_received_character: Option, + on_cursor_leave: Option, + on_cursor_enter: Option, + on_cursor_move: Option, + on_mouse_press: Option, + on_mouse_release: Option, + on_mouse_wheel: Option, + on_fullscreen_change: Option, + wants_fullscreen: Rc>, +} + +impl Drop for Canvas { + fn drop(&mut self) { + self.raw.remove(); + } +} + +impl Canvas { + pub fn create(attr: PlatformSpecificWindowBuilderAttributes) -> Result { + let canvas = match attr.canvas { + Some(canvas) => canvas, + None => document() + .create_element("canvas") + .map_err(|_| os_error!(OsError("Failed to create canvas element".to_owned())))? + .try_into() + .map_err(|_| os_error!(OsError("Failed to create canvas element".to_owned())))?, + }; + + // A tabindex is needed in order to capture local keyboard events. + // A "0" value means that the element should be focusable in + // sequential keyboard navigation, but its order is defined by the + // document's source order. + // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex + canvas + .set_attribute("tabindex", "0") + .map_err(|_| os_error!(OsError("Failed to set a tabindex".to_owned())))?; + + Ok(Canvas { + raw: canvas, + on_blur: None, + on_focus: None, + on_keyboard_release: None, + on_keyboard_press: None, + on_received_character: None, + on_cursor_leave: None, + on_cursor_enter: None, + on_cursor_move: None, + on_mouse_release: None, + on_mouse_press: None, + on_mouse_wheel: None, + on_fullscreen_change: None, + wants_fullscreen: Rc::new(RefCell::new(false)), + }) + } + + pub fn set_attribute(&self, attribute: &str, value: &str) { + self.raw + .set_attribute(attribute, value) + .expect(&format!("Set attribute: {}", attribute)); + } + + pub fn position(&self) -> LogicalPosition { + let bounds = self.raw.get_bounding_client_rect(); + + LogicalPosition { + x: bounds.get_x(), + y: bounds.get_y(), + } + } + + pub fn size(&self) -> PhysicalSize { + PhysicalSize { + width: self.raw.width() as u32, + height: self.raw.height() as u32, + } + } + + pub fn raw(&self) -> &CanvasElement { + &self.raw + } + + pub fn on_blur(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_blur = Some(self.add_event(move |_: BlurEvent| { + handler(); + })); + } + + pub fn on_focus(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_focus = Some(self.add_event(move |_: FocusEvent| { + handler(); + })); + } + + pub fn on_keyboard_release(&mut self, mut handler: F) + where + F: 'static + FnMut(ScanCode, Option, ModifiersState), + { + self.on_keyboard_release = Some(self.add_user_event(move |event: KeyUpEvent| { + handler( + event::scan_code(&event), + event::virtual_key_code(&event), + event::keyboard_modifiers(&event), + ); + })); + } + + pub fn on_keyboard_press(&mut self, mut handler: F) + where + F: 'static + FnMut(ScanCode, Option, ModifiersState), + { + self.on_keyboard_press = Some(self.add_user_event(move |event: KeyDownEvent| { + handler( + event::scan_code(&event), + event::virtual_key_code(&event), + event::keyboard_modifiers(&event), + ); + })); + } + + pub fn on_received_character(&mut self, mut handler: F) + where + F: 'static + FnMut(char), + { + // TODO: Use `beforeinput`. + // + // The `keypress` event is deprecated, but there does not seem to be a + // viable/compatible alternative as of now. `beforeinput` is still widely + // unsupported. + self.on_received_character = Some(self.add_user_event(move |event: KeyPressEvent| { + handler(event::codepoint(&event)); + })); + } + + pub fn on_cursor_leave(&mut self, mut handler: F) + where + F: 'static + FnMut(i32), + { + self.on_cursor_leave = Some(self.add_event(move |event: PointerOutEvent| { + handler(event.pointer_id()); + })); + } + + pub fn on_cursor_enter(&mut self, mut handler: F) + where + F: 'static + FnMut(i32), + { + self.on_cursor_enter = Some(self.add_event(move |event: PointerOverEvent| { + handler(event.pointer_id()); + })); + } + + pub fn on_mouse_release(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseButton, ModifiersState), + { + self.on_mouse_release = Some(self.add_user_event(move |event: PointerUpEvent| { + handler( + event.pointer_id(), + event::mouse_button(&event), + event::mouse_modifiers(&event), + ); + })); + } + + pub fn on_mouse_press(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseButton, ModifiersState), + { + self.on_mouse_press = Some(self.add_user_event(move |event: PointerDownEvent| { + handler( + event.pointer_id(), + event::mouse_button(&event), + event::mouse_modifiers(&event), + ); + })); + } + + pub fn on_cursor_move(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, PhysicalPosition, ModifiersState), + { + // todo + self.on_cursor_move = Some(self.add_event(move |event: PointerMoveEvent| { + handler( + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor()), + event::mouse_modifiers(&event), + ); + })); + } + + pub fn on_mouse_wheel(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState), + { + self.on_mouse_wheel = Some(self.add_event(move |event: MouseWheelEvent| { + if let Some(delta) = event::mouse_scroll_delta(&event) { + handler(0, delta, event::mouse_modifiers(&event)); + } + })); + } + + pub fn on_fullscreen_change(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_fullscreen_change = Some(self.add_event(move |_: FullscreenChangeEvent| handler())); + } + + pub fn on_dark_mode(&mut self, handler: F) + where + F: 'static + FnMut(bool), + { + // TODO: upstream to stdweb + js! { + var handler = @{handler}; + + if (window.matchMedia) { + window.matchMedia("(prefers-color-scheme: dark)").addListener(function(e) { + handler(event.matches) + }); + } + } + } + + fn add_event(&self, mut handler: F) -> EventListenerHandle + where + E: ConcreteEvent, + F: 'static + FnMut(E), + { + self.raw.add_event_listener(move |event: E| { + event.stop_propagation(); + event.cancel_bubble(); + + handler(event); + }) + } + + // The difference between add_event and add_user_event is that the latter has a special meaning + // for browser security. A user event is a deliberate action by the user (like a mouse or key + // press) and is the only time things like a fullscreen request may be successfully completed.) + fn add_user_event(&self, mut handler: F) -> EventListenerHandle + where + E: ConcreteEvent, + F: 'static + FnMut(E), + { + let wants_fullscreen = self.wants_fullscreen.clone(); + let canvas = self.raw.clone(); + + self.add_event(move |event: E| { + handler(event); + + if *wants_fullscreen.borrow() { + canvas.request_fullscreen(); + *wants_fullscreen.borrow_mut() = false; + } + }) + } + + pub fn request_fullscreen(&self) { + *self.wants_fullscreen.borrow_mut() = true; + } + + pub fn is_fullscreen(&self) -> bool { + super::is_fullscreen(&self.raw) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/event.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/event.rs new file mode 100644 index 0000000..8c534dc --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/event.rs @@ -0,0 +1,229 @@ +use crate::dpi::LogicalPosition; +use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode}; + +use stdweb::web::event::{IKeyboardEvent, IMouseEvent, MouseWheelDeltaMode, MouseWheelEvent}; +use stdweb::{js, unstable::TryInto, JsSerialize}; + +pub fn mouse_button(event: &impl IMouseEvent) -> MouseButton { + match event.button() { + stdweb::web::event::MouseButton::Left => MouseButton::Left, + stdweb::web::event::MouseButton::Right => MouseButton::Right, + stdweb::web::event::MouseButton::Wheel => MouseButton::Middle, + stdweb::web::event::MouseButton::Button4 => MouseButton::Other(0), + stdweb::web::event::MouseButton::Button5 => MouseButton::Other(1), + } +} + +pub fn mouse_modifiers(event: &impl IMouseEvent) -> ModifiersState { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, event.shift_key()); + m.set(ModifiersState::CTRL, event.ctrl_key()); + m.set(ModifiersState::ALT, event.alt_key()); + m.set(ModifiersState::LOGO, event.meta_key()); + m +} + +pub fn mouse_position(event: &impl IMouseEvent) -> LogicalPosition { + LogicalPosition { + x: event.offset_x() as f64, + y: event.offset_y() as f64, + } +} + +pub fn mouse_scroll_delta(event: &MouseWheelEvent) -> Option { + let x = event.delta_x(); + let y = event.delta_y(); + + match event.delta_mode() { + MouseWheelDeltaMode::Line => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)), + MouseWheelDeltaMode::Pixel => Some(MouseScrollDelta::PixelDelta(LogicalPosition { x, y })), + MouseWheelDeltaMode::Page => None, + } +} + +pub fn scan_code(event: &T) -> ScanCode { + let key_code = js! ( return @{event}.keyCode; ); + + key_code + .try_into() + .expect("The which value should be a number") +} + +pub fn virtual_key_code(event: &impl IKeyboardEvent) -> Option { + Some(match &event.code()[..] { + "Digit1" => VirtualKeyCode::Key1, + "Digit2" => VirtualKeyCode::Key2, + "Digit3" => VirtualKeyCode::Key3, + "Digit4" => VirtualKeyCode::Key4, + "Digit5" => VirtualKeyCode::Key5, + "Digit6" => VirtualKeyCode::Key6, + "Digit7" => VirtualKeyCode::Key7, + "Digit8" => VirtualKeyCode::Key8, + "Digit9" => VirtualKeyCode::Key9, + "Digit0" => VirtualKeyCode::Key0, + "KeyA" => VirtualKeyCode::A, + "KeyB" => VirtualKeyCode::B, + "KeyC" => VirtualKeyCode::C, + "KeyD" => VirtualKeyCode::D, + "KeyE" => VirtualKeyCode::E, + "KeyF" => VirtualKeyCode::F, + "KeyG" => VirtualKeyCode::G, + "KeyH" => VirtualKeyCode::H, + "KeyI" => VirtualKeyCode::I, + "KeyJ" => VirtualKeyCode::J, + "KeyK" => VirtualKeyCode::K, + "KeyL" => VirtualKeyCode::L, + "KeyM" => VirtualKeyCode::M, + "KeyN" => VirtualKeyCode::N, + "KeyO" => VirtualKeyCode::O, + "KeyP" => VirtualKeyCode::P, + "KeyQ" => VirtualKeyCode::Q, + "KeyR" => VirtualKeyCode::R, + "KeyS" => VirtualKeyCode::S, + "KeyT" => VirtualKeyCode::T, + "KeyU" => VirtualKeyCode::U, + "KeyV" => VirtualKeyCode::V, + "KeyW" => VirtualKeyCode::W, + "KeyX" => VirtualKeyCode::X, + "KeyY" => VirtualKeyCode::Y, + "KeyZ" => VirtualKeyCode::Z, + "Escape" => VirtualKeyCode::Escape, + "F1" => VirtualKeyCode::F1, + "F2" => VirtualKeyCode::F2, + "F3" => VirtualKeyCode::F3, + "F4" => VirtualKeyCode::F4, + "F5" => VirtualKeyCode::F5, + "F6" => VirtualKeyCode::F6, + "F7" => VirtualKeyCode::F7, + "F8" => VirtualKeyCode::F8, + "F9" => VirtualKeyCode::F9, + "F10" => VirtualKeyCode::F10, + "F11" => VirtualKeyCode::F11, + "F12" => VirtualKeyCode::F12, + "F13" => VirtualKeyCode::F13, + "F14" => VirtualKeyCode::F14, + "F15" => VirtualKeyCode::F15, + "F16" => VirtualKeyCode::F16, + "F17" => VirtualKeyCode::F17, + "F18" => VirtualKeyCode::F18, + "F19" => VirtualKeyCode::F19, + "F20" => VirtualKeyCode::F20, + "F21" => VirtualKeyCode::F21, + "F22" => VirtualKeyCode::F22, + "F23" => VirtualKeyCode::F23, + "F24" => VirtualKeyCode::F24, + "PrintScreen" => VirtualKeyCode::Snapshot, + "ScrollLock" => VirtualKeyCode::Scroll, + "Pause" => VirtualKeyCode::Pause, + "Insert" => VirtualKeyCode::Insert, + "Home" => VirtualKeyCode::Home, + "Delete" => VirtualKeyCode::Delete, + "End" => VirtualKeyCode::End, + "PageDown" => VirtualKeyCode::PageDown, + "PageUp" => VirtualKeyCode::PageUp, + "ArrowLeft" => VirtualKeyCode::Left, + "ArrowUp" => VirtualKeyCode::Up, + "ArrowRight" => VirtualKeyCode::Right, + "ArrowDown" => VirtualKeyCode::Down, + "Backspace" => VirtualKeyCode::Back, + "Enter" => VirtualKeyCode::Return, + "Space" => VirtualKeyCode::Space, + "Compose" => VirtualKeyCode::Compose, + "Caret" => VirtualKeyCode::Caret, + "NumLock" => VirtualKeyCode::Numlock, + "Numpad0" => VirtualKeyCode::Numpad0, + "Numpad1" => VirtualKeyCode::Numpad1, + "Numpad2" => VirtualKeyCode::Numpad2, + "Numpad3" => VirtualKeyCode::Numpad3, + "Numpad4" => VirtualKeyCode::Numpad4, + "Numpad5" => VirtualKeyCode::Numpad5, + "Numpad6" => VirtualKeyCode::Numpad6, + "Numpad7" => VirtualKeyCode::Numpad7, + "Numpad8" => VirtualKeyCode::Numpad8, + "Numpad9" => VirtualKeyCode::Numpad9, + "AbntC1" => VirtualKeyCode::AbntC1, + "AbntC2" => VirtualKeyCode::AbntC2, + "NumpadAdd" => VirtualKeyCode::Add, + "Quote" => VirtualKeyCode::Apostrophe, + "Apps" => VirtualKeyCode::Apps, + "At" => VirtualKeyCode::At, + "Ax" => VirtualKeyCode::Ax, + "Backslash" => VirtualKeyCode::Backslash, + "Calculator" => VirtualKeyCode::Calculator, + "Capital" => VirtualKeyCode::Capital, + "Semicolon" => VirtualKeyCode::Semicolon, + "Comma" => VirtualKeyCode::Comma, + "Convert" => VirtualKeyCode::Convert, + "NumpadDecimal" => VirtualKeyCode::Decimal, + "NumpadDivide" => VirtualKeyCode::Divide, + "Equal" => VirtualKeyCode::Equals, + "Backquote" => VirtualKeyCode::Grave, + "Kana" => VirtualKeyCode::Kana, + "Kanji" => VirtualKeyCode::Kanji, + "AltLeft" => VirtualKeyCode::LAlt, + "BracketLeft" => VirtualKeyCode::LBracket, + "ControlLeft" => VirtualKeyCode::LControl, + "ShiftLeft" => VirtualKeyCode::LShift, + "MetaLeft" => VirtualKeyCode::LWin, + "Mail" => VirtualKeyCode::Mail, + "MediaSelect" => VirtualKeyCode::MediaSelect, + "MediaStop" => VirtualKeyCode::MediaStop, + "Minus" => VirtualKeyCode::Minus, + "NumpadMultiply" => VirtualKeyCode::Multiply, + "Mute" => VirtualKeyCode::Mute, + "LaunchMyComputer" => VirtualKeyCode::MyComputer, + "NavigateForward" => VirtualKeyCode::NavigateForward, + "NavigateBackward" => VirtualKeyCode::NavigateBackward, + "NextTrack" => VirtualKeyCode::NextTrack, + "NoConvert" => VirtualKeyCode::NoConvert, + "NumpadComma" => VirtualKeyCode::NumpadComma, + "NumpadEnter" => VirtualKeyCode::NumpadEnter, + "NumpadEquals" => VirtualKeyCode::NumpadEquals, + "OEM102" => VirtualKeyCode::OEM102, + "Period" => VirtualKeyCode::Period, + "PlayPause" => VirtualKeyCode::PlayPause, + "Power" => VirtualKeyCode::Power, + "PrevTrack" => VirtualKeyCode::PrevTrack, + "AltRight" => VirtualKeyCode::RAlt, + "BracketRight" => VirtualKeyCode::RBracket, + "ControlRight" => VirtualKeyCode::RControl, + "ShiftRight" => VirtualKeyCode::RShift, + "MetaRight" => VirtualKeyCode::RWin, + "Slash" => VirtualKeyCode::Slash, + "Sleep" => VirtualKeyCode::Sleep, + "Stop" => VirtualKeyCode::Stop, + "NumpadSubtract" => VirtualKeyCode::Subtract, + "Sysrq" => VirtualKeyCode::Sysrq, + "Tab" => VirtualKeyCode::Tab, + "Underline" => VirtualKeyCode::Underline, + "Unlabeled" => VirtualKeyCode::Unlabeled, + "AudioVolumeDown" => VirtualKeyCode::VolumeDown, + "AudioVolumeUp" => VirtualKeyCode::VolumeUp, + "Wake" => VirtualKeyCode::Wake, + "WebBack" => VirtualKeyCode::WebBack, + "WebFavorites" => VirtualKeyCode::WebFavorites, + "WebForward" => VirtualKeyCode::WebForward, + "WebHome" => VirtualKeyCode::WebHome, + "WebRefresh" => VirtualKeyCode::WebRefresh, + "WebSearch" => VirtualKeyCode::WebSearch, + "WebStop" => VirtualKeyCode::WebStop, + "Yen" => VirtualKeyCode::Yen, + _ => return None, + }) +} + +pub fn keyboard_modifiers(event: &impl IKeyboardEvent) -> ModifiersState { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, event.shift_key()); + m.set(ModifiersState::CTRL, event.ctrl_key()); + m.set(ModifiersState::ALT, event.alt_key()); + m.set(ModifiersState::LOGO, event.meta_key()); + m +} + +pub fn codepoint(event: &impl IKeyboardEvent) -> char { + // `event.key()` always returns a non-empty `String`. Therefore, this should + // never panic. + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key + event.key().chars().next().unwrap() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/mod.rs new file mode 100644 index 0000000..a95dfc7 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/mod.rs @@ -0,0 +1,86 @@ +mod canvas; +mod event; +mod timeout; + +pub use self::canvas::Canvas; +pub use self::timeout::Timeout; + +use crate::dpi::{LogicalSize, Size}; +use crate::platform::web::WindowExtStdweb; +use crate::window::Window; + +use stdweb::js; +use stdweb::unstable::TryInto; +use stdweb::web::event::BeforeUnloadEvent; +use stdweb::web::window; +use stdweb::web::IEventTarget; +use stdweb::web::{document, html_element::CanvasElement, Element}; + +pub fn throw(msg: &str) { + js! { throw @{msg} } +} + +pub fn exit_fullscreen() { + document().exit_fullscreen(); +} + +pub fn on_unload(mut handler: impl FnMut() + 'static) { + window().add_event_listener(move |_: BeforeUnloadEvent| handler()); +} + +impl WindowExtStdweb for Window { + fn canvas(&self) -> CanvasElement { + self.window.canvas().raw().clone() + } + + fn is_dark_mode(&self) -> bool { + // TODO: upstream to stdweb + let is_dark_mode = js! { + return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) + }; + + is_dark_mode.try_into().expect("should return a bool") + } +} + +pub fn window_size() -> LogicalSize { + let window = window(); + let width = window.inner_width() as f64; + let height = window.inner_height() as f64; + + LogicalSize { width, height } +} + +pub fn scale_factor() -> f64 { + let window = window(); + window.device_pixel_ratio() +} + +pub fn set_canvas_size(raw: &CanvasElement, size: Size) { + use stdweb::*; + + let scale_factor = scale_factor(); + + let physical_size = size.to_physical::(scale_factor); + let logical_size = size.to_logical::(scale_factor); + + raw.set_width(physical_size.width); + raw.set_height(physical_size.height); + + js! { + @{raw.as_ref()}.style.width = @{logical_size.width} + "px"; + @{raw.as_ref()}.style.height = @{logical_size.height} + "px"; + } +} + +pub fn is_fullscreen(canvas: &CanvasElement) -> bool { + match document().fullscreen_element() { + Some(elem) => { + let raw: Element = canvas.clone().into(); + raw == elem + } + None => false, + } +} + +pub type RawCanvasType = CanvasElement; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/timeout.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/timeout.rs new file mode 100644 index 0000000..00ac2ab --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/stdweb/timeout.rs @@ -0,0 +1,25 @@ +use std::time::Duration; +use stdweb::web::{window, IWindowOrWorker, TimeoutHandle}; + +#[derive(Debug)] +pub struct Timeout { + handle: Option, +} + +impl Timeout { + pub fn new(f: F, duration: Duration) -> Timeout + where + F: 'static + FnMut(), + { + Timeout { + handle: Some(window().set_clearable_timeout(f, duration.as_millis() as u32)), + } + } +} + +impl Drop for Timeout { + fn drop(&mut self) { + let handle = self.handle.take().unwrap(); + handle.clear(); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/canvas.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/canvas.rs new file mode 100644 index 0000000..a2755b9 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/canvas.rs @@ -0,0 +1,333 @@ +use super::event; +use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; +use crate::error::OsError as RootOE; +use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode}; +use crate::platform_impl::{OsError, PlatformSpecificWindowBuilderAttributes}; + +use std::cell::RefCell; +use std::rc::Rc; + +use wasm_bindgen::{closure::Closure, JsCast}; +use web_sys::{ + Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, MediaQueryListEvent, PointerEvent, + WheelEvent, +}; + +pub struct Canvas { + /// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure the DPI factor is maintained. + raw: HtmlCanvasElement, + on_focus: Option>, + on_blur: Option>, + on_keyboard_release: Option>, + on_keyboard_press: Option>, + on_received_character: Option>, + on_cursor_leave: Option>, + on_cursor_enter: Option>, + on_cursor_move: Option>, + on_mouse_press: Option>, + on_mouse_release: Option>, + on_mouse_wheel: Option>, + on_fullscreen_change: Option>, + wants_fullscreen: Rc>, + on_dark_mode: Option>, +} + +impl Drop for Canvas { + fn drop(&mut self) { + self.raw.remove(); + } +} + +impl Canvas { + pub fn create(attr: PlatformSpecificWindowBuilderAttributes) -> Result { + let canvas = match attr.canvas { + Some(canvas) => canvas, + None => { + let window = web_sys::window() + .ok_or(os_error!(OsError("Failed to obtain window".to_owned())))?; + + let document = window + .document() + .ok_or(os_error!(OsError("Failed to obtain document".to_owned())))?; + + document + .create_element("canvas") + .map_err(|_| os_error!(OsError("Failed to create canvas element".to_owned())))? + .unchecked_into() + } + }; + + // A tabindex is needed in order to capture local keyboard events. + // A "0" value means that the element should be focusable in + // sequential keyboard navigation, but its order is defined by the + // document's source order. + // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex + canvas + .set_attribute("tabindex", "0") + .map_err(|_| os_error!(OsError("Failed to set a tabindex".to_owned())))?; + + Ok(Canvas { + raw: canvas, + on_blur: None, + on_focus: None, + on_keyboard_release: None, + on_keyboard_press: None, + on_received_character: None, + on_cursor_leave: None, + on_cursor_enter: None, + on_cursor_move: None, + on_mouse_release: None, + on_mouse_press: None, + on_mouse_wheel: None, + on_fullscreen_change: None, + wants_fullscreen: Rc::new(RefCell::new(false)), + on_dark_mode: None, + }) + } + + pub fn set_attribute(&self, attribute: &str, value: &str) { + self.raw + .set_attribute(attribute, value) + .expect(&format!("Set attribute: {}", attribute)); + } + + pub fn position(&self) -> LogicalPosition { + let bounds = self.raw.get_bounding_client_rect(); + + LogicalPosition { + x: bounds.x(), + y: bounds.y(), + } + } + + pub fn size(&self) -> PhysicalSize { + PhysicalSize { + width: self.raw.width(), + height: self.raw.height(), + } + } + + pub fn raw(&self) -> &HtmlCanvasElement { + &self.raw + } + + pub fn on_blur(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_blur = Some(self.add_event("blur", move |_: FocusEvent| { + handler(); + })); + } + + pub fn on_focus(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_focus = Some(self.add_event("focus", move |_: FocusEvent| { + handler(); + })); + } + + pub fn on_keyboard_release(&mut self, mut handler: F) + where + F: 'static + FnMut(ScanCode, Option, ModifiersState), + { + self.on_keyboard_release = + Some(self.add_user_event("keyup", move |event: KeyboardEvent| { + handler( + event::scan_code(&event), + event::virtual_key_code(&event), + event::keyboard_modifiers(&event), + ); + })); + } + + pub fn on_keyboard_press(&mut self, mut handler: F) + where + F: 'static + FnMut(ScanCode, Option, ModifiersState), + { + self.on_keyboard_press = + Some(self.add_user_event("keydown", move |event: KeyboardEvent| { + handler( + event::scan_code(&event), + event::virtual_key_code(&event), + event::keyboard_modifiers(&event), + ); + })); + } + + pub fn on_received_character(&mut self, mut handler: F) + where + F: 'static + FnMut(char), + { + // TODO: Use `beforeinput`. + // + // The `keypress` event is deprecated, but there does not seem to be a + // viable/compatible alternative as of now. `beforeinput` is still widely + // unsupported. + self.on_received_character = Some(self.add_user_event( + "keypress", + move |event: KeyboardEvent| { + handler(event::codepoint(&event)); + }, + )); + } + + pub fn on_cursor_leave(&mut self, mut handler: F) + where + F: 'static + FnMut(i32), + { + self.on_cursor_leave = Some(self.add_event("pointerout", move |event: PointerEvent| { + handler(event.pointer_id()); + })); + } + + pub fn on_cursor_enter(&mut self, mut handler: F) + where + F: 'static + FnMut(i32), + { + self.on_cursor_enter = Some(self.add_event("pointerover", move |event: PointerEvent| { + handler(event.pointer_id()); + })); + } + + pub fn on_mouse_release(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseButton, ModifiersState), + { + self.on_mouse_release = Some(self.add_user_event( + "pointerup", + move |event: PointerEvent| { + handler( + event.pointer_id(), + event::mouse_button(&event), + event::mouse_modifiers(&event), + ); + }, + )); + } + + pub fn on_mouse_press(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseButton, ModifiersState), + { + self.on_mouse_press = Some(self.add_user_event( + "pointerdown", + move |event: PointerEvent| { + handler( + event.pointer_id(), + event::mouse_button(&event), + event::mouse_modifiers(&event), + ); + }, + )); + } + + pub fn on_cursor_move(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, PhysicalPosition, ModifiersState), + { + self.on_cursor_move = Some(self.add_event("pointermove", move |event: PointerEvent| { + handler( + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor()), + event::mouse_modifiers(&event), + ); + })); + } + + pub fn on_mouse_wheel(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState), + { + self.on_mouse_wheel = Some(self.add_event("wheel", move |event: WheelEvent| { + if let Some(delta) = event::mouse_scroll_delta(&event) { + handler(0, delta, event::mouse_modifiers(&event)); + } + })); + } + + pub fn on_fullscreen_change(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_fullscreen_change = + Some(self.add_event("fullscreenchange", move |_: Event| handler())); + } + + pub fn on_dark_mode(&mut self, mut handler: F) + where + F: 'static + FnMut(bool), + { + let window = web_sys::window().expect("Failed to obtain window"); + + self.on_dark_mode = window + .match_media("(prefers-color-scheme: dark)") + .ok() + .flatten() + .and_then(|media| { + let closure = Closure::wrap(Box::new(move |event: MediaQueryListEvent| { + handler(event.matches()) + }) as Box); + + media + .add_listener_with_opt_callback(Some(&closure.as_ref().unchecked_ref())) + .map(|_| closure) + .ok() + }); + } + + fn add_event(&self, event_name: &str, mut handler: F) -> Closure + where + E: 'static + AsRef + wasm_bindgen::convert::FromWasmAbi, + F: 'static + FnMut(E), + { + let closure = Closure::wrap(Box::new(move |event: E| { + { + let event_ref = event.as_ref(); + event_ref.stop_propagation(); + event_ref.cancel_bubble(); + } + + handler(event); + }) as Box); + + self.raw + .add_event_listener_with_callback(event_name, &closure.as_ref().unchecked_ref()) + .expect("Failed to add event listener with callback"); + + closure + } + + // The difference between add_event and add_user_event is that the latter has a special meaning + // for browser security. A user event is a deliberate action by the user (like a mouse or key + // press) and is the only time things like a fullscreen request may be successfully completed.) + fn add_user_event(&self, event_name: &str, mut handler: F) -> Closure + where + E: 'static + AsRef + wasm_bindgen::convert::FromWasmAbi, + F: 'static + FnMut(E), + { + let wants_fullscreen = self.wants_fullscreen.clone(); + let canvas = self.raw.clone(); + + self.add_event(event_name, move |event: E| { + handler(event); + + if *wants_fullscreen.borrow() { + canvas + .request_fullscreen() + .expect("Failed to enter fullscreen"); + *wants_fullscreen.borrow_mut() = false; + } + }) + } + + pub fn request_fullscreen(&self) { + *self.wants_fullscreen.borrow_mut() = true; + } + + pub fn is_fullscreen(&self) -> bool { + super::is_fullscreen(&self.raw) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/event.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/event.rs new file mode 100644 index 0000000..1c1bdba --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/event.rs @@ -0,0 +1,227 @@ +use crate::dpi::LogicalPosition; +use crate::event::{ModifiersState, MouseButton, MouseScrollDelta, ScanCode, VirtualKeyCode}; + +use std::convert::TryInto; +use web_sys::{KeyboardEvent, MouseEvent, WheelEvent}; + +pub fn mouse_button(event: &MouseEvent) -> MouseButton { + match event.button() { + 0 => MouseButton::Left, + 1 => MouseButton::Middle, + 2 => MouseButton::Right, + i => MouseButton::Other((i - 3).try_into().expect("very large mouse button value")), + } +} + +pub fn mouse_modifiers(event: &MouseEvent) -> ModifiersState { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, event.shift_key()); + m.set(ModifiersState::CTRL, event.ctrl_key()); + m.set(ModifiersState::ALT, event.alt_key()); + m.set(ModifiersState::LOGO, event.meta_key()); + m +} + +pub fn mouse_position(event: &MouseEvent) -> LogicalPosition { + LogicalPosition { + x: event.offset_x() as f64, + y: event.offset_y() as f64, + } +} + +pub fn mouse_scroll_delta(event: &WheelEvent) -> Option { + let x = event.delta_x(); + let y = event.delta_y(); + + match event.delta_mode() { + WheelEvent::DOM_DELTA_LINE => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)), + WheelEvent::DOM_DELTA_PIXEL => Some(MouseScrollDelta::PixelDelta(LogicalPosition { x, y })), + _ => None, + } +} + +pub fn scan_code(event: &KeyboardEvent) -> ScanCode { + match event.key_code() { + 0 => event.char_code(), + i => i, + } +} + +pub fn virtual_key_code(event: &KeyboardEvent) -> Option { + Some(match &event.code()[..] { + "Digit1" => VirtualKeyCode::Key1, + "Digit2" => VirtualKeyCode::Key2, + "Digit3" => VirtualKeyCode::Key3, + "Digit4" => VirtualKeyCode::Key4, + "Digit5" => VirtualKeyCode::Key5, + "Digit6" => VirtualKeyCode::Key6, + "Digit7" => VirtualKeyCode::Key7, + "Digit8" => VirtualKeyCode::Key8, + "Digit9" => VirtualKeyCode::Key9, + "Digit0" => VirtualKeyCode::Key0, + "KeyA" => VirtualKeyCode::A, + "KeyB" => VirtualKeyCode::B, + "KeyC" => VirtualKeyCode::C, + "KeyD" => VirtualKeyCode::D, + "KeyE" => VirtualKeyCode::E, + "KeyF" => VirtualKeyCode::F, + "KeyG" => VirtualKeyCode::G, + "KeyH" => VirtualKeyCode::H, + "KeyI" => VirtualKeyCode::I, + "KeyJ" => VirtualKeyCode::J, + "KeyK" => VirtualKeyCode::K, + "KeyL" => VirtualKeyCode::L, + "KeyM" => VirtualKeyCode::M, + "KeyN" => VirtualKeyCode::N, + "KeyO" => VirtualKeyCode::O, + "KeyP" => VirtualKeyCode::P, + "KeyQ" => VirtualKeyCode::Q, + "KeyR" => VirtualKeyCode::R, + "KeyS" => VirtualKeyCode::S, + "KeyT" => VirtualKeyCode::T, + "KeyU" => VirtualKeyCode::U, + "KeyV" => VirtualKeyCode::V, + "KeyW" => VirtualKeyCode::W, + "KeyX" => VirtualKeyCode::X, + "KeyY" => VirtualKeyCode::Y, + "KeyZ" => VirtualKeyCode::Z, + "Escape" => VirtualKeyCode::Escape, + "F1" => VirtualKeyCode::F1, + "F2" => VirtualKeyCode::F2, + "F3" => VirtualKeyCode::F3, + "F4" => VirtualKeyCode::F4, + "F5" => VirtualKeyCode::F5, + "F6" => VirtualKeyCode::F6, + "F7" => VirtualKeyCode::F7, + "F8" => VirtualKeyCode::F8, + "F9" => VirtualKeyCode::F9, + "F10" => VirtualKeyCode::F10, + "F11" => VirtualKeyCode::F11, + "F12" => VirtualKeyCode::F12, + "F13" => VirtualKeyCode::F13, + "F14" => VirtualKeyCode::F14, + "F15" => VirtualKeyCode::F15, + "F16" => VirtualKeyCode::F16, + "F17" => VirtualKeyCode::F17, + "F18" => VirtualKeyCode::F18, + "F19" => VirtualKeyCode::F19, + "F20" => VirtualKeyCode::F20, + "F21" => VirtualKeyCode::F21, + "F22" => VirtualKeyCode::F22, + "F23" => VirtualKeyCode::F23, + "F24" => VirtualKeyCode::F24, + "PrintScreen" => VirtualKeyCode::Snapshot, + "ScrollLock" => VirtualKeyCode::Scroll, + "Pause" => VirtualKeyCode::Pause, + "Insert" => VirtualKeyCode::Insert, + "Home" => VirtualKeyCode::Home, + "Delete" => VirtualKeyCode::Delete, + "End" => VirtualKeyCode::End, + "PageDown" => VirtualKeyCode::PageDown, + "PageUp" => VirtualKeyCode::PageUp, + "ArrowLeft" => VirtualKeyCode::Left, + "ArrowUp" => VirtualKeyCode::Up, + "ArrowRight" => VirtualKeyCode::Right, + "ArrowDown" => VirtualKeyCode::Down, + "Backspace" => VirtualKeyCode::Back, + "Enter" => VirtualKeyCode::Return, + "Space" => VirtualKeyCode::Space, + "Compose" => VirtualKeyCode::Compose, + "Caret" => VirtualKeyCode::Caret, + "NumLock" => VirtualKeyCode::Numlock, + "Numpad0" => VirtualKeyCode::Numpad0, + "Numpad1" => VirtualKeyCode::Numpad1, + "Numpad2" => VirtualKeyCode::Numpad2, + "Numpad3" => VirtualKeyCode::Numpad3, + "Numpad4" => VirtualKeyCode::Numpad4, + "Numpad5" => VirtualKeyCode::Numpad5, + "Numpad6" => VirtualKeyCode::Numpad6, + "Numpad7" => VirtualKeyCode::Numpad7, + "Numpad8" => VirtualKeyCode::Numpad8, + "Numpad9" => VirtualKeyCode::Numpad9, + "AbntC1" => VirtualKeyCode::AbntC1, + "AbntC2" => VirtualKeyCode::AbntC2, + "NumpadAdd" => VirtualKeyCode::Add, + "Quote" => VirtualKeyCode::Apostrophe, + "Apps" => VirtualKeyCode::Apps, + "At" => VirtualKeyCode::At, + "Ax" => VirtualKeyCode::Ax, + "Backslash" => VirtualKeyCode::Backslash, + "Calculator" => VirtualKeyCode::Calculator, + "Capital" => VirtualKeyCode::Capital, + "Semicolon" => VirtualKeyCode::Semicolon, + "Comma" => VirtualKeyCode::Comma, + "Convert" => VirtualKeyCode::Convert, + "NumpadDecimal" => VirtualKeyCode::Decimal, + "NumpadDivide" => VirtualKeyCode::Divide, + "Equal" => VirtualKeyCode::Equals, + "Backquote" => VirtualKeyCode::Grave, + "Kana" => VirtualKeyCode::Kana, + "Kanji" => VirtualKeyCode::Kanji, + "AltLeft" => VirtualKeyCode::LAlt, + "BracketLeft" => VirtualKeyCode::LBracket, + "ControlLeft" => VirtualKeyCode::LControl, + "ShiftLeft" => VirtualKeyCode::LShift, + "MetaLeft" => VirtualKeyCode::LWin, + "Mail" => VirtualKeyCode::Mail, + "MediaSelect" => VirtualKeyCode::MediaSelect, + "MediaStop" => VirtualKeyCode::MediaStop, + "Minus" => VirtualKeyCode::Minus, + "NumpadMultiply" => VirtualKeyCode::Multiply, + "Mute" => VirtualKeyCode::Mute, + "LaunchMyComputer" => VirtualKeyCode::MyComputer, + "NavigateForward" => VirtualKeyCode::NavigateForward, + "NavigateBackward" => VirtualKeyCode::NavigateBackward, + "NextTrack" => VirtualKeyCode::NextTrack, + "NoConvert" => VirtualKeyCode::NoConvert, + "NumpadComma" => VirtualKeyCode::NumpadComma, + "NumpadEnter" => VirtualKeyCode::NumpadEnter, + "NumpadEquals" => VirtualKeyCode::NumpadEquals, + "OEM102" => VirtualKeyCode::OEM102, + "Period" => VirtualKeyCode::Period, + "PlayPause" => VirtualKeyCode::PlayPause, + "Power" => VirtualKeyCode::Power, + "PrevTrack" => VirtualKeyCode::PrevTrack, + "AltRight" => VirtualKeyCode::RAlt, + "BracketRight" => VirtualKeyCode::RBracket, + "ControlRight" => VirtualKeyCode::RControl, + "ShiftRight" => VirtualKeyCode::RShift, + "MetaRight" => VirtualKeyCode::RWin, + "Slash" => VirtualKeyCode::Slash, + "Sleep" => VirtualKeyCode::Sleep, + "Stop" => VirtualKeyCode::Stop, + "NumpadSubtract" => VirtualKeyCode::Subtract, + "Sysrq" => VirtualKeyCode::Sysrq, + "Tab" => VirtualKeyCode::Tab, + "Underline" => VirtualKeyCode::Underline, + "Unlabeled" => VirtualKeyCode::Unlabeled, + "AudioVolumeDown" => VirtualKeyCode::VolumeDown, + "AudioVolumeUp" => VirtualKeyCode::VolumeUp, + "Wake" => VirtualKeyCode::Wake, + "WebBack" => VirtualKeyCode::WebBack, + "WebFavorites" => VirtualKeyCode::WebFavorites, + "WebForward" => VirtualKeyCode::WebForward, + "WebHome" => VirtualKeyCode::WebHome, + "WebRefresh" => VirtualKeyCode::WebRefresh, + "WebSearch" => VirtualKeyCode::WebSearch, + "WebStop" => VirtualKeyCode::WebStop, + "Yen" => VirtualKeyCode::Yen, + _ => return None, + }) +} + +pub fn keyboard_modifiers(event: &KeyboardEvent) -> ModifiersState { + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, event.shift_key()); + m.set(ModifiersState::CTRL, event.ctrl_key()); + m.set(ModifiersState::ALT, event.alt_key()); + m.set(ModifiersState::LOGO, event.meta_key()); + m +} + +pub fn codepoint(event: &KeyboardEvent) -> char { + // `event.key()` always returns a non-empty `String`. Therefore, this should + // never panic. + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key + event.key().chars().next().unwrap() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/mod.rs new file mode 100644 index 0000000..c41cd06 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/mod.rs @@ -0,0 +1,106 @@ +mod canvas; +mod event; +mod timeout; + +pub use self::canvas::Canvas; +pub use self::timeout::Timeout; + +use crate::dpi::{LogicalSize, Size}; +use crate::platform::web::WindowExtWebSys; +use crate::window::Window; +use wasm_bindgen::{closure::Closure, JsCast}; +use web_sys::{window, BeforeUnloadEvent, Element, HtmlCanvasElement}; + +pub fn throw(msg: &str) { + wasm_bindgen::throw_str(msg); +} + +pub fn exit_fullscreen() { + let window = web_sys::window().expect("Failed to obtain window"); + let document = window.document().expect("Failed to obtain document"); + + document.exit_fullscreen(); +} + +pub fn on_unload(mut handler: impl FnMut() + 'static) { + let window = web_sys::window().expect("Failed to obtain window"); + + let closure = Closure::wrap( + Box::new(move |_: BeforeUnloadEvent| handler()) as Box + ); + + window + .add_event_listener_with_callback("beforeunload", &closure.as_ref().unchecked_ref()) + .expect("Failed to add close listener"); +} + +impl WindowExtWebSys for Window { + fn canvas(&self) -> HtmlCanvasElement { + self.window.canvas().raw().clone() + } + + fn is_dark_mode(&self) -> bool { + let window = web_sys::window().expect("Failed to obtain window"); + + window + .match_media("(prefers-color-scheme: dark)") + .ok() + .flatten() + .map(|media| media.matches()) + .unwrap_or(false) + } +} + +pub fn window_size() -> LogicalSize { + let window = web_sys::window().expect("Failed to obtain window"); + let width = window + .inner_width() + .expect("Failed to get width") + .as_f64() + .expect("Failed to get width as f64"); + let height = window + .inner_height() + .expect("Failed to get height") + .as_f64() + .expect("Failed to get height as f64"); + + LogicalSize { width, height } +} + +pub fn scale_factor() -> f64 { + let window = web_sys::window().expect("Failed to obtain window"); + window.device_pixel_ratio() +} + +pub fn set_canvas_size(raw: &HtmlCanvasElement, size: Size) { + let scale_factor = scale_factor(); + + let physical_size = size.to_physical::(scale_factor); + let logical_size = size.to_logical::(scale_factor); + + raw.set_width(physical_size.width); + raw.set_height(physical_size.height); + + let style = raw.style(); + style + .set_property("width", &format!("{}px", logical_size.width)) + .expect("Failed to set canvas width"); + style + .set_property("height", &format!("{}px", logical_size.height)) + .expect("Failed to set canvas height"); +} + +pub fn is_fullscreen(canvas: &HtmlCanvasElement) -> bool { + let window = window().expect("Failed to obtain window"); + let document = window.document().expect("Failed to obtain document"); + + match document.fullscreen_element() { + Some(elem) => { + let raw: Element = canvas.clone().into(); + raw == elem + } + None => false, + } +} + +pub type RawCanvasType = HtmlCanvasElement; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/timeout.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/timeout.rs new file mode 100644 index 0000000..e7ce69a --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/web_sys/timeout.rs @@ -0,0 +1,40 @@ +use std::time::Duration; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::JsCast; + +#[derive(Debug)] +pub struct Timeout { + handle: i32, + _closure: Closure, +} + +impl Timeout { + pub fn new(f: F, duration: Duration) -> Timeout + where + F: 'static + FnMut(), + { + let window = web_sys::window().expect("Failed to obtain window"); + + let closure = Closure::wrap(Box::new(f) as Box); + + let handle = window + .set_timeout_with_callback_and_timeout_and_arguments_0( + &closure.as_ref().unchecked_ref(), + duration.as_millis() as i32, + ) + .expect("Failed to set timeout"); + + Timeout { + handle, + _closure: closure, + } + } +} + +impl Drop for Timeout { + fn drop(&mut self) { + let window = web_sys::window().expect("Failed to obtain window"); + + window.clear_timeout_with_handle(self.handle); + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/window.rs new file mode 100644 index 0000000..bd52505 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/web/window.rs @@ -0,0 +1,287 @@ +use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOE}; +use crate::icon::Icon; +use crate::monitor::MonitorHandle as RootMH; +use crate::window::{CursorIcon, Fullscreen, WindowAttributes, WindowId as RootWI}; + +use raw_window_handle::web::WebHandle; + +use super::{backend, monitor, EventLoopWindowTarget}; + +use std::cell::RefCell; +use std::collections::vec_deque::IntoIter as VecDequeIter; +use std::collections::VecDeque; + +pub struct Window { + canvas: backend::Canvas, + previous_pointer: RefCell<&'static str>, + id: Id, + register_redraw_request: Box, +} + +impl Window { + pub fn new( + target: &EventLoopWindowTarget, + attr: WindowAttributes, + platform_attr: PlatformSpecificBuilderAttributes, + ) -> Result { + let runner = target.runner.clone(); + + let id = target.generate_id(); + + let mut canvas = backend::Canvas::create(platform_attr)?; + + let register_redraw_request = Box::new(move || runner.request_redraw(RootWI(id))); + + target.register(&mut canvas, id); + + let window = Window { + canvas, + previous_pointer: RefCell::new("auto"), + id, + register_redraw_request, + }; + + window.set_inner_size(attr.inner_size.unwrap_or(Size::Logical(LogicalSize { + width: 1024.0, + height: 768.0, + }))); + window.set_title(&attr.title); + window.set_maximized(attr.maximized); + window.set_visible(attr.visible); + window.set_window_icon(attr.window_icon); + + Ok(window) + } + + pub fn canvas(&self) -> &backend::Canvas { + &self.canvas + } + + pub fn set_title(&self, title: &str) { + self.canvas.set_attribute("alt", title); + } + + pub fn set_visible(&self, _visible: bool) { + // Intentionally a no-op + } + + pub fn request_redraw(&self) { + (self.register_redraw_request)(); + } + + pub fn outer_position(&self) -> Result, NotSupportedError> { + Ok(self.canvas.position().to_physical(self.scale_factor())) + } + + pub fn inner_position(&self) -> Result, NotSupportedError> { + // Note: the canvas element has no window decorations, so this is equal to `outer_position`. + self.outer_position() + } + + pub fn set_outer_position(&self, position: Position) { + let position = position.to_logical::(self.scale_factor()); + + self.canvas.set_attribute("position", "fixed"); + self.canvas.set_attribute("left", &position.x.to_string()); + self.canvas.set_attribute("top", &position.y.to_string()); + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + self.canvas.size() + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + // Note: the canvas element has no window decorations, so this is equal to `inner_size`. + self.inner_size() + } + + #[inline] + pub fn set_inner_size(&self, size: Size) { + backend::set_canvas_size(self.canvas.raw(), size); + } + + #[inline] + pub fn set_min_inner_size(&self, _dimensions: Option) { + // Intentionally a no-op: users can't resize canvas elements + } + + #[inline] + pub fn set_max_inner_size(&self, _dimensions: Option) { + // Intentionally a no-op: users can't resize canvas elements + } + + #[inline] + pub fn set_resizable(&self, _resizable: bool) { + // Intentionally a no-op: users can't resize canvas elements + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + super::backend::scale_factor() + } + + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + let text = match cursor { + CursorIcon::Default => "auto", + CursorIcon::Crosshair => "crosshair", + CursorIcon::Hand => "pointer", + CursorIcon::Arrow => "default", + CursorIcon::Move => "move", + CursorIcon::Text => "text", + CursorIcon::Wait => "wait", + CursorIcon::Help => "help", + CursorIcon::Progress => "progress", + + CursorIcon::NotAllowed => "not-allowed", + CursorIcon::ContextMenu => "context-menu", + CursorIcon::Cell => "cell", + CursorIcon::VerticalText => "vertical-text", + CursorIcon::Alias => "alias", + CursorIcon::Copy => "copy", + CursorIcon::NoDrop => "no-drop", + CursorIcon::Grab => "grab", + CursorIcon::Grabbing => "grabbing", + CursorIcon::AllScroll => "all-scroll", + CursorIcon::ZoomIn => "zoom-in", + CursorIcon::ZoomOut => "zoom-out", + + CursorIcon::EResize => "e-resize", + CursorIcon::NResize => "n-resize", + CursorIcon::NeResize => "ne-resize", + CursorIcon::NwResize => "nw-resize", + CursorIcon::SResize => "s-resize", + CursorIcon::SeResize => "se-resize", + CursorIcon::SwResize => "sw-resize", + CursorIcon::WResize => "w-resize", + CursorIcon::EwResize => "ew-resize", + CursorIcon::NsResize => "ns-resize", + CursorIcon::NeswResize => "nesw-resize", + CursorIcon::NwseResize => "nwse-resize", + CursorIcon::ColResize => "col-resize", + CursorIcon::RowResize => "row-resize", + }; + *self.previous_pointer.borrow_mut() = text; + self.canvas + .set_attribute("style", &format!("cursor: {}", text)); + } + + #[inline] + pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { + // Intentionally a no-op, as the web does not support setting cursor positions + Ok(()) + } + + #[inline] + pub fn set_cursor_grab(&self, _grab: bool) -> Result<(), ExternalError> { + // Intentionally a no-op, as the web does not (properly) support grabbing the cursor + Ok(()) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + if !visible { + self.canvas.set_attribute("cursor", "none"); + } else { + self.canvas + .set_attribute("cursor", *self.previous_pointer.borrow()); + } + } + + #[inline] + pub fn set_minimized(&self, _minimized: bool) { + // Intentionally a no-op, as canvases cannot be 'minimized' + } + + #[inline] + pub fn set_maximized(&self, _maximized: bool) { + // Intentionally a no-op, as canvases cannot be 'maximized' + } + + #[inline] + pub fn fullscreen(&self) -> Option { + if self.canvas.is_fullscreen() { + Some(Fullscreen::Borderless(self.current_monitor())) + } else { + None + } + } + + #[inline] + pub fn set_fullscreen(&self, monitor: Option) { + if monitor.is_some() { + self.canvas.request_fullscreen(); + } else if self.canvas.is_fullscreen() { + backend::exit_fullscreen(); + } + } + + #[inline] + pub fn set_decorations(&self, _decorations: bool) { + // Intentionally a no-op, no canvas decorations + } + + #[inline] + pub fn set_always_on_top(&self, _always_on_top: bool) { + // Intentionally a no-op, no window ordering + } + + #[inline] + pub fn set_window_icon(&self, _window_icon: Option) { + // Currently an intentional no-op + } + + #[inline] + pub fn set_ime_position(&self, _position: Position) { + // Currently a no-op as it does not seem there is good support for this on web + } + + #[inline] + pub fn current_monitor(&self) -> RootMH { + RootMH { + inner: monitor::Handle, + } + } + + #[inline] + pub fn available_monitors(&self) -> VecDequeIter { + VecDeque::new().into_iter() + } + + #[inline] + pub fn primary_monitor(&self) -> monitor::Handle { + monitor::Handle + } + + #[inline] + pub fn id(&self) -> Id { + return self.id; + } + + #[inline] + pub fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle { + let handle = WebHandle { + id: self.id.0, + ..WebHandle::empty() + }; + + raw_window_handle::RawWindowHandle::Web(handle) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Id(pub(crate) u32); + +impl Id { + pub unsafe fn dummy() -> Id { + Id(0) + } +} + +#[derive(Default, Clone)] +pub struct PlatformSpecificBuilderAttributes { + pub(crate) canvas: Option, +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dark_mode.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dark_mode.rs new file mode 100644 index 0000000..3c7c16e --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dark_mode.rs @@ -0,0 +1,210 @@ +/// This is a simple implementation of support for Windows Dark Mode, +/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode +use std::ffi::OsStr; +use std::os::windows::ffi::OsStrExt; + +use winapi::{ + shared::{ + basetsd::SIZE_T, + minwindef::{BOOL, DWORD, FALSE, UINT, ULONG, WORD}, + ntdef::{LPSTR, NTSTATUS, NT_SUCCESS, PVOID, WCHAR}, + windef::HWND, + winerror::S_OK, + }, + um::{libloaderapi, uxtheme, winuser}, +}; + +lazy_static! { + static ref WIN10_BUILD_VERSION: Option = { + // FIXME: RtlGetVersion is a documented windows API, + // should be part of winapi! + + #[allow(non_snake_case)] + #[repr(C)] + struct OSVERSIONINFOW { + dwOSVersionInfoSize: ULONG, + dwMajorVersion: ULONG, + dwMinorVersion: ULONG, + dwBuildNumber: ULONG, + dwPlatformId: ULONG, + szCSDVersion: [WCHAR; 128], + } + + type RtlGetVersion = unsafe extern "system" fn (*mut OSVERSIONINFOW) -> NTSTATUS; + let handle = get_function!("ntdll.dll", RtlGetVersion); + + if let Some(rtl_get_version) = handle { + unsafe { + let mut vi = OSVERSIONINFOW { + dwOSVersionInfoSize: 0, + dwMajorVersion: 0, + dwMinorVersion: 0, + dwBuildNumber: 0, + dwPlatformId: 0, + szCSDVersion: [0; 128], + }; + + let status = (rtl_get_version)(&mut vi as _); + + if NT_SUCCESS(status) && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { + Some(vi.dwBuildNumber) + } else { + None + } + } + } else { + None + } + }; + + static ref DARK_MODE_SUPPORTED: bool = { + // We won't try to do anything for windows versions < 17763 + // (Windows 10 October 2018 update) + match *WIN10_BUILD_VERSION { + Some(v) => v >= 17763, + None => false + } + }; + + static ref DARK_THEME_NAME: Vec = widestring("DarkMode_Explorer"); + static ref LIGHT_THEME_NAME: Vec = widestring(""); +} + +/// Attempt to set dark mode on a window, if necessary. +/// Returns true if dark mode was set, false if not. +pub fn try_dark_mode(hwnd: HWND) -> bool { + if *DARK_MODE_SUPPORTED { + let is_dark_mode = should_use_dark_mode(); + + let theme_name = if is_dark_mode { + DARK_THEME_NAME.as_ptr() + } else { + LIGHT_THEME_NAME.as_ptr() + }; + + let status = unsafe { uxtheme::SetWindowTheme(hwnd, theme_name as _, std::ptr::null()) }; + + status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) + } else { + false + } +} + +fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool { + // Uses Windows undocumented API SetWindowCompositionAttribute, + // as seen in win32-darkmode example linked at top of file. + + type SetWindowCompositionAttribute = + unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; + + #[allow(non_snake_case)] + type WINDOWCOMPOSITIONATTRIB = u32; + const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; + + #[allow(non_snake_case)] + #[repr(C)] + struct WINDOWCOMPOSITIONATTRIBDATA { + Attrib: WINDOWCOMPOSITIONATTRIB, + pvData: PVOID, + cbData: SIZE_T, + } + + lazy_static! { + static ref SET_WINDOW_COMPOSITION_ATTRIBUTE: Option = + get_function!("user32.dll", SetWindowCompositionAttribute); + } + + if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { + unsafe { + // SetWindowCompositionAttribute needs a bigbool (i32), not bool. + let mut is_dark_mode_bigbool = is_dark_mode as BOOL; + + let mut data = WINDOWCOMPOSITIONATTRIBDATA { + Attrib: WCA_USEDARKMODECOLORS, + pvData: &mut is_dark_mode_bigbool as *mut _ as _, + cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, + }; + + let status = set_window_composition_attribute(hwnd, &mut data as *mut _); + + status != FALSE + } + } else { + false + } +} + +fn should_use_dark_mode() -> bool { + should_apps_use_dark_mode() && !is_high_contrast() +} + +fn should_apps_use_dark_mode() -> bool { + type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; + lazy_static! { + static ref SHOULD_APPS_USE_DARK_MODE: Option = { + unsafe { + const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: WORD = 132; + + let module = libloaderapi::LoadLibraryA("uxtheme.dll\0".as_ptr() as _); + + if module.is_null() { + return None; + } + + let handle = libloaderapi::GetProcAddress( + module, + winuser::MAKEINTRESOURCEA(UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL), + ); + + if handle.is_null() { + None + } else { + Some(std::mem::transmute(handle)) + } + } + }; + } + + SHOULD_APPS_USE_DARK_MODE + .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) + .unwrap_or(false) +} + +// FIXME: This definition was missing from winapi. Can remove from +// here and use winapi once the following PR is released: +// https://github.com/retep998/winapi-rs/pull/815 +#[repr(C)] +#[allow(non_snake_case)] +struct HIGHCONTRASTA { + cbSize: UINT, + dwFlags: DWORD, + lpszDefaultScheme: LPSTR, +} + +const HCF_HIGHCONTRASTON: DWORD = 1; + +fn is_high_contrast() -> bool { + let mut hc = HIGHCONTRASTA { + cbSize: 0, + dwFlags: 0, + lpszDefaultScheme: std::ptr::null_mut(), + }; + + let ok = unsafe { + winuser::SystemParametersInfoA( + winuser::SPI_GETHIGHCONTRAST, + std::mem::size_of_val(&hc) as _, + &mut hc as *mut _ as _, + 0, + ) + }; + + ok != FALSE && (HCF_HIGHCONTRASTON & hc.dwFlags) == 1 +} + +fn widestring(src: &'static str) -> Vec { + OsStr::new(src) + .encode_wide() + .chain(Some(0).into_iter()) + .collect() +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dpi.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dpi.rs new file mode 100644 index 0000000..f7ec439 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/dpi.rs @@ -0,0 +1,116 @@ +#![allow(non_snake_case, unused_unsafe)] + +use std::sync::Once; + +use crate::platform_impl::platform::util::{ + ENABLE_NON_CLIENT_DPI_SCALING, GET_DPI_FOR_MONITOR, GET_DPI_FOR_WINDOW, SET_PROCESS_DPI_AWARE, + SET_PROCESS_DPI_AWARENESS, SET_PROCESS_DPI_AWARENESS_CONTEXT, +}; +use winapi::{ + shared::{ + minwindef::FALSE, + windef::{DPI_AWARENESS_CONTEXT, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, HMONITOR, HWND}, + winerror::S_OK, + }, + um::{ + shellscalingapi::{MDT_EFFECTIVE_DPI, PROCESS_PER_MONITOR_DPI_AWARE}, + wingdi::{GetDeviceCaps, LOGPIXELSX}, + winuser::{self, MONITOR_DEFAULTTONEAREST}, + }, +}; + +const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2: DPI_AWARENESS_CONTEXT = -4isize as _; + +pub fn become_dpi_aware() { + static ENABLE_DPI_AWARENESS: Once = Once::new(); + ENABLE_DPI_AWARENESS.call_once(|| { + unsafe { + if let Some(SetProcessDpiAwarenessContext) = *SET_PROCESS_DPI_AWARENESS_CONTEXT { + // We are on Windows 10 Anniversary Update (1607) or later. + if SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) + == FALSE + { + // V2 only works with Windows 10 Creators Update (1703). Try using the older + // V1 if we can't set V2. + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); + } + } else if let Some(SetProcessDpiAwareness) = *SET_PROCESS_DPI_AWARENESS { + // We are on Windows 8.1 or later. + SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); + } else if let Some(SetProcessDPIAware) = *SET_PROCESS_DPI_AWARE { + // We are on Vista or later. + SetProcessDPIAware(); + } + } + }); +} + +pub fn enable_non_client_dpi_scaling(hwnd: HWND) { + unsafe { + if let Some(EnableNonClientDpiScaling) = *ENABLE_NON_CLIENT_DPI_SCALING { + EnableNonClientDpiScaling(hwnd); + } + } +} + +pub fn get_monitor_dpi(hmonitor: HMONITOR) -> Option { + unsafe { + if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { + // We are on Windows 8.1 or later. + let mut dpi_x = 0; + let mut dpi_y = 0; + if GetDpiForMonitor(hmonitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { + // MSDN says that "the values of *dpiX and *dpiY are identical. You only need to + // record one of the values to determine the DPI and respond appropriately". + // https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx + return Some(dpi_x as u32); + } + } + } + None +} + +pub const BASE_DPI: u32 = 96; +pub fn dpi_to_scale_factor(dpi: u32) -> f64 { + dpi as f64 / BASE_DPI as f64 +} + +pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 { + let hdc = winuser::GetDC(hwnd); + if hdc.is_null() { + panic!("[winit] `GetDC` returned null!"); + } + if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { + // We are on Windows 10 Anniversary Update (1607) or later. + match GetDpiForWindow(hwnd) { + 0 => BASE_DPI, // 0 is returned if hwnd is invalid + dpi => dpi as u32, + } + } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { + // We are on Windows 8.1 or later. + let monitor = winuser::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + if monitor.is_null() { + return BASE_DPI; + } + + let mut dpi_x = 0; + let mut dpi_y = 0; + if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { + dpi_x as u32 + } else { + BASE_DPI + } + } else { + // We are on Vista or later. + if winuser::IsProcessDPIAware() != FALSE { + // If the process is DPI aware, then scaling must be handled by the application using + // this DPI value. + GetDeviceCaps(hdc, LOGPIXELSX) as u32 + } else { + // If the process is DPI unaware, then scaling is performed by the OS; we thus return + // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the + // application and the WM. + BASE_DPI + } + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/drop_handler.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/drop_handler.rs similarity index 68% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/windows/drop_handler.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/drop_handler.rs index 9b2af7c..f6c7a04 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/drop_handler.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/drop_handler.rs @@ -1,31 +1,39 @@ -use std::ffi::OsString; -use std::os::windows::ffi::OsStringExt; -use std::path::PathBuf; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::{mem, ptr}; +use std::{ + ffi::OsString, + os::windows::ffi::OsStringExt, + path::PathBuf, + ptr, + sync::atomic::{AtomicUsize, Ordering}, +}; -use winapi::ctypes::c_void; -use winapi::shared::guiddef::REFIID; -use winapi::shared::minwindef::{DWORD, MAX_PATH, UINT, ULONG}; -use winapi::shared::windef::{HWND, POINTL}; -use winapi::shared::winerror::S_OK; -use winapi::um::objidl::IDataObject; -use winapi::um::oleidl::{DROPEFFECT_COPY, DROPEFFECT_NONE, IDropTarget, IDropTargetVtbl}; -use winapi::um::winnt::HRESULT; -use winapi::um::{shellapi, unknwnbase}; +use winapi::{ + ctypes::c_void, + shared::{ + guiddef::REFIID, + minwindef::{DWORD, UINT, ULONG}, + windef::{HWND, POINTL}, + winerror::S_OK, + }, + um::{ + objidl::IDataObject, + oleidl::{IDropTarget, IDropTargetVtbl, DROPEFFECT_COPY, DROPEFFECT_NONE}, + shellapi, unknwnbase, + winnt::HRESULT, + }, +}; -use platform::platform::events_loop::send_event; -use platform::platform::WindowId; +use crate::platform_impl::platform::WindowId; -use {Event, WindowId as SuperWindowId}; +use crate::{event::Event, window::WindowId as SuperWindowId}; #[repr(C)] pub struct FileDropHandlerData { pub interface: IDropTarget, refcount: AtomicUsize, window: HWND, + send_event: Box)>, cursor_effect: DWORD, - hovered_is_valid: bool, // If the currently hovered item is not valid there must not be any `HoveredFileCancelled` emitted + hovered_is_valid: bool, /* If the currently hovered item is not valid there must not be any `HoveredFileCancelled` emitted */ } pub struct FileDropHandler { @@ -34,13 +42,14 @@ pub struct FileDropHandler { #[allow(non_snake_case)] impl FileDropHandler { - pub fn new(window: HWND) -> FileDropHandler { + pub fn new(window: HWND, send_event: Box)>) -> FileDropHandler { let data = Box::new(FileDropHandlerData { interface: IDropTarget { lpVtbl: &DROP_TARGET_VTBL as *const IDropTargetVtbl, }, refcount: AtomicUsize::new(1), window, + send_event, cursor_effect: DROPEFFECT_NONE, hovered_is_valid: false, }); @@ -83,10 +92,10 @@ impl FileDropHandler { _pt: *const POINTL, pdwEffect: *mut DWORD, ) -> HRESULT { - use events::WindowEvent::HoveredFile; + use crate::event::WindowEvent::HoveredFile; let drop_handler = Self::from_interface(this); let hdrop = Self::iterate_filenames(pDataObj, |filename| { - send_event(Event::WindowEvent { + drop_handler.send_event(Event::WindowEvent { window_id: SuperWindowId(WindowId(drop_handler.window)), event: HoveredFile(filename), }); @@ -115,10 +124,10 @@ impl FileDropHandler { } pub unsafe extern "system" fn DragLeave(this: *mut IDropTarget) -> HRESULT { - use events::WindowEvent::HoveredFileCancelled; + use crate::event::WindowEvent::HoveredFileCancelled; let drop_handler = Self::from_interface(this); if drop_handler.hovered_is_valid { - send_event(Event::WindowEvent { + drop_handler.send_event(Event::WindowEvent { window_id: SuperWindowId(WindowId(drop_handler.window)), event: HoveredFileCancelled, }); @@ -134,10 +143,10 @@ impl FileDropHandler { _pt: *const POINTL, _pdwEffect: *mut DWORD, ) -> HRESULT { - use events::WindowEvent::DroppedFile; + use crate::event::WindowEvent::DroppedFile; let drop_handler = Self::from_interface(this); let hdrop = Self::iterate_filenames(pDataObj, |filename| { - send_event(Event::WindowEvent { + drop_handler.send_event(Event::WindowEvent { window_id: SuperWindowId(WindowId(drop_handler.window)), event: DroppedFile(filename), }); @@ -153,16 +162,24 @@ impl FileDropHandler { &mut *(this as *mut _) } - unsafe fn iterate_filenames(data_obj: *const IDataObject, callback: F) -> Option + unsafe fn iterate_filenames( + data_obj: *const IDataObject, + callback: F, + ) -> Option where F: Fn(PathBuf), { - use winapi::ctypes::wchar_t; - use winapi::shared::winerror::{SUCCEEDED, DV_E_FORMATETC}; - use winapi::shared::wtypes::{CLIPFORMAT, DVASPECT_CONTENT}; - use winapi::um::objidl::{FORMATETC, TYMED_HGLOBAL}; - use winapi::um::shellapi::DragQueryFileW; - use winapi::um::winuser::CF_HDROP; + use winapi::{ + shared::{ + winerror::{DV_E_FORMATETC, SUCCEEDED}, + wtypes::{CLIPFORMAT, DVASPECT_CONTENT}, + }, + um::{ + objidl::{FORMATETC, TYMED_HGLOBAL}, + shellapi::DragQueryFileW, + winuser::CF_HDROP, + }, + }; let mut drop_format = FORMATETC { cfFormat: CF_HDROP as CLIPFORMAT, @@ -172,7 +189,7 @@ impl FileDropHandler { tymed: TYMED_HGLOBAL, }; - let mut medium = mem::uninitialized(); + let mut medium = std::mem::zeroed(); let get_data_result = (*data_obj).GetData(&mut drop_format, &mut medium); if SUCCEEDED(get_data_result) { let hglobal = (*medium.u).hGlobal(); @@ -181,15 +198,19 @@ impl FileDropHandler { // The second parameter (0xFFFFFFFF) instructs the function to return the item count let item_count = DragQueryFileW(hdrop, 0xFFFFFFFF, ptr::null_mut(), 0); - let mut pathbuf: [wchar_t; MAX_PATH] = mem::uninitialized(); - for i in 0..item_count { - let character_count = - DragQueryFileW(hdrop, i, pathbuf.as_mut_ptr(), MAX_PATH as UINT) as usize; + // Get the length of the path string NOT including the terminating null character. + // Previously, this was using a fixed size array of MAX_PATH length, but the + // Windows API allows longer paths under certain circumstances. + let character_count = DragQueryFileW(hdrop, i, ptr::null_mut(), 0) as usize; + let str_len = character_count + 1; - if character_count > 0 { - callback(OsString::from_wide(&pathbuf[0..character_count]).into()); - } + // Fill path_buf with the null-terminated file name + let mut path_buf = Vec::with_capacity(str_len); + DragQueryFileW(hdrop, i, path_buf.as_mut_ptr(), str_len as UINT); + path_buf.set_len(str_len); + + callback(OsString::from_wide(&path_buf[0..character_count]).into()); } return Some(hdrop); @@ -205,6 +226,12 @@ impl FileDropHandler { } } +impl FileDropHandlerData { + fn send_event(&self, event: Event<'static, ()>) { + (self.send_event)(event); + } +} + impl Drop for FileDropHandler { fn drop(&mut self) { unsafe { diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/event.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event.rs similarity index 60% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/windows/event.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event.rs index dfdff6e..49501f1 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/event.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event.rs @@ -1,31 +1,163 @@ -use std::char; -use std::os::raw::c_int; +use std::{ + char, + os::raw::c_int, + ptr, + sync::atomic::{AtomicBool, AtomicPtr, Ordering}, +}; -use events::VirtualKeyCode; -use events::ModifiersState; +use crate::event::{ModifiersState, ScanCode, VirtualKeyCode}; -use winapi::shared::minwindef::{WPARAM, LPARAM, UINT}; -use winapi::um::winuser; +use winapi::{ + shared::minwindef::{HKL, HKL__, LPARAM, UINT, WPARAM}, + um::winuser, +}; -use ScanCode; +fn key_pressed(vkey: c_int) -> bool { + unsafe { (winuser::GetKeyState(vkey) & (1 << 15)) == (1 << 15) } +} pub fn get_key_mods() -> ModifiersState { - let mut mods = ModifiersState::default(); - unsafe { - if winuser::GetKeyState(winuser::VK_SHIFT) & (1 << 15) == (1 << 15) { - mods.shift = true; - } - if winuser::GetKeyState(winuser::VK_CONTROL) & (1 << 15) == (1 << 15) { - mods.ctrl = true; - } - if winuser::GetKeyState(winuser::VK_MENU) & (1 << 15) == (1 << 15) { - mods.alt = true; - } - if (winuser::GetKeyState(winuser::VK_LWIN) | winuser::GetKeyState(winuser::VK_RWIN)) & (1 << 15) == (1 << 15) { - mods.logo = true; + let filter_out_altgr = layout_uses_altgr() && key_pressed(winuser::VK_RMENU); + + let mut mods = ModifiersState::empty(); + mods.set(ModifiersState::SHIFT, key_pressed(winuser::VK_SHIFT)); + mods.set( + ModifiersState::CTRL, + key_pressed(winuser::VK_CONTROL) && !filter_out_altgr, + ); + mods.set( + ModifiersState::ALT, + key_pressed(winuser::VK_MENU) && !filter_out_altgr, + ); + mods.set( + ModifiersState::LOGO, + key_pressed(winuser::VK_LWIN) || key_pressed(winuser::VK_RWIN), + ); + mods +} + +bitflags! { + #[derive(Default)] + pub struct ModifiersStateSide: u32 { + const LSHIFT = 0b010 << 0; + const RSHIFT = 0b001 << 0; + + const LCTRL = 0b010 << 3; + const RCTRL = 0b001 << 3; + + const LALT = 0b010 << 6; + const RALT = 0b001 << 6; + + const LLOGO = 0b010 << 9; + const RLOGO = 0b001 << 9; + } +} + +impl ModifiersStateSide { + pub fn filter_out_altgr(&self) -> ModifiersStateSide { + match layout_uses_altgr() && self.contains(Self::RALT) { + false => *self, + true => *self & !(Self::LCTRL | Self::RCTRL | Self::LALT | Self::RALT), } } - mods +} + +impl From for ModifiersState { + fn from(side: ModifiersStateSide) -> Self { + let mut state = ModifiersState::default(); + state.set( + Self::SHIFT, + side.intersects(ModifiersStateSide::LSHIFT | ModifiersStateSide::RSHIFT), + ); + state.set( + Self::CTRL, + side.intersects(ModifiersStateSide::LCTRL | ModifiersStateSide::RCTRL), + ); + state.set( + Self::ALT, + side.intersects(ModifiersStateSide::LALT | ModifiersStateSide::RALT), + ); + state.set( + Self::LOGO, + side.intersects(ModifiersStateSide::LLOGO | ModifiersStateSide::RLOGO), + ); + state + } +} + +pub fn get_pressed_keys() -> impl Iterator { + let mut keyboard_state = vec![0u8; 256]; + unsafe { winuser::GetKeyboardState(keyboard_state.as_mut_ptr()) }; + keyboard_state + .into_iter() + .enumerate() + .filter(|(_, p)| (*p & (1 << 7)) != 0) // whether or not a key is pressed is communicated via the high-order bit + .map(|(i, _)| i as c_int) +} + +unsafe fn get_char(keyboard_state: &[u8; 256], v_key: u32, hkl: HKL) -> Option { + let mut unicode_bytes = [0u16; 5]; + let len = winuser::ToUnicodeEx( + v_key, + 0, + keyboard_state.as_ptr(), + unicode_bytes.as_mut_ptr(), + unicode_bytes.len() as _, + 0, + hkl, + ); + if len >= 1 { + char::decode_utf16(unicode_bytes.iter().cloned()) + .next() + .and_then(|c| c.ok()) + } else { + None + } +} + +/// Figures out if the keyboard layout has an AltGr key instead of an Alt key. +/// +/// Unfortunately, the Windows API doesn't give a way for us to conveniently figure that out. So, +/// we use a technique blatantly stolen from [the Firefox source code][source]: iterate over every +/// possible virtual key and compare the `char` output when AltGr is pressed vs when it isn't. If +/// pressing AltGr outputs characters that are different from the standard characters, the layout +/// uses AltGr. Otherwise, it doesn't. +/// +/// [source]: https://github.com/mozilla/gecko-dev/blob/265e6721798a455604328ed5262f430cfcc37c2f/widget/windows/KeyboardLayout.cpp#L4356-L4416 +fn layout_uses_altgr() -> bool { + unsafe { + static ACTIVE_LAYOUT: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + static USES_ALTGR: AtomicBool = AtomicBool::new(false); + + let hkl = winuser::GetKeyboardLayout(0); + let old_hkl = ACTIVE_LAYOUT.swap(hkl, Ordering::SeqCst); + + if hkl == old_hkl { + return USES_ALTGR.load(Ordering::SeqCst); + } + + let mut keyboard_state_altgr = [0u8; 256]; + // AltGr is an alias for Ctrl+Alt for... some reason. Whatever it is, those are the keypresses + // we have to emulate to do an AltGr test. + keyboard_state_altgr[winuser::VK_MENU as usize] = 0x80; + keyboard_state_altgr[winuser::VK_CONTROL as usize] = 0x80; + + let keyboard_state_empty = [0u8; 256]; + + for v_key in 0..=255 { + let key_noaltgr = get_char(&keyboard_state_empty, v_key, hkl); + let key_altgr = get_char(&keyboard_state_altgr, v_key, hkl); + if let (Some(noaltgr), Some(altgr)) = (key_noaltgr, key_altgr) { + if noaltgr != altgr { + USES_ALTGR.store(true, Ordering::SeqCst); + return true; + } + } + } + + USES_ALTGR.store(false, Ordering::SeqCst); + false + } } pub fn vkey_to_winit_vkey(vkey: c_int) -> Option { @@ -113,8 +245,8 @@ pub fn vkey_to_winit_vkey(vkey: c_int) -> Option { 0x58 => Some(VirtualKeyCode::X), 0x59 => Some(VirtualKeyCode::Y), 0x5A => Some(VirtualKeyCode::Z), - //winuser::VK_LWIN => Some(VirtualKeyCode::Lwin), - //winuser::VK_RWIN => Some(VirtualKeyCode::Rwin), + winuser::VK_LWIN => Some(VirtualKeyCode::LWin), + winuser::VK_RWIN => Some(VirtualKeyCode::RWin), winuser::VK_APPS => Some(VirtualKeyCode::Apps), winuser::VK_SLEEP => Some(VirtualKeyCode::Sleep), winuser::VK_NUMPAD0 => Some(VirtualKeyCode::Numpad0), @@ -188,7 +320,7 @@ pub fn vkey_to_winit_vkey(vkey: c_int) -> Option { winuser::VK_OEM_5 => map_text_keys(vkey), winuser::VK_OEM_6 => map_text_keys(vkey), winuser::VK_OEM_7 => map_text_keys(vkey), - /*winuser::VK_OEM_8 => Some(VirtualKeyCode::Oem_8), */ + /* winuser::VK_OEM_8 => Some(VirtualKeyCode::Oem_8), */ winuser::VK_OEM_102 => Some(VirtualKeyCode::OEM102), /*winuser::VK_PROCESSKEY => Some(VirtualKeyCode::Processkey), winuser::VK_PACKET => Some(VirtualKeyCode::Packet), @@ -201,49 +333,61 @@ pub fn vkey_to_winit_vkey(vkey: c_int) -> Option { winuser::VK_NONAME => Some(VirtualKeyCode::Noname), winuser::VK_PA1 => Some(VirtualKeyCode::Pa1), winuser::VK_OEM_CLEAR => Some(VirtualKeyCode::Oem_clear),*/ - _ => None + _ => None, } } -pub fn handle_extended_keys(vkey: c_int, mut scancode: UINT, extended: bool) -> Option<(c_int, UINT)> { +pub fn handle_extended_keys( + vkey: c_int, + mut scancode: UINT, + extended: bool, +) -> Option<(c_int, UINT)> { // Welcome to hell https://blog.molecular-matters.com/2011/09/05/properly-handling-keyboard-input/ let vkey = match vkey { - winuser::VK_SHIFT => unsafe { winuser::MapVirtualKeyA( - scancode, - winuser::MAPVK_VSC_TO_VK_EX, - ) as _ }, - winuser::VK_CONTROL => if extended { - winuser::VK_RCONTROL - } else { - winuser::VK_LCONTROL + winuser::VK_SHIFT => unsafe { + winuser::MapVirtualKeyA(scancode, winuser::MAPVK_VSC_TO_VK_EX) as _ }, - winuser::VK_MENU => if extended { - winuser::VK_RMENU - } else { - winuser::VK_LMENU - }, - _ => match scancode { - // This is only triggered when using raw input. Without this check, we get two events whenever VK_PAUSE is - // pressed, the first one having scancode 0x1D but vkey VK_PAUSE... - 0x1D if vkey == winuser::VK_PAUSE => return None, - // ...and the second having scancode 0x45 but an unmatched vkey! - 0x45 => winuser::VK_PAUSE, - // VK_PAUSE and VK_SCROLL have the same scancode when using modifiers, alongside incorrect vkey values. - 0x46 => { - if extended { - scancode = 0x45; - winuser::VK_PAUSE - } else { - winuser::VK_SCROLL + winuser::VK_CONTROL => { + if extended { + winuser::VK_RCONTROL + } else { + winuser::VK_LCONTROL + } + } + winuser::VK_MENU => { + if extended { + winuser::VK_RMENU + } else { + winuser::VK_LMENU + } + } + _ => { + match scancode { + // This is only triggered when using raw input. Without this check, we get two events whenever VK_PAUSE is + // pressed, the first one having scancode 0x1D but vkey VK_PAUSE... + 0x1D if vkey == winuser::VK_PAUSE => return None, + // ...and the second having scancode 0x45 but an unmatched vkey! + 0x45 => winuser::VK_PAUSE, + // VK_PAUSE and VK_SCROLL have the same scancode when using modifiers, alongside incorrect vkey values. + 0x46 => { + if extended { + scancode = 0x45; + winuser::VK_PAUSE + } else { + winuser::VK_SCROLL + } } - }, - _ => vkey, - }, + _ => vkey, + } + } }; Some((vkey, scancode)) } -pub fn process_key_params(wparam: WPARAM, lparam: LPARAM) -> Option<(ScanCode, Option)> { +pub fn process_key_params( + wparam: WPARAM, + lparam: LPARAM, +) -> Option<(ScanCode, Option)> { let scancode = ((lparam >> 16) & 0xff) as UINT; let extended = (lparam & 0x01000000) != 0; handle_extended_keys(wparam as _, scancode, extended) @@ -253,7 +397,9 @@ pub fn process_key_params(wparam: WPARAM, lparam: LPARAM) -> Option<(ScanCode, O // This is needed as windows doesn't properly distinguish // some virtual key codes for different keyboard layouts fn map_text_keys(win_virtual_key: i32) -> Option { - let char_key = unsafe { winuser::MapVirtualKeyA(win_virtual_key as u32, winuser::MAPVK_VK_TO_CHAR) } & 0x7FFF; + let char_key = + unsafe { winuser::MapVirtualKeyA(win_virtual_key as u32, winuser::MAPVK_VK_TO_CHAR) } + & 0x7FFF; match char::from_u32(char_key) { Some(';') => Some(VirtualKeyCode::Semicolon), Some('/') => Some(VirtualKeyCode::Slash), @@ -262,6 +408,6 @@ fn map_text_keys(win_virtual_key: i32) -> Option { Some(']') => Some(VirtualKeyCode::RBracket), Some('\'') => Some(VirtualKeyCode::Apostrophe), Some('\\') => Some(VirtualKeyCode::Backslash), - _ => None + _ => None, } } diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop.rs new file mode 100644 index 0000000..e5a4d4f --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop.rs @@ -0,0 +1,1945 @@ +#![allow(non_snake_case)] +//! An events loop on Win32 is a background thread. +//! +//! Creating an events loop spawns a thread and blocks it in a permanent Win32 events loop. +//! Destroying the events loop stops the thread. +//! +//! You can use the `execute_in_thread` method to execute some code in the background thread. +//! Since Win32 requires you to create a window in the right thread, you must use this method +//! to create a window. +//! +//! If you create a window whose class is set to `callback`, the window's events will be +//! propagated with `run_forever` and `poll_events`. +//! The closure passed to the `execute_in_thread` method takes an `Inserter` that you can use to +//! add a `WindowState` entry to a list of window to be used by the callback. + +mod runner; + +use parking_lot::Mutex; +use std::{ + marker::PhantomData, + mem, panic, ptr, + rc::Rc, + sync::{ + mpsc::{self, Receiver, Sender}, + Arc, + }, + time::{Duration, Instant}, +}; +use winapi::shared::basetsd::{DWORD_PTR, UINT_PTR}; + +use winapi::{ + shared::{ + minwindef::{BOOL, DWORD, HIWORD, INT, LOWORD, LPARAM, LRESULT, UINT, WPARAM}, + windef::{HWND, POINT, RECT}, + windowsx, winerror, + }, + um::{ + commctrl, libloaderapi, ole2, processthreadsapi, winbase, + winnt::{HANDLE, LONG, LPCSTR, SHORT}, + winuser, + }, +}; + +use self::runner::{ELRShared, EventLoopRunnerShared}; +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + event::{DeviceEvent, Event, Force, KeyboardInput, Touch, TouchPhase, WindowEvent}, + event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW}, + platform_impl::platform::{ + dark_mode::try_dark_mode, + dpi::{become_dpi_aware, dpi_to_scale_factor, enable_non_client_dpi_scaling}, + drop_handler::FileDropHandler, + event::{self, handle_extended_keys, process_key_params, vkey_to_winit_vkey}, + monitor, raw_input, util, + window_state::{CursorFlags, WindowFlags, WindowState}, + wrap_device_id, WindowId, DEVICE_ID, + }, + window::{Fullscreen, WindowId as RootWindowId}, +}; + +type GetPointerFrameInfoHistory = unsafe extern "system" fn( + pointerId: UINT, + entriesCount: *mut UINT, + pointerCount: *mut UINT, + pointerInfo: *mut winuser::POINTER_INFO, +) -> BOOL; + +type SkipPointerFrameMessages = unsafe extern "system" fn(pointerId: UINT) -> BOOL; +type GetPointerDeviceRects = unsafe extern "system" fn( + device: HANDLE, + pointerDeviceRect: *mut RECT, + displayRect: *mut RECT, +) -> BOOL; + +type GetPointerTouchInfo = + unsafe extern "system" fn(pointerId: UINT, touchInfo: *mut winuser::POINTER_TOUCH_INFO) -> BOOL; + +type GetPointerPenInfo = + unsafe extern "system" fn(pointId: UINT, penInfo: *mut winuser::POINTER_PEN_INFO) -> BOOL; + +lazy_static! { + static ref GET_POINTER_FRAME_INFO_HISTORY: Option = + get_function!("user32.dll", GetPointerFrameInfoHistory); + static ref SKIP_POINTER_FRAME_MESSAGES: Option = + get_function!("user32.dll", SkipPointerFrameMessages); + static ref GET_POINTER_DEVICE_RECTS: Option = + get_function!("user32.dll", GetPointerDeviceRects); + static ref GET_POINTER_TOUCH_INFO: Option = + get_function!("user32.dll", GetPointerTouchInfo); + static ref GET_POINTER_PEN_INFO: Option = + get_function!("user32.dll", GetPointerPenInfo); +} + +pub(crate) struct SubclassInput { + pub window_state: Arc>, + pub event_loop_runner: EventLoopRunnerShared, + pub file_drop_handler: FileDropHandler, +} + +impl SubclassInput { + unsafe fn send_event(&self, event: Event<'_, T>) { + self.event_loop_runner.send_event(event); + } +} + +struct ThreadMsgTargetSubclassInput { + event_loop_runner: EventLoopRunnerShared, + user_event_receiver: Receiver, +} + +impl ThreadMsgTargetSubclassInput { + unsafe fn send_event(&self, event: Event<'_, T>) { + self.event_loop_runner.send_event(event); + } +} + +pub struct EventLoop { + thread_msg_sender: Sender, + window_target: RootELW, +} + +pub struct EventLoopWindowTarget { + thread_id: DWORD, + thread_msg_target: HWND, + pub(crate) runner_shared: EventLoopRunnerShared, +} + +macro_rules! main_thread_check { + ($fn_name:literal) => {{ + let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() }; + if thread_id != main_thread_id() { + panic!(concat!( + "Initializing the event loop outside of the main thread is a significant \ + cross-platform compatibility hazard. If you really, absolutely need to create an \ + EventLoop on a different thread, please use the `EventLoopExtWindows::", + $fn_name, + "` function." + )); + } + }}; +} + +impl EventLoop { + pub fn new() -> EventLoop { + main_thread_check!("new_any_thread"); + + Self::new_any_thread() + } + + pub fn new_any_thread() -> EventLoop { + become_dpi_aware(); + Self::new_dpi_unaware_any_thread() + } + + pub fn new_dpi_unaware() -> EventLoop { + main_thread_check!("new_dpi_unaware_any_thread"); + + Self::new_dpi_unaware_any_thread() + } + + pub fn new_dpi_unaware_any_thread() -> EventLoop { + let thread_id = unsafe { processthreadsapi::GetCurrentThreadId() }; + let runner_shared = Rc::new(ELRShared::new()); + let (thread_msg_target, thread_msg_sender) = + thread_event_target_window(runner_shared.clone()); + raw_input::register_all_mice_and_keyboards_for_raw_input(thread_msg_target); + + EventLoop { + thread_msg_sender, + window_target: RootELW { + p: EventLoopWindowTarget { + thread_id, + thread_msg_target, + runner_shared, + }, + _marker: PhantomData, + }, + } + } + + pub fn window_target(&self) -> &RootELW { + &self.window_target + } + + pub fn run(mut self, event_handler: F) -> ! + where + F: 'static + FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + self.run_return(event_handler); + ::std::process::exit(0); + } + + pub fn run_return(&mut self, mut event_handler: F) + where + F: FnMut(Event<'_, T>, &RootELW, &mut ControlFlow), + { + let event_loop_windows_ref = &self.window_target; + + unsafe { + self.window_target + .p + .runner_shared + .set_runner(self, move |event, control_flow| { + event_handler(event, event_loop_windows_ref, control_flow) + }) + } + + let runner = &self.window_target.p.runner_shared; + + unsafe { + let mut msg = mem::zeroed(); + let mut unread_message_exists = false; + + 'main: loop { + if let Err(payload) = runner.take_panic_error() { + runner.destroy_runner(); + panic::resume_unwind(payload); + } + + runner.new_events(); + loop { + if !unread_message_exists { + if 0 == winuser::PeekMessageW( + &mut msg, + ptr::null_mut(), + 0, + 0, + winuser::PM_REMOVE, + ) { + break; + } + } + winuser::TranslateMessage(&mut msg); + winuser::DispatchMessageW(&mut msg); + + unread_message_exists = false; + + if msg.message == winuser::WM_PAINT { + // An "external" redraw was requested. + // Note that the WM_PAINT has been dispatched and + // has caused the event loop to emit the MainEventsCleared event. + // See EventLoopRunner::process_event(). + // The call to main_events_cleared() below will do nothing. + break; + } + } + // Make sure we emit the MainEventsCleared event if no WM_PAINT message was received. + runner.main_events_cleared(); + // Drain eventual WM_PAINT messages sent if user called request_redraw() + // during handling of MainEventsCleared. + loop { + if 0 == winuser::PeekMessageW( + &mut msg, + ptr::null_mut(), + winuser::WM_PAINT, + winuser::WM_PAINT, + winuser::PM_QS_PAINT | winuser::PM_REMOVE, + ) { + break; + } + + winuser::TranslateMessage(&mut msg); + winuser::DispatchMessageW(&mut msg); + } + runner.redraw_events_cleared(); + match runner.control_flow() { + ControlFlow::Exit => break 'main, + ControlFlow::Wait => { + if 0 == winuser::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) { + break 'main; + } + unread_message_exists = true; + } + ControlFlow::WaitUntil(resume_time) => { + wait_until_time_or_msg(resume_time); + } + ControlFlow::Poll => (), + } + } + } + + runner.destroy_loop(); + runner.destroy_runner(); + } + + pub fn create_proxy(&self) -> EventLoopProxy { + EventLoopProxy { + target_window: self.window_target.p.thread_msg_target, + event_send: self.thread_msg_sender.clone(), + } + } +} + +impl EventLoopWindowTarget { + #[inline(always)] + pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor { + EventLoopThreadExecutor { + thread_id: self.thread_id, + target_window: self.thread_msg_target, + } + } +} + +fn main_thread_id() -> DWORD { + static mut MAIN_THREAD_ID: DWORD = 0; + #[used] + #[allow(non_upper_case_globals)] + #[link_section = ".CRT$XCU"] + static INIT_MAIN_THREAD_ID: unsafe fn() = { + unsafe fn initer() { + MAIN_THREAD_ID = processthreadsapi::GetCurrentThreadId(); + } + initer + }; + + unsafe { MAIN_THREAD_ID } +} + +unsafe fn wait_until_time_or_msg(wait_until: Instant) { + let now = Instant::now(); + if now < wait_until { + // MsgWaitForMultipleObjects tends to overshoot just a little bit. We subtract 1 millisecond + // from the requested time and spinlock for the remainder to compensate for that. + let resume_reason = winuser::MsgWaitForMultipleObjectsEx( + 0, + ptr::null(), + dur2timeout(wait_until - now).saturating_sub(1), + winuser::QS_ALLEVENTS, + winuser::MWMO_INPUTAVAILABLE, + ); + + if resume_reason == winerror::WAIT_TIMEOUT { + let mut msg = mem::zeroed(); + while Instant::now() < wait_until { + if 0 != winuser::PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, 0) { + break; + } + } + } + } +} + +// Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs +fn dur2timeout(dur: Duration) -> DWORD { + // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the + // timeouts in windows APIs are typically u32 milliseconds. To translate, we + // have two pieces to take care of: + // + // * Nanosecond precision is rounded up + // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE + // (never time out). + dur.as_secs() + .checked_mul(1000) + .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) + .and_then(|ms| { + ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { + 1 + } else { + 0 + }) + }) + .map(|ms| { + if ms > DWORD::max_value() as u64 { + winbase::INFINITE + } else { + ms as DWORD + } + }) + .unwrap_or(winbase::INFINITE) +} + +impl Drop for EventLoop { + fn drop(&mut self) { + unsafe { + winuser::DestroyWindow(self.window_target.p.thread_msg_target); + } + } +} + +pub(crate) struct EventLoopThreadExecutor { + thread_id: DWORD, + target_window: HWND, +} + +unsafe impl Send for EventLoopThreadExecutor {} +unsafe impl Sync for EventLoopThreadExecutor {} + +impl EventLoopThreadExecutor { + /// Check to see if we're in the parent event loop's thread. + pub(super) fn in_event_loop_thread(&self) -> bool { + let cur_thread_id = unsafe { processthreadsapi::GetCurrentThreadId() }; + self.thread_id == cur_thread_id + } + + /// Executes a function in the event loop thread. If we're already in the event loop thread, + /// we just call the function directly. + /// + /// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is + /// removed automatically if the callback receives a `WM_CLOSE` message for the window. + /// + /// Note that if you are using this to change some property of a window and updating + /// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the + /// events may be sent to the other thread in different order to the one in which you set + /// `WindowState`, leaving them out of sync. + /// + /// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent + /// to the unstable FnBox. + pub(super) fn execute_in_thread(&self, mut function: F) + where + F: FnMut() + Send + 'static, + { + unsafe { + if self.in_event_loop_thread() { + function(); + } else { + // We double-box because the first box is a fat pointer. + let boxed = Box::new(function) as Box; + let boxed2: ThreadExecFn = Box::new(boxed); + + let raw = Box::into_raw(boxed2); + + let res = winuser::PostMessageW( + self.target_window, + *EXEC_MSG_ID, + raw as *mut () as usize as WPARAM, + 0, + ); + assert!(res != 0, "PostMessage failed ; is the messages queue full?"); + } + } + } +} + +type ThreadExecFn = Box>; + +pub struct EventLoopProxy { + target_window: HWND, + event_send: Sender, +} +unsafe impl Send for EventLoopProxy {} + +impl Clone for EventLoopProxy { + fn clone(&self) -> Self { + Self { + target_window: self.target_window, + event_send: self.event_send.clone(), + } + } +} + +impl EventLoopProxy { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed> { + unsafe { + if winuser::PostMessageW(self.target_window, *USER_EVENT_MSG_ID, 0, 0) != 0 { + self.event_send.send(event).ok(); + Ok(()) + } else { + Err(EventLoopClosed(event)) + } + } + } +} + +lazy_static! { + // Message sent by the `EventLoopProxy` when we want to wake up the thread. + // WPARAM and LPARAM are unused. + static ref USER_EVENT_MSG_ID: u32 = { + unsafe { + winuser::RegisterWindowMessageA("Winit::WakeupMsg\0".as_ptr() as LPCSTR) + } + }; + // Message sent when we want to execute a closure in the thread. + // WPARAM contains a Box> that must be retrieved with `Box::from_raw`, + // and LPARAM is unused. + static ref EXEC_MSG_ID: u32 = { + unsafe { + winuser::RegisterWindowMessageA("Winit::ExecMsg\0".as_ptr() as *const i8) + } + }; + // Message sent by a `Window` when it wants to be destroyed by the main thread. + // WPARAM and LPARAM are unused. + pub static ref DESTROY_MSG_ID: u32 = { + unsafe { + winuser::RegisterWindowMessageA("Winit::DestroyMsg\0".as_ptr() as LPCSTR) + } + }; + // WPARAM is a bool specifying the `WindowFlags::MARKER_RETAIN_STATE_ON_SIZE` flag. See the + // documentation in the `window_state` module for more information. + pub static ref SET_RETAIN_STATE_ON_SIZE_MSG_ID: u32 = unsafe { + winuser::RegisterWindowMessageA("Winit::SetRetainMaximized\0".as_ptr() as LPCSTR) + }; + static ref THREAD_EVENT_TARGET_WINDOW_CLASS: Vec = unsafe { + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + + let class_name: Vec<_> = OsStr::new("Winit Thread Event Target") + .encode_wide() + .chain(Some(0).into_iter()) + .collect(); + + let class = winuser::WNDCLASSEXW { + cbSize: mem::size_of::() as UINT, + style: 0, + lpfnWndProc: Some(winuser::DefWindowProcW), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: libloaderapi::GetModuleHandleW(ptr::null()), + hIcon: ptr::null_mut(), + hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly + hbrBackground: ptr::null_mut(), + lpszMenuName: ptr::null(), + lpszClassName: class_name.as_ptr(), + hIconSm: ptr::null_mut(), + }; + + winuser::RegisterClassExW(&class); + + class_name + }; +} + +fn thread_event_target_window(event_loop_runner: EventLoopRunnerShared) -> (HWND, Sender) { + unsafe { + let window = winuser::CreateWindowExW( + winuser::WS_EX_NOACTIVATE | winuser::WS_EX_TRANSPARENT | winuser::WS_EX_LAYERED, + THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), + ptr::null_mut(), + 0, + 0, + 0, + 0, + 0, + ptr::null_mut(), + ptr::null_mut(), + libloaderapi::GetModuleHandleW(ptr::null()), + ptr::null_mut(), + ); + winuser::SetWindowLongPtrW( + window, + winuser::GWL_STYLE, + // The window technically has to be visible to receive WM_PAINT messages (which are used + // for delivering events during resizes), but it isn't displayed to the user because of + // the LAYERED style. + (winuser::WS_VISIBLE | winuser::WS_POPUP) as _, + ); + + let (tx, rx) = mpsc::channel(); + + let subclass_input = ThreadMsgTargetSubclassInput { + event_loop_runner, + user_event_receiver: rx, + }; + let input_ptr = Box::into_raw(Box::new(subclass_input)); + let subclass_result = commctrl::SetWindowSubclass( + window, + Some(thread_event_target_callback::), + THREAD_EVENT_TARGET_SUBCLASS_ID, + input_ptr as DWORD_PTR, + ); + assert_eq!(subclass_result, 1); + + (window, tx) + } +} + +/// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of +/// the window. +unsafe fn capture_mouse(window: HWND, window_state: &mut WindowState) { + window_state.mouse.buttons_down += 1; + winuser::SetCapture(window); +} + +/// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor +/// is outside the window. +unsafe fn release_mouse(window_state: &mut WindowState) { + window_state.mouse.buttons_down = window_state.mouse.buttons_down.saturating_sub(1); + if window_state.mouse.buttons_down == 0 { + winuser::ReleaseCapture(); + } +} + +const WINDOW_SUBCLASS_ID: UINT_PTR = 0; +const THREAD_EVENT_TARGET_SUBCLASS_ID: UINT_PTR = 1; +pub(crate) fn subclass_window(window: HWND, subclass_input: SubclassInput) { + let input_ptr = Box::into_raw(Box::new(subclass_input)); + let subclass_result = unsafe { + commctrl::SetWindowSubclass( + window, + Some(public_window_callback::), + WINDOW_SUBCLASS_ID, + input_ptr as DWORD_PTR, + ) + }; + assert_eq!(subclass_result, 1); +} + +fn normalize_pointer_pressure(pressure: u32) -> Option { + match pressure { + 1..=1024 => Some(Force::Normalized(pressure as f64 / 1024.0)), + _ => None, + } +} + +/// Emit a `ModifiersChanged` event whenever modifiers have changed. +fn update_modifiers(window: HWND, subclass_input: &SubclassInput) { + use crate::event::WindowEvent::ModifiersChanged; + + let modifiers = event::get_key_mods(); + let mut window_state = subclass_input.window_state.lock(); + if window_state.modifiers_state != modifiers { + window_state.modifiers_state = modifiers; + + // Drop lock + drop(window_state); + + unsafe { + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ModifiersChanged(modifiers), + }); + } + } +} + +/// Any window whose callback is configured to this function will have its events propagated +/// through the events loop of the thread the window was created in. +// +// This is the callback that is called by `DispatchMessage` in the events loop. +// +// Returning 0 tells the Win32 API that the message has been processed. +// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary +unsafe extern "system" fn public_window_callback( + window: HWND, + msg: UINT, + wparam: WPARAM, + lparam: LPARAM, + _: UINT_PTR, + subclass_input_ptr: DWORD_PTR, +) -> LRESULT { + let subclass_input = &*(subclass_input_ptr as *const SubclassInput); + + match msg { + winuser::WM_ENTERSIZEMOVE => { + subclass_input.event_loop_runner.set_modal_loop(true); + 0 + } + winuser::WM_EXITSIZEMOVE => { + subclass_input.event_loop_runner.set_modal_loop(false); + 0 + } + winuser::WM_NCCREATE => { + enable_non_client_dpi_scaling(window); + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + winuser::WM_NCLBUTTONDOWN => { + if wparam == winuser::HTCAPTION as _ { + winuser::PostMessageW(window, winuser::WM_MOUSEMOVE, 0, 0); + } + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + winuser::WM_CLOSE => { + use crate::event::WindowEvent::CloseRequested; + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CloseRequested, + }); + 0 + } + + winuser::WM_DESTROY => { + use crate::event::WindowEvent::Destroyed; + ole2::RevokeDragDrop(window); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Destroyed, + }); + + drop(subclass_input); + Box::from_raw(subclass_input_ptr as *mut SubclassInput); + 0 + } + + winuser::WM_PAINT => { + subclass_input.send_event(Event::RedrawRequested(RootWindowId(WindowId(window)))); + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + winuser::WM_WINDOWPOSCHANGING => { + let mut window_state = subclass_input.window_state.lock(); + if let Some(ref mut fullscreen) = window_state.fullscreen { + let window_pos = &mut *(lparam as *mut winuser::WINDOWPOS); + let new_rect = RECT { + left: window_pos.x, + top: window_pos.y, + right: window_pos.x + window_pos.cx, + bottom: window_pos.y + window_pos.cy, + }; + let new_monitor = + winuser::MonitorFromRect(&new_rect, winuser::MONITOR_DEFAULTTONULL); + match fullscreen { + Fullscreen::Borderless(ref mut fullscreen_monitor) => { + if new_monitor != fullscreen_monitor.inner.hmonitor() + && new_monitor != ptr::null_mut() + { + if let Ok(new_monitor_info) = monitor::get_monitor_info(new_monitor) { + let new_monitor_rect = new_monitor_info.rcMonitor; + window_pos.x = new_monitor_rect.left; + window_pos.y = new_monitor_rect.top; + window_pos.cx = new_monitor_rect.right - new_monitor_rect.left; + window_pos.cy = new_monitor_rect.bottom - new_monitor_rect.top; + } + *fullscreen_monitor = crate::monitor::MonitorHandle { + inner: monitor::MonitorHandle::new(new_monitor), + }; + } + } + Fullscreen::Exclusive(ref video_mode) => { + let old_monitor = video_mode.video_mode.monitor.hmonitor(); + if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) { + let old_monitor_rect = old_monitor_info.rcMonitor; + window_pos.x = old_monitor_rect.left; + window_pos.y = old_monitor_rect.top; + window_pos.cx = old_monitor_rect.right - old_monitor_rect.left; + window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top; + } + } + } + } + + 0 + } + + // WM_MOVE supplies client area positions, so we send Moved here instead. + winuser::WM_WINDOWPOSCHANGED => { + use crate::event::WindowEvent::Moved; + + let windowpos = lparam as *const winuser::WINDOWPOS; + if (*windowpos).flags & winuser::SWP_NOMOVE != winuser::SWP_NOMOVE { + let physical_position = + PhysicalPosition::new((*windowpos).x as i32, (*windowpos).y as i32); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Moved(physical_position), + }); + } + + // This is necessary for us to still get sent WM_SIZE. + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + winuser::WM_SIZE => { + use crate::event::WindowEvent::Resized; + let w = LOWORD(lparam as DWORD) as u32; + let h = HIWORD(lparam as DWORD) as u32; + + let physical_size = PhysicalSize::new(w, h); + let event = Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Resized(physical_size), + }; + + { + let mut w = subclass_input.window_state.lock(); + // See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check exists. + if !w + .window_flags() + .contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE) + { + let maximized = wparam == winuser::SIZE_MAXIMIZED; + w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized)); + } + } + + subclass_input.send_event(event); + 0 + } + + winuser::WM_CHAR | winuser::WM_SYSCHAR => { + use crate::event::WindowEvent::ReceivedCharacter; + use std::char; + let is_high_surrogate = 0xD800 <= wparam && wparam <= 0xDBFF; + let is_low_surrogate = 0xDC00 <= wparam && wparam <= 0xDFFF; + + if is_high_surrogate { + subclass_input.window_state.lock().high_surrogate = Some(wparam as u16); + } else if is_low_surrogate { + let high_surrogate = subclass_input.window_state.lock().high_surrogate.take(); + + if let Some(high_surrogate) = high_surrogate { + let pair = [high_surrogate, wparam as u16]; + if let Some(Ok(chr)) = char::decode_utf16(pair.iter().copied()).next() { + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ReceivedCharacter(chr), + }); + } + } + } else { + subclass_input.window_state.lock().high_surrogate = None; + + if let Some(chr) = char::from_u32(wparam as u32) { + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ReceivedCharacter(chr), + }); + } + } + 0 + } + + // this is necessary for us to maintain minimize/restore state + winuser::WM_SYSCOMMAND => { + if wparam == winuser::SC_RESTORE { + let mut w = subclass_input.window_state.lock(); + w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, false)); + } + if wparam == winuser::SC_MINIMIZE { + let mut w = subclass_input.window_state.lock(); + w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, true)); + } + // Send `WindowEvent::Minimized` here if we decide to implement one + + if wparam == winuser::SC_SCREENSAVE { + let window_state = subclass_input.window_state.lock(); + if window_state.fullscreen.is_some() { + return 0; + } + } + + winuser::DefWindowProcW(window, msg, wparam, lparam) + } + + winuser::WM_MOUSEMOVE => { + use crate::event::WindowEvent::{CursorEntered, CursorMoved}; + let mouse_was_outside_window = { + let mut w = subclass_input.window_state.lock(); + + let was_outside_window = !w.mouse.cursor_flags().contains(CursorFlags::IN_WINDOW); + w.mouse + .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, true)) + .ok(); + was_outside_window + }; + + if mouse_was_outside_window { + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorEntered { + device_id: DEVICE_ID, + }, + }); + + // Calling TrackMouseEvent in order to receive mouse leave events. + winuser::TrackMouseEvent(&mut winuser::TRACKMOUSEEVENT { + cbSize: mem::size_of::() as DWORD, + dwFlags: winuser::TME_LEAVE, + hwndTrack: window, + dwHoverTime: winuser::HOVER_DEFAULT, + }); + } + + let x = windowsx::GET_X_LPARAM(lparam) as f64; + let y = windowsx::GET_Y_LPARAM(lparam) as f64; + let position = PhysicalPosition::new(x, y); + let cursor_moved; + { + // handle spurious WM_MOUSEMOVE messages + // see https://devblogs.microsoft.com/oldnewthing/20031001-00/?p=42343 + // and http://debugandconquer.blogspot.com/2015/08/the-cause-of-spurious-mouse-move.html + let mut w = subclass_input.window_state.lock(); + cursor_moved = w.mouse.last_position != Some(position); + w.mouse.last_position = Some(position); + } + if cursor_moved { + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorMoved { + device_id: DEVICE_ID, + position, + modifiers: event::get_key_mods(), + }, + }); + } + + 0 + } + + winuser::WM_MOUSELEAVE => { + use crate::event::WindowEvent::CursorLeft; + { + let mut w = subclass_input.window_state.lock(); + w.mouse + .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)) + .ok(); + } + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorLeft { + device_id: DEVICE_ID, + }, + }); + + 0 + } + + winuser::WM_MOUSEWHEEL => { + use crate::event::MouseScrollDelta::LineDelta; + + let value = (wparam >> 16) as i16; + let value = value as i32; + let value = value as f32 / winuser::WHEEL_DELTA as f32; + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta: LineDelta(0.0, value), + phase: TouchPhase::Moved, + modifiers: event::get_key_mods(), + }, + }); + + 0 + } + + winuser::WM_MOUSEHWHEEL => { + use crate::event::MouseScrollDelta::LineDelta; + + let value = (wparam >> 16) as i16; + let value = value as i32; + let value = value as f32 / winuser::WHEEL_DELTA as f32; + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta: LineDelta(value, 0.0), + phase: TouchPhase::Moved, + modifiers: event::get_key_mods(), + }, + }); + + 0 + } + + winuser::WM_KEYDOWN | winuser::WM_SYSKEYDOWN => { + use crate::event::{ElementState::Pressed, VirtualKeyCode}; + if msg == winuser::WM_SYSKEYDOWN && wparam as i32 == winuser::VK_F4 { + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } else { + if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { + update_modifiers(window, subclass_input); + + #[allow(deprecated)] + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state: Pressed, + scancode, + virtual_keycode: vkey, + modifiers: event::get_key_mods(), + }, + is_synthetic: false, + }, + }); + // Windows doesn't emit a delete character by default, but in order to make it + // consistent with the other platforms we'll emit a delete character here. + if vkey == Some(VirtualKeyCode::Delete) { + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::ReceivedCharacter('\u{7F}'), + }); + } + } + 0 + } + } + + winuser::WM_KEYUP | winuser::WM_SYSKEYUP => { + use crate::event::ElementState::Released; + if let Some((scancode, vkey)) = process_key_params(wparam, lparam) { + update_modifiers(window, subclass_input); + + #[allow(deprecated)] + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + state: Released, + scancode, + virtual_keycode: vkey, + modifiers: event::get_key_mods(), + }, + is_synthetic: false, + }, + }); + } + 0 + } + + winuser::WM_LBUTTONDOWN => { + use crate::event::{ElementState::Pressed, MouseButton::Left, WindowEvent::MouseInput}; + + capture_mouse(window, &mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Pressed, + button: Left, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_LBUTTONUP => { + use crate::event::{ + ElementState::Released, MouseButton::Left, WindowEvent::MouseInput, + }; + + release_mouse(&mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Released, + button: Left, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_RBUTTONDOWN => { + use crate::event::{ + ElementState::Pressed, MouseButton::Right, WindowEvent::MouseInput, + }; + + capture_mouse(window, &mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Pressed, + button: Right, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_RBUTTONUP => { + use crate::event::{ + ElementState::Released, MouseButton::Right, WindowEvent::MouseInput, + }; + + release_mouse(&mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Released, + button: Right, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_MBUTTONDOWN => { + use crate::event::{ + ElementState::Pressed, MouseButton::Middle, WindowEvent::MouseInput, + }; + + capture_mouse(window, &mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Pressed, + button: Middle, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_MBUTTONUP => { + use crate::event::{ + ElementState::Released, MouseButton::Middle, WindowEvent::MouseInput, + }; + + release_mouse(&mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Released, + button: Middle, + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_XBUTTONDOWN => { + use crate::event::{ + ElementState::Pressed, MouseButton::Other, WindowEvent::MouseInput, + }; + let xbutton = winuser::GET_XBUTTON_WPARAM(wparam); + + capture_mouse(window, &mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Pressed, + button: Other(xbutton as u8), + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_XBUTTONUP => { + use crate::event::{ + ElementState::Released, MouseButton::Other, WindowEvent::MouseInput, + }; + let xbutton = winuser::GET_XBUTTON_WPARAM(wparam); + + release_mouse(&mut *subclass_input.window_state.lock()); + + update_modifiers(window, subclass_input); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Released, + button: Other(xbutton as u8), + modifiers: event::get_key_mods(), + }, + }); + 0 + } + + winuser::WM_TOUCH => { + let pcount = LOWORD(wparam as DWORD) as usize; + let mut inputs = Vec::with_capacity(pcount); + inputs.set_len(pcount); + let htouch = lparam as winuser::HTOUCHINPUT; + if winuser::GetTouchInputInfo( + htouch, + pcount as UINT, + inputs.as_mut_ptr(), + mem::size_of::() as INT, + ) > 0 + { + for input in &inputs { + let mut location = POINT { + x: input.x / 100, + y: input.y / 100, + }; + + if winuser::ScreenToClient(window, &mut location as *mut _) == 0 { + continue; + } + + let x = location.x as f64 + (input.x % 100) as f64 / 100f64; + let y = location.y as f64 + (input.y % 100) as f64 / 100f64; + let location = PhysicalPosition::new(x, y); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Touch(Touch { + phase: if input.dwFlags & winuser::TOUCHEVENTF_DOWN != 0 { + TouchPhase::Started + } else if input.dwFlags & winuser::TOUCHEVENTF_UP != 0 { + TouchPhase::Ended + } else if input.dwFlags & winuser::TOUCHEVENTF_MOVE != 0 { + TouchPhase::Moved + } else { + continue; + }, + location, + force: None, // WM_TOUCH doesn't support pressure information + id: input.dwID as u64, + device_id: DEVICE_ID, + }), + }); + } + } + winuser::CloseTouchInputHandle(htouch); + 0 + } + + winuser::WM_POINTERDOWN | winuser::WM_POINTERUPDATE | winuser::WM_POINTERUP => { + if let ( + Some(GetPointerFrameInfoHistory), + Some(SkipPointerFrameMessages), + Some(GetPointerDeviceRects), + ) = ( + *GET_POINTER_FRAME_INFO_HISTORY, + *SKIP_POINTER_FRAME_MESSAGES, + *GET_POINTER_DEVICE_RECTS, + ) { + let pointer_id = LOWORD(wparam as DWORD) as UINT; + let mut entries_count = 0 as UINT; + let mut pointers_count = 0 as UINT; + if GetPointerFrameInfoHistory( + pointer_id, + &mut entries_count as *mut _, + &mut pointers_count as *mut _, + std::ptr::null_mut(), + ) == 0 + { + return 0; + } + + let pointer_info_count = (entries_count * pointers_count) as usize; + let mut pointer_infos = Vec::with_capacity(pointer_info_count); + pointer_infos.set_len(pointer_info_count); + if GetPointerFrameInfoHistory( + pointer_id, + &mut entries_count as *mut _, + &mut pointers_count as *mut _, + pointer_infos.as_mut_ptr(), + ) == 0 + { + return 0; + } + + // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getpointerframeinfohistory + // The information retrieved appears in reverse chronological order, with the most recent entry in the first + // row of the returned array + for pointer_info in pointer_infos.iter().rev() { + let mut device_rect = mem::MaybeUninit::uninit(); + let mut display_rect = mem::MaybeUninit::uninit(); + + if (GetPointerDeviceRects( + pointer_info.sourceDevice, + device_rect.as_mut_ptr(), + display_rect.as_mut_ptr(), + )) == 0 + { + continue; + } + + let device_rect = device_rect.assume_init(); + let display_rect = display_rect.assume_init(); + + // For the most precise himetric to pixel conversion we calculate the ratio between the resolution + // of the display device (pixel) and the touch device (himetric). + let himetric_to_pixel_ratio_x = (display_rect.right - display_rect.left) as f64 + / (device_rect.right - device_rect.left) as f64; + let himetric_to_pixel_ratio_y = (display_rect.bottom - display_rect.top) as f64 + / (device_rect.bottom - device_rect.top) as f64; + + // ptHimetricLocation's origin is 0,0 even on multi-monitor setups. + // On multi-monitor setups we need to translate the himetric location to the rect of the + // display device it's attached to. + let x = display_rect.left as f64 + + pointer_info.ptHimetricLocation.x as f64 * himetric_to_pixel_ratio_x; + let y = display_rect.top as f64 + + pointer_info.ptHimetricLocation.y as f64 * himetric_to_pixel_ratio_y; + + let mut location = POINT { + x: x.floor() as i32, + y: y.floor() as i32, + }; + + if winuser::ScreenToClient(window, &mut location as *mut _) == 0 { + continue; + } + + let force = match pointer_info.pointerType { + winuser::PT_TOUCH => { + let mut touch_info = mem::MaybeUninit::uninit(); + GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| { + match GetPointerTouchInfo( + pointer_info.pointerId, + touch_info.as_mut_ptr(), + ) { + 0 => None, + _ => normalize_pointer_pressure( + touch_info.assume_init().pressure, + ), + } + }) + } + winuser::PT_PEN => { + let mut pen_info = mem::MaybeUninit::uninit(); + GET_POINTER_PEN_INFO.and_then(|GetPointerPenInfo| { + match GetPointerPenInfo( + pointer_info.pointerId, + pen_info.as_mut_ptr(), + ) { + 0 => None, + _ => { + normalize_pointer_pressure(pen_info.assume_init().pressure) + } + } + }) + } + _ => None, + }; + + let x = location.x as f64 + x.fract(); + let y = location.y as f64 + y.fract(); + let location = PhysicalPosition::new(x, y); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Touch(Touch { + phase: if pointer_info.pointerFlags & winuser::POINTER_FLAG_DOWN != 0 { + TouchPhase::Started + } else if pointer_info.pointerFlags & winuser::POINTER_FLAG_UP != 0 { + TouchPhase::Ended + } else if pointer_info.pointerFlags & winuser::POINTER_FLAG_UPDATE != 0 + { + TouchPhase::Moved + } else { + continue; + }, + location, + force, + id: pointer_info.pointerId as u64, + device_id: DEVICE_ID, + }), + }); + } + + SkipPointerFrameMessages(pointer_id); + } + 0 + } + + winuser::WM_SETFOCUS => { + use crate::event::{ElementState::Released, WindowEvent::Focused}; + for windows_keycode in event::get_pressed_keys() { + let scancode = + winuser::MapVirtualKeyA(windows_keycode as _, winuser::MAPVK_VK_TO_VSC); + let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode); + + update_modifiers(window, subclass_input); + + #[allow(deprecated)] + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + scancode, + virtual_keycode, + state: Released, + modifiers: event::get_key_mods(), + }, + is_synthetic: true, + }, + }) + } + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Focused(true), + }); + + 0 + } + + winuser::WM_KILLFOCUS => { + use crate::event::{ + ElementState::Released, + ModifiersState, + WindowEvent::{Focused, ModifiersChanged}, + }; + for windows_keycode in event::get_pressed_keys() { + let scancode = + winuser::MapVirtualKeyA(windows_keycode as _, winuser::MAPVK_VK_TO_VSC); + let virtual_keycode = event::vkey_to_winit_vkey(windows_keycode); + + #[allow(deprecated)] + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + input: KeyboardInput { + scancode, + virtual_keycode, + state: Released, + modifiers: event::get_key_mods(), + }, + is_synthetic: true, + }, + }) + } + + subclass_input.window_state.lock().modifiers_state = ModifiersState::empty(); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ModifiersChanged(ModifiersState::empty()), + }); + + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Focused(false), + }); + 0 + } + + winuser::WM_SETCURSOR => { + let set_cursor_to = { + let window_state = subclass_input.window_state.lock(); + if window_state + .mouse + .cursor_flags() + .contains(CursorFlags::IN_WINDOW) + { + Some(window_state.mouse.cursor) + } else { + None + } + }; + + match set_cursor_to { + Some(cursor) => { + let cursor = winuser::LoadCursorW(ptr::null_mut(), cursor.to_windows_cursor()); + winuser::SetCursor(cursor); + 0 + } + None => winuser::DefWindowProcW(window, msg, wparam, lparam), + } + } + + winuser::WM_DROPFILES => { + // See `FileDropHandler` for implementation. + 0 + } + + winuser::WM_GETMINMAXINFO => { + let mmi = lparam as *mut winuser::MINMAXINFO; + + let window_state = subclass_input.window_state.lock(); + + if window_state.min_size.is_some() || window_state.max_size.is_some() { + if let Some(min_size) = window_state.min_size { + let min_size = min_size.to_physical(window_state.scale_factor); + let (width, height): (u32, u32) = util::adjust_size(window, min_size).into(); + (*mmi).ptMinTrackSize = POINT { + x: width as i32, + y: height as i32, + }; + } + if let Some(max_size) = window_state.max_size { + let max_size = max_size.to_physical(window_state.scale_factor); + let (width, height): (u32, u32) = util::adjust_size(window, max_size).into(); + (*mmi).ptMaxTrackSize = POINT { + x: width as i32, + y: height as i32, + }; + } + } + + 0 + } + + // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change + // DPI, therefore all applications are closed while DPI is changing. + winuser::WM_DPICHANGED => { + use crate::event::WindowEvent::ScaleFactorChanged; + + // This message actually provides two DPI values - x and y. However MSDN says that + // "you only need to use either the X-axis or the Y-axis value when scaling your + // application since they are the same". + // https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx + let new_dpi_x = u32::from(LOWORD(wparam as DWORD)); + let new_scale_factor = dpi_to_scale_factor(new_dpi_x); + let old_scale_factor: f64; + + let allow_resize = { + let mut window_state = subclass_input.window_state.lock(); + old_scale_factor = window_state.scale_factor; + window_state.scale_factor = new_scale_factor; + + if new_scale_factor == old_scale_factor { + return 0; + } + + window_state.fullscreen.is_none() + && !window_state.window_flags().contains(WindowFlags::MAXIMIZED) + }; + + let style = winuser::GetWindowLongW(window, winuser::GWL_STYLE) as _; + let style_ex = winuser::GetWindowLongW(window, winuser::GWL_EXSTYLE) as _; + + // New size as suggested by Windows. + let suggested_rect = *(lparam as *const RECT); + + // The window rect provided is the window's outer size, not it's inner size. However, + // win32 doesn't provide an `UnadjustWindowRectEx` function to get the client rect from + // the outer rect, so we instead adjust the window rect to get the decoration margins + // and remove them from the outer size. + let margin_left: i32; + let margin_top: i32; + // let margin_right: i32; + // let margin_bottom: i32; + { + let adjusted_rect = + util::adjust_window_rect_with_styles(window, style, style_ex, suggested_rect) + .unwrap_or(suggested_rect); + margin_left = suggested_rect.left - adjusted_rect.left; + margin_top = suggested_rect.top - adjusted_rect.top; + // margin_right = adjusted_rect.right - suggested_rect.right; + // margin_bottom = adjusted_rect.bottom - suggested_rect.bottom; + } + + let old_physical_inner_rect = { + let mut old_physical_inner_rect = mem::zeroed(); + winuser::GetClientRect(window, &mut old_physical_inner_rect); + let mut origin = mem::zeroed(); + winuser::ClientToScreen(window, &mut origin); + + old_physical_inner_rect.left += origin.x; + old_physical_inner_rect.right += origin.x; + old_physical_inner_rect.top += origin.y; + old_physical_inner_rect.bottom += origin.y; + + old_physical_inner_rect + }; + let old_physical_inner_size = PhysicalSize::new( + (old_physical_inner_rect.right - old_physical_inner_rect.left) as u32, + (old_physical_inner_rect.bottom - old_physical_inner_rect.top) as u32, + ); + + // `allow_resize` prevents us from re-applying DPI adjustment to the restored size after + // exiting fullscreen (the restored size is already DPI adjusted). + let mut new_physical_inner_size = match allow_resize { + // We calculate our own size because the default suggested rect doesn't do a great job + // of preserving the window's logical size. + true => old_physical_inner_size + .to_logical::(old_scale_factor) + .to_physical::(new_scale_factor), + false => old_physical_inner_size, + }; + + let _ = subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ScaleFactorChanged { + scale_factor: new_scale_factor, + new_inner_size: &mut new_physical_inner_size, + }, + }); + + // Unset maximized if we're changing the window's size. + if new_physical_inner_size != old_physical_inner_size { + WindowState::set_window_flags(subclass_input.window_state.lock(), window, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + } + + let new_outer_rect: RECT; + { + let suggested_ul = ( + suggested_rect.left + margin_left, + suggested_rect.top + margin_top, + ); + + let mut conservative_rect = RECT { + left: suggested_ul.0, + top: suggested_ul.1, + right: suggested_ul.0 + new_physical_inner_size.width as LONG, + bottom: suggested_ul.1 + new_physical_inner_size.height as LONG, + }; + + conservative_rect = util::adjust_window_rect_with_styles( + window, + style, + style_ex, + conservative_rect, + ) + .unwrap_or(conservative_rect); + + // If we're not dragging the window, offset the window so that the cursor's + // relative horizontal position in the title bar is preserved. + let dragging_window = subclass_input.event_loop_runner.in_modal_loop(); + if dragging_window { + let bias = { + let cursor_pos = { + let mut pos = mem::zeroed(); + winuser::GetCursorPos(&mut pos); + pos + }; + let suggested_cursor_horizontal_ratio = (cursor_pos.x - suggested_rect.left) + as f64 + / (suggested_rect.right - suggested_rect.left) as f64; + + (cursor_pos.x + - (suggested_cursor_horizontal_ratio + * (conservative_rect.right - conservative_rect.left) as f64) + as LONG) + - conservative_rect.left + }; + conservative_rect.left += bias; + conservative_rect.right += bias; + } + + // Check to see if the new window rect is on the monitor with the new DPI factor. + // If it isn't, offset the window so that it is. + let new_dpi_monitor = winuser::MonitorFromWindow(window, 0); + let conservative_rect_monitor = winuser::MonitorFromRect(&conservative_rect, 0); + new_outer_rect = if conservative_rect_monitor == new_dpi_monitor { + conservative_rect + } else { + let get_monitor_rect = |monitor| { + let mut monitor_info = winuser::MONITORINFO { + cbSize: mem::size_of::() as _, + ..mem::zeroed() + }; + winuser::GetMonitorInfoW(monitor, &mut monitor_info); + monitor_info.rcMonitor + }; + let wrong_monitor = conservative_rect_monitor; + let wrong_monitor_rect = get_monitor_rect(wrong_monitor); + let new_monitor_rect = get_monitor_rect(new_dpi_monitor); + + // The direction to nudge the window in to get the window onto the monitor with + // the new DPI factor. We calculate this by seeing which monitor edges are + // shared and nudging away from the wrong monitor based on those. + let delta_nudge_to_dpi_monitor = ( + if wrong_monitor_rect.left == new_monitor_rect.right { + -1 + } else if wrong_monitor_rect.right == new_monitor_rect.left { + 1 + } else { + 0 + }, + if wrong_monitor_rect.bottom == new_monitor_rect.top { + 1 + } else if wrong_monitor_rect.top == new_monitor_rect.bottom { + -1 + } else { + 0 + }, + ); + + let abort_after_iterations = new_monitor_rect.right - new_monitor_rect.left + + new_monitor_rect.bottom + - new_monitor_rect.top; + for _ in 0..abort_after_iterations { + conservative_rect.left += delta_nudge_to_dpi_monitor.0; + conservative_rect.right += delta_nudge_to_dpi_monitor.0; + conservative_rect.top += delta_nudge_to_dpi_monitor.1; + conservative_rect.bottom += delta_nudge_to_dpi_monitor.1; + + if winuser::MonitorFromRect(&conservative_rect, 0) == new_dpi_monitor { + break; + } + } + + conservative_rect + }; + } + + winuser::SetWindowPos( + window, + ptr::null_mut(), + new_outer_rect.left, + new_outer_rect.top, + new_outer_rect.right - new_outer_rect.left, + new_outer_rect.bottom - new_outer_rect.top, + winuser::SWP_NOZORDER | winuser::SWP_NOACTIVATE, + ); + + 0 + } + + winuser::WM_SETTINGCHANGE => { + use crate::event::WindowEvent::ThemeChanged; + + let is_dark_mode = try_dark_mode(window); + let mut window_state = subclass_input.window_state.lock(); + let changed = window_state.is_dark_mode != is_dark_mode; + + if changed { + use crate::window::Theme::*; + let theme = if is_dark_mode { Dark } else { Light }; + + window_state.is_dark_mode = is_dark_mode; + mem::drop(window_state); + subclass_input.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ThemeChanged(theme), + }); + } + + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + _ => { + if msg == *DESTROY_MSG_ID { + winuser::DestroyWindow(window); + 0 + } else if msg == *SET_RETAIN_STATE_ON_SIZE_MSG_ID { + let mut window_state = subclass_input.window_state.lock(); + window_state.set_window_flags_in_place(|f| { + f.set(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE, wparam != 0) + }); + 0 + } else { + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + } + } +} + +unsafe extern "system" fn thread_event_target_callback( + window: HWND, + msg: UINT, + wparam: WPARAM, + lparam: LPARAM, + _: UINT_PTR, + subclass_input_ptr: DWORD_PTR, +) -> LRESULT { + let subclass_input = &mut *(subclass_input_ptr as *mut ThreadMsgTargetSubclassInput); + match msg { + winuser::WM_DESTROY => { + Box::from_raw(subclass_input); + drop(subclass_input); + 0 + } + // Because WM_PAINT comes after all other messages, we use it during modal loops to detect + // when the event queue has been emptied. See `process_event` for more details. + winuser::WM_PAINT => { + winuser::ValidateRect(window, ptr::null()); + let queue_call_again = || { + winuser::RedrawWindow( + window, + ptr::null(), + ptr::null_mut(), + winuser::RDW_INTERNALPAINT, + ); + }; + let in_modal_loop = subclass_input.event_loop_runner.in_modal_loop(); + if in_modal_loop { + let runner = &subclass_input.event_loop_runner; + runner.main_events_cleared(); + // Drain eventual WM_PAINT messages sent if user called request_redraw() + // during handling of MainEventsCleared. + let mut msg = mem::zeroed(); + loop { + if 0 == winuser::PeekMessageW( + &mut msg, + ptr::null_mut(), + winuser::WM_PAINT, + winuser::WM_PAINT, + winuser::PM_QS_PAINT | winuser::PM_REMOVE, + ) { + break; + } + + if msg.hwnd != window { + winuser::TranslateMessage(&mut msg); + winuser::DispatchMessageW(&mut msg); + } + } + runner.redraw_events_cleared(); + match runner.control_flow() { + // Waiting is handled by the modal loop. + ControlFlow::Exit | ControlFlow::Wait => runner.new_events(), + ControlFlow::WaitUntil(resume_time) => { + wait_until_time_or_msg(resume_time); + runner.new_events(); + queue_call_again(); + } + ControlFlow::Poll => { + runner.new_events(); + queue_call_again(); + } + } + } + 0 + } + + winuser::WM_INPUT_DEVICE_CHANGE => { + let event = match wparam as _ { + winuser::GIDC_ARRIVAL => DeviceEvent::Added, + winuser::GIDC_REMOVAL => DeviceEvent::Removed, + _ => unreachable!(), + }; + + subclass_input.send_event(Event::DeviceEvent { + device_id: wrap_device_id(lparam as _), + event, + }); + + 0 + } + + winuser::WM_INPUT => { + use crate::event::{ + DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel}, + ElementState::{Pressed, Released}, + MouseScrollDelta::LineDelta, + }; + + if let Some(data) = raw_input::get_raw_input_data(lparam as _) { + let device_id = wrap_device_id(data.header.hDevice as _); + + if data.header.dwType == winuser::RIM_TYPEMOUSE { + let mouse = data.data.mouse(); + + if util::has_flag(mouse.usFlags, winuser::MOUSE_MOVE_RELATIVE) { + let x = mouse.lLastX as f64; + let y = mouse.lLastY as f64; + + if x != 0.0 { + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: Motion { axis: 0, value: x }, + }); + } + + if y != 0.0 { + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: Motion { axis: 1, value: y }, + }); + } + + if x != 0.0 || y != 0.0 { + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: MouseMotion { delta: (x, y) }, + }); + } + } + + if util::has_flag(mouse.usButtonFlags, winuser::RI_MOUSE_WHEEL) { + let delta = mouse.usButtonData as SHORT / winuser::WHEEL_DELTA; + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: MouseWheel { + delta: LineDelta(0.0, delta as f32), + }, + }); + } + + let button_state = raw_input::get_raw_mouse_button_state(mouse.usButtonFlags); + // Left, middle, and right, respectively. + for (index, state) in button_state.iter().enumerate() { + if let Some(state) = *state { + // This gives us consistency with X11, since there doesn't + // seem to be anything else reasonable to do for a mouse + // button ID. + let button = (index + 1) as _; + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: Button { button, state }, + }); + } + } + } else if data.header.dwType == winuser::RIM_TYPEKEYBOARD { + let keyboard = data.data.keyboard(); + + let pressed = keyboard.Message == winuser::WM_KEYDOWN + || keyboard.Message == winuser::WM_SYSKEYDOWN; + let released = keyboard.Message == winuser::WM_KEYUP + || keyboard.Message == winuser::WM_SYSKEYUP; + + if pressed || released { + let state = if pressed { Pressed } else { Released }; + + let scancode = keyboard.MakeCode as _; + let extended = util::has_flag(keyboard.Flags, winuser::RI_KEY_E0 as _) + | util::has_flag(keyboard.Flags, winuser::RI_KEY_E1 as _); + + if let Some((vkey, scancode)) = + handle_extended_keys(keyboard.VKey as _, scancode, extended) + { + let virtual_keycode = vkey_to_winit_vkey(vkey); + + #[allow(deprecated)] + subclass_input.send_event(Event::DeviceEvent { + device_id, + event: Key(KeyboardInput { + scancode, + state, + virtual_keycode, + modifiers: event::get_key_mods(), + }), + }); + } + } + } + } + + commctrl::DefSubclassProc(window, msg, wparam, lparam) + } + + _ if msg == *USER_EVENT_MSG_ID => { + if let Ok(event) = subclass_input.user_event_receiver.recv() { + subclass_input.send_event(Event::UserEvent(event)); + } + 0 + } + _ if msg == *EXEC_MSG_ID => { + let mut function: ThreadExecFn = Box::from_raw(wparam as usize as *mut _); + function(); + 0 + } + _ => commctrl::DefSubclassProc(window, msg, wparam, lparam), + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop/runner.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop/runner.rs new file mode 100644 index 0000000..e5c062b --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/event_loop/runner.rs @@ -0,0 +1,475 @@ +use std::{any::Any, cell::RefCell, collections::VecDeque, mem, panic, ptr, rc::Rc, time::Instant}; + +use winapi::{shared::windef::HWND, um::winuser}; + +use crate::{ + dpi::PhysicalSize, + event::{Event, StartCause, WindowEvent}, + event_loop::ControlFlow, + platform_impl::platform::event_loop::{util, EventLoop}, + window::WindowId, +}; + +pub(crate) type EventLoopRunnerShared = Rc>; +pub(crate) struct ELRShared { + runner: RefCell>>, + buffer: RefCell>>, +} + +struct EventLoopRunner { + control_flow: ControlFlow, + runner_state: RunnerState, + modal_redraw_window: HWND, + in_modal_loop: bool, + event_handler: Box, &mut ControlFlow)>, + panic_error: Option, +} + +pub type PanicError = Box; + +pub enum BufferedEvent { + Event(Event<'static, T>), + ScaleFactorChanged(WindowId, f64, PhysicalSize), +} + +impl BufferedEvent { + pub fn from_event(event: Event<'_, T>) -> BufferedEvent { + match event { + Event::WindowEvent { + event: + WindowEvent::ScaleFactorChanged { + scale_factor, + new_inner_size, + }, + window_id, + } => BufferedEvent::ScaleFactorChanged(window_id, scale_factor, *new_inner_size), + event => BufferedEvent::Event(event.to_static().unwrap()), + } + } + + pub fn dispatch_event(self, dispatch: impl FnOnce(Event<'_, T>)) { + match self { + Self::Event(event) => dispatch(event), + Self::ScaleFactorChanged(window_id, scale_factor, mut new_inner_size) => { + dispatch(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor, + new_inner_size: &mut new_inner_size, + }, + }); + util::set_inner_size_physical( + (window_id.0).0, + new_inner_size.width as _, + new_inner_size.height as _, + ); + } + } + } +} + +impl ELRShared { + pub(crate) fn new() -> ELRShared { + ELRShared { + runner: RefCell::new(None), + buffer: RefCell::new(VecDeque::new()), + } + } + + pub(crate) unsafe fn set_runner(&self, event_loop: &EventLoop, f: F) + where + F: FnMut(Event<'_, T>, &mut ControlFlow), + { + let mut runner = EventLoopRunner::new(event_loop, f); + { + let mut runner_ref = self.runner.borrow_mut(); + // Dispatch any events that were buffered during the creation of the window + self.dispatch_buffered_events(&mut runner); + *runner_ref = Some(runner); + } + } + + pub(crate) fn destroy_runner(&self) { + *self.runner.borrow_mut() = None; + } + + pub(crate) fn new_events(&self) { + let mut runner_ref = self.runner.borrow_mut(); + if let Some(ref mut runner) = *runner_ref { + runner.new_events(); + // Dispatch any events that were buffered during the call `new_events` + self.dispatch_buffered_events(runner); + } + } + + pub(crate) fn send_event(&self, event: Event<'_, T>) { + if let Err(event) = self.send_event_unbuffered(event) { + // If the runner is already borrowed, we're in the middle of an event loop invocation. + // Add the event to a buffer to be processed later. + if let Event::RedrawRequested(_) = event { + panic!("buffering RedrawRequested event"); + } + self.buffer + .borrow_mut() + .push_back(BufferedEvent::from_event(event)); + } + } + + fn send_event_unbuffered<'e>(&self, event: Event<'e, T>) -> Result<(), Event<'e, T>> { + if let Ok(mut runner_ref) = self.runner.try_borrow_mut() { + if let Some(ref mut runner) = *runner_ref { + runner.process_event(event); + // Dispatch any events that were buffered during the call to `process_event`. + self.dispatch_buffered_events(runner); + return Ok(()); + } + } + Err(event) + } + + fn dispatch_buffered_events(&self, runner: &mut EventLoopRunner) { + // We do this instead of using a `while let` loop because if we use a `while let` + // loop the reference returned `borrow_mut()` doesn't get dropped until the end + // of the loop's body and attempts to add events to the event buffer while in + // `process_event` will fail. + loop { + let buffered_event_opt = self.buffer.borrow_mut().pop_front(); + match buffered_event_opt { + Some(e) => e.dispatch_event(|e| runner.process_event(e)), + None => break, + } + } + } + + pub(crate) fn main_events_cleared(&self) { + let mut runner_ref = self.runner.borrow_mut(); + if let Some(ref mut runner) = *runner_ref { + runner.main_events_cleared(); + if !self.buffer.borrow().is_empty() { + warn!("Buffered events while dispatching MainEventsCleared"); + } + } + } + + pub(crate) fn redraw_events_cleared(&self) { + let mut runner_ref = self.runner.borrow_mut(); + if let Some(ref mut runner) = *runner_ref { + runner.redraw_events_cleared(); + if !self.buffer.borrow().is_empty() { + warn!("Buffered events while dispatching RedrawEventsCleared"); + } + } + } + + pub(crate) fn destroy_loop(&self) { + if let Ok(mut runner_ref) = self.runner.try_borrow_mut() { + if let Some(ref mut runner) = *runner_ref { + runner.call_event_handler(Event::LoopDestroyed); + } + } + } + + pub(crate) fn take_panic_error(&self) -> Result<(), PanicError> { + let mut runner_ref = self.runner.borrow_mut(); + if let Some(ref mut runner) = *runner_ref { + runner.take_panic_error() + } else { + Ok(()) + } + } + + pub(crate) fn set_modal_loop(&self, in_modal_loop: bool) { + let mut runner_ref = self.runner.borrow_mut(); + if let Some(ref mut runner) = *runner_ref { + runner.in_modal_loop = in_modal_loop; + if in_modal_loop { + // jumpstart the modal loop + unsafe { + winuser::RedrawWindow( + runner.modal_redraw_window, + ptr::null(), + ptr::null_mut(), + winuser::RDW_INTERNALPAINT, + ); + } + } + } + } + + pub(crate) fn in_modal_loop(&self) -> bool { + let runner = self.runner.borrow(); + if let Some(ref runner) = *runner { + runner.in_modal_loop + } else { + false + } + } + + pub fn control_flow(&self) -> ControlFlow { + let runner_ref = self.runner.borrow(); + if let Some(ref runner) = *runner_ref { + runner.control_flow + } else { + ControlFlow::Exit + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RunnerState { + /// The event loop has just been created, and an `Init` event must be sent. + New, + /// The event loop is idling, and began idling at the given instant. + Idle(Instant), + /// The event loop has received a signal from the OS that the loop may resume, but no winit + /// events have been generated yet. We're waiting for an event to be processed or the events + /// to be marked as cleared to send `NewEvents`, depending on the current `ControlFlow`. + DeferredNewEvents(Instant), + /// The event loop is handling the OS's events and sending them to the user's callback. + /// `NewEvents` has been sent, and `MainEventsCleared` hasn't. + HandlingEvents, + /// The event loop is handling the redraw events and sending them to the user's callback. + /// `MainEventsCleared` has been sent, and `RedrawEventsCleared` hasn't. + HandlingRedraw, +} + +impl EventLoopRunner { + unsafe fn new(event_loop: &EventLoop, f: F) -> EventLoopRunner + where + F: FnMut(Event<'_, T>, &mut ControlFlow), + { + EventLoopRunner { + control_flow: ControlFlow::default(), + runner_state: RunnerState::New, + in_modal_loop: false, + modal_redraw_window: event_loop.window_target.p.thread_msg_target, + event_handler: mem::transmute::< + Box, &mut ControlFlow)>, + Box, &mut ControlFlow)>, + >(Box::new(f)), + panic_error: None, + } + } + + fn take_panic_error(&mut self) -> Result<(), PanicError> { + match self.panic_error.take() { + Some(err) => Err(err), + None => Ok(()), + } + } + + fn new_events(&mut self) { + self.runner_state = match self.runner_state { + // If we're already handling events or have deferred `NewEvents`, we don't need to do + // do any processing. + RunnerState::HandlingEvents + | RunnerState::HandlingRedraw + | RunnerState::DeferredNewEvents(..) => self.runner_state, + + // Send the `Init` `NewEvents` and immediately move into event processing. + RunnerState::New => { + self.call_event_handler(Event::NewEvents(StartCause::Init)); + RunnerState::HandlingEvents + } + + // When `NewEvents` gets sent after an idle depends on the control flow... + // Some `NewEvents` are deferred because not all Windows messages trigger an event_loop event. + // So we defer the `NewEvents` to when we actually process an event. + RunnerState::Idle(wait_start) => { + match self.control_flow { + // If we're polling, send `NewEvents` and immediately move into event processing. + ControlFlow::Poll => { + self.call_event_handler(Event::NewEvents(StartCause::Poll)); + RunnerState::HandlingEvents + }, + // If the user was waiting until a specific time, the `NewEvents` call gets sent + // at varying times depending on the current time. + ControlFlow::WaitUntil(resume_time) => { + match Instant::now() >= resume_time { + // If the current time is later than the requested resume time, we can tell the + // user that the resume time has been reached with `NewEvents` and immdiately move + // into event processing. + true => { + self.call_event_handler(Event::NewEvents(StartCause::ResumeTimeReached { + start: wait_start, + requested_resume: resume_time, + })); + RunnerState::HandlingEvents + }, + // However, if the current time is EARLIER than the requested resume time, we + // don't want to send the `WaitCancelled` event until we know an event is being + // sent. Defer. + false => RunnerState::DeferredNewEvents(wait_start) + } + }, + // If we're waiting, `NewEvents` doesn't get sent until winit gets an event, so + // we defer. + ControlFlow::Wait | + // `Exit` shouldn't really ever get sent here, but if it does do something somewhat sane. + ControlFlow::Exit => RunnerState::DeferredNewEvents(wait_start), + } + } + }; + } + + fn process_event(&mut self, event: Event<'_, T>) { + // If we're in the modal loop, we need to have some mechanism for finding when the event + // queue has been cleared so we can call `events_cleared`. Windows doesn't give any utilities + // for doing this, but it DOES guarantee that WM_PAINT will only occur after input events have + // been processed. So, we send WM_PAINT to a dummy window which calls `events_cleared` when + // the events queue has been emptied. + if self.in_modal_loop { + unsafe { + winuser::RedrawWindow( + self.modal_redraw_window, + ptr::null(), + ptr::null_mut(), + winuser::RDW_INTERNALPAINT, + ); + } + } + + // If new event processing has to be done (i.e. call NewEvents or defer), do it. If we're + // already in processing nothing happens with this call. + self.new_events(); + + // Now that an event has been received, we have to send any `NewEvents` calls that were + // deferred. + if let RunnerState::DeferredNewEvents(wait_start) = self.runner_state { + match self.control_flow { + ControlFlow::Exit | ControlFlow::Wait => { + self.call_event_handler(Event::NewEvents(StartCause::WaitCancelled { + start: wait_start, + requested_resume: None, + })) + } + ControlFlow::WaitUntil(resume_time) => { + let start_cause = match Instant::now() >= resume_time { + // If the current time is later than the requested resume time, the resume time + // has been reached. + true => StartCause::ResumeTimeReached { + start: wait_start, + requested_resume: resume_time, + }, + // Otherwise, the requested resume time HASN'T been reached and we send a WaitCancelled. + false => StartCause::WaitCancelled { + start: wait_start, + requested_resume: Some(resume_time), + }, + }; + self.call_event_handler(Event::NewEvents(start_cause)); + } + // This can be reached if the control flow is changed to poll during a `RedrawRequested` + // that was sent after `MainEventsCleared`. + ControlFlow::Poll => self.call_event_handler(Event::NewEvents(StartCause::Poll)), + } + self.runner_state = RunnerState::HandlingEvents; + } + + match (self.runner_state, &event) { + (RunnerState::HandlingEvents, Event::RedrawRequested(window_id)) => { + self.call_event_handler(Event::MainEventsCleared); + self.runner_state = RunnerState::HandlingRedraw; + self.call_event_handler(Event::RedrawRequested(*window_id)); + } + (RunnerState::HandlingRedraw, Event::RedrawRequested(window_id)) => { + self.call_event_handler(Event::RedrawRequested(*window_id)); + } + (RunnerState::HandlingRedraw, _) => { + warn!( + "non-redraw event in redraw phase: {:?}", + event.map_nonuser_event::<()>().ok() + ); + } + (_, _) => { + self.runner_state = RunnerState::HandlingEvents; + self.call_event_handler(event); + } + } + } + + fn main_events_cleared(&mut self) { + match self.runner_state { + // If we were handling events, send the MainEventsCleared message. + RunnerState::HandlingEvents => { + self.call_event_handler(Event::MainEventsCleared); + self.runner_state = RunnerState::HandlingRedraw; + } + + // We already cleared the main events, we don't have to do anything. + // This happens when process_events() processed a RedrawRequested event. + RunnerState::HandlingRedraw => {} + + // If we *weren't* handling events, we don't have to do anything. + RunnerState::New | RunnerState::Idle(..) => (), + + // Some control flows require a NewEvents call even if no events were received. This + // branch handles those. + RunnerState::DeferredNewEvents(wait_start) => { + match self.control_flow { + // If we had deferred a Poll, send the Poll NewEvents and MainEventsCleared. + ControlFlow::Poll => { + self.call_event_handler(Event::NewEvents(StartCause::Poll)); + self.runner_state = RunnerState::HandlingEvents; + self.call_event_handler(Event::MainEventsCleared); + self.runner_state = RunnerState::HandlingRedraw; + } + // If we had deferred a WaitUntil and the resume time has since been reached, + // send the resume notification and MainEventsCleared event. + ControlFlow::WaitUntil(resume_time) => { + if Instant::now() >= resume_time { + self.call_event_handler(Event::NewEvents( + StartCause::ResumeTimeReached { + start: wait_start, + requested_resume: resume_time, + }, + )); + self.runner_state = RunnerState::HandlingEvents; + self.call_event_handler(Event::MainEventsCleared); + self.runner_state = RunnerState::HandlingRedraw; + } + } + // If we deferred a wait and no events were received, the user doesn't have to + // get an event. + ControlFlow::Wait | ControlFlow::Exit => (), + } + } + } + } + + fn redraw_events_cleared(&mut self) { + match self.runner_state { + // If we were handling redraws, send the RedrawEventsCleared message. + RunnerState::HandlingRedraw => { + self.call_event_handler(Event::RedrawEventsCleared); + self.runner_state = RunnerState::Idle(Instant::now()); + } + // No event was processed, we don't have to do anything. + RunnerState::DeferredNewEvents(_) => (), + // Should not happen. + _ => warn!( + "unexpected state in redraw_events_cleared: {:?}", + self.runner_state + ), + } + } + + fn call_event_handler(&mut self, event: Event<'_, T>) { + if self.panic_error.is_none() { + let EventLoopRunner { + ref mut panic_error, + ref mut event_handler, + ref mut control_flow, + .. + } = self; + *panic_error = panic::catch_unwind(panic::AssertUnwindSafe(|| { + if *control_flow != ControlFlow::Exit { + (*event_handler)(event, control_flow); + } else { + (*event_handler)(event, &mut ControlFlow::Exit); + } + })) + .err(); + } + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/icon.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/icon.rs new file mode 100644 index 0000000..1308c74 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/icon.rs @@ -0,0 +1,169 @@ +use std::{fmt, io, iter::once, mem, os::windows::ffi::OsStrExt, path::Path, ptr, sync::Arc}; + +use winapi::{ + ctypes::{c_int, wchar_t}, + shared::{ + minwindef::{BYTE, LPARAM, WORD, WPARAM}, + windef::{HICON, HWND}, + }, + um::libloaderapi, + um::winuser, +}; + +use crate::dpi::PhysicalSize; +use crate::icon::*; + +impl Pixel { + fn to_bgra(&mut self) { + mem::swap(&mut self.r, &mut self.b); + } +} + +impl RgbaIcon { + fn into_windows_icon(self) -> Result { + let mut rgba = self.rgba; + let pixel_count = rgba.len() / PIXEL_SIZE; + let mut and_mask = Vec::with_capacity(pixel_count); + let pixels = + unsafe { std::slice::from_raw_parts_mut(rgba.as_mut_ptr() as *mut Pixel, pixel_count) }; + for pixel in pixels { + and_mask.push(pixel.a.wrapping_sub(std::u8::MAX)); // invert alpha channel + pixel.to_bgra(); + } + assert_eq!(and_mask.len(), pixel_count); + let handle = unsafe { + winuser::CreateIcon( + ptr::null_mut(), + self.width as c_int, + self.height as c_int, + 1, + (PIXEL_SIZE * 8) as BYTE, + and_mask.as_ptr() as *const BYTE, + rgba.as_ptr() as *const BYTE, + ) as HICON + }; + if !handle.is_null() { + Ok(WinIcon::from_handle(handle)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } +} + +#[derive(Debug)] +pub enum IconType { + Small = winuser::ICON_SMALL as isize, + Big = winuser::ICON_BIG as isize, +} + +#[derive(Debug)] +struct RaiiIcon { + handle: HICON, +} + +#[derive(Clone)] +pub struct WinIcon { + inner: Arc, +} + +unsafe impl Send for WinIcon {} + +impl WinIcon { + pub fn as_raw_handle(&self) -> HICON { + self.inner.handle + } + + pub fn from_path>( + path: P, + size: Option>, + ) -> Result { + let wide_path: Vec = path + .as_ref() + .as_os_str() + .encode_wide() + .chain(once(0)) + .collect(); + + // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size + let (width, height) = size.map(Into::into).unwrap_or((0, 0)); + + let handle = unsafe { + winuser::LoadImageW( + ptr::null_mut(), + wide_path.as_ptr() as *const wchar_t, + winuser::IMAGE_ICON, + width as c_int, + height as c_int, + winuser::LR_DEFAULTSIZE | winuser::LR_LOADFROMFILE, + ) as HICON + }; + if !handle.is_null() { + Ok(WinIcon::from_handle(handle)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } + + pub fn from_resource( + resource_id: WORD, + size: Option>, + ) -> Result { + // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size + let (width, height) = size.map(Into::into).unwrap_or((0, 0)); + let handle = unsafe { + winuser::LoadImageW( + libloaderapi::GetModuleHandleW(ptr::null_mut()), + winuser::MAKEINTRESOURCEW(resource_id), + winuser::IMAGE_ICON, + width as c_int, + height as c_int, + winuser::LR_DEFAULTSIZE, + ) as HICON + }; + if !handle.is_null() { + Ok(WinIcon::from_handle(handle)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } + + pub fn from_rgba(rgba: Vec, width: u32, height: u32) -> Result { + let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?; + rgba_icon.into_windows_icon() + } + + pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) { + unsafe { + winuser::SendMessageW( + hwnd, + winuser::WM_SETICON, + icon_type as WPARAM, + self.as_raw_handle() as LPARAM, + ); + } + } + + fn from_handle(handle: HICON) -> Self { + Self { + inner: Arc::new(RaiiIcon { handle }), + } + } +} + +impl Drop for RaiiIcon { + fn drop(&mut self) { + unsafe { winuser::DestroyIcon(self.handle) }; + } +} + +impl fmt::Debug for WinIcon { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + (*self.inner).fmt(formatter) + } +} + +pub fn unset_for_window(hwnd: HWND, icon_type: IconType) { + unsafe { + winuser::SendMessageW(hwnd, winuser::WM_SETICON, icon_type as WPARAM, 0 as LPARAM); + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/mod.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/mod.rs similarity index 67% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/windows/mod.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/mod.rs index 16f9e14..021c903 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/mod.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/mod.rs @@ -1,16 +1,23 @@ #![cfg(target_os = "windows")] -use winapi; -use winapi::shared::windef::HWND; +use winapi::{self, shared::windef::HWND}; -pub use self::events_loop::{EventsLoop, EventsLoopProxy}; -pub use self::monitor::MonitorId; -pub use self::window::Window; +pub use self::{ + event_loop::{EventLoop, EventLoopProxy, EventLoopWindowTarget}, + icon::WinIcon, + monitor::{MonitorHandle, VideoMode}, + window::Window, +}; + +pub use self::icon::WinIcon as PlatformIcon; + +use crate::event::DeviceId as RootDeviceId; +use crate::icon::Icon; #[derive(Clone, Default)] pub struct PlatformSpecificWindowBuilderAttributes { pub parent: Option, - pub taskbar_icon: Option<::Icon>, + pub taskbar_icon: Option, pub no_redirection_bitmap: bool, } @@ -33,7 +40,7 @@ impl DeviceId { } impl DeviceId { - pub fn get_persistent_identifier(&self) -> Option { + pub fn persistent_identifier(&self) -> Option { if self.0 != 0 { raw_input::get_raw_input_device_name(self.0 as _) } else { @@ -43,12 +50,14 @@ impl DeviceId { } // Constant device ID, to be removed when this backend is updated to report real device IDs. -const DEVICE_ID: ::DeviceId = ::DeviceId(DeviceId(0)); +const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId(0)); -fn wrap_device_id(id: u32) -> ::DeviceId { - ::DeviceId(DeviceId(id)) +fn wrap_device_id(id: u32) -> RootDeviceId { + RootDeviceId(DeviceId(id)) } +pub type OsError = std::io::Error; + #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct WindowId(HWND); unsafe impl Send for WindowId {} @@ -62,12 +71,15 @@ impl WindowId { } } +#[macro_use] +mod util; +mod dark_mode; mod dpi; mod drop_handler; mod event; -mod events_loop; +mod event_loop; mod icon; mod monitor; mod raw_input; -mod util; mod window; +mod window_state; diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/monitor.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/monitor.rs new file mode 100644 index 0000000..7136f35 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/monitor.rs @@ -0,0 +1,249 @@ +use winapi::{ + shared::{ + minwindef::{BOOL, DWORD, LPARAM, TRUE, WORD}, + windef::{HDC, HMONITOR, HWND, LPRECT, POINT}, + }, + um::{wingdi, winuser}, +}; + +use std::{ + collections::{BTreeSet, VecDeque}, + io, mem, ptr, +}; + +use super::{util, EventLoop}; +use crate::{ + dpi::{PhysicalPosition, PhysicalSize}, + monitor::{MonitorHandle as RootMonitorHandle, VideoMode as RootVideoMode}, + platform_impl::platform::{ + dpi::{dpi_to_scale_factor, get_monitor_dpi}, + window::Window, + }, +}; + +#[derive(Clone)] +pub struct VideoMode { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate: u16, + pub(crate) monitor: MonitorHandle, + pub(crate) native_video_mode: wingdi::DEVMODEW, +} + +impl PartialEq for VideoMode { + fn eq(&self, other: &Self) -> bool { + self.size == other.size + && self.bit_depth == other.bit_depth + && self.refresh_rate == other.refresh_rate + && self.monitor == other.monitor + } +} + +impl Eq for VideoMode {} + +impl std::hash::Hash for VideoMode { + fn hash(&self, state: &mut H) { + self.size.hash(state); + self.bit_depth.hash(state); + self.refresh_rate.hash(state); + self.monitor.hash(state); + } +} + +impl std::fmt::Debug for VideoMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoMode") + .field("size", &self.size) + .field("bit_depth", &self.bit_depth) + .field("refresh_rate", &self.refresh_rate) + .field("monitor", &self.monitor) + .finish() + } +} + +impl VideoMode { + pub fn size(&self) -> PhysicalSize { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate(&self) -> u16 { + self.refresh_rate + } + + pub fn monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: self.monitor.clone(), + } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] +pub struct MonitorHandle(HMONITOR); + +// Send is not implemented for HMONITOR, we have to wrap it and implement it manually. +// For more info see: +// https://github.com/retep998/winapi-rs/issues/360 +// https://github.com/retep998/winapi-rs/issues/396 + +unsafe impl Send for MonitorHandle {} + +unsafe extern "system" fn monitor_enum_proc( + hmonitor: HMONITOR, + _hdc: HDC, + _place: LPRECT, + data: LPARAM, +) -> BOOL { + let monitors = data as *mut VecDeque; + (*monitors).push_back(MonitorHandle::new(hmonitor)); + TRUE // continue enumeration +} + +pub fn available_monitors() -> VecDeque { + let mut monitors: VecDeque = VecDeque::new(); + unsafe { + winuser::EnumDisplayMonitors( + ptr::null_mut(), + ptr::null_mut(), + Some(monitor_enum_proc), + &mut monitors as *mut _ as LPARAM, + ); + } + monitors +} + +pub fn primary_monitor() -> MonitorHandle { + const ORIGIN: POINT = POINT { x: 0, y: 0 }; + let hmonitor = unsafe { winuser::MonitorFromPoint(ORIGIN, winuser::MONITOR_DEFAULTTOPRIMARY) }; + MonitorHandle::new(hmonitor) +} + +pub fn current_monitor(hwnd: HWND) -> MonitorHandle { + let hmonitor = unsafe { winuser::MonitorFromWindow(hwnd, winuser::MONITOR_DEFAULTTONEAREST) }; + MonitorHandle::new(hmonitor) +} + +impl EventLoop { + // TODO: Investigate opportunities for caching + pub fn available_monitors(&self) -> VecDeque { + available_monitors() + } + + pub fn primary_monitor(&self) -> MonitorHandle { + primary_monitor() + } +} + +impl Window { + pub fn available_monitors(&self) -> VecDeque { + available_monitors() + } + + pub fn primary_monitor(&self) -> MonitorHandle { + primary_monitor() + } +} + +pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result { + let mut monitor_info: winuser::MONITORINFOEXW = unsafe { mem::zeroed() }; + monitor_info.cbSize = mem::size_of::() as DWORD; + let status = unsafe { + winuser::GetMonitorInfoW( + hmonitor, + &mut monitor_info as *mut winuser::MONITORINFOEXW as *mut winuser::MONITORINFO, + ) + }; + if status == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(monitor_info) + } +} + +impl MonitorHandle { + pub(crate) fn new(hmonitor: HMONITOR) -> Self { + MonitorHandle(hmonitor) + } + + #[inline] + pub fn name(&self) -> Option { + let monitor_info = get_monitor_info(self.0).unwrap(); + Some(util::wchar_ptr_to_string(monitor_info.szDevice.as_ptr())) + } + + #[inline] + pub fn native_identifier(&self) -> String { + self.name().unwrap() + } + + #[inline] + pub fn hmonitor(&self) -> HMONITOR { + self.0 + } + + #[inline] + pub fn size(&self) -> PhysicalSize { + let monitor_info = get_monitor_info(self.0).unwrap(); + PhysicalSize { + width: (monitor_info.rcMonitor.right - monitor_info.rcMonitor.left) as u32, + height: (monitor_info.rcMonitor.bottom - monitor_info.rcMonitor.top) as u32, + } + } + + #[inline] + pub fn position(&self) -> PhysicalPosition { + let monitor_info = get_monitor_info(self.0).unwrap(); + PhysicalPosition { + x: monitor_info.rcMonitor.left, + y: monitor_info.rcMonitor.top, + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96)) + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator { + // EnumDisplaySettingsExW can return duplicate values (or some of the + // fields are probably changing, but we aren't looking at those fields + // anyway), so we're using a BTreeSet deduplicate + let mut modes = BTreeSet::new(); + let mut i = 0; + + loop { + unsafe { + let monitor_info = get_monitor_info(self.0).unwrap(); + let device_name = monitor_info.szDevice.as_ptr(); + let mut mode: wingdi::DEVMODEW = mem::zeroed(); + mode.dmSize = mem::size_of_val(&mode) as WORD; + if winuser::EnumDisplaySettingsExW(device_name, i, &mut mode, 0) == 0 { + break; + } + i += 1; + + const REQUIRED_FIELDS: DWORD = wingdi::DM_BITSPERPEL + | wingdi::DM_PELSWIDTH + | wingdi::DM_PELSHEIGHT + | wingdi::DM_DISPLAYFREQUENCY; + assert!(mode.dmFields & REQUIRED_FIELDS == REQUIRED_FIELDS); + + modes.insert(RootVideoMode { + video_mode: VideoMode { + size: (mode.dmPelsWidth, mode.dmPelsHeight), + bit_depth: mode.dmBitsPerPel as u16, + refresh_rate: mode.dmDisplayFrequency as u16, + monitor: self.clone(), + native_video_mode: mode, + }, + }); + } + } + + modes.into_iter() + } +} diff --git a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/raw_input.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/raw_input.rs similarity index 65% rename from third_party/cargo/vendor/winit-0.18.1/src/platform/windows/raw_input.rs rename to third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/raw_input.rs index 2f6e905..73b136a 100644 --- a/third_party/cargo/vendor/winit-0.18.1/src/platform/windows/raw_input.rs +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/raw_input.rs @@ -1,49 +1,35 @@ -use std::mem::{self, size_of}; -use std::ptr; - -use winapi::ctypes::wchar_t; -use winapi::shared::minwindef::{UINT, USHORT, TRUE}; -use winapi::shared::hidusage::{ - HID_USAGE_PAGE_GENERIC, - HID_USAGE_GENERIC_MOUSE, - HID_USAGE_GENERIC_KEYBOARD, -}; -use winapi::shared::windef::HWND; -use winapi::um::winnt::HANDLE; -use winapi::um::winuser::{ - self, - RAWINPUTDEVICELIST, - RID_DEVICE_INFO, - RID_DEVICE_INFO_MOUSE, - RID_DEVICE_INFO_KEYBOARD, - RID_DEVICE_INFO_HID, - RIM_TYPEMOUSE, - RIM_TYPEKEYBOARD, - RIM_TYPEHID, - RIDI_DEVICEINFO, - RIDI_DEVICENAME, - RAWINPUTDEVICE, - RIDEV_DEVNOTIFY, - RIDEV_INPUTSINK, - HRAWINPUT, - RAWINPUT, - RAWINPUTHEADER, - RID_INPUT, +use std::{ + mem::{self, size_of}, + ptr, }; -use platform::platform::util; -use events::ElementState; +use winapi::{ + ctypes::wchar_t, + shared::{ + hidusage::{HID_USAGE_GENERIC_KEYBOARD, HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC}, + minwindef::{TRUE, UINT, USHORT}, + windef::HWND, + }, + um::{ + winnt::HANDLE, + winuser::{ + self, HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTDEVICELIST, RAWINPUTHEADER, + RIDEV_DEVNOTIFY, RIDEV_INPUTSINK, RIDI_DEVICEINFO, RIDI_DEVICENAME, RID_DEVICE_INFO, + RID_DEVICE_INFO_HID, RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE, RID_INPUT, + RIM_TYPEHID, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, + }, + }, +}; + +use crate::{event::ElementState, platform_impl::platform::util}; #[allow(dead_code)] pub fn get_raw_input_device_list() -> Option> { let list_size = size_of::() as UINT; let mut num_devices = 0; - let status = unsafe { winuser::GetRawInputDeviceList( - ptr::null_mut(), - &mut num_devices, - list_size, - ) }; + let status = + unsafe { winuser::GetRawInputDeviceList(ptr::null_mut(), &mut num_devices, list_size) }; if status == UINT::max_value() { return None; @@ -51,11 +37,9 @@ pub fn get_raw_input_device_list() -> Option> { let mut buffer = Vec::with_capacity(num_devices as _); - let num_stored = unsafe { winuser::GetRawInputDeviceList( - buffer.as_ptr() as _, - &mut num_devices, - list_size, - ) }; + let num_stored = unsafe { + winuser::GetRawInputDeviceList(buffer.as_ptr() as _, &mut num_devices, list_size) + }; if num_stored == UINT::max_value() { return None; @@ -90,18 +74,20 @@ impl From for RawDeviceInfo { #[allow(dead_code)] pub fn get_raw_input_device_info(handle: HANDLE) -> Option { - let mut info: RID_DEVICE_INFO = unsafe { mem::uninitialized() }; + let mut info: RID_DEVICE_INFO = unsafe { mem::zeroed() }; let info_size = size_of::() as UINT; info.cbSize = info_size; let mut minimum_size = 0; - let status = unsafe { winuser::GetRawInputDeviceInfoW( - handle, - RIDI_DEVICEINFO, - &mut info as *mut _ as _, - &mut minimum_size, - ) }; + let status = unsafe { + winuser::GetRawInputDeviceInfoW( + handle, + RIDI_DEVICEINFO, + &mut info as *mut _ as _, + &mut minimum_size, + ) + }; if status == UINT::max_value() || status == 0 { return None; @@ -114,12 +100,9 @@ pub fn get_raw_input_device_info(handle: HANDLE) -> Option { pub fn get_raw_input_device_name(handle: HANDLE) -> Option { let mut minimum_size = 0; - let status = unsafe { winuser::GetRawInputDeviceInfoW( - handle, - RIDI_DEVICENAME, - ptr::null_mut(), - &mut minimum_size, - ) }; + let status = unsafe { + winuser::GetRawInputDeviceInfoW(handle, RIDI_DEVICENAME, ptr::null_mut(), &mut minimum_size) + }; if status != 0 { return None; @@ -127,12 +110,14 @@ pub fn get_raw_input_device_name(handle: HANDLE) -> Option { let mut name: Vec = Vec::with_capacity(minimum_size as _); - let status = unsafe { winuser::GetRawInputDeviceInfoW( - handle, - RIDI_DEVICENAME, - name.as_ptr() as _, - &mut minimum_size, - ) }; + let status = unsafe { + winuser::GetRawInputDeviceInfoW( + handle, + RIDI_DEVICENAME, + name.as_ptr() as _, + &mut minimum_size, + ) + }; if status == UINT::max_value() || status == 0 { return None; @@ -148,11 +133,9 @@ pub fn get_raw_input_device_name(handle: HANDLE) -> Option { pub fn register_raw_input_devices(devices: &[RAWINPUTDEVICE]) -> bool { let device_size = size_of::() as UINT; - let success = unsafe { winuser::RegisterRawInputDevices( - devices.as_ptr() as _, - devices.len() as _, - device_size, - ) }; + let success = unsafe { + winuser::RegisterRawInputDevices(devices.as_ptr() as _, devices.len() as _, device_size) + }; success == TRUE } @@ -181,17 +164,19 @@ pub fn register_all_mice_and_keyboards_for_raw_input(window_handle: HWND) -> boo } pub fn get_raw_input_data(handle: HRAWINPUT) -> Option { - let mut data: RAWINPUT = unsafe { mem::uninitialized() }; + let mut data: RAWINPUT = unsafe { mem::zeroed() }; let mut data_size = size_of::() as UINT; let header_size = size_of::() as UINT; - let status = unsafe { winuser::GetRawInputData( - handle, - RID_INPUT, - &mut data as *mut _ as _, - &mut data_size, - header_size, - ) }; + let status = unsafe { + winuser::GetRawInputData( + handle, + RID_INPUT, + &mut data as *mut _ as _, + &mut data_size, + header_size, + ) + }; if status == UINT::max_value() || status == 0 { return None; @@ -200,10 +185,11 @@ pub fn get_raw_input_data(handle: HRAWINPUT) -> Option { Some(data) } - -fn button_flags_to_element_state(button_flags: USHORT, down_flag: USHORT, up_flag: USHORT) - -> Option -{ +fn button_flags_to_element_state( + button_flags: USHORT, + down_flag: USHORT, + up_flag: USHORT, +) -> Option { // We assume the same button won't be simultaneously pressed and released. if util::has_flag(button_flags, down_flag) { Some(ElementState::Pressed) diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/util.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/util.rs new file mode 100644 index 0000000..5faaae3 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/util.rs @@ -0,0 +1,298 @@ +use std::{ + io, mem, + ops::BitAnd, + os::raw::c_void, + ptr, slice, + sync::atomic::{AtomicBool, Ordering}, +}; + +use crate::{dpi::PhysicalSize, window::CursorIcon}; +use winapi::{ + ctypes::wchar_t, + shared::{ + minwindef::{BOOL, DWORD, UINT}, + windef::{DPI_AWARENESS_CONTEXT, HMONITOR, HWND, LPRECT, RECT}, + }, + um::{ + libloaderapi::{GetProcAddress, LoadLibraryA}, + shellscalingapi::{MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS}, + winbase::lstrlenW, + winnt::{HRESULT, LONG, LPCSTR}, + winuser, + }, +}; + +pub fn has_flag(bitset: T, flag: T) -> bool +where + T: Copy + PartialEq + BitAnd, +{ + bitset & flag == flag +} + +pub fn wchar_to_string(wchar: &[wchar_t]) -> String { + String::from_utf16_lossy(wchar).to_string() +} + +pub fn wchar_ptr_to_string(wchar: *const wchar_t) -> String { + let len = unsafe { lstrlenW(wchar) } as usize; + let wchar_slice = unsafe { slice::from_raw_parts(wchar, len) }; + wchar_to_string(wchar_slice) +} + +pub unsafe fn status_map BOOL>(mut fun: F) -> Option { + let mut data: T = mem::zeroed(); + if fun(&mut data) != 0 { + Some(data) + } else { + None + } +} + +fn win_to_err BOOL>(f: F) -> Result<(), io::Error> { + if f() != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +pub fn get_window_rect(hwnd: HWND) -> Option { + unsafe { status_map(|rect| winuser::GetWindowRect(hwnd, rect)) } +} + +pub fn get_client_rect(hwnd: HWND) -> Result { + unsafe { + let mut rect = mem::zeroed(); + let mut top_left = mem::zeroed(); + + win_to_err(|| winuser::ClientToScreen(hwnd, &mut top_left))?; + win_to_err(|| winuser::GetClientRect(hwnd, &mut rect))?; + rect.left += top_left.x; + rect.top += top_left.y; + rect.right += top_left.x; + rect.bottom += top_left.y; + + Ok(rect) + } +} + +pub fn adjust_size(hwnd: HWND, size: PhysicalSize) -> PhysicalSize { + let (width, height): (u32, u32) = size.into(); + let rect = RECT { + left: 0, + right: width as LONG, + top: 0, + bottom: height as LONG, + }; + let rect = adjust_window_rect(hwnd, rect).unwrap_or(rect); + PhysicalSize::new((rect.right - rect.left) as _, (rect.bottom - rect.top) as _) +} + +pub(crate) fn set_inner_size_physical(window: HWND, x: u32, y: u32) { + unsafe { + let rect = adjust_window_rect( + window, + RECT { + top: 0, + left: 0, + bottom: y as LONG, + right: x as LONG, + }, + ) + .expect("adjust_window_rect failed"); + + let outer_x = (rect.right - rect.left).abs() as _; + let outer_y = (rect.top - rect.bottom).abs() as _; + winuser::SetWindowPos( + window, + ptr::null_mut(), + 0, + 0, + outer_x, + outer_y, + winuser::SWP_ASYNCWINDOWPOS + | winuser::SWP_NOZORDER + | winuser::SWP_NOREPOSITION + | winuser::SWP_NOMOVE + | winuser::SWP_NOACTIVATE, + ); + winuser::InvalidateRgn(window, ptr::null_mut(), 0); + } +} + +pub fn adjust_window_rect(hwnd: HWND, rect: RECT) -> Option { + unsafe { + let style = winuser::GetWindowLongW(hwnd, winuser::GWL_STYLE); + let style_ex = winuser::GetWindowLongW(hwnd, winuser::GWL_EXSTYLE); + adjust_window_rect_with_styles(hwnd, style as _, style_ex as _, rect) + } +} + +pub fn adjust_window_rect_with_styles( + hwnd: HWND, + style: DWORD, + style_ex: DWORD, + rect: RECT, +) -> Option { + unsafe { + status_map(|r| { + *r = rect; + + let b_menu = !winuser::GetMenu(hwnd).is_null() as BOOL; + if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) = + (*GET_DPI_FOR_WINDOW, *ADJUST_WINDOW_RECT_EX_FOR_DPI) + { + let dpi = get_dpi_for_window(hwnd); + adjust_window_rect_ex_for_dpi(r, style as _, b_menu, style_ex as _, dpi) + } else { + winuser::AdjustWindowRectEx(r, style as _, b_menu, style_ex as _) + } + }) + } +} + +pub fn set_cursor_hidden(hidden: bool) { + static HIDDEN: AtomicBool = AtomicBool::new(false); + let changed = HIDDEN.swap(hidden, Ordering::SeqCst) ^ hidden; + if changed { + unsafe { winuser::ShowCursor(!hidden as BOOL) }; + } +} + +pub fn get_cursor_clip() -> Result { + unsafe { + let mut rect: RECT = mem::zeroed(); + win_to_err(|| winuser::GetClipCursor(&mut rect)).map(|_| rect) + } +} + +/// Sets the cursor's clip rect. +/// +/// Note that calling this will automatically dispatch a `WM_MOUSEMOVE` event. +pub fn set_cursor_clip(rect: Option) -> Result<(), io::Error> { + unsafe { + let rect_ptr = rect + .as_ref() + .map(|r| r as *const RECT) + .unwrap_or(ptr::null()); + win_to_err(|| winuser::ClipCursor(rect_ptr)) + } +} + +pub fn get_desktop_rect() -> RECT { + unsafe { + let left = winuser::GetSystemMetrics(winuser::SM_XVIRTUALSCREEN); + let top = winuser::GetSystemMetrics(winuser::SM_YVIRTUALSCREEN); + RECT { + left, + top, + right: left + winuser::GetSystemMetrics(winuser::SM_CXVIRTUALSCREEN), + bottom: top + winuser::GetSystemMetrics(winuser::SM_CYVIRTUALSCREEN), + } + } +} + +pub fn is_focused(window: HWND) -> bool { + window == unsafe { winuser::GetActiveWindow() } +} + +impl CursorIcon { + pub(crate) fn to_windows_cursor(self) -> *const wchar_t { + match self { + CursorIcon::Arrow | CursorIcon::Default => winuser::IDC_ARROW, + CursorIcon::Hand => winuser::IDC_HAND, + CursorIcon::Crosshair => winuser::IDC_CROSS, + CursorIcon::Text | CursorIcon::VerticalText => winuser::IDC_IBEAM, + CursorIcon::NotAllowed | CursorIcon::NoDrop => winuser::IDC_NO, + CursorIcon::Grab | CursorIcon::Grabbing | CursorIcon::Move | CursorIcon::AllScroll => { + winuser::IDC_SIZEALL + } + CursorIcon::EResize + | CursorIcon::WResize + | CursorIcon::EwResize + | CursorIcon::ColResize => winuser::IDC_SIZEWE, + CursorIcon::NResize + | CursorIcon::SResize + | CursorIcon::NsResize + | CursorIcon::RowResize => winuser::IDC_SIZENS, + CursorIcon::NeResize | CursorIcon::SwResize | CursorIcon::NeswResize => { + winuser::IDC_SIZENESW + } + CursorIcon::NwResize | CursorIcon::SeResize | CursorIcon::NwseResize => { + winuser::IDC_SIZENWSE + } + CursorIcon::Wait => winuser::IDC_WAIT, + CursorIcon::Progress => winuser::IDC_APPSTARTING, + CursorIcon::Help => winuser::IDC_HELP, + _ => winuser::IDC_ARROW, // use arrow for the missing cases. + } + } +} + +// Helper function to dynamically load function pointer. +// `library` and `function` must be zero-terminated. +pub(super) fn get_function_impl(library: &str, function: &str) -> Option<*const c_void> { + assert_eq!(library.chars().last(), Some('\0')); + assert_eq!(function.chars().last(), Some('\0')); + + // Library names we will use are ASCII so we can use the A version to avoid string conversion. + let module = unsafe { LoadLibraryA(library.as_ptr() as LPCSTR) }; + if module.is_null() { + return None; + } + + let function_ptr = unsafe { GetProcAddress(module, function.as_ptr() as LPCSTR) }; + if function_ptr.is_null() { + return None; + } + + Some(function_ptr as _) +} + +macro_rules! get_function { + ($lib:expr, $func:ident) => { + crate::platform_impl::platform::util::get_function_impl( + concat!($lib, '\0'), + concat!(stringify!($func), '\0'), + ) + .map(|f| unsafe { std::mem::transmute::<*const _, $func>(f) }) + }; +} + +pub type SetProcessDPIAware = unsafe extern "system" fn() -> BOOL; +pub type SetProcessDpiAwareness = + unsafe extern "system" fn(value: PROCESS_DPI_AWARENESS) -> HRESULT; +pub type SetProcessDpiAwarenessContext = + unsafe extern "system" fn(value: DPI_AWARENESS_CONTEXT) -> BOOL; +pub type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> UINT; +pub type GetDpiForMonitor = unsafe extern "system" fn( + hmonitor: HMONITOR, + dpi_type: MONITOR_DPI_TYPE, + dpi_x: *mut UINT, + dpi_y: *mut UINT, +) -> HRESULT; +pub type EnableNonClientDpiScaling = unsafe extern "system" fn(hwnd: HWND) -> BOOL; +pub type AdjustWindowRectExForDpi = unsafe extern "system" fn( + rect: LPRECT, + dwStyle: DWORD, + bMenu: BOOL, + dwExStyle: DWORD, + dpi: UINT, +) -> BOOL; + +lazy_static! { + pub static ref GET_DPI_FOR_WINDOW: Option = + get_function!("user32.dll", GetDpiForWindow); + pub static ref ADJUST_WINDOW_RECT_EX_FOR_DPI: Option = + get_function!("user32.dll", AdjustWindowRectExForDpi); + pub static ref GET_DPI_FOR_MONITOR: Option = + get_function!("shcore.dll", GetDpiForMonitor); + pub static ref ENABLE_NON_CLIENT_DPI_SCALING: Option = + get_function!("user32.dll", EnableNonClientDpiScaling); + pub static ref SET_PROCESS_DPI_AWARENESS_CONTEXT: Option = + get_function!("user32.dll", SetProcessDpiAwarenessContext); + pub static ref SET_PROCESS_DPI_AWARENESS: Option = + get_function!("shcore.dll", SetProcessDpiAwareness); + pub static ref SET_PROCESS_DPI_AWARE: Option = + get_function!("user32.dll", SetProcessDPIAware); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window.rs new file mode 100644 index 0000000..3c58e1f --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window.rs @@ -0,0 +1,897 @@ +#![cfg(target_os = "windows")] + +use parking_lot::Mutex; +use raw_window_handle::{windows::WindowsHandle, RawWindowHandle}; +use std::{ + cell::Cell, + ffi::OsStr, + io, mem, + os::windows::ffi::OsStrExt, + ptr, + sync::{mpsc::channel, Arc}, +}; + +use winapi::{ + ctypes::c_int, + shared::{ + minwindef::{HINSTANCE, UINT}, + windef::{HWND, POINT, RECT}, + }, + um::{ + combaseapi, dwmapi, libloaderapi, + objbase::COINIT_APARTMENTTHREADED, + ole2, + oleidl::LPDROPTARGET, + shobjidl_core::{CLSID_TaskbarList, ITaskbarList2}, + wingdi::{CreateRectRgn, DeleteObject}, + winnt::LPCWSTR, + winuser, + }, +}; + +use crate::{ + dpi::{PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError as RootOsError}, + icon::Icon, + monitor::MonitorHandle as RootMonitorHandle, + platform_impl::platform::{ + dark_mode::try_dark_mode, + dpi::{dpi_to_scale_factor, hwnd_dpi}, + drop_handler::FileDropHandler, + event_loop::{self, EventLoopWindowTarget, DESTROY_MSG_ID}, + icon::{self, IconType}, + monitor, util, + window_state::{CursorFlags, SavedWindow, WindowFlags, WindowState}, + PlatformSpecificWindowBuilderAttributes, WindowId, + }, + window::{CursorIcon, Fullscreen, WindowAttributes}, +}; + +/// The Win32 implementation of the main `Window` object. +pub struct Window { + /// Main handle for the window. + window: WindowWrapper, + + /// The current window state. + window_state: Arc>, + + // The events loop proxy. + thread_executor: event_loop::EventLoopThreadExecutor, +} + +impl Window { + pub fn new( + event_loop: &EventLoopWindowTarget, + w_attr: WindowAttributes, + pl_attr: PlatformSpecificWindowBuilderAttributes, + ) -> Result { + // We dispatch an `init` function because of code style. + // First person to remove the need for cloning here gets a cookie! + // + // done. you owe me -- ossi + unsafe { + init(w_attr, pl_attr, event_loop).map(|win| { + let file_drop_handler = { + use winapi::shared::winerror::{OLE_E_WRONGCOMPOBJ, RPC_E_CHANGED_MODE, S_OK}; + + let ole_init_result = ole2::OleInitialize(ptr::null_mut()); + // It is ok if the initialize result is `S_FALSE` because it might happen that + // multiple windows are created on the same thread. + if ole_init_result == OLE_E_WRONGCOMPOBJ { + panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`"); + } else if ole_init_result == RPC_E_CHANGED_MODE { + panic!("OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`"); + } + + let file_drop_runner = event_loop.runner_shared.clone(); + let file_drop_handler = FileDropHandler::new( + win.window.0, + Box::new(move |event| { + if let Ok(e) = event.map_nonuser_event() { + file_drop_runner.send_event(e) + } + }), + ); + let handler_interface_ptr = + &mut (*file_drop_handler.data).interface as LPDROPTARGET; + + assert_eq!( + ole2::RegisterDragDrop(win.window.0, handler_interface_ptr), + S_OK + ); + file_drop_handler + }; + + let subclass_input = event_loop::SubclassInput { + window_state: win.window_state.clone(), + event_loop_runner: event_loop.runner_shared.clone(), + file_drop_handler, + }; + + event_loop::subclass_window(win.window.0, subclass_input); + win + }) + } + } + + pub fn set_title(&self, text: &str) { + let text = OsStr::new(text) + .encode_wide() + .chain(Some(0).into_iter()) + .collect::>(); + unsafe { + winuser::SetWindowTextW(self.window.0, text.as_ptr() as LPCWSTR); + } + } + + #[inline] + pub fn set_visible(&self, visible: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::VISIBLE, visible) + }); + }); + } + + #[inline] + pub fn request_redraw(&self) { + unsafe { + winuser::RedrawWindow( + self.window.0, + ptr::null(), + ptr::null_mut(), + winuser::RDW_INTERNALPAINT, + ); + } + } + + #[inline] + pub fn outer_position(&self) -> Result, NotSupportedError> { + util::get_window_rect(self.window.0) + .map(|rect| Ok(PhysicalPosition::new(rect.left as i32, rect.top as i32))) + .expect("Unexpected GetWindowRect failure; please report this error to https://github.com/rust-windowing/winit") + } + + #[inline] + pub fn inner_position(&self) -> Result, NotSupportedError> { + let mut position: POINT = unsafe { mem::zeroed() }; + if unsafe { winuser::ClientToScreen(self.window.0, &mut position) } == 0 { + panic!("Unexpected ClientToScreen failure: please report this error to https://github.com/rust-windowing/winit") + } + Ok(PhysicalPosition::new(position.x as i32, position.y as i32)) + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + let (x, y): (i32, i32) = position.to_physical::(self.scale_factor()).into(); + + let window_state = Arc::clone(&self.window_state); + let window = self.window.clone(); + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + }); + + unsafe { + winuser::SetWindowPos( + self.window.0, + ptr::null_mut(), + x as c_int, + y as c_int, + 0, + 0, + winuser::SWP_ASYNCWINDOWPOS + | winuser::SWP_NOZORDER + | winuser::SWP_NOSIZE + | winuser::SWP_NOACTIVATE, + ); + winuser::InvalidateRgn(self.window.0, ptr::null_mut(), 0); + } + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + let mut rect: RECT = unsafe { mem::zeroed() }; + if unsafe { winuser::GetClientRect(self.window.0, &mut rect) } == 0 { + panic!("Unexpected GetClientRect failure: please report this error to https://github.com/rust-windowing/winit") + } + PhysicalSize::new( + (rect.right - rect.left) as u32, + (rect.bottom - rect.top) as u32, + ) + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + util::get_window_rect(self.window.0) + .map(|rect| { + PhysicalSize::new( + (rect.right - rect.left) as u32, + (rect.bottom - rect.top) as u32, + ) + }) + .unwrap() + } + + #[inline] + pub fn set_inner_size(&self, size: Size) { + let scale_factor = self.scale_factor(); + let (width, height) = size.to_physical::(scale_factor).into(); + + let window_state = Arc::clone(&self.window_state); + let window = self.window.clone(); + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + }); + + util::set_inner_size_physical(self.window.0, width, height); + } + + #[inline] + pub fn set_min_inner_size(&self, size: Option) { + self.window_state.lock().min_size = size; + // Make windows re-check the window size bounds. + let size = self.inner_size(); + self.set_inner_size(size.into()); + } + + #[inline] + pub fn set_max_inner_size(&self, size: Option) { + self.window_state.lock().max_size = size; + // Make windows re-check the window size bounds. + let size = self.inner_size(); + self.set_inner_size(size.into()); + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::RESIZABLE, resizable) + }); + }); + } + + /// Returns the `hwnd` of this window. + #[inline] + pub fn hwnd(&self) -> HWND { + self.window.0 + } + + #[inline] + pub fn hinstance(&self) -> HINSTANCE { + unsafe { winuser::GetWindowLongW(self.hwnd(), winuser::GWL_HINSTANCE) as *mut _ } + } + + #[inline] + pub fn raw_window_handle(&self) -> RawWindowHandle { + let handle = WindowsHandle { + hwnd: self.window.0 as *mut _, + hinstance: self.hinstance() as *mut _, + ..WindowsHandle::empty() + }; + RawWindowHandle::Windows(handle) + } + + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + self.window_state.lock().mouse.cursor = cursor; + self.thread_executor.execute_in_thread(move || unsafe { + let cursor = winuser::LoadCursorW(ptr::null_mut(), cursor.to_windows_cursor()); + winuser::SetCursor(cursor); + }); + } + + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + + self.thread_executor.execute_in_thread(move || { + let result = window_state + .lock() + .mouse + .set_cursor_flags(window.0, |f| f.set(CursorFlags::GRABBED, grab)) + .map_err(|e| ExternalError::Os(os_error!(e))); + let _ = tx.send(result); + }); + rx.recv().unwrap() + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + + self.thread_executor.execute_in_thread(move || { + let result = window_state + .lock() + .mouse + .set_cursor_flags(window.0, |f| f.set(CursorFlags::HIDDEN, !visible)) + .map_err(|e| e.to_string()); + let _ = tx.send(result); + }); + rx.recv().unwrap().ok(); + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window_state.lock().scale_factor + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + let scale_factor = self.scale_factor(); + let (x, y) = position.to_physical::(scale_factor).into(); + + let mut point = POINT { x, y }; + unsafe { + if winuser::ClientToScreen(self.window.0, &mut point) == 0 { + return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); + } + if winuser::SetCursorPos(point.x, point.y) == 0 { + return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); + } + } + Ok(()) + } + + #[inline] + pub fn id(&self) -> WindowId { + WindowId(self.window.0) + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::MINIMIZED, minimized) + }); + }); + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::MAXIMIZED, maximized) + }); + }); + } + + #[inline] + pub fn fullscreen(&self) -> Option { + let window_state = self.window_state.lock(); + window_state.fullscreen.clone() + } + + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + let mut window_state_lock = window_state.lock(); + let old_fullscreen = window_state_lock.fullscreen.clone(); + if window_state_lock.fullscreen == fullscreen { + return; + } + window_state_lock.fullscreen = fullscreen.clone(); + drop(window_state_lock); + + self.thread_executor.execute_in_thread(move || { + let mut window_state_lock = window_state.lock(); + + // Save window bounds before entering fullscreen + match (&old_fullscreen, &fullscreen) { + (&None, &Some(_)) => { + let client_rect = util::get_client_rect(window.0).unwrap(); + window_state_lock.saved_window = Some(SavedWindow { + client_rect, + scale_factor: window_state_lock.scale_factor, + }); + } + _ => (), + } + + // Change video mode if we're transitioning to or from exclusive + // fullscreen + match (&old_fullscreen, &fullscreen) { + (&None, &Some(Fullscreen::Exclusive(ref video_mode))) + | ( + &Some(Fullscreen::Borderless(_)), + &Some(Fullscreen::Exclusive(ref video_mode)), + ) + | (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Exclusive(ref video_mode))) => + { + let monitor = video_mode.monitor(); + + let mut display_name = OsStr::new(&monitor.inner.native_identifier()) + .encode_wide() + .collect::>(); + // `encode_wide` does not add a null-terminator but + // `ChangeDisplaySettingsExW` requires a null-terminated + // string, so add it + display_name.push(0); + + let mut native_video_mode = video_mode.video_mode.native_video_mode.clone(); + + let res = unsafe { + winuser::ChangeDisplaySettingsExW( + display_name.as_ptr(), + &mut native_video_mode, + std::ptr::null_mut(), + winuser::CDS_FULLSCREEN, + std::ptr::null_mut(), + ) + }; + + debug_assert!(res != winuser::DISP_CHANGE_BADFLAGS); + debug_assert!(res != winuser::DISP_CHANGE_BADMODE); + debug_assert!(res != winuser::DISP_CHANGE_BADPARAM); + debug_assert!(res != winuser::DISP_CHANGE_FAILED); + assert_eq!(res, winuser::DISP_CHANGE_SUCCESSFUL); + } + (&Some(Fullscreen::Exclusive(_)), &None) + | (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Borderless(_))) => { + let res = unsafe { + winuser::ChangeDisplaySettingsExW( + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + winuser::CDS_FULLSCREEN, + std::ptr::null_mut(), + ) + }; + + debug_assert!(res != winuser::DISP_CHANGE_BADFLAGS); + debug_assert!(res != winuser::DISP_CHANGE_BADMODE); + debug_assert!(res != winuser::DISP_CHANGE_BADPARAM); + debug_assert!(res != winuser::DISP_CHANGE_FAILED); + assert_eq!(res, winuser::DISP_CHANGE_SUCCESSFUL); + } + _ => (), + } + + unsafe { + // There are some scenarios where calling `ChangeDisplaySettingsExW` takes long + // enough to execute that the DWM thinks our program has frozen and takes over + // our program's window. When that happens, the `SetWindowPos` call below gets + // eaten and the window doesn't get set to the proper fullscreen position. + // + // Calling `PeekMessageW` here notifies Windows that our process is still running + // fine, taking control back from the DWM and ensuring that the `SetWindowPos` call + // below goes through. + let mut msg = mem::zeroed(); + winuser::PeekMessageW(&mut msg, ptr::null_mut(), 0, 0, 0); + } + + // Update window style + WindowState::set_window_flags(window_state_lock, window.0, |f| { + f.set(WindowFlags::MARKER_FULLSCREEN, fullscreen.is_some()) + }); + + // Update window bounds + match &fullscreen { + Some(fullscreen) => { + let monitor = match fullscreen { + Fullscreen::Exclusive(ref video_mode) => video_mode.monitor(), + Fullscreen::Borderless(ref monitor) => monitor.clone(), + }; + + let position: (i32, i32) = monitor.position().into(); + let size: (u32, u32) = monitor.size().into(); + + unsafe { + winuser::SetWindowPos( + window.0, + ptr::null_mut(), + position.0, + position.1, + size.0 as i32, + size.1 as i32, + winuser::SWP_ASYNCWINDOWPOS | winuser::SWP_NOZORDER, + ); + winuser::InvalidateRgn(window.0, ptr::null_mut(), 0); + } + } + None => { + let mut window_state_lock = window_state.lock(); + if let Some(SavedWindow { + client_rect, + scale_factor, + }) = window_state_lock.saved_window.take() + { + window_state_lock.scale_factor = scale_factor; + drop(window_state_lock); + let client_rect = util::adjust_window_rect(window.0, client_rect).unwrap(); + + unsafe { + winuser::SetWindowPos( + window.0, + ptr::null_mut(), + client_rect.left, + client_rect.top, + client_rect.right - client_rect.left, + client_rect.bottom - client_rect.top, + winuser::SWP_ASYNCWINDOWPOS + | winuser::SWP_NOZORDER + | winuser::SWP_NOACTIVATE, + ); + winuser::InvalidateRgn(window.0, ptr::null_mut(), 0); + } + } + } + } + + unsafe { + taskbar_mark_fullscreen(window.0, fullscreen.is_some()); + } + }); + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::DECORATIONS, decorations) + }); + }); + } + + #[inline] + pub fn set_always_on_top(&self, always_on_top: bool) { + let window = self.window.clone(); + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock(), window.0, |f| { + f.set(WindowFlags::ALWAYS_ON_TOP, always_on_top) + }); + }); + } + + #[inline] + pub fn current_monitor(&self) -> RootMonitorHandle { + RootMonitorHandle { + inner: monitor::current_monitor(self.window.0), + } + } + + #[inline] + pub fn set_window_icon(&self, window_icon: Option) { + if let Some(ref window_icon) = window_icon { + window_icon + .inner + .set_for_window(self.window.0, IconType::Small); + } else { + icon::unset_for_window(self.window.0, IconType::Small); + } + self.window_state.lock().window_icon = window_icon; + } + + #[inline] + pub fn set_taskbar_icon(&self, taskbar_icon: Option) { + if let Some(ref taskbar_icon) = taskbar_icon { + taskbar_icon + .inner + .set_for_window(self.window.0, IconType::Big); + } else { + icon::unset_for_window(self.window.0, IconType::Big); + } + self.window_state.lock().taskbar_icon = taskbar_icon; + } + + #[inline] + pub fn set_ime_position(&self, _position: Position) { + unimplemented!(); + } + + #[inline] + pub fn is_dark_mode(&self) -> bool { + self.window_state.lock().is_dark_mode + } +} + +impl Drop for Window { + #[inline] + fn drop(&mut self) { + unsafe { + // The window must be destroyed from the same thread that created it, so we send a + // custom message to be handled by our callback to do the actual work. + winuser::PostMessageW(self.window.0, *DESTROY_MSG_ID, 0, 0); + } + } +} + +/// A simple non-owning wrapper around a window. +#[doc(hidden)] +#[derive(Clone)] +pub struct WindowWrapper(HWND); + +// Send and Sync are not implemented for HWND and HDC, we have to wrap it and implement them manually. +// For more info see: +// https://github.com/retep998/winapi-rs/issues/360 +// https://github.com/retep998/winapi-rs/issues/396 +unsafe impl Sync for WindowWrapper {} +unsafe impl Send for WindowWrapper {} + +unsafe fn init( + attributes: WindowAttributes, + pl_attribs: PlatformSpecificWindowBuilderAttributes, + event_loop: &EventLoopWindowTarget, +) -> Result { + let title = OsStr::new(&attributes.title) + .encode_wide() + .chain(Some(0).into_iter()) + .collect::>(); + + // registering the window class + let class_name = register_window_class(&attributes.window_icon, &pl_attribs.taskbar_icon); + + let mut window_flags = WindowFlags::empty(); + window_flags.set(WindowFlags::DECORATIONS, attributes.decorations); + window_flags.set(WindowFlags::ALWAYS_ON_TOP, attributes.always_on_top); + window_flags.set( + WindowFlags::NO_BACK_BUFFER, + pl_attribs.no_redirection_bitmap, + ); + window_flags.set(WindowFlags::TRANSPARENT, attributes.transparent); + // WindowFlags::VISIBLE and MAXIMIZED are set down below after the window has been configured. + window_flags.set(WindowFlags::RESIZABLE, attributes.resizable); + window_flags.set(WindowFlags::CHILD, pl_attribs.parent.is_some()); + window_flags.set(WindowFlags::ON_TASKBAR, true); + + // creating the real window this time, by using the functions in `extra_functions` + let real_window = { + let (style, ex_style) = window_flags.to_window_styles(); + let handle = winuser::CreateWindowExW( + ex_style, + class_name.as_ptr(), + title.as_ptr() as LPCWSTR, + style, + winuser::CW_USEDEFAULT, + winuser::CW_USEDEFAULT, + winuser::CW_USEDEFAULT, + winuser::CW_USEDEFAULT, + pl_attribs.parent.unwrap_or(ptr::null_mut()), + ptr::null_mut(), + libloaderapi::GetModuleHandleW(ptr::null()), + ptr::null_mut(), + ); + + if handle.is_null() { + return Err(os_error!(io::Error::last_os_error())); + } + + WindowWrapper(handle) + }; + + // Register for touch events if applicable + { + let digitizer = winuser::GetSystemMetrics(winuser::SM_DIGITIZER) as u32; + if digitizer & winuser::NID_READY != 0 { + winuser::RegisterTouchWindow(real_window.0, winuser::TWF_WANTPALM); + } + } + + let dpi = hwnd_dpi(real_window.0); + let scale_factor = dpi_to_scale_factor(dpi); + + // making the window transparent + if attributes.transparent && !pl_attribs.no_redirection_bitmap { + let region = CreateRectRgn(0, 0, -1, -1); // makes the window transparent + + let bb = dwmapi::DWM_BLURBEHIND { + dwFlags: dwmapi::DWM_BB_ENABLE | dwmapi::DWM_BB_BLURREGION, + fEnable: 1, + hRgnBlur: region, + fTransitionOnMaximized: 0, + }; + + dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb); + DeleteObject(region as _); + + if attributes.decorations { + // HACK: When opaque (opacity 255), there is a trail whenever + // the transparent window is moved. By reducing it to 254, + // the window is rendered properly. + let opacity = 254; + + // The color key can be any value except for black (0x0). + let color_key = 0x0030c100; + + winuser::SetLayeredWindowAttributes( + real_window.0, + color_key, + opacity, + winuser::LWA_ALPHA, + ); + } + } + + window_flags.set(WindowFlags::MAXIMIZED, attributes.maximized); + + // If the system theme is dark, we need to set the window theme now + // before we update the window flags (and possibly show the + // window for the first time). + let dark_mode = try_dark_mode(real_window.0); + + let window_state = { + let window_state = WindowState::new( + &attributes, + pl_attribs.taskbar_icon, + scale_factor, + dark_mode, + ); + let window_state = Arc::new(Mutex::new(window_state)); + WindowState::set_window_flags(window_state.lock(), real_window.0, |f| *f = window_flags); + window_state + }; + + let win = Window { + window: real_window, + window_state, + thread_executor: event_loop.create_thread_executor(), + }; + + let dimensions = attributes + .inner_size + .unwrap_or_else(|| PhysicalSize::new(1024, 768).into()); + win.set_inner_size(dimensions); + win.set_visible(attributes.visible); + + if let Some(_) = attributes.fullscreen { + win.set_fullscreen(attributes.fullscreen); + force_window_active(win.window.0); + } + + Ok(win) +} + +unsafe fn register_window_class( + window_icon: &Option, + taskbar_icon: &Option, +) -> Vec { + let class_name: Vec<_> = OsStr::new("Window Class") + .encode_wide() + .chain(Some(0).into_iter()) + .collect(); + + let h_icon = taskbar_icon + .as_ref() + .map(|icon| icon.inner.as_raw_handle()) + .unwrap_or(ptr::null_mut()); + let h_icon_small = window_icon + .as_ref() + .map(|icon| icon.inner.as_raw_handle()) + .unwrap_or(ptr::null_mut()); + + let class = winuser::WNDCLASSEXW { + cbSize: mem::size_of::() as UINT, + style: winuser::CS_HREDRAW | winuser::CS_VREDRAW | winuser::CS_OWNDC, + lpfnWndProc: Some(winuser::DefWindowProcW), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: libloaderapi::GetModuleHandleW(ptr::null()), + hIcon: h_icon, + hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly + hbrBackground: ptr::null_mut(), + lpszMenuName: ptr::null(), + lpszClassName: class_name.as_ptr(), + hIconSm: h_icon_small, + }; + + // We ignore errors because registering the same window class twice would trigger + // an error, and because errors here are detected during CreateWindowEx anyway. + // Also since there is no weird element in the struct, there is no reason for this + // call to fail. + winuser::RegisterClassExW(&class); + + class_name +} + +struct ComInitialized(*mut ()); +impl Drop for ComInitialized { + fn drop(&mut self) { + unsafe { combaseapi::CoUninitialize() }; + } +} + +thread_local! { + static COM_INITIALIZED: ComInitialized = { + unsafe { + combaseapi::CoInitializeEx(ptr::null_mut(), COINIT_APARTMENTTHREADED); + ComInitialized(ptr::null_mut()) + } + }; + + static TASKBAR_LIST: Cell<*mut ITaskbarList2> = Cell::new(ptr::null_mut()); +} + +pub fn com_initialized() { + COM_INITIALIZED.with(|_| {}); +} + +// Reference Implementation: +// https://github.com/chromium/chromium/blob/f18e79d901f56154f80eea1e2218544285e62623/ui/views/win/fullscreen_handler.cc +// +// As per MSDN marking the window as fullscreen should ensure that the +// taskbar is moved to the bottom of the Z-order when the fullscreen window +// is activated. If the window is not fullscreen, the Shell falls back to +// heuristics to determine how the window should be treated, which means +// that it could still consider the window as fullscreen. :( +unsafe fn taskbar_mark_fullscreen(handle: HWND, fullscreen: bool) { + com_initialized(); + + TASKBAR_LIST.with(|task_bar_list_ptr| { + let mut task_bar_list = task_bar_list_ptr.get(); + + if task_bar_list == ptr::null_mut() { + use winapi::{shared::winerror::S_OK, Interface}; + + let hr = combaseapi::CoCreateInstance( + &CLSID_TaskbarList, + ptr::null_mut(), + combaseapi::CLSCTX_ALL, + &ITaskbarList2::uuidof(), + &mut task_bar_list as *mut _ as *mut _, + ); + + if hr != S_OK || (*task_bar_list).HrInit() != S_OK { + // In some old windows, the taskbar object could not be created, we just ignore it + return; + } + task_bar_list_ptr.set(task_bar_list) + } + + task_bar_list = task_bar_list_ptr.get(); + (*task_bar_list).MarkFullscreenWindow(handle, if fullscreen { 1 } else { 0 }); + }) +} + +unsafe fn force_window_active(handle: HWND) { + // In some situation, calling SetForegroundWindow could not bring up the window, + // This is a little hack which can "steal" the foreground window permission + // We only call this function in the window creation, so it should be fine. + // See : https://stackoverflow.com/questions/10740346/setforegroundwindow-only-working-while-visual-studio-is-open + let alt_sc = winuser::MapVirtualKeyW(winuser::VK_MENU as _, winuser::MAPVK_VK_TO_VSC); + + let mut inputs: [winuser::INPUT; 2] = mem::zeroed(); + inputs[0].type_ = winuser::INPUT_KEYBOARD; + inputs[0].u.ki_mut().wVk = winuser::VK_LMENU as _; + inputs[0].u.ki_mut().wScan = alt_sc as _; + inputs[0].u.ki_mut().dwFlags = winuser::KEYEVENTF_EXTENDEDKEY; + + inputs[1].type_ = winuser::INPUT_KEYBOARD; + inputs[1].u.ki_mut().wVk = winuser::VK_LMENU as _; + inputs[1].u.ki_mut().wScan = alt_sc as _; + inputs[1].u.ki_mut().dwFlags = winuser::KEYEVENTF_EXTENDEDKEY | winuser::KEYEVENTF_KEYUP; + + // Simulate a key press and release + winuser::SendInput( + inputs.len() as _, + inputs.as_mut_ptr(), + mem::size_of::() as _, + ); + + winuser::SetForegroundWindow(handle); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window_state.rs b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window_state.rs new file mode 100644 index 0000000..1179482 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/platform_impl/windows/window_state.rs @@ -0,0 +1,368 @@ +use crate::{ + dpi::{PhysicalPosition, Size}, + event::ModifiersState, + icon::Icon, + platform_impl::platform::{event_loop, util}, + window::{CursorIcon, Fullscreen, WindowAttributes}, +}; +use parking_lot::MutexGuard; +use std::{io, ptr}; +use winapi::{ + shared::{ + minwindef::DWORD, + windef::{HWND, RECT}, + }, + um::winuser, +}; + +/// Contains information about states and the window that the callback is going to use. +pub struct WindowState { + pub mouse: MouseProperties, + + /// Used by `WM_GETMINMAXINFO`. + pub min_size: Option, + pub max_size: Option, + + pub window_icon: Option, + pub taskbar_icon: Option, + + pub saved_window: Option, + pub scale_factor: f64, + + pub modifiers_state: ModifiersState, + pub fullscreen: Option, + pub is_dark_mode: bool, + pub high_surrogate: Option, + window_flags: WindowFlags, +} + +#[derive(Clone)] +pub struct SavedWindow { + pub client_rect: RECT, + pub scale_factor: f64, +} + +#[derive(Clone)] +pub struct MouseProperties { + pub cursor: CursorIcon, + pub buttons_down: u32, + cursor_flags: CursorFlags, + pub last_position: Option>, +} + +bitflags! { + pub struct CursorFlags: u8 { + const GRABBED = 1 << 0; + const HIDDEN = 1 << 1; + const IN_WINDOW = 1 << 2; + } +} +bitflags! { + pub struct WindowFlags: u32 { + const RESIZABLE = 1 << 0; + const DECORATIONS = 1 << 1; + const VISIBLE = 1 << 2; + const ON_TASKBAR = 1 << 3; + const ALWAYS_ON_TOP = 1 << 4; + const NO_BACK_BUFFER = 1 << 5; + const TRANSPARENT = 1 << 6; + const CHILD = 1 << 7; + const MAXIMIZED = 1 << 8; + + /// Marker flag for fullscreen. Should always match `WindowState::fullscreen`, but is + /// included here to make masking easier. + const MARKER_FULLSCREEN = 1 << 9; + + /// The `WM_SIZE` event contains some parameters that can effect the state of `WindowFlags`. + /// In most cases, it's okay to let those parameters change the state. However, when we're + /// running the `WindowFlags::apply_diff` function, we *don't* want those parameters to + /// effect our stored state, because the purpose of `apply_diff` is to update the actual + /// window's state to match our stored state. This controls whether to accept those changes. + const MARKER_RETAIN_STATE_ON_SIZE = 1 << 10; + + const MINIMIZED = 1 << 11; + + const FULLSCREEN_AND_MASK = !( + WindowFlags::DECORATIONS.bits | + WindowFlags::RESIZABLE.bits | + WindowFlags::MAXIMIZED.bits + ); + const FULLSCREEN_OR_MASK = WindowFlags::ALWAYS_ON_TOP.bits; + const NO_DECORATIONS_AND_MASK = !WindowFlags::RESIZABLE.bits; + const INVISIBLE_AND_MASK = !WindowFlags::MAXIMIZED.bits; + } +} + +impl WindowState { + pub fn new( + attributes: &WindowAttributes, + taskbar_icon: Option, + scale_factor: f64, + is_dark_mode: bool, + ) -> WindowState { + WindowState { + mouse: MouseProperties { + cursor: CursorIcon::default(), + buttons_down: 0, + cursor_flags: CursorFlags::empty(), + last_position: None, + }, + + min_size: attributes.min_inner_size, + max_size: attributes.max_inner_size, + + window_icon: attributes.window_icon.clone(), + taskbar_icon, + + saved_window: None, + scale_factor, + + modifiers_state: ModifiersState::default(), + fullscreen: None, + is_dark_mode, + high_surrogate: None, + window_flags: WindowFlags::empty(), + } + } + + pub fn window_flags(&self) -> WindowFlags { + self.window_flags + } + + pub fn set_window_flags(mut this: MutexGuard<'_, Self>, window: HWND, f: F) + where + F: FnOnce(&mut WindowFlags), + { + let old_flags = this.window_flags; + f(&mut this.window_flags); + let new_flags = this.window_flags; + + drop(this); + old_flags.apply_diff(window, new_flags); + } + + pub fn set_window_flags_in_place(&mut self, f: F) + where + F: FnOnce(&mut WindowFlags), + { + f(&mut self.window_flags); + } +} + +impl MouseProperties { + pub fn cursor_flags(&self) -> CursorFlags { + self.cursor_flags + } + + pub fn set_cursor_flags(&mut self, window: HWND, f: F) -> Result<(), io::Error> + where + F: FnOnce(&mut CursorFlags), + { + let old_flags = self.cursor_flags; + f(&mut self.cursor_flags); + match self.cursor_flags.refresh_os_cursor(window) { + Ok(()) => (), + Err(e) => { + self.cursor_flags = old_flags; + return Err(e); + } + } + + Ok(()) + } +} + +impl WindowFlags { + fn mask(mut self) -> WindowFlags { + if self.contains(WindowFlags::MARKER_FULLSCREEN) { + self &= WindowFlags::FULLSCREEN_AND_MASK; + self |= WindowFlags::FULLSCREEN_OR_MASK; + } + if !self.contains(WindowFlags::VISIBLE) { + self &= WindowFlags::INVISIBLE_AND_MASK; + } + if !self.contains(WindowFlags::DECORATIONS) { + self &= WindowFlags::NO_DECORATIONS_AND_MASK; + } + self + } + + pub fn to_window_styles(self) -> (DWORD, DWORD) { + use winapi::um::winuser::*; + + let (mut style, mut style_ex) = (0, 0); + + if self.contains(WindowFlags::RESIZABLE) { + style |= WS_SIZEBOX | WS_MAXIMIZEBOX; + } + if self.contains(WindowFlags::DECORATIONS) { + style |= WS_CAPTION | WS_MINIMIZEBOX | WS_BORDER; + style_ex = WS_EX_WINDOWEDGE; + } + if self.contains(WindowFlags::VISIBLE) { + style |= WS_VISIBLE; + } + if self.contains(WindowFlags::ON_TASKBAR) { + style_ex |= WS_EX_APPWINDOW; + } + if self.contains(WindowFlags::ALWAYS_ON_TOP) { + style_ex |= WS_EX_TOPMOST; + } + if self.contains(WindowFlags::NO_BACK_BUFFER) { + style_ex |= WS_EX_NOREDIRECTIONBITMAP; + } + if self.contains(WindowFlags::TRANSPARENT) && self.contains(WindowFlags::DECORATIONS) { + style_ex |= WS_EX_LAYERED; + } + if self.contains(WindowFlags::CHILD) { + style |= WS_CHILD; // This is incompatible with WS_POPUP if that gets added eventually. + } + if self.contains(WindowFlags::MINIMIZED) { + style |= WS_MINIMIZE; + } + if self.contains(WindowFlags::MAXIMIZED) { + style |= WS_MAXIMIZE; + } + + style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU; + style_ex |= WS_EX_ACCEPTFILES; + + (style, style_ex) + } + + /// Adjust the window client rectangle to the return value, if present. + fn apply_diff(mut self, window: HWND, mut new: WindowFlags) { + self = self.mask(); + new = new.mask(); + + let diff = self ^ new; + if diff == WindowFlags::empty() { + return; + } + + if diff.contains(WindowFlags::VISIBLE) { + unsafe { + winuser::ShowWindow( + window, + match new.contains(WindowFlags::VISIBLE) { + true => winuser::SW_SHOW, + false => winuser::SW_HIDE, + }, + ); + } + } + if diff.contains(WindowFlags::ALWAYS_ON_TOP) { + unsafe { + winuser::SetWindowPos( + window, + match new.contains(WindowFlags::ALWAYS_ON_TOP) { + true => winuser::HWND_TOPMOST, + false => winuser::HWND_NOTOPMOST, + }, + 0, + 0, + 0, + 0, + winuser::SWP_ASYNCWINDOWPOS + | winuser::SWP_NOMOVE + | winuser::SWP_NOSIZE + | winuser::SWP_NOACTIVATE, + ); + winuser::InvalidateRgn(window, ptr::null_mut(), 0); + } + } + + if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { + unsafe { + winuser::ShowWindow( + window, + match new.contains(WindowFlags::MAXIMIZED) { + true => winuser::SW_MAXIMIZE, + false => winuser::SW_RESTORE, + }, + ); + } + } + + // Minimize operations should execute after maximize for proper window animations + if diff.contains(WindowFlags::MINIMIZED) { + unsafe { + winuser::ShowWindow( + window, + match new.contains(WindowFlags::MINIMIZED) { + true => winuser::SW_MINIMIZE, + false => winuser::SW_RESTORE, + }, + ); + } + } + + if diff != WindowFlags::empty() { + let (style, style_ex) = new.to_window_styles(); + + unsafe { + winuser::SendMessageW(window, *event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID, 1, 0); + + // This condition is necessary to avoid having an unrestorable window + if !new.contains(WindowFlags::MINIMIZED) { + winuser::SetWindowLongW(window, winuser::GWL_STYLE, style as _); + winuser::SetWindowLongW(window, winuser::GWL_EXSTYLE, style_ex as _); + } + + let mut flags = winuser::SWP_NOZORDER + | winuser::SWP_NOMOVE + | winuser::SWP_NOSIZE + | winuser::SWP_FRAMECHANGED; + + // We generally don't want style changes here to affect window + // focus, but for fullscreen windows they must be activated + // (i.e. focused) so that they appear on top of the taskbar + if !new.contains(WindowFlags::MARKER_FULLSCREEN) { + flags |= winuser::SWP_NOACTIVATE; + } + + // Refresh the window frame + winuser::SetWindowPos(window, ptr::null_mut(), 0, 0, 0, 0, flags); + winuser::SendMessageW(window, *event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID, 0, 0); + } + } + } +} + +impl CursorFlags { + fn refresh_os_cursor(self, window: HWND) -> Result<(), io::Error> { + let client_rect = util::get_client_rect(window)?; + + if util::is_focused(window) { + let cursor_clip = match self.contains(CursorFlags::GRABBED) { + true => Some(client_rect), + false => None, + }; + + let rect_to_tuple = |rect: RECT| (rect.left, rect.top, rect.right, rect.bottom); + let active_cursor_clip = rect_to_tuple(util::get_cursor_clip()?); + let desktop_rect = rect_to_tuple(util::get_desktop_rect()); + + let active_cursor_clip = match desktop_rect == active_cursor_clip { + true => None, + false => Some(active_cursor_clip), + }; + + // We do this check because calling `set_cursor_clip` incessantly will flood the event + // loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by `set_cursor_flags` + // which at times gets called once every iteration of the eventloop. + if active_cursor_clip != cursor_clip.map(rect_to_tuple) { + util::set_cursor_clip(cursor_clip)?; + } + } + + let cursor_in_client = self.contains(CursorFlags::IN_WINDOW); + if cursor_in_client { + util::set_cursor_hidden(self.contains(CursorFlags::HIDDEN)); + } else { + util::set_cursor_hidden(false); + } + + Ok(()) + } +} diff --git a/third_party/cargo/vendor/winit-0.22.0/src/window.rs b/third_party/cargo/vendor/winit-0.22.0/src/window.rs new file mode 100644 index 0000000..113e7c0 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/src/window.rs @@ -0,0 +1,870 @@ +//! The `Window` struct and associated types. +use std::fmt; + +use crate::{ + dpi::{PhysicalPosition, PhysicalSize, Position, Size}, + error::{ExternalError, NotSupportedError, OsError}, + event_loop::EventLoopWindowTarget, + monitor::{MonitorHandle, VideoMode}, + platform_impl, +}; + +pub use crate::icon::{BadIcon, Icon}; + +/// Represents a window. +/// +/// # Example +/// +/// ```no_run +/// use winit::{ +/// event::{Event, WindowEvent}, +/// event_loop::{ControlFlow, EventLoop}, +/// window::Window, +/// }; +/// +/// let mut event_loop = EventLoop::new(); +/// let window = Window::new(&event_loop).unwrap(); +/// +/// event_loop.run(move |event, _, control_flow| { +/// *control_flow = ControlFlow::Wait; +/// +/// match event { +/// Event::WindowEvent { +/// event: WindowEvent::CloseRequested, +/// .. +/// } => *control_flow = ControlFlow::Exit, +/// _ => (), +/// } +/// }); +/// ``` +pub struct Window { + pub(crate) window: platform_impl::Window, +} + +impl fmt::Debug for Window { + fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { + fmtr.pad("Window { .. }") + } +} + +impl Drop for Window { + fn drop(&mut self) { + // If the window is in exclusive fullscreen, we must restore the desktop + // video mode (generally this would be done on application exit, but + // closing the window doesn't necessarily always mean application exit, + // such as when there are multiple windows) + if let Some(Fullscreen::Exclusive(_)) = self.fullscreen() { + self.set_fullscreen(None); + } + } +} + +/// Identifier of a window. Unique for each window. +/// +/// Can be obtained with `window.id()`. +/// +/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you +/// can then compare to the ids of your windows. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(pub(crate) platform_impl::WindowId); + +impl WindowId { + /// Returns a dummy `WindowId`, useful for unit testing. The only guarantee made about the return + /// value of this function is that it will always be equal to itself and to future values returned + /// by this function. No other guarantees are made. This may be equal to a real `WindowId`. + /// + /// **Passing this into a winit function will result in undefined behavior.** + pub unsafe fn dummy() -> Self { + WindowId(platform_impl::WindowId::dummy()) + } +} + +/// Object that allows you to build windows. +#[derive(Clone, Default)] +pub struct WindowBuilder { + /// The attributes to use to create the window. + pub window: WindowAttributes, + + // Platform-specific configuration. + pub(crate) platform_specific: platform_impl::PlatformSpecificWindowBuilderAttributes, +} + +impl fmt::Debug for WindowBuilder { + fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { + fmtr.debug_struct("WindowBuilder") + .field("window", &self.window) + .finish() + } +} + +/// Attributes to use when creating a window. +#[derive(Debug, Clone)] +pub struct WindowAttributes { + /// The dimensions of the window. If this is `None`, some platform-specific dimensions will be + /// used. + /// + /// The default is `None`. + pub inner_size: Option, + + /// The minimum dimensions a window can be, If this is `None`, the window will have no minimum dimensions (aside from reserved). + /// + /// The default is `None`. + pub min_inner_size: Option, + + /// The maximum dimensions a window can be, If this is `None`, the maximum will have no maximum or will be set to the primary monitor's dimensions by the platform. + /// + /// The default is `None`. + pub max_inner_size: Option, + + /// Whether the window is resizable or not. + /// + /// The default is `true`. + pub resizable: bool, + + /// Whether the window should be set as fullscreen upon creation. + /// + /// The default is `None`. + pub fullscreen: Option, + + /// The title of the window in the title bar. + /// + /// The default is `"winit window"`. + pub title: String, + + /// Whether the window should be maximized upon creation. + /// + /// The default is `false`. + pub maximized: bool, + + /// Whether the window should be immediately visible upon creation. + /// + /// The default is `true`. + pub visible: bool, + + /// Whether the the window should be transparent. If this is true, writing colors + /// with alpha values different than `1.0` will produce a transparent window. + /// + /// The default is `false`. + pub transparent: bool, + + /// Whether the window should have borders and bars. + /// + /// The default is `true`. + pub decorations: bool, + + /// Whether the window should always be on top of other windows. + /// + /// The default is `false`. + pub always_on_top: bool, + + /// The window icon. + /// + /// The default is `None`. + pub window_icon: Option, +} + +impl Default for WindowAttributes { + #[inline] + fn default() -> WindowAttributes { + WindowAttributes { + inner_size: None, + min_inner_size: None, + max_inner_size: None, + resizable: true, + title: "winit window".to_owned(), + maximized: false, + fullscreen: None, + visible: true, + transparent: false, + decorations: true, + always_on_top: false, + window_icon: None, + } + } +} + +impl WindowBuilder { + /// Initializes a new `WindowBuilder` with default values. + #[inline] + pub fn new() -> Self { + Default::default() + } + + /// Requests the window to be of specific dimensions. + /// + /// See [`Window::set_inner_size`] for details. + /// + /// [`Window::set_inner_size`]: crate::window::Window::set_inner_size + #[inline] + pub fn with_inner_size>(mut self, size: S) -> Self { + self.window.inner_size = Some(size.into()); + self + } + + /// Sets a minimum dimension size for the window. + /// + /// See [`Window::set_min_inner_size`] for details. + /// + /// [`Window::set_min_inner_size`]: crate::window::Window::set_min_inner_size + #[inline] + pub fn with_min_inner_size>(mut self, min_size: S) -> Self { + self.window.min_inner_size = Some(min_size.into()); + self + } + + /// Sets a maximum dimension size for the window. + /// + /// See [`Window::set_max_inner_size`] for details. + /// + /// [`Window::set_max_inner_size`]: crate::window::Window::set_max_inner_size + #[inline] + pub fn with_max_inner_size>(mut self, max_size: S) -> Self { + self.window.max_inner_size = Some(max_size.into()); + self + } + + /// Sets whether the window is resizable or not. + /// + /// See [`Window::set_resizable`] for details. + /// + /// [`Window::set_resizable`]: crate::window::Window::set_resizable + #[inline] + pub fn with_resizable(mut self, resizable: bool) -> Self { + self.window.resizable = resizable; + self + } + + /// Requests a specific title for the window. + /// + /// See [`Window::set_title`] for details. + /// + /// [`Window::set_title`]: crate::window::Window::set_title + #[inline] + pub fn with_title>(mut self, title: T) -> Self { + self.window.title = title.into(); + self + } + + /// Sets the window fullscreen state. + /// + /// See [`Window::set_fullscreen`] for details. + /// + /// [`Window::set_fullscreen`]: crate::window::Window::set_fullscreen + #[inline] + pub fn with_fullscreen(mut self, monitor: Option) -> Self { + self.window.fullscreen = monitor; + self + } + + /// Requests maximized mode. + /// + /// See [`Window::set_maximized`] for details. + /// + /// [`Window::set_maximized`]: crate::window::Window::set_maximized + #[inline] + pub fn with_maximized(mut self, maximized: bool) -> Self { + self.window.maximized = maximized; + self + } + + /// Sets whether the window will be initially hidden or visible. + /// + /// See [`Window::set_visible`] for details. + /// + /// [`Window::set_visible`]: crate::window::Window::set_visible + #[inline] + pub fn with_visible(mut self, visible: bool) -> Self { + self.window.visible = visible; + self + } + + /// Sets whether the background of the window should be transparent. + #[inline] + pub fn with_transparent(mut self, transparent: bool) -> Self { + self.window.transparent = transparent; + self + } + + /// Sets whether the window should have a border, a title bar, etc. + /// + /// See [`Window::set_decorations`] for details. + /// + /// [`Window::set_decorations`]: crate::window::Window::set_decorations + #[inline] + pub fn with_decorations(mut self, decorations: bool) -> Self { + self.window.decorations = decorations; + self + } + + /// Sets whether or not the window will always be on top of other windows. + /// + /// See [`Window::set_always_on_top`] for details. + /// + /// [`Window::set_always_on_top`]: crate::window::Window::set_always_on_top + #[inline] + pub fn with_always_on_top(mut self, always_on_top: bool) -> Self { + self.window.always_on_top = always_on_top; + self + } + + /// Sets the window icon. + /// + /// See [`Window::set_window_icon`] for details. + /// + /// [`Window::set_window_icon`]: crate::window::Window::set_window_icon + #[inline] + pub fn with_window_icon(mut self, window_icon: Option) -> Self { + self.window.window_icon = window_icon; + self + } + + /// Builds the window. + /// + /// Possible causes of error include denied permission, incompatible system, and lack of memory. + /// + /// Platform-specific behavior: + /// - **Web**: The window is created but not inserted into the web page automatically. Please + /// see the web platform module for more information. + #[inline] + pub fn build( + self, + window_target: &EventLoopWindowTarget, + ) -> Result { + platform_impl::Window::new(&window_target.p, self.window, self.platform_specific).map( + |window| { + window.request_redraw(); + Window { window } + }, + ) + } +} + +/// Base Window functions. +impl Window { + /// Creates a new Window for platforms where this is appropriate. + /// + /// This function is equivalent to [`WindowBuilder::new().build(event_loop)`]. + /// + /// Error should be very rare and only occur in case of permission denied, incompatible system, + /// out of memory, etc. + /// + /// Platform-specific behavior: + /// - **Web**: The window is created but not inserted into the web page automatically. Please + /// see the web platform module for more information. + /// + /// [`WindowBuilder::new().build(event_loop)`]: crate::window::WindowBuilder::build + #[inline] + pub fn new(event_loop: &EventLoopWindowTarget) -> Result { + let builder = WindowBuilder::new(); + builder.build(event_loop) + } + + /// Returns an identifier unique to the window. + #[inline] + pub fn id(&self) -> WindowId { + WindowId(self.window.id()) + } + + /// Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa. + /// + /// See the [`dpi`](crate::dpi) module for more information. + /// + /// Note that this value can change depending on user action (for example if the window is + /// moved to another screen); as such, tracking `WindowEvent::ScaleFactorChanged` events is + /// the most robust way to track the DPI you need to use to draw. + /// + /// ## Platform-specific + /// + /// - **X11:** This respects Xft.dpi, and can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable. + /// - **Android:** Always returns 1.0. + /// - **iOS:** Can only be called on the main thread. Returns the underlying `UIView`'s + /// [`contentScaleFactor`]. + /// + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window.scale_factor() + } + + /// Emits a `WindowEvent::RedrawRequested` event in the associated event loop after all OS + /// events have been processed by the event loop. + /// + /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with + /// OS-requested redraws (e.g. when a window gets resized). + /// + /// This function can cause `RedrawRequested` events to be emitted after `Event::MainEventsCleared` + /// but before `Event::NewEvents` if called in the following circumstances: + /// * While processing `MainEventsCleared`. + /// * While processing a `RedrawRequested` event that was sent during `MainEventsCleared` or any + /// directly subsequent `RedrawRequested` event. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. + #[inline] + pub fn request_redraw(&self) { + self.window.request_redraw() + } +} + +/// Position and size functions. +impl Window { + /// Returns the position of the top-left hand corner of the window's client area relative to the + /// top-left hand corner of the desktop. + /// + /// The same conditions that apply to `outer_position` apply to this method. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the + /// window's [safe area] in the screen space coordinate system. + /// - **Web:** Returns the top-left coordinates relative to the viewport. _Note: this returns the + /// same value as `outer_position`._ + /// + /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc + #[inline] + pub fn inner_position(&self) -> Result, NotSupportedError> { + self.window.inner_position() + } + + /// Returns the position of the top-left hand corner of the window relative to the + /// top-left hand corner of the desktop. + /// + /// Note that the top-left hand corner of the desktop is not necessarily the same as + /// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner + /// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop. + /// + /// The coordinates can be negative if the top-left hand corner of the window is outside + /// of the visible screen region. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the + /// window in the screen space coordinate system. + /// - **Web:** Returns the top-left coordinates relative to the viewport. + #[inline] + pub fn outer_position(&self) -> Result, NotSupportedError> { + self.window.outer_position() + } + + /// Modifies the position of the window. + /// + /// See `outer_position` for more information about the coordinates. This automatically un-maximizes the + /// window if it's maximized. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Sets the top left coordinates of the + /// window in the screen space coordinate system. + /// - **Web:** Sets the top-left coordinates relative to the viewport. + #[inline] + pub fn set_outer_position>(&self, position: P) { + self.window.set_outer_position(position.into()) + } + + /// Returns the physical size of the window's client area. + /// + /// The client area is the content of the window, excluding the title bar and borders. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the `PhysicalSize` of the window's + /// [safe area] in screen space coordinates. + /// - **Web:** Returns the size of the canvas element. + /// + /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc + #[inline] + pub fn inner_size(&self) -> PhysicalSize { + self.window.inner_size() + } + + /// Modifies the inner size of the window. + /// + /// See `inner_size` for more information about the values. This automatically un-maximizes the + /// window if it's maximized. + /// + /// ## Platform-specific + /// + /// - **iOS:** Unimplemented. Currently this panics, as it's not clear what `set_inner_size` + /// would mean for iOS. + /// - **Web:** Sets the size of the canvas element. + #[inline] + pub fn set_inner_size>(&self, size: S) { + self.window.set_inner_size(size.into()) + } + + /// Returns the physical size of the entire window. + /// + /// These dimensions include the title bar and borders. If you don't want that (and you usually don't), + /// use `inner_size` instead. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the `PhysicalSize` of the window in + /// screen space coordinates. + /// - **Web:** Returns the size of the canvas element. _Note: this returns the same value as + /// `inner_size`._ + #[inline] + pub fn outer_size(&self) -> PhysicalSize { + self.window.outer_size() + } + + /// Sets a minimum dimension size for the window. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_min_inner_size>(&self, min_size: Option) { + self.window.set_min_inner_size(min_size.map(|s| s.into())) + } + + /// Sets a maximum dimension size for the window. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_max_inner_size>(&self, max_size: Option) { + self.window.set_max_inner_size(max_size.map(|s| s.into())) + } +} + +/// Misc. attribute functions. +impl Window { + /// Modifies the title of the window. + /// + /// ## Platform-specific + /// + /// - Has no effect on iOS. + #[inline] + pub fn set_title(&self, title: &str) { + self.window.set_title(title) + } + + /// Modifies the window's visibility. + /// + /// If `false`, this will hide the window. If `true`, this will show the window. + /// ## Platform-specific + /// + /// - **Android:** Has no effect. + /// - **iOS:** Can only be called on the main thread. + /// - **Web:** Has no effect. + #[inline] + pub fn set_visible(&self, visible: bool) { + self.window.set_visible(visible) + } + + /// Sets whether the window is resizable or not. + /// + /// Note that making the window unresizable doesn't exempt you from handling `Resized`, as that event can still be + /// triggered by DPI scaling, entering fullscreen mode, etc. + /// + /// ## Platform-specific + /// + /// This only has an effect on desktop platforms. + /// + /// Due to a bug in XFCE, this has no effect on Xfwm. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_resizable(&self, resizable: bool) { + self.window.set_resizable(resizable) + } + + /// Sets the window to minimized or back + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect + #[inline] + pub fn set_minimized(&self, minimized: bool) { + self.window.set_minimized(minimized); + } + + /// Sets the window to maximized or back. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_maximized(&self, maximized: bool) { + self.window.set_maximized(maximized) + } + + /// Sets the window to fullscreen or back. + /// + /// ## Platform-specific + /// + /// - **macOS:** `Fullscreen::Exclusive` provides true exclusive mode with a + /// video mode change. *Caveat!* macOS doesn't provide task switching (or + /// spaces!) while in exclusive fullscreen mode. This mode should be used + /// when a video mode change is desired, but for a better user experience, + /// borderless fullscreen might be preferred. + /// + /// `Fullscreen::Borderless` provides a borderless fullscreen window on a + /// separate space. This is the idiomatic way for fullscreen games to work + /// on macOS. See `WindowExtMacOs::set_simple_fullscreen` if + /// separate spaces are not preferred. + /// + /// The dock and the menu bar are always disabled in fullscreen mode. + /// - **iOS:** Can only be called on the main thread. + /// - **Wayland:** Does not support exclusive fullscreen mode. + /// - **Windows:** Screen saver is disabled in fullscreen mode. + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option) { + self.window.set_fullscreen(fullscreen) + } + + /// Gets the window's current fullscreen state. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. + #[inline] + pub fn fullscreen(&self) -> Option { + self.window.fullscreen() + } + + /// Turn window decorations on or off. + /// + /// ## Platform-specific + /// - **iOS:** Can only be called on the main thread. Controls whether the status bar is hidden + /// via [`setPrefersStatusBarHidden`]. + /// - **Web:** Has no effect. + /// + /// [`setPrefersStatusBarHidden`]: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc + #[inline] + pub fn set_decorations(&self, decorations: bool) { + self.window.set_decorations(decorations) + } + + /// Change whether or not the window will always be on top of other windows. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_always_on_top(&self, always_on_top: bool) { + self.window.set_always_on_top(always_on_top) + } + + /// Sets the window icon. On Windows and X11, this is typically the small icon in the top-left + /// corner of the titlebar. + /// + /// ## Platform-specific + /// + /// This only has an effect on Windows and X11. + /// + /// On Windows, this sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's + /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. + /// + /// X11 has no universal guidelines for icon sizes, so you're at the whims of the WM. That + /// said, it's usually in the same ballpark as on Windows. + #[inline] + pub fn set_window_icon(&self, window_icon: Option) { + self.window.set_window_icon(window_icon) + } + + /// Sets location of IME candidate box in client area coordinates relative to the top left. + /// + /// ## Platform-specific + /// + /// **iOS:** Has no effect. + /// - **Web:** Has no effect. + #[inline] + pub fn set_ime_position>(&self, position: P) { + self.window.set_ime_position(position.into()) + } +} + +/// Cursor functions. +impl Window { + /// Modifies the cursor icon of the window. + /// + /// ## Platform-specific + /// + /// - **iOS:** Has no effect. + /// - **Android:** Has no effect. + #[inline] + pub fn set_cursor_icon(&self, cursor: CursorIcon) { + self.window.set_cursor_icon(cursor); + } + + /// Changes the position of the cursor in window coordinates. + /// + /// ## Platform-specific + /// + /// - **iOS:** Always returns an `Err`. + /// - **Web:** Has no effect. + #[inline] + pub fn set_cursor_position>(&self, position: P) -> Result<(), ExternalError> { + self.window.set_cursor_position(position.into()) + } + + /// Grabs the cursor, preventing it from leaving the window. + /// + /// ## Platform-specific + /// + /// - **macOS:** This presently merely locks the cursor in a fixed location, which looks visually + /// awkward. + /// - **Wayland:** This presently merely locks the cursor in a fixed location, which looks visually + /// awkward. + /// - **Android:** Has no effect. + /// - **iOS:** Always returns an Err. + /// - **Web:** Has no effect. + #[inline] + pub fn set_cursor_grab(&self, grab: bool) -> Result<(), ExternalError> { + self.window.set_cursor_grab(grab) + } + + /// Modifies the cursor's visibility. + /// + /// If `false`, this will hide the cursor. If `true`, this will show the cursor. + /// + /// ## Platform-specific + /// + /// - **Windows:** The cursor is only hidden within the confines of the window. + /// - **X11:** The cursor is only hidden within the confines of the window. + /// - **Wayland:** The cursor is only hidden within the confines of the window. + /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor is + /// outside of the window. + /// - **iOS:** Has no effect. + /// - **Android:** Has no effect. + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + self.window.set_cursor_visible(visible) + } +} + +/// Monitor info functions. +impl Window { + /// Returns the monitor on which the window currently resides + /// + /// ## Platform-specific + /// + /// **iOS:** Can only be called on the main thread. + #[inline] + pub fn current_monitor(&self) -> MonitorHandle { + self.window.current_monitor() + } + + /// Returns the list of all the monitors available on the system. + /// + /// This is the same as `EventLoop::available_monitors`, and is provided for convenience. + /// + /// ## Platform-specific + /// + /// **iOS:** Can only be called on the main thread. + #[inline] + pub fn available_monitors(&self) -> impl Iterator { + self.window + .available_monitors() + .into_iter() + .map(|inner| MonitorHandle { inner }) + } + + /// Returns the primary monitor of the system. + /// + /// This is the same as `EventLoop::primary_monitor`, and is provided for convenience. + /// + /// ## Platform-specific + /// + /// **iOS:** Can only be called on the main thread. + #[inline] + pub fn primary_monitor(&self) -> MonitorHandle { + MonitorHandle { + inner: self.window.primary_monitor(), + } + } +} + +unsafe impl raw_window_handle::HasRawWindowHandle for Window { + fn raw_window_handle(&self) -> raw_window_handle::RawWindowHandle { + self.window.raw_window_handle() + } +} + +/// Describes the appearance of the mouse cursor. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum CursorIcon { + /// The platform-dependent default cursor. + Default, + /// A simple crosshair. + Crosshair, + /// A hand (often used to indicate links in web browsers). + Hand, + /// Self explanatory. + Arrow, + /// Indicates something is to be moved. + Move, + /// Indicates text that may be selected or edited. + Text, + /// Program busy indicator. + Wait, + /// Help indicator (often rendered as a "?") + Help, + /// Progress indicator. Shows that processing is being done. But in contrast + /// with "Wait" the user may still interact with the program. Often rendered + /// as a spinning beach ball, or an arrow with a watch or hourglass. + Progress, + + /// Cursor showing that something cannot be done. + NotAllowed, + ContextMenu, + Cell, + VerticalText, + Alias, + Copy, + NoDrop, + /// Indicates something can be grabbed. + Grab, + /// Indicates something is grabbed. + Grabbing, + AllScroll, + ZoomIn, + ZoomOut, + + /// Indicate that some edge is to be moved. For example, the 'SeResize' cursor + /// is used when the movement starts from the south-east corner of the box. + EResize, + NResize, + NeResize, + NwResize, + SResize, + SeResize, + SwResize, + WResize, + EwResize, + NsResize, + NeswResize, + NwseResize, + ColResize, + RowResize, +} + +impl Default for CursorIcon { + fn default() -> Self { + CursorIcon::Default + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Fullscreen { + Exclusive(VideoMode), + Borderless(MonitorHandle), +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Theme { + Light, + Dark, +} diff --git a/third_party/cargo/vendor/winit-0.22.0/tests/send_objects.rs b/third_party/cargo/vendor/winit-0.22.0/tests/send_objects.rs new file mode 100644 index 0000000..252b271 --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/tests/send_objects.rs @@ -0,0 +1,27 @@ +#[allow(dead_code)] +fn needs_send() {} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn event_loop_proxy_send() { + #[allow(dead_code)] + fn is_send() { + // ensures that `winit::EventLoopProxy` implements `Send` + needs_send::>(); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn window_send() { + // ensures that `winit::Window` implements `Send` + needs_send::(); +} + +#[test] +fn ids_send() { + // ensures that the various `..Id` types implement `Send` + needs_send::(); + needs_send::(); + needs_send::(); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/tests/serde_objects.rs b/third_party/cargo/vendor/winit-0.22.0/tests/serde_objects.rs new file mode 100644 index 0000000..ad729dc --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/tests/serde_objects.rs @@ -0,0 +1,39 @@ +#![cfg(feature = "serde")] + +use serde::{Deserialize, Serialize}; +use winit::{ + dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}, + event::{ + ElementState, KeyboardInput, ModifiersState, MouseButton, MouseScrollDelta, TouchPhase, + VirtualKeyCode, + }, + window::CursorIcon, +}; + +#[allow(dead_code)] +fn needs_serde>() {} + +#[test] +fn window_serde() { + needs_serde::(); +} + +#[test] +fn events_serde() { + needs_serde::(); + needs_serde::(); + needs_serde::(); + needs_serde::(); + needs_serde::(); + needs_serde::(); + needs_serde::(); +} + +#[test] +fn dpi_serde() { + needs_serde::>(); + needs_serde::>(); + needs_serde::>(); + needs_serde::>(); + needs_serde::>(); +} diff --git a/third_party/cargo/vendor/winit-0.22.0/tests/sync_object.rs b/third_party/cargo/vendor/winit-0.22.0/tests/sync_object.rs new file mode 100644 index 0000000..56524cb --- /dev/null +++ b/third_party/cargo/vendor/winit-0.22.0/tests/sync_object.rs @@ -0,0 +1,9 @@ +#[allow(dead_code)] +fn needs_sync() {} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn window_sync() { + // ensures that `winit::Window` implements `Sync` + needs_sync::(); +} diff --git a/third_party/cargo/vendor/ws2_32-sys-0.2.1/.cargo-checksum.json b/third_party/cargo/vendor/ws2_32-sys-0.2.1/.cargo-checksum.json new file mode 100644 index 0000000..984121d --- /dev/null +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"b5c32ebeb474fcf68bd5d6f296f12163d1627dca02dbe06341ee3d378535cdaa","README.md":"ad92627d07dcd015a10440590041e72723b1e5a3ca86f50d6d059e7e4e78433f","build.rs":"84b7d5871797983a021d1ae8cd9698687b7d2bddd4622e82b30c693218400f09","src/lib.rs":"71b9f929fe5227d63326e71ed2f49a96adb560318b8862d55927aac2d247e82d"},"package":"d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e"} \ No newline at end of file diff --git a/third_party/cargo/vendor/backtrace-sys-0.1.34/BUILD b/third_party/cargo/vendor/ws2_32-sys-0.2.1/BUILD similarity index 81% rename from third_party/cargo/vendor/backtrace-sys-0.1.34/BUILD rename to third_party/cargo/vendor/ws2_32-sys-0.2.1/BUILD index 0758f24..1c4b0ba 100644 --- a/third_party/cargo/vendor/backtrace-sys-0.1.34/BUILD +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "MIT,Apache-2.0" + "notice", # "MIT" ]) load( @@ -23,23 +23,26 @@ load( ) +# Unsupported target "build-script-build" with type "custom-build" omitted +alias( + name = "ws2_32_sys", + actual = ":ws2_32", +) rust_library( - name = "backtrace_sys", + name = "ws2_32", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/libc-0.2.67:libc", + "//third_party/cargo/vendor/winapi-0.2.8:winapi", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.1.34", + version = "0.2.1", crate_features = [ - "backtrace-sys", ], ) -# Unsupported target "build-script-build" with type "custom-build" omitted diff --git a/third_party/cargo/vendor/ws2_32-sys-0.2.1/Cargo.toml b/third_party/cargo/vendor/ws2_32-sys-0.2.1/Cargo.toml new file mode 100644 index 0000000..71dc566 --- /dev/null +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ws2_32-sys" +version = "0.2.1" +authors = ["Peter Atashian "] +description = "Contains function definitions for the Windows API library ws2_32. See winapi for types and constants." +documentation = "https://retep998.github.io/doc/ws2_32/" +repository = "https://github.com/retep998/winapi-rs" +readme = "README.md" +keywords = ["windows", "ffi", "win32"] +license = "MIT" +build = "build.rs" +[lib] +name = "ws2_32" +[dependencies] +winapi = { version = "0.2.5", path = "../.." } +[build-dependencies] +winapi-build = { version = "0.1.1", path = "../../build" } diff --git a/third_party/cargo/vendor/ws2_32-sys-0.2.1/README.md b/third_party/cargo/vendor/ws2_32-sys-0.2.1/README.md new file mode 100644 index 0000000..8dd54c8 --- /dev/null +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/README.md @@ -0,0 +1,13 @@ +# ws2_32 # +Contains function definitions for the Windows API library ws2_32. See winapi for types and constants. + +```toml +[dependencies] +ws2_32-sys = "0.2.0" +``` + +```rust +extern crate ws2_32; +``` + +[Documentation](https://retep998.github.io/doc/ws2_32/) diff --git a/third_party/cargo/vendor/ws2_32-sys-0.2.1/build.rs b/third_party/cargo/vendor/ws2_32-sys-0.2.1/build.rs new file mode 100644 index 0000000..30b8283 --- /dev/null +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/build.rs @@ -0,0 +1,6 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +extern crate build; +fn main() { + build::link("ws2_32", false) +} diff --git a/third_party/cargo/vendor/ws2_32-sys-0.2.1/src/lib.rs b/third_party/cargo/vendor/ws2_32-sys-0.2.1/src/lib.rs new file mode 100644 index 0000000..8a1cd4f --- /dev/null +++ b/third_party/cargo/vendor/ws2_32-sys-0.2.1/src/lib.rs @@ -0,0 +1,483 @@ +// Copyright © 2015, Peter Atashian +// Licensed under the MIT License +//! FFI bindings to ws2_32. +#![cfg(windows)] +extern crate winapi; +use winapi::*; +extern "system" { + pub fn FreeAddrInfoEx(pAddrInfoEx: PADDRINFOEXA); + pub fn FreeAddrInfoExW(pAddrInfoEx: PADDRINFOEXW); + pub fn FreeAddrInfoW(pAddrInfo: PADDRINFOW); + pub fn GetAddrInfoExA( + pName: PCSTR, pServiceName: PCSTR, dwNameSpace: DWORD, lpNspId: LPGUID, + hints: *const ADDRINFOEXA, ppResult: *mut PADDRINFOEXA, timeout: *mut timeval, + lpOverlapped: LPOVERLAPPED, lpCompletionRoutine: LPLOOKUPSERVICE_COMPLETION_ROUTINE, + lpNameHandle: LPHANDLE, + ) -> INT; + pub fn GetAddrInfoExCancel(lpHandle: LPHANDLE) -> INT; + pub fn GetAddrInfoExOverlappedResult(lpOverlapped: LPOVERLAPPED) -> INT; + pub fn GetAddrInfoExW( + pName: PCWSTR, pServiceName: PCWSTR, dwNameSpace: DWORD, lpNspId: LPGUID, + hints: *const ADDRINFOEXW, ppResult: *mut PADDRINFOEXW, timeout: *mut timeval, + lpOverlapped: LPOVERLAPPED, lpCompletionRoutine: LPLOOKUPSERVICE_COMPLETION_ROUTINE, + lpNameHandle: LPHANDLE, + ) -> INT; + pub fn GetAddrInfoW( + pNodeName: PCWSTR, pServiceName: PCWSTR, pHints: *const ADDRINFOW, + ppResult: *mut PADDRINFOW, + ) -> INT; + pub fn GetHostNameW(name: PWSTR, namelen: c_int) -> c_int; + pub fn GetNameInfoW( + pSockaddr: *const SOCKADDR, SockaddrLength: socklen_t, pNodeBuffer: PWCHAR, + NodeBufferSize: DWORD, pServiceBuffer: PWCHAR, ServiceBufferSize: DWORD, Flags: INT, + ) -> INT; + pub fn InetNtopW(Family: INT, pAddr: PVOID, pStringBuf: PWSTR, StringBufSize: size_t) -> PCWSTR; + pub fn InetPtonW(Family: INT, pszAddrString: PCWSTR, pAddrBuf: PVOID) -> INT; + pub fn SetAddrInfoExA( + pName: PCSTR, pServiceName: PCSTR, pAddresses: *mut SOCKET_ADDRESS, dwAddressCount: DWORD, + lpBlob: LPBLOB, dwFlags: DWORD, dwNameSpace: DWORD, lpNspId: LPGUID, timeout: *mut timeval, + lpOverlapped: LPOVERLAPPED, lpCompletionRoutine: LPLOOKUPSERVICE_COMPLETION_ROUTINE, + lpNameHandle: LPHANDLE, + ) -> INT; + pub fn SetAddrInfoExW( + pName: PCWSTR, pServiceName: PCWSTR, pAddresses: *mut SOCKET_ADDRESS, dwAddressCount: DWORD, + lpBlob: LPBLOB, dwFlags: DWORD, dwNameSpace: DWORD, lpNspId: LPGUID, timeout: *mut timeval, + lpOverlapped: LPOVERLAPPED, lpCompletionRoutine: LPLOOKUPSERVICE_COMPLETION_ROUTINE, + lpNameHandle: LPHANDLE, + ) -> INT; + // pub fn WEP(); + pub fn WPUCompleteOverlappedRequest( + s: SOCKET, lpOverlapped: LPWSAOVERLAPPED, dwError: DWORD, cbTransferred: DWORD, + lpErrno: LPINT, + ) -> c_int; + // pub fn WPUGetProviderPathEx(); + pub fn WSAAccept( + s: SOCKET, addr: *mut SOCKADDR, addrlen: LPINT, lpfnCondition: LPCONDITIONPROC, + dwCallbackData: DWORD_PTR, + ) -> SOCKET; + pub fn WSAAddressToStringA( + lpsaAddress: LPSOCKADDR, dwAddressLength: DWORD, lpProtocolInfo: LPWSAPROTOCOL_INFOA, + lpszAddressString: LPSTR, lpdwAddressStringLength: LPDWORD, + ) -> INT; + pub fn WSAAddressToStringW( + lpsaAddress: LPSOCKADDR, dwAddressLength: DWORD, lpProtocolInfo: LPWSAPROTOCOL_INFOW, + lpszAddressString: LPWSTR, lpdwAddressStringLength: LPDWORD, + ) -> INT; + pub fn WSAAdvertiseProvider( + puuidProviderId: *const GUID, pNSPv2Routine: *const LPCNSPV2_ROUTINE, + ) -> INT; + pub fn WSAAsyncGetHostByAddr( + hWnd: HWND, wMsg: u_int, addr: *const c_char, len: c_int, _type: c_int, buf: *mut c_char, + buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncGetHostByName( + hWnd: HWND, wMsg: u_int, name: *const c_char, buf: *mut c_char, buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncGetProtoByName( + hWnd: HWND, wMsg: u_int, name: *const c_char, buf: *mut c_char, buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncGetProtoByNumber( + hWnd: HWND, wMsg: u_int, number: c_int, buf: *mut c_char, buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncGetServByName( + hWnd: HWND, wMsg: u_int, name: *const c_char, proto: *const c_char, buf: *mut c_char, + buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncGetServByPort( + hWnd: HWND, wMsg: u_int, port: c_int, proto: *const c_char, buf: *mut c_char, buflen: c_int, + ) -> HANDLE; + pub fn WSAAsyncSelect(s: SOCKET, hWnd: HWND, wMsg: u_int, lEvent: c_long) -> c_int; + pub fn WSACancelAsyncRequest(hAsyncTaskHandle: HANDLE) -> c_int; + pub fn WSACancelBlockingCall() -> c_int; + pub fn WSACleanup() -> c_int; + pub fn WSACloseEvent(hEvent: WSAEVENT) -> BOOL; + pub fn WSAConnect( + s: SOCKET, name: *const SOCKADDR, namelen: c_int, lpCallerData: LPWSABUF, + lpCalleeData: LPWSABUF, lpSQOS: LPQOS, lpGQOS: LPQOS, + ) -> c_int; + pub fn WSAConnectByList( + s: SOCKET, SocketAddress: PSOCKET_ADDRESS_LIST, LocalAddressLength: LPDWORD, + LocalAddress: LPSOCKADDR, RemoteAddressLength: LPDWORD, RemoteAddress: LPSOCKADDR, + timeout: *const timeval, Reserved: LPWSAOVERLAPPED, + ) -> BOOL; + pub fn WSAConnectByNameA( + s: SOCKET, nodename: LPCSTR, servicename: LPCSTR, LocalAddressLength: LPDWORD, + LocalAddress: LPSOCKADDR, RemoteAddressLength: LPDWORD, RemoteAddress: LPSOCKADDR, + timeout: *const timeval, Reserved: LPWSAOVERLAPPED, + ) -> BOOL; + pub fn WSAConnectByNameW( + s: SOCKET, nodename: LPWSTR, servicename: LPWSTR, LocalAddressLength: LPDWORD, + LocalAddress: LPSOCKADDR, RemoteAddressLength: LPDWORD, RemoteAddress: LPSOCKADDR, + timeout: *const timeval, Reserved: LPWSAOVERLAPPED, + ) -> BOOL; + pub fn WSACreateEvent() -> WSAEVENT; + pub fn WSADuplicateSocketA( + s: SOCKET, dwProcessId: DWORD, lpProtocolInfo: LPWSAPROTOCOL_INFOA, + ) -> c_int; + pub fn WSADuplicateSocketW( + s: SOCKET, dwProcessId: DWORD, lpProtocolInfo: LPWSAPROTOCOL_INFOW, + ) -> c_int; + pub fn WSAEnumNameSpaceProvidersA( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOA, + ) -> INT; + pub fn WSAEnumNameSpaceProvidersExA( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOEXA, + ) -> INT; + pub fn WSAEnumNameSpaceProvidersExW( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOEXW, + ) -> INT; + pub fn WSAEnumNameSpaceProvidersW( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOW, + ) -> INT; + pub fn WSAEnumNetworkEvents( + s: SOCKET, hEventObject: WSAEVENT, lpNetworkEvents: LPWSANETWORKEVENTS, + ) -> c_int; + pub fn WSAEnumProtocolsA( + lpiProtocols: LPINT, lpProtocolBuffer: LPWSAPROTOCOL_INFOA, lpdwBufferLength: LPDWORD, + ) -> c_int; + pub fn WSAEnumProtocolsW( + lpiProtocols: LPINT, lpProtocolBuffer: LPWSAPROTOCOL_INFOW, lpdwBufferLength: LPDWORD, + ) -> c_int; + pub fn WSAEventSelect(s: SOCKET, hEventObject: WSAEVENT, lNetworkEvents: c_long) -> c_int; + pub fn WSAGetLastError() -> c_int; + pub fn WSAGetOverlappedResult( + s: SOCKET, lpOverlapped: LPWSAOVERLAPPED, lpcbTransfer: LPDWORD, fWait: BOOL, + lpdwFlags: LPDWORD, + ) -> BOOL; + pub fn WSAGetQOSByName(s: SOCKET, lpQOSName: LPWSABUF, lpQOS: LPQOS) -> BOOL; + pub fn WSAGetServiceClassInfoA( + lpProviderId: LPGUID, lpServiceClassId: LPGUID, lpdwBufSize: LPDWORD, + lpServiceClassInfo: LPWSASERVICECLASSINFOA, + ) -> INT; + pub fn WSAGetServiceClassInfoW( + lpProviderId: LPGUID, lpServiceClassId: LPGUID, lpdwBufSize: LPDWORD, + lpServiceClassInfo: LPWSASERVICECLASSINFOW, + ) -> INT; + pub fn WSAGetServiceClassNameByClassIdA( + lpServiceClassId: LPGUID, lpszServiceClassName: LPSTR, lpdwBufferLength: LPDWORD, + ) -> INT; + pub fn WSAGetServiceClassNameByClassIdW( + lpServiceClassId: LPGUID, lpszServiceClassName: LPWSTR, lpdwBufferLength: LPDWORD, + ) -> INT; + pub fn WSAHtonl(s: SOCKET, hostlong: u_long, lpnetlong: *mut u_long) -> c_int; + pub fn WSAHtons(s: SOCKET, hostshort: u_short, lpnetshort: *mut u_short) -> c_int; + pub fn WSAInstallServiceClassA(lpServiceClassInfo: LPWSASERVICECLASSINFOA) -> INT; + pub fn WSAInstallServiceClassW(lpServiceClassInfo: LPWSASERVICECLASSINFOW) -> INT; + pub fn WSAIoctl( + s: SOCKET, dwIoControlCode: DWORD, lpvInBuffer: LPVOID, cbInBuffer: DWORD, + lpvOutBuffer: LPVOID, cbOutBuffer: DWORD, lpcbBytesReturned: LPDWORD, + lpOverlapped: LPWSAOVERLAPPED, lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSAIsBlocking() -> BOOL; + pub fn WSAJoinLeaf( + s: SOCKET, name: *const SOCKADDR, namelen: c_int, lpCallerData: LPWSABUF, + lpCalleeData: LPWSABUF, lpSQOS: LPQOS, lpGQOS: LPQOS, dwFlags: DWORD, + ) -> SOCKET; + pub fn WSALookupServiceBeginA( + lpqsRestrictions: LPWSAQUERYSETA, dwControlFlags: DWORD, lphLookup: LPHANDLE, + ) -> INT; + pub fn WSALookupServiceBeginW( + lpqsRestrictions: LPWSAQUERYSETW, dwControlFlags: DWORD, lphLookup: LPHANDLE, + ) -> INT; + pub fn WSALookupServiceEnd(hLookup: HANDLE) -> INT; + pub fn WSALookupServiceNextA( + hLookup: HANDLE, dwControlFlags: DWORD, lpdwBufferLength: LPDWORD, + lpqsResults: LPWSAQUERYSETA, + ) -> INT; + pub fn WSALookupServiceNextW( + hLookup: HANDLE, dwControlFlags: DWORD, lpdwBufferLength: LPDWORD, + lpqsResults: LPWSAQUERYSETW, + ) -> INT; + pub fn WSANSPIoctl( + hLookup: HANDLE, dwControlFlags: DWORD, lpvInBuffer: LPVOID, cbInBuffer: DWORD, + lpvOutBuffer: LPVOID, cbOutBuffer: DWORD, lpcbBytesReturned: LPDWORD, + lpCompletion: LPWSACOMPLETION, + ) -> INT; + pub fn WSANtohl(s: SOCKET, netlong: u_long, lphostlong: *mut c_long) -> c_int; + pub fn WSANtohs(s: SOCKET, netshort: u_short, lphostshort: *mut c_short) -> c_int; + pub fn WSAPoll(fdArray: LPWSAPOLLFD, fds: ULONG, timeout: INT) -> c_int; + pub fn WSAProviderCompleteAsyncCall(hAsyncCall: HANDLE, iRetCode: INT) -> INT; + pub fn WSAProviderConfigChange( + lpNotificationHandle: LPHANDLE, lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> INT; + pub fn WSARecv( + s: SOCKET, lpBuffers: LPWSABUF, dwBufferCount: DWORD, lpNumberOfBytesRecvd: LPDWORD, + lpFlags: LPDWORD, lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSARecvDisconnect(s: SOCKET, lpInboundDisconnectData: LPWSABUF) -> c_int; + pub fn WSARecvFrom( + s: SOCKET, lpBuffers: LPWSABUF, dwBufferCount: DWORD, lpNumberOfBytesRecvd: LPDWORD, + lpFlags: LPDWORD, lpFrom: *mut SOCKADDR, lpFromlen: LPINT, lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSARemoveServiceClass(lpServiceClassId: LPGUID) -> INT; + pub fn WSAResetEvent(hEvent: WSAEVENT) -> BOOL; + pub fn WSASend( + s: SOCKET, lpBuffers: LPWSABUF, dwBufferCount: DWORD, lpNumberOfBytesSent: LPDWORD, + dwFlags: DWORD, lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSASendDisconnect(s: SOCKET, lpOutboundDisconnectData: LPWSABUF) -> c_int; + pub fn WSASendMsg( + Handle: SOCKET, lpMsg: LPWSAMSG, dwFlags: DWORD, lpNumberOfBytesSent: LPDWORD, + lpOverlapped: LPWSAOVERLAPPED, lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSASendTo( + s: SOCKET, lpBuffers: LPWSABUF, dwBufferCount: DWORD, lpNumberOfBytesSent: LPDWORD, + dwFlags: DWORD, lpTo: *const SOCKADDR, iToLen: c_int, lpOverlapped: LPWSAOVERLAPPED, + lpCompletionRoutine: LPWSAOVERLAPPED_COMPLETION_ROUTINE, + ) -> c_int; + pub fn WSASetBlockingHook(lpBlockFunc: FARPROC) -> FARPROC; + pub fn WSASetEvent(hEvent: WSAEVENT) -> BOOL; + pub fn WSASetLastError(iError: c_int); + pub fn WSASetServiceA( + lpqsRegInfo: LPWSAQUERYSETA, essoperation: WSAESETSERVICEOP, dwControlFlags: DWORD, + ) -> INT; + pub fn WSASetServiceW( + lpqsRegInfo: LPWSAQUERYSETW, essoperation: WSAESETSERVICEOP, dwControlFlags: DWORD, + ) -> INT; + pub fn WSASocketA( + af: c_int, _type: c_int, protocol: c_int, lpProtocolInfo: LPWSAPROTOCOL_INFOA, g: GROUP, + dwFlags: DWORD, + ) -> SOCKET; + pub fn WSASocketW( + af: c_int, _type: c_int, protocol: c_int, lpProtocolInfo: LPWSAPROTOCOL_INFOW, g: GROUP, + dwFlags: DWORD, + ) -> SOCKET; + pub fn WSAStartup(wVersionRequested: WORD, lpWSAData: LPWSADATA) -> c_int; + pub fn WSAStringToAddressA( + AddressString: LPSTR, AddressFamily: INT, lpProtocolInfo: LPWSAPROTOCOL_INFOA, + lpAddress: LPSOCKADDR, lpAddressLength: LPINT, + ) -> INT; + pub fn WSAStringToAddressW( + AddressString: LPWSTR, AddressFamily: INT, lpProtocolInfo: LPWSAPROTOCOL_INFOW, + lpAddress: LPSOCKADDR, lpAddressLength: LPINT, + ) -> INT; + pub fn WSAUnadvertiseProvider(puuidProviderId: *const GUID) -> INT; + pub fn WSAUnhookBlockingHook() -> c_int; + pub fn WSAWaitForMultipleEvents( + cEvents: DWORD, lphEvents: *const WSAEVENT, fWaitAll: BOOL, dwTimeout: DWORD, + fAlertable: BOOL, + ) -> DWORD; + pub fn WSCDeinstallProvider(lpProviderId: LPGUID, lpErrno: LPINT) -> c_int; + // pub fn WSCDeinstallProviderEx(); + pub fn WSCEnableNSProvider(lpProviderId: LPGUID, fEnable: BOOL) -> INT; + pub fn WSCEnumProtocols( + lpiProtocols: LPINT, lpProtocolBuffer: LPWSAPROTOCOL_INFOW, lpdwBufferLength: LPDWORD, + lpErrno: LPINT, + ) -> c_int; + // pub fn WSCEnumProtocolsEx(); + pub fn WSCGetApplicationCategory( + Path: LPCWSTR, PathLength: DWORD, Extra: LPCWSTR, ExtraLength: DWORD, + pPermittedLspCategories: *mut DWORD, lpErrno: LPINT, + ) -> c_int; + // pub fn WSCGetApplicationCategoryEx(); + pub fn WSCGetProviderInfo( + lpProviderId: LPGUID, InfoType: WSC_PROVIDER_INFO_TYPE, Info: PBYTE, InfoSize: *mut size_t, + Flags: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCGetProviderPath( + lpProviderId: LPGUID, lpszProviderDllPath: *mut WCHAR, lpProviderDllPathLen: LPINT, + lpErrno: LPINT, + ) -> c_int; + pub fn WSCInstallNameSpace( + lpszIdentifier: LPWSTR, lpszPathName: LPWSTR, dwNameSpace: DWORD, dwVersion: DWORD, + lpProviderId: LPGUID, + ) -> INT; + pub fn WSCInstallNameSpaceEx( + lpszIdentifier: LPWSTR, lpszPathName: LPWSTR, dwNameSpace: DWORD, dwVersion: DWORD, + lpProviderId: LPGUID, lpProviderSpecific: LPBLOB, + ) -> INT; + // pub fn WSCInstallNameSpaceEx2(); + pub fn WSCInstallProvider( + lpProviderId: LPGUID, lpszProviderDllPath: *const WCHAR, + lpProtocolInfoList: LPWSAPROTOCOL_INFOW, dwNumberOfEntries: DWORD, lpErrno: LPINT, + ) -> c_int; + // pub fn WSCInstallProviderEx(); + pub fn WSCSetApplicationCategory( + Path: LPCWSTR, PathLength: DWORD, Extra: LPCWSTR, ExtraLength: DWORD, + PermittedLspCategories: DWORD, pPrevPermLspCat: *mut DWORD, lpErrno: LPINT, + ) -> c_int; + // pub fn WSCSetApplicationCategoryEx(); + pub fn WSCSetProviderInfo( + lpProviderId: LPGUID, InfoType: WSC_PROVIDER_INFO_TYPE, Info: PBYTE, InfoSize: size_t, + Flags: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCUnInstallNameSpace(lpProviderId: LPGUID) -> INT; + // pub fn WSCUnInstallNameSpaceEx2(); + pub fn WSCUpdateProvider( + lpProviderId: LPGUID, lpszProviderDllPath: *const WCHAR, + lpProtocolInfoList: LPWSAPROTOCOL_INFOW, dwNumberOfEntries: DWORD, lpErrno: LPINT, + ) -> c_int; + // pub fn WSCUpdateProviderEx(); + pub fn WSCWriteNameSpaceOrder(lpProviderId: LPGUID, dwNumberOfEntries: DWORD) -> c_int; + pub fn WSCWriteProviderOrder(lpwdCatalogEntryId: LPDWORD, dwNumberOfEntries: DWORD) -> c_int; + // pub fn WSCWriteProviderOrderEx(); + // pub fn WahCloseApcHelper(); + // pub fn WahCloseHandleHelper(); + // pub fn WahCloseNotificationHandleHelper(); + // pub fn WahCloseSocketHandle(); + // pub fn WahCloseThread(); + // pub fn WahCompleteRequest(); + // pub fn WahCreateHandleContextTable(); + // pub fn WahCreateNotificationHandle(); + // pub fn WahCreateSocketHandle(); + // pub fn WahDestroyHandleContextTable(); + // pub fn WahDisableNonIFSHandleSupport(); + // pub fn WahEnableNonIFSHandleSupport(); + // pub fn WahEnumerateHandleContexts(); + // pub fn WahInsertHandleContext(); + // pub fn WahNotifyAllProcesses(); + // pub fn WahOpenApcHelper(); + // pub fn WahOpenCurrentThread(); + // pub fn WahOpenHandleHelper(); + // pub fn WahOpenNotificationHandleHelper(); + // pub fn WahQueueUserApc(); + // pub fn WahReferenceContextByHandle(); + // pub fn WahRemoveHandleContext(); + // pub fn WahWaitForNotification(); + // pub fn WahWriteLSPEvent(); + pub fn __WSAFDIsSet(fd: SOCKET, _: *mut fd_set) -> c_int; + pub fn accept(s: SOCKET, addr: *mut SOCKADDR, addrlen: *mut c_int) -> SOCKET; + pub fn bind(s: SOCKET, name: *const SOCKADDR, namelen: c_int) -> c_int; + pub fn closesocket(s: SOCKET) -> c_int; + pub fn connect(s: SOCKET, name: *const SOCKADDR, namelen: c_int) -> c_int; + pub fn freeaddrinfo(pAddrInfo: PADDRINFOA); + pub fn getaddrinfo( + pNodeName: PCSTR, pServiceName: PCSTR, pHints: *const ADDRINFOA, ppResult: *mut PADDRINFOA, + ) -> INT; + pub fn gethostbyaddr(addr: *const c_char, len: c_int, _type: c_int) -> *mut hostent; + pub fn gethostbyname(name: *const c_char) -> *mut hostent; + pub fn gethostname(name: *mut c_char, namelen: c_int) -> c_int; + pub fn getnameinfo( + pSockaddr: *const SOCKADDR, SockaddrLength: socklen_t, pNodeBuffer: PCHAR, + NodeBufferSize: DWORD, pServiceBuffer: PCHAR, ServiceBufferSize: DWORD, Flags: INT, + ) -> INT; + pub fn getpeername(s: SOCKET, name: *mut SOCKADDR, namelen: *mut c_int) -> c_int; + pub fn getprotobyname(name: *const c_char) -> *mut protoent; + pub fn getprotobynumber(number: c_int) -> *mut protoent; + pub fn getservbyname(name: *const c_char, proto: *const c_char) -> *mut servent; + pub fn getservbyport(port: c_int, proto: *const c_char) -> *mut servent; + pub fn getsockname(s: SOCKET, name: *mut SOCKADDR, namelen: *mut c_int) -> c_int; + pub fn getsockopt( + s: SOCKET, level: c_int, optname: c_int, optval: *mut c_char, optlen: *mut c_int, + ) -> c_int; + pub fn htonl(hostlong: u_long) -> u_long; + pub fn htons(hostshort: u_short) -> u_short; + pub fn inet_addr(cp: *const c_char) -> c_ulong; + pub fn inet_ntoa(_in: in_addr) -> *mut c_char; + pub fn inet_ntop(Family: INT, pAddr: PVOID, pStringBuf: PSTR, StringBufSize: size_t) -> PCSTR; + pub fn inet_pton(Family: INT, pszAddrString: PCSTR, pAddrBuf: PVOID) -> INT; + pub fn ioctlsocket(s: SOCKET, cmd: c_long, argp: *mut u_long) -> c_int; + pub fn listen(s: SOCKET, backlog: c_int) -> c_int; + pub fn ntohl(netlong: u_long) -> u_long; + pub fn ntohs(netshort: u_short) -> u_short; + pub fn recv(s: SOCKET, buf: *mut c_char, len: c_int, flags: c_int) -> c_int; + pub fn recvfrom( + s: SOCKET, buf: *mut c_char, len: c_int, flags: c_int, from: *mut SOCKADDR, + fromlen: *mut c_int, + ) -> c_int; + pub fn select( + nfds: c_int, readfds: *mut fd_set, writefds: *mut fd_set, exceptfds: *mut fd_set, + timeout: *const timeval, + ) -> c_int; + pub fn send(s: SOCKET, buf: *const c_char, len: c_int, flags: c_int) -> c_int; + pub fn sendto( + s: SOCKET, buf: *const c_char, len: c_int, flags: c_int, to: *const SOCKADDR, tolen: c_int, + ) -> c_int; + pub fn setsockopt( + s: SOCKET, level: c_int, optname: c_int, optval: *const c_char, optlen: c_int, + ) -> c_int; + pub fn shutdown(s: SOCKET, how: c_int) -> c_int; + pub fn socket(af: c_int, _type: c_int, protocol: c_int) -> SOCKET; +} +#[cfg(any(target_arch = "x86", target_arch = "arm"))] +extern "system" { + pub fn WSCInstallProviderAndChains( + lpProviderId: LPGUID, lpszProviderDllPath: LPWSTR, lpszLspName: LPWSTR, + dwServiceFlags: DWORD, lpProtocolInfoList: LPWSAPROTOCOL_INFOW, dwNumberOfEntries: DWORD, + lpdwCatalogEntryId: LPDWORD, lpErrno: LPINT, + ) -> c_int; +} +#[cfg(target_arch = "x86_64")] +extern "system" { + pub fn WSCDeinstallProvider32(lpProviderId: LPGUID, lpErrno: LPINT) -> c_int; + pub fn WSCEnableNSProvider32(lpProviderId: LPGUID, fEnable: BOOL) -> INT; + pub fn WSCEnumNameSpaceProviders32( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOW, + ) -> INT; + pub fn WSCEnumNameSpaceProvidersEx32( + lpdwBufferLength: LPDWORD, lpnspBuffer: LPWSANAMESPACE_INFOEXW, + ) -> INT; + pub fn WSCEnumProtocols32( + lpiProtocols: LPINT, lpProtocolBuffer: LPWSAPROTOCOL_INFOW, lpdwBufferLength: LPDWORD, + lpErrno: LPINT, + ) -> c_int; + pub fn WSCGetProviderInfo32( + lpProviderId: LPGUID, InfoType: WSC_PROVIDER_INFO_TYPE, Info: PBYTE, InfoSize: *mut size_t, + Flags: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCGetProviderPath32( + lpProviderId: LPGUID, lpszProviderDllPath: *mut WCHAR, lpProviderDllPathLen: LPINT, + lpErrno: LPINT, + ) -> c_int; + pub fn WSCInstallNameSpace32( + lpszIdentifier: LPWSTR, lpszPathName: LPWSTR, dwNameSpace: DWORD, dwVersion: DWORD, + lpProviderId: LPGUID, + ) -> INT; + pub fn WSCInstallNameSpaceEx32( + lpszIdentifier: LPWSTR, lpszPathName: LPWSTR, dwNameSpace: DWORD, dwVersion: DWORD, + lpProviderId: LPGUID, lpProviderSpecific: LPBLOB, + ) -> INT; + pub fn WSCInstallProvider64_32( + lpProviderId: LPGUID, lpszProviderDllPath: *const WCHAR, + lpProtocolInfoList: LPWSAPROTOCOL_INFOW, dwNumberOfEntries: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCInstallProviderAndChains64_32( + lpProviderId: LPGUID, lpszProviderDllPath: LPWSTR, lpszProviderDllPath32: LPWSTR, + lpszLspName: LPWSTR, dwServiceFlags: DWORD, lpProtocolInfoList: LPWSAPROTOCOL_INFOW, + dwNumberOfEntries: DWORD, lpdwCatalogEntryId: LPDWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCSetProviderInfo32( + lpProviderId: LPGUID, InfoType: WSC_PROVIDER_INFO_TYPE, Info: PBYTE, InfoSize: size_t, + Flags: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCUnInstallNameSpace32(lpProviderId: LPGUID) -> INT; + pub fn WSCUpdateProvider32( + lpProviderId: LPGUID, lpszProviderDllPath: *const WCHAR, + lpProtocolInfoList: LPWSAPROTOCOL_INFOW, dwNumberOfEntries: DWORD, lpErrno: LPINT, + ) -> c_int; + pub fn WSCWriteNameSpaceOrder32(lpProviderId: LPGUID, dwNumberOfEntries: DWORD) -> c_int; + pub fn WSCWriteProviderOrder32(lpwdCatalogEntryId: LPDWORD, dwNumberOfEntries: DWORD) -> c_int; +} +extern { + // pub static AddressFamilyInformation; + // pub static eui48_broadcast; + // pub static in4addr_alligmpv3routersonlink; + // pub static in4addr_allnodesonlink; + // pub static in4addr_allroutersonlink; + // pub static in4addr_allteredohostsonlink; + // pub static in4addr_any; + // pub static in4addr_broadcast; + // pub static in4addr_linklocalprefix; + // pub static in4addr_loopback; + // pub static in4addr_multicastprefix; + // pub static in6addr_6to4prefix; + // pub static in6addr_allmldv2routersonlink; + // pub static in6addr_allnodesonlink; + // pub static in6addr_allnodesonnode; + // pub static in6addr_allroutersonlink; + // pub static in6addr_any; + // pub static in6addr_linklocalprefix; + // pub static in6addr_loopback; + // pub static in6addr_multicastprefix; + // pub static in6addr_solicitednodemulticastprefix; + // pub static in6addr_teredoinitiallinklocaladdress; + // pub static in6addr_teredoprefix; + // pub static in6addr_teredoprefix_old; + // pub static in6addr_v4mappedprefix; + // pub static scopeid_unspecified; + // pub static sockaddr_size; +} diff --git a/third_party/cargo/vendor/x11-dl-2.18.5/BUILD b/third_party/cargo/vendor/x11-dl-2.18.5/BUILD index caa4cc6..c9f8115 100644 --- a/third_party/cargo/vendor/x11-dl-2.18.5/BUILD +++ b/third_party/cargo/vendor/x11-dl-2.18.5/BUILD @@ -22,8 +22,44 @@ load( "rust_test", ) +rust_binary( + name = "x11_dl_build_script", + srcs = glob(["**/*.rs"]), + crate_root = "build.rs", + edition = "2015", + deps = [ + "//third_party/cargo/vendor/pkg-config-0.3.17:pkg_config", + ], + rustc_flags = [ + "--cap-lints=allow", + ], + crate_features = [ + ], + data = glob(["*"]), + version = "2.18.5", + visibility = ["//visibility:private"], +) + +genrule( + name = "x11_dl_build_script_executor", + srcs = glob(["*", "**/*.rs"]), + outs = ["x11_dl_out_dir_outputs.tar.gz"], + tools = [ + ":x11_dl_build_script", + ], + tags = ["no-sandbox"], + cmd = "mkdir -p $$(dirname $@)/x11_dl_out_dir_outputs/;" + + " (export CARGO_MANIFEST_DIR=\"$$PWD/$$(dirname $(location :Cargo.toml))\";" + # TODO(acmcarther): This needs to be revisited as part of the cross compilation story. + # See also: https://github.com/google/cargo-raze/pull/54 + + " export TARGET='x86_64-unknown-linux-gnu';" + + " export RUST_BACKTRACE=1;" + + " export OUT_DIR=$$PWD/$$(dirname $@)/x11_dl_out_dir_outputs;" + + " export BINARY_PATH=\"$$PWD/$(location :x11_dl_build_script)\";" + + " export OUT_TAR=$$PWD/$@;" + + " cd $$(dirname $(location :Cargo.toml)) && $$BINARY_PATH && tar -czf $$OUT_TAR -C $$OUT_DIR .)" +) -# Unsupported target "build-script-build" with type "custom-build" omitted # Unsupported target "hello-world-dl" with type "example" omitted rust_library( @@ -40,6 +76,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], + out_dir_tar = ":x11_dl_build_script_executor", version = "2.18.5", crate_features = [ ],

{ - #[inline] - fn p(&self, s: &[u8]) -> Option { - let mut i = 0; - while let Some(len) = self.0.p(&s[i..]) { - i += len; - } - Some(i) - } -} diff --git a/third_party/cargo/vendor/semver-parser-0.7.0/src/version.rs b/third_party/cargo/vendor/semver-parser-0.7.0/src/version.rs deleted file mode 100644 index 570f947..0000000 --- a/third_party/cargo/vendor/semver-parser-0.7.0/src/version.rs +++ /dev/null @@ -1,365 +0,0 @@ -use std::fmt; -use std::str::from_utf8; - -use recognize::*; - -use common::{self, numeric_identifier}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Version { - pub major: u64, - pub minor: u64, - pub patch: u64, - pub pre: Vec, - pub build: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Identifier { - /// An identifier that's solely numbers. - Numeric(u64), - /// An identifier with letters and numbers. - AlphaNumeric(String), -} - -pub fn parse(version: &str) -> Result { - let s = version.trim().as_bytes(); - let mut i = 0; - let major = if let Some((major, len)) = numeric_identifier(&s[i..]) { - i += len; - major - } else { - return Err("Error parsing major identifier".to_string()); - }; - if let Some(len) = b'.'.p(&s[i..]) { - i += len; - } else { - return Err("Expected dot".to_string()); - } - let minor = if let Some((minor, len)) = numeric_identifier(&s[i..]) { - i += len; - minor - } else { - return Err("Error parsing minor identifier".to_string()); - }; - if let Some(len) = b'.'.p(&s[i..]) { - i += len; - } else { - return Err("Expected dot".to_string()); - } - let patch = if let Some((patch, len)) = numeric_identifier(&s[i..]) { - i += len; - patch - } else { - return Err("Error parsing patch identifier".to_string()); - }; - let (pre, pre_len) = common::parse_optional_meta(&s[i..], b'-')?; - i += pre_len; - let (build, build_len) = common::parse_optional_meta(&s[i..], b'+')?; - i += build_len; - if i != s.len() { - return Err("Extra junk after valid version: ".to_string() + - from_utf8(&s[i..]).unwrap()); - } - Ok(Version { - major: major, - minor: minor, - patch: patch, - pre: pre, - build: build, - }) -} - -impl fmt::Display for Version { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); - if !self.pre.is_empty() { - let strs: Vec<_> = - self.pre.iter().map(ToString::to_string).collect(); - try!(write!(f, "-{}", strs.join("."))); - } - if !self.build.is_empty() { - let strs: Vec<_> = - self.build.iter().map(ToString::to_string).collect(); - try!(write!(f, "+{}", strs.join("."))); - } - Ok(()) - } -} - -impl fmt::Display for Identifier { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Identifier::Numeric(ref id) => id.fmt(f), - Identifier::AlphaNumeric(ref id) => id.fmt(f), - } - } -} - -#[cfg(test)] -mod tests { - use version; - use super::*; - - #[test] - fn parse_empty() { - let version = ""; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "empty string incorrectly considered a valid parse"); - } - - #[test] - fn parse_blank() { - let version = " "; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "blank string incorrectly considered a valid parse"); - } - - #[test] - fn parse_no_minor_patch() { - let version = "1"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); - } - - #[test] - fn parse_no_patch() { - let version = "1.2"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); - } - - #[test] - fn parse_empty_pre() { - let version = "1.2.3-"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); - } - - #[test] - fn parse_letters() { - let version = "a.b.c"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); - } - - #[test] - fn parse_with_letters() { - let version = "1.2.3 a.b.c"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), format!("'{}' incorrectly considered a valid parse", version)); - } - - #[test] - fn parse_basic_version() { - let version = "1.2.3"; - - let parsed = version::parse(version).unwrap(); - - assert_eq!(1, parsed.major); - assert_eq!(2, parsed.minor); - assert_eq!(3, parsed.patch); - } - - #[test] - fn parse_trims_input() { - let version = " 1.2.3 "; - - let parsed = version::parse(version).unwrap(); - - assert_eq!(1, parsed.major); - assert_eq!(2, parsed.minor); - assert_eq!(3, parsed.patch); - } - - #[test] - fn parse_no_major_leading_zeroes() { - let version = "01.0.0"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "01 incorrectly considered a valid major version"); - } - - #[test] - fn parse_no_minor_leading_zeroes() { - let version = "0.01.0"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "01 incorrectly considered a valid minor version"); - } - - #[test] - fn parse_no_patch_leading_zeroes() { - let version = "0.0.01"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "01 incorrectly considered a valid patch version"); - } - - #[test] - fn parse_no_major_overflow() { - let version = "98765432109876543210.0.0"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid major version"); - } - - #[test] - fn parse_no_minor_overflow() { - let version = "0.98765432109876543210.0"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid minor version"); - } - - #[test] - fn parse_no_patch_overflow() { - let version = "0.0.98765432109876543210"; - - let parsed = version::parse(version); - - assert!(parsed.is_err(), "98765432109876543210 incorrectly considered a valid patch version"); - } - - #[test] - fn parse_basic_prerelease() { - let version = "1.2.3-pre"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("pre"))]; - assert_eq!(expected_pre, parsed.pre); - } - - #[test] - fn parse_prerelease_alphanumeric() { - let version = "1.2.3-alpha1"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; - assert_eq!(expected_pre, parsed.pre); - } - - #[test] - fn parse_prerelease_zero() { - let version = "1.2.3-pre.0"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("pre")), - Identifier::Numeric(0)]; - assert_eq!(expected_pre, parsed.pre); - } - - #[test] - fn parse_basic_build() { - let version = "1.2.3+build"; - - let parsed = version::parse(version).unwrap(); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("build"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_build_alphanumeric() { - let version = "1.2.3+build5"; - - let parsed = version::parse(version).unwrap(); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_pre_and_build() { - let version = "1.2.3-alpha1+build5"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("alpha1"))]; - assert_eq!(expected_pre, parsed.pre); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("build5"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_complex_metadata_01() { - let version = "1.2.3-1.alpha1.9+build5.7.3aedf "; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::Numeric(1), - Identifier::AlphaNumeric(String::from("alpha1")), - Identifier::Numeric(9)]; - assert_eq!(expected_pre, parsed.pre); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("build5")), - Identifier::Numeric(7), - Identifier::AlphaNumeric(String::from("3aedf"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_complex_metadata_02() { - let version = "0.4.0-beta.1+0851523"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1)]; - assert_eq!(expected_pre, parsed.pre); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("0851523"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_metadata_overflow() { - let version = "0.4.0-beta.1+98765432109876543210"; - - let parsed = version::parse(version).unwrap(); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1)]; - assert_eq!(expected_pre, parsed.pre); - - let expected_build = vec![Identifier::AlphaNumeric(String::from("98765432109876543210"))]; - assert_eq!(expected_build, parsed.build); - } - - #[test] - fn parse_regression_01() { - let version = "0.0.0-WIP"; - - let parsed = version::parse(version).unwrap(); - - assert_eq!(0, parsed.major); - assert_eq!(0, parsed.minor); - assert_eq!(0, parsed.patch); - - let expected_pre = vec![Identifier::AlphaNumeric(String::from("WIP"))]; - assert_eq!(expected_pre, parsed.pre); - } -} diff --git a/third_party/cargo/vendor/slab-0.4.2/.cargo-checksum.json b/third_party/cargo/vendor/slab-0.4.2/.cargo-checksum.json new file mode 100644 index 0000000..112dcc2 --- /dev/null +++ b/third_party/cargo/vendor/slab-0.4.2/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"f6f61243fdf15892a03150fad73f0e9bb959845e91596df87d1733874800f34e","Cargo.toml":"c28fd4f04c85aa8099590d4f3b120902a0466c1cf3cbfa2aace227b8389fc173","LICENSE":"8ce0830173fdac609dfb4ea603fdc002c2f4af0dc9b1a005653f5da9cf534b18","README.md":"8b455097ac90777929da00702b384d9b363bb8535e292df2f98d2f2ff321eff5","src/lib.rs":"a78013cc8ceb83bf096b035cda8710474b0c353bcd52a46e5d27ef0efb636f5c","tests/slab.rs":"f9be8e2a6f54285c61238b0a1cde26f7591a7abad5a22a42ea6d195679c1bd91"},"package":"c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"} \ No newline at end of file diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/BUILD b/third_party/cargo/vendor/slab-0.4.2/BUILD similarity index 85% rename from third_party/cargo/vendor/rustc-demangle-0.1.16/BUILD rename to third_party/cargo/vendor/slab-0.4.2/BUILD index 45ada52..6dfb1dd 100644 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/BUILD +++ b/third_party/cargo/vendor/slab-0.4.2/BUILD @@ -12,7 +12,7 @@ package(default_visibility = [ ]) licenses([ - "notice", # "MIT,Apache-2.0" + "notice", # "MIT" ]) load( @@ -25,7 +25,7 @@ load( rust_library( - name = "rustc_demangle", + name = "slab", crate_root = "src/lib.rs", crate_type = "lib", edition = "2015", @@ -35,8 +35,9 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.1.16", + version = "0.4.2", crate_features = [ ], ) +# Unsupported target "slab" with type "test" omitted diff --git a/third_party/cargo/vendor/slab-0.4.2/CHANGELOG.md b/third_party/cargo/vendor/slab-0.4.2/CHANGELOG.md new file mode 100644 index 0000000..9a222b4 --- /dev/null +++ b/third_party/cargo/vendor/slab-0.4.2/CHANGELOG.md @@ -0,0 +1,8 @@ +# 0.4.2 (January 11, 2019) + +* Add `Slab::drain` (#56). + +# 0.4.1 (July 15, 2018) + +* Improve `reserve` and `reserve_exact` (#37). +* Implement `Default` for `Slab` (#43). diff --git a/third_party/cargo/vendor/objc_id-0.1.1/Cargo.toml b/third_party/cargo/vendor/slab-0.4.2/Cargo.toml similarity index 60% rename from third_party/cargo/vendor/objc_id-0.1.1/Cargo.toml rename to third_party/cargo/vendor/slab-0.4.2/Cargo.toml index 86eef1d..9e9fc42 100644 --- a/third_party/cargo/vendor/objc_id-0.1.1/Cargo.toml +++ b/third_party/cargo/vendor/slab-0.4.2/Cargo.toml @@ -11,15 +11,14 @@ # will likely look very different (and much more reasonable) [package] -name = "objc_id" -version = "0.1.1" -authors = ["Steven Sheldon"] -exclude = [".gitignore"] -description = "Rust smart pointers for Objective-C reference counting." -documentation = "http://ssheldon.github.io/rust-objc/objc_id/" +name = "slab" +version = "0.4.2" +authors = ["Carl Lerche "] +description = "Pre-allocated storage for a uniform data type" +homepage = "https://github.com/carllerche/slab" +documentation = "https://docs.rs/slab/0.4.2/slab/" readme = "README.md" -keywords = ["objective-c", "osx", "ios"] +keywords = ["slab", "allocator"] +categories = ["memory-management", "data-structures"] license = "MIT" -repository = "http://github.com/SSheldon/rust-objc-id" -[dependencies.objc] -version = "0.2.4" +repository = "https://github.com/carllerche/slab" diff --git a/third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-MIT b/third_party/cargo/vendor/slab-0.4.2/LICENSE similarity index 96% rename from third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-MIT rename to third_party/cargo/vendor/slab-0.4.2/LICENSE index 39e0ed6..819ce21 100644 --- a/third_party/cargo/vendor/rustc-demangle-0.1.16/LICENSE-MIT +++ b/third_party/cargo/vendor/slab-0.4.2/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2014 Alex Crichton +Copyright (c) 2019 Carl Lerche Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated diff --git a/third_party/cargo/vendor/slab-0.4.2/README.md b/third_party/cargo/vendor/slab-0.4.2/README.md new file mode 100644 index 0000000..2609ffb --- /dev/null +++ b/third_party/cargo/vendor/slab-0.4.2/README.md @@ -0,0 +1,48 @@ +# Slab + +Pre-allocated storage for a uniform data type. + +[![Crates.io](https://img.shields.io/crates/v/slab.svg?maxAge=2592000)](https://crates.io/crates/slab) +[![Build Status](https://travis-ci.org/carllerche/slab.svg?branch=master)](https://travis-ci.org/carllerche/slab) + +[Documentation](https://docs.rs/slab/0.4.2/slab/) + +## Usage + +To use `slab`, first add this to your `Cargo.toml`: + +```toml +[dependencies] +slab = "0.4.2" +``` + +Next, add this to your crate: + +```rust +extern crate slab; + +use slab::Slab; + +let mut slab = Slab::new(); + +let hello = slab.insert("hello"); +let world = slab.insert("world"); + +assert_eq!(slab[hello], "hello"); +assert_eq!(slab[world], "world"); + +slab[world] = "earth"; +assert_eq!(slab[world], "earth"); +``` + +See [documentation](https://docs.rs/slab) for more details. + +## License + +This project is licensed under the [MIT license](LICENSE). + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in `slab` by you, shall be licensed as MIT, without any additional +terms or conditions. diff --git a/third_party/cargo/vendor/slab-0.4.2/src/lib.rs b/third_party/cargo/vendor/slab-0.4.2/src/lib.rs new file mode 100644 index 0000000..a3638ca --- /dev/null +++ b/third_party/cargo/vendor/slab-0.4.2/src/lib.rs @@ -0,0 +1,977 @@ +#![doc(html_root_url = "https://docs.rs/slab/0.4.2")] +#![deny(warnings, missing_docs, missing_debug_implementations)] +#![cfg_attr(test, deny(warnings, unreachable_pub))] + +//! Pre-allocated storage for a uniform data type. +//! +//! `Slab` provides pre-allocated storage for a single data type. If many values +//! of a single type are being allocated, it can be more efficient to +//! pre-allocate the necessary storage. Since the size of the type is uniform, +//! memory fragmentation can be avoided. Storing, clearing, and lookup +//! operations become very cheap. +//! +//! While `Slab` may look like other Rust collections, it is not intended to be +//! used as a general purpose collection. The primary difference between `Slab` +//! and `Vec` is that `Slab` returns the key when storing the value. +//! +//! It is important to note that keys may be reused. In other words, once a +//! value associated with a given key is removed from a slab, that key may be +//! returned from future calls to `insert`. +//! +//! # Examples +//! +//! Basic storing and retrieval. +//! +//! ``` +//! # use slab::*; +//! let mut slab = Slab::new(); +//! +//! let hello = slab.insert("hello"); +//! let world = slab.insert("world"); +//! +//! assert_eq!(slab[hello], "hello"); +//! assert_eq!(slab[world], "world"); +//! +//! slab[world] = "earth"; +//! assert_eq!(slab[world], "earth"); +//! ``` +//! +//! Sometimes it is useful to be able to associate the key with the value being +//! inserted in the slab. This can be done with the `vacant_entry` API as such: +//! +//! ``` +//! # use slab::*; +//! let mut slab = Slab::new(); +//! +//! let hello = { +//! let entry = slab.vacant_entry(); +//! let key = entry.key(); +//! +//! entry.insert((key, "hello")); +//! key +//! }; +//! +//! assert_eq!(hello, slab[hello].0); +//! assert_eq!("hello", slab[hello].1); +//! ``` +//! +//! It is generally a good idea to specify the desired capacity of a slab at +//! creation time. Note that `Slab` will grow the internal capacity when +//! attempting to insert a new value once the existing capacity has been reached. +//! To avoid this, add a check. +//! +//! ``` +//! # use slab::*; +//! let mut slab = Slab::with_capacity(1024); +//! +//! // ... use the slab +//! +//! if slab.len() == slab.capacity() { +//! panic!("slab full"); +//! } +//! +//! slab.insert("the slab is not at capacity yet"); +//! ``` +//! +//! # Capacity and reallocation +//! +//! The capacity of a slab is the amount of space allocated for any future +//! values that will be inserted in the slab. This is not to be confused with +//! the *length* of the slab, which specifies the number of actual values +//! currently being inserted. If a slab's length is equal to its capacity, the +//! next value inserted into the slab will require growing the slab by +//! reallocating. +//! +//! For example, a slab with capacity 10 and length 0 would be an empty slab +//! with space for 10 more stored values. Storing 10 or fewer elements into the +//! slab will not change its capacity or cause reallocation to occur. However, +//! if the slab length is increased to 11 (due to another `insert`), it will +//! have to reallocate, which can be slow. For this reason, it is recommended to +//! use [`Slab::with_capacity`] whenever possible to specify how many values the +//! slab is expected to store. +//! +//! # Implementation +//! +//! `Slab` is backed by a `Vec` of slots. Each slot is either occupied or +//! vacant. `Slab` maintains a stack of vacant slots using a linked list. To +//! find a vacant slot, the stack is popped. When a slot is released, it is +//! pushed onto the stack. +//! +//! If there are no more available slots in the stack, then `Vec::reserve(1)` is +//! called and a new slot is created. +//! +//! [`Slab::with_capacity`]: struct.Slab.html#with_capacity + +use std::iter::IntoIterator; +use std::ops; +use std::vec; +use std::{fmt, mem}; + +/// Pre-allocated storage for a uniform data type +/// +/// See the [module documentation] for more details. +/// +/// [module documentation]: index.html +#[derive(Clone)] +pub struct Slab { + // Chunk of memory + entries: Vec>, + + // Number of Filled elements currently in the slab + len: usize, + + // Offset of the next available slot in the slab. Set to the slab's + // capacity when the slab is full. + next: usize, +} + +impl Default for Slab { + fn default() -> Self { + Slab::new() + } +} + +/// A handle to a vacant entry in a `Slab`. +/// +/// `VacantEntry` allows constructing values with the key that they will be +/// assigned to. +/// +/// # Examples +/// +/// ``` +/// # use slab::*; +/// let mut slab = Slab::new(); +/// +/// let hello = { +/// let entry = slab.vacant_entry(); +/// let key = entry.key(); +/// +/// entry.insert((key, "hello")); +/// key +/// }; +/// +/// assert_eq!(hello, slab[hello].0); +/// assert_eq!("hello", slab[hello].1); +/// ``` +#[derive(Debug)] +pub struct VacantEntry<'a, T: 'a> { + slab: &'a mut Slab, + key: usize, +} + +/// An iterator over the values stored in the `Slab` +pub struct Iter<'a, T: 'a> { + entries: std::slice::Iter<'a, Entry>, + curr: usize, +} + +/// A mutable iterator over the values stored in the `Slab` +pub struct IterMut<'a, T: 'a> { + entries: std::slice::IterMut<'a, Entry>, + curr: usize, +} + +/// A draining iterator for `Slab` +pub struct Drain<'a, T: 'a>(vec::Drain<'a, Entry>); + +#[derive(Clone)] +enum Entry { + Vacant(usize), + Occupied(T), +} + +impl Slab { + /// Construct a new, empty `Slab`. + /// + /// The function does not allocate and the returned slab will have no + /// capacity until `insert` is called or capacity is explicitly reserved. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let slab: Slab = Slab::new(); + /// ``` + pub fn new() -> Slab { + Slab::with_capacity(0) + } + + /// Construct a new, empty `Slab` with the specified capacity. + /// + /// The returned slab will be able to store exactly `capacity` without + /// reallocating. If `capacity` is 0, the slab will not allocate. + /// + /// It is important to note that this function does not specify the *length* + /// of the returned slab, but only the capacity. For an explanation of the + /// difference between length and capacity, see [Capacity and + /// reallocation](index.html#capacity-and-reallocation). + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::with_capacity(10); + /// + /// // The slab contains no values, even though it has capacity for more + /// assert_eq!(slab.len(), 0); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// slab.insert(i); + /// } + /// + /// // ...but this may make the slab reallocate + /// slab.insert(11); + /// ``` + pub fn with_capacity(capacity: usize) -> Slab { + Slab { + entries: Vec::with_capacity(capacity), + next: 0, + len: 0, + } + } + + /// Return the number of values the slab can store without reallocating. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let slab: Slab = Slab::with_capacity(10); + /// assert_eq!(slab.capacity(), 10); + /// ``` + pub fn capacity(&self) -> usize { + self.entries.capacity() + } + + /// Reserve capacity for at least `additional` more values to be stored + /// without allocating. + /// + /// `reserve` does nothing if the slab already has sufficient capacity for + /// `additional` more values. If more capacity is required, a new segment of + /// memory will be allocated and all existing values will be copied into it. + /// As such, if the slab is already very large, a call to `reserve` can end + /// up being expensive. + /// + /// The slab may reserve more than `additional` extra space in order to + /// avoid frequent reallocations. Use `reserve_exact` instead to guarantee + /// that only the requested space is allocated. + /// + /// # Panics + /// + /// Panics if the new capacity overflows `usize`. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// slab.insert("hello"); + /// slab.reserve(10); + /// assert!(slab.capacity() >= 11); + /// ``` + pub fn reserve(&mut self, additional: usize) { + if self.capacity() - self.len >= additional { + return; + } + let need_add = self.len + additional - self.entries.len(); + self.entries.reserve(need_add); + } + + /// Reserve the minimum capacity required to store exactly `additional` + /// more values. + /// + /// `reserve_exact` does nothing if the slab already has sufficient capacity + /// for `additional` more valus. If more capacity is required, a new segment + /// of memory will be allocated and all existing values will be copied into + /// it. As such, if the slab is already very large, a call to `reserve` can + /// end up being expensive. + /// + /// Note that the allocator may give the slab more space than it requests. + /// Therefore capacity can not be relied upon to be precisely minimal. + /// Prefer `reserve` if future insertions are expected. + /// + /// # Panics + /// + /// Panics if the new capacity overflows `usize`. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// slab.insert("hello"); + /// slab.reserve_exact(10); + /// assert!(slab.capacity() >= 11); + /// ``` + pub fn reserve_exact(&mut self, additional: usize) { + if self.capacity() - self.len >= additional { + return; + } + let need_add = self.len + additional - self.entries.len(); + self.entries.reserve_exact(need_add); + } + + /// Shrink the capacity of the slab as much as possible. + /// + /// It will drop down as close as possible to the length but the allocator + /// may still inform the vector that there is space for a few more elements. + /// Also, since values are not moved, the slab cannot shrink past any stored + /// values. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::with_capacity(10); + /// + /// for i in 0..3 { + /// slab.insert(i); + /// } + /// + /// assert_eq!(slab.capacity(), 10); + /// slab.shrink_to_fit(); + /// assert!(slab.capacity() >= 3); + /// ``` + /// + /// In this case, even though two values are removed, the slab cannot shrink + /// past the last value. + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::with_capacity(10); + /// + /// for i in 0..3 { + /// slab.insert(i); + /// } + /// + /// slab.remove(0); + /// slab.remove(1); + /// + /// assert_eq!(slab.capacity(), 10); + /// slab.shrink_to_fit(); + /// assert!(slab.capacity() >= 3); + /// ``` + pub fn shrink_to_fit(&mut self) { + self.entries.shrink_to_fit(); + } + + /// Clear the slab of all values. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// for i in 0..3 { + /// slab.insert(i); + /// } + /// + /// slab.clear(); + /// assert!(slab.is_empty()); + /// ``` + pub fn clear(&mut self) { + self.entries.clear(); + self.len = 0; + self.next = 0; + } + + /// Return the number of stored values. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// for i in 0..3 { + /// slab.insert(i); + /// } + /// + /// assert_eq!(3, slab.len()); + /// ``` + pub fn len(&self) -> usize { + self.len + } + + /// Return `true` if there are no values stored in the slab. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// assert!(slab.is_empty()); + /// + /// slab.insert(1); + /// assert!(!slab.is_empty()); + /// ``` + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Return an iterator over the slab. + /// + /// This function should generally be **avoided** as it is not efficient. + /// Iterators must iterate over every slot in the slab even if it is + /// vacant. As such, a slab with a capacity of 1 million but only one + /// stored value must still iterate the million slots. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// for i in 0..3 { + /// slab.insert(i); + /// } + /// + /// let mut iterator = slab.iter(); + /// + /// assert_eq!(iterator.next(), Some((0, &0))); + /// assert_eq!(iterator.next(), Some((1, &1))); + /// assert_eq!(iterator.next(), Some((2, &2))); + /// assert_eq!(iterator.next(), None); + /// ``` + pub fn iter(&self) -> Iter { + Iter { + entries: self.entries.iter(), + curr: 0, + } + } + + /// Return an iterator that allows modifying each value. + /// + /// This function should generally be **avoided** as it is not efficient. + /// Iterators must iterate over every slot in the slab even if it is + /// vacant. As such, a slab with a capacity of 1 million but only one + /// stored value must still iterate the million slots. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let key1 = slab.insert(0); + /// let key2 = slab.insert(1); + /// + /// for (key, val) in slab.iter_mut() { + /// if key == key1 { + /// *val += 2; + /// } + /// } + /// + /// assert_eq!(slab[key1], 2); + /// assert_eq!(slab[key2], 1); + /// ``` + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + entries: self.entries.iter_mut(), + curr: 0, + } + } + + /// Return a reference to the value associated with the given key. + /// + /// If the given key is not associated with a value, then `None` is + /// returned. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// let key = slab.insert("hello"); + /// + /// assert_eq!(slab.get(key), Some(&"hello")); + /// assert_eq!(slab.get(123), None); + /// ``` + pub fn get(&self, key: usize) -> Option<&T> { + match self.entries.get(key) { + Some(&Entry::Occupied(ref val)) => Some(val), + _ => None, + } + } + + /// Return a mutable reference to the value associated with the given key. + /// + /// If the given key is not associated with a value, then `None` is + /// returned. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// let key = slab.insert("hello"); + /// + /// *slab.get_mut(key).unwrap() = "world"; + /// + /// assert_eq!(slab[key], "world"); + /// assert_eq!(slab.get_mut(123), None); + /// ``` + pub fn get_mut(&mut self, key: usize) -> Option<&mut T> { + match self.entries.get_mut(key) { + Some(&mut Entry::Occupied(ref mut val)) => Some(val), + _ => None, + } + } + + /// Return a reference to the value associated with the given key without + /// performing bounds checking. + /// + /// This function should be used with care. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// let key = slab.insert(2); + /// + /// unsafe { + /// assert_eq!(slab.get_unchecked(key), &2); + /// } + /// ``` + pub unsafe fn get_unchecked(&self, key: usize) -> &T { + match *self.entries.get_unchecked(key) { + Entry::Occupied(ref val) => val, + _ => unreachable!(), + } + } + + /// Return a mutable reference to the value associated with the given key + /// without performing bounds checking. + /// + /// This function should be used with care. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// let key = slab.insert(2); + /// + /// unsafe { + /// let val = slab.get_unchecked_mut(key); + /// *val = 13; + /// } + /// + /// assert_eq!(slab[key], 13); + /// ``` + pub unsafe fn get_unchecked_mut(&mut self, key: usize) -> &mut T { + match *self.entries.get_unchecked_mut(key) { + Entry::Occupied(ref mut val) => val, + _ => unreachable!(), + } + } + + /// Insert a value in the slab, returning key assigned to the value. + /// + /// The returned key can later be used to retrieve or remove the value using indexed + /// lookup and `remove`. Additional capacity is allocated if needed. See + /// [Capacity and reallocation](index.html#capacity-and-reallocation). + /// + /// # Panics + /// + /// Panics if the number of elements in the vector overflows a `usize`. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// let key = slab.insert("hello"); + /// assert_eq!(slab[key], "hello"); + /// ``` + pub fn insert(&mut self, val: T) -> usize { + let key = self.next; + + self.insert_at(key, val); + + key + } + + /// Return a handle to a vacant entry allowing for further manipulation. + /// + /// This function is useful when creating values that must contain their + /// slab key. The returned `VacantEntry` reserves a slot in the slab and is + /// able to query the associated key. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let hello = { + /// let entry = slab.vacant_entry(); + /// let key = entry.key(); + /// + /// entry.insert((key, "hello")); + /// key + /// }; + /// + /// assert_eq!(hello, slab[hello].0); + /// assert_eq!("hello", slab[hello].1); + /// ``` + pub fn vacant_entry(&mut self) -> VacantEntry { + VacantEntry { + key: self.next, + slab: self, + } + } + + fn insert_at(&mut self, key: usize, val: T) { + self.len += 1; + + if key == self.entries.len() { + self.entries.push(Entry::Occupied(val)); + self.next = key + 1; + } else { + let prev = mem::replace(&mut self.entries[key], Entry::Occupied(val)); + + match prev { + Entry::Vacant(next) => { + self.next = next; + } + _ => unreachable!(), + } + } + } + + /// Remove and return the value associated with the given key. + /// + /// The key is then released and may be associated with future stored + /// values. + /// + /// # Panics + /// + /// Panics if `key` is not associated with a value. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let hello = slab.insert("hello"); + /// + /// assert_eq!(slab.remove(hello), "hello"); + /// assert!(!slab.contains(hello)); + /// ``` + pub fn remove(&mut self, key: usize) -> T { + // Swap the entry at the provided value + let prev = mem::replace(&mut self.entries[key], Entry::Vacant(self.next)); + + match prev { + Entry::Occupied(val) => { + self.len -= 1; + self.next = key; + val + } + _ => { + // Woops, the entry is actually vacant, restore the state + self.entries[key] = prev; + panic!("invalid key"); + } + } + } + + /// Return `true` if a value is associated with the given key. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let hello = slab.insert("hello"); + /// assert!(slab.contains(hello)); + /// + /// slab.remove(hello); + /// + /// assert!(!slab.contains(hello)); + /// ``` + pub fn contains(&self, key: usize) -> bool { + self.entries + .get(key) + .map(|e| match *e { + Entry::Occupied(_) => true, + _ => false, + }) + .unwrap_or(false) + } + + /// Retain only the elements specified by the predicate. + /// + /// In other words, remove all elements `e` such that `f(usize, &mut e)` + /// returns false. This method operates in place and preserves the key + /// associated with the retained values. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let k1 = slab.insert(0); + /// let k2 = slab.insert(1); + /// let k3 = slab.insert(2); + /// + /// slab.retain(|key, val| key == k1 || *val == 1); + /// + /// assert!(slab.contains(k1)); + /// assert!(slab.contains(k2)); + /// assert!(!slab.contains(k3)); + /// + /// assert_eq!(2, slab.len()); + /// ``` + pub fn retain(&mut self, mut f: F) + where + F: FnMut(usize, &mut T) -> bool, + { + for i in 0..self.entries.len() { + let keep = match self.entries[i] { + Entry::Occupied(ref mut v) => f(i, v), + _ => true, + }; + + if !keep { + self.remove(i); + } + } + } + + /// Return a draining iterator that removes all elements from the slab and + /// yields the removed items. + /// + /// Note: Elements are removed even if the iterator is only partially + /// consumed or not consumed at all. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let _ = slab.insert(0); + /// let _ = slab.insert(1); + /// let _ = slab.insert(2); + /// + /// { + /// let mut drain = slab.drain(); + /// + /// assert_eq!(Some(0), drain.next()); + /// assert_eq!(Some(1), drain.next()); + /// assert_eq!(Some(2), drain.next()); + /// assert_eq!(None, drain.next()); + /// } + /// + /// assert!(slab.is_empty()); + /// ``` + pub fn drain(&mut self) -> Drain { + self.len = 0; + self.next = 0; + Drain(self.entries.drain(..)) + } +} + +impl ops::Index for Slab { + type Output = T; + + fn index(&self, key: usize) -> &T { + match self.entries[key] { + Entry::Occupied(ref v) => v, + _ => panic!("invalid key"), + } + } +} + +impl ops::IndexMut for Slab { + fn index_mut(&mut self, key: usize) -> &mut T { + match self.entries[key] { + Entry::Occupied(ref mut v) => v, + _ => panic!("invalid key"), + } + } +} + +impl<'a, T> IntoIterator for &'a Slab { + type Item = (usize, &'a T); + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T> IntoIterator for &'a mut Slab { + type Item = (usize, &'a mut T); + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl fmt::Debug for Slab +where + T: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!( + fmt, + "Slab {{ len: {}, cap: {} }}", + self.len, + self.capacity() + ) + } +} + +impl<'a, T: 'a> fmt::Debug for Iter<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Iter") + .field("curr", &self.curr) + .field("remaining", &self.entries.len()) + .finish() + } +} + +impl<'a, T: 'a> fmt::Debug for IterMut<'a, T> +where + T: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("IterMut") + .field("curr", &self.curr) + .field("remaining", &self.entries.len()) + .finish() + } +} + +impl<'a, T: 'a> fmt::Debug for Drain<'a, T> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Drain").finish() + } +} + +// ===== VacantEntry ===== + +impl<'a, T> VacantEntry<'a, T> { + /// Insert a value in the entry, returning a mutable reference to the value. + /// + /// To get the key associated with the value, use `key` prior to calling + /// `insert`. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let hello = { + /// let entry = slab.vacant_entry(); + /// let key = entry.key(); + /// + /// entry.insert((key, "hello")); + /// key + /// }; + /// + /// assert_eq!(hello, slab[hello].0); + /// assert_eq!("hello", slab[hello].1); + /// ``` + pub fn insert(self, val: T) -> &'a mut T { + self.slab.insert_at(self.key, val); + + match self.slab.entries[self.key] { + Entry::Occupied(ref mut v) => v, + _ => unreachable!(), + } + } + + /// Return the key associated with this entry. + /// + /// A value stored in this entry will be associated with this key. + /// + /// # Examples + /// + /// ``` + /// # use slab::*; + /// let mut slab = Slab::new(); + /// + /// let hello = { + /// let entry = slab.vacant_entry(); + /// let key = entry.key(); + /// + /// entry.insert((key, "hello")); + /// key + /// }; + /// + /// assert_eq!(hello, slab[hello].0); + /// assert_eq!("hello", slab[hello].1); + /// ``` + pub fn key(&self) -> usize { + self.key + } +} + +// ===== Iter ===== + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = (usize, &'a T); + + fn next(&mut self) -> Option<(usize, &'a T)> { + while let Some(entry) = self.entries.next() { + let curr = self.curr; + self.curr += 1; + + if let Entry::Occupied(ref v) = *entry { + return Some((curr, v)); + } + } + + None + } +} + +// ===== IterMut ===== + +impl<'a, T> Iterator for IterMut<'a, T> { + type Item = (usize, &'a mut T); + + fn next(&mut self) -> Option<(usize, &'a mut T)> { + while let Some(entry) = self.entries.next() { + let curr = self.curr; + self.curr += 1; + + if let Entry::Occupied(ref mut v) = *entry { + return Some((curr, v)); + } + } + + None + } +} + +// ===== Drain ===== + +impl<'a, T> Iterator for Drain<'a, T> { + type Item = T; + + fn next(&mut self) -> Option { + while let Some(entry) = self.0.next() { + if let Entry::Occupied(v) = entry { + return Some(v); + } + } + + None + } +} diff --git a/third_party/cargo/vendor/slab-0.4.2/tests/slab.rs b/third_party/cargo/vendor/slab-0.4.2/tests/slab.rs new file mode 100644 index 0000000..5203c95 --- /dev/null +++ b/third_party/cargo/vendor/slab-0.4.2/tests/slab.rs @@ -0,0 +1,301 @@ +extern crate slab; + +use slab::*; + +#[test] +fn insert_get_remove_one() { + let mut slab = Slab::new(); + assert!(slab.is_empty()); + + let key = slab.insert(10); + + assert_eq!(slab[key], 10); + assert_eq!(slab.get(key), Some(&10)); + assert!(!slab.is_empty()); + assert!(slab.contains(key)); + + assert_eq!(slab.remove(key), 10); + assert!(!slab.contains(key)); + assert!(slab.get(key).is_none()); +} + +#[test] +fn insert_get_many() { + let mut slab = Slab::with_capacity(10); + + for i in 0..10 { + let key = slab.insert(i + 10); + assert_eq!(slab[key], i + 10); + } + + assert_eq!(slab.capacity(), 10); + + // Storing another one grows the slab + let key = slab.insert(20); + assert_eq!(slab[key], 20); + + // Capacity grows by 2x + assert_eq!(slab.capacity(), 20); +} + +#[test] +fn insert_get_remove_many() { + let mut slab = Slab::with_capacity(10); + let mut keys = vec![]; + + for i in 0..10 { + for j in 0..10 { + let val = (i * 10) + j; + + let key = slab.insert(val); + keys.push((key, val)); + assert_eq!(slab[key], val); + } + + for (key, val) in keys.drain(..) { + assert_eq!(val, slab.remove(key)); + } + } + + assert_eq!(10, slab.capacity()); +} + +#[test] +fn insert_with_vacant_entry() { + let mut slab = Slab::with_capacity(1); + let key; + + { + let entry = slab.vacant_entry(); + key = entry.key(); + entry.insert(123); + } + + assert_eq!(123, slab[key]); +} + +#[test] +fn get_vacant_entry_without_using() { + let mut slab = Slab::::with_capacity(1); + let key = slab.vacant_entry().key(); + assert_eq!(key, slab.vacant_entry().key()); +} + +#[test] +#[should_panic] +fn invalid_get_panics() { + let slab = Slab::::with_capacity(1); + slab[0]; +} + +#[test] +#[should_panic] +fn double_remove_panics() { + let mut slab = Slab::::with_capacity(1); + let key = slab.insert(123); + slab.remove(key); + slab.remove(key); +} + +#[test] +#[should_panic] +fn invalid_remove_panics() { + let mut slab = Slab::::with_capacity(1); + slab.remove(0); +} + +#[test] +fn slab_get_mut() { + let mut slab = Slab::new(); + let key = slab.insert(1); + + slab[key] = 2; + assert_eq!(slab[key], 2); + + *slab.get_mut(key).unwrap() = 3; + assert_eq!(slab[key], 3); +} + +#[test] +fn reserve_does_not_allocate_if_available() { + let mut slab = Slab::with_capacity(10); + let mut keys = vec![]; + + for i in 0..6 { + keys.push(slab.insert(i)); + } + + for key in 0..4 { + slab.remove(key); + } + + assert!(slab.capacity() - slab.len() == 8); + + slab.reserve(8); + assert_eq!(10, slab.capacity()); +} + +#[test] +fn reserve_exact_does_not_allocate_if_available() { + let mut slab = Slab::with_capacity(10); + let mut keys = vec![]; + + for i in 0..6 { + keys.push(slab.insert(i)); + } + + for key in 0..4 { + slab.remove(key); + } + + assert!(slab.capacity() - slab.len() == 8); + + slab.reserve(8); + assert_eq!(10, slab.capacity()); +} + +#[test] +fn retain() { + let mut slab = Slab::with_capacity(2); + + let key1 = slab.insert(0); + let key2 = slab.insert(1); + + slab.retain(|key, x| { + assert_eq!(key, *x); + *x % 2 == 0 + }); + + assert_eq!(slab.len(), 1); + assert_eq!(slab[key1], 0); + assert!(!slab.contains(key2)); + + // Ensure consistency is retained + let key = slab.insert(123); + assert_eq!(key, key2); + + assert_eq!(2, slab.len()); + assert_eq!(2, slab.capacity()); + + // Inserting another element grows + let key = slab.insert(345); + assert_eq!(key, 2); + + assert_eq!(4, slab.capacity()); +} + +#[test] +fn iter() { + let mut slab = Slab::new(); + + for i in 0..4 { + slab.insert(i); + } + + let vals: Vec<_> = slab + .iter() + .enumerate() + .map(|(i, (key, val))| { + assert_eq!(i, key); + *val + }) + .collect(); + assert_eq!(vals, vec![0, 1, 2, 3]); + + slab.remove(1); + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert_eq!(vals, vec![0, 2, 3]); +} + +#[test] +fn iter_mut() { + let mut slab = Slab::new(); + + for i in 0..4 { + slab.insert(i); + } + + for (i, (key, e)) in slab.iter_mut().enumerate() { + assert_eq!(i, key); + *e = *e + 1; + } + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert_eq!(vals, vec![1, 2, 3, 4]); + + slab.remove(2); + + for (_, e) in slab.iter_mut() { + *e = *e + 1; + } + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert_eq!(vals, vec![2, 3, 5]); +} + +#[test] +fn clear() { + let mut slab = Slab::new(); + + for i in 0..4 { + slab.insert(i); + } + + // clear full + slab.clear(); + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert!(vals.is_empty()); + + assert_eq!(0, slab.len()); + assert_eq!(4, slab.capacity()); + + for i in 0..2 { + slab.insert(i); + } + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert_eq!(vals, vec![0, 1]); + + // clear half-filled + slab.clear(); + + let vals: Vec<_> = slab.iter().map(|(_, r)| *r).collect(); + assert!(vals.is_empty()); +} + +#[test] +fn fully_consumed_drain() { + let mut slab = Slab::new(); + + for i in 0..3 { + slab.insert(i); + } + + { + let mut drain = slab.drain(); + assert_eq!(Some(0), drain.next()); + assert_eq!(Some(1), drain.next()); + assert_eq!(Some(2), drain.next()); + assert_eq!(None, drain.next()); + } + + assert!(slab.is_empty()); +} + +#[test] +fn partially_consumed_drain() { + let mut slab = Slab::new(); + + for i in 0..3 { + slab.insert(i); + } + + { + let mut drain = slab.drain(); + assert_eq!(Some(0), drain.next()); + } + + assert!(slab.is_empty()) +} diff --git a/third_party/cargo/vendor/smallvec-0.6.13/.cargo-checksum.json b/third_party/cargo/vendor/smallvec-0.6.13/.cargo-checksum.json deleted file mode 100644 index 5ef6f73..0000000 --- a/third_party/cargo/vendor/smallvec-0.6.13/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"9b9dd0b09c80450d9b16308948eef9675bec260a4cd738572ff67e8d7d271f9c","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0b28172679e0009b655da42797c03fd163a3379d5cfa67ba1f1655e974a2a1a9","README.md":"38eef4ebde6fe6effa12a2dbca3bd69d6446b2935f19a329ac4926f1cb2e5013","benches/bench.rs":"9dca7122a3dcb2c099e49807e4d3b8f01d9220e2b3db0a54e9901ee74392866f","lib.rs":"f2f9c0f77e63672496591328cb90358d1a7d664aae8e7dee59cd0525010649cb","scripts/run_miri.sh":"cd645dfecf19cc77141ecaf698e58a3a743ad69aca5e5d25c8e5d3911e031322","specialization.rs":"b29ac094999b94cc193dde52432e8cd8d17a299192822b3485c27bf6a1bdc397"},"package":"f7b0758c52e15a8b5e3691eae6cc559f08eee9406e548a4477ba4e67770a82b6"} \ No newline at end of file diff --git a/third_party/cargo/vendor/smallvec-0.6.13/LICENSE-APACHE b/third_party/cargo/vendor/smallvec-0.6.13/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/third_party/cargo/vendor/smallvec-0.6.13/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/cargo/vendor/smallvec-0.6.13/README.md b/third_party/cargo/vendor/smallvec-0.6.13/README.md deleted file mode 100644 index fda7fd4..0000000 --- a/third_party/cargo/vendor/smallvec-0.6.13/README.md +++ /dev/null @@ -1,8 +0,0 @@ -rust-smallvec -============= - -[Documentation](https://docs.rs/smallvec/) - -[Release notes](https://github.com/servo/rust-smallvec/releases) - -"Small vector" optimization for Rust: store up to a small number of items on the stack diff --git a/third_party/cargo/vendor/smallvec-1.2.0/.cargo-checksum.json b/third_party/cargo/vendor/smallvec-1.2.0/.cargo-checksum.json new file mode 100644 index 0000000..3e4ba00 --- /dev/null +++ b/third_party/cargo/vendor/smallvec-1.2.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"82c58cfe1208040b0772a4eb0fc59c2f84c75dd28115f2847a6edc91a340b7f4","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0b28172679e0009b655da42797c03fd163a3379d5cfa67ba1f1655e974a2a1a9","README.md":"a01127c37308457e8d396b176fb790846be0978c173be3f13260b62efcef011b","benches/bench.rs":"9dca7122a3dcb2c099e49807e4d3b8f01d9220e2b3db0a54e9901ee74392866f","lib.rs":"6b128fc5aa50b5dd775d45252e277c13546f1de2ebee340c6c8ff48627678244","scripts/run_miri.sh":"2e83d153efc16cbc3c41589e306faa0624c8b9a0feecea3baae6e34f4563ac42","specialization.rs":"46433586203399251cba496d67b88d34e1be3c2b591986b77463513da1c66471"},"package":"5c2fb2ec9bcd216a5b0d0ccf31ab17b5ed1d627960edff65bbe95d3ce221cefc"} \ No newline at end of file diff --git a/third_party/cargo/vendor/smallvec-0.6.13/BUILD b/third_party/cargo/vendor/smallvec-1.2.0/BUILD similarity index 83% rename from third_party/cargo/vendor/smallvec-0.6.13/BUILD rename to third_party/cargo/vendor/smallvec-1.2.0/BUILD index f8490e5..1df4fb2 100644 --- a/third_party/cargo/vendor/smallvec-0.6.13/BUILD +++ b/third_party/cargo/vendor/smallvec-1.2.0/BUILD @@ -29,18 +29,15 @@ rust_library( name = "smallvec", crate_root = "lib.rs", crate_type = "lib", - edition = "2015", + edition = "2018", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/maybe-uninit-2.0.0:maybe_uninit", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.6.13", + version = "1.2.0", crate_features = [ - "default", - "std", ], ) diff --git a/third_party/cargo/vendor/smallvec-0.6.13/Cargo.toml b/third_party/cargo/vendor/smallvec-1.2.0/Cargo.toml similarity index 88% rename from third_party/cargo/vendor/smallvec-0.6.13/Cargo.toml rename to third_party/cargo/vendor/smallvec-1.2.0/Cargo.toml index 6d1679e..199dc13 100644 --- a/third_party/cargo/vendor/smallvec-0.6.13/Cargo.toml +++ b/third_party/cargo/vendor/smallvec-1.2.0/Cargo.toml @@ -11,11 +11,12 @@ # will likely look very different (and much more reasonable) [package] +edition = "2018" name = "smallvec" -version = "0.6.13" +version = "1.2.0" authors = ["Simon Sapin "] description = "'Small vector' optimization: store up to a small number of items on the stack" -documentation = "https://doc.servo.org/smallvec/" +documentation = "https://docs.rs/smallvec/" readme = "README.md" keywords = ["small", "vec", "vector", "stack", "no_std"] categories = ["data-structures"] @@ -25,9 +26,6 @@ repository = "https://github.com/servo/rust-smallvec" [lib] name = "smallvec" path = "lib.rs" -[dependencies.maybe-uninit] -version = "2.0" - [dependencies.serde] version = "1" optional = true @@ -35,8 +33,7 @@ optional = true version = "1.0.1" [features] -default = ["std"] may_dangle = [] specialization = [] -std = [] union = [] +write = [] diff --git a/third_party/cargo/vendor/percent-encoding-1.0.1/LICENSE-APACHE b/third_party/cargo/vendor/smallvec-1.2.0/LICENSE-APACHE similarity index 100% rename from third_party/cargo/vendor/percent-encoding-1.0.1/LICENSE-APACHE rename to third_party/cargo/vendor/smallvec-1.2.0/LICENSE-APACHE diff --git a/third_party/cargo/vendor/smallvec-0.6.13/LICENSE-MIT b/third_party/cargo/vendor/smallvec-1.2.0/LICENSE-MIT similarity index 100% rename from third_party/cargo/vendor/smallvec-0.6.13/LICENSE-MIT rename to third_party/cargo/vendor/smallvec-1.2.0/LICENSE-MIT diff --git a/third_party/cargo/vendor/smallvec-1.2.0/README.md b/third_party/cargo/vendor/smallvec-1.2.0/README.md new file mode 100644 index 0000000..724637c --- /dev/null +++ b/third_party/cargo/vendor/smallvec-1.2.0/README.md @@ -0,0 +1,26 @@ +rust-smallvec +============= + +[Documentation](https://docs.rs/smallvec/) + +[Release notes](https://github.com/servo/rust-smallvec/releases) + +"Small vector" optimization for Rust: store up to a small number of items on the stack + +## Example + +```rust +use smallvec::{SmallVec, smallvec}; + +// This SmallVec can hold up to 4 items on the stack: +let mut v: SmallVec<[i32; 4]> = smallvec![1, 2, 3, 4]; + +// It will automatically move its contents to the heap if +// contains more than four items: +v.push(5); + +// SmallVec points to a slice, so you can use normal slice +// indexing and other methods to access its contents: +v[0] = v[1] + v[2]; +v.sort(); +``` diff --git a/third_party/cargo/vendor/smallvec-0.6.13/benches/bench.rs b/third_party/cargo/vendor/smallvec-1.2.0/benches/bench.rs similarity index 100% rename from third_party/cargo/vendor/smallvec-0.6.13/benches/bench.rs rename to third_party/cargo/vendor/smallvec-1.2.0/benches/bench.rs diff --git a/third_party/cargo/vendor/smallvec-0.6.13/lib.rs b/third_party/cargo/vendor/smallvec-1.2.0/lib.rs similarity index 78% rename from third_party/cargo/vendor/smallvec-0.6.13/lib.rs rename to third_party/cargo/vendor/smallvec-1.2.0/lib.rs index 55278ad..0c8243e 100644 --- a/third_party/cargo/vendor/smallvec-0.6.13/lib.rs +++ b/third_party/cargo/vendor/smallvec-1.2.0/lib.rs @@ -8,14 +8,11 @@ //! to the heap for larger allocations. This can be a useful optimization for improving cache //! locality and reducing allocator traffic for workloads that fit within the inline buffer. //! -//! ## no_std support +//! ## `no_std` support //! -//! By default, `smallvec` depends on `libstd`. However, it can be configured to use the unstable -//! `liballoc` API instead, for use on platforms that have `liballoc` but not `libstd`. This -//! configuration is currently unstable and is not guaranteed to work on all versions of Rust. -//! -//! To depend on `smallvec` without `libstd`, use `default-features = false` in the `smallvec` -//! section of Cargo.toml to disable its `"std"` feature. +//! By default, `smallvec` does not depend on `std`. However, the optional +//! `write` feature implements the `std::io::Write` trait for vectors of `u8`. +//! When this feature is enabled, `smallvec` depends on `std`. //! //! ## `union` feature //! @@ -28,49 +25,43 @@ //! To use this feature add `features = ["union"]` in the `smallvec` section of Cargo.toml. //! Note that this feature requires a nightly compiler (for now). -#![cfg_attr(not(feature = "std"), no_std)] +#![no_std] #![cfg_attr(feature = "union", feature(untagged_unions))] #![cfg_attr(feature = "specialization", feature(specialization))] #![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))] #![deny(missing_docs)] +#[doc(hidden)] +pub extern crate alloc; -#[cfg(not(feature = "std"))] -#[macro_use] -extern crate alloc; +#[cfg(any(test, feature = "write"))] +extern crate std; -#[cfg(not(feature = "std"))] -use alloc::vec::Vec; +use alloc::boxed::Box; +use alloc::{vec, vec::Vec}; +use core::borrow::{Borrow, BorrowMut}; +use core::cmp; +use core::fmt; +use core::hash::{Hash, Hasher}; +use core::hint::unreachable_unchecked; +use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator}; +use core::mem; +use core::mem::MaybeUninit; +use core::ops::{self, RangeBounds}; +use core::ptr::{self, NonNull}; +use core::slice::{self, SliceIndex}; #[cfg(feature = "serde")] -extern crate serde; +use serde::{ + de::{Deserialize, Deserializer, SeqAccess, Visitor}, + ser::{Serialize, SerializeSeq, Serializer}, +}; -extern crate maybe_uninit; +#[cfg(feature = "serde")] +use core::marker::PhantomData; -#[cfg(not(feature = "std"))] -mod std { - pub use core::*; -} - -use maybe_uninit::MaybeUninit; - -use std::borrow::{Borrow, BorrowMut}; -use std::cmp; -use std::fmt; -use std::hash::{Hash, Hasher}; -use std::iter::{IntoIterator, FromIterator, repeat}; -use std::mem; -use std::ops; -use std::ptr; -use std::slice; -#[cfg(feature = "std")] +#[cfg(feature = "write")] use std::io; -#[cfg(feature = "serde")] -use serde::ser::{Serialize, Serializer, SerializeSeq}; -#[cfg(feature = "serde")] -use serde::de::{Deserialize, Deserializer, SeqAccess, Visitor}; -#[cfg(feature = "serde")] -use std::marker::PhantomData; /// Creates a [`SmallVec`] containing the arguments. /// @@ -125,81 +116,24 @@ macro_rules! smallvec { $(vec.push($x);)* vec } else { - $crate::SmallVec::from_vec(vec![$($x,)*]) + $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)*]) } }); } -/// Hint to the optimizer that any code path which calls this function is -/// statically unreachable and can be removed. -/// -/// Equivalent to `std::hint::unreachable_unchecked` but works in older versions of Rust. -#[inline] -pub unsafe fn unreachable() -> ! { - enum Void {} - let x: &Void = mem::transmute(1usize); - match *x {} -} - /// `panic!()` in debug builds, optimization hint in release. #[cfg(not(feature = "union"))] macro_rules! debug_unreachable { - () => { debug_unreachable!("entered unreachable code") }; + () => { + debug_unreachable!("entered unreachable code") + }; ($e:expr) => { if cfg!(not(debug_assertions)) { - unreachable(); + unreachable_unchecked(); } else { panic!($e); } - } -} - -/// Common operations implemented by both `Vec` and `SmallVec`. -/// -/// This can be used to write generic code that works with both `Vec` and `SmallVec`. -/// -/// ## Example -/// -/// ```rust -/// use smallvec::{VecLike, SmallVec}; -/// -/// fn initialize>(v: &mut V) { -/// for i in 0..5 { -/// v.push(i); -/// } -/// } -/// -/// let mut vec = Vec::new(); -/// initialize(&mut vec); -/// -/// let mut small_vec = SmallVec::<[u8; 8]>::new(); -/// initialize(&mut small_vec); -/// ``` -#[deprecated(note = "Use `Extend` and `Deref<[T]>` instead")] -pub trait VecLike: - ops::Index + - ops::IndexMut + - ops::Index, Output=[T]> + - ops::IndexMut> + - ops::Index, Output=[T]> + - ops::IndexMut> + - ops::Index, Output=[T]> + - ops::IndexMut> + - ops::Index + - ops::IndexMut + - ops::DerefMut + - Extend { - - /// Append an element to the vector. - fn push(&mut self, value: T); -} - -#[allow(deprecated)] -impl VecLike for Vec { - #[inline] - fn push(&mut self, value: T) { - Vec::push(self, value); - } + }; } /// Trait to be implemented by a collection that can be extended from a slice @@ -242,16 +176,33 @@ unsafe fn deallocate(ptr: *mut T, capacity: usize) { /// Returned from [`SmallVec::drain`][1]. /// /// [1]: struct.SmallVec.html#method.drain -pub struct Drain<'a, T: 'a> { - iter: slice::IterMut<'a,T>, +pub struct Drain<'a, T: 'a + Array> { + tail_start: usize, + tail_len: usize, + iter: slice::Iter<'a, T::Item>, + vec: NonNull>, } -impl<'a, T: 'a> Iterator for Drain<'a,T> { - type Item = T; +impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T> +where + T::Item: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("Drain").field(&self.iter.as_slice()).finish() + } +} + +unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {} +unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {} + +impl<'a, T: 'a + Array> Iterator for Drain<'a, T> { + type Item = T::Item; #[inline] - fn next(&mut self) -> Option { - self.iter.next().map(|reference| unsafe { ptr::read(reference) }) + fn next(&mut self) -> Option { + self.iter + .next() + .map(|reference| unsafe { ptr::read(reference) }) } #[inline] @@ -260,19 +211,43 @@ impl<'a, T: 'a> Iterator for Drain<'a,T> { } } -impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { +impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> { #[inline] - fn next_back(&mut self) -> Option { - self.iter.next_back().map(|reference| unsafe { ptr::read(reference) }) + fn next_back(&mut self) -> Option { + self.iter + .next_back() + .map(|reference| unsafe { ptr::read(reference) }) } } -impl<'a, T> ExactSizeIterator for Drain<'a, T> { } +impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } +} -impl<'a, T: 'a> Drop for Drain<'a,T> { +impl<'a, T: Array> FusedIterator for Drain<'a, T> {} + +impl<'a, T: 'a + Array> Drop for Drain<'a, T> { fn drop(&mut self) { - // Destroy the remaining elements. - for _ in self.by_ref() {} + self.for_each(drop); + + if self.tail_len > 0 { + unsafe { + let source_vec = self.vec.as_mut(); + + // memmove back untouched tail, update to new length + let start = source_vec.len(); + let tail = self.tail_start; + if tail != start { + let src = source_vec.as_ptr().add(tail); + let dst = source_vec.as_mut_ptr().add(start); + ptr::copy(src, dst, self.tail_len); + } + source_vec.set_len(start + self.tail_len); + } + } } } @@ -324,15 +299,15 @@ enum SmallVecData { impl SmallVecData { #[inline] unsafe fn inline(&self) -> *const A::Item { - match *self { - SmallVecData::Inline(ref a) => a.as_ptr() as *const A::Item, + match self { + SmallVecData::Inline(a) => a.as_ptr() as *const A::Item, _ => debug_unreachable!(), } } #[inline] unsafe fn inline_mut(&mut self) -> *mut A::Item { - match *self { - SmallVecData::Inline(ref mut a) => a.as_mut_ptr() as *mut A::Item, + match self { + SmallVecData::Inline(a) => a.as_mut_ptr() as *mut A::Item, _ => debug_unreachable!(), } } @@ -349,15 +324,15 @@ impl SmallVecData { } #[inline] unsafe fn heap(&self) -> (*mut A::Item, usize) { - match *self { - SmallVecData::Heap(data) => data, + match self { + SmallVecData::Heap(data) => *data, _ => debug_unreachable!(), } } #[inline] unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { - match *self { - SmallVecData::Heap(ref mut data) => data, + match self { + SmallVecData::Heap(data) => data, _ => debug_unreachable!(), } } @@ -511,7 +486,7 @@ impl SmallVec { #[inline] pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { assert!(len <= A::size()); - unsafe { SmallVec::from_buf_and_len_unchecked(buf, len) } + unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } } /// Constructs a new `SmallVec` on the stack from an `A` without @@ -520,23 +495,23 @@ impl SmallVec { /// /// ```rust /// use smallvec::SmallVec; + /// use std::mem::MaybeUninit; /// /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; /// let small_vec: SmallVec<_> = unsafe { - /// SmallVec::from_buf_and_len_unchecked(buf, 5) + /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) /// }; /// /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); /// ``` #[inline] - pub unsafe fn from_buf_and_len_unchecked(buf: A, len: usize) -> SmallVec { + pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { SmallVec { capacity: len, - data: SmallVecData::from_inline(MaybeUninit::new(buf)), + data: SmallVecData::from_inline(buf), } } - /// Sets the length of a vector. /// /// This will explicitly set the size of the vector, without actually @@ -604,18 +579,50 @@ impl SmallVec { self.capacity > A::size() } - /// Empty the vector and return an iterator over its former contents. - pub fn drain(&mut self) -> Drain { + /// Creates a draining iterator that removes the specified range in the vector + /// and yields the removed items. + /// + /// Note 1: The element range is removed even if the iterator is only + /// partially consumed or not consumed at all. + /// + /// Note 2: It is unspecified how many elements are removed from the vector + /// if the `Drain` value is leaked. + /// + /// # Panics + /// + /// Panics if the starting point is greater than the end point or if + /// the end point is greater than the length of the vector. + pub fn drain(&mut self, range: R) -> Drain<'_, A> + where + R: RangeBounds, + { + use core::ops::Bound::*; + + let len = self.len(); + let start = match range.start_bound() { + Included(&n) => n, + Excluded(&n) => n + 1, + Unbounded => 0, + }; + let end = match range.end_bound() { + Included(&n) => n + 1, + Excluded(&n) => n, + Unbounded => len, + }; + + assert!(start <= end); + assert!(end <= len); + unsafe { - let ptr = self.as_mut_ptr(); + self.set_len(start); - let current_len = self.len(); - self.set_len(0); - - let slice = slice::from_raw_parts_mut(ptr, current_len); + let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); Drain { - iter: slice.iter_mut(), + tail_start: end, + tail_len: len - end, + iter: range_slice.iter(), + vec: NonNull::from(self), } } } @@ -630,7 +637,7 @@ impl SmallVec { } let (ptr, len_ptr, _) = self.triple_mut(); *len_ptr = len + 1; - ptr::write(ptr.offset(len as isize), value); + ptr::write(ptr.add(len), value); } } @@ -644,7 +651,7 @@ impl SmallVec { } let last_index = *len_ptr - 1; *len_ptr = last_index; - Some(ptr::read(ptr.offset(last_index as isize))) + Some(ptr::read(ptr.add(last_index))) } } @@ -694,9 +701,10 @@ impl SmallVec { // from callers like insert() let (_, &mut len, cap) = self.triple_mut(); if cap - len < additional { - let new_cap = len.checked_add(additional). - and_then(usize::checked_next_power_of_two). - unwrap_or(usize::max_value()); + let new_cap = len + .checked_add(additional) + .and_then(usize::checked_next_power_of_two) + .unwrap_or(usize::max_value()); self.grow(new_cap); } } @@ -749,7 +757,7 @@ impl SmallVec { while len < *len_ptr { let last_index = *len_ptr - 1; *len_ptr = last_index; - ptr::drop_in_place(ptr.offset(last_index as isize)); + ptr::drop_in_place(ptr.add(last_index)); } } } @@ -777,7 +785,8 @@ impl SmallVec { pub fn swap_remove(&mut self, index: usize) -> A::Item { let len = self.len(); self.swap(len - 1, index); - self.pop().unwrap_or_else(|| unsafe { unreachable() }) + self.pop() + .unwrap_or_else(|| unsafe { unreachable_unchecked() }) } /// Remove all elements from the vector. @@ -796,9 +805,9 @@ impl SmallVec { let len = *len_ptr; assert!(index < len); *len_ptr = len - 1; - ptr = ptr.offset(index as isize); + ptr = ptr.add(index); let item = ptr::read(ptr); - ptr::copy(ptr.offset(1), ptr, len - index - 1); + ptr::copy(ptr.add(1), ptr, len - index - 1); item } } @@ -814,52 +823,56 @@ impl SmallVec { let len = *len_ptr; assert!(index <= len); *len_ptr = len + 1; - ptr = ptr.offset(index as isize); - ptr::copy(ptr, ptr.offset(1), len - index); + ptr = ptr.add(index); + ptr::copy(ptr, ptr.add(1), len - index); ptr::write(ptr, element); } } /// Insert multiple elements at position `index`, shifting all following elements toward the /// back. - pub fn insert_many>(&mut self, index: usize, iterable: I) { + pub fn insert_many>(&mut self, index: usize, iterable: I) { let iter = iterable.into_iter(); if index == self.len() { return self.extend(iter); } let (lower_size_bound, _) = iter.size_hint(); - assert!(lower_size_bound <= std::isize::MAX as usize); // Ensure offset is indexable - assert!(index + lower_size_bound >= index); // Protect against overflow + assert!(lower_size_bound <= core::isize::MAX as usize); // Ensure offset is indexable + assert!(index + lower_size_bound >= index); // Protect against overflow self.reserve(lower_size_bound); unsafe { let old_len = self.len(); assert!(index <= old_len); - let mut ptr = self.as_mut_ptr().offset(index as isize); + let mut ptr = self.as_mut_ptr().add(index); // Move the trailing elements. - ptr::copy(ptr, ptr.offset(lower_size_bound as isize), old_len - index); + ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index); // In case the iterator panics, don't double-drop the items we just copied above. self.set_len(index); let mut num_added = 0; for element in iter { - let mut cur = ptr.offset(num_added as isize); + let mut cur = ptr.add(num_added); if num_added >= lower_size_bound { // Iterator provided more elements than the hint. Move trailing items again. self.reserve(1); - ptr = self.as_mut_ptr().offset(index as isize); - cur = ptr.offset(num_added as isize); - ptr::copy(cur, cur.offset(1), old_len - index); + ptr = self.as_mut_ptr().add(index); + cur = ptr.add(num_added); + ptr::copy(cur, cur.add(1), old_len - index); } ptr::write(cur, element); num_added += 1; } if num_added < lower_size_bound { // Iterator provided fewer elements than the hint - ptr::copy(ptr.offset(lower_size_bound as isize), ptr.offset(num_added as isize), old_len - index); + ptr::copy( + ptr.add(lower_size_bound), + ptr.add(num_added), + old_len - index, + ); } self.set_len(old_len + num_added); @@ -881,6 +894,14 @@ impl SmallVec { } } + /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the `SmallVec` has already spilled + /// onto the heap. + /// + /// Note that this will drop any excess capacity. + pub fn into_boxed_slice(self) -> Box<[A::Item]> { + self.into_vec().into_boxed_slice() + } + /// Convert the SmallVec into an `A` if possible. Otherwise return `Err(Self)`. /// /// This method returns `Err(Self)` if the SmallVec is too short (and the `A` contains uninitialized elements), @@ -916,13 +937,17 @@ impl SmallVec { } /// Removes consecutive duplicate elements. - pub fn dedup(&mut self) where A::Item: PartialEq { + pub fn dedup(&mut self) + where + A::Item: PartialEq, + { self.dedup_by(|a, b| a == b); } /// Removes consecutive duplicate elements using the given equality relation. pub fn dedup_by(&mut self, mut same_bucket: F) - where F: FnMut(&mut A::Item, &mut A::Item) -> bool + where + F: FnMut(&mut A::Item, &mut A::Item) -> bool, { // See the implementation of Vec::dedup_by in the // standard library for an explanation of this algorithm. @@ -936,11 +961,11 @@ impl SmallVec { unsafe { for r in 1..len { - let p_r = ptr.offset(r as isize); - let p_wm1 = ptr.offset((w - 1) as isize); + let p_r = ptr.add(r); + let p_wm1 = ptr.add(w - 1); if !same_bucket(&mut *p_r, &mut *p_wm1) { if r != w { - let p_w = p_wm1.offset(1); + let p_w = p_wm1.add(1); mem::swap(&mut *p_r, &mut *p_w); } w += 1; @@ -953,8 +978,9 @@ impl SmallVec { /// Removes consecutive elements that map to the same key. pub fn dedup_by_key(&mut self, mut key: F) - where F: FnMut(&mut A::Item) -> K, - K: PartialEq + where + F: FnMut(&mut A::Item) -> K, + K: PartialEq, { self.dedup_by(|a, b| key(a) == key(b)); } @@ -1017,8 +1043,8 @@ impl SmallVec { /// // writing into the old `SmallVec`'s inline storage on the /// // stack. /// assert!(spilled); - /// for i in 0..len as isize { - /// ptr::write(p.offset(i), 4 + i); + /// for i in 0..len { + /// ptr::write(p.add(i), 4 + i); /// } /// /// // Put everything back together into a SmallVec with a different @@ -1027,11 +1053,7 @@ impl SmallVec { /// assert_eq!(&*rebuilt, &[4, 5, 6]); /// } /// } - pub unsafe fn from_raw_parts( - ptr: *mut A::Item, - length: usize, - capacity: usize, - ) -> SmallVec { + pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec { assert!(capacity > A::size()); SmallVec { capacity, @@ -1040,7 +1062,10 @@ impl SmallVec { } } -impl SmallVec where A::Item: Copy { +impl SmallVec +where + A::Item: Copy, +{ /// Copy the elements from a slice into a new `SmallVec`. /// /// For slices of `Copy` types, this is more efficient than `SmallVec::from(slice)`. @@ -1057,7 +1082,7 @@ impl SmallVec where A::Item: Copy { len, ); data - }) + }), } } else { let mut b = slice.to_vec(); @@ -1082,8 +1107,8 @@ impl SmallVec where A::Item: Copy { unsafe { let slice_ptr = slice.as_ptr(); - let ptr = self.as_mut_ptr().offset(index as isize); - ptr::copy(ptr, ptr.offset(slice.len() as isize), len - index); + let ptr = self.as_mut_ptr().add(index); + ptr::copy(ptr, ptr.add(slice.len()), len - index); ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); self.set_len(len + slice.len()); } @@ -1099,7 +1124,10 @@ impl SmallVec where A::Item: Copy { } } -impl SmallVec where A::Item: Clone { +impl SmallVec +where + A::Item: Clone, +{ /// Resizes the vector so that its length is equal to `len`. /// /// If `len` is less than the current length, the vector simply truncated. @@ -1132,8 +1160,8 @@ impl SmallVec where A::Item: Clone { let (ptr, len_ptr, _) = v.triple_mut(); let mut local_len = SetLenOnDrop::new(len_ptr); - for i in 0..n as isize { - ::std::ptr::write(ptr.offset(i), elem.clone()); + for i in 0..n { + ::core::ptr::write(ptr.add(i), elem.clone()); local_len.increment_len(1); } } @@ -1191,7 +1219,7 @@ impl BorrowMut<[A::Item]> for SmallVec { } } -#[cfg(feature = "std")] +#[cfg(feature = "write")] impl> io::Write for SmallVec { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result { @@ -1212,7 +1240,10 @@ impl> io::Write for SmallVec { } #[cfg(feature = "serde")] -impl Serialize for SmallVec where A::Item: Serialize { +impl Serialize for SmallVec +where + A::Item: Serialize, +{ fn serialize(&self, serializer: S) -> Result { let mut state = serializer.serialize_seq(Some(self.len()))?; for item in self { @@ -1223,30 +1254,36 @@ impl Serialize for SmallVec where A::Item: Serialize { } #[cfg(feature = "serde")] -impl<'de, A: Array> Deserialize<'de> for SmallVec where A::Item: Deserialize<'de> { +impl<'de, A: Array> Deserialize<'de> for SmallVec +where + A::Item: Deserialize<'de>, +{ fn deserialize>(deserializer: D) -> Result { - deserializer.deserialize_seq(SmallVecVisitor{phantom: PhantomData}) + deserializer.deserialize_seq(SmallVecVisitor { + phantom: PhantomData, + }) } } #[cfg(feature = "serde")] struct SmallVecVisitor { - phantom: PhantomData + phantom: PhantomData, } #[cfg(feature = "serde")] impl<'de, A: Array> Visitor<'de> for SmallVecVisitor -where A::Item: Deserialize<'de>, +where + A::Item: Deserialize<'de>, { type Value = SmallVec; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a sequence") } fn visit_seq(self, mut seq: B) -> Result - where - B: SeqAccess<'de>, + where + B: SeqAccess<'de>, { let len = seq.size_hint().unwrap_or(0); let mut values = SmallVec::with_capacity(len); @@ -1259,7 +1296,6 @@ where A::Item: Deserialize<'de>, } } - #[cfg(feature = "specialization")] trait SpecFrom { fn spec_from(slice: S) -> SmallVec; @@ -1269,18 +1305,24 @@ trait SpecFrom { mod specialization; #[cfg(feature = "specialization")] -impl<'a, A: Array> SpecFrom for SmallVec where A::Item: Copy { +impl<'a, A: Array> SpecFrom for SmallVec +where + A::Item: Copy, +{ #[inline] fn spec_from(slice: &'a [A::Item]) -> SmallVec { SmallVec::from_slice(slice) } } -impl<'a, A: Array> From<&'a [A::Item]> for SmallVec where A::Item: Clone { +impl<'a, A: Array> From<&'a [A::Item]> for SmallVec +where + A::Item: Clone, +{ #[cfg(not(feature = "specialization"))] #[inline] fn from(slice: &'a [A::Item]) -> SmallVec { - slice.into_iter().cloned().collect() + slice.iter().cloned().collect() } #[cfg(feature = "specialization")] @@ -1304,47 +1346,31 @@ impl From for SmallVec { } } -macro_rules! impl_index { - ($index_type: ty, $output_type: ty) => { - impl ops::Index<$index_type> for SmallVec { - type Output = $output_type; - #[inline] - fn index(&self, index: $index_type) -> &$output_type { - &(&**self)[index] - } - } +impl> ops::Index for SmallVec { + type Output = I::Output; - impl ops::IndexMut<$index_type> for SmallVec { - #[inline] - fn index_mut(&mut self, index: $index_type) -> &mut $output_type { - &mut (&mut **self)[index] - } - } + fn index(&self, index: I) -> &I::Output { + &(**self)[index] } } -impl_index!(usize, A::Item); -impl_index!(ops::Range, [A::Item]); -impl_index!(ops::RangeFrom, [A::Item]); -impl_index!(ops::RangeTo, [A::Item]); -impl_index!(ops::RangeFull, [A::Item]); +impl> ops::IndexMut for SmallVec { + fn index_mut(&mut self, index: I) -> &mut I::Output { + &mut (&mut **self)[index] + } +} -impl ExtendFromSlice for SmallVec where A::Item: Copy { +impl ExtendFromSlice for SmallVec +where + A::Item: Copy, +{ fn extend_from_slice(&mut self, other: &[A::Item]) { SmallVec::extend_from_slice(self, other) } } -#[allow(deprecated)] -impl VecLike for SmallVec { - #[inline] - fn push(&mut self, value: A::Item) { - SmallVec::push(self, value); - } -} - impl FromIterator for SmallVec { - fn from_iter>(iterable: I) -> SmallVec { + fn from_iter>(iterable: I) -> SmallVec { let mut v = SmallVec::new(); v.extend(iterable); v @@ -1352,7 +1378,7 @@ impl FromIterator for SmallVec { } impl Extend for SmallVec { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { let mut iter = iterable.into_iter(); let (lower_size_bound, _) = iter.size_hint(); self.reserve(lower_size_bound); @@ -1362,7 +1388,7 @@ impl Extend for SmallVec { let mut len = SetLenOnDrop::new(len_ptr); while len.get() < cap { if let Some(out) = iter.next() { - ptr::write(ptr.offset(len.get() as isize), out); + ptr::write(ptr.add(len.get()), out); len.increment_len(1); } else { return; @@ -1376,8 +1402,11 @@ impl Extend for SmallVec { } } -impl fmt::Debug for SmallVec where A::Item: fmt::Debug { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +impl fmt::Debug for SmallVec +where + A::Item: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.iter()).finish() } } @@ -1417,7 +1446,10 @@ impl Drop for SmallVec { } } -impl Clone for SmallVec where A::Item: Clone { +impl Clone for SmallVec +where + A::Item: Clone, +{ fn clone(&self) -> SmallVec { let mut new_vector = SmallVec::with_capacity(self.len()); for element in self.iter() { @@ -1428,30 +1460,41 @@ impl Clone for SmallVec where A::Item: Clone { } impl PartialEq> for SmallVec - where A::Item: PartialEq { +where + A::Item: PartialEq, +{ #[inline] - fn eq(&self, other: &SmallVec) -> bool { self[..] == other[..] } - #[inline] - fn ne(&self, other: &SmallVec) -> bool { self[..] != other[..] } + fn eq(&self, other: &SmallVec) -> bool { + self[..] == other[..] + } } impl Eq for SmallVec where A::Item: Eq {} -impl PartialOrd for SmallVec where A::Item: PartialOrd { +impl PartialOrd for SmallVec +where + A::Item: PartialOrd, +{ #[inline] fn partial_cmp(&self, other: &SmallVec) -> Option { PartialOrd::partial_cmp(&**self, &**other) } } -impl Ord for SmallVec where A::Item: Ord { +impl Ord for SmallVec +where + A::Item: Ord, +{ #[inline] fn cmp(&self, other: &SmallVec) -> cmp::Ordering { Ord::cmp(&**self, &**other) } } -impl Hash for SmallVec where A::Item: Hash { +impl Hash for SmallVec +where + A::Item: Hash, +{ fn hash(&self, state: &mut H) { (**self).hash(state) } @@ -1470,9 +1513,27 @@ pub struct IntoIter { end: usize, } +impl fmt::Debug for IntoIter +where + A::Item: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("IntoIter").field(&self.as_slice()).finish() + } +} + +impl Clone for IntoIter +where + A::Item: Clone, +{ + fn clone(&self) -> IntoIter { + SmallVec::from(self.as_slice()).into_iter() + } +} + impl Drop for IntoIter { fn drop(&mut self) { - for _ in self { } + for _ in self {} } } @@ -1483,12 +1544,11 @@ impl Iterator for IntoIter { fn next(&mut self) -> Option { if self.current == self.end { None - } - else { + } else { unsafe { - let current = self.current as isize; + let current = self.current; self.current += 1; - Some(ptr::read(self.data.as_ptr().offset(current))) + Some(ptr::read(self.data.as_ptr().add(current))) } } } @@ -1505,17 +1565,31 @@ impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option { if self.current == self.end { None - } - else { + } else { unsafe { self.end -= 1; - Some(ptr::read(self.data.as_ptr().offset(self.end as isize))) + Some(ptr::read(self.data.as_ptr().add(self.end))) } } } } -impl ExactSizeIterator for IntoIter { } +impl ExactSizeIterator for IntoIter {} +impl FusedIterator for IntoIter {} + +impl IntoIter { + /// Returns the remaining items of this iterator as a slice. + pub fn as_slice(&self) -> &[A::Item] { + let len = self.end - self.current; + unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) } + } + + /// Returns the remaining items of this iterator as a mutable slice. + pub fn as_mut_slice(&mut self) -> &mut [A::Item] { + let len = self.end - self.current; + unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) } + } +} impl IntoIterator for SmallVec { type IntoIter = IntoIter; @@ -1556,10 +1630,6 @@ pub unsafe trait Array { type Item; /// Returns the number of items the array can hold. fn size() -> usize; - /// Returns a pointer to the first element of the array. - fn ptr(&self) -> *const Self::Item; - /// Returns a mutable pointer to the first element of the array. - fn ptr_mut(&mut self) -> *mut Self::Item; } /// Set the length of the vec when the `SetLenOnDrop` value goes out of scope. @@ -1573,7 +1643,10 @@ struct SetLenOnDrop<'a> { impl<'a> SetLenOnDrop<'a> { #[inline] fn new(len: &'a mut usize) -> Self { - SetLenOnDrop { local_len: *len, len: len } + SetLenOnDrop { + local_len: *len, + len, + } } #[inline] @@ -1600,35 +1673,27 @@ macro_rules! impl_array( unsafe impl Array for [T; $size] { type Item = T; fn size() -> usize { $size } - fn ptr(&self) -> *const T { unimplemented!() } - fn ptr_mut(&mut self) -> *mut T { unimplemented!() } } )+ } ); -impl_array!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32, 36, - 0x40, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000, 0x2000, 0x4000, 0x8000, - 0x10000, 0x20000, 0x40000, 0x80000, 0x100000); +impl_array!( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 32, 36, 0x40, 0x60, 0x80, + 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000, 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, + 0x40000, 0x60000, 0x80000, 0x10_0000 +); #[cfg(test)] mod tests { - use SmallVec; + use crate::SmallVec; use std::iter::FromIterator; - #[cfg(feature = "std")] - use std::borrow::ToOwned; - #[cfg(not(feature = "std"))] use alloc::borrow::ToOwned; - #[cfg(feature = "std")] - use std::rc::Rc; - #[cfg(not(feature = "std"))] - use alloc::rc::Rc; - #[cfg(not(feature = "std"))] use alloc::boxed::Box; - #[cfg(not(feature = "std"))] - use alloc::vec::Vec; + use alloc::rc::Rc; + use alloc::{vec, vec::Vec}; #[test] pub fn test_zero() { @@ -1646,10 +1711,7 @@ mod tests { let mut v = SmallVec::<[_; 16]>::new(); v.push("hello".to_owned()); v.push("there".to_owned()); - assert_eq!(&*v, &[ - "hello".to_owned(), - "there".to_owned(), - ][..]); + assert_eq!(&*v, &["hello".to_owned(), "there".to_owned(),][..]); } #[test] @@ -1661,12 +1723,15 @@ mod tests { v.push("burma".to_owned()); assert_eq!(v[0], "hello"); v.push("shave".to_owned()); - assert_eq!(&*v, &[ - "hello".to_owned(), - "there".to_owned(), - "burma".to_owned(), - "shave".to_owned(), - ][..]); + assert_eq!( + &*v, + &[ + "hello".to_owned(), + "there".to_owned(), + "burma".to_owned(), + "shave".to_owned(), + ][..] + ); } #[test] @@ -1680,16 +1745,19 @@ mod tests { v.push("there".to_owned()); v.push("burma".to_owned()); v.push("shave".to_owned()); - assert_eq!(&*v, &[ - "hello".to_owned(), - "there".to_owned(), - "burma".to_owned(), - "shave".to_owned(), - "hello".to_owned(), - "there".to_owned(), - "burma".to_owned(), - "shave".to_owned(), - ][..]); + assert_eq!( + &*v, + &[ + "hello".to_owned(), + "there".to_owned(), + "burma".to_owned(), + "shave".to_owned(), + "hello".to_owned(), + "there".to_owned(), + "burma".to_owned(), + "shave".to_owned(), + ][..] + ); } /// https://github.com/servo/rust-smallvec/issues/4 @@ -1721,26 +1789,36 @@ mod tests { fn drain() { let mut v: SmallVec<[u8; 2]> = SmallVec::new(); v.push(3); - assert_eq!(v.drain().collect::>(), &[3]); + assert_eq!(v.drain(..).collect::>(), &[3]); // spilling the vec v.push(3); v.push(4); v.push(5); - assert_eq!(v.drain().collect::>(), &[3, 4, 5]); + let old_capacity = v.capacity(); + assert_eq!(v.drain(1..).collect::>(), &[4, 5]); + // drain should not change the capacity + assert_eq!(v.capacity(), old_capacity); } #[test] fn drain_rev() { let mut v: SmallVec<[u8; 2]> = SmallVec::new(); v.push(3); - assert_eq!(v.drain().rev().collect::>(), &[3]); + assert_eq!(v.drain(..).rev().collect::>(), &[3]); // spilling the vec v.push(3); v.push(4); v.push(5); - assert_eq!(v.drain().rev().collect::>(), &[5, 4, 3]); + assert_eq!(v.drain(..).rev().collect::>(), &[5, 4, 3]); + } + + #[test] + fn drain_forget() { + let mut v: SmallVec<[u8; 1]> = smallvec![0, 1, 2, 3, 4, 5, 6, 7]; + std::mem::forget(v.drain(2..5)); + assert_eq!(v.len(), 2); } #[test] @@ -1785,7 +1863,7 @@ mod tests { { let cell = Cell::new(0); - let mut v: SmallVec<[DropCounter; 2]> = SmallVec::new(); + let mut v: SmallVec<[DropCounter<'_>; 2]> = SmallVec::new(); v.push(DropCounter(&cell)); v.into_iter(); assert_eq!(cell.get(), 1); @@ -1793,7 +1871,7 @@ mod tests { { let cell = Cell::new(0); - let mut v: SmallVec<[DropCounter; 2]> = SmallVec::new(); + let mut v: SmallVec<[DropCounter<'_>; 2]> = SmallVec::new(); v.push(DropCounter(&cell)); v.push(DropCounter(&cell)); assert!(v.into_iter().next().is_some()); @@ -1802,7 +1880,7 @@ mod tests { { let cell = Cell::new(0); - let mut v: SmallVec<[DropCounter; 2]> = SmallVec::new(); + let mut v: SmallVec<[DropCounter<'_>; 2]> = SmallVec::new(); v.push(DropCounter(&cell)); v.push(DropCounter(&cell)); v.push(DropCounter(&cell)); @@ -1811,7 +1889,7 @@ mod tests { } { let cell = Cell::new(0); - let mut v: SmallVec<[DropCounter; 2]> = SmallVec::new(); + let mut v: SmallVec<[DropCounter<'_>; 2]> = SmallVec::new(); v.push(DropCounter(&cell)); v.push(DropCounter(&cell)); v.push(DropCounter(&cell)); @@ -1870,14 +1948,24 @@ mod tests { } assert_eq!(v.len(), 4); v.insert_many(1, [5, 6].iter().cloned()); - assert_eq!(&v.iter().map(|v| *v).collect::>(), &[0, 5, 6, 1, 2, 3]); + assert_eq!( + &v.iter().map(|v| *v).collect::>(), + &[0, 5, 6, 1, 2, 3] + ); } - struct MockHintIter{x: T, hint: usize} + struct MockHintIter { + x: T, + hint: usize, + } impl Iterator for MockHintIter { type Item = T::Item; - fn next(&mut self) -> Option {self.x.next()} - fn size_hint(&self) -> (usize, Option) {(self.hint, None)} + fn next(&mut self) -> Option { + self.x.next() + } + fn size_hint(&self) -> (usize, Option) { + (self.hint, None) + } } #[test] @@ -1887,8 +1975,17 @@ mod tests { v.push(x); } assert_eq!(v.len(), 4); - v.insert_many(1, MockHintIter{x: [5, 6].iter().cloned(), hint: 5}); - assert_eq!(&v.iter().map(|v| *v).collect::>(), &[0, 5, 6, 1, 2, 3]); + v.insert_many( + 1, + MockHintIter { + x: [5, 6].iter().cloned(), + hint: 5, + }, + ); + assert_eq!( + &v.iter().map(|v| *v).collect::>(), + &[0, 5, 6, 1, 2, 3] + ); } #[test] @@ -1898,16 +1995,24 @@ mod tests { v.push(x); } assert_eq!(v.len(), 4); - v.insert_many(1, MockHintIter{x: [5, 6].iter().cloned(), hint: 1}); - assert_eq!(&v.iter().map(|v| *v).collect::>(), &[0, 5, 6, 1, 2, 3]); + v.insert_many( + 1, + MockHintIter { + x: [5, 6].iter().cloned(), + hint: 1, + }, + ); + assert_eq!( + &v.iter().map(|v| *v).collect::>(), + &[0, 5, 6, 1, 2, 3] + ); } - #[cfg(all(feature = "std", not(miri)))] // Miri currently does not support unwinding #[test] // https://github.com/servo/rust-smallvec/issues/96 fn test_insert_many_panic() { struct PanicOnDoubleDrop { - dropped: Box + dropped: Box, } impl Drop for PanicOnDoubleDrop { @@ -1920,14 +2025,23 @@ mod tests { struct BadIter; impl Iterator for BadIter { type Item = PanicOnDoubleDrop; - fn size_hint(&self) -> (usize, Option) { (1, None) } - fn next(&mut self) -> Option { panic!() } + fn size_hint(&self) -> (usize, Option) { + (1, None) + } + fn next(&mut self) -> Option { + panic!() + } } let mut vec: SmallVec<[PanicOnDoubleDrop; 0]> = vec![ - PanicOnDoubleDrop { dropped: Box::new(false) }, - PanicOnDoubleDrop { dropped: Box::new(false) }, - ].into(); + PanicOnDoubleDrop { + dropped: Box::new(false), + }, + PanicOnDoubleDrop { + dropped: Box::new(false), + }, + ] + .into(); let result = ::std::panic::catch_unwind(move || { vec.insert_many(0, BadIter); }); @@ -1950,7 +2064,10 @@ mod tests { } assert_eq!(v.len(), 4); v.insert_from_slice(1, &[5, 6]); - assert_eq!(&v.iter().map(|v| *v).collect::>(), &[0, 5, 6, 1, 2, 3]); + assert_eq!( + &v.iter().map(|v| *v).collect::>(), + &[0, 5, 6, 1, 2, 3] + ); } #[test] @@ -1961,7 +2078,10 @@ mod tests { } assert_eq!(v.len(), 4); v.extend_from_slice(&[5, 6]); - assert_eq!(&v.iter().map(|v| *v).collect::>(), &[0, 1, 2, 3, 5, 6]); + assert_eq!( + &v.iter().map(|v| *v).collect::>(), + &[0, 1, 2, 3, 5, 6] + ); } #[test] @@ -2020,11 +2140,10 @@ mod tests { assert!(c > b); } - #[cfg(feature = "std")] #[test] fn test_hash() { - use std::hash::Hash; use std::collections::hash_map::DefaultHasher; + use std::hash::Hash; { let mut a: SmallVec<[u32; 2]> = SmallVec::new(); @@ -2128,31 +2247,63 @@ mod tests { #[test] fn test_from_slice() { assert_eq!(&SmallVec::<[u32; 2]>::from_slice(&[1][..])[..], [1]); - assert_eq!(&SmallVec::<[u32; 2]>::from_slice(&[1, 2, 3][..])[..], [1, 2, 3]); + assert_eq!( + &SmallVec::<[u32; 2]>::from_slice(&[1, 2, 3][..])[..], + [1, 2, 3] + ); } #[test] fn test_exact_size_iterator() { let mut vec = SmallVec::<[u32; 2]>::from(&[1, 2, 3][..]); assert_eq!(vec.clone().into_iter().len(), 3); - assert_eq!(vec.drain().len(), 3); + assert_eq!(vec.drain(..2).len(), 2); + assert_eq!(vec.into_iter().len(), 1); } #[test] - #[allow(deprecated)] - fn veclike_deref_slice() { - use super::VecLike; + fn test_into_iter_as_slice() { + let vec = SmallVec::<[u32; 2]>::from(&[1, 2, 3][..]); + let mut iter = vec.clone().into_iter(); + assert_eq!(iter.as_slice(), &[1, 2, 3]); + assert_eq!(iter.as_mut_slice(), &[1, 2, 3]); + iter.next(); + assert_eq!(iter.as_slice(), &[2, 3]); + assert_eq!(iter.as_mut_slice(), &[2, 3]); + iter.next_back(); + assert_eq!(iter.as_slice(), &[2]); + assert_eq!(iter.as_mut_slice(), &[2]); + } - fn test>(vec: &mut T) { - assert!(!vec.is_empty()); - assert_eq!(vec.len(), 3); - - vec.sort(); - assert_eq!(&vec[..], [1, 2, 3]); + #[test] + fn test_into_iter_clone() { + // Test that the cloned iterator yields identical elements and that it owns its own copy + // (i.e. no use after move errors). + let mut iter = SmallVec::<[u8; 2]>::from_iter(0..3).into_iter(); + let mut clone_iter = iter.clone(); + while let Some(x) = iter.next() { + assert_eq!(x, clone_iter.next().unwrap()); } + assert_eq!(clone_iter.next(), None); + } - let mut vec = SmallVec::<[i32; 2]>::from(&[3, 1, 2][..]); - test(&mut vec); + #[test] + fn test_into_iter_clone_partially_consumed_iterator() { + // Test that the cloned iterator only contains the remaining elements of the original iterator. + let mut iter = SmallVec::<[u8; 2]>::from_iter(0..3).into_iter().skip(1); + let mut clone_iter = iter.clone(); + while let Some(x) = iter.next() { + assert_eq!(x, clone_iter.next().unwrap()); + } + assert_eq!(clone_iter.next(), None); + } + + #[test] + fn test_into_iter_clone_empty_smallvec() { + let mut iter = SmallVec::<[u8; 2]>::new().into_iter(); + let mut clone_iter = iter.clone(); + assert_eq!(iter.next(), None); + assert_eq!(clone_iter.next(), None); } #[test] @@ -2283,10 +2434,10 @@ mod tests { assert_eq!(v[..], [1, 0][..]); } - #[cfg(feature = "std")] + #[cfg(feature = "write")] #[test] fn test_write() { - use io::Write; + use std::io::Write; let data = [1, 2, 3, 4, 5]; diff --git a/third_party/cargo/vendor/smallvec-0.6.13/scripts/run_miri.sh b/third_party/cargo/vendor/smallvec-1.2.0/scripts/run_miri.sh similarity index 69% rename from third_party/cargo/vendor/smallvec-0.6.13/scripts/run_miri.sh rename to third_party/cargo/vendor/smallvec-1.2.0/scripts/run_miri.sh index 42f2884..c5e5376 100644 --- a/third_party/cargo/vendor/smallvec-0.6.13/scripts/run_miri.sh +++ b/third_party/cargo/vendor/smallvec-1.2.0/scripts/run_miri.sh @@ -16,6 +16,6 @@ rustup default "$MIRI_NIGHTLY" rustup component add miri cargo miri setup -cargo miri test --verbose -- -- -Zunstable-options --exclude-should-panic -cargo miri test --verbose --features union -- -- -Zunstable-options --exclude-should-panic -cargo miri test --verbose --all-features -- -- -Zunstable-options --exclude-should-panic +cargo miri test --verbose -- -Zmiri-ignore-leaks +cargo miri test --verbose --features union -- -Zmiri-ignore-leaks +cargo miri test --verbose --all-features -- -Zmiri-ignore-leaks diff --git a/third_party/cargo/vendor/smallvec-0.6.13/specialization.rs b/third_party/cargo/vendor/smallvec-1.2.0/specialization.rs similarity index 78% rename from third_party/cargo/vendor/smallvec-0.6.13/specialization.rs rename to third_party/cargo/vendor/smallvec-1.2.0/specialization.rs index 2e7bb1e..658fa77 100644 --- a/third_party/cargo/vendor/smallvec-0.6.13/specialization.rs +++ b/third_party/cargo/vendor/smallvec-1.2.0/specialization.rs @@ -6,9 +6,12 @@ //! Implementations that require `default fn`. -use super::{SpecFrom, SmallVec, Array}; +use super::{Array, SmallVec, SpecFrom}; -impl<'a, A: Array> SpecFrom for SmallVec where A::Item: Clone { +impl<'a, A: Array> SpecFrom for SmallVec +where + A::Item: Clone, +{ #[inline] default fn spec_from(slice: &'a [A::Item]) -> SmallVec { slice.into_iter().cloned().collect() diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/.cargo-checksum.json b/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/.cargo-checksum.json deleted file mode 100644 index 35cba36..0000000 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"CHANGELOG.md":"2da4b714837a96ee9b51dd2dab5cef060ee2a66cca3c7dc752653beb85361520","CONTRIBUTING.md":"b3a310f25decb6d92da06a5db2df1a6d2e2a0843890e07c0bba0d517f83c60bf","Cargo.toml":"a8cdd44813422b28509a7f7675a709b3a27e7419ff94a4a837189eb06e3ec876","LICENSE.txt":"13c0147abe1c7607fde840e2dffcde75bf925aea504b2845b7be4869a5af2afc","README.md":"d9d772954f6bf2a0fbf963fabea93e2e9a5bae9a780ec14d44314842319d7fff","doc_index.html":"383be472c810a6ad7970779a37f2344735a6331ed21bd48de7a38a2772301621","examples/compositor_info.rs":"67611e783ca080082cdca05c72dcfc8c4bae5cebef107539b9b6e5438bb6a31e","examples/image_viewer.rs":"4a18e433296211e0022adbff1e966d19728e75a8faa4ae1fd431804629f03735","examples/kbd_input.rs":"a1656fef18fc07fbfd606fbf5dc4178e9da183789efae1bfd08f7cd9048f95db","examples/pointer_input.rs":"72c4d9c391b29bc94d29c8de2aa2cd76cd8db60ca13175d1f56f860c19113a09","examples/selection.rs":"e34fbdf99aed737fa071896b1671a5323d68b825ee8603a0e0b24325f4a60645","src/data_device/data_device.rs":"6951652791a8735e4feb314459030fae39e42635ac2f53bd08614db3f7382d6d","src/data_device/data_offer.rs":"9f8c84b06dd4c10d2412483e8efad9a6ac66e60e8a5bac3d07c0dd0af6cd3187","src/data_device/data_source.rs":"a00685604358808658143ef6c6b46cd9e4f64e3fc51fb3288809b5a80b7967c2","src/data_device/mod.rs":"6794d7443820d91144c957d9d09551f39624e33e337574a1c102b5aeea14c987","src/env.rs":"0cbd7b513387e18fe1a4d10a0cb64baf45cab92c401dbd0cdb2d8a3a5407be2d","src/keyboard/ffi.rs":"c35e40b4dab805dc3f6ae918497d04a2085958d41f27731f06b9dc4701e04fdb","src/keyboard/keysyms.rs":"c704c3b45ad18640ed906d0c14359aaea8afb49553e112cdef9f766de4f733f7","src/keyboard/mod.rs":"3494fedf5a49e830d9b622a825762f37dc50add68d980ef390814ecda37267ee","src/lib.rs":"cde040a0e905671c718db9f3390bb77dddf0c9db809c257a597442a7ba0152a4","src/output.rs":"b5268f6f3b7041b09844f900d8deedd2c2de51d9de3d17fcb7ecbf4faa9863e8","src/pointer/mod.rs":"95fc20099c165b401b7733a2ebbb9c33ca11a8aa0482d35e90bc745b14dacd28","src/pointer/theme.rs":"d13770347720e853f9ebe248aadca160ab77da0f14309941d440bbc18275504d","src/shell/mod.rs":"a2601abec2e14f12056ffba4e1d3c8474086e1652381f8a8948503599cdc8e90","src/shell/wl.rs":"ea83db9ccd9579ea423507e76ad9c656facb8e1bd172c6eafc99694245a57e6d","src/shell/xdg.rs":"fda40c7731dcafc481c237b3a2f5f83c62ce99bbea9be8efa53cfe7b17bee8bd","src/shell/zxdg.rs":"af3796a89dc4634e723da59d991162b0720527f55a7f45680e1ca80929106674","src/surface.rs":"c5d31a0ce6662758674e02756066e9939eecc98f20a26cbf7b1c0b49d13ca77c","src/utils/mempool.rs":"eb473a2d7dc6d41b88b53588afd31913e2ab1ad4a1b2679347bda1dd3eada9c7","src/utils/mod.rs":"0fd707ee8c6f7747910e7fa4c4e8b9eeb829eed250394175b814d6348bf131e9","src/window/basic_frame.rs":"7a051e1699847f0543e5283f3379e2b196a63e165c56ea4665983c19a7b96e23","src/window/concept_frame.rs":"96ec2f6959a00c5715d2ffb64242ddb265a7a9ebe89f7781283f266511fff316","src/window/mod.rs":"7c84ea00b415dd4f0b7a032bc1f8f10d5149323584dea8b8131522767ead1323","travis_install_wayland.sh":"02ba67cbc481d65b75440d04e059ab00fbd59bc1821d6206d28c6f4499e3368a","update_keysyms.sh":"6ef4695d6f0a083915e07bc92aae7757049ef507da140c5dc4b7a87d83090fa7"},"package":"2ccb8c57049b2a34d2cc2b203fa785020ba0129d31920ef0d317430adaf748fa"} \ No newline at end of file diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/.cargo-checksum.json b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/.cargo-checksum.json new file mode 100644 index 0000000..5119e20 --- /dev/null +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"28953ea7d5e9bdba87795b6ad32b46c20792efb166969493fc247f2a66d3914e","CONTRIBUTING.md":"b3a310f25decb6d92da06a5db2df1a6d2e2a0843890e07c0bba0d517f83c60bf","Cargo.lock":"2c0ffc691bf719e13bb6ece574e9cbf6c70cf8768b8d055a5285e5500cdb46e7","Cargo.toml":"b7a289d04da3a706056adfb5a3825ca1b44a329116a52e27601f008e8cd343e5","LICENSE.txt":"13c0147abe1c7607fde840e2dffcde75bf925aea504b2845b7be4869a5af2afc","README.md":"d9d772954f6bf2a0fbf963fabea93e2e9a5bae9a780ec14d44314842319d7fff","doc_index.html":"383be472c810a6ad7970779a37f2344735a6331ed21bd48de7a38a2772301621","examples/compositor_info.rs":"67611e783ca080082cdca05c72dcfc8c4bae5cebef107539b9b6e5438bb6a31e","examples/image_viewer.rs":"debab6e5b945ea99336113615a119223fa976cd5298592b4d40ac5a84adcb8e2","examples/kbd_input.rs":"af25c6064237c7a99a929569f587134c1ea2ac37ae7525d3de68f0a4ad60959e","examples/pointer_input.rs":"1af1a0ae902a2f477d454a1de9acfa406ddfadbc8a7b0a92d5352b21faae881f","examples/selection.rs":"8a0c41e23433c970bd7c73dd0ec3a9eaf58c8e22f147f8ba34b869ea448e5087","examples/themed_frame.rs":"2f3eda8d5a01cbe2e90d5308fff9a72fcd73d7ddba36b9aaaaec951e2ba8c86c","src/data_device/data_device.rs":"f3dea210271c81f038c53b5fd3f9030cf35a7b40fe6f0518d38860e8d22c6ac3","src/data_device/data_offer.rs":"cba25f479f0c48783fa14d1593c6c17a5311afef2f3e2553d775a49ab9b410d2","src/data_device/data_source.rs":"6a06ec7d5cfce76a6a802d505affc0128e9822e93ba982dd8b6dc0886e24791e","src/data_device/mod.rs":"6794d7443820d91144c957d9d09551f39624e33e337574a1c102b5aeea14c987","src/env.rs":"68409099b14112fce1c463280136ec31f405fe35889f212180899a0a5425db1f","src/keyboard/ffi.rs":"c35e40b4dab805dc3f6ae918497d04a2085958d41f27731f06b9dc4701e04fdb","src/keyboard/keysyms.rs":"c704c3b45ad18640ed906d0c14359aaea8afb49553e112cdef9f766de4f733f7","src/keyboard/mod.rs":"de64e2b4f24b1ab839b7f56b8be1facd56471a9ceb1b06eff68ca69d6315d550","src/lib.rs":"20940fbcad4735ee92eb881780d2335687027f69173f152da50be8601a428ec9","src/output.rs":"a20301bd08864472da5221784c79362b561eb297c0ee9d8975068c008a3b2bfe","src/pointer/mod.rs":"998a1ebc47d6e797349dc65d9bd5adc4a53a99d6e3201148bb935601edcb9c48","src/pointer/theme.rs":"8e2987bfde7c7ab6ce44b73edc8d71c22e5fe308f6f88312cec5e01d4b5ff5e2","src/shell/mod.rs":"7c7e144937133828642f8064d68a13eaae2d7f08c3cbdbca4eb274db8f3d0318","src/shell/wl.rs":"0cd5988ed3b4ae2f799551fd317c3e914cb6221b807cb87c7a8dbb95467cd680","src/shell/xdg.rs":"4da6cf7bad5a80b34e680bb764ed5c9eb8320fea45dd4f8ab827b5f926a3c9e5","src/shell/zxdg.rs":"cc3a84b7803e8f820f0160048e3cdffa3b270eaa3a36a1d02f04a6668ec85020","src/surface.rs":"44613b43ee97dcb7b3d9a2007d369a4f14a8c178837adb21589222defcd115e3","src/utils/mempool.rs":"f72c0d400165160f934826dccf989d7a7f9340ee6da6cccdca7eee236573bc90","src/utils/mod.rs":"0fd707ee8c6f7747910e7fa4c4e8b9eeb829eed250394175b814d6348bf131e9","src/window/basic_frame.rs":"23055bf62ee299080584c38f8c53ec48bfc10e7eedef33861f522c93ba3d8dfe","src/window/concept_frame.rs":"14d6d0dacfec2d00b1e1d7784a1473c9932f005de3519aad45aea23830f38c3b","src/window/mod.rs":"996ac3864a2e0b0e08f364827e84bc908e7db418061a59716e7fa348be3d2697","travis_install_wayland.sh":"02ba67cbc481d65b75440d04e059ab00fbd59bc1821d6206d28c6f4499e3368a","update_keysyms.sh":"6ef4695d6f0a083915e07bc92aae7757049ef507da140c5dc4b7a87d83090fa7"},"package":"421c8dc7acf5cb205b88160f8b4cc2c5cfabe210e43b2f80f009f4c1ef910f1d"} \ No newline at end of file diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/BUILD b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/BUILD similarity index 84% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/BUILD rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/BUILD index 6dbdab4..89a6d2d 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/BUILD +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/BUILD @@ -42,15 +42,15 @@ rust_library( "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", "//third_party/cargo/vendor/memmap-0.7.0:memmap", "//third_party/cargo/vendor/nix-0.14.1:nix", - "//third_party/cargo/vendor/wayland-client-0.21.13:wayland_client", - "//third_party/cargo/vendor/wayland-commons-0.21.13:wayland_commons", - "//third_party/cargo/vendor/wayland-protocols-0.21.13:wayland_protocols", + "//third_party/cargo/vendor/wayland-client-0.23.6:wayland_client", + "//third_party/cargo/vendor/wayland-protocols-0.23.6:wayland_protocols", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.4.6", + version = "0.6.6", crate_features = [ ], ) +# Unsupported target "themed_frame" with type "example" omitted diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/CHANGELOG.md b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/CHANGELOG.md similarity index 70% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/CHANGELOG.md rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/CHANGELOG.md index 1a7e20b..dc8a87f 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/CHANGELOG.md +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/CHANGELOG.md @@ -2,9 +2,67 @@ ## Unreleased +## 0.6.6 -- 2020-02-11 + +#### Bugfixes + +- Damaging decorations buffers in wrong coordinates +- Fix `HiDPI` cursor bounding box + +## 0.6.5 -- 2020-02-07 + +#### Bugfixes + +- `set_decorations` arbitrary changing SSD mode to CSD +- It is now possible to check the DPI factor of a surface from an other thread + +#### Additions + +- The `pointer` theming will now read the `XCURSOR_THEME` and `XCURSOR_SIZE` environment + variables to figure the default theme +- `pointer` theming utilities now provide a way to set cursor scale factor +- `HiDPI` scaling for decorations + +## 0.6.4 -- 2019-08-27 + +#### Bugfixes + +- Keyboard input breaking when `LC_ALL`, `LC_CTYPE` or `LANG` are set to an empty string +- UTF8 intepretation no longer stops working if loading the compose table failed + +## 0.6.3 -- 2019-06-29 + +- Keyboard: fix extra key repeat when using also releasing a modifier + +## 0.6.2 -- 2019-06-13 + +- Update `Nix` to 0.14 + +## 0.6.1 -- 2019-04-07 + +- Additional theming capability on `ConceptFrame` via the `Theme` trait: + optional methods `get__button_icon_color` allows the stroke + color on the buttons to be customized beyond what the secondary color allows. + Button color methods now affect the `ConceptFrame`'s fill behind the buttons. +- Fix the firing of `Configure` events in window abstraction. + +## 0.6.0 -- 2019-02-18 + +#### Breaking changes + +- Upgrade to `wayland-client` version 0.23 + +## 0.5.0 -- 2019-02-05 + +#### Breaking changes + +- Update the crate to `wayland-client` version 0.22 +- Window: `set_title()` now requires a manual `refresh()` for the change to take effect + +#### Bugfixes + - Keyboard: fix system repeat rate as repeats per second rather then millisecond delay between repeats - Surface: fix panic in `compute_dpi_factor()` by only computing the dpi factor on surfaces known to the OutputMgr -- Window: `set_title()` now requires a manual `refresh()` for the change to take effect ## 0.4.4 -- 2018-12-27 diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/CONTRIBUTING.md b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/CONTRIBUTING.md similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/CONTRIBUTING.md rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/CONTRIBUTING.md diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.lock b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.lock new file mode 100644 index 0000000..900dbc0 --- /dev/null +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.lock @@ -0,0 +1,644 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "adler32" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "andrew" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rusttype 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "approx" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "arrayvec" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "autocfg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "byteorder" +version = "1.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cc" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "color_quant" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "crossbeam-deque" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crossbeam-epoch 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)", + "scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-queue" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "crossbeam-utils" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "deflate" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "dlib" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libloading 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "downcast-rs" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "either" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "gif" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "color_quant 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lzw 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "hermit-abi" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "image" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", + "gif 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)", + "jpeg-decoder 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", + "lzw 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num-iter 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "num-rational 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", + "png 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "scoped_threadpool 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "tiff 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "inflate" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "jpeg-decoder" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", + "rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libc" +version = "0.2.66" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libloading" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "line_drawing" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lzw" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "memmap" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "memoffset" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "nix" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-derive" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-integer" +version = "0.1.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-iter" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-rational" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num-integer 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-traits" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num_cpus" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ordered-float" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "png" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "deflate 0.7.20 (registry+https://github.com/rust-lang/crates.io-index)", + "inflate 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "num-iter 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "proc-macro2" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quote" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rayon" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", + "rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rayon-core" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rustc_version" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rusttype" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rusttype 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rusttype" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "stb_truetype 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "scopeguard" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "semver" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "semver-parser" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "smithay-client-toolkit" +version = "0.6.6" +dependencies = [ + "andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", + "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "image 0.21.3 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-client 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-protocols 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "stb_truetype" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.15.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tiff" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", + "lzw 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "num-derive 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "void" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "walkdir" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-client" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "downcast-rs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-scanner 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-commons" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-protocols" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-client 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-commons 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", + "wayland-scanner 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-scanner" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "wayland-sys" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "xdg" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "xml-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" +"checksum andrew 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9b7f09f89872c2b6b29e319377b1fbe91c6f5947df19a25596e121cf19a7b35e" +"checksum approx 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f0e60b75072ecd4168020818c0107f2857bb6c4e64252d8d3983f6263b40a5c3" +"checksum arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cff77d8686867eceff3105329d4698d96c2391c176d5d03adc90c7389162b5b8" +"checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" +"checksum autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d" +"checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" +"checksum byteorder 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08c48aae112d48ed9f069b33538ea9e3e90aa263cfa3d1c24309612b1f7472de" +"checksum cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)" = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" +"checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" +"checksum color_quant 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0dbbb57365263e881e805dc77d94697c9118fd94d8da011240555aa7b23445bd" +"checksum crossbeam-deque 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c3aa945d63861bfe624b55d153a39684da1e8c0bc8fba932f7ee3a3c16cea3ca" +"checksum crossbeam-epoch 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5064ebdbf05ce3cb95e45c8b086f72263f4166b29b97f6baff7ef7fe047b55ac" +"checksum crossbeam-queue 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db" +"checksum crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" +"checksum deflate 0.7.20 (registry+https://github.com/rust-lang/crates.io-index)" = "707b6a7b384888a70c8d2e8650b3e60170dfc6a67bb4aa67b6dfca57af4bedb4" +"checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" +"checksum downcast-rs 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "52ba6eb47c2131e784a38b726eb54c1e1484904f013e576a25354d0124161af6" +"checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" +"checksum gif 0.10.3 (registry+https://github.com/rust-lang/crates.io-index)" = "471d90201b3b223f3451cd4ad53e34295f16a1df17b1edf3736d47761c3981af" +"checksum hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eff2656d88f158ce120947499e971d743c05dbcbed62e5bd2f38f1698bbc3772" +"checksum image 0.21.3 (registry+https://github.com/rust-lang/crates.io-index)" = "35371e467cd7b0b3d1d6013d619203658467df12d61b0ca43cd67b743b1965eb" +"checksum inflate 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1cdb29978cc5797bd8dcc8e5bf7de604891df2a8dc576973d71a281e916db2ff" +"checksum jpeg-decoder 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)" = "0256f0aec7352539102a9efbcb75543227b7ab1117e0f95450023af730128451" +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" +"checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" +"checksum libloading 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b111a074963af1d37a139918ac6d49ad1d0d5e47f72fd55388619691a7d753" +"checksum line_drawing 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5cc7ad3d82c845bdb5dde34ffdcc7a5fb4d2996e1e1ee0f19c33bc80e15196b9" +"checksum lzw 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7d947cbb889ed21c2a84be6ffbaebf5b4e0f4340638cba0444907e38b56be084" +"checksum memmap 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6585fd95e7bb50d6cc31e20d4cf9afb4e2ba16c5846fc76793f11218da9c475b" +"checksum memoffset 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "75189eb85871ea5c2e2c15abbdd541185f63b408415e5051f5cac122d8c774b9" +"checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" +"checksum num-derive 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "eafd0b45c5537c3ba526f79d3e75120036502bebacbb3f3220914067ce39dbf2" +"checksum num-integer 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "3f6ea62e9d81a77cd3ee9a2a5b9b609447857f3d358704331e4ef39eb247fcba" +"checksum num-iter 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "dfb0800a0291891dd9f4fe7bd9c19384f98f7fbe0cd0f39a2c6b88b9868bbc00" +"checksum num-rational 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "da4dc79f9e6c81bef96148c8f6b8e72ad4541caa4a24373e900a36da07de03a3" +"checksum num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" +"checksum num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" +"checksum ordered-float 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "18869315e81473c951eb56ad5558bbc56978562d3ecfb87abb7a1e944cea4518" +"checksum png 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "63daf481fdd0defa2d1d2be15c674fbfa1b0fd71882c303a91f9a79b3252c359" +"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" +"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" +"checksum rayon 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "db6ce3297f9c85e16621bb8cca38a06779ffc31bb8184e1be4bed2be4678a098" +"checksum rayon-core 1.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "08a89b46efaf957e52b18062fb2f4660f8b8a4dde1807ca002690868ef2c85a9" +"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" +"checksum rusttype 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)" = "310942406a39981bed7e12b09182a221a29e0990f3e7e0c971f131922ed135d5" +"checksum rusttype 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "14a911032fb5791ccbeec9f28fdcb9bf0983b81f227bafdfd227c658d0731c8a" +"checksum same-file 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +"checksum scoped_threadpool 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" +"checksum scopeguard 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b42e15e59b18a828bbf5c58ea01debb36b9b096346de35d941dcb89009f24a0d" +"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" +"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" +"checksum stb_truetype 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f77b6b07e862c66a9f3e62a07588fee67cd90a9135a2b942409f195507b4fb51" +"checksum syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)" = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" +"checksum tiff 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1e4834f28a0330cb9f3f2c87d2649dca723cb33802e2bdcf18da32759fbec7ce" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" +"checksum walkdir 2.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "777182bc735b6424e1a57516d35ed72cb8019d85c8c9bf536dccb3445c1a2f7d" +"checksum wayland-client 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "af1080ebe0efabcf12aef2132152f616038f2d7dcbbccf7b2d8c5270fe14bcda" +"checksum wayland-commons 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "bb66b0d1a27c39bbce712b6372131c6e25149f03ffb0cd017cf8f7de8d66dbdb" +"checksum wayland-protocols 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "6cc286643656742777d55dc8e70d144fa4699e426ca8e9d4ef454f4bf15ffcf9" +"checksum wayland-scanner 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "93b02247366f395b9258054f964fe293ddd019c3237afba9be2ccbe9e1651c3d" +"checksum wayland-sys 0.23.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d94e89a86e6d6d7c7c9b19ebf48a03afaac4af6bc22ae570e9a24124b75358f4" +"checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum xdg 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d089681aa106a86fade1b0128fb5daf07d5867a509ab036d99988dec80429a57" +"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/Cargo.toml b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.toml similarity index 86% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/Cargo.toml rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.toml index 2ffcf86..80caf16 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/Cargo.toml +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "smithay-client-toolkit" -version = "0.4.6" +version = "0.6.6" authors = ["Victor Berger "] description = "Toolkit for making client wayland applications." documentation = "https://smithay.github.io/client-toolkit" @@ -39,23 +39,20 @@ version = "0.7" version = "0.14.1" [dependencies.wayland-client] -version = "0.21" +version = "0.23" features = ["cursor"] -[dependencies.wayland-commons] -version = "0.21" - [dependencies.wayland-protocols] -version = "0.21" -features = ["native_client", "unstable_protocols"] +version = "0.23" +features = ["client", "unstable_protocols"] [dev-dependencies.byteorder] version = "1.0" [dev-dependencies.image] -version = "0.20" +version = "0.21" [dev-dependencies.wayland-client] -version = "0.21" +version = "0.23" features = ["dlopen"] [badges.travis-ci] repository = "smithay/client-toolkit" diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/LICENSE.txt b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/LICENSE.txt similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/LICENSE.txt rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/LICENSE.txt diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/README.md b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/README.md similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/README.md rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/README.md diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/doc_index.html b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/doc_index.html similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/doc_index.html rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/doc_index.html diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/compositor_info.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/compositor_info.rs similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/compositor_info.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/compositor_info.rs diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/image_viewer.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/image_viewer.rs similarity index 94% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/image_viewer.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/image_viewer.rs index cd824b6..9616e81 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/image_viewer.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/image_viewer.rs @@ -8,9 +8,8 @@ use std::sync::{Arc, Mutex}; use byteorder::{NativeEndian, WriteBytesExt}; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests; use sctk::reexports::client::protocol::{wl_shm, wl_surface}; -use sctk::reexports::client::{Display, Proxy}; +use sctk::reexports::client::{Display, NewProxy}; use sctk::utils::{DoubleMemPool, MemPool}; use sctk::window::{ConceptFrame, Event as WEvent, State, Window}; use sctk::Environment; @@ -135,7 +134,7 @@ fn main() { // Thus, we just automatically bind the first seat we find. let seat = env .manager - .instantiate_auto(|seat| seat.implement(|_, _| {}, ())) + .instantiate_range(1, 6, NewProxy::implement_dummy) .unwrap(); // And advertise it to the Window so it knows of it and can process the // required pointer events. @@ -249,22 +248,17 @@ fn main() { } } - // These last two calls are necessary for the processing of wayland messages: - // - first, flush all our requests to the server on the unix socket - display.flush().unwrap(); - // - then, retrieve all the incoming messages - // this method blocks until a message arrives from the server, and will process - // all events by calling the implementation of the target object or each, - // and only return once all pending messages have been processed. + // Finally, dispatch the event queue. This method blocks until a message + // sends all our request to the server, then blocks until an event arrives + // from it. It then processes all events by calling the implementation of + // the target object for each, and only return once all pending messages + // have been processed. event_queue.dispatch().unwrap(); } } // The draw function, which drawn `base_image` in the provided `MemPool`, -// at given dimensions, and returns a wl_buffer to it. -// -// It simply returns the `NewProxy`, as we'll take care of implementing the -// wl_buffer outside of this function. +// at given dimensions. // // If `base_image` is `None`, it'll just draw black contents. This is to // improve performance during resizing: we need to redraw the window frequently @@ -273,7 +267,7 @@ fn main() { // just draw black contents to not feel laggy. fn redraw( pool: &mut MemPool, - surface: &Proxy, + surface: &wl_surface::WlSurface, (buf_x, buf_y): (u32, u32), base_image: Option<&image::ImageBuffer, Vec>>, ) -> Result<(), ::std::io::Error> { @@ -352,7 +346,7 @@ fn redraw( ); surface.attach(Some(&new_buffer), 0, 0); // damage the surface so that the compositor knows it needs to redraw it - if surface.version() >= 4 { + if surface.as_ref().version() >= 4 { // If our server is recent enough and supports at least version 4 of the // wl_surface interface, we can specify the damage in buffer coordinates. // This is obviously the best and do that if possible. diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/kbd_input.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/kbd_input.rs similarity index 92% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/kbd_input.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/kbd_input.rs index baa48cf..c6bd3b8 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/kbd_input.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/kbd_input.rs @@ -10,10 +10,8 @@ use byteorder::{NativeEndian, WriteBytesExt}; use sctk::keyboard::{ map_keyboard_auto_with_repeat, Event as KbEvent, KeyRepeatEvent, KeyRepeatKind, }; -use sctk::reexports::client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests; use sctk::reexports::client::protocol::{wl_shm, wl_surface}; -use sctk::reexports::client::{Display, Proxy}; +use sctk::reexports::client::{Display, NewProxy}; use sctk::utils::{DoubleMemPool, MemPool}; use sctk::window::{ConceptFrame, Event as WEvent, Window}; use sctk::Environment; @@ -34,7 +32,7 @@ fn main() { let surface = env .compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); let next_action = Arc::new(Mutex::new(None::)); @@ -67,7 +65,7 @@ fn main() { // initialize a seat to retrieve keyboard events let seat = env .manager - .instantiate_auto(|seat| seat.implement(|_, _| {}, ())) + .instantiate_range(1, 6, NewProxy::implement_dummy) .unwrap(); window.new_seat(&seat); @@ -140,14 +138,13 @@ fn main() { None => {} } - display.flush().unwrap(); event_queue.dispatch().unwrap(); } } fn redraw( pool: &mut MemPool, - surface: &Proxy, + surface: &wl_surface::WlSurface, (buf_x, buf_y): (u32, u32), ) -> Result<(), ::std::io::Error> { // resize the pool if relevant diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/pointer_input.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/pointer_input.rs similarity index 94% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/pointer_input.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/pointer_input.rs index 8775a30..6193a05 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/pointer_input.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/pointer_input.rs @@ -7,10 +7,8 @@ use std::sync::{Arc, Mutex}; use byteorder::{NativeEndian, WriteBytesExt}; -use sctk::reexports::client::protocol::wl_seat::RequestsTrait as SeatRequests; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests; use sctk::reexports::client::protocol::{wl_pointer, wl_shm, wl_surface}; -use sctk::reexports::client::{Display, Proxy}; +use sctk::reexports::client::{Display, NewProxy}; use sctk::utils::{DoubleMemPool, MemPool}; use sctk::window::{ConceptFrame, Event as WEvent, Window}; use sctk::Environment; @@ -108,14 +106,14 @@ fn main() { // initialize a seat to retrieve keyboard events let seat = env .manager - .instantiate_auto(|seat| seat.implement(|_, _| {}, ())) + .instantiate_range(1, 6, NewProxy::implement_dummy) .unwrap(); window.new_seat(&seat); let main_surface = window.surface().clone(); seat.get_pointer(move |ptr| { - ptr.implement( + ptr.implement_closure( move |evt, _| match evt { wl_pointer::Event::Enter { surface, @@ -177,14 +175,13 @@ fn main() { None => {} } - display.flush().unwrap(); event_queue.dispatch().unwrap(); } } fn redraw( pool: &mut MemPool, - surface: &Proxy, + surface: &wl_surface::WlSurface, (buf_x, buf_y): (u32, u32), ) -> Result<(), ::std::io::Error> { // resize the pool if relevant diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/selection.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/selection.rs similarity index 93% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/selection.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/selection.rs index 9d2daf2..9d97158 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/examples/selection.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/selection.rs @@ -12,10 +12,8 @@ use sctk::utils::{DoubleMemPool, MemPool}; use sctk::window::{ConceptFrame, Event as WEvent, Window}; use sctk::Environment; -use sctk::reexports::client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use sctk::reexports::client::protocol::wl_surface::RequestsTrait as SurfaceRequests; use sctk::reexports::client::protocol::{wl_shm, wl_surface}; -use sctk::reexports::client::{Display, Proxy}; +use sctk::reexports::client::{Display, NewProxy}; fn main() { let (display, mut event_queue) = @@ -24,7 +22,7 @@ fn main() { let seat = env .manager - .instantiate_auto(|seat| seat.implement(|_, _| {}, ())) + .instantiate_range(1, 6, NewProxy::implement_dummy) .unwrap(); let device = DataDevice::init_for_seat(&env.data_device_manager, &seat, |event| match event { @@ -39,7 +37,7 @@ fn main() { let mut dimensions = (320u32, 240u32); let surface = env .compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); let next_action = Arc::new(Mutex::new(None::)); @@ -117,6 +115,17 @@ fn main() { } loop { + if let Some(mut reader) = reader.lock().unwrap().take() { + // we have something to read + // We flush the display, to ensure the server correctly did receive our request + // for it to send the contents + display.flush().unwrap(); + // when we read the contents + let mut text = String::new(); + reader.read_to_string(&mut text).unwrap(); + println!("The selection buffer contained: \"{}\"", text); + } + match next_action.lock().unwrap().take() { Some(WEvent::Close) => break, Some(WEvent::Refresh) => { @@ -136,22 +145,13 @@ fn main() { None => {} } - display.flush().unwrap(); - - if let Some(mut reader) = reader.lock().unwrap().take() { - // we have something to read - let mut text = String::new(); - reader.read_to_string(&mut text).unwrap(); - println!("The selection buffer contained: \"{}\"", text); - } - event_queue.dispatch().unwrap(); } } fn redraw( pool: &mut MemPool, - surface: &Proxy, + surface: &wl_surface::WlSurface, (buf_x, buf_y): (u32, u32), ) -> Result<(), ::std::io::Error> { // resize the pool if relevant diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/themed_frame.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/themed_frame.rs new file mode 100644 index 0000000..251a9e9 --- /dev/null +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/examples/themed_frame.rs @@ -0,0 +1,229 @@ +extern crate byteorder; +extern crate smithay_client_toolkit as sctk; + +use std::cmp::min; +use std::io::{BufWriter, Seek, SeekFrom, Write}; +use std::sync::{Arc, Mutex}; + +use byteorder::{NativeEndian, WriteBytesExt}; + +use sctk::reexports::client::protocol::{wl_shm, wl_surface}; +use sctk::reexports::client::{Display, NewProxy}; +use sctk::utils::{DoubleMemPool, MemPool}; +use sctk::window::{ButtonState, ConceptFrame, Event as WEvent, Theme, Window}; +use sctk::Environment; + +fn main() { + let (display, mut event_queue) = Display::connect_to_env().unwrap(); + let env = Environment::from_display(&*display, &mut event_queue).unwrap(); + + /* + * Create a buffer with window contents + */ + + let mut dimensions = (320u32, 240u32); + + /* + * Init wayland objects + */ + + let surface = env + .compositor + .create_surface(NewProxy::implement_dummy) + .unwrap(); + + let next_action = Arc::new(Mutex::new(None::)); + + let waction = next_action.clone(); + let mut window = Window::::init_from_env(&env, surface, dimensions, move |evt| { + let mut next_action = waction.lock().unwrap(); + // Keep last event in priority order : Close > Configure > Refresh + let replace = match (&evt, &*next_action) { + (_, &None) + | (_, &Some(WEvent::Refresh)) + | (&WEvent::Configure { .. }, &Some(WEvent::Configure { .. })) + | (&WEvent::Close, _) => true, + _ => false, + }; + if replace { + *next_action = Some(evt); + } + }) + .expect("Failed to create a window !"); + + let scaled_bg = [0xFF, 0x22, 0x22, 0x22]; + let vscaled_bg = [0xFF, 0x33, 0x33, 0x33]; + + window.set_title("Kbd Input".to_string()); + window.set_theme(WaylandTheme { + primary_active: scaled_bg, + primary_inactive: vscaled_bg, + secondary_active: [0xFF, 0xFF, 0xFF, 0xFF], + secondary_inactive: [0xFF, 0xFF, 0xFF, 0xFF], + close_button_hovered: [0xFF, 0xFF, 0x00, 0x00], + close_button: [0xFF, 0x88, 0x00, 0x00], + close_button_icon_hovered: scaled_bg, + close_button_icon: [0xFF, 0xff, 0xff, 0xff], + maximize_button_hovered: [0xFF, 0x00, 0xFF, 0x00], + maximize_button: [0xFF, 0x00, 0x88, 0x00], + minimize_button_hovered: [0xFF, 0x00, 0x00, 0xFF], + minimize_button: [0xFF, 0x00, 0x00, 0x88], + }); + + let mut pools = DoubleMemPool::new(&env.shm, || {}).expect("Failed to create a memory pool !"); + + /* + * Keyboard initialization + */ + + // initialize a seat to retrieve keyboard events + let seat = env + .manager + .instantiate_range(1, 6, NewProxy::implement_dummy) + .unwrap(); + + window.new_seat(&seat); + + if !env.shell.needs_configure() { + // initial draw to bootstrap on wl_shell + if let Some(pool) = pools.pool() { + redraw(pool, window.surface(), dimensions).expect("Failed to draw") + } + window.refresh(); + } + + loop { + match next_action.lock().unwrap().take() { + Some(WEvent::Close) => break, + Some(WEvent::Refresh) => { + window.refresh(); + window.surface().commit(); + } + Some(WEvent::Configure { new_size, states }) => { + if let Some((w, h)) = new_size { + window.resize(w, h); + dimensions = (w, h) + } + println!("Window states: {:?}", states); + window.refresh(); + if let Some(pool) = pools.pool() { + redraw(pool, window.surface(), dimensions).expect("Failed to draw") + } + } + None => {} + } + + event_queue.dispatch().unwrap(); + } +} + +fn redraw( + pool: &mut MemPool, + surface: &wl_surface::WlSurface, + (buf_x, buf_y): (u32, u32), +) -> Result<(), ::std::io::Error> { + // resize the pool if relevant + pool.resize((4 * buf_x * buf_y) as usize) + .expect("Failed to resize the memory pool."); + // write the contents, a nice color gradient =) + pool.seek(SeekFrom::Start(0))?; + { + let mut writer = BufWriter::new(&mut *pool); + for i in 0..(buf_x * buf_y) { + let x = (i % buf_x) as u32; + let y = (i / buf_x) as u32; + let r: u32 = min(((buf_x - x) * 0xFF) / buf_x, ((buf_y - y) * 0xFF) / buf_y); + let g: u32 = min((x * 0xFF) / buf_x, ((buf_y - y) * 0xFF) / buf_y); + let b: u32 = min(((buf_x - x) * 0xFF) / buf_x, (y * 0xFF) / buf_y); + writer.write_u32::((0xFF << 24) + (r << 16) + (g << 8) + b)?; + } + writer.flush()?; + } + // get a buffer and attach it + let new_buffer = pool.buffer( + 0, + buf_x as i32, + buf_y as i32, + 4 * buf_x as i32, + wl_shm::Format::Argb8888, + ); + surface.attach(Some(&new_buffer), 0, 0); + surface.commit(); + Ok(()) +} + +pub struct WaylandTheme { + /// Primary color when the window is focused + pub primary_active: [u8; 4], + /// Primary color when the window is unfocused + pub primary_inactive: [u8; 4], + /// Secondary color when the window is focused + pub secondary_active: [u8; 4], + /// Secondary color when the window is unfocused + pub secondary_inactive: [u8; 4], + /// Close button color when hovered over + pub close_button_hovered: [u8; 4], + /// Close button color + pub close_button: [u8; 4], + /// Close button fg color when hovered over + pub close_button_icon_hovered: [u8; 4], + /// Close button fg color + pub close_button_icon: [u8; 4], + /// Close button color when hovered over + pub maximize_button_hovered: [u8; 4], + /// Maximize button color + pub maximize_button: [u8; 4], + /// Minimize button color when hovered over + pub minimize_button_hovered: [u8; 4], + /// Minimize button color + pub minimize_button: [u8; 4], +} + +impl Theme for WaylandTheme { + fn get_primary_color(&self, active: bool) -> [u8; 4] { + if active { + self.primary_active + } else { + self.primary_inactive + } + } + + // Used for division line + fn get_secondary_color(&self, active: bool) -> [u8; 4] { + if active { + self.secondary_active + } else { + self.secondary_inactive + } + } + + fn get_close_button_color(&self, state: ButtonState) -> [u8; 4] { + match state { + ButtonState::Hovered => self.close_button_hovered, + ButtonState::Idle => self.close_button, + _ => self.close_button, + } + } + + fn get_close_button_icon_color(&self, state: ButtonState) -> [u8; 4] { + match state { + ButtonState::Hovered => self.close_button_icon_hovered, + ButtonState::Idle => self.close_button_icon, + _ => self.close_button, + } + } + + fn get_maximize_button_color(&self, state: ButtonState) -> [u8; 4] { + match state { + ButtonState::Hovered => self.maximize_button_hovered, + _ => self.maximize_button, + } + } + + fn get_minimize_button_color(&self, state: ButtonState) -> [u8; 4] { + match state { + ButtonState::Hovered => self.minimize_button_hovered, + _ => self.minimize_button, + } + } +} diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_device.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_device.rs similarity index 76% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_device.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_device.rs index 54b5c1a..da207e3 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_device.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_device.rs @@ -1,11 +1,7 @@ use wayland_client::protocol::{ wl_data_device, wl_data_device_manager, wl_data_offer, wl_seat, wl_surface, }; -use wayland_client::{NewProxy, Proxy, QueueToken}; - -use wayland_client::protocol::wl_data_device::RequestsTrait as DeviceRequests; -use wayland_client::protocol::wl_data_device_manager::RequestsTrait as MgrRequests; -use wayland_client::protocol::wl_data_source::RequestsTrait as SourceRequests; +use wayland_client::NewProxy; use std::sync::{Arc, Mutex}; @@ -22,12 +18,12 @@ impl Inner { self.known_offers.push(DataOffer::new(offer)); } - fn set_selection(&mut self, offer: Option>) { + fn set_selection(&mut self, offer: Option) { if let Some(offer) = offer { if let Some(id) = self .known_offers .iter() - .position(|o| o.offer.equals(&offer)) + .position(|o| o.offer.as_ref().equals(&offer.as_ref())) { self.selection = Some(self.known_offers.swap_remove(id)); } else { @@ -39,12 +35,12 @@ impl Inner { } } - fn set_dnd(&mut self, offer: Option>) { + fn set_dnd(&mut self, offer: Option) { if let Some(offer) = offer { if let Some(id) = self .known_offers .iter() - .position(|o| o.offer.equals(&offer)) + .position(|o| o.offer.as_ref().equals(&offer.as_ref())) { self.current_dnd = Some(self.known_offers.swap_remove(id)); } else { @@ -63,7 +59,7 @@ impl Inner { /// data through drag'n'drop or copy/paste actions. It is associated /// with a seat upon creation. pub struct DataDevice { - device: Proxy, + device: wl_data_device::WlDataDevice, inner: Arc>, } @@ -79,7 +75,7 @@ pub enum DndEvent<'a> { /// A serial associated with the entry of this dnd serial: u32, /// The entered surface - surface: Proxy, + surface: wl_surface::WlSurface, /// horizontal location on the surface x: f64, /// vertical location on the surface @@ -150,6 +146,7 @@ where }); } Event::Selection { id } => inner.set_selection(id), + _ => unreachable!(), } } @@ -159,12 +156,12 @@ impl DataDevice { /// You need to provide an implementation that will handle drag'n'drop /// events. pub fn init_for_seat( - manager: &Proxy, - seat: &Proxy, + manager: &wl_data_device_manager::WlDataDeviceManager, + seat: &wl_seat::WlSeat, mut implem: Impl, ) -> DataDevice where - for<'a> Impl: FnMut(DndEvent<'a>) + Send + 'static, + for<'a> Impl: FnMut(DndEvent<'a>) + 'static, { let inner = Arc::new(Mutex::new(Inner { selection: None, @@ -175,7 +172,7 @@ impl DataDevice { let inner2 = inner.clone(); let device = manager .get_data_device(seat, move |device| { - device.implement( + device.implement_closure( move |evt, _| { let mut inner = inner2.lock().unwrap(); data_device_implem(evt, &mut *inner, &mut implem); @@ -188,44 +185,6 @@ impl DataDevice { DataDevice { device, inner } } - /// Create the DataDevice helper for this seat. - /// - /// Same as `init_for_seat()`, but allows the implementation to - /// not be send. - /// - /// **unsafety**: unsafe for the same reasons as `NewProxy::implement_nonsend`. - pub unsafe fn init_for_seat_nonsend( - manager: &Proxy, - seat: &Proxy, - mut implem: Impl, - token: &QueueToken, - ) -> DataDevice - where - for<'a> Impl: FnMut(DndEvent<'a>) + Send + 'static, - { - let inner = Arc::new(Mutex::new(Inner { - selection: None, - current_dnd: None, - known_offers: Vec::new(), - })); - - let inner2 = inner.clone(); - let device = manager - .get_data_device(seat, move |device| { - device.implement_nonsend( - move |evt, _| { - let mut inner = inner2.lock().unwrap(); - data_device_implem(evt, &mut *inner, &mut implem); - }, - (), - token, - ) - }) - .expect("Invalid data device or seat."); - - DataDevice { device, inner } - } - /// Start a drag'n'drop offer /// /// You need to specify the origin surface, as well a serial associated @@ -243,10 +202,10 @@ impl DataDevice { /// this drag'n'drop for user visibility. pub fn start_drag( &self, - origin: &Proxy, + origin: &wl_surface::WlSurface, source: Option, actions: DndAction, - icon: Option<&Proxy>, + icon: Option<&wl_surface::WlSurface>, serial: u32, ) { if let Some(source) = source { diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_offer.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_offer.rs similarity index 95% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_offer.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_offer.rs index 3925fd2..2a156ca 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_offer.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_offer.rs @@ -1,8 +1,6 @@ use wayland_client::protocol::wl_data_device_manager::DndAction; use wayland_client::protocol::wl_data_offer; -use wayland_client::{NewProxy, Proxy}; - -use wayland_client::protocol::wl_data_offer::RequestsTrait as OfferRequests; +use wayland_client::NewProxy; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::sync::{Arc, Mutex}; @@ -18,7 +16,7 @@ struct Inner { /// A data offer for receiving data though copy/paste or /// drag and drop pub struct DataOffer { - pub(crate) offer: Proxy, + pub(crate) offer: wl_data_offer::WlDataOffer, inner: Arc>, } @@ -31,7 +29,7 @@ impl DataOffer { serial: 0, })); let inner2 = inner.clone(); - let offer = offer.implement( + let offer = offer.implement_closure( move |event, _| { use self::wl_data_offer::Event; let mut inner = inner2.lock().unwrap(); @@ -45,6 +43,7 @@ impl DataOffer { Event::Action { dnd_action } => { inner.current_action = DndAction::from_bits_truncate(dnd_action); } + _ => unreachable!(), } }, (), diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_source.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_source.rs similarity index 76% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_source.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_source.rs index f6a1dbf..d35a256 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/data_source.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/data_source.rs @@ -1,8 +1,4 @@ use wayland_client::protocol::{wl_data_device_manager, wl_data_source}; -use wayland_client::{Proxy, QueueToken}; - -use wayland_client::protocol::wl_data_device_manager::RequestsTrait as MgrRequests; -use wayland_client::protocol::wl_data_source::RequestsTrait as SourceRequests; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::{fs, io}; @@ -10,7 +6,7 @@ use std::{fs, io}; /// A data source for sending data though copy/paste or /// drag and drop pub struct DataSource { - pub(crate) source: Proxy, + pub(crate) source: wl_data_source::WlDataSource, } /// Possible events a data source needs to react to @@ -80,7 +76,7 @@ pub enum DataSourceEvent { fn data_source_impl( evt: wl_data_source::Event, - source: &Proxy, + source: &wl_data_source::WlDataSource, implem: &mut Impl, ) where Impl: FnMut(DataSourceEvent), @@ -104,6 +100,7 @@ fn data_source_impl( source.destroy(); DataSourceEvent::Finished } + _ => unreachable!(), }; implem(event); } @@ -114,50 +111,18 @@ impl DataSource { /// You'll then need to provide it to a data device to send it /// either via selection (aka copy/paste) or via a drag and drop. pub fn new( - mgr: &Proxy, + mgr: &wl_data_device_manager::WlDataDeviceManager, mime_types: &[&str], mut implem: Impl, ) -> DataSource - where - Impl: FnMut(DataSourceEvent) + Send + 'static, - { - let source = mgr - .create_data_source(|source| { - source.implement( - move |evt, source: Proxy<_>| data_source_impl(evt, &source, &mut implem), - (), - ) - }) - .expect("Provided a dead data device manager to create a data source."); - - for &mime in mime_types { - source.offer(mime.into()); - } - - DataSource { source } - } - - /// Create a data source - /// - /// Like `new`, but the implementation does not require to - /// be `Send`. - /// - /// **unsafety**: for the same reasons as `NewProxy::implement_nonsend` - pub unsafe fn new_nonsend( - mgr: &Proxy, - mime_types: &[&str], - mut implem: Impl, - token: &QueueToken, - ) -> DataSource where Impl: FnMut(DataSourceEvent) + 'static, { let source = mgr .create_data_source(|source| { - source.implement_nonsend( - move |evt, source: Proxy<_>| data_source_impl(evt, &source, &mut implem), + source.implement_closure( + move |evt, source| data_source_impl(evt, &source, &mut implem), (), - token, ) }) .expect("Provided a dead data device manager to create a data source."); diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/mod.rs similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/data_device/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/data_device/mod.rs diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/env.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/env.rs similarity index 72% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/env.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/env.rs index 1b46698..b9c62dc 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/env.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/env.rs @@ -8,7 +8,7 @@ use wayland_client::protocol::{ wl_compositor, wl_data_device_manager, wl_display, wl_registry, wl_shell, wl_shm, wl_subcompositor, wl_surface, }; -use wayland_client::{EventQueue, GlobalEvent, GlobalManager, Proxy}; +use wayland_client::{EventQueue, GlobalEvent, GlobalManager, NewProxy}; use wayland_protocols::unstable::xdg_decoration::v1::client::zxdg_decoration_manager_v1; use wayland_protocols::unstable::xdg_shell::v6::client::zxdg_shell_v6; use wayland_protocols::xdg_shell::client::xdg_wm_base; @@ -16,11 +16,11 @@ use wayland_protocols::xdg_shell::client::xdg_wm_base; /// Possible shell globals pub enum Shell { /// Using xdg_shell protocol, the standard - Xdg(Proxy), + Xdg(xdg_wm_base::XdgWmBase), /// Old version of xdg_shell, for compatibility - Zxdg(Proxy), + Zxdg(zxdg_shell_v6::ZxdgShellV6), /// Using wl_shell, deprecated, compatibility mode - Wl(Proxy), + Wl(wl_shell::WlShell), } impl Shell { @@ -48,25 +48,25 @@ pub struct Environment { /// The underlying GlobalManager wrapping your registry pub manager: GlobalManager, /// The compositor global, used to create surfaces - pub compositor: Proxy, + pub compositor: wl_compositor::WlCompositor, /// The subcompositor global, used to create subsurfaces - pub subcompositor: Proxy, + pub subcompositor: wl_subcompositor::WlSubcompositor, /// The shell global, used make your surfaces into windows /// /// This tries to bind using the xdg_shell protocol, and fallbacks /// to wl_shell if it fails pub shell: Shell, /// The SHM global, to create shared memory buffers - pub shm: Proxy, + pub shm: wl_shm::WlShm, /// The data device manager, used to handle drag&drop and selection /// copy/paste - pub data_device_manager: Proxy, + pub data_device_manager: wl_data_device_manager::WlDataDeviceManager, /// A manager for handling the advertised outputs pub outputs: ::output::OutputMgr, /// The decoration manager, if the server supports server-side decorations - pub decorations_mgr: Option>, + pub decorations_mgr: Option, shm_formats: Arc>>, - surfaces: Arc>>>, + surfaces: Arc>>, } impl Environment { @@ -76,7 +76,7 @@ impl Environment { /// the initialization process does a few roundtrip to the server /// to initialize all the globals. pub fn from_display( - display: &Proxy, + display: &wl_display::WlDisplay, evq: &mut EventQueue, ) -> io::Result { Environment::from_display_with_cb(display, evq, |_, _| {}) @@ -89,21 +89,24 @@ impl Environment { /// `GlobalManager::new_with_cb`. Note that you will still /// receive events even if they are processed by this `Environment`. pub fn from_display_with_cb( - display: &Proxy, + display: &wl_display::WlDisplay, evq: &mut EventQueue, mut cb: Impl, ) -> io::Result where - Impl: FnMut(GlobalEvent, Proxy) + Send + 'static, + Impl: FnMut(GlobalEvent, wl_registry::WlRegistry) + 'static, { let outputs = ::output::OutputMgr::new(); let outputs2 = outputs.clone(); - let surfaces: Arc>>> = - Arc::new(Mutex::new(Vec::new())); + let surfaces: Arc>> = Arc::new(Mutex::new(Vec::new())); let surfaces2 = surfaces.clone(); - let display_wrapper = display.make_wrapper(&evq.get_token()).unwrap(); + let display_wrapper = display + .as_ref() + .make_wrapper(&evq.get_token()) + .unwrap() + .into(); let manager = GlobalManager::new_with_cb(&display_wrapper, move |event, registry| { match event { GlobalEvent::New { @@ -122,6 +125,7 @@ impl Environment { .unwrap(); for surface in &*surfaces2.lock().unwrap() { surface + .as_ref() .user_data::>() .expect("Surface was not created with create_surface.") .lock() @@ -142,22 +146,24 @@ impl Environment { // wl_compositor let compositor = manager - .instantiate_auto(|compositor| compositor.implement(|_, _| {}, ())) + .instantiate_range(1, 4, NewProxy::implement_dummy) .expect("Server didn't advertise `wl_compositor`?!"); // wl_subcompositor let subcompositor = manager - .instantiate_auto(|subcompositor| subcompositor.implement(|_, _| {}, ())) + .instantiate_range(1, 1, NewProxy::implement_dummy) .expect("Server didn't advertise `wl_subcompositor`?!"); // wl_shm let shm_formats = Arc::new(Mutex::new(Vec::new())); let shm_formats2 = shm_formats.clone(); let shm = manager - .instantiate_auto(|shm| { - shm.implement( - move |wl_shm::Event::Format { format }, _| { - shm_formats2.lock().unwrap().push(format); + .instantiate_range(1, 1, |shm| { + shm.implement_closure( + move |evt, _| { + if let wl_shm::Event::Format { format } = evt { + shm_formats2.lock().unwrap().push(format); + } }, (), ) @@ -165,33 +171,36 @@ impl Environment { .expect("Server didn't advertise `wl_shm`?!"); let data_device_manager = manager - .instantiate_auto(|data_device_manager| data_device_manager.implement(|_, _| {}, ())) + .instantiate_range(1, 3, NewProxy::implement_dummy) .expect("Server didn't advertise `wl_data_device_manager`?!"); // shells - let shell = if let Ok(wm_base) = manager.instantiate_auto(|wm_base| { - wm_base.implement( - |xdg_wm_base::Event::Ping { serial }, proxy: Proxy<_>| { - use self::xdg_wm_base::RequestsTrait; - proxy.pong(serial) - }, - (), - ) - }) { + let shell = if let Ok(wm_base) = + manager.instantiate_exact(1, |wm_base: NewProxy| { + wm_base.implement_closure( + |evt, shell| { + if let xdg_wm_base::Event::Ping { serial } = evt { + shell.pong(serial) + } + }, + (), + ) + }) { Shell::Xdg(wm_base) - } else if let Ok(xdg_shell) = manager.instantiate_auto(|xdg_shell| { - xdg_shell.implement( - |zxdg_shell_v6::Event::Ping { serial }, proxy: Proxy<_>| { - use self::zxdg_shell_v6::RequestsTrait; - proxy.pong(serial) - }, - (), - ) - }) { - Shell::Zxdg(xdg_shell) - } else if let Ok(wl_shell) = - manager.instantiate_auto(|wl_shell| wl_shell.implement(|_, _| {}, ())) + } else if let Ok(xdg_shell) = + manager.instantiate_exact(1, |xdg_shell: NewProxy| { + xdg_shell.implement_closure( + |evt, shell| { + if let zxdg_shell_v6::Event::Ping { serial } = evt { + shell.pong(serial); + } + }, + (), + ) + }) { + Shell::Zxdg(xdg_shell) + } else if let Ok(wl_shell) = manager.instantiate_exact(1, NewProxy::implement_dummy) { Shell::Wl(wl_shell) } else { panic!("Server didn't advertise neither `xdg_wm_base` nor `wl_shell`?!"); @@ -199,9 +208,7 @@ impl Environment { // try to retrieve the decoration manager let decorations_mgr = if let Shell::Xdg(_) = shell { - manager - .instantiate_auto(|mgr| mgr.implement(|_, _| {}, ())) - .ok() + manager.instantiate_exact(1, NewProxy::implement_dummy).ok() } else { None }; @@ -235,9 +242,9 @@ impl Environment { /// /// The DPI factor associated to a surface is defined as the maximum of the DPI /// factors of the outputs it is displayed on. - pub fn create_surface(&self, dpi_change: F) -> Proxy + pub fn create_surface(&self, dpi_change: F) -> wl_surface::WlSurface where - F: FnMut(i32, Proxy) + Send + 'static, + F: FnMut(i32, wl_surface::WlSurface) + Send + 'static, { let surface = create_surface(&self, Box::new(dpi_change)); self.surfaces.lock().unwrap().push(surface.clone()); @@ -247,7 +254,7 @@ impl Environment { /// Create a new shell surface pub fn create_shell_surface( &self, - surface: &Proxy, + surface: &wl_surface::WlSurface, shell_impl: Impl, ) -> Box where diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/ffi.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/ffi.rs similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/ffi.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/ffi.rs diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/keysyms.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/keysyms.rs similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/keysyms.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/keysyms.rs diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/mod.rs similarity index 62% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/mod.rs index 359de1d..4f6b6ea 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/keyboard/mod.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/keyboard/mod.rs @@ -6,7 +6,7 @@ //! You simply need to provide an implementation to receive the //! intepreted events, as described by the `Event` enum of this modules. //! -//! Implementation of you `NewProxy` can be done with the +//! Implementation of your `NewProxy` can be done with the //! `map_keyboard_auto` or the `map_keyboard_rmlvo` functions depending //! on whether you wish to use the keymap provided by the server or a //! specific one. @@ -26,9 +26,6 @@ use memmap::MmapOptions; pub use wayland_client::protocol::wl_keyboard::KeyState; use wayland_client::protocol::{wl_keyboard, wl_seat, wl_surface}; -use wayland_client::Proxy; - -use wayland_client::protocol::wl_seat::RequestsTrait; use self::ffi::xkb_state_component; use self::ffi::XKBCOMMON_HANDLE as XKBH; @@ -253,8 +250,11 @@ impl KbState { unsafe fn init_compose(&mut self) { let locale = env::var_os("LC_ALL") + .and_then(|v| if v.is_empty() { None } else { Some(v) }) .or_else(|| env::var_os("LC_CTYPE")) + .and_then(|v| if v.is_empty() { None } else { Some(v) }) .or_else(|| env::var_os("LANG")) + .and_then(|v| if v.is_empty() { None } else { Some(v) }) .unwrap_or_else(|| "C".into()); let locale = CString::new(locale.into_vec()).unwrap(); @@ -406,7 +406,7 @@ pub enum Event<'a> { /// serial number of the event serial: u32, /// surface that was entered - surface: Proxy, + surface: wl_surface::WlSurface, /// raw values of the currently pressed keys rawkeys: &'a [u32], /// interpreted symbols of the currently pressed keys @@ -417,7 +417,7 @@ pub enum Event<'a> { /// serial number of the event serial: u32, /// surface that was left - surface: Proxy, + surface: wl_surface::WlSurface, }, /// A key event occurred Key { @@ -473,11 +473,11 @@ pub struct KeyRepeatEvent { /// /// Returns an error if xkbcommon could not be initialized. pub fn map_keyboard_auto( - seat: &Proxy, + seat: &wl_seat::WlSeat, implementation: Impl, -) -> Result, Error> +) -> Result where - for<'a> Impl: FnMut(Event<'a>, Proxy) + Send + 'static, + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, { let state = match KbState::new() { Ok(s) => s, @@ -502,12 +502,12 @@ where /// Returns an error if xkbcommon could not be initialized or the RMLVO specification /// contained invalid values. pub fn map_keyboard_rmlvo( - seat: &Proxy, + seat: &wl_seat::WlSeat, rmlvo: RMLVO, implementation: Impl, -) -> Result, Error> +) -> Result where - for<'a> Impl: FnMut(Event<'a>, Proxy) + Send + 'static, + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, { fn to_cstring(s: Option) -> Result, Error> { s.map_or(Ok(None), |s| CString::new(s).map(Option::Some)) @@ -551,238 +551,31 @@ where } fn implement_kbd( - seat: &Proxy, + seat: &wl_seat::WlSeat, state: KbState, - mut event_impl: Impl, + implementation: Impl, repeat: Option<(KeyRepeatKind, RepeatImpl)>, -) -> Proxy +) -> wl_keyboard::WlKeyboard where - for<'a> Impl: FnMut(Event<'a>, Proxy) + Send + 'static, - RepeatImpl: FnMut(KeyRepeatEvent, Proxy) + Send + 'static, + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, { - let safe_state = Arc::new(Mutex::new(state)); - let (key_repeat_kind, repeat_impl) = { - if let Some(repeat) = repeat { - (Some(repeat.0), Some(Arc::new(Mutex::new(repeat.1)))) - } else { - (None, None) - } - }; - let kill_chan = Arc::new(Mutex::new(mpsc::channel::<()>())); - let state_chan = Arc::new(Mutex::new(mpsc::channel::<()>())); - let mut key_held: Option = None; - let system_repeat_timing: Arc> = Arc::new(Mutex::new((30, 500))); + let state = Arc::new(Mutex::new(state)); + let repeat = repeat.map(|(kind, implem)| RepeatHandler { + implementation: Arc::new(Mutex::new(implem)), + state: state.clone(), + kind, + ongoing: None, + rate: 5, + delay: 300, + }); seat.get_keyboard(|kbd| { kbd.implement( - move |event: wl_keyboard::Event, proxy: Proxy| { - let mut state = safe_state.lock().unwrap(); - match event { - wl_keyboard::Event::Keymap { format, fd, size } => { - if state.locked { - // state is locked, ignore keymap updates - return; - } - if state.ready() { - // new keymap, we first deinit to free resources - unsafe { - state.de_init(); - } - } - match format { - wl_keyboard::KeymapFormat::XkbV1 => unsafe { - state.init_with_fd(fd, size as usize); - }, - wl_keyboard::KeymapFormat::NoKeymap => { - // TODO: how to handle this (hopefully never occuring) case? - } - } - } - wl_keyboard::Event::Enter { - serial, - surface, - keys, - } => { - let rawkeys: &[u32] = unsafe { - ::std::slice::from_raw_parts( - keys.as_ptr() as *const u32, - keys.len() / 4, - ) - }; - let keys: Vec = - rawkeys.iter().map(|k| state.get_one_sym_raw(*k)).collect(); - event_impl( - Event::Enter { - serial, - surface, - rawkeys, - keysyms: &keys, - }, - proxy, - ); - } - wl_keyboard::Event::Leave { serial, surface } => { - if key_held.is_some() { - kill_chan.lock().unwrap().0.send(()).unwrap(); - key_held = None; - } - event_impl(Event::Leave { serial, surface }, proxy); - } - wl_keyboard::Event::Key { - serial, - time, - key, - state: key_state, - } => { - // Get the values to generate a key event - let sym = state.get_one_sym_raw(key); - let utf8 = if key_state == wl_keyboard::KeyState::Pressed { - if state.compose_feed(sym) - != Some(ffi::xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED) - { - None - } else if let Some(status) = state.compose_status() { - match status { - ffi::xkb_compose_status::XKB_COMPOSE_COMPOSED => { - state.compose_get_utf8() - } - ffi::xkb_compose_status::XKB_COMPOSE_NOTHING => { - state.get_utf8_raw(key) - } - _ => None, - } - } else { - state.get_utf8_raw(key) - } - } else { - None - }; - - if key_state == wl_keyboard::KeyState::Pressed { - event_impl( - Event::Key { - serial, - time, - rawkey: key, - keysym: sym, - state: key_state, - utf8: utf8.clone(), - }, - proxy.clone(), - ); - if let Some(repeat_impl) = repeat_impl.clone() { - // Check with xkb if key is repeatable - if unsafe { state.key_repeats(key + 8) } { - if key_held.is_some() { - // If a key is being held then kill its repeat thread - kill_chan.lock().unwrap().0.send(()).unwrap(); - } - key_held = Some(key); - // Clone variables for the thread - let thread_kill_chan = kill_chan.clone(); - let thread_state_chan = state_chan.clone(); - let thread_state = safe_state.clone(); - let thread_repeat_impl = repeat_impl.clone(); - let repeat_timing = match key_repeat_kind { - Some(KeyRepeatKind::Fixed { rate, delay, .. }) => { - (rate, delay) - } - Some(KeyRepeatKind::System { .. }) => { - *system_repeat_timing.lock().unwrap() - } - None => panic!(), - }; - // Start thread to send key events - thread::spawn(move || { - let time_tracker = Instant::now(); - // Delay - thread::sleep(Duration::from_millis(repeat_timing.1)); - match thread_kill_chan.lock().unwrap().1.try_recv() { - Ok(_) | Err(mpsc::TryRecvError::Disconnected) => return, - _ => {} - } - let mut thread_sym = sym; - let mut thread_utf8 = utf8; - - loop { - if thread_state_chan - .lock() - .unwrap() - .1 - .try_recv() - .is_ok() - { - let mut thread_state = thread_state.lock().unwrap(); - thread_sym = thread_state.get_one_sym_raw(key); - thread_utf8 = thread_state.get_utf8_raw(key); - } - let elapsed_time = time_tracker.elapsed(); - (&mut *thread_repeat_impl.lock().unwrap())( - KeyRepeatEvent { - time: time - + elapsed_time.as_secs() as u32 * 1000 - + elapsed_time.subsec_nanos() / 1_000_000, - rawkey: key, - keysym: thread_sym, - utf8: thread_utf8.clone(), - }, - proxy.clone(), - ); - // Rate - thread::sleep( - Duration::from_secs(1) / repeat_timing.0 as u32, - ); - match thread_kill_chan.lock().unwrap().1.try_recv() { - Ok(_) | Err(mpsc::TryRecvError::Disconnected) => { - break; - } - _ => {} - } - } - }); - } - } - } else { - if key_held == Some(key) { - kill_chan.lock().unwrap().0.send(()).unwrap(); - key_held = None; - } - event_impl( - Event::Key { - serial, - time, - rawkey: key, - keysym: sym, - state: key_state, - utf8: utf8.clone(), - }, - proxy.clone(), - ); - } - } - wl_keyboard::Event::Modifiers { - mods_depressed, - mods_latched, - mods_locked, - group, - .. - } => { - state.update_modifiers(mods_depressed, mods_latched, mods_locked, group); - event_impl( - Event::Modifiers { - modifiers: state.mods_state, - }, - proxy, - ); - if key_held.is_some() { - state_chan.lock().unwrap().0.send(()).unwrap(); - } - } - wl_keyboard::Event::RepeatInfo { rate, delay } => { - event_impl(Event::RepeatInfo { rate, delay }, proxy); - *system_repeat_timing.lock().unwrap() = (rate as u64, delay as u64); - } - } + KbdHandler { + state, + repeat, + implementation, }, (), ) @@ -805,14 +598,14 @@ where /// /// Returns an error if xkbcommon could not be initialized. pub fn map_keyboard_auto_with_repeat( - seat: &Proxy, + seat: &wl_seat::WlSeat, key_repeat_kind: KeyRepeatKind, implementation: Impl, repeat_implementation: RepeatImpl, -) -> Result, Error> +) -> Result where - for<'a> Impl: FnMut(Event<'a>, Proxy) + Send + 'static, - RepeatImpl: FnMut(KeyRepeatEvent, Proxy) + Send + 'static, + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, { let state = match KbState::new() { Ok(s) => s, @@ -841,15 +634,15 @@ where /// Returns an error if xkbcommon could not be initialized or the RMLVO specification /// contained invalid values. pub fn map_keyboard_rmlvo_with_repeat( - seat: &Proxy, + seat: &wl_seat::WlSeat, rmlvo: RMLVO, key_repeat_kind: KeyRepeatKind, implementation: Impl, repeat_implementation: RepeatImpl, -) -> Result, Error> +) -> Result where - for<'a> Impl: FnMut(Event<'a>, Proxy) + Send + 'static, - RepeatImpl: FnMut(KeyRepeatEvent, Proxy) + Send + 'static, + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, { fn to_cstring(s: Option) -> Result, Error> { s.map_or(Ok(None), |s| CString::new(s).map(Option::Some)) @@ -891,3 +684,293 @@ where Err(error) => Err(error), } } + +struct KbdHandler { + implementation: Impl, + state: Arc>, + repeat: Option>, +} + +impl KbdHandler +where + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, +{ + fn start_repeat(&mut self, key: u32, object: wl_keyboard::WlKeyboard, time: u32) { + if let Some(ref mut repeat) = self.repeat { + repeat.start(key, object, time); + } + } + + fn stop_repeat(&mut self, key: Option) { + if let Some(ref mut repeat) = self.repeat { + repeat.stop(key); + } + } + + fn set_repeat_timing(&mut self, rate: i32, delay: i32) { + if let Some(ref mut repeat) = self.repeat { + repeat.rate = rate; + repeat.delay = delay; + } + } + + fn repeat_state_changed(&mut self) { + if let Some(ref mut repeat) = self.repeat { + repeat.state_changed(); + } + } +} + +struct RepeatHandler { + implementation: Arc>, + state: Arc>, + kind: KeyRepeatKind, + ongoing: Option<(u32, mpsc::Sender<()>)>, + rate: i32, + delay: i32, +} + +impl RepeatHandler +where + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, +{ + fn start(&mut self, key: u32, object: wl_keyboard::WlKeyboard, time: u32) { + // replace any previously repeating key + let (sender, receiver) = mpsc::channel(); + self.ongoing = Some((key, sender)); + + let thread_impl = self.implementation.clone(); + let thread_state = self.state.clone(); + let repeat_timing = match self.kind { + KeyRepeatKind::Fixed { rate, delay } => (rate, delay), + KeyRepeatKind::System => (self.rate as u64, self.delay as u64), + }; + // Start thread to send key events + thread::spawn(move || { + let time_tracker = Instant::now(); + // Delay + thread::sleep(Duration::from_millis(repeat_timing.1)); + let (mut sym, mut utf8) = { + let mut state = thread_state.lock().unwrap(); + (state.get_one_sym_raw(key), state.get_utf8_raw(key)) + }; + + loop { + // Drain channel + let mut need_update = false; + loop { + match receiver.try_recv() { + Ok(()) => need_update = true, + Err(mpsc::TryRecvError::Empty) => break, + Err(mpsc::TryRecvError::Disconnected) => return, + } + } + if need_update { + // Update state + let mut state = thread_state.lock().unwrap(); + sym = state.get_one_sym_raw(key); + utf8 = state.get_utf8_raw(key); + } + + let elapsed_time = time_tracker.elapsed(); + (&mut *thread_impl.lock().unwrap())( + KeyRepeatEvent { + time: time + + elapsed_time.as_secs() as u32 * 1000 + + elapsed_time.subsec_nanos() / 1_000_000, + rawkey: key, + keysym: sym, + utf8: utf8.clone(), + }, + object.clone(), + ); + // Rate + thread::sleep(Duration::from_secs(1) / repeat_timing.0 as u32); + } + }); + } + + fn stop(&mut self, key: Option) { + if let Some((current_key, sender)) = self.ongoing.take() { + if key.is_some() && Some(current_key) != key { + self.ongoing = Some((current_key, sender)) + } + } + } + + fn state_changed(&mut self) { + if let Some((_, ref chan)) = self.ongoing { + chan.send(()).unwrap(); + } + } +} + +impl wl_keyboard::EventHandler for KbdHandler +where + for<'a> Impl: FnMut(Event<'a>, wl_keyboard::WlKeyboard) + 'static, + RepeatImpl: FnMut(KeyRepeatEvent, wl_keyboard::WlKeyboard) + Send + 'static, +{ + fn keymap( + &mut self, + _: wl_keyboard::WlKeyboard, + format: wl_keyboard::KeymapFormat, + fd: RawFd, + size: u32, + ) { + let mut state = self.state.lock().unwrap(); + if state.locked { + // state is locked, ignore keymap updates + return; + } + if state.ready() { + // new keymap, we first deinit to free resources + unsafe { + state.de_init(); + } + } + match format { + wl_keyboard::KeymapFormat::XkbV1 => unsafe { + state.init_with_fd(fd, size as usize); + }, + wl_keyboard::KeymapFormat::NoKeymap => { + // TODO: how to handle this (hopefully never occuring) case? + } + _ => unreachable!(), + } + } + + fn enter( + &mut self, + object: wl_keyboard::WlKeyboard, + serial: u32, + surface: wl_surface::WlSurface, + keys: Vec, + ) { + let mut state = self.state.lock().unwrap(); + let rawkeys: &[u32] = + unsafe { ::std::slice::from_raw_parts(keys.as_ptr() as *const u32, keys.len() / 4) }; + let keys: Vec = rawkeys.iter().map(|k| state.get_one_sym_raw(*k)).collect(); + (self.implementation)( + Event::Enter { + serial, + surface, + rawkeys, + keysyms: &keys, + }, + object, + ); + } + + fn leave( + &mut self, + object: wl_keyboard::WlKeyboard, + serial: u32, + surface: wl_surface::WlSurface, + ) { + self.stop_repeat(None); + (self.implementation)(Event::Leave { serial, surface }, object); + } + + fn key( + &mut self, + object: wl_keyboard::WlKeyboard, + serial: u32, + time: u32, + key: u32, + key_state: wl_keyboard::KeyState, + ) { + let (sym, utf8, repeats) = { + let mut state = self.state.lock().unwrap(); + // Get the values to generate a key event + let sym = state.get_one_sym_raw(key); + let utf8 = if key_state == wl_keyboard::KeyState::Pressed { + match state.compose_feed(sym) { + Some(ffi::xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED) => { + if let Some(status) = state.compose_status() { + match status { + ffi::xkb_compose_status::XKB_COMPOSE_COMPOSED => { + state.compose_get_utf8() + } + ffi::xkb_compose_status::XKB_COMPOSE_NOTHING => { + state.get_utf8_raw(key) + } + _ => None, + } + } else { + state.get_utf8_raw(key) + } + } + Some(_) => { + // XKB_COMPOSE_FEED_IGNORED + None + } + None => { + // XKB COMPOSE is not initialized + state.get_utf8_raw(key) + } + } + } else { + None + }; + let repeats = unsafe { state.key_repeats(key + 8) }; + (sym, utf8, repeats) + }; + + if key_state == wl_keyboard::KeyState::Pressed { + (self.implementation)( + Event::Key { + serial, + time, + rawkey: key, + keysym: sym, + state: key_state, + utf8: utf8.clone(), + }, + object.clone(), + ); + if repeats { + self.start_repeat(key, object, time); + } + } else { + self.stop_repeat(Some(key)); + (self.implementation)( + Event::Key { + serial, + time, + rawkey: key, + keysym: sym, + state: key_state, + utf8: utf8.clone(), + }, + object, + ); + } + } + + fn modifiers( + &mut self, + object: wl_keyboard::WlKeyboard, + _: u32, + mods_depressed: u32, + mods_latched: u32, + mods_locked: u32, + group: u32, + ) { + { + let mut state = self.state.lock().unwrap(); + state.update_modifiers(mods_depressed, mods_latched, mods_locked, group); + (self.implementation)( + Event::Modifiers { + modifiers: state.mods_state, + }, + object, + ); + } + self.repeat_state_changed(); + } + + fn repeat_info(&mut self, _: wl_keyboard::WlKeyboard, rate: i32, delay: i32) { + self.set_repeat_timing(rate, delay); + } +} diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/lib.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/lib.rs similarity index 93% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/lib.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/lib.rs index c35557f..f96d409 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/lib.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/lib.rs @@ -16,8 +16,6 @@ extern crate nix; #[doc(hidden)] pub extern crate wayland_client; #[doc(hidden)] -pub extern crate wayland_commons; -#[doc(hidden)] pub extern crate wayland_protocols; /// Re-exports of some crates, for convenience diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/output.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/output.rs similarity index 86% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/output.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/output.rs index 66f31ae..74da0a1 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/output.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/output.rs @@ -2,9 +2,8 @@ use std::sync::{Arc, Mutex}; -use wayland_client::protocol::wl_output::{self, Event, RequestsTrait, WlOutput}; -use wayland_client::protocol::wl_registry::{self, RequestsTrait as RegistryRequest}; -use wayland_client::Proxy; +use wayland_client::protocol::wl_output::{self, Event, WlOutput}; +use wayland_client::protocol::wl_registry; pub use wayland_client::protocol::wl_output::{Subpixel, Transform}; @@ -74,16 +73,16 @@ impl OutputInfo { } struct Inner { - outputs: Vec<(u32, Proxy, OutputInfo)>, - pending: Vec<(Proxy, Event)>, + outputs: Vec<(u32, WlOutput, OutputInfo)>, + pending: Vec<(WlOutput, Event)>, } impl Inner { - fn merge(&mut self, output: &Proxy) { + fn merge(&mut self, output: &WlOutput) { let info = match self .outputs .iter_mut() - .find(|&&mut (_, ref o, _)| o.equals(output)) + .find(|&&mut (_, ref o, _)| o.as_ref().equals(output.as_ref())) { Some(&mut (_, _, ref mut info)) => info, // trying to merge a non-existing output ? @@ -91,14 +90,18 @@ impl Inner { // output being concurrently destroyed at the bad time ? None => { // clean stale state - self.pending.retain(|&(ref o, _)| o.is_alive()); + self.pending.retain(|&(ref o, _)| o.as_ref().is_alive()); return; } }; // slow, but could be improved with Vec::drain_filter // see https://github.com/rust-lang/rust/issues/43244 // this vec should be pretty small at all times anyway - while let Some(idx) = self.pending.iter().position(|&(ref o, _)| o.equals(output)) { + while let Some(idx) = self + .pending + .iter() + .position(|&(ref o, _)| o.as_ref().equals(output.as_ref())) + { let (_, event) = self.pending.swap_remove(idx); match event { Event::Geometry { @@ -152,6 +155,7 @@ impl Inner { }) } } + _ => unreachable!(), } } } @@ -173,23 +177,18 @@ impl OutputMgr { } } - pub(crate) fn new_output( - &self, - id: u32, - version: u32, - registry: &Proxy, - ) { + pub(crate) fn new_output(&self, id: u32, version: u32, registry: &wl_registry::WlRegistry) { let inner = self.inner.clone(); let output = registry .bind(version, id, |output| { - output.implement( + output.implement_closure( move |event, output| { let mut inner = inner.lock().unwrap(); if let Event::Done = event { inner.merge(&output); } else { inner.pending.push((output.clone(), event)); - if output.version() < 2 { + if output.as_ref().version() < 2 { // in case of very old outputs, we can't treat the changes // atomically as the Done event does not exist inner.merge(&output); @@ -213,8 +212,10 @@ impl OutputMgr { if let Some(idx) = inner.outputs.iter().position(|&(i, _, _)| i == id) { let (_, output, _) = inner.outputs.swap_remove(idx); // cleanup all remaining pending if any - inner.pending.retain(|&(ref o, _)| !o.equals(&output)); - if output.version() >= 3 { + inner + .pending + .retain(|&(ref o, _)| !o.as_ref().equals(&output.as_ref())); + if output.as_ref().version() >= 3 { output.release(); } } @@ -226,7 +227,7 @@ impl OutputMgr { /// the closure is not called and `None` is returned. pub fn find_id(&self, id: u32, f: F) -> Option where - F: FnOnce(&Proxy, &OutputInfo) -> T, + F: FnOnce(&wl_output::WlOutput, &OutputInfo) -> T, { let inner = self.inner.lock().unwrap(); if let Some(&(_, ref proxy, ref info)) = inner.outputs.iter().find(|&&(i, _, _)| i == id) { @@ -240,7 +241,7 @@ impl OutputMgr { /// /// If the requested output is not found (likely because it has been destroyed) /// the closure is not called and `None` is returned. - pub fn with_info(&self, output: &Proxy, f: F) -> Option + pub fn with_info(&self, output: &WlOutput, f: F) -> Option where F: FnOnce(u32, &OutputInfo) -> T, { @@ -248,7 +249,7 @@ impl OutputMgr { if let Some(&(id, _, ref info)) = inner .outputs .iter() - .find(|&&(_, ref o, _)| o.equals(output)) + .find(|&&(_, ref o, _)| o.as_ref().equals(output.as_ref())) { Some(f(id, info)) } else { @@ -259,7 +260,7 @@ impl OutputMgr { /// Access all output information pub fn with_all(&self, f: F) -> T where - F: FnOnce(&[(u32, Proxy, OutputInfo)]) -> T, + F: FnOnce(&[(u32, WlOutput, OutputInfo)]) -> T, { let inner = self.inner.lock().unwrap(); f(&inner.outputs) diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/mod.rs similarity index 66% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/mod.rs index 6e75f47..4e025f8 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/mod.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/mod.rs @@ -3,10 +3,6 @@ use std::ops::Deref; use wayland_client::protocol::{wl_compositor, wl_pointer, wl_seat, wl_shm}; -use wayland_client::{NewProxy, Proxy, QueueToken}; - -use wayland_client::protocol::wl_seat::RequestsTrait as SeatRequests; - mod theme; pub use self::theme::{ThemeManager, ThemedPointer}; @@ -34,8 +30,8 @@ impl AutoThemer { /// Falls back to `UnThemed` if `libwayland-cursor` is not available. pub fn init( name: Option<&str>, - compositor: Proxy, - shm: &Proxy, + compositor: wl_compositor::WlCompositor, + shm: &wl_shm::WlShm, ) -> AutoThemer { match ThemeManager::init(name, compositor, &shm) { Ok(mgr) => AutoThemer::Themed(mgr), @@ -44,7 +40,7 @@ impl AutoThemer { } /// Wrap a pointer to theme it - pub fn theme_pointer(&self, pointer: Proxy) -> AutoPointer { + pub fn theme_pointer(&self, pointer: wl_pointer::WlPointer) -> AutoPointer { match *self { AutoThemer::Themed(ref mgr) => AutoPointer::Themed(mgr.theme_pointer(pointer)), AutoThemer::UnThemed => AutoPointer::UnThemed(pointer), @@ -55,16 +51,16 @@ impl AutoThemer { /// /// You need to provide an implementation as if implementing a `wl_pointer`, but /// it will receive as `meta` argument an `AutoPointer` wrapping your pointer, - /// rather than a `Proxy`. + /// rather than a `WlPointer`. pub fn theme_pointer_with_impl( &self, - seat: &Proxy, + seat: &wl_seat::WlSeat, mut implementation: Impl, user_data: UD, ) -> AutoPointer where - Impl: FnMut(wl_pointer::Event, AutoPointer) + Send + 'static, - UD: Send + Sync + 'static, + Impl: FnMut(wl_pointer::Event, AutoPointer) + 'static, + UD: 'static, { match *self { AutoThemer::Themed(ref mgr) => { @@ -78,7 +74,7 @@ impl AutoThemer { AutoThemer::UnThemed => { let pointer = seat .get_pointer(|pointer| { - pointer.implement( + pointer.implement_closure( move |event, seat| implementation(event, AutoPointer::UnThemed(seat)), user_data, ) @@ -88,43 +84,6 @@ impl AutoThemer { } } } - - /// Initialize a new pointer as a ThemedPointer with an adapter implementation - /// - /// Like `theme_pointer_with_impl` but allows you to have a non-`Send` implementation. - /// - /// **Unsafe** for the same reasons as `NewProxy::implement_nonsend`. - pub unsafe fn theme_pointer_with_nonsend_impl( - &self, - pointer: NewProxy, - mut implementation: Impl, - user_data: UD, - token: &QueueToken, - ) -> AutoPointer - where - Impl: FnMut(wl_pointer::Event, AutoPointer) + Send + 'static, - UD: Send + Sync + 'static, - { - match *self { - AutoThemer::Themed(ref mgr) => { - let pointer = mgr.theme_pointer_with_nonsend_impl( - pointer, - move |event, pointer| implementation(event, AutoPointer::Themed(pointer)), - user_data, - token, - ); - AutoPointer::Themed(pointer) - } - AutoThemer::UnThemed => { - let pointer = pointer.implement_nonsend( - move |event, pointer| implementation(event, AutoPointer::UnThemed(pointer)), - user_data, - token, - ); - AutoPointer::UnThemed(pointer) - } - } - } } /// A pointer wrapper to gracefully handle a missing `libwayland-cursor` @@ -135,7 +94,7 @@ pub enum AutoPointer { /// The `ThemedPointer` Themed(ThemedPointer), /// The regular pointer if theme capability is not available - UnThemed(Proxy), + UnThemed(wl_pointer::WlPointer), } impl AutoPointer { @@ -144,7 +103,7 @@ impl AutoPointer { /// Possible names depend on the theme. Does nothing and returns /// `Err(())` if given name is not available. /// - /// Does nothing an returns `Ok(())` if no theme is loaded (if + /// Does nothing and returns `Ok(())` if no theme is loaded (if /// `wayland-cursor` is not available). /// /// If this is done as an answer to an input event, you need to provide @@ -155,11 +114,34 @@ impl AutoPointer { AutoPointer::UnThemed(_) => Ok(()), } } + + /// Change the cursor to the given cursor name and apply a scale to an underlying cursor + /// surface + /// + /// Possible names depend on the theme. Does nothing and returns + /// `Err(())` if given name is not available. + /// + /// Does nothing and returns `Ok(())` if no theme is loaded (if + /// `wayland-cursor` is not available). + /// + /// If this is done as an answer to an input event, you need to provide + /// the associated serial otherwise the server may ignore the request. + pub fn set_cursor_with_scale( + &self, + name: &str, + scale: u32, + serial: Option, + ) -> Result<(), ()> { + match *self { + AutoPointer::Themed(ref themed) => themed.set_cursor_with_scale(name, scale, serial), + AutoPointer::UnThemed(_) => Ok(()), + } + } } impl Deref for AutoPointer { - type Target = Proxy; - fn deref(&self) -> &Proxy { + type Target = wl_pointer::WlPointer; + fn deref(&self) -> &wl_pointer::WlPointer { match *self { AutoPointer::Themed(ref themed) => &**themed, AutoPointer::UnThemed(ref ptr) => ptr, diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/theme.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/theme.rs similarity index 57% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/theme.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/theme.rs index bf5156c..7a4f98a 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/pointer/theme.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/pointer/theme.rs @@ -1,13 +1,58 @@ use std::ops::Deref; use std::sync::{Arc, Mutex}; -use wayland_client::cursor::{is_available, load_theme, CursorTheme}; -use wayland_client::protocol::{wl_compositor, wl_pointer, wl_seat, wl_shm, wl_surface}; -use wayland_client::{NewProxy, Proxy, QueueToken}; -use wayland_client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use wayland_client::protocol::wl_pointer::RequestsTrait as PointerRequests; -use wayland_client::protocol::wl_seat::RequestsTrait as SeatRequests; -use wayland_client::protocol::wl_surface::RequestsTrait as SurfaceRequests; +use wayland_client::cursor::{is_available, load_theme, Cursor, CursorTheme}; +use wayland_client::protocol::{wl_compositor, wl_pointer, wl_seat, wl_shm, wl_surface}; +use wayland_client::NewProxy; + +struct ScaledThemeList { + shm: wl_shm::WlShm, + name: Option, + size: u32, + themes: Vec<(u32, CursorTheme)>, +} + +impl ScaledThemeList { + fn new(mut name: Option, shm: wl_shm::WlShm) -> ScaledThemeList { + let size = std::env::var("XCURSOR_SIZE") + .ok() + .and_then(|size| size.parse().ok()) + .unwrap_or(24); + + if name.is_none() { + name = std::env::var("XCURSOR_THEME").ok().and_then(|name| { + if name.is_empty() { + None + } else { + Some(name) + } + }); + } + + ScaledThemeList { + shm, + name, + size, + themes: Vec::new(), + } + } + + fn get_cursor(&mut self, name: &str, scale: u32) -> Option { + // Check if we already loaded the theme for this scale factor + let opt_index = self.themes.iter().position(|&(s, _)| s == scale); + if let Some(idx) = opt_index { + self.themes[idx].1.get_cursor(name) + } else { + let new_theme = load_theme( + self.name.as_ref().map(|s| &s[..]), + self.size * scale, + &self.shm, + ); + self.themes.push((scale, new_theme)); + self.themes.last().unwrap().1.get_cursor(name) + } + } +} /// Wrapper managing a system theme for pointer images /// @@ -19,20 +64,21 @@ use wayland_client::protocol::wl_surface::RequestsTrait as SurfaceRequests; /// /// Note that it is however not `Send` nor `Sync` pub struct ThemeManager { - theme: Arc>, - compositor: Proxy, + theme: Arc>, + compositor: wl_compositor::WlCompositor, } impl ThemeManager { /// Load a system pointer theme /// - /// Will use the default theme of the system if name is `None`. + /// Will use the default theme of the system if name is `None` or `XCURSOR_THEME` is unset. + /// The size of the theme is controlled by `XCURSOR_SIZE` environment variable. /// /// Fails if `libwayland-cursor` is not available. pub fn init( name: Option<&str>, - compositor: Proxy, - shm: &Proxy, + compositor: wl_compositor::WlCompositor, + shm: &wl_shm::WlShm, ) -> Result { if !is_available() { return Err(()); @@ -40,15 +86,18 @@ impl ThemeManager { Ok(ThemeManager { compositor, - theme: Arc::new(Mutex::new(load_theme(name, 16, &shm))), + theme: Arc::new(Mutex::new(ScaledThemeList::new( + name.map(|name| name.to_owned()), + shm.clone(), + ))), }) } /// Wrap a pointer to theme it - pub fn theme_pointer(&self, pointer: Proxy) -> ThemedPointer { + pub fn theme_pointer(&self, pointer: wl_pointer::WlPointer) -> ThemedPointer { let surface = self .compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); ThemedPointer { pointer, @@ -64,20 +113,20 @@ impl ThemeManager { /// /// You need to provide an implementation as if implementing a `wl_pointer`, but /// it will receive as `meta` argument a `ThemedPointer` wrapping your pointer, - /// rather than a `Proxy`. + /// rather than a `WlPointer`. pub fn theme_pointer_with_impl( &self, - seat: &Proxy, + seat: &wl_seat::WlSeat, mut implementation: Impl, user_data: UD, ) -> ThemedPointer where - Impl: FnMut(wl_pointer::Event, ThemedPointer) + Send + 'static, - UD: Send + Sync + 'static, + Impl: FnMut(wl_pointer::Event, ThemedPointer) + 'static, + UD: 'static, { let surface = self .compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); let inner = Arc::new(Mutex::new(PointerInner { @@ -89,7 +138,7 @@ impl ThemeManager { let pointer = seat .get_pointer(|pointer| { - pointer.implement( + pointer.implement_closure( move |event, ptr| { implementation( event, @@ -109,71 +158,23 @@ impl ThemeManager { inner: inner2, } } - - /// Initialize a new pointer as a ThemedPointer with an adapter implementation - /// - /// Like `theme_pointer_with_impl` but allows you to have a non-`Send` implementation. - /// - /// **Unsafe** for the same reasons as `NewProxy::implement_nonsend`. - pub unsafe fn theme_pointer_with_nonsend_impl( - &self, - pointer: NewProxy, - mut implementation: Impl, - user_data: UD, - token: &QueueToken, - ) -> ThemedPointer - where - Impl: FnMut(wl_pointer::Event, ThemedPointer) + 'static, - UD: Send + Sync + 'static, - { - let surface = self - .compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) - .unwrap(); - - let inner = Arc::new(Mutex::new(PointerInner { - surface, - theme: self.theme.clone(), - last_serial: 0, - })); - let inner2 = inner.clone(); - - let pointer = pointer.implement_nonsend( - move |event, ptr| { - implementation( - event, - ThemedPointer { - pointer: ptr, - inner: inner.clone(), - }, - ) - }, - user_data, - token, - ); - - ThemedPointer { - pointer, - inner: inner2, - } - } } struct PointerInner { - surface: Proxy, - theme: Arc>, + surface: wl_surface::WlSurface, + theme: Arc>, last_serial: u32, } /// Wrapper of a themed pointer /// -/// You can access the underlying `Proxy` via +/// You can access the underlying `wl_pointer::WlPointer` via /// deref. It will *not* release the proxy when dropped. /// /// Just like `Proxy`, this is a `Rc`-like wrapper. You can clone it /// to have several handles to the same theming machinery of a pointer. pub struct ThemedPointer { - pointer: Proxy, + pointer: wl_pointer::WlPointer, inner: Arc>, } @@ -186,6 +187,23 @@ impl ThemedPointer { /// If this is done as an answer to an input event, you need to provide /// the associated serial otherwise the server may ignore the request. pub fn set_cursor(&self, name: &str, serial: Option) -> Result<(), ()> { + self.set_cursor_with_scale(name, 1, serial) + } + + /// Change the cursor to the given cursor name and apply the given scale to an underlying + /// cursor surface + /// + /// Possible names depend on the theme. Does nothing and returns + /// `Err(())` if given name is not available. + /// + /// If this is done as an answer to an input event, you need to provide + /// the associated serial otherwise the server may ignore the request. + pub fn set_cursor_with_scale( + &self, + name: &str, + scale: u32, + serial: Option, + ) -> Result<(), ()> { let mut inner = self.inner.lock().unwrap(); let PointerInner { ref theme, @@ -193,25 +211,27 @@ impl ThemedPointer { ref mut last_serial, } = *inner; - let theme = theme.lock().unwrap(); - let cursor = theme.get_cursor(name).ok_or(())?; + let mut theme = theme.lock().unwrap(); + let cursor = theme.get_cursor(name, scale).ok_or(())?; let buffer = cursor.frame_buffer(0).ok_or(())?; + let scale = scale as i32; let (w, h, hx, hy) = cursor .frame_info(0) - .map(|(w, h, hx, hy, _)| (w as i32, h as i32, hx as i32, hy as i32)) + .map(|(w, h, hx, hy, _)| (w as i32, h as i32, hx as i32 / scale, hy as i32 / scale)) .unwrap_or((0, 0, 0, 0)); if let Some(s) = serial { *last_serial = s; } + surface.set_buffer_scale(scale); surface.attach(Some(&buffer), 0, 0); - if surface.version() >= 4 { + if surface.as_ref().version() >= 4 { surface.damage_buffer(0, 0, w, h); } else { // surface is old and does not support damage_buffer, so we damage // in surface coordinates and hope it is not rescaled - surface.damage(0, 0, w, h); + surface.damage(0, 0, w / scale, h / scale); } surface.commit(); self.pointer.set_cursor(*last_serial, Some(surface), hx, hy); @@ -230,8 +250,8 @@ impl Clone for ThemedPointer { } impl Deref for ThemedPointer { - type Target = Proxy; - fn deref(&self) -> &Proxy { + type Target = wl_pointer::WlPointer; + fn deref(&self) -> &wl_pointer::WlPointer { &self.pointer } } diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/mod.rs similarity index 90% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/mod.rs index ff9165d..fae482f 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/mod.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/mod.rs @@ -8,7 +8,6 @@ //! looking for a more battery-included abstraction for creating windows, //! consider the `Window` type. use wayland_client::protocol::{wl_output, wl_seat, wl_surface}; -use wayland_client::Proxy; use wayland_protocols::xdg_shell::client::xdg_toplevel; pub use wayland_protocols::xdg_shell::client::xdg_toplevel::State; @@ -50,7 +49,7 @@ pub enum Event { pub(crate) fn create_shell_surface( shell: &Shell, - surface: &Proxy, + surface: &wl_surface::WlSurface, implem: Impl, ) -> Box where @@ -70,15 +69,15 @@ where /// provided for older protocols. pub trait ShellSurface: Send + Sync { /// Resizes the shell surface - fn resize(&self, seat: &Proxy, serial: u32, edges: xdg_toplevel::ResizeEdge); + fn resize(&self, seat: &wl_seat::WlSeat, serial: u32, edges: xdg_toplevel::ResizeEdge); /// Moves the shell surface - fn move_(&self, seat: &Proxy, serial: u32); + fn move_(&self, seat: &wl_seat::WlSeat, serial: u32); /// Set the title of the shell surface fn set_title(&self, title: String); /// Set the app id of the shell surface fn set_app_id(&self, app_id: String); /// Make fullscreen - fn set_fullscreen(&self, output: Option<&Proxy>); + fn set_fullscreen(&self, output: Option<&wl_output::WlOutput>); /// Unset fullscreen fn unset_fullscreen(&self); /// Maximize surface @@ -98,5 +97,5 @@ pub trait ShellSurface: Send + Sync { /// /// This allows interactions with other protocol extensions, like /// `xdg_decoratins` for example. - fn get_xdg(&self) -> Option<&Proxy>; + fn get_xdg(&self) -> Option<&xdg_toplevel::XdgToplevel>; } diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/wl.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/wl.rs similarity index 80% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/wl.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/wl.rs index f3bfda6..6e604da 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/wl.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/wl.rs @@ -1,21 +1,17 @@ use wayland_client::protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface}; -use wayland_client::Proxy; - -use wayland_client::protocol::wl_shell::RequestsTrait as ShellRequests; -use wayland_client::protocol::wl_shell_surface::RequestsTrait as ShellSurfaceRequests; use wayland_protocols::xdg_shell::client::xdg_toplevel; use super::{Event, ShellSurface}; pub(crate) struct Wl { - shell_surface: Proxy, + shell_surface: wl_shell_surface::WlShellSurface, } impl Wl { pub(crate) fn create( - surface: &Proxy, - shell: &Proxy, + surface: &wl_surface::WlSurface, + shell: &wl_shell::WlShell, mut implementation: Impl, ) -> Wl where @@ -23,8 +19,8 @@ impl Wl { { let shell_surface = shell .get_shell_surface(surface, |shell_surface| { - shell_surface.implement( - move |event, shell_surface: Proxy<_>| match event { + shell_surface.implement_closure( + move |event, shell_surface| match event { wl_shell_surface::Event::Ping { serial } => { shell_surface.pong(serial); } @@ -38,6 +34,7 @@ impl Wl { wl_shell_surface::Event::PopupDone => { unreachable!(); } + _ => unreachable!(), }, (), ) @@ -49,7 +46,7 @@ impl Wl { } impl ShellSurface for Wl { - fn resize(&self, seat: &Proxy, serial: u32, edges: xdg_toplevel::ResizeEdge) { + fn resize(&self, seat: &wl_seat::WlSeat, serial: u32, edges: xdg_toplevel::ResizeEdge) { let edges = match edges { xdg_toplevel::ResizeEdge::None => wl_shell_surface::Resize::None, xdg_toplevel::ResizeEdge::Top => wl_shell_surface::Resize::Top, @@ -60,11 +57,12 @@ impl ShellSurface for Wl { xdg_toplevel::ResizeEdge::TopRight => wl_shell_surface::Resize::TopRight, xdg_toplevel::ResizeEdge::BottomLeft => wl_shell_surface::Resize::BottomLeft, xdg_toplevel::ResizeEdge::BottomRight => wl_shell_surface::Resize::BottomRight, + _ => unreachable!(), }; self.shell_surface.resize(seat, serial, edges); } - fn move_(&self, seat: &Proxy, serial: u32) { + fn move_(&self, seat: &wl_seat::WlSeat, serial: u32) { self.shell_surface._move(seat, serial); } @@ -75,7 +73,7 @@ impl ShellSurface for Wl { fn set_app_id(&self, app_id: String) { self.shell_surface.set_class(app_id); } - fn set_fullscreen(&self, output: Option<&Proxy>) { + fn set_fullscreen(&self, output: Option<&wl_output::WlOutput>) { self.shell_surface .set_fullscreen(wl_shell_surface::FullscreenMethod::Default, 0, output) } @@ -108,7 +106,7 @@ impl ShellSurface for Wl { /* not available */ } - fn get_xdg(&self) -> Option<&Proxy> { + fn get_xdg(&self) -> Option<&xdg_toplevel::XdgToplevel> { None } } diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/xdg.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/xdg.rs similarity index 67% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/xdg.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/xdg.rs index 71981fc..0afe1d4 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/xdg.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/xdg.rs @@ -1,47 +1,60 @@ +use std::cell::RefCell; +use std::rc::Rc; + use wayland_client::protocol::{wl_output, wl_seat, wl_surface}; -use wayland_client::Proxy; use wayland_protocols::xdg_shell::client::{xdg_surface, xdg_toplevel, xdg_wm_base}; -use wayland_client::protocol::wl_surface::RequestsTrait as WlSurfaceRequests; -use wayland_protocols::xdg_shell::client::xdg_surface::RequestsTrait as SurfaceRequests; -use wayland_protocols::xdg_shell::client::xdg_toplevel::RequestsTrait as ToplevelRequests; -use wayland_protocols::xdg_shell::client::xdg_wm_base::RequestsTrait as ShellRequests; - use super::{Event, ShellSurface}; pub(crate) struct Xdg { - surface: Proxy, - toplevel: Proxy, + surface: xdg_surface::XdgSurface, + toplevel: xdg_toplevel::XdgToplevel, } impl Xdg { pub(crate) fn create( - surface: &Proxy, - shell: &Proxy, - mut implementation: Impl, + surface: &wl_surface::WlSurface, + shell: &xdg_wm_base::XdgWmBase, + implementation: Impl, ) -> Xdg where - Impl: FnMut(Event) + Send + 'static, + Impl: FnMut(Event) + 'static, { + let pending_configure = Rc::new(RefCell::new(None)); + let pending_configure_2 = pending_configure.clone(); + + let implementation = Rc::new(RefCell::new(implementation)); + let implementation_2 = implementation.clone(); let xdgs = shell - .get_xdg_surface(surface, |xdgs| { - xdgs.implement( - |evt, xdgs: Proxy<_>| match evt { + .get_xdg_surface(surface, move |xdgs| { + xdgs.implement_closure( + move |evt, xdgs| match evt { xdg_surface::Event::Configure { serial } => { xdgs.ack_configure(serial); + if let Some((new_size, states)) = + pending_configure_2.borrow_mut().take() + { + (&mut *implementation_2.borrow_mut())(Event::Configure { + new_size, + states, + }); + } } + _ => unreachable!(), }, (), ) }) .unwrap(); let toplevel = xdgs - .get_toplevel(|toplevel| { - toplevel.implement( + .get_toplevel(move |toplevel| { + toplevel.implement_closure( move |evt, _| { match evt { - xdg_toplevel::Event::Close => implementation(Event::Close), + xdg_toplevel::Event::Close => { + (&mut *implementation.borrow_mut())(Event::Close) + } xdg_toplevel::Event::Configure { width, height, @@ -65,8 +78,9 @@ impl Xdg { .cloned() .flat_map(xdg_toplevel::State::from_raw) .collect::>(); - implementation(Event::Configure { new_size, states }); + *pending_configure.borrow_mut() = Some((new_size, states)); } + _ => unreachable!(), } }, (), @@ -82,11 +96,11 @@ impl Xdg { } impl ShellSurface for Xdg { - fn resize(&self, seat: &Proxy, serial: u32, edges: xdg_toplevel::ResizeEdge) { + fn resize(&self, seat: &wl_seat::WlSeat, serial: u32, edges: xdg_toplevel::ResizeEdge) { self.toplevel.resize(seat, serial, edges as u32); } - fn move_(&self, seat: &Proxy, serial: u32) { + fn move_(&self, seat: &wl_seat::WlSeat, serial: u32) { self.toplevel._move(seat, serial); } @@ -98,7 +112,7 @@ impl ShellSurface for Xdg { self.toplevel.set_app_id(app_id); } - fn set_fullscreen(&self, output: Option<&Proxy>) { + fn set_fullscreen(&self, output: Option<&wl_output::WlOutput>) { self.toplevel.set_fullscreen(output) } @@ -138,7 +152,7 @@ impl ShellSurface for Xdg { } } - fn get_xdg(&self) -> Option<&Proxy> { + fn get_xdg(&self) -> Option<&xdg_toplevel::XdgToplevel> { Some(&self.toplevel) } } diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/zxdg.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/zxdg.rs similarity index 69% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/zxdg.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/zxdg.rs index 8576e66..53fbd3d 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/shell/zxdg.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/shell/zxdg.rs @@ -1,40 +1,50 @@ +use std::cell::RefCell; +use std::rc::Rc; + use wayland_client::protocol::{wl_output, wl_seat, wl_surface}; -use wayland_client::Proxy; use wayland_protocols::unstable::xdg_shell::v6::client::{ zxdg_shell_v6, zxdg_surface_v6, zxdg_toplevel_v6, }; use wayland_protocols::xdg_shell::client::xdg_toplevel; -use self::zxdg_shell_v6_proto::zxdg_shell_v6::RequestsTrait as ShellRequests; -use self::zxdg_shell_v6_proto::zxdg_surface_v6::RequestsTrait as SurfaceRequests; -use self::zxdg_shell_v6_proto::zxdg_toplevel_v6::RequestsTrait as ToplevelRequests; -use wayland_client::protocol::wl_surface::RequestsTrait as WlSurfaceRequests; -use wayland_protocols::unstable::xdg_shell::v6::client as zxdg_shell_v6_proto; - use super::{Event, ShellSurface}; pub(crate) struct Zxdg { - surface: Proxy, - toplevel: Proxy, + surface: zxdg_surface_v6::ZxdgSurfaceV6, + toplevel: zxdg_toplevel_v6::ZxdgToplevelV6, } impl Zxdg { pub(crate) fn create( - surface: &Proxy, - shell: &Proxy, - mut implementation: Impl, + surface: &wl_surface::WlSurface, + shell: &zxdg_shell_v6::ZxdgShellV6, + implementation: Impl, ) -> Zxdg where Impl: FnMut(Event) + Send + 'static, { + let pending_configure = Rc::new(RefCell::new(None)); + let pending_configure_2 = pending_configure.clone(); + + let implementation = Rc::new(RefCell::new(implementation)); + let implementation_2 = implementation.clone(); let xdgs = shell - .get_xdg_surface(surface, |xdgs| { - xdgs.implement( - |evt, xdgs: Proxy<_>| match evt { + .get_xdg_surface(surface, move |xdgs| { + xdgs.implement_closure( + move |evt, xdgs| match evt { zxdg_surface_v6::Event::Configure { serial } => { xdgs.ack_configure(serial); + if let Some((new_size, states)) = + pending_configure_2.borrow_mut().take() + { + (&mut *implementation_2.borrow_mut())(Event::Configure { + new_size, + states, + }); + } } + _ => unreachable!(), }, (), ) @@ -42,10 +52,12 @@ impl Zxdg { .unwrap(); let toplevel = xdgs .get_toplevel(|toplevel| { - toplevel.implement( + toplevel.implement_closure( move |evt, _| { match evt { - zxdg_toplevel_v6::Event::Close => implementation(Event::Close), + zxdg_toplevel_v6::Event::Close => { + (&mut *implementation.borrow_mut())(Event::Close) + } zxdg_toplevel_v6::Event::Configure { width, height, @@ -70,8 +82,9 @@ impl Zxdg { // bit representation of xdg_toplevel_v6 and zxdg_toplevel_v6 matches .flat_map(xdg_toplevel::State::from_raw) .collect::>(); - implementation(Event::Configure { new_size, states }); + *pending_configure.borrow_mut() = Some((new_size, states)); } + _ => unreachable!(), } }, (), @@ -87,11 +100,11 @@ impl Zxdg { } impl ShellSurface for Zxdg { - fn resize(&self, seat: &Proxy, serial: u32, edges: xdg_toplevel::ResizeEdge) { + fn resize(&self, seat: &wl_seat::WlSeat, serial: u32, edges: xdg_toplevel::ResizeEdge) { self.toplevel.resize(seat, serial, edges as u32); } - fn move_(&self, seat: &Proxy, serial: u32) { + fn move_(&self, seat: &wl_seat::WlSeat, serial: u32) { self.toplevel._move(seat, serial); } @@ -103,7 +116,7 @@ impl ShellSurface for Zxdg { self.toplevel.set_app_id(app_id); } - fn set_fullscreen(&self, output: Option<&Proxy>) { + fn set_fullscreen(&self, output: Option<&wl_output::WlOutput>) { self.toplevel.set_fullscreen(output) } @@ -143,7 +156,7 @@ impl ShellSurface for Zxdg { } } - fn get_xdg(&self) -> Option<&Proxy> { + fn get_xdg(&self) -> Option<&xdg_toplevel::XdgToplevel> { None } } diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/surface.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/surface.rs similarity index 65% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/surface.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/surface.rs index efe9a8a..0b9328f 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/surface.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/surface.rs @@ -2,21 +2,19 @@ use env::Environment; use output::OutputMgr; use std::sync::Mutex; -use wayland_client::protocol::wl_compositor::RequestsTrait as CompositorRequest; use wayland_client::protocol::{wl_output, wl_surface}; -use wayland_client::Proxy; pub(crate) struct SurfaceUserData { dpi_factor: i32, - outputs: Vec>, + outputs: Vec, output_manager: OutputMgr, - dpi_change_cb: Box) + Send + 'static>, + dpi_change_cb: Box, } impl SurfaceUserData { fn new( output_manager: OutputMgr, - dpi_change_cb: Box) + Send + 'static>, + dpi_change_cb: Box, ) -> Self { SurfaceUserData { dpi_factor: 1, @@ -26,25 +24,18 @@ impl SurfaceUserData { } } - pub(crate) fn enter( - &mut self, - output: Proxy, - surface: Proxy, - ) { + pub(crate) fn enter(&mut self, output: wl_output::WlOutput, surface: wl_surface::WlSurface) { self.outputs.push(output); self.compute_dpi_factor(surface); } - pub(crate) fn leave( - &mut self, - output: &Proxy, - surface: Proxy, - ) { - self.outputs.retain(|output2| !output.equals(output2)); + pub(crate) fn leave(&mut self, output: &wl_output::WlOutput, surface: wl_surface::WlSurface) { + self.outputs + .retain(|output2| !output.as_ref().equals(output2.as_ref())); self.compute_dpi_factor(surface); } - fn compute_dpi_factor(&mut self, surface: Proxy) { + fn compute_dpi_factor(&mut self, surface: wl_surface::WlSurface) { let mut scale_factor = 1; for output in &self.outputs { if let Some(scale_factor2) = self @@ -64,22 +55,22 @@ impl SurfaceUserData { /// Creates a WlSurface from an Environment. /// /// Computes the dpi factor by taking the maximum dpi value of all the outputs -/// the surface is displayed on. The dpi factor is stored in the Proxy's user -/// data. When the dpi value is updated the caller is notified through the -/// dpi_change closure. +/// the surface is displayed on. When the dpi value is updated the caller is +/// notified through the dpi_change closure. pub(crate) fn create_surface( environment: &Environment, dpi_change: Box, -) -> Proxy +) -> wl_surface::WlSurface where - F: FnMut(i32, Proxy) + Send + 'static, + F: FnMut(i32, wl_surface::WlSurface) + Send + 'static, { environment .compositor .create_surface(move |surface| { - surface.implement( + surface.implement_closure_threadsafe( move |event, surface| { let mut user_data = surface + .as_ref() .user_data::>() .unwrap() .lock() @@ -91,6 +82,7 @@ where wl_surface::Event::Leave { output } => { user_data.leave(&output, surface.clone()); } + _ => unreachable!(), }; }, Mutex::new(SurfaceUserData::new( @@ -103,8 +95,9 @@ where } /// Returns the current dpi factor of a surface. -pub fn get_dpi_factor(surface: &Proxy) -> i32 { +pub fn get_dpi_factor(surface: &wl_surface::WlSurface) -> i32 { surface + .as_ref() .user_data::>() .expect("Surface was not created with create_surface.") .lock() @@ -112,9 +105,20 @@ pub fn get_dpi_factor(surface: &Proxy) -> i32 { .dpi_factor } +/// Returns the current dpi factor of a surface if it was created by SCTK or falling back to 1 if +/// it's not. +pub(crate) fn try_get_dpi_factor(surface: &wl_surface::WlSurface) -> Option { + if let Some(user_data) = surface.as_ref().user_data::>() { + Some(user_data.lock().unwrap().dpi_factor) + } else { + None + } +} + /// Returns a list of outputs the surface is displayed on. -pub fn get_outputs(surface: &Proxy) -> Vec> { +pub fn get_outputs(surface: &wl_surface::WlSurface) -> Vec { surface + .as_ref() .user_data::>() .expect("Surface was not created with create_surface.") .lock() diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/utils/mempool.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/utils/mempool.rs similarity index 93% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/utils/mempool.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/utils/mempool.rs index 6c4d53c..c45c439 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/utils/mempool.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/utils/mempool.rs @@ -18,11 +18,7 @@ use std::time::UNIX_EPOCH; use memmap::MmapMut; use wayland_client::protocol::{wl_buffer, wl_shm, wl_shm_pool}; -use wayland_client::Proxy; - -use wayland_client::protocol::wl_buffer::RequestsTrait; -use wayland_client::protocol::wl_shm::RequestsTrait as ShmRequests; -use wayland_client::protocol::wl_shm_pool::RequestsTrait as PoolRequests; +use wayland_client::NewProxy; /// A Double memory pool, for convenient double-buffering /// @@ -41,7 +37,7 @@ pub struct DoubleMemPool { impl DoubleMemPool { /// Create a double memory pool - pub fn new(shm: &Proxy, implementation: Impl) -> io::Result + pub fn new(shm: &wl_shm::WlShm, implementation: Impl) -> io::Result where Impl: FnMut() + Send + 'static, { @@ -104,7 +100,7 @@ impl DoubleMemPool { pub struct MemPool { file: File, len: usize, - pool: Proxy, + pool: wl_shm_pool::WlShmPool, buffer_count: Arc>, mmap: MmapMut, implementation: Arc>, @@ -112,7 +108,7 @@ pub struct MemPool { impl MemPool { /// Create a new memory pool associated with given shm - pub fn new(shm: &Proxy, implementation: Impl) -> io::Result + pub fn new(shm: &wl_shm::WlShm, implementation: Impl) -> io::Result where Impl: FnMut() + Send + 'static, { @@ -121,7 +117,7 @@ impl MemPool { mem_file.set_len(128)?; let pool = shm - .create_pool(mem_fd, 128, |pool| pool.implement(|e, _| match e {}, ())) + .create_pool(mem_fd, 128, NewProxy::implement_dummy) .unwrap(); let mmap = unsafe { MmapMut::map_mut(&mem_file).unwrap() }; @@ -176,14 +172,14 @@ impl MemPool { height: i32, stride: i32, format: wl_shm::Format, - ) -> Proxy { + ) -> wl_buffer::WlBuffer { *self.buffer_count.lock().unwrap() += 1; let my_buffer_count = self.buffer_count.clone(); let my_implementation = self.implementation.clone(); self.pool .create_buffer(offset, width, height, stride, format, |buffer| { - buffer.implement( - move |event, buffer: Proxy| match event { + buffer.implement_closure( + move |event, buffer: wl_buffer::WlBuffer| match event { wl_buffer::Event::Release => { buffer.destroy(); let mut my_buffer_count = my_buffer_count.lock().unwrap(); @@ -192,6 +188,7 @@ impl MemPool { (&mut *my_implementation.lock().unwrap())(); } } + _ => unreachable!(), }, (), ) diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/utils/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/utils/mod.rs similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/utils/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/utils/mod.rs diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/basic_frame.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/basic_frame.rs similarity index 94% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/basic_frame.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/basic_frame.rs index bb3d2ca..ee00528 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/basic_frame.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/basic_frame.rs @@ -10,13 +10,7 @@ use andrew::{Canvas, Endian}; use wayland_client::protocol::{ wl_compositor, wl_pointer, wl_seat, wl_shm, wl_subcompositor, wl_subsurface, wl_surface, }; -use wayland_client::Proxy; - -use wayland_client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use wayland_client::protocol::wl_pointer::RequestsTrait as PointerRequests; -use wayland_client::protocol::wl_subcompositor::RequestsTrait as SubcompRequests; -use wayland_client::protocol::wl_subsurface::RequestsTrait as SubsurfaceRequests; -use wayland_client::protocol::wl_surface::RequestsTrait as SurfaceRequests; +use wayland_client::NewProxy; use super::{ButtonState, Frame, FrameRequest, Theme}; use pointer::{AutoPointer, AutoThemer}; @@ -106,23 +100,21 @@ enum UIButton { } struct Part { - surface: Proxy, - subsurface: Proxy, + surface: wl_surface::WlSurface, + subsurface: wl_subsurface::WlSubsurface, } impl Part { fn new( - parent: &Proxy, - compositor: &Proxy, - subcompositor: &Proxy, + parent: &wl_surface::WlSurface, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, ) -> Part { let surface = compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); let subsurface = subcompositor - .get_subsurface(&surface, parent, |subsurface| { - subsurface.implement(|_, _| {}, ()) - }) + .get_subsurface(&surface, parent, NewProxy::implement_dummy) .unwrap(); Part { surface, @@ -141,7 +133,7 @@ impl Drop for Part { struct PointerUserData { location: Location, position: (f64, f64), - seat: Proxy, + seat: wl_seat::WlSeat, } /* @@ -157,16 +149,19 @@ struct Inner { } impl Inner { - fn find_surface(&self, surface: &Proxy) -> Location { - if surface.equals(&self.parts[HEAD].surface) { + fn find_surface(&self, surface: &wl_surface::WlSurface) -> Location { + if surface.as_ref().equals(&self.parts[HEAD].surface.as_ref()) { Location::Head - } else if surface.equals(&self.parts[TOP].surface) { + } else if surface.as_ref().equals(&self.parts[TOP].surface.as_ref()) { Location::Top - } else if surface.equals(&self.parts[BOTTOM].surface) { + } else if surface + .as_ref() + .equals(&self.parts[BOTTOM].surface.as_ref()) + { Location::Bottom - } else if surface.equals(&self.parts[LEFT].surface) { + } else if surface.as_ref().equals(&self.parts[LEFT].surface.as_ref()) { Location::Left - } else if surface.equals(&self.parts[RIGHT].surface) { + } else if surface.as_ref().equals(&self.parts[RIGHT].surface.as_ref()) { Location::Right } else { Location::None @@ -249,10 +244,10 @@ pub struct BasicFrame { impl Frame for BasicFrame { type Error = ::std::io::Error; fn init( - base_surface: &Proxy, - compositor: &Proxy, - subcompositor: &Proxy, - shm: &Proxy, + base_surface: &wl_surface::WlSurface, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, + shm: &wl_shm::WlShm, implementation: Box, ) -> Result { let parts = [ @@ -282,20 +277,20 @@ impl Frame for BasicFrame { hidden: false, pointers: Vec::new(), themer: AutoThemer::init(None, compositor.clone(), &shm), - surface_version: compositor.version(), + surface_version: compositor.as_ref().version(), theme: Box::new(DefaultTheme), title: None, font_data: None, }) } - fn new_seat(&mut self, seat: &Proxy) { + fn new_seat(&mut self, seat: &wl_seat::WlSeat) { use self::wl_pointer::Event; let inner = self.inner.clone(); let pointer = self.themer.theme_pointer_with_impl( seat, move |event, pointer: AutoPointer| { - let data: &Mutex = pointer.user_data().unwrap(); + let data: &Mutex = pointer.as_ref().user_data().unwrap(); let data = &mut *data.lock().unwrap(); let (width, _) = *(inner.size.lock().unwrap()); let resizable = *(inner.resizable.lock().unwrap()); @@ -471,8 +466,9 @@ impl Frame for BasicFrame { .pointers .iter() .flat_map(|p| { - if p.is_alive() { - let data: &Mutex = p.user_data().unwrap(); + if p.as_ref().is_alive() { + let data: &Mutex = + p.as_ref().user_data().unwrap(); Some(data.lock().unwrap().location) } else { None @@ -747,7 +743,7 @@ impl Frame for BasicFrame { impl Drop for BasicFrame { fn drop(&mut self) { for ptr in self.pointers.drain(..) { - if ptr.version() >= 3 { + if ptr.as_ref().version() >= 3 { ptr.release(); } } @@ -773,7 +769,7 @@ fn change_pointer(pointer: &AutoPointer, location: Location, serial: Option fn request_for_location( location: Location, - seat: &Proxy, + seat: &wl_seat::WlSeat, maximized: bool, resizable: bool, ) -> Option { diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/concept_frame.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/concept_frame.rs similarity index 65% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/concept_frame.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/concept_frame.rs index 43857ba..70f881d 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/concept_frame.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/concept_frame.rs @@ -11,15 +11,10 @@ use andrew::{Canvas, Endian}; use wayland_client::protocol::{ wl_compositor, wl_pointer, wl_seat, wl_shm, wl_subcompositor, wl_subsurface, wl_surface, }; -use wayland_client::Proxy; - -use wayland_client::protocol::wl_compositor::RequestsTrait as CompositorRequests; -use wayland_client::protocol::wl_pointer::RequestsTrait as PointerRequests; -use wayland_client::protocol::wl_subcompositor::RequestsTrait as SubcompRequests; -use wayland_client::protocol::wl_subsurface::RequestsTrait as SubsurfaceRequests; -use wayland_client::protocol::wl_surface::RequestsTrait as SurfaceRequests; +use wayland_client::NewProxy; use super::{ButtonState, Frame, FrameRequest, Theme}; +use crate::surface; use pointer::{AutoPointer, AutoThemer}; use utils::DoubleMemPool; @@ -108,23 +103,21 @@ enum UIButton { } struct Part { - surface: Proxy, - subsurface: Proxy, + surface: wl_surface::WlSurface, + subsurface: wl_subsurface::WlSubsurface, } impl Part { fn new( - parent: &Proxy, - compositor: &Proxy, - subcompositor: &Proxy, + parent: &wl_surface::WlSurface, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, ) -> Part { let surface = compositor - .create_surface(|surface| surface.implement(|_, _| {}, ())) + .create_surface(NewProxy::implement_dummy) .unwrap(); let subsurface = subcompositor - .get_subsurface(&surface, parent, |subsurface| { - subsurface.implement(|_, _| {}, ()) - }) + .get_subsurface(&surface, parent, NewProxy::implement_dummy) .unwrap(); Part { surface, @@ -143,7 +136,7 @@ impl Drop for Part { struct PointerUserData { location: Location, position: (f64, f64), - seat: Proxy, + seat: wl_seat::WlSeat, } /* @@ -159,16 +152,19 @@ struct Inner { } impl Inner { - fn find_surface(&self, surface: &Proxy) -> Location { - if surface.equals(&self.parts[HEAD].surface) { + fn find_surface(&self, surface: &wl_surface::WlSurface) -> Location { + if surface.as_ref().equals(&self.parts[HEAD].surface.as_ref()) { Location::Head - } else if surface.equals(&self.parts[TOP].surface) { + } else if surface.as_ref().equals(&self.parts[TOP].surface.as_ref()) { Location::Top - } else if surface.equals(&self.parts[BOTTOM].surface) { + } else if surface + .as_ref() + .equals(&self.parts[BOTTOM].surface.as_ref()) + { Location::Bottom - } else if surface.equals(&self.parts[LEFT].surface) { + } else if surface.as_ref().equals(&self.parts[LEFT].surface.as_ref()) { Location::Left - } else if surface.equals(&self.parts[RIGHT].surface) { + } else if surface.as_ref().equals(&self.parts[RIGHT].surface.as_ref()) { Location::Right } else { Location::None @@ -247,15 +243,16 @@ pub struct ConceptFrame { theme: Box, title: Option, font_data: Option>, + base_surface: wl_surface::WlSurface, } impl Frame for ConceptFrame { type Error = ::std::io::Error; fn init( - base_surface: &Proxy, - compositor: &Proxy, - subcompositor: &Proxy, - shm: &Proxy, + base_surface: &wl_surface::WlSurface, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, + shm: &wl_shm::WlShm, implementation: Box, ) -> Result { let parts = [ @@ -285,20 +282,22 @@ impl Frame for ConceptFrame { hidden: false, pointers: Vec::new(), themer: AutoThemer::init(None, compositor.clone(), &shm), - surface_version: compositor.version(), + surface_version: compositor.as_ref().version(), theme: Box::new(DefaultTheme), title: None, font_data: None, + base_surface: base_surface.clone(), }) } - fn new_seat(&mut self, seat: &Proxy) { + fn new_seat(&mut self, seat: &wl_seat::WlSeat) { use self::wl_pointer::Event; let inner = self.inner.clone(); + let base_surface = self.base_surface.clone(); let pointer = self.themer.theme_pointer_with_impl( seat, move |event, pointer: AutoPointer| { - let data: &Mutex = pointer.user_data().unwrap(); + let data: &Mutex = pointer.as_ref().user_data().unwrap(); let data = &mut *data.lock().unwrap(); let (width, _) = *(inner.size.lock().unwrap()); let resizable = *(inner.resizable.lock().unwrap()); @@ -317,12 +316,15 @@ impl Frame for ConceptFrame { ); data.position = (surface_x, surface_y); if resizable { - change_pointer(&pointer, data.location, Some(serial)) + let scale = + surface::try_get_dpi_factor(&base_surface).unwrap_or(1) as u32; + change_pointer(&pointer, scale, data.location, Some(serial)) } } Event::Leave { serial, .. } => { data.location = Location::None; - change_pointer(&pointer, data.location, Some(serial)); + let scale = surface::try_get_dpi_factor(&base_surface).unwrap_or(1) as u32; + change_pointer(&pointer, scale, data.location, Some(serial)); (&mut *inner.implem.lock().unwrap())(FrameRequest::Refresh, 0); } Event::Motion { @@ -344,7 +346,9 @@ impl Frame for ConceptFrame { // may need to be changed data.location = newpos; if resizable { - change_pointer(&pointer, data.location, None) + let scale = + surface::try_get_dpi_factor(&base_surface).unwrap_or(1) as u32; + change_pointer(&pointer, scale, data.location, None) } } } @@ -419,8 +423,23 @@ impl Frame for ConceptFrame { } return; } + + let scale = surface::try_get_dpi_factor(&self.base_surface).unwrap_or(1); + + // Update dpi scaling factor. + for p in &self.inner.parts { + p.surface.set_buffer_scale(scale as i32); + } + let (width, height) = *(self.inner.size.lock().unwrap()); + let scale = scale as u32; + + let scaled_header = HEADER_SIZE * scale; + let scaled_border = BORDER_SIZE * scale; + let scaled_width = scale * width; + let scaled_height = scale * height; + { // grab the current pool let pool = match self.pools.pool() { @@ -428,10 +447,10 @@ impl Frame for ConceptFrame { None => return, }; // resize the pool as appropriate - let pxcount = (HEADER_SIZE * width) + let pxcount = (scaled_header * scaled_width) + max( - (width + 2 * BORDER_SIZE) * BORDER_SIZE, - (height + HEADER_SIZE) * BORDER_SIZE, + (scaled_width + 2 * scaled_border) * scaled_border, + (scaled_height + scaled_header) * scaled_border, ); pool.resize(4 * pxcount as usize) @@ -444,17 +463,17 @@ impl Frame for ConceptFrame { let color = self.theme.get_primary_color(self.active); let mut header_canvas = Canvas::new( - &mut mmap[0..HEADER_SIZE as usize * width as usize * 4], - width as usize, - HEADER_SIZE as usize, - width as usize * 4, + &mut mmap[0..scaled_header as usize * scaled_width as usize * 4], + scaled_width as usize, + scaled_header as usize, + scaled_width as usize * 4, Endian::native(), ); header_canvas.clear(); let header_bar = rectangle::Rectangle::new( (0, 0), - (width as usize - 1, HEADER_SIZE as usize - 1), + (scaled_width as usize, scaled_header as usize), None, Some(color), ); @@ -463,13 +482,15 @@ impl Frame for ConceptFrame { draw_buttons( &mut header_canvas, width, + scale, true, &self .pointers .iter() .flat_map(|p| { - if p.is_alive() { - let data: &Mutex = p.user_data().unwrap(); + if p.as_ref().is_alive() { + let data: &Mutex = + p.as_ref().user_data().unwrap(); Some(data.lock().unwrap().location) } else { None @@ -488,12 +509,9 @@ impl Frame for ConceptFrame { .get_regular_family_fonts("sans") .unwrap() .iter() - .filter_map(|p| { - if p.extension().unwrap() == "ttf" { - Some(p) - } else { - None - } + .filter_map(|p| match p.extension() { + Some(e) if e == "ttf" => Some(p), + _ => None, }) .nth(0) { @@ -510,11 +528,11 @@ impl Frame for ConceptFrame { // Create text from stored title and font data if let Some(ref font_data) = self.font_data { let mut title_text = text::Text::new( - (0, HEADER_SIZE as usize / 2 - 8), + (0, (HEADER_SIZE as usize / 2 - 8) * scale as usize), [0, 0, 0, 255], font_data, - 17.0, - 1.0, + 17.0 * scale as f32, + 1.0 * scale as f32, title, ); @@ -522,15 +540,15 @@ impl Frame for ConceptFrame { if (width as isize - 88 - 4 * BUTTON_SPACE as isize) > (title_text.get_width() + BUTTON_SPACE as usize) as isize { - title_text.pos.0 = - (width as usize) / 2 - (title_text.get_width() / 2); + title_text.pos.0 = scale as usize + * ((width as usize) / 2 - (title_text.get_width() / 2)); // Adjust position for buttons if both compete for space if (width as usize) / 2 + (title_text.get_width() / 2) > (width - 88 - 2 * 2 * BUTTON_SPACE) as usize { - title_text.pos.0 -= ((width as usize) / 2 - + (title_text.get_width() / 2)) - - (width - 88 - 2 * 2 * BUTTON_SPACE) as usize; + title_text.pos.0 -= scale as usize + * (((width as usize) / 2 + (title_text.get_width() / 2)) + - (width - 88 - 2 * 2 * BUTTON_SPACE) as usize); } header_canvas.draw(&title_text); } @@ -540,7 +558,7 @@ impl Frame for ConceptFrame { // For each pixel in borders { - for b in &mut mmap[HEADER_SIZE as usize * width as usize * 4..] { + for b in &mut mmap[scaled_header as usize * scaled_width as usize * 4..] { *b = 0x00; } } @@ -556,9 +574,9 @@ impl Frame for ConceptFrame { // -> head-subsurface let buffer = pool.buffer( 0, - width as i32, - HEADER_SIZE as i32, - 4 * width as i32, + scaled_width as i32, + scaled_header as i32, + 4 * scaled_width as i32, wl_shm::Format::Argb8888, ); self.inner.parts[HEAD] @@ -569,8 +587,8 @@ impl Frame for ConceptFrame { self.inner.parts[HEAD].surface.damage_buffer( 0, 0, - width as i32, - HEADER_SIZE as i32, + scaled_width as i32, + scaled_header as i32, ); } else { // surface is old and does not support damage_buffer, so we damage @@ -583,10 +601,10 @@ impl Frame for ConceptFrame { // -> top-subsurface let buffer = pool.buffer( - 4 * (width * HEADER_SIZE) as i32, - (width + 2 * BORDER_SIZE) as i32, - BORDER_SIZE as i32, - 4 * (width + 2 * BORDER_SIZE) as i32, + 4 * (scaled_width * scaled_header) as i32, + (scaled_width + 2 * scaled_border) as i32, + scaled_border as i32, + 4 * (scaled_width + 2 * scaled_border) as i32, wl_shm::Format::Argb8888, ); self.inner.parts[TOP].subsurface.set_position( @@ -598,8 +616,8 @@ impl Frame for ConceptFrame { self.inner.parts[TOP].surface.damage_buffer( 0, 0, - (width + 2 * BORDER_SIZE) as i32, - BORDER_SIZE as i32, + (scaled_width + 2 * scaled_border) as i32, + scaled_border as i32, ); } else { // surface is old and does not support damage_buffer, so we damage @@ -615,10 +633,10 @@ impl Frame for ConceptFrame { // -> bottom-subsurface let buffer = pool.buffer( - 4 * (width * HEADER_SIZE) as i32, - (width + 2 * BORDER_SIZE) as i32, - BORDER_SIZE as i32, - 4 * (width + 2 * BORDER_SIZE) as i32, + 4 * (scaled_width * scaled_header) as i32, + (scaled_width + 2 * scaled_border) as i32, + scaled_border as i32, + 4 * (scaled_width + 2 * scaled_border) as i32, wl_shm::Format::Argb8888, ); self.inner.parts[BOTTOM] @@ -629,8 +647,8 @@ impl Frame for ConceptFrame { self.inner.parts[BOTTOM].surface.damage_buffer( 0, 0, - (width + 2 * BORDER_SIZE) as i32, - BORDER_SIZE as i32, + (scaled_width + 2 * scaled_border) as i32, + scaled_border as i32, ); } else { // surface is old and does not support damage_buffer, so we damage @@ -646,10 +664,10 @@ impl Frame for ConceptFrame { // -> left-subsurface let buffer = pool.buffer( - 4 * (width * HEADER_SIZE) as i32, - BORDER_SIZE as i32, - (height + HEADER_SIZE) as i32, - 4 * (BORDER_SIZE as i32), + 4 * (scaled_width * scaled_header) as i32, + scaled_border as i32, + (scaled_height + scaled_header) as i32, + 4 * (scaled_border as i32), wl_shm::Format::Argb8888, ); self.inner.parts[LEFT] @@ -660,8 +678,8 @@ impl Frame for ConceptFrame { self.inner.parts[LEFT].surface.damage_buffer( 0, 0, - BORDER_SIZE as i32, - (height + HEADER_SIZE) as i32, + scaled_border as i32, + (scaled_height + scaled_header) as i32, ); } else { // surface is old and does not support damage_buffer, so we damage @@ -677,10 +695,10 @@ impl Frame for ConceptFrame { // -> right-subsurface let buffer = pool.buffer( - 4 * (width * HEADER_SIZE) as i32, - BORDER_SIZE as i32, - (height + HEADER_SIZE) as i32, - 4 * (BORDER_SIZE as i32), + 4 * (scaled_width * scaled_header) as i32, + scaled_border as i32, + (scaled_height + scaled_header) as i32, + 4 * (scaled_border as i32), wl_shm::Format::Argb8888, ); self.inner.parts[RIGHT] @@ -691,8 +709,8 @@ impl Frame for ConceptFrame { self.inner.parts[RIGHT].surface.damage_buffer( 0, 0, - BORDER_SIZE as i32, - (height + HEADER_SIZE) as i32, + scaled_border as i32, + (scaled_height + scaled_height) as i32, ); } else { // surface is old and does not support damage_buffer, so we damage @@ -744,14 +762,14 @@ impl Frame for ConceptFrame { impl Drop for ConceptFrame { fn drop(&mut self) { for ptr in self.pointers.drain(..) { - if ptr.version() >= 3 { + if ptr.as_ref().version() >= 3 { ptr.release(); } } } } -fn change_pointer(pointer: &AutoPointer, location: Location, serial: Option) { +fn change_pointer(pointer: &AutoPointer, scale: u32, location: Location, serial: Option) { let name = match location { Location::Top => "top_side", Location::TopRight => "top_right_corner", @@ -763,14 +781,14 @@ fn change_pointer(pointer: &AutoPointer, location: Location, serial: Option Location::TopLeft => "top_left_corner", _ => "left_ptr", }; - if pointer.set_cursor(name, serial).is_err() { + if pointer.set_cursor_with_scale(name, scale, serial).is_err() { eprintln!("[SCTK] Basic frame: failed to set cursor"); } } fn request_for_location( location: Location, - seat: &Proxy, + seat: &wl_seat::WlSeat, maximized: bool, resizable: bool, ) -> Option { @@ -811,60 +829,97 @@ fn request_for_location( fn draw_buttons( canvas: &mut Canvas, width: u32, + scale: u32, maximizable: bool, mouses: &[Location], theme: &Theme, ) { - // Draw seperator between header and window contents - let division_line = line::Line::new( - (0, (HEADER_SIZE - 1) as usize), - ((width) as usize, (HEADER_SIZE - 1) as usize), - theme.get_secondary_color(false), - true, - ); - canvas.draw(&division_line); + let scale = scale as usize; - let button_color = theme.get_secondary_color(true); + // Draw seperator between header and window contents + + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let division_line = line::Line::new( + (0, y), + (width as usize * scale, y), + theme.get_secondary_color(false), + false, + ); + canvas.draw(&division_line); + } if width >= HEADER_SIZE { // Draw the red button + let mut button_color = theme.get_close_button_icon_color(ButtonState::Idle); if mouses .iter() .any(|&l| l == Location::Button(UIButton::Close)) { // Draw a red shading around close button if hovered over let red_shade = theme.get_close_button_color(ButtonState::Hovered); + // Change the button color (yet to be drawn) to the hovered version + button_color = theme.get_close_button_icon_color(ButtonState::Hovered); let red_hover = rectangle::Rectangle::new( - ((width - HEADER_SIZE) as usize, 0), - (HEADER_SIZE as usize, HEADER_SIZE as usize), + ((width - HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), None, Some(red_shade), ); canvas.draw(&red_hover); - let red_division_line = line::Line::new( - ((width - HEADER_SIZE) as usize, (HEADER_SIZE - 1) as usize), - ((width) as usize, (HEADER_SIZE - 1) as usize), - [ - red_shade[0].saturating_sub(50), - red_shade[1].saturating_sub(50), - red_shade[2].saturating_sub(50), - 255, - ], - true, + + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let red_division_line = line::Line::new( + ((width - HEADER_SIZE) as usize * scale, y), + ((width) as usize * scale, y), + [ + red_shade[0], + red_shade[1].saturating_sub(50), + red_shade[2].saturating_sub(50), + red_shade[3].saturating_sub(50), + ], + false, + ); + canvas.draw(&red_division_line); + } + } else { + // draw shading if around close button when idle + let red_shade = theme.get_close_button_color(ButtonState::Idle); + let red_hover = rectangle::Rectangle::new( + ((width - HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), + None, + Some(red_shade), ); - canvas.draw(&red_division_line); + canvas.draw(&red_hover); + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let red_division_line = line::Line::new( + ((width - HEADER_SIZE) as usize * scale, y), + ((width) as usize * scale, y), + [ + red_shade[0], + red_shade[1].saturating_sub(50), + red_shade[2].saturating_sub(50), + red_shade[3].saturating_sub(50), + ], + false, + ); + canvas.draw(&red_division_line); + } }; // Draw cross to represent the close button - for i in 0..2 { + for i in 0..2 * scale { let diagonal_line = line::Line::new( ( - (width - HEADER_SIZE / 2 - 4 + i) as usize, - (HEADER_SIZE / 2 - 4) as usize, + (width - HEADER_SIZE / 2 - 4) as usize * scale + i, + (HEADER_SIZE / 2 - 4) as usize * scale, ), ( - (width - HEADER_SIZE / 2 + 4) as usize, - (HEADER_SIZE / 2 + 4 - i) as usize, + (width - HEADER_SIZE / 2 + 4) as usize * scale, + (HEADER_SIZE / 2 + 4) as usize * scale - i, ), button_color, true, @@ -872,12 +927,12 @@ fn draw_buttons( canvas.draw(&diagonal_line); let diagonal_line = line::Line::new( ( - (width - HEADER_SIZE / 2 - 4) as usize, - (HEADER_SIZE / 2 - 4 + i) as usize, + (width - HEADER_SIZE / 2 - 4) as usize * scale, + (HEADER_SIZE / 2 - 4) as usize * scale + i, ), ( - (width - HEADER_SIZE / 2 + 4 - i) as usize, - (HEADER_SIZE / 2 + 4) as usize, + (width - HEADER_SIZE / 2 + 4) as usize * scale - i, + (HEADER_SIZE / 2 + 4) as usize * scale, ), button_color, true, @@ -885,12 +940,12 @@ fn draw_buttons( canvas.draw(&diagonal_line); let diagonal_line = line::Line::new( ( - (width - HEADER_SIZE / 2 + 4 - i) as usize, - (HEADER_SIZE / 2 - 4) as usize, + (width - HEADER_SIZE / 2 + 4) as usize * scale - i, + (HEADER_SIZE / 2 - 4) as usize * scale, ), ( - (width - HEADER_SIZE / 2 - 4) as usize, - (HEADER_SIZE / 2 + 4 - i) as usize, + (width - HEADER_SIZE / 2 - 4) as usize * scale, + (HEADER_SIZE / 2 + 4) as usize * scale - i, ), button_color, true, @@ -898,12 +953,12 @@ fn draw_buttons( canvas.draw(&diagonal_line); let diagonal_line = line::Line::new( ( - (width - HEADER_SIZE / 2 + 4) as usize, - (HEADER_SIZE / 2 - 4 + i) as usize, + (width - HEADER_SIZE / 2 + 4) as usize * scale, + (HEADER_SIZE / 2 - 4) as usize * scale + i, ), ( - (width - HEADER_SIZE / 2 - 4 + i) as usize, - (HEADER_SIZE / 2 + 4) as usize, + (width - HEADER_SIZE / 2 - 4) as usize * scale + i, + (HEADER_SIZE / 2 + 4) as usize * scale, ), button_color, true, @@ -914,6 +969,7 @@ fn draw_buttons( if width >= 2 * HEADER_SIZE { // Draw the green button + let mut button_color = theme.get_maximize_button_icon_color(ButtonState::Idle); if !maximizable { } else if mouses .iter() @@ -921,38 +977,69 @@ fn draw_buttons( { // Draw a green shading around maximize button if hovered over let green_shade = theme.get_maximize_button_color(ButtonState::Hovered); + // Change the button color (yet to be drawn) to the hovered version + button_color = theme.get_maximize_button_icon_color(ButtonState::Hovered); let green_hover = rectangle::Rectangle::new( - ((width - 2 * HEADER_SIZE) as usize, 0), - (HEADER_SIZE as usize, HEADER_SIZE as usize), + ((width - 2 * HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), None, Some(green_shade), ); canvas.draw(&green_hover); - let green_division_line = line::Line::new( - ( - (width - 2 * HEADER_SIZE) as usize, - (HEADER_SIZE - 1) as usize, - ), - ((width - HEADER_SIZE) as usize, (HEADER_SIZE - 1) as usize), - [ - green_shade[0].saturating_sub(50), - green_shade[1].saturating_sub(50), - green_shade[2].saturating_sub(50), - 255, - ], - true, + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let green_division_line = line::Line::new( + ((width - 2 * HEADER_SIZE) as usize * scale, y), + ((width - HEADER_SIZE) as usize * scale, y), + [ + green_shade[0], + green_shade[1].saturating_sub(50), + green_shade[2].saturating_sub(50), + green_shade[3].saturating_sub(50), + ], + false, + ); + + canvas.draw(&green_division_line); + } + } else { + // Draw a green shading around maximize button if idle + let green_shade = theme.get_maximize_button_color(ButtonState::Idle); + let green_hover = rectangle::Rectangle::new( + ((width - 2 * HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), + None, + Some(green_shade), ); - canvas.draw(&green_division_line); + + canvas.draw(&green_hover); + + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let green_division_line = line::Line::new( + ((width - 2 * HEADER_SIZE) as usize * scale, y), + ((width - HEADER_SIZE) as usize * scale, y), + [ + green_shade[0], + green_shade[1].saturating_sub(50), + green_shade[2].saturating_sub(50), + green_shade[3].saturating_sub(50), + ], + false, + ); + canvas.draw(&green_division_line); + } }; - for i in 0..3 { + + for i in 0..3 * scale { let left_diagional = line::Line::new( ( - (width - HEADER_SIZE - HEADER_SIZE / 2 - 4 - i) as usize, - (HEADER_SIZE / 2 + 2) as usize, + (width - HEADER_SIZE - HEADER_SIZE / 2 - 4) as usize * scale - i, + (HEADER_SIZE / 2 + 2) as usize * scale, ), ( - (width - HEADER_SIZE - HEADER_SIZE / 2) as usize, - (HEADER_SIZE / 2 - 2 - i) as usize, + (width - HEADER_SIZE - HEADER_SIZE / 2) as usize * scale, + (HEADER_SIZE / 2 - 2) as usize * scale - i, ), button_color, true, @@ -960,12 +1047,12 @@ fn draw_buttons( canvas.draw(&left_diagional); let right_diagional = line::Line::new( ( - (width - HEADER_SIZE - HEADER_SIZE / 2 + 4 + i) as usize, - (HEADER_SIZE / 2 + 2) as usize, + (width - HEADER_SIZE - HEADER_SIZE / 2 + 4) as usize * scale + i, + (HEADER_SIZE / 2 + 2) as usize * scale, ), ( - (width - HEADER_SIZE - HEADER_SIZE / 2) as usize, - (HEADER_SIZE / 2 - 2 - i) as usize, + (width - HEADER_SIZE - HEADER_SIZE / 2) as usize * scale, + (HEADER_SIZE / 2 - 2) as usize * scale - i, ), button_color, true, @@ -976,47 +1063,73 @@ fn draw_buttons( if width >= 3 * HEADER_SIZE { // Draw the blue button + let mut button_color = theme.get_minimize_button_icon_color(ButtonState::Idle); if mouses .iter() .any(|&l| l == Location::Button(UIButton::Minimize)) { // Draw a blue shading around minimize button if hovered over let blue_shade = theme.get_minimize_button_color(ButtonState::Hovered); + // Change the button color (yet to be drawn) to the hovered version + button_color = theme.get_minimize_button_icon_color(ButtonState::Hovered); let blue_hover = rectangle::Rectangle::new( - ((width - 3 * HEADER_SIZE) as usize, 0), - (HEADER_SIZE as usize, HEADER_SIZE as usize), + ((width - 3 * HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), None, Some(blue_shade), ); canvas.draw(&blue_hover); - let blue_division_line = line::Line::new( - ( - (width - 3 * HEADER_SIZE) as usize, - (HEADER_SIZE - 1) as usize, - ), - ( - (width - 2 * HEADER_SIZE) as usize, - (HEADER_SIZE - 1) as usize, - ), - [ - blue_shade[0].saturating_sub(50), - blue_shade[1].saturating_sub(50), - blue_shade[2].saturating_sub(50), - 255, - ], - true, + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let blue_division_line = line::Line::new( + ((width - 3 * HEADER_SIZE) as usize * scale, y), + ((width - 2 * HEADER_SIZE) as usize * scale, y), + [ + blue_shade[0], + blue_shade[1].saturating_sub(50), + blue_shade[2].saturating_sub(50), + blue_shade[3].saturating_sub(50), + ], + false, + ); + canvas.draw(&blue_division_line); + } + } else { + // Draw a blue shading around minimize button if idle + let blue_shade = theme.get_minimize_button_color(ButtonState::Idle); + let blue_hover = rectangle::Rectangle::new( + ((width - 3 * HEADER_SIZE) as usize * scale, 0), + (HEADER_SIZE as usize * scale, HEADER_SIZE as usize * scale), + None, + Some(blue_shade), ); - canvas.draw(&blue_division_line); + canvas.draw(&blue_hover); + for i in 1..=scale { + let y = HEADER_SIZE as usize * scale - i; + let blue_division_line = line::Line::new( + ((width - 3 * HEADER_SIZE) as usize * scale, y), + ((width - 2 * HEADER_SIZE) as usize * scale, y), + [ + blue_shade[0], + blue_shade[1].saturating_sub(50), + blue_shade[2].saturating_sub(50), + blue_shade[3].saturating_sub(50), + ], + false, + ); + canvas.draw(&blue_division_line); + } } - for i in 0..3 { + + for i in 0..3 * scale { let left_diagional = line::Line::new( ( - (width - 2 * HEADER_SIZE - HEADER_SIZE / 2 - 4 - i) as usize, - (HEADER_SIZE / 2 - 3) as usize, + (width - 2 * HEADER_SIZE - HEADER_SIZE / 2 - 4) as usize * scale - i, + (HEADER_SIZE / 2 - 3) as usize * scale, ), ( - (width - 2 * HEADER_SIZE - HEADER_SIZE / 2) as usize, - (HEADER_SIZE / 2 + 1 + i) as usize, + (width - 2 * HEADER_SIZE - HEADER_SIZE / 2) as usize * scale, + (HEADER_SIZE / 2 + 1) as usize * scale + i, ), button_color, true, @@ -1024,12 +1137,12 @@ fn draw_buttons( canvas.draw(&left_diagional); let right_diagional = line::Line::new( ( - (width - 2 * HEADER_SIZE - HEADER_SIZE / 2 + 4 + i) as usize, - (HEADER_SIZE / 2 - 3) as usize, + (width - 2 * HEADER_SIZE - HEADER_SIZE / 2 + 4) as usize * scale + i, + (HEADER_SIZE / 2 - 3) as usize * scale, ), ( - (width - 2 * HEADER_SIZE - HEADER_SIZE / 2) as usize, - (HEADER_SIZE / 2 + 1 + i) as usize, + (width - 2 * HEADER_SIZE - HEADER_SIZE / 2) as usize * scale, + (HEADER_SIZE / 2 + 1) as usize * scale + i, ), button_color, true, diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/mod.rs b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/mod.rs similarity index 83% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/mod.rs rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/mod.rs index ece8d45..4fee591 100644 --- a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/src/window/mod.rs +++ b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/src/window/mod.rs @@ -4,17 +4,16 @@ use std::sync::{Arc, Mutex}; use wayland_client::protocol::{ wl_compositor, wl_output, wl_seat, wl_shm, wl_subcompositor, wl_surface, }; -use wayland_client::Proxy; use wayland_protocols::xdg_shell::client::xdg_toplevel::ResizeEdge; pub use wayland_protocols::xdg_shell::client::xdg_toplevel::State; -use self::zxdg_decoration_manager_v1::RequestsTrait as DecorationMgrRequests; -use self::zxdg_toplevel_decoration_v1::RequestsTrait as DecorationRequests; use wayland_protocols::unstable::xdg_decoration::v1::client::{ zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1, }; +use self::zxdg_toplevel_decoration_v1::Mode as DecorationsMode; + use {Environment, Shell}; mod basic_frame; @@ -43,6 +42,14 @@ pub enum ButtonState { /// A type implementing this trait can be used to define custom /// themes to adjust the decorations provided by a type implementing /// the 'Frame' trait +/// +/// Note that the buttons will be drawn on top of the primary/secondary color. +/// As such if their alpha channel is not `255` some blending will occur. +/// +/// On `ConceptFrame`, setting the alpha channel to `0` thus makes the button +/// background the same color as the titlebar. +/// +/// All colors are to be specified in ARGB format. pub trait Theme: Send + 'static { /// Gets the primary color of the scheme, active when window is fn get_primary_color(&self, active: bool) -> [u8; 4]; @@ -50,10 +57,33 @@ pub trait Theme: Send + 'static { fn get_secondary_color(&self, active: bool) -> [u8; 4]; /// Gets the color for the close button, active when button is hovered over fn get_close_button_color(&self, status: ButtonState) -> [u8; 4]; - /// Gets the color for the maximize button, active when button is hovered over + /// Gets the icon color for the close button, this defaults to the + /// secondary color (for backwards compatibility) + fn get_close_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + match status { + _ => self.get_secondary_color(true), + } + } + /// Gets the background color for the maximize button, active when button is + /// hovered over fn get_maximize_button_color(&self, status: ButtonState) -> [u8; 4]; - /// Gets the color for the minimize button, active when button is hovered over + /// Gets the icon color for the maximize button, this defaults to the + /// secondary color (for backwards compatibility) + fn get_maximize_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + match status { + _ => self.get_secondary_color(true), + } + } + /// Gets the background color for the minimize button, active when button is + /// hovered over fn get_minimize_button_color(&self, status: ButtonState) -> [u8; 4]; + /// Gets the icon color for the minimize button, this defaults to the + /// secondary color (for backwards compatibility) + fn get_minimize_button_icon_color(&self, status: ButtonState) -> [u8; 4] { + match status { + _ => self.get_secondary_color(true), + } + } } /// Possible events generated by a window that you need to handle @@ -115,9 +145,9 @@ struct WindowInner { /// the `Frame` trait can do. pub struct Window { frame: Arc>, - surface: Proxy, - decoration: Mutex>>, - decoration_mgr: Option>, + surface: wl_surface::WlSurface, + decoration: Mutex>, + decoration_mgr: Option, shell_surface: Arc>, inner: Arc>>>, } @@ -127,7 +157,7 @@ impl Window { /// following the compositor's preference regarding server-side decorations. pub fn init_from_env( env: &Environment, - surface: Proxy, + surface: wl_surface::WlSurface, initial_dims: (u32, u32), implementation: Impl, ) -> Result, F::Error> @@ -151,11 +181,11 @@ impl Window { /// It can fail if the initialization of the frame fails (for example if the /// frame class fails to initialize its SHM). pub fn init( - surface: Proxy, + surface: wl_surface::WlSurface, initial_dims: (u32, u32), - compositor: &Proxy, - subcompositor: &Proxy, - shm: &Proxy, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, + shm: &wl_shm::WlShm, shell: &Shell, implementation: Impl, ) -> Result, F::Error> @@ -180,13 +210,13 @@ impl Window { /// It can fail if the initialization of the frame fails (for example if the /// frame class fails to initialize its SHM). pub fn init_with_decorations( - surface: Proxy, + surface: wl_surface::WlSurface, initial_dims: (u32, u32), - compositor: &Proxy, - subcompositor: &Proxy, - shm: &Proxy, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, + shm: &wl_shm::WlShm, shell: &Shell, - decoration_mgr: Option<&Proxy>, + decoration_mgr: Option<&zxdg_decoration_manager_v1::ZxdgDecorationManagerV1>, implementation: Impl, ) -> Result, F::Error> where @@ -307,14 +337,14 @@ impl Window { fn ensure_decoration( &self, - decoration: &mut Option>, + decoration: &mut Option, ) { if self.decoration_mgr.is_none() { return; } if let Some(ref decoration) = *decoration { - if decoration.is_alive() { + if decoration.as_ref().is_alive() { return; } } @@ -323,23 +353,25 @@ impl Window { let decoration_inner = self.inner.clone(); *decoration = match (self.shell_surface.get_xdg(), &self.decoration_mgr) { (Some(toplevel), &Some(ref mgr)) => { - use self::zxdg_toplevel_decoration_v1::{Event, Mode}; + use self::zxdg_toplevel_decoration_v1::Event; mgr.get_toplevel_decoration(toplevel, |newdec| { - newdec.implement( + newdec.implement_closure( move |event, _| { - let Event::Configure { mode } = event; - match mode { - Mode::ServerSide => { - decoration_frame.lock().unwrap().set_hidden(true); - } - Mode::ClientSide => { - let want_decorate = decoration_inner - .lock() - .unwrap() - .as_ref() - .map(|inner| inner.decorated) - .unwrap_or(false); - decoration_frame.lock().unwrap().set_hidden(!want_decorate); + if let Event::Configure { mode } = event { + match mode { + DecorationsMode::ServerSide => { + decoration_frame.lock().unwrap().set_hidden(true); + } + DecorationsMode::ClientSide => { + let want_decorate = decoration_inner + .lock() + .unwrap() + .as_ref() + .map(|inner| inner.decorated) + .unwrap_or(false); + decoration_frame.lock().unwrap().set_hidden(!want_decorate); + } + _ => unreachable!(), } } }, @@ -348,7 +380,7 @@ impl Window { }) .ok() .map(|decoration| { - decoration.set_mode(Mode::ServerSide); + decoration.set_mode(DecorationsMode::ServerSide); decoration }) } @@ -360,12 +392,12 @@ impl Window { /// /// This allows the decoration manager to get an handle to the pointer /// to manage pointer events and change the pointer image appropriately. - pub fn new_seat(&mut self, seat: &Proxy) { + pub fn new_seat(&mut self, seat: &wl_seat::WlSeat) { self.frame.lock().unwrap().new_seat(seat); } /// Access the surface wrapped in this Window - pub fn surface(&self) -> &Proxy { + pub fn surface(&self) -> &wl_surface::WlSurface { &self.surface } @@ -412,18 +444,18 @@ impl Window { /// You need to call `refresh()` afterwards for this to properly /// take effect. pub fn set_decorate(&self, decorate: bool) { - self.frame.lock().unwrap().set_hidden(!decorate); let mut decoration_guard = self.decoration.lock().unwrap(); self.ensure_decoration(&mut decoration_guard); if let Some(ref dec) = *decoration_guard { if decorate { - // let the server decide decorations dec.unset_mode(); } else { - // destroy the decoration object, so that the server does not - // decorate us - dec.destroy(); + dec.set_mode(DecorationsMode::ClientSide); + self.frame.lock().unwrap().set_hidden(!decorate); } + } else { + // We're managing decorations ourself, so they are always ClientSide + self.frame.lock().unwrap().set_hidden(!decorate); } } @@ -505,7 +537,7 @@ impl Window { /// /// Note: you need to manually disable the decorations if you /// want to hide them! - pub fn set_fullscreen(&self, output: Option<&Proxy>) { + pub fn set_fullscreen(&self, output: Option<&wl_output::WlOutput>) { self.shell_surface.set_fullscreen(output); } @@ -575,9 +607,9 @@ pub enum FrameRequest { /// The window should be closed Close, /// An interactive move should be started - Move(Proxy), + Move(wl_seat::WlSeat), /// An interactive resize should be started - Resize(Proxy, ResizeEdge), + Resize(wl_seat::WlSeat, ResizeEdge), /// The frame requests to be refreshed Refresh, } @@ -592,10 +624,10 @@ pub trait Frame: Sized + Send { type Error; /// Initialize the Frame fn init( - base_surface: &Proxy, - compositor: &Proxy, - subcompositor: &Proxy, - shm: &Proxy, + base_surface: &wl_surface::WlSurface, + compositor: &wl_compositor::WlCompositor, + subcompositor: &wl_subcompositor::WlSubcompositor, + shm: &wl_shm::WlShm, implementation: Box, ) -> Result; /// Set whether the decorations should be drawn as active or not @@ -616,7 +648,7 @@ pub trait Frame: Sized + Send { /// and reacted to fn set_resizable(&mut self, resizable: bool); /// Notify that a new wl_seat should be handled - fn new_seat(&mut self, seat: &Proxy); + fn new_seat(&mut self, seat: &wl_seat::WlSeat); /// Change the size of the decorations /// /// Calling this should *not* trigger a redraw diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/travis_install_wayland.sh b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/travis_install_wayland.sh similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/travis_install_wayland.sh rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/travis_install_wayland.sh diff --git a/third_party/cargo/vendor/smithay-client-toolkit-0.4.6/update_keysyms.sh b/third_party/cargo/vendor/smithay-client-toolkit-0.6.6/update_keysyms.sh similarity index 100% rename from third_party/cargo/vendor/smithay-client-toolkit-0.4.6/update_keysyms.sh rename to third_party/cargo/vendor/smithay-client-toolkit-0.6.6/update_keysyms.sh diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/.cargo-checksum.json b/third_party/cargo/vendor/stable_deref_trait-1.1.1/.cargo-checksum.json deleted file mode 100644 index abdf0b4..0000000 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"56ab4873c19b49e38e91820c4824f3ba208b58414c272d47cdbd34db1784eb69","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"5e05b024f653a5ce199e77cbbbd42fb5553562ec714b819421ed0c3e552a75d7","README.md":"750fc2d57412de57566289e567b5674a666cc7a8a054f8c7129b8553f9003de7","src/lib.rs":"0223b3f374305b556cba65406d6c8bc5ff053e592c6c0c36e276b94f5e06d70d"},"package":"dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8"} \ No newline at end of file diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-APACHE b/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright [yyyy] [name of copyright owner] - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-MIT b/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-MIT deleted file mode 100644 index 3bf61a0..0000000 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/LICENSE-MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2017 Robert Grosse - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/README.md b/third_party/cargo/vendor/stable_deref_trait-1.1.1/README.md deleted file mode 100644 index 24fd4b0..0000000 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/README.md +++ /dev/null @@ -1,23 +0,0 @@ -This crate defines an unsafe marker trait, StableDeref, for container types which deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address. - -It is intended to be used by crates such as [owning_ref](https://crates.io/crates/owning_ref) and [rental](https://crates.io/crates/rental), as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom Vec type together with owning_ref and rental. - -no_std support can be enabled by disabling default features (specifically "std"). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types. - -Enable the "alloc" feature (with default-features disabled) to have this trait be implemented for the above types from the built-in `alloc` crate, specifically -* `alloc::boxed::Box` -* `alloc::vec::Vec` -* `alloc::rc::Rc` -* `alloc::arc::Arc` -* `alloc::string::String` - -For example, this crate can be built with alloc support via the following command: -`cargo build --no-default-features --features alloc` - -Or added as a `Cargo.toml` dependency as follows: -``` -[dependencies.stable_deref_trait] -version = "" -default-features = false -features = [ "alloc" ] -``` diff --git a/third_party/cargo/vendor/stable_deref_trait-1.1.1/src/lib.rs b/third_party/cargo/vendor/stable_deref_trait-1.1.1/src/lib.rs deleted file mode 100644 index c4272b8..0000000 --- a/third_party/cargo/vendor/stable_deref_trait-1.1.1/src/lib.rs +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright 2017 Robert Grosse - -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -This module defines an unsafe marker trait, StableDeref, for container types that deref to a fixed address which is valid even when the containing type is moved. For example, Box, Vec, Rc, Arc and String implement this trait. Additionally, it defines CloneStableDeref for types like Rc where clones deref to the same address. - -It is intended to be used by crates such as [owning_ref](https://crates.io/crates/owning_ref) and [rental](https://crates.io/crates/rental), as well as library authors who wish to make their code interoperable with such crates. For example, if you write a custom Vec type, you can implement StableDeref, and then users will be able to use your custom type together with owning_ref and rental. - -no_std support can be enabled by disabling default features (specifically "std"). In this case, the trait will not be implemented for the std types mentioned above, but you can still use it for your own types. -*/ - -#![cfg_attr(feature = "alloc", feature(alloc))] - -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(feature = "std")] -extern crate core; - -#[cfg(feature = "alloc")] -extern crate alloc; - -use core::ops::Deref; - - -/** -An unsafe marker trait for types that deref to a stable address, even when moved. For example, this is implemented by Box, Vec, Rc, Arc and String, among others. Even when a Box is moved, the underlying storage remains at a fixed location. - -More specifically, implementors must ensure that the result of calling deref() is valid for the lifetime of the object, not just the lifetime of the borrow, and that the deref is valid even if the object is moved. Also, it must be valid even after invoking arbitrary &self methods or doing anything transitively accessible from &Self. If Self also implements DerefMut, the same restrictions apply to deref_mut() and it must remain valid if anything transitively accessible from the result of deref_mut() is mutated/called. Additionally, multiple calls to deref, (and deref_mut if implemented) must return the same address. No requirements are placed on &mut self methods other than deref_mut() and drop(), if applicable. - -Basically, it must be valid to convert the result of deref() to a pointer, and later dereference that pointer, as long as the original object is still live, even if it has been moved or &self methods have been called on it. If DerefMut is also implemented, it must be valid to get pointers from deref() and deref_mut() and dereference them while the object is live, as long as you don't simultaneously dereference both of them. - -Additionally, Deref and DerefMut implementations must not panic, but users of the trait are not allowed to rely on this fact (so that this restriction can be removed later without breaking backwards compatibility, should the need arise). - -Here are some examples to help illustrate the requirements for implementing this trait: - -``` -# use std::ops::Deref; -struct Foo(u8); -impl Deref for Foo { - type Target = u8; - fn deref(&self) -> &Self::Target { &self.0 } -} -``` - -Foo cannot implement StableDeref because the int will move when Foo is moved, invalidating the result of deref(). - -``` -# use std::ops::Deref; -struct Foo(Box); -impl Deref for Foo { - type Target = u8; - fn deref(&self) -> &Self::Target { &*self.0 } -} -``` - -Foo can safely implement StableDeref, due to the use of Box. - - -``` -# use std::ops::Deref; -# use std::ops::DerefMut; -# use std::rc::Rc; -#[derive(Clone)] -struct Foo(Rc); -impl Deref for Foo { - type Target = u8; - fn deref(&self) -> &Self::Target { &*self.0 } -} -impl DerefMut for Foo { - fn deref_mut(&mut self) -> &mut Self::Target { Rc::make_mut(&mut self.0) } -} -``` - -This is a simple implementation of copy-on-write: Foo's deref_mut will copy the underlying int if it is not uniquely owned, ensuring unique access at the point where deref_mut() returns. However, Foo cannot implement StableDeref because calling deref_mut(), followed by clone().deref() will result in mutable and immutable references to the same location. Note that if the DerefMut implementation were removed, Foo could safely implement StableDeref. Likewise, if the Clone implementation were removed, it would be safe to implement StableDeref, although Foo would not be very useful in that case, (without clones, the rc will always be uniquely owned). - - -``` -# use std::ops::Deref; -struct Foo; -impl Deref for Foo { - type Target = str; - fn deref(&self) -> &Self::Target { &"Hello" } -} -``` -Foo can safely implement StableDeref. It doesn't own the data being derefed, but the data is gaurenteed to live long enough, due to it being 'static. - -``` -# use std::ops::Deref; -# use std::cell::Cell; -struct Foo(Cell); -impl Deref for Foo { - type Target = str; - fn deref(&self) -> &Self::Target { - let b = self.0.get(); - self.0.set(!b); - if b { &"Hello" } else { &"World" } - } -} -``` -Foo cannot safely implement StableDeref, even though every possible result of deref lives long enough. In order to safely implement StableAddress, multiple calls to deref must return the same result. - -``` -# use std::ops::Deref; -# use std::ops::DerefMut; -struct Foo(Box<(u8, u8)>); -impl Deref for Foo { - type Target = u8; - fn deref(&self) -> &Self::Target { &self.0.deref().0 } -} -impl DerefMut for Foo { - fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0.deref_mut().1 } -} -``` - -Foo cannot implement StableDeref because deref and deref_mut return different addresses. - - -*/ -pub unsafe trait StableDeref: Deref {} - -/** -An unsafe marker trait for types where clones deref to the same address. This has all the requirements of StableDeref, and additionally requires that after calling clone(), both the old and new value deref to the same address. For example, Rc and Arc implement CloneStableDeref, but Box and Vec do not. - -Note that a single type should never implement both DerefMut and CloneStableDeref. If it did, this would let you get two mutable references to the same location, by cloning and then calling deref_mut() on both values. -*/ -pub unsafe trait CloneStableDeref: StableDeref + Clone {} - -///////////////////////////////////////////////////////////////////////////// -// std types integration -///////////////////////////////////////////////////////////////////////////// - -#[cfg(all(feature = "std", not(feature = "alloc")))] -use std::boxed::Box; -#[cfg(all(not(feature = "std"), feature = "alloc"))] -use alloc::boxed::Box; - -#[cfg(all(feature = "std", not(feature = "alloc")))] -use std::rc::Rc; -#[cfg(all(not(feature = "std"), feature = "alloc"))] -use alloc::rc::Rc; - -#[cfg(all(feature = "std", not(feature = "alloc")))] -use std::sync::Arc; -#[cfg(all(not(feature = "std"), feature = "alloc"))] -use alloc::sync::Arc; - -#[cfg(all(feature = "std", not(feature = "alloc")))] -use std::vec::Vec; -#[cfg(all(not(feature = "std"), feature = "alloc"))] -use alloc::vec::Vec; - -#[cfg(all(feature = "std", not(feature = "alloc")))] -use std::string::String; -#[cfg(all(not(feature = "std"), feature = "alloc"))] -use alloc::string::String; - - -#[cfg(feature = "std")] -use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; - -#[cfg(feature = "std")] -use std::cell::{Ref, RefMut}; -#[cfg(not(feature = "std"))] -use core::cell::{Ref, RefMut}; - - -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl StableDeref for Box {} -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl StableDeref for Vec {} -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl StableDeref for String {} - -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl StableDeref for Rc {} -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl CloneStableDeref for Rc {} -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl StableDeref for Arc {} -#[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl CloneStableDeref for Arc {} - -// #[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl<'a, T: ?Sized> StableDeref for Ref<'a, T> {} -// #[cfg(any(feature = "std", feature = "alloc"))] -unsafe impl<'a, T: ?Sized> StableDeref for RefMut<'a, T> {} -#[cfg(feature = "std")] -unsafe impl<'a, T: ?Sized> StableDeref for MutexGuard<'a, T> {} -#[cfg(feature = "std")] -unsafe impl<'a, T: ?Sized> StableDeref for RwLockReadGuard<'a, T> {} -#[cfg(feature = "std")] -unsafe impl<'a, T: ?Sized> StableDeref for RwLockWriteGuard<'a, T> {} - -unsafe impl<'a, T: ?Sized> StableDeref for &'a T {} -unsafe impl<'a, T: ?Sized> CloneStableDeref for &'a T {} -unsafe impl<'a, T: ?Sized> StableDeref for &'a mut T {} diff --git a/third_party/cargo/vendor/vk-sys-0.4.0/.cargo-checksum.json b/third_party/cargo/vendor/vk-sys-0.4.0/.cargo-checksum.json deleted file mode 100644 index 1f52e2b..0000000 --- a/third_party/cargo/vendor/vk-sys-0.4.0/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"a9572757fb3826c2a084b93eb6db19299212d77843c1225310a838bdde4eb698","src/lib.rs":"f0ed92c5b1c96696077298b13ac7dea1a2e880d75636411a32de0bb1ccfbc4b7"},"package":"36f5fd4a7d6d5d19808610583131c0aed271556527cad4cb71c436831a28e059"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vk-sys-0.5.1/.cargo-checksum.json b/third_party/cargo/vendor/vk-sys-0.5.1/.cargo-checksum.json new file mode 100644 index 0000000..fb9ffe8 --- /dev/null +++ b/third_party/cargo/vendor/vk-sys-0.5.1/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"def359582a4bf3fa7647e754fec6ee6e8fdeafacd68fcbbd2f369a023e10ca9b","src/lib.rs":"c6d12df9eb7b8196fc7a6fb03d16d01fa4720e5cf6defb4d8c4e0d0dc7070645"},"package":"c24c107c0402856ad434d2dc0f3dbdc68c9e170e8bab0f27aa82a282d234d57c"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vk-sys-0.4.0/BUILD b/third_party/cargo/vendor/vk-sys-0.5.1/BUILD similarity index 96% rename from third_party/cargo/vendor/vk-sys-0.4.0/BUILD rename to third_party/cargo/vendor/vk-sys-0.5.1/BUILD index df35203..27d473b 100644 --- a/third_party/cargo/vendor/vk-sys-0.4.0/BUILD +++ b/third_party/cargo/vendor/vk-sys-0.5.1/BUILD @@ -35,7 +35,7 @@ rust_library( rustc_flags = [ "--cap-lints=allow", ], - version = "0.4.0", + version = "0.5.1", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/vk-sys-0.4.0/Cargo.toml b/third_party/cargo/vendor/vk-sys-0.5.1/Cargo.toml similarity index 93% rename from third_party/cargo/vendor/vk-sys-0.4.0/Cargo.toml rename to third_party/cargo/vendor/vk-sys-0.5.1/Cargo.toml index 7ea285b..99affa5 100644 --- a/third_party/cargo/vendor/vk-sys-0.4.0/Cargo.toml +++ b/third_party/cargo/vendor/vk-sys-0.5.1/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "vk-sys" -version = "0.4.0" +version = "0.5.1" authors = ["Pierre Krieger ", "The vulkano contributors"] description = "Bindings for the Vulkan graphics API" documentation = "https://docs.rs/vk-sys" diff --git a/third_party/cargo/vendor/vk-sys-0.4.0/src/lib.rs b/third_party/cargo/vendor/vk-sys-0.5.1/src/lib.rs similarity index 94% rename from third_party/cargo/vendor/vk-sys-0.4.0/src/lib.rs rename to third_party/cargo/vendor/vk-sys-0.5.1/src/lib.rs index 357aab5..9e8316e 100644 --- a/third_party/cargo/vendor/vk-sys-0.4.0/src/lib.rs +++ b/third_party/cargo/vendor/vk-sys-0.5.1/src/lib.rs @@ -56,7 +56,6 @@ pub type SurfaceKHR = u64; pub type SwapchainKHR = u64; pub type DisplayKHR = u64; pub type DisplayModeKHR = u64; -pub type DebugReportCallbackEXT = u64; pub type DescriptorUpdateTemplateKHR = u64; pub const LOD_CLAMP_NONE: f32 = 1000.0; @@ -74,6 +73,7 @@ pub const MAX_MEMORY_TYPES: u32 = 32; pub const MAX_MEMORY_HEAPS: u32 = 16; pub const MAX_EXTENSION_NAME_SIZE: u32 = 256; pub const MAX_DESCRIPTION_SIZE: u32 = 256; +pub const NULL_HANDLE: u64 = 0; pub type PipelineCacheHeaderVersion = u32; pub const PIPELINE_CACHE_HEADER_VERSION_ONE: u32 = 1; @@ -104,6 +104,7 @@ pub const ERROR_INCOMPATIBLE_DISPLAY_KHR: u32 = -1000003001i32 as u32; pub const ERROR_VALIDATION_FAILED_EXT: u32 = -1000011001i32 as u32; pub const ERROR_INVALID_SHADER_NV: u32 = -1000012000i32 as u32; pub const ERROR_OUT_OF_POOL_MEMORY_KHR: u32 = -1000069000i32 as u32; +pub const ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT: u32 = -1000255000i32 as u32; pub type StructureType = u32; pub const STRUCTURE_TYPE_APPLICATION_INFO: u32 = 0; @@ -165,11 +166,13 @@ pub const STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR: u32 = 1000005000; pub const STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR: u32 = 1000006000; pub const STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR: u32 = 1000008000; pub const STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR: u32 = 1000009000; -#[deprecated(note = "Use STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT instead")] -pub const STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT: u32 = 1000011000; -pub const STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT: u32 = 1000011000; pub const STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK: u32 = 1000122000 + (122 * 1000); pub const STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK: u32 = 1000000000 + (123 * 1000); +pub const STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT:u32 = 1000128000; +pub const STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_TAG_INFO_EXT:u32 = 1000128001; +pub const STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT:u32 = 1000128002; +pub const STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT:u32 = 1000128003; +pub const STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT:u32 = 1000128004; pub const STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR: u32 = 1000059000; pub const STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR: u32 = 1000059001; pub const STRUCTURE_TYPE_FORMAT_PROPERTIES_2_KHR: u32 = 1000059002; @@ -181,6 +184,7 @@ pub const STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR: u32 = 1000059007; pub const STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2_KHR: u32 = 1000059008; pub const STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN: u32 = 1000062000; pub const STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: u32 = 1000080000; +pub const STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: u32 = 1000083000; pub const STRUCTURE_TYPE_PRESENT_REGIONS_KHR: u32 = 1000084000; pub const STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR: u32 = 1000085000; pub const STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: u32 = 1000127000; @@ -190,9 +194,7 @@ pub const STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR: u32 = 1000146001; pub const STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR: u32 = 1000146002; pub const STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR: u32 = 1000146003; pub const STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR: u32 = 1000146004; -pub const STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT: u32 = 1000022000; -pub const STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT: u32 = 1000022001; -pub const STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT: u32 = 1000022002; +pub const STRUCTURE_TYPE_SURFACE_FULL_SCREEN_EXCLUSIVE_INFO_EXT: u32 = 1000255000; pub type SystemAllocationScope = u32; pub const SYSTEM_ALLOCATION_SCOPE_COMMAND: u32 = 0; @@ -921,16 +923,6 @@ pub type DisplayPlaneAlphaFlagsKHR = Flags; pub type DisplaySurfaceCreateFlagsKHR = Flags; pub type ColorSpaceKHR = u32; -#[deprecated = "Renamed to COLOR_SPACE_SRGB_NONLINEAR_KHR"] -pub const COLORSPACE_SRGB_NONLINEAR_KHR: u32 = 0; -#[deprecated = "Magically disappeared from the Vulkan specs"] -pub const COLOR_SPACE_DISPLAY_P3_LINEAR_EXT: u32 = 1000104001; -#[deprecated = "Magically disappeared from the Vulkan specs"] -pub const COLOR_SPACE_SCRGB_LINEAR_EXT: u32 = 1000104003; -#[deprecated = "Magically disappeared from the Vulkan specs"] -pub const COLOR_SPACE_SCRGB_NONLINEAR_EXT: u32 = 1000104004; -#[deprecated = "Magically disappeared from the Vulkan specs"] -pub const COLOR_SPACE_BT2020_NONLINEAR_EXT: u32 = 1000104010; pub const COLOR_SPACE_SRGB_NONLINEAR_KHR: u32 = 0; pub const COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: u32 = 1000104001; pub const COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: u32 = 1000104002; @@ -973,56 +965,66 @@ pub const COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR: u32 = 0x00000004; pub const COMPOSITE_ALPHA_INHERIT_BIT_KHR: u32 = 0x00000008; pub type CompositeAlphaFlagsKHR = Flags; -pub type DebugReportObjectTypeEXT = u32; -pub const DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT: u32 = 0; -pub const DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT: u32 = 1; -pub const DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT: u32 = 2; -pub const DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT: u32 = 3; -pub const DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT: u32 = 4; -pub const DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT: u32 = 5; -pub const DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT: u32 = 6; -pub const DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT: u32 = 7; -pub const DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: u32 = 8; -pub const DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: u32 = 9; -pub const DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: u32 = 10; -pub const DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT: u32 = 11; -pub const DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT: u32 = 12; -pub const DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT: u32 = 13; -pub const DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT: u32 = 14; -pub const DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT: u32 = 15; -pub const DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT: u32 = 16; -pub const DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT: u32 = 17; -pub const DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT: u32 = 18; -pub const DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT: u32 = 19; -pub const DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT: u32 = 20; -pub const DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT: u32 = 21; -pub const DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT: u32 = 22; -pub const DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT: u32 = 23; -pub const DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT: u32 = 24; -pub const DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT: u32 = 25; -pub const DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT: u32 = 26; -pub const DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT: u32 = 27; -#[deprecated = "Renamed to DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT"] -pub const DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT: u32 = DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT; -pub const DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT: u32 = 28; -pub const DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT: u32 = 29; -pub const DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT: u32 = 30; -pub const DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT: u32 = 31; -pub const DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT: u32 = 32; -pub const DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT: u32 = 33; -pub const DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR_EXT: u32 = 1000085000; +pub type ObjectType = u32; +pub const OBJECT_TYPE_UNKNOWN: u32 = 0; +pub const OBJECT_TYPE_INSTANCE: u32 = 1; +pub const OBJECT_TYPE_PHYSICAL_DEVICE: u32 = 2; +pub const OBJECT_TYPE_DEVICE: u32 = 3; +pub const OBJECT_TYPE_QUEUE: u32 = 4; +pub const OBJECT_TYPE_SEMAPHORE: u32 = 5; +pub const OBJECT_TYPE_COMMAND_BUFFER: u32 = 6; +pub const OBJECT_TYPE_FENCE: u32 = 7; +pub const OBJECT_TYPE_DEVICE_MEMORY: u32 = 8; +pub const OBJECT_TYPE_BUFFER: u32 = 9; +pub const OBJECT_TYPE_IMAGE: u32 = 10; +pub const OBJECT_TYPE_EVENT: u32 = 11; +pub const OBJECT_TYPE_QUERY_POOL: u32 = 12; +pub const OBJECT_TYPE_BUFFER_VIEW: u32 = 13; +pub const OBJECT_TYPE_IMAGE_VIEW: u32 = 14; +pub const OBJECT_TYPE_SHADER_MODULE: u32 = 15; +pub const OBJECT_TYPE_PIPELINE_CACHE: u32 = 16; +pub const OBJECT_TYPE_PIPELINE_LAYOUT: u32 = 17; +pub const OBJECT_TYPE_RENDER_PASS: u32 = 18; +pub const OBJECT_TYPE_PIPELINE: u32 = 19; +pub const OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT: u32 = 20; +pub const OBJECT_TYPE_SAMPLER: u32 = 21; +pub const OBJECT_TYPE_DESCRIPTOR_POOL: u32 = 22; +pub const OBJECT_TYPE_DESCRIPTOR_SET: u32 = 23; +pub const OBJECT_TYPE_FRAMEBUFFER: u32 = 24; +pub const OBJECT_TYPE_COMMAND_POOL: u32 = 25; +pub const OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION: u32 = 1000156000; +pub const OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE: u32 = 1000085000; +pub const OBJECT_TYPE_SURFACE_KHR: u32 = 1000000000; +pub const OBJECT_TYPE_SWAPCHAIN_KHR: u32 = 1000001000; +pub const OBJECT_TYPE_DISPLAY_KHR: u32 = 1000002000; +pub const OBJECT_TYPE_DISPLAY_MODE_KHR: u32 = 1000002001; +pub const OBJECT_TYPE_OBJECT_TABLE_NVX: u32 = 1000086000; +pub const OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX: u32 = 1000086001; +pub const OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT: u32 = 1000128000; +pub const OBJECT_TYPE_VALIDATION_CACHE_EXT: u32 = 1000160000; +pub const OBJECT_TYPE_ACCELERATION_STRUCTURE_NV: u32 = 1000165000; +pub const OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL: u32 = 1000210000; +pub const OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_KHR: u32 = OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE; +pub const OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR: u32 = OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION; -pub type DebugReportErrorEXT = u32; -pub const DEBUG_REPORT_ERROR_NONE_EXT: u32 = 0; -pub const DEBUG_REPORT_ERROR_CALLBACK_REF_EXT: u32 = 1; +pub type DebugUtilsMessageSeverityFlagBitsEXT = u32; +pub const DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: u32 = 0x00000001; +pub const DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: u32 = 0x00000010; +pub const DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: u32 = 0x00000100; +pub const DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: u32 = 0x00001000; +pub type DebugUtilsMessageSeverityFlagsEXT = Flags; -pub type DebugReportFlagBitsEXT = u32; -pub const DEBUG_REPORT_INFORMATION_BIT_EXT: u32 = 0x00000001; -pub const DEBUG_REPORT_WARNING_BIT_EXT: u32 = 0x00000002; -pub const DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT: u32 = 0x00000004; -pub const DEBUG_REPORT_ERROR_BIT_EXT: u32 = 0x00000008; -pub const DEBUG_REPORT_DEBUG_BIT_EXT: u32 = 0x00000010; -pub type DebugReportFlagsEXT = Flags; +pub type DebugUtilsMessageTypeFlagBitsEXT = u32; +pub const DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT: u32 = 0x00000001; +pub const DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT: u32 = 0x00000002; +pub const DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT: u32 = 0x00000004; +pub type DebugUtilsMessageTypeFlagsEXT = Flags; + +pub type DebugUtilsMessengerCreateFlagsEXT = Flags; + +pub type DebugUtilsMessengerCallbackDataFlagsEXT = Flags; + +pub type DebugUtilsMessengerEXT = u64; pub type MacOSSurfaceCreateFlagsMVK = u32; @@ -1044,10 +1046,17 @@ pub type PFN_vkReallocationFunction = extern "system" fn(*mut c_void, *mut c_voi pub type PFN_vkFreeFunction = extern "system" fn(*mut c_void, *mut c_void); pub type PFN_vkInternalAllocationNotification = extern "system" fn(*mut c_void, usize, InternalAllocationType, SystemAllocationScope) -> *mut c_void; pub type PFN_vkInternalFreeNotification = extern "system" fn(*mut c_void, usize, InternalAllocationType, SystemAllocationScope) -> *mut c_void; -pub type PFN_vkDebugReportCallbackEXT = extern "system" fn(DebugReportFlagsEXT, DebugReportObjectTypeEXT, u64, usize, i32, *const c_char, *const c_char, *mut c_void) -> Bool32; +pub type PFN_vkDebugUtilsMessengerCallbackEXT = extern "system" fn(DebugUtilsMessageSeverityFlagBitsEXT, DebugUtilsMessageTypeFlagsEXT, *const DebugUtilsMessengerCallbackDataEXT, *mut c_void) -> Bool32; pub type PFN_vkVoidFunction = extern "system" fn() -> (); +pub type FullScreenExclusiveEXT = u32; +pub const FULL_SCREEN_EXCLUSIVE_DEFAUlT_EXT: u32 = 0; +pub const FULL_SCREEN_EXCLUSIVE_ALLOWED_EXT: u32 = 1; +pub const FULL_SCREEN_EXCLUSIVE_DISALLOWED_EXT: u32 = 2; +pub const FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT: u32 = 3; +pub const FULL_SCREEN_EXCLUSIVE_MAX_ENUM_EXT: u32 = 0x7FFFFFFF; + #[repr(C)] pub struct ApplicationInfo { pub sType: StructureType, @@ -2419,16 +2428,6 @@ pub struct Win32SurfaceCreateInfoKHR { pub hwnd: *mut c_void, } - -#[repr(C)] -pub struct DebugReportCallbackCreateInfoEXT { - pub sType: StructureType, - pub pNext: *const c_void, - pub flags: DebugReportFlagsEXT, - pub pfnCallback: PFN_vkDebugReportCallbackEXT, - pub pUserData: *mut c_void, -} - #[repr(C)] pub struct IOSSurfaceCreateInfoMVK { pub sType: StructureType, @@ -2645,33 +2644,66 @@ pub struct PresentRegionsKHR { } #[repr(C)] -pub struct DebugMarkerObjectNameInfoEXT { +pub struct DebugUtilsMessengerCreateInfoEXT { pub sType: StructureType, pub pNext: *const c_void, - pub objectType: DebugReportObjectTypeEXT, - pub object: u64, - pub name: *const c_char, + pub flags: DebugUtilsMessengerCreateFlagsEXT, + pub messageSeverity: DebugUtilsMessageSeverityFlagsEXT, + pub messageType: DebugUtilsMessageTypeFlagsEXT, + pub pfnUserCallback: PFN_vkDebugUtilsMessengerCallbackEXT, + pub pUserData: *mut c_void, } #[repr(C)] -pub struct DebugMarkerObjectTagInfoEXT { +pub struct DebugUtilsMessengerCallbackDataEXT { pub sType: StructureType, pub pNext: *const c_void, - pub objectType: DebugReportObjectTypeEXT, - pub object: u64, - pub tagName: u64, - pub tagSize: usize, - pub tag: *const c_void, + pub flags: DebugUtilsMessengerCallbackDataFlagsEXT, + pub pMessageIdName: *const c_char, + pub messageIdNumber: i32, + pub pMessage: *const c_char, + pub queueLabelCount: u32, + pub pQueueLabels: *const DebugUtilsLabelEXT, + pub cmdBufLabelCount: u32, + pub pCmdBufLabels: *const DebugUtilsLabelEXT, + pub objectCount: u32, + pub pObject: *const DebugUtilsObjectNameInfoEXT, } #[repr(C)] -pub struct DebugMarkerMarkerInfoEXT { +pub struct DebugUtilsLabelEXT { pub sType: StructureType, pub pNext: *const c_void, - pub pMarkerName: *const c_char, + pub pLabelName: *const c_char, pub color: [f32; 4], } +#[repr(C)] +pub struct PhysicalDevice16BitStorageFeaturesKHR { + pub sType: StructureType, + pub pNext: *const c_void, + pub storageBuffer16BitAccess: Bool32, + pub uniformAndStorageBuffer16BitAccess: Bool32, + pub storagePushConstant16: Bool32, + pub storageInputOutput16: Bool32, +} + +#[repr(C)] +pub struct DebugUtilsObjectNameInfoEXT { + pub sType: StructureType, + pub pNext: *const c_void, + pub objectType: ObjectType, + pub objectHandle: u64, + pub pObjectName: *const c_char, +} + +#[repr(C)] +pub struct SurfaceFullScreenExclusiveInfoEXT { + pub sType: StructureType, + pub pNext: *const c_void, + pub fullScreenExclusive: FullScreenExclusiveEXT, +} + macro_rules! ptrs { ($struct_name:ident, { $($name:ident => ($($param_n:ident: $param_ty:ty),*) -> $ret:ty,)+ }) => ( pub struct $struct_name { @@ -2762,9 +2794,8 @@ ptrs!(InstancePointers, { GetPhysicalDeviceSurfaceCapabilitiesKHR => (physicalDevice: PhysicalDevice, surface: SurfaceKHR, pSurfaceCapabilities: *mut SurfaceCapabilitiesKHR) -> Result, GetPhysicalDeviceSurfaceFormatsKHR => (physicalDevice: PhysicalDevice, surface: SurfaceKHR, pSurfaceFormatCount: *mut u32, pSurfaceFormats: *mut SurfaceFormatKHR) -> Result, GetPhysicalDeviceSurfacePresentModesKHR => (physicalDevice: PhysicalDevice, surface: SurfaceKHR, pPresentModeCount: *mut u32, pPresentModes: *mut PresentModeKHR) -> Result, - CreateDebugReportCallbackEXT => (instance: Instance, pCreateInfo: *const DebugReportCallbackCreateInfoEXT, pAllocator: *const AllocationCallbacks, pCallback: *mut DebugReportCallbackEXT) -> Result, - DestroyDebugReportCallbackEXT => (instance: Instance, callback: DebugReportCallbackEXT, pAllocator: *const AllocationCallbacks) -> (), - DebugReportMessageEXT => (instance: Instance, flags: DebugReportFlagsEXT, objectType: DebugReportObjectTypeEXT, object: u64, location: usize, messageCode: i32, pLayerPrefix: *const c_char, pMessage: *const c_char) -> (), + CreateDebugUtilsMessengerEXT => (instance: Instance, pCreateInfo: *const DebugUtilsMessengerCreateInfoEXT, pAllocator: *const AllocationCallbacks, pMessenger: *const DebugUtilsMessengerEXT) -> Result, + DestroyDebugUtilsMessengerEXT => (instance: Instance, messenger: DebugUtilsMessengerEXT, pAllocator: *const AllocationCallbacks) -> Result, CreateIOSSurfaceMVK => (instance: Instance, pCreateInfo: *const IOSSurfaceCreateInfoMVK, pAllocator: *const AllocationCallbacks, pSurface: *mut SurfaceKHR) -> Result, CreateMacOSSurfaceMVK => (instance: Instance, pCreateInfo: *const MacOSSurfaceCreateInfoMVK, pAllocator: *const AllocationCallbacks, pSurface: *mut SurfaceKHR) -> Result, ActivateMoltenVKLicenseMVK => (licenseID: *const c_char, licenseKey: *const c_char, acceptLicenseTermsAndConditions: Bool32) -> Result, @@ -2918,9 +2949,10 @@ ptrs!(DevicePointers, { CmdPushDescriptorSetWithTemplateKHR => (commandBuffer: CommandBuffer, descriptorUpdateTemplate: DescriptorUpdateTemplateKHR, layout: PipelineLayout, set: u32, pData: *const c_void) -> (), GetImageMemoryRequirements2KHR => (device: Device, pInfo: *const ImageMemoryRequirementsInfo2KHR, pMemoryRequirements: *mut MemoryRequirements2KHR) -> (), GetBufferMemoryRequirements2KHR => (device: Device, pInfo: *const BufferMemoryRequirementsInfo2KHR, pMemoryRequirements: *mut MemoryRequirements2KHR) -> (), - DebugMarkerSetObjectNameEXT => (device: Device, pNameInfo: *const DebugMarkerObjectNameInfoEXT) -> Result, - DebugMarkerSetObjectTagEXT => (device: Device, pTagInfo: *const DebugMarkerObjectTagInfoEXT) -> Result, - CmdDebugMarkerBeginEXT => (commandBuffer: CommandBuffer, pMarkerInfo: *const DebugMarkerMarkerInfoEXT) -> (), - CmdDebugMarkerEndEXT => (commandBuffer: CommandBuffer) -> (), - CmdDebugMarkerInsertEXT => (commandBuffer: CommandBuffer, pMarkerInfo: *const DebugMarkerMarkerInfoEXT) -> (), + SetDebugUtilsObjectNameEXT => (device: Device, pNameInfo: *const DebugUtilsObjectNameInfoEXT) -> Result, + CmdBeginDebugUtilsLabelEXT => (commandBuffer: CommandBuffer, pLabelInfo: *const DebugUtilsLabelEXT) -> Result, + CmdEndDebugUtilsLabelEXT => (commandBuffer: CommandBuffer) -> Result, + CmdInsertDebugUtilsLabelEXT => (commandBuffer: CommandBuffer, pLabelInfo: *const DebugUtilsLabelEXT) -> Result, + AcquireFullScreenExclusiveModeEXT => (device: Device, swapchain: SwapchainKHR) -> Result, + ReleaseFullScreenExclusiveModeEXT => (device: Device, swapchain: SwapchainKHR) -> Result, }); diff --git a/third_party/cargo/vendor/vulkano-0.11.1/.cargo-checksum.json b/third_party/cargo/vendor/vulkano-0.11.1/.cargo-checksum.json deleted file mode 100644 index d6f138a..0000000 --- a/third_party/cargo/vendor/vulkano-0.11.1/.cargo-checksum.json +++ /dev/null @@ -1 +0,0 @@ -{"files":{"Cargo.toml":"fc19cef33ec7d1d3c5fa2ec3a21d1aa17c36b13842cb7c8f29f52482ec8592db","build.rs":"5d41d549b78f0f85c4c4972eae3dd50398aafd5aa538f531b177381e6f439e21","src/alloc.rs":"92f53c94a7398dad0796e47afcf21f574e7571cd5415d7872874d3328341b042","src/buffer/cpu_access.rs":"8e19c2f080e4384eed2dfb1bc75858f30752e46141701f7274b99341b31b6073","src/buffer/cpu_pool.rs":"2f3f9c78baf1138e69425db623b17bb84dc097df98f0c6dcc0e506133aadde79","src/buffer/device_local.rs":"089dc2a675e87c78981d34b96380c7a1b4f7cbda6bfb5a3b775241aec103f41c","src/buffer/immutable.rs":"5f26e05713247c807e4d11ec3d7aed218f432a737234b50365dc21b2aeaaad0f","src/buffer/mod.rs":"91feaed262c84f37fc4ba6b5a9fe38d0b37c7b77764e8f6a2d34df59f7bcd5aa","src/buffer/slice.rs":"a99574585f4a8d32fc4789865576b083a7aba20eb17a76cc6d465043d92d9bf0","src/buffer/sys.rs":"fb4b31450c52c7476b938a843932c21c2ac27a60d4c30f094bb72031163e307b","src/buffer/traits.rs":"31d7936055c2ddccff856b1e80b49cc223bb91ced4b913bbf41479f71ff2a466","src/buffer/usage.rs":"048e41a7c433bb03d5a7c4627bf05ce7a397a1ce75ad53d416e07f19f9ee30ef","src/buffer/view.rs":"11186f30c71a278d58a8fc3b221db36b6b141ec9c969c60620962c559fd27ed0","src/command_buffer/auto.rs":"f951f0910bbf1d807aeb73f28268a531f8de3e726316f0f2f238f7fc523a97cb","src/command_buffer/mod.rs":"37e29521b32aec26d62ad5e1bc77b47b755ad471f78576b90fcea5c667480588","src/command_buffer/pool/mod.rs":"72ee8c6100691b27a7743449ed77046afa3ed31bdfb3479e959dcd376e77b4b7","src/command_buffer/pool/standard.rs":"0c6b9e87c55f31ba2ac8a9408d28e7913197d1fd29427cbec574fed0c172fdec","src/command_buffer/pool/sys.rs":"e70e2aeee58f8e5896de4d236014ca701dba2b78cf9b47db0604f5691e6debda","src/command_buffer/state_cacher.rs":"b1bd2a0ff7496f24d37edc8581213370263d5a35e551f8c3be575c415d04da8f","src/command_buffer/submit/bind_sparse.rs":"5e819d7c8ba1541e130ce3fc9eb970eef13e227bdd1bee7b570f83b8956b38dc","src/command_buffer/submit/mod.rs":"508027ed1e39b6f25ae9c3a5e4558647eec76b3751c9c35641791bd7dff33176","src/command_buffer/submit/queue_present.rs":"9af067341c6a04838eff898146669139660041a17c066b4914617476c9dbefd0","src/command_buffer/submit/queue_submit.rs":"6526c350220f3567edde8c8f53816d0c471709cb23223c0c51555ba9fe3911cf","src/command_buffer/submit/semaphores_wait.rs":"f8f3408a66d3ebca2b4cf4a53a54fda105c9c78b2278211263ef90b09333d1a8","src/command_buffer/synced/base.rs":"5320c7bddf7fbe7460e0626f4e6ea4bc64c7cd676951340c5edd702dd7ad6ffc","src/command_buffer/synced/commands.rs":"441abe24e14f19beae436d34285cdf25879260be484b8f2f552cde1ed831816a","src/command_buffer/synced/mod.rs":"73b2e30a22e124121362e435b91d0633f837c1506b4f2c62264f0370c0ef9e83","src/command_buffer/synced/tests.rs":"1ad3d125fc9018b5beca91b6e386b0ee80f6c594ae3b65e5a8fb88c718a773e1","src/command_buffer/sys.rs":"10571d81e535d944a5e9123652f26a06f6b4e4c289b54506e6315af767e84bfe","src/command_buffer/traits.rs":"6566967b92ac237e0422f730a73a49547ad6981532d5b9ce203e1df698ba368e","src/command_buffer/validity/blit_image.rs":"1667f130a29ff7ffd943c1f0773e446fa931d066ffd6e52f2fd6a697198ec2af","src/command_buffer/validity/clear_color_image.rs":"d4de33da67459ad650a75c6be3598d0650cb3b9d51d25e3a93d0654c69062103","src/command_buffer/validity/copy_buffer.rs":"471f2e1ed178f75f21897312e6385bd6c5d7742bcd9a3bec14b5c03a257ceb74","src/command_buffer/validity/copy_image.rs":"be27dc4e7052d4f986337c803ded9bf2206c8fc462d4d59b58ea7bf1de4e724d","src/command_buffer/validity/copy_image_buffer.rs":"f8bfb05756e2f1a0937bc5da44d35212612efff91fef8da538aaef3dae3ec390","src/command_buffer/validity/descriptor_sets.rs":"608ad2557f98126724b2ec074a7de2a3e176be3a1eacd31de340c4b64044cf00","src/command_buffer/validity/dispatch.rs":"e387feec3a0f7547ea3058fd8c0c45f0f094ff7ebba17cdda561858f90c9fa1e","src/command_buffer/validity/dynamic_state.rs":"0cbaece8b3921d92cc1403f88b6232f75c156760b78c1f98b4726a7983a06842","src/command_buffer/validity/fill_buffer.rs":"b64cd36974597694ec1c56247a154fc19524607b59faf3dbc9738fce29c5d068","src/command_buffer/validity/index_buffer.rs":"8a4d33cc6f98e255a6d29d7fdca988a898da7f2b1bb7b5bd77a587373088e8d2","src/command_buffer/validity/mod.rs":"9cc9153cc47c6a07f4119c51aca8fdab6851b2da8f5b14b04646ae88910c5e11","src/command_buffer/validity/push_constants.rs":"2229e83e1f31759fbdc5f32cdecf5f95ad790edf126693ea36845e438e6e2c54","src/command_buffer/validity/update_buffer.rs":"f7c8fecd162d28b423d975a1a2158efea0573af64d0434d30653e6d331d5260c","src/command_buffer/validity/vertex_buffers.rs":"3ea737b0953103724a1b3067952bff4c16b69e465cb0e17802094f68b9f00c86","src/descriptor/descriptor.rs":"50e41034e477de46079fb355d6cf890dd3b0550baa572a3cef4907d0b893bfa8","src/descriptor/descriptor_set/collection.rs":"ec0236d624fbeecf0db81a8c22194cfad5c3049e84691254f7fb53d6563d0284","src/descriptor/descriptor_set/fixed_size_pool.rs":"2e7ab32db3e278e75a93518362f212a63cc33fa9722576ca1f8ed4204875c54a","src/descriptor/descriptor_set/mod.rs":"ef128ee011618db22c005047511dd5de9a0084ae659ffd5079b11ab67dab3095","src/descriptor/descriptor_set/persistent.rs":"424ccbbed24e4720b61663236956f1ce911790c5489503ea471017c8541c78db","src/descriptor/descriptor_set/std_pool.rs":"3506791cf3d9c2d871293fe55986fbf53e276e14fdbdea186ee6a1035ed5f35b","src/descriptor/descriptor_set/sys.rs":"fddfa06000c2768050bc34919af06314431286c5afc05101fedb54d69955a656","src/descriptor/descriptor_set/unsafe_layout.rs":"6b89982776f750c278e77fbc735fb75cacce1a8a63b4e1d1b5d9342fb31ffc43","src/descriptor/mod.rs":"c3be3f1d7d7fa371f53fe79d58972220c590bdec7e3ac7356f8e7548c89b7bd2","src/descriptor/pipeline_layout/empty.rs":"abe6f50598a2325d9730a3b7005786476d636ff25f387ca78641153a3d005775","src/descriptor/pipeline_layout/limits_check.rs":"7f2c257e3b56eee03ce6a053b943085537eace8241bb5634484acd55508b7dcc","src/descriptor/pipeline_layout/mod.rs":"50d1ac01a6f3b69df48df6f8908c8cde63d292a23bfa3caa21cfa044ecda68ea","src/descriptor/pipeline_layout/runtime_desc.rs":"5d8019e16018d62fc00df13706340c0a8dcb2fb83db8ab14fdb2017ea5703aa4","src/descriptor/pipeline_layout/sys.rs":"cdebff27580c9807c8545a5a83297929456d37a59fa483e6ec78d97248d82631","src/descriptor/pipeline_layout/traits.rs":"1a38b276373a72d22fde25007be3cacdb12643643c8c661fc483370108efb82b","src/descriptor/pipeline_layout/tweaks.rs":"09da8effb0f18116971087d85deda987192599dd67507ea0918fea16f8c1d987","src/descriptor/pipeline_layout/union.rs":"1a97a91295a70882f69975dd64cbc5c5d8e9f20cd611dbb6fe958f1a3156aeae","src/device/extensions.rs":"0fac812987e10a0b1f19b3e5cfe6e73aa43825eb24a4d3fafa628ec4e5d64128","src/device/mod.rs":"614dd1d1243aca5ed253f18a18ff85a0a4a6b1bdf5985f096a02e90ad4e57078","src/extensions.rs":"0e7f2f208609f6b48202035b2a3e6a7fdcdc988e115b1752dda2ef173ff58d14","src/features.rs":"b820c519f8ca48b397088d2a75e976adf149ac227b58baa652bf51b5f11da890","src/format.rs":"b8afd7196a93f10391f2e377b622692e0d5d6979919c9fe018ea0ff5606a1360","src/framebuffer/attachments_list.rs":"c49ed2c54be0c8af9b37cba82b6abf6aeeb6e356acec4898dfc7edc563f0a09f","src/framebuffer/compat_atch.rs":"b6a4d127c3f8da4085e8d2507a4dab14f29c7655607349c169852651677f0091","src/framebuffer/desc.rs":"7273006b51d1aa65f30246bf8f3fc846489560640e6e714fa7e9add103622139","src/framebuffer/empty.rs":"dd910711113f0dbfbb3a396fe6bd8a22ba0ae287dd09280f0c6c16be76b66150","src/framebuffer/framebuffer.rs":"d56e8a1c1f5158af309c92148b94dda91e8fb679bf9a3fcde2d1746d02406639","src/framebuffer/macros.rs":"8e2ad980afeadc7759a12e900c0fadf3b85f185bd67d522177c715f1da942b96","src/framebuffer/mod.rs":"d71e2d1bc338d9f1b533ed3736c15d4f8ce5e7080ae142da9ce765ba8e38974e","src/framebuffer/sys.rs":"1e836b1dabbf5efaac7ec6fe9192a7522004d6f207a4656905ff4c0f10294351","src/framebuffer/traits.rs":"9a1a1c8bf35e77074af66fe2eb144e328e747ac32467823bfb0e6c2363328bee","src/image/attachment.rs":"76ac90bc3084a8976a09415634a27e9fae0e91006bb6ec586ff192b0bce0eeb3","src/image/immutable.rs":"dd92bfeceab97533745da9e67cfa1093030b53c6cf8dd4efadfeef06207226ff","src/image/layout.rs":"8b79a36208f2cd7790165c66b492d8d33979c4d5d108893821b9e920c0798c39","src/image/mod.rs":"aad7113f1a72855e1fcd74facaed88041f1fc3f43ac38889c4bfaf4dc27d1a1b","src/image/storage.rs":"b3de42691dcfc95d0eee6074412e167822b55cef0d7868ca1c1ee701b9d0e0d4","src/image/swapchain.rs":"63ca94aa140093359420e61cd272749e5272e299f714c3b71e8f96b2e148aa2f","src/image/sys.rs":"30a6aad07b95603669672781982c92f1d0d2b99b70703a93d7acf4887d95ae94","src/image/traits.rs":"a9043cbc7d9998e722b3b613e862465edc0b34ed2583ed847daaa32ad333c3bc","src/image/usage.rs":"c82d3be03f3159703ce2e2845d29401d21684af9221208bc17bee52e2bfefbc1","src/instance/debug.rs":"2065f08730532e5e84a019a36c1608c2bd2105c10421696595339b01538ef4dc","src/instance/extensions.rs":"6743b2b4133659e94099b76481b057e84b07ced506865e84e161a3d80d20ee33","src/instance/instance.rs":"3ac9c37c11b9c3261f78783833b9b358cb8576e8e842662c2f6de177998dc152","src/instance/layers.rs":"bc3620894ab6a6f11b6f17919f0a3c1722cd42828b0b63534d1c73c8299c719d","src/instance/limits.rs":"14bbf9208844b543ceb9b24bd4c17e14e427c9670c7ba2247e56cd956536ca81","src/instance/loader.rs":"95378a0f8db9e7148a0924548d056279dca4338a57a9feee3b00bcbb2ba36f1f","src/instance/mod.rs":"f4b4155bcb1e1e5c0edb7f3ad546baef79264db6b8d7c5c5062a5a8ec5f945f6","src/lib.rs":"76289ab5fd5fdc534e1a505421d6fd9bed6d85937c0006ee37d1d947a1fbe87b","src/memory/device_memory.rs":"9719cecfa31ab6f918735554509638426d51c6267ccb2957c75e9fa8ae1ff904","src/memory/mod.rs":"bbeda446fa69255d51a4ea99b07ac74e4b70af2d79628d84a27e8de821533075","src/memory/pool/host_visible.rs":"adafa215014a719eb5f7a9dbef911d7dda011d92fe77de0abe7b2aba8c879d63","src/memory/pool/mod.rs":"67070d3d7b5e619e82570c464d00f1aed70423931684d16b767b346986d71535","src/memory/pool/non_host_visible.rs":"4567828339cffacbb114d8764f8f15dfe8fd338edde94508d681f9aabfa5f8b8","src/memory/pool/pool.rs":"32f9f98b9f743ce5de85f80097b705f73802952e87272df8bd03af5fce7ce1ec","src/pipeline/blend.rs":"0e40f3aaa3f673e5a3fb56b5b67b98a977d589550cae8aff0fa4112bfd347e2f","src/pipeline/cache.rs":"b116f3e3d0aefddd2eb02ebaf032c5ba25cc80801b7ffbbc970044d1a1d777d3","src/pipeline/compute_pipeline.rs":"d58f1ed498a21cca5fac49edb73b1c01950c6a94c558e09cab02c95cec1670f4","src/pipeline/depth_stencil.rs":"9fa30b6cf5edc3a222c9211e302a12d796faf1d03abfe677fe2e9ead1a23e711","src/pipeline/graphics_pipeline/builder.rs":"bbd22ba9c38d89449bce7cf5c4323df5b3378bedc9a4fe22ac4a5c30db8fec3f","src/pipeline/graphics_pipeline/creation_error.rs":"51d152d0fa0bc08328af9e33afba4b4f830238576f3f26c613f62cf4ab134f58","src/pipeline/graphics_pipeline/mod.rs":"30484c9d70f554543eaca126c79485a76a9c868e29214434644a3fb745bf1ee3","src/pipeline/graphics_pipeline/tests.rs":"ebf6a7c77c82529091058d7d365f4b21a95ac44a82c98b4d00516080655f6d59","src/pipeline/input_assembly.rs":"9aceb3239264f7d7550034b3f0ac1339c8ccf5bfcd841421fd4a82245a119fca","src/pipeline/mod.rs":"b1b70cd6eb155cc7648f713a37016de9b233196d7d49eea25f79ce484f79fc1d","src/pipeline/multisample.rs":"d06bae13cad042a0827f3363d9f3828f1fcb13a788809288212c862ab698c1a7","src/pipeline/raster.rs":"4cf79b519cb26c77739d93e378e693f99da118dd6395fe9a5eeec30ad22a4239","src/pipeline/shader.rs":"d6afbfd045f6fcd6065024373af3e8c561211dee3001b6a91639ae9cc98daa7d","src/pipeline/vertex/bufferless.rs":"e3b9be77dd390a2a80b8d66eb91b18899132e5a92c75aded288f88b773bd6bd4","src/pipeline/vertex/definition.rs":"0ccc83d67985f9a1a488ab744105ffbbb3591758a441fa63a48f75d997eb86d9","src/pipeline/vertex/impl_vertex.rs":"5dbdb6e55825717f6a1b7d6c326cbec654814894fd19afb27911baab085c7fde","src/pipeline/vertex/instance_buffer.rs":"d96a84fa7528dd3c8f9b64ccd7e9c3527966d563c3d5537b3dd09ae3a2e08a27","src/pipeline/vertex/mod.rs":"afe3ac25e254a9794ffb7688bc7b669a2f7d9358324e5c2129b8e3034fe7b99f","src/pipeline/vertex/one_one.rs":"3e767879fd1dd3185d110d97d8c01ec76b9caa6dd6bebc3555a7d03f67f96ec8","src/pipeline/vertex/single.rs":"6ca26964f1a39310103e69e24700d68db677a6936db115730b002ee69e45eee3","src/pipeline/vertex/two.rs":"96e05f732e85b758b4dc1e15835d0c27bb3206942ef5601a6472934c4918ffeb","src/pipeline/vertex/vertex.rs":"8491bb8b29d80e82a80b518e083660ca38e92dbd4f8a96240da2772c3b92c383","src/pipeline/viewport.rs":"dce443ed415f4ec0fee05c870e9a5e2fbc9ff563ffba15b307db829fc627404f","src/query/mod.rs":"2b01a8c66f3c7fedf5062973c1586ea07b488d9a7d6a6bbf22264239f1752f20","src/sampler.rs":"f7aa27efeaeb90e5ad85da5a61c7e44c97598a34dec01df73e52011d726fa17b","src/swapchain/capabilities.rs":"490d4e9ee0272c4757e49231f39550cec81f1d4f9d46cdf51b39bb93221b874a","src/swapchain/display.rs":"f68d40ac409c0f4d76598a77c8cae26b8777005d040d8dd7c0e2718665546a39","src/swapchain/mod.rs":"3d22b36bdda23b4989ac4bdbde358a87ed5eb94a8054038a84488de8b75e9e82","src/swapchain/present_region.rs":"dfab165d09295fde86972a7173bf71e5b68f619c6511bc262c7faf8a691a17dd","src/swapchain/surface.rs":"006d6f01ef300ab0b46e2ee984bfe64b0be20f4a58e21ca85c44175604c4e9df","src/swapchain/swapchain.rs":"ce67f5e4d11edf1b97e138352465fd9b266d24c003c3d62a98365af3722c9880","src/sync/event.rs":"09d8d2090499e35d1929768724587da2bbf972d797633e18cdf3e31c6f3b8993","src/sync/fence.rs":"82721a1b91ed3af9bef6faa3e969c7d2d712c1810a124e2fbc2b35924ffb4aa0","src/sync/future/fence_signal.rs":"a93ad367afbeff07488d4f4091d2be4e789a3cc78d267d2381c5344103965c7b","src/sync/future/join.rs":"0047c8fbb2b886e1af1453ec96649a084775506742fcdea00b434cb0217e5d46","src/sync/future/mod.rs":"1d645727f4aa3672edf50607315a2a55eb6d53414ea73699ffd76415da8f9501","src/sync/future/now.rs":"30612cdd3784334f1d11e34bbb93aaa9eadebaa7c9391111080a8de1e62cf969","src/sync/future/semaphore_signal.rs":"632fcfddaca3add4091adc26db262e4c3aeb9c82a0795201b4f9f39bc7737320","src/sync/mod.rs":"5bc84e74386a70971b1dd90f472a03d17a9c8ac9e36a967675f0817f8ced4e07","src/sync/pipeline.rs":"b08df4301cb6ac4f3e4b6bd2b28bd9e525fbd8b0a3742927c881adb476c20bb5","src/sync/semaphore.rs":"780aae5374c0579688b483e76d4f964f34ce23b8971cb308096189622e72cbe6","src/tests.rs":"d9a0021fdb30f881026ca8acd7c98cf8333badcefc728fc063c7c43b064023f6","src/version.rs":"a69d8d926020f8428e3b5ddda09bda3fa8715aba1ebc5da775e71aa5ab14d1d6"},"package":"715b3528d50119f2b7088479a79ff9d95416a6613d18c853d87ad98185ca43d1"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vulkano-0.18.0/.cargo-checksum.json b/third_party/cargo/vendor/vulkano-0.18.0/.cargo-checksum.json new file mode 100644 index 0000000..33f5b3e --- /dev/null +++ b/third_party/cargo/vendor/vulkano-0.18.0/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"3d06a6db43531c9d04c1613814d90e9e9a8e09597109ea6d0171b3c31a278dd0","build.rs":"5d41d549b78f0f85c4c4972eae3dd50398aafd5aa538f531b177381e6f439e21","src/alloc.rs":"92f53c94a7398dad0796e47afcf21f574e7571cd5415d7872874d3328341b042","src/buffer/cpu_access.rs":"c8b1fbfba3a29be550cd95035b0d3b957d5ec63d60d21916eb9139453f400fc3","src/buffer/cpu_pool.rs":"0bae8d02d36117db239fad3667c02aee54b3751e951530668af088547cb4e5b3","src/buffer/device_local.rs":"ced4caebe7f7ed9da3e646d9c932b054bf60078e82bed324a5a80546dbc2262c","src/buffer/immutable.rs":"1d49d3f4a62750e4856152e952ebbd45213185a1b3f0ee9160ba5ae95262518b","src/buffer/mod.rs":"91feaed262c84f37fc4ba6b5a9fe38d0b37c7b77764e8f6a2d34df59f7bcd5aa","src/buffer/slice.rs":"dfbe0e4f2d963476e5b91700b25df9a22dc7378f52aef156e742de6f6305d46d","src/buffer/sys.rs":"8de3a65c9a0c2b0737ebc7d1e789a5bd62bccb8d62925396372a09f379753828","src/buffer/traits.rs":"e03f75e6c57b7a817dae88c736abbc601d1d3afd1ed22885769b0dd3e0d7ed63","src/buffer/usage.rs":"be5dab959334ee46a7b7d640c178bfb5e0cdf14ad01059c9704884ac303f3df2","src/buffer/view.rs":"b90eb2517f066b14d5aea65767211c2e99758e0561c43d968e578245c4ce5cbe","src/command_buffer/auto.rs":"6a2e82cc66d4584fbc1ba92017d63263eda90140d4026a6db1b4a9099e5ad99c","src/command_buffer/mod.rs":"b02e6004f358f775f3a087c767ee6d8157470a22a70eadddd0e6509d2a6a105c","src/command_buffer/pool/mod.rs":"72ee8c6100691b27a7743449ed77046afa3ed31bdfb3479e959dcd376e77b4b7","src/command_buffer/pool/standard.rs":"c885e1293aedda7b36fa6c5897a4808634b924425eb1e3975cb6dd0982b9612d","src/command_buffer/pool/sys.rs":"25dceb8913e1a81f2e0507bbd63e537b0344e4b10267c84ca7ef20d740942355","src/command_buffer/state_cacher.rs":"1567ea1d9d56b3b41d389eac9019464ca38d734c5b0651da0f2d9ef5e8957e08","src/command_buffer/submit/bind_sparse.rs":"2284e1679d8163f2242d3ae75a864856f60f725305e2d2e5fc3235fc5193623c","src/command_buffer/submit/mod.rs":"508027ed1e39b6f25ae9c3a5e4558647eec76b3751c9c35641791bd7dff33176","src/command_buffer/submit/queue_present.rs":"3afffbfd067f2eafbe200337a034662bfe5dc9d842b73827e1db0cf69138d2af","src/command_buffer/submit/queue_submit.rs":"a5fa2d371a17d4195cb3630f5f029187dea9040636c53053ce2d8bec4a2abaf1","src/command_buffer/submit/semaphores_wait.rs":"12e6b33fd254a8b9de1d4a2e9586af56dce5277645ae085bd155e7358512b537","src/command_buffer/synced/base.rs":"005b75476b73dae04ada5cb1680f8b24ecd0da1545a1f75da63b6f4318182983","src/command_buffer/synced/commands.rs":"7cb28b4f5cf89d11c7a50156a759ef2b31f564386de37d990bce160a8ed1df9a","src/command_buffer/synced/mod.rs":"73b2e30a22e124121362e435b91d0633f837c1506b4f2c62264f0370c0ef9e83","src/command_buffer/synced/tests.rs":"5ebb2995a6fa1376b81189cec43005c2480e511e1baa721c2e4b24b08ad1ce22","src/command_buffer/sys.rs":"11608fa0fd35be4ad7999aaae86ffba1c22a81ec79ad6729f7e20358d26a2387","src/command_buffer/traits.rs":"a9fe2a3d4eb3084e80449039c2054750cd898844def9d3645125dc11dc71ac5b","src/command_buffer/validity/blit_image.rs":"1667f130a29ff7ffd943c1f0773e446fa931d066ffd6e52f2fd6a697198ec2af","src/command_buffer/validity/clear_color_image.rs":"d4de33da67459ad650a75c6be3598d0650cb3b9d51d25e3a93d0654c69062103","src/command_buffer/validity/copy_buffer.rs":"471f2e1ed178f75f21897312e6385bd6c5d7742bcd9a3bec14b5c03a257ceb74","src/command_buffer/validity/copy_image.rs":"be27dc4e7052d4f986337c803ded9bf2206c8fc462d4d59b58ea7bf1de4e724d","src/command_buffer/validity/copy_image_buffer.rs":"54310fca73bfc2532e71a307b43f3df4d0c8e3693503e29872cc9485d54d5f6e","src/command_buffer/validity/descriptor_sets.rs":"756af199eb707686b8cfa293e4f04c750b047d25dc670c7d4822f4e38cf6be55","src/command_buffer/validity/dispatch.rs":"e387feec3a0f7547ea3058fd8c0c45f0f094ff7ebba17cdda561858f90c9fa1e","src/command_buffer/validity/dynamic_state.rs":"8c0585bf66cf70e507207c332d89c1d95ea6e230a7c0ee670c36043250cbafe7","src/command_buffer/validity/fill_buffer.rs":"368afdc789c0107620bf5eef43fbc20b511c03b61f11978b491fee340cb148b8","src/command_buffer/validity/index_buffer.rs":"da9ecf31e3af225850ac9f92e2b493340f576b2123728376065026e80e8ff42a","src/command_buffer/validity/mod.rs":"9cc9153cc47c6a07f4119c51aca8fdab6851b2da8f5b14b04646ae88910c5e11","src/command_buffer/validity/push_constants.rs":"2229e83e1f31759fbdc5f32cdecf5f95ad790edf126693ea36845e438e6e2c54","src/command_buffer/validity/update_buffer.rs":"63a2442c19360db04033e14e9b19733e2db1213346115b6f26f0c38acf703b59","src/command_buffer/validity/vertex_buffers.rs":"d276aec2b81a8b8ad4f9d1c903f1bd773567208b7c59ac626d2be969df86aaf8","src/descriptor/descriptor.rs":"b9b49ab885084a9b3c10e4424c46e2cdd96efd6cea5b26b08ea5848ca153a1c9","src/descriptor/descriptor_set/collection.rs":"58341611bc86e99c8fce1c64f8875a1ee2da750646daf9b9bd349c0b3b2693f4","src/descriptor/descriptor_set/fixed_size_pool.rs":"2129815d94f0360c30fb4162cbcae609f291991393e7d28c33186797a1bd0003","src/descriptor/descriptor_set/mod.rs":"7ea90453eb9c8957bc55226544e4e479f1006024c1da2f0912e0d76e6215a159","src/descriptor/descriptor_set/persistent.rs":"9f8b84395d0954c901b13c417d87f84ccbbdf806e773f877d05db9813babc53b","src/descriptor/descriptor_set/std_pool.rs":"3506791cf3d9c2d871293fe55986fbf53e276e14fdbdea186ee6a1035ed5f35b","src/descriptor/descriptor_set/sys.rs":"3ce49bed762631660d5051ea3a07e12f95519797c431d5da9f2b3741eef42fee","src/descriptor/descriptor_set/unsafe_layout.rs":"269361e333b61b3addfd94fe5db755395e666b65668a9c07547a74b2293a9762","src/descriptor/mod.rs":"21a5cd3a412f7c1d42c21fef9de40fe5fd483dfc6f4f44969044dec829f62767","src/descriptor/pipeline_layout/empty.rs":"abe6f50598a2325d9730a3b7005786476d636ff25f387ca78641153a3d005775","src/descriptor/pipeline_layout/limits_check.rs":"7f2c257e3b56eee03ce6a053b943085537eace8241bb5634484acd55508b7dcc","src/descriptor/pipeline_layout/mod.rs":"50d1ac01a6f3b69df48df6f8908c8cde63d292a23bfa3caa21cfa044ecda68ea","src/descriptor/pipeline_layout/runtime_desc.rs":"5d8019e16018d62fc00df13706340c0a8dcb2fb83db8ab14fdb2017ea5703aa4","src/descriptor/pipeline_layout/sys.rs":"2062d1c3ffbccdc25e612f8b6fe4499d3021f05ed0f5b91b9aab9cdd22c3768c","src/descriptor/pipeline_layout/traits.rs":"40b011847f805cbcbc8eb09ee535efb652267b123274fbb30a6c4e4af4220c03","src/descriptor/pipeline_layout/tweaks.rs":"09da8effb0f18116971087d85deda987192599dd67507ea0918fea16f8c1d987","src/descriptor/pipeline_layout/union.rs":"1a97a91295a70882f69975dd64cbc5c5d8e9f20cd611dbb6fe958f1a3156aeae","src/device/extensions.rs":"5b35b6bdbe25daf6cd404f17d4808d122b7f208cf8691c53eef709c317368c74","src/device/mod.rs":"15a4e5420ecd08645172d999bbe4027b1933797b48de918adfdf40fd1abb3548","src/extensions.rs":"e2cd991898288033fd0822b83ef4a5cc0d342c1796da6facf2d7c1c559fb286a","src/features.rs":"b820c519f8ca48b397088d2a75e976adf149ac227b58baa652bf51b5f11da890","src/format.rs":"dab29260dfd043de687d33029b8d409cb6d1f6052710b29760b5dfdc630649f9","src/framebuffer/attachments_list.rs":"f5f1a9820a7eb350648fa62d8a23ef70b8ab43437460b64a0ac2d2b70f65c5c5","src/framebuffer/compat_atch.rs":"b6a4d127c3f8da4085e8d2507a4dab14f29c7655607349c169852651677f0091","src/framebuffer/desc.rs":"7273006b51d1aa65f30246bf8f3fc846489560640e6e714fa7e9add103622139","src/framebuffer/empty.rs":"4046267b200691ca6baba5c29c176cc4fe793cf1c1cd84fdd39b0b5b2b7d7a22","src/framebuffer/framebuffer.rs":"ee2a7924b8717e17dd683fadc10306a90219689895141aef7149163dbbf8ff58","src/framebuffer/macros.rs":"e49bc5adf83a55008c5153c9802b2848cdfba023288e91f6f5325184930dcece","src/framebuffer/mod.rs":"d71e2d1bc338d9f1b533ed3736c15d4f8ce5e7080ae142da9ce765ba8e38974e","src/framebuffer/sys.rs":"dbece98ee4e01193d392b4c2cea55b5b55ff6a8cdf52b96801f97904d291e9cc","src/framebuffer/traits.rs":"b7df8db3c7dd41eec9e12e85cd0182325fe6914d678a664c1df9fcb6d8083af6","src/image/attachment.rs":"b9914a7ab2f817f39bd9b397613e2450ae3d82f6b67eb439652c34c8b51832d4","src/image/immutable.rs":"6e0256000cad2abfce9ac1faafad46712c3529b8bd69761da97912a72f9205e0","src/image/layout.rs":"8b79a36208f2cd7790165c66b492d8d33979c4d5d108893821b9e920c0798c39","src/image/mod.rs":"976730c48512b7b3a9c35ccd11b67d769dff25b4af0918242a65a938dc5b90d5","src/image/storage.rs":"b74d696ecac123bebc0ed2c94801181eb6724876e0b80d28dec05bda780634c4","src/image/swapchain.rs":"19641ae1b50c368f4207266041026e11e20073fc036913d1f643c2a3f7db47c2","src/image/sys.rs":"69a626a07e2aebbe5c2358175a3074024d12a5fbc7e01b8fdb04c350723710c6","src/image/traits.rs":"0ec2b05e8b1be55ce2745646c3fdb1eb8bc2a9eac5d6db4eb991e494653d4a18","src/image/usage.rs":"c82d3be03f3159703ce2e2845d29401d21684af9221208bc17bee52e2bfefbc1","src/instance/debug.rs":"79d6b1bc71d1b2dbb2f91fe471bd7a4cc9510fa205f73e75ba2a18bc05527c22","src/instance/extensions.rs":"481a1e42f7aedf002f7aea990acd3417fe20bc3312b7ac3132bc7dafe463519f","src/instance/instance.rs":"ba620ef7ef7ac897b1e827009142cc5498046b05da622514d28c4ea69f549638","src/instance/layers.rs":"bbe1236c65f9c823cfdfa968cad739088afc8e10a23f6a8e48cbff5ebbebee18","src/instance/limits.rs":"14bbf9208844b543ceb9b24bd4c17e14e427c9670c7ba2247e56cd956536ca81","src/instance/loader.rs":"be27136c20577b2b68119b4d953545a1f8bb02878c560948cb7b2678db508499","src/instance/mod.rs":"f4b4155bcb1e1e5c0edb7f3ad546baef79264db6b8d7c5c5062a5a8ec5f945f6","src/lib.rs":"afc8dd36607787b420fff3fe27d51d7a9642587a691c553cfb684b4d689f650b","src/memory/device_memory.rs":"7d8c54ce607e424fe7df744480ca019698e7f81a6190dfcce51c2f254de54e7a","src/memory/mod.rs":"bbeda446fa69255d51a4ea99b07ac74e4b70af2d79628d84a27e8de821533075","src/memory/pool/host_visible.rs":"adafa215014a719eb5f7a9dbef911d7dda011d92fe77de0abe7b2aba8c879d63","src/memory/pool/mod.rs":"67070d3d7b5e619e82570c464d00f1aed70423931684d16b767b346986d71535","src/memory/pool/non_host_visible.rs":"4567828339cffacbb114d8764f8f15dfe8fd338edde94508d681f9aabfa5f8b8","src/memory/pool/pool.rs":"32f9f98b9f743ce5de85f80097b705f73802952e87272df8bd03af5fce7ce1ec","src/pipeline/blend.rs":"0e40f3aaa3f673e5a3fb56b5b67b98a977d589550cae8aff0fa4112bfd347e2f","src/pipeline/cache.rs":"4285fce9b87cc4da7f88991aad43dae9bac79fbf1662823e3a0455b3db3966f5","src/pipeline/compute_pipeline.rs":"11714dfb392f0e7dad130967c1803a022e69f922fa1b82f8fc362f4dfa87e6ca","src/pipeline/depth_stencil.rs":"afb32b9dc475b9fde525f8726ff0d86a9cb0d18367700455a9c5e3c0b26b30cf","src/pipeline/graphics_pipeline/builder.rs":"5a2401b3dacb50c08a38bc964c9dda3a271e9f631a57748db3441a88e7ec22ff","src/pipeline/graphics_pipeline/creation_error.rs":"ea65a4fd07838417c3ee6f6fb0f2d30297f3a779a7c5808625f8829115f14a92","src/pipeline/graphics_pipeline/mod.rs":"5332cf8e2a1f0df39512fdc84c3988709d4d2327b0993c1409faaa0766e19e35","src/pipeline/graphics_pipeline/tests.rs":"ebf6a7c77c82529091058d7d365f4b21a95ac44a82c98b4d00516080655f6d59","src/pipeline/input_assembly.rs":"9aceb3239264f7d7550034b3f0ac1339c8ccf5bfcd841421fd4a82245a119fca","src/pipeline/mod.rs":"b1b70cd6eb155cc7648f713a37016de9b233196d7d49eea25f79ce484f79fc1d","src/pipeline/multisample.rs":"d06bae13cad042a0827f3363d9f3828f1fcb13a788809288212c862ab698c1a7","src/pipeline/raster.rs":"4cf79b519cb26c77739d93e378e693f99da118dd6395fe9a5eeec30ad22a4239","src/pipeline/shader.rs":"68b3c2a57e1abead648099d80f8379265a23330b1fea6620d00c44d102d88128","src/pipeline/vertex/bufferless.rs":"2455efb4c1114678cacda62a0956b7defa058235a3294a24d3253677a82a980d","src/pipeline/vertex/definition.rs":"9bb9dde6d46d75e725e0f3fa0b97d8b5a9a30193f768f62fd59a9cd44a55c347","src/pipeline/vertex/impl_vertex.rs":"be4d164769ff37cbd93e33eee33b2896a8f762e422870cca77a7751064c57cc3","src/pipeline/vertex/instance_buffer.rs":"dffbc203e90080564c70b10e29c0330a038d4893fa25154a2fb6b2ac1ea7736e","src/pipeline/vertex/mod.rs":"afe3ac25e254a9794ffb7688bc7b669a2f7d9358324e5c2129b8e3034fe7b99f","src/pipeline/vertex/one_one.rs":"f12ee55ae6e3f1126a347c19ec4668b1e0d39a4b9fcbede96ae247b3509b1616","src/pipeline/vertex/single.rs":"5938c22b03fc8f6a56bfafb335c374c1ccd2a928488e990babfb9f0df3ec8b93","src/pipeline/vertex/two.rs":"d875706b58fbcc78ad28d806fadaf84bdb84727e1205629060644ba209d3e841","src/pipeline/vertex/vertex.rs":"8491bb8b29d80e82a80b518e083660ca38e92dbd4f8a96240da2772c3b92c383","src/pipeline/viewport.rs":"dce443ed415f4ec0fee05c870e9a5e2fbc9ff563ffba15b307db829fc627404f","src/query/mod.rs":"636b1cbf3dbfcb332a1f669c55ad6e458b073736a2597f4434928598bf236930","src/sampler.rs":"6e2f17094bff0a5e1781b69397909a435cd15d538103cf9ad263eb25997c78a7","src/swapchain/capabilities.rs":"490d4e9ee0272c4757e49231f39550cec81f1d4f9d46cdf51b39bb93221b874a","src/swapchain/display.rs":"67c3681ec2c453b7b7846efb5aa7361980788381fc58e91462475a0a837ebdff","src/swapchain/mod.rs":"ede54f35d02ef39bd6a542a987824211c16054a992a5eb4e09a0712ed43aa957","src/swapchain/present_region.rs":"dfab165d09295fde86972a7173bf71e5b68f619c6511bc262c7faf8a691a17dd","src/swapchain/surface.rs":"e7bb2425efda4bd54036e37f82cb2f2798a4afed33b5ae978879e29360a67d46","src/swapchain/swapchain.rs":"753d68c156303c0b155e12b2952e274e04cd2fb03f957797845581b50ef16f01","src/sync/event.rs":"74f4dda4a95c1db8276edf0c1fe3d0cb0d854739fed728d049a082e6976d12e3","src/sync/fence.rs":"a730d9c50e075c282e09e92f22f5e1a188ae2fd5c9a24a49338a63d18fc475b8","src/sync/future/fence_signal.rs":"5054a2679adb76708123d4bd2400b0bd42c9d3ada8e076b349c411c0939fdd80","src/sync/future/join.rs":"2c258dc1e34fb9acb459024401feab37c300118522798a0cfc4d6b6c2981be27","src/sync/future/mod.rs":"244c15f660e1f2d4e053f1dae39836f85888e6cdc67a4759978373a193d00e2b","src/sync/future/now.rs":"633bf54e9028c1a1155f2c9ced30daf943fb80d1c6f112f47988655acc839de7","src/sync/future/semaphore_signal.rs":"b05fa76c125cca8b9c183a05b009834ee34f914c6f3d5beec653cdf8d4889fce","src/sync/mod.rs":"29c7ef2e8ce817520d7e9401d1764f06ff3b388a03dff0d2cf5968c001468a8e","src/sync/pipeline.rs":"b08df4301cb6ac4f3e4b6bd2b28bd9e525fbd8b0a3742927c881adb476c20bb5","src/sync/semaphore.rs":"80f1854a1acf3f4a6e6cea29e789c865618c4b3c9668687916bb3dca02c908c9","src/tests.rs":"d9a0021fdb30f881026ca8acd7c98cf8333badcefc728fc063c7c43b064023f6","src/version.rs":"a69d8d926020f8428e3b5ddda09bda3fa8715aba1ebc5da775e71aa5ab14d1d6"},"package":"1eb8a191577df4f71d70c31e5b69c56be2f3e88a87cbd6ad6e40ae06b38dc542"} \ No newline at end of file diff --git a/third_party/cargo/vendor/vulkano-0.11.1/BUILD b/third_party/cargo/vendor/vulkano-0.18.0/BUILD similarity index 83% rename from third_party/cargo/vendor/vulkano-0.11.1/BUILD rename to third_party/cargo/vendor/vulkano-0.18.0/BUILD index 16a627d..3ab7067 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/BUILD +++ b/third_party/cargo/vendor/vulkano-0.18.0/BUILD @@ -32,18 +32,18 @@ rust_library( edition = "2015", srcs = glob(["**/*.rs"]), deps = [ - "//third_party/cargo/vendor/crossbeam-0.5.0:crossbeam", + "//third_party/cargo/vendor/crossbeam-0.7.3:crossbeam", "//third_party/cargo/vendor/fnv-1.0.6:fnv", "//third_party/cargo/vendor/half-1.5.0:half", "//third_party/cargo/vendor/lazy_static-1.4.0:lazy_static", "//third_party/cargo/vendor/shared_library-0.1.9:shared_library", - "//third_party/cargo/vendor/smallvec-0.6.13:smallvec", - "//third_party/cargo/vendor/vk-sys-0.4.0:vk_sys", + "//third_party/cargo/vendor/smallvec-1.2.0:smallvec", + "//third_party/cargo/vendor/vk-sys-0.5.1:vk_sys", ], rustc_flags = [ "--cap-lints=allow", ], - version = "0.11.1", + version = "0.18.0", crate_features = [ ], ) diff --git a/third_party/cargo/vendor/vulkano-0.11.1/Cargo.toml b/third_party/cargo/vendor/vulkano-0.18.0/Cargo.toml similarity index 86% rename from third_party/cargo/vendor/vulkano-0.11.1/Cargo.toml rename to third_party/cargo/vendor/vulkano-0.18.0/Cargo.toml index ffc7d15..c912b01 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/Cargo.toml +++ b/third_party/cargo/vendor/vulkano-0.18.0/Cargo.toml @@ -3,7 +3,7 @@ # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g. crates.io) dependencies +# to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're @@ -12,7 +12,7 @@ [package] name = "vulkano" -version = "0.11.1" +version = "0.18.0" authors = ["Pierre Krieger ", "The vulkano contributors"] build = "build.rs" description = "Safe wrapper for the Vulkan graphics API" @@ -24,22 +24,22 @@ categories = ["rendering::graphics-api"] license = "MIT/Apache-2.0" repository = "https://github.com/vulkano-rs/vulkano" [dependencies.crossbeam] -version = "0.5" +version = "0.7" [dependencies.fnv] -version = "1.0.6" +version = "1.0" [dependencies.half] -version = "1" +version = "1.5" [dependencies.lazy_static] -version = "1" +version = "1.4" [dependencies.shared_library] -version = "0.1.7" +version = "0.1" [dependencies.smallvec] -version = "0.6.0" +version = "1.2" [dependencies.vk-sys] -version = "0.4.0" +version = "0.5.1" diff --git a/third_party/cargo/vendor/vulkano-0.11.1/build.rs b/third_party/cargo/vendor/vulkano-0.18.0/build.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/build.rs rename to third_party/cargo/vendor/vulkano-0.18.0/build.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/alloc.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/alloc.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/alloc.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/alloc.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_access.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_access.rs similarity index 89% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_access.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_access.rs index 62d8ba8..41ca724 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_access.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_access.rs @@ -19,6 +19,8 @@ use smallvec::SmallVec; use std::error; use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::iter; use std::marker::PhantomData; use std::mem; @@ -59,6 +61,12 @@ use sync::AccessError; use sync::Sharing; /// Buffer whose content is accessible by the CPU. +/// +/// Setting the `host_cached` field on the various initializers to `true` will make it so +/// the `CpuAccessibleBuffer` perfers to allocate from host_cached memory. Host cached +/// memory caches GPU data on the CPU side. This can be more performant in cases where +/// the cpu needs to read data coming off the GPU. + #[derive(Debug)] pub struct CpuAccessibleBuffer> { // Inner content. @@ -94,13 +102,13 @@ enum CurrentGpuAccess { impl CpuAccessibleBuffer { /// Builds a new buffer with some data in it. Only allowed for sized data. - pub fn from_data(device: Arc, usage: BufferUsage, data: T) + pub fn from_data(device: Arc, usage: BufferUsage, host_cached: bool, data: T) -> Result>, DeviceMemoryAllocError> where T: Content + 'static { unsafe { let uninitialized = - CpuAccessibleBuffer::raw(device, mem::size_of::(), usage, iter::empty())?; + CpuAccessibleBuffer::raw(device, mem::size_of::(), usage, host_cached, iter::empty())?; // Note that we are in panic-unsafety land here. However a panic should never ever // happen here, so in theory we are safe. @@ -117,23 +125,23 @@ impl CpuAccessibleBuffer { /// Builds a new uninitialized buffer. Only allowed for sized data. #[inline] - pub unsafe fn uninitialized(device: Arc, usage: BufferUsage) + pub unsafe fn uninitialized(device: Arc, usage: BufferUsage, host_cached: bool) -> Result>, DeviceMemoryAllocError> { - CpuAccessibleBuffer::raw(device, mem::size_of::(), usage, iter::empty()) + CpuAccessibleBuffer::raw(device, mem::size_of::(), usage, host_cached, iter::empty()) } } impl CpuAccessibleBuffer<[T]> { /// Builds a new buffer that contains an array `T`. The initial data comes from an iterator /// that produces that list of Ts. - pub fn from_iter(device: Arc, usage: BufferUsage, data: I) + pub fn from_iter(device: Arc, usage: BufferUsage, host_cached: bool, data: I) -> Result>, DeviceMemoryAllocError> where I: ExactSizeIterator, T: Content + 'static { unsafe { let uninitialized = - CpuAccessibleBuffer::uninitialized_array(device, data.len(), usage)?; + CpuAccessibleBuffer::uninitialized_array(device, data.len(), usage, host_cached)?; // Note that we are in panic-unsafety land here. However a panic should never ever // happen here, so in theory we are safe. @@ -154,9 +162,9 @@ impl CpuAccessibleBuffer<[T]> { /// Builds a new buffer. Can be used for arrays. #[inline] pub unsafe fn uninitialized_array( - device: Arc, len: usize, usage: BufferUsage) + device: Arc, len: usize, usage: BufferUsage, host_cached: bool) -> Result>, DeviceMemoryAllocError> { - CpuAccessibleBuffer::raw(device, len * mem::size_of::(), usage, iter::empty()) + CpuAccessibleBuffer::raw(device, len * mem::size_of::(), usage, host_cached, iter::empty()) } } @@ -168,7 +176,7 @@ impl CpuAccessibleBuffer { /// You must ensure that the size that you pass is correct for `T`. /// pub unsafe fn raw<'a, I>(device: Arc, size: usize, usage: BufferUsage, - queue_families: I) + host_cached: bool, queue_families: I) -> Result>, DeviceMemoryAllocError> where I: IntoIterator> { @@ -197,7 +205,19 @@ impl CpuAccessibleBuffer { AllocLayout::Linear, MappingRequirement::Map, DedicatedAlloc::Buffer(&buffer), - |_| AllocFromRequirementsFilter::Allowed)?; + |m| if m.is_host_cached() { + if host_cached { + AllocFromRequirementsFilter::Preferred + } else { + AllocFromRequirementsFilter::Allowed + } + } else { + if host_cached { + AllocFromRequirementsFilter::Allowed + } else { + AllocFromRequirementsFilter::Preferred + } + })?; debug_assert!((mem.offset() % mem_reqs.alignment) == 0); debug_assert!(mem.mapped_memory().is_some()); buffer.bind_memory(mem.memory(), mem.offset())?; @@ -318,12 +338,12 @@ unsafe impl BufferAccess for CpuAccessibleBuffer } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -440,6 +460,30 @@ unsafe impl DeviceOwned for CpuAccessibleBuffer { } } +impl PartialEq for CpuAccessibleBuffer + where T: 'static + Send + Sync +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for CpuAccessibleBuffer + where T: 'static + Send + Sync +{} + +impl Hash for CpuAccessibleBuffer + where T: 'static + Send + Sync +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + + /// Object that can be used to read or write the content of a `CpuAccessibleBuffer`. /// /// Note that this object holds a rwlock read guard on the chunk. If another thread tries to access @@ -579,6 +623,6 @@ mod tests { const EMPTY: [i32; 0] = []; - let _ = CpuAccessibleBuffer::from_data(device, BufferUsage::all(), EMPTY.iter()); + let _ = CpuAccessibleBuffer::from_data(device, BufferUsage::all(), false, EMPTY.iter()); } } diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_pool.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_pool.rs similarity index 95% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_pool.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_pool.rs index 7db45dc..c6ea89d 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/cpu_pool.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/cpu_pool.rs @@ -8,6 +8,8 @@ // according to those terms. use std::cmp; +use std::hash::Hash; +use std::hash::Hasher; use std::iter; use std::marker::PhantomData; use std::mem; @@ -608,12 +610,12 @@ unsafe impl BufferAccess for CpuBufferPoolChunk } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -721,6 +723,29 @@ unsafe impl DeviceOwned for CpuBufferPoolChunk } } +impl PartialEq for CpuBufferPoolChunk + where A: MemoryPool +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for CpuBufferPoolChunk + where A: MemoryPool +{} + +impl Hash for CpuBufferPoolChunk + where A: MemoryPool +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + impl Clone for CpuBufferPoolSubbuffer where A: MemoryPool { @@ -743,12 +768,12 @@ unsafe impl BufferAccess for CpuBufferPoolSubbuffer } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -788,6 +813,29 @@ unsafe impl DeviceOwned for CpuBufferPoolSubbuffer } } +impl PartialEq for CpuBufferPoolSubbuffer + where A: MemoryPool +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for CpuBufferPoolSubbuffer + where A: MemoryPool +{} + +impl Hash for CpuBufferPoolSubbuffer + where A: MemoryPool +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + #[cfg(test)] mod tests { use buffer::CpuBufferPool; diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/device_local.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/device_local.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/device_local.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/device_local.rs index f1719a5..fb07e00 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/device_local.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/device_local.rs @@ -14,6 +14,8 @@ //! write simultaneously, or write and write simultaneously will block with a semaphore. use smallvec::SmallVec; +use std::hash::Hash; +use std::hash::Hasher; use std::marker::PhantomData; use std::mem; use std::sync::Arc; @@ -196,12 +198,12 @@ unsafe impl BufferAccess for DeviceLocalBuffer } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -284,3 +286,26 @@ unsafe impl TypedBufferAccess for DeviceLocalBuffer { type Content = T; } + +impl PartialEq for DeviceLocalBuffer + where T: 'static + Send + Sync +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for DeviceLocalBuffer + where T: 'static + Send + Sync +{} + +impl Hash for DeviceLocalBuffer + where T: 'static + Send + Sync +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/immutable.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/immutable.rs similarity index 93% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/immutable.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/immutable.rs index 2b5c4ac..ae61ea2 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/immutable.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/immutable.rs @@ -19,6 +19,8 @@ //! use smallvec::SmallVec; +use std::hash::Hash; +use std::hash::Hasher; use std::marker::PhantomData; use std::mem; use std::sync::Arc; @@ -97,6 +99,7 @@ impl ImmutableBuffer { { let source = CpuAccessibleBuffer::from_data(queue.device().clone(), BufferUsage::transfer_source(), + false, data)?; ImmutableBuffer::from_buffer(source, usage, queue) } @@ -180,6 +183,7 @@ impl ImmutableBuffer<[T]> { { let source = CpuAccessibleBuffer::from_iter(queue.device().clone(), BufferUsage::transfer_source(), + false, data)?; ImmutableBuffer::from_buffer(source, usage, queue) } @@ -328,12 +332,12 @@ unsafe impl BufferAccess for ImmutableBuffer { } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -375,6 +379,23 @@ unsafe impl DeviceOwned for ImmutableBuffer { } } +impl PartialEq for ImmutableBuffer { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for ImmutableBuffer {} + +impl Hash for ImmutableBuffer { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + /// Access to the immutable buffer that can be used for the initial upload. //#[derive(Debug)] // TODO: pub struct ImmutableBufferInitialization> { @@ -394,12 +415,12 @@ unsafe impl BufferAccess for ImmutableBufferInitialization { } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.conflict_key() == other.conflict_key() // TODO: } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { false } @@ -453,6 +474,23 @@ impl Clone for ImmutableBufferInitialization { } } +impl PartialEq for ImmutableBufferInitialization { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for ImmutableBufferInitialization {} + +impl Hash for ImmutableBufferInitialization { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + #[cfg(test)] mod tests { use buffer::BufferUsage; @@ -469,7 +507,7 @@ mod tests { let (buffer, _) = ImmutableBuffer::from_data(12u32, BufferUsage::all(), queue.clone()) .unwrap(); - let destination = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), 0) + let destination = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), false, 0) .unwrap(); let _ = AutoCommandBufferBuilder::new(device.clone(), queue.family()) @@ -498,6 +536,7 @@ mod tests { let destination = CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), + false, (0 .. 512).map(|_| 0u32)) .unwrap(); @@ -549,7 +588,7 @@ mod tests { ImmutableBuffer::::uninitialized(device.clone(), BufferUsage::all()).unwrap() }; - let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), 0).unwrap(); + let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), false, 0).unwrap(); assert_should_panic!({ // TODO: check Result error instead of panicking @@ -575,7 +614,7 @@ mod tests { ImmutableBuffer::::uninitialized(device.clone(), BufferUsage::all()).unwrap() }; - let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), 0).unwrap(); + let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), false, 0).unwrap(); let _ = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .unwrap() @@ -600,7 +639,7 @@ mod tests { ImmutableBuffer::::uninitialized(device.clone(), BufferUsage::all()).unwrap() }; - let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), 0).unwrap(); + let source = CpuAccessibleBuffer::from_data(device.clone(), BufferUsage::all(), false, 0).unwrap(); let cb1 = AutoCommandBufferBuilder::new(device.clone(), queue.family()) .unwrap() diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/mod.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/mod.rs similarity index 100% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/mod.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/mod.rs diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/slice.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/slice.rs similarity index 90% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/slice.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/slice.rs index 4d8983a..4399b55 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/slice.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/slice.rs @@ -7,8 +7,11 @@ // notice may not be copied, modified, or distributed except // according to those terms. +use std::hash::Hash; +use std::hash::Hasher; use std::marker::PhantomData; use std::mem; +use std::mem::MaybeUninit; use std::ops::Range; use std::sync::Arc; @@ -117,8 +120,8 @@ impl BufferSlice { pub unsafe fn slice_custom(self, f: F) -> BufferSlice where F: for<'r> FnOnce(&'r T) -> &'r R // TODO: bounds on R { - let data: &T = mem::zeroed(); - let result = f(data); + let data: MaybeUninit<&T> = MaybeUninit::zeroed(); + let result = f(data.assume_init()); let size = mem::size_of_val(result); let result = result as *const R as *const () as usize; @@ -227,12 +230,12 @@ unsafe impl BufferAccess for BufferSlice } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { self.resource.conflicts_buffer(other) } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { self.resource.conflicts_image(other) } @@ -284,6 +287,29 @@ impl From> for BufferSlice<[T], B> { } } +impl PartialEq for BufferSlice + where B: BufferAccess +{ + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for BufferSlice + where B: BufferAccess +{} + +impl Hash for BufferSlice + where B: BufferAccess +{ + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} + /// Takes a `BufferSlice` that points to a struct, and returns a `BufferSlice` that points to /// a specific field of that struct. #[macro_export] diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/sys.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/sys.rs similarity index 92% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/sys.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/sys.rs index 48a1e25..32e12b3 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/sys.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/sys.rs @@ -27,7 +27,10 @@ use smallvec::SmallVec; use std::error; use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -60,8 +63,8 @@ impl UnsafeBuffer { /// /// # Panic /// - /// Panics if `sparse.sparse` is false and `sparse.sparse_residency` or - /// `sparse.sparse_aliased` is true. + /// - Panics if `sparse.sparse` is false and `sparse.sparse_residency` or `sparse.sparse_aliased` is true. + /// - Panics if `usage` is empty. /// pub unsafe fn new<'a, I>(device: Arc, size: usize, usage: BufferUsage, sharing: Sharing, sparse: SparseLevel) @@ -80,6 +83,10 @@ impl UnsafeBuffer { let usage_bits = usage.to_vulkan_bits(); + // Checking for empty BufferUsage. + assert!(usage_bits != 0, + "Can't create buffer with empty BufferUsage"); + // Checking sparse features. assert!(sparse.sparse || !sparse.sparse_residency, "Can't enable sparse residency without enabling sparse binding as well"); @@ -112,12 +119,12 @@ impl UnsafeBuffer { pQueueFamilyIndices: sh_indices.as_ptr(), }; - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateBuffer(device.internal_object(), &infos, ptr::null(), - &mut output))?; - output + output.as_mut_ptr()))?; + output.assume_init() }; let mem_reqs = { @@ -137,8 +144,8 @@ impl UnsafeBuffer { Some(vk::MemoryDedicatedRequirementsKHR { sType: vk::STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR, pNext: ptr::null(), - prefersDedicatedAllocation: mem::uninitialized(), - requiresDedicatedAllocation: mem::uninitialized(), + prefersDedicatedAllocation: mem::zeroed(), + requiresDedicatedAllocation: mem::zeroed(), }) } else { None @@ -150,7 +157,7 @@ impl UnsafeBuffer { .as_mut() .map(|o| o as *mut vk::MemoryDedicatedRequirementsKHR) .unwrap_or(ptr::null_mut()) as *mut _, - memoryRequirements: mem::uninitialized(), + memoryRequirements: mem::zeroed(), }; vk.GetBufferMemoryRequirements2KHR(device.internal_object(), &infos, &mut output); @@ -165,8 +172,9 @@ impl UnsafeBuffer { out } else { - let mut output: vk::MemoryRequirements = mem::uninitialized(); - vk.GetBufferMemoryRequirements(device.internal_object(), buffer, &mut output); + let mut output: MaybeUninit = MaybeUninit::uninit(); + vk.GetBufferMemoryRequirements(device.internal_object(), buffer, output.as_mut_ptr()); + let output = output.assume_init(); debug_assert!(output.size >= size as u64); debug_assert!(output.memoryTypeBits != 0); MemoryRequirements::from_vulkan_reqs(output) @@ -207,10 +215,12 @@ impl UnsafeBuffer { // We check for correctness in debug mode. debug_assert!({ - let mut mem_reqs = mem::uninitialized(); + let mut mem_reqs = MaybeUninit::uninit(); vk.GetBufferMemoryRequirements(self.device.internal_object(), self.buffer, - &mut mem_reqs); + mem_reqs.as_mut_ptr()); + + let mem_reqs = mem_reqs.assume_init(); mem_reqs.size <= (memory.size() - offset) as u64 && (offset as u64 % mem_reqs.alignment) == 0 && mem_reqs.memoryTypeBits & (1 << memory.memory_type().id()) != 0 @@ -298,7 +308,7 @@ impl UnsafeBuffer { unsafe impl VulkanObject for UnsafeBuffer { type Object = vk::Buffer; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_BUFFER; #[inline] fn internal_object(&self) -> vk::Buffer { @@ -330,6 +340,23 @@ impl Drop for UnsafeBuffer { } } +impl PartialEq for UnsafeBuffer { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.buffer == other.buffer && self.device == other.device + } +} + +impl Eq for UnsafeBuffer {} + +impl Hash for UnsafeBuffer { + #[inline] + fn hash(&self, state: &mut H) { + self.buffer.hash(state); + self.device.hash(state); + } +} + #[derive(Debug, Copy, Clone)] pub struct SparseLevel { pub sparse: bool, @@ -394,7 +421,7 @@ impl error::Error for BufferCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { BufferCreationError::AllocError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/traits.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/traits.rs similarity index 90% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/traits.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/traits.rs index d037768..d62e49b 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/traits.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/traits.rs @@ -8,6 +8,8 @@ // according to those terms. use std::ops::Range; +use std::hash::Hash; +use std::hash::Hasher; use buffer::BufferSlice; use buffer::sys::UnsafeBuffer; @@ -85,7 +87,7 @@ pub unsafe trait BufferAccess: DeviceOwned { /// /// Note that the function must be transitive. In other words if `conflicts(a, b)` is true and /// `conflicts(b, c)` is true, then `conflicts(a, c)` must be true as well. - fn conflicts_buffer(&self, other: &BufferAccess) -> bool; + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool; /// Returns true if an access to `self` potentially overlaps the same memory as an access to /// `other`. @@ -96,7 +98,7 @@ pub unsafe trait BufferAccess: DeviceOwned { /// /// Note that the function must be transitive. In other words if `conflicts(a, b)` is true and /// `conflicts(b, c)` is true, then `conflicts(a, c)` must be true as well. - fn conflicts_image(&self, other: &ImageAccess) -> bool; + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool; /// Returns a key that uniquely identifies the buffer. Two buffers or images that potentially /// overlap in memory must return the same key. @@ -139,7 +141,7 @@ pub unsafe trait BufferAccess: DeviceOwned { } /// Inner information about a buffer. -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct BufferInner<'a> { /// The underlying buffer object. pub buffer: &'a UnsafeBuffer, @@ -163,12 +165,12 @@ unsafe impl BufferAccess for T } #[inline] - fn conflicts_buffer(&self, other: &BufferAccess) -> bool { + fn conflicts_buffer(&self, other: &dyn BufferAccess) -> bool { (**self).conflicts_buffer(other) } #[inline] - fn conflicts_image(&self, other: &ImageAccess) -> bool { + fn conflicts_image(&self, other: &dyn ImageAccess) -> bool { (**self).conflicts_image(other) } @@ -213,3 +215,20 @@ unsafe impl TypedBufferAccess for T { type Content = ::Content; } + +impl PartialEq for dyn BufferAccess + Send + Sync { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.inner() == other.inner() && self.size() == other.size() + } +} + +impl Eq for dyn BufferAccess + Send + Sync {} + +impl Hash for dyn BufferAccess + Send + Sync { + #[inline] + fn hash(&self, state: &mut H) { + self.inner().hash(state); + self.size().hash(state); + } +} diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/usage.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/usage.rs similarity index 99% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/usage.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/usage.rs index 1db4a80..bc1b7b0 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/usage.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/usage.rs @@ -16,7 +16,7 @@ use vk; /// /// Some methods are provided to build `BufferUsage` structs for some common situations. However /// there is no restriction in the combination of BufferUsages that can be enabled. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct BufferUsage { pub transfer_source: bool, pub transfer_destination: bool, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/view.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/view.rs similarity index 96% rename from third_party/cargo/vendor/vulkano-0.11.1/src/buffer/view.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/buffer/view.rs index ff7695a..40baa00 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/buffer/view.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/buffer/view.rs @@ -39,7 +39,7 @@ use std::error; use std::fmt; use std::marker::PhantomData; -use std::mem; +use std::mem::MaybeUninit; use std::ptr; use std::sync::Arc; @@ -123,11 +123,11 @@ impl BufferView let format_props = { let vk_i = device.instance().pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); vk_i.GetPhysicalDeviceFormatProperties(device.physical_device().internal_object(), format as u32, - &mut output); - output.bufferFeatures + output.as_mut_ptr()); + output.assume_init().bufferFeatures }; if buffer.usage_uniform_texel_buffer() { @@ -153,12 +153,12 @@ impl BufferView }; let vk = device.pointers(); - let mut output = mem::uninitialized(); + let mut output = MaybeUninit::uninit(); check_errors(vk.CreateBufferView(device.internal_object(), &infos, ptr::null(), - &mut output))?; - (output, format_props) + output.as_mut_ptr()))?; + (output.assume_init(), format_props) }; Ok(BufferView { @@ -201,7 +201,7 @@ unsafe impl VulkanObject for BufferView { type Object = vk::BufferView; - const TYPE: vk::DebugReportObjectTypeEXT = vk::DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT; + const TYPE: vk::ObjectType = vk::OBJECT_TYPE_BUFFER_VIEW; #[inline] fn internal_object(&self) -> vk::BufferView { @@ -316,7 +316,7 @@ impl error::Error for BufferViewCreationError { } #[inline] - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match *self { BufferViewCreationError::OomError(ref err) => Some(err), _ => None, diff --git a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/auto.rs b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/auto.rs similarity index 97% rename from third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/auto.rs rename to third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/auto.rs index 9b48f6e..c8dc569 100644 --- a/third_party/cargo/vendor/vulkano-0.11.1/src/command_buffer/auto.rs +++ b/third_party/cargo/vendor/vulkano-0.18.0/src/command_buffer/auto.rs @@ -91,7 +91,7 @@ pub struct AutoCommandBufferBuilder